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

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

theory Universal
imports Bifinite Completion "HOL-Library.Nat_Bijection"
begin

no_notation binomial  (infixl "choose" 65)

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 ((^) 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_all
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:
    "(\<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 simp_all

termination basis_emb
  by (relation "measure place") (simp_all add: place_sub_less)

declare basis_emb.simps [simp del]

lemma basis_emb_compact_bot [simp]:
  "basis_emb compact_bot = 0"
  using basis_emb.simps [of compact_bot] by simp

lemma basis_emb_rec:
  "basis_emb x = node (place x) (basis_emb (sub x)) (basis_emb ` {y. place y < place x \<and> x \<sqsubseteq> y})"
  if "x \<noteq> compact_bot"
  using that basis_emb.simps [of x] by simp

lemma basis_emb_eq_0_iff [simp]:
  "basis_emb x = 0 \<longleftrightarrow> x = compact_bot"
  by (cases "x = compact_bot") (simp_all add: basis_emb_rec)

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"
proof (rule injI)
  fix x y
  assume "basis_emb x = basis_emb y"
  then show "x = y"
    by (cases "x = compact_bot \<or> y = compact_bot") (auto simp add: basis_emb_rec fin2 place_eqD)
qed

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

notation binomial  (infixl "choose" 65)

end


(*  Title:      HOL/Quotient_Examples/Quotient_Message.thy
    Author:     Christian Urban

Message datatype, based on an older version by Larry Paulson.
*)

theory Quotient_Message
imports Main "HOL-Library.Quotient_Syntax"
begin

subsection\<open>Defining the Free Algebra\<close>

datatype
  freemsg = NONCE  nat
        | MPAIR  freemsg freemsg
        | CRYPT  nat freemsg
        | DECRYPT  nat freemsg

inductive
  msgrel::"freemsg \<Rightarrow> freemsg \<Rightarrow> bool" (infixl "\<sim>" 50)
where
  CD:    "CRYPT K (DECRYPT K X) \<sim> X"
| DC:    "DECRYPT K (CRYPT K X) \<sim> X"
| NONCE: "NONCE N \<sim> NONCE N"
| MPAIR: "\<lbrakk>X \<sim> X'; Y \<sim> Y'\<rbrakk> \<Longrightarrow> MPAIR X Y \<sim> MPAIR X' Y'"
| CRYPT: "X \<sim> X' \<Longrightarrow> CRYPT K X \<sim> CRYPT K X'"
| DECRYPT: "X \<sim> X' \<Longrightarrow> DECRYPT K X \<sim> DECRYPT K X'"
| SYM:   "X \<sim> Y \<Longrightarrow> Y \<sim> X"
| TRANS: "\<lbrakk>X \<sim> Y; Y \<sim> Z\<rbrakk> \<Longrightarrow> X \<sim> Z"

lemmas msgrel.intros[intro]

text\<open>Proving that it is an equivalence relation\<close>

lemma msgrel_refl: "X \<sim> X"
by (induct X) (auto intro: msgrel.intros)

theorem equiv_msgrel: "equivp msgrel"
proof (rule equivpI)
  show "reflp msgrel" by (rule reflpI) (simp add: msgrel_refl)
  show "symp msgrel" by (rule sympI) (blast intro: msgrel.SYM)
  show "transp msgrel" by (rule transpI) (blast intro: msgrel.TRANS)
qed

subsection\<open>Some Functions on the Free Algebra\<close>

subsubsection\<open>The Set of Nonces\<close>

primrec
  freenonces :: "freemsg \<Rightarrow> nat set"
where
  "freenonces (NONCE N) = {N}"
| "freenonces (MPAIR X Y) = freenonces X \<union> freenonces Y"
| "freenonces (CRYPT K X) = freenonces X"
| "freenonces (DECRYPT K X) = freenonces X"

theorem msgrel_imp_eq_freenonces:
  assumes a: "U \<sim> V"
  shows "freenonces U = freenonces V"
  using a by (induct) (auto)

subsubsection\<open>The Left Projection\<close>

text\<open>A function to return the left part of the top pair in a message.  It will
be lifted to the initial algebra, to serve as an example of that process.\<close>
primrec
  freeleft :: "freemsg \<Rightarrow> freemsg"
where
  "freeleft (NONCE N) = NONCE N"
| "freeleft (MPAIR X Y) = X"
| "freeleft (CRYPT K X) = freeleft X"
| "freeleft (DECRYPT K X) = freeleft X"

text\<open>This theorem lets us prove that the left function respects the
equivalence relation.  It also helps us prove that MPair
  (the abstract constructor) is injective\<close>
lemma msgrel_imp_eqv_freeleft_aux:
  shows "freeleft U \<sim> freeleft U"
  by (fact msgrel_refl)

theorem msgrel_imp_eqv_freeleft:
  assumes a: "U \<sim> V"
  shows "freeleft U \<sim> freeleft V"
  using a
  by (induct) (auto intro: msgrel_imp_eqv_freeleft_aux)

subsubsection\<open>The Right Projection\<close>

text\<open>A function to return the right part of the top pair in a message.\<close>
primrec
  freeright :: "freemsg \<Rightarrow> freemsg"
where
  "freeright (NONCE N) = NONCE N"
| "freeright (MPAIR X Y) = Y"
| "freeright (CRYPT K X) = freeright X"
| "freeright (DECRYPT K X) = freeright X"

text\<open>This theorem lets us prove that the right function respects the
equivalence relation.  It also helps us prove that MPair
  (the abstract constructor) is injective\<close>
lemma msgrel_imp_eqv_freeright_aux:
  shows "freeright U \<sim> freeright U"
  by (fact msgrel_refl)

theorem msgrel_imp_eqv_freeright:
  assumes a: "U \<sim> V"
  shows "freeright U \<sim> freeright V"
  using a
  by (induct) (auto intro: msgrel_imp_eqv_freeright_aux)

subsubsection\<open>The Discriminator for Constructors\<close>

text\<open>A function to distinguish nonces, mpairs and encryptions\<close>
primrec
  freediscrim :: "freemsg \<Rightarrow> int"
where
   "freediscrim (NONCE N) = 0"
 | "freediscrim (MPAIR X Y) = 1"
 | "freediscrim (CRYPT K X) = freediscrim X + 2"
 | "freediscrim (DECRYPT K X) = freediscrim X - 2"

text\<open>This theorem helps us prove \<^term>\<open>Nonce N \<noteq> MPair X Y\<close>\<close>
theorem msgrel_imp_eq_freediscrim:
  assumes a: "U \<sim> V"
  shows "freediscrim U = freediscrim V"
  using a by (induct) (auto)

subsection\<open>The Initial Algebra: A Quotiented Message Type\<close>

quotient_type msg = freemsg / msgrel
  by (rule equiv_msgrel)

text\<open>The abstract message constructors\<close>

quotient_definition
  "Nonce :: nat \<Rightarrow> msg"
is
  "NONCE"
done

quotient_definition
  "MPair :: msg \<Rightarrow> msg \<Rightarrow> msg"
is
  "MPAIR"
by (rule MPAIR)

quotient_definition
  "Crypt :: nat \<Rightarrow> msg \<Rightarrow> msg"
is
  "CRYPT"
by (rule CRYPT)

quotient_definition
  "Decrypt :: nat \<Rightarrow> msg \<Rightarrow> msg"
is
  "DECRYPT"
by (rule DECRYPT)

text\<open>Establishing these two equations is the point of the whole exercise\<close>
theorem CD_eq [simp]:
  shows "Crypt K (Decrypt K X) = X"
  by (lifting CD)

theorem DC_eq [simp]:
  shows "Decrypt K (Crypt K X) = X"
  by (lifting DC)

subsection\<open>The Abstract Function to Return the Set of Nonces\<close>

quotient_definition
   "nonces:: msg \<Rightarrow> nat set"
is
  "freenonces"
by (rule msgrel_imp_eq_freenonces)

text\<open>Now prove the four equations for \<^term>\<open>nonces\<close>\<close>

lemma nonces_Nonce [simp]:
  shows "nonces (Nonce N) = {N}"
  by (lifting freenonces.simps(1))

lemma nonces_MPair [simp]:
  shows "nonces (MPair X Y) = nonces X \<union> nonces Y"
  by (lifting freenonces.simps(2))

lemma nonces_Crypt [simp]:
  shows "nonces (Crypt K X) = nonces X"
  by (lifting freenonces.simps(3))

lemma nonces_Decrypt [simp]:
  shows "nonces (Decrypt K X) = nonces X"
  by (lifting freenonces.simps(4))

subsection\<open>The Abstract Function to Return the Left Part\<close>

quotient_definition
  "left:: msg \<Rightarrow> msg"
is
  "freeleft"
by (rule msgrel_imp_eqv_freeleft)

lemma left_Nonce [simp]:
  shows "left (Nonce N) = Nonce N"
  by (lifting freeleft.simps(1))

lemma left_MPair [simp]:
  shows "left (MPair X Y) = X"
  by (lifting freeleft.simps(2))

lemma left_Crypt [simp]:
  shows "left (Crypt K X) = left X"
  by (lifting freeleft.simps(3))

lemma left_Decrypt [simp]:
  shows "left (Decrypt K X) = left X"
  by (lifting freeleft.simps(4))

subsection\<open>The Abstract Function to Return the Right Part\<close>

quotient_definition
  "right:: msg \<Rightarrow> msg"
is
  "freeright"
by (rule msgrel_imp_eqv_freeright)

text\<open>Now prove the four equations for \<^term>\<open>right\<close>\<close>

lemma right_Nonce [simp]:
  shows "right (Nonce N) = Nonce N"
  by (lifting freeright.simps(1))

lemma right_MPair [simp]:
  shows "right (MPair X Y) = Y"
  by (lifting freeright.simps(2))

lemma right_Crypt [simp]:
  shows "right (Crypt K X) = right X"
  by (lifting freeright.simps(3))

lemma right_Decrypt [simp]:
  shows "right (Decrypt K X) = right X"
  by (lifting freeright.simps(4))

subsection\<open>Injectivity Properties of Some Constructors\<close>

text\<open>Can also be proved using the function \<^term>\<open>nonces\<close>\<close>
lemma Nonce_Nonce_eq [iff]:
  shows "(Nonce m = Nonce n) = (m = n)"
proof
  assume "Nonce m = Nonce n"
  then show "m = n"
    by (descending) (drule msgrel_imp_eq_freenonces, simp)
next
  assume "m = n"
  then show "Nonce m = Nonce n" by simp
qed

lemma MPair_imp_eq_left:
  assumes eq: "MPair X Y = MPair X' Y'"
  shows "X = X'"
  using eq
  by (descending) (drule msgrel_imp_eqv_freeleft, simp)

lemma MPair_imp_eq_right:
  shows "MPair X Y = MPair X' Y' \<Longrightarrow> Y = Y'"
  by (descending) (drule msgrel_imp_eqv_freeright, simp)

theorem MPair_MPair_eq [iff]:
  shows "(MPair X Y = MPair X' Y') = (X=X' & Y=Y')"
  by (blast dest: MPair_imp_eq_left MPair_imp_eq_right)

theorem Nonce_neq_MPair [iff]:
  shows "Nonce N \<noteq> MPair X Y"
  by (descending) (auto dest: msgrel_imp_eq_freediscrim)

text\<open>Example suggested by a referee\<close>

theorem Crypt_Nonce_neq_Nonce:
  shows "Crypt K (Nonce M) \<noteq> Nonce N"
  by (descending) (auto dest: msgrel_imp_eq_freediscrim)

text\<open>...and many similar results\<close>

theorem Crypt2_Nonce_neq_Nonce:
  shows "Crypt K (Crypt K' (Nonce M)) \<noteq> Nonce N"
  by (descending) (auto dest: msgrel_imp_eq_freediscrim)

theorem Crypt_Crypt_eq [iff]:
  shows "(Crypt K X = Crypt K X') = (X=X')"
proof
  assume "Crypt K X = Crypt K X'"
  hence "Decrypt K (Crypt K X) = Decrypt K (Crypt K X')" by simp
  thus "X = X'" by simp
next
  assume "X = X'"
  thus "Crypt K X = Crypt K X'" by simp
qed

theorem Decrypt_Decrypt_eq [iff]:
  shows "(Decrypt K X = Decrypt K X') = (X=X')"
proof
  assume "Decrypt K X = Decrypt K X'"
  hence "Crypt K (Decrypt K X) = Crypt K (Decrypt K X')" by simp
  thus "X = X'" by simp
next
  assume "X = X'"
  thus "Decrypt K X = Decrypt K X'" by simp
qed

lemma msg_induct [case_names Nonce MPair Crypt Decrypt, cases type: msg]:
  assumes N: "\<And>N. P (Nonce N)"
      and M: "\<And>X Y. \<lbrakk>P X; P Y\<rbrakk> \<Longrightarrow> P (MPair X Y)"
      and C: "\<And>K X. P X \<Longrightarrow> P (Crypt K X)"
      and D: "\<And>K X. P X \<Longrightarrow> P (Decrypt K X)"
  shows "P msg"
  using N M C D
  by (descending) (auto intro: freemsg.induct)

subsection\<open>The Abstract Discriminator\<close>

text\<open>However, as \<open>Crypt_Nonce_neq_Nonce\<close> above illustrates, we don't
need this function in order to prove discrimination theorems.\<close>

quotient_definition
  "discrim:: msg \<Rightarrow> int"
is
  "freediscrim"
by (rule msgrel_imp_eq_freediscrim)

text\<open>Now prove the four equations for \<^term>\<open>discrim\<close>\<close>

lemma discrim_Nonce [simp]:
  shows "discrim (Nonce N) = 0"
  by (lifting freediscrim.simps(1))

lemma discrim_MPair [simp]:
  shows "discrim (MPair X Y) = 1"
  by (lifting freediscrim.simps(2))

lemma discrim_Crypt [simp]:
  shows "discrim (Crypt K X) = discrim X + 2"
  by (lifting freediscrim.simps(3))

lemma discrim_Decrypt [simp]:
  shows "discrim (Decrypt K X) = discrim X - 2"
  by (lifting freediscrim.simps(4))

end


theory T136
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z)))
"
nitpick[card nat=4,timeout=86400]
oops
end


(*
  File:    Rational_FPS_Solver.thy
  Author:  Manuel Eberl, TU München
*)
section \<open>Solver for rational formal power series\<close>

theory Rational_FPS_Solver
imports
  Complex_Main
  Pochhammer_Polynomials
  Partial_Fraction_Decomposition
  Factorizations
  "HOL-Computational_Algebra.Field_as_Ring"
begin

text \<open>
  We can determine the $k$-th coefficient of an FPS of the form $d/(1-cX)^n$, which is
  an important step in solving linear recurrences. The $k$-th coefficient of such an FPS is always
  of the form $p(k) c^k$ where $p$ is the following polynomial:
\<close>

definition inverse_irred_power_poly :: "'a :: field_char_0 \<Rightarrow> nat \<Rightarrow> 'a poly" where
  "inverse_irred_power_poly d n =
       Poly [(d * of_nat (stirling n (k+1))) / (fact (n - 1)). k \<leftarrow> [0..<n]]"

lemma one_minus_const_fps_X_neg_power'':
  fixes c :: "'a :: field_char_0"
  assumes n: "n > 0"
  shows "fps_const d / ((1 - fps_const (c :: 'a :: field_char_0) * fps_X) ^ n) =
           Abs_fps (\<lambda>k. poly (inverse_irred_power_poly d n) (of_nat k) * c^k)" (is "?lhs = ?rhs")
proof (rule fps_ext)
  include fps_notation
  fix k :: nat
  let ?p = "smult (d / (fact (n - 1))) (pcompose (pochhammer_poly (n - 1)) [:1,1:])"
  from n have "?lhs = fps_const d * inverse ((1 - fps_const c * fps_X) ^ n)"
    by (subst fps_divide_unit) auto
  also have "inverse ((1 - fps_const c * fps_X) ^ n) =
                 Abs_fps (\<lambda>k. of_nat ((n + k - 1) choose k) * c^k)"
    by (intro one_minus_const_fps_X_neg_power' n)
  also have "(fps_const d * \<dots>) $ k  = d * of_nat ((n + k - 1) choose k) * c^k" by simp
  also from n have "(n + k - 1 choose k) = (n + k - 1 choose (n - 1))"
    by (subst binomial_symmetric) simp_all
  also from n have "of_nat \<dots> = (pochhammer (of_nat k + 1) (n - 1) / fact (n - 1) :: 'a)"
    by (simp_all add: binomial_gbinomial gbinomial_pochhammer' of_nat_diff)
  also have "d * \<dots> = poly ?p (of_nat k)"
    by (simp add: divide_inverse eval_pochhammer_poly poly_pcompose add_ac)
  also {
    from assms have "pCons 0 (pcompose (pochhammer_poly (n-1)) [:1,1::'a:]) = pochhammer_poly n"
      by (subst pochhammer_poly_Suc' [symmetric]) simp
    also from assms have "\<dots> = pCons 0 (Poly [of_nat (stirling n (k+1)). k \<leftarrow> [0..<Suc n]])"
      unfolding pochhammer_poly_def
      by (auto simp add: poly_eq_iff nth_default_def coeff_pCons
               split: nat.split simp del: upt_Suc )
    finally have "pcompose (pochhammer_poly (n-1)) [:1,1::'a:] =
                      Poly [of_nat (stirling n (k+1)). k \<leftarrow> [0..<Suc n]]" by simp
  }
  also have "smult (d / fact (n - 1)) (Poly [of_nat (stirling n (k+1)). k \<leftarrow> [0..<Suc n]]) =
               inverse_irred_power_poly d n"
    by (auto simp: poly_eq_iff inverse_irred_power_poly_def nth_default_def)
  also have "poly \<dots> (of_nat k) * c ^ k = ?rhs $ k" by simp
  finally show "?lhs $ k = ?rhs $ k" .
qed

lemma inverse_irred_power_poly_code [code abstract]:
  "coeffs (inverse_irred_power_poly d n) =
    (if n = 0 \<or> d = 0 then [] else
     let e = d / (fact (n - 1))
     in  [e * of_nat x. x \<leftarrow> tl (stirling_row n)])"
proof (cases "n = 0 \<or> d = 0")
  case False
  define e where "e = d / (fact (n - 1))"
  from False have "coeffs (inverse_irred_power_poly d n) =
                     [e * of_nat (stirling n (k+1)). k \<leftarrow> [0..<n]]"
    by (auto simp: inverse_irred_power_poly_def Let_def divide_inverse mult_ac last_map
                   stirling_row_def map_tl [symmetric] tl_upt e_def no_trailing_unfold)
  also have "\<dots> = [e * of_nat x. x \<leftarrow> tl (stirling_row n)]"
    by (simp add: stirling_row_def map_tl [symmetric] o_def tl_upt
                  map_Suc_upt [symmetric] del: upt_Suc)
  finally show ?thesis using False by (simp add: Let_def e_def)
qed (auto simp: inverse_irred_power_poly_def)

lemma solve_rat_fps_aux:
  fixes p :: "'a :: {field_char_0,field_gcd} poly" and cs :: "('a \<times> nat) list"
  assumes distinct: "distinct (map fst cs)"
  assumes azs: "(a, zs) = poly_pfd_simple p cs"
  assumes nz: "0 \<notin> fst ` set cs"
  shows "fps_of_poly p / fps_of_poly (\<Prod>(c,n)\<leftarrow>cs. [:1,-c:]^Suc n) =
           Abs_fps (\<lambda>k. coeff a k + (\<Sum>i<length cs. poly (\<Sum>j\<le>snd (cs ! i).
                   (inverse_irred_power_poly (zs ! i ! j) (snd (cs ! i)+1 - j)))
               (of_nat k) * (fst (cs ! i)) ^ k))" (is "_ = ?rhs")
proof -
  interpret pfd_homomorphism "fps_of_poly :: 'a poly \<Rightarrow> 'a fps"
    by standard (auto simp: fps_of_poly_add fps_of_poly_mult)
  from distinct have distinct': "(a, b1) \<in> set cs \<Longrightarrow>
    (a, b2) \<in> set cs \<Longrightarrow> b1 = b2" for a b1 b2
    by (metis (no_types, hide_lams) Some_eq_map_of_iff image_set in_set_zipE insert_iff list.simps(15) map_of_Cons_code(2) map_of_SomeD nz snd_conv)
  from nz have nz': "(0, b) \<notin> set cs" for b
    by (auto simp add: image_iff)
  define n where "n = length cs"
  let ?g = "\<lambda>(c, n). [:1, - c:] ^ Suc n"
  have "inj_on ?g (set cs)"
  proof
    fix x y
    assume "x \<in> set cs" "y \<in> set cs" "?g x = ?g y"
    moreover obtain c1 n1 c2 n2 where [simp]: "x = (c1, n1)" "y = (c2, n2)"
      by (cases x, cases y)
    ultimately have in_cs: "(c1, n1) \<in> set cs"
      "(c2, n2) \<in> set cs"
      and eq: "[:1, - c1:] ^ Suc n1 = [:1, - c2:] ^ Suc n2"
      by simp_all
    with nz have [simp]: "c1 \<noteq> 0" "c2 \<noteq> 0"
      by (auto simp add: image_iff)
    have "Suc n1 = degree ([:1, - c1:] ^ Suc n1)"
      by (simp add: degree_power_eq del: power_Suc)
    also have "\<dots> = degree ([:1, - c2:] ^ Suc n2)"
      using eq by simp
    also have "\<dots> = Suc n2"
      by (simp add: degree_power_eq del: power_Suc)
    finally have "n1 = n2" by simp
    then have "0 = poly ([:1, - c1:] ^ Suc n1) (1 / c1)"
      by simp
    also have "\<dots> = poly ([:1, - c2:] ^ Suc n2) (1 / c1)"
      using eq by simp
    finally show "x = y" using \<open>n1 = n2\<close>
      by (auto simp: field_simps)
  qed
  with distinct have distinct': "distinct (map ?g cs)"
    by (simp add: distinct_map del: power_Suc)
  from nz' distinct have coprime: "pairwise coprime (?g ` set cs)"
    by (auto intro!: pairwise_imageI coprime_linear_poly' simp add: eq_key_imp_eq_value
      simp del: power_Suc)
  have [simp]: "length zs = n"
    using assms by (simp add: poly_pfd_simple_def n_def split: if_split_asm)
  have [simp]: "i < length cs \<Longrightarrow> length (zs!i) = snd (cs!i)+1" for i
   using assms by (simp add: poly_pfd_simple_def Let_def case_prod_unfold split: if_split_asm)

  let ?f = "\<lambda>(c, n). ([:1,-c:], n)"
  let ?cs' = "map ?f cs"
  have "fps_of_poly (fst (poly_pfd_simple p cs)) +
          (\<Sum>i<length ?cs'. \<Sum>j\<le>snd (?cs' ! i).
               from_decomp (map (map (\<lambda>c. [:c:])) (snd (poly_pfd_simple p cs)) ! i ! j)
                           (fst (?cs' ! i)) (snd (?cs' ! i)+1 - j)) =
          fps_of_poly p / fps_of_poly (\<Prod>(x, n)\<leftarrow>?cs'. x ^ Suc n)"
          (is "?A = ?B") using nz distinct' coprime
    by (intro partial_fraction_decomposition poly_pfd_simple)
       (force simp: o_def case_prod_unfold simp del: power_Suc)+
  note this [symmetric]
  also from azs [symmetric]
    have "?A = fps_of_poly a + (\<Sum>i<n. \<Sum>j\<le>snd (cs ! i). from_decomp
                  (map (map (\<lambda>c. [:c:])) zs ! i ! j) [:1,-fst (cs ! i):] (snd (cs ! i)+1 - j))"
      (is "_ = _ + ?S") by (simp add: case_prod_unfold Let_def n_def)
  also have "?S = (\<Sum>i<length cs. \<Sum>j\<le>snd (cs ! i). fps_const (zs ! i ! j) /
                      ((1 - fps_const (fst (cs!i))*fps_X) ^ (snd (cs!i)+1 - j)))"
    by (intro sum.cong refl)
       (auto simp: from_decomp_def map_nth n_def fps_of_poly_linear' fps_of_poly_simps
                    fps_const_neg [symmetric] mult_ac simp del: fps_const_neg)
  also have "\<dots> = (\<Sum>i<length cs. \<Sum>j\<le>snd (cs ! i) .
                      Abs_fps (\<lambda>k. poly (inverse_irred_power_poly (zs ! i ! j)
                          (snd (cs ! i)+1 - j)) (of_nat k) * (fst (cs ! i)) ^ k))"
    using nz by (intro sum.cong refl one_minus_const_fps_X_neg_power'') auto
  also have "fps_of_poly a + \<dots> = ?rhs"
    by (intro fps_ext) (simp_all add: sum_distrib_right fps_sum_nth poly_sum)
  finally show ?thesis by (simp add: o_def case_prod_unfold)
qed

definition solve_factored_ratfps ::
    "('a :: {field_char_0,field_gcd}) poly \<Rightarrow> ('a \<times> nat) list \<Rightarrow> 'a poly \<times> ('a poly \<times> 'a) list" where
  "solve_factored_ratfps p cs = (let n = length cs in case poly_pfd_simple p cs of (a, zs) \<Rightarrow>
      (a, zip_with (\<lambda>zs (c,n). ((\<Sum>(z,j) \<leftarrow> zip zs [0..<Suc n].
              inverse_irred_power_poly z (n + 1 - j)), c)) zs cs))"

lemma length_snd_poly_pfd_simple [simp]: "length (snd (poly_pfd_simple p cs)) = length cs"
  by (simp add: poly_pfd_simple_def)

lemma length_nth_snd_poly_pfd_simple [simp]:
  "i < length cs \<Longrightarrow> length (snd (poly_pfd_simple p cs) ! i) = snd (cs!i) + 1"
  by (auto simp: poly_pfd_simple_def case_prod_unfold Let_def)

lemma solve_factored_ratfps_roots:
  "map snd (snd (solve_factored_ratfps p cs)) = map fst cs"
  by (rule nth_equalityI)
     (simp_all add: solve_factored_ratfps_def poly_pfd_simple case_prod_unfold Let_def
                    zip_with_altdef o_def)

definition interp_ratfps_solution where
  "interp_ratfps_solution = (\<lambda>(p,cs) n. coeff p n + (\<Sum>(q,c)\<leftarrow>cs. poly q (of_nat n) * c ^ n))"

lemma solve_factored_ratfps:
  fixes p :: "'a :: {field_char_0,field_gcd} poly" and cs :: "('a \<times> nat) list"
  assumes distinct: "distinct (map fst cs)"
  assumes nz: "0 \<notin> fst ` set cs"
  shows "fps_of_poly p / fps_of_poly (\<Prod>(c,n)\<leftarrow>cs. [:1,-c:]^Suc n) =
           Abs_fps (interp_ratfps_solution (solve_factored_ratfps p cs))" (is "?lhs = ?rhs")
proof -
  obtain a zs where azs: "(a, zs) = solve_factored_ratfps p cs"
    using prod.exhaust by metis
  from azs have a: "a = fst (poly_pfd_simple p cs)"
    by (simp add: solve_factored_ratfps_def Let_def case_prod_unfold)
  define zs' where "zs' = snd (poly_pfd_simple p cs)"
  with a have azs': "(a, zs') = poly_pfd_simple p cs" by simp
  from azs have zs: "zs = snd (solve_factored_ratfps p cs)"
    by (auto simp add: snd_def split: prod.split)

  have "?lhs = Abs_fps (\<lambda>k. coeff a k + (\<Sum>i<length cs. poly (\<Sum>j\<le>snd (cs ! i).
                 inverse_irred_power_poly (zs' ! i ! j) (snd (cs ! i)+1 - j))
                 (of_nat k) * (fst (cs ! i)) ^ k))"
    by (rule solve_rat_fps_aux[OF distinct azs' nz])
  also from azs have "\<dots> = ?rhs" unfolding interp_ratfps_solution_def
    by (auto simp: a zs solve_factored_ratfps_def Let_def case_prod_unfold zip_altdef
                   zip_with_altdef' sum_list_sum_nth atLeast0LessThan zs'_def lessThan_Suc_atMost
             intro!: fps_ext sum.cong simp del: upt_Suc)
  finally show ?thesis .
qed

definition solve_factored_ratfps' where
  "solve_factored_ratfps' = (\<lambda>p (a,cs). solve_factored_ratfps (smult (inverse a) p) cs)"

lemma solve_factored_ratfps':
  assumes "is_alt_factorization_of fctrs q" "q \<noteq> 0"
  shows   "Abs_fps (interp_ratfps_solution (solve_factored_ratfps' p fctrs)) =
             fps_of_poly p / fps_of_poly q"
proof -
  from assms have q: "q = interp_alt_factorization fctrs"
    by (simp add: is_alt_factorization_of_def)
  from assms(2) have nz: "fst fctrs \<noteq> 0"
    by (subst (asm) q) (auto simp: interp_alt_factorization_def case_prod_unfold)
  note q
  also from nz have "coeff (interp_alt_factorization fctrs) 0 \<noteq> 0"
    by (auto simp: interp_alt_factorization_def case_prod_unfold coeff_0_prod_list
                   o_def coeff_0_power prod_list_zero_iff)
  finally have "coeff q 0 \<noteq> 0" .

  obtain a cs where fctrs: "fctrs = (a, cs)" by (cases fctrs) simp_all
  obtain b zs where sol: "solve_factored_ratfps' p fctrs = (b, zs)" using prod.exhaust by metis
  from assms have [simp]: "a \<noteq> 0"
    by (auto simp: is_alt_factorization_of_def interp_alt_factorization_def fctrs)

  have "fps_of_poly p / fps_of_poly (smult a (\<Prod>(c, n)\<leftarrow>cs. [:1, - c:] ^ Suc n)) =
          fps_of_poly p / (fps_const a * fps_of_poly (\<Prod>(c, n)\<leftarrow>cs. [:1, - c:] ^ Suc n))"
    by (simp_all add: fps_of_poly_smult case_prod_unfold del: power_Suc)
  also have "\<dots> = fps_of_poly p / fps_const a / fps_of_poly (\<Prod>(c, n)\<leftarrow>cs. [:1, - c:] ^ Suc n)"
    by (subst is_unit_div_mult2_eq)
       (auto simp: coeff_0_power coeff_0_prod_list prod_list_zero_iff)
  also have "fps_of_poly p / fps_const a = fps_of_poly (smult (inverse a) p)"
    by (simp add: fps_const_inverse fps_divide_unit)
  also from assms have "smult a (\<Prod>(c, n)\<leftarrow>cs. [:1, - c:] ^ Suc n) = q"
    by (simp add: is_alt_factorization_of_def interp_alt_factorization_def fctrs del: power_Suc)
  also have "fps_of_poly (smult (inverse a) p) /
                   fps_of_poly (\<Prod>(c, n)\<leftarrow>cs. [:1, - c:] ^ Suc n) =
               Abs_fps (interp_ratfps_solution (solve_factored_ratfps (smult (inverse a) p) cs))"
    (is "?lhs = _") using assms
    by (intro solve_factored_ratfps)
       (simp_all add: is_alt_factorization_of_def fctrs solve_factored_ratfps'_def)
  also have "\<dots> = Abs_fps (interp_ratfps_solution (solve_factored_ratfps' p fctrs))"
    by (simp add: solve_factored_ratfps'_def fctrs)
  finally show ?thesis ..
qed

lemma degree_Poly_eq:
  assumes "xs = [] \<or> last xs \<noteq> 0"
  shows   "degree (Poly xs) = length xs - 1"
proof -
  from assms consider "xs = []" | "xs \<noteq> []" "last xs \<noteq> 0" by blast
  thus ?thesis
  proof cases
    assume "last xs \<noteq> 0" "xs \<noteq> []"
    hence "no_trailing ((=) 0) xs" by (auto simp: no_trailing_unfold)
    thus ?thesis by (simp add: degree_eq_length_coeffs)
  qed auto
qed

lemma degree_Poly': "degree (Poly xs) \<le> length xs - 1"
  using length_strip_while_le[of "(=) 0" xs] by (simp add: degree_eq_length_coeffs)

lemma degree_inverse_irred_power_poly_le:
  "degree (inverse_irred_power_poly c n) \<le> n - 1"
  by (auto simp: inverse_irred_power_poly_def intro: order.trans[OF degree_Poly'])

lemma degree_inverse_irred_power_poly:
  assumes "c \<noteq> 0"
  shows   "degree (inverse_irred_power_poly c n) = n - 1"
  unfolding inverse_irred_power_poly_def using assms
  by (subst degree_Poly_eq) (auto simp: last_conv_nth)

lemma reflect_poly_0_iff [simp]: "reflect_poly p = 0 \<longleftrightarrow> p = 0"
  using coeff_0_reflect_poly_0_iff[of p] by fastforce

lemma degree_sum_list_le: "(\<And>p. p \<in> set ps \<Longrightarrow> degree p \<le> T) \<Longrightarrow> degree (sum_list ps) \<le> T"
  by (induction ps) (auto intro: degree_add_le)

theorem ratfps_closed_form_exists:
  fixes q :: "complex poly"
  assumes nz: "coeff q 0 \<noteq> 0"
  defines "q' \<equiv> reflect_poly q"
  obtains r rs
  where "\<And>n. fps_nth (fps_of_poly p / fps_of_poly q) n =
                coeff r n + (\<Sum>c | poly q' c = 0. poly (rs c) (of_nat n) * c ^ n)"
  and   "\<And>z. poly q' z = 0 \<Longrightarrow> degree (rs z) \<le> order z q' - 1"
proof -
  from assms have nz': "q \<noteq> 0" by auto
  from complex_alt_factorization_exists [OF nz]
  obtain fctrs where fctrs: "is_alt_factorization_of fctrs q" ..
  with nz have fctrs': "is_factorization_of fctrs q'" unfolding q'_def
    by (rule reflect_factorization')
  define r where "r = fst (solve_factored_ratfps' p fctrs)"
  define ts where "ts = snd (solve_factored_ratfps' p fctrs)"
  define rs where "rs = the \<circ> map_of (map (\<lambda>(x,y). (y,x)) ts)"

  from nz' have "q' \<noteq> 0" by (simp add: q'_def)
  hence roots: "{z. poly q' z = 0} = set (map fst (snd fctrs))"
    using is_factorization_of_roots [of "fst fctrs" "snd fctrs" q'] fctrs' by simp

  have rs: "rs c = r" if "(r, c) \<in> set ts" for c r
  proof -
    have "map_of (map (\<lambda>(x,y). (y, x)) (snd (solve_factored_ratfps' p fctrs))) c = Some r"
      using that fctrs
      by (intro map_of_is_SomeI)
         (force simp: o_def case_prod_unfold solve_factored_ratfps'_def ts_def
                      solve_factored_ratfps_roots is_alt_factorization_of_def)+
    thus ?thesis by (simp add: rs_def ts_def)
  qed

  have [simp]: "length ts = length (snd fctrs)"
    by (auto simp: ts_def solve_factored_ratfps'_def case_prod_unfold solve_factored_ratfps_def)

  {
    fix n :: nat
    have "fps_of_poly p / fps_of_poly q =
            Abs_fps (interp_ratfps_solution (solve_factored_ratfps' p fctrs))"
      using solve_factored_ratfps' [OF fctrs nz'] ..
    also have "fps_nth \<dots> n = interp_ratfps_solution (solve_factored_ratfps' p fctrs) n"
      by simp
    also have "\<dots> = coeff r n + (\<Sum>p\<leftarrow>snd (solve_factored_ratfps' p fctrs).
                                   poly (fst p) (of_nat n) * snd p ^ n)" (is "_ = _ + ?A")
      unfolding interp_ratfps_solution_def case_prod_unfold r_def by simp
    also have "?A = (\<Sum>p\<leftarrow>ts. poly (rs (snd p)) (of_nat n) * snd p ^ n)"
      by (intro arg_cong[OF map_cong] refl) (auto simp: rs ts_def)
    also have "\<dots> = (\<Sum>c\<leftarrow>map snd ts.
                       poly (rs c) (of_nat n) * c ^ n)" by (simp add: o_def)
    also have "map snd ts = map fst (snd fctrs)"
      unfolding solve_factored_ratfps'_def case_prod_unfold ts_def
      by (rule solve_factored_ratfps_roots)
    also have "(\<Sum>c\<leftarrow>\<dots>. poly (rs c) (of_nat n) * c ^ n) =
                 (\<Sum>c | poly q' c = 0. poly (rs c) (of_nat n) * c ^ n)" unfolding roots
      using fctrs by (intro sum_list_distinct_conv_sum_set) (auto simp: is_alt_factorization_of_def)
    finally have "fps_nth (fps_of_poly p / fps_of_poly q) n =
                    coeff r n + (\<Sum>c\<in>{z. poly q' z = 0}. poly (rs c) (of_nat n) * c ^ n)" .
  } moreover {
    fix z assume "poly q' z = 0"
    hence "z \<in> set (map fst (snd fctrs))" using roots by blast
    then obtain i where i: "i < length (snd fctrs)" and [simp]: "z = fst (snd fctrs ! i)"
      by (auto simp: set_conv_nth)
    from i have "(fst (ts ! i), snd (ts ! i)) \<in> set ts"
      by (auto simp: set_conv_nth)
    also from i have "snd (ts ! i) = z"
      by (simp add: ts_def solve_factored_ratfps'_def case_prod_unfold solve_factored_ratfps_def)
    finally have "rs z = fst (ts ! i)" by (intro rs) auto
    also have "\<dots> = (\<Sum>p\<leftarrow>zip (snd (poly_pfd_simple (smult (inverse (fst fctrs)) p) (snd fctrs)) ! i)
                       [0..<Suc (snd (snd fctrs ! i))].
                         inverse_irred_power_poly (fst p) (Suc (snd (snd fctrs ! i)) - snd p))"
      using i by (auto simp: ts_def solve_factored_ratfps'_def solve_factored_ratfps_def o_def
                     case_prod_unfold Let_def simp del: upt_Suc power_Suc)
    also have "degree \<dots> \<le> snd (snd fctrs ! i)"
      by (intro degree_sum_list_le)
         (auto intro!: order.trans [OF degree_inverse_irred_power_poly_le])
    also have "order z q' = Suc \<dots>"
      using nz' fctrs' i
      by (intro is_factorization_of_order[of q' "fst fctrs" "snd fctrs"]) (auto simp: q'_def)
    hence "snd (snd fctrs ! i) = order z q' - 1" by simp
    finally have "degree (rs z) \<le> \<dots>" .
  }
  ultimately show ?thesis
    using that[of r rs] by blast
qed

end