(* Property from Case-Analysis for Rippling and Inductive Proof,
   Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010.
   This Isabelle theory is produced using the TIP tool offered at the following website:
     https://github.com/tip-org/tools
   This file was originally provided as part of TIP benchmark at the following website:
     https://github.com/tip-org/benchmarks
   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
   to make it compatible with Isabelle2017.*)
  theory TIP_prop_19
  imports "../../Test_Base"
begin

datatype 'a list = nil2 | cons2 "'a" "'a list"

datatype Nat = Z | S "Nat"

fun len :: "'a list => Nat" where
  "len (nil2) = Z"
| "len (cons2 y xs) = S (len 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 t2 :: "Nat => Nat => Nat" where
  "t2 (Z) y = Z"
| "t2 (S z) (Z) = S z"
| "t2 (S z) (S x2) = t2 z x2"

theorem property0 :
  "((len (drop n xs)) = (t2 (len xs) n))"
  oops

end


theory sort_HSortPermutes'
imports Main
        "$HIPSTER_HOME/IsaHipster"
begin

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

datatype 'a Heap = Node "'a Heap" "'a" "'a Heap" | Nil2

fun toHeap2 :: "int list => (int Heap) list" where
"toHeap2 (Nil2) = Nil2"
| "toHeap2 (Cons2 y z) = Cons2 (Node (Nil2) y (Nil2)) (toHeap2 z)"

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

fun null :: "'t list => bool" where
"null (Nil2) = True"
| "null (Cons2 y z) = False"

fun hmerge :: "int Heap => int Heap => int Heap" where
"hmerge (Node z x2 x3) (Node x4 x5 x6) =
   (if x2 <= x5 then Node (hmerge x3 (Node x4 x5 x6)) x2 z else
      Node (hmerge (Node z x2 x3) x6) x5 x4)"
| "hmerge (Node z x2 x3) (Nil2) = Node z x2 x3"
| "hmerge (Nil2) y = y"

fun hpairwise :: "(int Heap) list => (int Heap) list" where
"hpairwise (Nil2) = Nil2"
| "hpairwise (Cons2 p (Nil2)) = Cons2 p (Nil2)"
| "hpairwise (Cons2 p (Cons2 q qs)) =
     Cons2 (hmerge p q) (hpairwise qs)"

fun hmerging :: "(int Heap) list => int Heap" where
"hmerging (Nil2) = Nil2"
| "hmerging (Cons2 p (Nil2)) = p"
| "hmerging (Cons2 p (Cons2 z x2)) =
     hmerging (hpairwise (Cons2 p (Cons2 z x2)))"

fun toHeap :: "int list => int Heap" where
"toHeap x = hmerging (toHeap2 x)"

fun toList :: "int Heap => int list" where
"toList (Node p y q) = Cons2 y (toList (hmerge p q))"
| "toList (Nil2) = Nil2"

fun elem :: "int => int list => bool" where
"elem x (Nil2) = False"
| "elem x (Cons2 z ys) = or2 (x = z) (elem x ys)"

fun dot :: "('b => 'c) => ('a => 'b) => 'a => 'c" where
"dot x y z = x (y z)"

fun hsort :: "int list => int list" where
"hsort x =
   dot
     (% (y :: int Heap) => toList y) (% (z :: int list) => toHeap z) x"

fun delete :: "int => int list => int list" where
"delete x (Nil2) = Nil2"
| "delete x (Cons2 z ys) =
     (if x = z then ys else Cons2 z (delete x ys))"

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

fun isPermutation :: "int list => int list => bool" where
"isPermutation (Nil2) y = null y"
| "isPermutation (Cons2 z xs) y =
     and2 (elem z y) (isPermutation xs (delete z y))"

(*hipster toHeap2
          or2
          null
          hmerge
          hpairwise
          hmerging
          toHeap
          toList
          elem
          dot
          hsort
          delete
          and2
          isPermutation *)

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

end


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

section \<open>Reflexive Transitive Closure\<close>

theory Relation_Algebra_RTC
  imports Relation_Algebra
begin

text \<open>We impose the Kleene algebra axioms for the star on relation algebras.
This gives us a reflexive transitive closure operation.\<close>

class relation_algebra_rtc = relation_algebra + star_op +
  assumes rtc_unfoldl: "1' +  x ; x\<^sup>\<star> \<le> x\<^sup>\<star>"
    and rtc_inductl: "z + x ; y \<le> y \<longrightarrow> x\<^sup>\<star> ; z \<le> y"
    and rtc_inductr: "z + y ; x \<le> y \<longrightarrow> z ; x\<^sup>\<star> \<le> y"

sublocale relation_algebra_rtc \<subseteq> kleene_algebra "(+)" "(;)" "1'" 0 "(\<le>)" "(<)" star
apply (unfold_locales)
  apply (rule rtc_unfoldl)
 apply (simp add: local.rtc_inductl)
apply (simp add: rtc_inductr)
done

context relation_algebra_rtc
begin

text \<open>First, we prove that the obvious interaction between the star and
converse is captured by the axioms.\<close>

lemma star_conv: "(x\<^sup>\<star>)\<^sup>\<smile> = (x\<^sup>\<smile>)\<^sup>\<star>"
proof (rule order.antisym)
  show "(x\<^sup>\<smile>)\<^sup>\<star> \<le> (x\<^sup>\<star>)\<^sup>\<smile>"
    by (metis local.conv_add local.conv_contrav local.conv_e local.conv_iso local.star_rtc1 local.star_rtc_least)
  show "(x\<^sup>\<star>)\<^sup>\<smile> \<le> (x\<^sup>\<smile>)\<^sup>\<star>"
    by (metis boffa_var conv_add conv_contrav conv_e conv_invol conv_iso star_denest star_ext star_iso star_plus_one sup.idem)
qed

text \<open>Next we provide an example to show how facts from Kleene algebra are
picked up in relation algebra.\<close>

lemma rel_church_rosser: "(x\<^sup>\<smile>)\<^sup>\<star> ; x\<^sup>\<star> \<le> x\<^sup>\<star> ; (x\<^sup>\<smile>)\<^sup>\<star> \<Longrightarrow> (x + x\<^sup>\<smile>)\<^sup>\<star> = x\<^sup>\<star> ; (x\<^sup>\<smile>)\<^sup>\<star>"
by (fact church_rosser)

end (* relation_algebra_rtc *)

end


(* This Isabelle theory is produced using the TIP tool offered at the following website:
     https://github.com/tip-org/tools
   This file was originally provided as part of TIP benchmark at the following website:
     https://github.com/tip-org/benchmarks
   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
   to make it compatible with Isabelle2017.*)
  theory TIP_sort_nat_SSortCount
  imports "../../Test_Base"
begin

datatype 'a list = nil2 | cons2 "'a" "'a list"

datatype Nat = Z | S "Nat"

fun plus :: "Nat => Nat => Nat" where
  "plus (Z) y = y"
| "plus (S z) y = S (plus z y)"

fun le :: "Nat => Nat => bool" where
  "le (Z) y = True"
| "le (S z) (Z) = False"
| "le (S z) (S x2) = le z x2"

fun ssortminimum1 :: "Nat => Nat list => Nat" where
  "ssortminimum1 x (nil2) = x"
| "ssortminimum1 x (cons2 y1 ys1) =
     (if le y1 x then ssortminimum1 y1 ys1 else ssortminimum1 x ys1)"

fun deleteBy :: "('a => ('a => bool)) => 'a => 'a list =>
                 'a list" where
  "deleteBy x y (nil2) = nil2"
| "deleteBy x y (cons2 y2 ys) =
     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))"

(*fun did not finish the proof*)
function ssort :: "Nat list => Nat list" where
  "ssort (nil2) = nil2"
| "ssort (cons2 y ys) =
     (let m :: Nat = ssortminimum1 y ys
     in cons2
          m
          (ssort
             (deleteBy
                (% (z :: Nat) => % (x2 :: Nat) => (z = x2)) m (cons2 y ys))))"
  by pat_completeness auto

fun count :: "'a => 'a list => Nat" where
  "count x (nil2) = Z"
| "count x (cons2 z ys) =
     (if (x = z) then plus (S Z) (count x ys) else count x ys)"

theorem property0 :
  "((count x (ssort xs)) = (count x xs))"
  oops

end


(* This Isabelle theory is produced using the TIP tool offered at the following website:
     https://github.com/tip-org/tools
   This file was originally provided as part of TIP benchmark at the following website:
     https://github.com/tip-org/benchmarks
   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
   to make it compatible with Isabelle2017.
\:w
   Some proofs were added by Yutaka Nagashima.*)
  theory TIP_sort_TSortCount
imports "../../Test_Base"
begin

datatype 'a list = nil2 | cons2 "'a" "'a list"

datatype Tree = TNode "Tree" "int" "Tree" | TNil

fun flatten :: "Tree => int list => int list" where
"flatten (TNode p z q) y = flatten p (cons2 z (flatten q y))"
| "flatten (TNil) y = y"

fun count :: "'a => 'a list => int" where
"count x (nil2) = 0"
| "count x (cons2 z ys) =
     (if (x = z) then 1 + (count x ys) else count x ys)"

fun add :: "int => Tree => Tree" where
"add x (TNode p z q) =
   (if x <= z then TNode (add x p) z q else TNode p z (add x q))"
| "add x (TNil) = TNode TNil x TNil"

fun toTree :: "int list => Tree" where
"toTree (nil2) = TNil"
| "toTree (cons2 y xs) = add y (toTree xs)"

fun tsort :: "int list => int list" where
"tsort x = flatten (toTree x) (nil2)"

theorem property0 :
  "((count x (tsort xs)) = (count x xs))"
  oops

end


theory Tree imports Main begin

subsection "Tree"

inductive_set
  tree :: "['a => 'a set,'a] => (nat * 'a) set"
  for subs :: "'a => 'a set" and gamma :: 'a
  (******
   * This set represents the nodes in a tree which may represent a proof of gamma.
   * Only storing the annotation and its level.
   * NOTE: could parameterize on subs
   ******)
  where
    tree0: "(0,gamma) : tree subs gamma"

  | tree1: "[| (n,delta) : tree subs gamma; sigma : subs delta |]
            ==> (Suc n,sigma) : tree subs gamma"

declare tree.cases [elim]
declare tree.intros [intro]

lemma tree0Eq: "(0,y) : tree subs gamma = (y = gamma)"
  apply(rule iffI)
  apply (erule tree.cases, auto)
  done

lemma tree1Eq [rule_format]:
    "\<forall>Y. (Suc n,Y) \<in> tree subs gamma = (\<exists>sigma \<in> subs gamma . (n,Y) \<in> tree subs sigma)"
  by (induct n) (blast, force)
    \<comment> \<open>moving down a tree\<close>

definition
  incLevel :: "nat * 'a => nat * 'a" where
  "incLevel = (% (n,a). (Suc n,a))"

lemma injIncLevel: "inj incLevel"
  apply(simp add: incLevel_def)
  apply(rule inj_onI)
  apply auto
  done

lemma treeEquation: "tree subs gamma = insert (0,gamma) (UN delta:subs gamma . incLevel ` tree subs delta)"
  apply(rule set_eqI)
  apply(simp add: split_paired_all)
  apply(case_tac a)
   apply(force simp add: tree0Eq incLevel_def)
  apply(force simp add: tree1Eq incLevel_def)
  done

definition
  fans :: "['a => 'a set] => bool" where
  "fans subs \<longleftrightarrow> (!x. finite (subs x))"

lemma fansD: "fans subs ==> finite (subs A)"
  by(simp add: fans_def)

lemma fansI:  "(!A. finite (subs A)) ==> fans subs"
  by(simp add: fans_def)

subsection "Terminal"

definition
  terminal :: "['a => 'a set,'a] => bool" where
  "terminal subs delta \<longleftrightarrow> subs(delta) = {}"

lemma terminalD: "terminal subs Gamma ==> x ~: subs Gamma"
  by(simp add: terminal_def)
  \<comment> \<open>not a good dest rule\<close>

lemma terminalI: "x \<in> subs Gamma ==> ~ terminal subs Gamma"
  by(auto simp add: terminal_def)
  \<comment> \<open>not a good intro rule\<close>

subsection "Inherited"

definition
  inherited :: "['a => 'a set,(nat * 'a) set => bool] => bool" where
  "inherited subs P \<longleftrightarrow> (!A B. (P A & P B) = P (A Un B))
                       & (!A. P A = P (incLevel ` A))
                       & (!n Gamma A. ~(terminal subs Gamma) --> P A = P (insert (n,Gamma) A))
                       & (P {})"

    (******
     inherited properties:
        - preserved under: dividing into 2, join 2 parts
                           moving up/down levels
                           inserting non terminal nodes
        - hold on empty node set
     ******)

  \<comment> \<open>FIXME tjr why does it have to be invariant under inserting nonterminal nodes?\<close>

lemma inheritedUn[rule_format]:"inherited subs P --> P A --> P B --> P (A Un B)"
  by (auto simp add: inherited_def)

lemma inheritedIncLevel[rule_format]: "inherited subs P --> P A --> P (incLevel ` A)"
  by (auto simp add: inherited_def)

lemma inheritedEmpty[rule_format]: "inherited subs P --> P {}"
  by (auto simp add: inherited_def)

lemma inheritedInsert[rule_format]:
  "inherited subs P --> ~(terminal subs Gamma) --> P A --> P (insert (n,Gamma) A)"
  by (auto simp add: inherited_def)

lemma inheritedI[rule_format]: "[| \<forall>A B . (P A & P B) = P (A Un B);
  \<forall>A . P A = P (incLevel ` A);
  \<forall>n Gamma A . ~(terminal subs Gamma) --> P A = P (insert (n,Gamma) A);
  P {} |] ==> inherited subs P"
  by (simp add: inherited_def)

(* These only for inherited join, and a few more places... *)
lemma inheritedUnEq[rule_format, symmetric]: "inherited subs P --> (P A & P B) = P (A Un B)"
  by (auto simp add: inherited_def)

lemma inheritedIncLevelEq[rule_format, symmetric]: "inherited subs P --> P A = P (incLevel ` A)"
  by (auto simp add: inherited_def)

lemma inheritedInsertEq[rule_format, symmetric]: "inherited subs P --> ~(terminal subs Gamma) --> P A = P (insert (n,Gamma) A)"
  by (auto simp add: inherited_def)

lemmas inheritedUnD = iffD1[OF inheritedUnEq]

lemmas inheritedInsertD = inheritedInsertEq[THEN iffD1]

lemmas inheritedIncLevelD = inheritedIncLevelEq[THEN iffD1]

lemma inheritedUNEq[rule_format]:
  "finite A --> inherited subs P --> (!x:A. P (B x)) = P (UN a:A. B a)"
  apply(intro impI)
  apply(erule finite_induct)
  apply simp
  apply(simp add: inheritedEmpty)
  apply(force dest: inheritedUnEq)
  done

lemmas inheritedUN  = inheritedUNEq[THEN iffD1]

lemmas inheritedUND[rule_format] = inheritedUNEq[THEN iffD2]

lemma inheritedPropagateEq[rule_format]: assumes a: "inherited subs P"
  and b: "fans subs"
  and c: "~(terminal subs delta)"
  shows "P(tree subs delta) = (!sigma:subs delta. P(tree subs sigma))"
  apply(insert fansD[OF b])
  apply(subst treeEquation [of _ delta])
  using assms
  apply(simp add: inheritedInsertEq inheritedUNEq[symmetric] inheritedIncLevelEq)
  done

lemma inheritedPropagate:
 "[| ~P(tree subs delta); inherited subs P; fans subs; ~(terminal subs delta)|]
  ==> \<exists>sigma \<in> subs delta . ~P(tree subs sigma)"
  by(simp add: inheritedPropagateEq)

lemma inheritedViaSub: "[| inherited subs P; fans subs; P(tree subs delta); sigma \<in> subs delta |]
  ==> P(tree subs sigma)"
  apply(frule_tac terminalI)
  apply(simp add: inheritedPropagateEq)
  done

lemma inheritedJoin[rule_format]:
    "(inherited subs P & inherited subs Q) --> inherited subs (%x. P x & Q x)"
  by(blast intro!: inheritedI
     dest: inheritedUnEq inheritedIncLevelEq inheritedInsertEq inheritedEmpty)

lemma inheritedJoinI[rule_format]: "[| inherited subs P; inherited subs Q; R = ( % x . P x & Q x) |] ==> inherited subs R"
  by(blast intro!:inheritedI dest: inheritedUnEq inheritedIncLevelEq inheritedInsertEq inheritedEmpty)

subsection "bounded, boundedBy"

definition
  boundedBy :: "nat => (nat * 'a) set => bool" where
  "boundedBy N A \<longleftrightarrow> (\<forall>(n,delta) \<in> A. n < N)"

definition
  bounded :: "(nat * 'a) set => bool" where
  "bounded A \<longleftrightarrow> (\<exists>N . boundedBy N A)"

lemma boundedByEmpty[simp]: "boundedBy N {}"
  by(simp add: boundedBy_def)

lemma boundedByInsert: "boundedBy N (insert (n,delta) B)     = (n < N & boundedBy N B)"
  by(simp add: boundedBy_def)

lemma boundedByUn: "boundedBy N (A Un B) = (boundedBy N A & boundedBy N B)"
  by(auto simp add: boundedBy_def)

lemma boundedByIncLevel': "boundedBy (Suc N) (incLevel ` A) = boundedBy N A"
  by(auto simp add: incLevel_def boundedBy_def)

lemma boundedByAdd1: "boundedBy N B \<Longrightarrow> boundedBy (N+M) B"
  by(auto simp add: boundedBy_def)

lemma boundedByAdd2: "boundedBy M B \<Longrightarrow> boundedBy (N+M) B"
  by(auto simp add: boundedBy_def)

lemma boundedByMono: "boundedBy m B \<Longrightarrow> m < M \<Longrightarrow> boundedBy M B"
  by(auto simp: boundedBy_def)

lemmas boundedByMonoD  = boundedByMono

lemma boundedBy0: "boundedBy 0 A = (A = {})"
  apply(simp add: boundedBy_def)
  apply(auto simp add: boundedBy_def)
  done

lemma boundedBySuc': "boundedBy N A \<Longrightarrow> boundedBy (Suc N) A"
  by (auto simp add: boundedBy_def)

lemma boundedByIncLevel: "boundedBy n (incLevel ` (tree subs gamma)) = ( \<exists>m . n = Suc m & boundedBy m (tree subs gamma))"
  apply(cases n)
   apply(force simp add: boundedBy0 tree0)
  apply(force simp add: treeEquation [of _ gamma] incLevel_def boundedBy_def)
  done

lemma boundedByUN: "boundedBy N (UN x:A. B x) = (!x:A. boundedBy N (B x))"
  by(simp add: boundedBy_def)

lemma boundedBySuc[rule_format]: "sigma \<in> subs Gamma \<Longrightarrow> boundedBy (Suc n) (tree subs Gamma) \<longrightarrow> boundedBy n (tree subs sigma)"
  apply(subst treeEquation [of _ Gamma])
  apply rule
  apply(simp add: boundedByInsert)
  apply(simp add: boundedByUN)
  apply(drule_tac x=sigma in bspec) apply assumption
  apply(simp add: boundedByIncLevel)
  done

subsection "Inherited Properties- bounded"

lemma boundedEmpty: "bounded {}"
  by(simp add: bounded_def)

lemma boundedUn: "bounded (A Un B) = (bounded A & bounded B)"
  apply(auto simp add: bounded_def boundedByUn)
  apply(rule_tac x="N+Na" in exI)
  apply(blast intro: boundedByAdd1 boundedByAdd2)
  done

lemma boundedIncLevel: "bounded (incLevel` A) = (bounded A)"
  apply (simp add: bounded_def, rule)
   apply(erule exE)
   apply(rule_tac x=N in exI)
   apply (simp add: boundedBy_def incLevel_def, force)
  apply(erule exE)
  apply(rule_tac x="Suc N" in exI)
  apply (simp add: boundedBy_def incLevel_def, force)
  done

lemma boundedInsert: "bounded (insert a B) = (bounded B)"
  apply(case_tac a)
  apply (simp add: bounded_def boundedByInsert, rule) apply blast
  apply(erule exE)
  apply(rule_tac x="Suc(aa+N)" in exI)
  apply(force intro:boundedByMono)
  done

lemma inheritedBounded: "inherited subs bounded"
  by(blast intro!: inheritedI boundedUn[symmetric] boundedIncLevel[symmetric]
    boundedInsert[symmetric] boundedEmpty)

subsection "founded"

definition
  founded :: "['a => 'a set,'a => bool,(nat * 'a) set] => bool" where
  "founded subs Pred = (%A. !(n,delta):A. terminal subs delta --> Pred delta)"

lemma foundedD: "founded subs P (tree subs delta) ==> terminal subs delta ==> P delta"
  by(simp add: treeEquation [of _ delta] founded_def)

lemma foundedMono: "[| founded subs P A; \<forall>x. P x --> Q x |] ==> founded subs Q A"
  by (auto simp: founded_def)

lemma foundedSubs: "founded subs P (tree subs Gamma) \<Longrightarrow> sigma \<in> subs Gamma \<Longrightarrow> founded subs P (tree subs sigma)"
  apply(simp add: founded_def)
  apply(intro ballI impI)
  apply (case_tac x, simp, rule)
  apply(drule_tac x="(Suc a, b)" in bspec)
   apply(subst treeEquation)
   apply (force simp: incLevel_def, simp)
  done

subsection "Inherited Properties- founded"

lemma foundedInsert[rule_format]: "~ terminal subs delta --> founded subs P (insert (n,delta) B) = (founded subs P B)"
  apply(simp add: terminal_def founded_def) done

lemma foundedUn: "(founded subs P (A Un B)) = (founded subs P A & founded subs P B)"
  apply(simp add: founded_def) by force

lemma foundedIncLevel: "founded subs P (incLevel ` A) = (founded subs P A)"
  apply (simp add: founded_def incLevel_def, auto) done

lemma foundedEmpty: "founded subs P {}"
  by(auto simp add: founded_def)

lemma inheritedFounded: "inherited subs (founded subs P)"
  by(blast intro!: inheritedI foundedUn[symmetric] foundedIncLevel[symmetric]
    foundedInsert[symmetric] foundedEmpty)

subsection "Inherited Properties- finite"

lemmas finiteInsert = finite_insert

lemma finiteUn: "finite (A Un B) = (finite A & finite B)"
  apply simp done

lemma finiteIncLevel: "finite (incLevel ` A) = finite A"
  apply (insert injIncLevel, rule)
   apply(frule finite_imageD)
    apply (blast intro: subset_inj_on, assumption)
  apply(rule finite_imageI)
  by assumption
  \<comment> \<open>FIXME often have injOn f A, finite f ` A, to show A finite\<close>

lemma finiteEmpty: "finite {}" by auto

lemma inheritedFinite: "inherited subs (%A. finite A)"
  apply(blast intro!: inheritedI finiteUn[symmetric] finiteIncLevel[symmetric] finiteInsert[symmetric] finiteEmpty)
  done

subsection "path: follows a failing inherited property through tree"

definition
  failingSub :: "['a => 'a set,(nat * 'a) set => bool,'a] => 'a" where
  "failingSub subs P gamma = (SOME sigma. (sigma:subs gamma & ~P(tree subs sigma)))"

lemma failingSubProps: "[| inherited subs P; ~P (tree subs gamma); ~(terminal subs gamma); fans subs |]
  ==> failingSub subs P gamma \<in> subs gamma & ~(P (tree subs (failingSub subs P gamma)))"
  apply(simp add: failingSub_def)
  apply(drule inheritedPropagate) apply(assumption+)
  apply(erule bexE)
  apply (rule someI2, auto)
  done

lemma failingSubFailsI: "[| inherited subs P; ~P (tree subs gamma); ~(terminal subs gamma); fans subs |]
  ==> ~(P (tree subs (failingSub subs P gamma)))"
  apply(rule conjunct2[OF failingSubProps]) .

lemmas failingSubFailsE = failingSubFailsI[THEN notE]

lemma failingSubSubs: "[| inherited subs P; ~P (tree subs gamma); ~(terminal subs gamma); fans subs |]
  ==> failingSub subs P gamma \<in> subs gamma"
  apply(rule conjunct1[OF failingSubProps]) .

primrec path :: "['a => 'a set,'a,(nat * 'a) set => bool,nat] => 'a"
where
  path0:   "path subs gamma P 0       = gamma"
| pathSuc: "path subs gamma P (Suc n) = (if terminal subs (path subs gamma P n)
                                          then path subs gamma P n
                                          else failingSub subs P (path subs gamma P n))"

lemma pathFailsP: "[| inherited subs P; fans subs; ~P(tree subs gamma) |]
  ==> ~(P (tree subs (path subs gamma P n)))"
  apply (induct_tac n, simp, simp)
  apply rule
  apply(rule failingSubFailsI) apply(assumption+)
  done

lemmas PpathE = pathFailsP[THEN notE]

lemma pathTerminal[rule_format]: "[| inherited subs P; fans subs; terminal subs gamma |]
  ==> terminal subs (path subs gamma P n)"
  apply (induct_tac n, simp_all) done

lemma pathStarts:  "path subs gamma P 0 = gamma"
  by simp

lemma pathSubs: "[| inherited subs P; fans subs; ~P(tree subs gamma); ~ (terminal subs (path subs gamma P n)) |]
  ==> path subs gamma P (Suc n) \<in> subs (path subs gamma P n)"
  apply simp
  apply (rule failingSubSubs, assumption)
    apply(rule pathFailsP)
      apply(assumption+)
  done

lemma pathStops: "terminal subs (path subs gamma P n) ==> path subs gamma P (Suc n) = path subs gamma P n"
  by simp

subsection "Branch"

definition
  branch :: "['a => 'a set,'a,nat => 'a] => bool" where
  "branch subs Gamma f \<longleftrightarrow> f 0 = Gamma
    & (!n . terminal subs (f n) --> f (Suc n) = f n)
    & (!n . ~ terminal subs (f n) --> f (Suc n) \<in> subs (f n))"

lemma branch0: "branch subs Gamma f ==> f 0 = Gamma"
  by (simp add: branch_def)

lemma branchStops: "branch subs Gamma f ==> terminal subs (f n) ==> f (Suc n) = f n"
  by (simp add: branch_def)

lemma branchSubs: "branch subs Gamma f ==> ~ terminal subs (f n) ==> f (Suc n) \<in> subs (f n)"
  by (simp add: branch_def)

lemma branchI: "[| (f 0 = Gamma);
  !n . terminal subs (f n) --> f (Suc n) = f n;
  !n . ~ terminal subs (f n) --> f (Suc n) \<in> subs (f n) |] ==> branch subs Gamma f"
  by (simp add: branch_def)

lemma branchTerminalPropagates: "branch subs Gamma f ==> terminal subs (f m) ==> terminal subs (f (m + n))"
  apply (induct_tac n, simp)
  by(simp add: branchStops)

lemma branchTerminalMono: "branch subs Gamma f ==> m < n ==> terminal subs (f m) ==> terminal subs (f n)"
  apply(subgoal_tac "terminal subs (f (m+(n-m)))") apply force
  apply(rule branchTerminalPropagates)
  .

lemma branchPath:
      "[| inherited subs P; fans subs; ~P(tree subs gamma) |]
       ==> branch subs gamma (path subs gamma P)"
  by(auto intro!: branchI pathStarts pathSubs pathStops)

subsection "failing branch property: abstracts path defn"

lemma failingBranchExistence:  "!!subs.
  [| inherited subs P; fans subs; ~P(tree subs gamma) |]
  ==> \<exists>f . branch subs gamma f & (\<forall>n . ~P(tree subs (f n)))"
  apply(rule_tac x="path subs gamma P" in exI)
  apply(rule conjI)
  apply(force intro!: branchPath)
  apply(intro allI)
  apply(rule pathFailsP)
  by auto

definition
  infBranch :: "['a => 'a set,'a,nat => 'a] => bool" where
  "infBranch subs Gamma f \<longleftrightarrow> f 0 = Gamma & (\<forall>n. f (Suc n) \<in> subs (f n))"

lemma infBranchI: "[| (f 0 = Gamma); !n . f (Suc n) \<in> subs (f n) |] ==> infBranch subs Gamma f"
  by (simp add: infBranch_def)

subsection "Tree induction principles"

  \<comment> \<open>we work hard to use nothing fancier that induction over naturals\<close>

lemma boundedTreeInduction':
 "\<lbrakk> fans subs;
    \<forall>delta. ~ terminal subs delta --> (\<forall>sigma \<in> subs delta. P sigma) --> P delta \<rbrakk>
  \<Longrightarrow> \<forall>Gamma. boundedBy m (tree subs Gamma) \<longrightarrow>  founded subs P (tree subs Gamma) \<longrightarrow> P Gamma"
  apply(induct_tac m)
   apply(intro impI allI)
   apply(simp add: boundedBy0)
   apply(subgoal_tac "(0,Gamma) \<in> tree subs Gamma") apply blast apply(rule tree0)
  apply(intro impI allI)
  apply(drule_tac x=Gamma in spec)
  apply (case_tac "terminal subs Gamma", simp)
   apply(drule_tac foundedD) apply assumption apply assumption
  apply (erule impE, assumption)
  apply (erule impE, rule)
   apply(drule_tac x=sigma in spec)
   apply(erule impE)
    apply(rule boundedBySuc) apply assumption apply assumption
   apply(erule impE)
    apply(rule foundedSubs) apply assumption apply assumption
   apply assumption
  apply assumption
  done
  \<comment> \<open>tjr tidied and introduced new lemmas\<close>

lemma boundedTreeInduction:
   "\<lbrakk>fans subs;
     bounded (tree subs Gamma); founded subs P (tree subs Gamma);
  \<forall>delta. ~ terminal subs delta --> (\<forall>sigma \<in> subs delta. P sigma) --> P delta
  \<rbrakk> \<Longrightarrow> P Gamma"
  apply(unfold bounded_def)
  apply(erule exE)
  apply(frule_tac boundedTreeInduction') apply assumption
  apply force
  done

lemma boundedTreeInduction2':
 "[| fans subs;
    \<forall>delta. (\<forall>sigma \<in> subs delta. P sigma) --> P delta |]
  ==> \<forall>Gamma. boundedBy m (tree subs Gamma) \<longrightarrow> P Gamma"
  apply(induct_tac m)
   apply(intro impI allI)
   apply(simp (no_asm_use) add: boundedBy0)
   apply(subgoal_tac "(0,Gamma) \<in> tree subs Gamma") apply blast apply(rule tree0)
  apply(intro impI allI)
  apply(drule_tac x=Gamma in spec)
  apply (erule impE, rule)
   apply(drule_tac x=sigma in spec)
   apply(erule impE)
    apply(rule boundedBySuc) apply assumption apply assumption
   apply assumption
  apply assumption
  done

lemma boundedTreeInduction2:
     "[| fans subs; boundedBy m (tree subs Gamma);
          \<forall>delta. (\<forall>sigma \<in> subs delta. P sigma) --> P delta |]
      ==> P Gamma"
  by (frule_tac boundedTreeInduction2', assumption, blast)

end


(*  Title:      FOL/ex/Nat_Class.thy
    Author:     Markus Wenzel, TU Muenchen
*)

theory Nat_Class
imports FOL
begin

text \<open>
  This is an abstract version of theory \<open>Nat\<close>. Instead of
  axiomatizing a single type \<open>nat\<close> we define the class of all
  these types (up to isomorphism).

  Note: The \<open>rec\<close> operator had to be made \emph{monomorphic},
  because class axioms may not contain more than one type variable.
\<close>

class nat =
  fixes Zero :: 'a  ("0")
    and Suc :: "'a \<Rightarrow> 'a"
    and rec :: "'a \<Rightarrow> 'a \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> 'a) \<Rightarrow> 'a"
  assumes induct: "P(0) \<Longrightarrow> (\<And>x. P(x) \<Longrightarrow> P(Suc(x))) \<Longrightarrow> P(n)"
    and Suc_inject: "Suc(m) = Suc(n) \<Longrightarrow> m = n"
    and Suc_neq_Zero: "Suc(m) = 0 \<Longrightarrow> R"
    and rec_Zero: "rec(0, a, f) = a"
    and rec_Suc: "rec(Suc(m), a, f) = f(m, rec(m, a, f))"
begin

definition add :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"  (infixl "+" 60)
  where "m + n = rec(m, n, \<lambda>x y. Suc(y))"

lemma Suc_n_not_n: "Suc(k) \<noteq> (k::'a)"
  apply (rule_tac n = k in induct)
   apply (rule notI)
   apply (erule Suc_neq_Zero)
  apply (rule notI)
  apply (erule notE)
  apply (erule Suc_inject)
  done

lemma "(k + m) + n = k + (m + n)"
  apply (rule induct)
  back
  back
  back
  back
  back
  oops

lemma add_Zero [simp]: "0 + n = n"
  apply (unfold add_def)
  apply (rule rec_Zero)
  done

lemma add_Suc [simp]: "Suc(m) + n = Suc(m + n)"
  apply (unfold add_def)
  apply (rule rec_Suc)
  done

lemma add_Zero_right: "m + 0 = m"
  apply (rule_tac n = m in induct)
   apply simp
  apply simp
  done

lemma add_Suc_right: "m + Suc(n) = Suc(m + n)"
  apply (rule_tac n = m in induct)
   apply simp_all
  done

lemma
  assumes prem: "\<And>n. f(Suc(n)) = Suc(f(n))"
  shows "f(i + j) = i + f(j)"
  apply (rule_tac n = i in induct)
   apply simp
  apply (simp add: prem)
  done

end

end


section \<open>The continued fraction expansion of \<open>e\<close>\<close>
theory E_CFrac
imports
  "HOL-Analysis.Analysis"
  "Continued_Fractions"
  "Quadratic_Irrationals"
begin

lemma fact_real_at_top: "filterlim (fact :: nat \<Rightarrow> real) at_top at_top"
proof (rule filterlim_at_top_mono)
  have "real n \<le> real (fact n)" for n
    unfolding of_nat_le_iff by (rule fact_ge_self)
  thus "eventually (\<lambda>n. real n \<le> fact n) at_top" by simp
qed (fact filterlim_real_sequentially)

lemma filterlim_div_nat_at_top:
  assumes "filterlim f at_top F" "m > 0"
  shows   "filterlim (\<lambda>x. f x div m :: nat) at_top F"
  unfolding filterlim_at_top
proof
  fix C :: nat
  from assms(1) have "eventually (\<lambda>x. f x \<ge> C * m) F"
    by (auto simp: filterlim_at_top)
  thus "eventually (\<lambda>x. f x div m \<ge> C) F"
  proof eventually_elim
    case (elim x)
    hence "(C * m) div m \<le> f x div m"
      by (intro div_le_mono)
    thus ?case using \<open>m > 0\<close> by simp
  qed
qed

text \<open>
  The continued fraction expansion of \<open>e\<close> has the form
  $[2; 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, \ldots]$:
\<close>
definition e_cfrac where
  "e_cfrac = cfrac (\<lambda>n. if n = 0 then 2 else if n mod 3 = 2 then 2 * (Suc n div 3) else 1)"

lemma cfrac_nth_e:
  "cfrac_nth e_cfrac n = (if n = 0 then 2 else if n mod 3 = 2 then 2 * (Suc n div 3) else 1)"
  unfolding e_cfrac_def by (subst cfrac_nth_cfrac) (auto simp: is_cfrac_def)

lemma cfrac_length_e [simp]: "cfrac_length e_cfrac = \<infinity>"
  by (simp add: e_cfrac_def)

text \<open>
  The formalised proof follows the one from Proof Wiki~\cite{proofwiki}.
\<close>

context
  fixes A B C :: "nat \<Rightarrow> real" and p q :: "nat \<Rightarrow> int" and a :: "nat \<Rightarrow> int"
  defines "A \<equiv> (\<lambda>n. integral {0..1} (\<lambda>x. exp x * x ^ n * (x - 1) ^ n / fact n))"
      and "B \<equiv> (\<lambda>n. integral {0..1} (\<lambda>x. exp x * x ^ Suc n * (x - 1) ^ n / fact n))"
      and "C \<equiv> (\<lambda>n. integral {0..1} (\<lambda>x. exp x * x ^ n * (x - 1) ^ Suc n / fact n))"
      and "p \<equiv> (\<lambda>n. if n \<le> 1 then 1 else conv_num e_cfrac (n - 2))"
      and "q \<equiv> (\<lambda>n. if n = 0 then 1 else if n = 1 then 0 else conv_denom e_cfrac (n - 2))"
      and "a \<equiv> (\<lambda>n. if n mod 3 = 2 then 2 * (Suc n div 3) else 1)"
begin

lemma
  assumes "n \<ge> 2"
  shows   p_rec: "p n = a (n - 2) * p (n - 1) + p (n - 2)" (is ?th1)
    and   q_rec: "q n = a (n - 2) * q (n - 1) + q (n - 2)" (is ?th2)
proof -
  have n_minus_3: "n - 3 = n - Suc (Suc (Suc 0))"
    by (simp add: numeral_3_eq_3)
  consider "n = 2" | "n = 3" | "n \<ge> 4"
    using assms by force
  hence "?th1 \<and> ?th2"
    by cases (auto simp: p_def q_def cfrac_nth_e a_def conv_num_rec conv_denom_rec n_minus_3)
  thus ?th1 ?th2 by blast+
qed

lemma
  assumes "n \<ge> 1"
  shows   p_rec0: "p (3 * n) = p (3 * n - 1) + p (3 * n - 2)"
    and   q_rec0: "q (3 * n) = q (3 * n - 1) + q (3 * n - 2)"
proof -
  define n' where "n' = n - 1"
  from assms have "(3 * n' + 1) mod 3 \<noteq> 2"
    by presburger
  also have "(3 * n' + 1) = 3 * n - 2"
    using assms by (simp add: n'_def)
  finally show "p (3 * n) = p (3 * n - 1) + p (3 * n - 2)"
               "q (3 * n) = q (3 * n - 1) + q (3 * n - 2)"
    using assms by (subst p_rec q_rec; simp add: a_def)+
qed

lemma
  assumes "n \<ge> 1"
  shows   p_rec1: "p (3 * n + 1) = 2 * int n * p (3 * n) + p (3 * n - 1)"
    and   q_rec1: "q (3 * n + 1) = 2 * int n * q (3 * n) + q (3 * n - 1)"
proof -
  define n' where "n' = n - 1"
  from assms have "(3 * n' + 2) mod 3 = 2"
    by presburger
  also have "(3 * n' + 2) = 3 * n - 1"
    using assms by (simp add: n'_def)
  finally show "p (3 * n + 1) = 2 * int n * p (3 * n) + p (3 * n - 1)"
               "q (3 * n + 1) = 2 * int n * q (3 * n) + q (3 * n - 1)"
    using assms by (subst p_rec q_rec; simp add: a_def)+
qed

lemma p_rec2: "p (3 * n + 2) = p (3 * n + 1) + p (3 * n)"
  and q_rec2: "q (3 * n + 2) = q (3 * n + 1) + q (3 * n)"
  by (subst p_rec q_rec; simp add: a_def nat_mult_distrib nat_add_distrib)+

lemma A_0: "A 0 = exp 1 - 1" and B_0: "B 0 = 1" and C_0: "C 0 = 2 - exp 1"
proof -
  have "(exp has_integral (exp 1 - exp 0)) {0..1::real}"
    by (intro fundamental_theorem_of_calculus)
       (auto intro!: derivative_eq_intros
             simp: has_field_derivative_iff_has_vector_derivative [symmetric])
  thus "A 0 = exp 1 - 1" by (simp add: A_def has_integral_iff)

  have "((\<lambda>x. exp x * x) has_integral (exp 1 * (1 - 1) - exp 0 * (0 - 1))) {0..1::real}"
    by (intro fundamental_theorem_of_calculus)
       (auto intro!: derivative_eq_intros
             simp: has_field_derivative_iff_has_vector_derivative [symmetric] algebra_simps)
  thus "B 0 = 1" by (simp add: B_def has_integral_iff)

  have "((\<lambda>x. exp x * (x - 1)) has_integral (exp 1 * (1 - 2) - exp 0 * (0 - 2))) {0..1::real}"
    by (intro fundamental_theorem_of_calculus)
       (auto intro!: derivative_eq_intros
             simp: has_field_derivative_iff_has_vector_derivative [symmetric] algebra_simps)
  thus "C 0 = 2 - exp 1" by (simp add: C_def has_integral_iff)
qed

lemma A_bound: "norm (A n) \<le> exp 1 / fact n"
proof -
  have "norm (exp t * t ^ n * (t - 1) ^ n / fact n) \<le> exp 1 * 1 ^ n * 1 ^ n / fact n"
    if "t \<in> {0..1}" for t :: real using that unfolding norm_mult norm_divide norm_power norm_fact
    by (intro mult_mono divide_right_mono power_mono) auto
  hence "norm (A n) \<le> exp 1 / fact n * (1 - 0)"
    unfolding A_def by (intro integral_bound) (auto intro!: continuous_intros)
  thus ?thesis by simp
qed

lemma B_bound: "norm (B n) \<le> exp 1 / fact n"
proof -
  have "norm (exp t * t ^ Suc n * (t - 1) ^ n / fact n) \<le> exp 1 * 1 ^ Suc n * 1 ^ n / fact n"
    if "t \<in> {0..1}" for t :: real using that unfolding norm_mult norm_divide norm_power norm_fact
    by (intro mult_mono divide_right_mono power_mono) auto
  hence "norm (B n) \<le> exp 1 / fact n * (1 - 0)"
    unfolding B_def by (intro integral_bound) (auto intro!: continuous_intros)
  thus ?thesis by simp
qed

lemma C_bound: "norm (C n) \<le> exp 1 / fact n"
proof -
  have "norm (exp t * t ^ n * (t - 1) ^ Suc n / fact n) \<le> exp 1 * 1 ^ n * 1 ^ Suc n / fact n"
    if "t \<in> {0..1}" for t :: real using that unfolding norm_mult norm_divide norm_power norm_fact
    by (intro mult_mono divide_right_mono power_mono) auto
  hence "norm (C n) \<le> exp 1 / fact n * (1 - 0)"
    unfolding C_def by (intro integral_bound) (auto intro!: continuous_intros)
  thus ?thesis by simp
qed

lemma A_Suc: "A (Suc n) = -B n - C n"
proof -
  let ?g = "\<lambda>x. x ^ Suc n * (x - 1) ^ Suc n * exp x / fact (Suc n)"
  have pos: "fact n + real n * fact n > 0" by (intro add_pos_nonneg) auto
  have "A (Suc n) + B n + C n =
          integral {0..1} (\<lambda>x. exp x * x ^ Suc n * (x - 1) ^ Suc n / fact (Suc n) +
             exp x * x ^ Suc n * (x - 1) ^ n / fact n + exp x * x ^ n * (x - 1) ^ Suc n / fact n)"
    unfolding A_def B_def C_def
    apply (subst integral_add [symmetric])
      apply (auto intro!: integrable_continuous_real continuous_intros)[2]
    apply (subst integral_add [symmetric])
      apply (auto intro!: integrable_continuous_real continuous_intros)
    done
  also have "\<dots> = integral {0..1} (\<lambda>x. exp x / fact (Suc n) *
                    (x ^ Suc n * (x - 1) ^ Suc n + Suc n * x ^ Suc n * (x - 1) ^ n +
                     Suc n * x ^ n * (x - 1) ^ Suc n))"
    (is "_ = integral _ ?f")
    apply (simp add: divide_simps)
    apply (simp add: field_simps)?
    done
  also have "(?f has_integral (?g 1 - ?g 0)) {0..1}"
    apply (intro fundamental_theorem_of_calculus)
     apply (simp; fail)
    unfolding has_field_derivative_iff_has_vector_derivative [symmetric]
    apply (rule derivative_eq_intros refl | simp)+
    apply (simp add: algebra_simps)?
    done
  hence "integral {0..1} ?f = 0"
    by (simp add: has_integral_iff)
  finally show ?thesis by simp
qed

lemma B_Suc: "B (Suc n) = -2 * Suc n * A (Suc n) + C n"
proof -
  let ?g = "\<lambda>x. x ^ Suc n * (x - 1) ^ (n+2) * exp x / fact (Suc n)"
  have pos: "fact n + real n * fact n > 0" by (intro add_pos_nonneg) auto
  have "B (Suc n) + 2 * Suc n * A (Suc n) - C n =
          integral {0..1} (\<lambda>x. exp x * x^(n+2) * (x - 1)^(n+1) / fact (Suc n) + 2 * Suc n *
             exp x * x ^ Suc n * (x - 1) ^ Suc n / fact (Suc n) - exp x * x ^ n * (x - 1) ^ Suc n / fact n)"
    unfolding A_def B_def C_def integral_mult_right [symmetric]
    apply (subst integral_add [symmetric])
      apply (auto intro!: integrable_continuous_real continuous_intros)[2]
    apply (subst integral_diff [symmetric])
      apply (auto intro!: integrable_continuous_real continuous_intros simp: mult_ac)
    done
  also have "\<dots> = integral {0..1} (\<lambda>x. exp x / fact (Suc n) *
                    (x^(n+2) * (x - 1)^(n+1) + 2 * Suc n * x ^ Suc n * (x - 1) ^ Suc n -
                     Suc n * x ^ n * (x - 1) ^ Suc n))"
    (is "_ = integral _ ?f")
    apply (simp add: divide_simps)
    apply (simp add: field_simps)?
    done
  also have "(?f has_integral (?g 1 - ?g 0)) {0..1}"
    apply (intro fundamental_theorem_of_calculus)
     apply (simp; fail)
    unfolding has_field_derivative_iff_has_vector_derivative [symmetric]
    apply (rule derivative_eq_intros refl | simp)+
    apply (simp add: algebra_simps)?
    done
  hence "integral {0..1} ?f = 0"
    by (simp add: has_integral_iff)
  finally show ?thesis by (simp add: algebra_simps)
qed

lemma C_Suc: "C n = B n - A n"
  unfolding A_def B_def C_def
  by (subst integral_diff [symmetric])
     (auto intro!: integrable_continuous_real continuous_intros simp: field_simps)

lemma unfold_add_numeral: "c * n + numeral b = Suc (c * n + pred_numeral b)"
  by simp

lemma ABC:
  "A n = q (3 * n) * exp 1 - p (3 * n) \<and>
   B n = p (Suc (3 * n)) - q (Suc (3 * n)) * exp 1 \<and>
   C n = p (Suc (Suc (3 * n))) - q (Suc (Suc (3 * n))) * exp 1"
proof (induction n)
  case 0
  thus ?case by (simp add: A_0 B_0 C_0 a_def p_def q_def cfrac_nth_e)
next
  case (Suc n)
  note [simp] =
    conjunct1[OF Suc.IH] conjunct1[OF conjunct2[OF Suc.IH]] conjunct2[OF conjunct2[OF Suc.IH]]
  have [simp]: "3 + m = Suc (Suc (Suc m))" for m by simp

  have A': "A (Suc n) = of_int (q (3 * Suc n)) * exp 1 - of_int (p (3 * Suc n))"
    unfolding A_Suc
    by (subst p_rec0 q_rec0, simp)+ (auto simp: algebra_simps)
  have B': "B (Suc n) = of_int (p (3 * Suc n + 1)) - of_int (q (3 * Suc n + 1)) * exp 1"
    unfolding B_Suc
    by (subst p_rec1 q_rec1 p_rec0 q_rec0, simp)+ (auto simp: algebra_simps A_Suc)
  have C': "C (Suc n) = of_int (p (3*Suc n+2)) - of_int (q (3*Suc n+2)) * exp 1"
    unfolding A_Suc B_Suc C_Suc using p_rec2[of n] q_rec2[of n]
    by ((subst p_rec2 q_rec2)+, (subst p_rec0 q_rec0 p_rec1 q_rec1, simp)+)
       (auto simp: algebra_simps A_Suc B_Suc)
  from A' B' C' show ?case by simp
qed

lemma q_pos: "q n > 0" if "n \<noteq> 1"
  using that by (auto simp: q_def)

lemma conv_diff_exp_bound:
  assumes "n \<noteq> 1"
  shows   "norm (exp 1 - p n / q n) \<le> exp 1 / fact (n div 3)"
proof -
  define n' where "n' = n div 3"
  consider "n mod 3 = 0" | "n mod 3 = 1" | "n mod 3 = 2"
    by force
  hence diff [unfolded n'_def]: "q n * exp 1 - p n =
    (if n mod 3 = 0 then A n' else if n mod 3 = 1 then -B n' else -C n')"
  proof cases
    assume "n mod 3 = 0"
    hence "3 * n' = n" unfolding n'_def by presburger
    with ABC[of n'] show ?thesis by auto
  next
    assume *: "n mod 3 = 1"
    hence "Suc (3 * n') = n" unfolding n'_def by presburger
    with * ABC[of n'] show ?thesis by auto
  next
    assume *: "n mod 3 = 2"
    hence "Suc (Suc (3 * n')) = n" unfolding n'_def by presburger
    with * ABC[of n'] show ?thesis by auto
  qed

  note [[linarith_split_limit = 0]]
  have "norm ((q n * exp 1 - p n) / q n) \<le> exp 1 / fact (n div 3) / 1" unfolding diff norm_divide
    using A_bound[of "n div 3"] B_bound[of "n div 3"] C_bound[of "n div 3"] q_pos[OF assms]
    by (subst frac_le) (auto simp: of_nat_ge_1_iff)
  also have "(q n * exp 1 - p n) / q n = exp 1 - p n / q n"
    using q_pos[OF assms] by (simp add: divide_simps)
  finally show ?thesis by simp
qed

theorem e_cfrac: "cfrac_lim e_cfrac = exp 1"
proof -
  have num: "conv_num e_cfrac n = p (n + 2)"
   and denom: "conv_denom e_cfrac n = q (n + 2)" for n
    by (simp_all add: p_def q_def)

  have "(\<lambda>n. exp 1 - p n / q n) \<longlonglongrightarrow> 0"
  proof (rule Lim_null_comparison)
    show "eventually (\<lambda>n. norm (exp 1 - p n / q n) \<le> exp 1 / fact (n div 3)) at_top"
      using eventually_gt_at_top[of "1::nat"] by eventually_elim (rule conv_diff_exp_bound, auto)
    show "(\<lambda>n. exp 1 / fact (n div 3) :: real) \<longlonglongrightarrow> 0"
      by (rule real_tendsto_divide_at_top tendsto_const filterlim_div_nat_at_top
               filterlim_ident filterlim_compose[OF fact_real_at_top])+ auto
  qed
  moreover have "eventually (\<lambda>n. exp 1 - p n / q n = exp 1 - conv e_cfrac (n - 2)) at_top"
    using eventually_ge_at_top[of 2]
  proof eventually_elim
    case (elim n)
    with num[of "n - 2"] denom[of "n - 2"] wf show ?case
      by (simp add: eval_nat_numeral Suc_diff_Suc conv_num_denom)
  qed
  ultimately have "(\<lambda>n. exp 1 - conv e_cfrac (n - 2)) \<longlonglongrightarrow> 0"
    using Lim_transform_eventually by fast
  hence "(\<lambda>n. exp 1 - (exp 1 - conv e_cfrac (Suc (Suc n) - 2))) \<longlonglongrightarrow> exp 1 - 0"
    by (subst filterlim_sequentially_Suc)+ (intro tendsto_diff tendsto_const)
  hence "conv e_cfrac \<longlonglongrightarrow> exp 1" by simp
  moreover have "conv e_cfrac \<longlonglongrightarrow> cfrac_lim e_cfrac"
    by (intro LIMSEQ_cfrac_lim wf) auto
  ultimately have "exp 1 = cfrac_lim e_cfrac"
    by (rule LIMSEQ_unique)
  thus ?thesis ..
qed

corollary e_cfrac_altdef: "e_cfrac = cfrac_of_real (exp 1)"
  by (metis e_cfrac cfrac_infinite_iff cfrac_length_e cfrac_of_real_cfrac_lim_irrational)

corollary exp1_irrational: "(exp 1 :: real) \<notin> \<rat>"
  by (metis cfrac_length_e e_cfrac cfrac_infinite_iff)

corollary exp1_not_quadratic_irrational: "\<not>quadratic_irrational (exp 1 :: real)"
proof -
  have "range (\<lambda>n. 2 * (int n + 1)) \<subseteq> range (cfrac_nth e_cfrac)"
  proof safe
    fix n :: nat
    have "cfrac_nth e_cfrac (3*n+2) \<in> range (cfrac_nth e_cfrac)"
      by blast
    also have "(3 * n + 2) mod 3 = 2"
      by presburger
    hence "cfrac_nth e_cfrac (3*n+2) = 2 * (int n + 1)"
      by (simp add: cfrac_nth_e)
    finally show "2 * (int n + 1) \<in> range (cfrac_nth e_cfrac)" .
  qed
  moreover have "infinite (range (\<lambda>n. 2 * (int n + 1)))"
    by (subst finite_image_iff) (auto intro!: injI)
  ultimately have "infinite (range (cfrac_nth e_cfrac))"
    using finite_subset by blast
  thus ?thesis using quadratic_irrational_cfrac_nth_range_finite[of e_cfrac]
    by (auto simp: e_cfrac)
qed

end
end


(*  Title:      HOL/HOLCF/Universal.thy
    Author:     Brian Huffman
*)

section \<open>A universal bifinite domain\<close>

theory Universal
imports Bifinite Completion "~~/src/HOL/Library/Nat_Bijection"
begin

subsection \<open>Basis for universal domain\<close>

subsubsection \<open>Basis datatype\<close>

type_synonym ubasis = nat

definition
  node :: "nat \<Rightarrow> ubasis \<Rightarrow> ubasis set \<Rightarrow> ubasis"
where
  "node i a S = Suc (prod_encode (i, prod_encode (a, set_encode S)))"

lemma node_not_0 [simp]: "node i a S \<noteq> 0"
unfolding node_def by simp

lemma node_gt_0 [simp]: "0 < node i a S"
unfolding node_def by simp

lemma node_inject [simp]:
  "\<lbrakk>finite S; finite T\<rbrakk>
    \<Longrightarrow> node i a S = node j b T \<longleftrightarrow> i = j \<and> a = b \<and> S = T"
unfolding node_def by (simp add: prod_encode_eq set_encode_eq)

lemma node_gt0: "i < node i a S"
unfolding node_def less_Suc_eq_le
by (rule le_prod_encode_1)

lemma node_gt1: "a < node i a S"
unfolding node_def less_Suc_eq_le
by (rule order_trans [OF le_prod_encode_1 le_prod_encode_2])

lemma nat_less_power2: "n < 2^n"
by (induct n) simp_all

lemma node_gt2: "\<lbrakk>finite S; b \<in> S\<rbrakk> \<Longrightarrow> b < node i a S"
unfolding node_def less_Suc_eq_le set_encode_def
apply (rule order_trans [OF _ le_prod_encode_2])
apply (rule order_trans [OF _ le_prod_encode_2])
apply (rule order_trans [where y="sum (op ^ 2) {b}"])
apply (simp add: nat_less_power2 [THEN order_less_imp_le])
apply (erule sum_mono2, simp, simp)
done

lemma eq_prod_encode_pairI:
  "\<lbrakk>fst (prod_decode x) = a; snd (prod_decode x) = b\<rbrakk> \<Longrightarrow> x = prod_encode (a, b)"
by (erule subst, erule subst, simp)

lemma node_cases:
  assumes 1: "x = 0 \<Longrightarrow> P"
  assumes 2: "\<And>i a S. \<lbrakk>finite S; x = node i a S\<rbrakk> \<Longrightarrow> P"
  shows "P"
 apply (cases x)
  apply (erule 1)
 apply (rule 2)
  apply (rule finite_set_decode)
 apply (simp add: node_def)
 apply (rule eq_prod_encode_pairI [OF refl])
 apply (rule eq_prod_encode_pairI [OF refl refl])
done

lemma node_induct:
  assumes 1: "P 0"
  assumes 2: "\<And>i a S. \<lbrakk>P a; finite S; \<forall>b\<in>S. P b\<rbrakk> \<Longrightarrow> P (node i a S)"
  shows "P x"
 apply (induct x rule: nat_less_induct)
 apply (case_tac n rule: node_cases)
  apply (simp add: 1)
 apply (simp add: 2 node_gt1 node_gt2)
done

subsubsection \<open>Basis ordering\<close>

inductive
  ubasis_le :: "nat \<Rightarrow> nat \<Rightarrow> bool"
where
  ubasis_le_refl: "ubasis_le a a"
| ubasis_le_trans:
    "\<lbrakk>ubasis_le a b; ubasis_le b c\<rbrakk> \<Longrightarrow> ubasis_le a c"
| ubasis_le_lower:
    "finite S \<Longrightarrow> ubasis_le a (node i a S)"
| ubasis_le_upper:
    "\<lbrakk>finite S; b \<in> S; ubasis_le a b\<rbrakk> \<Longrightarrow> ubasis_le (node i a S) b"

lemma ubasis_le_minimal: "ubasis_le 0 x"
apply (induct x rule: node_induct)
apply (rule ubasis_le_refl)
apply (erule ubasis_le_trans)
apply (erule ubasis_le_lower)
done

interpretation udom: preorder ubasis_le
apply standard
apply (rule ubasis_le_refl)
apply (erule (1) ubasis_le_trans)
done

subsubsection \<open>Generic take function\<close>

function
  ubasis_until :: "(ubasis \<Rightarrow> bool) \<Rightarrow> ubasis \<Rightarrow> ubasis"
where
  "ubasis_until P 0 = 0"
| "finite S \<Longrightarrow> ubasis_until P (node i a S) =
    (if P (node i a S) then node i a S else ubasis_until P a)"
   apply clarify
   apply (rule_tac x=b in node_cases)
    apply simp
   apply simp
   apply fast
  apply simp
 apply simp
done

termination ubasis_until
apply (relation "measure snd")
apply (rule wf_measure)
apply (simp add: node_gt1)
done

lemma ubasis_until: "P 0 \<Longrightarrow> P (ubasis_until P x)"
by (induct x rule: node_induct) simp_all

lemma ubasis_until': "0 < ubasis_until P x \<Longrightarrow> P (ubasis_until P x)"
by (induct x rule: node_induct) auto

lemma ubasis_until_same: "P x \<Longrightarrow> ubasis_until P x = x"
by (induct x rule: node_induct) simp_all

lemma ubasis_until_idem:
  "P 0 \<Longrightarrow> ubasis_until P (ubasis_until P x) = ubasis_until P x"
by (rule ubasis_until_same [OF ubasis_until])

lemma ubasis_until_0:
  "\<forall>x. x \<noteq> 0 \<longrightarrow> \<not> P x \<Longrightarrow> ubasis_until P x = 0"
by (induct x rule: node_induct) simp_all

lemma ubasis_until_less: "ubasis_le (ubasis_until P x) x"
apply (induct x rule: node_induct)
apply (simp add: ubasis_le_refl)
apply (simp add: ubasis_le_refl)
apply (rule impI)
apply (erule ubasis_le_trans)
apply (erule ubasis_le_lower)
done

lemma ubasis_until_chain:
  assumes PQ: "\<And>x. P x \<Longrightarrow> Q x"
  shows "ubasis_le (ubasis_until P x) (ubasis_until Q x)"
apply (induct x rule: node_induct)
apply (simp add: ubasis_le_refl)
apply (simp add: ubasis_le_refl)
apply (simp add: PQ)
apply clarify
apply (rule ubasis_le_trans)
apply (rule ubasis_until_less)
apply (erule ubasis_le_lower)
done

lemma ubasis_until_mono:
  assumes "\<And>i a S b. \<lbrakk>finite S; P (node i a S); b \<in> S; ubasis_le a b\<rbrakk> \<Longrightarrow> P b"
  shows "ubasis_le a b \<Longrightarrow> ubasis_le (ubasis_until P a) (ubasis_until P b)"
proof (induct set: ubasis_le)
  case (ubasis_le_refl a) show ?case by (rule ubasis_le.ubasis_le_refl)
next
  case (ubasis_le_trans a b c) thus ?case by - (rule ubasis_le.ubasis_le_trans)
next
  case (ubasis_le_lower S a i) thus ?case
    apply (clarsimp simp add: ubasis_le_refl)
    apply (rule ubasis_le_trans [OF ubasis_until_less])
    apply (erule ubasis_le.ubasis_le_lower)
    done
next
  case (ubasis_le_upper S b a i) thus ?case
    apply clarsimp
    apply (subst ubasis_until_same)
     apply (erule (3) assms)
    apply (erule (2) ubasis_le.ubasis_le_upper)
    done
qed

lemma finite_range_ubasis_until:
  "finite {x. P x} \<Longrightarrow> finite (range (ubasis_until P))"
apply (rule finite_subset [where B="insert 0 {x. P x}"])
apply (clarsimp simp add: ubasis_until')
apply simp
done

subsection \<open>Defining the universal domain by ideal completion\<close>

typedef udom = "{S. udom.ideal S}"
by (rule udom.ex_ideal)

instantiation udom :: below
begin

definition
  "x \<sqsubseteq> y \<longleftrightarrow> Rep_udom x \<subseteq> Rep_udom y"

instance ..
end

instance udom :: po
using type_definition_udom below_udom_def
by (rule udom.typedef_ideal_po)

instance udom :: cpo
using type_definition_udom below_udom_def
by (rule udom.typedef_ideal_cpo)

definition
  udom_principal :: "nat \<Rightarrow> udom" where
  "udom_principal t = Abs_udom {u. ubasis_le u t}"

lemma ubasis_countable: "\<exists>f::ubasis \<Rightarrow> nat. inj f"
by (rule exI, rule inj_on_id)

interpretation udom:
  ideal_completion ubasis_le udom_principal Rep_udom
using type_definition_udom below_udom_def
using udom_principal_def ubasis_countable
by (rule udom.typedef_ideal_completion)

text \<open>Universal domain is pointed\<close>

lemma udom_minimal: "udom_principal 0 \<sqsubseteq> x"
apply (induct x rule: udom.principal_induct)
apply (simp, simp add: ubasis_le_minimal)
done

instance udom :: pcpo
by intro_classes (fast intro: udom_minimal)

lemma inst_udom_pcpo: "\<bottom> = udom_principal 0"
by (rule udom_minimal [THEN bottomI, symmetric])

subsection \<open>Compact bases of domains\<close>

typedef 'a compact_basis = "{x::'a::pcpo. compact x}"
by auto

lemma Rep_compact_basis' [simp]: "compact (Rep_compact_basis a)"
by (rule Rep_compact_basis [unfolded mem_Collect_eq])

lemma Abs_compact_basis_inverse' [simp]:
   "compact x \<Longrightarrow> Rep_compact_basis (Abs_compact_basis x) = x"
by (rule Abs_compact_basis_inverse [unfolded mem_Collect_eq])

instantiation compact_basis :: (pcpo) below
begin

definition
  compact_le_def:
    "(op \<sqsubseteq>) \<equiv> (\<lambda>x y. Rep_compact_basis x \<sqsubseteq> Rep_compact_basis y)"

instance ..
end

instance compact_basis :: (pcpo) po
using type_definition_compact_basis compact_le_def
by (rule typedef_po)

definition
  approximants :: "'a \<Rightarrow> 'a compact_basis set" where
  "approximants = (\<lambda>x. {a. Rep_compact_basis a \<sqsubseteq> x})"

definition
  compact_bot :: "'a::pcpo compact_basis" where
  "compact_bot = Abs_compact_basis \<bottom>"

lemma Rep_compact_bot [simp]: "Rep_compact_basis compact_bot = \<bottom>"
unfolding compact_bot_def by simp

lemma compact_bot_minimal [simp]: "compact_bot \<sqsubseteq> a"
unfolding compact_le_def Rep_compact_bot by simp

subsection \<open>Universality of \emph{udom}\<close>

text \<open>We use a locale to parameterize the construction over a chain
of approx functions on the type to be embedded.\<close>

locale bifinite_approx_chain =
  approx_chain approx for approx :: "nat \<Rightarrow> 'a::bifinite \<rightarrow> 'a"
begin

subsubsection \<open>Choosing a maximal element from a finite set\<close>

lemma finite_has_maximal:
  fixes A :: "'a compact_basis set"
  shows "\<lbrakk>finite A; A \<noteq> {}\<rbrakk> \<Longrightarrow> \<exists>x\<in>A. \<forall>y\<in>A. x \<sqsubseteq> y \<longrightarrow> x = y"
proof (induct rule: finite_ne_induct)
  case (singleton x)
    show ?case by simp
next
  case (insert a A)
  from \<open>\<exists>x\<in>A. \<forall>y\<in>A. x \<sqsubseteq> y \<longrightarrow> x = y\<close>
  obtain x where x: "x \<in> A"
           and x_eq: "\<And>y. \<lbrakk>y \<in> A; x \<sqsubseteq> y\<rbrakk> \<Longrightarrow> x = y" by fast
  show ?case
  proof (intro bexI ballI impI)
    fix y
    assume "y \<in> insert a A" and "(if x \<sqsubseteq> a then a else x) \<sqsubseteq> y"
    thus "(if x \<sqsubseteq> a then a else x) = y"
      apply auto
      apply (frule (1) below_trans)
      apply (frule (1) x_eq)
      apply (rule below_antisym, assumption)
      apply simp
      apply (erule (1) x_eq)
      done
  next
    show "(if x \<sqsubseteq> a then a else x) \<in> insert a A"
      by (simp add: x)
  qed
qed

definition
  choose :: "'a compact_basis set \<Rightarrow> 'a compact_basis"
where
  "choose A = (SOME x. x \<in> {x\<in>A. \<forall>y\<in>A. x \<sqsubseteq> y \<longrightarrow> x = y})"

lemma choose_lemma:
  "\<lbrakk>finite A; A \<noteq> {}\<rbrakk> \<Longrightarrow> choose A \<in> {x\<in>A. \<forall>y\<in>A. x \<sqsubseteq> y \<longrightarrow> x = y}"
unfolding choose_def
apply (rule someI_ex)
apply (frule (1) finite_has_maximal, fast)
done

lemma maximal_choose:
  "\<lbrakk>finite A; y \<in> A; choose A \<sqsubseteq> y\<rbrakk> \<Longrightarrow> choose A = y"
apply (cases "A = {}", simp)
apply (frule (1) choose_lemma, simp)
done

lemma choose_in: "\<lbrakk>finite A; A \<noteq> {}\<rbrakk> \<Longrightarrow> choose A \<in> A"
by (frule (1) choose_lemma, simp)

function
  choose_pos :: "'a compact_basis set \<Rightarrow> 'a compact_basis \<Rightarrow> nat"
where
  "choose_pos A x =
    (if finite A \<and> x \<in> A \<and> x \<noteq> choose A
      then Suc (choose_pos (A - {choose A}) x) else 0)"
by auto

termination choose_pos
apply (relation "measure (card \<circ> fst)", simp)
apply clarsimp
apply (rule card_Diff1_less)
apply assumption
apply (erule choose_in)
apply clarsimp
done

declare choose_pos.simps [simp del]

lemma choose_pos_choose: "finite A \<Longrightarrow> choose_pos A (choose A) = 0"
by (simp add: choose_pos.simps)

lemma inj_on_choose_pos [OF refl]:
  "\<lbrakk>card A = n; finite A\<rbrakk> \<Longrightarrow> inj_on (choose_pos A) A"
 apply (induct n arbitrary: A)
  apply simp
 apply (case_tac "A = {}", simp)
 apply (frule (1) choose_in)
 apply (rule inj_onI)
 apply (drule_tac x="A - {choose A}" in meta_spec, simp)
 apply (simp add: choose_pos.simps)
 apply (simp split: if_split_asm)
 apply (erule (1) inj_onD, simp, simp)
done

lemma choose_pos_bounded [OF refl]:
  "\<lbrakk>card A = n; finite A; x \<in> A\<rbrakk> \<Longrightarrow> choose_pos A x < n"
apply (induct n arbitrary: A)
apply simp
 apply (case_tac "A = {}", simp)
 apply (frule (1) choose_in)
apply (subst choose_pos.simps)
apply simp
done

lemma choose_pos_lessD:
  "\<lbrakk>choose_pos A x < choose_pos A y; finite A; x \<in> A; y \<in> A\<rbrakk> \<Longrightarrow> x \<notsqsubseteq> y"
 apply (induct A x arbitrary: y rule: choose_pos.induct)
 apply simp
 apply (case_tac "x = choose A")
  apply simp
  apply (rule notI)
  apply (frule (2) maximal_choose)
  apply simp
 apply (case_tac "y = choose A")
  apply (simp add: choose_pos_choose)
 apply (drule_tac x=y in meta_spec)
 apply simp
 apply (erule meta_mp)
 apply (simp add: choose_pos.simps)
done

subsubsection \<open>Compact basis take function\<close>

primrec
  cb_take :: "nat \<Rightarrow> 'a compact_basis \<Rightarrow> 'a compact_basis" where
  "cb_take 0 = (\<lambda>x. compact_bot)"
| "cb_take (Suc n) = (\<lambda>a. Abs_compact_basis (approx n\<cdot>(Rep_compact_basis a)))"

declare cb_take.simps [simp del]

lemma cb_take_zero [simp]: "cb_take 0 a = compact_bot"
by (simp only: cb_take.simps)

lemma Rep_cb_take:
  "Rep_compact_basis (cb_take (Suc n) a) = approx n\<cdot>(Rep_compact_basis a)"
by (simp add: cb_take.simps(2))

lemmas approx_Rep_compact_basis = Rep_cb_take [symmetric]

lemma cb_take_covers: "\<exists>n. cb_take n x = x"
apply (subgoal_tac "\<exists>n. cb_take (Suc n) x = x", fast)
apply (simp add: Rep_compact_basis_inject [symmetric])
apply (simp add: Rep_cb_take)
apply (rule compact_eq_approx)
apply (rule Rep_compact_basis')
done

lemma cb_take_less: "cb_take n x \<sqsubseteq> x"
unfolding compact_le_def
by (cases n, simp, simp add: Rep_cb_take approx_below)

lemma cb_take_idem: "cb_take n (cb_take n x) = cb_take n x"
unfolding Rep_compact_basis_inject [symmetric]
by (cases n, simp, simp add: Rep_cb_take approx_idem)

lemma cb_take_mono: "x \<sqsubseteq> y \<Longrightarrow> cb_take n x \<sqsubseteq> cb_take n y"
unfolding compact_le_def
by (cases n, simp, simp add: Rep_cb_take monofun_cfun_arg)

lemma cb_take_chain_le: "m \<le> n \<Longrightarrow> cb_take m x \<sqsubseteq> cb_take n x"
unfolding compact_le_def
apply (cases m, simp, cases n, simp)
apply (simp add: Rep_cb_take, rule chain_mono, simp, simp)
done

lemma finite_range_cb_take: "finite (range (cb_take n))"
apply (cases n)
apply (subgoal_tac "range (cb_take 0) = {compact_bot}", simp, force)
apply (rule finite_imageD [where f="Rep_compact_basis"])
apply (rule finite_subset [where B="range (\<lambda>x. approx (n - 1)\<cdot>x)"])
apply (clarsimp simp add: Rep_cb_take)
apply (rule finite_range_approx)
apply (rule inj_onI, simp add: Rep_compact_basis_inject)
done

subsubsection \<open>Rank of basis elements\<close>

definition
  rank :: "'a compact_basis \<Rightarrow> nat"
where
  "rank x = (LEAST n. cb_take n x = x)"

lemma compact_approx_rank: "cb_take (rank x) x = x"
unfolding rank_def
apply (rule LeastI_ex)
apply (rule cb_take_covers)
done

lemma rank_leD: "rank x \<le> n \<Longrightarrow> cb_take n x = x"
apply (rule below_antisym [OF cb_take_less])
apply (subst compact_approx_rank [symmetric])
apply (erule cb_take_chain_le)
done

lemma rank_leI: "cb_take n x = x \<Longrightarrow> rank x \<le> n"
unfolding rank_def by (rule Least_le)

lemma rank_le_iff: "rank x \<le> n \<longleftrightarrow> cb_take n x = x"
by (rule iffI [OF rank_leD rank_leI])

lemma rank_compact_bot [simp]: "rank compact_bot = 0"
using rank_leI [of 0 compact_bot] by simp

lemma rank_eq_0_iff [simp]: "rank x = 0 \<longleftrightarrow> x = compact_bot"
using rank_le_iff [of x 0] by auto

definition
  rank_le :: "'a compact_basis \<Rightarrow> 'a compact_basis set"
where
  "rank_le x = {y. rank y \<le> rank x}"

definition
  rank_lt :: "'a compact_basis \<Rightarrow> 'a compact_basis set"
where
  "rank_lt x = {y. rank y < rank x}"

definition
  rank_eq :: "'a compact_basis \<Rightarrow> 'a compact_basis set"
where
  "rank_eq x = {y. rank y = rank x}"

lemma rank_eq_cong: "rank x = rank y \<Longrightarrow> rank_eq x = rank_eq y"
unfolding rank_eq_def by simp

lemma rank_lt_cong: "rank x = rank y \<Longrightarrow> rank_lt x = rank_lt y"
unfolding rank_lt_def by simp

lemma rank_eq_subset: "rank_eq x \<subseteq> rank_le x"
unfolding rank_eq_def rank_le_def by auto

lemma rank_lt_subset: "rank_lt x \<subseteq> rank_le x"
unfolding rank_lt_def rank_le_def by auto

lemma finite_rank_le: "finite (rank_le x)"
unfolding rank_le_def
apply (rule finite_subset [where B="range (cb_take (rank x))"])
apply clarify
apply (rule range_eqI)
apply (erule rank_leD [symmetric])
apply (rule finite_range_cb_take)
done

lemma finite_rank_eq: "finite (rank_eq x)"
by (rule finite_subset [OF rank_eq_subset finite_rank_le])

lemma finite_rank_lt: "finite (rank_lt x)"
by (rule finite_subset [OF rank_lt_subset finite_rank_le])

lemma rank_lt_Int_rank_eq: "rank_lt x \<inter> rank_eq x = {}"
unfolding rank_lt_def rank_eq_def rank_le_def by auto

lemma rank_lt_Un_rank_eq: "rank_lt x \<union> rank_eq x = rank_le x"
unfolding rank_lt_def rank_eq_def rank_le_def by auto

subsubsection \<open>Sequencing basis elements\<close>

definition
  place :: "'a compact_basis \<Rightarrow> nat"
where
  "place x = card (rank_lt x) + choose_pos (rank_eq x) x"

lemma place_bounded: "place x < card (rank_le x)"
unfolding place_def
 apply (rule ord_less_eq_trans)
  apply (rule add_strict_left_mono)
  apply (rule choose_pos_bounded)
   apply (rule finite_rank_eq)
  apply (simp add: rank_eq_def)
 apply (subst card_Un_disjoint [symmetric])
    apply (rule finite_rank_lt)
   apply (rule finite_rank_eq)
  apply (rule rank_lt_Int_rank_eq)
 apply (simp add: rank_lt_Un_rank_eq)
done

lemma place_ge: "card (rank_lt x) \<le> place x"
unfolding place_def by simp

lemma place_rank_mono:
  fixes x y :: "'a compact_basis"
  shows "rank x < rank y \<Longrightarrow> place x < place y"
apply (rule less_le_trans [OF place_bounded])
apply (rule order_trans [OF _ place_ge])
apply (rule card_mono)
apply (rule finite_rank_lt)
apply (simp add: rank_le_def rank_lt_def subset_eq)
done

lemma place_eqD: "place x = place y \<Longrightarrow> x = y"
 apply (rule linorder_cases [where x="rank x" and y="rank y"])
   apply (drule place_rank_mono, simp)
  apply (simp add: place_def)
  apply (rule inj_on_choose_pos [where A="rank_eq x", THEN inj_onD])
     apply (rule finite_rank_eq)
    apply (simp cong: rank_lt_cong rank_eq_cong)
   apply (simp add: rank_eq_def)
  apply (simp add: rank_eq_def)
 apply (drule place_rank_mono, simp)
done

lemma inj_place: "inj place"
by (rule inj_onI, erule place_eqD)

subsubsection \<open>Embedding and projection on basis elements\<close>

definition
  sub :: "'a compact_basis \<Rightarrow> 'a compact_basis"
where
  "sub x = (case rank x of 0 \<Rightarrow> compact_bot | Suc k \<Rightarrow> cb_take k x)"

lemma rank_sub_less: "x \<noteq> compact_bot \<Longrightarrow> rank (sub x) < rank x"
unfolding sub_def
apply (cases "rank x", simp)
apply (simp add: less_Suc_eq_le)
apply (rule rank_leI)
apply (rule cb_take_idem)
done

lemma place_sub_less: "x \<noteq> compact_bot \<Longrightarrow> place (sub x) < place x"
apply (rule place_rank_mono)
apply (erule rank_sub_less)
done

lemma sub_below: "sub x \<sqsubseteq> x"
unfolding sub_def by (cases "rank x", simp_all add: cb_take_less)

lemma rank_less_imp_below_sub: "\<lbrakk>x \<sqsubseteq> y; rank x < rank y\<rbrakk> \<Longrightarrow> x \<sqsubseteq> sub y"
unfolding sub_def
apply (cases "rank y", simp)
apply (simp add: less_Suc_eq_le)
apply (subgoal_tac "cb_take nat x \<sqsubseteq> cb_take nat y")
apply (simp add: rank_leD)
apply (erule cb_take_mono)
done

function
  basis_emb :: "'a compact_basis \<Rightarrow> ubasis"
where
  "basis_emb x = (if x = compact_bot then 0 else
    node (place x) (basis_emb (sub x))
      (basis_emb ` {y. place y < place x \<and> x \<sqsubseteq> y}))"
by auto

termination basis_emb
apply (relation "measure place", simp)
apply (simp add: place_sub_less)
apply simp
done

declare basis_emb.simps [simp del]

lemma basis_emb_compact_bot [simp]: "basis_emb compact_bot = 0"
by (simp add: basis_emb.simps)

lemma fin1: "finite {y. place y < place x \<and> x \<sqsubseteq> y}"
apply (subst Collect_conj_eq)
apply (rule finite_Int)
apply (rule disjI1)
apply (subgoal_tac "finite (place -` {n. n < place x})", simp)
apply (rule finite_vimageI [OF _ inj_place])
apply (simp add: lessThan_def [symmetric])
done

lemma fin2: "finite (basis_emb ` {y. place y < place x \<and> x \<sqsubseteq> y})"
by (rule finite_imageI [OF fin1])

lemma rank_place_mono:
  "\<lbrakk>place x < place y; x \<sqsubseteq> y\<rbrakk> \<Longrightarrow> rank x < rank y"
apply (rule linorder_cases, assumption)
apply (simp add: place_def cong: rank_lt_cong rank_eq_cong)
apply (drule choose_pos_lessD)
apply (rule finite_rank_eq)
apply (simp add: rank_eq_def)
apply (simp add: rank_eq_def)
apply simp
apply (drule place_rank_mono, simp)
done

lemma basis_emb_mono:
  "x \<sqsubseteq> y \<Longrightarrow> ubasis_le (basis_emb x) (basis_emb y)"
proof (induct "max (place x) (place y)" arbitrary: x y rule: less_induct)
  case less
  show ?case proof (rule linorder_cases)
    assume "place x < place y"
    then have "rank x < rank y"
      using \<open>x \<sqsubseteq> y\<close> by (rule rank_place_mono)
    with \<open>place x < place y\<close> show ?case
      apply (case_tac "y = compact_bot", simp)
      apply (simp add: basis_emb.simps [of y])
      apply (rule ubasis_le_trans [OF _ ubasis_le_lower [OF fin2]])
      apply (rule less)
       apply (simp add: less_max_iff_disj)
       apply (erule place_sub_less)
      apply (erule rank_less_imp_below_sub [OF \<open>x \<sqsubseteq> y\<close>])
      done
  next
    assume "place x = place y"
    hence "x = y" by (rule place_eqD)
    thus ?case by (simp add: ubasis_le_refl)
  next
    assume "place x > place y"
    with \<open>x \<sqsubseteq> y\<close> show ?case
      apply (case_tac "x = compact_bot", simp add: ubasis_le_minimal)
      apply (simp add: basis_emb.simps [of x])
      apply (rule ubasis_le_upper [OF fin2], simp)
      apply (rule less)
       apply (simp add: less_max_iff_disj)
       apply (erule place_sub_less)
      apply (erule rev_below_trans)
      apply (rule sub_below)
      done
  qed
qed

lemma inj_basis_emb: "inj basis_emb"
 apply (rule inj_onI)
 apply (case_tac "x = compact_bot")
  apply (case_tac [!] "y = compact_bot")
    apply simp
   apply (simp add: basis_emb.simps)
  apply (simp add: basis_emb.simps)
 apply (simp add: basis_emb.simps)
 apply (simp add: fin2 inj_eq [OF inj_place])
done

definition
  basis_prj :: "ubasis \<Rightarrow> 'a compact_basis"
where
  "basis_prj x = inv basis_emb
    (ubasis_until (\<lambda>x. x \<in> range (basis_emb :: 'a compact_basis \<Rightarrow> ubasis)) x)"

lemma basis_prj_basis_emb: "\<And>x. basis_prj (basis_emb x) = x"
unfolding basis_prj_def
 apply (subst ubasis_until_same)
  apply (rule rangeI)
 apply (rule inv_f_f)
 apply (rule inj_basis_emb)
done

lemma basis_prj_node:
  "\<lbrakk>finite S; node i a S \<notin> range (basis_emb :: 'a compact_basis \<Rightarrow> nat)\<rbrakk>
    \<Longrightarrow> basis_prj (node i a S) = (basis_prj a :: 'a compact_basis)"
unfolding basis_prj_def by simp

lemma basis_prj_0: "basis_prj 0 = compact_bot"
apply (subst basis_emb_compact_bot [symmetric])
apply (rule basis_prj_basis_emb)
done

lemma node_eq_basis_emb_iff:
  "finite S \<Longrightarrow> node i a S = basis_emb x \<longleftrightarrow>
    x \<noteq> compact_bot \<and> i = place x \<and> a = basis_emb (sub x) \<and>
        S = basis_emb ` {y. place y < place x \<and> x \<sqsubseteq> y}"
apply (cases "x = compact_bot", simp)
apply (simp add: basis_emb.simps [of x])
apply (simp add: fin2)
done

lemma basis_prj_mono: "ubasis_le a b \<Longrightarrow> basis_prj a \<sqsubseteq> basis_prj b"
proof (induct a b rule: ubasis_le.induct)
  case (ubasis_le_refl a) show ?case by (rule below_refl)
next
  case (ubasis_le_trans a b c) thus ?case by - (rule below_trans)
next
  case (ubasis_le_lower S a i) thus ?case
    apply (cases "node i a S \<in> range (basis_emb :: 'a compact_basis \<Rightarrow> nat)")
     apply (erule rangeE, rename_tac x)
     apply (simp add: basis_prj_basis_emb)
     apply (simp add: node_eq_basis_emb_iff)
     apply (simp add: basis_prj_basis_emb)
     apply (rule sub_below)
    apply (simp add: basis_prj_node)
    done
next
  case (ubasis_le_upper S b a i) thus ?case
    apply (cases "node i a S \<in> range (basis_emb :: 'a compact_basis \<Rightarrow> nat)")
     apply (erule rangeE, rename_tac x)
     apply (simp add: basis_prj_basis_emb)
     apply (clarsimp simp add: node_eq_basis_emb_iff)
     apply (simp add: basis_prj_basis_emb)
    apply (simp add: basis_prj_node)
    done
qed

lemma basis_emb_prj_less: "ubasis_le (basis_emb (basis_prj x)) x"
unfolding basis_prj_def
 apply (subst f_inv_into_f [where f=basis_emb])
  apply (rule ubasis_until)
  apply (rule range_eqI [where x=compact_bot])
  apply simp
 apply (rule ubasis_until_less)
done

lemma ideal_completion:
  "ideal_completion below Rep_compact_basis (approximants :: 'a \<Rightarrow> _)"
proof
  fix w :: "'a"
  show "below.ideal (approximants w)"
  proof (rule below.idealI)
    have "Abs_compact_basis (approx 0\<cdot>w) \<in> approximants w"
      by (simp add: approximants_def approx_below)
    thus "\<exists>x. x \<in> approximants w" ..
  next
    fix x y :: "'a compact_basis"
    assume x: "x \<in> approximants w" and y: "y \<in> approximants w"
    obtain i where i: "approx i\<cdot>(Rep_compact_basis x) = Rep_compact_basis x"
      using compact_eq_approx Rep_compact_basis' by fast
    obtain j where j: "approx j\<cdot>(Rep_compact_basis y) = Rep_compact_basis y"
      using compact_eq_approx Rep_compact_basis' by fast
    let ?z = "Abs_compact_basis (approx (max i j)\<cdot>w)"
    have "?z \<in> approximants w"
      by (simp add: approximants_def approx_below)
    moreover from x y have "x \<sqsubseteq> ?z \<and> y \<sqsubseteq> ?z"
      by (simp add: approximants_def compact_le_def)
         (metis i j monofun_cfun chain_mono chain_approx max.cobounded1 max.cobounded2)
    ultimately show "\<exists>z \<in> approximants w. x \<sqsubseteq> z \<and> y \<sqsubseteq> z" ..
  next
    fix x y :: "'a compact_basis"
    assume "x \<sqsubseteq> y" "y \<in> approximants w" thus "x \<in> approximants w"
      unfolding approximants_def compact_le_def
      by (auto elim: below_trans)
  qed
next
  fix Y :: "nat \<Rightarrow> 'a"
  assume "chain Y"
  thus "approximants (\<Squnion>i. Y i) = (\<Union>i. approximants (Y i))"
    unfolding approximants_def
    by (auto simp add: compact_below_lub_iff)
next
  fix a :: "'a compact_basis"
  show "approximants (Rep_compact_basis a) = {b. b \<sqsubseteq> a}"
    unfolding approximants_def compact_le_def ..
next
  fix x y :: "'a"
  assume "approximants x \<subseteq> approximants y"
  hence "\<forall>z. compact z \<longrightarrow> z \<sqsubseteq> x \<longrightarrow> z \<sqsubseteq> y"
    by (simp add: approximants_def subset_eq)
       (metis Abs_compact_basis_inverse')
  hence "(\<Squnion>i. approx i\<cdot>x) \<sqsubseteq> y"
    by (simp add: lub_below approx_below)
  thus "x \<sqsubseteq> y"
    by (simp add: lub_distribs)
next
  show "\<exists>f::'a compact_basis \<Rightarrow> nat. inj f"
    by (rule exI, rule inj_place)
qed

end

interpretation compact_basis:
  ideal_completion below Rep_compact_basis
    "approximants :: 'a::bifinite \<Rightarrow> 'a compact_basis set"
proof -
  obtain a :: "nat \<Rightarrow> 'a \<rightarrow> 'a" where "approx_chain a"
    using bifinite ..
  hence "bifinite_approx_chain a"
    unfolding bifinite_approx_chain_def .
  thus "ideal_completion below Rep_compact_basis (approximants :: 'a \<Rightarrow> _)"
    by (rule bifinite_approx_chain.ideal_completion)
qed

subsubsection \<open>EP-pair from any bifinite domain into \emph{udom}\<close>

context bifinite_approx_chain begin

definition
  udom_emb :: "'a \<rightarrow> udom"
where
  "udom_emb = compact_basis.extension (\<lambda>x. udom_principal (basis_emb x))"

definition
  udom_prj :: "udom \<rightarrow> 'a"
where
  "udom_prj = udom.extension (\<lambda>x. Rep_compact_basis (basis_prj x))"

lemma udom_emb_principal:
  "udom_emb\<cdot>(Rep_compact_basis x) = udom_principal (basis_emb x)"
unfolding udom_emb_def
apply (rule compact_basis.extension_principal)
apply (rule udom.principal_mono)
apply (erule basis_emb_mono)
done

lemma udom_prj_principal:
  "udom_prj\<cdot>(udom_principal x) = Rep_compact_basis (basis_prj x)"
unfolding udom_prj_def
apply (rule udom.extension_principal)
apply (rule compact_basis.principal_mono)
apply (erule basis_prj_mono)
done

lemma ep_pair_udom: "ep_pair udom_emb udom_prj"
 apply standard
  apply (rule compact_basis.principal_induct, simp)
  apply (simp add: udom_emb_principal udom_prj_principal)
  apply (simp add: basis_prj_basis_emb)
 apply (rule udom.principal_induct, simp)
 apply (simp add: udom_emb_principal udom_prj_principal)
 apply (rule basis_emb_prj_less)
done

end

abbreviation "udom_emb \<equiv> bifinite_approx_chain.udom_emb"
abbreviation "udom_prj \<equiv> bifinite_approx_chain.udom_prj"

lemmas ep_pair_udom =
  bifinite_approx_chain.ep_pair_udom [unfolded bifinite_approx_chain_def]

subsection \<open>Chain of approx functions for type \emph{udom}\<close>

definition
  udom_approx :: "nat \<Rightarrow> udom \<rightarrow> udom"
where
  "udom_approx i =
    udom.extension (\<lambda>x. udom_principal (ubasis_until (\<lambda>y. y \<le> i) x))"

lemma udom_approx_mono:
  "ubasis_le a b \<Longrightarrow>
    udom_principal (ubasis_until (\<lambda>y. y \<le> i) a) \<sqsubseteq>
    udom_principal (ubasis_until (\<lambda>y. y \<le> i) b)"
apply (rule udom.principal_mono)
apply (rule ubasis_until_mono)
apply (frule (2) order_less_le_trans [OF node_gt2])
apply (erule order_less_imp_le)
apply assumption
done

lemma adm_mem_finite: "\<lbrakk>cont f; finite S\<rbrakk> \<Longrightarrow> adm (\<lambda>x. f x \<in> S)"
by (erule adm_subst, induct set: finite, simp_all)

lemma udom_approx_principal:
  "udom_approx i\<cdot>(udom_principal x) =
    udom_principal (ubasis_until (\<lambda>y. y \<le> i) x)"
unfolding udom_approx_def
apply (rule udom.extension_principal)
apply (erule udom_approx_mono)
done

lemma finite_deflation_udom_approx: "finite_deflation (udom_approx i)"
proof
  fix x show "udom_approx i\<cdot>(udom_approx i\<cdot>x) = udom_approx i\<cdot>x"
    by (induct x rule: udom.principal_induct, simp)
       (simp add: udom_approx_principal ubasis_until_idem)
next
  fix x show "udom_approx i\<cdot>x \<sqsubseteq> x"
    by (induct x rule: udom.principal_induct, simp)
       (simp add: udom_approx_principal ubasis_until_less)
next
  have *: "finite (range (\<lambda>x. udom_principal (ubasis_until (\<lambda>y. y \<le> i) x)))"
    apply (subst range_composition [where f=udom_principal])
    apply (simp add: finite_range_ubasis_until)
    done
  show "finite {x. udom_approx i\<cdot>x = x}"
    apply (rule finite_range_imp_finite_fixes)
    apply (rule rev_finite_subset [OF *])
    apply (clarsimp, rename_tac x)
    apply (induct_tac x rule: udom.principal_induct)
    apply (simp add: adm_mem_finite *)
    apply (simp add: udom_approx_principal)
    done
qed

interpretation udom_approx: finite_deflation "udom_approx i"
by (rule finite_deflation_udom_approx)

lemma chain_udom_approx [simp]: "chain (\<lambda>i. udom_approx i)"
unfolding udom_approx_def
apply (rule chainI)
apply (rule udom.extension_mono)
apply (erule udom_approx_mono)
apply (erule udom_approx_mono)
apply (rule udom.principal_mono)
apply (rule ubasis_until_chain, simp)
done

lemma lub_udom_approx [simp]: "(\<Squnion>i. udom_approx i) = ID"
apply (rule cfun_eqI, simp add: contlub_cfun_fun)
apply (rule below_antisym)
apply (rule lub_below)
apply (simp)
apply (rule udom_approx.below)
apply (rule_tac x=x in udom.principal_induct)
apply (simp add: lub_distribs)
apply (rule_tac i=a in below_lub)
apply simp
apply (simp add: udom_approx_principal)
apply (simp add: ubasis_until_same ubasis_le_refl)
done

lemma udom_approx [simp]: "approx_chain udom_approx"
proof
  show "chain (\<lambda>i. udom_approx i)"
    by (rule chain_udom_approx)
  show "(\<Squnion>i. udom_approx i) = ID"
    by (rule lub_udom_approx)
qed

instance udom :: bifinite
  by standard (fast intro: udom_approx)

hide_const (open) node

end


theory Remove_And_Copy
  imports "HOL-IMP.Sem_Equiv" "HOL-IMP.Vars"
begin

notation Map.empty ("empty")

text \<open>
\exercise\label{exs:remove}
This exercise builds infrastructure for \autoref{exs:acopy}, where we
will have to manipulate partial maps from variable names to variable names.
\<close>
type_synonym tab = "vname \<Rightarrow> vname option"

text \<open>
  In addition to the function @{text merge} from theory @{text Fold},
  implement two functions @{text remove} and @{text remove_all} that
  remove one variable name from the range of a map, and a set of variable
  names from the domain and range of a map.
\<close>

definition
  merge :: "tab \<Rightarrow> tab \<Rightarrow> tab" where
  "merge t1 t2 = (\<lambda>m. if t1 m = t2 m then t1 m else None)"

definition remove :: "vname \<Rightarrow> tab \<Rightarrow> tab"  where
(* your definition/proof here *)

definition remove_all :: "vname set \<Rightarrow> tab \<Rightarrow> tab"  where
(* your definition/proof here *)

text \<open>
  Prove the following lemmas.
\<close>

lemma "ran (remove x t) = ran t - {x}"
(* your definition/proof here *)

lemma "ran (remove_all S t) \<subseteq> -S"
(* your definition/proof here *)

lemma "dom (remove_all S t) \<subseteq> -S"
(* your definition/proof here *)

lemma remove_all_update[simp]:
"remove_all {x} (t (x:= y)) = remove_all {x} t"
(* your definition/proof here *)

lemma remove_all_remove[simp]:
"remove_all {x} (remove x t) = remove_all {x} t"
(* your definition/proof here *)

lemma remove_all_Un[simp]:
"remove_all A (remove_all B t) = remove_all (A \<union> B) t"
(* your definition/proof here *)

lemma merge_remove_all:
  assumes "remove_all S t1 = remove_all S t"
  assumes "remove_all S t2 = remove_all S t"
  shows "remove_all S (merge t1 t2) = remove_all S t"
(* your definition/proof here *)

text \<open>
  \endexercise

  \exercise\label{exs:acopy}
  This is a more challenging exercise.
  Define and prove correct \emph{copy propagation}. Copy propagation is
similar to constant folding, but propagates the right-hand side of assignments
if these right-hand sides are just variables. For instance, the program
\texttt{x := y; z := x + z} will be transformed into
\texttt{x := y; z := y + z}.
The assignment \texttt{x := y} can then be eliminated in a liveness
analysis. Copy propagation is useful for cleaning up after other optimisation
phases.

  To do this, take the definitions for constant folding from theory
  @{text Fold} and adjust
  them to do copy propagation instead (without constant folding).
  Use the functions from \autoref{exs:remove} in your definition.
  The general proof idea and structure of constant folding remains
  applicable. Adjust it according to your new definitions.
\<close>

primrec copy :: "com \<Rightarrow> tab \<Rightarrow> com" where
(* your definition/proof here *)

value "copy (''x'' ::= V ''y'';; ''z'' ::= Plus (V ''x'') (V ''z'')) Map.empty"

lemma approx_merge:
  "approx t1 s \<or> approx t2 s \<Longrightarrow> approx (merge t1 t2) s"
  by (fastforce simp: merge_def approx_def)

lemma approx_map_le:
  "approx t2 s \<Longrightarrow> t1 \<subseteq>\<^sub>m t2 \<Longrightarrow> approx t1 s"
  by (clarsimp simp: approx_def map_le_def dom_def)

theorem "copy c Map.empty \<sim> c"
(* your definition/proof here *)

text \<open> \endexercise \<close>

end


section \<open>Integer Hull\<close>

text \<open>We define the integer hull of a polyhedron, i.e., the convex hull of all integer solutions.
  Moreover, we prove the result of Meyer that the integer hull of a polyhedron defined by an
  integer matrix is again a polyhedron, and give bounds for a corresponding decomposition theorem.\<close>

theory Integer_Hull
  imports
    Decomposition_Theorem
    Mixed_Integer_Solutions (* for gram-schmidt-floor *)
begin

context gram_schmidt
begin
definition "integer_hull P = convex_hull (P \<inter> \<int>\<^sub>v)"

lemma integer_hull_mono: "P \<subseteq> Q \<Longrightarrow> integer_hull P \<subseteq> integer_hull Q"
  unfolding integer_hull_def
  by (intro convex_hull_mono, auto)

end

lemma abs_neg_floor: "\<bar>of_int b\<bar> \<le> Bnd \<Longrightarrow> - (floor Bnd) \<le> b"
  using abs_le_D2 floor_mono by fastforce

lemma abs_pos_floor: "\<bar>of_int b\<bar> \<le> Bnd \<Longrightarrow> b \<le> floor Bnd"
  using abs_le_D1 le_floor_iff by auto

context gram_schmidt_floor
begin

lemma integer_hull_integer_cone: assumes C: "C \<subseteq> carrier_vec n"
  and CI: "C \<subseteq> \<int>\<^sub>v"
  shows "integer_hull (cone C) = cone C"
proof
  have "cone C \<inter> \<int>\<^sub>v \<subseteq> cone C" by blast
  thus "integer_hull (cone C) \<subseteq> cone C"
    using cone_cone[OF C] convex_cone[OF C] convex_hull_mono
    unfolding integer_hull_def convex_def by metis
  {
    fix x
    assume "x \<in> cone C"
    then obtain D where finD: "finite D" and DC: "D \<subseteq> C" and x: "x \<in> finite_cone D"
      unfolding cone_def by auto
    from DC C CI have D: "D \<subseteq> carrier_vec n" and DI: "D \<subseteq> \<int>\<^sub>v" by auto
    from D x finD have "x \<in> finite_cone (D \<union> {0\<^sub>v n})" using finite_cone_mono[of "D \<union> {0\<^sub>v n}" D] by auto
    then obtain l where x: "lincomb l (D \<union> {0\<^sub>v n}) = x"
                  and l: "l ` (D \<union> {0\<^sub>v n}) \<subseteq> {t. t \<ge> 0}"
      using finD unfolding finite_cone_def nonneg_lincomb_def by auto
    define L where "L = sum l (D \<union> {0\<^sub>v n})"
    define L_sup :: 'a where "L_sup = of_int (floor L + 1)"
    have "L_sup \<ge> L" using floor_correct[of L] unfolding L_sup_def by linarith
    have "L \<ge> 0" unfolding L_def using sum_nonneg[of _ l] l by blast
    hence "L_sup \<ge> 1" unfolding L_sup_def by simp
    hence "L_sup > 0" by fastforce

    let ?f = "\<lambda> y. if y = 0\<^sub>v n then L_sup - L else 0"
    have "lincomb ?f {0\<^sub>v n} = 0\<^sub>v n"
      using already_in_span[of "{}" "0\<^sub>v n"] lincomb_in_span local.span_empty
      by auto
    moreover have "lincomb ?f (D - {0\<^sub>v n}) = 0\<^sub>v n"
      by(rule lincomb_zero, insert D, auto)
    ultimately have "lincomb ?f (D \<union> {0\<^sub>v n}) = 0\<^sub>v n"
      using lincomb_vec_diff_add[of "D \<union> {0\<^sub>v n}" "{0\<^sub>v n}"] D finD by simp
    hence lcomb_f: "lincomb (\<lambda> y. l y + ?f y) (D \<union> {0\<^sub>v n}) = x"
      using lincomb_sum[of "D \<union> {0\<^sub>v n}" l ?f] finD D x by simp
    have "sum ?f (D \<union> {0\<^sub>v n}) = L_sup - L"
      by (simp add: sum.subset_diff[of "{0\<^sub>v n}" "D \<union> {0\<^sub>v n}" ?f] finD)
    hence "sum (\<lambda> y. l y + ?f y) (D \<union> {0\<^sub>v n}) = L_sup"
      using l L_def by auto
    moreover have "(\<lambda> y. l y + ?f y) ` (D \<union> {0\<^sub>v n}) \<subseteq> {t. t \<ge> 0}"
      using `L \<le> L_sup` l by force
    ultimately obtain l' where x: "lincomb l' (D \<union> {0\<^sub>v n}) = x"
                          and l': "l' ` (D \<union> {0\<^sub>v n}) \<subseteq> {t. t \<ge> 0}"
                          and sum_l': "sum l' (D \<union> {0\<^sub>v n}) = L_sup"
      using lcomb_f by blast

    let ?D' = "{L_sup \<cdot>\<^sub>v v | v. v \<in> D \<union> {0\<^sub>v n}}"
    have Did: "?D' = (\<lambda> v. L_sup \<cdot>\<^sub>v v) ` (D \<union> {0\<^sub>v n})" by force
    define l'' where "l'' = (\<lambda> y. l' ((1 / L_sup) \<cdot>\<^sub>v y) / L_sup)"
    obtain lD where dist: "distinct lD" and lD: "D \<union> {0\<^sub>v n} = set lD"
      using finite_distinct_list[of "D \<union> {0\<^sub>v n}"] finD by auto
    let ?lD' = "map ((\<cdot>\<^sub>v) L_sup) lD"
    have dist': "distinct ?lD'"
      using distinct_smult_nonneg[OF _ dist] `L_sup > 0` by fastforce

    have x': "lincomb l'' ?D' = x" unfolding x[symmetric] l''_def
      unfolding lincomb_def Did
    proof (subst finsum_reindex)
      from `L_sup > 0` smult_vec_nonneg_eq[of L_sup] show "inj_on ((\<cdot>\<^sub>v) L_sup) (D \<union> {0\<^sub>v n})"
        by (auto simp: inj_on_def)
      show "(\<lambda>v. l' (1 / L_sup \<cdot>\<^sub>v v) / L_sup \<cdot>\<^sub>v v) \<in> (\<cdot>\<^sub>v) L_sup ` (D \<union> {0\<^sub>v n}) \<rightarrow> carrier_vec n"
        using D by auto
      from `L_sup > 0` have "L_sup \<noteq> 0" by auto
      then show "(\<Oplus>\<^bsub>V\<^esub>x\<in>D \<union> {0\<^sub>v n}. l' (1 / L_sup \<cdot>\<^sub>v (L_sup \<cdot>\<^sub>v x)) / L_sup \<cdot>\<^sub>v (L_sup \<cdot>\<^sub>v x)) =
        (\<Oplus>\<^bsub>V\<^esub>v\<in>D \<union> {0\<^sub>v n}. l' v \<cdot>\<^sub>v v)"
        by (intro finsum_cong, insert D, auto simp: smult_smult_assoc)
    qed
    have "D \<union> {0\<^sub>v n} \<subseteq> cone C" using set_in_cone[OF C] DC zero_in_cone by blast
    hence D': "?D' \<subseteq> cone C" using cone_smult[of L_sup, OF _ C] `L_sup > 0` by auto
    have "D \<union> {0\<^sub>v n} \<subseteq> \<int>\<^sub>v" unfolding zero_vec_def using DI Ints_vec_def by auto
    moreover have "L_sup \<in> \<int>" unfolding L_sup_def by auto
    ultimately have D'I: "?D' \<subseteq> \<int>\<^sub>v" unfolding Ints_vec_def by force

    have "1 = sum l' (D \<union> {0\<^sub>v n}) * (1 / L_sup)" using sum_l' `L_sup > 0` by auto
    also have "sum l' (D \<union> {0\<^sub>v n}) = sum_list (map l' lD)"
      using sum.distinct_set_conv_list[OF dist] lD by auto
    also have "map l' lD = map (l' \<circ> ((\<cdot>\<^sub>v) (1 / L_sup))) ?lD'"
      using smult_smult_assoc[of "1 / L_sup" L_sup] `L_sup > 0`
      by (simp add: comp_assoc)
    also have "l' \<circ> ((\<cdot>\<^sub>v) (1 / L_sup)) = (\<lambda> x. l' ((1 / L_sup) \<cdot>\<^sub>v x))" by (rule comp_def)
    also have "sum_list (map \<dots> ?lD') * (1 / L_sup) =
               sum_list (map (\<lambda>y. l' (1 / L_sup \<cdot>\<^sub>v y) * (1 / L_sup)) ?lD')"
      using sum_list_mult_const[of _ "1 / L_sup" ?lD'] by presburger
    also have "\<dots> = sum_list (map l'' ?lD')"
      unfolding l''_def using `L_sup > 0` by simp
    also have "\<dots> = sum l'' (set ?lD')" using sum.distinct_set_conv_list[OF dist'] by metis
    also have "set ?lD' = ?D'" using lD by auto
    finally have sum_l': "sum l'' ?D' = 1" by auto

    moreover have "l'' ` ?D' \<subseteq> {t. t \<ge> 0}"
    proof
      fix y
      assume "y \<in> l'' ` ?D'"
      then obtain x where y: "y = l'' x" and "x \<in> ?D'" by blast
      then obtain v where "v \<in> D \<union> {0\<^sub>v n}" and x: "x = L_sup \<cdot>\<^sub>v v" by blast
      hence "0 \<le> l' v / L_sup" using l' `L_sup > 0` by fastforce
      also have "\<dots> = l'' x" unfolding x l''_def
        using smult_smult_assoc[of "1 / L_sup" "L_sup" v] `L_sup > 0` by simp
      finally show "y \<in> {t. t \<ge> 0}" using y by blast
      qed
    moreover have "finite ?D'" using finD by simp

    ultimately have "x \<in> integer_hull (cone C)"
      unfolding integer_hull_def convex_hull_def
      using x' D' D'I convex_lincomb_def[of l'' ?D' x]
                      nonneg_lincomb_def[of l'' ?D' x] by fast
  }
  thus "cone C \<subseteq> integer_hull (cone C)" by blast
qed

theorem decomposition_theorem_integer_hull_of_polyhedron: assumes A: "A \<in> carrier_mat nr n"
  and b: "b \<in> carrier_vec nr"
  and AI: "A \<in> \<int>\<^sub>m"
  and bI: "b \<in> \<int>\<^sub>v"
  and P: "P = polyhedron A b"
  and Bnd: "Bnd = Max (abs ` (elements_mat A \<union> vec_set b))"
shows "\<exists> H C. H \<union> C \<subseteq> carrier_vec n \<inter> \<int>\<^sub>v
  \<and> H \<subseteq> Bounded_vec (fact (n+1) * (max 1 Bnd)^n)
  \<and> C \<subseteq> Bounded_vec (fact n * (max 1 Bnd)^n)
  \<and> finite (H \<union> C)
  \<and> integer_hull P = convex_hull H + cone C"
proof -
  define DBnd where "DBnd = det_bound n (max 1 Bnd)"
  define nBnd where "nBnd = of_nat (n+1) * DBnd"
  have DBnd: "DBnd = fact n * (max 1 Bnd)^n" unfolding DBnd_def det_bound_def by auto
  have nBnd: "nBnd = fact (n+1) * (max 1 Bnd)^n" unfolding nBnd_def DBnd
    by auto
  have DBnd0: "DBnd \<ge> 0" unfolding DBnd_def det_bound_def by auto
  have Pn: "P \<subseteq> carrier_vec n" unfolding P polyhedron_def by auto
  have "A \<in> Bounded_mat Bnd \<and> b \<in> Bounded_vec Bnd"
    unfolding Bnd Bounded_mat_elements_mat Bounded_vec_vec_set
    by (intro ballI conjI Max_ge finite_imageI imageI finite_UnI, auto)
  from decomposition_theorem_polyhedra_1[OF A b P, of Bnd] AI bI this
  obtain QQ Q C where C: "C \<subseteq> carrier_vec n" and finC: "finite C"
    and QQ: "QQ \<subseteq> carrier_vec n" and finQ: "finite QQ" and BndQQ: "QQ \<subseteq> Bounded_vec DBnd"
    and P: "P = Q + cone C"
    and Q_def: "Q = convex_hull QQ"
    and CI: "C \<subseteq> \<int>\<^sub>v" and BndC: "C \<subseteq> Bounded_vec DBnd"
    by (auto simp: DBnd_def)
  define Bnd' where "Bnd' = of_nat n * DBnd"
  note coneC = cone_iff_finite_cone[OF C finC]
  have Q: "Q \<subseteq> carrier_vec n" unfolding Q_def using convex_hull_carrier[OF QQ] .
  define B where "B = {x. \<exists> a D. nonneg_lincomb a D x \<and> D \<subseteq> C \<and> lin_indpt D \<and> (\<forall> d \<in> D. a d \<le> 1)}"
  {
    fix b
    assume "b \<in> B"
    then obtain a D where b: "b = lincomb a D" and DC: "D \<subseteq> C"
      and linD: "lin_indpt D" and bnd_a: "\<forall> d \<in> D. 0 \<le> a d \<and> a d \<le> 1"
      by (force simp: B_def nonneg_lincomb_def)
    from DC C have D: "D \<subseteq> carrier_vec n" by auto
    from DC finC have finD: "finite D" by (metis finite_subset)
    from D linD finD have cardD: "card D \<le> n" using dim_is_n li_le_dim(2) by auto
    from BndC DC have BndD: "D \<subseteq> Bounded_vec DBnd" by auto
    from lincomb_card_bound[OF this D DBnd0 _ cardD, of a, folded b] bnd_a
    have "b \<in> Bounded_vec Bnd'" unfolding Bnd'_def by force
  }
  hence BndB: "B \<subseteq> Bounded_vec Bnd'" ..
  from BndQQ have BndQ: "Q \<subseteq> Bounded_vec DBnd" unfolding Q_def using QQ by (metis convex_hull_bound)
  have B: "B \<subseteq> carrier_vec n"
    unfolding B_def nonneg_lincomb_def using C by auto
  from Q B have QB: "Q + B \<subseteq> carrier_vec n" by (auto elim!: set_plus_elim)
  from sum_in_Bounded_vecI[of _ DBnd _ Bnd' n] BndQ BndB B Q
  have "Q + B \<subseteq> Bounded_vec (DBnd + Bnd')" by (auto elim!: set_plus_elim)
  also have "DBnd + Bnd' = nBnd" unfolding nBnd_def Bnd'_def by (simp add: algebra_simps)
  finally have QB_Bnd: "Q + B \<subseteq> Bounded_vec nBnd" by blast
  have finQBZ: "finite ((Q + B) \<inter> \<int>\<^sub>v)"
  proof (rule finite_subset[OF subsetI])
    define ZBnd where "ZBnd = floor nBnd"
    let ?vecs = "set (map vec_of_list (concat_lists (map (\<lambda> i. map (of_int :: _ \<Rightarrow> 'a) [-ZBnd..ZBnd]) [0..<n])))"
    have id: "?vecs = vec_of_list `
      {as. length as = n \<and> (\<forall>i<n. \<exists> b. as ! i = of_int b \<and> b \<in> {- ZBnd..ZBnd})}"
      unfolding set_map by (rule image_cong, auto)
    show "finite ?vecs" by (rule finite_set)
    fix x
    assume "x \<in> (Q + B) \<inter> \<int>\<^sub>v"
    hence xQB: "x \<in> Q + B" and xI: "x \<in> \<int>\<^sub>v" by auto
    from xQB QB_Bnd QB have xBnd: "x \<in> Bounded_vec nBnd" and x: "x \<in> carrier_vec n" by auto
    have xid: "x = vec_of_list (list_of_vec x)" by auto
    show "x \<in> ?vecs" unfolding id
    proof (subst xid, intro imageI CollectI conjI allI impI)
      show "length (list_of_vec x) = n" using x by auto
      fix i
      assume i: "i < n"
      have id: "list_of_vec x ! i = x $ i" using i x by auto
      from xBnd[unfolded Bounded_vec_def] i x have xiBnd: "abs (x $ i) \<le> nBnd" by auto
      from xI[unfolded Ints_vec_def] i x have "x $ i \<in> \<int>" by auto
      then obtain b where b: "x $ i = of_int b" unfolding Ints_def by blast
      show "\<exists>b. list_of_vec x ! i = of_int b \<and> b \<in> {- ZBnd..ZBnd}" unfolding id ZBnd_def
        using xiBnd unfolding b by (intro exI[of _ b], auto intro!: abs_neg_floor abs_pos_floor)
    qed
  qed
  have QBZ: "(Q + B) \<inter> \<int>\<^sub>v \<subseteq> carrier_vec n" using QB by auto
  from decomposition_theorem_polyhedra_2[OF QBZ finQBZ, folded integer_hull_def, OF C finC refl]
  obtain A' b' nr' where A': "A' \<in> carrier_mat nr' n" and b': "b' \<in> carrier_vec nr'"
    and IH: "integer_hull (Q + B) + cone C = polyhedron A' b'"
    by auto
  {
    fix p
    assume "p \<in> P \<inter> \<int>\<^sub>v"
    hence pI: "p \<in> \<int>\<^sub>v" and p: "p \<in> Q + cone C" unfolding P by auto
    from set_plus_elim[OF p] obtain q c where
      pqc: "p = q + c" and qQ: "q \<in> Q" and cC: "c \<in> cone C" by auto
    from qQ Q have q: "q \<in> carrier_vec n" by auto
    from Caratheodory_theorem[OF C] cC
    obtain D where cD: "c \<in> finite_cone D" and DC: "D \<subseteq> C" and linD: "lin_indpt D" by auto
    from DC C have D: "D \<subseteq> carrier_vec n" by auto
    from DC finC have finD: "finite D" by (metis finite_subset)
    from cD finD
    obtain a where "nonneg_lincomb a D c" unfolding finite_cone_def by auto
    hence caD: "c = lincomb a D" and a0: "\<And> d. d \<in> D \<Longrightarrow> a d \<ge> 0"
      unfolding nonneg_lincomb_def by auto
    define a1 where "a1 = (\<lambda> c. a c - of_int (floor (a c)))"
    define a2 where "a2 = (\<lambda> c. of_int (floor (a c)) :: 'a)"
    define d where "d = lincomb a2 D"
    define b where "b = lincomb a1 D"
    have b: "b \<in> carrier_vec n" and d: "d \<in> carrier_vec n" unfolding d_def b_def using D by auto
    have bB: "b \<in> B" unfolding B_def b_def nonneg_lincomb_def
    proof (intro CollectI exI[of _ a1] exI[of _ D] conjI ballI refl subsetI linD)
      show "x \<in> a1 ` D \<Longrightarrow> 0 \<le> x" for x using a0 unfolding a1_def by auto
      show "a1 c \<le> 1" for c unfolding a1_def by linarith
    qed (insert DC, auto)
    have cbd: "c = b + d" unfolding b_def d_def caD lincomb_sum[OF finD D, symmetric]
      by (rule lincomb_cong[OF refl D], auto simp: a1_def a2_def)
    have "nonneg_lincomb a2 D d" unfolding d_def nonneg_lincomb_def
      by (intro allI conjI refl subsetI, insert a0, auto simp: a2_def)
    hence dC: "d \<in> cone C" unfolding cone_def finite_cone_def using finC finD DC by auto
    have p: "p = (q + b) + d" unfolding pqc cbd using q b d by auto
    have dI: "d \<in> \<int>\<^sub>v" using CI DC C unfolding d_def indexed_Ints_vec_UNIV
      by (intro lincomb_indexed_Ints_vec, auto simp: a2_def)
    from diff_indexed_Ints_vec[of _ _ _ UNIV, folded indexed_Ints_vec_UNIV, OF _ d pI dI, unfolded p]
    have "q + b + d - d \<in> \<int>\<^sub>v" using q b d by auto
    also have "q + b + d - d = q + b" using q b d by auto
    finally have qbI: "q + b \<in> \<int>\<^sub>v" by auto
    have "p \<in> integer_hull (Q + B) + cone C" unfolding p integer_hull_def
      by (intro set_plus_intro dC set_mp[OF set_in_convex_hull] IntI qQ bB qbI, insert Q B,
          auto elim!: set_plus_elim)
  }
  hence "P \<inter> \<int>\<^sub>v \<subseteq> integer_hull (Q + B) + cone C" by auto
  hence one_dir: "integer_hull P \<subseteq> integer_hull (Q + B) + cone C" unfolding IH
    unfolding integer_hull_def using convex_convex_hull[OF polyhedra_are_convex[OF A' b' refl]]
      convex_hull_mono by blast
  have "integer_hull (Q + B) + cone C \<subseteq> integer_hull P + cone C" unfolding P
  proof (intro set_plus_mono2 subset_refl integer_hull_mono)
    show "B \<subseteq> cone C" unfolding B_def cone_def finite_cone_def using finite_subset[OF _ finC] by auto
  qed
  also have "\<dots> = integer_hull P + integer_hull (cone C)"
    using integer_hull_integer_cone[OF C CI] by simp
  also have "\<dots> = convex_hull (P \<inter> \<int>\<^sub>v) + convex_hull (cone C \<inter> \<int>\<^sub>v)"
    unfolding integer_hull_def by simp
  also have "\<dots> = convex_hull ((P \<inter> \<int>\<^sub>v) + (cone C \<inter> \<int>\<^sub>v))"
    by (rule convex_hull_sum[symmetric], insert Pn cone_carrier[OF C], auto)
  also have "\<dots> \<subseteq> convex_hull ((P + cone C) \<inter> \<int>\<^sub>v)"
  proof (rule convex_hull_mono)
    show "P \<inter> \<int>\<^sub>v + cone C \<inter> \<int>\<^sub>v \<subseteq> (P + cone C) \<inter> \<int>\<^sub>v"
      using add_indexed_Ints_vec[of _ n _ UNIV, folded indexed_Ints_vec_UNIV] cone_carrier[OF C] Pn
      by (auto elim!: set_plus_elim)
  qed
  also have "\<dots> = integer_hull (P + cone C)" unfolding integer_hull_def ..
  also have "P + cone C = P"
  proof -
    have CC: "cone C \<subseteq> carrier_vec n" using C by (rule cone_carrier)
    have "P + cone C = Q + (cone C + cone C)" unfolding P
      by (rule assoc_add_vecset[symmetric, OF Q CC CC])
    also have "cone C + cone C = cone C" by (rule cone_add_cone[OF C])
    finally show ?thesis unfolding P .
  qed
  finally have "integer_hull (Q + B) + cone C \<subseteq> integer_hull P" .
  with one_dir have id: "integer_hull P = integer_hull (Q + B) + cone C" by auto
  show ?thesis unfolding id unfolding integer_hull_def nBnd[symmetric] DBnd[symmetric]
  proof (rule exI[of _ "(Q + B) \<inter> \<int>\<^sub>v"], intro exI[of _ C] conjI refl BndC)
    from QB_Bnd show "(Q + B) \<inter> \<int>\<^sub>v \<subseteq> Bounded_vec nBnd" by auto
    show "(Q + B) \<inter> \<int>\<^sub>v \<union> C \<subseteq> carrier_vec n \<inter> \<int>\<^sub>v"
      using QB C CI by auto
    show "finite ((Q + B) \<inter> \<int>\<^sub>v \<union> C)" using finQBZ finC by auto
  qed
qed

corollary integer_hull_of_polyhedron: assumes A: "A \<in> carrier_mat nr n"
  and b: "b \<in> carrier_vec nr"
  and AI: "A \<in> \<int>\<^sub>m"
  and bI: "b \<in> \<int>\<^sub>v"
  and P: "P = polyhedron A b"
shows "\<exists> A' b' nr'. A' \<in> carrier_mat nr' n \<and> b' \<in> carrier_vec nr' \<and> integer_hull P = polyhedron A' b'"
proof -
  from decomposition_theorem_integer_hull_of_polyhedron[OF A b AI bI P refl]
  obtain H C
    where HC: "H \<union> C \<subseteq> carrier_vec n \<inter> \<int>\<^sub>v" "finite (H \<union> C)"
      and decomp: "integer_hull P = convex_hull H + cone C" by auto
  show ?thesis
    by (rule decomposition_theorem_polyhedra_2[OF _ _ _ _ decomp], insert HC, auto)
qed

corollary small_integer_solution_nonstrict_via_decomp: fixes A :: "'a mat"
  assumes A: "A \<in> carrier_mat nr n"
    and b: "b \<in> carrier_vec nr"
    and AI: "A \<in> \<int>\<^sub>m"
    and bI: "b \<in> \<int>\<^sub>v"
    and Bnd: "Bnd = Max (abs ` (elements_mat A \<union> vec_set b))"
    and x: "x \<in> carrier_vec n"
    and xI: "x \<in> \<int>\<^sub>v"
    and sol: "A *\<^sub>v x \<le> b"
  shows "\<exists> y.
  y \<in> carrier_vec n \<and>
  y \<in> \<int>\<^sub>v \<and>
  A *\<^sub>v y \<le> b \<and>
  y \<in> Bounded_vec (fact (n+1) * (max 1 Bnd)^n)"
proof -
  from x sol have "x \<in> polyhedron A b" unfolding polyhedron_def by auto
  with xI x have xsol: "x \<in> integer_hull (polyhedron A b)" unfolding integer_hull_def
    by (meson IntI convex_hull_mono in_mono inf_sup_ord(1) inf_sup_ord(2) set_in_convex_hull)
  from decomposition_theorem_integer_hull_of_polyhedron[OF A b AI bI refl Bnd]
  obtain H C where HC: "H \<union> C \<subseteq> carrier_vec n \<inter> \<int>\<^sub>v"
    "H \<subseteq> Bounded_vec (fact (n + 1) * max 1 Bnd ^ n)"
    "finite (H \<union> C)" and
    id: "integer_hull (polyhedron A b) = convex_hull H + cone C"
    by auto
  from xsol[unfolded id] have "H \<noteq> {}" unfolding set_plus_def by auto
  then obtain h where hH: "h \<in> H" by auto
  with set_in_convex_hull have "h \<in> convex_hull H" using HC by auto
  moreover have "0\<^sub>v n \<in> cone C" by (intro zero_in_cone)
  ultimately have "h + 0\<^sub>v n \<in> integer_hull (polyhedron A b)" unfolding id by auto
  also have "h + 0\<^sub>v n = h" using hH HC by auto
  also have "integer_hull (polyhedron A b) \<subseteq> convex_hull (polyhedron A b)"
    unfolding integer_hull_def by (rule convex_hull_mono, auto)
  also have "convex_hull (polyhedron A b) = polyhedron A b" using A b
    using convex_convex_hull polyhedra_are_convex by blast
  finally have h: "h \<in> carrier_vec n" "A *\<^sub>v h \<le> b" unfolding polyhedron_def by auto
  show ?thesis
    by (intro exI[of _ h] conjI h, insert HC hH, auto)
qed

end
end