(*  Author: John Harrison and Valentina Bruno
    Ported from "hol_light/Multivariate/complexes.ml" by L C Paulson
*)

section \<open>polynomial functions: extremal behaviour and root counts\<close>

theory Poly_Roots
imports Complex_Main
begin

subsection\<open>Geometric progressions\<close>

lemma sum_gp_basic:
  fixes x :: "'a::{comm_ring,monoid_mult}"
  shows "(1 - x) * (\<Sum>i\<le>n. x^i) = 1 - x^Suc n"
  by (simp only: one_diff_power_eq [of "Suc n" x] lessThan_Suc_atMost)

lemma sum_gp0:
  fixes x :: "'a::{comm_ring,division_ring}"
  shows   "(\<Sum>i\<le>n. x^i) = (if x = 1 then of_nat(n + 1) else (1 - x^Suc n) / (1 - x))"
  using sum_gp_basic[of x n]
  by (simp add: mult.commute divide_simps)

lemma sum_power_add:
  fixes x :: "'a::{comm_ring,monoid_mult}"
  shows "(\<Sum>i\<in>I. x^(m+i)) = x^m * (\<Sum>i\<in>I. x^i)"
  by (simp add: sum_distrib_left power_add)

lemma sum_power_shift:
  fixes x :: "'a::{comm_ring,monoid_mult}"
  assumes "m \<le> n"
  shows "(\<Sum>i=m..n. x^i) = x^m * (\<Sum>i\<le>n-m. x^i)"
proof -
  have "(\<Sum>i=m..n. x^i) = x^m * (\<Sum>i=m..n. x^(i-m))"
    by (simp add: sum_distrib_left power_add [symmetric])
  also have "(\<Sum>i=m..n. x^(i-m)) = (\<Sum>i\<le>n-m. x^i)"
    using \<open>m \<le> n\<close> by (intro sum.reindex_bij_witness[where j="\<lambda>i. i - m" and i="\<lambda>i. i + m"]) auto
  finally show ?thesis .
qed

lemma sum_gp_multiplied:
  fixes x :: "'a::{comm_ring,monoid_mult}"
  assumes "m \<le> n"
  shows "(1 - x) * (\<Sum>i=m..n. x^i) = x^m - x^Suc n"
proof -
  have  "(1 - x) * (\<Sum>i=m..n. x^i) = x^m * (1 - x) * (\<Sum>i\<le>n-m. x^i)"
    by (metis mult.assoc mult.commute assms sum_power_shift)
  also have "... =x^m * (1 - x^Suc(n-m))"
    by (metis mult.assoc sum_gp_basic)
  also have "... = x^m - x^Suc n"
    using assms
    by (simp add: algebra_simps) (metis le_add_diff_inverse power_add)
  finally show ?thesis .
qed

lemma sum_gp:
  fixes x :: "'a::{comm_ring,division_ring}"
  shows   "(\<Sum>i=m..n. x^i) =
               (if n < m then 0
                else if x = 1 then of_nat((n + 1) - m)
                else (x^m - x^Suc n) / (1 - x))"
using sum_gp_multiplied [of m n x]
apply auto
by (metis eq_iff_diff_eq_0 mult.commute nonzero_divide_eq_eq)

lemma sum_gp_offset:
  fixes x :: "'a::{comm_ring,division_ring}"
  shows   "(\<Sum>i=m..m+n. x^i) =
       (if x = 1 then of_nat n + 1 else x^m * (1 - x^Suc n) / (1 - x))"
  using sum_gp [of x m "m+n"]
  by (auto simp: power_add algebra_simps)

lemma sum_gp_strict:
  fixes x :: "'a::{comm_ring,division_ring}"
  shows "(\<Sum>i<n. x^i) = (if x = 1 then of_nat n else (1 - x^n) / (1 - x))"
  by (induct n) (auto simp: algebra_simps divide_simps)

subsection\<open>Basics about polynomial functions: extremal behaviour and root counts.\<close>

lemma sub_polyfun:
  fixes x :: "'a::{comm_ring,monoid_mult}"
  shows   "(\<Sum>i\<le>n. a i * x^i) - (\<Sum>i\<le>n. a i * y^i) =
           (x - y) * (\<Sum>j<n. \<Sum>k= Suc j..n. a k * y^(k - Suc j) * x^j)"
proof -
  have "(\<Sum>i\<le>n. a i * x^i) - (\<Sum>i\<le>n. a i * y^i) =
        (\<Sum>i\<le>n. a i * (x^i - y^i))"
    by (simp add: algebra_simps sum_subtractf [symmetric])
  also have "... = (\<Sum>i\<le>n. a i * (x - y) * (\<Sum>j<i. y^(i - Suc j) * x^j))"
    by (simp add: power_diff_sumr2 ac_simps)
  also have "... = (x - y) * (\<Sum>i\<le>n. (\<Sum>j<i. a i * y^(i - Suc j) * x^j))"
    by (simp add: sum_distrib_left ac_simps)
  also have "... = (x - y) * (\<Sum>j<n. (\<Sum>i=Suc j..n. a i * y^(i - Suc j) * x^j))"
    by (simp add: nested_sum_swap')
  finally show ?thesis .
qed

lemma sub_polyfun_alt:
  fixes x :: "'a::{comm_ring,monoid_mult}"
  shows   "(\<Sum>i\<le>n. a i * x^i) - (\<Sum>i\<le>n. a i * y^i) =
           (x - y) * (\<Sum>j<n. \<Sum>k<n-j. a (j+k+1) * y^k * x^j)"
proof -
  { fix j
    have "(\<Sum>k = Suc j..n. a k * y^(k - Suc j) * x^j) =
          (\<Sum>k <n - j. a (Suc (j + k)) * y^k * x^j)"
      by (rule sum.reindex_bij_witness[where i="\<lambda>i. i + Suc j" and j="\<lambda>i. i - Suc j"]) auto }
  then show ?thesis
    by (simp add: sub_polyfun)
qed

lemma polyfun_linear_factor:
  fixes a :: "'a::{comm_ring,monoid_mult}"
  shows  "\<exists>b. \<forall>z. (\<Sum>i\<le>n. c i * z^i) =
                  (z-a) * (\<Sum>i<n. b i * z^i) + (\<Sum>i\<le>n. c i * a^i)"
proof -
  { fix z
    have "(\<Sum>i\<le>n. c i * z^i) - (\<Sum>i\<le>n. c i * a^i) =
          (z - a) * (\<Sum>j<n. (\<Sum>k = Suc j..n. c k * a^(k - Suc j)) * z^j)"
      by (simp add: sub_polyfun sum_distrib_right)
    then have "(\<Sum>i\<le>n. c i * z^i) =
          (z - a) * (\<Sum>j<n. (\<Sum>k = Suc j..n. c k * a^(k - Suc j)) * z^j)
          + (\<Sum>i\<le>n. c i * a^i)"
      by (simp add: algebra_simps) }
  then show ?thesis
    by (intro exI allI)
qed

lemma polyfun_linear_factor_root:
  fixes a :: "'a::{comm_ring,monoid_mult}"
  assumes "(\<Sum>i\<le>n. c i * a^i) = 0"
  shows  "\<exists>b. \<forall>z. (\<Sum>i\<le>n. c i * z^i) = (z-a) * (\<Sum>i<n. b i * z^i)"
  using polyfun_linear_factor [of c n a] assms
  by simp

lemma adhoc_norm_triangle: "a + norm(y) \<le> b ==> norm(x) \<le> a ==> norm(x + y) \<le> b"
  by (metis norm_triangle_mono order.trans order_refl)

lemma polyfun_extremal_lemma:
  fixes c :: "nat \<Rightarrow> 'a::real_normed_div_algebra"
  assumes "e > 0"
    shows "\<exists>M. \<forall>z. M \<le> norm z \<longrightarrow> norm(\<Sum>i\<le>n. c i * z^i) \<le> e * norm(z) ^ Suc n"
proof (induction n)
  case 0
  show ?case
    by (rule exI [where x="norm (c 0) / e"]) (auto simp: mult.commute pos_divide_le_eq assms)
next
  case (Suc n)
  then obtain M where M: "\<forall>z. M \<le> norm z \<longrightarrow> norm (\<Sum>i\<le>n. c i * z^i) \<le> e * norm z ^ Suc n" ..
  show ?case
  proof (rule exI [where x="max 1 (max M ((e + norm(c(Suc n))) / e))"], clarify)
    fix z::'a
    assume "max 1 (max M ((e + norm (c (Suc n))) / e)) \<le> norm z"
    then have norm1: "0 < norm z" "M \<le> norm z" "(e + norm (c (Suc n))) / e \<le> norm z"
      by auto
    then have norm2: "(e + norm (c (Suc n))) \<le> e * norm z"  "(norm z * norm z ^ n) > 0"
      apply (metis assms less_divide_eq mult.commute not_le)
      using norm1 apply (metis mult_pos_pos zero_less_power)
      done
    have "e * (norm z * norm z ^ n) + norm (c (Suc n) * (z * z ^ n)) =
          (e + norm (c (Suc n))) * (norm z * norm z ^ n)"
      by (simp add: norm_mult norm_power algebra_simps)
    also have "... \<le> (e * norm z) * (norm z * norm z ^ n)"
      using norm2 by (metis real_mult_le_cancel_iff1)
    also have "... = e * (norm z * (norm z * norm z ^ n))"
      by (simp add: algebra_simps)
    finally have "e * (norm z * norm z ^ n) + norm (c (Suc n) * (z * z ^ n))
                  \<le> e * (norm z * (norm z * norm z ^ n))" .
    then show "norm (\<Sum>i\<le>Suc n. c i * z^i) \<le> e * norm z ^ Suc (Suc n)" using M norm1
      by (drule_tac x=z in spec) (auto simp: intro!: adhoc_norm_triangle)
    qed
qed

lemma norm_lemma_xy: assumes "\<bar>b\<bar> + 1 \<le> norm(y) - a" "norm(x) \<le> a" shows "b \<le> norm(x + y)"
proof -
  have "b \<le> norm y - norm x"
    using assms by linarith
  then show ?thesis
    by (metis (no_types) add.commute norm_diff_ineq order_trans)
qed

lemma polyfun_extremal:
  fixes c :: "nat \<Rightarrow> 'a::real_normed_div_algebra"
  assumes "\<exists>k. k \<noteq> 0 \<and> k \<le> n \<and> c k \<noteq> 0"
    shows "eventually (\<lambda>z. norm(\<Sum>i\<le>n. c i * z^i) \<ge> B) at_infinity"
using assms
proof (induction n)
  case 0 then show ?case
    by simp
next
  case (Suc n)
  show ?case
  proof (cases "c (Suc n) = 0")
    case True
    with Suc show ?thesis
      by auto (metis diff_is_0_eq diffs0_imp_equal less_Suc_eq_le not_less_eq)
  next
    case False
    with polyfun_extremal_lemma [of "norm(c (Suc n)) / 2" c n]
    obtain M where M: "\<And>z. M \<le> norm z \<Longrightarrow>
               norm (\<Sum>i\<le>n. c i * z^i) \<le> norm (c (Suc n)) / 2 * norm z ^ Suc n"
      by auto
    show ?thesis
    unfolding eventually_at_infinity
    proof (rule exI [where x="max M (max 1 ((\<bar>B\<bar> + 1) / (norm (c (Suc n)) / 2)))"], clarsimp)
      fix z::'a
      assume les: "M \<le> norm z"  "1 \<le> norm z"  "(\<bar>B\<bar> * 2 + 2) / norm (c (Suc n)) \<le> norm z"
      then have "\<bar>B\<bar> * 2 + 2 \<le> norm z * norm (c (Suc n))"
        by (metis False pos_divide_le_eq zero_less_norm_iff)
      then have "\<bar>B\<bar> * 2 + 2 \<le> norm z ^ (Suc n) * norm (c (Suc n))"
        by (metis \<open>1 \<le> norm z\<close> order.trans mult_right_mono norm_ge_zero self_le_power zero_less_Suc)
      then show "B \<le> norm ((\<Sum>i\<le>n. c i * z^i) + c (Suc n) * (z * z ^ n))" using M les
        apply auto
        apply (rule norm_lemma_xy [where a = "norm (c (Suc n)) * norm z ^ (Suc n) / 2"])
        apply (simp_all add: norm_mult norm_power)
        done
    qed
  qed
qed

lemma polyfun_rootbound:
 fixes c :: "nat \<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}"
 assumes "\<exists>k. k \<le> n \<and> c k \<noteq> 0"
   shows "finite {z. (\<Sum>i\<le>n. c i * z^i) = 0} \<and> card {z. (\<Sum>i\<le>n. c i * z^i) = 0} \<le> n"
using assms
proof (induction n arbitrary: c)
 case (Suc n) show ?case
 proof (cases "{z. (\<Sum>i\<le>Suc n. c i * z^i) = 0} = {}")
   case False
   then obtain a where a: "(\<Sum>i\<le>Suc n. c i * a^i) = 0"
     by auto
   from polyfun_linear_factor_root [OF this]
   obtain b where "\<And>z. (\<Sum>i\<le>Suc n. c i * z^i) = (z - a) * (\<Sum>i< Suc n. b i * z^i)"
     by auto
   then have b: "\<And>z. (\<Sum>i\<le>Suc n. c i * z^i) = (z - a) * (\<Sum>i\<le>n. b i * z^i)"
     by (metis lessThan_Suc_atMost)
   then have ins_ab: "{z. (\<Sum>i\<le>Suc n. c i * z^i) = 0} = insert a {z. (\<Sum>i\<le>n. b i * z^i) = 0}"
     by auto
   have c0: "c 0 = - (a * b 0)" using  b [of 0]
     by simp
   then have extr_prem: "~ (\<exists>k\<le>n. b k \<noteq> 0) \<Longrightarrow> \<exists>k. k \<noteq> 0 \<and> k \<le> Suc n \<and> c k \<noteq> 0"
     by (metis Suc.prems le0 minus_zero mult_zero_right)
   have "\<exists>k\<le>n. b k \<noteq> 0"
     apply (rule ccontr)
     using polyfun_extremal [OF extr_prem, of 1]
     apply (auto simp: eventually_at_infinity b simp del: sum_atMost_Suc)
     apply (drule_tac x="of_real ba" in spec, simp)
     done
   then show ?thesis using Suc.IH [of b] ins_ab
     by (auto simp: card_insert_if)
   qed simp
qed simp

corollary
  fixes c :: "nat \<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}"
  assumes "\<exists>k. k \<le> n \<and> c k \<noteq> 0"
    shows polyfun_rootbound_finite: "finite {z. (\<Sum>i\<le>n. c i * z^i) = 0}"
      and polyfun_rootbound_card:   "card {z. (\<Sum>i\<le>n. c i * z^i) = 0} \<le> n"
using polyfun_rootbound [OF assms] by auto

lemma polyfun_finite_roots:
  fixes c :: "nat \<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}"
    shows  "finite {z. (\<Sum>i\<le>n. c i * z^i) = 0} \<longleftrightarrow> (\<exists>k. k \<le> n \<and> c k \<noteq> 0)"
proof (cases " \<exists>k\<le>n. c k \<noteq> 0")
  case True then show ?thesis
    by (blast intro: polyfun_rootbound_finite)
next
  case False then show ?thesis
    by (auto simp: infinite_UNIV_char_0)
qed

lemma polyfun_eq_0:
  fixes c :: "nat \<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}"
    shows  "(\<forall>z. (\<Sum>i\<le>n. c i * z^i) = 0) \<longleftrightarrow> (\<forall>k. k \<le> n \<longrightarrow> c k = 0)"
proof (cases "(\<forall>z. (\<Sum>i\<le>n. c i * z^i) = 0)")
  case True
  then have "~ finite {z. (\<Sum>i\<le>n. c i * z^i) = 0}"
    by (simp add: infinite_UNIV_char_0)
  with True show ?thesis
    by (metis (poly_guards_query) polyfun_rootbound_finite)
next
  case False
  then show ?thesis
    by auto
qed

lemma polyfun_eq_const:
  fixes c :: "nat \<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}"
    shows  "(\<forall>z. (\<Sum>i\<le>n. c i * z^i) = k) \<longleftrightarrow> c 0 = k \<and> (\<forall>k. k \<noteq> 0 \<and> k \<le> n \<longrightarrow> c k = 0)"
proof -
  {fix z
    have "(\<Sum>i\<le>n. c i * z^i) = (\<Sum>i\<le>n. (if i = 0 then c 0 - k else c i) * z^i) + k"
      by (induct n) auto
  } then
  have "(\<forall>z. (\<Sum>i\<le>n. c i * z^i) = k) \<longleftrightarrow> (\<forall>z. (\<Sum>i\<le>n. (if i = 0 then c 0 - k else c i) * z^i) = 0)"
    by auto
  also have "... \<longleftrightarrow>  c 0 = k \<and> (\<forall>k. k \<noteq> 0 \<and> k \<le> n \<longrightarrow> c k = 0)"
    by (auto simp: polyfun_eq_0)
  finally show ?thesis .
qed

end


theory "slides_cours_isabelle_s_tourret"
imports Main
begin

lemma "\<not> surj(f :: 'a \<Rightarrow> 'a set)"
proof (rule notI)
  assume a : "surj f"
  (*from this have b: "\<forall>y. \<exists>x. f x = y" by blast*)
  from `surj f` have b : "\<forall>y. \<exists>x. y = f x" by (simp add: surj_def)
  from b have c : "\<exists>x. f x = {y. y \<notin> f y}" by blast
  from c show False by blast
qed

(*
lemma "(\<exists> ys zs. xs = ys @ zs \<and> length ys = length zs ) \<or>
      (\<exists> ys zs. xs = ys @ zs \<and> length ys = lenght zs + 1)"
proof (induction xs)
  let ?ys = "[]"
  let ?zs = "[]"
  have "[] = ?ys @ ?zs \<and> length ?ys = length ?zs" by simp
  then have "\<exists> ys zs. [] = ys @ zs \<and> length ys = length zs" by blast
  from this show "(\<exists>ys zs. [] = ys @ zs \<and> length ys = length zs) \<or>
    (\<exists>ys zs. [] = ys @ zs \<and> length ys = lenght zs + 1)" by (rule disjI1)
next
  fix a
  fix xs_
  assume xs
  assume IH : "(\<exists>ys zs. xs = ys @ zs \<and> length ys = length zs) \<or>
       (\<exists>ys zs. xs = ys @ zs \<and> length ys = lenght zs + 1)"

 \<And>a xs.
       (\<exists>ys cb zs. xs = ys @ zs \<and> length ys = length zs) \<or>
       (\<exists>ys zs. xs = ys @ zs \<and> length ys = lenght zs + 1) \<Longrightarrow>
       (\<exists>ys zs. a # xs = ys @ zs \<and> length ys = length zs) \<or>
       (\<exists>ys zs. a # xs = ys @ zs \<and> length ys = lenght zs + 1
*)

end


(*  Title:      HOL/Examples/Drinker.thy
    Author:     Makarius
*)

section \<open>The Drinker's Principle\<close>

theory Drinker
  imports Main
begin

text \<open>
  Here is another example of classical reasoning: the Drinker's Principle says
  that for some person, if he is drunk, everybody else is drunk!

  We first prove a classical part of de-Morgan's law.
\<close>

lemma de_Morgan:
  assumes "\<not> (\<forall>x. P x)"
  shows "\<exists>x. \<not> P x"
proof (rule classical)
  assume "\<nexists>x. \<not> P x"
  have "\<forall>x. P x"
  proof
    fix x show "P x"
    proof (rule classical)
      assume "\<not> P x"
      then have "\<exists>x. \<not> P x" ..
      with \<open>\<nexists>x. \<not> P x\<close> show ?thesis by contradiction
    qed
  qed
  with \<open>\<not> (\<forall>x. P x)\<close> show ?thesis by contradiction
qed

theorem Drinker's_Principle: "\<exists>x. drunk x \<longrightarrow> (\<forall>x. drunk x)"
proof cases
  assume "\<forall>x. drunk x"
  then have "drunk a \<longrightarrow> (\<forall>x. drunk x)" for a ..
  then show ?thesis ..
next
  assume "\<not> (\<forall>x. drunk x)"
  then have "\<exists>x. \<not> drunk x" by (rule de_Morgan)
  then obtain a where "\<not> drunk a" ..
  have "drunk a \<longrightarrow> (\<forall>x. drunk x)"
  proof
    assume "drunk a"
    with \<open>\<not> drunk a\<close> show "\<forall>x. drunk x" by contradiction
  qed
  then show ?thesis ..
qed

end


theory Chisholm_CJ_DDL_Dyadic imports CJ_DDL  CJ_DDL_Tests (*Christoph Benzmüller & Xavier Parent, 2019*)

begin (* Chisholm Example *)
consts go::\<tau> tell::\<tau> kill::\<tau>

 nitpick_params [user_axioms,show_all,format=2] (*Settings for model finder.*)

(*It ought to be that Jones goes to assist his neighbors.*)
  definition  "D1 \<equiv> \<^bold>O\<^bold>\<langle>go\<^bold>|\<^bold>\<top>\<^bold>\<rangle>"
(*It ought to be that if Jones goes, then he tells them he is coming.*)
  definition  "D2 \<equiv> \<^bold>O\<^bold>\<langle>tell\<^bold>|go\<^bold>\<rangle>"
(*If Jones doesn't go, then he ought not tell them he is coming.*)
  definition  "D3 \<equiv> \<^bold>O\<^bold>\<langle>\<^bold>\<not>tell\<^bold>|\<^bold>\<not>go\<^bold>\<rangle>"
(*Jones doesn't go. (This is encoded as a locally valid statement.)*)
  definition  "D4 \<equiv> \<^bold>\<not>go"

(*** Chisholm ***)
 (* All-wide scoping is not leading to a dependent set of the axioms.*)
 lemma "\<lfloor>(D1 \<^bold>\<and> D2 \<^bold>\<and> D3) \<^bold>\<rightarrow> D4\<rfloor>"  nitpick oops (*countermodel*)
 lemma "\<lfloor>(D1 \<^bold>\<and> D2 \<^bold>\<and> D4) \<^bold>\<rightarrow> D3\<rfloor>"  nitpick oops (*countermodel*)
 lemma "\<lfloor>(D1 \<^bold>\<and> D3 \<^bold>\<and> D4) \<^bold>\<rightarrow> D2\<rfloor>"  nitpick oops (*countermodel*)
 lemma "\<lfloor>(D2 \<^bold>\<and> D3 \<^bold>\<and> D4) \<^bold>\<rightarrow> D1\<rfloor>"  nitpick oops (*countermodel*)
 (* Chisholm is thus an adequate modeling. *)

 (* Consistency *)
 lemma "\<lfloor>(D1 \<^bold>\<and> D2 \<^bold>\<and> D3)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>l" nitpick [satisfy] oops (*Consistent? Yes*)
 lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2 \<^bold>\<and> D3)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>l" shows False nitpick oops (*Inconsistent? No*)
 (* Queries *)
 lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2 \<^bold>\<and> D3)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>l" shows "\<lfloor>\<^bold>O\<^bold>\<langle>\<^bold>\<not>tell\<^bold>|\<^bold>\<top>\<^bold>\<rangle>\<rfloor>\<^sub>l" nitpick oops (*Should James not tell? No*)
 lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2 \<^bold>\<and> D3)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>l" shows "\<lfloor>\<^bold>O\<^bold>\<langle>tell\<^bold>|\<^bold>\<top>\<^bold>\<rangle>\<rfloor>\<^sub>l"
   sledgehammer nitpick oops (*Should James tell? Timeout*)
 lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2 \<^bold>\<and> D3)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>l" shows "\<lfloor>\<^bold>O\<^bold>\<langle>kill\<^bold>|\<^bold>\<top>\<^bold>\<rangle>\<rfloor>\<^sub>l"  nitpick oops (*Should James kill? No*)

end


theory sort_NStoogeSortSorts
imports Main
        "$HIPSTER_HOME/IsaHipster"
begin

datatype 'a list = Nil2 | Cons2 "'a" "'a list"

datatype ('a, 'b) Pair2 = Pair "'a" "'b"

datatype Nat = Z | S "Nat"

fun third :: "Nat => Nat" where
"third (Z) = Z"
| "third (S (Z)) = Z"
| "third (S (S (Z))) = Z"
| "third (S (S (S n))) = S (third n)"

fun take :: "Nat => 'a list => 'a list" where
"take (Z) y = Nil2"
| "take (S z) (Nil2) = Nil2"
| "take (S z) (Cons2 x2 x3) = Cons2 x2 (take z x3)"

fun sort2 :: "int => int => int list" where
"sort2 x y =
   (if x <= y then Cons2 x (Cons2 y (Nil2)) else
      Cons2 y (Cons2 x (Nil2)))"

fun length :: "'t list => Nat" where
"length (Nil2) = Z"
| "length (Cons2 y xs) = S (length xs)"

fun drop :: "Nat => 'a list => 'a list" where
"drop (Z) y = y"
| "drop (S z) (Nil2) = Nil2"
| "drop (S z) (Cons2 x2 x3) = drop z x3"

fun splitAt :: "Nat => 'a list =>
              (('a list), ('a list)) Pair2" where
"splitAt x y = Pair (take x y) (drop x y)"

fun append :: "'a list => 'a list => 'a list" where
"append (Nil2) y = y"
| "append (Cons2 z xs) y = Cons2 z (append xs y)"

fun reverse :: "'t list => 't list" where
"reverse (Nil2) = Nil2"
| "reverse (Cons2 y xs) = append (reverse xs) (Cons2 y (Nil2))"

function nstooge1sort2 :: "int list => int list"
         and nstoogesort :: "int list => int list"
         and nstooge1sort1 :: "int list => int list" where
"nstooge1sort2 x =
   case splitAt (third (length x)) (reverse x) of
     | Pair ys zs =>
         case splitAt (third (length x)) (reverse x) of
           | Pair xs zs2 => append (nstoogesort zs) (reverse xs)
         end
   end"
| "nstoogesort (Nil2) = Nil2"
| "nstoogesort (Cons2 y (Nil2)) = Cons2 y (Nil2)"
| "nstoogesort (Cons2 y (Cons2 y2 (Nil2))) = sort2 y y2"
| "nstoogesort (Cons2 y (Cons2 y2 (Cons2 x3 x4))) =
     nstooge1sort2
       (nstooge1sort1 (nstooge1sort2 (Cons2 y (Cons2 y2 (Cons2 x3 x4)))))"
| "nstooge1sort1 x =
     case splitAt (third (length x)) x of
       | Pair ys zs =>
           case splitAt (third (length x)) x of
             | Pair xs zs2 => append ys (nstoogesort zs2)
           end
     end"
by pat_completeness auto

fun and2 :: "bool => bool => bool" where
"and2 True y = y"
| "and2 False y = False"

fun ordered :: "int list => bool" where
"ordered (Nil2) = True"
| "ordered (Cons2 y (Nil2)) = True"
| "ordered (Cons2 y (Cons2 y2 xs)) =
     and2 (y <= y2) (ordered (Cons2 y2 xs))"

(*hipster third
          take
          sort2
          length
          drop
          splitAt
          append
          reverse
          nstooge1sort2
          nstoogesort
          nstooge1sort1
          and2
          ordered *)

theorem x0 :
  "!! (x :: int list) . ordered (nstoogesort x)"
  by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>)

end


(* License: LGPL *)
(*
Author: Julian Parsert <julian.parsert@gmail.com>
Author: Cezary Kaliszyk
*)

section \<open> Consumers  \<close>

text \<open> Consumption sets \<close>

theory Consumers
  imports
    "HOL-Analysis.Multivariate_Analysis"
    "../Syntax"
begin

subsection \<open> Pre Arrow-Debreu consumption set \<close>

text \<open> It turns out that the First Welfare Theorem does
       not require any particular limitations on the consumption set \<close>
locale pre_arrow_debreu_consumption_set =
  fixes consumption_set :: "('a::euclidean_space) set"
  assumes "x \<in> (UNIV:: 'a set) \<Longrightarrow> x \<in> consumption_set"
begin
end

subsection \<open> Arrow-Debreu model consumption set\<close>

text \<open> The Arrow-Debreu model consumption set includes more and stricter
        assumptions which are necessary for further results. \<close>
locale gen_pre_arrow_debreu_consum_set =
  fixes consumption_set :: "('a::ordered_euclidean_space) set"
begin

end

locale arrow_debreu_consum_set =
  fixes consumption_set :: "('a::ordered_euclidean_space) set"
  assumes r_plus: "consumption_set \<subseteq> {(x::'a). x \<ge> 0}"
  assumes closed: "closed consumption_set"
  assumes convex: "convex consumption_set"
  assumes non_empty: "consumption_set \<noteq> {}"
  assumes "\<forall>M \<in> consumption_set. (\<forall>x > M. x \<in> consumption_set)" (*unbounded above*)
begin

lemma x_larger_0: "x \<in> consumption_set \<Longrightarrow> x \<ge> 0"
  using r_plus by auto

lemma larger_in_consump_set:
  "x \<in> consumption_set \<and> y \<ge> x \<Longrightarrow> y \<in> consumption_set"
  using arrow_debreu_consum_set_axioms arrow_debreu_consum_set_def
    dual_order.order_iff_strict by fastforce

end

end


section \<open>Preliminary Results\<close>

theory Frequency_Moments_Preliminary_Results
  imports
    "HOL.Transcendental"
    "HOL-Computational_Algebra.Primes"
    "HOL-Library.Extended_Real"
    "HOL-Library.Multiset"
    "HOL-Library.Sublist"
    Prefix_Free_Code_Combinators.Prefix_Free_Code_Combinators
    Bertrands_Postulate.Bertrand
begin

text \<open>This section contains various preliminary results.\<close>

lemma card_ordered_pairs:
  fixes M :: "('a ::linorder) set"
  assumes "finite M"
  shows "2 * card {(x,y) \<in> M \<times> M. x < y} = card M * (card M - 1)"
proof -
  have a: "finite (M \<times> M)" using assms by simp

  have inj_swap: "inj (\<lambda>x. (snd x, fst x))"
    by (rule inj_onI, simp add: prod_eq_iff)

  have "2 * card {(x,y) \<in> M \<times> M. x < y} =
    card {(x,y) \<in> M \<times> M. x < y} + card ((\<lambda>x. (snd x, fst x))`{(x,y) \<in> M \<times> M. x < y})"
    by (simp add: card_image[OF inj_on_subset[OF inj_swap]])
  also have "... = card {(x,y) \<in> M \<times> M. x < y} + card {(x,y) \<in> M \<times> M. y < x}"
    by (auto intro: arg_cong[where f="card"] simp add:set_eq_iff image_iff)
  also have "... = card ({(x,y) \<in> M \<times> M. x < y} \<union> {(x,y) \<in> M \<times> M. y < x})"
    by (intro card_Un_disjoint[symmetric] a finite_subset[where B="M \<times> M"] subsetI) auto
  also have "... = card ((M \<times> M) - {(x,y) \<in> M \<times> M. x = y})"
    by (auto intro: arg_cong[where f="card"] simp add:set_eq_iff)
  also have "... = card (M \<times> M) - card {(x,y) \<in> M \<times> M. x = y}"
    by (intro card_Diff_subset a finite_subset[where B="M \<times> M"] subsetI) auto
  also have "... = card M ^ 2 - card ((\<lambda>x. (x,x)) ` M)"
    using assms
    by (intro arg_cong2[where f="(-)"] arg_cong[where f="card"])
      (auto simp:power2_eq_square set_eq_iff image_iff)
  also have "... = card M ^ 2 - card M"
    by (intro arg_cong2[where f="(-)"] card_image inj_onI, auto)
  also have "... = card M * (card M - 1)"
    by (cases "card M \<ge> 0", auto simp:power2_eq_square algebra_simps)
  finally show ?thesis by simp
qed

lemma ereal_mono: "x \<le> y \<Longrightarrow> ereal x \<le> ereal y"
  by simp

lemma log_mono: "a > 1 \<Longrightarrow> x \<le> y \<Longrightarrow> 0 < x \<Longrightarrow> log a x \<le> log a y"
  by (subst log_le_cancel_iff, auto)

lemma abs_ge_iff: "((x::real) \<le> abs y) = (x \<le> y \<or> x \<le> -y)"
  by linarith

lemma count_list_gr_1:
  "(x \<in> set xs) = (count_list xs x \<ge> 1)"
  by (induction xs, simp, simp)

lemma count_list_append: "count_list (xs@ys) v = count_list xs v + count_list ys v"
  by (induction xs, simp, simp)

lemma count_list_lt_suffix:
  assumes "suffix a b"
  assumes "x \<in> {b ! i| i. i <  length b - length a}"
  shows  "count_list a x < count_list b x"
proof -
  have "length a \<le> length b" using assms(1)
    by (simp add: suffix_length_le)
  hence "x \<in> set (nths b {i. i < length b - length a})"
    using assms diff_commute by (auto simp add:set_nths)
  hence a:"x \<in> set (take (length b - length a) b)"
    by (subst (asm) lessThan_def[symmetric], simp)
  have "b = (take (length b - length a) b)@drop (length b - length a) b"
    by simp
  also have "... = (take (length b - length a) b)@a"
    using assms(1) suffix_take by auto
  finally have b:"b = (take (length b - length a) b)@a" by simp

  have "count_list a x < 1 + count_list a x" by simp
  also have "... \<le> count_list (take (length b - length a) b) x + count_list a x"
    using a count_list_gr_1
    by (intro add_mono, fast, simp)
  also have "... = count_list b x"
    using b count_list_append by metis
  finally show ?thesis by simp
qed

lemma suffix_drop_drop:
  assumes "x \<ge> y"
  shows "suffix (drop x a) (drop y a)"
proof -
  have "drop y a = take (x - y) (drop y a)@drop (x- y) (drop y a)"
    by (subst append_take_drop_id, simp)
  also have " ... = take (x-y) (drop y a)@drop x a"
    using assms by simp
  finally have "drop y a = take (x-y) (drop y a)@drop x a" by simp
  thus ?thesis
    by (auto simp add:suffix_def)
qed

lemma count_list_card: "count_list xs x = card {k. k < length xs \<and> xs ! k = x}"
proof -
  have "count_list xs x = length (filter ((=) x) xs)"
    by (induction xs, simp, simp)
  also have "... = card {k. k < length xs \<and> xs ! k = x}"
    by (subst length_filter_conv_card, metis)
  finally show ?thesis by simp
qed

lemma card_gr_1_iff:
  assumes "finite S"  "x \<in> S"  "y \<in> S"  "x \<noteq> y"
  shows "card S > 1"
  using assms card_le_Suc0_iff_eq leI by auto

lemma count_list_ge_2_iff:
  assumes "y < z"
  assumes "z < length xs"
  assumes "xs ! y = xs ! z"
  shows "count_list xs (xs ! y) > 1"
proof -
  have " 1 < card {k. k < length xs \<and> xs ! k = xs ! y}"
    using assms by (intro card_gr_1_iff[where x="y" and y="z"], auto)

  thus ?thesis
    by (simp add: count_list_card)
qed

text \<open>Results about multisets and sorting\<close>

text \<open>This is a induction scheme over the distinct elements of a multisets:
We can represent each multiset as a sum like:
@{text "replicate_mset n\<^sub>1 x\<^sub>1 + replicate_mset n\<^sub>2 x\<^sub>2 + ... + replicate_mset n\<^sub>k x\<^sub>k"} where the
@{term "x\<^sub>i"} are distinct.\<close>

lemma disj_induct_mset:
  assumes "P {#}"
  assumes "\<And>n M x. P M \<Longrightarrow> \<not>(x \<in># M) \<Longrightarrow> n > 0 \<Longrightarrow> P (M + replicate_mset n x)"
  shows "P M"
proof (induction "size M" arbitrary: M rule:nat_less_induct)
  case 1
  show ?case
  proof (cases "M = {#}")
    case True
    then show ?thesis using assms by simp
  next
    case False
    then obtain x where x_def: "x \<in># M" using multiset_nonemptyE by auto
    define M1 where "M1 = M - replicate_mset (count M x) x"
    then have M_def: "M = M1 + replicate_mset (count M x) x"
      by (metis count_le_replicate_mset_subset_eq dual_order.refl subset_mset.diff_add)
    have "size M1 < size M"
      by (metis M_def x_def count_greater_zero_iff less_add_same_cancel1 size_replicate_mset size_union)
    hence "P M1" using 1 by blast
    then show "P M"
      apply (subst M_def, rule assms(2), simp)
      by (simp add:M1_def x_def count_eq_zero_iff[symmetric])+
  qed
qed

lemma prod_mset_conv:
  fixes f :: "'a \<Rightarrow> 'b::{comm_monoid_mult}"
  shows "prod_mset (image_mset f A) = prod (\<lambda>x. f x^(count A x)) (set_mset A)"
proof (induction A rule: disj_induct_mset)
  case 1
  then show ?case by simp
next
  case (2 n M x)
  moreover have "count M x = 0" using 2 by (simp add: count_eq_zero_iff)
  moreover have "\<And>y. y \<in> set_mset M \<Longrightarrow> y \<noteq> x" using 2 by blast
  ultimately show ?case by (simp add:algebra_simps)
qed

text \<open>There is a version @{thm [source] sum_list_map_eq_sum_count} but it doesn't work
if the function maps into the reals.\<close>

lemma sum_list_eval:
  fixes f :: "'a \<Rightarrow> 'b::{ring,semiring_1}"
  shows "sum_list (map f xs) = (\<Sum>x \<in> set xs. of_nat (count_list xs x) * f x)"
proof -
  define M where "M = mset xs"
  have "sum_mset (image_mset f M) = (\<Sum>x \<in> set_mset M. of_nat (count M x) * f x)"
  proof (induction "M" rule:disj_induct_mset)
    case 1
    then show ?case by simp
  next
    case (2 n M x)
    have a:"\<And>y. y \<in> set_mset M \<Longrightarrow> y \<noteq> x" using 2(2) by blast
    show ?case using 2 by (simp add:a  count_eq_zero_iff[symmetric])
  qed
  moreover have "\<And>x. count_list xs x = count (mset xs) x"
    by (induction xs, simp, simp)
  ultimately show ?thesis
    by (simp add:M_def sum_mset_sum_list[symmetric])
qed

lemma prod_list_eval:
  fixes f :: "'a \<Rightarrow> 'b::{ring,semiring_1,comm_monoid_mult}"
  shows "prod_list (map f xs) = (\<Prod>x \<in> set xs. (f x)^(count_list xs x))"
proof -
  define M where "M = mset xs"
  have "prod_mset (image_mset f M) = (\<Prod>x \<in> set_mset M. f x ^ (count M x))"
  proof (induction "M" rule:disj_induct_mset)
    case 1
    then show ?case by simp
  next
    case (2 n M x)
    have a:"\<And>y. y \<in> set_mset M \<Longrightarrow> y \<noteq> x" using 2(2) by blast
    have b:"count M x = 0" using 2 by (subst  count_eq_zero_iff) blast
    show ?case using 2  by (simp add:a b mult.commute)
  qed
  moreover have "\<And>x. count_list xs x = count (mset xs) x"
    by (induction xs, simp, simp)
  ultimately show ?thesis
    by (simp add:M_def prod_mset_prod_list[symmetric])
qed

lemma sorted_sorted_list_of_multiset: "sorted (sorted_list_of_multiset M)"
  by (induction M, auto simp:sorted_insort)

lemma count_mset: "count (mset xs) a = count_list xs a"
  by (induction xs, auto)

lemma swap_filter_image: "filter_mset g (image_mset f A) = image_mset f (filter_mset (g \<circ> f) A)"
  by (induction A, auto)

lemma list_eq_iff:
  assumes "mset xs = mset ys"
  assumes "sorted xs"
  assumes "sorted ys"
  shows "xs = ys"
  using assms properties_for_sort by blast

lemma sorted_list_of_multiset_image_commute:
  assumes "mono f"
  shows "sorted_list_of_multiset (image_mset f M) = map f (sorted_list_of_multiset M)"
proof -
  have "sorted (sorted_list_of_multiset (image_mset f M))"
    by (simp add:sorted_sorted_list_of_multiset)
  moreover have " sorted_wrt (\<lambda>x y. f x \<le> f y) (sorted_list_of_multiset M)"
    by (rule sorted_wrt_mono_rel[where P="\<lambda>x y. x \<le> y"])
      (auto intro: monoD[OF assms] sorted_sorted_list_of_multiset)
  hence "sorted (map f (sorted_list_of_multiset M))"
    by (subst sorted_wrt_map)
  ultimately show ?thesis
    by (intro list_eq_iff, auto)
qed

text \<open>Results about rounding and floating point numbers\<close>

lemma round_down_ge:
  "x \<le> round_down prec x + 2 powr (-prec)"
  using round_down_correct by (simp, meson diff_diff_eq diff_eq_diff_less_eq)

lemma truncate_down_ge:
  "x \<le> truncate_down prec x + abs x * 2 powr (-prec)"
proof (cases "abs x > 0")
  case True
  have "x \<le> round_down (int prec - \<lfloor>log 2 \<bar>x\<bar>\<rfloor>) x + 2 powr (-real_of_int(int prec - \<lfloor>log 2 \<bar>x\<bar>\<rfloor>))"
    by (rule round_down_ge)
  also have "... \<le> truncate_down prec x + 2 powr ( \<lfloor>log 2 \<bar>x\<bar>\<rfloor>) * 2 powr (-real prec)"
    by (rule add_mono, simp_all add:powr_add[symmetric] truncate_down_def)
  also have "... \<le> truncate_down prec x + \<bar>x\<bar> * 2 powr (-real prec)"
    using True
    by (intro add_mono mult_right_mono, simp_all add:le_log_iff[symmetric])
  finally show ?thesis by simp
next
  case False
  then show ?thesis by simp
qed

lemma truncate_down_pos:
  assumes "x \<ge> 0"
  shows "x * (1 - 2 powr (-prec)) \<le> truncate_down prec x"
  by (simp add:right_diff_distrib diff_le_eq)
   (metis truncate_down_ge assms  abs_of_nonneg)

lemma truncate_down_eq:
  assumes "truncate_down r x = truncate_down r y"
  shows "abs (x-y) \<le> max (abs x) (abs y) * 2 powr (-real r)"
proof -
  have "x - y \<le> truncate_down r x + abs x * 2 powr (-real r) - y"
    by (rule diff_right_mono, rule truncate_down_ge)
  also have "... \<le> y + abs x * 2 powr (-real r) - y"
    using truncate_down_le
    by (intro diff_right_mono add_mono, subst assms(1), simp_all)
  also have "... \<le> abs x * 2 powr (-real r)" by simp
  also have "... \<le> max (abs x) (abs y) * 2 powr (-real r)" by simp
  finally have a:"x - y \<le> max (abs x) (abs y) * 2 powr (-real r)" by simp

  have "y - x \<le> truncate_down r y + abs y * 2 powr (-real r) - x"
    by (rule diff_right_mono, rule truncate_down_ge)
  also have "... \<le> x + abs y * 2 powr (-real r) - x"
    using truncate_down_le
    by (intro diff_right_mono add_mono, subst assms(1)[symmetric], auto)
  also have "... \<le> abs y * 2 powr (-real r)" by simp
  also have "... \<le> max (abs x) (abs y) * 2 powr (-real r)" by simp
  finally have b:"y - x \<le> max (abs x) (abs y) * 2 powr (-real r)" by simp

  show ?thesis
    using abs_le_iff a b by linarith
qed

definition rat_of_float :: "float \<Rightarrow> rat" where
  "rat_of_float f = of_int (mantissa f) *
    (if exponent f \<ge> 0 then 2 ^ (nat (exponent f)) else 1 / 2 ^ (nat (-exponent f)))"

lemma real_of_rat_of_float: "real_of_rat (rat_of_float x) = real_of_float x"
proof -
  have "real_of_rat (rat_of_float x) = mantissa x * (2 powr (exponent x))"
    by (simp add:rat_of_float_def of_rat_mult of_rat_divide of_rat_power powr_realpow[symmetric] powr_minus_divide)
  also have "... = real_of_float x"
    using mantissa_exponent by simp
  finally show ?thesis by simp
qed

lemma log_est: "log 2 (real n + 1) \<le> n"
proof -
  have "1 + real n = real (n + 1)"
    by simp
  also have "... \<le> real (2 ^ n)"
    by (intro of_nat_mono suc_n_le_2_pow_n)
  also have "... = 2 powr (real n)"
    by (simp add:powr_realpow)
  finally have "1 + real n \<le> 2 powr (real n)"
    by simp
  thus ?thesis
    by (simp add: Transcendental.log_le_iff)
qed

lemma truncate_mantissa_bound:
  "abs (\<lfloor>x * 2 powr (real r - real_of_int \<lfloor>log 2 \<bar>x\<bar>\<rfloor>)\<rfloor>) \<le> 2 ^ (r+1)" (is "?lhs \<le> _")
proof -
  define q where "q = \<lfloor>x * 2 powr (real r - real_of_int (\<lfloor>log 2 \<bar>x\<bar>\<rfloor>))\<rfloor>"

  have "abs q \<le> 2 ^ (r + 1)" if a:"x > 0"
  proof -
    have "abs q = q"
      using a by (intro abs_of_nonneg, simp add:q_def)
    also have "... \<le> x * 2 powr (real r - real_of_int \<lfloor>log 2 \<bar>x\<bar>\<rfloor>)"
      unfolding q_def using of_int_floor_le by blast
    also have "... = x * 2 powr real_of_int (int r - \<lfloor>log 2 \<bar>x\<bar>\<rfloor>)"
      by auto
    also have "... = 2 powr (log 2 x + real_of_int (int r - \<lfloor>log 2 \<bar>x\<bar>\<rfloor>))"
      using a by (simp add:powr_add)
    also have "... \<le> 2 powr (real r + 1)"
      using a by (intro powr_mono, linarith+)
    also have "... = 2 ^ (r+1)"
      by (subst powr_realpow[symmetric], simp_all add:add.commute)
    finally show "abs q \<le> 2 ^ (r+1)"
      by (metis of_int_le_iff of_int_numeral of_int_power)
  qed

  moreover have "abs q \<le> (2 ^ (r + 1))" if a: "x < 0"
  proof -
    have "-(2 ^ (r+1) + 1) = -(2 powr (real r + 1)+1)"
      by (subst powr_realpow[symmetric], simp_all add: add.commute)
    also have  "... < -(2 powr (log 2 (- x) + (r - \<lfloor>log 2 \<bar>x\<bar>\<rfloor>)) + 1)"
      using a by (simp, linarith)
    also have "... = x * 2 powr (r - \<lfloor>log 2 \<bar>x\<bar>\<rfloor>) - 1"
      using a by (simp add:powr_add)
    also have "... \<le> q"
      by (simp add:q_def)
    also have "... = - abs q"
      using a
      by (subst abs_of_neg, simp_all add: mult_pos_neg2 q_def)
    finally have "-(2 ^ (r+1)+1) < - abs q" using of_int_less_iff by fastforce
    hence "-(2 ^ (r+1)) \<le> - abs q" by linarith
    thus "abs q \<le> 2^(r+1)" by linarith
  qed

  moreover have "x = 0 \<Longrightarrow> abs q \<le> 2^(r+1)"
    by (simp add:q_def)
  ultimately have "abs q \<le> 2^(r+1)"
    by fastforce
  thus ?thesis using q_def by blast
qed

lemma truncate_float_bit_count:
  "bit_count (F\<^sub>e (float_of (truncate_down r x))) \<le> 10 + 4 * real r + 2*log 2 (2 + \<bar>log 2 \<bar>x\<bar>\<bar>)"
  (is "?lhs \<le> ?rhs")
proof -
  define m where "m = \<lfloor>x * 2 powr (real r - real_of_int \<lfloor>log 2 \<bar>x\<bar>\<rfloor>)\<rfloor>"
  define e where "e = \<lfloor>log 2 \<bar>x\<bar>\<rfloor> - int r"

  have a: "(real_of_int \<lfloor>log 2 \<bar>x\<bar>\<rfloor> - real r) = e"
    by (simp add:e_def)
  have "abs m + 2 \<le> 2 ^ (r + 1) + 2^1"
    using truncate_mantissa_bound
    by (intro add_mono, simp_all add:m_def)
  also have "... \<le> 2 ^ (r+2)"
    by simp
  finally have b:"abs m + 2 \<le> 2 ^ (r+2)" by simp
  hence "real_of_int (\<bar>m\<bar> + 2) \<le> real_of_int (4 * 2 ^ r)"
    by (subst of_int_le_iff, simp)
  hence "\<bar>real_of_int m\<bar> + 2 \<le> 4 * 2 ^ r"
    by simp
  hence c:"log 2 (real_of_int (\<bar>m\<bar> + 2)) \<le> r+2"
    by (simp add: Transcendental.log_le_iff powr_add powr_realpow)

  have "real_of_int (abs e + 1) \<le> real_of_int \<bar>\<lfloor>log 2 \<bar>x\<bar>\<rfloor>\<bar> +  real_of_int r + 1"
    by (simp add:e_def)
  also have "... \<le> 1 + abs (log 2 (abs x)) + real_of_int r + 1"
    by (simp add:abs_le_iff, linarith)
  also have "... \<le> (real_of_int r+ 1) * (2 + abs (log 2 (abs x)))"
    by (simp add:distrib_left distrib_right)
  finally have d:"real_of_int (abs e + 1) \<le> (real_of_int r+ 1) * (2 + abs (log 2 (abs x)))" by simp

  have "log 2 (real_of_int (abs e + 1)) \<le> log 2 (real_of_int r + 1) + log 2 (2 + abs (log 2 (abs x)))"
    using d by (simp add: log_mult[symmetric])
  also have "... \<le> r + log 2 (2 + abs (log 2 (abs x)))"
    using log_est by (intro add_mono, simp_all add:add.commute)
  finally have e: "log 2 (real_of_int (abs e + 1)) \<le> r + log 2 (2 + abs (log 2 (abs x)))" by simp

  have "?lhs =  bit_count (F\<^sub>e (float_of (real_of_int m * 2 powr real_of_int e)))"
    by (simp add:truncate_down_def round_down_def m_def[symmetric] a)
  also have "... \<le> ereal (6 + (2 * log 2 (real_of_int (\<bar>m\<bar> + 2)) + 2 * log 2 (real_of_int (\<bar>e\<bar> + 1))))"
    using float_bit_count_2 by simp
  also have "... \<le> ereal (6 + (2 * real (r+2) + 2 * (r + log 2 (2 + abs (log 2 (abs x))))))"
    using c e
    by (subst ereal_less_eq, intro add_mono mult_left_mono, linarith+)
  also have "... = ?rhs" by simp
  finally show ?thesis by simp
qed

definition prime_above :: "nat \<Rightarrow> nat"
  where "prime_above n = (SOME x. x \<in> {n..(2*n+2)} \<and> prime x)"

text \<open>The term @{term"prime_above n"} returns a prime between @{term "n::nat"} and @{term "2*(n::nat)+2"}.
Because of Bertrand's postulate there always is such a value. In a refinement of the algorithms, it may make sense to
replace this with an algorithm, that finds such a prime exactly or approximately.

The definition is intentionally inexact, to allow refinement with various algorithms, without modifying the
high-level mathematical correctness proof.\<close>

lemma ex_subset:
  assumes "\<exists>x \<in> A. P x"
  assumes "A \<subseteq> B"
  shows "\<exists>x \<in> B. P x"
  using assms by auto

lemma
  shows prime_above_prime: "prime (prime_above n)"
  and prime_above_range: "prime_above n \<in> {n..(2*n+2)}"
proof -
  define r where "r = (\<lambda>x. x \<in> {n..(2*n+2)} \<and> prime x)"
  have "\<exists>x. r x"
  proof (cases "n>2")
    case True
    hence "n-1 > 1" by simp
    hence "\<exists>x \<in> {(n-1)<..<(2*(n-1))}. prime x"
      using bertrand by simp
    moreover have "{n - 1<..<2 * (n - 1)} \<subseteq> {n..2 * n + 2}"
      by (intro subsetI, auto)
    ultimately have "\<exists>x \<in> {n..(2*n+2)}. prime x"
      by (rule ex_subset)
    then show ?thesis by (simp add:r_def Bex_def)
  next
    case False
    hence "2 \<in> {n..(2*n+2)}"
      by simp
    moreover have "prime (2::nat)"
      using two_is_prime_nat by blast
    ultimately have "r 2"
      using r_def by simp
    then show ?thesis by (rule exI)
  qed
  moreover have "prime_above n = (SOME x. r x)"
    by (simp add:prime_above_def r_def)
  ultimately have a:"r (prime_above n)"
    using someI_ex by metis
  show "prime (prime_above n)"
    using a unfolding r_def by blast
  show "prime_above n \<in> {n..(2*n+2)}"
    using a unfolding r_def by blast
qed

lemma prime_above_min:  "prime_above n \<ge> 2"
  using prime_above_prime
  by (simp add: prime_ge_2_nat)

lemma prime_above_lower_bound: "prime_above n \<ge> n"
  using prime_above_range
  by simp

lemma prime_above_upper_bound: "prime_above n \<le> 2*n+2"
  using prime_above_range
  by simp

end


(*  Title:       Safe OCL
    Author:      Denis Nikiforov, March 2019
    Maintainer:  Denis Nikiforov <denis.nikif at gmail.com>
    License:     LGPL
*)
chapter \<open>Preliminaries\<close>
section \<open>Transitive Closures\<close>
theory Transitive_Closure_Ext
  imports "HOL-Library.FuncSet"
begin

(*** Basic Properties *******************************************************)

subsection \<open>Basic Properties\<close>

text \<open>
  @{text "R\<^sup>+\<^sup>+"} is a transitive closure of a relation @{text R}.
  @{text "R\<^sup>*\<^sup>*"} is a reflexive transitive closure of a relation @{text R}.\<close>

text \<open>
  A function @{text f} is surjective on @{text "R\<^sup>+\<^sup>+"} iff for any
  two elements in the range of @{text f}, related through @{text "R\<^sup>+\<^sup>+"},
  all their intermediate elements belong to the range of @{text f}.\<close>

abbreviation "surj_on_trancl R f \<equiv>
  (\<forall>x y z. R\<^sup>+\<^sup>+ (f x) y \<longrightarrow> R y (f z) \<longrightarrow> y \<in> range f)"

text \<open>
  A function @{text f} is bijective on @{text "R\<^sup>+\<^sup>+"} iff
  it is injective and surjective on @{text "R\<^sup>+\<^sup>+"}.\<close>

abbreviation "bij_on_trancl R f \<equiv> inj f \<and> surj_on_trancl R f"

(*** Helper Lemmas **********************************************************)

subsection \<open>Helper Lemmas\<close>

lemma rtranclp_eq_rtranclp [iff]:
  "(\<lambda>x y. P x y \<or> x = y)\<^sup>*\<^sup>* = P\<^sup>*\<^sup>*"
proof (intro ext iffI)
  fix x y
  have "(\<lambda>x y. P x y \<or> x = y)\<^sup>*\<^sup>* x y \<longrightarrow> P\<^sup>=\<^sup>=\<^sup>*\<^sup>* x y"
    by (rule mono_rtranclp) simp
  thus "(\<lambda>x y. P x y \<or> x = y)\<^sup>*\<^sup>* x y \<Longrightarrow> P\<^sup>*\<^sup>* x y"
    by simp
  show "P\<^sup>*\<^sup>* x y \<Longrightarrow> (\<lambda>x y. P x y \<or> x = y)\<^sup>*\<^sup>* x y"
    by (metis (no_types, lifting) mono_rtranclp)
qed

lemma tranclp_eq_rtranclp [iff]:
  "(\<lambda>x y. P x y \<or> x = y)\<^sup>+\<^sup>+ = P\<^sup>*\<^sup>*"
proof (intro ext iffI)
  fix x y
  have "(\<lambda>x y. P x y \<or> x = y)\<^sup>*\<^sup>* x y \<longrightarrow> P\<^sup>=\<^sup>=\<^sup>*\<^sup>* x y"
    by (rule mono_rtranclp) simp
  thus "(\<lambda>x y. P x y \<or> x = y)\<^sup>+\<^sup>+ x y \<Longrightarrow> P\<^sup>*\<^sup>* x y"
    using tranclp_into_rtranclp by force
  show "P\<^sup>*\<^sup>* x y \<Longrightarrow> (\<lambda>x y. P x y \<or> x = y)\<^sup>+\<^sup>+ x y"
    by (metis (mono_tags, lifting) mono_rtranclp rtranclpD tranclp.r_into_trancl)
qed

lemma rtranclp_eq_rtranclp' [iff]:
  "(\<lambda>x y. P x y \<and> x \<noteq> y)\<^sup>*\<^sup>* = P\<^sup>*\<^sup>*"
proof (intro ext iffI)
  fix x y
  show "(\<lambda>x y. P x y \<and> x \<noteq> y)\<^sup>*\<^sup>* x y \<Longrightarrow> P\<^sup>*\<^sup>* x y"
    by (metis (no_types, lifting) mono_rtranclp)
  assume "P\<^sup>*\<^sup>* x y"
  hence "(inf P (\<noteq>))\<^sup>*\<^sup>* x y"
    by (simp add: rtranclp_r_diff_Id)
  also have "(inf P (\<noteq>))\<^sup>*\<^sup>* x y \<longrightarrow> (\<lambda>x y. P x y \<and> x \<noteq> y)\<^sup>*\<^sup>* x y"
    by (rule mono_rtranclp) simp
  finally show "P\<^sup>*\<^sup>* x y \<Longrightarrow> (\<lambda>x y. P x y \<and> x \<noteq> y)\<^sup>*\<^sup>* x y" by simp
qed

lemma tranclp_tranclp_to_tranclp_r:
  assumes "(\<And>x y z. R\<^sup>+\<^sup>+ x y \<Longrightarrow> R y z \<Longrightarrow> P x \<Longrightarrow> P z \<Longrightarrow> P y)"
  assumes "R\<^sup>+\<^sup>+ x y" and "R\<^sup>+\<^sup>+ y z"
  assumes "P x" and "P z"
  shows "P y"
proof -
  have "(\<And>x y z. R\<^sup>+\<^sup>+ x y \<Longrightarrow> R y z \<Longrightarrow> P x \<Longrightarrow> P z \<Longrightarrow> P y) \<Longrightarrow>
         R\<^sup>+\<^sup>+ y z \<Longrightarrow> R\<^sup>+\<^sup>+ x y \<Longrightarrow> P x \<longrightarrow> P z \<longrightarrow> P y"
    apply (erule tranclp_induct)
    apply simp
    by (meson tranclp_trans)
  thus ?thesis using assms by auto
qed

(*** Transitive Closure Preservation & Reflection ***************************)

subsection \<open>Transitive Closure Preservation\<close>

text \<open>
  A function @{text f} preserves @{text "R\<^sup>+\<^sup>+"} if it preserves @{text R}.\<close>

text \<open>
  The proof was derived from the accepted answer on the website
  Stack Overflow that is available at
  @{url "https://stackoverflow.com/a/52573551/632199"}
  and provided with the permission of the author of the answer.\<close>

lemma preserve_tranclp:
  assumes "\<And>x y. R x y \<Longrightarrow> S (f x) (f y)"
  assumes "R\<^sup>+\<^sup>+ x y"
  shows "S\<^sup>+\<^sup>+ (f x) (f y)"
proof -
  define P where P: "P = (\<lambda>x y. S\<^sup>+\<^sup>+ (f x) (f y))"
  define r where r: "r = (\<lambda>x y. S (f x) (f y))"
  have "r\<^sup>+\<^sup>+ x y" by (insert assms r; erule tranclp_trans_induct; auto)
  moreover have "\<And>x y. r x y \<Longrightarrow> P x y" unfolding P r by simp
  moreover have "\<And>x y z. r\<^sup>+\<^sup>+ x y \<Longrightarrow> P x y \<Longrightarrow> r\<^sup>+\<^sup>+ y z \<Longrightarrow> P y z \<Longrightarrow> P x z"
    unfolding P by auto
  ultimately have "P x y" by (rule tranclp_trans_induct)
  with P show ?thesis by simp
qed

text \<open>
  A function @{text f} preserves @{text "R\<^sup>*\<^sup>*"} if it preserves @{text R}.\<close>

lemma preserve_rtranclp:
  "(\<And>x y. R x y \<Longrightarrow> S (f x) (f y)) \<Longrightarrow>
   R\<^sup>*\<^sup>* x y \<Longrightarrow> S\<^sup>*\<^sup>* (f x) (f y)"
  unfolding Nitpick.rtranclp_unfold
  by (metis preserve_tranclp)

text \<open>
  If one needs to prove that @{text "(f x)"} and @{text "(g y)"}
  are related through @{text "S\<^sup>*\<^sup>*"} then one can use the previous
  lemma and add a one more step from @{text "(f y)"} to @{text "(g y)"}.\<close>

lemma preserve_rtranclp':
  "(\<And>x y. R x y \<Longrightarrow> S (f x) (f y)) \<Longrightarrow>
   (\<And>y. S (f y) (g y)) \<Longrightarrow>
   R\<^sup>*\<^sup>* x y \<Longrightarrow> S\<^sup>*\<^sup>* (f x) (g y)"
  by (metis preserve_rtranclp rtranclp.rtrancl_into_rtrancl)

lemma preserve_rtranclp'':
  "(\<And>x y. R x y \<Longrightarrow> S (f x) (f y)) \<Longrightarrow>
   (\<And>y. S (f y) (g y)) \<Longrightarrow>
   R\<^sup>*\<^sup>* x y \<Longrightarrow> S\<^sup>+\<^sup>+ (f x) (g y)"
  apply (rule_tac ?b="f y" in rtranclp_into_tranclp1, auto)
  by (rule preserve_rtranclp, auto)

subsection \<open>Transitive Closure Reflection\<close>

text \<open>
  A function @{text f} reflects @{text "S\<^sup>+\<^sup>+"} if it reflects
  @{text S} and is bijective on @{text "S\<^sup>+\<^sup>+"}.\<close>

text \<open>
  The proof was derived from the accepted answer on the website
  Stack Overflow that is available at
  @{url "https://stackoverflow.com/a/52573551/632199"}
  and provided with the permission of the author of the answer.\<close>

lemma reflect_tranclp:
  assumes refl_f: "\<And>x y. S (f x) (f y) \<Longrightarrow> R x y"
  assumes bij_f: "bij_on_trancl S f"
  assumes prem: "S\<^sup>+\<^sup>+ (f x) (f y)"
  shows "R\<^sup>+\<^sup>+ x y"
proof -
  define B where B: "B = range f"
  define g where g: "g = the_inv_into UNIV f"
  define gr where gr: "gr = restrict g B"
  define P where P: "P = (\<lambda>x y. x \<in> B \<longrightarrow> y \<in> B \<longrightarrow> R\<^sup>+\<^sup>+ (gr x) (gr y))"
  from prem have major: "S\<^sup>+\<^sup>+ (f x) (f y)" by blast
  from refl_f bij_f have cases_1: "\<And>x y. S x y \<Longrightarrow> P x y"
    unfolding B P g gr
    by (simp add: f_the_inv_into_f tranclp.r_into_trancl)
  from refl_f bij_f
  have "(\<And>x y z. S\<^sup>+\<^sup>+ x y \<Longrightarrow> S\<^sup>+\<^sup>+ y z \<Longrightarrow> x \<in> B \<Longrightarrow> z \<in> B \<Longrightarrow> y \<in> B)"
    unfolding B
    by (rule_tac ?z="z" in tranclp_tranclp_to_tranclp_r, auto, blast)
  with P have cases_2:
    "\<And>x y z. S\<^sup>+\<^sup>+ x y \<Longrightarrow> P x y \<Longrightarrow> S\<^sup>+\<^sup>+ y z \<Longrightarrow> P y z \<Longrightarrow> P x z"
    unfolding B
    by auto
  from major cases_1 cases_2 have "P (f x) (f y)"
    by (rule tranclp_trans_induct)
  with bij_f show ?thesis unfolding P B g gr by (simp add: the_inv_f_f)
qed

text \<open>
  A function @{text f} reflects @{text "S\<^sup>*\<^sup>*"} if it reflects
  @{text S} and is bijective on @{text "S\<^sup>+\<^sup>+"}.\<close>

lemma reflect_rtranclp:
  "(\<And>x y. S (f x) (f y) \<Longrightarrow> R x y) \<Longrightarrow>
   bij_on_trancl S f \<Longrightarrow>
   S\<^sup>*\<^sup>* (f x) (f y) \<Longrightarrow> R\<^sup>*\<^sup>* x y"
  unfolding Nitpick.rtranclp_unfold
  by (metis (full_types) injD reflect_tranclp)

end


(*  Title:      HOL/Lattices.thy
    Author:     Tobias Nipkow
*)

section {* Abstract lattices *}

theory Lattices
imports Groups
begin

subsection {* Abstract semilattice *}

text {*
  These locales provide a basic structure for interpretation into
  bigger structures;  extensions require careful thinking, otherwise
  undesired effects may occur due to interpretation.
*}

no_notation times (infixl "*" 70)
no_notation Groups.one ("1")

locale semilattice = abel_semigroup +
  assumes idem [simp]: "a * a = a"
begin

lemma left_idem [simp]: "a * (a * b) = a * b"
by (simp add: assoc [symmetric])

lemma right_idem [simp]: "(a * b) * b = a * b"
by (simp add: assoc)

end

locale semilattice_neutr = semilattice + comm_monoid

locale semilattice_order = semilattice +
  fixes less_eq :: "'a \<Rightarrow> 'a \<Rightarrow> bool" (infix "\<preceq>" 50)
    and less :: "'a \<Rightarrow> 'a \<Rightarrow> bool" (infix "\<prec>" 50)
  assumes order_iff: "a \<preceq> b \<longleftrightarrow> a = a * b"
    and semilattice_strict_iff_order: "a \<prec> b \<longleftrightarrow> a \<preceq> b \<and> a \<noteq> b"
begin

lemma orderI:
  "a = a * b \<Longrightarrow> a \<preceq> b"
  by (simp add: order_iff)

lemma orderE:
  assumes "a \<preceq> b"
  obtains "a = a * b"
  using assms by (unfold order_iff)

sublocale ordering less_eq less
proof
  fix a b
  show "a \<prec> b \<longleftrightarrow> a \<preceq> b \<and> a \<noteq> b"
    by (fact semilattice_strict_iff_order)
next
  fix a
  show "a \<preceq> a"
    by (simp add: order_iff)
next
  fix a b
  assume "a \<preceq> b" "b \<preceq> a"
  then have "a = a * b" "a * b = b"
    by (simp_all add: order_iff commute)
  then show "a = b" by simp
next
  fix a b c
  assume "a \<preceq> b" "b \<preceq> c"
  then have "a = a * b" "b = b * c"
    by (simp_all add: order_iff commute)
  then have "a = a * (b * c)"
    by simp
  then have "a = (a * b) * c"
    by (simp add: assoc)
  with `a = a * b` [symmetric] have "a = a * c" by simp
  then show "a \<preceq> c" by (rule orderI)
qed

lemma cobounded1 [simp]:
  "a * b \<preceq> a"
  by (simp add: order_iff commute)

lemma cobounded2 [simp]:
  "a * b \<preceq> b"
  by (simp add: order_iff)

lemma boundedI:
  assumes "a \<preceq> b" and "a \<preceq> c"
  shows "a \<preceq> b * c"
proof (rule orderI)
  from assms obtain "a * b = a" and "a * c = a" by (auto elim!: orderE)
  then show "a = a * (b * c)" by (simp add: assoc [symmetric])
qed

lemma boundedE:
  assumes "a \<preceq> b * c"
  obtains "a \<preceq> b" and "a \<preceq> c"
  using assms by (blast intro: trans cobounded1 cobounded2)

lemma bounded_iff [simp]:
  "a \<preceq> b * c \<longleftrightarrow> a \<preceq> b \<and> a \<preceq> c"
  by (blast intro: boundedI elim: boundedE)

lemma strict_boundedE:
  assumes "a \<prec> b * c"
  obtains "a \<prec> b" and "a \<prec> c"
  using assms by (auto simp add: commute strict_iff_order elim: orderE intro!: that)+

lemma coboundedI1:
  "a \<preceq> c \<Longrightarrow> a * b \<preceq> c"
  by (rule trans) auto

lemma coboundedI2:
  "b \<preceq> c \<Longrightarrow> a * b \<preceq> c"
  by (rule trans) auto

lemma strict_coboundedI1:
  "a \<prec> c \<Longrightarrow> a * b \<prec> c"
  using irrefl
    by (auto intro: not_eq_order_implies_strict coboundedI1 strict_implies_order elim: strict_boundedE)

lemma strict_coboundedI2:
  "b \<prec> c \<Longrightarrow> a * b \<prec> c"
  using strict_coboundedI1 [of b c a] by (simp add: commute)

lemma mono: "a \<preceq> c \<Longrightarrow> b \<preceq> d \<Longrightarrow> a * b \<preceq> c * d"
  by (blast intro: boundedI coboundedI1 coboundedI2)

lemma absorb1: "a \<preceq> b \<Longrightarrow> a * b = a"
  by (rule antisym) (auto simp add: refl)

lemma absorb2: "b \<preceq> a \<Longrightarrow> a * b = b"
  by (rule antisym) (auto simp add: refl)

lemma absorb_iff1: "a \<preceq> b \<longleftrightarrow> a * b = a"
  using order_iff by auto

lemma absorb_iff2: "b \<preceq> a \<longleftrightarrow> a * b = b"
  using order_iff by (auto simp add: commute)

end

locale semilattice_neutr_order = semilattice_neutr + semilattice_order
begin

sublocale ordering_top less_eq less 1
  by default (simp add: order_iff)

end

notation times (infixl "*" 70)
notation Groups.one ("1")

subsection {* Syntactic infimum and supremum operations *}

class inf =
  fixes inf :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "\<sqinter>" 70)

class sup =
  fixes sup :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "\<squnion>" 65)

subsection {* Concrete lattices *}

notation
  less_eq  (infix "\<sqsubseteq>" 50) and
  less  (infix "\<sqsubset>" 50)

class semilattice_inf =  order + inf +
  assumes inf_le1 [simp]: "x \<sqinter> y \<sqsubseteq> x"
  and inf_le2 [simp]: "x \<sqinter> y \<sqsubseteq> y"
  and inf_greatest: "x \<sqsubseteq> y \<Longrightarrow> x \<sqsubseteq> z \<Longrightarrow> x \<sqsubseteq> y \<sqinter> z"

class semilattice_sup = order + sup +
  assumes sup_ge1 [simp]: "x \<sqsubseteq> x \<squnion> y"
  and sup_ge2 [simp]: "y \<sqsubseteq> x \<squnion> y"
  and sup_least: "y \<sqsubseteq> x \<Longrightarrow> z \<sqsubseteq> x \<Longrightarrow> y \<squnion> z \<sqsubseteq> x"
begin

text {* Dual lattice *}

lemma dual_semilattice:
  "class.semilattice_inf sup greater_eq greater"
by (rule class.semilattice_inf.intro, rule dual_order)
  (unfold_locales, simp_all add: sup_least)

end

class lattice = semilattice_inf + semilattice_sup

subsubsection {* Intro and elim rules*}

context semilattice_inf
begin

lemma le_infI1:
  "a \<sqsubseteq> x \<Longrightarrow> a \<sqinter> b \<sqsubseteq> x"
  by (rule order_trans) auto

lemma le_infI2:
  "b \<sqsubseteq> x \<Longrightarrow> a \<sqinter> b \<sqsubseteq> x"
  by (rule order_trans) auto

lemma le_infI: "x \<sqsubseteq> a \<Longrightarrow> x \<sqsubseteq> b \<Longrightarrow> x \<sqsubseteq> a \<sqinter> b"
  by (fact inf_greatest) (* FIXME: duplicate lemma *)

lemma le_infE: "x \<sqsubseteq> a \<sqinter> b \<Longrightarrow> (x \<sqsubseteq> a \<Longrightarrow> x \<sqsubseteq> b \<Longrightarrow> P) \<Longrightarrow> P"
  by (blast intro: order_trans inf_le1 inf_le2)

lemma le_inf_iff:
  "x \<sqsubseteq> y \<sqinter> z \<longleftrightarrow> x \<sqsubseteq> y \<and> x \<sqsubseteq> z"
  by (blast intro: le_infI elim: le_infE)

lemma le_iff_inf:
  "x \<sqsubseteq> y \<longleftrightarrow> x \<sqinter> y = x"
  by (auto intro: le_infI1 antisym dest: eq_iff [THEN iffD1] simp add: le_inf_iff)

lemma inf_mono: "a \<sqsubseteq> c \<Longrightarrow> b \<sqsubseteq> d \<Longrightarrow> a \<sqinter> b \<sqsubseteq> c \<sqinter> d"
  by (fast intro: inf_greatest le_infI1 le_infI2)

lemma mono_inf:
  fixes f :: "'a \<Rightarrow> 'b\<Colon>semilattice_inf"
  shows "mono f \<Longrightarrow> f (A \<sqinter> B) \<sqsubseteq> f A \<sqinter> f B"
  by (auto simp add: mono_def intro: Lattices.inf_greatest)

end

context semilattice_sup
begin

lemma le_supI1:
  "x \<sqsubseteq> a \<Longrightarrow> x \<sqsubseteq> a \<squnion> b"
  by (rule order_trans) auto

lemma le_supI2:
  "x \<sqsubseteq> b \<Longrightarrow> x \<sqsubseteq> a \<squnion> b"
  by (rule order_trans) auto

lemma le_supI:
  "a \<sqsubseteq> x \<Longrightarrow> b \<sqsubseteq> x \<Longrightarrow> a \<squnion> b \<sqsubseteq> x"
  by (fact sup_least) (* FIXME: duplicate lemma *)

lemma le_supE:
  "a \<squnion> b \<sqsubseteq> x \<Longrightarrow> (a \<sqsubseteq> x \<Longrightarrow> b \<sqsubseteq> x \<Longrightarrow> P) \<Longrightarrow> P"
  by (blast intro: order_trans sup_ge1 sup_ge2)

lemma le_sup_iff:
  "x \<squnion> y \<sqsubseteq> z \<longleftrightarrow> x \<sqsubseteq> z \<and> y \<sqsubseteq> z"
  by (blast intro: le_supI elim: le_supE)

lemma le_iff_sup:
  "x \<sqsubseteq> y \<longleftrightarrow> x \<squnion> y = y"
  by (auto intro: le_supI2 antisym dest: eq_iff [THEN iffD1] simp add: le_sup_iff)

lemma sup_mono: "a \<sqsubseteq> c \<Longrightarrow> b \<sqsubseteq> d \<Longrightarrow> a \<squnion> b \<sqsubseteq> c \<squnion> d"
  by (fast intro: sup_least le_supI1 le_supI2)

lemma mono_sup:
  fixes f :: "'a \<Rightarrow> 'b\<Colon>semilattice_sup"
  shows "mono f \<Longrightarrow> f A \<squnion> f B \<sqsubseteq> f (A \<squnion> B)"
  by (auto simp add: mono_def intro: Lattices.sup_least)

end

subsubsection {* Equational laws *}

context semilattice_inf
begin

sublocale inf!: semilattice inf
proof
  fix a b c
  show "(a \<sqinter> b) \<sqinter> c = a \<sqinter> (b \<sqinter> c)"
    by (rule antisym) (auto intro: le_infI1 le_infI2 simp add: le_inf_iff)
  show "a \<sqinter> b = b \<sqinter> a"
    by (rule antisym) (auto simp add: le_inf_iff)
  show "a \<sqinter> a = a"
    by (rule antisym) (auto simp add: le_inf_iff)
qed

sublocale inf!: semilattice_order inf less_eq less
  by default (auto simp add: le_iff_inf less_le)

lemma inf_assoc: "(x \<sqinter> y) \<sqinter> z = x \<sqinter> (y \<sqinter> z)"
  by (fact inf.assoc)

lemma inf_commute: "(x \<sqinter> y) = (y \<sqinter> x)"
  by (fact inf.commute)

lemma inf_left_commute: "x \<sqinter> (y \<sqinter> z) = y \<sqinter> (x \<sqinter> z)"
  by (fact inf.left_commute)

lemma inf_idem: "x \<sqinter> x = x"
  by (fact inf.idem) (* already simp *)

lemma inf_left_idem: "x \<sqinter> (x \<sqinter> y) = x \<sqinter> y"
  by (fact inf.left_idem) (* already simp *)

lemma inf_right_idem: "(x \<sqinter> y) \<sqinter> y = x \<sqinter> y"
  by (fact inf.right_idem) (* already simp *)

lemma inf_absorb1: "x \<sqsubseteq> y \<Longrightarrow> x \<sqinter> y = x"
  by (rule antisym) auto

lemma inf_absorb2: "y \<sqsubseteq> x \<Longrightarrow> x \<sqinter> y = y"
  by (rule antisym) auto

lemmas inf_aci = inf_commute inf_assoc inf_left_commute inf_left_idem

end

context semilattice_sup
begin

sublocale sup!: semilattice sup
proof
  fix a b c
  show "(a \<squnion> b) \<squnion> c = a \<squnion> (b \<squnion> c)"
    by (rule antisym) (auto intro: le_supI1 le_supI2 simp add: le_sup_iff)
  show "a \<squnion> b = b \<squnion> a"
    by (rule antisym) (auto simp add: le_sup_iff)
  show "a \<squnion> a = a"
    by (rule antisym) (auto simp add: le_sup_iff)
qed

sublocale sup!: semilattice_order sup greater_eq greater
  by default (auto simp add: le_iff_sup sup.commute less_le)

lemma sup_assoc: "(x \<squnion> y) \<squnion> z = x \<squnion> (y \<squnion> z)"
  by (fact sup.assoc)

lemma sup_commute: "(x \<squnion> y) = (y \<squnion> x)"
  by (fact sup.commute)

lemma sup_left_commute: "x \<squnion> (y \<squnion> z) = y \<squnion> (x \<squnion> z)"
  by (fact sup.left_commute)

lemma sup_idem: "x \<squnion> x = x"
  by (fact sup.idem) (* already simp *)

lemma sup_left_idem [simp]: "x \<squnion> (x \<squnion> y) = x \<squnion> y"
  by (fact sup.left_idem)

lemma sup_absorb1: "y \<sqsubseteq> x \<Longrightarrow> x \<squnion> y = x"
  by (rule antisym) auto

lemma sup_absorb2: "x \<sqsubseteq> y \<Longrightarrow> x \<squnion> y = y"
  by (rule antisym) auto

lemmas sup_aci = sup_commute sup_assoc sup_left_commute sup_left_idem

end

context lattice
begin

lemma dual_lattice:
  "class.lattice sup (op \<ge>) (op >) inf"
  by (rule class.lattice.intro, rule dual_semilattice, rule class.semilattice_sup.intro, rule dual_order)
    (unfold_locales, auto)

lemma inf_sup_absorb [simp]: "x \<sqinter> (x \<squnion> y) = x"
  by (blast intro: antisym inf_le1 inf_greatest sup_ge1)

lemma sup_inf_absorb [simp]: "x \<squnion> (x \<sqinter> y) = x"
  by (blast intro: antisym sup_ge1 sup_least inf_le1)

lemmas inf_sup_aci = inf_aci sup_aci

lemmas inf_sup_ord = inf_le1 inf_le2 sup_ge1 sup_ge2

text{* Towards distributivity *}

lemma distrib_sup_le: "x \<squnion> (y \<sqinter> z) \<sqsubseteq> (x \<squnion> y) \<sqinter> (x \<squnion> z)"
  by (auto intro: le_infI1 le_infI2 le_supI1 le_supI2)

lemma distrib_inf_le: "(x \<sqinter> y) \<squnion> (x \<sqinter> z) \<sqsubseteq> x \<sqinter> (y \<squnion> z)"
  by (auto intro: le_infI1 le_infI2 le_supI1 le_supI2)

text{* If you have one of them, you have them all. *}

lemma distrib_imp1:
assumes D: "!!x y z. x \<sqinter> (y \<squnion> z) = (x \<sqinter> y) \<squnion> (x \<sqinter> z)"
shows "x \<squnion> (y \<sqinter> z) = (x \<squnion> y) \<sqinter> (x \<squnion> z)"
proof-
  have "x \<squnion> (y \<sqinter> z) = (x \<squnion> (x \<sqinter> z)) \<squnion> (y \<sqinter> z)" by simp
  also have "\<dots> = x \<squnion> (z \<sqinter> (x \<squnion> y))"
    by (simp add: D inf_commute sup_assoc del: sup_inf_absorb)
  also have "\<dots> = ((x \<squnion> y) \<sqinter> x) \<squnion> ((x \<squnion> y) \<sqinter> z)"
    by(simp add: inf_commute)
  also have "\<dots> = (x \<squnion> y) \<sqinter> (x \<squnion> z)" by(simp add:D)
  finally show ?thesis .
qed

lemma distrib_imp2:
assumes D: "!!x y z. x \<squnion> (y \<sqinter> z) = (x \<squnion> y) \<sqinter> (x \<squnion> z)"
shows "x \<sqinter> (y \<squnion> z) = (x \<sqinter> y) \<squnion> (x \<sqinter> z)"
proof-
  have "x \<sqinter> (y \<squnion> z) = (x \<sqinter> (x \<squnion> z)) \<sqinter> (y \<squnion> z)" by simp
  also have "\<dots> = x \<sqinter> (z \<squnion> (x \<sqinter> y))"
    by (simp add: D sup_commute inf_assoc del: inf_sup_absorb)
  also have "\<dots> = ((x \<sqinter> y) \<squnion> x) \<sqinter> ((x \<sqinter> y) \<squnion> z)"
    by(simp add: sup_commute)
  also have "\<dots> = (x \<sqinter> y) \<squnion> (x \<sqinter> z)" by(simp add:D)
  finally show ?thesis .
qed

end

subsubsection {* Strict order *}

context semilattice_inf
begin

lemma less_infI1:
  "a \<sqsubset> x \<Longrightarrow> a \<sqinter> b \<sqsubset> x"
  by (auto simp add: less_le inf_absorb1 intro: le_infI1)

lemma less_infI2:
  "b \<sqsubset> x \<Longrightarrow> a \<sqinter> b \<sqsubset> x"
  by (auto simp add: less_le inf_absorb2 intro: le_infI2)

end

context semilattice_sup
begin

lemma less_supI1:
  "x \<sqsubset> a \<Longrightarrow> x \<sqsubset> a \<squnion> b"
  using dual_semilattice
  by (rule semilattice_inf.less_infI1)

lemma less_supI2:
  "x \<sqsubset> b \<Longrightarrow> x \<sqsubset> a \<squnion> b"
  using dual_semilattice
  by (rule semilattice_inf.less_infI2)

end

subsection {* Distributive lattices *}

class distrib_lattice = lattice +
  assumes sup_inf_distrib1: "x \<squnion> (y \<sqinter> z) = (x \<squnion> y) \<sqinter> (x \<squnion> z)"

context distrib_lattice
begin

lemma sup_inf_distrib2:
  "(y \<sqinter> z) \<squnion> x = (y \<squnion> x) \<sqinter> (z \<squnion> x)"
  by (simp add: sup_commute sup_inf_distrib1)

lemma inf_sup_distrib1:
  "x \<sqinter> (y \<squnion> z) = (x \<sqinter> y) \<squnion> (x \<sqinter> z)"
  by (rule distrib_imp2 [OF sup_inf_distrib1])

lemma inf_sup_distrib2:
  "(y \<squnion> z) \<sqinter> x = (y \<sqinter> x) \<squnion> (z \<sqinter> x)"
  by (simp add: inf_commute inf_sup_distrib1)

lemma dual_distrib_lattice:
  "class.distrib_lattice sup (op \<ge>) (op >) inf"
  by (rule class.distrib_lattice.intro, rule dual_lattice)
    (unfold_locales, fact inf_sup_distrib1)

lemmas sup_inf_distrib =
  sup_inf_distrib1 sup_inf_distrib2

lemmas inf_sup_distrib =
  inf_sup_distrib1 inf_sup_distrib2

lemmas distrib =
  sup_inf_distrib1 sup_inf_distrib2 inf_sup_distrib1 inf_sup_distrib2

end

subsection {* Bounded lattices and boolean algebras *}

class bounded_semilattice_inf_top = semilattice_inf + order_top
begin

sublocale inf_top!: semilattice_neutr inf top
  + inf_top!: semilattice_neutr_order inf top less_eq less
proof
  fix x
  show "x \<sqinter> \<top> = x"
    by (rule inf_absorb1) simp
qed

end

class bounded_semilattice_sup_bot = semilattice_sup + order_bot
begin

sublocale sup_bot!: semilattice_neutr sup bot
  + sup_bot!: semilattice_neutr_order sup bot greater_eq greater
proof
  fix x
  show "x \<squnion> \<bottom> = x"
    by (rule sup_absorb1) simp
qed

end

class bounded_lattice_bot = lattice + order_bot
begin

subclass bounded_semilattice_sup_bot ..

lemma inf_bot_left [simp]:
  "\<bottom> \<sqinter> x = \<bottom>"
  by (rule inf_absorb1) simp

lemma inf_bot_right [simp]:
  "x \<sqinter> \<bottom> = \<bottom>"
  by (rule inf_absorb2) simp

lemma sup_bot_left:
  "\<bottom> \<squnion> x = x"
  by (fact sup_bot.left_neutral)

lemma sup_bot_right:
  "x \<squnion> \<bottom> = x"
  by (fact sup_bot.right_neutral)

lemma sup_eq_bot_iff [simp]:
  "x \<squnion> y = \<bottom> \<longleftrightarrow> x = \<bottom> \<and> y = \<bottom>"
  by (simp add: eq_iff)

lemma bot_eq_sup_iff [simp]:
  "\<bottom> = x \<squnion> y \<longleftrightarrow> x = \<bottom> \<and> y = \<bottom>"
  by (simp add: eq_iff)

end

class bounded_lattice_top = lattice + order_top
begin

subclass bounded_semilattice_inf_top ..

lemma sup_top_left [simp]:
  "\<top> \<squnion> x = \<top>"
  by (rule sup_absorb1) simp

lemma sup_top_right [simp]:
  "x \<squnion> \<top> = \<top>"
  by (rule sup_absorb2) simp

lemma inf_top_left:
  "\<top> \<sqinter> x = x"
  by (fact inf_top.left_neutral)

lemma inf_top_right:
  "x \<sqinter> \<top> = x"
  by (fact inf_top.right_neutral)

lemma inf_eq_top_iff [simp]:
  "x \<sqinter> y = \<top> \<longleftrightarrow> x = \<top> \<and> y = \<top>"
  by (simp add: eq_iff)

end

class bounded_lattice = lattice + order_bot + order_top
begin

subclass bounded_lattice_bot ..
subclass bounded_lattice_top ..

lemma dual_bounded_lattice:
  "class.bounded_lattice sup greater_eq greater inf \<top> \<bottom>"
  by unfold_locales (auto simp add: less_le_not_le)

end

class boolean_algebra = distrib_lattice + bounded_lattice + minus + uminus +
  assumes inf_compl_bot: "x \<sqinter> - x = \<bottom>"
    and sup_compl_top: "x \<squnion> - x = \<top>"
  assumes diff_eq: "x - y = x \<sqinter> - y"
begin

lemma dual_boolean_algebra:
  "class.boolean_algebra (\<lambda>x y. x \<squnion> - y) uminus sup greater_eq greater inf \<top> \<bottom>"
  by (rule class.boolean_algebra.intro, rule dual_bounded_lattice, rule dual_distrib_lattice)
    (unfold_locales, auto simp add: inf_compl_bot sup_compl_top diff_eq)

lemma compl_inf_bot [simp]:
  "- x \<sqinter> x = \<bottom>"
  by (simp add: inf_commute inf_compl_bot)

lemma compl_sup_top [simp]:
  "- x \<squnion> x = \<top>"
  by (simp add: sup_commute sup_compl_top)

lemma compl_unique:
  assumes "x \<sqinter> y = \<bottom>"
    and "x \<squnion> y = \<top>"
  shows "- x = y"
proof -
  have "(x \<sqinter> - x) \<squnion> (- x \<sqinter> y) = (x \<sqinter> y) \<squnion> (- x \<sqinter> y)"
    using inf_compl_bot assms(1) by simp
  then have "(- x \<sqinter> x) \<squnion> (- x \<sqinter> y) = (y \<sqinter> x) \<squnion> (y \<sqinter> - x)"
    by (simp add: inf_commute)
  then have "- x \<sqinter> (x \<squnion> y) = y \<sqinter> (x \<squnion> - x)"
    by (simp add: inf_sup_distrib1)
  then have "- x \<sqinter> \<top> = y \<sqinter> \<top>"
    using sup_compl_top assms(2) by simp
  then show "- x = y" by simp
qed

lemma double_compl [simp]:
  "- (- x) = x"
  using compl_inf_bot compl_sup_top by (rule compl_unique)

lemma compl_eq_compl_iff [simp]:
  "- x = - y \<longleftrightarrow> x = y"
proof
  assume "- x = - y"
  then have "- (- x) = - (- y)" by (rule arg_cong)
  then show "x = y" by simp
next
  assume "x = y"
  then show "- x = - y" by simp
qed

lemma compl_bot_eq [simp]:
  "- \<bottom> = \<top>"
proof -
  from sup_compl_top have "\<bottom> \<squnion> - \<bottom> = \<top>" .
  then show ?thesis by simp
qed

lemma compl_top_eq [simp]:
  "- \<top> = \<bottom>"
proof -
  from inf_compl_bot have "\<top> \<sqinter> - \<top> = \<bottom>" .
  then show ?thesis by simp
qed

lemma compl_inf [simp]:
  "- (x \<sqinter> y) = - x \<squnion> - y"
proof (rule compl_unique)
  have "(x \<sqinter> y) \<sqinter> (- x \<squnion> - y) = (y \<sqinter> (x \<sqinter> - x)) \<squnion> (x \<sqinter> (y \<sqinter> - y))"
    by (simp only: inf_sup_distrib inf_aci)
  then show "(x \<sqinter> y) \<sqinter> (- x \<squnion> - y) = \<bottom>"
    by (simp add: inf_compl_bot)
next
  have "(x \<sqinter> y) \<squnion> (- x \<squnion> - y) = (- y \<squnion> (x \<squnion> - x)) \<sqinter> (- x \<squnion> (y \<squnion> - y))"
    by (simp only: sup_inf_distrib sup_aci)
  then show "(x \<sqinter> y) \<squnion> (- x \<squnion> - y) = \<top>"
    by (simp add: sup_compl_top)
qed

lemma compl_sup [simp]:
  "- (x \<squnion> y) = - x \<sqinter> - y"
  using dual_boolean_algebra
  by (rule boolean_algebra.compl_inf)

lemma compl_mono:
  "x \<sqsubseteq> y \<Longrightarrow> - y \<sqsubseteq> - x"
proof -
  assume "x \<sqsubseteq> y"
  then have "x \<squnion> y = y" by (simp only: le_iff_sup)
  then have "- (x \<squnion> y) = - y" by simp
  then have "- x \<sqinter> - y = - y" by simp
  then have "- y \<sqinter> - x = - y" by (simp only: inf_commute)
  then show "- y \<sqsubseteq> - x" by (simp only: le_iff_inf)
qed

lemma compl_le_compl_iff [simp]:
  "- x \<sqsubseteq> - y \<longleftrightarrow> y \<sqsubseteq> x"
  by (auto dest: compl_mono)

lemma compl_le_swap2:
  assumes "- y \<sqsubseteq> x" shows "- x \<sqsubseteq> y"
proof -
  from assms have "- x \<sqsubseteq> - (- y)" by (simp only: compl_le_compl_iff)
  then show ?thesis by simp
qed

lemma compl_less_compl_iff: (* TODO: declare [simp] ? *)
  "- x \<sqsubset> - y \<longleftrightarrow> y \<sqsubset> x"
  by (auto simp add: less_le)

lemma compl_less_swap1:
  assumes "y \<sqsubset> - x" shows "x \<sqsubset> - y"
proof -
  from assms have "- (- x) \<sqsubset> - y" by (simp only: compl_less_compl_iff)
  then show ?thesis by simp
qed

lemma compl_less_swap2:
  assumes "- y \<sqsubset> x" shows "- x \<sqsubset> y"
proof -
  from assms have "- x \<sqsubset> - (- y)" by (simp only: compl_less_compl_iff)
  then show ?thesis by simp
qed

end

subsection {* @{text "min/max"} as special case of lattice *}

context linorder
begin

sublocale min!: semilattice_order min less_eq less
  + max!: semilattice_order max greater_eq greater
  by default (auto simp add: min_def max_def)

lemma min_le_iff_disj:
  "min x y \<le> z \<longleftrightarrow> x \<le> z \<or> y \<le> z"
  unfolding min_def using linear by (auto intro: order_trans)

lemma le_max_iff_disj:
  "z \<le> max x y \<longleftrightarrow> z \<le> x \<or> z \<le> y"
  unfolding max_def using linear by (auto intro: order_trans)

lemma min_less_iff_disj:
  "min x y < z \<longleftrightarrow> x < z \<or> y < z"
  unfolding min_def le_less using less_linear by (auto intro: less_trans)

lemma less_max_iff_disj:
  "z < max x y \<longleftrightarrow> z < x \<or> z < y"
  unfolding max_def le_less using less_linear by (auto intro: less_trans)

lemma min_less_iff_conj [simp]:
  "z < min x y \<longleftrightarrow> z < x \<and> z < y"
  unfolding min_def le_less using less_linear by (auto intro: less_trans)

lemma max_less_iff_conj [simp]:
  "max x y < z \<longleftrightarrow> x < z \<and> y < z"
  unfolding max_def le_less using less_linear by (auto intro: less_trans)

lemma min_max_distrib1:
  "min (max b c) a = max (min b a) (min c a)"
  by (auto simp add: min_def max_def not_le dest: le_less_trans less_trans intro: antisym)

lemma min_max_distrib2:
  "min a (max b c) = max (min a b) (min a c)"
  by (auto simp add: min_def max_def not_le dest: le_less_trans less_trans intro: antisym)

lemma max_min_distrib1:
  "max (min b c) a = min (max b a) (max c a)"
  by (auto simp add: min_def max_def not_le dest: le_less_trans less_trans intro: antisym)

lemma max_min_distrib2:
  "max a (min b c) = min (max a b) (max a c)"
  by (auto simp add: min_def max_def not_le dest: le_less_trans less_trans intro: antisym)

lemmas min_max_distribs = min_max_distrib1 min_max_distrib2 max_min_distrib1 max_min_distrib2

lemma split_min [no_atp]:
  "P (min i j) \<longleftrightarrow> (i \<le> j \<longrightarrow> P i) \<and> (\<not> i \<le> j \<longrightarrow> P j)"
  by (simp add: min_def)

lemma split_max [no_atp]:
  "P (max i j) \<longleftrightarrow> (i \<le> j \<longrightarrow> P j) \<and> (\<not> i \<le> j \<longrightarrow> P i)"
  by (simp add: max_def)

lemma min_of_mono:
  fixes f :: "'a \<Rightarrow> 'b\<Colon>linorder"
  shows "mono f \<Longrightarrow> min (f m) (f n) = f (min m n)"
  by (auto simp: mono_def Orderings.min_def min_def intro: Orderings.antisym)

lemma max_of_mono:
  fixes f :: "'a \<Rightarrow> 'b\<Colon>linorder"
  shows "mono f \<Longrightarrow> max (f m) (f n) = f (max m n)"
  by (auto simp: mono_def Orderings.max_def max_def intro: Orderings.antisym)

end

lemma inf_min: "inf = (min \<Colon> 'a\<Colon>{semilattice_inf, linorder} \<Rightarrow> 'a \<Rightarrow> 'a)"
  by (auto intro: antisym simp add: min_def fun_eq_iff)

lemma sup_max: "sup = (max \<Colon> 'a\<Colon>{semilattice_sup, linorder} \<Rightarrow> 'a \<Rightarrow> 'a)"
  by (auto intro: antisym simp add: max_def fun_eq_iff)

subsection {* Uniqueness of inf and sup *}

lemma (in semilattice_inf) inf_unique:
  fixes f (infixl "\<triangle>" 70)
  assumes le1: "\<And>x y. x \<triangle> y \<sqsubseteq> x" and le2: "\<And>x y. x \<triangle> y \<sqsubseteq> y"
  and greatest: "\<And>x y z. x \<sqsubseteq> y \<Longrightarrow> x \<sqsubseteq> z \<Longrightarrow> x \<sqsubseteq> y \<triangle> z"
  shows "x \<sqinter> y = x \<triangle> y"
proof (rule antisym)
  show "x \<triangle> y \<sqsubseteq> x \<sqinter> y" by (rule le_infI) (rule le1, rule le2)
next
  have leI: "\<And>x y z. x \<sqsubseteq> y \<Longrightarrow> x \<sqsubseteq> z \<Longrightarrow> x \<sqsubseteq> y \<triangle> z" by (blast intro: greatest)
  show "x \<sqinter> y \<sqsubseteq> x \<triangle> y" by (rule leI) simp_all
qed

lemma (in semilattice_sup) sup_unique:
  fixes f (infixl "\<nabla>" 70)
  assumes ge1 [simp]: "\<And>x y. x \<sqsubseteq> x \<nabla> y" and ge2: "\<And>x y. y \<sqsubseteq> x \<nabla> y"
  and least: "\<And>x y z. y \<sqsubseteq> x \<Longrightarrow> z \<sqsubseteq> x \<Longrightarrow> y \<nabla> z \<sqsubseteq> x"
  shows "x \<squnion> y = x \<nabla> y"
proof (rule antisym)
  show "x \<squnion> y \<sqsubseteq> x \<nabla> y" by (rule le_supI) (rule ge1, rule ge2)
next
  have leI: "\<And>x y z. x \<sqsubseteq> z \<Longrightarrow> y \<sqsubseteq> z \<Longrightarrow> x \<nabla> y \<sqsubseteq> z" by (blast intro: least)
  show "x \<nabla> y \<sqsubseteq> x \<squnion> y" by (rule leI) simp_all
qed

subsection {* Lattice on @{typ bool} *}

instantiation bool :: boolean_algebra
begin

definition
  bool_Compl_def [simp]: "uminus = Not"

definition
  bool_diff_def [simp]: "A - B \<longleftrightarrow> A \<and> \<not> B"

definition
  [simp]: "P \<sqinter> Q \<longleftrightarrow> P \<and> Q"

definition
  [simp]: "P \<squnion> Q \<longleftrightarrow> P \<or> Q"

instance proof
qed auto

end

lemma sup_boolI1:
  "P \<Longrightarrow> P \<squnion> Q"
  by simp

lemma sup_boolI2:
  "Q \<Longrightarrow> P \<squnion> Q"
  by simp

lemma sup_boolE:
  "P \<squnion> Q \<Longrightarrow> (P \<Longrightarrow> R) \<Longrightarrow> (Q \<Longrightarrow> R) \<Longrightarrow> R"
  by auto

subsection {* Lattice on @{typ "_ \<Rightarrow> _"} *}

instantiation "fun" :: (type, semilattice_sup) semilattice_sup
begin

definition
  "f \<squnion> g = (\<lambda>x. f x \<squnion> g x)"

lemma sup_apply [simp, code]:
  "(f \<squnion> g) x = f x \<squnion> g x"
  by (simp add: sup_fun_def)

instance proof
qed (simp_all add: le_fun_def)

end

instantiation "fun" :: (type, semilattice_inf) semilattice_inf
begin

definition
  "f \<sqinter> g = (\<lambda>x. f x \<sqinter> g x)"

lemma inf_apply [simp, code]:
  "(f \<sqinter> g) x = f x \<sqinter> g x"
  by (simp add: inf_fun_def)

instance proof
qed (simp_all add: le_fun_def)

end

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

instance "fun" :: (type, distrib_lattice) distrib_lattice proof
qed (rule ext, simp add: sup_inf_distrib1)

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

instantiation "fun" :: (type, uminus) uminus
begin

definition
  fun_Compl_def: "- A = (\<lambda>x. - A x)"

lemma uminus_apply [simp, code]:
  "(- A) x = - (A x)"
  by (simp add: fun_Compl_def)

instance ..

end

instantiation "fun" :: (type, minus) minus
begin

definition
  fun_diff_def: "A - B = (\<lambda>x. A x - B x)"

lemma minus_apply [simp, code]:
  "(A - B) x = A x - B x"
  by (simp add: fun_diff_def)

instance ..

end

instance "fun" :: (type, boolean_algebra) boolean_algebra proof
qed (rule ext, simp_all add: inf_compl_bot sup_compl_top diff_eq)+

subsection {* Lattice on unary and binary predicates *}

lemma inf1I: "A x \<Longrightarrow> B x \<Longrightarrow> (A \<sqinter> B) x"
  by (simp add: inf_fun_def)

lemma inf2I: "A x y \<Longrightarrow> B x y \<Longrightarrow> (A \<sqinter> B) x y"
  by (simp add: inf_fun_def)

lemma inf1E: "(A \<sqinter> B) x \<Longrightarrow> (A x \<Longrightarrow> B x \<Longrightarrow> P) \<Longrightarrow> P"
  by (simp add: inf_fun_def)

lemma inf2E: "(A \<sqinter> B) x y \<Longrightarrow> (A x y \<Longrightarrow> B x y \<Longrightarrow> P) \<Longrightarrow> P"
  by (simp add: inf_fun_def)

lemma inf1D1: "(A \<sqinter> B) x \<Longrightarrow> A x"
  by (rule inf1E)

lemma inf2D1: "(A \<sqinter> B) x y \<Longrightarrow> A x y"
  by (rule inf2E)

lemma inf1D2: "(A \<sqinter> B) x \<Longrightarrow> B x"
  by (rule inf1E)

lemma inf2D2: "(A \<sqinter> B) x y \<Longrightarrow> B x y"
  by (rule inf2E)

lemma sup1I1: "A x \<Longrightarrow> (A \<squnion> B) x"
  by (simp add: sup_fun_def)

lemma sup2I1: "A x y \<Longrightarrow> (A \<squnion> B) x y"
  by (simp add: sup_fun_def)

lemma sup1I2: "B x \<Longrightarrow> (A \<squnion> B) x"
  by (simp add: sup_fun_def)

lemma sup2I2: "B x y \<Longrightarrow> (A \<squnion> B) x y"
  by (simp add: sup_fun_def)

lemma sup1E: "(A \<squnion> B) x \<Longrightarrow> (A x \<Longrightarrow> P) \<Longrightarrow> (B x \<Longrightarrow> P) \<Longrightarrow> P"
  by (simp add: sup_fun_def) iprover

lemma sup2E: "(A \<squnion> B) x y \<Longrightarrow> (A x y \<Longrightarrow> P) \<Longrightarrow> (B x y \<Longrightarrow> P) \<Longrightarrow> P"
  by (simp add: sup_fun_def) iprover

text {*
  \medskip Classical introduction rule: no commitment to @{text A} vs
  @{text B}.
*}

lemma sup1CI: "(\<not> B x \<Longrightarrow> A x) \<Longrightarrow> (A \<squnion> B) x"
  by (auto simp add: sup_fun_def)

lemma sup2CI: "(\<not> B x y \<Longrightarrow> A x y) \<Longrightarrow> (A \<squnion> B) x y"
  by (auto simp add: sup_fun_def)

no_notation
  less_eq (infix "\<sqsubseteq>" 50) and
  less (infix "\<sqsubset>" 50)

end


(*
    File:     Group_Relations.thy
    Author:   Joseph Thommes, TU München
*)
section \<open>Group relations\<close>

theory Group_Relations
  imports Finite_Product_Extend
begin

text \<open>We introduce the notion of a relation of a set of elements: a way to express the neutral
element by using only powers of said elements. The following predicate describes the set of all the
relations that one can construct from a set of elements.\<close>

definition (in comm_group) relations :: "'a set \<Rightarrow> ('a \<Rightarrow> int) set" where
  "relations A = {f. finprod G (\<lambda>a. a [^] f a) A = \<one>} \<inter> extensional A"

text \<open>Now some basic lemmas about relations.\<close>

lemma (in comm_group) in_relationsI[intro]:
  assumes "finprod G (\<lambda>a. a [^] f a) A = \<one>" "f \<in> extensional A"
  shows "f \<in> relations A"
  unfolding relations_def using assms by blast

lemma (in comm_group) triv_rel:
  "restrict (\<lambda>_. 0::int) A \<in> relations A"
proof
  show "(\<Otimes>a\<in>A. a [^] (\<lambda>_\<in>A. 0::int) a) = \<one>" by (intro finprod_one_eqI, simp)
qed simp

lemma (in comm_group) not_triv_relI:
  assumes "a \<in> A" "f a \<noteq> (0::int)"
  shows "f \<noteq> (\<lambda>_\<in>A. 0::int)"
  using assms by auto

lemma (in comm_group) rel_in_carr:
  assumes "A \<subseteq> carrier G" "r \<in> relations A"
  shows "(\<lambda>a. a [^] r a) \<in> A \<rightarrow> carrier G"
  by (meson Pi_I assms(1) int_pow_closed subsetD)

text \<open>The following lemmas are of importance when proving the fundamental theorem of finitely
generated abelian groups in the case that there is just the trivial relation between a set of
generators. They all build up to the last lemma that then is actually used in the proof.\<close>

lemma (in comm_group) relations_zero_imp_pow_not_one:
  assumes "a \<in> A" "\<forall>f\<in>(relations A). f a = 0"
  shows "\<forall>z::int \<noteq> 0. a [^] z \<noteq> \<one>"
proof (rule ccontr; safe)
  fix z::int
  assume z: "z \<noteq> 0" "a [^] z = \<one>"
  have "restrict ((\<lambda>x. 0)(a := z)) A \<in> relations A"
    by (intro in_relationsI finprod_one_eqI, use z in auto)
  thus False using z assms by auto
qed

lemma (in comm_group) relations_zero_imp_ord_zero:
  assumes "a \<in> A" "\<forall>f\<in>(relations A). f a = 0"
  and "a \<in> carrier G"
  shows "ord a = 0"
  using assms relations_zero_imp_pow_not_one[OF assms(1, 2)]
  by (meson finite_cyclic_subgroup_int infinite_cyclic_subgroup_order)

lemma (in comm_group) finprod_relations_triv_harder_better_stronger:
  assumes "A \<subseteq> carrier G" "relations A = {(\<lambda>_\<in>A. 0::int)}"
  shows "\<forall>f \<in> Pi\<^sub>E A (\<lambda>a. generate G {a}). finprod G f A = \<one> \<longrightarrow> (\<forall>a\<in>A. f a = \<one>)"
proof(rule, rule)
  fix f
  assume f: "f \<in> (\<Pi>\<^sub>E a\<in>A. generate G {a})" "finprod G f A = \<one>"
  with generate_pow assms(1) have "\<forall>a\<in>A. \<exists>k::int. f a = a [^] k" by blast
  then obtain r::"'a \<Rightarrow> int" where r: "\<forall>a\<in>A. f a = a [^] r a" by metis
  have "restrict r A \<in> relations A"
  proof(intro in_relationsI)
    have "(\<Otimes>a\<in>A. a [^] restrict r A a) = finprod G f A"
      by (intro finprod_cong, use assms r in auto)
    thus "(\<Otimes>a\<in>A. a [^] restrict r A a) = \<one>" using f by simp
  qed simp
  with assms(2) have z: "restrict r A = (\<lambda>_\<in>A. 0)" by blast
  have "(restrict r A) a = r a" if "a \<in> A" for a using that by auto
  with r z show "\<forall>a\<in>A. f a = \<one>" by auto
qed

lemma (in comm_group) stronger_PiE_finprod_imp:
  assumes "A \<subseteq> carrier G" "\<forall>f \<in> Pi\<^sub>E A (\<lambda>a. generate G {a}). finprod G f A = \<one> \<longrightarrow> (\<forall>a\<in>A. f a = \<one>)"
  shows "\<forall>f \<in> Pi\<^sub>E ((\<lambda>a. generate G {a}) ` A) id.
         finprod G f ((\<lambda>a. generate G {a}) ` A) = \<one> \<longrightarrow> (\<forall>H\<in> (\<lambda>a. generate G {a}) ` A. f H = \<one>)"
proof(rule, rule)
  fix f
  assume f: "f \<in> Pi\<^sub>E ((\<lambda>a. generate G {a}) ` A) id" "finprod G f ((\<lambda>a. generate G {a}) ` A) = \<one>"
  define B where "B = inv_into A (\<lambda>a. generate G {a}) ` ((\<lambda>a. generate G {a}) ` A)"
  have Bs: "B \<subseteq> A"
  proof
    fix x
    assume x: "x \<in> B"
    then obtain C where C: "C \<in> ((\<lambda>a. generate G {a}) ` A)" "x = inv_into A (\<lambda>a. generate G {a}) C"
      unfolding B_def by blast
    then obtain c where c: "C = generate G {c}" "c \<in> A" by blast
    with C someI_ex[of "\<lambda>y. y \<in> A \<and> generate G {y} = C"] show "x \<in> A"
      unfolding inv_into_def by blast
  qed
  have sI: "(\<lambda>x. generate G {x}) ` B = (\<lambda>x. generate G {x}) ` A"
  proof
    show "(\<lambda>x. generate G {x}) ` B \<subseteq> (\<lambda>x. generate G {x}) ` A" using Bs by blast
    show "(\<lambda>x. generate G {x}) ` A \<subseteq> (\<lambda>x. generate G {x}) ` B"
    proof
      fix C
      assume C: "C \<in> (\<lambda>x. generate G {x}) ` A"
      then obtain x where x: "x = inv_into A (\<lambda>a. generate G {a}) C" unfolding B_def by blast
      then obtain c where c: "C = generate G {c}" "c \<in> A" using C by blast
      with C x someI_ex[of "\<lambda>y. y \<in> A \<and> generate G {y} = C"] have "generate G {x} = C"
        unfolding inv_into_def by blast
      with x C show "C \<in> (\<lambda>x. generate G {x}) ` B" unfolding B_def by blast
    qed
  qed
  have fBc: "f (generate G {b}) \<in> carrier G" if "b \<in> B" for b
  proof -
    have "f (generate G {b}) \<in> generate G {b}" using f(1)
      by (subst (asm) sI[symmetric], use that in fastforce)
    moreover have "generate G {b} \<subseteq> carrier G" using assms(1) that Bs generate_incl by blast
    ultimately show ?thesis by blast
  qed
  let ?r = "restrict (\<lambda>a. if a\<in>B then f (generate G {a}) else \<one>) A"
  have "?r \<in> Pi\<^sub>E A (\<lambda>a. generate G {a})"
  proof
    show "?r x = undefined" if "x \<notin> A" for x using that by simp
    show "?r x \<in> generate G {x}" if "x \<in> A" for x using that generate.one B_def f(1) by auto
  qed
  moreover have "finprod G ?r A = \<one>"
  proof (cases "finite A")
    case True
    have "A = B \<union> (A - B)" using Bs by auto
    then have "finprod G ?r A = finprod G ?r (B\<union>(A-B))" by auto
    moreover have "\<dots> = finprod G ?r B \<otimes> finprod G ?r (A - B)"
    proof(intro finprod_Un_disjoint)
      from True Bs finite_subset show "finite B" "finite (A - B)" "B \<inter> (A - B) = {}" by auto
      show "(\<lambda>a\<in>A. if a \<in> B then f (generate G {a}) else \<one>) \<in> A - B \<rightarrow> carrier G" using Bs by simp
      from fBc show "(\<lambda>a\<in>A. if a \<in> B then f (generate G {a}) else \<one>) \<in> B \<rightarrow> carrier G"
        using Bs by auto
    qed
    moreover have "finprod G ?r B = \<one>"
    proof -
      have "finprod G ?r B = finprod G (f \<circ> (\<lambda>a. generate G {a})) B"
      proof(intro finprod_cong')
        show "?r b = (f \<circ> (\<lambda>a. generate G {a})) b" if "b \<in> B" for b using that Bs by auto
        show "f \<circ> (\<lambda>a. generate G {a}) \<in> B \<rightarrow> carrier G" using fBc by simp
      qed simp
      also have "\<dots> = finprod G f ((\<lambda>a. generate G {a}) ` B)"
      proof(intro finprod_comp[symmetric])
        show "(f \<circ> (\<lambda>a. generate G {a})) ` B \<subseteq> carrier G" using fBc by auto
        show "inj_on (\<lambda>a. generate G {a}) B"
          by (intro inj_onI, unfold B_def, metis (no_types, lifting) f_inv_into_f inv_into_into)
      qed
      also have "\<dots> = finprod G f ((\<lambda>a. generate G {a}) ` A)" using sI by argo
      finally show ?thesis using f(2) by argo
    qed
    moreover have "finprod G ?r (A - B) = \<one>" by(intro finprod_one_eqI, simp)
    ultimately show ?thesis by fastforce
  next
    case False
    then show ?thesis unfolding finprod_def by simp
  qed
  ultimately have a: "\<forall>a\<in>A. ?r a = \<one>" using assms(2) by blast
  then have BA: "\<forall>a\<in>B\<inter>A. ?r a = \<one>" by blast
  from Bs sI have "\<forall>a\<in>A. (generate G {a}) \<in> ((\<lambda>x. generate G {x}) ` B)" by simp
  then have "\<forall>a\<in>A. \<exists>b\<in>B. f (generate G {a}) = f (generate G {b})" by force
  thus "\<forall>H\<in>(\<lambda>a. generate G {a}) ` A. f H = \<one>" using a BA Bs by fastforce
qed

lemma (in comm_group) finprod_relations_triv:
  assumes "A \<subseteq> carrier G" "relations A = {(\<lambda>_\<in>A. 0::int)}"
  shows "\<forall>f \<in> Pi\<^sub>E ((\<lambda>a. generate G {a}) ` A) id.
         finprod G f ((\<lambda>a. generate G {a}) ` A) = \<one> \<longrightarrow> (\<forall>H\<in> (\<lambda>a. generate G {a}) ` A. f H = \<one>)"
  using assms finprod_relations_triv_harder_better_stronger stronger_PiE_finprod_imp by presburger

lemma (in comm_group) ord_zero_strong_imp_rel_triv:
  assumes "A \<subseteq> carrier G" "\<forall>a \<in> A. ord a = 0"
  and "\<forall>f \<in> Pi\<^sub>E A (\<lambda>a. generate G {a}). finprod G f A = \<one> \<longrightarrow> (\<forall>a\<in>A. f a = \<one>)"
  shows "relations A = {(\<lambda>_\<in>A. 0::int)}"
proof -
  have "\<And>r. r \<in> relations A \<Longrightarrow> r = (\<lambda>_\<in>A. 0::int)"
  proof
    fix r x
    assume r: "r \<in> relations A"
    show "r x = (\<lambda>_\<in>A. 0::int) x"
    proof (cases "x \<in> A")
      case True
      let ?r = "restrict (\<lambda>a. a [^] r a) A"
      have rp: "?r \<in> Pi\<^sub>E A (\<lambda>a. generate G {a})"
      proof -
        have "?r \<in> extensional A" by blast
        moreover have "?r \<in> Pi A (\<lambda>a. generate G {a})"
        proof
          fix a
          assume a: "a \<in> A"
          then have sga: "subgroup (generate G {a}) G" using generate_is_subgroup assms(1) by auto
          show "a [^] r a \<in> generate G {a}"
            using generate.incl[of a "{a}" G] subgroup_int_pow_closed[OF sga] by simp
        qed
        ultimately show ?thesis unfolding PiE_def by blast
      qed
      have "finprod G ?r A = (\<Otimes>a\<in>A. a [^] r a)" by(intro finprod_cong, use assms(1) in auto)
      with r have "finprod G ?r A = \<one>" unfolding relations_def by simp
      with assms(3) rp have "\<forall>a\<in>A. ?r a = \<one>" by fast
      then have "\<forall>a\<in>A. a [^] r a = \<one>" by simp
      with assms(1, 2) True have "r x = 0"
        using finite_cyclic_subgroup_int infinite_cyclic_subgroup_order by blast
      thus ?thesis using True by simp
    next
      case False
      thus ?thesis using r unfolding relations_def extensional_def by simp
    qed
  qed
  thus ?thesis using triv_rel by blast
qed

lemma (in comm_group) compl_fam_iff_relations_triv:
  assumes "finite gs" "gs \<subseteq> carrier G" "\<forall>g\<in>gs. ord g = 0"
  shows "relations gs = {(\<lambda>_\<in>gs. 0::int)} \<longleftrightarrow> compl_fam (\<lambda>g. generate G {g}) gs"
  using triv_finprod_iff_compl_fam_PiE[of _ "\<lambda>g. generate G {g}", OF assms(1) generate_is_subgroup]
        ord_zero_strong_imp_rel_triv[OF assms(2, 3)]
        finprod_relations_triv_harder_better_stronger[OF assms(2)] assms by blast

end