Theory Equivalence_Lebesgue_Henstock_Integration

theory Equivalence_Lebesgue_Henstock_Integration
imports Henstock_Kurzweil_Integration Set_Integral
(*  Title:      HOL/Analysis/Equivalence_Lebesgue_Henstock_Integration.thy
    Author:     Johannes Hölzl, TU München
    Author:     Robert Himmelmann, TU München
    Huge cleanup by LCP
*)

theory Equivalence_Lebesgue_Henstock_Integration
  imports Lebesgue_Measure Henstock_Kurzweil_Integration Complete_Measure Set_Integral
begin

lemma le_left_mono: "x ≤ y ⟹ y ≤ a ⟶ x ≤ (a::'a::preorder)"
  by (auto intro: order_trans)

lemma ball_trans:
  assumes "y ∈ ball z q" "r + q ≤ s" shows "ball y r ⊆ ball z s"
proof safe
  fix x assume x: "x ∈ ball y r"
  have "dist z x ≤ dist z y + dist y x"
    by (rule dist_triangle)
  also have "… < s"
    using assms x by auto
  finally show "x ∈ ball z s"
    by simp
qed

lemma has_integral_implies_lebesgue_measurable_cbox:
  fixes f :: "'a :: euclidean_space ⇒ real"
  assumes f: "(f has_integral I) (cbox x y)"
  shows "f ∈ lebesgue_on (cbox x y) →M borel"
proof (rule cld_measure.borel_measurable_cld)
  let ?L = "lebesgue_on (cbox x y)"
  let  = "emeasure ?L"
  let ?μ' = "outer_measure_of ?L"
  interpret L: finite_measure ?L
  proof
    show "?μ (space ?L) ≠ ∞"
      by (simp add: emeasure_restrict_space space_restrict_space emeasure_lborel_cbox_eq)
  qed

  show "cld_measure ?L"
  proof
    fix B A assume "B ⊆ A" "A ∈ null_sets ?L"
    then show "B ∈ sets ?L"
      using null_sets_completion_subset[OF ‹B ⊆ A›, of lborel]
      by (auto simp add: null_sets_restrict_space sets_restrict_space_iff intro: )
  next
    fix A assume "A ⊆ space ?L" "⋀B. B ∈ sets ?L ⟹ ?μ B < ∞ ⟹ A ∩ B ∈ sets ?L"
    from this(1) this(2)[of "space ?L"] show "A ∈ sets ?L"
      by (auto simp: Int_absorb2 less_top[symmetric])
  qed auto
  then interpret cld_measure ?L
    .

  have content_eq_L: "A ∈ sets borel ⟹ A ⊆ cbox x y ⟹ content A = measure ?L A" for A
    by (subst measure_restrict_space) (auto simp: measure_def)

  fix E and a b :: real assume "E ∈ sets ?L" "a < b" "0 < ?μ E" "?μ E < ∞"
  then obtain M :: real where "?μ E = M" "0 < M"
    by (cases "?μ E") auto
  define e where "e = M / (4 + 2 / (b - a))"
  from ‹a < b› ‹0<M› have "0 < e"
    by (auto intro!: divide_pos_pos simp: field_simps e_def)

  have "e < M / (3 + 2 / (b - a))"
    using ‹a < b› ‹0 < M›
    unfolding e_def by (intro divide_strict_left_mono add_strict_right_mono mult_pos_pos) (auto simp: field_simps)
  then have "2 * e < (b - a) * (M - e * 3)"
    using ‹0<M› ‹0 < e› ‹a < b› by (simp add: field_simps)

  have e_less_M: "e < M / 1"
    unfolding e_def using ‹a < b› ‹0<M› by (intro divide_strict_left_mono) (auto simp: field_simps)

  obtain d
    where "gauge d"
      and integral_f: "∀p. p tagged_division_of cbox x y ∧ d fine p ⟶
        norm ((∑(x,k) ∈ p. content k *R f x) - I) < e"
    using ‹0<e› f unfolding has_integral by auto

  define C where "C X m = X ∩ {x. ball x (1/Suc m) ⊆ d x}" for X m
  have "incseq (C X)" for X
    unfolding C_def [abs_def]
    by (intro monoI Collect_mono conj_mono imp_refl le_left_mono subset_ball divide_left_mono Int_mono) auto

  { fix X assume "X ⊆ space ?L" and eq: "?μ' X = ?μ E"
    have "(SUP m. outer_measure_of ?L (C X m)) = outer_measure_of ?L (⋃m. C X m)"
      using ‹X ⊆ space ?L› by (intro SUP_outer_measure_of_incseq ‹incseq (C X)›) (auto simp: C_def)
    also have "(⋃m. C X m) = X"
    proof -
      { fix x
        obtain e where "0 < e" "ball x e ⊆ d x"
          using gaugeD[OF ‹gauge d›, of x] unfolding open_contains_ball by auto
        moreover
        obtain n where "1 / (1 + real n) < e"
          using reals_Archimedean[OF ‹0<e›] by (auto simp: inverse_eq_divide)
        then have "ball x (1 / (1 + real n)) ⊆ ball x e"
          by (intro subset_ball) auto
        ultimately have "∃n. ball x (1 / (1 + real n)) ⊆ d x"
          by blast }
      then show ?thesis
        by (auto simp: C_def)
    qed
    finally have "(SUP m. outer_measure_of ?L (C X m)) = ?μ E"
      using eq by auto
    also have "… > M - e"
      using ‹0 < M› ‹?μ E = M› ‹0<e› by (auto intro!: ennreal_lessI)
    finally have "∃m. M - e < outer_measure_of ?L (C X m)"
      unfolding less_SUP_iff by auto }
  note C = this

  let ?E = "{x∈E. f x ≤ a}" and ?F = "{x∈E. b ≤ f x}"

  have "¬ (?μ' ?E = ?μ E ∧ ?μ' ?F = ?μ E)"
  proof
    assume eq: "?μ' ?E = ?μ E ∧ ?μ' ?F = ?μ E"
    with C[of ?E] C[of ?F] ‹E ∈ sets ?L›[THEN sets.sets_into_space] obtain ma mb
      where "M - e < outer_measure_of ?L (C ?E ma)" "M - e < outer_measure_of ?L (C ?F mb)"
      by auto
    moreover define m where "m = max ma mb"
    ultimately have M_minus_e: "M - e < outer_measure_of ?L (C ?E m)" "M - e < outer_measure_of ?L (C ?F m)"
      using
        incseqD[OF ‹incseq (C ?E)›, of ma m, THEN outer_measure_of_mono]
        incseqD[OF ‹incseq (C ?F)›, of mb m, THEN outer_measure_of_mono]
      by (auto intro: less_le_trans)
    define d' where "d' x = d x ∩ ball x (1 / (3 * Suc m))" for x
    have "gauge d'"
      unfolding d'_def by (intro gauge_Int ‹gauge d› gauge_ball) auto
    then obtain p where p: "p tagged_division_of cbox x y" "d' fine p"
      by (rule fine_division_exists)
    then have "d fine p"
      unfolding d'_def[abs_def] fine_def by auto

    define s where "s = {(x::'a, k). k ∩ (C ?E m) ≠ {} ∧ k ∩ (C ?F m) ≠ {}}"
    define T where "T E k = (SOME x. x ∈ k ∩ C E m)" for E k
    let ?A = "(λ(x, k). (T ?E k, k)) ` (p ∩ s) ∪ (p - s)"
    let ?B = "(λ(x, k). (T ?F k, k)) ` (p ∩ s) ∪ (p - s)"

    { fix X assume X_eq: "X = ?E ∨ X = ?F"
      let ?T = "(λ(x, k). (T X k, k))"
      let ?p = "?T ` (p ∩ s) ∪ (p - s)"

      have in_s: "(x, k) ∈ s ⟹ T X k ∈ k ∩ C X m" for x k
        using someI_ex[of "λx. x ∈ k ∩ C X m"] X_eq unfolding ex_in_conv by (auto simp: T_def s_def)

      { fix x k assume "(x, k) ∈ p" "(x, k) ∈ s"
        have k: "k ⊆ ball x (1 / (3 * Suc m))"
          using ‹d' fine p›[THEN fineD, OF ‹(x, k) ∈ p›] by (auto simp: d'_def)
        then have "x ∈ ball (T X k) (1 / (3 * Suc m))"
          using in_s[OF ‹(x, k) ∈ s›] by (auto simp: C_def subset_eq dist_commute)
        then have "ball x (1 / (3 * Suc m)) ⊆ ball (T X k) (1 / Suc m)"
          by (rule ball_trans) (auto simp: divide_simps)
        with k in_s[OF ‹(x, k) ∈ s›] have "k ⊆ d (T X k)"
          by (auto simp: C_def) }
      then have "d fine ?p"
        using ‹d fine p› by (auto intro!: fineI)
      moreover
      have "?p tagged_division_of cbox x y"
      proof (rule tagged_division_ofI)
        show "finite ?p"
          using p(1) by auto
      next
        fix z k assume *: "(z, k) ∈ ?p"
        then consider "(z, k) ∈ p" "(z, k) ∉ s"
          | x' where "(x', k) ∈ p" "(x', k) ∈ s" "z = T X k"
          by (auto simp: T_def)
        then have "z ∈ k ∧ k ⊆ cbox x y ∧ (∃a b. k = cbox a b)"
          using p(1) by cases (auto dest: in_s)
        then show "z ∈ k" "k ⊆ cbox x y" "∃a b. k = cbox a b"
          by auto
      next
        fix z k z' k' assume "(z, k) ∈ ?p" "(z', k') ∈ ?p" "(z, k) ≠ (z', k')"
        with tagged_division_ofD(5)[OF p(1), of _ k _ k']
        show "interior k ∩ interior k' = {}"
          by (auto simp: T_def dest: in_s)
      next
        have "{k. ∃x. (x, k) ∈ ?p} = {k. ∃x. (x, k) ∈ p}"
          by (auto simp: T_def image_iff Bex_def)
        then show "⋃{k. ∃x. (x, k) ∈ ?p} = cbox x y"
          using p(1) by auto
      qed
      ultimately have I: "norm ((∑(x,k) ∈ ?p. content k *R f x) - I) < e"
        using integral_f by auto

      have "(∑(x,k) ∈ ?p. content k *R f x) =
        (∑(x,k) ∈ ?T ` (p ∩ s). content k *R f x) + (∑(x,k) ∈ p - s. content k *R f x)"
        using p(1)[THEN tagged_division_ofD(1)]
        by (safe intro!: sum.union_inter_neutral) (auto simp: s_def T_def)
      also have "(∑(x,k) ∈ ?T ` (p ∩ s). content k *R f x) = (∑(x,k) ∈ p ∩ s. content k *R f (T X k))"
      proof (subst sum.reindex_nontrivial, safe)
        fix x1 x2 k assume 1: "(x1, k) ∈ p" "(x1, k) ∈ s" and 2: "(x2, k) ∈ p" "(x2, k) ∈ s"
          and eq: "content k *R f (T X k) ≠ 0"
        with tagged_division_ofD(5)[OF p(1), of x1 k x2 k] tagged_division_ofD(4)[OF p(1), of x1 k]
        show "x1 = x2"
          by (auto simp: content_eq_0_interior)
      qed (use p in ‹auto intro!: sum.cong›)
      finally have eq: "(∑(x,k) ∈ ?p. content k *R f x) =
        (∑(x,k) ∈ p ∩ s. content k *R f (T X k)) + (∑(x,k) ∈ p - s. content k *R f x)" .

      have in_T: "(x, k) ∈ s ⟹ T X k ∈ X" for x k
        using in_s[of x k] by (auto simp: C_def)

      note I eq in_T }
    note parts = this

    have p_in_L: "(x, k) ∈ p ⟹ k ∈ sets ?L" for x k
      using tagged_division_ofD(3, 4)[OF p(1), of x k] by (auto simp: sets_restrict_space)

    have [simp]: "finite p"
      using tagged_division_ofD(1)[OF p(1)] .

    have "(M - 3*e) * (b - a) ≤ (∑(x,k) ∈ p ∩ s. content k) * (b - a)"
    proof (intro mult_right_mono)
      have fin: "?μ (E ∩ ⋃{k∈snd`p. k ∩ C X m = {}}) < ∞" for X
        using ‹?μ E < ∞› by (rule le_less_trans[rotated]) (auto intro!: emeasure_mono ‹E ∈ sets ?L›)
      have sets: "(E ∩ ⋃{k∈snd`p. k ∩ C X m = {}}) ∈ sets ?L" for X
        using tagged_division_ofD(1)[OF p(1)] by (intro sets.Diff ‹E ∈ sets ?L› sets.finite_Union sets.Int) (auto intro: p_in_L)
      { fix X assume "X ⊆ E" "M - e < ?μ' (C X m)"
        have "M - e ≤ ?μ' (C X m)"
          by (rule less_imp_le) fact
        also have "… ≤ ?μ' (E - (E ∩ ⋃{k∈snd`p. k ∩ C X m = {}}))"
        proof (intro outer_measure_of_mono subsetI)
          fix v assume "v ∈ C X m"
          then have "v ∈ cbox x y" "v ∈ E"
            using ‹E ⊆ space ?L› ‹X ⊆ E› by (auto simp: space_restrict_space C_def)
          then obtain z k where "(z, k) ∈ p" "v ∈ k"
            using tagged_division_ofD(6)[OF p(1), symmetric] by auto
          then show "v ∈ E - E ∩ (⋃{k∈snd`p. k ∩ C X m = {}})"
            using ‹v ∈ C X m› ‹v ∈ E› by auto
        qed
        also have "… = ?μ E - ?μ (E ∩ ⋃{k∈snd`p. k ∩ C X m = {}})"
          using ‹E ∈ sets ?L› fin[of X] sets[of X] by (auto intro!: emeasure_Diff)
        finally have "?μ (E ∩ ⋃{k∈snd`p. k ∩ C X m = {}}) ≤ e"
          using ‹0 < e› e_less_M apply (cases "?μ (E ∩ ⋃{k∈snd`p. k ∩ C X m = {}})")
          by (auto simp add: ‹?μ E = M› ennreal_minus ennreal_le_iff2)
        note this }
      note upper_bound = this

      have "?μ (E ∩ ⋃(snd`(p - s))) =
        ?μ ((E ∩ ⋃{k∈snd`p. k ∩ C ?E m = {}}) ∪ (E ∩ ⋃{k∈snd`p. k ∩ C ?F m = {}}))"
        by (intro arg_cong[where f="?μ"]) (auto simp: s_def image_def Bex_def)
      also have "… ≤ ?μ (E ∩ ⋃{k∈snd`p. k ∩ C ?E m = {}}) + ?μ (E ∩ ⋃{k∈snd`p. k ∩ C ?F m = {}})"
        using sets[of ?E] sets[of ?F] M_minus_e by (intro emeasure_subadditive) auto
      also have "… ≤ e + ennreal e"
        using upper_bound[of ?E] upper_bound[of ?F] M_minus_e by (intro add_mono) auto
      finally have "?μ E - 2*e ≤ ?μ (E - (E ∩ ⋃(snd`(p - s))))"
        using ‹0 < e› ‹E ∈ sets ?L› tagged_division_ofD(1)[OF p(1)]
        by (subst emeasure_Diff)
           (auto simp: ennreal_plus[symmetric] top_unique simp del: ennreal_plus
                 intro!: sets.Int sets.finite_UN ennreal_mono_minus intro: p_in_L)
      also have "… ≤ ?μ (⋃x∈p ∩ s. snd x)"
      proof (safe intro!: emeasure_mono subsetI)
        fix v assume "v ∈ E" and not: "v ∉ (⋃x∈p ∩ s. snd x)"
        then have "v ∈ cbox x y"
          using ‹E ⊆ space ?L› by (auto simp: space_restrict_space)
        then obtain z k where "(z, k) ∈ p" "v ∈ k"
          using tagged_division_ofD(6)[OF p(1), symmetric] by auto
        with not show "v ∈ UNION (p - s) snd"
          by (auto intro!: bexI[of _ "(z, k)"] elim: ballE[of _ _ "(z, k)"])
      qed (auto intro!: sets.Int sets.finite_UN ennreal_mono_minus intro: p_in_L)
      also have "… = measure ?L (⋃x∈p ∩ s. snd x)"
        by (auto intro!: emeasure_eq_ennreal_measure)
      finally have "M - 2 * e ≤ measure ?L (⋃x∈p ∩ s. snd x)"
        unfolding ‹?μ E = M› using ‹0 < e› by (simp add: ennreal_minus)
      also have "measure ?L (⋃x∈p ∩ s. snd x) = content (⋃x∈p ∩ s. snd x)"
        using tagged_division_ofD(1,3,4) [OF p(1)]
        by (intro content_eq_L[symmetric])
           (fastforce intro!: sets.finite_UN UN_least del: subsetI)+
      also have "content (⋃x∈p ∩ s. snd x) ≤ (∑k∈p ∩ s. content (snd k))"
        using p(1) by (auto simp: emeasure_lborel_cbox_eq intro!: measure_subadditive_finite
                            dest!: p(1)[THEN tagged_division_ofD(4)])
      finally show "M - 3 * e ≤ (∑(x, y)∈p ∩ s. content y)"
        using ‹0 < e› by (simp add: split_beta)
    qed (use ‹a < b› in auto)
    also have "… = (∑(x,k) ∈ p ∩ s. content k * (b - a))"
      by (simp add: sum_distrib_right split_beta')
    also have "… ≤ (∑(x,k) ∈ p ∩ s. content k * (f (T ?F k) - f (T ?E k)))"
      using parts(3) by (auto intro!: sum_mono mult_left_mono diff_mono)
    also have "… = (∑(x,k) ∈ p ∩ s. content k * f (T ?F k)) - (∑(x,k) ∈ p ∩ s. content k * f (T ?E k))"
      by (auto intro!: sum.cong simp: field_simps sum_subtractf[symmetric])
    also have "… = (∑(x,k) ∈ ?B. content k *R f x) - (∑(x,k) ∈ ?A. content k *R f x)"
      by (subst (1 2) parts) auto
    also have "… ≤ norm ((∑(x,k) ∈ ?B. content k *R f x) - (∑(x,k) ∈ ?A. content k *R f x))"
      by auto
    also have "… ≤ e + e"
      using parts(1)[of ?E] parts(1)[of ?F] by (intro norm_diff_triangle_le[of _ I]) auto
    finally show False
      using ‹2 * e < (b - a) * (M - e * 3)› by (auto simp: field_simps)
  qed
  moreover have "?μ' ?E ≤ ?μ E" "?μ' ?F ≤ ?μ E"
    unfolding outer_measure_of_eq[OF ‹E ∈ sets ?L›, symmetric] by (auto intro!: outer_measure_of_mono)
  ultimately show "min (?μ' ?E) (?μ' ?F) < ?μ E"
    unfolding min_less_iff_disj by (auto simp: less_le)
qed

lemma has_integral_implies_lebesgue_measurable_real:
  fixes f :: "'a :: euclidean_space ⇒ real"
  assumes f: "(f has_integral I) Ω"
  shows "(λx. f x * indicator Ω x) ∈ lebesgue →M borel"
proof -
  define B :: "nat ⇒ 'a set" where "B n = cbox (- real n *R One) (real n *R One)" for n
  show "(λx. f x * indicator Ω x) ∈ lebesgue →M borel"
  proof (rule measurable_piecewise_restrict)
    have "(⋃n. box (- real n *R One) (real n *R One)) ⊆ UNION UNIV B"
      unfolding B_def by (intro UN_mono box_subset_cbox order_refl)
    then show "countable (range B)" "space lebesgue ⊆ UNION UNIV B"
      by (auto simp: B_def UN_box_eq_UNIV)
  next
    fix Ω' assume "Ω' ∈ range B"
    then obtain n where Ω': "Ω' = B n" by auto
    then show "Ω' ∩ space lebesgue ∈ sets lebesgue"
      by (auto simp: B_def)

    have "f integrable_on Ω"
      using f by auto
    then have "(λx. f x * indicator Ω x) integrable_on Ω"
      by (auto simp: integrable_on_def cong: has_integral_cong)
    then have "(λx. f x * indicator Ω x) integrable_on (Ω ∪ B n)"
      by (rule integrable_on_superset) auto
    then have "(λx. f x * indicator Ω x) integrable_on B n"
      unfolding B_def by (rule integrable_on_subcbox) auto
    then show "(λx. f x * indicator Ω x) ∈ lebesgue_on Ω' →M borel"
      unfolding B_def Ω' by (auto intro: has_integral_implies_lebesgue_measurable_cbox simp: integrable_on_def)
  qed
qed

lemma has_integral_implies_lebesgue_measurable:
  fixes f :: "'a :: euclidean_space ⇒ 'b :: euclidean_space"
  assumes f: "(f has_integral I) Ω"
  shows "(λx. indicator Ω x *R f x) ∈ lebesgue →M borel"
proof (intro borel_measurable_euclidean_space[where 'c='b, THEN iffD2] ballI)
  fix i :: "'b" assume "i ∈ Basis"
  have "(λx. (f x ∙ i) * indicator Ω x) ∈ borel_measurable (completion lborel)"
    using has_integral_linear[OF f bounded_linear_inner_left, of i]
    by (intro has_integral_implies_lebesgue_measurable_real) (auto simp: comp_def)
  then show "(λx. indicator Ω x *R f x ∙ i) ∈ borel_measurable (completion lborel)"
    by (simp add: ac_simps)
qed

subsection ‹Equivalence Lebesgue integral on @{const lborel} and HK-integral›

lemma has_integral_measure_lborel:
  fixes A :: "'a::euclidean_space set"
  assumes A[measurable]: "A ∈ sets borel" and finite: "emeasure lborel A < ∞"
  shows "((λx. 1) has_integral measure lborel A) A"
proof -
  { fix l u :: 'a
    have "((λx. 1) has_integral measure lborel (box l u)) (box l u)"
    proof cases
      assume "∀b∈Basis. l ∙ b ≤ u ∙ b"
      then show ?thesis
        apply simp
        apply (subst has_integral_restrict[symmetric, OF box_subset_cbox])
        apply (subst has_integral_spike_interior_eq[where g="λ_. 1"])
        using has_integral_const[of "1::real" l u]
        apply (simp_all add: inner_diff_left[symmetric] content_cbox_cases)
        done
    next
      assume "¬ (∀b∈Basis. l ∙ b ≤ u ∙ b)"
      then have "box l u = {}"
        unfolding box_eq_empty by (auto simp: not_le intro: less_imp_le)
      then show ?thesis
        by simp
    qed }
  note has_integral_box = this

  { fix a b :: 'a let ?M = "λA. measure lborel (A ∩ box a b)"
    have "Int_stable  (range (λ(a, b). box a b))"
      by (auto simp: Int_stable_def box_Int_box)
    moreover have "(range (λ(a, b). box a b)) ⊆ Pow UNIV"
      by auto
    moreover have "A ∈ sigma_sets UNIV (range (λ(a, b). box a b))"
       using A unfolding borel_eq_box by simp
    ultimately have "((λx. 1) has_integral ?M A) (A ∩ box a b)"
    proof (induction rule: sigma_sets_induct_disjoint)
      case (basic A) then show ?case
        by (auto simp: box_Int_box has_integral_box)
    next
      case empty then show ?case
        by simp
    next
      case (compl A)
      then have [measurable]: "A ∈ sets borel"
        by (simp add: borel_eq_box)

      have "((λx. 1) has_integral ?M (box a b)) (box a b)"
        by (simp add: has_integral_box)
      moreover have "((λx. if x ∈ A ∩ box a b then 1 else 0) has_integral ?M A) (box a b)"
        by (subst has_integral_restrict) (auto intro: compl)
      ultimately have "((λx. 1 - (if x ∈ A ∩ box a b then 1 else 0)) has_integral ?M (box a b) - ?M A) (box a b)"
        by (rule has_integral_diff)
      then have "((λx. (if x ∈ (UNIV - A) ∩ box a b then 1 else 0)) has_integral ?M (box a b) - ?M A) (box a b)"
        by (rule has_integral_cong[THEN iffD1, rotated 1]) auto
      then have "((λx. 1) has_integral ?M (box a b) - ?M A) ((UNIV - A) ∩ box a b)"
        by (subst (asm) has_integral_restrict) auto
      also have "?M (box a b) - ?M A = ?M (UNIV - A)"
        by (subst measure_Diff[symmetric]) (auto simp: emeasure_lborel_box_eq Diff_Int_distrib2)
      finally show ?case .
    next
      case (union F)
      then have [measurable]: "⋀i. F i ∈ sets borel"
        by (simp add: borel_eq_box subset_eq)
      have "((λx. if x ∈ UNION UNIV F ∩ box a b then 1 else 0) has_integral ?M (⋃i. F i)) (box a b)"
      proof (rule has_integral_monotone_convergence_increasing)
        let ?f = "λk x. ∑i<k. if x ∈ F i ∩ box a b then 1 else 0 :: real"
        show "⋀k. (?f k has_integral (∑i<k. ?M (F i))) (box a b)"
          using union.IH by (auto intro!: has_integral_sum simp del: Int_iff)
        show "⋀k x. ?f k x ≤ ?f (Suc k) x"
          by (intro sum_mono2) auto
        from union(1) have *: "⋀x i j. x ∈ F i ⟹ x ∈ F j ⟷ j = i"
          by (auto simp add: disjoint_family_on_def)
        show "⋀x. (λk. ?f k x) ⇢ (if x ∈ UNION UNIV F ∩ box a b then 1 else 0)"
          apply (auto simp: * sum.If_cases Iio_Int_singleton)
          apply (rule_tac k="Suc xa" in LIMSEQ_offset)
          apply simp
          done
        have *: "emeasure lborel ((⋃x. F x) ∩ box a b) ≤ emeasure lborel (box a b)"
          by (intro emeasure_mono) auto

        with union(1) show "(λk. ∑i<k. ?M (F i)) ⇢ ?M (⋃i. F i)"
          unfolding sums_def[symmetric] UN_extend_simps
          by (intro measure_UNION) (auto simp: disjoint_family_on_def emeasure_lborel_box_eq top_unique)
      qed
      then show ?case
        by (subst (asm) has_integral_restrict) auto
    qed }
  note * = this

  show ?thesis
  proof (rule has_integral_monotone_convergence_increasing)
    let ?B = "λn::nat. box (- real n *R One) (real n *R One) :: 'a set"
    let ?f = "λn::nat. λx. if x ∈ A ∩ ?B n then 1 else 0 :: real"
    let ?M = "λn. measure lborel (A ∩ ?B n)"

    show "⋀n::nat. (?f n has_integral ?M n) A"
      using * by (subst has_integral_restrict) simp_all
    show "⋀k x. ?f k x ≤ ?f (Suc k) x"
      by (auto simp: box_def)
    { fix x assume "x ∈ A"
      moreover have "(λk. indicator (A ∩ ?B k) x :: real) ⇢ indicator (⋃k::nat. A ∩ ?B k) x"
        by (intro LIMSEQ_indicator_incseq) (auto simp: incseq_def box_def)
      ultimately show "(λk. if x ∈ A ∩ ?B k then 1 else 0::real) ⇢ 1"
        by (simp add: indicator_def UN_box_eq_UNIV) }

    have "(λn. emeasure lborel (A ∩ ?B n)) ⇢ emeasure lborel (⋃n::nat. A ∩ ?B n)"
      by (intro Lim_emeasure_incseq) (auto simp: incseq_def box_def)
    also have "(λn. emeasure lborel (A ∩ ?B n)) = (λn. measure lborel (A ∩ ?B n))"
    proof (intro ext emeasure_eq_ennreal_measure)
      fix n have "emeasure lborel (A ∩ ?B n) ≤ emeasure lborel (?B n)"
        by (intro emeasure_mono) auto
      then show "emeasure lborel (A ∩ ?B n) ≠ top"
        by (auto simp: top_unique)
    qed
    finally show "(λn. measure lborel (A ∩ ?B n)) ⇢ measure lborel A"
      using emeasure_eq_ennreal_measure[of lborel A] finite
      by (simp add: UN_box_eq_UNIV less_top)
  qed
qed

lemma nn_integral_has_integral:
  fixes f::"'a::euclidean_space ⇒ real"
  assumes f: "f ∈ borel_measurable borel" "⋀x. 0 ≤ f x" "(∫+x. f x ∂lborel) = ennreal r" "0 ≤ r"
  shows "(f has_integral r) UNIV"
using f proof (induct f arbitrary: r rule: borel_measurable_induct_real)
  case (set A)
  then have "((λx. 1) has_integral measure lborel A) A"
    by (intro has_integral_measure_lborel) (auto simp: ennreal_indicator)
  with set show ?case
    by (simp add: ennreal_indicator measure_def) (simp add: indicator_def)
next
  case (mult g c)
  then have "ennreal c * (∫+ x. g x ∂lborel) = ennreal r"
    by (subst nn_integral_cmult[symmetric]) (auto simp: ennreal_mult)
  with ‹0 ≤ r› ‹0 ≤ c›
  obtain r' where "(c = 0 ∧ r = 0) ∨ (0 ≤ r' ∧ (∫+ x. ennreal (g x) ∂lborel) = ennreal r' ∧ r = c * r')"
    by (cases "∫+ x. ennreal (g x) ∂lborel" rule: ennreal_cases)
       (auto split: if_split_asm simp: ennreal_mult_top ennreal_mult[symmetric])
  with mult show ?case
    by (auto intro!: has_integral_cmult_real)
next
  case (add g h)
  then have "(∫+ x. h x + g x ∂lborel) = (∫+ x. h x ∂lborel) + (∫+ x. g x ∂lborel)"
    by (simp add: nn_integral_add)
  with add obtain a b where "0 ≤ a" "0 ≤ b" "(∫+ x. h x ∂lborel) = ennreal a" "(∫+ x. g x ∂lborel) = ennreal b" "r = a + b"
    by (cases "∫+ x. h x ∂lborel" "∫+ x. g x ∂lborel" rule: ennreal2_cases)
       (auto simp: add_top nn_integral_add top_add ennreal_plus[symmetric] simp del: ennreal_plus)
  with add show ?case
    by (auto intro!: has_integral_add)
next
  case (seq U)
  note seq(1)[measurable] and f[measurable]

  { fix i x
    have "U i x ≤ f x"
      using seq(5)
      apply (rule LIMSEQ_le_const)
      using seq(4)
      apply (auto intro!: exI[of _ i] simp: incseq_def le_fun_def)
      done }
  note U_le_f = this

  { fix i
    have "(∫+x. U i x ∂lborel) ≤ (∫+x. f x ∂lborel)"
      using seq(2) f(2) U_le_f by (intro nn_integral_mono) simp
    then obtain p where "(∫+x. U i x ∂lborel) = ennreal p" "p ≤ r" "0 ≤ p"
      using seq(6) ‹0≤r› by (cases "∫+x. U i x ∂lborel" rule: ennreal_cases) (auto simp: top_unique)
    moreover note seq
    ultimately have "∃p. (∫+x. U i x ∂lborel) = ennreal p ∧ 0 ≤ p ∧ p ≤ r ∧ (U i has_integral p) UNIV"
      by auto }
  then obtain p where p: "⋀i. (∫+x. ennreal (U i x) ∂lborel) = ennreal (p i)"
    and bnd: "⋀i. p i ≤ r" "⋀i. 0 ≤ p i"
    and U_int: "⋀i.(U i has_integral (p i)) UNIV" by metis

  have int_eq: "⋀i. integral UNIV (U i) = p i" using U_int by (rule integral_unique)

  have *: "f integrable_on UNIV ∧ (λk. integral UNIV (U k)) ⇢ integral UNIV f"
  proof (rule monotone_convergence_increasing)
    show "⋀k. U k integrable_on UNIV" using U_int by auto
    show "⋀k x. x∈UNIV ⟹ U k x ≤ U (Suc k) x" using ‹incseq U› by (auto simp: incseq_def le_fun_def)
    then show "bounded (range (λk. integral UNIV (U k)))"
      using bnd int_eq by (auto simp: bounded_real intro!: exI[of _ r])
    show "⋀x. x∈UNIV ⟹ (λk. U k x) ⇢ f x"
      using seq by auto
  qed
  moreover have "(λi. (∫+x. U i x ∂lborel)) ⇢ (∫+x. f x ∂lborel)"
    using seq f(2) U_le_f by (intro nn_integral_dominated_convergence[where w=f]) auto
  ultimately have "integral UNIV f = r"
    by (auto simp add: bnd int_eq p seq intro: LIMSEQ_unique)
  with * show ?case
    by (simp add: has_integral_integral)
qed

lemma nn_integral_lborel_eq_integral:
  fixes f::"'a::euclidean_space ⇒ real"
  assumes f: "f ∈ borel_measurable borel" "⋀x. 0 ≤ f x" "(∫+x. f x ∂lborel) < ∞"
  shows "(∫+x. f x ∂lborel) = integral UNIV f"
proof -
  from f(3) obtain r where r: "(∫+x. f x ∂lborel) = ennreal r" "0 ≤ r"
    by (cases "∫+x. f x ∂lborel" rule: ennreal_cases) auto
  then show ?thesis
    using nn_integral_has_integral[OF f(1,2) r] by (simp add: integral_unique)
qed

lemma nn_integral_integrable_on:
  fixes f::"'a::euclidean_space ⇒ real"
  assumes f: "f ∈ borel_measurable borel" "⋀x. 0 ≤ f x" "(∫+x. f x ∂lborel) < ∞"
  shows "f integrable_on UNIV"
proof -
  from f(3) obtain r where r: "(∫+x. f x ∂lborel) = ennreal r" "0 ≤ r"
    by (cases "∫+x. f x ∂lborel" rule: ennreal_cases) auto
  then show ?thesis
    by (intro has_integral_integrable[where i=r] nn_integral_has_integral[where r=r] f)
qed

lemma nn_integral_has_integral_lborel:
  fixes f :: "'a::euclidean_space ⇒ real"
  assumes f_borel: "f ∈ borel_measurable borel" and nonneg: "⋀x. 0 ≤ f x"
  assumes I: "(f has_integral I) UNIV"
  shows "integralN lborel f = I"
proof -
  from f_borel have "(λx. ennreal (f x)) ∈ borel_measurable lborel" by auto
  from borel_measurable_implies_simple_function_sequence'[OF this] 
  obtain F where F: "⋀i. simple_function lborel (F i)" "incseq F" 
                 "⋀i x. F i x < top" "⋀x. (SUP i. F i x) = ennreal (f x)"
    by blast
  then have [measurable]: "⋀i. F i ∈ borel_measurable lborel"
    by (metis borel_measurable_simple_function)
  let ?B = "λi::nat. box (- (real i *R One)) (real i *R One) :: 'a set"

  have "0 ≤ I"
    using I by (rule has_integral_nonneg) (simp add: nonneg)

  have F_le_f: "enn2real (F i x) ≤ f x" for i x
    using F(3,4)[where x=x] nonneg SUP_upper[of i UNIV "λi. F i x"]
    by (cases "F i x" rule: ennreal_cases) auto
  let ?F = "λi x. F i x * indicator (?B i) x"
  have "(∫+ x. ennreal (f x) ∂lborel) = (SUP i. integralN lborel (λx. ?F i x))"
  proof (subst nn_integral_monotone_convergence_SUP[symmetric])
    { fix x
      obtain j where j: "x ∈ ?B j"
        using UN_box_eq_UNIV by auto

      have "ennreal (f x) = (SUP i. F i x)"
        using F(4)[of x] nonneg[of x] by (simp add: max_def)
      also have "… = (SUP i. ?F i x)"
      proof (rule SUP_eq)
        fix i show "∃j∈UNIV. F i x ≤ ?F j x"
          using j F(2)
          by (intro bexI[of _ "max i j"])
             (auto split: split_max split_indicator simp: incseq_def le_fun_def box_def)
      qed (auto intro!: F split: split_indicator)
      finally have "ennreal (f x) =  (SUP i. ?F i x)" . }
    then show "(∫+ x. ennreal (f x) ∂lborel) = (∫+ x. (SUP i. ?F i x) ∂lborel)"
      by simp
  qed (insert F, auto simp: incseq_def le_fun_def box_def split: split_indicator)
  also have "… ≤ ennreal I"
  proof (rule SUP_least)
    fix i :: nat
    have finite_F: "(∫+ x. ennreal (enn2real (F i x) * indicator (?B i) x) ∂lborel) < ∞"
    proof (rule nn_integral_bound_simple_function)
      have "emeasure lborel {x ∈ space lborel. ennreal (enn2real (F i x) * indicator (?B i) x) ≠ 0} ≤
        emeasure lborel (?B i)"
        by (intro emeasure_mono)  (auto split: split_indicator)
      then show "emeasure lborel {x ∈ space lborel. ennreal (enn2real (F i x) * indicator (?B i) x) ≠ 0} < ∞"
        by (auto simp: less_top[symmetric] top_unique)
    qed (auto split: split_indicator
              intro!: F simple_function_compose1[where g="enn2real"] simple_function_ennreal)

    have int_F: "(λx. enn2real (F i x) * indicator (?B i) x) integrable_on UNIV"
      using F(4) finite_F
      by (intro nn_integral_integrable_on) (auto split: split_indicator simp: enn2real_nonneg)

    have "(∫+ x. F i x * indicator (?B i) x ∂lborel) =
      (∫+ x. ennreal (enn2real (F i x) * indicator (?B i) x) ∂lborel)"
      using F(3,4)
      by (intro nn_integral_cong) (auto simp: image_iff eq_commute split: split_indicator)
    also have "… = ennreal (integral UNIV (λx. enn2real (F i x) * indicator (?B i) x))"
      using F
      by (intro nn_integral_lborel_eq_integral[OF _ _ finite_F])
         (auto split: split_indicator intro: enn2real_nonneg)
    also have "… ≤ ennreal I"
      by (auto intro!: has_integral_le[OF integrable_integral[OF int_F] I] nonneg F_le_f
               simp: ‹0 ≤ I› split: split_indicator )
    finally show "(∫+ x. F i x * indicator (?B i) x ∂lborel) ≤ ennreal I" .
  qed
  finally have "(∫+ x. ennreal (f x) ∂lborel) < ∞"
    by (auto simp: less_top[symmetric] top_unique)
  from nn_integral_lborel_eq_integral[OF assms(1,2) this] I show ?thesis
    by (simp add: integral_unique)
qed

lemma has_integral_iff_emeasure_lborel:
  fixes A :: "'a::euclidean_space set"
  assumes A[measurable]: "A ∈ sets borel" and [simp]: "0 ≤ r"
  shows "((λx. 1) has_integral r) A ⟷ emeasure lborel A = ennreal r"
proof (cases "emeasure lborel A = ∞")
  case emeasure_A: True
  have "¬ (λx. 1::real) integrable_on A"
  proof
    assume int: "(λx. 1::real) integrable_on A"
    then have "(indicator A::'a ⇒ real) integrable_on UNIV"
      unfolding indicator_def[abs_def] integrable_restrict_UNIV .
    then obtain r where "((indicator A::'a⇒real) has_integral r) UNIV"
      by auto
    from nn_integral_has_integral_lborel[OF _ _ this] emeasure_A show False
      by (simp add: ennreal_indicator)
  qed
  with emeasure_A show ?thesis
    by auto
next
  case False
  then have "((λx. 1) has_integral measure lborel A) A"
    by (simp add: has_integral_measure_lborel less_top)
  with False show ?thesis
    by (auto simp: emeasure_eq_ennreal_measure has_integral_unique)
qed

lemma ennreal_max_0: "ennreal (max 0 x) = ennreal x"
  by (auto simp: max_def ennreal_neg)

lemma has_integral_integral_real:
  fixes f::"'a::euclidean_space ⇒ real"
  assumes f: "integrable lborel f"
  shows "(f has_integral (integralL lborel f)) UNIV"
proof -
  from integrableE[OF f] obtain r q
    where "0 ≤ r" "0 ≤ q"
      and r: "(∫+ x. ennreal (max 0 (f x)) ∂lborel) = ennreal r"
      and q: "(∫+ x. ennreal (max 0 (- f x)) ∂lborel) = ennreal q"
      and f: "f ∈ borel_measurable lborel" and eq: "integralL lborel f = r - q"
    unfolding ennreal_max_0 by auto
  then have "((λx. max 0 (f x)) has_integral r) UNIV" "((λx. max 0 (- f x)) has_integral q) UNIV"
    using nn_integral_has_integral[OF _ _ r] nn_integral_has_integral[OF _ _ q] by auto
  note has_integral_diff[OF this]
  moreover have "(λx. max 0 (f x) - max 0 (- f x)) = f"
    by auto
  ultimately show ?thesis
    by (simp add: eq)
qed

lemma has_integral_AE:
  assumes ae: "AE x in lborel. x ∈ Ω ⟶ f x = g x"
  shows "(f has_integral x) Ω = (g has_integral x) Ω"
proof -
  from ae obtain N
    where N: "N ∈ sets borel" "emeasure lborel N = 0" "{x. ¬ (x ∈ Ω ⟶ f x = g x)} ⊆ N"
    by (auto elim!: AE_E)
  then have not_N: "AE x in lborel. x ∉ N"
    by (simp add: AE_iff_measurable)
  show ?thesis
  proof (rule has_integral_spike_eq[symmetric])
    show "⋀x. x∈Ω - N ⟹ f x = g x" using N(3) by auto
    show "negligible N"
      unfolding negligible_def
    proof (intro allI)
      fix a b :: "'a"
      let ?F = "λx::'a. if x ∈ cbox a b then indicator N x else 0 :: real"
      have "integrable lborel ?F = integrable lborel (λx::'a. 0::real)"
        using not_N N(1) by (intro integrable_cong_AE) auto
      moreover have "(LINT x|lborel. ?F x) = (LINT x::'a|lborel. 0::real)"
        using not_N N(1) by (intro integral_cong_AE) auto
      ultimately have "(?F has_integral 0) UNIV"
        using has_integral_integral_real[of ?F] by simp
      then show "(indicator N has_integral (0::real)) (cbox a b)"
        unfolding has_integral_restrict_UNIV .
    qed
  qed
qed

lemma nn_integral_has_integral_lebesgue:
  fixes f :: "'a::euclidean_space ⇒ real"
  assumes nonneg: "⋀x. 0 ≤ f x" and I: "(f has_integral I) Ω"
  shows "integralN lborel (λx. indicator Ω x * f x) = I"
proof -
  from I have "(λx. indicator Ω x *R f x) ∈ lebesgue →M borel"
    by (rule has_integral_implies_lebesgue_measurable)
  then obtain f' :: "'a ⇒ real"
    where [measurable]: "f' ∈ borel →M borel" and eq: "AE x in lborel. indicator Ω x * f x = f' x"
    by (auto dest: completion_ex_borel_measurable_real)

  from I have "((λx. abs (indicator Ω x * f x)) has_integral I) UNIV"
    using nonneg by (simp add: indicator_def if_distrib[of "λx. x * f y" for y] cong: if_cong)
  also have "((λx. abs (indicator Ω x * f x)) has_integral I) UNIV ⟷ ((λx. abs (f' x)) has_integral I) UNIV"
    using eq by (intro has_integral_AE) auto
  finally have "integralN lborel (λx. abs (f' x)) = I"
    by (rule nn_integral_has_integral_lborel[rotated 2]) auto
  also have "integralN lborel (λx. abs (f' x)) = integralN lborel (λx. abs (indicator Ω x * f x))"
    using eq by (intro nn_integral_cong_AE) auto
  finally show ?thesis
    using nonneg by auto
qed

lemma has_integral_iff_nn_integral_lebesgue:
  assumes f: "⋀x. 0 ≤ f x"
  shows "(f has_integral r) UNIV ⟷ (f ∈ lebesgue →M borel ∧ integralN lebesgue f = r ∧ 0 ≤ r)" (is "?I = ?N")
proof
  assume ?I
  have "0 ≤ r"
    using has_integral_nonneg[OF ‹?I›] f by auto
  then show ?N
    using nn_integral_has_integral_lebesgue[OF f ‹?I›]
      has_integral_implies_lebesgue_measurable[OF ‹?I›]
    by (auto simp: nn_integral_completion)
next
  assume ?N
  then obtain f' where f': "f' ∈ borel →M borel" "AE x in lborel. f x = f' x"
    by (auto dest: completion_ex_borel_measurable_real)
  moreover have "(∫+ x. ennreal ¦f' x¦ ∂lborel) = (∫+ x. ennreal ¦f x¦ ∂lborel)"
    using f' by (intro nn_integral_cong_AE) auto
  moreover have "((λx. ¦f' x¦) has_integral r) UNIV ⟷ ((λx. ¦f x¦) has_integral r) UNIV"
    using f' by (intro has_integral_AE) auto
  moreover note nn_integral_has_integral[of "λx. ¦f' x¦" r] ‹?N›
  ultimately show ?I
    using f by (auto simp: nn_integral_completion)
qed

context
  fixes f::"'a::euclidean_space ⇒ 'b::euclidean_space"
begin

lemma has_integral_integral_lborel:
  assumes f: "integrable lborel f"
  shows "(f has_integral (integralL lborel f)) UNIV"
proof -
  have "((λx. ∑b∈Basis. (f x ∙ b) *R b) has_integral (∑b∈Basis. integralL lborel (λx. f x ∙ b) *R b)) UNIV"
    using f by (intro has_integral_sum finite_Basis ballI has_integral_scaleR_left has_integral_integral_real) auto
  also have eq_f: "(λx. ∑b∈Basis. (f x ∙ b) *R b) = f"
    by (simp add: fun_eq_iff euclidean_representation)
  also have "(∑b∈Basis. integralL lborel (λx. f x ∙ b) *R b) = integralL lborel f"
    using f by (subst (2) eq_f[symmetric]) simp
  finally show ?thesis .
qed

lemma integrable_on_lborel: "integrable lborel f ⟹ f integrable_on UNIV"
  using has_integral_integral_lborel by auto

lemma integral_lborel: "integrable lborel f ⟹ integral UNIV f = (∫x. f x ∂lborel)"
  using has_integral_integral_lborel by auto

end

context
begin

private lemma has_integral_integral_lebesgue_real:
  fixes f :: "'a::euclidean_space ⇒ real"
  assumes f: "integrable lebesgue f"
  shows "(f has_integral (integralL lebesgue f)) UNIV"
proof -
  obtain f' where f': "f' ∈ borel →M borel" "AE x in lborel. f x = f' x"
    using completion_ex_borel_measurable_real[OF borel_measurable_integrable[OF f]] by auto
  moreover have "(∫+ x. ennreal (norm (f x)) ∂lborel) = (∫+ x. ennreal (norm (f' x)) ∂lborel)"
    using f' by (intro nn_integral_cong_AE) auto
  ultimately have "integrable lborel f'"
    using f by (auto simp: integrable_iff_bounded nn_integral_completion cong: nn_integral_cong_AE)
  note has_integral_integral_real[OF this]
  moreover have "integralL lebesgue f = integralL lebesgue f'"
    using f' f by (intro integral_cong_AE) (auto intro: AE_completion measurable_completion)
  moreover have "integralL lebesgue f' = integralL lborel f'"
    using f' by (simp add: integral_completion)
  moreover have "(f' has_integral integralL lborel f') UNIV ⟷ (f has_integral integralL lborel f') UNIV"
    using f' by (intro has_integral_AE) auto
  ultimately show ?thesis
    by auto
qed

lemma has_integral_integral_lebesgue:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes f: "integrable lebesgue f"
  shows "(f has_integral (integralL lebesgue f)) UNIV"
proof -
  have "((λx. ∑b∈Basis. (f x ∙ b) *R b) has_integral (∑b∈Basis. integralL lebesgue (λx. f x ∙ b) *R b)) UNIV"
    using f by (intro has_integral_sum finite_Basis ballI has_integral_scaleR_left has_integral_integral_lebesgue_real) auto
  also have eq_f: "(λx. ∑b∈Basis. (f x ∙ b) *R b) = f"
    by (simp add: fun_eq_iff euclidean_representation)
  also have "(∑b∈Basis. integralL lebesgue (λx. f x ∙ b) *R b) = integralL lebesgue f"
    using f by (subst (2) eq_f[symmetric]) simp
  finally show ?thesis .
qed

lemma integrable_on_lebesgue:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  shows "integrable lebesgue f ⟹ f integrable_on UNIV"
  using has_integral_integral_lebesgue by auto

lemma integral_lebesgue:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  shows "integrable lebesgue f ⟹ integral UNIV f = (∫x. f x ∂lebesgue)"
  using has_integral_integral_lebesgue by auto

end

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

translations
"LBINT x. f" == "CONST lebesgue_integral CONST lborel (λx. f)"

translations
"LBINT x:A. f" == "CONST set_lebesgue_integral CONST lborel A (λx. f)"

lemma set_integral_reflect:
  fixes S and f :: "real ⇒ 'a :: {banach, second_countable_topology}"
  shows "(LBINT x : S. f x) = (LBINT x : {x. - x ∈ S}. f (- x))"
  by (subst lborel_integral_real_affine[where c="-1" and t=0])
     (auto intro!: Bochner_Integration.integral_cong split: split_indicator)

lemma borel_integrable_atLeastAtMost':
  fixes f :: "real ⇒ 'a::{banach, second_countable_topology}"
  assumes f: "continuous_on {a..b} f"
  shows "set_integrable lborel {a..b} f" (is "integrable _ ?f")
  by (intro borel_integrable_compact compact_Icc f)

lemma integral_FTC_atLeastAtMost:
  fixes f :: "real ⇒ 'a :: euclidean_space"
  assumes "a ≤ b"
    and F: "⋀x. a ≤ x ⟹ x ≤ b ⟹ (F has_vector_derivative f x) (at x within {a .. b})"
    and f: "continuous_on {a .. b} f"
  shows "integralL lborel (λx. indicator {a .. b} x *R f x) = F b - F a"
proof -
  let ?f = "λx. indicator {a .. b} x *R f x"
  have "(?f has_integral (∫x. ?f x ∂lborel)) UNIV"
    using borel_integrable_atLeastAtMost'[OF f] by (rule has_integral_integral_lborel)
  moreover
  have "(f has_integral F b - F a) {a .. b}"
    by (intro fundamental_theorem_of_calculus ballI assms) auto
  then have "(?f has_integral F b - F a) {a .. b}"
    by (subst has_integral_cong[where g=f]) auto
  then have "(?f has_integral F b - F a) UNIV"
    by (intro has_integral_on_superset[where T=UNIV and S="{a..b}"]) auto
  ultimately show "integralL lborel ?f = F b - F a"
    by (rule has_integral_unique)
qed

lemma set_borel_integral_eq_integral:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "set_integrable lborel S f"
  shows "f integrable_on S" "LINT x : S | lborel. f x = integral S f"
proof -
  let ?f = "λx. indicator S x *R f x"
  have "(?f has_integral LINT x : S | lborel. f x) UNIV"
    by (rule has_integral_integral_lborel) fact
  hence 1: "(f has_integral (set_lebesgue_integral lborel S f)) S"
    apply (subst has_integral_restrict_UNIV [symmetric])
    apply (rule has_integral_eq)
    by auto
  thus "f integrable_on S"
    by (auto simp add: integrable_on_def)
  with 1 have "(f has_integral (integral S f)) S"
    by (intro integrable_integral, auto simp add: integrable_on_def)
  thus "LINT x : S | lborel. f x = integral S f"
    by (intro has_integral_unique [OF 1])
qed

lemma has_integral_set_lebesgue:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes f: "set_integrable lebesgue S f"
  shows "(f has_integral (LINT x:S|lebesgue. f x)) S"
  using has_integral_integral_lebesgue[OF f]
  by (simp_all add: indicator_def if_distrib[of "λx. x *R f _"] has_integral_restrict_UNIV cong: if_cong)

lemma set_lebesgue_integral_eq_integral:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes f: "set_integrable lebesgue S f"
  shows "f integrable_on S" "LINT x:S | lebesgue. f x = integral S f"
  using has_integral_set_lebesgue[OF f] by (auto simp: integral_unique integrable_on_def)

lemma lmeasurable_iff_has_integral:
  "S ∈ lmeasurable ⟷ ((indicator S) has_integral measure lebesgue S) UNIV"
  by (subst has_integral_iff_nn_integral_lebesgue)
     (auto simp: ennreal_indicator emeasure_eq_measure2 borel_measurable_indicator_iff intro!: fmeasurableI)

abbreviation
  absolutely_integrable_on :: "('a::euclidean_space ⇒ 'b::{banach, second_countable_topology}) ⇒ 'a set ⇒ bool"
  (infixr "absolutely'_integrable'_on" 46)
  where "f absolutely_integrable_on s ≡ set_integrable lebesgue s f"


lemma absolutely_integrable_on_def:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  shows "f absolutely_integrable_on s ⟷ f integrable_on s ∧ (λx. norm (f x)) integrable_on s"
proof safe
  assume f: "f absolutely_integrable_on s"
  then have nf: "integrable lebesgue (λx. norm (indicator s x *R f x))"
    by (intro integrable_norm)
  note integrable_on_lebesgue[OF f] integrable_on_lebesgue[OF nf]
  moreover have
    "(λx. indicator s x *R f x) = (λx. if x ∈ s then f x else 0)"
    "(λx. norm (indicator s x *R f x)) = (λx. if x ∈ s then norm (f x) else 0)"
    by auto
  ultimately show "f integrable_on s" "(λx. norm (f x)) integrable_on s"
    by (simp_all add: integrable_restrict_UNIV)
next
  assume f: "f integrable_on s" and nf: "(λx. norm (f x)) integrable_on s"
  show "f absolutely_integrable_on s"
  proof (rule integrableI_bounded)
    show "(λx. indicator s x *R f x) ∈ borel_measurable lebesgue"
      using f has_integral_implies_lebesgue_measurable[of f _ s] by (auto simp: integrable_on_def)
    show "(∫+ x. ennreal (norm (indicator s x *R f x)) ∂lebesgue) < ∞"
      using nf nn_integral_has_integral_lebesgue[of "λx. norm (f x)" _ s]
      by (auto simp: integrable_on_def nn_integral_completion)
  qed
qed
  
lemma absolutely_integrable_on_null [intro]:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  shows "content (cbox a b) = 0 ⟹ f absolutely_integrable_on (cbox a b)"
  by (auto simp: absolutely_integrable_on_def)

lemma absolutely_integrable_on_open_interval:
  fixes f :: "'a :: euclidean_space ⇒ 'b :: euclidean_space"
  shows "f absolutely_integrable_on box a b ⟷
         f absolutely_integrable_on cbox a b"
  by (auto simp: integrable_on_open_interval absolutely_integrable_on_def)

lemma absolutely_integrable_restrict_UNIV:
  "(λx. if x ∈ s then f x else 0) absolutely_integrable_on UNIV ⟷ f absolutely_integrable_on s"
  by (intro arg_cong2[where f=integrable]) auto

lemma absolutely_integrable_onI:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  shows "f integrable_on s ⟹ (λx. norm (f x)) integrable_on s ⟹ f absolutely_integrable_on s"
  unfolding absolutely_integrable_on_def by auto

lemma nonnegative_absolutely_integrable_1:
  fixes f :: "'a :: euclidean_space ⇒ real"
  assumes f: "f integrable_on A" and "⋀x. x ∈ A ⟹ 0 ≤ f x"
  shows "f absolutely_integrable_on A"
  apply (rule absolutely_integrable_onI [OF f])
  using assms by (simp add: integrable_eq)

lemma absolutely_integrable_on_iff_nonneg:
  fixes f :: "'a :: euclidean_space ⇒ real"
  assumes "⋀x. x ∈ S ⟹ 0 ≤ f x" shows "f absolutely_integrable_on S ⟷ f integrable_on S"
proof -
  { assume "f integrable_on S"
    then have "(λx. if x ∈ S then f x else 0) integrable_on UNIV"
      by (simp add: integrable_restrict_UNIV)
    then have "(λx. if x ∈ S then f x else 0) absolutely_integrable_on UNIV"
      using ‹f integrable_on S› absolutely_integrable_restrict_UNIV assms nonnegative_absolutely_integrable_1 by blast
    then have "f absolutely_integrable_on S"
      using absolutely_integrable_restrict_UNIV by blast
  }
  then show ?thesis        
    unfolding absolutely_integrable_on_def by auto
qed

lemma lmeasurable_iff_integrable_on: "S ∈ lmeasurable ⟷ (λx. 1::real) integrable_on S"
  by (subst absolutely_integrable_on_iff_nonneg[symmetric])
     (simp_all add: lmeasurable_iff_integrable)

lemma lmeasure_integral_UNIV: "S ∈ lmeasurable ⟹ measure lebesgue S = integral UNIV (indicator S)"
  by (simp add: lmeasurable_iff_has_integral integral_unique)

lemma lmeasure_integral: "S ∈ lmeasurable ⟹ measure lebesgue S = integral S (λx. 1::real)"
  by (auto simp add: lmeasure_integral_UNIV indicator_def[abs_def] lmeasurable_iff_integrable_on)

lemma
  assumes 𝒟: "𝒟 division_of S"
  shows lmeasurable_division: "S ∈ lmeasurable" (is ?l)
    and content_division: "(∑k∈𝒟. measure lebesgue k) = measure lebesgue S" (is ?m)
proof -
  { fix d1 d2 assume *: "d1 ∈ 𝒟" "d2 ∈ 𝒟" "d1 ≠ d2"
    then obtain a b c d where "d1 = cbox a b" "d2 = cbox c d"
      using division_ofD(4)[OF 𝒟] by blast
    with division_ofD(5)[OF 𝒟 *]
    have "d1 ∈ sets lborel" "d2 ∈ sets lborel" "d1 ∩ d2 ⊆ (cbox a b - box a b) ∪ (cbox c d - box c d)"
      by auto
    moreover have "(cbox a b - box a b) ∪ (cbox c d - box c d) ∈ null_sets lborel"
      by (intro null_sets.Un null_sets_cbox_Diff_box)
    ultimately have "d1 ∩ d2 ∈ null_sets lborel"
      by (blast intro: null_sets_subset) }
  then show ?l ?m
    unfolding division_ofD(6)[OF 𝒟, symmetric]
    using division_ofD(1,4)[OF 𝒟]
    by (auto intro!: measure_Union_AE[symmetric] simp: completion.AE_iff_null_sets Int_def[symmetric] pairwise_def null_sets_def)
qed

text ‹This should be an abbreviation for negligible.›
lemma negligible_iff_null_sets: "negligible S ⟷ S ∈ null_sets lebesgue"
proof
  assume "negligible S"
  then have "(indicator S has_integral (0::real)) UNIV"
    by (auto simp: negligible)
  then show "S ∈ null_sets lebesgue"
    by (subst (asm) has_integral_iff_nn_integral_lebesgue)
        (auto simp: borel_measurable_indicator_iff nn_integral_0_iff_AE AE_iff_null_sets indicator_eq_0_iff)
next
  assume S: "S ∈ null_sets lebesgue"
  show "negligible S"
    unfolding negligible_def
  proof (safe intro!: has_integral_iff_nn_integral_lebesgue[THEN iffD2]
                      has_integral_restrict_UNIV[where s="cbox _ _", THEN iffD1])
    fix a b
    show "(λx. if x ∈ cbox a b then indicator S x else 0) ∈ lebesgue →M borel"
      using S by (auto intro!: measurable_If)
    then show "(∫+ x. ennreal (if x ∈ cbox a b then indicator S x else 0) ∂lebesgue) = ennreal 0"
      using S[THEN AE_not_in] by (auto intro!: nn_integral_0_iff_AE[THEN iffD2])
  qed auto
qed

lemma starlike_negligible:
  assumes "closed S"
      and eq1: "⋀c x. ⟦(a + c *R x) ∈ S; 0 ≤ c; a + x ∈ S⟧ ⟹ c = 1"
    shows "negligible S"
proof -
  have "negligible (op + (-a) ` S)"
  proof (subst negligible_on_intervals, intro allI)
    fix u v
    show "negligible (op + (- a) ` S ∩ cbox u v)"
      unfolding negligible_iff_null_sets
      apply (rule starlike_negligible_compact)
       apply (simp add: assms closed_translation closed_Int_compact, clarify)
      by (metis eq1 minus_add_cancel)
  qed
  then show ?thesis
    by (rule negligible_translation_rev)
qed

lemma starlike_negligible_strong:
  assumes "closed S"
      and star: "⋀c x. ⟦0 ≤ c; c < 1; a+x ∈ S⟧ ⟹ a + c *R x ∉ S"
    shows "negligible S"
proof -
  show ?thesis
  proof (rule starlike_negligible [OF ‹closed S›, of a])
    fix c x
    assume cx: "a + c *R x ∈ S" "0 ≤ c" "a + x ∈ S"
    with star have "~ (c < 1)" by auto
    moreover have "~ (c > 1)"
      using star [of "1/c" "c *R x"] cx by force
    ultimately show "c = 1" by arith
  qed
qed

subsection‹Applications›

lemma negligible_hyperplane:
  assumes "a ≠ 0 ∨ b ≠ 0" shows "negligible {x. a ∙ x = b}"
proof -
  obtain x where x: "a ∙ x ≠ b"
    using assms
    apply auto
     apply (metis inner_eq_zero_iff inner_zero_right)
    using inner_zero_right by fastforce
  show ?thesis
    apply (rule starlike_negligible [OF closed_hyperplane, of x])
    using x apply (auto simp: algebra_simps)
    done
qed

lemma negligible_lowdim:
  fixes S :: "'N :: euclidean_space set"
  assumes "dim S < DIM('N)"
    shows "negligible S"
proof -
  obtain a where "a ≠ 0" and a: "span S ⊆ {x. a ∙ x = 0}"
    using lowdim_subset_hyperplane [OF assms] by blast
  have "negligible (span S)"
    using ‹a ≠ 0› a negligible_hyperplane by (blast intro: negligible_subset)
  then show ?thesis
    using span_inc by (blast intro: negligible_subset)
qed

proposition negligible_convex_frontier:
  fixes S :: "'N :: euclidean_space set"
  assumes "convex S"
    shows "negligible(frontier S)"
proof -
  have nf: "negligible(frontier S)" if "convex S" "0 ∈ S" for S :: "'N set"
  proof -
    obtain B where "B ⊆ S" and indB: "independent B"
               and spanB: "S ⊆ span B" and cardB: "card B = dim S"
      by (metis basis_exists)
    consider "dim S < DIM('N)" | "dim S = DIM('N)"
      using dim_subset_UNIV le_eq_less_or_eq by blast
    then show ?thesis
    proof cases
      case 1
      show ?thesis
        by (rule negligible_subset [of "closure S"])
           (simp_all add: Diff_subset frontier_def negligible_lowdim 1)
    next
      case 2
      obtain a where a: "a ∈ interior S"
        apply (rule interior_simplex_nonempty [OF indB])
          apply (simp add: indB independent_finite)
         apply (simp add: cardB 2)
        apply (metis ‹B ⊆ S› ‹0 ∈ S› ‹convex S› insert_absorb insert_subset interior_mono subset_hull)
        done
      show ?thesis
      proof (rule starlike_negligible_strong [where a=a])
        fix c::real and x
        have eq: "a + c *R x = (a + x) - (1 - c) *R ((a + x) - a)"
          by (simp add: algebra_simps)
        assume "0 ≤ c" "c < 1" "a + x ∈ frontier S"
        then show "a + c *R x ∉ frontier S"
          apply (clarsimp simp: frontier_def)
          apply (subst eq)
          apply (rule mem_interior_closure_convex_shrink [OF ‹convex S› a, of _ "1-c"], auto)
          done
      qed auto
    qed
  qed
  show ?thesis
  proof (cases "S = {}")
    case True then show ?thesis by auto
  next
    case False
    then obtain a where "a ∈ S" by auto
    show ?thesis
      using nf [of "(λx. -a + x) ` S"]
      by (metis ‹a ∈ S› add.left_inverse assms convex_translation_eq frontier_translation
                image_eqI negligible_translation_rev)
  qed
qed

corollary negligible_sphere: "negligible (sphere a e)"
  using frontier_cball negligible_convex_frontier convex_cball
  by (blast intro: negligible_subset)


lemma non_negligible_UNIV [simp]: "¬ negligible UNIV"
  unfolding negligible_iff_null_sets by (auto simp: null_sets_def emeasure_lborel_UNIV)

lemma negligible_interval:
  "negligible (cbox a b) ⟷ box a b = {}" "negligible (box a b) ⟷ box a b = {}"
   by (auto simp: negligible_iff_null_sets null_sets_def prod_nonneg inner_diff_left box_eq_empty
                  not_le emeasure_lborel_cbox_eq emeasure_lborel_box_eq
            intro: eq_refl antisym less_imp_le)

subsection ‹Negligibility of a Lipschitz image of a negligible set›

lemma measure_eq_0_null_sets: "S ∈ null_sets M ⟹ measure M S = 0"
  by (auto simp: measure_def null_sets_def)

text‹The bound will be eliminated by a sort of onion argument›
lemma locally_Lipschitz_negl_bounded:
  fixes f :: "'M::euclidean_space ⇒ 'N::euclidean_space"
  assumes MleN: "DIM('M) ≤ DIM('N)" "0 < B" "bounded S" "negligible S"
      and lips: "⋀x. x ∈ S
                      ⟹ ∃T. open T ∧ x ∈ T ∧
                              (∀y ∈ S ∩ T. norm(f y - f x) ≤ B * norm(y - x))"
  shows "negligible (f ` S)"
  unfolding negligible_iff_null_sets
proof (clarsimp simp: completion.null_sets_outer)
  fix e::real
  assume "0 < e"
  have "S ∈ lmeasurable"
    using ‹negligible S› by (simp add: negligible_iff_null_sets fmeasurableI_null_sets)
  have e22: "0 < e/2 / (2 * B * real DIM('M)) ^ DIM('N)"
    using ‹0 < e› ‹0 < B› by (simp add: divide_simps)
  obtain T
    where "open T" "S ⊆ T" "T ∈ lmeasurable"
      and "measure lebesgue T ≤ measure lebesgue S + e/2 / (2 * B * DIM('M)) ^ DIM('N)"
    by (rule lmeasurable_outer_open [OF ‹S ∈ lmeasurable› e22])
  then have T: "measure lebesgue T ≤ e/2 / (2 * B * DIM('M)) ^ DIM('N)"
    using ‹negligible S› by (simp add: negligible_iff_null_sets measure_eq_0_null_sets)
  have "∃r. 0 < r ∧ r ≤ 1/2 ∧
            (x ∈ S ⟶ (∀y. norm(y - x) < r
                       ⟶ y ∈ T ∧ (y ∈ S ⟶ norm(f y - f x) ≤ B * norm(y - x))))"
        for x
  proof (cases "x ∈ S")
    case True
    obtain U where "open U" "x ∈ U" and U: "⋀y. y ∈ S ∩ U ⟹ norm(f y - f x) ≤ B * norm(y - x)"
      using lips [OF ‹x ∈ S›] by auto
    have "x ∈ T ∩ U"
      using ‹S ⊆ T› ‹x ∈ U› ‹x ∈ S› by auto
    then obtain ε where "0 < ε" "ball x ε ⊆ T ∩ U"
      by (metis ‹open T› ‹open U› openE open_Int)
    then show ?thesis
      apply (rule_tac x="min (1/2) ε" in exI)
      apply (simp del: divide_const_simps)
      apply (intro allI impI conjI)
       apply (metis dist_commute dist_norm mem_ball subsetCE)
      by (metis Int_iff subsetCE U dist_norm mem_ball norm_minus_commute)
  next
    case False
    then show ?thesis
      by (rule_tac x="1/4" in exI) auto
  qed
  then obtain R where R12: "⋀x. 0 < R x ∧ R x ≤ 1/2"
                and RT: "⋀x y. ⟦x ∈ S; norm(y - x) < R x⟧ ⟹ y ∈ T"
                and RB: "⋀x y. ⟦x ∈ S; y ∈ S; norm(y - x) < R x⟧ ⟹ norm(f y - f x) ≤ B * norm(y - x)"
    by metis+
  then have gaugeR: "gauge (λx. ball x (R x))"
    by (simp add: gauge_def)
  obtain c where c: "S ⊆ cbox (-c *R One) (c *R One)" "box (-c *R One:: 'M) (c *R One) ≠ {}"
  proof -
    obtain B where B: "⋀x. x ∈ S ⟹ norm x ≤ B"
      using ‹bounded S› bounded_iff by blast
    show ?thesis
      apply (rule_tac c = "abs B + 1" in that)
      using norm_bound_Basis_le Basis_le_norm
       apply (fastforce simp: box_eq_empty mem_box dest!: B intro: order_trans)+
      done
  qed
  obtain 𝒟 where "countable 𝒟"
     and Dsub: "⋃𝒟 ⊆ cbox (-c *R One) (c *R One)"
     and cbox: "⋀K. K ∈ 𝒟 ⟹ interior K ≠ {} ∧ (∃c d. K = cbox c d)"
     and pw:   "pairwise (λA B. interior A ∩ interior B = {}) 𝒟"
     and Ksub: "⋀K. K ∈ 𝒟 ⟹ ∃x ∈ S ∩ K. K ⊆ (λx. ball x (R x)) x"
     and exN:  "⋀u v. cbox u v ∈ 𝒟 ⟹ ∃n. ∀i ∈ Basis. v ∙ i - u ∙ i = (2*c) / 2^n"
     and "S ⊆ ⋃𝒟"
    using covering_lemma [OF c gaugeR]  by force
  have "∃u v z. K = cbox u v ∧ box u v ≠ {} ∧ z ∈ S ∧ z ∈ cbox u v ∧
                cbox u v ⊆ ball z (R z)" if "K ∈ 𝒟" for K
  proof -
    obtain u v where "K = cbox u v"
      using ‹K ∈ 𝒟› cbox by blast
    with that show ?thesis
      apply (rule_tac x=u in exI)
      apply (rule_tac x=v in exI)
      apply (metis Int_iff interior_cbox cbox Ksub)
      done
  qed
  then obtain uf vf zf
    where uvz: "⋀K. K ∈ 𝒟 ⟹
                K = cbox (uf K) (vf K) ∧ box (uf K) (vf K) ≠ {} ∧ zf K ∈ S ∧
                zf K ∈ cbox (uf K) (vf K) ∧ cbox (uf K) (vf K) ⊆ ball (zf K) (R (zf K))"
    by metis
  define prj1 where "prj1 ≡ λx::'M. x ∙ (SOME i. i ∈ Basis)"
  define fbx where "fbx ≡ λD. cbox (f(zf D) - (B * DIM('M) * (prj1(vf D - uf D))) *R One::'N)
                                    (f(zf D) + (B * DIM('M) * prj1(vf D - uf D)) *R One)"
  have vu_pos: "0 < prj1 (vf X - uf X)" if "X ∈ 𝒟" for X
    using uvz [OF that] by (simp add: prj1_def box_ne_empty SOME_Basis inner_diff_left)
  have prj1_idem: "prj1 (vf X - uf X) = (vf X - uf X) ∙ i" if  "X ∈ 𝒟" "i ∈ Basis" for X i
  proof -
    have "cbox (uf X) (vf X) ∈ 𝒟"
      using uvz ‹X ∈ 𝒟› by auto
    with exN obtain n where "⋀i. i ∈ Basis ⟹ vf X ∙ i - uf X ∙ i = (2*c) / 2^n"
      by blast
    then show ?thesis
      by (simp add: ‹i ∈ Basis› SOME_Basis inner_diff prj1_def)
  qed
  have countbl: "countable (fbx ` 𝒟)"
    using ‹countable 𝒟› by blast
  have "(∑k∈fbx`𝒟'. measure lebesgue k) ≤ e/2" if "𝒟' ⊆ 𝒟" "finite 𝒟'" for 𝒟'
  proof -
    have BM_ge0: "0 ≤ B * (DIM('M) * prj1 (vf X - uf X))" if "X ∈ 𝒟'" for X
      using ‹0 < B› ‹𝒟' ⊆ 𝒟› that vu_pos by fastforce
    have "{} ∉ 𝒟'"
      using cbox ‹𝒟' ⊆ 𝒟› interior_empty by blast
    have "(∑k∈fbx`𝒟'. measure lebesgue k) ≤ sum (measure lebesgue o fbx) 𝒟'"
      by (rule sum_image_le [OF ‹finite 𝒟'›]) (force simp: fbx_def)
    also have "… ≤ (∑X∈𝒟'. (2 * B * DIM('M)) ^ DIM('N) * measure lebesgue X)"
    proof (rule sum_mono)
      fix X assume "X ∈ 𝒟'"
      then have "X ∈ 𝒟" using ‹𝒟' ⊆ 𝒟› by blast
      then have ufvf: "cbox (uf X) (vf X) = X"
        using uvz by blast
      have "prj1 (vf X - uf X) ^ DIM('M) = (∏i::'M ∈ Basis. prj1 (vf X - uf X))"
        by (rule prod_constant [symmetric])
      also have "… = (∏i∈Basis. vf X ∙ i - uf X ∙ i)"
        using prj1_idem [OF ‹X ∈ 𝒟›] by (auto simp: algebra_simps intro: prod.cong)
      finally have prj1_eq: "prj1 (vf X - uf X) ^ DIM('M) = (∏i∈Basis. vf X ∙ i - uf X ∙ i)" .
      have "uf X ∈ cbox (uf X) (vf X)" "vf X ∈ cbox (uf X) (vf X)"
        using uvz [OF ‹X ∈ 𝒟›] by (force simp: mem_box)+
      moreover have "cbox (uf X) (vf X) ⊆ ball (zf X) (1/2)"
        by (meson R12 order_trans subset_ball uvz [OF ‹X ∈ 𝒟›])
      ultimately have "uf X ∈ ball (zf X) (1/2)"  "vf X ∈ ball (zf X) (1/2)"
        by auto
      then have "dist (vf X) (uf X) ≤ 1"
        unfolding mem_ball
        by (metis dist_commute dist_triangle_half_l dual_order.order_iff_strict)
      then have 1: "prj1 (vf X - uf X) ≤ 1"
        unfolding prj1_def dist_norm using Basis_le_norm SOME_Basis order_trans by fastforce
      have 0: "0 ≤ prj1 (vf X - uf X)"
        using ‹X ∈ 𝒟› prj1_def vu_pos by fastforce
      have "(measure lebesgue ∘ fbx) X ≤ (2 * B * DIM('M)) ^ DIM('N) * content (cbox (uf X) (vf X))"
        apply (simp add: fbx_def content_cbox_cases algebra_simps BM_ge0 ‹X ∈ 𝒟'› prod_constant)
        apply (simp add: power_mult_distrib ‹0 < B› prj1_eq [symmetric])
        using MleN 0 1 uvz ‹X ∈ 𝒟›
        apply (fastforce simp add: box_ne_empty power_decreasing)
        done
      also have "… = (2 * B * DIM('M)) ^ DIM('N) * measure lebesgue X"
        by (subst (3) ufvf[symmetric]) simp
      finally show "(measure lebesgue ∘ fbx) X ≤ (2 * B * DIM('M)) ^ DIM('N) * measure lebesgue X" .
    qed
    also have "… = (2 * B * DIM('M)) ^ DIM('N) * sum (measure lebesgue) 𝒟'"
      by (simp add: sum_distrib_left)
    also have "… ≤ e/2"
    proof -
      have div: "𝒟' division_of ⋃𝒟'"
        apply (auto simp: ‹finite 𝒟'› ‹{} ∉ 𝒟'› division_of_def)
        using cbox that apply blast
        using pairwise_subset [OF pw ‹𝒟' ⊆ 𝒟›] unfolding pairwise_def apply force+
        done
      have le_meaT: "measure lebesgue (⋃𝒟') ≤ measure lebesgue T"
      proof (rule measure_mono_fmeasurable [OF _ _ ‹T : lmeasurable›])
        show "(⋃𝒟') ∈ sets lebesgue"
          using div lmeasurable_division by auto
        have "⋃𝒟' ⊆ ⋃𝒟"
          using ‹𝒟' ⊆ 𝒟› by blast
        also have "... ⊆ T"
        proof (clarify)
          fix x D
          assume "x ∈ D" "D ∈ 𝒟"
          show "x ∈ T"
            using Ksub [OF ‹D ∈ 𝒟›]
            by (metis ‹x ∈ D› Int_iff dist_norm mem_ball norm_minus_commute subsetD RT)
        qed
        finally show "⋃𝒟' ⊆ T" .
      qed
      have "sum (measure lebesgue) 𝒟' = sum content 𝒟'"
        using  ‹𝒟' ⊆ 𝒟› cbox by (force intro: sum.cong)
      then have "(2 * B * DIM('M)) ^ DIM('N) * sum (measure lebesgue) 𝒟' =
                 (2 * B * real DIM('M)) ^ DIM('N) * measure lebesgue (⋃𝒟')"
        using content_division [OF div] by auto
      also have "… ≤ (2 * B * real DIM('M)) ^ DIM('N) * measure lebesgue T"
        apply (rule mult_left_mono [OF le_meaT])
        using ‹0 < B›
        apply (simp add: algebra_simps)
        done
      also have "… ≤ e/2"
        using T ‹0 < B› by (simp add: field_simps)
      finally show ?thesis .
    qed
    finally show ?thesis .
  qed
  then have e2: "sum (measure lebesgue) 𝒢 ≤ e/2" if "𝒢 ⊆ fbx ` 𝒟" "finite 𝒢" for 𝒢
    by (metis finite_subset_image that)
  show "∃W∈lmeasurable. f ` S ⊆ W ∧ measure lebesgue W < e"
  proof (intro bexI conjI)
    have "∃X∈𝒟. f y ∈ fbx X" if "y ∈ S" for y
    proof -
      obtain X where "y ∈ X" "X ∈ 𝒟"
        using ‹S ⊆ ⋃𝒟› ‹y ∈ S› by auto
      then have y: "y ∈ ball(zf X) (R(zf X))"
        using uvz by fastforce
      have conj_le_eq: "z - b ≤ y ∧ y ≤ z + b ⟷ abs(y - z) ≤ b" for z y b::real
        by auto
      have yin: "y ∈ cbox (uf X) (vf X)" and zin: "(zf X) ∈ cbox (uf X) (vf X)"
        using uvz ‹X ∈ 𝒟› ‹y ∈ X› by auto
      have "norm (y - zf X) ≤ (∑i∈Basis. ¦(y - zf X) ∙ i¦)"
        by (rule norm_le_l1)
      also have "… ≤ real DIM('M) * prj1 (vf X - uf X)"
      proof (rule sum_bounded_above)
        fix j::'M assume j: "j ∈ Basis"
        show "¦(y - zf X) ∙ j¦ ≤ prj1 (vf X - uf X)"
          using yin zin j
          by (fastforce simp add: mem_box prj1_idem [OF ‹X ∈ 𝒟› j] inner_diff_left)
      qed
      finally have nole: "norm (y - zf X) ≤ DIM('M) * prj1 (vf X - uf X)"
        by simp
      have fle: "¦f y ∙ i - f(zf X) ∙ i¦ ≤ B * DIM('M) * prj1 (vf X - uf X)" if "i ∈ Basis" for i
      proof -
        have "¦f y ∙ i - f (zf X) ∙ i¦ = ¦(f y - f (zf X)) ∙ i¦"
          by (simp add: algebra_simps)
        also have "… ≤ norm (f y - f (zf X))"
          by (simp add: Basis_le_norm that)
        also have "… ≤ B * norm(y - zf X)"
          by (metis uvz RB ‹X ∈ 𝒟› dist_commute dist_norm mem_ball ‹y ∈ S› y)
        also have "… ≤ B * real DIM('M) * prj1 (vf X - uf X)"
          using ‹0 < B› by (simp add: nole)
        finally show ?thesis .
      qed
      show ?thesis
        by (rule_tac x=X in bexI)
           (auto simp: fbx_def prj1_idem mem_box conj_le_eq inner_add inner_diff fle ‹X ∈ 𝒟›)
    qed
    then show "f ` S ⊆ (⋃D∈𝒟. fbx D)" by auto
  next
    have 1: "⋀D. D ∈ 𝒟 ⟹ fbx D ∈ lmeasurable"
      by (auto simp: fbx_def)
    have 2: "I' ⊆ 𝒟 ⟹ finite I' ⟹ measure lebesgue (⋃D∈I'. fbx D) ≤ e/2" for I'
      by (rule order_trans[OF measure_Union_le e2]) (auto simp: fbx_def)
    have 3: "0 ≤ e/2"
      using ‹0<e› by auto
    show "(⋃D∈𝒟. fbx D) ∈ lmeasurable"
      by (intro fmeasurable_UN_bound[OF ‹countable 𝒟› 1 2 3])
    have "measure lebesgue (⋃D∈𝒟. fbx D) ≤ e/2"
      by (intro measure_UN_bound[OF ‹countable 𝒟› 1 2 3])
    then show "measure lebesgue (⋃D∈𝒟. fbx D) < e"
      using ‹0 < e› by linarith
  qed
qed

proposition negligible_locally_Lipschitz_image:
  fixes f :: "'M::euclidean_space ⇒ 'N::euclidean_space"
  assumes MleN: "DIM('M) ≤ DIM('N)" "negligible S"
      and lips: "⋀x. x ∈ S
                      ⟹ ∃T B. open T ∧ x ∈ T ∧
                              (∀y ∈ S ∩ T. norm(f y - f x) ≤ B * norm(y - x))"
    shows "negligible (f ` S)"
proof -
  let ?S = "λn. ({x ∈ S. norm x ≤ n ∧
                          (∃T. open T ∧ x ∈ T ∧
                               (∀y∈S ∩ T. norm (f y - f x) ≤ (real n + 1) * norm (y - x)))})"
  have negfn: "f ` ?S n ∈ null_sets lebesgue" for n::nat
    unfolding negligible_iff_null_sets[symmetric]
    apply (rule_tac B = "real n + 1" in locally_Lipschitz_negl_bounded)
    by (auto simp: MleN bounded_iff intro: negligible_subset [OF ‹negligible S›])
  have "S = (⋃n. ?S n)"
  proof (intro set_eqI iffI)
    fix x assume "x ∈ S"
    with lips obtain T B where T: "open T" "x ∈ T"
                           and B: "⋀y. y ∈ S ∩ T ⟹ norm(f y - f x) ≤ B * norm(y - x)"
      by metis+
    have no: "norm (f y - f x) ≤ (nat ⌈max B (norm x)⌉ + 1) * norm (y - x)" if "y ∈ S ∩ T" for y
    proof -
      have "B * norm(y - x) ≤ (nat ⌈max B (norm x)⌉ + 1) * norm (y - x)"
        by (meson max.cobounded1 mult_right_mono nat_ceiling_le_eq nat_le_iff_add norm_ge_zero order_trans)
      then show ?thesis
        using B order_trans that by blast
    qed
    have "x ∈ ?S (nat (ceiling (max B (norm x))))"
      apply (simp add: ‹x ∈ S ›, rule)
      using real_nat_ceiling_ge max.bounded_iff apply blast
      using T no
      apply (force simp: algebra_simps)
      done
    then show "x ∈ (⋃n. ?S n)" by force
  qed auto
  then show ?thesis
    by (rule ssubst) (auto simp: image_Union negligible_iff_null_sets intro: negfn)
qed

corollary negligible_differentiable_image_negligible:
  fixes f :: "'M::euclidean_space ⇒ 'N::euclidean_space"
  assumes MleN: "DIM('M) ≤ DIM('N)" "negligible S"
      and diff_f: "f differentiable_on S"
    shows "negligible (f ` S)"
proof -
  have "∃T B. open T ∧ x ∈ T ∧ (∀y ∈ S ∩ T. norm(f y - f x) ≤ B * norm(y - x))"
        if "x ∈ S" for x
  proof -
    obtain f' where "linear f'"
      and f': "⋀e. e>0 ⟹
                  ∃d>0. ∀y∈S. norm (y - x) < d ⟶
                              norm (f y - f x - f' (y - x)) ≤ e * norm (y - x)"
      using diff_f ‹x ∈ S›
      by (auto simp: linear_linear differentiable_on_def differentiable_def has_derivative_within_alt)
    obtain B where "B > 0" and B: "∀x. norm (f' x) ≤ B * norm x"
      using linear_bounded_pos ‹linear f'› by blast
    obtain d where "d>0"
              and d: "⋀y. ⟦y ∈ S; norm (y - x) < d⟧ ⟹
                          norm (f y - f x - f' (y - x)) ≤ norm (y - x)"
      using f' [of 1] by (force simp:)
    have *: "norm (f y - f x) ≤ (B + 1) * norm (y - x)"
              if "y ∈ S" "norm (y - x) < d" for y
    proof -
      have "norm (f y - f x) -B *  norm (y - x) ≤ norm (f y - f x) - norm (f' (y - x))"
        by (simp add: B)
      also have "… ≤ norm (f y - f x - f' (y - x))"
        by (rule norm_triangle_ineq2)
      also have "... ≤ norm (y - x)"
        by (rule d [OF that])
      finally show ?thesis
        by (simp add: algebra_simps)
    qed
    show ?thesis
      apply (rule_tac x="ball x d" in exI)
      apply (rule_tac x="B+1" in exI)
      using ‹d>0›
      apply (auto simp: dist_norm norm_minus_commute intro!: *)
      done
  qed
  with negligible_locally_Lipschitz_image assms show ?thesis by metis
qed

corollary negligible_differentiable_image_lowdim:
  fixes f :: "'M::euclidean_space ⇒ 'N::euclidean_space"
  assumes MlessN: "DIM('M) < DIM('N)" and diff_f: "f differentiable_on S"
    shows "negligible (f ` S)"
proof -
  have "x ≤ DIM('M) ⟹ x ≤ DIM('N)" for x
    using MlessN by linarith
  obtain lift :: "'M * real ⇒ 'N" and drop :: "'N ⇒ 'M * real" and j :: 'N
    where "linear lift" "linear drop" and dropl [simp]: "⋀z. drop (lift z) = z"
      and "j ∈ Basis" and j: "⋀x. lift(x,0) ∙ j = 0"
    using lowerdim_embeddings [OF MlessN] by metis
  have "negligible {x. x∙j = 0}"
    by (metis ‹j ∈ Basis› negligible_standard_hyperplane)
  then have neg0S: "negligible ((λx. lift (x, 0)) ` S)"
    apply (rule negligible_subset)
    by (simp add: image_subsetI j)
  have diff_f': "f ∘ fst ∘ drop differentiable_on (λx. lift (x, 0)) ` S"
    using diff_f
    apply (clarsimp simp add: differentiable_on_def)
    apply (intro differentiable_chain_within linear_imp_differentiable [OF ‹linear drop›]
             linear_imp_differentiable [OF fst_linear])
    apply (force simp: image_comp o_def)
    done
  have "f = (f o fst o drop o (λx. lift (x, 0)))"
    by (simp add: o_def)
  then show ?thesis
    apply (rule ssubst)
    apply (subst image_comp [symmetric])
    apply (metis negligible_differentiable_image_negligible order_refl diff_f' neg0S)
    done
qed

lemma set_integral_norm_bound:
  fixes f :: "_ ⇒ 'a :: {banach, second_countable_topology}"
  shows "set_integrable M k f ⟹ norm (LINT x:k|M. f x) ≤ LINT x:k|M. norm (f x)"
  using integral_norm_bound[of M "λx. indicator k x *R f x"] by simp

lemma set_integral_finite_UN_AE:
  fixes f :: "_ ⇒ _ :: {banach, second_countable_topology}"
  assumes "finite I"
    and ae: "⋀i j. i ∈ I ⟹ j ∈ I ⟹ AE x in M. (x ∈ A i ∧ x ∈ A j) ⟶ i = j"
    and [measurable]: "⋀i. i ∈ I ⟹ A i ∈ sets M"
    and f: "⋀i. i ∈ I ⟹ set_integrable M (A i) f"
  shows "LINT x:(⋃i∈I. A i)|M. f x = (∑i∈I. LINT x:A i|M. f x)"
  using ‹finite I› order_refl[of I]
proof (induction I rule: finite_subset_induct')
  case (insert i I')
  have "AE x in M. (∀j∈I'. x ∈ A i ⟶ x ∉ A j)"
  proof (intro AE_ball_countable[THEN iffD2] ballI)
    fix j assume "j ∈ I'"
    with ‹I' ⊆ I› ‹i ∉ I'› have "i ≠ j" "j ∈ I"
      by auto
    then show "AE x in M. x ∈ A i ⟶ x ∉ A j"
      using ae[of i j] ‹i ∈ I› by auto
  qed (use ‹finite I'› in ‹rule countable_finite›)
  then have "AE x∈A i in M. ∀xa∈I'. x ∉ A xa "
    by auto
  with insert.hyps insert.IH[symmetric]
  show ?case
    by (auto intro!: set_integral_Un_AE sets.finite_UN f set_integrable_UN)
qed simp

lemma set_integrable_norm:
  fixes f :: "'a ⇒ 'b::{banach, second_countable_topology}"
  assumes f: "set_integrable M k f" shows "set_integrable M k (λx. norm (f x))"
  using integrable_norm[OF f] by simp

lemma absolutely_integrable_bounded_variation:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes f: "f absolutely_integrable_on UNIV"
  obtains B where "∀d. d division_of (⋃d) ⟶ sum (λk. norm (integral k f)) d ≤ B"
proof (rule that[of "integral UNIV (λx. norm (f x))"]; safe)
  fix d :: "'a set set" assume d: "d division_of ⋃d"
  have *: "k ∈ d ⟹ f absolutely_integrable_on k" for k
    using f[THEN set_integrable_subset, of k] division_ofD(2,4)[OF d, of k] by auto
  note d' = division_ofD[OF d]

  have "(∑k∈d. norm (integral k f)) = (∑k∈d. norm (LINT x:k|lebesgue. f x))"
    by (intro sum.cong refl arg_cong[where f=norm] set_lebesgue_integral_eq_integral(2)[symmetric] *)
  also have "… ≤ (∑k∈d. LINT x:k|lebesgue. norm (f x))"
    by (intro sum_mono set_integral_norm_bound *)
  also have "… = (∑k∈d. integral k (λx. norm (f x)))"
    by (intro sum.cong refl set_lebesgue_integral_eq_integral(2) set_integrable_norm *)
  also have "… ≤ integral (⋃d) (λx. norm (f x))"
    using integrable_on_subdivision[OF d] assms f unfolding absolutely_integrable_on_def
    by (subst integral_combine_division_topdown[OF _ d]) auto
  also have "… ≤ integral UNIV (λx. norm (f x))"
    using integrable_on_subdivision[OF d] assms unfolding absolutely_integrable_on_def
    by (intro integral_subset_le) auto
  finally show "(∑k∈d. norm (integral k f)) ≤ integral UNIV (λx. norm (f x))" .
qed

lemma absdiff_norm_less:
  assumes "sum (λx. norm (f x - g x)) s < e"
    and "finite s"
  shows "¦sum (λx. norm(f x)) s - sum (λx. norm(g x)) s¦ < e"
  unfolding sum_subtractf[symmetric]
  apply (rule le_less_trans[OF sum_abs])
  apply (rule le_less_trans[OF _ assms(1)])
  apply (rule sum_mono)
  apply (rule norm_triangle_ineq3)
  done

proposition 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) ⟹ sum (λ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"
  have *: "∃γ. gauge γ ∧
             (∀p. p tagged_division_of cbox a b ∧
                  γ fine p ⟶
                  norm ((∑(x,k) ∈ p. content k *R norm (f x)) - ?S) < e)"
    if e: "e > 0" for e
  proof -
    have "?S - e/2 < ?S" using ‹e > 0› 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 "∃e>0. ∀i∈d. x ∉ i ⟶ ball x e ∩ i = {}" for x
    proof -
      have "∃d'>0. ∀x'∈⋃{i ∈ d. x ∉ i}. d' ≤ dist x x'"
      proof (rule separate_point_closed)
        show "closed (⋃{i ∈ d. x ∉ i})"
          using d' by force
        show "x ∉ ⋃{i ∈ d. x ∉ i}"
          by auto
      qed 
      then show ?thesis
        by force
    qed
    then obtain k where k: "⋀x. 0 < k x" "⋀i x. ⟦i ∈ d; x ∉ i⟧ ⟹ ball x (k x) ∩ i = {}"
      by metis
    have "e/2 > 0"
      using e by auto
    with Henstock_lemma[OF f] 
    obtain γ where g: "gauge γ"
      "⋀p. ⟦p tagged_partial_division_of cbox a b; γ fine p⟧ 
                ⟹ (∑(x,k) ∈ p. norm (content k *R f x - integral k f)) < e/2"
      by (metis (no_types, lifting))      
    let ?g = "λx. γ x ∩ ball x (k x)"
    show ?thesis 
    proof (intro exI conjI allI impI)
      show "gauge ?g"
        using g(1) k(1) by (auto simp: gauge_def)
    next
      fix p
      assume "p tagged_division_of (cbox a b) ∧ ?g fine p"
      then have p: "p tagged_division_of cbox a b" "γ fine p" "(λx. ball x (k x)) fine p"
        by (auto simp: fine_Int)
      note p' = tagged_division_ofD[OF p(1)]
      define p' where "p' = {(x,k) | x k. ∃i l. x ∈ i ∧ i ∈ d ∧ (x,l) ∈ p ∧ k = i ∩ l}"
      have gp': "γ fine p'"
        using p(2) by (auto simp: p'_def fine_def)
      have p'': "p' tagged_division_of (cbox a b)"
      proof (rule tagged_division_ofI)
        show "finite p'"
        proof (rule finite_subset)
          show "p' ⊆ (λ(k, x, l). (x, k ∩ l)) ` (d × p)"
            by (force simp: p'_def image_iff)
          show "finite ((λ(k, x, l). (x, k ∩ l)) ` (d × p))"
            by (simp add: d'(1) p'(1))
        qed
      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 obtain i l where il: "x ∈ i" "i ∈ d" "(x, l) ∈ p" "K = i ∩ l" by blast
        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)] by (meson Int_interval)
      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 obtain i1 l1 where il1: "x1 ∈ i1" "i1 ∈ d" "(x1, l1) ∈ p" "K1 = i1 ∩ l1" by blast
        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 obtain i2 l2 where il2: "x2 ∈ i2" "i2 ∈ d" "(x2, l2) ∈ p" "K2 = i2 ∩ l2" by blast
        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)]  by (auto simp: il1 il2)
        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 blast
        have "y ∈ ⋃{K. ∃x. (x, K) ∈ p'}" if y: "y ∈ cbox a b" for y
        proof -
          obtain x l where xl: "(x, l) ∈ p" "y ∈ l" 
            using y unfolding p'(6)[symmetric] by auto
          obtain i where i: "i ∈ d" "y ∈ i" 
            using y unfolding d'(6)[symmetric] by auto
          have "x ∈ i"
            using fineD[OF p(3) xl(1)] using k(2) i xl by auto
          then show ?thesis
            unfolding p'_def by (rule_tac X="i ∩ l" in UnionI) (use i xl in auto)
        qed
        show "⋃{K. ∃x. (x, K) ∈ p'} = cbox a b"
        proof
          show "⋃{k. ∃x. (x, k) ∈ p'} ⊆ cbox a b"
            using * by auto
        next
          show "cbox a b ⊆ ⋃{k. ∃x. (x, k) ∈ p'}"
          proof 
            fix y
            assume y: "y ∈ cbox a b"
            obtain x L where xl: "(x, L) ∈ p" "y ∈ L" 
              using y unfolding p'(6)[symmetric] by auto
            obtain I where i: "I ∈ d" "y ∈ I" 
              using y unfolding d'(6)[symmetric] by auto
            have "x ∈ I"
              using fineD[OF p(3) xl(1)] using k(2) i xl by auto
            then show "y ∈ ⋃{k. ∃x. (x, k) ∈ p'}"
              apply (rule_tac X="I ∩ L" in UnionI)
              using i xl by (auto simp: p'_def)
          qed
        qed
      qed

      then have sum_less_e2: "(∑(x,K) ∈ p'. norm (content K *R f x - integral K f)) < e/2"
        using g(2) gp' tagged_division_of_def by blast

      have "(x, I ∩ L) ∈ p'" if x: "(x, L) ∈ p" "I ∈ d" and y: "y ∈ I" "y ∈ L"
        for x I L y
      proof -
        have "x ∈ I"
          using fineD[OF p(3) that(1)] k(2)[OF ‹I ∈ d›] y by auto
        with x have "(∃i l. x ∈ i ∧ i ∈ d ∧ (x, l) ∈ p ∧ I ∩ L = i ∩ l)"
          by blast
        then have "(x, I ∩ L) ∈ p'"
          by (simp add: p'_def)
        with y show ?thesis by auto
      qed
      moreover have "∃y i l. (x, K) = (y, i ∩ l) ∧ (y, l) ∈ p ∧ i ∈ d ∧ i ∩ l ≠ {}"
        if xK: "(x,K) ∈ p'" for x K
      proof -
        obtain i l where il: "x ∈ i" "i ∈ d" "(x, l) ∈ p" "K = i ∩ l" 
          using xK unfolding p'_def by auto
        then show ?thesis
          using p'(2) by fastforce
      qed
      ultimately have p'alt: "p' = {(x, I ∩ L) | x I L. (x,L) ∈ p ∧ I ∈ d ∧ I ∩ L ≠ {}}"
        by auto
      have sum_p': "(∑(x,K) ∈ p'. norm (integral K f)) = (∑k∈snd ` p'. norm (integral k f))"
        apply (subst sum.over_tagged_division_lemma[OF p'',of "λk. norm (integral k f)"])
         apply (auto intro: integral_null simp: content_eq_0_interior)
        done
      have snd_p_div: "snd ` p division_of cbox a b"
        by (rule division_of_tagged_division[OF p(1)])
      note snd_p = division_ofD[OF snd_p_div]
      have fin_d_sndp: "finite (d × snd ` p)"
        by (simp add: d'(1) snd_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
      proof (rule *)
        show "¦(∑(x,K)∈p'. norm (content K *R f x)) - (∑(x,k)∈p'. norm (integral k f))¦ < e/2"
          using p'' sum_less_e2 unfolding split_def by (force intro!: absdiff_norm_less)
        show "(∑(x,k) ∈ p'. norm (integral k f)) ≤?S"
          by (auto simp: sum_p' division_of_tagged_division[OF p''] D intro!: cSUP_upper)
        show "(∑k∈d. norm (integral k f)) ≤ (∑(x,k) ∈ p'. norm (integral k f))"
        proof -
          have *: "{k ∩ l | k l. k ∈ d ∧ l ∈ snd ` p} = (λ(k,l). k ∩ l) ` (d × snd ` p)"
            by auto
          have "(∑K∈d. norm (integral K f)) ≤ (∑i∈d. ∑l∈snd ` p. norm (integral (i ∩ l) f))"
          proof (rule sum_mono)
            fix K assume k: "K ∈ d"
            from d'(4)[OF this] obtain u v where uv: "K = cbox u v" by metis
            define d' where "d' = {cbox u v ∩ l |l. l ∈ snd ` p ∧  cbox u v ∩ l ≠ {}}"
            have uvab: "cbox u v ⊆ cbox a b"
              using d(1) k uv by blast
            have "d' division_of cbox u v"
              unfolding d'_def by (rule division_inter_1 [OF snd_p_div uvab])
            moreover then have "norm (∑i∈d'. integral i f) ≤ (∑k∈d'. norm (integral k f))"
              by (simp add: sum_norm_le)
            ultimately have "norm (integral K f) ≤ sum (λk. norm (integral k f)) d'"
              apply (subst integral_combine_division_topdown[of _ _ d'])
                apply (auto simp: uv intro: integrable_on_subcbox[OF assms(1) uvab])
              done
            also have "… = (∑I∈{K ∩ L |L. L ∈ snd ` p}. norm (integral I f))"
            proof -
              have *: "norm (integral I f) = 0"
                if "I ∈ {cbox u v ∩ l |l. l ∈ snd ` p}"
                  "I ∉ {cbox u v ∩ l |l. l ∈ snd ` p ∧ cbox u v ∩ l ≠ {}}" for I
                using that by auto
              show ?thesis
                apply (rule sum.mono_neutral_left)
                  apply (simp add: snd_p(1))
                unfolding d'_def uv using * by auto 
            qed
            also have "… = (∑l∈snd ` p. norm (integral (K ∩ l) f))"
            proof -
              have *: "norm (integral (K ∩ l) f) = 0"
                if "l ∈ snd ` p" "y ∈ snd ` p" "l ≠ y" "K ∩ l = K ∩ y" for l y
              proof -
                have "interior (K ∩ l) ⊆ interior (l ∩ y)"
                  by (metis Int_lower2 interior_mono le_inf_iff that(4))
                then have "interior (K ∩ l) = {}"
                  by (simp add: snd_p(5) that) 
                moreover from d'(4)[OF k] snd_p(4)[OF that(1)] 
                obtain u1 v1 u2 v2
                  where uv: "K = cbox u1 u2" "l = cbox v1 v2" by metis
                ultimately show ?thesis
                  using that integral_null
                  unfolding uv Int_interval content_eq_0_interior
                  by (metis (mono_tags, lifting) norm_eq_zero)
              qed
              show ?thesis
                unfolding Setcompr_eq_image
                apply (rule sum.reindex_nontrivial [unfolded o_def])
                 apply (rule finite_imageI)
                 apply (rule p')
                using * by auto
            qed
            finally show "norm (integral K f) ≤ (∑l∈snd ` p. norm (integral (K ∩ l) f))" .
          qed
          also have "… = (∑(i,l) ∈ d × snd ` p. norm (integral (i∩l) f))"
            by (simp add: sum.cartesian_product)
          also have "… = (∑x ∈ d × snd ` p. norm (integral (case_prod op ∩ x) f))"
            by (force simp: split_def intro!: sum.cong)
          also have "… = (∑k∈{i ∩ l |i l. i ∈ d ∧ l ∈ snd ` p}. norm (integral k f))"
          proof -
            have eq0: " (integral (l1 ∩ k1) f) = 0"
              if "l1 ∩ k1 = l2 ∩ k2" "(l1, k1) ≠ (l2, k2)"
                "l1 ∈ d" "(j1,k1) ∈ p" "l2 ∈ d" "(j2,k2) ∈ p"
              for l1 l2 k1 k2 j1 j2
            proof -
              obtain u1 v1 u2 v2 where uv: "l1 = cbox u1 u2" "k1 = cbox v1 v2"
                using ‹(j1, k1) ∈ p› ‹l1 ∈ d› d'(4) p'(4) by blast
              have "l1 ≠ l2 ∨ k1 ≠ k2"
                using that by auto
              then have "interior k1 ∩ interior k2 = {} ∨ interior l1 ∩ interior l2 = {}"
                by (meson d'(5) old.prod.inject p'(5) that(3) that(4) that(5) that(6))
              moreover have "interior (l1 ∩ k1) = interior (l2 ∩ k2)"
                by (simp add: that(1))
              ultimately have "interior(l1 ∩ k1) = {}"
                by auto
              then show ?thesis
                unfolding uv Int_interval content_eq_0_interior[symmetric] by auto
            qed
            show ?thesis
              unfolding *
              apply (rule sum.reindex_nontrivial [OF fin_d_sndp, symmetric, unfolded o_def])
              apply clarsimp
              by (metis eq0 fst_conv snd_conv)
          qed
          also have "… = (∑(x,k) ∈ p'. norm (integral k f))"
          proof -
            have 0: "integral (ia ∩ snd (a, b)) f = 0"
              if "ia ∩ snd (a, b) ∉ snd ` p'" "ia ∈ d" "(a, b) ∈ p" for ia a b
            proof -
              have "ia ∩ b = {}"
                using that unfolding p'alt image_iff Bex_def not_ex
                apply (erule_tac x="(a, ia ∩ b)" in allE)
                apply auto
                done
              then show ?thesis by auto
            qed
            have 1: "∃i l. snd (a, b) = i ∩ l ∧ i ∈ d ∧ l ∈ snd ` p" if "(a, b) ∈ p'" for a b
              using that 
              apply (clarsimp simp: p'_def image_iff)
              by (metis (no_types, hide_lams) snd_conv)
            show ?thesis
              unfolding sum_p'
              apply (rule sum.mono_neutral_right)
                apply (metis * finite_imageI[OF fin_d_sndp])
              using 0 1 by auto
          qed
          finally show ?thesis .
        qed
        show "(∑(x,k) ∈ p'. norm (content k *R f x)) = (∑(x,k) ∈ p. content k *R norm (f x))"
        proof -
          let ?S = "{(x, i ∩ l) |x i l. (x, l) ∈ p ∧ i ∈ d}"
          have *: "?S = (λ(xl,i). (fst xl, snd xl ∩ i)) ` (p × d)"
            by force
          have fin_pd: "finite (p × d)"
            using finite_cartesian_product[OF p'(1) d'(1)] by metis
          have "(∑(x,k) ∈ p'. norm (content k *R f x)) = (∑(x,k) ∈ ?S. ¦content k¦ * norm (f x))"
            unfolding norm_scaleR
            apply (rule sum.mono_neutral_left)
              apply (subst *)
              apply (rule finite_imageI [OF fin_pd])
            unfolding p'alt apply auto
            by fastforce
          also have "… = (∑((x,l),i)∈p × d. ¦content (l ∩ i)¦ * norm (f x))"
          proof -
            have "¦content (l1 ∩ k1)¦ * norm (f x1) = 0"
              if "(x1, l1) ∈ p" "(x2, l2) ∈ p" "k1 ∈ d" "k2 ∈ d"
                "x1 = x2" "l1 ∩ k1 = l2 ∩ k2" "x1 ≠ x2 ∨ l1 ≠ l2 ∨ k1 ≠ k2"
              for x1 l1 k1 x2 l2 k2
            proof -
              obtain u1 v1 u2 v2 where uv: "k1 = cbox u1 u2" "l1 = cbox v1 v2"
                by (meson ‹(x1, l1) ∈ p› ‹k1 ∈ d› d(1) division_ofD(4) p'(4))
              have "l1 ≠ l2 ∨ k1 ≠ k2"
                using that by auto
              then have "interior k1 ∩ interior k2 = {} ∨ interior l1 ∩ interior l2 = {}"
                apply (rule disjE)
                using that p'(5) d'(5) by auto
              moreover have "interior (l1 ∩ k1) = interior (l2 ∩ k2)"
                unfolding that ..
              ultimately have "interior (l1 ∩ k1) = {}"
                by auto
              then show "¦content (l1 ∩ k1)¦ * norm (f x1) = 0"
                unfolding uv Int_interval content_eq_0_interior[symmetric] by auto
            qed 
            then show ?thesis
              unfolding *
              apply (subst sum.reindex_nontrivial [OF fin_pd])
              unfolding split_paired_all o_def split_def prod.inject
               apply force+
              done
          qed
          also have "… = (∑(x,k) ∈ p. content k *R norm (f x))"
          proof -
            have sumeq: "(∑i∈d. content (l ∩ i) * norm (f x)) = content l * norm (f x)"
              if "(x, l) ∈ p" for x l
            proof -
              note xl = p'(2-4)[OF that]
              then obtain u v where uv: "l = cbox u v" by blast
              have "(∑i∈d. ¦content (l ∩ i)¦) = (∑k∈d. content (k ∩ cbox u v))"
                by (simp add: Int_commute uv)
              also have "… = sum content {k ∩ cbox u v| k. k ∈ d}"
              proof -
                have eq0: "content (k ∩ cbox u v) = 0"
                  if "k ∈ d" "y ∈ d" "k ≠ y" and eq: "k ∩ cbox u v = y ∩ cbox u v" for k y
                proof -
                  from d'(4)[OF that(1)] d'(4)[OF that(2)]
                  obtain α β where α: "k ∩ cbox u v = cbox α β"
                    by (meson Int_interval)
                  have "{} = interior ((k ∩ y) ∩ cbox u v)"
                    by (simp add: d'(5) that)
                  also have "… = interior (y ∩ (k ∩ cbox u v))"
                    by auto
                  also have "… = interior (k ∩ cbox u v)"
                    unfolding eq by auto
                  finally show ?thesis
                    unfolding α content_eq_0_interior ..
                qed
                then show ?thesis
                  unfolding Setcompr_eq_image
                  apply (rule sum.reindex_nontrivial [OF ‹finite d›, unfolded o_def, symmetric])
                  by auto
              qed
              also have "… = sum content {cbox u v ∩ k |k. k ∈ d ∧ cbox u v ∩ k ≠ {}}"
                apply (rule sum.mono_neutral_right)
                unfolding Setcompr_eq_image
                  apply (rule finite_imageI [OF ‹finite d›])
                 apply (fastforce simp: inf.commute)+
                done
              finally show "(∑i∈d. content (l ∩ i) * norm (f x)) = content l * norm (f x)"
                unfolding sum_distrib_right[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
            show ?thesis
              by (subst sum_Sigma_product[symmetric]) (auto intro!: sumeq sum.cong p' d')
          qed
          finally show ?thesis .
        qed
      qed (rule d)
    qed 
  qed
  then show ?thesis
    using absolutely_integrable_onI [OF f has_integral_integrable] has_integral[of _ ?S]
    by blast
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) ⟶ sum (λk. norm (integral k f)) d ≤ B"
  shows "f absolutely_integrable_on UNIV"
proof (rule absolutely_integrable_onI, fact)
  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 "⋀a b. f integrable_on cbox a b"
    using assms(1) integrable_on_subcbox by blast
  then have f_int: "⋀a b. f absolutely_integrable_on cbox a b"
    apply (rule bounded_variation_absolutely_integrable_interval[where B=B])
    using assms(2) apply blast
    done
  have "((λ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] unfolding absolutely_integrable_on_def by auto
  next
    case prems: (2 e)
    have "∃y∈sum (λ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 d K where ddiv: "d division_of ⋃d" and "K = (∑k∈d. norm (integral k f))"
      "SUPREMUM {d. d division_of ⋃d} (sum (λk. norm (integral k f))) - e < K"
      by (auto simp add: image_iff not_le)
    then have d: "SUPREMUM {d. d division_of ⋃d} (sum (λk. norm (integral k f))) - e 
                  < (∑k∈d. norm (integral k f))"
      by auto
    note d'=division_ofD[OF ddiv]
    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
    proof (intro conjI impI allI exI)
      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
      proof (rule * [OF d])
        have "(∑k∈d. norm (integral k f)) ≤ sum (λk. integral k (λx. norm (f x))) d"
        proof (intro sum_mono)
          fix k assume "k ∈ d"
          with d'(4) f_int show "norm (integral k f) ≤ integral k (λx. norm (f x))"
            by (force simp: absolutely_integrable_on_def integral_norm_bound_integral)
        qed
        also have "… = integral (⋃d) (λx. norm (f x))"
          apply (rule integral_combine_division_bottomup[OF ddiv, symmetric])
          using absolutely_integrable_on_def d'(4) f_int by blast
        also have "… ≤ integral (cbox a b) (λx. if x ∈ UNIV then norm (f x) else 0)"
        proof -
          have "⋃d ⊆ cbox a b"
            using K(2) ab by fastforce
          then show ?thesis
            using integrable_on_subdivision[OF ddiv] f_int[of a b] unfolding absolutely_integrable_on_def
            by (auto intro!: integral_subset_le)
        qed
        finally show "(∑k∈d. norm (integral k f))
                      ≤ integral (cbox a b) (λx. if x ∈ UNIV then norm (f x) else 0)" .
      next
        have "e/2>0"
          using ‹e > 0› by auto
        moreover
        have f: "f integrable_on cbox a b" "(λx. norm (f x)) integrable_on cbox a b"
          using f_int by (auto simp: absolutely_integrable_on_def)
        ultimately obtain d1 where "gauge d1"
           and 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"
          unfolding has_integral_integral has_integral by meson
        obtain d2 where "gauge d2" 
          and 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"
          by (blast intro: Henstock_lemma [OF f(1) ‹e/2>0›])
        obtain p where
          p: "p tagged_division_of (cbox a b)" "d1 fine p" "d2 fine p"
          by (rule fine_division_exists [OF gauge_Int [OF ‹gauge d1› ‹gauge d2›], of a b])
            (auto simp add: fine_Int)
        have *: "⋀sf sf' si di. ⟦sf' = sf; si ≤ ?S; ¦sf - si¦ < e/2;
                      ¦sf' - di¦ < e/2⟧ ⟹ di < ?S + e"
          by arith
        have "integral (cbox a b) (λx. norm (f x)) < ?S + e"
        proof (rule *)
          show "¦(∑(x,k)∈p. norm (content k *R f x)) - (∑(x,k)∈p. norm (integral k f))¦ < e/2"
            unfolding split_def
            apply (rule absdiff_norm_less)
            using d2[of p] p(1,3) apply (auto simp: tagged_division_of_def split_def)
            done
          show "¦(∑(x,k) ∈ p. content k *R norm (f x)) - integral (cbox a b) (λx. norm(f x))¦ < e/2"
            using d1[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))"
            by (auto simp: split_paired_all sum.cong [OF refl])
          show "(∑(x,k) ∈ p. norm (integral k f)) ≤ ?S"
            using partial_division_of_tagged_division[of p "cbox a b"] p(1)
            apply (subst sum.over_tagged_division_lemma[OF p(1)])
            apply (auto simp: content_eq_0_interior tagged_partial_division_of_def intro!: cSUP_upper2 D)
            done
        qed
        then show "integral (cbox a b) (λx. if x ∈ UNIV then norm (f x) else 0) < ?S + e"
          by simp
      qed
    qed (insert K, auto)
  qed
  then show "(λx. norm (f x)) integrable_on UNIV"
    by blast
qed

lemma absolutely_integrable_add[intro]:
  fixes f g :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  shows "f absolutely_integrable_on s ⟹ g absolutely_integrable_on s ⟹ (λx. f x + g x) absolutely_integrable_on s"
  by (rule set_integral_add)

lemma absolutely_integrable_diff[intro]:
  fixes f g :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  shows "f absolutely_integrable_on s ⟹ g absolutely_integrable_on s ⟹ (λx. f x - g x) absolutely_integrable_on s"
  by (rule set_integral_diff)

lemma absolutely_integrable_linear:
  fixes f :: "'m::euclidean_space ⇒ 'n::euclidean_space"
    and h :: "'n::euclidean_space ⇒ 'p::euclidean_space"
  shows "f absolutely_integrable_on s ⟹ bounded_linear h ⟹ (h ∘ f) absolutely_integrable_on s"
  using integrable_bounded_linear[of h lebesgue "λx. indicator s x *R f x"]
  by (simp add: linear_simps[of h])

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

lemma absolutely_integrable_integrable_bound:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes le: "∀x∈s. norm (f x) ≤ g x" and f: "f integrable_on s" and g: "g integrable_on s"
  shows "f absolutely_integrable_on s"
proof (rule Bochner_Integration.integrable_bound)
  show "g absolutely_integrable_on s"
    unfolding absolutely_integrable_on_def
  proof
    show "(λx. norm (g x)) integrable_on s"
      using le norm_ge_zero[of "f _"]
      by (intro integrable_spike_finite[OF _ _ g, of "{}"])
         (auto intro!: abs_of_nonneg intro: order_trans simp del: norm_ge_zero)
  qed fact
  show "set_borel_measurable lebesgue s f"
    using f by (auto intro: has_integral_implies_lebesgue_measurable simp: integrable_on_def)
qed (use le in ‹auto intro!: always_eventually split: split_indicator›)

subsection ‹Componentwise›

proposition absolutely_integrable_componentwise_iff:
  shows "f absolutely_integrable_on A ⟷ (∀b∈Basis. (λx. f x ∙ b) absolutely_integrable_on A)"
proof -
  have *: "(λx. norm (f x)) integrable_on A ⟷ (∀b∈Basis. (λx. norm (f x ∙ b)) integrable_on A)"
          if "f integrable_on A"
  proof -
    have 1: "⋀i. ⟦(λx. norm (f x)) integrable_on A; i ∈ Basis⟧
                 ⟹ (λx. f x ∙ i) absolutely_integrable_on A"
      apply (rule absolutely_integrable_integrable_bound [where g = "λx. norm(f x)"])
      using Basis_le_norm integrable_component that apply fastforce+
      done
    have 2: "∀i∈Basis. (λx. ¦f x ∙ i¦) integrable_on A ⟹ f absolutely_integrable_on A"
      apply (rule absolutely_integrable_integrable_bound [where g = "λx. ∑i∈Basis. norm (f x ∙ i)"])
      using norm_le_l1 that apply (force intro: integrable_sum)+
      done
    show ?thesis
      apply auto
       apply (metis (full_types) absolutely_integrable_on_def set_integrable_abs 1)
      apply (metis (full_types) absolutely_integrable_on_def 2)
      done
  qed
  show ?thesis
    unfolding absolutely_integrable_on_def
    by (simp add:  integrable_componentwise_iff [symmetric] ball_conj_distrib * cong: conj_cong)
qed

lemma absolutely_integrable_componentwise:
  shows "(⋀b. b ∈ Basis ⟹ (λx. f x ∙ b) absolutely_integrable_on A) ⟹ f absolutely_integrable_on A"
  by (simp add: absolutely_integrable_componentwise_iff)

lemma absolutely_integrable_component:
  "f absolutely_integrable_on A ⟹ (λx. f x ∙ (b :: 'b :: euclidean_space)) absolutely_integrable_on A"
  by (drule absolutely_integrable_linear[OF _ bounded_linear_inner_left[of b]]) (simp add: o_def)


lemma absolutely_integrable_scaleR_left:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
    assumes "f absolutely_integrable_on S"
  shows "(λx. c *R f x) absolutely_integrable_on S"
proof -
  have "(λx. c *R x) o f absolutely_integrable_on S"
    apply (rule absolutely_integrable_linear [OF assms])
    by (simp add: bounded_linear_scaleR_right)
  then show ?thesis by simp
qed

lemma absolutely_integrable_scaleR_right:
  assumes "f absolutely_integrable_on S"
  shows "(λx. f x *R c) absolutely_integrable_on S"
  using assms by blast

lemma absolutely_integrable_norm:
  fixes f :: "'a :: euclidean_space ⇒ 'b :: euclidean_space"
  assumes "f absolutely_integrable_on S"
  shows "(norm o f) absolutely_integrable_on S"
  using assms unfolding absolutely_integrable_on_def by auto
    
lemma absolutely_integrable_abs:
  fixes f :: "'a :: euclidean_space ⇒ 'b :: euclidean_space"
  assumes "f absolutely_integrable_on S"
  shows "(λx. ∑i∈Basis. ¦f x ∙ i¦ *R i) absolutely_integrable_on S"
        (is "?g absolutely_integrable_on S")
proof -
  have eq: "?g =
        (λx. ∑i∈Basis. ((λy. ∑j∈Basis. if j = i then y *R j else 0) ∘
               (λx. norm(∑j∈Basis. if j = i then (x ∙ i) *R j else 0)) ∘ f) x)"
    by (simp add: sum.delta)
  have *: "(λy. ∑j∈Basis. if j = i then y *R j else 0) ∘
           (λx. norm (∑j∈Basis. if j = i then (x ∙ i) *R j else 0)) ∘ f 
           absolutely_integrable_on S" 
        if "i ∈ Basis" for i
  proof -
    have "bounded_linear (λy. ∑j∈Basis. if j = i then y *R j else 0)"
      by (simp add: linear_linear algebra_simps linearI)
    moreover have "(λx. norm (∑j∈Basis. if j = i then (x ∙ i) *R j else 0)) ∘ f 
                   absolutely_integrable_on S"
      unfolding o_def
      apply (rule absolutely_integrable_norm [unfolded o_def])
      using assms ‹i ∈ Basis›
      apply (auto simp: algebra_simps dest: absolutely_integrable_component[where b=i])
      done
    ultimately show ?thesis
      by (subst comp_assoc) (blast intro: absolutely_integrable_linear)
  qed
  show ?thesis
    apply (rule ssubst [OF eq])
    apply (rule absolutely_integrable_sum)
     apply (force simp: intro!: *)+
    done
qed

lemma abs_absolutely_integrableI_1:
  fixes f :: "'a :: euclidean_space ⇒ real"
  assumes f: "f integrable_on A" and "(λx. ¦f x¦) integrable_on A"
  shows "f absolutely_integrable_on A"
  by (rule absolutely_integrable_integrable_bound [OF _ assms]) auto

  
lemma abs_absolutely_integrableI:
  assumes f: "f integrable_on S" and fcomp: "(λx. ∑i∈Basis. ¦f x ∙ i¦ *R i) integrable_on S"
  shows "f absolutely_integrable_on S"
proof -
  have "(λx. (f x ∙ i) *R i) absolutely_integrable_on S" if "i ∈ Basis" for i
  proof -
    have "(λx. ¦f x ∙ i¦) integrable_on S" 
      using assms integrable_component [OF fcomp, where y=i] that by simp
    then have "(λx. f x ∙ i) absolutely_integrable_on S"
      apply -
      apply (rule abs_absolutely_integrableI_1, auto)
      by (simp add: f integrable_component)
    then show ?thesis
      by (rule absolutely_integrable_scaleR_right)
  qed
  then have "(λx. ∑i∈Basis. (f x ∙ i) *R i) absolutely_integrable_on S"
    by (simp add: absolutely_integrable_sum)
  then show ?thesis
    by (simp add: euclidean_representation)
qed

    
lemma absolutely_integrable_abs_iff:
   "f absolutely_integrable_on S ⟷
    f integrable_on S ∧ (λx. ∑i∈Basis. ¦f x ∙ i¦ *R i) integrable_on S"
    (is "?lhs = ?rhs")
proof
  assume ?lhs then show ?rhs
    using absolutely_integrable_abs absolutely_integrable_on_def by blast
next
  assume ?rhs 
  moreover
  have "(λx. if x ∈ S then ∑i∈Basis. ¦f x ∙ i¦ *R i else 0) = (λx. ∑i∈Basis. ¦(if x ∈ S then f x else 0) ∙ i¦ *R i)"
    by force
  ultimately show ?lhs
    by (simp only: absolutely_integrable_restrict_UNIV [of S, symmetric] integrable_restrict_UNIV [of S, symmetric] abs_absolutely_integrableI)
qed

lemma absolutely_integrable_max:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "f absolutely_integrable_on S" "g absolutely_integrable_on S"
   shows "(λx. ∑i∈Basis. max (f x ∙ i) (g x ∙ i) *R i)
            absolutely_integrable_on S"
proof -
  have "(λx. ∑i∈Basis. max (f x ∙ i) (g x ∙ i) *R i) = 
        (λx. (1/2) *R (f x + g x + (∑i∈Basis. ¦f x ∙ i - g x ∙ i¦ *R i)))"
  proof (rule ext)
    fix x
    have "(∑i∈Basis. max (f x ∙ i) (g x ∙ i) *R i) = (∑i∈Basis. ((f x ∙ i + g x ∙ i + ¦f x ∙ i - g x ∙ i¦) / 2) *R i)"
      by (force intro: sum.cong)
    also have "... = (1 / 2) *R (∑i∈Basis. (f x ∙ i + g x ∙ i + ¦f x ∙ i - g x ∙ i¦) *R i)"
      by (simp add: scaleR_right.sum)
    also have "... = (1 / 2) *R (f x + g x + (∑i∈Basis. ¦f x ∙ i - g x ∙ i¦ *R i))"
      by (simp add: sum.distrib algebra_simps euclidean_representation)
    finally
    show "(∑i∈Basis. max (f x ∙ i) (g x ∙ i) *R i) =
         (1 / 2) *R (f x + g x + (∑i∈Basis. ¦f x ∙ i - g x ∙ i¦ *R i))" .
  qed
  moreover have "(λx. (1 / 2) *R (f x + g x + (∑i∈Basis. ¦f x ∙ i - g x ∙ i¦ *R i))) 
                 absolutely_integrable_on S"
    apply (intro absolutely_integrable_add absolutely_integrable_scaleR_left assms)
    using absolutely_integrable_abs [OF absolutely_integrable_diff [OF assms]]
    apply (simp add: algebra_simps)
    done
  ultimately show ?thesis by metis
qed
  
corollary absolutely_integrable_max_1:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "f absolutely_integrable_on S" "g absolutely_integrable_on S"
   shows "(λx. max (f x) (g x)) absolutely_integrable_on S"
  using absolutely_integrable_max [OF assms] by simp

lemma absolutely_integrable_min:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "f absolutely_integrable_on S" "g absolutely_integrable_on S"
   shows "(λx. ∑i∈Basis. min (f x ∙ i) (g x ∙ i) *R i)
            absolutely_integrable_on S"
proof -
  have "(λx. ∑i∈Basis. min (f x ∙ i) (g x ∙ i) *R i) = 
        (λx. (1/2) *R (f x + g x - (∑i∈Basis. ¦f x ∙ i - g x ∙ i¦ *R i)))"
  proof (rule ext)
    fix x
    have "(∑i∈Basis. min (f x ∙ i) (g x ∙ i) *R i) = (∑i∈Basis. ((f x ∙ i + g x ∙ i - ¦f x ∙ i - g x ∙ i¦) / 2) *R i)"
      by (force intro: sum.cong)
    also have "... = (1 / 2) *R (∑i∈Basis. (f x ∙ i + g x ∙ i - ¦f x ∙ i - g x ∙ i¦) *R i)"
      by (simp add: scaleR_right.sum)
    also have "... = (1 / 2) *R (f x + g x - (∑i∈Basis. ¦f x ∙ i - g x ∙ i¦ *R i))"
      by (simp add: sum.distrib sum_subtractf algebra_simps euclidean_representation)
    finally
    show "(∑i∈Basis. min (f x ∙ i) (g x ∙ i) *R i) =
         (1 / 2) *R (f x + g x - (∑i∈Basis. ¦f x ∙ i - g x ∙ i¦ *R i))" .
  qed
  moreover have "(λx. (1 / 2) *R (f x + g x - (∑i∈Basis. ¦f x ∙ i - g x ∙ i¦ *R i))) 
                 absolutely_integrable_on S"
    apply (intro absolutely_integrable_add absolutely_integrable_diff absolutely_integrable_scaleR_left assms)
    using absolutely_integrable_abs [OF absolutely_integrable_diff [OF assms]]
    apply (simp add: algebra_simps)
    done
  ultimately show ?thesis by metis
qed
  
corollary absolutely_integrable_min_1:
  fixes f :: "'n::euclidean_space ⇒ real"
  assumes "f absolutely_integrable_on S" "g absolutely_integrable_on S"
   shows "(λx. min (f x) (g x)) absolutely_integrable_on S"
  using absolutely_integrable_min [OF assms] by simp

lemma nonnegative_absolutely_integrable:
  fixes f :: "'a :: euclidean_space ⇒ 'b :: euclidean_space"
  assumes "f integrable_on A" and comp: "⋀x b. ⟦x ∈ A; b ∈ Basis⟧ ⟹ 0 ≤ f x ∙ b"
  shows "f absolutely_integrable_on A"
proof -
  have "(λx. (f x ∙ i) *R i) absolutely_integrable_on A" if "i ∈ Basis" for i
  proof -
    have "(λx. f x ∙ i) integrable_on A" 
      by (simp add: assms(1) integrable_component)
    then have "(λx. f x ∙ i) absolutely_integrable_on A"
      by (metis that comp nonnegative_absolutely_integrable_1)
    then show ?thesis
      by (rule absolutely_integrable_scaleR_right)
  qed
  then have "(λx. ∑i∈Basis. (f x ∙ i) *R i) absolutely_integrable_on A"
    by (simp add: absolutely_integrable_sum)
  then show ?thesis
    by (simp add: euclidean_representation)
qed

  
lemma absolutely_integrable_component_ubound:
  fixes f :: "'a :: euclidean_space ⇒ 'b :: euclidean_space"
  assumes f: "f integrable_on A" and g: "g absolutely_integrable_on A"
      and comp: "⋀x b. ⟦x ∈ A; b ∈ Basis⟧ ⟹ f x ∙ b ≤ g x ∙ b"
  shows "f absolutely_integrable_on A"
proof -
  have "(λx. g x - (g x - f x)) absolutely_integrable_on A"
    apply (rule absolutely_integrable_diff [OF g nonnegative_absolutely_integrable])
    using Henstock_Kurzweil_Integration.integrable_diff absolutely_integrable_on_def f g apply blast
    by (simp add: comp inner_diff_left)
  then show ?thesis
    by simp
qed


lemma absolutely_integrable_component_lbound:
  fixes f :: "'a :: euclidean_space ⇒ 'b :: euclidean_space"
  assumes f: "f absolutely_integrable_on A" and g: "g integrable_on A"
      and comp: "⋀x b. ⟦x ∈ A; b ∈ Basis⟧ ⟹ f x ∙ b ≤ g x ∙ b"
  shows "g absolutely_integrable_on A"
proof -
  have "(λx. f x + (g x - f x)) absolutely_integrable_on A"
    apply (rule absolutely_integrable_add [OF f nonnegative_absolutely_integrable])
    using Henstock_Kurzweil_Integration.integrable_diff absolutely_integrable_on_def f g apply blast
    by (simp add: comp inner_diff_left)
  then show ?thesis
    by simp
qed

subsection ‹Dominated convergence›

lemma dominated_convergence:
  fixes f :: "nat ⇒ 'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes f: "⋀k. (f k) integrable_on s" and h: "h integrable_on s"
    and le: "⋀k. ∀x ∈ s. norm (f k x) ≤ h x"
    and conv: "∀x ∈ s. (λk. f k x) ⇢ g x"
  shows "g integrable_on s" "(λk. integral s (f k)) ⇢ integral s g"
proof -
  have 3: "h absolutely_integrable_on s"
    unfolding absolutely_integrable_on_def
  proof
    show "(λx. norm (h x)) integrable_on s"
    proof (intro integrable_spike_finite[OF _ _ h, of "{}"] ballI)
      fix x assume "x ∈ s - {}" then show "norm (h x) = h x"
        by (metis Diff_empty abs_of_nonneg bot_set_def le norm_ge_zero order_trans real_norm_def)
    qed auto
  qed fact
  have 2: "set_borel_measurable lebesgue s (f k)" for k
    using f by (auto intro: has_integral_implies_lebesgue_measurable simp: integrable_on_def)
  then have 1: "set_borel_measurable lebesgue s g"
    by (rule borel_measurable_LIMSEQ_metric) (use conv in ‹auto split: split_indicator›)
  have 4: "AE x in lebesgue. (λi. indicator s x *R f i x) ⇢ indicator s x *R g x"
    "AE x in lebesgue. norm (indicator s x *R f k x) ≤ indicator s x *R h x" for k
    using conv le by (auto intro!: always_eventually split: split_indicator)

  have g: "g absolutely_integrable_on s"
    using 1 2 3 4 by (rule integrable_dominated_convergence)
  then show "g integrable_on s"
    by (auto simp: absolutely_integrable_on_def)
  have "(λk. (LINT x:s|lebesgue. f k x)) ⇢ (LINT x:s|lebesgue. g x)"
    using 1 2 3 4 by (rule integral_dominated_convergence)
  then show "(λk. integral s (f k)) ⇢ integral s g"
    using g absolutely_integrable_integrable_bound[OF le f h]
    by (subst (asm) (1 2) set_lebesgue_integral_eq_integral) auto
qed

lemma has_integral_dominated_convergence:
  fixes f :: "nat ⇒ 'n::euclidean_space ⇒ 'm::euclidean_space"
  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 ‹Fundamental Theorem of Calculus for the Lebesgue integral›

text ‹

For the positive integral we replace continuity with Borel-measurability.

›

lemma                                                                                          
  fixes f :: "real ⇒ real"
  assumes [measurable]: "f ∈ borel_measurable borel"
  assumes f: "⋀x. x ∈ {a..b} ⟹ DERIV F x :> f x" "⋀x. x ∈ {a..b} ⟹ 0 ≤ f x" and "a ≤ b"
  shows nn_integral_FTC_Icc: "(∫+x. ennreal (f x) * indicator {a .. b} x ∂lborel) = F b - F a" (is ?nn)
    and has_bochner_integral_FTC_Icc_nonneg:
      "has_bochner_integral lborel (λx. f x * indicator {a .. b} x) (F b - F a)" (is ?has)
    and integral_FTC_Icc_nonneg: "(∫x. f x * indicator {a .. b} x ∂lborel) = F b - F a" (is ?eq)
    and integrable_FTC_Icc_nonneg: "integrable lborel (λx. f x * indicator {a .. b} x)" (is ?int)
proof -
  have *: "(λx. f x * indicator {a..b} x) ∈ borel_measurable borel" "⋀x. 0 ≤ f x * indicator {a..b} x"
    using f(2) by (auto split: split_indicator)

  have F_mono: "a ≤ x ⟹ x ≤ y ⟹ y ≤ b⟹ F x ≤ F y" for x y
    using f by (intro DERIV_nonneg_imp_nondecreasing[of x y F]) (auto intro: order_trans)

  have "(f has_integral F b - F a) {a..b}"
    by (intro fundamental_theorem_of_calculus)
       (auto simp: has_field_derivative_iff_has_vector_derivative[symmetric]
             intro: has_field_derivative_subset[OF f(1)] ‹a ≤ b›)
  then have i: "((λx. f x * indicator {a .. b} x) has_integral F b - F a) UNIV"
    unfolding indicator_def if_distrib[where f="λx. a * x" for a]
    by (simp cong del: if_weak_cong del: atLeastAtMost_iff)
  then have nn: "(∫+x. f x * indicator {a .. b} x ∂lborel) = F b - F a"
    by (rule nn_integral_has_integral_lborel[OF *])
  then show ?has
    by (rule has_bochner_integral_nn_integral[rotated 3]) (simp_all add: * F_mono ‹a ≤ b›)
  then show ?eq ?int
    unfolding has_bochner_integral_iff by auto
  show ?nn
    by (subst nn[symmetric])
       (auto intro!: nn_integral_cong simp add: ennreal_mult f split: split_indicator)
qed

lemma
  fixes f :: "real ⇒ 'a :: euclidean_space"
  assumes "a ≤ b"
  assumes "⋀x. a ≤ x ⟹ x ≤ b ⟹ (F has_vector_derivative f x) (at x within {a .. b})"
  assumes cont: "continuous_on {a .. b} f"
  shows has_bochner_integral_FTC_Icc:
      "has_bochner_integral lborel (λx. indicator {a .. b} x *R f x) (F b - F a)" (is ?has)
    and integral_FTC_Icc: "(∫x. indicator {a .. b} x *R f x ∂lborel) = F b - F a" (is ?eq)
proof -
  let ?f = "λx. indicator {a .. b} x *R f x"
  have int: "integrable lborel ?f"
    using borel_integrable_compact[OF _ cont] by auto
  have "(f has_integral F b - F a) {a..b}"
    using assms(1,2) by (intro fundamental_theorem_of_calculus) auto
  moreover
  have "(f has_integral integralL lborel ?f) {a..b}"
    using has_integral_integral_lborel[OF int]
    unfolding indicator_def if_distrib[where f="λx. x *R a" for a]
    by (simp cong del: if_weak_cong del: atLeastAtMost_iff)
  ultimately show ?eq
    by (auto dest: has_integral_unique)
  then show ?has
    using int by (auto simp: has_bochner_integral_iff)
qed

lemma
  fixes f :: "real ⇒ real"
  assumes "a ≤ b"
  assumes deriv: "⋀x. a ≤ x ⟹ x ≤ b ⟹ DERIV F x :> f x"
  assumes cont: "⋀x. a ≤ x ⟹ x ≤ b ⟹ isCont f x"
  shows has_bochner_integral_FTC_Icc_real:
      "has_bochner_integral lborel (λx. f x * indicator {a .. b} x) (F b - F a)" (is ?has)
    and integral_FTC_Icc_real: "(∫x. f x * indicator {a .. b} x ∂lborel) = F b - F a" (is ?eq)
proof -
  have 1: "⋀x. a ≤ x ⟹ x ≤ b ⟹ (F has_vector_derivative f x) (at x within {a .. b})"
    unfolding has_field_derivative_iff_has_vector_derivative[symmetric]
    using deriv by (auto intro: DERIV_subset)
  have 2: "continuous_on {a .. b} f"
    using cont by (intro continuous_at_imp_continuous_on) auto
  show ?has ?eq
    using has_bochner_integral_FTC_Icc[OF ‹a ≤ b› 1 2] integral_FTC_Icc[OF ‹a ≤ b› 1 2]
    by (auto simp: mult.commute)
qed

lemma nn_integral_FTC_atLeast:
  fixes f :: "real ⇒ real"
  assumes f_borel: "f ∈ borel_measurable borel"
  assumes f: "⋀x. a ≤ x ⟹ DERIV F x :> f x"
  assumes nonneg: "⋀x. a ≤ x ⟹ 0 ≤ f x"
  assumes lim: "(F ⤏ T) at_top"
  shows "(∫+x. ennreal (f x) * indicator {a ..} x ∂lborel) = T - F a"
proof -
  let ?f = "λ(i::nat) (x::real). ennreal (f x) * indicator {a..a + real i} x"
  let ?fR = "λx. ennreal (f x) * indicator {a ..} x"

  have F_mono: "a ≤ x ⟹ x ≤ y ⟹ F x ≤ F y" for x y
    using f nonneg by (intro DERIV_nonneg_imp_nondecreasing[of x y F]) (auto intro: order_trans)
  then have F_le_T: "a ≤ x ⟹ F x ≤ T" for x
    by (intro tendsto_lowerbound[OF lim])
       (auto simp: eventually_at_top_linorder)

  have "(SUP i::nat. ?f i x) = ?fR x" for x
  proof (rule LIMSEQ_unique[OF LIMSEQ_SUP])
    obtain n where "x - a < real n"
      using reals_Archimedean2[of "x - a"] ..
    then have "eventually (λn. ?f n x = ?fR x) sequentially"
      by (auto intro!: eventually_sequentiallyI[where c=n] split: split_indicator)
    then show "(λn. ?f n x) ⇢ ?fR x"
      by (rule Lim_eventually)
  qed (auto simp: nonneg incseq_def le_fun_def split: split_indicator)
  then have "integralN lborel ?fR = (∫+ x. (SUP i::nat. ?f i x) ∂lborel)"
    by simp
  also have "… = (SUP i::nat. (∫+ x. ?f i x ∂lborel))"
  proof (rule nn_integral_monotone_convergence_SUP)
    show "incseq ?f"
      using nonneg by (auto simp: incseq_def le_fun_def split: split_indicator)
    show "⋀i. (?f i) ∈ borel_measurable lborel"
      using f_borel by auto
  qed
  also have "… = (SUP i::nat. ennreal (F (a + real i) - F a))"
    by (subst nn_integral_FTC_Icc[OF f_borel f nonneg]) auto
  also have "… = T - F a"
  proof (rule LIMSEQ_unique[OF LIMSEQ_SUP])
    have "(λx. F (a + real x)) ⇢ T"
      apply (rule filterlim_compose[OF lim filterlim_tendsto_add_at_top])
      apply (rule LIMSEQ_const_iff[THEN iffD2, OF refl])
      apply (rule filterlim_real_sequentially)
      done
    then show "(λn. ennreal (F (a + real n) - F a)) ⇢ ennreal (T - F a)"
      by (simp add: F_mono F_le_T tendsto_diff)
  qed (auto simp: incseq_def intro!: ennreal_le_iff[THEN iffD2] F_mono)
  finally show ?thesis .
qed

lemma integral_power:
  "a ≤ b ⟹ (∫x. x^k * indicator {a..b} x ∂lborel) = (b^Suc k - a^Suc k) / Suc k"
proof (subst integral_FTC_Icc_real)
  fix x show "DERIV (λx. x^Suc k / Suc k) x :> x^k"
    by (intro derivative_eq_intros) auto
qed (auto simp: field_simps simp del: of_nat_Suc)

subsection ‹Integration by parts›

lemma integral_by_parts_integrable:
  fixes f g F G::"real ⇒ real"
  assumes "a ≤ b"
  assumes cont_f[intro]: "!!x. a ≤x ⟹ x≤b ⟹ isCont f x"
  assumes cont_g[intro]: "!!x. a ≤x ⟹ x≤b ⟹ isCont g x"
  assumes [intro]: "!!x. DERIV F x :> f x"
  assumes [intro]: "!!x. DERIV G x :> g x"
  shows  "integrable lborel (λx.((F x) * (g x) + (f x) * (G x)) * indicator {a .. b} x)"
  by (auto intro!: borel_integrable_atLeastAtMost continuous_intros) (auto intro!: DERIV_isCont)

lemma integral_by_parts:
  fixes f g F G::"real ⇒ real"
  assumes [arith]: "a ≤ b"
  assumes cont_f[intro]: "!!x. a ≤x ⟹ x≤b ⟹ isCont f x"
  assumes cont_g[intro]: "!!x. a ≤x ⟹ x≤b ⟹ isCont g x"
  assumes [intro]: "!!x. DERIV F x :> f x"
  assumes [intro]: "!!x. DERIV G x :> g x"
  shows "(∫x. (F x * g x) * indicator {a .. b} x ∂lborel)
            =  F b * G b - F a * G a - ∫x. (f x * G x) * indicator {a .. b} x ∂lborel"
proof-
  have 0: "(∫x. (F x * g x + f x * G x) * indicator {a .. b} x ∂lborel) = F b * G b - F a * G a"
    by (rule integral_FTC_Icc_real, auto intro!: derivative_eq_intros continuous_intros)
      (auto intro!: DERIV_isCont)

  have "(∫x. (F x * g x + f x * G x) * indicator {a .. b} x ∂lborel) =
    (∫x. (F x * g x) * indicator {a .. b} x ∂lborel) + ∫x. (f x * G x) * indicator {a .. b} x ∂lborel"
    apply (subst Bochner_Integration.integral_add[symmetric])
    apply (auto intro!: borel_integrable_atLeastAtMost continuous_intros)
    by (auto intro!: DERIV_isCont Bochner_Integration.integral_cong split: split_indicator)

  thus ?thesis using 0 by auto
qed

lemma integral_by_parts':
  fixes f g F G::"real ⇒ real"
  assumes "a ≤ b"
  assumes "!!x. a ≤x ⟹ x≤b ⟹ isCont f x"
  assumes "!!x. a ≤x ⟹ x≤b ⟹ isCont g x"
  assumes "!!x. DERIV F x :> f x"
  assumes "!!x. DERIV G x :> g x"
  shows "(∫x. indicator {a .. b} x *R (F x * g x) ∂lborel)
            =  F b * G b - F a * G a - ∫x. indicator {a .. b} x *R (f x * G x) ∂lborel"
  using integral_by_parts[OF assms] by (simp add: ac_simps)

lemma has_bochner_integral_even_function:
  fixes f :: "real ⇒ 'a :: {banach, second_countable_topology}"
  assumes f: "has_bochner_integral lborel (λx. indicator {0..} x *R f x) x"
  assumes even: "⋀x. f (- x) = f x"
  shows "has_bochner_integral lborel f (2 *R x)"
proof -
  have indicator: "⋀x::real. indicator {..0} (- x) = indicator {0..} x"
    by (auto split: split_indicator)
  have "has_bochner_integral lborel (λx. indicator {.. 0} x *R f x) x"
    by (subst lborel_has_bochner_integral_real_affine_iff[where c="-1" and t=0])
       (auto simp: indicator even f)
  with f have "has_bochner_integral lborel (λx. indicator {0..} x *R f x + indicator {.. 0} x *R f x) (x + x)"
    by (rule has_bochner_integral_add)
  then have "has_bochner_integral lborel f (x + x)"
    by (rule has_bochner_integral_discrete_difference[where X="{0}", THEN iffD1, rotated 4])
       (auto split: split_indicator)
  then show ?thesis
    by (simp add: scaleR_2)
qed

lemma has_bochner_integral_odd_function:
  fixes f :: "real ⇒ 'a :: {banach, second_countable_topology}"
  assumes f: "has_bochner_integral lborel (λx. indicator {0..} x *R f x) x"
  assumes odd: "⋀x. f (- x) = - f x"
  shows "has_bochner_integral lborel f 0"
proof -
  have indicator: "⋀x::real. indicator {..0} (- x) = indicator {0..} x"
    by (auto split: split_indicator)
  have "has_bochner_integral lborel (λx. - indicator {.. 0} x *R f x) x"
    by (subst lborel_has_bochner_integral_real_affine_iff[where c="-1" and t=0])
       (auto simp: indicator odd f)
  from has_bochner_integral_minus[OF this]
  have "has_bochner_integral lborel (λx. indicator {.. 0} x *R f x) (- x)"
    by simp
  with f have "has_bochner_integral lborel (λx. indicator {0..} x *R f x + indicator {.. 0} x *R f x) (x + - x)"
    by (rule has_bochner_integral_add)
  then have "has_bochner_integral lborel f (x + - x)"
    by (rule has_bochner_integral_discrete_difference[where X="{0}", THEN iffD1, rotated 4])
       (auto split: split_indicator)
  then show ?thesis
    by simp
qed

lemma has_integral_0_closure_imp_0:
  fixes f :: "'a::euclidean_space ⇒ real"
  assumes f: "continuous_on (closure S) f"
    and nonneg_interior: "⋀x. x ∈ S ⟹ 0 ≤ f x"
    and pos: "0 < emeasure lborel S"
    and finite: "emeasure lborel S < ∞"
    and regular: "emeasure lborel (closure S) = emeasure lborel S"
    and opn: "open S"
  assumes int: "(f has_integral 0) (closure S)"
  assumes x: "x ∈ closure S"
  shows "f x = 0"
proof -
  have zero: "emeasure lborel (frontier S) = 0"
    using finite closure_subset regular
    unfolding frontier_def
    by (subst emeasure_Diff) (auto simp: frontier_def interior_open ‹open S› )
  have nonneg: "0 ≤ f x" if "x ∈ closure S" for x
    using continuous_ge_on_closure[OF f that nonneg_interior] by simp
  have "0 = integral (closure S) f"
    by (blast intro: int sym)
  also
  note intl = has_integral_integrable[OF int]
  have af: "f absolutely_integrable_on (closure S)"
    using nonneg
    by (intro absolutely_integrable_onI intl integrable_eq[OF intl]) simp
  then have "integral (closure S) f = set_lebesgue_integral lebesgue (closure S) f"
    by (intro set_lebesgue_integral_eq_integral(2)[symmetric])
  also have "… = 0 ⟷ (AE x in lebesgue. indicator (closure S) x *R f x = 0)"
    by (rule integral_nonneg_eq_0_iff_AE[OF af]) (use nonneg in ‹auto simp: indicator_def›)
  also have "… ⟷ (AE x in lebesgue. x ∈ {x. x ∈ closure S ⟶ f x = 0})"
    by (auto simp: indicator_def)
  finally have "(AE x in lebesgue. x ∈ {x. x ∈ closure S ⟶ f x = 0})" by simp
  moreover have "(AE x in lebesgue. x ∈ - frontier S)"
    using zero
    by (auto simp: eventually_ae_filter null_sets_def intro!: exI[where x="frontier S"])
  ultimately have ae: "AE x ∈ S in lebesgue. x ∈ {x ∈ closure S. f x = 0}" (is ?th)
    by eventually_elim (use closure_subset in ‹auto simp: ›)
  have "closed {0::real}" by simp
  with continuous_on_closed_vimage[OF closed_closure, of S f] f
  have "closed (f -` {0} ∩ closure S)" by blast
  then have "closed {x ∈ closure S. f x = 0}" by (auto simp: vimage_def Int_def conj_commute)
  with ‹open S› have "x ∈ {x ∈ closure S. f x = 0}" if "x ∈ S" for x using ae that
    by (rule mem_closed_if_AE_lebesgue_open)
  then have "f x = 0" if "x ∈ S" for x using that by auto
  from continuous_constant_on_closure[OF f this ‹x ∈ closure S›]
  show "f x = 0" .
qed

lemma has_integral_0_cbox_imp_0:
  fixes f :: "'a::euclidean_space ⇒ real"
  assumes f: "continuous_on (cbox a b) f"
    and nonneg_interior: "⋀x. x ∈ box a b ⟹ 0 ≤ f x"
  assumes int: "(f has_integral 0) (cbox a b)"
  assumes ne: "box a b ≠ {}"
  assumes x: "x ∈ cbox a b"
  shows "f x = 0"
proof -
  have "0 < emeasure lborel (box a b)"
    using ne x unfolding emeasure_lborel_box_eq
    by (force intro!: prod_pos simp: mem_box algebra_simps)
  then show ?thesis using assms
    by (intro has_integral_0_closure_imp_0[of "box a b" f x])
      (auto simp: emeasure_lborel_box_eq emeasure_lborel_cbox_eq algebra_simps mem_box)
qed

end