Theory Integration

theory Integration
imports Derivative
(*  Author:     John Harrison
    Author:     Robert Himmelmann, TU Muenchen (Translation from HOL light); proofs reworked by LCP
*)

section ‹Kurzweil-Henstock Gauge Integration in many dimensions.›

theory Integration
imports
  Derivative
  Uniform_Limit
  "~~/src/HOL/Library/Indicator_Function"
begin

lemmas scaleR_simps = scaleR_zero_left scaleR_minus_left scaleR_left_diff_distrib
  scaleR_zero_right scaleR_minus_right scaleR_right_diff_distrib scaleR_eq_0_iff
  scaleR_cancel_left scaleR_cancel_right scaleR_add_right scaleR_add_left real_vector_class.scaleR_one


subsection ‹Sundries›

lemma conjunctD2: assumes "a ∧ b" shows a b using assms by auto
lemma conjunctD3: assumes "a ∧ b ∧ c" shows a b c using assms by auto
lemma conjunctD4: assumes "a ∧ b ∧ c ∧ d" shows a b c d using assms by auto

declare norm_triangle_ineq4[intro]

lemma simple_image: "{f x |x . x ∈ s} = f ` s"
  by blast

lemma linear_simps:
  assumes "bounded_linear f"
  shows
    "f (a + b) = f a + f b"
    "f (a - b) = f a - f b"
    "f 0 = 0"
    "f (- a) = - f a"
    "f (s *R v) = s *R (f v)"
proof -
  interpret f: bounded_linear f by fact
  show "f (a + b) = f a + f b" by (rule f.add)
  show "f (a - b) = f a - f b" by (rule f.diff)
  show "f 0 = 0" by (rule f.zero)
  show "f (- a) = - f a" by (rule f.minus)
  show "f (s *R v) = s *R (f v)" by (rule f.scaleR)
qed

lemma bounded_linearI:
  assumes "⋀x y. f (x + y) = f x + f y"
    and "⋀r x. f (r *R x) = r *R f x"
    and "⋀x. norm (f x) ≤ norm x * K"
  shows "bounded_linear f"
  using assms by (rule bounded_linear_intro) (* FIXME: duplicate *)

lemma bounded_linear_component [intro]: "bounded_linear (λx::'a::euclidean_space. x ∙ k)"
  by (rule bounded_linear_inner_left)

lemma transitive_stepwise_lt_eq:
  assumes "(⋀x y z::nat. R x y ⟹ R y z ⟹ R x z)"
  shows "((∀m. ∀n>m. R m n) ⟷ (∀n. R n (Suc n)))"
  (is "?l = ?r")
proof safe
  assume ?r
  fix n m :: nat
  assume "m < n"
  then show "R m n"
  proof (induct n arbitrary: m)
    case 0
    then show ?case by auto
  next
    case (Suc n)
    show ?case
    proof (cases "m < n")
      case True
      show ?thesis
        apply (rule assms[OF Suc(1)[OF True]])
        using ‹?r›
        apply auto
        done
    next
      case False
      then have "m = n"
        using Suc(2) by auto
      then show ?thesis
        using ‹?r› by auto
    qed
  qed
qed auto

lemma transitive_stepwise_gt:
  assumes "⋀x y z. R x y ⟹ R y z ⟹ R x z" "⋀n. R n (Suc n)"
  shows "∀n>m. R m n"
proof -
  have "∀m. ∀n>m. R m n"
    apply (subst transitive_stepwise_lt_eq)
    apply (blast intro: assms)+
    done
  then show ?thesis by auto
qed

lemma transitive_stepwise_le_eq:
  assumes "⋀x. R x x" "⋀x y z. R x y ⟹ R y z ⟹ R x z"
  shows "(∀m. ∀n≥m. R m n) ⟷ (∀n. R n (Suc n))"
  (is "?l = ?r")
proof safe
  assume ?r
  fix m n :: nat
  assume "m ≤ n"
  then show "R m n"
  proof (induct n arbitrary: m)
    case 0
    with assms show ?case by auto
  next
    case (Suc n)
    show ?case
    proof (cases "m ≤ n")
      case True
      with Suc.hyps ‹∀n. R n (Suc n)› assms show ?thesis
        by blast
    next
      case False
      then have "m = Suc n"
        using Suc(2) by auto
      then show ?thesis
        using assms(1) by auto
    qed
  qed
qed auto

lemma transitive_stepwise_le:
  assumes "⋀x. R x x" "⋀x y z. R x y ⟹ R y z ⟹ R x z"
    and "⋀n. R n (Suc n)"
  shows "∀n≥m. R m n"
proof -
  have "∀m. ∀n≥m. R m n"
    apply (subst transitive_stepwise_le_eq)
    apply (blast intro: assms)+
    done
  then show ?thesis by auto
qed


subsection ‹Some useful lemmas about intervals.›

lemma empty_as_interval: "{} = cbox One (0::'a::euclidean_space)"
  using nonempty_Basis
  by (fastforce simp add: set_eq_iff mem_box)

lemma interior_subset_union_intervals:
  assumes "i = cbox a b"
    and "j = cbox c d"
    and "interior j ≠ {}"
    and "i ⊆ j ∪ s"
    and "interior i ∩ interior j = {}"
  shows "interior i ⊆ interior s"
proof -
  have "box a b ∩ cbox c d = {}"
     using inter_interval_mixed_eq_empty[of c d a b] and assms(3,5)
     unfolding assms(1,2) interior_cbox by auto
  moreover
  have "box a b ⊆ cbox c d ∪ s"
    apply (rule order_trans,rule box_subset_cbox)
    using assms(4) unfolding assms(1,2)
    apply auto
    done
  ultimately
  show ?thesis
    unfolding assms interior_cbox
      by auto (metis IntI UnE empty_iff interior_maximal open_box subsetCE subsetI)
qed

lemma inter_interior_unions_intervals:
  fixes f::"('a::euclidean_space) set set"
  assumes "finite f"
    and "open s"
    and "∀t∈f. ∃a b. t = cbox a b"
    and "∀t∈f. s ∩ (interior t) = {}"
  shows "s ∩ interior (⋃f) = {}"
proof (clarsimp simp only: all_not_in_conv [symmetric])
  fix x
  assume x: "x ∈ s" "x ∈ interior (⋃f)"
  have lem1: "⋀x e s U. ball x e ⊆ s ∩ interior U ⟷ ball x e ⊆ s ∩ U"
    using interior_subset
    by auto (meson Topology_Euclidean_Space.open_ball contra_subsetD interior_maximal mem_ball)
  have "∃t∈f. ∃x. ∃e>0. ball x e ⊆ s ∩ t"
    if "finite f" and "∀t∈f. ∃a b. t = cbox a b" and "∃x. x ∈ s ∩ interior (⋃f)" for f
    using that
  proof (induct rule: finite_induct)
    case empty
    obtain x where "x ∈ s ∩ interior (⋃{})"
      using empty(2) ..
    then have False
      unfolding Union_empty interior_empty by auto
    then show ?case by auto
  next
    case (insert i f)
    obtain x where x: "x ∈ s ∩ interior (⋃insert i f)"
      using insert(5) ..
    then obtain e where e: "0 < e ∧ ball x e ⊆ s ∩ interior (⋃insert i f)"
      unfolding open_contains_ball_eq[OF open_Int[OF assms(2) open_interior], rule_format] ..
    obtain a where "∃b. i = cbox a b"
      using insert(4)[rule_format,OF insertI1] ..
    then obtain b where ab: "i = cbox a b" ..
    show ?case
    proof (cases "x ∈ i")
      case False
      then have "x ∈ UNIV - cbox a b"
        unfolding ab by auto
      then obtain d where "0 < d ∧ ball x d ⊆ UNIV - cbox a b"
        unfolding open_contains_ball_eq[OF open_Diff[OF open_UNIV closed_cbox],rule_format] ..
      then have "0 < d" "ball x (min d e) ⊆ UNIV - i"
        unfolding ab ball_min_Int by auto
      then have "ball x (min d e) ⊆ s ∩ interior (⋃f)"
        using e unfolding lem1 unfolding  ball_min_Int by auto
      then have "x ∈ s ∩ interior (⋃f)" using ‹d>0› e by auto
      then have "∃t∈f. ∃x e. 0 < e ∧ ball x e ⊆ s ∩ t"
        using insert.hyps(3) insert.prems(1) by blast
      then show ?thesis by auto
    next
      case True show ?thesis
      proof (cases "x∈box a b")
        case True
        then obtain d where "0 < d ∧ ball x d ⊆ box a b"
          unfolding open_contains_ball_eq[OF open_box,rule_format] ..
        then show ?thesis
          apply (rule_tac x=i in bexI, rule_tac x=x in exI, rule_tac x="min d e" in exI)
          unfolding ab
          using box_subset_cbox[of a b] and e
          apply fastforce+
          done
      next
        case False
        then obtain k where "x∙k ≤ a∙k ∨ x∙k ≥ b∙k" and k: "k ∈ Basis"
          unfolding mem_box by (auto simp add: not_less)
        then have "x∙k = a∙k ∨ x∙k = b∙k"
          using True unfolding ab and mem_box
            apply (erule_tac x = k in ballE)
            apply auto
            done
        then have "∃x. ball x (e/2) ⊆ s ∩ (⋃f)"
        proof (rule disjE)
          let ?z = "x - (e/2) *R k"
          assume as: "x∙k = a∙k"
          have "ball ?z (e / 2) ∩ i = {}"
          proof (clarsimp simp only: all_not_in_conv [symmetric])
            fix y
            assume "y ∈ ball ?z (e / 2)" and yi: "y ∈ i"
            then have "dist ?z y < e/2" by auto
            then have "¦(?z - y) ∙ k¦ < e/2"
              using Basis_le_norm[OF k, of "?z - y"] unfolding dist_norm by auto
            then have "y∙k < a∙k"
              using e k
              by (auto simp add: field_simps abs_less_iff as inner_simps)
            then have "y ∉ i"
              unfolding ab mem_box by (auto intro!: bexI[OF _ k])
            then show False using yi by auto
          qed
          moreover
          have "ball ?z (e/2) ⊆ s ∩ (⋃insert i f)"
            apply (rule order_trans[OF _ e[THEN conjunct2, unfolded lem1]])
          proof
            fix y
            assume as: "y ∈ ball ?z (e/2)"
            have "norm (x - y) ≤ ¦e¦ / 2 + norm (x - y - (e / 2) *R k)"
              apply (rule order_trans,rule norm_triangle_sub[of "x - y" "(e/2) *R k"])
              unfolding norm_scaleR norm_Basis[OF k]
              apply auto
              done
            also have "… < ¦e¦ / 2 + ¦e¦ / 2"
              apply (rule add_strict_left_mono)
              using as e
              apply (auto simp add: field_simps dist_norm)
              done
            finally show "y ∈ ball x e"
              unfolding mem_ball dist_norm using e by (auto simp add:field_simps)
          qed
          ultimately show ?thesis
            apply (rule_tac x="?z" in exI)
            unfolding Union_insert
            apply auto
            done
        next
          let ?z = "x + (e/2) *R k"
          assume as: "x∙k = b∙k"
          have "ball ?z (e / 2) ∩ i = {}"
          proof (clarsimp simp only: all_not_in_conv [symmetric])
            fix y
            assume "y ∈ ball ?z (e / 2)" and yi: "y ∈ i"
            then have "dist ?z y < e/2"
              by auto
            then have "¦(?z - y) ∙ k¦ < e/2"
              using Basis_le_norm[OF k, of "?z - y"]
              unfolding dist_norm by auto
            then have "y∙k > b∙k"
              using e k
              by (auto simp add:field_simps inner_simps inner_Basis as)
            then have "y ∉ i"
              unfolding ab mem_box by (auto intro!: bexI[OF _ k])
            then show False using yi by auto
          qed
          moreover
          have "ball ?z (e/2) ⊆ s ∩ (⋃insert i f)"
            apply (rule order_trans[OF _ e[THEN conjunct2, unfolded lem1]])
          proof
            fix y
            assume as: "y∈ ball ?z (e/2)"
            have "norm (x - y) ≤ ¦e¦ / 2 + norm (x - y + (e / 2) *R k)"
              apply (rule order_trans,rule norm_triangle_sub[of "x - y" "- (e/2) *R k"])
              unfolding norm_scaleR
              apply (auto simp: k)
              done
            also have "… < ¦e¦ / 2 + ¦e¦ / 2"
              apply (rule add_strict_left_mono)
              using as unfolding mem_ball dist_norm
              using e apply (auto simp add: field_simps)
              done
            finally show "y ∈ ball x e"
              unfolding mem_ball dist_norm using e by (auto simp add:field_simps)
          qed
          ultimately show ?thesis
            apply (rule_tac x="?z" in exI)
            unfolding Union_insert
            apply auto
            done
        qed
        then obtain x where "ball x (e / 2) ⊆ s ∩ ⋃f" ..
        then have "x ∈ s ∩ interior (⋃f)"
          unfolding lem1[where U="⋃f", symmetric]
          using centre_in_ball e by auto
        then show ?thesis
          using insert.hyps(3) insert.prems(1) by blast
      qed
    qed
  qed
  from this[OF assms(1,3)] x
  obtain t x e where "t ∈ f" "0 < e" "ball x e ⊆ s ∩ t"
    by blast
  then have "x ∈ s" "x ∈ interior t"
    using open_subset_interior[OF open_ball, of x e t]
    by auto
  then show False
    using ‹t ∈ f› assms(4) by auto
qed

subsection ‹Bounds on intervals where they exist.›

definition interval_upperbound :: "('a::euclidean_space) set ⇒ 'a"
  where "interval_upperbound s = (∑i∈Basis. (SUP x:s. x∙i) *R i)"

definition interval_lowerbound :: "('a::euclidean_space) set ⇒ 'a"
   where "interval_lowerbound s = (∑i∈Basis. (INF x:s. x∙i) *R i)"

lemma interval_upperbound[simp]:
  "∀i∈Basis. a∙i ≤ b∙i ⟹
    interval_upperbound (cbox a b) = (b::'a::euclidean_space)"
  unfolding interval_upperbound_def euclidean_representation_setsum cbox_def
  by (safe intro!: cSup_eq) auto

lemma interval_lowerbound[simp]:
  "∀i∈Basis. a∙i ≤ b∙i ⟹
    interval_lowerbound (cbox a b) = (a::'a::euclidean_space)"
  unfolding interval_lowerbound_def euclidean_representation_setsum cbox_def
  by (safe intro!: cInf_eq) auto

lemmas interval_bounds = interval_upperbound interval_lowerbound

lemma
  fixes X::"real set"
  shows interval_upperbound_real[simp]: "interval_upperbound X = Sup X"
    and interval_lowerbound_real[simp]: "interval_lowerbound X = Inf X"
  by (auto simp: interval_upperbound_def interval_lowerbound_def)

lemma interval_bounds'[simp]:
  assumes "cbox a b ≠ {}"
  shows "interval_upperbound (cbox a b) = b"
    and "interval_lowerbound (cbox a b) = a"
  using assms unfolding box_ne_empty by auto


lemma interval_upperbound_Times:
  assumes "A ≠ {}" and "B ≠ {}"
  shows "interval_upperbound (A × B) = (interval_upperbound A, interval_upperbound B)"
proof-
  from assms have fst_image_times': "A = fst ` (A × B)" by simp
  have "(∑i∈Basis. (SUP x:A × B. x ∙ (i, 0)) *R i) = (∑i∈Basis. (SUP x:A. x ∙ i) *R i)"
      by (subst (2) fst_image_times') (simp del: fst_image_times add: o_def inner_Pair_0)
  moreover from assms have snd_image_times': "B = snd ` (A × B)" by simp
  have "(∑i∈Basis. (SUP x:A × B. x ∙ (0, i)) *R i) = (∑i∈Basis. (SUP x:B. x ∙ i) *R i)"
      by (subst (2) snd_image_times') (simp del: snd_image_times add: o_def inner_Pair_0)
  ultimately show ?thesis unfolding interval_upperbound_def
      by (subst setsum_Basis_prod_eq) (auto simp add: setsum_prod)
qed

lemma interval_lowerbound_Times:
  assumes "A ≠ {}" and "B ≠ {}"
  shows "interval_lowerbound (A × B) = (interval_lowerbound A, interval_lowerbound B)"
proof-
  from assms have fst_image_times': "A = fst ` (A × B)" by simp
  have "(∑i∈Basis. (INF x:A × B. x ∙ (i, 0)) *R i) = (∑i∈Basis. (INF x:A. x ∙ i) *R i)"
      by (subst (2) fst_image_times') (simp del: fst_image_times add: o_def inner_Pair_0)
  moreover from assms have snd_image_times': "B = snd ` (A × B)" by simp
  have "(∑i∈Basis. (INF x:A × B. x ∙ (0, i)) *R i) = (∑i∈Basis. (INF x:B. x ∙ i) *R i)"
      by (subst (2) snd_image_times') (simp del: snd_image_times add: o_def inner_Pair_0)
  ultimately show ?thesis unfolding interval_lowerbound_def
      by (subst setsum_Basis_prod_eq) (auto simp add: setsum_prod)
qed

subsection ‹Content (length, area, volume...) of an interval.›

definition "content (s::('a::euclidean_space) set) =
  (if s = {} then 0 else (∏i∈Basis. (interval_upperbound s)∙i - (interval_lowerbound s)∙i))"

lemma interval_not_empty: "∀i∈Basis. a∙i ≤ b∙i ⟹ cbox a b ≠ {}"
  unfolding box_eq_empty unfolding not_ex not_less by auto

lemma content_cbox:
  fixes a :: "'a::euclidean_space"
  assumes "∀i∈Basis. a∙i ≤ b∙i"
  shows "content (cbox a b) = (∏i∈Basis. b∙i - a∙i)"
  using interval_not_empty[OF assms]
  unfolding content_def
  by auto

lemma content_cbox':
  fixes a :: "'a::euclidean_space"
  assumes "cbox a b ≠ {}"
  shows "content (cbox a b) = (∏i∈Basis. b∙i - a∙i)"
    using assms box_ne_empty(1) content_cbox by blast

lemma content_real: "a ≤ b ⟹ content {a..b} = b - a"
  by (auto simp: interval_upperbound_def interval_lowerbound_def content_def)

lemma abs_eq_content: "¦y - x¦ = (if x≤y then content {x .. y} else content {y..x})"
  by (auto simp: content_real)

lemma content_singleton[simp]: "content {a} = 0"
proof -
  have "content (cbox a a) = 0"
    by (subst content_cbox) (auto simp: ex_in_conv)
  then show ?thesis by (simp add: cbox_sing)
qed

lemma content_unit[iff]: "content(cbox 0 (One::'a::euclidean_space)) = 1"
 proof -
   have *: "∀i∈Basis. (0::'a)∙i ≤ (One::'a)∙i"
    by auto
  have "0 ∈ cbox 0 (One::'a)"
    unfolding mem_box by auto
  then show ?thesis
     unfolding content_def interval_bounds[OF *] using setprod.neutral_const by auto
 qed

lemma content_pos_le[intro]:
  fixes a::"'a::euclidean_space"
  shows "0 ≤ content (cbox a b)"
proof (cases "cbox a b = {}")
  case False
  then have *: "∀i∈Basis. a ∙ i ≤ b ∙ i"
    unfolding box_ne_empty .
  have "0 ≤ (∏i∈Basis. interval_upperbound (cbox a b) ∙ i - interval_lowerbound (cbox a b) ∙ i)"
    apply (rule setprod_nonneg)
    unfolding interval_bounds[OF *]
    using *
    apply auto
    done
  also have "… = content (cbox a b)" using False by (simp add: content_def)
  finally show ?thesis .
qed (simp add: content_def)

corollary content_nonneg [simp]:
  fixes a::"'a::euclidean_space"
  shows "~ content (cbox a b) < 0"
using not_le by blast

lemma content_pos_lt:
  fixes a :: "'a::euclidean_space"
  assumes "∀i∈Basis. a∙i < b∙i"
  shows "0 < content (cbox a b)"
  using assms
  by (auto simp: content_def box_eq_empty intro!: setprod_pos)

lemma content_eq_0:
  "content (cbox a b) = 0 ⟷ (∃i∈Basis. b∙i ≤ a∙i)"
  by (auto simp: content_def box_eq_empty intro!: setprod_pos bexI)

lemma cond_cases: "(P ⟹ Q x) ⟹ (¬ P ⟹ Q y) ⟹ Q (if P then x else y)"
  by auto

lemma content_cbox_cases:
  "content (cbox a (b::'a::euclidean_space)) =
    (if ∀i∈Basis. a∙i ≤ b∙i then setprod (λi. b∙i - a∙i) Basis else 0)"
  by (auto simp: not_le content_eq_0 intro: less_imp_le content_cbox)

lemma content_eq_0_interior: "content (cbox a b) = 0 ⟷ interior(cbox a b) = {}"
  unfolding content_eq_0 interior_cbox box_eq_empty
  by auto

lemma content_pos_lt_eq:
  "0 < content (cbox a (b::'a::euclidean_space)) ⟷ (∀i∈Basis. a∙i < b∙i)"
proof (rule iffI)
  assume "0 < content (cbox a b)"
  then have "content (cbox a b) ≠ 0" by auto
  then show "∀i∈Basis. a∙i < b∙i"
    unfolding content_eq_0 not_ex not_le by fastforce
next
  assume "∀i∈Basis. a ∙ i < b ∙ i"
  then show "0 < content (cbox a b)"
    by (metis content_pos_lt)
qed

lemma content_empty [simp]: "content {} = 0"
  unfolding content_def by auto

lemma content_real_if [simp]: "content {a..b} = (if a ≤ b then b - a else 0)"
  by (simp add: content_real)

lemma content_subset:
  assumes "cbox a b ⊆ cbox c d"
  shows "content (cbox a b) ≤ content (cbox c d)"
proof (cases "cbox a b = {}")
  case True
  then show ?thesis
    using content_pos_le[of c d] by auto
next
  case False
  then have ab_ne: "∀i∈Basis. a ∙ i ≤ b ∙ i"
    unfolding box_ne_empty by auto
  then have ab_ab: "a∈cbox a b" "b∈cbox a b"
    unfolding mem_box by auto
  have "cbox c d ≠ {}" using assms False by auto
  then have cd_ne: "∀i∈Basis. c ∙ i ≤ d ∙ i"
    using assms unfolding box_ne_empty by auto
  have "⋀i. i ∈ Basis ⟹ 0 ≤ b ∙ i - a ∙ i"
    using ab_ne by auto
  moreover
  have "⋀i. i ∈ Basis ⟹ b ∙ i - a ∙ i ≤ d ∙ i - c ∙ i"
    using assms[unfolded subset_eq mem_box,rule_format,OF ab_ab(2)]
          assms[unfolded subset_eq mem_box,rule_format,OF ab_ab(1)]
      by (metis diff_mono)
  ultimately show ?thesis
    unfolding content_def interval_bounds[OF ab_ne] interval_bounds[OF cd_ne]
    by (simp add: setprod_mono if_not_P[OF False] if_not_P[OF ‹cbox c d ≠ {}›])
qed

lemma content_lt_nz: "0 < content (cbox a b) ⟷ content (cbox a b) ≠ 0"
  unfolding content_pos_lt_eq content_eq_0 unfolding not_ex not_le by fastforce

lemma content_times[simp]: "content (A × B) = content A * content B"
proof (cases "A × B = {}")
  let ?ub1 = "interval_upperbound" and ?lb1 = "interval_lowerbound"
  let ?ub2 = "interval_upperbound" and ?lb2 = "interval_lowerbound"
  assume nonempty: "A × B ≠ {}"
  hence "content (A × B) = (∏i∈Basis. (?ub1 A, ?ub2 B) ∙ i - (?lb1 A, ?lb2 B) ∙ i)"
      unfolding content_def by (simp add: interval_upperbound_Times interval_lowerbound_Times)
  also have "... = content A * content B" unfolding content_def using nonempty
    apply (subst Basis_prod_def, subst setprod.union_disjoint, force, force, force, simp)
    apply (subst (1 2) setprod.reindex, auto intro: inj_onI)
    done
  finally show ?thesis .
qed (auto simp: content_def)

lemma content_Pair: "content (cbox (a,c) (b,d)) = content (cbox a b) * content (cbox c d)"
  by (simp add: cbox_Pair_eq)

lemma content_cbox_pair_eq0_D:
   "content (cbox (a,c) (b,d)) = 0 ⟹ content (cbox a b) = 0 ∨ content (cbox c d) = 0"
  by (simp add: content_Pair)

lemma content_eq_0_gen:
  fixes s :: "'a::euclidean_space set"
  assumes "bounded s"
  shows "content s = 0 ⟷ (∃i∈Basis. ∃v. ∀x ∈ s. x ∙ i = v)"  (is "_ = ?rhs")
proof safe
  assume "content s = 0" then show ?rhs
    apply (clarsimp simp: ex_in_conv content_def split: if_split_asm)
    apply (rule_tac x=a in bexI)
    apply (rule_tac x="interval_lowerbound s ∙ a" in exI)
    apply (clarsimp simp: interval_upperbound_def interval_lowerbound_def)
    apply (drule cSUP_eq_cINF_D)
    apply (auto simp: bounded_inner_imp_bdd_above [OF assms]  bounded_inner_imp_bdd_below [OF assms])
    done
next
  fix i a
  assume "i ∈ Basis" "∀x∈s. x ∙ i = a"
  then show "content s = 0"
    apply (clarsimp simp: content_def)
    apply (rule_tac x=i in bexI)
    apply (auto simp: interval_upperbound_def interval_lowerbound_def)
    done
qed

lemma content_0_subset_gen:
  fixes a :: "'a::euclidean_space"
  assumes "content t = 0" "s ⊆ t" "bounded t" shows "content s = 0"
proof -
  have "bounded s"
    using assms by (metis bounded_subset)
  then show ?thesis
    using assms
    by (auto simp: content_eq_0_gen)
qed

lemma content_0_subset: "⟦content(cbox a b) = 0; s ⊆ cbox a b⟧ ⟹ content s = 0"
  by (simp add: content_0_subset_gen bounded_cbox)


subsection ‹The notion of a gauge --- simply an open set containing the point.›

definition "gauge d ⟷ (∀x. x ∈ d x ∧ open (d x))"

lemma gaugeI:
  assumes "⋀x. x ∈ g x"
    and "⋀x. open (g x)"
  shows "gauge g"
  using assms unfolding gauge_def by auto

lemma gaugeD[dest]:
  assumes "gauge d"
  shows "x ∈ d x"
    and "open (d x)"
  using assms unfolding gauge_def by auto

lemma gauge_ball_dependent: "∀x. 0 < e x ⟹ gauge (λx. ball x (e x))"
  unfolding gauge_def by auto

lemma gauge_ball[intro]: "0 < e ⟹ gauge (λx. ball x e)"
  unfolding gauge_def by auto

lemma gauge_trivial[intro!]: "gauge (λx. ball x 1)"
  by (rule gauge_ball) auto

lemma gauge_inter[intro]: "gauge d1 ⟹ gauge d2 ⟹ gauge (λx. d1 x ∩ d2 x)"
  unfolding gauge_def by auto

lemma gauge_inters:
  assumes "finite s"
    and "∀d∈s. gauge (f d)"
  shows "gauge (λx. ⋂{f d x | d. d ∈ s})"
proof -
  have *: "⋀x. {f d x |d. d ∈ s} = (λd. f d x) ` s"
    by auto
  show ?thesis
    unfolding gauge_def unfolding *
    using assms unfolding Ball_def Inter_iff mem_Collect_eq gauge_def by auto
qed

lemma gauge_existence_lemma:
  "(∀x. ∃d :: real. p x ⟶ 0 < d ∧ q d x) ⟷ (∀x. ∃d>0. p x ⟶ q d x)"
  by (metis zero_less_one)


subsection ‹Divisions.›

definition division_of (infixl "division'_of" 40)
where
  "s division_of i ⟷
    finite s ∧
    (∀k∈s. k ⊆ i ∧ k ≠ {} ∧ (∃a b. k = cbox a b)) ∧
    (∀k1∈s. ∀k2∈s. k1 ≠ k2 ⟶ interior(k1) ∩ interior(k2) = {}) ∧
    (⋃s = i)"

lemma division_ofD[dest]:
  assumes "s division_of i"
  shows "finite s"
    and "⋀k. k ∈ s ⟹ k ⊆ i"
    and "⋀k. k ∈ s ⟹ k ≠ {}"
    and "⋀k. k ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀k1 k2. k1 ∈ s ⟹ k2 ∈ s ⟹ k1 ≠ k2 ⟹ interior(k1) ∩ interior(k2) = {}"
    and "⋃s = i"
  using assms unfolding division_of_def by auto

lemma division_ofI:
  assumes "finite s"
    and "⋀k. k ∈ s ⟹ k ⊆ i"
    and "⋀k. k ∈ s ⟹ k ≠ {}"
    and "⋀k. k ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀k1 k2. k1 ∈ s ⟹ k2 ∈ s ⟹ k1 ≠ k2 ⟹ interior k1 ∩ interior k2 = {}"
    and "⋃s = i"
  shows "s division_of i"
  using assms unfolding division_of_def by auto

lemma division_of_finite: "s division_of i ⟹ finite s"
  unfolding division_of_def by auto

lemma division_of_self[intro]: "cbox a b ≠ {} ⟹ {cbox a b} division_of (cbox a b)"
  unfolding division_of_def by auto

lemma division_of_trivial[simp]: "s division_of {} ⟷ s = {}"
  unfolding division_of_def by auto

lemma division_of_sing[simp]:
  "s division_of cbox a (a::'a::euclidean_space) ⟷ s = {cbox a a}"
  (is "?l = ?r")
proof
  assume ?r
  moreover
  { fix k
    assume "s = {{a}}" "k∈s"
    then have "∃x y. k = cbox x y"
      apply (rule_tac x=a in exI)+
      apply (force simp: cbox_sing)
      done
  }
  ultimately show ?l
    unfolding division_of_def cbox_sing by auto
next
  assume ?l
  note * = conjunctD4[OF this[unfolded division_of_def cbox_sing]]
  {
    fix x
    assume x: "x ∈ s" have "x = {a}"
      using *(2)[rule_format,OF x] by auto
  }
  moreover have "s ≠ {}"
    using *(4) by auto
  ultimately show ?r
    unfolding cbox_sing by auto
qed

lemma elementary_empty: obtains p where "p division_of {}"
  unfolding division_of_trivial by auto

lemma elementary_interval: obtains p where "p division_of (cbox a b)"
  by (metis division_of_trivial division_of_self)

lemma division_contains: "s division_of i ⟹ ∀x∈i. ∃k∈s. x ∈ k"
  unfolding division_of_def by auto

lemma forall_in_division:
  "d division_of i ⟹ (∀x∈d. P x) ⟷ (∀a b. cbox a b ∈ d ⟶ P (cbox a b))"
  unfolding division_of_def by fastforce

lemma division_of_subset:
  assumes "p division_of (⋃p)"
    and "q ⊆ p"
  shows "q division_of (⋃q)"
proof (rule division_ofI)
  note * = division_ofD[OF assms(1)]
  show "finite q"
    using "*"(1) assms(2) infinite_super by auto
  {
    fix k
    assume "k ∈ q"
    then have kp: "k ∈ p"
      using assms(2) by auto
    show "k ⊆ ⋃q"
      using ‹k ∈ q› by auto
    show "∃a b. k = cbox a b"
      using *(4)[OF kp] by auto
    show "k ≠ {}"
      using *(3)[OF kp] by auto
  }
  fix k1 k2
  assume "k1 ∈ q" "k2 ∈ q" "k1 ≠ k2"
  then have **: "k1 ∈ p" "k2 ∈ p" "k1 ≠ k2"
    using assms(2) by auto
  show "interior k1 ∩ interior k2 = {}"
    using *(5)[OF **] by auto
qed auto

lemma division_of_union_self[intro]: "p division_of s ⟹ p division_of (⋃p)"
  unfolding division_of_def by auto

lemma division_of_content_0:
  assumes "content (cbox a b) = 0" "d division_of (cbox a b)"
  shows "∀k∈d. content k = 0"
  unfolding forall_in_division[OF assms(2)]
  by (metis antisym_conv assms content_pos_le content_subset division_ofD(2))

lemma division_inter:
  fixes s1 s2 :: "'a::euclidean_space set"
  assumes "p1 division_of s1"
    and "p2 division_of s2"
  shows "{k1 ∩ k2 | k1 k2 .k1 ∈ p1 ∧ k2 ∈ p2 ∧ k1 ∩ k2 ≠ {}} division_of (s1 ∩ s2)"
  (is "?A' division_of _")
proof -
  let ?A = "{s. s ∈  (λ(k1,k2). k1 ∩ k2) ` (p1 × p2) ∧ s ≠ {}}"
  have *: "?A' = ?A" by auto
  show ?thesis
    unfolding *
  proof (rule division_ofI)
    have "?A ⊆ (λ(x, y). x ∩ y) ` (p1 × p2)"
      by auto
    moreover have "finite (p1 × p2)"
      using assms unfolding division_of_def by auto
    ultimately show "finite ?A" by auto
    have *: "⋀s. ⋃{x∈s. x ≠ {}} = ⋃s"
      by auto
    show "⋃?A = s1 ∩ s2"
      apply (rule set_eqI)
      unfolding * and UN_iff
      using division_ofD(6)[OF assms(1)] and division_ofD(6)[OF assms(2)]
      apply auto
      done
    {
      fix k
      assume "k ∈ ?A"
      then obtain k1 k2 where k: "k = k1 ∩ k2" "k1 ∈ p1" "k2 ∈ p2" "k ≠ {}"
        by auto
      then show "k ≠ {}"
        by auto
      show "k ⊆ s1 ∩ s2"
        using division_ofD(2)[OF assms(1) k(2)] and division_ofD(2)[OF assms(2) k(3)]
        unfolding k by auto
      obtain a1 b1 where k1: "k1 = cbox a1 b1"
        using division_ofD(4)[OF assms(1) k(2)] by blast
      obtain a2 b2 where k2: "k2 = cbox a2 b2"
        using division_ofD(4)[OF assms(2) k(3)] by blast
      show "∃a b. k = cbox a b"
        unfolding k k1 k2 unfolding inter_interval by auto
    }
    fix k1 k2
    assume "k1 ∈ ?A"
    then obtain x1 y1 where k1: "k1 = x1 ∩ y1" "x1 ∈ p1" "y1 ∈ p2" "k1 ≠ {}"
      by auto
    assume "k2 ∈ ?A"
    then obtain x2 y2 where k2: "k2 = x2 ∩ y2" "x2 ∈ p1" "y2 ∈ p2" "k2 ≠ {}"
      by auto
    assume "k1 ≠ k2"
    then have th: "x1 ≠ x2 ∨ y1 ≠ y2"
      unfolding k1 k2 by auto
    have *: "interior x1 ∩ interior x2 = {} ∨ interior y1 ∩ interior y2 = {} ⟹
      interior (x1 ∩ y1) ⊆ interior x1 ⟹ interior (x1 ∩ y1) ⊆ interior y1 ⟹
      interior (x2 ∩ y2) ⊆ interior x2 ⟹ interior (x2 ∩ y2) ⊆ interior y2 ⟹
      interior (x1 ∩ y1) ∩ interior (x2 ∩ y2) = {}" by auto
    show "interior k1 ∩ interior k2 = {}"
      unfolding k1 k2
      apply (rule *)
      using assms division_ofD(5) k1 k2(2) k2(3) th apply auto
      done
  qed
qed

lemma division_inter_1:
  assumes "d division_of i"
    and "cbox a (b::'a::euclidean_space) ⊆ i"
  shows "{cbox a b ∩ k | k. k ∈ d ∧ cbox a b ∩ k ≠ {}} division_of (cbox a b)"
proof (cases "cbox a b = {}")
  case True
  show ?thesis
    unfolding True and division_of_trivial by auto
next
  case False
  have *: "cbox a b ∩ i = cbox a b" using assms(2) by auto
  show ?thesis
    using division_inter[OF division_of_self[OF False] assms(1)]
    unfolding * by auto
qed

lemma elementary_inter:
  fixes s t :: "'a::euclidean_space set"
  assumes "p1 division_of s"
    and "p2 division_of t"
  shows "∃p. p division_of (s ∩ t)"
using assms division_inter by blast

lemma elementary_inters:
  assumes "finite f"
    and "f ≠ {}"
    and "∀s∈f. ∃p. p division_of (s::('a::euclidean_space) set)"
  shows "∃p. p division_of (⋂f)"
  using assms
proof (induct f rule: finite_induct)
  case (insert x f)
  show ?case
  proof (cases "f = {}")
    case True
    then show ?thesis
      unfolding True using insert by auto
  next
    case False
    obtain p where "p division_of ⋂f"
      using insert(3)[OF False insert(5)[unfolded ball_simps,THEN conjunct2]] ..
    moreover obtain px where "px division_of x"
      using insert(5)[rule_format,OF insertI1] ..
    ultimately show ?thesis
      by (simp add: elementary_inter Inter_insert)
  qed
qed auto

lemma division_disjoint_union:
  assumes "p1 division_of s1"
    and "p2 division_of s2"
    and "interior s1 ∩ interior s2 = {}"
  shows "(p1 ∪ p2) division_of (s1 ∪ s2)"
proof (rule division_ofI)
  note d1 = division_ofD[OF assms(1)]
  note d2 = division_ofD[OF assms(2)]
  show "finite (p1 ∪ p2)"
    using d1(1) d2(1) by auto
  show "⋃(p1 ∪ p2) = s1 ∪ s2"
    using d1(6) d2(6) by auto
  {
    fix k1 k2
    assume as: "k1 ∈ p1 ∪ p2" "k2 ∈ p1 ∪ p2" "k1 ≠ k2"
    moreover
    let ?g="interior k1 ∩ interior k2 = {}"
    {
      assume as: "k1∈p1" "k2∈p2"
      have ?g
        using interior_mono[OF d1(2)[OF as(1)]] interior_mono[OF d2(2)[OF as(2)]]
        using assms(3) by blast
    }
    moreover
    {
      assume as: "k1∈p2" "k2∈p1"
      have ?g
        using interior_mono[OF d1(2)[OF as(2)]] interior_mono[OF d2(2)[OF as(1)]]
        using assms(3) by blast
    }
    ultimately show ?g
      using d1(5)[OF _ _ as(3)] and d2(5)[OF _ _ as(3)] by auto
  }
  fix k
  assume k: "k ∈ p1 ∪ p2"
  show "k ⊆ s1 ∪ s2"
    using k d1(2) d2(2) by auto
  show "k ≠ {}"
    using k d1(3) d2(3) by auto
  show "∃a b. k = cbox a b"
    using k d1(4) d2(4) by auto
qed

lemma partial_division_extend_1:
  fixes a b c d :: "'a::euclidean_space"
  assumes incl: "cbox c d ⊆ cbox a b"
    and nonempty: "cbox c d ≠ {}"
  obtains p where "p division_of (cbox a b)" "cbox c d ∈ p"
proof
  let ?B = "λf::'a⇒'a × 'a.
    cbox (∑i∈Basis. (fst (f i) ∙ i) *R i) (∑i∈Basis. (snd (f i) ∙ i) *R i)"
  def p  "?B ` (Basis →E {(a, c), (c, d), (d, b)})"

  show "cbox c d ∈ p"
    unfolding p_def
    by (auto simp add: box_eq_empty cbox_def intro!: image_eqI[where x="λ(i::'a)∈Basis. (c, d)"])
  {
    fix i :: 'a
    assume "i ∈ Basis"
    with incl nonempty have "a ∙ i ≤ c ∙ i" "c ∙ i ≤ d ∙ i" "d ∙ i ≤ b ∙ i"
      unfolding box_eq_empty subset_box by (auto simp: not_le)
  }
  note ord = this

  show "p division_of (cbox a b)"
  proof (rule division_ofI)
    show "finite p"
      unfolding p_def by (auto intro!: finite_PiE)
    {
      fix k
      assume "k ∈ p"
      then obtain f where f: "f ∈ Basis →E {(a, c), (c, d), (d, b)}" and k: "k = ?B f"
        by (auto simp: p_def)
      then show "∃a b. k = cbox a b"
        by auto
      have "k ⊆ cbox a b ∧ k ≠ {}"
      proof (simp add: k box_eq_empty subset_box not_less, safe)
        fix i :: 'a
        assume i: "i ∈ Basis"
        with f have "f i = (a, c) ∨ f i = (c, d) ∨ f i = (d, b)"
          by (auto simp: PiE_iff)
        with i ord[of i]
        show "a ∙ i ≤ fst (f i) ∙ i" "snd (f i) ∙ i ≤ b ∙ i" "fst (f i) ∙ i ≤ snd (f i) ∙ i"
          by auto
      qed
      then show "k ≠ {}" "k ⊆ cbox a b"
        by auto
      {
        fix l
        assume "l ∈ p"
        then obtain g where g: "g ∈ Basis →E {(a, c), (c, d), (d, b)}" and l: "l = ?B g"
          by (auto simp: p_def)
        assume "l ≠ k"
        have "∃i∈Basis. f i ≠ g i"
        proof (rule ccontr)
          assume "¬ ?thesis"
          with f g have "f = g"
            by (auto simp: PiE_iff extensional_def intro!: ext)
          with ‹l ≠ k› show False
            by (simp add: l k)
        qed
        then obtain i where *: "i ∈ Basis" "f i ≠ g i" ..
        then have "f i = (a, c) ∨ f i = (c, d) ∨ f i = (d, b)"
                  "g i = (a, c) ∨ g i = (c, d) ∨ g i = (d, b)"
          using f g by (auto simp: PiE_iff)
        with * ord[of i] show "interior l ∩ interior k = {}"
          by (auto simp add: l k interior_cbox disjoint_interval intro!: bexI[of _ i])
      }
      note ‹k ⊆ cbox a b›
    }
    moreover
    {
      fix x assume x: "x ∈ cbox a b"
      have "∀i∈Basis. ∃l. x ∙ i ∈ {fst l ∙ i .. snd l ∙ i} ∧ l ∈ {(a, c), (c, d), (d, b)}"
      proof
        fix i :: 'a
        assume "i ∈ Basis"
        with x ord[of i]
        have "(a ∙ i ≤ x ∙ i ∧ x ∙ i ≤ c ∙ i) ∨ (c ∙ i ≤ x ∙ i ∧ x ∙ i ≤ d ∙ i) ∨
            (d ∙ i ≤ x ∙ i ∧ x ∙ i ≤ b ∙ i)"
          by (auto simp: cbox_def)
        then show "∃l. x ∙ i ∈ {fst l ∙ i .. snd l ∙ i} ∧ l ∈ {(a, c), (c, d), (d, b)}"
          by auto
      qed
      then obtain f where
        f: "∀i∈Basis. x ∙ i ∈ {fst (f i) ∙ i..snd (f i) ∙ i} ∧ f i ∈ {(a, c), (c, d), (d, b)}"
        unfolding bchoice_iff ..
      moreover from f have "restrict f Basis ∈ Basis →E {(a, c), (c, d), (d, b)}"
        by auto
      moreover from f have "x ∈ ?B (restrict f Basis)"
        by (auto simp: mem_box)
      ultimately have "∃k∈p. x ∈ k"
        unfolding p_def by blast
    }
    ultimately show "⋃p = cbox a b"
      by auto
  qed
qed

lemma partial_division_extend_interval:
  assumes "p division_of (⋃p)" "(⋃p) ⊆ cbox a b"
  obtains q where "p ⊆ q" "q division_of cbox a (b::'a::euclidean_space)"
proof (cases "p = {}")
  case True
  obtain q where "q division_of (cbox a b)"
    by (rule elementary_interval)
  then show ?thesis
    using True that by blast
next
  case False
  note p = division_ofD[OF assms(1)]
  have div_cbox: "∀k∈p. ∃q. q division_of cbox a b ∧ k ∈ q"
  proof
    fix k
    assume kp: "k ∈ p"
    obtain c d where k: "k = cbox c d"
      using p(4)[OF kp] by blast
    have *: "cbox c d ⊆ cbox a b" "cbox c d ≠ {}"
      using p(2,3)[OF kp, unfolded k] using assms(2)
      by (blast intro: order.trans)+
    obtain q where "q division_of cbox a b" "cbox c d ∈ q"
      by (rule partial_division_extend_1[OF *])
    then show "∃q. q division_of cbox a b ∧ k ∈ q"
      unfolding k by auto
  qed
  obtain q where q: "⋀x. x ∈ p ⟹ q x division_of cbox a b" "⋀x. x ∈ p ⟹ x ∈ q x"
    using bchoice[OF div_cbox] by blast
  { fix x
    assume x: "x ∈ p"
    have "q x division_of ⋃q x"
      apply (rule division_ofI)
      using division_ofD[OF q(1)[OF x]]
      apply auto
      done }
  then have "⋀x. x ∈ p ⟹ ∃d. d division_of ⋃(q x - {x})"
    by (meson Diff_subset division_of_subset)
  then have "∃d. d division_of ⋂((λi. ⋃(q i - {i})) ` p)"
    apply -
    apply (rule elementary_inters [OF finite_imageI[OF p(1)]])
    apply (auto simp: False elementary_inters [OF finite_imageI[OF p(1)]])
    done
  then obtain d where d: "d division_of ⋂((λi. ⋃(q i - {i})) ` p)" ..
  have "d ∪ p division_of cbox a b"
  proof -
    have te: "⋀s f t. s ≠ {} ⟹ ∀i∈s. f i ∪ i = t ⟹ t = ⋂(f ` s) ∪ ⋃s" by auto
    have cbox_eq: "cbox a b = ⋂((λi. ⋃(q i - {i})) ` p) ∪ ⋃p"
    proof (rule te[OF False], clarify)
      fix i
      assume i: "i ∈ p"
      show "⋃(q i - {i}) ∪ i = cbox a b"
        using division_ofD(6)[OF q(1)[OF i]] using q(2)[OF i] by auto
    qed
    { fix k
      assume k: "k ∈ p"
      have *: "⋀u t s. t ∩ s = {} ⟹ u ⊆ s ⟹ u ∩ t = {}"
        by auto
      have "interior (⋂i∈p. ⋃(q i - {i})) ∩ interior k = {}"
      proof (rule *[OF inter_interior_unions_intervals])
        note qk=division_ofD[OF q(1)[OF k]]
        show "finite (q k - {k})" "open (interior k)" "∀t∈q k - {k}. ∃a b. t = cbox a b"
          using qk by auto
        show "∀t∈q k - {k}. interior k ∩ interior t = {}"
          using qk(5) using q(2)[OF k] by auto
        show "interior (⋂i∈p. ⋃(q i - {i})) ⊆ interior (⋃(q k - {k}))"
          apply (rule interior_mono)+
          using k
          apply auto
          done
      qed } note [simp] = this
    show "d ∪ p division_of (cbox a b)"
      unfolding cbox_eq
      apply (rule division_disjoint_union[OF d assms(1)])
      apply (rule inter_interior_unions_intervals)
      apply (rule p open_interior ballI)+
      apply simp_all
      done
  qed
  then show ?thesis
    by (meson Un_upper2 that)
qed

lemma elementary_bounded[dest]:
  fixes s :: "'a::euclidean_space set"
  shows "p division_of s ⟹ bounded s"
  unfolding division_of_def by (metis bounded_Union bounded_cbox)

lemma elementary_subset_cbox:
  "p division_of s ⟹ ∃a b. s ⊆ cbox a (b::'a::euclidean_space)"
  by (meson elementary_bounded bounded_subset_cbox)

lemma division_union_intervals_exists:
  fixes a b :: "'a::euclidean_space"
  assumes "cbox a b ≠ {}"
  obtains p where "(insert (cbox a b) p) division_of (cbox a b ∪ cbox c d)"
proof (cases "cbox c d = {}")
  case True
  show ?thesis
    apply (rule that[of "{}"])
    unfolding True
    using assms
    apply auto
    done
next
  case False
  show ?thesis
  proof (cases "cbox a b ∩ cbox c d = {}")
    case True
    then show ?thesis
      by (metis that False assms division_disjoint_union division_of_self insert_is_Un interior_Int interior_empty)
  next
    case False
    obtain u v where uv: "cbox a b ∩ cbox c d = cbox u v"
      unfolding inter_interval by auto
    have uv_sub: "cbox u v ⊆ cbox c d" using uv by auto
    obtain p where "p division_of cbox c d" "cbox u v ∈ p"
      by (rule partial_division_extend_1[OF uv_sub False[unfolded uv]])
    note p = this division_ofD[OF this(1)]
    have "interior (cbox a b ∩ ⋃(p - {cbox u v})) = interior(cbox u v ∩ ⋃(p - {cbox u v}))"
      apply (rule arg_cong[of _ _ interior])
      using p(8) uv by auto
    also have "… = {}"
      unfolding interior_Int
      apply (rule inter_interior_unions_intervals)
      using p(6) p(7)[OF p(2)] p(3)
      apply auto
      done
    finally have [simp]: "interior (cbox a b) ∩ interior (⋃(p - {cbox u v})) = {}" by simp
    have cbe: "cbox a b ∪ cbox c d = cbox a b ∪ ⋃(p - {cbox u v})"
      using p(8) unfolding uv[symmetric] by auto
    have "insert (cbox a b) (p - {cbox u v}) division_of cbox a b ∪ ⋃(p - {cbox u v})"
    proof -
      have "{cbox a b} division_of cbox a b"
        by (simp add: assms division_of_self)
      then show "insert (cbox a b) (p - {cbox u v}) division_of cbox a b ∪ ⋃(p - {cbox u v})"
        by (metis (no_types) Diff_subset ‹interior (cbox a b) ∩ interior (⋃(p - {cbox u v})) = {}› division_disjoint_union division_of_subset insert_is_Un p(1) p(8))
    qed
    with that[of "p - {cbox u v}"] show ?thesis by (simp add: cbe)
  qed
qed

lemma division_of_unions:
  assumes "finite f"
    and "⋀p. p ∈ f ⟹ p division_of (⋃p)"
    and "⋀k1 k2. k1 ∈ ⋃f ⟹ k2 ∈ ⋃f ⟹ k1 ≠ k2 ⟹ interior k1 ∩ interior k2 = {}"
  shows "⋃f division_of ⋃⋃f"
  using assms
  by (auto intro!: division_ofI)

lemma elementary_union_interval:
  fixes a b :: "'a::euclidean_space"
  assumes "p division_of ⋃p"
  obtains q where "q division_of (cbox a b ∪ ⋃p)"
proof -
  note assm = division_ofD[OF assms]
  have lem1: "⋀f s. ⋃⋃(f ` s) = ⋃((λx. ⋃(f x)) ` s)"
    by auto
  have lem2: "⋀f s. f ≠ {} ⟹ ⋃{s ∪ t |t. t ∈ f} = s ∪ ⋃f"
    by auto
  {
    presume "p = {} ⟹ thesis"
      "cbox a b = {} ⟹ thesis"
      "cbox a b ≠ {} ⟹ interior (cbox a b) = {} ⟹ thesis"
      "p ≠ {} ⟹ interior (cbox a b)≠{} ⟹ cbox a b ≠ {} ⟹ thesis"
    then show thesis by auto
  next
    assume as: "p = {}"
    obtain p where "p division_of (cbox a b)"
      by (rule elementary_interval)
    then show thesis
      using as that by auto
  next
    assume as: "cbox a b = {}"
    show thesis
      using as assms that by auto
  next
    assume as: "interior (cbox a b) = {}" "cbox a b ≠ {}"
    show thesis
      apply (rule that[of "insert (cbox a b) p"],rule division_ofI)
      unfolding finite_insert
      apply (rule assm(1)) unfolding Union_insert
      using assm(2-4) as
      apply -
      apply (fast dest: assm(5))+
      done
  next
    assume as: "p ≠ {}" "interior (cbox a b) ≠ {}" "cbox a b ≠ {}"
    have "∀k∈p. ∃q. (insert (cbox a b) q) division_of (cbox a b ∪ k)"
    proof
      fix k
      assume kp: "k ∈ p"
      from assm(4)[OF kp] obtain c d where "k = cbox c d" by blast
      then show "∃q. (insert (cbox a b) q) division_of (cbox a b ∪ k)"
        by (meson as(3) division_union_intervals_exists)
    qed
    from bchoice[OF this] obtain q where "∀x∈p. insert (cbox a b) (q x) division_of (cbox a b) ∪ x" ..
    note q = division_ofD[OF this[rule_format]]
    let ?D = "⋃{insert (cbox a b) (q k) | k. k ∈ p}"
    show thesis
    proof (rule that[OF division_ofI])
      have *: "{insert (cbox a b) (q k) |k. k ∈ p} = (λk. insert (cbox a b) (q k)) ` p"
        by auto
      show "finite ?D"
        using "*" assm(1) q(1) by auto
      show "⋃?D = cbox a b ∪ ⋃p"
        unfolding * lem1
        unfolding lem2[OF as(1), of "cbox a b", symmetric]
        using q(6)
        by auto
      fix k
      assume k: "k ∈ ?D"
      then show "k ⊆ cbox a b ∪ ⋃p"
        using q(2) by auto
      show "k ≠ {}"
        using q(3) k by auto
      show "∃a b. k = cbox a b"
        using q(4) k by auto
      fix k'
      assume k': "k' ∈ ?D" "k ≠ k'"
      obtain x where x: "k ∈ insert (cbox a b) (q x)" "x∈p"
        using k by auto
      obtain x' where x': "k'∈insert (cbox a b) (q x')" "x'∈p"
        using k' by auto
      show "interior k ∩ interior k' = {}"
      proof (cases "x = x'")
        case True
        show ?thesis
          using True k' q(5) x' x by auto
      next
        case False
        {
          presume "k = cbox a b ⟹ ?thesis"
            and "k' = cbox a b ⟹ ?thesis"
            and "k ≠ cbox a b ⟹ k' ≠ cbox a b ⟹ ?thesis"
          then show ?thesis by linarith
        next
          assume as': "k  = cbox a b"
          show ?thesis
            using as' k' q(5) x' by blast 
        next
          assume as': "k' = cbox a b"
          show ?thesis
            using as' k'(2) q(5) x by blast
        }
        assume as': "k ≠ cbox a b" "k' ≠ cbox a b"
        obtain c d where k: "k = cbox c d"
          using q(4)[OF x(2,1)] by blast
        have "interior k ∩ interior (cbox a b) = {}"
          using as' k'(2) q(5) x by blast
        then have "interior k ⊆ interior x"
        using interior_subset_union_intervals
          by (metis as(2) k q(2) x interior_subset_union_intervals)
        moreover
        obtain c d where c_d: "k' = cbox c d"
          using q(4)[OF x'(2,1)] by blast
        have "interior k' ∩ interior (cbox a b) = {}"
          using as'(2) q(5) x' by blast
        then have "interior k' ⊆ interior x'"
          by (metis as(2) c_d interior_subset_union_intervals q(2) x'(1) x'(2))
        ultimately show ?thesis
          using assm(5)[OF x(2) x'(2) False] by auto
      qed
    qed
  }
qed

lemma elementary_unions_intervals:
  assumes fin: "finite f"
    and "⋀s. s ∈ f ⟹ ∃a b. s = cbox a (b::'a::euclidean_space)"
  obtains p where "p division_of (⋃f)"
proof -
  have "∃p. p division_of (⋃f)"
  proof (induct_tac f rule:finite_subset_induct)
    show "∃p. p division_of ⋃{}" using elementary_empty by auto
  next
    fix x F
    assume as: "finite F" "x ∉ F" "∃p. p division_of ⋃F" "x∈f"
    from this(3) obtain p where p: "p division_of ⋃F" ..
    from assms(2)[OF as(4)] obtain a b where x: "x = cbox a b" by blast
    have *: "⋃F = ⋃p"
      using division_ofD[OF p] by auto
    show "∃p. p division_of ⋃insert x F"
      using elementary_union_interval[OF p[unfolded *], of a b]
      unfolding Union_insert x * by metis
  qed (insert assms, auto)
  then show ?thesis
    using that by auto
qed

lemma elementary_union:
  fixes s t :: "'a::euclidean_space set"
  assumes "ps division_of s" "pt division_of t"
  obtains p where "p division_of (s ∪ t)"
proof -
  have *: "s ∪ t = ⋃ps ∪ ⋃pt"
    using assms unfolding division_of_def by auto
  show ?thesis
    apply (rule elementary_unions_intervals[of "ps ∪ pt"])
    using assms apply auto
    by (simp add: * that)
qed

lemma partial_division_extend:
  fixes t :: "'a::euclidean_space set"
  assumes "p division_of s"
    and "q division_of t"
    and "s ⊆ t"
  obtains r where "p ⊆ r" and "r division_of t"
proof -
  note divp = division_ofD[OF assms(1)] and divq = division_ofD[OF assms(2)]
  obtain a b where ab: "t ⊆ cbox a b"
    using elementary_subset_cbox[OF assms(2)] by auto
  obtain r1 where "p ⊆ r1" "r1 division_of (cbox a b)"
    using assms
    by (metis ab dual_order.trans partial_division_extend_interval divp(6))
  note r1 = this division_ofD[OF this(2)]
  obtain p' where "p' division_of ⋃(r1 - p)"
    apply (rule elementary_unions_intervals[of "r1 - p"])
    using r1(3,6)
    apply auto
    done
  then obtain r2 where r2: "r2 division_of (⋃(r1 - p)) ∩ (⋃q)"
    by (metis assms(2) divq(6) elementary_inter)
  {
    fix x
    assume x: "x ∈ t" "x ∉ s"
    then have "x∈⋃r1"
      unfolding r1 using ab by auto
    then obtain r where r: "r ∈ r1" "x ∈ r"
      unfolding Union_iff ..
    moreover
    have "r ∉ p"
    proof
      assume "r ∈ p"
      then have "x ∈ s" using divp(2) r by auto
      then show False using x by auto
    qed
    ultimately have "x∈⋃(r1 - p)" by auto
  }
  then have *: "t = ⋃p ∪ (⋃(r1 - p) ∩ ⋃q)"
    unfolding divp divq using assms(3) by auto
  show ?thesis
    apply (rule that[of "p ∪ r2"])
    unfolding *
    defer
    apply (rule division_disjoint_union)
    unfolding divp(6)
    apply(rule assms r2)+
  proof -
    have "interior s ∩ interior (⋃(r1-p)) = {}"
    proof (rule inter_interior_unions_intervals)
      show "finite (r1 - p)" and "open (interior s)" and "∀t∈r1-p. ∃a b. t = cbox a b"
        using r1 by auto
      have *: "⋀s. (⋀x. x ∈ s ⟹ False) ⟹ s = {}"
        by auto
      show "∀t∈r1-p. interior s ∩ interior t = {}"
      proof
        fix m x
        assume as: "m ∈ r1 - p"
        have "interior m ∩ interior (⋃p) = {}"
        proof (rule inter_interior_unions_intervals)
          show "finite p" and "open (interior m)" and "∀t∈p. ∃a b. t = cbox a b"
            using divp by auto
          show "∀t∈p. interior m ∩ interior t = {}"
            by (metis DiffD1 DiffD2 as r1(1) r1(7) set_rev_mp)
        qed
        then show "interior s ∩ interior m = {}"
          unfolding divp by auto
      qed
    qed
    then show "interior s ∩ interior (⋃(r1-p) ∩ (⋃q)) = {}"
      using interior_subset by auto
  qed auto
qed


subsection ‹Tagged (partial) divisions.›

definition tagged_partial_division_of (infixr "tagged'_partial'_division'_of" 40)
  where "s tagged_partial_division_of i ⟷
    finite s ∧
    (∀x k. (x, k) ∈ s ⟶ x ∈ k ∧ k ⊆ i ∧ (∃a b. k = cbox a b)) ∧
    (∀x1 k1 x2 k2. (x1, k1) ∈ s ∧ (x2, k2) ∈ s ∧ (x1, k1) ≠ (x2, k2) ⟶
      interior k1 ∩ interior k2 = {})"

lemma tagged_partial_division_ofD[dest]:
  assumes "s tagged_partial_division_of i"
  shows "finite s"
    and "⋀x k. (x,k) ∈ s ⟹ x ∈ k"
    and "⋀x k. (x,k) ∈ s ⟹ k ⊆ i"
    and "⋀x k. (x,k) ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀x1 k1 x2 k2. (x1,k1) ∈ s ⟹
      (x2, k2) ∈ s ⟹ (x1, k1) ≠ (x2, k2) ⟹ interior k1 ∩ interior k2 = {}"
  using assms unfolding tagged_partial_division_of_def by blast+

definition tagged_division_of (infixr "tagged'_division'_of" 40)
  where "s tagged_division_of i ⟷ s tagged_partial_division_of i ∧ (⋃{k. ∃x. (x,k) ∈ s} = i)"

lemma tagged_division_of_finite: "s tagged_division_of i ⟹ finite s"
  unfolding tagged_division_of_def tagged_partial_division_of_def by auto

lemma tagged_division_of:
  "s tagged_division_of i ⟷
    finite s ∧
    (∀x k. (x, k) ∈ s ⟶ x ∈ k ∧ k ⊆ i ∧ (∃a b. k = cbox a b)) ∧
    (∀x1 k1 x2 k2. (x1, k1) ∈ s ∧ (x2, k2) ∈ s ∧ (x1, k1) ≠ (x2, k2) ⟶
      interior k1 ∩ interior k2 = {}) ∧
    (⋃{k. ∃x. (x,k) ∈ s} = i)"
  unfolding tagged_division_of_def tagged_partial_division_of_def by auto

lemma tagged_division_ofI:
  assumes "finite s"
    and "⋀x k. (x,k) ∈ s ⟹ x ∈ k"
    and "⋀x k. (x,k) ∈ s ⟹ k ⊆ i"
    and "⋀x k. (x,k) ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀x1 k1 x2 k2. (x1,k1) ∈ s ⟹ (x2, k2) ∈ s ⟹ (x1, k1) ≠ (x2, k2) ⟹
      interior k1 ∩ interior k2 = {}"
    and "(⋃{k. ∃x. (x,k) ∈ s} = i)"
  shows "s tagged_division_of i"
  unfolding tagged_division_of
  using assms
  apply auto
  apply fastforce+
  done

lemma tagged_division_ofD[dest]:  (*FIXME USE A LOCALE*)
  assumes "s tagged_division_of i"
  shows "finite s"
    and "⋀x k. (x,k) ∈ s ⟹ x ∈ k"
    and "⋀x k. (x,k) ∈ s ⟹ k ⊆ i"
    and "⋀x k. (x,k) ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀x1 k1 x2 k2. (x1, k1) ∈ s ⟹ (x2, k2) ∈ s ⟹ (x1, k1) ≠ (x2, k2) ⟹
      interior k1 ∩ interior k2 = {}"
    and "(⋃{k. ∃x. (x,k) ∈ s} = i)"
  using assms unfolding tagged_division_of by blast+

lemma division_of_tagged_division:
  assumes "s tagged_division_of i"
  shows "(snd ` s) division_of i"
proof (rule division_ofI)
  note assm = tagged_division_ofD[OF assms]
  show "⋃(snd ` s) = i" "finite (snd ` s)"
    using assm by auto
  fix k
  assume k: "k ∈ snd ` s"
  then obtain xk where xk: "(xk, k) ∈ s"
    by auto
  then show "k ⊆ i" "k ≠ {}" "∃a b. k = cbox a b"
    using assm by fastforce+
  fix k'
  assume k': "k' ∈ snd ` s" "k ≠ k'"
  from this(1) obtain xk' where xk': "(xk', k') ∈ s"
    by auto
  then show "interior k ∩ interior k' = {}"
    using assm(5) k'(2) xk by blast
qed

lemma partial_division_of_tagged_division:
  assumes "s tagged_partial_division_of i"
  shows "(snd ` s) division_of ⋃(snd ` s)"
proof (rule division_ofI)
  note assm = tagged_partial_division_ofD[OF assms]
  show "finite (snd ` s)" "⋃(snd ` s) = ⋃(snd ` s)"
    using assm by auto
  fix k
  assume k: "k ∈ snd ` s"
  then obtain xk where xk: "(xk, k) ∈ s"
    by auto
  then show "k ≠ {}" "∃a b. k = cbox a b" "k ⊆ ⋃(snd ` s)"
    using assm by auto
  fix k'
  assume k': "k' ∈ snd ` s" "k ≠ k'"
  from this(1) obtain xk' where xk': "(xk', k') ∈ s"
    by auto
  then show "interior k ∩ interior k' = {}"
    using assm(5) k'(2) xk by auto
qed

lemma tagged_partial_division_subset:
  assumes "s tagged_partial_division_of i"
    and "t ⊆ s"
  shows "t tagged_partial_division_of i"
  using assms
  unfolding tagged_partial_division_of_def
  using finite_subset[OF assms(2)]
  by blast

lemma setsum_over_tagged_division_lemma:
  assumes "p tagged_division_of i"
    and "⋀u v. cbox u v ≠ {} ⟹ content (cbox u v) = 0 ⟹ d (cbox u v) = 0"
  shows "setsum (λ(x,k). d k) p = setsum d (snd ` p)"
proof -
  have *: "(λ(x,k). d k) = d ∘ snd"
    unfolding o_def by (rule ext) auto
  note assm = tagged_division_ofD[OF assms(1)]
  show ?thesis
    unfolding *
  proof (rule setsum.reindex_nontrivial[symmetric])
    show "finite p"
      using assm by auto
    fix x y
    assume "x∈p" "y∈p" "x≠y" "snd x = snd y"
    obtain a b where ab: "snd x = cbox a b"
      using assm(4)[of "fst x" "snd x"] ‹x∈p› by auto
    have "(fst x, snd y) ∈ p" "(fst x, snd y) ≠ y"
      by (metis prod.collapse ‹x∈p› ‹snd x = snd y› ‹x ≠ y›)+
    with ‹x∈p› ‹y∈p› have "interior (snd x) ∩ interior (snd y) = {}"
      by (intro assm(5)[of "fst x" _ "fst y"]) auto
    then have "content (cbox a b) = 0"
      unfolding ‹snd x = snd y›[symmetric] ab content_eq_0_interior by auto
    then have "d (cbox a b) = 0"
      using assm(2)[of "fst x" "snd x"] ‹x∈p› ab[symmetric] by (intro assms(2)) auto
    then show "d (snd x) = 0"
      unfolding ab by auto
  qed
qed

lemma tag_in_interval: "p tagged_division_of i ⟹ (x, k) ∈ p ⟹ x ∈ i"
  by auto

lemma tagged_division_of_empty: "{} tagged_division_of {}"
  unfolding tagged_division_of by auto

lemma tagged_partial_division_of_trivial[simp]: "p tagged_partial_division_of {} ⟷ p = {}"
  unfolding tagged_partial_division_of_def by auto

lemma tagged_division_of_trivial[simp]: "p tagged_division_of {} ⟷ p = {}"
  unfolding tagged_division_of by auto

lemma tagged_division_of_self: "x ∈ cbox a b ⟹ {(x,cbox a b)} tagged_division_of (cbox a b)"
  by (rule tagged_division_ofI) auto

lemma tagged_division_of_self_real: "x ∈ {a .. b::real} ⟹ {(x,{a .. b})} tagged_division_of {a .. b}"
  unfolding box_real[symmetric]
  by (rule tagged_division_of_self)

lemma tagged_division_union:
  assumes "p1 tagged_division_of s1"
    and "p2 tagged_division_of s2"
    and "interior s1 ∩ interior s2 = {}"
  shows "(p1 ∪ p2) tagged_division_of (s1 ∪ s2)"
proof (rule tagged_division_ofI)
  note p1 = tagged_division_ofD[OF assms(1)]
  note p2 = tagged_division_ofD[OF assms(2)]
  show "finite (p1 ∪ p2)"
    using p1(1) p2(1) by auto
  show "⋃{k. ∃x. (x, k) ∈ p1 ∪ p2} = s1 ∪ s2"
    using p1(6) p2(6) by blast
  fix x k
  assume xk: "(x, k) ∈ p1 ∪ p2"
  show "x ∈ k" "∃a b. k = cbox a b"
    using xk p1(2,4) p2(2,4) by auto
  show "k ⊆ s1 ∪ s2"
    using xk p1(3) p2(3) by blast
  fix x' k'
  assume xk': "(x', k') ∈ p1 ∪ p2" "(x, k) ≠ (x', k')"
  have *: "⋀a b. a ⊆ s1 ⟹ b ⊆ s2 ⟹ interior a ∩ interior b = {}"
    using assms(3) interior_mono by blast
  show "interior k ∩ interior k' = {}"
    apply (cases "(x, k) ∈ p1")
    apply (meson "*" UnE assms(1) assms(2) p1(5) tagged_division_ofD(3) xk'(1) xk'(2))
    by (metis "*" UnE assms(1) assms(2) inf_sup_aci(1) p2(5) tagged_division_ofD(3) xk xk'(1) xk'(2))
qed

lemma tagged_division_unions:
  assumes "finite iset"
    and "∀i∈iset. pfn i tagged_division_of i"
    and "∀i1∈iset. ∀i2∈iset. i1 ≠ i2 ⟶ interior(i1) ∩ interior(i2) = {}"
  shows "⋃(pfn ` iset) tagged_division_of (⋃iset)"
proof (rule tagged_division_ofI)
  note assm = tagged_division_ofD[OF assms(2)[rule_format]]
  show "finite (⋃(pfn ` iset))"
    apply (rule finite_Union)
    using assms
    apply auto
    done
  have "⋃{k. ∃x. (x, k) ∈ ⋃(pfn ` iset)} = ⋃((λi. ⋃{k. ∃x. (x, k) ∈ pfn i}) ` iset)"
    by blast
  also have "… = ⋃iset"
    using assm(6) by auto
  finally show "⋃{k. ∃x. (x, k) ∈ ⋃(pfn ` iset)} = ⋃iset" .
  fix x k
  assume xk: "(x, k) ∈ ⋃(pfn ` iset)"
  then obtain i where i: "i ∈ iset" "(x, k) ∈ pfn i"
    by auto
  show "x ∈ k" "∃a b. k = cbox a b" "k ⊆ ⋃iset"
    using assm(2-4)[OF i] using i(1) by auto
  fix x' k'
  assume xk': "(x', k') ∈ ⋃(pfn ` iset)" "(x, k) ≠ (x', k')"
  then obtain i' where i': "i' ∈ iset" "(x', k') ∈ pfn i'"
    by auto
  have *: "⋀a b. i ≠ i' ⟹ a ⊆ i ⟹ b ⊆ i' ⟹ interior a ∩ interior b = {}"
    using i(1) i'(1)
    using assms(3)[rule_format] interior_mono
    by blast
  show "interior k ∩ interior k' = {}"
    apply (cases "i = i'")
    using assm(5) i' i(2) xk'(2) apply blast
    using "*" assm(3) i' i by auto
qed

lemma tagged_partial_division_of_union_self:
  assumes "p tagged_partial_division_of s"
  shows "p tagged_division_of (⋃(snd ` p))"
  apply (rule tagged_division_ofI)
  using tagged_partial_division_ofD[OF assms]
  apply auto
  done

lemma tagged_division_of_union_self:
  assumes "p tagged_division_of s"
  shows "p tagged_division_of (⋃(snd ` p))"
  apply (rule tagged_division_ofI)
  using tagged_division_ofD[OF assms]
  apply auto
  done


subsection ‹Fine-ness of a partition w.r.t. a gauge.›

definition fine  (infixr "fine" 46)
  where "d fine s ⟷ (∀(x,k) ∈ s. k ⊆ d x)"

lemma fineI:
  assumes "⋀x k. (x, k) ∈ s ⟹ k ⊆ d x"
  shows "d fine s"
  using assms unfolding fine_def by auto

lemma fineD[dest]:
  assumes "d fine s"
  shows "⋀x k. (x,k) ∈ s ⟹ k ⊆ d x"
  using assms unfolding fine_def by auto

lemma fine_inter: "(λx. d1 x ∩ d2 x) fine p ⟷ d1 fine p ∧ d2 fine p"
  unfolding fine_def by auto

lemma fine_inters:
 "(λx. ⋂{f d x | d.  d ∈ s}) fine p ⟷ (∀d∈s. (f d) fine p)"
  unfolding fine_def by blast

lemma fine_union: "d fine p1 ⟹ d fine p2 ⟹ d fine (p1 ∪ p2)"
  unfolding fine_def by blast

lemma fine_unions: "(⋀p. p ∈ ps ⟹ d fine p) ⟹ d fine (⋃ps)"
  unfolding fine_def by auto

lemma fine_subset: "p ⊆ q ⟹ d fine q ⟹ d fine p"
  unfolding fine_def by blast


subsection ‹Gauge integral. Define on compact intervals first, then use a limit.›

definition has_integral_compact_interval (infixr "has'_integral'_compact'_interval" 46)
  where "(f has_integral_compact_interval y) i ⟷
    (∀e>0. ∃d. gauge d ∧
      (∀p. p tagged_division_of i ∧ d fine p ⟶
        norm (setsum (λ(x,k). content k *R f x) p - y) < e))"

definition has_integral ::
    "('n::euclidean_space ⇒ 'b::real_normed_vector) ⇒ 'b ⇒ 'n set ⇒ bool"
  (infixr "has'_integral" 46)
  where "(f has_integral y) i ⟷
    (if ∃a b. i = cbox a b
     then (f has_integral_compact_interval y) i
     else (∀e>0. ∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ i then f x else 0) has_integral_compact_interval z) (cbox a b) ∧
        norm (z - y) < e)))"

lemma has_integral:
  "(f has_integral y) (cbox a b) ⟷
    (∀e>0. ∃d. gauge d ∧
      (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
        norm (setsum (λ(x,k). content(k) *R f x) p - y) < e))"
  unfolding has_integral_def has_integral_compact_interval_def
  by auto

lemma has_integral_real:
  "(f has_integral y) {a .. b::real} ⟷
    (∀e>0. ∃d. gauge d ∧
      (∀p. p tagged_division_of {a .. b} ∧ d fine p ⟶
        norm (setsum (λ(x,k). content(k) *R f x) p - y) < e))"
  unfolding box_real[symmetric]
  by (rule has_integral)

lemma has_integralD[dest]:
  assumes "(f has_integral y) (cbox a b)"
    and "e > 0"
  obtains d where "gauge d"
    and "⋀p. p tagged_division_of (cbox a b) ⟹ d fine p ⟹
      norm (setsum (λ(x,k). content(k) *R f(x)) p - y) < e"
  using assms unfolding has_integral by auto

lemma has_integral_alt:
  "(f has_integral y) i ⟷
    (if ∃a b. i = cbox a b
     then (f has_integral y) i
     else (∀e>0. ∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ i then f(x) else 0) has_integral z) (cbox a b) ∧ norm (z - y) < e)))"
  unfolding has_integral
  unfolding has_integral_compact_interval_def has_integral_def
  by auto

lemma has_integral_altD:
  assumes "(f has_integral y) i"
    and "¬ (∃a b. i = cbox a b)"
    and "e>0"
  obtains B where "B > 0"
    and "∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ i then f(x) else 0) has_integral z) (cbox a b) ∧ norm(z - y) < e)"
  using assms
  unfolding has_integral
  unfolding has_integral_compact_interval_def has_integral_def
  by auto

definition integrable_on (infixr "integrable'_on" 46)
  where "f integrable_on i ⟷ (∃y. (f has_integral y) i)"

definition "integral i f = (SOME y. (f has_integral y) i ∨ ~ f integrable_on i ∧ y=0)"

lemma integrable_integral[dest]: "f integrable_on i ⟹ (f has_integral (integral i f)) i"
  unfolding integrable_on_def integral_def by (metis (mono_tags, lifting) someI_ex)

lemma not_integrable_integral: "~ f integrable_on i ⟹ integral i f = 0"
  unfolding integrable_on_def integral_def by blast 

lemma has_integral_integrable[intro]: "(f has_integral i) s ⟹ f integrable_on s"
  unfolding integrable_on_def by auto

lemma has_integral_integral: "f integrable_on s ⟷ (f has_integral (integral s f)) s"
  by auto

lemma setsum_content_null:
  assumes "content (cbox a b) = 0"
    and "p tagged_division_of (cbox a b)"
  shows "setsum (λ(x,k). content k *R f x) p = (0::'a::real_normed_vector)"
proof (rule setsum.neutral, rule)
  fix y
  assume y: "y ∈ p"
  obtain x k where xk: "y = (x, k)"
    using surj_pair[of y] by blast
  note assm = tagged_division_ofD(3-4)[OF assms(2) y[unfolded xk]]
  from this(2) obtain c d where k: "k = cbox c d" by blast
  have "(λ(x, k). content k *R f x) y = content k *R f x"
    unfolding xk by auto
  also have "… = 0"
    using content_subset[OF assm(1)[unfolded k]] content_pos_le[of c d]
    unfolding assms(1) k
    by auto
  finally show "(λ(x, k). content k *R f x) y = 0" .
qed


subsection ‹Some basic combining lemmas.›

lemma tagged_division_unions_exists:
  assumes "finite iset"
    and "∀i∈iset. ∃p. p tagged_division_of i ∧ d fine p"
    and "∀i1∈iset. ∀i2∈iset. i1 ≠ i2 ⟶ interior i1 ∩ interior i2 = {}"
    and "⋃iset = i"
   obtains p where "p tagged_division_of i" and "d fine p"
proof -
  obtain pfn where pfn:
    "⋀x. x ∈ iset ⟹ pfn x tagged_division_of x"
    "⋀x. x ∈ iset ⟹ d fine pfn x"
    using bchoice[OF assms(2)] by auto
  show thesis
    apply (rule_tac p="⋃(pfn ` iset)" in that)
    using assms(1) assms(3) assms(4) pfn(1) tagged_division_unions apply force
    by (metis (mono_tags, lifting) fine_unions imageE pfn(2))
qed


subsection ‹The set we're concerned with must be closed.›

lemma division_of_closed:
  fixes i :: "'n::euclidean_space set"
  shows "s division_of i ⟹ closed i"
  unfolding division_of_def by fastforce

subsection ‹General bisection principle for intervals; might be useful elsewhere.›

lemma interval_bisection_step:
  fixes type :: "'a::euclidean_space"
  assumes "P {}"
    and "∀s t. P s ∧ P t ∧ interior(s) ∩ interior(t) = {} ⟶ P (s ∪ t)"
    and "¬ P (cbox a (b::'a))"
  obtains c d where "¬ P (cbox c d)"
    and "∀i∈Basis. a∙i ≤ c∙i ∧ c∙i ≤ d∙i ∧ d∙i ≤ b∙i ∧ 2 * (d∙i - c∙i) ≤ b∙i - a∙i"
proof -
  have "cbox a b ≠ {}"
    using assms(1,3) by metis
  then have ab: "⋀i. i∈Basis ⟹ a ∙ i ≤ b ∙ i"
    by (force simp: mem_box)
  { fix f
    have "⟦finite f;
           ⋀s. s∈f ⟹ P s;
           ⋀s. s∈f ⟹ ∃a b. s = cbox a b;
           ⋀s t. s∈f ⟹ t∈f ⟹ s ≠ t ⟹ interior s ∩ interior t = {}⟧ ⟹ P (⋃f)"
    proof (induct f rule: finite_induct)
      case empty
      show ?case
        using assms(1) by auto
    next
      case (insert x f)
      show ?case
        unfolding Union_insert
        apply (rule assms(2)[rule_format])
        using inter_interior_unions_intervals [of f "interior x"]
        apply (auto simp: insert)
        by (metis IntI empty_iff insert.hyps(2) insert.prems(3) insert_iff)
    qed
  } note UN_cases = this
  let ?A = "{cbox c d | c d::'a. ∀i∈Basis. (c∙i = a∙i) ∧ (d∙i = (a∙i + b∙i) / 2) ∨
    (c∙i = (a∙i + b∙i) / 2) ∧ (d∙i = b∙i)}"
  let ?PP = "λc d. ∀i∈Basis. a∙i ≤ c∙i ∧ c∙i ≤ d∙i ∧ d∙i ≤ b∙i ∧ 2 * (d∙i - c∙i) ≤ b∙i - a∙i"
  {
    presume "∀c d. ?PP c d ⟶ P (cbox c d) ⟹ False"
    then show thesis
      unfolding atomize_not not_all
      by (blast intro: that)
  }
  assume as: "∀c d. ?PP c d ⟶ P (cbox c d)"
  have "P (⋃?A)"
  proof (rule UN_cases)
    let ?B = "(λs. cbox (∑i∈Basis. (if i ∈ s then a∙i else (a∙i + b∙i) / 2) *R i::'a)
      (∑i∈Basis. (if i ∈ s then (a∙i + b∙i) / 2 else b∙i) *R i)) ` {s. s ⊆ Basis}"
    have "?A ⊆ ?B"
    proof
      fix x
      assume "x ∈ ?A"
      then obtain c d
        where x:  "x = cbox c d"
                  "⋀i. i ∈ Basis ⟹
                        c ∙ i = a ∙ i ∧ d ∙ i = (a ∙ i + b ∙ i) / 2 ∨
                        c ∙ i = (a ∙ i + b ∙ i) / 2 ∧ d ∙ i = b ∙ i" by blast
      show "x ∈ ?B"
        unfolding image_iff x
        apply (rule_tac x="{i. i∈Basis ∧ c∙i = a∙i}" in bexI)
        apply (rule arg_cong2 [where f = cbox])
        using x(2) ab
        apply (auto simp add: euclidean_eq_iff[where 'a='a])
        by fastforce
    qed
    then show "finite ?A"
      by (rule finite_subset) auto
  next
    fix s
    assume "s ∈ ?A"
    then obtain c d
      where s: "s = cbox c d"
               "⋀i. i ∈ Basis ⟹
                     c ∙ i = a ∙ i ∧ d ∙ i = (a ∙ i + b ∙ i) / 2 ∨
                     c ∙ i = (a ∙ i + b ∙ i) / 2 ∧ d ∙ i = b ∙ i"
      by blast
    show "P s"
      unfolding s
      apply (rule as[rule_format])
      using ab s(2) by force
    show "∃a b. s = cbox a b"
      unfolding s by auto
    fix t
    assume "t ∈ ?A"
    then obtain e f where t:
      "t = cbox e f"
      "⋀i. i ∈ Basis ⟹
        e ∙ i = a ∙ i ∧ f ∙ i = (a ∙ i + b ∙ i) / 2 ∨
        e ∙ i = (a ∙ i + b ∙ i) / 2 ∧ f ∙ i = b ∙ i"
      by blast
    assume "s ≠ t"
    then have "¬ (c = e ∧ d = f)"
      unfolding s t by auto
    then obtain i where "c∙i ≠ e∙i ∨ d∙i ≠ f∙i" and i': "i ∈ Basis"
      unfolding euclidean_eq_iff[where 'a='a] by auto
    then have i: "c∙i ≠ e∙i" "d∙i ≠ f∙i"
      using s(2) t(2) apply fastforce
      using t(2)[OF i'] ‹c ∙ i ≠ e ∙ i ∨ d ∙ i ≠ f ∙ i› i' s(2) t(2) by fastforce
    have *: "⋀s t. (⋀a. a ∈ s ⟹ a ∈ t ⟹ False) ⟹ s ∩ t = {}"
      by auto
    show "interior s ∩ interior t = {}"
      unfolding s t interior_cbox
    proof (rule *)
      fix x
      assume "x ∈ box c d" "x ∈ box e f"
      then have x: "c∙i < d∙i" "e∙i < f∙i" "c∙i < f∙i" "e∙i < d∙i"
        unfolding mem_box using i'
        by force+
      show False  using s(2)[OF i']
      proof safe
        assume as: "c ∙ i = a ∙ i" "d ∙ i = (a ∙ i + b ∙ i) / 2"
        show False
          using t(2)[OF i'] and i x unfolding as by (fastforce simp add:field_simps)
      next
        assume as: "c ∙ i = (a ∙ i + b ∙ i) / 2" "d ∙ i = b ∙ i"
        show False
          using t(2)[OF i'] and i x unfolding as by(fastforce simp add:field_simps)
      qed
    qed
  qed
  also have "⋃?A = cbox a b"
  proof (rule set_eqI,rule)
    fix x
    assume "x ∈ ⋃?A"
    then obtain c d where x:
      "x ∈ cbox c d"
      "⋀i. i ∈ Basis ⟹
        c ∙ i = a ∙ i ∧ d ∙ i = (a ∙ i + b ∙ i) / 2 ∨
        c ∙ i = (a ∙ i + b ∙ i) / 2 ∧ d ∙ i = b ∙ i"
      by blast
    show "x∈cbox a b"
      unfolding mem_box
    proof safe
      fix i :: 'a
      assume i: "i ∈ Basis"
      then show "a ∙ i ≤ x ∙ i" "x ∙ i ≤ b ∙ i"
        using x(2)[OF i] x(1)[unfolded mem_box,THEN bspec, OF i] by auto
    qed
  next
    fix x
    assume x: "x ∈ cbox a b"
    have "∀i∈Basis.
      ∃c d. (c = a∙i ∧ d = (a∙i + b∙i) / 2 ∨ c = (a∙i + b∙i) / 2 ∧ d = b∙i) ∧ c≤x∙i ∧ x∙i ≤ d"
      (is "∀i∈Basis. ∃c d. ?P i c d")
      unfolding mem_box
    proof
      fix i :: 'a
      assume i: "i ∈ Basis"
      have "?P i (a∙i) ((a ∙ i + b ∙ i) / 2) ∨ ?P i ((a ∙ i + b ∙ i) / 2) (b∙i)"
        using x[unfolded mem_box,THEN bspec, OF i] by auto
      then show "∃c d. ?P i c d"
        by blast
    qed
    then show "x∈⋃?A"
      unfolding Union_iff Bex_def mem_Collect_eq choice_Basis_iff
      apply auto
      apply (rule_tac x="cbox xa xaa" in exI)
      unfolding mem_box
      apply auto
      done
  qed
  finally show False
    using assms by auto
qed

lemma interval_bisection:
  fixes type :: "'a::euclidean_space"
  assumes "P {}"
    and "(∀s t. P s ∧ P t ∧ interior(s) ∩ interior(t) = {} ⟶ P(s ∪ t))"
    and "¬ P (cbox a (b::'a))"
  obtains x where "x ∈ cbox a b"
    and "∀e>0. ∃c d. x ∈ cbox c d ∧ cbox c d ⊆ ball x e ∧ cbox c d ⊆ cbox a b ∧ ¬ P (cbox c d)"
proof -
  have "∀x. ∃y. ¬ P (cbox (fst x) (snd x)) ⟶ (¬ P (cbox (fst y) (snd y)) ∧
    (∀i∈Basis. fst x∙i ≤ fst y∙i ∧ fst y∙i ≤ snd y∙i ∧ snd y∙i ≤ snd x∙i ∧
       2 * (snd y∙i - fst y∙i) ≤ snd x∙i - fst x∙i))" (is "∀x. ?P x")
  proof
    show "?P x" for x
    proof (cases "P (cbox (fst x) (snd x))")
      case True
      then show ?thesis by auto
    next
      case as: False
      obtain c d where "¬ P (cbox c d)"
        "∀i∈Basis.
           fst x ∙ i ≤ c ∙ i ∧
           c ∙ i ≤ d ∙ i ∧
           d ∙ i ≤ snd x ∙ i ∧
           2 * (d ∙ i - c ∙ i) ≤ snd x ∙ i - fst x ∙ i"
        by (rule interval_bisection_step[of P, OF assms(1-2) as])
      then show ?thesis
        apply -
        apply (rule_tac x="(c,d)" in exI)
        apply auto
        done
    qed
  qed
  then obtain f where f:
    "∀x.
      ¬ P (cbox (fst x) (snd x)) ⟶
      ¬ P (cbox (fst (f x)) (snd (f x))) ∧
        (∀i∈Basis.
            fst x ∙ i ≤ fst (f x) ∙ i ∧
            fst (f x) ∙ i ≤ snd (f x) ∙ i ∧
            snd (f x) ∙ i ≤ snd x ∙ i ∧
            2 * (snd (f x) ∙ i - fst (f x) ∙ i) ≤ snd x ∙ i - fst x ∙ i)"
    apply -
    apply (drule choice)
    apply blast
    done
  def AB  "λn. (f ^^ n) (a,b)"
  def A  "λn. fst(AB n)"
  def B  "λn. snd(AB n)"
  note ab_def = A_def B_def AB_def
  have "A 0 = a" "B 0 = b" "⋀n. ¬ P (cbox (A(Suc n)) (B(Suc n))) ∧
    (∀i∈Basis. A(n)∙i ≤ A(Suc n)∙i ∧ A(Suc n)∙i ≤ B(Suc n)∙i ∧ B(Suc n)∙i ≤ B(n)∙i ∧
    2 * (B(Suc n)∙i - A(Suc n)∙i) ≤ B(n)∙i - A(n)∙i)" (is "⋀n. ?P n")
  proof -
    show "A 0 = a" "B 0 = b"
      unfolding ab_def by auto
    note S = ab_def funpow.simps o_def id_apply
    show "?P n" for n
    proof (induct n)
      case 0
      then show ?case
        unfolding S
        apply (rule f[rule_format]) using assms(3)
        apply auto
        done
    next
      case (Suc n)
      show ?case
        unfolding S
        apply (rule f[rule_format])
        using Suc
        unfolding S
        apply auto
        done
    qed
  qed
  note AB = this(1-2) conjunctD2[OF this(3),rule_format]

  have interv: "∃n. ∀x∈cbox (A n) (B n). ∀y∈cbox (A n) (B n). dist x y < e"
    if e: "0 < e" for e
  proof -
    obtain n where n: "(∑i∈Basis. b ∙ i - a ∙ i) / e < 2 ^ n"
      using real_arch_pow[of 2 "(setsum (λi. b∙i - a∙i) Basis) / e"] by auto
    show ?thesis
    proof (rule exI [where x=n], clarify)
      fix x y
      assume xy: "x∈cbox (A n) (B n)" "y∈cbox (A n) (B n)"
      have "dist x y ≤ setsum (λi. ¦(x - y)∙i¦) Basis"
        unfolding dist_norm by(rule norm_le_l1)
      also have "… ≤ setsum (λi. B n∙i - A n∙i) Basis"
      proof (rule setsum_mono)
        fix i :: 'a
        assume i: "i ∈ Basis"
        show "¦(x - y) ∙ i¦ ≤ B n ∙ i - A n ∙ i"
          using xy[unfolded mem_box,THEN bspec, OF i]
          by (auto simp: inner_diff_left)
      qed
      also have "… ≤ setsum (λi. b∙i - a∙i) Basis / 2^n"
        unfolding setsum_divide_distrib
      proof (rule setsum_mono)
        show "B n ∙ i - A n ∙ i ≤ (b ∙ i - a ∙ i) / 2 ^ n" if i: "i ∈ Basis" for i
        proof (induct n)
          case 0
          then show ?case
            unfolding AB by auto
        next
          case (Suc n)
          have "B (Suc n) ∙ i - A (Suc n) ∙ i ≤ (B n ∙ i - A n ∙ i) / 2"
            using AB(4)[of i n] using i by auto
          also have "… ≤ (b ∙ i - a ∙ i) / 2 ^ Suc n"
            using Suc by (auto simp add: field_simps)
          finally show ?case .
        qed
      qed
      also have "… < e"
        using n using e by (auto simp add: field_simps)
      finally show "dist x y < e" .
    qed
  qed
  {
    fix n m :: nat
    assume "m ≤ n" then have "cbox (A n) (B n) ⊆ cbox (A m) (B m)"
    proof (induction rule: inc_induct)
      case (step i)
      show ?case
        using AB(4) by (intro order_trans[OF step.IH] subset_box_imp) auto
    qed simp
  } note ABsubset = this
  have "∃a. ∀n. a∈ cbox (A n) (B n)"
    by (rule decreasing_closed_nest[rule_format,OF closed_cbox _ ABsubset interv])
      (metis nat.exhaust AB(1-3) assms(1,3))
  then obtain x0 where x0: "⋀n. x0 ∈ cbox (A n) (B n)"
    by blast
  show thesis
  proof (rule that[rule_format, of x0])
    show "x0∈cbox a b"
      using x0[of 0] unfolding AB .
    fix e :: real
    assume "e > 0"
    from interv[OF this] obtain n
      where n: "∀x∈cbox (A n) (B n). ∀y∈cbox (A n) (B n). dist x y < e" ..
    have "¬ P (cbox (A n) (B n))"
      apply (cases "0 < n")
      using AB(3)[of "n - 1"] assms(3) AB(1-2)
      apply auto
      done
    moreover have "cbox (A n) (B n) ⊆ ball x0 e"
      using n using x0[of n] by auto
    moreover have "cbox (A n) (B n) ⊆ cbox a b"
      unfolding AB(1-2)[symmetric] by (rule ABsubset) auto
    ultimately show "∃c d. x0 ∈ cbox c d ∧ cbox c d ⊆ ball x0 e ∧ cbox c d ⊆ cbox a b ∧ ¬ P (cbox c d)"
      apply (rule_tac x="A n" in exI)
      apply (rule_tac x="B n" in exI)
      apply (auto simp: x0)
      done
  qed
qed


subsection ‹Cousin's lemma.›

lemma fine_division_exists:
  fixes a b :: "'a::euclidean_space"
  assumes "gauge g"
  obtains p where "p tagged_division_of (cbox a b)" "g fine p"
proof -
  presume "¬ (∃p. p tagged_division_of (cbox a b) ∧ g fine p) ⟹ False"
  then obtain p where "p tagged_division_of (cbox a b)" "g fine p"
    by blast
  then show thesis ..
next
  assume as: "¬ (∃p. p tagged_division_of (cbox a b) ∧ g fine p)"
  obtain x where x:
      "x ∈ (cbox a b)"
      "⋀e. 0 < e ⟹
        ∃c d.
          x ∈ cbox c d ∧
          cbox c d ⊆ ball x e ∧
          cbox c d ⊆ (cbox a b) ∧
          ¬ (∃p. p tagged_division_of cbox c d ∧ g fine p)"
    apply (rule interval_bisection[of "λs. ∃p. p tagged_division_of s ∧ g fine p", OF _ _ as])
    apply (simp add: fine_def)
    apply (metis tagged_division_union fine_union)
    apply (auto simp: )
    done
  obtain e where e: "e > 0" "ball x e ⊆ g x"
    using gaugeD[OF assms, of x] unfolding open_contains_ball by auto
  from x(2)[OF e(1)]
  obtain c d where c_d: "x ∈ cbox c d"
                        "cbox c d ⊆ ball x e"
                        "cbox c d ⊆ cbox a b"
                        "¬ (∃p. p tagged_division_of cbox c d ∧ g fine p)"
    by blast
  have "g fine {(x, cbox c d)}"
    unfolding fine_def using e using c_d(2) by auto
  then show False
    using tagged_division_of_self[OF c_d(1)] using c_d by auto
qed

lemma fine_division_exists_real:
  fixes a b :: real
  assumes "gauge g"
  obtains p where "p tagged_division_of {a .. b}" "g fine p"
  by (metis assms box_real(2) fine_division_exists)

subsection ‹Basic theorems about integrals.›

lemma has_integral_unique:
  fixes f :: "'n::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "(f has_integral k1) i"
    and "(f has_integral k2) i"
  shows "k1 = k2"
proof (rule ccontr)
  let ?e = "norm (k1 - k2) / 2"
  assume as: "k1 ≠ k2"
  then have e: "?e > 0"
    by auto
  have lem: False
    if f_k1: "(f has_integral k1) (cbox a b)"
    and f_k2: "(f has_integral k2) (cbox a b)"
    and "k1 ≠ k2"
    for f :: "'n ⇒ 'a" and a b k1 k2
  proof -
    let ?e = "norm (k1 - k2) / 2"
    from ‹k1 ≠ k2› have e: "?e > 0" by auto
    obtain d1 where d1:
        "gauge d1"
        "⋀p. p tagged_division_of cbox a b ⟹
          d1 fine p ⟹ norm ((∑(x, k)∈p. content k *R f x) - k1) < norm (k1 - k2) / 2"
      by (rule has_integralD[OF f_k1 e]) blast
    obtain d2 where d2:
        "gauge d2"
        "⋀p. p tagged_division_of cbox a b ⟹
          d2 fine p ⟹ norm ((∑(x, k)∈p. content k *R f x) - k2) < norm (k1 - k2) / 2"
      by (rule has_integralD[OF f_k2 e]) blast
    obtain p where p:
        "p tagged_division_of cbox a b"
        "(λx. d1 x ∩ d2 x) fine p"
      by (rule fine_division_exists[OF gauge_inter[OF d1(1) d2(1)]])
    let ?c = "(∑(x, k)∈p. content k *R f x)"
    have "norm (k1 - k2) ≤ norm (?c - k2) + norm (?c - k1)"
      using norm_triangle_ineq4[of "k1 - ?c" "k2 - ?c"]
      by (auto simp add:algebra_simps norm_minus_commute)
    also have "… < norm (k1 - k2) / 2 + norm (k1 - k2) / 2"
      apply (rule add_strict_mono)
      apply (rule_tac[!] d2(2) d1(2))
      using p unfolding fine_def
      apply auto
      done
    finally show False by auto
  qed
  {
    presume "¬ (∃a b. i = cbox a b) ⟹ False"
    then show False
      using as assms lem by blast
  }
  assume as: "¬ (∃a b. i = cbox a b)"
  obtain B1 where B1:
      "0 < B1"
      "⋀a b. ball 0 B1 ⊆ cbox a b ⟹
        ∃z. ((λx. if x ∈ i then f x else 0) has_integral z) (cbox a b) ∧
          norm (z - k1) < norm (k1 - k2) / 2"
    by (rule has_integral_altD[OF assms(1) as,OF e]) blast
  obtain B2 where B2:
      "0 < B2"
      "⋀a b. ball 0 B2 ⊆ cbox a b ⟹
        ∃z. ((λx. if x ∈ i then f x else 0) has_integral z) (cbox a b) ∧
          norm (z - k2) < norm (k1 - k2) / 2"
    by (rule has_integral_altD[OF assms(2) as,OF e]) blast
  have "∃a b::'n. ball 0 B1 ∪ ball 0 B2 ⊆ cbox a b"
    apply (rule bounded_subset_cbox)
    using bounded_Un bounded_ball
    apply auto
    done
  then obtain a b :: 'n where ab: "ball 0 B1 ⊆ cbox a b" "ball 0 B2 ⊆ cbox a b"
    by blast
  obtain w where w:
    "((λx. if x ∈ i then f x else 0) has_integral w) (cbox a b)"
    "norm (w - k1) < norm (k1 - k2) / 2"
    using B1(2)[OF ab(1)] by blast
  obtain z where z:
    "((λx. if x ∈ i then f x else 0) has_integral z) (cbox a b)"
    "norm (z - k2) < norm (k1 - k2) / 2"
    using B2(2)[OF ab(2)] by blast
  have "z = w"
    using lem[OF w(1) z(1)] by auto
  then have "norm (k1 - k2) ≤ norm (z - k2) + norm (w - k1)"
    using norm_triangle_ineq4 [of "k1 - w" "k2 - z"]
    by (auto simp add: norm_minus_commute)
  also have "… < norm (k1 - k2) / 2 + norm (k1 - k2) / 2"
    apply (rule add_strict_mono)
    apply (rule_tac[!] z(2) w(2))
    done
  finally show False by auto
qed

lemma integral_unique [intro]: "(f has_integral y) k ⟹ integral k f = y"
  unfolding integral_def
  by (rule some_equality) (auto intro: has_integral_unique)

lemma eq_integralD: "integral k f = y ⟹ (f has_integral y) k ∨ ~ f integrable_on k ∧ y=0"
  unfolding integral_def integrable_on_def
  apply (erule subst)
  apply (rule someI_ex)
  by blast

lemma has_integral_is_0:
  fixes f :: "'n::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "∀x∈s. f x = 0"
  shows "(f has_integral 0) s"
proof -
  have lem: "⋀a b. ⋀f::'n ⇒ 'a.
    (∀x∈cbox a b. f(x) = 0) ⟹ (f has_integral 0) (cbox a b)"
    unfolding has_integral
  proof clarify
    fix a b e
    fix f :: "'n ⇒ 'a"
    assume as: "∀x∈cbox a b. f x = 0" "0 < (e::real)"
    have "norm ((∑(x, k)∈p. content k *R f x) - 0) < e"
      if p: "p tagged_division_of cbox a b" for p
    proof -
      have "(∑(x, k)∈p. content k *R f x) = 0"
      proof (rule setsum.neutral, rule)
        fix x
        assume x: "x ∈ p"
        have "f (fst x) = 0"
          using tagged_division_ofD(2-3)[OF p, of "fst x" "snd x"] using as x by auto
        then show "(λ(x, k). content k *R f x) x = 0"
          apply (subst surjective_pairing[of x])
          unfolding split_conv
          apply auto
          done
      qed
      then show ?thesis
        using as by auto
    qed
    then show "∃d. gauge d ∧
        (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶ norm ((∑(x, k)∈p. content k *R f x) - 0) < e)"
      by auto
  qed
  {
    presume "¬ (∃a b. s = cbox a b) ⟹ ?thesis"
    with assms lem show ?thesis
      by blast
  }
  have *: "(λx. if x ∈ s then f x else 0) = (λx. 0)"
    apply (rule ext)
    using assms
    apply auto
    done
  assume "¬ (∃a b. s = cbox a b)"
  then show ?thesis
    using lem
    by (subst has_integral_alt) (force simp add: *)
qed

lemma has_integral_0[simp]: "((λx::'n::euclidean_space. 0) has_integral 0) s"
  by (rule has_integral_is_0) auto

lemma has_integral_0_eq[simp]: "((λx. 0) has_integral i) s ⟷ i = 0"
  using has_integral_unique[OF has_integral_0] by auto

lemma has_integral_linear:
  fixes f :: "'n::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "(f has_integral y) s"
    and "bounded_linear h"
  shows "((h ∘ f) has_integral ((h y))) s"
proof -
  interpret bounded_linear h
    using assms(2) .
  from pos_bounded obtain B where B: "0 < B" "⋀x. norm (h x) ≤ norm x * B"
    by blast
  have lem: "⋀(f :: 'n ⇒ 'a) y a b.
    (f has_integral y) (cbox a b) ⟹ ((h ∘ f) has_integral h y) (cbox a b)"
    unfolding has_integral
  proof (clarify, goal_cases)
    case prems: (1 f y a b e)
    from pos_bounded
    obtain B where B: "0 < B" "⋀x. norm (h x) ≤ norm x * B"
      by blast
    have "e / B > 0" using prems(2) B by simp
    then obtain g
      where g: "gauge g"
               "⋀p. p tagged_division_of (cbox a b) ⟹ g fine p ⟹
                    norm ((∑(x, k)∈p. content k *R f x) - y) < e / B"
        using prems(1) by auto
    {
      fix p
      assume as: "p tagged_division_of (cbox a b)" "g fine p"
      have hc: "⋀x k. h ((λ(x, k). content k *R f x) x) = (λ(x, k). h (content k *R f x)) x"
        by auto
      then have "(∑(x, k)∈p. content k *R (h ∘ f) x) = setsum (h ∘ (λ(x, k). content k *R f x)) p"
        unfolding o_def unfolding scaleR[symmetric] hc by simp
      also have "… = h (∑(x, k)∈p. content k *R f x)"
        using setsum[of "λ(x,k). content k *R f x" p] using as by auto
      finally have "(∑(x, k)∈p. content k *R (h ∘ f) x) = h (∑(x, k)∈p. content k *R f x)" .
      then have "norm ((∑(x, k)∈p. content k *R (h ∘ f) x) - h y) < e"
        apply (simp add: diff[symmetric])
        apply (rule le_less_trans[OF B(2)])
        using g(2)[OF as] B(1)
        apply (auto simp add: field_simps)
        done
    }
    with g show ?case
      by (rule_tac x=g in exI) auto
  qed
  {
    presume "¬ (∃a b. s = cbox a b) ⟹ ?thesis"
    then show ?thesis
      using assms(1) lem by blast
  }
  assume as: "¬ (∃a b. s = cbox a b)"
  then show ?thesis
  proof (subst has_integral_alt, clarsimp)
    fix e :: real
    assume e: "e > 0"
    have *: "0 < e/B" using e B(1) by simp
    obtain M where M:
      "M > 0"
      "⋀a b. ball 0 M ⊆ cbox a b ⟹
        ∃z. ((λx. if x ∈ s then f x else 0) has_integral z) (cbox a b) ∧ norm (z - y) < e / B"
      using has_integral_altD[OF assms(1) as *] by blast
    show "∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ s then (h ∘ f) x else 0) has_integral z) (cbox a b) ∧ norm (z - h y) < e)"
    proof (rule_tac x=M in exI, clarsimp simp add: M, goal_cases)
      case prems: (1 a b)
      obtain z where z:
        "((λx. if x ∈ s then f x else 0) has_integral z) (cbox a b)"
        "norm (z - y) < e / B"
        using M(2)[OF prems(1)] by blast
      have *: "(λx. if x ∈ s then (h ∘ f) x else 0) = h ∘ (λx. if x ∈ s then f x else 0)"
        using zero by auto
      show ?case
        apply (rule_tac x="h z" in exI)
        apply (simp add: * lem z(1))
        apply (metis B diff le_less_trans pos_less_divide_eq z(2))
        done
    qed
  qed
qed

lemma has_integral_scaleR_left:
  "(f has_integral y) s ⟹ ((λx. f x *R c) has_integral (y *R c)) s"
  using has_integral_linear[OF _ bounded_linear_scaleR_left] by (simp add: comp_def)

lemma has_integral_mult_left:
  fixes c :: "_ :: real_normed_algebra"
  shows "(f has_integral y) s ⟹ ((λx. f x * c) has_integral (y * c)) s"
  using has_integral_linear[OF _ bounded_linear_mult_left] by (simp add: comp_def)

text‹The case analysis eliminates the condition @{term "f integrable_on s"} at the cost
     of the type class constraint ‹division_ring››
corollary integral_mult_left [simp]:
  fixes c:: "'a::{real_normed_algebra,division_ring}"
  shows "integral s (λx. f x * c) = integral s f * c"
proof (cases "f integrable_on s ∨ c = 0")
  case True then show ?thesis
    by (force intro: has_integral_mult_left)
next
  case False then have "~ (λx. f x * c) integrable_on s"
    using has_integral_mult_left [of "(λx. f x * c)" _ s "inverse c"]
    by (force simp add: mult.assoc)
  with False show ?thesis by (simp add: not_integrable_integral)
qed

corollary integral_mult_right [simp]:
  fixes c:: "'a::{real_normed_field}"
  shows "integral s (λx. c * f x) = c * integral s f"
by (simp add: mult.commute [of c])

corollary integral_divide [simp]:
  fixes z :: "'a::real_normed_field"
  shows "integral S (λx. f x / z) = integral S (λx. f x) / z"
using integral_mult_left [of S f "inverse z"]
  by (simp add: divide_inverse_commute)

lemma has_integral_mult_right:
  fixes c :: "'a :: real_normed_algebra"
  shows "(f has_integral y) i ⟹ ((λx. c * f x) has_integral (c * y)) i"
  using has_integral_linear[OF _ bounded_linear_mult_right] by (simp add: comp_def)

lemma has_integral_cmul: "(f has_integral k) s ⟹ ((λx. c *R f x) has_integral (c *R k)) s"
  unfolding o_def[symmetric]
  by (metis has_integral_linear bounded_linear_scaleR_right)

lemma has_integral_cmult_real:
  fixes c :: real
  assumes "c ≠ 0 ⟹ (f has_integral x) A"
  shows "((λx. c * f x) has_integral c * x) A"
proof (cases "c = 0")
  case True
  then show ?thesis by simp
next
  case False
  from has_integral_cmul[OF assms[OF this], of c] show ?thesis
    unfolding real_scaleR_def .
qed

lemma has_integral_neg: "(f has_integral k) s ⟹ ((λx. -(f x)) has_integral -k) s"
  by (drule_tac c="-1" in has_integral_cmul) auto

lemma has_integral_add:
  fixes f :: "'n::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "(f has_integral k) s"
    and "(g has_integral l) s"
  shows "((λx. f x + g x) has_integral (k + l)) s"
proof -
  have lem: "((λx. f x + g x) has_integral (k + l)) (cbox a b)"
    if f_k: "(f has_integral k) (cbox a b)"
    and g_l: "(g has_integral l) (cbox a b)"
    for f :: "'n ⇒ 'a" and g a b k l
    unfolding has_integral
  proof clarify
    fix e :: real
    assume e: "e > 0"
    then have *: "e / 2 > 0"
      by auto
    obtain d1 where d1:
      "gauge d1"
      "⋀p. p tagged_division_of (cbox a b) ⟹ d1 fine p ⟹
        norm ((∑(x, k)∈p. content k *R f x) - k) < e / 2"
      using has_integralD[OF f_k *] by blast
    obtain d2 where d2:
      "gauge d2"
      "⋀p. p tagged_division_of (cbox a b) ⟹ d2 fine p ⟹
        norm ((∑(x, k)∈p. content k *R g x) - l) < e / 2"
      using has_integralD[OF g_l *] by blast
    show "∃d. gauge d ∧ (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
              norm ((∑(x, k)∈p. content k *R (f x + g x)) - (k + l)) < e)"
    proof (rule exI [where x="λx. (d1 x) ∩ (d2 x)"], clarsimp simp add: gauge_inter[OF d1(1) d2(1)])
      fix p
      assume as: "p tagged_division_of (cbox a b)" "(λx. d1 x ∩ d2 x) fine p"
      have *: "(∑(x, k)∈p. content k *R (f x + g x)) =
        (∑(x, k)∈p. content k *R f x) + (∑(x, k)∈p. content k *R g x)"
        unfolding scaleR_right_distrib setsum.distrib[of "λ(x,k). content k *R f x" "λ(x,k). content k *R g x" p,symmetric]
        by (rule setsum.cong) auto
      from as have fine: "d1 fine p" "d2 fine p"
        unfolding fine_inter by auto
      have "norm ((∑(x, k)∈p. content k *R (f x + g x)) - (k + l)) =
            norm (((∑(x, k)∈p. content k *R f x) - k) + ((∑(x, k)∈p. content k *R g x) - l))"
        unfolding * by (auto simp add: algebra_simps)
      also have "… < e/2 + e/2"
        apply (rule le_less_trans[OF norm_triangle_ineq])
        using as d1 d2 fine
        apply (blast intro: add_strict_mono)
        done
      finally show "norm ((∑(x, k)∈p. content k *R (f x + g x)) - (k + l)) < e"
        by auto
    qed
  qed
  {
    presume "¬ (∃a b. s = cbox a b) ⟹ ?thesis"
    then show ?thesis
      using assms lem by force
  }
  assume as: "¬ (∃a b. s = cbox a b)"
  then show ?thesis
  proof (subst has_integral_alt, clarsimp, goal_cases)
    case (1 e)
    then have *: "e / 2 > 0"
      by auto
    from has_integral_altD[OF assms(1) as *]
    obtain B1 where B1:
        "0 < B1"
        "⋀a b. ball 0 B1 ⊆ cbox a b ⟹
          ∃z. ((λx. if x ∈ s then f x else 0) has_integral z) (cbox a b) ∧ norm (z - k) < e / 2"
      by blast
    from has_integral_altD[OF assms(2) as *]
    obtain B2 where B2:
        "0 < B2"
        "⋀a b. ball 0 B2 ⊆ (cbox a b) ⟹
          ∃z. ((λx. if x ∈ s then g x else 0) has_integral z) (cbox a b) ∧ norm (z - l) < e / 2"
      by blast
    show ?case
    proof (rule_tac x="max B1 B2" in exI, clarsimp simp add: max.strict_coboundedI1 B1)
      fix a b
      assume "ball 0 (max B1 B2) ⊆ cbox a (b::'n)"
      then have *: "ball 0 B1 ⊆ cbox a (b::'n)" "ball 0 B2 ⊆ cbox a (b::'n)"
        by auto
      obtain w where w:
        "((λx. if x ∈ s then f x else 0) has_integral w) (cbox a b)"
        "norm (w - k) < e / 2"
        using B1(2)[OF *(1)] by blast
      obtain z where z:
        "((λx. if x ∈ s then g x else 0) has_integral z) (cbox a b)"
        "norm (z - l) < e / 2"
        using B2(2)[OF *(2)] by blast
      have *: "⋀x. (if x ∈ s then f x + g x else 0) =
        (if x ∈ s then f x else 0) + (if x ∈ s then g x else 0)"
        by auto
      show "∃z. ((λx. if x ∈ s then f x + g x else 0) has_integral z) (cbox a b) ∧ norm (z - (k + l)) < e"
        apply (rule_tac x="w + z" in exI)
        apply (simp add: lem[OF w(1) z(1), unfolded *[symmetric]])
        using norm_triangle_ineq[of "w - k" "z - l"] w(2) z(2)
        apply (auto simp add: field_simps)
        done
    qed
  qed
qed

lemma has_integral_sub:
  "(f has_integral k) s ⟹ (g has_integral l) s ⟹
    ((λx. f x - g x) has_integral (k - l)) s"
  using has_integral_add[OF _ has_integral_neg, of f k s g l]
  unfolding algebra_simps
  by auto

lemma integral_0 [simp]:
  "integral s (λx::'n::euclidean_space. 0::'m::real_normed_vector) = 0"
  by (rule integral_unique has_integral_0)+

lemma integral_add: "f integrable_on s ⟹ g integrable_on s ⟹
    integral s (λx. f x + g x) = integral s f + integral s g"
  by (rule integral_unique) (metis integrable_integral has_integral_add)

lemma integral_cmul [simp]: "integral s (λx. c *R f x) = c *R integral s f"
proof (cases "f integrable_on s ∨ c = 0")
  case True with has_integral_cmul show ?thesis by force
next
  case False then have "~ (λx. c *R f x) integrable_on s"
    using has_integral_cmul [of "(λx. c *R f x)" _ s "inverse c"]
    by force
  with False show ?thesis by (simp add: not_integrable_integral)
qed

lemma integral_neg [simp]: "integral s (λx. - f x) = - integral s f"
proof (cases "f integrable_on s")
  case True then show ?thesis
    by (simp add: has_integral_neg integrable_integral integral_unique)
next
  case False then have "~ (λx. - f x) integrable_on s"
    using has_integral_neg [of "(λx. - f x)" _ s ]
    by force
  with False show ?thesis by (simp add: not_integrable_integral)
qed

lemma integral_diff: "f integrable_on s ⟹ g integrable_on s ⟹
    integral s (λx. f x - g x) = integral s f - integral s g"
  by (rule integral_unique) (metis integrable_integral has_integral_sub)

lemma integrable_0: "(λx. 0) integrable_on s"
  unfolding integrable_on_def using has_integral_0 by auto

lemma integrable_add: "f integrable_on s ⟹ g integrable_on s ⟹ (λx. f x + g x) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_add)

lemma integrable_cmul: "f integrable_on s ⟹ (λx. c *R f(x)) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_cmul)

lemma integrable_on_cmult_iff:
  fixes c :: real
  assumes "c ≠ 0"
  shows "(λx. c * f x) integrable_on s ⟷ f integrable_on s"
  using integrable_cmul[of "λx. c * f x" s "1 / c"] integrable_cmul[of f s c] ‹c ≠ 0›
  by auto

lemma integrable_on_cmult_left:
  assumes "f integrable_on s"
  shows "(λx. of_real c * f x) integrable_on s"
    using integrable_cmul[of f s "of_real c"] assms
    by (simp add: scaleR_conv_of_real)

lemma integrable_neg: "f integrable_on s ⟹ (λx. -f(x)) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_neg)

lemma integrable_diff:
  "f integrable_on s ⟹ g integrable_on s ⟹ (λx. f x - g x) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_sub)

lemma integrable_linear:
  "f integrable_on s ⟹ bounded_linear h ⟹ (h ∘ f) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_linear)

lemma integral_linear:
  "f integrable_on s ⟹ bounded_linear h ⟹ integral s (h ∘ f) = h (integral s f)"
  apply (rule has_integral_unique [where i=s and f = "h ∘ f"])
  apply (simp_all add: integrable_integral integrable_linear has_integral_linear )
  done

lemma integral_component_eq[simp]:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "f integrable_on s"
  shows "integral s (λx. f x ∙ k) = integral s f ∙ k"
  unfolding integral_linear[OF assms(1) bounded_linear_component,unfolded o_def] ..

lemma has_integral_setsum:
  assumes "finite t"
    and "∀a∈t. ((f a) has_integral (i a)) s"
  shows "((λx. setsum (λa. f a x) t) has_integral (setsum i t)) s"
  using assms(1) subset_refl[of t]
proof (induct rule: finite_subset_induct)
  case empty
  then show ?case by auto
next
  case (insert x F)
  with assms show ?case
    by (simp add: has_integral_add)
qed

lemma integral_setsum:
  "⟦finite t;  ∀a∈t. (f a) integrable_on s⟧ ⟹
   integral s (λx. setsum (λa. f a x) t) = setsum (λa. integral s (f a)) t"
  by (auto intro: has_integral_setsum integrable_integral)

lemma integrable_setsum:
  "⟦finite t;  ∀a∈t. (f a) integrable_on s⟧ ⟹ (λx. setsum (λa. f a x) t) integrable_on s"
  unfolding integrable_on_def
  apply (drule bchoice)
  using has_integral_setsum[of t]
  apply auto
  done

lemma has_integral_eq:
  assumes "⋀x. x ∈ s ⟹ f x = g x"
    and "(f has_integral k) s"
  shows "(g has_integral k) s"
  using has_integral_sub[OF assms(2), of "λx. f x - g x" 0]
  using has_integral_is_0[of s "λx. f x - g x"]
  using assms(1)
  by auto

lemma integrable_eq: "(⋀x. x ∈ s ⟹ f x = g x) ⟹ f integrable_on s ⟹ g integrable_on s"
  unfolding integrable_on_def
  using has_integral_eq[of s f g] has_integral_eq by blast

lemma has_integral_cong:
  assumes "⋀x. x ∈ s ⟹ f x = g x"
  shows "(f has_integral i) s = (g has_integral i) s"
  using has_integral_eq[of s f g] has_integral_eq[of s g f] assms
  by auto

lemma integral_cong:
  assumes "⋀x. x ∈ s ⟹ f x = g x"
  shows "integral s f = integral s g"
  unfolding integral_def
by (metis (full_types, hide_lams) assms has_integral_cong integrable_eq)

lemma integrable_on_cmult_left_iff [simp]:
  assumes "c ≠ 0"
  shows "(λx. of_real c * f x) integrable_on s ⟷ f integrable_on s"
        (is "?lhs = ?rhs")
proof
  assume ?lhs
  then have "(λx. of_real (1 / c) * (of_real c * f x)) integrable_on s"
    using integrable_cmul[of "λx. of_real c * f x" s "1 / of_real c"]
    by (simp add: scaleR_conv_of_real)
  then have "(λx. (of_real (1 / c) * of_real c * f x)) integrable_on s"
    by (simp add: algebra_simps)
  with ‹c ≠ 0› show ?rhs
    by (metis (no_types, lifting) integrable_eq mult.left_neutral nonzero_divide_eq_eq of_real_1 of_real_mult)
qed (blast intro: integrable_on_cmult_left)

lemma integrable_on_cmult_right:
  fixes f :: "_ ⇒ 'b :: {comm_ring,real_algebra_1,real_normed_vector}"
  assumes "f integrable_on s"
  shows "(λx. f x * of_real c) integrable_on s"
using integrable_on_cmult_left [OF assms] by (simp add: mult.commute)

lemma integrable_on_cmult_right_iff [simp]:
  fixes f :: "_ ⇒ 'b :: {comm_ring,real_algebra_1,real_normed_vector}"
  assumes "c ≠ 0"
  shows "(λx. f x * of_real c) integrable_on s ⟷ f integrable_on s"
using integrable_on_cmult_left_iff [OF assms] by (simp add: mult.commute)

lemma integrable_on_cdivide:
  fixes f :: "_ ⇒ 'b :: real_normed_field"
  assumes "f integrable_on s"
  shows "(λx. f x / of_real c) integrable_on s"
by (simp add: integrable_on_cmult_right divide_inverse assms of_real_inverse [symmetric] del: of_real_inverse)

lemma integrable_on_cdivide_iff [simp]:
  fixes f :: "_ ⇒ 'b :: real_normed_field"
  assumes "c ≠ 0"
  shows "(λx. f x / of_real c) integrable_on s ⟷ f integrable_on s"
by (simp add: divide_inverse assms of_real_inverse [symmetric] del: of_real_inverse)

lemma has_integral_null [intro]:
  assumes "content(cbox a b) = 0"
  shows "(f has_integral 0) (cbox a b)"
proof -
  have "gauge (λx. ball x 1)"
    by auto
  moreover
  {
    fix e :: real
    fix p
    assume e: "e > 0"
    assume p: "p tagged_division_of (cbox a b)"
    have "norm ((∑(x, k)∈p. content k *R f x) - 0) = 0"
      unfolding norm_eq_zero diff_0_right
      using setsum_content_null[OF assms(1) p, of f] .
    then have "norm ((∑(x, k)∈p. content k *R f x) - 0) < e"
      using e by auto
  }
  ultimately show ?thesis
    by (auto simp: has_integral)
qed

lemma has_integral_null_real [intro]:
  assumes "content {a .. b::real} = 0"
  shows "(f has_integral 0) {a .. b}"
  by (metis assms box_real(2) has_integral_null)

lemma has_integral_null_eq[simp]: "content (cbox a b) = 0 ⟹ (f has_integral i) (cbox a b) ⟷ i = 0"
  by (auto simp add: has_integral_null dest!: integral_unique)

lemma integral_null [simp]: "content (cbox a b) = 0 ⟹ integral (cbox a b) f = 0"
  by (metis has_integral_null integral_unique)

lemma integrable_on_null [intro]: "content (cbox a b) = 0 ⟹ f integrable_on (cbox a b)"
  by (simp add: has_integral_integrable)

lemma has_integral_empty[intro]: "(f has_integral 0) {}"
  by (simp add: has_integral_is_0)

lemma has_integral_empty_eq[simp]: "(f has_integral i) {} ⟷ i = 0"
  by (auto simp add: has_integral_empty has_integral_unique)

lemma integrable_on_empty[intro]: "f integrable_on {}"
  unfolding integrable_on_def by auto

lemma integral_empty[simp]: "integral {} f = 0"
  by (rule integral_unique) (rule has_integral_empty)

lemma has_integral_refl[intro]:
  fixes a :: "'a::euclidean_space"
  shows "(f has_integral 0) (cbox a a)"
    and "(f has_integral 0) {a}"
proof -
  have *: "{a} = cbox a a"
    apply (rule set_eqI)
    unfolding mem_box singleton_iff euclidean_eq_iff[where 'a='a]
    apply safe
    prefer 3
    apply (erule_tac x=b in ballE)
    apply (auto simp add: field_simps)
    done
  show "(f has_integral 0) (cbox a a)" "(f has_integral 0) {a}"
    unfolding *
    apply (rule_tac[!] has_integral_null)
    unfolding content_eq_0_interior
    unfolding interior_cbox
    using box_sing
    apply auto
    done
qed

lemma integrable_on_refl[intro]: "f integrable_on cbox a a"
  unfolding integrable_on_def by auto

lemma integral_refl [simp]: "integral (cbox a a) f = 0"
  by (rule integral_unique) auto

lemma integral_singleton [simp]: "integral {a} f = 0"
  by auto

lemma integral_blinfun_apply:
  assumes "f integrable_on s"
  shows "integral s (λx. blinfun_apply h (f x)) = blinfun_apply h (integral s f)"
  by (subst integral_linear[symmetric, OF assms blinfun.bounded_linear_right]) (simp add: o_def)

lemma blinfun_apply_integral:
  assumes "f integrable_on s"
  shows "blinfun_apply (integral s f) x = integral s (λy. blinfun_apply (f y) x)"
  by (metis (no_types, lifting) assms blinfun.prod_left.rep_eq integral_blinfun_apply integral_cong)


subsection ‹Cauchy-type criterion for integrability.›

(* XXXXXXX *)
lemma integrable_cauchy:
  fixes f :: "'n::euclidean_space ⇒ 'a::{real_normed_vector,complete_space}"
  shows "f integrable_on cbox a b ⟷
    (∀e>0.∃d. gauge d ∧
      (∀p1 p2. p1 tagged_division_of (cbox a b) ∧ d fine p1 ∧
        p2 tagged_division_of (cbox a b) ∧ d fine p2 ⟶
        norm (setsum (λ(x,k). content k *R f x) p1 -
        setsum (λ(x,k). content k *R f x) p2) < e))"
  (is "?l = (∀e>0. ∃d. ?P e d)")
proof
  assume ?l
  then guess y unfolding integrable_on_def has_integral .. note y=this
  show "∀e>0. ∃d. ?P e d"
  proof (clarify, goal_cases)
    case (1 e)
    then have "e/2 > 0" by auto
    then guess d
      apply -
      apply (drule y[rule_format])
      apply (elim exE conjE)
      done
    note d=this[rule_format]
    show ?case
    proof (rule_tac x=d in exI, clarsimp simp: d)
      fix p1 p2
      assume as: "p1 tagged_division_of (cbox a b)" "d fine p1"
                 "p2 tagged_division_of (cbox a b)" "d fine p2"
      show "norm ((∑(x, k)∈p1. content k *R f x) - (∑(x, k)∈p2. content k *R f x)) < e"
        apply (rule dist_triangle_half_l[where y=y,unfolded dist_norm])
        using d(2)[OF conjI[OF as(1-2)]] d(2)[OF conjI[OF as(3-4)]] .
    qed
  qed
next
  assume "∀e>0. ∃d. ?P e d"
  then have "∀n::nat. ∃d. ?P (inverse(of_nat (n + 1))) d"
    by auto
  from choice[OF this] guess d .. note d=conjunctD2[OF this[rule_format],rule_format]
  have "⋀n. gauge (λx. ⋂{d i x |i. i ∈ {0..n}})"
    apply (rule gauge_inters)
    using d(1)
    apply auto
    done
  then have "∀n. ∃p. p tagged_division_of (cbox a b) ∧ (λx. ⋂{d i x |i. i ∈ {0..n}}) fine p"
    by (meson fine_division_exists)
  from choice[OF this] guess p .. note p = conjunctD2[OF this[rule_format]]
  have dp: "⋀i n. i≤n ⟹ d i fine p n"
    using p(2) unfolding fine_inters by auto
  have "Cauchy (λn. setsum (λ(x,k). content k *R (f x)) (p n))"
  proof (rule CauchyI, goal_cases)
    case (1 e)
    then guess N unfolding real_arch_inverse[of e] .. note N=this
    show ?case
      apply (rule_tac x=N in exI)
    proof clarify
      fix m n
      assume mn: "N ≤ m" "N ≤ n"
      have *: "N = (N - 1) + 1" using N by auto
      show "norm ((∑(x, k)∈p m. content k *R f x) - (∑(x, k)∈p n. content k *R f x)) < e"
        apply (rule less_trans[OF _ N[THEN conjunct2,THEN conjunct2]])
        apply(subst *)
        using dp p(1) mn d(2) by auto
    qed
  qed
  then guess y unfolding convergent_eq_cauchy[symmetric] .. note y=this[THEN LIMSEQ_D]
  show ?l
    unfolding integrable_on_def has_integral
  proof (rule_tac x=y in exI, clarify)
    fix e :: real
    assume "e>0"
    then have *:"e/2 > 0" by auto
    then guess N1 unfolding real_arch_inverse[of "e/2"] .. note N1=this
    then have N1': "N1 = N1 - 1 + 1"
      by auto
    guess N2 using y[OF *] .. note N2=this
    have "gauge (d (N1 + N2))"
      using d by auto
    moreover
    {
      fix q
      assume as: "q tagged_division_of (cbox a b)" "d (N1 + N2) fine q"
      have *: "inverse (of_nat (N1 + N2 + 1)) < e / 2"
        apply (rule less_trans)
        using N1
        apply auto
        done
      have "norm ((∑(x, k)∈q. content k *R f x) - y) < e"
        apply (rule norm_triangle_half_r)
        apply (rule less_trans[OF _ *])
        apply (subst N1', rule d(2)[of "p (N1+N2)"])
        using N1' as(1) as(2) dp
        apply (simp add: ‹∀x. p x tagged_division_of cbox a b ∧ (λxa. ⋂{d i xa |i. i ∈ {0..x}}) fine p x›)
        using N2 le_add2 by blast
    }
    ultimately show "∃d. gauge d ∧
      (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
        norm ((∑(x, k)∈p. content k *R f x) - y) < e)"
      by (rule_tac x="d (N1 + N2)" in exI) auto
  qed
qed


subsection ‹Additivity of integral on abutting intervals.›

lemma interval_split:
  fixes a :: "'a::euclidean_space"
  assumes "k ∈ Basis"
  shows
    "cbox a b ∩ {x. x∙k ≤ c} = cbox a (∑i∈Basis. (if i = k then min (b∙k) c else b∙i) *R i)"
    "cbox a b ∩ {x. x∙k ≥ c} = cbox (∑i∈Basis. (if i = k then max (a∙k) c else a∙i) *R i) b"
  apply (rule_tac[!] set_eqI)
  unfolding Int_iff mem_box mem_Collect_eq
  using assms
  apply auto
  done

lemma content_split:
  fixes a :: "'a::euclidean_space"
  assumes "k ∈ Basis"
  shows "content (cbox a b) = content(cbox a b ∩ {x. x∙k ≤ c}) + content(cbox a b ∩ {x. x∙k ≥ c})"
proof cases
  note simps = interval_split[OF assms] content_cbox_cases
  have *: "Basis = insert k (Basis - {k})" "⋀x. finite (Basis-{x})" "⋀x. x∉Basis-{x}"
    using assms by auto
  have *: "⋀X Y Z. (∏i∈Basis. Z i (if i = k then X else Y i)) = Z k X * (∏i∈Basis-{k}. Z i (Y i))"
    "(∏i∈Basis. b∙i - a∙i) = (∏i∈Basis-{k}. b∙i - a∙i) * (b∙k - a∙k)"
    apply (subst *(1))
    defer
    apply (subst *(1))
    unfolding setprod.insert[OF *(2-)]
    apply auto
    done
  assume as: "∀i∈Basis. a ∙ i ≤ b ∙ i"
  moreover
  have "⋀x. min (b ∙ k) c = max (a ∙ k) c ⟹
    x * (b∙k - a∙k) = x * (max (a ∙ k) c - a ∙ k) + x * (b ∙ k - max (a ∙ k) c)"
    by  (auto simp add: field_simps)
  moreover
  have **: "(∏i∈Basis. ((∑i∈Basis. (if i = k then min (b ∙ k) c else b ∙ i) *R i) ∙ i - a ∙ i)) =
      (∏i∈Basis. (if i = k then min (b ∙ k) c else b ∙ i) - a ∙ i)"
    "(∏i∈Basis. b ∙ i - ((∑i∈Basis. (if i = k then max (a ∙ k) c else a ∙ i) *R i) ∙ i)) =
      (∏i∈Basis. b ∙ i - (if i = k then max (a ∙ k) c else a ∙ i))"
    by (auto intro!: setprod.cong)
  have "¬ a ∙ k ≤ c ⟹ ¬ c ≤ b ∙ k ⟹ False"
    unfolding not_le
    using as[unfolded ,rule_format,of k] assms
    by auto
  ultimately show ?thesis
    using assms
    unfolding simps **
    unfolding *(1)[of "λi x. b∙i - x"] *(1)[of "λi x. x - a∙i"]
    unfolding *(2)
    by auto
next
  assume "¬ (∀i∈Basis. a ∙ i ≤ b ∙ i)"
  then have "cbox a b = {}"
    unfolding box_eq_empty by (auto simp: not_le)
  then show ?thesis
    by (auto simp: not_le)
qed

lemma division_split_left_inj:
  fixes type :: "'a::euclidean_space"
  assumes "d division_of i"
    and "k1 ∈ d"
    and "k2 ∈ d"
    and "k1 ≠ k2"
    and "k1 ∩ {x::'a. x∙k ≤ c} = k2 ∩ {x. x∙k ≤ c}"
    and k: "k∈Basis"
  shows "content(k1 ∩ {x. x∙k ≤ c}) = 0"
proof -
  note d=division_ofD[OF assms(1)]
  have *: "⋀(a::'a) b c. content (cbox a b ∩ {x. x∙k ≤ c}) = 0 ⟷
    interior(cbox a b ∩ {x. x∙k ≤ c}) = {}"
    unfolding  interval_split[OF k] content_eq_0_interior by auto
  guess u1 v1 using d(4)[OF assms(2)] by (elim exE) note uv1=this
  guess u2 v2 using d(4)[OF assms(3)] by (elim exE) note uv2=this
  have **: "⋀s t u. s ∩ t = {} ⟹ u ⊆ s ⟹ u ⊆ t ⟹ u = {}"
    by auto
  show ?thesis
    unfolding uv1 uv2 *
    apply (rule **[OF d(5)[OF assms(2-4)]])
    apply (simp add: uv1)
    using assms(5) uv1 by auto
qed

lemma division_split_right_inj:
  fixes type :: "'a::euclidean_space"
  assumes "d division_of i"
    and "k1 ∈ d"
    and "k2 ∈ d"
    and "k1 ≠ k2"
    and "k1 ∩ {x::'a. x∙k ≥ c} = k2 ∩ {x. x∙k ≥ c}"
    and k: "k ∈ Basis"
  shows "content (k1 ∩ {x. x∙k ≥ c}) = 0"
proof -
  note d=division_ofD[OF assms(1)]
  have *: "⋀a b::'a. ⋀c. content(cbox a b ∩ {x. x∙k ≥ c}) = 0 ⟷
    interior(cbox a b ∩ {x. x∙k ≥ c}) = {}"
    unfolding interval_split[OF k] content_eq_0_interior by auto
  guess u1 v1 using d(4)[OF assms(2)] by (elim exE) note uv1=this
  guess u2 v2 using d(4)[OF assms(3)] by (elim exE) note uv2=this
  have **: "⋀s t u. s ∩ t = {} ⟹ u ⊆ s ⟹ u ⊆ t ⟹ u = {}"
    by auto
  show ?thesis
    unfolding uv1 uv2 *
    apply (rule **[OF d(5)[OF assms(2-4)]])
    apply (simp add: uv1)
    using assms(5) uv1 by auto
qed

lemma tagged_division_split_left_inj:
  fixes x1 :: "'a::euclidean_space"
  assumes d: "d tagged_division_of i"
    and k12: "(x1, k1) ∈ d"
             "(x2, k2) ∈ d"
             "k1 ≠ k2"
             "k1 ∩ {x. x∙k ≤ c} = k2 ∩ {x. x∙k ≤ c}"
             "k ∈ Basis"
  shows "content (k1 ∩ {x. x∙k ≤ c}) = 0"
proof -
  have *: "⋀a b c. (a,b) ∈ c ⟹ b ∈ snd ` c"
    by force
  show ?thesis
    using k12
    by (fastforce intro!:  division_split_left_inj[OF division_of_tagged_division[OF d]] *)
qed

lemma tagged_division_split_right_inj:
  fixes x1 :: "'a::euclidean_space"
  assumes d: "d tagged_division_of i"
    and k12: "(x1, k1) ∈ d"
             "(x2, k2) ∈ d"
             "k1 ≠ k2"
             "k1 ∩ {x. x∙k ≥ c} = k2 ∩ {x. x∙k ≥ c}"
             "k ∈ Basis"
  shows "content (k1 ∩ {x. x∙k ≥ c}) = 0"
proof -
  have *: "⋀a b c. (a,b) ∈ c ⟹ b ∈ snd ` c"
    by force
  show ?thesis
    using k12
    by (fastforce intro!:  division_split_right_inj[OF division_of_tagged_division[OF d]] *)
qed

lemma division_split:
  fixes a :: "'a::euclidean_space"
  assumes "p division_of (cbox a b)"
    and k: "k∈Basis"
  shows "{l ∩ {x. x∙k ≤ c} | l. l ∈ p ∧ l ∩ {x. x∙k ≤ c} ≠ {}} division_of(cbox a b ∩ {x. x∙k ≤ c})"
      (is "?p1 division_of ?I1")
    and "{l ∩ {x. x∙k ≥ c} | l. l ∈ p ∧ l ∩ {x. x∙k ≥ c} ≠ {}} division_of (cbox a b ∩ {x. x∙k ≥ c})"
      (is "?p2 division_of ?I2")
proof (rule_tac[!] division_ofI)
  note p = division_ofD[OF assms(1)]
  show "finite ?p1" "finite ?p2"
    using p(1) by auto
  show "⋃?p1 = ?I1" "⋃?p2 = ?I2"
    unfolding p(6)[symmetric] by auto
  {
    fix k
    assume "k ∈ ?p1"
    then guess l unfolding mem_Collect_eq by (elim exE conjE) note l=this
    guess u v using p(4)[OF l(2)] by (elim exE) note uv=this
    show "k ⊆ ?I1"
      using l p(2) uv by force
    show  "k ≠ {}"
      by (simp add: l)
    show  "∃a b. k = cbox a b"
      apply (simp add: l uv p(2-3)[OF l(2)])
      apply (subst interval_split[OF k])
      apply (auto intro: order.trans)
      done
    fix k'
    assume "k' ∈ ?p1"
    then guess l' unfolding mem_Collect_eq by (elim exE conjE) note l'=this
    assume "k ≠ k'"
    then show "interior k ∩ interior k' = {}"
      unfolding l l' using p(5)[OF l(2) l'(2)] by auto
  }
  {
    fix k
    assume "k ∈ ?p2"
    then guess l unfolding mem_Collect_eq by (elim exE conjE) note l=this
    guess u v using p(4)[OF l(2)] by (elim exE) note uv=this
    show "k ⊆ ?I2"
      using l p(2) uv by force
    show  "k ≠ {}"
      by (simp add: l)
    show  "∃a b. k = cbox a b"
      apply (simp add: l uv p(2-3)[OF l(2)])
      apply (subst interval_split[OF k])
      apply (auto intro: order.trans)
      done
    fix k'
    assume "k' ∈ ?p2"
    then guess l' unfolding mem_Collect_eq by (elim exE conjE) note l'=this
    assume "k ≠ k'"
    then show "interior k ∩ interior k' = {}"
      unfolding l l' using p(5)[OF l(2) l'(2)] by auto
  }
qed

lemma has_integral_split:
  fixes f :: "'a::euclidean_space ⇒ 'b::real_normed_vector"
  assumes fi: "(f has_integral i) (cbox a b ∩ {x. x∙k ≤ c})"
      and fj: "(f has_integral j) (cbox a b ∩ {x. x∙k ≥ c})"
      and k: "k ∈ Basis"
  shows "(f has_integral (i + j)) (cbox a b)"
proof (unfold has_integral, rule, rule, goal_cases)
  case (1 e)
  then have e: "e/2 > 0"
    by auto
    obtain d1
    where d1: "gauge d1"
      and d1norm:
        "⋀p. ⟦p tagged_division_of cbox a b ∩ {x. x ∙ k ≤ c};
               d1 fine p⟧ ⟹ norm ((∑(x, k) ∈ p. content k *R f x) - i) < e / 2"
       apply (rule has_integralD[OF fi[unfolded interval_split[OF k]] e])
       apply (simp add: interval_split[symmetric] k)
       done
    obtain d2
    where d2: "gauge d2"
      and d2norm:
        "⋀p. ⟦p tagged_division_of cbox a b ∩ {x. c ≤ x ∙ k};
               d2 fine p⟧ ⟹ norm ((∑(x, k) ∈ p. content k *R f x) - j) < e / 2"
       apply (rule has_integralD[OF fj[unfolded interval_split[OF k]] e])
       apply (simp add: interval_split[symmetric] k)
       done
  let ?d = "λx. if x∙k = c then (d1 x ∩ d2 x) else ball x ¦x∙k - c¦ ∩ d1 x ∩ d2 x"
  have "gauge ?d"
    using d1 d2 unfolding gauge_def by auto
  then show ?case
  proof (rule_tac x="?d" in exI, safe)
    fix p
    assume "p tagged_division_of (cbox a b)" "?d fine p"
    note p = this tagged_division_ofD[OF this(1)]
    have xk_le_c: "⋀x kk. (x, kk) ∈ p ⟹ kk ∩ {x. x∙k ≤ c} ≠ {} ⟹ x∙k ≤ c"
    proof -
      fix x kk
      assume as: "(x, kk) ∈ p" and kk: "kk ∩ {x. x∙k ≤ c} ≠ {}"
      show "x∙k ≤ c"
      proof (rule ccontr)
        assume **: "¬ ?thesis"
        from this[unfolded not_le]
        have "kk ⊆ ball x ¦x ∙ k - c¦"
          using p(2)[unfolded fine_def, rule_format,OF as] by auto
        with kk obtain y where y: "y ∈ ball x ¦x ∙ k - c¦" "y∙k ≤ c"
          by blast
        then have "¦x ∙ k - y ∙ k¦ < ¦x ∙ k - c¦"
          using Basis_le_norm[OF k, of "x - y"]
          by (auto simp add: dist_norm inner_diff_left intro: le_less_trans)
        with y show False
          using ** by (auto simp add: field_simps)
      qed
    qed
    have xk_ge_c: "⋀x kk. (x, kk) ∈ p ⟹ kk ∩ {x. x∙k ≥ c} ≠ {} ⟹ x∙k ≥ c"
    proof -
      fix x kk
      assume as: "(x, kk) ∈ p" and kk: "kk ∩ {x. x∙k ≥ c} ≠ {}"
      show "x∙k ≥ c"
      proof (rule ccontr)
        assume **: "¬ ?thesis"
        from this[unfolded not_le] have "kk ⊆ ball x ¦x ∙ k - c¦"
          using p(2)[unfolded fine_def,rule_format,OF as,unfolded split_conv] by auto
        with kk obtain y where y: "y ∈ ball x ¦x ∙ k - c¦" "y∙k ≥ c"
          by blast
        then have "¦x ∙ k - y ∙ k¦ < ¦x ∙ k - c¦"
          using Basis_le_norm[OF k, of "x - y"]
          by (auto simp add: dist_norm inner_diff_left intro: le_less_trans)
        with y show False
          using ** by (auto simp add: field_simps)
      qed
    qed

    have lem1: "⋀f P Q. (∀x k. (x, k) ∈ {(x, f k) | x k. P x k} ⟶ Q x k) ⟷
                         (∀x k. P x k ⟶ Q x (f k))"
      by auto
    have fin_finite: "finite {(x,f k) | x k. (x,k) ∈ s ∧ P x k}" if "finite s" for f s P
    proof -
      from that have "finite ((λ(x, k). (x, f k)) ` s)"
        by auto
      then show ?thesis
        by (rule rev_finite_subset) auto
    qed
    { fix g :: "'a set ⇒ 'a set"
      fix i :: "'a × 'a set"
      assume "i ∈ (λ(x, k). (x, g k)) ` p - {(x, g k) |x k. (x, k) ∈ p ∧ g k ≠ {}}"
      then obtain x k where xk:
              "i = (x, g k)"  "(x, k) ∈ p"
              "(x, g k) ∉ {(x, g k) |x k. (x, k) ∈ p ∧ g k ≠ {}}"
          by auto
      have "content (g k) = 0"
        using xk using content_empty by auto
      then have "(λ(x, k). content k *R f x) i = 0"
        unfolding xk split_conv by auto
    } note [simp] = this
    have lem3: "⋀g :: 'a set ⇒ 'a set. finite p ⟹
                  setsum (λ(x, k). content k *R f x) {(x,g k) |x k. (x,k) ∈ p ∧ g k ≠ {}} =
                  setsum (λ(x, k). content k *R f x) ((λ(x, k). (x, g k)) ` p)"
      by (rule setsum.mono_neutral_left) auto
    let ?M1 = "{(x, kk ∩ {x. x∙k ≤ c}) |x kk. (x, kk) ∈ p ∧ kk ∩ {x. x∙k ≤ c} ≠ {}}"
    have d1_fine: "d1 fine ?M1"
      by (force intro: fineI dest: fineD[OF p(2)] simp add: split: if_split_asm)
    have "norm ((∑(x, k)∈?M1. content k *R f x) - i) < e/2"
    proof (rule d1norm [OF tagged_division_ofI d1_fine])
      show "finite ?M1"
        by (rule fin_finite p(3))+
      show "⋃{k. ∃x. (x, k) ∈ ?M1} = cbox a b ∩ {x. x∙k ≤ c}"
        unfolding p(8)[symmetric] by auto
      fix x l
      assume xl: "(x, l) ∈ ?M1"
      then guess x' l' unfolding mem_Collect_eq unfolding prod.inject by (elim exE conjE) note xl'=this
      show "x ∈ l" "l ⊆ cbox a b ∩ {x. x ∙ k ≤ c}"
        unfolding xl'
        using p(4-6)[OF xl'(3)] using xl'(4)
        using xk_le_c[OF xl'(3-4)] by auto
      show "∃a b. l = cbox a b"
        unfolding xl'
        using p(6)[OF xl'(3)]
        by (fastforce simp add: interval_split[OF k,where c=c])
      fix y r
      let ?goal = "interior l ∩ interior r = {}"
      assume yr: "(y, r) ∈ ?M1"
      then guess y' r' unfolding mem_Collect_eq unfolding prod.inject by (elim exE conjE) note yr'=this
      assume as: "(x, l) ≠ (y, r)"
      show "interior l ∩ interior r = {}"
      proof (cases "l' = r' ⟶ x' = y'")
        case False
        then show ?thesis
          using p(7)[OF xl'(3) yr'(3)] using as unfolding xl' yr' by auto
      next
        case True
        then have "l' ≠ r'"
          using as unfolding xl' yr' by auto
        then show ?thesis
          using p(7)[OF xl'(3) yr'(3)] using as unfolding xl' yr' by auto
      qed
    qed
    moreover
    let ?M2 = "{(x,kk ∩ {x. x∙k ≥ c}) |x kk. (x,kk) ∈ p ∧ kk ∩ {x. x∙k ≥ c} ≠ {}}"
    have d2_fine: "d2 fine ?M2"
      by (force intro: fineI dest: fineD[OF p(2)] simp add: split: if_split_asm)
    have "norm ((∑(x, k)∈?M2. content k *R f x) - j) < e/2"
    proof (rule d2norm [OF tagged_division_ofI d2_fine])
      show "finite ?M2"
        by (rule fin_finite p(3))+
      show "⋃{k. ∃x. (x, k) ∈ ?M2} = cbox a b ∩ {x. x∙k ≥ c}"
        unfolding p(8)[symmetric] by auto
      fix x l
      assume xl: "(x, l) ∈ ?M2"
      then guess x' l' unfolding mem_Collect_eq unfolding prod.inject by (elim exE conjE) note xl'=this
      show "x ∈ l" "l ⊆ cbox a b ∩ {x. x ∙ k ≥ c}"
        unfolding xl'
        using p(4-6)[OF xl'(3)] xl'(4) xk_ge_c[OF xl'(3-4)]
        by auto
      show "∃a b. l = cbox a b"
        unfolding xl'
        using p(6)[OF xl'(3)]
        by (fastforce simp add: interval_split[OF k, where c=c])
      fix y r
      let ?goal = "interior l ∩ interior r = {}"
      assume yr: "(y, r) ∈ ?M2"
      then guess y' r' unfolding mem_Collect_eq unfolding prod.inject by (elim exE conjE) note yr'=this
      assume as: "(x, l) ≠ (y, r)"
      show "interior l ∩ interior r = {}"
      proof (cases "l' = r' ⟶ x' = y'")
        case False
        then show ?thesis
          using p(7)[OF xl'(3) yr'(3)] using as unfolding xl' yr' by auto
      next
        case True
        then have "l' ≠ r'"
          using as unfolding xl' yr' by auto
        then show ?thesis
          using p(7)[OF xl'(3) yr'(3)] using as unfolding xl' yr' by auto
      qed
    qed
    ultimately
    have "norm (((∑(x, k)∈?M1. content k *R f x) - i) + ((∑(x, k)∈?M2. content k *R f x) - j)) < e/2 + e/2"
      using norm_add_less by blast
    also {
      have eq0: "⋀x y. x = (0::real) ⟹ x *R (y::'b) = 0"
        using scaleR_zero_left by auto
      have cont_eq: "⋀g. (λ(x,l). content l *R f x) ∘ (λ(x,l). (x,g l)) = (λ(x,l). content (g l) *R f x)"
        by auto
      have "((∑(x, k)∈?M1. content k *R f x) - i) + ((∑(x, k)∈?M2. content k *R f x) - j) =
        (∑(x, k)∈?M1. content k *R f x) + (∑(x, k)∈?M2. content k *R f x) - (i + j)"
        by auto
      also have "… = (∑(x, ka)∈p. content (ka ∩ {x. x ∙ k ≤ c}) *R f x) +
        (∑(x, ka)∈p. content (ka ∩ {x. c ≤ x ∙ k}) *R f x) - (i + j)"
        unfolding lem3[OF p(3)]
        by (subst setsum.reindex_nontrivial[OF p(3)], auto intro!: k eq0 tagged_division_split_left_inj[OF p(1)] tagged_division_split_right_inj[OF p(1)]
              simp: cont_eq)+
      also note setsum.distrib[symmetric]
      also have "⋀x. x ∈ p ⟹
                    (λ(x,ka). content (ka ∩ {x. x ∙ k ≤ c}) *R f x) x +
                    (λ(x,ka). content (ka ∩ {x. c ≤ x ∙ k}) *R f x) x =
                    (λ(x,ka). content ka *R f x) x"
      proof clarify
        fix a b
        assume "(a, b) ∈ p"
        from p(6)[OF this] guess u v by (elim exE) note uv=this
        then show "content (b ∩ {x. x ∙ k ≤ c}) *R f a + content (b ∩ {x. c ≤ x ∙ k}) *R f a =
          content b *R f a"
          unfolding scaleR_left_distrib[symmetric]
          unfolding uv content_split[OF k,of u v c]
          by auto
      qed
      note setsum.cong [OF _ this]
      finally have "(∑(x, k)∈{(x, kk ∩ {x. x ∙ k ≤ c}) |x kk. (x, kk) ∈ p ∧ kk ∩ {x. x ∙ k ≤ c} ≠ {}}. content k *R f x) - i +
        ((∑(x, k)∈{(x, kk ∩ {x. c ≤ x ∙ k}) |x kk. (x, kk) ∈ p ∧ kk ∩ {x. c ≤ x ∙ k} ≠ {}}. content k *R f x) - j) =
        (∑(x, ka)∈p. content ka *R f x) - (i + j)"
        by auto
    }
    finally show "norm ((∑(x, k)∈p. content k *R f x) - (i + j)) < e"
      by auto
  qed
qed


subsection ‹A sort of converse, integrability on subintervals.›

lemma tagged_division_union_interval:
  fixes a :: "'a::euclidean_space"
  assumes "p1 tagged_division_of (cbox a b ∩ {x. x∙k ≤ (c::real)})"
    and "p2 tagged_division_of (cbox a b ∩ {x. x∙k ≥ c})"
    and k: "k ∈ Basis"
  shows "(p1 ∪ p2) tagged_division_of (cbox a b)"
proof -
  have *: "cbox a b = (cbox a b ∩ {x. x∙k ≤ c}) ∪ (cbox a b ∩ {x. x∙k ≥ c})"
    by auto
  show ?thesis
    apply (subst *)
    apply (rule tagged_division_union[OF assms(1-2)])
    unfolding interval_split[OF k] interior_cbox
    using k
    apply (auto simp add: box_def elim!: ballE[where x=k])
    done
qed

lemma tagged_division_union_interval_real:
  fixes a :: real
  assumes "p1 tagged_division_of ({a .. b} ∩ {x. x∙k ≤ (c::real)})"
    and "p2 tagged_division_of ({a .. b} ∩ {x. x∙k ≥ c})"
    and k: "k ∈ Basis"
  shows "(p1 ∪ p2) tagged_division_of {a .. b}"
  using assms
  unfolding box_real[symmetric]
  by (rule tagged_division_union_interval)

lemma has_integral_separate_sides:
  fixes f :: "'a::euclidean_space ⇒ 'b::real_normed_vector"
  assumes "(f has_integral i) (cbox a b)"
    and "e > 0"
    and k: "k ∈ Basis"
  obtains d where "gauge d"
    "∀p1 p2. p1 tagged_division_of (cbox a b ∩ {x. x∙k ≤ c}) ∧ d fine p1 ∧
        p2 tagged_division_of (cbox a b ∩ {x. x∙k ≥ c}) ∧ d fine p2 ⟶
        norm ((setsum (λ(x,k). content k *R f x) p1 + setsum (λ(x,k). content k *R f x) p2) - i) < e"
proof -
  guess d using has_integralD[OF assms(1-2)] . note d=this
  { fix p1 p2
    assume "p1 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≤ c}" "d fine p1"
    note p1=tagged_division_ofD[OF this(1)] this
    assume "p2 tagged_division_of (cbox a b) ∩ {x. c ≤ x ∙ k}" "d fine p2"
    note p2=tagged_division_ofD[OF this(1)] this
    note tagged_division_union_interval[OF p1(7) p2(7)] note p12 = tagged_division_ofD[OF this] this
    { fix a b
      assume ab: "(a, b) ∈ p1 ∩ p2"
      have "(a, b) ∈ p1"
        using ab by auto
      with p1 obtain u v where uv: "b = cbox u v" by auto
      have "b ⊆ {x. x∙k = c}"
        using ab p1(3)[of a b] p2(3)[of a b] by fastforce
      moreover
      have "interior {x::'a. x ∙ k = c} = {}"
      proof (rule ccontr)
        assume "¬ ?thesis"
        then obtain x where x: "x ∈ interior {x::'a. x∙k = c}"
          by auto
        then guess e unfolding mem_interior .. note e=this
        have x: "x∙k = c"
          using x interior_subset by fastforce
        have *: "⋀i. i ∈ Basis ⟹ ¦(x - (x + (e / 2) *R k)) ∙ i¦ = (if i = k then e/2 else 0)"
          using e k by (auto simp: inner_simps inner_not_same_Basis)
        have "(∑i∈Basis. ¦(x - (x + (e / 2 ) *R k)) ∙ i¦) =
              (∑i∈Basis. (if i = k then e / 2 else 0))"
          using "*" by (blast intro: setsum.cong)
        also have "… < e"
          apply (subst setsum.delta)
          using e
          apply auto
          done
        finally have "x + (e/2) *R k ∈ ball x e"
          unfolding mem_ball dist_norm by(rule le_less_trans[OF norm_le_l1])
        then have "x + (e/2) *R k ∈ {x. x∙k = c}"
          using e by auto
        then show False
          unfolding mem_Collect_eq using e x k by (auto simp: inner_simps)
      qed
      ultimately have "content b = 0"
        unfolding uv content_eq_0_interior
        using interior_mono by blast
      then have "content b *R f a = 0"
        by auto
    }
    then have "norm ((∑(x, k)∈p1. content k *R f x) + (∑(x, k)∈p2. content k *R f x) - i) =
               norm ((∑(x, k)∈p1 ∪ p2. content k *R f x) - i)"
      by (subst setsum.union_inter_neutral) (auto simp: p1 p2)
    also have "… < e"
      by (rule k d(2) p12 fine_union p1 p2)+
    finally have "norm ((∑(x, k)∈p1. content k *R f x) + (∑(x, k)∈p2. content k *R f x) - i) < e" .
   }
  then show ?thesis
    by (auto intro: that[of d] d elim: )
qed

lemma integrable_split[intro]:
  fixes f :: "'a::euclidean_space ⇒ 'b::{real_normed_vector,complete_space}"
  assumes "f integrable_on cbox a b"
    and k: "k ∈ Basis"
  shows "f integrable_on (cbox a b ∩ {x. x∙k ≤ c})" (is ?t1)
    and "f integrable_on (cbox a b ∩ {x. x∙k ≥ c})" (is ?t2)
proof -
  guess y using assms(1) unfolding integrable_on_def .. note y=this
  def b'  "∑i∈Basis. (if i = k then min (b∙k) c else b∙i)*R i::'a"
  def a'  "∑i∈Basis. (if i = k then max (a∙k) c else a∙i)*R i::'a"
  show ?t1 ?t2
    unfolding interval_split[OF k] integrable_cauchy
    unfolding interval_split[symmetric,OF k]
  proof (rule_tac[!] allI impI)+
    fix e :: real
    assume "e > 0"
    then have "e/2>0"
      by auto
    from has_integral_separate_sides[OF y this k,of c] guess d . note d=this[rule_format]
    let ?P = "λA. ∃d. gauge d ∧ (∀p1 p2. p1 tagged_division_of (cbox a b) ∩ A ∧ d fine p1 ∧
      p2 tagged_division_of (cbox a b) ∩ A ∧ d fine p2 ⟶
      norm ((∑(x, k)∈p1. content k *R f x) - (∑(x, k)∈p2. content k *R f x)) < e)"
    show "?P {x. x ∙ k ≤ c}"
    proof (rule_tac x=d in exI, clarsimp simp add: d)
      fix p1 p2
      assume as: "p1 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≤ c}" "d fine p1"
                 "p2 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≤ c}" "d fine p2"
      show "norm ((∑(x, k)∈p1. content k *R f x) - (∑(x, k)∈p2. content k *R f x)) < e"
      proof (rule fine_division_exists[OF d(1), of a' b] )
        fix p
        assume "p tagged_division_of cbox a' b" "d fine p"
        then show ?thesis
          using as norm_triangle_half_l[OF d(2)[of p1 p] d(2)[of p2 p]]
          unfolding interval_split[OF k] b'_def[symmetric] a'_def[symmetric]
          by (auto simp add: algebra_simps)
      qed
    qed
    show "?P {x. x ∙ k ≥ c}"
    proof (rule_tac x=d in exI, clarsimp simp add: d)
      fix p1 p2
      assume as: "p1 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≥ c}" "d fine p1"
                 "p2 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≥ c}" "d fine p2"
      show "norm ((∑(x, k)∈p1. content k *R f x) - (∑(x, k)∈p2. content k *R f x)) < e"
      proof (rule fine_division_exists[OF d(1), of a b'] )
        fix p
        assume "p tagged_division_of cbox a b'" "d fine p"
        then show ?thesis
          using as norm_triangle_half_l[OF d(2)[of p p1] d(2)[of p p2]]
          unfolding interval_split[OF k] b'_def[symmetric] a'_def[symmetric]
          by (auto simp add: algebra_simps)
      qed
    qed
  qed
qed


subsection ‹Generalized notion of additivity.›

definition "neutral opp = (SOME x. ∀y. opp x y = y ∧ opp y x = y)"

definition operative :: "('a ⇒ 'a ⇒ 'a) ⇒ (('b::euclidean_space) set ⇒ 'a) ⇒ bool"
  where "operative opp f ⟷
    (∀a b. content (cbox a b) = 0 ⟶ f (cbox a b) = neutral opp) ∧
    (∀a b c. ∀k∈Basis. f (cbox a b) = opp (f(cbox a b ∩ {x. x∙k ≤ c})) (f (cbox a b ∩ {x. x∙k ≥ c})))"

lemma operativeD[dest]:
  fixes type :: "'a::euclidean_space"
  assumes "operative opp f"
  shows "⋀a b::'a. content (cbox a b) = 0 ⟹ f (cbox a b) = neutral opp"
    and "⋀a b c k. k ∈ Basis ⟹ f (cbox a b) =
      opp (f (cbox a b ∩ {x. x∙k ≤ c})) (f (cbox a b ∩ {x. x∙k ≥ c}))"
  using assms unfolding operative_def by auto

lemma property_empty_interval: "∀a b. content (cbox a b) = 0 ⟶ P (cbox a b) ⟹ P {}"
  using content_empty unfolding empty_as_interval by auto

lemma operative_empty: "operative opp f ⟹ f {} = neutral opp"
  unfolding operative_def by (rule property_empty_interval) auto


subsection ‹Using additivity of lifted function to encode definedness.›

fun lifted where
  "lifted (opp :: 'a ⇒ 'a ⇒ 'b) (Some x) (Some y) = Some (opp x y)"
| "lifted opp None _ = (None::'b option)"
| "lifted opp _ None = None"

lemma lifted_simp_1[simp]: "lifted opp v None = None"
  by (induct v) auto

definition "monoidal opp ⟷
  (∀x y. opp x y = opp y x) ∧
  (∀x y z. opp x (opp y z) = opp (opp x y) z) ∧
  (∀x. opp (neutral opp) x = x)"

lemma monoidalI:
  assumes "⋀x y. opp x y = opp y x"
    and "⋀x y z. opp x (opp y z) = opp (opp x y) z"
    and "⋀x. opp (neutral opp) x = x"
  shows "monoidal opp"
  unfolding monoidal_def using assms by fastforce

lemma monoidal_ac:
  assumes "monoidal opp"
  shows [simp]: "opp (neutral opp) a = a"
    and [simp]: "opp a (neutral opp) = a"
    and "opp a b = opp b a"
    and "opp (opp a b) c = opp a (opp b c)"
    and "opp a (opp b c) = opp b (opp a c)"
  using assms unfolding monoidal_def by metis+

lemma neutral_lifted [cong]:
  assumes "monoidal opp"
  shows "neutral (lifted opp) = Some (neutral opp)"
proof -
  { fix x
    assume "∀y. lifted opp x y = y ∧ lifted opp y x = y"
    then have "Some (neutral opp) = x"
      apply (induct x)
      apply force
      by (metis assms lifted.simps(1) monoidal_ac(2) option.inject) }
  note [simp] = this
  show ?thesis
    apply (subst neutral_def)
    apply (intro some_equality allI)
    apply (induct_tac y)
    apply (auto simp add:monoidal_ac[OF assms])
    done
qed

lemma monoidal_lifted[intro]:
  assumes "monoidal opp"
  shows "monoidal (lifted opp)"
  unfolding monoidal_def split_option_all neutral_lifted[OF assms]
  using monoidal_ac[OF assms]
  by auto

definition "support opp f s = {x. x∈s ∧ f x ≠ neutral opp}"
definition "fold' opp e s = (if finite s then Finite_Set.fold opp e s else e)"
definition "iterate opp s f = fold' (λx a. opp (f x) a) (neutral opp) (support opp f s)"

lemma support_subset[intro]: "support opp f s ⊆ s"
  unfolding support_def by auto

lemma support_empty[simp]: "support opp f {} = {}"
  using support_subset[of opp f "{}"] by auto

lemma comp_fun_commute_monoidal[intro]:
  assumes "monoidal opp"
  shows "comp_fun_commute opp"
  unfolding comp_fun_commute_def
  using monoidal_ac[OF assms]
  by auto

lemma support_clauses:
  "⋀f g s. support opp f {} = {}"
  "⋀f g s. support opp f (insert x s) =
    (if f(x) = neutral opp then support opp f s else insert x (support opp f s))"
  "⋀f g s. support opp f (s - {x}) = (support opp f s) - {x}"
  "⋀f g s. support opp f (s ∪ t) = (support opp f s) ∪ (support opp f t)"
  "⋀f g s. support opp f (s ∩ t) = (support opp f s) ∩ (support opp f t)"
  "⋀f g s. support opp f (s - t) = (support opp f s) - (support opp f t)"
  "⋀f g s. support opp g (f ` s) = f ` (support opp (g ∘ f) s)"
  unfolding support_def by auto

lemma finite_support[intro]: "finite s ⟹ finite (support opp f s)"
  unfolding support_def by auto

lemma iterate_empty[simp]: "iterate opp {} f = neutral opp"
  unfolding iterate_def fold'_def by auto

lemma iterate_insert[simp]:
  assumes "monoidal opp"
    and "finite s"
  shows "iterate opp (insert x s) f =
         (if x ∈ s then iterate opp s f else opp (f x) (iterate opp s f))"
proof (cases "x ∈ s")
  case True
  then show ?thesis by (auto simp: insert_absorb iterate_def)
next
  case False
  note * = comp_fun_commute.comp_comp_fun_commute [OF comp_fun_commute_monoidal[OF assms(1)]]
  show ?thesis
  proof (cases "f x = neutral opp")
    case True
    then show ?thesis
      using assms ‹x ∉ s›
      by (auto simp: iterate_def support_clauses)
  next
    case False
    with ‹x ∉ s› ‹finite s› support_subset show ?thesis
      apply (simp add: iterate_def fold'_def support_clauses)
      apply (subst comp_fun_commute.fold_insert[OF * finite_support, simplified comp_def])
      apply (force simp add: )+
      done
  qed
qed

lemma iterate_some:
    "⟦monoidal opp; finite s⟧ ⟹ iterate (lifted opp) s (λx. Some(f x)) = Some (iterate opp s f)"
  by (erule finite_induct) (auto simp: monoidal_lifted)


subsection ‹Two key instances of additivity.›

lemma neutral_add[simp]: "neutral op + = (0::'a::comm_monoid_add)"
  unfolding neutral_def
  by (force elim: allE [where x=0])

lemma operative_content[intro]: "operative (op +) content"
  by (force simp add: operative_def content_split[symmetric])

lemma monoidal_monoid[intro]: "monoidal ((op +)::('a::comm_monoid_add) ⇒ 'a ⇒ 'a)"
  unfolding monoidal_def neutral_add
  by (auto simp add: algebra_simps)

lemma operative_integral:
  fixes f :: "'a::euclidean_space ⇒ 'b::banach"
  shows "operative (lifted(op +)) (λi. if f integrable_on i then Some(integral i f) else None)"
  unfolding operative_def neutral_lifted[OF monoidal_monoid] neutral_add
proof safe
  fix a b c
  fix k :: 'a
  assume k: "k ∈ Basis"
  show "(if f integrable_on cbox a b then Some (integral (cbox a b) f) else None) =
        lifted op + (if f integrable_on cbox a b ∩ {x. x ∙ k ≤ c} then Some (integral (cbox a b ∩ {x. x ∙ k ≤ c}) f) else None)
        (if f integrable_on cbox a b ∩ {x. c ≤ x ∙ k} then Some (integral (cbox a b ∩ {x. c ≤ x ∙ k}) f) else None)"
  proof (cases "f integrable_on cbox a b")
    case True
    with k show ?thesis
      apply (simp add: integrable_split)
      apply (rule integral_unique [OF has_integral_split[OF _ _ k]])
      apply (auto intro: integrable_integral)
      done
  next
    case False
    have "¬ (f integrable_on cbox a b ∩ {x. x ∙ k ≤ c}) ∨ ¬ ( f integrable_on cbox a b ∩ {x. c ≤ x ∙ k})"
    proof (rule ccontr)
      assume "¬ ?thesis"
      then have "f integrable_on cbox a b"
        unfolding integrable_on_def
        apply (rule_tac x="integral (cbox a b ∩ {x. x ∙ k ≤ c}) f + integral (cbox a b ∩ {x. x ∙ k ≥ c}) f" in exI)
        apply (rule has_integral_split[OF _ _ k])
        apply (auto intro: integrable_integral)
        done
      then show False
        using False by auto
    qed
    then show ?thesis
      using False by auto
  qed
next
  fix a b :: 'a
  assume "content (cbox a b) = 0"
  then show "(if f integrable_on cbox a b then Some (integral (cbox a b) f) else None) = Some 0"
    using has_integral_null_eq
    by (auto simp: integrable_on_null)
qed


subsection ‹Points of division of a partition.›

definition "division_points (k::('a::euclidean_space) set) d =
   {(j,x). j ∈ Basis ∧ (interval_lowerbound k)∙j < x ∧ x < (interval_upperbound k)∙j ∧
     (∃i∈d. (interval_lowerbound i)∙j = x ∨ (interval_upperbound i)∙j = x)}"

lemma division_points_finite:
  fixes i :: "'a::euclidean_space set"
  assumes "d division_of i"
  shows "finite (division_points i d)"
proof -
  note assm = division_ofD[OF assms]
  let ?M = "λj. {(j,x)|x. (interval_lowerbound i)∙j < x ∧ x < (interval_upperbound i)∙j ∧
    (∃i∈d. (interval_lowerbound i)∙j = x ∨ (interval_upperbound i)∙j = x)}"
  have *: "division_points i d = ⋃(?M ` Basis)"
    unfolding division_points_def by auto
  show ?thesis
    unfolding * using assm by auto
qed

lemma division_points_subset:
  fixes a :: "'a::euclidean_space"
  assumes "d division_of (cbox a b)"
    and "∀i∈Basis. a∙i < b∙i"  "a∙k < c" "c < b∙k"
    and k: "k ∈ Basis"
  shows "division_points (cbox a b ∩ {x. x∙k ≤ c}) {l ∩ {x. x∙k ≤ c} | l . l ∈ d ∧ l ∩ {x. x∙k ≤ c} ≠ {}} ⊆
      division_points (cbox a b) d" (is ?t1)
    and "division_points (cbox a b ∩ {x. x∙k ≥ c}) {l ∩ {x. x∙k ≥ c} | l . l ∈ d ∧ ~(l ∩ {x. x∙k ≥ c} = {})} ⊆
      division_points (cbox a b) d" (is ?t2)
proof -
  note assm = division_ofD[OF assms(1)]
  have *: "∀i∈Basis. a∙i ≤ b∙i"
    "∀i∈Basis. a∙i ≤ (∑i∈Basis. (if i = k then min (b ∙ k) c else  b ∙ i) *R i) ∙ i"
    "∀i∈Basis. (∑i∈Basis. (if i = k then max (a ∙ k) c else a ∙ i) *R i) ∙ i ≤ b∙i"
    "min (b ∙ k) c = c" "max (a ∙ k) c = c"
    using assms using less_imp_le by auto
  show ?t1 (*FIXME a horrible mess*)
    unfolding division_points_def interval_split[OF k, of a b]
    unfolding interval_bounds[OF *(1)] interval_bounds[OF *(2)] interval_bounds[OF *(3)]
    unfolding *
    apply (rule subsetI)
    unfolding mem_Collect_eq split_beta
    apply (erule bexE conjE)+
    apply (simp add: )
    apply (erule exE conjE)+
  proof
    fix i l x
    assume as:
      "a ∙ fst x < snd x" "snd x < (if fst x = k then c else b ∙ fst x)"
      "interval_lowerbound i ∙ fst x = snd x ∨ interval_upperbound i ∙ fst x = snd x"
      "i = l ∩ {x. x ∙ k ≤ c}" "l ∈ d" "l ∩ {x. x ∙ k ≤ c} ≠ {}"
      and fstx: "fst x ∈ Basis"
    from assm(4)[OF this(5)] guess u v apply-by(erule exE)+ note l=this
    have *: "∀i∈Basis. u ∙ i ≤ (∑i∈Basis. (if i = k then min (v ∙ k) c else v ∙ i) *R i) ∙ i"
      using as(6) unfolding l interval_split[OF k] box_ne_empty as .
    have **: "∀i∈Basis. u∙i ≤ v∙i"
      using l using as(6) unfolding box_ne_empty[symmetric] by auto
    show "∃i∈d. interval_lowerbound i ∙ fst x = snd x ∨ interval_upperbound i ∙ fst x = snd x"
      apply (rule bexI[OF _ ‹l ∈ d›])
      using as(1-3,5) fstx
      unfolding l interval_bounds[OF **] interval_bounds[OF *] interval_split[OF k] as
      apply (auto split: if_split_asm)
      done
    show "snd x < b ∙ fst x"
      using as(2) ‹c < b∙k› by (auto split: if_split_asm)
  qed
  show ?t2
    unfolding division_points_def interval_split[OF k, of a b]
    unfolding interval_bounds[OF *(1)] interval_bounds[OF *(2)] interval_bounds[OF *(3)]
    unfolding *
    unfolding subset_eq
    apply rule
    unfolding mem_Collect_eq split_beta
    apply (erule bexE conjE)+
    apply (simp only: mem_Collect_eq inner_setsum_left_Basis simp_thms)
    apply (erule exE conjE)+
  proof
    fix i l x
    assume as:
      "(if fst x = k then c else a ∙ fst x) < snd x" "snd x < b ∙ fst x"
      "interval_lowerbound i ∙ fst x = snd x ∨ interval_upperbound i ∙ fst x = snd x"
      "i = l ∩ {x. c ≤ x ∙ k}" "l ∈ d" "l ∩ {x. c ≤ x ∙ k} ≠ {}"
      and fstx: "fst x ∈ Basis"
    from assm(4)[OF this(5)] guess u v by (elim exE) note l=this
    have *: "∀i∈Basis. (∑i∈Basis. (if i = k then max (u ∙ k) c else u ∙ i) *R i) ∙ i ≤ v ∙ i"
      using as(6) unfolding l interval_split[OF k] box_ne_empty as .
    have **: "∀i∈Basis. u∙i ≤ v∙i"
      using l using as(6) unfolding box_ne_empty[symmetric] by auto
    show "∃i∈d. interval_lowerbound i ∙ fst x = snd x ∨ interval_upperbound i ∙ fst x = snd x"
      apply (rule bexI[OF _ ‹l ∈ d›])
      using as(1-3,5) fstx
      unfolding l interval_bounds[OF **] interval_bounds[OF *] interval_split[OF k] as
      apply (auto split: if_split_asm)
      done
    show "a ∙ fst x < snd x"
      using as(1) ‹a∙k < c› by (auto split: if_split_asm)
   qed
qed

lemma division_points_psubset:
  fixes a :: "'a::euclidean_space"
  assumes "d division_of (cbox a b)"
      and "∀i∈Basis. a∙i < b∙i"  "a∙k < c" "c < b∙k"
      and "l ∈ d"
      and "interval_lowerbound l∙k = c ∨ interval_upperbound l∙k = c"
      and k: "k ∈ Basis"
  shows "division_points (cbox a b ∩ {x. x∙k ≤ c}) {l ∩ {x. x∙k ≤ c} | l. l∈d ∧ l ∩ {x. x∙k ≤ c} ≠ {}} ⊂
         division_points (cbox a b) d" (is "?D1 ⊂ ?D")
    and "division_points (cbox a b ∩ {x. x∙k ≥ c}) {l ∩ {x. x∙k ≥ c} | l. l∈d ∧ l ∩ {x. x∙k ≥ c} ≠ {}} ⊂
         division_points (cbox a b) d" (is "?D2 ⊂ ?D")
proof -
  have ab: "∀i∈Basis. a∙i ≤ b∙i"
    using assms(2) by (auto intro!:less_imp_le)
  guess u v using division_ofD(4)[OF assms(1,5)] by (elim exE) note l=this
  have uv: "∀i∈Basis. u∙i ≤ v∙i" "∀i∈Basis. a∙i ≤ u∙i ∧ v∙i ≤ b∙i"
    using division_ofD(2,2,3)[OF assms(1,5)] unfolding l box_ne_empty
    using subset_box(1)
    apply auto
    apply blast+
    done
  have *: "interval_upperbound (cbox a b ∩ {x. x ∙ k ≤ interval_upperbound l ∙ k}) ∙ k = interval_upperbound l ∙ k"
          "interval_upperbound (cbox a b ∩ {x. x ∙ k ≤ interval_lowerbound l ∙ k}) ∙ k = interval_lowerbound l ∙ k"
    unfolding l interval_split[OF k] interval_bounds[OF uv(1)]
    using uv[rule_format, of k] ab k
    by auto
  have "∃x. x ∈ ?D - ?D1"
    using assms(3-)
    unfolding division_points_def interval_bounds[OF ab]
    apply -
    apply (erule disjE)
    apply (rule_tac x="(k,(interval_lowerbound l)∙k)" in exI, force simp add: *)
    apply (rule_tac x="(k,(interval_upperbound l)∙k)" in exI, force simp add: *)
    done
  moreover have "?D1 ⊆ ?D"
    by (auto simp add: assms division_points_subset)
  ultimately show "?D1 ⊂ ?D"
    by blast
  have *: "interval_lowerbound (cbox a b ∩ {x. x ∙ k ≥ interval_lowerbound l ∙ k}) ∙ k = interval_lowerbound l ∙ k"
    "interval_lowerbound (cbox a b ∩ {x. x ∙ k ≥ interval_upperbound l ∙ k}) ∙ k = interval_upperbound l ∙ k"
    unfolding l interval_split[OF k] interval_bounds[OF uv(1)]
    using uv[rule_format, of k] ab k
    by auto
  have "∃x. x ∈ ?D - ?D2"
    using assms(3-)
    unfolding division_points_def interval_bounds[OF ab]
    apply -
    apply (erule disjE)
    apply (rule_tac x="(k,(interval_lowerbound l)∙k)" in exI, force simp add: *)
    apply (rule_tac x="(k,(interval_upperbound l)∙k)" in exI, force simp add: *)
    done
  moreover have "?D2 ⊆ ?D"
    by (auto simp add: assms division_points_subset)
  ultimately show "?D2 ⊂ ?D"
    by blast
qed


subsection ‹Preservation by divisions and tagged divisions.›

lemma support_support[simp]:"support opp f (support opp f s) = support opp f s"
  unfolding support_def by auto

lemma iterate_support[simp]: "iterate opp (support opp f s) f = iterate opp s f"
  unfolding iterate_def support_support by auto

lemma iterate_expand_cases:
  "iterate opp s f = (if finite(support opp f s) then iterate opp (support opp f s) f else neutral opp)"
    by (simp add: iterate_def fold'_def)

lemma iterate_image:
  assumes "monoidal opp"
    and "inj_on f s"
  shows "iterate opp (f ` s) g = iterate opp s (g ∘ f)"
proof -
  have *: "iterate opp (f ` s) g = iterate opp s (g ∘ f)"
    if "finite s" "∀x∈s. ∀y∈s. f x = f y ⟶ x = y" for s
    using that
  proof (induct s)
    case empty
    then show ?case by simp
  next
    case insert
    with assms(1) show ?case by auto
  qed
  show ?thesis
    apply (cases "finite (support opp g (f ` s))")
    prefer 2
      apply (metis finite_imageI iterate_expand_cases support_clauses(7))
    apply (subst (1) iterate_support[symmetric], subst (2) iterate_support[symmetric])
    unfolding support_clauses
    apply (rule *)
    apply (meson assms(2) finite_imageD subset_inj_on support_subset)
    apply (meson assms(2) inj_on_contraD rev_subsetD support_subset)
    done
qed


(* This lemma about iterations comes up in a few places. *)
lemma iterate_nonzero_image_lemma:
  assumes "monoidal opp"
    and "finite s" "g(a) = neutral opp"
    and "∀x∈s. ∀y∈s. f x = f y ∧ x ≠ y ⟶ g(f x) = neutral opp"
  shows "iterate opp {f x | x. x ∈ s ∧ f x ≠ a} g = iterate opp s (g ∘ f)"
proof -
  have *: "{f x |x. x ∈ s ∧ f x ≠ a} = f ` {x. x ∈ s ∧ f x ≠ a}"
    by auto
  have **: "support opp (g ∘ f) {x ∈ s. f x ≠ a} = support opp (g ∘ f) s"
    unfolding support_def using assms(3) by auto
  have inj: "inj_on f (support opp (g ∘ f) {x ∈ s. f x ≠ a})"
    apply (simp add: inj_on_def)
    apply (metis (mono_tags, lifting) assms(4) comp_def mem_Collect_eq support_def)
    done
  show ?thesis
    apply (subst iterate_support[symmetric])
    apply (simp add: * support_clauses iterate_image[OF assms(1) inj])
    apply (simp add: iterate_def **)
    done
qed

lemma iterate_eq_neutral:
  assumes "monoidal opp"
      and "⋀x. x ∈ s ⟹ f x = neutral opp"
    shows "iterate opp s f = neutral opp"
proof -
  have [simp]: "support opp f s = {}"
    unfolding support_def using assms(2) by auto
  show ?thesis
    by (subst iterate_support[symmetric]) simp
qed

lemma iterate_op:
   "⟦monoidal opp; finite s⟧
    ⟹ iterate opp s (λx. opp (f x) (g x)) = opp (iterate opp s f) (iterate opp s g)"
by (erule finite_induct) (auto simp: monoidal_ac(4) monoidal_ac(5))

lemma iterate_eq:
  assumes "monoidal opp"
    and "⋀x. x ∈ s ⟹ f x = g x"
  shows "iterate opp s f = iterate opp s g"
proof -
  have *: "support opp g s = support opp f s"
    unfolding support_def using assms(2) by auto
  show ?thesis
  proof (cases "finite (support opp f s)")
    case False
    then show ?thesis
      by (simp add: "*" iterate_expand_cases)
  next
    case True
    def su  "support opp f s"
    have fsu: "finite su"
      using True by (simp add: su_def)
    moreover
    { assume "finite su" "su ⊆ s"
      then have "iterate opp su f = iterate opp su g"
        by (induct su) (auto simp: assms)
    }
    ultimately have "iterate opp (support opp f s) f = iterate opp (support opp g s) g"
      by (simp add: "*" su_def support_subset)
    then show ?thesis
      by simp
  qed
qed

lemma nonempty_witness:
  assumes "s ≠ {}"
  obtains x where "x ∈ s"
  using assms by auto

lemma operative_division:
  fixes f :: "'a::euclidean_space set ⇒ 'b"
  assumes "monoidal opp"
      and "operative opp f"
      and "d division_of (cbox a b)"
    shows "iterate opp d f = f (cbox a b)"
proof -
  def C  "card (division_points (cbox a b) d)"
  then show ?thesis
    using assms
  proof (induct C arbitrary: a b d rule: full_nat_induct)
    case (1 a b d)
    show ?case
    proof (cases "content (cbox a b) = 0")
      case True
      show "iterate opp d f = f (cbox a b)"
        unfolding operativeD(1)[OF assms(2) True]
      proof (rule iterate_eq_neutral[OF ‹monoidal opp›])
        fix x
        assume x: "x ∈ d"
        then show "f x = neutral opp"
          by (metis division_ofD(4) 1(4) division_of_content_0[OF True] operativeD(1)[OF assms(2)] x)
      qed
    next
      case False
      note ab = this[unfolded content_lt_nz[symmetric] content_pos_lt_eq]
      then have ab': "∀i∈Basis. a∙i ≤ b∙i"
        by (auto intro!: less_imp_le)
        show "iterate opp d f = f (cbox a b)"
      proof (cases "division_points (cbox a b) d = {}")
        case True
        { fix u v and j :: 'a
          assume j: "j ∈ Basis" and as: "cbox u v ∈ d"
          then have "cbox u v ≠ {}"
            using "1.prems"(3) by blast
          then have uv: "∀i∈Basis. u∙i ≤ v∙i" "u∙j ≤ v∙j"
            using j unfolding box_ne_empty by auto
          have *: "⋀p r Q. ¬ j∈Basis ∨ p ∨ r ∨ (∀x∈d. Q x) ⟹ p ∨ r ∨ Q (cbox u v)"
            using as j by auto
          have "(j, u∙j) ∉ division_points (cbox a b) d"
               "(j, v∙j) ∉ division_points (cbox a b) d" using True by auto
          note this[unfolded de_Morgan_conj division_points_def mem_Collect_eq split_conv interval_bounds[OF ab'] bex_simps]
          note *[OF this(1)] *[OF this(2)] note this[unfolded interval_bounds[OF uv(1)]]
          moreover
          have "a∙j ≤ u∙j" "v∙j ≤ b∙j"
            using division_ofD(2,2,3)[OF ‹d division_of cbox a b› as]
            apply (metis j subset_box(1) uv(1))
            by (metis ‹cbox u v ⊆ cbox a b› j subset_box(1) uv(1))
          ultimately have "u∙j = a∙j ∧ v∙j = a∙j ∨ u∙j = b∙j ∧ v∙j = b∙j ∨ u∙j = a∙j ∧ v∙j = b∙j"
            unfolding not_less de_Morgan_disj using ab[rule_format,of j] uv(2) j by force }
        then have d': "∀i∈d. ∃u v. i = cbox u v ∧
          (∀j∈Basis. u∙j = a∙j ∧ v∙j = a∙j ∨ u∙j = b∙j ∧ v∙j = b∙j ∨ u∙j = a∙j ∧ v∙j = b∙j)"
          unfolding forall_in_division[OF 1(4)]
          by blast
        have "(1/2) *R (a+b) ∈ cbox a b"
          unfolding mem_box using ab by(auto intro!: less_imp_le simp: inner_simps)
        note this[unfolded division_ofD(6)[OF ‹d division_of cbox a b›,symmetric] Union_iff]
        then guess i .. note i=this
        guess u v using d'[rule_format,OF i(1)] by (elim exE conjE) note uv=this
        have "cbox a b ∈ d"
        proof -
          have "u = a" "v = b"
            unfolding euclidean_eq_iff[where 'a='a]
          proof safe
            fix j :: 'a
            assume j: "j ∈ Basis"
            note i(2)[unfolded uv mem_box,rule_format,of j]
            then show "u ∙ j = a ∙ j" and "v ∙ j = b ∙ j"
              using uv(2)[rule_format,of j] j by (auto simp: inner_simps)
          qed
          then have "i = cbox a b" using uv by auto
          then show ?thesis using i by auto
        qed
        then have deq: "d = insert (cbox a b) (d - {cbox a b})"
          by auto
        have "iterate opp (d - {cbox a b}) f = neutral opp"
        proof (rule iterate_eq_neutral[OF 1(2)])
          fix x
          assume x: "x ∈ d - {cbox a b}"
          then have "x∈d"
            by auto note d'[rule_format,OF this]
          then guess u v by (elim exE conjE) note uv=this
          have "u ≠ a ∨ v ≠ b"
            using x[unfolded uv] by auto
          then obtain j where "u∙j ≠ a∙j ∨ v∙j ≠ b∙j" and j: "j ∈ Basis"
            unfolding euclidean_eq_iff[where 'a='a] by auto
          then have "u∙j = v∙j"
            using uv(2)[rule_format,OF j] by auto
          then have "content (cbox u v) = 0"
            unfolding content_eq_0 using j
            by force
          then show "f x = neutral opp"
            unfolding uv(1) by (rule operativeD(1)[OF 1(3)])
        qed
        then show "iterate opp d f = f (cbox a b)"
          apply (subst deq)
          apply (subst iterate_insert[OF 1(2)])
          using 1
          apply auto
          done
      next
        case False
        then have "∃x. x ∈ division_points (cbox a b) d"
          by auto
        then guess k c
          unfolding split_paired_Ex division_points_def mem_Collect_eq split_conv
          apply (elim exE conjE)
          done
        note this(2-4,1) note kc=this[unfolded interval_bounds[OF ab']]
        from this(3) guess j .. note j=this
        def d1  "{l ∩ {x. x∙k ≤ c} | l. l ∈ d ∧ l ∩ {x. x∙k ≤ c} ≠ {}}"
        def d2  "{l ∩ {x. x∙k ≥ c} | l. l ∈ d ∧ l ∩ {x. x∙k ≥ c} ≠ {}}"
        def cb  "(∑i∈Basis. (if i = k then c else b∙i) *R i)::'a"
        def ca  "(∑i∈Basis. (if i = k then c else a∙i) *R i)::'a"
        note division_points_psubset[OF ‹d division_of cbox a b› ab kc(1-2) j]
        note psubset_card_mono[OF _ this(1)] psubset_card_mono[OF _ this(2)]
        then have *: "(iterate opp d1 f) = f (cbox a b ∩ {x. x∙k ≤ c})"
          "(iterate opp d2 f) = f (cbox a b ∩ {x. x∙k ≥ c})"
          unfolding interval_split[OF kc(4)]
          apply (rule_tac[!] "1.hyps"[rule_format])
          using division_split[OF ‹d division_of cbox a b›, where k=k and c=c]
          apply (simp_all add: interval_split 1 kc d1_def d2_def division_points_finite[OF ‹d division_of cbox a b›])
          done
        { fix l y
          assume as: "l ∈ d" "y ∈ d" "l ∩ {x. x ∙ k ≤ c} = y ∩ {x. x ∙ k ≤ c}" "l ≠ y"
          from division_ofD(4)[OF ‹d division_of cbox a b› this(1)] guess u v by (elim exE) note leq=this
          have "f (l ∩ {x. x ∙ k ≤ c}) = neutral opp"
            unfolding leq interval_split[OF kc(4)]
            apply (rule operativeD(1) 1)+
            unfolding interval_split[symmetric,OF kc(4)]
            using division_split_left_inj 1 as kc leq by blast
        } note fxk_le = this
        { fix l y
          assume as: "l ∈ d" "y ∈ d" "l ∩ {x. c ≤ x ∙ k} = y ∩ {x. c ≤ x ∙ k}" "l ≠ y"
          from division_ofD(4)[OF ‹d division_of cbox a b› this(1)] guess u v by (elim exE) note leq=this
          have "f (l ∩ {x. x ∙ k ≥ c}) = neutral opp"
            unfolding leq interval_split[OF kc(4)]
            apply (rule operativeD(1) 1)+
            unfolding interval_split[symmetric,OF kc(4)]
            using division_split_right_inj 1 leq as kc by blast
        } note fxk_ge = this
        have "f (cbox a b) = opp (iterate opp d1 f) (iterate opp d2 f)" (is "_ = ?prev")
          unfolding *
          using assms(2) kc(4) by blast
        also have "iterate opp d1 f = iterate opp d (λl. f(l ∩ {x. x∙k ≤ c}))"
          unfolding d1_def empty_as_interval
          apply (rule iterate_nonzero_image_lemma[unfolded o_def])
          apply (rule 1 division_of_finite operativeD[OF 1(3)])+
          apply (force simp add: empty_as_interval[symmetric] fxk_le)+
          done
        also have "iterate opp d2 f = iterate opp d (λl. f(l ∩ {x. x∙k ≥ c}))"
          unfolding d2_def empty_as_interval
          apply (rule iterate_nonzero_image_lemma[unfolded o_def])
          apply (rule 1 division_of_finite operativeD[OF 1(3)])+
          apply (force simp add: empty_as_interval[symmetric] fxk_ge)+
          done
        also have *: "∀x∈d. f x = opp (f (x ∩ {x. x ∙ k ≤ c})) (f (x ∩ {x. c ≤ x ∙ k}))"
          unfolding forall_in_division[OF ‹d division_of cbox a b›]
          using assms(2) kc(4) by blast
        have "opp (iterate opp d (λl. f (l ∩ {x. x ∙ k ≤ c}))) (iterate opp d (λl. f (l ∩ {x. c ≤ x ∙ k}))) =
          iterate opp d f"
          apply (subst(3) iterate_eq[OF _ *[rule_format]])
          using 1
          apply (auto simp: iterate_op[symmetric])
          done
        finally show ?thesis by auto
      qed
    qed
  qed
qed

lemma iterate_image_nonzero:
  assumes "monoidal opp"
      and "finite s"
      and "⋀x y. ∀x∈s. ∀y∈s. x ≠ y ∧ f x = f y ⟶ g (f x) = neutral opp"
    shows "iterate opp (f ` s) g = iterate opp s (g ∘ f)"
using assms
by (induct rule: finite_subset_induct[OF assms(2) subset_refl]) auto

lemma operative_tagged_division:
  assumes "monoidal opp"
      and "operative opp f"
      and "d tagged_division_of (cbox a b)"
    shows "iterate opp d (λ(x,l). f l) = f (cbox a b)"
proof -
  have *: "(λ(x,l). f l) = f ∘ snd"
    unfolding o_def by rule auto note tagged = tagged_division_ofD[OF assms(3)]
  { fix a b a'
    assume as: "(a, b) ∈ d" "(a', b) ∈ d" "(a, b) ≠ (a', b)"
    have "f b = neutral opp"
      using tagged(4)[OF as(1)]
      apply clarify
      apply (rule operativeD(1)[OF assms(2)])
      by (metis content_eq_0_interior inf.idem tagged_division_ofD(5)[OF assms(3) as(1-3)])
  }
  then have "iterate opp d (λ(x,l). f l) = iterate opp (snd ` d) f"
    unfolding *
    by (force intro!: assms iterate_image_nonzero[symmetric, OF _ tagged_division_of_finite])
  also have "… = f (cbox a b)"
    using operative_division[OF assms(1-2) division_of_tagged_division[OF assms(3)]] .
  finally show ?thesis .
qed


subsection ‹Additivity of content.›

lemma setsum_iterate:
  assumes "finite s"
  shows "setsum f s = iterate op + s f"
proof -
  have "setsum f s = setsum f (support op + f s)"
    using assms
    by (auto simp: support_def intro: setsum.mono_neutral_right)
  then show ?thesis unfolding iterate_def fold'_def setsum.eq_fold
    by (simp add: comp_def)
qed

lemma additive_content_division:
    "d division_of (cbox a b) ⟹ setsum content d = content (cbox a b)"
  by (metis division_ofD(1) monoidal_monoid operative_content operative_division setsum_iterate)

lemma additive_content_tagged_division:
    "d tagged_division_of (cbox a b) ⟹ setsum (λ(x,l). content l) d = content (cbox a b)"
  unfolding operative_tagged_division[OF monoidal_monoid operative_content assms,symmetric]
  using setsum_iterate by blast


subsection ‹Finally, the integral of a constant›

lemma has_integral_const [intro]:
  fixes a b :: "'a::euclidean_space"
  shows "((λx. c) has_integral (content (cbox a b) *R c)) (cbox a b)"
  apply (auto intro!: exI [where x="λx. ball x 1"] simp: split_def has_integral)
  apply (subst scaleR_left.setsum[symmetric, unfolded o_def])
  apply (subst additive_content_tagged_division[unfolded split_def])
  apply auto
  done

lemma has_integral_const_real [intro]:
  fixes a b :: real
  shows "((λx. c) has_integral (content {a .. b} *R c)) {a .. b}"
  by (metis box_real(2) has_integral_const)

lemma integral_const [simp]:
  fixes a b :: "'a::euclidean_space"
  shows "integral (cbox a b) (λx. c) = content (cbox a b) *R c"
  by (rule integral_unique) (rule has_integral_const)

lemma integral_const_real [simp]:
  fixes a b :: real
  shows "integral {a .. b} (λx. c) = content {a .. b} *R c"
  by (metis box_real(2) integral_const)


subsection ‹Bounds on the norm of Riemann sums and the integral itself.›

lemma dsum_bound:
  assumes "p division_of (cbox a b)"
    and "norm c ≤ e"
  shows "norm (setsum (λl. content l *R c) p) ≤ e * content(cbox a b)"
proof -
  have sumeq: "(∑i∈p. ¦content i¦) = setsum content p"
    apply (rule setsum.cong)
    using assms
    apply simp
    apply (metis abs_of_nonneg assms(1) content_pos_le division_ofD(4))
    done
  have e: "0 ≤ e"
    using assms(2) norm_ge_zero order_trans by blast
  have "norm (setsum (λl. content l *R c) p) ≤ (∑i∈p. norm (content i *R c))"
    using norm_setsum by blast
  also have "...  ≤ e * (∑i∈p. ¦content i¦)"
    apply (simp add: setsum_right_distrib[symmetric] mult.commute)
    using assms(2) mult_right_mono by blast
  also have "... ≤ e * content (cbox a b)"
    apply (rule mult_left_mono [OF _ e])
    apply (simp add: sumeq)
    using additive_content_division assms(1) eq_iff apply blast
    done
  finally show ?thesis .
qed

lemma rsum_bound:
  assumes p: "p tagged_division_of (cbox a b)"
      and "∀x∈cbox a b. norm (f x) ≤ e"
    shows "norm (setsum (λ(x,k). content k *R f x) p) ≤ e * content (cbox a b)"
proof (cases "cbox a b = {}")
  case True show ?thesis
    using p unfolding True tagged_division_of_trivial by auto
next
  case False
  then have e: "e ≥ 0"
    by (metis assms(2) norm_ge_zero order_trans nonempty_witness)
  have setsum_le: "setsum (content ∘ snd) p ≤ content (cbox a b)"
    unfolding additive_content_tagged_division[OF p, symmetric] split_def
    by (auto intro: eq_refl)
  have con: "⋀xk. xk ∈ p ⟹ 0 ≤ content (snd xk)"
    using tagged_division_ofD(4) [OF p] content_pos_le
    by force
  have norm: "⋀xk. xk ∈ p ⟹ norm (f (fst xk)) ≤ e"
    unfolding fst_conv using tagged_division_ofD(2,3)[OF p] assms
    by (metis prod.collapse subset_eq)
  have "norm (setsum (λ(x,k). content k *R f x) p) ≤ (∑i∈p. norm (case i of (x, k) ⇒ content k *R f x))"
    by (rule norm_setsum)
  also have "...  ≤ e * content (cbox a b)"
    unfolding split_def norm_scaleR
    apply (rule order_trans[OF setsum_mono])
    apply (rule mult_left_mono[OF _ abs_ge_zero, of _ e])
    apply (metis norm)
    unfolding setsum_left_distrib[symmetric]
    using con setsum_le
    apply (auto simp: mult.commute intro: mult_left_mono [OF _ e])
    done
  finally show ?thesis .
qed

lemma rsum_diff_bound:
  assumes "p tagged_division_of (cbox a b)"
    and "∀x∈cbox a b. norm (f x - g x) ≤ e"
  shows "norm (setsum (λ(x,k). content k *R f x) p - setsum (λ(x,k). content k *R g x) p) ≤
         e * content (cbox a b)"
  apply (rule order_trans[OF _ rsum_bound[OF assms]])
  apply (simp add: split_def scaleR_diff_right setsum_subtractf eq_refl)
  done

lemma has_integral_bound:
  fixes f :: "'a::euclidean_space ⇒ 'b::real_normed_vector"
  assumes "0 ≤ B"
      and "(f has_integral i) (cbox a b)"
      and "∀x∈cbox a b. norm (f x) ≤ B"
    shows "norm i ≤ B * content (cbox a b)"
proof (rule ccontr)
  assume "¬ ?thesis"
  then have *: "norm i - B * content (cbox a b) > 0"
    by auto
  from assms(2)[unfolded has_integral,rule_format,OF *]
  guess d by (elim exE conjE) note d=this[rule_format]
  from fine_division_exists[OF this(1), of a b] guess p . note p=this
  have *: "⋀s B. norm s ≤ B ⟹ ¬ norm (s - i) < norm i - B"
    unfolding not_less
    by (metis norm_triangle_sub[of i] add.commute le_less_trans less_diff_eq linorder_not_le norm_minus_commute)
  show False
    using d(2)[OF conjI[OF p]] *[OF rsum_bound[OF p(1) assms(3)]] by auto
qed

corollary has_integral_bound_real:
  fixes f :: "real ⇒ 'b::real_normed_vector"
  assumes "0 ≤ B"
      and "(f has_integral i) {a .. b}"
      and "∀x∈{a .. b}. norm (f x) ≤ B"
    shows "norm i ≤ B * content {a .. b}"
  by (metis assms box_real(2) has_integral_bound)

corollary integrable_bound:
  fixes f :: "'a::euclidean_space ⇒ 'b::real_normed_vector"
  assumes "0 ≤ B"
      and "f integrable_on (cbox a b)"
      and "⋀x. x∈cbox a b ⟹ norm (f x) ≤ B"
    shows "norm (integral (cbox a b) f) ≤ B * content (cbox a b)"
by (metis integrable_integral has_integral_bound assms)


subsection ‹Similar theorems about relationship among components.›

lemma rsum_component_le:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "p tagged_division_of (cbox a b)"
      and "∀x∈cbox a b. (f x)∙i ≤ (g x)∙i"
    shows "(setsum (λ(x,k). content k *R f x) p)∙i ≤ (setsum (λ(x,k). content k *R g x) p)∙i"
unfolding inner_setsum_left
proof (rule setsum_mono, clarify)
  fix a b
  assume ab: "(a, b) ∈ p"
  note tagged = tagged_division_ofD(2-4)[OF assms(1) ab]
  from this(3) guess u v by (elim exE) note b=this
  show "(content b *R f a) ∙ i ≤ (content b *R g a) ∙ i"
    unfolding b inner_simps real_scaleR_def
    apply (rule mult_left_mono)
    using assms(2) tagged
    by (auto simp add: content_pos_le)
qed

lemma has_integral_component_le:
  fixes f g :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes k: "k ∈ Basis"
  assumes "(f has_integral i) s" "(g has_integral j) s"
    and "∀x∈s. (f x)∙k ≤ (g x)∙k"
  shows "i∙k ≤ j∙k"
proof -
  have lem: "i∙k ≤ j∙k"
    if f_i: "(f has_integral i) (cbox a b)"
    and g_j: "(g has_integral j) (cbox a b)"
    and le: "∀x∈cbox a b. (f x)∙k ≤ (g x)∙k"
    for a b i and j :: 'b and f g :: "'a ⇒ 'b"
  proof (rule ccontr)
    assume "¬ ?thesis"
    then have *: "0 < (i∙k - j∙k) / 3"
      by auto
    guess d1 using f_i[unfolded has_integral,rule_format,OF *] by (elim exE conjE) note d1=this[rule_format]
    guess d2 using g_j[unfolded has_integral,rule_format,OF *] by (elim exE conjE) note d2=this[rule_format]
    obtain p where p: "p tagged_division_of cbox a b" "d1 fine p" "d2 fine p"
       using fine_division_exists[OF gauge_inter[OF d1(1) d2(1)], of a b] unfolding fine_inter
       by metis
    note le_less_trans[OF Basis_le_norm[OF k]]
    then have "¦((∑(x, k)∈p. content k *R f x) - i) ∙ k¦ < (i ∙ k - j ∙ k) / 3"
              "¦((∑(x, k)∈p. content k *R g x) - j) ∙ k¦ < (i ∙ k - j ∙ k) / 3"
      using  k norm_bound_Basis_lt d1 d2 p
      by blast+
    then show False
      unfolding inner_simps
      using rsum_component_le[OF p(1) le]
      by (simp add: abs_real_def split: if_split_asm)
  qed
  show ?thesis
  proof (cases "∃a b. s = cbox a b")
    case True
    with lem assms show ?thesis
      by auto
  next
    case False
    show ?thesis
    proof (rule ccontr)
      assume "¬ i∙k ≤ j∙k"
      then have ij: "(i∙k - j∙k) / 3 > 0"
        by auto
      note has_integral_altD[OF _ False this]
      from this[OF assms(2)] this[OF assms(3)] guess B1 B2 . note B=this[rule_format]
      have "bounded (ball 0 B1 ∪ ball (0::'a) B2)"
        unfolding bounded_Un by(rule conjI bounded_ball)+
      from bounded_subset_cbox[OF this] guess a b by (elim exE)
      note ab = conjunctD2[OF this[unfolded Un_subset_iff]]
      guess w1 using B(2)[OF ab(1)] .. note w1=conjunctD2[OF this]
      guess w2 using B(4)[OF ab(2)] .. note w2=conjunctD2[OF this]
      have *: "⋀w1 w2 j i::real .¦w1 - i¦ < (i - j) / 3 ⟹ ¦w2 - j¦ < (i - j) / 3 ⟹ w1 ≤ w2 ⟹ False"
        by (simp add: abs_real_def split: if_split_asm)
      note le_less_trans[OF Basis_le_norm[OF k]]
      note this[OF w1(2)] this[OF w2(2)]
      moreover
      have "w1∙k ≤ w2∙k"
        by (rule lem[OF w1(1) w2(1)]) (simp add: assms(4))
      ultimately show False
        unfolding inner_simps by(rule *)
    qed
  qed
qed

lemma integral_component_le:
  fixes g f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "k ∈ Basis"
    and "f integrable_on s" "g integrable_on s"
    and "∀x∈s. (f x)∙k ≤ (g x)∙k"
  shows "(integral s f)∙k ≤ (integral s g)∙k"
  apply (rule has_integral_component_le)
  using integrable_integral assms
  apply auto
  done

lemma has_integral_component_nonneg:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "k ∈ Basis"
    and "(f has_integral i) s"
    and "∀x∈s. 0 ≤ (f x)∙k"
  shows "0 ≤ i∙k"
  using has_integral_component_le[OF assms(1) has_integral_0 assms(2)]
  using assms(3-)
  by auto

lemma integral_component_nonneg:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "k ∈ Basis"
    and  "∀x∈s. 0 ≤ (f x)∙k"
  shows "0 ≤ (integral s f)∙k"
proof (cases "f integrable_on s")
  case True show ?thesis
    apply (rule has_integral_component_nonneg)
    using assms True
    apply auto
    done
next
  case False then show ?thesis by (simp add: not_integrable_integral)
qed

lemma has_integral_component_neg:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "k ∈ Basis"
    and "(f has_integral i) s"
    and "∀x∈s. (f x)∙k ≤ 0"
  shows "i∙k ≤ 0"
  using has_integral_component_le[OF assms(1,2) has_integral_0] assms(2-)
  by auto

lemma has_integral_component_lbound:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "(f has_integral i) (cbox a b)"
    and "∀x∈cbox a b. B ≤ f(x)∙k"
    and "k ∈ Basis"
  shows "B * content (cbox a b) ≤ i∙k"
  using has_integral_component_le[OF assms(3) has_integral_const assms(1),of "(∑i∈Basis. B *R i)::'b"] assms(2-)
  by (auto simp add: field_simps)

lemma has_integral_component_ubound:
  fixes f::"'a::euclidean_space => 'b::euclidean_space"
  assumes "(f has_integral i) (cbox a b)"
    and "∀x∈cbox a b. f x∙k ≤ B"
    and "k ∈ Basis"
  shows "i∙k ≤ B * content (cbox a b)"
  using has_integral_component_le[OF assms(3,1) has_integral_const, of "∑i∈Basis. B *R i"] assms(2-)
  by (auto simp add: field_simps)

lemma integral_component_lbound:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "f integrable_on cbox a b"
    and "∀x∈cbox a b. B ≤ f(x)∙k"
    and "k ∈ Basis"
  shows "B * content (cbox a b) ≤ (integral(cbox a b) f)∙k"
  apply (rule has_integral_component_lbound)
  using assms
  unfolding has_integral_integral
  apply auto
  done

lemma integral_component_lbound_real:
  assumes "f integrable_on {a ::real .. b}"
    and "∀x∈{a .. b}. B ≤ f(x)∙k"
    and "k ∈ Basis"
  shows "B * content {a .. b} ≤ (integral {a .. b} f)∙k"
  using assms
  by (metis box_real(2) integral_component_lbound)

lemma integral_component_ubound:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "f integrable_on cbox a b"
    and "∀x∈cbox a b. f x∙k ≤ B"
    and "k ∈ Basis"
  shows "(integral (cbox a b) f)∙k ≤ B * content (cbox a b)"
  apply (rule has_integral_component_ubound)
  using assms
  unfolding has_integral_integral
  apply auto
  done

lemma integral_component_ubound_real:
  fixes f :: "real ⇒ 'a::euclidean_space"
  assumes "f integrable_on {a .. b}"
    and "∀x∈{a .. b}. f x∙k ≤ B"
    and "k ∈ Basis"
  shows "(integral {a .. b} f)∙k ≤ B * content {a .. b}"
  using assms
  by (metis box_real(2) integral_component_ubound)

subsection ‹Uniform limit of integrable functions is integrable.›

lemma real_arch_invD:
  "0 < (e::real) ⟹ (∃n::nat. n ≠ 0 ∧ 0 < inverse (real n) ∧ inverse (real n) < e)"
  by (subst(asm) real_arch_inverse)

lemma integrable_uniform_limit:
  fixes f :: "'a::euclidean_space ⇒ 'b::banach"
  assumes "∀e>0. ∃g. (∀x∈cbox a b. norm (f x - g x) ≤ e) ∧ g integrable_on cbox a b"
  shows "f integrable_on cbox a b"
proof (cases "content (cbox a b) > 0")
  case False then show ?thesis
      using has_integral_null
      by (simp add: content_lt_nz integrable_on_def)
next
  case True
  have *: "⋀P. ∀e>(0::real). P e ⟹ ∀n::nat. P (inverse (real n + 1))"
    by auto
  from choice[OF *[OF assms]] guess g .. note g=conjunctD2[OF this[rule_format],rule_format]
  from choice[OF allI[OF g(2)[unfolded integrable_on_def], of "λx. x"]]
  obtain i where i: "⋀x. (g x has_integral i x) (cbox a b)"
      by auto
  have "Cauchy i"
    unfolding Cauchy_def
  proof clarify
    fix e :: real
    assume "e>0"
    then have "e / 4 / content (cbox a b) > 0"
      using True by (auto simp add: field_simps)
    then obtain M :: nat
         where M: "M ≠ 0" "0 < inverse (real_of_nat M)" "inverse (of_nat M) < e / 4 / content (cbox a b)"
      by (subst (asm) real_arch_inverse) auto
    show "∃M. ∀m≥M. ∀n≥M. dist (i m) (i n) < e"
    proof (rule exI [where x=M], clarify)
      fix m n
      assume m: "M ≤ m" and n: "M ≤ n"
      have "e/4>0" using ‹e>0› by auto
      note * = i[unfolded has_integral,rule_format,OF this]
      from *[of m] guess gm by (elim conjE exE) note gm=this[rule_format]
      from *[of n] guess gn by (elim conjE exE) note gn=this[rule_format]
      from fine_division_exists[OF gauge_inter[OF gm(1) gn(1)], of a b]
      obtain p where p: "p tagged_division_of cbox a b" "(λx. gm x ∩ gn x) fine p"
        by auto
      { fix s1 s2 i1 and i2::'b
        assume no: "norm(s2 - s1) ≤ e/2" "norm (s1 - i1) < e/4" "norm (s2 - i2) < e/4"
        have "norm (i1 - i2) ≤ norm (i1 - s1) + norm (s1 - s2) + norm (s2 - i2)"
          using norm_triangle_ineq[of "i1 - s1" "s1 - i2"]
          using norm_triangle_ineq[of "s1 - s2" "s2 - i2"]
          by (auto simp add: algebra_simps)
        also have "… < e"
          using no
          unfolding norm_minus_commute
          by (auto simp add: algebra_simps)
        finally have "norm (i1 - i2) < e" .
      } note triangle3 = this
      have finep: "gm fine p" "gn fine p"
        using fine_inter p  by auto
      { fix x
        assume x: "x ∈ cbox a b"
        have "norm (f x - g n x) + norm (f x - g m x) ≤ inverse (real n + 1) + inverse (real m + 1)"
          using g(1)[OF x, of n] g(1)[OF x, of m] by auto
        also have "… ≤ inverse (real M) + inverse (real M)"
          apply (rule add_mono)
          using M(2) m n by auto
        also have "… = 2 / real M"
          unfolding divide_inverse by auto
        finally have "norm (g n x - g m x) ≤ 2 / real M"
          using norm_triangle_le[of "g n x - f x" "f x - g m x" "2 / real M"]
          by (auto simp add: algebra_simps simp add: norm_minus_commute)
      } note norm_le = this
      have le_e2: "norm ((∑(x, k)∈p. content k *R g n x) - (∑(x, k)∈p. content k *R g m x)) ≤ e / 2"
        apply (rule order_trans [OF rsum_diff_bound[OF p(1), where e="2 / real M"]])
        apply (blast intro: norm_le)
        using M True
        by (auto simp add: field_simps)
      then show "dist (i m) (i n) < e"
        unfolding dist_norm
        using gm gn p finep
        by (auto intro!: triangle3)
    qed
  qed
  then obtain s where s: "i ⇢ s"
    using convergent_eq_cauchy[symmetric] by blast
  show ?thesis
    unfolding integrable_on_def has_integral
  proof (rule_tac x=s in exI, clarify)
    fix e::real
    assume e: "0 < e"
    then have *: "e/3 > 0" by auto
    then obtain N1 where N1: "∀n≥N1. norm (i n - s) < e / 3"
      using LIMSEQ_D [OF s] by metis
    from e True have "e / 3 / content (cbox a b) > 0"
      by (auto simp add: field_simps)
    from real_arch_invD[OF this] guess N2 by (elim exE conjE) note N2=this
    from i[of "N1 + N2",unfolded has_integral,rule_format,OF *] guess g' .. note g'=conjunctD2[OF this,rule_format]
    { fix sf sg i
      assume no: "norm (sf - sg) ≤ e / 3"
                 "norm(i - s) < e / 3"
                 "norm (sg - i) < e / 3"
      have "norm (sf - s) ≤ norm (sf - sg) + norm (sg - i) + norm (i - s)"
        using norm_triangle_ineq[of "sf - sg" "sg - s"]
        using norm_triangle_ineq[of "sg -  i" " i - s"]
        by (auto simp add: algebra_simps)
      also have "… < e"
        using no
        unfolding norm_minus_commute
        by (auto simp add: algebra_simps)
      finally have "norm (sf - s) < e" .
    } note lem = this
    { fix p
      assume p: "p tagged_division_of (cbox a b) ∧ g' fine p"
      then have norm_less: "norm ((∑(x, k)∈p. content k *R g (N1 + N2) x) - i (N1 + N2)) < e / 3"
        using g' by blast
      have "content (cbox a b) < e / 3 * (of_nat N2)"
        using N2 unfolding inverse_eq_divide using True by (auto simp add: field_simps)
      moreover have "e / 3 * of_nat N2 ≤ e / 3 * (of_nat (N1 + N2) + 1)"
        using ‹e>0› by auto
      ultimately have "content (cbox a b) < e / 3 * (of_nat (N1 + N2) + 1)"
        by linarith
      then have le_e3: "inverse (real (N1 + N2) + 1) * content (cbox a b) ≤ e / 3"
        unfolding inverse_eq_divide
        by (auto simp add: field_simps)
      have ne3: "norm (i (N1 + N2) - s) < e / 3"
        using N1 by auto
      have "norm ((∑(x, k)∈p. content k *R f x) - s) < e"
        apply (rule lem[OF order_trans [OF _ le_e3] ne3 norm_less])
        apply (rule rsum_diff_bound[OF p[THEN conjunct1]])
        apply (blast intro: g)
        done }
    then show "∃d. gauge d ∧
             (∀p. p tagged_division_of cbox a b ∧ d fine p ⟶ norm ((∑(x, k)∈p. content k *R f x) - s) < e)"
      by (blast intro: g')
  qed
qed

lemmas integrable_uniform_limit_real = integrable_uniform_limit [where 'a=real, simplified]


subsection ‹Negligible sets.›

definition "negligible (s:: 'a::euclidean_space set) ⟷
  (∀a b. ((indicator s :: 'a⇒real) has_integral 0) (cbox a b))"


subsection ‹Negligibility of hyperplane.›

lemma setsum_nonzero_image_lemma:
  assumes "finite s"
    and "g a = 0"
    and "∀x∈s. ∀y∈s. f x = f y ∧ x ≠ y ⟶ g (f x) = 0"
  shows "setsum g {f x |x. x ∈ s ∧ f x ≠ a} = setsum (g ∘ f) s"
  apply (subst setsum_iterate)
  using assms monoidal_monoid
  unfolding setsum_iterate[OF assms(1)]
  apply (auto intro!: iterate_nonzero_image_lemma)
  done

lemma interval_doublesplit:
  fixes a :: "'a::euclidean_space"
  assumes "k ∈ Basis"
  shows "cbox a b ∩ {x . ¦x∙k - c¦ ≤ (e::real)} =
    cbox (∑i∈Basis. (if i = k then max (a∙k) (c - e) else a∙i) *R i)
     (∑i∈Basis. (if i = k then min (b∙k) (c + e) else b∙i) *R i)"
proof -
  have *: "⋀x c e::real. ¦x - c¦ ≤ e ⟷ x ≥ c - e ∧ x ≤ c + e"
    by auto
  have **: "⋀s P Q. s ∩ {x. P x ∧ Q x} = (s ∩ {x. Q x}) ∩ {x. P x}"
    by blast
  show ?thesis
    unfolding * ** interval_split[OF assms] by (rule refl)
qed

lemma division_doublesplit:
  fixes a :: "'a::euclidean_space"
  assumes "p division_of (cbox a b)"
    and k: "k ∈ Basis"
  shows "{l ∩ {x. ¦x∙k - c¦ ≤ e} |l. l ∈ p ∧ l ∩ {x. ¦x∙k - c¦ ≤ e} ≠ {}}
         division_of  (cbox a b ∩ {x. ¦x∙k - c¦ ≤ e})"
proof -
  have *: "⋀x c. ¦x - c¦ ≤ e ⟷ x ≥ c - e ∧ x ≤ c + e"
    by auto
  have **: "⋀p q p' q'. p division_of q ⟹ p = p' ⟹ q = q' ⟹ p' division_of q'"
    by auto
  note division_split(1)[OF assms, where c="c+e",unfolded interval_split[OF k]]
  note division_split(2)[OF this, where c="c-e" and k=k,OF k]
  then show ?thesis
    apply (rule **)
    unfolding interval_doublesplit [OF k]
    using k
    apply (simp_all add: * interval_split)
    apply (rule equalityI, blast)
    apply clarsimp
    apply (rule_tac x="l ∩ {x. c + e ≥ x ∙ k}" in exI)
    apply auto
    done
qed

lemma content_doublesplit:
  fixes a :: "'a::euclidean_space"
  assumes "0 < e"
    and k: "k ∈ Basis"
  obtains d where "0 < d" and "content (cbox a b ∩ {x. ¦x∙k - c¦ ≤ d}) < e"
proof (cases "content (cbox a b) = 0")
  case True
  then have ce: "content (cbox a b) < e"
    by (metis ‹0 < e›)
  show ?thesis
    apply (rule that[of 1])
    apply simp
    unfolding interval_doublesplit[OF k]
    apply (rule le_less_trans[OF content_subset ce])
    apply (auto simp: interval_doublesplit[symmetric] k)
    done
next
  case False
  def d  "e / 3 / setprod (λi. b∙i - a∙i) (Basis - {k})"
  note False[unfolded content_eq_0 not_ex not_le, rule_format]
  then have "⋀x. x ∈ Basis ⟹ b∙x > a∙x"
    by (auto simp add:not_le)
  then have prod0: "0 < setprod (λi. b∙i - a∙i) (Basis - {k})"
    by (force simp add: setprod_pos field_simps)
  then have "d > 0"
    using assms
    by (auto simp add: d_def field_simps)
  then show ?thesis
  proof (rule that[of d])
    have *: "Basis = insert k (Basis - {k})"
      using k by auto
    have less_e: "(min (b ∙ k) (c + d) - max (a ∙ k) (c - d)) * (∏i∈Basis - {k}. b ∙ i - a ∙ i) < e"
    proof -
      have "(min (b ∙ k) (c + d) - max (a ∙ k) (c - d)) ≤ 2 * d"
        by auto
      also have "… < e / (∏i∈Basis - {k}. b ∙ i - a ∙ i)"
        unfolding d_def
        using assms prod0
        by (auto simp add: field_simps)
      finally show "(min (b ∙ k) (c + d) - max (a ∙ k) (c - d)) * (∏i∈Basis - {k}. b ∙ i - a ∙ i) < e"
        unfolding pos_less_divide_eq[OF prod0] .
    qed
    show "content (cbox a b ∩ {x. ¦x ∙ k - c¦ ≤ d}) < e"
    proof (cases "cbox a b ∩ {x. ¦x ∙ k - c¦ ≤ d} = {}")
      case True
      then show ?thesis
        using assms by simp
    next
      case False
      then have
          "(∏i∈Basis - {k}. interval_upperbound (cbox a b ∩ {x. ¦x ∙ k - c¦ ≤ d}) ∙ i -
                interval_lowerbound (cbox a b ∩ {x. ¦x ∙ k - c¦ ≤ d}) ∙ i)
           = (∏i∈Basis - {k}. b∙i - a∙i)"
        by (simp add: box_eq_empty interval_doublesplit[OF k])
      then show "content (cbox a b ∩ {x. ¦x ∙ k - c¦ ≤ d}) < e"
        unfolding content_def
        using assms False
        apply (subst *)
        apply (subst setprod.insert)
        apply (simp_all add: interval_doublesplit[OF k] box_eq_empty not_less less_e)
        done
    qed
  qed
qed

lemma negligible_standard_hyperplane[intro]:
  fixes k :: "'a::euclidean_space"
  assumes k: "k ∈ Basis"
  shows "negligible {x. x∙k = c}"
  unfolding negligible_def has_integral
proof (clarify, goal_cases)
  case (1 a b e)
  from this and k obtain d where d: "0 < d" "content (cbox a b ∩ {x. ¦x ∙ k - c¦ ≤ d}) < e"
    by (rule content_doublesplit)
  let ?i = "indicator {x::'a. x∙k = c} :: 'a⇒real"
  show ?case
    apply (rule_tac x="λx. ball x d" in exI)
    apply rule
    apply (rule gauge_ball)
    apply (rule d)
  proof (rule, rule)
    fix p
    assume p: "p tagged_division_of (cbox a b) ∧ (λx. ball x d) fine p"
    have *: "(∑(x, ka)∈p. content ka *R ?i x) =
      (∑(x, ka)∈p. content (ka ∩ {x. ¦x∙k - c¦ ≤ d}) *R ?i x)"
      apply (rule setsum.cong)
      apply (rule refl)
      unfolding split_paired_all real_scaleR_def mult_cancel_right split_conv
      apply cases
      apply (rule disjI1)
      apply assumption
      apply (rule disjI2)
    proof -
      fix x l
      assume as: "(x, l) ∈ p" "?i x ≠ 0"
      then have xk: "x∙k = c"
        unfolding indicator_def
        apply -
        apply (rule ccontr)
        apply auto
        done
      show "content l = content (l ∩ {x. ¦x ∙ k - c¦ ≤ d})"
        apply (rule arg_cong[where f=content])
        apply (rule set_eqI)
        apply rule
        apply rule
        unfolding mem_Collect_eq
      proof -
        fix y
        assume y: "y ∈ l"
        note p[THEN conjunct2,unfolded fine_def,rule_format,OF as(1),unfolded split_conv]
        note this[unfolded subset_eq mem_ball dist_norm,rule_format,OF y]
        note le_less_trans[OF Basis_le_norm[OF k] this]
        then show "¦y ∙ k - c¦ ≤ d"
          unfolding inner_simps xk by auto
      qed auto
    qed
    note p'= tagged_division_ofD[OF p[THEN conjunct1]] and p''=division_of_tagged_division[OF p[THEN conjunct1]]
    show "norm ((∑(x, ka)∈p. content ka *R ?i x) - 0) < e"
      unfolding diff_0_right *
      unfolding real_scaleR_def real_norm_def
      apply (subst abs_of_nonneg)
      apply (rule setsum_nonneg)
      apply rule
      unfolding split_paired_all split_conv
      apply (rule mult_nonneg_nonneg)
      apply (drule p'(4))
      apply (erule exE)+
      apply(rule_tac b=b in back_subst)
      prefer 2
      apply (subst(asm) eq_commute)
      apply assumption
      apply (subst interval_doublesplit[OF k])
      apply (rule content_pos_le)
      apply (rule indicator_pos_le)
    proof -
      have "(∑(x, ka)∈p. content (ka ∩ {x. ¦x ∙ k - c¦ ≤ d}) * ?i x) ≤
        (∑(x, ka)∈p. content (ka ∩ {x. ¦x ∙ k - c¦ ≤ d}))"
        apply (rule setsum_mono)
        unfolding split_paired_all split_conv
        apply (rule mult_right_le_one_le)
        apply (drule p'(4))
        apply (auto simp add:interval_doublesplit[OF k])
        done
      also have "… < e"
      proof (subst setsum_over_tagged_division_lemma[OF p[THEN conjunct1]], goal_cases)
        case prems: (1 u v)
        have "content (cbox u v ∩ {x. ¦x ∙ k - c¦ ≤ d}) ≤ content (cbox u v)"
          unfolding interval_doublesplit[OF k]
          apply (rule content_subset)
          unfolding interval_doublesplit[symmetric,OF k]
          apply auto
          done
        then show ?case
          unfolding prems interval_doublesplit[OF k]
          by (blast intro: antisym)
      next
        have *: "setsum content {l ∩ {x. ¦x ∙ k - c¦ ≤ d} |l. l ∈ snd ` p ∧ l ∩ {x. ¦x ∙ k - c¦ ≤ d} ≠ {}} ≥ 0"
          apply (rule setsum_nonneg)
          apply rule
          unfolding mem_Collect_eq image_iff
          apply (erule exE bexE conjE)+
          unfolding split_paired_all
        proof -
          fix x l a b
          assume as: "x = l ∩ {x. ¦x ∙ k - c¦ ≤ d}" "(a, b) ∈ p" "l = snd (a, b)"
          guess u v using p'(4)[OF as(2)] by (elim exE) note * = this
          show "content x ≥ 0"
            unfolding as snd_conv * interval_doublesplit[OF k]
            by (rule content_pos_le)
        qed
        have **: "norm (1::real) ≤ 1"
          by auto
        note division_doublesplit[OF p'' k,unfolded interval_doublesplit[OF k]]
        note dsum_bound[OF this **,unfolded interval_doublesplit[symmetric,OF k]]
        note this[unfolded real_scaleR_def real_norm_def mult_1_right mult_1, of c d]
        note le_less_trans[OF this d(2)]
        from this[unfolded abs_of_nonneg[OF *]]
        show "(∑ka∈snd ` p. content (ka ∩ {x. ¦x ∙ k - c¦ ≤ d})) < e"
          apply (subst setsum_nonzero_image_lemma[of "snd ` p" content "{}", unfolded o_def,symmetric])
          apply (rule finite_imageI p' content_empty)+
          unfolding forall_in_division[OF p'']
        proof (rule,rule,rule,rule,rule,rule,rule,erule conjE)
          fix m n u v
          assume as:
            "cbox m n ∈ snd ` p" "cbox u v ∈ snd ` p"
            "cbox m n ≠ cbox u v"
            "cbox m n ∩ {x. ¦x ∙ k - c¦ ≤ d} = cbox u v ∩ {x. ¦x ∙ k - c¦ ≤ d}"
          have "(cbox m n ∩ {x. ¦x ∙ k - c¦ ≤ d}) ∩ (cbox u v ∩ {x. ¦x ∙ k - c¦ ≤ d}) ⊆ cbox m n ∩ cbox u v"
            by blast
          note interior_mono[OF this, unfolded division_ofD(5)[OF p'' as(1-3)] interior_Int[of "cbox m n"]]
          then have "interior (cbox m n ∩ {x. ¦x ∙ k - c¦ ≤ d}) = {}"
            unfolding as Int_absorb by auto
          then show "content (cbox m n ∩ {x. ¦x ∙ k - c¦ ≤ d}) = 0"
            unfolding interval_doublesplit[OF k] content_eq_0_interior[symmetric] .
        qed
      qed
      finally show "(∑(x, ka)∈p. content (ka ∩ {x. ¦x ∙ k - c¦ ≤ d}) * ?i x) < e" .
    qed
  qed
qed


subsection ‹A technical lemma about "refinement" of division.›

lemma tagged_division_finer:
  fixes p :: "('a::euclidean_space × ('a::euclidean_space set)) set"
  assumes "p tagged_division_of (cbox a b)"
    and "gauge d"
  obtains q where "q tagged_division_of (cbox a b)"
    and "d fine q"
    and "∀(x,k) ∈ p. k ⊆ d(x) ⟶ (x,k) ∈ q"
proof -
  let ?P = "λp. p tagged_partial_division_of (cbox a b) ⟶ gauge d ⟶
    (∃q. q tagged_division_of (⋃{k. ∃x. (x,k) ∈ p}) ∧ d fine q ∧
      (∀(x,k) ∈ p. k ⊆ d(x) ⟶ (x,k) ∈ q))"
  {
    have *: "finite p" "p tagged_partial_division_of (cbox a b)"
      using assms(1)
      unfolding tagged_division_of_def
      by auto
    presume "⋀p. finite p ⟹ ?P p"
    from this[rule_format,OF * assms(2)] guess q .. note q=this
    then show ?thesis
      apply -
      apply (rule that[of q])
      unfolding tagged_division_ofD[OF assms(1)]
      apply auto
      done
  }
  fix p :: "('a::euclidean_space × ('a::euclidean_space set)) set"
  assume as: "finite p"
  show "?P p"
    apply rule
    apply rule
    using as
  proof (induct p)
    case empty
    show ?case
      apply (rule_tac x="{}" in exI)
      unfolding fine_def
      apply auto
      done
  next
    case (insert xk p)
    guess x k using surj_pair[of xk] by (elim exE) note xk=this
    note tagged_partial_division_subset[OF insert(4) subset_insertI]
    from insert(3)[OF this insert(5)] guess q1 .. note q1 = conjunctD3[OF this]
    have *: "⋃{l. ∃y. (y,l) ∈ insert xk p} = k ∪ ⋃{l. ∃y. (y,l) ∈ p}"
      unfolding xk by auto
    note p = tagged_partial_division_ofD[OF insert(4)]
    from p(4)[unfolded xk, OF insertI1] guess u v by (elim exE) note uv=this

    have "finite {k. ∃x. (x, k) ∈ p}"
      apply (rule finite_subset[of _ "snd ` p"])
      using p
      apply safe
      apply (metis image_iff snd_conv)
      apply auto
      done
    then have int: "interior (cbox u v) ∩ interior (⋃{k. ∃x. (x, k) ∈ p}) = {}"
      apply (rule inter_interior_unions_intervals)
      apply (rule open_interior)
      apply (rule_tac[!] ballI)
      unfolding mem_Collect_eq
      apply (erule_tac[!] exE)
      apply (drule p(4)[OF insertI2])
      apply assumption
      apply (rule p(5))
      unfolding uv xk
      apply (rule insertI1)
      apply (rule insertI2)
      apply assumption
      using insert(2)
      unfolding uv xk
      apply auto
      done
    show ?case
    proof (cases "cbox u v ⊆ d x")
      case True
      then show ?thesis
        apply (rule_tac x="{(x,cbox u v)} ∪ q1" in exI)
        apply rule
        unfolding * uv
        apply (rule tagged_division_union)
        apply (rule tagged_division_of_self)
        apply (rule p[unfolded xk uv] insertI1)+
        apply (rule q1)
        apply (rule int)
        apply rule
        apply (rule fine_union)
        apply (subst fine_def)
        defer
        apply (rule q1)
        unfolding Ball_def split_paired_All split_conv
        apply rule
        apply rule
        apply rule
        apply rule
        apply (erule insertE)
        apply (simp add: uv xk)
        apply (rule UnI2)
        apply (drule q1(3)[rule_format])
        unfolding xk uv
        apply auto
        done
    next
      case False
      from fine_division_exists[OF assms(2), of u v] guess q2 . note q2=this
      show ?thesis
        apply (rule_tac x="q2 ∪ q1" in exI)
        apply rule
        unfolding * uv
        apply (rule tagged_division_union q2 q1 int fine_union)+
        unfolding Ball_def split_paired_All split_conv
        apply rule
        apply (rule fine_union)
        apply (rule q1 q2)+
        apply rule
        apply rule
        apply rule
        apply rule
        apply (erule insertE)
        apply (rule UnI2)
        apply (simp add: False uv xk)
        apply (drule q1(3)[rule_format])
        using False
        unfolding xk uv
        apply auto
        done
    qed
  qed
qed


subsection ‹Hence the main theorem about negligible sets.›

lemma finite_product_dependent:
  assumes "finite s"
    and "⋀x. x ∈ s ⟹ finite (t x)"
  shows "finite {(i, j) |i j. i ∈ s ∧ j ∈ t i}"
  using assms
proof induct
  case (insert x s)
  have *: "{(i, j) |i j. i ∈ insert x s ∧ j ∈ t i} =
    (λy. (x,y)) ` (t x) ∪ {(i, j) |i j. i ∈ s ∧ j ∈ t i}" by auto
  show ?case
    unfolding *
    apply (rule finite_UnI)
    using insert
    apply auto
    done
qed auto

lemma sum_sum_product:
  assumes "finite s"
    and "∀i∈s. finite (t i)"
  shows "setsum (λi. setsum (x i) (t i)::real) s =
    setsum (λ(i,j). x i j) {(i,j) | i j. i ∈ s ∧ j ∈ t i}"
  using assms
proof induct
  case (insert a s)
  have *: "{(i, j) |i j. i ∈ insert a s ∧ j ∈ t i} =
    (λy. (a,y)) ` (t a) ∪ {(i, j) |i j. i ∈ s ∧ j ∈ t i}" by auto
  show ?case
    unfolding *
    apply (subst setsum.union_disjoint)
    unfolding setsum.insert[OF insert(1-2)]
    prefer 4
    apply (subst insert(3))
    unfolding add_right_cancel
  proof -
    show "setsum (x a) (t a) = (∑(xa, y)∈ Pair a ` t a. x xa y)"
      apply (subst setsum.reindex)
      unfolding inj_on_def
      apply auto
      done
    show "finite {(i, j) |i j. i ∈ s ∧ j ∈ t i}"
      apply (rule finite_product_dependent)
      using insert
      apply auto
      done
  qed (insert insert, auto)
qed auto

lemma has_integral_negligible:
  fixes f :: "'b::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "negligible s"
    and "∀x∈(t - s). f x = 0"
  shows "(f has_integral 0) t"
proof -
  presume P: "⋀f::'b::euclidean_space ⇒ 'a.
    ⋀a b. ∀x. x ∉ s ⟶ f x = 0 ⟹ (f has_integral 0) (cbox a b)"
  let ?f = "(λx. if x ∈ t then f x else 0)"
  show ?thesis
    apply (rule_tac f="?f" in has_integral_eq)
    unfolding if_P
    apply (rule refl)
    apply (subst has_integral_alt)
    apply cases
    apply (subst if_P, assumption)
    unfolding if_not_P
  proof -
    assume "∃a b. t = cbox a b"
    then guess a b apply - by (erule exE)+ note t = this
    show "(?f has_integral 0) t"
      unfolding t
      apply (rule P)
      using assms(2)
      unfolding t
      apply auto
      done
  next
    show "∀e>0. ∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ t then ?f x else 0) has_integral z) (cbox a b) ∧ norm (z - 0) < e)"
      apply safe
      apply (rule_tac x=1 in exI)
      apply rule
      apply (rule zero_less_one)
      apply safe
      apply (rule_tac x=0 in exI)
      apply rule
      apply (rule P)
      using assms(2)
      apply auto
      done
  qed
next
  fix f :: "'b ⇒ 'a"
  fix a b :: 'b
  assume assm: "∀x. x ∉ s ⟶ f x = 0"
  show "(f has_integral 0) (cbox a b)"
    unfolding has_integral
  proof (safe, goal_cases)
    case prems: (1 e)
    then have "⋀n. e / 2 / ((real n+1) * (2 ^ n)) > 0"
      apply -
      apply (rule divide_pos_pos)
      defer
      apply (rule mult_pos_pos)
      apply (auto simp add:field_simps)
      done
    note assms(1)[unfolded negligible_def has_integral,rule_format,OF this,of a b]
    note allI[OF this,of "λx. x"]
    from choice[OF this] guess d .. note d=conjunctD2[OF this[rule_format]]
    show ?case
      apply (rule_tac x="λx. d (nat ⌊norm (f x)⌋) x" in exI)
    proof safe
      show "gauge (λx. d (nat ⌊norm (f x)⌋) x)"
        using d(1) unfolding gauge_def by auto
      fix p
      assume as: "p tagged_division_of (cbox a b)" "(λx. d (nat ⌊norm (f x)⌋) x) fine p"
      let ?goal = "norm ((∑(x, k)∈p. content k *R f x) - 0) < e"
      {
        presume "p ≠ {} ⟹ ?goal"
        then show ?goal
          apply (cases "p = {}")
          using prems
          apply auto
          done
      }
      assume as': "p ≠ {}"
      from real_arch_simple[of "Max((λ(x,k). norm(f x)) ` p)"] guess N ..
      then have N: "∀x∈(λ(x, k). norm (f x)) ` p. x ≤ real N"
        by (meson Max_ge as(1) dual_order.trans finite_imageI tagged_division_of_finite)
      have "∀i. ∃q. q tagged_division_of (cbox a b) ∧ (d i) fine q ∧ (∀(x, k)∈p. k ⊆ (d i) x ⟶ (x, k) ∈ q)"
        by (auto intro: tagged_division_finer[OF as(1) d(1)])
      from choice[OF this] guess q .. note q=conjunctD3[OF this[rule_format]]
      have *: "⋀i. (∑(x, k)∈q i. content k *R indicator s x) ≥ (0::real)"
        apply (rule setsum_nonneg)
        apply safe
        unfolding real_scaleR_def
        apply (drule tagged_division_ofD(4)[OF q(1)])
        apply (auto intro: mult_nonneg_nonneg)
        done
      have **: "finite s ⟹ finite t ⟹ (∀(x,y) ∈ t. (0::real) ≤ g(x,y)) ⟹
        (∀y∈s. ∃x. (x,y) ∈ t ∧ f(y) ≤ g(x,y)) ⟹ setsum f s ≤ setsum g t" for f g s t
        apply (rule setsum_le_included[of s t g snd f])
        prefer 4
        apply safe
        apply (erule_tac x=x in ballE)
        apply (erule exE)
        apply (rule_tac x="(xa,x)" in bexI)
        apply auto
        done
      have "norm ((∑(x, k)∈p. content k *R f x) - 0) ≤ setsum (λi. (real i + 1) *
        norm (setsum (λ(x,k). content k *R indicator s x :: real) (q i))) {..N+1}"
        unfolding real_norm_def setsum_right_distrib abs_of_nonneg[OF *] diff_0_right
        apply (rule order_trans)
        apply (rule norm_setsum)
        apply (subst sum_sum_product)
        prefer 3
      proof (rule **, safe)
        show "finite {(i, j) |i j. i ∈ {..N + 1} ∧ j ∈ q i}"
          apply (rule finite_product_dependent)
          using q
          apply auto
          done
        fix i a b
        assume as'': "(a, b) ∈ q i"
        show "0 ≤ (real i + 1) * (content b *R indicator s a)"
          unfolding real_scaleR_def
          using tagged_division_ofD(4)[OF q(1) as'']
          by (auto intro!: mult_nonneg_nonneg)
      next
        fix i :: nat
        show "finite (q i)"
          using q by auto
      next
        fix x k
        assume xk: "(x, k) ∈ p"
        def n  "nat ⌊norm (f x)⌋"
        have *: "norm (f x) ∈ (λ(x, k). norm (f x)) ` p"
          using xk by auto
        have nfx: "real n ≤ norm (f x)" "norm (f x) ≤ real n + 1"
          unfolding n_def by auto
        then have "n ∈ {0..N + 1}"
          using N[rule_format,OF *] by auto
        moreover
        note as(2)[unfolded fine_def,rule_format,OF xk,unfolded split_conv]
        note q(3)[rule_format,OF xk,unfolded split_conv,rule_format,OF this]
        note this[unfolded n_def[symmetric]]
        moreover
        have "norm (content k *R f x) ≤ (real n + 1) * (content k * indicator s x)"
        proof (cases "x ∈ s")
          case False
          then show ?thesis
            using assm by auto
        next
          case True
          have *: "content k ≥ 0"
            using tagged_division_ofD(4)[OF as(1) xk] by auto
          moreover
          have "content k * norm (f x) ≤ content k * (real n + 1)"
            apply (rule mult_mono)
            using nfx *
            apply auto
            done
          ultimately
          show ?thesis
            unfolding abs_mult
            using nfx True
            by (auto simp add: field_simps)
        qed
        ultimately show "∃y. (y, x, k) ∈ {(i, j) |i j. i ∈ {..N + 1} ∧ j ∈ q i} ∧ norm (content k *R f x) ≤
          (real y + 1) * (content k *R indicator s x)"
          apply (rule_tac x=n in exI)
          apply safe
          apply (rule_tac x=n in exI)
          apply (rule_tac x="(x,k)" in exI)
          apply safe
          apply auto
          done
      qed (insert as, auto)
      also have "… ≤ setsum (λi. e / 2 / 2 ^ i) {..N+1}"
      proof (rule setsum_mono, goal_cases)
        case (1 i)
        then show ?case
          apply (subst mult.commute, subst pos_le_divide_eq[symmetric])
          using d(2)[rule_format, of "q i" i]
          using q[rule_format]
          apply (auto simp add: field_simps)
          done
      qed
      also have "… < e * inverse 2 * 2"
        unfolding divide_inverse setsum_right_distrib[symmetric]
        apply (rule mult_strict_left_mono)
        unfolding power_inverse [symmetric] lessThan_Suc_atMost[symmetric]
        apply (subst geometric_sum)
        using prems
        apply auto
        done
      finally show "?goal" by auto
    qed
  qed
qed

lemma has_integral_spike:
  fixes f :: "'b::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "negligible s"
    and "(∀x∈(t - s). g x = f x)"
    and "(f has_integral y) t"
  shows "(g has_integral y) t"
proof -
  {
    fix a b :: 'b
    fix f g :: "'b ⇒ 'a"
    fix y :: 'a
    assume as: "∀x ∈ cbox a b - s. g x = f x" "(f has_integral y) (cbox a b)"
    have "((λx. f x + (g x - f x)) has_integral (y + 0)) (cbox a b)"
      apply (rule has_integral_add[OF as(2)])
      apply (rule has_integral_negligible[OF assms(1)])
      using as
      apply auto
      done
    then have "(g has_integral y) (cbox a b)"
      by auto
  } note * = this
  show ?thesis
    apply (subst has_integral_alt)
    using assms(2-)
    apply -
    apply (rule cond_cases)
    apply safe
    apply (rule *)
    apply assumption+
    apply (subst(asm) has_integral_alt)
    unfolding if_not_P
    apply (erule_tac x=e in allE)
    apply safe
    apply (rule_tac x=B in exI)
    apply safe
    apply (erule_tac x=a in allE)
    apply (erule_tac x=b in allE)
    apply safe
    apply (rule_tac x=z in exI)
    apply safe
    apply (rule *[where fa2="λx. if x∈t then f x else 0"])
    apply auto
    done
qed

lemma has_integral_spike_eq:
  assumes "negligible s"
    and "∀x∈(t - s). g x = f x"
  shows "((f has_integral y) t ⟷ (g has_integral y) t)"
  apply rule
  apply (rule_tac[!] has_integral_spike[OF assms(1)])
  using assms(2)
  apply auto
  done

lemma integrable_spike:
  assumes "negligible s"
    and "∀x∈(t - s). g x = f x"
    and "f integrable_on t"
  shows "g integrable_on  t"
  using assms
  unfolding integrable_on_def
  apply -
  apply (erule exE)
  apply rule
  apply (rule has_integral_spike)
  apply fastforce+
  done

lemma integral_spike:
  assumes "negligible s"
    and "∀x∈(t - s). g x = f x"
  shows "integral t f = integral t g"
  using has_integral_spike_eq[OF assms] by (simp add: integral_def integrable_on_def)


subsection ‹Some other trivialities about negligible sets.›

lemma negligible_subset[intro]:
  assumes "negligible s"
    and "t ⊆ s"
  shows "negligible t"
  unfolding negligible_def
proof (safe, goal_cases)
  case (1 a b)
  show ?case
    using assms(1)[unfolded negligible_def,rule_format,of a b]
    apply -
    apply (rule has_integral_spike[OF assms(1)])
    defer
    apply assumption
    using assms(2)
    unfolding indicator_def
    apply auto
    done
qed

lemma negligible_diff[intro?]:
  assumes "negligible s"
  shows "negligible (s - t)"
  using assms by auto

lemma negligible_inter:
  assumes "negligible s ∨ negligible t"
  shows "negligible (s ∩ t)"
  using assms by auto

lemma negligible_union:
  assumes "negligible s"
    and "negligible t"
  shows "negligible (s ∪ t)"
  unfolding negligible_def
proof (safe, goal_cases)
  case (1 a b)
  note assm = assms[unfolded negligible_def,rule_format,of a b]
  then show ?case
    apply (subst has_integral_spike_eq[OF assms(2)])
    defer
    apply assumption
    unfolding indicator_def
    apply auto
    done
qed

lemma negligible_union_eq[simp]: "negligible (s ∪ t) ⟷ negligible s ∧ negligible t"
  using negligible_union by auto

lemma negligible_sing[intro]: "negligible {a::'a::euclidean_space}"
  using negligible_standard_hyperplane[OF SOME_Basis, of "a ∙ (SOME i. i ∈ Basis)"] by auto

lemma negligible_insert[simp]: "negligible (insert a s) ⟷ negligible s"
  apply (subst insert_is_Un)
  unfolding negligible_union_eq
  apply auto
  done

lemma negligible_empty[iff]: "negligible {}"
  by auto

lemma negligible_finite[intro]:
  assumes "finite s"
  shows "negligible s"
  using assms by (induct s) auto

lemma negligible_unions[intro]:
  assumes "finite s"
    and "∀t∈s. negligible t"
  shows "negligible(⋃s)"
  using assms by induct auto

lemma negligible:
  "negligible s ⟷ (∀t::('a::euclidean_space) set. ((indicator s::'a⇒real) has_integral 0) t)"
  apply safe
  defer
  apply (subst negligible_def)
proof -
  fix t :: "'a set"
  assume as: "negligible s"
  have *: "(λx. if x ∈ s ∩ t then 1 else 0) = (λx. if x∈t then if x∈s then 1 else 0 else 0)"
    by auto
  show "((indicator s::'a⇒real) has_integral 0) t"
    apply (subst has_integral_alt)
    apply cases
    apply (subst if_P,assumption)
    unfolding if_not_P
    apply safe
    apply (rule as[unfolded negligible_def,rule_format])
    apply (rule_tac x=1 in exI)
    apply safe
    apply (rule zero_less_one)
    apply (rule_tac x=0 in exI)
    using negligible_subset[OF as,of "s ∩ t"]
    unfolding negligible_def indicator_def [abs_def]
    unfolding *
    apply auto
    done
qed auto


subsection ‹Finite case of the spike theorem is quite commonly needed.›

lemma has_integral_spike_finite:
  assumes "finite s"
    and "∀x∈t-s. g x = f x"
    and "(f has_integral y) t"
  shows "(g has_integral y) t"
  apply (rule has_integral_spike)
  using assms
  apply auto
  done

lemma has_integral_spike_finite_eq:
  assumes "finite s"
    and "∀x∈t-s. g x = f x"
  shows "((f has_integral y) t ⟷ (g has_integral y) t)"
  apply rule
  apply (rule_tac[!] has_integral_spike_finite)
  using assms
  apply auto
  done

lemma integrable_spike_finite:
  assumes "finite s"
    and "∀x∈t-s. g x = f x"
    and "f integrable_on t"
  shows "g integrable_on  t"
  using assms
  unfolding integrable_on_def
  apply safe
  apply (rule_tac x=y in exI)
  apply (rule has_integral_spike_finite)
  apply auto
  done


subsection ‹In particular, the boundary of an interval is negligible.›

lemma negligible_frontier_interval: "negligible(cbox (a::'a::euclidean_space) b - box a b)"
proof -
  let ?A = "⋃((λk. {x. x∙k = a∙k} ∪ {x::'a. x∙k = b∙k}) ` Basis)"
  have "cbox a b - box a b ⊆ ?A"
    apply rule unfolding Diff_iff mem_box
    apply simp
    apply(erule conjE bexE)+
    apply(rule_tac x=i in bexI)
    apply auto
    done
  then show ?thesis
    apply -
    apply (rule negligible_subset[of ?A])
    apply (rule negligible_unions[OF finite_imageI])
    apply auto
    done
qed

lemma has_integral_spike_interior:
  assumes "∀x∈box a b. g x = f x"
    and "(f has_integral y) (cbox a b)"
  shows "(g has_integral y) (cbox a b)"
  apply (rule has_integral_spike[OF negligible_frontier_interval _ assms(2)])
  using assms(1)
  apply auto
  done

lemma has_integral_spike_interior_eq:
  assumes "∀x∈box a b. g x = f x"
  shows "(f has_integral y) (cbox a b) ⟷ (g has_integral y) (cbox a b)"
  apply rule
  apply (rule_tac[!] has_integral_spike_interior)
  using assms
  apply auto
  done

lemma integrable_spike_interior:
  assumes "∀x∈box a b. g x = f x"
    and "f integrable_on cbox a b"
  shows "g integrable_on cbox a b"
  using assms
  unfolding integrable_on_def
  using has_integral_spike_interior[OF assms(1)]
  by auto


subsection ‹Integrability of continuous functions.›

lemma neutral_and[simp]: "neutral op ∧ = True"
  unfolding neutral_def by (rule some_equality) auto

lemma monoidal_and[intro]: "monoidal op ∧"
  unfolding monoidal_def by auto

lemma iterate_and[simp]:
  assumes "finite s"
  shows "(iterate op ∧) s p ⟷ (∀x∈s. p x)"
  using assms
  apply induct
  unfolding iterate_insert[OF monoidal_and]
  apply auto
  done

lemma operative_division_and:
  assumes "operative op ∧ P"
    and "d division_of (cbox a b)"
  shows "(∀i∈d. P i) ⟷ P (cbox a b)"
  using operative_division[OF monoidal_and assms] division_of_finite[OF assms(2)]
  by auto

lemma operative_approximable:
  fixes f :: "'b::euclidean_space ⇒ 'a::banach"
  assumes "0 ≤ e"
  shows "operative op ∧ (λi. ∃g. (∀x∈i. norm (f x - g (x::'b)) ≤ e) ∧ g integrable_on i)"
  unfolding operative_def neutral_and
proof safe
  fix a b :: 'b
  show "∃g. (∀x∈cbox a b. norm (f x - g x) ≤ e) ∧ g integrable_on cbox a b"
    if "content (cbox a b) = 0"
    apply (rule_tac x=f in exI)
    using assms that
    apply (auto intro!: integrable_on_null)
    done
  {
    fix c g
    fix k :: 'b
    assume as: "∀x∈cbox a b. norm (f x - g x) ≤ e" "g integrable_on cbox a b"
    assume k: "k ∈ Basis"
    show "∃g. (∀x∈cbox a b ∩ {x. x ∙ k ≤ c}. norm (f x - g x) ≤ e) ∧ g integrable_on cbox a b ∩ {x. x ∙ k ≤ c}"
      "∃g. (∀x∈cbox a b ∩ {x. c ≤ x ∙ k}. norm (f x - g x) ≤ e) ∧ g integrable_on cbox a b ∩ {x. c ≤ x ∙ k}"
      apply (rule_tac[!] x=g in exI)
      using as(1) integrable_split[OF as(2) k]
      apply auto
      done
  }
  fix c k g1 g2
  assume as: "∀x∈cbox a b ∩ {x. x ∙ k ≤ c}. norm (f x - g1 x) ≤ e" "g1 integrable_on cbox a b ∩ {x. x ∙ k ≤ c}"
    "∀x∈cbox a b ∩ {x. c ≤ x ∙ k}. norm (f x - g2 x) ≤ e" "g2 integrable_on cbox a b ∩ {x. c ≤ x ∙ k}"
  assume k: "k ∈ Basis"
  let ?g = "λx. if x∙k = c then f x else if x∙k ≤ c then g1 x else g2 x"
  show "∃g. (∀x∈cbox a b. norm (f x - g x) ≤ e) ∧ g integrable_on cbox a b"
    apply (rule_tac x="?g" in exI)
    apply safe
  proof goal_cases
    case (1 x)
    then show ?case
      apply -
      apply (cases "x∙k=c")
      apply (case_tac "x∙k < c")
      using as assms
      apply auto
      done
  next
    case 2
    presume "?g integrable_on cbox a b ∩ {x. x ∙ k ≤ c}"
      and "?g integrable_on cbox a b ∩ {x. x ∙ k ≥ c}"
    then guess h1 h2 unfolding integrable_on_def by auto
    from has_integral_split[OF this k] show ?case
      unfolding integrable_on_def by auto
  next
    show "?g integrable_on cbox a b ∩ {x. x ∙ k ≤ c}" "?g integrable_on cbox a b ∩ {x. x ∙ k ≥ c}"
      apply(rule_tac[!] integrable_spike[OF negligible_standard_hyperplane[of k c]])
      using k as(2,4)
      apply auto
      done
  qed
qed

lemma approximable_on_division:
  fixes f :: "'b::euclidean_space ⇒ 'a::banach"
  assumes "0 ≤ e"
    and "d division_of (cbox a b)"
    and "∀i∈d. ∃g. (∀x∈i. norm (f x - g x) ≤ e) ∧ g integrable_on i"
  obtains g where "∀x∈cbox a b. norm (f x - g x) ≤ e" "g integrable_on cbox a b"
proof -
  note * = operative_division[OF monoidal_and operative_approximable[OF assms(1)] assms(2)]
  note this[unfolded iterate_and[OF division_of_finite[OF assms(2)]]]
  from assms(3)[unfolded this[of f]] guess g ..
  then show thesis
    apply -
    apply (rule that[of g])
    apply auto
    done
qed

lemma integrable_continuous:
  fixes f :: "'b::euclidean_space ⇒ 'a::banach"
  assumes "continuous_on (cbox a b) f"
  shows "f integrable_on cbox a b"
proof (rule integrable_uniform_limit, safe)
  fix e :: real
  assume e: "e > 0"
  from compact_uniformly_continuous[OF assms compact_cbox,unfolded uniformly_continuous_on_def,rule_format,OF e] guess d ..
  note d=conjunctD2[OF this,rule_format]
  from fine_division_exists[OF gauge_ball[OF d(1)], of a b] guess p . note p=this
  note p' = tagged_division_ofD[OF p(1)]
  have *: "∀i∈snd ` p. ∃g. (∀x∈i. norm (f x - g x) ≤ e) ∧ g integrable_on i"
  proof (safe, unfold snd_conv)
    fix x l
    assume as: "(x, l) ∈ p"
    from p'(4)[OF this] guess a b by (elim exE) note l=this
    show "∃g. (∀x∈l. norm (f x - g x) ≤ e) ∧ g integrable_on l"
      apply (rule_tac x="λy. f x" in exI)
    proof safe
      show "(λy. f x) integrable_on l"
        unfolding integrable_on_def l
        apply rule
        apply (rule has_integral_const)
        done
      fix y
      assume y: "y ∈ l"
      note fineD[OF p(2) as,unfolded subset_eq,rule_format,OF this]
      note d(2)[OF _ _ this[unfolded mem_ball]]
      then show "norm (f y - f x) ≤ e"
        using y p'(2-3)[OF as] unfolding dist_norm l norm_minus_commute by fastforce
    qed
  qed
  from e have "e ≥ 0"
    by auto
  from approximable_on_division[OF this division_of_tagged_division[OF p(1)] *] guess g .
  then show "∃g. (∀x∈cbox a b. norm (f x - g x) ≤ e) ∧ g integrable_on cbox a b"
    by auto
qed

lemma integrable_continuous_real:
  fixes f :: "real ⇒ 'a::banach"
  assumes "continuous_on {a .. b} f"
  shows "f integrable_on {a .. b}"
  by (metis assms box_real(2) integrable_continuous)


subsection ‹Specialization of additivity to one dimension.›

lemma
  shows real_inner_1_left: "inner 1 x = x"
  and real_inner_1_right: "inner x 1 = x"
  by simp_all

lemma content_real_eq_0: "content {a .. b::real} = 0 ⟷ a ≥ b"
  by (metis atLeastatMost_empty_iff2 content_empty content_real diff_self eq_iff le_cases le_iff_diff_le_0)

lemma interval_real_split:
  "{a .. b::real} ∩ {x. x ≤ c} = {a .. min b c}"
  "{a .. b} ∩ {x. c ≤ x} = {max a c .. b}"
  apply (metis Int_atLeastAtMostL1 atMost_def)
  apply (metis Int_atLeastAtMostL2 atLeast_def)
  done

lemma operative_1_lt:
  assumes "monoidal opp"
  shows "operative opp f ⟷ ((∀a b. b ≤ a ⟶ f {a .. b::real} = neutral opp) ∧
    (∀a b c. a < c ∧ c < b ⟶ opp (f {a .. c}) (f {c .. b}) = f {a .. b}))"
  apply (simp add: operative_def content_real_eq_0 del: content_real_if)
proof safe
  fix a b c :: real
  assume as:
    "∀a b c. f {a..b} = opp (f ({a..b} ∩ {x. x ≤ c})) (f ({a..b} ∩ Collect (op ≤ c)))"
    "a < c"
    "c < b"
    from this(2-) have "cbox a b ∩ {x. x ≤ c} = cbox a c" "cbox a b ∩ {x. x ≥ c} = cbox c b"
      by (auto simp: mem_box)
    then show "opp (f {a..c}) (f {c..b}) = f {a..b}"
      unfolding as(1)[rule_format,of a b "c"] by auto
next
  fix a b c :: real
  assume as: "∀a b. b ≤ a ⟶ f {a..b} = neutral opp"
    "∀a b c. a < c ∧ c < b ⟶ opp (f {a..c}) (f {c..b}) = f {a..b}"
  show " f {a..b} = opp (f ({a..b} ∩ {x. x ≤ c})) (f ({a..b} ∩ Collect (op ≤ c)))"
  proof (cases "c ∈ {a..b}")
    case False
    then have "c < a ∨ c > b" by auto
    then show ?thesis
    proof
      assume "c < a"
      then have *: "{a..b} ∩ {x. x ≤ c} = {1..0}" "{a..b} ∩ {x. c ≤ x} = {a..b}"
        by auto
      show ?thesis
        unfolding *
        apply (subst as(1)[rule_format,of 0 1])
        using assms
        apply auto
        done
    next
      assume "b < c"
      then have *: "{a..b} ∩ {x. x ≤ c} = {a..b}" "{a..b} ∩ {x. c ≤ x} = {1 .. 0}"
        by auto
      show ?thesis
        unfolding *
        apply (subst as(1)[rule_format,of 0 1])
        using assms
        apply auto
        done
    qed
  next
    case True
    then have *: "min (b) c = c" "max a c = c"
      by auto
    have **: "(1::real) ∈ Basis"
      by simp
    have ***: "⋀P Q. (∑i∈Basis. (if i = 1 then P i else Q i) *R i) = (P 1::real)"
      by simp
    show ?thesis
      unfolding interval_real_split unfolding *
    proof (cases "c = a ∨ c = b")
      case False
      then show "f {a..b} = opp (f {a..c}) (f {c..b})"
        apply -
        apply (subst as(2)[rule_format])
        using True
        apply auto
        done
    next
      case True
      then show "f {a..b} = opp (f {a..c}) (f {c..b})"
      proof
        assume *: "c = a"
        then have "f {a .. c} = neutral opp"
          apply -
          apply (rule as(1)[rule_format])
          apply auto
          done
        then show ?thesis
          using assms unfolding * by auto
      next
        assume *: "c = b"
        then have "f {c .. b} = neutral opp"
          apply -
          apply (rule as(1)[rule_format])
          apply auto
          done
        then show ?thesis
          using assms unfolding * by auto
      qed
    qed
  qed
qed

lemma operative_1_le:
  assumes "monoidal opp"
  shows "operative opp f ⟷ ((∀a b. b ≤ a ⟶ f {a .. b::real} = neutral opp) ∧
    (∀a b c. a ≤ c ∧ c ≤ b ⟶ opp (f {a .. c}) (f {c .. b}) = f {a .. b}))"
  unfolding operative_1_lt[OF assms]
proof safe
  fix a b c :: real
  assume as:
    "∀a b c. a ≤ c ∧ c ≤ b ⟶ opp (f {a..c}) (f {c..b}) = f {a..b}"
    "a < c"
    "c < b"
  show "opp (f {a..c}) (f {c..b}) = f {a..b}"
    apply (rule as(1)[rule_format])
    using as(2-)
    apply auto
    done
next
  fix a b c :: real
  assume "∀a b. b ≤ a ⟶ f {a .. b} = neutral opp"
    and "∀a b c. a < c ∧ c < b ⟶ opp (f {a..c}) (f {c..b}) = f {a..b}"
    and "a ≤ c"
    and "c ≤ b"
  note as = this[rule_format]
  show "opp (f {a..c}) (f {c..b}) = f {a..b}"
  proof (cases "c = a ∨ c = b")
    case False
    then show ?thesis
      apply -
      apply (subst as(2))
      using as(3-)
      apply auto
      done
  next
    case True
    then show ?thesis
    proof
      assume *: "c = a"
      then have "f {a .. c} = neutral opp"
        apply -
        apply (rule as(1)[rule_format])
        apply auto
        done
      then show ?thesis
        using assms unfolding * by auto
    next
      assume *: "c = b"
      then have "f {c .. b} = neutral opp"
        apply -
        apply (rule as(1)[rule_format])
        apply auto
        done
      then show ?thesis
        using assms unfolding * by auto
    qed
  qed
qed


subsection ‹Special case of additivity we need for the FCT.›

lemma additive_tagged_division_1:
  fixes f :: "real ⇒ 'a::real_normed_vector"
  assumes "a ≤ b"
    and "p tagged_division_of {a..b}"
  shows "setsum (λ(x,k). f(Sup k) - f(Inf k)) p = f b - f a"
proof -
  let ?f = "(λk::(real) set. if k = {} then 0 else f(interval_upperbound k) - f(interval_lowerbound k))"
  have ***: "∀i∈Basis. a ∙ i ≤ b ∙ i"
    using assms by auto
  have *: "operative op + ?f"
    unfolding operative_1_lt[OF monoidal_monoid] box_eq_empty
    by auto
  have **: "cbox a b ≠ {}"
    using assms(1) by auto
  note operative_tagged_division[OF monoidal_monoid * assms(2)[simplified box_real[symmetric]]]
  note * = this[unfolded if_not_P[OF **] interval_bounds[OF ***],symmetric]
  show ?thesis
    unfolding *
    apply (subst setsum_iterate[symmetric])
    defer
    apply (rule setsum.cong)
    unfolding split_paired_all split_conv
    using assms(2)
    apply auto
    done
qed


subsection ‹A useful lemma allowing us to factor out the content size.›

lemma has_integral_factor_content:
  "(f has_integral i) (cbox a b) ⟷
    (∀e>0. ∃d. gauge d ∧ (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
      norm (setsum (λ(x,k). content k *R f x) p - i) ≤ e * content (cbox a b)))"
proof (cases "content (cbox a b) = 0")
  case True
  show ?thesis
    unfolding has_integral_null_eq[OF True]
    apply safe
    apply (rule, rule, rule gauge_trivial, safe)
    unfolding setsum_content_null[OF True] True
    defer
    apply (erule_tac x=1 in allE)
    apply safe
    defer
    apply (rule fine_division_exists[of _ a b])
    apply assumption
    apply (erule_tac x=p in allE)
    unfolding setsum_content_null[OF True]
    apply auto
    done
next
  case False
  note F = this[unfolded content_lt_nz[symmetric]]
  let ?P = "λe opp. ∃d. gauge d ∧
    (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶ opp (norm ((∑(x, k)∈p. content k *R f x) - i)) e)"
  show ?thesis
    apply (subst has_integral)
  proof safe
    fix e :: real
    assume e: "e > 0"
    {
      assume "∀e>0. ?P e op <"
      then show "?P (e * content (cbox a b)) op ≤"
        apply (erule_tac x="e * content (cbox a b)" in allE)
        apply (erule impE)
        defer
        apply (erule exE,rule_tac x=d in exI)
        using F e
        apply (auto simp add:field_simps)
        done
    }
    {
      assume "∀e>0. ?P (e * content (cbox a b)) op ≤"
      then show "?P e op <"
        apply (erule_tac x="e / 2 / content (cbox a b)" in allE)
        apply (erule impE)
        defer
        apply (erule exE,rule_tac x=d in exI)
        using F e
        apply (auto simp add: field_simps)
        done
    }
  qed
qed

lemma has_integral_factor_content_real:
  "(f has_integral i) {a .. b::real} ⟷
    (∀e>0. ∃d. gauge d ∧ (∀p. p tagged_division_of {a .. b}  ∧ d fine p ⟶
      norm (setsum (λ(x,k). content k *R f x) p - i) ≤ e * content {a .. b} ))"
  unfolding box_real[symmetric]
  by (rule has_integral_factor_content)


subsection ‹Fundamental theorem of calculus.›

lemma interval_bounds_real:
  fixes q b :: real
  assumes "a ≤ b"
  shows "Sup {a..b} = b"
    and "Inf {a..b} = a"
  using assms by auto

lemma fundamental_theorem_of_calculus:
  fixes f :: "real ⇒ 'a::banach"
  assumes "a ≤ b"
    and "∀x∈{a .. b}. (f has_vector_derivative f' x) (at x within {a .. b})"
  shows "(f' has_integral (f b - f a)) {a .. b}"
  unfolding has_integral_factor_content box_real[symmetric]
proof safe
  fix e :: real
  assume e: "e > 0"
  note assm = assms(2)[unfolded has_vector_derivative_def has_derivative_within_alt]
  have *: "⋀P Q. ∀x∈{a .. b}. P x ∧ (∀e>0. ∃d>0. Q x e d) ⟹ ∀x. ∃(d::real)>0. x∈{a .. b} ⟶ Q x e d"
    using e by blast
  note this[OF assm,unfolded gauge_existence_lemma]
  from choice[OF this,unfolded Ball_def[symmetric]] guess d ..
  note d=conjunctD2[OF this[rule_format],rule_format]
  show "∃d. gauge d ∧ (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
    norm ((∑(x, k)∈p. content k *R f' x) - (f b - f a)) ≤ e * content (cbox a b))"
    apply (rule_tac x="λx. ball x (d x)" in exI)
    apply safe
    apply (rule gauge_ball_dependent)
    apply rule
    apply (rule d(1))
  proof -
    fix p
    assume as: "p tagged_division_of cbox a b" "(λx. ball x (d x)) fine p"
    show "norm ((∑(x, k)∈p. content k *R f' x) - (f b - f a)) ≤ e * content (cbox a b)"
      unfolding content_real[OF assms(1), simplified box_real[symmetric]] additive_tagged_division_1[OF assms(1) as(1)[simplified box_real],of f,symmetric]
      unfolding additive_tagged_division_1[OF assms(1) as(1)[simplified box_real],of "λx. x",symmetric]
      unfolding setsum_right_distrib
      defer
      unfolding setsum_subtractf[symmetric]
    proof (rule setsum_norm_le,safe)
      fix x k
      assume "(x, k) ∈ p"
      note xk = tagged_division_ofD(2-4)[OF as(1) this]
      from this(3) guess u v by (elim exE) note k=this
      have *: "u ≤ v"
        using xk unfolding k by auto
      have ball: "∀xa∈k. xa ∈ ball x (d x)"
        using as(2)[unfolded fine_def,rule_format,OF ‹(x,k)∈p›,unfolded split_conv subset_eq] .
      have "norm ((v - u) *R f' x - (f v - f u)) ≤
        norm (f u - f x - (u - x) *R f' x) + norm (f v - f x - (v - x) *R f' x)"
        apply (rule order_trans[OF _ norm_triangle_ineq4])
        apply (rule eq_refl)
        apply (rule arg_cong[where f=norm])
        unfolding scaleR_diff_left
        apply (auto simp add:algebra_simps)
        done
      also have "… ≤ e * norm (u - x) + e * norm (v - x)"
        apply (rule add_mono)
        apply (rule d(2)[of "x" "u",unfolded o_def])
        prefer 4
        apply (rule d(2)[of "x" "v",unfolded o_def])
        using ball[rule_format,of u] ball[rule_format,of v]
        using xk(1-2)
        unfolding k subset_eq
        apply (auto simp add:dist_real_def)
        done
      also have "… ≤ e * (Sup k - Inf k)"
        unfolding k interval_bounds_real[OF *]
        using xk(1)
        unfolding k
        by (auto simp add: dist_real_def field_simps)
      finally show "norm (content k *R f' x - (f (Sup k) - f (Inf k))) ≤
        e * (Sup k - Inf k)"
        unfolding box_real k interval_bounds_real[OF *] content_real[OF *]
          interval_upperbound_real interval_lowerbound_real
          .
    qed
  qed
qed

lemma ident_has_integral:
  fixes a::real
  assumes "a ≤ b"
  shows "((λx. x) has_integral (b2 - a2) / 2) {a..b}"
proof -
  have "((λx. x) has_integral inverse 2 * b2 - inverse 2 * a2) {a..b}"
    apply (rule fundamental_theorem_of_calculus [OF assms], clarify)
    unfolding power2_eq_square
    by (rule derivative_eq_intros | simp)+
  then show ?thesis
    by (simp add: field_simps)
qed

lemma integral_ident [simp]:
  fixes a::real
  assumes "a ≤ b"
  shows "integral {a..b} (λx. x) = (if a ≤ b then (b2 - a2) / 2 else 0)"
using ident_has_integral integral_unique by fastforce

lemma ident_integrable_on:
  fixes a::real
  shows "(λx. x) integrable_on {a..b}"
by (metis atLeastatMost_empty_iff integrable_on_def has_integral_empty ident_has_integral)


subsection ‹Taylor series expansion›

lemma (in bounded_bilinear) setsum_prod_derivatives_has_vector_derivative:
  assumes "p>0"
  and f0: "Df 0 = f"
  and Df: "⋀m t. m < p ⟹ a ≤ t ⟹ t ≤ b ⟹
    (Df m has_vector_derivative Df (Suc m) t) (at t within {a .. b})"
  and g0: "Dg 0 = g"
  and Dg: "⋀m t. m < p ⟹ a ≤ t ⟹ t ≤ b ⟹
    (Dg m has_vector_derivative Dg (Suc m) t) (at t within {a .. b})"
  and ivl: "a ≤ t" "t ≤ b"
  shows "((λt. ∑i<p. (-1)^i *R prod (Df i t) (Dg (p - Suc i) t))
    has_vector_derivative
      prod (f t) (Dg p t) - (-1)^p *R prod (Df p t) (g t))
    (at t within {a .. b})"
  using assms
proof cases
  assume p: "p ≠ 1"
  def p'  "p - 2"
  from assms p have p': "{..<p} = {..Suc p'}" "p = Suc (Suc p')"
    by (auto simp: p'_def)
  have *: "⋀i. i ≤ p' ⟹ Suc (Suc p' - i) = (Suc (Suc p') - i)"
    by auto
  let ?f = "λi. (-1) ^ i *R (prod (Df i t) (Dg ((p - i)) t))"
  have "(∑i<p. (-1) ^ i *R (prod (Df i t) (Dg (Suc (p - Suc i)) t) +
    prod (Df (Suc i) t) (Dg (p - Suc i) t))) =
    (∑i≤(Suc p'). ?f i - ?f (Suc i))"
    by (auto simp: algebra_simps p'(2) numeral_2_eq_2 * lessThan_Suc_atMost)
  also note setsum_telescope
  finally
  have "(∑i<p. (-1) ^ i *R (prod (Df i t) (Dg (Suc (p - Suc i)) t) +
    prod (Df (Suc i) t) (Dg (p - Suc i) t)))
    = prod (f t) (Dg p t) - (- 1) ^ p *R prod (Df p t) (g t)"
    unfolding p'[symmetric]
    by (simp add: assms)
  thus ?thesis
    using assms
    by (auto intro!: derivative_eq_intros has_vector_derivative)
qed (auto intro!: derivative_eq_intros has_vector_derivative)

lemma
  fixes f::"real⇒'a::banach"
  assumes "p>0"
  and f0: "Df 0 = f"
  and Df: "⋀m t. m < p ⟹ a ≤ t ⟹ t ≤ b ⟹
    (Df m has_vector_derivative Df (Suc m) t) (at t within {a .. b})"
  and ivl: "a ≤ b"
  defines "i ≡ λx. ((b - x) ^ (p - 1) / fact (p - 1)) *R Df p x"
  shows taylor_has_integral:
    "(i has_integral f b - (∑i<p. ((b - a) ^ i / fact i) *R Df i a)) {a..b}"
  and taylor_integral:
    "f b = (∑i<p. ((b - a) ^ i / fact i) *R Df i a) + integral {a..b} i"
  and taylor_integrable:
    "i integrable_on {a .. b}"
proof goal_cases
  case 1
  interpret bounded_bilinear "scaleR::real⇒'a⇒'a"
    by (rule bounded_bilinear_scaleR)
  def g  "λs. (b - s)^(p - 1)/fact (p - 1)"
  def Dg  "λn s. if n < p then (-1)^n * (b - s)^(p - 1 - n) / fact (p - 1 - n) else 0"
  have g0: "Dg 0 = g"
    using ‹p > 0›
    by (auto simp add: Dg_def divide_simps g_def split: if_split_asm)
  {
    fix m
    assume "p > Suc m"
    hence "p - Suc m = Suc (p - Suc (Suc m))"
      by auto
    hence "real (p - Suc m) * fact (p - Suc (Suc m)) = fact (p - Suc m)"
      by auto
  } note fact_eq = this
  have Dg: "⋀m t. m < p ⟹ a ≤ t ⟹ t ≤ b ⟹
    (Dg m has_vector_derivative Dg (Suc m) t) (at t within {a .. b})"
    unfolding Dg_def
    by (auto intro!: derivative_eq_intros simp: has_vector_derivative_def fact_eq divide_simps)
  let ?sum = "λt. ∑i<p. (- 1) ^ i *R Dg i t *R Df (p - Suc i) t"
  from setsum_prod_derivatives_has_vector_derivative[of _ Dg _ _ _ Df,
      OF ‹p > 0› g0 Dg f0 Df]
  have deriv: "⋀t. a ≤ t ⟹ t ≤ b ⟹
    (?sum has_vector_derivative
      g t *R Df p t - (- 1) ^ p *R Dg p t *R f t) (at t within {a..b})"
    by auto
  from fundamental_theorem_of_calculus[rule_format, OF ‹a ≤ b› deriv]
  have "(i has_integral ?sum b - ?sum a) {a .. b}"
    by (simp add: i_def g_def Dg_def)
  also
  have one: "(- 1) ^ p' * (- 1) ^ p' = (1::real)"
    and "{..<p} ∩ {i. p = Suc i} = {p - 1}"
    for p'
    using ‹p > 0›
    by (auto simp: power_mult_distrib[symmetric])
  then have "?sum b = f b"
    using Suc_pred'[OF ‹p > 0›]
    by (simp add: diff_eq_eq Dg_def power_0_left le_Suc_eq if_distrib
        cond_application_beta setsum.If_cases f0)
  also
  have "{..<p} = (λx. p - x - 1) ` {..<p}"
  proof safe
    fix x
    assume "x < p"
    thus "x ∈ (λx. p - x - 1) ` {..<p}"
      by (auto intro!: image_eqI[where x = "p - x - 1"])
  qed simp
  from _ this
  have "?sum a = (∑i<p. ((b - a) ^ i / fact i) *R Df i a)"
    by (rule setsum.reindex_cong) (auto simp add: inj_on_def Dg_def one)
  finally show c: ?case .
  case 2 show ?case using c integral_unique by force
  case 3 show ?case using c by force
qed


subsection ‹Attempt a systematic general set of "offset" results for components.›

lemma gauge_modify:
  assumes "(∀s. open s ⟶ open {x. f(x) ∈ s})" "gauge d"
  shows "gauge (λx. {y. f y ∈ d (f x)})"
  using assms
  unfolding gauge_def
  apply safe
  defer
  apply (erule_tac x="f x" in allE)
  apply (erule_tac x="d (f x)" in allE)
  apply auto
  done


subsection ‹Only need trivial subintervals if the interval itself is trivial.›

lemma division_of_nontrivial:
  fixes s :: "'a::euclidean_space set set"
  assumes "s division_of (cbox a b)"
    and "content (cbox a b) ≠ 0"
  shows "{k. k ∈ s ∧ content k ≠ 0} division_of (cbox a b)"
  using assms(1)
  apply -
proof (induct "card s" arbitrary: s rule: nat_less_induct)
  fix s::"'a set set"
  assume assm: "s division_of (cbox a b)"
    "∀m<card s. ∀x. m = card x ⟶
      x division_of (cbox a b) ⟶ {k ∈ x. content k ≠ 0} division_of (cbox a b)"
  note s = division_ofD[OF assm(1)]
  let ?thesis = "{k ∈ s. content k ≠ 0} division_of (cbox a b)"
  {
    presume *: "{k ∈ s. content k ≠ 0} ≠ s ⟹ ?thesis"
    show ?thesis
      apply cases
      defer
      apply (rule *)
      apply assumption
      using assm(1)
      apply auto
      done
  }
  assume noteq: "{k ∈ s. content k ≠ 0} ≠ s"
  then obtain k where k: "k ∈ s" "content k = 0"
    by auto
  from s(4)[OF k(1)] guess c d by (elim exE) note k=k this
  from k have "card s > 0"
    unfolding card_gt_0_iff using assm(1) by auto
  then have card: "card (s - {k}) < card s"
    using assm(1) k(1)
    apply (subst card_Diff_singleton_if)
    apply auto
    done
  have *: "closed (⋃(s - {k}))"
    apply (rule closed_Union)
    defer
    apply rule
    apply (drule DiffD1,drule s(4))
    using assm(1)
    apply auto
    done
  have "k ⊆ ⋃(s - {k})"
    apply safe
    apply (rule *[unfolded closed_limpt,rule_format])
    unfolding islimpt_approachable
  proof safe
    fix x
    fix e :: real
    assume as: "x ∈ k" "e > 0"
    from k(2)[unfolded k content_eq_0] guess i ..
    then have i:"c∙i = d∙i" "i∈Basis"
      using s(3)[OF k(1),unfolded k] unfolding box_ne_empty by auto
    then have xi: "x∙i = d∙i"
      using as unfolding k mem_box by (metis antisym)
    def y  "∑j∈Basis. (if j = i then if c∙i ≤ (a∙i + b∙i) / 2 then c∙i +
      min e (b∙i - c∙i) / 2 else c∙i - min e (c∙i - a∙i) / 2 else x∙j) *R j"
    show "∃x'∈⋃(s - {k}). x' ≠ x ∧ dist x' x < e"
      apply (rule_tac x=y in bexI)
    proof
      have "d ∈ cbox c d"
        using s(3)[OF k(1)]
        unfolding k box_eq_empty mem_box
        by (fastforce simp add: not_less)
      then have "d ∈ cbox a b"
        using s(2)[OF k(1)]
        unfolding k
        by auto
      note di = this[unfolded mem_box,THEN bspec[where x=i]]
      then have xyi: "y∙i ≠ x∙i"
        unfolding y_def i xi
        using as(2) assms(2)[unfolded content_eq_0] i(2)
        by (auto elim!: ballE[of _ _ i])
      then show "y ≠ x"
        unfolding euclidean_eq_iff[where 'a='a] using i by auto
      have *: "Basis = insert i (Basis - {i})"
        using i by auto
      have "norm (y - x) < e + setsum (λi. 0) Basis"
        apply (rule le_less_trans[OF norm_le_l1])
        apply (subst *)
        apply (subst setsum.insert)
        prefer 3
        apply (rule add_less_le_mono)
      proof -
        show "¦(y - x) ∙ i¦ < e"
          using di as(2) y_def i xi by (auto simp: inner_simps)
        show "(∑i∈Basis - {i}. ¦(y - x) ∙ i¦) ≤ (∑i∈Basis. 0)"
          unfolding y_def by (auto simp: inner_simps)
      qed auto
      then show "dist y x < e"
        unfolding dist_norm by auto
      have "y ∉ k"
        unfolding k mem_box
        apply rule
        apply (erule_tac x=i in ballE)
        using xyi k i xi
        apply auto
        done
      moreover
      have "y ∈ ⋃s"
        using set_rev_mp[OF as(1) s(2)[OF k(1)]] as(2) di i
        unfolding s mem_box y_def
        by (auto simp: field_simps elim!: ballE[of _ _ i])
      ultimately
      show "y ∈ ⋃(s - {k})" by auto
    qed
  qed
  then have "⋃(s - {k}) = cbox a b"
    unfolding s(6)[symmetric] by auto
  then have  "{ka ∈ s - {k}. content ka ≠ 0} division_of (cbox a b)"
    apply -
    apply (rule assm(2)[rule_format,OF card refl])
    apply (rule division_ofI)
    defer
    apply (rule_tac[1-4] s)
    using assm(1)
    apply auto
    done
  moreover
  have "{ka ∈ s - {k}. content ka ≠ 0} = {k ∈ s. content k ≠ 0}"
    using k by auto
  ultimately show ?thesis by auto
qed


subsection ‹Integrability on subintervals.›

lemma operative_integrable:
  fixes f :: "'b::euclidean_space ⇒ 'a::banach"
  shows "operative op ∧ (λi. f integrable_on i)"
  unfolding operative_def neutral_and
  apply safe
  apply (subst integrable_on_def)
  unfolding has_integral_null_eq
  apply (rule, rule refl)
  apply (rule, assumption, assumption)+
  unfolding integrable_on_def
  by (auto intro!: has_integral_split)

lemma integrable_subinterval:
  fixes f :: "'b::euclidean_space ⇒ 'a::banach"
  assumes "f integrable_on cbox a b"
    and "cbox c d ⊆ cbox a b"
  shows "f integrable_on cbox c d"
  apply (cases "cbox c d = {}")
  defer
  apply (rule partial_division_extend_1[OF assms(2)],assumption)
  using operative_division_and[OF operative_integrable,symmetric,of _ _ _ f] assms(1)
  apply auto
  done

lemma integrable_subinterval_real:
  fixes f :: "real ⇒ 'a::banach"
  assumes "f integrable_on {a .. b}"
    and "{c .. d} ⊆ {a .. b}"
  shows "f integrable_on {c .. d}"
  by (metis assms(1) assms(2) box_real(2) integrable_subinterval)


subsection ‹Combining adjacent intervals in 1 dimension.›

lemma has_integral_combine:
  fixes a b c :: real
  assumes "a ≤ c"
    and "c ≤ b"
    and "(f has_integral i) {a .. c}"
    and "(f has_integral (j::'a::banach)) {c .. b}"
  shows "(f has_integral (i + j)) {a .. b}"
proof -
  note operative_integral[of f, unfolded operative_1_le[OF monoidal_lifted[OF monoidal_monoid]]]
  note conjunctD2[OF this,rule_format]
  note * = this(2)[OF conjI[OF assms(1-2)],unfolded if_P[OF assms(3)]]
  then have "f integrable_on cbox a b"
    apply -
    apply (rule ccontr)
    apply (subst(asm) if_P)
    defer
    apply (subst(asm) if_P)
    using assms(3-)
    apply auto
    done
  with *
  show ?thesis
    apply -
    apply (subst(asm) if_P)
    defer
    apply (subst(asm) if_P)
    defer
    apply (subst(asm) if_P)
    unfolding lifted.simps
    using assms(3-)
    apply (auto simp add: integrable_on_def integral_unique)
    done
qed

lemma integral_combine:
  fixes f :: "real ⇒ 'a::banach"
  assumes "a ≤ c"
    and "c ≤ b"
    and "f integrable_on {a .. b}"
  shows "integral {a .. c} f + integral {c .. b} f = integral {a .. b} f"
  apply (rule integral_unique[symmetric])
  apply (rule has_integral_combine[OF assms(1-2)])
  apply (metis assms(2) assms(3) atLeastatMost_subset_iff box_real(2) content_pos_le content_real_eq_0 integrable_integral integrable_subinterval le_add_same_cancel2 monoid_add_class.add.left_neutral)
  by (metis assms(1) assms(3) atLeastatMost_subset_iff box_real(2) content_pos_le content_real_eq_0 integrable_integral integrable_subinterval le_add_same_cancel1 monoid_add_class.add.right_neutral)

lemma integrable_combine:
  fixes f :: "real ⇒ 'a::banach"
  assumes "a ≤ c"
    and "c ≤ b"
    and "f integrable_on {a .. c}"
    and "f integrable_on {c .. b}"
  shows "f integrable_on {a .. b}"
  using assms
  unfolding integrable_on_def
  by (fastforce intro!:has_integral_combine)


subsection ‹Reduce integrability to "local" integrability.›

lemma integrable_on_little_subintervals:
  fixes f :: "'b::euclidean_space ⇒ 'a::banach"
  assumes "∀x∈cbox a b. ∃d>0. ∀u v. x ∈ cbox u v ∧ cbox u v ⊆ ball x d ∧ cbox u v ⊆ cbox a b ⟶
    f integrable_on cbox u v"
  shows "f integrable_on cbox a b"
proof -
  have "∀x. ∃d. x∈cbox a b ⟶ d>0 ∧ (∀u v. x ∈ cbox u v ∧ cbox u v ⊆ ball x d ∧ cbox u v ⊆ cbox a b ⟶
    f integrable_on cbox u v)"
    using assms by auto
  note this[unfolded gauge_existence_lemma]
  from choice[OF this] guess d .. note d=this[rule_format]
  guess p
    apply (rule fine_division_exists[OF gauge_ball_dependent,of d a b])
    using d
    by auto
  note p=this(1-2)
  note division_of_tagged_division[OF this(1)]
  note * = operative_division_and[OF operative_integrable,OF this,symmetric,of f]
  show ?thesis
    unfolding *
    apply safe
    unfolding snd_conv
  proof -
    fix x k
    assume "(x, k) ∈ p"
    note tagged_division_ofD(2-4)[OF p(1) this] fineD[OF p(2) this]
    then show "f integrable_on k"
      apply safe
      apply (rule d[THEN conjunct2,rule_format,of x])
      apply (auto intro: order.trans)
      done
  qed
qed


subsection ‹Second FCT or existence of antiderivative.›

lemma integrable_const[intro]: "(λx. c) integrable_on cbox a b"
  unfolding integrable_on_def
  apply rule
  apply (rule has_integral_const)
  done

lemma integral_has_vector_derivative_continuous_at:
  fixes f :: "real ⇒ 'a::banach"
  assumes f: "f integrable_on {a..b}"
      and x: "x ∈ {a..b}"
      and fx: "continuous (at x within {a..b}) f"
  shows "((λu. integral {a..u} f) has_vector_derivative f x) (at x within {a..b})"
proof -
  let ?I = "λa b. integral {a..b} f"
  { fix e::real
    assume "e > 0"
    obtain d where "d>0" and d: "⋀x'. ⟦x' ∈ {a..b}; ¦x' - x¦ < d⟧ ⟹ norm(f x' - f x) ≤ e"
      using ‹e>0› fx by (auto simp: continuous_within_eps_delta dist_norm less_imp_le)
    have "norm (integral {a..y} f - integral {a..x} f - (y - x) *R f x) ≤ e * ¦y - x¦"
           if y: "y ∈ {a..b}" and yx: "¦y - x¦ < d" for y
    proof (cases "y < x")
      case False
      have "f integrable_on {a..y}"
        using f y by (simp add: integrable_subinterval_real)
      then have Idiff: "?I a y - ?I a x = ?I x y"
        using False x by (simp add: algebra_simps integral_combine)
      have fux_int: "((λu. f u - f x) has_integral integral {x..y} f - (y - x) *R f x) {x..y}"
        apply (rule has_integral_sub)
        using x y apply (force intro: integrable_integral [OF integrable_subinterval_real [OF f]])
        using has_integral_const_real [of "f x" x y] False
        apply (simp add: )
        done
      show ?thesis
        using False
        apply (simp add: abs_eq_content del: content_real_if)
        apply (rule has_integral_bound_real[where f="(λu. f u - f x)"])
        using yx False d x y ‹e>0› apply (auto simp add: Idiff fux_int)
        done
    next
      case True
      have "f integrable_on {a..x}"
        using f x by (simp add: integrable_subinterval_real)
      then have Idiff: "?I a x - ?I a y = ?I y x"
        using True x y by (simp add: algebra_simps integral_combine)
      have fux_int: "((λu. f u - f x) has_integral integral {y..x} f - (x - y) *R f x) {y..x}"
        apply (rule has_integral_sub)
        using x y apply (force intro: integrable_integral [OF integrable_subinterval_real [OF f]])
        using has_integral_const_real [of "f x" y x] True
        apply (simp add: )
        done
      have "norm (integral {a..x} f - integral {a..y} f - (x - y) *R f x) ≤ e * ¦y - x¦"
        using True
        apply (simp add: abs_eq_content del: content_real_if)
        apply (rule has_integral_bound_real[where f="(λu. f u - f x)"])
        using yx True d x y ‹e>0› apply (auto simp add: Idiff fux_int)
        done
      then show ?thesis
        by (simp add: algebra_simps norm_minus_commute)
    qed
    then have "∃d>0. ∀y∈{a..b}. ¦y - x¦ < d ⟶ norm (integral {a..y} f - integral {a..x} f - (y - x) *R f x) ≤ e * ¦y - x¦"
      using ‹d>0› by blast
  }
  then show ?thesis
    by (simp add: has_vector_derivative_def has_derivative_within_alt bounded_linear_scaleR_left)
qed

lemma integral_has_vector_derivative:
  fixes f :: "real ⇒ 'a::banach"
  assumes "continuous_on {a .. b} f"
    and "x ∈ {a .. b}"
  shows "((λu. integral {a .. u} f) has_vector_derivative f(x)) (at x within {a .. b})"
apply (rule integral_has_vector_derivative_continuous_at [OF integrable_continuous_real])
using assms
apply (auto simp: continuous_on_eq_continuous_within)
done

lemma antiderivative_continuous:
  fixes q b :: real
  assumes "continuous_on {a .. b} f"
  obtains g where "∀x∈{a .. b}. (g has_vector_derivative (f x::_::banach)) (at x within {a .. b})"
  apply (rule that)
  apply rule
  using integral_has_vector_derivative[OF assms]
  apply auto
  done


subsection ‹Combined fundamental theorem of calculus.›

lemma antiderivative_integral_continuous:
  fixes f :: "real ⇒ 'a::banach"
  assumes "continuous_on {a .. b} f"
  obtains g where "∀u∈{a .. b}. ∀v ∈ {a .. b}. u ≤ v ⟶ (f has_integral (g v - g u)) {u .. v}"
proof -
  from antiderivative_continuous[OF assms] guess g . note g=this
  show ?thesis
    apply (rule that[of g])
    apply safe
  proof goal_cases
    case prems: (1 u v)
    have "∀x∈cbox u v. (g has_vector_derivative f x) (at x within cbox u v)"
      apply rule
      apply (rule has_vector_derivative_within_subset)
      apply (rule g[rule_format])
      using prems(1,2)
      apply auto
      done
    then show ?case
      using fundamental_theorem_of_calculus[OF prems(3), of g f] by auto
  qed
qed


subsection ‹General "twiddling" for interval-to-interval function image.›

lemma has_integral_twiddle:
  assumes "0 < r"
    and "∀x. h(g x) = x"
    and "∀x. g(h x) = x"
    and "∀x. continuous (at x) g"
    and "∀u v. ∃w z. g ` cbox u v = cbox w z"
    and "∀u v. ∃w z. h ` cbox u v = cbox w z"
    and "∀u v. content(g ` cbox u v) = r * content (cbox u v)"
    and "(f has_integral i) (cbox a b)"
  shows "((λx. f(g x)) has_integral (1 / r) *R i) (h ` cbox a b)"
proof -
  show ?thesis when *: "cbox a b ≠ {} ⟹ ?thesis"
    apply cases
    defer
    apply (rule *)
    apply assumption
  proof goal_cases
    case prems: 1
    then show ?thesis
      unfolding prems assms(8)[unfolded prems has_integral_empty_eq] by auto
  qed
  assume "cbox a b ≠ {}"
  from assms(6)[rule_format,of a b] guess w z by (elim exE) note wz=this
  have inj: "inj g" "inj h"
    unfolding inj_on_def
    apply safe
    apply(rule_tac[!] ccontr)
    using assms(2)
    apply(erule_tac x=x in allE)
    using assms(2)
    apply(erule_tac x=y in allE)
    defer
    using assms(3)
    apply (erule_tac x=x in allE)
    using assms(3)
    apply(erule_tac x=y in allE)
    apply auto
    done
  show ?thesis
    unfolding has_integral_def has_integral_compact_interval_def
    apply (subst if_P)
    apply rule
    apply rule
    apply (rule wz)
  proof safe
    fix e :: real
    assume e: "e > 0"
    with assms(1) have "e * r > 0" by simp
    from assms(8)[unfolded has_integral,rule_format,OF this] guess d by (elim exE conjE) note d=this[rule_format]
    def d'  "λx. {y. g y ∈ d (g x)}"
    have d': "⋀x. d' x = {y. g y ∈ (d (g x))}"
      unfolding d'_def ..
    show "∃d. gauge d ∧ (∀p. p tagged_division_of h ` cbox a b ∧ d fine p ⟶ norm ((∑(x, k)∈p. content k *R f (g x)) - (1 / r) *R i) < e)"
    proof (rule_tac x=d' in exI, safe)
      show "gauge d'"
        using d(1)
        unfolding gauge_def d'
        using continuous_open_preimage_univ[OF assms(4)]
        by auto
      fix p
      assume as: "p tagged_division_of h ` cbox a b" "d' fine p"
      note p = tagged_division_ofD[OF as(1)]
      have "(λ(x, k). (g x, g ` k)) ` p tagged_division_of (cbox a b) ∧ d fine (λ(x, k). (g x, g ` k)) ` p"
        unfolding tagged_division_of
      proof safe
        show "finite ((λ(x, k). (g x, g ` k)) ` p)"
          using as by auto
        show "d fine (λ(x, k). (g x, g ` k)) ` p"
          using as(2) unfolding fine_def d' by auto
        fix x k
        assume xk[intro]: "(x, k) ∈ p"
        show "g x ∈ g ` k"
          using p(2)[OF xk] by auto
        show "∃u v. g ` k = cbox u v"
          using p(4)[OF xk] using assms(5-6) by auto
        {
          fix y
          assume "y ∈ k"
          then show "g y ∈ cbox a b" "g y ∈ cbox a b"
            using p(3)[OF xk,unfolded subset_eq,rule_format,of "h (g y)"]
            using assms(2)[rule_format,of y]
            unfolding inj_image_mem_iff[OF inj(2)]
            by auto
        }
        fix x' k'
        assume xk': "(x', k') ∈ p"
        fix z
        assume "z ∈ interior (g ` k)" and "z ∈ interior (g ` k')"
        then have *: "interior (g ` k) ∩ interior (g ` k') ≠ {}"
          by auto
        have same: "(x, k) = (x', k')"
          apply -
          apply (rule ccontr)
          apply (drule p(5)[OF xk xk'])
        proof -
          assume as: "interior k ∩ interior k' = {}"
          from nonempty_witness[OF *] guess z .
          then have "z ∈ g ` (interior k ∩ interior k')"
            using interior_image_subset[OF assms(4) inj(1)]
            unfolding image_Int[OF inj(1)]
            by auto
          then show False
            using as by blast
        qed
        then show "g x = g x'"
          by auto
        {
          fix z
          assume "z ∈ k"
          then show "g z ∈ g ` k'"
            using same by auto
        }
        {
          fix z
          assume "z ∈ k'"
          then show "g z ∈ g ` k"
            using same by auto
        }
      next
        fix x
        assume "x ∈ cbox a b"
        then have "h x ∈  ⋃{k. ∃x. (x, k) ∈ p}"
          using p(6) by auto
        then guess X unfolding Union_iff .. note X=this
        from this(1) guess y unfolding mem_Collect_eq ..
        then show "x ∈ ⋃{k. ∃x. (x, k) ∈ (λ(x, k). (g x, g ` k)) ` p}"
          apply -
          apply (rule_tac X="g ` X" in UnionI)
          defer
          apply (rule_tac x="h x" in image_eqI)
          using X(2) assms(3)[rule_format,of x]
          apply auto
          done
      qed
        note ** = d(2)[OF this]
        have *: "inj_on (λ(x, k). (g x, g ` k)) p"
          using inj(1) unfolding inj_on_def by fastforce
        have "(∑(x, k)∈(λ(x, k). (g x, g ` k)) ` p. content k *R f x) - i = r *R (∑(x, k)∈p. content k *R f (g x)) - i" (is "?l = _")
          using assms(7)
          unfolding algebra_simps add_left_cancel scaleR_right.setsum
          by (subst setsum.reindex_bij_betw[symmetric, where h="λ(x, k). (g x, g ` k)" and S=p])
             (auto intro!: * setsum.cong simp: bij_betw_def dest!: p(4))
      also have "… = r *R ((∑(x, k)∈p. content k *R f (g x)) - (1 / r) *R i)" (is "_ = ?r")
        unfolding scaleR_diff_right scaleR_scaleR
        using assms(1)
        by auto
      finally have *: "?l = ?r" .
      show "norm ((∑(x, k)∈p. content k *R f (g x)) - (1 / r) *R i) < e"
        using **
        unfolding *
        unfolding norm_scaleR
        using assms(1)
        by (auto simp add:field_simps)
    qed
  qed
qed


subsection ‹Special case of a basic affine transformation.›

lemma interval_image_affinity_interval:
  "∃u v. (λx. m *R (x::'a::euclidean_space) + c) ` cbox a b = cbox u v"
  unfolding image_affinity_cbox
  by auto

lemma content_image_affinity_cbox:
  "content((λx::'a::euclidean_space. m *R x + c) ` cbox a b) =
    ¦m¦ ^ DIM('a) * content (cbox a b)" (is "?l = ?r")
proof (cases "cbox a b = {}")
  case True then show ?thesis by simp
next
  case False
  show ?thesis
  proof (cases "m ≥ 0")
    case True
    with ‹cbox a b ≠ {}› have "cbox (m *R a + c) (m *R b + c) ≠ {}"
      unfolding box_ne_empty
      apply (intro ballI)
      apply (erule_tac x=i in ballE)
      apply (auto simp: inner_simps mult_left_mono)
      done
    moreover from True have *: "⋀i. (m *R b + c) ∙ i - (m *R a + c) ∙ i = m *R (b - a) ∙ i"
      by (simp add: inner_simps field_simps)
    ultimately show ?thesis
      by (simp add: image_affinity_cbox True content_cbox'
        setprod.distrib setprod_constant inner_diff_left)
  next
    case False
    with ‹cbox a b ≠ {}› have "cbox (m *R b + c) (m *R a + c) ≠ {}"
      unfolding box_ne_empty
      apply (intro ballI)
      apply (erule_tac x=i in ballE)
      apply (auto simp: inner_simps mult_left_mono)
      done
    moreover from False have *: "⋀i. (m *R a + c) ∙ i - (m *R b + c) ∙ i = (-m) *R (b - a) ∙ i"
      by (simp add: inner_simps field_simps)
    ultimately show ?thesis using False
      by (simp add: image_affinity_cbox content_cbox'
        setprod.distrib[symmetric] setprod_constant[symmetric] inner_diff_left)
  qed
qed

lemma has_integral_affinity:
  fixes a :: "'a::euclidean_space"
  assumes "(f has_integral i) (cbox a b)"
      and "m ≠ 0"
  shows "((λx. f(m *R x + c)) has_integral ((1 / (¦m¦ ^ DIM('a))) *R i)) ((λx. (1 / m) *R x + -((1 / m) *R c)) ` cbox a b)"
  apply (rule has_integral_twiddle)
  using assms
  apply (safe intro!: interval_image_affinity_interval content_image_affinity_cbox)
  apply (rule zero_less_power)
  unfolding scaleR_right_distrib
  apply auto
  done

lemma integrable_affinity:
  assumes "f integrable_on cbox a b"
    and "m ≠ 0"
  shows "(λx. f(m *R x + c)) integrable_on ((λx. (1 / m) *R x + -((1/m) *R c)) ` cbox a b)"
  using assms
  unfolding integrable_on_def
  apply safe
  apply (drule has_integral_affinity)
  apply auto
  done

lemmas has_integral_affinity01 = has_integral_affinity [of _ _ 0 "1::real", simplified]

subsection ‹Special case of stretching coordinate axes separately.›

lemma image_stretch_interval:
  "(λx. ∑k∈Basis. (m k * (x∙k)) *R k) ` cbox a (b::'a::euclidean_space) =
  (if (cbox a b) = {} then {} else
    cbox (∑k∈Basis. (min (m k * (a∙k)) (m k * (b∙k))) *R k::'a)
     (∑k∈Basis. (max (m k * (a∙k)) (m k * (b∙k))) *R k))"
proof cases
  assume *: "cbox a b ≠ {}"
  show ?thesis
    unfolding box_ne_empty if_not_P[OF *]
    apply (simp add: cbox_def image_Collect set_eq_iff euclidean_eq_iff[where 'a='a] ball_conj_distrib[symmetric])
    apply (subst choice_Basis_iff[symmetric])
  proof (intro allI ball_cong refl)
    fix x i :: 'a assume "i ∈ Basis"
    with * have a_le_b: "a ∙ i ≤ b ∙ i"
      unfolding box_ne_empty by auto
    show "(∃xa. x ∙ i = m i * xa ∧ a ∙ i ≤ xa ∧ xa ≤ b ∙ i) ⟷
        min (m i * (a ∙ i)) (m i * (b ∙ i)) ≤ x ∙ i ∧ x ∙ i ≤ max (m i * (a ∙ i)) (m i * (b ∙ i))"
    proof (cases "m i = 0")
      case True
      with a_le_b show ?thesis by auto
    next
      case False
      then have *: "⋀a b. a = m i * b ⟷ b = a / m i"
        by (auto simp add: field_simps)
      from False have
          "min (m i * (a ∙ i)) (m i * (b ∙ i)) = (if 0 < m i then m i * (a ∙ i) else m i * (b ∙ i))"
          "max (m i * (a ∙ i)) (m i * (b ∙ i)) = (if 0 < m i then m i * (b ∙ i) else m i * (a ∙ i))"
        using a_le_b by (auto simp: min_def max_def mult_le_cancel_left)
      with False show ?thesis using a_le_b
        unfolding * by (auto simp add: le_divide_eq divide_le_eq ac_simps)
    qed
  qed
qed simp

lemma interval_image_stretch_interval:
  "∃u v. (λx. ∑k∈Basis. (m k * (x∙k))*R k) ` cbox a (b::'a::euclidean_space) = cbox u (v::'a::euclidean_space)"
  unfolding image_stretch_interval by auto

lemma content_image_stretch_interval:
  "content ((λx::'a::euclidean_space. (∑k∈Basis. (m k * (x∙k))*R k)::'a) ` cbox a b) =
    ¦setprod m Basis¦ * content (cbox a b)"
proof (cases "cbox a b = {}")
  case True
  then show ?thesis
    unfolding content_def image_is_empty image_stretch_interval if_P[OF True] by auto
next
  case False
  then have "(λx. (∑k∈Basis. (m k * (x∙k))*R k)) ` cbox a b ≠ {}"
    by auto
  then show ?thesis
    using False
    unfolding content_def image_stretch_interval
    apply -
    unfolding interval_bounds' if_not_P
    unfolding abs_setprod setprod.distrib[symmetric]
    apply (rule setprod.cong)
    apply (rule refl)
    unfolding lessThan_iff
    apply (simp only: inner_setsum_left_Basis)
  proof -
    fix i :: 'a
    assume i: "i ∈ Basis"
    have "(m i < 0 ∨ m i > 0) ∨ m i = 0"
      by auto
    then show "max (m i * (a ∙ i)) (m i * (b ∙ i)) - min (m i * (a ∙ i)) (m i * (b ∙ i)) =
      ¦m i¦ * (b ∙ i - a ∙ i)"
      apply -
      apply (erule disjE)+
      unfolding min_def max_def
      using False[unfolded box_ne_empty,rule_format,of i] i
      apply (auto simp add:field_simps not_le mult_le_cancel_left_neg mult_le_cancel_left_pos)
      done
  qed
qed

lemma has_integral_stretch:
  fixes f :: "'a::euclidean_space ⇒ 'b::real_normed_vector"
  assumes "(f has_integral i) (cbox a b)"
    and "∀k∈Basis. m k ≠ 0"
  shows "((λx. f (∑k∈Basis. (m k * (x∙k))*R k)) has_integral
    ((1/ ¦setprod m Basis¦) *R i)) ((λx. (∑k∈Basis. (1 / m k * (x∙k))*R k)) ` cbox a b)"
  apply (rule has_integral_twiddle[where f=f])
  unfolding zero_less_abs_iff content_image_stretch_interval
  unfolding image_stretch_interval empty_as_interval euclidean_eq_iff[where 'a='a]
  using assms
proof -
  show "∀y::'a. continuous (at y) (λx. (∑k∈Basis. (m k * (x∙k))*R k))"
    apply rule
    apply (rule linear_continuous_at)
    unfolding linear_linear
    unfolding linear_iff inner_simps euclidean_eq_iff[where 'a='a]
    apply (auto simp add: field_simps)
    done
qed auto

lemma integrable_stretch:
  fixes f :: "'a::euclidean_space ⇒ 'b::real_normed_vector"
  assumes "f integrable_on cbox a b"
    and "∀k∈Basis. m k ≠ 0"
  shows "(λx::'a. f (∑k∈Basis. (m k * (x∙k))*R k)) integrable_on
    ((λx. ∑k∈Basis. (1 / m k * (x∙k))*R k) ` cbox a b)"
  using assms
  unfolding integrable_on_def
  apply -
  apply (erule exE)
  apply (drule has_integral_stretch)
  apply assumption
  apply auto
  done


subsection ‹even more special cases.›

lemma uminus_interval_vector[simp]:
  fixes a b :: "'a::euclidean_space"
  shows "uminus ` cbox a b = cbox (-b) (-a)"
  apply (rule set_eqI)
  apply rule
  defer
  unfolding image_iff
  apply (rule_tac x="-x" in bexI)
  apply (auto simp add:minus_le_iff le_minus_iff mem_box)
  done

lemma has_integral_reflect_lemma[intro]:
  assumes "(f has_integral i) (cbox a b)"
  shows "((λx. f(-x)) has_integral i) (cbox (-b) (-a))"
  using has_integral_affinity[OF assms, of "-1" 0]
  by auto

lemma has_integral_reflect_lemma_real[intro]:
  assumes "(f has_integral i) {a .. b::real}"
  shows "((λx. f(-x)) has_integral i) {-b .. -a}"
  using assms
  unfolding box_real[symmetric]
  by (rule has_integral_reflect_lemma)

lemma has_integral_reflect[simp]:
  "((λx. f (-x)) has_integral i) (cbox (-b) (-a)) ⟷ (f has_integral i) (cbox a b)"
  apply rule
  apply (drule_tac[!] has_integral_reflect_lemma)
  apply auto
  done

lemma integrable_reflect[simp]: "(λx. f(-x)) integrable_on cbox (-b) (-a) ⟷ f integrable_on cbox a b"
  unfolding integrable_on_def by auto

lemma integrable_reflect_real[simp]: "(λx. f(-x)) integrable_on {-b .. -a} ⟷ f integrable_on {a .. b::real}"
  unfolding box_real[symmetric]
  by (rule integrable_reflect)

lemma integral_reflect[simp]: "integral (cbox (-b) (-a)) (λx. f (-x)) = integral (cbox a b) f"
  unfolding integral_def by auto

lemma integral_reflect_real[simp]: "integral {-b .. -a} (λx. f (-x)) = integral {a .. b::real} f"
  unfolding box_real[symmetric]
  by (rule integral_reflect)


subsection ‹Stronger form of FCT; quite a tedious proof.›

lemma bgauge_existence_lemma: "(∀x∈s. ∃d::real. 0 < d ∧ q d x) ⟷ (∀x. ∃d>0. x∈s ⟶ q d x)"
  by (meson zero_less_one)

lemma additive_tagged_division_1':
  fixes f :: "real ⇒ 'a::real_normed_vector"
  assumes "a ≤ b"
    and "p tagged_division_of {a..b}"
  shows "setsum (λ(x,k). f (Sup k) - f(Inf k)) p = f b - f a"
  using additive_tagged_division_1[OF _ assms(2), of f]
  using assms(1)
  by auto

lemma split_minus[simp]: "(λ(x, k). f x k) x - (λ(x, k). g x k) x = (λ(x, k). f x k - g x k) x"
  by (simp add: split_def)

lemma norm_triangle_le_sub: "norm x + norm y ≤ e ⟹ norm (x - y) ≤ e"
  apply (subst(asm)(2) norm_minus_cancel[symmetric])
  apply (drule norm_triangle_le)
  apply (auto simp add: algebra_simps)
  done

lemma fundamental_theorem_of_calculus_interior:
  fixes f :: "real ⇒ 'a::real_normed_vector"
  assumes "a ≤ b"
    and "continuous_on {a .. b} f"
    and "∀x∈{a <..< b}. (f has_vector_derivative f'(x)) (at x)"
  shows "(f' has_integral (f b - f a)) {a .. b}"
proof -
  {
    presume *: "a < b ⟹ ?thesis"
    show ?thesis
    proof (cases "a < b")
      case True
      then show ?thesis by (rule *)
    next
      case False
      then have "a = b"
        using assms(1) by auto
      then have *: "cbox a b = {b}" "f b - f a = 0"
        by (auto simp add:  order_antisym)
      show ?thesis
        unfolding *(2)
        unfolding content_eq_0
        using * ‹a = b›
        by (auto simp: ex_in_conv)
    qed
  }
  assume ab: "a < b"
  let ?P = "λe. ∃d. gauge d ∧ (∀p. p tagged_division_of {a .. b} ∧ d fine p ⟶
    norm ((∑(x, k)∈p. content k *R f' x) - (f b - f a)) ≤ e * content {a .. b})"
  { presume "⋀e. e > 0 ⟹ ?P e" then show ?thesis unfolding has_integral_factor_content_real by auto }
  fix e :: real
  assume e: "e > 0"
  note assms(3)[unfolded has_vector_derivative_def has_derivative_at_alt ball_conj_distrib]
  note conjunctD2[OF this]
  note bounded=this(1) and this(2)
  from this(2) have "∀x∈box a b. ∃d>0. ∀y. norm (y - x) < d ⟶
    norm (f y - f x - (y - x) *R f' x) ≤ e/2 * norm (y - x)"
    apply -
    apply safe
    apply (erule_tac x=x in ballE)
    apply (erule_tac x="e/2" in allE)
    using e
    apply auto
    done
  note this[unfolded bgauge_existence_lemma]
  from choice[OF this] guess d ..
  note conjunctD2[OF this[rule_format]]
  note d = this[rule_format]
  have "bounded (f ` cbox a b)"
    apply (rule compact_imp_bounded compact_continuous_image)+
    using compact_cbox assms
    apply auto
    done
  from this[unfolded bounded_pos] guess B .. note B = this[rule_format]

  have "∃da. 0 < da ∧ (∀c. a ≤ c ∧ {a .. c} ⊆ {a .. b} ∧ {a .. c} ⊆ ball a da ⟶
    norm (content {a .. c} *R f' a - (f c - f a)) ≤ (e * (b - a)) / 4)"
  proof -
    have "a ∈ {a .. b}"
      using ab by auto
    note assms(2)[unfolded continuous_on_eq_continuous_within,rule_format,OF this]
    note * = this[unfolded continuous_within Lim_within,rule_format]
    have "(e * (b - a)) / 8 > 0"
      using e ab by (auto simp add: field_simps)
    from *[OF this] guess k .. note k = conjunctD2[OF this,rule_format]
    have "∃l. 0 < l ∧ norm(l *R f' a) ≤ (e * (b - a)) / 8"
    proof (cases "f' a = 0")
      case True
      thus ?thesis using ab e by auto
    next
      case False
      then show ?thesis
        apply (rule_tac x="(e * (b - a)) / 8 / norm (f' a)" in exI)
        using ab e
        apply (auto simp add: field_simps)
        done
    qed
    then guess l .. note l = conjunctD2[OF this]
    show ?thesis
      apply (rule_tac x="min k l" in exI)
      apply safe
      unfolding min_less_iff_conj
      apply rule
      apply (rule l k)+
    proof -
      fix c
      assume as: "a ≤ c" "{a .. c} ⊆ {a .. b}" "{a .. c} ⊆ ball a (min k l)"
      note as' = this[unfolded subset_eq Ball_def mem_ball dist_real_def mem_box]
      have "norm ((c - a) *R f' a - (f c - f a)) ≤ norm ((c - a) *R f' a) + norm (f c - f a)"
        by (rule norm_triangle_ineq4)
      also have "… ≤ e * (b - a) / 8 + e * (b - a) / 8"
      proof (rule add_mono)
        have "¦c - a¦ ≤ ¦l¦"
          using as' by auto
        then show "norm ((c - a) *R f' a) ≤ e * (b - a) / 8"
          apply -
          apply (rule order_trans[OF _ l(2)])
          unfolding norm_scaleR
          apply (rule mult_right_mono)
          apply auto
          done
      next
        show "norm (f c - f a) ≤ e * (b - a) / 8"
          apply (rule less_imp_le)
          apply (cases "a = c")
          defer
          apply (rule k(2)[unfolded dist_norm])
          using as' e ab
          apply (auto simp add: field_simps)
          done
      qed
      finally show "norm (content {a .. c} *R f' a - (f c - f a)) ≤ e * (b - a) / 4"
        unfolding content_real[OF as(1)] by auto
    qed
  qed
  then guess da .. note da=conjunctD2[OF this,rule_format]

  have "∃db>0. ∀c≤b. {c .. b} ⊆ {a .. b} ∧ {c .. b} ⊆ ball b db ⟶
    norm (content {c .. b} *R f' b - (f b - f c)) ≤ (e * (b - a)) / 4"
  proof -
    have "b ∈ {a .. b}"
      using ab by auto
    note assms(2)[unfolded continuous_on_eq_continuous_within,rule_format,OF this]
    note * = this[unfolded continuous_within Lim_within,rule_format] have "(e * (b - a)) / 8 > 0"
      using e ab by (auto simp add: field_simps)
    from *[OF this] guess k .. note k = conjunctD2[OF this,rule_format]
    have "∃l. 0 < l ∧ norm (l *R f' b) ≤ (e * (b - a)) / 8"
    proof (cases "f' b = 0")
      case True
      thus ?thesis using ab e by auto
    next
      case False
      then show ?thesis
        apply (rule_tac x="(e * (b - a)) / 8 / norm (f' b)" in exI)
        using ab e
        apply (auto simp add: field_simps)
        done
    qed
    then guess l .. note l = conjunctD2[OF this]
    show ?thesis
      apply (rule_tac x="min k l" in exI)
      apply safe
      unfolding min_less_iff_conj
      apply rule
      apply (rule l k)+
    proof -
      fix c
      assume as: "c ≤ b" "{c..b} ⊆ {a..b}" "{c..b} ⊆ ball b (min k l)"
      note as' = this[unfolded subset_eq Ball_def mem_ball dist_real_def mem_box]
      have "norm ((b - c) *R f' b - (f b - f c)) ≤ norm ((b - c) *R f' b) + norm (f b - f c)"
        by (rule norm_triangle_ineq4)
      also have "… ≤ e * (b - a) / 8 + e * (b - a) / 8"
      proof (rule add_mono)
        have "¦c - b¦ ≤ ¦l¦"
          using as' by auto
        then show "norm ((b - c) *R f' b) ≤ e * (b - a) / 8"
          apply -
          apply (rule order_trans[OF _ l(2)])
          unfolding norm_scaleR
          apply (rule mult_right_mono)
          apply auto
          done
      next
        show "norm (f b - f c) ≤ e * (b - a) / 8"
          apply (rule less_imp_le)
          apply (cases "b = c")
          defer
          apply (subst norm_minus_commute)
          apply (rule k(2)[unfolded dist_norm])
          using as' e ab
          apply (auto simp add: field_simps)
          done
      qed
      finally show "norm (content {c .. b} *R f' b - (f b - f c)) ≤ e * (b - a) / 4"
        unfolding content_real[OF as(1)] by auto
    qed
  qed
  then guess db .. note db=conjunctD2[OF this,rule_format]

  let ?d = "(λx. ball x (if x=a then da else if x=b then db else d x))"
  show "?P e"
    apply (rule_tac x="?d" in exI)
  proof (safe, goal_cases)
    case 1
    show ?case
      apply (rule gauge_ball_dependent)
      using ab db(1) da(1) d(1)
      apply auto
      done
  next
    case as: (2 p)
    let ?A = "{t. fst t ∈ {a, b}}"
    note p = tagged_division_ofD[OF as(1)]
    have pA: "p = (p ∩ ?A) ∪ (p - ?A)" "finite (p ∩ ?A)" "finite (p - ?A)" "(p ∩ ?A) ∩ (p - ?A) = {}"
      using as by auto
    note * = additive_tagged_division_1'[OF assms(1) as(1), symmetric]
    have **: "⋀n1 s1 n2 s2::real. n2 ≤ s2 / 2 ⟹ n1 - s1 ≤ s2 / 2 ⟹ n1 + n2 ≤ s1 + s2"
      by arith
    show ?case
      unfolding content_real[OF assms(1)] and *[of "λx. x"] *[of f] setsum_subtractf[symmetric] split_minus
      unfolding setsum_right_distrib
      apply (subst(2) pA)
      apply (subst pA)
      unfolding setsum.union_disjoint[OF pA(2-)]
    proof (rule norm_triangle_le, rule **, goal_cases)
      case 1
      show ?case
        apply (rule order_trans)
        apply (rule setsum_norm_le)
        defer
        apply (subst setsum_divide_distrib)
        apply (rule order_refl)
        apply safe
        apply (unfold not_le o_def split_conv fst_conv)
      proof (rule ccontr)
        fix x k
        assume xk: "(x, k) ∈ p"
          "e * (Sup k -  Inf k) / 2 <
            norm (content k *R f' x - (f (Sup k) - f (Inf k)))"
        from p(4)[OF this(1)] guess u v by (elim exE) note k=this
        then have "u ≤ v" and uv: "{u, v} ⊆ cbox u v"
          using p(2)[OF xk(1)] by auto
        note result = xk(2)[unfolded k box_real interval_bounds_real[OF this(1)] content_real[OF this(1)]]

        assume as': "x ≠ a" "x ≠ b"
        then have "x ∈ box a b"
          using p(2-3)[OF xk(1)] by (auto simp: mem_box)
        note  * = d(2)[OF this]
        have "norm ((v - u) *R f' (x) - (f (v) - f (u))) =
          norm ((f (u) - f (x) - (u - x) *R f' (x)) - (f (v) - f (x) - (v - x) *R f' (x)))"
          apply (rule arg_cong[of _ _ norm])
          unfolding scaleR_left.diff
          apply auto
          done
        also have "… ≤ e / 2 * norm (u - x) + e / 2 * norm (v - x)"
          apply (rule norm_triangle_le_sub)
          apply (rule add_mono)
          apply (rule_tac[!] *)
          using fineD[OF as(2) xk(1)] as'
          unfolding k subset_eq
          apply -
          apply (erule_tac x=u in ballE)
          apply (erule_tac[3] x=v in ballE)
          using uv
          apply (auto simp:dist_real_def)
          done
        also have "… ≤ e / 2 * norm (v - u)"
          using p(2)[OF xk(1)]
          unfolding k
          by (auto simp add: field_simps)
        finally have "e * (v - u) / 2 < e * (v - u) / 2"
          apply -
          apply (rule less_le_trans[OF result])
          using uv
          apply auto
          done
        then show False by auto
      qed
    next
      have *: "⋀x s1 s2::real. 0 ≤ s1 ⟹ x ≤ (s1 + s2) / 2 ⟹ x - s1 ≤ s2 / 2"
        by auto
      case 2
      show ?case
        apply (rule *)
        apply (rule setsum_nonneg)
        apply rule
        apply (unfold split_paired_all split_conv)
        defer
        unfolding setsum.union_disjoint[OF pA(2-),symmetric] pA(1)[symmetric]
        unfolding setsum_right_distrib[symmetric]
        apply (subst additive_tagged_division_1[OF _ as(1)])
        apply (rule assms)
      proof -
        fix x k
        assume "(x, k) ∈ p ∩ {t. fst t ∈ {a, b}}"
        note xk=IntD1[OF this]
        from p(4)[OF this] guess u v by (elim exE) note uv=this
        with p(2)[OF xk] have "cbox u v ≠ {}"
          by auto
        then show "0 ≤ e * ((Sup k) - (Inf k))"
          unfolding uv using e by (auto simp add: field_simps)
      next
        have *: "⋀s f t e. setsum f s = setsum f t ⟹ norm (setsum f t) ≤ e ⟹ norm (setsum f s) ≤ e"
          by auto
        show "norm (∑(x, k)∈p ∩ ?A. content k *R f' x -
          (f ((Sup k)) - f ((Inf k)))) ≤ e * (b - a) / 2"
          apply (rule *[where t1="p ∩ {t. fst t ∈ {a, b} ∧ content(snd t) ≠ 0}"])
          apply (rule setsum.mono_neutral_right[OF pA(2)])
          defer
          apply rule
          unfolding split_paired_all split_conv o_def
        proof goal_cases
          fix x k
          assume "(x, k) ∈ p ∩ {t. fst t ∈ {a, b}} - p ∩ {t. fst t ∈ {a, b} ∧ content (snd t) ≠ 0}"
          then have xk: "(x, k) ∈ p" "content k = 0"
            by auto
          from p(4)[OF xk(1)] guess u v by (elim exE) note uv=this
          have "k ≠ {}"
            using p(2)[OF xk(1)] by auto
          then have *: "u = v"
            using xk
            unfolding uv content_eq_0 box_eq_empty
            by auto
          then show "content k *R (f' (x)) - (f ((Sup k)) - f ((Inf k))) = 0"
            using xk unfolding uv by auto
        next
          have *: "p ∩ {t. fst t ∈ {a, b} ∧ content(snd t) ≠ 0} =
            {t. t∈p ∧ fst t = a ∧ content(snd t) ≠ 0} ∪ {t. t∈p ∧ fst t = b ∧ content(snd t) ≠ 0}"
            by blast
          have **: "norm (setsum f s) ≤ e"
            if "∀x y. x ∈ s ∧ y ∈ s ⟶ x = y"
            and "∀x. x ∈ s ⟶ norm (f x) ≤ e"
            and "e > 0"
            for s f and e :: real
          proof (cases "s = {}")
            case True
            with that show ?thesis by auto
          next
            case False
            then obtain x where "x ∈ s"
              by auto
            then have *: "s = {x}"
              using that(1) by auto
            then show ?thesis
              using ‹x ∈ s› that(2) by auto
          qed
          case 2
          show ?case
            apply (subst *)
            apply (subst setsum.union_disjoint)
            prefer 4
            apply (rule order_trans[of _ "e * (b - a)/4 + e * (b - a)/4"])
            apply (rule norm_triangle_le,rule add_mono)
            apply (rule_tac[1-2] **)
          proof -
            let ?B = "λx. {t ∈ p. fst t = x ∧ content (snd t) ≠ 0}"
            have pa: "∃v. k = cbox a v ∧ a ≤ v" if "(a, k) ∈ p" for k
            proof -
              guess u v using p(4)[OF that] by (elim exE) note uv=this
              have *: "u ≤ v"
                using p(2)[OF that] unfolding uv by auto
              have u: "u = a"
              proof (rule ccontr)
                have "u ∈ cbox u v"
                  using p(2-3)[OF that(1)] unfolding uv by auto
                have "u ≥ a"
                  using p(2-3)[OF that(1)] unfolding uv subset_eq by auto
                moreover assume "¬ ?thesis"
                ultimately have "u > a" by auto
                then show False
                  using p(2)[OF that(1)] unfolding uv by (auto simp add:)
              qed
              then show ?thesis
                apply (rule_tac x=v in exI)
                unfolding uv
                using *
                apply auto
                done
            qed
            have pb: "∃v. k = cbox v b ∧ b ≥ v" if "(b, k) ∈ p" for k
            proof -
              guess u v using p(4)[OF that] by (elim exE) note uv=this
              have *: "u ≤ v"
                using p(2)[OF that] unfolding uv by auto
              have u: "v = b"
              proof (rule ccontr)
                have "u ∈ cbox u v"
                  using p(2-3)[OF that(1)] unfolding uv by auto
                have "v ≤ b"
                  using p(2-3)[OF that(1)] unfolding uv subset_eq by auto
                moreover assume "¬ ?thesis"
                ultimately have "v < b" by auto
                then show False
                  using p(2)[OF that(1)] unfolding uv by (auto simp add:)
              qed
              then show ?thesis
                apply (rule_tac x=u in exI)
                unfolding uv
                using *
                apply auto
                done
            qed
            show "∀x y. x ∈ ?B a ∧ y ∈ ?B a ⟶ x = y"
              apply (rule,rule,rule,unfold split_paired_all)
              unfolding mem_Collect_eq fst_conv snd_conv
              apply safe
            proof -
              fix x k k'
              assume k: "(a, k) ∈ p" "(a, k') ∈ p" "content k ≠ 0" "content k' ≠ 0"
              guess v using pa[OF k(1)] .. note v = conjunctD2[OF this]
              guess v' using pa[OF k(2)] .. note v' = conjunctD2[OF this] let ?v = "min v v'"
              have "box a ?v ⊆ k ∩ k'"
                unfolding v v' by (auto simp add: mem_box)
              note interior_mono[OF this,unfolded interior_Int]
              moreover have "(a + ?v)/2 ∈ box a ?v"
                using k(3-)
                unfolding v v' content_eq_0 not_le
                by (auto simp add: mem_box)
              ultimately have "(a + ?v)/2 ∈ interior k ∩ interior k'"
                unfolding interior_open[OF open_box] by auto
              then have *: "k = k'"
                apply -
                apply (rule ccontr)
                using p(5)[OF k(1-2)]
                apply auto
                done
              { assume "x ∈ k" then show "x ∈ k'" unfolding * . }
              { assume "x ∈ k'" then show "x ∈ k" unfolding * . }
            qed
            show "∀x y. x ∈ ?B b ∧ y ∈ ?B b ⟶ x = y"
              apply rule
              apply rule
              apply rule
              apply (unfold split_paired_all)
              unfolding mem_Collect_eq fst_conv snd_conv
              apply safe
            proof -
              fix x k k'
              assume k: "(b, k) ∈ p" "(b, k') ∈ p" "content k ≠ 0" "content k' ≠ 0"
              guess v using pb[OF k(1)] .. note v = conjunctD2[OF this]
              guess v' using pb[OF k(2)] .. note v' = conjunctD2[OF this]
              let ?v = "max v v'"
              have "box ?v b ⊆ k ∩ k'"
                unfolding v v' by (auto simp: mem_box)
                note interior_mono[OF this,unfolded interior_Int]
              moreover have " ((b + ?v)/2) ∈ box ?v b"
                using k(3-) unfolding v v' content_eq_0 not_le by (auto simp: mem_box)
              ultimately have " ((b + ?v)/2) ∈ interior k ∩ interior k'"
                unfolding interior_open[OF open_box] by auto
              then have *: "k = k'"
                apply -
                apply (rule ccontr)
                using p(5)[OF k(1-2)]
                apply auto
                done
              { assume "x ∈ k" then show "x ∈ k'" unfolding * . }
              { assume "x ∈ k'" then show "x∈k" unfolding * . }
            qed

            let ?a = a and ?b = b (* a is something else while proofing the next theorem. *)
            show "∀x. x ∈ ?B a ⟶ norm ((λ(x, k). content k *R f' x - (f (Sup k) -
              f (Inf k))) x) ≤ e * (b - a) / 4"
              apply rule
              apply rule
              unfolding mem_Collect_eq
              unfolding split_paired_all fst_conv snd_conv
            proof (safe, goal_cases)
              case prems: 1
              guess v using pa[OF prems(1)] .. note v = conjunctD2[OF this]
              have "?a ∈ {?a..v}"
                using v(2) by auto
              then have "v ≤ ?b"
                using p(3)[OF prems(1)] unfolding subset_eq v by auto
              moreover have "{?a..v} ⊆ ball ?a da"
                using fineD[OF as(2) prems(1)]
                apply -
                apply (subst(asm) if_P)
                apply (rule refl)
                unfolding subset_eq
                apply safe
                apply (erule_tac x=" x" in ballE)
                apply (auto simp add:subset_eq dist_real_def v)
                done
              ultimately show ?case
                unfolding v interval_bounds_real[OF v(2)] box_real
                apply -
                apply(rule da(2)[of "v"])
                using prems fineD[OF as(2) prems(1)]
                unfolding v content_eq_0
                apply auto
                done
            qed
            show "∀x. x ∈ ?B b ⟶ norm ((λ(x, k). content k *R f' x -
              (f (Sup k) - f (Inf k))) x) ≤ e * (b - a) / 4"
              apply rule
              apply rule
              unfolding mem_Collect_eq
              unfolding split_paired_all fst_conv snd_conv
            proof (safe, goal_cases)
              case prems: 1
              guess v using pb[OF prems(1)] .. note v = conjunctD2[OF this]
              have "?b ∈ {v.. ?b}"
                using v(2) by auto
              then have "v ≥ ?a" using p(3)[OF prems(1)]
                unfolding subset_eq v by auto
              moreover have "{v..?b} ⊆ ball ?b db"
                using fineD[OF as(2) prems(1)]
                apply -
                apply (subst(asm) if_P, rule refl)
                unfolding subset_eq
                apply safe
                apply (erule_tac x=" x" in ballE)
                using ab
                apply (auto simp add:subset_eq v dist_real_def)
                done
              ultimately show ?case
                unfolding v
                unfolding interval_bounds_real[OF v(2)] box_real
                apply -
                apply(rule db(2)[of "v"])
                using prems fineD[OF as(2) prems(1)]
                unfolding v content_eq_0
                apply auto
                done
            qed
          qed (insert p(1) ab e, auto simp add: field_simps)
        qed auto
      qed
    qed
  qed
qed


subsection ‹Stronger form with finite number of exceptional points.›

lemma fundamental_theorem_of_calculus_interior_strong:
  fixes f :: "real ⇒ 'a::banach"
  assumes "finite s"
    and "a ≤ b"
    and "continuous_on {a .. b} f"
    and "∀x∈{a <..< b} - s. (f has_vector_derivative f'(x)) (at x)"
  shows "(f' has_integral (f b - f a)) {a .. b}"
  using assms
proof (induct "card s" arbitrary: s a b)
  case 0
  show ?case
    apply (rule fundamental_theorem_of_calculus_interior)
    using 0
    apply auto
    done
next
  case (Suc n)
  from this(2) guess c s'
    apply -
    apply (subst(asm) eq_commute)
    unfolding card_Suc_eq
    apply (subst(asm)(2) eq_commute)
    apply (elim exE conjE)
    done
  note cs = this[rule_format]
  show ?case
  proof (cases "c ∈ box a b")
    case False
    then show ?thesis
      apply -
      apply (rule Suc(1)[OF cs(3) _ Suc(4,5)])
      apply safe
      defer
      apply (rule Suc(6)[rule_format])
      using Suc(3)
      unfolding cs
      apply auto
      done
  next
    have *: "f b - f a = (f c - f a) + (f b - f c)"
      by auto
    case True
    then have "a ≤ c" "c ≤ b"
      by (auto simp: mem_box)
    then show ?thesis
      apply (subst *)
      apply (rule has_integral_combine)
      apply assumption+
      apply (rule_tac[!] Suc(1)[OF cs(3)])
      using Suc(3)
      unfolding cs
    proof -
      show "continuous_on {a .. c} f" "continuous_on {c .. b} f"
        apply (rule_tac[!] continuous_on_subset[OF Suc(5)])
        using True
        apply (auto simp: mem_box)
        done
      let ?P = "λi j. ∀x∈{i <..< j} - s'. (f has_vector_derivative f' x) (at x)"
      show "?P a c" "?P c b"
        apply safe
        apply (rule_tac[!] Suc(6)[rule_format])
        using True
        unfolding cs
        apply (auto simp: mem_box)
        done
    qed auto
  qed
qed

lemma fundamental_theorem_of_calculus_strong:
  fixes f :: "real ⇒ 'a::banach"
  assumes "finite s"
    and "a ≤ b"
    and "continuous_on {a .. b} f"
    and "∀x∈{a .. b} - s. (f has_vector_derivative f'(x)) (at x)"
  shows "(f' has_integral (f b - f a)) {a .. b}"
  apply (rule fundamental_theorem_of_calculus_interior_strong[OF assms(1-3), of f'])
  using assms(4)
  apply (auto simp: mem_box)
  done

lemma indefinite_integral_continuous_left:
  fixes f:: "real ⇒ 'a::banach"
  assumes "f integrable_on {a .. b}"
    and "a < c"
    and "c ≤ b"
    and "e > 0"
  obtains d where "d > 0"
    and "∀t. c - d < t ∧ t ≤ c ⟶ norm (integral {a .. c} f - integral {a .. t} f) < e"
proof -
  have "∃w>0. ∀t. c - w < t ∧ t < c ⟶ norm (f c) * norm(c - t) < e / 3"
  proof (cases "f c = 0")
    case False
    hence "0 < e / 3 / norm (f c)" using ‹e>0› by simp
    then show ?thesis
      apply -
      apply rule
      apply rule
      apply assumption
      apply safe
    proof -
      fix t
      assume as: "t < c" and "c - e / 3 / norm (f c) < t"
      then have "c - t < e / 3 / norm (f c)"
        by auto
      then have "norm (c - t) < e / 3 / norm (f c)"
        using as by auto
      then show "norm (f c) * norm (c - t) < e / 3"
        using False
        apply -
        apply (subst mult.commute)
        apply (subst pos_less_divide_eq[symmetric])
        apply auto
        done
    qed
  next
    case True
    show ?thesis
      apply (rule_tac x=1 in exI)
      unfolding True
      using ‹e > 0›
      apply auto
      done
  qed
  then guess w .. note w = conjunctD2[OF this,rule_format]

  have *: "e / 3 > 0"
    using assms by auto
  have "f integrable_on {a .. c}"
    apply (rule integrable_subinterval_real[OF assms(1)])
    using assms(2-3)
    apply auto
    done
  from integrable_integral[OF this,unfolded has_integral_real,rule_format,OF *] guess d1 ..
  note d1 = conjunctD2[OF this,rule_format]
  def d  "λx. ball x w ∩ d1 x"
  have "gauge d"
    unfolding d_def using w(1) d1 by auto
  note this[unfolded gauge_def,rule_format,of c]
  note conjunctD2[OF this]
  from this(2)[unfolded open_contains_ball,rule_format,OF this(1)] guess k ..
  note k=conjunctD2[OF this]

  let ?d = "min k (c - a) / 2"
  show ?thesis
    apply (rule that[of ?d])
    apply safe
  proof -
    show "?d > 0"
      using k(1) using assms(2) by auto
    fix t
    assume as: "c - ?d < t" "t ≤ c"
    let ?thesis = "norm (integral ({a .. c}) f - integral ({a .. t}) f) < e"
    {
      presume *: "t < c ⟹ ?thesis"
      show ?thesis
        apply (cases "t = c")
        defer
        apply (rule *)
        apply (subst less_le)
        using ‹e > 0› as(2)
        apply auto
        done
    }
    assume "t < c"

    have "f integrable_on {a .. t}"
      apply (rule integrable_subinterval_real[OF assms(1)])
      using assms(2-3) as(2)
      apply auto
      done
    from integrable_integral[OF this,unfolded has_integral_real,rule_format,OF *] guess d2 ..
    note d2 = conjunctD2[OF this,rule_format]
    def d3  "λx. if x ≤ t then d1 x ∩ d2 x else d1 x"
    have "gauge d3"
      using d2(1) d1(1) unfolding d3_def gauge_def by auto
    from fine_division_exists_real[OF this, of a t] guess p . note p=this
    note p'=tagged_division_ofD[OF this(1)]
    have pt: "∀(x,k)∈p. x ≤ t"
    proof (safe, goal_cases)
      case prems: 1
      from p'(2,3)[OF prems] show ?case
        by auto
    qed
    with p(2) have "d2 fine p"
      unfolding fine_def d3_def
      apply safe
      apply (erule_tac x="(a,b)" in ballE)+
      apply auto
      done
    note d2_fin = d2(2)[OF conjI[OF p(1) this]]

    have *: "{a .. c} ∩ {x. x ∙ 1 ≤ t} = {a .. t}" "{a .. c} ∩ {x. x ∙ 1 ≥ t} = {t .. c}"
      using assms(2-3) as by (auto simp add: field_simps)
    have "p ∪ {(c, {t .. c})} tagged_division_of {a .. c} ∧ d1 fine p ∪ {(c, {t .. c})}"
      apply rule
      apply (rule tagged_division_union_interval_real[of _ _ _ 1 "t"])
      unfolding *
      apply (rule p)
      apply (rule tagged_division_of_self_real)
      unfolding fine_def
      apply safe
    proof -
      fix x k y
      assume "(x,k) ∈ p" and "y ∈ k"
      then show "y ∈ d1 x"
        using p(2) pt
        unfolding fine_def d3_def
        apply -
        apply (erule_tac x="(x,k)" in ballE)+
        apply auto
        done
    next
      fix x assume "x ∈ {t..c}"
      then have "dist c x < k"
        unfolding dist_real_def
        using as(1)
        by (auto simp add: field_simps)
      then show "x ∈ d1 c"
        using k(2)
        unfolding d_def
        by auto
    qed (insert as(2), auto) note d1_fin = d1(2)[OF this]

    have *: "integral {a .. c} f - integral {a .. t} f = -(((c - t) *R f c + (∑(x, k)∈p. content k *R f x)) -
      integral {a .. c} f) + ((∑(x, k)∈p. content k *R f x) - integral {a .. t} f) + (c - t) *R f c"
      "e = (e/3 + e/3) + e/3"
      by auto
    have **: "(∑(x, k)∈p ∪ {(c, {t .. c})}. content k *R f x) =
      (c - t) *R f c + (∑(x, k)∈p. content k *R f x)"
    proof -
      have **: "⋀x F. F ∪ {x} = insert x F"
        by auto
      have "(c, cbox t c) ∉ p"
      proof (safe, goal_cases)
        case prems: 1
        from p'(2-3)[OF prems] have "c ∈ cbox a t"
          by auto
        then show False using ‹t < c›
          by auto
      qed
      then show ?thesis
        unfolding ** box_real
        apply -
        apply (subst setsum.insert)
        apply (rule p')
        unfolding split_conv
        defer
        apply (subst content_real)
        using as(2)
        apply auto
        done
    qed
    have ***: "c - w < t ∧ t < c"
    proof -
      have "c - k < t"
        using ‹k>0› as(1) by (auto simp add: field_simps)
      moreover have "k ≤ w"
        apply (rule ccontr)
        using k(2)
        unfolding subset_eq
        apply (erule_tac x="c + ((k + w)/2)" in ballE)
        unfolding d_def
        using ‹k > 0› ‹w > 0›
        apply (auto simp add: field_simps not_le not_less dist_real_def)
        done
      ultimately show ?thesis using ‹t < c›
        by (auto simp add: field_simps)
    qed
    show ?thesis
      unfolding *(1)
      apply (subst *(2))
      apply (rule norm_triangle_lt add_strict_mono)+
      unfolding norm_minus_cancel
      apply (rule d1_fin[unfolded **])
      apply (rule d2_fin)
      using w(2)[OF ***]
      unfolding norm_scaleR
      apply (auto simp add: field_simps)
      done
  qed
qed

lemma indefinite_integral_continuous_right:
  fixes f :: "real ⇒ 'a::banach"
  assumes "f integrable_on {a .. b}"
    and "a ≤ c"
    and "c < b"
    and "e > 0"
  obtains d where "0 < d"
    and "∀t. c ≤ t ∧ t < c + d ⟶ norm (integral {a .. c} f - integral {a .. t} f) < e"
proof -
  have *: "(λx. f (- x)) integrable_on {-b .. -a}" "- b < - c" "- c ≤ - a"
    using assms by auto
  from indefinite_integral_continuous_left[OF * ‹e>0›] guess d . note d = this
  let ?d = "min d (b - c)"
  show ?thesis
    apply (rule that[of "?d"])
    apply safe
  proof -
    show "0 < ?d"
      using d(1) assms(3) by auto
    fix t :: real
    assume as: "c ≤ t" "t < c + ?d"
    have *: "integral {a .. c} f = integral {a .. b} f - integral {c .. b} f"
      "integral {a .. t} f = integral {a .. b} f - integral {t .. b} f"
      unfolding algebra_simps
      apply (rule_tac[!] integral_combine)
      using assms as
      apply auto
      done
    have "(- c) - d < (- t) ∧ - t ≤ - c"
      using as by auto note d(2)[rule_format,OF this]
    then show "norm (integral {a .. c} f - integral {a .. t} f) < e"
      unfolding *
      unfolding integral_reflect
      apply (subst norm_minus_commute)
      apply (auto simp add: algebra_simps)
      done
  qed
qed

lemma indefinite_integral_continuous:
  fixes f :: "real ⇒ 'a::banach"
  assumes "f integrable_on {a .. b}"
  shows "continuous_on {a .. b} (λx. integral {a .. x} f)"
proof (unfold continuous_on_iff, safe)
  fix x e :: real
  assume as: "x ∈ {a .. b}" "e > 0"
  let ?thesis = "∃d>0. ∀x'∈{a .. b}. dist x' x < d ⟶ dist (integral {a .. x'} f) (integral {a .. x} f) < e"
  {
    presume *: "a < b ⟹ ?thesis"
    show ?thesis
      apply cases
      apply (rule *)
      apply assumption
    proof goal_cases
      case 1
      then have "cbox a b = {x}"
        using as(1)
        apply -
        apply (rule set_eqI)
        apply auto
        done
      then show ?case using ‹e > 0› by auto
    qed
  }
  assume "a < b"
  have "(x = a ∨ x = b) ∨ (a < x ∧ x < b)"
    using as(1) by auto
  then show ?thesis
    apply (elim disjE)
  proof -
    assume "x = a"
    have "a ≤ a" ..
    from indefinite_integral_continuous_right[OF assms(1) this ‹a<b› ‹e>0›] guess d . note d=this
    show ?thesis
      apply rule
      apply rule
      apply (rule d)
      apply safe
      apply (subst dist_commute)
      unfolding ‹x = a› dist_norm
      apply (rule d(2)[rule_format])
      apply auto
      done
  next
    assume "x = b"
    have "b ≤ b" ..
    from indefinite_integral_continuous_left[OF assms(1) ‹a<b› this ‹e>0›] guess d . note d=this
    show ?thesis
      apply rule
      apply rule
      apply (rule d)
      apply safe
      apply (subst dist_commute)
      unfolding ‹x = b› dist_norm
      apply (rule d(2)[rule_format])
      apply auto
      done
  next
    assume "a < x ∧ x < b"
    then have xl: "a < x" "x ≤ b" and xr: "a ≤ x" "x < b"
      by auto
    from indefinite_integral_continuous_left [OF assms(1) xl ‹e>0›] guess d1 . note d1=this
    from indefinite_integral_continuous_right[OF assms(1) xr ‹e>0›] guess d2 . note d2=this
    show ?thesis
      apply (rule_tac x="min d1 d2" in exI)
    proof safe
      show "0 < min d1 d2"
        using d1 d2 by auto
      fix y
      assume "y ∈ {a .. b}" and "dist y x < min d1 d2"
      then show "dist (integral {a .. y} f) (integral {a .. x} f) < e"
        apply (subst dist_commute)
        apply (cases "y < x")
        unfolding dist_norm
        apply (rule d1(2)[rule_format])
        defer
        apply (rule d2(2)[rule_format])
        unfolding not_less
        apply (auto simp add: field_simps)
        done
    qed
  qed
qed


subsection ‹This doesn't directly involve integration, but that gives an easy proof.›

lemma has_derivative_zero_unique_strong_interval:
  fixes f :: "real ⇒ 'a::banach"
  assumes "finite k"
    and "continuous_on {a .. b} f"
    and "f a = y"
    and "∀x∈({a .. b} - k). (f has_derivative (λh. 0)) (at x within {a .. b})" "x ∈ {a .. b}"
  shows "f x = y"
proof -
  have ab: "a ≤ b"
    using assms by auto
  have *: "a ≤ x"
    using assms(5) by auto
  have "((λx. 0::'a) has_integral f x - f a) {a .. x}"
    apply (rule fundamental_theorem_of_calculus_interior_strong[OF assms(1) *])
    apply (rule continuous_on_subset[OF assms(2)])
    defer
    apply safe
    unfolding has_vector_derivative_def
    apply (subst has_derivative_within_open[symmetric])
    apply assumption
    apply (rule open_greaterThanLessThan)
    apply (rule has_derivative_within_subset[where s="{a .. b}"])
    using assms(4) assms(5)
    apply (auto simp: mem_box)
    done
  note this[unfolded *]
  note has_integral_unique[OF has_integral_0 this]
  then show ?thesis
    unfolding assms by auto
qed


subsection ‹Generalize a bit to any convex set.›

lemma has_derivative_zero_unique_strong_convex:
  fixes f :: "'a::euclidean_space ⇒ 'b::banach"
  assumes "convex s"
    and "finite k"
    and "continuous_on s f"
    and "c ∈ s"
    and "f c = y"
    and "∀x∈(s - k). (f has_derivative (λh. 0)) (at x within s)"
    and "x ∈ s"
  shows "f x = y"
proof -
  {
    presume *: "x ≠ c ⟹ ?thesis"
    show ?thesis
      apply cases
      apply (rule *)
      apply assumption
      unfolding assms(5)[symmetric]
      apply auto
      done
  }
  assume "x ≠ c"
  note conv = assms(1)[unfolded convex_alt,rule_format]
  have as1: "continuous_on {0 ..1} (f ∘ (λt. (1 - t) *R c + t *R x))"
    apply (rule continuous_intros)+
    apply (rule continuous_on_subset[OF assms(3)])
    apply safe
    apply (rule conv)
    using assms(4,7)
    apply auto
    done
  have *: "t = xa" if "(1 - t) *R c + t *R x = (1 - xa) *R c + xa *R x" for t xa
  proof -
    from that have "(t - xa) *R x = (t - xa) *R c"
      unfolding scaleR_simps by (auto simp add: algebra_simps)
    then show ?thesis
      using ‹x ≠ c› by auto
  qed
  have as2: "finite {t. ((1 - t) *R c + t *R x) ∈ k}"
    using assms(2)
    apply (rule finite_surj[where f="λz. SOME t. (1-t) *R c + t *R x = z"])
    apply safe
    unfolding image_iff
    apply rule
    defer
    apply assumption
    apply (rule sym)
    apply (rule some_equality)
    defer
    apply (drule *)
    apply auto
    done
  have "(f ∘ (λt. (1 - t) *R c + t *R x)) 1 = y"
    apply (rule has_derivative_zero_unique_strong_interval[OF as2 as1, of ])
    unfolding o_def
    using assms(5)
    defer
    apply -
    apply rule
  proof -
    fix t
    assume as: "t ∈ {0 .. 1} - {t. (1 - t) *R c + t *R x ∈ k}"
    have *: "c - t *R c + t *R x ∈ s - k"
      apply safe
      apply (rule conv[unfolded scaleR_simps])
      using ‹x ∈ s› ‹c ∈ s› as
      by (auto simp add: algebra_simps)
    have "(f ∘ (λt. (1 - t) *R c + t *R x) has_derivative (λx. 0) ∘ (λz. (0 - z *R c) + z *R x))
      (at t within {0 .. 1})"
      apply (intro derivative_eq_intros)
      apply simp_all
      apply (simp add: field_simps)
      unfolding scaleR_simps
      apply (rule has_derivative_within_subset,rule assms(6)[rule_format])
      apply (rule *)
      apply safe
      apply (rule conv[unfolded scaleR_simps])
      using ‹x ∈ s› ‹c ∈ s›
      apply auto
      done
    then show "((λxa. f ((1 - xa) *R c + xa *R x)) has_derivative (λh. 0)) (at t within {0 .. 1})"
      unfolding o_def .
  qed auto
  then show ?thesis
    by auto
qed


text ‹Also to any open connected set with finite set of exceptions. Could
 generalize to locally convex set with limpt-free set of exceptions.›

lemma has_derivative_zero_unique_strong_connected:
  fixes f :: "'a::euclidean_space ⇒ 'b::banach"
  assumes "connected s"
    and "open s"
    and "finite k"
    and "continuous_on s f"
    and "c ∈ s"
    and "f c = y"
    and "∀x∈(s - k). (f has_derivative (λh. 0)) (at x within s)"
    and "x∈s"
  shows "f x = y"
proof -
  have "{x ∈ s. f x ∈ {y}} = {} ∨ {x ∈ s. f x ∈ {y}} = s"
    apply (rule assms(1)[unfolded connected_clopen,rule_format])
    apply rule
    defer
    apply (rule continuous_closedin_preimage[OF assms(4) closed_singleton])
    apply (rule open_openin_trans[OF assms(2)])
    unfolding open_contains_ball
  proof safe
    fix x
    assume "x ∈ s"
    from assms(2)[unfolded open_contains_ball,rule_format,OF this] guess e .. note e=conjunctD2[OF this]
    show "∃e>0. ball x e ⊆ {xa ∈ s. f xa ∈ {f x}}"
      apply rule
      apply rule
      apply (rule e)
    proof safe
      fix y
      assume y: "y ∈ ball x e"
      then show "y ∈ s"
        using e by auto
      show "f y = f x"
        apply (rule has_derivative_zero_unique_strong_convex[OF convex_ball])
        apply (rule assms)
        apply (rule continuous_on_subset)
        apply (rule assms)
        apply (rule e)+
        apply (subst centre_in_ball)
        apply (rule e)
        apply rule
        apply safe
        apply (rule has_derivative_within_subset)
        apply (rule assms(7)[rule_format])
        using y e
        apply auto
        done
    qed
  qed
  then show ?thesis
    using ‹x ∈ s› ‹f c = y› ‹c ∈ s› by auto
qed

lemma has_derivative_zero_connected_constant:
  fixes f :: "'a::euclidean_space ⇒ 'b::banach"
  assumes "connected s"
      and "open s"
      and "finite k"
      and "continuous_on s f"
      and "∀x∈(s - k). (f has_derivative (λh. 0)) (at x within s)"
    obtains c where "⋀x. x ∈ s ⟹ f(x) = c"
proof (cases "s = {}")
  case True
  then show ?thesis
by (metis empty_iff that)
next
  case False
  then obtain c where "c ∈ s"
    by (metis equals0I)
  then show ?thesis
    by (metis has_derivative_zero_unique_strong_connected assms that)
qed


subsection ‹Integrating characteristic function of an interval›

lemma has_integral_restrict_open_subinterval:
  fixes f :: "'a::euclidean_space ⇒ 'b::banach"
  assumes "(f has_integral i) (cbox c d)"
    and "cbox c d ⊆ cbox a b"
  shows "((λx. if x ∈ box c d then f x else 0) has_integral i) (cbox a b)"
proof -
  def g  "λx. if x ∈box c d then f x else 0"
  {
    presume *: "cbox c d ≠ {} ⟹ ?thesis"
    show ?thesis
      apply cases
      apply (rule *)
      apply assumption
    proof goal_cases
      case prems: 1
      then have *: "box c d = {}"
        by (metis bot.extremum_uniqueI box_subset_cbox)
      show ?thesis
        using assms(1)
        unfolding *
        using prems
        by auto
    qed
  }
  assume "cbox c d ≠ {}"
  from partial_division_extend_1[OF assms(2) this] guess p . note p=this
  note mon = monoidal_lifted[OF monoidal_monoid]
  note operat = operative_division[OF this operative_integral p(1), symmetric]
  let ?P = "(if g integrable_on cbox a b then Some (integral (cbox a b) g) else None) = Some i"
  {
    presume "?P"
    then have "g integrable_on cbox a b ∧ integral (cbox a b) g = i"
      apply -
      apply cases
      apply (subst(asm) if_P)
      apply assumption
      apply auto
      done
    then show ?thesis
      using integrable_integral
      unfolding g_def
      by auto
  }

  note iterate_eq_neutral[OF mon,unfolded neutral_lifted[OF monoidal_monoid]]
  note * = this[unfolded neutral_add]
  have iterate:"iterate (lifted op +) (p - {cbox c d})
    (λi. if g integrable_on i then Some (integral i g) else None) = Some 0"
  proof (rule *)
    fix x
    assume x: "x ∈ p - {cbox c d}"
    then have "x ∈ p"
      by auto
    note div = division_ofD(2-5)[OF p(1) this]
    from div(3) guess u v by (elim exE) note uv=this
    have "interior x ∩ interior (cbox c d) = {}"
      using div(4)[OF p(2)] x by auto
    then have "(g has_integral 0) x"
      unfolding uv
      apply -
      apply (rule has_integral_spike_interior[where f="λx. 0"])
      unfolding g_def interior_cbox
      apply auto
      done
    then show "(if g integrable_on x then Some (integral x g) else None) = Some 0"
      by auto
  qed

  have *: "p = insert (cbox c d) (p - {cbox c d})"
    using p by auto
  have **: "g integrable_on cbox c d"
    apply (rule integrable_spike_interior[where f=f])
    unfolding g_def  using assms(1)
    apply auto
    done
  moreover
  have "integral (cbox c d) g = i"
    apply (rule has_integral_unique[OF _ assms(1)])
    apply (rule has_integral_spike_interior[where f=g])
    defer
    apply (rule integrable_integral[OF **])
    unfolding g_def
    apply auto
    done
  ultimately show ?P
    unfolding operat
    apply (subst *)
    apply (subst iterate_insert)
    apply rule+
    unfolding iterate
    defer
    apply (subst if_not_P)
    defer
    using p
    apply auto
    done
qed

lemma has_integral_restrict_closed_subinterval:
  fixes f :: "'a::euclidean_space ⇒ 'b::banach"
  assumes "(f has_integral i) (cbox c d)"
    and "cbox c d ⊆ cbox a b"
  shows "((λx. if x ∈ cbox c d then f x else 0) has_integral i) (cbox a b)"
proof -
  note has_integral_restrict_open_subinterval[OF assms]
  note * = has_integral_spike[OF negligible_frontier_interval _ this]
  show ?thesis
    apply (rule *[of c d])
    using box_subset_cbox[of c d]
    apply auto
    done
qed

lemma has_integral_restrict_closed_subintervals_eq:
  fixes f :: "'a::euclidean_space ⇒ 'b::banach"
  assumes "cbox c d ⊆ cbox a b"
  shows "((λx. if x ∈ cbox c d then f x else 0) has_integral i) (cbox a b) ⟷ (f has_integral i) (cbox c d)"
  (is "?l = ?r")
proof (cases "cbox c d = {}")
  case False
  let ?g = "λx. if x ∈ cbox c d then f x else 0"
  show ?thesis
    apply rule
    defer
    apply (rule has_integral_restrict_closed_subinterval[OF _ assms])
    apply assumption
  proof -
    assume ?l
    then have "?g integrable_on cbox c d"
      using assms has_integral_integrable integrable_subinterval by blast
    then have *: "f integrable_on cbox c d"
      apply -
      apply (rule integrable_eq)
      apply auto
      done
    then have "i = integral (cbox c d) f"
      apply -
      apply (rule has_integral_unique)
      apply (rule ‹?l›)
      apply (rule has_integral_restrict_closed_subinterval[OF _ assms])
      apply auto
      done
    then show ?r
      using * by auto
  qed
qed auto


text ‹Hence we can apply the limit process uniformly to all integrals.›

lemma has_integral':
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  shows "(f has_integral i) s ⟷
    (∀e>0. ∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ s then f(x) else 0) has_integral z) (cbox a b) ∧ norm(z - i) < e))"
  (is "?l ⟷ (∀e>0. ?r e)")
proof -
  {
    presume *: "∃a b. s = cbox a b ⟹ ?thesis"
    show ?thesis
      apply cases
      apply (rule *)
      apply assumption
      apply (subst has_integral_alt)
      apply auto
      done
  }
  assume "∃a b. s = cbox a b"
  then guess a b by (elim exE) note s=this
  from bounded_cbox[of a b, unfolded bounded_pos] guess B ..
  note B = conjunctD2[OF this,rule_format] show ?thesis
    apply safe
  proof -
    fix e :: real
    assume ?l and "e > 0"
    show "?r e"
      apply (rule_tac x="B+1" in exI)
      apply safe
      defer
      apply (rule_tac x=i in exI)
    proof
      fix c d :: 'n
      assume as: "ball 0 (B+1) ⊆ cbox c d"
      then show "((λx. if x ∈ s then f x else 0) has_integral i) (cbox c d)"
        unfolding s
        apply -
        apply (rule has_integral_restrict_closed_subinterval)
        apply (rule ‹?l›[unfolded s])
        apply safe
        apply (drule B(2)[rule_format])
        unfolding subset_eq
        apply (erule_tac x=x in ballE)
        apply (auto simp add: dist_norm)
        done
    qed (insert B ‹e>0›, auto)
  next
    assume as: "∀e>0. ?r e"
    from this[rule_format,OF zero_less_one] guess C .. note C=conjunctD2[OF this,rule_format]
    def c  "(∑i∈Basis. (- max B C) *R i)::'n"
    def d  "(∑i∈Basis. max B C *R i)::'n"
    have c_d: "cbox a b ⊆ cbox c d"
      apply safe
      apply (drule B(2))
      unfolding mem_box
    proof
      fix x i
      show "c ∙ i ≤ x ∙ i ∧ x ∙ i ≤ d ∙ i" if "norm x ≤ B" and "i ∈ Basis"
        using that and Basis_le_norm[OF ‹i∈Basis›, of x]
        unfolding c_def d_def
        by (auto simp add: field_simps setsum_negf)
    qed
    have "ball 0 C ⊆ cbox c d"
      apply (rule subsetI)
      unfolding mem_box mem_ball dist_norm
    proof
      fix x i :: 'n
      assume x: "norm (0 - x) < C" and i: "i ∈ Basis"
      show "c ∙ i ≤ x ∙ i ∧ x ∙ i ≤ d ∙ i"
        using Basis_le_norm[OF i, of x] and x i
        unfolding c_def d_def
        by (auto simp: setsum_negf)
    qed
    from C(2)[OF this] have "∃y. (f has_integral y) (cbox a b)"
      unfolding has_integral_restrict_closed_subintervals_eq[OF c_d,symmetric]
      unfolding s
      by auto
    then guess y .. note y=this

    have "y = i"
    proof (rule ccontr)
      assume "¬ ?thesis"
      then have "0 < norm (y - i)"
        by auto
      from as[rule_format,OF this] guess C ..  note C=conjunctD2[OF this,rule_format]
      def c  "(∑i∈Basis. (- max B C) *R i)::'n"
      def d  "(∑i∈Basis. max B C *R i)::'n"
      have c_d: "cbox a b ⊆ cbox c d"
        apply safe
        apply (drule B(2))
        unfolding mem_box
      proof
        fix x i :: 'n
        assume "norm x ≤ B" and "i ∈ Basis"
        then show "c ∙ i ≤ x ∙ i ∧ x ∙ i ≤ d ∙ i"
          using Basis_le_norm[of i x]
          unfolding c_def d_def
          by (auto simp add: field_simps setsum_negf)
      qed
      have "ball 0 C ⊆ cbox c d"
        apply (rule subsetI)
        unfolding mem_box mem_ball dist_norm
      proof
        fix x i :: 'n
        assume "norm (0 - x) < C" and "i ∈ Basis"
        then show "c ∙ i ≤ x ∙ i ∧ x ∙ i ≤ d ∙ i"
          using Basis_le_norm[of i x]
          unfolding c_def d_def
          by (auto simp: setsum_negf)
      qed
      note C(2)[OF this] then guess z .. note z = conjunctD2[OF this, unfolded s]
      note this[unfolded has_integral_restrict_closed_subintervals_eq[OF c_d]]
      then have "z = y" and "norm (z - i) < norm (y - i)"
        apply -
        apply (rule has_integral_unique[OF _ y(1)])
        apply assumption
        apply assumption
        done
      then show False
        by auto
    qed
    then show ?l
      using y
      unfolding s
      by auto
  qed
qed

lemma has_integral_le:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "(f has_integral i) s"
    and "(g has_integral j) s"
    and "∀x∈s. f x ≤ g x"
  shows "i ≤ j"
  using has_integral_component_le[OF _ assms(1-2), of 1]
  using assms(3)
  by auto

lemma integral_le:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "f integrable_on s"
    and "g integrable_on s"
    and "∀x∈s. f x ≤ g x"
  shows "integral s f ≤ integral s g"
  by (rule has_integral_le[OF assms(1,2)[unfolded has_integral_integral] assms(3)])

lemma has_integral_nonneg:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "(f has_integral i) s"
    and "∀x∈s. 0 ≤ f x"
  shows "0 ≤ i"
  using has_integral_component_nonneg[of 1 f i s]
  unfolding o_def
  using assms
  by auto

lemma integral_nonneg:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "f integrable_on s"
    and "∀x∈s. 0 ≤ f x"
  shows "0 ≤ integral s f"
  by (rule has_integral_nonneg[OF assms(1)[unfolded has_integral_integral] assms(2)])


text ‹Hence a general restriction property.›

lemma has_integral_restrict[simp]:
  assumes "s ⊆ t"
  shows "((λx. if x ∈ s then f x else (0::'a::banach)) has_integral i) t ⟷ (f has_integral i) s"
proof -
  have *: "⋀x. (if x ∈ t then if x ∈ s then f x else 0 else 0) =  (if x∈s then f x else 0)"
    using assms by auto
  show ?thesis
    apply (subst(2) has_integral')
    apply (subst has_integral')
    unfolding *
    apply rule
    done
qed

lemma has_integral_restrict_univ:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  shows "((λx. if x ∈ s then f x else 0) has_integral i) UNIV ⟷ (f has_integral i) s"
  by auto

lemma has_integral_on_superset:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "∀x. x ∉ s ⟶ f x = 0"
    and "s ⊆ t"
    and "(f has_integral i) s"
  shows "(f has_integral i) t"
proof -
  have "(λx. if x ∈ s then f x else 0) = (λx. if x ∈ t then f x else 0)"
    apply rule
    using assms(1-2)
    apply auto
    done
  then show ?thesis
    using assms(3)
    apply (subst has_integral_restrict_univ[symmetric])
    apply (subst(asm) has_integral_restrict_univ[symmetric])
    apply auto
    done
qed

lemma integrable_on_superset:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "∀x. x ∉ s ⟶ f x = 0"
    and "s ⊆ t"
    and "f integrable_on s"
  shows "f integrable_on t"
  using assms
  unfolding integrable_on_def
  by (auto intro:has_integral_on_superset)

lemma integral_restrict_univ[intro]:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  shows "f integrable_on s ⟹ integral UNIV (λx. if x ∈ s then f x else 0) = integral s f"
  apply (rule integral_unique)
  unfolding has_integral_restrict_univ
  apply auto
  done

lemma integrable_restrict_univ:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  shows "(λx. if x ∈ s then f x else 0) integrable_on UNIV ⟷ f integrable_on s"
  unfolding integrable_on_def
  by auto

lemma negligible_on_intervals: "negligible s ⟷ (∀a b. negligible(s ∩ cbox a b))" (is "?l ⟷ ?r")
proof
  assume ?r
  show ?l
    unfolding negligible_def
  proof safe
    fix a b
    show "(indicator s has_integral 0) (cbox a b)"
      apply (rule has_integral_negligible[OF ‹?r›[rule_format,of a b]])
      unfolding indicator_def
      apply auto
      done
  qed
qed auto

lemma has_integral_spike_set_eq:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "negligible ((s - t) ∪ (t - s))"
  shows "(f has_integral y) s ⟷ (f has_integral y) t"
  unfolding has_integral_restrict_univ[symmetric,of f]
  apply (rule has_integral_spike_eq[OF assms])
  by (auto split: if_split_asm)

lemma has_integral_spike_set[dest]:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "negligible ((s - t) ∪ (t - s))"
    and "(f has_integral y) s"
  shows "(f has_integral y) t"
  using assms has_integral_spike_set_eq
  by auto

lemma integrable_spike_set[dest]:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "negligible ((s - t) ∪ (t - s))"
    and "f integrable_on s"
  shows "f integrable_on t"
  using assms(2)
  unfolding integrable_on_def
  unfolding has_integral_spike_set_eq[OF assms(1)] .

lemma integrable_spike_set_eq:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "negligible ((s - t) ∪ (t - s))"
  shows "f integrable_on s ⟷ f integrable_on t"
  apply rule
  apply (rule_tac[!] integrable_spike_set)
  using assms
  apply auto
  done

(*lemma integral_spike_set:
 "∀f:real^M->real^N g s t.
        negligible(s DIFF t ∪ t DIFF s)
        ⟶ integral s f = integral t f"
qed  REPEAT STRIP_TAC THEN REWRITE_TAC[integral] THEN
  AP_TERM_TAC THEN ABS_TAC THEN MATCH_MP_TAC HAS_INTEGRAL_SPIKE_SET_EQ THEN
  ASM_MESON_TAC[]);;

lemma has_integral_interior:
 "∀f:real^M->real^N y s.
        negligible(frontier s)
        ⟶ ((f has_integral y) (interior s) ⟷ (f has_integral y) s)"
qed  REPEAT STRIP_TAC THEN MATCH_MP_TAC HAS_INTEGRAL_SPIKE_SET_EQ THEN
  FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (REWRITE_RULE[IMP_CONJ]
    NEGLIGIBLE_SUBSET)) THEN
  REWRITE_TAC[frontier] THEN
  MP_TAC(ISPEC `s:real^M->bool` INTERIOR_SUBSET) THEN
  MP_TAC(ISPEC `s:real^M->bool` CLOSURE_SUBSET) THEN
  SET_TAC[]);;

lemma has_integral_closure:
 "∀f:real^M->real^N y s.
        negligible(frontier s)
        ⟶ ((f has_integral y) (closure s) ⟷ (f has_integral y) s)"
qed  REPEAT STRIP_TAC THEN MATCH_MP_TAC HAS_INTEGRAL_SPIKE_SET_EQ THEN
  FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (REWRITE_RULE[IMP_CONJ]
    NEGLIGIBLE_SUBSET)) THEN
  REWRITE_TAC[frontier] THEN
  MP_TAC(ISPEC `s:real^M->bool` INTERIOR_SUBSET) THEN
  MP_TAC(ISPEC `s:real^M->bool` CLOSURE_SUBSET) THEN
  SET_TAC[]);;*)


subsection ‹More lemmas that are useful later›

lemma has_integral_subset_component_le:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes k: "k ∈ Basis"
    and as: "s ⊆ t" "(f has_integral i) s" "(f has_integral j) t" "∀x∈t. 0 ≤ f(x)∙k"
  shows "i∙k ≤ j∙k"
proof -
  note has_integral_restrict_univ[symmetric, of f]
  note as(2-3)[unfolded this] note * = has_integral_component_le[OF k this]
  show ?thesis
    apply (rule *)
    using as(1,4)
    apply auto
    done
qed

lemma has_integral_subset_le:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "s ⊆ t"
    and "(f has_integral i) s"
    and "(f has_integral j) t"
    and "∀x∈t. 0 ≤ f x"
  shows "i ≤ j"
  using has_integral_subset_component_le[OF _ assms(1), of 1 f i j]
  using assms
  by auto

lemma integral_subset_component_le:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "k ∈ Basis"
    and "s ⊆ t"
    and "f integrable_on s"
    and "f integrable_on t"
    and "∀x ∈ t. 0 ≤ f x ∙ k"
  shows "(integral s f)∙k ≤ (integral t f)∙k"
  apply (rule has_integral_subset_component_le)
  using assms
  apply auto
  done

lemma integral_subset_le:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "s ⊆ t"
    and "f integrable_on s"
    and "f integrable_on t"
    and "∀x ∈ t. 0 ≤ f x"
  shows "integral s f ≤ integral t f"
  apply (rule has_integral_subset_le)
  using assms
  apply auto
  done

lemma has_integral_alt':
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  shows "(f has_integral i) s ⟷ (∀a b. (λx. if x ∈ s then f x else 0) integrable_on cbox a b) ∧
    (∀e>0. ∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      norm (integral (cbox a b) (λx. if x ∈ s then f x else 0) - i) < e)"
  (is "?l = ?r")
proof
  assume ?r
  show ?l
    apply (subst has_integral')
    apply safe
  proof goal_cases
    case (1 e)
    from ‹?r›[THEN conjunct2,rule_format,OF this] guess B .. note B=conjunctD2[OF this]
    show ?case
      apply rule
      apply rule
      apply (rule B)
      apply safe
      apply (rule_tac x="integral (cbox a b) (λx. if x ∈ s then f x else 0)" in exI)
      apply (drule B(2)[rule_format])
      using integrable_integral[OF ‹?r›[THEN conjunct1,rule_format]]
      apply auto
      done
  qed
next
  assume ?l note as = this[unfolded has_integral'[of f],rule_format]
  let ?f = "λx. if x ∈ s then f x else 0"
  show ?r
  proof safe
    fix a b :: 'n
    from as[OF zero_less_one] guess B .. note B=conjunctD2[OF this,rule_format]
    let ?a = "∑i∈Basis. min (a∙i) (-B) *R i::'n"
    let ?b = "∑i∈Basis. max (b∙i) B *R i::'n"
    show "?f integrable_on cbox a b"
    proof (rule integrable_subinterval[of _ ?a ?b])
      have "ball 0 B ⊆ cbox ?a ?b"
        apply (rule subsetI)
        unfolding mem_ball mem_box dist_norm
      proof (rule, goal_cases)
        case (1 x i)
        then show ?case using Basis_le_norm[of i x]
          by (auto simp add:field_simps)
      qed
      from B(2)[OF this] guess z .. note conjunct1[OF this]
      then show "?f integrable_on cbox ?a ?b"
        unfolding integrable_on_def by auto
      show "cbox a b ⊆ cbox ?a ?b"
        apply safe
        unfolding mem_box
        apply rule
        apply (erule_tac x=i in ballE)
        apply auto
        done
    qed

    fix e :: real
    assume "e > 0"
    from as[OF this] guess B .. note B=conjunctD2[OF this,rule_format]
    show "∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      norm (integral (cbox a b) (λx. if x ∈ s then f x else 0) - i) < e"
      apply rule
      apply rule
      apply (rule B)
      apply safe
    proof goal_cases
      case 1
      from B(2)[OF this] guess z .. note z=conjunctD2[OF this]
      from integral_unique[OF this(1)] show ?case
        using z(2) by auto
    qed
  qed
qed


subsection ‹Continuity of the integral (for a 1-dimensional interval).›

lemma integrable_alt:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  shows "f integrable_on s ⟷
    (∀a b. (λx. if x ∈ s then f x else 0) integrable_on cbox a b) ∧
    (∀e>0. ∃B>0. ∀a b c d. ball 0 B ⊆ cbox a b ∧ ball 0 B ⊆ cbox c d ⟶
    norm (integral (cbox a b) (λx. if x ∈ s then f x else 0) -
      integral (cbox c d)  (λx. if x ∈ s then f x else 0)) < e)"
  (is "?l = ?r")
proof
  assume ?l
  then guess y unfolding integrable_on_def .. note this[unfolded has_integral_alt'[of f]]
  note y=conjunctD2[OF this,rule_format]
  show ?r
    apply safe
    apply (rule y)
  proof goal_cases
    case (1 e)
    then have "e/2 > 0"
      by auto
    from y(2)[OF this] guess B .. note B=conjunctD2[OF this,rule_format]
    show ?case
      apply rule
      apply rule
      apply (rule B)
      apply safe
    proof goal_cases
      case prems: (1 a b c d)
      show ?case
        apply (rule norm_triangle_half_l)
        using B(2)[OF prems(1)] B(2)[OF prems(2)]
        apply auto
        done
    qed
  qed
next
  assume ?r
  note as = conjunctD2[OF this,rule_format]
  let ?cube = "λn. cbox (∑i∈Basis. - real n *R i::'n) (∑i∈Basis. real n *R i)"
  have "Cauchy (λn. integral (?cube n) (λx. if x ∈ s then f x else 0))"
  proof (unfold Cauchy_def, safe, goal_cases)
    case (1 e)
    from as(2)[OF this] guess B .. note B = conjunctD2[OF this,rule_format]
    from real_arch_simple[of B] guess N .. note N = this
    {
      fix n
      assume n: "n ≥ N"
      have "ball 0 B ⊆ ?cube n"
        apply (rule subsetI)
        unfolding mem_ball mem_box dist_norm
      proof (rule, goal_cases)
        case (1 x i)
        then show ?case
          using Basis_le_norm[of i x] ‹i∈Basis›
          using n N
          by (auto simp add: field_simps setsum_negf)
      qed
    }
    then show ?case
      apply -
      apply (rule_tac x=N in exI)
      apply safe
      unfolding dist_norm
      apply (rule B(2))
      apply auto
      done
  qed
  from this[unfolded convergent_eq_cauchy[symmetric]] guess i ..
  note i = this[THEN LIMSEQ_D]

  show ?l unfolding integrable_on_def has_integral_alt'[of f]
    apply (rule_tac x=i in exI)
    apply safe
    apply (rule as(1)[unfolded integrable_on_def])
  proof goal_cases
    case (1 e)
    then have *: "e/2 > 0" by auto
    from i[OF this] guess N .. note N =this[rule_format]
    from as(2)[OF *] guess B .. note B=conjunctD2[OF this,rule_format]
    let ?B = "max (real N) B"
    show ?case
      apply (rule_tac x="?B" in exI)
    proof safe
      show "0 < ?B"
        using B(1) by auto
      fix a b :: 'n
      assume ab: "ball 0 ?B ⊆ cbox a b"
      from real_arch_simple[of ?B] guess n .. note n=this
      show "norm (integral (cbox a b) (λx. if x ∈ s then f x else 0) - i) < e"
        apply (rule norm_triangle_half_l)
        apply (rule B(2))
        defer
        apply (subst norm_minus_commute)
        apply (rule N[of n])
      proof safe
        show "N ≤ n"
          using n by auto
        fix x :: 'n
        assume x: "x ∈ ball 0 B"
        then have "x ∈ ball 0 ?B"
          by auto
        then show "x ∈ cbox a b"
          using ab by blast
        show "x ∈ ?cube n"
          using x
          unfolding mem_box mem_ball dist_norm
          apply -
        proof (rule, goal_cases)
          case (1 i)
          then show ?case
            using Basis_le_norm[of i x] ‹i ∈ Basis›
            using n
            by (auto simp add: field_simps setsum_negf)
        qed
      qed
    qed
  qed
qed

lemma integrable_altD:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f integrable_on s"
  shows "⋀a b. (λx. if x ∈ s then f x else 0) integrable_on cbox a b"
    and "⋀e. e > 0 ⟹ ∃B>0. ∀a b c d. ball 0 B ⊆ cbox a b ∧ ball 0 B ⊆ cbox c d ⟶
      norm (integral (cbox a b) (λx. if x ∈ s then f x else 0) - integral (cbox c d)  (λx. if x ∈ s then f x else 0)) < e"
  using assms[unfolded integrable_alt[of f]] by auto

lemma integrable_on_subcbox:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f integrable_on s"
    and "cbox a b ⊆ s"
  shows "f integrable_on cbox a b"
  apply (rule integrable_eq)
  defer
  apply (rule integrable_altD(1)[OF assms(1)])
  using assms(2)
  apply auto
  done


subsection ‹A straddling criterion for integrability›

lemma integrable_straddle_interval:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "∀e>0. ∃g  h i j. (g has_integral i) (cbox a b) ∧ (h has_integral j) (cbox a b) ∧
    norm (i - j) < e ∧ (∀x∈cbox a b. (g x) ≤ f x ∧ f x ≤ h x)"
  shows "f integrable_on cbox a b"
proof (subst integrable_cauchy, safe, goal_cases)
  case (1 e)
  then have e: "e/3 > 0"
    by auto
  note assms[rule_format,OF this]
  then guess g h i j by (elim exE conjE) note obt = this
  from obt(1)[unfolded has_integral[of g], rule_format, OF e] guess d1 .. note d1=conjunctD2[OF this,rule_format]
  from obt(2)[unfolded has_integral[of h], rule_format, OF e] guess d2 .. note d2=conjunctD2[OF this,rule_format]
  show ?case
    apply (rule_tac x="λx. d1 x ∩ d2 x" in exI)
    apply (rule conjI gauge_inter d1 d2)+
    unfolding fine_inter
  proof (safe, goal_cases)
    have **: "⋀i j g1 g2 h1 h2 f1 f2. g1 - h2 ≤ f1 - f2 ⟹ f1 - f2 ≤ h1 - g2 ⟹
      ¦i - j¦ < e / 3 ⟹ ¦g2 - i¦ < e / 3 ⟹ ¦g1 - i¦ < e / 3 ⟹
      ¦h2 - j¦ < e / 3 ⟹ ¦h1 - j¦ < e / 3 ⟹ ¦f1 - f2¦ < e"
    using ‹e > 0› by arith
    case prems: (1 p1 p2)
    note tagged_division_ofD(2-4) note * = this[OF prems(1)] this[OF prems(4)]

    have "(∑(x, k)∈p1. content k *R f x) - (∑(x, k)∈p1. content k *R g x) ≥ 0"
      and "0 ≤ (∑(x, k)∈p2. content k *R h x) - (∑(x, k)∈p2. content k *R f x)"
      and "(∑(x, k)∈p2. content k *R f x) - (∑(x, k)∈p2. content k *R g x) ≥ 0"
      and "0 ≤ (∑(x, k)∈p1. content k *R h x) - (∑(x, k)∈p1. content k *R f x)"
      unfolding setsum_subtractf[symmetric]
      apply -
      apply (rule_tac[!] setsum_nonneg)
      apply safe
      unfolding real_scaleR_def right_diff_distrib[symmetric]
      apply (rule_tac[!] mult_nonneg_nonneg)
    proof -
      fix a b
      assume ab: "(a, b) ∈ p1"
      show "0 ≤ content b"
        using *(3)[OF ab]
        apply safe
        apply (rule content_pos_le)
        done
      then show "0 ≤ content b" .
      show "0 ≤ f a - g a" "0 ≤ h a - f a"
        using *(1-2)[OF ab]
        using obt(4)[rule_format,of a]
        by auto
    next
      fix a b
      assume ab: "(a, b) ∈ p2"
      show "0 ≤ content b"
        using *(6)[OF ab]
        apply safe
        apply (rule content_pos_le)
        done
      then show "0 ≤ content b" .
      show "0 ≤ f a - g a" and "0 ≤ h a - f a"
        using *(4-5)[OF ab] using obt(4)[rule_format,of a] by auto
    qed
    then show ?case
      apply -
      unfolding real_norm_def
      apply (rule **)
      defer
      defer
      unfolding real_norm_def[symmetric]
      apply (rule obt(3))
      apply (rule d1(2)[OF conjI[OF prems(4,5)]])
      apply (rule d1(2)[OF conjI[OF prems(1,2)]])
      apply (rule d2(2)[OF conjI[OF prems(4,6)]])
      apply (rule d2(2)[OF conjI[OF prems(1,3)]])
      apply auto
      done
  qed
qed

lemma integrable_straddle:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "∀e>0. ∃g h i j. (g has_integral i) s ∧ (h has_integral j) s ∧
    norm (i - j) < e ∧ (∀x∈s. g x ≤ f x ∧ f x ≤ h x)"
  shows "f integrable_on s"
proof -
  have "⋀a b. (λx. if x ∈ s then f x else 0) integrable_on cbox a b"
  proof (rule integrable_straddle_interval, safe, goal_cases)
    case (1 a b e)
    then have *: "e/4 > 0"
      by auto
    from assms[rule_format,OF this] guess g h i j by (elim exE conjE) note obt=this
    note obt(1)[unfolded has_integral_alt'[of g]]
    note conjunctD2[OF this, rule_format]
    note g = this(1) and this(2)[OF *]
    from this(2) guess B1 .. note B1 = conjunctD2[OF this,rule_format]
    note obt(2)[unfolded has_integral_alt'[of h]]
    note conjunctD2[OF this, rule_format]
    note h = this(1) and this(2)[OF *]
    from this(2) guess B2 .. note B2 = conjunctD2[OF this,rule_format]
    def c  "∑i∈Basis. min (a∙i) (- (max B1 B2)) *R i::'n"
    def d  "∑i∈Basis. max (b∙i) (max B1 B2) *R i::'n"
    have *: "ball 0 B1 ⊆ cbox c d" "ball 0 B2 ⊆ cbox c d"
      apply safe
      unfolding mem_ball mem_box dist_norm
      apply (rule_tac[!] ballI)
    proof goal_cases
      case (1 x i)
      then show ?case using Basis_le_norm[of i x]
        unfolding c_def d_def by auto
    next
      case (2 x i)
      then show ?case using Basis_le_norm[of i x]
        unfolding c_def d_def by auto
    qed
    have **: "⋀ch cg ag ah::real. norm (ah - ag) ≤ norm (ch - cg) ⟹ norm (cg - i) < e / 4 ⟹
      norm (ch - j) < e / 4 ⟹ norm (ag - ah) < e"
      using obt(3)
      unfolding real_norm_def
      by arith
    show ?case
      apply (rule_tac x="λx. if x ∈ s then g x else 0" in exI)
      apply (rule_tac x="λx. if x ∈ s then h x else 0" in exI)
      apply (rule_tac x="integral (cbox a b) (λx. if x ∈ s then g x else 0)" in exI)
      apply (rule_tac x="integral (cbox a b) (λx. if x ∈ s then h x else 0)" in exI)
      apply safe
      apply (rule_tac[1-2] integrable_integral,rule g)
      apply (rule h)
      apply (rule **[OF _ B1(2)[OF *(1)] B2(2)[OF *(2)]])
    proof -
      have *: "⋀x f g. (if x ∈ s then f x else 0) - (if x ∈ s then g x else 0) =
        (if x ∈ s then f x - g x else (0::real))"
        by auto
      note ** = abs_of_nonneg[OF integral_nonneg[OF integrable_diff, OF h g]]
      show "norm (integral (cbox a b) (λx. if x ∈ s then h x else 0) -
          integral (cbox a b) (λx. if x ∈ s then g x else 0)) ≤
        norm (integral (cbox c d) (λx. if x ∈ s then h x else 0) -
          integral (cbox c d) (λx. if x ∈ s then g x else 0))"
        unfolding integral_diff[OF h g,symmetric] real_norm_def
        apply (subst **)
        defer
        apply (subst **)
        defer
        apply (rule has_integral_subset_le)
        defer
        apply (rule integrable_integral integrable_diff h g)+
      proof safe
        fix x
        assume "x ∈ cbox a b"
        then show "x ∈ cbox c d"
          unfolding mem_box c_def d_def
          apply -
          apply rule
          apply (erule_tac x=i in ballE)
          apply auto
          done
      qed (insert obt(4), auto)
    qed (insert obt(4), auto)
  qed
  note interv = this

  show ?thesis
    unfolding integrable_alt[of f]
    apply safe
    apply (rule interv)
  proof goal_cases
    case (1 e)
    then have *: "e/3 > 0"
      by auto
    from assms[rule_format,OF this] guess g h i j by (elim exE conjE) note obt=this
    note obt(1)[unfolded has_integral_alt'[of g]]
    note conjunctD2[OF this, rule_format]
    note g = this(1) and this(2)[OF *]
    from this(2) guess B1 .. note B1 = conjunctD2[OF this,rule_format]
    note obt(2)[unfolded has_integral_alt'[of h]]
    note conjunctD2[OF this, rule_format]
    note h = this(1) and this(2)[OF *]
    from this(2) guess B2 .. note B2 = conjunctD2[OF this,rule_format]
    show ?case
      apply (rule_tac x="max B1 B2" in exI)
      apply safe
      apply (rule max.strict_coboundedI1)
      apply (rule B1)
    proof -
      fix a b c d :: 'n
      assume as: "ball 0 (max B1 B2) ⊆ cbox a b" "ball 0 (max B1 B2) ⊆ cbox c d"
      have **: "ball 0 B1 ⊆ ball (0::'n) (max B1 B2)" "ball 0 B2 ⊆ ball (0::'n) (max B1 B2)"
        by auto
      have *: "⋀ga gc ha hc fa fc::real.
        ¦ga - i¦ < e / 3 ∧ ¦gc - i¦ < e / 3 ∧ ¦ha - j¦ < e / 3 ∧
        ¦hc - j¦ < e / 3 ∧ ¦i - j¦ < e / 3 ∧ ga ≤ fa ∧ fa ≤ ha ∧ gc ≤ fc ∧ fc ≤ hc ⟹
        ¦fa - fc¦ < e"
        by (simp add: abs_real_def split: if_split_asm)
      show "norm (integral (cbox a b) (λx. if x ∈ s then f x else 0) - integral (cbox c d)
        (λx. if x ∈ s then f x else 0)) < e"
        unfolding real_norm_def
        apply (rule *)
        apply safe
        unfolding real_norm_def[symmetric]
        apply (rule B1(2))
        apply (rule order_trans)
        apply (rule **)
        apply (rule as(1))
        apply (rule B1(2))
        apply (rule order_trans)
        apply (rule **)
        apply (rule as(2))
        apply (rule B2(2))
        apply (rule order_trans)
        apply (rule **)
        apply (rule as(1))
        apply (rule B2(2))
        apply (rule order_trans)
        apply (rule **)
        apply (rule as(2))
        apply (rule obt)
        apply (rule_tac[!] integral_le)
        using obt
        apply (auto intro!: h g interv)
        done
    qed
  qed
qed


subsection ‹Adding integrals over several sets›

lemma has_integral_union:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "(f has_integral i) s"
    and "(f has_integral j) t"
    and "negligible (s ∩ t)"
  shows "(f has_integral (i + j)) (s ∪ t)"
proof -
  note * = has_integral_restrict_univ[symmetric, of f]
  show ?thesis
    unfolding *
    apply (rule has_integral_spike[OF assms(3)])
    defer
    apply (rule has_integral_add[OF assms(1-2)[unfolded *]])
    apply auto
    done
qed

lemma has_integral_unions:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "finite t"
    and "∀s∈t. (f has_integral (i s)) s"
    and "∀s∈t. ∀s'∈t. s ≠ s' ⟶ negligible (s ∩ s')"
  shows "(f has_integral (setsum i t)) (⋃t)"
proof -
  note * = has_integral_restrict_univ[symmetric, of f]
  have **: "negligible (⋃((λ(a,b). a ∩ b) ` {(a,b). a ∈ t ∧ b ∈ {y. y ∈ t ∧ a ≠ y}}))"
    apply (rule negligible_unions)
    apply (rule finite_imageI)
    apply (rule finite_subset[of _ "t × t"])
    defer
    apply (rule finite_cartesian_product[OF assms(1,1)])
    using assms(3)
    apply auto
    done
  note assms(2)[unfolded *]
  note has_integral_setsum[OF assms(1) this]
  then show ?thesis
    unfolding *
    apply -
    apply (rule has_integral_spike[OF **])
    defer
    apply assumption
    apply safe
  proof goal_cases
    case prems: (1 x)
    then show ?case
    proof (cases "x ∈ ⋃t")
      case True
      then guess s unfolding Union_iff .. note s=this
      then have *: "∀b∈t. x ∈ b ⟷ b = s"
        using prems(3) by blast
      show ?thesis
        unfolding if_P[OF True]
        apply (rule trans)
        defer
        apply (rule setsum.cong)
        apply (rule refl)
        apply (subst *)
        apply assumption
        apply (rule refl)
        unfolding setsum.delta[OF assms(1)]
        using s
        apply auto
        done
    qed auto
  qed
qed


text ‹In particular adding integrals over a division, maybe not of an interval.›

lemma has_integral_combine_division:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "d division_of s"
    and "∀k∈d. (f has_integral (i k)) k"
  shows "(f has_integral (setsum i d)) s"
proof -
  note d = division_ofD[OF assms(1)]
  show ?thesis
    unfolding d(6)[symmetric]
    apply (rule has_integral_unions)
    apply (rule d assms)+
    apply rule
    apply rule
    apply rule
  proof goal_cases
    case prems: (1 s s')
    from d(4)[OF this(1)] d(4)[OF this(2)] guess a c b d by (elim exE) note obt=this
    from d(5)[OF prems] show ?case
      unfolding obt interior_cbox
      apply -
      apply (rule negligible_subset[of "(cbox a b-box a b) ∪ (cbox c d-box c d)"])
      apply (rule negligible_union negligible_frontier_interval)+
      apply auto
      done
  qed
qed

lemma integral_combine_division_bottomup:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "d division_of s"
    and "∀k∈d. f integrable_on k"
  shows "integral s f = setsum (λi. integral i f) d"
  apply (rule integral_unique)
  apply (rule has_integral_combine_division[OF assms(1)])
  using assms(2)
  unfolding has_integral_integral
  apply assumption
  done

lemma has_integral_combine_division_topdown:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f integrable_on s"
    and "d division_of k"
    and "k ⊆ s"
  shows "(f has_integral (setsum (λi. integral i f) d)) k"
  apply (rule has_integral_combine_division[OF assms(2)])
  apply safe
  unfolding has_integral_integral[symmetric]
proof goal_cases
  case (1 k)
  from division_ofD(2,4)[OF assms(2) this]
  show ?case
    apply safe
    apply (rule integrable_on_subcbox)
    apply (rule assms)
    using assms(3)
    apply auto
    done
qed

lemma integral_combine_division_topdown:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f integrable_on s"
    and "d division_of s"
  shows "integral s f = setsum (λi. integral i f) d"
  apply (rule integral_unique)
  apply (rule has_integral_combine_division_topdown)
  using assms
  apply auto
  done

lemma integrable_combine_division:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "d division_of s"
    and "∀i∈d. f integrable_on i"
  shows "f integrable_on s"
  using assms(2)
  unfolding integrable_on_def
  by (metis has_integral_combine_division[OF assms(1)])

lemma integrable_on_subdivision:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "d division_of i"
    and "f integrable_on s"
    and "i ⊆ s"
  shows "f integrable_on i"
  apply (rule integrable_combine_division assms)+
  apply safe
proof goal_cases
  case 1
  note division_ofD(2,4)[OF assms(1) this]
  then show ?case
    apply safe
    apply (rule integrable_on_subcbox[OF assms(2)])
    using assms(3)
    apply auto
    done
qed


subsection ‹Also tagged divisions›

lemma has_integral_combine_tagged_division:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "p tagged_division_of s"
    and "∀(x,k) ∈ p. (f has_integral (i k)) k"
  shows "(f has_integral (setsum (λ(x,k). i k) p)) s"
proof -
  have *: "(f has_integral (setsum (λk. integral k f) (snd ` p))) s"
    apply (rule has_integral_combine_division)
    apply (rule division_of_tagged_division[OF assms(1)])
    using assms(2)
    unfolding has_integral_integral[symmetric]
    apply safe
    apply auto
    done
  then show ?thesis
    apply -
    apply (rule subst[where P="λi. (f has_integral i) s"])
    defer
    apply assumption
    apply (rule trans[of _ "setsum (λ(x,k). integral k f) p"])
    apply (subst eq_commute)
    apply (rule setsum_over_tagged_division_lemma[OF assms(1)])
    apply (rule integral_null)
    apply assumption
    apply (rule setsum.cong)
    using assms(2)
    apply auto
    done
qed

lemma integral_combine_tagged_division_bottomup:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "p tagged_division_of (cbox a b)"
    and "∀(x,k)∈p. f integrable_on k"
  shows "integral (cbox a b) f = setsum (λ(x,k). integral k f) p"
  apply (rule integral_unique)
  apply (rule has_integral_combine_tagged_division[OF assms(1)])
  using assms(2)
  apply auto
  done

lemma has_integral_combine_tagged_division_topdown:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f integrable_on cbox a b"
    and "p tagged_division_of (cbox a b)"
  shows "(f has_integral (setsum (λ(x,k). integral k f) p)) (cbox a b)"
  apply (rule has_integral_combine_tagged_division[OF assms(2)])
  apply safe
proof goal_cases
  case 1
  note tagged_division_ofD(3-4)[OF assms(2) this]
  then show ?case
    using integrable_subinterval[OF assms(1)] by blast
qed

lemma integral_combine_tagged_division_topdown:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f integrable_on cbox a b"
    and "p tagged_division_of (cbox a b)"
  shows "integral (cbox a b) f = setsum (λ(x,k). integral k f) p"
  apply (rule integral_unique)
  apply (rule has_integral_combine_tagged_division_topdown)
  using assms
  apply auto
  done


subsection ‹Henstock's lemma›

lemma henstock_lemma_part1:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f integrable_on cbox a b"
    and "e > 0"
    and "gauge d"
    and "(∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
      norm (setsum (λ(x,k). content k *R f x) p - integral(cbox a b) f) < e)"
    and p: "p tagged_partial_division_of (cbox a b)" "d fine p"
  shows "norm (setsum (λ(x,k). content k *R f x - integral k f) p) ≤ e"
  (is "?x ≤ e")
proof -
  { presume "⋀k. 0<k ⟹ ?x ≤ e + k" then show ?thesis by (blast intro: field_le_epsilon) }
  fix k :: real
  assume k: "k > 0"
  note p' = tagged_partial_division_ofD[OF p(1)]
  have "⋃(snd ` p) ⊆ cbox a b"
    using p'(3) by fastforce
  note partial_division_of_tagged_division[OF p(1)] this
  from partial_division_extend_interval[OF this] guess q . note q=this and q' = division_ofD[OF this(2)]
  def r  "q - snd ` p"
  have "snd ` p ∩ r = {}"
    unfolding r_def by auto
  have r: "finite r"
    using q' unfolding r_def by auto

  have "∀i∈r. ∃p. p tagged_division_of i ∧ d fine p ∧
    norm (setsum (λ(x,j). content j *R f x) p - integral i f) < k / (real (card r) + 1)"
    apply safe
  proof goal_cases
    case (1 i)
    then have i: "i ∈ q"
      unfolding r_def by auto
    from q'(4)[OF this] guess u v by (elim exE) note uv=this
    have *: "k / (real (card r) + 1) > 0" using k by simp
    have "f integrable_on cbox u v"
      apply (rule integrable_subinterval[OF assms(1)])
      using q'(2)[OF i]
      unfolding uv
      apply auto
      done
    note integrable_integral[OF this, unfolded has_integral[of f]]
    from this[rule_format,OF *] guess dd .. note dd=conjunctD2[OF this,rule_format]
    note gauge_inter[OF ‹gauge d› dd(1)]
    from fine_division_exists[OF this,of u v] guess qq .
    then show ?case
      apply (rule_tac x=qq in exI)
      using dd(2)[of qq]
      unfolding fine_inter uv
      apply auto
      done
  qed
  from bchoice[OF this] guess qq .. note qq=this[rule_format]

  let ?p = "p ∪ ⋃(qq ` r)"
  have "norm ((∑(x, k)∈?p. content k *R f x) - integral (cbox a b) f) < e"
    apply (rule assms(4)[rule_format])
  proof
    show "d fine ?p"
      apply (rule fine_union)
      apply (rule p)
      apply (rule fine_unions)
      using qq
      apply auto
      done
    note * = tagged_partial_division_of_union_self[OF p(1)]
    have "p ∪ ⋃(qq ` r) tagged_division_of ⋃(snd ` p) ∪ ⋃r"
      using r
    proof (rule tagged_division_union[OF * tagged_division_unions], goal_cases)
      case 1
      then show ?case
        using qq by auto
    next
      case 2
      then show ?case
        apply rule
        apply rule
        apply rule
        apply(rule q'(5))
        unfolding r_def
        apply auto
        done
    next
      case 3
      then show ?case
        apply (rule inter_interior_unions_intervals)
        apply fact
        apply rule
        apply rule
        apply (rule q')
        defer
        apply rule
        apply (subst Int_commute)
        apply (rule inter_interior_unions_intervals)
        apply (rule finite_imageI)
        apply (rule p')
        apply rule
        defer
        apply rule
        apply (rule q')
        using q(1) p'
        unfolding r_def
        apply auto
        done
    qed
    moreover have "⋃(snd ` p) ∪ ⋃r = cbox a b" and "{qq i |i. i ∈ r} = qq ` r"
      unfolding Union_Un_distrib[symmetric] r_def
      using q
      by auto
    ultimately show "?p tagged_division_of (cbox a b)"
      by fastforce
  qed

  then have "norm ((∑(x, k)∈p. content k *R f x) + (∑(x, k)∈⋃(qq ` r). content k *R f x) -
    integral (cbox a b) f) < e"
    apply (subst setsum.union_inter_neutral[symmetric])
    apply (rule p')
    prefer 3
    apply assumption
    apply rule
    apply (rule r)
    apply safe
    apply (drule qq)
  proof -
    fix x l k
    assume as: "(x, l) ∈ p" "(x, l) ∈ qq k" "k ∈ r"
    note qq[OF this(3)]
    note tagged_division_ofD(3,4)[OF conjunct1[OF this] as(2)]
    from this(2) guess u v by (elim exE) note uv=this
    have "l∈snd ` p" unfolding image_iff apply(rule_tac x="(x,l)" in bexI) using as by auto
    then have "l ∈ q" "k ∈ q" "l ≠ k"
      using as(1,3) q(1) unfolding r_def by auto
    note q'(5)[OF this]
    then have "interior l = {}"
      using interior_mono[OF ‹l ⊆ k›] by blast
    then show "content l *R f x = 0"
      unfolding uv content_eq_0_interior[symmetric] by auto
  qed auto

  then have "norm ((∑(x, k)∈p. content k *R f x) + setsum (setsum (λ(x, k). content k *R f x))
    (qq ` r) - integral (cbox a b) f) < e"
    apply (subst (asm) setsum.Union_comp)
    prefer 2
    unfolding split_paired_all split_conv image_iff
    apply (erule bexE)+
  proof -
    fix x m k l T1 T2
    assume "(x, m) ∈ T1" "(x, m) ∈ T2" "T1 ≠ T2" "k ∈ r" "l ∈ r" "T1 = qq k" "T2 = qq l"
    note as = this(1-5)[unfolded this(6-)]
    note kl = tagged_division_ofD(3,4)[OF qq[THEN conjunct1]]
    from this(2)[OF as(4,1)] guess u v by (elim exE) note uv=this
    have *: "interior (k ∩ l) = {}"
      by (metis DiffE ‹T1 = qq k› ‹T1 ≠ T2› ‹T2 = qq l› as(4) as(5) interior_Int q'(5) r_def)
    have "interior m = {}"
      unfolding subset_empty[symmetric]
      unfolding *[symmetric]
      apply (rule interior_mono)
      using kl(1)[OF as(4,1)] kl(1)[OF as(5,2)]
      apply auto
      done
    then show "content m *R f x = 0"
      unfolding uv content_eq_0_interior[symmetric]
      by auto
  qed (insert qq, auto)

  then have **: "norm ((∑(x, k)∈p. content k *R f x) + setsum (setsum (λ(x, k). content k *R f x) ∘ qq) r -
    integral (cbox a b) f) < e"
    apply (subst (asm) setsum.reindex_nontrivial)
    apply fact
    apply (rule setsum.neutral)
    apply rule
    unfolding split_paired_all split_conv
    defer
    apply assumption
  proof -
    fix k l x m
    assume as: "k ∈ r" "l ∈ r" "k ≠ l" "qq k = qq l" "(x, m) ∈ qq k"
    note tagged_division_ofD(6)[OF qq[THEN conjunct1]]
    from this[OF as(1)] this[OF as(2)] show "content m *R f x = 0"
      using as(3) unfolding as by auto
  qed

  have *: "norm (cp - ip) ≤ e + k"
    if "norm ((cp + cr) - i) < e"
    and "norm (cr - ir) < k"
    and "ip + ir = i"
    for ir ip i cr cp
  proof -
    from that show ?thesis
      using norm_triangle_le[of "cp + cr - i" "- (cr - ir)"]
      unfolding that(3)[symmetric] norm_minus_cancel
      by (auto simp add: algebra_simps)
  qed

  have "?x =  norm ((∑(x, k)∈p. content k *R f x) - (∑(x, k)∈p. integral k f))"
    unfolding split_def setsum_subtractf ..
  also have "… ≤ e + k"
    apply (rule *[OF **, where ir1="setsum (λk. integral k f) r"])
  proof goal_cases
    case 1
    have *: "k * real (card r) / (1 + real (card r)) < k"
      using k by (auto simp add: field_simps)
    show ?case
      apply (rule le_less_trans[of _ "setsum (λx. k / (real (card r) + 1)) r"])
      unfolding setsum_subtractf[symmetric]
      apply (rule setsum_norm_le)
      apply rule
      apply (drule qq)
      defer
      unfolding divide_inverse setsum_left_distrib[symmetric]
      unfolding divide_inverse[symmetric]
      using * apply (auto simp add: field_simps)
      done
  next
    case 2
    have *: "(∑(x, k)∈p. integral k f) = (∑k∈snd ` p. integral k f)"
      apply (subst setsum.reindex_nontrivial)
      apply fact
      unfolding split_paired_all snd_conv split_def o_def
    proof -
      fix x l y m
      assume as: "(x, l) ∈ p" "(y, m) ∈ p" "(x, l) ≠ (y, m)" "l = m"
      from p'(4)[OF as(1)] guess u v by (elim exE) note uv=this
      show "integral l f = 0"
        unfolding uv
        apply (rule integral_unique)
        apply (rule has_integral_null)
        unfolding content_eq_0_interior
        using p'(5)[OF as(1-3)]
        unfolding uv as(4)[symmetric]
        apply auto
        done
    qed auto
    from q(1) have **: "snd ` p ∪ q = q" by auto
    show ?case
      unfolding integral_combine_division_topdown[OF assms(1) q(2)] * r_def
      using ** q'(1) p'(1) setsum.union_disjoint [of "snd ` p" "q - snd ` p" "λk. integral k f", symmetric]
        by simp
  qed
  finally show "?x ≤ e + k" .
qed

lemma henstock_lemma_part2:
  fixes f :: "'m::euclidean_space ⇒ 'n::euclidean_space"
  assumes "f integrable_on cbox a b"
    and "e > 0"
    and "gauge d"
    and "∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
      norm (setsum (λ(x,k). content k *R f x) p - integral (cbox a b) f) < e"
    and "p tagged_partial_division_of (cbox a b)"
    and "d fine p"
  shows "setsum (λ(x,k). norm (content k *R f x - integral k f)) p ≤ 2 * real (DIM('n)) * e"
  unfolding split_def
  apply (rule setsum_norm_allsubsets_bound)
  defer
  apply (rule henstock_lemma_part1[unfolded split_def,OF assms(1-3)])
  apply safe
  apply (rule assms[rule_format,unfolded split_def])
  defer
  apply (rule tagged_partial_division_subset)
  apply (rule assms)
  apply assumption
  apply (rule fine_subset)
  apply assumption
  apply (rule assms)
  using assms(5)
  apply auto
  done

lemma henstock_lemma:
  fixes f :: "'m::euclidean_space ⇒ 'n::euclidean_space"
  assumes "f integrable_on cbox a b"
    and "e > 0"
  obtains d where "gauge d"
    and "∀p. p tagged_partial_division_of (cbox a b) ∧ d fine p ⟶
      setsum (λ(x,k). norm(content k *R f x - integral k f)) p < e"
proof -
  have *: "e / (2 * (real DIM('n) + 1)) > 0" using assms(2) by simp
  from integrable_integral[OF assms(1),unfolded has_integral[of f],rule_format,OF this]
  guess d .. note d = conjunctD2[OF this]
  show thesis
    apply (rule that)
    apply (rule d)
  proof (safe, goal_cases)
    case (1 p)
    note * = henstock_lemma_part2[OF assms(1) * d this]
    show ?case
      apply (rule le_less_trans[OF *])
      using ‹e > 0›
      apply (auto simp add: field_simps)
      done
  qed
qed


subsection ‹Geometric progression›

text ‹FIXME: Should one or more of these theorems be moved to @{file
"~~/src/HOL/Set_Interval.thy"}, alongside ‹geometric_sum›?›

lemma sum_gp_basic:
  fixes x :: "'a::ring_1"
  shows "(1 - x) * setsum (λi. x^i) {0 .. n} = (1 - x^(Suc n))"
proof -
  def y  "1 - x"
  have "y * (∑i=0..n. (1 - y) ^ i) = 1 - (1 - y) ^ Suc n"
    by (induct n) (simp_all add: algebra_simps)
  then show ?thesis
    unfolding y_def by simp
qed

lemma sum_gp_multiplied:
  assumes mn: "m ≤ n"
  shows "((1::'a::{field}) - x) * setsum (op ^ x) {m..n} = x^m - x^ Suc n"
  (is "?lhs = ?rhs")
proof -
  let ?S = "{0..(n - m)}"
  from mn have mn': "n - m ≥ 0"
    by arith
  let ?f = "op + m"
  have i: "inj_on ?f ?S"
    unfolding inj_on_def by auto
  have f: "?f ` ?S = {m..n}"
    using mn
    apply (auto simp add: image_iff Bex_def)
    apply presburger
    done
  have th: "op ^ x ∘ op + m = (λi. x^m * x^i)"
    by (rule ext) (simp add: power_add power_mult)
  from setsum.reindex[OF i, of "op ^ x", unfolded f th setsum_right_distrib[symmetric]]
  have "?lhs = x^m * ((1 - x) * setsum (op ^ x) {0..n - m})"
    by simp
  then show ?thesis
    unfolding sum_gp_basic
    using mn
    by (simp add: field_simps power_add[symmetric])
qed

lemma sum_gp:
  "setsum (op ^ (x::'a::{field})) {m .. n} =
    (if n < m then 0
     else if x = 1 then of_nat ((n + 1) - m)
     else (x^ m - x^ (Suc n)) / (1 - x))"
proof -
  {
    assume nm: "n < m"
    then have ?thesis by simp
  }
  moreover
  {
    assume "¬ n < m"
    then have nm: "m ≤ n"
      by arith
    {
      assume x: "x = 1"
      then have ?thesis
        by simp
    }
    moreover
    {
      assume x: "x ≠ 1"
      then have nz: "1 - x ≠ 0"
        by simp
      from sum_gp_multiplied[OF nm, of x] nz have ?thesis
        by (simp add: field_simps)
    }
    ultimately have ?thesis by blast
  }
  ultimately show ?thesis by blast
qed

lemma sum_gp_offset:
  "setsum (op ^ (x::'a::{field})) {m .. m+n} =
    (if x = 1 then of_nat n + 1 else x^m * (1 - x^Suc n) / (1 - x))"
  unfolding sum_gp[of x m "m + n"] power_Suc
  by (simp add: field_simps power_add)


subsection ‹Monotone convergence (bounded interval first)›

lemma monotone_convergence_interval:
  fixes f :: "nat ⇒ 'n::euclidean_space ⇒ real"
  assumes "∀k. (f k) integrable_on cbox a b"
    and "∀k. ∀x∈cbox a b.(f k x) ≤ f (Suc k) x"
    and "∀x∈cbox a b. ((λk. f k x) ⤏ g x) sequentially"
    and "bounded {integral (cbox a b) (f k) | k . k ∈ UNIV}"
  shows "g integrable_on cbox a b ∧ ((λk. integral (cbox a b) (f k)) ⤏ integral (cbox a b) g) sequentially"
proof (cases "content (cbox a b) = 0")
  case True
  show ?thesis
    using integrable_on_null[OF True]
    unfolding integral_null[OF True]
    using tendsto_const
    by auto
next
  case False
  have fg: "∀x∈cbox a b. ∀k. (f k x) ∙ 1 ≤ (g x) ∙ 1"
  proof safe
    fix x k
    assume x: "x ∈ cbox a b"
    note * = Lim_component_ge[OF assms(3)[rule_format, OF x] trivial_limit_sequentially]
    show "f k x ∙ 1 ≤ g x ∙ 1"
      apply (rule *)
      unfolding eventually_sequentially
      apply (rule_tac x=k in exI)
      apply -
      apply (rule transitive_stepwise_le)
      using assms(2)[rule_format, OF x]
      apply auto
      done
  qed
  have "∃i. ((λk. integral (cbox a b) (f k)) ⤏ i) sequentially"
    apply (rule bounded_increasing_convergent)
    defer
    apply rule
    apply (rule integral_le)
    apply safe
    apply (rule assms(1-2)[rule_format])+
    using assms(4)
    apply auto
    done
  then guess i .. note i=this
  have i': "⋀k. (integral(cbox a b) (f k)) ≤ i∙1"
    apply (rule Lim_component_ge)
    apply (rule i)
    apply (rule trivial_limit_sequentially)
    unfolding eventually_sequentially
    apply (rule_tac x=k in exI)
    apply (rule transitive_stepwise_le)
    prefer 3
    unfolding inner_simps real_inner_1_right
    apply (rule integral_le)
    apply (rule assms(1-2)[rule_format])+
    using assms(2)
    apply auto
    done

  have "(g has_integral i) (cbox a b)"
    unfolding has_integral
  proof (safe, goal_cases)
    case e: (1 e)
    then have "∀k. (∃d. gauge d ∧ (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
      norm ((∑(x, ka)∈p. content ka *R f k x) - integral (cbox a b) (f k)) < e / 2 ^ (k + 2)))"
      apply -
      apply rule
      apply (rule assms(1)[unfolded has_integral_integral has_integral,rule_format])
      apply auto
      done
    from choice[OF this] guess c .. note c=conjunctD2[OF this[rule_format],rule_format]

    have "∃r. ∀k≥r. 0 ≤ i∙1 - (integral (cbox a b) (f k)) ∧ i∙1 - (integral (cbox a b) (f k)) < e / 4"
    proof -
      have "e/4 > 0"
        using e by auto
      from LIMSEQ_D [OF i this] guess r ..
      then show ?thesis
        apply (rule_tac x=r in exI)
        apply rule
        apply (erule_tac x=k in allE)
        subgoal for k using i'[of k] by auto
        done
    qed
    then guess r .. note r=conjunctD2[OF this[rule_format]]

    have "∀x∈cbox a b. ∃n≥r. ∀k≥n. 0 ≤ (g x)∙1 - (f k x)∙1 ∧
      (g x)∙1 - (f k x)∙1 < e / (4 * content(cbox a b))"
    proof (rule, goal_cases)
      case prems: (1 x)
      have "e / (4 * content (cbox a b)) > 0"
        using ‹e>0› False content_pos_le[of a b] by auto
      from assms(3)[rule_format, OF prems, THEN LIMSEQ_D, OF this]
      guess n .. note n=this
      then show ?case
        apply (rule_tac x="n + r" in exI)
        apply safe
        apply (erule_tac[2-3] x=k in allE)
        unfolding dist_real_def
        using fg[rule_format, OF prems]
        apply (auto simp add: field_simps)
        done
    qed
    from bchoice[OF this] guess m .. note m=conjunctD2[OF this[rule_format],rule_format]
    def d  "λx. c (m x) x"

    show ?case
      apply (rule_tac x=d in exI)
    proof safe
      show "gauge d"
        using c(1) unfolding gauge_def d_def by auto
    next
      fix p
      assume p: "p tagged_division_of (cbox a b)" "d fine p"
      note p'=tagged_division_ofD[OF p(1)]
      have "∃a. ∀x∈p. m (fst x) ≤ a"
        by (metis finite_imageI finite_nat_set_iff_bounded_le p'(1) rev_image_eqI)
      then guess s .. note s=this
      have *: "∀a b c d. norm(a - b) ≤ e / 4 ∧ norm(b - c) < e / 2 ∧
        norm (c - d) < e / 4 ⟶ norm (a - d) < e"
      proof (safe, goal_cases)
        case (1 a b c d)
        then show ?case
          using norm_triangle_lt[of "a - b" "b - c" "3* e/4"]
            norm_triangle_lt[of "a - b + (b - c)" "c - d" e]
          unfolding norm_minus_cancel
          by (auto simp add: algebra_simps)
      qed
      show "norm ((∑(x, k)∈p. content k *R g x) - i) < e"
        apply (rule *[rule_format,where
          b="∑(x, k)∈p. content k *R f (m x) x" and c="∑(x, k)∈p. integral k (f (m x))"])
      proof (safe, goal_cases)
        case 1
        show ?case
          apply (rule order_trans[of _ "∑(x, k)∈p. content k * (e / (4 * content (cbox a b)))"])
          unfolding setsum_subtractf[symmetric]
          apply (rule order_trans)
          apply (rule norm_setsum)
          apply (rule setsum_mono)
          unfolding split_paired_all split_conv
          unfolding split_def setsum_left_distrib[symmetric] scaleR_diff_right[symmetric]
          unfolding additive_content_tagged_division[OF p(1), unfolded split_def]
        proof -
          fix x k
          assume xk: "(x, k) ∈ p"
          then have x: "x ∈ cbox a b"
            using p'(2-3)[OF xk] by auto
          from p'(4)[OF xk] guess u v by (elim exE) note uv=this
          show "norm (content k *R (g x - f (m x) x)) ≤ content k * (e / (4 * content (cbox a b)))"
            unfolding norm_scaleR uv
            unfolding abs_of_nonneg[OF content_pos_le]
            apply (rule mult_left_mono)
            using m(2)[OF x,of "m x"]
            apply auto
            done
        qed (insert False, auto)

      next
        case 2
        show ?case
          apply (rule le_less_trans[of _ "norm (∑j = 0..s.
            ∑(x, k)∈{xk∈p. m (fst xk) = j}. content k *R f (m x) x - integral k (f (m x)))"])
          apply (subst setsum_group)
          apply fact
          apply (rule finite_atLeastAtMost)
          defer
          apply (subst split_def)+
          unfolding setsum_subtractf
          apply rule
        proof -
          show "norm (∑j = 0..s. ∑(x, k)∈{xk ∈ p.
            m (fst xk) = j}. content k *R f (m x) x - integral k (f (m x))) < e / 2"
            apply (rule le_less_trans[of _ "setsum (λi. e / 2^(i+2)) {0..s}"])
            apply (rule setsum_norm_le)
          proof
            show "(∑i = 0..s. e / 2 ^ (i + 2)) < e / 2"
              unfolding power_add divide_inverse inverse_mult_distrib
              unfolding setsum_right_distrib[symmetric] setsum_left_distrib[symmetric]
              unfolding power_inverse [symmetric] sum_gp
              apply(rule mult_strict_left_mono[OF _ e])
              unfolding power2_eq_square
              apply auto
              done
            fix t
            assume "t ∈ {0..s}"
            show "norm (∑(x, k)∈{xk ∈ p. m (fst xk) = t}. content k *R f (m x) x -
              integral k (f (m x))) ≤ e / 2 ^ (t + 2)"
              apply (rule order_trans
                [of _ "norm (setsum (λ(x,k). content k *R f t x - integral k (f t)) {xk ∈ p. m (fst xk) = t})"])
              apply (rule eq_refl)
              apply (rule arg_cong[where f=norm])
              apply (rule setsum.cong)
              apply (rule refl)
              defer
              apply (rule henstock_lemma_part1)
              apply (rule assms(1)[rule_format])
              apply (simp add: e)
              apply safe
              apply (rule c)+
              apply rule
              apply assumption+
              apply (rule tagged_partial_division_subset[of p])
              apply (rule p(1)[unfolded tagged_division_of_def,THEN conjunct1])
              defer
              unfolding fine_def
              apply safe
              apply (drule p(2)[unfolded fine_def,rule_format])
              unfolding d_def
              apply auto
              done
          qed
        qed (insert s, auto)
      next
        case 3
        note comb = integral_combine_tagged_division_topdown[OF assms(1)[rule_format] p(1)]
        have *: "⋀sr sx ss ks kr::real. kr = sr ⟶ ks = ss ⟶
          ks ≤ i ∧ sr ≤ sx ∧ sx ≤ ss ∧ 0 ≤ i∙1 - kr∙1 ∧ i∙1 - kr∙1 < e/4 ⟶ ¦sx - i¦ < e/4"
          by auto
        show ?case
          unfolding real_norm_def
          apply (rule *[rule_format])
          apply safe
          apply (rule comb[of r])
          apply (rule comb[of s])
          apply (rule i'[unfolded real_inner_1_right])
          apply (rule_tac[1-2] setsum_mono)
          unfolding split_paired_all split_conv
          apply (rule_tac[1-2] integral_le[OF ])
        proof safe
          show "0 ≤ i∙1 - (integral (cbox a b) (f r))∙1"
            using r(1) by auto
          show "i∙1 - (integral (cbox a b) (f r))∙1 < e / 4"
            using r(2) by auto
          fix x k
          assume xk: "(x, k) ∈ p"
          from p'(4)[OF this] guess u v by (elim exE) note uv=this
          show "f r integrable_on k"
            and "f s integrable_on k"
            and "f (m x) integrable_on k"
            and "f (m x) integrable_on k"
            unfolding uv
            apply (rule_tac[!] integrable_on_subcbox[OF assms(1)[rule_format]])
            using p'(3)[OF xk]
            unfolding uv
            apply auto
            done
          fix y
          assume "y ∈ k"
          then have "y ∈ cbox a b"
            using p'(3)[OF xk] by auto
          then have *: "⋀m. ∀n≥m. f m y ≤ f n y"
            apply -
            apply (rule transitive_stepwise_le)
            using assms(2)
            apply auto
            done
          show "f r y ≤ f (m x) y" and "f (m x) y ≤ f s y"
            apply (rule_tac[!] *[rule_format])
            using s[rule_format,OF xk] m(1)[of x] p'(2-3)[OF xk]
            apply auto
            done
        qed
      qed
    qed
  qed note * = this

  have "integral (cbox a b) g = i"
    by (rule integral_unique) (rule *)
  then show ?thesis
    using i * by auto
qed

lemma monotone_convergence_increasing:
  fixes f :: "nat ⇒ 'n::euclidean_space ⇒ real"
  assumes "∀k. (f k) integrable_on s"
    and "∀k. ∀x∈s. (f k x) ≤ (f (Suc k) x)"
    and "∀x∈s. ((λk. f k x) ⤏ g x) sequentially"
    and "bounded {integral s (f k)| k. True}"
  shows "g integrable_on s ∧ ((λk. integral s (f k)) ⤏ integral s g) sequentially"
proof -
  have lem: "g integrable_on s ∧ ((λk. integral s (f k)) ⤏ integral s g) sequentially"
    if "∀k. ∀x∈s. 0 ≤ f k x"
    and "∀k. (f k) integrable_on s"
    and "∀k. ∀x∈s. f k x ≤ f (Suc k) x"
    and "∀x∈s. ((λk. f k x) ⤏ g x) sequentially"
    and "bounded {integral s (f k)| k. True}"
    for f :: "nat ⇒ 'n::euclidean_space ⇒ real" and g s
  proof -
    note assms=that[rule_format]
    have "∀x∈s. ∀k. (f k x)∙1 ≤ (g x)∙1"
      apply safe
      apply (rule Lim_component_ge)
      apply (rule that(4)[rule_format])
      apply assumption
      apply (rule trivial_limit_sequentially)
      unfolding eventually_sequentially
      apply (rule_tac x=k in exI)
      apply (rule transitive_stepwise_le)
      using that(3)
      apply auto
      done
    note fg=this[rule_format]

    have "∃i. ((λk. integral s (f k)) ⤏ i) sequentially"
      apply (rule bounded_increasing_convergent)
      apply (rule that(5))
      apply rule
      apply (rule integral_le)
      apply (rule that(2)[rule_format])+
      using that(3)
      apply auto
      done
    then guess i .. note i=this
    have "⋀k. ∀x∈s. ∀n≥k. f k x ≤ f n x"
      apply rule
      apply (rule transitive_stepwise_le)
      using that(3)
      apply auto
      done
    then have i': "∀k. (integral s (f k))∙1 ≤ i∙1"
      apply -
      apply rule
      apply (rule Lim_component_ge)
      apply (rule i)
      apply (rule trivial_limit_sequentially)
      unfolding eventually_sequentially
      apply (rule_tac x=k in exI)
      apply safe
      apply (rule integral_component_le)
      apply simp
      apply (rule that(2)[rule_format])+
      apply auto
      done

    note int = assms(2)[unfolded integrable_alt[of _ s],THEN conjunct1,rule_format]
    have ifif: "⋀k t. (λx. if x ∈ t then if x ∈ s then f k x else 0 else 0) =
      (λx. if x ∈ t ∩ s then f k x else 0)"
      by (rule ext) auto
    have int': "⋀k a b. f k integrable_on cbox a b ∩ s"
      apply (subst integrable_restrict_univ[symmetric])
      apply (subst ifif[symmetric])
      apply (subst integrable_restrict_univ)
      apply (rule int)
      done
    have "⋀a b. (λx. if x ∈ s then g x else 0) integrable_on cbox a b ∧
      ((λk. integral (cbox a b) (λx. if x ∈ s then f k x else 0)) ⤏
      integral (cbox a b) (λx. if x ∈ s then g x else 0)) sequentially"
    proof (rule monotone_convergence_interval, safe, goal_cases)
      case 1
      show ?case by (rule int)
    next
      case (2 _ _ _ x)
      then show ?case
        apply (cases "x ∈ s")
        using assms(3)
        apply auto
        done
    next
      case (3 _ _ x)
      then show ?case
        apply (cases "x ∈ s")
        using assms(4)
        apply auto
        done
    next
      case (4 a b)
      note * = integral_nonneg
      have "⋀k. norm (integral (cbox a b) (λx. if x ∈ s then f k x else 0)) ≤ norm (integral s (f k))"
        unfolding real_norm_def
        apply (subst abs_of_nonneg)
        apply (rule *[OF int])
        apply safe
        apply (case_tac "x ∈ s")
        apply (drule assms(1))
        prefer 3
        apply (subst abs_of_nonneg)
        apply (rule *[OF assms(2) that(1)[THEN spec]])
        apply (subst integral_restrict_univ[symmetric,OF int])
        unfolding ifif
        unfolding integral_restrict_univ[OF int']
        apply (rule integral_subset_le[OF _ int' assms(2)])
        using assms(1)
        apply auto
        done
      then show ?case
        using assms(5)
        unfolding bounded_iff
        apply safe
        apply (rule_tac x=aa in exI)
        apply safe
        apply (erule_tac x="integral s (f k)" in ballE)
        apply (rule order_trans)
        apply assumption
        apply auto
        done
    qed
    note g = conjunctD2[OF this]

    have "(g has_integral i) s"
      unfolding has_integral_alt'
      apply safe
      apply (rule g(1))
    proof goal_cases
      case (1 e)
      then have "e/4>0"
        by auto
      from LIMSEQ_D [OF i this] guess N .. note N=this
      note assms(2)[of N,unfolded has_integral_integral has_integral_alt'[of "f N"]]
      from this[THEN conjunct2,rule_format,OF ‹e/4>0›] guess B .. note B=conjunctD2[OF this]
      show ?case
        apply rule
        apply rule
        apply (rule B)
        apply safe
      proof -
        fix a b :: 'n
        assume ab: "ball 0 B ⊆ cbox a b"
        from ‹e > 0› have "e/2 > 0"
          by auto
        from LIMSEQ_D [OF g(2)[of a b] this] guess M .. note M=this
        have **: "norm (integral (cbox a b) (λx. if x ∈ s then f N x else 0) - i) < e/2"
          apply (rule norm_triangle_half_l)
          using B(2)[rule_format,OF ab] N[rule_format,of N]
          apply -
          defer
          apply (subst norm_minus_commute)
          apply auto
          done
        have *: "⋀f1 f2 g. ¦f1 - i¦ < e / 2 ⟶ ¦f2 - g¦ < e / 2 ⟶
          f1 ≤ f2 ⟶ f2 ≤ i ⟶ ¦g - i¦ < e"
          unfolding real_inner_1_right by arith
        show "norm (integral (cbox a b) (λx. if x ∈ s then g x else 0) - i) < e"
          unfolding real_norm_def
          apply (rule *[rule_format])
          apply (rule **[unfolded real_norm_def])
          apply (rule M[rule_format,of "M + N",unfolded real_norm_def])
          apply (rule le_add1)
          apply (rule integral_le[OF int int])
          defer
          apply (rule order_trans[OF _ i'[rule_format,of "M + N",unfolded real_inner_1_right]])
        proof (safe, goal_cases)
          case (2 x)
          have "⋀m. x ∈ s ⟹ ∀n≥m. (f m x)∙1 ≤ (f n x)∙1"
            apply (rule transitive_stepwise_le)
            using assms(3)
            apply auto
            done
          then show ?case
            by auto
        next
          case 1
          show ?case
            apply (subst integral_restrict_univ[symmetric,OF int])
            unfolding ifif integral_restrict_univ[OF int']
            apply (rule integral_subset_le[OF _ int'])
            using assms
            apply auto
            done
        qed
      qed
    qed
    then show ?thesis
      apply safe
      defer
      apply (drule integral_unique)
      using i
      apply auto
      done
  qed

  have sub: "⋀k. integral s (λx. f k x - f 0 x) = integral s (f k) - integral s (f 0)"
    apply (subst integral_diff)
    apply (rule assms(1)[rule_format])+
    apply rule
    done
  have "⋀x m. x ∈ s ⟹ ∀n≥m. f m x ≤ f n x"
    apply (rule transitive_stepwise_le)
    using assms(2)
    apply auto
    done
  note * = this[rule_format]
  have "(λx. g x - f 0 x) integrable_on s ∧ ((λk. integral s (λx. f (Suc k) x - f 0 x)) ⤏
    integral s (λx. g x - f 0 x)) sequentially"
    apply (rule lem)
    apply safe
  proof goal_cases
    case (1 k x)
    then show ?case
      using *[of x 0 "Suc k"] by auto
  next
    case (2 k)
    then show ?case
      apply (rule integrable_diff)
      using assms(1)
      apply auto
      done
  next
    case (3 k x)
    then show ?case
      using *[of x "Suc k" "Suc (Suc k)"] by auto
  next
    case (4 x)
    then show ?case
      apply -
      apply (rule tendsto_diff)
      using LIMSEQ_ignore_initial_segment[OF assms(3)[rule_format],of x 1]
      apply auto
      done
  next
    case 5
    then show ?case
      using assms(4)
      unfolding bounded_iff
      apply safe
      apply (rule_tac x="a + norm (integral s (λx. f 0 x))" in exI)
      apply safe
      apply (erule_tac x="integral s (λx. f (Suc k) x)" in ballE)
      unfolding sub
      apply (rule order_trans[OF norm_triangle_ineq4])
      apply auto
      done
  qed
  note conjunctD2[OF this]
  note tendsto_add[OF this(2) tendsto_const[of "integral s (f 0)"]]
    integrable_add[OF this(1) assms(1)[rule_format,of 0]]
  then show ?thesis
    unfolding sub
    apply -
    apply rule
    defer
    apply (subst(asm) integral_diff)
    using assms(1)
    apply auto
    apply (rule LIMSEQ_imp_Suc)
    apply assumption
    done
qed

lemma has_integral_monotone_convergence_increasing:
  fixes f :: "nat ⇒ 'a::euclidean_space ⇒ real"
  assumes f: "⋀k. (f k has_integral x k) s"
  assumes "⋀k x. x ∈ s ⟹ f k x ≤ f (Suc k) x"
  assumes "⋀x. x ∈ s ⟹ (λk. f k x) ⇢ g x"
  assumes "x ⇢ x'"
  shows "(g has_integral x') s"
proof -
  have x_eq: "x = (λi. integral s (f i))"
    by (simp add: integral_unique[OF f])
  then have x: "{integral s (f k) |k. True} = range x"
    by auto

  have "g integrable_on s ∧ (λk. integral s (f k)) ⇢ integral s g"
  proof (intro monotone_convergence_increasing allI ballI assms)
    show "bounded {integral s (f k) |k. True}"
      unfolding x by (rule convergent_imp_bounded) fact
  qed (auto intro: f)
  moreover then have "integral s g = x'"
    by (intro LIMSEQ_unique[OF _ ‹x ⇢ x'›]) (simp add: x_eq)
  ultimately show ?thesis
    by (simp add: has_integral_integral)
qed

lemma monotone_convergence_decreasing:
  fixes f :: "nat ⇒ 'n::euclidean_space ⇒ real"
  assumes "∀k. (f k) integrable_on s"
    and "∀k. ∀x∈s. f (Suc k) x ≤ f k x"
    and "∀x∈s. ((λk. f k x) ⤏ g x) sequentially"
    and "bounded {integral s (f k)| k. True}"
  shows "g integrable_on s ∧ ((λk. integral s (f k)) ⤏ integral s g) sequentially"
proof -
  note assm = assms[rule_format]
  have *: "{integral s (λx. - f k x) |k. True} = op *R (- 1) ` {integral s (f k)| k. True}"
    apply safe
    unfolding image_iff
    apply (rule_tac x="integral s (f k)" in bexI)
    prefer 3
    apply (rule_tac x=k in exI)
    apply auto
    done
  have "(λx. - g x) integrable_on s ∧
    ((λk. integral s (λx. - f k x)) ⤏ integral s (λx. - g x)) sequentially"
    apply (rule monotone_convergence_increasing)
    apply safe
    apply (rule integrable_neg)
    apply (rule assm)
    defer
    apply (rule tendsto_minus)
    apply (rule assm)
    apply assumption
    unfolding *
    apply (rule bounded_scaling)
    using assm
    apply auto
    done
  note * = conjunctD2[OF this]
  show ?thesis
    using integrable_neg[OF *(1)] tendsto_minus[OF *(2)]
    by auto
qed


subsection ‹Absolute integrability (this is the same as Lebesgue integrability)›

definition absolutely_integrable_on (infixr "absolutely'_integrable'_on" 46)
  where "f absolutely_integrable_on s ⟷ f integrable_on s ∧ (λx. (norm(f x))) integrable_on s"

lemma absolutely_integrable_onI[intro?]:
  "f integrable_on s ⟹
    (λx. (norm(f x))) integrable_on s ⟹ f absolutely_integrable_on s"
  unfolding absolutely_integrable_on_def
  by auto

lemma absolutely_integrable_onD[dest]:
  assumes "f absolutely_integrable_on s"
  shows "f integrable_on s"
    and "(λx. norm (f x)) integrable_on s"
  using assms
  unfolding absolutely_integrable_on_def
  by auto

(*lemma absolutely_integrable_on_trans[simp]:
  fixes f::"'n::euclidean_space ⇒ real"
  shows "(vec1 ∘ f) absolutely_integrable_on s ⟷ f absolutely_integrable_on s"
  unfolding absolutely_integrable_on_def o_def by auto*)

lemma integral_norm_bound_integral:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f integrable_on s"
    and "g integrable_on s"
    and "∀x∈s. norm (f x) ≤ g x"
  shows "norm (integral s f) ≤ integral s g"
proof -
  have *: "⋀x y. (∀e::real. 0 < e ⟶ x < y + e) ⟹ x ≤ y"
    apply (rule ccontr)
    apply (erule_tac x="x - y" in allE)
    apply auto
    done
  have norm: "norm ig < dia + e"
    if "norm sg ≤ dsa"
    and "¦dsa - dia¦ < e / 2"
    and "norm (sg - ig) < e / 2"
    for e dsa dia and sg ig :: 'a
    apply (rule le_less_trans[OF norm_triangle_sub[of ig sg]])
    apply (subst real_sum_of_halves[of e,symmetric])
    unfolding add.assoc[symmetric]
    apply (rule add_le_less_mono)
    defer
    apply (subst norm_minus_commute)
    apply (rule that(3))
    apply (rule order_trans[OF that(1)])
    using that(2)
    apply arith
    done
  have lem: "norm (integral(cbox a b) f) ≤ integral (cbox a b) g"
    if "f integrable_on cbox a b"
    and "g integrable_on cbox a b"
    and "∀x∈cbox a b. norm (f x) ≤ g x"
    for f :: "'n ⇒ 'a" and g a b
  proof (rule *[rule_format])
    fix e :: real
    assume "e > 0"
    then have *: "e/2 > 0"
      by auto
    from integrable_integral[OF that(1),unfolded has_integral[of f],rule_format,OF *]
    guess d1 .. note d1 = conjunctD2[OF this,rule_format]
    from integrable_integral[OF that(2),unfolded has_integral[of g],rule_format,OF *]
    guess d2 .. note d2 = conjunctD2[OF this,rule_format]
    note gauge_inter[OF d1(1) d2(1)]
    from fine_division_exists[OF this, of a b] guess p . note p=this
    show "norm (integral (cbox a b) f) < integral (cbox a b) g + e"
      apply (rule norm)
      defer
      apply (rule d2(2)[OF conjI[OF p(1)],unfolded real_norm_def])
      defer
      apply (rule d1(2)[OF conjI[OF p(1)]])
      defer
      apply (rule setsum_norm_le)
    proof safe
      fix x k
      assume "(x, k) ∈ p"
      note as = tagged_division_ofD(2-4)[OF p(1) this]
      from this(3) guess u v by (elim exE) note uv=this
      show "norm (content k *R f x) ≤ content k *R g x"
        unfolding uv norm_scaleR
        unfolding abs_of_nonneg[OF content_pos_le] real_scaleR_def
        apply (rule mult_left_mono)
        using that(3) as
        apply auto
        done
    qed (insert p[unfolded fine_inter], auto)
  qed

  { presume "⋀e. 0 < e ⟹ norm (integral s f) < integral s g + e"
    then show ?thesis by (rule *[rule_format]) auto }
  fix e :: real
  assume "e > 0"
  then have e: "e/2 > 0"
    by auto
  note assms(1)[unfolded integrable_alt[of f]] note f=this[THEN conjunct1,rule_format]
  note assms(2)[unfolded integrable_alt[of g]] note g=this[THEN conjunct1,rule_format]
  from integrable_integral[OF assms(1),unfolded has_integral'[of f],rule_format,OF e]
  guess B1 .. note B1=conjunctD2[OF this[rule_format],rule_format]
  from integrable_integral[OF assms(2),unfolded has_integral'[of g],rule_format,OF e]
  guess B2 .. note B2=conjunctD2[OF this[rule_format],rule_format]
  from bounded_subset_cbox[OF bounded_ball, of "0::'n" "max B1 B2"]
  guess a b by (elim exE) note ab=this[unfolded ball_max_Un]

  have "ball 0 B1 ⊆ cbox a b"
    using ab by auto
  from B1(2)[OF this] guess z .. note z=conjunctD2[OF this]
  have "ball 0 B2 ⊆ cbox a b"
    using ab by auto
  from B2(2)[OF this] guess w .. note w=conjunctD2[OF this]

  show "norm (integral s f) < integral s g + e"
    apply (rule norm)
    apply (rule lem[OF f g, of a b])
    unfolding integral_unique[OF z(1)] integral_unique[OF w(1)]
    defer
    apply (rule w(2)[unfolded real_norm_def])
    apply (rule z(2))
    apply safe
    apply (case_tac "x ∈ s")
    unfolding if_P
    apply (rule assms(3)[rule_format])
    apply auto
    done
qed

lemma integral_norm_bound_integral_component:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  fixes g :: "'n ⇒ 'b::euclidean_space"
  assumes "f integrable_on s"
    and "g integrable_on s"
    and "∀x∈s. norm(f x) ≤ (g x)∙k"
  shows "norm (integral s f) ≤ (integral s g)∙k"
proof -
  have "norm (integral s f) ≤ integral s ((λx. x ∙ k) ∘ g)"
    apply (rule integral_norm_bound_integral[OF assms(1)])
    apply (rule integrable_linear[OF assms(2)])
    apply rule
    unfolding o_def
    apply (rule assms)
    done
  then show ?thesis
    unfolding o_def integral_component_eq[OF assms(2)] .
qed

lemma has_integral_norm_bound_integral_component:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  fixes g :: "'n ⇒ 'b::euclidean_space"
  assumes "(f has_integral i) s"
    and "(g has_integral j) s"
    and "∀x∈s. norm (f x) ≤ (g x)∙k"
  shows "norm i ≤ j∙k"
  using integral_norm_bound_integral_component[of f s g k]
  unfolding integral_unique[OF assms(1)] integral_unique[OF assms(2)]
  using assms
  by auto

lemma absolutely_integrable_le:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f absolutely_integrable_on s"
  shows "norm (integral s f) ≤ integral s (λx. norm (f x))"
  apply (rule integral_norm_bound_integral)
  using assms
  apply auto
  done

lemma absolutely_integrable_0[intro]:
  "(λx. 0) absolutely_integrable_on s"
  unfolding absolutely_integrable_on_def
  by auto

lemma absolutely_integrable_cmul[intro]:
  "f absolutely_integrable_on s ⟹
    (λx. c *R f x) absolutely_integrable_on s"
  unfolding absolutely_integrable_on_def
  using integrable_cmul[of f s c]
  using integrable_cmul[of "λx. norm (f x)" s "¦c¦"]
  by auto

lemma absolutely_integrable_neg[intro]:
  "f absolutely_integrable_on s ⟹
    (λx. -f(x)) absolutely_integrable_on s"
  apply (drule absolutely_integrable_cmul[where c="-1"])
  apply auto
  done

lemma absolutely_integrable_norm[intro]:
  "f absolutely_integrable_on s ⟹
    (λx. norm (f x)) absolutely_integrable_on s"
  unfolding absolutely_integrable_on_def
  by auto

lemma absolutely_integrable_abs[intro]:
  "f absolutely_integrable_on s ⟹
    (λx. ¦f x::real¦) absolutely_integrable_on s"
  apply (drule absolutely_integrable_norm)
  unfolding real_norm_def
  apply assumption
  done

lemma absolutely_integrable_on_subinterval:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  shows "f absolutely_integrable_on s ⟹
    cbox a b ⊆ s ⟹ f absolutely_integrable_on cbox a b"
  unfolding absolutely_integrable_on_def
  by (metis integrable_on_subcbox)

lemma absolutely_integrable_bounded_variation:
  fixes f :: "'n::euclidean_space ⇒ 'a::banach"
  assumes "f absolutely_integrable_on UNIV"
  obtains B where "∀d. d division_of (⋃d) ⟶ setsum (λk. norm(integral k f)) d ≤ B"
  apply (rule that[of "integral UNIV (λx. norm (f x))"])
  apply safe
proof goal_cases
  case prems: (1 d)
  note d = division_ofD[OF prems(2)]
  have "(∑k∈d. norm (integral k f)) ≤ (∑i∈d. integral i (λx. norm (f x)))"
    apply (rule setsum_mono,rule absolutely_integrable_le)
    apply (drule d(4))
    apply safe
    apply (rule absolutely_integrable_on_subinterval[OF assms])
    apply auto
    done
  also have "… ≤ integral (⋃d) (λx. norm (f x))"
    apply (subst integral_combine_division_topdown[OF _ prems(2)])
    using integrable_on_subdivision[OF prems(2)]
    using assms
    apply auto
    done
  also have "… ≤ integral UNIV (λx. norm (f x))"
    apply (rule integral_subset_le)
    using integrable_on_subdivision[OF prems(2)]
    using assms
    apply auto
    done
  finally show ?case .
qed

lemma helplemma:
  assumes "setsum (λx. norm (f x - g x)) s < e"
    and "finite s"
  shows "¦setsum (λx. norm(f x)) s - setsum (λx. norm(g x)) s¦ < e"
  unfolding setsum_subtractf[symmetric]
  apply (rule le_less_trans[OF setsum_abs])
  apply (rule le_less_trans[OF _ assms(1)])
  apply (rule setsum_mono)
  apply (rule norm_triangle_ineq3)
  done

lemma bounded_variation_absolutely_integrable_interval:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes f: "f integrable_on cbox a b"
    and *: "∀d. d division_of (cbox a b) ⟶ setsum (λk. norm(integral k f)) d ≤ B"
  shows "f absolutely_integrable_on cbox a b"
proof -
  let ?f = "λd. ∑k∈d. norm (integral k f)" and ?D = "{d. d division_of (cbox a b)}"
  have D_1: "?D ≠ {}"
    by (rule elementary_interval[of a b]) auto
  have D_2: "bdd_above (?f`?D)"
    by (metis * mem_Collect_eq bdd_aboveI2)
  note D = D_1 D_2
  let ?S = "SUP x:?D. ?f x"
  show ?thesis
    apply (rule absolutely_integrable_onI [OF f has_integral_integrable])
    apply (subst has_integral[of _ ?S])
    apply safe
  proof goal_cases
    case e: (1 e)
    then have "?S - e / 2 < ?S" by simp
    then obtain d where d: "d division_of (cbox a b)" "?S - e / 2 < (∑k∈d. norm (integral k f))"
      unfolding less_cSUP_iff[OF D] by auto
    note d' = division_ofD[OF this(1)]

    have "∀x. ∃e>0. ∀i∈d. x ∉ i ⟶ ball x e ∩ i = {}"
    proof
      fix x
      have "∃da>0. ∀xa∈⋃{i ∈ d. x ∉ i}. da ≤ dist x xa"
        apply (rule separate_point_closed)
        apply (rule closed_Union)
        apply (rule finite_subset[OF _ d'(1)])
        using d'(4)
        apply auto
        done
      then show "∃e>0. ∀i∈d. x ∉ i ⟶ ball x e ∩ i = {}"
        by force
    qed
    from choice[OF this] guess k .. note k=conjunctD2[OF this[rule_format],rule_format]

    have "e/2 > 0"
      using e by auto
    from henstock_lemma[OF assms(1) this] guess g . note g=this[rule_format]
    let ?g = "λx. g x ∩ ball x (k x)"
    show ?case
      apply (rule_tac x="?g" in exI)
      apply safe
    proof -
      show "gauge ?g"
        using g(1) k(1)
        unfolding gauge_def
        by auto
      fix p
      assume "p tagged_division_of (cbox a b)" and "?g fine p"
      note p = this(1) conjunctD2[OF this(2)[unfolded fine_inter]]
      note p' = tagged_division_ofD[OF p(1)]
      def p'  "{(x,k) | x k. ∃i l. x ∈ i ∧ i ∈ d ∧ (x,l) ∈ p ∧ k = i ∩ l}"
      have gp': "g fine p'"
        using p(2)
        unfolding p'_def fine_def
        by auto
      have p'': "p' tagged_division_of (cbox a b)"
        apply (rule tagged_division_ofI)
      proof -
        show "finite p'"
          apply (rule finite_subset[of _ "(λ(k,(x,l)). (x,k ∩ l)) `
            {(k,xl) | k xl. k ∈ d ∧ xl ∈ p}"])
          unfolding p'_def
          defer
          apply (rule finite_imageI,rule finite_product_dependent[OF d'(1) p'(1)])
          apply safe
          unfolding image_iff
          apply (rule_tac x="(i,x,l)" in bexI)
          apply auto
          done
        fix x k
        assume "(x, k) ∈ p'"
        then have "∃i l. x ∈ i ∧ i ∈ d ∧ (x, l) ∈ p ∧ k = i ∩ l"
          unfolding p'_def by auto
        then guess i l by (elim exE) note il=conjunctD4[OF this]
        show "x ∈ k" and "k ⊆ cbox a b"
          using p'(2-3)[OF il(3)] il by auto
        show "∃a b. k = cbox a b"
          unfolding il using p'(4)[OF il(3)] d'(4)[OF il(2)]
          apply safe
          unfolding inter_interval
          apply auto
          done
      next
        fix x1 k1
        assume "(x1, k1) ∈ p'"
        then have "∃i l. x1 ∈ i ∧ i ∈ d ∧ (x1, l) ∈ p ∧ k1 = i ∩ l"
          unfolding p'_def by auto
        then guess i1 l1 by (elim exE) note il1=conjunctD4[OF this]
        fix x2 k2
        assume "(x2,k2)∈p'"
        then have "∃i l. x2 ∈ i ∧ i ∈ d ∧ (x2, l) ∈ p ∧ k2 = i ∩ l"
          unfolding p'_def by auto
        then guess i2 l2 by (elim exE) note il2=conjunctD4[OF this]
        assume "(x1, k1) ≠ (x2, k2)"
        then have "interior i1 ∩ interior i2 = {} ∨ interior l1 ∩ interior l2 = {}"
          using d'(5)[OF il1(2) il2(2)] p'(5)[OF il1(3) il2(3)]
          unfolding il1 il2
          by auto
        then show "interior k1 ∩ interior k2 = {}"
          unfolding il1 il2 by auto
      next
        have *: "∀(x, X) ∈ p'. X ⊆ cbox a b"
          unfolding p'_def using d' by auto
        show "⋃{k. ∃x. (x, k) ∈ p'} = cbox a b"
          apply rule
          apply (rule Union_least)
          unfolding mem_Collect_eq
          apply (erule exE)
          apply (drule *[rule_format])
          apply safe
        proof -
          fix y
          assume y: "y ∈ cbox a b"
          then have "∃x l. (x, l) ∈ p ∧ y∈l"
            unfolding p'(6)[symmetric] by auto
          then guess x l by (elim exE) note xl=conjunctD2[OF this]
          then have "∃k. k ∈ d ∧ y ∈ k"
            using y unfolding d'(6)[symmetric] by auto
          then guess i .. note i = conjunctD2[OF this]
          have "x ∈ i"
            using fineD[OF p(3) xl(1)]
            using k(2)[OF i(1), of x]
            using i(2) xl(2)
            by auto
          then show "y ∈ ⋃{k. ∃x. (x, k) ∈ p'}"
            unfolding p'_def Union_iff
            apply (rule_tac x="i ∩ l" in bexI)
            using i xl
            apply auto
            done
        qed
      qed

      then have "(∑(x, k)∈p'. norm (content k *R f x - integral k f)) < e / 2"
        apply -
        apply (rule g(2)[rule_format])
        unfolding tagged_division_of_def
        apply safe
        apply (rule gp')
        done
      then have **: "¦(∑(x,k)∈p'. norm (content k *R f x)) - (∑(x,k)∈p'. norm (integral k f))¦ < e / 2"
        unfolding split_def
        using p''
        by (force intro!: helplemma)

      have p'alt: "p' = {(x,(i ∩ l)) | x i l. (x,l) ∈ p ∧ i ∈ d ∧ i ∩ l ≠ {}}"
      proof (safe, goal_cases)
        case prems: (2 _ _ x i l)
        have "x ∈ i"
          using fineD[OF p(3) prems(1)] k(2)[OF prems(2), of x] prems(4-)
          by auto
        then have "(x, i ∩ l) ∈ p'"
          unfolding p'_def
          using prems
          apply safe
          apply (rule_tac x=x in exI)
          apply (rule_tac x="i ∩ l" in exI)
          apply safe
          using prems
          apply auto
          done
        then show ?case
          using prems(3) by auto
      next
        fix x k
        assume "(x, k) ∈ p'"
        then have "∃i l. x ∈ i ∧ i ∈ d ∧ (x, l) ∈ p ∧ k = i ∩ l"
          unfolding p'_def by auto
        then guess i l by (elim exE) note il=conjunctD4[OF this]
        then show "∃y i l. (x, k) = (y, i ∩ l) ∧ (y, l) ∈ p ∧ i ∈ d ∧ i ∩ l ≠ {}"
          apply (rule_tac x=x in exI)
          apply (rule_tac x=i in exI)
          apply (rule_tac x=l in exI)
          using p'(2)[OF il(3)]
          apply auto
          done
      qed
      have sum_p': "(∑(x, k)∈p'. norm (integral k f)) = (∑k∈snd ` p'. norm (integral k f))"
        apply (subst setsum_over_tagged_division_lemma[OF p'',of "λk. norm (integral k f)"])
        unfolding norm_eq_zero
        apply (rule integral_null)
        apply assumption
        apply rule
        done
      note snd_p = division_ofD[OF division_of_tagged_division[OF p(1)]]

      have *: "⋀sni sni' sf sf'. ¦sf' - sni'¦ < e / 2 ⟶ ?S - e / 2 < sni ∧ sni' ≤ ?S ∧
        sni ≤ sni' ∧ sf' = sf ⟶ ¦sf - ?S¦ < e"
        by arith
      show "norm ((∑(x, k)∈p. content k *R norm (f x)) - ?S) < e"
        unfolding real_norm_def
        apply (rule *[rule_format,OF **])
        apply safe
        apply(rule d(2))
      proof goal_cases
        case 1
        show ?case
          by (auto simp: sum_p' division_of_tagged_division[OF p''] D intro!: cSUP_upper)
      next
        case 2
        have *: "{k ∩ l | k l. k ∈ d ∧ l ∈ snd ` p} =
          (λ(k,l). k ∩ l) ` {(k,l)|k l. k ∈ d ∧ l ∈ snd ` p}"
          by auto
        have "(∑k∈d. norm (integral k f)) ≤ (∑i∈d. ∑l∈snd ` p. norm (integral (i ∩ l) f))"
        proof (rule setsum_mono, goal_cases)
          case k: (1 k)
          from d'(4)[OF this] guess u v by (elim exE) note uv=this
          def d'  "{cbox u v ∩ l |l. l ∈ snd ` p ∧  cbox u v ∩ l ≠ {}}"
          note uvab = d'(2)[OF k[unfolded uv]]
          have "d' division_of cbox u v"
            apply (subst d'_def)
            apply (rule division_inter_1)
            apply (rule division_of_tagged_division[OF p(1)])
            apply (rule uvab)
            done
          then have "norm (integral k f) ≤ setsum (λk. norm (integral k f)) d'"
            unfolding uv
            apply (subst integral_combine_division_topdown[of _ _ d'])
            apply (rule integrable_on_subcbox[OF assms(1) uvab])
            apply assumption
            apply (rule setsum_norm_le)
            apply auto
            done
          also have "… = (∑k∈{k ∩ l |l. l ∈ snd ` p}. norm (integral k f))"
            apply (rule setsum.mono_neutral_left)
            apply (subst simple_image)
            apply (rule finite_imageI)+
            apply fact
            unfolding d'_def uv
            apply blast
          proof (rule, goal_cases)
            case prems: (1 i)
            then have "i ∈ {cbox u v ∩ l |l. l ∈ snd ` p}"
              by auto
            from this[unfolded mem_Collect_eq] guess l .. note l=this
            then have "cbox u v ∩ l = {}"
              using prems by auto
            then show ?case
              using l by auto
          qed
          also have "… = (∑l∈snd ` p. norm (integral (k ∩ l) f))"
            unfolding simple_image
            apply (rule setsum.reindex_nontrivial [unfolded o_def])
            apply (rule finite_imageI)
            apply (rule p')
          proof goal_cases
            case prems: (1 l y)
            have "interior (k ∩ l) ⊆ interior (l ∩ y)"
              apply (subst(2) interior_Int)
              apply (rule Int_greatest)
              defer
              apply (subst prems(4))
              apply auto
              done
            then have *: "interior (k ∩ l) = {}"
              using snd_p(5)[OF prems(1-3)] by auto
            from d'(4)[OF k] snd_p(4)[OF prems(1)] guess u1 v1 u2 v2 by (elim exE) note uv=this
            show ?case
              using *
              unfolding uv inter_interval content_eq_0_interior[symmetric]
              by auto
          qed
          finally show ?case .
        qed
        also have "… = (∑(i,l)∈{(i, l) |i l. i ∈ d ∧ l ∈ snd ` p}. norm (integral (i∩l) f))"
          apply (subst sum_sum_product[symmetric])
          apply fact
          using p'(1)
          apply auto
          done
        also have "… = (∑x∈{(i, l) |i l. i ∈ d ∧ l ∈ snd ` p}. norm (integral (case_prod op ∩ x) f))"
          unfolding split_def ..
        also have "… = (∑k∈{i ∩ l |i l. i ∈ d ∧ l ∈ snd ` p}. norm (integral k f))"
          unfolding *
          apply (rule setsum.reindex_nontrivial [symmetric, unfolded o_def])
          apply (rule finite_product_dependent)
          apply fact
          apply (rule finite_imageI)
          apply (rule p')
          unfolding split_paired_all mem_Collect_eq split_conv o_def
        proof -
          note * = division_ofD(4,5)[OF division_of_tagged_division,OF p(1)]
          fix l1 l2 k1 k2
          assume as:
            "(l1, k1) ≠ (l2, k2)"
            "l1 ∩ k1 = l2 ∩ k2"
            "∃i l. (l1, k1) = (i, l) ∧ i ∈ d ∧ l ∈ snd ` p"
            "∃i l. (l2, k2) = (i, l) ∧ i ∈ d ∧ l ∈ snd ` p"
          then have "l1 ∈ d" and "k1 ∈ snd ` p"
            by auto from d'(4)[OF this(1)] *(1)[OF this(2)]
          guess u1 v1 u2 v2 by (elim exE) note uv=this
          have "l1 ≠ l2 ∨ k1 ≠ k2"
            using as by auto
          then have "interior k1 ∩ interior k2 = {} ∨ interior l1 ∩ interior l2 = {}"
            apply -
            apply (erule disjE)
            apply (rule disjI2)
            apply (rule d'(5))
            prefer 4
            apply (rule disjI1)
            apply (rule *)
            using as
            apply auto
            done
          moreover have "interior (l1 ∩ k1) = interior (l2 ∩ k2)"
            using as(2) by auto
          ultimately have "interior(l1 ∩ k1) = {}"
            by auto
          then show "norm (integral (l1 ∩ k1) f) = 0"
            unfolding uv inter_interval
            unfolding content_eq_0_interior[symmetric]
            by auto
        qed
        also have "… = (∑(x, k)∈p'. norm (integral k f))"
          unfolding sum_p'
          apply (rule setsum.mono_neutral_right)
          apply (subst *)
          apply (rule finite_imageI[OF finite_product_dependent])
          apply fact
          apply (rule finite_imageI[OF p'(1)])
          apply safe
        proof goal_cases
          case (2 i ia l a b)
          then have "ia ∩ b = {}"
            unfolding p'alt image_iff Bex_def not_ex
            apply (erule_tac x="(a, ia ∩ b)" in allE)
            apply auto
            done
          then show ?case
            by auto
        next
          case (1 x a b)
          then show ?case
            unfolding p'_def
            apply safe
            apply (rule_tac x=i in exI)
            apply (rule_tac x=l in exI)
            unfolding snd_conv image_iff
            apply safe
            apply (rule_tac x="(a,l)" in bexI)
            apply auto
            done
        qed
        finally show ?case .
      next
        case 3
        let ?S = "{(x, i ∩ l) |x i l. (x, l) ∈ p ∧ i ∈ d}"
        have Sigma_alt: "⋀s t. s × t = {(i, j) |i j. i ∈ s ∧ j ∈ t}"
          by auto
        have *: "?S = (λ(xl,i). (fst xl, snd xl ∩ i)) ` (p × d)" (*{(xl,i)|xl i. xl∈p ∧ i∈d}"**)
          apply safe
          unfolding image_iff
          apply (rule_tac x="((x,l),i)" in bexI)
          apply auto
          done
        note pdfin = finite_cartesian_product[OF p'(1) d'(1)]
        have "(∑(x, k)∈p'. norm (content k *R f x)) = (∑(x, k)∈?S. ¦content k¦ * norm (f x))"
          unfolding norm_scaleR
          apply (rule setsum.mono_neutral_left)
          apply (subst *)
          apply (rule finite_imageI)
          apply fact
          unfolding p'alt
          apply blast
          apply safe
          apply (rule_tac x=x in exI)
          apply (rule_tac x=i in exI)
          apply (rule_tac x=l in exI)
          apply auto
          done
        also have "… = (∑((x,l),i)∈p × d. ¦content (l ∩ i)¦ * norm (f x))"
          unfolding *
          apply (subst setsum.reindex_nontrivial)
          apply fact
          unfolding split_paired_all
          unfolding o_def split_def snd_conv fst_conv mem_Sigma_iff prod.inject
          apply (elim conjE)
        proof -
          fix x1 l1 k1 x2 l2 k2
          assume as: "(x1, l1) ∈ p" "(x2, l2) ∈ p" "k1 ∈ d" "k2 ∈ d"
            "x1 = x2" "l1 ∩ k1 = l2 ∩ k2" "¬ ((x1 = x2 ∧ l1 = l2) ∧ k1 = k2)"
          from d'(4)[OF as(3)] p'(4)[OF as(1)] guess u1 v1 u2 v2 by (elim exE) note uv=this
          from as have "l1 ≠ l2 ∨ k1 ≠ k2"
            by auto
          then have "interior k1 ∩ interior k2 = {} ∨ interior l1 ∩ interior l2 = {}"
            apply -
            apply (erule disjE)
            apply (rule disjI2)
            defer
            apply (rule disjI1)
            apply (rule d'(5)[OF as(3-4)])
            apply assumption
            apply (rule p'(5)[OF as(1-2)])
            apply auto
            done
          moreover have "interior (l1 ∩ k1) = interior (l2 ∩ k2)"
            unfolding  as ..
          ultimately have "interior (l1 ∩ k1) = {}"
            by auto
          then show "¦content (l1 ∩ k1)¦ * norm (f x1) = 0"
            unfolding uv inter_interval
            unfolding content_eq_0_interior[symmetric]
            by auto
        qed safe
        also have "… = (∑(x, k)∈p. content k *R norm (f x))"
          unfolding Sigma_alt
          apply (subst sum_sum_product[symmetric])
          apply (rule p')
          apply rule
          apply (rule d')
          apply (rule setsum.cong)
          apply (rule refl)
          unfolding split_paired_all split_conv
        proof -
          fix x l
          assume as: "(x, l) ∈ p"
          note xl = p'(2-4)[OF this]
          from this(3) guess u v by (elim exE) note uv=this
          have "(∑i∈d. ¦content (l ∩ i)¦) = (∑k∈d. content (k ∩ cbox u v))"
            apply (rule setsum.cong)
            apply (rule refl)
            apply (drule d'(4))
            apply safe
            apply (subst Int_commute)
            unfolding inter_interval uv
            apply (subst abs_of_nonneg)
            apply auto
            done
          also have "… = setsum content {k ∩ cbox u v| k. k ∈ d}"
            unfolding simple_image
            apply (rule setsum.reindex_nontrivial [unfolded o_def, symmetric])
            apply (rule d')
          proof goal_cases
            case prems: (1 k y)
            from d'(4)[OF this(1)] d'(4)[OF this(2)]
            guess u1 v1 u2 v2 by (elim exE) note uv=this
            have "{} = interior ((k ∩ y) ∩ cbox u v)"
              apply (subst interior_Int)
              using d'(5)[OF prems(1-3)]
              apply auto
              done
            also have "… = interior (y ∩ (k ∩ cbox u v))"
              by auto
            also have "… = interior (k ∩ cbox u v)"
              unfolding prems(4) by auto
            finally show ?case
              unfolding uv inter_interval content_eq_0_interior ..
          qed
          also have "… = setsum content {cbox u v ∩ k |k. k ∈ d ∧ cbox u v ∩ k ≠ {}}"
            apply (rule setsum.mono_neutral_right)
            unfolding simple_image
            apply (rule finite_imageI)
            apply (rule d')
            apply blast
            apply safe
            apply (rule_tac x=k in exI)
          proof goal_cases
            case prems: (1 i k)
            from d'(4)[OF this(1)] guess a b by (elim exE) note ab=this
            have "interior (k ∩ cbox u v) ≠ {}"
              using prems(2)
              unfolding ab inter_interval content_eq_0_interior
              by auto
            then show ?case
              using prems(1)
              using interior_subset[of "k ∩ cbox u v"]
              by auto
          qed
          finally show "(∑i∈d. ¦content (l ∩ i)¦ * norm (f x)) = content l *R norm (f x)"
            unfolding setsum_left_distrib[symmetric] real_scaleR_def
            apply (subst(asm) additive_content_division[OF division_inter_1[OF d(1)]])
            using xl(2)[unfolded uv]
            unfolding uv
            apply auto
            done
        qed
        finally show ?case .
      qed
    qed
  qed
qed

lemma bounded_variation_absolutely_integrable:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "f integrable_on UNIV"
    and "∀d. d division_of (⋃d) ⟶ setsum (λk. norm (integral k f)) d ≤ B"
  shows "f absolutely_integrable_on UNIV"
proof (rule absolutely_integrable_onI, fact, rule)
  let ?f = "λd. ∑k∈d. norm (integral k f)" and ?D = "{d. d division_of  (⋃d)}"
  have D_1: "?D ≠ {}"
    by (rule elementary_interval) auto
  have D_2: "bdd_above (?f`?D)"
    by (intro bdd_aboveI2[where M=B] assms(2)[rule_format]) simp
  note D = D_1 D_2
  let ?S = "SUP d:?D. ?f d"
  have f_int: "⋀a b. f absolutely_integrable_on cbox a b"
    apply (rule bounded_variation_absolutely_integrable_interval[where B=B])
    apply (rule integrable_on_subcbox[OF assms(1)])
    defer
    apply safe
    apply (rule assms(2)[rule_format])
    apply auto
    done
  show "((λx. norm (f x)) has_integral ?S) UNIV"
    apply (subst has_integral_alt')
    apply safe
  proof goal_cases
    case (1 a b)
    show ?case
      using f_int[of a b] by auto
  next
    case prems: (2 e)
    have "∃y∈setsum (λk. norm (integral k f)) ` {d. d division_of ⋃d}. ¬ y ≤ ?S - e"
    proof (rule ccontr)
      assume "¬ ?thesis"
      then have "?S ≤ ?S - e"
        by (intro cSUP_least[OF D(1)]) auto
      then show False
        using prems by auto
    qed
    then obtain K where *: "∃x∈{d. d division_of ⋃d}. K = (∑k∈x. norm (integral k f))"
      "SUPREMUM {d. d division_of ⋃d} (setsum (λk. norm (integral k f))) - e < K"
      by (auto simp add: image_iff not_le)
    from this(1) obtain d where "d division_of ⋃d"
      and "K = (∑k∈d. norm (integral k f))"
      by auto
    note d = this(1) *(2)[unfolded this(2)]
    note d'=division_ofD[OF this(1)]
    have "bounded (⋃d)"
      by (rule elementary_bounded,fact)
    from this[unfolded bounded_pos] obtain K where
       K: "0 < K" "∀x∈⋃d. norm x ≤ K" by auto
    show ?case
      apply (rule_tac x="K + 1" in exI)
      apply safe
    proof -
      fix a b :: 'n
      assume ab: "ball 0 (K + 1) ⊆ cbox a b"
      have *: "∀s s1. ?S - e < s1 ∧ s1 ≤ s ∧ s < ?S + e ⟶ ¦s - ?S¦ < e"
        by arith
      show "norm (integral (cbox a b) (λx. if x ∈ UNIV then norm (f x) else 0) - ?S) < e"
        unfolding real_norm_def
        apply (rule *[rule_format])
        apply safe
        apply (rule d(2))
      proof goal_cases
        case 1
        have "(∑k∈d. norm (integral k f)) ≤ setsum (λk. integral k (λx. norm (f x))) d"
          apply (rule setsum_mono)
          apply (rule absolutely_integrable_le)
          apply (drule d'(4))
          apply safe
          apply (rule f_int)
          done
        also have "… = integral (⋃d) (λx. norm (f x))"
          apply (rule integral_combine_division_bottomup[symmetric])
          apply (rule d)
          unfolding forall_in_division[OF d(1)]
          using f_int
          apply auto
          done
        also have "… ≤ integral (cbox a b) (λx. if x ∈ UNIV then norm (f x) else 0)"
        proof -
          have "⋃d ⊆ cbox a b"
            apply rule
            apply (drule K(2)[rule_format])
            apply (rule ab[unfolded subset_eq,rule_format])
            apply (auto simp add: dist_norm)
            done
          then show ?thesis
            apply -
            apply (subst if_P)
            apply rule
            apply (rule integral_subset_le)
            defer
            apply (rule integrable_on_subdivision[of _ _ _ "cbox a b"])
            apply (rule d)
            using f_int[of a b]
            apply auto
            done
        qed
        finally show ?case .
      next
        note f = absolutely_integrable_onD[OF f_int[of a b]]
        note * = this(2)[unfolded has_integral_integral has_integral[of "λx. norm (f x)"],rule_format]
        have "e/2>0"
          using ‹e > 0› by auto
        from * [OF this] obtain d1 where
          d1: "gauge d1" "∀p. p tagged_division_of (cbox a b) ∧ d1 fine p ⟶
            norm ((∑(x, k)∈p. content k *R norm (f x)) - integral (cbox a b) (λx. norm (f x))) < e / 2"
          by auto
        from henstock_lemma [OF f(1) ‹e/2>0›] obtain d2 where
          d2: "gauge d2" "∀p. p tagged_partial_division_of (cbox a b) ∧ d2 fine p ⟶
            (∑(x, k)∈p. norm (content k *R f x - integral k f)) < e / 2" .
         obtain p where
          p: "p tagged_division_of (cbox a b)" "d1 fine p" "d2 fine p"
          by (rule fine_division_exists [OF gauge_inter [OF d1(1) d2(1)], of a b])
            (auto simp add: fine_inter)
        have *: "⋀sf sf' si di. sf' = sf ⟶ si ≤ ?S ⟶ ¦sf - si¦ < e / 2 ⟶
          ¦sf' - di¦ < e / 2 ⟶ di < ?S + e"
          by arith
        show "integral (cbox a b) (λx. if x ∈ UNIV then norm (f x) else 0) < ?S + e"
          apply (subst if_P)
          apply rule
        proof (rule *[rule_format])
          show "¦(∑(x,k)∈p. norm (content k *R f x)) - (∑(x,k)∈p. norm (integral k f))¦ < e / 2"
            unfolding split_def
            apply (rule helplemma)
            using d2(2)[rule_format,of p]
            using p(1,3)
            unfolding tagged_division_of_def split_def
            apply auto
            done
          show "¦(∑(x, k)∈p. content k *R norm (f x)) - integral (cbox a b) (λx. norm(f x))¦ < e / 2"
            using d1(2)[rule_format,OF conjI[OF p(1,2)]]
            by (simp only: real_norm_def)
          show "(∑(x, k)∈p. content k *R norm (f x)) = (∑(x, k)∈p. norm (content k *R f x))"
            apply (rule setsum.cong)
            apply (rule refl)
            unfolding split_paired_all split_conv
            apply (drule tagged_division_ofD(4)[OF p(1)])
            unfolding norm_scaleR
            apply (subst abs_of_nonneg)
            apply auto
            done
          show "(∑(x, k)∈p. norm (integral k f)) ≤ ?S"
            using partial_division_of_tagged_division[of p "cbox a b"] p(1)
            apply (subst setsum_over_tagged_division_lemma[OF p(1)])
            apply (simp add: integral_null)
            apply (intro cSUP_upper2[OF D(2), of "snd ` p"])
            apply (auto simp: tagged_partial_division_of_def)
            done
        qed
      qed
    qed (insert K, auto)
  qed
qed

lemma absolutely_integrable_restrict_univ:
  "(λx. if x ∈ s then f x else (0::'a::banach)) absolutely_integrable_on UNIV ⟷
    f absolutely_integrable_on s"
  unfolding absolutely_integrable_on_def if_distrib norm_zero integrable_restrict_univ ..

lemma absolutely_integrable_add[intro]:
  fixes f g :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "f absolutely_integrable_on s"
    and "g absolutely_integrable_on s"
  shows "(λx. f x + g x) absolutely_integrable_on s"
proof -
  let ?P = "⋀f g::'n ⇒ 'm. f absolutely_integrable_on UNIV ⟹
    g absolutely_integrable_on UNIV ⟹ (λx. f x + g x) absolutely_integrable_on UNIV"
  {
    presume as: "PROP ?P"
    note a = absolutely_integrable_restrict_univ[symmetric]
    have *: "⋀x. (if x ∈ s then f x else 0) + (if x ∈ s then g x else 0) =
      (if x ∈ s then f x + g x else 0)" by auto
    show ?thesis
      apply (subst a)
      using as[OF assms[unfolded a[of f] a[of g]]]
      apply (simp only: *)
      done
  }
  fix f g :: "'n ⇒ 'm"
  assume assms: "f absolutely_integrable_on UNIV" "g absolutely_integrable_on UNIV"
  note absolutely_integrable_bounded_variation
  from this[OF assms(1)] this[OF assms(2)] guess B1 B2 . note B=this[rule_format]
  show "(λx. f x + g x) absolutely_integrable_on UNIV"
    apply (rule bounded_variation_absolutely_integrable[of _ "B1+B2"])
    apply (rule integrable_add)
    prefer 3
    apply safe
  proof goal_cases
    case prems: (1 d)
    have "⋀k. k ∈ d ⟹ f integrable_on k ∧ g integrable_on k"
      apply (drule division_ofD(4)[OF prems])
      apply safe
      apply (rule_tac[!] integrable_on_subcbox[of _ UNIV])
      using assms
      apply auto
      done
    then have "(∑k∈d. norm (integral k (λx. f x + g x))) ≤
      (∑k∈d. norm (integral k f)) + (∑k∈d. norm (integral k g))"
      apply -
      unfolding setsum.distrib [symmetric]
      apply (rule setsum_mono)
      apply (subst integral_add)
      prefer 3
      apply (rule norm_triangle_ineq)
      apply auto
      done
    also have "… ≤ B1 + B2"
      using B(1)[OF prems] B(2)[OF prems] by auto
    finally show ?case .
  qed (insert assms, auto)
qed

lemma absolutely_integrable_sub[intro]:
  fixes f g :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "f absolutely_integrable_on s"
    and "g absolutely_integrable_on s"
  shows "(λx. f x - g x) absolutely_integrable_on s"
  using absolutely_integrable_add[OF assms(1) absolutely_integrable_neg[OF assms(2)]]
  by (simp add: algebra_simps)

lemma absolutely_integrable_linear:
  fixes f :: "'m::euclidean_space ⇒ 'n::euclidean_space"
    and h :: "'n::euclidean_space ⇒ 'p::euclidean_space"
  assumes "f absolutely_integrable_on s"
    and "bounded_linear h"
  shows "(h ∘ f) absolutely_integrable_on s"
proof -
  {
    presume as: "⋀f::'m ⇒ 'n. ⋀h::'n ⇒ 'p. f absolutely_integrable_on UNIV ⟹
      bounded_linear h ⟹ (h ∘ f) absolutely_integrable_on UNIV"
    note a = absolutely_integrable_restrict_univ[symmetric]
    show ?thesis
      apply (subst a)
      using as[OF assms[unfolded a[of f] a[of g]]]
      apply (simp only: o_def if_distrib linear_simps[OF assms(2)])
      done
  }
  fix f :: "'m ⇒ 'n"
  fix h :: "'n ⇒ 'p"
  assume assms: "f absolutely_integrable_on UNIV" "bounded_linear h"
  from absolutely_integrable_bounded_variation[OF assms(1)] guess B . note B=this
  from bounded_linear.pos_bounded[OF assms(2)] guess b .. note b=conjunctD2[OF this]
  show "(h ∘ f) absolutely_integrable_on UNIV"
    apply (rule bounded_variation_absolutely_integrable[of _ "B * b"])
    apply (rule integrable_linear[OF _ assms(2)])
    apply safe
  proof goal_cases
    case prems: (2 d)
    have "(∑k∈d. norm (integral k (h ∘ f))) ≤ setsum (λk. norm(integral k f)) d * b"
      unfolding setsum_left_distrib
      apply (rule setsum_mono)
    proof goal_cases
      case (1 k)
      from division_ofD(4)[OF prems this]
      guess u v by (elim exE) note uv=this
      have *: "f integrable_on k"
        unfolding uv
        apply (rule integrable_on_subcbox[of _ UNIV])
        using assms
        apply auto
        done
      note this[unfolded has_integral_integral]
      note has_integral_linear[OF this assms(2)] integrable_linear[OF * assms(2)]
      note * = has_integral_unique[OF this(2)[unfolded has_integral_integral] this(1)]
      show ?case
        unfolding * using b by auto
    qed
    also have "… ≤ B * b"
      apply (rule mult_right_mono)
      using B prems b
      apply auto
      done
    finally show ?case .
  qed (insert assms, auto)
qed

lemma absolutely_integrable_setsum:
  fixes f :: "'a ⇒ 'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "finite t"
    and "⋀a. a ∈ t ⟹ (f a) absolutely_integrable_on s"
  shows "(λx. setsum (λa. f a x) t) absolutely_integrable_on s"
  using assms(1,2)
  by induct auto

lemma absolutely_integrable_vector_abs:
  fixes f :: "'a::euclidean_space => 'b::euclidean_space"
    and T :: "'c::euclidean_space ⇒ 'b"
  assumes f: "f absolutely_integrable_on s"
  shows "(λx. (∑i∈Basis. ¦f x∙T i¦ *R i)) absolutely_integrable_on s"
  (is "?Tf absolutely_integrable_on s")
proof -
  have if_distrib: "⋀P A B x. (if P then A else B) *R x = (if P then A *R x else B *R x)"
    by simp
  have *: "⋀x. ?Tf x = (∑i∈Basis.
    ((λy. (∑j∈Basis. (if j = i then y else 0) *R j)) o
     (λx. (norm (∑j∈Basis. (if j = i then f x∙T i else 0) *R j)))) x)"
    by (simp add: comp_def if_distrib setsum.If_cases)
  show ?thesis
    unfolding *
    apply (rule absolutely_integrable_setsum[OF finite_Basis])
    apply (rule absolutely_integrable_linear)
    apply (rule absolutely_integrable_norm)
    apply (rule absolutely_integrable_linear[OF f, unfolded o_def])
    apply (auto simp: linear_linear euclidean_eq_iff[where 'a='c] inner_simps intro!: linearI)
    done
qed

lemma absolutely_integrable_max:
  fixes f g :: "'m::euclidean_space ⇒ 'n::euclidean_space"
  assumes "f absolutely_integrable_on s"
    and "g absolutely_integrable_on s"
  shows "(λx. (∑i∈Basis. max (f(x)∙i) (g(x)∙i) *R i)::'n) absolutely_integrable_on s"
proof -
  have *:"⋀x. (1 / 2) *R (((∑i∈Basis. ¦(f x - g x) ∙ i¦ *R i)::'n) + (f x + g x)) =
      (∑i∈Basis. max (f(x)∙i) (g(x)∙i) *R i)"
    unfolding euclidean_eq_iff[where 'a='n] by (auto simp: inner_simps)
  note absolutely_integrable_sub[OF assms] absolutely_integrable_add[OF assms]
  note absolutely_integrable_vector_abs[OF this(1), where T="λx. x"] this(2)
  note absolutely_integrable_add[OF this]
  note absolutely_integrable_cmul[OF this, of "1/2"]
  then show ?thesis unfolding * .
qed

lemma absolutely_integrable_min:
  fixes f g::"'m::euclidean_space ⇒ 'n::euclidean_space"
  assumes "f absolutely_integrable_on s"
    and "g absolutely_integrable_on s"
  shows "(λx. (∑i∈Basis. min (f(x)∙i) (g(x)∙i) *R i)::'n) absolutely_integrable_on s"
proof -
  have *:"⋀x. (1 / 2) *R ((f x + g x) - (∑i∈Basis. ¦(f x - g x) ∙ i¦ *R i::'n)) =
      (∑i∈Basis. min (f(x)∙i) (g(x)∙i) *R i)"
    unfolding euclidean_eq_iff[where 'a='n] by (auto simp: inner_simps)

  note absolutely_integrable_add[OF assms] absolutely_integrable_sub[OF assms]
  note this(1) absolutely_integrable_vector_abs[OF this(2), where T="λx. x"]
  note absolutely_integrable_sub[OF this]
  note absolutely_integrable_cmul[OF this,of "1/2"]
  then show ?thesis unfolding * .
qed

lemma absolutely_integrable_abs_eq:
  fixes f::"'n::euclidean_space ⇒ 'm::euclidean_space"
  shows "f absolutely_integrable_on s ⟷ f integrable_on s ∧
    (λx. (∑i∈Basis. ¦f x∙i¦ *R i)::'m) integrable_on s"
  (is "?l = ?r")
proof
  assume ?l
  then show ?r
    apply -
    apply rule
    defer
    apply (drule absolutely_integrable_vector_abs)
    apply auto
    done
next
  assume ?r
  {
    presume lem: "⋀f::'n ⇒ 'm. f integrable_on UNIV ⟹
      (λx. (∑i∈Basis. ¦f x∙i¦ *R i)::'m) integrable_on UNIV ⟹
        f absolutely_integrable_on UNIV"
    have *: "⋀x. (∑i∈Basis. ¦(if x ∈ s then f x else 0) ∙ i¦ *R i) =
      (if x ∈ s then (∑i∈Basis. ¦f x ∙ i¦ *R i) else (0::'m))"
      unfolding euclidean_eq_iff[where 'a='m]
      by auto
    show ?l
      apply (subst absolutely_integrable_restrict_univ[symmetric])
      apply (rule lem)
      unfolding integrable_restrict_univ *
      using ‹?r›
      apply auto
      done
  }
  fix f :: "'n ⇒ 'm"
  assume assms: "f integrable_on UNIV" "(λx. (∑i∈Basis. ¦f x∙i¦ *R i)::'m) integrable_on UNIV"
  let ?B = "∑i∈Basis. integral UNIV (λx. (∑i∈Basis. ¦f x∙i¦ *R i)::'m) ∙ i"
  show "f absolutely_integrable_on UNIV"
    apply (rule bounded_variation_absolutely_integrable[OF assms(1), where B="?B"])
    apply safe
  proof goal_cases
    case d: (1 d)
    note d'=division_ofD[OF d]
    have "(∑k∈d. norm (integral k f)) ≤
      (∑k∈d. setsum (op ∙ (integral k (λx. (∑i∈Basis. ¦f x∙i¦ *R i)::'m))) Basis)"
      apply (rule setsum_mono)
      apply (rule order_trans[OF norm_le_l1])
      apply (rule setsum_mono)
      unfolding lessThan_iff
    proof -
      fix k
      fix i :: 'm
      assume "k ∈ d" and i: "i ∈ Basis"
      from d'(4)[OF this(1)] guess a b by (elim exE) note ab=this
      show "¦integral k f ∙ i¦ ≤ integral k (λx. (∑i∈Basis. ¦f x∙i¦ *R i)::'m) ∙ i"
        apply (rule abs_leI)
        unfolding inner_minus_left[symmetric]
        defer
        apply (subst integral_neg[symmetric])
        apply (rule_tac[1-2] integral_component_le[OF i])
        using integrable_on_subcbox[OF assms(1),of a b]
          integrable_on_subcbox[OF assms(2),of a b] i  integrable_neg
        unfolding ab
        apply auto
        done
    qed
    also have "… ≤ setsum (op ∙ (integral UNIV (λx. (∑i∈Basis. ¦f x∙i¦ *R i)::'m))) Basis"
      apply (subst setsum.commute)
      apply (rule setsum_mono)
    proof goal_cases
      case (1 j)
      have *: "(λx. ∑i∈Basis. ¦f x∙i¦ *R i::'m) integrable_on ⋃d"
        using integrable_on_subdivision[OF d assms(2)] by auto
      have "(∑i∈d. integral i (λx. ∑i∈Basis. ¦f x∙i¦ *R i::'m) ∙ j) =
        integral (⋃d) (λx. ∑i∈Basis. ¦f x∙i¦ *R i::'m) ∙ j"
        unfolding inner_setsum_left[symmetric] integral_combine_division_topdown[OF * d] ..
      also have "… ≤ integral UNIV (λx. ∑i∈Basis. ¦f x∙i¦ *R i::'m) ∙ j"
        apply (rule integral_subset_component_le)
        using assms * ‹j ∈ Basis›
        apply auto
        done
      finally show ?case .
    qed
    finally show ?case .
  qed
qed

lemma nonnegative_absolutely_integrable:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "∀x∈s. ∀i∈Basis. 0 ≤ f x ∙ i"
    and "f integrable_on s"
  shows "f absolutely_integrable_on s"
  unfolding absolutely_integrable_abs_eq
  apply rule
  apply (rule assms)thm integrable_eq
  apply (rule integrable_eq[of _ f])
  using assms
  apply (auto simp: euclidean_eq_iff[where 'a='m])
  done

lemma absolutely_integrable_integrable_bound:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "∀x∈s. norm (f x) ≤ g x"
    and "f integrable_on s"
    and "g integrable_on s"
  shows "f absolutely_integrable_on s"
proof -
  {
    presume *: "⋀f::'n ⇒ 'm. ⋀g. ∀x. norm (f x) ≤ g x ⟹ f integrable_on UNIV ⟹
      g integrable_on UNIV ⟹ f absolutely_integrable_on UNIV"
    show ?thesis
      apply (subst absolutely_integrable_restrict_univ[symmetric])
      apply (rule *[of _ "λx. if x∈s then g x else 0"])
      using assms
      unfolding integrable_restrict_univ
      apply auto
      done
  }
  fix g
  fix f :: "'n ⇒ 'm"
  assume assms: "∀x. norm (f x) ≤ g x" "f integrable_on UNIV" "g integrable_on UNIV"
  show "f absolutely_integrable_on UNIV"
    apply (rule bounded_variation_absolutely_integrable[OF assms(2),where B="integral UNIV g"])
    apply safe
  proof goal_cases
    case d: (1 d)
    note d'=division_ofD[OF d]
    have "(∑k∈d. norm (integral k f)) ≤ (∑k∈d. integral k g)"
      apply (rule setsum_mono)
      apply (rule integral_norm_bound_integral)
      apply (drule_tac[!] d'(4))
      apply safe
      apply (rule_tac[1-2] integrable_on_subcbox)
      using assms
      apply auto
      done
    also have "… = integral (⋃d) g"
      apply (rule integral_combine_division_bottomup[symmetric])
      apply (rule d)
      apply safe
      apply (drule d'(4))
      apply safe
      apply (rule integrable_on_subcbox[OF assms(3)])
      apply auto
      done
    also have "… ≤ integral UNIV g"
      apply (rule integral_subset_le)
      defer
      apply (rule integrable_on_subdivision[OF d,of _ UNIV])
      prefer 4
      apply rule
      apply (rule_tac y="norm (f x)" in order_trans)
      using assms
      apply auto
      done
    finally show ?case .
  qed
qed

lemma absolutely_integrable_absolutely_integrable_bound:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
    and g :: "'n::euclidean_space ⇒ 'p::euclidean_space"
  assumes "∀x∈s. norm (f x) ≤ norm (g x)"
    and "f integrable_on s"
    and "g absolutely_integrable_on s"
  shows "f absolutely_integrable_on s"
  apply (rule absolutely_integrable_integrable_bound[of s f "λx. norm (g x)"])
  using assms
  apply auto
  done

lemma absolutely_integrable_inf_real:
  assumes "finite k"
    and "k ≠ {}"
    and "∀i∈k. (λx. (fs x i)::real) absolutely_integrable_on s"
  shows "(λx. (Inf ((fs x) ` k))) absolutely_integrable_on s"
  using assms
proof induct
  case (insert a k)
  let ?P = "(λx.
    if fs x ` k = {} then fs x a
    else min (fs x a) (Inf (fs x ` k))) absolutely_integrable_on s"
  show ?case
    unfolding image_insert
    apply (subst Inf_insert_finite)
    apply (rule finite_imageI[OF insert(1)])
  proof (cases "k = {}")
    case True
    then show ?P
      apply (subst if_P)
      defer
      apply (rule insert(5)[rule_format])
      apply auto
      done
  next
    case False
    then show ?P
      apply (subst if_not_P)
      defer
      apply (rule absolutely_integrable_min[where 'n=real, unfolded Basis_real_def, simplified])
      defer
      apply(rule insert(3)[OF False])
      using insert(5)
      apply auto
      done
  qed
next
  case empty
  then show ?case by auto
qed

lemma absolutely_integrable_sup_real:
  assumes "finite k"
    and "k ≠ {}"
    and "∀i∈k. (λx. (fs x i)::real) absolutely_integrable_on s"
  shows "(λx. (Sup ((fs x) ` k))) absolutely_integrable_on s"
  using assms
proof induct
  case (insert a k)
  let ?P = "(λx.
    if fs x ` k = {} then fs x a
    else max (fs x a) (Sup (fs x ` k))) absolutely_integrable_on s"
  show ?case
    unfolding image_insert
    apply (subst Sup_insert_finite)
    apply (rule finite_imageI[OF insert(1)])
  proof (cases "k = {}")
    case True
    then show ?P
      apply (subst if_P)
      defer
      apply (rule insert(5)[rule_format])
      apply auto
      done
  next
    case False
    then show ?P
      apply (subst if_not_P)
      defer
      apply (rule absolutely_integrable_max[where 'n=real, unfolded Basis_real_def, simplified])
      defer
      apply (rule insert(3)[OF False])
      using insert(5)
      apply auto
      done
  qed
qed auto


subsection ‹differentiation under the integral sign›

lemma tube_lemma:
  assumes "compact K"
  assumes "open W"
  assumes "{x0} × K ⊆ W"
  shows "∃X0. x0 ∈ X0 ∧ open X0 ∧ X0 × K ⊆ W"
proof -
  {
    fix y assume "y ∈ K"
    then have "(x0, y) ∈ W" using assms by auto
    with ‹open W›
    have "∃X0 Y. open X0 ∧ open Y ∧ x0 ∈ X0 ∧ y ∈ Y ∧ X0 × Y ⊆ W"
      by (rule open_prod_elim) blast
  } then obtain X0 Y where
    "∀y ∈ K. open (X0 y) ∧ open (Y y) ∧ x0 ∈ X0 y ∧ y ∈ Y y ∧ X0 y × Y y ⊆ W"
    by metis
  moreover
  then have "∀t∈Y ` K. open t" "K ⊆ ⋃(Y ` K)" by auto
  with ‹compact K› obtain CC where "CC ⊆ Y ` K" "finite CC" "K ⊆ ⋃CC"
    by (rule compactE)
  moreover
  then obtain c where c:
    "⋀C. C ∈ CC ⟹ c C ∈ K ∧ C = Y (c C)"
    by (force intro!: choice)
  ultimately show ?thesis
    by (force intro!: exI[where x="⋂C∈CC. X0 (c C)"])
qed

lemma continuous_on_prod_compactE:
  fixes fx::"'a::topological_space × 'b::topological_space ⇒ 'c::metric_space"
    and e::real
  assumes cont_fx: "continuous_on (U × C) fx"
  assumes "compact C"
  assumes [intro]: "x0 ∈ U"
  notes [continuous_intros] = continuous_on_compose2[OF cont_fx]
  assumes "e > 0"
  obtains X0 where "x0 ∈ X0" "open X0"
    "∀x∈X0 ∩ U. ∀t ∈ C. dist (fx (x, t)) (fx (x0, t)) ≤ e"
proof -
  def psi  "λ(x, t). dist (fx (x, t)) (fx (x0, t))"
  def W0  "{(x, t) ∈ U × C. psi (x, t) < e}"
  have W0_eq: "W0 = psi -` {..<e} ∩ U × C"
    by (auto simp: vimage_def W0_def)
  have "open {..<e}" by simp
  have "continuous_on (U × C) psi"
    by (auto intro!: continuous_intros simp: psi_def split_beta')
  from this[unfolded continuous_on_open_invariant, rule_format, OF ‹open {..<e}›]
  obtain W where W: "open W" "W ∩ U × C = W0 ∩ U × C"
    unfolding W0_eq by blast
  have "{x0} × C ⊆ W ∩ U × C"
    unfolding W
    by (auto simp: W0_def psi_def ‹0 < e›)
  then have "{x0} × C ⊆ W" by blast
  from tube_lemma[OF ‹compact C› ‹open W› this]
  obtain X0 where X0: "x0 ∈ X0" "open X0" "X0 × C ⊆ W"
    by blast

  have "∀x∈X0 ∩ U. ∀t ∈ C. dist (fx (x, t)) (fx (x0, t)) ≤ e"
  proof safe
    fix x assume x: "x ∈ X0" "x ∈ U"
    fix t assume t: "t ∈ C"
    have "dist (fx (x, t)) (fx (x0, t)) = psi (x, t)"
      by (auto simp: psi_def)
    also
    {
      have "(x, t) ∈ X0 × C"
        using t x
        by auto
      also note ‹… ⊆ W›
      finally have "(x, t) ∈ W" .
      with t x have "(x, t) ∈ W ∩ U × C"
        by blast
      also note ‹W ∩ U × C = W0 ∩ U × C›
      finally  have "psi (x, t) < e"
        by (auto simp: W0_def)
    }
    finally show "dist (fx (x, t)) (fx (x0, t)) ≤ e" by simp
  qed
  from X0(1,2) this show ?thesis ..
qed

lemma integral_continuous_on_param:
  fixes f::"'a::topological_space ⇒ 'b::euclidean_space ⇒ 'c::banach"
  assumes cont_fx: "continuous_on (U × cbox a b) (λ(x, t). f x t)"
  shows "continuous_on U (λx. integral (cbox a b) (f x))"
proof cases
  assume "content (cbox a b) ≠ 0"
  then have ne: "cbox a b ≠ {}" by auto

  note [continuous_intros] =
    continuous_on_compose2[OF cont_fx, where f="λy. Pair x y" for x,
      unfolded split_beta fst_conv snd_conv]

  show ?thesis
    unfolding continuous_on_def
  proof (safe intro!: tendstoI)
    fix e'::real and x
    assume "e' > 0"
    def e  "e' / (content (cbox a b) + 1)"
    have "e > 0" using ‹e' > 0› by (auto simp: e_def intro!: divide_pos_pos add_nonneg_pos)
    assume "x ∈ U"
    from continuous_on_prod_compactE[OF cont_fx compact_cbox ‹x ∈ U› ‹0 < e›]
    obtain X0 where X0: "x ∈ X0" "open X0"
      and fx_bound: "⋀y t. y ∈ X0 ∩ U ⟹ t ∈ cbox a b ⟹ norm (f y t - f x t) ≤ e"
      unfolding split_beta fst_conv snd_conv dist_norm
      by metis
    have "∀F y in at x within U. y ∈ X0 ∩ U"
      using X0(1) X0(2) eventually_at_topological by auto
    then show "∀F y in at x within U. dist (integral (cbox a b) (f y)) (integral (cbox a b) (f x)) < e'"
    proof eventually_elim
      case (elim y)
      have "dist (integral (cbox a b) (f y)) (integral (cbox a b) (f x)) =
        norm (integral (cbox a b) (λt. f y t - f x t))"
        using elim ‹x ∈ U›
        unfolding dist_norm
        by (subst integral_diff)
           (auto intro!: integrable_continuous continuous_intros)
      also have "… ≤ e * content (cbox a b)"
        using elim ‹x ∈ U›
        by (intro integrable_bound)
           (auto intro!: fx_bound ‹x ∈ U › less_imp_le[OF ‹0 < e›]
              integrable_continuous continuous_intros)
      also have "… < e'"
        using ‹0 < e'› ‹e > 0›
        by (auto simp: e_def divide_simps)
      finally show "dist (integral (cbox a b) (f y)) (integral (cbox a b) (f x)) < e'" .
    qed
  qed
qed (auto intro!: continuous_on_const)

lemma eventually_closed_segment:
  fixes x0::"'a::real_normed_vector"
  assumes "open X0" "x0 ∈ X0"
  shows "∀F x in at x0 within U. closed_segment x0 x ⊆ X0"
proof -
  from openE[OF assms]
  obtain e where e: "0 < e" "ball x0 e ⊆ X0" .
  then have "∀F x in at x0 within U. x ∈ ball x0 e"
    by (auto simp: dist_commute eventually_at)
  then show ?thesis
  proof eventually_elim
    case (elim x)
    have "x0 ∈ ball x0 e" using ‹e > 0› by simp
    from convex_ball[unfolded convex_contains_segment, rule_format, OF this elim]
    have "closed_segment x0 x ⊆ ball x0 e" .
    also note ‹… ⊆ X0›
    finally show ?case .
  qed
qed

lemma leibniz_rule:
  fixes f::"'a::banach ⇒ 'b::euclidean_space ⇒ 'c::banach"
  assumes fx: "⋀x t. x ∈ U ⟹ t ∈ cbox a b ⟹
    ((λx. f x t) has_derivative blinfun_apply (fx x t)) (at x within U)"
  assumes integrable_f2: "⋀x. x ∈ U ⟹ f x integrable_on cbox a b"
  assumes cont_fx: "continuous_on (U × (cbox a b)) (λ(x, t). fx x t)"
  assumes [intro]: "x0 ∈ U"
  assumes "convex U"
  shows
    "((λx. integral (cbox a b) (f x)) has_derivative integral (cbox a b) (fx x0)) (at x0 within U)"
    (is "(?F has_derivative ?dF) _")
proof cases
  assume "content (cbox a b) ≠ 0"
  then have ne: "cbox a b ≠ {}" by auto
  note [continuous_intros] =
    continuous_on_compose2[OF cont_fx, where f="λy. Pair x y" for x,
      unfolded split_beta fst_conv snd_conv]
  show ?thesis
  proof (intro has_derivativeI bounded_linear_scaleR_left tendstoI, fold norm_conv_dist)
    have cont_f1: "⋀t. t ∈ cbox a b ⟹ continuous_on U (λx. f x t)"
      by (auto simp: continuous_on_eq_continuous_within intro!: has_derivative_continuous fx)
    note [continuous_intros] = continuous_on_compose2[OF cont_f1]
    fix e'::real
    assume "e' > 0"
    def e  "e' / (content (cbox a b) + 1)"
    have "e > 0" using ‹e' > 0› by (auto simp: e_def intro!: divide_pos_pos add_nonneg_pos)
    from continuous_on_prod_compactE[OF cont_fx compact_cbox ‹x0 ∈ U› ‹e > 0›]
    obtain X0 where X0: "x0 ∈ X0" "open X0"
      and fx_bound: "⋀x t. x ∈ X0 ∩ U ⟹ t ∈ cbox a b ⟹ norm (fx x t - fx x0 t) ≤ e"
      unfolding split_beta fst_conv snd_conv
      by (metis dist_norm)

    note eventually_closed_segment[OF ‹open X0› ‹x0 ∈ X0›, of U]
    moreover
    have "∀F x in at x0 within U. x ∈ X0"
      using ‹open X0› ‹x0 ∈ X0› eventually_at_topological by blast
    moreover have "∀F x in at x0 within U. x ≠ x0"
      by (auto simp: eventually_at_filter)
    moreover have "∀F x in at x0 within U. x ∈ U"
      by (auto simp: eventually_at_filter)
    ultimately
    show "∀F x in at x0 within U. norm ((?F x - ?F x0 - ?dF (x - x0)) /R norm (x - x0)) < e'"
    proof eventually_elim
      case (elim x)
      from elim have "0 < norm (x - x0)" by simp
      have "closed_segment x0 x ⊆ U"
        by (rule ‹convex U›[unfolded convex_contains_segment, rule_format, OF ‹x0 ∈ U› ‹x ∈ U›])
      from elim have [intro]: "x ∈ U" by auto

      have "?F x - ?F x0 - ?dF (x - x0) =
        integral (cbox a b) (λy. f x y - f x0 y - fx x0 y (x - x0))"
        (is "_ = ?id")
        using ‹x ≠ x0›
        by (subst blinfun_apply_integral integral_diff,
            auto intro!: integrable_diff integrable_f2 continuous_intros
              intro: integrable_continuous)+
      also
      {
        fix t assume t: "t ∈ (cbox a b)"
        have seg: "⋀t. t ∈ {0..1} ⟹ x0 + t *R (x - x0) ∈ X0 ∩ U"
          using ‹closed_segment x0 x ⊆ U›
            ‹closed_segment x0 x ⊆ X0›
          by (force simp: closed_segment_def algebra_simps)
        from t have deriv:
          "((λx. f x t) has_derivative (fx y t)) (at y within X0 ∩ U)"
          if "y ∈ X0 ∩ U" for y
          unfolding has_vector_derivative_def[symmetric]
          using that ‹x ∈ X0›
          by (intro has_derivative_within_subset[OF fx]) auto
        have "∀x ∈ X0 ∩ U. onorm (blinfun_apply (fx x t) - (fx x0 t)) ≤ e"
          using fx_bound t
          by (auto simp add: norm_blinfun_def fun_diff_def blinfun.bilinear_simps[symmetric])
        from differentiable_bound_linearization[OF seg deriv this] X0
        have "norm (f x t - f x0 t - fx x0 t (x - x0)) ≤ e * norm (x - x0)"
          by (auto simp add: ac_simps)
      }
      then have "norm ?id ≤ integral (cbox a b) (λ_. e * norm (x - x0))"
        by (intro integral_norm_bound_integral)
          (auto intro!: continuous_intros integrable_diff integrable_f2
            intro: integrable_continuous)
      also have "… = content (cbox a b) * e * norm (x - x0)"
        by simp
      also have "… < e' * norm (x - x0)"
        using ‹e' > 0› content_pos_le[of a b]
        by (intro mult_strict_right_mono[OF _ ‹0 < norm (x - x0)›])
          (auto simp: divide_simps e_def)
      finally have "norm (?F x - ?F x0 - ?dF (x - x0)) < e' * norm (x - x0)" .
      then show ?case
        by (auto simp: divide_simps)
    qed
  qed (rule blinfun.bounded_linear_right)
qed (auto intro!: derivative_eq_intros simp: blinfun.bilinear_simps)

lemma
  has_vector_derivative_eq_has_derivative_blinfun:
  "(f has_vector_derivative f') (at x within U) ⟷
    (f has_derivative blinfun_scaleR_left f') (at x within U)"
  by (simp add: has_vector_derivative_def)

lemma leibniz_rule_vector_derivative:
  fixes f::"real ⇒ 'b::euclidean_space ⇒ 'c::banach"
  assumes fx: "⋀x t. x ∈ U ⟹ t ∈ cbox a b ⟹
      ((λx. f x t) has_vector_derivative (fx x t)) (at x within U)"
  assumes integrable_f2: "⋀x. x ∈ U ⟹ (f x) integrable_on cbox a b"
  assumes cont_fx: "continuous_on (U × cbox a b) (λ(x, t). fx x t)"
  assumes U: "x0 ∈ U" "convex U"
  shows "((λx. integral (cbox a b) (f x)) has_vector_derivative integral (cbox a b) (fx x0))
      (at x0 within U)"
proof -
  note [continuous_intros] =
    continuous_on_compose2[OF cont_fx, where f="λy. Pair x y" for x,
      unfolded split_beta fst_conv snd_conv]
  have *: "blinfun_scaleR_left (integral (cbox a b) (fx x0)) =
    integral (cbox a b) (λt. blinfun_scaleR_left (fx x0 t))"
    by (subst integral_linear[symmetric])
       (auto simp: has_vector_derivative_def o_def
         intro!: integrable_continuous U continuous_intros bounded_linear_intros)
  show ?thesis
    unfolding has_vector_derivative_eq_has_derivative_blinfun
    apply (rule has_derivative_eq_rhs)
    apply (rule leibniz_rule[OF _ integrable_f2 _ U, where fx="λx t. blinfun_scaleR_left (fx x t)"])
    using fx cont_fx
    apply (auto simp: has_vector_derivative_def * split_beta intro!: continuous_intros)
    done
qed

lemma
  has_field_derivative_eq_has_derivative_blinfun:
  "(f has_field_derivative f') (at x within U) ⟷ (f has_derivative blinfun_mult_right f') (at x within U)"
  by (simp add: has_field_derivative_def)

lemma leibniz_rule_field_derivative:
  fixes f::"'a::{real_normed_field, banach} ⇒ 'b::euclidean_space ⇒ 'a"
  assumes fx: "⋀x t. x ∈ U ⟹ t ∈ cbox a b ⟹ ((λx. f x t) has_field_derivative fx x t) (at x within U)"
  assumes integrable_f2: "⋀x. x ∈ U ⟹ (f x) integrable_on cbox a b"
  assumes cont_fx: "continuous_on (U × (cbox a b)) (λ(x, t). fx x t)"
  assumes U: "x0 ∈ U" "convex U"
  shows "((λx. integral (cbox a b) (f x)) has_field_derivative integral (cbox a b) (fx x0)) (at x0 within U)"
proof -
  note [continuous_intros] =
    continuous_on_compose2[OF cont_fx, where f="λy. Pair x y" for x,
      unfolded split_beta fst_conv snd_conv]
  have *: "blinfun_mult_right (integral (cbox a b) (fx x0)) =
    integral (cbox a b) (λt. blinfun_mult_right (fx x0 t))"
    by (subst integral_linear[symmetric])
      (auto simp: has_vector_derivative_def o_def
        intro!: integrable_continuous U continuous_intros bounded_linear_intros)
  show ?thesis
    unfolding has_field_derivative_eq_has_derivative_blinfun
    apply (rule has_derivative_eq_rhs)
    apply (rule leibniz_rule[OF _ integrable_f2 _ U, where fx="λx t. blinfun_mult_right (fx x t)"])
    using fx cont_fx
    apply (auto simp: has_field_derivative_def * split_beta intro!: continuous_intros)
    done
qed


subsection ‹Exchange uniform limit and integral›

lemma
  uniform_limit_integral:
  fixes f::"'a ⇒ 'b::euclidean_space ⇒ 'c::banach"
  assumes u: "uniform_limit (cbox a b) f g F"
  assumes c: "⋀n. continuous_on (cbox a b) (f n)"
  assumes [simp]: "F ≠ bot"
  obtains I J where
    "⋀n. (f n has_integral I n) (cbox a b)"
    "(g has_integral J) (cbox a b)"
    "(I ⤏ J) F"
proof -
  have fi[simp]: "f n integrable_on (cbox a b)" for n
    by (auto intro!: integrable_continuous assms)
  then obtain I where I: "⋀n. (f n has_integral I n) (cbox a b)"
    by atomize_elim (auto simp: integrable_on_def intro!: choice)

  moreover

  have gi[simp]: "g integrable_on (cbox a b)"
    by (auto intro!: integrable_continuous uniform_limit_theorem[OF _ u] eventuallyI c)
  then obtain J where J: "(g has_integral J) (cbox a b)"
    by blast

  moreover

  have "(I ⤏ J) F"
  proof cases
    assume "content (cbox a b) = 0"
    hence "I = (λ_. 0)" "J = 0"
      by (auto intro!: has_integral_unique I J)
    thus ?thesis by simp
  next
    assume content_nonzero: "content (cbox a b) ≠ 0"
    show ?thesis
    proof (rule tendstoI)
      fix e::real
      assume "e > 0"
      def e'  "e / 2"
      with ‹e > 0› have "e' > 0" by simp
      then have "∀F n in F. ∀x∈cbox a b. norm (f n x - g x) < e' / content (cbox a b)"
        using u content_nonzero content_pos_le[of a b]
        by (auto simp: uniform_limit_iff dist_norm)
      then show "∀F n in F. dist (I n) J < e"
      proof eventually_elim
        case (elim n)
        have "I n = integral (cbox a b) (f n)"
            "J = integral (cbox a b) g"
          using I[of n] J by (simp_all add: integral_unique)
        then have "dist (I n) J = norm (integral (cbox a b) (λx. f n x - g x))"
          by (simp add: integral_diff dist_norm)
        also have "… ≤ integral (cbox a b) (λx. (e' / content (cbox a b)))"
          using elim
          by (intro integral_norm_bound_integral)
            (auto intro!: integrable_diff absolutely_integrable_onI)
        also have "… < e"
          using ‹0 < e›
          by (simp add: e'_def)
        finally show ?case .
      qed
    qed
  qed
  ultimately show ?thesis ..
qed


subsection ‹Dominated convergence›

(* GENERALIZE the following theorems *)

lemma dominated_convergence:
  fixes f :: "nat ⇒ 'n::euclidean_space ⇒ real"
  assumes "⋀k. (f k) integrable_on s" "h integrable_on s"
    and "⋀k. ∀x ∈ s. norm (f k x) ≤ h x"
    and "∀x ∈ s. ((λk. f k x) ⤏ g x) sequentially"
  shows "g integrable_on s"
    and "((λk. integral s (f k)) ⤏ integral s g) sequentially"
proof -
  have bdd_below[simp]: "⋀x P. x ∈ s ⟹ bdd_below {f n x |n. P n}"
  proof (safe intro!: bdd_belowI)
    fix n x show "x ∈ s ⟹ - h x ≤ f n x"
      using assms(3)[rule_format, of x n] by simp
  qed
  have bdd_above[simp]: "⋀x P. x ∈ s ⟹ bdd_above {f n x |n. P n}"
  proof (safe intro!: bdd_aboveI)
    fix n x show "x ∈ s ⟹ f n x ≤ h x"
      using assms(3)[rule_format, of x n] by simp
  qed

  have "⋀m. (λx. Inf {f j x |j. m ≤ j}) integrable_on s ∧
    ((λk. integral s (λx. Inf {f j x |j. j ∈ {m..m + k}})) ⤏
    integral s (λx. Inf {f j x |j. m ≤ j}))sequentially"
  proof (rule monotone_convergence_decreasing, safe)
    fix m :: nat
    show "bounded {integral s (λx. Inf {f j x |j. j ∈ {m..m + k}}) |k. True}"
      unfolding bounded_iff
      apply (rule_tac x="integral s h" in exI)
    proof safe
      fix k :: nat
      show "norm (integral s (λx. Inf {f j x |j. j ∈ {m..m + k}})) ≤ integral s h"
        apply (rule integral_norm_bound_integral)
        unfolding simple_image
        apply (rule absolutely_integrable_onD)
        apply (rule absolutely_integrable_inf_real)
        prefer 5
        unfolding real_norm_def
        apply rule
        apply (rule cInf_abs_ge)
        prefer 5
        apply rule
        apply (rule_tac g = h in absolutely_integrable_integrable_bound)
        using assms
        unfolding real_norm_def
        apply auto
        done
    qed
    fix k :: nat
    show "(λx. Inf {f j x |j. j ∈ {m..m + k}}) integrable_on s"
      unfolding simple_image
      apply (rule absolutely_integrable_onD)
      apply (rule absolutely_integrable_inf_real)
      prefer 3
      using absolutely_integrable_integrable_bound[OF assms(3,1,2)]
      apply auto
      done
    fix x
    assume x: "x ∈ s"
    show "Inf {f j x |j. j ∈ {m..m + Suc k}} ≤ Inf {f j x |j. j ∈ {m..m + k}}"
      by (rule cInf_superset_mono) auto
    let ?S = "{f j x| j. m ≤ j}"
    show "((λk. Inf {f j x |j. j ∈ {m..m + k}}) ⤏ Inf ?S) sequentially"
    proof (rule LIMSEQ_I, goal_cases)
      case r: (1 r)

      have "∃y∈?S. y < Inf ?S + r"
        by (subst cInf_less_iff[symmetric]) (auto simp: ‹x∈s› r)
      then obtain N where N: "f N x < Inf ?S + r" "m ≤ N"
        by blast

      show ?case
        apply (rule_tac x=N in exI)
        apply safe
      proof goal_cases
        case prems: (1 n)
        have *: "⋀y ix. y < Inf ?S + r ⟶ Inf ?S ≤ ix ⟶ ix ≤ y ⟶ ¦ix - Inf ?S¦ < r"
          by arith
        show ?case
          unfolding real_norm_def
            apply (rule *[rule_format, OF N(1)])
            apply (rule cInf_superset_mono, auto simp: ‹x∈s›) []
            apply (rule cInf_lower)
            using N prems
            apply auto []
            apply simp
            done
      qed
    qed
  qed
  note dec1 = conjunctD2[OF this]

  have "⋀m. (λx. Sup {f j x |j. m ≤ j}) integrable_on s ∧
    ((λk. integral s (λx. Sup {f j x |j. j ∈ {m..m + k}})) ⤏
    integral s (λx. Sup {f j x |j. m ≤ j})) sequentially"
  proof (rule monotone_convergence_increasing,safe)
    fix m :: nat
    show "bounded {integral s (λx. Sup {f j x |j. j ∈ {m..m + k}}) |k. True}"
      unfolding bounded_iff
      apply (rule_tac x="integral s h" in exI)
    proof safe
      fix k :: nat
      show "norm (integral s (λx. Sup {f j x |j. j ∈ {m..m + k}})) ≤ integral s h"
        apply (rule integral_norm_bound_integral) unfolding simple_image
        apply (rule absolutely_integrable_onD)
        apply(rule absolutely_integrable_sup_real)
        prefer 5 unfolding real_norm_def
        apply rule
        apply (rule cSup_abs_le)
        using assms
        apply (force simp add: )
        prefer 4
        apply rule
        apply (rule_tac g=h in absolutely_integrable_integrable_bound)
        using assms
        unfolding real_norm_def
        apply auto
        done
    qed
    fix k :: nat
    show "(λx. Sup {f j x |j. j ∈ {m..m + k}}) integrable_on s"
      unfolding simple_image
      apply (rule absolutely_integrable_onD)
      apply (rule absolutely_integrable_sup_real)
      prefer 3
      using absolutely_integrable_integrable_bound[OF assms(3,1,2)]
      apply auto
      done
    fix x
    assume x: "x∈s"
    show "Sup {f j x |j. j ∈ {m..m + Suc k}} ≥ Sup {f j x |j. j ∈ {m..m + k}}"
      by (rule cSup_subset_mono) auto
    let ?S = "{f j x| j. m ≤ j}"
    show "((λk. Sup {f j x |j. j ∈ {m..m + k}}) ⤏ Sup ?S) sequentially"
    proof (rule LIMSEQ_I, goal_cases)
      case r: (1 r)
      have "∃y∈?S. Sup ?S - r < y"
        by (subst less_cSup_iff[symmetric]) (auto simp: r ‹x∈s›)
      then obtain N where N: "Sup ?S - r < f N x" "m ≤ N"
        by blast

      show ?case
        apply (rule_tac x=N in exI)
        apply safe
      proof goal_cases
        case prems: (1 n)
        have *: "⋀y ix. Sup ?S - r < y ⟶ ix ≤ Sup ?S ⟶ y ≤ ix ⟶ ¦ix - Sup ?S¦ < r"
          by arith
        show ?case
          apply simp
          apply (rule *[rule_format, OF N(1)])
          apply (rule cSup_subset_mono, auto simp: ‹x∈s›) []
          apply (subst cSup_upper)
          using N prems
          apply auto
          done
      qed
    qed
  qed
  note inc1 = conjunctD2[OF this]

  have "g integrable_on s ∧
    ((λk. integral s (λx. Inf {f j x |j. k ≤ j})) ⤏ integral s g) sequentially"
    apply (rule monotone_convergence_increasing,safe)
    apply fact
  proof -
    show "bounded {integral s (λx. Inf {f j x |j. k ≤ j}) |k. True}"
      unfolding bounded_iff apply(rule_tac x="integral s h" in exI)
    proof safe
      fix k :: nat
      show "norm (integral s (λx. Inf {f j x |j. k ≤ j})) ≤ integral s h"
        apply (rule integral_norm_bound_integral)
        apply fact+
        unfolding real_norm_def
        apply rule
        apply (rule cInf_abs_ge)
        using assms(3)
        apply auto
        done
    qed
    fix k :: nat and x
    assume x: "x ∈ s"

    have *: "⋀x y::real. x ≥ - y ⟹ - x ≤ y" by auto
    show "Inf {f j x |j. k ≤ j} ≤ Inf {f j x |j. Suc k ≤ j}"
      by (intro cInf_superset_mono) (auto simp: ‹x∈s›)

    show "(λk::nat. Inf {f j x |j. k ≤ j}) ⇢ g x"
    proof (rule LIMSEQ_I, goal_cases)
      case r: (1 r)
      then have "0<r/2"
        by auto
      from assms(4)[THEN bspec, THEN LIMSEQ_D, OF x this] guess N .. note N = this
      show ?case
        apply (rule_tac x=N in exI)
        apply safe
        unfolding real_norm_def
        apply (rule le_less_trans[of _ "r/2"])
        apply (rule cInf_asclose)
        apply safe
        defer
        apply (rule less_imp_le)
        using N r
        apply auto
        done
    qed
  qed
  note inc2 = conjunctD2[OF this]

  have "g integrable_on s ∧
    ((λk. integral s (λx. Sup {f j x |j. k ≤ j})) ⤏ integral s g) sequentially"
    apply (rule monotone_convergence_decreasing,safe)
    apply fact
  proof -
    show "bounded {integral s (λx. Sup {f j x |j. k ≤ j}) |k. True}"
      unfolding bounded_iff
      apply (rule_tac x="integral s h" in exI)
    proof safe
      fix k :: nat
      show "norm (integral s (λx. Sup {f j x |j. k ≤ j})) ≤ integral s h"
        apply (rule integral_norm_bound_integral)
        apply fact+
        unfolding real_norm_def
        apply rule
        apply (rule cSup_abs_le)
        using assms(3)
        apply auto
        done
    qed
    fix k :: nat
    fix x
    assume x: "x ∈ s"

    show "Sup {f j x |j. k ≤ j} ≥ Sup {f j x |j. Suc k ≤ j}"
      by (rule cSup_subset_mono) (auto simp: ‹x∈s›)
    show "((λk. Sup {f j x |j. k ≤ j}) ⤏ g x) sequentially"
    proof (rule LIMSEQ_I, goal_cases)
      case r: (1 r)
      then have "0<r/2"
        by auto
      from assms(4)[THEN bspec, THEN LIMSEQ_D, OF x this] guess N .. note N=this
      show ?case
        apply (rule_tac x=N in exI,safe)
        unfolding real_norm_def
        apply (rule le_less_trans[of _ "r/2"])
        apply (rule cSup_asclose)
        apply safe
        defer
        apply (rule less_imp_le)
        using N r
        apply auto
        done
    qed
  qed
  note dec2 = conjunctD2[OF this]

  show "g integrable_on s" by fact
  show "((λk. integral s (f k)) ⤏ integral s g) sequentially"
  proof (rule LIMSEQ_I, goal_cases)
    case r: (1 r)
    from LIMSEQ_D [OF inc2(2) r] guess N1 .. note N1=this[unfolded real_norm_def]
    from LIMSEQ_D [OF dec2(2) r] guess N2 .. note N2=this[unfolded real_norm_def]
    show ?case
    proof (rule_tac x="N1+N2" in exI, safe)
      fix n
      assume n: "n ≥ N1 + N2"
      have *: "⋀i0 i i1 g. ¦i0 - g¦ < r ⟶ ¦i1 - g¦ < r ⟶ i0 ≤ i ⟶ i ≤ i1 ⟶ ¦i - g¦ < r"
        by arith
      show "norm (integral s (f n) - integral s g) < r"
        unfolding real_norm_def
      proof (rule *[rule_format,OF N1[rule_format] N2[rule_format], of n n])
        show "integral s (λx. Inf {f j x |j. n ≤ j}) ≤ integral s (f n)"
          by (rule integral_le[OF dec1(1) assms(1)]) (auto intro!: cInf_lower)
        show "integral s (f n) ≤ integral s (λx. Sup {f j x |j. n ≤ j})"
          by (rule integral_le[OF assms(1) inc1(1)]) (auto intro!: cSup_upper)
      qed (insert n, auto)
    qed
  qed
qed

lemma has_integral_dominated_convergence:
  fixes f :: "nat ⇒ 'n::euclidean_space ⇒ real"
  assumes "⋀k. (f k has_integral y k) s" "h integrable_on s"
    "⋀k. ∀x∈s. norm (f k x) ≤ h x" "∀x∈s. (λk. f k x) ⇢ g x"
    and x: "y ⇢ x"
  shows "(g has_integral x) s"
proof -
  have int_f: "⋀k. (f k) integrable_on s"
    using assms by (auto simp: integrable_on_def)
  have "(g has_integral (integral s g)) s"
    by (intro integrable_integral dominated_convergence[OF int_f assms(2)]) fact+
  moreover have "integral s g = x"
  proof (rule LIMSEQ_unique)
    show "(λi. integral s (f i)) ⇢ x"
      using integral_unique[OF assms(1)] x by simp
    show "(λi. integral s (f i)) ⇢ integral s g"
      by (intro dominated_convergence[OF int_f assms(2)]) fact+
  qed
  ultimately show ?thesis
    by simp
qed

subsection‹Compute a double integral using iterated integrals and switching the order of integration›

lemma setcomp_dot1: "{z. P (z ∙ (i,0))} = {(x,y). P(x ∙ i)}"
  by auto

lemma setcomp_dot2: "{z. P (z ∙ (0,i))} = {(x,y). P(y ∙ i)}"
  by auto

lemma Sigma_Int_Paircomp1: "(Sigma A B) ∩ {(x, y). P x} = Sigma (A ∩ {x. P x}) B"
  by blast

lemma Sigma_Int_Paircomp2: "(Sigma A B) ∩ {(x, y). P y} = Sigma A (λz. B z ∩ {y. P y})"
  by blast

lemma continuous_on_imp_integrable_on_Pair1:
  fixes f :: "_ ⇒ 'b::banach"
  assumes con: "continuous_on (cbox (a,c) (b,d)) f" and x: "x ∈ cbox a b"
  shows "(λy. f (x, y)) integrable_on (cbox c d)"
proof -
  have "f ∘ (λy. (x, y)) integrable_on (cbox c d)"
    apply (rule integrable_continuous)
    apply (rule continuous_on_compose [OF _ continuous_on_subset [OF con]])
    using x
    apply (auto intro: continuous_on_Pair continuous_on_const continuous_on_id continuous_on_subset con)
    done
  then show ?thesis
    by (simp add: o_def)
qed

lemma integral_integrable_2dim:
  fixes f :: "('a::euclidean_space * 'b::euclidean_space) ⇒ 'c::banach"
  assumes "continuous_on (cbox (a,c) (b,d)) f"
    shows "(λx. integral (cbox c d) (λy. f (x,y))) integrable_on cbox a b"
proof (cases "content(cbox c d) = 0")
case True
  then show ?thesis
    by (simp add: True integrable_const)
next
  case False
  have uc: "uniformly_continuous_on (cbox (a,c) (b,d)) f"
    by (simp add: assms compact_cbox compact_uniformly_continuous)
  { fix x::'a and e::real
    assume x: "x ∈ cbox a b" and e: "0 < e"
    then have e2_gt: "0 < e / 2 / content (cbox c d)" and e2_less: "e / 2 / content (cbox c d) * content (cbox c d) < e"
      by (auto simp: False content_lt_nz e)
    then obtain dd
    where dd: "⋀x x'. ⟦x∈cbox (a, c) (b, d); x'∈cbox (a, c) (b, d); norm (x' - x) < dd⟧
                       ⟹ norm (f x' - f x) ≤ e / (2 * content (cbox c d))"  "dd>0"
      using uc [unfolded uniformly_continuous_on_def, THEN spec, of "e / (2 * content (cbox c d))"]
      by (auto simp: dist_norm intro: less_imp_le)
    have "∃delta>0. ∀x'∈cbox a b. norm (x' - x) < delta ⟶ norm (integral (cbox c d) (λu. f (x', u) - f (x, u))) < e"
      apply (rule_tac x=dd in exI)
      using dd e2_gt assms x
      apply clarify
      apply (rule le_less_trans [OF _ e2_less])
      apply (rule integrable_bound)
      apply (auto intro: integrable_diff continuous_on_imp_integrable_on_Pair1)
      done
  } note * = this
  show ?thesis
    apply (rule integrable_continuous)
    apply (simp add: * continuous_on_iff dist_norm integral_diff [symmetric] continuous_on_imp_integrable_on_Pair1 [OF assms])
    done
qed

lemma norm_diff2: "⟦y = y1 + y2; x = x1 + x2; e = e1 + e2; norm(y1 - x1) ≤ e1; norm(y2 - x2) ≤ e2⟧
            ⟹ norm(y - x) ≤ e"
using norm_triangle_mono [of "y1 - x1" "e1" "y2 - x2" "e2"]
  by (simp add: add_diff_add)

lemma integral_split:
  fixes f :: "'a::euclidean_space ⇒ 'b::{real_normed_vector,complete_space}"
  assumes f: "f integrable_on (cbox a b)"
      and k: "k ∈ Basis"
  shows "integral (cbox a b) f =
           integral (cbox a b ∩ {x. x∙k ≤ c}) f +
           integral (cbox a b ∩ {x. x∙k ≥ c}) f"
  apply (rule integral_unique [OF has_integral_split [where c=c]])
  using k f
  apply (auto simp: has_integral_integral [symmetric])
  done

lemma integral_swap_operative:
  fixes f :: "('a::euclidean_space * 'b::euclidean_space) ⇒ 'c::banach"
  assumes f: "continuous_on s f" and e: "0 < e"
    shows "operative(op ∧)
           (λk. ∀a b c d.
                cbox (a,c) (b,d) ⊆ k ∧ cbox (a,c) (b,d) ⊆ s
                ⟶ norm(integral (cbox (a,c) (b,d)) f -
                         integral (cbox a b) (λx. integral (cbox c d) (λy. f((x,y)))))
                    ≤ e * content (cbox (a,c) (b,d)))"
proof (auto simp: operative_def)
  fix a::'a and c::'b and b::'a and d::'b and u::'a and v::'a and w::'b and z::'b
  assume c0: "content (cbox (a, c) (b, d)) = 0"
     and cb1: "cbox (u, w) (v, z) ⊆ cbox (a, c) (b, d)"
     and cb2: "cbox (u, w) (v, z) ⊆ s"
  have c0': "content (cbox (u, w) (v, z)) = 0"
    by (fact content_0_subset [OF c0 cb1])
  show "norm (integral (cbox (u,w) (v,z)) f - integral (cbox u v) (λx. integral (cbox w z) (λy. f (x, y))))
          ≤ e * content (cbox (u,w) (v,z))"
    using content_cbox_pair_eq0_D [OF c0']
    by (force simp add: c0')
next
  fix a::'a and c::'b and b::'a and d::'b
  and M::real and i::'a and j::'b
  and u::'a and v::'a and w::'b and z::'b
  assume ij: "(i,j) ∈ Basis"
     and n1: "∀a' b' c' d'.
                cbox (a',c') (b',d') ⊆ cbox (a,c) (b,d) ∧
                cbox (a',c') (b',d') ⊆ {x. x ∙ (i,j) ≤ M} ∧ cbox (a',c') (b',d') ⊆ s ⟶
                norm (integral (cbox (a',c') (b',d')) f - integral (cbox a' b') (λx. integral (cbox c' d') (λy. f (x,y))))
                ≤ e * content (cbox (a',c') (b',d'))"
     and n2: "∀a' b' c' d'.
                cbox (a',c') (b',d') ⊆ cbox (a,c) (b,d) ∧
                cbox (a',c') (b',d') ⊆ {x. M ≤ x ∙ (i,j)} ∧ cbox (a',c') (b',d') ⊆ s ⟶
                norm (integral (cbox (a',c') (b',d')) f - integral (cbox a' b') (λx. integral (cbox c' d') (λy. f (x,y))))
                ≤ e * content (cbox (a',c') (b',d'))"
     and subs: "cbox (u,w) (v,z) ⊆ cbox (a,c) (b,d)"  "cbox (u,w) (v,z) ⊆ s"
  have fcont: "continuous_on (cbox (u, w) (v, z)) f"
    using assms(1) continuous_on_subset  subs(2) by blast
  then have fint: "f integrable_on cbox (u, w) (v, z)"
    by (metis integrable_continuous)
  consider "i ∈ Basis" "j=0" | "j ∈ Basis" "i=0"  using ij
    by (auto simp: Euclidean_Space.Basis_prod_def)
  then show "norm (integral (cbox (u,w) (v,z)) f - integral (cbox u v) (λx. integral (cbox w z) (λy. f (x,y))))
             ≤ e * content (cbox (u,w) (v,z))" (is ?normle)
  proof cases
    case 1
    then have e: "e * content (cbox (u, w) (v, z)) =
                  e * (content (cbox u v ∩ {x. x ∙ i ≤ M}) * content (cbox w z)) +
                  e * (content (cbox u v ∩ {x. M ≤ x ∙ i}) * content (cbox w z))"
      by (simp add: content_split [where c=M] content_Pair algebra_simps)
    have *: "integral (cbox u v) (λx. integral (cbox w z) (λy. f (x, y))) =
                integral (cbox u v ∩ {x. x ∙ i ≤ M}) (λx. integral (cbox w z) (λy. f (x, y))) +
                integral (cbox u v ∩ {x. M ≤ x ∙ i}) (λx. integral (cbox w z) (λy. f (x, y)))"
      using 1 f subs integral_integrable_2dim continuous_on_subset
      by (blast intro: integral_split)
    show ?normle
      apply (rule norm_diff2 [OF integral_split [where c=M, OF fint ij] * e])
      using 1 subs
      apply (simp_all add: cbox_Pair_eq setcomp_dot1 [of "λu. M≤u"] setcomp_dot1 [of "λu. u≤M"] Sigma_Int_Paircomp1)
      apply (simp_all add: interval_split ij)
      apply (simp_all add: cbox_Pair_eq [symmetric] content_Pair [symmetric])
      apply (force simp add: interval_split [symmetric] intro!: n1 [rule_format])
      apply (force simp add: interval_split [symmetric] intro!: n2 [rule_format])
      done
  next
    case 2
    then have e: "e * content (cbox (u, w) (v, z)) =
                  e * (content (cbox u v) * content (cbox w z ∩ {x. x ∙ j ≤ M})) +
                  e * (content (cbox u v) * content (cbox w z ∩ {x. M ≤ x ∙ j}))"
      by (simp add: content_split [where c=M] content_Pair algebra_simps)
    have "(λx. integral (cbox w z ∩ {x. x ∙ j ≤ M}) (λy. f (x, y))) integrable_on cbox u v"
                "(λx. integral (cbox w z ∩ {x. M ≤ x ∙ j}) (λy. f (x, y))) integrable_on cbox u v"
      using 2 subs
      apply (simp_all add: interval_split)
      apply (rule_tac [!] integral_integrable_2dim [OF continuous_on_subset [OF f]])
      apply (auto simp: cbox_Pair_eq interval_split [symmetric])
      done
    with 2 have *: "integral (cbox u v) (λx. integral (cbox w z) (λy. f (x, y))) =
                   integral (cbox u v) (λx. integral (cbox w z ∩ {x. x ∙ j ≤ M}) (λy. f (x, y))) +
                   integral (cbox u v) (λx. integral (cbox w z ∩ {x. M ≤ x ∙ j}) (λy. f (x, y)))"
      by (simp add: integral_add [symmetric] integral_split [symmetric]
                    continuous_on_imp_integrable_on_Pair1 [OF fcont] cong: integral_cong)
    show ?normle
      apply (rule norm_diff2 [OF integral_split [where c=M, OF fint ij] * e])
      using 2 subs
      apply (simp_all add: cbox_Pair_eq setcomp_dot2 [of "λu. M≤u"] setcomp_dot2 [of "λu. u≤M"] Sigma_Int_Paircomp2)
      apply (simp_all add: interval_split ij)
      apply (simp_all add: cbox_Pair_eq [symmetric] content_Pair [symmetric])
      apply (force simp add: interval_split [symmetric] intro!: n1 [rule_format])
      apply (force simp add: interval_split [symmetric] intro!: n2 [rule_format])
      done
  qed
qed

lemma integral_Pair_const:
    "integral (cbox (a,c) (b,d)) (λx. k) =
     integral (cbox a b) (λx. integral (cbox c d) (λy. k))"
  by (simp add: content_Pair)

lemma norm_minus2: "norm (x1-x2, y1-y2) = norm (x2-x1, y2-y1)"
  by (simp add: norm_minus_eqI)

lemma integral_prod_continuous:
  fixes f :: "('a::euclidean_space * 'b::euclidean_space) ⇒ 'c::banach"
  assumes "continuous_on (cbox (a,c) (b,d)) f" (is "continuous_on ?CBOX f")
    shows "integral (cbox (a,c) (b,d)) f = integral (cbox a b) (λx. integral (cbox c d) (λy. f(x,y)))"
proof (cases "content ?CBOX = 0")
  case True
  then show ?thesis
    by (auto simp: content_Pair)
next
  case False
  then have cbp: "content ?CBOX > 0"
    using content_lt_nz by blast
  have "norm (integral ?CBOX f - integral (cbox a b) (λx. integral (cbox c d) (λy. f (x,y)))) = 0"
  proof (rule dense_eq0_I, simp)
    fix e::real  assume "0 < e"
    with cbp have e': "0 < e / content ?CBOX"
      by simp
    have f_int_acbd: "f integrable_on cbox (a,c) (b,d)"
      by (rule integrable_continuous [OF assms])
    { fix p
      assume p: "p division_of cbox (a,c) (b,d)"
      note opd1 = operative_division_and [OF integral_swap_operative [OF assms e'], THEN iffD1,
                       THEN spec, THEN spec, THEN spec, THEN spec, of p "(a,c)" "(b,d)" a c b d]
      have "(⋀t u v w z.
              ⟦t ∈ p; cbox (u,w) (v,z) ⊆ t;  cbox (u,w) (v,z) ⊆ cbox (a,c) (b,d)⟧ ⟹
              norm (integral (cbox (u,w) (v,z)) f - integral (cbox u v) (λx. integral (cbox w z) (λy. f (x,y))))
              ≤ e * content (cbox (u,w) (v,z)) / content?CBOX)
            ⟹
            norm (integral ?CBOX f - integral (cbox a b) (λx. integral (cbox c d) (λy. f (x,y)))) ≤ e"
        using opd1 [OF p] False  by simp
    } note op_acbd = this
    { fix k::real and p and u::'a and v w and z::'b and t1 t2 l
      assume k: "0 < k"
         and nf: "⋀x y u v.
                  ⟦x ∈ cbox a b; y ∈ cbox c d; u ∈ cbox a b; v∈cbox c d; norm (u-x, v-y) < k⟧
                  ⟹ norm (f(u,v) - f(x,y)) < e / (2 * (content ?CBOX))"
         and p_acbd: "p tagged_division_of cbox (a,c) (b,d)"
         and fine: "(λx. ball x k) fine p"  "((t1,t2), l) ∈ p"
         and uwvz_sub: "cbox (u,w) (v,z) ⊆ l" "cbox (u,w) (v,z) ⊆ cbox (a,c) (b,d)"
      have t: "t1 ∈ cbox a b" "t2 ∈ cbox c d"
        by (meson fine p_acbd cbox_Pair_iff tag_in_interval)+
      have ls: "l ⊆ ball (t1,t2) k"
        using fine by (simp add: fine_def Ball_def)
      { fix x1 x2
        assume xuvwz: "x1 ∈ cbox u v" "x2 ∈ cbox w z"
        then have x: "x1 ∈ cbox a b" "x2 ∈ cbox c d"
          using uwvz_sub by auto
        have "norm (x1 - t1, x2 - t2) < k"
          using xuvwz ls uwvz_sub unfolding ball_def
          by (force simp add: cbox_Pair_eq dist_norm norm_minus2)
        then have "norm (f (x1,x2) - f (t1,t2)) ≤ e / content ?CBOX / 2"
          using nf [OF t x]  by simp
      } note nf' = this
      have f_int_uwvz: "f integrable_on cbox (u,w) (v,z)"
        using f_int_acbd uwvz_sub integrable_on_subcbox by blast
      have f_int_uv: "⋀x. x ∈ cbox u v ⟹ (λy. f (x,y)) integrable_on cbox w z"
        using assms continuous_on_subset uwvz_sub
        by (blast intro: continuous_on_imp_integrable_on_Pair1)
      have 1: "norm (integral (cbox (u,w) (v,z)) f - integral (cbox (u,w) (v,z)) (λx. f (t1,t2)))
         ≤ e * content (cbox (u,w) (v,z)) / content ?CBOX / 2"
        apply (simp only: integral_diff [symmetric] f_int_uwvz integrable_const)
        apply (rule order_trans [OF integrable_bound [of "e / content ?CBOX / 2"]])
        using cbp e' nf'
        apply (auto simp: integrable_diff f_int_uwvz integrable_const)
        done
      have int_integrable: "(λx. integral (cbox w z) (λy. f (x, y))) integrable_on cbox u v"
        using assms integral_integrable_2dim continuous_on_subset uwvz_sub(2) by blast
      have normint_wz:
         "⋀x. x ∈ cbox u v ⟹
               norm (integral (cbox w z) (λy. f (x, y)) - integral (cbox w z) (λy. f (t1, t2)))
               ≤ e * content (cbox w z) / content (cbox (a, c) (b, d)) / 2"
        apply (simp only: integral_diff [symmetric] f_int_uv integrable_const)
        apply (rule order_trans [OF integrable_bound [of "e / content ?CBOX / 2"]])
        using cbp e' nf'
        apply (auto simp: integrable_diff f_int_uv integrable_const)
        done
      have "norm (integral (cbox u v)
               (λx. integral (cbox w z) (λy. f (x,y)) - integral (cbox w z) (λy. f (t1,t2))))
            ≤ e * content (cbox w z) / content ?CBOX / 2 * content (cbox u v)"
        apply (rule integrable_bound [OF _ _ normint_wz])
        using cbp e'
        apply (auto simp: divide_simps content_pos_le integrable_diff int_integrable integrable_const)
        done
      also have "... ≤ e * content (cbox (u,w) (v,z)) / content ?CBOX / 2"
        by (simp add: content_Pair divide_simps)
      finally have 2: "norm (integral (cbox u v) (λx. integral (cbox w z) (λy. f (x,y))) -
                      integral (cbox u v) (λx. integral (cbox w z) (λy. f (t1,t2))))
                ≤ e * content (cbox (u,w) (v,z)) / content ?CBOX / 2"
        by (simp only: integral_diff [symmetric] int_integrable integrable_const)
      have norm_xx: "⟦x' = y'; norm(x - x') ≤ e/2; norm(y - y') ≤ e/2⟧ ⟹ norm(x - y) ≤ e" for x::'c and y x' y' e
        using norm_triangle_mono [of "x-y'" "e/2" "y'-y" "e/2"] real_sum_of_halves
        by (simp add: norm_minus_commute)
      have "norm (integral (cbox (u,w) (v,z)) f - integral (cbox u v) (λx. integral (cbox w z) (λy. f (x,y))))
            ≤ e * content (cbox (u,w) (v,z)) / content ?CBOX"
        by (rule norm_xx [OF integral_Pair_const 1 2])
    } note * = this
    show "norm (integral ?CBOX f - integral (cbox a b) (λx. integral (cbox c d) (λy. f (x,y)))) ≤ e"
      using compact_uniformly_continuous [OF assms compact_cbox]
      apply (simp add: uniformly_continuous_on_def dist_norm)
      apply (drule_tac x="e / 2 / content?CBOX" in spec)
      using cbp ‹0 < e›
      apply (auto simp: zero_less_mult_iff)
      apply (rename_tac k)
      apply (rule_tac e1=k in fine_division_exists [OF gauge_ball, where a = "(a,c)" and b = "(b,d)"])
      apply assumption
      apply (rule op_acbd)
      apply (erule division_of_tagged_division)
      using *
      apply auto
      done
  qed
  then show ?thesis
    by simp
qed

lemma swap_continuous:
  assumes "continuous_on (cbox (a,c) (b,d)) (λ(x,y). f x y)"
    shows "continuous_on (cbox (c,a) (d,b)) (λ(x, y). f y x)"
proof -
  have "(λ(x, y). f y x) = (λ(x, y). f x y) ∘ prod.swap"
    by auto
  then show ?thesis
    apply (rule ssubst)
    apply (rule continuous_on_compose)
    apply (simp add: split_def)
    apply (rule continuous_intros | simp add: assms)+
    done
qed

lemma integral_swap_2dim:
  fixes f :: "['a::euclidean_space, 'b::euclidean_space] ⇒ 'c::banach"
  assumes "continuous_on (cbox (a,c) (b,d)) (λ(x,y). f x y)"
    shows "integral (cbox (a, c) (b, d)) (λ(x, y). f x y) = integral (cbox (c, a) (d, b)) (λ(x, y). f y x)"
proof -
  have "((λ(x, y). f x y) has_integral integral (cbox (c, a) (d, b)) (λ(x, y). f y x)) (prod.swap ` (cbox (c, a) (d, b)))"
    apply (rule has_integral_twiddle [of 1 prod.swap prod.swap "λ(x,y). f y x" "integral (cbox (c, a) (d, b)) (λ(x, y). f y x)", simplified])
    apply (auto simp: isCont_swap content_Pair has_integral_integral [symmetric] integrable_continuous swap_continuous assms)
    done
 then show ?thesis
   by force
qed

theorem integral_swap_continuous:
  fixes f :: "['a::euclidean_space, 'b::euclidean_space] ⇒ 'c::banach"
  assumes "continuous_on (cbox (a,c) (b,d)) (λ(x,y). f x y)"
    shows "integral (cbox a b) (λx. integral (cbox c d) (f x)) =
           integral (cbox c d) (λy. integral (cbox a b) (λx. f x y))"
proof -
  have "integral (cbox a b) (λx. integral (cbox c d) (f x)) = integral (cbox (a, c) (b, d)) (λ(x, y). f x y)"
    using integral_prod_continuous [OF assms] by auto
  also have "... = integral (cbox (c, a) (d, b)) (λ(x, y). f y x)"
    by (rule integral_swap_2dim [OF assms])
  also have "... = integral (cbox c d) (λy. integral (cbox a b) (λx. f x y))"
    using integral_prod_continuous [OF swap_continuous] assms
    by auto
  finally show ?thesis .
qed

end