(*  Title:      HOL/Library/Permutations.thy
    Author:     Amine Chaieb, University of Cambridge
*)

section \<open>Permutations, both general and specifically on finite sets.\<close>

theory Permutations
imports Binomial Multiset Disjoint_Sets
begin

subsection \<open>Transpositions\<close>

lemma swap_id_idempotent [simp]:
  "Fun.swap a b id \<circ> Fun.swap a b id = id"
  by (rule ext, auto simp add: Fun.swap_def)

lemma inv_swap_id:
  "inv (Fun.swap a b id) = Fun.swap a b id"
  by (rule inv_unique_comp) simp_all

lemma swap_id_eq:
  "Fun.swap a b id x = (if x = a then b else if x = b then a else x)"
  by (simp add: Fun.swap_def)

lemma bij_inv_eq_iff: "bij p \<Longrightarrow> x = inv p y \<longleftrightarrow> p x = y"
  using surj_f_inv_f[of p] by (auto simp add: bij_def)

lemma bij_swap_comp:
  assumes bp: "bij p"
  shows "Fun.swap a b id \<circ> p = Fun.swap (inv p a) (inv p b) p"
  using surj_f_inv_f[OF bij_is_surj[OF bp]]
  by (simp add: fun_eq_iff Fun.swap_def bij_inv_eq_iff[OF bp])

lemma bij_swap_ompose_bij: "bij p \<Longrightarrow> bij (Fun.swap a b id \<circ> p)"
proof -
  assume H: "bij p"
  show ?thesis
    unfolding bij_swap_comp[OF H] bij_swap_iff
    using H .
qed

subsection \<open>Basic consequences of the definition\<close>

definition permutes  (infixr "permutes" 41)
  where "(p permutes S) \<longleftrightarrow> (\<forall>x. x \<notin> S \<longrightarrow> p x = x) \<and> (\<forall>y. \<exists>!x. p x = y)"

lemma permutes_in_image: "p permutes S \<Longrightarrow> p x \<in> S \<longleftrightarrow> x \<in> S"
  unfolding permutes_def by metis

lemma permutes_not_in:
  assumes "f permutes S" "x \<notin> S" shows "f x = x"
  using assms by (auto simp: permutes_def)

lemma permutes_image: "p permutes S \<Longrightarrow> p ` S = S"
  unfolding permutes_def
  apply (rule set_eqI)
  apply (simp add: image_iff)
  apply metis
  done

lemma permutes_inj: "p permutes S \<Longrightarrow> inj p"
  unfolding permutes_def inj_on_def by blast

lemma permutes_inj_on: "f permutes S \<Longrightarrow> inj_on f A"
  unfolding permutes_def inj_on_def by auto

lemma permutes_surj: "p permutes s \<Longrightarrow> surj p"
  unfolding permutes_def surj_def by metis

lemma permutes_bij: "p permutes s \<Longrightarrow> bij p"
unfolding bij_def by (metis permutes_inj permutes_surj)

lemma permutes_imp_bij: "p permutes S \<Longrightarrow> bij_betw p S S"
by (metis UNIV_I bij_betw_subset permutes_bij permutes_image subsetI)

lemma bij_imp_permutes: "bij_betw p S S \<Longrightarrow> (\<And>x. x \<notin> S \<Longrightarrow> p x = x) \<Longrightarrow> p permutes S"
  unfolding permutes_def bij_betw_def inj_on_def
  by auto (metis image_iff)+

lemma permutes_inv_o:
  assumes pS: "p permutes S"
  shows "p \<circ> inv p = id"
    and "inv p \<circ> p = id"
  using permutes_inj[OF pS] permutes_surj[OF pS]
  unfolding inj_iff[symmetric] surj_iff[symmetric] by blast+

lemma permutes_inverses:
  fixes p :: "'a \<Rightarrow> 'a"
  assumes pS: "p permutes S"
  shows "p (inv p x) = x"
    and "inv p (p x) = x"
  using permutes_inv_o[OF pS, unfolded fun_eq_iff o_def] by auto

lemma permutes_subset: "p permutes S \<Longrightarrow> S \<subseteq> T \<Longrightarrow> p permutes T"
  unfolding permutes_def by blast

lemma permutes_empty[simp]: "p permutes {} \<longleftrightarrow> p = id"
  unfolding fun_eq_iff permutes_def by simp metis

lemma permutes_sing[simp]: "p permutes {a} \<longleftrightarrow> p = id"
  unfolding fun_eq_iff permutes_def by simp metis

lemma permutes_univ: "p permutes UNIV \<longleftrightarrow> (\<forall>y. \<exists>!x. p x = y)"
  unfolding permutes_def by simp

lemma permutes_inv_eq: "p permutes S \<Longrightarrow> inv p y = x \<longleftrightarrow> p x = y"
  unfolding permutes_def inv_def
  apply auto
  apply (erule allE[where x=y])
  apply (erule allE[where x=y])
  apply (rule someI_ex)
  apply blast
  apply (rule some1_equality)
  apply blast
  apply blast
  done

lemma permutes_swap_id: "a \<in> S \<Longrightarrow> b \<in> S \<Longrightarrow> Fun.swap a b id permutes S"
  unfolding permutes_def Fun.swap_def fun_upd_def by auto metis

lemma permutes_superset: "p permutes S \<Longrightarrow> (\<forall>x \<in> S - T. p x = x) \<Longrightarrow> p permutes T"
  by (simp add: Ball_def permutes_def) metis

(* Next three lemmas contributed by Lukas Bulwahn *)
lemma permutes_bij_inv_into:
  fixes A :: "'a set" and B :: "'b set"
  assumes "p permutes A"
  assumes "bij_betw f A B"
  shows "(\<lambda>x. if x \<in> B then f (p (inv_into A f x)) else x) permutes B"
proof (rule bij_imp_permutes)
  have "bij_betw p A A" "bij_betw f A B" "bij_betw (inv_into A f) B A"
    using assms by (auto simp add: permutes_imp_bij bij_betw_inv_into)
  from this have "bij_betw (f o p o inv_into A f) B B" by (simp add: bij_betw_trans)
  from this show "bij_betw (\<lambda>x. if x \<in> B then f (p (inv_into A f x)) else x) B B"
    by (subst bij_betw_cong[where g="f o p o inv_into A f"]) auto
next
  fix x
  assume "x \<notin> B"
  from this show "(if x \<in> B then f (p (inv_into A f x)) else x) = x" by auto
qed

lemma permutes_image_mset:
  assumes "p permutes A"
  shows "image_mset p (mset_set A) = mset_set A"
using assms by (metis image_mset_mset_set bij_betw_imp_inj_on permutes_imp_bij permutes_image)

lemma permutes_implies_image_mset_eq:
  assumes "p permutes A" "\<And>x. x \<in> A \<Longrightarrow> f x = f' (p x)"
  shows "image_mset f' (mset_set A) = image_mset f (mset_set A)"
proof -
  have "f x = f' (p x)" if x: "x \<in># mset_set A" for x
    using assms(2)[of x] x by (cases "finite A") auto
  from this have "image_mset f (mset_set A) = image_mset (f' o p) (mset_set A)"
    using assms by (auto intro!: image_mset_cong)
  also have "\<dots> = image_mset f' (image_mset p (mset_set A))"
    by (simp add: image_mset.compositionality)
  also have "\<dots> = image_mset f' (mset_set A)"
  proof -
    from assms have "image_mset p (mset_set A) = mset_set A"
      using permutes_image_mset by blast
    from this show ?thesis by simp
  qed
  finally show ?thesis ..
qed

subsection \<open>Group properties\<close>

lemma permutes_id: "id permutes S"
  unfolding permutes_def by simp

lemma permutes_compose: "p permutes S \<Longrightarrow> q permutes S \<Longrightarrow> q \<circ> p permutes S"
  unfolding permutes_def o_def by metis

lemma permutes_inv:
  assumes pS: "p permutes S"
  shows "inv p permutes S"
  using pS unfolding permutes_def permutes_inv_eq[OF pS] by metis

lemma permutes_inv_inv:
  assumes pS: "p permutes S"
  shows "inv (inv p) = p"
  unfolding fun_eq_iff permutes_inv_eq[OF pS] permutes_inv_eq[OF permutes_inv[OF pS]]
  by blast

lemma permutes_invI:
  assumes perm: "p permutes S"
      and inv:  "\<And>x. x \<in> S \<Longrightarrow> p' (p x) = x"
      and outside: "\<And>x. x \<notin> S \<Longrightarrow> p' x = x"
  shows   "inv p = p'"
proof
  fix x show "inv p x = p' x"
  proof (cases "x \<in> S")
    assume [simp]: "x \<in> S"
    from assms have "p' x = p' (p (inv p x))" by (simp add: permutes_inverses)
    also from permutes_inv[OF perm]
      have "\<dots> = inv p x" by (subst inv) (simp_all add: permutes_in_image)
    finally show "inv p x = p' x" ..
  qed (insert permutes_inv[OF perm], simp_all add: outside permutes_not_in)
qed

lemma permutes_vimage: "f permutes A \<Longrightarrow> f -` A = A"
  by (simp add: bij_vimage_eq_inv_image permutes_bij permutes_image[OF permutes_inv])

subsection \<open>The number of permutations on a finite set\<close>

lemma permutes_insert_lemma:
  assumes pS: "p permutes (insert a S)"
  shows "Fun.swap a (p a) id \<circ> p permutes S"
  apply (rule permutes_superset[where S = "insert a S"])
  apply (rule permutes_compose[OF pS])
  apply (rule permutes_swap_id, simp)
  using permutes_in_image[OF pS, of a]
  apply simp
  apply (auto simp add: Ball_def Fun.swap_def)
  done

lemma permutes_insert: "{p. p permutes (insert a S)} =
  (\<lambda>(b,p). Fun.swap a b id \<circ> p) ` {(b,p). b \<in> insert a S \<and> p \<in> {p. p permutes S}}"
proof -
  {
    fix p
    {
      assume pS: "p permutes insert a S"
      let ?b = "p a"
      let ?q = "Fun.swap a (p a) id \<circ> p"
      have th0: "p = Fun.swap a ?b id \<circ> ?q"
        unfolding fun_eq_iff o_assoc by simp
      have th1: "?b \<in> insert a S"
        unfolding permutes_in_image[OF pS] by simp
      from permutes_insert_lemma[OF pS] th0 th1
      have "\<exists>b q. p = Fun.swap a b id \<circ> q \<and> b \<in> insert a S \<and> q permutes S" by blast
    }
    moreover
    {
      fix b q
      assume bq: "p = Fun.swap a b id \<circ> q" "b \<in> insert a S" "q permutes S"
      from permutes_subset[OF bq(3), of "insert a S"]
      have qS: "q permutes insert a S"
        by auto
      have aS: "a \<in> insert a S"
        by simp
      from bq(1) permutes_compose[OF qS permutes_swap_id[OF aS bq(2)]]
      have "p permutes insert a S"
        by simp
    }
    ultimately have "p permutes insert a S \<longleftrightarrow>
        (\<exists>b q. p = Fun.swap a b id \<circ> q \<and> b \<in> insert a S \<and> q permutes S)"
      by blast
  }
  then show ?thesis
    by auto
qed

lemma card_permutations:
  assumes Sn: "card S = n"
    and fS: "finite S"
  shows "card {p. p permutes S} = fact n"
  using fS Sn
proof (induct arbitrary: n)
  case empty
  then show ?case by simp
next
  case (insert x F)
  {
    fix n
    assume H0: "card (insert x F) = n"
    let ?xF = "{p. p permutes insert x F}"
    let ?pF = "{p. p permutes F}"
    let ?pF' = "{(b, p). b \<in> insert x F \<and> p \<in> ?pF}"
    let ?g = "(\<lambda>(b, p). Fun.swap x b id \<circ> p)"
    from permutes_insert[of x F]
    have xfgpF': "?xF = ?g ` ?pF'" .
    have Fs: "card F = n - 1"
      using \<open>x \<notin> F\<close> H0 \<open>finite F\<close> by auto
    from insert.hyps Fs have pFs: "card ?pF = fact (n - 1)"
      using \<open>finite F\<close> by auto
    then have "finite ?pF"
      by (auto intro: card_ge_0_finite)
    then have pF'f: "finite ?pF'"
      using H0 \<open>finite F\<close>
      apply (simp only: Collect_case_prod Collect_mem_eq)
      apply (rule finite_cartesian_product)
      apply simp_all
      done

    have ginj: "inj_on ?g ?pF'"
    proof -
      {
        fix b p c q
        assume bp: "(b,p) \<in> ?pF'"
        assume cq: "(c,q) \<in> ?pF'"
        assume eq: "?g (b,p) = ?g (c,q)"
        from bp cq have ths: "b \<in> insert x F" "c \<in> insert x F" "x \<in> insert x F"
          "p permutes F" "q permutes F"
          by auto
        from ths(4) \<open>x \<notin> F\<close> eq have "b = ?g (b,p) x"
          unfolding permutes_def
          by (auto simp add: Fun.swap_def fun_upd_def fun_eq_iff)
        also have "\<dots> = ?g (c,q) x"
          using ths(5) \<open>x \<notin> F\<close> eq
          by (auto simp add: swap_def fun_upd_def fun_eq_iff)
        also have "\<dots> = c"
          using ths(5) \<open>x \<notin> F\<close>
          unfolding permutes_def
          by (auto simp add: Fun.swap_def fun_upd_def fun_eq_iff)
        finally have bc: "b = c" .
        then have "Fun.swap x b id = Fun.swap x c id"
          by simp
        with eq have "Fun.swap x b id \<circ> p = Fun.swap x b id \<circ> q"
          by simp
        then have "Fun.swap x b id \<circ> (Fun.swap x b id \<circ> p) =
          Fun.swap x b id \<circ> (Fun.swap x b id \<circ> q)"
          by simp
        then have "p = q"
          by (simp add: o_assoc)
        with bc have "(b, p) = (c, q)"
          by simp
      }
      then show ?thesis
        unfolding inj_on_def by blast
    qed
    from \<open>x \<notin> F\<close> H0 have n0: "n \<noteq> 0"
      using \<open>finite F\<close> by auto
    then have "\<exists>m. n = Suc m"
      by presburger
    then obtain m where n[simp]: "n = Suc m"
      by blast
    from pFs H0 have xFc: "card ?xF = fact n"
      unfolding xfgpF' card_image[OF ginj]
      using \<open>finite F\<close> \<open>finite ?pF\<close>
      apply (simp only: Collect_case_prod Collect_mem_eq card_cartesian_product)
      apply simp
      done
    from finite_imageI[OF pF'f, of ?g] have xFf: "finite ?xF"
      unfolding xfgpF' by simp
    have "card ?xF = fact n"
      using xFf xFc unfolding xFf by blast
  }
  then show ?case
    using insert by simp
qed

lemma finite_permutations:
  assumes fS: "finite S"
  shows "finite {p. p permutes S}"
  using card_permutations[OF refl fS]
  by (auto intro: card_ge_0_finite)

subsection \<open>Permutations of index set for iterated operations\<close>

lemma (in comm_monoid_set) permute:
  assumes "p permutes S"
  shows "F g S = F (g \<circ> p) S"
proof -
  from \<open>p permutes S\<close> have "inj p"
    by (rule permutes_inj)
  then have "inj_on p S"
    by (auto intro: subset_inj_on)
  then have "F g (p ` S) = F (g \<circ> p) S"
    by (rule reindex)
  moreover from \<open>p permutes S\<close> have "p ` S = S"
    by (rule permutes_image)
  ultimately show ?thesis
    by simp
qed

subsection \<open>Various combinations of transpositions with 2, 1 and 0 common elements\<close>

lemma swap_id_common:" a \<noteq> c \<Longrightarrow> b \<noteq> c \<Longrightarrow>
  Fun.swap a b id \<circ> Fun.swap a c id = Fun.swap b c id \<circ> Fun.swap a b id"
  by (simp add: fun_eq_iff Fun.swap_def)

lemma swap_id_common': "a \<noteq> b \<Longrightarrow> a \<noteq> c \<Longrightarrow>
  Fun.swap a c id \<circ> Fun.swap b c id = Fun.swap b c id \<circ> Fun.swap a b id"
  by (simp add: fun_eq_iff Fun.swap_def)

lemma swap_id_independent: "a \<noteq> c \<Longrightarrow> a \<noteq> d \<Longrightarrow> b \<noteq> c \<Longrightarrow> b \<noteq> d \<Longrightarrow>
  Fun.swap a b id \<circ> Fun.swap c d id = Fun.swap c d id \<circ> Fun.swap a b id"
  by (simp add: fun_eq_iff Fun.swap_def)

subsection \<open>Permutations as transposition sequences\<close>

inductive swapidseq :: "nat \<Rightarrow> ('a \<Rightarrow> 'a) \<Rightarrow> bool"
where
  id[simp]: "swapidseq 0 id"
| comp_Suc: "swapidseq n p \<Longrightarrow> a \<noteq> b \<Longrightarrow> swapidseq (Suc n) (Fun.swap a b id \<circ> p)"

declare id[unfolded id_def, simp]

definition "permutation p \<longleftrightarrow> (\<exists>n. swapidseq n p)"

subsection \<open>Some closure properties of the set of permutations, with lengths\<close>

lemma permutation_id[simp]: "permutation id"
  unfolding permutation_def by (rule exI[where x=0]) simp

declare permutation_id[unfolded id_def, simp]

lemma swapidseq_swap: "swapidseq (if a = b then 0 else 1) (Fun.swap a b id)"
  apply clarsimp
  using comp_Suc[of 0 id a b]
  apply simp
  done

lemma permutation_swap_id: "permutation (Fun.swap a b id)"
  apply (cases "a = b")
  apply simp_all
  unfolding permutation_def
  using swapidseq_swap[of a b]
  apply blast
  done

lemma swapidseq_comp_add: "swapidseq n p \<Longrightarrow> swapidseq m q \<Longrightarrow> swapidseq (n + m) (p \<circ> q)"
proof (induct n p arbitrary: m q rule: swapidseq.induct)
  case (id m q)
  then show ?case by simp
next
  case (comp_Suc n p a b m q)
  have th: "Suc n + m = Suc (n + m)"
    by arith
  show ?case
    unfolding th comp_assoc
    apply (rule swapidseq.comp_Suc)
    using comp_Suc.hyps(2)[OF comp_Suc.prems] comp_Suc.hyps(3)
    apply blast+
    done
qed

lemma permutation_compose: "permutation p \<Longrightarrow> permutation q \<Longrightarrow> permutation (p \<circ> q)"
  unfolding permutation_def using swapidseq_comp_add[of _ p _ q] by metis

lemma swapidseq_endswap: "swapidseq n p \<Longrightarrow> a \<noteq> b \<Longrightarrow> swapidseq (Suc n) (p \<circ> Fun.swap a b id)"
  apply (induct n p rule: swapidseq.induct)
  using swapidseq_swap[of a b]
  apply (auto simp add: comp_assoc intro: swapidseq.comp_Suc)
  done

lemma swapidseq_inverse_exists: "swapidseq n p \<Longrightarrow> \<exists>q. swapidseq n q \<and> p \<circ> q = id \<and> q \<circ> p = id"
proof (induct n p rule: swapidseq.induct)
  case id
  then show ?case
    by (rule exI[where x=id]) simp
next
  case (comp_Suc n p a b)
  from comp_Suc.hyps obtain q where q: "swapidseq n q" "p \<circ> q = id" "q \<circ> p = id"
    by blast
  let ?q = "q \<circ> Fun.swap a b id"
  note H = comp_Suc.hyps
  from swapidseq_swap[of a b] H(3) have th0: "swapidseq 1 (Fun.swap a b id)"
    by simp
  from swapidseq_comp_add[OF q(1) th0] have th1: "swapidseq (Suc n) ?q"
    by simp
  have "Fun.swap a b id \<circ> p \<circ> ?q = Fun.swap a b id \<circ> (p \<circ> q) \<circ> Fun.swap a b id"
    by (simp add: o_assoc)
  also have "\<dots> = id"
    by (simp add: q(2))
  finally have th2: "Fun.swap a b id \<circ> p \<circ> ?q = id" .
  have "?q \<circ> (Fun.swap a b id \<circ> p) = q \<circ> (Fun.swap a b id \<circ> Fun.swap a b id) \<circ> p"
    by (simp only: o_assoc)
  then have "?q \<circ> (Fun.swap a b id \<circ> p) = id"
    by (simp add: q(3))
  with th1 th2 show ?case
    by blast
qed

lemma swapidseq_inverse:
  assumes H: "swapidseq n p"
  shows "swapidseq n (inv p)"
  using swapidseq_inverse_exists[OF H] inv_unique_comp[of p] by auto

lemma permutation_inverse: "permutation p \<Longrightarrow> permutation (inv p)"
  using permutation_def swapidseq_inverse by blast

subsection \<open>The identity map only has even transposition sequences\<close>

lemma symmetry_lemma:
  assumes "\<And>a b c d. P a b c d \<Longrightarrow> P a b d c"
    and "\<And>a b c d. a \<noteq> b \<Longrightarrow> c \<noteq> d \<Longrightarrow>
      a = c \<and> b = d \<or> a = c \<and> b \<noteq> d \<or> a \<noteq> c \<and> b = d \<or> a \<noteq> c \<and> a \<noteq> d \<and> b \<noteq> c \<and> b \<noteq> d \<Longrightarrow>
      P a b c d"
  shows "\<And>a b c d. a \<noteq> b \<longrightarrow> c \<noteq> d \<longrightarrow>  P a b c d"
  using assms by metis

lemma swap_general: "a \<noteq> b \<Longrightarrow> c \<noteq> d \<Longrightarrow>
  Fun.swap a b id \<circ> Fun.swap c d id = id \<or>
  (\<exists>x y z. x \<noteq> a \<and> y \<noteq> a \<and> z \<noteq> a \<and> x \<noteq> y \<and>
    Fun.swap a b id \<circ> Fun.swap c d id = Fun.swap x y id \<circ> Fun.swap a z id)"
proof -
  assume H: "a \<noteq> b" "c \<noteq> d"
  have "a \<noteq> b \<longrightarrow> c \<noteq> d \<longrightarrow>
    (Fun.swap a b id \<circ> Fun.swap c d id = id \<or>
      (\<exists>x y z. x \<noteq> a \<and> y \<noteq> a \<and> z \<noteq> a \<and> x \<noteq> y \<and>
        Fun.swap a b id \<circ> Fun.swap c d id = Fun.swap x y id \<circ> Fun.swap a z id))"
    apply (rule symmetry_lemma[where a=a and b=b and c=c and d=d])
    apply (simp_all only: swap_commute)
    apply (case_tac "a = c \<and> b = d")
    apply (clarsimp simp only: swap_commute swap_id_idempotent)
    apply (case_tac "a = c \<and> b \<noteq> d")
    apply (rule disjI2)
    apply (rule_tac x="b" in exI)
    apply (rule_tac x="d" in exI)
    apply (rule_tac x="b" in exI)
    apply (clarsimp simp add: fun_eq_iff Fun.swap_def)
    apply (case_tac "a \<noteq> c \<and> b = d")
    apply (rule disjI2)
    apply (rule_tac x="c" in exI)
    apply (rule_tac x="d" in exI)
    apply (rule_tac x="c" in exI)
    apply (clarsimp simp add: fun_eq_iff Fun.swap_def)
    apply (rule disjI2)
    apply (rule_tac x="c" in exI)
    apply (rule_tac x="d" in exI)
    apply (rule_tac x="b" in exI)
    apply (clarsimp simp add: fun_eq_iff Fun.swap_def)
    done
  with H show ?thesis by metis
qed

lemma swapidseq_id_iff[simp]: "swapidseq 0 p \<longleftrightarrow> p = id"
  using swapidseq.cases[of 0 p "p = id"]
  by auto

lemma swapidseq_cases: "swapidseq n p \<longleftrightarrow>
  n = 0 \<and> p = id \<or> (\<exists>a b q m. n = Suc m \<and> p = Fun.swap a b id \<circ> q \<and> swapidseq m q \<and> a \<noteq> b)"
  apply (rule iffI)
  apply (erule swapidseq.cases[of n p])
  apply simp
  apply (rule disjI2)
  apply (rule_tac x= "a" in exI)
  apply (rule_tac x= "b" in exI)
  apply (rule_tac x= "pa" in exI)
  apply (rule_tac x= "na" in exI)
  apply simp
  apply auto
  apply (rule comp_Suc, simp_all)
  done

lemma fixing_swapidseq_decrease:
  assumes spn: "swapidseq n p"
    and ab: "a \<noteq> b"
    and pa: "(Fun.swap a b id \<circ> p) a = a"
  shows "n \<noteq> 0 \<and> swapidseq (n - 1) (Fun.swap a b id \<circ> p)"
  using spn ab pa
proof (induct n arbitrary: p a b)
  case 0
  then show ?case
    by (auto simp add: Fun.swap_def fun_upd_def)
next
  case (Suc n p a b)
  from Suc.prems(1) swapidseq_cases[of "Suc n" p]
  obtain c d q m where
    cdqm: "Suc n = Suc m" "p = Fun.swap c d id \<circ> q" "swapidseq m q" "c \<noteq> d" "n = m"
    by auto
  {
    assume H: "Fun.swap a b id \<circ> Fun.swap c d id = id"
    have ?case by (simp only: cdqm o_assoc H) (simp add: cdqm)
  }
  moreover
  {
    fix x y z
    assume H: "x \<noteq> a" "y \<noteq> a" "z \<noteq> a" "x \<noteq> y"
      "Fun.swap a b id \<circ> Fun.swap c d id = Fun.swap x y id \<circ> Fun.swap a z id"
    from H have az: "a \<noteq> z"
      by simp

    {
      fix h
      have "(Fun.swap x y id \<circ> h) a = a \<longleftrightarrow> h a = a"
        using H by (simp add: Fun.swap_def)
    }
    note th3 = this
    from cdqm(2) have "Fun.swap a b id \<circ> p = Fun.swap a b id \<circ> (Fun.swap c d id \<circ> q)"
      by simp
    then have "Fun.swap a b id \<circ> p = Fun.swap x y id \<circ> (Fun.swap a z id \<circ> q)"
      by (simp add: o_assoc H)
    then have "(Fun.swap a b id \<circ> p) a = (Fun.swap x y id \<circ> (Fun.swap a z id \<circ> q)) a"
      by simp
    then have "(Fun.swap x y id \<circ> (Fun.swap a z id \<circ> q)) a = a"
      unfolding Suc by metis
    then have th1: "(Fun.swap a z id \<circ> q) a = a"
      unfolding th3 .
    from Suc.hyps[OF cdqm(3)[ unfolded cdqm(5)[symmetric]] az th1]
    have th2: "swapidseq (n - 1) (Fun.swap a z id \<circ> q)" "n \<noteq> 0"
      by blast+
    have th: "Suc n - 1 = Suc (n - 1)"
      using th2(2) by auto
    have ?case
      unfolding cdqm(2) H o_assoc th
      apply (simp only: Suc_not_Zero simp_thms comp_assoc)
      apply (rule comp_Suc)
      using th2 H
      apply blast+
      done
  }
  ultimately show ?case
    using swap_general[OF Suc.prems(2) cdqm(4)] by metis
qed

lemma swapidseq_identity_even:
  assumes "swapidseq n (id :: 'a \<Rightarrow> 'a)"
  shows "even n"
  using \<open>swapidseq n id\<close>
proof (induct n rule: nat_less_induct)
  fix n
  assume H: "\<forall>m<n. swapidseq m (id::'a \<Rightarrow> 'a) \<longrightarrow> even m" "swapidseq n (id :: 'a \<Rightarrow> 'a)"
  {
    assume "n = 0"
    then have "even n" by presburger
  }
  moreover
  {
    fix a b :: 'a and q m
    assume h: "n = Suc m" "(id :: 'a \<Rightarrow> 'a) = Fun.swap a b id \<circ> q" "swapidseq m q" "a \<noteq> b"
    from fixing_swapidseq_decrease[OF h(3,4), unfolded h(2)[symmetric]]
    have m: "m \<noteq> 0" "swapidseq (m - 1) (id :: 'a \<Rightarrow> 'a)"
      by auto
    from h m have mn: "m - 1 < n"
      by arith
    from H(1)[rule_format, OF mn m(2)] h(1) m(1) have "even n"
      by presburger
  }
  ultimately show "even n"
    using H(2)[unfolded swapidseq_cases[of n id]] by auto
qed

subsection \<open>Therefore we have a welldefined notion of parity\<close>

definition "evenperm p = even (SOME n. swapidseq n p)"

lemma swapidseq_even_even:
  assumes m: "swapidseq m p"
    and n: "swapidseq n p"
  shows "even m \<longleftrightarrow> even n"
proof -
  from swapidseq_inverse_exists[OF n]
  obtain q where q: "swapidseq n q" "p \<circ> q = id" "q \<circ> p = id"
    by blast
  from swapidseq_identity_even[OF swapidseq_comp_add[OF m q(1), unfolded q]]
  show ?thesis
    by arith
qed

lemma evenperm_unique:
  assumes p: "swapidseq n p"
    and n:"even n = b"
  shows "evenperm p = b"
  unfolding n[symmetric] evenperm_def
  apply (rule swapidseq_even_even[where p = p])
  apply (rule someI[where x = n])
  using p
  apply blast+
  done

subsection \<open>And it has the expected composition properties\<close>

lemma evenperm_id[simp]: "evenperm id = True"
  by (rule evenperm_unique[where n = 0]) simp_all

lemma evenperm_swap: "evenperm (Fun.swap a b id) = (a = b)"
  by (rule evenperm_unique[where n="if a = b then 0 else 1"]) (simp_all add: swapidseq_swap)

lemma evenperm_comp:
  assumes p: "permutation p"
    and q:"permutation q"
  shows "evenperm (p \<circ> q) = (evenperm p = evenperm q)"
proof -
  from p q obtain n m where n: "swapidseq n p" and m: "swapidseq m q"
    unfolding permutation_def by blast
  note nm =  swapidseq_comp_add[OF n m]
  have th: "even (n + m) = (even n \<longleftrightarrow> even m)"
    by arith
  from evenperm_unique[OF n refl] evenperm_unique[OF m refl]
    evenperm_unique[OF nm th]
  show ?thesis
    by blast
qed

lemma evenperm_inv:
  assumes p: "permutation p"
  shows "evenperm (inv p) = evenperm p"
proof -
  from p obtain n where n: "swapidseq n p"
    unfolding permutation_def by blast
  from evenperm_unique[OF swapidseq_inverse[OF n] evenperm_unique[OF n refl, symmetric]]
  show ?thesis .
qed

subsection \<open>A more abstract characterization of permutations\<close>

lemma bij_iff: "bij f \<longleftrightarrow> (\<forall>x. \<exists>!y. f y = x)"
  unfolding bij_def inj_on_def surj_def
  apply auto
  apply metis
  apply metis
  done

lemma permutation_bijective:
  assumes p: "permutation p"
  shows "bij p"
proof -
  from p obtain n where n: "swapidseq n p"
    unfolding permutation_def by blast
  from swapidseq_inverse_exists[OF n]
  obtain q where q: "swapidseq n q" "p \<circ> q = id" "q \<circ> p = id"
    by blast
  then show ?thesis unfolding bij_iff
    apply (auto simp add: fun_eq_iff)
    apply metis
    done
qed

lemma permutation_finite_support:
  assumes p: "permutation p"
  shows "finite {x. p x \<noteq> x}"
proof -
  from p obtain n where n: "swapidseq n p"
    unfolding permutation_def by blast
  from n show ?thesis
  proof (induct n p rule: swapidseq.induct)
    case id
    then show ?case by simp
  next
    case (comp_Suc n p a b)
    let ?S = "insert a (insert b {x. p x \<noteq> x})"
    from comp_Suc.hyps(2) have fS: "finite ?S"
      by simp
    from \<open>a \<noteq> b\<close> have th: "{x. (Fun.swap a b id \<circ> p) x \<noteq> x} \<subseteq> ?S"
      by (auto simp add: Fun.swap_def)
    from finite_subset[OF th fS] show ?case  .
  qed
qed

lemma permutation_lemma:
  assumes fS: "finite S"
    and p: "bij p"
    and pS: "\<forall>x. x\<notin> S \<longrightarrow> p x = x"
  shows "permutation p"
  using fS p pS
proof (induct S arbitrary: p rule: finite_induct)
  case (empty p)
  then show ?case by simp
next
  case (insert a F p)
  let ?r = "Fun.swap a (p a) id \<circ> p"
  let ?q = "Fun.swap a (p a) id \<circ> ?r"
  have raa: "?r a = a"
    by (simp add: Fun.swap_def)
  from bij_swap_ompose_bij[OF insert(4)]
  have br: "bij ?r"  .

  from insert raa have th: "\<forall>x. x \<notin> F \<longrightarrow> ?r x = x"
    apply (clarsimp simp add: Fun.swap_def)
    apply (erule_tac x="x" in allE)
    apply auto
    unfolding bij_iff
    apply metis
    done
  from insert(3)[OF br th]
  have rp: "permutation ?r" .
  have "permutation ?q"
    by (simp add: permutation_compose permutation_swap_id rp)
  then show ?case
    by (simp add: o_assoc)
qed

lemma permutation: "permutation p \<longleftrightarrow> bij p \<and> finite {x. p x \<noteq> x}"
  (is "?lhs \<longleftrightarrow> ?b \<and> ?f")
proof
  assume p: ?lhs
  from p permutation_bijective permutation_finite_support show "?b \<and> ?f"
    by auto
next
  assume "?b \<and> ?f"
  then have "?f" "?b" by blast+
  from permutation_lemma[OF this] show ?lhs
    by blast
qed

lemma permutation_inverse_works:
  assumes p: "permutation p"
  shows "inv p \<circ> p = id"
    and "p \<circ> inv p = id"
  using permutation_bijective [OF p]
  unfolding bij_def inj_iff surj_iff by auto

lemma permutation_inverse_compose:
  assumes p: "permutation p"
    and q: "permutation q"
  shows "inv (p \<circ> q) = inv q \<circ> inv p"
proof -
  note ps = permutation_inverse_works[OF p]
  note qs = permutation_inverse_works[OF q]
  have "p \<circ> q \<circ> (inv q \<circ> inv p) = p \<circ> (q \<circ> inv q) \<circ> inv p"
    by (simp add: o_assoc)
  also have "\<dots> = id"
    by (simp add: ps qs)
  finally have th0: "p \<circ> q \<circ> (inv q \<circ> inv p) = id" .
  have "inv q \<circ> inv p \<circ> (p \<circ> q) = inv q \<circ> (inv p \<circ> p) \<circ> q"
    by (simp add: o_assoc)
  also have "\<dots> = id"
    by (simp add: ps qs)
  finally have th1: "inv q \<circ> inv p \<circ> (p \<circ> q) = id" .
  from inv_unique_comp[OF th0 th1] show ?thesis .
qed

subsection \<open>Relation to "permutes"\<close>

lemma permutation_permutes: "permutation p \<longleftrightarrow> (\<exists>S. finite S \<and> p permutes S)"
  unfolding permutation permutes_def bij_iff[symmetric]
  apply (rule iffI, clarify)
  apply (rule exI[where x="{x. p x \<noteq> x}"])
  apply simp
  apply clarsimp
  apply (rule_tac B="S" in finite_subset)
  apply auto
  done

subsection \<open>Hence a sort of induction principle composing by swaps\<close>

lemma permutes_induct: "finite S \<Longrightarrow> P id \<Longrightarrow>
  (\<And> a b p. a \<in> S \<Longrightarrow> b \<in> S \<Longrightarrow> P p \<Longrightarrow> P p \<Longrightarrow> permutation p \<Longrightarrow> P (Fun.swap a b id \<circ> p)) \<Longrightarrow>
  (\<And>p. p permutes S \<Longrightarrow> P p)"
proof (induct S rule: finite_induct)
  case empty
  then show ?case by auto
next
  case (insert x F p)
  let ?r = "Fun.swap x (p x) id \<circ> p"
  let ?q = "Fun.swap x (p x) id \<circ> ?r"
  have qp: "?q = p"
    by (simp add: o_assoc)
  from permutes_insert_lemma[OF insert.prems(3)] insert have Pr: "P ?r"
    by blast
  from permutes_in_image[OF insert.prems(3), of x]
  have pxF: "p x \<in> insert x F"
    by simp
  have xF: "x \<in> insert x F"
    by simp
  have rp: "permutation ?r"
    unfolding permutation_permutes using insert.hyps(1)
      permutes_insert_lemma[OF insert.prems(3)]
    by blast
  from insert.prems(2)[OF xF pxF Pr Pr rp]
  show ?case
    unfolding qp .
qed

subsection \<open>Sign of a permutation as a real number\<close>

definition "sign p = (if evenperm p then (1::int) else -1)"

lemma sign_nz: "sign p \<noteq> 0"
  by (simp add: sign_def)

lemma sign_id: "sign id = 1"
  by (simp add: sign_def)

lemma sign_inverse: "permutation p \<Longrightarrow> sign (inv p) = sign p"
  by (simp add: sign_def evenperm_inv)

lemma sign_compose: "permutation p \<Longrightarrow> permutation q \<Longrightarrow> sign (p \<circ> q) = sign p * sign q"
  by (simp add: sign_def evenperm_comp)

lemma sign_swap_id: "sign (Fun.swap a b id) = (if a = b then 1 else -1)"
  by (simp add: sign_def evenperm_swap)

lemma sign_idempotent: "sign p * sign p = 1"
  by (simp add: sign_def)

subsection \<open>Permuting a list\<close>

text \<open>This function permutes a list by applying a permutation to the indices.\<close>

definition permute_list :: "(nat \<Rightarrow> nat) \<Rightarrow> 'a list \<Rightarrow> 'a list" where
  "permute_list f xs = map (\<lambda>i. xs ! (f i)) [0..<length xs]"

lemma permute_list_map:
  assumes "f permutes {..<length xs}"
  shows   "permute_list f (map g xs) = map g (permute_list f xs)"
  using permutes_in_image[OF assms] by (auto simp: permute_list_def)

lemma permute_list_nth:
  assumes "f permutes {..<length xs}" "i < length xs"
  shows   "permute_list f xs ! i = xs ! f i"
  using permutes_in_image[OF assms(1)] assms(2)
  by (simp add: permute_list_def)

lemma permute_list_Nil [simp]: "permute_list f [] = []"
  by (simp add: permute_list_def)

lemma length_permute_list [simp]: "length (permute_list f xs) = length xs"
  by (simp add: permute_list_def)

lemma permute_list_compose:
  assumes "g permutes {..<length xs}"
  shows   "permute_list (f \<circ> g) xs = permute_list g (permute_list f xs)"
  using assms[THEN permutes_in_image] by (auto simp add: permute_list_def)

lemma permute_list_ident [simp]: "permute_list (\<lambda>x. x) xs = xs"
  by (simp add: permute_list_def map_nth)

lemma permute_list_id [simp]: "permute_list id xs = xs"
  by (simp add: id_def)

lemma mset_permute_list [simp]:
  assumes "f permutes {..<length (xs :: 'a list)}"
  shows   "mset (permute_list f xs) = mset xs"
proof (rule multiset_eqI)
  fix y :: 'a
  from assms have [simp]: "f x < length xs \<longleftrightarrow> x < length xs" for x
    using permutes_in_image[OF assms] by auto
  have "count (mset (permute_list f xs)) y =
          card ((\<lambda>i. xs ! f i) -` {y} \<inter> {..<length xs})"
    by (simp add: permute_list_def mset_map count_image_mset atLeast0LessThan)
  also have "(\<lambda>i. xs ! f i) -` {y} \<inter> {..<length xs} = f -` {i. i < length xs \<and> y = xs ! i}"
    by auto
  also from assms have "card \<dots> = card {i. i < length xs \<and> y = xs ! i}"
    by (intro card_vimage_inj) (auto simp: permutes_inj permutes_surj)
  also have "\<dots> = count (mset xs) y" by (simp add: count_mset length_filter_conv_card)
  finally show "count (mset (permute_list f xs)) y = count (mset xs) y" by simp
qed

lemma set_permute_list [simp]:
  assumes "f permutes {..<length xs}"
  shows   "set (permute_list f xs) = set xs"
  by (rule mset_eq_setD[OF mset_permute_list]) fact

lemma distinct_permute_list [simp]:
  assumes "f permutes {..<length xs}"
  shows   "distinct (permute_list f xs) = distinct xs"
  by (simp add: distinct_count_atmost_1 assms)

lemma permute_list_zip:
  assumes "f permutes A" "A = {..<length xs}"
  assumes [simp]: "length xs = length ys"
  shows   "permute_list f (zip xs ys) = zip (permute_list f xs) (permute_list f ys)"
proof -
  from permutes_in_image[OF assms(1)] assms(2)
    have [simp]: "f i < length ys \<longleftrightarrow> i < length ys" for i by simp
  have "permute_list f (zip xs ys) = map (\<lambda>i. zip xs ys ! f i) [0..<length ys]"
    by (simp_all add: permute_list_def zip_map_map)
  also have "\<dots> = map (\<lambda>(x, y). (xs ! f x, ys ! f y)) (zip [0..<length ys] [0..<length ys])"
    by (intro nth_equalityI) simp_all
  also have "\<dots> = zip (permute_list f xs) (permute_list f ys)"
    by (simp_all add: permute_list_def zip_map_map)
  finally show ?thesis .
qed

lemma map_of_permute:
  assumes "\<sigma> permutes fst ` set xs"
  shows   "map_of xs \<circ> \<sigma> = map_of (map (\<lambda>(x,y). (inv \<sigma> x, y)) xs)" (is "_ = map_of (map ?f _)")
proof
  fix x
  from assms have "inj \<sigma>" "surj \<sigma>" by (simp_all add: permutes_inj permutes_surj)
  thus "(map_of xs \<circ> \<sigma>) x = map_of (map ?f xs) x"
    by (induction xs) (auto simp: inv_f_f surj_f_inv_f)
qed

subsection \<open>More lemmas about permutations\<close>

text \<open>
  The following few lemmas were contributed by Lukas Bulwahn.
\<close>

lemma count_image_mset_eq_card_vimage:
  assumes "finite A"
  shows "count (image_mset f (mset_set A)) b = card {a \<in> A. f a = b}"
  using assms
proof (induct A)
  case empty
  show ?case by simp
next
  case (insert x F)
  show ?case
  proof cases
    assume "f x = b"
    from this have "count (image_mset f (mset_set (insert x F))) b = Suc (card {a \<in> F. f a = f x})"
      using insert.hyps by auto
    also have "\<dots> = card (insert x {a \<in> F. f a = f x})"
      using insert.hyps(1,2) by simp
    also have "card (insert x {a \<in> F. f a = f x}) = card {a \<in> insert x F. f a = b}"
      using \<open>f x = b\<close> by (auto intro: arg_cong[where f="card"])
    finally show ?thesis using insert by auto
  next
    assume A: "f x \<noteq> b"
    hence "{a \<in> F. f a = b} = {a \<in> insert x F. f a = b}" by auto
    with insert A show ?thesis by simp
  qed
qed

(* Prove image_mset_eq_implies_permutes *)
lemma image_mset_eq_implies_permutes:
  fixes f :: "'a \<Rightarrow> 'b"
  assumes "finite A"
  assumes mset_eq: "image_mset f (mset_set A) = image_mset f' (mset_set A)"
  obtains p where "p permutes A" and "\<forall>x\<in>A. f x = f' (p x)"
proof -
  from \<open>finite A\<close> have [simp]: "finite {a \<in> A. f a = (b::'b)}" for f b by auto
  have "f ` A = f' ` A"
  proof -
    have "f ` A = f ` (set_mset (mset_set A))" using \<open>finite A\<close> by simp
    also have "\<dots> = f' ` (set_mset (mset_set A))"
      by (metis mset_eq multiset.set_map)
    also have "\<dots> = f' ` A" using \<open>finite A\<close> by simp
    finally show ?thesis .
  qed
  have "\<forall>b\<in>(f ` A). \<exists>p. bij_betw p {a \<in> A. f a = b} {a \<in> A. f' a = b}"
  proof
    fix b
    from mset_eq have
      "count (image_mset f (mset_set A)) b = count (image_mset f' (mset_set A)) b" by simp
    from this  have "card {a \<in> A. f a = b} = card {a \<in> A. f' a = b}"
      using \<open>finite A\<close>
      by (simp add: count_image_mset_eq_card_vimage)
    from this show "\<exists>p. bij_betw p {a\<in>A. f a = b} {a \<in> A. f' a = b}"
      by (intro finite_same_card_bij) simp_all
  qed
  hence "\<exists>p. \<forall>b\<in>f ` A. bij_betw (p b) {a \<in> A. f a = b} {a \<in> A. f' a = b}"
    by (rule bchoice)
  then guess p .. note p = this
  define p' where "p' = (\<lambda>a. if a \<in> A then p (f a) a else a)"
  have "p' permutes A"
  proof (rule bij_imp_permutes)
    have "disjoint_family_on (\<lambda>i. {a \<in> A. f' a = i}) (f ` A)"
      unfolding disjoint_family_on_def by auto
    moreover have "bij_betw (\<lambda>a. p (f a) a) {a \<in> A. f a = b} {a \<in> A. f' a = b}" if b: "b \<in> f ` A" for b
      using p b by (subst bij_betw_cong[where g="p b"]) auto
    ultimately have "bij_betw (\<lambda>a. p (f a) a) (\<Union>b\<in>f ` A. {a \<in> A. f a = b}) (\<Union>b\<in>f ` A. {a \<in> A. f' a = b})"
      by (rule bij_betw_UNION_disjoint)
    moreover have "(\<Union>b\<in>f ` A. {a \<in> A. f a = b}) = A" by auto
    moreover have "(\<Union>b\<in>f ` A. {a \<in> A. f' a = b}) = A" using \<open>f ` A = f' ` A\<close> by auto
    ultimately show "bij_betw p' A A"
      unfolding p'_def by (subst bij_betw_cong[where g="(\<lambda>a. p (f a) a)"]) auto
  next
    fix x
    assume "x \<notin> A"
    from this show "p' x = x"
      unfolding p'_def by simp
  qed
  moreover from p have "\<forall>x\<in>A. f x = f' (p' x)"
    unfolding p'_def using bij_betwE by fastforce
  ultimately show ?thesis by (rule that)
qed

lemma mset_set_upto_eq_mset_upto:
  "mset_set {..<n} = mset [0..<n]"
  by (induct n) (auto simp add: add.commute lessThan_Suc)

(* and derive the existing property: *)
lemma mset_eq_permutation:
  assumes mset_eq: "mset (xs::'a list) = mset ys"
  obtains p where "p permutes {..<length ys}" "permute_list p ys = xs"
proof -
  from mset_eq have length_eq: "length xs = length ys"
    using mset_eq_length by blast
  have "mset_set {..<length ys} = mset [0..<length ys]"
    using mset_set_upto_eq_mset_upto by blast
  from mset_eq length_eq this have
    "image_mset (\<lambda>i. xs ! i) (mset_set {..<length ys}) = image_mset (\<lambda>i. ys ! i) (mset_set {..<length ys})"
    by (metis map_nth mset_map)
  from image_mset_eq_implies_permutes[OF _ this]
    obtain p where "p permutes {..<length ys}"
    and "\<forall>i\<in>{..<length ys}. xs ! i = ys ! (p i)" by auto
  moreover from this length_eq have "permute_list p ys = xs"
    by (auto intro!: nth_equalityI simp add: permute_list_nth)
  ultimately show thesis using that by blast
qed

lemma permutes_natset_le:
  fixes S :: "'a::wellorder set"
  assumes p: "p permutes S"
    and le: "\<forall>i \<in> S. p i \<le> i"
  shows "p = id"
proof -
  {
    fix n
    have "p n = n"
      using p le
    proof (induct n arbitrary: S rule: less_induct)
      fix n S
      assume H:
        "\<And>m S. m < n \<Longrightarrow> p permutes S \<Longrightarrow> \<forall>i\<in>S. p i \<le> i \<Longrightarrow> p m = m"
        "p permutes S" "\<forall>i \<in>S. p i \<le> i"
      {
        assume "n \<notin> S"
        with H(2) have "p n = n"
          unfolding permutes_def by metis
      }
      moreover
      {
        assume ns: "n \<in> S"
        from H(3)  ns have "p n < n \<or> p n = n"
          by auto
        moreover {
          assume h: "p n < n"
          from H h have "p (p n) = p n"
            by metis
          with permutes_inj[OF H(2)] have "p n = n"
            unfolding inj_on_def by blast
          with h have False
            by simp
        }
        ultimately have "p n = n"
          by blast
      }
      ultimately show "p n = n"
        by blast
    qed
  }
  then show ?thesis
    by (auto simp add: fun_eq_iff)
qed

lemma permutes_natset_ge:
  fixes S :: "'a::wellorder set"
  assumes p: "p permutes S"
    and le: "\<forall>i \<in> S. p i \<ge> i"
  shows "p = id"
proof -
  {
    fix i
    assume i: "i \<in> S"
    from i permutes_in_image[OF permutes_inv[OF p]] have "inv p i \<in> S"
      by simp
    with le have "p (inv p i) \<ge> inv p i"
      by blast
    with permutes_inverses[OF p] have "i \<ge> inv p i"
      by simp
  }
  then have th: "\<forall>i\<in>S. inv p i \<le> i"
    by blast
  from permutes_natset_le[OF permutes_inv[OF p] th]
  have "inv p = inv id"
    by simp
  then show ?thesis
    apply (subst permutes_inv_inv[OF p, symmetric])
    apply (rule inv_unique_comp)
    apply simp_all
    done
qed

lemma image_inverse_permutations: "{inv p |p. p permutes S} = {p. p permutes S}"
  apply (rule set_eqI)
  apply auto
  using permutes_inv_inv permutes_inv
  apply auto
  apply (rule_tac x="inv x" in exI)
  apply auto
  done

lemma image_compose_permutations_left:
  assumes q: "q permutes S"
  shows "{q \<circ> p | p. p permutes S} = {p . p permutes S}"
  apply (rule set_eqI)
  apply auto
  apply (rule permutes_compose)
  using q
  apply auto
  apply (rule_tac x = "inv q \<circ> x" in exI)
  apply (simp add: o_assoc permutes_inv permutes_compose permutes_inv_o)
  done

lemma image_compose_permutations_right:
  assumes q: "q permutes S"
  shows "{p \<circ> q | p. p permutes S} = {p . p permutes S}"
  apply (rule set_eqI)
  apply auto
  apply (rule permutes_compose)
  using q
  apply auto
  apply (rule_tac x = "x \<circ> inv q" in exI)
  apply (simp add: o_assoc permutes_inv permutes_compose permutes_inv_o comp_assoc)
  done

lemma permutes_in_seg: "p permutes {1 ..n} \<Longrightarrow> i \<in> {1..n} \<Longrightarrow> 1 \<le> p i \<and> p i \<le> n"
  by (simp add: permutes_def) metis

lemma sum_permutations_inverse:
  "sum f {p. p permutes S} = sum (\<lambda>p. f(inv p)) {p. p permutes S}"
  (is "?lhs = ?rhs")
proof -
  let ?S = "{p . p permutes S}"
  have th0: "inj_on inv ?S"
  proof (auto simp add: inj_on_def)
    fix q r
    assume q: "q permutes S"
      and r: "r permutes S"
      and qr: "inv q = inv r"
    then have "inv (inv q) = inv (inv r)"
      by simp
    with permutes_inv_inv[OF q] permutes_inv_inv[OF r] show "q = r"
      by metis
  qed
  have th1: "inv ` ?S = ?S"
    using image_inverse_permutations by blast
  have th2: "?rhs = sum (f \<circ> inv) ?S"
    by (simp add: o_def)
  from sum.reindex[OF th0, of f] show ?thesis unfolding th1 th2 .
qed

lemma setum_permutations_compose_left:
  assumes q: "q permutes S"
  shows "sum f {p. p permutes S} = sum (\<lambda>p. f(q \<circ> p)) {p. p permutes S}"
  (is "?lhs = ?rhs")
proof -
  let ?S = "{p. p permutes S}"
  have th0: "?rhs = sum (f \<circ> (op \<circ> q)) ?S"
    by (simp add: o_def)
  have th1: "inj_on (op \<circ> q) ?S"
  proof (auto simp add: inj_on_def)
    fix p r
    assume "p permutes S"
      and r: "r permutes S"
      and rp: "q \<circ> p = q \<circ> r"
    then have "inv q \<circ> q \<circ> p = inv q \<circ> q \<circ> r"
      by (simp add: comp_assoc)
    with permutes_inj[OF q, unfolded inj_iff] show "p = r"
      by simp
  qed
  have th3: "(op \<circ> q) ` ?S = ?S"
    using image_compose_permutations_left[OF q] by auto
  from sum.reindex[OF th1, of f] show ?thesis unfolding th0 th1 th3 .
qed

lemma sum_permutations_compose_right:
  assumes q: "q permutes S"
  shows "sum f {p. p permutes S} = sum (\<lambda>p. f(p \<circ> q)) {p. p permutes S}"
  (is "?lhs = ?rhs")
proof -
  let ?S = "{p. p permutes S}"
  have th0: "?rhs = sum (f \<circ> (\<lambda>p. p \<circ> q)) ?S"
    by (simp add: o_def)
  have th1: "inj_on (\<lambda>p. p \<circ> q) ?S"
  proof (auto simp add: inj_on_def)
    fix p r
    assume "p permutes S"
      and r: "r permutes S"
      and rp: "p \<circ> q = r \<circ> q"
    then have "p \<circ> (q \<circ> inv q) = r \<circ> (q \<circ> inv q)"
      by (simp add: o_assoc)
    with permutes_surj[OF q, unfolded surj_iff] show "p = r"
      by simp
  qed
  have th3: "(\<lambda>p. p \<circ> q) ` ?S = ?S"
    using image_compose_permutations_right[OF q] by auto
  from sum.reindex[OF th1, of f]
  show ?thesis unfolding th0 th1 th3 .
qed

subsection \<open>Sum over a set of permutations (could generalize to iteration)\<close>

lemma sum_over_permutations_insert:
  assumes fS: "finite S"
    and aS: "a \<notin> S"
  shows "sum f {p. p permutes (insert a S)} =
    sum (\<lambda>b. sum (\<lambda>q. f (Fun.swap a b id \<circ> q)) {p. p permutes S}) (insert a S)"
proof -
  have th0: "\<And>f a b. (\<lambda>(b,p). f (Fun.swap a b id \<circ> p)) = f \<circ> (\<lambda>(b,p). Fun.swap a b id \<circ> p)"
    by (simp add: fun_eq_iff)
  have th1: "\<And>P Q. P \<times> Q = {(a,b). a \<in> P \<and> b \<in> Q}"
    by blast
  have th2: "\<And>P Q. P \<Longrightarrow> (P \<Longrightarrow> Q) \<Longrightarrow> P \<and> Q"
    by blast
  show ?thesis
    unfolding permutes_insert
    unfolding sum.cartesian_product
    unfolding th1[symmetric]
    unfolding th0
  proof (rule sum.reindex)
    let ?f = "(\<lambda>(b, y). Fun.swap a b id \<circ> y)"
    let ?P = "{p. p permutes S}"
    {
      fix b c p q
      assume b: "b \<in> insert a S"
      assume c: "c \<in> insert a S"
      assume p: "p permutes S"
      assume q: "q permutes S"
      assume eq: "Fun.swap a b id \<circ> p = Fun.swap a c id \<circ> q"
      from p q aS have pa: "p a = a" and qa: "q a = a"
        unfolding permutes_def by metis+
      from eq have "(Fun.swap a b id \<circ> p) a  = (Fun.swap a c id \<circ> q) a"
        by simp
      then have bc: "b = c"
        by (simp add: permutes_def pa qa o_def fun_upd_def Fun.swap_def id_def
            cong del: if_weak_cong split: if_split_asm)
      from eq[unfolded bc] have "(\<lambda>p. Fun.swap a c id \<circ> p) (Fun.swap a c id \<circ> p) =
        (\<lambda>p. Fun.swap a c id \<circ> p) (Fun.swap a c id \<circ> q)" by simp
      then have "p = q"
        unfolding o_assoc swap_id_idempotent
        by (simp add: o_def)
      with bc have "b = c \<and> p = q"
        by blast
    }
    then show "inj_on ?f (insert a S \<times> ?P)"
      unfolding inj_on_def by clarify metis
  qed
qed

subsection \<open>Constructing permutations from association lists\<close>

definition list_permutes where
  "list_permutes xs A \<longleftrightarrow> set (map fst xs) \<subseteq> A \<and> set (map snd xs) = set (map fst xs) \<and>
     distinct (map fst xs) \<and> distinct (map snd xs)"

lemma list_permutesI [simp]:
  assumes "set (map fst xs) \<subseteq> A" "set (map snd xs) = set (map fst xs)" "distinct (map fst xs)"
  shows   "list_permutes xs A"
proof -
  from assms(2,3) have "distinct (map snd xs)"
    by (intro card_distinct) (simp_all add: distinct_card del: set_map)
  with assms show ?thesis by (simp add: list_permutes_def)
qed

definition permutation_of_list where
  "permutation_of_list xs x = (case map_of xs x of None \<Rightarrow> x | Some y \<Rightarrow> y)"

lemma permutation_of_list_Cons:
  "permutation_of_list ((x,y) # xs) x' = (if x = x' then y else permutation_of_list xs x')"
  by (simp add: permutation_of_list_def)

fun inverse_permutation_of_list where
  "inverse_permutation_of_list [] x = x"
| "inverse_permutation_of_list ((y,x')#xs) x =
     (if x = x' then y else inverse_permutation_of_list xs x)"

declare inverse_permutation_of_list.simps [simp del]

lemma inj_on_map_of:
  assumes "distinct (map snd xs)"
  shows   "inj_on (map_of xs) (set (map fst xs))"
proof (rule inj_onI)
  fix x y assume xy: "x \<in> set (map fst xs)" "y \<in> set (map fst xs)"
  assume eq: "map_of xs x = map_of xs y"
  from xy obtain x' y'
    where x'y': "map_of xs x = Some x'" "map_of xs y = Some y'"
    by (cases "map_of xs x"; cases "map_of xs y")
       (simp_all add: map_of_eq_None_iff)
  moreover from x'y' have *: "(x,x') \<in> set xs" "(y,y') \<in> set xs"
    by (force dest: map_of_SomeD)+
  moreover from * eq x'y' have "x' = y'" by simp
  ultimately show "x = y" using assms
    by (force simp: distinct_map dest: inj_onD[of _ _ "(x,x')" "(y,y')"])
qed

lemma inj_on_the: "None \<notin> A \<Longrightarrow> inj_on the A"
  by (auto simp: inj_on_def option.the_def split: option.splits)

lemma inj_on_map_of':
  assumes "distinct (map snd xs)"
  shows   "inj_on (the \<circ> map_of xs) (set (map fst xs))"
  by (intro comp_inj_on inj_on_map_of assms inj_on_the)
     (force simp: eq_commute[of None] map_of_eq_None_iff)

lemma image_map_of:
  assumes "distinct (map fst xs)"
  shows   "map_of xs ` set (map fst xs) = Some ` set (map snd xs)"
  using assms by (auto simp: rev_image_eqI)

lemma the_Some_image [simp]: "the ` Some ` A = A"
  by (subst image_image) simp

lemma image_map_of':
  assumes "distinct (map fst xs)"
  shows   "(the \<circ> map_of xs) ` set (map fst xs) = set (map snd xs)"
  by (simp only: image_comp [symmetric] image_map_of assms the_Some_image)

lemma permutation_of_list_permutes [simp]:
  assumes "list_permutes xs A"
  shows   "permutation_of_list xs permutes A" (is "?f permutes _")
proof (rule permutes_subset[OF bij_imp_permutes])
  from assms show "set (map fst xs) \<subseteq> A"
    by (simp add: list_permutes_def)
  from assms have "inj_on (the \<circ> map_of xs) (set (map fst xs))" (is ?P)
    by (intro inj_on_map_of') (simp_all add: list_permutes_def)
  also have "?P \<longleftrightarrow> inj_on ?f (set (map fst xs))"
    by (intro inj_on_cong)
       (auto simp: permutation_of_list_def map_of_eq_None_iff split: option.splits)
  finally have "bij_betw ?f (set (map fst xs)) (?f ` set (map fst xs))"
    by (rule inj_on_imp_bij_betw)
  also from assms have "?f ` set (map fst xs) = (the \<circ> map_of xs) ` set (map fst xs)"
    by (intro image_cong refl)
       (auto simp: permutation_of_list_def map_of_eq_None_iff split: option.splits)
  also from assms have "\<dots> = set (map fst xs)"
    by (subst image_map_of') (simp_all add: list_permutes_def)
  finally show "bij_betw ?f (set (map fst xs)) (set (map fst xs))" .
qed (force simp: permutation_of_list_def dest!: map_of_SomeD split: option.splits)+

lemma eval_permutation_of_list [simp]:
  "permutation_of_list [] x = x"
  "x = x' \<Longrightarrow> permutation_of_list ((x',y)#xs) x = y"
  "x \<noteq> x' \<Longrightarrow> permutation_of_list ((x',y')#xs) x = permutation_of_list xs x"
  by (simp_all add: permutation_of_list_def)

lemma eval_inverse_permutation_of_list [simp]:
  "inverse_permutation_of_list [] x = x"
  "x = x' \<Longrightarrow> inverse_permutation_of_list ((y,x')#xs) x = y"
  "x \<noteq> x' \<Longrightarrow> inverse_permutation_of_list ((y',x')#xs) x = inverse_permutation_of_list xs x"
  by (simp_all add: inverse_permutation_of_list.simps)

lemma permutation_of_list_id:
  assumes "x \<notin> set (map fst xs)"
  shows   "permutation_of_list xs x = x"
  using assms by (induction xs) (auto simp: permutation_of_list_Cons)

lemma permutation_of_list_unique':
  assumes "distinct (map fst xs)" "(x, y) \<in> set xs"
  shows   "permutation_of_list xs x = y"
  using assms by (induction xs) (force simp: permutation_of_list_Cons)+

lemma permutation_of_list_unique:
  assumes "list_permutes xs A" "(x,y) \<in> set xs"
  shows   "permutation_of_list xs x = y"
  using assms by (intro permutation_of_list_unique') (simp_all add: list_permutes_def)

lemma inverse_permutation_of_list_id:
  assumes "x \<notin> set (map snd xs)"
  shows   "inverse_permutation_of_list xs x = x"
  using assms by (induction xs) auto

lemma inverse_permutation_of_list_unique':
  assumes "distinct (map snd xs)" "(x, y) \<in> set xs"
  shows   "inverse_permutation_of_list xs y = x"
  using assms by (induction xs) (force simp: inverse_permutation_of_list.simps)+

lemma inverse_permutation_of_list_unique:
  assumes "list_permutes xs A" "(x,y) \<in> set xs"
  shows   "inverse_permutation_of_list xs y = x"
  using assms by (intro inverse_permutation_of_list_unique') (simp_all add: list_permutes_def)

lemma inverse_permutation_of_list_correct:
  assumes "list_permutes xs (A :: 'a set)"
  shows   "inverse_permutation_of_list xs = inv (permutation_of_list xs)"
proof (rule ext, rule sym, subst permutes_inv_eq)
  from assms show "permutation_of_list xs permutes A" by simp
next
  fix x
  show "permutation_of_list xs (inverse_permutation_of_list xs x) = x"
  proof (cases "x \<in> set (map snd xs)")
    case True
    then obtain y where "(y, x) \<in> set xs" by force
    with assms show ?thesis
      by (simp add: inverse_permutation_of_list_unique permutation_of_list_unique)
  qed (insert assms, auto simp: list_permutes_def
         inverse_permutation_of_list_id permutation_of_list_id)
qed

end


theory PALandWiseMenPuzzle2021_2Agents_New imports Main    (* Christoph Benzmüller and Sebastian Reiche, 2021 *)

begin
 (* Parameter settings for Nitpick *) nitpick_params[user_axioms=true, format=4, show_all]

 typedecl i (* Type of possible worlds *)
 type_synonym \<sigma> = "i\<Rightarrow>bool" (* \<D> *)
 type_synonym \<tau> = "\<sigma>\<Rightarrow>i\<Rightarrow>bool" (* Type of world depended formulas (truth sets) *)
 type_synonym \<alpha> = "i\<Rightarrow>i\<Rightarrow>bool" (* Type of accessibility relations between world *)

 (* Some useful relations (for constraining accessibility relations) *)
 definition reflexive::"\<alpha>\<Rightarrow>bool" where "reflexive R \<equiv> \<forall>x. R x x"
 definition symmetric::"\<alpha>\<Rightarrow>bool" where "symmetric R \<equiv> \<forall>x y. R x y \<longrightarrow> R y x"
 definition transitive::"\<alpha>\<Rightarrow>bool" where "transitive R \<equiv> \<forall>x y z. R x y \<and> R y z \<longrightarrow> R x z"
 definition euclidean::"\<alpha>\<Rightarrow>bool" where "euclidean R \<equiv> \<forall>x y z. R x y \<and> R x z \<longrightarrow> R y z"
 definition intersection_rel::"\<alpha>\<Rightarrow>\<alpha>\<Rightarrow>\<alpha>" where "intersection_rel R Q \<equiv> \<lambda>u v. R u v \<and> Q u v"
 definition union_rel::"\<alpha>\<Rightarrow>\<alpha>\<Rightarrow>\<alpha>" where "union_rel R Q \<equiv> \<lambda>u v. R u v \<or> Q u v"
 definition sub_rel::"\<alpha>\<Rightarrow>\<alpha>\<Rightarrow>bool" where "sub_rel R Q \<equiv> \<forall>u v. R u v \<longrightarrow> Q u v"
 definition inverse_rel::"\<alpha>\<Rightarrow>\<alpha>" where "inverse_rel R \<equiv> \<lambda>u v. R v u"
 definition bigunion_rel::"(\<alpha>\<Rightarrow>bool)\<Rightarrow>\<alpha>" ("\<^bold>\<Union>_") where "\<^bold>\<Union> X \<equiv> \<lambda>u v. \<exists>R. (X R) \<and> (R u v)"
 definition bigintersection_rel::"(\<alpha>\<Rightarrow>bool)\<Rightarrow>\<alpha>" ("\<^bold>\<Inter>_") where "\<^bold>\<Inter> X \<equiv> \<lambda>u v. \<forall>R. (X R) \<longrightarrow> (R u v)"

 (*In HOL the transitive closure of a relation can be defined in a single line.*)
 definition tc::"\<alpha>\<Rightarrow>\<alpha>" where "tc R \<equiv> \<lambda>x y.\<forall>Q. transitive Q \<longrightarrow> (sub_rel R Q \<longrightarrow> Q x y)"

 (* Lifted HOMML connectives for PAL *)
 abbreviation patom::"\<sigma>\<Rightarrow>\<tau>" ("\<^sup>A_"[79]80) where "\<^sup>Ap \<equiv> \<lambda>W w. W w \<and> p w"
 abbreviation ptop::"\<tau>" ("\<^bold>\<top>") where "\<^bold>\<top> \<equiv> \<lambda>W w. True"
 abbreviation pneg::"\<tau>\<Rightarrow>\<tau>" ("\<^bold>\<not>_"[52]53) where "\<^bold>\<not>\<phi> \<equiv> \<lambda>W w. \<not>(\<phi> W w)"
 abbreviation pand::"\<tau>\<Rightarrow>\<tau>\<Rightarrow>\<tau>" (infixr"\<^bold>\<and>"51) where "\<phi>\<^bold>\<and>\<psi> \<equiv> \<lambda>W w. (\<phi> W w) \<and> (\<psi> W w)"
 abbreviation por::"\<tau>\<Rightarrow>\<tau>\<Rightarrow>\<tau>" (infixr"\<^bold>\<or>"50) where "\<phi>\<^bold>\<or>\<psi> \<equiv> \<lambda>W w. (\<phi> W w) \<or> (\<psi> W w)"
 abbreviation pimp::"\<tau>\<Rightarrow>\<tau>\<Rightarrow>\<tau>" (infixr"\<^bold>\<rightarrow>"49) where "\<phi>\<^bold>\<rightarrow>\<psi> \<equiv> \<lambda>W w. (\<phi> W w) \<longrightarrow> (\<psi> W w)"
 abbreviation pequ::"\<tau>\<Rightarrow>\<tau>\<Rightarrow>\<tau>" (infixr"\<^bold>\<leftrightarrow>"48) where "\<phi>\<^bold>\<leftrightarrow>\<psi> \<equiv> \<lambda>W w. (\<phi> W w) \<longleftrightarrow> (\<psi> W w)"
 abbreviation pknow::"\<alpha>\<Rightarrow>\<tau>\<Rightarrow>\<tau>" ("\<^bold>K_ _") where "\<^bold>K r \<phi> \<equiv> \<lambda>W w.\<forall>v. (W v \<and> r w v) \<longrightarrow> (\<phi> W v)"
 abbreviation ppal::"\<tau>\<Rightarrow>\<tau>\<Rightarrow>\<tau>" ("\<^bold>[\<^bold>!_\<^bold>]_") where "\<^bold>[\<^bold>!\<phi>\<^bold>]\<psi> \<equiv> \<lambda>W w. (\<phi> W w) \<longrightarrow> (\<psi> (\<lambda>z. W z \<and> \<phi> W z) w)"

 (* Validity of \<tau>-type lifted PAL formulas *)
 abbreviation pvalid::"\<tau> \<Rightarrow> bool" ("\<^bold>\<lfloor>_\<^bold>\<rfloor>"[7]8) where "\<^bold>\<lfloor>\<phi>\<^bold>\<rfloor> \<equiv> \<forall>W.\<forall>w. W w \<longrightarrow> \<phi> W w"

 (* Agent Knowledge, Mutual Knowledge, Common Knowledge *)
 abbreviation  "EVR A \<equiv> \<^bold>\<Union> A"
 abbreviation  "DIS A \<equiv> \<^bold>\<Inter> A"
 abbreviation agttknows::"\<alpha>\<Rightarrow>\<tau>\<Rightarrow>\<tau>" ("\<^bold>K\<^sub>_ _") where "\<^bold>K\<^sub>r \<phi> \<equiv>  \<^bold>K r \<phi>"
 abbreviation evrknows::"(\<alpha>\<Rightarrow>bool)\<Rightarrow>\<tau>\<Rightarrow>\<tau>" ("\<^bold>E\<^sub>_ _") where "\<^bold>E\<^sub>A \<phi> \<equiv>  \<^bold>K (EVR A) \<phi>"
 abbreviation prck::"(\<alpha>\<Rightarrow>bool)\<Rightarrow>\<tau>\<Rightarrow>\<tau>\<Rightarrow>\<tau>" ("\<^bold>C\<^sub>_\<^bold>\<lparr>_\<^bold>|_\<^bold>\<rparr>")
   where "\<^bold>C\<^sub>A\<^bold>\<lparr>\<phi>\<^bold>|\<psi>\<^bold>\<rparr> \<equiv> \<lambda>W w. \<forall>v. \<not>(tc (intersection_rel (EVR A) (\<lambda>u v. W v \<and> \<phi> W v)) w v) \<or> (\<psi> W v)"
 abbreviation pcmn::"(\<alpha>\<Rightarrow>bool)\<Rightarrow>\<tau>\<Rightarrow>\<tau>" ("\<^bold>C\<^sub>_ _") where "\<^bold>C\<^sub>A \<phi> \<equiv>  \<^bold>C\<^sub>A\<^bold>\<lparr>\<^bold>\<top>\<^bold>|\<phi>\<^bold>\<rparr>"
 abbreviation disknows :: "(\<alpha>\<Rightarrow>bool)\<Rightarrow>\<tau>\<Rightarrow>\<tau>" ("\<^bold>D\<^sub>_ _") where "\<^bold>D\<^sub>A \<phi> \<equiv> \<^bold>K (DIS A) \<phi>"

 (* Introducing "Defs" as the set of the above definitions; useful for convenient unfolding *)
 named_theorems Defs
 declare reflexive_def[Defs] symmetric_def[Defs] transitive_def[Defs] euclidean_def[Defs]
   intersection_rel_def[Defs] union_rel_def[Defs] sub_rel_def[Defs] inverse_rel_def[Defs]
   bigunion_rel_def[Defs] tc_def[Defs]

 (***********************************************************************************************)
 (*****                         Wise Men Puzzle                                             *****)
 (***********************************************************************************************)
 (*** Encoding of the wise men puzzle in PAL ***)
 (* Agents *)
 consts a::"\<alpha>" b::"\<alpha>" (* Agents modeled as accessibility relations *)
 abbreviation  Agent::"\<alpha>\<Rightarrow>bool" ("\<A>") where "\<A> x \<equiv> x = a \<or> x = b"
 axiomatization where  group_S5: "S5Agents \<A>"

 (*** Encoding of the wise men puzzle in PAL ***)
 (* Common knowledge: At least one of a and b has a white spot *)
 consts ws::"\<alpha>\<Rightarrow>\<sigma>"
 axiomatization where WM1: "\<^bold>\<lfloor>\<^bold>C\<^sub>\<A> (\<^sup>Aws a \<^bold>\<or> \<^sup>Aws b)\<^bold>\<rfloor>"

 axiomatization where
   (* Common knowledge: If x does not have a white spot then y know this *)
   WM2ab: "\<^bold>\<lfloor>\<^bold>C\<^sub>\<A> (\<^bold>\<not>(\<^sup>Aws a) \<^bold>\<rightarrow> (\<^bold>K\<^sub>b (\<^bold>\<not>(\<^sup>Aws a))))\<^bold>\<rfloor>" and
   WM2ba: "\<^bold>\<lfloor>\<^bold>C\<^sub>\<A> (\<^bold>\<not>(\<^sup>Aws b) \<^bold>\<rightarrow> (\<^bold>K\<^sub>a (\<^bold>\<not>(\<^sup>Aws b))))\<^bold>\<rfloor>"

 (* Automated solutions of the Wise Men Puzzle with 4 Agents*)

 theorem "\<^bold>\<lfloor>\<^bold>[\<^bold>!\<^bold>\<not>\<^bold>K\<^sub>a(\<^sup>Aws a)\<^bold>](\<^bold>K\<^sub>b (\<^sup>Aws b))\<^bold>\<rfloor>"
   using WM1 WM2ba unfolding Defs by (smt (verit))

 (* This one does not work yet *)
 theorem whitespot_c:
     "\<^bold>\<lfloor>\<^bold>[\<^bold>!\<^bold>\<not>((\<^bold>K\<^sub>a (\<^sup>Aws a)) \<^bold>\<or> (\<^bold>K\<^sub>a (\<^bold>\<not>\<^sup>Aws a)))\<^bold>](\<^bold>K\<^sub>b (\<^sup>Aws b))\<^bold>\<rfloor>"
   using WM1 WM2ba unfolding Defs by (smt (verit))

 (* Consistency confirmed by nitpick *)
 lemma True nitpick [satisfy] oops  (* model found *)

end


section \<open>Quadratic Irrationals\<close>
theory Quadratic_Irrationals
imports
  Continued_Fractions
  "HOL-Computational_Algebra.Computational_Algebra"
  "HOL-Library.Discrete"
begin

subsection \<open>Basic results on rationality of square roots\<close>

lemma inverse_in_Rats_iff [simp]: "inverse (x :: real) \<in> \<rat> \<longleftrightarrow> x \<in> \<rat>"
  by (auto simp: inverse_eq_divide divide_in_Rats_iff1)

lemma nonneg_sqrt_nat_or_irrat:
  assumes "x ^ 2 = real a" and "x \<ge> 0"
  shows   "x \<in> \<nat> \<or> x \<notin> \<rat>"
proof safe
  assume "x \<notin> \<nat>" and "x \<in> \<rat>"
  from Rats_abs_nat_div_natE[OF this(2)]
    obtain p q :: nat where q_nz [simp]: "q \<noteq> 0" and "abs x = p / q" and coprime: "coprime p q" .
  with \<open>x \<ge> 0\<close> have x: "x = p / q"
      by simp
  with assms have "real (q ^ 2) * real a = real (p ^ 2)"
    by (simp add: field_simps)
  also have "real (q ^ 2) * real a = real (q ^ 2 * a)"
    by simp
  finally have "p ^ 2 = q ^ 2 * a"
    by (subst (asm) of_nat_eq_iff) auto
  hence "q ^ 2 dvd p ^ 2"
    by simp
  hence "q dvd p"
    by simp
  with coprime have "q = 1"
    by auto
  with x and \<open>x \<notin> \<nat>\<close> show False
    by simp
qed

text \<open>
  A square root of a natural number is either an integer or irrational.
\<close>
corollary sqrt_nat_or_irrat:
  assumes "x ^ 2 = real a"
  shows   "x \<in> \<int> \<or> x \<notin> \<rat>"
proof (cases "x \<ge> 0")
  case True
  with nonneg_sqrt_nat_or_irrat[OF assms this]
    show ?thesis by (auto simp: Nats_altdef2)
next
  case False
  from assms have "(-x) ^ 2 = real a"
    by simp
  moreover from False have "-x \<ge> 0"
    by simp
  ultimately have "-x \<in> \<nat> \<or> -x \<notin> \<rat>"
    by (rule nonneg_sqrt_nat_or_irrat)
  thus ?thesis
    by (auto simp: Nats_altdef2 minus_in_Ints_iff)
qed

corollary sqrt_nat_or_irrat':
  "sqrt (real a) \<in> \<nat> \<or> sqrt (real a) \<notin> \<rat>"
  using nonneg_sqrt_nat_or_irrat[of "sqrt a" a] by auto

text \<open>
  The square root of a natural number \<open>n\<close> is again a natural number iff \<open>n is a perfect square.\<close>
\<close>
corollary sqrt_nat_iff_is_square:
  "sqrt (real n) \<in> \<nat> \<longleftrightarrow> is_square n"
proof
  assume "sqrt (real n) \<in> \<nat>"
  then obtain k where "sqrt (real n) = real k" by (auto elim!: Nats_cases)
  hence "sqrt (real n) ^ 2 = real (k ^ 2)" by (simp only: of_nat_power)
  also have "sqrt (real n) ^ 2 = real n" by simp
  finally have "n = k ^ 2" by (simp only: of_nat_eq_iff)
  thus "is_square n" by blast
qed (auto elim!: is_nth_powerE)

corollary irrat_sqrt_nonsquare: "\<not>is_square n \<Longrightarrow> sqrt (real n) \<notin> \<rat>"
  using sqrt_nat_or_irrat'[of n] by (auto simp: sqrt_nat_iff_is_square)

lemma sqrt_of_nat_in_Rats_iff: "sqrt (real n) \<in> \<rat> \<longleftrightarrow> is_square n"
  using irrat_sqrt_nonsquare[of n] sqrt_nat_iff_is_square[of n] Nats_subset_Rats by blast

lemma Discrete_sqrt_altdef: "Discrete.sqrt n = nat \<lfloor>sqrt n\<rfloor>"
proof -
  have "real (Discrete.sqrt n ^ 2) \<le> sqrt n ^ 2"
    by simp
  hence "Discrete.sqrt n \<le> sqrt n"
    unfolding of_nat_power by (rule power2_le_imp_le) auto
  moreover have "real (Suc (Discrete.sqrt n) ^ 2) > real n"
    unfolding of_nat_less_iff by (rule Suc_sqrt_power2_gt)
  hence "real (Discrete.sqrt n + 1) ^ 2 > sqrt n ^ 2"
    unfolding of_nat_power by simp
  hence "real (Discrete.sqrt n + 1) > sqrt n"
    by (rule power2_less_imp_less) auto
  hence "Discrete.sqrt n + 1 > sqrt n" by simp
  ultimately show ?thesis by linarith
qed

subsection \<open>Quadratic irrationals\<close>

text \<open>
  Irrational real numbers $x$ that satisfy a quadratic equation $a x^2 + b x + c = 0$
  with \<open>a\<close>, \<open>b\<close>, \<open>c\<close> not all equal to 0 are called \<^emph>\<open>quadratic irrationals\<close>. These are of the form
  $p + q \sqrt{d}$ for rational numbers \<open>p\<close>, \<open>q\<close> and a positive integer \<open>d\<close>.
\<close>
inductive quadratic_irrational :: "real \<Rightarrow> bool" where
  "x \<notin> \<rat> \<Longrightarrow> real_of_int a * x ^ 2 + real_of_int b * x + real_of_int c = 0 \<Longrightarrow>
     a \<noteq> 0 \<or> b \<noteq> 0 \<or> c \<noteq> 0 \<Longrightarrow> quadratic_irrational x"

lemma quadratic_irrational_sqrt [intro]:
  assumes "\<not>is_square n"
  shows   "quadratic_irrational (sqrt (real n))"
  using irrat_sqrt_nonsquare[OF assms]
  by (intro quadratic_irrational.intros[of "sqrt n" 1 0 "-int n"]) auto

lemma quadratic_irrational_uminus [intro]:
  assumes "quadratic_irrational x"
  shows   "quadratic_irrational (-x)"
  using assms
proof induction
  case (1 x a b c)
  thus ?case by (intro quadratic_irrational.intros[of "-x" a "-b" c]) auto
qed

lemma quadratic_irrational_uminus_iff [simp]:
  "quadratic_irrational (-x) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_uminus[of x] quadratic_irrational_uminus[of "-x"] by auto

lemma quadratic_irrational_plus_int [intro]:
  assumes "quadratic_irrational x"
  shows   "quadratic_irrational (x + of_int n)"
  using assms
proof induction
  case (1 x a b c)
  define x' where "x' = x + of_int n"
  define a' b' c' where
     "a' = a" and "b' = b - 2 * of_int n * a" and
     "c' = a * of_int n ^ 2 - b * of_int n + c"
  from 1 have "0 = a * (x' - of_int n) ^ 2 + b * (x' - of_int n) + c"
    by (simp add: x'_def)
  also have "\<dots> = a' * x' ^ 2 + b' * x' + c'"
    by (simp add: algebra_simps a'_def b'_def c'_def power2_eq_square)
  finally have "\<dots> = 0" ..
  moreover have "x' \<notin> \<rat>"
    using 1 by (auto simp: x'_def add_in_Rats_iff2)
  moreover have "a' \<noteq> 0 \<or> b' \<noteq> 0 \<or> c' \<noteq> 0"
    using 1 by (auto simp: a'_def b'_def c'_def)
  ultimately show ?case
    by (intro quadratic_irrational.intros[of "x + of_int n" a' b' c']) (auto simp: x'_def)
qed

lemma quadratic_irrational_plus_int_iff [simp]:
  "quadratic_irrational (x + of_int n) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_plus_int[of x n]
        quadratic_irrational_plus_int[of "x + of_int n" "-n"] by auto

lemma quadratic_irrational_minus_int_iff [simp]:
  "quadratic_irrational (x - of_int n) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_plus_int_iff[of x "-n"]
  by (simp del: quadratic_irrational_plus_int_iff)

lemma quadratic_irrational_plus_nat_iff [simp]:
  "quadratic_irrational (x + of_nat n) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_plus_int_iff[of x "int n"]
  by (simp del: quadratic_irrational_plus_int_iff)

lemma quadratic_irrational_minus_nat_iff [simp]:
  "quadratic_irrational (x - of_nat n) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_plus_int_iff[of x "-int n"]
  by (simp del: quadratic_irrational_plus_int_iff)

lemma quadratic_irrational_plus_1_iff [simp]:
  "quadratic_irrational (x + 1) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_plus_int_iff[of x 1]
  by (simp del: quadratic_irrational_plus_int_iff)

lemma quadratic_irrational_minus_1_iff [simp]:
  "quadratic_irrational (x - 1) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_plus_int_iff[of x "-1"]
  by (simp del: quadratic_irrational_plus_int_iff)

lemma quadratic_irrational_plus_numeral_iff [simp]:
  "quadratic_irrational (x + numeral n) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_plus_int_iff[of x "numeral n"]
  by (simp del: quadratic_irrational_plus_int_iff)

lemma quadratic_irrational_minus_numeral_iff [simp]:
  "quadratic_irrational (x - numeral n) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_plus_int_iff[of x "-numeral n"]
  by (simp del: quadratic_irrational_plus_int_iff)

lemma quadratic_irrational_inverse:
  assumes "quadratic_irrational x"
  shows   "quadratic_irrational (inverse x)"
  using assms
proof induction
  case (1 x a b c)
  from 1 have "x \<noteq> 0" by auto
  have "0 = (real_of_int a * x\<^sup>2 + real_of_int b * x + real_of_int c) / x ^ 2"
    by (subst 1) simp
  also have "\<dots> = real_of_int c * (inverse x) ^ 2 + real_of_int b * inverse x + real_of_int a"
    using \<open>x \<noteq> 0\<close> by (simp add: field_simps power2_eq_square)
  finally have "\<dots> = 0" ..
  thus ?case using 1
    by (intro quadratic_irrational.intros[of "inverse x" c b a]) auto
qed

lemma quadratic_irrational_inverse_iff [simp]:
  "quadratic_irrational (inverse x) \<longleftrightarrow> quadratic_irrational x"
  using quadratic_irrational_inverse[of x] quadratic_irrational_inverse[of "inverse x"]
  by (cases "x = 0") auto

lemma quadratic_irrational_cfrac_remainder_iff:
  "quadratic_irrational (cfrac_remainder c n) \<longleftrightarrow> quadratic_irrational (cfrac_lim c)"
proof (cases "cfrac_length c = \<infinity>")
  case False
  thus ?thesis
    by (auto simp: quadratic_irrational.simps)
next
  case [simp]: True
  show ?thesis
  proof (induction n)
    case (Suc n)
    from Suc.prems have "cfrac_remainder c (Suc n) =
                           inverse (cfrac_remainder c n - of_int (cfrac_nth c n))"
      by (subst cfrac_remainder_Suc) (auto simp: field_simps)
    also have "quadratic_irrational \<dots> \<longleftrightarrow> quadratic_irrational (cfrac_remainder c n)"
      by simp
    also have "\<dots> \<longleftrightarrow> quadratic_irrational (cfrac_lim c)"
      by (rule Suc.IH)
    finally show ?case .
  qed auto
qed

subsection \<open>Real solutions of quadratic equations\<close>

text \<open>
  For the next result, we need some basic properties of real solutions to quadratic equations.
\<close>
lemma quadratic_equation_reals_cases:
  fixes a b c :: real
  defines "f \<equiv> (\<lambda>x. a * x ^ 2 + b * x + c)"
  defines "discr \<equiv> (b^2 - 4 * a * c)"
  shows   "{x. f x = 0} =
             (if a = 0 then
                (if b = 0 then if c = 0 then UNIV else {} else {-c/b})
              else if discr \<ge> 0 then {(-b + sqrt discr) / (2 * a), (-b - sqrt discr) / (2 * a)}
                                else {})" (is ?th1)
proof (cases "a = 0")
  case [simp]: True
  show ?th1
  proof (cases "b = 0")
    case [simp]: True
    hence "{x. f x = 0} = (if c = 0 then UNIV else {})"
      by (auto simp: f_def)
    thus ?th1 by simp
  next
    case False
    hence "{x. f x = 0} = {-c / b}" by (auto simp: f_def field_simps)
    thus ?th1 using False by simp
  qed
next
  case [simp]: False
  show ?th1
  proof (cases "discr \<ge> 0")
    case True
    {
      fix x :: real
      have "f x = a * (x - (-b + sqrt discr) / (2 * a)) * (x - (-b - sqrt discr) / (2 * a))"
        using True by (simp add: f_def field_simps discr_def power2_eq_square)
      also have "\<dots> = 0 \<longleftrightarrow> x \<in> {(-b + sqrt discr) / (2 * a), (-b - sqrt discr) / (2 * a)}"
        by simp
      finally have "f x = 0 \<longleftrightarrow> \<dots>" .
    }
    hence "{x. f x = 0} = {(-b + sqrt discr) / (2 * a), (-b - sqrt discr) / (2 * a)}"
      by blast
    thus ?th1 using True by simp
  next
    case False
    {
      fix x :: real
      assume x: "f x = 0"
      have "0 \<le> (x + b / (2 * a)) ^ 2" by simp
      also have "f x = a * ((x + b / (2 * a)) ^ 2 - b ^ 2 / (4 * a ^ 2) + c / a)"
        by (simp add: field_simps power2_eq_square f_def)
      with x have "(x + b / (2 * a)) ^ 2 - b ^ 2 / (4 * a ^ 2) + c / a = 0"
        by simp
      hence "(x + b / (2 * a)) ^ 2 = b ^ 2 / (4 * a ^ 2) - c / a"
        by (simp add: algebra_simps)
      finally have "0 \<le> (b\<^sup>2 / (4 * a\<^sup>2) - c / a) * (4 * a\<^sup>2)"
        by (intro mult_nonneg_nonneg) auto
      also have "\<dots> = b\<^sup>2 - 4 * a * c" by (simp add: field_simps power2_eq_square)
      also have "\<dots> < 0" using False by (simp add: discr_def)
      finally have False by simp
    }
    hence "{x. f x = 0} = {}" by auto
    thus ?th1 using False by simp
  qed
qed

lemma finite_quadratic_equation_solutions_reals:
  fixes a b c :: real
  defines "discr \<equiv> (b^2 - 4 * a * c)"
  shows   "finite {x. a * x ^ 2 + b * x + c = 0} \<longleftrightarrow> a \<noteq> 0 \<or> b \<noteq> 0 \<or> c \<noteq> 0"
  by (subst quadratic_equation_reals_cases)
     (auto simp: discr_def card_eq_0_iff infinite_UNIV_char_0 split: if_split)

lemma card_quadratic_equation_solutions_reals:
  fixes a b c :: real
  defines "discr \<equiv> (b^2 - 4 * a * c)"
  shows   "card {x. a * x ^ 2 + b * x + c = 0} =
             (if a = 0 then
                (if b = 0 then 0 else 1)
              else if discr \<ge> 0 then if discr = 0 then 1 else 2 else 0)" (is ?th1)
  by (subst quadratic_equation_reals_cases)
     (auto simp: discr_def card_eq_0_iff infinite_UNIV_char_0 split: if_split)

lemma card_quadratic_equation_solutions_reals_le_2:
  "card {x :: real. a * x ^ 2 + b * x + c = 0} \<le> 2"
  by (subst card_quadratic_equation_solutions_reals) auto

lemma quadratic_equation_solution_rat_iff:
  fixes a b c :: int and x y :: real
  defines "f \<equiv> (\<lambda>x::real. a * x ^ 2 + b * x + c)"
  defines "discr \<equiv> nat (b ^ 2 - 4 * a * c)"
  assumes "a \<noteq> 0" "f x = 0"
  shows   "x \<in> \<rat> \<longleftrightarrow> is_square discr"
proof -
  define discr' where "discr' \<equiv> real_of_int (b ^ 2 - 4 * a * c)"
  from assms have "x \<in> {x. f x = 0}" by simp
  with \<open>a \<noteq> 0\<close> have "discr' \<ge> 0" unfolding discr'_def f_def of_nat_diff
    by (subst (asm) quadratic_equation_reals_cases) (auto simp: discr_def split: if_splits)
  hence *: "sqrt (discr') = sqrt (real discr)" unfolding of_int_0_le_iff discr_def discr'_def
    by (simp add: algebra_simps nat_diff_distrib)
  from \<open>x \<in> {x. f x = 0}\<close> have "x = (-b + sqrt discr) / (2 * a) \<or> x = (-b - sqrt discr) / (2 * a)"
    using \<open>a \<noteq> 0\<close> * unfolding discr'_def f_def
    by (subst (asm) quadratic_equation_reals_cases) (auto split: if_splits)
  thus ?thesis using \<open>a \<noteq> 0\<close>
    by (auto simp: sqrt_of_nat_in_Rats_iff divide_in_Rats_iff2 diff_in_Rats_iff2 diff_in_Rats_iff1)
qed

subsection \<open>Periodic continued fractions and quadratic irrationals\<close>

text \<open>
  We now show the main result: A positive irrational number has a periodic continued
  fraction expansion iff it is a quadratic irrational.

  In principle, this statement naturally also holds for negative numbers, but the current
  formalisation of continued fractions only supports non-negative numbers. It also holds for
  rational numbers in some sense, since their continued fraction expansion is finite to begin with.
\<close>
theorem periodic_cfrac_imp_quadratic_irrational:
  assumes [simp]: "cfrac_length c = \<infinity>"
      and period: "l > 0" "\<And>k. k \<ge> N \<Longrightarrow> cfrac_nth c (k + l) = cfrac_nth c k"
  shows   "quadratic_irrational (cfrac_lim c)"
proof -
  define h' and k' where "h' = conv_num_int (cfrac_drop N c)"
                     and "k' = conv_denom_int (cfrac_drop N c)"
  define x' where "x' = cfrac_remainder c N"

  have c_pos: "cfrac_nth c n > 0" if "n \<ge> N" for n
  proof -
    from assms(1,2) have "cfrac_nth c (n + l) > 0" by auto
    with assms(3)[OF that] show ?thesis by simp
  qed
  have k'_pos: "k' n > 0" if "n \<noteq> -1" "n \<ge> -2" for n
    using that by (auto simp: k'_def conv_denom_int_def intro!: conv_denom_pos)
  have k'_nonneg: "k' n \<ge> 0" if "n \<ge> -2" for n
    using that by (auto simp: k'_def conv_denom_int_def intro!: conv_denom_pos)
  have "cfrac_nth c (n + (N + l)) = cfrac_nth c (n + N)" for n
    using period(2)[of "n + N"] by (simp add: add_ac)
  have "cfrac_drop (N + l) c = cfrac_drop N c"
    by (rule cfrac_eqI) (use period(2)[of "n + N" for n] in \<open>auto simp: algebra_simps\<close>)
  hence x'_altdef: "x' = cfrac_remainder c (N + l)"
    by (simp add: x'_def cfrac_remainder_def)
  have x'_pos: "x' > 0" unfolding x'_def
    using c_pos by (intro cfrac_remainder_pos) auto

  define A where "A = (k' (int l - 1))"
  define B where "B = k' (int l - 2) - h' (int l - 1)"
  define C where "C = -(h' (int l - 2))"

  have pos: "(k' (int l - 1) * x' + k' (int l - 2)) > 0"
    using x'_pos \<open>l > 0\<close>
    by (intro add_pos_nonneg mult_pos_pos) (auto intro!: k'_pos k'_nonneg)
  have "x' = conv' (cfrac_drop N c) l x'"
    apply (subst x'_def, subst x'_altdef, subst add.commute)
    apply (simp add: cfrac_remainder_def cfrac_drop_add conv'_cfrac_remainder)
    apply (subst (2) cfrac_remainder_def [symmetric])
    apply (subst conv'_cfrac_remainder)
     apply auto
    done
  also have "\<dots> = (h' (int l - 1) * x' + h' (int l - 2)) / (k' (int l - 1) * x' + k' (int l - 2))"
    using conv'_num_denom_int[OF x'_pos, of _ l] unfolding h'_def k'_def
    by (simp add: mult_ac)
  finally have "x' * (k' (int l - 1) * x' + k' (int l - 2)) = (h' (int l - 1) * x' + h' (int l - 2))"
    using pos by (simp add: divide_simps)
  hence quadratic: "A * x' ^ 2 + B * x' + C = 0"
    by (simp add: algebra_simps power2_eq_square A_def B_def C_def)
  moreover have "x' \<notin> \<rat>" unfolding x'_def
    by auto
  moreover have "A > 0" using \<open>l > 0\<close> by (auto simp: A_def intro!: k'_pos)
  ultimately have "quadratic_irrational x'" using \<open>x' \<notin> \<rat>\<close>
    by (intro quadratic_irrational.intros[of x' A B C]) simp_all
  thus ?thesis
    using assms by (simp add: x'_def quadratic_irrational_cfrac_remainder_iff)
qed

theorem quadratic_irrational_imp_periodic_cfrac:
  assumes "quadratic_irrational (cfrac_lim e)"
  obtains N l where "l > 0" and "\<And>n m. n \<ge> N \<Longrightarrow> cfrac_nth e (n + m * l) = cfrac_nth e n"
                and "cfrac_remainder e (N + l) = cfrac_remainder e N"
proof -
  have [simp]: "cfrac_length e = \<infinity>"
    using assms by (auto simp: quadratic_irrational.simps)
  note [intro] = assms(1)
  define x where "x = cfrac_lim e"
  from assms obtain a b c :: int where
    nontrivial: "a \<noteq> 0 \<or> b \<noteq> 0 \<or> c \<noteq> 0" and
          root: "a * x^2 + b * x + c = 0" (is "?f x = 0")
    by (auto simp: quadratic_irrational.simps x_def)

  define f where "f = ?f"
  define h and k where "h = conv_num e" and "k = conv_denom e"
  define X where "X = cfrac_remainder e"
  have [simp]: "k i > 0" "k i \<noteq> 0" for i
    using conv_denom_pos[of e i] by (auto simp: k_def)
  have k_leI: "k i \<le> k j" if "i \<le> j" for i j
    by (auto simp: k_def intro!: conv_denom_leI that)
  have k_nonneg: "k n \<ge> 0" for n
    by (auto simp: k_def)
  have k_ge_1: "k n \<ge> 1" for n
    using k_leI[of 0 n] by (simp add: k_def)

  define R where "R = conv e"
  define A where "A = (\<lambda>n. a * h (n - 1) ^ 2 + b * h (n - 1) * k (n - 1) + c * k (n - 1) ^ 2)"
  define B where "B = (\<lambda>n. 2 * a * h (n - 1) * h (n - 2) + b * (h (n - 1) * k (n - 2) + h (n - 2) * k (n - 1)) + 2 * c * k (n - 1) * k (n - 2))"
  define C where "C = (\<lambda>n. a * h (n - 2) ^ 2 + b * h (n - 2) * k (n - 2) + c * k (n - 2) ^ 2)"

  define A' where "A' = nat \<lfloor>2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>a\<bar> + \<bar>b\<bar>\<rfloor>"
  define B' where "B' = nat \<lfloor>(3 / 2) * (2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) + 9 / 4 * \<bar>a\<bar>\<rfloor>"

  have [simp]: "X n \<notin> \<rat>" for n unfolding X_def
    by simp
  from this[of 0] have [simp]: "x \<notin> \<rat>"
    unfolding X_def by (simp add: x_def)

  have "a \<noteq> 0"
  proof
    assume "a = 0"
    with root and nontrivial have "x = 0 \<or> x = -c / b"
      by (auto simp: divide_simps add_eq_0_iff)
    hence "x \<in> \<rat>" by (auto simp del: \<open>x \<notin> \<rat>\<close>)
    thus False by simp
  qed

  have bounds: "(A n, B n, C n) \<in> {-A'..A'} \<times> {-B'..B'} \<times> {-A'..A'}"
   and X_root: "A n * X n ^ 2 + B n * X n + C n = 0" if n: "n \<ge> 2" for n
  proof -
    define n' where "n' = n - 2"
    have n': "n = Suc (Suc n')" using \<open>n \<ge> 2\<close> unfolding n'_def by simp
    have *: "of_int (k (n - Suc 0)) * X n + of_int (k (n - 2)) \<noteq> 0"
    proof
      assume "of_int (k (n - Suc 0)) * X n + of_int (k (n - 2)) = 0"
      hence "X n = -k (n - 2) / k (n - 1)" by (auto simp: divide_simps mult_ac)
      also have "\<dots> \<in> \<rat>" by auto
      finally show False by simp
    qed

    let ?denom = "(k (n - 1) * X n + k (n - 2))"
    have "0 = 0 * ?denom ^ 2" by simp
    also have "0 * ?denom ^ 2 = (a * x ^ 2 + b * x + c) * ?denom ^ 2" using root by simp
    also have "\<dots> = a * (x * ?denom) ^ 2 + b * ?denom * (x * ?denom) + c * ?denom * ?denom"
      by (simp add: algebra_simps power2_eq_square)
    also have "x * ?denom = h (n - 1) * X n + h (n - 2)"
      using cfrac_lim_eq_num_denom_remainder_aux[of "n - 2" e] \<open>n \<ge> 2\<close>
      by (simp add: numeral_2_eq_2 Suc_diff_Suc x_def k_def h_def X_def)
    also have "a * \<dots> ^ 2 + b * ?denom * \<dots> + c * ?denom * ?denom = A n * X n ^ 2 + B n * X n + C n"
      by (simp add: A_def B_def C_def power2_eq_square algebra_simps)
    finally show "A n * X n ^ 2 + B n * X n + C n = 0" ..

    have f_abs_bound: "\<bar>f (R n)\<bar> \<le> (2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) * (1 / (k n * k (Suc n))) +
                                      \<bar>a\<bar> * (1 / (k n * k (Suc n))) ^ 2" for n
    proof -
      have "\<bar>f (R n)\<bar> = \<bar>?f (R n) - ?f x\<bar>" by (simp add: root f_def)
      also have "?f (R n) - ?f x = (R n - x) * (2 * a * x + b) + (R n - x) ^ 2 * a"
        by (simp add: power2_eq_square algebra_simps)
      also have "\<bar>\<dots>\<bar> \<le> \<bar>(R n - x) * (2 * a * x + b)\<bar> + \<bar>(R n - x) ^ 2 * a\<bar>"
        by (rule abs_triangle_ineq)
      also have "\<dots> = \<bar>2 * a * x + b\<bar> * \<bar>R n - x\<bar> + \<bar>a\<bar> * \<bar>R n - x\<bar> ^ 2"
        by (simp add: abs_mult)
      also have "\<dots> \<le> \<bar>2 * a * x + b\<bar> * (1 / (k n * k (Suc n))) + \<bar>a\<bar> * (1 / (k n * k (Suc n))) ^ 2"
        unfolding x_def R_def using cfrac_lim_minus_conv_bounds[of n e]
        by (intro add_mono mult_left_mono power_mono) (auto simp: k_def)
      also have "\<bar>2 * a * x + b\<bar> \<le> 2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>"
        by (rule order.trans[OF abs_triangle_ineq]) (auto simp: abs_mult)
      hence "\<bar>2 * a * x + b\<bar> * (1 / (k n * k (Suc n))) + \<bar>a\<bar> * (1 / (k n * k (Suc n))) ^ 2 \<le>
               \<dots> * (1 / (k n * k (Suc n))) + \<bar>a\<bar> * (1 / (k n * k (Suc n))) ^ 2"
        by (intro add_mono mult_right_mono) (auto intro!: mult_nonneg_nonneg k_nonneg)
      finally show "\<bar>f (R n)\<bar> \<le> \<dots>"
        by (simp add: mult_right_mono add_mono divide_left_mono)
    qed

    have h_eq_conv_k: "h i = R i * k i" for i
      using conv_denom_pos[of e i] unfolding R_def
      by (subst conv_num_denom) (auto simp: h_def k_def)

    have "A n = k (n - 1) ^ 2 * f (R (n - 1))" for n
      by (simp add: algebra_simps A_def n' k_def power2_eq_square h_eq_conv_k f_def)
    have A_bound: "\<bar>A i\<bar> \<le> A'" if "i > 0" for i
    proof -
      have "k i > 0"
        by simp
      hence "k i \<ge> 1"
        by linarith
      have "A i = k (i - 1) ^ 2 * f (R (i - 1))"
        by (simp add: algebra_simps A_def k_def power2_eq_square h_eq_conv_k f_def)
      also have "\<bar>\<dots>\<bar> = k (i - 1) ^ 2 * \<bar>f (R (i - 1))\<bar>"
        by (simp add: abs_mult f_def)
      also have "\<dots> \<le> k (i - 1) ^ 2 * ((2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) * (1 / (k (i - 1) * k (Suc (i - 1)))) +
                        \<bar>a\<bar> * (1 / (k (i - 1) * k (Suc (i - 1)))) ^ 2)"
        by (intro mult_left_mono f_abs_bound) auto
      also have "\<dots> = k (i - 1) / k i * (2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) + \<bar>a\<bar> / k i ^ 2" using \<open>i > 0\<close>
        by (simp add: power2_eq_square field_simps)
      also have "\<dots> \<le> 1 * (2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) + \<bar>a\<bar> / 1" using \<open>i > 0\<close> \<open>k i \<ge> 1\<close>
        by (intro add_mono divide_left_mono mult_right_mono)
           (auto intro!: k_leI one_le_power simp: of_nat_ge_1_iff)
      also have "\<dots> = 2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>a\<bar> + \<bar>b\<bar>" by simp
      finally show ?thesis unfolding A'_def by linarith
    qed

    have "C n = A (n - 1)" by (simp add: A_def C_def n')
    hence C_bound: "\<bar>C n\<bar> \<le> A'" using A_bound[of "n - 1"] n by simp

    have "B n = k (n - 1) * k (n - 2) *
                  (f (R (n - 1)) + f (R (n - 2)) - a * (R (n - 1) - R (n - 2)) ^ 2)"
      by (simp add: B_def h_eq_conv_k algebra_simps power2_eq_square f_def)
    also have "\<bar>\<dots>\<bar> = k (n - 1) * k (n - 2) *
                       \<bar>f (R (n - 1)) + f (R (n - 2)) - a * (R (n - 1) - R (n - 2)) ^ 2\<bar>"
      by (simp add: abs_mult k_nonneg)
    also have "\<dots> \<le> k (n - 1) * k (n - 2) *
                      (((2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) * (1 / (k (n - 1) * k (Suc (n - 1)))) +
                          \<bar>a\<bar> * (1 / (k (n - 1) * k (Suc (n - 1)))) ^ 2) +
                       ((2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) * (1 / (k (n - 2) * k (Suc (n - 2)))) +
                          \<bar>a\<bar> * (1 / (k (n - 2) * k (Suc (n - 2)))) ^ 2) +
                        \<bar>a\<bar> * \<bar>R (Suc (n - 2)) - R (n - 2)\<bar> ^ 2)" (is "_ \<le> _ * (?S1 + ?S2 + ?S3)")
      by (intro mult_left_mono order.trans[OF abs_triangle_ineq4] order.trans[OF abs_triangle_ineq]
            add_mono f_abs_bound order.refl)
         (insert n, auto simp: abs_mult Suc_diff_Suc numeral_2_eq_2 k_nonneg)
    also have "\<bar>R (Suc (n - 2)) - R (n - 2)\<bar> = 1 / (k (n - 2) * k (Suc (n - 2)))"
      unfolding R_def k_def by (rule abs_diff_successive_convs)
    also have "of_int (k (n - 1) * k (n - 2)) * (?S1 + ?S2 + \<bar>a\<bar> * \<dots> ^ 2) =
                 (k (n - 2) / k n + 1) * (2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) +
                 \<bar>a\<bar> * (k (n - 2) / (k (n - 1) * k n ^ 2) + 2 / (k (n - 1) * k (n - 2)))"
      (is "_ = ?S") using n by (simp add: field_simps power2_eq_square numeral_2_eq_2 Suc_diff_Suc)
    also {
      have A: "2 * real_of_int (k (n - 2)) \<le> of_int (k n)"
        using conv_denom_plus2_ratio_ge[of e "n - 2"] n
        by (simp add: numeral_2_eq_2 Suc_diff_Suc k_def)
      have "fib (Suc 2) \<le> k 2" unfolding k_def by (intro conv_denom_lower_bound)
      also have "\<dots> \<le> k n" by (intro k_leI n)
      finally have "k n \<ge> 2" by (simp add: numeral_3_eq_3)
      hence B: "of_int (k (n - 2)) * 2 ^ 2 \<le> (of_int (k (n - 1)) * (of_int (k n))\<^sup>2 :: real)"
        by (intro mult_mono power_mono) (auto intro: k_leI k_nonneg)
      have C: "1 * 1 \<le> real_of_int (k (n - 1)) * of_int (k (n - 2))" using k_ge_1
        by (intro mult_mono) (auto simp: Suc_le_eq of_nat_ge_1_iff k_nonneg)
      note A B C
    }
    hence "?S \<le> (1 / 2 + 1) * (2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) + \<bar>a\<bar> * (1 / 4 + 2)"
      by (intro add_mono mult_right_mono mult_left_mono) (auto simp: field_simps)
    also have "\<dots> = (3 / 2) * (2 * \<bar>a\<bar> * \<bar>x\<bar> + \<bar>b\<bar>) + 9 / 4 * \<bar>a\<bar>" by simp
    finally have B_bound: "\<bar>B n\<bar> \<le> B'" unfolding B'_def by linarith
    from A_bound[of n] B_bound C_bound n
    show "(A n, B n, C n) \<in> {-A'..A'} \<times> {-B'..B'} \<times> {-A'..A'}" by auto
  qed

  have A_nz: "A n \<noteq> 0" if "n \<ge> 1" for n
    using that
  proof (induction n rule: dec_induct)
    case base
    show ?case
    proof
      assume "A 1 = 0"
      hence "real_of_int (A 1) = 0" by simp
      also have "real_of_int (A 1) =
                   real_of_int a * of_int (cfrac_nth e 0) ^ 2 +
                   real_of_int b * cfrac_nth e 0 + real_of_int c"
        by (simp add: A_def h_def k_def)
      finally have root': "\<dots> = 0" .

      have "cfrac_nth e 0 \<in> \<rat>" by auto
      also from root' and \<open>a \<noteq> 0\<close> have "?this \<longleftrightarrow> is_square (nat (b\<^sup>2 - 4 * a * c))"
        by (intro quadratic_equation_solution_rat_iff) auto
      also from root and \<open>a \<noteq> 0\<close> have "\<dots> \<longleftrightarrow> x \<in> \<rat>"
        by (intro quadratic_equation_solution_rat_iff [symmetric]) auto
      finally show False using \<open>x \<notin> \<rat>\<close> by contradiction
    qed
  next
    case (step m)
    hence nz: "C (Suc m) \<noteq> 0" by (simp add: C_def A_def)
    show "A (Suc m) \<noteq> 0"
    proof
      assume [simp]: "A (Suc m) = 0"
      have "X (Suc m) > 0" unfolding X_def
        by (intro cfrac_remainder_pos) auto
      with X_root[of "Suc m"] step.hyps nz have "X (Suc m) = -C (Suc m) / B (Suc m)"
        by (auto simp: divide_simps mult_ac)
      also have "\<dots> \<in> \<rat>" by auto
      finally show False by simp
    qed
  qed

  have "finite ({-A'..A'} \<times> {-B'..B'} \<times> {-A'..A'})" by auto
  from this and bounds have "finite ((\<lambda>n. (A n, B n, C n)) ` {2..})"
    by (blast intro: finite_subset)
  moreover have "infinite ({2..} :: nat set)" by (simp add: infinite_Ici)
  ultimately have "\<exists>k1\<in>{2..}. infinite {n \<in> {2..}. (A n, B n, C n) = (A k1, B k1, C k1)}"
    by (intro pigeonhole_infinite)
  then obtain k0 where k0: "k0 \<ge> 2" "infinite {n \<in> {2..}. (A n, B n, C n) = (A k0, B k0, C k0)}"
    by auto
  from infinite_countable_subset[OF this(2)] obtain g :: "nat \<Rightarrow> _"
    where g: "inj g" "range g \<subseteq> {n\<in>{2..}. (A n, B n, C n) = (A k0, B k0, C k0)}" by blast
  hence g_ge_2: "g k \<ge> 2" for k by auto
  from g have [simp]: "A (g k) = A k0" "B (g k) = B k0" "C (g k) = C k0" for k
    by auto

  from g(1) have [simp]: "g k1 = g k2 \<longleftrightarrow> k1 = k2" for k1 k2 by (auto simp: inj_def)
  define z where "z = (A k0, B k0, C k0)"
  let ?h = "\<lambda>k. (A (g k), B (g k), C (g k))"
  from g have g': "distinct [g 1, g 2, g 3]" "?h 0 = z" "?h 1 = z" "?h 2 = z"
    by (auto simp: z_def)
  have fin: "finite {x :: real. A k0 * x ^ 2 + B k0 * x + C k0 = 0}" using A_nz[of k0] k0(1)
    by (subst finite_quadratic_equation_solutions_reals) auto
  from X_root[of "g 0"] X_root[of "g 1"] X_root[of "g 2"] g_ge_2 g
    have "(X \<circ> g) ` {0, 1, 2} \<subseteq> {x. A k0 * x ^ 2 + B k0 * x + C k0 = 0}"
    by auto
  hence "card ((X \<circ> g) ` {0, 1, 2}) \<le> card \<dots>"
    by (intro card_mono fin) auto
  also have "\<dots> \<le> 2"
    by (rule card_quadratic_equation_solutions_reals_le_2)
  also have "\<dots> < card {0, 1, 2 :: nat}" by simp
  finally have "\<not>inj_on (X \<circ> g) {0, 1, 2}"
    by (rule pigeonhole)
  then obtain m1 m2 where
    m12: "m1 \<in> {0, 1, 2}" "m2 \<in> {0, 1, 2}" "X (g m1) = X (g m2)" "m1 \<noteq> m2"
    unfolding inj_on_def o_def by blast
  define n and l where "n = min (g m1) (g m2)" and "l = nat \<bar>int (g m1) - g m2\<bar>"
  with m12 g' have l: "l > 0" "X (n + l) = X n"
    by (auto simp: min_def nat_diff_distrib split: if_splits)

  from l have "cfrac_lim (cfrac_drop (n + l) e) = cfrac_lim (cfrac_drop n e)"
    by (simp add: X_def cfrac_remainder_def)
  hence "cfrac_drop (n + l) e = cfrac_drop n e"
    by (simp add: cfrac_lim_eq_iff)
  hence "cfrac_nth (cfrac_drop (n + l) e) = cfrac_nth (cfrac_drop n e)"
    by (simp only:)
  hence period: "cfrac_nth e (n + l + k) = cfrac_nth e (n + k)" for k
    by (simp add: fun_eq_iff add_ac)
  have period: "cfrac_nth e (k + l) = cfrac_nth e k" if "k \<ge> n" for k
    using period[of "k - n"] that by (simp add: add_ac)
  have period: "cfrac_nth e (k + m * l) = cfrac_nth e k" if "k \<ge> n" for k m
    using that
  proof (induction m)
    case (Suc m)
    have "cfrac_nth e (k + Suc m * l) = cfrac_nth e (k + m * l + l)"
      by (simp add: algebra_simps)
    also have "\<dots> = cfrac_nth e (k + m * l)"
      using Suc.prems by (intro period) auto
    also have "\<dots> = cfrac_nth e k"
      using Suc.prems by (intro Suc.IH) auto
    finally show ?case .
  qed simp_all

  from this and l and that[of l n] show ?thesis by (simp add: X_def)
qed

theorem periodic_cfrac_iff_quadratic_irrational:
  assumes "x \<notin> \<rat>" "x \<ge> 0"
  shows   "quadratic_irrational x \<longleftrightarrow>
             (\<exists>N l. l > 0 \<and> (\<forall>n\<ge>N. cfrac_nth (cfrac_of_real x) (n + l) = cfrac_nth (cfrac_of_real x) n))"
proof safe
  assume *: "quadratic_irrational x"
  with assms have "quadratic_irrational (cfrac_lim (cfrac_of_real x))" by auto
  from quadratic_irrational_imp_periodic_cfrac [OF this] guess N l . note Nl = this
  show "\<exists>N l. l > 0 \<and> (\<forall>n\<ge>N. cfrac_nth (cfrac_of_real x) (n + l) = cfrac_nth (cfrac_of_real x) n)"
    by (rule exI[of _ N], rule exI[of _ l]) (insert Nl(1) Nl(2)[of _ 1], auto)
next
  fix N l assume "l > 0" "\<forall>n\<ge>N. cfrac_nth (cfrac_of_real x) (n + l) = cfrac_nth (cfrac_of_real x) n"
  hence "quadratic_irrational (cfrac_lim (cfrac_of_real x))" using assms
    by (intro periodic_cfrac_imp_quadratic_irrational[of _ l N]) auto
  with assms show "quadratic_irrational x"
    by simp
qed

text \<open>
  The following result can e.g. be used to show that a number is \<^emph>\<open>not\<close> a quadratic
  irrational.
\<close>
lemma quadratic_irrational_cfrac_nth_range_finite:
  assumes "quadratic_irrational (cfrac_lim e)"
  shows   "finite (range (cfrac_nth e))"
proof -
  from quadratic_irrational_imp_periodic_cfrac[OF assms] obtain l N
    where period: "l > 0" "\<And>m n. n \<ge> N \<Longrightarrow> cfrac_nth e (n + m * l) = cfrac_nth e n"
    by metis
  have "cfrac_nth e k \<in> cfrac_nth e ` {..<N+l}" for k
  proof (cases "k < N + l")
    case False
    define n m where "n = N + (k - N) mod l" and "m = (k - N) div l"
    have "cfrac_nth e n \<in> cfrac_nth e ` {..<N+l}"
      using \<open>l > 0\<close> by (intro imageI) (auto simp: n_def)
    also have "cfrac_nth e n = cfrac_nth e (n + m * l)"
      by (subst period) (auto simp: n_def)
    also have "n + m * l = k"
      using False by (simp add: n_def m_def)
    finally show ?thesis .
  qed auto
  hence "range (cfrac_nth e) \<subseteq> cfrac_nth e ` {..<N+l}"
    by blast
  thus ?thesis by (rule finite_subset) auto
qed

end