(*  Title:      HOL/Code_Numeral.thy
    Author:     Florian Haftmann, TU Muenchen
*)

section \<open>Numeric types for code generation onto target language numerals only\<close>

theory Code_Numeral
imports Divides Lifting Bit_Operations
begin

subsection \<open>Type of target language integers\<close>

typedef integer = "UNIV :: int set"
  morphisms int_of_integer integer_of_int ..

setup_lifting type_definition_integer

lemma integer_eq_iff:
  "k = l \<longleftrightarrow> int_of_integer k = int_of_integer l"
  by transfer rule

lemma integer_eqI:
  "int_of_integer k = int_of_integer l \<Longrightarrow> k = l"
  using integer_eq_iff [of k l] by simp

lemma int_of_integer_integer_of_int [simp]:
  "int_of_integer (integer_of_int k) = k"
  by transfer rule

lemma integer_of_int_int_of_integer [simp]:
  "integer_of_int (int_of_integer k) = k"
  by transfer rule

instantiation integer :: ring_1
begin

lift_definition zero_integer :: integer
  is "0 :: int"
  .

declare zero_integer.rep_eq [simp]

lift_definition one_integer :: integer
  is "1 :: int"
  .

declare one_integer.rep_eq [simp]

lift_definition plus_integer :: "integer \<Rightarrow> integer \<Rightarrow> integer"
  is "plus :: int \<Rightarrow> int \<Rightarrow> int"
  .

declare plus_integer.rep_eq [simp]

lift_definition uminus_integer :: "integer \<Rightarrow> integer"
  is "uminus :: int \<Rightarrow> int"
  .

declare uminus_integer.rep_eq [simp]

lift_definition minus_integer :: "integer \<Rightarrow> integer \<Rightarrow> integer"
  is "minus :: int \<Rightarrow> int \<Rightarrow> int"
  .

declare minus_integer.rep_eq [simp]

lift_definition times_integer :: "integer \<Rightarrow> integer \<Rightarrow> integer"
  is "times :: int \<Rightarrow> int \<Rightarrow> int"
  .

declare times_integer.rep_eq [simp]

instance proof
qed (transfer, simp add: algebra_simps)+

end

instance integer :: Rings.dvd ..

context
  includes lifting_syntax
  notes transfer_rule_numeral [transfer_rule]
begin

lemma [transfer_rule]:
  "((\<longleftrightarrow>) ===> pcr_integer) of_bool of_bool"
  by (unfold of_bool_def) transfer_prover

lemma [transfer_rule]:
  "((=) ===> pcr_integer) int of_nat"
  by (rule transfer_rule_of_nat) transfer_prover+

lemma [transfer_rule]:
  "((=) ===> pcr_integer) (\<lambda>k. k) of_int"
proof -
  have "((=) ===> pcr_integer) of_int of_int"
    by (rule transfer_rule_of_int) transfer_prover+
  then show ?thesis by (simp add: id_def)
qed

lemma [transfer_rule]:
  "((=) ===> pcr_integer) numeral numeral"
  by transfer_prover

lemma [transfer_rule]:
  "((=) ===> (=) ===> pcr_integer) Num.sub Num.sub"
  by (unfold Num.sub_def) transfer_prover

lemma [transfer_rule]:
  "(pcr_integer ===> (=) ===> pcr_integer) (^) (^)"
  by (unfold power_def) transfer_prover

end

lemma int_of_integer_of_nat [simp]:
  "int_of_integer (of_nat n) = of_nat n"
  by transfer rule

lift_definition integer_of_nat :: "nat \<Rightarrow> integer"
  is "of_nat :: nat \<Rightarrow> int"
  .

lemma integer_of_nat_eq_of_nat [code]:
  "integer_of_nat = of_nat"
  by transfer rule

lemma int_of_integer_integer_of_nat [simp]:
  "int_of_integer (integer_of_nat n) = of_nat n"
  by transfer rule

lift_definition nat_of_integer :: "integer \<Rightarrow> nat"
  is Int.nat
  .

lemma nat_of_integer_of_nat [simp]:
  "nat_of_integer (of_nat n) = n"
  by transfer simp

lemma int_of_integer_of_int [simp]:
  "int_of_integer (of_int k) = k"
  by transfer simp

lemma nat_of_integer_integer_of_nat [simp]:
  "nat_of_integer (integer_of_nat n) = n"
  by transfer simp

lemma integer_of_int_eq_of_int [simp, code_abbrev]:
  "integer_of_int = of_int"
  by transfer (simp add: fun_eq_iff)

lemma of_int_integer_of [simp]:
  "of_int (int_of_integer k) = (k :: integer)"
  by transfer rule

lemma int_of_integer_numeral [simp]:
  "int_of_integer (numeral k) = numeral k"
  by transfer rule

lemma int_of_integer_sub [simp]:
  "int_of_integer (Num.sub k l) = Num.sub k l"
  by transfer rule

definition integer_of_num :: "num \<Rightarrow> integer"
  where [simp]: "integer_of_num = numeral"

lemma integer_of_num [code]:
  "integer_of_num Num.One = 1"
  "integer_of_num (Num.Bit0 n) = (let k = integer_of_num n in k + k)"
  "integer_of_num (Num.Bit1 n) = (let k = integer_of_num n in k + k + 1)"
  by (simp_all only: integer_of_num_def numeral.simps Let_def)

lemma integer_of_num_triv:
  "integer_of_num Num.One = 1"
  "integer_of_num (Num.Bit0 Num.One) = 2"
  by simp_all

instantiation integer :: "{linordered_idom, equal}"
begin

lift_definition abs_integer :: "integer \<Rightarrow> integer"
  is "abs :: int \<Rightarrow> int"
  .

declare abs_integer.rep_eq [simp]

lift_definition sgn_integer :: "integer \<Rightarrow> integer"
  is "sgn :: int \<Rightarrow> int"
  .

declare sgn_integer.rep_eq [simp]

lift_definition less_eq_integer :: "integer \<Rightarrow> integer \<Rightarrow> bool"
  is "less_eq :: int \<Rightarrow> int \<Rightarrow> bool"
  .

lemma integer_less_eq_iff:
  "k \<le> l \<longleftrightarrow> int_of_integer k \<le> int_of_integer l"
  by (fact less_eq_integer.rep_eq)

lift_definition less_integer :: "integer \<Rightarrow> integer \<Rightarrow> bool"
  is "less :: int \<Rightarrow> int \<Rightarrow> bool"
  .

lemma integer_less_iff:
  "k < l \<longleftrightarrow> int_of_integer k < int_of_integer l"
  by (fact less_integer.rep_eq)

lift_definition equal_integer :: "integer \<Rightarrow> integer \<Rightarrow> bool"
  is "HOL.equal :: int \<Rightarrow> int \<Rightarrow> bool"
  .

instance
  by standard (transfer, simp add: algebra_simps equal less_le_not_le [symmetric] mult_strict_right_mono linear)+

end

context
  includes lifting_syntax
begin

lemma [transfer_rule]:
  \<open>(pcr_integer ===> pcr_integer ===> pcr_integer) min min\<close>
  by (unfold min_def) transfer_prover

lemma [transfer_rule]:
  \<open>(pcr_integer ===> pcr_integer ===> pcr_integer) max max\<close>
  by (unfold max_def) transfer_prover

end

lemma int_of_integer_min [simp]:
  "int_of_integer (min k l) = min (int_of_integer k) (int_of_integer l)"
  by transfer rule

lemma int_of_integer_max [simp]:
  "int_of_integer (max k l) = max (int_of_integer k) (int_of_integer l)"
  by transfer rule

lemma nat_of_integer_non_positive [simp]:
  "k \<le> 0 \<Longrightarrow> nat_of_integer k = 0"
  by transfer simp

lemma of_nat_of_integer [simp]:
  "of_nat (nat_of_integer k) = max 0 k"
  by transfer auto

instantiation integer :: unique_euclidean_ring
begin

lift_definition divide_integer :: "integer \<Rightarrow> integer \<Rightarrow> integer"
  is "divide :: int \<Rightarrow> int \<Rightarrow> int"
  .

declare divide_integer.rep_eq [simp]

lift_definition modulo_integer :: "integer \<Rightarrow> integer \<Rightarrow> integer"
  is "modulo :: int \<Rightarrow> int \<Rightarrow> int"
  .

declare modulo_integer.rep_eq [simp]

lift_definition euclidean_size_integer :: "integer \<Rightarrow> nat"
  is "euclidean_size :: int \<Rightarrow> nat"
  .

declare euclidean_size_integer.rep_eq [simp]

lift_definition division_segment_integer :: "integer \<Rightarrow> integer"
  is "division_segment :: int \<Rightarrow> int"
  .

declare division_segment_integer.rep_eq [simp]

instance
  apply (standard; transfer)
  apply (use mult_le_mono2 [of 1] in \<open>auto simp add: sgn_mult_abs abs_mult sgn_mult abs_mod_less sgn_mod nat_mult_distrib
     division_segment_mult division_segment_mod\<close>)
  apply (simp add: division_segment_int_def split: if_splits)
  done

end

lemma [code]:
  "division_segment (k :: integer) = (if k \<ge> 0 then 1 else - 1)"
  by transfer (simp add: division_segment_int_def)

instance integer :: unique_euclidean_ring_with_nat
  by (standard; transfer) (simp_all add: of_nat_div division_segment_int_def)

instantiation integer :: ring_bit_operations
begin

lift_definition bit_integer :: \<open>integer \<Rightarrow> nat \<Rightarrow> bool\<close>
  is bit .

lift_definition not_integer :: \<open>integer \<Rightarrow> integer\<close>
  is not .

lift_definition and_integer :: \<open>integer \<Rightarrow> integer \<Rightarrow> integer\<close>
  is \<open>and\<close> .

lift_definition or_integer :: \<open>integer \<Rightarrow> integer \<Rightarrow> integer\<close>
  is or .

lift_definition xor_integer ::  \<open>integer \<Rightarrow> integer \<Rightarrow> integer\<close>
  is xor .

lift_definition mask_integer :: \<open>nat \<Rightarrow> integer\<close>
  is mask .

lift_definition set_bit_integer :: \<open>nat \<Rightarrow> integer \<Rightarrow> integer\<close>
  is set_bit .

lift_definition unset_bit_integer :: \<open>nat \<Rightarrow> integer \<Rightarrow> integer\<close>
  is unset_bit .

lift_definition flip_bit_integer :: \<open>nat \<Rightarrow> integer \<Rightarrow> integer\<close>
  is flip_bit .

lift_definition push_bit_integer :: \<open>nat \<Rightarrow> integer \<Rightarrow> integer\<close>
  is push_bit .

lift_definition drop_bit_integer :: \<open>nat \<Rightarrow> integer \<Rightarrow> integer\<close>
  is drop_bit .

lift_definition take_bit_integer :: \<open>nat \<Rightarrow> integer \<Rightarrow> integer\<close>
  is take_bit .

instance by (standard; transfer)
  (fact bit_eq_rec bits_induct bit_iff_odd push_bit_eq_mult drop_bit_eq_div take_bit_eq_mod
    bits_div_0 bits_div_by_1 bits_mod_div_trivial even_succ_div_2
    exp_div_exp_eq div_exp_eq mod_exp_eq mult_exp_mod_exp_eq div_exp_mod_exp_eq
    even_mask_div_iff even_mult_exp_div_exp_iff
    bit_and_iff bit_or_iff bit_xor_iff mask_eq_exp_minus_1
    set_bit_def bit_unset_bit_iff flip_bit_def bit_not_iff_eq minus_eq_not_minus_1)+

end

instance integer :: unique_euclidean_semiring_with_bit_operations ..

context
  includes bit_operations_syntax
begin

lemma [code]:
  \<open>bit k n \<longleftrightarrow> odd (drop_bit n k)\<close>
  \<open>NOT k = - k - 1\<close>
  \<open>mask n = 2 ^ n - (1 :: integer)\<close>
  \<open>set_bit n k = k OR push_bit n 1\<close>
  \<open>unset_bit n k = k AND NOT (push_bit n 1)\<close>
  \<open>flip_bit n k = k XOR push_bit n 1\<close>
  \<open>push_bit n k = k * 2 ^ n\<close>
  \<open>drop_bit n k = k div 2 ^ n\<close>
  \<open>take_bit n k = k mod 2 ^ n\<close> for k :: integer
  by (fact bit_iff_odd_drop_bit not_eq_complement mask_eq_exp_minus_1
    set_bit_eq_or unset_bit_eq_and_not flip_bit_eq_xor push_bit_eq_mult drop_bit_eq_div take_bit_eq_mod)+

lemma [code]:
  \<open>k AND l = (if k = 0 \<or> l = 0 then 0 else if k = - 1 then l else if l = - 1 then k
    else (k mod 2) * (l mod 2) + 2 * ((k div 2) AND (l div 2)))\<close> for k l :: integer
  by transfer (fact and_int_unfold)

lemma [code]:
  \<open>k OR l = (if k = - 1 \<or> l = - 1 then - 1 else if k = 0 then l else if l = 0 then k
    else max (k mod 2) (l mod 2) + 2 * ((k div 2) OR (l div 2)))\<close> for k l :: integer
  by transfer (fact or_int_unfold)

lemma [code]:
  \<open>k XOR l = (if k = - 1 then NOT l else if l = - 1 then NOT k else if k = 0 then l else if l = 0 then k
    else \<bar>k mod 2 - l mod 2\<bar> + 2 * ((k div 2) XOR (l div 2)))\<close> for k l :: integer
  by transfer (fact xor_int_unfold)

end

instantiation integer :: unique_euclidean_semiring_with_nat_division
begin

definition divmod_integer :: "num \<Rightarrow> num \<Rightarrow> integer \<times> integer"
where
  divmod_integer'_def: "divmod_integer m n = (numeral m div numeral n, numeral m mod numeral n)"

definition divmod_step_integer :: "integer \<Rightarrow> integer \<times> integer \<Rightarrow> integer \<times> integer"
where
  "divmod_step_integer l qr = (let (q, r) = qr
    in if \<bar>l\<bar> \<le> \<bar>r\<bar> then (2 * q + 1, r - l)
    else (2 * q, r))"

instance by standard
  (auto simp add: divmod_integer'_def divmod_step_integer_def integer_less_eq_iff)

end

declare divmod_algorithm_code [where ?'a = integer,
  folded integer_of_num_def, unfolded integer_of_num_triv,
  code]

lemma integer_of_nat_0: "integer_of_nat 0 = 0"
by transfer simp

lemma integer_of_nat_1: "integer_of_nat 1 = 1"
by transfer simp

lemma integer_of_nat_numeral:
  "integer_of_nat (numeral n) = numeral n"
by transfer simp

subsection \<open>Code theorems for target language integers\<close>

text \<open>Constructors\<close>

definition Pos :: "num \<Rightarrow> integer"
where
  [simp, code_post]: "Pos = numeral"

context
  includes lifting_syntax
begin

lemma [transfer_rule]:
  \<open>((=) ===> pcr_integer) numeral Pos\<close>
  by simp transfer_prover

end

lemma Pos_fold [code_unfold]:
  "numeral Num.One = Pos Num.One"
  "numeral (Num.Bit0 k) = Pos (Num.Bit0 k)"
  "numeral (Num.Bit1 k) = Pos (Num.Bit1 k)"
  by simp_all

definition Neg :: "num \<Rightarrow> integer"
where
  [simp, code_abbrev]: "Neg n = - Pos n"

context
  includes lifting_syntax
begin

lemma [transfer_rule]:
  \<open>((=) ===> pcr_integer) (\<lambda>n. - numeral n) Neg\<close>
  by (unfold Neg_def) transfer_prover

end

code_datatype "0::integer" Pos Neg

text \<open>A further pair of constructors for generated computations\<close>

context
begin

qualified definition positive :: "num \<Rightarrow> integer"
  where [simp]: "positive = numeral"

qualified definition negative :: "num \<Rightarrow> integer"
  where [simp]: "negative = uminus \<circ> numeral"

lemma [code_computation_unfold]:
  "numeral = positive"
  "Pos = positive"
  "Neg = negative"
  by (simp_all add: fun_eq_iff)

end

text \<open>Auxiliary operations\<close>

lift_definition dup :: "integer \<Rightarrow> integer"
  is "\<lambda>k::int. k + k"
  .

lemma dup_code [code]:
  "dup 0 = 0"
  "dup (Pos n) = Pos (Num.Bit0 n)"
  "dup (Neg n) = Neg (Num.Bit0 n)"
  by (transfer, simp only: numeral_Bit0 minus_add_distrib)+

lift_definition sub :: "num \<Rightarrow> num \<Rightarrow> integer"
  is "\<lambda>m n. numeral m - numeral n :: int"
  .

lemma sub_code [code]:
  "sub Num.One Num.One = 0"
  "sub (Num.Bit0 m) Num.One = Pos (Num.BitM m)"
  "sub (Num.Bit1 m) Num.One = Pos (Num.Bit0 m)"
  "sub Num.One (Num.Bit0 n) = Neg (Num.BitM n)"
  "sub Num.One (Num.Bit1 n) = Neg (Num.Bit0 n)"
  "sub (Num.Bit0 m) (Num.Bit0 n) = dup (sub m n)"
  "sub (Num.Bit1 m) (Num.Bit1 n) = dup (sub m n)"
  "sub (Num.Bit1 m) (Num.Bit0 n) = dup (sub m n) + 1"
  "sub (Num.Bit0 m) (Num.Bit1 n) = dup (sub m n) - 1"
  by (transfer, simp add: dbl_def dbl_inc_def dbl_dec_def)+

text \<open>Implementations\<close>

lemma one_integer_code [code, code_unfold]:
  "1 = Pos Num.One"
  by simp

lemma plus_integer_code [code]:
  "k + 0 = (k::integer)"
  "0 + l = (l::integer)"
  "Pos m + Pos n = Pos (m + n)"
  "Pos m + Neg n = sub m n"
  "Neg m + Pos n = sub n m"
  "Neg m + Neg n = Neg (m + n)"
  by (transfer, simp)+

lemma uminus_integer_code [code]:
  "uminus 0 = (0::integer)"
  "uminus (Pos m) = Neg m"
  "uminus (Neg m) = Pos m"
  by simp_all

lemma minus_integer_code [code]:
  "k - 0 = (k::integer)"
  "0 - l = uminus (l::integer)"
  "Pos m - Pos n = sub m n"
  "Pos m - Neg n = Pos (m + n)"
  "Neg m - Pos n = Neg (m + n)"
  "Neg m - Neg n = sub n m"
  by (transfer, simp)+

lemma abs_integer_code [code]:
  "\<bar>k\<bar> = (if (k::integer) < 0 then - k else k)"
  by simp

lemma sgn_integer_code [code]:
  "sgn k = (if k = 0 then 0 else if (k::integer) < 0 then - 1 else 1)"
  by simp

lemma times_integer_code [code]:
  "k * 0 = (0::integer)"
  "0 * l = (0::integer)"
  "Pos m * Pos n = Pos (m * n)"
  "Pos m * Neg n = Neg (m * n)"
  "Neg m * Pos n = Neg (m * n)"
  "Neg m * Neg n = Pos (m * n)"
  by simp_all

definition divmod_integer :: "integer \<Rightarrow> integer \<Rightarrow> integer \<times> integer"
where
  "divmod_integer k l = (k div l, k mod l)"

lemma fst_divmod_integer [simp]:
  "fst (divmod_integer k l) = k div l"
  by (simp add: divmod_integer_def)

lemma snd_divmod_integer [simp]:
  "snd (divmod_integer k l) = k mod l"
  by (simp add: divmod_integer_def)

definition divmod_abs :: "integer \<Rightarrow> integer \<Rightarrow> integer \<times> integer"
where
  "divmod_abs k l = (\<bar>k\<bar> div \<bar>l\<bar>, \<bar>k\<bar> mod \<bar>l\<bar>)"

lemma fst_divmod_abs [simp]:
  "fst (divmod_abs k l) = \<bar>k\<bar> div \<bar>l\<bar>"
  by (simp add: divmod_abs_def)

lemma snd_divmod_abs [simp]:
  "snd (divmod_abs k l) = \<bar>k\<bar> mod \<bar>l\<bar>"
  by (simp add: divmod_abs_def)

lemma divmod_abs_code [code]:
  "divmod_abs (Pos k) (Pos l) = divmod k l"
  "divmod_abs (Neg k) (Neg l) = divmod k l"
  "divmod_abs (Neg k) (Pos l) = divmod k l"
  "divmod_abs (Pos k) (Neg l) = divmod k l"
  "divmod_abs j 0 = (0, \<bar>j\<bar>)"
  "divmod_abs 0 j = (0, 0)"
  by (simp_all add: prod_eq_iff)

lemma divmod_integer_eq_cases:
  "divmod_integer k l =
    (if k = 0 then (0, 0) else if l = 0 then (0, k) else
    (apsnd \<circ> times \<circ> sgn) l (if sgn k = sgn l
      then divmod_abs k l
      else (let (r, s) = divmod_abs k l in
        if s = 0 then (- r, 0) else (- r - 1, \<bar>l\<bar> - s))))"
proof -
  have *: "sgn k = sgn l \<longleftrightarrow> k = 0 \<and> l = 0 \<or> 0 < l \<and> 0 < k \<or> l < 0 \<and> k < 0" for k l :: int
    by (auto simp add: sgn_if)
  have **: "- k = l * q \<longleftrightarrow> k = - (l * q)" for k l q :: int
    by auto
  show ?thesis
    by (simp add: divmod_integer_def divmod_abs_def)
      (transfer, auto simp add: * ** not_less zdiv_zminus1_eq_if zmod_zminus1_eq_if div_minus_right mod_minus_right)
qed

lemma divmod_integer_code [code]: \<^marker>\<open>contributor \<open>René Thiemann\<close>\<close> \<^marker>\<open>contributor \<open>Akihisa Yamada\<close>\<close>
  "divmod_integer k l =
   (if k = 0 then (0, 0)
    else if l > 0 then
            (if k > 0 then Code_Numeral.divmod_abs k l
             else case Code_Numeral.divmod_abs k l of (r, s) \<Rightarrow>
                  if s = 0 then (- r, 0) else (- r - 1, l - s))
    else if l = 0 then (0, k)
    else apsnd uminus
            (if k < 0 then Code_Numeral.divmod_abs k l
             else case Code_Numeral.divmod_abs k l of (r, s) \<Rightarrow>
                  if s = 0 then (- r, 0) else (- r - 1, - l - s)))"
  by (cases l "0 :: integer" rule: linorder_cases)
    (auto split: prod.splits simp add: divmod_integer_eq_cases)

lemma div_integer_code [code]:
  "k div l = fst (divmod_integer k l)"
  by simp

lemma mod_integer_code [code]:
  "k mod l = snd (divmod_integer k l)"
  by simp

definition bit_cut_integer :: "integer \<Rightarrow> integer \<times> bool"
  where "bit_cut_integer k = (k div 2, odd k)"

lemma bit_cut_integer_code [code]:
  "bit_cut_integer k = (if k = 0 then (0, False)
     else let (r, s) = Code_Numeral.divmod_abs k 2
       in (if k > 0 then r else - r - s, s = 1))"
proof -
  have "bit_cut_integer k = (let (r, s) = divmod_integer k 2 in (r, s = 1))"
    by (simp add: divmod_integer_def bit_cut_integer_def odd_iff_mod_2_eq_one)
  then show ?thesis
    by (simp add: divmod_integer_code) (auto simp add: split_def)
qed

lemma equal_integer_code [code]:
  "HOL.equal 0 (0::integer) \<longleftrightarrow> True"
  "HOL.equal 0 (Pos l) \<longleftrightarrow> False"
  "HOL.equal 0 (Neg l) \<longleftrightarrow> False"
  "HOL.equal (Pos k) 0 \<longleftrightarrow> False"
  "HOL.equal (Pos k) (Pos l) \<longleftrightarrow> HOL.equal k l"
  "HOL.equal (Pos k) (Neg l) \<longleftrightarrow> False"
  "HOL.equal (Neg k) 0 \<longleftrightarrow> False"
  "HOL.equal (Neg k) (Pos l) \<longleftrightarrow> False"
  "HOL.equal (Neg k) (Neg l) \<longleftrightarrow> HOL.equal k l"
  by (simp_all add: equal)

lemma equal_integer_refl [code nbe]:
  "HOL.equal (k::integer) k \<longleftrightarrow> True"
  by (fact equal_refl)

lemma less_eq_integer_code [code]:
  "0 \<le> (0::integer) \<longleftrightarrow> True"
  "0 \<le> Pos l \<longleftrightarrow> True"
  "0 \<le> Neg l \<longleftrightarrow> False"
  "Pos k \<le> 0 \<longleftrightarrow> False"
  "Pos k \<le> Pos l \<longleftrightarrow> k \<le> l"
  "Pos k \<le> Neg l \<longleftrightarrow> False"
  "Neg k \<le> 0 \<longleftrightarrow> True"
  "Neg k \<le> Pos l \<longleftrightarrow> True"
  "Neg k \<le> Neg l \<longleftrightarrow> l \<le> k"
  by simp_all

lemma less_integer_code [code]:
  "0 < (0::integer) \<longleftrightarrow> False"
  "0 < Pos l \<longleftrightarrow> True"
  "0 < Neg l \<longleftrightarrow> False"
  "Pos k < 0 \<longleftrightarrow> False"
  "Pos k < Pos l \<longleftrightarrow> k < l"
  "Pos k < Neg l \<longleftrightarrow> False"
  "Neg k < 0 \<longleftrightarrow> True"
  "Neg k < Pos l \<longleftrightarrow> True"
  "Neg k < Neg l \<longleftrightarrow> l < k"
  by simp_all

lift_definition num_of_integer :: "integer \<Rightarrow> num"
  is "num_of_nat \<circ> nat"
  .

lemma num_of_integer_code [code]:
  "num_of_integer k = (if k \<le> 1 then Num.One
     else let
       (l, j) = divmod_integer k 2;
       l' = num_of_integer l;
       l'' = l' + l'
     in if j = 0 then l'' else l'' + Num.One)"
proof -
  {
    assume "int_of_integer k mod 2 = 1"
    then have "nat (int_of_integer k mod 2) = nat 1" by simp
    moreover assume *: "1 < int_of_integer k"
    ultimately have **: "nat (int_of_integer k) mod 2 = 1" by (simp add: nat_mod_distrib)
    have "num_of_nat (nat (int_of_integer k)) =
      num_of_nat (2 * (nat (int_of_integer k) div 2) + nat (int_of_integer k) mod 2)"
      by simp
    then have "num_of_nat (nat (int_of_integer k)) =
      num_of_nat (nat (int_of_integer k) div 2 + nat (int_of_integer k) div 2 + nat (int_of_integer k) mod 2)"
      by (simp add: mult_2)
    with ** have "num_of_nat (nat (int_of_integer k)) =
      num_of_nat (nat (int_of_integer k) div 2 + nat (int_of_integer k) div 2 + 1)"
      by simp
  }
  note aux = this
  show ?thesis
    by (auto simp add: num_of_integer_def nat_of_integer_def Let_def case_prod_beta
      not_le integer_eq_iff less_eq_integer_def
      nat_mult_distrib nat_div_distrib num_of_nat_One num_of_nat_plus_distrib
       mult_2 [where 'a=nat] aux add_One)
qed

lemma nat_of_integer_code [code]:
  "nat_of_integer k = (if k \<le> 0 then 0
     else let
       (l, j) = divmod_integer k 2;
       l' = nat_of_integer l;
       l'' = l' + l'
     in if j = 0 then l'' else l'' + 1)"
proof -
  obtain j where k: "k = integer_of_int j"
  proof
    show "k = integer_of_int (int_of_integer k)" by simp
  qed
  have *: "nat j mod 2 = nat_of_integer (of_int j mod 2)" if "j \<ge> 0"
    using that by transfer (simp add: nat_mod_distrib)
  from k show ?thesis
    by (auto simp add: split_def Let_def nat_of_integer_def nat_div_distrib mult_2 [symmetric]
      minus_mod_eq_mult_div [symmetric] *)
qed

lemma int_of_integer_code [code]:
  "int_of_integer k = (if k < 0 then - (int_of_integer (- k))
     else if k = 0 then 0
     else let
       (l, j) = divmod_integer k 2;
       l' = 2 * int_of_integer l
     in if j = 0 then l' else l' + 1)"
  by (auto simp add: split_def Let_def integer_eq_iff minus_mod_eq_mult_div [symmetric])

lemma integer_of_int_code [code]:
  "integer_of_int k = (if k < 0 then - (integer_of_int (- k))
     else if k = 0 then 0
     else let
       l = 2 * integer_of_int (k div 2);
       j = k mod 2
     in if j = 0 then l else l + 1)"
  by (auto simp add: split_def Let_def integer_eq_iff minus_mod_eq_mult_div [symmetric])

hide_const (open) Pos Neg sub dup divmod_abs

subsection \<open>Serializer setup for target language integers\<close>

code_reserved Eval int Integer abs

code_printing
  type_constructor integer \<rightharpoonup>
    (SML) "IntInf.int"
    and (OCaml) "Z.t"
    and (Haskell) "Integer"
    and (Scala) "BigInt"
    and (Eval) "int"
| class_instance integer :: equal \<rightharpoonup>
    (Haskell) -

code_printing
  constant "0::integer" \<rightharpoonup>
    (SML) "!(0/ :/ IntInf.int)"
    and (OCaml) "Z.zero"
    and (Haskell) "!(0/ ::/ Integer)"
    and (Scala) "BigInt(0)"

setup \<open>
  fold (fn target =>
    Numeral.add_code \<^const_name>\<open>Code_Numeral.Pos\<close> I Code_Printer.literal_numeral target
    #> Numeral.add_code \<^const_name>\<open>Code_Numeral.Neg\<close> (~) Code_Printer.literal_numeral target)
    ["SML", "OCaml", "Haskell", "Scala"]
\<close>

code_printing
  constant "plus :: integer \<Rightarrow> _ \<Rightarrow> _" \<rightharpoonup>
    (SML) "IntInf.+ ((_), (_))"
    and (OCaml) "Z.add"
    and (Haskell) infixl 6 "+"
    and (Scala) infixl 7 "+"
    and (Eval) infixl 8 "+"
| constant "uminus :: integer \<Rightarrow> _" \<rightharpoonup>
    (SML) "IntInf.~"
    and (OCaml) "Z.neg"
    and (Haskell) "negate"
    and (Scala) "!(- _)"
    and (Eval) "~/ _"
| constant "minus :: integer \<Rightarrow> _" \<rightharpoonup>
    (SML) "IntInf.- ((_), (_))"
    and (OCaml) "Z.sub"
    and (Haskell) infixl 6 "-"
    and (Scala) infixl 7 "-"
    and (Eval) infixl 8 "-"
| constant Code_Numeral.dup \<rightharpoonup>
    (SML) "IntInf.*/ (2,/ (_))"
    and (OCaml) "Z.shift'_left/ _/ 1"
    and (Haskell) "!(2 * _)"
    and (Scala) "!(2 * _)"
    and (Eval) "!(2 * _)"
| constant Code_Numeral.sub \<rightharpoonup>
    (SML) "!(raise/ Fail/ \"sub\")"
    and (OCaml) "failwith/ \"sub\""
    and (Haskell) "error/ \"sub\""
    and (Scala) "!sys.error(\"sub\")"
| constant "times :: integer \<Rightarrow> _ \<Rightarrow> _" \<rightharpoonup>
    (SML) "IntInf.* ((_), (_))"
    and (OCaml) "Z.mul"
    and (Haskell) infixl 7 "*"
    and (Scala) infixl 8 "*"
    and (Eval) infixl 9 "*"
| constant Code_Numeral.divmod_abs \<rightharpoonup>
    (SML) "IntInf.divMod/ (IntInf.abs _,/ IntInf.abs _)"
    and (OCaml) "!(fun k l ->/ if Z.equal Z.zero l then/ (Z.zero, l) else/ Z.div'_rem/ (Z.abs k)/ (Z.abs l))"
    and (Haskell) "divMod/ (abs _)/ (abs _)"
    and (Scala) "!((k: BigInt) => (l: BigInt) =>/ if (l == 0)/ (BigInt(0), k) else/ (k.abs '/% l.abs))"
    and (Eval) "Integer.div'_mod/ (abs _)/ (abs _)"
| constant "HOL.equal :: integer \<Rightarrow> _ \<Rightarrow> bool" \<rightharpoonup>
    (SML) "!((_ : IntInf.int) = _)"
    and (OCaml) "Z.equal"
    and (Haskell) infix 4 "=="
    and (Scala) infixl 5 "=="
    and (Eval) infixl 6 "="
| constant "less_eq :: integer \<Rightarrow> _ \<Rightarrow> bool" \<rightharpoonup>
    (SML) "IntInf.<= ((_), (_))"
    and (OCaml) "Z.leq"
    and (Haskell) infix 4 "<="
    and (Scala) infixl 4 "<="
    and (Eval) infixl 6 "<="
| constant "less :: integer \<Rightarrow> _ \<Rightarrow> bool" \<rightharpoonup>
    (SML) "IntInf.< ((_), (_))"
    and (OCaml) "Z.lt"
    and (Haskell) infix 4 "<"
    and (Scala) infixl 4 "<"
    and (Eval) infixl 6 "<"
| constant "abs :: integer \<Rightarrow> _" \<rightharpoonup>
    (SML) "IntInf.abs"
    and (OCaml) "Z.abs"
    and (Haskell) "Prelude.abs"
    and (Scala) "_.abs"
    and (Eval) "abs"

code_identifier
  code_module Code_Numeral \<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith

subsection \<open>Type of target language naturals\<close>

typedef natural = "UNIV :: nat set"
  morphisms nat_of_natural natural_of_nat ..

setup_lifting type_definition_natural

lemma natural_eq_iff [termination_simp]:
  "m = n \<longleftrightarrow> nat_of_natural m = nat_of_natural n"
  by transfer rule

lemma natural_eqI:
  "nat_of_natural m = nat_of_natural n \<Longrightarrow> m = n"
  using natural_eq_iff [of m n] by simp

lemma nat_of_natural_of_nat_inverse [simp]:
  "nat_of_natural (natural_of_nat n) = n"
  by transfer rule

lemma natural_of_nat_of_natural_inverse [simp]:
  "natural_of_nat (nat_of_natural n) = n"
  by transfer rule

instantiation natural :: "{comm_monoid_diff, semiring_1}"
begin

lift_definition zero_natural :: natural
  is "0 :: nat"
  .

declare zero_natural.rep_eq [simp]

lift_definition one_natural :: natural
  is "1 :: nat"
  .

declare one_natural.rep_eq [simp]

lift_definition plus_natural :: "natural \<Rightarrow> natural \<Rightarrow> natural"
  is "plus :: nat \<Rightarrow> nat \<Rightarrow> nat"
  .

declare plus_natural.rep_eq [simp]

lift_definition minus_natural :: "natural \<Rightarrow> natural \<Rightarrow> natural"
  is "minus :: nat \<Rightarrow> nat \<Rightarrow> nat"
  .

declare minus_natural.rep_eq [simp]

lift_definition times_natural :: "natural \<Rightarrow> natural \<Rightarrow> natural"
  is "times :: nat \<Rightarrow> nat \<Rightarrow> nat"
  .

declare times_natural.rep_eq [simp]

instance proof
qed (transfer, simp add: algebra_simps)+

end

instance natural :: Rings.dvd ..

context
  includes lifting_syntax
begin

lemma [transfer_rule]:
  \<open>(pcr_natural ===> pcr_natural ===> (\<longleftrightarrow>)) (dvd) (dvd)\<close>
  by (unfold dvd_def) transfer_prover

lemma [transfer_rule]:
  \<open>((\<longleftrightarrow>) ===> pcr_natural) of_bool of_bool\<close>
  by (unfold of_bool_def) transfer_prover

lemma [transfer_rule]:
  \<open>((=) ===> pcr_natural) (\<lambda>n. n) of_nat\<close>
proof -
  have "rel_fun HOL.eq pcr_natural (of_nat :: nat \<Rightarrow> nat) (of_nat :: nat \<Rightarrow> natural)"
    by (unfold of_nat_def) transfer_prover
  then show ?thesis by (simp add: id_def)
qed

lemma [transfer_rule]:
  \<open>((=) ===> pcr_natural) numeral numeral\<close>
proof -
  have \<open>((=) ===> pcr_natural) numeral (\<lambda>n. of_nat (numeral n))\<close>
    by transfer_prover
  then show ?thesis by simp
qed

lemma [transfer_rule]:
  \<open>(pcr_natural ===> (=) ===> pcr_natural) (^) (^)\<close>
  by (unfold power_def) transfer_prover

end

lemma nat_of_natural_of_nat [simp]:
  "nat_of_natural (of_nat n) = n"
  by transfer rule

lemma natural_of_nat_of_nat [simp, code_abbrev]:
  "natural_of_nat = of_nat"
  by transfer rule

lemma of_nat_of_natural [simp]:
  "of_nat (nat_of_natural n) = n"
  by transfer rule

lemma nat_of_natural_numeral [simp]:
  "nat_of_natural (numeral k) = numeral k"
  by transfer rule

instantiation natural :: "{linordered_semiring, equal}"
begin

lift_definition less_eq_natural :: "natural \<Rightarrow> natural \<Rightarrow> bool"
  is "less_eq :: nat \<Rightarrow> nat \<Rightarrow> bool"
  .

declare less_eq_natural.rep_eq [termination_simp]

lift_definition less_natural :: "natural \<Rightarrow> natural \<Rightarrow> bool"
  is "less :: nat \<Rightarrow> nat \<Rightarrow> bool"
  .

declare less_natural.rep_eq [termination_simp]

lift_definition equal_natural :: "natural \<Rightarrow> natural \<Rightarrow> bool"
  is "HOL.equal :: nat \<Rightarrow> nat \<Rightarrow> bool"
  .

instance proof
qed (transfer, simp add: algebra_simps equal less_le_not_le [symmetric] linear)+

end

context
  includes lifting_syntax
begin

lemma [transfer_rule]:
  \<open>(pcr_natural ===> pcr_natural ===> pcr_natural) min min\<close>
  by (unfold min_def) transfer_prover

lemma [transfer_rule]:
  \<open>(pcr_natural ===> pcr_natural ===> pcr_natural) max max\<close>
  by (unfold max_def) transfer_prover

end

lemma nat_of_natural_min [simp]:
  "nat_of_natural (min k l) = min (nat_of_natural k) (nat_of_natural l)"
  by transfer rule

lemma nat_of_natural_max [simp]:
  "nat_of_natural (max k l) = max (nat_of_natural k) (nat_of_natural l)"
  by transfer rule

instantiation natural :: unique_euclidean_semiring
begin

lift_definition divide_natural :: "natural \<Rightarrow> natural \<Rightarrow> natural"
  is "divide :: nat \<Rightarrow> nat \<Rightarrow> nat"
  .

declare divide_natural.rep_eq [simp]

lift_definition modulo_natural :: "natural \<Rightarrow> natural \<Rightarrow> natural"
  is "modulo :: nat \<Rightarrow> nat \<Rightarrow> nat"
  .

declare modulo_natural.rep_eq [simp]

lift_definition euclidean_size_natural :: "natural \<Rightarrow> nat"
  is "euclidean_size :: nat \<Rightarrow> nat"
  .

declare euclidean_size_natural.rep_eq [simp]

lift_definition division_segment_natural :: "natural \<Rightarrow> natural"
  is "division_segment :: nat \<Rightarrow> nat"
  .

declare division_segment_natural.rep_eq [simp]

instance
  by (standard; transfer)
    (auto simp add: algebra_simps unit_factor_nat_def gr0_conv_Suc)

end

lemma [code]:
  "euclidean_size = nat_of_natural"
  by (simp add: fun_eq_iff)

lemma [code]:
  "division_segment (n::natural) = 1"
  by (simp add: natural_eq_iff)

instance natural :: linordered_semidom
  by (standard; transfer) simp_all

instance natural :: unique_euclidean_semiring_with_nat
  by (standard; transfer) simp_all

instantiation natural :: semiring_bit_operations
begin

lift_definition bit_natural :: \<open>natural \<Rightarrow> nat \<Rightarrow> bool\<close>
  is bit .

lift_definition and_natural :: \<open>natural \<Rightarrow> natural \<Rightarrow> natural\<close>
  is \<open>and\<close> .

lift_definition or_natural :: \<open>natural \<Rightarrow> natural \<Rightarrow> natural\<close>
  is or .

lift_definition xor_natural ::  \<open>natural \<Rightarrow> natural \<Rightarrow> natural\<close>
  is xor .

lift_definition mask_natural :: \<open>nat \<Rightarrow> natural\<close>
  is mask .

lift_definition set_bit_natural :: \<open>nat \<Rightarrow> natural \<Rightarrow> natural\<close>
  is set_bit .

lift_definition unset_bit_natural :: \<open>nat \<Rightarrow> natural \<Rightarrow> natural\<close>
  is unset_bit .

lift_definition flip_bit_natural :: \<open>nat \<Rightarrow> natural \<Rightarrow> natural\<close>
  is flip_bit .

lift_definition push_bit_natural :: \<open>nat \<Rightarrow> natural \<Rightarrow> natural\<close>
  is push_bit .

lift_definition drop_bit_natural :: \<open>nat \<Rightarrow> natural \<Rightarrow> natural\<close>
  is drop_bit .

lift_definition take_bit_natural :: \<open>nat \<Rightarrow> natural \<Rightarrow> natural\<close>
  is take_bit .

instance by (standard; transfer)
  (fact bit_eq_rec bits_induct bit_iff_odd push_bit_eq_mult drop_bit_eq_div take_bit_eq_mod
    bits_div_0 bits_div_by_1 bits_mod_div_trivial even_succ_div_2
    exp_div_exp_eq div_exp_eq mod_exp_eq mult_exp_mod_exp_eq div_exp_mod_exp_eq
    even_mask_div_iff even_mult_exp_div_exp_iff bit_and_iff bit_or_iff bit_xor_iff
    mask_eq_exp_minus_1 set_bit_def bit_unset_bit_iff flip_bit_def)+

end

instance natural :: unique_euclidean_semiring_with_bit_operations ..

context
  includes bit_operations_syntax
begin

lemma [code]:
  \<open>bit m n \<longleftrightarrow> odd (drop_bit n m)\<close>
  \<open>mask n = 2 ^ n - (1 :: integer)\<close>
  \<open>set_bit n m = m OR push_bit n 1\<close>
  \<open>flip_bit n m = m XOR push_bit n 1\<close>
  \<open>push_bit n m = m * 2 ^ n\<close>
  \<open>drop_bit n m = m div 2 ^ n\<close>
  \<open>take_bit n m = m mod 2 ^ n\<close> for m :: natural
  by (fact bit_iff_odd_drop_bit mask_eq_exp_minus_1
    set_bit_eq_or flip_bit_eq_xor push_bit_eq_mult drop_bit_eq_div take_bit_eq_mod)+

lemma [code]:
  \<open>m AND n = (if m = 0 \<or> n = 0 then 0
    else (m mod 2) * (n mod 2) + 2 * ((m div 2) AND (n div 2)))\<close> for m n :: natural
  by transfer (fact and_nat_unfold)

lemma [code]:
  \<open>m OR n = (if m = 0 then n else if n = 0 then m
    else max (m mod 2) (n mod 2) + 2 * ((m div 2) OR (n div 2)))\<close> for m n :: natural
  by transfer (fact or_nat_unfold)

lemma [code]:
  \<open>m XOR n = (if m = 0 then n else if n = 0 then m
    else (m mod 2 + n mod 2) mod 2 + 2 * ((m div 2) XOR (n div 2)))\<close> for m n :: natural
  by transfer (fact xor_nat_unfold)

lemma [code]:
  \<open>unset_bit 0 m = 2 * (m div 2)\<close>
  \<open>unset_bit (Suc n) m = m mod 2 + 2 * unset_bit n (m div 2)\<close> for m :: natural
  by (transfer; simp add: unset_bit_Suc)+

end

lift_definition natural_of_integer :: "integer \<Rightarrow> natural"
  is "nat :: int \<Rightarrow> nat"
  .

lift_definition integer_of_natural :: "natural \<Rightarrow> integer"
  is "of_nat :: nat \<Rightarrow> int"
  .

lemma natural_of_integer_of_natural [simp]:
  "natural_of_integer (integer_of_natural n) = n"
  by transfer simp

lemma integer_of_natural_of_integer [simp]:
  "integer_of_natural (natural_of_integer k) = max 0 k"
  by transfer auto

lemma int_of_integer_of_natural [simp]:
  "int_of_integer (integer_of_natural n) = of_nat (nat_of_natural n)"
  by transfer rule

lemma integer_of_natural_of_nat [simp]:
  "integer_of_natural (of_nat n) = of_nat n"
  by transfer rule

lemma [measure_function]:
  "is_measure nat_of_natural"
  by (rule is_measure_trivial)

subsection \<open>Inductive representation of target language naturals\<close>

lift_definition Suc :: "natural \<Rightarrow> natural"
  is Nat.Suc
  .

declare Suc.rep_eq [simp]

old_rep_datatype "0::natural" Suc
  by (transfer, fact nat.induct nat.inject nat.distinct)+

lemma natural_cases [case_names nat, cases type: natural]:
  fixes m :: natural
  assumes "\<And>n. m = of_nat n \<Longrightarrow> P"
  shows P
  using assms by transfer blast

instantiation natural :: size
begin

definition size_nat where [simp, code]: "size_nat = nat_of_natural"

instance ..

end

lemma natural_decr [termination_simp]:
  "n \<noteq> 0 \<Longrightarrow> nat_of_natural n - Nat.Suc 0 < nat_of_natural n"
  by transfer simp

lemma natural_zero_minus_one: "(0::natural) - 1 = 0"
  by (rule zero_diff)

lemma Suc_natural_minus_one: "Suc n - 1 = n"
  by transfer simp

hide_const (open) Suc

subsection \<open>Code refinement for target language naturals\<close>

lift_definition Nat :: "integer \<Rightarrow> natural"
  is nat
  .

lemma [code_post]:
  "Nat 0 = 0"
  "Nat 1 = 1"
  "Nat (numeral k) = numeral k"
  by (transfer, simp)+

lemma [code abstype]:
  "Nat (integer_of_natural n) = n"
  by transfer simp

lemma [code]:
  "natural_of_nat n = natural_of_integer (integer_of_nat n)"
  by transfer simp

lemma [code abstract]:
  "integer_of_natural (natural_of_integer k) = max 0 k"
  by simp

lemma [code]:
  \<open>integer_of_natural (mask n) = mask n\<close>
  by transfer (simp add: mask_eq_exp_minus_1 of_nat_diff)

lemma [code_abbrev]:
  "natural_of_integer (Code_Numeral.Pos k) = numeral k"
  by transfer simp

lemma [code abstract]:
  "integer_of_natural 0 = 0"
  by transfer simp

lemma [code abstract]:
  "integer_of_natural 1 = 1"
  by transfer simp

lemma [code abstract]:
  "integer_of_natural (Code_Numeral.Suc n) = integer_of_natural n + 1"
  by transfer simp

lemma [code]:
  "nat_of_natural = nat_of_integer \<circ> integer_of_natural"
  by transfer (simp add: fun_eq_iff)

lemma [code, code_unfold]:
  "case_natural f g n = (if n = 0 then f else g (n - 1))"
  by (cases n rule: natural.exhaust) (simp_all, simp add: Suc_def)

declare natural.rec [code del]

lemma [code abstract]:
  "integer_of_natural (m + n) = integer_of_natural m + integer_of_natural n"
  by transfer simp

lemma [code abstract]:
  "integer_of_natural (m - n) = max 0 (integer_of_natural m - integer_of_natural n)"
  by transfer simp

lemma [code abstract]:
  "integer_of_natural (m * n) = integer_of_natural m * integer_of_natural n"
  by transfer simp

lemma [code abstract]:
  "integer_of_natural (m div n) = integer_of_natural m div integer_of_natural n"
  by transfer (simp add: zdiv_int)

lemma [code abstract]:
  "integer_of_natural (m mod n) = integer_of_natural m mod integer_of_natural n"
  by transfer (simp add: zmod_int)

lemma [code]:
  "HOL.equal m n \<longleftrightarrow> HOL.equal (integer_of_natural m) (integer_of_natural n)"
  by transfer (simp add: equal)

lemma [code nbe]: "HOL.equal n (n::natural) \<longleftrightarrow> True"
  by (rule equal_class.equal_refl)

lemma [code]: "m \<le> n \<longleftrightarrow> integer_of_natural m \<le> integer_of_natural n"
  by transfer simp

lemma [code]: "m < n \<longleftrightarrow> integer_of_natural m < integer_of_natural n"
  by transfer simp

hide_const (open) Nat

code_reflect Code_Numeral
  datatypes natural
  functions "Code_Numeral.Suc" "0 :: natural" "1 :: natural"
    "plus :: natural \<Rightarrow> _" "minus :: natural \<Rightarrow> _"
    "times :: natural \<Rightarrow> _" "divide :: natural \<Rightarrow> _"
    "modulo :: natural \<Rightarrow> _"
    integer_of_natural natural_of_integer

lifting_update integer.lifting
lifting_forget integer.lifting

lifting_update natural.lifting
lifting_forget natural.lifting

end


theory prop_34
imports Main
        "$HIPSTER_HOME/IsaHipster"
begin
  datatype Nat = Z | S "Nat"
  fun plus :: "Nat => Nat => Nat" where
  "plus (Z) y = y"
  | "plus (S z) y = S (plus z y)"
  fun mult :: "Nat => Nat => Nat" where
  "mult (Z) y = Z"
  | "mult (S z) y = plus y (mult z y)"
  fun mult2 :: "Nat => Nat => Nat => Nat" where
  "mult2 (Z) y z = z"
  | "mult2 (S x2) y z = mult2 x2 y (plus y z)"
  (*hipster plus mult2 mult *)

(*hipster plus*)
lemma lemma_a [thy_expl]: "plus x2 Z = x2"
by (hipster_induct_schemes plus.simps)

lemma lemma_aa [thy_expl]: "plus (plus x2 y2) z2 = plus x2 (plus y2 z2)"
by (hipster_induct_schemes plus.simps)

lemma lemma_ab [thy_expl]: "plus x2 (S y2) = S (plus x2 y2)"
by (hipster_induct_schemes plus.simps)

lemma lemma_ac [thy_expl]: "plus x1 (plus y1 x1) = plus y1 (plus x1 x1)"
by (hipster_induct_schemes plus.simps)

lemma lemma_ad [thy_expl]: "plus x2 (plus y2 y2) = plus y2 (plus y2 x2)"
by (hipster_induct_schemes plus.simps)

lemma lemma_ae [thy_expl]: "plus x2 (S y2) = S (plus y2 x2)"
by (hipster_induct_schemes plus.simps)

lemma lemma_af [thy_expl]: "plus (S x2) y2 = S (plus y2 x2)"
by (hipster_induct_schemes plus.simps)

lemma lemma_ag [thy_expl]: "plus (plus x2 y2) (plus x2 z2) = plus (plus x2 z2) (plus x2 y2)"
by (hipster_induct_schemes plus.simps)

lemma lemma_ah [thy_expl]: "plus (plus x2 y2) (plus z2 x2) = plus (plus z2 x2) (plus x2 y2)"
by (hipster_induct_schemes plus.simps)

lemma lemma_ai [thy_expl]: "plus x2 (plus y2 z2) = plus y2 (plus z2 x2)"
by (hipster_induct_schemes plus.simps)

hipster mult plus
lemma lemma_aj [thy_expl]: "mult x2 Z = Z"
by (hipster_induct_schemes mult.simps plus.simps)

lemma lemma_ak [thy_expl]: "mult (plus x9 x9) y9 = mult x9 (plus y9 y9)"
by (hipster_induct_schemes mult.simps plus.simps)

lemma lemma_al [thy_expl]: "plus (mult x9 y9) (mult x9 z9) = mult x9 (plus y9 z9)"
by (hipster_induct_schemes mult.simps plus.simps)

lemma lemma_am [thy_expl]: "plus (mult x10 x10) (mult y10 y10) = plus (mult y10 y10) (mult x10 x10)"
by (hipster_induct_schemes mult.simps plus.simps)

lemma lemma_an [thy_expl]: "mult x2 (S Z) = x2"
by (hipster_induct_schemes mult.simps plus.simps)

lemma lemma_ao [thy_expl]: "mult (mult x10 x10) (plus x10 x10) = mult (plus x10 x10) (mult x10 x10)"
by (hipster_induct_schemes mult.simps plus.simps)

lemma lemma_ap [thy_expl]: "mult (S x10) (plus x10 x10) = mult (plus x10 x10) (S x10)"
by (hipster_induct_schemes mult.simps plus.simps)

lemma lemma_aq [thy_expl]: "mult x10 y10 = mult y10 x10"
by (hipster_induct_schemes mult.simps plus.simps)

lemma lemma_ar [thy_expl]: "mult x10 (mult y10 z10) = mult y10 (mult x10 z10)"
by (hipster_induct_schemes mult.simps plus.simps)

lemma lemma_as [thy_expl]: "mult (plus x9 x9) (mult y9 y9) = mult (mult y9 x9) (plus y9 y9)"
by (hipster_induct_schemes mult.simps plus.simps)

  theorem x0 :
    "(mult x y) = (mult2 x y Z)"
    apply(hipster_induct_schemes mult.simps mult2.simps Nat.exhaust)
    by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>)
end


(*  Title:       Preliminaries for hybrid systems verification
    Maintainer:  Jonathan Julián Huerta y Munive <jonjulian23@gmail.com>
*)

section \<open> Hybrid Systems Preliminaries \<close>

text \<open>Hybrid systems combine continuous dynamics with discrete control. This section contains
auxiliary lemmas for verification of hybrid systems.\<close>

theory HS_Preliminaries
  imports
    "Ordinary_Differential_Equations.Picard_Lindeloef_Qualitative"
    "Hybrid-Library.Matrix_Syntax"
begin

subsection \<open> Notation \<close>

bundle derivative_notation
begin

no_notation has_vderiv_on (infix "(has'_vderiv'_on)" 50)

notation has_derivative ("(1(D _ \<mapsto> (_))/ _)" [65,65] 61)
     and has_vderiv_on ("(1 D _ = (_)/ on _)" [65,65] 61)

end

bundle derivative_no_notation
begin

notation has_vderiv_on (infix "(has'_vderiv'_on)" 50)

no_notation has_derivative ("(1(D _ \<mapsto> (_))/ _)" [65,65] 61)
     and has_vderiv_on ("(1 D _ = (_)/ on _)" [65,65] 61)

end

text \<open>Special syntax for cubes, power to the 4th and 5th. \<close>
abbreviation power3 :: "'a::power \<Rightarrow> 'a"  ("(_\<^sup>3)" [1000] 999)
  where "x\<^sup>3 \<equiv> x ^ 3"

abbreviation power4 :: "'a::power \<Rightarrow> 'a"  ("(_\<^sup>4)" [1000] 999)
  where "x\<^sup>4 \<equiv> x ^ 4"

abbreviation power5 :: "'a::power \<Rightarrow> 'a"  ("(_\<^sup>5)" [1000] 999)
  where "x\<^sup>5 \<equiv> x ^ 5"

bundle power_notation
begin

notation power2 ("(_\<^sup>2)" [1000] 999)
  and power3 ("(_\<^sup>3)" [1000] 999)
  and power4 ("(_\<^sup>4)" [1000] 999)
  and power5 ("(_\<^sup>5)" [1000] 999)

end

bundle power_no_notation
begin

no_notation power2 ("(_\<^sup>2)" [1000] 999)
  and power3 ("(_\<^sup>3)" [1000] 999)
  and power4 ("(_\<^sup>4)" [1000] 999)
  and power5 ("(_\<^sup>5)" [1000] 999)

end

unbundle power_no_notation
unbundle derivative_notation
unbundle power_notation \<comment> \<open> enable notation \<close>

lemma nat_wf_induct[case_names zero induct]:
  assumes "P 0"
    and "(\<And>n. (\<And>m. m \<le> n \<Longrightarrow> P m) \<Longrightarrow> P (Suc n))"
  shows "P n"
  using assms
  apply (induct n rule: full_nat_induct)
  by simp (metis Suc_le_mono not0_implies_Suc)

subsection \<open> Real vector arithmetic \<close>

definition vec_upd :: "('a^'b) \<Rightarrow> 'b \<Rightarrow> 'a \<Rightarrow> 'a^'b"
  where "vec_upd s i a = (\<chi> j. ((($) s)(i := a)) j)"

lemma vec_upd_eq: "vec_upd s i a = (\<chi> j. if j = i then a else s$j)"
  by (simp add: vec_upd_def)

lemma nonneg_real_within_Suc: "r \<ge> 0 \<Longrightarrow> \<exists>n. Suc n > r \<and> r \<ge> n" for r::real
  by (metis Groups.add_ac(2) Suc_n_not_le_n Suc_neq_Zero
      less_add_one less_le_not_le linorder_le_cases linorder_not_less
      nat.inject nat_ceiling_le_eq of_nat_0_less_iff of_nat_Suc
      old.nat.exhaust order_less_le_trans real_nat_ceiling_ge)

lemma pos_real_within_Suc: "r > 0 \<Longrightarrow> \<exists>n. Suc n \<ge> r \<and> r > n" for r::real
  by (metis gr0_implies_Suc lessI of_nat_0_less_iff of_nat_less_iff
      order_le_less nonneg_real_within_Suc)

lemma abs_le_eq:
  shows "(r::real) > 0 \<Longrightarrow> (\<bar>x\<bar> < r) = (-r < x \<and> x < r)"
    and "(r::real) > 0 \<Longrightarrow> (\<bar>x\<bar> \<le> r) = (-r \<le> x \<and> x \<le> r)"
  by linarith+

lemma real_ivl_eqs:
  assumes "0 < r"
  shows "ball x r = {x-r<--< x+r}"         and "{x-r<--< x+r} = {x-r<..< x+r}"
    and "ball (r / 2) (r / 2) = {0<--<r}"  and "{0<--<r} = {0<..<r}"
    and "ball 0 r = {-r<--<r}"             and "{-r<--<r} = {-r<..<r}"
    and "cball x r = {x-r--x+r}"           and "{x-r--x+r} = {x-r..x+r}"
    and "cball (r / 2) (r / 2) = {0--r}"   and "{0--r} = {0..r}"
    and "cball 0 r = {-r--r}"              and "{-r--r} = {-r..r}"
  unfolding open_segment_eq_real_ivl closed_segment_eq_real_ivl
  using assms by (auto simp: cball_def ball_def dist_norm field_simps)

lemma is_interval_real_nonneg[simp]: "is_interval (Collect ((\<le>) (0::real)))"
  by (auto simp: is_interval_def)

lemma open_real_segment: "open {a<--<b}" for a::real
  unfolding open_segment_eq_real_ivl by auto

lemma norm_rotate_eq[simp]:
  fixes x :: "'a:: {banach,real_normed_field}"
  shows "(x * cos t - y * sin t)\<^sup>2 + (x * sin t + y * cos t)\<^sup>2 = x\<^sup>2 + y\<^sup>2"
    and "(x * cos t + y * sin t)\<^sup>2 + (y * cos t - x * sin t)\<^sup>2 = x\<^sup>2 + y\<^sup>2"
proof-
  have "(x * cos t - y * sin t)\<^sup>2 = x\<^sup>2 * (cos t)\<^sup>2 + y\<^sup>2 * (sin t)\<^sup>2 - 2 * (x * cos t) * (y * sin t)"
    by(simp add: power2_diff power_mult_distrib)
  also have "(x * sin t + y * cos t)\<^sup>2 = y\<^sup>2 * (cos t)\<^sup>2 + x\<^sup>2 * (sin t)\<^sup>2 + 2 * (x * cos t) * (y * sin t)"
    by(simp add: power2_sum power_mult_distrib)
  ultimately show "(x * cos t - y * sin t)\<^sup>2 + (x * sin t + y * cos t)\<^sup>2 = x\<^sup>2 + y\<^sup>2"
    by (simp add: Groups.mult_ac(2) Groups.mult_ac(3) right_diff_distrib sin_squared_eq)
  thus "(x * cos t + y * sin t)\<^sup>2 + (y * cos t - x * sin t)\<^sup>2 = x\<^sup>2 + y\<^sup>2"
    by (simp add: add.commute add.left_commute power2_diff power2_sum)
qed

lemma sum_eq_Sum:
  assumes "inj_on f A"
  shows "(\<Sum>x\<in>A. f x) = (\<Sum> {f x |x. x \<in> A})"
proof-
  have "(\<Sum> {f x |x. x \<in> A}) = (\<Sum> (f ` A))"
    apply(auto simp: image_def)
    by (rule_tac f=Sum in arg_cong, auto)
  also have "... = (\<Sum>x\<in>A. f x)"
    by (subst sum.image_eq[OF assms], simp)
  finally show "(\<Sum>x\<in>A. f x) = (\<Sum> {f x |x. x \<in> A})"
    by simp
qed

lemma triangle_norm_vec_le_sum: "\<parallel>x\<parallel> \<le> (\<Sum>i\<in>UNIV. \<parallel>x $ i\<parallel>)"
  by (simp add: L2_set_le_sum norm_vec_def)

subsection \<open> Single variable derivatives \<close>

lemma has_derivative_at_within_iff: "(D f \<mapsto> f' (at x within S))
  \<longleftrightarrow> bounded_linear f'
  \<and>  (\<forall>X. open X \<longrightarrow> 0 \<in> X \<longrightarrow> (\<exists>d>0. \<forall>s\<in>S. s \<noteq> x \<and> \<parallel>s - x\<parallel> < d
    \<longrightarrow> (f s - f x - f' (s - x)) /\<^sub>R \<parallel>s - x\<parallel> \<in> X))"
  unfolding has_derivative_at_within tendsto_def
    eventually_at dist_norm by simp

lemma has_vderiv_on_iff: "(D f = f' on T)
  \<longleftrightarrow> (\<forall>x\<in>T. D f \<mapsto> (\<lambda>h. h *\<^sub>R f' x) (at x within T))"
  unfolding has_vderiv_on_def has_vector_derivative_def by simp

named_theorems vderiv_intros "optimised compilation of derivative rules."

declare has_vderiv_on_const [vderiv_intros]
    and has_vderiv_on_id [vderiv_intros]
    and has_vderiv_on_add[THEN has_vderiv_on_eq_rhs, vderiv_intros]
    and has_vderiv_on_diff[THEN has_vderiv_on_eq_rhs, vderiv_intros]
    and has_vderiv_on_mult[THEN has_vderiv_on_eq_rhs, vderiv_intros]
    and has_vderiv_on_ln[vderiv_intros]

lemma vderiv_compI:
  fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::real_normed_vector"
  assumes dg: "D g = g' on T"
    and df: "\<forall>t\<in>T. D f \<mapsto> f' at (g t) within g ` T"
    and h_eq: "\<forall>t\<in>T. h t = f' (g' t)"
  shows "D (f \<circ> g) = h on T"
  using assms vector_derivative_diff_chain_within[of g _ _ T f f']
  unfolding has_vderiv_on_def by metis

lemma vderiv_composeI:
  assumes "D f = f' on g ` T"
    and " D g = g' on T"
    and "h = (\<lambda>t. g' t *\<^sub>R f' (g t))"
  shows "D (\<lambda>t. f (g t)) = h on T"
  apply (rule has_vderiv_on_compose[THEN has_vderiv_on_eq_rhs, unfolded comp_def])
  using assms by auto

lemma vderiv_uminusI[vderiv_intros]:
  "D f = f' on T \<Longrightarrow> g = (\<lambda>t. - f' t) \<Longrightarrow> D (\<lambda>t. - f t) = g on T"
  using has_vderiv_on_uminus by auto

lemma vderiv_npowI[vderiv_intros]:
  fixes f::"real \<Rightarrow> real"
  assumes "n \<ge> 1" and "D f = f' on T" and "g = (\<lambda>t. n * (f' t) * (f t)^(n-1))"
  shows "D (\<lambda>t. (f t)^n) = g on T"
  using assms unfolding has_vderiv_on_def has_vector_derivative_def
  by (auto intro: derivative_eq_intros simp: field_simps)

lemma vderiv_divI[vderiv_intros]:
  assumes "\<forall>t\<in>T. g t \<noteq> (0::real)" and "D f = f' on T"and "D g = g' on T"
    and "h = (\<lambda>t. (f' t * g t - f t * (g' t)) / (g t)^2)"
  shows "D (\<lambda>t. (f t)/(g t)) = h on T"
  apply(subgoal_tac "(\<lambda>t. (f t)/(g t)) = (\<lambda>t. (f t) * (1/(g t)))")
   apply(erule ssubst, rule vderiv_intros(5)[OF assms(2)])
  apply(rule vderiv_composeI[where g=g and f="\<lambda>t. 1/t" and f'="\<lambda>t. - 1/t^2", OF _ assms(3)])
  apply(subst has_vderiv_on_def, subst has_vector_derivative_def, clarsimp)
  using assms(1) apply(force intro!: derivative_eq_intros simp: fun_eq_iff power2_eq_square)
  using assms by (auto simp: field_simps)

lemma vderiv_cosI[vderiv_intros]:
  assumes "D (f::real \<Rightarrow> real) = f' on T" and "g = (\<lambda>t. - (f' t) * sin (f t))"
  shows "D (\<lambda>t. cos (f t)) = g on T"
  by (rule vderiv_composeI[OF _ assms(1), of "\<lambda>t. cos t"])
    (auto intro!: derivative_eq_intros simp: assms has_vderiv_on_iff)

lemma vderiv_sinI[vderiv_intros]:
  assumes "D (f::real \<Rightarrow> real) = f' on T" and "g = (\<lambda>t. (f' t) * cos (f t))"
  shows "D (\<lambda>t. sin (f t)) = g on T"
  by (rule vderiv_composeI[OF _ assms(1), of "\<lambda>t. sin t"])
    (auto intro!: derivative_eq_intros simp: assms has_vderiv_on_iff)

lemma vderiv_tanI[vderiv_intros]:
  assumes "D (f::real \<Rightarrow> real) = f' on T" and "\<forall>t\<in>T. cos (f t) \<noteq> 0"
    and "g = (\<lambda>t. f' t * inverse (cos (f t) *  cos (f t)))"
  shows "D (\<lambda>t. tan (f t)) = g on T"
  by (rule vderiv_composeI[OF _ assms(1), of "\<lambda>t. tan t"])
    (auto intro!: derivative_eq_intros simp: power2_eq_square assms has_vderiv_on_iff)

lemma vderiv_cotI[vderiv_intros]:
  assumes "D (f::real \<Rightarrow> real) = f' on T" and "\<forall>t\<in>T. sin (f t) \<noteq> 0"
    and "g = (\<lambda>t. - f' t * inverse (sin (f t) *  sin (f t)))"
  shows "D (\<lambda>t. cot (f t)) = g on T"
  using assms
  unfolding has_vderiv_on_def has_vector_derivative_def
  apply clarsimp
  apply (subst has_derivative_eq_rhs)
  by (rule DERIV_cot[THEN DERIV_compose_FDERIV]; force)
    (auto simp add: field_simps)

lemma vderiv_expI[vderiv_intros]:
  assumes "D (f::real \<Rightarrow> real) = f' on T" and "g = (\<lambda>t. (f' t) * exp (f t))"
  shows "D (\<lambda>t. exp (f t)) = g on T"
  by (rule vderiv_composeI[OF _ assms(1), of "\<lambda>t. exp t"])
    (auto intro!: derivative_eq_intros simp: assms has_vderiv_on_iff)

lemma has_vderiv_on_Pair: "\<lbrakk> D f = f' on T; D g = g' on T \<rbrakk>
  \<Longrightarrow> D (\<lambda>x. (f x, g x)) = (\<lambda> x. (f' x, g' x)) on T"
  by (auto intro: has_vector_derivative_Pair
      simp add: has_vderiv_on_def)

lemma vderiv_pairI[vderiv_intros]:
  assumes "D f1 = f1' on T"
    and "D f2 = f2' on T"
    and "g = (\<lambda>t. (f1' t, f2' t))"
  shows "D (\<lambda>t. (f1 t, f2 t)) = g on T"
  using assms
  by (clarsimp simp: scaleR_vec_def has_vderiv_on_def has_vector_derivative_def)
    (rule has_derivative_Pair, auto)

lemma has_vderiv_on_proj:
  assumes "D f = f' on T " and "f' = (\<lambda>t. (f1' t, f2' t))"
  shows has_vderiv_on_fst: "D (\<lambda>t. fst (f t)) = (\<lambda>t. f1' t) on T"
    and has_vderiv_on_snd: "D (\<lambda>t. snd (f t)) = (\<lambda>t. f2' t) on T"
  using assms
  unfolding has_vderiv_on_def comp_def[symmetric]
  by (auto intro!: has_vector_derivative_fst'
      has_vector_derivative_snd'')

lemma vderiv_fstI [vderiv_intros]:
  assumes "D f = f' on T " and "g = (\<lambda>t. fst (f' t))"
  shows "D (\<lambda>t. fst (f t)) = g on T"
  using assms
  apply (unfold has_vderiv_on_def comp_def[symmetric], safe)
  subgoal for x by (rule_tac has_vector_derivative_fst'[of _ _ "(snd \<circ> f') x"], force)
  done

lemma vderiv_sndI [vderiv_intros]:
  assumes "D f = f' on T " and "g = (\<lambda>t. snd (f' t))"
  shows "D (\<lambda>t. snd (f t)) = g on T"
  using assms
  apply (unfold has_vderiv_on_def comp_def[symmetric], safe)
  subgoal for x by (rule_tac has_vector_derivative_snd''[of _ "(fst \<circ> f') x"], force)
  done

lemma has_vderiv_on_inverse: "D f = f' on T \<Longrightarrow> \<forall>t\<in>T. f t \<noteq> 0
  \<Longrightarrow> D (\<lambda>t. inverse (f t)) = (\<lambda>t. - (inverse (f t)) * (f' t) * (inverse (f t))) on T"
  for f :: "real \<Rightarrow> 'b :: real_normed_div_algebra"
  unfolding has_vderiv_on_def apply (clarsimp simp: )
  unfolding has_vector_derivative_def
  apply (subst has_derivative_eq_rhs; clarsimp?)
  by (rule Deriv.has_derivative_inverse) auto

lemmas vderiv_scaleR[vderiv_intros] = has_vderiv_on_scaleR[THEN has_vderiv_on_eq_rhs]
  and vderiv_inverse[vderiv_intros] = has_vderiv_on_inverse[THEN has_vderiv_on_eq_rhs]

lemma has_vderiv_on_divideR: "\<forall>t\<in>T. g t \<noteq> (0::real) \<Longrightarrow> D f = f' on T \<Longrightarrow>  D g = g' on T
  \<Longrightarrow> D (\<lambda>t. f t /\<^sub>R g t) = (\<lambda>t. (f' t *\<^sub>R g t - f t *\<^sub>R (g' t)) /\<^sub>R (g t)^2) on T"
  by (auto intro!: vderiv_intros)
    (clarsimp simp: field_simps)

lemmas vderiv_divideRI = has_vderiv_on_divideR[THEN has_vderiv_on_eq_rhs]

lemma vderiv_sqrtI [vderiv_intros]:
  assumes "D f = f' on T" and "f \<in> T \<rightarrow> {t. t > 0}"
    and "g = (\<lambda>t. f' t * (inverse (sqrt (f t)) / 2))"
  shows "D (\<lambda>t. sqrt (f t)) = g on T"
  using assms
  unfolding has_vderiv_on_def has_vector_derivative_def
  apply clarsimp
  apply (subst has_derivative_eq_rhs)
  by (rule has_derivative_real_sqrt; force)
    (auto simp add: field_simps)

lemma vderiv_powrI [vderiv_intros]:
  fixes f :: "real \<Rightarrow> real"
  assumes "D f = f' on T"
    and "D g = g' on T" and "f \<in> T \<rightarrow> {t. t > 0}"
    and "h = (\<lambda>t. f t powr g t * (g' t * ln (f t) + f' t * g t / f t))"
  shows "D (\<lambda>t. f t powr g t) = h on T"
  using assms
  unfolding has_vderiv_on_def has_vector_derivative_def
  apply clarsimp
  apply (subst has_derivative_eq_rhs)
  by (rule has_derivative_powr; force)
    (auto simp add: field_simps)

lemma vderiv_innerI [vderiv_intros]:
  assumes "D f = f' on T"
    and "D g = g' on T"
    and "h = (\<lambda>t. f t \<bullet> g' t + f' t \<bullet> g t)"
  shows "D (\<lambda>t. f t \<bullet> g t) = h on T"
  using assms
  unfolding has_vderiv_on_def has_vector_derivative_def
  apply clarsimp
  apply (subst has_derivative_eq_rhs)
  by (rule has_derivative_inner; force)
    (auto simp add: field_simps)

lemma vderiv_normI [vderiv_intros]:
  assumes "D f = f' on T" and "f \<in> T \<rightarrow> {t. t \<noteq> 0}"
    and "g = (\<lambda>t. f' t \<bullet> sgn (f t))"
  shows "D (\<lambda>t. \<parallel>f t\<parallel>) = g on T"
  using assms
  unfolding has_vderiv_on_def has_vector_derivative_def
  apply clarsimp
  apply (subst has_derivative_eq_rhs)
  apply (rule_tac g=norm in has_derivative_compose, force)
  by (rule has_derivative_norm, force)
    (auto simp add: field_simps)

lemmas vderiv_ivl_integralI[vderiv_intros] = ivl_integral_has_vderiv_on[OF vderiv_on_continuous_on]

lemma vderiv_exp_scaleR_leftI:
  assumes "D f = f' on T" and "g' = (\<lambda>x. f' x *\<^sub>R exp (f x *\<^sub>R A) * A)"
  shows "D (\<lambda>x. exp (f x *\<^sub>R A)) = g' on T"
  using assms
  by (auto intro!: exp_scaleR_has_derivative_right
      simp: fun_eq_iff has_vderiv_on_iff)

text \<open>Examples for checking derivatives\<close>

lemma "D (*) a = (\<lambda>t. a) on T"
  by (auto intro!: vderiv_intros)

lemma "a \<noteq> 0 \<Longrightarrow> D (\<lambda>t. t/a) = (\<lambda>t. 1/a) on T"
  by (auto intro!: vderiv_intros simp: power2_eq_square)

lemma "(a::real) \<noteq> 0 \<Longrightarrow> D f = f' on T \<Longrightarrow> g = (\<lambda>t. (f' t)/a) \<Longrightarrow> D (\<lambda>t. (f t)/a) = g on T"
  by (auto intro!: vderiv_intros simp: power2_eq_square)

lemma "\<forall>t\<in>T. f t \<noteq> (0::real) \<Longrightarrow> D f = f' on T \<Longrightarrow> g = (\<lambda>t. - a * f' t / (f t)^2) \<Longrightarrow>
  D (\<lambda>t. a/(f t)) = g on T"
  by (auto intro!: vderiv_intros simp: power2_eq_square)

lemma "D (\<lambda>t. a * t\<^sup>2 / 2 + v * t + x) = (\<lambda>t. a * t + v) on T"
  by(auto intro!: vderiv_intros)

lemma "D (\<lambda>t. v * t - a * t\<^sup>2 / 2 + x) = (\<lambda>x. v - a * x) on T"
  by(auto intro!: vderiv_intros)

lemma "D x = x' on (\<lambda>\<tau>. \<tau> + t) ` T \<Longrightarrow> D (\<lambda>\<tau>. x (\<tau> + t)) = (\<lambda>\<tau>. x' (\<tau> + t)) on T"
  by (rule vderiv_composeI, auto intro: vderiv_intros)

lemma "a \<noteq> 0 \<Longrightarrow> D (\<lambda>t. t/a) = (\<lambda>t. 1/a) on T"
  by (auto intro!: vderiv_intros simp: power2_eq_square)

lemma "c \<noteq> 0 \<Longrightarrow> D (\<lambda>t. a5 * t^5 + a3 * (t^3 / c) - a2 * exp (t^2) + a1 * cos t + a0) =
  (\<lambda>t. 5 * a5 * t^4 + 3 * a3 * (t^2 / c) - 2 * a2 * t * exp (t^2) - a1 * sin t) on T"
  by (auto intro!: vderiv_intros simp: power2_eq_square)

lemma "c \<noteq> 0 \<Longrightarrow> D (\<lambda>t. - a3 * exp (t^3 / c) + a1 * sin t + a2 * t^2) =
  (\<lambda>t. a1 * cos t + 2 * a2 * t - 3 * a3 * t^2 / c * exp (t^3 / c)) on T"
  by (auto intro!: vderiv_intros simp: power2_eq_square)

lemma "c \<noteq> 0 \<Longrightarrow> D (\<lambda>t. exp (a * sin (cos (t^4) / c))) =
  (\<lambda>t. - 4 * a * t^3 * sin (t^4) / c * cos (cos (t^4) / c) * exp (a * sin (cos (t^4) / c))) on T"
  by (intro vderiv_intros)
    (auto intro!: vderiv_intros simp: power2_eq_square)

subsection \<open> Bounded linear and bounded bilinear \<close>

thm bounded_bilinear.bounded_linear_prod_right
  bounded_bilinear.bounded_linear_left
  bounded_bilinear.bounded_linear_right
thm linear_iff bounded_linear.bounded
  bounded_linear_def[unfolded bounded_linear_axioms_def]
  bounded_bilinear_def
thm bounded_bilinear.diff_left bounded_bilinear.diff_right
thm bounded_bilinear.has_vector_derivative

lemma bdd_linear_iff_has_derivative:
  "bounded_linear f \<longleftrightarrow> D f \<mapsto> f F"
  using bounded_linear_imp_has_derivative
  has_derivative_bounded_linear
  by blast

lemma bdd_bilinear_derivativeL:
  "bounded_bilinear f \<Longrightarrow> D (\<lambda>x. f x y) \<mapsto> (\<lambda>x. f x y) F"
  by (subst  bdd_linear_iff_has_derivative[symmetric])
    (rule bounded_bilinear.bounded_linear_left)

lemma bdd_bilinear_derivativeR:
  "bounded_bilinear f \<Longrightarrow> D (f x) \<mapsto> (f x) F"
  by (subst  bdd_linear_iff_has_derivative[symmetric])
    (rule bounded_bilinear.bounded_linear_right)

lemma has_derivative_bdd_bilinear:
  assumes "bounded_bilinear op"
    and "D f \<mapsto> (\<lambda>t. t *\<^sub>R f') at x within S"
    and "D g \<mapsto> (\<lambda>t. t *\<^sub>R g') at x within S"
  shows "D (\<lambda>x. op (f x) (g x)) \<mapsto> (\<lambda>t. t *\<^sub>R op (f x) g' + t *\<^sub>R op f' (g x)) at x within S"
  using bounded_bilinear.has_vector_derivative[OF assms(1)] assms
  unfolding has_vector_derivative_def
  by (clarsimp simp: scaleR_add_right)

lemma vderiv_bdd_bilinearI:
  assumes "bounded_bilinear op"
    and h_eq: "h = (\<lambda>t. op (f t) (g' t) + op (f' t) (g t))"
    and df: "D f = f' on S" and dg: "D g = g' on S'" and "S \<subseteq> S'"
  shows "D (\<lambda>t. op (f t) (g t)) = h on S"
  unfolding has_vderiv_on_def
  by (auto simp: h_eq intro!: bounded_bilinear.has_vector_derivative[OF assms(1)]
      has_vderiv_on_subset[OF dg \<open>S \<subseteq> S'\<close>, unfolded has_vderiv_on_def, rule_format]
      df[unfolded has_vderiv_on_def, rule_format])

lemma bdd_linear_2op_has_vderiv_onL:
  fixes op :: "'a::real_normed_vector \<Rightarrow> 'b \<Rightarrow> 'c::real_normed_vector"
  assumes bdd_linear_put: "\<forall>v. bounded_linear (\<lambda>s. op s v)"
    and non_trivial_state_space: "\<exists>s::'a. s \<noteq> 0"
  shows "D f = f' on T
  \<Longrightarrow> D (\<lambda>t. op (f t) v) = (\<lambda>t. op (f' t) v) on T"
proof (clarsimp simp: has_vderiv_on_def has_vector_derivative_def has_derivative_at_within, safe)
  fix \<tau>
  let "?quot f f'" = "\<lambda>\<tau> t. (f t - f \<tau> - (t - \<tau>) *\<^sub>R f' \<tau>) /\<^sub>R \<bar>t - \<tau>\<bar>"
  let "?lim f f'" = "\<lambda>\<tau>. ((\<lambda>t. ?quot f f' \<tau> t) \<longlongrightarrow> 0) (at \<tau> within T)"
  assume "\<tau> \<in> T" and f_hyps: "\<forall>x\<in>T. bounded_linear (\<lambda>xa. xa *\<^sub>R f' x) \<and> ?lim f f' x"
  hence linearv: "linear (\<lambda>s. op s v)"
    and bdd_put: "\<exists>K. \<forall>x. \<parallel>op x v\<parallel> \<le> \<parallel>x\<parallel> * K"
    using bdd_linear_put
    unfolding bounded_linear_def bounded_linear_axioms_def
    by auto
  show "bounded_linear (\<lambda>z. z *\<^sub>R op (f' \<tau>) v)"
    using bounded_linear_scaleR_const[OF bounded_linear_ident] .
  {fix e::real
    assume "e > 0"
    obtain K where K_def: "\<forall>x. \<parallel>op x v\<parallel> \<le> \<parallel>x\<parallel> * K"
      using bdd_put by auto
    hence "K \<ge> 0"
      using order.trans[OF norm_ge_zero, of "op _ v" "\<parallel>_\<parallel> * K", unfolded zero_le_mult_iff]
        non_trivial_state_space by auto
    have "\<parallel>op (?quot f f' \<tau> t) v\<parallel> \<le> \<parallel>?quot f f' \<tau> t\<parallel> * K" for t
        using K_def
      by (erule_tac x="?quot f f' \<tau> t" in allE, force)
    moreover note f_hyps[THEN bspec[OF _ \<open>\<tau> \<in> T\<close>], THEN conjunct2, unfolded tendsto_iff eventually_at dist_norm]
    ultimately have "\<exists>d>0. \<forall>t\<in>T. t \<noteq> \<tau> \<and> \<parallel>t - \<tau>\<parallel> < d \<longrightarrow> \<parallel>op (?quot f f' \<tau> t) v\<parallel> < e"
      using \<open>e > 0\<close> \<open>K \<ge> 0\<close>
      apply (cases "K = 0", force)
      apply (erule_tac x="e / K" in allE, clarsimp)
      apply (rule_tac x=d in exI, clarsimp)
      apply (erule_tac x=t in ballE; clarsimp)
      by (smt (verit, ccfv_SIG) mult_imp_div_pos_le)
  }
  thus "((\<lambda>y. (op (f y) v - op (f \<tau>) v - (y - \<tau>) *\<^sub>R op (f' \<tau>) v) /\<^sub>R \<bar>y - \<tau>\<bar>) \<longlongrightarrow> 0) (at \<tau> within T)"
    apply (fold linear_cmul[OF linearv] linear_diff[OF linearv])+
    unfolding tendsto_iff dist_norm eventually_at by force
qed

lemma vderiv_on_blopI1:
  fixes op :: "'a::real_normed_vector \<Rightarrow> 'b \<Rightarrow> 'c::real_normed_vector"
  assumes "\<forall>v. bounded_linear (\<lambda>s. op s v)"
    and "\<exists>s::'a. s \<noteq> 0"
    and "D f = f' on T"
    and "g = (\<lambda>t. op (f' t) v)"
  shows "D (\<lambda>t. op (f t) v) = g on T"
  using bdd_linear_2op_has_vderiv_onL[OF assms(1-3)] assms(4)
  by auto

lemma leibniz_rule_bdd_bilinear':
  fixes f :: "real \<Rightarrow> 'a::banach"
    and op :: "'a \<Rightarrow> 'b::real_normed_vector \<Rightarrow> 'c::banach"
  assumes bdd_bil: "bounded_bilinear op"
    and h_eq: "h = (\<lambda>t. op (f t) (g' t) + op (f' t) (g t))"
    and df: "D f = f' on {a--b}"
    and dg: "D g = g' on S'"
    and dg': "D g' = g'' on S''"
    and "{a--b} \<subseteq> S'" "{a--b} \<subseteq> S''"
  shows "D (\<lambda>t. op (f t) (g t) - (ivl_integral a t (\<lambda>\<tau>. (op (f \<tau>) (g' \<tau>))))) = (\<lambda>t. op (f' t) (g t)) on {a--b}"
  by (auto intro!: vderiv_intros vderiv_bdd_bilinearI[OF bdd_bil _ df dg \<open>{a--b} \<subseteq> S'\<close>]
      vderiv_bdd_bilinearI[OF bdd_bil _ df dg'  \<open>{a--b} \<subseteq> S''\<close>])

thm vderiv_ivl_integralI
  ivl_integral_has_vector_derivative_compact_interval
  ivl_integral_has_vderiv_on_compact_interval
  ivl_integral_has_vderiv_on_subset_segment
  ivl_integral_has_vderiv_on
  ivl_integral_has_vector_derivative
  has_vector_derivative_transform
  integral_has_vector_derivative
  has_integral_def[unfolded tendsto_iff dist_norm]

subsection \<open> Intermediate Value Theorem \<close>

lemma IVT_two_functions:
  fixes f :: "('a::{linear_continuum_topology, real_vector}) \<Rightarrow>
  ('b::{linorder_topology,real_normed_vector,ordered_ab_group_add})"
  assumes conts: "continuous_on {a..b} f" "continuous_on {a..b} g"
      and ahyp: "f a < g a" and bhyp: "g b < f b " and "a \<le> b"
    shows "\<exists>x\<in>{a..b}. f x = g x"
proof-
  let "?h x" = "f x - g x"
  have "?h a \<le> 0" and "?h b \<ge> 0"
    using ahyp bhyp by simp_all
  also have "continuous_on {a..b} ?h"
    using conts continuous_on_diff by blast
  ultimately obtain x where "a \<le> x" "x \<le> b" and "?h x = 0"
    using IVT'[of "?h"] \<open>a \<le> b\<close> by blast
  thus ?thesis
    using \<open>a \<le> b\<close> by auto
qed

lemma IVT_two_functions_real_ivl:
  fixes f :: "real \<Rightarrow> real"
  assumes conts: "continuous_on {a--b} f" "continuous_on {a--b} g"
      and ahyp: "f a < g a" and bhyp: "g b < f b "
    shows "\<exists>x\<in>{a--b}. f x = g x"
proof(cases "a \<le> b")
  case True
  then show ?thesis
    using IVT_two_functions assms
    unfolding closed_segment_eq_real_ivl by auto
next
  case False
  hence "a \<ge> b"
    by auto
  hence "continuous_on {b..a} f" "continuous_on {b..a} g"
    using conts False unfolding closed_segment_eq_real_ivl by auto
  hence "\<exists>x\<in>{b..a}. g x = f x"
    using IVT_two_functions[of b a g f] assms(3,4) False by auto
  then show ?thesis
    using \<open>a \<ge> b\<close> unfolding closed_segment_eq_real_ivl by auto force
qed

lemma mvt_ivl_general:
  fixes f :: "real \<Rightarrow> 'a::real_inner"
  assumes "a \<noteq> b" and "continuous_on {a--b} f"
    and "\<forall>x\<in>{a<--<b}. D f \<mapsto> (f' x) (at x)"
  shows "\<exists>x\<in>{a<--<b}. \<parallel>f b - f a\<parallel> \<le> \<parallel>f' x \<bar>b - a\<bar>\<parallel>"
proof(cases "a < b")
  case True
  thus ?thesis
    using closed_segment_eq_real_ivl open_segment_eq_real_ivl
      assms mvt_general[of a b f] by force
next
  case False
  hence "b < a" "{a--b} = {b..a}" "{a<--<b} = {b<..<a}"
    using assms closed_segment_eq_real_ivl open_segment_eq_real_ivl by auto
  hence cont: "continuous_on {b..a} f" and "\<forall>x\<in>{b<..<a}. D f \<mapsto> (f' x) (at x)"
    using assms by auto
  hence "\<exists>x\<in>{b<..<a}. \<parallel>f b - f a\<parallel> \<le> \<parallel>f' x \<bar>a - b\<bar>\<parallel>"
    using mvt_general[OF \<open>b < a\<close> cont, of f']
    by (auto simp: Real_Vector_Spaces.real_normed_vector_class.norm_minus_commute)
  thus ?thesis
    by (subst \<open>{a<--<b} = {b<..<a}\<close>) auto
qed

subsection \<open> Filters \<close>

lemma eventually_at_within_mono:
  assumes "t \<in> interior T" and "T \<subseteq> S"
    and "eventually P (at t within T)"
  shows "eventually P (at t within S)"
  by (meson assms eventually_within_interior interior_mono subsetD)

lemma netlimit_at_within_mono:
  fixes t::"'a::{perfect_space,t2_space}"
  assumes "t \<in> interior T" and "T \<subseteq> S"
  shows "netlimit (at t within S) = t"
  using assms(1) interior_mono[OF \<open>T \<subseteq> S\<close>] netlimit_within_interior by auto

lemma has_derivative_at_within_mono:
  fixes t::"'a::{perfect_space,t2_space,real_normed_vector}"
  assumes "t \<in> interior T" and "T \<subseteq> S"
    and "D f \<mapsto> f' at t within T"
  shows "D f \<mapsto> f' at t within S"
  using assms(3) apply(unfold has_derivative_def tendsto_iff, safe)
  unfolding netlimit_at_within_mono[OF assms(1,2)] netlimit_within_interior[OF assms(1)]
  by (rule eventually_at_within_mono[OF assms(1,2)]) simp

lemma eventually_all_finite2:
  fixes P :: "('a::finite) \<Rightarrow> 'b \<Rightarrow> bool"
  assumes h:"\<forall>i. eventually (P i) F"
  shows "eventually (\<lambda>x. \<forall>i. P i x) F"
proof(unfold eventually_def)
  let ?F = "Rep_filter F"
  have obs: "\<forall>i. ?F (P i)"
    using h by auto
  have "?F (\<lambda>x. \<forall>i \<in> UNIV. P i x)"
    apply(rule finite_induct)
    by(auto intro: eventually_conj simp: obs h)
  thus "?F (\<lambda>x. \<forall>i. P i x)"
    by simp
qed

lemma eventually_all_finite_mono:
  fixes P :: "('a::finite) \<Rightarrow> 'b \<Rightarrow> bool"
  assumes h1: "\<forall>i. eventually (P i) F"
      and h2: "\<forall>x. (\<forall>i. (P i x)) \<longrightarrow> Q x"
  shows "eventually Q F"
proof-
  have "eventually (\<lambda>x. \<forall>i. P i x) F"
    using h1 eventually_all_finite2 by blast
  thus "eventually Q F"
    unfolding eventually_def
    using h2 eventually_mono by auto
qed

subsection \<open> Multivariable derivatives \<close>

lemma has_derivative_vec_nth[derivative_intros]:
  "D (\<lambda>s. s $ i) \<mapsto> (\<lambda>s. s $ i) (at x within S)"
  by (clarsimp simp: has_derivative_within) standard

lemma bounded_linear_coordinate:
  "(bounded_linear f) \<longleftrightarrow> (\<forall>i. bounded_linear (\<lambda>x. (f x) $ i))" (is "?lhs = ?rhs")
proof
  assume ?lhs
  thus ?rhs
    apply(clarsimp, rule_tac f="(\<lambda>x. x $ i)" in bounded_linear_compose)
     apply(simp_all add: bounded_linear_def bounded_linear_axioms_def linear_iff)
    by (rule_tac x=1 in exI, clarsimp) (meson Finite_Cartesian_Product.norm_nth_le)
next
  assume ?rhs
  hence "(\<forall>i. \<exists>K. \<forall>x. \<parallel>f x $ i\<parallel> \<le> \<parallel>x\<parallel> * K)" "linear f"
    by (auto simp: bounded_linear_def bounded_linear_axioms_def linear_iff vec_eq_iff)
  then obtain F where F: "\<And>i x. \<parallel>f x $ i\<parallel> \<le> \<parallel>x\<parallel> * F i"
    by metis
  have "\<parallel>f x\<parallel> \<le> \<parallel>x\<parallel> * sum F UNIV" for x
  proof -
    have "norm (f x) \<le> (\<Sum>i\<in>UNIV. \<parallel>f x $ i\<parallel>)"
      by (simp add: L2_set_le_sum norm_vec_def)
    also have "... \<le> (\<Sum>i\<in>UNIV. norm x * F i)"
      by (metis F sum_mono)
    also have "... = norm x * sum F UNIV"
      by (simp add: sum_distrib_left)
    finally show ?thesis .
  qed
  then show ?lhs
    by (force simp: bounded_linear_def bounded_linear_axioms_def \<open>linear f\<close>)
qed

lemma open_preimage_nth:
  "open S \<Longrightarrow> open {s::('a::real_normed_vector^'n::finite). s $ i \<in> S}"
  unfolding open_contains_ball apply clarsimp
  apply(erule_tac x="x$i" in ballE; clarsimp)
  apply(rule_tac x=e in exI; clarsimp simp: dist_norm subset_eq ball_def)
  apply(rename_tac x e y, erule_tac x="y$i" in allE)
  using Finite_Cartesian_Product.norm_nth_le
  by (metis le_less_trans vector_minus_component)

lemma tendsto_nth_iff:
  fixes l::"'a::real_normed_vector^'n::finite"
  defines "m \<equiv> real CARD('n)"
  shows "(f \<longlongrightarrow> l) F \<longleftrightarrow> (\<forall>i. ((\<lambda>x. f x $ i) \<longlongrightarrow> l $ i) F)" (is "?lhs = ?rhs")
proof
  assume ?lhs
  thus ?rhs
    unfolding tendsto_def
    by (clarify, drule_tac x="{s. s $ i \<in> S}" in spec) (auto simp: open_preimage_nth)
next
  assume ?rhs
  thus ?lhs
  proof(unfold tendsto_iff dist_norm, clarify)
    fix \<epsilon>::real assume "0 < \<epsilon>"
    assume evnt_h: "\<forall>i \<epsilon>. 0 < \<epsilon> \<longrightarrow> (\<forall>\<^sub>F x in F. \<parallel>f x $ i - l $ i\<parallel> < \<epsilon>)"
    {fix x assume hyp: "\<forall>i. \<parallel>f x $ i - l $ i\<parallel> < (\<epsilon>/m)"
      have "\<parallel>f x - l\<parallel> \<le> (\<Sum>i\<in>UNIV. \<parallel>f x $ i - l $ i\<parallel>)"
        using triangle_norm_vec_le_sum[of "f x - l"] by auto
      also have "... < (\<Sum>(i::'n)\<in>UNIV. (\<epsilon>/m))"
        apply(rule sum_strict_mono[of UNIV "\<lambda>i. \<parallel>f x $ i - l $ i\<parallel>" "\<lambda>i. \<epsilon>/m"])
        using hyp by auto
      also have "... = m * (\<epsilon>/m)"
        unfolding assms by simp
      finally have "\<parallel>f x - l\<parallel> < \<epsilon>"
        unfolding assms by simp}
    hence key: "\<And>x. \<forall>i. \<parallel>f x $ i - l $ i\<parallel> < (\<epsilon>/m) \<Longrightarrow> \<parallel>f x - l\<parallel> < \<epsilon>"
      by blast
    have obs: "\<forall>\<^sub>F x in F. \<forall>i. \<parallel>f x $ i - l $ i\<parallel> < (\<epsilon>/m)"
      apply(rule eventually_all_finite)
      using \<open>0 < \<epsilon>\<close> evnt_h unfolding assms by auto
    thus "\<forall>\<^sub>F x in F. \<parallel>f x - l\<parallel> < \<epsilon>"
      by (rule eventually_mono[OF _ key], simp)
  qed
qed

lemma has_derivative_coordinate:
  "(D f \<mapsto> f' at x within S) \<longleftrightarrow> (\<forall>i. D (\<lambda>s. f s $ i) \<mapsto> (\<lambda>s. f' s $ i) at x within S)"
  by (simp add: has_derivative_within tendsto_nth_iff
      bounded_linear_coordinate all_conj_distrib)

lemma has_vderiv_on_component[simp]:
  fixes x::"real \<Rightarrow> ('a::banach)^('n::finite)"
  shows "(D x = x' on T) = (\<forall>i. D (\<lambda>t. x t $ i) = (\<lambda>t. x' t $ i) on T)"
  unfolding has_vderiv_on_def has_vector_derivative_def
  by (auto simp: has_derivative_coordinate)

text \<open> The results below are legacy and particular cases of the lemmas above in this section.
We leave them here because they might be useful for Sledgehammer. \<close>

lemma frechet_tendsto_vec_lambda:
  fixes f::"real \<Rightarrow> ('a::banach)^('m::finite)" and x::real and T::"real set"
  defines "x\<^sub>0 \<equiv> netlimit (at x within T)" and "m \<equiv> real CARD('m)"
  assumes "\<forall>i. ((\<lambda>y. (f y $ i - f x\<^sub>0 $ i - (y - x\<^sub>0) *\<^sub>R f' x $ i) /\<^sub>R (\<parallel>y - x\<^sub>0\<parallel>)) \<longlongrightarrow> 0) (at x within T)"
  shows "((\<lambda>y. (f y - f x\<^sub>0 - (y - x\<^sub>0) *\<^sub>R f' x) /\<^sub>R (\<parallel>y - x\<^sub>0\<parallel>)) \<longlongrightarrow> 0) (at x within T)"
  apply(subst tendsto_nth_iff)
  using assms by auto

lemma tendsto_norm_bound:
  "\<forall>x. \<parallel>G x - L\<parallel> \<le> \<parallel>F x - L\<parallel> \<Longrightarrow> (F \<longlongrightarrow> L) net \<Longrightarrow> (G \<longlongrightarrow> L) net"
  apply(unfold tendsto_iff dist_norm, clarsimp)
  apply(rule_tac P="\<lambda>x. \<parallel>F x - L\<parallel> < e" in eventually_mono, simp)
  by (rename_tac e z) (erule_tac x=z in allE, simp)

lemma tendsto_zero_norm_bound:
  "\<forall>x. \<parallel>G x\<parallel> \<le> \<parallel>F x\<parallel> \<Longrightarrow> (F \<longlongrightarrow> 0) net \<Longrightarrow> (G \<longlongrightarrow> 0) net"
  apply(unfold tendsto_iff dist_norm, clarsimp)
  apply(rule_tac P="\<lambda>x. \<parallel>F x\<parallel> < e" in eventually_mono, simp)
  by (rename_tac e z) (erule_tac x=z in allE, simp)

lemma frechet_tendsto_vec_nth:
  fixes f::"real \<Rightarrow> ('a::real_normed_vector)^'m"
  assumes "((\<lambda>x. (f x - f x\<^sub>0 - (x - x\<^sub>0) *\<^sub>R f' t) /\<^sub>R (\<parallel>x - x\<^sub>0\<parallel>)) \<longlongrightarrow> 0) (at t within T)"
  shows "((\<lambda>x. (f x $ i - f x\<^sub>0 $ i - (x - x\<^sub>0) *\<^sub>R f' t $ i) /\<^sub>R (\<parallel>x - x\<^sub>0\<parallel>)) \<longlongrightarrow> 0) (at t within T)"
  apply(rule_tac F="(\<lambda>x. (f x - f x\<^sub>0 - (x - x\<^sub>0) *\<^sub>R f' t) /\<^sub>R (\<parallel>x - x\<^sub>0\<parallel>))" in tendsto_zero_norm_bound)
   apply(clarsimp, rule mult_left_mono)
    apply (metis Finite_Cartesian_Product.norm_nth_le vector_minus_component vector_scaleR_component)
  using assms by simp_all

lemma has_derivative_vec_lambda_old:
  fixes f::"real \<Rightarrow> ('a::banach)^('n::finite)"
  assumes "\<forall>i. D (\<lambda>t. f t $ i) \<mapsto> (\<lambda> h. h *\<^sub>R f' x $ i) (at x within T)"
  shows "D f \<mapsto> (\<lambda>h. h *\<^sub>R f' x) at x within T"
  apply(subst has_derivative_coordinate)
  using assms by auto

lemma has_derivative_vec_nth_old:
  assumes "D f \<mapsto> (\<lambda>h. h *\<^sub>R f' x) at x within T"
  shows "D (\<lambda>t. f t $ i) \<mapsto> (\<lambda>h. h *\<^sub>R f' x $ i) at x within T"
  using  assms
  by (subst (asm) has_derivative_coordinate, simp)

subsection \<open> Differentiability implies Lipschitz \<close>

(********************************************************************************)

text \<open> Dive on topological classes \<close>
thm first_countable_topology_axioms
thm class.first_countable_topology.axioms
thm class.metric_space.axioms class.metric_space_axioms_def
find_theorems "class.metric_space _ _ _ \<Longrightarrow> _"
find_theorems "class.t2_space"

term "x :: 'a :: first_countable_topology" thm first_countable_basis
term "x :: 'a :: metric_space" thm dist_eq_0_iff dist_triangle2
term "x :: 'a :: uniformity"
term "x :: 'a :: dist"
term "x :: 'a :: uniformity_dist" thm uniformity_dist
term "x :: 'a :: open_uniformity" thm open_uniformity
term "x :: 'a :: open"

text \<open> Useful to remember these theorems \<close>

text \<open> A filter is a predicate of predicates closed under sub-properties and finite conjunctions.
Given a filter F and predicate P, the property @{term "eventually F P"} holds iff @{term "F P"}.\<close>

thm filter_eq_iff eventually_principal \<comment> \<open> filters (principal) \<close>
thm eventually_at_filter eventually_at eventually_at_topological
  at_within_open at_within_open_subset at_within_Icc_at \<comment> \<open> @{term "at x within T"} \<close>
thm at_within_def nhds_metric nhds_def eventually_inf_principal eventually_nhds_metric
  eventually_at[unfolded at_within_def eventually_inf_principal] \<comment> \<open> Proof of @{thm eventually_at} \<close>
thm has_derivative_at_within Lim_ident_at \<comment> \<open> derivative at within \<close>
thm has_real_derivative_iff_has_vector_derivative \<comment> \<open> real vs vector derivative \<close>
thm Rolle_deriv mvt mvt_simple mvt_very_simple mvt_general \<comment> \<open> mean value theorem \<close>
thm banach_fix banach_fix_type \<comment> \<open> banach fixpoint theorems \<close>
thm has_derivative_componentwise_within tendsto_componentwise_iff bounded_linear_compose
thm bounded_linear_compose
thm c1_implies_local_lipschitz

thm blinfun_apply
thm local_lipschitz_def lipschitz_on_def
(********************************************************************************)

lemma bounded_iff_subset_ball:
  "bounded S \<longleftrightarrow> (\<exists>e x. S \<subseteq> ball x e \<and> 0 \<le> e)"
  unfolding bounded_def ball_def subset_eq apply (clarsimp, safe)
  apply (metis approximation_preproc_push_neg(1) dual_order.strict_trans2 gt_ex linear)
  using less_eq_real_def by blast

lemmas bounded_continuous_image = compact_imp_bounded[OF compact_continuous_image]

lemmas bdd_above_continuous_image = bounded_continuous_image[THEN bounded_imp_bdd_above]

lemma is_compact_intervalD:
  "is_interval T \<Longrightarrow> compact T \<Longrightarrow> \<exists>a b. T = {a..b}" for T::"real set"
  by (meson connected_compact_interval_1 is_interval_connected)

lemma c1_local_lipschitz:
  fixes f::"real \<Rightarrow> ('a::{banach,perfect_space}) \<Rightarrow> 'a"
  assumes "open S" and "open T"
    and c1hyp: "\<forall>\<tau> \<in> T. \<forall>s \<in> S. D (f \<tau>) \<mapsto> \<DD> (at s within S)" "continuous_on S \<DD>"
  shows "local_lipschitz T S f"
proof(unfold local_lipschitz_def lipschitz_on_def, clarsimp simp: dist_norm)
  fix s and t assume "s \<in> S" and "t \<in> T"
  then obtain L where bdd: "\<forall>x. \<parallel>\<DD> x\<parallel> \<le> L * \<parallel>x\<parallel>"
    using c1hyp unfolding has_derivative_def bounded_linear_def bounded_linear_axioms_def
    by (metis mult.commute)
  hence "L \<ge> 0"
    by (metis mult.commute mult.left_neutral norm_ge_zero
        order_trans vector_choose_size zero_le_one)
  then obtain \<epsilon>\<^sub>1 and \<epsilon>\<^sub>2 where "\<epsilon>\<^sub>1 > 0" and "t \<in> cball t \<epsilon>\<^sub>1"  and "cball t \<epsilon>\<^sub>1 \<subseteq> T"
    and "\<epsilon>\<^sub>2 > 0"  and "s \<in> cball s \<epsilon>\<^sub>2" and "cball s \<epsilon>\<^sub>2 \<subseteq> S"
    using \<open>t \<in> T\<close> \<open>s \<in> S\<close> \<open>open T\<close> \<open>open S\<close> open_contains_cball_eq
    by (metis centre_in_cball less_eq_real_def)
  hence "t \<in> cball t (min \<epsilon>\<^sub>1 \<epsilon>\<^sub>2) \<inter> T" (is "t \<in> ?B1 \<inter> T")
    and "s \<in> cball s (min \<epsilon>\<^sub>1 \<epsilon>\<^sub>2) \<inter> S" (is "s \<in> ?B2 \<inter> S")
    and "cball s (min \<epsilon>\<^sub>1 \<epsilon>\<^sub>2) \<subseteq> S"
    by auto
  {fix \<tau> assume tau_hyp: "\<tau> \<in> ?B1 \<inter> T"
    {fix x and y assume x_hyp: "x \<in> ?B2 \<inter> S" and y_hyp: "y \<in> ?B2 \<inter> S"
      define \<sigma> and \<sigma>' where sigma_def: "\<sigma> = (\<lambda>\<tau>. x + \<tau> *\<^sub>R (y - x))"
        and dsigma_def: "\<sigma>' = (\<lambda>\<tau>. \<tau> *\<^sub>R (y - x))"
      let ?g = "(f \<tau>) \<circ> \<sigma>"
      have deriv: "D \<sigma> = (\<lambda>t. y - x) on {0..1}"
        unfolding sigma_def has_vderiv_on_def
        by (auto intro!: derivative_eq_intros)
      have "\<sigma> ` {0..1} = closed_segment x y"
        apply(clarsimp simp: closed_segment_def set_eq_iff sigma_def, safe)
         apply(rename_tac r, rule_tac x="r" in exI, force simp: algebra_simps sigma_def)
        by (auto simp: algebra_simps sigma_def)
      hence sigma_img: "\<sigma> ` {0..1} \<subseteq> ?B2"
        using convex_cball[of s "min \<epsilon>\<^sub>1 \<epsilon>\<^sub>2"] convex_contains_segment[of ?B2]
          \<open>?B2 \<subseteq> S\<close> x_hyp y_hyp by blast
      hence "\<forall>r\<in>{0..1}. D f \<tau> \<mapsto> \<DD> at (\<sigma> r) within \<sigma> ` {0..1}"
        using \<open>?B2 \<subseteq> S\<close> c1hyp
        apply(clarify, rule_tac s=S in has_derivative_subset)
        using tau_hyp by blast force
      hence "\<And>r. r \<in> {0..1} \<Longrightarrow> (f \<tau> \<circ> \<sigma> has_vector_derivative \<DD> (y - x)) (at r within {0..1})"
        using vector_derivative_diff_chain_within[of \<sigma> "y - x" _ "{0..1}" "f \<tau>" \<DD>] deriv
        unfolding has_vderiv_on_def by blast
      note fundamental_theorem_of_calculus[OF zero_le_one this]
      hence key: "((\<lambda>t::real. \<DD> (y - x)) has_integral (f \<tau> \<circ> \<sigma>) 1 - (f \<tau> \<circ> \<sigma>) 0) {0..1}"
        by (clarsimp simp: sigma_def)
      thm has_integral_iff
      have "f \<tau> y - f \<tau> x = ?g 1 - ?g 0"
        by (simp add: sigma_def)
      also have "... = integral {0..1} (\<lambda>t::real. \<DD> (y - x))"
        by (rule sym, rule integral_unique[OF key])
      also have "... = \<DD> (y - x)"
        by (subst integral_const_real, subst content_real, simp_all)
      finally have "\<parallel>f \<tau> y - f \<tau> x\<parallel> = \<parallel>\<DD> (y - x)\<parallel>"
        by simp
      hence "\<parallel>f \<tau> y - f \<tau> x\<parallel> \<le> L * \<parallel>y - x\<parallel>"
        using bdd by auto}
    hence "0 \<le> L \<and> (\<forall>x \<in> ?B2 \<inter> S. \<forall>y \<in> ?B2 \<inter> S. \<parallel>f \<tau> x - f \<tau> y\<parallel> \<le> L * \<parallel>x - y\<parallel>)"
      using \<open>0 \<le> L\<close> by blast}
  thus "\<exists>\<epsilon>>0. \<exists>L. \<forall>\<tau>\<in>cball t \<epsilon> \<inter> T. 0 \<le> L \<and>
    (\<forall>x\<in>cball s \<epsilon> \<inter> S. \<forall>y\<in>cball s \<epsilon> \<inter> S. \<parallel>f \<tau> x - f \<tau> y\<parallel> \<le> L * \<parallel>x - y\<parallel>)"
    using \<open>\<epsilon>\<^sub>1 > 0\<close> \<open>\<epsilon>\<^sub>2 > 0\<close> by (metis Int_commute min_less_iff_conj)
qed

lemma continuous_derivative_local_lipschitz: (* This should be generalised *)
  fixes f :: "real \<Rightarrow> 'a::real_inner"
  assumes "(D f = f' on UNIV)" and "(continuous_on UNIV f')"
  shows "local_lipschitz UNIV UNIV (\<lambda>t::real. f)"
proof(unfold local_lipschitz_def lipschitz_on_def, clarsimp simp: dist_norm)
  fix x and t
  obtain f' where h1: "D f = f' on UNIV" and h2: "continuous_on UNIV f'"
    using assms by blast
  hence deriv_f1: "\<And>a b. a < b \<Longrightarrow> D f = f' on {a..b}"
    using has_vderiv_on_subset[OF h1] by auto
  hence cont_f: "\<And>a b. a < b \<Longrightarrow> continuous_on {a..b} f"
    using vderiv_on_continuous_on by blast
  have deriv_f2: "\<And>a b x. a < x \<Longrightarrow> x < b \<Longrightarrow> D f \<mapsto> (\<lambda>t. t *\<^sub>R f' x) (at x)"
    using h1 unfolding has_vderiv_on_def has_vector_derivative_def by simp
  have cont_f': "continuous_on UNIV (\<lambda>z. \<parallel>f' z\<parallel>)"
    apply(subst comp_def[symmetric, where f=norm])
    apply(rule continuous_on_compose[OF h2])
    using continuous_on_norm_id by blast
  {fix a b::real assume "a < b"
    hence f1: "(\<And>x. a < x \<Longrightarrow> x < b \<Longrightarrow> D f \<mapsto> (\<lambda>t. t *\<^sub>R f' x) (at x))"
      using deriv_f2 unfolding has_vderiv_on_def has_vector_derivative_def by simp
    thm mvt_general[of a b]
    hence "\<exists>x\<in>{a<..<b}. \<parallel>f b - f a\<parallel> \<le> \<bar>b - a\<bar> * \<parallel>f' x\<parallel>"
      using mvt_general[OF \<open>a < b\<close> cont_f[OF \<open>a < b\<close>] f1] by auto}
  hence key: "\<And>a b. a < b \<Longrightarrow> \<exists>x\<in>{a<..<b}. \<parallel>f b - f a\<parallel> \<le> \<parallel>f' x\<parallel> * \<bar>b - a\<bar>"
    by (metis mult.commute)
  {fix \<epsilon>::real assume "\<epsilon> > 0"
    let ?L = "Sup ((\<lambda>z. \<parallel>f' z\<parallel>) ` cball x \<epsilon>)"
    have "?L \<ge> 0"
      apply(rule_tac x=x in conditionally_complete_lattice_class.cSUP_upper2)
        apply(rule bdd_above_continuous_image; clarsimp?)
        apply(rule continuous_on_subset[OF cont_f'])
      using \<open>\<epsilon> > 0\<close> by auto
    {fix a b assume "a \<in> cball x \<epsilon>" and "b \<in> cball x \<epsilon>"
      hence "\<exists>x\<in>{a--b}. \<parallel>f b - f a\<parallel> \<le> \<parallel>f' x\<parallel> * \<bar>b - a\<bar>"
        using key apply(cases "a = b", clarsimp)
        apply(cases "a < b"; clarsimp)
         apply (metis ODE_Auxiliarities.closed_segment_eq_real_ivl atLeastAtMost_iff
            greaterThanLessThan_iff less_eq_real_def)
        by (metis ODE_Auxiliarities.closed_segment_eq_real_ivl atLeastAtMost_iff
            dist_commute dist_norm greaterThanLessThan_iff less_eq_real_def not_le)
      then obtain z where "z\<in>{a--b}" and z_hyp: "\<parallel>f b - f a\<parallel> \<le> \<parallel>f' z\<parallel> * \<bar>b - a\<bar>"
        by blast
      hence "{a--b} \<subseteq> cball x \<epsilon>" and "z \<in> cball x \<epsilon>"
        by (meson \<open>a \<in> cball x \<epsilon>\<close> \<open>b \<in> cball x \<epsilon>\<close> closed_segment_subset convex_cball subset_eq)+
      hence "\<parallel>f' z\<parallel> \<le> ?L"
        by (metis bdd_above_continuous_image cSUP_upper compact_cball cont_f'
            continuous_on_subset top.extremum)
      hence "\<parallel>f b - f a\<parallel> \<le> ?L * \<bar>b - a\<bar>"
        using z_hyp by (smt (verit, best) mult_right_mono)}
    hence "(\<exists>ta. \<bar>t - ta\<bar> \<le> \<epsilon>) \<longrightarrow> (\<exists>L\<ge>0. \<forall>xa\<in>cball x \<epsilon>. \<forall>y\<in>cball x \<epsilon>. \<parallel>f xa - f y\<parallel> \<le> L * \<bar>xa - y\<bar>)"
      using \<open>?L \<ge> 0\<close> by auto}
  thus "\<exists>u>0. (\<exists>ta. \<bar>t - ta\<bar> \<le> u) \<longrightarrow>
    (\<exists>L\<ge>0. \<forall>xa\<in>cball x u. \<forall>y\<in>cball x u. \<parallel>f xa - f y\<parallel> \<le> L * \<bar>xa - y\<bar>)"
    by (rule_tac x=1 in exI, auto)
qed

end