(* Title:      Relation Algebra
   Author:     Alasdair Armstrong, Simon Foster, Georg Struth, Tjark Weber
   Maintainer: Georg Struth <g.struth at sheffield.ac.uk>
               Tjark Weber <tjark.weber at it.uu.se>
*)

header {* Vectors *}

theory Relation_Algebra_Vectors
  imports Relation_Algebra
begin

text {* Vectors can be used for modelling sets of states. In this section we
follow Maddux's book to derive some of their most important properties. *}

context relation_algebra
begin

definition is_vector :: "'a \<Rightarrow> bool"
  where "is_vector x \<equiv> x = x ; 1"

lemma vector_compl: "is_vector x \<Longrightarrow> is_vector (-x)"
by (metis one_compl is_vector_def)

lemma vector_add: "\<lbrakk>is_vector x; is_vector y\<rbrakk> \<Longrightarrow> is_vector (x + y)"
by (metis comp_distr is_vector_def)

lemma vector_mult: "\<lbrakk>is_vector x; is_vector y\<rbrakk> \<Longrightarrow> is_vector (x \<cdot> y)"
by (metis ra_1 is_vector_def)

lemma vector_comp: "\<lbrakk>is_vector x; is_vector y\<rbrakk> \<Longrightarrow> is_vector (x ; y)"
by (metis comp_assoc is_vector_def)

lemma vector_1: "is_vector x \<Longrightarrow> (x \<cdot> y) ; z = x \<cdot> y ; z"
by (metis inf.commute ra_1 is_vector_def)

lemma vector_1_comm: "is_vector y \<Longrightarrow> (x \<cdot> y) ; z = x ; z \<cdot> y"
by (metis ra_1 is_vector_def)

lemma vector_2_var: "is_vector y \<Longrightarrow> (x \<cdot> y\<^sup>\<smile>) ; z = (x \<cdot> y\<^sup>\<smile>) ; (y \<cdot> z)"
by (metis inf.left_idem vector_2)

lemma vector_idem [simp]: "is_vector x \<Longrightarrow> x ; x = x"
by (metis inf_absorb2 inf_top_left maddux_21 vector_1_comm)

lemma vector_rectangle [simp]: "is_vector x \<Longrightarrow> x ; 1 ; x = x"
by (metis vector_idem is_vector_def)

lemma vector_3 [simp]: "is_vector x \<Longrightarrow> (x \<cdot> 1') ; y = x \<cdot> y"
by (metis inf.commute mult.left_neutral vector_1)

end (* relation_algebra *)

end


(*  Title:      HOL/ZF/HOLZF.thy
    Author:     Steven Obua

Axiomatizes the ZFC universe as an HOL type.  See "Partizan Games in
Isabelle/HOLZF", available from http://www4.in.tum.de/~obua/partizan
*)

theory HOLZF
imports MainRLT
begin

typedecl ZF

axiomatization
  Empty :: ZF and
  Elem :: "ZF \<Rightarrow> ZF \<Rightarrow> bool" and
  Sum :: "ZF \<Rightarrow> ZF" and
  Power :: "ZF \<Rightarrow> ZF" and
  Repl :: "ZF \<Rightarrow> (ZF \<Rightarrow> ZF) \<Rightarrow> ZF" and
  Inf :: ZF

definition Upair :: "ZF \<Rightarrow> ZF \<Rightarrow> ZF" where
  "Upair a b == Repl (Power (Power Empty)) (% x. if x = Empty then a else b)"

definition Singleton:: "ZF \<Rightarrow> ZF" where
  "Singleton x == Upair x x"

definition union :: "ZF \<Rightarrow> ZF \<Rightarrow> ZF" where
  "union A B == Sum (Upair A B)"

definition SucNat:: "ZF \<Rightarrow> ZF" where
  "SucNat x == union x (Singleton x)"

definition subset :: "ZF \<Rightarrow> ZF \<Rightarrow> bool" where
  "subset A B \<equiv> \<forall>x. Elem x A \<longrightarrow> Elem x B"

axiomatization where
  Empty: "Not (Elem x Empty)" and
  Ext: "(x = y) = (\<forall>z. Elem z x = Elem z y)" and
  Sum: "Elem z (Sum x) = (\<exists>y. Elem z y \<and> Elem y x)" and
  Power: "Elem y (Power x) = (subset y x)" and
  Repl: "Elem b (Repl A f) = (\<exists>a. Elem a A \<and> b = f a)" and
  Regularity: "A \<noteq> Empty \<longrightarrow> (\<exists>x. Elem x A \<and> (\<forall>y. Elem y x \<longrightarrow> Not (Elem y A)))" and
  Infinity: "Elem Empty Inf \<and> (\<forall>x. Elem x Inf \<longrightarrow> Elem (SucNat x) Inf)"

definition Sep :: "ZF \<Rightarrow> (ZF \<Rightarrow> bool) \<Rightarrow> ZF" where
  "Sep A p == (if (\<forall>x. Elem x A \<longrightarrow> Not (p x)) then Empty else
  (let z = (\<some> x. Elem x A & p x) in
   let f = \<lambda>x. (if p x then x else z) in Repl A f))"

thm Power[unfolded subset_def]

theorem Sep: "Elem b (Sep A p) = (Elem b A \<and> p b)"
  apply (auto simp add: Sep_def Empty)
  apply (auto simp add: Let_def Repl)
  apply (rule someI2, auto)+
  done

lemma subset_empty: "subset Empty A"
  by (simp add: subset_def Empty)

theorem Upair: "Elem x (Upair a b) = (x = a \<or> x = b)"
  apply (auto simp add: Upair_def Repl)
  apply (rule exI[where x=Empty])
  apply (simp add: Power subset_empty)
  apply (rule exI[where x="Power Empty"])
  apply (auto)
  apply (auto simp add: Ext Power subset_def Empty)
  apply (drule spec[where x=Empty], simp add: Empty)+
  done

lemma Singleton: "Elem x (Singleton y) = (x = y)"
  by (simp add: Singleton_def Upair)

definition Opair :: "ZF \<Rightarrow> ZF \<Rightarrow> ZF" where
  "Opair a b == Upair (Upair a a) (Upair a b)"

lemma Upair_singleton: "(Upair a a = Upair c d) = (a = c & a = d)"
  by (auto simp add: Ext[where x="Upair a a"] Upair)

lemma Upair_fsteq: "(Upair a b = Upair a c) = ((a = b & a = c) | (b = c))"
  by (auto simp add: Ext[where x="Upair a b"] Upair)

lemma Upair_comm: "Upair a b = Upair b a"
  by (auto simp add: Ext Upair)

theorem Opair: "(Opair a b = Opair c d) = (a = c & b = d)"
  proof -
    have fst: "(Opair a b = Opair c d) \<Longrightarrow> a = c"
      apply (simp add: Opair_def)
      apply (simp add: Ext[where x="Upair (Upair a a) (Upair a b)"])
      apply (drule spec[where x="Upair a a"])
      apply (auto simp add: Upair Upair_singleton)
      done
    show ?thesis
      apply (auto)
      apply (erule fst)
      apply (frule fst)
      apply (auto simp add: Opair_def Upair_fsteq)
      done
  qed

definition Replacement :: "ZF \<Rightarrow> (ZF \<Rightarrow> ZF option) \<Rightarrow> ZF" where
  "Replacement A f == Repl (Sep A (% a. f a \<noteq> None)) (the o f)"

theorem Replacement: "Elem y (Replacement A f) = (\<exists>x. Elem x A \<and> f x = Some y)"
  by (auto simp add: Replacement_def Repl Sep)

definition Fst :: "ZF \<Rightarrow> ZF" where
  "Fst q == SOME x. \<exists>y. q = Opair x y"

definition Snd :: "ZF \<Rightarrow> ZF" where
  "Snd q == SOME y. \<exists>x. q = Opair x y"

theorem Fst: "Fst (Opair x y) = x"
  apply (simp add: Fst_def)
  apply (rule someI2)
  apply (simp_all add: Opair)
  done

theorem Snd: "Snd (Opair x y) = y"
  apply (simp add: Snd_def)
  apply (rule someI2)
  apply (simp_all add: Opair)
  done

definition isOpair :: "ZF \<Rightarrow> bool" where
  "isOpair q == \<exists>x y. q = Opair x y"

lemma isOpair: "isOpair (Opair x y) = True"
  by (auto simp add: isOpair_def)

lemma FstSnd: "isOpair x \<Longrightarrow> Opair (Fst x) (Snd x) = x"
  by (auto simp add: isOpair_def Fst Snd)

definition CartProd :: "ZF \<Rightarrow> ZF \<Rightarrow> ZF" where
  "CartProd A B == Sum(Repl A (% a. Repl B (% b. Opair a b)))"

lemma CartProd: "Elem x (CartProd A B) = (\<exists>a b. Elem a A \<and> Elem b B \<and> x = (Opair a b))"
  apply (auto simp add: CartProd_def Sum Repl)
  apply (rule_tac x="Repl B (Opair a)" in exI)
  apply (auto simp add: Repl)
  done

definition explode :: "ZF \<Rightarrow> ZF set" where
  "explode z == { x. Elem x z }"

lemma explode_Empty: "(explode x = {}) = (x = Empty)"
  by (auto simp add: explode_def Ext Empty)

lemma explode_Elem: "(x \<in> explode X) = (Elem x X)"
  by (simp add: explode_def)

lemma Elem_explode_in: "\<lbrakk> Elem a A; explode A \<subseteq> B\<rbrakk> \<Longrightarrow> a \<in> B"
  by (auto simp add: explode_def)

lemma explode_CartProd_eq: "explode (CartProd a b) = (% (x,y). Opair x y) ` ((explode a) \<times> (explode b))"
  by (simp add: explode_def set_eq_iff CartProd image_def)

lemma explode_Repl_eq: "explode (Repl A f) = image f (explode A)"
  by (simp add: explode_def Repl image_def)

definition Domain :: "ZF \<Rightarrow> ZF" where
  "Domain f == Replacement f (% p. if isOpair p then Some (Fst p) else None)"

definition Range :: "ZF \<Rightarrow> ZF" where
  "Range f == Replacement f (% p. if isOpair p then Some (Snd p) else None)"

theorem Domain: "Elem x (Domain f) = (\<exists>y. Elem (Opair x y) f)"
  apply (auto simp add: Domain_def Replacement)
  apply (rule_tac x="Snd xa" in exI)
  apply (simp add: FstSnd)
  apply (rule_tac x="Opair x y" in exI)
  apply (simp add: isOpair Fst)
  done

theorem Range: "Elem y (Range f) = (\<exists>x. Elem (Opair x y) f)"
  apply (auto simp add: Range_def Replacement)
  apply (rule_tac x="Fst x" in exI)
  apply (simp add: FstSnd)
  apply (rule_tac x="Opair x y" in exI)
  apply (simp add: isOpair Snd)
  done

theorem union: "Elem x (union A B) = (Elem x A | Elem x B)"
  by (auto simp add: union_def Sum Upair)

definition Field :: "ZF \<Rightarrow> ZF" where
  "Field A == union (Domain A) (Range A)"

definition app :: "ZF \<Rightarrow> ZF => ZF" (infixl "\<acute>" 90) \<comment> \<open>function application\<close> where
  "f \<acute> x == (THE y. Elem (Opair x y) f)"

definition isFun :: "ZF \<Rightarrow> bool" where
  "isFun f == (\<forall>x y1 y2. Elem (Opair x y1) f & Elem (Opair x y2) f \<longrightarrow> y1 = y2)"

definition Lambda :: "ZF \<Rightarrow> (ZF \<Rightarrow> ZF) \<Rightarrow> ZF" where
  "Lambda A f == Repl A (% x. Opair x (f x))"

lemma Lambda_app: "Elem x A \<Longrightarrow> (Lambda A f)\<acute>x = f x"
  by (simp add: app_def Lambda_def Repl Opair)

lemma isFun_Lambda: "isFun (Lambda A f)"
  by (auto simp add: isFun_def Lambda_def Repl Opair)

lemma domain_Lambda: "Domain (Lambda A f) = A"
  apply (auto simp add: Domain_def)
  apply (subst Ext)
  apply (auto simp add: Replacement)
  apply (simp add: Lambda_def Repl)
  apply (auto simp add: Fst)
  apply (simp add: Lambda_def Repl)
  apply (rule_tac x="Opair z (f z)" in exI)
  apply (auto simp add: Fst isOpair_def)
  done

lemma Lambda_ext: "(Lambda s f = Lambda t g) = (s = t \<and> (\<forall>x. Elem x s \<longrightarrow> f x = g x))"
proof -
  have "Lambda s f = Lambda t g \<Longrightarrow> s = t"
    apply (subst domain_Lambda[where A = s and f = f, symmetric])
    apply (subst domain_Lambda[where A = t and f = g, symmetric])
    apply auto
    done
  then show ?thesis
    apply auto
    apply (subst Lambda_app[where f=f, symmetric], simp)
    apply (subst Lambda_app[where f=g, symmetric], simp)
    apply auto
    apply (auto simp add: Lambda_def Repl Ext)
    apply (auto simp add: Ext[symmetric])
    done
qed

definition PFun :: "ZF \<Rightarrow> ZF \<Rightarrow> ZF" where
  "PFun A B == Sep (Power (CartProd A B)) isFun"

definition Fun :: "ZF \<Rightarrow> ZF \<Rightarrow> ZF" where
  "Fun A B == Sep (PFun A B) (\<lambda> f. Domain f = A)"

lemma Fun_Range: "Elem f (Fun U V) \<Longrightarrow> subset (Range f) V"
  apply (simp add: Fun_def Sep PFun_def Power subset_def CartProd)
  apply (auto simp add: Domain Range)
  apply (erule_tac x="Opair xa x" in allE)
  apply (auto simp add: Opair)
  done

lemma Elem_Elem_PFun: "Elem F (PFun U V) \<Longrightarrow> Elem p F \<Longrightarrow> isOpair p & Elem (Fst p) U & Elem (Snd p) V"
  apply (simp add: PFun_def Sep Power subset_def, clarify)
  apply (erule_tac x=p in allE)
  apply (auto simp add: CartProd isOpair Fst Snd)
  done

lemma Fun_implies_PFun[simp]: "Elem f (Fun U V) \<Longrightarrow> Elem f (PFun U V)"
  by (simp add: Fun_def Sep)

lemma Elem_Elem_Fun: "Elem F (Fun U V) \<Longrightarrow> Elem p F \<Longrightarrow> isOpair p & Elem (Fst p) U & Elem (Snd p) V"
  by (auto simp add: Elem_Elem_PFun dest: Fun_implies_PFun)

lemma PFun_inj: "Elem F (PFun U V) \<Longrightarrow> Elem x F \<Longrightarrow> Elem y F \<Longrightarrow> Fst x = Fst y \<Longrightarrow> Snd x = Snd y"
  apply (frule Elem_Elem_PFun[where p=x], simp)
  apply (frule Elem_Elem_PFun[where p=y], simp)
  apply (subgoal_tac "isFun F")
  apply (simp add: isFun_def isOpair_def)
  apply (auto simp add: Fst Snd)
  apply (auto simp add: PFun_def Sep)
  done

lemma Fun_total: "\<lbrakk>Elem F (Fun U V); Elem a U\<rbrakk> \<Longrightarrow> \<exists>x. Elem (Opair a x) F"
  using [[simp_depth_limit = 2]]
  by (auto simp add: Fun_def Sep Domain)

lemma unique_fun_value: "\<lbrakk>isFun f; Elem x (Domain f)\<rbrakk> \<Longrightarrow> \<exists>!y. Elem (Opair x y) f"
  by (auto simp add: Domain isFun_def)

lemma fun_value_in_range: "\<lbrakk>isFun f; Elem x (Domain f)\<rbrakk> \<Longrightarrow> Elem (f\<acute>x) (Range f)"
  apply (auto simp add: Range)
  apply (drule unique_fun_value)
  apply simp
  apply (simp add: app_def)
  apply (rule exI[where x=x])
  apply (auto simp add: the_equality)
  done

lemma fun_range_witness: "\<lbrakk>isFun f; Elem y (Range f)\<rbrakk> \<Longrightarrow> \<exists>x. Elem x (Domain f) & f\<acute>x = y"
  apply (auto simp add: Range)
  apply (rule_tac x="x" in exI)
  apply (auto simp add: app_def the_equality isFun_def Domain)
  done

lemma Elem_Fun_Lambda: "Elem F (Fun U V) \<Longrightarrow> \<exists>f. F = Lambda U f"
  apply (rule exI[where x= "% x. (THE y. Elem (Opair x y) F)"])
  apply (simp add: Ext Lambda_def Repl Domain)
  apply (simp add: Ext[symmetric])
  apply auto
  apply (frule Elem_Elem_Fun)
  apply auto
  apply (rule_tac x="Fst z" in exI)
  apply (simp add: isOpair_def)
  apply (auto simp add: Fst Snd Opair)
  apply (rule the1I2)
  apply auto
  apply (drule Fun_implies_PFun)
  apply (drule_tac x="Opair x ya" and y="Opair x yb" in PFun_inj)
  apply (auto simp add: Fst Snd)
  apply (drule Fun_implies_PFun)
  apply (drule_tac x="Opair x y" and y="Opair x ya" in PFun_inj)
  apply (auto simp add: Fst Snd)
  apply (rule the1I2)
  apply (auto simp add: Fun_total)
  apply (drule Fun_implies_PFun)
  apply (drule_tac x="Opair a x" and y="Opair a y" in PFun_inj)
  apply (auto simp add: Fst Snd)
  done

lemma Elem_Lambda_Fun: "Elem (Lambda A f) (Fun U V) = (A = U \<and> (\<forall>x. Elem x A \<longrightarrow> Elem (f x) V))"
proof -
  have "Elem (Lambda A f) (Fun U V) \<Longrightarrow> A = U"
    by (simp add: Fun_def Sep domain_Lambda)
  then show ?thesis
    apply auto
    apply (drule Fun_Range)
    apply (subgoal_tac "f x = ((Lambda U f) \<acute> x)")
    prefer 2
    apply (simp add: Lambda_app)
    apply simp
    apply (subgoal_tac "Elem (Lambda U f \<acute> x) (Range (Lambda U f))")
    apply (simp add: subset_def)
    apply (rule fun_value_in_range)
    apply (simp_all add: isFun_Lambda domain_Lambda)
    apply (simp add: Fun_def Sep PFun_def Power domain_Lambda isFun_Lambda)
    apply (auto simp add: subset_def CartProd)
    apply (rule_tac x="Fst x" in exI)
    apply (auto simp add: Lambda_def Repl Fst)
    done
qed

definition is_Elem_of :: "(ZF * ZF) set" where
  "is_Elem_of == { (a,b) | a b. Elem a b }"

lemma cond_wf_Elem:
  assumes hyps:"\<forall>x. (\<forall>y. Elem y x \<longrightarrow> Elem y U \<longrightarrow> P y) \<longrightarrow> Elem x U \<longrightarrow> P x" "Elem a U"
  shows "P a"
proof -
  {
    fix P
    fix U
    fix a
    assume P_induct: "(\<forall>x. (\<forall>y. Elem y x \<longrightarrow> Elem y U \<longrightarrow> P y) \<longrightarrow> (Elem x U \<longrightarrow> P x))"
    assume a_in_U: "Elem a U"
    have "P a"
      proof -
        term "P"
        term Sep
        let ?Z = "Sep U (Not o P)"
        have "?Z = Empty \<longrightarrow> P a" by (simp add: Ext Sep Empty a_in_U)
        moreover have "?Z \<noteq> Empty \<longrightarrow> False"
          proof
            assume not_empty: "?Z \<noteq> Empty"
            note thereis_x = Regularity[where A="?Z", simplified not_empty, simplified]
            then obtain x where x_def: "Elem x ?Z \<and> (\<forall>y. Elem y x \<longrightarrow> Not (Elem y ?Z))" ..
            then have x_induct:"\<forall>y. Elem y x \<longrightarrow> Elem y U \<longrightarrow> P y" by (simp add: Sep)
            have "Elem x U \<longrightarrow> P x"
              by (rule impE[OF spec[OF P_induct, where x=x], OF x_induct], assumption)
            moreover have "Elem x U & Not(P x)"
              apply (insert x_def)
              apply (simp add: Sep)
              done
            ultimately show "False" by auto
          qed
        ultimately show "P a" by auto
      qed
  }
  with hyps show ?thesis by blast
qed

lemma cond2_wf_Elem:
  assumes
     special_P: "\<exists>U. \<forall>x. Not(Elem x U) \<longrightarrow> (P x)"
     and P_induct: "\<forall>x. (\<forall>y. Elem y x \<longrightarrow> P y) \<longrightarrow> P x"
  shows
     "P a"
proof -
  have "\<exists>U Q. P = (\<lambda> x. (Elem x U \<longrightarrow> Q x))"
  proof -
    from special_P obtain U where U: "\<forall>x. Not(Elem x U) \<longrightarrow> (P x)" ..
    show ?thesis
      apply (rule_tac exI[where x=U])
      apply (rule exI[where x="P"])
      apply (rule ext)
      apply (auto simp add: U)
      done
  qed
  then obtain U where "\<exists>Q. P = (\<lambda> x. (Elem x U \<longrightarrow> Q x))" ..
  then obtain Q where UQ: "P = (\<lambda> x. (Elem x U \<longrightarrow> Q x))" ..
  show ?thesis
    apply (auto simp add: UQ)
    apply (rule cond_wf_Elem)
    apply (rule P_induct[simplified UQ])
    apply simp
    done
qed

primrec nat2Nat :: "nat \<Rightarrow> ZF" where
  nat2Nat_0[intro]:  "nat2Nat 0 = Empty"
| nat2Nat_Suc[intro]:  "nat2Nat (Suc n) = SucNat (nat2Nat n)"

definition Nat2nat :: "ZF \<Rightarrow> nat" where
  "Nat2nat == inv nat2Nat"

lemma Elem_nat2Nat_inf[intro]: "Elem (nat2Nat n) Inf"
  apply (induct n)
  apply (simp_all add: Infinity)
  done

definition Nat :: ZF
 where  "Nat == Sep Inf (\<lambda>N. \<exists>n. nat2Nat n = N)"

lemma Elem_nat2Nat_Nat[intro]: "Elem (nat2Nat n) Nat"
  by (auto simp add: Nat_def Sep)

lemma Elem_Empty_Nat: "Elem Empty Nat"
  by (auto simp add: Nat_def Sep Infinity)

lemma Elem_SucNat_Nat: "Elem N Nat \<Longrightarrow> Elem (SucNat N) Nat"
  by (auto simp add: Nat_def Sep Infinity)

lemma no_infinite_Elem_down_chain:
  "Not (\<exists>f. isFun f \<and> Domain f = Nat \<and> (\<forall>N. Elem N Nat \<longrightarrow> Elem (f\<acute>(SucNat N)) (f\<acute>N)))"
proof -
  {
    fix f
    assume f: "isFun f \<and> Domain f = Nat \<and> (\<forall>N. Elem N Nat \<longrightarrow> Elem (f\<acute>(SucNat N)) (f\<acute>N))"
    let ?r = "Range f"
    have "?r \<noteq> Empty"
      apply (auto simp add: Ext Empty)
      apply (rule exI[where x="f\<acute>Empty"])
      apply (rule fun_value_in_range)
      apply (auto simp add: f Elem_Empty_Nat)
      done
    then have "\<exists>x. Elem x ?r \<and> (\<forall>y. Elem y x \<longrightarrow> Not(Elem y ?r))"
      by (simp add: Regularity)
    then obtain x where x: "Elem x ?r \<and> (\<forall>y. Elem y x \<longrightarrow> Not(Elem y ?r))" ..
    then have "\<exists>N. Elem N (Domain f) & f\<acute>N = x"
      apply (rule_tac fun_range_witness)
      apply (simp_all add: f)
      done
    then have "\<exists>N. Elem N Nat & f\<acute>N = x"
      by (simp add: f)
    then obtain N where N: "Elem N Nat & f\<acute>N = x" ..
    from N have N': "Elem N Nat" by auto
    let ?y = "f\<acute>(SucNat N)"
    have Elem_y_r: "Elem ?y ?r"
      by (simp_all add: f Elem_SucNat_Nat N fun_value_in_range)
    have "Elem ?y (f\<acute>N)" by (auto simp add: f N')
    then have "Elem ?y x" by (simp add: N)
    with x have "Not (Elem ?y ?r)" by auto
    with Elem_y_r have "False" by auto
  }
  then show ?thesis by auto
qed

lemma Upair_nonEmpty: "Upair a b \<noteq> Empty"
  by (auto simp add: Ext Empty Upair)

lemma Singleton_nonEmpty: "Singleton x \<noteq> Empty"
  by (auto simp add: Singleton_def Upair_nonEmpty)

lemma notsym_Elem: "Not(Elem a b & Elem b a)"
proof -
  {
    fix a b
    assume ab: "Elem a b"
    assume ba: "Elem b a"
    let ?Z = "Upair a b"
    have "?Z \<noteq> Empty" by (simp add: Upair_nonEmpty)
    then have "\<exists>x. Elem x ?Z \<and> (\<forall>y. Elem y x \<longrightarrow> Not(Elem y ?Z))"
      by (simp add: Regularity)
    then obtain x where x:"Elem x ?Z \<and> (\<forall>y. Elem y x \<longrightarrow> Not(Elem y ?Z))" ..
    then have "x = a \<or> x = b" by (simp add: Upair)
    moreover have "x = a \<longrightarrow> Not (Elem b ?Z)"
      by (auto simp add: x ba)
    moreover have "x = b \<longrightarrow> Not (Elem a ?Z)"
      by (auto simp add: x ab)
    ultimately have "False"
      by (auto simp add: Upair)
  }
  then show ?thesis by auto
qed

lemma irreflexiv_Elem: "Not(Elem a a)"
  by (simp add: notsym_Elem[of a a, simplified])

lemma antisym_Elem: "Elem a b \<Longrightarrow> Not (Elem b a)"
  apply (insert notsym_Elem[of a b])
  apply auto
  done

primrec NatInterval :: "nat \<Rightarrow> nat \<Rightarrow> ZF" where
  "NatInterval n 0 = Singleton (nat2Nat n)"
| "NatInterval n (Suc m) = union (NatInterval n m) (Singleton (nat2Nat (n+m+1)))"

lemma n_Elem_NatInterval[rule_format]: "\<forall>q. q \<le> m \<longrightarrow> Elem (nat2Nat (n+q)) (NatInterval n m)"
  apply (induct m)
  apply (auto simp add: Singleton union)
  apply (case_tac "q <= m")
  apply auto
  apply (subgoal_tac "q = Suc m")
  apply auto
  done

lemma NatInterval_not_Empty: "NatInterval n m \<noteq> Empty"
  by (auto intro:   n_Elem_NatInterval[where q = 0, simplified] simp add: Empty Ext)

lemma increasing_nat2Nat[rule_format]: "0 < n \<longrightarrow> Elem (nat2Nat (n - 1)) (nat2Nat n)"
  apply (case_tac "\<exists>m. n = Suc m")
  apply (auto simp add: SucNat_def union Singleton)
  apply (drule spec[where x="n - 1"])
  apply arith
  done

lemma represent_NatInterval[rule_format]: "Elem x (NatInterval n m) \<longrightarrow> (\<exists>u. n \<le> u \<and> u \<le> n+m \<and> nat2Nat u = x)"
  apply (induct m)
  apply (auto simp add: Singleton union)
  apply (rule_tac x="Suc (n+m)" in exI)
  apply auto
  done

lemma inj_nat2Nat: "inj nat2Nat"
proof -
  {
    fix n m :: nat
    assume nm: "nat2Nat n = nat2Nat (n+m)"
    assume mg0: "0 < m"
    let ?Z = "NatInterval n m"
    have "?Z \<noteq> Empty" by (simp add: NatInterval_not_Empty)
    then have "\<exists>x. (Elem x ?Z) \<and> (\<forall>y. Elem y x \<longrightarrow> Not (Elem y ?Z))"
      by (auto simp add: Regularity)
    then obtain x where x:"Elem x ?Z \<and> (\<forall>y. Elem y x \<longrightarrow> Not (Elem y ?Z))" ..
    then have "\<exists>u. n \<le> u & u \<le> n+m & nat2Nat u = x"
      by (simp add: represent_NatInterval)
    then obtain u where u: "n \<le> u & u \<le> n+m \<and> nat2Nat u = x" ..
    have "n < u \<longrightarrow> False"
    proof
      assume n_less_u: "n < u"
      let ?y = "nat2Nat (u - 1)"
      have "Elem ?y (nat2Nat u)"
        apply (rule increasing_nat2Nat)
        apply (insert n_less_u)
        apply arith
        done
      with u have "Elem ?y x" by auto
      with x have "Not (Elem ?y ?Z)" by auto
      moreover have "Elem ?y ?Z"
        apply (insert n_Elem_NatInterval[where q = "u - n - 1" and n=n and m=m])
        apply (insert n_less_u)
        apply (insert u)
        apply auto
        done
      ultimately show False by auto
    qed
    moreover have "u = n \<longrightarrow> False"
    proof
      assume "u = n"
      with u have "nat2Nat n = x" by auto
      then have nm_eq_x: "nat2Nat (n+m) = x" by (simp add: nm)
      let ?y = "nat2Nat (n+m - 1)"
      have "Elem ?y (nat2Nat (n+m))"
        apply (rule increasing_nat2Nat)
        apply (insert mg0)
        apply arith
        done
      with nm_eq_x have "Elem ?y x" by auto
      with x have "Not (Elem ?y ?Z)" by auto
      moreover have "Elem ?y ?Z"
        apply (insert n_Elem_NatInterval[where q = "m - 1" and n=n and m=m])
        apply (insert mg0)
        apply auto
        done
      ultimately show False by auto
    qed
    ultimately have "False" using u by arith
  }
  note lemma_nat2Nat = this
  have th:"\<And>x y. \<not> (x < y \<and> (\<forall>(m::nat). y \<noteq> x + m))" by presburger
  have th': "\<And>x y. \<not> (x \<noteq> y \<and> (\<not> x < y) \<and> (\<forall>(m::nat). x \<noteq> y + m))" by presburger
  show ?thesis
    apply (auto simp add: inj_on_def)
    apply (case_tac "x = y")
    apply auto
    apply (case_tac "x < y")
    apply (case_tac "\<exists>m. y = x + m & 0 < m")
    apply (auto intro: lemma_nat2Nat)
    apply (case_tac "y < x")
    apply (case_tac "\<exists>m. x = y + m & 0 < m")
    apply simp
    apply simp
    using th apply blast
    apply (case_tac "\<exists>m. x = y + m")
    apply (auto intro: lemma_nat2Nat)
    apply (drule sym)
    using lemma_nat2Nat apply blast
    using th' apply blast
    done
qed

lemma Nat2nat_nat2Nat[simp]: "Nat2nat (nat2Nat n) = n"
  by (simp add: Nat2nat_def inv_f_f[OF inj_nat2Nat])

lemma nat2Nat_Nat2nat[simp]: "Elem n Nat \<Longrightarrow> nat2Nat (Nat2nat n) = n"
  apply (simp add: Nat2nat_def)
  apply (rule_tac f_inv_into_f)
  apply (auto simp add: image_def Nat_def Sep)
  done

lemma Nat2nat_SucNat: "Elem N Nat \<Longrightarrow> Nat2nat (SucNat N) = Suc (Nat2nat N)"
  apply (auto simp add: Nat_def Sep Nat2nat_def)
  apply (auto simp add: inv_f_f[OF inj_nat2Nat])
  apply (simp only: nat2Nat.simps[symmetric])
  apply (simp only: inv_f_f[OF inj_nat2Nat])
  done

(*lemma Elem_induct: "(\<And>x. \<forall>y. Elem y x \<longrightarrow> P y \<Longrightarrow> P x) \<Longrightarrow> P a"
  by (erule wf_induct[OF wf_is_Elem_of, simplified is_Elem_of_def, simplified])*)

lemma Elem_Opair_exists: "\<exists>z. Elem x z & Elem y z & Elem z (Opair x y)"
  apply (rule exI[where x="Upair x y"])
  by (simp add: Upair Opair_def)

lemma UNIV_is_not_in_ZF: "UNIV \<noteq> explode R"
proof
  let ?Russell = "{ x. Not(Elem x x) }"
  have "?Russell = UNIV" by (simp add: irreflexiv_Elem)
  moreover assume "UNIV = explode R"
  ultimately have russell: "?Russell = explode R" by simp
  then show "False"
  proof(cases "Elem R R")
    case True
    then show ?thesis
      by (insert irreflexiv_Elem, auto)
  next
    case False
    then have "R \<in> ?Russell" by auto
    then have "Elem R R" by (simp add: russell explode_def)
    with False show ?thesis by auto
  qed
qed

definition SpecialR :: "(ZF * ZF) set" where
  "SpecialR \<equiv> { (x, y) . x \<noteq> Empty \<and> y = Empty}"

lemma "wf SpecialR"
  apply (subst wf_def)
  apply (auto simp add: SpecialR_def)
  done

definition Ext :: "('a * 'b) set \<Rightarrow> 'b \<Rightarrow> 'a set" where
  "Ext R y \<equiv> { x . (x, y) \<in> R }"

lemma Ext_Elem: "Ext is_Elem_of = explode"
  by (auto simp add: Ext_def is_Elem_of_def explode_def)

lemma "Ext SpecialR Empty \<noteq> explode z"
proof
  have "Ext SpecialR Empty = UNIV - {Empty}"
    by (auto simp add: Ext_def SpecialR_def)
  moreover assume "Ext SpecialR Empty = explode z"
  ultimately have "UNIV = explode(union z (Singleton Empty)) "
    by (auto simp add: explode_def union Singleton)
  then show "False" by (simp add: UNIV_is_not_in_ZF)
qed

definition implode :: "ZF set \<Rightarrow> ZF" where
  "implode == inv explode"

lemma inj_explode: "inj explode"
  by (auto simp add: inj_on_def explode_def Ext)

lemma implode_explode[simp]: "implode (explode x) = x"
  by (simp add: implode_def inj_explode)

definition regular :: "(ZF * ZF) set \<Rightarrow> bool" where
  "regular R == \<forall>A. A \<noteq> Empty \<longrightarrow> (\<exists>x. Elem x A \<and> (\<forall>y. (y, x) \<in> R \<longrightarrow> Not (Elem y A)))"

definition set_like :: "(ZF * ZF) set \<Rightarrow> bool" where
  "set_like R == \<forall>y. Ext R y \<in> range explode"

definition wfzf :: "(ZF * ZF) set \<Rightarrow> bool" where
  "wfzf R == regular R \<and> set_like R"

lemma regular_Elem: "regular is_Elem_of"
  by (simp add: regular_def is_Elem_of_def Regularity)

lemma set_like_Elem: "set_like is_Elem_of"
  by (auto simp add: set_like_def image_def Ext_Elem)

lemma wfzf_is_Elem_of: "wfzf is_Elem_of"
  by (auto simp add: wfzf_def regular_Elem set_like_Elem)

definition SeqSum :: "(nat \<Rightarrow> ZF) \<Rightarrow> ZF" where
  "SeqSum f == Sum (Repl Nat (f o Nat2nat))"

lemma SeqSum: "Elem x (SeqSum f) = (\<exists>n. Elem x (f n))"
  apply (auto simp add: SeqSum_def Sum Repl)
  apply (rule_tac x = "f n" in exI)
  apply auto
  done

definition Ext_ZF :: "(ZF * ZF) set \<Rightarrow> ZF \<Rightarrow> ZF" where
  "Ext_ZF R s == implode (Ext R s)"

lemma Elem_implode: "A \<in> range explode \<Longrightarrow> Elem x (implode A) = (x \<in> A)"
  apply (auto)
  apply (simp_all add: explode_def)
  done

lemma Elem_Ext_ZF: "set_like R \<Longrightarrow> Elem x (Ext_ZF R s) = ((x,s) \<in> R)"
  apply (simp add: Ext_ZF_def)
  apply (subst Elem_implode)
  apply (simp add: set_like_def)
  apply (simp add: Ext_def)
  done

primrec Ext_ZF_n :: "(ZF * ZF) set \<Rightarrow> ZF \<Rightarrow> nat \<Rightarrow> ZF" where
  "Ext_ZF_n R s 0 = Ext_ZF R s"
| "Ext_ZF_n R s (Suc n) = Sum (Repl (Ext_ZF_n R s n) (Ext_ZF R))"

definition Ext_ZF_hull :: "(ZF * ZF) set \<Rightarrow> ZF \<Rightarrow> ZF" where
  "Ext_ZF_hull R s == SeqSum (Ext_ZF_n R s)"

lemma Elem_Ext_ZF_hull:
  assumes set_like_R: "set_like R"
  shows "Elem x (Ext_ZF_hull R S) = (\<exists>n. Elem x (Ext_ZF_n R S n))"
  by (simp add: Ext_ZF_hull_def SeqSum)

lemma Elem_Elem_Ext_ZF_hull:
  assumes set_like_R: "set_like R"
          and x_hull: "Elem x (Ext_ZF_hull R S)"
          and y_R_x: "(y, x) \<in> R"
  shows "Elem y (Ext_ZF_hull R S)"
proof -
  from Elem_Ext_ZF_hull[OF set_like_R] x_hull
  have "\<exists>n. Elem x (Ext_ZF_n R S n)" by auto
  then obtain n where n:"Elem x (Ext_ZF_n R S n)" ..
  with y_R_x have "Elem y (Ext_ZF_n R S (Suc n))"
    apply (auto simp add: Repl Sum)
    apply (rule_tac x="Ext_ZF R x" in exI)
    apply (auto simp add: Elem_Ext_ZF[OF set_like_R])
    done
  with Elem_Ext_ZF_hull[OF set_like_R, where x=y] show ?thesis
    by (auto simp del: Ext_ZF_n.simps)
qed

lemma wfzf_minimal:
  assumes hyps: "wfzf R" "C \<noteq> {}"
  shows "\<exists>x. x \<in> C \<and> (\<forall>y. (y, x) \<in> R \<longrightarrow> y \<notin> C)"
proof -
  from hyps have "\<exists>S. S \<in> C" by auto
  then obtain S where S:"S \<in> C" by auto
  let ?T = "Sep (Ext_ZF_hull R S) (\<lambda> s. s \<in> C)"
  from hyps have set_like_R: "set_like R" by (simp add: wfzf_def)
  show ?thesis
  proof (cases "?T = Empty")
    case True
    then have "\<forall> z. \<not> (Elem z (Sep (Ext_ZF R S) (\<lambda> s. s \<in> C)))"
      apply (auto simp add: Ext Empty Sep Ext_ZF_hull_def SeqSum)
      apply (erule_tac x="z" in allE, auto)
      apply (erule_tac x=0 in allE, auto)
      done
    then show ?thesis
      apply (rule_tac exI[where x=S])
      apply (auto simp add: Sep Empty S)
      apply (erule_tac x=y in allE)
      apply (simp add: set_like_R Elem_Ext_ZF)
      done
  next
    case False
    from hyps have regular_R: "regular R" by (simp add: wfzf_def)
    from
      regular_R[simplified regular_def, rule_format, OF False, simplified Sep]
      Elem_Elem_Ext_ZF_hull[OF set_like_R]
    show ?thesis by blast
  qed
qed

lemma wfzf_implies_wf: "wfzf R \<Longrightarrow> wf R"
proof (subst wf_def, rule allI)
  assume wfzf: "wfzf R"
  fix P :: "ZF \<Rightarrow> bool"
  let ?C = "{x. P x}"
  {
    assume induct: "(\<forall>x. (\<forall>y. (y, x) \<in> R \<longrightarrow> P y) \<longrightarrow> P x)"
    let ?C = "{x. \<not> (P x)}"
    have "?C = {}"
    proof (rule ccontr)
      assume C: "?C \<noteq> {}"
      from
        wfzf_minimal[OF wfzf C]
      obtain x where x: "x \<in> ?C \<and> (\<forall>y. (y, x) \<in> R \<longrightarrow> y \<notin> ?C)" ..
      then have "P x"
        apply (rule_tac induct[rule_format])
        apply auto
        done
      with x show "False" by auto
    qed
    then have "\<forall>x. P x" by auto
  }
  then show "(\<forall>x. (\<forall>y. (y, x) \<in> R \<longrightarrow> P y) \<longrightarrow> P x) \<longrightarrow> (\<forall>x. P x)" by blast
qed

lemma wf_is_Elem_of: "wf is_Elem_of"
  by (auto simp add: wfzf_is_Elem_of wfzf_implies_wf)

lemma in_Ext_RTrans_implies_Elem_Ext_ZF_hull:
  "set_like R \<Longrightarrow> x \<in> (Ext (R\<^sup>+) s) \<Longrightarrow> Elem x (Ext_ZF_hull R s)"
  apply (simp add: Ext_def Elem_Ext_ZF_hull)
  apply (erule converse_trancl_induct[where r="R"])
  apply (rule exI[where x=0])
  apply (simp add: Elem_Ext_ZF)
  apply auto
  apply (rule_tac x="Suc n" in exI)
  apply (simp add: Sum Repl)
  apply (rule_tac x="Ext_ZF R z" in exI)
  apply (auto simp add: Elem_Ext_ZF)
  done

lemma implodeable_Ext_trancl: "set_like R \<Longrightarrow> set_like (R\<^sup>+)"
  apply (subst set_like_def)
  apply (auto simp add: image_def)
  apply (rule_tac x="Sep (Ext_ZF_hull R y) (\<lambda> z. z \<in> (Ext (R\<^sup>+) y))" in exI)
  apply (auto simp add: explode_def Sep set_eqI
    in_Ext_RTrans_implies_Elem_Ext_ZF_hull)
  done

lemma Elem_Ext_ZF_hull_implies_in_Ext_RTrans[rule_format]:
  "set_like R \<Longrightarrow> \<forall>x. Elem x (Ext_ZF_n R s n) \<longrightarrow> x \<in> (Ext (R\<^sup>+) s)"
  apply (induct_tac n)
  apply (auto simp add: Elem_Ext_ZF Ext_def Sum Repl)
  done

lemma "set_like R \<Longrightarrow> Ext_ZF (R\<^sup>+) s = Ext_ZF_hull R s"
  apply (frule implodeable_Ext_trancl)
  apply (auto simp add: Ext)
  apply (erule in_Ext_RTrans_implies_Elem_Ext_ZF_hull)
  apply (simp add: Elem_Ext_ZF Ext_def)
  apply (auto simp add: Elem_Ext_ZF Elem_Ext_ZF_hull)
  apply (erule Elem_Ext_ZF_hull_implies_in_Ext_RTrans[simplified Ext_def, simplified], assumption)
  done

lemma wf_implies_regular: "wf R \<Longrightarrow> regular R"
proof (simp add: regular_def, rule allI)
  assume wf: "wf R"
  fix A
  show "A \<noteq> Empty \<longrightarrow> (\<exists>x. Elem x A \<and> (\<forall>y. (y, x) \<in> R \<longrightarrow> \<not> Elem y A))"
  proof
    assume A: "A \<noteq> Empty"
    then have "\<exists>x. x \<in> explode A"
      by (auto simp add: explode_def Ext Empty)
    then obtain x where x:"x \<in> explode A" ..
    from iffD1[OF wf_eq_minimal wf, rule_format, where Q="explode A", OF x]
    obtain z where "z \<in> explode A \<and> (\<forall>y. (y, z) \<in> R \<longrightarrow> y \<notin> explode A)" by auto
    then show "\<exists>x. Elem x A \<and> (\<forall>y. (y, x) \<in> R \<longrightarrow> \<not> Elem y A)"
      apply (rule_tac exI[where x = z])
      apply (simp add: explode_def)
      done
  qed
qed

lemma wf_eq_wfzf: "(wf R \<and> set_like R) = wfzf R"
  apply (auto simp add: wfzf_implies_wf)
  apply (auto simp add: wfzf_def wf_implies_regular)
  done

lemma wfzf_trancl: "wfzf R \<Longrightarrow> wfzf (R\<^sup>+)"
  by (auto simp add: wf_eq_wfzf[symmetric] implodeable_Ext_trancl wf_trancl)

lemma Ext_subset_mono: "R \<subseteq> S \<Longrightarrow> Ext R y \<subseteq> Ext S y"
  by (auto simp add: Ext_def)

lemma set_like_subset: "set_like R \<Longrightarrow> S \<subseteq> R \<Longrightarrow> set_like S"
  apply (auto simp add: set_like_def)
  apply (erule_tac x=y in allE)
  apply (drule_tac y=y in Ext_subset_mono)
  apply (auto simp add: image_def)
  apply (rule_tac x="Sep x (% z. z \<in> (Ext S y))" in exI)
  apply (auto simp add: explode_def Sep)
  done

lemma wfzf_subset: "wfzf S \<Longrightarrow> R \<subseteq> S \<Longrightarrow> wfzf R"
  by (auto intro: set_like_subset wf_subset simp add: wf_eq_wfzf[symmetric])

end


(*by Ammer*)
theory VEBT_Member imports VEBT_Definitions
begin

section \<open>Member Function\<close>

context begin
interpretation VEBT_internal .

fun vebt_member :: "VEBT  \<Rightarrow> nat \<Rightarrow> bool" where
  "vebt_member (Leaf a b) x = (if x = 0 then a else if x = 1 then b else False)"|
  "vebt_member (Node None _ _ _) x = False"|
  "vebt_member (Node _ 0 _ _) x = False"|
  "vebt_member (Node _ (Suc 0) _ _) x = False"|
  "vebt_member (Node (Some (mi, ma)) deg treeList summary) x = (
    if x = mi then True else
    if x = ma then True else
    if x < mi then False else
    if x > ma then False else (
     let h = high x (deg div 2);
         l = low x (deg div 2) in(
          if h < length treeList
          then vebt_member (treeList ! h) l
          else False))) "

end

context VEBT_internal begin

lemma member_inv:
  assumes "vebt_member  (Node (Some (mi, ma)) deg treeList summary) x "
  shows "deg \<ge> 2 \<and>
         (x = mi \<or> x = ma \<or> (x < ma \<and> x > mi \<and>  high x (deg div 2) < length treeList \<and>
                                   vebt_member (treeList ! ( high x (deg div 2))) (low x (deg div 2))))"
proof(cases deg)
  case 0
  then show ?thesis using vebt_member.simps(3)[of "(mi, ma)" treeList summary x]
    using assms by blast
  next
  case (Suc nat)
  hence "deg = Suc nat" by simp
  then show ?thesis proof(cases nat)
    case 0
    then show ?thesis
      using Suc assms by auto
    next
    case (Suc nata)
    hence "deg \<ge> 2"
      by (simp add: \<open>deg = Suc nat\<close>)
    then show ?thesis
      by (metis vebt_member.simps(5) Suc \<open>deg = Suc nat\<close> assms linorder_neqE_nat)
  qed
qed

definition bit_concat::"nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat" where
"bit_concat h l d = h*2^d + l"

lemma bit_split_inv: "bit_concat (high x d) (low x d) d = x"
  unfolding bit_concat_def high_def low_def
  by presburger

definition set_vebt'::"VEBT \<Rightarrow> nat set" where
  "set_vebt' t = {x. vebt_member t x}"

lemma Leaf_0_not: assumes "invar_vebt (Leaf a b) 0 "shows " False"
proof-
  from assms show ?thesis
  proof(cases)
  qed
qed

lemma  valid_0_not: "invar_vebt t 0 \<Longrightarrow> False"
proof(induction t)
  case (Node info deg treeList summary)
  from this(3) have  "length treeList > 0"
    apply cases
    apply auto
    done
  then obtain t where "t \<in> set treeList" by fastforce
  from Node(3) obtain n where "invar_vebt t n"
    apply cases
    using Node.IH(2) apply auto
    done
  from  Node(3) have  "n \<le> 0"
    apply cases
    using Node.IH(2) apply auto
    done
  hence "n = 0" by blast
  then show ?case
    using Node.IH(1) \<open>t \<in> set treeList\<close> \<open>invar_vebt t n\<close> by blast
next
  case (Leaf x1 x2)
  then show ?case
    using Leaf_0_not by blast
qed

theorem valid_tree_deg_neq_0: "(\<not> invar_vebt t 0)"
  using valid_0_not by blast

lemma deg_1_Leafy:  "invar_vebt t n \<Longrightarrow> n = 1 \<Longrightarrow> \<exists> a b. t = Leaf a b"
  apply(induction rule: invar_vebt.induct)
  apply simp
  apply presburger
  apply (metis (full_types) Suc_eq_plus1 add_cancel_right_left in_set_replicate list.map_cong0 map_replicate_const nat_neq_iff not_add_less2 numeral_1_eq_Suc_0 numeral_2_eq_2 numerals(1) order_less_irrefl power_eq_0_iff valid_tree_deg_neq_0 zero_less_numeral)
  apply (metis odd_add odd_one)
  by (metis Suc_eq_plus1 add_cancel_right_left in_set_replicate list.map_cong0 map_replicate_const nat_neq_iff not_add_less2 numeral_2_eq_2 power_eq_0_iff valid_tree_deg_neq_0)

lemma deg_1_Leaf: "invar_vebt t 1 \<Longrightarrow>  \<exists> a b. t = Leaf a b"
  using deg_1_Leafy by blast

corollary deg1Leaf: "invar_vebt t 1 \<longleftrightarrow>  (\<exists> a b. t = Leaf a b)"
  using deg_1_Leaf invar_vebt.intros(1) by auto

lemma deg_SUcn_Node: assumes "invar_vebt tree (Suc (Suc n)) " shows
                " \<exists> info treeList s. tree = Node info (Suc (Suc n)) treeList s"
proof-
  from assms show ?thesis apply(cases)
    apply blast+
   done
qed

lemma "invar_vebt (Node info deg treeList summary) deg \<Longrightarrow> deg > 1"
  by (metis VEBT.simps(4) deg_1_Leafy less_one linorder_neqE_nat valid_tree_deg_neq_0)

lemma deg_deg_n: assumes "invar_vebt (Node info deg treeList summary) n "shows" deg = n"
proof-
  from assms show ?thesis proof(cases)
  qed blast+
qed

lemma member_valid_both_member_options:
  "invar_vebt tree n \<Longrightarrow> vebt_member tree x \<Longrightarrow> (naive_member tree x \<or> membermima tree x)"
proof(induction tree n arbitrary: x rule: invar_vebt.induct)
  case (1 a b)
  then show ?case
    using vebt_member.simps(1) naive_member.simps(1) by blast
next
  case (2 treeList n summary m deg)
  then show ?case by simp
next
  case (3 treeList n summary m deg)
  then show ?case
    using vebt_member.simps(2) by blast
next
  case (4 treeList n summary m deg mi ma)
  hence "deg \<ge> 2"
    using member_inv by blast
  then show ?case proof(cases "x = mi \<or> x = ma")
    case True
    then show ?thesis
      by (metis (full_types) "4"(12) vebt_member.simps(3) membermima.simps(4) old.nat.exhaust)
  next
    case False
    hence 1:"mi < x \<and> x < ma \<and> (high x (deg div 2 )) < length treeList \<and> vebt_member (treeList ! (high x (deg div 2))) (low x (deg div 2))"
      using member_inv[of mi ma deg treeList summary x] "4"(12) by blast
    hence " (treeList ! (high x (deg div 2))) \<in> set treeList"
      by (metis in_set_member inthall)
    hence "both_member_options  (treeList ! (high x (deg div 2))) (low x (deg div 2))"
      using "1" "4.IH"(1) both_member_options_def by blast
    then show ?thesis
      by (smt "1" "4"(1) "4"(6) \<open>treeList ! high x (deg div 2) \<in> set treeList\<close> membermima.simps(4) naive_member.simps(3) old.nat.exhaust valid_tree_deg_neq_0 zero_eq_add_iff_both_eq_0)
  qed
next
  case (5 treeList n summary m deg mi ma)
  hence "deg \<ge> 2"
    using member_inv by presburger
  then show ?case proof(cases "x = mi \<or> x = ma")
    case True
    then show ?thesis
      by (metis (full_types) "5"(12) vebt_member.simps(3) membermima.simps(4) old.nat.exhaust)
  next
    case False
    hence 1:"mi < x \<and> x < ma \<and> (high x (deg div 2 )) < length treeList \<and> vebt_member (treeList ! (high x (deg div 2))) (low x (deg div 2))"
      using member_inv[of mi ma deg treeList summary x] "5"(12) by blast
    hence " (treeList ! (high x (deg div 2))) \<in> set treeList"
      by (metis in_set_member inthall)
    hence "both_member_options  (treeList ! (high x (deg div 2))) (low x (deg div 2))"
      using "1" "5.IH"(1) both_member_options_def by blast
    then show ?thesis
      by (smt "1" "5"(1) "5"(6) \<open>treeList ! high x (deg div 2) \<in> set treeList\<close> membermima.simps(4) naive_member.simps(3) old.nat.exhaust valid_tree_deg_neq_0 zero_eq_add_iff_both_eq_0)
  qed
qed

lemma  member_bound: "vebt_member tree x \<Longrightarrow> invar_vebt tree n  \<Longrightarrow> x < 2^n"
proof(induction tree x arbitrary: n rule: vebt_member.induct)
  case (1 a b x)
  then show ?case  by (metis vebt_member.simps(1) One_nat_def le_neq_implies_less nat_power_eq_Suc_0_iff
                       numeral_eq_iff numerals(1) one_le_numeral one_le_power semiring_norm(85) valid_tree_deg_neq_0
                       zero_less_numeral zero_less_power)
next
  case (2 uu uv uw x)
  then show ?case by simp
next
  case (3 v uy uz x)
  then show ?case by simp
next
  case (4 v vb vc x)
  then show ?case by simp
next
  case (5 mi ma va treeList summary x)
  hence 111: "n =  Suc (Suc va)"
    using deg_deg_n by fastforce
  hence "ma < 2^n"
    using "5.prems"(2) mi_ma_2_deg by blast
  then show ?case
    by (metis "5.prems"(1) "5.prems"(2) le_less_trans less_imp_le_nat member_inv mi_ma_2_deg)
qed

theorem inrange: assumes "invar_vebt t n" shows " set_vebt' t \<subseteq> {0..2^n-1}"
proof
  fix x
  assume "x \<in> set_vebt' t"
  hence "vebt_member t x"
    using set_vebt'_def by auto
    hence "x < 2^n"
      using assms member_bound by blast
    then show "x \<in> {0..2^n-1}" by simp
  qed

theorem buildup_gives_empty: "set_vebt' (vebt_buildup n) = {}"
  unfolding set_vebt'_def
  by (metis Collect_empty_eq vebt_member.simps(1) vebt_member.simps(2) vebt_buildup.elims)

fun minNull::"VEBT \<Rightarrow> bool" where
"minNull (Leaf False False) = True"|
"minNull (Leaf _ _ ) = False"|
"minNull (Node None _ _ _) = True"|
"minNull (Node (Some _) _ _ _) = False"

lemma min_Null_member: "minNull t \<Longrightarrow> \<not> vebt_member t x"
  apply(induction t)
  using vebt_member.simps(2) minNull.elims(2) apply blast
  apply  auto
  done

lemma not_min_Null_member: "\<not> minNull t \<Longrightarrow> \<exists> y. both_member_options t y"
proof(induction t)
  case (Node info deg treeList summary)
  obtain mi ma where "info = Some(mi , ma)"
    by (metis Node.prems minNull.simps(4) not_None_eq surj_pair)
  then show ?case
    by (metis (full_types) both_member_options_def membermima.simps(3) membermima.simps(4) not0_implies_Suc)
next
  case (Leaf x1 x2)
  then show ?case
    by (metis (full_types) both_member_options_def minNull.simps(1) naive_member.simps(1) zero_neq_one)
qed

lemma valid_member_both_member_options: "invar_vebt t n \<Longrightarrow>  both_member_options t x \<Longrightarrow> vebt_member t x"
proof(induction t n arbitrary: x rule: invar_vebt.induct)
  case (1 a b)
  then show ?case
    by (simp add: both_member_options_def)
next
  case (2 treeList n summary m deg)
  hence 0: " ( \<forall> t \<in> set treeList. invar_vebt t n) " and 1:" invar_vebt summary n" and 2:" length treeList = 2^n" and
    3:" deg = 2*n" and 4:" (\<nexists> i. both_member_options summary i)" and 5:" (\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y) " and 6: "n> 0"
          apply blast+
          apply (auto simp add: "2.hyps"(3) "2.hyps")
          using "2.hyps"(1) "2.hyps"(3) neq0_conv valid_tree_deg_neq_0 by blast
  have "both_member_options (Node None deg treeList summary) x \<Longrightarrow> False"
  proof-
    assume "both_member_options (Node None deg treeList summary) x"
    hence "naive_member  (Node None deg treeList summary) x \<or> membermima  (Node None deg treeList summary) x" unfolding both_member_options_def by simp
    then show False
    proof(cases  "naive_member  (Node None deg treeList summary) x")
      case True
      hence "high x n < length treeList \<and> naive_member (treeList ! (high x n)) (low x n)"
        by (metis "1" "2.hyps"(3) "2.hyps"(4) add_cancel_right_left add_self_div_2 naive_member.simps(3) old.nat.exhaust valid_tree_deg_neq_0)
      then show ?thesis
        by (metis "5" both_member_options_def in_set_member inthall)
    next
      case False
      hence "membermima  (Node None deg treeList summary) x"
        using \<open>naive_member (Node None deg treeList summary) x \<or> membermima (Node None deg treeList summary) x\<close> by blast
      moreover have "Suc (deg-1) =deg"
        by (simp add: "2.hyps"(4) "6")
      moreover hence "(let pos = high x (deg div 2) in if pos < length treeList then membermima (treeList ! pos) (low x (Suc (deg - 1) div 2)) else False)"
        using calculation(1) membermima.simps(5) by metis
      moreover hence " if  high x (deg div 2) < length treeList then membermima (treeList ! (  high x (deg div 2))) (low x(deg div 2)) else False"
        using calculation(2) by metis
      ultimately
      have " high x (deg div 2) < length treeList \<and> membermima (treeList ! (high x n)) (low x n)"
        by (metis "2.hyps"(3) "2.hyps"(4) add_self_div_2)
      then show ?thesis using "2.IH" "5" both_member_options_def in_set_member inthall
        by (metis "2.hyps"(3) "2.hyps"(4) add_self_div_2)
    qed
  qed
  then show ?case
    by (simp add: "2.prems")
next
  case (3 treeList n summary m deg)
  hence 0: " ( \<forall> t \<in> set treeList. invar_vebt t n) " and 1:" invar_vebt summary m" and 2:" length treeList = 2^m" and
    3:" deg = n+m" and 4:" (\<nexists> i. both_member_options summary i)" and 5:" (\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y) " and 6: "n> 0" and 7: "m> 0"
    and 8: "n+1 = m"
            apply blast+
            apply (metis (full_types) "3.IH"(1) "3.hyps"(2) in_set_member inthall neq0_conv power_eq_0_iff valid_tree_deg_neq_0 zero_neq_numeral)
            apply (simp add: "3.hyps"(3))
            by (simp add: "3.hyps"(3))
  have "both_member_options (Node None deg treeList summary) x \<Longrightarrow> False"
  proof-
    assume "both_member_options (Node None deg treeList summary) x"
    hence "naive_member  (Node None deg treeList summary) x \<or> membermima  (Node None deg treeList summary) x" unfolding both_member_options_def by simp
    then show False
    proof(cases  "naive_member  (Node None deg treeList summary) x")
      case True
      hence "high x n < length treeList \<and> naive_member (treeList ! (high x n)) (low x n)"
        by (metis "3" "3.hyps"(3) add_Suc_right add_self_div_2 even_Suc_div_two naive_member.simps(3) odd_add)
      then show ?thesis
        by (metis "5" both_member_options_def in_set_member inthall)
    next
      case False
      hence "membermima  (Node None deg treeList summary) x"
        using \<open>naive_member (Node None deg treeList summary) x \<or> membermima (Node None deg treeList summary) x\<close> by blast
      moreover have "Suc (deg-1) =deg"
        by (simp add: "3" "3.hyps"(3))
      moreover hence "(let pos = high x (deg div 2) in if pos < length treeList then membermima (treeList ! pos) (low x (Suc (deg - 1) div 2)) else False)"
        using calculation(1) membermima.simps(5) by metis
      moreover hence 11:" if  high x (deg div 2) < length treeList then membermima (treeList ! (  high x (deg div 2))) (low x(deg div 2)) else False"
        using calculation(2) by metis
      ultimately
      have " high x (deg div 2) < length treeList \<and> membermima (treeList ! (high x n)) (low x n)"
        by (metis "3" "3.hyps"(3) add_Suc_right add_self_div_2 even_Suc_div_two odd_add)
      then show ?thesis using "3.IH" "5" both_member_options_def in_set_member inthall 11 by metis
    qed
  qed
  then show ?case
    using "3.prems" by blast
next
  case (4 treeList n summary m deg mi ma)
  hence 0: "( \<forall> t \<in> set treeList. invar_vebt t n)" and 1: " invar_vebt summary n" and 2:"length treeList = 2^n" and 3:" deg = n+m" and "n=m" and
    4: "(\<forall> i < 2^n. (\<exists> y. both_member_options (treeList ! i) y) \<longleftrightarrow> ( both_member_options summary i))" and
    5: "(mi = ma \<longrightarrow> (\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y))" and 6:"mi \<le> ma  \<and> ma < 2^deg" and
    7: "(mi \<noteq> ma \<longrightarrow> (\<forall> i < 2^m. (high ma n = i \<longrightarrow> both_member_options (treeList ! i) (low ma n)) \<and>
                                         (\<forall> y. (high y n = i \<and> both_member_options (treeList ! i) (low y n)  ) \<longrightarrow> mi < y \<and> y \<le> ma)))"
    using "4.prems" by auto
  hence "n>0"
    by (metis neq0_conv valid_tree_deg_neq_0)
  then show ?case proof(cases "x = mi \<or> x = ma")
    case True
    hence xmimastmt: "x = mi \<or> x=ma" by simp
    then show ?thesis using vebt_member.simps(5)[of mi ma "deg-2" treeList summary x]
      by (metis "3" "4.hyps"(3) \<open>0 < n\<close> add_diff_inverse_nat add_numeral_left add_self_div_2 div_if nat_neq_iff numerals(1) plus_1_eq_Suc semiring_norm(2))
  next
    case False
    hence xmimastmt: "x \<noteq> mi \<and> x\<noteq>ma" by simp
    hence "mi = ma \<Longrightarrow> False"
    proof-
      assume "mi = ma"
      hence astmt: "(\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y)" using 5 by simp
      have bstmt: "both_member_options  (Node (Some (mi, ma)) deg treeList summary) x"
        by (simp add: "4.prems")
      then show False
      proof(cases  "naive_member  (Node (Some (mi, ma)) deg treeList summary) x")
        case True
        hence "high x n < length treeList \<and> naive_member (treeList ! (high x n)) (low x n)"
          by (metis (no_types, opaque_lifting) "3" "4.hyps"(1) "4.hyps"(3) add_self_div_2 naive_member.simps(3) old.nat.exhaust valid_0_not zero_eq_add_iff_both_eq_0)
        then show ?thesis
          by (metis "5" \<open>mi = ma\<close> both_member_options_def in_set_member inthall)
      next
        case False
        hence "membermima  (Node (Some (mi, ma)) deg treeList summary) x" using bstmt unfolding both_member_options_def by blast
        hence " x = mi \<or> x = ma \<or> (if high x n < length treeList then  membermima (treeList ! (high x n)) (low x n) else False)"
          using membermima.simps(4)[of mi ma "deg-1" treeList summary x]
          by (metis "3" "4.hyps"(3) One_nat_def Suc_diff_Suc \<open>0 < n\<close> add_gr_0 add_self_div_2 diff_zero)
        hence " high x n < length treeList \<and> membermima (treeList ! (high x n)) (low x n)" using xmimastmt
          by presburger
        then show ?thesis using both_member_options_def in_set_member inthall membermima.simps(4)[of mi ma n treeList summary x] astmt
          by metis
      qed
    qed
    hence "mi \<noteq> ma " by blast
    hence followstmt: "(\<forall> i < 2^m. (high ma n = i \<longrightarrow> both_member_options (treeList ! i) (low ma n)) \<and>
                                         (\<forall> y. (high y n = i \<and> both_member_options (treeList ! i) (low y n)  ) \<longrightarrow> mi < y \<and> y \<le> ma))"
      using 7 by simp
    have 10:"high x n < length treeList \<and>
       (naive_member (treeList ! (high x n)) (low x n) \<or> membermima (treeList ! (high x n)) (low x n) )"
      by (smt "3" "4.hyps"(3) "4.prems" False One_nat_def Suc_leI \<open>0 < n\<close> add_gr_0 add_self_div_2 both_member_options_def le_add_diff_inverse membermima.simps(4) naive_member.simps(3) plus_1_eq_Suc)
    hence 11:"both_member_options (treeList ! (high x n)) (low x n)"
      by (simp add: both_member_options_def)
    have 12:"high x n< 2^m"
      using "10" "4.hyps"(2) by auto
    hence "mi < x \<and> x < ma" proof-
      have "(\<forall> y. (high y n = (high x n) \<and> both_member_options (treeList ! (high y n)) (low y n)  ) \<longrightarrow> mi < y \<and> y \<le> ma)"
        using "12" followstmt by auto
      then show ?thesis
        using "11" False order.not_eq_order_implies_strict by blast
    qed
    have "vebt_member (treeList ! (high x n)) (low x n)"
      by (metis"10" "11" "4.IH"(1) in_set_member inthall)
    then show ?thesis
      by (smt "10" "11" "12" "3" "4.hyps"(3) vebt_member.simps(5) One_nat_def Suc_leI \<open>0 < n\<close> add_Suc_right add_self_div_2 followstmt le_add_diff_inverse le_imp_less_Suc not_less_eq not_less_iff_gr_or_eq plus_1_eq_Suc)
  qed
next
  case (5 treeList n summary m deg mi ma)
  hence 0: "( \<forall> t \<in> set treeList. invar_vebt t n)" and 1: " invar_vebt summary m" and 2:"length treeList = 2^m" and 3:" deg = n+m" and "Suc n=m" and
    4: "(\<forall> i < 2^m. (\<exists> y. both_member_options (treeList ! i) y) \<longleftrightarrow> ( both_member_options summary i))" and
    5: "(mi = ma \<longrightarrow> (\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y))" and 6:"mi \<le> ma  \<and> ma < 2^deg" and
    7: "(mi \<noteq> ma \<longrightarrow> (\<forall> i < 2^m. (high ma n = i \<longrightarrow> both_member_options (treeList ! i) (low ma n)) \<and>
                                         (\<forall> y. (high y n = i \<and> both_member_options (treeList ! i) (low y n)  ) \<longrightarrow> mi < y \<and> y \<le> ma)))"
    using "5.prems" by auto
  hence "n>0"
    by (metis "5.hyps"(3) in_set_member inthall neq0_conv power_Suc0_right valid_tree_deg_neq_0 zero_neq_numeral)
  then show ?case proof(cases "x = mi \<or> x = ma")
    case True
    hence xmimastmt: "x = mi \<or> x=ma" by simp
    then show ?thesis using vebt_member.simps(5)[of mi ma "deg-2" treeList summary x]
      using "3" "5.hyps"(3) \<open>0 < n\<close> by auto
  next
    case False
    hence xmimastmt: "x \<noteq> mi \<and> x\<noteq>ma" by simp
    hence "mi = ma \<Longrightarrow> False"
    proof-
      assume "mi = ma"
      hence astmt: "(\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y)" using 5 by simp
      have bstmt: "both_member_options  (Node (Some (mi, ma)) deg treeList summary) x"
        by (simp add: "5.prems")
      then show False
      proof(cases  "naive_member  (Node (Some (mi, ma)) deg treeList summary) x")
        case True
        hence "high x n < length treeList \<and> naive_member (treeList ! (high x n)) (low x n)"
          by (metis "3" "5.hyps"(3) add_Suc_right add_self_div_2 even_Suc_div_two naive_member.simps(3) odd_add)
        then show ?thesis
          by (metis "5" \<open>mi = ma\<close> both_member_options_def in_set_member inthall)
      next
        case False
        hence "membermima  (Node (Some (mi, ma)) deg treeList summary) x" using bstmt unfolding both_member_options_def by blast
        hence " x = mi \<or> x = ma \<or> (if high x n < length treeList then  membermima (treeList ! (high x n)) (low x n) else False)"
          using membermima.simps(4)[of mi ma "deg-1" treeList summary x]
          using "3" "5.hyps"(3) by auto
        hence " high x n < length treeList \<and> membermima (treeList ! (high x n)) (low x n)" using xmimastmt
          by presburger
        then show ?thesis using both_member_options_def in_set_member inthall membermima.simps(4)[of mi ma n treeList summary x] astmt
          by metis
      qed
    qed
    hence "mi \<noteq> ma " by blast
    hence followstmt: "(\<forall> i < 2^m. (high ma n = i \<longrightarrow> both_member_options (treeList ! i) (low ma n)) \<and>
                                         (\<forall> y. (high y n = i \<and> both_member_options (treeList ! i) (low y n)  ) \<longrightarrow> mi < y \<and> y \<le> ma))"
      using 7 by simp
    have 10:"high x n < length treeList \<and>
       (naive_member (treeList ! (high x n)) (low x n) \<or> membermima (treeList ! (high x n)) (low x n) )"
      by (smt "3" "5.hyps"(3) "5.prems" False add_Suc_right add_self_div_2 both_member_options_def even_Suc_div_two membermima.simps(4) naive_member.simps(3) odd_add)
    hence 11:"both_member_options (treeList ! (high x n)) (low x n)"
      by (simp add: both_member_options_def)
    have 12:"high x n< 2^m"
      using "10" "5.hyps"(2) by auto
    hence "mi < x \<and> x < ma" proof-
      have "(\<forall> y. (high y n = (high x n) \<and> both_member_options (treeList ! (high y n)) (low y n)  ) \<longrightarrow> mi < y \<and> y \<le> ma)"
        using "12" followstmt by auto
      then show ?thesis
        using "11" False order.not_eq_order_implies_strict by blast
    qed
    have "vebt_member (treeList ! (high x n)) (low x n)"
      by (metis "10" "11" "5.IH"(1) in_set_member inthall)
    then show ?thesis
      by (smt "10" "11" "12" "3" "5.hyps"(3) vebt_member.simps(5) Suc_pred \<open>0 < n\<close> add_Suc_right add_self_div_2 even_Suc_div_two followstmt le_neq_implies_less not_less_iff_gr_or_eq odd_add)
  qed
qed

corollary both_member_options_equiv_member: assumes "invar_vebt t n"
  shows "both_member_options t x \<longleftrightarrow> vebt_member t x"
  using assms both_member_options_def member_valid_both_member_options valid_member_both_member_options by blast

lemma member_correct: "invar_vebt t n \<Longrightarrow> vebt_member t x \<longleftrightarrow> x \<in> set_vebt t "
  using both_member_options_equiv_member set_vebt_def  by auto

corollary set_vebt_set_vebt'_valid: assumes "invar_vebt t n" shows "set_vebt t =set_vebt' t"
  unfolding set_vebt_def set_vebt'_def
  apply auto
  using assms valid_member_both_member_options apply auto[1]
  using assms both_member_options_equiv_member by auto

lemma set_vebt_finite: "invar_vebt t n \<Longrightarrow> finite (set_vebt' t)"
  using finite_subset inrange by blast

lemma mi_eq_ma_no_ch:assumes "invar_vebt (Node (Some (mi, ma)) deg treeList summary) deg " and " mi  = ma "
  shows  "(\<forall> t \<in> set treeList. \<nexists> x. both_member_options t x ) \<and> (\<nexists> x. both_member_options summary x)"
proof-
  from assms(1) show ?thesis
  proof(cases)
    case (4 n m)
    have 0:"\<forall>t\<in>set treeList. \<not> Ex (both_member_options t)"
      by (simp add: "4"(7) assms(2))
    moreover have "both_member_options summary x \<Longrightarrow> False" for x
    proof-
      assume "both_member_options summary x "
      hence "vebt_member summary x"
        using "4"(2) valid_member_both_member_options by auto
      moreover hence "x < 2^m"
        using "4"(2) member_bound by auto
      ultimately have "\<exists> y. both_member_options (treeList ! (high x n)) y"
        using  "0" "4"(3) "4"(4) "4"(6) \<open>both_member_options summary x\<close> inthall
        by (metis nth_mem)
      then show ?thesis
        by (metis "0" "4"(3) "4"(4) div_eq_0_iff \<open>x < 2 ^ m\<close> high_def nth_mem zero_less_numeral zero_less_power)
    qed
    then show ?thesis
      using calculation by blast
  next
    case (5 n m)
    have 0:"\<forall>t\<in>set treeList. \<not> Ex (both_member_options t)"
      using "5"(7) assms(2) by blast
    moreover have "both_member_options summary x \<Longrightarrow> False" for x
    proof-
      assume "both_member_options summary x "
      hence "vebt_member summary x"
        using "5"(2) valid_member_both_member_options by auto
      moreover hence "x < 2^m"
        using "5"(2) member_bound by auto
      ultimately have "\<exists> y. both_member_options (treeList ! (high x n)) y"
        using  "0" "5"(3) "5"(4) "5"(6) \<open>both_member_options summary x\<close> inthall
        by (metis nth_mem)
      then show ?thesis
        by (metis "0" "5"(3) "5"(6) \<open>both_member_options summary x\<close> \<open>x < 2 ^ m\<close> nth_mem)
    qed
    then show ?thesis
      using calculation by blast
  qed
qed

end
end


(*
  File:    Buffons_Needle.thy
  Author:  Manuel Eberl <eberlm@in.tum.de>

  A formal solution of Buffon's needle problem.
*)
section \<open>Buffon's Needle Problem\<close>
theory Buffons_Needle
  imports "HOL-Probability.Probability"
begin

subsection \<open>Auxiliary material\<close>

lemma sin_le_zero': "sin x \<le> 0" if "x \<ge> -pi" "x \<le> 0" for x
  by (metis minus_le_iff neg_0_le_iff_le sin_ge_zero sin_minus that(1) that(2))

subsection \<open>Problem definition\<close>

text \<open>
  Consider a needle of length $l$ whose centre has the $x$-coordinate $x$. The following then
  defines the set of all $x$-coordinates that the needle covers
  (i.e. the projection of the needle onto the $x$-axis.)
\<close>
definition needle :: "real \<Rightarrow> real \<Rightarrow> real \<Rightarrow> real set" where
  "needle l x \<phi> = closed_segment (x - l / 2 * sin \<phi>) (x + l / 2 * sin \<phi>)"

text_raw \<open>
\begin{figure}
\begin{center}
\begin{tikzpicture}
\coordinate (lefttick) at (-3,0);
\coordinate (righttick) at (3,0);

\draw (lefttick) -- (righttick);
\draw [thick] (lefttick) ++ (0,0.4) -- ++(0,3);
\draw [thick] (righttick) ++ (0,0.4) -- ++(0,3);

\coordinate (needle) at (1,2);

\newcommand{\needleangle}{55}
\newcommand{\needlelength}{{1}}
\newcommand{\needlethickness}{0.6pt}

\draw ($(lefttick)+(0,4pt)$) -- ($(lefttick)-(0,4pt)$);
\draw ($(righttick)+(0,4pt)$) -- ($(righttick)-(0,4pt)$);
\draw (0,4pt) -- (0,-4pt);

\draw [densely dashed, thin] let \p1 = (needle) in (\x1, 0) -- (needle);
\draw [densely dashed, thin] let \p1 = (needle) in (needle) -- (3, \y1);
\draw (needle) ++ (15pt,0) arc(0:\needleangle:15pt);
\path (needle) -- ++(15pt,0) node [above, midway, yshift=-1.9pt, xshift=1.8pt] {$\scriptstyle\varphi$};

\node [below, xshift=-3.5pt] at ($(lefttick)-(0,4pt)$) {$-\nicefrac{d}{2}$};
\node [below] at ($(righttick)-(0,4pt)$) {$\nicefrac{d}{2}$};
\node [below,yshift=-1pt] at (0,-4pt) {$0$};
\node [below,yshift=-2pt] at (needle |- 0,-4pt) {$x$};

\draw[<->] (needle) ++({\needleangle+90}:5pt) ++(\needleangle:{-\needlelength}) -- ++(\needleangle:2) node [midway, above, rotate=\needleangle] {$\scriptstyle l$};

\draw [line width=0.7pt,fill=white] (needle) ++({\needleangle+90}:\needlethickness) -- ++(\needleangle:\needlelength) arc({\needleangle+90}:{\needleangle-90}:\needlethickness)
  -- ++(\needleangle:-\needlelength) -- ++(\needleangle:-\needlelength) arc({\needleangle+270}:{\needleangle+90}:\needlethickness) -- ++(\needleangle:\needlelength);

\end{tikzpicture}
\end{center}
\caption{A sketch of the situation in Buffon's needle experiment. There is a needle of length $l$
with its centre at a certain $x$ coordinate, angled at an angle $\varphi$ off the horizontal axis.
The two vertical lines are a distance of $d$ apart, each being $\nicefrac{d}{2}$ away from the
origin.}
\label{fig:buffon}
\end{figure}

\definecolor{myred}{HTML}{cc2428}
\begin{figure}[h]
\begin{center}
\begin{tikzpicture}
  \begin{axis}[
          xmin=0, xmax=7, ymin=0, ymax=1,
          width=\textwidth, height=0.6\textwidth,
          xlabel={$l/d$}, ylabel={$\mathcal P$}, tick style={thin,black},
          ylabel style = {rotate=270,anchor=west},
  ]
  \addplot [color=myred, line width=1pt, mark=none,domain=0:1,samples=200] ({x}, {2/pi*x});
  \addplot [color=myred, line width=1pt, mark=none,domain=1:7,samples=200] ({x}, {2/pi*(x-sqrt(x*x-1)+acos(1/x)/180*pi)});
  \end{axis}
\end{tikzpicture}
\caption{The probability $\mathcal P$ of the needle hitting one of the lines, as a function of the quotient $l/d$ (where $l$ is the length of the needle and $d$ the horizontal distance between the lines).}
\label{fig:buffonplot}
\end{center}
\end{figure}
\<close>

text \<open>
  Buffon's Needle problem is then this: Assuming the needle's $x$ position is chosen uniformly
  at random in a strip of width $d$ centred at the origin, what is the probability that the
  needle crosses at least one of the left/right boundaries of that strip (located at
  $x = \pm\frac{1}{2}d$)?

  We will show that, if we let $x := \nicefrac{l}{d}$, the probability of this is
  \[
  \mathcal P_{l,d} =
    \begin{cases}
      \nicefrac{2}{\pi} \cdot x & \text{if}\ l \leq d\\
      \nicefrac{2}{\pi}\cdot(x - \sqrt{x^2 - 1} + \arccos (\nicefrac{1}{x})) & \text{if}\ l \geq d
    \end{cases}
  \]
  A plot of this function can be found in Figure~\ref{fig:buffonplot}.
\<close>

locale Buffon =
  fixes d l :: real
  assumes d: "d > 0" and l: "l > 0"
begin

definition Buffon :: "(real \<times> real) measure" where
  "Buffon = uniform_measure lborel ({-d/2..d/2} \<times> {-pi..pi})"

lemma space_Buffon [simp]: "space Buffon = UNIV"
  by (simp add: Buffon_def)

definition Buffon_set :: "(real \<times> real) set" where
  "Buffon_set = {(x,\<phi>) \<in> {-d/2..d/2} \<times> {-pi..pi}. needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}}"

subsection \<open>Derivation of the solution\<close>

text \<open>
  The following form is a bit easier to handle.
\<close>
lemma Buffon_set_altdef1:
  "Buffon_set =
     {(x,\<phi>) \<in> {-d/2..d/2} \<times> {-pi..pi}.
         let a = x - l / 2 * sin \<phi>; b = x + l / 2 * sin \<phi>
         in  min a b + d/2 \<le> 0 \<and> max a b + d/2 \<ge> 0 \<or> min a b - d/2 \<le> 0 \<and> max a b - d/2 \<ge> 0}"
proof -
  have "(\<lambda>(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}) =
      (\<lambda>(x,\<phi>). let a = x - l / 2 * sin \<phi>; b = x + l / 2 * sin \<phi>
               in  -d/2 \<ge> min a b \<and> -d/2 \<le> max a b \<or> min a b \<le> d/2 \<and> max a b \<ge> d/2)"
    by (auto simp: needle_def Let_def closed_segment_eq_real_ivl min_def max_def)
  also have "\<dots> =
    (\<lambda>(x,\<phi>). let a = x - l / 2 * sin \<phi>; b = x + l / 2 * sin \<phi>
             in  min a b + d/2 \<le> 0 \<and> max a b + d/2 \<ge> 0 \<or> min a b - d/2 \<le> 0 \<and> max a b - d/2 \<ge> 0)"
    by (auto simp add: algebra_simps Let_def)
  finally show ?thesis unfolding Buffon_set_def case_prod_unfold
    by (intro Collect_cong conj_cong refl) meson
qed

lemma Buffon_set_altdef2:
  "Buffon_set = {(x,\<phi>) \<in> {-d/2..d/2} \<times> {-pi..pi}. abs x \<ge> d / 2 - abs (sin \<phi>) * l / 2}"
  unfolding Buffon_set_altdef1
proof (intro Collect_cong prod.case_cong refl conj_cong)
  fix x \<phi>
  assume *: "(x, \<phi>) \<in> {-d/2..d/2} \<times> {-pi..pi}"
  let ?P = "\<lambda>x \<phi>. let a = x - l / 2 * sin \<phi>; b = x + l / 2 * sin \<phi>
               in  min a b + d/2 \<le> 0 \<and> max a b + d/2 \<ge> 0 \<or> min a b - d/2 \<le> 0 \<and> max a b - d/2 \<ge> 0"

  show "?P x \<phi> \<longleftrightarrow> (d / 2 - \<bar>sin \<phi>\<bar> * l / 2 \<le> \<bar>x\<bar>)"
  proof (cases "\<phi> \<ge> 0")
    case True
    have "x - l / 2 * sin \<phi> \<le> x + l / 2 * sin \<phi>" using l True *
      by (auto simp: sin_ge_zero)
    moreover from True and * have "sin \<phi> \<ge> 0" by (auto simp: sin_ge_zero)
    ultimately show ?thesis using * True
      by (force simp: field_simps Let_def min_def max_def case_prod_unfold abs_if)
  next
    case False
    with * have "x - l / 2 * sin \<phi> \<ge> x + l / 2 * sin \<phi>" using l
      by (auto simp: sin_le_zero' mult_nonneg_nonpos)
    moreover from False and * have "sin \<phi> \<le> 0" by (auto simp: sin_le_zero')
    ultimately show ?thesis using * False l d
      by (force simp: field_simps Let_def min_def max_def case_prod_unfold abs_if)
  qed
qed

text \<open>
  By using the symmetry inherent in the problem, we can reduce the problem to the following
  set, which corresponds to one quadrant of the original set:
\<close>
definition Buffon_set' :: "(real \<times> real) set" where
  "Buffon_set' = {(x,\<phi>) \<in> {0..d/2} \<times> {0..pi}. x \<ge> d / 2 - sin \<phi> * l / 2}"

lemma closed_buffon_set [simp, intro, measurable]: "closed Buffon_set"
  proof -
  have "Buffon_set = ({-d/2..d/2} \<times> {-pi..pi}) \<inter>
          (\<lambda>z. abs (fst z) + abs (sin (snd z)) * l / 2 - d / 2) -` {0..}"
    (is "_ = ?A") unfolding Buffon_set_altdef2 by auto
  also have "closed \<dots>"
    by (intro closed_Int closed_vimage closed_Times) (auto intro!: continuous_intros)
  finally show ?thesis by simp
qed

lemma closed_buffon_set' [simp, intro, measurable]: "closed Buffon_set'"
proof -
  have "Buffon_set' = ({0..d/2} \<times> {0..pi}) \<inter>
          (\<lambda>z. fst z + sin (snd z) * l / 2 - d / 2) -` {0..}"
    (is "_ = ?A") unfolding Buffon_set'_def by auto
  also have "closed \<dots>"
    by (intro closed_Int closed_vimage closed_Times) (auto intro!: continuous_intros)
  finally show ?thesis by simp
qed

lemma measurable_buffon_set [measurable]: "Buffon_set \<in> sets borel"
  by measurable

lemma measurable_buffon_set' [measurable]: "Buffon_set' \<in> sets borel"
  by measurable

sublocale prob_space Buffon
  unfolding Buffon_def
proof -
  have "emeasure lborel ({- d / 2..d / 2} \<times> {- pi..pi}) = ennreal (2 * d * pi)"
    unfolding lborel_prod [symmetric] using d
    by (subst lborel.emeasure_pair_measure_Times)
       (auto simp: ennreal_mult mult_ac simp flip: ennreal_numeral)
  also have "\<dots> \<noteq> 0 \<and> \<dots> \<noteq> \<infinity>"
    using d by auto
  finally show "prob_space (uniform_measure lborel ({- d / 2..d / 2} \<times> {- pi..pi}))"
    by (intro prob_space_uniform_measure) auto
qed

lemma buffon_prob_aux:
  "emeasure Buffon {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} =
     emeasure lborel Buffon_set / ennreal (2 * d * pi)"
proof -
  have [measurable]: "A \<times> B \<in> sets borel" if "A \<in> sets borel" "B \<in> sets borel"
    for A B :: "real set" using that unfolding borel_prod [symmetric] by simp
  have "{(x, \<phi>). needle l x \<phi> \<inter> {- d / 2, d / 2} \<noteq> {}} \<in> sets borel"
    by (intro pred_Collect_borel)
       (simp add: borel_prod [symmetric] needle_def closed_segment_eq_real_ivl case_prod_unfold)
  hence "emeasure Buffon {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} =
           emeasure lborel (({-d/2..d/2} \<times> {- pi..pi}) \<inter> {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}}) /
           emeasure lborel ({-(d/2)..d/2} \<times> {-pi..pi})"
    unfolding Buffon_def Buffon_set_def by (subst emeasure_uniform_measure) simp_all
  also have "({-d/2..d/2} \<times> {- pi..pi}) \<inter> {(x, \<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} = Buffon_set"
    unfolding Buffon_set_def by auto
  also have "emeasure lborel ({-(d/2)..d/2} \<times> {-pi..pi}) = ennreal (2 * d * pi)"
    using d by (simp flip: lborel_prod ennreal_mult add: lborel.emeasure_pair_measure_Times)
  finally show ?thesis .
qed

lemma emeasure_buffon_set_conv_buffon_set':
  "emeasure lborel Buffon_set = 4 * emeasure lborel Buffon_set'"
proof -
  have distr_lborel [simp]: "distr M lborel f = distr M borel f" for M and f :: "real \<Rightarrow> real"
    by (rule distr_cong) simp_all

  define A where "A = Buffon_set'"
  define B C D where "B = (\<lambda>x. (-fst x, snd x)) -` A" and "C = (\<lambda>x. (fst x, -snd x)) -` A" and
      "D = (\<lambda>x. (-fst x, -snd x)) -` A"
  have meas [measurable]:
     "(\<lambda>x::real \<times> real. (-fst x, snd x)) \<in> borel_measurable borel"
     "(\<lambda>x::real \<times> real. (fst x, -snd x)) \<in> borel_measurable borel"
     "(\<lambda>x::real \<times> real. (-fst x, -snd x)) \<in> borel_measurable borel"
    unfolding borel_prod [symmetric] by measurable
  have meas' [measurable]: "A \<in> sets borel" "B \<in> sets borel" "C \<in> sets borel" "D \<in> sets borel"
    unfolding A_def B_def C_def D_def by (rule measurable_buffon_set' measurable_sets_borel meas)+

  have *: "Buffon_set = A \<union> B \<union> C \<union> D"
  proof (intro equalityI subsetI, goal_cases)
    case (1 z)
    show ?case
    proof (cases "fst z \<ge> 0"; cases "snd z \<ge> 0")
      assume "fst z \<ge> 0" "snd z \<ge> 0"
      with 1 have "z \<in> A"
        by (auto split: prod.splits simp: Buffon_set_altdef2 Buffon_set'_def sin_ge_zero A_def B_def)
      thus ?thesis by blast
    next
      assume "\<not>(fst z \<ge> 0)" "snd z \<ge> 0"
      with 1 have "z \<in> B"
        by (auto split: prod.splits simp: Buffon_set_altdef2 Buffon_set'_def sin_ge_zero A_def B_def)
      thus ?thesis by blast
    next
      assume "fst z \<ge> 0" "\<not>(snd z \<ge> 0)"
      with 1 have "z \<in> C"
        by (auto split: prod.splits simp: Buffon_set_altdef2 Buffon_set'_def sin_le_zero' A_def B_def C_def)
      thus ?thesis by blast
    next
      assume "\<not>(fst z \<ge> 0)" "\<not>(snd z \<ge> 0)"
      with 1 have "z \<in> D"
        by (auto split: prod.splits simp: Buffon_set_altdef2 Buffon_set'_def sin_le_zero' A_def B_def D_def)
      thus ?thesis by blast
    qed
  next
    case (2 z)
    thus ?case using d l
      by (auto simp: Buffon_set_altdef2 Buffon_set'_def sin_ge_zero sin_le_zero'  A_def B_def C_def D_def)
  qed

  have "A \<inter> B = {0} \<times> ({0..pi} \<inter> {\<phi>. sin \<phi> * l - d \<ge> 0})"
    using d l by (auto simp: Buffon_set'_def  A_def B_def C_def D_def)
  moreover have "emeasure lborel \<dots> = 0"
    unfolding lborel_prod [symmetric] by (subst lborel.emeasure_pair_measure_Times) simp_all
  ultimately have AB: "(A \<inter> B) \<in> null_sets lborel"
    unfolding lborel_prod [symmetric] by (simp add: null_sets_def)

  have "C \<inter> D = {0} \<times> ({-pi..0} \<inter> {\<phi>. -sin \<phi> * l - d \<ge> 0})"
    using d l by (auto simp: Buffon_set'_def  A_def B_def C_def D_def)
  moreover have "emeasure lborel \<dots> = 0"
    unfolding lborel_prod [symmetric] by (subst lborel.emeasure_pair_measure_Times) simp_all
  ultimately have CD: "(C \<inter> D) \<in> null_sets lborel"
    unfolding lborel_prod [symmetric] by (simp add: null_sets_def)

  have "A \<inter> D = {}" "B \<inter> C = {}" using d l
    by (auto simp: Buffon_set'_def A_def D_def B_def C_def)
  moreover have "A \<inter> C = {(d/2, 0)}" "B \<inter> D = {(-d/2, 0)}"
    using d l by (auto simp: case_prod_unfold Buffon_set'_def A_def B_def C_def D_def)
  ultimately have AD: "A \<inter> D \<in> null_sets lborel" and BC: "B \<inter> C \<in> null_sets lborel" and
    AC: "A \<inter> C \<in> null_sets lborel" and BD: "B \<inter> D \<in> null_sets lborel" by auto

  note *
  also have "emeasure lborel (A \<union> B \<union> C \<union> D) = emeasure lborel (A \<union> B \<union> C) + emeasure lborel D"
    using AB AC AD BC BD CD by (intro emeasure_Un') (auto simp: Int_Un_distrib2)
  also have "emeasure lborel (A \<union> B \<union> C) = emeasure lborel (A \<union> B) + emeasure lborel C"
    using AB AC BC using AB AC AD BC BD CD by (intro emeasure_Un') (auto simp: Int_Un_distrib2)
  also have "emeasure lborel (A \<union> B) = emeasure lborel A + emeasure lborel B"
    using AB using AB AC AD BC BD CD by (intro emeasure_Un') (auto simp: Int_Un_distrib2)
  also have "emeasure lborel B = emeasure (distr lborel lborel (\<lambda>(x,y). (-x, y))) A"
    (is "_ = emeasure ?M _") unfolding B_def
    by (subst emeasure_distr) (simp_all add: case_prod_unfold)
  also have "?M = lborel" unfolding lborel_prod [symmetric]
    by (subst pair_measure_distr [symmetric]) (simp_all add: sigma_finite_lborel lborel_distr_uminus)
  also have "emeasure lborel C = emeasure (distr lborel lborel (\<lambda>(x,y). (x, -y))) A"
    (is "_ = emeasure ?M _") unfolding C_def
    by (subst emeasure_distr) (simp_all add: case_prod_unfold)
  also have "?M = lborel" unfolding lborel_prod [symmetric]
    by (subst pair_measure_distr [symmetric]) (simp_all add: sigma_finite_lborel lborel_distr_uminus)
  also have "emeasure lborel D = emeasure (distr lborel lborel (\<lambda>(x,y). (-x, -y))) A"
    (is "_ = emeasure ?M _") unfolding D_def
    by (subst emeasure_distr) (simp_all add: case_prod_unfold)
  also have "?M = lborel" unfolding lborel_prod [symmetric]
    by (subst pair_measure_distr [symmetric]) (simp_all add: sigma_finite_lborel lborel_distr_uminus)
  finally have "emeasure lborel Buffon_set =
                  of_nat (Suc (Suc (Suc (Suc 0)))) * emeasure lborel A"
    unfolding of_nat_Suc ring_distribs by simp
  also have "of_nat (Suc (Suc (Suc (Suc 0)))) = (4 :: ennreal)" by simp
  finally show ?thesis unfolding A_def .
qed

text \<open>
  It only remains now to compute the measure of @{const Buffon_set'}. We first reduce this
  problem to a relatively simple integral:
\<close>
lemma emeasure_buffon_set':
  "emeasure lborel Buffon_set' =
     ennreal (integral {0..pi} (\<lambda>x. min (d / 2) (sin x * l / 2)))"
  (is "emeasure lborel ?A = _")
proof -
  have "emeasure lborel ?A = nn_integral lborel (\<lambda>x. indicator ?A x)"
    by (intro nn_integral_indicator [symmetric]) simp_all
  also have "(lborel :: (real \<times> real) measure) = lborel \<Otimes>\<^sub>M lborel"
    by (simp only: lborel_prod)
  also have "nn_integral \<dots> (indicator ?A) = (\<integral>\<^sup>+\<phi>. \<integral>\<^sup>+x. indicator ?A (x, \<phi>) \<partial>lborel \<partial>lborel)"
    by (subst lborel_pair.nn_integral_snd [symmetric]) (simp_all add: lborel_prod borel_prod)
  also have "\<dots> = (\<integral>\<^sup>+\<phi>. \<integral>\<^sup>+x. indicator {0..pi} \<phi> * indicator {max 0 (d/2 - sin \<phi> * l / 2) .. d/2} x \<partial>lborel \<partial>lborel)"
    using d l by (intro nn_integral_cong) (auto simp: indicator_def field_simps Buffon_set'_def)
  also have "\<dots> = \<integral>\<^sup>+ \<phi>. indicator {0..pi} \<phi> * emeasure lborel {max 0 (d / 2 - sin \<phi> * l / 2)..d / 2} \<partial>lborel"
    by (subst nn_integral_cmult) simp_all
  also have "\<dots> = \<integral>\<^sup>+ \<phi>. ennreal (indicator {0..pi} \<phi> * min (d / 2) (sin \<phi> * l / 2)) \<partial>lborel"
    (is "_ = ?I") using d l by (intro nn_integral_cong) (auto simp: indicator_def sin_ge_zero max_def min_def)
  also have "integrable lborel (\<lambda>\<phi>. (d / 2) * indicator {0..pi} \<phi>)" by simp
  hence int: "integrable lborel (\<lambda>\<phi>. indicator {0..pi} \<phi> * min (d / 2) (sin \<phi> * l / 2))"
    by (rule Bochner_Integration.integrable_bound)
       (insert l d, auto intro!: AE_I2 simp: indicator_def min_def sin_ge_zero)
  hence "?I = set_lebesgue_integral lborel {0..pi} (\<lambda>\<phi>. min (d / 2) (sin \<phi> * l / 2))"
    by (subst nn_integral_eq_integral, assumption)
       (insert d l, auto intro!: AE_I2 simp: sin_ge_zero min_def indicator_def set_lebesgue_integral_def)
  also have "\<dots> = ennreal (integral {0..pi} (\<lambda>x. min (d / 2) (sin x * l / 2)))"
    (is "_ = ennreal ?I") using int by (subst set_borel_integral_eq_integral) (simp_all add: set_integrable_def)
  finally show ?thesis by (simp add: lborel_prod)
qed

text \<open>
  We now have to distinguish two cases: The first and easier one is that where the length
  of the needle, $l$, is less than or equal to the strip width, $d$:
\<close>
context
  assumes l_le_d: "l \<le> d"
begin

lemma emeasure_buffon_set'_short: "emeasure lborel Buffon_set' = ennreal l"
proof -
  have "emeasure lborel Buffon_set' =
          ennreal (integral {0..pi} (\<lambda>x. min (d / 2) (sin x * l / 2)))" (is "_ = ennreal ?I")
    by (rule emeasure_buffon_set')
  also have *: "sin \<phi> * l \<le> d" if "\<phi> \<ge> 0" "\<phi> \<le> pi" for \<phi>
    using mult_mono[OF l_le_d sin_le_one _ sin_ge_zero] that d by (simp add: algebra_simps)
  have "?I = integral {0..pi} (\<lambda>x. (l / 2) * sin x)"
    using l d l_le_d
    by (intro integral_cong) (auto dest: * simp: min_def sin_ge_zero)
  also have "\<dots> = l / 2 * integral {0..pi} sin" by simp
  also have "(sin has_integral (-cos pi - (- cos 0))) {0..pi}"
    by (intro fundamental_theorem_of_calculus)
       (auto intro!: derivative_eq_intros simp: has_field_derivative_iff_has_vector_derivative [symmetric])
  hence "integral {0..pi} sin = -cos pi - (-cos 0)"
    by (simp add: has_integral_iff)
  finally show ?thesis by (simp add: lborel_prod)
qed

lemma emeasure_buffon_set_short: "emeasure lborel Buffon_set = 4 * ennreal l"
  by (simp add: emeasure_buffon_set_conv_buffon_set' emeasure_buffon_set'_short l_le_d)

lemma prob_short_aux:
  "Buffon {(x, \<phi>). needle l x \<phi> \<inter> {- d / 2, d / 2} \<noteq> {}} = ennreal (2 * l / (d * pi))"
  unfolding buffon_prob_aux emeasure_buffon_set_short using d l
  by (simp flip: ennreal_mult ennreal_numeral add: divide_ennreal)

lemma prob_short: "\<P>((x,\<phi>) in Buffon. needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}) = 2 * l / (d * pi)"
  using prob_short_aux unfolding emeasure_eq_measure
  using l d by (subst (asm) ennreal_inj) auto

end

text \<open>
  The other case where the needle is at least as long as the strip width is more complicated:
\<close>
context
  assumes l_ge_d: "l \<ge> d"
begin

lemma emeasure_buffon_set'_long:
  shows "l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d \<ge> 0"
  and   "emeasure lborel Buffon_set' =
           ennreal (l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d)"
proof -
  define \<phi>' where "\<phi>' = arcsin (d / l)"
  have \<phi>'_nonneg: "\<phi>' \<ge> 0" unfolding \<phi>'_def using d l l_ge_d arcsin_le_mono[of 0 "d/l"]
    by (simp add: \<phi>'_def)
  have \<phi>'_le: "\<phi>' \<le> pi / 2" unfolding \<phi>'_def using arcsin_bounded[of "d/l"] d l l_ge_d
    by (simp add: field_simps)
  have ge_phi': "sin \<phi> \<ge> d / l" if "\<phi> \<ge> \<phi>'" "\<phi> \<le> pi / 2" for \<phi>
    using arcsin_le_iff[of "d / l" "\<phi>"] d l_ge_d that \<phi>'_nonneg by (auto simp: \<phi>'_def field_simps)
  have le_phi': "sin \<phi> \<le> d / l" if "\<phi> \<le> \<phi>'" "\<phi> \<ge> 0" for \<phi>
    using le_arcsin_iff[of "d / l" "\<phi>"] d l_ge_d that \<phi>'_le by (auto simp: \<phi>'_def field_simps)
  have "cos \<phi>' = sqrt (1 - (d / l)^2)"
    unfolding \<phi>'_def by (rule cos_arcsin) (insert d l l_ge_d, auto simp: field_simps)

  have "l * (1 - cos \<phi>') + arccos (d / l) * d \<ge> 0"
    using l d l_ge_d
    by (intro add_nonneg_nonneg mult_nonneg_nonneg arccos_lbound) (auto simp: field_simps)
  thus "l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d \<ge> 0"
    by (simp add: \<open>cos \<phi>' = sqrt (1 - (d / l)^2)\<close>)

  let ?f = "(\<lambda>x. min (d / 2) (sin x * l / 2))"
  have "emeasure lborel Buffon_set' = ennreal (integral {0..pi} ?f)" (is "_ = ennreal ?I")
    by (rule emeasure_buffon_set')
  also have "?I = integral {0..pi/2} ?f + integral {pi/2..pi} ?f"
    by (rule Henstock_Kurzweil_Integration.integral_combine [symmetric]) (auto intro!: integrable_continuous_real continuous_intros)
  also have "integral {pi/2..pi} ?f = integral {-pi/2..0} (?f \<circ> (\<lambda>\<phi>. \<phi> + pi))"
    by (subst integral_shift) (auto intro!: continuous_intros)
  also have "\<dots> = integral {-(pi/2)..-0} (\<lambda>x. min (d / 2) (sin (-x) * l / 2))" by (simp add: o_def)
  also have "\<dots> = integral {0..pi/2} ?f" (is "_ = ?I") by (subst Henstock_Kurzweil_Integration.integral_reflect_real) simp_all
  also have "\<dots> + \<dots> = 2 * \<dots>" by simp
  also have "?I = integral {0..\<phi>'} ?f + integral {\<phi>'..pi/2} ?f"
    using l d l_ge_d \<phi>'_nonneg \<phi>'_le
    by (intro Henstock_Kurzweil_Integration.integral_combine [symmetric]) (auto intro!: integrable_continuous_real continuous_intros)
  also have "integral {0..\<phi>'} ?f = integral {0..\<phi>'} (\<lambda>x. l / 2 * sin x)"
    using l by (intro integral_cong) (auto simp: min_def field_simps dest: le_phi')
  also have "((\<lambda>x. l / 2 * sin x) has_integral (- (l / 2 * cos \<phi>') - (- (l / 2 * cos 0)))) {0..\<phi>'}"
    using \<phi>'_nonneg
    by (intro fundamental_theorem_of_calculus)
       (auto simp: has_field_derivative_iff_has_vector_derivative [symmetric] intro!: derivative_eq_intros)
  hence "integral {0..\<phi>'} (\<lambda>x. l / 2 * sin x) = (1 - cos \<phi>') * l / 2"
    by (simp add: has_integral_iff algebra_simps)
  also have "integral {\<phi>'..pi/2} ?f = integral {\<phi>'..pi/2} (\<lambda>_. d / 2)"
    using l by (intro integral_cong) (auto simp: min_def field_simps dest: ge_phi')
  also have "\<dots> = arccos (d / l) * d / 2" using \<phi>'_le d l l_ge_d
    by (subst arccos_arcsin_eq) (auto simp: field_simps \<phi>'_def)
  also note \<open>cos \<phi>' = sqrt (1 - (d / l)^2)\<close>
  also have "2 * ((1 - sqrt (1 - (d / l)\<^sup>2)) * l / 2 + arccos (d / l) * d / 2) =
               l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d"
    using d l by (simp add: field_simps)
  finally show "emeasure lborel Buffon_set' =
                  ennreal (l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d)" .
qed

lemma emeasure_set_long: "emeasure lborel Buffon_set =
        4 * ennreal (l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d)"
  by (simp add: emeasure_buffon_set_conv_buffon_set' emeasure_buffon_set'_long l_ge_d)

lemma prob_long_aux:
  shows "2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l)) \<ge> 0"
  and   "Buffon {(x, \<phi>). needle l x \<phi> \<inter> {- d / 2, d / 2} \<noteq> {}} =
           ennreal (2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l)))"
  using emeasure_buffon_set'_long(1)
proof -
  have *: "l * sqrt ((l\<^sup>2 - d\<^sup>2) / l\<^sup>2) + 0 \<le> l + d * arccos (d / l)"
    using d l_ge_d by (intro add_mono mult_nonneg_nonneg arccos_lbound) (auto simp: field_simps)

  have "l / d \<ge> sqrt ((l / d)\<^sup>2 - 1)"
    using l d l_ge_d by (intro real_le_lsqrt) (auto simp: field_simps)
  thus "2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l)) \<ge> 0"
    using d l l_ge_d
    by (intro mult_nonneg_nonneg add_nonneg_nonneg arccos_lbound) (auto simp: field_simps)

  have "emeasure Buffon {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} =
          ennreal (4 * (l - l * sqrt (1 - (d / l)\<^sup>2) + arccos (d / l) * d)) / ennreal (2 * d * pi)"
    using d l l_ge_d * unfolding buffon_prob_aux emeasure_set_long ennreal_numeral [symmetric]
    by (subst ennreal_mult [symmetric])
       (auto intro!: add_nonneg_nonneg mult_nonneg_nonneg simp: field_simps)
  also have "\<dots> = ennreal ((4 * (l - l * sqrt (1 - (d / l)\<^sup>2) + arccos (d / l) * d)) / (2 * d * pi))"
    using d l * by (subst divide_ennreal) (auto simp: field_simps)
  also have "(4 * (l - l * sqrt (1 - (d / l)\<^sup>2) + arccos (d / l) * d)) / (2 * d * pi) =
               2 / pi * (l / d - l / d * sqrt ((d / l)^2 * ((l / d)^2 - 1)) + arccos (d / l))"
    using d l by (simp add: field_simps)
  also have "l / d * sqrt ((d / l)^2 * ((l / d)^2 - 1)) = sqrt ((l / d) ^ 2 - 1)"
    using d l l_ge_d unfolding real_sqrt_mult real_sqrt_abs by simp
  finally show "emeasure Buffon {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} =
                  ennreal (2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l)))" .
qed

lemma prob_long:
  "\<P>((x,\<phi>) in Buffon. needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}) =
     2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l))"
  using prob_long_aux unfolding emeasure_eq_measure
  by (subst (asm) ennreal_inj) simp_all

end

theorem prob_eq:
  defines "x \<equiv> l / d"
  shows   "\<P>((x,\<phi>) in Buffon. needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}) =
             (if l \<le> d then
                2 / pi * x
              else
                2 / pi * (x - sqrt (x\<^sup>2 - 1) + arccos (1 / x)))"
  using prob_short prob_long unfolding x_def by auto

end

end


theory E2_7
  imports Main
begin

datatype 'a tree = Leaf 'a | Node "'a tree" 'a "'a tree"

fun mirror :: "'a tree \<Rightarrow> 'a tree" where
  "mirror (Leaf v) = Leaf v" |
  "mirror (Node l v r) = Node (mirror r) v (mirror l)"

fun pre_order :: "'a tree \<Rightarrow> 'a list" where
  "pre_order (Leaf v) = [v]" |
  "pre_order (Node l v r) = v # (pre_order l) @ (pre_order r)"

fun post_order :: "'a tree \<Rightarrow> 'a list" where
  "post_order (Leaf v) = [v]" |
  "post_order (Node l v r) = (post_order l) @ (post_order r) @ [v]"

value "pre_order (mirror (Node (Leaf 1) (2::nat) (Node (Leaf 3) 4 (Node (Leaf 5) 6 (Leaf 7)))))"
value "rev (post_order (Node (Leaf 1) (2::nat) (Node (Leaf 3) 4 (Node (Leaf 5) 6 (Leaf 7)))))"

lemma "pre_order (mirror t) = rev (post_order t)"
  apply(induction t)
  apply(auto)
  done

(*
datatype 'a tree = Til | Node "'a tree" 'a "'a tree"

fun mirror :: "'a tree \<Rightarrow> 'a tree" where
  "mirror Til = Til" |
  "mirror (Node l v r) = Node (mirror r) v (mirror l)"

fun pre_order :: "'a tree \<Rightarrow> 'a list" where
  "pre_order Til = []" |
  "pre_order (Node l v r) = v # (pre_order l) @ (pre_order r)"

fun post_order :: "'a tree \<Rightarrow> 'a list" where
  "post_order Til = []" |
  "post_order (Node l v r) = (post_order l) @ (post_order r) @ [v]"

value "pre_order (mirror (Node Til (1::nat) (Node Til 2 (Node Til 3 Til))))"
value "rev (post_order (Node Til (1::nat) (Node Til 2 (Node Til 3 Til))))"

lemma "pre_order (mirror t) = rev (post_order t)"
  apply(induction t)
  apply(auto)
  done
*)

end