(******************************************************************************)
(* Project: Isabelle/UTP Toolkit                                              *)
(* File: Infinity.thy                                                         *)
(* Authors: Frank Zeyda and Simon Foster (University of York, UK)             *)
(* Emails: frank.zeyda@york.ac.uk and simon.foster@york.ac.uk                 *)
(******************************************************************************)

section \<open> Infinity Supplement \<close>

theory Infinity
imports HOL.Real
  "HOL-Library.Infinite_Set"
  "Optics.Two"
begin

text \<open>
  This theory introduces a type class @{text infinite} that guarantees that the
  underlying universe of the type is infinite. It also provides useful theorems
  to prove infinity of the universes for various HOL types.
\<close>

subsection \<open> Type class @{text infinite} \<close>

text \<open>
  The type class postulates that the universe (carrier) of a type is infinite.
\<close>

class infinite =
  assumes infinite_UNIV [simp]: "infinite (UNIV :: 'a set)"

subsection \<open> Infinity Theorems \<close>

text \<open> Useful theorems to prove that a type's @{const UNIV} is infinite. \<close>

text \<open>
  Note that @{thm [source] infinite_UNIV_nat} is already a simplification rule
  by default.
\<close>

lemmas infinite_UNIV_int [simp]

theorem infinite_UNIV_real [simp]:
"infinite (UNIV :: real set)"
  by (rule infinite_UNIV_char_0)

theorem infinite_UNIV_fun1 [simp]:
"infinite (UNIV :: 'a set) \<Longrightarrow>
 card (UNIV :: 'b set) \<noteq> Suc 0 \<Longrightarrow>
 infinite (UNIV :: ('a \<Rightarrow> 'b) set)"
  apply (erule contrapos_nn)
  apply (erule finite_fun_UNIVD1)
  apply (assumption)
  done

theorem infinite_UNIV_fun2 [simp]:
"infinite (UNIV :: 'b set) \<Longrightarrow>
 infinite (UNIV :: ('a \<Rightarrow> 'b) set)"
  apply (erule contrapos_nn)
  apply (erule finite_fun_UNIVD2)
  done

theorem infinite_UNIV_set [simp]:
"infinite (UNIV :: 'a set) \<Longrightarrow>
 infinite (UNIV :: 'a set set)"
  apply (erule contrapos_nn)
  apply (simp add: Finite_Set.finite_set)
  done

theorem infinite_UNIV_prod1 [simp]:
"infinite (UNIV :: 'a set) \<Longrightarrow>
 infinite (UNIV :: ('a \<times> 'b) set)"
  apply (erule contrapos_nn)
  apply (simp add: finite_prod)
  done

theorem infinite_UNIV_prod2 [simp]:
"infinite (UNIV :: 'b set) \<Longrightarrow>
 infinite (UNIV :: ('a \<times> 'b) set)"
  apply (erule contrapos_nn)
  apply (simp add: finite_prod)
  done

theorem infinite_UNIV_sum1 [simp]:
"infinite (UNIV :: 'a set) \<Longrightarrow>
 infinite (UNIV :: ('a + 'b) set)"
  apply (erule contrapos_nn)
  apply (simp)
  done

theorem infinite_UNIV_sum2 [simp]:
"infinite (UNIV :: 'b set) \<Longrightarrow>
 infinite (UNIV :: ('a + 'b) set)"
  apply (erule contrapos_nn)
  apply (simp)
  done

theorem infinite_UNIV_option [simp]:
"infinite (UNIV :: 'a set) \<Longrightarrow>
 infinite (UNIV :: 'a option set)"
  apply (erule contrapos_nn)
  apply (simp)
  done

theorem infinite_image [intro]:
"infinite A \<Longrightarrow> inj_on f A \<Longrightarrow> infinite (f ` A)"
  apply (metis finite_imageD)
  done

theorem infinite_transfer (*[intro]*) :
"infinite B \<Longrightarrow> B \<subseteq> f ` A \<Longrightarrow> infinite A"
  using infinite_super
  apply (blast)
  done

subsection \<open> Instantiations \<close>

text \<open>
  The instantiations for product and sum types have stronger caveats than in
  principle needed. Namely, it would be sufficient for one type of a product
  or sum to be infinite. A corresponding rule, however, cannot be formulated
  using type classes. Generally, classes are not entirely adequate for the
  purpose of deriving the infinity of HOL types, which is perhaps why a class
  such as @{class infinite} was omitted from the Isabelle/HOL library.
\<close>

instance nat :: infinite by (intro_classes, simp)
instance int :: infinite by (intro_classes, simp)
instance real :: infinite by (intro_classes, simp)
instance "fun" :: (type, infinite) infinite by (intro_classes, simp)
instance set :: (infinite) infinite by (intro_classes, simp)
instance prod :: (infinite, infinite) infinite by (intro_classes, simp)
instance sum :: (infinite, infinite) infinite by (intro_classes, simp)
instance list :: (type) infinite by (intro_classes, simp)
instance option :: (infinite) infinite by (intro_classes, simp)

subclass (in infinite) two  by (intro_classes, auto)

end


(*  Title:      HOL/Corec_Examples/LFilter.thy
    Author:     Andreas Lochbihler, ETH Zuerich
    Author:     Dmitriy Traytel, ETH Zuerich
    Author:     Andrei Popescu, TU Muenchen
    Copyright   2014, 2016

The filter function on lazy lists.
*)

section \<open>The Filter Function on Lazy Lists\<close>

theory LFilter
imports "~~/src/HOL/Library/BNF_Corec"
begin

codatatype (lset: 'a) llist =
  LNil
| LCons (lhd: 'a) (ltl: "'a llist")

corecursive lfilter where
  "lfilter P xs = (if \<forall>x \<in> lset xs. \<not> P x then
    LNil
    else if P (lhd xs) then
      LCons (lhd xs) (lfilter P (ltl xs))
    else
      lfilter P (ltl xs))"
proof (relation "measure (\<lambda>(P, xs). LEAST n. P (lhd ((ltl ^^ n) xs)))", rule wf_measure, clarsimp)
  fix P xs x
  assume "x \<in> lset xs" "P x" "\<not> P (lhd xs)"
  from this(1,2) obtain a where "P (lhd ((ltl ^^ a) xs))"
    by (atomize_elim, induct x xs rule: llist.set_induct)
       (auto simp: funpow_Suc_right simp del: funpow.simps(2) intro: exI[of _ 0] exI[of _ "Suc i" for i])
  with \<open>\<not> P (lhd xs)\<close>
    have "(LEAST n. P (lhd ((ltl ^^ n) xs))) = Suc (LEAST n. P (lhd ((ltl ^^ Suc n) xs)))"
    by (intro Least_Suc) auto
  then show "(LEAST n. P (lhd ((ltl ^^ n) (ltl xs)))) < (LEAST n. P (lhd ((ltl ^^ n) xs)))"
    by (simp add: funpow_swap1[of ltl])
qed

lemma lfilter_LNil [simp]: "lfilter P LNil = LNil"
  by(simp add: lfilter.code)

lemma lnull_lfilter [simp]: "lfilter P xs = LNil \<longleftrightarrow> (\<forall>x \<in> lset xs. \<not> P x)"
proof(rule iffI ballI)+
  show "\<not> P x" if "x \<in> lset xs" "lfilter P xs = LNil" for x using that
    by(induction rule: llist.set_induct)(subst (asm) lfilter.code; auto split: if_split_asm; fail)+
qed(simp add: lfilter.code)

lemma lfilter_LCons [simp]: "lfilter P (LCons x xs) = (if P x then LCons x (lfilter P xs) else lfilter P xs)"
  by(subst lfilter.code)(auto intro: sym)

lemma llist_in_lfilter [simp]: "lset (lfilter P xs) = lset xs \<inter> {x. P x}"
proof(intro set_eqI iffI)
  show "x \<in> lset xs \<inter> {x. P x}" if "x \<in> lset (lfilter P xs)" for x using that
  proof(induction ys\<equiv>"lfilter P xs" arbitrary: xs rule: llist.set_induct)
    case (LCons1 x xs ys)
    from this show ?case
      apply(induction arg\<equiv>"(P, ys)" arbitrary: ys rule: lfilter.inner_induct)
      subgoal by(subst (asm) (2) lfilter.code)(auto split: if_split_asm elim: llist.set_cases)
      done
  next
    case (LCons2 xs y x ys)
    from LCons2(3) LCons2(1) show ?case
      apply(induction arg\<equiv>"(P, ys)" arbitrary: ys rule: lfilter.inner_induct)
      subgoal using LCons2(2) by(subst (asm) (2) lfilter.code)(auto split: if_split_asm elim: llist.set_cases)
      done
  qed
  show "x \<in> lset (lfilter P xs)" if "x \<in> lset xs \<inter> {x. P x}" for x
    using that[THEN IntD1] that[THEN IntD2] by(induction) auto
qed

lemma lfilter_unique_weak:
  "(\<And>xs. f xs = (if \<forall>x \<in> lset xs. \<not> P x then LNil
    else if P (lhd xs) then LCons (lhd xs) (f (ltl xs))
    else lfilter P (ltl xs)))
   \<Longrightarrow> f = lfilter P"
  by(corec_unique)(rule ext lfilter.code)+

lemma lfilter_unique:
  assumes "\<And>xs. f xs = (if \<forall>x\<in>lset xs. \<not> P x then LNil
    else if P (lhd xs) then LCons (lhd xs) (f (ltl xs))
    else f (ltl xs))"
  shows "f = lfilter P"
\<comment> \<open>It seems as if we cannot use @{thm lfilter_unique_weak} for showing this as the induction and the coinduction must be nested\<close>
proof(rule ext)
  show "f xs = lfilter P xs" for xs
  proof(coinduction arbitrary: xs)
    case (Eq_llist xs)
    show ?case
      apply(induction arg\<equiv>"(P, xs)" arbitrary: xs rule: lfilter.inner_induct)
      apply(subst (1 2 3 4) assms)
      apply(subst (1 2 3 4) lfilter.code)
      apply auto
      done
  qed
qed

lemma lfilter_lfilter: "lfilter P \<circ> lfilter Q = lfilter (\<lambda>x. P x \<and> Q x)"
  by(rule lfilter_unique)(auto elim: llist.set_cases)

end


(*  Author: Tobias Nipkow, 2007 *)

section {* Lists as vectors *}

theory ListVector
imports List Main
begin

text{* \noindent
A vector-space like structure of lists and arithmetic operations on them.
Is only a vector space if restricted to lists of the same length. *}

text{* Multiplication with a scalar: *}

abbreviation scale :: "('a::times) \<Rightarrow> 'a list \<Rightarrow> 'a list" (infix "*\<^sub>s" 70)
where "x *\<^sub>s xs \<equiv> map (op * x) xs"

lemma scale1[simp]: "(1::'a::monoid_mult) *\<^sub>s xs = xs"
by (induct xs) simp_all

subsection {* @{text"+"} and @{text"-"} *}

fun zipwith0 :: "('a::zero \<Rightarrow> 'b::zero \<Rightarrow> 'c) \<Rightarrow> 'a list \<Rightarrow> 'b list \<Rightarrow> 'c list"
where
"zipwith0 f [] [] = []" |
"zipwith0 f (x#xs) (y#ys) = f x y # zipwith0 f xs ys" |
"zipwith0 f (x#xs) [] = f x 0 # zipwith0 f xs []" |
"zipwith0 f [] (y#ys) = f 0 y # zipwith0 f [] ys"

instantiation list :: ("{zero, plus}") plus
begin

definition
  list_add_def: "op + = zipwith0 (op +)"

instance ..

end

instantiation list :: ("{zero, uminus}") uminus
begin

definition
  list_uminus_def: "uminus = map uminus"

instance ..

end

instantiation list :: ("{zero,minus}") minus
begin

definition
  list_diff_def: "op - = zipwith0 (op -)"

instance ..

end

lemma zipwith0_Nil[simp]: "zipwith0 f [] ys = map (f 0) ys"
by(induct ys) simp_all

lemma list_add_Nil[simp]: "[] + xs = (xs::'a::monoid_add list)"
by (induct xs) (auto simp:list_add_def)

lemma list_add_Nil2[simp]: "xs + [] = (xs::'a::monoid_add list)"
by (induct xs) (auto simp:list_add_def)

lemma list_add_Cons[simp]: "(x#xs) + (y#ys) = (x+y)#(xs+ys)"
by(auto simp:list_add_def)

lemma list_diff_Nil[simp]: "[] - xs = -(xs::'a::group_add list)"
by (induct xs) (auto simp:list_diff_def list_uminus_def)

lemma list_diff_Nil2[simp]: "xs - [] = (xs::'a::group_add list)"
by (induct xs) (auto simp:list_diff_def)

lemma list_diff_Cons_Cons[simp]: "(x#xs) - (y#ys) = (x-y)#(xs-ys)"
by (induct xs) (auto simp:list_diff_def)

lemma list_uminus_Cons[simp]: "-(x#xs) = (-x)#(-xs)"
by (induct xs) (auto simp:list_uminus_def)

lemma self_list_diff:
  "xs - xs = replicate (length(xs::'a::group_add list)) 0"
by(induct xs) simp_all

lemma list_add_assoc: fixes xs :: "'a::monoid_add list"
shows "(xs+ys)+zs = xs+(ys+zs)"
apply(induct xs arbitrary: ys zs)
 apply simp
apply(case_tac ys)
 apply(simp)
apply(simp)
apply(case_tac zs)
 apply(simp)
apply(simp add: add.assoc)
done

subsection "Inner product"

definition iprod :: "'a::ring list \<Rightarrow> 'a list \<Rightarrow> 'a" ("\<langle>_,_\<rangle>") where
"\<langle>xs,ys\<rangle> = (\<Sum>(x,y) \<leftarrow> zip xs ys. x*y)"

lemma iprod_Nil[simp]: "\<langle>[],ys\<rangle> = 0"
by(simp add: iprod_def)

lemma iprod_Nil2[simp]: "\<langle>xs,[]\<rangle> = 0"
by(simp add: iprod_def)

lemma iprod_Cons[simp]: "\<langle>x#xs,y#ys\<rangle> = x*y + \<langle>xs,ys\<rangle>"
by(simp add: iprod_def)

lemma iprod0_if_coeffs0: "\<forall>c\<in>set cs. c = 0 \<Longrightarrow> \<langle>cs,xs\<rangle> = 0"
apply(induct cs arbitrary:xs)
 apply simp
apply(case_tac xs) apply simp
apply auto
done

lemma iprod_uminus[simp]: "\<langle>-xs,ys\<rangle> = -\<langle>xs,ys\<rangle>"
by(simp add: iprod_def uminus_listsum_map o_def split_def map_zip_map list_uminus_def)

lemma iprod_left_add_distrib: "\<langle>xs + ys,zs\<rangle> = \<langle>xs,zs\<rangle> + \<langle>ys,zs\<rangle>"
apply(induct xs arbitrary: ys zs)
apply (simp add: o_def split_def)
apply(case_tac ys)
apply simp
apply(case_tac zs)
apply (simp)
apply(simp add: distrib_right)
done

lemma iprod_left_diff_distrib: "\<langle>xs - ys, zs\<rangle> = \<langle>xs,zs\<rangle> - \<langle>ys,zs\<rangle>"
apply(induct xs arbitrary: ys zs)
apply (simp add: o_def split_def)
apply(case_tac ys)
apply simp
apply(case_tac zs)
apply (simp)
apply(simp add: left_diff_distrib)
done

lemma iprod_assoc: "\<langle>x *\<^sub>s xs, ys\<rangle> = x * \<langle>xs,ys\<rangle>"
apply(induct xs arbitrary: ys)
apply simp
apply(case_tac ys)
apply (simp)
apply (simp add: distrib_left mult.assoc)
done

end


theory Formula
imports BDT
begin

type_synonym atom = bool

datatype binop = And | Or | Impl

(* inductive definition of abstract syntax trees for formula *)

datatype form =
     Var  "var"
   | Atom "atom"
   | Neg  "form"
   | Bin  "binop" "form" "form"

text \<open> Notations \<close>

syntax        "_top"  :: "form"   ("top\<^sub>F")
translations  "top\<^sub>F"  == "(CONST Atom) (CONST True)"

syntax        "_bot"  :: "form"   ("bot\<^sub>F")
translations  "bot\<^sub>F"  == "(CONST Atom) (CONST False)"

syntax        "_neg"  :: "form \<Rightarrow> form"   ("neg\<^sub>F _")
translations  "neg\<^sub>F F" == "(CONST Neg) F"

syntax        "_and"  :: "form \<Rightarrow> form \<Rightarrow> form"   ("and\<^sub>F _ _")
translations  "and\<^sub>F F1 F2" == "(CONST Bin) (CONST And) F1 F2"

syntax        "_or"  :: "form \<Rightarrow> form \<Rightarrow> form"   ("or\<^sub>F _ _")
translations  "or\<^sub>F F1 F2" == "(CONST Bin) (CONST Or) F1 F2"

syntax        "_impl"  :: "form \<Rightarrow> form \<Rightarrow> form"   ("impl\<^sub>F _ _")
translations  "impl\<^sub>F F1 F2" == "(CONST Bin) (CONST Impl) F1 F2"

(** Test cases *)

definition p0 where "p0 = Var 0"
definition p1 where "p1 = Var 1"
definition p2 where "p2 = Var 2"

definition P0     where "P0        = impl\<^sub>F p0 p1"
definition P1     where "P1        = impl\<^sub>F p1 P0"
definition dnegp  where "dnegp P Q = (impl\<^sub>F (impl\<^sub>F P Q) Q)"
definition P2     where "P2        = dnegp P0 p0"

(** ** Semantic *)
(* Boolean interpretation of binary operators *)

fun interp ("I\<^sub>f\<^sub>o\<^sub>r\<^sub>m") where
    "I\<^sub>f\<^sub>o\<^sub>r\<^sub>m  _ _ = undefined" (* a completer *)

value "I\<^sub>f\<^sub>o\<^sub>r\<^sub>m P2 Itrue "
value "I\<^sub>f\<^sub>o\<^sub>r\<^sub>m P2 Ifalse "
value "I\<^sub>f\<^sub>o\<^sub>r\<^sub>m P2 (list2interpretation [True,False] False) "
value "I\<^sub>f\<^sub>o\<^sub>r\<^sub>m P2 (list2interpretation [False,True] False) "

(** ** Equivalence *)

definition equiv where "equiv P Q = (\<forall>I. I\<^sub>f\<^sub>o\<^sub>r\<^sub>m  P I = I\<^sub>f\<^sub>o\<^sub>r\<^sub>m  Q I)"

lemma negimpl : "equiv (neg\<^sub>F (impl\<^sub>F P Q)) (and\<^sub>F P (neg\<^sub>F Q))"
unfolding equiv_def
by auto

lemma implor : "equiv (impl\<^sub>F P Q) (or\<^sub>F (neg\<^sub>F P)  Q)"
unfolding equiv_def
by auto

(** ** Validity *)
definition valid where "valid P = (\<forall> I. I\<^sub>f\<^sub>o\<^sub>r\<^sub>m  P I = True)"

lemma Pierce :" valid (impl\<^sub>F (impl\<^sub>F (impl\<^sub>F P Q) P) P)"
unfolding valid_def
by auto

end


theory E4_6
  imports Main
begin

fun elems :: "'a list \<Rightarrow> 'a set" where
  "elems [] = {}" |
  "elems (x # xs) = {x} \<union> elems xs"

lemma "x \<in> elems xs \<Longrightarrow> \<exists> ys zs. xs = ys @ x # zs \<and> x \<notin> elems ys"
proof (induction xs)
case Nil
  then show ?case by auto
next
  case (Cons a xs)
  then show ?case
  proof (cases "x = a")
    case True
    then show ?thesis by fastforce
  next
    case False
    hence "x \<in> elems xs" using Cons.prems by auto
    thus ?thesis by (metis Cons.IH False UnE append_Cons elems.simps(2) empty_iff insert_iff)
  qed
qed

end


theory Chap3_1ex4
imports Main
begin

type_synonym vname = string

datatype aexp = N int | V vname | Plus aexp aexp | Times aexp aexp

type_synonym val = int
type_synonym state = "vname \<Rightarrow> val"

fun aval :: "aexp \<Rightarrow> state \<Rightarrow> val" where
"aval (N n) s = n"
| "aval (V v) s = s v"
| "aval (Plus e1 e2) s = aval e1 s + aval e2 s"
| "aval (Times e1 e2) s = aval e1 s * aval e2 s"

fun plus :: "aexp \<Rightarrow> aexp \<Rightarrow> aexp" where
"plus (N i1) (N i2) = N (i1 + i2)"
| "plus (N i) a = (if i=0 then a else Plus (N i) a)"
| "plus a (N i) = (if i=0 then a else Plus a (N i))"
| "plus a1 a2 = Plus a1 a2"

fun times :: "aexp \<Rightarrow> aexp \<Rightarrow> aexp" where
"times (N i1) (N i2) = N (i1 * i2)"
| "times (N i) a = (if i=0 then N 0 else if i=1 then a else Times (N i) a)"
| "times a (N i) = (if i=0 then N 0 else if i=1 then a else Times a (N i))"
| "times a1 a2 = Times a1 a2"

fun asimp :: "aexp \<Rightarrow> aexp" where
"asimp (N n) = N n"
| "asimp (V x) = V x"
| "asimp (Plus a1 a2) = plus (asimp a1) (asimp a2)"
| "asimp (Times a1 a2) = times (asimp a1) (asimp a2)"

lemma aval_plus: "aval (plus a1 a2) s = aval a1 s + aval a2 s"
  apply (induction rule: plus.induct)
  by auto

lemma aval_times: "aval (times a1 a2) s = aval a1 s * aval a2 s"
  apply (induction rule: times.induct)
  by auto

lemma "aval (asimp a) s = aval a s"
  apply (induction a)
  using aval_plus aval_times by auto

end


theory Aabid_ProgProv_Exercises2
imports Main
begin

(*2.1*)
value "1 + (2::nat)"
value "1 + (2::int)"
value "1 - (2::nat)"
value "1 - (2::int)"

(*2.2*)
fun add :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"add 0 n = n" |
"add (Suc m) n = Suc(add m n)"

lemma add_zeroright: "add a 0 = a"
  by (induction a, auto)

lemma add_Suceq: "Suc(add a b) = add a (Suc b)"
  by (induction a, auto)

lemma add_comm: "add a b = add b a"
  by (induction a, simp add: add_zeroright, simp add: add_Suceq)

primrec double :: "nat \<Rightarrow>  nat" where
"double 0  = 0"|
"double (Suc n) = Suc (Suc (double n))"

lemma double_add: "double m = add m m"
  by (induction m, auto, simp add: add_Suceq)

(*2.3*)
primrec count :: "int  \<Rightarrow> int list \<Rightarrow> nat" where
"count a [] = 0"|
"count a (y#ys) = (if a = y then (Suc(count a ys)) else (count a ys))"

lemma count_length: "count x xs \<le> length xs"
  by (induction xs, auto)

(*2.4*)
primrec snoc :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a list" where
"snoc [] a  = (a#[])"|
"snoc (x#xs) a = x#(snoc xs a)"

primrec reverse :: "'a list \<Rightarrow> 'a list" where
"reverse [] = []"|
"reverse (x#xs) = snoc (reverse xs) x"

lemma app_assoc: "(xs @ ys) @ zs = xs @ (ys @ zs)"
  by (induction xs, auto)

lemma snoc_app: "snoc xs x = xs @ [x]"
  by (induction xs, auto)

lemma reverse_app_distr: "reverse (xs @ ys) = (reverse ys) @ reverse(xs)"
  by (induction xs, simp add: snoc_app, auto, simp add: snoc_app)

lemma reverse_reverse : "reverse (reverse xs) = xs"
  by (induction xs, auto, simp add: snoc_app, simp add: reverse_app_distr)

(*2.5*)
primrec sum_upto  :: "nat \<Rightarrow> nat" where
"sum_upto 0 = 0"|
"sum_upto (Suc n) = (n + (sum_upto n)) + 1"

lemma sum_upto_formula: "sum_upto n = n * (n + 1) div 2"
  by (induction n, auto)

(*2.6*)
datatype 'a tree = Tip | Node "'a tree" 'a " 'a tree"

primrec contents :: "'a tree \<Rightarrow> 'a list" where
"contents Tip = []"|
"contents (Node l a r) = a#((contents l) @ (contents r))"

primrec sum_tree :: "nat tree \<Rightarrow> nat" where
"sum_tree Tip = 0"|
"sum_tree (Node l a r) = a + (sum_tree l) +  (sum_tree r)"

lemma sumtree_sumlist: "sum_tree t = sum_list (contents t)"
  by (induction t, auto)

(*2.7*)
(* primrec mirror :: "'a tree \<Rightarrow> 'a tree" where
"mirror Tip = Tip" |
"mirror (Node l a r ) = Node (mirror r ) a (mirror l)"

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

primrec post_order :: "'a tree \<Rightarrow> 'a list" where
"post_order Tip = []"|
"post_order (Node l a r) = ((pre_order l) @ (pre_order r)) @ (a#[])" *)

(*2.8*)
primrec intersperse :: "'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"intersperse a [] = []"|
"intersperse a (x#xs) = (x#(a#(intersperse a xs)))"

lemma map_intersperse: "map f (intersperse a xs) = intersperse (f a) (map f xs)"
  by (induction xs, auto)

(*2.9*)
fun itadd :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"itadd 0 m  = m"|
"itadd (Suc 0) m = Suc m"|
"itadd (Suc n) m = itadd (Suc 0) (itadd n m)"

lemma itadd_add: "itadd n m = add n m"
  by(induction n m rule: itadd.induct, auto)

(*2.10*)
datatype tree0 = Tip0 | Node0 "tree0" "tree0"

primrec nodes :: "tree0 \<Rightarrow> nat" where
"nodes Tip0 = 1"|
"nodes (Node0 l r) = 1 + nodes l + nodes r"

primrec explode :: "nat \<Rightarrow> tree0 \<Rightarrow> tree0" where
"explode 0 t = t"|
"explode (Suc n) t = explode n (Node0 t t)"

lemma nodes_explode_formula: "nodes (explode n t) = ((2^n) * (nodes t)) + ((2^n) - 1)"
  by(induction n arbitrary: t, auto simp add: algebra_simps)

(*2.11*)
datatype exp = Var | Const int | Add exp exp | Mult exp exp

primrec eval :: "exp \<Rightarrow> int \<Rightarrow> int" where
"eval Var x = x"|
"eval (Const c) x = c"|
"eval (Add a b) x = (eval a x) + (eval b x)"|
"eval (Mult a b) x = (eval a x) * (eval b x)"

primrec evalp :: "int list \<Rightarrow> int \<Rightarrow> int" where
"evalp [] c = 0"|
"evalp (x#xs) c  = x + (c * (evalp xs c))"


section \<open>\isaheader{Implementing Unique Priority Queues by Annotated Lists}\<close>
theory PrioUniqueByAnnotatedList
imports
  "../spec/AnnotatedListSpec"
  "../spec/PrioUniqueSpec"
begin

text \<open>
  In this theory we use annotated lists to implement unique priority queues
  with totally ordered elements.

  This theory is written as a generic adapter from the AnnotatedList interface
  to the unique priority queue interface.

  The annotated list stores a sequence of elements annotated with
  priorities\footnote{Technically, the annotated list elements are of unit-type,
  and the annotations hold both, the priority queue elements and the priorities.
  This is required as we defined annotated lists to only sum up the elements
  annotations.}

  The monoids operations forms the maximum over the elements and
  the minimum over the priorities.
  The sequence of pairs is ordered by ascending elements' order.
  The insertion point for a new element, or the priority of an existing element
  can be found by splitting the
  sequence at the point where the maximum of the elements read so far gets
  bigger than the element to be inserted.

  The minimum priority can be read out as the sum over the whole sequence.
  Finding the element with minimum priority is done by splitting the sequence
  at the point where the minimum priority of the elements read so far becomes
  equal to the minimum priority of the whole sequence.
\<close>

subsection "Definitions"

subsubsection "Monoid"
datatype ('e, 'a) LP = Infty | LP 'e 'a

fun p_unwrap :: "('e,'a) LP \<Rightarrow> ('e \<times> 'a)" where
  "p_unwrap (LP e a) = (e , a)"

fun p_min :: "('e::linorder, 'a::linorder) LP \<Rightarrow> ('e, 'a) LP \<Rightarrow> ('e, 'a) LP"  where
  "p_min Infty Infty = Infty"|
  "p_min Infty (LP e a) = LP e a"|
  "p_min (LP e a) Infty = LP e a"|
  "p_min (LP e1 a) (LP e2 b) = (LP (max e1 e2) (min a b))"

fun e_less_eq :: "'e \<Rightarrow> ('e::linorder, 'a::linorder) LP \<Rightarrow> bool"  where
  "e_less_eq e Infty = False"|
  "e_less_eq e (LP e' _) = (e \<le> e')"

text_raw\<open>\paragraph{Instantiation of classes}\ \\\<close>
lemma p_min_re_neut[simp]: "p_min a Infty = a" by (induct a) auto
lemma p_min_le_neut[simp]: "p_min Infty a = a" by (induct a) auto
lemma p_min_asso: "p_min (p_min a b) c = p_min a (p_min b c)"
  apply(induct a b  rule: p_min.induct )
  apply (auto)
  apply (induct c)
  apply (auto)
apply (metis max.assoc)
apply (metis min.assoc)
  done

lemma lp_mono: "class.monoid_add p_min Infty" by  unfold_locales  (auto simp add: p_min_asso)

instantiation LP :: (linorder,linorder) monoid_add
begin
definition zero_def: "0 == Infty"
definition plus_def: "a+b == p_min a b"

instance by
  intro_classes
(auto simp add: p_min_asso zero_def plus_def)
end

fun p_less_eq :: "('e, 'a::linorder) LP \<Rightarrow> ('e, 'a) LP \<Rightarrow> bool" where
  "p_less_eq (LP e a) (LP f b) = (a \<le> b)"|
  "p_less_eq  _ Infty = True"|
  "p_less_eq Infty (LP e a) = False"

fun p_less :: "('e, 'a::linorder) LP \<Rightarrow> ('e, 'a) LP \<Rightarrow> bool" where
  "p_less (LP e a) (LP f b) = (a < b)"|
  "p_less (LP e a) Infty = True"|
  "p_less Infty _ = False"

lemma p_less_le_not_le : "p_less x y \<longleftrightarrow> p_less_eq x y \<and> \<not> (p_less_eq y x)"
  by (induct x y rule: p_less.induct) auto

lemma p_order_refl : "p_less_eq x x"
  by (induct x) auto

lemma p_le_inf : "p_less_eq Infty x \<Longrightarrow> x = Infty"
  by (induct x) auto

lemma p_order_trans : "\<lbrakk>p_less_eq x y; p_less_eq y z\<rbrakk> \<Longrightarrow> p_less_eq x z"
  apply (induct y z rule: p_less.induct)
  apply auto
  apply (induct x)
  apply auto
  apply (cases x)
  apply auto
  apply(induct x)
  apply (auto simp add: p_le_inf)
  apply (metis p_le_inf p_less_eq.simps(2))
  done

lemma p_linear2 : "p_less_eq x y \<or> p_less_eq y x"
  apply (induct x y rule: p_less_eq.induct)
  apply auto
  done

instantiation LP :: (type, linorder) preorder
begin
definition plesseq_def: "less_eq = p_less_eq"
definition pless_def: "less = p_less"

instance
  apply (intro_classes)
  apply (simp only: p_less_le_not_le pless_def plesseq_def)
  apply (simp only: p_order_refl plesseq_def pless_def)
  apply (simp only: plesseq_def)
  apply (metis p_order_trans)
  done

end

subsubsection "Operations"

definition aluprio_\<alpha> :: "('s \<Rightarrow> (unit \<times> ('e::linorder,'a::linorder) LP) list)
  \<Rightarrow> 's \<Rightarrow> ('e::linorder \<rightharpoonup>  'a::linorder)"
  where
  "aluprio_\<alpha> \<alpha> ft == (map_of (map p_unwrap (map snd (\<alpha> ft))))"

definition aluprio_invar :: "('s \<Rightarrow> (unit \<times> ('c::linorder, 'd::linorder) LP) list)
  \<Rightarrow> ('s \<Rightarrow> bool) \<Rightarrow> 's \<Rightarrow> bool"
  where
  "aluprio_invar \<alpha> invar ft ==
     invar ft
     \<and> (\<forall> x\<in>set (\<alpha> ft). snd x\<noteq>Infty)
     \<and> sorted (map fst (map p_unwrap (map snd (\<alpha> ft))))
     \<and> distinct (map fst (map p_unwrap (map snd (\<alpha> ft)))) "

definition aluprio_empty  where
  "aluprio_empty empt = empt"

definition aluprio_isEmpty  where
  "aluprio_isEmpty isEmpty = isEmpty"

definition aluprio_insert ::
  "((('e::linorder,'a::linorder) LP \<Rightarrow> bool)
  \<Rightarrow> ('e,'a) LP \<Rightarrow> 's \<Rightarrow> ('s \<times> (unit \<times> ('e,'a) LP) \<times> 's))
    \<Rightarrow> ('s \<Rightarrow> ('e,'a) LP)
      \<Rightarrow> ('s \<Rightarrow> bool)
        \<Rightarrow> ('s \<Rightarrow> 's \<Rightarrow> 's)
          \<Rightarrow> ('s \<Rightarrow> unit \<Rightarrow> ('e,'a) LP \<Rightarrow> 's)
            \<Rightarrow> 's \<Rightarrow> 'e \<Rightarrow> 'a \<Rightarrow> 's"
  where
  "
  aluprio_insert splits annot isEmpty app consr s e a =
    (if e_less_eq e (annot s) \<and> \<not> isEmpty s
    then
      (let (l, (_,lp) , r) = splits (e_less_eq e) Infty s in
        (if e < fst (p_unwrap lp)
        then
          app (consr (consr l () (LP e a))  () lp) r
        else
          app (consr l () (LP e a)) r  ))
    else
      consr s () (LP e a))
  "

definition aluprio_pop :: "((('e::linorder,'a::linorder) LP \<Rightarrow> bool) \<Rightarrow> ('e,'a) LP
  \<Rightarrow> 's \<Rightarrow> ('s \<times> (unit \<times> ('e,'a) LP) \<times> 's))
    \<Rightarrow> ('s \<Rightarrow> ('e,'a) LP)
      \<Rightarrow> ('s \<Rightarrow> 's \<Rightarrow> 's)
        \<Rightarrow> 's
          \<Rightarrow> 'e \<times>'a \<times>'s"
  where
  "aluprio_pop splits annot app s =
    (let (l, (_,lp) , r) = splits (\<lambda> x. x \<le> (annot s)) Infty s
    in
      (case lp of
        (LP e a) \<Rightarrow>
          (e, a, app l r) ))"

definition aluprio_prio ::
  "((('e::linorder,'a::linorder) LP \<Rightarrow> bool) \<Rightarrow> ('e,'a) LP \<Rightarrow> 's
  \<Rightarrow> ('s \<times> (unit \<times> ('e,'a) LP) \<times> 's))
    \<Rightarrow> ('s \<Rightarrow> ('e,'a) LP)
      \<Rightarrow> ('s \<Rightarrow> bool)
        \<Rightarrow> 's \<Rightarrow> 'e \<Rightarrow> 'a option"
  where
  "
  aluprio_prio splits annot isEmpty s e =
    (if e_less_eq e (annot s) \<and> \<not> isEmpty s
    then
      (let (l, (_,lp) , r) = splits (e_less_eq e) Infty s in
        (if e = fst (p_unwrap lp)
        then
          Some (snd (p_unwrap lp))
        else
          None))
    else
      None)
  "

lemmas aluprio_defs =
aluprio_invar_def
aluprio_\<alpha>_def
aluprio_empty_def
aluprio_isEmpty_def
aluprio_insert_def
aluprio_pop_def
aluprio_prio_def

subsection "Correctness"

subsubsection "Auxiliary Lemmas"

lemma p_linear: "(x::('e, 'a::linorder) LP) \<le> y \<or> y \<le> x"
  by (unfold plesseq_def) (simp only: p_linear2)

lemma e_less_eq_mon1: "e_less_eq e x \<Longrightarrow> e_less_eq e (x + y)"
  apply (cases x)
  apply (auto simp add: plus_def)
  apply (cases y)
  apply (auto simp add: max.coboundedI1)
  done
lemma e_less_eq_mon2: "e_less_eq e y \<Longrightarrow> e_less_eq e (x + y)"
  apply (cases x)
  apply (auto simp add: plus_def)
  apply (cases y)
  apply (auto simp add: max.coboundedI2)
  done
lemmas e_less_eq_mon =
  e_less_eq_mon1
  e_less_eq_mon2

lemma p_less_eq_mon:
  "(x::('e::linorder,'a::linorder) LP) \<le> z \<Longrightarrow> (x + y) \<le> z"
  apply(cases y)
  apply(auto simp add: plus_def)
  apply (cases x)
  apply (cases z)
  apply (auto simp add: plesseq_def)
  apply (cases z)
  apply (auto simp add: min.coboundedI1)
  done

lemma e_less_eq_sum_list:
  "\<lbrakk>\<not> e_less_eq e (sum_list xs)\<rbrakk> \<Longrightarrow> \<forall>x \<in> set xs. \<not> e_less_eq e x"
proof (induct xs)
  case Nil thus ?case by simp
next
  case (Cons a xs)
  hence "\<not> e_less_eq e (sum_list xs)" by (auto simp add: e_less_eq_mon)
  hence v1: "\<forall>x\<in>set xs. \<not> e_less_eq e x" using Cons.hyps by simp
  from Cons.prems have "\<not> e_less_eq e a" by (auto simp add: e_less_eq_mon)
  with v1 show "\<forall>x\<in>set (a#xs). \<not> e_less_eq e x" by simp
qed

lemma e_less_eq_p_unwrap:
  "\<lbrakk>x \<noteq> Infty;\<not> e_less_eq e x\<rbrakk> \<Longrightarrow> fst (p_unwrap x) < e"
  by (cases x) auto

lemma e_less_eq_refl :
  "b \<noteq> Infty \<Longrightarrow> e_less_eq (fst (p_unwrap b)) b"
  by (cases b) auto

lemma e_less_eq_sum_list2:
  assumes
  "\<forall>x\<in>set (\<alpha>s). snd x \<noteq> Infty"
  "((), b) \<in> set (\<alpha>s)"
  shows "e_less_eq (fst (p_unwrap b)) (sum_list (map snd (\<alpha>s)))"
  apply(insert assms)
  apply (induct "\<alpha>s")
  apply (auto simp add: zero_def e_less_eq_mon e_less_eq_refl)
  done

lemma e_less_eq_lem1:
  "\<lbrakk>\<not> e_less_eq e a;e_less_eq e (a + b)\<rbrakk> \<Longrightarrow> e_less_eq e b"
  apply (auto simp add: plus_def)
  apply (cases a)
  apply auto
  apply (cases b)
  apply auto
  apply (metis le_max_iff_disj)
  done

lemma p_unwrap_less_sum: "snd (p_unwrap ((LP e aa) + b)) \<le> aa"
  apply (cases b)
  apply (auto simp add: plus_def)
done

lemma  sum_list_less_elems: "\<forall>x\<in>set xs. snd x \<noteq> Infty \<Longrightarrow>
  \<forall>y\<in>set (map snd (map p_unwrap (map snd xs))).
              snd (p_unwrap (sum_list (map snd xs))) \<le> y"
    proof (induct xs)
    case Nil thus ?case by simp
    next
    case (Cons a as) thus ?case
      apply auto
      apply (cases "(snd a)" rule: p_unwrap.cases)
      apply auto
      apply (cases "sum_list (map snd as)")
      apply auto
      apply (metis linorder_linear p_min_re_neut p_unwrap.simps
        plus_def[abs_def] snd_eqD)
      apply (auto simp add: p_unwrap_less_sum)
      apply (unfold plus_def)
      apply (cases "(snd a, sum_list (map snd as))" rule: p_min.cases)
      apply auto
      apply (cases "map snd as")
      apply (auto simp add: infadd)
      apply (metis min.coboundedI2 snd_conv)
      done
qed

lemma distinct_sortet_list_app:
  "\<lbrakk>sorted xs; distinct xs; xs = as @ b # cs\<rbrakk>
  \<Longrightarrow> \<forall> x\<in> set cs. b < x"
  by (metis distinct.simps(2) distinct_append
    antisym_conv2 sorted.simps(2) sorted_append)

lemma distinct_sorted_list_lem1:
  assumes
  "sorted xs"
  "sorted ys"
  "distinct xs"
  "distinct ys"
  " \<forall> x \<in> set xs. x < e"
  " \<forall> y \<in> set ys. e < y"
  shows
  "sorted (xs @ e # ys)"
  "distinct (xs @ e # ys)"
proof -
  from assms (5,6)
  have "\<forall>x\<in>set xs. \<forall>y\<in>set ys. x \<le> y" by force
  thus "sorted (xs @ e # ys)"
    using assms
    by (auto simp add: sorted_append)
  have "set xs \<inter> set ys = {}" using assms (5,6) by force
  thus "distinct (xs @ e # ys)"
    using assms
    by (auto)
qed

lemma distinct_sorted_list_lem2:
  assumes
  "sorted xs"
  "sorted ys"
  "distinct xs"
  "distinct ys"
  "e < e'"
  " \<forall> x \<in> set xs. x < e"
  " \<forall> y \<in> set ys. e' < y"
  shows
  "sorted (xs @ e # e' # ys)"
  "distinct (xs @ e # e' # ys)"
proof -
  have "sorted (e' # ys)"
    "distinct (e' # ys)"
    "\<forall> y \<in> set (e' # ys). e < y"
    using assms(2,4,5,7)
    by (auto)
  thus "sorted (xs @ e # e' # ys)"
  "distinct (xs @ e # e' # ys)"
    using assms(1,3,6) distinct_sorted_list_lem1[of xs "e' # ys" e]
    by auto
qed

lemma map_of_distinct_upd:
  "x \<notin> set (map fst xs) \<Longrightarrow> [x \<mapsto> y] ++ map_of xs = (map_of xs) (x \<mapsto> y)"
  by (induct xs) (auto simp add: fun_upd_twist)

lemma map_of_distinct_upd2:
  assumes "x \<notin> set(map fst xs)"
  "x \<notin> set (map fst ys)"
  shows "map_of (xs @ (x,y) # ys) = (map_of (xs @ ys))(x \<mapsto> y)"
  apply(insert assms)
  apply(induct xs)
  apply (auto intro: ext)
  done

lemma map_of_distinct_upd3:
  assumes "x \<notin> set(map fst xs)"
  "x \<notin> set (map fst ys)"
  shows "map_of (xs @ (x,y) # ys) = (map_of (xs @ (x,y') # ys))(x \<mapsto> y)"
  apply(insert assms)
  apply(induct xs)
  apply (auto intro: ext)
  done

lemma map_of_distinct_upd4:
  assumes "x \<notin> set(map fst xs)"
  "x \<notin> set (map fst ys)"
  shows "map_of (xs @ ys) = (map_of (xs @ (x,y) # ys))(x := None)"
  apply(insert assms)
  apply(induct xs)

  apply clarsimp
  apply (metis dom_map_of_conv_image_fst fun_upd_None_restrict
    restrict_complement_singleton_eq restrict_map_self)

  apply (auto simp add: map_of_eq_None_iff) []
  done

lemma map_of_distinct_lookup:
  assumes "x \<notin> set(map fst xs)"
  "x \<notin> set (map fst ys)"
  shows "map_of (xs @ (x,y) # ys) x = Some y"
proof -
  have "map_of (xs @ (x,y) # ys) = (map_of (xs @ ys)) (x \<mapsto> y)"
    using assms map_of_distinct_upd2 by simp
  thus ?thesis
    by simp
qed

lemma ran_distinct:
  assumes dist: "distinct (map fst al)"
  shows "ran (map_of al) = snd ` set al"
using assms proof (induct al)
  case Nil then show ?case by simp
next
  case (Cons kv al)
  then have "ran (map_of al) = snd ` set al" by simp
  moreover from Cons.prems have "map_of al (fst kv) = None"
    by (simp add: map_of_eq_None_iff)
  ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp
qed

subsubsection "Finite"

lemma aluprio_finite_correct: "uprio_finite (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar)"
  by(unfold_locales) (simp add: aluprio_defs finite_dom_map_of)

subsubsection "Empty"
lemma aluprio_empty_correct:
  assumes "al_empty \<alpha> invar empt"
  shows "uprio_empty (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar) (aluprio_empty empt)"
proof -
  interpret al_empty \<alpha> invar empt by fact
  show ?thesis
    apply (unfold_locales)
    apply (auto simp add: empty_correct aluprio_defs)
    done
qed

subsubsection "Is Empty"

lemma aluprio_isEmpty_correct:
  assumes "al_isEmpty \<alpha> invar isEmpty"
  shows "uprio_isEmpty (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar) (aluprio_isEmpty isEmpty)"
proof -
  interpret al_isEmpty \<alpha> invar isEmpty by fact
  show ?thesis
    apply (unfold_locales)
    apply (auto simp add: aluprio_defs isEmpty_correct)
    done
qed

subsubsection "Insert"

lemma annot_inf:
  assumes A: "invar s" "\<forall>x\<in>set (\<alpha> s). snd x \<noteq> Infty" "al_annot \<alpha> invar annot"
  shows "annot s = Infty \<longleftrightarrow> \<alpha> s = [] "
proof -
  from A have invs: "invar s" by (simp add: aluprio_defs)
  interpret al_annot \<alpha> invar annot by fact
  show "annot s = Infty \<longleftrightarrow> \<alpha> s = []"
  proof (cases "\<alpha> s = []")
    case True
    hence "map snd (\<alpha> s) = []" by simp
    hence "sum_list (map snd (\<alpha> s)) = Infty"
      by (auto simp add: zero_def)
    with invs have  "annot s = Infty" by (auto simp add: annot_correct)
    with True show ?thesis by simp
  next
    case False
    hence " \<exists>x xs. (\<alpha> s) = x # xs" by (cases "\<alpha> s") auto
    from this obtain x xs where [simp]: "(\<alpha> s) = x # xs" by blast
    from this assms(2) have "snd x \<noteq> Infty" by (auto simp add: aluprio_defs)
    hence "sum_list (map snd (\<alpha> s)) \<noteq> Infty" by (auto simp add: infadd)
    thus ?thesis using annot_correct invs False by simp
  qed
qed

lemma e_less_eq_annot:

  assumes "al_annot \<alpha> invar annot"
   "invar s" "\<forall>x\<in>set (\<alpha> s). snd x \<noteq> Infty" "\<not> e_less_eq e (annot s)"
  shows "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> s)). x < e"
proof -
  interpret al_annot \<alpha> invar annot by fact
  from assms(2) have "annot s = sum_list (map snd (\<alpha> s))"
    by (auto simp add: annot_correct)
  with assms(4) have
    "\<forall>x \<in> set (map snd (\<alpha> s)). \<not> e_less_eq e x"
    by (metis e_less_eq_sum_list)
  with assms(3)
  show ?thesis
    by (auto simp add: e_less_eq_p_unwrap)
qed

lemma aluprio_insert_correct:
  assumes
  "al_splits \<alpha> invar splits"
  "al_annot \<alpha> invar annot"
  "al_isEmpty \<alpha> invar isEmpty"
  "al_app \<alpha> invar app"
  "al_consr \<alpha> invar consr"
  shows
  "uprio_insert (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar)
    (aluprio_insert splits annot isEmpty app consr)"
proof -
  interpret al_splits \<alpha> invar splits by fact
  interpret al_annot \<alpha> invar annot by fact
  interpret al_isEmpty \<alpha> invar isEmpty by fact
  interpret al_app \<alpha> invar app by fact
  interpret al_consr \<alpha> invar consr by fact
  show ?thesis
  proof (unfold_locales, unfold aluprio_defs, goal_cases)
    case g1asms: (1 s e a)
    thus ?case proof (cases "e_less_eq e (annot s) \<and> \<not> isEmpty s")
      case False with g1asms show  ?thesis
        apply (auto simp add: consr_correct )
      proof goal_cases
        case prems: 1
        with assms(2) have
          "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> s)). x < e"
          by (simp add: e_less_eq_annot)
        with prems(3) show ?case
          by(auto simp add: sorted_append)
      next
        case prems: 2
        hence "annot s = sum_list (map snd (\<alpha> s))"
          by (simp add: annot_correct)
        with prems
        show ?case
          by (auto simp add: e_less_eq_sum_list2)
      next
        case prems: 3
        hence "\<alpha> s = []" by (auto simp add: isEmpty_correct)
        thus ?case by simp
      next
        case prems: 4
        hence "\<alpha> s = []" by (auto simp add: isEmpty_correct)
        with prems show ?case by simp
      qed
    next
      case True note T1 = this
      obtain l uu lp r where
        l_lp_r: "(splits (e_less_eq e) Infty s) = (l, ((), lp), r) "
        by (cases "splits (e_less_eq e) Infty s", auto)
      note v2 = splits_correct[of s "e_less_eq e" Infty l "()" lp r]
      have
        v3: "invar s"
        "\<not> e_less_eq e Infty"
        "e_less_eq e (Infty + sum_list (map snd (\<alpha> s)))"
        using T1 g1asms annot_correct
        by (auto simp add: plus_def)
      have
        v4: "\<alpha> s = \<alpha> l @ ((), lp) # \<alpha> r"
        "\<not> e_less_eq e (Infty + sum_list (map snd (\<alpha> l)))"
        "e_less_eq e (Infty + sum_list (map snd (\<alpha> l)) + lp)"
        "invar l"
        "invar r"
        using v2[OF v3(1) _ v3(2) v3(3) l_lp_r] e_less_eq_mon(1) by auto
      hence v5: "e_less_eq e lp"
        by (metis e_less_eq_lem1)
      hence v6: "e \<le> (fst (p_unwrap lp))"
        by (cases lp) auto
      have "(Infty + sum_list (map snd (\<alpha> l))) = (annot l)"
        by (metis add_0_left annot_correct v4(4) zero_def)
      hence v7:"\<not> e_less_eq e (annot l)"
        using v4(2) by simp
      have "\<forall>x\<in>set (\<alpha> l). snd x \<noteq> Infty"
        using g1asms v4(1) by simp
      hence v7: "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> l)). x < e"
        using v4(4) v7 assms(2)
        by(simp add: e_less_eq_annot)
      have v8:"map fst (map p_unwrap (map snd (\<alpha> s))) =
        map fst (map p_unwrap (map snd (\<alpha> l))) @ fst(p_unwrap lp) #
        map fst (map p_unwrap (map snd (\<alpha> r)))"
        using v4(1)
        by simp
      note distinct_sortet_list_app[of "map fst (map p_unwrap (map snd (\<alpha> s)))"
        "map fst (map p_unwrap (map snd (\<alpha> l)))" "fst(p_unwrap lp)"
        "map fst (map p_unwrap (map snd (\<alpha> r)))"]
      hence v9:
        "\<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). fst(p_unwrap lp) < x"
        using v4(1) g1asms v8
        by auto
      have v10:
        "sorted (map fst (map p_unwrap (map snd (\<alpha> l))))"
        "distinct (map fst (map p_unwrap (map snd (\<alpha> l))))"
        "sorted (map fst (map p_unwrap (map snd (\<alpha> r))))"
        "distinct (map fst (map p_unwrap (map snd (\<alpha> l))))"
        using g1asms v8
        by (auto simp add: sorted_append)

      from l_lp_r T1 g1asms show ?thesis
      proof (fold aluprio_insert_def, cases "e < fst (p_unwrap lp)")
        case True
        hence v11:
          "aluprio_insert splits annot isEmpty app consr s e a
            = app (consr (consr l () (LP e a)) () lp) r"
          using l_lp_r T1
          by (auto simp add: aluprio_defs)
        have  v12: "invar (app (consr (consr l () (LP e a)) () lp) r)"
          using v4(4,5)
          by (auto simp add: app_correct consr_correct)
        have v13:
          "\<alpha> (app (consr (consr l () (LP e a)) () lp) r)
            = \<alpha> l @ ((),(LP e a)) # ((), lp) # \<alpha> r"
          using v4(4,5) by (auto simp add: app_correct consr_correct)
        hence v14:
          "(\<forall>x\<in>set (\<alpha> (app (consr (consr l () (LP e a)) () lp) r)).
             snd x \<noteq> Infty)"
          using g1asms v4(1)
          by auto
        have v15: "e = fst(p_unwrap (LP e a))" by simp
        hence v16:
          "sorted (map fst (map p_unwrap
             (map snd (\<alpha> l @ ((),(LP e a)) # ((), lp) # \<alpha> r))))"
          "distinct (map fst (map p_unwrap
             (map snd (\<alpha> l @ ((),(LP e a)) # ((), lp) # \<alpha> r))))"
          using v10(1,3) v7 True v9 v4(1) g1asms distinct_sorted_list_lem2
          by (auto simp add: sorted_append)
        thus "invar (aluprio_insert splits annot isEmpty app consr s e a) \<and>
          (\<forall>x\<in>set (\<alpha> (aluprio_insert splits annot isEmpty app consr s e a)).
             snd x \<noteq> Infty) \<and>
          sorted (map fst (map p_unwrap (map snd (\<alpha>
             (aluprio_insert splits annot isEmpty app consr s e a))))) \<and>
          distinct (map fst (map p_unwrap (map snd (\<alpha>
             (aluprio_insert splits annot isEmpty app consr s e a)))))"
          using v11 v12 v13 v14
          by simp
      next
        case False
        hence v11:
          "aluprio_insert splits annot isEmpty app consr s e a
             = app (consr l () (LP e a)) r"
          using l_lp_r T1
          by (auto simp add: aluprio_defs)
        have  v12: "invar (app (consr l () (LP e a)) r)" using v4(4,5)
          by (auto simp add: app_correct consr_correct)
        have v13: "\<alpha> (app (consr l () (LP e a)) r) = \<alpha> l @ ((),(LP e a)) # \<alpha> r"
          using v4(4,5) by (auto simp add: app_correct consr_correct)
        hence v14: "(\<forall>x\<in>set (\<alpha> (app (consr l () (LP e a)) r)). snd x \<noteq> Infty)"
          using g1asms v4(1)
          by auto
        have v15: "e = fst(p_unwrap (LP e a))" by simp
        have v16: "e = fst(p_unwrap lp)"
          using False v5 by (cases lp) auto
        hence v17:
          "sorted (map fst (map p_unwrap
            (map snd (\<alpha> l @ ((),(LP e a)) # \<alpha> r))))"
          "distinct (map fst (map p_unwrap
            (map snd (\<alpha> l @ ((),(LP e a)) # \<alpha> r))))"
          using v16 v15 v10(1,3) v7 True v9 v4(1)
            g1asms distinct_sorted_list_lem1
          by (auto simp add: sorted_append)
        thus "invar (aluprio_insert splits annot isEmpty app consr s e a) \<and>
          (\<forall>x\<in>set (\<alpha> (aluprio_insert splits annot isEmpty app consr s e a)).
            snd x \<noteq> Infty) \<and>
          sorted (map fst (map p_unwrap (map snd (\<alpha>
            (aluprio_insert splits annot isEmpty app consr s e a))))) \<and>
          distinct (map fst (map p_unwrap (map snd (\<alpha>
            (aluprio_insert splits annot isEmpty app consr s e a)))))"
          using v11 v12 v13 v14
          by simp
      qed
    qed
  next
    case g1asms: (2 s e a)
    thus ?case proof (cases "e_less_eq e (annot s) \<and> \<not> isEmpty s")
      case False with g1asms show  ?thesis
        apply (auto simp add: consr_correct)
      proof goal_cases
        case prems: 1
        with assms(2) have
          "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> s)). x < e"
          by (simp add: e_less_eq_annot)
        hence "e \<notin> set (map fst ((map (p_unwrap \<circ> snd)) (\<alpha> s)))"
          by auto
        thus ?case
          by (auto simp add: map_of_distinct_upd)
      next
        case prems: 2
        hence "\<alpha> s = []" by (auto simp add: isEmpty_correct)
        thus ?case
          by simp
      qed
    next
      case True note T1 = this
      obtain l lp r where
        l_lp_r: "(splits (e_less_eq e) Infty s) = (l, ((), lp), r) "
        by (cases "splits (e_less_eq e) Infty s", auto)
      note v2 = splits_correct[of s "e_less_eq e" Infty l "()" lp r]
      have
        v3: "invar s"
        "\<not> e_less_eq e Infty"
        "e_less_eq e (Infty + sum_list (map snd (\<alpha> s)))"
        using T1 g1asms annot_correct
        by (auto simp add: plus_def)
      have
        v4: "\<alpha> s = \<alpha> l @ ((), lp) # \<alpha> r"
        "\<not> e_less_eq e (Infty + sum_list (map snd (\<alpha> l)))"
        "e_less_eq e (Infty + sum_list (map snd (\<alpha> l)) + lp)"
        "invar l"
        "invar r"
        using v2[OF v3(1) _ v3(2) v3(3) l_lp_r] e_less_eq_mon(1) by auto
      hence v5: "e_less_eq e lp"
        by (metis e_less_eq_lem1)
      hence v6: "e \<le> (fst (p_unwrap lp))"
        by (cases lp) auto
      have "(Infty + sum_list (map snd (\<alpha> l))) = (annot l)"
        by (metis add_0_left annot_correct v4(4) zero_def)
      hence v7:"\<not> e_less_eq e (annot l)"
        using v4(2) by simp
      have "\<forall>x\<in>set (\<alpha> l). snd x \<noteq> Infty"
        using g1asms v4(1) by simp
      hence v7: "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> l)). x < e"
        using v4(4) v7 assms(2)
        by(simp add: e_less_eq_annot)
      have v8:"map fst (map p_unwrap (map snd (\<alpha> s))) =
        map fst (map p_unwrap (map snd (\<alpha> l))) @ fst(p_unwrap lp) #
        map fst (map p_unwrap (map snd (\<alpha> r)))"
        using v4(1)
        by simp
      note distinct_sortet_list_app[of "map fst (map p_unwrap (map snd (\<alpha> s)))"
        "map fst (map p_unwrap (map snd (\<alpha> l)))" "fst(p_unwrap lp)"
        "map fst (map p_unwrap (map snd (\<alpha> r)))"]
      hence v9: "
        \<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). fst(p_unwrap lp) < x"
        using v4(1) g1asms v8
        by auto
      hence v10: " \<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). e < x"
        using v6 by auto
      have v11:
        "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> l))))"
        "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> r))))"
        using v7 v10 v8 g1asms
        by auto
      from l_lp_r T1 g1asms show ?thesis
      proof (fold aluprio_insert_def, cases "e < fst (p_unwrap lp)")
        case True
        hence v12:
          "aluprio_insert splits annot isEmpty app consr s e a
            = app (consr (consr l () (LP e a)) () lp) r"
          using l_lp_r T1
          by (auto simp add: aluprio_defs)
        have v13:
          "\<alpha> (app (consr (consr l () (LP e a)) () lp) r)
            = \<alpha> l @ ((),(LP e a)) # ((), lp) # \<alpha> r"
          using v4(4,5) by (auto simp add: app_correct consr_correct)
        have v14: "e = fst(p_unwrap (LP e a))" by simp
        have v15: "e \<notin> set (map fst (map p_unwrap (map snd(((),lp)#\<alpha> r))))"
          using v11(2) True by auto
        note map_of_distinct_upd2[OF v11(1) v15]
        thus
          "map_of (map p_unwrap (map snd (\<alpha>
              (aluprio_insert splits annot isEmpty app consr s e a))))
            = map_of (map p_unwrap (map snd (\<alpha> s)))(e \<mapsto> a)"
          using v12 v13 v4(1)
          by simp
      next
        case False
        hence v12:
          "aluprio_insert splits annot isEmpty app consr s e a
            = app (consr l () (LP e a)) r"
          using l_lp_r T1
          by (auto simp add: aluprio_defs)
        have v13:
          "\<alpha> (app (consr l () (LP e a)) r) = \<alpha> l @ ((),(LP e a)) # \<alpha> r"
          using v4(4,5) by (auto simp add: app_correct consr_correct)
        have v14: "e = fst(p_unwrap lp)"
          using False v5 by (cases lp) auto
        note v15 = map_of_distinct_upd3[OF v11(1) v11(2)]
        have v16:"(map p_unwrap (map snd (\<alpha> s))) =
          (map p_unwrap (map snd (\<alpha> l))) @ (e,snd(p_unwrap lp)) #
          (map p_unwrap (map snd (\<alpha> r)))"
          using v4(1) v14
          by simp
        note v15[of a "snd(p_unwrap lp)"]
        thus
          "map_of (map p_unwrap (map snd (\<alpha>
              (aluprio_insert splits annot isEmpty app consr s e a))))
            = map_of (map p_unwrap (map snd (\<alpha> s)))(e \<mapsto> a)"
          using v12 v13 v16
          by simp
      qed
    qed
  qed
qed

subsubsection "Prio"
lemma aluprio_prio_correct:
  assumes
  "al_splits \<alpha> invar splits"
  "al_annot \<alpha> invar annot"
  "al_isEmpty \<alpha> invar isEmpty"
  shows
  "uprio_prio (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar) (aluprio_prio splits annot isEmpty)"
proof -
  interpret al_splits \<alpha> invar splits by fact
  interpret al_annot \<alpha> invar annot by fact
  interpret al_isEmpty \<alpha> invar isEmpty by fact
  show ?thesis
  proof (unfold_locales)
    fix s e
    assume inv1: "aluprio_invar \<alpha> invar s"
    hence sinv: "invar s"
      "(\<forall> x\<in>set (\<alpha> s). snd x\<noteq>Infty)"
      "sorted (map fst (map p_unwrap (map snd (\<alpha> s))))"
      "distinct (map fst (map p_unwrap (map snd (\<alpha> s))))"
      by (auto simp add: aluprio_defs)
    show "aluprio_prio splits annot isEmpty s e = aluprio_\<alpha> \<alpha> s e"
    proof(cases "e_less_eq e (annot s) \<and> \<not> isEmpty s")
      case False note F1 = this
      thus ?thesis
      proof(cases "isEmpty s")
        case True
        hence "\<alpha> s = []"
          using sinv isEmpty_correct by simp
        hence "aluprio_\<alpha> \<alpha> s = Map.empty" by (simp add:aluprio_defs)
        hence "aluprio_\<alpha> \<alpha> s e = None" by simp
        thus "aluprio_prio splits annot isEmpty s e = aluprio_\<alpha> \<alpha> s e"
          using F1
          by (auto simp add: aluprio_defs)
      next
        case False
        hence v3:"\<not> e_less_eq e (annot s)"  using F1 by simp
        note v4=e_less_eq_annot[OF assms(2)]
        note v4[OF sinv(1) sinv(2) v3]
        hence v5:"e\<notin>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> s))"
          by auto
        hence "map_of (map (p_unwrap \<circ> snd) (\<alpha> s)) e = None"
          using map_of_eq_None_iff
          by (metis map_map map_of_eq_None_iff set_map v5)
        thus "aluprio_prio splits annot isEmpty s e = aluprio_\<alpha> \<alpha> s e"
          using F1
          by (auto simp add: aluprio_defs)
      qed
    next
      case True note T1 = this
      obtain l uu lp r where
        l_lp_r: "(splits (e_less_eq e) Infty s) = (l, ((), lp), r) "
        by (cases "splits (e_less_eq e) Infty s", auto)
      note v2 = splits_correct[of s "e_less_eq e" Infty l "()" lp r]
      have
        v3: "invar s"
        "\<not> e_less_eq e Infty"
        "e_less_eq e (Infty + sum_list (map snd (\<alpha> s)))"
        using T1 sinv annot_correct
        by (auto simp add: plus_def)
      have
        v4: "\<alpha> s = \<alpha> l @ ((), lp) # \<alpha> r"
        "\<not> e_less_eq e (Infty + sum_list (map snd (\<alpha> l)))"
        "e_less_eq e (Infty + sum_list (map snd (\<alpha> l)) + lp)"
        "invar l"
        "invar r"
        using v2[OF v3(1) _ v3(2) v3(3) l_lp_r] e_less_eq_mon(1) by auto
      hence v5: "e_less_eq e lp"
        by (metis e_less_eq_lem1)
      hence v6: "e \<le> (fst (p_unwrap lp))"
        by (cases lp) auto
      have "(Infty + sum_list (map snd (\<alpha> l))) = (annot l)"
        by (metis add_0_left annot_correct v4(4) zero_def)
      hence v7:"\<not> e_less_eq e (annot l)"
        using v4(2) by simp
      have "\<forall>x\<in>set (\<alpha> l). snd x \<noteq> Infty"
        using sinv v4(1) by simp
      hence v7: "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> l)). x < e"
        using v4(4) v7 assms(2)
        by(simp add: e_less_eq_annot)
      have v8:"map fst (map p_unwrap (map snd (\<alpha> s))) =
        map fst (map p_unwrap (map snd (\<alpha> l))) @ fst(p_unwrap lp) #
        map fst (map p_unwrap (map snd (\<alpha> r)))"
        using v4(1)
        by simp
      note distinct_sortet_list_app[of "map fst (map p_unwrap (map snd (\<alpha> s)))"
        "map fst (map p_unwrap (map snd (\<alpha> l)))" "fst(p_unwrap lp)"
        "map fst (map p_unwrap (map snd (\<alpha> r)))"]
      hence v9:
        "\<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). fst(p_unwrap lp) < x"
        using v4(1) sinv v8
        by auto
      hence v10: " \<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). e < x"
        using v6 by auto
      have v11:
        "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> l))))"
        "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> r))))"
        using v7 v10 v8 sinv
        by auto
      from l_lp_r T1 sinv show ?thesis
      proof (cases "e = fst (p_unwrap lp)")
        case False
        have v12: "e \<notin> set (map fst (map p_unwrap (map snd(\<alpha> s))))"
          using v11 False v4(1) by auto
        hence "map_of (map (p_unwrap \<circ> snd) (\<alpha> s)) e = None"
          using map_of_eq_None_iff
          by (metis map_map map_of_eq_None_iff set_map v12)
        thus ?thesis
          using T1 False l_lp_r
          by (auto simp add: aluprio_defs)
      next
        case True
        have v12: "map (p_unwrap \<circ> snd) (\<alpha> s) =
          map p_unwrap (map snd (\<alpha> l)) @ (e,snd (p_unwrap lp)) #
          map p_unwrap (map snd (\<alpha> r))"
          using v4(1) True by simp
        note map_of_distinct_lookup[OF v11]
        hence
          "map_of (map (p_unwrap \<circ> snd) (\<alpha> s)) e = Some (snd (p_unwrap lp))"
          using v12 by simp
        thus ?thesis
          using T1 True l_lp_r
          by (auto simp add: aluprio_defs)
      qed
    qed
  qed
qed

subsubsection "Pop"

lemma aluprio_pop_correct:
  assumes "al_splits \<alpha> invar splits"
  "al_annot \<alpha> invar annot"
  "al_app \<alpha> invar app"
  shows
  "uprio_pop (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar) (aluprio_pop splits annot app)"
proof -
  interpret al_splits \<alpha> invar splits by fact
  interpret al_annot \<alpha> invar annot by fact
  interpret al_app \<alpha> invar app by fact
  show ?thesis
  proof (unfold_locales)
    fix s e a s'
    assume A: "aluprio_invar \<alpha> invar s"
      "aluprio_\<alpha> \<alpha> s \<noteq> Map.empty"
      "aluprio_pop splits annot app s = (e, a, s')"
    hence v1: "\<alpha> s \<noteq> []"
      by (auto simp add: aluprio_defs)
    obtain l lp r where
      l_lp_r: "splits (\<lambda> x. x\<le>annot s) Infty s = (l,((),lp),r)"
      by (cases "splits (\<lambda> x. x\<le>annot s) Infty s", auto)
    have invs:
      "invar s"
      "(\<forall>x\<in>set (\<alpha> s). snd x \<noteq> Infty)"
      "sorted (map fst (map p_unwrap (map snd (\<alpha> s))))"
      "distinct (map fst (map p_unwrap (map snd (\<alpha> s))))"
      using A by (auto simp add:aluprio_defs)
    note a1 = annot_inf[of invar s \<alpha> annot]
    note a1[OF invs(1) invs(2) assms(2)]
    hence v2: "annot s \<noteq> Infty"
      using v1 by simp
    hence v3:
      "\<not> Infty \<le> annot s"
      by(cases "annot s") (auto simp add: plesseq_def)
    have v4: "annot s = sum_list (map snd (\<alpha> s))"
      by (auto simp add: annot_correct invs(1))
    hence
      v5:
      "(Infty + sum_list (map snd (\<alpha> s))) \<le> annot s"
      by (auto simp add: plus_def)
    note p_mon = p_less_eq_mon[of _ "annot s"]
    note v6 = splits_correct[OF invs(1)]
    note v7 = v6[of "\<lambda> x. x \<le> annot s"]
    note v7[OF _ v3 v5 l_lp_r] p_mon
    hence v8:
      " \<alpha> s = \<alpha> l @ ((), lp) # \<alpha> r"
      "\<not> Infty + sum_list (map snd (\<alpha> l)) \<le> annot s"
      "Infty + sum_list (map snd (\<alpha> l)) + lp \<le> annot s"
      "invar l"
      "invar r"
      by auto
    hence v9: "lp \<noteq> Infty"
      using invs(2) by auto
    hence v10:
      "s' = app l r"
      "(e,a) = p_unwrap lp"
      using l_lp_r A(3)
      apply (auto simp add: aluprio_defs)
      apply (cases lp)
      apply auto
      apply (cases lp)
      apply auto
      done
    have "lp \<le> annot s"
      using v8(2,3) p_less_eq_lem1
      by auto
    hence v11: "a \<le> snd (p_unwrap (annot s))"
      using v10(2) v2 v9
      apply (cases "annot s")
      apply auto
      apply (cases lp)
      apply (auto simp add: plesseq_def)
      done
    note sum_list_less_elems[OF invs(2)]
    hence v12: "\<forall>y\<in>set (map snd (map p_unwrap (map snd (\<alpha> s)))). a \<le> y"
      using v4 v11 by auto
    have "ran (aluprio_\<alpha> \<alpha> s) = set (map snd (map p_unwrap (map snd (\<alpha> s))))"
      using ran_distinct[OF invs(4)]
      apply (unfold aluprio_defs)
      apply (simp only: set_map)
      done
    hence ziel1: "\<forall>y\<in>ran (aluprio_\<alpha> \<alpha> s). a \<le> y"
      using v12 by simp
    have v13:
      "map p_unwrap (map snd (\<alpha> s))
        = map p_unwrap (map  snd (\<alpha> l)) @ (e,a) # map p_unwrap (map snd (\<alpha> r))"
      using v8(1) v10 by auto
     hence v14:
      "map fst (map p_unwrap (map snd (\<alpha> s)))
         = map fst (map p_unwrap (map snd (\<alpha> l))) @ e
             # map fst (map p_unwrap (map snd (\<alpha> r)))"
       by auto
    hence v15:
      "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> l))))"
      "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> r))))"
      using invs(4) by auto
    note map_of_distinct_lookup[OF v15]
    note this[of a]
    hence ziel2: "aluprio_\<alpha> \<alpha> s e = Some a"
      using  v13
      by (unfold aluprio_defs, auto)
    have v16:
      "\<alpha> s' = \<alpha> l @ \<alpha> r"
      "invar s'"
      using v8(4,5) app_correct v10 by auto
    note map_of_distinct_upd4[OF v15]
    note this[of a]
    hence
      ziel3: "aluprio_\<alpha> \<alpha> s' = (aluprio_\<alpha> \<alpha> s)(e := None)"
      unfolding aluprio_defs
      using v16(1) v13 by auto
    have ziel4: "aluprio_invar \<alpha> invar s'"
      using v16 v8(1) invs(2,3,4)
      unfolding aluprio_defs
      by (auto simp add: sorted_append)

    show "aluprio_invar \<alpha> invar s' \<and>
          aluprio_\<alpha> \<alpha> s' = (aluprio_\<alpha> \<alpha> s)(e := None) \<and>
          aluprio_\<alpha> \<alpha> s e = Some a \<and> (\<forall>y\<in>ran (aluprio_\<alpha> \<alpha> s). a \<le> y)"
      using ziel1 ziel2 ziel3 ziel4 by simp
  qed
qed

lemmas aluprio_correct =
  aluprio_finite_correct
  aluprio_empty_correct
  aluprio_isEmpty_correct
  aluprio_insert_correct
  aluprio_pop_correct
  aluprio_prio_correct

locale aluprio_defs = StdALDefs ops
  for ops :: "(unit,('e::linorder,'a::linorder) LP,'s) alist_ops"
begin
  definition [icf_rec_def]: "aluprio_ops \<equiv> \<lparr>
    upr_\<alpha> = aluprio_\<alpha> \<alpha>,
    upr_invar = aluprio_invar \<alpha> invar,
    upr_empty = aluprio_empty empty,
    upr_isEmpty = aluprio_isEmpty isEmpty,
    upr_insert = aluprio_insert splits annot isEmpty app consr,
    upr_pop = aluprio_pop splits annot app,
    upr_prio = aluprio_prio splits annot isEmpty
    \<rparr>"

end

locale aluprio = aluprio_defs ops + StdAL ops
  for ops :: "(unit,('e::linorder,'a::linorder) LP,'s) alist_ops"
begin
  lemma aluprio_ops_impl: "StdUprio aluprio_ops"
    apply (rule StdUprio.intro)
    apply (simp_all add: icf_rec_unf)
    apply (rule aluprio_correct)
    apply (rule aluprio_correct, unfold_locales) []
    apply (rule aluprio_correct, unfold_locales) []
    apply (rule aluprio_correct, unfold_locales) []
    apply (rule aluprio_correct, unfold_locales) []
    apply (rule aluprio_correct, unfold_locales) []
    done
end

end


(*
  File:     Residues_Nat.thy
  Authors:  Daniel Stüwe, Manuel Eberl

  The multiplicative group of the ring of residues modulo n.
*)
section \<open>Residue Rings of Natural Numbers\<close>
theory Residues_Nat
  imports Algebraic_Auxiliaries
begin

subsection \<open>The multiplicative group of residues modulo \<open>n\<close>\<close>

definition Residues_Mult :: "'a :: {linordered_semidom, euclidean_semiring} \<Rightarrow> 'a monoid" where
  "Residues_Mult p =
     \<lparr>carrier = {x \<in> {1..p} . coprime x p}, monoid.mult = \<lambda>x y. x * y mod p, one = 1\<rparr>"

locale residues_mult_nat =
  fixes n :: nat and G
  assumes n_gt_1: "n > 1"
  defines "G \<equiv> Residues_Mult n"
begin

lemma carrier_eq [simp]: "carrier G = totatives n"
  and mult_eq [simp]:    "(x \<otimes>\<^bsub>G\<^esub> y) = (x * y) mod n"
  and one_eq [simp]:     "\<one>\<^bsub>G\<^esub> = 1"
  by (auto simp: G_def Residues_Mult_def totatives_def)

lemma mult_eq': "(\<otimes>\<^bsub>G\<^esub>) = (\<lambda>x y. (x * y) mod n)"
  by (intro ext; simp)+

sublocale group G
proof(rule groupI, goal_cases)
  case (1 x y)
  from 1 show ?case using n_gt_1
    by (auto intro!: Nat.gr0I simp: coprime_commute coprime_dvd_mult_left_iff
                                    coprime_absorb_left nat_dvd_not_less totatives_def)
next
  case (5 x)
  hence "(\<exists>y. y \<ge> 0 \<and> y < n \<and> [x * y = Suc 0] (mod n))"
    using coprime_iff_invertible'_nat[of n x] n_gt_1
    by (auto simp: totatives_def)
  then obtain y where y: "y \<ge> 0" "y < n" "[x * y = Suc 0] (mod n)" by blast

  from \<open>[x * y = Suc 0] (mod n)\<close> have "gcd (x * y) n = 1"
    by (simp add: cong_gcd_eq)
  hence "coprime y n" by fastforce

  with y n_gt_1 show "\<exists>y\<in>carrier G. y \<otimes>\<^bsub>G\<^esub> x = \<one>\<^bsub>G\<^esub>"
    by (intro bexI[of _ y]) (auto simp: totatives_def cong_def mult_ac intro!: Nat.gr0I)
qed (use n_gt_1 in \<open>auto simp: mod_simps algebra_simps totatives_less\<close>)

sublocale comm_group
  by unfold_locales (auto simp: mult_ac)

lemma nat_pow_eq [simp]: "x [^]\<^bsub>G\<^esub> (k :: nat) = (x ^ k) mod n"
  using n_gt_1 by (induction k) (simp_all add: mod_mult_left_eq mod_mult_right_eq mult_ac)

lemma nat_pow_eq': "([^]\<^bsub>G\<^esub>) = (\<lambda>x k. (x ^ k) mod n)"
  by (intro ext) simp

lemma order_eq: "order G = totient n"
  by (simp add: order_def totient_def)

lemma order_less: "\<not>prime n \<Longrightarrow> order G < n - 1"
  using totient_less_not_prime[of n] n_gt_1
  by (auto simp: order_eq)

lemma ord_residue_mult_group:
  assumes "a \<in> totatives n"
  shows   "local.ord a = Pocklington.ord n a"
proof (rule dvd_antisym)
  have "[a ^ local.ord a = 1] (mod n)"
    using pow_ord_eq_1[of a] assms by (auto simp: cong_def)
  thus "Pocklington.ord n a dvd local.ord a"
    by (subst (asm) ord_divides)
next
  show "local.ord a dvd Pocklington.ord n a"
    using assms Pocklington.ord[of a n] n_gt_1 pow_eq_id by (simp add: cong_def)
qed

end

subsection \<open>The ring of residues modulo \<open>n\<close>\<close>

definition Residues_nat :: "nat \<Rightarrow> nat ring" where
  "Residues_nat m = \<lparr>carrier = {0..<m}, monoid.mult = \<lambda>x y. (x * y) mod m, one = 1,
                     ring.zero = 0, add = \<lambda>x y. (x + y) mod m\<rparr>"

locale residues_nat =
  fixes n :: nat and R
  assumes n_gt_1: "n > 1"
  defines "R \<equiv> Residues_nat n"
begin

lemma carrier_eq [simp]: "carrier R = {0..<n}"
  and mult_eq [simp]: "x \<otimes>\<^bsub>R\<^esub> y = (x * y) mod n"
  and add_eq [simp]: "x \<oplus>\<^bsub>R\<^esub> y = (x + y) mod n"
  and one_eq [simp]: "\<one>\<^bsub>R\<^esub> = 1"
  and zero_eq [simp]: "\<zero>\<^bsub>R\<^esub> = 0"
  by (simp_all add: Residues_nat_def R_def)

lemma mult_eq': "(\<otimes>\<^bsub>R\<^esub>) = (\<lambda>x y. (x * y) mod n)"
  and add_eq': "(\<oplus>\<^bsub>R\<^esub>) = (\<lambda>x y. (x + y) mod n)"
  by (intro ext; simp)+

sublocale abelian_group R
proof(rule abelian_groupI, goal_cases)
  case (1 x y)
  then show ?case
    using n_gt_1
    by (auto simp: mod_simps algebra_simps simp flip: less_Suc_eq_le)
next
  case (6 x)
  { assume "x < n" "1 < n"
    hence "n - x \<in> {0..<n}" "((n - x) + x) mod n = 0" if "x \<noteq> 0"
      using that by auto
    moreover have "0 \<in> {0..<n}" "(0 + x) mod n = 0" if "x = 0"
      using that n_gt_1 by auto
    ultimately have "\<exists>y\<in>{0..<n}. (y + x) mod n = 0"
      by meson
  }

  with 6 show ?case using n_gt_1 by auto
qed (use n_gt_1 in \<open>auto simp add: mod_simps algebra_simps\<close>)

sublocale comm_monoid R
  using n_gt_1 by unfold_locales (auto simp: mult_ac mod_simps)

sublocale cring R
  by unfold_locales (auto simp: mod_simps algebra_simps)

lemma Units_eq: "Units R = totatives n"
proof safe
  fix x assume x: "x \<in> Units R"
  then obtain y where y: "[x * y = 1] (mod n)"
    using n_gt_1 by (auto simp: Units_def cong_def)
  hence "coprime x n"
    using cong_imp_coprime cong_sym coprime_1_left coprime_mult_left_iff by metis
  with x show "x \<in> totatives n" by (auto simp: totatives_def Units_def intro!: Nat.gr0I)
next
  fix x assume x: "x \<in> totatives n"
  then obtain y where "y < n" "[x * y = 1] (mod n)"
    using coprime_iff_invertible'_nat[of n x] by (auto simp: totatives_def)
  with x show "x \<in> Units R"
    using n_gt_1 by (auto simp: Units_def mult_ac cong_def totatives_less)
qed

sublocale units: residues_mult_nat n "units_of R"
proof unfold_locales
  show "units_of R \<equiv> Residues_Mult n"
    by (auto simp: units_of_def Units_eq Residues_Mult_def totatives_def Suc_le_eq mult_eq')
qed (use n_gt_1 in auto)

lemma nat_pow_eq [simp]: "x [^]\<^bsub>R\<^esub> (k :: nat) = (x ^ k) mod n"
  using n_gt_1 by (induction k) (auto simp: mod_simps mult_ac)

lemma nat_pow_eq': "([^]\<^bsub>R\<^esub>) = (\<lambda>x k. (x ^ k) mod n)"
  by (intro ext) simp

end

subsection \<open>The ring of residues modulo a prime\<close>

locale residues_nat_prime =
  fixes p :: nat and R
  assumes prime_p: "prime p"
  defines "R \<equiv> Residues_nat p"
begin

sublocale residues_nat p R
  using prime_gt_1_nat[OF prime_p] by unfold_locales (auto simp: R_def)

lemma carrier_eq' [simp]: "totatives p = {0<..<p}"
  using prime_p by (auto simp: totatives_prime)

lemma order_eq: "order (units_of R) = p - 1"
  using prime_p by (simp add: units.order_eq totient_prime)

lemma order_eq' [simp]: "totient p = p - 1"
  using prime_p by (auto simp: totient_prime)

sublocale field R
proof (rule cring_fieldI)
  show "Units R = carrier R - {\<zero>\<^bsub>R\<^esub>}"
    by (subst Units_eq) (use prime_p in \<open>auto simp: totatives_prime\<close>)
qed

lemma residues_prime_cyclic: "\<exists>x\<in>{0<..<p}. {0<..<p} = {y. \<exists>i. y = x ^ i mod p}"
proof -
  from n_gt_1 have "{0..<p} - {0} = {0<..<p}" by auto
  thus ?thesis using finite_field_mult_group_has_gen by simp
qed

lemma residues_prime_cyclic': "\<exists>x\<in>{0<..<p}. units.ord x = p - 1"
proof -
  from residues_prime_cyclic obtain x
    where x: "x \<in> {0<..<p}" "{0<..<p} = {y. \<exists>i. y = x ^ i mod p}" by metis
  have "units.ord x = p - 1"
  proof (intro antisym)
    show "units.ord x \<le> p - 1"
      using units.ord_dvd_group_order[of x] x(1) by (auto simp: units.order_eq intro!: dvd_imp_le)
  next
    (* TODO FIXME: a bit ugly; could be simplified if we had a theory of finite cyclic rings *)
    have "p - 1 = card {0<..<p}" by simp
    also have "{0<..<p} = {y. \<exists>i. y = x ^ i mod p}" by fact
    also have "card \<dots> \<le> card ((\<lambda>i. x ^ i mod p) ` {..<units.ord x})"
    proof (intro card_mono; safe?)
      fix j :: nat
      have "j = units.ord x * (j div units.ord x) + (j mod units.ord x)"
        by simp
      also have "x [^]\<^bsub>units_of R\<^esub> \<dots> = x [^]\<^bsub>units_of R\<^esub> (units.ord x * (j div units.ord x))
                   \<otimes>\<^bsub>units_of R\<^esub> x [^]\<^bsub>units_of R\<^esub> (j mod units.ord x)"
        using x by (subst units.nat_pow_mult) auto
      also have "x [^]\<^bsub>units_of R\<^esub> (units.ord x * (j div units.ord x)) =
                   (x [^]\<^bsub>units_of R\<^esub> units.ord x) [^]\<^bsub>units_of R\<^esub> (j div units.ord x)"
        using x by (subst units.nat_pow_pow) auto
      also have "x [^]\<^bsub>units_of R\<^esub> units.ord x = 1"
        using x(1) by (subst units.pow_ord_eq_1) auto
      finally have "x ^ j mod p = x ^ (j mod units.ord x) mod p" using n_gt_1 by simp
      thus "x ^ j mod p \<in> (\<lambda>i. x ^ i mod p) ` {..<units.ord x}"
        using units.ord_ge_1[of x] x(1) by force
    qed auto
    also have "\<dots> \<le> card {..<units.ord x}"
      by (intro card_image_le) auto
    also have "\<dots> = units.ord x" by simp
    finally show "p - 1 \<le> units.ord x" .
  qed
  with x show ?thesis by metis
qed

end

subsection \<open>\<open>-1\<close> in residue rings\<close>

lemma minus_one_cong_solve_weak:
  fixes n x :: nat
  assumes "1 < n" "x \<in> totatives n" "y \<in> totatives n"
    and  "[x = n - 1] (mod n)" "[x * y = 1] (mod n)"
  shows "y = n - 1"
proof -
  define G where "G = Residues_Mult n"
  interpret residues_mult_nat n G
    by unfold_locales (use \<open>n > 1\<close> in \<open>simp_all add: G_def\<close>)
  have "[x * (n - 1) = x * n - x] (mod n)"
    by (simp add: algebra_simps)
  also have "[x * n - x = (n - 1) * n - (n - 1)] (mod n)"
    using assms by (intro cong_diff_nat cong_mult) auto
  also have "(n - 1) * n - (n - 1) = (n - 1) ^ 2"
    by (simp add: power2_eq_square algebra_simps)
  also have "[(n - 1)\<^sup>2 = 1] (mod n)"
    using assms by (intro square_minus_one_cong_one) auto
  finally have "x * (n - 1) mod n = 1"
    using \<open>n > 1\<close> by (simp add: cong_def)
  hence "y = n - 1"
    using inv_unique'[of x "n - 1"] inv_unique'[of x y] minus_one_in_totatives[of n] assms(1-3,5)
    by (simp_all add: mult_ac cong_def)
  then show ?thesis by simp
qed

lemma coprime_imp_mod_not_zero:
  fixes n x :: nat
  assumes "1 < n" "coprime x n"
  shows "0 < x mod n"
  using assms coprime_0_left_iff nat_dvd_not_less by fastforce

lemma minus_one_cong_solve:
  fixes n x :: nat
  assumes "1 < n"
    and eq: "[x = n - 1] (mod n)" "[x * y = 1] (mod n)"
    and coprime: "coprime x n" "coprime y n"
  shows "[y = n - 1](mod n)"
proof -
  have "0 < x mod n" "0 < y mod n"
    using coprime coprime_imp_mod_not_zero \<open>1 < n\<close> by blast+
  moreover have "x mod n < n" "y mod n < n"
    using \<open>1 < n\<close> by auto
  moreover have "[x mod n = n - 1] (mod n)" "[x mod n * (y mod n) = 1] (mod n)"
    using eq by auto
  moreover have "coprime (x mod n) n" "coprime (y mod n) n"
    using coprime coprime_mod_left_iff \<open>1 < n\<close> by auto
  ultimately have "[y mod n = n - 1] (mod n)"
    using minus_one_cong_solve_weak[OF \<open>1 < n\<close>, of "x mod n" "y mod n"]
    by (auto simp: totatives_def)
  then show ?thesis by simp
qed

corollary square_minus_one_cong_one':
  fixes n x :: nat
  assumes "1 < n"
  shows "[(n - 1) * (n - 1) = 1](mod n)"
  using square_minus_one_cong_one[OF assms, of "n - 1"] assms
  by (fastforce simp: power2_eq_square)

end


(*  Title:      HOL/Hahn_Banach/Normed_Space.thy
    Author:     Gertrud Bauer, TU Munich
*)

section \<open>Normed vector spaces\<close>

theory Normed_Space
imports Subspace
begin

subsection \<open>Quasinorms\<close>

text \<open>
  A \<^emph>\<open>seminorm\<close> \<open>\<parallel>\<cdot>\<parallel>\<close> is a function on a real vector space into the reals that
  has the following properties: it is positive definite, absolute homogeneous
  and subadditive.
\<close>

locale seminorm =
  fixes V :: "'a::{minus, plus, zero, uminus} set"
  fixes norm :: "'a \<Rightarrow> real"    ("\<parallel>_\<parallel>")
  assumes ge_zero [iff?]: "x \<in> V \<Longrightarrow> 0 \<le> \<parallel>x\<parallel>"
    and abs_homogenous [iff?]: "x \<in> V \<Longrightarrow> \<parallel>a \<cdot> x\<parallel> = \<bar>a\<bar> * \<parallel>x\<parallel>"
    and subadditive [iff?]: "x \<in> V \<Longrightarrow> y \<in> V \<Longrightarrow> \<parallel>x + y\<parallel> \<le> \<parallel>x\<parallel> + \<parallel>y\<parallel>"

declare seminorm.intro [intro?]

lemma (in seminorm) diff_subadditive:
  assumes "vectorspace V"
  shows "x \<in> V \<Longrightarrow> y \<in> V \<Longrightarrow> \<parallel>x - y\<parallel> \<le> \<parallel>x\<parallel> + \<parallel>y\<parallel>"
proof -
  interpret vectorspace V by fact
  assume x: "x \<in> V" and y: "y \<in> V"
  then have "x - y = x + - 1 \<cdot> y"
    by (simp add: diff_eq2 negate_eq2a)
  also from x y have "\<parallel>\<dots>\<parallel> \<le> \<parallel>x\<parallel> + \<parallel>- 1 \<cdot> y\<parallel>"
    by (simp add: subadditive)
  also from y have "\<parallel>- 1 \<cdot> y\<parallel> = \<bar>- 1\<bar> * \<parallel>y\<parallel>"
    by (rule abs_homogenous)
  also have "\<dots> = \<parallel>y\<parallel>" by simp
  finally show ?thesis .
qed

lemma (in seminorm) minus:
  assumes "vectorspace V"
  shows "x \<in> V \<Longrightarrow> \<parallel>- x\<parallel> = \<parallel>x\<parallel>"
proof -
  interpret vectorspace V by fact
  assume x: "x \<in> V"
  then have "- x = - 1 \<cdot> x" by (simp only: negate_eq1)
  also from x have "\<parallel>\<dots>\<parallel> = \<bar>- 1\<bar> * \<parallel>x\<parallel>" by (rule abs_homogenous)
  also have "\<dots> = \<parallel>x\<parallel>" by simp
  finally show ?thesis .
qed

subsection \<open>Norms\<close>

text \<open>
  A \<^emph>\<open>norm\<close> \<open>\<parallel>\<cdot>\<parallel>\<close> is a seminorm that maps only the \<open>0\<close> vector to \<open>0\<close>.
\<close>

locale norm = seminorm +
  assumes zero_iff [iff]: "x \<in> V \<Longrightarrow> (\<parallel>x\<parallel> = 0) = (x = 0)"

subsection \<open>Normed vector spaces\<close>

text \<open>
  A vector space together with a norm is called a \<^emph>\<open>normed space\<close>.
\<close>

locale normed_vectorspace = vectorspace + norm

declare normed_vectorspace.intro [intro?]

lemma (in normed_vectorspace) gt_zero [intro?]:
  assumes x: "x \<in> V" and neq: "x \<noteq> 0"
  shows "0 < \<parallel>x\<parallel>"
proof -
  from x have "0 \<le> \<parallel>x\<parallel>" ..
  also have "0 \<noteq> \<parallel>x\<parallel>"
  proof
    assume "0 = \<parallel>x\<parallel>"
    with x have "x = 0" by simp
    with neq show False by contradiction
  qed
  finally show ?thesis .
qed

text \<open>
  Any subspace of a normed vector space is again a normed vectorspace.
\<close>

lemma subspace_normed_vs [intro?]:
  fixes F E norm
  assumes "subspace F E" "normed_vectorspace E norm"
  shows "normed_vectorspace F norm"
proof -
  interpret subspace F E by fact
  interpret normed_vectorspace E norm by fact
  show ?thesis
  proof
    show "vectorspace F" by (rule vectorspace) unfold_locales
  next
    have "Normed_Space.norm E norm" ..
    with subset show "Normed_Space.norm F norm"
      by (simp add: norm_def seminorm_def norm_axioms_def)
  qed
qed

end


theory neighborRelation
  imports Main
begin

text {* Idea of edge list representation taken from Nishihara and Minamide's paper:
      https://www.isa-afp.org/browser_info/current/AFP/Depth-First-Search/document.pdf *}

type_synonym node = int
type_synonym graph = "(node * node) list"

definition isReachable :: "[graph, node, node] ⇒ bool"
  where "isReachable g a b = (if a = b ∨ ((a, b) ∈ set g ∧ (b, a) ∈ set g) then True else False)"

theorem neighbor_reflexive:
  fixes a :: node
  fixes g :: graph
  shows "isReachable g a a"
  by (metis isReachable_def)

theorem neighbor_symmetric:
  fixes a b :: node
  fixes g :: graph
  assumes "isReachable g a b"
  shows "isReachable g b a"
    by (metis assms isReachable_def)

theorem neighbor_not_transitive:
  shows "∃ (g :: graph) (a :: node) (b :: node) (c :: node). isReachable g a b ∧ isReachable g b c ∧ ¬isReachable g a c"
proof -
  obtain a b c :: node where unique: "a ≠ b ∧ b ≠ c ∧ a ≠ c"
  proof -
    assume a1: "⋀a b c. (a::int) ≠ b ∧ b ≠ c ∧ a ≠ c ⟹ thesis"
    have f2: "(0::int) ≠ 2"
      by auto
    have f3: "(1::int) ≠ 2"
      by auto
    have "(0::int) ≠ 1"
      by auto
    then show ?thesis
      using f3 f2 a1 by blast
  qed
  obtain g :: graph where G: "g = (a, b) # (b, a) # (b, c) # (c, b) # []" by auto

  have "(a, b) ∈ set g" and baInG: "(b, a) ∈ set g" using G by auto
  hence ab: "isReachable g a b" using isReachable_def by metis

  have "(b, c) ∈ set g" and cbInG: "(c, b) ∈ set g" using G by auto
  hence bc: "isReachable g b c" using isReachable_def by metis

  have ac: "¬ isReachable g a c"
  proof-
    from G have "g = (a, b) # (b, a) # (b, c) # (c, b) # []" by auto
    then have "set g = {(a, b), (b, a), (b, c), (c, b)}" by auto
    then have "(a, c) ∉ set g" using unique by auto
    thus ?thesis using isReachable_def unique by auto
  qed

  show ?thesis using ab ac bc by auto
qed

end


chapter "Orbit-Stabiliser Theorem"
text \<open>
In this Theory we will prove the orbit-stabiliser theorem, a basic result in the algebra of groups.

\<close>

theory Orbit_Stabiliser
  imports
    "HOL-Algebra.Left_Coset"

begin

section "Imports"
text \<open>
  /HOL/Algebra/Group.thy is used for the definitions of groups and subgroups
\<close>

text \<open>
  Left\_Coset.thy is a copy of /HOL/Algebra/Coset.thy that includes additional theorems about left cosets.

  The version of Coset.thy in the Isabelle library is missing some theorems about left cosets
  that are available for right cosets, so these had to be added by simply replacing the definitions
  of right cosets with those of left cosets.

  Coset.thy is used for definitions of group order, quotient groups (operator LMod), and Lagranges theorem.
\<close>

text \<open>
  /HOL/Fun.thy is used for function composition and the identity function.
\<close>

section "Group Actions"

text \<open>
  We begin by augmenting the existing definition of a group with a group action.

  The group action was defined according to \<^cite>\<open>groupaction\<close>.
\<close>

locale orbit_stabiliser = group +
  fixes action :: "'a \<Rightarrow> 'b \<Rightarrow> 'b" (infixl "\<odot>" 51)
  assumes id_act [simp]: "\<one> \<odot> x = x"
    and compat_act:
    "g \<in> carrier G \<and> h \<in> carrier G \<longrightarrow> g \<odot> (h \<odot> x) = (g \<otimes> h) \<odot> x"

section "Orbit and stabiliser"

text \<open>
Next, we define orbit and stabiliser, according to the same Wikipedia article.
\<close>

context orbit_stabiliser
begin

definition orbit :: "'b \<Rightarrow> 'b set" where
  "orbit x = {y. (\<exists> g \<in> carrier G. y = g \<odot> x)}"

definition stabiliser :: "'b \<Rightarrow> 'a set"
  where "stabiliser x = {g \<in> carrier G. g \<odot> x = x}"

section "Stabiliser Theorems"

text \<open>
We begin our proofs by showing that the stabiliser forms a subgroup.

This proof follows the template from  \<^cite>\<open>stabsub\<close>.
\<close>

theorem stabiliser_subgroup: "subgroup (stabiliser x) G"
proof(rule subgroupI)
  show "stabiliser x \<subseteq> carrier G" using stabiliser_def by auto
next
  fix x
  from id_act have "\<one> \<odot> x = x" by simp
  then have "\<one> \<in> stabiliser x" using stabiliser_def by auto
  then show "stabiliser x \<noteq> {}" by auto
next
  fix g x
  assume gStab:"g \<in> stabiliser x"
  then have g_car:"g \<in> carrier G" using stabiliser_def by simp
  then have invg_car:"inv g \<in> carrier G" using inv_closed by simp
  have "g \<odot> x = x" using stabiliser_def gStab by simp
  then have "inv g \<odot> (g \<odot> x) = inv g \<odot> x" by simp
  then have "(inv g \<otimes> g) \<odot> x = inv g \<odot> x" using compat_act g_car invg_car by simp
  then have "x = (inv g) \<odot> x" using g_car l_inv by simp
  then show "inv g \<in> stabiliser x" using invg_car stabiliser_def by simp
next
  fix g h x
  assume g_stab: "g \<in> stabiliser x" and h_stab: "h \<in> stabiliser x"
  then have g_car: "g \<in> carrier G" and h_car: "h \<in> carrier G" using stabiliser_def by auto
  then have "g \<odot> x = x" "h \<odot> x = x"
    using stabiliser_def g_stab h_stab by auto
  then have "g \<odot> (h \<odot> x) = x" by simp
  then have "(g \<otimes> h) \<odot> x = x" using compat_act g_car h_car by simp
  then show "(g \<otimes> h) \<in> stabiliser x"
    using g_stab h_stab stabiliser_def by auto
qed

text \<open>
As an intermediate step we formulate a lemma about the relationship between the group action
and the stabiliser.

This proof follows the template from \<^cite>\<open>stabsubcor\<close>.
\<close>

corollary stabiliser_subgroup_corollary:
  assumes g_car: "g \<in> carrier G" and
    h_car: "h \<in> carrier G"
  shows "(g \<odot> x) = (h \<odot> x) \<longleftrightarrow> ((inv g) \<otimes> h) \<in> stabiliser x"
proof
  from g_car have invg_car: "(inv g) \<in> carrier G" by auto
  show "(g \<odot> x) = (h \<odot> x) \<Longrightarrow> inv g \<otimes> h \<in> stabiliser x"
  proof -
    assume gh: "(g \<odot> x) = (h \<odot> x)"
    have "((inv g) \<otimes> h) \<odot> x = (inv g) \<odot> (h \<odot> x)" using assms compat_act by simp
    moreover have "(inv g) \<odot> (h \<odot> x) = (inv g) \<odot> (g \<odot> x)" using gh by simp
    moreover have "(inv g) \<odot> (g \<odot> x) = ((inv g) \<otimes> g) \<odot> x" using invg_car g_car compat_act by simp
    moreover have "((inv g) \<otimes> g) \<odot> x = x" using g_car by simp
    ultimately have "((inv g) \<otimes> h) \<odot> x = x" by simp
    then show ?thesis using stabiliser_def assms by simp
  qed

  show "inv g \<otimes> h \<in> stabiliser x \<Longrightarrow> g \<odot> x = h \<odot> x"
  proof -
    assume gh_stab: "inv g \<otimes> h \<in> stabiliser x"
    with stabiliser_def have "x = ((inv g) \<otimes> h) \<odot> x" by simp
    then have "\<one> \<odot> x = ((inv g) \<otimes> h) \<odot> x"  by simp
    then have "((inv g) \<otimes> g) \<odot> x = ((inv g) \<otimes> h) \<odot> x" using invg_car g_car by simp
    then have "x = (inv g) \<odot> (h \<odot> x)" using compat_act g_car h_car by simp
    then have "g \<odot> x = (g \<otimes> (inv g)) \<odot> (h \<odot> x)" using compat_act g_car invg_car by metis
    then have "g \<odot> x = h \<odot> x" using compat_act g_car id_act invg_car r_inv by simp
    then show ?thesis by simp
  qed
qed

text \<open>
Using the previous lemma and our proof that the stabiliser forms a subgroup, we can now
show that the elements of the orbit map to left cosets of the stabiliser.

This will later form the basis of showing a bijection between the orbit and those cosets.
\<close>

lemma stabiliser_cosets_equivalent:
  assumes g_car: "g \<in> carrier G" and
    h_car: "h \<in> carrier G"
  shows "(g \<odot> x) = (h \<odot> x) \<longleftrightarrow> (g <# stabiliser x) = (h <# stabiliser x)"
proof
  show "g \<odot> x = h \<odot> x \<Longrightarrow> g <# stabiliser x = h <# stabiliser x"
  proof -
    assume "g \<odot> x = h \<odot> x"
    then have stab_elem: "((inv g) \<otimes> h) \<in> stabiliser x"
      using assms stabiliser_subgroup_corollary by simp
    with subgroup.lcos_module_rev[OF stabiliser_subgroup] have "h \<in> g <# (stabiliser x)"
      using assms is_group by simp
    with l_repr_independence have  "g <# (stabiliser x) = h <# (stabiliser x)"
      using assms  stab_elem stabiliser_subgroup by auto
    then show ?thesis by simp
  qed
  show "g <# stabiliser x = h <# stabiliser x \<Longrightarrow> g \<odot> x = h \<odot> x"
  proof -
    assume "g <# stabiliser x = h <# stabiliser x"
    with subgroup.lcos_module_rev[OF stabiliser_subgroup] have "h \<in> g <# (stabiliser x)"
      using assms is_group l_inv stabiliser_subgroup subgroup_def by metis
    with subgroup.lcos_module_imp[OF stabiliser_subgroup] have "((inv g) \<otimes> h) \<in> stabiliser x"
      using assms is_group by blast
    with stabiliser_subgroup_corollary have "g \<odot> x = h \<odot> x" using assms by simp
    then show ?thesis by simp
  qed
qed

section "Picking representatives from cosets"

text \<open>
Before we can prove the bijection, we need a few lemmas about representatives from sets.

First we define rep to be an arbitrary element from a left coset of the stabiliser.
\<close>
definition rep :: "'a set \<Rightarrow> 'a" where
  "(H \<in> carrier (G LMod (stabiliser x))) \<Longrightarrow> rep H = (SOME y. y \<in> H)"

text \<open>
  The next lemma shows that the representative is always an element of its coset.
\<close>
lemma quotient_rep_ex  : "H \<in> (carrier (G LMod (stabiliser x))) \<Longrightarrow> rep H \<in> H"
proof -
  fix H
  assume H:"H \<in> carrier (G LMod stabiliser x)"
  then obtain g where "g \<in> carrier G" "H = g <# (stabiliser x)"
    unfolding LFactGroup_def LCOSETS_def by auto
  then have "(SOME x. x \<in> H) \<in> H" using lcos_self stabiliser_subgroup someI_ex by fast
  then show "rep H \<in> H" using H rep_def by auto
qed

text \<open>
The final lemma about representatives shows that it does not matter which element of the coset
is picked, i.e. all representatives are equivalent.
\<close>
lemma rep_equivalent:
  assumes H:"H \<in> carrier (G LMod stabiliser x)" and
    gH:"g \<in> H"
  shows "H = g <# (stabiliser x)"
proof -
  fix h
  from H obtain h where hG:"h \<in> carrier G" and H2:"H = h <# (stabiliser x)"
    unfolding LFactGroup_def LCOSETS_def by auto
  with H gH have gh:"g \<in> h <# (stabiliser x)" by simp
  from l_repr_independence have "h <# stabiliser x = g <# stabiliser x"
    using hG gh stabiliser_subgroup by simp
  with H2 have "H = g <# (stabiliser x)" by simp
  then show ?thesis by simp
qed

section "Orbit-Stabiliser Theorem"

text \<open>
  We can now establish the bijection between orbit(x) and the quotient group G/(stabiliser(x))

  The idea for this bijection is from \<^cite>\<open>orbitstab\<close>
\<close>
theorem orbit_stabiliser_bij:
  "bij_betw (\<lambda>H. rep H \<odot> x) (carrier (G LMod (stabiliser x))) (orbit x) "
proof (rule bij_betw_imageI)
  (* show the function is injective *)
  show "inj_on (\<lambda>H. rep H \<odot> x) (carrier (G LMod stabiliser x))"
  proof(rule inj_onI)
    fix H H'
    assume H:"H \<in> carrier (G LMod (stabiliser x))"
    assume H':"H' \<in> carrier (G LMod (stabiliser x))"
    obtain h h' where  h:"h = rep H" and h': "h' = rep H'" by simp
    assume act_equal: "(rep H) \<odot> x = (rep H') \<odot> x"
    from H h quotient_rep_ex have hH: "h \<in> H" by simp
    from H' h' quotient_rep_ex have hH': "h' \<in> H'" by simp
    from subgroup.lcosets_carrier[OF stabiliser_subgroup is_group] H have "H \<subseteq> carrier G"
      unfolding LFactGroup_def by simp
    then have hG: "h \<in> carrier G" using hH by auto
    from subgroup.lcosets_carrier[OF stabiliser_subgroup is_group] H' have "H' \<subseteq> carrier G"
      unfolding LFactGroup_def by simp
    then have h'G: "h' \<in> carrier G" using hH' by auto

        (* Apply lemma about equivalent cosets *)
    have hh'_equiv:"h <# (stabiliser x) = h' <# (stabiliser x)"
      using hG h'G h h' act_equal stabiliser_cosets_equivalent by simp

    from hh'_equiv have H2:"H = h <# (stabiliser x)"
      using H hH rep_equivalent by blast
    moreover from hh'_equiv have H3:"H' = h <# (stabiliser x)"
      using H' hH' rep_equivalent by blast
    then show "H = H'" using H2 H3 by simp
  qed
next
  show "(\<lambda>H. rep H \<odot> x) ` carrier (G LMod stabiliser x) = orbit x"
  proof(auto)
    show "\<And>H. H \<in> carrier (G LMod stabiliser x) \<Longrightarrow> rep H \<odot> x \<in> orbit x"
    proof -
      fix H
      assume H:"H \<in> carrier (G LMod (stabiliser x))"
      obtain h where h:"h = rep H" by simp
      from H h quotient_rep_ex have hH: "h \<in> H" by simp
      have stab_sub: "(stabiliser x) \<subseteq> carrier G" using stabiliser_def by auto
      from subgroup.lcosets_carrier[OF stabiliser_subgroup is_group] H have "H \<subseteq> carrier G"
        unfolding LFactGroup_def by simp
      with hH have "h \<in> carrier G" by auto
      then show "(rep H) \<odot> x \<in> orbit x" using h orbit_def mem_Collect_eq by blast
    qed
    show "\<And>y. y \<in> orbit x \<Longrightarrow> y \<in> (\<lambda>H. rep H \<odot> x) ` carrier (G LMod stabiliser x)"
    proof -
      fix y
      assume y:"y \<in> orbit x"
      obtain g  where gG:"g \<in> carrier G" and "y = g \<odot> x" using y orbit_def by auto
      obtain H where H:"H = g <# (stabiliser x)" by auto
      with gG have H_carr:"H \<in> carrier (G LMod stabiliser x)"
        unfolding LFactGroup_def LCOSETS_def by auto
      then have "rep H \<in> H" using quotient_rep_ex by auto
      then obtain h where h_stab:"h \<in> stabiliser x" and gh:"rep H = g \<otimes> h"
        unfolding H l_coset_def by auto
      have hG:"h \<in> carrier G" using h_stab stabiliser_def by auto
      from stabiliser_def h_stab have "h \<odot> x = x" by auto
      with \<open>y = g \<odot> x\<close> have "y = g \<odot> (h \<odot> x)" by simp
      then have "y = (g \<otimes> h) \<odot> x" using gG hG compat_act by auto
      then have "y = (rep H) \<odot> x" using gh by simp
      then show "y \<in> (\<lambda>H. rep H \<odot> x) ` carrier (G LMod stabiliser x)"
        using H_carr by simp
    qed
  qed
qed

text\<open>
  The actual orbit-stabiliser theorem is a consequence of the bijection
   we established in the previous theorem and of Lagrange's theorem
\<close>
theorem orbit_stabiliser:
  assumes finite: "finite (carrier G)"
  shows "order G = card (orbit x) * card (stabiliser x)"
proof -
  have "card (carrier (G LMod (stabiliser x))) = card (orbit x)"
    using bij_betw_same_card orbit_stabiliser_bij by auto
  moreover have "card (carrier (G LMod (stabiliser x))) * card (stabiliser x)  = order G"
    using finite stabiliser_subgroup l_lagrange unfolding LFactGroup_def by simp
  ultimately show ?thesis by simp
qed
end

end