(*  Title:       HOL/Complex.thy
    Author:      Jacques D. Fleuriot, 2001 University of Edinburgh
    Author:      Lawrence C Paulson, 2003/4
*)

section \<open>Complex Numbers: Rectangular and Polar Representations\<close>

theory Complex
imports Transcendental
begin

text \<open>
  We use the \<^theory_text>\<open>codatatype\<close> command to define the type of complex numbers. This
  allows us to use \<^theory_text>\<open>primcorec\<close> to define complex functions by defining their
  real and imaginary result separately.
\<close>

codatatype complex = Complex (Re: real) (Im: real)

lemma complex_surj: "Complex (Re z) (Im z) = z"
  by (rule complex.collapse)

lemma complex_eqI [intro?]: "Re x = Re y \<Longrightarrow> Im x = Im y \<Longrightarrow> x = y"
  by (rule complex.expand) simp

lemma complex_eq_iff: "x = y \<longleftrightarrow> Re x = Re y \<and> Im x = Im y"
  by (auto intro: complex.expand)

subsection \<open>Addition and Subtraction\<close>

instantiation complex :: ab_group_add
begin

primcorec zero_complex
  where
    "Re 0 = 0"
  | "Im 0 = 0"

primcorec plus_complex
  where
    "Re (x + y) = Re x + Re y"
  | "Im (x + y) = Im x + Im y"

primcorec uminus_complex
  where
    "Re (- x) = - Re x"
  | "Im (- x) = - Im x"

primcorec minus_complex
  where
    "Re (x - y) = Re x - Re y"
  | "Im (x - y) = Im x - Im y"

instance
  by standard (simp_all add: complex_eq_iff)

end

subsection \<open>Multiplication and Division\<close>

instantiation complex :: field
begin

primcorec one_complex
  where
    "Re 1 = 1"
  | "Im 1 = 0"

primcorec times_complex
  where
    "Re (x * y) = Re x * Re y - Im x * Im y"
  | "Im (x * y) = Re x * Im y + Im x * Re y"

primcorec inverse_complex
  where
    "Re (inverse x) = Re x / ((Re x)\<^sup>2 + (Im x)\<^sup>2)"
  | "Im (inverse x) = - Im x / ((Re x)\<^sup>2 + (Im x)\<^sup>2)"

definition "x div y = x * inverse y" for x y :: complex

instance
  by standard
     (simp_all add: complex_eq_iff divide_complex_def
      distrib_left distrib_right right_diff_distrib left_diff_distrib
      power2_eq_square add_divide_distrib [symmetric])

end

lemma Re_divide: "Re (x / y) = (Re x * Re y + Im x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2)"
  by (simp add: divide_complex_def add_divide_distrib)

lemma Im_divide: "Im (x / y) = (Im x * Re y - Re x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2)"
  by (simp add: divide_complex_def diff_divide_distrib)

lemma Complex_divide:
    "(x / y) = Complex ((Re x * Re y + Im x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2))
                       ((Im x * Re y - Re x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2))"
  by (metis Im_divide Re_divide complex_surj)

lemma Re_power2: "Re (x ^ 2) = (Re x)^2 - (Im x)^2"
  by (simp add: power2_eq_square)

lemma Im_power2: "Im (x ^ 2) = 2 * Re x * Im x"
  by (simp add: power2_eq_square)

lemma Re_power_real [simp]: "Im x = 0 \<Longrightarrow> Re (x ^ n) = Re x ^ n "
  by (induct n) simp_all

lemma Im_power_real [simp]: "Im x = 0 \<Longrightarrow> Im (x ^ n) = 0"
  by (induct n) simp_all

subsection \<open>Scalar Multiplication\<close>

instantiation complex :: real_field
begin

primcorec scaleR_complex
  where
    "Re (scaleR r x) = r * Re x"
  | "Im (scaleR r x) = r * Im x"

instance
proof
  fix a b :: real and x y :: complex
  show "scaleR a (x + y) = scaleR a x + scaleR a y"
    by (simp add: complex_eq_iff distrib_left)
  show "scaleR (a + b) x = scaleR a x + scaleR b x"
    by (simp add: complex_eq_iff distrib_right)
  show "scaleR a (scaleR b x) = scaleR (a * b) x"
    by (simp add: complex_eq_iff mult.assoc)
  show "scaleR 1 x = x"
    by (simp add: complex_eq_iff)
  show "scaleR a x * y = scaleR a (x * y)"
    by (simp add: complex_eq_iff algebra_simps)
  show "x * scaleR a y = scaleR a (x * y)"
    by (simp add: complex_eq_iff algebra_simps)
qed

end

subsection \<open>Numerals, Arithmetic, and Embedding from R\<close>

abbreviation complex_of_real :: "real \<Rightarrow> complex"
  where "complex_of_real \<equiv> of_real"

declare [[coercion "of_real :: real \<Rightarrow> complex"]]
declare [[coercion "of_rat :: rat \<Rightarrow> complex"]]
declare [[coercion "of_int :: int \<Rightarrow> complex"]]
declare [[coercion "of_nat :: nat \<Rightarrow> complex"]]

lemma complex_Re_of_nat [simp]: "Re (of_nat n) = of_nat n"
  by (induct n) simp_all

lemma complex_Im_of_nat [simp]: "Im (of_nat n) = 0"
  by (induct n) simp_all

lemma complex_Re_of_int [simp]: "Re (of_int z) = of_int z"
  by (cases z rule: int_diff_cases) simp

lemma complex_Im_of_int [simp]: "Im (of_int z) = 0"
  by (cases z rule: int_diff_cases) simp

lemma complex_Re_numeral [simp]: "Re (numeral v) = numeral v"
  using complex_Re_of_int [of "numeral v"] by simp

lemma complex_Im_numeral [simp]: "Im (numeral v) = 0"
  using complex_Im_of_int [of "numeral v"] by simp

lemma Re_complex_of_real [simp]: "Re (complex_of_real z) = z"
  by (simp add: of_real_def)

lemma Im_complex_of_real [simp]: "Im (complex_of_real z) = 0"
  by (simp add: of_real_def)

lemma Re_divide_numeral [simp]: "Re (z / numeral w) = Re z / numeral w"
  by (simp add: Re_divide sqr_conv_mult)

lemma Im_divide_numeral [simp]: "Im (z / numeral w) = Im z / numeral w"
  by (simp add: Im_divide sqr_conv_mult)

lemma Re_divide_of_nat [simp]: "Re (z / of_nat n) = Re z / of_nat n"
  by (cases n) (simp_all add: Re_divide field_split_simps power2_eq_square del: of_nat_Suc)

lemma Im_divide_of_nat [simp]: "Im (z / of_nat n) = Im z / of_nat n"
  by (cases n) (simp_all add: Im_divide field_split_simps power2_eq_square del: of_nat_Suc)

lemma of_real_Re [simp]: "z \<in> \<real> \<Longrightarrow> of_real (Re z) = z"
  by (auto simp: Reals_def)

lemma complex_Re_fact [simp]: "Re (fact n) = fact n"
proof -
  have "(fact n :: complex) = of_real (fact n)"
    by simp
  also have "Re \<dots> = fact n"
    by (subst Re_complex_of_real) simp_all
  finally show ?thesis .
qed

lemma complex_Im_fact [simp]: "Im (fact n) = 0"
  by (subst of_nat_fact [symmetric]) (simp only: complex_Im_of_nat)

lemma Re_prod_Reals: "(\<And>x. x \<in> A \<Longrightarrow> f x \<in> \<real>) \<Longrightarrow> Re (prod f A) = prod (\<lambda>x. Re (f x)) A"
proof (induction A rule: infinite_finite_induct)
  case (insert x A)
  hence "Re (prod f (insert x A)) = Re (f x) * Re (prod f A) - Im (f x) * Im (prod f A)"
    by simp
  also from insert.prems have "f x \<in> \<real>" by simp
  hence "Im (f x) = 0" by (auto elim!: Reals_cases)
  also have "Re (prod f A) = (\<Prod>x\<in>A. Re (f x))"
    by (intro insert.IH insert.prems) auto
  finally show ?case using insert.hyps by simp
qed auto

subsection \<open>The Complex Number $i$\<close>

primcorec imaginary_unit :: complex  ("\<i>")
  where
    "Re \<i> = 0"
  | "Im \<i> = 1"

lemma Complex_eq: "Complex a b = a + \<i> * b"
  by (simp add: complex_eq_iff)

lemma complex_eq: "a = Re a + \<i> * Im a"
  by (simp add: complex_eq_iff)

lemma fun_complex_eq: "f = (\<lambda>x. Re (f x) + \<i> * Im (f x))"
  by (simp add: fun_eq_iff complex_eq)

lemma i_squared [simp]: "\<i> * \<i> = -1"
  by (simp add: complex_eq_iff)

lemma power2_i [simp]: "\<i>\<^sup>2 = -1"
  by (simp add: power2_eq_square)

lemma inverse_i [simp]: "inverse \<i> = - \<i>"
  by (rule inverse_unique) simp

lemma divide_i [simp]: "x / \<i> = - \<i> * x"
  by (simp add: divide_complex_def)

lemma complex_i_mult_minus [simp]: "\<i> * (\<i> * x) = - x"
  by (simp add: mult.assoc [symmetric])

lemma complex_i_not_zero [simp]: "\<i> \<noteq> 0"
  by (simp add: complex_eq_iff)

lemma complex_i_not_one [simp]: "\<i> \<noteq> 1"
  by (simp add: complex_eq_iff)

lemma complex_i_not_numeral [simp]: "\<i> \<noteq> numeral w"
  by (simp add: complex_eq_iff)

lemma complex_i_not_neg_numeral [simp]: "\<i> \<noteq> - numeral w"
  by (simp add: complex_eq_iff)

lemma complex_split_polar: "\<exists>r a. z = complex_of_real r * (cos a + \<i> * sin a)"
  by (simp add: complex_eq_iff polar_Ex)

lemma i_even_power [simp]: "\<i> ^ (n * 2) = (-1) ^ n"
  by (metis mult.commute power2_i power_mult)

lemma Re_i_times [simp]: "Re (\<i> * z) = - Im z"
  by simp

lemma Im_i_times [simp]: "Im (\<i> * z) = Re z"
  by simp

lemma i_times_eq_iff: "\<i> * w = z \<longleftrightarrow> w = - (\<i> * z)"
  by auto

lemma divide_numeral_i [simp]: "z / (numeral n * \<i>) = - (\<i> * z) / numeral n"
  by (metis divide_divide_eq_left divide_i mult.commute mult_minus_right)

lemma imaginary_eq_real_iff [simp]:
  assumes "y \<in> Reals" "x \<in> Reals"
  shows "\<i> * y = x \<longleftrightarrow> x=0 \<and> y=0"
  by (metis Im_complex_of_real Im_i_times assms mult_zero_right of_real_0 of_real_Re)

lemma real_eq_imaginary_iff [simp]:
  assumes "y \<in> Reals" "x \<in> Reals"
  shows "x = \<i> * y  \<longleftrightarrow> x=0 \<and> y=0"
    using assms imaginary_eq_real_iff by fastforce

subsection \<open>Vector Norm\<close>

instantiation complex :: real_normed_field
begin

definition "norm z = sqrt ((Re z)\<^sup>2 + (Im z)\<^sup>2)"

abbreviation cmod :: "complex \<Rightarrow> real"
  where "cmod \<equiv> norm"

definition complex_sgn_def: "sgn x = x /\<^sub>R cmod x"

definition dist_complex_def: "dist x y = cmod (x - y)"

definition uniformity_complex_def [code del]:
  "(uniformity :: (complex \<times> complex) filter) = (INF e\<in>{0 <..}. principal {(x, y). dist x y < e})"

definition open_complex_def [code del]:
  "open (U :: complex set) \<longleftrightarrow> (\<forall>x\<in>U. eventually (\<lambda>(x', y). x' = x \<longrightarrow> y \<in> U) uniformity)"

instance
proof
  fix r :: real and x y :: complex and S :: "complex set"
  show "(norm x = 0) = (x = 0)"
    by (simp add: norm_complex_def complex_eq_iff)
  show "norm (x + y) \<le> norm x + norm y"
    by (simp add: norm_complex_def complex_eq_iff real_sqrt_sum_squares_triangle_ineq)
  show "norm (scaleR r x) = \<bar>r\<bar> * norm x"
    by (simp add: norm_complex_def complex_eq_iff power_mult_distrib distrib_left [symmetric]
        real_sqrt_mult)
  show "norm (x * y) = norm x * norm y"
    by (simp add: norm_complex_def complex_eq_iff real_sqrt_mult [symmetric]
        power2_eq_square algebra_simps)
qed (rule complex_sgn_def dist_complex_def open_complex_def uniformity_complex_def)+

end

declare uniformity_Abort[where 'a = complex, code]

lemma norm_ii [simp]: "norm \<i> = 1"
  by (simp add: norm_complex_def)

lemma cmod_unit_one: "cmod (cos a + \<i> * sin a) = 1"
  by (simp add: norm_complex_def)

lemma cmod_complex_polar: "cmod (r * (cos a + \<i> * sin a)) = \<bar>r\<bar>"
  by (simp add: norm_mult cmod_unit_one)

lemma complex_Re_le_cmod: "Re x \<le> cmod x"
  unfolding norm_complex_def by (rule real_sqrt_sum_squares_ge1)

lemma complex_mod_minus_le_complex_mod: "- cmod x \<le> cmod x"
  by (rule order_trans [OF _ norm_ge_zero]) simp

lemma complex_mod_triangle_ineq2: "cmod (b + a) - cmod b \<le> cmod a"
  by (rule ord_le_eq_trans [OF norm_triangle_ineq2]) simp

lemma abs_Re_le_cmod: "\<bar>Re x\<bar> \<le> cmod x"
  by (simp add: norm_complex_def)

lemma abs_Im_le_cmod: "\<bar>Im x\<bar> \<le> cmod x"
  by (simp add: norm_complex_def)

lemma cmod_le: "cmod z \<le> \<bar>Re z\<bar> + \<bar>Im z\<bar>"
  using norm_complex_def sqrt_sum_squares_le_sum_abs by presburger

lemma cmod_eq_Re: "Im z = 0 \<Longrightarrow> cmod z = \<bar>Re z\<bar>"
  by (simp add: norm_complex_def)

lemma cmod_eq_Im: "Re z = 0 \<Longrightarrow> cmod z = \<bar>Im z\<bar>"
  by (simp add: norm_complex_def)

lemma cmod_power2: "(cmod z)\<^sup>2 = (Re z)\<^sup>2 + (Im z)\<^sup>2"
  by (simp add: norm_complex_def)

lemma cmod_plus_Re_le_0_iff: "cmod z + Re z \<le> 0 \<longleftrightarrow> Re z = - cmod z"
  using abs_Re_le_cmod[of z] by auto

lemma cmod_Re_le_iff: "Im x = Im y \<Longrightarrow> cmod x \<le> cmod y \<longleftrightarrow> \<bar>Re x\<bar> \<le> \<bar>Re y\<bar>"
  by (metis add.commute add_le_cancel_left norm_complex_def real_sqrt_abs real_sqrt_le_iff)

lemma cmod_Im_le_iff: "Re x = Re y \<Longrightarrow> cmod x \<le> cmod y \<longleftrightarrow> \<bar>Im x\<bar> \<le> \<bar>Im y\<bar>"
  by (metis add_le_cancel_left norm_complex_def real_sqrt_abs real_sqrt_le_iff)

lemma Im_eq_0: "\<bar>Re z\<bar> = cmod z \<Longrightarrow> Im z = 0"
  by (subst (asm) power_eq_iff_eq_base[symmetric, where n=2]) (auto simp add: norm_complex_def)

lemma abs_sqrt_wlog: "(\<And>x. x \<ge> 0 \<Longrightarrow> P x (x\<^sup>2)) \<Longrightarrow> P \<bar>x\<bar> (x\<^sup>2)"
  for x::"'a::linordered_idom"
  by (metis abs_ge_zero power2_abs)

lemma complex_abs_le_norm: "\<bar>Re z\<bar> + \<bar>Im z\<bar> \<le> sqrt 2 * norm z"
  unfolding norm_complex_def
  apply (rule abs_sqrt_wlog [where x="Re z"])
  apply (rule abs_sqrt_wlog [where x="Im z"])
  apply (rule power2_le_imp_le)
   apply (simp_all add: power2_sum add.commute sum_squares_bound real_sqrt_mult [symmetric])
  done

lemma complex_unit_circle: "z \<noteq> 0 \<Longrightarrow> (Re z / cmod z)\<^sup>2 + (Im z / cmod z)\<^sup>2 = 1"
  by (simp add: norm_complex_def complex_eq_iff power2_eq_square add_divide_distrib [symmetric])

text \<open>Properties of complex signum.\<close>

lemma sgn_eq: "sgn z = z / complex_of_real (cmod z)"
  by (simp add: sgn_div_norm divide_inverse scaleR_conv_of_real mult.commute)

lemma Re_sgn [simp]: "Re(sgn z) = Re(z)/cmod z"
  by (simp add: complex_sgn_def divide_inverse)

lemma Im_sgn [simp]: "Im(sgn z) = Im(z)/cmod z"
  by (simp add: complex_sgn_def divide_inverse)

subsection \<open>Absolute value\<close>

instantiation complex :: field_abs_sgn
begin

definition abs_complex :: "complex \<Rightarrow> complex"
  where "abs_complex = of_real \<circ> norm"

instance
  proof qed (auto simp add: abs_complex_def complex_sgn_def norm_divide norm_mult scaleR_conv_of_real field_simps)
end

subsection \<open>Completeness of the Complexes\<close>

lemma bounded_linear_Re: "bounded_linear Re"
  by (rule bounded_linear_intro [where K=1]) (simp_all add: norm_complex_def)

lemma bounded_linear_Im: "bounded_linear Im"
  by (rule bounded_linear_intro [where K=1]) (simp_all add: norm_complex_def)

lemmas Cauchy_Re = bounded_linear.Cauchy [OF bounded_linear_Re]
lemmas Cauchy_Im = bounded_linear.Cauchy [OF bounded_linear_Im]
lemmas tendsto_Re [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_Re]
lemmas tendsto_Im [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_Im]
lemmas isCont_Re [simp] = bounded_linear.isCont [OF bounded_linear_Re]
lemmas isCont_Im [simp] = bounded_linear.isCont [OF bounded_linear_Im]
lemmas continuous_Re [simp] = bounded_linear.continuous [OF bounded_linear_Re]
lemmas continuous_Im [simp] = bounded_linear.continuous [OF bounded_linear_Im]
lemmas continuous_on_Re [continuous_intros] = bounded_linear.continuous_on[OF bounded_linear_Re]
lemmas continuous_on_Im [continuous_intros] = bounded_linear.continuous_on[OF bounded_linear_Im]
lemmas has_derivative_Re [derivative_intros] = bounded_linear.has_derivative[OF bounded_linear_Re]
lemmas has_derivative_Im [derivative_intros] = bounded_linear.has_derivative[OF bounded_linear_Im]
lemmas sums_Re = bounded_linear.sums [OF bounded_linear_Re]
lemmas sums_Im = bounded_linear.sums [OF bounded_linear_Im]
lemmas Re_suminf = bounded_linear.suminf[OF bounded_linear_Re]
lemmas Im_suminf = bounded_linear.suminf[OF bounded_linear_Im]

lemma tendsto_Complex [tendsto_intros]:
  "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. Complex (f x) (g x)) \<longlongrightarrow> Complex a b) F"
  unfolding Complex_eq by (auto intro!: tendsto_intros)

lemma tendsto_complex_iff:
  "(f \<longlongrightarrow> x) F \<longleftrightarrow> (((\<lambda>x. Re (f x)) \<longlongrightarrow> Re x) F \<and> ((\<lambda>x. Im (f x)) \<longlongrightarrow> Im x) F)"
proof safe
  assume "((\<lambda>x. Re (f x)) \<longlongrightarrow> Re x) F" "((\<lambda>x. Im (f x)) \<longlongrightarrow> Im x) F"
  from tendsto_Complex[OF this] show "(f \<longlongrightarrow> x) F"
    unfolding complex.collapse .
qed (auto intro: tendsto_intros)

lemma continuous_complex_iff:
  "continuous F f \<longleftrightarrow> continuous F (\<lambda>x. Re (f x)) \<and> continuous F (\<lambda>x. Im (f x))"
  by (simp only: continuous_def tendsto_complex_iff)

lemma continuous_on_of_real_o_iff [simp]:
     "continuous_on S (\<lambda>x. complex_of_real (g x)) = continuous_on S g"
  using continuous_on_Re continuous_on_of_real  by fastforce

lemma continuous_on_of_real_id [simp]:
     "continuous_on S (of_real :: real \<Rightarrow> 'a::real_normed_algebra_1)"
  by (rule continuous_on_of_real [OF continuous_on_id])

lemma has_vector_derivative_complex_iff: "(f has_vector_derivative x) F \<longleftrightarrow>
    ((\<lambda>x. Re (f x)) has_field_derivative (Re x)) F \<and>
    ((\<lambda>x. Im (f x)) has_field_derivative (Im x)) F"
  by (simp add: has_vector_derivative_def has_field_derivative_def has_derivative_def
      tendsto_complex_iff algebra_simps bounded_linear_scaleR_left bounded_linear_mult_right)

lemma has_field_derivative_Re[derivative_intros]:
  "(f has_vector_derivative D) F \<Longrightarrow> ((\<lambda>x. Re (f x)) has_field_derivative (Re D)) F"
  unfolding has_vector_derivative_complex_iff by safe

lemma has_field_derivative_Im[derivative_intros]:
  "(f has_vector_derivative D) F \<Longrightarrow> ((\<lambda>x. Im (f x)) has_field_derivative (Im D)) F"
  unfolding has_vector_derivative_complex_iff by safe

instance complex :: banach
proof
  fix X :: "nat \<Rightarrow> complex"
  assume X: "Cauchy X"
  then have "(\<lambda>n. Complex (Re (X n)) (Im (X n))) \<longlonglongrightarrow>
    Complex (lim (\<lambda>n. Re (X n))) (lim (\<lambda>n. Im (X n)))"
    by (intro tendsto_Complex convergent_LIMSEQ_iff[THEN iffD1]
        Cauchy_convergent_iff[THEN iffD1] Cauchy_Re Cauchy_Im)
  then show "convergent X"
    unfolding complex.collapse by (rule convergentI)
qed

declare DERIV_power[where 'a=complex, unfolded of_nat_def[symmetric], derivative_intros]

subsection \<open>Complex Conjugation\<close>

primcorec cnj :: "complex \<Rightarrow> complex"
  where
    "Re (cnj z) = Re z"
  | "Im (cnj z) = - Im z"

lemma complex_cnj_cancel_iff [simp]: "cnj x = cnj y \<longleftrightarrow> x = y"
  by (simp add: complex_eq_iff)

lemma complex_cnj_cnj [simp]: "cnj (cnj z) = z"
  by (simp add: complex_eq_iff)

lemma complex_cnj_zero [simp]: "cnj 0 = 0"
  by (simp add: complex_eq_iff)

lemma complex_cnj_zero_iff [iff]: "cnj z = 0 \<longleftrightarrow> z = 0"
  by (simp add: complex_eq_iff)

lemma complex_cnj_one_iff [simp]: "cnj z = 1 \<longleftrightarrow> z = 1"
  by (simp add: complex_eq_iff)

lemma complex_cnj_add [simp]: "cnj (x + y) = cnj x + cnj y"
  by (simp add: complex_eq_iff)

lemma cnj_sum [simp]: "cnj (sum f s) = (\<Sum>x\<in>s. cnj (f x))"
  by (induct s rule: infinite_finite_induct) auto

lemma complex_cnj_diff [simp]: "cnj (x - y) = cnj x - cnj y"
  by (simp add: complex_eq_iff)

lemma complex_cnj_minus [simp]: "cnj (- x) = - cnj x"
  by (simp add: complex_eq_iff)

lemma complex_cnj_one [simp]: "cnj 1 = 1"
  by (simp add: complex_eq_iff)

lemma complex_cnj_mult [simp]: "cnj (x * y) = cnj x * cnj y"
  by (simp add: complex_eq_iff)

lemma cnj_prod [simp]: "cnj (prod f s) = (\<Prod>x\<in>s. cnj (f x))"
  by (induct s rule: infinite_finite_induct) auto

lemma complex_cnj_inverse [simp]: "cnj (inverse x) = inverse (cnj x)"
  by (simp add: complex_eq_iff)

lemma complex_cnj_divide [simp]: "cnj (x / y) = cnj x / cnj y"
  by (simp add: divide_complex_def)

lemma complex_cnj_power [simp]: "cnj (x ^ n) = cnj x ^ n"
  by (induct n) simp_all

lemma complex_cnj_of_nat [simp]: "cnj (of_nat n) = of_nat n"
  by (simp add: complex_eq_iff)

lemma complex_cnj_of_int [simp]: "cnj (of_int z) = of_int z"
  by (simp add: complex_eq_iff)

lemma complex_cnj_numeral [simp]: "cnj (numeral w) = numeral w"
  by (simp add: complex_eq_iff)

lemma complex_cnj_neg_numeral [simp]: "cnj (- numeral w) = - numeral w"
  by (simp add: complex_eq_iff)

lemma complex_cnj_scaleR [simp]: "cnj (scaleR r x) = scaleR r (cnj x)"
  by (simp add: complex_eq_iff)

lemma complex_mod_cnj [simp]: "cmod (cnj z) = cmod z"
  by (simp add: norm_complex_def)

lemma complex_cnj_complex_of_real [simp]: "cnj (of_real x) = of_real x"
  by (simp add: complex_eq_iff)

lemma complex_cnj_i [simp]: "cnj \<i> = - \<i>"
  by (simp add: complex_eq_iff)

lemma complex_add_cnj: "z + cnj z = complex_of_real (2 * Re z)"
  by (simp add: complex_eq_iff)

lemma complex_diff_cnj: "z - cnj z = complex_of_real (2 * Im z) * \<i>"
  by (simp add: complex_eq_iff)

lemma Ints_cnj [intro]: "x \<in> \<int> \<Longrightarrow> cnj x \<in> \<int>"
  by (auto elim!: Ints_cases)

lemma cnj_in_Ints_iff [simp]: "cnj x \<in> \<int> \<longleftrightarrow> x \<in> \<int>"
  using Ints_cnj[of x] Ints_cnj[of "cnj x"] by auto

lemma complex_mult_cnj: "z * cnj z = complex_of_real ((Re z)\<^sup>2 + (Im z)\<^sup>2)"
  by (simp add: complex_eq_iff power2_eq_square)

lemma cnj_add_mult_eq_Re: "z * cnj w + cnj z * w = 2 * Re (z * cnj w)"
  by (rule complex_eqI) auto

lemma complex_mod_mult_cnj: "cmod (z * cnj z) = (cmod z)\<^sup>2"
  by (simp add: norm_mult power2_eq_square)

lemma complex_mod_sqrt_Re_mult_cnj: "cmod z = sqrt (Re (z * cnj z))"
  by (simp add: norm_complex_def power2_eq_square)

lemma complex_In_mult_cnj_zero [simp]: "Im (z * cnj z) = 0"
  by simp

lemma complex_cnj_fact [simp]: "cnj (fact n) = fact n"
  by (subst of_nat_fact [symmetric], subst complex_cnj_of_nat) simp

lemma complex_cnj_pochhammer [simp]: "cnj (pochhammer z n) = pochhammer (cnj z) n"
  by (induct n arbitrary: z) (simp_all add: pochhammer_rec)

lemma bounded_linear_cnj: "bounded_linear cnj"
  using complex_cnj_add complex_cnj_scaleR by (rule bounded_linear_intro [where K=1]) simp

lemma linear_cnj: "linear cnj"
  using bounded_linear.linear[OF bounded_linear_cnj] .

lemmas tendsto_cnj [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_cnj]
  and isCont_cnj [simp] = bounded_linear.isCont [OF bounded_linear_cnj]
  and continuous_cnj [simp, continuous_intros] = bounded_linear.continuous [OF bounded_linear_cnj]
  and continuous_on_cnj [simp, continuous_intros] = bounded_linear.continuous_on [OF bounded_linear_cnj]
  and has_derivative_cnj [simp, derivative_intros] = bounded_linear.has_derivative [OF bounded_linear_cnj]

lemma lim_cnj: "((\<lambda>x. cnj(f x)) \<longlongrightarrow> cnj l) F \<longleftrightarrow> (f \<longlongrightarrow> l) F"
  by (simp add: tendsto_iff dist_complex_def complex_cnj_diff [symmetric] del: complex_cnj_diff)

lemma sums_cnj: "((\<lambda>x. cnj(f x)) sums cnj l) \<longleftrightarrow> (f sums l)"
  by (simp add: sums_def lim_cnj cnj_sum [symmetric] del: cnj_sum)

lemma differentiable_cnj_iff:
  "(\<lambda>z. cnj (f z)) differentiable at x within A \<longleftrightarrow> f differentiable at x within A"
proof
  assume "(\<lambda>z. cnj (f z)) differentiable at x within A"
  then obtain D where "((\<lambda>z. cnj (f z)) has_derivative D) (at x within A)"
    by (auto simp: differentiable_def)
  from has_derivative_cnj[OF this] show "f differentiable at x within A"
    by (auto simp: differentiable_def)
next
  assume "f differentiable at x within A"
  then obtain D where "(f has_derivative D) (at x within A)"
    by (auto simp: differentiable_def)
  from has_derivative_cnj[OF this] show "(\<lambda>z. cnj (f z)) differentiable at x within A"
    by (auto simp: differentiable_def)
qed

lemma has_vector_derivative_cnj [derivative_intros]:
  assumes "(f has_vector_derivative f') (at z within A)"
  shows   "((\<lambda>z. cnj (f z)) has_vector_derivative cnj f') (at z within A)"
  using assms by (auto simp: has_vector_derivative_complex_iff intro: derivative_intros)

subsection \<open>Basic Lemmas\<close>

lemma complex_of_real_code[code_unfold]: "of_real = (\<lambda>x. Complex x 0)"
  by (intro ext, auto simp: complex_eq_iff)

lemma complex_eq_0: "z=0 \<longleftrightarrow> (Re z)\<^sup>2 + (Im z)\<^sup>2 = 0"
  by (metis zero_complex.sel complex_eqI sum_power2_eq_zero_iff)

lemma complex_neq_0: "z\<noteq>0 \<longleftrightarrow> (Re z)\<^sup>2 + (Im z)\<^sup>2 > 0"
  by (metis complex_eq_0 less_numeral_extra(3) sum_power2_gt_zero_iff)

lemma complex_norm_square: "of_real ((norm z)\<^sup>2) = z * cnj z"
  by (cases z)
    (auto simp: complex_eq_iff norm_complex_def power2_eq_square[symmetric] of_real_power[symmetric]
      simp del: of_real_power)

lemma complex_div_cnj: "a / b = (a * cnj b) / (norm b)\<^sup>2"
  using complex_norm_square by auto

lemma Re_complex_div_eq_0: "Re (a / b) = 0 \<longleftrightarrow> Re (a * cnj b) = 0"
  by (auto simp add: Re_divide)

lemma Im_complex_div_eq_0: "Im (a / b) = 0 \<longleftrightarrow> Im (a * cnj b) = 0"
  by (auto simp add: Im_divide)

lemma complex_div_gt_0: "(Re (a / b) > 0 \<longleftrightarrow> Re (a * cnj b) > 0) \<and> (Im (a / b) > 0 \<longleftrightarrow> Im (a * cnj b) > 0)"
proof (cases "b = 0")
  case True
  then show ?thesis by auto
next
  case False
  then have "0 < (Re b)\<^sup>2 + (Im b)\<^sup>2"
    by (simp add: complex_eq_iff sum_power2_gt_zero_iff)
  then show ?thesis
    by (simp add: Re_divide Im_divide zero_less_divide_iff)
qed

lemma Re_complex_div_gt_0: "Re (a / b) > 0 \<longleftrightarrow> Re (a * cnj b) > 0"
  and Im_complex_div_gt_0: "Im (a / b) > 0 \<longleftrightarrow> Im (a * cnj b) > 0"
  using complex_div_gt_0 by auto

lemma Re_complex_div_ge_0: "Re (a / b) \<ge> 0 \<longleftrightarrow> Re (a * cnj b) \<ge> 0"
  by (metis le_less Re_complex_div_eq_0 Re_complex_div_gt_0)

lemma Im_complex_div_ge_0: "Im (a / b) \<ge> 0 \<longleftrightarrow> Im (a * cnj b) \<ge> 0"
  by (metis Im_complex_div_eq_0 Im_complex_div_gt_0 le_less)

lemma Re_complex_div_lt_0: "Re (a / b) < 0 \<longleftrightarrow> Re (a * cnj b) < 0"
  by (metis less_asym neq_iff Re_complex_div_eq_0 Re_complex_div_gt_0)

lemma Im_complex_div_lt_0: "Im (a / b) < 0 \<longleftrightarrow> Im (a * cnj b) < 0"
  by (metis Im_complex_div_eq_0 Im_complex_div_gt_0 less_asym neq_iff)

lemma Re_complex_div_le_0: "Re (a / b) \<le> 0 \<longleftrightarrow> Re (a * cnj b) \<le> 0"
  by (metis not_le Re_complex_div_gt_0)

lemma Im_complex_div_le_0: "Im (a / b) \<le> 0 \<longleftrightarrow> Im (a * cnj b) \<le> 0"
  by (metis Im_complex_div_gt_0 not_le)

lemma Re_divide_of_real [simp]: "Re (z / of_real r) = Re z / r"
  by (simp add: Re_divide power2_eq_square)

lemma Im_divide_of_real [simp]: "Im (z / of_real r) = Im z / r"
  by (simp add: Im_divide power2_eq_square)

lemma Re_divide_Reals [simp]: "r \<in> \<real> \<Longrightarrow> Re (z / r) = Re z / Re r"
  by (metis Re_divide_of_real of_real_Re)

lemma Im_divide_Reals [simp]: "r \<in> \<real> \<Longrightarrow> Im (z / r) = Im z / Re r"
  by (metis Im_divide_of_real of_real_Re)

lemma Re_sum[simp]: "Re (sum f s) = (\<Sum>x\<in>s. Re (f x))"
  by (induct s rule: infinite_finite_induct) auto

lemma Im_sum[simp]: "Im (sum f s) = (\<Sum>x\<in>s. Im(f x))"
  by (induct s rule: infinite_finite_induct) auto

lemma sum_Re_le_cmod: "(\<Sum>i\<in>I. Re (z i)) \<le> cmod (\<Sum>i\<in>I. z i)"
  by (metis Re_sum complex_Re_le_cmod)

lemma sum_Im_le_cmod: "(\<Sum>i\<in>I. Im (z i)) \<le> cmod (\<Sum>i\<in>I. z i)"
  by (smt (verit, best) Im_sum abs_Im_le_cmod sum.cong)

lemma sums_complex_iff: "f sums x \<longleftrightarrow> ((\<lambda>x. Re (f x)) sums Re x) \<and> ((\<lambda>x. Im (f x)) sums Im x)"
  unfolding sums_def tendsto_complex_iff Im_sum Re_sum ..

lemma summable_complex_iff: "summable f \<longleftrightarrow> summable (\<lambda>x. Re (f x)) \<and>  summable (\<lambda>x. Im (f x))"
  unfolding summable_def sums_complex_iff[abs_def] by (metis complex.sel)

lemma summable_complex_of_real [simp]: "summable (\<lambda>n. complex_of_real (f n)) \<longleftrightarrow> summable f"
  unfolding summable_complex_iff by simp

lemma summable_Re: "summable f \<Longrightarrow> summable (\<lambda>x. Re (f x))"
  unfolding summable_complex_iff by blast

lemma summable_Im: "summable f \<Longrightarrow> summable (\<lambda>x. Im (f x))"
  unfolding summable_complex_iff by blast

lemma complex_is_Nat_iff: "z \<in> \<nat> \<longleftrightarrow> Im z = 0 \<and> (\<exists>i. Re z = of_nat i)"
  by (auto simp: Nats_def complex_eq_iff)

lemma complex_is_Int_iff: "z \<in> \<int> \<longleftrightarrow> Im z = 0 \<and> (\<exists>i. Re z = of_int i)"
  by (auto simp: Ints_def complex_eq_iff)

lemma complex_is_Real_iff: "z \<in> \<real> \<longleftrightarrow> Im z = 0"
  by (auto simp: Reals_def complex_eq_iff)

lemma Reals_cnj_iff: "z \<in> \<real> \<longleftrightarrow> cnj z = z"
  by (auto simp: complex_is_Real_iff complex_eq_iff)

lemma in_Reals_norm: "z \<in> \<real> \<Longrightarrow> norm z = \<bar>Re z\<bar>"
  by (simp add: complex_is_Real_iff norm_complex_def)

lemma Re_Reals_divide: "r \<in> \<real> \<Longrightarrow> Re (r / z) = Re r * Re z / (norm z)\<^sup>2"
  by (simp add: Re_divide complex_is_Real_iff cmod_power2)

lemma Im_Reals_divide: "r \<in> \<real> \<Longrightarrow> Im (r / z) = -Re r * Im z / (norm z)\<^sup>2"
  by (simp add: Im_divide complex_is_Real_iff cmod_power2)

lemma series_comparison_complex:
  fixes f:: "nat \<Rightarrow> 'a::banach"
  assumes sg: "summable g"
    and "\<And>n. g n \<in> \<real>" "\<And>n. Re (g n) \<ge> 0"
    and fg: "\<And>n. n \<ge> N \<Longrightarrow> norm(f n) \<le> norm(g n)"
  shows "summable f"
proof -
  have g: "\<And>n. cmod (g n) = Re (g n)"
    using assms by (metis abs_of_nonneg in_Reals_norm)
  show ?thesis
    by (metis fg g sg summable_comparison_test summable_complex_iff)
qed

subsection \<open>Polar Form for Complex Numbers\<close>

lemma complex_unimodular_polar:
  assumes "norm z = 1"
  obtains t where "0 \<le> t" "t < 2 * pi" "z = Complex (cos t) (sin t)"
  by (metis cmod_power2 one_power2 complex_surj sincos_total_2pi [of "Re z" "Im z"] assms)

subsubsection \<open>$\cos \theta + i \sin \theta$\<close>

primcorec cis :: "real \<Rightarrow> complex"
  where
    "Re (cis a) = cos a"
  | "Im (cis a) = sin a"

lemma cis_zero [simp]: "cis 0 = 1"
  by (simp add: complex_eq_iff)

lemma norm_cis [simp]: "norm (cis a) = 1"
  by (simp add: norm_complex_def)

lemma sgn_cis [simp]: "sgn (cis a) = cis a"
  by (simp add: sgn_div_norm)

lemma cis_2pi [simp]: "cis (2 * pi) = 1"
  by (simp add: cis.ctr complex_eq_iff)

lemma cis_neq_zero [simp]: "cis a \<noteq> 0"
  by (metis norm_cis norm_zero zero_neq_one)

lemma cis_cnj: "cnj (cis t) = cis (-t)"
  by (simp add: complex_eq_iff)

lemma cis_mult: "cis a * cis b = cis (a + b)"
  by (simp add: complex_eq_iff cos_add sin_add)

lemma DeMoivre: "(cis a) ^ n = cis (real n * a)"
  by (induct n) (simp_all add: algebra_simps cis_mult)

lemma cis_inverse [simp]: "inverse (cis a) = cis (- a)"
  by (simp add: complex_eq_iff)

lemma cis_divide: "cis a / cis b = cis (a - b)"
  by (simp add: divide_complex_def cis_mult)

lemma cos_n_Re_cis_pow_n: "cos (real n * a) = Re (cis a ^ n)"
  by (auto simp add: DeMoivre)

lemma sin_n_Im_cis_pow_n: "sin (real n * a) = Im (cis a ^ n)"
  by (auto simp add: DeMoivre)

lemma cis_pi [simp]: "cis pi = -1"
  by (simp add: complex_eq_iff)

lemma cis_pi_half[simp]: "cis (pi / 2) = \<i>"
  by (simp add: cis.ctr complex_eq_iff)

lemma cis_minus_pi_half[simp]: "cis (-(pi / 2)) = -\<i>"
  by (simp add: cis.ctr complex_eq_iff)

lemma cis_multiple_2pi[simp]: "n \<in> \<int> \<Longrightarrow> cis (2 * pi * n) = 1"
  by (auto elim!: Ints_cases simp: cis.ctr one_complex.ctr)

subsubsection \<open>$r(\cos \theta + i \sin \theta)$\<close>

definition rcis :: "real \<Rightarrow> real \<Rightarrow> complex"
  where "rcis r a = complex_of_real r * cis a"

lemma Re_rcis [simp]: "Re(rcis r a) = r * cos a"
  by (simp add: rcis_def)

lemma Im_rcis [simp]: "Im(rcis r a) = r * sin a"
  by (simp add: rcis_def)

lemma rcis_Ex: "\<exists>r a. z = rcis r a"
  by (simp add: complex_eq_iff polar_Ex)

lemma complex_mod_rcis [simp]: "cmod (rcis r a) = \<bar>r\<bar>"
  by (simp add: rcis_def norm_mult)

lemma cis_rcis_eq: "cis a = rcis 1 a"
  by (simp add: rcis_def)

lemma rcis_mult: "rcis r1 a * rcis r2 b = rcis (r1 * r2) (a + b)"
  by (simp add: rcis_def cis_mult)

lemma rcis_zero_mod [simp]: "rcis 0 a = 0"
  by (simp add: rcis_def)

lemma rcis_zero_arg [simp]: "rcis r 0 = complex_of_real r"
  by (simp add: rcis_def)

lemma rcis_eq_zero_iff [simp]: "rcis r a = 0 \<longleftrightarrow> r = 0"
  by (simp add: rcis_def)

lemma DeMoivre2: "(rcis r a) ^ n = rcis (r ^ n) (real n * a)"
  by (simp add: rcis_def power_mult_distrib DeMoivre)

lemma rcis_inverse: "inverse(rcis r a) = rcis (1 / r) (- a)"
  by (simp add: divide_inverse rcis_def)

lemma rcis_divide: "rcis r1 a / rcis r2 b = rcis (r1 / r2) (a - b)"
  by (simp add: rcis_def cis_divide [symmetric])

subsubsection \<open>Complex exponential\<close>

lemma exp_Reals_eq:
  assumes "z \<in> \<real>"
  shows   "exp z = of_real (exp (Re z))"
  using assms by (auto elim!: Reals_cases simp: exp_of_real)

lemma cis_conv_exp: "cis b = exp (\<i> * b)"
proof -
  have "(\<i> * complex_of_real b) ^ n /\<^sub>R fact n =
      of_real (cos_coeff n * b^n) + \<i> * of_real (sin_coeff n * b^n)"
    for n :: nat
  proof -
    have "\<i> ^ n = fact n *\<^sub>R (cos_coeff n + \<i> * sin_coeff n)"
      by (induct n)
        (simp_all add: sin_coeff_Suc cos_coeff_Suc complex_eq_iff Re_divide Im_divide field_simps
          power2_eq_square add_nonneg_eq_0_iff)
    then show ?thesis
      by (simp add: field_simps)
  qed
  then show ?thesis
    using sin_converges [of b] cos_converges [of b]
    by (auto simp add: Complex_eq cis.ctr exp_def simp del: of_real_mult
        intro!: sums_unique sums_add sums_mult sums_of_real)
qed

lemma exp_eq_polar: "exp z = exp (Re z) * cis (Im z)"
  unfolding cis_conv_exp exp_of_real [symmetric] mult_exp_exp
  by (cases z) (simp add: Complex_eq)

lemma Re_exp: "Re (exp z) = exp (Re z) * cos (Im z)"
  unfolding exp_eq_polar by simp

lemma Im_exp: "Im (exp z) = exp (Re z) * sin (Im z)"
  unfolding exp_eq_polar by simp

lemma norm_cos_sin [simp]: "norm (Complex (cos t) (sin t)) = 1"
  by (simp add: norm_complex_def)

lemma norm_exp_eq_Re [simp]: "norm (exp z) = exp (Re z)"
  by (simp add: cis.code cmod_complex_polar exp_eq_polar Complex_eq)

lemma complex_exp_exists: "\<exists>a r. z = complex_of_real r * exp a"
  using cis_conv_exp rcis_Ex rcis_def by force

lemma exp_pi_i [simp]: "exp (of_real pi * \<i>) = -1"
  by (metis cis_conv_exp cis_pi mult.commute)

lemma exp_pi_i' [simp]: "exp (\<i> * of_real pi) = -1"
  using cis_conv_exp cis_pi by auto

lemma exp_two_pi_i [simp]: "exp (2 * of_real pi * \<i>) = 1"
  by (simp add: exp_eq_polar complex_eq_iff)

lemma exp_two_pi_i' [simp]: "exp (\<i> * (of_real pi * 2)) = 1"
  by (metis exp_two_pi_i mult.commute)

lemma continuous_on_cis [continuous_intros]:
  "continuous_on A f \<Longrightarrow> continuous_on A (\<lambda>x. cis (f x))"
  by (auto simp: cis_conv_exp intro!: continuous_intros)

subsubsection \<open>Complex argument\<close>

definition Arg :: "complex \<Rightarrow> real"
  where "Arg z = (if z = 0 then 0 else (SOME a. sgn z = cis a \<and> - pi < a \<and> a \<le> pi))"

lemma Arg_zero: "Arg 0 = 0"
  by (simp add: Arg_def)

lemma cis_Arg_unique:
  assumes "sgn z = cis x" and "-pi < x" and "x \<le> pi"
  shows "Arg z = x"
proof -
  from assms have "z \<noteq> 0" by auto
  have "(SOME a. sgn z = cis a \<and> -pi < a \<and> a \<le> pi) = x"
  proof
    fix a
    define d where "d = a - x"
    assume a: "sgn z = cis a \<and> - pi < a \<and> a \<le> pi"
    from a assms have "- (2*pi) < d \<and> d < 2*pi"
      unfolding d_def by simp
    moreover
    from a assms have "cos a = cos x" and "sin a = sin x"
      by (simp_all add: complex_eq_iff)
    then have cos: "cos d = 1"
      by (simp add: d_def cos_diff)
    moreover from cos have "sin d = 0"
      by (rule cos_one_sin_zero)
    ultimately have "d = 0"
      by (auto simp: sin_zero_iff elim!: evenE dest!: less_2_cases)
    then show "a = x"
      by (simp add: d_def)
  qed (simp add: assms del: Re_sgn Im_sgn)
  with \<open>z \<noteq> 0\<close> show "Arg z = x"
    by (simp add: Arg_def)
qed

lemma Arg_correct:
  assumes "z \<noteq> 0"
  shows "sgn z = cis (Arg z) \<and> -pi < Arg z \<and> Arg z \<le> pi"
proof (simp add: Arg_def assms, rule someI_ex)
  obtain r a where z: "z = rcis r a"
    using rcis_Ex by fast
  with assms have "r \<noteq> 0" by auto
  define b where "b = (if 0 < r then a else a + pi)"
  have b: "sgn z = cis b"
    using \<open>r \<noteq> 0\<close> by (simp add: z b_def rcis_def of_real_def sgn_scaleR sgn_if complex_eq_iff)
  have cis_2pi_nat: "cis (2 * pi * real_of_nat n) = 1" for n
    by (induct n) (simp_all add: distrib_left cis_mult [symmetric] complex_eq_iff)
  have cis_2pi_int: "cis (2 * pi * real_of_int x) = 1" for x
    by (cases x rule: int_diff_cases)
      (simp add: right_diff_distrib cis_divide [symmetric] cis_2pi_nat)
  define c where "c = b - 2 * pi * of_int \<lceil>(b - pi) / (2 * pi)\<rceil>"
  have "sgn z = cis c"
    by (simp add: b c_def cis_divide [symmetric] cis_2pi_int)
  moreover have "- pi < c \<and> c \<le> pi"
    using ceiling_correct [of "(b - pi) / (2*pi)"]
    by (simp add: c_def less_divide_eq divide_le_eq algebra_simps del: le_of_int_ceiling)
  ultimately show "\<exists>a. sgn z = cis a \<and> -pi < a \<and> a \<le> pi"
    by fast
qed

lemma Arg_bounded: "- pi < Arg z \<and> Arg z \<le> pi"
  by (cases "z = 0") (simp_all add: Arg_zero Arg_correct)

lemma cis_Arg: "z \<noteq> 0 \<Longrightarrow> cis (Arg z) = sgn z"
  by (simp add: Arg_correct)

lemma rcis_cmod_Arg: "rcis (cmod z) (Arg z) = z"
  by (cases "z = 0") (simp_all add: rcis_def cis_Arg sgn_div_norm of_real_def)

lemma rcis_cnj:
  shows "cnj a = rcis (cmod a) (- Arg a)"
  by (metis cis_cnj complex_cnj_complex_of_real complex_cnj_mult rcis_cmod_Arg rcis_def)

lemma cos_Arg_i_mult_zero [simp]: "y \<noteq> 0 \<Longrightarrow> Re y = 0 \<Longrightarrow> cos (Arg y) = 0"
  using cis_Arg [of y] by (simp add: complex_eq_iff)

lemma Arg_ii [simp]: "Arg \<i> = pi/2"
  by (rule cis_Arg_unique; simp add: sgn_eq)

lemma Arg_minus_ii [simp]: "Arg (-\<i>) = -pi/2"
proof (rule cis_Arg_unique)
  show "sgn (- \<i>) = cis (- pi / 2)"
    by (simp add: sgn_eq)
  show "- pi / 2 \<le> pi"
    using pi_not_less_zero by linarith
qed auto

subsection \<open>Complex n-th roots\<close>

lemma bij_betw_roots_unity:
  assumes "n > 0"
  shows   "bij_betw (\<lambda>k. cis (2 * pi * real k / real n)) {..<n} {z. z ^ n = 1}"
    (is "bij_betw ?f _ _")
  unfolding bij_betw_def
proof (intro conjI)
  show inj: "inj_on ?f {..<n}" unfolding inj_on_def
  proof (safe, goal_cases)
    case (1 k l)
    hence kl: "k < n" "l < n" by simp_all
    from 1 have "1 = ?f k / ?f l" by simp
    also have "\<dots> = cis (2*pi*(real k - real l)/n)"
      using assms by (simp add: field_simps cis_divide)
    finally have "cos (2*pi*(real k - real l) / n) = 1"
      by (simp add: complex_eq_iff)
    then obtain m :: int where "2 * pi * (real k - real l) / real n = real_of_int m * 2 * pi"
      by (subst (asm) cos_one_2pi_int) blast
    hence "real_of_int (int k - int l) = real_of_int (m * int n)"
      unfolding of_int_diff of_int_mult using assms
      by (simp add: nonzero_divide_eq_eq)
    also note of_int_eq_iff
    finally have *: "abs m * n = abs (int k - int l)" by (simp add: abs_mult)
    also have "\<dots> < int n" using kl by linarith
    finally have "m = 0" using assms by simp
    with * show "k = l" by simp
  qed

  have subset: "?f ` {..<n} \<subseteq> {z. z ^ n = 1}"
  proof safe
    fix k :: nat
    have "cis (2 * pi * real k / real n) ^ n = cis (2 * pi) ^ k"
      using assms by (simp add: DeMoivre mult_ac)
    also have "cis (2 * pi) = 1" by (simp add: complex_eq_iff)
    finally show "?f k ^ n = 1" by simp
  qed

  have "n = card {..<n}" by simp
  also from assms and subset have "\<dots> \<le> card {z::complex. z ^ n = 1}"
    by (intro card_inj_on_le[OF inj]) (auto simp: finite_roots_unity)
  finally have card: "card {z::complex. z ^ n = 1} = n"
    using assms by (intro antisym card_roots_unity) auto

  have "card (?f ` {..<n}) = card {z::complex. z ^ n = 1}"
    using card inj by (subst card_image) auto
  with subset and assms show "?f ` {..<n} = {z::complex. z ^ n = 1}"
    by (intro card_subset_eq finite_roots_unity) auto
qed

lemma card_roots_unity_eq:
  assumes "n > 0"
  shows   "card {z::complex. z ^ n = 1} = n"
  using bij_betw_same_card [OF bij_betw_roots_unity [OF assms]] by simp

lemma bij_betw_nth_root_unity:
  fixes c :: complex and n :: nat
  assumes c: "c \<noteq> 0" and n: "n > 0"
  defines "c' \<equiv> root n (norm c) * cis (Arg c / n)"
  shows "bij_betw (\<lambda>z. c' * z) {z. z ^ n = 1} {z. z ^ n = c}"
proof -
  have "c' ^ n = of_real (root n (norm c) ^ n) * cis (Arg c)"
    unfolding of_real_power using n by (simp add: c'_def power_mult_distrib DeMoivre)
  also from n have "root n (norm c) ^ n = norm c" by simp
  also from c have "of_real \<dots> * cis (Arg c) = c" by (simp add: cis_Arg Complex.sgn_eq)
  finally have [simp]: "c' ^ n = c" .

  show ?thesis unfolding bij_betw_def inj_on_def
  proof safe
    fix z :: complex assume "z ^ n = 1"
    hence "(c' * z) ^ n = c' ^ n" by (simp add: power_mult_distrib)
    also have "c' ^ n = of_real (root n (norm c) ^ n) * cis (Arg c)"
      unfolding of_real_power using n by (simp add: c'_def power_mult_distrib DeMoivre)
    also from n have "root n (norm c) ^ n = norm c" by simp
    also from c have "\<dots> * cis (Arg c) = c" by (simp add: cis_Arg Complex.sgn_eq)
    finally show "(c' * z) ^ n = c" .
  next
    fix z assume z: "c = z ^ n"
    define z' where "z' = z / c'"
    from c and n have "c' \<noteq> 0" by (auto simp: c'_def)
    with n c have "z = c' * z'" and "z' ^ n = 1"
      by (auto simp: z'_def power_divide z)
    thus "z \<in> (\<lambda>z. c' * z) ` {z. z ^ n = 1}" by blast
  qed (insert c n, auto simp: c'_def)
qed

lemma finite_nth_roots [intro]:
  assumes "n > 0"
  shows   "finite {z::complex. z ^ n = c}"
proof (cases "c = 0")
  case True
  with assms have "{z::complex. z ^ n = c} = {0}" by auto
  thus ?thesis by simp
next
  case False
  from assms have "finite {z::complex. z ^ n = 1}" by (intro finite_roots_unity) simp_all
  also have "?this \<longleftrightarrow> ?thesis"
    by (rule bij_betw_finite, rule bij_betw_nth_root_unity) fact+
  finally show ?thesis .
qed

lemma card_nth_roots:
  assumes "c \<noteq> 0" "n > 0"
  shows   "card {z::complex. z ^ n = c} = n"
proof -
  have "card {z. z ^ n = c} = card {z::complex. z ^ n = 1}"
    by (rule sym, rule bij_betw_same_card, rule bij_betw_nth_root_unity) fact+
  also have "\<dots> = n" by (rule card_roots_unity_eq) fact+
  finally show ?thesis .
qed

lemma sum_roots_unity:
  assumes "n > 1"
  shows   "\<Sum>{z::complex. z ^ n = 1} = 0"
proof -
  define \<omega> where "\<omega> = cis (2 * pi / real n)"
  have [simp]: "\<omega> \<noteq> 1"
  proof
    assume "\<omega> = 1"
    with assms obtain k :: int where "2 * pi / real n = 2 * pi * of_int k"
      by (auto simp: \<omega>_def complex_eq_iff cos_one_2pi_int)
    with assms have "real n * of_int k = 1" by (simp add: field_simps)
    also have "real n * of_int k = of_int (int n * k)" by simp
    also have "1 = (of_int 1 :: real)" by simp
    also note of_int_eq_iff
    finally show False using assms by (auto simp: zmult_eq_1_iff)
  qed

  have "(\<Sum>z | z ^ n = 1. z :: complex) = (\<Sum>k<n. cis (2 * pi * real k / real n))"
    using assms by (intro sum.reindex_bij_betw [symmetric] bij_betw_roots_unity) auto
  also have "\<dots> = (\<Sum>k<n. \<omega> ^ k)"
    by (intro sum.cong refl) (auto simp: \<omega>_def DeMoivre mult_ac)
  also have "\<dots> = (\<omega> ^ n - 1) / (\<omega> - 1)"
    by (subst geometric_sum) auto
  also have "\<omega> ^ n - 1 = cis (2 * pi) - 1" using assms by (auto simp: \<omega>_def DeMoivre)
  also have "\<dots> = 0" by (simp add: complex_eq_iff)
  finally show ?thesis by simp
qed

lemma sum_nth_roots:
  assumes "n > 1"
  shows   "\<Sum>{z::complex. z ^ n = c} = 0"
proof (cases "c = 0")
  case True
  with assms have "{z::complex. z ^ n = c} = {0}" by auto
  also have "\<Sum>\<dots> = 0" by simp
  finally show ?thesis .
next
  case False
  define c' where "c' = root n (norm c) * cis (Arg c / n)"
  from False and assms have "(\<Sum>{z. z ^ n = c}) = (\<Sum>z | z ^ n = 1. c' * z)"
    by (subst sum.reindex_bij_betw [OF bij_betw_nth_root_unity, symmetric])
       (auto simp: sum_distrib_left finite_roots_unity c'_def)
  also from assms have "\<dots> = 0"
    by (simp add: sum_distrib_left [symmetric] sum_roots_unity)
  finally show ?thesis .
qed

subsection \<open>Square root of complex numbers\<close>

primcorec csqrt :: "complex \<Rightarrow> complex"
  where
    "Re (csqrt z) = sqrt ((cmod z + Re z) / 2)"
  | "Im (csqrt z) = (if Im z = 0 then 1 else sgn (Im z)) * sqrt ((cmod z - Re z) / 2)"

lemma csqrt_of_real_nonneg [simp]: "Im x = 0 \<Longrightarrow> Re x \<ge> 0 \<Longrightarrow> csqrt x = sqrt (Re x)"
  by (simp add: complex_eq_iff norm_complex_def)

lemma csqrt_of_real_nonpos [simp]: "Im x = 0 \<Longrightarrow> Re x \<le> 0 \<Longrightarrow> csqrt x = \<i> * sqrt \<bar>Re x\<bar>"
  by (simp add: complex_eq_iff norm_complex_def)

lemma of_real_sqrt: "x \<ge> 0 \<Longrightarrow> of_real (sqrt x) = csqrt (of_real x)"
  by (simp add: complex_eq_iff norm_complex_def)

lemma csqrt_0 [simp]: "csqrt 0 = 0"
  by simp

lemma csqrt_1 [simp]: "csqrt 1 = 1"
  by simp

lemma csqrt_ii [simp]: "csqrt \<i> = (1 + \<i>) / sqrt 2"
  by (simp add: complex_eq_iff Re_divide Im_divide real_sqrt_divide real_div_sqrt)

lemma power2_csqrt[simp,algebra]: "(csqrt z)\<^sup>2 = z"
proof (cases "Im z = 0")
  case True
  then show ?thesis
    using real_sqrt_pow2[of "Re z"] real_sqrt_pow2[of "- Re z"]
    by (cases "0::real" "Re z" rule: linorder_cases)
      (simp_all add: complex_eq_iff Re_power2 Im_power2 power2_eq_square cmod_eq_Re)
next
  case False
  moreover have "cmod z * cmod z - Re z * Re z = Im z * Im z"
    by (simp add: norm_complex_def power2_eq_square)
  moreover have "\<bar>Re z\<bar> \<le> cmod z"
    by (simp add: norm_complex_def)
  ultimately show ?thesis
    by (simp add: Re_power2 Im_power2 complex_eq_iff real_sgn_eq
        field_simps real_sqrt_mult[symmetric] real_sqrt_divide)
qed

lemma csqrt_eq_0 [simp]: "csqrt z = 0 \<longleftrightarrow> z = 0"
  by auto (metis power2_csqrt power_eq_0_iff)

lemma csqrt_eq_1 [simp]: "csqrt z = 1 \<longleftrightarrow> z = 1"
  by auto (metis power2_csqrt power2_eq_1_iff)

lemma csqrt_principal: "0 < Re (csqrt z) \<or> Re (csqrt z) = 0 \<and> 0 \<le> Im (csqrt z)"
  by (auto simp add: not_less cmod_plus_Re_le_0_iff Im_eq_0)

lemma Re_csqrt: "0 \<le> Re (csqrt z)"
  by (metis csqrt_principal le_less)

lemma csqrt_square:
  assumes "0 < Re b \<or> (Re b = 0 \<and> 0 \<le> Im b)"
  shows "csqrt (b^2) = b"
proof -
  have "csqrt (b^2) = b \<or> csqrt (b^2) = - b"
    by (simp add: power2_eq_iff[symmetric])
  moreover have "csqrt (b^2) \<noteq> -b \<or> b = 0"
    using csqrt_principal[of "b ^ 2"] assms
    by (intro disjCI notI) (auto simp: complex_eq_iff)
  ultimately show ?thesis
    by auto
qed

lemma csqrt_unique: "w\<^sup>2 = z \<Longrightarrow> 0 < Re w \<or> Re w = 0 \<and> 0 \<le> Im w \<Longrightarrow> csqrt z = w"
  by (auto simp: csqrt_square)

lemma csqrt_minus [simp]:
  assumes "Im x < 0 \<or> (Im x = 0 \<and> 0 \<le> Re x)"
  shows "csqrt (- x) = \<i> * csqrt x"
proof -
  have "csqrt ((\<i> * csqrt x)^2) = \<i> * csqrt x"
  proof (rule csqrt_square)
    have "Im (csqrt x) \<le> 0"
      using assms by (auto simp add: cmod_eq_Re mult_le_0_iff field_simps complex_Re_le_cmod)
    then show "0 < Re (\<i> * csqrt x) \<or> Re (\<i> * csqrt x) = 0 \<and> 0 \<le> Im (\<i> * csqrt x)"
      by (auto simp add: Re_csqrt simp del: csqrt.simps)
  qed
  also have "(\<i> * csqrt x)^2 = - x"
    by (simp add: power_mult_distrib)
  finally show ?thesis .
qed

text \<open>Legacy theorem names\<close>

lemmas cmod_def = norm_complex_def

lemma legacy_Complex_simps:
  shows Complex_eq_0: "Complex a b = 0 \<longleftrightarrow> a = 0 \<and> b = 0"
    and complex_add: "Complex a b + Complex c d = Complex (a + c) (b + d)"
    and complex_minus: "- (Complex a b) = Complex (- a) (- b)"
    and complex_diff: "Complex a b - Complex c d = Complex (a - c) (b - d)"
    and Complex_eq_1: "Complex a b = 1 \<longleftrightarrow> a = 1 \<and> b = 0"
    and Complex_eq_neg_1: "Complex a b = - 1 \<longleftrightarrow> a = - 1 \<and> b = 0"
    and complex_mult: "Complex a b * Complex c d = Complex (a * c - b * d) (a * d + b * c)"
    and complex_inverse: "inverse (Complex a b) = Complex (a / (a\<^sup>2 + b\<^sup>2)) (- b / (a\<^sup>2 + b\<^sup>2))"
    and Complex_eq_numeral: "Complex a b = numeral w \<longleftrightarrow> a = numeral w \<and> b = 0"
    and Complex_eq_neg_numeral: "Complex a b = - numeral w \<longleftrightarrow> a = - numeral w \<and> b = 0"
    and complex_scaleR: "scaleR r (Complex a b) = Complex (r * a) (r * b)"
    and Complex_eq_i: "Complex x y = \<i> \<longleftrightarrow> x = 0 \<and> y = 1"
    and i_mult_Complex: "\<i> * Complex a b = Complex (- b) a"
    and Complex_mult_i: "Complex a b * \<i> = Complex (- b) a"
    and i_complex_of_real: "\<i> * complex_of_real r = Complex 0 r"
    and complex_of_real_i: "complex_of_real r * \<i> = Complex 0 r"
    and Complex_add_complex_of_real: "Complex x y + complex_of_real r = Complex (x+r) y"
    and complex_of_real_add_Complex: "complex_of_real r + Complex x y = Complex (r+x) y"
    and Complex_mult_complex_of_real: "Complex x y * complex_of_real r = Complex (x*r) (y*r)"
    and complex_of_real_mult_Complex: "complex_of_real r * Complex x y = Complex (r*x) (r*y)"
    and complex_eq_cancel_iff2: "(Complex x y = complex_of_real xa) = (x = xa \<and> y = 0)"
    and complex_cnj: "cnj (Complex a b) = Complex a (- b)"
    and Complex_sum': "sum (\<lambda>x. Complex (f x) 0) s = Complex (sum f s) 0"
    and Complex_sum: "Complex (sum f s) 0 = sum (\<lambda>x. Complex (f x) 0) s"
    and complex_of_real_def: "complex_of_real r = Complex r 0"
    and complex_norm: "cmod (Complex x y) = sqrt (x\<^sup>2 + y\<^sup>2)"
  by (simp_all add: norm_complex_def field_simps complex_eq_iff Re_divide Im_divide)

lemma Complex_in_Reals: "Complex x 0 \<in> \<real>"
  by (metis Reals_of_real complex_of_real_def)

end


section \<open>Bernstein Polynomials over any finite interval\<close>

theory Bernstein
  imports "Bernstein_01"
begin

subsection \<open>Definition and relation to Bernstein Polynomials over [0, 1]\<close>

definition Bernstein_Poly :: "nat \<Rightarrow> nat \<Rightarrow> real \<Rightarrow> real \<Rightarrow> real poly" where
  "Bernstein_Poly j p c d = smult ((p choose j)/(d - c)^p)
      (((monom 1 j) \<circ>\<^sub>p [:-c, 1:]) * (monom 1 (p-j) \<circ>\<^sub>p [:d, -1:]))"

lemma Bernstein_Poly_altdef:
  assumes "c \<noteq> d" and "j \<le> p"
  shows "Bernstein_Poly j p c d = smult (p choose j)
            ([:-c/(d-c), 1/(d-c):]^j * [:d/(d-c), -1/(d-c):]^(p-j))"
    (is "?L = ?R")
proof -
  have "?L = smult (p choose j) (smult ((1/(d - c))^j)
        (smult ((1/(d - c))^(p-j)) ([:-c, 1:]^j * [:d, -1:]^(p-j))))"
    using assms by (auto simp: Bernstein_Poly_def monom_altdef hom_distribs
                    pcompose_pCons smult_eq_iff field_simps power_add[symmetric])
  also have "... = ?R"
    apply (subst mult_smult_right[symmetric])
    apply (subst mult_smult_left[symmetric])
    apply (subst smult_power)
    apply (subst smult_power)
    by auto
  finally show ?thesis .
qed

lemma Bernstein_Poly_nonneg:
  assumes "c \<le> x" and "x \<le> d"
  shows "poly (Bernstein_Poly j p c d) x \<ge> 0"
  using assms by (auto simp: Bernstein_Poly_def poly_pcompose poly_monom)

lemma Bernstein_Poly_01: "Bernstein_Poly j p 0 1 = Bernstein_Poly_01 j p"
  by (auto simp: Bernstein_Poly_def Bernstein_Poly_01_def monom_altdef)

lemma Bernstein_Poly_rescale:
  assumes "a \<noteq> b"
  shows "Bernstein_Poly j p c d \<circ>\<^sub>p [:a, 1:] \<circ>\<^sub>p [:0, b-a:]
            = Bernstein_Poly j p ((c-a)/(b-a)) ((d-a)/(b-a))"
  (is "?L = ?R")
proof -
  have "?R = smult (real (p choose j)
      / ((d - a) / (b - a) - (c - a) / (b - a)) ^ p)
      ([:- ((c - a) / (b - a)), 1:] ^ j
      * [:(d - a) / (b - a), - 1:] ^ (p - j))"
    by (auto simp: Bernstein_Poly_def monom_altdef hom_distribs
        pcompose_pCons)
  also have "... = smult (real (p choose j) / ((d - c) / (b - a)) ^ p)
              ([:- ((c - a) / (b - a)), 1:] ^ j * [:(d - a) / (b - a), - 1:]
            ^ (p - j))"
    by argo
  also have "... = smult (real (p choose j) / (d - c) ^ p)
      (smult ((b - a) ^ (p - j)) (smult ((b - a) ^ j)
      ([:- ((c - a) / (b - a)), 1:] ^ j * [:(d - a) / (b - a), - 1:]
      ^ (p - j))))"
    by (auto simp: power_add[symmetric] power_divide)
  also have "... = smult (real (p choose j) / (d - c) ^ p)
              ([:- (c - a), b - a:] ^ j * [:d - a, -(b - a):] ^ (p - j))"
    apply (subst mult_smult_left[symmetric])
    apply (subst mult_smult_right[symmetric])
    using assms by (auto simp: smult_power)
  also have "... = ?L"
    using assms
    by (auto simp: Bernstein_Poly_def monom_altdef pcompose_mult
        pcompose_smult hom_distribs pcompose_pCons)
  finally show ?thesis by presburger
qed

lemma Bernstein_Poly_rescale_01:
  assumes "c \<noteq> d"
  shows "Bernstein_Poly j p c d \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d-c:]
          = Bernstein_Poly_01 j p"
  apply (subst Bernstein_Poly_rescale)
  using assms by (auto simp: Bernstein_Poly_01)

lemma Bernstein_Poly_eq_rescale_01:
  assumes "c \<noteq> d"
  shows "Bernstein_Poly j p c d = Bernstein_Poly_01 j p
            \<circ>\<^sub>p [:0, 1/(d-c):] \<circ>\<^sub>p [:-c, 1:]"
  apply (subst Bernstein_Poly_rescale_01[symmetric])
  using assms by (auto simp: pcompose_pCons pcompose_assoc[symmetric])

lemma coeff_Bernstein_sum:
  fixes b::"nat \<Rightarrow> real" and p::nat and c d::real
  defines "P \<equiv> (\<Sum>j = 0..p. (smult (b j) (Bernstein_Poly j p c d)))"
  assumes "i \<le> p" and "c \<noteq> d"
  shows "coeff ((reciprocal_poly p (P \<circ>\<^sub>p [:c, 1:]
      \<circ>\<^sub>p [:0, d-c:])) \<circ>\<^sub>p [:1, 1:]) (p - i) = (p choose i) * (b i)"
proof -
  have h: "P \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d-c:]
      = (\<Sum>j = 0..p. (smult (b j) (Bernstein_Poly_01 j p)))"
    using assms
    by (auto simp: P_def pcompose_sum pcompose_smult
          pcompose_add Bernstein_Poly_rescale_01)
  then show ?thesis
    using coeff_Bernstein_sum_01 assms by simp
qed

lemma Bernstein_sum:
  assumes "c \<noteq> d" and "degree P \<le> p"
  shows "P = (\<Sum>j = 0..p. smult (inverse (real (p choose j))
     * coeff (reciprocal_poly p (P \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d-c:])
      \<circ>\<^sub>p [:1, 1:]) (p-j)) (Bernstein_Poly j p c d))"
  apply (subst Bernstein_Poly_eq_rescale_01)
  subgoal using assms by blast
  subgoal
    apply (subst pcompose_smult[symmetric])
    apply (subst pcompose_sum[symmetric])
    apply (subst pcompose_smult[symmetric])
    apply (subst pcompose_sum[symmetric])
    apply (subst Bernstein_sum_01[symmetric])
    using assms by (auto simp: degree_pcompose pcompose_assoc[symmetric]
        pcompose_pCons)
  done

lemma Bernstein_Poly_span1:
  assumes "c \<noteq> d" and "degree P \<le> p"
  shows "P \<in> poly_vs.span {Bernstein_Poly x p c d | x. x \<le> p}"
proof (subst Bernstein_sum[OF assms], rule poly_vs.span_sum)
  fix x :: nat
  assume "x \<in> {0..p}"
  then have "\<exists>n. Bernstein_Poly x p c d = Bernstein_Poly n p c d \<and> n \<le> p"
    by auto
  then have
    "Bernstein_Poly x p c d \<in> poly_vs.span {Bernstein_Poly n p c d |n. n \<le> p}"
    by (simp add: poly_vs.span_base)
  thus "smult (inverse (real (p choose x)) *
        coeff (reciprocal_poly p (P \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d - c:]) \<circ>\<^sub>p [:1, 1:])
        (p - x)) (Bernstein_Poly x p c d)
         \<in> poly_vs.span {Bernstein_Poly x p c d |x. x \<le> p}"
    by (rule poly_vs.span_scale)
qed

lemma Bernstein_Poly_span:
  assumes "c \<noteq> d"
  shows "poly_vs.span {Bernstein_Poly x p c d | x. x \<le> p} = {x. degree x \<le> p}"
proof (subst Bernstein_Poly_01_span[symmetric], subst poly_vs.span_eq, rule conjI)
  show "{Bernstein_Poly x p c d |x. x \<le> p}
      \<subseteq> poly_vs.span {Bernstein_Poly_01 x p |x. x \<le> p}"
    apply (subst Setcompr_subset)
    apply (rule allI, rule impI)
    apply (rule Bernstein_Poly_01_span1)
    using assms by (auto simp: degree_Bernstein_le Bernstein_Poly_eq_rescale_01
                    degree_pcompose)

  show "{Bernstein_Poly_01 x p |x. x \<le> p}
      \<subseteq> poly_vs.span {Bernstein_Poly x p c d |x. x \<le> p}"
    apply (subst Setcompr_subset)
    apply (rule allI, rule impI)
    apply (rule Bernstein_Poly_span1)
    using assms by (auto simp: degree_Bernstein_le)
qed

lemma Bernstein_Poly_independent: assumes "c \<noteq> d"
  shows "poly_vs.independent {Bernstein_Poly x p c d | x. x \<in> {..p}}"
proof (rule poly_vs.card_le_dim_spanning)
  show "{Bernstein_Poly x p c d |x. x \<in> {.. p}} \<subseteq> {x. degree x \<le> p}"
    using assms
    by (auto simp: degree_Bernstein Bernstein_Poly_eq_rescale_01 degree_pcompose)
  show "{x. degree x \<le> p} \<subseteq> poly_vs.span {Bernstein_Poly x p c d |x. x \<in> {..p}}"
    using assms by (auto simp: Bernstein_Poly_span1)
  show "finite {Bernstein_Poly x p c d |x. x \<in> {..p}}" by fastforce
  show "card {Bernstein_Poly x p c d |x. x \<in> {..p}} \<le> poly_vs.dim {x. degree x \<le> p}"
    apply (rule le_trans)
     apply (subst image_Collect[symmetric], rule card_image_le, force)
    by (force simp: dim_degree)
qed

subsection \<open>Bernstein coefficients and changes over any interval\<close>

definition Bernstein_coeffs ::
  "nat \<Rightarrow> real \<Rightarrow> real \<Rightarrow> real poly \<Rightarrow> real list" where
  "Bernstein_coeffs p c d P =
    [(inverse (real (p choose j)) *
      coeff (reciprocal_poly p (P \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d-c:]) \<circ>\<^sub>p [:1, 1:]) (p-j)).
     j \<leftarrow> [0..<(p+1)]]"

lemma Bernstein_coeffs_eq_rescale: assumes "c \<noteq> d"
  shows "Bernstein_coeffs p c d P = Bernstein_coeffs_01 p (P \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d-c:])"
  using assms by (auto simp: pcompose_pCons pcompose_assoc[symmetric]
                  Bernstein_coeffs_def Bernstein_coeffs_01_def)

lemma nth_default_Bernstein_coeffs: assumes "degree P \<le> p"
  shows "nth_default 0 (Bernstein_coeffs p c d P) i =
         inverse (p choose i) * coeff
         (reciprocal_poly p (P \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d-c:]) \<circ>\<^sub>p [:1, 1:]) (p-i)"
  apply (cases "p = i")
  using assms by (auto simp: Bernstein_coeffs_def nth_default_append
                  nth_default_Cons Nitpick.case_nat_unfold binomial_eq_0)

lemma Bernstein_coeffs_sum: assumes "c \<noteq> d" and hP: "degree P \<le> p"
  shows "P = (\<Sum>j = 0..p. smult (nth_default 0 (Bernstein_coeffs p c d P) j)
         (Bernstein_Poly j p c d))"
  apply (subst nth_default_Bernstein_coeffs[OF hP])
  apply (subst Bernstein_sum[OF assms])
  by argo

definition Bernstein_changes :: "nat \<Rightarrow> real \<Rightarrow> real \<Rightarrow> real poly \<Rightarrow> int" where
  "Bernstein_changes p c d P = nat (changes (Bernstein_coeffs p c d P))"

lemma Bernstein_changes_eq_rescale: assumes "c \<noteq> d" and "degree P \<le> p"
  shows "Bernstein_changes p c d P =
         Bernstein_changes_01 p (P \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d-c:])"
  using assms by (auto simp: Bernstein_coeffs_eq_rescale Bernstein_changes_def
                  Bernstein_changes_01_def)

text \<open>This is related and mostly equivalent to previous Descartes test \<^cite>\<open>"li2019counting"\<close>\<close>
lemma Bernstein_changes_test:
  fixes P::"real poly"
  assumes "degree P \<le> p" and "P \<noteq> 0" and "c < d"
  shows "proots_count P {x. c < x \<and> x < d} \<le> Bernstein_changes p c d P \<and>
        even (Bernstein_changes p c d P - proots_count P {x. c < x \<and> x < d})"
proof -
  define Q where "Q=P \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d - c:]"

  have "int (proots_count Q {x. 0 < x \<and> x < 1})
          \<le> Bernstein_changes_01 p Q \<and>
              even (Bernstein_changes_01 p Q -
                  int (proots_count Q {x. 0 < x \<and> x < 1}))"
    unfolding Q_def
    apply (rule Bernstein_changes_01_test)
    subgoal using assms by fastforce
    subgoal using assms by (auto simp: pcompose_eq_0)
    done
  moreover have "proots_count P {x. c < x \<and> x < d} =
            proots_count Q {x. 0 < x \<and> x < 1}"
    unfolding Q_def
  proof (subst proots_pcompose)
    have "poly [:c, 1:] ` poly [:0, d - c:] ` {x. 0 < x \<and> x < 1} =
        {x. c < x \<and> x < d}" (is "?L = ?R")
    proof
      have "c + x * (d - c) < d" if "x < 1" for x
      proof -
        have "x * (d - c) < 1 * (d - c)"
          using \<open>c < d\<close> that by force
        then show ?thesis by fastforce
      qed
      then show "?L \<subseteq> ?R"
        using assms by auto
    next
      show "?R \<subseteq> ?L"
      proof
        fix x::real assume "x \<in> ?R"
        hence "c < x" and "x < d" by auto
        thus "x \<in> ?L"
        proof (subst image_eqI)
          show "x = poly [:c, 1:] (x - c)" by force
          assume "c < x" and "x < d"
          thus "x - c \<in> poly [:0, d - c:] ` {x. 0 < x \<and> x < 1}"
          proof (subst image_eqI)
            show "x - c = poly [:0, d - c:] ((x - c)/(d - c))"
              using assms by fastforce
            assume "c < x" and "x < d"
            thus "(x - c) / (d - c) \<in> {x. 0 < x \<and> x < 1}"
              by auto
          qed fast
        qed fast
      qed
    qed
    then show "proots_count P {x. c < x \<and> x < d} =
        proots_count (P \<circ>\<^sub>p [:c, 1:])
        (poly [:0, d - c:] ` {x. 0 < x \<and> x < 1})"
      using assms by (auto simp:proots_pcompose)
    show "P \<circ>\<^sub>p [:c, 1:] \<noteq> 0"
      by (simp add: pcompose_eq_0 assms(2))
    show "degree [:0, d - c:] = 1"
      using assms by auto
  qed
  moreover have " Bernstein_changes p c d P = Bernstein_changes_01 p Q"
    unfolding Q_def
    apply (rule Bernstein_changes_eq_rescale)
    using assms by auto
  ultimately show ?thesis by auto
qed

subsection \<open>The control polygon of a polynomial\<close>

definition control_points ::
  "nat \<Rightarrow> real \<Rightarrow> real \<Rightarrow> real poly \<Rightarrow> (real \<times> real) list"
where
  "control_points p c d P =
   [(((real i)*d + (real (p - i))*c)/p,
      nth_default 0 (Bernstein_coeffs p c d P) i).
      i \<leftarrow> [0..<(p+1)]]"

lemma line_above:
  fixes a b c d :: real and p :: nat and P :: "real poly"
  assumes hline: "\<And>i. i \<le> p \<Longrightarrow> a * (((real i)*d + (real (p - i))*c)/p) + b \<ge>
                  nth_default 0 (Bernstein_coeffs p c d P) i"
  and hp: "p \<noteq> 0" and hcd: "c \<noteq> d" and hP: "degree P \<le> p"
  shows "\<And>x. c \<le> x \<Longrightarrow> x \<le> d \<Longrightarrow> a*x + b \<ge> poly P x"
proof -
  fix x
  assume hc: "c \<le> x" and  hd: "x \<le> d"

  have bern_eq:"Bernstein_coeffs p c d [:b, a:] =
           [a*(real i * d + real (p - i) * c)/p + b. i \<leftarrow> [0..<(p+1)]]"
  proof -
    have "Bernstein_coeffs p c d [:b, a:] = map (nth_default 0
          (Bernstein_coeffs_01 p ([:b, a:] \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d - c:])))
         [0..<p+1]"
      apply (subst Bernstein_coeffs_eq_rescale["OF" hcd])
      apply (subst map_nth_default[symmetric])
      apply (subst length_Bernstein_coeffs_01)
      by blast
    also have
      "... = map (\<lambda>i. a * (real i * d + real (p - i) * c) / real p + b) [0..<p + 1]"
    proof (rule map_cong)
      fix x assume hx: "x \<in> set [0..<p + 1]"
      have "nth_default 0 (Bernstein_coeffs_01 p
            ([:b, a:] \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d - c:])) x =
            nth_default 0 (Bernstein_coeffs_01 p
            (smult (b + a*c) 1 + smult (a*(d - c)) (monom 1 1))) x"
      proof-
        have "[:b, a:] \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d - c:] =
                  smult (b + a*c) 1 + smult (a*(d - c)) (monom 1 1)"
          by (simp add: monom_altdef pcompose_pCons)
        then show ?thesis by auto
      qed
      also have "... =
          nth_default 0 (Bernstein_coeffs_01 p (smult (b + a * c) 1)) x +
          nth_default 0 (Bernstein_coeffs_01 p (smult (a * (d - c)) (monom 1 1))) x"
        apply (subst Bernstein_coeffs_01_add)
        using hp by (auto simp: degree_monom_eq)
      also have "...  =
            (b + a*c) * nth_default 0 (Bernstein_coeffs_01 p 1) x +
            (a*(d - c)) * nth_default 0 (Bernstein_coeffs_01 p (monom 1 1)) x"
        apply (subst Bernstein_coeffs_01_smult)
        using hp by (auto simp: Bernstein_coeffs_01_smult degree_monom_eq)
      also have "... =
          (b + a * c) * (if x < p + 1 then 1 else 0) +
           a * (d - c) * (real (nth_default 0 [0..<p + 1] x) / real p)"
        apply (subst Bernstein_coeffs_01_1, subst Bernstein_coeffs_01_x[OF hp])
        apply (subst nth_default_replicate_eq, subst nth_default_map_eq[of _ 0])
        by auto
      also have "... =
              (b + a * c) * (if x < p + 1 then 1 else 0) +
              a * (d - c) * (real ([0..<p + 1] ! x) / real p)"
        apply (subst nth_default_nth)
        using hx by auto
      also have "... = (b + a * c) * (if x < p + 1 then 1 else 0) +
              a * (d - c) * (real (0 + x) / real p)"
        apply (subst nth_upt)
        using hx by auto
      also have "... = a * (real x * d + real (p - x) * c) / real p + b"
        apply (subst of_nat_diff)
        using hx hp by (auto simp: field_simps)
      finally show "nth_default 0 (Bernstein_coeffs_01 p
                    ([:b, a:] \<circ>\<^sub>p [:c, 1:] \<circ>\<^sub>p [:0, d - c:])) x =
                    a * (real x * d + real (p - x) * c) / real p + b" .
    qed blast
    finally show ?thesis .
  qed

  have nth_default_geq:"nth_default 0 (Bernstein_coeffs p c d [:b, a:]) i \<ge>
           nth_default 0 (Bernstein_coeffs p c d P) i" for i
  proof -
    show "nth_default 0 (Bernstein_coeffs p c d [:b, a:]) i \<ge>
          nth_default 0 (Bernstein_coeffs p c d P) i"
    proof cases
      define p1 where "p1 \<equiv> p+1"
      assume h: "i \<le> p"
      hence "nth_default 0 (Bernstein_coeffs p c d P) i \<le>
             a * (((real i)*d + (real (p - i))*c)/p) + b"
        by (rule hline)
      also have "... = nth_default 0 (map (\<lambda>i. a * (real i * d
          + real (p - i) * c) / real p + b) [0..<p + 1]) i"
        apply (subst p1_def[symmetric])
        using h apply (auto simp: nth_default_def)
        by (auto simp: p1_def)
      also have "... = nth_default 0 (Bernstein_coeffs p c d [:b, a:]) i"
        using bern_eq by simp
      finally show ?thesis .
    next
      assume h: "\<not>i \<le> p"
      thus ?thesis
        using assms
        by (auto simp: nth_default_def Bernstein_coeffs_eq_rescale
                        length_Bernstein_coeffs_01)
    qed
  qed

  have "poly P x = (\<Sum>k = 0..p.
        poly (smult (nth_default 0 (Bernstein_coeffs p c d P) k)
        (Bernstein_Poly k p c d)) x)"
    apply (subst Bernstein_coeffs_sum[OF hcd hP])
    by (rule poly_sum)
  also have "... \<le> (\<Sum>k = 0..p.
      poly (smult (nth_default 0 (Bernstein_coeffs p c d [:b, a:]) k)
        (Bernstein_Poly k p c d)) x)"
    apply (rule sum_mono)
    using mult_right_mono[OF nth_default_geq] Bernstein_Poly_nonneg[OF hc hd]
    by auto
  also have "... = poly [:b, a:] x"
    apply (subst(2) Bernstein_coeffs_sum[of c d "[:b, a:]" p])
    using assms apply auto[2]
    by (rule poly_sum[symmetric])
  also have "... = a*x + b" by force
  finally show "poly P x \<le> a*x + b" .
qed

end


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

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

datatype Nat = Z | S "Nat"

fun map :: "('a => 'b) => 'a list => 'b list" where
  "map f (nil2) = nil2"
| "map f (cons2 y xs) = cons2 (f y) (map f xs)"

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

fun lmerge :: "Nat list => Nat list => Nat list" where
  "lmerge (nil2) y = y"
| "lmerge (cons2 z x2) (nil2) = cons2 z x2"
| "lmerge (cons2 z x2) (cons2 x3 x4) =
     (if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else
        cons2 x3 (lmerge (cons2 z x2) x4))"

fun pairwise :: "(Nat list) list => (Nat list) list" where
  "pairwise (nil2) = nil2"
| "pairwise (cons2 xs (nil2)) = cons2 xs (nil2)"
| "pairwise (cons2 xs (cons2 ys xss)) =
     cons2 (lmerge xs ys) (pairwise xss)"

(*fun did not finish the proof*)
function mergingbu :: "(Nat list) list => Nat list" where
  "mergingbu (nil2) = nil2"
| "mergingbu (cons2 xs (nil2)) = xs"
| "mergingbu (cons2 xs (cons2 z x2)) =
     mergingbu (pairwise (cons2 xs (cons2 z x2)))"
  by pat_completeness auto

fun msortbu :: "Nat list => Nat list" where
  "msortbu x = mergingbu (map (% (y :: Nat) => cons2 y (nil2)) x)"

fun insert :: "Nat => Nat list => Nat list" where
  "insert x (nil2) = cons2 x (nil2)"
| "insert x (cons2 z xs) =
     (if le x z then cons2 x (cons2 z xs) else cons2 z (insert x xs))"

fun isort :: "Nat list => Nat list" where
  "isort (nil2) = nil2"
| "isort (cons2 y xs) = insert y (isort xs)"

theorem property0 :
  "((msortbu xs) = (isort xs))"
  oops

end


(*  Title:      FOL/ex/Natural_Numbers.thy
    Author:     Markus Wenzel, TU Munich
*)

section {* Natural numbers *}

theory Natural_Numbers
imports FOL
begin

text {*
  Theory of the natural numbers: Peano's axioms, primitive recursion.
  (Modernized version of Larry Paulson's theory "Nat".)  \medskip
*}

typedecl nat
instance nat :: "term" ..

axiomatization
  Zero :: nat    ("0") and
  Suc :: "nat => nat" and
  rec :: "[nat, 'a, [nat, 'a] => 'a] => 'a"
where
  induct [case_names 0 Suc, induct type: nat]:
    "P(0) ==> (!!x. P(x) ==> P(Suc(x))) ==> P(n)" and
  Suc_inject: "Suc(m) = Suc(n) ==> m = n" and
  Suc_neq_0: "Suc(m) = 0 ==> R" and
  rec_0: "rec(0, a, f) = a" and
  rec_Suc: "rec(Suc(m), a, f) = f(m, rec(m, a, f))"

lemma Suc_n_not_n: "Suc(k) \<noteq> k"
proof (induct k)
  show "Suc(0) \<noteq> 0"
  proof
    assume "Suc(0) = 0"
    then show False by (rule Suc_neq_0)
  qed
next
  fix n assume hyp: "Suc(n) \<noteq> n"
  show "Suc(Suc(n)) \<noteq> Suc(n)"
  proof
    assume "Suc(Suc(n)) = Suc(n)"
    then have "Suc(n) = n" by (rule Suc_inject)
    with hyp show False by contradiction
  qed
qed

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

lemma add_0 [simp]: "0 + n = n"
  unfolding add_def by (rule rec_0)

lemma add_Suc [simp]: "Suc(m) + n = Suc(m + n)"
  unfolding add_def by (rule rec_Suc)

lemma add_0_right: "m + 0 = m"
  by (induct m) simp_all

lemma add_Suc_right: "m + Suc(n) = Suc(m + n)"
  by (induct m) simp_all

lemma
  assumes "!!n. f(Suc(n)) = Suc(f(n))"
  shows "f(i + j) = i + f(j)"
  using assms by (induct i) simp_all

end


section \<open>Stochastic Matrices and Markov Models\<close>

text \<open>We interpret stochastic matrices as Markov chain with
  discrete time and finite state and prove that the bind-operation
  on probability mass functions is precisely matrix-vector multiplication.
  As a consequence, the notion of stationary distribution is equivalent to
  being an eigenvector with eigenvalue 1.\<close>

theory Stochastic_Matrix_Markov_Models
imports
  Markov_Models.Classifying_Markov_Chain_States
  Stochastic_Vector_PMF
begin

definition transition_of_st_mat :: "'i st_mat \<Rightarrow> 'i :: finite \<Rightarrow> 'i pmf" where
  "transition_of_st_mat a i = pmf_as_measure.pmf_of_st_vec (transition_vec_of_st_mat a i)"

lemma st_vec_transition_vec_of_st_mat[simp]:
  "st_vec (transition_vec_of_st_mat A a) $ i = st_mat A $ i $ a"
  by (transfer, auto simp: column_def)

locale transition_matrix = pmf_as_measure +
  fixes A :: "'i :: finite st_mat"
begin
sublocale MC_syntax "transition_of_st_mat A" .

lemma measure_pmf_of_st_vec[simp]: "measure_pmf (pmf_of_st_vec x) = measure_of_st_vec x"
  by (rule pmf_as_measure.pmf_of_st_vec.rep_eq)

lemma pmf_transition_of_st_mat[simp]: "pmf (transition_of_st_mat A a) i = st_mat A $ i $ a"
  unfolding transition_of_st_mat_def
  by (transfer, auto simp: measure_def)

lemma bind_is_matrix_vector_mult: "(bind_pmf x (transition_of_st_mat A)) =
  pmf_as_measure.pmf_of_st_vec (A *st st_vec_of_pmf x)"
proof (rule pmf_eqI, goal_cases)
  case (1 i)
  define X where "X = st_vec_of_pmf x"
  have "pmf (bind_pmf x (transition_of_st_mat A)) i =
    (\<Sum>a\<in>UNIV. pmf x a *\<^sub>R pmf (transition_of_st_mat A a) i)"
    unfolding pmf_bind by (subst integral_measure_pmf[of UNIV], auto)
  also have "\<dots> = (\<Sum>a\<in>UNIV. st_mat A $ i $ a * st_vec X $ a)"
    by (rule sum.cong[OF refl], auto simp: X_def)
  also have "\<dots> = (st_mat A *v st_vec X) $ i"
    unfolding matrix_vector_mult_def by auto
  also have "\<dots> = st_vec (A *st X) $ i" unfolding st_mat_mult_st_vec by simp
  also have "\<dots> = pmf (pmf_of_st_vec (A *st X)) i" by simp
  finally show ?case by (simp add: X_def)
qed

lemmas stationary_distribution_alt_def =
  stationary_distribution_def[unfolded bind_is_matrix_vector_mult]

lemma stationary_distribution_implies_pmf_of_st_vec:
  assumes "stationary_distribution N"
  shows "\<exists> x. N = pmf_of_st_vec x"
proof -
  from assms[unfolded stationary_distribution_alt_def] show ?thesis by auto
qed

lemma stationary_distribution_pmf_of_st_vec:
  "stationary_distribution (pmf_of_st_vec x) = (A *st x = x)"
  unfolding stationary_distribution_alt_def pmf_of_st_vec_inj by auto
end
end


(*  Author:     Paulo Emílio de Vilhena
*)

theory Cycles
  imports
    "HOL-Library.FuncSet"
Permutations
begin

section \<open>Cycles\<close>

subsection \<open>Definitions\<close>

abbreviation cycle :: "'a list \<Rightarrow> bool"
  where "cycle cs \<equiv> distinct cs"

fun cycle_of_list :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a"
  where
    "cycle_of_list (i # j # cs) = transpose i j \<circ> cycle_of_list (j # cs)"
  | "cycle_of_list cs = id"

subsection \<open>Basic Properties\<close>

text \<open>We start proving that the function derived from a cycle rotates its support list.\<close>

lemma id_outside_supp:
  assumes "x \<notin> set cs" shows "(cycle_of_list cs) x = x"
  using assms by (induct cs rule: cycle_of_list.induct) (simp_all)

lemma permutation_of_cycle: "permutation (cycle_of_list cs)"
proof (induct cs rule: cycle_of_list.induct)
  case 1 thus ?case
    using permutation_compose[OF permutation_swap_id] unfolding comp_apply by simp
qed simp_all

lemma cycle_permutes: "(cycle_of_list cs) permutes (set cs)"
  using permutation_bijective[OF permutation_of_cycle] id_outside_supp[of _ cs]
  by (simp add: bij_iff permutes_def)

theorem cyclic_rotation:
  assumes "cycle cs" shows "map ((cycle_of_list cs) ^^ n) cs = rotate n cs"
proof -
  { have "map (cycle_of_list cs) cs = rotate1 cs" using assms(1)
    proof (induction cs rule: cycle_of_list.induct)
      case (1 i j cs)
      then have \<open>i \<notin> set cs\<close> \<open>j \<notin> set cs\<close>
        by auto
      then have \<open>map (Transposition.transpose i j) cs = cs\<close>
        by (auto intro: map_idI simp add: transpose_eq_iff)
      show ?case
      proof (cases)
        assume "cs = Nil" thus ?thesis by simp
      next
        assume "cs \<noteq> Nil" hence ge_two: "length (j # cs) \<ge> 2"
          using not_less by auto
        have "map (cycle_of_list (i # j # cs)) (i # j # cs) =
              map (transpose i j) (map (cycle_of_list (j # cs)) (i # j # cs))" by simp
        also have " ... = map (transpose i j) (i # (rotate1 (j # cs)))"
          by (metis "1.IH" "1.prems" distinct.simps(2) id_outside_supp list.simps(9))
        also have " ... = map (transpose i j) (i # (cs @ [j]))" by simp
        also have " ... = j # (map (transpose i j) cs) @ [i]" by simp
        also have " ... = j # cs @ [i]"
          using \<open>map (Transposition.transpose i j) cs = cs\<close> by simp
        also have " ... = rotate1 (i # j # cs)" by simp
        finally show ?thesis .
      qed
    qed simp_all }
  note cyclic_rotation' = this

  show ?thesis
    using cyclic_rotation' by (induct n) (auto, metis map_map rotate1_rotate_swap rotate_map)
qed

corollary cycle_is_surj:
  assumes "cycle cs" shows "(cycle_of_list cs) ` (set cs) = (set cs)"
  using cyclic_rotation[OF assms, of "Suc 0"] by (simp add: image_set)

corollary cycle_is_id_root:
  assumes "cycle cs" shows "(cycle_of_list cs) ^^ (length cs) = id"
proof -
  have "map ((cycle_of_list cs) ^^ (length cs)) cs = cs"
    unfolding cyclic_rotation[OF assms] by simp
  hence "((cycle_of_list cs) ^^ (length cs)) i = i" if "i \<in> set cs" for i
    using that map_eq_conv by fastforce
  moreover have "((cycle_of_list cs) ^^ n) i = i" if "i \<notin> set cs" for i n
    using id_outside_supp[OF that] by (induct n) (simp_all)
  ultimately show ?thesis
    by fastforce
qed

corollary cycle_of_list_rotate_independent:
  assumes "cycle cs" shows "(cycle_of_list cs) = (cycle_of_list (rotate n cs))"
proof -
  { fix cs :: "'a list" assume cs: "cycle cs"
    have "(cycle_of_list cs) = (cycle_of_list (rotate1 cs))"
    proof -
      from cs have rotate1_cs: "cycle (rotate1 cs)" by simp
      hence "map (cycle_of_list (rotate1 cs)) (rotate1 cs) = (rotate 2 cs)"
        using cyclic_rotation[OF rotate1_cs, of 1] by (simp add: numeral_2_eq_2)
      moreover have "map (cycle_of_list cs) (rotate1 cs) = (rotate 2 cs)"
        using cyclic_rotation[OF cs]
        by (metis One_nat_def Suc_1 funpow.simps(2) id_apply map_map rotate0 rotate_Suc)
      ultimately have "(cycle_of_list cs) i = (cycle_of_list (rotate1 cs)) i" if "i \<in> set cs" for i
        using that map_eq_conv unfolding sym[OF set_rotate1[of cs]] by fastforce
      moreover have "(cycle_of_list cs) i = (cycle_of_list (rotate1 cs)) i" if "i \<notin> set cs" for i
        using that by (simp add: id_outside_supp)
      ultimately show "(cycle_of_list cs) = (cycle_of_list (rotate1 cs))"
        by blast
    qed } note rotate1_lemma = this

  show ?thesis
    using rotate1_lemma[of "rotate n cs"] by (induct n) (auto, metis assms distinct_rotate rotate1_lemma)
qed

subsection\<open>Conjugation of cycles\<close>

lemma conjugation_of_cycle:
  assumes "cycle cs" and "bij p"
  shows "p \<circ> (cycle_of_list cs) \<circ> (inv p) = cycle_of_list (map p cs)"
  using assms
proof (induction cs rule: cycle_of_list.induct)
  case (1 i j cs)
  have "p \<circ> cycle_of_list (i # j # cs) \<circ> inv p =
       (p \<circ> (transpose i j) \<circ> inv p) \<circ> (p \<circ> cycle_of_list (j # cs) \<circ> inv p)"
    by (simp add: assms(2) bij_is_inj fun.map_comp)
  also have " ... = (transpose (p i) (p j)) \<circ> (p \<circ> cycle_of_list (j # cs) \<circ> inv p)"
    using "1.prems"(2) by (simp add: bij_inv_eq_iff transpose_apply_commute fun_eq_iff bij_betw_inv_into_left)
  finally have "p \<circ> cycle_of_list (i # j # cs) \<circ> inv p =
               (transpose (p i) (p j)) \<circ> (cycle_of_list (map p (j # cs)))"
    using "1.IH" "1.prems"(1) assms(2) by fastforce
  thus ?case by (simp add: fun_eq_iff)
next
  case "2_1" thus ?case
    by (metis bij_is_surj comp_id cycle_of_list.simps(2) list.simps(8) surj_iff)
next
  case "2_2" thus ?case
    by (metis bij_is_surj comp_id cycle_of_list.simps(3) list.simps(8) list.simps(9) surj_iff)
qed

subsection\<open>When Cycles Commute\<close>

lemma cycles_commute:
  assumes "cycle p" "cycle q" and "set p \<inter> set q = {}"
  shows "(cycle_of_list p) \<circ> (cycle_of_list q) = (cycle_of_list q) \<circ> (cycle_of_list p)"
proof
  { fix p :: "'a list" and q :: "'a list" and i :: "'a"
    assume A: "cycle p" "cycle q" "set p \<inter> set q = {}" "i \<in> set p" "i \<notin> set q"
    have "((cycle_of_list p) \<circ> (cycle_of_list q)) i =
          ((cycle_of_list q) \<circ> (cycle_of_list p)) i"
    proof -
      have "((cycle_of_list p) \<circ> (cycle_of_list q)) i = (cycle_of_list p) i"
        using id_outside_supp[OF A(5)] by simp
      also have " ... = ((cycle_of_list q) \<circ> (cycle_of_list p)) i"
        using id_outside_supp[of "(cycle_of_list p) i"] cycle_is_surj[OF A(1)] A(3,4) by fastforce
      finally show ?thesis .
    qed } note aui_lemma = this

  fix i consider "i \<in> set p" "i \<notin> set q" | "i \<notin> set p" "i \<in> set q" | "i \<notin> set p" "i \<notin> set q"
    using \<open>set p \<inter> set q = {}\<close> by blast
  thus "((cycle_of_list p) \<circ> (cycle_of_list q)) i = ((cycle_of_list q) \<circ> (cycle_of_list p)) i"
  proof cases
    case 1 thus ?thesis
      using aui_lemma[OF assms] by simp
  next
    case 2 thus ?thesis
      using aui_lemma[OF assms(2,1)] assms(3) by (simp add: ac_simps)
  next
    case 3 thus ?thesis
      by (simp add: id_outside_supp)
  qed
qed

subsection \<open>Cycles from Permutations\<close>

subsubsection \<open>Exponentiation of permutations\<close>

text \<open>Some important properties of permutations before defining how to extract its cycles.\<close>

lemma permutation_funpow:
  assumes "permutation p" shows "permutation (p ^^ n)"
  using assms by (induct n) (simp_all add: permutation_compose)

lemma permutes_funpow:
  assumes "p permutes S" shows "(p ^^ n) permutes S"
  using assms by (induct n) (simp add: permutes_def, metis funpow_Suc_right permutes_compose)

lemma funpow_diff:
  assumes "inj p" and "i \<le> j" "(p ^^ i) a = (p ^^ j) a" shows "(p ^^ (j - i)) a = a"
proof -
  have "(p ^^ i) ((p ^^ (j - i)) a) = (p ^^ i) a"
    using assms(2-3) by (metis (no_types) add_diff_inverse_nat funpow_add not_le o_def)
  thus ?thesis
    unfolding inj_eq[OF inj_fn[OF assms(1)], of i] .
qed

lemma permutation_is_nilpotent:
  assumes "permutation p" obtains n where "(p ^^ n) = id" and "n > 0"
proof -
  obtain S where "finite S" and "p permutes S"
    using assms unfolding permutation_permutes by blast
  hence "\<exists>n. (p ^^ n) = id \<and> n > 0"
  proof (induct S arbitrary: p)
    case empty thus ?case
      using id_funpow[of 1] unfolding permutes_empty by blast
  next
    case (insert s S)
    have "(\<lambda>n. (p ^^ n) s) ` UNIV \<subseteq> (insert s S)"
      using permutes_in_image[OF permutes_funpow[OF insert(4)], of _ s] by auto
    hence "\<not> inj_on (\<lambda>n. (p ^^ n) s)  UNIV"
      using insert(1) infinite_iff_countable_subset unfolding sym[OF finite_insert, of S s] by metis
    then obtain i j where ij: "i < j" "(p ^^ i) s = (p ^^ j) s"
      unfolding inj_on_def by (metis nat_neq_iff)
    hence "(p ^^ (j - i)) s = s"
      using funpow_diff[OF permutes_inj[OF insert(4)]] le_eq_less_or_eq by blast
    hence "p ^^ (j - i) permutes S"
      using permutes_superset[OF permutes_funpow[OF insert(4), of "j - i"], of S] by auto
    then obtain n where n: "((p ^^ (j - i)) ^^ n) = id" "n > 0"
      using insert(3) by blast
    thus ?case
      using ij(1) nat_0_less_mult_iff zero_less_diff unfolding funpow_mult by metis
  qed
  thus thesis
    using that by blast
qed

lemma permutation_is_nilpotent':
  assumes "permutation p" obtains n where "(p ^^ n) = id" and "n > m"
proof -
  obtain n where "(p ^^ n) = id" and "n > 0"
    using permutation_is_nilpotent[OF assms] by blast
  then obtain k where "n * k > m"
    by (metis dividend_less_times_div mult_Suc_right)
  from \<open>(p ^^ n) = id\<close> have "p ^^ (n * k) = id"
    by (induct k) (simp, metis funpow_mult id_funpow)
  with \<open>n * k > m\<close> show thesis
    using that by blast
qed

subsubsection \<open>Extraction of cycles from permutations\<close>

definition least_power :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> nat"
  where "least_power f x = (LEAST n. (f ^^ n) x = x \<and> n > 0)"

abbreviation support :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a list"
  where "support p x \<equiv> map (\<lambda>i. (p ^^ i) x) [0..< (least_power p x)]"

lemma least_powerI:
  assumes "(f ^^ n) x = x" and "n > 0"
  shows "(f ^^ (least_power f x)) x = x" and "least_power f x > 0"
  using assms unfolding least_power_def by (metis (mono_tags, lifting) LeastI)+

lemma least_power_le:
  assumes "(f ^^ n) x = x" and "n > 0" shows "least_power f x \<le> n"
  using assms unfolding least_power_def by (simp add: Least_le)

lemma least_power_of_permutation:
  assumes "permutation p" shows "(p ^^ (least_power p a)) a = a" and "least_power p a > 0"
  using permutation_is_nilpotent[OF assms] least_powerI by (metis id_apply)+

lemma least_power_gt_one:
  assumes "permutation p" and "p a \<noteq> a" shows "least_power p a > Suc 0"
  using least_power_of_permutation[OF assms(1)] assms(2)
  by (metis Suc_lessI funpow.simps(2) funpow_simps_right(1) o_id)

lemma least_power_minimal:
  assumes "(p ^^ n) a = a" shows "(least_power p a) dvd n"
proof (cases "n = 0", simp)
  let ?lpow = "least_power p"

  assume "n \<noteq> 0" then have "n > 0" by simp
  hence "(p ^^ (?lpow a)) a = a" and "least_power p a > 0"
    using assms unfolding least_power_def by (metis (mono_tags, lifting) LeastI)+
  hence aux_lemma: "(p ^^ ((?lpow a) * k)) a = a" for k :: nat
    by (induct k) (simp_all add: funpow_add)

  have "(p ^^ (n mod ?lpow a)) ((p ^^ (n - (n mod ?lpow a))) a) = (p ^^ n) a"
    by (metis add_diff_inverse_nat funpow_add mod_less_eq_dividend not_less o_apply)
  with \<open>(p ^^ n) a = a\<close> have "(p ^^ (n mod ?lpow a)) a = a"
    using aux_lemma by (simp add: minus_mod_eq_mult_div)
  hence "?lpow a \<le> n mod ?lpow a" if "n mod ?lpow a > 0"
    using least_power_le[OF _ that, of p a] by simp
  with \<open>least_power p a > 0\<close> show "(least_power p a) dvd n"
    using mod_less_divisor not_le by blast
qed

lemma least_power_dvd:
  assumes "permutation p" shows "(least_power p a) dvd n \<longleftrightarrow> (p ^^ n) a = a"
proof
  show "(p ^^ n) a = a \<Longrightarrow> (least_power p a) dvd n"
    using least_power_minimal[of _ p] by simp
next
  have "(p ^^ ((least_power p a) * k)) a = a" for k :: nat
    using least_power_of_permutation(1)[OF assms(1)] by (induct k) (simp_all add: funpow_add)
  thus "(least_power p a) dvd n \<Longrightarrow> (p ^^ n) a = a" by blast
qed

theorem cycle_of_permutation:
  assumes "permutation p" shows "cycle (support p a)"
proof -
  have "(least_power p a) dvd (j - i)" if "i \<le> j" "j < least_power p a" and "(p ^^ i) a = (p ^^ j) a" for i j
    using funpow_diff[OF bij_is_inj that(1,3)] assms by (simp add: permutation least_power_dvd)
  moreover have "i = j" if "i \<le> j" "j < least_power p a" and "(least_power p a) dvd (j - i)" for i j
    using that le_eq_less_or_eq nat_dvd_not_less by auto
  ultimately have "inj_on (\<lambda>i. (p ^^ i) a) {..< (least_power p a)}"
    unfolding inj_on_def by (metis le_cases lessThan_iff)
  thus ?thesis
    by (simp add: atLeast_upt distinct_map)
qed

subsection \<open>Decomposition on Cycles\<close>

text \<open>We show that a permutation can be decomposed on cycles\<close>

subsubsection \<open>Preliminaries\<close>

lemma support_set:
  assumes "permutation p" shows "set (support p a) = range (\<lambda>i. (p ^^ i) a)"
proof
  show "set (support p a) \<subseteq> range (\<lambda>i. (p ^^ i) a)"
    by auto
next
  show "range (\<lambda>i. (p ^^ i) a) \<subseteq> set (support p a)"
  proof (auto)
    fix i
    have "(p ^^ i) a = (p ^^ (i mod (least_power p a))) ((p ^^ (i - (i mod (least_power p a)))) a)"
      by (metis add_diff_inverse_nat funpow_add mod_less_eq_dividend not_le o_apply)
    also have " ... = (p ^^ (i mod (least_power p a))) a"
      using least_power_dvd[OF assms] by (metis dvd_minus_mod)
    also have " ... \<in> (\<lambda>i. (p ^^ i) a) ` {0..< (least_power p a)}"
      using least_power_of_permutation(2)[OF assms] by fastforce
    finally show "(p ^^ i) a \<in> (\<lambda>i. (p ^^ i) a) ` {0..< (least_power p a)}" .
  qed
qed

lemma disjoint_support:
  assumes "permutation p" shows "disjoint (range (\<lambda>a. set (support p a)))" (is "disjoint ?A")
proof (rule disjointI)
  { fix i j a b
    assume "set (support p a) \<inter> set (support p b) \<noteq> {}" have "set (support p a) \<subseteq> set (support p b)"
      unfolding support_set[OF assms]
    proof (auto)
      from \<open>set (support p a) \<inter> set (support p b) \<noteq> {}\<close>
      obtain i j where ij: "(p ^^ i) a = (p ^^ j) b"
        by auto

      fix k
      have "(p ^^ k) a = (p ^^ (k + (least_power p a) * l)) a" for l
        using least_power_dvd[OF assms] by (induct l) (simp, metis dvd_triv_left funpow_add o_def)
      then obtain m where "m \<ge> i" and "(p ^^ m) a = (p ^^ k) a"
        using least_power_of_permutation(2)[OF assms]
        by (metis dividend_less_times_div le_eq_less_or_eq mult_Suc_right trans_less_add2)
      hence "(p ^^ m) a = (p ^^ (m - i)) ((p ^^ i) a)"
        by (metis Nat.le_imp_diff_is_add funpow_add o_apply)
      with \<open>(p ^^ m) a = (p ^^ k) a\<close> have "(p ^^ k) a = (p ^^ ((m - i) + j)) b"
        unfolding ij by (simp add: funpow_add)
      thus "(p ^^ k) a \<in> range (\<lambda>i. (p ^^ i) b)"
        by blast
    qed } note aux_lemma = this

  fix supp_a supp_b
  assume "supp_a \<in> ?A" and "supp_b \<in> ?A"
  then obtain a b where a: "supp_a = set (support p a)" and b: "supp_b = set (support p b)"
    by auto
  assume "supp_a \<noteq> supp_b" thus "supp_a \<inter> supp_b = {}"
    using aux_lemma unfolding a b by blast
qed

lemma disjoint_support':
  assumes "permutation p"
  shows "set (support p a) \<inter> set (support p b) = {} \<longleftrightarrow> a \<notin> set (support p b)"
proof -
  have "a \<in> set (support p a)"
    using least_power_of_permutation(2)[OF assms] by force
  show ?thesis
  proof
    assume "set (support p a) \<inter> set (support p b) = {}"
    with \<open>a \<in> set (support p a)\<close> show "a \<notin> set (support p b)"
      by blast
  next
    assume "a \<notin> set (support p b)" show "set (support p a) \<inter> set (support p b) = {}"
    proof (rule ccontr)
      assume "set (support p a) \<inter> set (support p b) \<noteq> {}"
      hence "set (support p a) = set (support p b)"
        using disjoint_support[OF assms] by (meson UNIV_I disjoint_def image_iff)
      with \<open>a \<in> set (support p a)\<close> and \<open>a \<notin> set (support p b)\<close> show False
        by simp
    qed
  qed
qed

lemma support_coverture:
  assumes "permutation p" shows "\<Union> { set (support p a) | a. p a \<noteq> a } = { a. p a \<noteq> a }"
proof
  show "{ a. p a \<noteq> a } \<subseteq> \<Union> { set (support p a) | a. p a \<noteq> a }"
  proof
    fix a assume "a \<in> { a. p a \<noteq> a }"
    have "a \<in> set (support p a)"
      using least_power_of_permutation(2)[OF assms, of a] by force
    with \<open>a \<in> { a. p a \<noteq> a }\<close> show "a \<in> \<Union> { set (support p a) | a. p a \<noteq> a }"
      by blast
  qed
next
  show "\<Union> { set (support p a) | a. p a \<noteq> a } \<subseteq> { a. p a \<noteq> a }"
  proof
    fix b assume "b \<in> \<Union> { set (support p a) | a. p a \<noteq> a }"
    then obtain a i where "p a \<noteq> a" and "(p ^^ i) a = b"
      by auto
    have "p a = a" if "(p ^^ i) a = (p ^^ Suc i) a"
      using funpow_diff[OF bij_is_inj _ that] assms unfolding permutation by simp
    with \<open>p a \<noteq> a\<close> and \<open>(p ^^ i) a = b\<close> show "b \<in> { a. p a \<noteq> a }"
      by auto
  qed
qed

theorem cycle_restrict:
  assumes "permutation p" and "b \<in> set (support p a)" shows "p b = (cycle_of_list (support p a)) b"
proof -
  note least_power_props [simp] = least_power_of_permutation[OF assms(1)]

  have "map (cycle_of_list (support p a)) (support p a) = rotate1 (support p a)"
    using cyclic_rotation[OF cycle_of_permutation[OF assms(1)], of 1 a] by simp
  hence "map (cycle_of_list (support p a)) (support p a) = tl (support p a) @ [ a ]"
    by (simp add: hd_map rotate1_hd_tl)
  also have " ... = map p (support p a)"
  proof (rule nth_equalityI, auto)
    fix i assume "i < least_power p a" show "(tl (support p a) @ [a]) ! i = p ((p ^^ i) a)"
    proof (cases)
      assume i: "i = least_power p a - 1"
      hence "(tl (support p a) @ [ a ]) ! i = a"
        by (metis (no_types, lifting) diff_zero length_map length_tl length_upt nth_append_length)
      also have " ... = p ((p ^^ i) a)"
        by (metis (mono_tags, opaque_lifting) least_power_props i Suc_diff_1 funpow_simps_right(2) funpow_swap1 o_apply)
      finally show ?thesis .
    next
      assume "i \<noteq> least_power p a - 1"
      with \<open>i < least_power p a\<close> have "i < least_power p a - 1"
        by simp
      hence "(tl (support p a) @ [ a ]) ! i = (p ^^ (Suc i)) a"
        by (metis One_nat_def Suc_eq_plus1 add.commute length_map length_upt map_tl nth_append nth_map_upt tl_upt)
      thus ?thesis
        by simp
    qed
  qed
  finally have "map (cycle_of_list (support p a)) (support p a) = map p (support p a)" .
  thus ?thesis
    using assms(2) by auto
qed

subsubsection\<open>Decomposition\<close>

inductive cycle_decomp :: "'a set \<Rightarrow> ('a \<Rightarrow> 'a) \<Rightarrow> bool"
  where
    empty:  "cycle_decomp {} id"
  | comp: "\<lbrakk> cycle_decomp I p; cycle cs; set cs \<inter> I = {} \<rbrakk> \<Longrightarrow>
             cycle_decomp (set cs \<union> I) ((cycle_of_list cs) \<circ> p)"

lemma semidecomposition:
  assumes "p permutes S" and "finite S"
  shows "(\<lambda>y. if y \<in> (S - set (support p a)) then p y else y) permutes (S - set (support p a))"
proof (rule bij_imp_permutes)
  show "(if b \<in> (S - set (support p a)) then p b else b) = b" if "b \<notin> S - set (support p a)" for b
    using that by auto
next
  have is_permutation: "permutation p"
    using assms unfolding permutation_permutes by blast

  let ?q = "\<lambda>y. if y \<in> (S - set (support p a)) then p y else y"
  show "bij_betw ?q (S - set (support p a)) (S - set (support p a))"
  proof (rule bij_betw_imageI)
    show "inj_on ?q (S - set (support p a))"
      using permutes_inj[OF assms(1)] unfolding inj_on_def by auto
  next
    have aux_lemma: "set (support p s) \<subseteq> (S - set (support p a))" if "s \<in> S - set (support p a)" for s
    proof -
      have "(p ^^ i) s \<in> S" for i
        using that unfolding permutes_in_image[OF permutes_funpow[OF assms(1)]] by simp
      thus ?thesis
        using that disjoint_support'[OF is_permutation, of s a] by auto
    qed
    have "(p ^^ 1) s \<in> set (support p s)" for s
      unfolding support_set[OF is_permutation] by blast
    hence "p s \<in> set (support p s)" for s
      by simp
    hence "p ` (S - set (support p a)) \<subseteq> S - set (support p a)"
      using aux_lemma by blast
    moreover have "(p ^^ ((least_power p s) - 1)) s \<in> set (support p s)" for s
      unfolding support_set[OF is_permutation] by blast
    hence "\<exists>s' \<in> set (support p s). p s' = s" for s
      using least_power_of_permutation[OF is_permutation] by (metis Suc_diff_1 funpow.simps(2) o_apply)
    hence "S - set (support p a) \<subseteq> p ` (S - set (support p a))"
      using aux_lemma
      by (clarsimp simp add: image_iff) (metis image_subset_iff)
    ultimately show "?q ` (S - set (support p a)) = (S - set (support p a))"
      by auto
  qed
qed

theorem cycle_decomposition:
  assumes "p permutes S" and "finite S" shows "cycle_decomp S p"
  using assms
proof(induct "card S" arbitrary: S p rule: less_induct)
  case less show ?case
  proof (cases)
    assume "S = {}" thus ?thesis
      using empty less(2) by auto
  next
    have is_permutation: "permutation p"
      using less(2-3) unfolding permutation_permutes by blast

    assume "S \<noteq> {}" then obtain s where "s \<in> S"
      by blast
    define q where "q = (\<lambda>y. if y \<in> (S - set (support p s)) then p y else y)"
    have "(cycle_of_list (support p s) \<circ> q) = p"
    proof
      fix a
      consider "a \<in> S - set (support p s)" | "a \<in> set (support p s)" | "a \<notin> S" "a \<notin> set (support p s)"
        by blast
      thus "((cycle_of_list (support p s) \<circ> q)) a = p a"
      proof cases
        case 1
        have "(p ^^ 1) a \<in> set (support p a)"
          unfolding support_set[OF is_permutation] by blast
        with \<open>a \<in> S - set (support p s)\<close> have "p a \<notin> set (support p s)"
          using disjoint_support'[OF is_permutation, of a s] by auto
        with \<open>a \<in> S - set (support p s)\<close> show ?thesis
          using id_outside_supp[of _ "support p s"] unfolding q_def by simp
      next
        case 2 thus ?thesis
          using cycle_restrict[OF is_permutation] unfolding q_def by simp
      next
        case 3 thus ?thesis
          using id_outside_supp[OF 3(2)] less(2) permutes_not_in unfolding q_def by fastforce
      qed
    qed

    moreover from \<open>s \<in> S\<close> have "(p ^^ i) s \<in> S" for i
      unfolding permutes_in_image[OF permutes_funpow[OF less(2)]] .
    hence "set (support p s) \<union> (S - set (support p s)) = S"
      by auto

    moreover have "s \<in> set (support p s)"
      using least_power_of_permutation[OF is_permutation] by force
    with \<open>s \<in> S\<close> have "card (S - set (support p s)) < card S"
      using less(3) by (metis DiffE card_seteq linorder_not_le subsetI)
    hence "cycle_decomp (S - set (support p s)) q"
      using less(1)[OF _ semidecomposition[OF less(2-3)], of s] less(3) unfolding q_def by blast

    moreover show ?thesis
      using comp[OF calculation(3) cycle_of_permutation[OF is_permutation], of s]
      unfolding calculation(1-2) by blast
  qed
qed

end