(*
Authors:

  Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk;
  Yijun He, University of Cambridge, yh403@cam.ac.uk
*)

section \<open>Further Results on Tensor Products\<close>

theory More_Tensor
imports
  Quantum
  Tensor
  Jordan_Normal_Form.Matrix
  Basics
begin

lemma tensor_prod_2 [simp]:
"mult.vec_vec_Tensor (*) [x1::complex,x2] [x3, x4] = [x1 * x3, x1 * x4, x2 * x3, x2 * x4]"
proof -
  have "Matrix_Tensor.mult (1::complex) (*)"
    by (simp add: Matrix_Tensor.mult_def)
  thus "mult.vec_vec_Tensor (*) [x1::complex,x2] [x3,x4] = [x1*x3,x1*x4,x2*x3,x2*x4]"
    using mult.vec_vec_Tensor_def[of "(1::complex)" "(*)"] mult.times_def[of "(1::complex)" "(*)"] by simp
qed

lemma list_vec [simp]:
  assumes "v \<in> state_qbit 1"
  shows "list_of_vec v = [v $ 0, v $ 1]"
proof -
  have "Rep_vec v = (fst(Rep_vec v), snd(Rep_vec v))" by simp
  also have "\<dots> = (2, vec_index v)"
    by (metis (mono_tags, lifting) assms dim_vec.rep_eq mem_Collect_eq power_one_right state_qbit_def vec_index.rep_eq)
  moreover have "[0..<2::nat] = [0,1]"
    by(simp add: upt_rec)
  ultimately show ?thesis
    by(simp add: list_of_vec_def)
qed

lemma vec_tensor_prod_2 [simp]:
  assumes "v \<in> state_qbit 1" and "w \<in> state_qbit 1"
  shows "v \<otimes> w = vec_of_list [v $ 0 * w $ 0, v $ 0 * w $ 1, v $ 1 * w $ 0, v $ 1 * w $ 1]"
proof -
  have "list_of_vec v = [v $ 0, v $ 1]"
    using assms by simp
  moreover have "list_of_vec w = [w $ 0, w $ 1]"
    using assms by simp
  ultimately show "v \<otimes> w = vec_of_list [v $ 0 * w $ 0, v $ 0 * w $ 1, v $ 1 * w $ 0, v $ 1 * w $ 1]"
    by(simp add: tensor_vec_def)
qed

lemma vec_dim_of_vec_of_list [simp]:
  assumes "length l = n"
  shows "dim_vec (vec_of_list l) = n"
  using assms vec_of_list_def by simp

lemma vec_tensor_prod_2_bis [simp]:
  assumes "v \<in> state_qbit 1" and "w \<in> state_qbit 1"
  shows "v \<otimes> w = Matrix.vec 4 (\<lambda>i. if i = 0 then v $ 0 * w $ 0 else
                                      if i = 3 then v $ 1 * w $ 1 else
                                          if i = 1 then v $ 0 * w $ 1 else v $ 1 * w $ 0)"
proof
  define u where "u = Matrix.vec 4 (\<lambda>i. if i = 0 then v $ 0 * w $ 0 else
                                          if i = 3 then v $ 1 * w $ 1 else
                                            if i = 1 then v $ 0 * w $ 1 else v $ 1 * w $ 0)"
  then show f2:"dim_vec (v \<otimes> w) = dim_vec u"
    using assms by simp
  show "\<And>i. i < dim_vec u \<Longrightarrow> (v \<otimes> w) $ i = u $ i"
    apply (auto simp: u_def)
    using assms apply auto[3]
    apply (simp add: numeral_3_eq_3)
    using u_def vec_of_list_index vec_tensor_prod_2 index_is_2
    by (metis (no_types, lifting) One_nat_def assms nth_Cons_0 nth_Cons_Suc numeral_2_eq_2)
qed

lemma index_col_mat_of_cols_list [simp]:
  assumes "i < n" and "j < length l"
  shows "Matrix.col (mat_of_cols_list n l) j $ i = l ! j ! i"
  apply (auto simp: Matrix.col_def mat_of_cols_list_def)
  using assms less_le_trans by fastforce

lemma multTensor2 [simp]:
  assumes a1:"A = Matrix.mat 2 1 (\<lambda>(i,j). if i = 0 then a0 else a1)" and
          a2:"B = Matrix.mat 2 1 (\<lambda>(i,j). if i = 0 then b0 else b1)"
  shows "mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list B) = [[a0*b0, a0*b1, a1*b0, a1*b1]]"
proof -
  have "mat_to_cols_list A = [[a0, a1]]"
    by (auto simp: a1 mat_to_cols_list_def) (simp add: numeral_2_eq_2)
  moreover have f2:"mat_to_cols_list B = [[b0, b1]]"
    by (auto simp: a2 mat_to_cols_list_def) (simp add: numeral_2_eq_2)
  ultimately have "mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list B) =
                   mult.Tensor (*) [[a0,a1]] [[b0,b1]]" by simp
  thus ?thesis
    using mult.Tensor_def[of "(1::complex)" "(*)"] mult.times_def[of "(1::complex)" "(*)"]
    by (metis (mono_tags, lifting) append_self_conv list.simps(6) mult.Tensor.simps(2) mult.vec_mat_Tensor.simps(1)
mult.vec_mat_Tensor.simps(2) plus_mult_cpx plus_mult_def tensor_prod_2)
qed

lemma multTensor2_bis [simp]:
  assumes a1:"dim_row A = 2" and a2:"dim_col A = 1" and a3:"dim_row B = 2" and a4:"dim_col B = 1"
  shows "mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list B) =
[[A $$ (0,0) * B $$ (0,0), A $$ (0,0) *  B $$ (1,0), A $$ (1,0) * B $$ (0,0), A $$ (1,0) * B $$ (1,0)]]"
proof -
  have "mat_to_cols_list A = [[A $$ (0,0), A $$ (1,0)]]"
    by (auto simp: a1 a2 mat_to_cols_list_def) (simp add: numeral_2_eq_2)
  moreover have f2:"mat_to_cols_list B = [[B $$ (0,0), B $$ (1,0)]]"
    by (auto simp: a3 a4 mat_to_cols_list_def) (simp add: numeral_2_eq_2)
  ultimately have "mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list B) =
                   mult.Tensor (*) [[A $$ (0,0), A $$ (1,0)]] [[B $$ (0,0), B $$ (1,0)]]" by simp
  thus ?thesis
    using mult.Tensor_def[of "(1::complex)" "(*)"] mult.times_def[of "(1::complex)" "(*)"]
    by (smt append_self_conv list.simps(6) mult.Tensor.simps(2) mult.vec_mat_Tensor.simps(1)
mult.vec_mat_Tensor.simps(2) plus_mult_cpx plus_mult_def tensor_prod_2)
qed

lemma mat_tensor_prod_2_prelim [simp]:
  assumes "state 1 v" and "state 1 w"
  shows "v \<Otimes> w = mat_of_cols_list 4
[[v $$ (0,0) * w $$ (0,0), v $$ (0,0) * w $$ (1,0), v $$ (1,0) * w $$ (0,0), v $$ (1,0) * w $$ (1,0)]]"
proof
  define u where "u = mat_of_cols_list 4
[[v $$ (0,0) * w $$ (0,0), v $$ (0,0) * w $$ (1,0), v $$ (1,0) * w $$ (0,0), v $$ (1,0) * w $$ (1,0)]]"
  then show f1:"dim_row (v \<Otimes> w) = dim_row u"
    using assms state_def mat_of_cols_list_def tensor_mat_def by simp
  show f2:"dim_col (v \<Otimes> w) = dim_col u"
    using assms state_def mat_of_cols_list_def tensor_mat_def u_def by simp
  show "\<And>i j. i < dim_row u \<Longrightarrow> j < dim_col u \<Longrightarrow>  (v \<Otimes> w) $$ (i, j) = u $$ (i, j)"
      using u_def tensor_mat_def assms state_def by simp
qed

lemma mat_tensor_prod_2_col [simp]:
  assumes "state 1 v" and "state 1 w"
  shows "Matrix.col (v \<Otimes> w) 0 = Matrix.col v 0 \<otimes> Matrix.col w 0"
proof
  show f1:"dim_vec (Matrix.col (v \<Otimes> w) 0) = dim_vec (Matrix.col v 0 \<otimes> Matrix.col w 0)"
    using assms vec_tensor_prod_2_bis
    by (smt Tensor.mat_of_cols_list_def dim_col dim_row_mat(1) dim_vec mat_tensor_prod_2_prelim state.state_to_state_qbit)
next
  show "\<And>i. i<dim_vec (Matrix.col v 0 \<otimes> Matrix.col w 0) \<Longrightarrow> Matrix.col (v \<Otimes> w) 0 $ i = (Matrix.col v 0 \<otimes> Matrix.col w 0) $ i"
  proof -
    have "dim_vec (Matrix.col v 0 \<otimes> Matrix.col w 0) = 4"
      by (metis (no_types, lifting) assms(1) assms(2) dim_vec state.state_to_state_qbit vec_tensor_prod_2_bis)
    moreover have "(Matrix.col v 0 \<otimes> Matrix.col w 0) $ 0 = v $$ (0,0) * w $$ (0,0)"
      using assms vec_tensor_prod_2 state.state_to_state_qbit col_index_of_mat_col
      by (smt nth_Cons_0 power_one_right state_def vec_of_list_index zero_less_numeral)
    moreover have "\<dots> = Matrix.col (v \<Otimes> w) 0 $ 0"
      using assms by simp
    moreover have "(Matrix.col v 0 \<otimes> Matrix.col w 0) $ 1 = v $$ (0,0) * w $$ (1,0)"
      using assms vec_tensor_prod_2 state.state_to_state_qbit col_index_of_mat_col
      by (smt One_nat_def Suc_1 lessI nth_Cons_0 power_one_right state_def vec_index_vCons_Suc
vec_of_list_Cons vec_of_list_index zero_less_numeral)
    moreover have "\<dots> = Matrix.col (v \<Otimes> w) 0 $ 1"
      using assms by simp
    moreover have "(Matrix.col v 0 \<otimes> Matrix.col w 0) $ 2 = v $$ (1,0) * w $$ (0,0)"
      using assms vec_tensor_prod_2 state.state_to_state_qbit col_index_of_mat_col
      by (smt One_nat_def Suc_1 lessI nth_Cons_0 power_one_right state_def vec_index_vCons_Suc
vec_of_list_Cons vec_of_list_index zero_less_numeral)
    moreover have "\<dots> = Matrix.col (v \<Otimes> w) 0 $ 2"
      using assms by simp
    moreover have "(Matrix.col v 0 \<otimes> Matrix.col w 0) $ 3 = v $$ (1,0) * w $$ (1,0)"
      using assms vec_tensor_prod_2 state.state_to_state_qbit col_index_of_mat_col numeral_3_eq_3
  by (smt One_nat_def Suc_1 lessI nth_Cons_0 power_one_right state_def vec_index_vCons_Suc
vec_of_list_Cons vec_of_list_index zero_less_numeral)
    moreover have "\<dots> = Matrix.col (v \<Otimes> w) 0 $ 3"
      using assms by simp
    ultimately show "\<And>i. i<dim_vec (Matrix.col v 0 \<otimes> Matrix.col w 0) \<Longrightarrow> Matrix.col (v \<Otimes> w) 0 $ i = (Matrix.col v 0 \<otimes> Matrix.col w 0) $ i"
      using index_sl_four by auto
  qed
qed

lemma mat_tensor_prod_2 [simp]:
  assumes "state 1 v" and "state 1 w"
  shows "v \<Otimes> w = Matrix.mat 4 1 (\<lambda>(i,j). if i = 0 then v $$ (0,0) * w $$ (0,0) else
                                            if i = 3 then v $$ (1,0) * w $$ (1,0) else
                                              if i = 1 then v $$ (0,0) * w $$ (1,0) else
                                                v $$ (1,0) * w $$ (0,0))"
proof
  define u where "u = Matrix.mat 4 1 (\<lambda>(i,j). if i = 0 then v $$ (0,0) * w $$ (0,0) else
                                            if i = 3 then v $$ (1,0) * w $$ (1,0) else
                                              if i = 1 then v $$ (0,0) * w $$ (1,0) else
                                                v $$ (1,0) * w $$ (0,0))"
  then show "dim_row (v \<Otimes> w) = dim_row u"
    using assms tensor_mat_def state_def by(simp add: Tensor.mat_of_cols_list_def)
  also have "\<dots> = 4" by (simp add: u_def)
  show "dim_col (v \<Otimes> w) = dim_col u"
    using u_def assms tensor_mat_def state_def Tensor.mat_of_cols_list_def by simp
  moreover have "\<dots> = 1" by(simp add: u_def)
  ultimately show "\<And>i j. i < dim_row u \<Longrightarrow> j < dim_col u \<Longrightarrow> (v \<Otimes> w) $$ (i, j) = u $$ (i,j)"
  proof -
    fix i j::nat
    assume a1:"i < dim_row u" and a2:"j < dim_col u"
    then have "(v \<Otimes> w) $$ (i, j) = Matrix.col (v \<Otimes> w) 0 $ i"
      using Matrix.col_def u_def assms by simp
    then have f1:"(v \<Otimes> w) $$ (i, j) = (Matrix.col v 0 \<otimes> Matrix.col w 0) $ i"
      using assms mat_tensor_prod_2_col by simp
    have "(Matrix.col v 0 \<otimes> Matrix.col w 0) $ i =
 Matrix.vec 4 (\<lambda>i. if i = 0 then Matrix.col v 0 $ 0 * Matrix.col w 0 $ 0 else
                                      if i = 3 then Matrix.col v 0 $ 1 * Matrix.col w 0 $ 1 else
                                          if i = 1 then Matrix.col v 0 $ 0 * Matrix.col w 0 $ 1 else
                                            Matrix.col v 0 $ 1 * Matrix.col w 0 $ 0) $ i"
      using vec_tensor_prod_2_bis assms state.state_to_state_qbit by presburger
    thus "(v \<Otimes> w) $$ (i, j) = u $$ (i,j)"
      using u_def a1 a2 assms state_def by simp
  qed
qed

lemma mat_tensor_prod_2_bis:
  assumes "state 1 v" and "state 1 w"
  shows "v \<Otimes> w = |Matrix.vec 4 (\<lambda>i. if i = 0 then v $$ (0,0) * w $$ (0,0) else
                                          if i = 3 then v $$ (1,0) * w $$ (1,0) else
                                            if i = 1 then v $$ (0,0) * w $$ (1,0) else
                                              v $$ (1,0) * w $$ (0,0))\<rangle>"
  using assms ket_vec_def mat_tensor_prod_2 by(simp add: mat_eq_iff)

lemma eq_ket_vec:
  fixes u v:: "complex Matrix.vec"
  assumes "u = v"
  shows "|u\<rangle> = |v\<rangle>"
  using assms by simp

lemma mat_tensor_ket_vec:
  assumes "state 1 v" and "state 1 w"
  shows "v \<Otimes> w = |(Matrix.col v 0) \<otimes> (Matrix.col w 0)\<rangle>"
proof -
  have "v \<Otimes> w = |Matrix.col v 0\<rangle> \<Otimes> |Matrix.col w 0\<rangle>"
    using assms state_def by simp
  also have "\<dots> =
|Matrix.vec 4 (\<lambda>i. if i = 0 then |Matrix.col v 0\<rangle> $$ (0,0) * |Matrix.col w 0\<rangle> $$ (0,0) else
                                          if i = 3 then |Matrix.col v 0\<rangle> $$ (1,0) * |Matrix.col w 0\<rangle> $$ (1,0) else
                                            if i = 1 then |Matrix.col v 0\<rangle> $$ (0,0) * |Matrix.col w 0\<rangle> $$ (1,0) else
                                              |Matrix.col v 0\<rangle> $$ (1,0) * |Matrix.col w 0\<rangle> $$ (0,0))\<rangle>"
    using assms mat_tensor_prod_2_bis state_col_ket_vec by simp
  also have "\<dots> =
|Matrix.vec 4 (\<lambda>i. if i = 0 then v $$ (0,0) * w $$ (0,0) else
                                          if i = 3 then v $$ (1,0) * w $$ (1,0) else
                                            if i = 1 then v $$ (0,0) * w $$ (1,0) else
                                              v $$ (1,0) * w $$ (0,0))\<rangle>"
    using assms mat_tensor_prod_2_bis calculation by auto
  also have "\<dots> =
|Matrix.vec 4 (\<lambda>i. if i = 0 then Matrix.col v 0 $ 0 * Matrix.col w 0 $ 0 else
                                      if i = 3 then Matrix.col v 0 $ 1 * Matrix.col w 0 $ 1 else
                                          if i = 1 then Matrix.col v 0 $ 0 * Matrix.col w 0 $ 1 else
                                            Matrix.col v 0 $ 1 * Matrix.col w 0 $ 0)\<rangle>"
    apply(rule eq_ket_vec)
    apply (rule eq_vecI)
    using col_index_of_mat_col assms state_def by auto
  finally show ?thesis
    using vec_tensor_prod_2_bis assms state.state_to_state_qbit by presburger
qed

text \<open>The property of being a state (resp. a gate) is preserved by tensor product.\<close>

lemma tensor_state2 [simp]:
  assumes "state 1 u" and "state 1 v"
  shows "state 2 (u \<Otimes> v)"
proof
  show "dim_col (u \<Otimes> v) = 1"
    using assms dim_col_tensor_mat state.is_column by presburger
  show "dim_row (u \<Otimes> v) = 2\<^sup>2"
    using assms dim_row_tensor_mat state.dim_row
    by (metis (mono_tags, lifting) power2_eq_square power_one_right)
  show "\<parallel>Matrix.col (u \<Otimes> v) 0\<parallel> = 1"
  proof -
    define l where d0:"l = [u $$ (0,0) * v $$ (0,0), u $$ (0,0) * v $$ (1,0), u $$ (1,0) * v $$ (0,0), u $$ (1,0) * v $$ (1,0)]"
    then have f4:"length l = 4" by simp
    also have "u \<Otimes> v = mat_of_cols_list 4
[[u $$ (0,0) * v $$ (0,0), u $$ (0,0) * v $$ (1,0), u $$ (1,0) * v $$ (0,0), u $$ (1,0) * v $$ (1,0)]]"
      using assms by simp
    then have "Matrix.col (u \<Otimes> v) 0 = vec_of_list [u $$ (0,0) * v $$ (0,0), u $$ (0,0) * v $$ (1,0),
u $$ (1,0) * v $$ (0,0), u $$ (1,0) * v $$ (1,0)]"
      by (metis One_nat_def Suc_eq_plus1 add_Suc col_mat_of_cols_list list.size(3) list.size(4)
nth_Cons_0 numeral_2_eq_2 numeral_Bit0 plus_1_eq_Suc vec_of_list_Cons zero_less_one_class.zero_less_one)
    then have f5:"\<parallel>Matrix.col (u \<Otimes> v) 0\<parallel> = sqrt(\<Sum>i<4. (cmod (l ! i))\<^sup>2)"
      by (metis d0 f4 One_nat_def cpx_length_of_vec_of_list d0 vec_of_list_Cons)
    also have "\<dots> = sqrt ((cmod (u $$ (0,0) * v $$ (0,0)))\<^sup>2 + (cmod(u $$ (0,0) * v $$ (1,0)))\<^sup>2 +
(cmod(u $$ (1,0) * v $$ (0,0)))\<^sup>2 + (cmod(u $$ (1,0) * v $$ (1,0)))\<^sup>2)"
    proof -
      have "(\<Sum>i<4. (cmod (l ! i))\<^sup>2) = (cmod (l ! 0))\<^sup>2 + (cmod (l ! 1))\<^sup>2 + (cmod (l ! 2))\<^sup>2 +
(cmod (l ! 3))\<^sup>2"
        using sum_insert
        by (smt One_nat_def empty_iff finite.emptyI finite.insertI insertE lessThan_0 lessThan_Suc
numeral_2_eq_2 numeral_3_eq_3 numeral_plus_one one_plus_numeral_commute plus_1_eq_Suc semiring_norm(2)
semiring_norm(8) sum.empty)
      also have "\<dots> = (cmod (u $$ (0,0) * v $$ (0,0)))\<^sup>2 + (cmod(u $$ (0,0) * v $$ (1,0)))\<^sup>2 +
(cmod(u $$ (1,0) * v $$ (0,0)))\<^sup>2 + (cmod(u $$ (1,0) * v $$ (1,0)))\<^sup>2"
        using d0 by simp
      finally show ?thesis by(simp add: f5)
    qed
    moreover have "\<dots> =
sqrt ((cmod (u $$ (0,0)))\<^sup>2 * (cmod (v $$ (0,0)))\<^sup>2 + (cmod(u $$ (0,0)))\<^sup>2 * (cmod (v $$ (1,0)))\<^sup>2 +
(cmod(u $$ (1,0)))\<^sup>2 * (cmod (v $$ (0,0)))\<^sup>2 + (cmod(u $$ (1,0)))\<^sup>2 * (cmod(v $$ (1,0)))\<^sup>2)"
      by (simp add: norm_mult power_mult_distrib)
    moreover have "\<dots> = sqrt ((((cmod(u $$ (0,0)))\<^sup>2 + (cmod(u $$ (1,0)))\<^sup>2)) *
(((cmod(v $$ (0,0)))\<^sup>2 + (cmod(v $$ (1,0)))\<^sup>2)))"
      by (simp add: distrib_left mult.commute)
    ultimately have f6:"\<parallel>Matrix.col (u \<Otimes> v) 0\<parallel>\<^sup>2 = (((cmod(u $$ (0,0)))\<^sup>2 + (cmod(u $$ (1,0)))\<^sup>2)) *
(((cmod(v $$ (0,0)))\<^sup>2 + (cmod(v $$ (1,0)))\<^sup>2))"
      by (simp add: f4)
    also have f7:"\<dots> = (\<Sum>i< 2. (cmod (u $$ (i,0)))\<^sup>2) * (\<Sum>i<2. (cmod (v $$ (i,0)))\<^sup>2)"
      by (simp add: numeral_2_eq_2)
    also have f8:"\<dots> = (\<Sum>i< 2.(cmod (Matrix.col u 0 $ i))\<^sup>2) * (\<Sum>i<2.(cmod (Matrix.col v 0 $ i))\<^sup>2)"
      using assms index_col state_def by simp
    finally show ?thesis
    proof -
      have f1:"(\<Sum>i< 2.(cmod (Matrix.col u 0 $ i))\<^sup>2) = 1"
        using assms(1) state_def cpx_vec_length_def by auto
      have f2:"(\<Sum>i< 2.(cmod (Matrix.col v 0 $ i))\<^sup>2) = 1"
        using assms(2) state_def cpx_vec_length_def by auto
      thus ?thesis
        using f1 f8 f5 f6 f7
        by (simp add: \<open>sqrt (\<Sum>i<4. (cmod (l ! i))\<^sup>2) = sqrt ((cmod (u $$ (0, 0) * v $$ (0, 0)))\<^sup>2 +
(cmod (u $$ (0, 0) * v $$ (1, 0)))\<^sup>2 + (cmod (u $$ (1, 0) * v $$ (0, 0)))\<^sup>2 + (cmod (u $$ (1, 0) * v $$ (1, 0)))\<^sup>2)\<close>)
    qed
  qed
qed

lemma sum_prod:
  fixes f::"nat \<Rightarrow> complex" and g::"nat \<Rightarrow> complex"
  shows "(\<Sum>i<a*b. f(i div b) * g(i mod b)) = (\<Sum>i<a. f(i)) * (\<Sum>j<b. g(j))"
proof (induction a)
  case 0
  then show ?case by simp
next
  case (Suc a)
  have "(\<Sum>i<(a+1)*b. f (i div b) * g (i mod b)) = (\<Sum>i<a*b. f (i div b) * g (i mod b)) +
(\<Sum>i\<in>{a*b..<(a+1)*b}. f (i div b) * g (i mod b))"
    apply (auto simp: algebra_simps)
    by (smt add.commute mult_Suc sum.lessThan_Suc sum.nat_group)
  also have "\<dots> = (\<Sum>i<a. f(i)) * (\<Sum>j<b. g(j)) + (\<Sum>i\<in>{a*b..<(a+1)*b}. f (i div b) * g (i mod b))"
    by (simp add: Suc.IH)
  also have "\<dots> = (\<Sum>i<a. f(i)) * (\<Sum>j<b. g(j)) + (\<Sum>i\<in>{a*b..<(a+1)*b}. f (a) * g(i-a*b))" by simp
  also have "\<dots> = (\<Sum>i<a. f(i)) * (\<Sum>j<b. g(j)) + f(a) * (\<Sum>i\<in>{a*b..<(a+1)*b}. g(i-a*b))"
    by(simp add: sum_distrib_left)
  also have "\<dots> = (\<Sum>i<a. f(i)) * (\<Sum>j<b. g(j)) + f(a) * (\<Sum>i\<in>{..<b}. g(i))"
    using sum_of_index_diff[of "g" "(a*b)" "b"] by (simp add: algebra_simps)
  ultimately show ?case  by (simp add: semiring_normalization_rules(1))
qed

lemma tensor_state [simp]:
  assumes "state m u" and "state n v"
  shows "state (m + n) (u \<Otimes> v)"
proof
  show c1:"dim_col (u \<Otimes> v) = 1"
    using assms dim_col_tensor_mat state.is_column by presburger
  show c2:"dim_row (u \<Otimes> v) = 2^(m + n)"
    using assms dim_row_tensor_mat state.dim_row by (metis power_add)
  have "(\<Sum>i<2^(m + n). (cmod (u $$ (i div 2 ^ n, 0) * v $$ (i mod 2 ^ n, 0)))\<^sup>2) =
(\<Sum>i<2^(m + n). (cmod (u $$ (i div 2 ^ n, 0)))\<^sup>2 * (cmod (v $$ (i mod 2 ^ n, 0)))\<^sup>2)"
    by (simp add: sqr_of_cmod_of_prod)
  also have "\<dots> = (\<Sum>i<2^m. (cmod (u $$ (i, 0)))\<^sup>2) * (\<Sum>i<2^n. (cmod (v $$ (i, 0)))\<^sup>2)"
  proof-
    have "\<dots> = (\<Sum>i<2^(m + n).complex_of_real((cmod (u $$ (i div 2^n,0)))\<^sup>2) * complex_of_real((cmod (v $$ (i mod 2^n,0)))\<^sup>2))"
      by simp
    moreover have "(\<Sum>i<2^m. (cmod (u $$ (i, 0)))\<^sup>2) = (\<Sum>i<2^m. complex_of_real ((cmod (u $$ (i,0)))\<^sup>2))" by simp
    moreover have "(\<Sum>i<2^n. (cmod (v $$ (i, 0)))\<^sup>2) = (\<Sum>i<2^n. complex_of_real ((cmod (v $$ (i, 0)))\<^sup>2))" by simp
    ultimately show ?thesis
      using sum_prod[of "\<lambda>i. (cmod (u $$ (i , 0)))\<^sup>2" "2^n" "\<lambda>i. (cmod (v $$ (i , 0)))\<^sup>2" "2^m"]
      by (smt of_real_eq_iff of_real_mult power_add)
  qed
  also have "\<dots> = 1"
  proof-
    have "(\<Sum>i<2^m. (cmod (u $$ (i, 0)))\<^sup>2) = 1"
      using assms(1) state_def cpx_vec_length_def by auto
    moreover have "(\<Sum>i<2^n. (cmod (v $$ (i, 0)))\<^sup>2) = 1"
      using assms(2) state_def cpx_vec_length_def by auto
    ultimately show ?thesis by simp
  qed
  ultimately show "\<parallel>Matrix.col (u \<Otimes> v) 0\<parallel> = 1"
    using c1 c2 assms state_def by (auto simp add: cpx_vec_length_def)
qed

lemma dim_row_of_tensor_gate:
  assumes "gate m G1" and "gate n G2"
  shows "dim_row (G1 \<Otimes> G2) = 2^(m+n)"
  using assms dim_row_tensor_mat gate.dim_row by (simp add: power_add)

lemma tensor_gate_sqr_mat:
  assumes "gate m G1" and "gate n G2"
  shows "square_mat (G1 \<Otimes> G2)"
  using assms gate.square_mat by simp

lemma dim_row_of_one_mat_less_pow:
  assumes "gate m G1" and "gate n G2" and "i < dim_row (1\<^sub>m(dim_col G1 * dim_col G2))"
  shows "i < 2^(m+n)"
  using assms gate_def by (simp add: power_add)

lemma dim_col_of_one_mat_less_pow:
  assumes "gate m G1" and "gate n G2" and "j < dim_col (1\<^sub>m(dim_col G1 * dim_col G2))"
  shows "j < 2^(m+n)"
  using assms gate_def by (simp add: power_add)

lemma index_tensor_gate_unitary1:
  assumes "gate m G1" and "gate n G2" and "i < dim_row (1\<^sub>m(dim_col G1 * dim_col G2))" and
"j < dim_col (1\<^sub>m(dim_col G1 * dim_col G2))"
  shows "((G1 \<Otimes> G2)\<^sup>\<dagger> * (G1 \<Otimes> G2)) $$ (i, j) = 1\<^sub>m(dim_col G1 * dim_col G2) $$ (i, j)"
proof-
  have "\<And>k. k<2^(m+n) \<Longrightarrow> cnj((G1 \<Otimes> G2) $$ (k,i)) =
cnj(G1 $$ (k div 2^n, i div 2^n)) * cnj(G2 $$ (k mod 2^n, i mod 2^n))"
    using assms(1-3) by (simp add: gate_def power_add)
  moreover have "\<And>k. k<2^(m+n) \<Longrightarrow> (G1 \<Otimes> G2) $$ (k,j) =
                                   G1 $$ (k div 2^n, j div 2^n) * G2 $$ (k mod 2^n, j mod 2^n)"
    using assms(1,2,4) by (simp add: gate_def power_add)
  ultimately have "\<And>k. k<2^(m+n) \<Longrightarrow> cnj((G1 \<Otimes> G2) $$ (k,i)) * ((G1 \<Otimes> G2) $$ (k,j)) =
      cnj(G1 $$ (k div 2^n, i div 2^n)) * G1 $$ (k div 2^n, j div 2^n) *
      cnj(G2 $$ (k mod 2^n, i mod 2^n)) * G2 $$ (k mod 2^n, j mod 2^n)" by simp
  then have "(\<Sum>k<2^(m+n). cnj((G1 \<Otimes> G2) $$ (k,i)) * ((G1 \<Otimes> G2) $$ (k,j))) =
      (\<Sum>k<2^(m+n). cnj(G1 $$ (k div 2^n, i div 2^n)) * G1 $$ (k div 2^n, j div 2^n) *
                    cnj(G2 $$ (k mod 2^n, i mod 2^n)) * G2 $$ (k mod 2^n, j mod 2^n))" by simp
  also have "\<dots> =
             (\<Sum>k<2^m. cnj(G1 $$ (k, i div 2^n)) * G1 $$ (k, j div 2^n)) *
             (\<Sum>k<2^n. cnj(G2 $$ (k, i mod 2^n)) * G2 $$ (k, j mod 2^n))"
    using sum_prod[of "\<lambda>x. cnj(G1 $$ (x, i div 2^n)) * G1 $$ (x, j div 2^n)" "2^n"
"\<lambda>x. cnj(G2 $$ (x, i mod 2^n)) * G2 $$ (x, j mod 2^n)" "2^m"]
    by (metis (no_types, lifting) power_add semigroup_mult_class.mult.assoc sum.cong)
  also have "((G1 \<Otimes> G2)\<^sup>\<dagger> * (G1 \<Otimes> G2)) $$ (i, j) = (\<Sum>k<2^(m+n).cnj((G1 \<Otimes> G2) $$ (k,i)) * ((G1 \<Otimes> G2) $$ (k,j)))"
    using assms index_matrix_prod[of "i" "(G1 \<Otimes> G2)\<^sup>\<dagger>" "j" "(G1 \<Otimes> G2)"] dagger_def
dim_row_of_tensor_gate tensor_gate_sqr_mat by simp
  ultimately have "((G1 \<Otimes> G2)\<^sup>\<dagger> * (G1 \<Otimes> G2)) $$ (i,j) =
              (\<Sum>k1<2^m. cnj(G1 $$ (k1, i div 2^n)) * G1 $$ (k1, j div 2^n)) *
              (\<Sum>k2<2^n. cnj(G2 $$ (k2, i mod 2^n)) * G2 $$ (k2, j mod 2^n))" by simp
  moreover have "(\<Sum>k<2^m. cnj(G1 $$ (k, i div 2^n))* G1 $$ (k, j div 2^n)) = (G1\<^sup>\<dagger> * G1) $$ (i div 2^n, j div 2^n)"
      using assms gate_def dagger_def index_matrix_prod[of "i div 2^n" "G1\<^sup>\<dagger>" "j div 2^n" "G1"]
      by (simp add: less_mult_imp_div_less power_add)
  moreover have "\<dots> = 1\<^sub>m(2^m) $$ (i div 2^n, j div 2^n)"
    using assms(1,2) gate_def unitary_def by simp
  moreover have "(\<Sum>k<2^n. cnj(G2 $$ (k, i mod 2^n))* G2 $$ (k, j mod 2^n)) = (G2\<^sup>\<dagger> * G2) $$ (i mod 2^n, j mod 2^n)"
    using assms(1,2) gate_def dagger_def index_matrix_prod[of "i mod 2^n" "G2\<^sup>\<dagger>" "j mod 2^n" "G2"] by simp
  moreover have "\<dots> = 1\<^sub>m(2^n) $$ (i mod 2^n, j mod 2^n)"
    using assms(1,2) gate_def unitary_def by simp
  ultimately have "((G1 \<Otimes> G2)\<^sup>\<dagger> * (G1 \<Otimes> G2)) $$ (i,j) = 1\<^sub>m (2^m) $$ (i div 2^n, j div 2^n) * 1\<^sub>m (2^n) $$ (i mod 2^n, j mod 2^n)"
    by simp
  thus ?thesis
    using assms assms(3,4) gate_def index_one_mat_div_mod[of "i" "m" "n" "j"] by(simp add: power_add)
qed

lemma tensor_gate_unitary1 [simp]:
  assumes "gate m G1" and "gate n G2"
  shows "(G1 \<Otimes> G2)\<^sup>\<dagger> * (G1 \<Otimes> G2) = 1\<^sub>m(dim_col G1 * dim_col G2)"
proof
  show "dim_row ((G1 \<Otimes> G2)\<^sup>\<dagger> * (G1 \<Otimes> G2)) = dim_row (1\<^sub>m(dim_col G1 * dim_col G2))" by simp
  show "dim_col ((G1 \<Otimes> G2)\<^sup>\<dagger> * (G1 \<Otimes> G2)) = dim_col (1\<^sub>m(dim_col G1 * dim_col G2))" by simp
  fix i j assume "i < dim_row (1\<^sub>m(dim_col G1 * dim_col G2))" and "j < dim_col (1\<^sub>m(dim_col G1 * dim_col G2))"
  thus "((G1 \<Otimes> G2)\<^sup>\<dagger> * (G1 \<Otimes> G2)) $$ (i, j) = 1\<^sub>m(dim_col G1 * dim_col G2) $$ (i, j)"
    using assms index_tensor_gate_unitary1 by simp
qed

lemma index_tensor_gate_unitary2 [simp]:
  assumes "gate m G1" and "gate n G2" and "i < dim_row (1\<^sub>m (dim_col G1 * dim_col G2))" and
"j < dim_col (1\<^sub>m (dim_col G1 * dim_col G2))"
  shows "((G1 \<Otimes> G2) * ((G1 \<Otimes> G2)\<^sup>\<dagger>)) $$ (i, j) = 1\<^sub>m(dim_col G1 * dim_col G2) $$ (i, j)"
proof-
  have "\<And>k. k<2^(m+n) \<Longrightarrow> (G1 \<Otimes> G2) $$ (i,k) =
G1 $$ (i div 2^n, k div 2^n) * G2 $$ (i mod 2^n, k mod 2^n)"
    using assms(1-3) by (simp add: gate_def power_add)
  moreover have "\<And>k. k<2^(m+n) \<Longrightarrow> cnj((G1 \<Otimes> G2) $$ (j,k)) =
cnj(G1 $$ (j div 2^n, k div 2^n)) * cnj(G2 $$ (j mod 2^n, k mod 2^n))"
    using assms(1,2,4) by (simp add: gate_def power_add)
  ultimately have "\<And>k. k\<in>{..<2^(m+n)} \<Longrightarrow> (G1 \<Otimes> G2) $$ (i,k) * cnj((G1 \<Otimes> G2) $$ (j,k)) =
                         G1 $$ (i div 2^n, k div 2^n) * cnj(G1 $$ (j div 2^n, k div 2^n)) *
                         G2 $$ (i mod 2^n, k mod 2^n) * cnj(G2 $$ (j mod 2^n, k mod 2^n))" by simp
  then have "(\<Sum>k<2^(m+n). (G1 \<Otimes> G2) $$ (i,k) * cnj((G1 \<Otimes> G2) $$ (j,k))) =
      (\<Sum>k<2^(m+n). G1 $$ (i div 2^n, k div 2^n) * cnj(G1 $$ (j div 2^n, k div 2^n)) *
      G2 $$ (i mod 2^n, k mod 2^n) * cnj(G2 $$ (j mod 2^n, k mod 2^n)))" by simp
  also have "\<dots> =
             (\<Sum>k<2^m. G1 $$ (i div 2^n, k) * cnj(G1 $$ (j div 2^n, k))) *
             (\<Sum>k<2^n. G2 $$ (i mod 2^n, k) * cnj(G2 $$ (j mod 2^n, k)))"
    using sum_prod[of "\<lambda>k. G1 $$ (i div 2^n, k) * cnj(G1 $$ (j div 2^n, k))" "2^n"
                        "\<lambda>k. G2 $$ (i mod 2^n, k) * cnj(G2 $$ (j mod 2^n, k))" "2^m"]
    by (metis (no_types, lifting) power_add semigroup_mult_class.mult.assoc sum.cong)
  also have "((G1 \<Otimes> G2) * ((G1 \<Otimes> G2)\<^sup>\<dagger>)) $$ (i, j) = (\<Sum>k<2^(m+n). (G1 \<Otimes> G2) $$ (i,k) * cnj((G1 \<Otimes> G2) $$ (j,k)))"
    using assms index_matrix_prod[of "i" "(G1 \<Otimes> G2)" "j" "(G1 \<Otimes> G2)\<^sup>\<dagger>"] dagger_def
dim_row_of_tensor_gate tensor_gate_sqr_mat by simp
  ultimately have "((G1 \<Otimes> G2) * ((G1 \<Otimes> G2)\<^sup>\<dagger>)) $$ (i,j) =
             (\<Sum>k<2^m. G1 $$ (i div 2^n, k) * cnj(G1 $$ (j div 2^n, k))) *
             (\<Sum>k<2^n. G2 $$ (i mod 2^n, k) * cnj(G2 $$ (j mod 2^n, k)))" by simp
  moreover have "(\<Sum>k<2^m. G1 $$ (i div 2^n, k) * cnj(G1 $$ (j div 2^n, k))) = (G1 * (G1\<^sup>\<dagger>)) $$ (i div 2^n, j div 2^n)"
    using assms gate_def dagger_def index_matrix_prod[of "i div 2^n" "G1" "j div 2^n" "G1\<^sup>\<dagger>"]
    by (simp add: less_mult_imp_div_less power_add)
  moreover have "\<dots> = 1\<^sub>m(2^m) $$ (i div 2^n, j div 2^n)"
    using assms(1,2) gate_def unitary_def by simp
  moreover have "(\<Sum>k<2^n. G2 $$ (i mod 2^n, k) * cnj(G2 $$ (j mod 2^n, k))) = (G2 * (G2\<^sup>\<dagger>)) $$ (i mod 2^n, j mod 2^n)"
    using assms(1,2) gate_def dagger_def index_matrix_prod[of "i mod 2^n" "G2" "j mod 2^n" "G2\<^sup>\<dagger>"] by simp
  moreover have "\<dots> = 1\<^sub>m(2^n) $$ (i mod 2^n, j mod 2^n)"
    using assms(1,2) gate_def unitary_def by simp
  ultimately have "((G1 \<Otimes> G2) * ((G1 \<Otimes> G2)\<^sup>\<dagger>)) $$ (i,j) = 1\<^sub>m(2^m) $$ (i div 2^n, j div 2^n) * 1\<^sub>m(2^n) $$ (i mod 2^n, j mod 2^n)"
    by simp
  thus ?thesis
    using assms gate_def index_one_mat_div_mod[of "i" "m" "n" "j"] by(simp add: power_add)
qed

lemma tensor_gate_unitary2 [simp]:
  assumes "gate m G1" and "gate n G2"
  shows "(G1 \<Otimes> G2) * ((G1 \<Otimes> G2)\<^sup>\<dagger>) = 1\<^sub>m(dim_col G1 * dim_col G2)"
proof
  show "dim_row ((G1 \<Otimes> G2) * ((G1 \<Otimes> G2)\<^sup>\<dagger>)) = dim_row(1\<^sub>m (dim_col G1 * dim_col G2))"
    using assms gate_def by simp
  show "dim_col ((G1 \<Otimes> G2) * ((G1 \<Otimes> G2)\<^sup>\<dagger>)) = dim_col (1\<^sub>m(dim_col G1 * dim_col G2))"
    using assms gate_def by simp
  fix i j assume "i < dim_row (1\<^sub>m (dim_col G1 * dim_col G2))" and "j < dim_col (1\<^sub>m (dim_col G1 * dim_col G2))"
  thus "((G1 \<Otimes> G2) * ((G1 \<Otimes> G2)\<^sup>\<dagger>)) $$ (i, j) = 1\<^sub>m(dim_col G1 * dim_col G2) $$ (i, j)"
    using assms index_tensor_gate_unitary2 by simp
qed

end


(*  Title:      HOL/Number_Theory/Totient.thy
    Author:     Jeremy Avigad
    Author:     Florian Haftmann
    Author:     Manuel Eberl
*)

section \<open>Fundamental facts about Euler's totient function\<close>

theory Totient
imports
  Complex_Main
  "HOL-Computational_Algebra.Primes"
  "~~/src/HOL/Number_Theory/Cong"
begin

definition totatives :: "nat \<Rightarrow> nat set" where
  "totatives n = {k \<in> {0<..n}. coprime k n}"

lemma in_totatives_iff: "k \<in> totatives n \<longleftrightarrow> k > 0 \<and> k \<le> n \<and> coprime k n"
  by (simp add: totatives_def)

lemma totatives_code [code]: "totatives n = Set.filter (\<lambda>k. coprime k n) {0<..n}"
  by (simp add: totatives_def Set.filter_def)

lemma finite_totatives [simp]: "finite (totatives n)"
  by (simp add: totatives_def)

lemma totatives_subset: "totatives n \<subseteq> {0<..n}"
  by (auto simp: totatives_def)

lemma zero_not_in_totatives [simp]: "0 \<notin> totatives n"
  by (auto simp: totatives_def)

lemma totatives_le: "x \<in> totatives n \<Longrightarrow> x \<le> n"
  by (auto simp: totatives_def)

lemma totatives_less:
  assumes "x \<in> totatives n" "n > 1"
  shows   "x < n"
proof -
  from assms have "x \<noteq> n" by (auto simp: totatives_def)
  with totatives_le[OF assms(1)] show ?thesis by simp
qed

lemma totatives_0 [simp]: "totatives 0 = {}"
  by (auto simp: totatives_def)

lemma totatives_1 [simp]: "totatives 1 = {Suc 0}"
  by (auto simp: totatives_def)

lemma totatives_Suc_0 [simp]: "totatives (Suc 0) = {Suc 0}"
  by (auto simp: totatives_def)

lemma one_in_totatives [simp]: "n > 0 \<Longrightarrow> Suc 0 \<in> totatives n"
  by (auto simp: totatives_def)

lemma totatives_eq_empty_iff [simp]: "totatives n = {} \<longleftrightarrow> n = 0"
  using one_in_totatives[of n] by (auto simp del: one_in_totatives)

lemma minus_one_in_totatives:
  assumes "n \<ge> 2"
  shows "n - 1 \<in> totatives n"
  using assms coprime_diff_one_left_nat [of n] by (simp add: in_totatives_iff)

lemma power_in_totatives:
  assumes "m > 1" "coprime m g"
  shows   "g ^ i mod m \<in> totatives m"
proof -
  have "\<not>m dvd g ^ i"
  proof
    assume "m dvd g ^ i"
    hence "\<not>coprime m (g ^ i)"
      using \<open>m > 1\<close> by (subst coprime_absorb_left) auto
    with \<open>coprime m g\<close> show False by simp
  qed
  with assms show ?thesis
    by (auto simp: totatives_def coprime_commute intro!: Nat.gr0I)
qed

lemma totatives_prime_power_Suc:
  assumes "prime p"
  shows   "totatives (p ^ Suc n) = {0<..p^Suc n} - (\<lambda>m. p * m) ` {0<..p^n}"
proof safe
  fix m assume m: "p * m \<in> totatives (p ^ Suc n)" and m: "m \<in> {0<..p^n}"
  thus False using assms by (auto simp: totatives_def gcd_mult_left)
next
  fix k assume k: "k \<in> {0<..p^Suc n}" "k \<notin> (\<lambda>m. p * m) ` {0<..p^n}"
  from k have "\<not>(p dvd k)" by (auto elim!: dvdE)
  hence "coprime k (p ^ Suc n)"
    using prime_imp_coprime [OF assms, of k]
    by (cases "n > 0") (auto simp add: ac_simps)
  with k show "k \<in> totatives (p ^ Suc n)" by (simp add: totatives_def)
qed (auto simp: totatives_def)

lemma totatives_prime: "prime p \<Longrightarrow> totatives p = {0<..<p}"
  using totatives_prime_power_Suc [of p 0] by auto

lemma bij_betw_totatives:
  assumes "m1 > 1" "m2 > 1" "coprime m1 m2"
  shows   "bij_betw (\<lambda>x. (x mod m1, x mod m2)) (totatives (m1 * m2))
             (totatives m1 \<times> totatives m2)"
  unfolding bij_betw_def
proof
  show "inj_on (\<lambda>x. (x mod m1, x mod m2)) (totatives (m1 * m2))"
  proof (intro inj_onI, clarify)
    fix x y assume xy: "x \<in> totatives (m1 * m2)" "y \<in> totatives (m1 * m2)"
                       "x mod m1 = y mod m1" "x mod m2 = y mod m2"
    have ex: "\<exists>!z. z < m1 * m2 \<and> [z = x] (mod m1) \<and> [z = x] (mod m2)"
      by (rule binary_chinese_remainder_unique_nat) (insert assms, simp_all)
    have "x < m1 * m2 \<and> [x = x] (mod m1) \<and> [x = x] (mod m2)"
         "y < m1 * m2 \<and> [y = x] (mod m1) \<and> [y = x] (mod m2)"
      using xy assms by (simp_all add: totatives_less one_less_mult cong_def)
    from this[THEN the1_equality[OF ex]] show "x = y" by simp
  qed
next
  show "(\<lambda>x. (x mod m1, x mod m2)) ` totatives (m1 * m2) = totatives m1 \<times> totatives m2"
  proof safe
    fix x assume "x \<in> totatives (m1 * m2)"
    with assms show "x mod m1 \<in> totatives m1" "x mod m2 \<in> totatives m2"
      using coprime_common_divisor [of x m1 m1] coprime_common_divisor [of x m2 m2]
      by (auto simp add: in_totatives_iff mod_greater_zero_iff_not_dvd)
  next
    fix a b assume ab: "a \<in> totatives m1" "b \<in> totatives m2"
    with assms have ab': "a < m1" "b < m2" by (auto simp: totatives_less)
    with binary_chinese_remainder_unique_nat[OF assms(3), of a b] obtain x
      where x: "x < m1 * m2" "x mod m1 = a" "x mod m2 = b" by (auto simp: cong_def)
    from x ab assms(3) have "x \<in> totatives (m1 * m2)"
      by (auto intro: ccontr simp add: in_totatives_iff)
    with x show "(a, b) \<in> (\<lambda>x. (x mod m1, x mod m2)) ` totatives (m1*m2)" by blast
  qed
qed

lemma bij_betw_totatives_gcd_eq:
  fixes n d :: nat
  assumes "d dvd n" "n > 0"
  shows   "bij_betw (\<lambda>k. k * d) (totatives (n div d)) {k\<in>{0<..n}. gcd k n = d}"
  unfolding bij_betw_def
proof
  show "inj_on (\<lambda>k. k * d) (totatives (n div d))"
    by (auto simp: inj_on_def)
next
  show "(\<lambda>k. k * d) ` totatives (n div d) = {k\<in>{0<..n}. gcd k n = d}"
  proof (intro equalityI subsetI, goal_cases)
    case (1 k)
    then show ?case using assms
      by (auto elim: dvdE simp add: in_totatives_iff ac_simps gcd_mult_right)
  next
    case (2 k)
    hence "d dvd k" by auto
    then obtain l where k: "k = l * d" by (elim dvdE) auto
    from 2 assms show ?case
      using gcd_mult_right [of _ d l]
      by (auto intro: gcd_eq_1_imp_coprime elim!: dvdE simp add: k image_iff in_totatives_iff ac_simps)
  qed
qed

definition totient :: "nat \<Rightarrow> nat" where
  "totient n = card (totatives n)"

primrec totient_naive :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat" where
  "totient_naive 0 acc n = acc"
| "totient_naive (Suc k) acc n =
     (if coprime (Suc k) n then totient_naive k (acc + 1) n else totient_naive k acc n)"

lemma totient_naive:
  "totient_naive k acc n = card {x \<in> {0<..k}. coprime x n} + acc"
proof (induction k arbitrary: acc)
  case (Suc k acc)
  have "totient_naive (Suc k) acc n =
          (if coprime (Suc k) n then 1 else 0) + card {x \<in> {0<..k}. coprime x n} + acc"
    using Suc by simp
  also have "(if coprime (Suc k) n then 1 else 0) =
               card (if coprime (Suc k) n then {Suc k} else {})" by auto
  also have "\<dots> + card {x \<in> {0<..k}. coprime x n} =
               card ((if coprime (Suc k) n then {Suc k} else {}) \<union> {x \<in> {0<..k}. coprime x n})"
    by (intro card_Un_disjoint [symmetric]) auto
  also have "((if coprime (Suc k) n then {Suc k} else {}) \<union> {x \<in> {0<..k}. coprime x n}) =
               {x \<in> {0<..Suc k}. coprime x n}" by (auto elim: le_SucE)
  finally show ?case .
qed simp_all

lemma totient_code_naive [code]: "totient n = totient_naive n 0 n"
  by (subst totient_naive) (simp add: totient_def totatives_def)

lemma totient_le: "totient n \<le> n"
proof -
  have "card (totatives n) \<le> card {0<..n}"
    by (intro card_mono) (auto simp: totatives_def)
  thus ?thesis by (simp add: totient_def)
qed

lemma totient_less:
  assumes "n > 1"
  shows "totient n < n"
proof -
  from assms have "card (totatives n) \<le> card {0<..<n}"
    using totatives_less[of _ n] totatives_subset[of n] by (intro card_mono) auto
  with assms show ?thesis by (simp add: totient_def)
qed

lemma totient_0 [simp]: "totient 0 = 0"
  by (simp add: totient_def)

lemma totient_Suc_0 [simp]: "totient (Suc 0) = Suc 0"
  by (simp add: totient_def)

lemma totient_1 [simp]: "totient 1 = Suc 0"
  by simp

lemma totient_0_iff [simp]: "totient n = 0 \<longleftrightarrow> n = 0"
  by (auto simp: totient_def)

lemma totient_gt_0_iff [simp]: "totient n > 0 \<longleftrightarrow> n > 0"
  by (auto intro: Nat.gr0I)

lemma totient_gt_1:
  assumes "n > 2"
  shows   "totient n > 1"
proof -
  have "{1, n - 1} \<subseteq> totatives n"
    using assms coprime_diff_one_left_nat[of n] by (auto simp: totatives_def)
  hence "card {1, n - 1} \<le> card (totatives n)"
    by (intro card_mono) auto
  thus ?thesis using assms
    by (simp add: totient_def)
qed

lemma card_gcd_eq_totient:
  "n > 0 \<Longrightarrow> d dvd n \<Longrightarrow> card {k\<in>{0<..n}. gcd k n = d} = totient (n div d)"
  unfolding totient_def by (rule sym, rule bij_betw_same_card[OF bij_betw_totatives_gcd_eq])

lemma totient_divisor_sum: "(\<Sum>d | d dvd n. totient d) = n"
proof (cases "n = 0")
  case False
  hence "n > 0" by simp
  define A where "A = (\<lambda>d. {k\<in>{0<..n}. gcd k n = d})"
  have *: "card (A d) = totient (n div d)" if d: "d dvd n" for d
    using \<open>n > 0\<close> and d unfolding A_def by (rule card_gcd_eq_totient)
  have "n = card {1..n}" by simp
  also have "{1..n} = (\<Union>d\<in>{d. d dvd n}. A d)" by safe (auto simp: A_def)
  also have "card \<dots> = (\<Sum>d | d dvd n. card (A d))"
    using \<open>n > 0\<close> by (intro card_UN_disjoint) (auto simp: A_def)
  also have "\<dots> = (\<Sum>d | d dvd n. totient (n div d))" by (intro sum.cong refl *) auto
  also have "\<dots> = (\<Sum>d | d dvd n. totient d)" using \<open>n > 0\<close>
    by (intro sum.reindex_bij_witness[of _ "(div) n" "(div) n"]) (auto elim: dvdE)
  finally show ?thesis ..
qed auto

lemma totient_mult_coprime:
  assumes "coprime m n"
  shows   "totient (m * n) = totient m * totient n"
proof (cases "m > 1 \<and> n > 1")
  case True
  hence mn: "m > 1" "n > 1" by simp_all
  have "totient (m * n) = card (totatives (m * n))" by (simp add: totient_def)
  also have "\<dots> = card (totatives m \<times> totatives n)"
    using bij_betw_totatives [OF mn \<open>coprime m n\<close>] by (rule bij_betw_same_card)
  also have "\<dots> = totient m * totient n" by (simp add: totient_def)
  finally show ?thesis .
next
  case False
  with assms show ?thesis by (cases m; cases n) auto
qed

lemma totient_prime_power_Suc:
  assumes "prime p"
  shows   "totient (p ^ Suc n) = p ^ n * (p - 1)"
proof -
  from assms have "totient (p ^ Suc n) = card ({0<..p ^ Suc n} - (*) p ` {0<..p ^ n})"
    unfolding totient_def by (subst totatives_prime_power_Suc) simp_all
  also from assms have "\<dots> = p ^ Suc n - card ((*) p ` {0<..p^n})"
    by (subst card_Diff_subset) (auto intro: prime_gt_0_nat)
  also from assms have "card ((*) p ` {0<..p^n}) = p ^ n"
    by (subst card_image) (auto simp: inj_on_def)
  also have "p ^ Suc n - p ^ n = p ^ n * (p - 1)" by (simp add: algebra_simps)
  finally show ?thesis .
qed

lemma totient_prime_power:
  assumes "prime p" "n > 0"
  shows   "totient (p ^ n) = p ^ (n - 1) * (p - 1)"
  using totient_prime_power_Suc[of p "n - 1"] assms by simp

lemma totient_imp_prime:
  assumes "totient p = p - 1" "p > 0"
  shows   "prime p"
proof (cases "p = 1")
  case True
  with assms show ?thesis by auto
next
  case False
  with assms have p: "p > 1" by simp
  have "x \<in> {0<..<p}" if "x \<in> totatives p" for x
    using that and p by (cases "x = p") (auto simp: totatives_def)
  with assms have *: "totatives p = {0<..<p}"
    by (intro card_subset_eq) (auto simp: totient_def)
  have **: False if "x \<noteq> 1" "x \<noteq> p" "x dvd p" for x
  proof -
    from that have nz: "x \<noteq> 0" by (auto intro!: Nat.gr0I)
    from that and p have le: "x \<le> p" by (intro dvd_imp_le) auto
    from that and nz have "\<not>coprime x p"
      by (auto elim: dvdE)
    hence "x \<notin> totatives p" by (simp add: totatives_def)
    also note *
    finally show False using that and le by auto
  qed
  hence "(\<forall>m. m dvd p \<longrightarrow> m = 1 \<or> m = p)" by blast
  with p show ?thesis by (subst prime_nat_iff) (auto dest: **)
qed

lemma totient_prime:
  assumes "prime p"
  shows   "totient p = p - 1"
  using totient_prime_power_Suc[of p 0] assms by simp

lemma totient_2 [simp]: "totient 2 = 1"
  and totient_3 [simp]: "totient 3 = 2"
  and totient_5 [simp]: "totient 5 = 4"
  and totient_7 [simp]: "totient 7 = 6"
  by (subst totient_prime; simp)+

lemma totient_4 [simp]: "totient 4 = 2"
  and totient_8 [simp]: "totient 8 = 4"
  and totient_9 [simp]: "totient 9 = 6"
  using totient_prime_power[of 2 2] totient_prime_power[of 2 3] totient_prime_power[of 3 2]
  by simp_all

lemma totient_6 [simp]: "totient 6 = 2"
  using totient_mult_coprime [of 2 3] coprime_add_one_right [of 2]
  by simp

lemma totient_even:
  assumes "n > 2"
  shows   "even (totient n)"
proof (cases "\<exists>p. prime p \<and> p \<noteq> 2 \<and> p dvd n")
  case True
  then obtain p where p: "prime p" "p \<noteq> 2" "p dvd n" by auto
  from \<open>p \<noteq> 2\<close> have "p = 0 \<or> p = 1 \<or> p > 2" by auto
  with p(1) have "odd p" using prime_odd_nat[of p] by auto
  define k where "k = multiplicity p n"
  from p assms have k_pos: "k > 0" unfolding k_def by (subst multiplicity_gt_zero_iff) auto
  have "p ^ k dvd n" unfolding k_def by (simp add: multiplicity_dvd)
  then obtain m where m: "n = p ^ k * m" by (elim dvdE)
  with assms have m_pos: "m > 0" by (auto intro!: Nat.gr0I)
  from k_def m_pos p have "\<not> p dvd m"
    by (subst (asm) m) (auto intro!: Nat.gr0I simp: prime_elem_multiplicity_mult_distrib
                          prime_elem_multiplicity_eq_zero_iff)
  with \<open>prime p\<close> have "coprime p m"
    by (rule prime_imp_coprime)
  with \<open>k > 0\<close> have "coprime (p ^ k) m"
    by simp
  then show ?thesis using p k_pos \<open>odd p\<close>
    by (auto simp add: m totient_mult_coprime totient_prime_power)
next
  case False
  from assms have "n = (\<Prod>p\<in>prime_factors n. p ^ multiplicity p n)"
    by (intro Primes.prime_factorization_nat) auto
  also from False have "\<dots> = (\<Prod>p\<in>prime_factors n. if p = 2 then 2 ^ multiplicity 2 n else 1)"
    by (intro prod.cong refl) auto
  also have "\<dots> = 2 ^ multiplicity 2 n"
    by (subst prod.delta[OF finite_set_mset]) (auto simp: prime_factors_multiplicity)
  finally have n: "n = 2 ^ multiplicity 2 n" .
  have "multiplicity 2 n = 0 \<or> multiplicity 2 n = 1 \<or> multiplicity 2 n > 1" by force
  with n assms have "multiplicity 2 n > 1" by auto
  thus ?thesis by (subst n) (simp add: totient_prime_power)
qed

lemma totient_prod_coprime:
  assumes "pairwise coprime (f ` A)" "inj_on f A"
  shows   "totient (prod f A) = (\<Prod>a\<in>A. totient (f a))"
  using assms
proof (induction A rule: infinite_finite_induct)
  case (insert x A)
  have *: "coprime (prod f A) (f x)"
  proof (rule prod_coprime_left)
    fix y
    assume "y \<in> A"
    with \<open>x \<notin> A\<close> have "y \<noteq> x"
      by auto
    with \<open>x \<notin> A\<close> \<open>y \<in> A\<close> \<open>inj_on f (insert x A)\<close> have "f y \<noteq> f x"
      using inj_onD [of f "insert x A" y x]
      by auto
    with \<open>y \<in> A\<close> show "coprime (f y) (f x)"
      using pairwiseD [OF \<open>pairwise coprime (f ` insert x A)\<close>]
      by auto
  qed
  from insert.hyps have "prod f (insert x A) = prod f A * f x" by simp
  also have "totient \<dots> = totient (prod f A) * totient (f x)"
    using insert.hyps insert.prems by (intro totient_mult_coprime *)
  also have "totient (prod f A) = (\<Prod>a\<in>A. totient (f a))"
    using insert.prems by (intro insert.IH) (auto dest: pairwise_subset)
  also from insert.hyps have "\<dots> * totient (f x) = (\<Prod>a\<in>insert x A. totient (f a))" by simp
  finally show ?case .
qed simp_all

(* TODO Move *)
lemma prime_power_eq_imp_eq:
  fixes p q :: "'a :: factorial_semiring"
  assumes "prime p" "prime q" "m > 0"
  assumes "p ^ m = q ^ n"
  shows   "p = q"
proof (rule ccontr)
  assume pq: "p \<noteq> q"
  from assms have "m = multiplicity p (p ^ m)"
    by (subst multiplicity_prime_power) auto
  also note \<open>p ^ m = q ^ n\<close>
  also from assms pq have "multiplicity p (q ^ n) = 0"
    by (subst multiplicity_distinct_prime_power) auto
  finally show False using \<open>m > 0\<close> by simp
qed

lemma totient_formula1:
  assumes "n > 0"
  shows   "totient n = (\<Prod>p\<in>prime_factors n. p ^ (multiplicity p n - 1) * (p - 1))"
proof -
  from assms have "n = (\<Prod>p\<in>prime_factors n. p ^ multiplicity p n)"
    by (rule prime_factorization_nat)
  also have "totient \<dots> = (\<Prod>x\<in>prime_factors n. totient (x ^ multiplicity x n))"
  proof (rule totient_prod_coprime)
    show "pairwise coprime ((\<lambda>p. p ^ multiplicity p n) ` prime_factors n)"
    proof (rule pairwiseI, clarify)
      fix p q assume *: "p \<in># prime_factorization n" "q \<in># prime_factorization n"
                     "p ^ multiplicity p n \<noteq> q ^ multiplicity q n"
      then have "multiplicity p n > 0" "multiplicity q n > 0"
        by (simp_all add: prime_factors_multiplicity)
      with * primes_coprime [of p q] show "coprime (p ^ multiplicity p n) (q ^ multiplicity q n)"
        by auto
    qed
  next
    show "inj_on (\<lambda>p. p ^ multiplicity p n) (prime_factors n)"
    proof
      fix p q assume pq: "p \<in># prime_factorization n" "q \<in># prime_factorization n"
                         "p ^ multiplicity p n = q ^ multiplicity q n"
      from assms and pq have "prime p" "prime q" "multiplicity p n > 0"
        by (simp_all add: prime_factors_multiplicity)
      from prime_power_eq_imp_eq[OF this pq(3)] show "p = q" .
    qed
  qed
  also have "\<dots> = (\<Prod>p\<in>prime_factors n. p ^ (multiplicity p n - 1) * (p - 1))"
    by (intro prod.cong refl totient_prime_power) (auto simp: prime_factors_multiplicity)
  finally show ?thesis .
qed

lemma totient_dvd:
  assumes "m dvd n"
  shows   "totient m dvd totient n"
proof (cases "m = 0 \<or> n = 0")
  case False
  let ?M = "\<lambda>p m :: nat. multiplicity p m - 1"
  have "(\<Prod>p\<in>prime_factors m. p ^ ?M p m * (p - 1)) dvd
          (\<Prod>p\<in>prime_factors n. p ^ ?M p n * (p - 1))" using assms False
    by (intro prod_dvd_prod_subset2 mult_dvd_mono dvd_refl le_imp_power_dvd diff_le_mono
              dvd_prime_factors dvd_imp_multiplicity_le) auto
  with False show ?thesis by (simp add: totient_formula1)
qed (insert assms, auto)

lemma totient_dvd_mono:
  assumes "m dvd n" "n > 0"
  shows   "totient m \<le> totient n"
  by (cases "m = 0") (insert assms, auto intro: dvd_imp_le totient_dvd)

(* TODO Move *)
lemma prime_factors_power: "n > 0 \<Longrightarrow> prime_factors (x ^ n) = prime_factors x"
  by (cases "x = 0"; cases "n = 0")
     (auto simp: prime_factors_multiplicity prime_elem_multiplicity_power_distrib zero_power)

lemma totient_formula2:
  "real (totient n) = real n * (\<Prod>p\<in>prime_factors n. 1 - 1 / real p)"
proof (cases "n = 0")
  case False
  have "real (totient n) = (\<Prod>p\<in>prime_factors n. real
          (p ^ (multiplicity p n - 1) * (p - 1)))"
    using False by (subst totient_formula1) simp_all
  also have "\<dots> = (\<Prod>p\<in>prime_factors n. real (p ^ multiplicity p n) * (1 - 1 / real p))"
    by (intro prod.cong refl) (auto simp add: field_simps prime_factors_multiplicity
          prime_ge_Suc_0_nat of_nat_diff power_Suc [symmetric] simp del: power_Suc)
  also have "\<dots> = real (\<Prod>p\<in>prime_factors n. p ^ multiplicity p n) *
                    (\<Prod>p\<in>prime_factors n. 1 - 1 / real p)" by (subst prod.distrib) auto
  also have "(\<Prod>p\<in>prime_factors n. p ^ multiplicity p n) = n"
    using False by (intro Primes.prime_factorization_nat [symmetric]) auto
  finally show ?thesis .
qed auto

lemma totient_gcd: "totient (a * b) * totient (gcd a b) = totient a * totient b * gcd a b"
proof (cases "a = 0 \<or> b = 0")
  case False
  let ?P = "prime_factors :: nat \<Rightarrow> nat set"
  have "real (totient a * totient b * gcd a b) = real (a * b * gcd a b) *
          ((\<Prod>p\<in>?P a. 1 - 1 / real p) * (\<Prod>p\<in>?P b. 1 - 1 / real p))"
    by (simp add: totient_formula2)
  also have "?P a = (?P a - ?P b) \<union> (?P a \<inter> ?P b)" by auto
  also have "(\<Prod>p\<in>\<dots>. 1 - 1 / real p) =
                 (\<Prod>p\<in>?P a - ?P b. 1 - 1 / real p) * (\<Prod>p\<in>?P a \<inter> ?P b. 1 - 1 / real p)"
    by (rule prod.union_disjoint) blast+
  also have "\<dots> * (\<Prod>p\<in>?P b. 1 - 1 / real p) = (\<Prod>p\<in>?P a - ?P b. 1 - 1 / real p) *
               (\<Prod>p\<in>?P b. 1 - 1 / real p) * (\<Prod>p\<in>?P a \<inter> ?P b. 1 - 1 / real p)" (is "_ = ?A * _")
    by (simp only: mult_ac)
  also have "?A = (\<Prod>p\<in>?P a - ?P b \<union> ?P b. 1 - 1 / real p)"
    by (rule prod.union_disjoint [symmetric]) blast+
  also have "?P a - ?P b \<union> ?P b = ?P a \<union> ?P b" by blast
  also have "real (a * b * gcd a b) * ((\<Prod>p\<in>\<dots>. 1 - 1 / real p) *
                 (\<Prod>p\<in>?P a \<inter> ?P b. 1 - 1 / real p)) = real (totient (a * b) * totient (gcd a b))"
    using False by (simp add: totient_formula2 prime_factors_product prime_factorization_gcd)
  finally show ?thesis by (simp only: of_nat_eq_iff)
qed auto

lemma totient_mult: "totient (a * b) = totient a * totient b * gcd a b div totient (gcd a b)"
  by (subst totient_gcd [symmetric]) simp

lemma of_nat_eq_1_iff: "of_nat x = (1 :: 'a :: {semiring_1, semiring_char_0}) \<longleftrightarrow> x = 1"
  by (fact of_nat_eq_1_iff)

(* TODO Move *)
lemma odd_imp_coprime_nat:
  assumes "odd (n::nat)"
  shows   "coprime n 2"
proof -
  from assms obtain k where n: "n = Suc (2 * k)" by (auto elim!: oddE)
  have "coprime (Suc (2 * k)) (2 * k)"
    by (fact coprime_Suc_left_nat)
  then show ?thesis using n
    by simp
qed

lemma totient_double: "totient (2 * n) = (if even n then 2 * totient n else totient n)"
  by (simp add: totient_mult ac_simps odd_imp_coprime_nat)

lemma totient_power_Suc: "totient (n ^ Suc m) = n ^ m * totient n"
proof (induction m arbitrary: n)
  case (Suc m n)
  have "totient (n ^ Suc (Suc m)) = totient (n * n ^ Suc m)" by simp
  also have "\<dots> = n ^ Suc m * totient n"
    using Suc.IH by (subst totient_mult) simp
  finally show ?case .
qed simp_all

lemma totient_power: "m > 0 \<Longrightarrow> totient (n ^ m) = n ^ (m - 1) * totient n"
  using totient_power_Suc[of n "m - 1"] by (cases m) simp_all

lemma totient_gcd_lcm: "totient (gcd a b) * totient (lcm a b) = totient a * totient b"
proof (cases "a = 0 \<or> b = 0")
  case False
  let ?P = "prime_factors :: nat \<Rightarrow> nat set" and ?f = "\<lambda>p::nat. 1 - 1 / real p"
  have "real (totient (gcd a b) * totient (lcm a b)) = real (gcd a b * lcm a b) *
          (prod ?f (?P a \<inter> ?P b) * prod ?f (?P a \<union> ?P b))"
    using False unfolding of_nat_mult
    by (simp add: totient_formula2 prime_factorization_gcd prime_factorization_lcm)
  also have "gcd a b * lcm a b = a * b" by simp
  also have "?P a \<union> ?P b = (?P a - ?P a \<inter> ?P b) \<union> ?P b" by blast
  also have "prod ?f \<dots> = prod ?f (?P a - ?P a \<inter> ?P b) * prod ?f (?P b)"
    by (rule prod.union_disjoint) blast+
  also have "prod ?f (?P a \<inter> ?P b) * \<dots> =
               prod ?f (?P a \<inter> ?P b \<union> (?P a - ?P a \<inter> ?P b)) * prod ?f (?P b)"
    by (subst prod.union_disjoint) auto
  also have "?P a \<inter> ?P b \<union> (?P a - ?P a \<inter> ?P b) = ?P a" by blast
  also have "real (a * b) * (prod ?f (?P a) * prod ?f (?P b)) = real (totient a * totient b)"
    using False by (simp add: totient_formula2)
  finally show ?thesis by (simp only: of_nat_eq_iff)
qed auto

end


(*
   File:      Analysis/Simplex_Content.thy
   Author:    Manuel Eberl <manuel@pruvisto.org>

   The content of an n-dimensional simplex, including the formula for the content of a
   triangle and Heron's formula.
*)
section \<open>Volume of a Simplex\<close>

theory Simplex_Content
imports Change_Of_Vars
begin

lemma fact_neq_top_ennreal [simp]: "fact n \<noteq> (top :: ennreal)"
  by (induction n) (auto simp: ennreal_mult_eq_top_iff)

lemma ennreal_fact: "ennreal (fact n) = fact n"
  by (induction n) (auto simp: ennreal_mult algebra_simps ennreal_of_nat_eq_real_of_nat)

context
  fixes S :: "'a set \<Rightarrow> real \<Rightarrow> ('a \<Rightarrow> real) set"
  defines "S \<equiv> (\<lambda>A t. {x. (\<forall>i\<in>A. 0 \<le> x i) \<and> sum x A \<le> t})"
begin

lemma emeasure_std_simplex_aux_step:
  assumes "b \<notin> A" "finite A"
  shows   "x(b := y) \<in> S (insert b A) t \<longleftrightarrow> y \<in> {0..t} \<and> x \<in> S A (t - y)"
  using assms sum_nonneg[of A x] unfolding S_def
  by (force simp: sum_delta_notmem algebra_simps)

lemma emeasure_std_simplex_aux:
  fixes t :: real
  assumes "finite (A :: 'a set)" "t \<ge> 0"
  shows   "emeasure (Pi\<^sub>M A (\<lambda>_. lborel))
             (S A t \<inter> space (Pi\<^sub>M A (\<lambda>_. lborel))) = t ^ card A / fact (card A)"
  using assms(1,2)
proof (induction arbitrary: t rule: finite_induct)
  case (empty t)
  thus ?case by (simp add: PiM_empty S_def)
next
  case (insert b A t)
  define n where "n = Suc (card A)"
  have n_pos: "n > 0" by (simp add: n_def)
  let ?M = "\<lambda>A. (Pi\<^sub>M A (\<lambda>_. lborel))"
  {
    fix A :: "'a set" and t :: real assume "finite A"
    have "S A t \<inter> space (Pi\<^sub>M A (\<lambda>_. lborel)) =
            Pi\<^sub>E A (\<lambda>_. {0..}) \<inter> (\<lambda>x. sum x A) -` {..t} \<inter> space (Pi\<^sub>M A (\<lambda>_. lborel))"
      by (auto simp: S_def space_PiM)
    also have "\<dots> \<in> sets (Pi\<^sub>M A (\<lambda>_. lborel))"
      using \<open>finite A\<close> by measurable
    finally have "S A t \<inter> space (Pi\<^sub>M A (\<lambda>_. lborel)) \<in> sets (Pi\<^sub>M A (\<lambda>_. lborel))" .
  } note meas [measurable] = this

  interpret product_sigma_finite "\<lambda>_. lborel"
    by standard
  have "emeasure (?M (insert b A)) (S (insert b A) t \<inter> space (?M (insert b A))) =
        nn_integral (?M (insert b A))
          (\<lambda>x. indicator (S (insert b A) t \<inter> space (?M (insert b A))) x)"
    using insert.hyps by (subst nn_integral_indicator) auto
  also have "\<dots> = (\<integral>\<^sup>+ y. \<integral>\<^sup>+ x. indicator (S (insert b A) t \<inter> space (?M (insert b A)))
                    (x(b := y)) \<partial>?M A \<partial>lborel)"
    using insert.prems insert.hyps by (intro product_nn_integral_insert_rev) auto
  also have "\<dots> = (\<integral>\<^sup>+ y. \<integral>\<^sup>+ x. indicator {0..t} y * indicator (S A (t - y) \<inter> space (?M A)) x
                    \<partial>?M A \<partial>lborel)"
    using insert.hyps insert.prems emeasure_std_simplex_aux_step[of b A]
    by (intro nn_integral_cong)
       (auto simp: fun_eq_iff indicator_def space_PiM PiE_def extensional_def)
  also have "\<dots> = (\<integral>\<^sup>+ y. indicator {0..t} y * (\<integral>\<^sup>+ x. indicator (S A (t - y) \<inter> space (?M A)) x
                    \<partial>?M A) \<partial>lborel)" using \<open>finite A\<close>
    by (subst nn_integral_cmult) auto
  also have "\<dots> = (\<integral>\<^sup>+ y. indicator {0..t} y * emeasure (?M A) (S A (t - y) \<inter> space (?M A)) \<partial>lborel)"
    using \<open>finite A\<close> by (subst nn_integral_indicator) auto
  also have "\<dots> = (\<integral>\<^sup>+ y. indicator {0..t} y * (t - y) ^ card A / ennreal (fact (card A)) \<partial>lborel)"
    using insert.IH by (intro nn_integral_cong) (auto simp: indicator_def divide_ennreal)
  also have "\<dots> = (\<integral>\<^sup>+ y. indicator {0..t} y * (t - y) ^ card A \<partial>lborel) / ennreal (fact (card A))"
    using \<open>finite A\<close> by (subst nn_integral_divide) auto
  also have "(\<integral>\<^sup>+ y. indicator {0..t} y * (t - y) ^ card A \<partial>lborel) =
               (\<integral>\<^sup>+y\<in>{0..t}. ennreal ((t - y) ^ (n - 1)) \<partial>lborel)"
    by (intro nn_integral_cong) (auto simp: indicator_def n_def)
  also have "((\<lambda>x. - ((t - x) ^ n / n)) has_real_derivative (t - x) ^ (n - 1)) (at x)"
    if "x \<in> {0..t}" for x by (rule derivative_eq_intros refl | simp add: n_pos)+
  hence "(\<integral>\<^sup>+y\<in>{0..t}. ennreal ((t - y) ^ (n - 1)) \<partial>lborel) =
           ennreal (-((t - t) ^ n / n) - (-((t - 0) ^ n / n)))"
    using insert.prems insert.hyps by (intro nn_integral_FTC_Icc) auto
  also have "\<dots> = ennreal (t ^ n / n)" using n_pos by (simp add: zero_power)
  also have "\<dots> / ennreal (fact (card A)) = ennreal (t ^ n / n / fact (card A))"
    using n_pos \<open>t \<ge> 0\<close> by (subst divide_ennreal) auto
  also have "t ^ n / n / fact (card A) = t ^ n / fact n"
    by (simp add: n_def)
  also have "n = card (insert b A)"
    using insert.hyps by (subst card.insert_remove) (auto simp: n_def)
  finally show ?case .
qed

end

lemma emeasure_std_simplex:
  "emeasure lborel (convex hull (insert 0 Basis :: 'a :: euclidean_space set)) =
     ennreal (1 / fact DIM('a))"
proof -
  have "emeasure lborel {x::'a. (\<forall>i\<in>Basis. 0 \<le> x \<bullet> i) \<and> sum ((\<bullet>) x) Basis \<le> 1} =
               emeasure (distr (Pi\<^sub>M Basis (\<lambda>b. lborel)) borel (\<lambda>f. \<Sum>b\<in>Basis. f b *\<^sub>R b))
                 {x::'a. (\<forall>i\<in>Basis. 0 \<le> x \<bullet> i) \<and> sum ((\<bullet>) x) Basis \<le> 1}"
    by (subst lborel_eq) simp
  also have "\<dots> = emeasure (Pi\<^sub>M Basis (\<lambda>b. lborel))
                    ({y::'a \<Rightarrow> real. (\<forall>i\<in>Basis. 0 \<le> y i) \<and> sum y Basis \<le> 1} \<inter>
                      space (Pi\<^sub>M Basis (\<lambda>b. lborel)))"
    by (subst emeasure_distr) auto
  also have "\<dots> = ennreal (1 / fact DIM('a))"
    by (subst emeasure_std_simplex_aux) auto
  finally show ?thesis by (simp only: std_simplex)
qed

theorem content_std_simplex:
  "measure lborel (convex hull (insert 0 Basis :: 'a :: euclidean_space set)) =
     1 / fact DIM('a)"
  by (simp add: measure_def emeasure_std_simplex)

(* TODO: move to Change_of_Vars *)
proposition measure_lebesgue_linear_transformation:
  fixes A :: "(real ^ 'n :: {finite, wellorder}) set"
  fixes f :: "_ \<Rightarrow> real ^ 'n :: {finite, wellorder}"
  assumes "bounded A" "A \<in> sets lebesgue" "linear f"
  shows   "measure lebesgue (f ` A) = \<bar>det (matrix f)\<bar> * measure lebesgue A"
proof -
  from assms have [intro]: "A \<in> lmeasurable"
    by (intro bounded_set_imp_lmeasurable) auto
  hence [intro]: "f ` A \<in> lmeasurable"
    by (intro lmeasure_integral measurable_linear_image assms)
  have "measure lebesgue (f ` A) = integral (f ` A) (\<lambda>_. 1)"
    by (intro lmeasure_integral measurable_linear_image assms) auto
  also have "\<dots> = integral (f ` A) (\<lambda>_. 1 :: real ^ 1) $ 0"
    by (subst integral_component_eq_cart [symmetric]) (auto intro: integrable_on_const)
  also have "\<dots> = \<bar>det (matrix f)\<bar> * integral A (\<lambda>x. 1 :: real ^ 1) $ 0"
    using assms
    by (subst integral_change_of_variables_linear)
       (auto simp: o_def absolutely_integrable_on_def intro: integrable_on_const)
  also have "integral A (\<lambda>x. 1 :: real ^ 1) $ 0 = integral A (\<lambda>x. 1)"
    by (subst integral_component_eq_cart [symmetric]) (auto intro: integrable_on_const)
  also have "\<dots> = measure lebesgue A"
    by (intro lmeasure_integral [symmetric]) auto
  finally show ?thesis .
qed

theorem content_simplex:
  fixes X :: "(real ^ 'n :: {finite, wellorder}) set" and f :: "'n :: _ \<Rightarrow> real ^ ('n :: _)"
  assumes "finite X" "card X = Suc CARD('n)" and x0: "x0 \<in> X" and bij: "bij_betw f UNIV (X - {x0})"
  defines "M \<equiv> (\<chi> i. \<chi> j. f j $ i - x0 $ i)"
  shows "content (convex hull X) = \<bar>det M\<bar> / fact (CARD('n))"
proof -
  define g where "g = (\<lambda>x. M *v x)"
  have [simp]: "M *v axis i 1 = f i - x0" for i :: 'n
    by (simp add: M_def matrix_vector_mult_basis column_def vec_eq_iff)
  define std where "std = (convex hull insert 0 Basis :: (real ^ 'n :: _) set)"
  have compact: "compact std" unfolding std_def
    by (intro finite_imp_compact_convex_hull) auto

  have "measure lebesgue (convex hull X) = measure lebesgue (((+) (-x0)) ` (convex hull X))"
    by (rule measure_translation [symmetric])
  also have "((+) (-x0)) ` (convex hull X) = convex hull (((+) (-x0)) ` X)"
    by (rule convex_hull_translation [symmetric])
  also have "((+) (-x0)) ` X = insert 0 ((\<lambda>x. x - x0) ` (X - {x0}))"
    using x0 by (auto simp: image_iff)
  finally have eq: "measure lebesgue (convex hull X) = measure lebesgue (convex hull \<dots>)" .

  from compact have "measure lebesgue (g ` std) = \<bar>det M\<bar> * measure lebesgue std"
    by (subst measure_lebesgue_linear_transformation)
       (auto intro: finite_imp_bounded_convex_hull dest: compact_imp_closed simp: g_def std_def)
  also have "measure lebesgue std = content std" using compact
    by (intro measure_completion) (auto dest: compact_imp_closed)
  also have "content std = 1 / fact CARD('n)" unfolding std_def
    by (simp add: content_std_simplex)
  also have "g ` std = convex hull (g ` insert 0 Basis)" unfolding std_def
    by (rule convex_hull_linear_image) (auto simp: g_def)
  also have "g ` insert 0 Basis = insert 0 (g ` Basis)"
    by (auto simp: g_def)
  also have "g ` Basis = (\<lambda>x. x - x0) ` range f"
    by (auto simp: g_def Basis_vec_def image_iff)
  also have "range f = X - {x0}" using bij
    using bij_betw_imp_surj_on by blast
  also note eq [symmetric]
  finally show ?thesis
    using finite_imp_compact_convex_hull[OF \<open>finite X\<close>] by (auto dest: compact_imp_closed)
qed

theorem content_triangle:
  fixes A B C :: "real ^ 2"
  shows "content (convex hull {A, B, C}) =
           \<bar>(C $ 1 - A $ 1) * (B $ 2 - A $ 2) - (B $ 1 - A $ 1) * (C $ 2 - A $ 2)\<bar> / 2"
proof -
  define M :: "real ^ 2 ^ 2" where "M \<equiv> (\<chi> i. \<chi> j. (if j = 1 then B else C) $ i - A $ i)"
  define g where "g = (\<lambda>x. M *v x)"
  define std where "std = (convex hull insert 0 Basis :: (real ^ 2) set)"
  have [simp]: "M *v axis i 1 = (if i = 1 then B - A else C - A)" for i
    by (auto simp: M_def matrix_vector_mult_basis column_def vec_eq_iff)
  have compact: "compact std" unfolding std_def
    by (intro finite_imp_compact_convex_hull) auto

  have "measure lebesgue (convex hull {A, B, C}) =
          measure lebesgue (((+) (-A)) ` (convex hull {A, B, C}))"
    by (rule measure_translation [symmetric])
  also have "((+) (-A)) ` (convex hull {A, B, C}) = convex hull (((+) (-A)) ` {A, B, C})"
    by (rule convex_hull_translation [symmetric])
  also have "((+) (-A)) ` {A, B, C} = {0, B - A, C - A}"
    by (auto simp: image_iff)
  finally have eq: "measure lebesgue (convex hull {A, B, C}) =
                      measure lebesgue (convex hull {0, B - A, C - A})" .

  from compact have "measure lebesgue (g ` std) = \<bar>det M\<bar> * measure lebesgue std"
    by (subst measure_lebesgue_linear_transformation)
       (auto intro: finite_imp_bounded_convex_hull dest: compact_imp_closed simp: g_def std_def)
  also have "measure lebesgue std = content std" using compact
    by (intro measure_completion) (auto dest: compact_imp_closed)
  also have "content std = 1 / 2" unfolding std_def
    by (simp add: content_std_simplex)
  also have "g ` std = convex hull (g ` insert 0 Basis)" unfolding std_def
    by (rule convex_hull_linear_image) (auto simp: g_def)
  also have "g ` insert 0 Basis = insert 0 (g ` Basis)"
    by (auto simp: g_def)
  also have "(2 :: 2) \<noteq> 1" by auto
  hence "\<not>(\<forall>y::2. y = 1)" by blast
  hence "g ` Basis = {B - A, C - A}"
    by (auto simp: g_def Basis_vec_def image_iff)
  also note eq [symmetric]
  finally show ?thesis
    using finite_imp_compact_convex_hull[of "{A, B, C}"]
    by (auto dest!: compact_imp_closed simp: det_2 M_def)
qed

theorem heron:
  fixes A B C :: "real ^ 2"
  defines "a \<equiv> dist B C" and "b \<equiv> dist A C" and "c \<equiv> dist A B"
  defines "s \<equiv> (a + b + c) / 2"
  shows   "content (convex hull {A, B, C}) = sqrt (s * (s - a) * (s - b) * (s - c))"
proof -
  have [simp]: "(UNIV :: 2 set) = {1, 2}"
    using exhaust_2 by auto
  have dist_eq: "dist (A :: real ^ 2) B ^ 2 = (A $ 1 - B $ 1) ^ 2 + (A $ 2 - B $ 2) ^ 2"
    for A B by (simp add: dist_vec_def dist_real_def)
  have nonneg: "s * (s - a) * (s - b) * (s - c) \<ge> 0"
    using dist_triangle[of A B C] dist_triangle[of A C B] dist_triangle[of B C A]
    by (intro mult_nonneg_nonneg) (auto simp: s_def a_def b_def c_def dist_commute)

  have "16 * content (convex hull {A, B, C}) ^ 2 =
          4 * ((C $ 1 - A $ 1) * (B $ 2 - A $ 2) - (B $ 1 - A $ 1) * (C $ 2 - A $ 2)) ^ 2"
    by (subst content_triangle) (simp add: power_divide)
  also have "\<dots> = (2 * (dist A B ^ 2 * dist A C ^ 2 + dist A B ^ 2 * dist B C ^ 2 +
      dist A C ^ 2 * dist B C ^ 2) - (dist A B ^ 2) ^ 2 - (dist A C ^ 2) ^ 2 - (dist B C ^ 2) ^ 2)"
    unfolding dist_eq unfolding power2_eq_square by algebra
  also have "\<dots> = (a + b + c) * ((a + b + c) - 2 * a) * ((a + b + c) - 2 * b) *
                    ((a + b + c) - 2 * c)"
    unfolding power2_eq_square by (simp add: s_def a_def b_def c_def algebra_simps)
  also have "\<dots> = 16 * s * (s - a) * (s - b) * (s - c)"
    by (simp add: s_def field_split_simps)
  finally have "content (convex hull {A, B, C}) ^ 2 = s * (s - a) * (s - b) * (s - c)"
    by simp
  also have "\<dots> = sqrt (s * (s - a) * (s - b) * (s - c)) ^ 2"
    by (intro real_sqrt_pow2 [symmetric] nonneg)
  finally show ?thesis using nonneg
    by (subst (asm) power2_eq_iff_nonneg) auto
qed

end


(*  Title:      Well-Quasi-Orders
    Author:     Christian Sternagel <c.sternagel@gmail.com>
    Maintainer: Christian Sternagel
    License:    LGPL
*)

section \<open>Enumerations of Well-Ordered Sets in Increasing Order\<close>

theory Least_Enum
imports Main
begin

locale infinitely_many1 =
  fixes P :: "'a :: wellorder \<Rightarrow> bool"
  assumes infm: "\<forall>i. \<exists>j>i. P j"
begin

text \<open>
  Enumerate the elements of a well-ordered infinite set in increasing order.
\<close>
fun enum :: "nat \<Rightarrow> 'a" where
  "enum 0 = (LEAST n. P n)" |
  "enum (Suc i) = (LEAST n. n > enum i \<and> P n)"

lemma enum_mono:
  shows "enum i < enum (Suc i)"
  using infm by (cases i, auto) (metis (lifting) LeastI)+

lemma enum_less:
  "i < j \<Longrightarrow> enum i < enum j"
  using enum_mono by (metis lift_Suc_mono_less)

lemma enum_P:
  shows "P (enum i)"
  using infm by (cases i, auto) (metis (lifting) LeastI)+

end

locale infinitely_many2 =
  fixes P :: "'a :: wellorder \<Rightarrow> 'a \<Rightarrow> bool"
    and N :: "'a"
  assumes infm: "\<forall>i\<ge>N. \<exists>j>i. P i j"
begin

text \<open>
  Enumerate the elements of a well-ordered infinite set that form a chain w.r.t.\ a given predicate
  @{term P} starting from a given index @{term N} in increasing order.
\<close>
fun enumchain :: "nat \<Rightarrow> 'a" where
  "enumchain 0 = N" |
  "enumchain (Suc n) = (LEAST m. m > enumchain n \<and> P (enumchain n) m)"

lemma enumchain_mono:
  shows "N \<le> enumchain i \<and> enumchain i < enumchain (Suc i)"
proof (induct i)
  case 0
  have "enumchain 0 \<ge> N" by simp
  moreover then have "\<exists>m>enumchain 0. P (enumchain 0) m" using infm by blast
  ultimately show ?case by auto (metis (lifting) LeastI)
next
  case (Suc i)
  then have "N \<le> enumchain (Suc i)" by auto
  moreover then have "\<exists>m>enumchain (Suc i). P (enumchain (Suc i)) m" using infm by blast
  ultimately show ?case by (auto) (metis (lifting) LeastI)
qed

lemma enumchain_chain:
  shows "P (enumchain i) (enumchain (Suc i))"
proof (cases i)
  case 0
  moreover have "\<exists>m>enumchain 0. P (enumchain 0) m" using infm by auto
  ultimately show ?thesis by auto (metis (lifting) LeastI)
next
  case (Suc i)
  moreover have "enumchain (Suc i) > N" using enumchain_mono by (metis le_less_trans)
  moreover then have "\<exists>m>enumchain (Suc i). P (enumchain (Suc i)) m" using infm by auto
  ultimately show ?thesis by (auto) (metis (lifting) LeastI)
qed

end

end


(*<*)
theory T11EnumFormulasIngles
imports T10MaximalHintikkaIngles EnumArbolesBinariosIngles
begin
(*>*)

subsection \<open> Enumeración de fórmulas proposicionales \<close>

text \<open>

  Para enumerar las fórmulas de un lenguaje proposicional, mostramos
  inicialmente cómo asignar una fórmula a cada árbol binario que sea una
  hoja con t_v_evaluation $n\geq 0$ y, de forma recursiva, a cada árbol binario
  cuyo hijo izquierdo esté compuesto por una hoja con t_v_evaluation entre 0 y 4,
  del cual dependerá el tipo de fórmula que se le asocie.

  Sea $g$ una sucesión de símbolos proposicionales:
 \begin{enumerate}
  \item
  \begin{enumerate}
    \qtreecenterfalse
    \item Al árbol compuesto por la hoja 0 le corresponde la fórmula $\bot$.
    \item Al árbol compuesto por la hoja 1 le corresponde la fórmula $\top$.
    \item Al árbol compuesto por la hoja $n+2$  le corresponde la
      fórmula atómica $P$, donde $g(n)= P.$
    \end{enumerate}
  \item
   \begin{enumerate}
    \item Al árbol,
      {\begin{center}
       \qtreecenterfalse
      \Tree [ $n$  [ \qroof{árbol  binario $T_1$}.{\textbullet}
                     \qroof{árbol  binario $T_2$}.{\textbullet} ] ]
       \end{center}}
      le corresponde una de las fórmulas $F \wedge G$, $F \vee G$,
      $F \rightarrow G$ dependiendo si $n=1$, $n=2$ ó $n=3$,
      respectivamente. Donde $F,G$ son las fórmulas corres\-pondientes a
      los árboles $T_1, T_2$.
    \item Al árbol,
      {\begin{center}
        \qtreecenterfalse
        \Tree [ $4$   \qroof{árbol  binario $T$}.{\textbullet} ]
       \end{center}}
      le corresponde la fórmula $\neg F$. Donde $F$ es la fórmula
      correspondiente al árbol $T$.
   \end{enumerate}
  \end{enumerate}

  Obsérvese que no todos los árboles binarios tienen una fórmula asociada.
  La si\-guiente función {\em parcial} formaliza la correspondencia
  anterior.
\<close>

fun formulaP_del_arbolb :: "(nat \<Rightarrow> 'b) \<Rightarrow> arbolb \<Rightarrow> 'b formula" where
  "formulaP_del_arbolb g (Hoja 0) = FF"
| "formulaP_del_arbolb g (Hoja (Suc 0)) = TT"
| "formulaP_del_arbolb g (Hoja (Suc (Suc n))) = (atom (g n))"
| "formulaP_del_arbolb g (Arbol (Hoja (Suc 0)) (Arbol T1 T2)) =
   ((formulaP_del_arbolb g T1) \<and>. (formulaP_del_arbolb g T2))"
| "formulaP_del_arbolb g (Arbol (Hoja (Suc (Suc 0))) (Arbol T1 T2)) =
   ((formulaP_del_arbolb g T1) \<or>. (formulaP_del_arbolb g T2))"
| "formulaP_del_arbolb g (Arbol (Hoja (Suc (Suc (Suc 0)))) (Arbol T1 T2)) =
   ((formulaP_del_arbolb g T1) \<rightarrow>. (formulaP_del_arbolb g T2))"
| "formulaP_del_arbolb g (Arbol (Hoja (Suc (Suc (Suc (Suc 0))))) T) =
   (\<not>. (formulaP_del_arbolb g T))"
(*<*)

lemma "formulaP_del_arbolb  (\<lambda>n. n) (Hoja  0) = FF"
by simp
(*
normal_form
  "formulaP_del_arbolb (\<lambda>n. n) (Arbol (Hoja (Suc 0)) (Arbol (Hoja 0) (Hoja 0)))"
*)
lemma
  "formulaP_del_arbolb
   (\<lambda>n. n) (Arbol (Hoja (Suc 0)) (Arbol (Hoja 0) (Hoja 0))) = FF \<and>. FF"
by simp
(*
normal_form
  "formulaP_del_arbolb g (Arbol (Hoja (Suc 0)) (Arbol (Hoja 0) (Hoja 0)))"
*)
lemma
  "formulaP_del_arbolb g (Arbol (Hoja (Suc 0)) (Arbol (Hoja 0) (Hoja 0)))
   = FF \<and>. FF"
by simp
(*
normal_form  "formulaP_del_arbolb (\<lambda>n. n) (Hoja  0) = FF"
normal_form  "formulaP_del_arbolb (\<lambda>n. n) (Hoja  0)"
normal_form
  "formulaP_del_arbolb
   (\<lambda>n. n) (Arbol (Hoja (Suc (Suc (Suc (Suc 0))))) (Hoja 0))"
*)
lemma
  "formulaP_del_arbolb
  (\<lambda>n. n) (Arbol (Hoja (Suc (Suc (Suc (Suc 0))))) (Hoja 0)) = (\<not>. FF)"
by simp
(*>*)

text \<open>
  De manera recíproca, la siguiente función formaliza la inversa de la
  correspon\-dencia anterior: dada una función $g$ del conjunto de símbolos
  proposicionales al conjunto de números naturales, a cada fórmula
  proposicional se le asigna un árbol binario.
\<close>

primrec arbolb_de_la_formulaP :: "('b \<Rightarrow> nat) \<Rightarrow>  'b formula \<Rightarrow> arbolb" where
  "arbolb_de_la_formulaP  g FF = Hoja 0"
| "arbolb_de_la_formulaP g TT = Hoja (Suc 0)"
| "arbolb_de_la_formulaP g (atom P) = Hoja (Suc (Suc (g P)))"
| "arbolb_de_la_formulaP g (F \<and>. G) = Arbol (Hoja (Suc 0))
   (Arbol (arbolb_de_la_formulaP g F) (arbolb_de_la_formulaP g G))"
| "arbolb_de_la_formulaP g (F \<or>. G) = Arbol (Hoja (Suc (Suc 0)))
   (Arbol (arbolb_de_la_formulaP g F) (arbolb_de_la_formulaP g G))"
| "arbolb_de_la_formulaP g (F \<rightarrow>. G) = Arbol (Hoja (Suc (Suc (Suc 0))))
   (Arbol (arbolb_de_la_formulaP g F) (arbolb_de_la_formulaP g G))"
| "arbolb_de_la_formulaP g (\<not>. F) = Arbol (Hoja (Suc (Suc (Suc (Suc 0)))))
   (arbolb_de_la_formulaP g F)"

text \<open>
  Con base a lo anterior, y usando la enumeración @{text "diag_arbolb"}
  del conjunto de árboles binarios, tenemos que en cualquier lenguaje
  proposicional y por cada enumeración $g$ del conjunto $\mathcal{P}$ de
  símbolos proposicionales, podemos construir una enumeración $\Delta_{g}$ del
  co\-rrespondiente conjunto de fórmulas $\mathcal{F}$:

  \begin{definicion}\label{enumformulasP}
  La función $\Delta_{g} : \mathbb{N} \to \mathcal{F}$ está definida
  por,
  $$\Delta_{g}(n) =
    (formulaP\mbox{-}de\mbox{-}arbolb\ g)(diag\mbox{-}arbolb\ n).$$
  \end{definicion}

  \begin{teorema}\label{enumformulas1}
  Sea $g:\mathbb{N} \to \mathcal{P}$ una enumeración de los símbolos
  proposicionales del lenguaje $\mathbf{L}$. Entonces, $\Delta_{g}$ es
  una enumeración del conjunto de fórmulas de $\mathbf{L}$.
  \end{teorema}

  \begin{demostracion}
  Por hipótesis y el lema \ref{enumera}, existe $g':\mathcal{P}\to
  \mathbb{N}$ inversa a derecha de $g$. Entonces, la función
  $\Delta'_{g'} : \mathcal{F}\to \mathbb{N}$ definida por,
  $$\Delta'_{g'}(F) = undiag\mbox{-}arbolb\
  (arbolb\mbox{-}de\mbox{-}la\mbox{-}formulaP\ g'\ F),$$ es inversa por
  derecha de $\Delta_{g}$. Es decir, $\Delta_{g}(\Delta'_{g'}(F)) = F$
  para toda fórmula $F$.
  \end{demostracion}

  Para la formalización del teorema anterior, definimos en Isabelle la
  función $\Delta_{g}$ y su inversa $\Delta'_{g}$ de la siguiente manera.
\<close>

definition \<Delta>P :: "(nat \<Rightarrow> 'b) \<Rightarrow> nat \<Rightarrow> 'b formula" where
  "\<Delta>P g n = formulaP_del_arbolb g (diag_arbolb n)"

definition \<Delta>P' :: "('b \<Rightarrow> nat) \<Rightarrow> 'b formula \<Rightarrow> nat" where
  "\<Delta>P' g' F = undiag_arbolb (arbolb_de_la_formulaP g' F)"

theorem enumerationformulasP[simp]:
  assumes "\<forall>x. g(g' x) = x"
  shows "\<Delta>P g (\<Delta>P' g' F) = F"
using assms
by (induct F)(simp_all add: \<Delta>P_def \<Delta>P'_def)

text \<open>
  Los siguientes corolarios muestran otras formas de expresar la
  propiedad de enumerabilidad anterior.

  \begin{corolario}\label{enumformulasP}
  Sea $g:\mathbb{N} \to \mathcal{P}$ tal que, $\forall P \exists n\, (P
  = g(n))$. Entonces, $\forall F \exists n\, (F = \Delta_{g}(n))$.
  \end{corolario}

\begin{demostracion}
  Sea $g':\mathcal{P} \to \mathbb{N}$ definida de la siguiente manera:
  dado $P\in \mathcal{P}$, definimos $g'(P)=n$, donde $n$ es tal que $P
  = g(n)$.

  De las definición anterior se tiene que $g(g'(P)) = P$ para todo $P\in
  \mathcal{P}$. Luego, por el teorema anterior, $\Delta_{g}
  (\Delta'_{g'}(F))=F$ para toda fórmula $F$. De esta forma, para toda
  fórmula $F$ existe $n$ tal que, $F = \Delta_{g}(n)$, donde
  $n=\Delta'_{g'}(F)$.
  \end{demostracion}

  \noindent Su formalización es:
\<close>

corollary EnumerationFormulasP:
  assumes "\<forall>P. \<exists> n. P = g n"
  shows "\<forall>F. \<exists>n. F = \<Delta>P g n"
proof (rule allI)
  fix F
  { have "\<forall>P. P = g (SOME n. P = (g n))"
    proof(rule allI)
      fix P
      obtain n where n: "P=g(n)" using assms by auto
      thus "P = g (SOME n. P = (g n))" by (rule someI)
    qed }
  hence "\<forall>P. g((\<lambda>P. SOME n. P = (g n)) P) = P" by simp
  hence "F = \<Delta>P g (\<Delta>P' (\<lambda>P. SOME n. P = (g n)) F)"
    using enumerationformulasP by simp
  thus "\<exists>n. F = \<Delta>P g n"
    by (rule_tac x= "(\<Delta>P' (\<lambda>P. SOME n. P = (g n)) F)" in exI)
qed

text \<open>
  \begin{corolario}\label{EnumeracionFormulas}
  Si $g:\mathbb{N} \to \mathcal{P}$ es una enumeración del conjunto de
  símbolos proposicionales $\mathcal{P}$ de un lenguaje $\mathbf{L}$,
  entonces la función $\Delta_{g} : \mathbb{N} \to \mathcal{F}$
  (definición \ref{enumformulasP}) es una enumeración del
  corres\-pondiente conjunto de fórmulas proposicionales $\mathcal{F}$.
  \end{corolario}

  \begin{demostracion}
  Es consecuencia del corolario anterior y la definición de enumeración.
  \end{demostracion}

  \noindent Su formalización es:
\<close>

corollary EnumerationFormulasP1:
  assumes "enumeration (g:: nat \<Rightarrow> 'b)"
  shows "enumeration ((\<Delta>P g):: nat \<Rightarrow> 'b formula)"
proof -
  have "\<forall>P. \<exists> n. P = g n" using assms by(unfold enumeration_def)
  hence "\<forall>F. \<exists>n. F = \<Delta>P g n" using EnumerationFormulasP by auto
  thus ?thesis by(unfold enumeration_def)
qed
text\<open> Por ejemplo,
\begin{corolario}\label{EnumeracionFormulasNat}
El lenguaje proposicional con símbolos proposicionales
los números naturales es enumerable.
\end{corolario}
\begin{demostracion}
Puesto que la función identidad es una enumeración de los números
naturales (\ref{enumidentidad}), por el teorema anterior, se tiene el resultado.
\end{demostracion}
 \<close>
corollary EnumeracionFormulasNat:
  shows "\<exists> f. enumeration (f:: nat \<Rightarrow> nat formula)"
  proof -
    obtain g where g: "enumeration (g:: nat \<Rightarrow> nat)" using enum_nat by auto
    thus  "\<exists> f. enumeration (f:: nat \<Rightarrow> nat formula)"
      using  enum_nat EnumerationFormulasP1 by auto
qed
(*<*)
end
(*>*)