source
stringlengths
17
118
lean4
stringlengths
0
335k
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue.lean
import Mathlib.MeasureTheory.Integral.Lebesgue.Basic import Mathlib.MeasureTheory.Integral.Lebesgue.Countable import Mathlib.MeasureTheory.Integral.Lebesgue.MeasurePreserving import Mathlib.MeasureTheory.Integral.Lebesgue.Norm deprecated_module (since := "2025-04-13")
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Periodic.lean
import Mathlib.MeasureTheory.Integral.IntervalIntegral.Periodic deprecated_module (since := "2025-04-13")
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Layercake.lean
import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic /-! # The layer cake formula / Cavalieri's principle / tail probability formula In this file we prove the following layer cake formula. Consider a non-negative measurable function `f` on a measure space. Apply pointwise to it an increasing absolutely continuous function `G : ℝ≥0 → ℝ≥0` vanishing at the origin, with derivative `G' = g` on the positive real line (in other words, `G` a primitive of a non-negative locally integrable function `g` on the positive real line). Then the integral of the result, `∫ G ∘ f`, can be written as the integral over the positive real line of the "tail measures" of `f` (i.e., a function giving the measures of the sets on which `f` exceeds different positive real values) weighted by `g`. In probability theory contexts, the "tail measures" could be referred to as "tail probabilities" of the random variable `f`, or as values of the "complementary cumulative distribution function" of the random variable `f`. The terminology "tail probability formula" is therefore occasionally used for the layer cake formula (or a standard application of it). The essence of the (mathematical) proof is Fubini's theorem. We also give the most common application of the layer cake formula - a representation of the integral of a nonnegative function f: ∫ f(ω) ∂μ(ω) = ∫ μ {ω | f(ω) ≥ t} dt Variants of the formulas with measures of sets of the form {ω | f(ω) > t} instead of {ω | f(ω) ≥ t} are also included. ## Main results * `MeasureTheory.lintegral_comp_eq_lintegral_meas_le_mul` and `MeasureTheory.lintegral_comp_eq_lintegral_meas_lt_mul`: The general layer cake formulas with Lebesgue integrals, written in terms of measures of sets of the forms {ω | t ≤ f(ω)} and {ω | t < f(ω)}, respectively. * `MeasureTheory.lintegral_eq_lintegral_meas_le` and `MeasureTheory.lintegral_eq_lintegral_meas_lt`: The most common special cases of the layer cake formulas, stating that for a nonnegative function f we have ∫ f(ω) ∂μ(ω) = ∫ μ {ω | f(ω) ≥ t} dt and ∫ f(ω) ∂μ(ω) = ∫ μ {ω | f(ω) > t} dt, respectively. * `Integrable.integral_eq_integral_meas_lt`: A Bochner integral version of the most common special case of the layer cake formulas, stating that for an integrable and a.e.-nonnegative function f we have ∫ f(ω) ∂μ(ω) = ∫ μ {ω | f(ω) > t} dt. ## See also Another common application, a representation of the integral of a real power of a nonnegative function, is given in `Mathlib/Analysis/SpecialFunctions/Pow/Integral.lean`. ## Tags layer cake representation, Cavalieri's principle, tail probability formula -/ noncomputable section open scoped ENNReal MeasureTheory Topology open Set MeasureTheory Filter Measure namespace MeasureTheory section variable {α R : Type*} [MeasurableSpace α] (μ : Measure α) [LinearOrder R] theorem countable_meas_le_ne_meas_lt (g : α → R) : {t : R | μ {a : α | t ≤ g a} ≠ μ {a : α | t < g a}}.Countable := by -- the target set is contained in the set of points where the function `t ↦ μ {a : α | t ≤ g a}` -- jumps down on the right of `t`. This jump set is countable for any function. let F : R → ℝ≥0∞ := fun t ↦ μ {a : α | t ≤ g a} apply (countable_image_gt_image_Ioi F).mono intro t ht have : μ {a | t < g a} < μ {a | t ≤ g a} := lt_of_le_of_ne (measure_mono (fun a ha ↦ le_of_lt ha)) (Ne.symm ht) exact ⟨μ {a | t < g a}, this, fun s hs ↦ measure_mono (fun a ha ↦ hs.trans_le ha)⟩ theorem meas_le_ae_eq_meas_lt {R : Type*} [LinearOrder R] [MeasurableSpace R] (ν : Measure R) [NoAtoms ν] (g : α → R) : (fun t => μ {a : α | t ≤ g a}) =ᵐ[ν] fun t => μ {a : α | t < g a} := Set.Countable.measure_zero (countable_meas_le_ne_meas_lt μ g) _ end /-! ### Layercake formula -/ section Layercake variable {α : Type*} [MeasurableSpace α] {f : α → ℝ} {g : ℝ → ℝ} /-- An auxiliary version of the layer cake formula (Cavalieri's principle, tail probability formula), with a measurability assumption that would also essentially follow from the integrability assumptions, and a sigma-finiteness assumption. See `MeasureTheory.lintegral_comp_eq_lintegral_meas_le_mul` and `MeasureTheory.lintegral_comp_eq_lintegral_meas_lt_mul` for the main formulations of the layer cake formula. -/ theorem lintegral_comp_eq_lintegral_meas_le_mul_of_measurable_of_sigmaFinite (μ : Measure α) [SFinite μ] (f_nn : 0 ≤ f) (f_mble : Measurable f) (g_intble : ∀ t > 0, IntervalIntegrable g volume 0 t) (g_mble : Measurable g) (g_nn : ∀ t > 0, 0 ≤ g t) : ∫⁻ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂μ = ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) := by have g_intble' : ∀ t : ℝ, 0 ≤ t → IntervalIntegrable g volume 0 t := by intro t ht rcases eq_or_lt_of_le ht with h | h · simp [← h] · exact g_intble t h have integrand_eq : ∀ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) = ∫⁻ t in Ioc 0 (f ω), ENNReal.ofReal (g t) := by intro ω have g_ae_nn : 0 ≤ᵐ[volume.restrict (Ioc 0 (f ω))] g := by filter_upwards [self_mem_ae_restrict (measurableSet_Ioc : MeasurableSet (Ioc 0 (f ω)))] with x hx using g_nn x hx.1 rw [← ofReal_integral_eq_lintegral_ofReal (g_intble' (f ω) (f_nn ω)).1 g_ae_nn] congr exact intervalIntegral.integral_of_le (f_nn ω) rw [lintegral_congr integrand_eq] simp_rw [← lintegral_indicator measurableSet_Ioc] rw [← lintegral_indicator measurableSet_Ioi, lintegral_lintegral_swap] · apply congr_arg funext s have aux₁ : (fun x => (Ioc 0 (f x)).indicator (fun t : ℝ => ENNReal.ofReal (g t)) s) = fun x => ENNReal.ofReal (g s) * (Ioi (0 : ℝ)).indicator (fun _ => 1) s * (Ici s).indicator (fun _ : ℝ => (1 : ℝ≥0∞)) (f x) := by funext a by_cases h : s ∈ Ioc (0 : ℝ) (f a) · simp only [h, show s ∈ Ioi (0 : ℝ) from h.1, show f a ∈ Ici s from h.2, indicator_of_mem, mul_one] · have h_copy := h simp only [mem_Ioc, not_and, not_le] at h by_cases h' : 0 < s · simp only [h_copy, h h', indicator_of_notMem, not_false_iff, mem_Ici, not_le, mul_zero] · have : s ∉ Ioi (0 : ℝ) := h' simp only [this, h', indicator_of_notMem, not_false_iff, mul_zero, zero_mul, mem_Ioc, false_and] simp_rw [aux₁] rw [lintegral_const_mul'] swap · apply ENNReal.mul_ne_top ENNReal.ofReal_ne_top by_cases h : (0 : ℝ) < s <;> · simp [h] simp_rw [show (fun a => (Ici s).indicator (fun _ : ℝ => (1 : ℝ≥0∞)) (f a)) = fun a => {a : α | s ≤ f a}.indicator (fun _ => 1) a by funext a; by_cases h : s ≤ f a <;> simp [h]] rw [lintegral_indicator₀] swap; · exact f_mble.nullMeasurable measurableSet_Ici rw [lintegral_one, Measure.restrict_apply MeasurableSet.univ, univ_inter, indicator_mul_left, mul_assoc, show (Ioi 0).indicator (fun _x : ℝ => (1 : ℝ≥0∞)) s * μ {a : α | s ≤ f a} = (Ioi 0).indicator (fun _x : ℝ => 1 * μ {a : α | s ≤ f a}) s by by_cases h : 0 < s <;> simp [h]] simp_rw [mul_comm _ (ENNReal.ofReal _), one_mul] rfl have aux₂ : (Function.uncurry fun (x : α) (y : ℝ) => (Ioc 0 (f x)).indicator (fun t : ℝ => ENNReal.ofReal (g t)) y) = {p : α × ℝ | p.2 ∈ Ioc 0 (f p.1)}.indicator fun p => ENNReal.ofReal (g p.2) := by funext p cases p with | mk p_fst p_snd => ?_ rw [Function.uncurry_apply_pair] by_cases h : p_snd ∈ Ioc 0 (f p_fst) · have h' : (p_fst, p_snd) ∈ {p : α × ℝ | p.snd ∈ Ioc 0 (f p.fst)} := h rw [Set.indicator_of_mem h', Set.indicator_of_mem h] · have h' : (p_fst, p_snd) ∉ {p : α × ℝ | p.snd ∈ Ioc 0 (f p.fst)} := h rw [Set.indicator_of_notMem h', Set.indicator_of_notMem h] rw [aux₂] have mble₀ : MeasurableSet {p : α × ℝ | p.snd ∈ Ioc 0 (f p.fst)} := by simpa only [mem_univ, Pi.zero_apply, true_and] using measurableSet_region_between_oc measurable_zero f_mble MeasurableSet.univ exact (ENNReal.measurable_ofReal.comp (g_mble.comp measurable_snd)).aemeasurable.indicator₀ mble₀.nullMeasurableSet /-- An auxiliary version of the layer cake formula (Cavalieri's principle, tail probability formula), with a measurability assumption that would also essentially follow from the integrability assumptions. Compared to `lintegral_comp_eq_lintegral_meas_le_mul_of_measurable_of_sigmaFinite`, we remove the sigma-finite assumption. See `MeasureTheory.lintegral_comp_eq_lintegral_meas_le_mul` and `MeasureTheory.lintegral_comp_eq_lintegral_meas_lt_mul` for the main formulations of the layer cake formula. -/ theorem lintegral_comp_eq_lintegral_meas_le_mul_of_measurable (μ : Measure α) (f_nn : 0 ≤ f) (f_mble : Measurable f) (g_intble : ∀ t > 0, IntervalIntegrable g volume 0 t) (g_mble : Measurable g) (g_nn : ∀ t > 0, 0 ≤ g t) : ∫⁻ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂μ = ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) := by /- We will reduce to the sigma-finite case, after excluding two easy cases where the result is more or less obvious. -/ have f_nonneg : ∀ ω, 0 ≤ f ω := fun ω ↦ f_nn ω -- trivial case where `g` is ae zero. Then both integrals vanish. by_cases H1 : g =ᵐ[volume.restrict (Ioi (0 : ℝ))] 0 · have A : ∫⁻ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂μ = 0 := by have : ∀ ω, ∫ t in 0..f ω, g t = ∫ t in 0..f ω, 0 := by intro ω simp_rw [intervalIntegral.integral_of_le (f_nonneg ω)] apply integral_congr_ae exact ae_restrict_of_ae_restrict_of_subset Ioc_subset_Ioi_self H1 simp [this] have B : ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) = 0 := by have : (fun t ↦ μ {a : α | t ≤ f a} * ENNReal.ofReal (g t)) =ᵐ[volume.restrict (Ioi (0 : ℝ))] 0 := by filter_upwards [H1] with t ht using by simp [ht] simp [lintegral_congr_ae this] rw [A, B] -- easy case where both sides are obviously infinite: for some `s`, one has -- `μ {a : α | s < f a} = ∞` and moreover `g` is not ae zero on `[0, s]`. by_cases! H2 : ∃ s > 0, 0 < ∫ t in 0..s, g t ∧ μ {a : α | s < f a} = ∞ · rcases H2 with ⟨s, s_pos, hs, h's⟩ rw [intervalIntegral.integral_of_le s_pos.le] at hs /- The first integral is infinite, as for `t ∈ [0, s]` one has `μ {a : α | t ≤ f a} = ∞`, and moreover the additional integral `g` is not uniformly zero. -/ have A : ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) = ∞ := by rw [eq_top_iff] calc ∞ = ∫⁻ t in Ioc 0 s, ∞ * ENNReal.ofReal (g t) := by have I_pos : ∫⁻ (a : ℝ) in Ioc 0 s, ENNReal.ofReal (g a) ≠ 0 := by rw [← ofReal_integral_eq_lintegral_ofReal (g_intble s s_pos).1] · simpa only [not_lt, ne_eq, ENNReal.ofReal_eq_zero, not_le] using hs · filter_upwards [ae_restrict_mem measurableSet_Ioc] with t ht using g_nn _ ht.1 rw [lintegral_const_mul, ENNReal.top_mul I_pos] exact ENNReal.measurable_ofReal.comp g_mble _ ≤ ∫⁻ t in Ioc 0 s, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) := by apply setLIntegral_mono' measurableSet_Ioc (fun x hx ↦ ?_) rw [← h's] gcongr exact fun ha ↦ hx.2.trans (le_of_lt ha) _ ≤ ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) := lintegral_mono_set Ioc_subset_Ioi_self /- The second integral is infinite, as one integrates among other things on those `ω` where `f ω > s`: this is an infinite measure set, and on it the integrand is bounded below by `∫ t in 0..s, g t` which is positive. -/ have B : ∫⁻ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂μ = ∞ := by rw [eq_top_iff] calc ∞ = ∫⁻ _ in {a | s < f a}, ENNReal.ofReal (∫ t in 0..s, g t) ∂μ := by simp only [lintegral_const, MeasurableSet.univ, Measure.restrict_apply, univ_inter, h's] rw [ENNReal.mul_top] simpa [intervalIntegral.integral_of_le s_pos.le] using hs _ ≤ ∫⁻ ω in {a | s < f a}, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂μ := by apply setLIntegral_mono' (measurableSet_lt measurable_const f_mble) (fun a ha ↦ ?_) apply ENNReal.ofReal_le_ofReal apply intervalIntegral.integral_mono_interval le_rfl s_pos.le (le_of_lt ha) · filter_upwards [ae_restrict_mem measurableSet_Ioc] with t ht using g_nn _ ht.1 · exact g_intble _ (s_pos.trans ha) _ ≤ ∫⁻ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂μ := setLIntegral_le_lintegral _ _ rw [A, B] /- It remains to handle the interesting case, where `g` is not zero, but both integrals are not obviously infinite. Let `M` be the largest number such that `g = 0` on `[0, M]`. Then we may restrict `μ` to the points where `f ω > M` (as the other ones do not contribute to the integral). The restricted measure `ν` is sigma-finite, as `μ` gives finite measure to `{ω | f ω > a}` for any `a > M` (otherwise, we would be in the easy case above), so that one can write (a full measure subset of) the space as the countable union of the finite measure sets `{ω | f ω > uₙ}` for `uₙ` a sequence decreasing to `M`. Therefore, this case follows from the case where the measure is sigma-finite, applied to `ν`. -/ have M_bdd : BddAbove {s : ℝ | g =ᵐ[volume.restrict (Ioc (0 : ℝ) s)] 0} := by contrapose! H1 have : ∀ (n : ℕ), g =ᵐ[volume.restrict (Ioc (0 : ℝ) n)] 0 := by intro n rcases not_bddAbove_iff.1 H1 n with ⟨s, hs, ns⟩ exact ae_restrict_of_ae_restrict_of_subset (Ioc_subset_Ioc_right ns.le) hs have Hg : g =ᵐ[volume.restrict (⋃ (n : ℕ), (Ioc (0 : ℝ) n))] 0 := (ae_restrict_iUnion_iff _ _).2 this have : (⋃ (n : ℕ), (Ioc (0 : ℝ) n)) = Ioi 0 := iUnion_Ioc_eq_Ioi_self_iff.2 (fun x _ ↦ exists_nat_ge x) rwa [this] at Hg -- let `M` be the largest number such that `g` vanishes ae on `(0, M]`. let M : ℝ := sSup {s : ℝ | g =ᵐ[volume.restrict (Ioc (0 : ℝ) s)] 0} have zero_mem : 0 ∈ {s : ℝ | g =ᵐ[volume.restrict (Ioc (0 : ℝ) s)] 0} := by simpa using trivial have M_nonneg : 0 ≤ M := le_csSup M_bdd zero_mem -- Then the function `g` indeed vanishes ae on `(0, M]`. have hgM : g =ᵐ[volume.restrict (Ioc (0 : ℝ) M)] 0 := by rw [← restrict_Ioo_eq_restrict_Ioc] obtain ⟨u, -, uM, ulim⟩ : ∃ u, StrictMono u ∧ (∀ (n : ℕ), u n < M) ∧ Tendsto u atTop (𝓝 M) := exists_seq_strictMono_tendsto M have I : ∀ n, g =ᵐ[volume.restrict (Ioc (0 : ℝ) (u n))] 0 := by intro n obtain ⟨s, hs, uns⟩ : ∃ s, g =ᶠ[ae (Measure.restrict volume (Ioc 0 s))] 0 ∧ u n < s := exists_lt_of_lt_csSup (Set.nonempty_of_mem zero_mem) (uM n) exact ae_restrict_of_ae_restrict_of_subset (Ioc_subset_Ioc_right uns.le) hs have : g =ᵐ[volume.restrict (⋃ n, Ioc (0 : ℝ) (u n))] 0 := (ae_restrict_iUnion_iff _ _).2 I apply ae_restrict_of_ae_restrict_of_subset _ this rintro x ⟨x_pos, xM⟩ obtain ⟨n, hn⟩ : ∃ n, x < u n := ((tendsto_order.1 ulim).1 _ xM).exists exact mem_iUnion.2 ⟨n, ⟨x_pos, hn.le⟩⟩ -- Let `ν` be the restriction of `μ` to those points where `f a > M`. let ν := μ.restrict {a : α | M < f a} -- This measure is sigma-finite (this is the whole point of the argument). have : SigmaFinite ν := by obtain ⟨u, -, uM, ulim⟩ : ∃ u, StrictAnti u ∧ (∀ (n : ℕ), M < u n) ∧ Tendsto u atTop (𝓝 M) := exists_seq_strictAnti_tendsto M let s : ν.FiniteSpanningSetsIn univ := { set := fun n ↦ {a | f a ≤ M} ∪ {a | u n < f a} set_mem := fun _ ↦ trivial finite := by intro n have I : ν {a | f a ≤ M} = 0 := by rw [Measure.restrict_apply (measurableSet_le f_mble measurable_const)] convert measure_empty (μ := μ) rw [← disjoint_iff_inter_eq_empty] exact disjoint_left.mpr (fun a ha ↦ by simpa using ha) have J : μ {a | u n < f a} < ∞ := by rw [lt_top_iff_ne_top] apply H2 _ (M_nonneg.trans_lt (uM n)) by_contra H3 rw [not_lt, intervalIntegral.integral_of_le (M_nonneg.trans (uM n).le)] at H3 have g_nn_ae : ∀ᵐ t ∂(volume.restrict (Ioc 0 (u n))), 0 ≤ g t := by filter_upwards [ae_restrict_mem measurableSet_Ioc] with s hs using g_nn _ hs.1 have Ig : ∫ (t : ℝ) in Ioc 0 (u n), g t = 0 := le_antisymm H3 (integral_nonneg_of_ae g_nn_ae) have J : ∀ᵐ t ∂(volume.restrict (Ioc 0 (u n))), g t = 0 := (integral_eq_zero_iff_of_nonneg_ae g_nn_ae (g_intble (u n) (M_nonneg.trans_lt (uM n))).1).1 Ig have : u n ≤ M := le_csSup M_bdd J exact lt_irrefl _ (this.trans_lt (uM n)) refine lt_of_le_of_lt (measure_union_le _ _) ?_ rw [I, zero_add] apply lt_of_le_of_lt _ J exact restrict_le_self _ spanning := by apply eq_univ_iff_forall.2 (fun a ↦ ?_) rcases le_or_gt (f a) M with ha|ha · exact mem_iUnion.2 ⟨0, Or.inl ha⟩ · obtain ⟨n, hn⟩ : ∃ n, u n < f a := ((tendsto_order.1 ulim).2 _ ha).exists exact mem_iUnion.2 ⟨n, Or.inr hn⟩ } exact ⟨⟨s⟩⟩ -- the first integrals with respect to `μ` and to `ν` coincide, as points with `f a ≤ M` are -- weighted by zero as `g` vanishes there. have A : ∫⁻ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂μ = ∫⁻ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂ν := by have meas : MeasurableSet {a | M < f a} := measurableSet_lt measurable_const f_mble have I : ∫⁻ ω in {a | M < f a}ᶜ, ENNReal.ofReal (∫ t in 0.. f ω, g t) ∂μ = ∫⁻ _ in {a | M < f a}ᶜ, 0 ∂μ := by apply setLIntegral_congr_fun meas.compl (fun s hs ↦ ?_) have : ∫ (t : ℝ) in 0..f s, g t = ∫ (t : ℝ) in 0..f s, 0 := by simp_rw [intervalIntegral.integral_of_le (f_nonneg s)] apply integral_congr_ae apply ae_mono (restrict_mono ?_ le_rfl) hgM apply Ioc_subset_Ioc_right simpa using hs simp [this] simp only [lintegral_const, zero_mul] at I rw [← lintegral_add_compl _ meas, I, add_zero] -- the second integrals with respect to `μ` and to `ν` coincide, as points with `f a ≤ M` do not -- contribute to either integral since the weight `g` vanishes. have B : ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) = ∫⁻ t in Ioi 0, ν {a : α | t ≤ f a} * ENNReal.ofReal (g t) := by have B1 : ∫⁻ t in Ioc 0 M, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) = ∫⁻ t in Ioc 0 M, ν {a : α | t ≤ f a} * ENNReal.ofReal (g t) := by apply lintegral_congr_ae filter_upwards [hgM] with t ht simp [ht] have B2 : ∫⁻ t in Ioi M, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) = ∫⁻ t in Ioi M, ν {a : α | t ≤ f a} * ENNReal.ofReal (g t) := by apply setLIntegral_congr_fun measurableSet_Ioi (fun t ht ↦ ?_) rw [Measure.restrict_apply (measurableSet_le measurable_const f_mble)] congr 3 exact (inter_eq_left.2 (fun a ha ↦ (mem_Ioi.1 ht).trans_le ha)).symm have I : Ioi (0 : ℝ) = Ioc (0 : ℝ) M ∪ Ioi M := (Ioc_union_Ioi_eq_Ioi M_nonneg).symm have J : Disjoint (Ioc 0 M) (Ioi M) := Ioc_disjoint_Ioi le_rfl rw [I, lintegral_union measurableSet_Ioi J, lintegral_union measurableSet_Ioi J, B1, B2] -- therefore, we may replace the integrals w.r.t. `μ` with integrals w.r.t. `ν`, and apply the -- result for sigma-finite measures. rw [A, B] exact lintegral_comp_eq_lintegral_meas_le_mul_of_measurable_of_sigmaFinite ν f_nn f_mble g_intble g_mble g_nn /-- The layer cake formula / **Cavalieri's principle** / tail probability formula: Let `f` be a non-negative measurable function on a measure space. Let `G` be an increasing absolutely continuous function on the positive real line, vanishing at the origin, with derivative `G' = g`. Then the integral of the composition `G ∘ f` can be written as the integral over the positive real line of the "tail measures" `μ {ω | f(ω) ≥ t}` of `f` weighted by `g`. Roughly speaking, the statement is: `∫⁻ (G ∘ f) ∂μ = ∫⁻ t in 0..∞, g(t) * μ {ω | f(ω) ≥ t}`. See `MeasureTheory.lintegral_comp_eq_lintegral_meas_lt_mul` for a version with sets of the form `{ω | f(ω) > t}` instead. -/ theorem lintegral_comp_eq_lintegral_meas_le_mul (μ : Measure α) (f_nn : 0 ≤ᵐ[μ] f) (f_mble : AEMeasurable f μ) (g_intble : ∀ t > 0, IntervalIntegrable g volume 0 t) (g_nn : ∀ᵐ t ∂volume.restrict (Ioi 0), 0 ≤ g t) : ∫⁻ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂μ = ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) := by obtain ⟨G, G_mble, G_nn, g_eq_G⟩ : ∃ G : ℝ → ℝ, Measurable G ∧ 0 ≤ G ∧ g =ᵐ[volume.restrict (Ioi 0)] G := by refine AEMeasurable.exists_measurable_nonneg ?_ g_nn exact aemeasurable_Ioi_of_forall_Ioc fun t ht => (g_intble t ht).1.1.aemeasurable have g_eq_G_on : ∀ t, g =ᵐ[volume.restrict (Ioc 0 t)] G := fun t => ae_mono (Measure.restrict_mono Ioc_subset_Ioi_self le_rfl) g_eq_G have G_intble : ∀ t > 0, IntervalIntegrable G volume 0 t := by refine fun t t_pos => ⟨(g_intble t t_pos).1.congr_fun_ae (g_eq_G_on t), ?_⟩ rw [Ioc_eq_empty_of_le t_pos.lt.le] exact integrableOn_empty obtain ⟨F, F_mble, F_nn, f_eq_F⟩ : ∃ F : α → ℝ, Measurable F ∧ 0 ≤ F ∧ f =ᵐ[μ] F := by refine ⟨fun ω ↦ max (f_mble.mk f ω) 0, f_mble.measurable_mk.max measurable_const, fun ω ↦ le_max_right _ _, ?_⟩ filter_upwards [f_mble.ae_eq_mk, f_nn] with ω hω h'ω rw [← hω] exact (max_eq_left h'ω).symm have eq₁ : ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ENNReal.ofReal (g t) = ∫⁻ t in Ioi 0, μ {a : α | t ≤ F a} * ENNReal.ofReal (G t) := by apply lintegral_congr_ae filter_upwards [g_eq_G] with t ht rw [ht] congr 1 apply measure_congr filter_upwards [f_eq_F] with a ha using by simp [setOf, ha] have eq₂ : ∀ᵐ ω ∂μ, ENNReal.ofReal (∫ t in 0..f ω, g t) = ENNReal.ofReal (∫ t in 0..F ω, G t) := by filter_upwards [f_eq_F] with ω fω_nn rw [fω_nn] congr 1 refine intervalIntegral.integral_congr_ae ?_ have fω_nn : 0 ≤ F ω := F_nn ω rw [uIoc_of_le fω_nn, ← ae_restrict_iff' (measurableSet_Ioc : MeasurableSet (Ioc (0 : ℝ) (F ω)))] exact g_eq_G_on (F ω) simp_rw [lintegral_congr_ae eq₂, eq₁] exact lintegral_comp_eq_lintegral_meas_le_mul_of_measurable μ F_nn F_mble G_intble G_mble (fun t _ => G_nn t) /-- The standard case of the layer cake formula / Cavalieri's principle / tail probability formula: For a nonnegative function `f` on a measure space, the Lebesgue integral of `f` can be written (roughly speaking) as: `∫⁻ f ∂μ = ∫⁻ t in 0..∞, μ {ω | f(ω) ≥ t}`. See `MeasureTheory.lintegral_eq_lintegral_meas_lt` for a version with sets of the form `{ω | f(ω) > t}` instead. -/ theorem lintegral_eq_lintegral_meas_le (μ : Measure α) (f_nn : 0 ≤ᵐ[μ] f) (f_mble : AEMeasurable f μ) : ∫⁻ ω, ENNReal.ofReal (f ω) ∂μ = ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} := by set cst := fun _ : ℝ => (1 : ℝ) have cst_intble : ∀ t > 0, IntervalIntegrable cst volume 0 t := fun _ _ => intervalIntegrable_const have key := lintegral_comp_eq_lintegral_meas_le_mul μ f_nn f_mble cst_intble (Eventually.of_forall fun _ => zero_le_one) simp_rw [cst, ENNReal.ofReal_one, mul_one] at key rw [← key] congr with ω simp only [intervalIntegral.integral_const, sub_zero, Algebra.id.smul_eq_mul, mul_one] end Layercake section LayercakeLT variable {α : Type*} [MeasurableSpace α] variable {f : α → ℝ} {g : ℝ → ℝ} /-- The layer cake formula / Cavalieri's principle / tail probability formula: Let `f` be a non-negative measurable function on a measure space. Let `G` be an increasing absolutely continuous function on the positive real line, vanishing at the origin, with derivative `G' = g`. Then the integral of the composition `G ∘ f` can be written as the integral over the positive real line of the "tail measures" `μ {ω | f(ω) > t}` of `f` weighted by `g`. Roughly speaking, the statement is: `∫⁻ (G ∘ f) ∂μ = ∫⁻ t in 0..∞, g(t) * μ {ω | f(ω) > t}`. See `lintegral_comp_eq_lintegral_meas_le_mul` for a version with sets of the form `{ω | f(ω) ≥ t}` instead. -/ theorem lintegral_comp_eq_lintegral_meas_lt_mul (μ : Measure α) (f_nn : 0 ≤ᵐ[μ] f) (f_mble : AEMeasurable f μ) (g_intble : ∀ t > 0, IntervalIntegrable g volume 0 t) (g_nn : ∀ᵐ t ∂volume.restrict (Ioi 0), 0 ≤ g t) : ∫⁻ ω, ENNReal.ofReal (∫ t in 0..f ω, g t) ∂μ = ∫⁻ t in Ioi 0, μ {a : α | t < f a} * ENNReal.ofReal (g t) := by rw [lintegral_comp_eq_lintegral_meas_le_mul μ f_nn f_mble g_intble g_nn] apply lintegral_congr_ae filter_upwards [meas_le_ae_eq_meas_lt μ (volume.restrict (Ioi 0)) f] with t ht rw [ht] /-- The standard case of the layer cake formula / Cavalieri's principle / tail probability formula: For a nonnegative function `f` on a measure space, the Lebesgue integral of `f` can be written (roughly speaking) as: `∫⁻ f ∂μ = ∫⁻ t in 0..∞, μ {ω | f(ω) > t}`. See `lintegral_eq_lintegral_meas_le` for a version with sets of the form `{ω | f(ω) ≥ t}` instead. -/ theorem lintegral_eq_lintegral_meas_lt (μ : Measure α) (f_nn : 0 ≤ᵐ[μ] f) (f_mble : AEMeasurable f μ) : ∫⁻ ω, ENNReal.ofReal (f ω) ∂μ = ∫⁻ t in Ioi 0, μ {a : α | t < f a} := by rw [lintegral_eq_lintegral_meas_le μ f_nn f_mble] apply lintegral_congr_ae filter_upwards [meas_le_ae_eq_meas_lt μ (volume.restrict (Ioi 0)) f] with t ht rw [ht] end LayercakeLT section LayercakeIntegral variable {α : Type*} [MeasurableSpace α] {μ : Measure α} {f : α → ℝ} /-- The standard case of the layer cake formula / Cavalieri's principle / tail probability formula: For an integrable a.e.-nonnegative real-valued function `f`, the Bochner integral of `f` can be written (roughly speaking) as: `∫ f ∂μ = ∫ t in 0..∞, μ {ω | f(ω) > t}`. See `MeasureTheory.lintegral_eq_lintegral_meas_lt` for a version with Lebesgue integral `∫⁻` instead. -/ theorem Integrable.integral_eq_integral_meas_lt (f_intble : Integrable f μ) (f_nn : 0 ≤ᵐ[μ] f) : ∫ ω, f ω ∂μ = ∫ t in Set.Ioi 0, μ.real {a : α | t < f a} := by have key := lintegral_eq_lintegral_meas_lt μ f_nn f_intble.aemeasurable have lhs_finite : ∫⁻ (ω : α), ENNReal.ofReal (f ω) ∂μ < ∞ := Integrable.lintegral_lt_top f_intble have rhs_finite : ∫⁻ (t : ℝ) in Set.Ioi 0, μ {a | t < f a} < ∞ := by simp only [← key, lhs_finite] have rhs_integrand_finite : ∀ (t : ℝ), t > 0 → μ {a | t < f a} < ∞ := fun t ht ↦ measure_gt_lt_top f_intble ht convert (ENNReal.toReal_eq_toReal_iff' lhs_finite.ne rhs_finite.ne).mpr key · exact integral_eq_lintegral_of_nonneg_ae f_nn f_intble.aestronglyMeasurable · have aux := @integral_eq_lintegral_of_nonneg_ae _ _ ((volume : Measure ℝ).restrict (Set.Ioi 0)) (fun t ↦ μ.real {a : α | t < f a}) ?_ ?_ · rw [aux] congr 1 apply setLIntegral_congr_fun measurableSet_Ioi exact fun t t_pos ↦ ENNReal.ofReal_toReal (rhs_integrand_finite t t_pos).ne · exact Eventually.of_forall (fun x ↦ by positivity) · apply Measurable.aestronglyMeasurable refine Measurable.ennreal_toReal ?_ exact Antitone.measurable (fun _ _ hst ↦ measure_mono (fun _ h ↦ lt_of_le_of_lt hst h)) theorem Integrable.integral_eq_integral_meas_le (f_intble : Integrable f μ) (f_nn : 0 ≤ᵐ[μ] f) : ∫ ω, f ω ∂μ = ∫ t in Set.Ioi 0, μ.real {a : α | t ≤ f a} := by rw [Integrable.integral_eq_integral_meas_lt f_intble f_nn] apply integral_congr_ae filter_upwards [meas_le_ae_eq_meas_lt μ (volume.restrict (Ioi 0)) f] with t ht exact congrArg ENNReal.toReal ht.symm lemma Integrable.integral_eq_integral_Ioc_meas_le {f : α → ℝ} {M : ℝ} (f_intble : Integrable f μ) (f_nn : 0 ≤ᵐ[μ] f) (f_bdd : f ≤ᵐ[μ] (fun _ ↦ M)) : ∫ ω, f ω ∂μ = ∫ t in Ioc 0 M, μ.real {a : α | t ≤ f a} := by rw [f_intble.integral_eq_integral_meas_le f_nn] rw [setIntegral_eq_of_subset_of_ae_diff_eq_zero nullMeasurableSet_Ioi Ioc_subset_Ioi_self ?_] apply Eventually.of_forall (fun t ht ↦ ?_) have htM : M < t := by simp_all only [mem_diff, mem_Ioi, mem_Ioc, not_and, not_le] have obs : μ {a | M < f a} = 0 := by rw [measure_eq_zero_iff_ae_notMem] filter_upwards [f_bdd] with a ha using not_lt.mpr ha rw [measureReal_def, ENNReal.toReal_eq_zero_iff] exact Or.inl <| measure_mono_null (fun a ha ↦ lt_of_lt_of_le htM ha) obs end LayercakeIntegral end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/SetToL1.lean
import Mathlib.MeasureTheory.Integral.FinMeasAdditive import Mathlib.Analysis.Normed.Operator.Extend /-! # Extension of a linear function from indicators to L1 Given `T : Set α → E →L[ℝ] F` with `DominatedFinMeasAdditive μ T C`, we construct an extension of `T` to integrable simple functions, which are finite sums of indicators of measurable sets with finite measure, then to integrable functions, which are limits of integrable simple functions. The main result is a continuous linear map `(α →₁[μ] E) →L[ℝ] F`. This extension process is used to define the Bochner integral in the `Mathlib/MeasureTheory/Integral/Bochner/Basic.lean` file and the conditional expectation of an integrable function in `Mathlib/MeasureTheory/Function/ConditionalExpectation/CondexpL1.lean`. ## Main definitions - `setToL1 (hT : DominatedFinMeasAdditive μ T C) : (α →₁[μ] E) →L[ℝ] F`: the extension of `T` from indicators to L1. - `setToFun μ T (hT : DominatedFinMeasAdditive μ T C) (f : α → E) : F`: a version of the extension which applies to functions (with value 0 if the function is not integrable). ## Properties For most properties of `setToFun`, we provide two lemmas. One version uses hypotheses valid on all sets, like `T = T'`, and a second version which uses a primed name uses hypotheses on measurable sets with finite measure, like `∀ s, MeasurableSet s → μ s < ∞ → T s = T' s`. The lemmas listed here don't show all hypotheses. Refer to the actual lemmas for details. Linearity: - `setToFun_zero_left : setToFun μ 0 hT f = 0` - `setToFun_add_left : setToFun μ (T + T') _ f = setToFun μ T hT f + setToFun μ T' hT' f` - `setToFun_smul_left : setToFun μ (fun s ↦ c • (T s)) (hT.smul c) f = c • setToFun μ T hT f` - `setToFun_zero : setToFun μ T hT (0 : α → E) = 0` - `setToFun_neg : setToFun μ T hT (-f) = - setToFun μ T hT f` If `f` and `g` are integrable: - `setToFun_add : setToFun μ T hT (f + g) = setToFun μ T hT f + setToFun μ T hT g` - `setToFun_sub : setToFun μ T hT (f - g) = setToFun μ T hT f - setToFun μ T hT g` If `T` satisfies `∀ c : 𝕜, ∀ s x, T s (c • x) = c • T s x`: - `setToFun_smul : setToFun μ T hT (c • f) = c • setToFun μ T hT f` Other: - `setToFun_congr_ae (h : f =ᵐ[μ] g) : setToFun μ T hT f = setToFun μ T hT g` - `setToFun_measure_zero (h : μ = 0) : setToFun μ T hT f = 0` If the space is also an ordered additive group with an order closed topology and `T` is such that `0 ≤ T s x` for `0 ≤ x`, we also prove order-related properties: - `setToFun_mono_left (h : ∀ s x, T s x ≤ T' s x) : setToFun μ T hT f ≤ setToFun μ T' hT' f` - `setToFun_nonneg (hf : 0 ≤ᵐ[μ] f) : 0 ≤ setToFun μ T hT f` - `setToFun_mono (hfg : f ≤ᵐ[μ] g) : setToFun μ T hT f ≤ setToFun μ T hT g` -/ noncomputable section open scoped Topology NNReal open Set Filter TopologicalSpace ENNReal namespace MeasureTheory variable {α E F F' G 𝕜 : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [NormedAddCommGroup F] [NormedSpace ℝ F] [NormedAddCommGroup F'] [NormedSpace ℝ F'] [NormedAddCommGroup G] {m : MeasurableSpace α} {μ : Measure α} namespace L1 open AEEqFun Lp.simpleFunc Lp namespace SimpleFunc theorem norm_eq_sum_mul (f : α →₁ₛ[μ] G) : ‖f‖ = ∑ x ∈ (toSimpleFunc f).range, μ.real (toSimpleFunc f ⁻¹' {x}) * ‖x‖ := by rw [norm_toSimpleFunc, eLpNorm_one_eq_lintegral_enorm] have h_eq := SimpleFunc.map_apply (‖·‖ₑ) (toSimpleFunc f) simp_rw [← h_eq, measureReal_def] rw [SimpleFunc.lintegral_eq_lintegral, SimpleFunc.map_lintegral, ENNReal.toReal_sum] · congr ext1 x rw [ENNReal.toReal_mul, mul_comm, ← ofReal_norm_eq_enorm, ENNReal.toReal_ofReal (norm_nonneg _)] · intro x _ by_cases hx0 : x = 0 · rw [hx0]; simp · have := SimpleFunc.measure_preimage_lt_top_of_integrable _ (SimpleFunc.integrable f) hx0 finiteness section SetToL1S variable [NormedRing 𝕜] [Module 𝕜 E] [IsBoundedSMul 𝕜 E] attribute [local instance] Lp.simpleFunc.module attribute [local instance] Lp.simpleFunc.normedSpace /-- Extend `Set α → (E →L[ℝ] F')` to `(α →₁ₛ[μ] E) → F'`. -/ def setToL1S (T : Set α → E →L[ℝ] F) (f : α →₁ₛ[μ] E) : F := (toSimpleFunc f).setToSimpleFunc T theorem setToL1S_eq_setToSimpleFunc (T : Set α → E →L[ℝ] F) (f : α →₁ₛ[μ] E) : setToL1S T f = (toSimpleFunc f).setToSimpleFunc T := rfl @[simp] theorem setToL1S_zero_left (f : α →₁ₛ[μ] E) : setToL1S (0 : Set α → E →L[ℝ] F) f = 0 := SimpleFunc.setToSimpleFunc_zero _ theorem setToL1S_zero_left' {T : Set α → E →L[ℝ] F} (h_zero : ∀ s, MeasurableSet s → μ s < ∞ → T s = 0) (f : α →₁ₛ[μ] E) : setToL1S T f = 0 := SimpleFunc.setToSimpleFunc_zero' h_zero _ (SimpleFunc.integrable f) theorem setToL1S_congr (T : Set α → E →L[ℝ] F) (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) {f g : α →₁ₛ[μ] E} (h : toSimpleFunc f =ᵐ[μ] toSimpleFunc g) : setToL1S T f = setToL1S T g := SimpleFunc.setToSimpleFunc_congr T h_zero h_add (SimpleFunc.integrable f) h theorem setToL1S_congr_left (T T' : Set α → E →L[ℝ] F) (h : ∀ s, MeasurableSet s → μ s < ∞ → T s = T' s) (f : α →₁ₛ[μ] E) : setToL1S T f = setToL1S T' f := SimpleFunc.setToSimpleFunc_congr_left T T' h (simpleFunc.toSimpleFunc f) (SimpleFunc.integrable f) /-- `setToL1S` does not change if we replace the measure `μ` by `μ'` with `μ ≪ μ'`. The statement uses two functions `f` and `f'` because they have to belong to different types, but morally these are the same function (we have `f =ᵐ[μ] f'`). -/ theorem setToL1S_congr_measure {μ' : Measure α} (T : Set α → E →L[ℝ] F) (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (hμ : μ ≪ μ') (f : α →₁ₛ[μ] E) (f' : α →₁ₛ[μ'] E) (h : (f : α → E) =ᵐ[μ] f') : setToL1S T f = setToL1S T f' := by refine SimpleFunc.setToSimpleFunc_congr T h_zero h_add (SimpleFunc.integrable f) ?_ refine (toSimpleFunc_eq_toFun f).trans ?_ suffices (f' : α → E) =ᵐ[μ] simpleFunc.toSimpleFunc f' from h.trans this have goal' : (f' : α → E) =ᵐ[μ'] simpleFunc.toSimpleFunc f' := (toSimpleFunc_eq_toFun f').symm exact hμ.ae_eq goal' theorem setToL1S_add_left (T T' : Set α → E →L[ℝ] F) (f : α →₁ₛ[μ] E) : setToL1S (T + T') f = setToL1S T f + setToL1S T' f := SimpleFunc.setToSimpleFunc_add_left T T' theorem setToL1S_add_left' (T T' T'' : Set α → E →L[ℝ] F) (h_add : ∀ s, MeasurableSet s → μ s < ∞ → T'' s = T s + T' s) (f : α →₁ₛ[μ] E) : setToL1S T'' f = setToL1S T f + setToL1S T' f := SimpleFunc.setToSimpleFunc_add_left' T T' T'' h_add (SimpleFunc.integrable f) theorem setToL1S_smul_left (T : Set α → E →L[ℝ] F) (c : ℝ) (f : α →₁ₛ[μ] E) : setToL1S (fun s => c • T s) f = c • setToL1S T f := SimpleFunc.setToSimpleFunc_smul_left T c _ theorem setToL1S_smul_left' (T T' : Set α → E →L[ℝ] F) (c : ℝ) (h_smul : ∀ s, MeasurableSet s → μ s < ∞ → T' s = c • T s) (f : α →₁ₛ[μ] E) : setToL1S T' f = c • setToL1S T f := SimpleFunc.setToSimpleFunc_smul_left' T T' c h_smul (SimpleFunc.integrable f) theorem setToL1S_add (T : Set α → E →L[ℝ] F) (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (f g : α →₁ₛ[μ] E) : setToL1S T (f + g) = setToL1S T f + setToL1S T g := by simp_rw [setToL1S] rw [← SimpleFunc.setToSimpleFunc_add T h_add (SimpleFunc.integrable f) (SimpleFunc.integrable g)] exact SimpleFunc.setToSimpleFunc_congr T h_zero h_add (SimpleFunc.integrable _) (add_toSimpleFunc f g) theorem setToL1S_neg {T : Set α → E →L[ℝ] F} (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (f : α →₁ₛ[μ] E) : setToL1S T (-f) = -setToL1S T f := by simp_rw [setToL1S] have : simpleFunc.toSimpleFunc (-f) =ᵐ[μ] ⇑(-simpleFunc.toSimpleFunc f) := neg_toSimpleFunc f rw [SimpleFunc.setToSimpleFunc_congr T h_zero h_add (SimpleFunc.integrable _) this] exact SimpleFunc.setToSimpleFunc_neg T h_add (SimpleFunc.integrable f) theorem setToL1S_sub {T : Set α → E →L[ℝ] F} (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (f g : α →₁ₛ[μ] E) : setToL1S T (f - g) = setToL1S T f - setToL1S T g := by rw [sub_eq_add_neg, setToL1S_add T h_zero h_add, setToL1S_neg h_zero h_add, sub_eq_add_neg] theorem setToL1S_smul_real (T : Set α → E →L[ℝ] F) (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (c : ℝ) (f : α →₁ₛ[μ] E) : setToL1S T (c • f) = c • setToL1S T f := by simp_rw [setToL1S] rw [← SimpleFunc.setToSimpleFunc_smul_real T h_add c (SimpleFunc.integrable f)] refine SimpleFunc.setToSimpleFunc_congr T h_zero h_add (SimpleFunc.integrable _) ?_ exact smul_toSimpleFunc c f theorem setToL1S_smul [DistribSMul 𝕜 F] (T : Set α → E →L[ℝ] F) (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (h_smul : ∀ c : 𝕜, ∀ s x, T s (c • x) = c • T s x) (c : 𝕜) (f : α →₁ₛ[μ] E) : setToL1S T (c • f) = c • setToL1S T f := by simp_rw [setToL1S] rw [← SimpleFunc.setToSimpleFunc_smul T h_add h_smul c (SimpleFunc.integrable f)] refine SimpleFunc.setToSimpleFunc_congr T h_zero h_add (SimpleFunc.integrable _) ?_ exact smul_toSimpleFunc c f theorem norm_setToL1S_le (T : Set α → E →L[ℝ] F) {C : ℝ} (hT_norm : ∀ s, MeasurableSet s → μ s < ∞ → ‖T s‖ ≤ C * μ.real s) (f : α →₁ₛ[μ] E) : ‖setToL1S T f‖ ≤ C * ‖f‖ := by rw [setToL1S, norm_eq_sum_mul f] exact SimpleFunc.norm_setToSimpleFunc_le_sum_mul_norm_of_integrable T hT_norm _ (SimpleFunc.integrable f) theorem setToL1S_indicatorConst {T : Set α → E →L[ℝ] F} {s : Set α} (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (hs : MeasurableSet s) (hμs : μ s < ∞) (x : E) : setToL1S T (simpleFunc.indicatorConst 1 hs hμs.ne x) = T s x := by have h_empty : T ∅ = 0 := h_zero _ MeasurableSet.empty measure_empty rw [setToL1S_eq_setToSimpleFunc] refine Eq.trans ?_ (SimpleFunc.setToSimpleFunc_indicator T h_empty hs x) refine SimpleFunc.setToSimpleFunc_congr T h_zero h_add (SimpleFunc.integrable _) ?_ exact toSimpleFunc_indicatorConst hs hμs.ne x theorem setToL1S_const [IsFiniteMeasure μ] {T : Set α → E →L[ℝ] F} (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (x : E) : setToL1S T (simpleFunc.indicatorConst 1 MeasurableSet.univ (measure_ne_top μ _) x) = T univ x := setToL1S_indicatorConst h_zero h_add MeasurableSet.univ (measure_lt_top _ _) x section Order variable {G'' G' : Type*} [NormedAddCommGroup G'] [PartialOrder G'] [IsOrderedAddMonoid G'] [NormedSpace ℝ G'] [NormedAddCommGroup G''] [PartialOrder G''] [IsOrderedAddMonoid G''] [NormedSpace ℝ G''] {T : Set α → G'' →L[ℝ] G'} theorem setToL1S_mono_left {T T' : Set α → E →L[ℝ] G''} (hTT' : ∀ s x, T s x ≤ T' s x) (f : α →₁ₛ[μ] E) : setToL1S T f ≤ setToL1S T' f := SimpleFunc.setToSimpleFunc_mono_left T T' hTT' _ theorem setToL1S_mono_left' {T T' : Set α → E →L[ℝ] G''} (hTT' : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, T s x ≤ T' s x) (f : α →₁ₛ[μ] E) : setToL1S T f ≤ setToL1S T' f := SimpleFunc.setToSimpleFunc_mono_left' T T' hTT' _ (SimpleFunc.integrable f) omit [IsOrderedAddMonoid G''] in theorem setToL1S_nonneg (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) {f : α →₁ₛ[μ] G''} (hf : 0 ≤ f) : 0 ≤ setToL1S T f := by simp_rw [setToL1S] obtain ⟨f', hf', hff'⟩ := exists_simpleFunc_nonneg_ae_eq hf replace hff' : simpleFunc.toSimpleFunc f =ᵐ[μ] f' := (Lp.simpleFunc.toSimpleFunc_eq_toFun f).trans hff' rw [SimpleFunc.setToSimpleFunc_congr _ h_zero h_add (SimpleFunc.integrable _) hff'] exact SimpleFunc.setToSimpleFunc_nonneg' T hT_nonneg _ hf' ((SimpleFunc.integrable f).congr hff') theorem setToL1S_mono (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) {f g : α →₁ₛ[μ] G''} (hfg : f ≤ g) : setToL1S T f ≤ setToL1S T g := by rw [← sub_nonneg] at hfg ⊢ rw [← setToL1S_sub h_zero h_add] exact setToL1S_nonneg h_zero h_add hT_nonneg hfg end Order variable [Module 𝕜 F] [IsBoundedSMul 𝕜 F] variable (α E μ 𝕜) /-- Extend `Set α → E →L[ℝ] F` to `(α →₁ₛ[μ] E) →L[𝕜] F`. -/ def setToL1SCLM' {T : Set α → E →L[ℝ] F} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) (h_smul : ∀ c : 𝕜, ∀ s x, T s (c • x) = c • T s x) : (α →₁ₛ[μ] E) →L[𝕜] F := LinearMap.mkContinuous ⟨⟨setToL1S T, setToL1S_add T (fun _ => hT.eq_zero_of_measure_zero) hT.1⟩, setToL1S_smul T (fun _ => hT.eq_zero_of_measure_zero) hT.1 h_smul⟩ C fun f => norm_setToL1S_le T hT.2 f /-- Extend `Set α → E →L[ℝ] F` to `(α →₁ₛ[μ] E) →L[ℝ] F`. -/ def setToL1SCLM {T : Set α → E →L[ℝ] F} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) : (α →₁ₛ[μ] E) →L[ℝ] F := LinearMap.mkContinuous ⟨⟨setToL1S T, setToL1S_add T (fun _ => hT.eq_zero_of_measure_zero) hT.1⟩, setToL1S_smul_real T (fun _ => hT.eq_zero_of_measure_zero) hT.1⟩ C fun f => norm_setToL1S_le T hT.2 f variable {α E μ 𝕜} variable {T T' T'' : Set α → E →L[ℝ] F} {C C' C'' : ℝ} @[simp] theorem setToL1SCLM_zero_left (hT : DominatedFinMeasAdditive μ (0 : Set α → E →L[ℝ] F) C) (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ hT f = 0 := setToL1S_zero_left _ theorem setToL1SCLM_zero_left' (hT : DominatedFinMeasAdditive μ T C) (h_zero : ∀ s, MeasurableSet s → μ s < ∞ → T s = 0) (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ hT f = 0 := setToL1S_zero_left' h_zero f theorem setToL1SCLM_congr_left (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (h : T = T') (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ hT f = setToL1SCLM α E μ hT' f := setToL1S_congr_left T T' (fun _ _ _ => by rw [h]) f theorem setToL1SCLM_congr_left' (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (h : ∀ s, MeasurableSet s → μ s < ∞ → T s = T' s) (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ hT f = setToL1SCLM α E μ hT' f := setToL1S_congr_left T T' h f theorem setToL1SCLM_congr_measure {μ' : Measure α} (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ' T C') (hμ : μ ≪ μ') (f : α →₁ₛ[μ] E) (f' : α →₁ₛ[μ'] E) (h : (f : α → E) =ᵐ[μ] f') : setToL1SCLM α E μ hT f = setToL1SCLM α E μ' hT' f' := setToL1S_congr_measure T (fun _ => hT.eq_zero_of_measure_zero) hT.1 hμ _ _ h theorem setToL1SCLM_add_left (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ (hT.add hT') f = setToL1SCLM α E μ hT f + setToL1SCLM α E μ hT' f := setToL1S_add_left T T' f theorem setToL1SCLM_add_left' (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (hT'' : DominatedFinMeasAdditive μ T'' C'') (h_add : ∀ s, MeasurableSet s → μ s < ∞ → T'' s = T s + T' s) (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ hT'' f = setToL1SCLM α E μ hT f + setToL1SCLM α E μ hT' f := setToL1S_add_left' T T' T'' h_add f theorem setToL1SCLM_smul_left (c : ℝ) (hT : DominatedFinMeasAdditive μ T C) (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ (hT.smul c) f = c • setToL1SCLM α E μ hT f := setToL1S_smul_left T c f theorem setToL1SCLM_smul_left' (c : ℝ) (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (h_smul : ∀ s, MeasurableSet s → μ s < ∞ → T' s = c • T s) (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ hT' f = c • setToL1SCLM α E μ hT f := setToL1S_smul_left' T T' c h_smul f theorem norm_setToL1SCLM_le {T : Set α → E →L[ℝ] F} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hC : 0 ≤ C) : ‖setToL1SCLM α E μ hT‖ ≤ C := LinearMap.mkContinuous_norm_le _ hC _ theorem norm_setToL1SCLM_le' {T : Set α → E →L[ℝ] F} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) : ‖setToL1SCLM α E μ hT‖ ≤ max C 0 := LinearMap.mkContinuous_norm_le' _ _ theorem setToL1SCLM_const [IsFiniteMeasure μ] {T : Set α → E →L[ℝ] F} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) (x : E) : setToL1SCLM α E μ hT (simpleFunc.indicatorConst 1 MeasurableSet.univ (measure_ne_top μ _) x) = T univ x := setToL1S_const (fun _ => hT.eq_zero_of_measure_zero) hT.1 x section Order variable {G' G'' : Type*} [NormedAddCommGroup G''] [PartialOrder G''] [IsOrderedAddMonoid G''] [NormedSpace ℝ G''] [NormedAddCommGroup G'] [PartialOrder G'] [IsOrderedAddMonoid G'] [NormedSpace ℝ G'] theorem setToL1SCLM_mono_left {T T' : Set α → E →L[ℝ] G''} {C C' : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (hTT' : ∀ s x, T s x ≤ T' s x) (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ hT f ≤ setToL1SCLM α E μ hT' f := SimpleFunc.setToSimpleFunc_mono_left T T' hTT' _ theorem setToL1SCLM_mono_left' {T T' : Set α → E →L[ℝ] G''} {C C' : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (hTT' : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, T s x ≤ T' s x) (f : α →₁ₛ[μ] E) : setToL1SCLM α E μ hT f ≤ setToL1SCLM α E μ hT' f := SimpleFunc.setToSimpleFunc_mono_left' T T' hTT' _ (SimpleFunc.integrable f) omit [IsOrderedAddMonoid G'] in theorem setToL1SCLM_nonneg {T : Set α → G' →L[ℝ] G''} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) {f : α →₁ₛ[μ] G'} (hf : 0 ≤ f) : 0 ≤ setToL1SCLM α G' μ hT f := setToL1S_nonneg (fun _ => hT.eq_zero_of_measure_zero) hT.1 hT_nonneg hf theorem setToL1SCLM_mono {T : Set α → G' →L[ℝ] G''} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) {f g : α →₁ₛ[μ] G'} (hfg : f ≤ g) : setToL1SCLM α G' μ hT f ≤ setToL1SCLM α G' μ hT g := setToL1S_mono (fun _ => hT.eq_zero_of_measure_zero) hT.1 hT_nonneg hfg end Order end SetToL1S end SimpleFunc open SimpleFunc section SetToL1 attribute [local instance] Lp.simpleFunc.module attribute [local instance] Lp.simpleFunc.normedSpace variable (𝕜) [NormedRing 𝕜] [Module 𝕜 E] [Module 𝕜 F] [IsBoundedSMul 𝕜 E] [IsBoundedSMul 𝕜 F] [CompleteSpace F] {T T' T'' : Set α → E →L[ℝ] F} {C C' C'' : ℝ} /-- Extend `Set α → (E →L[ℝ] F)` to `(α →₁[μ] E) →L[𝕜] F`. -/ def setToL1' (hT : DominatedFinMeasAdditive μ T C) (h_smul : ∀ c : 𝕜, ∀ s x, T s (c • x) = c • T s x) : (α →₁[μ] E) →L[𝕜] F := (setToL1SCLM' α E 𝕜 μ hT h_smul).extend (coeToLp α E 𝕜) (simpleFunc.denseRange one_ne_top) simpleFunc.isUniformInducing variable {𝕜} /-- Extend `Set α → E →L[ℝ] F` to `(α →₁[μ] E) →L[ℝ] F`. -/ def setToL1 (hT : DominatedFinMeasAdditive μ T C) : (α →₁[μ] E) →L[ℝ] F := (setToL1SCLM α E μ hT).extend (coeToLp α E ℝ) (simpleFunc.denseRange one_ne_top) simpleFunc.isUniformInducing theorem setToL1_eq_setToL1SCLM (hT : DominatedFinMeasAdditive μ T C) (f : α →₁ₛ[μ] E) : setToL1 hT f = setToL1SCLM α E μ hT f := uniformly_extend_of_ind simpleFunc.isUniformInducing (simpleFunc.denseRange one_ne_top) (setToL1SCLM α E μ hT).uniformContinuous _ theorem setToL1_eq_setToL1' (hT : DominatedFinMeasAdditive μ T C) (h_smul : ∀ c : 𝕜, ∀ s x, T s (c • x) = c • T s x) (f : α →₁[μ] E) : setToL1 hT f = setToL1' 𝕜 hT h_smul f := rfl @[simp] theorem setToL1_zero_left (hT : DominatedFinMeasAdditive μ (0 : Set α → E →L[ℝ] F) C) (f : α →₁[μ] E) : setToL1 hT f = 0 := by suffices setToL1 hT = 0 by rw [this]; simp refine ContinuousLinearMap.extend_unique (setToL1SCLM α E μ hT) _ _ _ _ ?_ ext1 f rw [setToL1SCLM_zero_left hT f, ContinuousLinearMap.zero_comp, ContinuousLinearMap.zero_apply] theorem setToL1_zero_left' (hT : DominatedFinMeasAdditive μ T C) (h_zero : ∀ s, MeasurableSet s → μ s < ∞ → T s = 0) (f : α →₁[μ] E) : setToL1 hT f = 0 := by suffices setToL1 hT = 0 by rw [this]; simp refine ContinuousLinearMap.extend_unique (setToL1SCLM α E μ hT) _ _ _ _ ?_ ext1 f rw [setToL1SCLM_zero_left' hT h_zero f, ContinuousLinearMap.zero_comp, ContinuousLinearMap.zero_apply] theorem setToL1_congr_left (T T' : Set α → E →L[ℝ] F) {C C' : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (h : T = T') (f : α →₁[μ] E) : setToL1 hT f = setToL1 hT' f := by suffices setToL1 hT = setToL1 hT' by rw [this] refine ContinuousLinearMap.extend_unique (setToL1SCLM α E μ hT) _ _ _ _ ?_ ext1 f suffices setToL1 hT' f = setToL1SCLM α E μ hT f by rw [← this]; simp [coeToLp] rw [setToL1_eq_setToL1SCLM] exact setToL1SCLM_congr_left hT' hT h.symm f theorem setToL1_congr_left' (T T' : Set α → E →L[ℝ] F) {C C' : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (h : ∀ s, MeasurableSet s → μ s < ∞ → T s = T' s) (f : α →₁[μ] E) : setToL1 hT f = setToL1 hT' f := by suffices setToL1 hT = setToL1 hT' by rw [this] refine ContinuousLinearMap.extend_unique (setToL1SCLM α E μ hT) _ _ _ _ ?_ ext1 f suffices setToL1 hT' f = setToL1SCLM α E μ hT f by rw [← this]; simp [coeToLp] rw [setToL1_eq_setToL1SCLM] exact (setToL1SCLM_congr_left' hT hT' h f).symm theorem setToL1_add_left (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (f : α →₁[μ] E) : setToL1 (hT.add hT') f = setToL1 hT f + setToL1 hT' f := by suffices setToL1 (hT.add hT') = setToL1 hT + setToL1 hT' by rw [this, ContinuousLinearMap.add_apply] refine ContinuousLinearMap.extend_unique (setToL1SCLM α E μ (hT.add hT')) _ _ _ _ ?_ ext1 f suffices setToL1 hT f + setToL1 hT' f = setToL1SCLM α E μ (hT.add hT') f by rw [← this]; simp [coeToLp] rw [setToL1_eq_setToL1SCLM, setToL1_eq_setToL1SCLM, setToL1SCLM_add_left hT hT'] theorem setToL1_add_left' (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (hT'' : DominatedFinMeasAdditive μ T'' C'') (h_add : ∀ s, MeasurableSet s → μ s < ∞ → T'' s = T s + T' s) (f : α →₁[μ] E) : setToL1 hT'' f = setToL1 hT f + setToL1 hT' f := by suffices setToL1 hT'' = setToL1 hT + setToL1 hT' by rw [this, ContinuousLinearMap.add_apply] refine ContinuousLinearMap.extend_unique (setToL1SCLM α E μ hT'') _ _ _ _ ?_ ext1 f suffices setToL1 hT f + setToL1 hT' f = setToL1SCLM α E μ hT'' f by rw [← this]; simp [coeToLp] rw [setToL1_eq_setToL1SCLM, setToL1_eq_setToL1SCLM, setToL1SCLM_add_left' hT hT' hT'' h_add] theorem setToL1_smul_left (hT : DominatedFinMeasAdditive μ T C) (c : ℝ) (f : α →₁[μ] E) : setToL1 (hT.smul c) f = c • setToL1 hT f := by suffices setToL1 (hT.smul c) = c • setToL1 hT by rw [this, ContinuousLinearMap.smul_apply] refine ContinuousLinearMap.extend_unique (setToL1SCLM α E μ (hT.smul c)) _ _ _ _ ?_ ext1 f suffices c • setToL1 hT f = setToL1SCLM α E μ (hT.smul c) f by rw [← this]; simp [coeToLp] rw [setToL1_eq_setToL1SCLM, setToL1SCLM_smul_left c hT] theorem setToL1_smul_left' (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (c : ℝ) (h_smul : ∀ s, MeasurableSet s → μ s < ∞ → T' s = c • T s) (f : α →₁[μ] E) : setToL1 hT' f = c • setToL1 hT f := by suffices setToL1 hT' = c • setToL1 hT by rw [this, ContinuousLinearMap.smul_apply] refine ContinuousLinearMap.extend_unique (setToL1SCLM α E μ hT') _ _ _ _ ?_ ext1 f suffices c • setToL1 hT f = setToL1SCLM α E μ hT' f by rw [← this]; simp [coeToLp] rw [setToL1_eq_setToL1SCLM, setToL1SCLM_smul_left' c hT hT' h_smul] theorem setToL1_smul (hT : DominatedFinMeasAdditive μ T C) (h_smul : ∀ c : 𝕜, ∀ s x, T s (c • x) = c • T s x) (c : 𝕜) (f : α →₁[μ] E) : setToL1 hT (c • f) = c • setToL1 hT f := by rw [setToL1_eq_setToL1' hT h_smul, setToL1_eq_setToL1' hT h_smul] exact ContinuousLinearMap.map_smul _ _ _ theorem setToL1_simpleFunc_indicatorConst (hT : DominatedFinMeasAdditive μ T C) {s : Set α} (hs : MeasurableSet s) (hμs : μ s < ∞) (x : E) : setToL1 hT (simpleFunc.indicatorConst 1 hs hμs.ne x) = T s x := by rw [setToL1_eq_setToL1SCLM] exact setToL1S_indicatorConst (fun s => hT.eq_zero_of_measure_zero) hT.1 hs hμs x theorem setToL1_indicatorConstLp (hT : DominatedFinMeasAdditive μ T C) {s : Set α} (hs : MeasurableSet s) (hμs : μ s ≠ ∞) (x : E) : setToL1 hT (indicatorConstLp 1 hs hμs x) = T s x := by rw [← Lp.simpleFunc.coe_indicatorConst hs hμs x] exact setToL1_simpleFunc_indicatorConst hT hs hμs.lt_top x theorem setToL1_const [IsFiniteMeasure μ] (hT : DominatedFinMeasAdditive μ T C) (x : E) : setToL1 hT (indicatorConstLp 1 MeasurableSet.univ (measure_ne_top _ _) x) = T univ x := setToL1_indicatorConstLp hT MeasurableSet.univ (measure_ne_top _ _) x section Order variable {G' G'' : Type*} [NormedAddCommGroup G''] [PartialOrder G''] [OrderClosedTopology G''] [IsOrderedAddMonoid G''] [NormedSpace ℝ G''] [CompleteSpace G''] [NormedAddCommGroup G'] [PartialOrder G'] [NormedSpace ℝ G'] theorem setToL1_mono_left' {T T' : Set α → E →L[ℝ] G''} {C C' : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (hTT' : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, T s x ≤ T' s x) (f : α →₁[μ] E) : setToL1 hT f ≤ setToL1 hT' f := by induction f using Lp.induction (hp_ne_top := one_ne_top) with | @indicatorConst c s hs hμs => rw [setToL1_simpleFunc_indicatorConst hT hs hμs, setToL1_simpleFunc_indicatorConst hT' hs hμs] exact hTT' s hs hμs c | @add f g hf hg _ hf_le hg_le => rw [(setToL1 hT).map_add, (setToL1 hT').map_add] exact add_le_add hf_le hg_le | isClosed => exact isClosed_le (setToL1 hT).continuous (setToL1 hT').continuous theorem setToL1_mono_left {T T' : Set α → E →L[ℝ] G''} {C C' : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (hTT' : ∀ s x, T s x ≤ T' s x) (f : α →₁[μ] E) : setToL1 hT f ≤ setToL1 hT' f := setToL1_mono_left' hT hT' (fun s _ _ x => hTT' s x) f theorem setToL1_nonneg {T : Set α → G' →L[ℝ] G''} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) {f : α →₁[μ] G'} (hf : 0 ≤ f) : 0 ≤ setToL1 hT f := by suffices ∀ f : { g : α →₁[μ] G' // 0 ≤ g }, 0 ≤ setToL1 hT f from this (⟨f, hf⟩ : { g : α →₁[μ] G' // 0 ≤ g }) refine fun g => @isClosed_property { g : α →₁ₛ[μ] G' // 0 ≤ g } { g : α →₁[μ] G' // 0 ≤ g } _ _ (fun g => 0 ≤ setToL1 hT g) (denseRange_coeSimpleFuncNonnegToLpNonneg 1 μ G' one_ne_top) ?_ ?_ g · exact isClosed_le continuous_zero ((setToL1 hT).continuous.comp continuous_induced_dom) · intro g have : (coeSimpleFuncNonnegToLpNonneg 1 μ G' g : α →₁[μ] G') = (g : α →₁ₛ[μ] G') := rfl rw [this, setToL1_eq_setToL1SCLM] exact setToL1S_nonneg (fun s => hT.eq_zero_of_measure_zero) hT.1 hT_nonneg g.2 theorem setToL1_mono [IsOrderedAddMonoid G'] {T : Set α → G' →L[ℝ] G''} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) {f g : α →₁[μ] G'} (hfg : f ≤ g) : setToL1 hT f ≤ setToL1 hT g := by rw [← sub_nonneg] at hfg ⊢ rw [← (setToL1 hT).map_sub] exact setToL1_nonneg hT hT_nonneg hfg end Order theorem norm_setToL1_le_norm_setToL1SCLM (hT : DominatedFinMeasAdditive μ T C) : ‖setToL1 hT‖ ≤ ‖setToL1SCLM α E μ hT‖ := calc ‖setToL1 hT‖ ≤ (1 : ℝ≥0) * ‖setToL1SCLM α E μ hT‖ := by refine ContinuousLinearMap.opNorm_extend_le (setToL1SCLM α E μ hT) (coeToLp α E ℝ) (simpleFunc.denseRange one_ne_top) fun x => le_of_eq ?_ rw [NNReal.coe_one, one_mul] simp [coeToLp] _ = ‖setToL1SCLM α E μ hT‖ := by rw [NNReal.coe_one, one_mul] theorem norm_setToL1_le_mul_norm (hT : DominatedFinMeasAdditive μ T C) (hC : 0 ≤ C) (f : α →₁[μ] E) : ‖setToL1 hT f‖ ≤ C * ‖f‖ := calc ‖setToL1 hT f‖ ≤ ‖setToL1SCLM α E μ hT‖ * ‖f‖ := ContinuousLinearMap.le_of_opNorm_le _ (norm_setToL1_le_norm_setToL1SCLM hT) _ _ ≤ C * ‖f‖ := mul_le_mul (norm_setToL1SCLM_le hT hC) le_rfl (norm_nonneg _) hC theorem norm_setToL1_le_mul_norm' (hT : DominatedFinMeasAdditive μ T C) (f : α →₁[μ] E) : ‖setToL1 hT f‖ ≤ max C 0 * ‖f‖ := calc ‖setToL1 hT f‖ ≤ ‖setToL1SCLM α E μ hT‖ * ‖f‖ := ContinuousLinearMap.le_of_opNorm_le _ (norm_setToL1_le_norm_setToL1SCLM hT) _ _ ≤ max C 0 * ‖f‖ := mul_le_mul (norm_setToL1SCLM_le' hT) le_rfl (norm_nonneg _) (le_max_right _ _) theorem norm_setToL1_le (hT : DominatedFinMeasAdditive μ T C) (hC : 0 ≤ C) : ‖setToL1 hT‖ ≤ C := ContinuousLinearMap.opNorm_le_bound _ hC (norm_setToL1_le_mul_norm hT hC) theorem norm_setToL1_le' (hT : DominatedFinMeasAdditive μ T C) : ‖setToL1 hT‖ ≤ max C 0 := ContinuousLinearMap.opNorm_le_bound _ (le_max_right _ _) (norm_setToL1_le_mul_norm' hT) theorem setToL1_lipschitz (hT : DominatedFinMeasAdditive μ T C) : LipschitzWith (Real.toNNReal C) (setToL1 hT) := (setToL1 hT).lipschitz.weaken (norm_setToL1_le' hT) /-- If `fs i → f` in `L1`, then `setToL1 hT (fs i) → setToL1 hT f`. -/ theorem tendsto_setToL1 (hT : DominatedFinMeasAdditive μ T C) (f : α →₁[μ] E) {ι} (fs : ι → α →₁[μ] E) {l : Filter ι} (hfs : Tendsto fs l (𝓝 f)) : Tendsto (fun i => setToL1 hT (fs i)) l (𝓝 <| setToL1 hT f) := ((setToL1 hT).continuous.tendsto _).comp hfs end SetToL1 end L1 section Function variable [CompleteSpace F] {T T' T'' : Set α → E →L[ℝ] F} {C C' C'' : ℝ} {f g : α → E} variable (μ T) open Classical in /-- Extend `T : Set α → E →L[ℝ] F` to `(α → E) → F` (for integrable functions `α → E`). We set it to 0 if the function is not integrable. -/ def setToFun (hT : DominatedFinMeasAdditive μ T C) (f : α → E) : F := if hf : Integrable f μ then L1.setToL1 hT (hf.toL1 f) else 0 variable {μ T} theorem setToFun_eq (hT : DominatedFinMeasAdditive μ T C) (hf : Integrable f μ) : setToFun μ T hT f = L1.setToL1 hT (hf.toL1 f) := dif_pos hf theorem L1.setToFun_eq_setToL1 (hT : DominatedFinMeasAdditive μ T C) (f : α →₁[μ] E) : setToFun μ T hT f = L1.setToL1 hT f := by rw [setToFun_eq hT (L1.integrable_coeFn f), Integrable.toL1_coeFn] theorem setToFun_undef (hT : DominatedFinMeasAdditive μ T C) (hf : ¬Integrable f μ) : setToFun μ T hT f = 0 := dif_neg hf theorem setToFun_non_aestronglyMeasurable (hT : DominatedFinMeasAdditive μ T C) (hf : ¬AEStronglyMeasurable f μ) : setToFun μ T hT f = 0 := setToFun_undef hT (not_and_of_not_left _ hf) theorem setToFun_congr_left (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (h : T = T') (f : α → E) : setToFun μ T hT f = setToFun μ T' hT' f := by by_cases hf : Integrable f μ · simp_rw [setToFun_eq _ hf, L1.setToL1_congr_left T T' hT hT' h] · simp_rw [setToFun_undef _ hf] theorem setToFun_congr_left' (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (h : ∀ s, MeasurableSet s → μ s < ∞ → T s = T' s) (f : α → E) : setToFun μ T hT f = setToFun μ T' hT' f := by by_cases hf : Integrable f μ · simp_rw [setToFun_eq _ hf, L1.setToL1_congr_left' T T' hT hT' h] · simp_rw [setToFun_undef _ hf] theorem setToFun_add_left (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (f : α → E) : setToFun μ (T + T') (hT.add hT') f = setToFun μ T hT f + setToFun μ T' hT' f := by by_cases hf : Integrable f μ · simp_rw [setToFun_eq _ hf, L1.setToL1_add_left hT hT'] · simp_rw [setToFun_undef _ hf, add_zero] theorem setToFun_add_left' (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (hT'' : DominatedFinMeasAdditive μ T'' C'') (h_add : ∀ s, MeasurableSet s → μ s < ∞ → T'' s = T s + T' s) (f : α → E) : setToFun μ T'' hT'' f = setToFun μ T hT f + setToFun μ T' hT' f := by by_cases hf : Integrable f μ · simp_rw [setToFun_eq _ hf, L1.setToL1_add_left' hT hT' hT'' h_add] · simp_rw [setToFun_undef _ hf, add_zero] theorem setToFun_smul_left (hT : DominatedFinMeasAdditive μ T C) (c : ℝ) (f : α → E) : setToFun μ (fun s => c • T s) (hT.smul c) f = c • setToFun μ T hT f := by by_cases hf : Integrable f μ · simp_rw [setToFun_eq _ hf, L1.setToL1_smul_left hT c] · simp_rw [setToFun_undef _ hf, smul_zero] theorem setToFun_smul_left' (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (c : ℝ) (h_smul : ∀ s, MeasurableSet s → μ s < ∞ → T' s = c • T s) (f : α → E) : setToFun μ T' hT' f = c • setToFun μ T hT f := by by_cases hf : Integrable f μ · simp_rw [setToFun_eq _ hf, L1.setToL1_smul_left' hT hT' c h_smul] · simp_rw [setToFun_undef _ hf, smul_zero] @[simp] theorem setToFun_zero (hT : DominatedFinMeasAdditive μ T C) : setToFun μ T hT (0 : α → E) = 0 := by rw [Pi.zero_def, setToFun_eq hT (integrable_zero _ _ _)] simp only [← Pi.zero_def] rw [Integrable.toL1_zero, ContinuousLinearMap.map_zero] @[simp] theorem setToFun_zero_left {hT : DominatedFinMeasAdditive μ (0 : Set α → E →L[ℝ] F) C} : setToFun μ 0 hT f = 0 := by by_cases hf : Integrable f μ · rw [setToFun_eq hT hf]; exact L1.setToL1_zero_left hT _ · exact setToFun_undef hT hf theorem setToFun_zero_left' (hT : DominatedFinMeasAdditive μ T C) (h_zero : ∀ s, MeasurableSet s → μ s < ∞ → T s = 0) : setToFun μ T hT f = 0 := by by_cases hf : Integrable f μ · rw [setToFun_eq hT hf]; exact L1.setToL1_zero_left' hT h_zero _ · exact setToFun_undef hT hf theorem setToFun_add (hT : DominatedFinMeasAdditive μ T C) (hf : Integrable f μ) (hg : Integrable g μ) : setToFun μ T hT (f + g) = setToFun μ T hT f + setToFun μ T hT g := by rw [setToFun_eq hT (hf.add hg), setToFun_eq hT hf, setToFun_eq hT hg, Integrable.toL1_add, (L1.setToL1 hT).map_add] theorem setToFun_finset_sum' (hT : DominatedFinMeasAdditive μ T C) {ι} (s : Finset ι) {f : ι → α → E} (hf : ∀ i ∈ s, Integrable (f i) μ) : setToFun μ T hT (∑ i ∈ s, f i) = ∑ i ∈ s, setToFun μ T hT (f i) := by classical revert hf refine Finset.induction_on s ?_ ?_ · intro _ simp only [setToFun_zero, Finset.sum_empty] · intro i s his ih hf simp only [his, Finset.sum_insert, not_false_iff] rw [setToFun_add hT (hf i (Finset.mem_insert_self i s)) _] · rw [ih fun i hi => hf i (Finset.mem_insert_of_mem hi)] · convert integrable_finset_sum s fun i hi => hf i (Finset.mem_insert_of_mem hi) with x simp theorem setToFun_finset_sum (hT : DominatedFinMeasAdditive μ T C) {ι} (s : Finset ι) {f : ι → α → E} (hf : ∀ i ∈ s, Integrable (f i) μ) : (setToFun μ T hT fun a => ∑ i ∈ s, f i a) = ∑ i ∈ s, setToFun μ T hT (f i) := by convert setToFun_finset_sum' hT s hf with a; simp theorem setToFun_neg (hT : DominatedFinMeasAdditive μ T C) (f : α → E) : setToFun μ T hT (-f) = -setToFun μ T hT f := by by_cases hf : Integrable f μ · rw [setToFun_eq hT hf, setToFun_eq hT hf.neg, Integrable.toL1_neg, (L1.setToL1 hT).map_neg] · rw [setToFun_undef hT hf, setToFun_undef hT, neg_zero] rwa [← integrable_neg_iff] at hf theorem setToFun_sub (hT : DominatedFinMeasAdditive μ T C) (hf : Integrable f μ) (hg : Integrable g μ) : setToFun μ T hT (f - g) = setToFun μ T hT f - setToFun μ T hT g := by rw [sub_eq_add_neg, sub_eq_add_neg, setToFun_add hT hf hg.neg, setToFun_neg hT g] theorem setToFun_smul [NormedDivisionRing 𝕜] [Module 𝕜 E] [NormSMulClass 𝕜 E] [Module 𝕜 F] [NormSMulClass 𝕜 F] (hT : DominatedFinMeasAdditive μ T C) (h_smul : ∀ c : 𝕜, ∀ s x, T s (c • x) = c • T s x) (c : 𝕜) (f : α → E) : setToFun μ T hT (c • f) = c • setToFun μ T hT f := by by_cases hf : Integrable f μ · rw [setToFun_eq hT hf, setToFun_eq hT (hf.smul c), Integrable.toL1_smul' f hf, L1.setToL1_smul hT h_smul c] · by_cases hr : c = 0 · rw [hr]; simp · have hf' : ¬Integrable (c • f) μ := by rwa [integrable_smul_iff hr f] rw [setToFun_undef hT hf, setToFun_undef hT hf', smul_zero] theorem setToFun_congr_ae (hT : DominatedFinMeasAdditive μ T C) (h : f =ᵐ[μ] g) : setToFun μ T hT f = setToFun μ T hT g := by by_cases hfi : Integrable f μ · have hgi : Integrable g μ := hfi.congr h rw [setToFun_eq hT hfi, setToFun_eq hT hgi, (Integrable.toL1_eq_toL1_iff f g hfi hgi).2 h] · have hgi : ¬Integrable g μ := by rw [integrable_congr h] at hfi; exact hfi rw [setToFun_undef hT hfi, setToFun_undef hT hgi] theorem setToFun_measure_zero (hT : DominatedFinMeasAdditive μ T C) (h : μ = 0) : setToFun μ T hT f = 0 := by have : f =ᵐ[μ] 0 := by simp [h, EventuallyEq] rw [setToFun_congr_ae hT this, setToFun_zero] theorem setToFun_measure_zero' (hT : DominatedFinMeasAdditive μ T C) (h : ∀ s, MeasurableSet s → μ s < ∞ → μ s = 0) : setToFun μ T hT f = 0 := setToFun_zero_left' hT fun s hs hμs => hT.eq_zero_of_measure_zero hs (h s hs hμs) theorem setToFun_toL1 (hT : DominatedFinMeasAdditive μ T C) (hf : Integrable f μ) : setToFun μ T hT (hf.toL1 f) = setToFun μ T hT f := setToFun_congr_ae hT hf.coeFn_toL1 theorem setToFun_indicator_const (hT : DominatedFinMeasAdditive μ T C) {s : Set α} (hs : MeasurableSet s) (hμs : μ s ≠ ∞) (x : E) : setToFun μ T hT (s.indicator fun _ => x) = T s x := by rw [setToFun_congr_ae hT (@indicatorConstLp_coeFn _ _ _ 1 _ _ _ hs hμs x).symm] rw [L1.setToFun_eq_setToL1 hT] exact L1.setToL1_indicatorConstLp hT hs hμs x theorem setToFun_const [IsFiniteMeasure μ] (hT : DominatedFinMeasAdditive μ T C) (x : E) : (setToFun μ T hT fun _ => x) = T univ x := by have : (fun _ : α => x) = Set.indicator univ fun _ => x := (indicator_univ _).symm rw [this] exact setToFun_indicator_const hT MeasurableSet.univ (measure_ne_top _ _) x section Order variable {G' G'' : Type*} [NormedAddCommGroup G''] [PartialOrder G''] [OrderClosedTopology G''] [IsOrderedAddMonoid G''] [NormedSpace ℝ G''] [CompleteSpace G''] [NormedAddCommGroup G'] [PartialOrder G'] [NormedSpace ℝ G'] theorem setToFun_mono_left' {T T' : Set α → E →L[ℝ] G''} {C C' : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (hTT' : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, T s x ≤ T' s x) (f : α → E) : setToFun μ T hT f ≤ setToFun μ T' hT' f := by by_cases hf : Integrable f μ · simp_rw [setToFun_eq _ hf]; exact L1.setToL1_mono_left' hT hT' hTT' _ · simp_rw [setToFun_undef _ hf, le_rfl] theorem setToFun_mono_left {T T' : Set α → E →L[ℝ] G''} {C C' : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') (hTT' : ∀ s x, T s x ≤ T' s x) (f : α →₁[μ] E) : setToFun μ T hT f ≤ setToFun μ T' hT' f := setToFun_mono_left' hT hT' (fun s _ _ x => hTT' s x) f theorem setToFun_nonneg {T : Set α → G' →L[ℝ] G''} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) {f : α → G'} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ setToFun μ T hT f := by by_cases hfi : Integrable f μ · simp_rw [setToFun_eq _ hfi] refine L1.setToL1_nonneg hT hT_nonneg ?_ rw [← Lp.coeFn_le] have h0 := Lp.coeFn_zero G' 1 μ have h := Integrable.coeFn_toL1 hfi filter_upwards [h0, h, hf] with _ h0a ha hfa rw [h0a, ha] exact hfa · simp_rw [setToFun_undef _ hfi, le_rfl] theorem setToFun_mono [IsOrderedAddMonoid G'] {T : Set α → G' →L[ℝ] G''} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) {f g : α → G'} (hf : Integrable f μ) (hg : Integrable g μ) (hfg : f ≤ᵐ[μ] g) : setToFun μ T hT f ≤ setToFun μ T hT g := by rw [← sub_nonneg, ← setToFun_sub hT hg hf] refine setToFun_nonneg hT hT_nonneg (hfg.mono fun a ha => ?_) rw [Pi.sub_apply, Pi.zero_apply, sub_nonneg] exact ha end Order @[continuity] theorem continuous_setToFun (hT : DominatedFinMeasAdditive μ T C) : Continuous fun f : α →₁[μ] E => setToFun μ T hT f := by simp_rw [L1.setToFun_eq_setToL1 hT]; exact ContinuousLinearMap.continuous _ /-- If `F i → f` in `L1`, then `setToFun μ T hT (F i) → setToFun μ T hT f`. -/ theorem tendsto_setToFun_of_L1 (hT : DominatedFinMeasAdditive μ T C) {ι} (f : α → E) (hfi : Integrable f μ) {fs : ι → α → E} {l : Filter ι} (hfsi : ∀ᶠ i in l, Integrable (fs i) μ) (hfs : Tendsto (fun i => ∫⁻ x, ‖fs i x - f x‖ₑ ∂μ) l (𝓝 0)) : Tendsto (fun i => setToFun μ T hT (fs i)) l (𝓝 <| setToFun μ T hT f) := by classical let f_lp := hfi.toL1 f let F_lp i := if hFi : Integrable (fs i) μ then hFi.toL1 (fs i) else 0 have tendsto_L1 : Tendsto F_lp l (𝓝 f_lp) := by rw [Lp.tendsto_Lp_iff_tendsto_eLpNorm'] simp_rw [eLpNorm_one_eq_lintegral_enorm, Pi.sub_apply] refine (tendsto_congr' ?_).mp hfs filter_upwards [hfsi] with i hi refine lintegral_congr_ae ?_ filter_upwards [hi.coeFn_toL1, hfi.coeFn_toL1] with x hxi hxf simp_rw [F_lp, dif_pos hi, hxi, f_lp, hxf] suffices Tendsto (fun i => setToFun μ T hT (F_lp i)) l (𝓝 (setToFun μ T hT f)) by refine (tendsto_congr' ?_).mp this filter_upwards [hfsi] with i hi suffices h_ae_eq : F_lp i =ᵐ[μ] fs i from setToFun_congr_ae hT h_ae_eq simp_rw [F_lp, dif_pos hi] exact hi.coeFn_toL1 rw [setToFun_congr_ae hT hfi.coeFn_toL1.symm] exact ((continuous_setToFun hT).tendsto f_lp).comp tendsto_L1 theorem tendsto_setToFun_approxOn_of_measurable (hT : DominatedFinMeasAdditive μ T C) [MeasurableSpace E] [BorelSpace E] {f : α → E} {s : Set E} [SeparableSpace s] (hfi : Integrable f μ) (hfm : Measurable f) (hs : ∀ᵐ x ∂μ, f x ∈ closure s) {y₀ : E} (h₀ : y₀ ∈ s) (h₀i : Integrable (fun _ => y₀) μ) : Tendsto (fun n => setToFun μ T hT (SimpleFunc.approxOn f hfm s y₀ h₀ n)) atTop (𝓝 <| setToFun μ T hT f) := tendsto_setToFun_of_L1 hT _ hfi (Eventually.of_forall (SimpleFunc.integrable_approxOn hfm hfi h₀ h₀i)) (SimpleFunc.tendsto_approxOn_L1_enorm hfm _ hs (hfi.sub h₀i).2) theorem tendsto_setToFun_approxOn_of_measurable_of_range_subset (hT : DominatedFinMeasAdditive μ T C) [MeasurableSpace E] [BorelSpace E] {f : α → E} (fmeas : Measurable f) (hf : Integrable f μ) (s : Set E) [SeparableSpace s] (hs : range f ∪ {0} ⊆ s) : Tendsto (fun n => setToFun μ T hT (SimpleFunc.approxOn f fmeas s 0 (hs <| by simp) n)) atTop (𝓝 <| setToFun μ T hT f) := by refine tendsto_setToFun_approxOn_of_measurable hT hf fmeas ?_ _ (integrable_zero _ _ _) exact Eventually.of_forall fun x => subset_closure (hs (Set.mem_union_left _ (mem_range_self _))) /-- Auxiliary lemma for `setToFun_congr_measure`: the function sending `f : α →₁[μ] G` to `f : α →₁[μ'] G` is continuous when `μ' ≤ c' • μ` for `c' ≠ ∞`. -/ theorem continuous_L1_toL1 {μ' : Measure α} (c' : ℝ≥0∞) (hc' : c' ≠ ∞) (hμ'_le : μ' ≤ c' • μ) : Continuous fun f : α →₁[μ] G => (Integrable.of_measure_le_smul hc' hμ'_le (L1.integrable_coeFn f)).toL1 f := by by_cases hc'0 : c' = 0 · have hμ'0 : μ' = 0 := by rw [← Measure.nonpos_iff_eq_zero']; refine hμ'_le.trans ?_; simp [hc'0] have h_im_zero : (fun f : α →₁[μ] G => (Integrable.of_measure_le_smul hc' hμ'_le (L1.integrable_coeFn f)).toL1 f) = 0 := by ext1 f; ext1; simp_rw [hμ'0]; simp only [ae_zero, EventuallyEq, eventually_bot] rw [h_im_zero] exact continuous_zero rw [Metric.continuous_iff] intro f ε hε_pos use ε / 2 / c'.toReal refine ⟨div_pos (half_pos hε_pos) (toReal_pos hc'0 hc'), ?_⟩ intro g hfg rw [Lp.dist_def] at hfg ⊢ let h_int := fun f' : α →₁[μ] G => (L1.integrable_coeFn f').of_measure_le_smul hc' hμ'_le have : eLpNorm (⇑(Integrable.toL1 g (h_int g)) - ⇑(Integrable.toL1 f (h_int f))) 1 μ' = eLpNorm (⇑g - ⇑f) 1 μ' := eLpNorm_congr_ae ((Integrable.coeFn_toL1 _).sub (Integrable.coeFn_toL1 _)) rw [this] have h_eLpNorm_ne_top : eLpNorm (⇑g - ⇑f) 1 μ ≠ ∞ := by rw [← eLpNorm_congr_ae (Lp.coeFn_sub _ _)]; exact Lp.eLpNorm_ne_top _ calc (eLpNorm (⇑g - ⇑f) 1 μ').toReal ≤ (c' * eLpNorm (⇑g - ⇑f) 1 μ).toReal := by refine toReal_mono (ENNReal.mul_ne_top hc' h_eLpNorm_ne_top) ?_ refine (eLpNorm_mono_measure (⇑g - ⇑f) hμ'_le).trans_eq ?_ rw [eLpNorm_smul_measure_of_ne_zero hc'0, smul_eq_mul] simp _ = c'.toReal * (eLpNorm (⇑g - ⇑f) 1 μ).toReal := toReal_mul _ ≤ c'.toReal * (ε / 2 / c'.toReal) := by gcongr _ = ε / 2 := by refine mul_div_cancel₀ (ε / 2) ?_; rw [Ne, toReal_eq_zero_iff]; simp [hc', hc'0] _ < ε := half_lt_self hε_pos theorem setToFun_congr_measure_of_integrable {μ' : Measure α} (c' : ℝ≥0∞) (hc' : c' ≠ ∞) (hμ'_le : μ' ≤ c' • μ) (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ' T C') (f : α → E) (hfμ : Integrable f μ) : setToFun μ T hT f = setToFun μ' T hT' f := by -- integrability for `μ` implies integrability for `μ'`. have h_int : ∀ g : α → E, Integrable g μ → Integrable g μ' := fun g hg => Integrable.of_measure_le_smul hc' hμ'_le hg -- We use `Integrable.induction` apply hfμ.induction (P := fun f => setToFun μ T hT f = setToFun μ' T hT' f) · intro c s hs hμs have hμ's : μ' s ≠ ∞ := by refine ((hμ'_le s).trans_lt ?_).ne rw [Measure.smul_apply, smul_eq_mul] exact ENNReal.mul_lt_top hc'.lt_top hμs rw [setToFun_indicator_const hT hs hμs.ne, setToFun_indicator_const hT' hs hμ's] · intro f₂ g₂ _ hf₂ hg₂ h_eq_f h_eq_g rw [setToFun_add hT hf₂ hg₂, setToFun_add hT' (h_int f₂ hf₂) (h_int g₂ hg₂), h_eq_f, h_eq_g] · refine isClosed_eq (continuous_setToFun hT) ?_ have : (fun f : α →₁[μ] E => setToFun μ' T hT' f) = fun f : α →₁[μ] E => setToFun μ' T hT' ((h_int f (L1.integrable_coeFn f)).toL1 f) := by ext1 f; exact setToFun_congr_ae hT' (Integrable.coeFn_toL1 _).symm rw [this] exact (continuous_setToFun hT').comp (continuous_L1_toL1 c' hc' hμ'_le) · intro f₂ g₂ hfg _ hf_eq have hfg' : f₂ =ᵐ[μ'] g₂ := (Measure.absolutelyContinuous_of_le_smul hμ'_le).ae_eq hfg rw [← setToFun_congr_ae hT hfg, hf_eq, setToFun_congr_ae hT' hfg'] theorem setToFun_congr_measure {μ' : Measure α} (c c' : ℝ≥0∞) (hc : c ≠ ∞) (hc' : c' ≠ ∞) (hμ_le : μ ≤ c • μ') (hμ'_le : μ' ≤ c' • μ) (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ' T C') (f : α → E) : setToFun μ T hT f = setToFun μ' T hT' f := by by_cases hf : Integrable f μ · exact setToFun_congr_measure_of_integrable c' hc' hμ'_le hT hT' f hf · -- if `f` is not integrable, both `setToFun` are 0. have h_int : ∀ g : α → E, ¬Integrable g μ → ¬Integrable g μ' := fun g => mt fun h => h.of_measure_le_smul hc hμ_le simp_rw [setToFun_undef _ hf, setToFun_undef _ (h_int f hf)] theorem setToFun_congr_measure_of_add_right {μ' : Measure α} (hT_add : DominatedFinMeasAdditive (μ + μ') T C') (hT : DominatedFinMeasAdditive μ T C) (f : α → E) (hf : Integrable f (μ + μ')) : setToFun (μ + μ') T hT_add f = setToFun μ T hT f := by refine setToFun_congr_measure_of_integrable 1 one_ne_top ?_ hT_add hT f hf rw [one_smul] nth_rw 1 [← add_zero μ] exact add_le_add le_rfl bot_le theorem setToFun_congr_measure_of_add_left {μ' : Measure α} (hT_add : DominatedFinMeasAdditive (μ + μ') T C') (hT : DominatedFinMeasAdditive μ' T C) (f : α → E) (hf : Integrable f (μ + μ')) : setToFun (μ + μ') T hT_add f = setToFun μ' T hT f := by refine setToFun_congr_measure_of_integrable 1 one_ne_top ?_ hT_add hT f hf rw [one_smul] exact Measure.le_add_left le_rfl theorem setToFun_top_smul_measure (hT : DominatedFinMeasAdditive (∞ • μ) T C) (f : α → E) : setToFun (∞ • μ) T hT f = 0 := by refine setToFun_measure_zero' hT fun s _ hμs => ?_ rw [lt_top_iff_ne_top] at hμs simp only [true_and, Measure.smul_apply, ENNReal.mul_eq_top, top_ne_zero, Ne, not_false_iff, not_or, Classical.not_not, smul_eq_mul] at hμs simp only [hμs.right, Measure.smul_apply, mul_zero, smul_eq_mul] theorem setToFun_congr_smul_measure (c : ℝ≥0∞) (hc_ne_top : c ≠ ∞) (hT : DominatedFinMeasAdditive μ T C) (hT_smul : DominatedFinMeasAdditive (c • μ) T C') (f : α → E) : setToFun μ T hT f = setToFun (c • μ) T hT_smul f := by by_cases hc0 : c = 0 · simp [hc0] at hT_smul have h : ∀ s, MeasurableSet s → μ s < ∞ → T s = 0 := fun s hs _ => hT_smul.eq_zero hs rw [setToFun_zero_left' _ h, setToFun_measure_zero] simp [hc0] refine setToFun_congr_measure c⁻¹ c ?_ hc_ne_top (le_of_eq ?_) le_rfl hT hT_smul f · simp [hc0] · rw [smul_smul, ENNReal.inv_mul_cancel hc0 hc_ne_top, one_smul] theorem norm_setToFun_le_mul_norm (hT : DominatedFinMeasAdditive μ T C) (f : α →₁[μ] E) (hC : 0 ≤ C) : ‖setToFun μ T hT f‖ ≤ C * ‖f‖ := by rw [L1.setToFun_eq_setToL1]; exact L1.norm_setToL1_le_mul_norm hT hC f theorem norm_setToFun_le_mul_norm' (hT : DominatedFinMeasAdditive μ T C) (f : α →₁[μ] E) : ‖setToFun μ T hT f‖ ≤ max C 0 * ‖f‖ := by rw [L1.setToFun_eq_setToL1]; exact L1.norm_setToL1_le_mul_norm' hT f theorem norm_setToFun_le (hT : DominatedFinMeasAdditive μ T C) (hf : Integrable f μ) (hC : 0 ≤ C) : ‖setToFun μ T hT f‖ ≤ C * ‖hf.toL1 f‖ := by rw [setToFun_eq hT hf]; exact L1.norm_setToL1_le_mul_norm hT hC _ theorem norm_setToFun_le' (hT : DominatedFinMeasAdditive μ T C) (hf : Integrable f μ) : ‖setToFun μ T hT f‖ ≤ max C 0 * ‖hf.toL1 f‖ := by rw [setToFun_eq hT hf]; exact L1.norm_setToL1_le_mul_norm' hT _ /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their image by `setToFun`. We could weaken the condition `bound_integrable` to require `HasFiniteIntegral bound μ` instead (i.e. not requiring that `bound` is measurable), but in all applications proving integrability is easier. -/ theorem tendsto_setToFun_of_dominated_convergence (hT : DominatedFinMeasAdditive μ T C) {fs : ℕ → α → E} {f : α → E} (bound : α → ℝ) (fs_measurable : ∀ n, AEStronglyMeasurable (fs n) μ) (bound_integrable : Integrable bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ‖fs n a‖ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, Tendsto (fun n => fs n a) atTop (𝓝 (f a))) : Tendsto (fun n => setToFun μ T hT (fs n)) atTop (𝓝 <| setToFun μ T hT f) := by -- `f` is a.e.-measurable, since it is the a.e.-pointwise limit of a.e.-measurable functions. have f_measurable : AEStronglyMeasurable f μ := aestronglyMeasurable_of_tendsto_ae _ fs_measurable h_lim -- all functions we consider are integrable have fs_int : ∀ n, Integrable (fs n) μ := fun n => bound_integrable.mono' (fs_measurable n) (h_bound _) have f_int : Integrable f μ := ⟨f_measurable, hasFiniteIntegral_of_dominated_convergence bound_integrable.hasFiniteIntegral h_bound h_lim⟩ -- it suffices to prove the result for the corresponding L1 functions suffices Tendsto (fun n => L1.setToL1 hT ((fs_int n).toL1 (fs n))) atTop (𝓝 (L1.setToL1 hT (f_int.toL1 f))) by convert this with n · exact setToFun_eq hT (fs_int n) · exact setToFun_eq hT f_int -- the convergence of setToL1 follows from the convergence of the L1 functions refine L1.tendsto_setToL1 hT _ _ ?_ -- up to some rewriting, what we need to prove is `h_lim` rw [tendsto_iff_norm_sub_tendsto_zero] have lintegral_norm_tendsto_zero : Tendsto (fun n => ENNReal.toReal <| ∫⁻ a, ENNReal.ofReal ‖fs n a - f a‖ ∂μ) atTop (𝓝 0) := (tendsto_toReal zero_ne_top).comp (tendsto_lintegral_norm_of_dominated_convergence fs_measurable bound_integrable.hasFiniteIntegral h_bound h_lim) convert lintegral_norm_tendsto_zero with n rw [L1.norm_def] congr 1 refine lintegral_congr_ae ?_ rw [← Integrable.toL1_sub] refine ((fs_int n).sub f_int).coeFn_toL1.mono fun x hx => ?_ dsimp only rw [hx, ofReal_norm_eq_enorm, Pi.sub_apply] /-- Lebesgue dominated convergence theorem for filters with a countable basis -/ theorem tendsto_setToFun_filter_of_dominated_convergence (hT : DominatedFinMeasAdditive μ T C) {ι} {l : Filter ι} [l.IsCountablyGenerated] {fs : ι → α → E} {f : α → E} (bound : α → ℝ) (hfs_meas : ∀ᶠ n in l, AEStronglyMeasurable (fs n) μ) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, ‖fs n a‖ ≤ bound a) (bound_integrable : Integrable bound μ) (h_lim : ∀ᵐ a ∂μ, Tendsto (fun n => fs n a) l (𝓝 (f a))) : Tendsto (fun n => setToFun μ T hT (fs n)) l (𝓝 <| setToFun μ T hT f) := by rw [tendsto_iff_seq_tendsto] intro x xl have hxl : ∀ s ∈ l, ∃ a, ∀ b ≥ a, x b ∈ s := by rwa [tendsto_atTop'] at xl have h : { x : ι | (fun n => AEStronglyMeasurable (fs n) μ) x } ∩ { x : ι | (fun n => ∀ᵐ a ∂μ, ‖fs n a‖ ≤ bound a) x } ∈ l := inter_mem hfs_meas h_bound obtain ⟨k, h⟩ := hxl _ h rw [← tendsto_add_atTop_iff_nat k] refine tendsto_setToFun_of_dominated_convergence hT bound ?_ bound_integrable ?_ ?_ · exact fun n => (h _ (self_le_add_left _ _)).1 · exact fun n => (h _ (self_le_add_left _ _)).2 · filter_upwards [h_lim] refine fun a h_lin => @Tendsto.comp _ _ _ (fun n => x (n + k)) (fun n => fs n a) _ _ _ h_lin ?_ rwa [tendsto_add_atTop_iff_nat] variable {X : Type*} [TopologicalSpace X] [FirstCountableTopology X] theorem continuousWithinAt_setToFun_of_dominated (hT : DominatedFinMeasAdditive μ T C) {fs : X → α → E} {x₀ : X} {bound : α → ℝ} {s : Set X} (hfs_meas : ∀ᶠ x in 𝓝[s] x₀, AEStronglyMeasurable (fs x) μ) (h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ a ∂μ, ‖fs x a‖ ≤ bound a) (bound_integrable : Integrable bound μ) (h_cont : ∀ᵐ a ∂μ, ContinuousWithinAt (fun x => fs x a) s x₀) : ContinuousWithinAt (fun x => setToFun μ T hT (fs x)) s x₀ := tendsto_setToFun_filter_of_dominated_convergence hT bound ‹_› ‹_› ‹_› ‹_› theorem continuousAt_setToFun_of_dominated (hT : DominatedFinMeasAdditive μ T C) {fs : X → α → E} {x₀ : X} {bound : α → ℝ} (hfs_meas : ∀ᶠ x in 𝓝 x₀, AEStronglyMeasurable (fs x) μ) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ a ∂μ, ‖fs x a‖ ≤ bound a) (bound_integrable : Integrable bound μ) (h_cont : ∀ᵐ a ∂μ, ContinuousAt (fun x => fs x a) x₀) : ContinuousAt (fun x => setToFun μ T hT (fs x)) x₀ := tendsto_setToFun_filter_of_dominated_convergence hT bound ‹_› ‹_› ‹_› ‹_› theorem continuousOn_setToFun_of_dominated (hT : DominatedFinMeasAdditive μ T C) {fs : X → α → E} {bound : α → ℝ} {s : Set X} (hfs_meas : ∀ x ∈ s, AEStronglyMeasurable (fs x) μ) (h_bound : ∀ x ∈ s, ∀ᵐ a ∂μ, ‖fs x a‖ ≤ bound a) (bound_integrable : Integrable bound μ) (h_cont : ∀ᵐ a ∂μ, ContinuousOn (fun x => fs x a) s) : ContinuousOn (fun x => setToFun μ T hT (fs x)) s := by intro x hx refine continuousWithinAt_setToFun_of_dominated hT ?_ ?_ bound_integrable ?_ · filter_upwards [self_mem_nhdsWithin] with x hx using hfs_meas x hx · filter_upwards [self_mem_nhdsWithin] with x hx using h_bound x hx · filter_upwards [h_cont] with a ha using ha x hx theorem continuous_setToFun_of_dominated (hT : DominatedFinMeasAdditive μ T C) {fs : X → α → E} {bound : α → ℝ} (hfs_meas : ∀ x, AEStronglyMeasurable (fs x) μ) (h_bound : ∀ x, ∀ᵐ a ∂μ, ‖fs x a‖ ≤ bound a) (bound_integrable : Integrable bound μ) (h_cont : ∀ᵐ a ∂μ, Continuous fun x => fs x a) : Continuous fun x => setToFun μ T hT (fs x) := continuous_iff_continuousAt.mpr fun _ => continuousAt_setToFun_of_dominated hT (Eventually.of_forall hfs_meas) (Eventually.of_forall h_bound) ‹_› <| h_cont.mono fun _ => Continuous.continuousAt end Function end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/PeakFunction.lean
import Mathlib.MeasureTheory.Integral.IntegralEqImproper /-! # Integrals against peak functions A sequence of peak functions is a sequence of functions with average one concentrating around a point `x₀`. Given such a sequence `φₙ`, then `∫ φₙ g` tends to `g x₀` in many situations, with a whole zoo of possible assumptions on `φₙ` and `g`. This file is devoted to such results. Such functions are also called approximations of unity, or approximations of identity. ## Main results * `tendsto_setIntegral_peak_smul_of_integrableOn_of_tendsto`: If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and continuous at `x₀`, then `∫ φᵢ • g` converges to `g x₀`. * `tendsto_setIntegral_pow_smul_of_unique_maximum_of_isCompact_of_continuousOn`: If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is continuous on `s`. * `tendsto_integral_comp_smul_smul_of_integrable`: If a nonnegative function `φ` has integral one and decays quickly enough at infinity, then its renormalizations `x ↦ c ^ d * φ (c • x)` form a sequence of peak functions as `c → ∞`. Therefore, `∫ (c ^ d * φ (c • x)) • g x` converges to `g 0` as `c → ∞` if `g` is continuous at `0` and integrable. Note that there are related results about convolution with respect to peak functions in the file `Mathlib/Analysis/Convolution.lean`, such as `MeasureTheory.convolution_tendsto_right` there. -/ open Set Filter MeasureTheory MeasureTheory.Measure TopologicalSpace Metric open scoped Topology ENNReal /-! ### General convergent result for integrals against a sequence of peak functions -/ open Set variable {α E ι : Type*} {hm : MeasurableSpace α} {μ : Measure α} [TopologicalSpace α] [BorelSpace α] [NormedAddCommGroup E] [NormedSpace ℝ E] {g : α → E} {l : Filter ι} {x₀ : α} {s t : Set α} {φ : ι → α → ℝ} {a : E} /-- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and has a limit at `x₀`, then `φᵢ • g` is eventually integrable. -/ theorem integrableOn_peak_smul_of_integrableOn_of_tendsto (hs : MeasurableSet s) (h'st : t ∈ 𝓝[s] x₀) (hlφ : ∀ u : Set α, IsOpen u → x₀ ∈ u → TendstoUniformlyOn φ 0 l (s \ u)) (hiφ : Tendsto (fun i ↦ ∫ x in t, φ i x ∂μ) l (𝓝 1)) (h'iφ : ∀ᶠ i in l, AEStronglyMeasurable (φ i) (μ.restrict s)) (hmg : IntegrableOn g s μ) (hcg : Tendsto g (𝓝[s] x₀) (𝓝 a)) : ∀ᶠ i in l, IntegrableOn (fun x => φ i x • g x) s μ := by obtain ⟨u, u_open, x₀u, ut, hu⟩ : ∃ u, IsOpen u ∧ x₀ ∈ u ∧ s ∩ u ⊆ t ∧ ∀ x ∈ u ∩ s, g x ∈ ball a 1 := by rcases mem_nhdsWithin.1 (Filter.inter_mem h'st (hcg (ball_mem_nhds _ zero_lt_one))) with ⟨u, u_open, x₀u, hu⟩ refine ⟨u, u_open, x₀u, ?_, hu.trans inter_subset_right⟩ rw [inter_comm] exact hu.trans inter_subset_left rw [tendsto_iff_norm_sub_tendsto_zero] at hiφ filter_upwards [tendstoUniformlyOn_iff.1 (hlφ u u_open x₀u) 1 zero_lt_one, (tendsto_order.1 hiφ).2 1 zero_lt_one, h'iφ] with i hi h'i h''i have I : IntegrableOn (φ i) t μ := .of_integral_ne_zero (fun h ↦ by simp [h] at h'i) have A : IntegrableOn (fun x => φ i x • g x) (s \ u) μ := by refine Integrable.smul_of_top_right (hmg.mono diff_subset le_rfl) ?_ apply memLp_top_of_bound (h''i.mono_set diff_subset) 1 filter_upwards [self_mem_ae_restrict (hs.diff u_open.measurableSet)] with x hx simpa only [Pi.zero_apply, dist_zero_left] using (hi x hx).le have B : IntegrableOn (fun x => φ i x • g x) (s ∩ u) μ := by apply Integrable.smul_of_top_left · exact IntegrableOn.mono_set I ut · apply memLp_top_of_bound (hmg.mono_set inter_subset_left).aestronglyMeasurable (‖a‖ + 1) filter_upwards [self_mem_ae_restrict (hs.inter u_open.measurableSet)] with x hx rw [inter_comm] at hx exact (norm_lt_of_mem_ball (hu x hx)).le convert A.union B simp only [diff_union_inter] /-- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀` and its integral on some finite-measure neighborhood of `x₀` converges to `1`, and `g` is integrable and has a limit `a` at `x₀`, then `∫ φᵢ • g` converges to `a`. Auxiliary lemma where one assumes additionally `a = 0`. -/ theorem tendsto_setIntegral_peak_smul_of_integrableOn_of_tendsto_aux (hs : MeasurableSet s) (ht : MeasurableSet t) (hts : t ⊆ s) (h'ts : t ∈ 𝓝[s] x₀) (hnφ : ∀ᶠ i in l, ∀ x ∈ s, 0 ≤ φ i x) (hlφ : ∀ u : Set α, IsOpen u → x₀ ∈ u → TendstoUniformlyOn φ 0 l (s \ u)) (hiφ : Tendsto (fun i ↦ ∫ x in t, φ i x ∂μ) l (𝓝 1)) (h'iφ : ∀ᶠ i in l, AEStronglyMeasurable (φ i) (μ.restrict s)) (hmg : IntegrableOn g s μ) (hcg : Tendsto g (𝓝[s] x₀) (𝓝 0)) : Tendsto (fun i : ι => ∫ x in s, φ i x • g x ∂μ) l (𝓝 0) := by refine Metric.tendsto_nhds.2 fun ε εpos => ?_ obtain ⟨δ, hδ, δpos, δone⟩ : ∃ δ, (δ * ∫ x in s, ‖g x‖ ∂μ) + 2 * δ < ε ∧ 0 < δ ∧ δ < 1 := by have A : Tendsto (fun δ => (δ * ∫ x in s, ‖g x‖ ∂μ) + 2 * δ) (𝓝[>] 0) (𝓝 ((0 * ∫ x in s, ‖g x‖ ∂μ) + 2 * 0)) := by apply Tendsto.mono_left _ nhdsWithin_le_nhds exact (tendsto_id.mul tendsto_const_nhds).add (tendsto_id.const_mul _) rw [zero_mul, zero_add, mul_zero] at A have : Ioo (0 : ℝ) 1 ∈ 𝓝[>] 0 := Ioo_mem_nhdsGT zero_lt_one rcases (((tendsto_order.1 A).2 ε εpos).and this).exists with ⟨δ, hδ, h'δ⟩ exact ⟨δ, hδ, h'δ.1, h'δ.2⟩ suffices ∀ᶠ i in l, ‖∫ x in s, φ i x • g x ∂μ‖ ≤ (δ * ∫ x in s, ‖g x‖ ∂μ) + 2 * δ by filter_upwards [this] with i hi simp only [dist_zero_right] exact hi.trans_lt hδ obtain ⟨u, u_open, x₀u, ut, hu⟩ : ∃ u, IsOpen u ∧ x₀ ∈ u ∧ s ∩ u ⊆ t ∧ ∀ x ∈ u ∩ s, g x ∈ ball 0 δ := by rcases mem_nhdsWithin.1 (Filter.inter_mem h'ts (hcg (ball_mem_nhds _ δpos))) with ⟨u, u_open, x₀u, hu⟩ refine ⟨u, u_open, x₀u, ?_, hu.trans inter_subset_right⟩ rw [inter_comm] exact hu.trans inter_subset_left filter_upwards [tendstoUniformlyOn_iff.1 (hlφ u u_open x₀u) δ δpos, (tendsto_order.1 (tendsto_iff_norm_sub_tendsto_zero.1 hiφ)).2 δ δpos, hnφ, integrableOn_peak_smul_of_integrableOn_of_tendsto hs h'ts hlφ hiφ h'iφ hmg hcg] with i hi h'i hφpos h''i have I : IntegrableOn (φ i) t μ := by apply Integrable.of_integral_ne_zero (fun h ↦ ?_) simp [h] at h'i linarith have B : ‖∫ x in s ∩ u, φ i x • g x ∂μ‖ ≤ 2 * δ := calc ‖∫ x in s ∩ u, φ i x • g x ∂μ‖ ≤ ∫ x in s ∩ u, ‖φ i x • g x‖ ∂μ := norm_integral_le_integral_norm _ _ ≤ ∫ x in s ∩ u, ‖φ i x‖ * δ ∂μ := by refine setIntegral_mono_on ?_ ?_ (hs.inter u_open.measurableSet) fun x hx => ?_ · exact IntegrableOn.mono_set h''i.norm inter_subset_left · exact IntegrableOn.mono_set (I.norm.mul_const _) ut rw [norm_smul] gcongr rw [inter_comm] at hu exact (mem_ball_zero_iff.1 (hu x hx)).le _ ≤ ∫ x in t, ‖φ i x‖ * δ ∂μ := by apply setIntegral_mono_set · exact I.norm.mul_const _ · exact Eventually.of_forall fun x => mul_nonneg (norm_nonneg _) δpos.le · exact Eventually.of_forall ut _ = ∫ x in t, φ i x * δ ∂μ := by apply setIntegral_congr_fun ht fun x hx => ?_ rw [Real.norm_of_nonneg (hφpos _ (hts hx))] _ = (∫ x in t, φ i x ∂μ) * δ := by rw [integral_mul_const] _ ≤ 2 * δ := by gcongr; linarith [(le_abs_self _).trans h'i.le] have C : ‖∫ x in s \ u, φ i x • g x ∂μ‖ ≤ δ * ∫ x in s, ‖g x‖ ∂μ := calc ‖∫ x in s \ u, φ i x • g x ∂μ‖ ≤ ∫ x in s \ u, ‖φ i x • g x‖ ∂μ := norm_integral_le_integral_norm _ _ ≤ ∫ x in s \ u, δ * ‖g x‖ ∂μ := by refine setIntegral_mono_on ?_ ?_ (hs.diff u_open.measurableSet) fun x hx => ?_ · exact IntegrableOn.mono_set h''i.norm diff_subset · exact IntegrableOn.mono_set (hmg.norm.const_mul _) diff_subset rw [norm_smul] gcongr simpa only [Pi.zero_apply, dist_zero_left] using (hi x hx).le _ ≤ δ * ∫ x in s, ‖g x‖ ∂μ := by rw [integral_const_mul] apply mul_le_mul_of_nonneg_left (setIntegral_mono_set hmg.norm _ _) δpos.le · filter_upwards with x using norm_nonneg _ · filter_upwards using diff_subset (s := s) (t := u) calc ‖∫ x in s, φ i x • g x ∂μ‖ = ‖(∫ x in s \ u, φ i x • g x ∂μ) + ∫ x in s ∩ u, φ i x • g x ∂μ‖ := by conv_lhs => rw [← diff_union_inter s u] rw [setIntegral_union disjoint_sdiff_inter (hs.inter u_open.measurableSet) (h''i.mono_set diff_subset) (h''i.mono_set inter_subset_left)] _ ≤ ‖∫ x in s \ u, φ i x • g x ∂μ‖ + ‖∫ x in s ∩ u, φ i x • g x ∂μ‖ := norm_add_le _ _ _ ≤ (δ * ∫ x in s, ‖g x‖ ∂μ) + 2 * δ := add_le_add C B variable [CompleteSpace E] /-- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀` and its integral on some finite-measure neighborhood of `x₀` converges to `1`, and `g` is integrable and has a limit `a` at `x₀`, then `∫ φᵢ • g` converges to `a`. Version localized to a subset. -/ theorem tendsto_setIntegral_peak_smul_of_integrableOn_of_tendsto (hs : MeasurableSet s) {t : Set α} (ht : MeasurableSet t) (hts : t ⊆ s) (h'ts : t ∈ 𝓝[s] x₀) (h't : μ t ≠ ∞) (hnφ : ∀ᶠ i in l, ∀ x ∈ s, 0 ≤ φ i x) (hlφ : ∀ u : Set α, IsOpen u → x₀ ∈ u → TendstoUniformlyOn φ 0 l (s \ u)) (hiφ : Tendsto (fun i ↦ ∫ x in t, φ i x ∂μ) l (𝓝 1)) (h'iφ : ∀ᶠ i in l, AEStronglyMeasurable (φ i) (μ.restrict s)) (hmg : IntegrableOn g s μ) (hcg : Tendsto g (𝓝[s] x₀) (𝓝 a)) : Tendsto (fun i : ι ↦ ∫ x in s, φ i x • g x ∂μ) l (𝓝 a) := by let h := g - t.indicator (fun _ ↦ a) have A : Tendsto (fun i : ι => (∫ x in s, φ i x • h x ∂μ) + (∫ x in t, φ i x ∂μ) • a) l (𝓝 (0 + (1 : ℝ) • a)) := by refine Tendsto.add ?_ (Tendsto.smul hiφ tendsto_const_nhds) apply tendsto_setIntegral_peak_smul_of_integrableOn_of_tendsto_aux hs ht hts h'ts hnφ hlφ hiφ h'iφ · apply hmg.sub simp only [integrable_indicator_iff ht, integrableOn_const_iff (C := a), ht, Measure.restrict_apply] right exact lt_of_le_of_lt (measure_mono inter_subset_left) (h't.lt_top) · rw [← sub_self a] apply Tendsto.sub hcg apply tendsto_const_nhds.congr' filter_upwards [h'ts] with x hx using by simp [hx] simp only [one_smul, zero_add] at A refine Tendsto.congr' ?_ A filter_upwards [integrableOn_peak_smul_of_integrableOn_of_tendsto hs h'ts hlφ hiφ h'iφ hmg hcg, (tendsto_order.1 (tendsto_iff_norm_sub_tendsto_zero.1 hiφ)).2 1 zero_lt_one] with i hi h'i simp only [h, Pi.sub_apply, smul_sub, ← indicator_smul_apply] rw [integral_sub hi, setIntegral_indicator ht, inter_eq_right.mpr hts, integral_smul_const, sub_add_cancel] rw [integrable_indicator_iff ht] apply Integrable.smul_const rw [restrict_restrict ht, inter_eq_left.mpr hts] exact .of_integral_ne_zero (fun h ↦ by simp [h] at h'i) /-- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀` and its integral on some finite-measure neighborhood of `x₀` converges to `1`, and `g` is integrable and has a limit `a` at `x₀`, then `∫ φᵢ • g` converges to `a`. -/ theorem tendsto_integral_peak_smul_of_integrable_of_tendsto {t : Set α} (ht : MeasurableSet t) (h'ts : t ∈ 𝓝 x₀) (h't : μ t ≠ ∞) (hnφ : ∀ᶠ i in l, ∀ x, 0 ≤ φ i x) (hlφ : ∀ u : Set α, IsOpen u → x₀ ∈ u → TendstoUniformlyOn φ 0 l uᶜ) (hiφ : Tendsto (fun i ↦ ∫ x in t, φ i x ∂μ) l (𝓝 1)) (h'iφ : ∀ᶠ i in l, AEStronglyMeasurable (φ i) μ) (hmg : Integrable g μ) (hcg : Tendsto g (𝓝 x₀) (𝓝 a)) : Tendsto (fun i : ι ↦ ∫ x, φ i x • g x ∂μ) l (𝓝 a) := by suffices Tendsto (fun i : ι ↦ ∫ x in univ, φ i x • g x ∂μ) l (𝓝 a) by simpa exact tendsto_setIntegral_peak_smul_of_integrableOn_of_tendsto MeasurableSet.univ ht (x₀ := x₀) (subset_univ _) (by simpa [nhdsWithin_univ]) h't (by simpa) (by simpa [← compl_eq_univ_diff] using hlφ) hiφ (by simpa) (by simpa) (by simpa [nhdsWithin_univ]) /-! ### Peak functions of the form `x ↦ (c x) ^ n / ∫ (c y) ^ n` -/ /-- If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is integrable on `s` and continuous at `x₀`. Version assuming that `μ` gives positive mass to all neighborhoods of `x₀` within `s`. For a less precise but more usable version, see `tendsto_setIntegral_pow_smul_of_unique_maximum_of_isCompact_of_continuousOn`. -/ theorem tendsto_setIntegral_pow_smul_of_unique_maximum_of_isCompact_of_measure_nhdsWithin_pos [MetrizableSpace α] [IsLocallyFiniteMeasure μ] (hs : IsCompact s) (hμ : ∀ u, IsOpen u → x₀ ∈ u → 0 < μ (u ∩ s)) {c : α → ℝ} (hc : ContinuousOn c s) (h'c : ∀ y ∈ s, y ≠ x₀ → c y < c x₀) (hnc : ∀ x ∈ s, 0 ≤ c x) (hnc₀ : 0 < c x₀) (h₀ : x₀ ∈ s) (hmg : IntegrableOn g s μ) (hcg : ContinuousWithinAt g s x₀) : Tendsto (fun n : ℕ => (∫ x in s, c x ^ n ∂μ)⁻¹ • ∫ x in s, c x ^ n • g x ∂μ) atTop (𝓝 (g x₀)) := by /- We apply the general result `tendsto_setIntegral_peak_smul_of_integrableOn_of_continuousWithinAt` to the sequence of peak functions `φₙ = (c x) ^ n / ∫ (c x) ^ n`. The only nontrivial bit is to check that this sequence converges uniformly to zero on any set `s \ u` away from `x₀`. By compactness, the function `c` is bounded by `t < c x₀` there. Consider `t' ∈ (t, c x₀)`, and a neighborhood `v` of `x₀` where `c x ≥ t'`, by continuity. Then `∫ (c x) ^ n` is bounded below by `t' ^ n μ v`. It follows that, on `s \ u`, then `φₙ x ≤ t ^ n / (t' ^ n μ v)`, which tends (exponentially fast) to zero with `n`. -/ let φ : ℕ → α → ℝ := fun n x => (∫ x in s, c x ^ n ∂μ)⁻¹ * c x ^ n have hnφ : ∀ n, ∀ x ∈ s, 0 ≤ φ n x := by intro n x hx apply mul_nonneg (inv_nonneg.2 _) (pow_nonneg (hnc x hx) _) exact setIntegral_nonneg hs.measurableSet fun x hx => pow_nonneg (hnc x hx) _ have I : ∀ n, IntegrableOn (fun x => c x ^ n) s μ := fun n => ContinuousOn.integrableOn_compact hs (hc.pow n) have J : ∀ n, 0 ≤ᵐ[μ.restrict s] fun x : α => c x ^ n := by intro n filter_upwards [ae_restrict_mem hs.measurableSet] with x hx exact pow_nonneg (hnc x hx) n have P : ∀ n, (0 : ℝ) < ∫ x in s, c x ^ n ∂μ := by intro n refine (setIntegral_pos_iff_support_of_nonneg_ae (J n) (I n)).2 ?_ obtain ⟨u, u_open, x₀_u, hu⟩ : ∃ u : Set α, IsOpen u ∧ x₀ ∈ u ∧ u ∩ s ⊆ c ⁻¹' Ioi 0 := _root_.continuousOn_iff.1 hc x₀ h₀ (Ioi (0 : ℝ)) isOpen_Ioi hnc₀ apply (hμ u u_open x₀_u).trans_le exact measure_mono fun x hx => ⟨ne_of_gt (pow_pos (a := c x) (hu hx) _), hx.2⟩ have hiφ : ∀ n, ∫ x in s, φ n x ∂μ = 1 := fun n => by rw [integral_const_mul, inv_mul_cancel₀ (P n).ne'] have A : ∀ u : Set α, IsOpen u → x₀ ∈ u → TendstoUniformlyOn φ 0 atTop (s \ u) := by intro u u_open x₀u obtain ⟨t, t_pos, tx₀, ht⟩ : ∃ t, 0 ≤ t ∧ t < c x₀ ∧ ∀ x ∈ s \ u, c x ≤ t := by rcases eq_empty_or_nonempty (s \ u) with (h | h) · exact ⟨0, le_rfl, hnc₀, by simp only [h, mem_empty_iff_false, IsEmpty.forall_iff, imp_true_iff]⟩ obtain ⟨x, hx, h'x⟩ : ∃ x ∈ s \ u, ∀ y ∈ s \ u, c y ≤ c x := IsCompact.exists_isMaxOn (hs.diff u_open) h (hc.mono diff_subset) refine ⟨c x, hnc x hx.1, h'c x hx.1 ?_, h'x⟩ rintro rfl exact hx.2 x₀u obtain ⟨t', tt', t'x₀⟩ : ∃ t', t < t' ∧ t' < c x₀ := exists_between tx₀ have t'_pos : 0 < t' := t_pos.trans_lt tt' obtain ⟨v, v_open, x₀_v, hv⟩ : ∃ v : Set α, IsOpen v ∧ x₀ ∈ v ∧ v ∩ s ⊆ c ⁻¹' Ioi t' := _root_.continuousOn_iff.1 hc x₀ h₀ (Ioi t') isOpen_Ioi t'x₀ have M : ∀ n, ∀ x ∈ s \ u, φ n x ≤ (μ.real (v ∩ s))⁻¹ * (t / t') ^ n := by intro n x hx have B : t' ^ n * μ.real (v ∩ s) ≤ ∫ y in s, c y ^ n ∂μ := calc t' ^ n * μ.real (v ∩ s) = ∫ _ in v ∩ s, t' ^ n ∂μ := by simp [mul_comm] _ ≤ ∫ y in v ∩ s, c y ^ n ∂μ := by apply setIntegral_mono_on _ _ (v_open.measurableSet.inter hs.measurableSet) _ · refine integrableOn_const (C := t' ^ n) ?_ exact (lt_of_le_of_lt (measure_mono inter_subset_right) hs.measure_lt_top).ne · exact (I n).mono inter_subset_right le_rfl · intro x hx exact pow_le_pow_left₀ t'_pos.le (hv hx).le _ _ ≤ ∫ y in s, c y ^ n ∂μ := setIntegral_mono_set (I n) (J n) (Eventually.of_forall inter_subset_right) simp_rw [φ, ← div_eq_inv_mul, div_pow, div_div] have := ENNReal.toReal_pos (hμ v v_open x₀_v).ne' ((measure_mono inter_subset_right).trans_lt hs.measure_lt_top).ne gcongr · exact hnc _ hx.1 · exact ht x hx have N : Tendsto (fun n => (μ.real (v ∩ s))⁻¹ * (t / t') ^ n) atTop (𝓝 ((μ.real (v ∩ s))⁻¹ * 0)) := by apply Tendsto.mul tendsto_const_nhds _ apply tendsto_pow_atTop_nhds_zero_of_lt_one (div_nonneg t_pos t'_pos.le) exact (div_lt_one t'_pos).2 tt' rw [mul_zero] at N refine tendstoUniformlyOn_iff.2 fun ε εpos => ?_ filter_upwards [(tendsto_order.1 N).2 ε εpos] with n hn x hx simp only [Pi.zero_apply, dist_zero_left, Real.norm_of_nonneg (hnφ n x hx.1)] exact (M n x hx).trans_lt hn have : Tendsto (fun i : ℕ => ∫ x : α in s, φ i x • g x ∂μ) atTop (𝓝 (g x₀)) := by have B : Tendsto (fun i ↦ ∫ (x : α) in s, φ i x ∂μ) atTop (𝓝 1) := tendsto_const_nhds.congr (fun n ↦ (hiφ n).symm) have C : ∀ᶠ (i : ℕ) in atTop, AEStronglyMeasurable (fun x ↦ φ i x) (μ.restrict s) := by apply Eventually.of_forall (fun n ↦ ((I n).const_mul _).aestronglyMeasurable) exact tendsto_setIntegral_peak_smul_of_integrableOn_of_tendsto hs.measurableSet hs.measurableSet (Subset.rfl) (self_mem_nhdsWithin) hs.measure_lt_top.ne (Eventually.of_forall hnφ) A B C hmg hcg convert this simp_rw [φ, ← smul_smul, integral_smul] /-- If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is integrable on `s` and continuous at `x₀`. Version assuming that `μ` gives positive mass to all open sets. For a less precise but more usable version, see `tendsto_setIntegral_pow_smul_of_unique_maximum_of_isCompact_of_continuousOn`. -/ theorem tendsto_setIntegral_pow_smul_of_unique_maximum_of_isCompact_of_integrableOn [MetrizableSpace α] [IsLocallyFiniteMeasure μ] [IsOpenPosMeasure μ] (hs : IsCompact s) {c : α → ℝ} (hc : ContinuousOn c s) (h'c : ∀ y ∈ s, y ≠ x₀ → c y < c x₀) (hnc : ∀ x ∈ s, 0 ≤ c x) (hnc₀ : 0 < c x₀) (h₀ : x₀ ∈ closure (interior s)) (hmg : IntegrableOn g s μ) (hcg : ContinuousWithinAt g s x₀) : Tendsto (fun n : ℕ => (∫ x in s, c x ^ n ∂μ)⁻¹ • ∫ x in s, c x ^ n • g x ∂μ) atTop (𝓝 (g x₀)) := by have : x₀ ∈ s := by rw [← hs.isClosed.closure_eq]; exact closure_mono interior_subset h₀ apply tendsto_setIntegral_pow_smul_of_unique_maximum_of_isCompact_of_measure_nhdsWithin_pos hs _ hc h'c hnc hnc₀ this hmg hcg intro u u_open x₀_u calc 0 < μ (u ∩ interior s) := (u_open.inter isOpen_interior).measure_pos μ (_root_.mem_closure_iff.1 h₀ u u_open x₀_u) _ ≤ μ (u ∩ s) := by gcongr; apply interior_subset /-- If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is continuous on `s`. -/ theorem tendsto_setIntegral_pow_smul_of_unique_maximum_of_isCompact_of_continuousOn [MetrizableSpace α] [IsLocallyFiniteMeasure μ] [IsOpenPosMeasure μ] (hs : IsCompact s) {c : α → ℝ} (hc : ContinuousOn c s) (h'c : ∀ y ∈ s, y ≠ x₀ → c y < c x₀) (hnc : ∀ x ∈ s, 0 ≤ c x) (hnc₀ : 0 < c x₀) (h₀ : x₀ ∈ closure (interior s)) (hmg : ContinuousOn g s) : Tendsto (fun n : ℕ => (∫ x in s, c x ^ n ∂μ)⁻¹ • ∫ x in s, c x ^ n • g x ∂μ) atTop (𝓝 (g x₀)) := haveI : x₀ ∈ s := by rw [← hs.isClosed.closure_eq]; exact closure_mono interior_subset h₀ tendsto_setIntegral_pow_smul_of_unique_maximum_of_isCompact_of_integrableOn hs hc h'c hnc hnc₀ h₀ (hmg.integrableOn_compact hs) (hmg x₀ this) /-! ### Peak functions of the form `x ↦ c ^ dim * φ (c x)` -/ open Module Bornology variable {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] [FiniteDimensional ℝ F] [MeasurableSpace F] [BorelSpace F] {μ : Measure F} [IsAddHaarMeasure μ] /-- Consider a nonnegative function `φ` with integral one, decaying quickly enough at infinity. Then suitable renormalizations of `φ` form a sequence of peak functions around the origin: `∫ (c ^ d * φ (c • x)) • g x` converges to `g 0` as `c → ∞` if `g` is continuous at `0` and integrable. -/ theorem tendsto_integral_comp_smul_smul_of_integrable {φ : F → ℝ} (hφ : ∀ x, 0 ≤ φ x) (h'φ : ∫ x, φ x ∂μ = 1) (h : Tendsto (fun x ↦ ‖x‖ ^ finrank ℝ F * φ x) (cobounded F) (𝓝 0)) {g : F → E} (hg : Integrable g μ) (h'g : ContinuousAt g 0) : Tendsto (fun (c : ℝ) ↦ ∫ x, (c ^ (finrank ℝ F) * φ (c • x)) • g x ∂μ) atTop (𝓝 (g 0)) := by have I : Integrable φ μ := integrable_of_integral_eq_one h'φ apply tendsto_integral_peak_smul_of_integrable_of_tendsto (t := closedBall 0 1) (x₀ := 0) · exact isClosed_closedBall.measurableSet · exact closedBall_mem_nhds _ zero_lt_one · exact (isCompact_closedBall 0 1).measure_ne_top · filter_upwards [Ici_mem_atTop 0] with c (hc : 0 ≤ c) x using mul_nonneg (by positivity) (hφ _) · intro u u_open hu apply tendstoUniformlyOn_iff.2 (fun ε εpos ↦ ?_) obtain ⟨δ, δpos, h'u⟩ : ∃ δ > 0, ball 0 δ ⊆ u := Metric.isOpen_iff.1 u_open _ hu obtain ⟨M, Mpos, hM⟩ : ∃ M > 0, ∀ ⦃x : F⦄, x ∈ (closedBall 0 M)ᶜ → ‖x‖ ^ finrank ℝ F * φ x < δ ^ finrank ℝ F * ε := by rcases (hasBasis_cobounded_compl_closedBall (0 : F)).eventually_iff.1 ((tendsto_order.1 h).2 (δ ^ finrank ℝ F * ε) (by positivity)) with ⟨M, -, hM⟩ refine ⟨max M 1, zero_lt_one.trans_le (le_max_right _ _), fun x hx ↦ hM ?_⟩ simp only [mem_compl_iff, mem_closedBall, dist_zero_right, le_max_iff, not_or, not_le] at hx simpa using hx.1 filter_upwards [Ioi_mem_atTop (M / δ)] with c (hc : M / δ < c) x hx have cpos : 0 < c := lt_trans (by positivity) hc suffices c ^ finrank ℝ F * φ (c • x) < ε by simpa [abs_of_nonneg (hφ _), abs_of_nonneg cpos.le] have hδx : δ ≤ ‖x‖ := by have : x ∈ (ball 0 δ)ᶜ := fun h ↦ hx (h'u h) simpa only [mem_compl_iff, mem_ball, dist_zero_right, not_lt] suffices δ ^ finrank ℝ F * (c ^ finrank ℝ F * φ (c • x)) < δ ^ finrank ℝ F * ε by rwa [mul_lt_mul_iff_of_pos_left (by positivity)] at this calc δ ^ finrank ℝ F * (c ^ finrank ℝ F * φ (c • x)) _ ≤ ‖x‖ ^ finrank ℝ F * (c ^ finrank ℝ F * φ (c • x)) := by gcongr; exact mul_nonneg (by positivity) (hφ _) _ = ‖c • x‖ ^ finrank ℝ F * φ (c • x) := by simp [norm_smul, abs_of_pos cpos, mul_pow]; ring _ < δ ^ finrank ℝ F * ε := by apply hM rw [div_lt_iff₀ δpos] at hc simp only [mem_compl_iff, mem_closedBall, dist_zero_right, norm_smul, Real.norm_eq_abs, abs_of_nonneg cpos.le, not_le] exact hc.trans_le (by gcongr) · have : Tendsto (fun c ↦ ∫ (x : F) in closedBall 0 c, φ x ∂μ) atTop (𝓝 1) := by rw [← h'φ] exact (aecover_closedBall tendsto_id).integral_tendsto_of_countably_generated I apply this.congr' filter_upwards [Ioi_mem_atTop 0] with c (hc : 0 < c) rw [integral_const_mul, setIntegral_comp_smul_of_pos _ _ _ hc, smul_eq_mul, ← mul_assoc, mul_inv_cancel₀ (by positivity), _root_.smul_closedBall _ _ zero_le_one] simp [abs_of_nonneg hc.le] · filter_upwards [Ioi_mem_atTop 0] with c (hc : 0 < c) exact (I.comp_smul hc.ne').aestronglyMeasurable.const_mul _ · exact hg · exact h'g /-- Consider a nonnegative function `φ` with integral one, decaying quickly enough at infinity. Then suitable renormalizations of `φ` form a sequence of peak functions around any point: `∫ (c ^ d * φ (c • (x₀ - x)) • g x` converges to `g x₀` as `c → ∞` if `g` is continuous at `x₀` and integrable. -/ theorem tendsto_integral_comp_smul_smul_of_integrable' {φ : F → ℝ} (hφ : ∀ x, 0 ≤ φ x) (h'φ : ∫ x, φ x ∂μ = 1) (h : Tendsto (fun x ↦ ‖x‖ ^ finrank ℝ F * φ x) (cobounded F) (𝓝 0)) {g : F → E} {x₀ : F} (hg : Integrable g μ) (h'g : ContinuousAt g x₀) : Tendsto (fun (c : ℝ) ↦ ∫ x, (c ^ (finrank ℝ F) * φ (c • (x₀ - x))) • g x ∂μ) atTop (𝓝 (g x₀)) := by let f := fun x ↦ g (x₀ - x) have If : Integrable f μ := by simpa [f, sub_eq_add_neg] using (hg.comp_add_left x₀).comp_neg have : Tendsto (fun (c : ℝ) ↦ ∫ x, (c ^ (finrank ℝ F) * φ (c • x)) • f x ∂μ) atTop (𝓝 (f 0)) := by apply tendsto_integral_comp_smul_smul_of_integrable hφ h'φ h If have A : ContinuousAt g (x₀ - 0) := by simpa using h'g exact A.comp <| by fun_prop simp only [f, sub_zero] at this convert this using 2 with c conv_rhs => rw [← integral_add_left_eq_self x₀ (μ := μ) (f := fun x ↦ (c ^ finrank ℝ F * φ (c • x)) • g (x₀ - x)), ← integral_neg_eq_self] simp [sub_eq_add_neg]
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/VitaliCaratheodory.lean
import Mathlib.MeasureTheory.Integral.Bochner.VitaliCaratheodory deprecated_module (since := "2025-04-06")
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/DivergenceTheorem.lean
import Mathlib.Analysis.BoxIntegral.DivergenceTheorem import Mathlib.Analysis.BoxIntegral.Integrability import Mathlib.Analysis.Calculus.Deriv.Basic import Mathlib.Analysis.Calculus.FDeriv.Equiv import Mathlib.MeasureTheory.Integral.Prod import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic /-! # Divergence theorem for Bochner integral In this file we prove the Divergence theorem for Bochner integral on a box in `ℝⁿ⁺¹ = Fin (n + 1) → ℝ`. More precisely, we prove the following theorem. Let `E` be a complete normed space. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is continuous on a rectangular box `[a, b] : Set ℝⁿ⁺¹`, `a ≤ b`, differentiable on its interior with derivative `f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹`, and the divergence `fun x ↦ ∑ i, f' x eᵢ i` is integrable on `[a, b]`, where `eᵢ = Pi.single i 1` is the `i`-th basis vector, then its integral is equal to the sum of integrals of `f` over the faces of `[a, b]`, taken with appropriate signs. Moreover, the same is true if the function is not differentiable at countably many points of the interior of `[a, b]`. Once we prove the general theorem, we deduce corollaries for functions `ℝ → E` and pairs of functions `(ℝ × ℝ) → E`. ## Notation We use the following local notation to make the statement more readable. Note that the documentation website shows the actual terms, not those abbreviated using local notations. * `ℝⁿ`, `ℝⁿ⁺¹`, `Eⁿ⁺¹`: `Fin n → ℝ`, `Fin (n + 1) → ℝ`, `Fin (n + 1) → E`; * `face i`: the `i`-th face of the box `[a, b]` as a closed segment in `ℝⁿ`, namely `[a ∘ Fin.succAbove i, b ∘ Fin.succAbove i]`; * `e i` : `i`-th basis vector `Pi.single i 1`; * `frontFace i`, `backFace i`: embeddings `ℝⁿ → ℝⁿ⁺¹` corresponding to the front face `{x | x i = b i}` and back face `{x | x i = a i}` of the box `[a, b]`, respectively. They are given by `Fin.insertNth i (b i)` and `Fin.insertNth i (a i)`. ## TODO * Add a version that assumes existence and integrability of partial derivatives. ## Tags divergence theorem, Bochner integral -/ open Set Finset TopologicalSpace Function BoxIntegral MeasureTheory Filter open scoped Topology Interval universe u namespace MeasureTheory variable {E : Type u} [NormedAddCommGroup E] [NormedSpace ℝ E] section variable {n : ℕ} local macro:arg t:term:max noWs "ⁿ" : term => `(Fin n → $t) local macro:arg t:term:max noWs "ⁿ⁺¹" : term => `(Fin (n + 1) → $t) local notation "e " i => Pi.single i 1 section /-! ### Divergence theorem for functions on `ℝⁿ⁺¹ = Fin (n + 1) → ℝ`. In this section we use the divergence theorem for a Henstock-Kurzweil-like integral `BoxIntegral.hasIntegral_GP_divergence_of_forall_hasDerivWithinAt` to prove the divergence theorem for Bochner integral. The divergence theorem for Bochner integral `MeasureTheory.integral_divergence_of_hasFDerivWithinAt_off_countable` assumes that the function itself is continuous on a closed box, differentiable at all but countably many points of its interior, and the divergence is integrable on the box. This statement differs from `BoxIntegral.hasIntegral_GP_divergence_of_forall_hasDerivWithinAt` in several aspects. * We use Bochner integral instead of a Henstock-Kurzweil integral. This modification is done in `MeasureTheory.integral_divergence_of_hasFDerivWithinAt_off_countable_aux₁`. As a side effect of this change, we need to assume that the divergence is integrable. * We don't assume differentiability on the boundary of the box. This modification is done in `MeasureTheory.integral_divergence_of_hasFDerivWithinAt_off_countable_aux₂`. To prove it, we choose an increasing sequence of smaller boxes that cover the interior of the original box, then apply the previous lemma to these smaller boxes and take the limit of both sides of the equation. * We assume `a ≤ b` instead of `∀ i, a i < b i`. This is the last step of the proof, and it is done in the main theorem `MeasureTheory.integral_divergence_of_hasFDerivWithinAt_off_countable`. -/ /-- An auxiliary lemma for `MeasureTheory.integral_divergence_of_hasFDerivWithinAt_off_countable`. This is exactly `BoxIntegral.hasIntegral_GP_divergence_of_forall_hasDerivWithinAt` reformulated for the Bochner integral. -/ private theorem integral_divergence_of_hasFDerivWithinAt_off_countable_aux₁ (I : Box (Fin (n + 1))) (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : Set ℝⁿ⁺¹) (hs : s.Countable) (Hc : ContinuousOn f (Box.Icc I)) (Hd : ∀ x ∈ (Box.Icc I) \ s, HasFDerivWithinAt f (f' x) (Box.Icc I) x) (Hi : IntegrableOn (fun x => ∑ i, f' x (e i) i) (Box.Icc I)) : (∫ x in Box.Icc I, ∑ i, f' x (e i) i) = ∑ i : Fin (n + 1), ((∫ x in Box.Icc (I.face i), f (i.insertNth (I.upper i) x) i) - ∫ x in Box.Icc (I.face i), f (i.insertNth (I.lower i) x) i) := by wlog hE : CompleteSpace E generalizing · simp [integral, hE] simp only [← setIntegral_congr_set (Box.coe_ae_eq_Icc _)] have A := (Hi.mono_set Box.coe_subset_Icc).hasBoxIntegral ⊥ rfl have B := hasIntegral_GP_divergence_of_forall_hasDerivWithinAt I f f' (s ∩ Box.Icc I) (hs.mono inter_subset_left) (fun x hx => Hc _ hx.2) fun x hx => Hd _ ⟨hx.1, fun h => hx.2 ⟨h, hx.1⟩⟩ rw [continuousOn_pi] at Hc refine (A.unique B).trans (sum_congr rfl fun i _ => ?_) refine congr_arg₂ Sub.sub ?_ ?_ · have := Box.continuousOn_face_Icc (Hc i) (Set.right_mem_Icc.2 (I.lower_le_upper i)) have := (this.integrableOn_compact (μ := volume) (Box.isCompact_Icc _)).mono_set Box.coe_subset_Icc exact (this.hasBoxIntegral ⊥ rfl).integral_eq · have := Box.continuousOn_face_Icc (Hc i) (Set.left_mem_Icc.2 (I.lower_le_upper i)) have := (this.integrableOn_compact (μ := volume) (Box.isCompact_Icc _)).mono_set Box.coe_subset_Icc exact (this.hasBoxIntegral ⊥ rfl).integral_eq /-- An auxiliary lemma for `MeasureTheory.integral_divergence_of_hasFDerivWithinAt_off_countable`. Compared to the previous lemma, here we drop the assumption of differentiability on the boundary of the box. -/ private theorem integral_divergence_of_hasFDerivAt_off_countable_aux₂ (I : Box (Fin (n + 1))) (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : Set ℝⁿ⁺¹) (hs : s.Countable) (Hc : ContinuousOn f (Box.Icc I)) (Hd : ∀ x ∈ Box.Ioo I \ s, HasFDerivAt f (f' x) x) (Hi : IntegrableOn (∑ i, f' · (e i) i) (Box.Icc I)) : (∫ x in Box.Icc I, ∑ i, f' x (e i) i) = ∑ i : Fin (n + 1), ((∫ x in Box.Icc (I.face i), f (i.insertNth (I.upper i) x) i) - ∫ x in Box.Icc (I.face i), f (i.insertNth (I.lower i) x) i) := by /- Choose a monotone sequence `J k` of subboxes that cover the interior of `I` and prove that these boxes satisfy the assumptions of the previous lemma. -/ rcases I.exists_seq_mono_tendsto with ⟨J, hJ_sub, hJl, hJu⟩ have hJ_sub' : ∀ k, Box.Icc (J k) ⊆ Box.Icc I := fun k => (hJ_sub k).trans I.Ioo_subset_Icc have hJ_le : ∀ k, J k ≤ I := fun k => Box.le_iff_Icc.2 (hJ_sub' k) have HcJ : ∀ k, ContinuousOn f (Box.Icc (J k)) := fun k => Hc.mono (hJ_sub' k) have HdJ : ∀ (k), ∀ x ∈ (Box.Icc (J k)) \ s, HasFDerivWithinAt f (f' x) (Box.Icc (J k)) x := fun k x hx => (Hd x ⟨hJ_sub k hx.1, hx.2⟩).hasFDerivWithinAt have HiJ : ∀ k, IntegrableOn (∑ i, f' · (e i) i) (Box.Icc (J k)) volume := fun k => Hi.mono_set (hJ_sub' k) -- Apply the previous lemma to `J k`. have HJ_eq := fun k => integral_divergence_of_hasFDerivWithinAt_off_countable_aux₁ (J k) f f' s hs (HcJ k) (HdJ k) (HiJ k) -- Note that the LHS of `HJ_eq k` tends to the LHS of the goal as `k → ∞`. have hI_tendsto : Tendsto (fun k => ∫ x in Box.Icc (J k), ∑ i, f' x (e i) i) atTop (𝓝 (∫ x in Box.Icc I, ∑ i, f' x (e i) i)) := by simp only [IntegrableOn, ← Measure.restrict_congr_set (Box.Ioo_ae_eq_Icc _)] at Hi ⊢ rw [← Box.iUnion_Ioo_of_tendsto J.monotone hJl hJu] at Hi ⊢ exact tendsto_setIntegral_of_monotone (fun k => (J k).measurableSet_Ioo) (Box.Ioo.comp J).monotone Hi -- Thus it suffices to prove the same about the RHS. refine tendsto_nhds_unique_of_eventuallyEq hI_tendsto ?_ (Eventually.of_forall HJ_eq) clear hI_tendsto rw [tendsto_pi_nhds] at hJl hJu /- We'll need to prove a similar statement about the integrals over the front sides and the integrals over the back sides. In order to avoid repeating ourselves, we formulate a lemma. -/ suffices ∀ (i : Fin (n + 1)) (c : ℕ → ℝ) (d), (∀ k, c k ∈ Icc (I.lower i) (I.upper i)) → Tendsto c atTop (𝓝 d) → Tendsto (fun k => ∫ x in Box.Icc ((J k).face i), f (i.insertNth (c k) x) i) atTop (𝓝 <| ∫ x in Box.Icc (I.face i), f (i.insertNth d x) i) by rw [Box.Icc_eq_pi] at hJ_sub' refine tendsto_finset_sum _ fun i _ => (this _ _ _ ?_ (hJu _)).sub (this _ _ _ ?_ (hJl _)) exacts [fun k => hJ_sub' k (J k).upper_mem_Icc _ trivial, fun k => hJ_sub' k (J k).lower_mem_Icc _ trivial] intro i c d hc hcd /- First we prove that the integrals of the restriction of `f` to `{x | x i = d}` over increasing boxes `((J k).face i).Icc` tend to the desired limit. The proof mostly repeats the one above. -/ have hd : d ∈ Icc (I.lower i) (I.upper i) := isClosed_Icc.mem_of_tendsto hcd (Eventually.of_forall hc) have Hic : ∀ k, IntegrableOn (fun x => f (i.insertNth (c k) x) i) (Box.Icc (I.face i)) := fun k => (Box.continuousOn_face_Icc ((continuous_apply i).comp_continuousOn Hc) (hc k)).integrableOn_Icc have Hid : IntegrableOn (fun x => f (i.insertNth d x) i) (Box.Icc (I.face i)) := (Box.continuousOn_face_Icc ((continuous_apply i).comp_continuousOn Hc) hd).integrableOn_Icc have H : Tendsto (fun k => ∫ x in Box.Icc ((J k).face i), f (i.insertNth d x) i) atTop (𝓝 <| ∫ x in Box.Icc (I.face i), f (i.insertNth d x) i) := by have hIoo : (⋃ k, Box.Ioo ((J k).face i)) = Box.Ioo (I.face i) := Box.iUnion_Ioo_of_tendsto ((Box.monotone_face i).comp J.monotone) (tendsto_pi_nhds.2 fun _ => hJl _) (tendsto_pi_nhds.2 fun _ => hJu _) simp only [IntegrableOn, ← Measure.restrict_congr_set (Box.Ioo_ae_eq_Icc _), ← hIoo] at Hid ⊢ exact tendsto_setIntegral_of_monotone (fun k => ((J k).face i).measurableSet_Ioo) (Box.Ioo.monotone.comp ((Box.monotone_face i).comp J.monotone)) Hid /- Thus it suffices to show that the distance between the integrals of the restrictions of `f` to `{x | x i = c k}` and `{x | x i = d}` over `((J k).face i).Icc` tends to zero as `k → ∞`. Choose `ε > 0`. -/ refine H.congr_dist (Metric.nhds_basis_closedBall.tendsto_right_iff.2 fun ε εpos => ?_) have hvol_pos : ∀ J : Box (Fin n), 0 < ∏ j, (J.upper j - J.lower j) := fun J => prod_pos fun j hj => sub_pos.2 <| J.lower_lt_upper _ /- Choose `δ > 0` such that for any `x y ∈ I.Icc` at distance at most `δ`, the distance between `f x` and `f y` is at most `ε / volume (I.face i).Icc`, then the distance between the integrals is at most `(ε / volume (I.face i).Icc) * volume ((J k).face i).Icc ≤ ε`. -/ rcases Metric.uniformContinuousOn_iff_le.1 (I.isCompact_Icc.uniformContinuousOn_of_continuous Hc) (ε / ∏ j, ((I.face i).upper j - (I.face i).lower j)) (div_pos εpos (hvol_pos (I.face i))) with ⟨δ, δpos, hδ⟩ refine (hcd.eventually (Metric.ball_mem_nhds _ δpos)).mono fun k hk => ?_ have Hsub : Box.Icc ((J k).face i) ⊆ Box.Icc (I.face i) := Box.le_iff_Icc.1 (Box.face_mono (hJ_le _) i) rw [mem_closedBall_zero_iff, Real.norm_eq_abs, abs_of_nonneg dist_nonneg, dist_eq_norm, ← integral_sub (Hid.mono_set Hsub) ((Hic _).mono_set Hsub)] calc ‖∫ x in Box.Icc ((J k).face i), f (i.insertNth d x) i - f (i.insertNth (c k) x) i‖ ≤ (ε / ∏ j, ((I.face i).upper j - (I.face i).lower j)) * (volume (Box.Icc ((J k).face i))).toReal := by refine norm_setIntegral_le_of_norm_le_const (((J k).face i).measure_Icc_lt_top _) fun x hx => ?_ rw [← dist_eq_norm] calc dist (f (i.insertNth d x) i) (f (i.insertNth (c k) x) i) ≤ dist (f (i.insertNth d x)) (f (i.insertNth (c k) x)) := dist_le_pi_dist (f (i.insertNth d x)) (f (i.insertNth (c k) x)) i _ ≤ ε / ∏ j, ((I.face i).upper j - (I.face i).lower j) := hδ _ (I.mapsTo_insertNth_face_Icc hd <| Hsub hx) _ (I.mapsTo_insertNth_face_Icc (hc _) <| Hsub hx) ?_ rw [Fin.dist_insertNth_insertNth, dist_self, dist_comm] exact max_le hk.le δpos.lt.le _ ≤ ε := by rw [Box.Icc_def, Real.volume_Icc_pi_toReal ((J k).face i).lower_le_upper, ← le_div_iff₀ (hvol_pos _)] gcongr exacts [hvol_pos _, fun _ _ ↦ sub_nonneg.2 (Box.lower_le_upper _ _), (hJ_sub' _ (J _).upper_mem_Icc).2 _, (hJ_sub' _ (J _).lower_mem_Icc).1 _] variable (a b : Fin (n + 1) → ℝ) local notation "face " i => Set.Icc (a ∘ Fin.succAbove i) (b ∘ Fin.succAbove i) local notation:max "frontFace " i:arg => Fin.insertNth i (b i) local notation:max "backFace " i:arg => Fin.insertNth i (a i) /-- **Divergence theorem** for Bochner integral. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is continuous on a rectangular box `[a, b] : Set ℝⁿ⁺¹`, `a ≤ b`, is differentiable on its interior with derivative `f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹` and the divergence `fun x ↦ ∑ i, f' x eᵢ i` is integrable on `[a, b]`, where `eᵢ = Pi.single i 1` is the `i`-th basis vector, then its integral is equal to the sum of integrals of `f` over the faces of `[a, b]`, taken with appropriate signs. Moreover, the same is true if the function is not differentiable at countably many points of the interior of `[a, b]`. We represent both faces `x i = a i` and `x i = b i` as the box `face i = [a ∘ Fin.succAbove i, b ∘ Fin.succAbove i]` in `ℝⁿ`, where `Fin.succAbove : Fin n ↪o Fin (n + 1)` is the order embedding with range `{i}ᶜ`. The restrictions of `f : ℝⁿ⁺¹ → Eⁿ⁺¹` to these faces are given by `f ∘ backFace i` and `f ∘ frontFace i`, where `backFace i = Fin.insertNth i (a i)` and `frontFace i = Fin.insertNth i (b i)` are embeddings `ℝⁿ → ℝⁿ⁺¹` that take `y : ℝⁿ` and insert `a i` (resp., `b i`) as `i`-th coordinate. -/ theorem integral_divergence_of_hasFDerivAt_off_countable (hle : a ≤ b) (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : Set ℝⁿ⁺¹) (hs : s.Countable) (Hc : ContinuousOn f (Icc a b)) (Hd : ∀ x ∈ (Set.pi univ fun i => Ioo (a i) (b i)) \ s, HasFDerivAt f (f' x) x) (Hi : IntegrableOn (fun x => ∑ i, f' x (e i) i) (Icc a b)) : (∫ x in Icc a b, ∑ i, f' x (e i) i) = ∑ i : Fin (n + 1), ((∫ x in face i, f (frontFace i x) i) - ∫ x in face i, f (backFace i x) i) := by rcases em (∃ i, a i = b i) with (⟨i, hi⟩ | hne) · -- First we sort out the trivial case `∃ i, a i = b i`. rw [volume_pi, ← setIntegral_congr_set Measure.univ_pi_Ioc_ae_eq_Icc] have hi' : Ioc (a i) (b i) = ∅ := Ioc_eq_empty hi.not_lt have : (pi Set.univ fun j => Ioc (a j) (b j)) = ∅ := univ_pi_eq_empty hi' rw [this, setIntegral_empty, sum_eq_zero] rintro j - rcases eq_or_ne i j with (rfl | hne) · simp [hi] · rcases Fin.exists_succAbove_eq hne with ⟨i, rfl⟩ have : Icc (a ∘ j.succAbove) (b ∘ j.succAbove) =ᵐ[volume] (∅ : Set ℝⁿ) := by rw [ae_eq_empty, Real.volume_Icc_pi, prod_eq_zero (Finset.mem_univ i)] simp [hi] rw [setIntegral_congr_set this, setIntegral_congr_set this, setIntegral_empty, setIntegral_empty, sub_self] · -- In the non-trivial case `∀ i, a i < b i`, we apply a lemma we proved above. have hlt : ∀ i, a i < b i := fun i => (hle i).lt_of_ne fun hi => hne ⟨i, hi⟩ exact integral_divergence_of_hasFDerivAt_off_countable_aux₂ ⟨a, b, hlt⟩ f f' s hs Hc Hd Hi @[deprecated (since := "2025-05-02")] alias integral_divergence_of_hasFDerivWithinAt_off_countable := integral_divergence_of_hasFDerivAt_off_countable /-- **Divergence theorem** for a family of functions `f : Fin (n + 1) → ℝⁿ⁺¹ → E`. See also `MeasureTheory.integral_divergence_of_hasFDerivWithinAt_off_countable'` for a version formulated in terms of a vector-valued function `f : ℝⁿ⁺¹ → Eⁿ⁺¹`. -/ theorem integral_divergence_of_hasFDerivAt_off_countable' (hle : a ≤ b) (f : Fin (n + 1) → ℝⁿ⁺¹ → E) (f' : Fin (n + 1) → ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] E) (s : Set ℝⁿ⁺¹) (hs : s.Countable) (Hc : ∀ i, ContinuousOn (f i) (Icc a b)) (Hd : ∀ x ∈ (pi Set.univ fun i => Ioo (a i) (b i)) \ s, ∀ (i), HasFDerivAt (f i) (f' i x) x) (Hi : IntegrableOn (fun x => ∑ i, f' i x (e i)) (Icc a b)) : (∫ x in Icc a b, ∑ i, f' i x (e i)) = ∑ i : Fin (n + 1), ((∫ x in face i, f i (frontFace i x)) - ∫ x in face i, f i (backFace i x)) := integral_divergence_of_hasFDerivAt_off_countable a b hle (fun x i => f i x) (fun x => ContinuousLinearMap.pi fun i => f' i x) s hs (continuousOn_pi.2 Hc) (fun x hx => hasFDerivAt_pi.2 (Hd x hx)) Hi @[deprecated (since := "2025-05-02")] alias integral_divergence_of_hasFDerivWithinAt_off_countable' := integral_divergence_of_hasFDerivAt_off_countable' end /-- An auxiliary lemma that is used to specialize the general divergence theorem to spaces that do not have the form `Fin n → ℝ`. -/ theorem integral_divergence_of_hasFDerivAt_off_countable_of_equiv {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] [Preorder F] [MeasureSpace F] [BorelSpace F] (eL : F ≃L[ℝ] ℝⁿ⁺¹) (he_ord : ∀ x y, eL x ≤ eL y ↔ x ≤ y) (he_vol : MeasurePreserving eL volume volume) (f : Fin (n + 1) → F → E) (f' : Fin (n + 1) → F → F →L[ℝ] E) (s : Set F) (hs : s.Countable) (a b : F) (hle : a ≤ b) (Hc : ∀ i, ContinuousOn (f i) (Icc a b)) (Hd : ∀ x ∈ interior (Icc a b) \ s, ∀ (i), HasFDerivAt (f i) (f' i x) x) (DF : F → E) (hDF : ∀ x, DF x = ∑ i, f' i x (eL.symm <| e i)) (Hi : IntegrableOn DF (Icc a b)) : ∫ x in Icc a b, DF x = ∑ i : Fin (n + 1), ((∫ x in Icc (eL a ∘ i.succAbove) (eL b ∘ i.succAbove), f i (eL.symm <| i.insertNth (eL b i) x)) - ∫ x in Icc (eL a ∘ i.succAbove) (eL b ∘ i.succAbove), f i (eL.symm <| i.insertNth (eL a i) x)) := have he_emb : MeasurableEmbedding eL := eL.toHomeomorph.measurableEmbedding have hIcc : eL ⁻¹' Icc (eL a) (eL b) = Icc a b := by ext1 x; simp only [Set.mem_preimage, Set.mem_Icc, he_ord] have hIcc' : Icc (eL a) (eL b) = eL.symm ⁻¹' Icc a b := by rw [← hIcc, eL.symm_preimage_preimage] calc ∫ x in Icc a b, DF x = ∫ x in Icc a b, ∑ i, f' i x (eL.symm <| e i) := by simp only [hDF] _ = ∫ x in Icc (eL a) (eL b), ∑ i, f' i (eL.symm x) (eL.symm <| e i) := by rw [← he_vol.setIntegral_preimage_emb he_emb] simp only [hIcc, eL.symm_apply_apply] _ = ∑ i : Fin (n + 1), ((∫ x in Icc (eL a ∘ i.succAbove) (eL b ∘ i.succAbove), f i (eL.symm <| i.insertNth (eL b i) x)) - ∫ x in Icc (eL a ∘ i.succAbove) (eL b ∘ i.succAbove), f i (eL.symm <| i.insertNth (eL a i) x)) := by refine integral_divergence_of_hasFDerivAt_off_countable' (eL a) (eL b) ((he_ord _ _).2 hle) (fun i x => f i (eL.symm x)) (fun i x => f' i (eL.symm x) ∘L (eL.symm : ℝⁿ⁺¹ →L[ℝ] F)) (eL.symm ⁻¹' s) (hs.preimage eL.symm.injective) ?_ ?_ ?_ · exact fun i => (Hc i).comp eL.symm.continuousOn hIcc'.subset · refine fun x hx i => (Hd (eL.symm x) ⟨?_, hx.2⟩ i).comp x eL.symm.hasFDerivAt rw [← hIcc] refine preimage_interior_subset_interior_preimage eL.continuous ?_ simpa only [Set.mem_preimage, eL.apply_symm_apply, ← pi_univ_Icc, interior_pi_set (@finite_univ (Fin _) _), interior_Icc] using hx.1 · rw [← he_vol.integrableOn_comp_preimage he_emb, hIcc] simp [← hDF, Function.comp_def, Hi] @[deprecated (since := "2025-05-02")] alias integral_divergence_of_hasFDerivWithinAt_off_countable_of_equiv := integral_divergence_of_hasFDerivAt_off_countable_of_equiv end open scoped Interval open ContinuousLinearMap (smulRight) local macro:arg t:term:max noWs "¹" : term => `(Fin 1 → $t) local macro:arg t:term:max noWs "²" : term => `(Fin 2 → $t) /-- **Fundamental theorem of calculus, part 2**. This version assumes that `f` is continuous on the interval and is differentiable off a countable set `s`. See also * `intervalIntegral.integral_eq_sub_of_hasDeriv_right_of_le` for a version that only assumes right differentiability of `f`; * `MeasureTheory.integral_eq_of_hasDerivWithinAt_off_countable` for a version that works both for `a ≤ b` and `b ≤ a` at the expense of using unordered intervals instead of `Set.Icc`. -/ theorem integral_eq_of_hasDerivAt_off_countable_of_le [CompleteSpace E] (f f' : ℝ → E) {a b : ℝ} (hle : a ≤ b) {s : Set ℝ} (hs : s.Countable) (Hc : ContinuousOn f (Icc a b)) (Hd : ∀ x ∈ Ioo a b \ s, HasDerivAt f (f' x) x) (Hi : IntervalIntegrable f' volume a b) : ∫ x in a..b, f' x = f b - f a := by set e : ℝ ≃L[ℝ] ℝ¹ := (ContinuousLinearEquiv.funUnique (Fin 1) ℝ ℝ).symm have e_symm : ∀ x, e.symm x = x 0 := fun x => rfl set F' : ℝ → ℝ →L[ℝ] E := fun x => smulRight (1 : ℝ →L[ℝ] ℝ) (f' x) have hF' : ∀ x y, F' x y = y • f' x := fun x y => rfl calc ∫ x in a..b, f' x = ∫ x in Icc a b, f' x := by rw [intervalIntegral.integral_of_le hle, setIntegral_congr_set Ioc_ae_eq_Icc] _ = ∑ i : Fin 1, ((∫ x in Icc (e a ∘ i.succAbove) (e b ∘ i.succAbove), f (e.symm <| i.insertNth (e b i) x)) - ∫ x in Icc (e a ∘ i.succAbove) (e b ∘ i.succAbove), f (e.symm <| i.insertNth (e a i) x)) := by simp only [← interior_Icc] at Hd refine integral_divergence_of_hasFDerivAt_off_countable_of_equiv e ?_ ?_ (fun _ => f) (fun _ => F') s hs a b hle (fun _ => Hc) (fun x hx _ => Hd x hx) _ ?_ ?_ · exact fun x y => (OrderIso.funUnique (Fin 1) ℝ).symm.le_iff_le · exact (volume_preserving_funUnique (Fin 1) ℝ).symm _ · intro x; rw [Fin.sum_univ_one, hF', e_symm, Pi.single_eq_same, one_smul] · rw [intervalIntegrable_iff_integrableOn_Ioc_of_le hle] at Hi exact Hi.congr_set_ae Ioc_ae_eq_Icc.symm _ = f b - f a := by simp [e, Subsingleton.elim (const (Fin 0) _) isEmptyElim, volume_pi, Measure.pi_of_empty fun _ : Fin 0 ↦ _] @[deprecated (since := "2025-05-02")] alias integral_eq_of_hasDerivWithinAt_off_countable_of_le := integral_eq_of_hasDerivAt_off_countable_of_le /-- **Fundamental theorem of calculus, part 2**. This version assumes that `f` is continuous on the interval and is differentiable off a countable set `s`. See also `intervalIntegral.integral_eq_sub_of_hasDeriv_right` for a version that only assumes right differentiability of `f`. -/ theorem integral_eq_of_hasDerivAt_off_countable [CompleteSpace E] (f f' : ℝ → E) {a b : ℝ} {s : Set ℝ} (hs : s.Countable) (Hc : ContinuousOn f [[a, b]]) (Hd : ∀ x ∈ Ioo (min a b) (max a b) \ s, HasDerivAt f (f' x) x) (Hi : IntervalIntegrable f' volume a b) : ∫ x in a..b, f' x = f b - f a := by rcases le_total a b with hab | hab · simp only [uIcc_of_le hab, min_eq_left hab, max_eq_right hab] at * exact integral_eq_of_hasDerivAt_off_countable_of_le f f' hab hs Hc Hd Hi · simp only [uIcc_of_ge hab, min_eq_right hab, max_eq_left hab] at * rw [intervalIntegral.integral_symm, neg_eq_iff_eq_neg, neg_sub] exact integral_eq_of_hasDerivAt_off_countable_of_le f f' hab hs Hc Hd Hi.symm @[deprecated (since := "2025-05-02")] alias integral_eq_of_hasDerivWithinAt_off_countable := integral_eq_of_hasDerivAt_off_countable /-- **Divergence theorem** for functions on the plane along rectangles. It is formulated in terms of two functions `f g : ℝ × ℝ → E` and an integral over `Icc a b = [a.1, b.1] × [a.2, b.2]`, where `a b : ℝ × ℝ`, `a ≤ b`. When thinking of `f` and `g` as the two coordinates of a single function `F : ℝ × ℝ → E × E` and when `E = ℝ`, this is the usual statement that the integral of the divergence of `F` inside the rectangle equals the integral of the normal derivative of `F` along the boundary. See also `MeasureTheory.integral2_divergence_prod_of_hasFDerivAt_off_countable` for a version that does not assume `a ≤ b` and uses iterated interval integral instead of the integral over `Icc a b`. -/ theorem integral_divergence_prod_Icc_of_hasFDerivAt_off_countable_of_le (f g : ℝ × ℝ → E) (f' g' : ℝ × ℝ → ℝ × ℝ →L[ℝ] E) (a b : ℝ × ℝ) (hle : a ≤ b) (s : Set (ℝ × ℝ)) (hs : s.Countable) (Hcf : ContinuousOn f (Icc a b)) (Hcg : ContinuousOn g (Icc a b)) (Hdf : ∀ x ∈ Ioo a.1 b.1 ×ˢ Ioo a.2 b.2 \ s, HasFDerivAt f (f' x) x) (Hdg : ∀ x ∈ Ioo a.1 b.1 ×ˢ Ioo a.2 b.2 \ s, HasFDerivAt g (g' x) x) (Hi : IntegrableOn (fun x => f' x (1, 0) + g' x (0, 1)) (Icc a b)) : (∫ x in Icc a b, f' x (1, 0) + g' x (0, 1)) = (((∫ x in a.1..b.1, g (x, b.2)) - ∫ x in a.1..b.1, g (x, a.2)) + ∫ y in a.2..b.2, f (b.1, y)) - ∫ y in a.2..b.2, f (a.1, y) := let e : (ℝ × ℝ) ≃L[ℝ] ℝ² := (ContinuousLinearEquiv.finTwoArrow ℝ ℝ).symm calc (∫ x in Icc a b, f' x (1, 0) + g' x (0, 1)) = ∑ i : Fin 2, ((∫ x in Icc (e a ∘ i.succAbove) (e b ∘ i.succAbove), ![f, g] i (e.symm <| i.insertNth (e b i) x)) - ∫ x in Icc (e a ∘ i.succAbove) (e b ∘ i.succAbove), ![f, g] i (e.symm <| i.insertNth (e a i) x)) := by refine integral_divergence_of_hasFDerivAt_off_countable_of_equiv e ?_ ?_ ![f, g] ![f', g'] s hs a b hle ?_ (fun x hx => ?_) _ ?_ Hi · exact fun x y => (OrderIso.finTwoArrowIso ℝ).symm.le_iff_le · exact (volume_preserving_finTwoArrow ℝ).symm _ · exact Fin.forall_fin_two.2 ⟨Hcf, Hcg⟩ · rw [Icc_prod_eq, interior_prod_eq, interior_Icc, interior_Icc] at hx exact Fin.forall_fin_two.2 ⟨Hdf x hx, Hdg x hx⟩ · intro x; rw [Fin.sum_univ_two]; rfl _ = ((∫ y in Icc a.2 b.2, f (b.1, y)) - ∫ y in Icc a.2 b.2, f (a.1, y)) + ((∫ x in Icc a.1 b.1, g (x, b.2)) - ∫ x in Icc a.1 b.1, g (x, a.2)) := by have : ∀ (a b : ℝ¹) (f : ℝ¹ → E), ∫ x in Icc a b, f x = ∫ x in Icc (a 0) (b 0), f fun _ => x := fun a b f ↦ by convert (((volume_preserving_funUnique (Fin 1) ℝ).symm _).setIntegral_preimage_emb (MeasurableEquiv.measurableEmbedding _) f _).symm exact ((OrderIso.funUnique (Fin 1) ℝ).symm.preimage_Icc a b).symm simp only [Fin.sum_univ_two, this] rfl _ = (((∫ x in a.1..b.1, g (x, b.2)) - ∫ x in a.1..b.1, g (x, a.2)) + ∫ y in a.2..b.2, f (b.1, y)) - ∫ y in a.2..b.2, f (a.1, y) := by simp only [intervalIntegral.integral_of_le hle.1, intervalIntegral.integral_of_le hle.2, setIntegral_congr_set (Ioc_ae_eq_Icc (α := ℝ) (μ := volume))] abel @[deprecated (since := "2025-05-02")] alias integral_divergence_prod_Icc_of_hasFDerivWithinAt_off_countable_of_le := integral_divergence_prod_Icc_of_hasFDerivAt_off_countable_of_le /-- **Divergence theorem** for functions on the plane along rectangles. It is formulated in terms of two functions `f g : ℝ × ℝ → E` and an integral over `Icc a b = [a.1, b.1] × [a.2, b.2]`, where `a b : ℝ × ℝ`, `a ≤ b`. When thinking of `f` and `g` as the two coordinates of a single function `F : ℝ × ℝ → E × E` and when `E = ℝ`, this is the usual statement that the integral of the divergence of `F` inside the rectangle equals the integral of the normal derivative of `F` along the boundary. See also `MeasureTheory.integral2_divergence_prod_of_hasFDerivAt` for a version that does not assume `a ≤ b` and uses iterated interval integral instead of the integral over `Icc a b`. See also `integral_divergence_prod_Icc_of_hasFDerivAt_off_countable_of_le` for a version that assumes differentiability out of a countable set. -/ theorem integral_divergence_prod_Icc_of_hasFDerivAt_of_le (f g : ℝ × ℝ → E) (f' g' : ℝ × ℝ → ℝ × ℝ →L[ℝ] E) (a b : ℝ × ℝ) (hle : a ≤ b) (Hcf : ContinuousOn f (Icc a b)) (Hcg : ContinuousOn g (Icc a b)) (Hdf : ∀ x ∈ Ioo a.1 b.1 ×ˢ Ioo a.2 b.2, HasFDerivAt f (f' x) x) (Hdg : ∀ x ∈ Ioo a.1 b.1 ×ˢ Ioo a.2 b.2, HasFDerivAt g (g' x) x) (Hi : IntegrableOn (fun x => f' x (1, 0) + g' x (0, 1)) (Icc a b)) : (∫ x in Icc a b, f' x (1, 0) + g' x (0, 1)) = (((∫ x in a.1..b.1, g (x, b.2)) - ∫ x in a.1..b.1, g (x, a.2)) + ∫ y in a.2..b.2, f (b.1, y)) - ∫ y in a.2..b.2, f (a.1, y) := integral_divergence_prod_Icc_of_hasFDerivAt_off_countable_of_le f g f' g' a b hle ∅ (by simp) Hcf Hcg (by simpa only [diff_empty]) (by simpa only [diff_empty]) Hi /-- **Divergence theorem** for functions on the plane. It is formulated in terms of two functions `f g : ℝ × ℝ → E` and iterated integral `∫ x in a₁..b₁, ∫ y in a₂..b₂, _`, where `a₁ a₂ b₁ b₂ : ℝ`. When thinking of `f` and `g` as the two coordinates of a single function `F : ℝ × ℝ → E × E` and when `E = ℝ`, this is the usual statement that the integral of the divergence of `F` inside the rectangle with vertices `(aᵢ, bⱼ)`, `i, j =1,2`, equals the integral of the normal derivative of `F` along the boundary. See also `MeasureTheory.integral_divergence_prod_Icc_of_hasFDerivAt_off_countable_of_le` for a version that uses an integral over `Icc a b`, where `a b : ℝ × ℝ`, `a ≤ b`. -/ theorem integral2_divergence_prod_of_hasFDerivAt_off_countable (f g : ℝ × ℝ → E) (f' g' : ℝ × ℝ → ℝ × ℝ →L[ℝ] E) (a₁ a₂ b₁ b₂ : ℝ) (s : Set (ℝ × ℝ)) (hs : s.Countable) (Hcf : ContinuousOn f ([[a₁, b₁]] ×ˢ [[a₂, b₂]])) (Hcg : ContinuousOn g ([[a₁, b₁]] ×ˢ [[a₂, b₂]])) (Hdf : ∀ x ∈ Ioo (min a₁ b₁) (max a₁ b₁) ×ˢ Ioo (min a₂ b₂) (max a₂ b₂) \ s, HasFDerivAt f (f' x) x) (Hdg : ∀ x ∈ Ioo (min a₁ b₁) (max a₁ b₁) ×ˢ Ioo (min a₂ b₂) (max a₂ b₂) \ s, HasFDerivAt g (g' x) x) (Hi : IntegrableOn (fun x => f' x (1, 0) + g' x (0, 1)) ([[a₁, b₁]] ×ˢ [[a₂, b₂]])) : (∫ x in a₁..b₁, ∫ y in a₂..b₂, f' (x, y) (1, 0) + g' (x, y) (0, 1)) = (((∫ x in a₁..b₁, g (x, b₂)) - ∫ x in a₁..b₁, g (x, a₂)) + ∫ y in a₂..b₂, f (b₁, y)) - ∫ y in a₂..b₂, f (a₁, y) := by wlog h₁ : a₁ ≤ b₁ generalizing a₁ b₁ · specialize this b₁ a₁ rw [uIcc_comm b₁ a₁, min_comm b₁ a₁, max_comm b₁ a₁] at this simp only [intervalIntegral.integral_symm b₁ a₁] refine (congr_arg Neg.neg (this Hcf Hcg Hdf Hdg Hi (le_of_not_ge h₁))).trans ?_; abel wlog h₂ : a₂ ≤ b₂ generalizing a₂ b₂ · specialize this b₂ a₂ rw [uIcc_comm b₂ a₂, min_comm b₂ a₂, max_comm b₂ a₂] at this simp only [intervalIntegral.integral_symm b₂ a₂, intervalIntegral.integral_neg] refine (congr_arg Neg.neg (this Hcf Hcg Hdf Hdg Hi (le_of_not_ge h₂))).trans ?_; abel simp only [uIcc_of_le h₁, uIcc_of_le h₂, min_eq_left, max_eq_right, h₁, h₂] at Hcf Hcg Hdf Hdg Hi calc (∫ x in a₁..b₁, ∫ y in a₂..b₂, f' (x, y) (1, 0) + g' (x, y) (0, 1)) = ∫ x in Icc a₁ b₁, ∫ y in Icc a₂ b₂, f' (x, y) (1, 0) + g' (x, y) (0, 1) := by simp only [intervalIntegral.integral_of_le, h₁, h₂, setIntegral_congr_set (Ioc_ae_eq_Icc (α := ℝ) (μ := volume))] _ = ∫ x in Icc a₁ b₁ ×ˢ Icc a₂ b₂, f' x (1, 0) + g' x (0, 1) := (setIntegral_prod _ Hi).symm _ = (((∫ x in a₁..b₁, g (x, b₂)) - ∫ x in a₁..b₁, g (x, a₂)) + ∫ y in a₂..b₂, f (b₁, y)) - ∫ y in a₂..b₂, f (a₁, y) := by rw [Icc_prod_Icc] at * apply integral_divergence_prod_Icc_of_hasFDerivAt_off_countable_of_le f g f' g' (a₁, a₂) (b₁, b₂) ⟨h₁, h₂⟩ s <;> assumption @[deprecated (since := "2025-05-02")] alias integral2_divergence_prod_of_hasFDerivWithinAt_off_countable := integral2_divergence_prod_of_hasFDerivAt_off_countable /-- **Divergence theorem** for functions on the plane. It is formulated in terms of two functions `f g : ℝ × ℝ → E` and iterated integral `∫ x in a₁..b₁, ∫ y in a₂..b₂, _`, where `a₁ a₂ b₁ b₂ : ℝ`. When thinking of `f` and `g` as the two coordinates of a single function `F : ℝ × ℝ → E × E` and when `E = ℝ`, this is the usual statement that the integral of the divergence of `F` inside the rectangle with vertices `(aᵢ, bⱼ)`, `i, j = 1, 2`, equals the integral of the normal derivative of `F` along the boundary. See also `MeasureTheory.integral_divergence_prod_Icc_of_hasFDerivAt_of_le` for a version that uses an integral over `Icc a b`, where `a b : ℝ × ℝ`, `a ≤ b`. See also `integral2_divergence_prod_of_hasFDerivAt_off_countable` for a version that assumes differentiability outside of a countable set. -/ theorem integral2_divergence_prod_of_hasFDerivAt (f g : ℝ × ℝ → E) (f' g' : ℝ × ℝ → ℝ × ℝ →L[ℝ] E) (a₁ a₂ b₁ b₂ : ℝ) (Hcf : ContinuousOn f ([[a₁, b₁]] ×ˢ [[a₂, b₂]])) (Hcg : ContinuousOn g ([[a₁, b₁]] ×ˢ [[a₂, b₂]])) (Hdf : ∀ x ∈ Ioo (min a₁ b₁) (max a₁ b₁) ×ˢ Ioo (min a₂ b₂) (max a₂ b₂), HasFDerivAt f (f' x) x) (Hdg : ∀ x ∈ Ioo (min a₁ b₁) (max a₁ b₁) ×ˢ Ioo (min a₂ b₂) (max a₂ b₂), HasFDerivAt g (g' x) x) (Hi : IntegrableOn (fun x => f' x (1, 0) + g' x (0, 1)) ([[a₁, b₁]] ×ˢ [[a₂, b₂]])) : (∫ x in a₁..b₁, ∫ y in a₂..b₂, f' (x, y) (1, 0) + g' (x, y) (0, 1)) = (((∫ x in a₁..b₁, g (x, b₂)) - ∫ x in a₁..b₁, g (x, a₂)) + ∫ y in a₂..b₂, f (b₁, y)) - ∫ y in a₂..b₂, f (a₁, y) := integral2_divergence_prod_of_hasFDerivAt_off_countable f g f' g' a₁ a₂ b₁ b₂ ∅ countable_empty Hcf Hcg (fun x hx ↦ Hdf x hx.1) (fun x hx ↦ Hdg x hx.1) Hi end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue/MeasurePreserving.lean
import Mathlib.Dynamics.Ergodic.MeasurePreserving import Mathlib.MeasureTheory.Integral.Lebesgue.Basic deprecated_module (since := "2025-04-15")
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue/Add.lean
import Mathlib.MeasureTheory.Constructions.BorelSpace.Real import Mathlib.MeasureTheory.Integral.Lebesgue.Basic /-! # Monotone convergence theorem and addition of Lebesgue integrals The monotone convergence theorem (aka Beppo Levi lemma) states that the Lebesgue integral and supremum can be swapped for a pointwise monotone sequence of functions. This file first proves several variants of this theorem, then uses it to show that the Lebesgue integral is additive (assuming one of the functions is at least `AEMeasurable`) and respects multiplication by a constant. -/ namespace MeasureTheory open Set Filter ENNReal Topology NNReal SimpleFunc variable {α β : Type*} {m : MeasurableSpace α} {μ : Measure α} local infixr:25 " →ₛ " => SimpleFunc section MonotoneConvergence /-- **Monotone convergence theorem**, version with `Measurable` functions. -/ theorem lintegral_iSup {f : ℕ → α → ℝ≥0∞} (hf : ∀ n, Measurable (f n)) (h_mono : Monotone f) : ∫⁻ a, ⨆ n, f n a ∂μ = ⨆ n, ∫⁻ a, f n a ∂μ := by set c : ℝ≥0 → ℝ≥0∞ := (↑) set F := fun a : α => ⨆ n, f n a refine le_antisymm ?_ (iSup_lintegral_le _) rw [lintegral_eq_nnreal] refine iSup_le fun s => iSup_le fun hsf => ?_ refine ENNReal.le_of_forall_lt_one_mul_le fun a ha => ?_ rcases ENNReal.lt_iff_exists_coe.1 ha with ⟨r, rfl, _⟩ have ha : r < 1 := ENNReal.coe_lt_coe.1 ha let rs := s.map fun a => r * a have eq_rs : rs.map c = (const α r : α →ₛ ℝ≥0∞) * map c s := rfl have eq : ∀ p, rs.map c ⁻¹' {p} = ⋃ n, rs.map c ⁻¹' {p} ∩ { a | p ≤ f n a } := by intro p rw [← inter_iUnion]; nth_rw 1 [← inter_univ (map c rs ⁻¹' {p})] refine Set.ext fun x => and_congr_right fun hx => (iff_of_eq (true_iff _)).2 ?_ by_cases p_eq : p = 0 · simp [p_eq] simp only [coe_map, mem_preimage, Function.comp_apply, mem_singleton_iff] at hx subst hx have : r * s x ≠ 0 := by rwa [Ne, ← ENNReal.coe_eq_zero] have : s x ≠ 0 := right_ne_zero_of_mul this have : (rs.map c) x < ⨆ n : ℕ, f n x := by refine lt_of_lt_of_le (ENNReal.coe_lt_coe.2 ?_) (hsf x) suffices r * s x < 1 * s x by simpa exact mul_lt_mul_of_pos_right ha (pos_iff_ne_zero.2 this) rcases lt_iSup_iff.1 this with ⟨i, hi⟩ exact mem_iUnion.2 ⟨i, le_of_lt hi⟩ have mono : ∀ r : ℝ≥0∞, Monotone fun n => rs.map c ⁻¹' {r} ∩ { a | r ≤ f n a } := by intro r i j h refine inter_subset_inter_right _ ?_ simp_rw [subset_def, mem_setOf] intro x hx exact le_trans hx (h_mono h x) have h_meas : ∀ n, MeasurableSet {a : α | map c rs a ≤ f n a} := fun n => measurableSet_le (SimpleFunc.measurable _) (hf n) calc (r : ℝ≥0∞) * (s.map c).lintegral μ = ∑ r ∈ (rs.map c).range, r * μ (rs.map c ⁻¹' {r}) := by rw [← const_mul_lintegral, eq_rs, SimpleFunc.lintegral] _ = ∑ r ∈ (rs.map c).range, r * μ (⋃ n, rs.map c ⁻¹' {r} ∩ { a | r ≤ f n a }) := by simp only [(eq _).symm] _ = ∑ r ∈ (rs.map c).range, ⨆ n, r * μ (rs.map c ⁻¹' {r} ∩ { a | r ≤ f n a }) := Finset.sum_congr rfl fun x _ => by rw [(mono x).measure_iUnion, ENNReal.mul_iSup] _ = ⨆ n, ∑ r ∈ (rs.map c).range, r * μ (rs.map c ⁻¹' {r} ∩ { a | r ≤ f n a }) := by refine ENNReal.finsetSum_iSup_of_monotone fun p i j h ↦ ?_ gcongr _ * μ ?_ exact mono p h _ ≤ ⨆ n : ℕ, ((rs.map c).restrict { a | (rs.map c) a ≤ f n a }).lintegral μ := by gcongr with n rw [restrict_lintegral _ (h_meas n)] refine le_of_eq (Finset.sum_congr rfl fun r _ => ?_) congr 2 with a refine and_congr_right ?_ simp +contextual _ ≤ ⨆ n, ∫⁻ a, f n a ∂μ := by simp only [← SimpleFunc.lintegral_eq_lintegral] gcongr with n a simp only [map_apply] at h_meas simp only [coe_map, restrict_apply _ (h_meas _), (· ∘ ·)] exact indicator_apply_le id /-- **Monotone convergence theorem**, version with `AEMeasurable` functions. -/ theorem lintegral_iSup' {f : ℕ → α → ℝ≥0∞} (hf : ∀ n, AEMeasurable (f n) μ) (h_mono : ∀ᵐ x ∂μ, Monotone fun n => f n x) : ∫⁻ a, ⨆ n, f n a ∂μ = ⨆ n, ∫⁻ a, f n a ∂μ := by simp_rw [← iSup_apply] let p : α → (ℕ → ℝ≥0∞) → Prop := fun _ f' => Monotone f' have hp : ∀ᵐ x ∂μ, p x fun i => f i x := h_mono have h_ae_seq_mono : Monotone (aeSeq hf p) := by intro n m hnm x by_cases hx : x ∈ aeSeqSet hf p · exact aeSeq.prop_of_mem_aeSeqSet hf hx hnm · simp only [aeSeq, hx, if_false, le_rfl] rw [lintegral_congr_ae (aeSeq.iSup hf hp).symm] simp_rw [iSup_apply] rw [lintegral_iSup (aeSeq.measurable hf p) h_ae_seq_mono] congr with n exact lintegral_congr_ae (aeSeq.aeSeq_n_eq_fun_n_ae hf hp n) /-- **Monotone convergence theorem** expressed with limits. -/ theorem lintegral_tendsto_of_tendsto_of_monotone {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} (hf : ∀ n, AEMeasurable (f n) μ) (h_mono : ∀ᵐ x ∂μ, Monotone fun n => f n x) (h_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 <| F x)) : Tendsto (fun n => ∫⁻ x, f n x ∂μ) atTop (𝓝 <| ∫⁻ x, F x ∂μ) := by have : Monotone fun n => ∫⁻ x, f n x ∂μ := fun i j hij => lintegral_mono_ae (h_mono.mono fun x hx => hx hij) suffices key : ∫⁻ x, F x ∂μ = ⨆ n, ∫⁻ x, f n x ∂μ by rw [key] exact tendsto_atTop_iSup this rw [← lintegral_iSup' hf h_mono] refine lintegral_congr_ae ?_ filter_upwards [h_mono, h_tendsto] with _ hx_mono hx_tendsto using tendsto_nhds_unique hx_tendsto (tendsto_atTop_iSup hx_mono) /-- Weaker version of the **monotone convergence theorem**. -/ theorem lintegral_iSup_ae {f : ℕ → α → ℝ≥0∞} (hf : ∀ n, Measurable (f n)) (h_mono : ∀ n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) : ∫⁻ a, ⨆ n, f n a ∂μ = ⨆ n, ∫⁻ a, f n a ∂μ := by classical let ⟨s, hs⟩ := exists_measurable_superset_of_null (ae_iff.1 (ae_all_iff.2 h_mono)) let g n a := if a ∈ s then 0 else f n a have g_eq_f : ∀ᵐ a ∂μ, ∀ n, g n a = f n a := (measure_eq_zero_iff_ae_notMem.1 hs.2.2).mono fun a ha n => if_neg ha calc ∫⁻ a, ⨆ n, f n a ∂μ = ∫⁻ a, ⨆ n, g n a ∂μ := lintegral_congr_ae <| g_eq_f.mono fun a ha => by simp only [ha] _ = ⨆ n, ∫⁻ a, g n a ∂μ := (lintegral_iSup (fun n => measurable_const.piecewise hs.2.1 (hf n)) (monotone_nat_of_le_succ fun n a => ?_)) _ = ⨆ n, ∫⁻ a, f n a ∂μ := by simp only [lintegral_congr_ae (g_eq_f.mono fun _a ha => ha _)] simp only [g] split_ifs with h · rfl · have := Set.notMem_subset hs.1 h simp only [not_forall, not_le, mem_setOf_eq, not_exists, not_lt] at this exact this n open Encodable in /-- **Monotone convergence theorem** for a supremum over a directed family and indexed by a countable type. -/ theorem lintegral_iSup_directed_of_measurable [Countable β] {f : β → α → ℝ≥0∞} (hf : ∀ b, Measurable (f b)) (h_directed : Directed (· ≤ ·) f) : ∫⁻ a, ⨆ b, f b a ∂μ = ⨆ b, ∫⁻ a, f b a ∂μ := by cases nonempty_encodable β cases isEmpty_or_nonempty β · simp inhabit β have : ∀ a, ⨆ b, f b a = ⨆ n, f (h_directed.sequence f n) a := by intro a refine le_antisymm (iSup_le fun b => ?_) (iSup_le fun n => le_iSup (fun n => f n a) _) exact le_iSup_of_le (encode b + 1) (h_directed.le_sequence b a) calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ := by simp only [this] _ = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ := (lintegral_iSup (fun n => hf _) h_directed.sequence_mono) _ = ⨆ b, ∫⁻ a, f b a ∂μ := by refine le_antisymm (iSup_le fun n => ?_) (iSup_le fun b => ?_) · exact le_iSup (fun b => ∫⁻ a, f b a ∂μ) _ · exact le_iSup_of_le (encode b + 1) (lintegral_mono <| h_directed.le_sequence b) /-- **Monotone convergence theorem** for a supremum over a directed family and indexed by a countable type. -/ theorem lintegral_iSup_directed [Countable β] {f : β → α → ℝ≥0∞} (hf : ∀ b, AEMeasurable (f b) μ) (h_directed : Directed (· ≤ ·) f) : ∫⁻ a, ⨆ b, f b a ∂μ = ⨆ b, ∫⁻ a, f b a ∂μ := by simp_rw [← iSup_apply] let p : α → (β → ENNReal) → Prop := fun x f' => Directed LE.le f' have hp : ∀ᵐ x ∂μ, p x fun i => f i x := by filter_upwards [] with x i j obtain ⟨z, hz₁, hz₂⟩ := h_directed i j exact ⟨z, hz₁ x, hz₂ x⟩ have h_ae_seq_directed : Directed LE.le (aeSeq hf p) := by intro b₁ b₂ obtain ⟨z, hz₁, hz₂⟩ := h_directed b₁ b₂ refine ⟨z, ?_, ?_⟩ <;> · intro x by_cases hx : x ∈ aeSeqSet hf p · repeat rw [aeSeq.aeSeq_eq_fun_of_mem_aeSeqSet hf hx] apply_rules [hz₁, hz₂] · simp only [aeSeq, hx, if_false] exact le_rfl convert lintegral_iSup_directed_of_measurable (aeSeq.measurable hf p) h_ae_seq_directed using 1 · simp_rw [← iSup_apply] rw [lintegral_congr_ae (aeSeq.iSup hf hp).symm] · congr 1 ext1 b rw [lintegral_congr_ae] apply EventuallyEq.symm exact aeSeq.aeSeq_n_eq_fun_n_ae hf hp _ /-- **Fatou's lemma**, version with `AEMeasurable` functions. -/ theorem lintegral_liminf_le' {f : ℕ → α → ℝ≥0∞} (h_meas : ∀ n, AEMeasurable (f n) μ) : ∫⁻ a, liminf (fun n => f n a) atTop ∂μ ≤ liminf (fun n => ∫⁻ a, f n a ∂μ) atTop := calc ∫⁻ a, liminf (fun n => f n a) atTop ∂μ = ∫⁻ a, ⨆ n : ℕ, ⨅ i ≥ n, f i a ∂μ := by simp only [liminf_eq_iSup_iInf_of_nat] _ = ⨆ n : ℕ, ∫⁻ a, ⨅ i ≥ n, f i a ∂μ := (lintegral_iSup' (fun _ => .biInf _ (to_countable _) (fun i _ ↦ h_meas i)) (ae_of_all μ fun _ _ _ hnm => iInf_le_iInf_of_subset fun _ hi => le_trans hnm hi)) _ ≤ ⨆ n : ℕ, ⨅ i ≥ n, ∫⁻ a, f i a ∂μ := iSup_mono fun _ => le_iInf₂_lintegral _ _ = atTop.liminf fun n => ∫⁻ a, f n a ∂μ := Filter.liminf_eq_iSup_iInf_of_nat.symm /-- **Fatou's lemma**, version with `Measurable` functions. -/ theorem lintegral_liminf_le {f : ℕ → α → ℝ≥0∞} (h_meas : ∀ n, Measurable (f n)) : ∫⁻ a, liminf (fun n => f n a) atTop ∂μ ≤ liminf (fun n => ∫⁻ a, f n a ∂μ) atTop := lintegral_liminf_le' fun n => (h_meas n).aemeasurable end MonotoneConvergence section Add theorem lintegral_eq_iSup_eapprox_lintegral {f : α → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a, f a ∂μ = ⨆ n, (eapprox f n).lintegral μ := calc ∫⁻ a, f a ∂μ = ∫⁻ a, ⨆ n, (eapprox f n : α → ℝ≥0∞) a ∂μ := by congr; ext a; rw [iSup_eapprox_apply hf] _ = ⨆ n, ∫⁻ a, (eapprox f n : α → ℝ≥0∞) a ∂μ := by apply lintegral_iSup · fun_prop · intro i j h exact monotone_eapprox f h _ = ⨆ n, (eapprox f n).lintegral μ := by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral] lemma lintegral_eapprox_le_lintegral {f : α → ℝ≥0∞} (hf : Measurable f) (n : ℕ) : (eapprox f n).lintegral μ ≤ ∫⁻ x, f x ∂μ := by rw [lintegral_eq_iSup_eapprox_lintegral hf] exact le_iSup (fun n ↦ (eapprox f n).lintegral μ) n lemma measure_support_eapprox_lt_top {f : α → ℝ≥0∞} (hf_meas : Measurable f) (hf : ∫⁻ x, f x ∂μ ≠ ∞) (n : ℕ) : μ (Function.support (eapprox f n)) < ∞ := measure_support_lt_top_of_lintegral_ne_top <| ((lintegral_eapprox_le_lintegral hf_meas n).trans_lt hf.lt_top).ne /-- The sum of the lower Lebesgue integrals of two functions is less than or equal to the integral of their sum. The other inequality needs one of these functions to be (a.e.-)measurable. -/ theorem le_lintegral_add (f g : α → ℝ≥0∞) : ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ ≤ ∫⁻ a, f a + g a ∂μ := by simp only [lintegral] refine ENNReal.biSup_add_biSup_le' (p := fun h : α →ₛ ℝ≥0∞ => h ≤ f) (q := fun h : α →ₛ ℝ≥0∞ => h ≤ g) ⟨0, zero_le f⟩ ⟨0, zero_le g⟩ fun f' hf' g' hg' => ?_ exact le_iSup₂_of_le (f' + g') (add_le_add hf' hg') (add_lintegral _ _).ge -- Use stronger lemmas `lintegral_add_left`/`lintegral_add_right` instead theorem lintegral_add_aux {f g : α → ℝ≥0∞} (hf : Measurable f) (hg : Measurable g) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := calc ∫⁻ a, f a + g a ∂μ = ∫⁻ a, (⨆ n, (eapprox f n : α → ℝ≥0∞) a) + ⨆ n, (eapprox g n : α → ℝ≥0∞) a ∂μ := by simp only [iSup_eapprox_apply, hf, hg] _ = ∫⁻ a, ⨆ n, (eapprox f n + eapprox g n : α → ℝ≥0∞) a ∂μ := by congr; funext a rw [ENNReal.iSup_add_iSup_of_monotone] · simp only [Pi.add_apply] · intro i j h exact monotone_eapprox _ h a · intro i j h exact monotone_eapprox _ h a _ = ⨆ n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ := by rw [lintegral_iSup] · congr funext n rw [← SimpleFunc.add_lintegral, ← SimpleFunc.lintegral_eq_lintegral] simp only [Pi.add_apply, SimpleFunc.coe_add] · fun_prop · intro i j h a dsimp gcongr <;> exact monotone_eapprox _ h _ _ = (⨆ n, (eapprox f n).lintegral μ) + ⨆ n, (eapprox g n).lintegral μ := by refine (ENNReal.iSup_add_iSup_of_monotone ?_ ?_).symm <;> · intro i j h exact SimpleFunc.lintegral_mono (monotone_eapprox _ h) le_rfl _ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := by rw [lintegral_eq_iSup_eapprox_lintegral hf, lintegral_eq_iSup_eapprox_lintegral hg] /-- If `f g : α → ℝ≥0∞` are two functions and one of them is (a.e.) measurable, then the Lebesgue integral of `f + g` equals the sum of integrals. This lemma assumes that `f` is integrable, see also `MeasureTheory.lintegral_add_right` and primed versions of these lemmas. -/ @[simp] theorem lintegral_add_left {f : α → ℝ≥0∞} (hf : Measurable f) (g : α → ℝ≥0∞) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := by refine le_antisymm ?_ (le_lintegral_add _ _) rcases exists_measurable_le_lintegral_eq μ fun a => f a + g a with ⟨φ, hφm, hφ_le, hφ_eq⟩ calc ∫⁻ a, f a + g a ∂μ = ∫⁻ a, φ a ∂μ := hφ_eq _ ≤ ∫⁻ a, f a + (φ a - f a) ∂μ := lintegral_mono fun a => le_add_tsub _ = ∫⁻ a, f a ∂μ + ∫⁻ a, φ a - f a ∂μ := lintegral_add_aux hf (hφm.sub hf) _ ≤ ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := by gcongr with a; exact tsub_le_iff_left.2 <| hφ_le _ theorem lintegral_add_left' {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) (g : α → ℝ≥0∞) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := by rw [lintegral_congr_ae hf.ae_eq_mk, ← lintegral_add_left hf.measurable_mk, lintegral_congr_ae (hf.ae_eq_mk.fun_add (ae_eq_refl g))] theorem lintegral_add_right' (f : α → ℝ≥0∞) {g : α → ℝ≥0∞} (hg : AEMeasurable g μ) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := by simpa only [add_comm] using lintegral_add_left' hg f /-- If `f g : α → ℝ≥0∞` are two functions and one of them is (a.e.) measurable, then the Lebesgue integral of `f + g` equals the sum of integrals. This lemma assumes that `g` is integrable, see also `MeasureTheory.lintegral_add_left` and primed versions of these lemmas. -/ @[simp] theorem lintegral_add_right (f : α → ℝ≥0∞) {g : α → ℝ≥0∞} (hg : Measurable g) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := lintegral_add_right' f hg.aemeasurable theorem lintegral_finset_sum' (s : Finset β) {f : β → α → ℝ≥0∞} (hf : ∀ b ∈ s, AEMeasurable (f b) μ) : ∫⁻ a, ∑ b ∈ s, f b a ∂μ = ∑ b ∈ s, ∫⁻ a, f b a ∂μ := by classical induction s using Finset.induction_on with | empty => simp | insert a s has ih => simp only [Finset.sum_insert has] rw [Finset.forall_mem_insert] at hf rw [lintegral_add_left' hf.1, ih hf.2] theorem lintegral_finset_sum (s : Finset β) {f : β → α → ℝ≥0∞} (hf : ∀ b ∈ s, Measurable (f b)) : ∫⁻ a, ∑ b ∈ s, f b a ∂μ = ∑ b ∈ s, ∫⁻ a, f b a ∂μ := lintegral_finset_sum' s fun b hb => (hf b hb).aemeasurable theorem lintegral_tsum [Countable β] {f : β → α → ℝ≥0∞} (hf : ∀ i, AEMeasurable (f i) μ) : ∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ := by classical simp only [ENNReal.tsum_eq_iSup_sum] rw [lintegral_iSup_directed] · simp [lintegral_finset_sum' _ fun i _ => hf i] · intro b exact Finset.aemeasurable_fun_sum _ fun i _ => hf i · intro s t use s ∪ t constructor · exact fun a => Finset.sum_le_sum_of_subset Finset.subset_union_left · exact fun a => Finset.sum_le_sum_of_subset Finset.subset_union_right end Add section Mul @[simp] theorem lintegral_const_mul (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a, r * f a ∂μ = r * ∫⁻ a, f a ∂μ := calc ∫⁻ a, r * f a ∂μ = ∫⁻ a, ⨆ n, (const α r * eapprox f n) a ∂μ := by congr funext a rw [← iSup_eapprox_apply hf, ENNReal.mul_iSup] simp _ = ⨆ n, r * (eapprox f n).lintegral μ := by rw [lintegral_iSup] · congr funext n rw [← SimpleFunc.const_mul_lintegral, ← SimpleFunc.lintegral_eq_lintegral] · intro n exact SimpleFunc.measurable _ · intro i j h a dsimp gcongr exact monotone_eapprox _ h _ _ = r * ∫⁻ a, f a ∂μ := by rw [← ENNReal.mul_iSup, lintegral_eq_iSup_eapprox_lintegral hf] theorem lintegral_const_mul'' (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) : ∫⁻ a, r * f a ∂μ = r * ∫⁻ a, f a ∂μ := by have A : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk have B : ∫⁻ a, r * f a ∂μ = ∫⁻ a, r * hf.mk f a ∂μ := lintegral_congr_ae (EventuallyEq.fun_comp hf.ae_eq_mk _) rw [A, B, lintegral_const_mul _ hf.measurable_mk] theorem lintegral_const_mul_le (r : ℝ≥0∞) (f : α → ℝ≥0∞) : r * ∫⁻ a, f a ∂μ ≤ ∫⁻ a, r * f a ∂μ := by rw [lintegral, ENNReal.mul_iSup] refine iSup_le fun s => ?_ rw [ENNReal.mul_iSup, iSup_le_iff] intro hs rw [← SimpleFunc.const_mul_lintegral, lintegral] refine le_iSup_of_le (const α r * s) (le_iSup_of_le (fun x => ?_) le_rfl) dsimp grw [hs x] theorem lintegral_const_mul' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞) : ∫⁻ a, r * f a ∂μ = r * ∫⁻ a, f a ∂μ := by by_cases h : r = 0 · simp [h] apply le_antisymm _ (lintegral_const_mul_le r f) have rinv : r * r⁻¹ = 1 := ENNReal.mul_inv_cancel h hr have rinv' : r⁻¹ * r = 1 := by rw [mul_comm] exact rinv have := lintegral_const_mul_le (μ := μ) r⁻¹ fun x => r * f x simp only [(mul_assoc _ _ _).symm, rinv'] at this simpa [(mul_assoc _ _ _).symm, rinv] using mul_le_mul_left' this r theorem lintegral_mul_const (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a, f a * r ∂μ = (∫⁻ a, f a ∂μ) * r := by simp_rw [mul_comm, lintegral_const_mul r hf] theorem lintegral_mul_const'' (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) : ∫⁻ a, f a * r ∂μ = (∫⁻ a, f a ∂μ) * r := by simp_rw [mul_comm, lintegral_const_mul'' r hf] theorem lintegral_mul_const_le (r : ℝ≥0∞) (f : α → ℝ≥0∞) : (∫⁻ a, f a ∂μ) * r ≤ ∫⁻ a, f a * r ∂μ := by simp_rw [mul_comm, lintegral_const_mul_le r f] theorem lintegral_mul_const' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞) : ∫⁻ a, f a * r ∂μ = (∫⁻ a, f a ∂μ) * r := by simp_rw [mul_comm, lintegral_const_mul' r f hr] /- A double integral of a product where each factor contains only one variable is a product of integrals -/ theorem lintegral_lintegral_mul {β} [MeasurableSpace β] {ν : Measure β} {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : AEMeasurable f μ) (hg : AEMeasurable g ν) : ∫⁻ x, ∫⁻ y, f x * g y ∂ν ∂μ = (∫⁻ x, f x ∂μ) * ∫⁻ y, g y ∂ν := by simp [lintegral_const_mul'' _ hg, lintegral_mul_const'' _ hf] end Mul section Trim variable {m m0 : MeasurableSpace α} theorem lintegral_trim {μ : Measure α} (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : Measurable[m] f) : ∫⁻ a, f a ∂μ.trim hm = ∫⁻ a, f a ∂μ := by refine @Measurable.ennreal_induction α m (fun f => ∫⁻ a, f a ∂μ.trim hm = ∫⁻ a, f a ∂μ) ?_ ?_ ?_ f hf · intro c s hs rw [lintegral_indicator hs, lintegral_indicator (hm s hs), setLIntegral_const, setLIntegral_const] suffices h_trim_s : μ.trim hm s = μ s by rw [h_trim_s] exact trim_measurableSet_eq hm hs · intro f g _ hf _ hf_prop hg_prop have h_m := lintegral_add_left (μ := Measure.trim μ hm) hf g have h_m0 := lintegral_add_left (μ := μ) (Measurable.mono hf hm le_rfl) g rwa [hf_prop, hg_prop, ← h_m0] at h_m · intro f hf hf_mono hf_prop rw [lintegral_iSup hf hf_mono] rw [lintegral_iSup (fun n => Measurable.mono (hf n) hm le_rfl) hf_mono] congr with n exact hf_prop n theorem lintegral_trim_ae {μ : Measure α} (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : AEMeasurable f (μ.trim hm)) : ∫⁻ a, f a ∂μ.trim hm = ∫⁻ a, f a ∂μ := by rw [lintegral_congr_ae (ae_eq_of_ae_eq_trim hf.ae_eq_mk), lintegral_congr_ae hf.ae_eq_mk, lintegral_trim hm hf.measurable_mk] end Trim end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue/Norm.lean
import Mathlib.Analysis.Normed.Group.Basic import Mathlib.MeasureTheory.Integral.Lebesgue.Basic /-! # Interactions between the Lebesgue integral and norms -/ namespace MeasureTheory variable {α : Type*} [MeasurableSpace α] {μ : Measure α} theorem lintegral_ofReal_le_lintegral_enorm (f : α → ℝ) : ∫⁻ x, ENNReal.ofReal (f x) ∂μ ≤ ∫⁻ x, ‖f x‖ₑ ∂μ := by simp_rw [← ofReal_norm_eq_enorm] refine lintegral_mono fun x => ENNReal.ofReal_le_ofReal ?_ rw [Real.norm_eq_abs] exact le_abs_self (f x) theorem lintegral_enorm_of_ae_nonneg {f : α → ℝ} (h_nonneg : 0 ≤ᵐ[μ] f) : ∫⁻ x, ‖f x‖ₑ ∂μ = ∫⁻ x, .ofReal (f x) ∂μ := by apply lintegral_congr_ae filter_upwards [h_nonneg] with x hx rw [Real.enorm_eq_ofReal hx] theorem lintegral_enorm_of_nonneg {f : α → ℝ} (h_nonneg : 0 ≤ f) : ∫⁻ x, ‖f x‖ₑ ∂μ = ∫⁻ x, .ofReal (f x) ∂μ := lintegral_enorm_of_ae_nonneg <| .of_forall h_nonneg end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue/DominatedConvergence.lean
import Mathlib.MeasureTheory.Integral.Lebesgue.Markov import Mathlib.MeasureTheory.Integral.Lebesgue.Sub /-! # Dominated convergence theorem Lebesgue's dominated convergence theorem states that the limit and Lebesgue integral of a sequence of (almost everywhere) measurable functions can be swapped if the functions are pointwise dominated by a fixed function. This file provides a few variants of the result. -/ open Filter ENNReal Topology namespace MeasureTheory variable {α : Type*} [MeasurableSpace α] {μ : Measure α} theorem limsup_lintegral_le {f : ℕ → α → ℝ≥0∞} (g : α → ℝ≥0∞) (hf_meas : ∀ n, Measurable (f n)) (h_bound : ∀ n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ ≠ ∞) : limsup (fun n => ∫⁻ a, f n a ∂μ) atTop ≤ ∫⁻ a, limsup (fun n => f n a) atTop ∂μ := calc limsup (fun n => ∫⁻ a, f n a ∂μ) atTop = ⨅ n : ℕ, ⨆ i ≥ n, ∫⁻ a, f i a ∂μ := limsup_eq_iInf_iSup_of_nat _ ≤ ⨅ n : ℕ, ∫⁻ a, ⨆ i ≥ n, f i a ∂μ := iInf_mono fun _ => iSup₂_lintegral_le _ _ = ∫⁻ a, ⨅ n : ℕ, ⨆ i ≥ n, f i a ∂μ := by refine (lintegral_iInf ?_ ?_ ?_).symm · intro n exact .biSup _ (Set.to_countable _) (fun i _ ↦ hf_meas i) · intro n m hnm a exact iSup_le_iSup_of_subset fun i hi => le_trans hnm hi · refine ne_top_of_le_ne_top h_fin (lintegral_mono_ae ?_) refine (ae_all_iff.2 h_bound).mono fun n hn => ?_ exact iSup_le fun i => iSup_le fun _ => hn i _ = ∫⁻ a, limsup (fun n => f n a) atTop ∂μ := by simp only [limsup_eq_iInf_iSup_of_nat] /-- **Dominated convergence theorem** for nonnegative `Measurable` functions. -/ theorem tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀ n, Measurable (F n)) (h_bound : ∀ n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, Tendsto (fun n => F n a) atTop (𝓝 (f a))) : Tendsto (fun n => ∫⁻ a, F n a ∂μ) atTop (𝓝 (∫⁻ a, f a ∂μ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf (fun n : ℕ => F n a) atTop ∂μ := lintegral_congr_ae <| h_lim.mono fun _ h => h.liminf_eq.symm _ ≤ liminf (fun n => ∫⁻ a, F n a ∂μ) atTop := lintegral_liminf_le hF_meas) (calc limsup (fun n : ℕ => ∫⁻ a, F n a ∂μ) atTop ≤ ∫⁻ a, limsup (fun n => F n a) atTop ∂μ := limsup_lintegral_le _ hF_meas h_bound h_fin _ = ∫⁻ a, f a ∂μ := lintegral_congr_ae <| h_lim.mono fun _ h => h.limsup_eq) /-- **Dominated convergence theorem** for nonnegative `AEMeasurable` functions. -/ theorem tendsto_lintegral_of_dominated_convergence' {F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀ n, AEMeasurable (F n) μ) (h_bound : ∀ n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, Tendsto (fun n => F n a) atTop (𝓝 (f a))) : Tendsto (fun n => ∫⁻ a, F n a ∂μ) atTop (𝓝 (∫⁻ a, f a ∂μ)) := by have : ∀ n, ∫⁻ a, F n a ∂μ = ∫⁻ a, (hF_meas n).mk (F n) a ∂μ := fun n => lintegral_congr_ae (hF_meas n).ae_eq_mk simp_rw [this] apply tendsto_lintegral_of_dominated_convergence bound (fun n => (hF_meas n).measurable_mk) _ h_fin · have : ∀ n, ∀ᵐ a ∂μ, (hF_meas n).mk (F n) a = F n a := fun n => (hF_meas n).ae_eq_mk.symm have : ∀ᵐ a ∂μ, ∀ n, (hF_meas n).mk (F n) a = F n a := ae_all_iff.mpr this filter_upwards [this, h_lim] with a H H' simp_rw [H] exact H' · intro n filter_upwards [h_bound n, (hF_meas n).ae_eq_mk] with a H H' rwa [H'] at H /-- **Dominated convergence theorem** for filters with a countable basis. -/ theorem tendsto_lintegral_filter_of_dominated_convergence {ι} {l : Filter ι} [l.IsCountablyGenerated] {F : ι → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀ᶠ n in l, Measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, Tendsto (fun n => F n a) l (𝓝 (f a))) : Tendsto (fun n => ∫⁻ a, F n a ∂μ) l (𝓝 <| ∫⁻ a, f a ∂μ) := by rw [tendsto_iff_seq_tendsto] intro x xl have hxl := by rw [tendsto_atTop'] at xl exact xl have h := inter_mem hF_meas h_bound replace h := hxl _ h rcases h with ⟨k, h⟩ rw [← tendsto_add_atTop_iff_nat k] refine tendsto_lintegral_of_dominated_convergence ?_ ?_ ?_ ?_ ?_ · exact bound · intro refine (h _ ?_).1 exact Nat.le_add_left _ _ · intro refine (h _ ?_).2 exact Nat.le_add_left _ _ · assumption · refine h_lim.mono fun a h_lim => ?_ apply @Tendsto.comp _ _ _ (fun n => x (n + k)) fun n => F n a · assumption rw [tendsto_add_atTop_iff_nat] assumption /-- If a monotone sequence of functions has an upper bound and the sequence of integrals of these functions tends to the integral of the upper bound, then the sequence of functions converges almost everywhere to the upper bound. Auxiliary version assuming moreover that the functions in the sequence are ae measurable. -/ lemma tendsto_of_lintegral_tendsto_of_monotone_aux {α : Type*} {mα : MeasurableSpace α} {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} {μ : Measure α} (hf_meas : ∀ n, AEMeasurable (f n) μ) (hF_meas : AEMeasurable F μ) (hf_tendsto : Tendsto (fun i ↦ ∫⁻ a, f i a ∂μ) atTop (𝓝 (∫⁻ a, F a ∂μ))) (hf_mono : ∀ᵐ a ∂μ, Monotone (fun i ↦ f i a)) (h_bound : ∀ᵐ a ∂μ, ∀ i, f i a ≤ F a) (h_int_finite : ∫⁻ a, F a ∂μ ≠ ∞) : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F a)) := by have h_bound_finite : ∀ᵐ a ∂μ, F a ≠ ∞ := by filter_upwards [ae_lt_top' hF_meas h_int_finite] with a ha using ha.ne have h_exists : ∀ᵐ a ∂μ, ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) := by filter_upwards [h_bound, h_bound_finite, hf_mono] with a h_le h_fin h_mono have h_tendsto : Tendsto (fun i ↦ f i a) atTop atTop ∨ ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) := tendsto_of_monotone h_mono rcases h_tendsto with h_absurd | h_tendsto · rw [tendsto_atTop_atTop_iff_of_monotone h_mono] at h_absurd obtain ⟨i, hi⟩ := h_absurd (F a + 1) refine absurd (hi.trans (h_le _)) (not_le.mpr ?_) exact ENNReal.lt_add_right h_fin one_ne_zero · exact h_tendsto classical let F' : α → ℝ≥0∞ := fun a ↦ if h : ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) then h.choose else ∞ have hF'_tendsto : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F' a)) := by filter_upwards [h_exists] with a ha simp_rw [F', dif_pos ha] exact ha.choose_spec suffices F' =ᵐ[μ] F by filter_upwards [this, hF'_tendsto] with a h_eq h_tendsto using h_eq ▸ h_tendsto have hF'_le : F' ≤ᵐ[μ] F := by filter_upwards [h_bound, hF'_tendsto] with a h_le h_tendsto exact le_of_tendsto' h_tendsto (fun m ↦ h_le _) suffices ∫⁻ a, F' a ∂μ = ∫⁻ a, F a ∂μ from ae_eq_of_ae_le_of_lintegral_le hF'_le (this ▸ h_int_finite) hF_meas this.symm.le refine tendsto_nhds_unique ?_ hf_tendsto exact lintegral_tendsto_of_tendsto_of_monotone hf_meas hf_mono hF'_tendsto /-- If a monotone sequence of functions has an upper bound and the sequence of integrals of these functions tends to the integral of the upper bound, then the sequence of functions converges almost everywhere to the upper bound. -/ lemma tendsto_of_lintegral_tendsto_of_monotone {α : Type*} {mα : MeasurableSpace α} {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} {μ : Measure α} (hF_meas : AEMeasurable F μ) (hf_tendsto : Tendsto (fun i ↦ ∫⁻ a, f i a ∂μ) atTop (𝓝 (∫⁻ a, F a ∂μ))) (hf_mono : ∀ᵐ a ∂μ, Monotone (fun i ↦ f i a)) (h_bound : ∀ᵐ a ∂μ, ∀ i, f i a ≤ F a) (h_int_finite : ∫⁻ a, F a ∂μ ≠ ∞) : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F a)) := by have : ∀ n, ∃ g : α → ℝ≥0∞, Measurable g ∧ g ≤ f n ∧ ∫⁻ a, f n a ∂μ = ∫⁻ a, g a ∂μ := fun n ↦ exists_measurable_le_lintegral_eq _ _ choose g gmeas gf hg using this let g' : ℕ → α → ℝ≥0∞ := Nat.rec (g 0) (fun n I x ↦ max (g (n + 1) x) (I x)) have M n : Measurable (g' n) := by induction n with | zero => simp [g', gmeas 0] | succ n ih => exact Measurable.max (gmeas (n + 1)) ih have I : ∀ n x, g n x ≤ g' n x := by intro n x cases n with | zero | succ => simp [g'] have I' : ∀ᵐ x ∂μ, ∀ n, g' n x ≤ f n x := by filter_upwards [hf_mono] with x hx n induction n with | zero => simpa [g'] using gf 0 x | succ n ih => exact max_le (gf (n + 1) x) (ih.trans (hx (Nat.le_succ n))) have Int_eq n : ∫⁻ x, g' n x ∂μ = ∫⁻ x, f n x ∂μ := by apply le_antisymm · apply lintegral_mono_ae filter_upwards [I'] with x hx using hx n · rw [hg n] exact lintegral_mono (I n) have : ∀ᵐ a ∂μ, Tendsto (fun i ↦ g' i a) atTop (𝓝 (F a)) := by apply tendsto_of_lintegral_tendsto_of_monotone_aux _ hF_meas _ _ _ h_int_finite · exact fun n ↦ (M n).aemeasurable · simp_rw [Int_eq] exact hf_tendsto · exact Eventually.of_forall (fun x ↦ monotone_nat_of_le_succ (fun n ↦ le_max_right _ _)) · filter_upwards [h_bound, I'] with x h'x hx n using (hx n).trans (h'x n) filter_upwards [this, I', h_bound] with x hx h'x h''x exact tendsto_of_tendsto_of_tendsto_of_le_of_le hx tendsto_const_nhds h'x h''x /-- If an antitone sequence of functions has a lower bound and the sequence of integrals of these functions tends to the integral of the lower bound, then the sequence of functions converges almost everywhere to the lower bound. -/ lemma tendsto_of_lintegral_tendsto_of_antitone {α : Type*} {mα : MeasurableSpace α} {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} {μ : Measure α} (hf_meas : ∀ n, AEMeasurable (f n) μ) (hf_tendsto : Tendsto (fun i ↦ ∫⁻ a, f i a ∂μ) atTop (𝓝 (∫⁻ a, F a ∂μ))) (hf_mono : ∀ᵐ a ∂μ, Antitone (fun i ↦ f i a)) (h_bound : ∀ᵐ a ∂μ, ∀ i, F a ≤ f i a) (h0 : ∫⁻ a, f 0 a ∂μ ≠ ∞) : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F a)) := by have h_int_finite : ∫⁻ a, F a ∂μ ≠ ∞ := by refine ((lintegral_mono_ae ?_).trans_lt h0.lt_top).ne filter_upwards [h_bound] with a ha using ha 0 have h_exists : ∀ᵐ a ∂μ, ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) := by filter_upwards [hf_mono] with a h_mono rcases _root_.tendsto_of_antitone h_mono with h | h · refine ⟨0, h.mono_right ?_⟩ rw [OrderBot.atBot_eq] exact pure_le_nhds _ · exact h classical let F' : α → ℝ≥0∞ := fun a ↦ if h : ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) then h.choose else ∞ have hF'_tendsto : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F' a)) := by filter_upwards [h_exists] with a ha simp_rw [F', dif_pos ha] exact ha.choose_spec suffices F' =ᵐ[μ] F by filter_upwards [this, hF'_tendsto] with a h_eq h_tendsto using h_eq ▸ h_tendsto have hF'_le : F ≤ᵐ[μ] F' := by filter_upwards [h_bound, hF'_tendsto] with a h_le h_tendsto exact ge_of_tendsto' h_tendsto (fun m ↦ h_le _) suffices ∫⁻ a, F' a ∂μ = ∫⁻ a, F a ∂μ by refine (ae_eq_of_ae_le_of_lintegral_le hF'_le h_int_finite ?_ this.le).symm exact ENNReal.aemeasurable_of_tendsto hf_meas hF'_tendsto refine tendsto_nhds_unique ?_ hf_tendsto exact lintegral_tendsto_of_tendsto_of_antitone hf_meas hf_mono h0 hF'_tendsto end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue/Map.lean
import Mathlib.Dynamics.Ergodic.MeasurePreserving import Mathlib.MeasureTheory.Integral.Lebesgue.Add /-! # Behavior of the Lebesgue integral under maps -/ namespace MeasureTheory open Set Filter ENNReal SimpleFunc variable {α β : Type*} [MeasurableSpace α] [MeasurableSpace β] {μ : Measure α} {ν : Measure β} section Map open Measure theorem lintegral_map {f : β → ℝ≥0∞} {g : α → β} (hf : Measurable f) (hg : Measurable g) : ∫⁻ a, f a ∂map g μ = ∫⁻ a, f (g a) ∂μ := by rw [lintegral_eq_iSup_eapprox_lintegral hf] simp only [← Function.comp_apply (f := f) (g := g)] rw [lintegral_eq_iSup_eapprox_lintegral (hf.comp hg)] congr with n : 1 convert SimpleFunc.lintegral_map _ hg ext1 x; simp only [eapprox_comp hf hg, coe_comp] theorem lintegral_map' {f : β → ℝ≥0∞} {g : α → β} (hf : AEMeasurable f (Measure.map g μ)) (hg : AEMeasurable g μ) : ∫⁻ a, f a ∂Measure.map g μ = ∫⁻ a, f (g a) ∂μ := calc ∫⁻ a, f a ∂Measure.map g μ = ∫⁻ a, hf.mk f a ∂Measure.map g μ := lintegral_congr_ae hf.ae_eq_mk _ = ∫⁻ a, hf.mk f a ∂Measure.map (hg.mk g) μ := by congr 1 exact Measure.map_congr hg.ae_eq_mk _ = ∫⁻ a, hf.mk f (hg.mk g a) ∂μ := lintegral_map hf.measurable_mk hg.measurable_mk _ = ∫⁻ a, hf.mk f (g a) ∂μ := lintegral_congr_ae <| hg.ae_eq_mk.symm.fun_comp _ _ = ∫⁻ a, f (g a) ∂μ := lintegral_congr_ae (ae_eq_comp hg hf.ae_eq_mk.symm) theorem lintegral_map_le (f : β → ℝ≥0∞) (g : α → β) : ∫⁻ a, f a ∂Measure.map g μ ≤ ∫⁻ a, f (g a) ∂μ := by by_cases hg : AEMeasurable g μ · rw [← iSup_lintegral_measurable_le_eq_lintegral] refine iSup₂_le fun i hi => iSup_le fun h'i => ?_ rw [lintegral_map' hi.aemeasurable hg] exact lintegral_mono fun _ ↦ h'i _ · simp [map_of_not_aemeasurable hg] theorem lintegral_comp {f : β → ℝ≥0∞} {g : α → β} (hf : Measurable f) (hg : Measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂map g μ := (lintegral_map hf hg).symm theorem setLIntegral_map {f : β → ℝ≥0∞} {g : α → β} {s : Set β} (hs : MeasurableSet s) (hf : Measurable f) (hg : Measurable g) : ∫⁻ y in s, f y ∂map g μ = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ := by rw [restrict_map hg hs, lintegral_map hf hg] theorem lintegral_indicator_const_comp {f : α → β} {s : Set β} (hf : Measurable f) (hs : MeasurableSet s) (c : ℝ≥0∞) : ∫⁻ a, s.indicator (fun _ => c) (f a) ∂μ = c * μ (f ⁻¹' s) := by erw [lintegral_comp (measurable_const.indicator hs) hf] rw [lintegral_indicator_const hs, Measure.map_apply hf hs] /-- If `g : α → β` is a measurable embedding and `f : β → ℝ≥0∞` is any function (not necessarily measurable), then `∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ`. Compare with `lintegral_map` which applies to any measurable `g : α → β` but requires that `f` is measurable as well. -/ theorem _root_.MeasurableEmbedding.lintegral_map {g : α → β} (hg : MeasurableEmbedding g) (f : β → ℝ≥0∞) : ∫⁻ a, f a ∂map g μ = ∫⁻ a, f (g a) ∂μ := by rw [lintegral, lintegral] refine le_antisymm (iSup₂_le fun f₀ hf₀ => ?_) (iSup₂_le fun f₀ hf₀ => ?_) · rw [SimpleFunc.lintegral_map _ hg.measurable] have : (f₀.comp g hg.measurable : α → ℝ≥0∞) ≤ f ∘ g := fun x => hf₀ (g x) exact le_iSup_of_le (comp f₀ g hg.measurable) (by exact le_iSup (α := ℝ≥0∞) _ this) · rw [← f₀.extend_comp_eq hg (const _ 0), ← SimpleFunc.lintegral_map, ← SimpleFunc.lintegral_eq_lintegral, ← lintegral] refine lintegral_mono_ae (hg.ae_map_iff.2 <| Eventually.of_forall fun x => ?_) exact (extend_apply _ _ _ _).trans_le (hf₀ _) /-- The `lintegral` transforms appropriately under a measurable equivalence `g : α ≃ᵐ β`. (Compare `lintegral_map`, which applies to a wider class of functions `g : α → β`, but requires measurability of the function being integrated.) -/ theorem lintegral_map_equiv (f : β → ℝ≥0∞) (g : α ≃ᵐ β) : ∫⁻ a, f a ∂map g μ = ∫⁻ a, f (g a) ∂μ := g.measurableEmbedding.lintegral_map f theorem lintegral_subtype_comap {s : Set α} (hs : MeasurableSet s) (f : α → ℝ≥0∞) : ∫⁻ x : s, f x ∂(μ.comap (↑)) = ∫⁻ x in s, f x ∂μ := by rw [← (MeasurableEmbedding.subtype_coe hs).lintegral_map, map_comap_subtype_coe hs] theorem setLIntegral_subtype {s : Set α} (hs : MeasurableSet s) (t : Set s) (f : α → ℝ≥0∞) : ∫⁻ x in t, f x ∂(μ.comap (↑)) = ∫⁻ x in (↑) '' t, f x ∂μ := by rw [(MeasurableEmbedding.subtype_coe hs).restrict_comap, lintegral_subtype_comap hs, restrict_restrict hs, inter_eq_right.2 (Subtype.coe_image_subset _ _)] end Map namespace MeasurePreserving variable {g : α → β} (hg : MeasurePreserving g μ ν) protected theorem lintegral_map_equiv (f : β → ℝ≥0∞) (g : α ≃ᵐ β) (hg : MeasurePreserving g μ ν) : ∫⁻ a, f a ∂ν = ∫⁻ a, f (g a) ∂μ := by rw [← MeasureTheory.lintegral_map_equiv f g, hg.map_eq] include hg theorem lintegral_comp {f : β → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν := by rw [← hg.map_eq, lintegral_map hf hg.measurable] theorem lintegral_comp_emb (hge : MeasurableEmbedding g) (f : β → ℝ≥0∞) : ∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν := by rw [← hg.map_eq, hge.lintegral_map] theorem setLIntegral_comp_preimage {s : Set β} (hs : MeasurableSet s) {f : β → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν := by rw [← hg.map_eq, setLIntegral_map hs hf hg.measurable] theorem setLIntegral_comp_preimage_emb (hge : MeasurableEmbedding g) (f : β → ℝ≥0∞) (s : Set β) : ∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν := by rw [← hg.map_eq, hge.restrict_map, hge.lintegral_map] theorem setLIntegral_comp_emb (hge : MeasurableEmbedding g) (f : β → ℝ≥0∞) (s : Set α) : ∫⁻ a in s, f (g a) ∂μ = ∫⁻ b in g '' s, f b ∂ν := by rw [← hg.setLIntegral_comp_preimage_emb hge, Set.preimage_image_eq _ hge.injective] end MeasurePreserving end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue/Basic.lean
import Mathlib.MeasureTheory.Function.SimpleFunc /-! # Lower Lebesgue integral for `ℝ≥0∞`-valued functions We define the lower Lebesgue integral of an `ℝ≥0∞`-valued function. ## Notation We introduce the following notation for the lower Lebesgue integral of a function `f : α → ℝ≥0∞`. * `∫⁻ x, f x ∂μ`: integral of a function `f : α → ℝ≥0∞` with respect to a measure `μ`; * `∫⁻ x, f x`: integral of a function `f : α → ℝ≥0∞` with respect to the canonical measure `volume` on `α`; * `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ℝ≥0∞` over a set `s` with respect to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`; * `∫⁻ x in s, f x`: integral of a function `f : α → ℝ≥0∞` over a set `s` with respect to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`. -/ assert_not_exists Module.Basis Norm MeasureTheory.MeasurePreserving MeasureTheory.Measure.dirac open Set hiding restrict restrict_apply open Filter ENNReal Topology NNReal namespace MeasureTheory local infixr:25 " →ₛ " => SimpleFunc variable {α β γ : Type*} open SimpleFunc variable {m : MeasurableSpace α} {μ ν : Measure α} {s : Set α} /-- The **lower Lebesgue integral** of a function `f` with respect to a measure `μ`. -/ noncomputable irreducible_def lintegral (μ : Measure α) (f : α → ℝ≥0∞) : ℝ≥0∞ := ⨆ (g : α →ₛ ℝ≥0∞) (_ : ⇑g ≤ f), g.lintegral μ /-! In the notation for integrals, an expression like `∫⁻ x, g ‖x‖ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫⁻ x, f x = 0` will be parsed incorrectly. -/ @[inherit_doc MeasureTheory.lintegral] notation3 "∫⁻ "(...)", "r:60:(scoped f => f)" ∂"μ:70 => lintegral μ r @[inherit_doc MeasureTheory.lintegral] notation3 "∫⁻ "(...)", "r:60:(scoped f => lintegral volume f) => r @[inherit_doc MeasureTheory.lintegral] notation3"∫⁻ "(...)" in "s", "r:60:(scoped f => f)" ∂"μ:70 => lintegral (Measure.restrict μ s) r @[inherit_doc MeasureTheory.lintegral] notation3"∫⁻ "(...)" in "s", "r:60:(scoped f => lintegral (Measure.restrict volume s) f) => r theorem SimpleFunc.lintegral_eq_lintegral {m : MeasurableSpace α} (f : α →ₛ ℝ≥0∞) (μ : Measure α) : ∫⁻ a, f a ∂μ = f.lintegral μ := by rw [MeasureTheory.lintegral] exact le_antisymm (iSup₂_le fun g hg => lintegral_mono hg <| le_rfl) (le_iSup₂_of_le f le_rfl le_rfl) @[mono] theorem lintegral_mono' {m : MeasurableSpace α} ⦃μ ν : Measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ℝ≥0∞⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν := by rw [lintegral, lintegral] exact iSup_mono fun φ => iSup_mono' fun hφ => ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩ -- version where `hfg` is an explicit forall, so that `@[gcongr]` can recognize it @[gcongr] theorem lintegral_mono_fn' (h2 : μ ≤ ν) ⦃f g : α → ℝ≥0∞⦄ (hfg : ∀ x, f x ≤ g x) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν := lintegral_mono' h2 hfg theorem lintegral_mono ⦃f g : α → ℝ≥0∞⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono' (le_refl μ) hfg @[deprecated lintegral_mono (since := "2025-07-10")] theorem lintegral_mono_fn ⦃f g : α → ℝ≥0∞⦄ (hfg : ∀ x, f x ≤ g x) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono hfg theorem lintegral_mono_nnreal {f g : α → ℝ≥0} (h : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono fun a => ENNReal.coe_le_coe.2 (h a) theorem iSup_lintegral_measurable_le_eq_lintegral (f : α → ℝ≥0∞) : ⨆ (g : α → ℝ≥0∞) (_ : Measurable g) (_ : g ≤ f), ∫⁻ a, g a ∂μ = ∫⁻ a, f a ∂μ := by apply le_antisymm · exact iSup_le fun i => iSup_le fun _ => iSup_le fun h'i => lintegral_mono h'i · rw [lintegral] refine iSup₂_le fun i hi => le_iSup₂_of_le i i.measurable <| le_iSup_of_le hi ?_ exact le_of_eq (i.lintegral_eq_lintegral _).symm theorem lintegral_mono_set {_ : MeasurableSpace α} ⦃μ : Measure α⦄ {s t : Set α} {f : α → ℝ≥0∞} (hst : s ⊆ t) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in t, f x ∂μ := lintegral_mono' (Measure.restrict_mono hst (le_refl μ)) (le_refl f) theorem lintegral_mono_set' {_ : MeasurableSpace α} ⦃μ : Measure α⦄ {s t : Set α} {f : α → ℝ≥0∞} (hst : s ≤ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in t, f x ∂μ := lintegral_mono' (Measure.restrict_mono' hst (le_refl μ)) (le_refl f) theorem monotone_lintegral {_ : MeasurableSpace α} (μ : Measure α) : Monotone (lintegral μ) := lintegral_mono @[simp] theorem lintegral_const (c : ℝ≥0∞) : ∫⁻ _, c ∂μ = c * μ univ := by rw [← SimpleFunc.const_lintegral, ← SimpleFunc.lintegral_eq_lintegral, SimpleFunc.coe_const] rfl theorem lintegral_zero : ∫⁻ _ : α, 0 ∂μ = 0 := by simp theorem lintegral_zero_fun : lintegral μ (0 : α → ℝ≥0∞) = 0 := lintegral_zero theorem lintegral_one : ∫⁻ _, (1 : ℝ≥0∞) ∂μ = μ univ := by rw [lintegral_const, one_mul] theorem setLIntegral_const (s : Set α) (c : ℝ≥0∞) : ∫⁻ _ in s, c ∂μ = c * μ s := by rw [lintegral_const, Measure.restrict_apply_univ] theorem setLIntegral_one (s) : ∫⁻ _ in s, 1 ∂μ = μ s := by rw [setLIntegral_const, one_mul] lemma iInf_mul_le_lintegral (f : α → ℝ≥0∞) : (⨅ x, f x) * μ .univ ≤ ∫⁻ x, f x ∂μ := by calc (⨅ x, f x) * μ .univ _ = ∫⁻ y, ⨅ x, f x ∂μ := by simp _ ≤ ∫⁻ x, f x ∂μ := by gcongr; exact iInf_le _ _ lemma lintegral_le_iSup_mul (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ ≤ (⨆ x, f x) * μ .univ := by calc ∫⁻ x, f x ∂μ _ ≤ ∫⁻ y, ⨆ x, f x ∂μ := by gcongr; exact le_iSup _ _ _ = (⨆ x, f x) * μ .univ := by simp variable (μ) in /-- For any function `f : α → ℝ≥0∞`, there exists a measurable function `g ≤ f` with the same integral. -/ theorem exists_measurable_le_lintegral_eq (f : α → ℝ≥0∞) : ∃ g : α → ℝ≥0∞, Measurable g ∧ g ≤ f ∧ ∫⁻ a, f a ∂μ = ∫⁻ a, g a ∂μ := by rcases eq_or_ne (∫⁻ a, f a ∂μ) 0 with h₀ | h₀ · exact ⟨0, measurable_zero, zero_le f, h₀.trans lintegral_zero.symm⟩ rcases exists_seq_strictMono_tendsto' h₀.bot_lt with ⟨L, _, hLf, hL_tendsto⟩ have : ∀ n, ∃ g : α → ℝ≥0∞, Measurable g ∧ g ≤ f ∧ L n < ∫⁻ a, g a ∂μ := by intro n simpa only [← iSup_lintegral_measurable_le_eq_lintegral f, lt_iSup_iff, exists_prop] using (hLf n).2 choose g hgm hgf hLg using this refine ⟨fun x => ⨆ n, g n x, .iSup hgm, fun x => iSup_le fun n => hgf n x, le_antisymm ?_ ?_⟩ · refine le_of_tendsto' hL_tendsto fun n => (hLg n).le.trans <| lintegral_mono fun x => ?_ exact le_iSup (fun n => g n x) n · exact lintegral_mono fun x => iSup_le fun n => hgf n x /-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions `φ : α →ₛ ℝ≥0∞` such that `φ ≤ f`. This lemma says that it suffices to take functions `φ : α →ₛ ℝ≥0`. -/ theorem lintegral_eq_nnreal {m : MeasurableSpace α} (f : α → ℝ≥0∞) (μ : Measure α) : ∫⁻ a, f a ∂μ = ⨆ (φ : α →ₛ ℝ≥0) (_ : ∀ x, ↑(φ x) ≤ f x), (φ.map ((↑) : ℝ≥0 → ℝ≥0∞)).lintegral μ := by rw [lintegral] refine le_antisymm (iSup₂_le fun φ hφ ↦ ?_) (iSup_mono' fun φ ↦ ⟨φ.map ((↑) : ℝ≥0 → ℝ≥0∞), le_rfl⟩) by_cases h : ∀ᵐ a ∂μ, φ a ≠ ∞ · let ψ := φ.map ENNReal.toNNReal replace h : ψ.map ((↑) : ℝ≥0 → ℝ≥0∞) =ᵐ[μ] φ := h.mono fun a => ENNReal.coe_toNNReal have : ∀ x, ↑(ψ x) ≤ f x := fun x => le_trans ENNReal.coe_toNNReal_le_self (hφ x) exact le_iSup₂_of_le (φ.map ENNReal.toNNReal) this (ge_of_eq <| lintegral_congr h) · have h_meas : μ (φ ⁻¹' {∞}) ≠ 0 := mt measure_eq_zero_iff_ae_notMem.1 h refine le_trans le_top (ge_of_eq <| (iSup_eq_top _).2 fun b hb => ?_) obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {∞}) := exists_nat_mul_gt h_meas (ne_of_lt hb) use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {∞}) simp only [lt_iSup_iff, exists_prop, coe_restrict, φ.measurableSet_preimage, coe_const, ENNReal.coe_indicator, map_coe_ennreal_restrict, SimpleFunc.map_const, ENNReal.coe_natCast, restrict_const_lintegral] refine ⟨indicator_le fun x hx => le_trans ?_ (hφ _), hn⟩ simp only [mem_preimage, mem_singleton_iff] at hx simp only [hx, le_top] theorem exists_simpleFunc_forall_lintegral_sub_lt_of_pos {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ φ : α →ₛ ℝ≥0, (∀ x, ↑(φ x) ≤ f x) ∧ ∀ ψ : α →ₛ ℝ≥0, (∀ x, ↑(ψ x) ≤ f x) → (map (↑) (ψ - φ)).lintegral μ < ε := by rw [lintegral_eq_nnreal] at h have := ENNReal.lt_add_right h hε erw [ENNReal.biSup_add] at this <;> [skip; exact ⟨0, fun x => zero_le _⟩] simp_rw [lt_iSup_iff, iSup_lt_iff, iSup_le_iff] at this rcases this with ⟨φ, hle : ∀ x, ↑(φ x) ≤ f x, b, hbφ, hb⟩ refine ⟨φ, hle, fun ψ hψ => ?_⟩ have : (map (↑) φ).lintegral μ ≠ ∞ := ne_top_of_le_ne_top h (by exact le_iSup₂ (α := ℝ≥0∞) φ hle) rw [← ENNReal.add_lt_add_iff_left this, ← add_lintegral, ← SimpleFunc.map_add @ENNReal.coe_add] refine (hb _ fun x => le_trans ?_ (max_le (hle x) (hψ x))).trans_lt hbφ norm_cast simp only [add_apply, sub_apply, add_tsub_eq_max] rfl theorem iSup_lintegral_le {ι : Sort*} (f : ι → α → ℝ≥0∞) : ⨆ i, ∫⁻ a, f i a ∂μ ≤ ∫⁻ a, ⨆ i, f i a ∂μ := by simp only [← iSup_apply] exact (monotone_lintegral μ).le_map_iSup theorem iSup₂_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : ∀ i, ι' i → α → ℝ≥0∞) : ⨆ (i) (j), ∫⁻ a, f i j a ∂μ ≤ ∫⁻ a, ⨆ (i) (j), f i j a ∂μ := by convert (monotone_lintegral μ).le_map_iSup₂ f with a simp only [iSup_apply] theorem le_iInf_lintegral {ι : Sort*} (f : ι → α → ℝ≥0∞) : ∫⁻ a, ⨅ i, f i a ∂μ ≤ ⨅ i, ∫⁻ a, f i a ∂μ := by simp only [← iInf_apply] exact (monotone_lintegral μ).map_iInf_le theorem le_iInf₂_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : ∀ i, ι' i → α → ℝ≥0∞) : ∫⁻ a, ⨅ (i) (h : ι' i), f i h a ∂μ ≤ ⨅ (i) (h : ι' i), ∫⁻ a, f i h a ∂μ := by convert (monotone_lintegral μ).map_iInf₂_le f with a simp only [iInf_apply] theorem lintegral_mono_ae {f g : α → ℝ≥0∞} (h : ∀ᵐ a ∂μ, f a ≤ g a) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := by rcases exists_measurable_superset_of_null h with ⟨t, hts, ht, ht0⟩ have : ∀ᵐ x ∂μ, x ∉ t := measure_eq_zero_iff_ae_notMem.1 ht0 rw [lintegral, lintegral] refine iSup₂_le fun s hfs ↦ le_iSup₂_of_le (s.restrict tᶜ) ?_ ?_ · intro a by_cases h : a ∈ t <;> simp only [restrict_apply s ht.compl, mem_compl_iff, h, not_true, not_false_eq_true, indicator_of_notMem, zero_le, not_false_eq_true, indicator_of_mem] exact le_trans (hfs a) (by_contradiction fun hnfg => h (hts hnfg)) · refine le_of_eq (SimpleFunc.lintegral_congr <| this.mono fun a hnt => ?_) by_cases hat : a ∈ t <;> simp only [restrict_apply s ht.compl, mem_compl_iff, hat, not_true, not_false_eq_true, indicator_of_notMem, not_false_eq_true, indicator_of_mem] exact (hnt hat).elim /-- Lebesgue integral over a set is monotone in function. This version assumes that the upper estimate is an a.e. measurable function and the estimate holds a.e. on the set. See also `setLIntegral_mono_ae'` for a version that assumes measurability of the set but assumes no regularity of either function. -/ theorem setLIntegral_mono_ae {s : Set α} {f g : α → ℝ≥0∞} (hg : AEMeasurable g (μ.restrict s)) (hfg : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ := by rcases exists_measurable_le_lintegral_eq (μ.restrict s) f with ⟨f', hf'm, hle, hf'⟩ rw [hf'] apply lintegral_mono_ae rw [ae_restrict_iff₀] · exact hfg.mono fun x hx hxs ↦ (hle x).trans (hx hxs) · exact nullMeasurableSet_le hf'm.aemeasurable hg theorem setLIntegral_mono {s : Set α} {f g : α → ℝ≥0∞} (hg : Measurable g) (hfg : ∀ x ∈ s, f x ≤ g x) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ := setLIntegral_mono_ae hg.aemeasurable (ae_of_all _ hfg) theorem setLIntegral_mono_ae' {s : Set α} {f g : α → ℝ≥0∞} (hs : MeasurableSet s) (hfg : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ := lintegral_mono_ae <| (ae_restrict_iff' hs).2 hfg theorem setLIntegral_mono' {s : Set α} {f g : α → ℝ≥0∞} (hs : MeasurableSet s) (hfg : ∀ x ∈ s, f x ≤ g x) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ := setLIntegral_mono_ae' hs (ae_of_all _ hfg) theorem setLIntegral_le_lintegral (s : Set α) (f : α → ℝ≥0∞) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x, f x ∂μ := lintegral_mono' Measure.restrict_le_self le_rfl lemma iInf_mul_le_setLIntegral (f : α → ℝ≥0∞) {s : Set α} (hs : MeasurableSet s) : (⨅ x ∈ s, f x) * μ s ≤ ∫⁻ x in s, f x ∂μ := by calc (⨅ x ∈ s, f x) * μ s _ = ∫⁻ y in s, ⨅ x ∈ s, f x ∂μ := by simp _ ≤ ∫⁻ x in s, f x ∂μ := setLIntegral_mono' hs fun x hx ↦ iInf₂_le x hx lemma setLIntegral_le_iSup_mul (f : α → ℝ≥0∞) {s : Set α} (hs : MeasurableSet s) : ∫⁻ x in s, f x ∂μ ≤ (⨆ x ∈ s, f x) * μ s := by calc ∫⁻ x in s, f x ∂μ _ ≤ ∫⁻ y in s, ⨆ x ∈ s, f x ∂μ := setLIntegral_mono' hs fun x hx ↦ le_iSup₂ (f := fun x _ ↦ f x) x hx _ = (⨆ x ∈ s, f x) * μ s := by simp theorem lintegral_congr_ae {f g : α → ℝ≥0∞} (h : f =ᵐ[μ] g) : ∫⁻ a, f a ∂μ = ∫⁻ a, g a ∂μ := le_antisymm (lintegral_mono_ae <| h.le) (lintegral_mono_ae <| h.symm.le) theorem lintegral_congr {f g : α → ℝ≥0∞} (h : ∀ a, f a = g a) : ∫⁻ a, f a ∂μ = ∫⁻ a, g a ∂μ := by simp only [h] theorem setLIntegral_congr {f : α → ℝ≥0∞} {s t : Set α} (h : s =ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := by rw [Measure.restrict_congr_set h] theorem setLIntegral_congr_fun_ae {f g : α → ℝ≥0∞} {s : Set α} (hs : MeasurableSet s) (hfg : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in s, g x ∂μ := by rw [lintegral_congr_ae] rw [EventuallyEq] rwa [ae_restrict_iff' hs] theorem setLIntegral_congr_fun {f g : α → ℝ≥0∞} {s : Set α} (hs : MeasurableSet s) (hfg : EqOn f g s) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in s, g x ∂μ := setLIntegral_congr_fun_ae hs <| Eventually.of_forall hfg lemma setLIntegral_eq_zero {f : α → ℝ≥0∞} {s : Set α} (hs : MeasurableSet s) (h's : EqOn f 0 s) : ∫⁻ x in s, f x ∂μ = 0 := by simp [setLIntegral_congr_fun hs h's] section theorem lintegral_eq_zero_of_ae_eq_zero {f : α → ℝ≥0∞} (h : f =ᵐ[μ] 0) : ∫⁻ a, f a ∂μ = 0 := (lintegral_congr_ae h).trans lintegral_zero /-- The Lebesgue integral is zero iff the function is a.e. zero. The measurability assumption is necessary, otherwise there are counterexamples: for instance, the conclusion fails if `f` is the characteristic function of a Vitali set. -/ @[simp] theorem lintegral_eq_zero_iff' {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) : ∫⁻ a, f a ∂μ = 0 ↔ f =ᵐ[μ] 0 := by -- The proof implicitly uses Markov's inequality, -- but it has been inlined for the sake of imports refine ⟨fun h ↦ ?_, lintegral_eq_zero_of_ae_eq_zero⟩ have meas_levels_0 : ∀ ε > 0, μ { x | ε ≤ f x } = 0 := fun ε εpos ↦ by by_contra! h'; rw [← zero_lt_iff] at h' refine ((mul_pos_iff.mpr ⟨εpos, h'⟩).trans_le ?_).ne' h calc _ ≥ ∫⁻ a in {x | ε ≤ f x}, f a ∂μ := setLIntegral_le_lintegral _ _ _ ≥ ∫⁻ _ in {x | ε ≤ f x}, ε ∂μ := setLIntegral_mono_ae hf.restrict (ae_of_all μ fun _ ↦ id) _ = _ := setLIntegral_const _ _ obtain ⟨u, -, bu, tu⟩ := exists_seq_strictAnti_tendsto' (α := ℝ≥0∞) zero_lt_one have u_union : {x | f x ≠ 0} = ⋃ n, {x | u n ≤ f x} := by ext x; rw [mem_iUnion, mem_setOf_eq, ← zero_lt_iff] rw [ENNReal.tendsto_atTop_zero] at tu constructor <;> intro h' · obtain ⟨n, hn⟩ := tu _ h'; use n, hn _ le_rfl · obtain ⟨n, hn⟩ := h'; exact (bu n).1.trans_le hn have res := measure_iUnion_null_iff.mpr fun n ↦ meas_levels_0 _ (bu n).1 rwa [← u_union] at res /-- The measurability assumption is necessary, otherwise there are counterexamples: for instance, the conclusion fails if `f` is the characteristic function of a Vitali set. -/ @[simp] theorem lintegral_eq_zero_iff {f : α → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a, f a ∂μ = 0 ↔ f =ᵐ[μ] 0 := lintegral_eq_zero_iff' hf.aemeasurable /-- The measurability assumption is necessary, otherwise there are counterexamples: for instance, the conclusion fails if `s = univ` and `f` is the characteristic function of a Vitali set. -/ theorem setLIntegral_eq_zero_iff' {s : Set α} (hs : MeasurableSet s) {f : α → ℝ≥0∞} (hf : AEMeasurable f (μ.restrict s)) : ∫⁻ a in s, f a ∂μ = 0 ↔ ∀ᵐ x ∂μ, x ∈ s → f x = 0 := (lintegral_eq_zero_iff' hf).trans (ae_restrict_iff' hs) theorem setLIntegral_eq_zero_iff {s : Set α} (hs : MeasurableSet s) {f : α → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a in s, f a ∂μ = 0 ↔ ∀ᵐ x ∂μ, x ∈ s → f x = 0 := setLIntegral_eq_zero_iff' hs hf.aemeasurable theorem lintegral_pos_iff_support {f : α → ℝ≥0∞} (hf : Measurable f) : (0 < ∫⁻ a, f a ∂μ) ↔ 0 < μ (Function.support f) := by simp [pos_iff_ne_zero, hf, Filter.EventuallyEq, ae_iff, Function.support] theorem setLIntegral_pos_iff {f : α → ℝ≥0∞} (hf : Measurable f) {s : Set α} : 0 < ∫⁻ a in s, f a ∂μ ↔ 0 < μ (Function.support f ∩ s) := by rw [lintegral_pos_iff_support hf, Measure.restrict_apply (measurableSet_support hf)] @[deprecated (since := "2025-04-22")] alias setLintegral_pos_iff := setLIntegral_pos_iff end /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. This lemma states this fact in terms of `ε` and `δ`. -/ theorem exists_pos_setLIntegral_lt_of_measure_lt {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ δ > 0, ∀ s, μ s < δ → ∫⁻ x in s, f x ∂μ < ε := by rcases exists_between (pos_iff_ne_zero.mpr hε) with ⟨ε₂, hε₂0, hε₂ε⟩ rcases exists_between hε₂0 with ⟨ε₁, hε₁0, hε₁₂⟩ rcases exists_simpleFunc_forall_lintegral_sub_lt_of_pos h hε₁0.ne' with ⟨φ, _, hφ⟩ rcases φ.exists_forall_le with ⟨C, hC⟩ use (ε₂ - ε₁) / C, ENNReal.div_pos_iff.2 ⟨(tsub_pos_iff_lt.2 hε₁₂).ne', ENNReal.coe_ne_top⟩ refine fun s hs => lt_of_le_of_lt ?_ hε₂ε simp only [lintegral_eq_nnreal, iSup_le_iff] intro ψ hψ calc (map (↑) ψ).lintegral (μ.restrict s) ≤ (map (↑) φ).lintegral (μ.restrict s) + (map (↑) (ψ - φ)).lintegral (μ.restrict s) := by rw [← SimpleFunc.add_lintegral, ← SimpleFunc.map_add @ENNReal.coe_add] refine SimpleFunc.lintegral_mono (fun x => ?_) le_rfl simp only [add_tsub_eq_max, le_max_right, coe_map, Function.comp_apply, SimpleFunc.coe_add, SimpleFunc.coe_sub, Pi.add_apply, Pi.sub_apply, ENNReal.coe_max (φ x) (ψ x)] _ ≤ (map (↑) φ).lintegral (μ.restrict s) + ε₁ := by gcongr refine le_trans ?_ (hφ _ hψ).le exact SimpleFunc.lintegral_mono le_rfl Measure.restrict_le_self _ ≤ (SimpleFunc.const α (C : ℝ≥0∞)).lintegral (μ.restrict s) + ε₁ := by gcongr exact fun x ↦ ENNReal.coe_le_coe.2 (hC x) _ = C * μ s + ε₁ := by simp only [← SimpleFunc.lintegral_eq_lintegral, coe_const, lintegral_const, Measure.restrict_apply, MeasurableSet.univ, univ_inter, Function.const] _ ≤ C * ((ε₂ - ε₁) / C) + ε₁ := by gcongr _ ≤ ε₂ - ε₁ + ε₁ := by gcongr; apply mul_div_le _ = ε₂ := tsub_add_cancel_of_le hε₁₂.le /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ theorem tendsto_setLIntegral_zero {ι} {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞) {l : Filter ι} {s : ι → Set α} (hl : Tendsto (μ ∘ s) l (𝓝 0)) : Tendsto (fun i => ∫⁻ x in s i, f x ∂μ) l (𝓝 0) := by simp only [ENNReal.nhds_zero, tendsto_iInf, tendsto_principal, mem_Iio, ← pos_iff_ne_zero] at hl ⊢ intro ε ε0 rcases exists_pos_setLIntegral_lt_of_measure_lt h ε0.ne' with ⟨δ, δ0, hδ⟩ exact (hl δ δ0).mono fun i => hδ _ @[simp] theorem lintegral_smul_measure {R : Type*} [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0∞ ℝ≥0∞] (c : R) (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂c • μ = c • ∫⁻ a, f a ∂μ := by simp only [lintegral, iSup_subtype', SimpleFunc.lintegral_smul, ENNReal.smul_iSup] lemma setLIntegral_smul_measure {R : Type*} [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0∞ ℝ≥0∞] (c : R) (f : α → ℝ≥0∞) (s : Set α) : ∫⁻ a in s, f a ∂(c • μ) = c • ∫⁻ a in s, f a ∂μ := by rw [Measure.restrict_smul, lintegral_smul_measure] @[simp] theorem lintegral_zero_measure {m : MeasurableSpace α} (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂(0 : Measure α) = 0 := by simp [lintegral] @[simp] theorem lintegral_add_measure (f : α → ℝ≥0∞) (μ ν : Measure α) : ∫⁻ a, f a ∂(μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν := by simp only [lintegral, SimpleFunc.lintegral_add, iSup_subtype'] refine (ENNReal.iSup_add_iSup ?_).symm rintro ⟨φ, hφ⟩ ⟨ψ, hψ⟩ refine ⟨⟨φ ⊔ ψ, sup_le hφ hψ⟩, ?_⟩ gcongr exacts [le_sup_left, le_sup_right] @[simp] theorem lintegral_finset_sum_measure {ι} (s : Finset ι) (f : α → ℝ≥0∞) (μ : ι → Measure α) : ∫⁻ a, f a ∂(∑ i ∈ s, μ i) = ∑ i ∈ s, ∫⁻ a, f a ∂μ i := let F : Measure α →+ ℝ≥0∞ := { toFun := (lintegral · f), map_zero' := lintegral_zero_measure f, map_add' := lintegral_add_measure f } map_sum F μ s @[simp] theorem lintegral_sum_measure {m : MeasurableSpace α} {ι} (f : α → ℝ≥0∞) (μ : ι → Measure α) : ∫⁻ a, f a ∂Measure.sum μ = ∑' i, ∫⁻ a, f a ∂μ i := by simp_rw [ENNReal.tsum_eq_iSup_sum, ← lintegral_finset_sum_measure, lintegral, SimpleFunc.lintegral_sum, ENNReal.tsum_eq_iSup_sum, SimpleFunc.lintegral_finset_sum, iSup_comm (ι := Finset ι)] theorem hasSum_lintegral_measure {ι} {_ : MeasurableSpace α} (f : α → ℝ≥0∞) (μ : ι → Measure α) : HasSum (fun i => ∫⁻ a, f a ∂μ i) (∫⁻ a, f a ∂Measure.sum μ) := (lintegral_sum_measure f μ).symm ▸ ENNReal.summable.hasSum @[simp] theorem lintegral_of_isEmpty {α} [MeasurableSpace α] [IsEmpty α] (μ : Measure α) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = 0 := by have : Subsingleton (Measure α) := inferInstance convert lintegral_zero_measure f theorem setLIntegral_empty (f : α → ℝ≥0∞) : ∫⁻ x in ∅, f x ∂μ = 0 := by rw [Measure.restrict_empty, lintegral_zero_measure] theorem setLIntegral_univ (f : α → ℝ≥0∞) : ∫⁻ x in univ, f x ∂μ = ∫⁻ x, f x ∂μ := by rw [Measure.restrict_univ] theorem setLIntegral_measure_zero (s : Set α) (f : α → ℝ≥0∞) (hs' : μ s = 0) : ∫⁻ x in s, f x ∂μ = 0 := by convert lintegral_zero_measure _ exact Measure.restrict_eq_zero.2 hs' -- TODO: Need a better way of rewriting inside of an integral theorem lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ℝ≥0∞) : ∫⁻ a, g (f a) ∂μ = ∫⁻ a, g (f' a) ∂μ := lintegral_congr_ae <| h.mono fun a h => by dsimp only; rw [h] -- TODO: Need a better way of rewriting inside of an integral theorem lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁') (h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ℝ≥0∞) : ∫⁻ a, g (f₁ a) (f₂ a) ∂μ = ∫⁻ a, g (f₁' a) (f₂' a) ∂μ := lintegral_congr_ae <| h₁.mp <| h₂.mono fun _ h₂ h₁ => by dsimp only; rw [h₁, h₂] theorem lintegral_indicator_le (f : α → ℝ≥0∞) (s : Set α) : ∫⁻ a, s.indicator f a ∂μ ≤ ∫⁻ a in s, f a ∂μ := by simp only [lintegral] apply iSup_le (fun g ↦ (iSup_le (fun hg ↦ ?_))) have : g ≤ f := hg.trans (indicator_le_self s f) refine le_iSup_of_le g (le_iSup_of_le this (le_of_eq ?_)) rw [lintegral_restrict, SimpleFunc.lintegral] congr with t by_cases H : t = 0 · simp [H] congr with x simp only [mem_preimage, mem_singleton_iff, mem_inter_iff, iff_self_and] rintro rfl contrapose! H simpa [H] using hg x @[simp] theorem lintegral_indicator {s : Set α} (hs : MeasurableSet s) (f : α → ℝ≥0∞) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := by apply le_antisymm (lintegral_indicator_le f s) simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, iSup_subtype'] refine iSup_mono' (Subtype.forall.2 fun φ hφ => ?_) refine ⟨⟨φ.restrict s, fun x => ?_⟩, le_rfl⟩ simp [hφ x, hs, indicator_le_indicator] lemma setLIntegral_indicator {s t : Set α} (hs : MeasurableSet s) (f : α → ℝ≥0∞) : ∫⁻ a in t, s.indicator f a ∂μ = ∫⁻ a in s ∩ t, f a ∂μ := by rw [lintegral_indicator hs, Measure.restrict_restrict hs] theorem lintegral_indicator₀ {s : Set α} (hs : NullMeasurableSet s μ) (f : α → ℝ≥0∞) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := by rw [← lintegral_congr_ae (indicator_ae_eq_of_ae_eq_set hs.toMeasurable_ae_eq), lintegral_indicator (measurableSet_toMeasurable _ _), Measure.restrict_congr_set hs.toMeasurable_ae_eq] lemma setLIntegral_indicator₀ (f : α → ℝ≥0∞) {s t : Set α} (hs : NullMeasurableSet s (μ.restrict t)) : ∫⁻ a in t, s.indicator f a ∂μ = ∫⁻ a in s ∩ t, f a ∂μ := by rw [lintegral_indicator₀ hs, Measure.restrict_restrict₀ hs] theorem lintegral_indicator_const_le (s : Set α) (c : ℝ≥0∞) : ∫⁻ a, s.indicator (fun _ => c) a ∂μ ≤ c * μ s := (lintegral_indicator_le _ _).trans (setLIntegral_const s c).le theorem lintegral_indicator_const₀ {s : Set α} (hs : NullMeasurableSet s μ) (c : ℝ≥0∞) : ∫⁻ a, s.indicator (fun _ => c) a ∂μ = c * μ s := by rw [lintegral_indicator₀ hs, setLIntegral_const] theorem lintegral_indicator_const {s : Set α} (hs : MeasurableSet s) (c : ℝ≥0∞) : ∫⁻ a, s.indicator (fun _ => c) a ∂μ = c * μ s := lintegral_indicator_const₀ hs.nullMeasurableSet c lemma setLIntegral_eq_of_support_subset {s : Set α} {f : α → ℝ≥0∞} (hsf : f.support ⊆ s) : ∫⁻ x in s, f x ∂μ = ∫⁻ x, f x ∂μ := by apply le_antisymm (setLIntegral_le_lintegral s fun x ↦ f x) apply le_trans (le_of_eq _) (lintegral_indicator_le _ _) congr with x simp only [indicator] split_ifs with h · rfl · exact Function.support_subset_iff'.1 hsf x h theorem setLIntegral_eq_const {f : α → ℝ≥0∞} (hf : Measurable f) (r : ℝ≥0∞) : ∫⁻ x in { x | f x = r }, f x ∂μ = r * μ { x | f x = r } := by have : ∀ x ∈ { x | f x = r }, f x = r := fun _ hx => hx rw [setLIntegral_congr_fun _ this] · rw [lintegral_const, Measure.restrict_apply MeasurableSet.univ, Set.univ_inter] · exact hf (measurableSet_singleton r) theorem lintegral_indicator_one_le (s : Set α) : ∫⁻ a, s.indicator 1 a ∂μ ≤ μ s := (lintegral_indicator_const_le _ _).trans <| (one_mul _).le @[simp] theorem lintegral_indicator_one₀ {s : Set α} (hs : NullMeasurableSet s μ) : ∫⁻ a, s.indicator 1 a ∂μ = μ s := (lintegral_indicator_const₀ hs _).trans <| one_mul _ theorem lintegral_indicator_one {s : Set α} (hs : MeasurableSet s) : ∫⁻ a, s.indicator 1 a ∂μ = μ s := by simp [hs] theorem Measure.ext_iff_lintegral (ν : Measure α) : μ = ν ↔ ∀ f : α → ℝ≥0∞, Measurable f → ∫⁻ a, f a ∂μ = ∫⁻ a, f a ∂ν := by refine ⟨fun h _ _ ↦ by rw [h], ?_⟩ intro h ext s hs simp only [← lintegral_indicator_one hs] exact h (s.indicator 1) ((measurable_indicator_const_iff 1).mpr hs) theorem Measure.ext_of_lintegral (ν : Measure α) (hμν : ∀ f : α → ℝ≥0∞, Measurable f → ∫⁻ a, f a ∂μ = ∫⁻ a, f a ∂ν) : μ = ν := (μ.ext_iff_lintegral ν).mpr hμν open Measure open scoped Function -- required for scoped `on` notation theorem lintegral_iUnion₀ [Countable β] {s : β → Set α} (hm : ∀ i, NullMeasurableSet (s i) μ) (hd : Pairwise (AEDisjoint μ on s)) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := by simp only [Measure.restrict_iUnion_ae hd hm, lintegral_sum_measure] theorem lintegral_iUnion [Countable β] {s : β → Set α} (hm : ∀ i, MeasurableSet (s i)) (hd : Pairwise (Disjoint on s)) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := lintegral_iUnion₀ (fun i => (hm i).nullMeasurableSet) hd.aedisjoint f theorem lintegral_biUnion₀ {t : Set β} {s : β → Set α} (ht : t.Countable) (hm : ∀ i ∈ t, NullMeasurableSet (s i) μ) (hd : t.Pairwise (AEDisjoint μ on s)) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i ∈ t, s i, f a ∂μ = ∑' i : t, ∫⁻ a in s i, f a ∂μ := by haveI := ht.toEncodable rw [biUnion_eq_iUnion, lintegral_iUnion₀ (SetCoe.forall'.1 hm) (hd.subtype _ _)] theorem lintegral_biUnion {t : Set β} {s : β → Set α} (ht : t.Countable) (hm : ∀ i ∈ t, MeasurableSet (s i)) (hd : t.PairwiseDisjoint s) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i ∈ t, s i, f a ∂μ = ∑' i : t, ∫⁻ a in s i, f a ∂μ := lintegral_biUnion₀ ht (fun i hi => (hm i hi).nullMeasurableSet) hd.aedisjoint f theorem lintegral_biUnion_finset₀ {s : Finset β} {t : β → Set α} (hd : Set.Pairwise (↑s) (AEDisjoint μ on t)) (hm : ∀ b ∈ s, NullMeasurableSet (t b) μ) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ b ∈ s, t b, f a ∂μ = ∑ b ∈ s, ∫⁻ a in t b, f a ∂μ := by simp only [← Finset.mem_coe, lintegral_biUnion₀ s.countable_toSet hm hd, ← Finset.tsum_subtype'] theorem lintegral_biUnion_finset {s : Finset β} {t : β → Set α} (hd : Set.PairwiseDisjoint (↑s) t) (hm : ∀ b ∈ s, MeasurableSet (t b)) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ b ∈ s, t b, f a ∂μ = ∑ b ∈ s, ∫⁻ a in t b, f a ∂μ := lintegral_biUnion_finset₀ hd.aedisjoint (fun b hb => (hm b hb).nullMeasurableSet) f theorem lintegral_iUnion_le [Countable β] (s : β → Set α) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ := by rw [← lintegral_sum_measure] exact lintegral_mono' restrict_iUnion_le le_rfl theorem lintegral_union {f : α → ℝ≥0∞} {A B : Set α} (hB : MeasurableSet B) (hAB : Disjoint A B) : ∫⁻ a in A ∪ B, f a ∂μ = ∫⁻ a in A, f a ∂μ + ∫⁻ a in B, f a ∂μ := by rw [restrict_union hAB hB, lintegral_add_measure] theorem lintegral_union_le (f : α → ℝ≥0∞) (s t : Set α) : ∫⁻ a in s ∪ t, f a ∂μ ≤ ∫⁻ a in s, f a ∂μ + ∫⁻ a in t, f a ∂μ := by rw [← lintegral_add_measure] exact lintegral_mono' (restrict_union_le _ _) le_rfl theorem lintegral_inter_add_diff {B : Set α} (f : α → ℝ≥0∞) (A : Set α) (hB : MeasurableSet B) : ∫⁻ x in A ∩ B, f x ∂μ + ∫⁻ x in A \ B, f x ∂μ = ∫⁻ x in A, f x ∂μ := by rw [← lintegral_add_measure, restrict_inter_add_diff _ hB] theorem lintegral_add_compl (f : α → ℝ≥0∞) {A : Set α} (hA : MeasurableSet A) : ∫⁻ x in A, f x ∂μ + ∫⁻ x in Aᶜ, f x ∂μ = ∫⁻ x, f x ∂μ := by rw [← lintegral_add_measure, Measure.restrict_add_restrict_compl hA] lemma lintegral_piecewise (hs : MeasurableSet s) (f g : α → ℝ≥0∞) [∀ j, Decidable (j ∈ s)] : ∫⁻ a, s.piecewise f g a ∂μ = ∫⁻ a in s, f a ∂μ + ∫⁻ a in sᶜ, g a ∂μ := by rw [← lintegral_add_compl _ hs] congr 1 · exact setLIntegral_congr_fun hs <| fun _ ↦ Set.piecewise_eq_of_mem _ _ _ · exact setLIntegral_congr_fun hs.compl <| fun _ ↦ Set.piecewise_eq_of_notMem _ _ _ theorem setLIntegral_compl {f : α → ℝ≥0∞} {s : Set α} (hsm : MeasurableSet s) (hfs : ∫⁻ x in s, f x ∂μ ≠ ∞) : ∫⁻ x in sᶜ, f x ∂μ = ∫⁻ x, f x ∂μ - ∫⁻ x in s, f x ∂μ := by rw [← lintegral_add_compl (μ := μ) f hsm, ENNReal.add_sub_cancel_left hfs] @[deprecated (since := "2025-04-22")] alias setLintegral_compl := setLIntegral_compl theorem setLIntegral_iUnion_of_directed {ι : Type*} [Countable ι] (f : α → ℝ≥0∞) {s : ι → Set α} (hd : Directed (· ⊆ ·) s) : ∫⁻ x in ⋃ i, s i, f x ∂μ = ⨆ i, ∫⁻ x in s i, f x ∂μ := by simp only [lintegral_def, iSup_comm (ι := ι), SimpleFunc.lintegral_restrict_iUnion_of_directed _ hd] theorem lintegral_max {f g : α → ℝ≥0∞} (hf : Measurable f) (hg : Measurable g) : ∫⁻ x, max (f x) (g x) ∂μ = ∫⁻ x in { x | f x ≤ g x }, g x ∂μ + ∫⁻ x in { x | g x < f x }, f x ∂μ := by have hm : MeasurableSet { x | f x ≤ g x } := measurableSet_le hf hg rw [← lintegral_add_compl (fun x => max (f x) (g x)) hm] simp only [← compl_setOf, ← not_le] refine congr_arg₂ (· + ·) (setLIntegral_congr_fun hm ?_) (setLIntegral_congr_fun hm.compl ?_) exacts [fun x => max_eq_right (a := f x) (b := g x), fun x (hx : ¬ f x ≤ g x) => max_eq_left (not_le.1 hx).le] theorem setLIntegral_max {f g : α → ℝ≥0∞} (hf : Measurable f) (hg : Measurable g) (s : Set α) : ∫⁻ x in s, max (f x) (g x) ∂μ = ∫⁻ x in s ∩ { x | f x ≤ g x }, g x ∂μ + ∫⁻ x in s ∩ { x | g x < f x }, f x ∂μ := by rw [lintegral_max hf hg, restrict_restrict, restrict_restrict, inter_comm s, inter_comm s] exacts [measurableSet_lt hg hf, measurableSet_le hf hg] /-- Lebesgue integral of a bounded function over a set of finite measure is finite. Note that this lemma assumes no regularity of either `f` or `s`. -/ theorem setLIntegral_lt_top_of_le_nnreal {s : Set α} (hs : μ s ≠ ∞) {f : α → ℝ≥0∞} (hbdd : ∃ y : ℝ≥0, ∀ x ∈ s, f x ≤ y) : ∫⁻ x in s, f x ∂μ < ∞ := by obtain ⟨M, hM⟩ := hbdd refine lt_of_le_of_lt (setLIntegral_mono measurable_const hM) ?_ simp [ENNReal.mul_lt_top, hs.lt_top] /-- Lebesgue integral of a bounded function over a set of finite measure is finite. Note that this lemma assumes no regularity of either `f` or `s`. -/ theorem setLIntegral_lt_top_of_bddAbove {s : Set α} (hs : μ s ≠ ∞) {f : α → ℝ≥0} (hbdd : BddAbove (f '' s)) : ∫⁻ x in s, f x ∂μ < ∞ := setLIntegral_lt_top_of_le_nnreal hs <| hbdd.imp fun _M hM _x hx ↦ ENNReal.coe_le_coe.2 <| hM (mem_image_of_mem f hx) theorem setLIntegral_lt_top_of_isCompact [TopologicalSpace α] {s : Set α} (hs : μ s ≠ ∞) (hsc : IsCompact s) {f : α → ℝ≥0} (hf : Continuous f) : ∫⁻ x in s, f x ∂μ < ∞ := setLIntegral_lt_top_of_bddAbove hs (hsc.image hf).bddAbove end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue/Markov.lean
import Mathlib.MeasureTheory.Integral.Lebesgue.Add /-! # Markov's inequality The classical form of Markov's inequality states that for a nonnegative random variable `X` and real number `ε > 0`, `P(X ≥ ε) ≤ E(X) / ε`. Multiplying both sides by the measure of the space gives the measure-theoretic form: ``` μ { x | ε ≤ f x } ≤ (∫⁻ a, f a ∂μ) / ε ``` This file proves a few variants of the inequality and other lemmas that depend on it. -/ namespace MeasureTheory open Set Filter ENNReal Topology variable {α : Type*} [MeasurableSpace α] {μ : Measure α} /-- A version of **Markov's inequality** for two functions. It doesn't follow from the standard Markov's inequality because we only assume measurability of `g`, not `f`. -/ theorem lintegral_add_mul_meas_add_le_le_lintegral {f g : α → ℝ≥0∞} (hle : f ≤ᵐ[μ] g) (hg : AEMeasurable g μ) (ε : ℝ≥0∞) : ∫⁻ a, f a ∂μ + ε * μ { x | f x + ε ≤ g x } ≤ ∫⁻ a, g a ∂μ := by rcases exists_measurable_le_lintegral_eq μ f with ⟨φ, hφm, hφ_le, hφ_eq⟩ calc ∫⁻ x, f x ∂μ + ε * μ { x | f x + ε ≤ g x } = ∫⁻ x, φ x ∂μ + ε * μ { x | f x + ε ≤ g x } := by rw [hφ_eq] _ ≤ ∫⁻ x, φ x ∂μ + ε * μ { x | φ x + ε ≤ g x } := by gcongr exact hφ_le _ _ = ∫⁻ x, φ x + indicator { x | φ x + ε ≤ g x } (fun _ => ε) x ∂μ := by rw [lintegral_add_left hφm, lintegral_indicator₀, setLIntegral_const] exact measurableSet_le (hφm.nullMeasurable.measurable'.add_const _) hg.nullMeasurable _ ≤ ∫⁻ x, g x ∂μ := lintegral_mono_ae (hle.mono fun x hx₁ => ?_) simp only [indicator_apply]; split_ifs with hx₂ exacts [hx₂, (add_zero _).trans_le <| (hφ_le x).trans hx₁] /-- **Markov's inequality** also known as **Chebyshev's first inequality**. -/ theorem mul_meas_ge_le_lintegral₀ {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) (ε : ℝ≥0∞) : ε * μ { x | ε ≤ f x } ≤ ∫⁻ a, f a ∂μ := by simpa only [lintegral_zero, zero_add] using lintegral_add_mul_meas_add_le_le_lintegral (ae_of_all _ fun x => zero_le (f x)) hf ε /-- **Markov's inequality** also known as **Chebyshev's first inequality**. For a version assuming `AEMeasurable`, see `mul_meas_ge_le_lintegral₀`. -/ theorem mul_meas_ge_le_lintegral {f : α → ℝ≥0∞} (hf : Measurable f) (ε : ℝ≥0∞) : ε * μ { x | ε ≤ f x } ≤ ∫⁻ a, f a ∂μ := mul_meas_ge_le_lintegral₀ hf.aemeasurable ε lemma meas_le_lintegral₀ {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) {s : Set α} (hs : ∀ x ∈ s, 1 ≤ f x) : μ s ≤ ∫⁻ a, f a ∂μ := by apply le_trans _ (mul_meas_ge_le_lintegral₀ hf 1) rw [one_mul] exact measure_mono hs lemma lintegral_le_meas {s : Set α} {f : α → ℝ≥0∞} (hf : ∀ a, f a ≤ 1) (h'f : ∀ a ∈ sᶜ, f a = 0) : ∫⁻ a, f a ∂μ ≤ μ s := by apply (lintegral_mono (fun x ↦ ?_)).trans (lintegral_indicator_one_le s) by_cases hx : x ∈ s · simpa [hx] using hf x · simpa [hx] using h'f x hx lemma setLIntegral_le_meas {s t : Set α} (hs : MeasurableSet s) {f : α → ℝ≥0∞} (hf : ∀ a ∈ s, a ∈ t → f a ≤ 1) (hf' : ∀ a ∈ s, a ∉ t → f a = 0) : ∫⁻ a in s, f a ∂μ ≤ μ t := by rw [← lintegral_indicator hs] refine lintegral_le_meas (fun a ↦ ?_) (by simp_all) by_cases has : a ∈ s <;> [by_cases hat : a ∈ t; skip] <;> simp [*] theorem lintegral_eq_top_of_measure_eq_top_ne_zero {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) (hμf : μ {x | f x = ∞} ≠ 0) : ∫⁻ x, f x ∂μ = ∞ := eq_top_iff.mpr <| calc ∞ = ∞ * μ { x | ∞ ≤ f x } := by simp [hμf] _ ≤ ∫⁻ x, f x ∂μ := mul_meas_ge_le_lintegral₀ hf ∞ theorem setLIntegral_eq_top_of_measure_eq_top_ne_zero {f : α → ℝ≥0∞} {s : Set α} (hf : AEMeasurable f (μ.restrict s)) (hμf : μ ({x ∈ s | f x = ∞}) ≠ 0) : ∫⁻ x in s, f x ∂μ = ∞ := lintegral_eq_top_of_measure_eq_top_ne_zero hf <| mt (eq_bot_mono <| by rw [← setOf_inter_eq_sep]; exact Measure.le_restrict_apply _ _) hμf @[deprecated (since := "2025-04-22")] alias setLintegral_eq_top_of_measure_eq_top_ne_zero := setLIntegral_eq_top_of_measure_eq_top_ne_zero theorem measure_eq_top_of_lintegral_ne_top {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) (hμf : ∫⁻ x, f x ∂μ ≠ ∞) : μ {x | f x = ∞} = 0 := of_not_not fun h => hμf <| lintegral_eq_top_of_measure_eq_top_ne_zero hf h theorem measure_eq_top_of_setLIntegral_ne_top {f : α → ℝ≥0∞} {s : Set α} (hf : AEMeasurable f (μ.restrict s)) (hμf : ∫⁻ x in s, f x ∂μ ≠ ∞) : μ ({x ∈ s | f x = ∞}) = 0 := of_not_not fun h => hμf <| setLIntegral_eq_top_of_measure_eq_top_ne_zero hf h @[deprecated (since := "2025-04-22")] alias measure_eq_top_of_setLintegral_ne_top := measure_eq_top_of_setLIntegral_ne_top /-- **Markov's inequality**, also known as **Chebyshev's first inequality**. -/ theorem meas_ge_le_lintegral_div {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) {ε : ℝ≥0∞} (hε : ε ≠ 0) (hε' : ε ≠ ∞) : μ { x | ε ≤ f x } ≤ (∫⁻ a, f a ∂μ) / ε := (ENNReal.le_div_iff_mul_le (Or.inl hε) (Or.inl hε')).2 <| by rw [mul_comm] exact mul_meas_ge_le_lintegral₀ hf ε theorem ae_eq_of_ae_le_of_lintegral_le {f g : α → ℝ≥0∞} (hfg : f ≤ᵐ[μ] g) (hf : ∫⁻ x, f x ∂μ ≠ ∞) (hg : AEMeasurable g μ) (hgf : ∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ) : f =ᵐ[μ] g := by have : ∀ n : ℕ, ∀ᵐ x ∂μ, g x < f x + (n : ℝ≥0∞)⁻¹ := by intro n simp only [ae_iff, not_lt] have : ∫⁻ x, f x ∂μ + (↑n)⁻¹ * μ { x : α | f x + (n : ℝ≥0∞)⁻¹ ≤ g x } ≤ ∫⁻ x, f x ∂μ := (lintegral_add_mul_meas_add_le_le_lintegral hfg hg n⁻¹).trans hgf rw [(ENNReal.cancel_of_ne hf).add_le_iff_nonpos_right, nonpos_iff_eq_zero, mul_eq_zero] at this exact this.resolve_left (ENNReal.inv_ne_zero.2 (ENNReal.natCast_ne_top _)) refine hfg.mp ((ae_all_iff.2 this).mono fun x hlt hle => hle.antisymm ?_) suffices Tendsto (fun n : ℕ => f x + (n : ℝ≥0∞)⁻¹) atTop (𝓝 (f x)) from ge_of_tendsto' this fun i => (hlt i).le simpa only [inv_top, add_zero] using tendsto_const_nhds.add (ENNReal.tendsto_inv_iff.2 ENNReal.tendsto_nat_nhds_top) theorem lintegral_strict_mono_of_ae_le_of_frequently_ae_lt {f g : α → ℝ≥0∞} (hg : AEMeasurable g μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h_le : f ≤ᵐ[μ] g) (h : ∃ᵐ x ∂μ, f x ≠ g x) : ∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ := by contrapose! h simp only [not_frequently, Ne, Classical.not_not] exact ae_eq_of_ae_le_of_lintegral_le h_le hfi hg h theorem lintegral_strict_mono_of_ae_le_of_ae_lt_on {f g : α → ℝ≥0∞} (hg : AEMeasurable g μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h_le : f ≤ᵐ[μ] g) {s : Set α} (hμs : μ s ≠ 0) (h : ∀ᵐ x ∂μ, x ∈ s → f x < g x) : ∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ := lintegral_strict_mono_of_ae_le_of_frequently_ae_lt hg hfi h_le <| ((frequently_ae_mem_iff.2 hμs).and_eventually h).mono fun _x hx => (hx.2 hx.1).ne theorem lintegral_strict_mono {f g : α → ℝ≥0∞} (hμ : μ ≠ 0) (hg : AEMeasurable g μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h : ∀ᵐ x ∂μ, f x < g x) : ∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ := by rw [Ne, ← Measure.measure_univ_eq_zero] at hμ refine lintegral_strict_mono_of_ae_le_of_ae_lt_on hg hfi (ae_le_of_ae_lt h) hμ ?_ simpa using h theorem setLIntegral_strict_mono {f g : α → ℝ≥0∞} {s : Set α} (hsm : MeasurableSet s) (hs : μ s ≠ 0) (hg : Measurable g) (hfi : ∫⁻ x in s, f x ∂μ ≠ ∞) (h : ∀ᵐ x ∂μ, x ∈ s → f x < g x) : ∫⁻ x in s, f x ∂μ < ∫⁻ x in s, g x ∂μ := lintegral_strict_mono (by simp [hs]) hg.aemeasurable hfi ((ae_restrict_iff' hsm).mpr h) theorem ae_lt_top' {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) (h2f : ∫⁻ x, f x ∂μ ≠ ∞) : ∀ᵐ x ∂μ, f x < ∞ := by simp_rw [ae_iff, ENNReal.not_lt_top] exact measure_eq_top_of_lintegral_ne_top hf h2f theorem ae_lt_top {f : α → ℝ≥0∞} (hf : Measurable f) (h2f : ∫⁻ x, f x ∂μ ≠ ∞) : ∀ᵐ x ∂μ, f x < ∞ := ae_lt_top' hf.aemeasurable h2f end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue/Sub.lean
import Mathlib.MeasureTheory.Integral.Lebesgue.Add /-! # Subtraction of Lebesgue integrals In this file we first show that Lebesgue integrals can be subtracted with the expected results – `∫⁻ f - ∫⁻ g ≤ ∫⁻ (f - g)`, with equality if `g ≤ f` almost everywhere. Then we prove variants of the monotone convergence theorem that use this subtraction in their proofs. -/ open Filter ENNReal Topology namespace MeasureTheory variable {α β : Type*} [MeasurableSpace α] {μ : Measure α} theorem lintegral_sub' {f g : α → ℝ≥0∞} (hg : AEMeasurable g μ) (hg_fin : ∫⁻ a, g a ∂μ ≠ ∞) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := by refine ENNReal.eq_sub_of_add_eq hg_fin ?_ rw [← lintegral_add_right' _ hg] exact lintegral_congr_ae (h_le.mono fun x hx => tsub_add_cancel_of_le hx) theorem lintegral_sub {f g : α → ℝ≥0∞} (hg : Measurable g) (hg_fin : ∫⁻ a, g a ∂μ ≠ ∞) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := lintegral_sub' hg.aemeasurable hg_fin h_le theorem lintegral_sub_le' (f g : α → ℝ≥0∞) (hf : AEMeasurable f μ) : ∫⁻ x, g x ∂μ - ∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x - f x ∂μ := by rw [tsub_le_iff_right] by_cases hfi : ∫⁻ x, f x ∂μ = ∞ · rw [hfi, add_top] exact le_top · rw [← lintegral_add_right' _ hf] gcongr exact le_tsub_add theorem lintegral_sub_le (f g : α → ℝ≥0∞) (hf : Measurable f) : ∫⁻ x, g x ∂μ - ∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x - f x ∂μ := lintegral_sub_le' f g hf.aemeasurable /-- **Monotone convergence theorem** for nonincreasing sequences of functions. -/ theorem lintegral_iInf_ae {f : ℕ → α → ℝ≥0∞} (h_meas : ∀ n, Measurable (f n)) (h_mono : ∀ n : ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ ≠ ∞) : ∫⁻ a, ⨅ n, f n a ∂μ = ⨅ n, ∫⁻ a, f n a ∂μ := have fn_le_f0 : ∫⁻ a, ⨅ n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ := lintegral_mono fun _ => iInf_le_of_le 0 le_rfl have fn_le_f0' : ⨅ n, ∫⁻ a, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ := iInf_le_of_le 0 le_rfl (ENNReal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 <| show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅ n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - ⨅ n, ∫⁻ a, f n a ∂μ from calc ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅ n, f n a ∂μ = ∫⁻ a, f 0 a - ⨅ n, f n a ∂μ := (lintegral_sub (.iInf h_meas) (ne_top_of_le_ne_top h_fin <| lintegral_mono fun _ => iInf_le _ _) (ae_of_all _ fun _ => iInf_le _ _)).symm _ = ∫⁻ a, ⨆ n, f 0 a - f n a ∂μ := congr rfl (funext fun _ => ENNReal.sub_iInf) _ = ⨆ n, ∫⁻ a, f 0 a - f n a ∂μ := (lintegral_iSup_ae (fun n => (h_meas 0).sub (h_meas n)) fun n => (h_mono n).mono fun _ ha => tsub_le_tsub le_rfl ha) _ = ⨆ n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ := (have h_mono : ∀ᵐ a ∂μ, ∀ n : ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono have h_mono : ∀ n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := fun n => h_mono.mono fun a h => by induction n with | zero => rfl | succ n ih => exact (h n).trans ih congr_arg iSup <| funext fun n => lintegral_sub (h_meas _) (ne_top_of_le_ne_top h_fin <| lintegral_mono_ae <| h_mono n) (h_mono n)) _ = ∫⁻ a, f 0 a ∂μ - ⨅ n, ∫⁻ a, f n a ∂μ := ENNReal.sub_iInf.symm /-- **Monotone convergence theorem** for nonincreasing sequences of functions. -/ theorem lintegral_iInf {f : ℕ → α → ℝ≥0∞} (h_meas : ∀ n, Measurable (f n)) (h_anti : Antitone f) (h_fin : ∫⁻ a, f 0 a ∂μ ≠ ∞) : ∫⁻ a, ⨅ n, f n a ∂μ = ⨅ n, ∫⁻ a, f n a ∂μ := lintegral_iInf_ae h_meas (fun n => ae_of_all _ <| h_anti n.le_succ) h_fin theorem lintegral_iInf' {f : ℕ → α → ℝ≥0∞} (h_meas : ∀ n, AEMeasurable (f n) μ) (h_anti : ∀ᵐ a ∂μ, Antitone (fun i ↦ f i a)) (h_fin : ∫⁻ a, f 0 a ∂μ ≠ ∞) : ∫⁻ a, ⨅ n, f n a ∂μ = ⨅ n, ∫⁻ a, f n a ∂μ := by simp_rw [← iInf_apply] let p : α → (ℕ → ℝ≥0∞) → Prop := fun _ f' => Antitone f' have hp : ∀ᵐ x ∂μ, p x fun i => f i x := h_anti have h_ae_seq_mono : Antitone (aeSeq h_meas p) := by intro n m hnm x by_cases hx : x ∈ aeSeqSet h_meas p · exact aeSeq.prop_of_mem_aeSeqSet h_meas hx hnm · simp only [aeSeq, hx, if_false] exact le_rfl rw [lintegral_congr_ae (aeSeq.iInf h_meas hp).symm] simp_rw [iInf_apply] rw [lintegral_iInf (aeSeq.measurable h_meas p) h_ae_seq_mono] · congr exact funext fun n ↦ lintegral_congr_ae (aeSeq.aeSeq_n_eq_fun_n_ae h_meas hp n) · rwa [lintegral_congr_ae (aeSeq.aeSeq_n_eq_fun_n_ae h_meas hp 0)] /-- **Monotone convergence theorem** for an infimum over a directed family and indexed by a countable type. -/ theorem lintegral_iInf_directed_of_measurable [Countable β] {f : β → α → ℝ≥0∞} {μ : Measure α} (hμ : μ ≠ 0) (hf : ∀ b, Measurable (f b)) (hf_int : ∀ b, ∫⁻ a, f b a ∂μ ≠ ∞) (h_directed : Directed (· ≥ ·) f) : ∫⁻ a, ⨅ b, f b a ∂μ = ⨅ b, ∫⁻ a, f b a ∂μ := by cases nonempty_encodable β cases isEmpty_or_nonempty β · simp only [iInf_of_empty, lintegral_const, ENNReal.top_mul (Measure.measure_univ_ne_zero.mpr hμ)] inhabit β have : ∀ a, ⨅ b, f b a = ⨅ n, f (h_directed.sequence f n) a := by refine fun a => le_antisymm (le_iInf fun n => iInf_le _ _) (le_iInf fun b => iInf_le_of_le (Encodable.encode b + 1) ?_) exact h_directed.sequence_le b a calc ∫⁻ a, ⨅ b, f b a ∂μ _ = ∫⁻ a, ⨅ n, (f ∘ h_directed.sequence f) n a ∂μ := by simp only [this, Function.comp_apply] _ = ⨅ n, ∫⁻ a, (f ∘ h_directed.sequence f) n a ∂μ := by rw [lintegral_iInf ?_ h_directed.sequence_anti] · exact hf_int _ · exact fun n => hf _ _ = ⨅ b, ∫⁻ a, f b a ∂μ := by refine le_antisymm (le_iInf fun b => ?_) (le_iInf fun n => ?_) · exact iInf_le_of_le (Encodable.encode b + 1) (lintegral_mono <| h_directed.sequence_le b) · exact iInf_le (fun b => ∫⁻ a, f b a ∂μ) _ theorem lintegral_tendsto_of_tendsto_of_antitone {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} (hf : ∀ n, AEMeasurable (f n) μ) (h_anti : ∀ᵐ x ∂μ, Antitone fun n ↦ f n x) (h0 : ∫⁻ a, f 0 a ∂μ ≠ ∞) (h_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n ↦ f n x) atTop (𝓝 (F x))) : Tendsto (fun n ↦ ∫⁻ x, f n x ∂μ) atTop (𝓝 (∫⁻ x, F x ∂μ)) := by have : Antitone fun n ↦ ∫⁻ x, f n x ∂μ := fun i j hij ↦ lintegral_mono_ae (h_anti.mono fun x hx ↦ hx hij) suffices key : ∫⁻ x, F x ∂μ = ⨅ n, ∫⁻ x, f n x ∂μ by rw [key] exact tendsto_atTop_iInf this rw [← lintegral_iInf' hf h_anti h0] refine lintegral_congr_ae ?_ filter_upwards [h_anti, h_tendsto] with _ hx_anti hx_tendsto using tendsto_nhds_unique hx_tendsto (tendsto_atTop_iInf hx_anti) section UnifTight local infixr:25 " →ₛ " => SimpleFunc open Function in /-- If `f : α → ℝ≥0∞` has finite integral, then there exists a measurable set `s` of finite measure such that the integral of `f` over `sᶜ` is less than a given positive number. Also used to prove an `Lᵖ`-norm version in `MeasureTheory.MemLp.exists_eLpNorm_indicator_compl_le`. -/ theorem exists_setLIntegral_compl_lt {f : α → ℝ≥0∞} (hf : ∫⁻ a, f a ∂μ ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ s : Set α, MeasurableSet s ∧ μ s < ∞ ∧ ∫⁻ a in sᶜ, f a ∂μ < ε := by by_cases hf₀ : ∫⁻ a, f a ∂μ = 0 · exact ⟨∅, .empty, by simp, by simpa [hf₀, pos_iff_ne_zero]⟩ obtain ⟨g, hgf, hg_meas, hgsupp, hgε⟩ : ∃ g ≤ f, Measurable g ∧ μ (support g) < ∞ ∧ ∫⁻ a, f a ∂μ - ε < ∫⁻ a, g a ∂μ := by obtain ⟨g, hgf, hgε⟩ : ∃ (g : α →ₛ ℝ≥0∞) (_ : g ≤ f), ∫⁻ a, f a ∂μ - ε < g.lintegral μ := by simpa only [← lt_iSup_iff, ← lintegral_def] using ENNReal.sub_lt_self hf hf₀ hε refine ⟨g, hgf, g.measurable, ?_, by rwa [g.lintegral_eq_lintegral]⟩ exact SimpleFunc.FinMeasSupp.of_lintegral_ne_top <| ne_top_of_le_ne_top hf <| g.lintegral_eq_lintegral μ ▸ lintegral_mono hgf refine ⟨_, measurableSet_support hg_meas, hgsupp, ?_⟩ calc ∫⁻ a in (support g)ᶜ, f a ∂μ = ∫⁻ a in (support g)ᶜ, f a - g a ∂μ := setLIntegral_congr_fun (measurableSet_support hg_meas).compl <| by intro; simp_all _ ≤ ∫⁻ a, f a - g a ∂μ := setLIntegral_le_lintegral _ _ _ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := lintegral_sub hg_meas (ne_top_of_le_ne_top hf <| lintegral_mono hgf) (ae_of_all _ hgf) _ < ε := ENNReal.sub_lt_of_lt_add (lintegral_mono hgf) <| ENNReal.lt_add_of_sub_lt_left (.inl hf) hgε @[deprecated (since := "2025-04-22")] alias exists_setLintegral_compl_lt := exists_setLIntegral_compl_lt /-- For any function `f : α → ℝ≥0∞`, there exists a measurable function `g ≤ f` with the same integral over any measurable set. -/ theorem exists_measurable_le_setLIntegral_eq_of_integrable {f : α → ℝ≥0∞} (hf : ∫⁻ a, f a ∂μ ≠ ∞) : ∃ (g : α → ℝ≥0∞), Measurable g ∧ g ≤ f ∧ ∀ s : Set α, MeasurableSet s → ∫⁻ a in s, f a ∂μ = ∫⁻ a in s, g a ∂μ := by obtain ⟨g, hmg, hgf, hifg⟩ := exists_measurable_le_lintegral_eq (μ := μ) f use g, hmg, hgf refine fun s hms ↦ le_antisymm ?_ (lintegral_mono hgf) rw [← compl_compl s, setLIntegral_compl hms.compl, setLIntegral_compl hms.compl, hifg] · gcongr; apply hgf · rw [hifg] at hf exact ne_top_of_le_ne_top hf (setLIntegral_le_lintegral _ _) · exact ne_top_of_le_ne_top hf (setLIntegral_le_lintegral _ _) @[deprecated (since := "2025-04-22")] alias exists_measurable_le_setLintegral_eq_of_integrable := exists_measurable_le_setLIntegral_eq_of_integrable end UnifTight end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Lebesgue/Countable.lean
import Mathlib.MeasureTheory.Integral.Lebesgue.Map import Mathlib.MeasureTheory.Integral.Lebesgue.Markov import Mathlib.MeasureTheory.Measure.Count /-! # Lebesgue integral over finite and countable types, sets and measures The lemmas in this file require at least one of the following of the Lebesgue integral: * The type of the set of integration is finite or countable * The set of integration is finite or countable * The measure is finite, s-finite or sigma-finite -/ namespace MeasureTheory open Set ENNReal NNReal Measure variable {α : Type*} [MeasurableSpace α] {μ : Measure α} section FiniteMeasure theorem setLIntegral_const_lt_top [IsFiniteMeasure μ] (s : Set α) {c : ℝ≥0∞} (hc : c ≠ ∞) : ∫⁻ _ in s, c ∂μ < ∞ := by rw [lintegral_const] exact ENNReal.mul_lt_top hc.lt_top (measure_lt_top (μ.restrict s) univ) theorem lintegral_const_lt_top [IsFiniteMeasure μ] {c : ℝ≥0∞} (hc : c ≠ ∞) : ∫⁻ _, c ∂μ < ∞ := by simpa only [Measure.restrict_univ] using setLIntegral_const_lt_top (univ : Set α) hc lemma lintegral_eq_const [IsProbabilityMeasure μ] {f : α → ℝ≥0∞} {c : ℝ≥0∞} (hf : ∀ᵐ x ∂μ, f x = c) : ∫⁻ x, f x ∂μ = c := by simp [lintegral_congr_ae hf] lemma lintegral_le_const [IsProbabilityMeasure μ] {f : α → ℝ≥0∞} {c : ℝ≥0∞} (hf : ∀ᵐ x ∂μ, f x ≤ c) : ∫⁻ x, f x ∂μ ≤ c := (lintegral_mono_ae hf).trans_eq (by simp) lemma iInf_le_lintegral [IsProbabilityMeasure μ] (f : α → ℝ≥0∞) : ⨅ x, f x ≤ ∫⁻ x, f x ∂μ := le_trans (by simp) (iInf_mul_le_lintegral f) lemma lintegral_le_iSup [IsProbabilityMeasure μ] (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ ≤ ⨆ x, f x := le_trans (lintegral_le_iSup_mul f) (by simp) variable (μ) in theorem _root_.IsFiniteMeasure.lintegral_lt_top_of_bounded_to_ennreal [IsFiniteMeasure μ] {f : α → ℝ≥0∞} (f_bdd : ∃ c : ℝ≥0, ∀ x, f x ≤ c) : ∫⁻ x, f x ∂μ < ∞ := by rw [← μ.restrict_univ] refine setLIntegral_lt_top_of_le_nnreal (measure_ne_top _ _) ?_ simpa using f_bdd end FiniteMeasure section DiracAndCount theorem lintegral_dirac' (a : α) {f : α → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a, f a ∂dirac a = f a := by simp [lintegral_congr_ae (ae_eq_dirac' hf)] @[simp] theorem lintegral_dirac [MeasurableSingletonClass α] (a : α) (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂dirac a = f a := by simp [lintegral_congr_ae (ae_eq_dirac f)] theorem setLIntegral_dirac' {a : α} {f : α → ℝ≥0∞} (hf : Measurable f) {s : Set α} (hs : MeasurableSet s) [Decidable (a ∈ s)] : ∫⁻ x in s, f x ∂Measure.dirac a = if a ∈ s then f a else 0 := by rw [restrict_dirac' hs] split_ifs · exact lintegral_dirac' _ hf · exact lintegral_zero_measure _ theorem setLIntegral_dirac {a : α} (f : α → ℝ≥0∞) (s : Set α) [MeasurableSingletonClass α] [Decidable (a ∈ s)] : ∫⁻ x in s, f x ∂Measure.dirac a = if a ∈ s then f a else 0 := by rw [restrict_dirac] split_ifs · exact lintegral_dirac _ _ · exact lintegral_zero_measure _ theorem lintegral_count' {f : α → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a, f a ∂count = ∑' a, f a := by rw [count, lintegral_sum_measure] congr exact funext fun a => lintegral_dirac' a hf theorem lintegral_count [MeasurableSingletonClass α] (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂count = ∑' a, f a := by rw [count, lintegral_sum_measure] congr exact funext fun a => lintegral_dirac a f /-- Markov's inequality for the counting measure with hypothesis using `tsum` in `ℝ≥0∞`. -/ theorem _root_.ENNReal.count_const_le_le_of_tsum_le [MeasurableSingletonClass α] {a : α → ℝ≥0∞} (a_mble : Measurable a) {c : ℝ≥0∞} (tsum_le_c : ∑' i, a i ≤ c) {ε : ℝ≥0∞} (ε_ne_zero : ε ≠ 0) (ε_ne_top : ε ≠ ∞) : Measure.count { i : α | ε ≤ a i } ≤ c / ε := by rw [← lintegral_count] at tsum_le_c apply (MeasureTheory.meas_ge_le_lintegral_div a_mble.aemeasurable ε_ne_zero ε_ne_top).trans exact ENNReal.div_le_div tsum_le_c rfl.le /-- Markov's inequality for the counting measure with hypothesis using `tsum` in `ℝ≥0`. -/ theorem _root_.NNReal.count_const_le_le_of_tsum_le [MeasurableSingletonClass α] {a : α → ℝ≥0} (a_mble : Measurable a) (a_summable : Summable a) {c : ℝ≥0} (tsum_le_c : ∑' i, a i ≤ c) {ε : ℝ≥0} (ε_ne_zero : ε ≠ 0) : Measure.count { i : α | ε ≤ a i } ≤ c / ε := by rw [show (fun i => ε ≤ a i) = fun i => (ε : ℝ≥0∞) ≤ ((↑) ∘ a) i by simp only [ENNReal.coe_le_coe, Function.comp]] apply ENNReal.count_const_le_le_of_tsum_le (measurable_coe_nnreal_ennreal.comp a_mble) _ (mod_cast ε_ne_zero) (@ENNReal.coe_ne_top ε) convert ENNReal.coe_le_coe.mpr tsum_le_c simp_rw [Function.comp_apply] rw [ENNReal.tsum_coe_eq a_summable.hasSum] end DiracAndCount section Countable theorem lintegral_countable' [Countable α] [MeasurableSingletonClass α] (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂μ = ∑' a, f a * μ {a} := by conv_lhs => rw [← sum_smul_dirac μ, lintegral_sum_measure] congr 1 with a : 1 simp [mul_comm] theorem lintegral_singleton' {f : α → ℝ≥0∞} (hf : Measurable f) (a : α) : ∫⁻ x in {a}, f x ∂μ = f a * μ {a} := by simp [lintegral_dirac' _ hf, mul_comm] theorem lintegral_singleton [MeasurableSingletonClass α] (f : α → ℝ≥0∞) (a : α) : ∫⁻ x in {a}, f x ∂μ = f a * μ {a} := by simp [mul_comm] theorem lintegral_countable [MeasurableSingletonClass α] (f : α → ℝ≥0∞) {s : Set α} (hs : s.Countable) : ∫⁻ a in s, f a ∂μ = ∑' a : s, f a * μ {(a : α)} := calc ∫⁻ a in s, f a ∂μ = ∫⁻ a in ⋃ x ∈ s, {x}, f a ∂μ := by rw [biUnion_of_singleton] _ = ∑' a : s, ∫⁻ x in {(a : α)}, f x ∂μ := (lintegral_biUnion hs (fun _ _ => measurableSet_singleton _) (pairwiseDisjoint_fiber id s) _) _ = ∑' a : s, f a * μ {(a : α)} := by simp only [lintegral_singleton] theorem lintegral_insert [MeasurableSingletonClass α] {a : α} {s : Set α} (h : a ∉ s) (f : α → ℝ≥0∞) : ∫⁻ x in insert a s, f x ∂μ = f a * μ {a} + ∫⁻ x in s, f x ∂μ := by rw [← union_singleton, lintegral_union (measurableSet_singleton a), lintegral_singleton, add_comm] rwa [disjoint_singleton_right] theorem lintegral_finset [MeasurableSingletonClass α] (s : Finset α) (f : α → ℝ≥0∞) : ∫⁻ x in s, f x ∂μ = ∑ x ∈ s, f x * μ {x} := by simp only [lintegral_countable _ s.countable_toSet, ← Finset.tsum_subtype'] theorem lintegral_fintype [MeasurableSingletonClass α] [Fintype α] (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = ∑ x, f x * μ {x} := by rw [← lintegral_finset, Finset.coe_univ, Measure.restrict_univ] theorem lintegral_unique [Unique α] (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = f default * μ univ := calc ∫⁻ x, f x ∂μ = ∫⁻ _, f default ∂μ := lintegral_congr <| Unique.forall_iff.2 rfl _ = f default * μ univ := lintegral_const _ end Countable section SFinite variable (μ) in /-- If `μ` is an s-finite measure, then for any function `f` there exists a measurable function `g ≤ f` that has the same Lebesgue integral over every set. For the integral over the whole space, the statement is true without extra assumptions, see `exists_measurable_le_lintegral_eq`. See also `MeasureTheory.Measure.restrict_toMeasurable_of_sFinite` for a similar result. -/ theorem exists_measurable_le_forall_setLIntegral_eq [SFinite μ] (f : α → ℝ≥0∞) : ∃ g : α → ℝ≥0∞, Measurable g ∧ g ≤ f ∧ ∀ s, ∫⁻ a in s, f a ∂μ = ∫⁻ a in s, g a ∂μ := by -- We only need to prove the `≤` inequality for the integrals, the other one follows from `g ≤ f`. rsuffices ⟨g, hgm, hgle, hleg⟩ : ∃ g : α → ℝ≥0∞, Measurable g ∧ g ≤ f ∧ ∀ s, ∫⁻ a in s, f a ∂μ ≤ ∫⁻ a in s, g a ∂μ · exact ⟨g, hgm, hgle, fun s ↦ (hleg s).antisymm (lintegral_mono hgle)⟩ -- Without loss of generality, `μ` is a finite measure. wlog h : IsFiniteMeasure μ generalizing μ · choose g hgm hgle hgint using fun n ↦ @this (sfiniteSeq μ n) _ inferInstance refine ⟨fun x ↦ ⨆ n, g n x, .iSup hgm, fun x ↦ iSup_le (hgle · x), fun s ↦ ?_⟩ rw [← sum_sfiniteSeq μ, Measure.restrict_sum_of_countable, lintegral_sum_measure, lintegral_sum_measure] exact ENNReal.tsum_le_tsum fun n ↦ (hgint n s).trans (lintegral_mono fun x ↦ le_iSup (g · x) _) -- According to `exists_measurable_le_lintegral_eq`, for any natural `n` -- we can choose a measurable function $g_{n}$ -- such that $g_{n}(x) ≤ \min (f(x), n)$ for all $x$ -- and both sides have the same integral over the whole space w.r.t. $μ$. have (n : ℕ): ∃ g : α → ℝ≥0∞, Measurable g ∧ g ≤ f ∧ g ≤ n ∧ ∫⁻ a, min (f a) n ∂μ = ∫⁻ a, g a ∂μ := by simpa [and_assoc] using exists_measurable_le_lintegral_eq μ (f ⊓ n) choose g hgm hgf hgle hgint using this -- Let `φ` be the pointwise supremum of the functions $g_{n}$. -- Clearly, `φ` is a measurable function and `φ ≤ f`. set φ : α → ℝ≥0∞ := fun x ↦ ⨆ n, g n x have hφm : Measurable φ := by fun_prop have hφle : φ ≤ f := fun x ↦ iSup_le (hgf · x) refine ⟨φ, hφm, hφle, fun s ↦ ?_⟩ -- Now we show the inequality between set integrals. -- Choose a simple function `ψ ≤ f` with values in `ℝ≥0` and prove for `ψ`. rw [lintegral_eq_nnreal] refine iSup₂_le fun ψ hψ ↦ ?_ -- Choose `n` such that `ψ x ≤ n` for all `x`. obtain ⟨n, hn⟩ : ∃ n : ℕ, ∀ x, ψ x ≤ n := by rcases ψ.range.bddAbove with ⟨C, hC⟩ exact ⟨⌈C⌉₊, fun x ↦ (hC <| ψ.mem_range_self x).trans (Nat.le_ceil _)⟩ calc (ψ.map (↑)).lintegral (μ.restrict s) = ∫⁻ a in s, ψ a ∂μ := SimpleFunc.lintegral_eq_lintegral .. |>.symm _ ≤ ∫⁻ a in s, min (f a) n ∂μ := lintegral_mono fun a ↦ le_min (hψ _) (ENNReal.coe_le_coe.2 (hn a)) _ ≤ ∫⁻ a in s, g n a ∂μ := by have : ∫⁻ a in (toMeasurable μ s)ᶜ, min (f a) n ∂μ ≠ ∞ := IsFiniteMeasure.lintegral_lt_top_of_bounded_to_ennreal _ ⟨n, fun _ ↦ min_le_right ..⟩ |>.ne have hsm : MeasurableSet (toMeasurable μ s) := measurableSet_toMeasurable .. apply ENNReal.le_of_add_le_add_right this rw [← μ.restrict_toMeasurable_of_sFinite, lintegral_add_compl _ hsm, hgint, ← lintegral_add_compl _ hsm] gcongr with x exact le_min (hgf n x) (hgle n x) _ ≤ _ := lintegral_mono fun x ↦ le_iSup (g · x) n /-- In a sigma-finite measure space, there exists an integrable function which is positive everywhere (and with an arbitrarily small integral). -/ theorem exists_pos_lintegral_lt_of_sigmaFinite (μ : Measure α) [SigmaFinite μ] {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0, (∀ x, 0 < g x) ∧ Measurable g ∧ ∫⁻ x, g x ∂μ < ε := by /- Let `s` be a covering of `α` by pairwise disjoint measurable sets of finite measure. Let `δ : ℕ → ℝ≥0` be a positive function such that `∑' i, μ (s i) * δ i < ε`. Then the function that is equal to `δ n` on `s n` is a positive function with integral less than `ε`. -/ set s : ℕ → Set α := disjointed (spanningSets μ) have : ∀ n, μ (s n) < ∞ := fun n => (measure_mono <| disjointed_subset _ _).trans_lt (measure_spanningSets_lt_top μ n) obtain ⟨δ, δpos, δsum⟩ : ∃ δ : ℕ → ℝ≥0, (∀ i, 0 < δ i) ∧ (∑' i, μ (s i) * δ i) < ε := ENNReal.exists_pos_tsum_mul_lt_of_countable ε0 _ fun n => (this n).ne set N : α → ℕ := spanningSetsIndex μ have hN_meas : Measurable N := measurableSet_spanningSetsIndex μ have hNs : ∀ n, N ⁻¹' {n} = s n := preimage_spanningSetsIndex_singleton μ refine ⟨δ ∘ N, fun x => δpos _, measurable_from_nat.comp hN_meas, ?_⟩ erw [lintegral_comp measurable_from_nat.coe_nnreal_ennreal hN_meas] simpa [N, hNs, lintegral_countable', measurableSet_spanningSetsIndex, mul_comm] using δsum omit [MeasurableSpace α] variable {m m0 : MeasurableSpace α} local infixr:25 " →ₛ " => SimpleFunc theorem univ_le_of_forall_fin_meas_le {μ : Measure α} (hm : m ≤ m0) [SigmaFinite (μ.trim hm)] (C : ℝ≥0∞) {f : Set α → ℝ≥0∞} (hf : ∀ s, MeasurableSet[m] s → μ s ≠ ∞ → f s ≤ C) (h_F_lim : ∀ S : ℕ → Set α, (∀ n, MeasurableSet[m] (S n)) → Monotone S → f (⋃ n, S n) ≤ ⨆ n, f (S n)) : f univ ≤ C := by let S := @spanningSets _ m (μ.trim hm) _ have hS_mono : Monotone S := @monotone_spanningSets _ m (μ.trim hm) _ have hS_meas : ∀ n, MeasurableSet[m] (S n) := @measurableSet_spanningSets _ m (μ.trim hm) _ rw [← @iUnion_spanningSets _ m (μ.trim hm)] refine (h_F_lim S hS_meas hS_mono).trans ?_ refine iSup_le fun n => hf (S n) (hS_meas n) ?_ exact ((le_trim hm).trans_lt (@measure_spanningSets_lt_top _ m (μ.trim hm) _ n)).ne /-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite measure in a sub-σ-algebra and the measure is σ-finite on that sub-σ-algebra, then the integral over the whole space is bounded by that same constant. -/ theorem lintegral_le_of_forall_fin_meas_trim_le {μ : Measure α} (hm : m ≤ m0) [SigmaFinite (μ.trim hm)] (C : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : ∀ s, MeasurableSet[m] s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) : ∫⁻ x, f x ∂μ ≤ C := by have : ∫⁻ x in univ, f x ∂μ = ∫⁻ x, f x ∂μ := by simp only [Measure.restrict_univ] rw [← this] refine univ_le_of_forall_fin_meas_le hm C hf fun S _ hS_mono => ?_ rw [setLIntegral_iUnion_of_directed] exact directed_of_isDirected_le hS_mono alias lintegral_le_of_forall_fin_meas_le_of_measurable := lintegral_le_of_forall_fin_meas_trim_le /-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite measure and the measure is σ-finite, then the integral over the whole space is bounded by that same constant. -/ theorem lintegral_le_of_forall_fin_meas_le [MeasurableSpace α] {μ : Measure α} [SigmaFinite μ] (C : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : ∀ s, MeasurableSet s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) : ∫⁻ x, f x ∂μ ≤ C := have : SigmaFinite (μ.trim le_rfl) := by rwa [trim_eq_self] lintegral_le_of_forall_fin_meas_trim_le _ C hf theorem SimpleFunc.exists_lt_lintegral_simpleFunc_of_lt_lintegral {m : MeasurableSpace α} {μ : Measure α} [SigmaFinite μ] {f : α →ₛ ℝ≥0} {L : ℝ≥0∞} (hL : L < ∫⁻ x, f x ∂μ) : ∃ g : α →ₛ ℝ≥0, (∀ x, g x ≤ f x) ∧ ∫⁻ x, g x ∂μ < ∞ ∧ L < ∫⁻ x, g x ∂μ := by induction f using MeasureTheory.SimpleFunc.induction generalizing L with | @const c s hs => simp only [hs, const_zero, coe_piecewise, coe_const, SimpleFunc.coe_zero, univ_inter, piecewise_eq_indicator, lintegral_indicator, lintegral_const, Measure.restrict_apply', ENNReal.coe_indicator, Function.const_apply] at hL have c_ne_zero : c ≠ 0 := by intro hc simp only [hc, ENNReal.coe_zero, zero_mul, not_lt_zero] at hL have : L / c < μ s := by rwa [ENNReal.div_lt_iff, mul_comm] · simp only [c_ne_zero, Ne, ENNReal.coe_eq_zero, not_false_iff, true_or] · simp only [Ne, coe_ne_top, not_false_iff, true_or] obtain ⟨t, ht, ts, mlt, t_top⟩ : ∃ t : Set α, MeasurableSet t ∧ t ⊆ s ∧ L / ↑c < μ t ∧ μ t < ∞ := Measure.exists_subset_measure_lt_top hs this refine ⟨piecewise t ht (const α c) (const α 0), fun x => ?_, ?_, ?_⟩ · refine indicator_le_indicator_of_subset ts (fun x => ?_) x exact zero_le _ · simp only [ht, const_zero, coe_piecewise, coe_const, SimpleFunc.coe_zero, univ_inter, piecewise_eq_indicator, ENNReal.coe_indicator, Function.const_apply, lintegral_indicator, lintegral_const, Measure.restrict_apply', ENNReal.mul_lt_top ENNReal.coe_lt_top t_top] · simp only [ht, const_zero, coe_piecewise, coe_const, SimpleFunc.coe_zero, piecewise_eq_indicator, ENNReal.coe_indicator, Function.const_apply, lintegral_indicator, lintegral_const, Measure.restrict_apply', univ_inter] rwa [mul_comm, ← ENNReal.div_lt_iff] · simp only [c_ne_zero, Ne, ENNReal.coe_eq_zero, not_false_iff, true_or] · simp only [Ne, coe_ne_top, not_false_iff, true_or] | @add f₁ f₂ _ h₁ h₂ => replace hL : L < ∫⁻ x, f₁ x ∂μ + ∫⁻ x, f₂ x ∂μ := by rwa [← lintegral_add_left f₁.measurable.coe_nnreal_ennreal] by_cases hf₁ : ∫⁻ x, f₁ x ∂μ = 0 · simp only [hf₁, zero_add] at hL rcases h₂ hL with ⟨g, g_le, g_top, gL⟩ refine ⟨g, fun x => (g_le x).trans ?_, g_top, gL⟩ simp only [SimpleFunc.coe_add, Pi.add_apply, le_add_iff_nonneg_left, zero_le'] by_cases hf₂ : ∫⁻ x, f₂ x ∂μ = 0 · simp only [hf₂, add_zero] at hL rcases h₁ hL with ⟨g, g_le, g_top, gL⟩ refine ⟨g, fun x => (g_le x).trans ?_, g_top, gL⟩ simp only [SimpleFunc.coe_add, Pi.add_apply, le_add_iff_nonneg_right, zero_le'] obtain ⟨L₁, hL₁, L₂, hL₂, hL⟩ : ∃ L₁ < ∫⁻ x, f₁ x ∂μ, ∃ L₂ < ∫⁻ x, f₂ x ∂μ, L < L₁ + L₂ := ENNReal.exists_lt_add_of_lt_add hL hf₁ hf₂ rcases h₁ hL₁ with ⟨g₁, g₁_le, g₁_top, hg₁⟩ rcases h₂ hL₂ with ⟨g₂, g₂_le, g₂_top, hg₂⟩ refine ⟨g₁ + g₂, fun x => add_le_add (g₁_le x) (g₂_le x), ?_, ?_⟩ · apply lt_of_le_of_lt _ (add_lt_top.2 ⟨g₁_top, g₂_top⟩) rw [← lintegral_add_left g₁.measurable.coe_nnreal_ennreal] exact le_rfl · apply hL.trans ((ENNReal.add_lt_add hg₁ hg₂).trans_le _) rw [← lintegral_add_left g₁.measurable.coe_nnreal_ennreal] simp only [coe_add, Pi.add_apply, ENNReal.coe_add, le_rfl] theorem exists_lt_lintegral_simpleFunc_of_lt_lintegral {m : MeasurableSpace α} {μ : Measure α} [SigmaFinite μ] {f : α → ℝ≥0} {L : ℝ≥0∞} (hL : L < ∫⁻ x, f x ∂μ) : ∃ g : α →ₛ ℝ≥0, (∀ x, g x ≤ f x) ∧ ∫⁻ x, g x ∂μ < ∞ ∧ L < ∫⁻ x, g x ∂μ := by simp_rw [lintegral_eq_nnreal, lt_iSup_iff] at hL rcases hL with ⟨g₀, hg₀, g₀L⟩ have h'L : L < ∫⁻ x, g₀ x ∂μ := by convert g₀L rw [← SimpleFunc.lintegral_eq_lintegral, SimpleFunc.coe_map] simp only [Function.comp_apply] rcases SimpleFunc.exists_lt_lintegral_simpleFunc_of_lt_lintegral h'L with ⟨g, hg, gL, gtop⟩ exact ⟨g, fun x => (hg x).trans (ENNReal.coe_le_coe.1 (hg₀ x)), gL, gtop⟩ end SFinite end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/RieszMarkovKakutani/Basic.lean
import Mathlib.MeasureTheory.Measure.Content import Mathlib.Topology.ContinuousMap.CompactlySupported import Mathlib.Topology.PartitionOfUnity /-! # Riesz–Markov–Kakutani representation theorem This file prepares technical definitions and results for the Riesz-Markov-Kakutani representation theorem on a locally compact T2 space `X`. As a special case, the statements about linear functionals on bounded continuous functions follows. Actual theorems, depending on the linearity (`ℝ`, `ℝ≥0` or `ℂ`), are proven in separate files (`Mathlib/MeasureTheory/Integral/RieszMarkovKakutani/Real.lean`, `Mathlib/MeasureTheory/Integral/RieszMarkovKakutani/NNReal.lean`...) To make use of the existing API, the measure is constructed from a content `λ` on the compact subsets of a locally compact space X, rather than the usual construction of open sets in the literature. ## References * [Walter Rudin, Real and Complex Analysis.][Rud87] -/ noncomputable section open scoped BoundedContinuousFunction NNReal ENNReal open Set Function TopologicalSpace CompactlySupported CompactlySupportedContinuousMap MeasureTheory variable {X : Type*} [TopologicalSpace X] variable (Λ : C_c(X, ℝ≥0) →ₗ[ℝ≥0] ℝ≥0) /-! ### Construction of the content: -/ section Monotone lemma CompactlySupportedContinuousMap.monotone_of_nnreal : Monotone Λ := by intro f₁ f₂ h obtain ⟨g, hg⟩ := CompactlySupportedContinuousMap.exists_add_of_le h rw [← hg] simp /-- The positivity of a linear functional `Λ` implies that `Λ` is monotone. -/ @[deprecated PositiveLinearMap.mk₀ (since := "2025-08-08")] lemma CompactlySupportedContinuousMap.monotone_of_nonneg {Λ : C_c(X, ℝ) →ₗ[ℝ] ℝ} (hΛ : ∀ f, 0 ≤ f → 0 ≤ Λ f) : Monotone Λ := (PositiveLinearMap.mk₀ Λ hΛ).monotone end Monotone /-- Given a positive linear functional `Λ` on continuous compactly supported functions on `X` with values in `ℝ≥0`, for `K ⊆ X` compact define `λ(K) = inf {Λf | 1≤f on K}`. When `X` is a locally compact T2 space, this will be shown to be a content, and will be shown to agree with the Riesz measure on the compact subsets `K ⊆ X`. -/ def rieszContentAux : Compacts X → ℝ≥0 := fun K => sInf (Λ '' { f : C_c(X, ℝ≥0) | ∀ x ∈ K, (1 : ℝ≥0) ≤ f x }) section RieszMonotone variable [T2Space X] [LocallyCompactSpace X] /-- For any compact subset `K ⊆ X`, there exist some compactly supported continuous nonnegative functions `f` on `X` such that `f ≥ 1` on `K`. -/ theorem rieszContentAux_image_nonempty (K : Compacts X) : (Λ '' { f : C_c(X, ℝ≥0) | ∀ x ∈ K, (1 : ℝ≥0) ≤ f x }).Nonempty := by rw [image_nonempty] obtain ⟨V, hVcp, hKsubintV⟩ := exists_compact_superset K.2 have hIsCompact_closure_interior : IsCompact (closure (interior V)) := by apply IsCompact.of_isClosed_subset hVcp isClosed_closure nth_rw 2 [← closure_eq_iff_isClosed.mpr (IsCompact.isClosed hVcp)] exact closure_mono interior_subset obtain ⟨f, hsuppfsubV, hfeq1onK, hfinicc⟩ := exists_tsupport_one_of_isOpen_isClosed isOpen_interior hIsCompact_closure_interior (IsCompact.isClosed K.2) hKsubintV have hfHasCompactSupport : HasCompactSupport f := IsCompact.of_isClosed_subset hVcp (isClosed_tsupport f) (Set.Subset.trans hsuppfsubV interior_subset) use nnrealPart ⟨f, hfHasCompactSupport⟩ intro x hx apply le_of_eq simp only [nnrealPart_apply, CompactlySupportedContinuousMap.coe_mk] rw [← Real.toNNReal_one, Real.toNNReal_eq_toNNReal_iff (zero_le_one' ℝ) (hfinicc x).1] exact hfeq1onK.symm hx /-- Riesz content `λ` (associated with a positive linear functional `Λ`) is monotone: if `K₁ ⊆ K₂` are compact subsets in `X`, then `λ(K₁) ≤ λ(K₂)`. -/ theorem rieszContentAux_mono {K₁ K₂ : Compacts X} (h : K₁ ≤ K₂) : rieszContentAux Λ K₁ ≤ rieszContentAux Λ K₂ := by unfold rieszContentAux gcongr apply rieszContentAux_image_nonempty end RieszMonotone section RieszSubadditive /-- Any compactly supported continuous nonnegative `f` such that `f ≥ 1` on `K` gives an upper bound on the content of `K`; namely `λ(K) ≤ Λ f`. -/ theorem rieszContentAux_le {K : Compacts X} {f : C_c(X, ℝ≥0)} (h : ∀ x ∈ K, (1 : ℝ≥0) ≤ f x) : rieszContentAux Λ K ≤ Λ f := csInf_le (OrderBot.bddBelow _) ⟨f, ⟨h, rfl⟩⟩ variable [T2Space X] [LocallyCompactSpace X] /-- The Riesz content can be approximated arbitrarily well by evaluating the positive linear functional on test functions: for any `ε > 0`, there exists a compactly supported continuous nonnegative function `f` on `X` such that `f ≥ 1` on `K` and such that `λ(K) ≤ Λ f < λ(K) + ε`. -/ theorem exists_lt_rieszContentAux_add_pos (K : Compacts X) {ε : ℝ≥0} (εpos : 0 < ε) : ∃ f : C_c(X, ℝ≥0), (∀ x ∈ K, (1 : ℝ≥0) ≤ f x) ∧ Λ f < rieszContentAux Λ K + ε := by --choose a test function `f` s.t. `Λf = α < λ(K) + ε` obtain ⟨α, ⟨⟨f, f_hyp⟩, α_hyp⟩⟩ := exists_lt_of_csInf_lt (rieszContentAux_image_nonempty Λ K) (lt_add_of_pos_right (rieszContentAux Λ K) εpos) refine ⟨f, f_hyp.left, ?_⟩ rw [f_hyp.right] exact α_hyp /-- The Riesz content `λ` associated to a given positive linear functional `Λ` is finitely subadditive: `λ(K₁ ∪ K₂) ≤ λ(K₁) + λ(K₂)` for any compact subsets `K₁, K₂ ⊆ X`. -/ theorem rieszContentAux_sup_le (K1 K2 : Compacts X) : rieszContentAux Λ (K1 ⊔ K2) ≤ rieszContentAux Λ K1 + rieszContentAux Λ K2 := by apply _root_.le_of_forall_pos_le_add intro ε εpos --get test functions s.t. `λ(Ki) ≤ Λfi ≤ λ(Ki) + ε/2, i=1,2` obtain ⟨f1, f_test_function_K1⟩ := exists_lt_rieszContentAux_add_pos Λ K1 (half_pos εpos) obtain ⟨f2, f_test_function_K2⟩ := exists_lt_rieszContentAux_add_pos Λ K2 (half_pos εpos) --let `f := f1 + f2` test function for the content of `K` have f_test_function_union : ∀ x ∈ K1 ⊔ K2, (1 : ℝ≥0) ≤ (f1 + f2) x := by rintro x (x_in_K1 | x_in_K2) · exact le_add_right (f_test_function_K1.left x x_in_K1) · exact le_add_left (f_test_function_K2.left x x_in_K2) --use that `Λf` is an upper bound for `λ(K1⊔K2)` apply (rieszContentAux_le Λ f_test_function_union).trans (le_of_lt _) rw [map_add] --use that `Λfi` are lower bounds for `λ(Ki) + ε/2` apply lt_of_lt_of_le (_root_.add_lt_add f_test_function_K1.right f_test_function_K2.right) (le_of_eq _) rw [add_assoc, add_comm (ε / 2), add_assoc, add_halves ε, add_assoc] end RieszSubadditive section PartitionOfUnity variable [T2Space X] [LocallyCompactSpace X] lemma exists_continuous_add_one_of_isCompact_nnreal {s₀ s₁ : Set X} {t : Set X} (s₀_compact : IsCompact s₀) (s₁_compact : IsCompact s₁) (t_compact : IsCompact t) (disj : Disjoint s₀ s₁) (hst : s₀ ∪ s₁ ⊆ t) : ∃ (f₀ f₁ : C_c(X, ℝ≥0)), EqOn f₀ 1 s₀ ∧ EqOn f₁ 1 s₁ ∧ EqOn (f₀ + f₁) 1 t := by set so : Fin 2 → Set X := fun j => if j = 0 then s₀ᶜ else s₁ᶜ with hso have soopen (j : Fin 2) : IsOpen (so j) := by fin_cases j · simp only [hso, Fin.zero_eta, Fin.isValue, ↓reduceIte, isOpen_compl_iff] exact IsCompact.isClosed <| s₀_compact · simp only [hso, Fin.isValue, Fin.mk_one, one_ne_zero, ↓reduceIte, isOpen_compl_iff] exact IsCompact.isClosed <| s₁_compact have hsot : t ⊆ ⋃ j, so j := by rw [hso] simp only [Fin.isValue] intro x hx rw [mem_iUnion] rw [← subset_compl_iff_disjoint_right, ← compl_compl s₀, compl_subset_iff_union] at disj have h : x ∈ s₀ᶜ ∨ x ∈ s₁ᶜ := by rw [← mem_union, disj] exact mem_univ _ apply Or.elim h · intro h0 use 0 simp only [Fin.isValue, ↓reduceIte] exact h0 · intro h1 use 1 simp only [Fin.isValue, one_ne_zero, ↓reduceIte] exact h1 obtain ⟨f, f_supp_in_so, sum_f_one_on_t, f_in_icc, f_hcs⟩ := exists_continuous_sum_one_of_isOpen_isCompact soopen t_compact hsot use (nnrealPart (⟨f 1, f_hcs 1⟩ : C_c(X, ℝ))), (nnrealPart (⟨f 0, f_hcs 0⟩ : C_c(X, ℝ))) simp only [Fin.isValue, CompactlySupportedContinuousMap.coe_add] have sum_one_x (x : X) (hx : x ∈ t) : (f 0) x + (f 1) x = 1 := by simpa only [Finset.sum_apply, Fin.sum_univ_two, Fin.isValue, Pi.one_apply] using sum_f_one_on_t hx refine ⟨?_, ?_, ?_⟩ · intro x hx simp only [Fin.isValue, nnrealPart_apply, CompactlySupportedContinuousMap.coe_mk, Pi.one_apply, Real.toNNReal_eq_one] have : (f 0) x = 0 := by rw [← notMem_support] have : s₀ ⊆ (tsupport (f 0))ᶜ := by apply subset_trans _ (compl_subset_compl.mpr (f_supp_in_so 0)) rw [hso] simp only [Fin.isValue, ↓reduceIte, compl_compl, subset_refl] apply notMem_of_mem_compl exact mem_of_subset_of_mem (subset_trans this (compl_subset_compl_of_subset subset_closure)) hx rw [union_subset_iff] at hst rw [← sum_one_x x (mem_of_subset_of_mem hst.1 hx), this] exact Eq.symm (AddZeroClass.zero_add ((f 1) x)) · intro x hx simp only [Fin.isValue, nnrealPart_apply, CompactlySupportedContinuousMap.coe_mk, Pi.one_apply, Real.toNNReal_eq_one] have : (f 1) x = 0 := by rw [← notMem_support] have : s₁ ⊆ (tsupport (f 1))ᶜ := by apply subset_trans _ (compl_subset_compl.mpr (f_supp_in_so 1)) rw [hso] simp only [Fin.isValue, one_ne_zero, ↓reduceIte, compl_compl, subset_refl] apply notMem_of_mem_compl exact mem_of_subset_of_mem (subset_trans this (compl_subset_compl_of_subset subset_closure)) hx rw [union_subset_iff] at hst rw [← sum_one_x x (mem_of_subset_of_mem hst.2 hx), this] exact Eq.symm (AddMonoid.add_zero ((f 0) x)) · intro x hx simp only [Fin.isValue, Pi.add_apply, nnrealPart_apply, CompactlySupportedContinuousMap.coe_mk, Pi.one_apply] rw [Real.toNNReal_add_toNNReal (f_in_icc 1 x).1 (f_in_icc 0 x).1, add_comm] simp only [Fin.isValue, Real.toNNReal_eq_one] exact sum_one_x x hx end PartitionOfUnity section RieszContentAdditive variable [T2Space X] [LocallyCompactSpace X] lemma rieszContentAux_union {K₁ K₂ : TopologicalSpace.Compacts X} (disj : Disjoint (K₁ : Set X) K₂) : rieszContentAux Λ (K₁ ⊔ K₂) = rieszContentAux Λ K₁ + rieszContentAux Λ K₂ := by refine le_antisymm (rieszContentAux_sup_le Λ K₁ K₂) ?_ refine le_csInf (rieszContentAux_image_nonempty Λ (K₁ ⊔ K₂)) ?_ intro b ⟨f, ⟨hf, Λf_eq_b⟩⟩ have hsuppf : ∀ x ∈ K₁ ⊔ K₂, x ∈ support f := by intro x hx rw [mem_support] exact ne_of_gt <| lt_of_lt_of_le (zero_lt_one' ℝ≥0) (hf x hx) have hsubsuppf : (K₁ : Set X) ∪ (K₂ : Set X) ⊆ tsupport f := subset_trans hsuppf subset_closure obtain ⟨g₁, g₂, hg₁, hg₂, sum_g⟩ := exists_continuous_add_one_of_isCompact_nnreal K₁.isCompact' K₂.isCompact' f.hasCompactSupport'.isCompact disj hsubsuppf have f_eq_sum : f = g₁ * f + g₂ * f := by ext x simp only [CompactlySupportedContinuousMap.coe_add, CompactlySupportedContinuousMap.coe_mul, Pi.mul_apply, NNReal.coe_mul, Eq.symm (RightDistribClass.right_distrib _ _ _)] by_cases h : f x = 0 · rw [h] simp only [NNReal.coe_zero, mul_zero] · simp only [CompactlySupportedContinuousMap.coe_add, ContinuousMap.toFun_eq_coe, CompactlySupportedContinuousMap.coe_toContinuousMap] at sum_g rw [sum_g (mem_of_subset_of_mem subset_closure (mem_support.mpr h))] simp only [Pi.one_apply, NNReal.coe_one, one_mul] rw [← Λf_eq_b, f_eq_sum, map_add] have aux₁ : ∀ x ∈ K₁, 1 ≤ (g₁ * f) x := by intro x x_in_K₁ simp [hg₁ x_in_K₁, hf x (mem_union_left _ x_in_K₁)] have aux₂ : ∀ x ∈ K₂, 1 ≤ (g₂ * f) x := by intro x x_in_K₂ simp [hg₂ x_in_K₂, hf x (mem_union_right _ x_in_K₂)] exact add_le_add (rieszContentAux_le Λ aux₁) (rieszContentAux_le Λ aux₂) end RieszContentAdditive section RieszContentRegular variable [T2Space X] [LocallyCompactSpace X] /-- The content induced by the linear functional `Λ`. -/ noncomputable def rieszContent (Λ : C_c(X, ℝ≥0) →ₗ[ℝ≥0] ℝ≥0) : Content X where toFun := rieszContentAux Λ mono' := fun _ _ ↦ rieszContentAux_mono Λ sup_disjoint' := fun _ _ disj _ _ ↦ rieszContentAux_union Λ disj sup_le' := rieszContentAux_sup_le Λ lemma rieszContent_ne_top {K : Compacts X} : rieszContent Λ K ≠ ⊤ := by simp [rieszContent, ne_eq, ENNReal.coe_ne_top, not_false_eq_true] lemma contentRegular_rieszContent : (rieszContent Λ).ContentRegular := by intro K simp only [rieszContent, le_antisymm_iff, le_iInf_iff, ENNReal.coe_le_coe, Content.mk_apply] refine ⟨fun K' hK' ↦ rieszContentAux_mono Λ (hK'.trans interior_subset), ?_⟩ rw [iInf_le_iff] intro b hb rw [rieszContentAux, ENNReal.le_coe_iff] have : b < ⊤ := by obtain ⟨F, hF⟩ := exists_compact_superset K.2 exact (le_iInf_iff.mp (hb ⟨F, hF.1⟩) hF.2).trans_lt ENNReal.coe_lt_top refine ⟨b.toNNReal, (ENNReal.coe_toNNReal this.ne).symm, NNReal.coe_le_coe.mp ?_⟩ apply le_iff_forall_pos_le_add.mpr intro ε hε lift ε to ℝ≥0 using hε.le obtain ⟨f, hfleoneonK, hfle⟩ := exists_lt_rieszContentAux_add_pos Λ K (Real.toNNReal_pos.mpr hε) rw [rieszContentAux, Real.toNNReal_of_nonneg hε.le, ← NNReal.coe_lt_coe] at hfle refine ((le_iff_forall_one_lt_le_mul₀ (zero_le (Λ f))).mpr fun α hα ↦ ?_).trans hfle.le rw [mul_comm, ← smul_eq_mul, ← map_smul] set K' := f ⁻¹' Ici α⁻¹ have hKK' : ↑K ⊆ interior K' := subset_interior_iff.2 ⟨f ⁻¹' Ioi α⁻¹, isOpen_Ioi.preimage f.1.2, fun x hx ↦ (inv_lt_one_of_one_lt₀ hα).trans_le (hfleoneonK x hx), preimage_mono Ioi_subset_Ici_self⟩ have hK'cp : IsCompact K' := .of_isClosed_subset f.2 (isClosed_Ici.preimage f.1.2) fun x hx ↦ subset_closure ((inv_pos_of_pos <| zero_lt_one.trans hα).trans_le hx).ne' set hb' := hb ⟨K', hK'cp⟩ simp only [Compacts.coe_mk, le_iInf_iff] at hb' exact (ENNReal.toNNReal_mono (by simp) <| hb' hKK').trans <| csInf_le' ⟨α • f, fun x ↦ (inv_le_iff_one_le_mul₀' (zero_lt_one.trans hα)).mp, by simp⟩ end RieszContentRegular namespace NNRealRMK variable [T2Space X] [LocallyCompactSpace X] [MeasurableSpace X] [BorelSpace X] /-- `rieszContent` gives a `Content` from `Λ : C_c(X, ℝ≥0) →ₗ[ℝ≥0] ℝ≥0`. Here `rieszContent Λ` is promoted to a measure. It will be later shown that `∫ (x : X), f x ∂(rieszMeasure Λ hΛ) = Λ f` for all `f : C_c(X, ℝ≥0)`. -/ def rieszMeasure := (rieszContent Λ).measure lemma le_rieszMeasure_of_isCompact_tsupport_subset {f : C_c(X, ℝ≥0)} (hf : ∀ x, f x ≤ 1) {K : Set X} (hK : IsCompact K) (h : tsupport f ⊆ K) : .ofNNReal (Λ f) ≤ rieszMeasure Λ K := by rw [← TopologicalSpace.Compacts.coe_mk K hK] simp only [rieszMeasure, Content.measure_eq_content_of_regular (rieszContent Λ) (contentRegular_rieszContent Λ)] simp only [rieszContent, ENNReal.coe_le_coe, Content.mk_apply] apply le_iff_forall_pos_le_add.mpr intro ε hε obtain ⟨g, hg⟩ := exists_lt_rieszContentAux_add_pos Λ ⟨K, hK⟩ hε apply le_trans _ hg.2.le apply monotone_of_nnreal Λ intro x simp only by_cases hx : x ∈ tsupport f · exact le_trans (hf x) (hg.1 x (Set.mem_of_subset_of_mem h hx)) · rw [image_eq_zero_of_notMem_tsupport hx] exact zero_le (g x) lemma le_rieszMeasure_of_tsupport_subset {f : C_c(X, ℝ≥0)} (hf : ∀ x, f x ≤ 1) {V : Set X} (h : tsupport f ⊆ V) : .ofNNReal (Λ f) ≤ rieszMeasure Λ V := by apply le_trans _ (measure_mono h) apply le_rieszMeasure_of_isCompact_tsupport_subset Λ hf f.hasCompactSupport exact subset_rfl end NNRealRMK
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/RieszMarkovKakutani/NNReal.lean
import Mathlib.MeasureTheory.Integral.RieszMarkovKakutani.Real /-! # Riesz–Markov–Kakutani representation theorem for `ℝ≥0` This file proves the Riesz-Markov-Kakutani representation theorem on a locally compact T2 space `X` for `ℝ≥0`-linear functionals `Λ`. ## Implementation notes The proof depends on the version of the theorem for `ℝ`-linear functional Λ because in a standard proof one has to prove the inequalities by `le_antisymm`, yet for `C_c(X, ℝ≥0)` there is no `Neg`. Here we prove the result by writing `ℝ≥0`-linear `Λ` in terms of `ℝ`-linear `toRealLinear Λ` and by reducing the statement to the `ℝ`-version of the theorem. ## References * [Walter Rudin, Real and Complex Analysis.][Rud87] -/ open scoped NNReal open CompactlySupported CompactlySupportedContinuousMap MeasureTheory variable {X : Type*} [TopologicalSpace X] [T2Space X] [LocallyCompactSpace X] [MeasurableSpace X] [BorelSpace X] variable (Λ : C_c(X, ℝ≥0) →ₗ[ℝ≥0] ℝ≥0) namespace NNRealRMK /-- The **Riesz-Markov-Kakutani representation theorem**: given a positive linear functional `Λ`, the (Bochner) integral of `f` (as a `ℝ`-valued function) with respect to the `rieszMeasure` associated to `Λ` is equal to `Λ f`. -/ @[simp] theorem integral_rieszMeasure (f : C_c(X, ℝ≥0)) : ∫ (x : X), (f x : ℝ) ∂(rieszMeasure Λ) = Λ f := by rw [← eq_toRealPositiveLinear_toReal Λ f, ← RealRMK.integral_rieszMeasure (toRealPositiveLinear Λ) f.toReal] simp [RealRMK.rieszMeasure, NNRealRMK.rieszMeasure] /-- The **Riesz-Markov-Kakutani representation theorem**: given a positive linear functional `Λ`, the (lower) Lebesgue integral of `f` with respect to the `rieszMeasure` associated to `Λ` is equal to `Λ f`. -/ @[simp] theorem lintegral_rieszMeasure (f : C_c(X, ℝ≥0)) : ∫⁻ (x : X), f x ∂(rieszMeasure Λ) = Λ f := by rw [lintegral_coe_eq_integral, ← ENNReal.ofNNReal_toNNReal] · rw [ENNReal.coe_inj, Real.toNNReal_of_nonneg (MeasureTheory.integral_nonneg (by intro a; simp)), NNReal.eq_iff, NNReal.coe_mk] exact integral_rieszMeasure Λ f rw [rieszMeasure] exact Continuous.integrable_of_hasCompactSupport (by fun_prop) (HasCompactSupport.comp_left f.hasCompactSupport rfl) /-- The Riesz measure induced by a linear functional on `C_c(X, ℝ≥0)` is regular. -/ instance rieszMeasure_regular (Λ : C_c(X, ℝ≥0) →ₗ[ℝ≥0] ℝ≥0) : (rieszMeasure Λ).Regular := (rieszContent Λ).regular section integralLinearMap /-! We show that `NNRealRMK.rieszMeasure` is a bijection between linear functionals on `C_c(X, ℝ≥0)` and regular measures with inverse `NNRealRMK.integralLinearMap`. -/ /-- If two regular measures give the same integral for every function in `C_c(X, ℝ≥0)`, then they are equal. -/ theorem _root_.MeasureTheory.Measure.ext_of_integral_eq_on_compactlySupported_nnreal {μ ν : Measure X} [μ.Regular] [ν.Regular] (hμν : ∀ (f : C_c(X, ℝ≥0)), ∫ (x : X), (f x : ℝ) ∂μ = ∫ (x : X), (f x : ℝ) ∂ν) : μ = ν := by apply Measure.ext_of_integral_eq_on_compactlySupported intro f repeat rw [integral_eq_integral_pos_part_sub_integral_neg_part f.integrable] erw [hμν f.nnrealPart, hμν (-f).nnrealPart] rfl /-- If two regular measures induce the same linear functional on `C_c(X, ℝ≥0)`, then they are equal. -/ @[simp] theorem integralLinearMap_inj {μ ν : Measure X} [μ.Regular] [ν.Regular] : integralLinearMap μ = integralLinearMap ν ↔ μ = ν := ⟨fun hμν ↦ Measure.ext_of_integral_eq_on_compactlySupported_nnreal fun f ↦ by simpa using congr(($hμν f).toReal), fun _ ↦ by congr⟩ /-- Every regular measure is induced by a positive linear functional on `C_c(X, ℝ≥0)`. That is, `NNRealRMK.rieszMeasure` is a surjective function onto regular measures. -/ @[simp] theorem rieszMeasure_integralLinearMap {μ : Measure X} [μ.Regular] : rieszMeasure (integralLinearMap μ) = μ := Measure.ext_of_integral_eq_on_compactlySupported_nnreal (by simp) @[simp] theorem integralLinearMap_rieszMeasure : integralLinearMap (rieszMeasure Λ) = Λ := by ext; simp end integralLinearMap end NNRealRMK
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/RieszMarkovKakutani/Real.lean
import Mathlib.MeasureTheory.Integral.Bochner.Set import Mathlib.MeasureTheory.Integral.CompactlySupported import Mathlib.MeasureTheory.Integral.RieszMarkovKakutani.Basic import Mathlib.Order.Interval.Set.Union /-! # Riesz–Markov–Kakutani representation theorem for real-linear functionals The Riesz–Markov–Kakutani representation theorem relates linear functionals on spaces of continuous functions on a locally compact space to measures. There are many closely related variations of the theorem. This file contains that proof of the version where the space is a locally compact T2 space, the linear functionals are real and the continuous functions have compact support. ## Main definitions & statements * `RealRMK.rieszMeasure`: the measure induced by a real linear positive functional. * `RealRMK.integral_rieszMeasure`: the Riesz–Markov–Kakutani representation theorem for a real linear positive functional. * `RealRMK.rieszMeasure_integralPositiveLinearMap`: the uniqueness of the representing measure in the Riesz–Markov–Kakutani representation theorem. ## Implementation notes The measure is defined through `rieszContent` which is for `NNReal` using the `toNNRealLinear` version of `Λ`. The Riesz–Markov–Kakutani representation theorem is first proved for `Real`-linear `Λ` because equality is proven using two inequalities by considering `Λ f` and `Λ (-f)` for all functions `f`, yet on `C_c(X, ℝ≥0)` there is no negation. ## References * [Walter Rudin, Real and Complex Analysis.][Rud87] -/ open scoped ENNReal open CompactlySupported CompactlySupportedContinuousMap Filter Function Set Topology TopologicalSpace MeasureTheory namespace RealRMK variable {X : Type*} [TopologicalSpace X] [T2Space X] [LocallyCompactSpace X] [MeasurableSpace X] [BorelSpace X] variable (Λ : C_c(X, ℝ) →ₚ[ℝ] ℝ) /-- The measure induced for `Real`-linear positive functional `Λ`, defined through `toNNRealLinear` and the `NNReal`-version of `rieszContent`. This is under the namespace `RealRMK`, while `rieszMeasure` without namespace is for `NNReal`-linear `Λ`. -/ noncomputable def rieszMeasure := (rieszContent (toNNRealLinear Λ)).measure /-- If `f` assumes values between `0` and `1` and the support is contained in `V`, then `Λ f ≤ rieszMeasure V`. -/ lemma le_rieszMeasure_tsupport_subset {f : C_c(X, ℝ)} (hf : ∀ (x : X), 0 ≤ f x ∧ f x ≤ 1) {V : Set X} (hV : tsupport f ⊆ V) : ENNReal.ofReal (Λ f) ≤ rieszMeasure Λ V := by apply le_trans _ (measure_mono hV) have := Content.measure_eq_content_of_regular (rieszContent (toNNRealLinear Λ)) (contentRegular_rieszContent (toNNRealLinear Λ)) (⟨tsupport f, f.hasCompactSupport⟩) rw [← Compacts.coe_mk (tsupport f) f.hasCompactSupport, rieszMeasure, this, rieszContent, ENNReal.ofReal_eq_coe_nnreal (Λ.map_nonneg fun x ↦ (hf x).1), Content.mk_apply, ENNReal.coe_le_coe] apply le_iff_forall_pos_le_add.mpr intro _ hε obtain ⟨g, hg⟩ := exists_lt_rieszContentAux_add_pos (toNNRealLinear Λ) ⟨tsupport f, f.hasCompactSupport⟩ (Real.toNNReal_pos.mpr hε) simp_rw [NNReal.val_eq_coe, Real.toNNReal_coe] at hg refine (Λ.mono ?_).trans hg.2.le intro x by_cases hx : x ∈ tsupport f · simpa using le_trans (hf x).2 (hg.1 x hx) · simp [image_eq_zero_of_notMem_tsupport hx] /-- If `f` assumes the value `1` on a compact set `K` then `rieszMeasure K ≤ Λ f`. -/ lemma rieszMeasure_le_of_eq_one {f : C_c(X, ℝ)} (hf : ∀ x, 0 ≤ f x) {K : Set X} (hK : IsCompact K) (hfK : ∀ x ∈ K, f x = 1) : rieszMeasure Λ K ≤ ENNReal.ofReal (Λ f) := by rw [← Compacts.coe_mk K hK, rieszMeasure, Content.measure_eq_content_of_regular _ (contentRegular_rieszContent (toNNRealLinear Λ))] apply ENNReal.coe_le_iff.mpr intro p hp rw [← ENNReal.ofReal_coe_nnreal, ENNReal.ofReal_eq_ofReal_iff (Λ.map_nonneg hf) NNReal.zero_le_coe] at hp apply csInf_le' rw [Set.mem_image] use f.nnrealPart simp_rw [Set.mem_setOf_eq, nnrealPart_apply, Real.one_le_toNNReal] refine ⟨(fun x hx ↦ Eq.ge (hfK x hx)), ?_⟩ apply NNReal.eq rw [toNNRealLinear_apply, show f.nnrealPart.toReal = f by ext z; simp [hf z], hp] omit [T2Space X] [LocallyCompactSpace X] in /-- Given `f : C_c(X, ℝ)` such that `range f ⊆ [a, b]` we obtain a partition of the support of `f` determined by partitioning `[a, b]` into `N` pieces. -/ lemma range_cut_partition (f : C_c(X, ℝ)) (a : ℝ) {ε : ℝ} (hε : 0 < ε) (N : ℕ) (hf : range f ⊆ Ioo a (a + N * ε)) : ∃ (E : Fin N → Set X), tsupport f = ⋃ j, E j ∧ univ.PairwiseDisjoint E ∧ (∀ n : Fin N, ∀ x ∈ E n, a + ε * n < f x ∧ f x ≤ a + ε * (n + 1)) ∧ ∀ n : Fin N, MeasurableSet (E n) := by let b := a + N * ε let y : Fin N → ℝ := fun n ↦ a + ε * (n + 1) -- By definition `y n` and `y m` are separated by at least `ε`. have hy {n m : Fin N} (h : n < m) : y n + ε ≤ y m := calc _ ≤ a + ε * m + ε := by exact add_le_add_three (by rfl) ((mul_le_mul_iff_of_pos_left hε).mpr (by norm_cast)) (by rfl) _ = _ := by dsimp [y]; rw [mul_add, mul_one, add_assoc] -- Define `E n` as the inverse image of the interval `(y n - ε, y n]`. let E (n : Fin N) := (f ⁻¹' Ioc (y n - ε) (y n)) ∩ (tsupport f) use E refine ⟨?_, ?_, ?_, ?_⟩ · -- The sets `E n` are a partition of the support of `f`. have partition_aux : range f ⊆ ⋃ n, Ioc (y n - ε) (y n) := calc _ ⊆ Ioc (a + (0 : ℕ) * ε) (a + N * ε) := by intro _ hz simpa using Ioo_subset_Ioc_self (hf hz) _ ⊆ ⋃ i ∈ Finset.range N, Ioc (a + ↑i * ε) (a + ↑(i + 1) * ε) := Ioc_subset_biUnion_Ioc N (fun n ↦ a + n * ε) _ ⊆ _ := by intro z simp only [Finset.mem_range, mem_iUnion, mem_Ioc, forall_exists_index, and_imp, y] refine fun n hn _ _ ↦ ⟨⟨n, hn⟩, ⟨by linarith, by simp_all [mul_comm ε _]⟩⟩ simp only [E, ← iUnion_inter, ← preimage_iUnion, eq_comm (a := tsupport _), inter_eq_right] exact fun x _ ↦ partition_aux (mem_range_self x) · -- The sets `E n` are pairwise disjoint. intro m _ n _ hmn apply Disjoint.preimage simp_rw [mem_preimage, mem_Ioc, disjoint_left] intro x hx rw [mem_setOf_eq, and_assoc] at hx simp_rw [mem_setOf_eq, not_and_or, not_lt, not_le, or_assoc] rcases (by cutsat : m < n ∨ n < m) with hc | hc · left exact le_trans hx.2.1 (le_tsub_of_add_le_right (hy hc)) · right; left exact lt_of_le_of_lt (le_tsub_of_add_le_right (hy hc)) hx.1 · -- Upper and lower bound on `f x` follow from the definition of `E n` . intro _ _ hx simp only [mem_inter_iff, mem_preimage, mem_Ioc, E, y] at hx constructor <;> linarith · exact fun _ ↦ (f.1.measurable measurableSet_Ioc).inter measurableSet_closure omit [LocallyCompactSpace X] in /-- Given a set `E`, a function `f : C_c(X, ℝ)`, `0 < ε` and `∀ x ∈ E, f x < c`, there exists an open set `V` such that `E ⊆ V` and the sets are similar in measure and `∀ x ∈ V, f x < c`. -/ lemma exists_open_approx (f : C_c(X, ℝ)) {ε : ℝ} (hε : 0 < ε) (E : Set X) {μ : Content X} (hμ : μ.outerMeasure E ≠ ∞) (hμ' : MeasurableSet E) {c : ℝ} (hfE : ∀ x ∈ E, f x < c) : ∃ (V : Opens X), E ⊆ V ∧ (∀ x ∈ V, f x < c) ∧ μ.measure V ≤ μ.measure E + ENNReal.ofReal ε := by have hε' := ne_of_gt <| Real.toNNReal_pos.mpr hε obtain ⟨V₁ : Opens X, hV₁⟩ := Content.outerMeasure_exists_open μ hμ hε' let V₂ : Opens X := ⟨(f ⁻¹' Iio c), IsOpen.preimage f.1.2 isOpen_Iio⟩ use V₁ ⊓ V₂ refine ⟨subset_inter hV₁.1 hfE, ?_, ?_⟩ · intro x hx suffices ∀ x ∈ V₂.carrier, f x < c from this x (mem_of_mem_inter_right hx) exact fun _ a ↦ a · calc _ ≤ μ.measure V₁ := by simp [measure_mono] _ = μ.outerMeasure V₁ := Content.measure_apply μ (V₁.2.measurableSet) _ ≤ μ.outerMeasure E + ε.toNNReal := hV₁.2 _ = _ := by rw [Content.measure_apply μ hμ', ENNReal.ofNNReal_toNNReal] /-- Choose `N` sufficiently large such that a particular quantity is small. -/ private lemma exists_nat_large (a' b' : ℝ) {ε : ℝ} (hε : 0 < ε) : ∃ (N : ℕ), 0 < N ∧ a' / N * (b' + a' / N) ≤ ε := by have A : Tendsto (fun (N : ℝ) ↦ a' / N * (b' + a' / N)) atTop (𝓝 (0 * (b' + 0))) := by apply Tendsto.mul · exact Tendsto.div_atTop tendsto_const_nhds tendsto_id · exact Tendsto.add tendsto_const_nhds (Tendsto.div_atTop tendsto_const_nhds tendsto_id) have B := A.comp tendsto_natCast_atTop_atTop simp only [add_zero, zero_mul] at B obtain ⟨N, hN, h'N⟩ := (((tendsto_order.1 B).2 _ hε).and (Ici_mem_atTop 1)).exists exact ⟨N, h'N, hN.le⟩ /-- The main estimate in the proof of the Riesz-Markov-Kakutani: `Λ f` is bounded above by the integral of `f` with respect to the `rieszMeasure` associated to `Λ`. -/ private lemma integral_riesz_aux (f : C_c(X, ℝ)) : Λ f ≤ ∫ x, f x ∂(rieszMeasure Λ) := by let μ := rieszMeasure Λ let K := tsupport f -- Suffices to show that `Λ f ≤ ∫ x, f x ∂μ + ε` for arbitrary `ε`. apply le_iff_forall_pos_le_add.mpr intro ε hε -- Choose an interval `(a, b)` which contains the range of `f`. obtain ⟨a, b, hab⟩ : ∃ a b : ℝ, a < b ∧ range f ⊆ Ioo a b := by obtain ⟨r, hr⟩ := (Metric.isCompact_iff_isClosed_bounded.mp (HasCompactSupport.isCompact_range f.2 f.1.2)).2.subset_ball_lt 0 0 exact ⟨-r, r, by linarith, hr.2.trans_eq (by simp [Real.ball_eq_Ioo])⟩ -- Choose `N` positive and sufficiently large such that `ε'` is sufficiently small obtain ⟨N, hN, hε'⟩ := exists_nat_large (b - a) (2 * μ.real K + |a| + b) hε let ε' := (b - a) / N replace hε' : 0 < ε' ∧ ε' * (2 * μ.real K + |a| + b + ε') ≤ ε := ⟨div_pos (sub_pos.mpr hab.1) (Nat.cast_pos'.mpr hN), hε'⟩ -- Take a partition of the support of `f` into sets `E` by partitioning the range. obtain ⟨E, hE⟩ := range_cut_partition f a hε'.1 N <| by dsimp [ε'] field_simp simp [hab.2] -- Introduce notation for the partition of the range. let y : Fin N → ℝ := fun n ↦ a + ε' * (n + 1) -- The measure of each `E n` is finite. have hE' (n : Fin N) : μ (E n) ≠ ∞ := by have h : E n ⊆ tsupport f := by rw [hE.1]; exact subset_iUnion _ _ refine lt_top_iff_ne_top.mp ?_ apply lt_of_le_of_lt <| measure_mono h dsimp [μ] rw [rieszMeasure, ← coe_toContinuousMap, ← ContinuousMap.toFun_eq_coe, Content.measure_apply _ f.2.measurableSet] exact Content.outerMeasure_lt_top_of_isCompact _ f.2 -- Define sets `V` which are open approximations to the sets `E` obtain ⟨V, hV⟩ : ∃ V : Fin N → Opens X, ∀ n, E n ⊆ (V n) ∧ (∀ x ∈ V n, f x < y n + ε') ∧ μ (V n) ≤ μ (E n) + ENNReal.ofReal (ε' / N) := by have h_ε' := (div_pos hε'.1 (Nat.cast_pos'.mpr hN)) have h n x (hx : x ∈ E n) := lt_add_of_le_of_pos ((hE.2.2.1 n x hx).right) hε'.1 have h' n := Eq.trans_ne (Content.measure_apply (rieszContent (toNNRealLinear Λ)) (hE.2.2.2 n)).symm (hE' n) choose V hV using fun n ↦ exists_open_approx f h_ε' (E n) (h' n) (hE.2.2.2 n) (h n) exact ⟨V, hV⟩ -- Define a partition of unity subordinated to the sets `V` obtain ⟨g, hg⟩ : ∃ g : Fin N → C_c(X, ℝ), (∀ n, tsupport (g n) ⊆ (V n).carrier) ∧ EqOn (∑ n : Fin N, (g n)) 1 (tsupport f.toFun) ∧ (∀ n x, (g n) x ∈ Icc 0 1) ∧ ∀ n, HasCompactSupport (g n) := by have : tsupport f ⊆ ⋃ n, (V n).carrier := calc _ = ⋃ j, E j := hE.1 _ ⊆ _ := by gcongr with n; exact (hV n).1 obtain ⟨g', hg⟩ := exists_continuous_sum_one_of_isOpen_isCompact (fun n ↦ (V n).2) f.2 this exact ⟨fun n ↦ ⟨g' n, hg.2.2.2 n⟩, hg⟩ -- The proof is completed by a chain of inequalities. calc Λ f _ = Λ (∑ n, g n • f) := ?_ _ = ∑ n, Λ (g n • f) := by simp _ ≤ ∑ n, Λ ((y n + ε') • g n) := ?_ _ = ∑ n, (y n + ε') * Λ (g n) := by simp -- That `y n + ε'` can be negative is bad in the inequalities so we artificially include `|a|`. _ = ∑ n, (|a| + y n + ε') * Λ (g n) - |a| * ∑ n, Λ (g n) := by simp [add_assoc, add_mul |a|, Finset.sum_add_distrib, Finset.mul_sum] _ ≤ ∑ n, (|a| + y n + ε') * (μ.real (E n) + ε' / N) - |a| * ∑ n, Λ (g n) := ?_ _ ≤ ∑ n, (|a| + y n + ε') * (μ.real (E n) + ε' / N) - |a| * μ.real K := ?_ _ = ∑ n, (y n - ε') * μ.real (E n) + 2 * ε' * μ.real K + ε' / N * ∑ n, (|a| + y n + ε') := ?_ _ ≤ ∫ x, f x ∂μ + 2 * ε' * μ.real K + ε' / N * ∑ n, (|a| + y n + ε') := ?_ _ ≤ ∫ x, f x ∂μ + ε' * (2 * μ.real K + |a| + b + ε') := ?_ _ ≤ ∫ x, f x ∂μ + ε := by simp [hε'.2] · -- Equality since `∑ i : Fin N, (g i)` is equal to unity on the support of `f` congr; ext x simp only [coe_sum, smul_eq_mul, coe_mul, Pi.mul_apply, ← Finset.sum_mul] by_cases hx : x ∈ tsupport f · simp [hg.2.1 hx] · simp [image_eq_zero_of_notMem_tsupport hx] · -- Use that `f ≤ y n + ε'` on `V n` gcongr with n hn intro x by_cases hx : x ∈ tsupport (g n) · rw [smul_eq_mul, mul_comm] apply mul_le_mul_of_nonneg_right ?_ (hg.2.2.1 n x).1 exact le_of_lt <| (hV n).2.1 x <| mem_of_subset_of_mem (hg.1 n) hx · simp [image_eq_zero_of_notMem_tsupport hx] · -- Use that `Λ (g n) ≤ μ (V n)).toReal ≤ μ (E n)).toReal + ε' / N` gcongr with n hn · calc _ ≤ |a| + a := neg_le_iff_add_nonneg'.mp <| neg_abs_le a _ ≤ |a| + a + ε' * (n + 1) := (le_add_iff_nonneg_right (|a| + a)).mpr <| Left.mul_nonneg (le_of_lt hε'.1) <| Left.add_nonneg (Nat.cast_nonneg' n) (zero_le_one' ℝ) _ ≤ _ := by rw [← add_assoc, le_add_iff_nonneg_right]; exact le_of_lt hε'.1 · calc _ ≤ μ.real (V n) := by apply (ENNReal.ofReal_le_iff_le_toReal _).mp · exact le_rieszMeasure_tsupport_subset Λ (fun x ↦ hg.2.2.1 n x) (hg.1 n) · rw [← lt_top_iff_ne_top] apply lt_of_le_of_lt (hV n).2.2 rw [WithTop.add_lt_top] exact ⟨WithTop.lt_top_iff_ne_top.mpr (hE' n), ENNReal.ofReal_lt_top⟩ _ ≤ _ := by rw [← ENNReal.toReal_ofReal (div_nonneg (le_of_lt hε'.1) (Nat.cast_nonneg _))] apply ENNReal.toReal_le_add (hV n).2.2 (hE' n) · finiteness · -- Use that `μ K ≤ Λ (∑ n, g n)` gcongr rw [← map_sum Λ g _] have h x : 0 ≤ (∑ n, g n) x := by simpa using Fintype.sum_nonneg fun n ↦ (hg.2.2.1 n x).1 apply ENNReal.toReal_le_of_le_ofReal · exact Λ.map_nonneg (fun x ↦ h x) · have h' x (hx : x ∈ K) : (∑ n, g n) x = 1 := by simp [hg.2.1 hx] refine rieszMeasure_le_of_eq_one Λ h f.2 h' · -- Rearrange the sums have (n : Fin N) : (|a| + y n + ε') * μ.real (E n) = (|a| + 2 * ε') * μ.real (E n) + (y n - ε') * μ.real (E n) := by linarith simp_rw [mul_add, this] have : ∑ i, μ.real (E i) = μ.real K := by suffices h : μ K = ∑ i, (μ (E i)) by simp only [measureReal_def, h] exact Eq.symm <| ENNReal.toReal_sum <| fun n _ ↦ hE' n dsimp [K]; rw [hE.1] rw [measure_iUnion (fun m n hmn ↦ hE.2.1 trivial trivial hmn) hE.2.2.2] exact tsum_fintype fun b ↦ μ (E b) rw [Finset.sum_add_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, this, ← Finset.sum_mul] linarith · -- Use that `y n - ε' ≤ f x` on `E n` gcongr have h : ∀ n, (y n - ε') * μ.real (E n) ≤ ∫ x in (E n), f x ∂μ := by intro n apply setIntegral_ge_of_const_le_real (hE.2.2.2 n) (hE' n) · intro x hx dsimp [y]; linarith [(hE.2.2.1 n x hx).1] · apply Integrable.integrableOn dsimp [μ, rieszMeasure] exact Continuous.integrable_of_hasCompactSupport f.1.2 f.2 calc _ ≤ ∑ n, ∫ (x : X) in E n, f x ∂μ := Finset.sum_le_sum fun i a ↦ h i _ = ∫ x in (⋃ n, E n), f x ∂μ := by refine Eq.symm <| integral_iUnion_fintype hE.2.2.2 (fun _ _ ↦ hE.2.1 trivial trivial) ?_ dsimp [μ, rieszMeasure] exact fun _ ↦ Integrable.integrableOn <| Continuous.integrable_of_hasCompactSupport f.1.2 f.2 _ = ∫ x in tsupport f, f x ∂μ := by simp_rw [hE.1] _ = _ := setIntegral_tsupport · -- Rough bound of the sum have h : ∑ n : Fin N, y n ≤ N * b := by have (n : Fin N) := calc y n _ ≤ a + ε' * N := by simp_all [y, show (n : ℝ) + 1 ≤ N by norm_cast; cutsat] _ = b := by simp [field, ε'] have : ∑ n, y n ≤ ∑ n, b := Finset.sum_le_sum (fun n ↦ fun _ ↦ this n) simp_all simp only [Finset.sum_add_distrib, Finset.sum_add_distrib, Fin.sum_const, Fin.sum_const, nsmul_eq_mul, ← add_assoc, mul_add, ← mul_assoc] simpa [show (N : ℝ) ≠ 0 by simp [hN.ne.symm], mul_comm _ ε', div_eq_mul_inv, mul_assoc] using (mul_le_mul_iff_of_pos_left hε'.1).mpr <| (inv_mul_le_iff₀ (Nat.cast_pos'.mpr hN)).mpr h /-- The **Riesz-Markov-Kakutani representation theorem**: given a positive linear functional `Λ`, the integral of `f` with respect to the `rieszMeasure` associated to `Λ` is equal to `Λ f`. -/ @[simp] theorem integral_rieszMeasure (f : C_c(X, ℝ)) : ∫ x, f x ∂(rieszMeasure Λ) = Λ f := by -- We apply the result `Λ f ≤ ∫ x, f x ∂(rieszMeasure hΛ)` to `f` and `-f`. apply le_antisymm -- prove the inequality for `- f` · calc _ = - ∫ x, (-f) x ∂(rieszMeasure Λ) := by simpa using integral_neg' (-f) _ ≤ - Λ (-f) := neg_le_neg (integral_riesz_aux Λ (-f)) _ = _ := by simp -- prove the inequality for `f` · exact integral_riesz_aux Λ f /-- The Riesz measure induced by a positive linear functional on `C_c(X, ℝ)` is regular. -/ instance regular_rieszMeasure : (rieszMeasure Λ).Regular := (rieszContent _).regular section integralPositiveLinearMap variable {μ ν : Measure X} /-! We show that `RealRMK.rieszMeasure` is a bijection between positive linear functionals on `C_c(X, ℝ)` and regular measures with inverse `RealRMK.integralPositiveLinearMap`. -/ /-- Note: the assumption `IsFiniteMeasureOnCompacts μ` cannot be removed. For example, if `μ` is infinite on any nonempty set and `ν = 0`, then the hypotheses are satisfied. -/ lemma measure_le_of_isCompact_of_integral [ν.OuterRegular] [IsFiniteMeasureOnCompacts ν] [IsFiniteMeasureOnCompacts μ] (hμν : ∀ f : C_c(X, ℝ), ∫ x, f x ∂μ ≤ ∫ x, f x ∂ν) ⦃K : Set X⦄ (hK : IsCompact K) : μ K ≤ ν K := by refine ENNReal.le_of_forall_pos_le_add fun ε hε hν ↦ ?_ have hνK : ν K ≠ ⊤ := hν.ne have hμK : μ K ≠ ⊤ := hK.measure_lt_top.ne obtain ⟨V, pV1, pV2, pV3⟩ : ∃ V ⊇ K, IsOpen V ∧ ν V ≤ ν K + ε := exists_isOpen_le_add K ν (ne_of_gt (ENNReal.coe_lt_coe.mpr hε)) suffices μ.real K ≤ ν.real K + ε by rwa [← ENNReal.toReal_le_toReal, ENNReal.toReal_add, ENNReal.coe_toReal] all_goals finiteness have VltTop : ν V < ⊤ := pV3.trans_lt <| by finiteness obtain ⟨f, pf1, pf2, pf3⟩ : ∃ f : C_c(X, ℝ), Set.EqOn (⇑f) 1 K ∧ tsupport ⇑f ⊆ V ∧ ∀ (x : X), f x ∈ Set.Icc 0 1 := by obtain ⟨f, hf1, hf2, hf3⟩ := exists_continuousMap_one_of_isCompact_subset_isOpen hK pV2 pV1 exact ⟨⟨f, hasCompactSupport_def.mpr hf2⟩, hf1, hf3⟩ have hfV (x : X) : f x ≤ V.indicator 1 x := by by_cases hx : x ∈ tsupport f · simp [(pf2 hx), (pf3 x).2] · simp [image_eq_zero_of_notMem_tsupport hx, Set.indicator_nonneg] have hfK (x : X) : K.indicator 1 x ≤ f x := by by_cases hx : x ∈ K · simp [hx, pf1 hx] · simp [hx, (pf3 x).1] calc μ.real K = ∫ x, K.indicator 1 x ∂μ := integral_indicator_one hK.measurableSet |>.symm _ ≤ ∫ x, f x ∂μ := by refine integral_mono ?_ f.integrable hfK exact (continuousOn_const.integrableOn_compact hK).integrable_indicator hK.measurableSet _ ≤ ∫ x, f x ∂ν := hμν f _ ≤ ∫ x, V.indicator 1 x ∂ν := by refine integral_mono f.integrable ?_ hfV exact IntegrableOn.integrable_indicator integrableOn_const pV2.measurableSet _ ≤ (ν K).toReal + ↑ε := by rwa [integral_indicator_one pV2.measurableSet, measureReal_def, ← ENNReal.coe_toReal, ← ENNReal.toReal_add, ENNReal.toReal_le_toReal] all_goals finiteness /-- If two regular measures give the same integral for every function in `C_c(X, ℝ)`, then they are equal. -/ theorem _root_.MeasureTheory.Measure.ext_of_integral_eq_on_compactlySupported [μ.Regular] [ν.Regular] (hμν : ∀ f : C_c(X, ℝ), ∫ x, f x ∂μ = ∫ x, f x ∂ν) : μ = ν := by apply Measure.OuterRegular.ext_isOpen apply Measure.InnerRegularWRT.eq_of_innerRegularWRT_of_forall_eq Measure.Regular.innerRegular Measure.Regular.innerRegular intro K hK apply le_antisymm · exact measure_le_of_isCompact_of_integral (fun f ↦ (hμν f).le) hK · exact measure_le_of_isCompact_of_integral (fun f ↦ (hμν f).ge) hK /-- Two regular measures are equal iff they induce the same positive linear functional on `C_c(X, ℝ)`. -/ theorem integralPositiveLinearMap_inj [μ.Regular] [ν.Regular] : integralPositiveLinearMap μ = integralPositiveLinearMap ν ↔ μ = ν where mp hμν := Measure.ext_of_integral_eq_on_compactlySupported fun f ↦ congr($hμν f) mpr _ := by congr /-- Every regular measure is induced by a positive linear functional on `C_c(X, ℝ)`. That is, `RealRMK.rieszMeasure` is a surjective function onto regular measures. -/ @[simp] theorem rieszMeasure_integralPositiveLinearMap [μ.Regular] : rieszMeasure (integralPositiveLinearMap μ) = μ := Measure.ext_of_integral_eq_on_compactlySupported (by simp) @[simp] theorem integralPositiveLinearMap_rieszMeasure : integralPositiveLinearMap (rieszMeasure Λ) = Λ := by ext; simp end integralPositiveLinearMap end RealRMK
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/CurveIntegral/Basic.lean
import Mathlib.Algebra.Order.Field.Pointwise import Mathlib.Analysis.Calculus.ContDiff.Basic import Mathlib.Analysis.Calculus.Deriv.AffineMap import Mathlib.Analysis.Calculus.Deriv.Shift import Mathlib.Analysis.Normed.Module.Convex import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic /-! # Integral of a 1-form along a path In this file we define the integral of a 1-form along a path indexed by `[0, 1]` and prove basic properties of this operation. The integral `∫ᶜ x in γ, ω x` is defined as $\int_0^1 \omega(\gamma(t))(\gamma'(t))$. More precisely, we use - `Path.extend γ t` instead of `γ t`, because both derivatives and `intervalIntegral` expect globally defined functions; - `derivWithin γ.extend (Set.Icc 0 1) t`, not `deriv γ.extend t`, for the derivative, so that it takes meaningful values at `t = 0` and `t = 1`, even though this does not affect the integral. The argument `ω : E → E →L[𝕜] F` is a `𝕜`-linear 1-form on `E` taking values in `F`, where `𝕜` is `ℝ` or `ℂ`. The definition does not depend on `𝕜`, see `curveIntegral_restrictScalars` and nearby lemmas. However, the fact that `𝕜 = ℝ` is not hardcoded allows us to avoid inserting `ContinuousLinearMap.restrictScalars` here and there. ## Main definitions - `curveIntegral ω γ`, notation `∫ᶜ x in γ, ω x`, is the integral of a 1-form `ω` along a path `γ`. - `CurveIntegrable ω γ` is the predicate saying that the above integral makes sense. ## Main results We prove that `curveIntegral` well behaves with respect to - operations on `Path`s, see `curveIntegral_refl`, `curveIntegral_symm`, `curveIntegral_trans` etc; - algebraic operations on 1-forms, see `curveIntegral_add` etc. We also show that the derivative of `fun b ↦ ∫ᶜ x in Path.segment a b, ω x` has derivative `ω a` at `b = a`. We provide 2 versions of this result: one for derivative (`HasFDerivWithinAt`) within a convex set and one for `HasFDerivAt`. ## Implementation notes ### Naming In literature, the integral of a function or a 1-form along a path is called “line integral”, “path integral”, “curve integral”, or “curvelinear integral”. We use the name “curve integral” instead of other names for the following reasons: - for many people whose mother tongue is not English, “line integral” sounds like an integral along a straight line; - we reserve the name "path integral" for Feynmann-style integrals over the space of paths. ### Usage of `ContinuousLinearMap`s for 1-forms Similarly to the way `fderiv` uses continuous linear maps while higher order derivatives use continuous multilinear maps, this file uses `E → E →L[𝕜] F` instead of continuous alternating maps for 1-forms. ### Differentiability assumptions The definitions in this file make sense if the path is a piecewise $C^1$ curve. Poincaré lemma (formalization WIP, see #24019) implies that for a closed 1-form on an open set `U`, the integral depends on the homotopy class of the path only, thus we can define the integral along a continuous path or an element of the fundamental groupoid of `U`. ### Usage of an extra field The definitions in this file deal with `𝕜`-linear 1-forms. This allows us to avoid using `ContinuousLinearMap.restrictScalars` in `HasFDerivWithinAt.curveIntegral_segment_source` and a future formalization of Poincaré lemma. -/ open Metric MeasureTheory Topology Set Interval AffineMap Convex Filter open scoped Pointwise unitInterval section Defs variable {𝕜 E F : Type*} [RCLike 𝕜] [NormedAddCommGroup E] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [NormedSpace 𝕜 F] {a b : E} /-- The function `t ↦ ω (γ t) (γ' t)` which appears in the definition of a curve integral. This definition is used to factor out common parts of lemmas about `CurveIntegrable` and `curveIntegral`. -/ noncomputable irreducible_def curveIntegralFun (lemma := curveIntegralFun_def') (ω : E → E →L[𝕜] F) (γ : Path a b) (t : ℝ) : F := letI : NormedSpace ℝ E := .restrictScalars ℝ 𝕜 E ω (γ.extend t) (derivWithin γ.extend I t) /-- A 1-form `ω` is *curve integrable* along a path `γ`, if the function `curveIntegralFun ω γ t = ω (γ t) (γ' t)` is integrable on `[0, 1]`. The actual definition uses `Path.extend γ`, because both interval integrals and derivatives expect globally defined functions. -/ def CurveIntegrable (ω : E → E →L[𝕜] F) (γ : Path a b) : Prop := IntervalIntegrable (curveIntegralFun ω γ) volume 0 1 /-- Integral of a 1-form `ω : E → E →L[𝕜] F` along a path `γ`, defined as $\int_0^1 \omega(\gamma(t))(\gamma'(t))$. The actual definition uses `curveIntegralFun` which uses `Path.extend γ` and `derivWithin (Path.extend γ) (Set.Icc 0 1) t`, because calculus-related definitions in Mathlib expect globally defined functions as arguments. -/ noncomputable irreducible_def curveIntegral (lemma := curveIntegral_def') (ω : E → E →L[𝕜] F) (γ : Path a b) : F := letI : NormedSpace ℝ F := .restrictScalars ℝ 𝕜 F ∫ t in 0..1, curveIntegralFun ω γ t @[inherit_doc curveIntegral] notation3 "∫ᶜ "(...)" in " γ ", "r:67:(scoped ω => curveIntegral ω γ) => r /-- curve integral is defined using Bochner integral, thus it is defined as zero whenever the codomain is not a complete space. -/ theorem curveIntegral_of_not_completeSpace (h : ¬CompleteSpace F) (ω : E → E →L[𝕜] F) (γ : Path a b) : ∫ᶜ x in γ, ω x = 0 := by simp [curveIntegral, intervalIntegral, integral, h] theorem curveIntegralFun_def [NormedSpace ℝ E] (ω : E → E →L[𝕜] F) (γ : Path a b) (t : ℝ) : curveIntegralFun ω γ t = ω (γ.extend t) (derivWithin γ.extend I t) := by simp only [curveIntegralFun, NormedSpace.restrictScalars_eq] theorem curveIntegral_def [NormedSpace ℝ F] (ω : E → E →L[𝕜] F) (γ : Path a b) : curveIntegral ω γ = ∫ t in 0..1, curveIntegralFun ω γ t := by simp only [curveIntegral, NormedSpace.restrictScalars_eq] theorem curveIntegral_eq_intervalIntegral_deriv [NormedSpace ℝ E] [NormedSpace ℝ F] (ω : E → E →L[𝕜] F) (γ : Path a b) : ∫ᶜ x in γ, ω x = ∫ t in 0..1, ω (γ.extend t) (deriv γ.extend t) := by simp only [curveIntegral_def, curveIntegralFun_def] apply intervalIntegral.integral_congr_ae_restrict rw [uIoc_of_le zero_le_one, ← restrict_Ioo_eq_restrict_Ioc] filter_upwards [ae_restrict_mem (by measurability)] with x hx rw [derivWithin_of_mem_nhds (by simpa)] end Defs /-! ### Operations on paths -/ section PathOperations variable {𝕜 E F : Type*} [RCLike 𝕜] [NormedAddCommGroup E] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [NormedSpace 𝕜 F] {a b c d : E} {ω : E → E →L[𝕜] F} {γ γab : Path a b} {γbc : Path b c} {t : ℝ} @[simp] theorem curveIntegralFun_refl (ω : E → E →L[𝕜] F) (a : E) : curveIntegralFun ω (.refl a) = 0 := by ext simp [curveIntegralFun, ← Function.const_def] @[simp] theorem curveIntegral_refl (ω : E → E →L[𝕜] F) (a : E) : ∫ᶜ x in .refl a, ω x = 0 := by simp [curveIntegral] @[simp] theorem CurveIntegrable.refl (ω : E → E →L[𝕜] F) (a : E) : CurveIntegrable ω (.refl a) := by simp [CurveIntegrable, Pi.zero_def] @[simp] theorem curveIntegralFun_cast (ω : E → E →L[𝕜] F) (γ : Path a b) (hc : c = a) (hd : d = b) : curveIntegralFun ω (γ.cast hc hd) = curveIntegralFun ω γ := by ext t simp only [curveIntegralFun_def', Path.extend_cast] @[simp] theorem curveIntegral_cast (ω : E → E →L[𝕜] F) (γ : Path a b) (hc : c = a) (hd : d = b) : ∫ᶜ x in γ.cast hc hd, ω x = ∫ᶜ x in γ, ω x := by simp [curveIntegral] @[simp] theorem curveIntegrable_cast_iff (hc : c = a) (hd : d = b) : CurveIntegrable ω (γ.cast hc hd) ↔ CurveIntegrable ω γ := by simp [CurveIntegrable] protected alias ⟨_, CurveIntegrable.cast⟩ := curveIntegrable_cast_iff theorem curveIntegralFun_symm_apply (ω : E → E →L[𝕜] F) (γ : Path a b) (t : ℝ) : curveIntegralFun ω γ.symm t = -curveIntegralFun ω γ (1 - t) := by simp [curveIntegralFun, γ.extend_symm, derivWithin_comp_const_sub] @[simp] theorem curveIntegralFun_symm (ω : E → E →L[𝕜] F) (γ : Path a b) : curveIntegralFun ω γ.symm = (-curveIntegralFun ω γ <| 1 - ·) := funext <| curveIntegralFun_symm_apply ω γ protected theorem CurveIntegrable.symm (h : CurveIntegrable ω γ) : CurveIntegrable ω γ.symm := by simpa [CurveIntegrable] using (h.comp_sub_left 1).neg.symm @[simp] theorem curveIntegrable_symm : CurveIntegrable ω γ.symm ↔ CurveIntegrable ω γ := ⟨fun h ↦ by simpa using h.symm, .symm⟩ @[simp] theorem curveIntegral_symm (ω : E → E →L[𝕜] F) (γ : Path a b) : ∫ᶜ x in γ.symm, ω x = -∫ᶜ x in γ, ω x := by simp [curveIntegral, curveIntegralFun_symm] theorem curveIntegralFun_trans_of_lt_half (ω : E → E →L[𝕜] F) (γab : Path a b) (γbc : Path b c) (ht : t < 1 / 2) : curveIntegralFun ω (γab.trans γbc) t = (2 : ℕ) • curveIntegralFun ω γab (2 * t) := by let instE := NormedSpace.restrictScalars ℝ 𝕜 E have H₁ : (γab.trans γbc).extend =ᶠ[𝓝 t] (fun s ↦ γab.extend (2 * s)) := (eventually_le_nhds ht).mono fun _ ↦ Path.extend_trans_of_le_half _ _ have H₂ : (2 : ℝ) • I =ᶠ[𝓝 (2 * t)] I := by rw [LinearOrderedField.smul_Icc two_pos, mul_zero, mul_one, ← nhdsWithin_eq_iff_eventuallyEq] rcases lt_trichotomy t 0 with ht₀ | rfl | ht₀ · rw [notMem_closure_iff_nhdsWithin_eq_bot.mp, notMem_closure_iff_nhdsWithin_eq_bot.mp] <;> simp_intro h <;> linarith · simp · rw [nhdsWithin_eq_nhds.2, nhdsWithin_eq_nhds.2] <;> simp [*] <;> linarith rw [curveIntegralFun_def, H₁.self_of_nhds, H₁.derivWithin_eq_of_nhds, curveIntegralFun_def, derivWithin_comp_mul_left, ofNat_smul_eq_nsmul, map_nsmul, derivWithin_congr_set H₂] theorem curveIntegralFun_trans_aeeq_left (ω : E → E →L[𝕜] F) (γab : Path a b) (γbc : Path b c) : curveIntegralFun ω (γab.trans γbc) =ᵐ[volume.restrict (Ι (0 : ℝ) (1 / 2))] fun t ↦ (2 : ℕ) • curveIntegralFun ω γab (2 * t) := by rw [uIoc_of_le (by positivity), ← restrict_Ioo_eq_restrict_Ioc] filter_upwards [ae_restrict_mem measurableSet_Ioo] with t ⟨ht₀, ht⟩ exact curveIntegralFun_trans_of_lt_half ω γab γbc ht theorem curveIntegralFun_trans_of_half_lt (ω : E → E →L[𝕜] F) (γab : Path a b) (γbc : Path b c) (ht₀ : 1 / 2 < t) : curveIntegralFun ω (γab.trans γbc) t = (2 : ℕ) • curveIntegralFun ω γbc (2 * t - 1) := by rw [← (γab.trans γbc).symm_symm, curveIntegralFun_symm_apply, Path.trans_symm, curveIntegralFun_trans_of_lt_half (ht := by linarith), curveIntegralFun_symm_apply, smul_neg, neg_neg] congr 2 ring theorem curveIntegralFun_trans_aeeq_right (ω : E → E →L[𝕜] F) (γab : Path a b) (γbc : Path b c) : curveIntegralFun ω (γab.trans γbc) =ᵐ[volume.restrict (Ι (1 / 2 : ℝ) 1)] fun t ↦ (2 : ℕ) • curveIntegralFun ω γbc (2 * t - 1) := by rw [uIoc_of_le (by linarith), ← restrict_Ioo_eq_restrict_Ioc] filter_upwards [ae_restrict_mem measurableSet_Ioo] with t ⟨ht₁, ht₂⟩ exact curveIntegralFun_trans_of_half_lt ω γab γbc ht₁ theorem CurveIntegrable.intervalIntegrable_curveIntegralFun_trans_left (h : CurveIntegrable ω γab) (γbc : Path b c) : IntervalIntegrable (curveIntegralFun ω (γab.trans γbc)) volume 0 (1 / 2) := by refine .congr_ae ?_ (curveIntegralFun_trans_aeeq_left _ _ _).symm simpa [ofNat_smul_eq_nsmul] using h.comp_mul_left.smul (2 : 𝕜) theorem CurveIntegrable.intervalIntegrable_curveIntegralFun_trans_right (γab : Path a b) (h : CurveIntegrable ω γbc) : IntervalIntegrable (curveIntegralFun ω (γab.trans γbc)) volume (1 / 2) 1 := by refine .congr_ae ?_ (curveIntegralFun_trans_aeeq_right _ _ _).symm simpa [ofNat_smul_eq_nsmul] using h.comp_sub_right 1 |>.comp_mul_left (c := 2) |>.smul (2 : 𝕜) protected theorem CurveIntegrable.trans (h₁ : CurveIntegrable ω γab) (h₂ : CurveIntegrable ω γbc) : CurveIntegrable ω (γab.trans γbc) := (h₁.intervalIntegrable_curveIntegralFun_trans_left γbc).trans (h₂.intervalIntegrable_curveIntegralFun_trans_right γab) theorem curveIntegral_trans (h₁ : CurveIntegrable ω γab) (h₂ : CurveIntegrable ω γbc) : ∫ᶜ x in γab.trans γbc, ω x = (∫ᶜ x in γab, ω x) + ∫ᶜ x in γbc, ω x := by let instF := NormedSpace.restrictScalars ℝ 𝕜 F rw [curveIntegral_def, ← intervalIntegral.integral_add_adjacent_intervals (h₁.intervalIntegrable_curveIntegralFun_trans_left γbc) (h₂.intervalIntegrable_curveIntegralFun_trans_right γab), intervalIntegral.integral_congr_ae_restrict (curveIntegralFun_trans_aeeq_left _ _ _), intervalIntegral.integral_congr_ae_restrict (curveIntegralFun_trans_aeeq_right _ _ _)] simp only [← ofNat_smul_eq_nsmul (R := ℝ)] rw [intervalIntegral.integral_smul, intervalIntegral.smul_integral_comp_mul_left, intervalIntegral.integral_smul, intervalIntegral.smul_integral_comp_mul_left (f := (curveIntegralFun ω γbc <| · - 1)), intervalIntegral.integral_comp_sub_right] simp only [curveIntegral_def] norm_num theorem curveIntegralFun_segment [NormedSpace ℝ E] (ω : E → E →L[𝕜] F) (a b : E) {t : ℝ} (ht : t ∈ I) : curveIntegralFun ω (.segment a b) t = ω (lineMap a b t) (b - a) := by have := Path.eqOn_extend_segment a b simp only [curveIntegralFun_def, this ht, derivWithin_congr this (this ht), (hasDerivWithinAt_lineMap ..).derivWithin (uniqueDiffOn_Icc_zero_one t ht)] theorem curveIntegrable_segment [NormedSpace ℝ E] : CurveIntegrable ω (.segment a b) ↔ IntervalIntegrable (fun t ↦ ω (lineMap a b t) (b - a)) volume 0 1 := by rw [CurveIntegrable, intervalIntegrable_congr] rw [uIoc_of_le zero_le_one] exact .mono Ioc_subset_Icc_self fun _t ↦ curveIntegralFun_segment ω a b theorem curveIntegral_segment [NormedSpace ℝ E] [NormedSpace ℝ F] (ω : E → E →L[𝕜] F) (a b : E) : ∫ᶜ x in .segment a b, ω x = ∫ t in 0..1, ω (lineMap a b t) (b - a) := by rw [curveIntegral_def] refine intervalIntegral.integral_congr fun t ht ↦ ?_ rw [uIcc_of_le zero_le_one] at ht exact curveIntegralFun_segment ω a b ht @[simp] theorem curveIntegral_segment_const [NormedSpace ℝ E] [CompleteSpace F] (ω : E →L[𝕜] F) (a b : E) : ∫ᶜ _ in .segment a b, ω = ω (b - a) := by letI : NormedSpace ℝ F := .restrictScalars ℝ 𝕜 F simp [curveIntegral_segment] /-- If `‖ω z‖ ≤ C` at all points of the segment `[a -[ℝ] b]`, then the curve integral `∫ᶜ x in .segment a b, ω x` has norm at most `C * ‖b - a‖`. -/ theorem norm_curveIntegral_segment_le [NormedSpace ℝ E] {C : ℝ} (h : ∀ z ∈ [a -[ℝ] b], ‖ω z‖ ≤ C) : ‖∫ᶜ x in .segment a b, ω x‖ ≤ C * ‖b - a‖ := calc ‖∫ᶜ x in .segment a b, ω x‖ ≤ C * ‖b - a‖ * |1 - 0| := by letI : NormedSpace ℝ F := .restrictScalars ℝ 𝕜 F rw [curveIntegral_segment] refine intervalIntegral.norm_integral_le_of_norm_le_const fun t ht ↦ ?_ rw [segment_eq_image_lineMap] at h rw [uIoc_of_le zero_le_one] at ht apply_rules [(ω _).le_of_opNorm_le, mem_image_of_mem, Ioc_subset_Icc_self] _ = C * ‖b - a‖ := by simp /-- If a 1-form `ω` is continuous on a set `s`, then it is curve integrable along any $C^1$ path in this set. -/ theorem ContinuousOn.curveIntegrable_of_contDiffOn [NormedSpace ℝ E] {s : Set E} (hω : ContinuousOn ω s) (hγ : ContDiffOn ℝ 1 γ.extend I) (hγs : ∀ t, γ t ∈ s) : CurveIntegrable ω γ := by apply ContinuousOn.intervalIntegrable_of_Icc zero_le_one simp only [funext (curveIntegralFun_def ω γ)] apply ContinuousOn.clm_apply · exact hω.comp (by fun_prop) fun _ _ ↦ hγs _ · exact hγ.continuousOn_derivWithin uniqueDiffOn_Icc_zero_one le_rfl end PathOperations /-! ### Algebraic operations on the 1-form -/ section Algebra variable {𝕜 E F : Type*} [RCLike 𝕜] [NormedAddCommGroup E] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [NormedSpace 𝕜 F] {a b : E} {ω ω₁ ω₂ : E → E →L[𝕜] F} {γ : Path a b} {t : ℝ} @[simp] theorem curveIntegralFun_add : curveIntegralFun (ω₁ + ω₂) γ = curveIntegralFun ω₁ γ + curveIntegralFun ω₂ γ := by ext; simp [curveIntegralFun] protected theorem CurveIntegrable.add (h₁ : CurveIntegrable ω₁ γ) (h₂ : CurveIntegrable ω₂ γ) : CurveIntegrable (ω₁ + ω₂) γ := by simpa [CurveIntegrable] using IntervalIntegrable.add h₁ h₂ theorem curveIntegral_add (h₁ : CurveIntegrable ω₁ γ) (h₂ : CurveIntegrable ω₂ γ) : curveIntegral (ω₁ + ω₂) γ = ∫ᶜ x in γ, ω₁ x + ∫ᶜ x in γ, ω₂ x := by letI : NormedSpace ℝ F := .restrictScalars ℝ 𝕜 F simp only [curveIntegral, curveIntegralFun_add] exact intervalIntegral.integral_add h₁ h₂ theorem curveIntegral_fun_add (h₁ : CurveIntegrable ω₁ γ) (h₂ : CurveIntegrable ω₂ γ) : ∫ᶜ x in γ, (ω₁ x + ω₂ x) = ∫ᶜ x in γ, ω₁ x + ∫ᶜ x in γ, ω₂ x := curveIntegral_add h₁ h₂ @[simp] theorem curveIntegralFun_zero : curveIntegralFun (0 : E → E →L[𝕜] F) γ = 0 := by ext; simp [curveIntegralFun] @[simp] theorem curveIntegralFun_fun_zero : curveIntegralFun (fun _ ↦ 0 : E → E →L[𝕜] F) γ = 0 := curveIntegralFun_zero theorem CurveIntegrable.zero : CurveIntegrable (0 : E → E →L[𝕜] F) γ := by simp [CurveIntegrable, IntervalIntegrable.zero] theorem CurveIntegrable.fun_zero : CurveIntegrable (fun _ ↦ 0 : E → E →L[𝕜] F) γ := .zero @[simp] theorem curveIntegral_zero : curveIntegral (0 : E → E →L[𝕜] F) γ = 0 := by simp [curveIntegral] @[simp] theorem curveIntegral_fun_zero : ∫ᶜ _ in γ, (0 : E →L[𝕜] F) = 0 := curveIntegral_zero @[simp] theorem curveIntegralFun_neg : curveIntegralFun (-ω) γ = -curveIntegralFun ω γ := by ext; simp [curveIntegralFun] theorem CurveIntegrable.neg (h : CurveIntegrable ω γ) : CurveIntegrable (-ω) γ := by simpa [CurveIntegrable] using IntervalIntegrable.neg h theorem CurveIntegrable.fun_neg (h : CurveIntegrable ω γ) : CurveIntegrable (-ω ·) γ := h.neg @[simp] theorem curveIntegrable_neg_iff : CurveIntegrable (-ω) γ ↔ CurveIntegrable ω γ := ⟨fun h ↦ by simpa using h.neg, .neg⟩ @[simp] theorem curveIntegrable_fun_neg_iff : CurveIntegrable (-ω ·) γ ↔ CurveIntegrable ω γ := curveIntegrable_neg_iff @[simp] theorem curveIntegral_neg : curveIntegral (-ω) γ = -∫ᶜ x in γ, ω x := by simp [curveIntegral] @[simp] theorem curveIntegral_fun_neg : ∫ᶜ x in γ, -ω x = -∫ᶜ x in γ, ω x := curveIntegral_neg @[simp] theorem curveIntegralFun_sub : curveIntegralFun (ω₁ - ω₂) γ = curveIntegralFun ω₁ γ - curveIntegralFun ω₂ γ := by simp [sub_eq_add_neg] protected theorem CurveIntegrable.sub (h₁ : CurveIntegrable ω₁ γ) (h₂ : CurveIntegrable ω₂ γ) : CurveIntegrable (ω₁ - ω₂) γ := sub_eq_add_neg ω₁ ω₂ ▸ h₁.add h₂.neg theorem curveIntegral_sub (h₁ : CurveIntegrable ω₁ γ) (h₂ : CurveIntegrable ω₂ γ) : curveIntegral (ω₁ - ω₂) γ = ∫ᶜ x in γ, ω₁ x - ∫ᶜ x in γ, ω₂ x := by rw [sub_eq_add_neg, sub_eq_add_neg, curveIntegral_add h₁ h₂.neg, curveIntegral_neg] theorem curveIntegral_fun_sub (h₁ : CurveIntegrable ω₁ γ) (h₂ : CurveIntegrable ω₂ γ) : ∫ᶜ x in γ, (ω₁ x - ω₂ x) = ∫ᶜ x in γ, ω₁ x - ∫ᶜ x in γ, ω₂ x := curveIntegral_sub h₁ h₂ section RestrictScalars variable {𝕝 : Type*} [RCLike 𝕝] [NormedSpace 𝕝 F] [NormedSpace 𝕝 E] [LinearMap.CompatibleSMul E F 𝕝 𝕜] @[simp] theorem curveIntegralFun_restrictScalars : curveIntegralFun (fun t ↦ (ω t).restrictScalars 𝕝) γ = curveIntegralFun ω γ := by ext letI : NormedSpace ℝ E := .restrictScalars ℝ 𝕜 E simp [curveIntegralFun_def] @[simp] theorem curveIntegrable_restrictScalars_iff : CurveIntegrable (fun t ↦ (ω t).restrictScalars 𝕝) γ ↔ CurveIntegrable ω γ := by simp [CurveIntegrable] @[simp] theorem curveIntegral_restrictScalars : ∫ᶜ x in γ, (ω x).restrictScalars 𝕝 = ∫ᶜ x in γ, ω x := by letI : NormedSpace ℝ F := .restrictScalars ℝ 𝕜 F simp [curveIntegral_def] end RestrictScalars variable {𝕝 : Type*} [RCLike 𝕝] [NormedSpace 𝕝 F] [SMulCommClass 𝕜 𝕝 F] {c : 𝕝} @[simp] theorem curveIntegralFun_smul : curveIntegralFun (c • ω) γ = c • curveIntegralFun ω γ := by ext simp [curveIntegralFun] theorem CurveIntegrable.smul (h : CurveIntegrable ω γ) : CurveIntegrable (c • ω) γ := by simpa [CurveIntegrable] using IntervalIntegrable.smul h c @[simp] theorem curveIntegrable_smul_iff : CurveIntegrable (c • ω) γ ↔ c = 0 ∨ CurveIntegrable ω γ := by rcases eq_or_ne c 0 with rfl | hc · simp [CurveIntegrable.zero] · simp only [hc, false_or] refine ⟨fun h ↦ ?_, .smul⟩ simpa [hc] using h.smul (c := c⁻¹) @[simp] theorem curveIntegral_smul : curveIntegral (c • ω) γ = c • curveIntegral ω γ := by letI : NormedSpace ℝ F := .restrictScalars ℝ 𝕜 F simp [curveIntegral_def, intervalIntegral.integral_smul] @[simp] theorem curveIntegral_fun_smul : ∫ᶜ x in γ, c • ω x = c • ∫ᶜ x in γ, ω x := curveIntegral_smul end Algebra section FDeriv variable {𝕜 E F : Type*} [RCLike 𝕜] [NormedAddCommGroup E] [NormedSpace ℝ E] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [NormedSpace 𝕜 F] [CompleteSpace F] {a b : E} {s : Set E} {ω : E → E →L[𝕜] F} /-! ### Derivative of the curve integral w.r.t. the right endpoint In this section we prove that the integral of `ω` along `[a -[ℝ] b]`, as a function of `b`, has derivative `ω a` at `b = a`. We provide several versions of this theorem, for `HasFDerivWithinAt` and `HasFDerivAt`, as well as for continuity near a point and for continuity on the whole set or space. Note that we take the derivative at the left endpoint of the segment. Similar facts about the derivative at a different point are true provided that `ω` is a closed 1-form (formalization WIP, see #24019). -/ /-- The integral of `ω` along `[a -[ℝ] b]`, as a function of `b`, has derivative `ω a` at `b = a`. This is a `HasFDerivWithinAt` version assuming that `ω` is continuous within a convex set `s` in a neighborhood of `a` within `s`. -/ theorem HasFDerivWithinAt.curveIntegral_segment_source' (hs : Convex ℝ s) (hω : ∀ᶠ x in 𝓝[s] a, ContinuousWithinAt ω s x) (ha : a ∈ s) : HasFDerivWithinAt (∫ᶜ x in .segment a ·, ω x) (ω a) s a := by /- Given `ε > 0`, take a number `δ > 0` such that `ω` is continuous on `ball a δ ∩ s` and `‖ω z - ω a‖ ≤ ε` on this set. Then for `b ∈ ball a δ ∩ s`, we have `‖(∫ᶜ x in .segment a b, ω x) - ω a (b - a)‖ = ‖(∫ᶜ x in .segment a b, ω x) - ∫ᶜ x in .segment a b, ω a‖ ≤ ∫ x in 0..1, ‖ω x - ω a‖ * ‖b - a‖ ≤ ε * ‖b - a‖` -/ simp only [HasFDerivWithinAt, hasFDerivAtFilter_iff_isLittleO, Path.segment_same, curveIntegral_refl, sub_zero, Asymptotics.isLittleO_iff] intro ε hε obtain ⟨δ, hδ₀, hδ⟩ : ∃ δ > 0, ball a δ ∩ s ⊆ {z | ContinuousWithinAt ω s z ∧ dist (ω z) (ω a) ≤ ε} := by rw [← Metric.mem_nhdsWithin_iff, setOf_and, inter_mem_iff] exact ⟨hω, (hω.self_of_nhdsWithin ha).eventually <| closedBall_mem_nhds _ hε⟩ rw [eventually_nhdsWithin_iff] filter_upwards [Metric.ball_mem_nhds _ hδ₀] with b hb hbs have hsub : [a -[ℝ] b] ⊆ ball a δ ∩ s := ((convex_ball _ _).inter hs).segment_subset (by simp [*]) (by simp [*]) rw [← curveIntegral_segment_const, ← curveIntegral_fun_sub] · refine norm_curveIntegral_segment_le fun z hz ↦ (hδ (hsub hz)).2 · rw [curveIntegrable_segment] refine ContinuousOn.intervalIntegrable_of_Icc zero_le_one fun t ht ↦ ?_ refine ((hδ ?_).1.eval_const _).comp AffineMap.lineMap_continuous.continuousWithinAt ?_ · refine hsub <| segment_eq_image_lineMap ℝ a b ▸ mem_image_of_mem _ ht · rw [mapsTo_iff_image_subset, ← segment_eq_image_lineMap] exact hs.segment_subset ha hbs · rw [curveIntegrable_segment] exact intervalIntegrable_const /-- The integral of `ω` along `[a -[ℝ] b]`, as a function of `b`, has derivative `ω a` at `b = a`. This is a `HasFDerivWithinAt` version assuming that `ω` is continuous on `s`. -/ theorem HasFDerivWithinAt.curveIntegral_segment_source (hs : Convex ℝ s) (hω : ContinuousOn ω s) (ha : a ∈ s) : HasFDerivWithinAt (∫ᶜ x in .segment a ·, ω x) (ω a) s a := .curveIntegral_segment_source' hs (mem_of_superset self_mem_nhdsWithin hω) ha /-- The integral of `ω` along `[a -[ℝ] b]`, as a function of `b`, has derivative `ω a` at `b = a`. This is a `HasFDerivAt` version assuming that `ω` is continuous in a neighborhood of `a`. -/ theorem HasFDerivAt.curveIntegral_segment_source' (hω : ∀ᶠ z in 𝓝 a, ContinuousAt ω z) : HasFDerivAt (∫ᶜ x in .segment a ·, ω x) (ω a) a := HasFDerivWithinAt.curveIntegral_segment_source' convex_univ (by simpa only [nhdsWithin_univ, continuousWithinAt_univ]) (mem_univ _) |>.hasFDerivAt_of_univ /-- The integral of `ω` along `[a -[ℝ] b]`, as a function of `b`, has derivative `ω a` at `b = a`. This is a `HasFDerivAt` version assuming that `ω` is continuous on the whole space. -/ theorem HasFDerivAt.curveIntegral_segment_source (hω : Continuous ω) : HasFDerivAt (∫ᶜ x in .segment a ·, ω x) (ω a) a := .curveIntegral_segment_source' <| .of_forall fun _ ↦ hω.continuousAt end FDeriv
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/IntervalIntegral/LebesgueDifferentiationThm.lean
import Mathlib.Analysis.Calculus.Deriv.Slope import Mathlib.MeasureTheory.Covering.OneDim import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic /-! # Lebesgue Differentiation Theorem (Interval Version) This file proves the interval version of the Lebesgue Differentiation Theorem. There are two versions in this file. * `LocallyIntegrable.ae_hasDerivAt_integral` is the global version. It states that if `f : ℝ → ℝ` is locally integrable, then for almost every `x`, for any `c : ℝ`, the derivative of `∫ (t : ℝ) in c..x, f t` at `x` is equal to `f x`. * `IntervalIntegrable.ae_hasDerivAt_integral` is the local version. It states that if `f : ℝ → ℝ` is interval integrable on `a..b`, then for almost every `x ∈ uIcc a b`, for any `c ∈ uIcc a b`, the derivative of `∫ (t : ℝ) in c..x, f t` at `x` is equal to `f x`. -/ open MeasureTheory Set Filter Function IsUnifLocDoublingMeasure open scoped Topology /-- The (global) interval version of the *Lebesgue Differentiation Theorem*: if `f : ℝ → ℝ` is locally integrable, then for almost every `x`, for any `c : ℝ`, the derivative of `∫ (t : ℝ) in c..x, f t` at `x` is equal to `f x`. -/ theorem LocallyIntegrable.ae_hasDerivAt_integral {f : ℝ → ℝ} (hf : LocallyIntegrable f volume) : ∀ᵐ x, ∀ c, HasDerivAt (fun x => ∫ (t : ℝ) in c..x, f t) (f x) x := by have hg (x y : ℝ) : IntervalIntegrable f volume x y := intervalIntegrable_iff.mpr <| (hf.integrableOn_isCompact isCompact_uIcc).mono_set uIoc_subset_uIcc have LDT := (vitaliFamily volume 1).ae_tendsto_average hf have {a b : ℝ} : ∫ (t : ℝ) in Ioc a b, f t = ∫ (t : ℝ) in Icc a b, f t := integral_Icc_eq_integral_Ioc (x := a) (y := b) (X := ℝ) |>.symm filter_upwards [LDT] with x hx intro c rw [hasDerivAt_iff_tendsto_slope_left_right] constructor · refine Filter.tendsto_congr' ?_ |>.mpr (hx.comp x.tendsto_Icc_vitaliFamily_left) filter_upwards [self_mem_nhdsWithin] with y hy replace hy : y ≤ x := by grind simp [slope, average, intervalIntegral.integral_interval_sub_left, hg, intervalIntegral.integral_of_ge, hy, this] grind · refine Filter.tendsto_congr' ?_ |>.mpr (hx.comp x.tendsto_Icc_vitaliFamily_right) filter_upwards [self_mem_nhdsWithin] with y hy replace hy : x ≤ y := by grind simp [slope, average, intervalIntegral.integral_interval_sub_left, hg, intervalIntegral.integral_of_le, hy, this] /-- The (local) interval version of the *Lebesgue Differentiation Theorem*: if `f : ℝ → ℝ` is interval integrable on `a..b`, then for almost every `x ∈ uIcc a b`, for any `c ∈ uIcc a b`, the derivative of `∫ (t : ℝ) in c..x, f t` at `x` is equal to `f x`. -/ theorem IntervalIntegrable.ae_hasDerivAt_integral {f : ℝ → ℝ} {a b : ℝ} (hf : IntervalIntegrable f volume a b) : ∀ᵐ x, x ∈ uIcc a b → ∀ c ∈ uIcc a b, HasDerivAt (fun x => ∫ (t : ℝ) in c..x, f t) (f x) x := by wlog hab : a ≤ b · exact uIcc_comm b a ▸ @this f b a hf.symm (by linarith) rw [uIcc_of_le hab] have h₁ : ∀ᵐ x, x ≠ a := by simp [ae_iff, measure_singleton] have h₂ : ∀ᵐ x, x ≠ b := by simp [ae_iff, measure_singleton] let g (x : ℝ) := if x ∈ Ioc a b then f x else 0 have hg : LocallyIntegrable g volume := integrableOn_congr_fun (by grind [EqOn]) (by simp) |>.mpr hf.left |>.integrable_of_forall_notMem_eq_zero (by grind) |>.locallyIntegrable filter_upwards [LocallyIntegrable.ae_hasDerivAt_integral hg, h₁, h₂] with x hx _ _ _ intro c hc #adaptation_note /-- 2025-09-30 https://github.com/leanprover/lean4/issues/10622 `grind -order` calls used be `grind` -/ refine HasDerivWithinAt.hasDerivAt (s := Ioo a b) ?_ <| Ioo_mem_nhds (by grind -order) (by grind -order) rw [show f x = g x by grind -order] refine (hx c).hasDerivWithinAt.congr (fun y hy ↦ ?_) ?_ all_goals apply intervalIntegral.integral_congr_ae' <;> filter_upwards <;> grind
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/IntervalIntegral/IntegrationByParts.lean
import Mathlib.Analysis.Calculus.Deriv.Mul import Mathlib.Analysis.Calculus.Deriv.Slope import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus /-! # Integration by parts and by substitution We derive additional integration techniques from FTC-2: * `intervalIntegral.integral_mul_deriv_eq_deriv_mul` - integration by parts * `intervalIntegral.integral_comp_mul_deriv''` - integration by substitution Versions of the change of variables formula for monotone and antitone functions, but with much weaker assumptions on the integrands and not restricted to intervals, can be found in `Mathlib/MeasureTheory/Function/JacobianOneDim.lean` ## Tags integration by parts, change of variables in integrals -/ open MeasureTheory Set open scoped Topology Interval namespace intervalIntegral variable {a b : ℝ} section Parts section Mul variable {A : Type*} [NormedRing A] [NormedAlgebra ℝ A] [CompleteSpace A] {u v u' v' : ℝ → A} /-- The integral of the derivative of a product of two maps. For improper integrals, see `MeasureTheory.integral_deriv_mul_eq_sub`, `MeasureTheory.integral_Ioi_deriv_mul_eq_sub`, and `MeasureTheory.integral_Iic_deriv_mul_eq_sub`. -/ theorem integral_deriv_mul_eq_sub_of_hasDeriv_right (hu : ContinuousOn u [[a, b]]) (hv : ContinuousOn v [[a, b]]) (huu' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt u (u' x) (Ioi x) x) (hvv' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt v (v' x) (Ioi x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := by apply integral_eq_sub_of_hasDeriv_right (hu.mul hv) fun x hx ↦ (huu' x hx).mul (hvv' x hx) exact (hu'.mul_continuousOn hv).add (hv'.continuousOn_mul hu) /-- The integral of the derivative of a product of two maps. Special case of `integral_deriv_mul_eq_sub_of_hasDeriv_right` where the functions have a two-sided derivative in the interior of the interval. -/ theorem integral_deriv_mul_eq_sub_of_hasDerivAt (hu : ContinuousOn u [[a, b]]) (hv : ContinuousOn v [[a, b]]) (huu' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivAt u (u' x) x) (hvv' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivAt v (v' x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := integral_deriv_mul_eq_sub_of_hasDeriv_right hu hv (fun x hx ↦ huu' x hx |>.hasDerivWithinAt) (fun x hx ↦ hvv' x hx |>.hasDerivWithinAt) hu' hv' /-- The integral of the derivative of a product of two maps. Special case of `integral_deriv_mul_eq_sub_of_hasDeriv_right` where the functions have a one-sided derivative at the endpoints. -/ theorem integral_deriv_mul_eq_sub_of_hasDerivWithinAt (hu : ∀ x ∈ [[a, b]], HasDerivWithinAt u (u' x) [[a, b]] x) (hv : ∀ x ∈ [[a, b]], HasDerivWithinAt v (v' x) [[a, b]] x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := integral_deriv_mul_eq_sub_of_hasDerivAt (fun x hx ↦ (hu x hx).continuousWithinAt) (fun x hx ↦ (hv x hx).continuousWithinAt) (fun x hx ↦ hu x (mem_Icc_of_Ioo hx) |>.hasDerivAt (Icc_mem_nhds hx.1 hx.2)) (fun x hx ↦ hv x (mem_Icc_of_Ioo hx) |>.hasDerivAt (Icc_mem_nhds hx.1 hx.2)) hu' hv' /-- Special case of `integral_deriv_mul_eq_sub_of_hasDeriv_right` where the functions have a derivative at the endpoints. -/ theorem integral_deriv_mul_eq_sub (hu : ∀ x ∈ [[a, b]], HasDerivAt u (u' x) x) (hv : ∀ x ∈ [[a, b]], HasDerivAt v (v' x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := integral_deriv_mul_eq_sub_of_hasDerivWithinAt (fun x hx ↦ hu x hx |>.hasDerivWithinAt) (fun x hx ↦ hv x hx |>.hasDerivWithinAt) hu' hv' /-- **Integration by parts**. For improper integrals, see `MeasureTheory.integral_mul_deriv_eq_deriv_mul`, `MeasureTheory.integral_Ioi_mul_deriv_eq_deriv_mul`, and `MeasureTheory.integral_Iic_mul_deriv_eq_deriv_mul`. -/ theorem integral_mul_deriv_eq_deriv_mul_of_hasDeriv_right (hu : ContinuousOn u [[a, b]]) (hv : ContinuousOn v [[a, b]]) (huu' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt u (u' x) (Ioi x) x) (hvv' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt v (v' x) (Ioi x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, u' x * v x := by rw [← integral_deriv_mul_eq_sub_of_hasDeriv_right hu hv huu' hvv' hu' hv', ← integral_sub] · simp_rw [add_sub_cancel_left] · exact (hu'.mul_continuousOn hv).add (hv'.continuousOn_mul hu) · exact hu'.mul_continuousOn hv /-- **Integration by parts**. Special case of `integral_mul_deriv_eq_deriv_mul_of_hasDeriv_right` where the functions have a two-sided derivative in the interior of the interval. -/ theorem integral_mul_deriv_eq_deriv_mul_of_hasDerivAt (hu : ContinuousOn u [[a, b]]) (hv : ContinuousOn v [[a, b]]) (huu' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivAt u (u' x) x) (hvv' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivAt v (v' x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, u' x * v x := integral_mul_deriv_eq_deriv_mul_of_hasDeriv_right hu hv (fun x hx ↦ (huu' x hx).hasDerivWithinAt) (fun x hx ↦ (hvv' x hx).hasDerivWithinAt) hu' hv' /-- **Integration by parts**. Special case of `intervalIntegrable.integral_mul_deriv_eq_deriv_mul_of_hasDeriv_right` where the functions have a one-sided derivative at the endpoints. -/ theorem integral_mul_deriv_eq_deriv_mul_of_hasDerivWithinAt (hu : ∀ x ∈ [[a, b]], HasDerivWithinAt u (u' x) [[a, b]] x) (hv : ∀ x ∈ [[a, b]], HasDerivWithinAt v (v' x) [[a, b]] x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, u' x * v x := integral_mul_deriv_eq_deriv_mul_of_hasDerivAt (fun x hx ↦ (hu x hx).continuousWithinAt) (fun x hx ↦ (hv x hx).continuousWithinAt) (fun x hx ↦ hu x (mem_Icc_of_Ioo hx) |>.hasDerivAt (Icc_mem_nhds hx.1 hx.2)) (fun x hx ↦ hv x (mem_Icc_of_Ioo hx) |>.hasDerivAt (Icc_mem_nhds hx.1 hx.2)) hu' hv' /-- **Integration by parts**. Special case of `intervalIntegrable.integral_mul_deriv_eq_deriv_mul_of_hasDeriv_right` where the functions have a derivative also at the endpoints. For improper integrals, see `MeasureTheory.integral_mul_deriv_eq_deriv_mul`, `MeasureTheory.integral_Ioi_mul_deriv_eq_deriv_mul`, and `MeasureTheory.integral_Iic_mul_deriv_eq_deriv_mul`. -/ theorem integral_mul_deriv_eq_deriv_mul (hu : ∀ x ∈ [[a, b]], HasDerivAt u (u' x) x) (hv : ∀ x ∈ [[a, b]], HasDerivAt v (v' x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, u' x * v x := integral_mul_deriv_eq_deriv_mul_of_hasDerivWithinAt (fun x hx ↦ (hu x hx).hasDerivWithinAt) (fun x hx ↦ (hv x hx).hasDerivWithinAt) hu' hv' end Mul section SMul variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] [NormedAlgebra ℝ 𝕜] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] [NormedSpace ℝ E] [CompleteSpace E] variable [IsScalarTower ℝ 𝕜 E] variable {u u' : ℝ → 𝕜} variable {v v' : ℝ → E} /-- The integral of the derivative of a scalar multiplication. -/ theorem integral_deriv_smul_eq_sub_of_hasDeriv_right (hu : ContinuousOn u [[a, b]]) (hv : ContinuousOn v [[a, b]]) (huu' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt u (u' x) (Ioi x) x) (hvv' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt v (v' x) (Ioi x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u' x • v x + u x • v' x = u b • v b - u a • v a := by simp_rw [add_comm] apply integral_eq_sub_of_hasDeriv_right (hu.smul hv) fun x hx ↦ (huu' x hx).smul (hvv' x hx) exact (hv'.continuousOn_smul hu).add (hu'.smul_continuousOn hv) /-- **Integration by parts** (vector-valued). -/ theorem integral_smul_deriv_eq_deriv_smul_of_hasDeriv_right (hu : ContinuousOn u [[a, b]]) (hv : ContinuousOn v [[a, b]]) (huu' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt u (u' x) (Ioi x) x) (hvv' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt v (v' x) (Ioi x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u x • v' x = u b • v b - u a • v a - ∫ x in a..b, u' x • v x := by rw [← integral_deriv_smul_eq_sub_of_hasDeriv_right hu hv huu' hvv' hu' hv', ← integral_sub] · simp_rw [add_sub_cancel_left] · exact (hu'.smul_continuousOn hv).add (hv'.continuousOn_smul hu) · exact hu'.smul_continuousOn hv /-- **Integration by parts** (vector-valued). Special case of `integral_smul_deriv_eq_deriv_smul_of_hasDeriv_right` where the functions have a two-sided derivative in the interior of the interval. -/ theorem integral_smul_deriv_eq_deriv_smul_of_hasDerivAt (hu : ContinuousOn u [[a, b]]) (hv : ContinuousOn v [[a, b]]) (huu' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivAt u (u' x) x) (hvv' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivAt v (v' x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u x • v' x = u b • v b - u a • v a - ∫ x in a..b, u' x • v x := integral_smul_deriv_eq_deriv_smul_of_hasDeriv_right hu hv (fun x hx ↦ (huu' x hx).hasDerivWithinAt) (fun x hx ↦ (hvv' x hx).hasDerivWithinAt) hu' hv' /-- **Integration by parts** (vector-valued). Special case of `intervalIntegrable.integral_smul_deriv_eq_deriv_smul_of_hasDeriv_right` where the functions have a one-sided derivative at the endpoints. -/ theorem integral_smul_deriv_eq_deriv_smul_of_hasDerivWithinAt (hu : ∀ x ∈ [[a, b]], HasDerivWithinAt u (u' x) [[a, b]] x) (hv : ∀ x ∈ [[a, b]], HasDerivWithinAt v (v' x) [[a, b]] x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u x • v' x = u b • v b - u a • v a - ∫ x in a..b, u' x • v x := integral_smul_deriv_eq_deriv_smul_of_hasDerivAt (fun x hx ↦ (hu x hx).continuousWithinAt) (fun x hx ↦ (hv x hx).continuousWithinAt) (fun x hx ↦ hu x (mem_Icc_of_Ioo hx) |>.hasDerivAt (Icc_mem_nhds hx.1 hx.2)) (fun x hx ↦ hv x (mem_Icc_of_Ioo hx) |>.hasDerivAt (Icc_mem_nhds hx.1 hx.2)) hu' hv' /-- **Integration by parts** (vector-valued). Special case of `intervalIntegrable.integral_smul_deriv_eq_deriv_smul_of_hasDeriv_right` where the functions have a derivative also at the endpoints. -/ theorem integral_smul_deriv_eq_deriv_smul (hu : ∀ x ∈ [[a, b]], HasDerivAt u (u' x) x) (hv : ∀ x ∈ [[a, b]], HasDerivAt v (v' x) x) (hu' : IntervalIntegrable u' volume a b) (hv' : IntervalIntegrable v' volume a b) : ∫ x in a..b, u x • v' x = u b • v b - u a • v a - ∫ x in a..b, u' x • v x := integral_smul_deriv_eq_deriv_smul_of_hasDerivWithinAt (fun x hx ↦ (hu x hx).hasDerivWithinAt) (fun x hx ↦ (hv x hx).hasDerivWithinAt) hu' hv' end SMul end Parts /-! ### Integration by substitution / Change of variables -/ section SMul variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] {f f' : ℝ → ℝ} {g g' : ℝ → E} /-- Change of variables, general form. If `f` is continuous on `[a, b]` and has right-derivative `f'` in `(a, b)`, `g` is continuous on `f '' (a, b)` and integrable on `f '' [a, b]`, and `f' x • (g ∘ f) x` is integrable on `[a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. If the function `f` is monotone or antitone, see also `integral_image_eq_integral_deriv_smul_of_monotoneOn` dropping all assumptions on `g`. -/ theorem integral_comp_smul_deriv''' (hf : ContinuousOn f [[a, b]]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt f (f' x) (Ioi x) x) (hg_cont : ContinuousOn g (f '' Ioo (min a b) (max a b))) (hg1 : IntegrableOn g (f '' [[a, b]])) (hg2 : IntegrableOn (fun x ↦ f' x • (g ∘ f) x) [[a, b]]) : (∫ x in a..b, f' x • (g ∘ f) x) = ∫ u in f a..f b, g u := by by_cases hE : CompleteSpace E; swap · simp [intervalIntegral, integral, hE] rw [hf.image_uIcc, ← intervalIntegrable_iff'] at hg1 have h_cont : ContinuousOn (fun u ↦ ∫ t in f a..f u, g t) [[a, b]] := by refine (continuousOn_primitive_interval' hg1 ?_).comp hf ?_ · rw [← hf.image_uIcc]; exact mem_image_of_mem f left_mem_uIcc · rw [← hf.image_uIcc]; exact mapsTo_image _ _ have h_der : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt (fun u ↦ ∫ t in f a..f u, g t) (f' x • (g ∘ f) x) (Ioi x) x := by intro x hx obtain ⟨c, hc⟩ := nonempty_Ioo.mpr hx.1 obtain ⟨d, hd⟩ := nonempty_Ioo.mpr hx.2 have cdsub : [[c, d]] ⊆ Ioo (min a b) (max a b) := by rw [uIcc_of_le (hc.2.trans hd.1).le] exact Icc_subset_Ioo hc.1 hd.2 replace hg_cont := hg_cont.mono (image_mono cdsub) let J := [[sInf (f '' [[c, d]]), sSup (f '' [[c, d]])]] have hJ : f '' [[c, d]] = J := (hf.mono (cdsub.trans Ioo_subset_Icc_self)).image_uIcc rw [hJ] at hg_cont have h2x : f x ∈ J := by rw [← hJ]; exact mem_image_of_mem _ (mem_uIcc_of_le hc.2.le hd.1.le) have h2g : IntervalIntegrable g volume (f a) (f x) := by refine hg1.mono_set ?_ rw [← hf.image_uIcc] exact hf.surjOn_uIcc left_mem_uIcc (Ioo_subset_Icc_self hx) have h3g : StronglyMeasurableAtFilter g (𝓝[J] f x) := hg_cont.stronglyMeasurableAtFilter_nhdsWithin measurableSet_Icc (f x) haveI : Fact (f x ∈ J) := ⟨h2x⟩ have : HasDerivWithinAt (fun u ↦ ∫ x in f a..u, g x) (g (f x)) J (f x) := intervalIntegral.integral_hasDerivWithinAt_right h2g h3g (hg_cont (f x) h2x) refine (this.scomp x ((hff' x hx).Ioo_of_Ioi hd.1) ?_).Ioi_of_Ioo hd.1 rw [← hJ] refine (mapsTo_image _ _).mono ?_ Subset.rfl exact Ioo_subset_Icc_self.trans ((Icc_subset_Icc_left hc.2.le).trans Icc_subset_uIcc) rw [← intervalIntegrable_iff'] at hg2 simp_rw [integral_eq_sub_of_hasDeriv_right h_cont h_der hg2, integral_same, sub_zero] /-- Change of variables for continuous integrands. If `f` is continuous on `[a, b]` and has continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. If the function `f` is monotone or antitone, see also `integral_image_eq_integral_deriv_smul_of_monotoneOn` dropping all assumptions on `g`. -/ theorem integral_comp_smul_deriv'' (hf : ContinuousOn f [[a, b]]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt f (f' x) (Ioi x) x) (hf' : ContinuousOn f' [[a, b]]) (hg : ContinuousOn g (f '' [[a, b]])) : (∫ x in a..b, f' x • (g ∘ f) x) = ∫ u in f a..f b, g u := by refine integral_comp_smul_deriv''' hf hff' (hg.mono <| image_mono Ioo_subset_Icc_self) ?_ (hf'.smul (hg.comp hf <| subset_preimage_image f _)).integrableOn_Icc rw [hf.image_uIcc] at hg ⊢ exact hg.integrableOn_Icc /-- Change of variables. If `f` has continuous derivative `f'` on `[a, b]`, and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. Compared to `intervalIntegral.integral_comp_smul_deriv` we only require that `g` is continuous on `f '' [a, b]`. If the function `f` is monotone or antitone, see also `integral_image_eq_integral_deriv_smul_of_monotoneOn` dropping all assumptions on `g`. -/ theorem integral_comp_smul_deriv' (h : ∀ x ∈ uIcc a b, HasDerivAt f (f' x) x) (h' : ContinuousOn f' (uIcc a b)) (hg : ContinuousOn g (f '' [[a, b]])) : (∫ x in a..b, f' x • (g ∘ f) x) = ∫ x in f a..f b, g x := integral_comp_smul_deriv'' (fun x hx ↦ (h x hx).continuousAt.continuousWithinAt) (fun x hx ↦ (h x <| Ioo_subset_Icc_self hx).hasDerivWithinAt) h' hg /-- Change of variables, most common version. If `f` has continuous derivative `f'` on `[a, b]`, and `g` is continuous, then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. If the function `f` is monotone or antitone, see also `integral_image_eq_integral_deriv_smul_of_monotoneOn` dropping all assumptions on `g`. -/ theorem integral_comp_smul_deriv (h : ∀ x ∈ uIcc a b, HasDerivAt f (f' x) x) (h' : ContinuousOn f' (uIcc a b)) (hg : Continuous g) : (∫ x in a..b, f' x • (g ∘ f) x) = ∫ x in f a..f b, g x := integral_comp_smul_deriv' h h' hg.continuousOn section CompleteSpace variable [CompleteSpace E] theorem integral_deriv_comp_smul_deriv' (hf : ContinuousOn f [[a, b]]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt f (f' x) (Ioi x) x) (hf' : ContinuousOn f' [[a, b]]) (hg : ContinuousOn g [[f a, f b]]) (hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), HasDerivWithinAt g (g' x) (Ioi x) x) (hg' : ContinuousOn g' (f '' [[a, b]])) : (∫ x in a..b, f' x • (g' ∘ f) x) = (g ∘ f) b - (g ∘ f) a := by rw [integral_comp_smul_deriv'' hf hff' hf' hg', integral_eq_sub_of_hasDeriv_right hg hgg' (hg'.mono _).intervalIntegrable] exacts [rfl, intermediate_value_uIcc hf] theorem integral_deriv_comp_smul_deriv (hf : ∀ x ∈ uIcc a b, HasDerivAt f (f' x) x) (hg : ∀ x ∈ uIcc a b, HasDerivAt g (g' (f x)) (f x)) (hf' : ContinuousOn f' (uIcc a b)) (hg' : Continuous g') : (∫ x in a..b, f' x • (g' ∘ f) x) = (g ∘ f) b - (g ∘ f) a := integral_eq_sub_of_hasDerivAt (fun x hx ↦ (hg x hx).scomp x <| hf x hx) (hf'.smul (hg'.comp_continuousOn <| HasDerivAt.continuousOn hf)).intervalIntegrable end CompleteSpace end SMul section Mul /-- Change of variables, general form for scalar functions. If `f` is continuous on `[a, b]` and has continuous right-derivative `f'` in `(a, b)`, `g` is continuous on `f '' (a, b)` and integrable on `f '' [a, b]`, and `(g ∘ f) x * f' x` is integrable on `[a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_mul_deriv''' {a b : ℝ} {f f' : ℝ → ℝ} {g : ℝ → ℝ} (hf : ContinuousOn f [[a, b]]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt f (f' x) (Ioi x) x) (hg_cont : ContinuousOn g (f '' Ioo (min a b) (max a b))) (hg1 : IntegrableOn g (f '' [[a, b]])) (hg2 : IntegrableOn (fun x ↦ (g ∘ f) x * f' x) [[a, b]]) : (∫ x in a..b, (g ∘ f) x * f' x) = ∫ u in f a..f b, g u := by have hg2' : IntegrableOn (fun x ↦ f' x • (g ∘ f) x) [[a, b]] := by simpa [mul_comm] using hg2 simpa [mul_comm] using integral_comp_smul_deriv''' hf hff' hg_cont hg1 hg2' /-- Change of variables for continuous integrands. If `f` is continuous on `[a, b]` and has continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_mul_deriv'' {f f' g : ℝ → ℝ} (hf : ContinuousOn f [[a, b]]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt f (f' x) (Ioi x) x) (hf' : ContinuousOn f' [[a, b]]) (hg : ContinuousOn g (f '' [[a, b]])) : (∫ x in a..b, (g ∘ f) x * f' x) = ∫ u in f a..f b, g u := by simpa [mul_comm] using integral_comp_smul_deriv'' hf hff' hf' hg /-- Change of variables. If `f` has continuous derivative `f'` on `[a, b]`, and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. Compared to `intervalIntegral.integral_comp_mul_deriv` we only require that `g` is continuous on `f '' [a, b]`. -/ theorem integral_comp_mul_deriv' {f f' g : ℝ → ℝ} (h : ∀ x ∈ uIcc a b, HasDerivAt f (f' x) x) (h' : ContinuousOn f' (uIcc a b)) (hg : ContinuousOn g (f '' [[a, b]])) : (∫ x in a..b, (g ∘ f) x * f' x) = ∫ x in f a..f b, g x := by simpa [mul_comm] using integral_comp_smul_deriv' h h' hg /-- Change of variables, most common version. If `f` has continuous derivative `f'` on `[a, b]`, and `g` is continuous, then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_mul_deriv {f f' g : ℝ → ℝ} (h : ∀ x ∈ uIcc a b, HasDerivAt f (f' x) x) (h' : ContinuousOn f' (uIcc a b)) (hg : Continuous g) : (∫ x in a..b, (g ∘ f) x * f' x) = ∫ x in f a..f b, g x := integral_comp_mul_deriv' h h' hg.continuousOn theorem integral_deriv_comp_mul_deriv' {f f' g g' : ℝ → ℝ} (hf : ContinuousOn f [[a, b]]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt f (f' x) (Ioi x) x) (hf' : ContinuousOn f' [[a, b]]) (hg : ContinuousOn g [[f a, f b]]) (hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), HasDerivWithinAt g (g' x) (Ioi x) x) (hg' : ContinuousOn g' (f '' [[a, b]])) : (∫ x in a..b, (g' ∘ f) x * f' x) = (g ∘ f) b - (g ∘ f) a := by simpa [mul_comm] using integral_deriv_comp_smul_deriv' hf hff' hf' hg hgg' hg' theorem integral_deriv_comp_mul_deriv {f f' g g' : ℝ → ℝ} (hf : ∀ x ∈ uIcc a b, HasDerivAt f (f' x) x) (hg : ∀ x ∈ uIcc a b, HasDerivAt g (g' (f x)) (f x)) (hf' : ContinuousOn f' (uIcc a b)) (hg' : Continuous g') : (∫ x in a..b, (g' ∘ f) x * f' x) = (g ∘ f) b - (g ∘ f) a := by simpa [mul_comm] using integral_deriv_comp_smul_deriv hf hg hf' hg' end Mul end intervalIntegral
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/IntervalIntegral/ContDiff.lean
import Mathlib.Analysis.Calculus.ContDiff.Basic import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus /-! # Fundamental theorem of calculus for `C^1` functions We give versions of the second fundamental theorem of calculus under the strong assumption that the function is `C^1` on the interval. This is restrictive, but satisfied in many situations. -/ noncomputable section open MeasureTheory Set Filter Function Asymptotics open scoped Topology ENNReal Interval NNReal variable {ι 𝕜 E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] {f : ℝ → E} {a b : ℝ} namespace intervalIntegral variable [CompleteSpace E] /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is `C^1` on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_of_contDiffOn_Icc (h : ContDiffOn ℝ 1 f (Icc a b)) (hab : a ≤ b) : ∫ x in a..b, deriv f x = f b - f a := by rcases hab.eq_or_lt with rfl | h'ab · simp apply integral_eq_sub_of_hasDerivAt_of_le hab h.continuousOn · intro x hx apply DifferentiableAt.hasDerivAt apply ((h x ⟨hx.1.le, hx.2.le⟩).differentiableWithinAt le_rfl).differentiableAt exact Icc_mem_nhds hx.1 hx.2 · have := (h.derivWithin (m := 0) (uniqueDiffOn_Icc h'ab) (by simp)).continuousOn apply (this.intervalIntegrable_of_Icc (μ := volume) hab).congr_ae simp only [hab, uIoc_of_le] rw [← restrict_Ioo_eq_restrict_Ioc] filter_upwards [self_mem_ae_restrict measurableSet_Ioo] with x hx exact derivWithin_of_mem_nhds (Icc_mem_nhds hx.1 hx.2) /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is `C^1` on `[a, b]`, then `∫ y in a..b, derivWithin f (Icc a b) y` equals `f b - f a`. -/ theorem integral_derivWithin_Icc_of_contDiffOn_Icc (h : ContDiffOn ℝ 1 f (Icc a b)) (hab : a ≤ b) : ∫ x in a..b, derivWithin f (Icc a b) x = f b - f a := by rw [← integral_deriv_of_contDiffOn_Icc h hab] rw [integral_of_le hab, integral_of_le hab] apply MeasureTheory.integral_congr_ae rw [← restrict_Ioo_eq_restrict_Ioc] filter_upwards [self_mem_ae_restrict measurableSet_Ioo] with x hx exact derivWithin_of_mem_nhds (Icc_mem_nhds hx.1 hx.2) /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is `C^1` on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_of_contDiffOn_uIcc (h : ContDiffOn ℝ 1 f (uIcc a b)) : ∫ x in a..b, deriv f x = f b - f a := by rcases le_or_gt a b with hab | hab · simp only [uIcc_of_le hab] at h exact integral_deriv_of_contDiffOn_Icc h hab · simp only [uIcc_of_ge hab.le] at h rw [integral_symm, integral_deriv_of_contDiffOn_Icc h hab.le] abel /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is `C^1` on `[a, b]`, then `∫ y in a..b, derivWithin f (uIcc a b) y` equals `f b - f a`. -/ theorem integral_derivWithin_uIcc_of_contDiffOn_uIcc (h : ContDiffOn ℝ 1 f (uIcc a b)) : ∫ x in a..b, derivWithin f (uIcc a b) x = f b - f a := by rcases le_or_gt a b with hab | hab · simp only [uIcc_of_le hab] at h ⊢ exact integral_derivWithin_Icc_of_contDiffOn_Icc h hab · simp only [uIcc_of_ge hab.le] at h ⊢ rw [integral_symm, integral_derivWithin_Icc_of_contDiffOn_Icc h hab.le] abel end intervalIntegral open intervalIntegral theorem enorm_sub_le_lintegral_deriv_of_contDiffOn_Icc (h : ContDiffOn ℝ 1 f (Icc a b)) (hab : a ≤ b) : ‖f b - f a‖ₑ ≤ ∫⁻ x in Icc a b, ‖deriv f x‖ₑ := by /- We want to write `f b - f a = ∫ x in Icc a b, deriv f x` and use the inequality between norm of integral and integral of norm. There is a small difficulty that this formula is not true when `E` is not complete, so we need to go first to the completion, and argue there. -/ let g := UniformSpace.Completion.toComplₗᵢ (𝕜 := ℝ) (E := E) have : ‖(g ∘ f) b - (g ∘ f) a‖ₑ = ‖f b - f a‖ₑ := by rw [← edist_eq_enorm_sub, Function.comp_def, g.isometry.edist_eq, edist_eq_enorm_sub] rw [← this, ← integral_deriv_of_contDiffOn_Icc (g.contDiff.comp_contDiffOn h) hab, integral_of_le hab, restrict_Ioc_eq_restrict_Icc] apply (enorm_integral_le_lintegral_enorm _).trans apply lintegral_mono_ae rw [← restrict_Ioo_eq_restrict_Icc] filter_upwards [self_mem_ae_restrict measurableSet_Ioo] with x hx rw [fderiv_comp_deriv]; rotate_left · exact (g.contDiff.differentiable le_rfl).differentiableAt · exact ((h x ⟨hx.1.le, hx.2.le⟩).contDiffAt (Icc_mem_nhds hx.1 hx.2)).differentiableAt le_rfl have : fderiv ℝ g (f x) = g.toContinuousLinearMap := g.toContinuousLinearMap.fderiv simp [this] theorem enorm_sub_le_lintegral_derivWithin_Icc_of_contDiffOn_Icc (h : ContDiffOn ℝ 1 f (Icc a b)) (hab : a ≤ b) : ‖f b - f a‖ₑ ≤ ∫⁻ x in Icc a b, ‖derivWithin f (Icc a b) x‖ₑ := by apply (enorm_sub_le_lintegral_deriv_of_contDiffOn_Icc h hab).trans_eq apply lintegral_congr_ae rw [← restrict_Ioo_eq_restrict_Icc] filter_upwards [self_mem_ae_restrict measurableSet_Ioo] with x hx rw [derivWithin_of_mem_nhds (Icc_mem_nhds hx.1 hx.2)]
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/IntervalIntegral/Basic.lean
import Mathlib.MeasureTheory.Integral.Bochner.ContinuousLinearMap import Mathlib.MeasureTheory.Measure.Lebesgue.Basic import Mathlib.MeasureTheory.Topology /-! # Integral over an interval In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and `-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`. ## Implementation notes ### Avoiding `if`, `min`, and `max` In order to avoid `if`s in the definition, we define `IntervalIntegrable f μ a b` as `IntegrableOn f (Ioc a b) μ ∧ IntegrableOn f (Ioc b a) μ`. For any `a`, `b` one of these intervals is empty and the other coincides with `Set.uIoc a b = Set.Ioc (min a b) (max a b)`. Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result. This way some properties can be translated from integrals over sets without dealing with the cases `a ≤ b` and `b ≤ a` separately. ### Choice of the interval We use integral over `Set.uIoc a b = Set.Ioc (min a b) (max a b)` instead of one of the other three possible intervals with the same endpoints for two reasons: * this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever `f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom at `b`; this rules out `Set.Ioo` and `Set.Icc` intervals; * with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) of `μ`. ## Tags integral -/ noncomputable section open MeasureTheory Set Filter Function TopologicalSpace open scoped Topology Filter ENNReal Interval NNReal variable {ι 𝕜 ε ε' E F A : Type*} [NormedAddCommGroup E] [TopologicalSpace ε] [ENormedAddMonoid ε] [TopologicalSpace ε'] [ENormedAddMonoid ε'] /-! ### Integrability on an interval -/ /-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these intervals is always empty, so this property is equivalent to `f` being integrable on `(min a b, max a b]`. -/ def IntervalIntegrable (f : ℝ → ε) (μ : Measure ℝ) (a b : ℝ) : Prop := IntegrableOn f (Ioc a b) μ ∧ IntegrableOn f (Ioc b a) μ /-! ## Basic iff's for `IntervalIntegrable` -/ section variable [PseudoMetrizableSpace ε] {f : ℝ → ε} {a b : ℝ} {μ : Measure ℝ} /-- A function is interval integrable with respect to a given measure `μ` on `a..b` if and only if it is integrable on `uIoc a b` with respect to `μ`. This is an equivalent definition of `IntervalIntegrable`. -/ theorem intervalIntegrable_iff : IntervalIntegrable f μ a b ↔ IntegrableOn f (Ι a b) μ := by rw [uIoc_eq_union, integrableOn_union, IntervalIntegrable] /-- If a function is interval integrable with respect to a given measure `μ` on `a..b` then it is integrable on `uIoc a b` with respect to `μ`. -/ theorem IntervalIntegrable.def' (h : IntervalIntegrable f μ a b) : IntegrableOn f (Ι a b) μ := intervalIntegrable_iff.mp h theorem intervalIntegrable_congr_ae {g : ℝ → ε} (h : f =ᵐ[μ.restrict (Ι a b)] g) : IntervalIntegrable f μ a b ↔ IntervalIntegrable g μ a b := by rw [intervalIntegrable_iff, integrableOn_congr_fun_ae h, intervalIntegrable_iff] theorem IntervalIntegrable.congr_ae {g : ℝ → ε} (hf : IntervalIntegrable f μ a b) (h : f =ᵐ[μ.restrict (Ι a b)] g) : IntervalIntegrable g μ a b := by rwa [← intervalIntegrable_congr_ae h] theorem intervalIntegrable_congr {g : ℝ → ε} (h : EqOn f g (Ι a b)) : IntervalIntegrable f μ a b ↔ IntervalIntegrable g μ a b := intervalIntegrable_congr_ae <| (ae_restrict_mem measurableSet_uIoc).mono h alias ⟨IntervalIntegrable.congr, _⟩ := intervalIntegrable_congr /-- Interval integrability is invariant when functions change along discrete sets. -/ theorem IntervalIntegrable.congr_codiscreteWithin {g : ℝ → ε} [NoAtoms μ] (h : f =ᶠ[codiscreteWithin (Ι a b)] g) (hf : IntervalIntegrable f μ a b) : IntervalIntegrable g μ a b := hf.congr_ae (ae_restrict_le_codiscreteWithin measurableSet_Ioc h) /-- Interval integrability is invariant when functions change along discrete sets. -/ theorem intervalIntegrable_congr_codiscreteWithin {g : ℝ → ε} [NoAtoms μ] (h : f =ᶠ[codiscreteWithin (Ι a b)] g) : IntervalIntegrable f μ a b ↔ IntervalIntegrable g μ a b := ⟨(IntervalIntegrable.congr_codiscreteWithin h ·), (IntervalIntegrable.congr_codiscreteWithin h.symm ·)⟩ theorem intervalIntegrable_iff_integrableOn_Ioc_of_le (hab : a ≤ b) : IntervalIntegrable f μ a b ↔ IntegrableOn f (Ioc a b) μ := by rw [intervalIntegrable_iff, uIoc_of_le hab] theorem intervalIntegrable_iff' [NoAtoms μ] (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable f μ a b ↔ IntegrableOn f (uIcc a b) μ := by rw [intervalIntegrable_iff, ← Icc_min_max, uIoc, integrableOn_Icc_iff_integrableOn_Ioc h] theorem intervalIntegrable_iff_integrableOn_Icc_of_le [NoAtoms μ] (hab : a ≤ b) (ha : ‖f a‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable f μ a b ↔ IntegrableOn f (Icc a b) μ := by rw [intervalIntegrable_iff_integrableOn_Ioc_of_le hab, integrableOn_Icc_iff_integrableOn_Ioc ha] theorem intervalIntegrable_iff_integrableOn_Ico_of_le [NoAtoms μ] (hab : a ≤ b) (ha : ‖f a‖ₑ ≠ ∞ := by finiteness) (hb : ‖f b‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable f μ a b ↔ IntegrableOn f (Ico a b) μ := by rw [intervalIntegrable_iff_integrableOn_Icc_of_le hab ha, integrableOn_Icc_iff_integrableOn_Ico hb] theorem intervalIntegrable_iff_integrableOn_Ioo_of_le [NoAtoms μ] (hab : a ≤ b) (ha : ‖f a‖ₑ ≠ ∞ := by finiteness) (hb : ‖f b‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable f μ a b ↔ IntegrableOn f (Ioo a b) μ := by rw [intervalIntegrable_iff_integrableOn_Icc_of_le hab ha, integrableOn_Icc_iff_integrableOn_Ioo ha hb] omit [PseudoMetrizableSpace ε] in /-- If a function is integrable with respect to a given measure `μ` then it is interval integrable with respect to `μ` on `uIcc a b`. -/ theorem MeasureTheory.Integrable.intervalIntegrable (hf : Integrable f μ) : IntervalIntegrable f μ a b := ⟨hf.integrableOn, hf.integrableOn⟩ omit [PseudoMetrizableSpace ε] in theorem MeasureTheory.IntegrableOn.intervalIntegrable (hf : IntegrableOn f [[a, b]] μ) : IntervalIntegrable f μ a b := ⟨MeasureTheory.IntegrableOn.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_uIcc), MeasureTheory.IntegrableOn.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_uIcc')⟩ theorem intervalIntegrable_const_iff {c : ε} (hc : ‖c‖ₑ ≠ ⊤ := by finiteness) : IntervalIntegrable (fun _ => c) μ a b ↔ c = 0 ∨ μ (Ι a b) < ∞ := by simp [intervalIntegrable_iff, integrableOn_const_iff hc] @[simp] theorem intervalIntegrable_const [IsLocallyFiniteMeasure μ] {c : E} (hc : ‖c‖ₑ ≠ ⊤ := by finiteness) : IntervalIntegrable (fun _ => c) μ a b := intervalIntegrable_const_iff hc |>.2 <| Or.inr measure_Ioc_lt_top protected theorem IntervalIntegrable.zero : IntervalIntegrable (0 : ℝ → E) μ a b := (intervalIntegrable_const_iff <| by finiteness).mpr <| .inl rfl end /-! ## Basic properties of interval integrability - interval integrability is symmetric, reflexive, transitive - monotonicity and strong measurability of the interval integral - if `f` is interval integrable, so are its absolute value and norm - arithmetic properties -/ namespace IntervalIntegrable section variable {f : ℝ → ε} {a b c d : ℝ} {μ ν : Measure ℝ} @[symm] nonrec theorem symm (h : IntervalIntegrable f μ a b) : IntervalIntegrable f μ b a := h.symm theorem symm_iff : IntervalIntegrable f μ a b ↔ IntervalIntegrable f μ b a := ⟨.symm, .symm⟩ @[refl, simp] theorem refl : IntervalIntegrable f μ a a := by constructor <;> simp variable [PseudoMetrizableSpace ε] @[trans] theorem trans {a b c : ℝ} (hab : IntervalIntegrable f μ a b) (hbc : IntervalIntegrable f μ b c) : IntervalIntegrable f μ a c := ⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc, (hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩ theorem trans_iff (h : b ∈ [[a, c]]) : IntervalIntegrable f μ a c ↔ IntervalIntegrable f μ a b ∧ IntervalIntegrable f μ b c := by simp only [intervalIntegrable_iff, ← integrableOn_union, uIoc_union_uIoc h] theorem trans_iterate_Ico {a : ℕ → ℝ} {m n : ℕ} (hmn : m ≤ n) (hint : ∀ k ∈ Ico m n, IntervalIntegrable f μ (a k) (a <| k + 1)) : IntervalIntegrable f μ (a m) (a n) := by revert hint refine Nat.le_induction ?_ ?_ n hmn · simp · intro p hp IH h exact (IH fun k hk => h k (Ico_subset_Ico_right p.le_succ hk)).trans (h p (by simp [hp])) theorem trans_iterate {a : ℕ → ℝ} {n : ℕ} (hint : ∀ k < n, IntervalIntegrable f μ (a k) (a <| k + 1)) : IntervalIntegrable f μ (a 0) (a n) := trans_iterate_Ico bot_le fun k hk => hint k hk.2 theorem neg {f : ℝ → E} (h : IntervalIntegrable f μ a b) : IntervalIntegrable (-f) μ a b := ⟨h.1.neg, h.2.neg⟩ omit [PseudoMetrizableSpace ε] in theorem enorm (h : IntervalIntegrable f μ a b) : IntervalIntegrable (‖f ·‖ₑ) μ a b := ⟨h.1.enorm, h.2.enorm⟩ theorem norm {f : ℝ → E} (h : IntervalIntegrable f μ a b) : IntervalIntegrable (‖f ·‖) μ a b := ⟨h.1.norm, h.2.norm⟩ theorem intervalIntegrable_enorm_iff {μ : Measure ℝ} {a b : ℝ} (hf : AEStronglyMeasurable f (μ.restrict (Ι a b))) : IntervalIntegrable (fun t => ‖f t‖ₑ) μ a b ↔ IntervalIntegrable f μ a b := by simp_rw [intervalIntegrable_iff, IntegrableOn, integrable_enorm_iff hf] theorem intervalIntegrable_norm_iff {f : ℝ → E} {μ : Measure ℝ} {a b : ℝ} (hf : AEStronglyMeasurable f (μ.restrict (Ι a b))) : IntervalIntegrable (fun t => ‖f t‖) μ a b ↔ IntervalIntegrable f μ a b := by simp_rw [intervalIntegrable_iff, IntegrableOn, integrable_norm_iff hf] theorem abs {f : ℝ → ℝ} (h : IntervalIntegrable f μ a b) : IntervalIntegrable (fun x => |f x|) μ a b := h.norm theorem mono (hf : IntervalIntegrable f ν a b) (h1 : [[c, d]] ⊆ [[a, b]]) (h2 : μ ≤ ν) : IntervalIntegrable f μ c d := intervalIntegrable_iff.mpr <| hf.def'.mono (uIoc_subset_uIoc_of_uIcc_subset_uIcc h1) h2 theorem mono_measure (hf : IntervalIntegrable f ν a b) (h : μ ≤ ν) : IntervalIntegrable f μ a b := hf.mono Subset.rfl h theorem mono_set (hf : IntervalIntegrable f μ a b) (h : [[c, d]] ⊆ [[a, b]]) : IntervalIntegrable f μ c d := hf.mono h le_rfl theorem mono_set_ae (hf : IntervalIntegrable f μ a b) (h : Ι c d ≤ᵐ[μ] Ι a b) : IntervalIntegrable f μ c d := intervalIntegrable_iff.mpr <| hf.def'.mono_set_ae h theorem mono_set' (hf : IntervalIntegrable f μ a b) (hsub : Ι c d ⊆ Ι a b) : IntervalIntegrable f μ c d := hf.mono_set_ae <| Eventually.of_forall hsub theorem mono_fun_enorm [PseudoMetrizableSpace ε'] {g : ℝ → ε'} (hf : IntervalIntegrable f μ a b) (hgm : AEStronglyMeasurable g (μ.restrict (Ι a b))) (hle : (‖g ·‖ₑ) ≤ᵐ[μ.restrict (Ι a b)] (‖f ·‖ₑ)) : IntervalIntegrable g μ a b := intervalIntegrable_iff.2 <| hf.def'.integrable.mono_enorm hgm hle theorem mono_fun {f : ℝ → E} [NormedAddCommGroup F] {g : ℝ → F} (hf : IntervalIntegrable f μ a b) (hgm : AEStronglyMeasurable g (μ.restrict (Ι a b))) (hle : (fun x => ‖g x‖) ≤ᵐ[μ.restrict (Ι a b)] fun x => ‖f x‖) : IntervalIntegrable g μ a b := intervalIntegrable_iff.2 <| hf.def'.integrable.mono hgm hle -- XXX: the best spelling of this lemma may look slightly different (e.gl, with different domain) theorem mono_fun_enorm' {f : ℝ → ε} {g : ℝ → ℝ≥0∞} (hg : IntervalIntegrable g μ a b) (hfm : AEStronglyMeasurable f (μ.restrict (Ι a b))) (hle : (fun x => ‖f x‖ₑ) ≤ᵐ[μ.restrict (Ι a b)] g) : IntervalIntegrable f μ a b := intervalIntegrable_iff.2 <| hg.def'.integrable.mono_enorm hfm hle theorem mono_fun' {f : ℝ → E} {g : ℝ → ℝ} (hg : IntervalIntegrable g μ a b) (hfm : AEStronglyMeasurable f (μ.restrict (Ι a b))) (hle : (fun x => ‖f x‖) ≤ᵐ[μ.restrict (Ι a b)] g) : IntervalIntegrable f μ a b := intervalIntegrable_iff.2 <| hg.def'.integrable.mono' hfm hle omit [PseudoMetrizableSpace ε] in protected theorem aestronglyMeasurable (h : IntervalIntegrable f μ a b) : AEStronglyMeasurable f (μ.restrict (Ioc a b)) := h.1.aestronglyMeasurable omit [PseudoMetrizableSpace ε] in protected theorem aestronglyMeasurable' (h : IntervalIntegrable f μ a b) : AEStronglyMeasurable f (μ.restrict (Ioc b a)) := h.2.aestronglyMeasurable end variable [NormedRing A] {f g : ℝ → ε} {a b : ℝ} {μ : Measure ℝ} theorem smul {R : Type*} [NormedAddCommGroup R] [SMulZeroClass R E] [IsBoundedSMul R E] {f : ℝ → E} (h : IntervalIntegrable f μ a b) (r : R) : IntervalIntegrable (r • f) μ a b := ⟨h.1.smul r, h.2.smul r⟩ @[simp] theorem add [ContinuousAdd ε] (hf : IntervalIntegrable f μ a b) (hg : IntervalIntegrable g μ a b) : IntervalIntegrable (fun x => f x + g x) μ a b := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ @[simp] theorem sub {f g : ℝ → E} (hf : IntervalIntegrable f μ a b) (hg : IntervalIntegrable g μ a b) : IntervalIntegrable (fun x => f x - g x) μ a b := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ theorem sum {ε} [TopologicalSpace ε] [ENormedAddCommMonoid ε] [ContinuousAdd ε] (s : Finset ι) {f : ι → ℝ → ε} (h : ∀ i ∈ s, IntervalIntegrable (f i) μ a b) : IntervalIntegrable (∑ i ∈ s, f i) μ a b := ⟨integrable_finset_sum' s fun i hi => (h i hi).1, integrable_finset_sum' s fun i hi => (h i hi).2⟩ /-- Finite sums of interval integrable functions are interval integrable. -/ @[simp] protected theorem finsum {ε} [TopologicalSpace ε] [ENormedAddCommMonoid ε] [ContinuousAdd ε] [PseudoMetrizableSpace ε] {f : ι → ℝ → ε} (h : ∀ i, IntervalIntegrable (f i) μ a b) : IntervalIntegrable (∑ᶠ i, f i) μ a b := by by_cases h₁ : f.support.Finite · simp [finsum_eq_sum _ h₁, IntervalIntegrable.sum h₁.toFinset (fun i _ ↦ h i)] · rw [finsum_of_infinite_support h₁] apply intervalIntegrable_const_iff (c := 0) (by simp) |>.2 tauto section Mul theorem mul_continuousOn {f g : ℝ → A} (hf : IntervalIntegrable f μ a b) (hg : ContinuousOn g [[a, b]]) : IntervalIntegrable (fun x => f x * g x) μ a b := by rw [intervalIntegrable_iff] at hf ⊢ exact hf.mul_continuousOn_of_subset hg measurableSet_Ioc isCompact_uIcc Ioc_subset_Icc_self theorem continuousOn_mul {f g : ℝ → A} (hf : IntervalIntegrable f μ a b) (hg : ContinuousOn g [[a, b]]) : IntervalIntegrable (fun x => g x * f x) μ a b := by rw [intervalIntegrable_iff] at hf ⊢ exact hf.continuousOn_mul_of_subset hg isCompact_uIcc measurableSet_Ioc Ioc_subset_Icc_self @[simp] theorem const_mul {f : ℝ → A} (hf : IntervalIntegrable f μ a b) (c : A) : IntervalIntegrable (fun x => c * f x) μ a b := hf.continuousOn_mul continuousOn_const @[simp] theorem mul_const {f : ℝ → A} (hf : IntervalIntegrable f μ a b) (c : A) : IntervalIntegrable (fun x => f x * c) μ a b := hf.mul_continuousOn continuousOn_const end Mul section SMul variable {f : ℝ → 𝕜} {g : ℝ → E} [NormedRing 𝕜] [Module 𝕜 E] [NormSMulClass 𝕜 E] theorem smul_continuousOn (hf : IntervalIntegrable f μ a b) (hg : ContinuousOn g [[a, b]]) : IntervalIntegrable (fun x => f x • g x) μ a b := by rw [intervalIntegrable_iff] at hf ⊢ exact hf.smul_continuousOn_of_subset hg measurableSet_Ioc isCompact_uIcc Ioc_subset_Icc_self theorem continuousOn_smul (hg : IntervalIntegrable g μ a b) (hf : ContinuousOn f [[a, b]]) : IntervalIntegrable (fun x => f x • g x) μ a b := by rw [intervalIntegrable_iff] at hg ⊢ exact hg.continuousOn_smul_of_subset hf isCompact_uIcc measurableSet_Ioc Ioc_subset_Icc_self end SMul @[simp] theorem div_const {𝕜 : Type*} {f : ℝ → 𝕜} [NormedDivisionRing 𝕜] (h : IntervalIntegrable f μ a b) (c : 𝕜) : IntervalIntegrable (fun x => f x / c) μ a b := by simpa only [div_eq_mul_inv] using mul_const h c⁻¹ variable [PseudoMetrizableSpace ε] theorem comp_mul_left (hf : IntervalIntegrable f volume a b) {c : ℝ} (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) (h' : ‖f (c * min (a / c) (b / c))‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable (fun x => f (c * x)) volume (a / c) (b / c) := by rcases eq_or_ne c 0 with (hc | hc); · rw [hc]; simp rw [intervalIntegrable_iff' h] at hf rw [intervalIntegrable_iff' h'] at ⊢ have A : MeasurableEmbedding fun x => x * c⁻¹ := (Homeomorph.mulRight₀ _ (inv_ne_zero hc)).isClosedEmbedding.measurableEmbedding rw [← Real.smul_map_volume_mul_right (inv_ne_zero hc), IntegrableOn, Measure.restrict_smul, integrable_smul_measure (by simpa : ENNReal.ofReal |c⁻¹| ≠ 0) ENNReal.ofReal_ne_top, ← IntegrableOn, MeasurableEmbedding.integrableOn_map_iff A] convert hf using 1 · ext; simp only [comp_apply]; congr 1; field · rw [preimage_mul_const_uIcc (inv_ne_zero hc)]; field_simp -- Note that `h'` is **not** implied by `h` if `c` is negative. -- TODO: generalise this lemma to enorms! theorem comp_mul_left_iff {f : ℝ → E} {c : ℝ} (hc : c ≠ 0) (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) (h' : ‖f (c * min (a / c) (b / c))‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable (fun x ↦ f (c * x)) volume (a / c) (b / c) ↔ IntervalIntegrable f volume a b := by exact ⟨fun h ↦ by simpa [hc] using h.comp_mul_left (c := c⁻¹) h' (by simp), (comp_mul_left · h h')⟩ theorem comp_mul_right (hf : IntervalIntegrable f volume a b) {c : ℝ} (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) (h' : ‖f (c * min (a / c) (b / c))‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable (fun x => f (x * c)) volume (a / c) (b / c) := by simpa only [mul_comm] using comp_mul_left hf h h' theorem comp_add_right (hf : IntervalIntegrable f volume a b) (c : ℝ) (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable (fun x ↦ f (x + c)) volume (a - c) (b - c) := by have h' : ‖f (min (a - c) (b - c) + c)‖ₑ ≠ ⊤ := by rw [min_sub_sub_right, sub_add, sub_self, sub_zero] exact h wlog hab : a ≤ b generalizing a b · apply IntervalIntegrable.symm (this hf.symm ?_ ?_ (le_of_not_ge hab)) · rw [min_comm]; exact h · rw [min_comm]; exact h' rw [intervalIntegrable_iff' h] at hf rw [intervalIntegrable_iff' h'] at ⊢ have A : MeasurableEmbedding fun x => x + c := (Homeomorph.addRight c).isClosedEmbedding.measurableEmbedding rw [← map_add_right_eq_self volume c] at hf convert (MeasurableEmbedding.integrableOn_map_iff A).mp hf using 1 rw [preimage_add_const_uIcc] theorem comp_add_left (hf : IntervalIntegrable f volume a b) (c : ℝ) (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable (fun x ↦ f (c + x)) volume (a - c) (b - c) := by simpa [add_comm] using IntervalIntegrable.comp_add_right hf c h theorem comp_sub_right (hf : IntervalIntegrable f volume a b) (c : ℝ) (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable (fun x ↦ f (x - c)) volume (a + c) (b + c) := by simpa only [sub_neg_eq_add] using IntervalIntegrable.comp_add_right hf (-c) h -- TODO: generalise this lemma to enorms! theorem iff_comp_neg {f : ℝ → E} (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable f volume a b ↔ IntervalIntegrable (fun x ↦ f (-x)) volume (-a) (-b) := by rw [← comp_mul_left_iff (neg_ne_zero.2 one_ne_zero) h (by simp)]; simp [div_neg] -- TODO: generalise this lemma to enorms! theorem comp_sub_left {f : ℝ → E} (hf : IntervalIntegrable f volume a b) (c : ℝ) (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable (fun x ↦ f (c - x)) volume (c - a) (c - b) := by simpa only [neg_sub, ← sub_eq_add_neg] using (iff_comp_neg (by simp)).mp (hf.comp_add_left c h) -- TODO: generalise this lemma to enorms! theorem comp_sub_left_iff {f : ℝ → E} (c : ℝ) (h : ‖f (min a b)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable (fun x => f (c - x)) volume (c - a) (c - b) ↔ IntervalIntegrable f volume a b := ⟨fun h ↦ by simpa using h.comp_sub_left c, (.comp_sub_left · c h)⟩ end IntervalIntegrable /-! ## Continuous functions are interval integrable -/ section variable {μ : Measure ℝ} [IsLocallyFiniteMeasure μ] theorem ContinuousOn.intervalIntegrable {u : ℝ → E} {a b : ℝ} (hu : ContinuousOn u (uIcc a b)) : IntervalIntegrable u μ a b := (ContinuousOn.integrableOn_Icc hu).intervalIntegrable theorem ContinuousOn.intervalIntegrable_of_Icc {u : ℝ → E} {a b : ℝ} (h : a ≤ b) (hu : ContinuousOn u (Icc a b)) : IntervalIntegrable u μ a b := ContinuousOn.intervalIntegrable ((uIcc_of_le h).symm ▸ hu) /-- A continuous function on `ℝ` is `IntervalIntegrable` with respect to any locally finite measure `ν` on ℝ. -/ theorem Continuous.intervalIntegrable {u : ℝ → E} (hu : Continuous u) (a b : ℝ) : IntervalIntegrable u μ a b := hu.continuousOn.intervalIntegrable end /-! ## Monotone and antitone functions are integral integrable -/ section variable {μ : Measure ℝ} [IsLocallyFiniteMeasure μ] [ConditionallyCompleteLinearOrder E] [OrderTopology E] [SecondCountableTopology E] theorem MonotoneOn.intervalIntegrable {u : ℝ → E} {a b : ℝ} (hu : MonotoneOn u (uIcc a b)) : IntervalIntegrable u μ a b := by rw [intervalIntegrable_iff] exact (hu.integrableOn_isCompact isCompact_uIcc).mono_set Ioc_subset_Icc_self theorem AntitoneOn.intervalIntegrable {u : ℝ → E} {a b : ℝ} (hu : AntitoneOn u (uIcc a b)) : IntervalIntegrable u μ a b := hu.dual_right.intervalIntegrable theorem Monotone.intervalIntegrable {u : ℝ → E} {a b : ℝ} (hu : Monotone u) : IntervalIntegrable u μ a b := (hu.monotoneOn _).intervalIntegrable theorem Antitone.intervalIntegrable {u : ℝ → E} {a b : ℝ} (hu : Antitone u) : IntervalIntegrable u μ a b := (hu.antitoneOn _).intervalIntegrable end /-! ## Interval integrability of functions with even or odd parity -/ section variable {f : ℝ → E} /-- An even function is interval integrable (with respect to the volume measure) on every interval of the form `0..x` if it is interval integrable (with respect to the volume measure) on every interval of the form `0..x`, for positive `x`. See `intervalIntegrable_of_even` for a stronger result. -/ lemma intervalIntegrable_of_even₀ (h₁f : ∀ x, f x = f (-x)) (h₂f : ∀ x, 0 < x → IntervalIntegrable f volume 0 x) {t : ℝ} (ht : ‖f (min 0 t)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable f volume 0 t := by rcases lt_trichotomy t 0 with h | h | h · rw [IntervalIntegrable.iff_comp_neg ht] conv => arg 1; intro t; rw [← h₁f] simp [h₂f (-t) (by simp [h])] · rw [h] · exact h₂f t h /-- An even function is interval integrable (with respect to the volume measure) on every interval if it is interval integrable (with respect to the volume measure) on every interval of the form `0..x`, for positive `x`. -/ theorem intervalIntegrable_of_even (h₁f : ∀ x, f x = f (-x)) (h₂f : ∀ x, 0 < x → IntervalIntegrable f volume 0 x) {a b : ℝ} (ha : ‖f (min 0 a)‖ₑ ≠ ∞ := by finiteness) (hb : ‖f (min 0 b)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable f volume a b := -- Split integral and apply lemma (intervalIntegrable_of_even₀ h₁f h₂f ha).symm.trans (b := 0) (intervalIntegrable_of_even₀ h₁f h₂f hb) /-- An odd function is interval integrable (with respect to the volume measure) on every interval of the form `0..x` if it is interval integrable (with respect to the volume measure) on every interval of the form `0..x`, for positive `x`. See `intervalIntegrable_of_odd` for a stronger result. -/ lemma intervalIntegrable_of_odd₀ (h₁f : ∀ x, -f x = f (-x)) (h₂f : ∀ x, 0 < x → IntervalIntegrable f volume 0 x) {t : ℝ} (ht : ‖f (min 0 t)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable f volume 0 t := by rcases lt_trichotomy t 0 with h | h | h · rw [IntervalIntegrable.iff_comp_neg] conv => arg 1; intro t; rw [← h₁f] apply IntervalIntegrable.neg simp [h₂f (-t) (by simp [h])] · rw [h] · exact h₂f t h /-- An odd function is interval integrable (with respect to the volume measure) on every interval iff it is interval integrable (with respect to the volume measure) on every interval of the form `0..x`, for positive `x`. -/ theorem intervalIntegrable_of_odd (h₁f : ∀ x, -f x = f (-x)) (h₂f : ∀ x, 0 < x → IntervalIntegrable f volume 0 x) {a b : ℝ} (ha : ‖f (min 0 a)‖ₑ ≠ ∞ := by finiteness) (hb : ‖f (min 0 b)‖ₑ ≠ ∞ := by finiteness) : IntervalIntegrable f volume a b := -- Split integral and apply lemma (intervalIntegrable_of_odd₀ h₁f h₂f ha).symm.trans (intervalIntegrable_of_odd₀ h₁f h₂f hb) end /-! ## Limits of intervals -/ /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : ℝ → E` has a finite limit at `l' ⊓ ae μ`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply Tendsto.eventually_intervalIntegrable_ae` will generate goals `Filter ℝ` and `TendstoIxxClass Ioc ?m_1 l'`. -/ theorem Filter.Tendsto.eventually_intervalIntegrable_ae {f : ℝ → E} {μ : Measure ℝ} {l l' : Filter ℝ} (hfm : StronglyMeasurableAtFilter f l' μ) [TendstoIxxClass Ioc l l'] [IsMeasurablyGenerated l'] (hμ : μ.FiniteAtFilter l') {c : E} (hf : Tendsto f (l' ⊓ ae μ) (𝓝 c)) {u v : ι → ℝ} {lt : Filter ι} (hu : Tendsto u lt l) (hv : Tendsto v lt l) : ∀ᶠ t in lt, IntervalIntegrable f μ (u t) (v t) := have := (hf.integrableAtFilter_ae hfm hμ).eventually ((hu.Ioc hv).eventually this).and <| (hv.Ioc hu).eventually this /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : ℝ → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply Tendsto.eventually_intervalIntegrable` will generate goals `Filter ℝ` and `TendstoIxxClass Ioc ?m_1 l'`. -/ theorem Filter.Tendsto.eventually_intervalIntegrable {f : ℝ → E} {μ : Measure ℝ} {l l' : Filter ℝ} (hfm : StronglyMeasurableAtFilter f l' μ) [TendstoIxxClass Ioc l l'] [IsMeasurablyGenerated l'] (hμ : μ.FiniteAtFilter l') {c : E} (hf : Tendsto f l' (𝓝 c)) {u v : ι → ℝ} {lt : Filter ι} (hu : Tendsto u lt l) (hv : Tendsto v lt l) : ∀ᶠ t in lt, IntervalIntegrable f μ (u t) (v t) := (hf.mono_left inf_le_left).eventually_intervalIntegrable_ae hfm hμ hu hv /-! ### Interval integral: definition and basic properties In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ` and prove some basic properties. -/ variable [NormedSpace ℝ E] /-- The interval integral `∫ x in a..b, f x ∂μ` is defined as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals `∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/ def intervalIntegral (f : ℝ → E) (a b : ℝ) (μ : Measure ℝ) : E := (∫ x in Ioc a b, f x ∂μ) - ∫ x in Ioc b a, f x ∂μ @[inherit_doc intervalIntegral] notation3"∫ "(...)" in "a".."b", "r:60:(scoped f => f)" ∂"μ:70 => intervalIntegral r a b μ /-- The interval integral `∫ x in a..b, f x` is defined as `∫ x in Ioc a b, f x - ∫ x in Ioc b a, f x`. If `a ≤ b`, then it equals `∫ x in Ioc a b, f x`, otherwise it equals `-∫ x in Ioc b a, f x`. -/ notation3"∫ "(...)" in "a".."b", "r:60:(scoped f => intervalIntegral f a b volume) => r namespace intervalIntegral section Basic variable {a b : ℝ} {f g : ℝ → E} {μ : Measure ℝ} @[simp] theorem integral_zero : (∫ _ in a..b, (0 : E) ∂μ) = 0 := by simp [intervalIntegral] theorem integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ := by simp [intervalIntegral, h] @[simp] theorem integral_same : ∫ x in a..a, f x ∂μ = 0 := sub_self _ theorem integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ := by simp only [intervalIntegral, neg_sub] theorem integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ := by simp only [integral_symm b, integral_of_le h] theorem intervalIntegral_eq_integral_uIoc (f : ℝ → E) (a b : ℝ) (μ : Measure ℝ) : ∫ x in a..b, f x ∂μ = (if a ≤ b then 1 else -1 : ℝ) • ∫ x in Ι a b, f x ∂μ := by split_ifs with h · simp only [integral_of_le h, uIoc_of_le h, one_smul] · simp only [integral_of_ge (not_le.1 h).le, uIoc_of_ge (not_le.1 h).le, neg_one_smul] theorem norm_intervalIntegral_eq (f : ℝ → E) (a b : ℝ) (μ : Measure ℝ) : ‖∫ x in a..b, f x ∂μ‖ = ‖∫ x in Ι a b, f x ∂μ‖ := by simp_rw [intervalIntegral_eq_integral_uIoc, norm_smul] split_ifs <;> simp only [norm_neg, norm_one, one_mul] theorem abs_intervalIntegral_eq (f : ℝ → ℝ) (a b : ℝ) (μ : Measure ℝ) : |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| := norm_intervalIntegral_eq f a b μ theorem integral_cases (f : ℝ → E) (a b) : (∫ x in a..b, f x ∂μ) ∈ ({∫ x in Ι a b, f x ∂μ, -∫ x in Ι a b, f x ∂μ} : Set E) := by rw [intervalIntegral_eq_integral_uIoc]; split_ifs <;> simp nonrec theorem integral_undef (h : ¬IntervalIntegrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 := by rw [intervalIntegrable_iff] at h rw [intervalIntegral_eq_integral_uIoc, integral_undef h, smul_zero] theorem intervalIntegrable_of_integral_ne_zero {a b : ℝ} {f : ℝ → E} {μ : Measure ℝ} (h : (∫ x in a..b, f x ∂μ) ≠ 0) : IntervalIntegrable f μ a b := not_imp_comm.1 integral_undef h nonrec theorem integral_non_aestronglyMeasurable (hf : ¬AEStronglyMeasurable f (μ.restrict (Ι a b))) : ∫ x in a..b, f x ∂μ = 0 := by rw [intervalIntegral_eq_integral_uIoc, integral_non_aestronglyMeasurable hf, smul_zero] theorem integral_non_aestronglyMeasurable_of_le (h : a ≤ b) (hf : ¬AEStronglyMeasurable f (μ.restrict (Ioc a b))) : ∫ x in a..b, f x ∂μ = 0 := integral_non_aestronglyMeasurable <| by rwa [uIoc_of_le h] theorem norm_integral_min_max (f : ℝ → E) : ‖∫ x in min a b..max a b, f x ∂μ‖ = ‖∫ x in a..b, f x ∂μ‖ := by cases le_total a b <;> simp [*, integral_symm a b] theorem norm_integral_eq_norm_integral_uIoc (f : ℝ → E) : ‖∫ x in a..b, f x ∂μ‖ = ‖∫ x in Ι a b, f x ∂μ‖ := by rw [← norm_integral_min_max, integral_of_le min_le_max, uIoc] theorem abs_integral_eq_abs_integral_uIoc (f : ℝ → ℝ) : |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| := norm_integral_eq_norm_integral_uIoc f theorem norm_integral_le_integral_norm_uIoc : ‖∫ x in a..b, f x ∂μ‖ ≤ ∫ x in Ι a b, ‖f x‖ ∂μ := calc ‖∫ x in a..b, f x ∂μ‖ = ‖∫ x in Ι a b, f x ∂μ‖ := norm_integral_eq_norm_integral_uIoc f _ ≤ ∫ x in Ι a b, ‖f x‖ ∂μ := norm_integral_le_integral_norm f theorem norm_integral_le_abs_integral_norm : ‖∫ x in a..b, f x ∂μ‖ ≤ |∫ x in a..b, ‖f x‖ ∂μ| := by simp only [← Real.norm_eq_abs, norm_integral_eq_norm_integral_uIoc] exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _) theorem norm_integral_le_integral_norm (h : a ≤ b) : ‖∫ x in a..b, f x ∂μ‖ ≤ ∫ x in a..b, ‖f x‖ ∂μ := norm_integral_le_integral_norm_uIoc.trans_eq <| by rw [uIoc_of_le h, integral_of_le h] theorem norm_integral_le_abs_of_norm_le {g : ℝ → ℝ} (h : ∀ᵐ t ∂μ.restrict <| Ι a b, ‖f t‖ ≤ g t) (hbound : IntervalIntegrable g μ a b) : ‖∫ t in a..b, f t ∂μ‖ ≤ |∫ t in a..b, g t ∂μ| := by rw [norm_intervalIntegral_eq, abs_intervalIntegral_eq] exact (norm_integral_le_of_norm_le hbound.def' h).trans (le_abs_self _) theorem norm_integral_le_of_norm_le {g : ℝ → ℝ} (hab : a ≤ b) (h : ∀ᵐ t ∂μ, t ∈ Set.Ioc a b → ‖f t‖ ≤ g t) (hbound : IntervalIntegrable g μ a b) : ‖∫ t in a..b, f t ∂μ‖ ≤ ∫ t in a..b, g t ∂μ := by simp only [integral_of_le hab, ← ae_restrict_iff' measurableSet_Ioc] at * exact MeasureTheory.norm_integral_le_of_norm_le hbound.1 h theorem norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E} (h : ∀ᵐ x, x ∈ Ι a b → ‖f x‖ ≤ C) : ‖∫ x in a..b, f x‖ ≤ C * |b - a| := by rw [norm_integral_eq_norm_integral_uIoc] convert norm_setIntegral_le_of_norm_le_const_ae' _ h using 1 · rw [uIoc, Real.volume_real_Ioc_of_le inf_le_sup, max_sub_min_eq_abs] · simp [uIoc, Real.volume_Ioc] theorem norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E} (h : ∀ x ∈ Ι a b, ‖f x‖ ≤ C) : ‖∫ x in a..b, f x‖ ≤ C * |b - a| := norm_integral_le_of_norm_le_const_ae <| Eventually.of_forall h @[simp] nonrec theorem integral_add (hf : IntervalIntegrable f μ a b) (hg : IntervalIntegrable g μ a b) : ∫ x in a..b, f x + g x ∂μ = (∫ x in a..b, f x ∂μ) + ∫ x in a..b, g x ∂μ := by simp only [intervalIntegral_eq_integral_uIoc, integral_add hf.def' hg.def', smul_add] nonrec theorem integral_finset_sum {ι} {s : Finset ι} {f : ι → ℝ → E} (h : ∀ i ∈ s, IntervalIntegrable (f i) μ a b) : ∫ x in a..b, ∑ i ∈ s, f i x ∂μ = ∑ i ∈ s, ∫ x in a..b, f i x ∂μ := by simp only [intervalIntegral_eq_integral_uIoc, integral_finset_sum s fun i hi => (h i hi).def', Finset.smul_sum] @[simp] nonrec theorem integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ := by simp only [intervalIntegral, integral_neg]; abel @[simp] theorem integral_sub (hf : IntervalIntegrable f μ a b) (hg : IntervalIntegrable g μ a b) : ∫ x in a..b, f x - g x ∂μ = (∫ x in a..b, f x ∂μ) - ∫ x in a..b, g x ∂μ := by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg) /-- Compatibility with scalar multiplication. Note this assumes `𝕜` is a division ring in order to ensure that for `c ≠ 0`, `c • f` is integrable iff `f` is. For scalar multiplication by more general rings assuming integrability, see `IntervalIntegrable.integral_smul`. -/ @[simp] nonrec theorem integral_smul [NormedDivisionRing 𝕜] [Module 𝕜 E] [NormSMulClass 𝕜 E] [SMulCommClass ℝ 𝕜 E] (r : 𝕜) (f : ℝ → E) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [intervalIntegral, integral_smul, smul_sub] theorem _root_.IntervalIntegrable.integral_smul {R : Type*} [NormedRing R] [Module R E] [IsBoundedSMul R E] [SMulCommClass ℝ R E] {f : ℝ → E} (r : R) (hf : IntervalIntegrable f μ a b) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [intervalIntegral, smul_sub, hf.1.integral_smul, hf.2.integral_smul] @[simp] nonrec theorem integral_smul_const [CompleteSpace E] {𝕜 : Type*} [RCLike 𝕜] [NormedSpace 𝕜 E] (f : ℝ → 𝕜) (c : E) : ∫ x in a..b, f x • c ∂μ = (∫ x in a..b, f x ∂μ) • c := by simp only [intervalIntegral_eq_integral_uIoc, integral_smul_const, smul_assoc] @[simp] theorem integral_const_mul [NormedDivisionRing 𝕜] [NormedAlgebra ℝ 𝕜] (r : 𝕜) (f : ℝ → 𝕜) : ∫ x in a..b, r * f x ∂μ = r * ∫ x in a..b, f x ∂μ := integral_smul r f @[simp] theorem integral_mul_const {𝕜 : Type*} [RCLike 𝕜] (r : 𝕜) (f : ℝ → 𝕜) : ∫ x in a..b, f x * r ∂μ = (∫ x in a..b, f x ∂μ) * r := by simpa only [mul_comm r] using integral_const_mul r f @[simp] theorem integral_div {𝕜 : Type*} [RCLike 𝕜] (r : 𝕜) (f : ℝ → 𝕜) : ∫ x in a..b, f x / r ∂μ = (∫ x in a..b, f x ∂μ) / r := by simpa only [div_eq_mul_inv] using integral_mul_const r⁻¹ f theorem integral_const' [CompleteSpace E] (c : E) : ∫ _ in a..b, c ∂μ = (μ.real (Ioc a b) - μ.real (Ioc b a)) • c := by simp only [measureReal_def, intervalIntegral, setIntegral_const, sub_smul] @[simp] theorem integral_const [CompleteSpace E] (c : E) : ∫ _ in a..b, c = (b - a) • c := by simp only [integral_const', Real.volume_Ioc, ENNReal.toReal_ofReal', ← neg_sub b, max_zero_sub_eq_self, measureReal_def] nonrec theorem integral_smul_measure (c : ℝ≥0∞) : ∫ x in a..b, f x ∂c • μ = c.toReal • ∫ x in a..b, f x ∂μ := by simp only [intervalIntegral, Measure.restrict_smul, integral_smul_measure, smul_sub] end Basic -- TODO: add `Complex.ofReal` version of `_root_.integral_ofReal` nonrec theorem _root_.RCLike.intervalIntegral_ofReal {𝕜 : Type*} [RCLike 𝕜] {a b : ℝ} {μ : Measure ℝ} {f : ℝ → ℝ} : (∫ x in a..b, (f x : 𝕜) ∂μ) = ↑(∫ x in a..b, f x ∂μ) := by simp only [intervalIntegral, integral_ofReal, RCLike.ofReal_sub] nonrec theorem integral_ofReal {a b : ℝ} {μ : Measure ℝ} {f : ℝ → ℝ} : (∫ x in a..b, (f x : ℂ) ∂μ) = ↑(∫ x in a..b, f x ∂μ) := RCLike.intervalIntegral_ofReal section ContinuousLinearMap variable {a b : ℝ} {μ : Measure ℝ} {f : ℝ → E} variable [RCLike 𝕜] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [NormedSpace 𝕜 F] open ContinuousLinearMap theorem _root_.ContinuousLinearMap.intervalIntegral_apply {a b : ℝ} {φ : ℝ → F →L[𝕜] E} (hφ : IntervalIntegrable φ μ a b) (v : F) : (∫ x in a..b, φ x ∂μ) v = ∫ x in a..b, φ x v ∂μ := by simp_rw [intervalIntegral_eq_integral_uIoc, ← integral_apply hφ.def' v, coe_smul', Pi.smul_apply] variable [NormedSpace ℝ F] [CompleteSpace F] theorem _root_.ContinuousLinearMap.intervalIntegral_comp_comm [CompleteSpace E] (L : E →L[𝕜] F) (hf : IntervalIntegrable f μ a b) : (∫ x in a..b, L (f x) ∂μ) = L (∫ x in a..b, f x ∂μ) := by simp_rw [intervalIntegral, L.integral_comp_comm hf.1, L.integral_comp_comm hf.2, L.map_sub] end ContinuousLinearMap /-! ## Basic arithmetic Includes addition, scalar multiplication and affine transformations. -/ section Comp variable {a b c d : ℝ} (f : ℝ → E) @[simp] theorem integral_comp_mul_right (hc : c ≠ 0) : (∫ x in a..b, f (x * c)) = c⁻¹ • ∫ x in a * c..b * c, f x := by have A : MeasurableEmbedding fun x => x * c := (Homeomorph.mulRight₀ c hc).isClosedEmbedding.measurableEmbedding conv_rhs => rw [← Real.smul_map_volume_mul_right hc] simp_rw [integral_smul_measure, intervalIntegral, A.setIntegral_map, ENNReal.toReal_ofReal (abs_nonneg c)] rcases hc.lt_or_gt with h | h · simp [h, mul_div_cancel_right₀, hc, abs_of_neg, Measure.restrict_congr_set (α := ℝ) (μ := volume) Ico_ae_eq_Ioc] · simp [h, mul_div_cancel_right₀, hc, abs_of_pos] @[simp] theorem smul_integral_comp_mul_right (c) : (c • ∫ x in a..b, f (x * c)) = ∫ x in a * c..b * c, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_mul_right] @[simp] theorem integral_comp_mul_left (hc : c ≠ 0) : (∫ x in a..b, f (c * x)) = c⁻¹ • ∫ x in c * a..c * b, f x := by simpa only [mul_comm c] using integral_comp_mul_right f hc @[simp] theorem smul_integral_comp_mul_left (c) : (c • ∫ x in a..b, f (c * x)) = ∫ x in c * a..c * b, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_mul_left] @[simp] theorem integral_comp_div (hc : c ≠ 0) : (∫ x in a..b, f (x / c)) = c • ∫ x in a / c..b / c, f x := by simpa only [inv_inv] using integral_comp_mul_right f (inv_ne_zero hc) @[simp] theorem inv_smul_integral_comp_div (c) : (c⁻¹ • ∫ x in a..b, f (x / c)) = ∫ x in a / c..b / c, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_div] @[simp] theorem integral_comp_add_right (d) : (∫ x in a..b, f (x + d)) = ∫ x in a + d..b + d, f x := have A : MeasurableEmbedding fun x => x + d := (Homeomorph.addRight d).isClosedEmbedding.measurableEmbedding calc (∫ x in a..b, f (x + d)) = ∫ x in a + d..b + d, f x ∂Measure.map (fun x => x + d) volume := by simp [intervalIntegral, A.setIntegral_map] _ = ∫ x in a + d..b + d, f x := by rw [map_add_right_eq_self] @[simp] nonrec theorem integral_comp_add_left (d) : (∫ x in a..b, f (d + x)) = ∫ x in d + a..d + b, f x := by simpa only [add_comm d] using integral_comp_add_right f d @[simp] theorem integral_comp_mul_add (hc : c ≠ 0) (d) : (∫ x in a..b, f (c * x + d)) = c⁻¹ • ∫ x in c * a + d..c * b + d, f x := by rw [← integral_comp_add_right, ← integral_comp_mul_left _ hc] @[simp] theorem smul_integral_comp_mul_add (c d) : (c • ∫ x in a..b, f (c * x + d)) = ∫ x in c * a + d..c * b + d, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_mul_add] @[simp] theorem integral_comp_add_mul (hc : c ≠ 0) (d) : (∫ x in a..b, f (d + c * x)) = c⁻¹ • ∫ x in d + c * a..d + c * b, f x := by rw [← integral_comp_add_left, ← integral_comp_mul_left _ hc] @[simp] theorem smul_integral_comp_add_mul (c d) : (c • ∫ x in a..b, f (d + c * x)) = ∫ x in d + c * a..d + c * b, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_add_mul] @[simp] theorem integral_comp_div_add (hc : c ≠ 0) (d) : (∫ x in a..b, f (x / c + d)) = c • ∫ x in a / c + d..b / c + d, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_mul_add f (inv_ne_zero hc) d @[simp] theorem inv_smul_integral_comp_div_add (c d) : (c⁻¹ • ∫ x in a..b, f (x / c + d)) = ∫ x in a / c + d..b / c + d, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_div_add] @[simp] theorem integral_comp_add_div (hc : c ≠ 0) (d) : (∫ x in a..b, f (d + x / c)) = c • ∫ x in d + a / c..d + b / c, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_add_mul f (inv_ne_zero hc) d @[simp] theorem inv_smul_integral_comp_add_div (c d) : (c⁻¹ • ∫ x in a..b, f (d + x / c)) = ∫ x in d + a / c..d + b / c, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_add_div] @[simp] theorem integral_comp_mul_sub (hc : c ≠ 0) (d) : (∫ x in a..b, f (c * x - d)) = c⁻¹ • ∫ x in c * a - d..c * b - d, f x := by simpa only [sub_eq_add_neg] using integral_comp_mul_add f hc (-d) @[simp] theorem smul_integral_comp_mul_sub (c d) : (c • ∫ x in a..b, f (c * x - d)) = ∫ x in c * a - d..c * b - d, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_mul_sub] @[simp] theorem integral_comp_sub_mul (hc : c ≠ 0) (d) : (∫ x in a..b, f (d - c * x)) = c⁻¹ • ∫ x in d - c * b..d - c * a, f x := by simp only [sub_eq_add_neg, neg_mul_eq_neg_mul] rw [integral_comp_add_mul f (neg_ne_zero.mpr hc) d, integral_symm] simp only [inv_neg, smul_neg, neg_neg, neg_smul] @[simp] theorem smul_integral_comp_sub_mul (c d) : (c • ∫ x in a..b, f (d - c * x)) = ∫ x in d - c * b..d - c * a, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_sub_mul] @[simp] theorem integral_comp_div_sub (hc : c ≠ 0) (d) : (∫ x in a..b, f (x / c - d)) = c • ∫ x in a / c - d..b / c - d, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_mul_sub f (inv_ne_zero hc) d @[simp] theorem inv_smul_integral_comp_div_sub (c d) : (c⁻¹ • ∫ x in a..b, f (x / c - d)) = ∫ x in a / c - d..b / c - d, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_div_sub] @[simp] theorem integral_comp_sub_div (hc : c ≠ 0) (d) : (∫ x in a..b, f (d - x / c)) = c • ∫ x in d - b / c..d - a / c, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_sub_mul f (inv_ne_zero hc) d @[simp] theorem inv_smul_integral_comp_sub_div (c d) : (c⁻¹ • ∫ x in a..b, f (d - x / c)) = ∫ x in d - b / c..d - a / c, f x := by by_cases hc : c = 0 <;> simp [hc, integral_comp_sub_div] @[simp] theorem integral_comp_sub_right (d) : (∫ x in a..b, f (x - d)) = ∫ x in a - d..b - d, f x := by simpa only [sub_eq_add_neg] using integral_comp_add_right f (-d) @[simp] theorem integral_comp_sub_left (d) : (∫ x in a..b, f (d - x)) = ∫ x in d - b..d - a, f x := by simpa only [one_mul, one_smul, inv_one] using integral_comp_sub_mul f one_ne_zero d @[simp] theorem integral_comp_neg : (∫ x in a..b, f (-x)) = ∫ x in -b..-a, f x := by simpa only [zero_sub] using integral_comp_sub_left f 0 end Comp /-! ### Integral is an additive function of the interval In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` as well as a few other identities trivially equivalent to this one. We also prove that `∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`. -/ section OrderClosedTopology variable {a b c d : ℝ} {f g : ℝ → E} {μ : Measure ℝ} /-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/ theorem integral_congr {a b : ℝ} (h : EqOn f g [[a, b]]) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by rcases le_total a b with hab | hab <;> simpa [hab, integral_of_le, integral_of_ge] using setIntegral_congr_fun measurableSet_Ioc (h.mono Ioc_subset_Icc_self) theorem integral_add_adjacent_intervals_cancel (hab : IntervalIntegrable f μ a b) (hbc : IntervalIntegrable f μ b c) : (((∫ x in a..b, f x ∂μ) + ∫ x in b..c, f x ∂μ) + ∫ x in c..a, f x ∂μ) = 0 := by have hac := hab.trans hbc simp only [intervalIntegral, sub_add_sub_comm, sub_eq_zero] iterate 4 rw [← setIntegral_union] · suffices Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c by rw [this] rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle, min_left_comm, max_left_comm] all_goals simp [*, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] theorem integral_add_adjacent_intervals (hab : IntervalIntegrable f μ a b) (hbc : IntervalIntegrable f μ b c) : ((∫ x in a..b, f x ∂μ) + ∫ x in b..c, f x ∂μ) = ∫ x in a..c, f x ∂μ := by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc] theorem sum_integral_adjacent_intervals_Ico {a : ℕ → ℝ} {m n : ℕ} (hmn : m ≤ n) (hint : ∀ k ∈ Ico m n, IntervalIntegrable f μ (a k) (a <| k + 1)) : ∑ k ∈ Finset.Ico m n, ∫ x in a k..a <| k + 1, f x ∂μ = ∫ x in a m..a n, f x ∂μ := by revert hint refine Nat.le_induction ?_ ?_ n hmn · simp · intro p hmp IH h rw [Finset.sum_Ico_succ_top hmp, IH, integral_add_adjacent_intervals] · refine IntervalIntegrable.trans_iterate_Ico hmp fun k hk => h k ?_ exact (Ico_subset_Ico le_rfl (Nat.le_succ _)) hk · apply h simp [hmp] · intro k hk exact h _ (Ico_subset_Ico_right p.le_succ hk) theorem sum_integral_adjacent_intervals {a : ℕ → ℝ} {n : ℕ} (hint : ∀ k < n, IntervalIntegrable f μ (a k) (a <| k + 1)) : ∑ k ∈ Finset.range n, ∫ x in a k..a <| k + 1, f x ∂μ = ∫ x in (a 0)..(a n), f x ∂μ := by rw [← Nat.Ico_zero_eq_range] exact sum_integral_adjacent_intervals_Ico (zero_le n) fun k hk => hint k hk.2 theorem integral_interval_sub_left (hab : IntervalIntegrable f μ a b) (hac : IntervalIntegrable f μ a c) : ((∫ x in a..b, f x ∂μ) - ∫ x in a..c, f x ∂μ) = ∫ x in c..b, f x ∂μ := sub_eq_of_eq_add' <| Eq.symm <| integral_add_adjacent_intervals hac (hac.symm.trans hab) theorem integral_interval_add_interval_comm (hab : IntervalIntegrable f μ a b) (hcd : IntervalIntegrable f μ c d) (hac : IntervalIntegrable f μ a c) : ((∫ x in a..b, f x ∂μ) + ∫ x in c..d, f x ∂μ) = (∫ x in a..d, f x ∂μ) + ∫ x in c..b, f x ∂μ := by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm, integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm] theorem integral_interval_sub_interval_comm (hab : IntervalIntegrable f μ a b) (hcd : IntervalIntegrable f μ c d) (hac : IntervalIntegrable f μ a c) : ((∫ x in a..b, f x ∂μ) - ∫ x in c..d, f x ∂μ) = (∫ x in a..c, f x ∂μ) - ∫ x in b..d, f x ∂μ := by simp only [sub_eq_add_neg, ← integral_symm, integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)] theorem integral_interval_sub_interval_comm' (hab : IntervalIntegrable f μ a b) (hcd : IntervalIntegrable f μ c d) (hac : IntervalIntegrable f μ a c) : ((∫ x in a..b, f x ∂μ) - ∫ x in c..d, f x ∂μ) = (∫ x in d..b, f x ∂μ) - ∫ x in c..a, f x ∂μ := by rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c, sub_neg_eq_add, sub_eq_neg_add] theorem integral_Iic_sub_Iic (ha : IntegrableOn f (Iic a) μ) (hb : IntegrableOn f (Iic b) μ) : ((∫ x in Iic b, f x ∂μ) - ∫ x in Iic a, f x ∂μ) = ∫ x in a..b, f x ∂μ := by wlog hab : a ≤ b generalizing a b · rw [integral_symm, ← this hb ha (le_of_not_ge hab), neg_sub] rw [sub_eq_iff_eq_add', integral_of_le hab, ← setIntegral_union (Iic_disjoint_Ioc le_rfl), Iic_union_Ioc_eq_Iic hab] exacts [measurableSet_Ioc, ha, hb.mono_set fun _ => And.right] theorem integral_Iic_add_Ioi (h_left : IntegrableOn f (Iic b) μ) (h_right : IntegrableOn f (Ioi b) μ) : (∫ x in Iic b, f x ∂μ) + (∫ x in Ioi b, f x ∂μ) = ∫ (x : ℝ), f x ∂μ := by convert (setIntegral_union (Iic_disjoint_Ioi <| Eq.le rfl) measurableSet_Ioi h_left h_right).symm rw [Iic_union_Ioi, Measure.restrict_univ] theorem integral_Iio_add_Ici (h_left : IntegrableOn f (Iio b) μ) (h_right : IntegrableOn f (Ici b) μ) : (∫ x in Iio b, f x ∂μ) + (∫ x in Ici b, f x ∂μ) = ∫ (x : ℝ), f x ∂μ := by convert (setIntegral_union (Iio_disjoint_Ici <| Eq.le rfl) measurableSet_Ici h_left h_right).symm rw [Iio_union_Ici, Measure.restrict_univ] /-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/ theorem integral_const_of_cdf [CompleteSpace E] [IsFiniteMeasure μ] (c : E) : ∫ _ in a..b, c ∂μ = (μ.real (Iic b) - μ.real (Iic a)) • c := by simp only [sub_smul, ← setIntegral_const] refine (integral_Iic_sub_Iic ?_ ?_).symm <;> simp theorem integral_eq_integral_of_support_subset {a b} (h : support f ⊆ Ioc a b) : ∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ := by rcases le_total a b with hab | hab · rw [integral_of_le hab, ← integral_indicator measurableSet_Ioc, indicator_eq_self.2 h] · rw [Ioc_eq_empty hab.not_gt, subset_empty_iff, support_eq_empty_iff] at h simp [h] theorem integral_congr_ae' (h : ∀ᵐ x ∂μ, x ∈ Ioc a b → f x = g x) (h' : ∀ᵐ x ∂μ, x ∈ Ioc b a → f x = g x) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by simp only [intervalIntegral, setIntegral_congr_ae measurableSet_Ioc h, setIntegral_congr_ae measurableSet_Ioc h'] theorem integral_congr_ae (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = g x) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := integral_congr_ae' (ae_uIoc_iff.mp h).1 (ae_uIoc_iff.mp h).2 /-- Integrals are equal for functions that agree almost everywhere for the restricted measure. -/ theorem integral_congr_ae_restrict {a b : ℝ} {f g : ℝ → E} {μ : Measure ℝ} (h : f =ᵐ[μ.restrict (Ι a b)] g) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := integral_congr_ae (ae_imp_of_ae_restrict h) /-- Integrals are invariant when functions change along discrete sets. -/ theorem integral_congr_codiscreteWithin {a b : ℝ} {f₁ f₂ : ℝ → ℝ} (hf : f₁ =ᶠ[codiscreteWithin (Ι a b)] f₂) : ∫ (x : ℝ) in a..b, f₁ x = ∫ (x : ℝ) in a..b, f₂ x := integral_congr_ae_restrict (ae_restrict_le_codiscreteWithin measurableSet_uIoc hf) theorem integral_zero_ae (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = 0) : ∫ x in a..b, f x ∂μ = 0 := calc ∫ x in a..b, f x ∂μ = ∫ _ in a..b, 0 ∂μ := integral_congr_ae h _ = 0 := integral_zero nonrec theorem integral_indicator {a₁ a₂ a₃ : ℝ} (h : a₂ ∈ Icc a₁ a₃) : ∫ x in a₁..a₃, indicator {x | x ≤ a₂} f x ∂μ = ∫ x in a₁..a₂, f x ∂μ := by have : {x | x ≤ a₂} ∩ Ioc a₁ a₃ = Ioc a₁ a₂ := Iic_inter_Ioc_of_le h.2 rw [integral_of_le h.1, integral_of_le (h.1.trans h.2), integral_indicator, Measure.restrict_restrict, this] · exact measurableSet_Iic all_goals apply measurableSet_Iic end OrderClosedTopology section variable {f g : ℝ → ℝ} {a b : ℝ} {μ : Measure ℝ} theorem integral_eq_zero_iff_of_le_of_nonneg_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Ioc a b)] f) (hfi : IntervalIntegrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b)] 0 := by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1] theorem integral_eq_zero_iff_of_nonneg_ae (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : IntervalIntegrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] 0 := by rcases le_total a b with hab | hab <;> simp only [Ioc_eq_empty hab.not_gt, empty_union, union_empty] at hf ⊢ · exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi · rw [integral_symm, neg_eq_zero, integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm] /-- If `f` is nonnegative and integrable on the unordered interval `Set.uIoc a b`, then its integral over `a..b` is positive if and only if `a < b` and the measure of `Function.support f ∩ Set.Ioc a b` is positive. -/ theorem integral_pos_iff_support_of_nonneg_ae' (hf : 0 ≤ᵐ[μ.restrict (Ι a b)] f) (hfi : IntervalIntegrable f μ a b) : (0 < ∫ x in a..b, f x ∂μ) ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := by rcases lt_or_ge a b with hab | hba · rw [uIoc_of_le hab.le] at hf simp only [hab, true_and, integral_of_le hab.le, setIntegral_pos_iff_support_of_nonneg_ae hf hfi.1] · suffices (∫ x in a..b, f x ∂μ) ≤ 0 by simp only [this.not_gt, hba.not_gt, false_and] rw [integral_of_ge hba, neg_nonpos] rw [uIoc_comm, uIoc_of_le hba] at hf exact integral_nonneg_of_ae hf /-- If `f` is nonnegative a.e.-everywhere and it is integrable on the unordered interval `Set.uIoc a b`, then its integral over `a..b` is positive if and only if `a < b` and the measure of `Function.support f ∩ Set.Ioc a b` is positive. -/ theorem integral_pos_iff_support_of_nonneg_ae (hf : 0 ≤ᵐ[μ] f) (hfi : IntervalIntegrable f μ a b) : (0 < ∫ x in a..b, f x ∂μ) ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := integral_pos_iff_support_of_nonneg_ae' (ae_mono Measure.restrict_le_self hf) hfi /-- If `f : ℝ → ℝ` is integrable on `(a, b]` for real numbers `a < b`, and positive on the interior of the interval, then its integral over `a..b` is strictly positive. -/ theorem intervalIntegral_pos_of_pos_on {f : ℝ → ℝ} {a b : ℝ} (hfi : IntervalIntegrable f volume a b) (hpos : ∀ x : ℝ, x ∈ Ioo a b → 0 < f x) (hab : a < b) : 0 < ∫ x : ℝ in a..b, f x := by have hsupp : Ioo a b ⊆ support f ∩ Ioc a b := fun x hx => ⟨mem_support.mpr (hpos x hx).ne', Ioo_subset_Ioc_self hx⟩ have h₀ : 0 ≤ᵐ[volume.restrict (uIoc a b)] f := by rw [EventuallyLE, uIoc_of_le hab.le] refine ae_restrict_of_ae_eq_of_ae_restrict Ioo_ae_eq_Ioc ?_ rw [ae_restrict_iff' measurableSet_Ioo] filter_upwards with x hx using (hpos x hx).le rw [integral_pos_iff_support_of_nonneg_ae' h₀ hfi] exact ⟨hab, ((Measure.measure_Ioo_pos _).mpr hab).trans_le (measure_mono hsupp)⟩ /-- If `f : ℝ → ℝ` is strictly positive everywhere, and integrable on `(a, b]` for real numbers `a < b`, then its integral over `a..b` is strictly positive. (See `intervalIntegral_pos_of_pos_on` for a version only assuming positivity of `f` on `(a, b)` rather than everywhere.) -/ theorem intervalIntegral_pos_of_pos {f : ℝ → ℝ} {a b : ℝ} (hfi : IntervalIntegrable f MeasureSpace.volume a b) (hpos : ∀ x, 0 < f x) (hab : a < b) : 0 < ∫ x in a..b, f x := intervalIntegral_pos_of_pos_on hfi (fun x _ => hpos x) hab /-- If `f` and `g` are two functions that are interval integrable on `a..b`, `a ≤ b`, `f x ≤ g x` for a.e. `x ∈ Set.Ioc a b`, and `f x < g x` on a subset of `Set.Ioc a b` of nonzero measure, then `∫ x in a..b, f x ∂μ < ∫ x in a..b, g x ∂μ`. -/ theorem integral_lt_integral_of_ae_le_of_measure_setOf_lt_ne_zero (hab : a ≤ b) (hfi : IntervalIntegrable f μ a b) (hgi : IntervalIntegrable g μ a b) (hle : f ≤ᵐ[μ.restrict (Ioc a b)] g) (hlt : μ.restrict (Ioc a b) {x | f x < g x} ≠ 0) : (∫ x in a..b, f x ∂μ) < ∫ x in a..b, g x ∂μ := by rw [← sub_pos, ← integral_sub hgi hfi, integral_of_le hab, MeasureTheory.integral_pos_iff_support_of_nonneg_ae] · refine pos_iff_ne_zero.2 (mt (measure_mono_null ?_) hlt) exact fun x hx => (sub_pos.2 hx.out).ne' exacts [hle.mono fun x => sub_nonneg.2, hgi.1.sub hfi.1] /-- If `f` and `g` are continuous on `[a, b]`, `a < b`, `f x ≤ g x` on this interval, and `f c < g c` at some point `c ∈ [a, b]`, then `∫ x in a..b, f x < ∫ x in a..b, g x`. -/ theorem integral_lt_integral_of_continuousOn_of_le_of_exists_lt {f g : ℝ → ℝ} {a b : ℝ} (hab : a < b) (hfc : ContinuousOn f (Icc a b)) (hgc : ContinuousOn g (Icc a b)) (hle : ∀ x ∈ Ioc a b, f x ≤ g x) (hlt : ∃ c ∈ Icc a b, f c < g c) : (∫ x in a..b, f x) < ∫ x in a..b, g x := by apply integral_lt_integral_of_ae_le_of_measure_setOf_lt_ne_zero hab.le (hfc.intervalIntegrable_of_Icc hab.le) (hgc.intervalIntegrable_of_Icc hab.le) · simpa only [measurableSet_Ioc, ae_restrict_eq] using (ae_restrict_mem measurableSet_Ioc).mono hle contrapose! hlt have h_eq : f =ᵐ[volume.restrict (Ioc a b)] g := by simp only [← not_le, ← ae_iff] at hlt exact EventuallyLE.antisymm ((ae_restrict_iff' measurableSet_Ioc).2 <| Eventually.of_forall hle) hlt rw [Measure.restrict_congr_set Ioc_ae_eq_Icc] at h_eq exact fun c hc ↦ (Measure.eqOn_Icc_of_ae_eq volume hab.ne h_eq hfc hgc hc).ge theorem integral_nonneg_of_ae_restrict (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Icc a b)] f) : 0 ≤ ∫ u in a..b, f u ∂μ := by let H := ae_restrict_of_ae_restrict_of_subset Ioc_subset_Icc_self hf simpa only [integral_of_le hab] using setIntegral_nonneg_of_ae_restrict H theorem integral_nonneg_of_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ u in a..b, f u ∂μ := integral_nonneg_of_ae_restrict hab <| ae_restrict_of_ae hf theorem integral_nonneg_of_forall (hab : a ≤ b) (hf : ∀ u, 0 ≤ f u) : 0 ≤ ∫ u in a..b, f u ∂μ := integral_nonneg_of_ae hab <| Eventually.of_forall hf theorem integral_nonneg (hab : a ≤ b) (hf : ∀ u, u ∈ Icc a b → 0 ≤ f u) : 0 ≤ ∫ u in a..b, f u ∂μ := integral_nonneg_of_ae_restrict hab <| (ae_restrict_iff' measurableSet_Icc).mpr <| ae_of_all μ hf theorem abs_integral_le_integral_abs (hab : a ≤ b) : |∫ x in a..b, f x ∂μ| ≤ ∫ x in a..b, |f x| ∂μ := by simpa only [← Real.norm_eq_abs] using norm_integral_le_integral_norm hab lemma integral_pos (hab : a < b) (hfc : ContinuousOn f (Icc a b)) (hle : ∀ x ∈ Ioc a b, 0 ≤ f x) (hlt : ∃ c ∈ Icc a b, 0 < f c) : 0 < ∫ x in a..b, f x := (integral_lt_integral_of_continuousOn_of_le_of_exists_lt hab continuousOn_const hfc hle hlt).trans_eq' (by simp) section Mono theorem integral_mono_interval {c d} (hca : c ≤ a) (hab : a ≤ b) (hbd : b ≤ d) (hf : 0 ≤ᵐ[μ.restrict (Ioc c d)] f) (hfi : IntervalIntegrable f μ c d) : (∫ x in a..b, f x ∂μ) ≤ ∫ x in c..d, f x ∂μ := by rw [integral_of_le hab, integral_of_le (hca.trans (hab.trans hbd))] exact setIntegral_mono_set hfi.1 hf (Ioc_subset_Ioc hca hbd).eventuallyLE theorem abs_integral_mono_interval {c d} (h : Ι a b ⊆ Ι c d) (hf : 0 ≤ᵐ[μ.restrict (Ι c d)] f) (hfi : IntervalIntegrable f μ c d) : |∫ x in a..b, f x ∂μ| ≤ |∫ x in c..d, f x ∂μ| := have hf' : 0 ≤ᵐ[μ.restrict (Ι a b)] f := ae_mono (Measure.restrict_mono h le_rfl) hf calc |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| := abs_integral_eq_abs_integral_uIoc f _ = ∫ x in Ι a b, f x ∂μ := abs_of_nonneg (MeasureTheory.integral_nonneg_of_ae hf') _ ≤ ∫ x in Ι c d, f x ∂μ := setIntegral_mono_set hfi.def' hf h.eventuallyLE _ ≤ |∫ x in Ι c d, f x ∂μ| := le_abs_self _ _ = |∫ x in c..d, f x ∂μ| := (abs_integral_eq_abs_integral_uIoc f).symm variable (hab : a ≤ b) (hf : IntervalIntegrable f μ a b) (hg : IntervalIntegrable g μ a b) include hab hf hg theorem integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict (Icc a b)] g) : (∫ u in a..b, f u ∂μ) ≤ ∫ u in a..b, g u ∂μ := by let H := h.filter_mono <| ae_mono <| Measure.restrict_mono Ioc_subset_Icc_self <| le_refl μ simpa only [integral_of_le hab] using setIntegral_mono_ae_restrict hf.1 hg.1 H theorem integral_mono_ae (h : f ≤ᵐ[μ] g) : (∫ u in a..b, f u ∂μ) ≤ ∫ u in a..b, g u ∂μ := by simpa only [integral_of_le hab] using setIntegral_mono_ae hf.1 hg.1 h theorem integral_mono_on (h : ∀ x ∈ Icc a b, f x ≤ g x) : (∫ u in a..b, f u ∂μ) ≤ ∫ u in a..b, g u ∂μ := by let H x hx := h x <| Ioc_subset_Icc_self hx simpa only [integral_of_le hab] using setIntegral_mono_on hf.1 hg.1 measurableSet_Ioc H theorem integral_mono_on_of_le_Ioo [NoAtoms μ] (h : ∀ x ∈ Ioo a b, f x ≤ g x) : (∫ u in a..b, f u ∂μ) ≤ ∫ u in a..b, g u ∂μ := by simp only [integral_of_le hab, integral_Ioc_eq_integral_Ioo] apply setIntegral_mono_on · apply hf.1.mono Ioo_subset_Ioc_self le_rfl · apply hg.1.mono Ioo_subset_Ioc_self le_rfl · exact measurableSet_Ioo · exact h theorem integral_mono (h : f ≤ g) : (∫ u in a..b, f u ∂μ) ≤ ∫ u in a..b, g u ∂μ := integral_mono_ae hab hf hg <| ae_of_all _ h end Mono end section HasSum variable {μ : Measure ℝ} {f : ℝ → E} theorem _root_.MeasureTheory.Integrable.hasSum_intervalIntegral (hfi : Integrable f μ) (y : ℝ) : HasSum (fun n : ℤ => ∫ x in y + n..y + n + 1, f x ∂μ) (∫ x, f x ∂μ) := by simp_rw [integral_of_le (le_add_of_nonneg_right zero_le_one)] rw [← setIntegral_univ, ← iUnion_Ioc_add_intCast y] exact hasSum_integral_iUnion (fun i => measurableSet_Ioc) (pairwise_disjoint_Ioc_add_intCast y) hfi.integrableOn theorem _root_.MeasureTheory.Integrable.hasSum_intervalIntegral_comp_add_int (hfi : Integrable f) : HasSum (fun n : ℤ => ∫ x in (0 : ℝ)..(1 : ℝ), f (x + n)) (∫ x, f x) := by simpa only [integral_comp_add_right, zero_add, add_comm (1 : ℝ)] using hfi.hasSum_intervalIntegral 0 end HasSum end intervalIntegral
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/IntervalIntegral/Slope.lean
import Mathlib.LinearAlgebra.AffineSpace.Slope import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic /-! # Some properties of the interval integral of `fun x ↦ slope f x (x + c)`, given a constant `c : ℝ` This file proves that: * `IntervalIntegrable.intervalIntegrable_slope`: If `f` is interval integrable on `a..(b + c)` where `a ≤ b` and `0 ≤ c`, then `fun x ↦ slope f x (x + c)` is interval integrable on `a..b`. * `MonotoneOn.intervalIntegrable_slope`: If `f` is monotone on `a..(b + c)` where `a ≤ b` and `0 ≤ c`, then `fun x ↦ slope f x (x + c)` is interval integrable on `a..b`. * `MonotoneOn.intervalIntegral_slope_le`: If `f` is monotone on `a..(b + c)` where `a ≤ b` and `0 ≤ c`, then the interval integral of `fun x ↦ slope f x (x + c)` on `a..b` is at most `f (b + c) - f a`. ## Tags interval integrable, interval integral, monotone, slope -/ open MeasureTheory Set /-- If `f` is interval integrable on `a..(b + c)` where `a ≤ b` and `0 ≤ c`, then `fun x ↦ slope f x (x + c)` is interval integrable on `a..b`. -/ theorem IntervalIntegrable.intervalIntegrable_slope {f : ℝ → ℝ} {a b c : ℝ} (hf : IntervalIntegrable f volume a (b + c)) (hab : a ≤ b) (hc : 0 ≤ c) : IntervalIntegrable (fun x ↦ slope f x (x + c)) volume a b := by simp only [slope, add_sub_cancel_left, vsub_eq_sub, smul_eq_mul] exact hf.comp_add_right c |>.mono_set (by grind [uIcc]) |>.sub (hf.mono_set (by grind [uIcc])) |>.const_mul (c := c⁻¹) /-- If `f` is monotone on `a..(b + c)` where `a ≤ b` and `0 ≤ c`, then `fun x ↦ slope f x (x + c)` is interval integrable on `a..b`. -/ theorem MonotoneOn.intervalIntegrable_slope {f : ℝ → ℝ} {a b c : ℝ} (hf : MonotoneOn f (Icc a (b + c))) (hab : a ≤ b) (hc : 0 ≤ c) : IntervalIntegrable (fun x ↦ slope f x (x + c)) volume a b := uIcc_of_le (show a ≤ b + c by linarith) ▸ hf |>.intervalIntegrable.intervalIntegrable_slope hab hc /-- If `f` is monotone on `a..(b + c)` where `a ≤ b` and `0 ≤ c`, then the interval integral of `fun x ↦ slope f x (x + c)` on `a..b` is at most `f (b + c) - f a`. -/ theorem MonotoneOn.intervalIntegral_slope_le {f : ℝ → ℝ} {a b c : ℝ} (hf : MonotoneOn f (Icc a (b + c))) (hab : a ≤ b) (hc : 0 ≤ c) : ∫ x in a..b, slope f x (x + c) ≤ f (b + c) - f a := by rcases eq_or_lt_of_le hc with hc | hc · simp only [← hc, add_zero, slope_same, intervalIntegral.integral_zero, sub_nonneg] apply hf <;> grind rw [← uIcc_of_le (by linarith)] at hf have hf' := hf.intervalIntegrable (μ := volume) simp only [slope, add_sub_cancel_left, vsub_eq_sub, smul_eq_mul, intervalIntegral.integral_const_mul] rw [intervalIntegral.integral_sub (hf'.comp_add_right c |>.mono_set (by grind [uIcc])) (hf'.mono_set (by grind [uIcc])), intervalIntegral.integral_comp_add_right, intervalIntegral.integral_interval_sub_interval_comm' (hf'.mono_set (by grind [uIcc])) (hf'.mono_set (by grind [uIcc])) (hf'.mono_set (by grind [uIcc]))] have fU : ∫ (x : ℝ) in b..b + c, f x ≤ c * f (b + c) := by grw [intervalIntegral.integral_mono_on (g := fun _ ↦ f (b + c)) (by linarith) (hf'.mono_set (by grind [uIcc])) (by simp) (by intros; apply hf <;> grind [uIcc])] simp have fL : c * f a ≤ ∫ (x : ℝ) in a..a + c, f x := by grw [← intervalIntegral.integral_mono_on (f := fun _ ↦ f a) (by linarith) (by simp) (hf'.mono_set (by grind [uIcc])) (by intros; apply hf <;> grind [uIcc])] simp grw [fU, ← fL] field_simp; rfl
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/IntervalIntegral/FundThmCalculus.lean
import Mathlib.Analysis.Calculus.Deriv.Add import Mathlib.Analysis.Calculus.Deriv.Comp import Mathlib.Analysis.Calculus.FDeriv.Measurable import Mathlib.Analysis.Normed.Module.Dual import Mathlib.MeasureTheory.Integral.Bochner.FundThmCalculus import Mathlib.MeasureTheory.Integral.Bochner.VitaliCaratheodory import Mathlib.MeasureTheory.Integral.DominatedConvergence import Mathlib.Analysis.Calculus.TangentCone.Prod /-! # Fundamental Theorem of Calculus We prove various versions of the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for interval integrals in `ℝ`. Recall that its first version states that the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(δu, δv) ↦ δv • f b - δu • f a` at `(a, b)` provided that `f` is continuous at `a` and `b`, and its second version states that, if `f` has an integrable derivative on `[a, b]`, then `∫ x in a..b, f' x = f b - f a`. ## Main statements ### FTC-1 for Lebesgue measure We prove several versions of FTC-1, all in the `intervalIntegral` namespace. Many of them follow the naming scheme `integral_has(Strict?)(F?)Deriv(Within?)At(_of_tendsto_ae?)(_right|_left?)`. They formulate FTC in terms of `Has(Strict?)(F?)Deriv(Within?)At`. Let us explain the meaning of each part of the name: * `Strict` means that the theorem is about strict differentiability, see `HasStrictDerivAt` and `HasStrictFDerivAt`; * `F` means that the theorem is about differentiability in both endpoints; incompatible with `_right|_left`; * `Within` means that the theorem is about one-sided derivatives, see below for details; * `_of_tendsto_ae` means that instead of continuity the theorem assumes that `f` has a finite limit almost surely as `x` tends to `a` and/or `b`; * `_right` or `_left` mean that the theorem is about differentiability in the right (resp., left) endpoint. We also reformulate these theorems in terms of `(f?)deriv(Within?)`. These theorems are named `(f?)deriv(Within?)_integral(_of_tendsto_ae?)(_right|_left?)` with the same meaning of parts of the name. ### One-sided derivatives Theorem `intervalIntegral.integral_hasFDerivWithinAt_of_tendsto_ae` states that `(u, v) ↦ ∫ x in u..v, f x` has a derivative `(δu, δv) ↦ δv • cb - δu • ca` within the set `s × t` at `(a, b)` provided that `f` tends to `ca` (resp., `cb`) almost surely at `la` (resp., `lb`), where possible values of `s`, `t`, and corresponding filters `la`, `lb` are given in the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` | | `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | We use a typeclass `intervalIntegral.FTCFilter` to make Lean automatically find `la`/`lb` based on `s`/`t`. This way we can formulate one theorem instead of `16` (or `8` if we leave only non-trivial ones not covered by `integral_hasDerivWithinAt_of_tendsto_ae_(left|right)` and `integral_hasFDerivAt_of_tendsto_ae`). Similarly, `integral_hasDerivWithinAt_of_tendsto_ae_right` works for both one-sided derivatives using the same typeclass to find an appropriate filter. ### FTC for a locally finite measure Before proving FTC for the Lebesgue measure, we prove a few statements that can be seen as FTC for any measure. The most general of them, `measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae`, states the following. Let `(la, la')` be an `intervalIntegral.FTCFilter` pair of filters around `a` (i.e., `intervalIntegral.FTCFilter a la la'`) and let `(lb, lb')` be an `intervalIntegral.FTCFilter` pair of filters around `b`. If `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then $$ \int_{va}^{vb} f ∂μ - \int_{ua}^{ub} f ∂μ = \int_{ub}^{vb} cb ∂μ - \int_{ua}^{va} ca ∂μ + o(‖∫_{ua}^{va} 1 ∂μ‖ + ‖∫_{ub}^{vb} (1:ℝ) ∂μ‖) $$ as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. ### FTC-2 and corollaries We use FTC-1 to prove several versions of FTC-2 for the Lebesgue measure, using a similar naming scheme as for the versions of FTC-1. They include: * `intervalIntegral.integral_eq_sub_of_hasDeriv_right_of_le` - most general version, for functions with a right derivative * `intervalIntegral.integral_eq_sub_of_hasDerivAt` - version for functions with a derivative on an open set * `intervalIntegral.integral_deriv_eq_sub'` - version that is easiest to use when computing the integral of a specific function Many applications of these theorems can be found in the file `Mathlib/Analysis/SpecialFunctions/Integrals.lean`. Note that the assumptions of FTC-2 are formulated in the form that `f'` is integrable. To use it in a context with the stronger assumption that `f'` is continuous, one can use `ContinuousOn.intervalIntegrable` or `ContinuousOn.integrableOn_Icc` or `ContinuousOn.integrableOn_uIcc`. Versions of FTC-2 under the simpler assumption that the function is `C^1` are given in the file `Mathlib.MeasureTheory.Integral.IntervalIntegral.ContDiff`. Applications to integration by parts are in the file `Mathlib.MeasureTheory.Integral.IntegrationByParts`. ### `intervalIntegral.FTCFilter` class As explained above, many theorems in this file rely on the typeclass `intervalIntegral.FTCFilter (a : ℝ) (l l' : Filter ℝ)` to avoid code duplication. This typeclass combines four assumptions: - `pure a ≤ l`; - `l' ≤ 𝓝 a`; - `l'` has a basis of measurable sets; - if `u n` and `v n` tend to `l`, then for any `s ∈ l'`, `Ioc (u n) (v n)` is eventually included in `s`. This typeclass has the following “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[≥] a, 𝓝[>] a)`, `(a, 𝓝[≤] a, 𝓝[≤] a)`, `(a, 𝓝 a, 𝓝 a)`. Furthermore, we have the following instances that are equal to the previously mentioned instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. While the difference between `Ici a` and `Ioi a` doesn't matter for theorems about Lebesgue measure, it becomes important in the versions of FTC about any locally finite measure if this measure has an atom at one of the endpoints. ### Combining one-sided and two-sided derivatives There are some `intervalIntegral.FTCFilter` instances where the fact that it is one-sided or two-sided depends on the point, namely `(x, 𝓝[Set.Icc a b] x, 𝓝[Set.Icc a b] x)` (resp. `(x, 𝓝[Set.uIcc a b] x, 𝓝[Set.uIcc a b] x)`, with `x ∈ Icc a b` (resp. `x ∈ uIcc a b`). This results in a two-sided derivatives for `x ∈ Set.Ioo a b` and one-sided derivatives for `x ∈ {a, b}`. Other instances could be added when needed (in that case, one also needs to add instances for `Filter.IsMeasurablyGenerated` and `Filter.TendstoIxxClass`). ## Tags integral, fundamental theorem of calculus, FTC-1, FTC-2 -/ assert_not_exists HasDerivAt.mul -- guard against import creep noncomputable section open MeasureTheory Set Filter Function Asymptotics open scoped Topology ENNReal Interval NNReal variable {ι 𝕜 E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] namespace intervalIntegral section FTC1 /-! ### Fundamental theorem of calculus, part 1, for any measure In this section we prove a few lemmas that can be seen as versions of FTC-1 for interval integrals w.r.t. any measure. Many theorems are formulated for one or two pairs of filters related by `intervalIntegral.FTCFilter a l l'`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[≥] a, 𝓝[>] a)`, `(a, 𝓝[≤] a, 𝓝[≤] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. We use this approach to avoid repeating arguments in many very similar cases. Lean can automatically find both `a` and `l'` based on `l`. The most general theorem `measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae` can be seen as a generalization of lemma `integral_hasStrictFDerivAt` below which states strict differentiability of `∫ x in u..v, f x` in `(u, v)` at `(a, b)` for a measurable function `f` that is integrable on `a..b` and is continuous at `a` and `b`. The lemma is generalized in three directions: first, `measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae` deals with any locally finite measure `μ`; second, it works for one-sided limits/derivatives; third, it assumes only that `f` has finite limits almost surely at `a` and `b`. Namely, let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `intervalIntegral.FTCFilter`s around `a`; let `(lb, lb')` be a pair of `intervalIntegral.FTCFilter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ ae μ` and `lb' ⊓ ae μ`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(‖∫ x in ua..va, (1:ℝ) ∂μ‖ + ‖∫ x in ub..vb, (1:ℝ) ∂μ‖)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This theorem is formulated with integral of constants instead of measures in the right-hand sides for two reasons: first, this way we avoid `min`/`max` in the statements; second, often it is possible to write better `simp` lemmas for these integrals, see `integral_const` and `integral_const_of_cdf`. In the next subsection we apply this theorem to prove various theorems about differentiability of the integral w.r.t. Lebesgue measure. -/ /-- An auxiliary typeclass for the Fundamental theorem of calculus, part 1. It is used to formulate theorems that work simultaneously for left and right one-sided derivatives of `∫ x in u..v, f x`. -/ class FTCFilter (a : outParam ℝ) (outer : Filter ℝ) (inner : outParam <| Filter ℝ) : Prop extends TendstoIxxClass Ioc outer inner where pure_le : pure a ≤ outer le_nhds : inner ≤ 𝓝 a [meas_gen : IsMeasurablyGenerated inner] namespace FTCFilter instance pure (a : ℝ) : FTCFilter a (pure a) ⊥ where pure_le := le_rfl le_nhds := bot_le instance nhdsWithinSingleton (a : ℝ) : FTCFilter a (𝓝[{a}] a) ⊥ := by rw [nhdsWithin, principal_singleton, inf_eq_right.2 (pure_le_nhds a)]; infer_instance theorem finiteAt_inner {a : ℝ} (l : Filter ℝ) {l'} [h : FTCFilter a l l'] {μ : Measure ℝ} [IsLocallyFiniteMeasure μ] : μ.FiniteAtFilter l' := (μ.finiteAt_nhds a).filter_mono h.le_nhds instance nhds (a : ℝ) : FTCFilter a (𝓝 a) (𝓝 a) where pure_le := pure_le_nhds a le_nhds := le_rfl instance nhdsUniv (a : ℝ) : FTCFilter a (𝓝[univ] a) (𝓝 a) := by rw [nhdsWithin_univ]; infer_instance instance nhdsLeft (a : ℝ) : FTCFilter a (𝓝[≤] a) (𝓝[≤] a) where pure_le := pure_le_nhdsWithin right_mem_Iic le_nhds := inf_le_left instance nhdsRight (a : ℝ) : FTCFilter a (𝓝[≥] a) (𝓝[>] a) where pure_le := pure_le_nhdsWithin left_mem_Ici le_nhds := inf_le_left instance nhdsIcc {x a b : ℝ} [h : Fact (x ∈ Icc a b)] : FTCFilter x (𝓝[Icc a b] x) (𝓝[Icc a b] x) where pure_le := pure_le_nhdsWithin h.out le_nhds := inf_le_left instance nhdsUIcc {x a b : ℝ} [h : Fact (x ∈ [[a, b]])] : FTCFilter x (𝓝[[[a, b]]] x) (𝓝[[[a, b]]] x) := .nhdsIcc (h := h) end FTCFilter section variable {f : ℝ → E} {a b : ℝ} {c ca cb : E} {l l' la la' lb lb' : Filter ℝ} {lt : Filter ι} {μ : Measure ℝ} {u v ua va ub vb : ι → ℝ} /-- **Fundamental theorem of calculus-1**, local version for any measure. Let filters `l` and `l'` be related by `TendstoIxxClass Ioc`. If `f` has a finite limit `c` at `l' ⊓ ae μ`, where `μ` is a measure finite at `l'`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_isLittleO_of_tendsto_ae` for a version assuming `[intervalIntegral.FTCFilter a l l']` and `[MeasureTheory.IsLocallyFiniteMeasure μ]`. If `l` is one of `𝓝[≥] a`, `𝓝[≤] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = atTop`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ theorem measure_integral_sub_linear_isLittleO_of_tendsto_ae' [IsMeasurablyGenerated l'] [TendstoIxxClass Ioc l l'] (hfm : StronglyMeasurableAtFilter f l' μ) (hf : Tendsto f (l' ⊓ ae μ) (𝓝 c)) (hl : μ.FiniteAtFilter l') (hu : Tendsto u lt l) (hv : Tendsto v lt l) : (fun t => (∫ x in u t..v t, f x ∂μ) - ∫ _ in u t..v t, c ∂μ) =o[lt] fun t => ∫ _ in u t..v t, (1 : ℝ) ∂μ := by by_cases hE : CompleteSpace E; swap · simp [intervalIntegral, integral, hE] have A := hf.integral_sub_linear_isLittleO_ae hfm hl (hu.Ioc hv) have B := hf.integral_sub_linear_isLittleO_ae hfm hl (hv.Ioc hu) simp_rw [integral_const', sub_smul] refine ((A.trans_le fun t ↦ ?_).sub (B.trans_le fun t ↦ ?_)).congr_left fun t ↦ ?_ · cases le_total (u t) (v t) <;> simp [*] · cases le_total (u t) (v t) <;> simp [*] · simp_rw [intervalIntegral] abel /-- **Fundamental theorem of calculus-1**, local version for any measure. Let filters `l` and `l'` be related by `TendstoIxxClass Ioc`. If `f` has a finite limit `c` at `l ⊓ ae μ`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l` so that `u ≤ v`. See also `measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_le` for a version assuming `[intervalIntegral.FTCFilter a l l']` and `[MeasureTheory.IsLocallyFiniteMeasure μ]`. If `l` is one of `𝓝[≥] a`, `𝓝[≤] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = Filter.atTop`. -/ theorem measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_le' [CompleteSpace E] [IsMeasurablyGenerated l'] [TendstoIxxClass Ioc l l'] (hfm : StronglyMeasurableAtFilter f l' μ) (hf : Tendsto f (l' ⊓ ae μ) (𝓝 c)) (hl : μ.FiniteAtFilter l') (hu : Tendsto u lt l) (hv : Tendsto v lt l) (huv : u ≤ᶠ[lt] v) : (fun t => (∫ x in u t..v t, f x ∂μ) - μ.real (Ioc (u t) (v t)) • c) =o[lt] fun t => μ.real (Ioc (u t) (v t)) := (measure_integral_sub_linear_isLittleO_of_tendsto_ae' hfm hf hl hu hv).congr' (huv.mono fun x hx => by simp [integral_const', hx]) (huv.mono fun x hx => by simp [integral_const', hx]) /-- **Fundamental theorem of calculus-1**, local version for any measure. Let filters `l` and `l'` be related by `TendstoIxxClass Ioc`. If `f` has a finite limit `c` at `l ⊓ ae μ`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l` so that `v ≤ u`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge` for a version assuming `[intervalIntegral.FTCFilter a l l']` and `[MeasureTheory.IsLocallyFiniteMeasure μ]`. If `l` is one of `𝓝[≥] a`, `𝓝[≤] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = Filter.atTop`. -/ theorem measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_ge' [CompleteSpace E] [IsMeasurablyGenerated l'] [TendstoIxxClass Ioc l l'] (hfm : StronglyMeasurableAtFilter f l' μ) (hf : Tendsto f (l' ⊓ ae μ) (𝓝 c)) (hl : μ.FiniteAtFilter l') (hu : Tendsto u lt l) (hv : Tendsto v lt l) (huv : v ≤ᶠ[lt] u) : (fun t => (∫ x in u t..v t, f x ∂μ) + μ.real (Ioc (v t) (u t)) • c) =o[lt] fun t => μ.real (Ioc (v t) (u t)) := (measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_le' hfm hf hl hv hu huv).neg_left.congr_left fun t => by simp [integral_symm (u t), add_comm] section IsLocallyFiniteMeasure variable [IsLocallyFiniteMeasure μ] variable [FTCFilter a la la'] [FTCFilter b lb lb'] /-- **Fundamental theorem of calculus-1**, local version for any measure. Let filters `l` and `l'` be related by `[intervalIntegral.FTCFilter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ ae μ`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_isLittleO_of_tendsto_ae'` for a version that also works, e.g., for `l = l' = Filter.atTop`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ theorem measure_integral_sub_linear_isLittleO_of_tendsto_ae [FTCFilter a l l'] (hfm : StronglyMeasurableAtFilter f l' μ) (hf : Tendsto f (l' ⊓ ae μ) (𝓝 c)) (hu : Tendsto u lt l) (hv : Tendsto v lt l) : (fun t => (∫ x in u t..v t, f x ∂μ) - ∫ _ in u t..v t, c ∂μ) =o[lt] fun t => ∫ _ in u t..v t, (1 : ℝ) ∂μ := haveI := FTCFilter.meas_gen l measure_integral_sub_linear_isLittleO_of_tendsto_ae' hfm hf (FTCFilter.finiteAt_inner l) hu hv /-- **Fundamental theorem of calculus-1**, local version for any measure. Let filters `l` and `l'` be related by `[intervalIntegral.FTCFilter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ ae μ`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_le'` for a version that also works, e.g., for `l = l' = Filter.atTop`. -/ theorem measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_le [CompleteSpace E] [FTCFilter a l l'] (hfm : StronglyMeasurableAtFilter f l' μ) (hf : Tendsto f (l' ⊓ ae μ) (𝓝 c)) (hu : Tendsto u lt l) (hv : Tendsto v lt l) (huv : u ≤ᶠ[lt] v) : (fun t => (∫ x in u t..v t, f x ∂μ) - μ.real (Ioc (u t) (v t)) • c) =o[lt] fun t => μ.real (Ioc (u t) (v t)) := haveI := FTCFilter.meas_gen l measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_le' hfm hf (FTCFilter.finiteAt_inner l) hu hv huv /-- **Fundamental theorem of calculus-1**, local version for any measure. Let filters `l` and `l'` be related by `[intervalIntegral.FTCFilter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ ae μ`, then `∫ x in u..v, f x ∂μ = -μ (Set.Ioc v u) • c + o(μ(Set.Ioc v u))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_ge'` for a version that also works, e.g., for `l = l' = Filter.atTop`. -/ theorem measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_ge [CompleteSpace E] [FTCFilter a l l'] (hfm : StronglyMeasurableAtFilter f l' μ) (hf : Tendsto f (l' ⊓ ae μ) (𝓝 c)) (hu : Tendsto u lt l) (hv : Tendsto v lt l) (huv : v ≤ᶠ[lt] u) : (fun t => (∫ x in u t..v t, f x ∂μ) + μ.real (Ioc (v t) (u t)) • c) =o[lt] fun t => μ.real (Ioc (v t) (u t)) := haveI := FTCFilter.meas_gen l measure_integral_sub_linear_isLittleO_of_tendsto_ae_of_ge' hfm hf (FTCFilter.finiteAt_inner l) hu hv huv /-- **Fundamental theorem of calculus-1**, strict derivative in both limits for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `intervalIntegral.FTCFilter`s around `a`; let `(lb, lb')` be a pair of `intervalIntegral.FTCFilter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ ae μ` and `lb' ⊓ ae μ`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(‖∫ x in ua..va, (1:ℝ) ∂μ‖ + ‖∫ x in ub..vb, (1:ℝ) ∂μ‖)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. -/ theorem measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae (hab : IntervalIntegrable f μ a b) (hmeas_a : StronglyMeasurableAtFilter f la' μ) (hmeas_b : StronglyMeasurableAtFilter f lb' μ) (ha_lim : Tendsto f (la' ⊓ ae μ) (𝓝 ca)) (hb_lim : Tendsto f (lb' ⊓ ae μ) (𝓝 cb)) (hua : Tendsto ua lt la) (hva : Tendsto va lt la) (hub : Tendsto ub lt lb) (hvb : Tendsto vb lt lb) : (fun t => ((∫ x in va t..vb t, f x ∂μ) - ∫ x in ua t..ub t, f x ∂μ) - ((∫ _ in ub t..vb t, cb ∂μ) - ∫ _ in ua t..va t, ca ∂μ)) =o[lt] fun t => ‖∫ _ in ua t..va t, (1 : ℝ) ∂μ‖ + ‖∫ _ in ub t..vb t, (1 : ℝ) ∂μ‖ := by haveI := FTCFilter.meas_gen la; haveI := FTCFilter.meas_gen lb refine ((measure_integral_sub_linear_isLittleO_of_tendsto_ae hmeas_a ha_lim hua hva).neg_left.add_add (measure_integral_sub_linear_isLittleO_of_tendsto_ae hmeas_b hb_lim hub hvb)).congr' ?_ EventuallyEq.rfl have A : ∀ᶠ t in lt, IntervalIntegrable f μ (ua t) (va t) := ha_lim.eventually_intervalIntegrable_ae hmeas_a (FTCFilter.finiteAt_inner la) hua hva have A' : ∀ᶠ t in lt, IntervalIntegrable f μ a (ua t) := ha_lim.eventually_intervalIntegrable_ae hmeas_a (FTCFilter.finiteAt_inner la) (tendsto_const_pure.mono_right FTCFilter.pure_le) hua have B : ∀ᶠ t in lt, IntervalIntegrable f μ (ub t) (vb t) := hb_lim.eventually_intervalIntegrable_ae hmeas_b (FTCFilter.finiteAt_inner lb) hub hvb have B' : ∀ᶠ t in lt, IntervalIntegrable f μ b (ub t) := hb_lim.eventually_intervalIntegrable_ae hmeas_b (FTCFilter.finiteAt_inner lb) (tendsto_const_pure.mono_right FTCFilter.pure_le) hub filter_upwards [A, A', B, B'] with _ ua_va a_ua ub_vb b_ub rw [← integral_interval_sub_interval_comm'] · abel exacts [ub_vb, ua_va, b_ub.symm.trans <| hab.symm.trans a_ua] /-- **Fundamental theorem of calculus-1**, strict derivative in right endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(lb, lb')` be a pair of `intervalIntegral.FTCFilter`s around `b`. Suppose that `f` has a finite limit `c` at `lb' ⊓ ae μ`. Then `∫ x in a..v, f x ∂μ - ∫ x in a..u, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `lb`. -/ theorem measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae_right (hab : IntervalIntegrable f μ a b) (hmeas : StronglyMeasurableAtFilter f lb' μ) (hf : Tendsto f (lb' ⊓ ae μ) (𝓝 c)) (hu : Tendsto u lt lb) (hv : Tendsto v lt lb) : (fun t => ((∫ x in a..v t, f x ∂μ) - ∫ x in a..u t, f x ∂μ) - ∫ _ in u t..v t, c ∂μ) =o[lt] fun t => ∫ _ in u t..v t, (1 : ℝ) ∂μ := by simpa using measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae hab stronglyMeasurableAt_bot hmeas ((tendsto_bot : Tendsto _ ⊥ (𝓝 (0 : E))).mono_left inf_le_left) hf (tendsto_const_pure : Tendsto _ _ (pure a)) tendsto_const_pure hu hv /-- **Fundamental theorem of calculus-1**, strict derivative in left endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `intervalIntegral.FTCFilter`s around `a`. Suppose that `f` has a finite limit `c` at `la' ⊓ ae μ`. Then `∫ x in v..b, f x ∂μ - ∫ x in u..b, f x ∂μ = -∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `la`. -/ theorem measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae_left (hab : IntervalIntegrable f μ a b) (hmeas : StronglyMeasurableAtFilter f la' μ) (hf : Tendsto f (la' ⊓ ae μ) (𝓝 c)) (hu : Tendsto u lt la) (hv : Tendsto v lt la) : (fun t => ((∫ x in v t..b, f x ∂μ) - ∫ x in u t..b, f x ∂μ) + ∫ _ in u t..v t, c ∂μ) =o[lt] fun t => ∫ _ in u t..v t, (1 : ℝ) ∂μ := by simpa using measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae hab hmeas stronglyMeasurableAt_bot hf ((tendsto_bot : Tendsto _ ⊥ (𝓝 (0 : E))).mono_left inf_le_left) hu hv (tendsto_const_pure : Tendsto _ _ (pure b)) tendsto_const_pure end IsLocallyFiniteMeasure end /-! ### Fundamental theorem of calculus-1 for Lebesgue measure In this section we restate theorems from the previous section for Lebesgue measure. In particular, we prove that `∫ x in u..v, f x` is strictly differentiable in `(u, v)` at `(a, b)` provided that `f` is integrable on `a..b` and is continuous at `a` and `b`. -/ variable [CompleteSpace E] {f : ℝ → E} {c ca cb : E} {l l' la la' lb lb' : Filter ℝ} {lt : Filter ι} {a b : ℝ} {u v ua ub va vb : ι → ℝ} [FTCFilter a la la'] [FTCFilter b lb lb'] /-! #### Auxiliary `Asymptotics.IsLittleO` statements In this section we prove several lemmas that can be interpreted as strict differentiability of `(u, v) ↦ ∫ x in u..v, f x ∂μ` in `u` and/or `v` at a filter. The statements use `Asymptotics.isLittleO` because we have no definition of `HasStrict(F)DerivAtFilter` in the library. -/ /-- **Fundamental theorem of calculus-1**, local version. If `f` has a finite limit `c` almost surely at `l'`, where `(l, l')` is an `intervalIntegral.FTCFilter` pair around `a`, then `∫ x in u..v, f x ∂μ = (v - u) • c + o (v - u)` as both `u` and `v` tend to `l`. -/ theorem integral_sub_linear_isLittleO_of_tendsto_ae [FTCFilter a l l'] (hfm : StronglyMeasurableAtFilter f l') (hf : Tendsto f (l' ⊓ ae volume) (𝓝 c)) {u v : ι → ℝ} (hu : Tendsto u lt l) (hv : Tendsto v lt l) : (fun t => (∫ x in u t..v t, f x) - (v t - u t) • c) =o[lt] (v - u) := by simpa [integral_const] using measure_integral_sub_linear_isLittleO_of_tendsto_ae hfm hf hu hv /-- **Fundamental theorem of calculus-1**, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `intervalIntegral.FTCFilter` pair around `a`, and `(lb, lb')` is an `intervalIntegral.FTCFilter` pair around `b`, and `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `(∫ x in va..vb, f x) - ∫ x in ua..ub, f x = (vb - ub) • cb - (va - ua) • ca + o(‖va - ua‖ + ‖vb - ub‖)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This lemma could've been formulated using `HasStrictFDerivAtFilter` if we had this definition. -/ theorem integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae (hab : IntervalIntegrable f volume a b) (hmeas_a : StronglyMeasurableAtFilter f la') (hmeas_b : StronglyMeasurableAtFilter f lb') (ha_lim : Tendsto f (la' ⊓ ae volume) (𝓝 ca)) (hb_lim : Tendsto f (lb' ⊓ ae volume) (𝓝 cb)) (hua : Tendsto ua lt la) (hva : Tendsto va lt la) (hub : Tendsto ub lt lb) (hvb : Tendsto vb lt lb) : (fun t => ((∫ x in va t..vb t, f x) - ∫ x in ua t..ub t, f x) - ((vb t - ub t) • cb - (va t - ua t) • ca)) =o[lt] fun t => ‖va t - ua t‖ + ‖vb t - ub t‖ := by simpa [integral_const] using measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae hab hmeas_a hmeas_b ha_lim hb_lim hua hva hub hvb /-- **Fundamental theorem of calculus-1**, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(lb, lb')` is an `intervalIntegral.FTCFilter` pair around `b`, and `f` has a finite limit `c` almost surely at `lb'`, then `(∫ x in a..v, f x) - ∫ x in a..u, f x = (v - u) • c + o(‖v - u‖)` as `u` and `v` tend to `lb`. This lemma could've been formulated using `HasStrictDerivAtFilter` if we had this definition. -/ theorem integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae_right (hab : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f lb') (hf : Tendsto f (lb' ⊓ ae volume) (𝓝 c)) (hu : Tendsto u lt lb) (hv : Tendsto v lt lb) : (fun t => ((∫ x in a..v t, f x) - ∫ x in a..u t, f x) - (v t - u t) • c) =o[lt] (v - u) := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae_right hab hmeas hf hu hv /-- **Fundamental theorem of calculus-1**, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `intervalIntegral.FTCFilter` pair around `a`, and `f` has a finite limit `c` almost surely at `la'`, then `(∫ x in v..b, f x) - ∫ x in u..b, f x = -(v - u) • c + o(‖v - u‖)` as `u` and `v` tend to `la`. This lemma could've been formulated using `HasStrictDerivAtFilter` if we had this definition. -/ theorem integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae_left (hab : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f la') (hf : Tendsto f (la' ⊓ ae volume) (𝓝 c)) (hu : Tendsto u lt la) (hv : Tendsto v lt la) : (fun t => ((∫ x in v t..b, f x) - ∫ x in u t..b, f x) + (v t - u t) • c) =o[lt] (v - u) := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae_left hab hmeas hf hu hv open ContinuousLinearMap (fst snd smulRight sub_apply smulRight_apply coe_fst' coe_snd' map_sub) /-! #### Strict differentiability In this section we prove that for a measurable function `f` integrable on `a..b`, * `integral_hasStrictFDerivAt_of_tendsto_ae`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability provided that `f` tends to `ca` and `cb` almost surely as `x` tendsto to `a` and `b`, respectively; * `integral_hasStrictFDerivAt`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` at `(a, b)` in the sense of strict differentiability provided that `f` is continuous at `a` and `b`; * `integral_hasStrictDerivAt_of_tendsto_ae_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `b`; * `integral_hasStrictDerivAt_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability provided that `f` is continuous at `b`; * `integral_hasStrictDerivAt_of_tendsto_ae_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `a`; * `integral_hasStrictDerivAt_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability provided that `f` is continuous at `a`. -/ /-- **Fundamental theorem of calculus-1**, strict differentiability in both endpoints. If `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ theorem integral_hasStrictFDerivAt_of_tendsto_ae (hf : IntervalIntegrable f volume a b) (hmeas_a : StronglyMeasurableAtFilter f (𝓝 a)) (hmeas_b : StronglyMeasurableAtFilter f (𝓝 b)) (ha : Tendsto f (𝓝 a ⊓ ae volume) (𝓝 ca)) (hb : Tendsto f (𝓝 b ⊓ ae volume) (𝓝 cb)) : HasStrictFDerivAt (fun p : ℝ × ℝ => ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smulRight cb - (fst ℝ ℝ ℝ).smulRight ca) (a, b) := by have := integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae hf hmeas_a hmeas_b ha hb (continuous_snd.fst.tendsto ((a, b), (a, b))) (continuous_fst.fst.tendsto ((a, b), (a, b))) (continuous_snd.snd.tendsto ((a, b), (a, b))) (continuous_fst.snd.tendsto ((a, b), (a, b))) refine .of_isLittleO <| (this.congr_left ?_).trans_isBigO ?_ · simp [sub_smul] · exact isBigO_fst_prod.norm_left.add isBigO_snd_prod.norm_left /-- **Fundamental theorem of calculus-1**, strict differentiability in both endpoints. If `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ theorem integral_hasStrictFDerivAt (hf : IntervalIntegrable f volume a b) (hmeas_a : StronglyMeasurableAtFilter f (𝓝 a)) (hmeas_b : StronglyMeasurableAtFilter f (𝓝 b)) (ha : ContinuousAt f a) (hb : ContinuousAt f b) : HasStrictFDerivAt (fun p : ℝ × ℝ => ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smulRight (f b) - (fst ℝ ℝ ℝ).smulRight (f a)) (a, b) := integral_hasStrictFDerivAt_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- **Fundamental theorem of calculus-1**, strict differentiability in the right endpoint. If `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability. -/ theorem integral_hasStrictDerivAt_of_tendsto_ae_right (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 b)) (hb : Tendsto f (𝓝 b ⊓ ae volume) (𝓝 c)) : HasStrictDerivAt (fun u => ∫ x in a..u, f x) c b := .of_isLittleO <| integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae_right hf hmeas hb continuousAt_snd continuousAt_fst /-- **Fundamental theorem of calculus-1**, strict differentiability in the right endpoint. If `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability. -/ theorem integral_hasStrictDerivAt_right (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 b)) (hb : ContinuousAt f b) : HasStrictDerivAt (fun u => ∫ x in a..u, f x) (f b) b := integral_hasStrictDerivAt_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- **Fundamental theorem of calculus-1**, strict differentiability in the left endpoint. If `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability. -/ theorem integral_hasStrictDerivAt_of_tendsto_ae_left (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 a)) (ha : Tendsto f (𝓝 a ⊓ ae volume) (𝓝 c)) : HasStrictDerivAt (fun u => ∫ x in u..b, f x) (-c) a := by simpa only [← integral_symm] using (integral_hasStrictDerivAt_of_tendsto_ae_right hf.symm hmeas ha).fun_neg /-- **Fundamental theorem of calculus-1**, strict differentiability in the left endpoint. If `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability. -/ theorem integral_hasStrictDerivAt_left (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 a)) (ha : ContinuousAt f a) : HasStrictDerivAt (fun u => ∫ x in u..b, f x) (-f a) a := by simpa only [← integral_symm] using (integral_hasStrictDerivAt_right hf.symm hmeas ha).fun_neg /-- **Fundamental theorem of calculus-1**, strict differentiability in the right endpoint. If `f : ℝ → E` is continuous, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability. -/ theorem _root_.Continuous.integral_hasStrictDerivAt {f : ℝ → E} (hf : Continuous f) (a b : ℝ) : HasStrictDerivAt (fun u => ∫ x : ℝ in a..u, f x) (f b) b := integral_hasStrictDerivAt_right (hf.intervalIntegrable _ _) (hf.stronglyMeasurableAtFilter _ _) hf.continuousAt /-- **Fundamental theorem of calculus-1**, derivative in the right endpoint. If `f : ℝ → E` is continuous, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` is `f b`. -/ theorem _root_.Continuous.deriv_integral (f : ℝ → E) (hf : Continuous f) (a b : ℝ) : deriv (fun u => ∫ x : ℝ in a..u, f x) b = f b := (hf.integral_hasStrictDerivAt a b).hasDerivAt.deriv /-! #### Fréchet differentiability In this subsection we restate results from the previous subsection in terms of `HasFDerivAt`, `HasDerivAt`, `fderiv`, and `deriv`. -/ /-- **Fundamental theorem of calculus-1**: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ theorem integral_hasFDerivAt_of_tendsto_ae (hf : IntervalIntegrable f volume a b) (hmeas_a : StronglyMeasurableAtFilter f (𝓝 a)) (hmeas_b : StronglyMeasurableAtFilter f (𝓝 b)) (ha : Tendsto f (𝓝 a ⊓ ae volume) (𝓝 ca)) (hb : Tendsto f (𝓝 b ⊓ ae volume) (𝓝 cb)) : HasFDerivAt (fun p : ℝ × ℝ => ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smulRight cb - (fst ℝ ℝ ℝ).smulRight ca) (a, b) := (integral_hasStrictFDerivAt_of_tendsto_ae hf hmeas_a hmeas_b ha hb).hasFDerivAt /-- **Fundamental theorem of calculus-1**: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ theorem integral_hasFDerivAt (hf : IntervalIntegrable f volume a b) (hmeas_a : StronglyMeasurableAtFilter f (𝓝 a)) (hmeas_b : StronglyMeasurableAtFilter f (𝓝 b)) (ha : ContinuousAt f a) (hb : ContinuousAt f b) : HasFDerivAt (fun p : ℝ × ℝ => ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smulRight (f b) - (fst ℝ ℝ ℝ).smulRight (f a)) (a, b) := (integral_hasStrictFDerivAt hf hmeas_a hmeas_b ha hb).hasFDerivAt /-- **Fundamental theorem of calculus-1**: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ theorem fderiv_integral_of_tendsto_ae (hf : IntervalIntegrable f volume a b) (hmeas_a : StronglyMeasurableAtFilter f (𝓝 a)) (hmeas_b : StronglyMeasurableAtFilter f (𝓝 b)) (ha : Tendsto f (𝓝 a ⊓ ae volume) (𝓝 ca)) (hb : Tendsto f (𝓝 b ⊓ ae volume) (𝓝 cb)) : fderiv ℝ (fun p : ℝ × ℝ => ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smulRight cb - (fst ℝ ℝ ℝ).smulRight ca := (integral_hasFDerivAt_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv /-- **Fundamental theorem of calculus-1**: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ theorem fderiv_integral (hf : IntervalIntegrable f volume a b) (hmeas_a : StronglyMeasurableAtFilter f (𝓝 a)) (hmeas_b : StronglyMeasurableAtFilter f (𝓝 b)) (ha : ContinuousAt f a) (hb : ContinuousAt f b) : fderiv ℝ (fun p : ℝ × ℝ => ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smulRight (f b) - (fst ℝ ℝ ℝ).smulRight (f a) := (integral_hasFDerivAt hf hmeas_a hmeas_b ha hb).fderiv /-- **Fundamental theorem of calculus-1**: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b`. -/ theorem integral_hasDerivAt_of_tendsto_ae_right (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 b)) (hb : Tendsto f (𝓝 b ⊓ ae volume) (𝓝 c)) : HasDerivAt (fun u => ∫ x in a..u, f x) c b := (integral_hasStrictDerivAt_of_tendsto_ae_right hf hmeas hb).hasDerivAt /-- **Fundamental theorem of calculus-1**: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b`. -/ theorem integral_hasDerivAt_right (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 b)) (hb : ContinuousAt f b) : HasDerivAt (fun u => ∫ x in a..u, f x) (f b) b := (integral_hasStrictDerivAt_right hf hmeas hb).hasDerivAt /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ theorem deriv_integral_of_tendsto_ae_right (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 b)) (hb : Tendsto f (𝓝 b ⊓ ae volume) (𝓝 c)) : deriv (fun u => ∫ x in a..u, f x) b = c := (integral_hasDerivAt_of_tendsto_ae_right hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ theorem deriv_integral_right (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 b)) (hb : ContinuousAt f b) : deriv (fun u => ∫ x in a..u, f x) b = f b := (integral_hasDerivAt_right hf hmeas hb).deriv /-- **Fundamental theorem of calculus-1**: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a`. -/ theorem integral_hasDerivAt_of_tendsto_ae_left (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 a)) (ha : Tendsto f (𝓝 a ⊓ ae volume) (𝓝 c)) : HasDerivAt (fun u => ∫ x in u..b, f x) (-c) a := (integral_hasStrictDerivAt_of_tendsto_ae_left hf hmeas ha).hasDerivAt /-- **Fundamental theorem of calculus-1**: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a`. -/ theorem integral_hasDerivAt_left (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 a)) (ha : ContinuousAt f a) : HasDerivAt (fun u => ∫ x in u..b, f x) (-f a) a := (integral_hasStrictDerivAt_left hf hmeas ha).hasDerivAt /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ theorem deriv_integral_of_tendsto_ae_left (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 a)) (hb : Tendsto f (𝓝 a ⊓ ae volume) (𝓝 c)) : deriv (fun u => ∫ x in u..b, f x) a = -c := (integral_hasDerivAt_of_tendsto_ae_left hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ theorem deriv_integral_left (hf : IntervalIntegrable f volume a b) (hmeas : StronglyMeasurableAtFilter f (𝓝 a)) (hb : ContinuousAt f a) : deriv (fun u => ∫ x in u..b, f x) a = -f a := (integral_hasDerivAt_left hf hmeas hb).deriv /-! #### One-sided derivatives -/ /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` | | `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ theorem integral_hasFDerivWithinAt_of_tendsto_ae (hf : IntervalIntegrable f volume a b) {s t : Set ℝ} [FTCFilter a (𝓝[s] a) la] [FTCFilter b (𝓝[t] b) lb] (hmeas_a : StronglyMeasurableAtFilter f la) (hmeas_b : StronglyMeasurableAtFilter f lb) (ha : Tendsto f (la ⊓ ae volume) (𝓝 ca)) (hb : Tendsto f (lb ⊓ ae volume) (𝓝 cb)) : HasFDerivWithinAt (fun p : ℝ × ℝ => ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smulRight cb - (fst ℝ ℝ ℝ).smulRight ca) (s ×ˢ t) (a, b) := by rw [HasFDerivWithinAt, nhdsWithin_prod_eq] have := integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae hf hmeas_a hmeas_b ha hb (tendsto_const_pure.mono_right FTCFilter.pure_le : Tendsto _ _ (𝓝[s] a)) tendsto_fst (tendsto_const_pure.mono_right FTCFilter.pure_le : Tendsto _ _ (𝓝[t] b)) tendsto_snd refine .of_isLittleO <| (this.congr_left ?_).trans_isBigO ?_ · simp [sub_smul] · exact isBigO_fst_prod.norm_left.add isBigO_snd_prod.norm_left /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `f a` and `f b` at the filters `la` and `lb` from the following table. In most cases this assumption is definitionally equal `ContinuousAt f _` or `ContinuousWithinAt f _ _`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` | | `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ theorem integral_hasFDerivWithinAt (hf : IntervalIntegrable f volume a b) (hmeas_a : StronglyMeasurableAtFilter f la) (hmeas_b : StronglyMeasurableAtFilter f lb) {s t : Set ℝ} [FTCFilter a (𝓝[s] a) la] [FTCFilter b (𝓝[t] b) lb] (ha : Tendsto f la (𝓝 <| f a)) (hb : Tendsto f lb (𝓝 <| f b)) : HasFDerivWithinAt (fun p : ℝ × ℝ => ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smulRight (f b) - (fst ℝ ℝ ℝ).smulRight (f a)) (s ×ˢ t) (a, b) := integral_hasFDerivWithinAt_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- An auxiliary tactic closing goals `UniqueDiffWithinAt ℝ s a` where `s ∈ {Iic a, Ici a, univ}`. -/ macro "uniqueDiffWithinAt_Ici_Iic_univ" : tactic => `(tactic| (first | exact uniqueDiffOn_Ici _ _ left_mem_Ici | exact uniqueDiffOn_Iic _ _ right_mem_Iic | exact uniqueDiffWithinAt_univ (𝕜 := ℝ) (E := ℝ))) /-- Let `f` be a measurable function integrable on `a..b`. Choose `s ∈ {Iic a, Ici a, univ}` and `t ∈ {Iic b, Ici b, univ}`. Suppose that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the table below. Then `fderivWithin ℝ (fun p ↦ ∫ x in p.1..p.2, f x) (s ×ˢ t)` is equal to `(u, v) ↦ u • cb - v • ca`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` | | `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ theorem fderivWithin_integral_of_tendsto_ae (hf : IntervalIntegrable f volume a b) (hmeas_a : StronglyMeasurableAtFilter f la) (hmeas_b : StronglyMeasurableAtFilter f lb) {s t : Set ℝ} [FTCFilter a (𝓝[s] a) la] [FTCFilter b (𝓝[t] b) lb] (ha : Tendsto f (la ⊓ ae volume) (𝓝 ca)) (hb : Tendsto f (lb ⊓ ae volume) (𝓝 cb)) (hs : UniqueDiffWithinAt ℝ s a := by uniqueDiffWithinAt_Ici_Iic_univ) (ht : UniqueDiffWithinAt ℝ t b := by uniqueDiffWithinAt_Ici_Iic_univ) : fderivWithin ℝ (fun p : ℝ × ℝ => ∫ x in p.1..p.2, f x) (s ×ˢ t) (a, b) = (snd ℝ ℝ ℝ).smulRight cb - (fst ℝ ℝ ℝ).smulRight ca := (integral_hasFDerivWithinAt_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderivWithin <| hs.prod ht /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then `u ↦ ∫ x in a..u, f x` has right (resp., left) derivative `c` at `b`. -/ theorem integral_hasDerivWithinAt_of_tendsto_ae_right (hf : IntervalIntegrable f volume a b) {s t : Set ℝ} [FTCFilter b (𝓝[s] b) (𝓝[t] b)] (hmeas : StronglyMeasurableAtFilter f (𝓝[t] b)) (hb : Tendsto f (𝓝[t] b ⊓ ae volume) (𝓝 c)) : HasDerivWithinAt (fun u => ∫ x in a..u, f x) c s b := .of_isLittleO <| integral_sub_integral_sub_linear_isLittleO_of_tendsto_ae_right hf hmeas hb (tendsto_const_pure.mono_right FTCFilter.pure_le) tendsto_id /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `b`, then `u ↦ ∫ x in a..u, f x` has left (resp., right) derivative `f b` at `b`. -/ theorem integral_hasDerivWithinAt_right (hf : IntervalIntegrable f volume a b) {s t : Set ℝ} [FTCFilter b (𝓝[s] b) (𝓝[t] b)] (hmeas : StronglyMeasurableAtFilter f (𝓝[t] b)) (hb : ContinuousWithinAt f t b) : HasDerivWithinAt (fun u => ∫ x in a..u, f x) (f b) s b := integral_hasDerivWithinAt_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ theorem derivWithin_integral_of_tendsto_ae_right (hf : IntervalIntegrable f volume a b) {s t : Set ℝ} [FTCFilter b (𝓝[s] b) (𝓝[t] b)] (hmeas : StronglyMeasurableAtFilter f (𝓝[t] b)) (hb : Tendsto f (𝓝[t] b ⊓ ae volume) (𝓝 c)) (hs : UniqueDiffWithinAt ℝ s b := by uniqueDiffWithinAt_Ici_Iic_univ) : derivWithin (fun u => ∫ x in a..u, f x) s b = c := (integral_hasDerivWithinAt_of_tendsto_ae_right hf hmeas hb).derivWithin hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `b`, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ theorem derivWithin_integral_right (hf : IntervalIntegrable f volume a b) {s t : Set ℝ} [FTCFilter b (𝓝[s] b) (𝓝[t] b)] (hmeas : StronglyMeasurableAtFilter f (𝓝[t] b)) (hb : ContinuousWithinAt f t b) (hs : UniqueDiffWithinAt ℝ s b := by uniqueDiffWithinAt_Ici_Iic_univ) : derivWithin (fun u => ∫ x in a..u, f x) s b = f b := (integral_hasDerivWithinAt_right hf hmeas hb).derivWithin hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then `u ↦ ∫ x in u..b, f x` has right (resp., left) derivative `-c` at `a`. -/ theorem integral_hasDerivWithinAt_of_tendsto_ae_left (hf : IntervalIntegrable f volume a b) {s t : Set ℝ} [FTCFilter a (𝓝[s] a) (𝓝[t] a)] (hmeas : StronglyMeasurableAtFilter f (𝓝[t] a)) (ha : Tendsto f (𝓝[t] a ⊓ ae volume) (𝓝 c)) : HasDerivWithinAt (fun u => ∫ x in u..b, f x) (-c) s a := by simp only [integral_symm b] exact (integral_hasDerivWithinAt_of_tendsto_ae_right hf.symm hmeas ha).neg /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `a`, then `u ↦ ∫ x in u..b, f x` has left (resp., right) derivative `-f a` at `a`. -/ theorem integral_hasDerivWithinAt_left (hf : IntervalIntegrable f volume a b) {s t : Set ℝ} [FTCFilter a (𝓝[s] a) (𝓝[t] a)] (hmeas : StronglyMeasurableAtFilter f (𝓝[t] a)) (ha : ContinuousWithinAt f t a) : HasDerivWithinAt (fun u => ∫ x in u..b, f x) (-f a) s a := integral_hasDerivWithinAt_of_tendsto_ae_left hf hmeas (ha.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ theorem derivWithin_integral_of_tendsto_ae_left (hf : IntervalIntegrable f volume a b) {s t : Set ℝ} [FTCFilter a (𝓝[s] a) (𝓝[t] a)] (hmeas : StronglyMeasurableAtFilter f (𝓝[t] a)) (ha : Tendsto f (𝓝[t] a ⊓ ae volume) (𝓝 c)) (hs : UniqueDiffWithinAt ℝ s a := by uniqueDiffWithinAt_Ici_Iic_univ) : derivWithin (fun u => ∫ x in u..b, f x) s a = -c := (integral_hasDerivWithinAt_of_tendsto_ae_left hf hmeas ha).derivWithin hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `a`, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ theorem derivWithin_integral_left (hf : IntervalIntegrable f volume a b) {s t : Set ℝ} [FTCFilter a (𝓝[s] a) (𝓝[t] a)] (hmeas : StronglyMeasurableAtFilter f (𝓝[t] a)) (ha : ContinuousWithinAt f t a) (hs : UniqueDiffWithinAt ℝ s a := by uniqueDiffWithinAt_Ici_Iic_univ) : derivWithin (fun u => ∫ x in u..b, f x) s a = -f a := (integral_hasDerivWithinAt_left hf hmeas ha).derivWithin hs /-- The integral of a continuous function is differentiable on a real set `s`. -/ theorem differentiable_integral_of_continuous (hcont : Continuous f) : Differentiable ℝ (fun u => ∫ x in a..u, f x) := fun _ ↦ (integral_hasDerivAt_right (hcont.intervalIntegrable _ _) hcont.aestronglyMeasurable.stronglyMeasurableAtFilter hcont.continuousAt).differentiableAt /-- The integral of a continuous function is differentiable on a real set `s`. -/ theorem differentiableOn_integral_of_continuous {s : Set ℝ} (hcont : Continuous f) : DifferentiableOn ℝ (fun u => ∫ x in a..u, f x) s := (differentiable_integral_of_continuous hcont).differentiableOn end FTC1 /-! ### Fundamental theorem of calculus, part 2 This section contains theorems pertaining to FTC-2 for interval integrals, i.e., the assertion that `∫ x in a..b, f' x = f b - f a` under suitable assumptions. The most classical version of this theorem assumes that `f'` is continuous. However, this is unnecessarily strong: the result holds if `f'` is just integrable. We prove the strong version, following [Rudin, *Real and Complex Analysis* (Theorem 7.21)][rudin2006real]. The proof is first given for real-valued functions, and then deduced for functions with a general target space. For a real-valued function `g`, it suffices to show that `g b - g a ≤ (∫ x in a..b, g' x) + ε` for all positive `ε`. To prove this, choose a lower-semicontinuous function `G'` with `g' < G'` and with integral close to that of `g'` (its existence is guaranteed by the Vitali-Carathéodory theorem). It satisfies `g t - g a ≤ ∫ x in a..t, G' x` for all `t ∈ [a, b]`: this inequality holds at `a`, and if it holds at `t` then it holds for `u` close to `t` on its right, as the left-hand side increases by `g u - g t ∼ (u -t) g' t`, while the right-hand side increases by `∫ x in t..u, G' x` which is roughly at least `∫ x in t..u, G' t = (u - t) G' t`, by lower semicontinuity. As `g' t < G' t`, this gives the conclusion. One can therefore push progressively this inequality to the right until the point `b`, where it gives the desired conclusion. -/ section FTC2 variable {g' g φ : ℝ → ℝ} {a b : ℝ} /-- Hard part of FTC-2 for integrable derivatives, real-valued functions: one has `g b - g a ≤ ∫ y in a..b, g' y` when `g'` is integrable. Auxiliary lemma in the proof of `integral_eq_sub_of_hasDeriv_right_of_le`. We give the slightly more general version that `g b - g a ≤ ∫ y in a..b, φ y` when `g' ≤ φ` and `φ` is integrable (even if `g'` is not known to be integrable). Version assuming that `g` is differentiable on `[a, b)`. -/ theorem sub_le_integral_of_hasDeriv_right_of_le_Ico (hab : a ≤ b) (hcont : ContinuousOn g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, HasDerivWithinAt g (g' x) (Ioi x) x) (φint : IntegrableOn φ (Icc a b)) (hφg : ∀ x ∈ Ico a b, g' x ≤ φ x) : g b - g a ≤ ∫ y in a..b, φ y := by refine le_of_forall_pos_le_add fun ε εpos => ?_ -- Bound from above `g'` by a lower-semicontinuous function `G'`. rcases exists_lt_lowerSemicontinuous_integral_lt φ φint εpos with ⟨G', f_lt_G', G'cont, G'int, G'lt_top, hG'⟩ -- we will show by "induction" that `g t - g a ≤ ∫ u in a..t, G' u` for all `t ∈ [a, b]`. set s := {t | g t - g a ≤ ∫ u in a..t, (G' u).toReal} ∩ Icc a b -- the set `s` of points where this property holds is closed. have s_closed : IsClosed s := by have : ContinuousOn (fun t => (g t - g a, ∫ u in a..t, (G' u).toReal)) (Icc a b) := by rw [← uIcc_of_le hab] at G'int hcont ⊢ exact (hcont.sub continuousOn_const).prodMk (continuousOn_primitive_interval G'int) simp only [s, inter_comm] exact this.preimage_isClosed_of_isClosed isClosed_Icc OrderClosedTopology.isClosed_le' have main : Icc a b ⊆ {t | g t - g a ≤ ∫ u in a..t, (G' u).toReal} := by -- to show that the set `s` is all `[a, b]`, it suffices to show that any point `t` in `s` -- with `t < b` admits another point in `s` slightly to its right -- (this is a sort of real induction). refine s_closed.Icc_subset_of_forall_exists_gt (by simp only [integral_same, mem_setOf_eq, sub_self, le_rfl]) fun t ht v t_lt_v => ?_ obtain ⟨y, g'_lt_y', y_lt_G'⟩ : ∃ y : ℝ, (g' t : EReal) < y ∧ (y : EReal) < G' t := EReal.lt_iff_exists_real_btwn.1 ((EReal.coe_le_coe_iff.2 (hφg t ht.2)).trans_lt (f_lt_G' t)) -- bound from below the increase of `∫ x in a..u, G' x` on the right of `t`, using the lower -- semicontinuity of `G'`. have I1 : ∀ᶠ u in 𝓝[>] t, (u - t) * y ≤ ∫ w in t..u, (G' w).toReal := by have B : ∀ᶠ u in 𝓝 t, (y : EReal) < G' u := G'cont.lowerSemicontinuousAt _ _ y_lt_G' rcases mem_nhds_iff_exists_Ioo_subset.1 B with ⟨m, M, ⟨hm, hM⟩, H⟩ have : Ioo t (min M b) ∈ 𝓝[>] t := Ioo_mem_nhdsGT (lt_min hM ht.right.right) filter_upwards [this] with u hu have I : Icc t u ⊆ Icc a b := Icc_subset_Icc ht.2.1 (hu.2.le.trans (min_le_right _ _)) calc (u - t) * y = ∫ _ in Icc t u, y := by simp only [MeasureTheory.integral_const, MeasurableSet.univ, measureReal_restrict_apply, univ_inter, hu.left.le, Real.volume_real_Icc_of_le, smul_eq_mul] _ ≤ ∫ w in t..u, (G' w).toReal := by rw [intervalIntegral.integral_of_le hu.1.le, ← integral_Icc_eq_integral_Ioc] apply setIntegral_mono_ae_restrict · simp · exact IntegrableOn.mono_set G'int I · have C1 : ∀ᵐ x : ℝ ∂volume.restrict (Icc t u), G' x < ∞ := ae_mono (Measure.restrict_mono I le_rfl) G'lt_top have C2 : ∀ᵐ x : ℝ ∂volume.restrict (Icc t u), x ∈ Icc t u := ae_restrict_mem measurableSet_Icc filter_upwards [C1, C2] with x G'x hx apply EReal.coe_le_coe_iff.1 have : x ∈ Ioo m M := by simp only [hm.trans_le hx.left, (hx.right.trans_lt hu.right).trans_le (min_le_left M b), mem_Ioo, and_self_iff] refine (H this).out.le.trans_eq ?_ exact (EReal.coe_toReal G'x.ne (f_lt_G' x).ne_bot).symm -- bound from above the increase of `g u - g a` on the right of `t`, using the derivative at `t` have I2 : ∀ᶠ u in 𝓝[>] t, g u - g t ≤ (u - t) * y := by have g'_lt_y : g' t < y := EReal.coe_lt_coe_iff.1 g'_lt_y' filter_upwards [(hderiv t ⟨ht.2.1, ht.2.2⟩).limsup_slope_le' (notMem_Ioi.2 le_rfl) g'_lt_y, self_mem_nhdsWithin] with u hu t_lt_u have := mul_le_mul_of_nonneg_left hu.le (sub_pos.2 t_lt_u.out).le rwa [← smul_eq_mul, sub_smul_slope] at this -- combine the previous two bounds to show that `g u - g a` increases less quickly than -- `∫ x in a..u, G' x`. have I3 : ∀ᶠ u in 𝓝[>] t, g u - g t ≤ ∫ w in t..u, (G' w).toReal := by filter_upwards [I1, I2] with u hu1 hu2 using hu2.trans hu1 have I4 : ∀ᶠ u in 𝓝[>] t, u ∈ Ioc t (min v b) := Ioc_mem_nhdsGT <| lt_min t_lt_v ht.2.2 -- choose a point `x` slightly to the right of `t` which satisfies the above bound rcases (I3.and I4).exists with ⟨x, hx, h'x⟩ -- we check that it belongs to `s`, essentially by construction refine ⟨x, ?_, Ioc_subset_Ioc le_rfl (min_le_left _ _) h'x⟩ calc g x - g a = g t - g a + (g x - g t) := by abel _ ≤ (∫ w in a..t, (G' w).toReal) + ∫ w in t..x, (G' w).toReal := add_le_add ht.1 hx _ = ∫ w in a..x, (G' w).toReal := by apply integral_add_adjacent_intervals · rw [intervalIntegrable_iff_integrableOn_Ioc_of_le ht.2.1] exact IntegrableOn.mono_set G'int (Ioc_subset_Icc_self.trans (Icc_subset_Icc le_rfl ht.2.2.le)) · rw [intervalIntegrable_iff_integrableOn_Ioc_of_le h'x.1.le] apply IntegrableOn.mono_set G'int exact Ioc_subset_Icc_self.trans (Icc_subset_Icc ht.2.1 (h'x.2.trans (min_le_right _ _))) -- now that we know that `s` contains `[a, b]`, we get the desired result by applying this to `b`. calc g b - g a ≤ ∫ y in a..b, (G' y).toReal := main (right_mem_Icc.2 hab) _ ≤ (∫ y in a..b, φ y) + ε := by convert hG'.le <;> · rw [intervalIntegral.integral_of_le hab] simp only [integral_Icc_eq_integral_Ioc', Real.volume_singleton] /-- Hard part of FTC-2 for integrable derivatives, real-valued functions: one has `g b - g a ≤ ∫ y in a..b, g' y` when `g'` is integrable. Auxiliary lemma in the proof of `integral_eq_sub_of_hasDeriv_right_of_le`. We give the slightly more general version that `g b - g a ≤ ∫ y in a..b, φ y` when `g' ≤ φ` and `φ` is integrable (even if `g'` is not known to be integrable). Version assuming that `g` is differentiable on `(a, b)`. -/ theorem sub_le_integral_of_hasDeriv_right_of_le (hab : a ≤ b) (hcont : ContinuousOn g (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, HasDerivWithinAt g (g' x) (Ioi x) x) (φint : IntegrableOn φ (Icc a b)) (hφg : ∀ x ∈ Ioo a b, g' x ≤ φ x) : g b - g a ≤ ∫ y in a..b, φ y := by -- This follows from the version on a closed-open interval (applied to `[t, b)` for `t` close to -- `a`) and a continuity argument. obtain rfl | a_lt_b := hab.eq_or_lt · simp set s := {t | g b - g t ≤ ∫ u in t..b, φ u} ∩ Icc a b have s_closed : IsClosed s := by have : ContinuousOn (fun t => (g b - g t, ∫ u in t..b, φ u)) (Icc a b) := by rw [← uIcc_of_le hab] at hcont φint ⊢ exact (continuousOn_const.sub hcont).prodMk (continuousOn_primitive_interval_left φint) simp only [s, inter_comm] exact this.preimage_isClosed_of_isClosed isClosed_Icc isClosed_le_prod have A : closure (Ioc a b) ⊆ s := by apply s_closed.closure_subset_iff.2 intro t ht refine ⟨?_, ⟨ht.1.le, ht.2⟩⟩ exact sub_le_integral_of_hasDeriv_right_of_le_Ico ht.2 (hcont.mono (Icc_subset_Icc ht.1.le le_rfl)) (fun x hx => hderiv x ⟨ht.1.trans_le hx.1, hx.2⟩) (φint.mono_set (Icc_subset_Icc ht.1.le le_rfl)) fun x hx => hφg x ⟨ht.1.trans_le hx.1, hx.2⟩ rw [closure_Ioc a_lt_b.ne] at A exact (A (left_mem_Icc.2 hab)).1 /-- Auxiliary lemma in the proof of `integral_eq_sub_of_hasDeriv_right_of_le`. -/ theorem integral_le_sub_of_hasDeriv_right_of_le (hab : a ≤ b) (hcont : ContinuousOn g (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, HasDerivWithinAt g (g' x) (Ioi x) x) (φint : IntegrableOn φ (Icc a b)) (hφg : ∀ x ∈ Ioo a b, φ x ≤ g' x) : (∫ y in a..b, φ y) ≤ g b - g a := by rw [← neg_le_neg_iff] convert sub_le_integral_of_hasDeriv_right_of_le hab hcont.neg (fun x hx => (hderiv x hx).neg) φint.neg fun x hx => neg_le_neg (hφg x hx) using 1 · abel · simp only [← integral_neg]; rfl /-- Auxiliary lemma in the proof of `integral_eq_sub_of_hasDeriv_right_of_le`: real version -/ theorem integral_eq_sub_of_hasDeriv_right_of_le_real (hab : a ≤ b) (hcont : ContinuousOn g (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, HasDerivWithinAt g (g' x) (Ioi x) x) (g'int : IntegrableOn g' (Icc a b)) : ∫ y in a..b, g' y = g b - g a := le_antisymm (integral_le_sub_of_hasDeriv_right_of_le hab hcont hderiv g'int fun _ _ => le_rfl) (sub_le_integral_of_hasDeriv_right_of_le hab hcont hderiv g'int fun _ _ => le_rfl) variable [CompleteSpace E] {f f' : ℝ → E} /-- **Fundamental theorem of calculus-2**: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a right derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_hasDeriv_right_of_le (hab : a ≤ b) (hcont : ContinuousOn f (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, HasDerivWithinAt f (f' x) (Ioi x) x) (f'int : IntervalIntegrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := by refine (NormedSpace.eq_iff_forall_dual_eq ℝ).2 fun g => ?_ rw [← g.intervalIntegral_comp_comm f'int, g.map_sub] exact integral_eq_sub_of_hasDeriv_right_of_le_real hab (g.continuous.comp_continuousOn hcont) (fun x hx => g.hasFDerivAt.comp_hasDerivWithinAt x (hderiv x hx)) (g.integrable_comp ((intervalIntegrable_iff_integrableOn_Icc_of_le hab enorm_ne_top).1 f'int)) /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is integrable on `[a, b]` then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_hasDeriv_right (hcont : ContinuousOn f (uIcc a b)) (hderiv : ∀ x ∈ Ioo (min a b) (max a b), HasDerivWithinAt f (f' x) (Ioi x) x) (hint : IntervalIntegrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := by rcases le_total a b with hab | hab · simp only [uIcc_of_le, min_eq_left, max_eq_right, hab] at hcont hderiv hint apply integral_eq_sub_of_hasDeriv_right_of_le hab hcont hderiv hint · simp only [uIcc_of_ge, min_eq_right, max_eq_left, hab] at hcont hderiv rw [integral_symm, integral_eq_sub_of_hasDeriv_right_of_le hab hcont hderiv hint.symm, neg_sub] /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_hasDerivAt_of_le (hab : a ≤ b) (hcont : ContinuousOn f (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, HasDerivAt f (f' x) x) (hint : IntervalIntegrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_hasDeriv_right_of_le hab hcont (fun x hx => (hderiv x hx).hasDerivWithinAt) hint /-- Fundamental theorem of calculus-2: If `f : ℝ → E` has a derivative at `f' x` for all `x` in `[a, b]` and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_hasDerivAt (hderiv : ∀ x ∈ uIcc a b, HasDerivAt f (f' x) x) (hint : IntervalIntegrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_hasDeriv_right (HasDerivAt.continuousOn hderiv) (fun _x hx => (hderiv _ (mem_Icc_of_Ioo hx)).hasDerivWithinAt) hint theorem integral_eq_sub_of_hasDerivAt_of_tendsto (hab : a < b) {fa fb} (hderiv : ∀ x ∈ Ioo a b, HasDerivAt f (f' x) x) (hint : IntervalIntegrable f' volume a b) (ha : Tendsto f (𝓝[>] a) (𝓝 fa)) (hb : Tendsto f (𝓝[<] b) (𝓝 fb)) : ∫ y in a..b, f' y = fb - fa := by set F : ℝ → E := update (update f a fa) b fb have Fderiv : ∀ x ∈ Ioo a b, HasDerivAt F (f' x) x := by refine fun x hx => (hderiv x hx).congr_of_eventuallyEq ?_ filter_upwards [Ioo_mem_nhds hx.1 hx.2] with _ hy unfold F rw [update_of_ne hy.2.ne, update_of_ne hy.1.ne'] have hcont : ContinuousOn F (Icc a b) := by rw [continuousOn_update_iff, continuousOn_update_iff, Icc_diff_right, Ico_diff_left] refine ⟨⟨fun z hz => (hderiv z hz).continuousAt.continuousWithinAt, ?_⟩, ?_⟩ · exact fun _ => ha.mono_left (nhdsWithin_mono _ Ioo_subset_Ioi_self) · rintro - refine (hb.congr' ?_).mono_left (nhdsWithin_mono _ Ico_subset_Iio_self) filter_upwards [Ioo_mem_nhdsLT hab] with _ hz using (update_of_ne hz.1.ne' _ _).symm simpa [F, hab.ne, hab.ne'] using integral_eq_sub_of_hasDerivAt_of_le hab.le hcont Fderiv hint /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is differentiable at every `x` in `[a, b]` and its derivative is integrable on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. See also `integral_deriv_of_contDiffOn_Icc` for a similar theorem assuming that `f` is `C^1`. -/ theorem integral_deriv_eq_sub (hderiv : ∀ x ∈ [[a, b]], DifferentiableAt ℝ f x) (hint : IntervalIntegrable (deriv f) volume a b) : ∫ y in a..b, deriv f y = f b - f a := integral_eq_sub_of_hasDerivAt (fun x hx => (hderiv x hx).hasDerivAt) hint theorem integral_deriv_eq_sub' (f) (hderiv : deriv f = f') (hdiff : ∀ x ∈ uIcc a b, DifferentiableAt ℝ f x) (hcont : ContinuousOn f' (uIcc a b)) : ∫ y in a..b, f' y = f b - f a := by rw [← hderiv, integral_deriv_eq_sub hdiff] rw [hderiv] exact hcont.intervalIntegrable /-- A variant of `intervalIntegral.integral_deriv_eq_sub`, the Fundamental theorem of calculus, involving integrating over the unit interval. -/ lemma integral_unitInterval_deriv_eq_sub [RCLike 𝕜] [NormedSpace 𝕜 E] [IsScalarTower ℝ 𝕜 E] {f f' : 𝕜 → E} {z₀ z₁ : 𝕜} (hcont : ContinuousOn (fun t : ℝ ↦ f' (z₀ + t • z₁)) (Set.Icc 0 1)) (hderiv : ∀ t ∈ Set.Icc (0 : ℝ) 1, HasDerivAt f (f' (z₀ + t • z₁)) (z₀ + t • z₁)) : z₁ • ∫ t in (0 : ℝ)..1, f' (z₀ + t • z₁) = f (z₀ + z₁) - f z₀ := by let γ (t : ℝ) : 𝕜 := z₀ + t • z₁ have hint : IntervalIntegrable (z₁ • (f' ∘ γ)) MeasureTheory.volume 0 1 := (ContinuousOn.const_smul hcont z₁).intervalIntegrable_of_Icc zero_le_one have hderiv' (t) (ht : t ∈ Set.uIcc (0 : ℝ) 1) : HasDerivAt (f ∘ γ) (z₁ • (f' ∘ γ) t) t := by refine (hderiv t <| (Set.uIcc_of_le (α := ℝ) zero_le_one).symm ▸ ht).scomp t <| .const_add _ ?_ simp [hasDerivAt_iff_isLittleO, sub_smul] convert (integral_eq_sub_of_hasDerivAt hderiv' hint) using 1 · simp_rw [← integral_smul, Function.comp_apply, γ] · simp only [γ, Function.comp_apply, one_smul, zero_smul, add_zero] /-! ### Automatic integrability for nonnegative derivatives -/ /-- When the right derivative of a function is nonnegative, then it is automatically integrable. -/ theorem integrableOn_deriv_right_of_nonneg (hcont : ContinuousOn g (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, HasDerivWithinAt g (g' x) (Ioi x) x) (g'pos : ∀ x ∈ Ioo a b, 0 ≤ g' x) : IntegrableOn g' (Ioc a b) := by by_cases hab : a < b; swap · simp [Ioc_eq_empty hab] rw [integrableOn_Ioc_iff_integrableOn_Ioo] have meas_g' : AEMeasurable g' (volume.restrict (Ioo a b)) := by apply (aemeasurable_derivWithin_Ioi g _).congr refine (ae_restrict_mem measurableSet_Ioo).mono fun x hx => ?_ exact (hderiv x hx).derivWithin (uniqueDiffWithinAt_Ioi _) suffices H : (∫⁻ x in Ioo a b, ‖g' x‖₊) ≤ ENNReal.ofReal (g b - g a) from ⟨meas_g'.aestronglyMeasurable, H.trans_lt ENNReal.ofReal_lt_top⟩ by_contra! H obtain ⟨f, fle, fint, hf⟩ : ∃ f : SimpleFunc ℝ ℝ≥0, (∀ x, f x ≤ ‖g' x‖₊) ∧ (∫⁻ x : ℝ in Ioo a b, f x) < ∞ ∧ ENNReal.ofReal (g b - g a) < ∫⁻ x : ℝ in Ioo a b, f x := exists_lt_lintegral_simpleFunc_of_lt_lintegral H let F : ℝ → ℝ := (↑) ∘ f have intF : IntegrableOn F (Ioo a b) := by refine ⟨f.measurable.coe_nnreal_real.aestronglyMeasurable, ?_⟩ simpa only [F, hasFiniteIntegral_iff_enorm, comp_apply, NNReal.enorm_eq] using fint have A : ∫⁻ x : ℝ in Ioo a b, f x = ENNReal.ofReal (∫ x in Ioo a b, F x) := lintegral_coe_eq_integral _ intF rw [A] at hf have B : (∫ x : ℝ in Ioo a b, F x) ≤ g b - g a := by rw [← integral_Ioc_eq_integral_Ioo, ← intervalIntegral.integral_of_le hab.le] refine integral_le_sub_of_hasDeriv_right_of_le hab.le hcont hderiv ?_ fun x hx => ?_ · rwa [integrableOn_Icc_iff_integrableOn_Ioo] · convert NNReal.coe_le_coe.2 (fle x) simp only [Real.norm_of_nonneg (g'pos x hx), coe_nnnorm] exact lt_irrefl _ (hf.trans_le (ENNReal.ofReal_le_ofReal B)) /-- When the derivative of a function is nonnegative, then it is automatically integrable, Ioc version. -/ theorem integrableOn_deriv_of_nonneg (hcont : ContinuousOn g (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, HasDerivAt g (g' x) x) (g'pos : ∀ x ∈ Ioo a b, 0 ≤ g' x) : IntegrableOn g' (Ioc a b) := integrableOn_deriv_right_of_nonneg hcont (fun x hx => (hderiv x hx).hasDerivWithinAt) g'pos /-- When the derivative of a function is nonnegative, then it is automatically integrable, interval version. -/ theorem intervalIntegrable_deriv_of_nonneg (hcont : ContinuousOn g (uIcc a b)) (hderiv : ∀ x ∈ Ioo (min a b) (max a b), HasDerivAt g (g' x) x) (hpos : ∀ x ∈ Ioo (min a b) (max a b), 0 ≤ g' x) : IntervalIntegrable g' volume a b := by rcases le_total a b with hab | hab · simp only [uIcc_of_le, min_eq_left, max_eq_right, IntervalIntegrable, hab, Ioc_eq_empty_of_le, integrableOn_empty, and_true] at hcont hderiv hpos ⊢ exact integrableOn_deriv_of_nonneg hcont hderiv hpos · simp only [uIcc_of_ge, min_eq_right, max_eq_left, hab, IntervalIntegrable, Ioc_eq_empty_of_le, integrableOn_empty, true_and] at hcont hderiv hpos ⊢ exact integrableOn_deriv_of_nonneg hcont hderiv hpos end FTC2 end intervalIntegral
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/IntervalIntegral/DerivIntegrable.lean
import Mathlib.Analysis.BoundedVariation import Mathlib.MeasureTheory.Function.AbsolutelyContinuous import Mathlib.MeasureTheory.Integral.IntervalIntegral.Slope /-! # `f'` is interval integrable for certain classes of functions `f` This file proves that: * `MonotoneOn.intervalIntegrable_deriv`: If `f` is monotone on `a..b`, then `f'` is interval integrable on `a..b`. * `MonotoneOn.intervalIntegral_deriv_mem_uIcc`: If `f` is monotone on `a..b`, then the integral of `f'` on `a..b` is in `uIcc 0 (f b - f a)`. * `BoundedVariationOn.intervalIntegrable_deriv`: If `f` has bounded variation on `a..b`, then `f'` is interval integrable on `a..b`. * `AbsolutelyContinuousOnInterval.intervalIntegrable_deriv`: If `f` is absolutely continuous on `a..b`, then `f'` is interval integrable on `a..b`. ## Tags interval integrable, monotone, bounded variation, absolutely continuous -/ open MeasureTheory Set Filter open scoped Topology /-- If `f` is monotone on `[a, b]`, then `f'` is the limit of `G n` a.e. on `[a, b]`, where each `G n` is `AEStronglyMeasurable` and the liminf of the lower Lebesgue integral of `‖G n ·‖ₑ` is at most `f b - f a`. -/ lemma MonotoneOn.exists_tendsto_deriv_liminf_lintegral_enorm_le {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (hf : MonotoneOn f (Icc a b)) : ∃ G : (ℕ → ℝ → ℝ), (∀ᵐ x ∂volume.restrict (Icc a b), Filter.Tendsto (fun (n : ℕ) ↦ G n x) Filter.atTop (𝓝 (deriv f x))) ∧ (∀ (n : ℕ), AEStronglyMeasurable (G n) (volume.restrict (Icc a b))) ∧ liminf (fun (n : ℕ) ↦ ∫⁻ (x : ℝ) in Icc a b, ‖G n x‖ₑ) atTop ≤ ENNReal.ofReal (f b - f a) := by /- Proof Sketch: Extend `f` on `[a, b]` to a function `g` on `ℝ` by defining `g x = f a` for `x < a` and `g x = f b` for `x > b`. `g` is globally monotone and `g'` agrees with `f'` on `(a, b)`. We let `G c x = slope g x (x + c)` for `c > 0`. Then `G c x` is nonnegative, `∫⁻ (x : ℝ) in Icc a b, ‖G c x‖ₑ ≤ f b - f a`, and `G c x` tends to `f' x` as `c` tends to `0` from the right. The function `fun n x ↦ G (n : ℝ)⁻¹ x` is a witness to the conclusion of the lemma. -/ let g (x : ℝ) : ℝ := f (max a (min x b)) have hg : Monotone g := monotoneOn_univ.mp <| hf.comp (by grind [MonotoneOn]) (by grind [MapsTo]) have hfg : EqOn f g (Ioo a b) := by grind [EqOn] replace hfg := hfg.deriv isOpen_Ioo have h₁ : ∀ᵐ x, x ≠ a := by simp [ae_iff, measure_singleton] have h₂ : ∀ᵐ x, x ≠ b := by simp [ae_iff, measure_singleton] let G (c x : ℝ) := slope g x (x + c) have G_integrable (n : ℕ) : Integrable (G (↑n)⁻¹) (volume.restrict (Icc a b)) := by have := hg.monotoneOn (Icc a (b + (n : ℝ)⁻¹)) |>.intervalIntegrable_slope hab (by simp) exact intervalIntegrable_iff_integrableOn_Icc_of_le hab |>.mp this refine ⟨fun n x ↦ G (n : ℝ)⁻¹ x, ?_, fun n ↦ G_integrable n |>.aestronglyMeasurable, ?_⟩ · rw [MeasureTheory.ae_restrict_iff' (by measurability)] filter_upwards [hg.ae_differentiableAt, h₁, h₂] with x hx₁ hx₂ hx₃ hx₄ rw [hfg (by grind [Icc_diff_both])] exact hx₁.hasDerivAt.tendsto_slope.comp <| tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within _ (by convert tendsto_const_nhds.add (tendsto_inv_atTop_nhds_zero_nat (𝕜 := ℝ)); simp) (by simp [eventually_ne_atTop 0]) · calc _ = liminf (fun (n : ℕ) ↦ ENNReal.ofReal (∫ (x : ℝ) in Icc a b, (G (n : ℝ)⁻¹) x)) atTop := by apply Filter.liminf_congr filter_upwards with n rw [← MeasureTheory.ofReal_integral_norm_eq_lintegral_enorm (G_integrable n)] congr with y exact abs_eq_self.mpr (hg.monotoneOn univ |>.slope_nonneg trivial trivial) _ ≤ ENNReal.ofReal (g b - g a) := by refine Filter.liminf_le_of_frequently_le' (Filter.Frequently.of_forall fun n ↦ ENNReal.ofReal_le_ofReal ?_) rw [integral_Icc_eq_integral_Ioc, ← intervalIntegral.integral_of_le hab] convert hg.monotoneOn (Icc a (b + (n : ℝ)⁻¹)) |>.intervalIntegral_slope_le hab (by simp) using 2 simp [g] _ = ENNReal.ofReal (f b - f a) := by grind /-- If `f` is monotone on `a..b`, then `f'` is interval integrable on `a..b`. -/ theorem MonotoneOn.intervalIntegrable_deriv {f : ℝ → ℝ} {a b : ℝ} (hf : MonotoneOn f (uIcc a b)) : IntervalIntegrable (deriv f) volume a b := by wlog hab : a ≤ b generalizing a b with h · exact h (uIcc_comm a b ▸ hf) (by linarith) |>.symm rw [uIcc_of_le hab] at hf obtain ⟨G, hGf, hG, hG'⟩ := hf.exists_tendsto_deriv_liminf_lintegral_enorm_le hab have hG'₀ : liminf (fun (n : ℕ) ↦ ∫⁻ (x : ℝ) in Icc a b, ‖G n x‖ₑ) atTop ≠ ⊤ := lt_of_le_of_lt hG' ENNReal.ofReal_lt_top |>.ne_top have integrable_f_deriv := integrable_of_tendsto hGf hG hG'₀ exact (intervalIntegrable_iff_integrableOn_Icc_of_le hab).mpr integrable_f_deriv /-- If `f` is monotone on `a..b`, then `f'` is interval integrable on `a..b` and the integral of `f'` on `a..b` is in between `0` and `f b - f a`. -/ theorem MonotoneOn.intervalIntegral_deriv_mem_uIcc {f : ℝ → ℝ} {a b : ℝ} (hf : MonotoneOn f (uIcc a b)) : ∫ x in a..b, deriv f x ∈ uIcc 0 (f b - f a) := by wlog hab : a ≤ b generalizing a b with h · specialize h (uIcc_comm a b ▸ hf) (by linarith) have : f b ≤ f a := hf (by simp) (by simp) (by linarith) rw [intervalIntegral.integral_symm, uIcc_of_ge (by linarith)] refine neg_mem_Icc_iff.mpr ?_ simp only [neg_zero, neg_sub] rwa [uIcc_of_le (by linarith)] at h rw [uIcc_of_le hab] at hf obtain ⟨G, hGf, hG, hG'⟩ := hf.exists_tendsto_deriv_liminf_lintegral_enorm_le hab have h₁ : ∀ᵐ x, x ≠ a := by simp [ae_iff, measure_singleton] have h₂ : ∀ᵐ x, x ≠ b := by simp [ae_iff, measure_singleton] have hG'₀ : liminf (fun (n : ℕ) ↦ ∫⁻ (x : ℝ) in Icc a b, ‖G n x‖ₑ) atTop ≠ ⊤ := lt_of_le_of_lt hG' ENNReal.ofReal_lt_top |>.ne_top have integrable_f_deriv := integrable_of_tendsto hGf hG hG'₀ rw [MeasureTheory.ae_restrict_iff' (by simp)] at hGf rw [← uIcc_of_le hab] at hGf hG hG' have : f a ≤ f b := hf (by simp [hab]) (by simp [hab]) hab rw [uIcc_of_le (by linarith), mem_Icc] have f_deriv_nonneg {x : ℝ} (hx : x ∈ Ioo a b): 0 ≤ deriv f x := by rw [← derivWithin_of_mem_nhds (Icc_mem_nhds (a := a) (b := b) (by grind) (by grind))] exact hf.derivWithin_nonneg constructor · apply intervalIntegral.integral_nonneg_of_ae_restrict hab rw [Filter.EventuallyLE, MeasureTheory.ae_restrict_iff' (by simp)] filter_upwards [h₁, h₂] with x _ _ _ exact f_deriv_nonneg (by grind [Icc_diff_both]) · have ebound := lintegral_enorm_le_liminf_of_tendsto ((MeasureTheory.ae_restrict_iff' (by measurability) |>.mpr hGf)) (fun n ↦ (hG n).aemeasurable.enorm) grw [hG'] at ebound rw [uIcc_of_le hab, ← MeasureTheory.ofReal_integral_norm_eq_lintegral_enorm integrable_f_deriv, ENNReal.ofReal_le_ofReal_iff (by linarith), integral_Icc_eq_integral_Ioc, ← intervalIntegral.integral_of_le hab] at ebound convert ebound using 1 refine intervalIntegral.integral_congr_ae ?_ rw [uIoc_of_le hab] filter_upwards [h₂] with x _ _ exact abs_eq_self.mpr (f_deriv_nonneg (by rw [← Ioc_diff_right]; grind)) |>.symm /-- If `f` has bounded variation on `uIcc a b`, then `f'` is interval integrable on `a..b`. -/ theorem BoundedVariationOn.intervalIntegrable_deriv {f : ℝ → ℝ} {a b : ℝ} (hf : BoundedVariationOn f (uIcc a b)) : IntervalIntegrable (deriv f) volume a b := by obtain ⟨p, q, hp, hq, rfl⟩ := hf.locallyBoundedVariationOn.exists_monotoneOn_sub_monotoneOn have h₂ : ∀ᵐ x, x ≠ max a b := by simp [ae_iff, measure_singleton] apply (hp.intervalIntegrable_deriv.sub hq.intervalIntegrable_deriv).congr_ae rw [Filter.EventuallyEq, MeasureTheory.ae_restrict_iff' (by simp [uIoc])] filter_upwards [hp.ae_differentiableWithinAt_of_mem, hq.ae_differentiableWithinAt_of_mem, h₂] with x hx₁ hx₂ hx₃ hx₄ have hx₅ : x ∈ uIcc a b := Ioc_subset_Icc_self hx₄ rw [uIoc, mem_Ioc] at hx₄ have hx₆ : uIcc a b ∈ 𝓝 x := Icc_mem_nhds hx₄.left (lt_of_le_of_ne hx₄.right hx₃) replace hx₁ := (hx₁ hx₅).differentiableAt hx₆ |>.hasDerivAt replace hx₂ := (hx₂ hx₅).differentiableAt hx₆ |>.hasDerivAt exact (hx₁.sub hx₂).deriv.symm /-- If `f` is absolutely continuous on `uIcc a b`, then `f'` is interval integrable on `a..b`. -/ theorem AbsolutelyContinuousOnInterval.intervalIntegrable_deriv {f : ℝ → ℝ} {a b : ℝ} (hf : AbsolutelyContinuousOnInterval f a b) : IntervalIntegrable (deriv f) volume a b := hf.boundedVariationOn.intervalIntegrable_deriv
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/IntervalIntegral/Periodic.lean
import Mathlib.MeasureTheory.Measure.Lebesgue.EqHaar import Mathlib.MeasureTheory.Measure.Haar.Quotient import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic import Mathlib.Topology.Algebra.Order.Floor import Mathlib.Topology.Instances.AddCircle.Real /-! # Integrals of periodic functions In this file we prove that the half-open interval `Ioc t (t + T)` in `ℝ` is a fundamental domain of the action of the subgroup `ℤ ∙ T` on `ℝ`. A consequence is `AddCircle.measurePreserving_mk`: the covering map from `ℝ` to the "additive circle" `ℝ ⧸ (ℤ ∙ T)` is measure-preserving, with respect to the restriction of Lebesgue measure to `Ioc t (t + T)` (upstairs) and with respect to Haar measure (downstairs). Another consequence (`Function.Periodic.intervalIntegral_add_eq` and related declarations) is that `∫ x in t..t + T, f x = ∫ x in s..s + T, f x` for any (not necessarily measurable) function with period `T`. -/ open Set Function MeasureTheory MeasureTheory.Measure TopologicalSpace AddSubgroup intervalIntegral open scoped MeasureTheory NNReal ENNReal /-! ## Measures and integrability on ℝ and on the circle -/ @[measurability] protected theorem AddCircle.measurable_mk' {a : ℝ} : Measurable (β := AddCircle a) ((↑) : ℝ → AddCircle a) := Continuous.measurable <| AddCircle.continuous_mk' a theorem isAddFundamentalDomain_Ioc {T : ℝ} (hT : 0 < T) (t : ℝ) (μ : Measure ℝ := by volume_tac) : IsAddFundamentalDomain (AddSubgroup.zmultiples T) (Ioc t (t + T)) μ := by refine IsAddFundamentalDomain.mk' nullMeasurableSet_Ioc fun x => ?_ have : Bijective (codRestrict (fun n : ℤ => n • T) (AddSubgroup.zmultiples T) _) := (Equiv.ofInjective (fun n : ℤ => n • T) (zsmul_left_strictMono hT).injective).bijective refine this.existsUnique_iff.2 ?_ simpa only [add_comm x] using existsUnique_add_zsmul_mem_Ioc hT x t theorem isAddFundamentalDomain_Ioc' {T : ℝ} (hT : 0 < T) (t : ℝ) (μ : Measure ℝ := by volume_tac) : IsAddFundamentalDomain (AddSubgroup.op <| .zmultiples T) (Ioc t (t + T)) μ := by refine IsAddFundamentalDomain.mk' nullMeasurableSet_Ioc fun x => ?_ have : Bijective (codRestrict (fun n : ℤ => n • T) (AddSubgroup.zmultiples T) _) := (Equiv.ofInjective (fun n : ℤ => n • T) (zsmul_left_strictMono hT).injective).bijective refine (AddSubgroup.equivOp _).bijective.comp this |>.existsUnique_iff.2 ?_ simpa using existsUnique_add_zsmul_mem_Ioc hT x t namespace AddCircle variable (T : ℝ) [hT : Fact (0 < T)] /-- Equip the "additive circle" `ℝ ⧸ (ℤ ∙ T)` with, as a standard measure, the Haar measure of total mass `T` -/ noncomputable instance measureSpace : MeasureSpace (AddCircle T) := { QuotientAddGroup.measurableSpace _ with volume := ENNReal.ofReal T • addHaarMeasure ⊤ } @[simp] protected theorem measure_univ : volume (Set.univ : Set (AddCircle T)) = ENNReal.ofReal T := by dsimp [volume] rw [← PositiveCompacts.coe_top] simp [addHaarMeasure_self (G := AddCircle T), -PositiveCompacts.coe_top] instance : IsAddHaarMeasure (volume : Measure (AddCircle T)) := IsAddHaarMeasure.smul _ (by simp [hT.out]) ENNReal.ofReal_ne_top instance isFiniteMeasure : IsFiniteMeasure (volume : Measure (AddCircle T)) where measure_univ_lt_top := by simp instance : HasAddFundamentalDomain (AddSubgroup.op <| .zmultiples T) ℝ where ExistsIsAddFundamentalDomain := ⟨Ioc 0 (0 + T), isAddFundamentalDomain_Ioc' Fact.out 0⟩ instance : AddQuotientMeasureEqMeasurePreimage volume (volume : Measure (AddCircle T)) := by apply MeasureTheory.leftInvariantIsAddQuotientMeasureEqMeasurePreimage simp [(isAddFundamentalDomain_Ioc' hT.out 0).covolume_eq_volume, AddCircle.measure_univ] /-- The covering map from `ℝ` to the "additive circle" `ℝ ⧸ (ℤ ∙ T)` is measure-preserving, considered with respect to the standard measure (defined to be the Haar measure of total mass `T`) on the additive circle, and with respect to the restriction of Lebesgue measure on `ℝ` to an interval (t, t + T]. -/ protected theorem measurePreserving_mk (t : ℝ) : MeasurePreserving (β := AddCircle T) ((↑) : ℝ → AddCircle T) (volume.restrict (Ioc t (t + T))) := measurePreserving_quotientAddGroup_mk_of_AddQuotientMeasureEqMeasurePreimage volume (𝓕 := Ioc t (t+T)) (isAddFundamentalDomain_Ioc' hT.out _) _ lemma add_projection_respects_measure (t : ℝ) {U : Set (AddCircle T)} (meas_U : MeasurableSet U) : volume U = volume (QuotientAddGroup.mk ⁻¹' U ∩ (Ioc t (t + T))) := (isAddFundamentalDomain_Ioc' hT.out _).addProjection_respects_measure_apply (volume : Measure (AddCircle T)) meas_U theorem volume_closedBall {x : AddCircle T} (ε : ℝ) : volume (Metric.closedBall x ε) = ENNReal.ofReal (min T (2 * ε)) := by have hT' : |T| = T := abs_eq_self.mpr hT.out.le let I := Ioc (-(T / 2)) (T / 2) have h₁ : ε < T / 2 → Metric.closedBall (0 : ℝ) ε ∩ I = Metric.closedBall (0 : ℝ) ε := by intro hε rw [inter_eq_left, Real.closedBall_eq_Icc, zero_sub, zero_add] rintro y ⟨hy₁, hy₂⟩; constructor <;> linarith have h₂ : (↑) ⁻¹' Metric.closedBall (0 : AddCircle T) ε ∩ I = if ε < T / 2 then Metric.closedBall (0 : ℝ) ε else I := by conv_rhs => rw [← if_ctx_congr (Iff.rfl : ε < T / 2 ↔ ε < T / 2) h₁ fun _ => rfl, ← hT'] apply coe_real_preimage_closedBall_inter_eq simpa only [hT', Real.closedBall_eq_Icc, zero_add, zero_sub] using Ioc_subset_Icc_self rw [addHaar_closedBall_center, add_projection_respects_measure T (-(T/2)) measurableSet_closedBall, (by linarith : -(T / 2) + T = T / 2), h₂] by_cases hε : ε < T / 2 · simp [hε, min_eq_right (by linarith : 2 * ε ≤ T)] · simp [I, hε, min_eq_left (by linarith : T ≤ 2 * ε)] instance : IsUnifLocDoublingMeasure (volume : Measure (AddCircle T)) := by refine ⟨⟨Real.toNNReal 2, Filter.Eventually.of_forall fun ε x => ?_⟩⟩ simp only [volume_closedBall] erw [← ENNReal.ofReal_mul zero_le_two] apply ENNReal.ofReal_le_ofReal rw [mul_min_of_nonneg _ _ (zero_le_two : (0 : ℝ) ≤ 2)] exact min_le_min (by linarith [hT.out]) (le_refl _) /-- The isomorphism `AddCircle T ≃ Ioc a (a + T)` whose inverse is the natural quotient map, as an equivalence of measurable spaces. -/ noncomputable def measurableEquivIoc (a : ℝ) : AddCircle T ≃ᵐ Ioc a (a + T) where toEquiv := equivIoc T a measurable_toFun := measurable_of_measurable_on_compl_singleton _ (continuousOn_iff_continuous_restrict.mp <| continuousOn_of_forall_continuousAt fun _x hx => continuousAt_equivIoc T a hx).measurable measurable_invFun := AddCircle.measurable_mk'.comp measurable_subtype_coe /-- The isomorphism `AddCircle T ≃ Ico a (a + T)` whose inverse is the natural quotient map, as an equivalence of measurable spaces. -/ noncomputable def measurableEquivIco (a : ℝ) : AddCircle T ≃ᵐ Ico a (a + T) where toEquiv := equivIco T a measurable_toFun := measurable_of_measurable_on_compl_singleton _ (continuousOn_iff_continuous_restrict.mp <| continuousOn_of_forall_continuousAt fun _x hx => continuousAt_equivIco T a hx).measurable measurable_invFun := AddCircle.measurable_mk'.comp measurable_subtype_coe /-- The equivalence `equivIoc` is measure preserving with respect to the natural volume measures. -/ lemma measurePreserving_equivIoc {a : ℝ} : MeasurePreserving (equivIoc T a) volume (Measure.comap Subtype.val volume) := by have h := (measurableEquivIoc T a).measurable refine ⟨h, ?_⟩ ext s hs rw [comap_apply _ Subtype.val_injective (fun _ ↦ measurableSet_Ioc.subtype_image) _ hs, map_apply (by measurability) hs, add_projection_respects_measure T a (by exact h hs)] congr! ext x simp only [mem_inter_iff, mem_preimage, mem_image, Subtype.exists, exists_and_right, exists_eq_right] rw [and_comm, ← exists_prop] congr! with hx rw [equivIoc_coe_eq hx] attribute [local instance] Subtype.measureSpace in /-- The lower integral of a function over `AddCircle T` is equal to the lower integral over an interval (t, t + T] in `ℝ` of its lift to `ℝ`. -/ protected theorem lintegral_preimage (t : ℝ) (f : AddCircle T → ℝ≥0∞) : (∫⁻ a in Ioc t (t + T), f a) = ∫⁻ b : AddCircle T, f b := by have m : MeasurableSet (Ioc t (t + T)) := measurableSet_Ioc have := lintegral_map_equiv (μ := volume) f (measurableEquivIoc T t).symm simp only [measurableEquivIoc, equivIoc, QuotientAddGroup.equivIocMod, MeasurableEquiv.symm_mk, MeasurableEquiv.coe_mk, Equiv.coe_fn_symm_mk] at this rw [← (AddCircle.measurePreserving_mk T t).map_eq] convert this.symm using 1 · rw [← map_comap_subtype_coe m _] exact MeasurableEmbedding.lintegral_map (MeasurableEmbedding.subtype_coe m) _ · congr 1 have : ((↑) : Ioc t (t + T) → AddCircle T) = ((↑) : ℝ → AddCircle T) ∘ ((↑) : _ → ℝ) := by ext1 x; rfl simp_rw [this] rw [← map_map AddCircle.measurable_mk' measurable_subtype_coe, ← map_comap_subtype_coe m] rfl variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] attribute [local instance] Subtype.measureSpace in /-- The integral of an almost-everywhere strongly measurable function over `AddCircle T` is equal to the integral over an interval (t, t + T] in `ℝ` of its lift to `ℝ`. -/ protected theorem integral_preimage (t : ℝ) (f : AddCircle T → E) : (∫ a in Ioc t (t + T), f a) = ∫ b : AddCircle T, f b := by have m : MeasurableSet (Ioc t (t + T)) := measurableSet_Ioc have := integral_map_equiv (μ := volume) (measurableEquivIoc T t).symm f simp only [measurableEquivIoc, equivIoc, QuotientAddGroup.equivIocMod, MeasurableEquiv.symm_mk, MeasurableEquiv.coe_mk, Equiv.coe_fn_symm_mk] at this rw [← (AddCircle.measurePreserving_mk T t).map_eq, ← integral_subtype m, ← this] have : ((↑) : Ioc t (t + T) → AddCircle T) = ((↑) : ℝ → AddCircle T) ∘ ((↑) : _ → ℝ) := by ext1 x; rfl simp_rw [this] rw [← map_map AddCircle.measurable_mk' measurable_subtype_coe, ← map_comap_subtype_coe m] rfl /-- The integral of an almost-everywhere strongly measurable function over `AddCircle T` is equal to the integral over an interval (t, t + T] in `ℝ` of its lift to `ℝ`. -/ protected theorem intervalIntegral_preimage (t : ℝ) (f : AddCircle T → E) : ∫ a in t..t + T, f a = ∫ b : AddCircle T, f b := by rw [integral_of_le, AddCircle.integral_preimage T t f] linarith [hT.out] /-- The integral of a function lifted to AddCircle from an interval `(t, t + T]` to `AddCircle T` is equal the the intervalIntegral over the interval. -/ lemma integral_liftIoc_eq_intervalIntegral {t : ℝ} {f : ℝ → E} : ∫ a, liftIoc T t f a = ∫ a in t..t + T, f a := by rw [← AddCircle.intervalIntegral_preimage T t] apply intervalIntegral.integral_congr_ae refine .of_forall fun x hx ↦ ?_ rw [uIoc_of_le (by linarith [hT.out])] at hx rw [liftIoc_coe_apply hx] end AddCircle /-- If a function satisfies `MemLp` on the interval `(t, t + T]`, then its lift to the AddCircle also satisfies `MemLp` with respect to the Haar measure. -/ lemma MeasureTheory.MemLp.memLp_liftIoc {T : ℝ} [hT : Fact (0 < T)] {t : ℝ} {f : ℝ → ℂ} {p : ℝ≥0∞} (hLp : MemLp f p (volume.restrict (Ioc t (t + T)))) : MemLp (AddCircle.liftIoc T t f) p := by simp only [AddCircle.liftIoc, Set.restrict_def, Function.comp_def] apply hLp.comp_measurePreserving refine .comp (measurePreserving_subtype_coe measurableSet_Ioc) ?_ exact AddCircle.measurePreserving_equivIoc T namespace UnitAddCircle attribute [local instance] Real.fact_zero_lt_one protected theorem measure_univ : volume (Set.univ : Set UnitAddCircle) = 1 := by simp /-- The covering map from `ℝ` to the "unit additive circle" `ℝ ⧸ ℤ` is measure-preserving, considered with respect to the standard measure (defined to be the Haar measure of total mass 1) on the additive circle, and with respect to the restriction of Lebesgue measure on `ℝ` to an interval (t, t + 1]. -/ protected theorem measurePreserving_mk (t : ℝ) : MeasurePreserving (β := UnitAddCircle) ((↑) : ℝ → UnitAddCircle) (volume.restrict (Ioc t (t + 1))) := AddCircle.measurePreserving_mk 1 t /-- The integral of a measurable function over `UnitAddCircle` is equal to the integral over an interval (t, t + 1] in `ℝ` of its lift to `ℝ`. -/ protected theorem lintegral_preimage (t : ℝ) (f : UnitAddCircle → ℝ≥0∞) : (∫⁻ a in Ioc t (t + 1), f a) = ∫⁻ b : UnitAddCircle, f b := AddCircle.lintegral_preimage 1 t f variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] /-- The integral of an almost-everywhere strongly measurable function over `UnitAddCircle` is equal to the integral over an interval (t, t + 1] in `ℝ` of its lift to `ℝ`. -/ protected theorem integral_preimage (t : ℝ) (f : UnitAddCircle → E) : (∫ a in Ioc t (t + 1), f a) = ∫ b : UnitAddCircle, f b := AddCircle.integral_preimage 1 t f /-- The integral of an almost-everywhere strongly measurable function over `UnitAddCircle` is equal to the integral over an interval (t, t + 1] in `ℝ` of its lift to `ℝ`. -/ protected theorem intervalIntegral_preimage (t : ℝ) (f : UnitAddCircle → E) : ∫ a in t..t + 1, f a = ∫ b : UnitAddCircle, f b := AddCircle.intervalIntegral_preimage 1 t f end UnitAddCircle /-! ## Interval integrability of periodic functions -/ namespace Function namespace Periodic variable {E : Type*} [NormedAddCommGroup E] variable {f : ℝ → E} {T : ℝ} /-- A periodic function is interval integrable over every interval if it is interval integrable over one period. -/ theorem intervalIntegrable {t : ℝ} (h₁f : Function.Periodic f T) (hT : 0 < T) (hT' : ‖f (min t (t + T))‖ₑ ≠ ∞ := by finiteness) (h₂f : IntervalIntegrable f MeasureTheory.volume t (t + T)) (a₁ a₂ : ℝ) : IntervalIntegrable f MeasureTheory.volume a₁ a₂ := by -- Replace [a₁, a₂] by [t - n₁ * T, t + n₂ * T], where n₁ and n₂ are natural numbers obtain ⟨n₁, hn₁⟩ := exists_nat_ge ((t - min a₁ a₂) / T) obtain ⟨n₂, hn₂⟩ := exists_nat_ge ((max a₁ a₂ - t) / T) have : Set.uIcc a₁ a₂ ⊆ Set.uIcc (t - n₁ * T) (t + n₂ * T) := by rw [Set.uIcc_subset_uIcc_iff_le] constructor · calc min (t - n₁ * T) (t + n₂ * T) _ ≤ (t - n₁ * T) := by apply min_le_left _ ≤ min a₁ a₂ := by linarith [(div_le_iff₀ hT).1 hn₁] · calc max a₁ a₂ _ ≤ t + n₂ * T := by linarith [(div_le_iff₀ hT).1 hn₂] _ ≤ max (t - n₁ * T) (t + n₂ * T) := by apply le_max_right apply IntervalIntegrable.mono_set _ this -- Suffices to show integrability over shifted periods let a : ℕ → ℝ := fun n ↦ t + (n - n₁) * T rw [(by ring : t - n₁ * T = a 0), (by simp [a] : t + n₂ * T = a (n₁ + n₂))] apply IntervalIntegrable.trans_iterate -- Show integrability over a shifted period intro k hk convert (IntervalIntegrable.comp_sub_right h₂f ((k - n₁) * T) hT') using 1 · funext x simpa using (h₁f.sub_int_mul_eq (k - n₁)).symm · simp [a, Nat.cast_add] ring /-- Special case of Function.Periodic.intervalIntegrable: A periodic function is interval integrable over every interval if it is interval integrable over the period starting from zero. -/ theorem intervalIntegrable₀ (h₁f : Function.Periodic f T) (hT : 0 < T) (h₂f : IntervalIntegrable f MeasureTheory.volume 0 T) (a₁ a₂ : ℝ) : IntervalIntegrable f MeasureTheory.volume a₁ a₂ := by apply h₁f.intervalIntegrable hT (t := 0) simpa /-! ## Interval integrals of periodic functions -/ variable [NormedSpace ℝ E] /-- An auxiliary lemma for a more general `Function.Periodic.intervalIntegral_add_eq`. -/ theorem intervalIntegral_add_eq_of_pos (hf : Periodic f T) (hT : 0 < T) (t s : ℝ) : ∫ x in t..t + T, f x = ∫ x in s..s + T, f x := by simp only [integral_of_le, hT.le, le_add_iff_nonneg_right] haveI : VAddInvariantMeasure (AddSubgroup.zmultiples T) ℝ volume := ⟨fun c s _ => measure_preimage_add _ _ _⟩ apply IsAddFundamentalDomain.setIntegral_eq (G := AddSubgroup.zmultiples T) exacts [isAddFundamentalDomain_Ioc hT t, isAddFundamentalDomain_Ioc hT s, hf.map_vadd_zmultiples] /-- If `f` is a periodic function with period `T`, then its integral over `[t, t + T]` does not depend on `t`. -/ theorem intervalIntegral_add_eq (hf : Periodic f T) (t s : ℝ) : ∫ x in t..t + T, f x = ∫ x in s..s + T, f x := by rcases lt_trichotomy (0 : ℝ) T with (hT | rfl | hT) · exact hf.intervalIntegral_add_eq_of_pos hT t s · simp · rw [← neg_inj, ← integral_symm, ← integral_symm] simpa only [← sub_eq_add_neg, add_sub_cancel_right] using hf.neg.intervalIntegral_add_eq_of_pos (neg_pos.2 hT) (t + T) (s + T) /-- If `f` is an integrable periodic function with period `T`, then its integral over `[t, s + T]` is the sum of its integrals over the intervals `[t, s]` and `[t, t + T]`. -/ theorem intervalIntegral_add_eq_add (hf : Periodic f T) (t s : ℝ) (h_int : ∀ t₁ t₂, IntervalIntegrable f MeasureSpace.volume t₁ t₂) : ∫ x in t..s + T, f x = (∫ x in t..s, f x) + ∫ x in t..t + T, f x := by rw [hf.intervalIntegral_add_eq t s, integral_add_adjacent_intervals (h_int t s) (h_int s _)] /-- If `f` is an integrable periodic function with period `T`, and `n` is an integer, then its integral over `[t, t + n • T]` is `n` times its integral over `[t, t + T]`. -/ theorem intervalIntegral_add_zsmul_eq (hf : Periodic f T) (n : ℤ) (t : ℝ) (h_int : ∀ t₁ t₂, IntervalIntegrable f MeasureSpace.volume t₁ t₂) : ∫ x in t..t + n • T, f x = n • ∫ x in t..t + T, f x := by -- Reduce to the case `b = 0` suffices (∫ x in 0..(n • T), f x) = n • ∫ x in 0..T, f x by simp only [hf.intervalIntegral_add_eq t 0, (hf.zsmul n).intervalIntegral_add_eq t 0, zero_add, this] -- First prove it for natural numbers have : ∀ m : ℕ, (∫ x in 0..m • T, f x) = m • ∫ x in 0..T, f x := fun m ↦ by induction m with | zero => simp | succ m ih => simp only [succ_nsmul, hf.intervalIntegral_add_eq_add 0 (m • T) h_int, ih, zero_add] -- Then prove it for all integers rcases n with n | n · simp [← this n] · conv_rhs => rw [negSucc_zsmul] have h₀ : Int.negSucc n • T + (n + 1) • T = 0 := by simp; linarith rw [integral_symm, ← (hf.nsmul (n + 1)).funext, neg_inj] simp_rw [integral_comp_add_right, h₀, zero_add, this (n + 1), add_comm T, hf.intervalIntegral_add_eq ((n + 1) • T) 0, zero_add] section RealValued open Filter variable {g : ℝ → ℝ} variable (hg : Periodic g T) include hg /-- If `g : ℝ → ℝ` is periodic with period `T > 0`, then for any `t : ℝ`, the function `t ↦ ∫ x in 0..t, g x` is bounded below by `t ↦ X + ⌊t/T⌋ • Y` for appropriate constants `X` and `Y`. -/ theorem sInf_add_zsmul_le_integral_of_pos (h_int : IntervalIntegrable g MeasureSpace.volume 0 T) (hT : 0 < T) (t : ℝ) : (sInf ((fun t => ∫ x in 0..t, g x) '' Icc 0 T) + ⌊t / T⌋ • ∫ x in 0..T, g x) ≤ ∫ x in 0..t, g x := by let h'_int := hg.intervalIntegrable₀ hT h_int let ε := Int.fract (t / T) * T conv_rhs => rw [← Int.fract_div_mul_self_add_zsmul_eq T t (by linarith), ← integral_add_adjacent_intervals (h'_int 0 ε) (h'_int _ _)] rw [hg.intervalIntegral_add_zsmul_eq ⌊t / T⌋ ε (hg.intervalIntegrable₀ hT h_int), hg.intervalIntegral_add_eq ε 0, zero_add, add_le_add_iff_right] exact (continuous_primitive h'_int 0).continuousOn.sInf_image_Icc_le <| mem_Icc_of_Ico (Int.fract_div_mul_self_mem_Ico T t hT) /-- If `g : ℝ → ℝ` is periodic with period `T > 0`, then for any `t : ℝ`, the function `t ↦ ∫ x in 0..t, g x` is bounded above by `t ↦ X + ⌊t/T⌋ • Y` for appropriate constants `X` and `Y`. -/ theorem integral_le_sSup_add_zsmul_of_pos (h_int : IntervalIntegrable g MeasureSpace.volume 0 T) (hT : 0 < T) (t : ℝ) : (∫ x in 0..t, g x) ≤ sSup ((fun t => ∫ x in 0..t, g x) '' Icc 0 T) + ⌊t / T⌋ • ∫ x in 0..T, g x := by let h'_int := hg.intervalIntegrable₀ hT h_int let ε := Int.fract (t / T) * T conv_lhs => rw [← Int.fract_div_mul_self_add_zsmul_eq T t (by linarith), ← integral_add_adjacent_intervals (h'_int 0 ε) (h'_int _ _)] rw [hg.intervalIntegral_add_zsmul_eq ⌊t / T⌋ ε h'_int, hg.intervalIntegral_add_eq ε 0, zero_add, add_le_add_iff_right] exact (continuous_primitive h'_int 0).continuousOn.le_sSup_image_Icc (mem_Icc_of_Ico (Int.fract_div_mul_self_mem_Ico T t hT)) /-- If `g : ℝ → ℝ` is periodic with period `T > 0` and `0 < ∫ x in 0..T, g x`, then `t ↦ ∫ x in 0..t, g x` tends to `∞` as `t` tends to `∞`. -/ theorem tendsto_atTop_intervalIntegral_of_pos (h₀ : 0 < ∫ x in 0..T, g x) (hT : 0 < T) : Tendsto (fun t => ∫ x in 0..t, g x) atTop atTop := by have h_int := intervalIntegrable_of_integral_ne_zero h₀.ne' apply tendsto_atTop_mono (hg.sInf_add_zsmul_le_integral_of_pos h_int hT) apply atTop.tendsto_atTop_add_const_left (sInf <| (fun t => ∫ x in 0..t, g x) '' Icc 0 T) apply Tendsto.atTop_zsmul_const h₀ exact tendsto_floor_atTop.comp (tendsto_id.atTop_mul_const (inv_pos.mpr hT)) /-- If `g : ℝ → ℝ` is periodic with period `T > 0` and `0 < ∫ x in 0..T, g x`, then `t ↦ ∫ x in 0..t, g x` tends to `-∞` as `t` tends to `-∞`. -/ theorem tendsto_atBot_intervalIntegral_of_pos (h₀ : 0 < ∫ x in 0..T, g x) (hT : 0 < T) : Tendsto (fun t => ∫ x in 0..t, g x) atBot atBot := by have h_int := intervalIntegrable_of_integral_ne_zero h₀.ne' apply tendsto_atBot_mono (hg.integral_le_sSup_add_zsmul_of_pos h_int hT) apply atBot.tendsto_atBot_add_const_left (sSup <| (fun t => ∫ x in 0..t, g x) '' Icc 0 T) apply Tendsto.atBot_zsmul_const h₀ exact tendsto_floor_atBot.comp (tendsto_id.atBot_mul_const (inv_pos.mpr hT)) /-- If `g : ℝ → ℝ` is periodic with period `T > 0` and `∀ x, 0 < g x`, then `t ↦ ∫ x in 0..t, g x` tends to `∞` as `t` tends to `∞`. -/ theorem tendsto_atTop_intervalIntegral_of_pos' (h_int : IntervalIntegrable g MeasureSpace.volume 0 T) (h₀ : ∀ x, 0 < g x) (hT : 0 < T) : Tendsto (fun t => ∫ x in 0..t, g x) atTop atTop := hg.tendsto_atTop_intervalIntegral_of_pos (intervalIntegral_pos_of_pos h_int h₀ hT) hT /-- If `g : ℝ → ℝ` is periodic with period `T > 0` and `∀ x, 0 < g x`, then `t ↦ ∫ x in 0..t, g x` tends to `-∞` as `t` tends to `-∞`. -/ theorem tendsto_atBot_intervalIntegral_of_pos' (h_int : IntervalIntegrable g MeasureSpace.volume 0 T) (h₀ : ∀ x, 0 < g x) (hT : 0 < T) : Tendsto (fun t => ∫ x in 0..t, g x) atBot atBot := by exact hg.tendsto_atBot_intervalIntegral_of_pos (intervalIntegral_pos_of_pos h_int h₀ hT) hT end RealValued end Periodic end Function
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/IntervalIntegral/TrapezoidalRule.lean
import Mathlib.Analysis.SpecialFunctions.Integrals.Basic import Mathlib.Tactic.Field /-! # The trapezoidal rule This file contains a definition of integration on `[[a, b]]` via the trapezoidal rule, along with an error bound in terms of a bound on the second derivative of the integrand. ## Main results - `trapezoidal_error_le`: the convergence theorem for the trapezoidal rule. ## References We follow the proof on (Wikipedia)[https://en.wikipedia.org/wiki/Trapezoidal_rule] for the error bound. -/ open MeasureTheory intervalIntegral Interval Finset HasDerivWithinAt Set /-- Integration of `f` from `a` to `b` using the trapezoidal rule with `N+1` total evaluations of `f`. (Note the off-by-one problem here: `N` counts the number of trapezoids, not the number of evaluations.) -/ noncomputable def trapezoidal_integral (f : ℝ → ℝ) (N : ℕ) (a b : ℝ) : ℝ := ((b - a) / N) * ((f a + f b) / 2 + ∑ k ∈ range (N - 1), f (a + (k + 1) * (b - a) / N)) /-- The absolute error of trapezoidal integration. -/ noncomputable def trapezoidal_error (f : ℝ → ℝ) (N : ℕ) (a b : ℝ) : ℝ := (trapezoidal_integral f N a b) - (∫ x in a..b, f x) /-- Just like exact integration, the trapezoidal approximation retains the same magnitude but changes sign when the endpoints are swapped. -/ theorem trapezoidal_integral_symm (f : ℝ → ℝ) {N : ℕ} (N_nonzero : 0 < N) (a b : ℝ) : trapezoidal_integral f N a b = -(trapezoidal_integral f N b a) := by unfold trapezoidal_integral rw [neg_mul_eq_neg_mul, neg_div', neg_sub, add_comm (f b) (f a), ← sum_range_reflect] congr 2 apply sum_congr rfl intro k hk norm_cast rw [tsub_tsub, add_comm 1, Nat.cast_add, Nat.cast_sub (mem_range.mp hk), Nat.cast_sub N_nonzero] apply congr_arg field /-- The absolute error of the trapezoidal rule does not change when the endpoints are swapped. -/ theorem trapezoidal_error_symm (f : ℝ → ℝ) {N : ℕ} (N_nonzero : 0 < N) (a b : ℝ) : trapezoidal_error f N a b = -trapezoidal_error f N b a := by unfold trapezoidal_error rw [trapezoidal_integral_symm f N_nonzero a b, integral_symm, neg_sub_neg, neg_sub] /-- Just like exact integration, the trapezoidal integration from `a` to `a` is zero. -/ @[simp] theorem trapezoidal_integral_eq (f : ℝ → ℝ) (N : ℕ) (a : ℝ) : trapezoidal_integral f N a a = 0 := by simp [trapezoidal_integral] /-- The error of the trapezoidal integration from `a` to `a` is zero. -/ @[simp] theorem trapezoidal_error_eq (f : ℝ → ℝ) (N : ℕ) (a : ℝ) : trapezoidal_error f N a a = 0 := by simp [trapezoidal_error] /-- An exact formula for integration with a single trapezoid (the "midpoint rule"). -/ @[simp] theorem trapezoidal_integral_one (f : ℝ → ℝ) (a b : ℝ) : trapezoidal_integral f 1 a b = (b - a) / 2 * (f a + f b) := by simp [trapezoidal_integral, mul_comm_div] /-- A basic trapezoidal equivalent to `IntervalIntegral.sum_integral_adjacent_intervals`. More general theorems are certainly possible, but many of them can be derived from repeated applications of this one. -/ theorem sum_trapezoidal_integral_adjacent_intervals {f : ℝ → ℝ} {N : ℕ} {a h : ℝ} (N_nonzero : 0 < N) : ∑ i ∈ range N, trapezoidal_integral f 1 (a + i * h) (a + (i + 1) * h) = trapezoidal_integral f N a (a + N * h) := by simp_rw [trapezoidal_integral_one, add_sub_add_left_eq_sub, ← sub_mul, trapezoidal_integral, add_sub_cancel_left, one_mul, ← mul_sum, ← mul_div, show N * (h / N) = h by field] rw [sum_add_distrib, ← Nat.sub_one_add_one_eq_of_pos N_nonzero, sum_range_succ', sum_range_succ, add_add_add_comm, ← sum_add_distrib, add_comm, Nat.sub_one_add_one_eq_of_pos N_nonzero] simp_rw [Nat.cast_sub N_nonzero, Nat.cast_add, Nat.cast_one, ← two_mul, ← mul_sum] ring_nf /-- A simplified version of the previous theorem, for use in proofs by induction and the like. -/ theorem trapezoidal_integral_ext {f : ℝ → ℝ} {N : ℕ} {a h : ℝ} (N_nonzero : 0 < N) : trapezoidal_integral f N a (a + N * h) + trapezoidal_integral f 1 (a + N * h) (a + (N + 1) * h) = trapezoidal_integral f (N + 1) a (a + (N + 1) * h) := by rw [← Nat.cast_add_one, ← sum_trapezoidal_integral_adjacent_intervals N_nonzero, ← sum_trapezoidal_integral_adjacent_intervals (Nat.add_pos_left N_nonzero 1), sum_range_succ, Nat.cast_add_one] /-- Since we have `sum_[]_adjacent_intervals` theorems for both exact and trapezoidal integration, it's natural to combine them into a similar formula for the error. This theorem is in particular used in the proof of the general error bound. -/ theorem sum_trapezoidal_error_adjacent_intervals {f : ℝ → ℝ} {N : ℕ} {a h : ℝ} (N_nonzero : 0 < N) (h_f_int : IntervalIntegrable f volume a (a + N * h)) : ∑ i ∈ range N, trapezoidal_error f 1 (a + i * h) (a + (i + 1) * h) = trapezoidal_error f N a (a + N * h) := by unfold trapezoidal_error rw [sum_sub_distrib, sum_trapezoidal_integral_adjacent_intervals N_nonzero] norm_cast rw [sum_integral_adjacent_intervals] · simp · intro k hk suffices ∀ {k : ℕ}, k ≤ N → a + k * h ∈ [[a, a + N * h]] from IntervalIntegrable.mono h_f_int (Set.uIcc_subset_uIcc (this hk.le) (this hk)) le_rfl rcases le_total h 0 with h_neg | h_pos <;> intro k hk <;> rw [← Nat.cast_le (α := ℝ)] at hk · simpa [Set.mem_uIcc] using .inr ⟨mul_le_mul_of_nonpos_right hk h_neg, mul_nonpos_of_nonneg_of_nonpos k.cast_nonneg h_neg⟩ · exact Set.mem_uIcc_of_le (le_add_of_nonneg_right (by positivity)) (by grw [hk]) /-- The most basic case possible: two ordered points, with N = 1. This lemma is used in the proof of the general error bound later on. -/ private lemma trapezoidal_error_le_of_lt' {f : ℝ → ℝ} {ζ : ℝ} {a b : ℝ} (a_lt_b : a < b) (h_df : DifferentiableOn ℝ f (Icc a b)) (h_ddf : DifferentiableOn ℝ (derivWithin f (Icc a b)) (Icc a b)) (h_ddf_integrable : IntervalIntegrable (iteratedDerivWithin 2 f (Icc a b)) volume a b) (fpp_bound : ∀ x, |iteratedDerivWithin 2 f (Icc a b) x| ≤ ζ) : |trapezoidal_error f 1 a b| ≤ (b - a) ^ 3 * ζ / 12 := by rw [mul_div_assoc, mul_comm] let g (t : ℝ) := trapezoidal_error f 1 a t -- Hand-computed expressions for g' and g''. let dg (t : ℝ) := (1 / 2) * (f a + f t) + ((t - a) / 2) * (derivWithin f (Icc a b) t) - f t let ddg (t : ℝ) := ((t - a) / 2) * (iteratedDerivWithin 2 f (Icc a b) t) -- Compute g' by applying standard derivative identities. have h_dg (y : ℝ) (hy: y ∈ Icc a b) : HasDerivWithinAt g (dg y) (Icc a b) y := by unfold g trapezoidal_error trapezoidal_integral simp only [Nat.cast_one, div_one, tsub_self, Finset.range_zero, sum_empty, add_zero] simp_rw [← mul_comm_div] refine fun_sub (fun_mul (div_const (sub_const _ (hasDerivWithinAt_id _ _)) _) (const_add _ (h_df y hy).hasDerivWithinAt)) ?_ have := Fact.mk hy -- Needed for integral_hasDerivWithinAt_right apply integral_hasDerivWithinAt_right · exact (h_df.continuousOn.mono (Icc_subset_Icc le_rfl hy.2)).intervalIntegrable_of_Icc hy.1 · exact h_df.continuousOn.stronglyMeasurableAtFilter_nhdsWithin measurableSet_Icc y · exact h_df.continuousOn.continuousWithinAt hy -- Compute g'', once again applying standard derivative identities. have h_ddg (y : ℝ) (hx: y ∈ Icc a b) : HasDerivWithinAt dg (ddg y) (Icc a b) y := by -- The eventual expression for g'' has several terms that cancel, which we have to undo here -- so that the various HasDerivWithinAt theorems will have everything they need. let dfaky := derivWithin f (Icc a b) y rw [(by ring: ddg y = (1 / 2) * dfaky + ((1 / 2) * dfaky + ddg y) - dfaky)] refine fun_sub (fun_add (const_mul _ (const_add _ (h_df y hx).hasDerivWithinAt)) (fun_mul (div_const (sub_const _ (hasDerivWithinAt_id _ _)) _) ?_)) (h_df y hx).hasDerivWithinAt rw [iteratedDerivWithin_eq_iterate] exact (h_ddf y hx).hasDerivWithinAt -- Technically this would work for all x ≥ a, but we only need it for x ∈ Icc a b (and it makes -- more pure-mathematical sense that way). have bound_ddg (x : ℝ) (hx : x ∈ Icc a b) : |ddg x| ≤ (ζ / 2) * ((x - a) ^ 1) := by simp_rw [pow_one, ddg, abs_mul, abs_div, abs_two] grw [fpp_bound x, abs_of_nonneg (sub_nonneg.mpr hx.1), div_mul_comm] have key {φ φ' : ℝ → ℝ} (h : ∀ x ∈ Icc a b, HasDerivWithinAt φ (φ' x) (Icc a b) x) (h0 : φ a = 0) {c : ℝ} {n : ℕ} (h_bound : ∀ t ∈ Icc a b, |φ' t| ≤ c * (t - a) ^ n) (hφ' : IntervalIntegrable φ' volume a b) : ∀ t ∈ Icc a b, |φ t| ≤ c / (n + 1) * (t - a) ^ (n + 1) := by intro t ht have hs : Icc a t ⊆ Icc a b := Icc_subset_Icc_right ht.2 have hs' : Ioo a t ⊆ Ioo a b := Ioo_subset_Ioo_right ht.2 have hs'' : uIcc a t ⊆ uIcc a b := by rwa [uIcc_of_lt a_lt_b, uIcc_of_le ht.1] replace hφ' := hφ'.mono hs'' le_rfl have key := integral_eq_sub_of_hasDerivAt_of_le (f := φ) (f' := φ') ht.1 (fun x hx ↦ (h x (hs hx)).continuousWithinAt.mono hs) (fun x hx ↦ (h x (hs (mem_Icc_of_Ioo hx))).hasDerivAt (Icc_mem_nhds_iff.mpr (hs' hx))) hφ' rw [h0, sub_zero] at key grw [← key, abs_integral_le_integral_abs ht.1, integral_mono_on ht.1 hφ'.abs (Continuous.intervalIntegrable (by fun_prop) a t) fun x hx ↦ h_bound x (hs hx), integral_comp_sub_right (c * · ^ n), ← mul_div_right_comm, mul_div_assoc] simp have bound_dg := key h_ddg (by ring) bound_ddg (h_ddf_integrable.continuousOn_mul (by fun_prop)) have bound_g := key h_dg (trapezoidal_error_eq f 1 a) bound_dg (ContinuousOn.intervalIntegrable_of_Icc a_lt_b.le fun x hx ↦ (h_ddg x hx).continuousWithinAt) exact (bound_g b ⟨a_lt_b.le, le_rfl⟩).trans_eq (by ring_nf) /-- The hard part of the trapezoidal rule error bound: proving it in the case of a non-empty closed interval with ordered endpoints. This lemma is used in the proof of the general error bound later on. -/ private lemma trapezoidal_error_le_of_lt {f : ℝ → ℝ} {ζ : ℝ} {a b : ℝ} (a_lt_b : a < b) (h_df : DifferentiableOn ℝ f (Icc a b)) (h_ddf : DifferentiableOn ℝ (derivWithin f (Icc a b)) (Icc a b)) (h_ddf_integrable : IntervalIntegrable (iteratedDerivWithin 2 f (Icc a b)) volume a b) (fpp_bound : ∀ x, |iteratedDerivWithin 2 f (Icc a b) x| ≤ ζ) {N : ℕ} (N_nonzero : 0 < N) : |trapezoidal_error f N a b| ≤ (b - a) ^ 3 * ζ / (12 * N ^ 2) := by let h := (b - a) / N let ak (k : ℕ) := a + k * h have h0 : ∀ k : ℕ, ak (k + 1) - ak k = h := by simp [ak, ← sub_mul] have hab : 0 < b - a := sub_pos.mpr a_lt_b have hpos : 0 < h := by positivity have hb : b = a + N * h := by unfold h; field rw [hb, ← sum_trapezoidal_error_adjacent_intervals N_nonzero (hb ▸ h_df.continuousOn.intervalIntegrable_of_Icc a_lt_b.le)] grw [abs_sum_le_sum_abs] suffices ∀ k ∈ range N, |trapezoidal_error f 1 (ak k) (ak (k + 1))| ≤ (ζ / 12) * h ^ 3 by norm_cast calc _ ≤ ∑ k ∈ range N, ζ / 12 * h ^ 3 := sum_le_sum this _ = N * (ζ / 12 * h ^ 3) := by simp [sum_const] _ = _ := by unfold h; push_cast; field intro k hk rw [Finset.mem_range] at hk have h1 : a ≤ ak k := by simp only [ak, le_add_iff_nonneg_right]; positivity have h2 : ak (k + 1) ≤ b := by simp only [ak, hb]; grw [Nat.lt_iff_add_one_le.mp hk] have h3 : Icc (ak k) (ak (k + 1)) ⊆ Icc a b := Icc_subset_Icc h1 h2 have h4 : ak k < ak (k + 1) := by rwa [← sub_pos, h0] have h5 : EqOn (derivWithin f (Icc a b)) (derivWithin f (Icc (ak k) (ak (k + 1)))) (Icc (ak k) (ak (k + 1))) := by intro x hx rw [← derivWithin_subset h3 (uniqueDiffOn_Icc h4 x hx) (h_df x (h3 hx))] have h6 : EqOn (iteratedDerivWithin 2 f (Icc a b)) (iteratedDerivWithin 2 f (Icc (ak k) (ak (k + 1)))) (Icc (ak k) (ak (k + 1))) := by intro x hx simp only [iteratedDerivWithin_succ', iteratedDerivWithin_zero] rw [← derivWithin_subset h3 (uniqueDiffOn_Icc h4 x hx) (h_ddf x (h3 hx))] exact derivWithin_congr h5 (h5 hx) have h7 (x : ℝ) : |iteratedDerivWithin 2 f (Set.Icc (ak k) (ak (k + 1))) x| ≤ ζ := by by_cases hx : x ∈ Icc (ak k) (ak (k + 1)) · grw [← h6 hx, fpp_bound] · rw [iteratedDerivWithin_succ, derivWithin_zero_of_notMem_closure (by rwa [closure_Icc]), abs_zero] exact (abs_nonneg _).trans (fpp_bound 0) refine (trapezoidal_error_le_of_lt' (ζ := ζ) h4 (h_df.mono h3) ?_ ?_ h7).trans_eq ?_ · refine h_ddf.congr_mono (fun x hx ↦ ?_) h3 exact derivWithin_subset h3 (uniqueDiffOn_Icc h4 x hx) (h_df x (h3 hx)) · exact (h_ddf_integrable.mono_set (by rwa [Set.uIcc_of_lt h4, Set.uIcc_of_lt a_lt_b])).congr (h6.mono (Set.uIoc_subset_uIcc.trans_eq (Set.uIcc_of_lt h4))) · rw [h0, mul_div_assoc, mul_comm] /-- The standard error bound for trapezoidal integration on the general interval `[[a, b]]`. -/ theorem trapezoidal_error_le {f : ℝ → ℝ} {a b : ℝ} (h_df : DifferentiableOn ℝ f [[a, b]]) (h_ddf : DifferentiableOn ℝ (derivWithin f [[a, b]]) [[a, b]]) (h_ddf_integrable : IntervalIntegrable (iteratedDerivWithin 2 f [[a, b]]) volume a b) {ζ : ℝ} (fpp_bound : ∀ x, |iteratedDerivWithin 2 f [[a, b]] x| ≤ ζ) {N : ℕ} (N_nonzero : 0 < N) : |trapezoidal_error f N a b| ≤ |b - a| ^ 3 * ζ / (12 * N ^ 2) := by rcases lt_trichotomy a b with h_lt | h_eq | h_gt -- Standard case: a < b · rw [uIcc_of_lt h_lt] at * rw [abs_of_pos (sub_pos.mpr h_lt)] exact trapezoidal_error_le_of_lt h_lt h_df h_ddf h_ddf_integrable fpp_bound N_nonzero -- Trivial case: a = b · simp [h_eq] -- Slightly trickier case: a > b (requires flipping the direction and sign of the true and -- approximate integrals) · rw [uIcc_of_gt h_gt] at * rw [abs_of_neg (sub_neg.mpr h_gt), neg_sub, trapezoidal_error_symm f N_nonzero a b, abs_neg] exact trapezoidal_error_le_of_lt h_gt h_df h_ddf h_ddf_integrable.symm fpp_bound N_nonzero /-- The error bound for trapezoidal integration in the slightly weaker, but very common, case where `f` is `C^2`. -/ theorem trapezoidal_error_le_of_c2 {f : ℝ → ℝ} {a b : ℝ} (h_f_c2 : ContDiffOn ℝ 2 f [[a, b]]) {ζ : ℝ} (fpp_bound : ∀ x, |iteratedDerivWithin 2 f [[a, b]] x| ≤ ζ) {N : ℕ} (N_nonzero : 0 < N) : |trapezoidal_error f N a b| ≤ |b - a| ^ 3 * ζ / (12 * N ^ 2) := by -- This use of rcases slightly duplicates effort from the proof of trapezoidal_error_le, but doing -- it any other way that I can think of would be worse. rcases eq_or_ne a b with h_eq | h_neq · simp [h_eq] -- Once we have a ≠ b, all the necessary assumptions on f follow pretty quickly from its being -- C^2. have ud : UniqueDiffOn ℝ [[a, b]] := uniqueDiffOn_Icc (inf_lt_sup.mpr h_neq) have h_df : DifferentiableOn ℝ f [[a, b]] := ContDiffOn.differentiableOn h_f_c2 one_le_two have h_ddf : DifferentiableOn ℝ (derivWithin f [[a, b]]) [[a, b]] := by rw [← iteratedDerivWithin_one] exact ContDiffOn.differentiableOn_iteratedDerivWithin h_f_c2 (by norm_cast) ud have h_ddf_integrable : IntervalIntegrable (iteratedDerivWithin 2 f [[a, b]]) volume a b := (ContDiffOn.continuousOn_iteratedDerivWithin h_f_c2 (le_refl 2) ud).intervalIntegrable exact trapezoidal_error_le h_df h_ddf h_ddf_integrable fpp_bound N_nonzero
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Bochner/ContinuousLinearMap.lean
import Mathlib.Analysis.Normed.Operator.CompleteCodomain import Mathlib.MeasureTheory.Integral.Bochner.Set import Mathlib.Topology.ContinuousMap.ContinuousMapZero /-! # Continuous linear maps composed with integration The goal of this file is to prove that integration commutes with continuous linear maps. This holds for simple functions. The general result follows from the continuity of all involved operations on the space `L¹`. Note that composition by a continuous linear map on `L¹` is not just the composition, as we are dealing with classes of functions, but it has already been defined as `ContinuousLinearMap.compLp`. We take advantage of this construction here. -/ open MeasureTheory RCLike open scoped ENNReal NNReal variable {X Y E F Fₗ : Type*} [MeasurableSpace X] {μ : Measure X} {𝕜 𝕜' : Type*} [RCLike 𝕜] [RCLike 𝕜'] [NormedAddCommGroup E] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [NormedSpace 𝕜' F] [NormedAddCommGroup Fₗ] [NormedSpace 𝕜 Fₗ] {p : ℝ≥0∞} namespace ContinuousLinearMap variable [NormedSpace ℝ F] [NormedSpace ℝ Fₗ] variable {σ : 𝕜 →+* 𝕜'} [RingHomIsometric σ] theorem integral_compLp (L : E →SL[σ] F) (φ : Lp E p μ) : ∫ x, (L.compLp φ) x ∂μ = ∫ x, L (φ x) ∂μ := integral_congr_ae <| coeFn_compLp _ _ theorem setIntegral_compLp (L : E →SL[σ] F) (φ : Lp E p μ) {s : Set X} (hs : MeasurableSet s) : ∫ x in s, (L.compLp φ) x ∂μ = ∫ x in s, L (φ x) ∂μ := setIntegral_congr_ae hs ((L.coeFn_compLp φ).mono fun _x hx _ => hx) theorem continuous_integral_comp_L1 (L : E →SL[σ] F) : Continuous fun φ : X →₁[μ] E => ∫ x : X, L (φ x) ∂μ := by rw [← funext L.integral_compLp]; exact continuous_integral.comp (L.compLpL 1 μ).continuous variable [CompleteSpace F] [CompleteSpace Fₗ] [NormedSpace ℝ E] theorem integral_comp_commSL [CompleteSpace E] (hσ : ∀ (r : ℝ) (x : 𝕜), σ (r • x) = r • σ x) (L : E →SL[σ] F) {φ : X → E} (φ_int : Integrable φ μ) : ∫ x, L (φ x) ∂μ = L (∫ x, φ x ∂μ) := by apply φ_int.induction (P := fun φ => ∫ x, L (φ x) ∂μ = L (∫ x, φ x ∂μ)) · intro e s s_meas _ rw [integral_indicator_const e s_meas, ← @smul_one_smul E ℝ 𝕜 _ _ _ _ _ (μ.real s) e, ContinuousLinearMap.map_smulₛₗ, hσ, map_one, smul_assoc, one_smul, ← integral_indicator_const (L e) s_meas] congr 1 with a rw [← Function.comp_def L, Set.indicator_comp_of_zero L.map_zero, Function.comp_apply] · intro f g _ f_int g_int hf hg simp [L.map_add, integral_add (μ := μ) f_int g_int, integral_add (μ := μ) (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] · exact isClosed_eq L.continuous_integral_comp_L1 (L.continuous.comp continuous_integral) · intro f g hfg _ hf convert hf using 1 <;> clear hf · exact integral_congr_ae (hfg.fun_comp L).symm · rw [integral_congr_ae hfg.symm] theorem integral_comp_comm [CompleteSpace E] (L : E →L[𝕜] Fₗ) {φ : X → E} (φ_int : Integrable φ μ) : ∫ x, L (φ x) ∂μ = L (∫ x, φ x ∂μ) := integral_comp_commSL (by simp) L φ_int theorem integral_apply {H : Type*} [NormedAddCommGroup H] [NormedSpace 𝕜 H] {φ : X → H →L[𝕜] E} (φ_int : Integrable φ μ) (v : H) : (∫ x, φ x ∂μ) v = ∫ x, φ x v ∂μ := by by_cases hE : CompleteSpace E · exact ((ContinuousLinearMap.apply 𝕜 E v).integral_comp_comm φ_int).symm · rcases subsingleton_or_nontrivial H with hH|hH · simp [Subsingleton.eq_zero v] · have : ¬(CompleteSpace (H →L[𝕜] E)) := by rwa [SeparatingDual.completeSpace_continuousLinearMap_iff] simp [integral, hE, this] theorem _root_.ContinuousMultilinearMap.integral_apply {ι : Type*} [Fintype ι] {M : ι → Type*} [∀ i, NormedAddCommGroup (M i)] [∀ i, NormedSpace 𝕜 (M i)] {φ : X → ContinuousMultilinearMap 𝕜 M E} (φ_int : Integrable φ μ) (m : ∀ i, M i) : (∫ x, φ x ∂μ) m = ∫ x, φ x m ∂μ := by by_cases hE : CompleteSpace E · exact ((ContinuousMultilinearMap.apply 𝕜 M E m).integral_comp_comm φ_int).symm · by_cases! hm : ∀ i, m i ≠ 0 · have : ¬ CompleteSpace (ContinuousMultilinearMap 𝕜 M E) := by rwa [SeparatingDual.completeSpace_continuousMultilinearMap_iff _ _ hm] simp [integral, hE, this] · rcases hm with ⟨i, hi⟩ simp [ContinuousMultilinearMap.map_coord_zero _ i hi] variable [CompleteSpace E] theorem integral_comp_comm' (L : E →L[𝕜] Fₗ) {K} (hL : AntilipschitzWith K L) (φ : X → E) : ∫ x, L (φ x) ∂μ = L (∫ x, φ x ∂μ) := by by_cases h : Integrable φ μ · exact integral_comp_comm L h have : ¬Integrable (fun x => L (φ x)) μ := by rwa [← Function.comp_def, LipschitzWith.integrable_comp_iff_of_antilipschitz L.lipschitz hL L.map_zero] simp [integral_undef, h, this] theorem integral_comp_L1_comm (L : E →L[𝕜] Fₗ) (φ : X →₁[μ] E) : ∫ x, L (φ x) ∂μ = L (∫ x, φ x ∂μ) := L.integral_comp_comm (L1.integrable_coeFn φ) end ContinuousLinearMap namespace LinearIsometry variable [CompleteSpace F] [NormedSpace 𝕜 F] [NormedSpace ℝ F] [CompleteSpace E] [NormedSpace ℝ E] theorem integral_comp_comm (L : E →ₗᵢ[𝕜] F) (φ : X → E) : ∫ x, L (φ x) ∂μ = L (∫ x, φ x ∂μ) := L.toContinuousLinearMap.integral_comp_comm' L.antilipschitz _ end LinearIsometry namespace ContinuousLinearEquiv variable [NormedSpace ℝ F] [NormedSpace 𝕜 F] [NormedSpace ℝ E] theorem integral_comp_comm (L : E ≃L[𝕜] F) (φ : X → E) : ∫ x, L (φ x) ∂μ = L (∫ x, φ x ∂μ) := by have : CompleteSpace E ↔ CompleteSpace F := completeSpace_congr (e := L.toEquiv) L.isUniformEmbedding obtain ⟨_, _⟩|⟨_, _⟩ := iff_iff_and_or_not_and_not.mp this · exact L.toContinuousLinearMap.integral_comp_comm' L.antilipschitz _ · simp [integral, *] end ContinuousLinearEquiv section ContinuousMap variable [TopologicalSpace Y] [CompactSpace Y] lemma ContinuousMap.integral_apply [NormedSpace ℝ E] [CompleteSpace E] {f : X → C(Y, E)} (hf : Integrable f μ) (y : Y) : (∫ x, f x ∂μ) y = ∫ x, f x y ∂μ := by calc (∫ x, f x ∂μ) y = ContinuousMap.evalCLM ℝ y (∫ x, f x ∂μ) := rfl _ = ∫ x, ContinuousMap.evalCLM ℝ y (f x) ∂μ := (ContinuousLinearMap.integral_comp_comm _ hf).symm _ = _ := rfl open scoped ContinuousMapZero in theorem ContinuousMapZero.integral_apply {R : Type*} [NormedCommRing R] [Zero Y] [NormedAlgebra ℝ R] [CompleteSpace R] {f : X → C(Y, R)₀} (hf : MeasureTheory.Integrable f μ) (y : Y) : (∫ (x : X), f x ∂μ) y = ∫ (x : X), (f x) y ∂μ := by calc (∫ x, f x ∂μ) y = ContinuousMapZero.evalCLM ℝ y (∫ x, f x ∂μ) := rfl _ = ∫ x, ContinuousMapZero.evalCLM ℝ y (f x) ∂μ := (ContinuousLinearMap.integral_comp_comm _ hf).symm _ = _ := rfl end ContinuousMap @[norm_cast] theorem integral_ofReal {f : X → ℝ} : ∫ x, (f x : 𝕜) ∂μ = ↑(∫ x, f x ∂μ) := (@RCLike.ofRealLI 𝕜 _).integral_comp_comm f theorem integral_complex_ofReal {f : X → ℝ} : ∫ x, (f x : ℂ) ∂μ = ∫ x, f x ∂μ := integral_ofReal theorem integral_re {f : X → 𝕜} (hf : Integrable f μ) : ∫ x, RCLike.re (f x) ∂μ = RCLike.re (∫ x, f x ∂μ) := (@RCLike.reCLM 𝕜 _).integral_comp_comm hf theorem integral_im {f : X → 𝕜} (hf : Integrable f μ) : ∫ x, RCLike.im (f x) ∂μ = RCLike.im (∫ x, f x ∂μ) := (@RCLike.imCLM 𝕜 _).integral_comp_comm hf open scoped ComplexConjugate in theorem integral_conj {f : X → 𝕜} : ∫ x, conj (f x) ∂μ = conj (∫ x, f x ∂μ) := (@RCLike.conjLIE 𝕜 _).toLinearIsometry.integral_comp_comm f theorem integral_coe_re_add_coe_im {f : X → 𝕜} (hf : Integrable f μ) : ∫ x, (re (f x) : 𝕜) ∂μ + (∫ x, (im (f x) : 𝕜) ∂μ) * RCLike.I = ∫ x, f x ∂μ := by rw [mul_comm, ← smul_eq_mul, ← integral_smul, ← integral_add] · congr ext1 x rw [smul_eq_mul, mul_comm, RCLike.re_add_im] · exact hf.re.ofReal · exact hf.im.ofReal.smul (𝕜 := 𝕜) (β := 𝕜) RCLike.I theorem integral_re_add_im {f : X → 𝕜} (hf : Integrable f μ) : ((∫ x, RCLike.re (f x) ∂μ : ℝ) : 𝕜) + (∫ x, RCLike.im (f x) ∂μ : ℝ) * RCLike.I = ∫ x, f x ∂μ := by rw [← integral_ofReal, ← integral_ofReal, integral_coe_re_add_coe_im hf] theorem setIntegral_re_add_im {f : X → 𝕜} {i : Set X} (hf : IntegrableOn f i μ) : ((∫ x in i, RCLike.re (f x) ∂μ : ℝ) : 𝕜) + (∫ x in i, RCLike.im (f x) ∂μ : ℝ) * RCLike.I = ∫ x in i, f x ∂μ := integral_re_add_im hf variable [NormedSpace ℝ E] [NormedSpace ℝ F] lemma swap_integral (f : X → E × F) : (∫ x, f x ∂μ).swap = ∫ x, (f x).swap ∂μ := .symm <| (ContinuousLinearEquiv.prodComm ℝ E F).integral_comp_comm f theorem fst_integral [CompleteSpace F] {f : X → E × F} (hf : Integrable f μ) : (∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ := by by_cases hE : CompleteSpace E · exact ((ContinuousLinearMap.fst ℝ E F).integral_comp_comm hf).symm · have : ¬(CompleteSpace (E × F)) := fun h ↦ hE <| .fst_of_prod (β := F) simp [integral, *] theorem snd_integral [CompleteSpace E] {f : X → E × F} (hf : Integrable f μ) : (∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ := by rw [← Prod.fst_swap, swap_integral] exact fst_integral <| hf.snd.prodMk hf.fst theorem integral_pair [CompleteSpace E] [CompleteSpace F] {f : X → E} {g : X → F} (hf : Integrable f μ) (hg : Integrable g μ) : ∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) := have := hf.prodMk hg Prod.ext (fst_integral this) (snd_integral this) theorem integral_smul_const {𝕜 : Type*} [RCLike 𝕜] [NormedSpace 𝕜 E] [CompleteSpace E] (f : X → 𝕜) (c : E) : ∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c := by by_cases hf : Integrable f μ · exact ((1 : 𝕜 →L[𝕜] 𝕜).smulRight c).integral_comp_comm hf · by_cases hc : c = 0 · simp [hc, integral_zero, smul_zero] rw [integral_undef hf, integral_undef, zero_smul] rw [integrable_smul_const hc] simp_rw [hf, not_false_eq_true] /- Note that the integrability hypothesis in the two lemmas below is necessary: consider the case where `A = ℝ × ℝ`, `c = (1,0)`, and `f` is only integrable on the first component. -/ lemma integral_const_mul_of_integrable {A : Type*} [NonUnitalNormedRing A] [NormedSpace ℝ A] [IsScalarTower ℝ A A] [SMulCommClass ℝ A A] {f : X → A} (hf : Integrable f μ) {c : A} : ∫ x, c * f x ∂μ = c * ∫ x, f x ∂μ := by by_cases hA : CompleteSpace A · change ∫ x, ContinuousLinearMap.mul ℝ _ c (f x) ∂μ = ContinuousLinearMap.mul ℝ _ c (∫ x, f x ∂μ) rw [ContinuousLinearMap.integral_comp_comm _ hf] · simp [integral, hA] lemma integral_mul_const_of_integrable {A : Type*} [NonUnitalNormedRing A] [NormedSpace ℝ A] [IsScalarTower ℝ A A] [SMulCommClass ℝ A A] {f : X → A} (hf : Integrable f μ) {c : A} : ∫ x, f x * c ∂μ = (∫ x, f x ∂μ) * c := by by_cases hA : CompleteSpace A · change ∫ x, (ContinuousLinearMap.mul ℝ _).flip c (f x) ∂μ = (ContinuousLinearMap.mul ℝ _).flip c (∫ x, f x ∂μ) rw [ContinuousLinearMap.integral_comp_comm _ hf] · simp [integral, hA] theorem integral_withDensity_eq_integral_smul {f : X → ℝ≥0} (f_meas : Measurable f) (g : X → E) : ∫ x, g x ∂μ.withDensity (fun x => f x) = ∫ x, f x • g x ∂μ := by by_cases hE : CompleteSpace E; swap; · simp [integral, hE] by_cases hg : Integrable g (μ.withDensity fun x => f x); swap · rw [integral_undef hg, integral_undef] rwa [← integrable_withDensity_iff_integrable_smul f_meas] refine Integrable.induction (P := fun g => ∫ x, g x ∂μ.withDensity (fun x => f x) = ∫ x, f x • g x ∂μ) ?_ ?_ ?_ ?_ hg · intro c s s_meas hs rw [integral_indicator s_meas] simp_rw [← Set.indicator_smul_apply, integral_indicator s_meas] simp only [s_meas, integral_const, Measure.restrict_apply', Set.univ_inter, withDensity_apply, measureReal_def] rw [lintegral_coe_eq_integral, ENNReal.toReal_ofReal, ← integral_smul_const] · rfl · exact integral_nonneg fun x => NNReal.coe_nonneg _ · refine ⟨f_meas.coe_nnreal_real.aemeasurable.aestronglyMeasurable, ?_⟩ simpa [withDensity_apply _ s_meas, hasFiniteIntegral_iff_enorm] using hs · intro u u' _ u_int u'_int h h' change (∫ x : X, u x + u' x ∂μ.withDensity fun x : X => ↑(f x)) = ∫ x : X, f x • (u x + u' x) ∂μ simp_rw [smul_add] rw [integral_add u_int u'_int, h, h', integral_add] · exact (integrable_withDensity_iff_integrable_smul f_meas).1 u_int · exact (integrable_withDensity_iff_integrable_smul f_meas).1 u'_int · have C1 : Continuous fun u : Lp E 1 (μ.withDensity fun x => f x) => ∫ x, u x ∂μ.withDensity fun x => f x := continuous_integral have C2 : Continuous fun u : Lp E 1 (μ.withDensity fun x => f x) => ∫ x, f x • u x ∂μ := by have : Continuous ((fun u : Lp E 1 μ => ∫ x, u x ∂μ) ∘ withDensitySMulLI (E := E) μ f_meas) := continuous_integral.comp (withDensitySMulLI (E := E) μ f_meas).continuous convert this with u simp only [Function.comp_apply, withDensitySMulLI_apply] exact integral_congr_ae (memL1_smul_of_L1_withDensity f_meas u).coeFn_toLp.symm exact isClosed_eq C1 C2 · intro u v huv _ hu rw [← integral_congr_ae huv, hu] apply integral_congr_ae filter_upwards [(ae_withDensity_iff f_meas.coe_nnreal_ennreal).1 huv] with x hx rcases eq_or_ne (f x) 0 with (h'x | h'x) · simp only [h'x, zero_smul] · rw [hx _] simpa only [Ne, ENNReal.coe_eq_zero] using h'x theorem integral_withDensity_eq_integral_smul₀ {f : X → ℝ≥0} (hf : AEMeasurable f μ) (g : X → E) : ∫ x, g x ∂μ.withDensity (fun x => f x) = ∫ x, f x • g x ∂μ := by let f' := hf.mk _ calc ∫ x, g x ∂μ.withDensity (fun x => f x) = ∫ x, g x ∂μ.withDensity fun x => f' x := by congr 1 apply withDensity_congr_ae filter_upwards [hf.ae_eq_mk] with x hx rw [hx] _ = ∫ x, f' x • g x ∂μ := integral_withDensity_eq_integral_smul hf.measurable_mk _ _ = ∫ x, f x • g x ∂μ := by apply integral_congr_ae filter_upwards [hf.ae_eq_mk] with x hx rw [hx] theorem integral_withDensity_eq_integral_toReal_smul₀ {f : X → ℝ≥0∞} (f_meas : AEMeasurable f μ) (hf_lt_top : ∀ᵐ x ∂μ, f x < ∞) (g : X → E) : ∫ x, g x ∂μ.withDensity f = ∫ x, (f x).toReal • g x ∂μ := by dsimp only [ENNReal.toReal, ← NNReal.smul_def] rw [← integral_withDensity_eq_integral_smul₀ f_meas.ennreal_toNNReal, withDensity_congr_ae (coe_toNNReal_ae_eq hf_lt_top)] theorem integral_withDensity_eq_integral_toReal_smul {f : X → ℝ≥0∞} (f_meas : Measurable f) (hf_lt_top : ∀ᵐ x ∂μ, f x < ∞) (g : X → E) : ∫ x, g x ∂μ.withDensity f = ∫ x, (f x).toReal • g x ∂μ := integral_withDensity_eq_integral_toReal_smul₀ f_meas.aemeasurable hf_lt_top g theorem setIntegral_withDensity_eq_setIntegral_smul₀ {f : X → ℝ≥0} {s : Set X} (hf : AEMeasurable f (μ.restrict s)) (g : X → E) (hs : MeasurableSet s) : ∫ x in s, g x ∂μ.withDensity (fun x => f x) = ∫ x in s, f x • g x ∂μ := by rw [restrict_withDensity hs, integral_withDensity_eq_integral_smul₀ hf] theorem setIntegral_withDensity_eq_setIntegral_toReal_smul₀ {f : X → ℝ≥0∞} {s : Set X} (hf : AEMeasurable f (μ.restrict s)) (hf_top : ∀ᵐ x ∂μ.restrict s, f x < ∞) (g : X → E) (hs : MeasurableSet s) : ∫ x in s, g x ∂μ.withDensity (fun x => f x) = ∫ x in s, (f x).toReal • g x ∂μ := by rw [restrict_withDensity hs, integral_withDensity_eq_integral_toReal_smul₀ hf hf_top] theorem setIntegral_withDensity_eq_setIntegral_smul {f : X → ℝ≥0} (f_meas : Measurable f) (g : X → E) {s : Set X} (hs : MeasurableSet s) : ∫ x in s, g x ∂μ.withDensity (fun x => f x) = ∫ x in s, f x • g x ∂μ := setIntegral_withDensity_eq_setIntegral_smul₀ f_meas.aemeasurable _ hs theorem setIntegral_withDensity_eq_setIntegral_toReal_smul {f : X → ℝ≥0∞} {s : Set X} (hf : Measurable f) (hf_top : ∀ᵐ x ∂μ.restrict s, f x < ∞) (g : X → E) (hs : MeasurableSet s) : ∫ x in s, g x ∂μ.withDensity (fun x => f x) = ∫ x in s, (f x).toReal • g x ∂μ := setIntegral_withDensity_eq_setIntegral_toReal_smul₀ hf.aemeasurable hf_top g hs theorem setIntegral_withDensity_eq_setIntegral_smul₀' [SFinite μ] {f : X → ℝ≥0} (s : Set X) (hf : AEMeasurable f (μ.restrict s)) (g : X → E) : ∫ x in s, g x ∂μ.withDensity (fun x => f x) = ∫ x in s, f x • g x ∂μ := by rw [restrict_withDensity' s, integral_withDensity_eq_integral_smul₀ hf] theorem setIntegral_withDensity_eq_setIntegral_toReal_smul₀' [SFinite μ] {f : X → ℝ≥0∞} (s : Set X) (hf : AEMeasurable f (μ.restrict s)) (hf_top : ∀ᵐ x ∂μ.restrict s, f x < ∞) (g : X → E) : ∫ x in s, g x ∂μ.withDensity f = ∫ x in s, (f x).toReal • g x ∂μ := by rw [restrict_withDensity' s, integral_withDensity_eq_integral_toReal_smul₀ hf hf_top] theorem setIntegral_withDensity_eq_setIntegral_toReal_smul' [SFinite μ] {f : X → ℝ≥0∞} (s : Set X) (hf : Measurable f) (hf_top : ∀ᵐ x ∂μ.restrict s, f x < ∞) (g : X → E) : ∫ x in s, g x ∂μ.withDensity f = ∫ x in s, (f x).toReal • g x ∂μ := setIntegral_withDensity_eq_setIntegral_toReal_smul₀' s hf.aemeasurable hf_top g
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Bochner/Basic.lean
import Mathlib.MeasureTheory.Group.MeasurableEquiv import Mathlib.MeasureTheory.Integral.Bochner.L1 import Mathlib.MeasureTheory.Integral.IntegrableOn import Mathlib.MeasureTheory.Measure.OpenPos import Mathlib.MeasureTheory.Measure.Real /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here using the L1 Bochner integral constructed in the file `Mathlib/MeasureTheory/Integral/Bochner/L1.lean`. ## Main definitions The Bochner integral is defined through the extension process described in the file `Mathlib/MeasureTheory/Integral/SetToL1.lean`, which follows these steps: * `MeasureTheory.integral`: the Bochner integral on functions defined as the Bochner integral of its equivalence class in L1 space, if it is in L1, and 0 otherwise. The result of that construction is `∫ a, f a ∂μ`, which is definitionally equal to `setToFun (dominatedFinMeasAdditive_weightedSMul μ) f`. Some basic properties of the integral (like linearity) are particular cases of the properties of `setToFun` (which are described in the file `Mathlib/MeasureTheory/Integral/SetToL1.lean`). ## Main statements 1. Basic properties of the Bochner integral on functions of type `α → E`, where `α` is a measure space and `E` is a real normed space. * `integral_zero` : `∫ 0 ∂μ = 0` * `integral_add` : `∫ x, f x + g x ∂μ = ∫ x, f ∂μ + ∫ x, g x ∂μ` * `integral_neg` : `∫ x, - f x ∂μ = - ∫ x, f x ∂μ` * `integral_sub` : `∫ x, f x - g x ∂μ = ∫ x, f x ∂μ - ∫ x, g x ∂μ` * `integral_smul` : `∫ x, r • f x ∂μ = r • ∫ x, f x ∂μ` * `integral_congr_ae` : `f =ᵐ[μ] g → ∫ x, f x ∂μ = ∫ x, g x ∂μ` * `norm_integral_le_integral_norm` : `‖∫ x, f x ∂μ‖ ≤ ∫ x, ‖f x‖ ∂μ` 2. Basic order properties of the Bochner integral on functions of type `α → E`, where `α` is a measure space and `E` is a real ordered Banach space. * `integral_nonneg_of_ae` : `0 ≤ᵐ[μ] f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos_of_ae` : `f ≤ᵐ[μ] 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono_ae` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` * `integral_nonneg` : `0 ≤ f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos` : `f ≤ 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` 3. Propositions connecting the Bochner integral with the integral on `ℝ≥0∞`-valued functions, which is called `lintegral` and has the notation `∫⁻`. * `integral_eq_lintegral_pos_part_sub_lintegral_neg_part` : `∫ x, f x ∂μ = ∫⁻ x, f⁺ x ∂μ - ∫⁻ x, f⁻ x ∂μ`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `0 ≤ᵐ[μ] f → ∫ x, f x ∂μ = ∫⁻ x, f x ∂μ` 4. (In the file `Mathlib/MeasureTheory/Integral/DominatedConvergence.lean`) `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem 5. (In `Mathlib/MeasureTheory/Integral/Bochner/Set.lean`) integration commutes with continuous linear maps. * `ContinuousLinearMap.integral_comp_comm` * `LinearIsometry.integral_comp_comm` ## Notes Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that you need to unfold the definition of the Bochner integral and go back to simple functions. One method is to use the theorem `Integrable.induction` in the file `Mathlib/MeasureTheory/Function/SimpleFuncDenseLp.lean` (or one of the related results, like `Lp.induction` for functions in `Lp`), which allows you to prove something for an arbitrary integrable function. Another method is using the following steps. See `integral_eq_lintegral_pos_part_sub_lintegral_neg_part` for a complicated example, which proves that `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued function `f : α → ℝ`, and second and third integral sign being the integral on `ℝ≥0∞`-valued functions (called `lintegral`). The proof of `integral_eq_lintegral_pos_part_sub_lintegral_neg_part` is scattered in sections with the name `posPart`. Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all functions : 1. First go to the `L¹` space. For example, if you see `ENNReal.toReal (∫⁻ a, ENNReal.ofReal <| ‖f a‖)`, that is the norm of `f` in `L¹` space. Rewrite using `L1.norm_of_fun_eq_lintegral_norm`. 2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `isClosed_eq`. 3. Show that the property holds for all simple functions `s` in `L¹` space. Typically, you need to convert various notions to their `SimpleFunc` counterpart, using lemmas like `L1.integral_coe_eq_integral`. 4. Since simple functions are dense in `L¹`, ``` univ = closure {s simple} = closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions ⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} = {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself ``` Use `isClosed_property` or `DenseRange.induction_on` for this argument. ## Notation * `α →ₛ E` : simple functions (defined in `Mathlib/MeasureTheory/Function/SimpleFunc.lean`) * `α →₁[μ] E` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `Mathlib/MeasureTheory/Function/LpSpace/Basic.lean`) * `∫ a, f a ∂μ` : integral of `f` with respect to a measure `μ` * `∫ a, f a` : integral of `f` with respect to `volume`, the default measure on the ambient type We also define notations for integral on a set, which are described in the file `Mathlib/MeasureTheory/Integral/Bochner/Set.lean`. Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if the font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable section open Filter ENNReal EMetric Set TopologicalSpace Topology open scoped NNReal ENNReal MeasureTheory namespace MeasureTheory variable {α E F 𝕜 : Type*} local infixr:25 " →ₛ " => SimpleFunc /-! ## The Bochner integral on functions Define the Bochner integral on functions generally to be the `L1` Bochner integral, for integrable functions, and 0 otherwise; prove its basic properties. -/ variable [NormedAddCommGroup E] [NormedDivisionRing 𝕜] [NormedAddCommGroup F] [NormedSpace ℝ F] [CompleteSpace F] {G : Type*} [NormedAddCommGroup G] [NormedSpace ℝ G] open Classical in /-- The Bochner integral -/ irreducible_def integral {_ : MeasurableSpace α} (μ : Measure α) (f : α → G) : G := if _ : CompleteSpace G then if hf : Integrable f μ then L1.integral (hf.toL1 f) else 0 else 0 /-! In the notation for integrals, an expression like `∫ x, g ‖x‖ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫ x, f x = 0` will be parsed incorrectly. -/ @[inherit_doc MeasureTheory.integral] notation3 "∫ "(...)", "r:60:(scoped f => f)" ∂"μ:70 => integral μ r @[inherit_doc MeasureTheory.integral] notation3 "∫ "(...)", "r:60:(scoped f => integral volume f) => r @[inherit_doc MeasureTheory.integral] notation3 "∫ "(...)" in "s", "r:60:(scoped f => f)" ∂"μ:70 => integral (Measure.restrict μ s) r @[inherit_doc MeasureTheory.integral] notation3 "∫ "(...)" in "s", "r:60:(scoped f => integral (Measure.restrict volume s) f) => r section Properties open ContinuousLinearMap MeasureTheory.SimpleFunc variable [NormedSpace ℝ E] variable {f : α → E} {m : MeasurableSpace α} {μ : Measure α} section Basic variable [hE : CompleteSpace E] theorem integral_eq (f : α → E) (hf : Integrable f μ) : ∫ a, f a ∂μ = L1.integral (hf.toL1 f) := by simp [integral, hE, hf] theorem integral_eq_setToFun (f : α → E) : ∫ a, f a ∂μ = setToFun μ (weightedSMul μ) (dominatedFinMeasAdditive_weightedSMul μ) f := by simp only [integral, hE, L1.integral]; rfl theorem L1.integral_eq_integral (f : α →₁[μ] E) : L1.integral f = ∫ a, f a ∂μ := by simp only [integral, L1.integral, integral_eq_setToFun] exact (L1.setToFun_eq_setToL1 (dominatedFinMeasAdditive_weightedSMul μ) f).symm theorem integral_undef {f : α → G} (h : ¬Integrable f μ) : ∫ a, f a ∂μ = 0 := by by_cases hG : CompleteSpace G · simp [integral, hG, h] · simp [integral, hG] theorem Integrable.of_integral_ne_zero {f : α → G} (h : ∫ a, f a ∂μ ≠ 0) : Integrable f μ := Not.imp_symm integral_undef h theorem integral_non_aestronglyMeasurable {f : α → G} (h : ¬AEStronglyMeasurable f μ) : ∫ a, f a ∂μ = 0 := integral_undef <| not_and_of_not_left _ h variable (α G) @[simp] theorem integral_zero : ∫ _ : α, (0 : G) ∂μ = 0 := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact setToFun_zero (dominatedFinMeasAdditive_weightedSMul μ) · simp [integral, hG] @[simp] theorem integral_zero' : integral μ (0 : α → G) = 0 := integral_zero α G lemma integral_indicator₂ {β : Type*} (f : β → α → G) (s : Set β) (b : β) : ∫ y, s.indicator (f · y) b ∂μ = s.indicator (fun x ↦ ∫ y, f x y ∂μ) b := by by_cases hb : b ∈ s <;> simp [hb] variable {α G} theorem integrable_of_integral_eq_one {f : α → ℝ} (h : ∫ x, f x ∂μ = 1) : Integrable f μ := .of_integral_ne_zero <| h ▸ one_ne_zero theorem integral_add {f g : α → G} (hf : Integrable f μ) (hg : Integrable g μ) : ∫ a, f a + g a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact setToFun_add (dominatedFinMeasAdditive_weightedSMul μ) hf hg · simp [integral, hG] theorem integral_add' {f g : α → G} (hf : Integrable f μ) (hg : Integrable g μ) : ∫ a, (f + g) a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := integral_add hf hg theorem integral_finset_sum {ι} (s : Finset ι) {f : ι → α → G} (hf : ∀ i ∈ s, Integrable (f i) μ) : ∫ a, ∑ i ∈ s, f i a ∂μ = ∑ i ∈ s, ∫ a, f i a ∂μ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact setToFun_finset_sum (dominatedFinMeasAdditive_weightedSMul _) s hf · simp [integral, hG] @[integral_simps] theorem integral_neg (f : α → G) : ∫ a, -f a ∂μ = -∫ a, f a ∂μ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact setToFun_neg (dominatedFinMeasAdditive_weightedSMul μ) f · simp [integral, hG] theorem integral_neg' (f : α → G) : ∫ a, (-f) a ∂μ = -∫ a, f a ∂μ := integral_neg f theorem integral_sub {f g : α → G} (hf : Integrable f μ) (hg : Integrable g μ) : ∫ a, f a - g a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact setToFun_sub (dominatedFinMeasAdditive_weightedSMul μ) hf hg · simp [integral, hG] theorem integral_sub' {f g : α → G} (hf : Integrable f μ) (hg : Integrable g μ) : ∫ a, (f - g) a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := integral_sub hf hg /-- The Bochner integral is linear. Note this requires `𝕜` to be a normed division ring, in order to ensure that for `c ≠ 0`, the function `c • f` is integrable iff `f` is. For an analogous statement for more general rings with an *a priori* integrability assumption on `f`, see `MeasureTheory.Integrable.integral_smul`. -/ @[integral_simps] theorem integral_smul [Module 𝕜 G] [NormSMulClass 𝕜 G] [SMulCommClass ℝ 𝕜 G] (c : 𝕜) (f : α → G) : ∫ a, c • f a ∂μ = c • ∫ a, f a ∂μ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact setToFun_smul (dominatedFinMeasAdditive_weightedSMul μ) weightedSMul_smul c f · simp [integral, hG] theorem Integrable.integral_smul {R : Type*} [NormedRing R] [Module R G] [IsBoundedSMul R G] [SMulCommClass ℝ R G] (c : R) {f : α → G} (hf : Integrable f μ) : ∫ a, c • f a ∂μ = c • ∫ a, f a ∂μ := by by_cases hG : CompleteSpace G · simpa only [integral, hG, hf, hf.fun_smul c] using L1.integral_smul c (toL1 f hf) · simp [integral, hG] theorem integral_const_mul {L : Type*} [RCLike L] (r : L) (f : α → L) : ∫ a, r * f a ∂μ = r * ∫ a, f a ∂μ := integral_smul r f @[deprecated (since := "2025-04-27")] alias integral_mul_left := integral_const_mul theorem integral_mul_const {L : Type*} [RCLike L] (r : L) (f : α → L) : ∫ a, f a * r ∂μ = (∫ a, f a ∂μ) * r := by simp only [mul_comm, integral_const_mul r f] @[deprecated (since := "2025-04-27")] alias integral_mul_right := integral_mul_const theorem integral_div {L : Type*} [RCLike L] (r : L) (f : α → L) : ∫ a, f a / r ∂μ = (∫ a, f a ∂μ) / r := by simpa only [← div_eq_mul_inv] using integral_mul_const r⁻¹ f theorem integral_congr_ae {f g : α → G} (h : f =ᵐ[μ] g) : ∫ a, f a ∂μ = ∫ a, g a ∂μ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact setToFun_congr_ae (dominatedFinMeasAdditive_weightedSMul μ) h · simp [integral, hG] lemma integral_congr_ae₂ {β : Type*} {_ : MeasurableSpace β} {ν : Measure β} {f g : α → β → G} (h : ∀ᵐ a ∂μ, f a =ᵐ[ν] g a) : ∫ a, ∫ b, f a b ∂ν ∂μ = ∫ a, ∫ b, g a b ∂ν ∂μ := by apply integral_congr_ae filter_upwards [h] with _ ha apply integral_congr_ae filter_upwards [ha] with _ hb using hb @[simp] theorem L1.integral_of_fun_eq_integral' {f : α → G} (hf : Integrable f μ) : ∫ a, (AEEqFun.mk f hf.aestronglyMeasurable) a ∂μ = ∫ a, f a ∂μ := by by_cases hG : CompleteSpace G · simp only [MeasureTheory.integral, hG, L1.integral] exact setToFun_toL1 (dominatedFinMeasAdditive_weightedSMul μ) hf · simp [MeasureTheory.integral, hG] theorem L1.integral_of_fun_eq_integral {f : α → G} (hf : Integrable f μ) : ∫ a, (hf.toL1 f) a ∂μ = ∫ a, f a ∂μ := by simp [hf] @[continuity] theorem continuous_integral : Continuous fun f : α →₁[μ] G => ∫ a, f a ∂μ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact continuous_setToFun (dominatedFinMeasAdditive_weightedSMul μ) · simp [integral, hG, continuous_const] theorem norm_integral_le_lintegral_norm (f : α → G) : ‖∫ a, f a ∂μ‖ ≤ ENNReal.toReal (∫⁻ a, ENNReal.ofReal ‖f a‖ ∂μ) := by by_cases hG : CompleteSpace G · by_cases hf : Integrable f μ · rw [integral_eq f hf, ← Integrable.norm_toL1_eq_lintegral_norm f hf] exact L1.norm_integral_le _ · rw [integral_undef hf, norm_zero]; exact toReal_nonneg · simp [integral, hG] theorem enorm_integral_le_lintegral_enorm (f : α → G) : ‖∫ a, f a ∂μ‖ₑ ≤ ∫⁻ a, ‖f a‖ₑ ∂μ := by simp_rw [← ofReal_norm_eq_enorm] apply ENNReal.ofReal_le_of_le_toReal exact norm_integral_le_lintegral_norm f theorem integral_eq_zero_of_ae {f : α → G} (hf : f =ᵐ[μ] 0) : ∫ a, f a ∂μ = 0 := by simp [integral_congr_ae hf, integral_zero] /-- If `f` has finite integral, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ theorem HasFiniteIntegral.tendsto_setIntegral_nhds_zero {ι} {f : α → G} (hf : HasFiniteIntegral f μ) {l : Filter ι} {s : ι → Set α} (hs : Tendsto (μ ∘ s) l (𝓝 0)) : Tendsto (fun i => ∫ x in s i, f x ∂μ) l (𝓝 0) := by rw [tendsto_zero_iff_norm_tendsto_zero] simp_rw [← coe_nnnorm, ← NNReal.coe_zero, NNReal.tendsto_coe, ← ENNReal.tendsto_coe, ENNReal.coe_zero] exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds (tendsto_setLIntegral_zero (ne_of_lt hf) hs) (fun i => zero_le _) fun i => enorm_integral_le_lintegral_enorm _ /-- If `f` is integrable, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ theorem Integrable.tendsto_setIntegral_nhds_zero {ι} {f : α → G} (hf : Integrable f μ) {l : Filter ι} {s : ι → Set α} (hs : Tendsto (μ ∘ s) l (𝓝 0)) : Tendsto (fun i => ∫ x in s i, f x ∂μ) l (𝓝 0) := hf.2.tendsto_setIntegral_nhds_zero hs /-- If `F i → f` in `L1`, then `∫ x, F i x ∂μ → ∫ x, f x ∂μ`. -/ theorem tendsto_integral_of_L1 {ι} (f : α → G) (hfi : Integrable f μ) {F : ι → α → G} {l : Filter ι} (hFi : ∀ᶠ i in l, Integrable (F i) μ) (hF : Tendsto (fun i => ∫⁻ x, ‖F i x - f x‖ₑ ∂μ) l (𝓝 0)) : Tendsto (fun i => ∫ x, F i x ∂μ) l (𝓝 <| ∫ x, f x ∂μ) := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact tendsto_setToFun_of_L1 (dominatedFinMeasAdditive_weightedSMul μ) f hfi hFi hF · simp [integral, hG, tendsto_const_nhds] /-- If `F i → f` in `L1`, then `∫ x, F i x ∂μ → ∫ x, f x ∂μ`. -/ lemma tendsto_integral_of_L1' {ι} (f : α → G) (hfi : Integrable f μ) {F : ι → α → G} {l : Filter ι} (hFi : ∀ᶠ i in l, Integrable (F i) μ) (hF : Tendsto (fun i ↦ eLpNorm (F i - f) 1 μ) l (𝓝 0)) : Tendsto (fun i ↦ ∫ x, F i x ∂μ) l (𝓝 (∫ x, f x ∂μ)) := by refine tendsto_integral_of_L1 f hfi hFi ?_ simp_rw [eLpNorm_one_eq_lintegral_enorm, Pi.sub_apply] at hF exact hF /-- If `F i → f` in `L1`, then `∫ x in s, F i x ∂μ → ∫ x in s, f x ∂μ`. -/ lemma tendsto_setIntegral_of_L1 {ι} (f : α → G) (hfi : Integrable f μ) {F : ι → α → G} {l : Filter ι} (hFi : ∀ᶠ i in l, Integrable (F i) μ) (hF : Tendsto (fun i ↦ ∫⁻ x, ‖F i x - f x‖ₑ ∂μ) l (𝓝 0)) (s : Set α) : Tendsto (fun i ↦ ∫ x in s, F i x ∂μ) l (𝓝 (∫ x in s, f x ∂μ)) := by refine tendsto_integral_of_L1 f hfi.restrict ?_ ?_ · filter_upwards [hFi] with i hi using hi.restrict · simp_rw [← eLpNorm_one_eq_lintegral_enorm] at hF ⊢ exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds hF (fun _ ↦ zero_le') (fun _ ↦ eLpNorm_mono_measure _ Measure.restrict_le_self) /-- If `F i → f` in `L1`, then `∫ x in s, F i x ∂μ → ∫ x in s, f x ∂μ`. -/ lemma tendsto_setIntegral_of_L1' {ι} (f : α → G) (hfi : Integrable f μ) {F : ι → α → G} {l : Filter ι} (hFi : ∀ᶠ i in l, Integrable (F i) μ) (hF : Tendsto (fun i ↦ eLpNorm (F i - f) 1 μ) l (𝓝 0)) (s : Set α) : Tendsto (fun i ↦ ∫ x in s, F i x ∂μ) l (𝓝 (∫ x in s, f x ∂μ)) := by refine tendsto_setIntegral_of_L1 f hfi hFi ?_ s simp_rw [eLpNorm_one_eq_lintegral_enorm, Pi.sub_apply] at hF exact hF variable {X : Type*} [TopologicalSpace X] [FirstCountableTopology X] theorem continuousWithinAt_of_dominated {F : X → α → G} {x₀ : X} {bound : α → ℝ} {s : Set X} (hF_meas : ∀ᶠ x in 𝓝[s] x₀, AEStronglyMeasurable (F x) μ) (h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ a ∂μ, ‖F x a‖ ≤ bound a) (bound_integrable : Integrable bound μ) (h_cont : ∀ᵐ a ∂μ, ContinuousWithinAt (fun x => F x a) s x₀) : ContinuousWithinAt (fun x => ∫ a, F x a ∂μ) s x₀ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact continuousWithinAt_setToFun_of_dominated (dominatedFinMeasAdditive_weightedSMul μ) hF_meas h_bound bound_integrable h_cont · simp [integral, hG, continuousWithinAt_const] theorem continuousAt_of_dominated {F : X → α → G} {x₀ : X} {bound : α → ℝ} (hF_meas : ∀ᶠ x in 𝓝 x₀, AEStronglyMeasurable (F x) μ) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ a ∂μ, ‖F x a‖ ≤ bound a) (bound_integrable : Integrable bound μ) (h_cont : ∀ᵐ a ∂μ, ContinuousAt (fun x => F x a) x₀) : ContinuousAt (fun x => ∫ a, F x a ∂μ) x₀ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact continuousAt_setToFun_of_dominated (dominatedFinMeasAdditive_weightedSMul μ) hF_meas h_bound bound_integrable h_cont · simp [integral, hG, continuousAt_const] theorem continuousOn_of_dominated {F : X → α → G} {bound : α → ℝ} {s : Set X} (hF_meas : ∀ x ∈ s, AEStronglyMeasurable (F x) μ) (h_bound : ∀ x ∈ s, ∀ᵐ a ∂μ, ‖F x a‖ ≤ bound a) (bound_integrable : Integrable bound μ) (h_cont : ∀ᵐ a ∂μ, ContinuousOn (fun x => F x a) s) : ContinuousOn (fun x => ∫ a, F x a ∂μ) s := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact continuousOn_setToFun_of_dominated (dominatedFinMeasAdditive_weightedSMul μ) hF_meas h_bound bound_integrable h_cont · simp [integral, hG, continuousOn_const] theorem continuous_of_dominated {F : X → α → G} {bound : α → ℝ} (hF_meas : ∀ x, AEStronglyMeasurable (F x) μ) (h_bound : ∀ x, ∀ᵐ a ∂μ, ‖F x a‖ ≤ bound a) (bound_integrable : Integrable bound μ) (h_cont : ∀ᵐ a ∂μ, Continuous fun x => F x a) : Continuous fun x => ∫ a, F x a ∂μ := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact continuous_setToFun_of_dominated (dominatedFinMeasAdditive_weightedSMul μ) hF_meas h_bound bound_integrable h_cont · simp [integral, hG, continuous_const] /-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the integral of the positive part of `f` and the integral of the negative part of `f`. -/ theorem integral_eq_lintegral_pos_part_sub_lintegral_neg_part {f : α → ℝ} (hf : Integrable f μ) : ∫ a, f a ∂μ = ENNReal.toReal (∫⁻ a, .ofReal (f a) ∂μ) - ENNReal.toReal (∫⁻ a, .ofReal (-f a) ∂μ) := by let f₁ := hf.toL1 f -- Go to the `L¹` space have eq₁ : ENNReal.toReal (∫⁻ a, ENNReal.ofReal (f a) ∂μ) = ‖Lp.posPart f₁‖ := by rw [L1.norm_def] congr 1 apply lintegral_congr_ae filter_upwards [Lp.coeFn_posPart f₁, hf.coeFn_toL1] with _ h₁ h₂ rw [h₁, h₂, ENNReal.ofReal] congr 1 apply NNReal.eq rw [Real.nnnorm_of_nonneg (le_max_right _ _)] rw [Real.coe_toNNReal', NNReal.coe_mk] -- Go to the `L¹` space have eq₂ : ENNReal.toReal (∫⁻ a, ENNReal.ofReal (-f a) ∂μ) = ‖Lp.negPart f₁‖ := by rw [L1.norm_def] congr 1 apply lintegral_congr_ae filter_upwards [Lp.coeFn_negPart f₁, hf.coeFn_toL1] with _ h₁ h₂ rw [h₁, h₂, ENNReal.ofReal] congr 1 apply NNReal.eq simp only [Real.coe_toNNReal', coe_nnnorm, nnnorm_neg] rw [Real.norm_of_nonpos (min_le_right _ _), ← max_neg_neg, neg_zero] rw [eq₁, eq₂, integral, dif_pos, dif_pos] exact L1.integral_eq_norm_posPart_sub _ theorem integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfm : AEStronglyMeasurable f μ) : ∫ a, f a ∂μ = ENNReal.toReal (∫⁻ a, ENNReal.ofReal (f a) ∂μ) := by by_cases hfi : Integrable f μ · rw [integral_eq_lintegral_pos_part_sub_lintegral_neg_part hfi] have h_min : ∫⁻ a, ENNReal.ofReal (-f a) ∂μ = 0 := by rw [lintegral_eq_zero_iff'] · refine hf.mono ?_ simp only [Pi.zero_apply] intro a h simp only [h, neg_nonpos, ofReal_eq_zero] · exact measurable_ofReal.comp_aemeasurable hfm.aemeasurable.neg rw [h_min, toReal_zero, _root_.sub_zero] · rw [integral_undef hfi] simp_rw [Integrable, hfm, hasFiniteIntegral_iff_norm, lt_top_iff_ne_top, Ne, true_and, Classical.not_not] at hfi have : ∫⁻ a : α, ENNReal.ofReal (f a) ∂μ = ∫⁻ a, ENNReal.ofReal ‖f a‖ ∂μ := by refine lintegral_congr_ae (hf.mono fun a h => ?_) dsimp only rw [Real.norm_eq_abs, abs_of_nonneg h] rw [this, hfi, toReal_top] theorem integral_norm_eq_lintegral_enorm {P : Type*} [NormedAddCommGroup P] {f : α → P} (hf : AEStronglyMeasurable f μ) : ∫ x, ‖f x‖ ∂μ = (∫⁻ x, ‖f x‖ₑ ∂μ).toReal := by rw [integral_eq_lintegral_of_nonneg_ae _ hf.norm] · simp_rw [ofReal_norm_eq_enorm] · filter_upwards; simp_rw [Pi.zero_apply, norm_nonneg, imp_true_iff] theorem ofReal_integral_norm_eq_lintegral_enorm {P : Type*} [NormedAddCommGroup P] {f : α → P} (hf : Integrable f μ) : ENNReal.ofReal (∫ x, ‖f x‖ ∂μ) = ∫⁻ x, ‖f x‖ₑ ∂μ := by rw [integral_norm_eq_lintegral_enorm hf.aestronglyMeasurable, ENNReal.ofReal_toReal] exact lt_top_iff_ne_top.mp (hasFiniteIntegral_iff_enorm.mpr hf.2) theorem SimpleFunc.integral_eq_integral (f : α →ₛ E) (hfi : Integrable f μ) : f.integral μ = ∫ x, f x ∂μ := by rw [MeasureTheory.integral_eq f hfi, ← L1.SimpleFunc.toLp_one_eq_toL1, L1.SimpleFunc.integral_L1_eq_integral, L1.SimpleFunc.integral_eq_integral] exact SimpleFunc.integral_congr hfi (Lp.simpleFunc.toSimpleFunc_toLp _ _).symm theorem SimpleFunc.integral_eq_sum (f : α →ₛ E) (hfi : Integrable f μ) : ∫ x, f x ∂μ = ∑ x ∈ f.range, μ.real (f ⁻¹' {x}) • x := by rw [← f.integral_eq_integral hfi, SimpleFunc.integral, ← SimpleFunc.integral_eq]; rfl theorem tendsto_integral_approxOn_of_measurable [MeasurableSpace E] [BorelSpace E] {f : α → E} {s : Set E} [SeparableSpace s] (hfi : Integrable f μ) (hfm : Measurable f) (hs : ∀ᵐ x ∂μ, f x ∈ closure s) {y₀ : E} (h₀ : y₀ ∈ s) (h₀i : Integrable (fun _ => y₀) μ) : Tendsto (fun n => (SimpleFunc.approxOn f hfm s y₀ h₀ n).integral μ) atTop (𝓝 <| ∫ x, f x ∂μ) := by have hfi' := SimpleFunc.integrable_approxOn hfm hfi h₀ h₀i simp only [SimpleFunc.integral_eq_integral _ (hfi' _), integral, hE, L1.integral] exact tendsto_setToFun_approxOn_of_measurable (dominatedFinMeasAdditive_weightedSMul μ) hfi hfm hs h₀ h₀i theorem tendsto_integral_approxOn_of_measurable_of_range_subset [MeasurableSpace E] [BorelSpace E] {f : α → E} (fmeas : Measurable f) (hf : Integrable f μ) (s : Set E) [SeparableSpace s] (hs : range f ∪ {0} ⊆ s) : Tendsto (fun n => (SimpleFunc.approxOn f fmeas s 0 (hs <| by simp) n).integral μ) atTop (𝓝 <| ∫ x, f x ∂μ) := by apply tendsto_integral_approxOn_of_measurable hf fmeas _ _ (integrable_zero _ _ _) exact Eventually.of_forall fun x => subset_closure (hs (Set.mem_union_left _ (mem_range_self _))) -- We redeclare `E` here to temporarily avoid -- the `[CompleteSpace E]` and `[NormedSpace ℝ E]` instances. theorem tendsto_integral_norm_approxOn_sub {E : Type*} [NormedAddCommGroup E] [MeasurableSpace E] [BorelSpace E] {f : α → E} (fmeas : Measurable f) (hf : Integrable f μ) [SeparableSpace (range f ∪ {0} : Set E)] : Tendsto (fun n ↦ ∫ x, ‖SimpleFunc.approxOn f fmeas (range f ∪ {0}) 0 (by simp) n x - f x‖ ∂μ) atTop (𝓝 0) := by convert (tendsto_toReal zero_ne_top).comp (tendsto_approxOn_range_L1_enorm fmeas hf) with n rw [integral_norm_eq_lintegral_enorm] · simp · apply (SimpleFunc.aestronglyMeasurable _).sub apply (stronglyMeasurable_iff_measurable_separable.2 ⟨fmeas, ?_⟩).aestronglyMeasurable exact .mono (.of_subtype (range f ∪ {0})) subset_union_left theorem integral_eq_integral_pos_part_sub_integral_neg_part {f : α → ℝ} (hf : Integrable f μ) : ∫ a, f a ∂μ = ∫ a, (Real.toNNReal (f a) : ℝ) ∂μ - ∫ a, (Real.toNNReal (-f a) : ℝ) ∂μ := by rw [← integral_sub hf.real_toNNReal] · simp · exact hf.neg.real_toNNReal end Basic section Order variable [PartialOrder E] [IsOrderedAddMonoid E] [IsOrderedModule ℝ E] [OrderClosedTopology E] /-- The integral of a function which is nonnegative almost everywhere is nonnegative. -/ lemma integral_nonneg_of_ae {f : α → E} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ x, f x ∂μ := by by_cases hE : CompleteSpace E · exact integral_eq_setToFun f ▸ setToFun_nonneg (dominatedFinMeasAdditive_weightedSMul μ) (fun s _ _ => weightedSMul_nonneg s) hf · simp [integral, hE] lemma integral_nonneg {f : α → E} (hf : 0 ≤ f) : 0 ≤ ∫ x, f x ∂μ := integral_nonneg_of_ae (ae_of_all _ hf) lemma integral_nonpos_of_ae {f : α → E} (hf : f ≤ᵐ[μ] 0) : ∫ x, f x ∂μ ≤ 0 := by rw [← neg_nonneg, ← integral_neg] refine integral_nonneg_of_ae ?_ filter_upwards [hf] with x hx simpa lemma integral_nonpos {f : α → E} (hf : f ≤ 0) : ∫ x, f x ∂μ ≤ 0 := integral_nonpos_of_ae (ae_of_all _ hf) lemma integral_mono_ae {f g : α → E} (hf : Integrable f μ) (hg : Integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ := by rw [← sub_nonneg, ← integral_sub hg hf] refine integral_nonneg_of_ae ?_ filter_upwards [h] with x hx simpa @[gcongr, mono] lemma integral_mono {f g : α → E} (hf : Integrable f μ) (hg : Integrable g μ) (h : f ≤ g) : ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ := integral_mono_ae hf hg (ae_of_all _ h) lemma integral_mono_of_nonneg {f g : α → E} (hf : 0 ≤ᵐ[μ] f) (hgi : Integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := by by_cases hfi : Integrable f μ · exact integral_mono_ae hfi hgi h · exact integral_undef hfi ▸ integral_nonneg_of_ae (hf.trans h) @[gcongr] lemma integral_mono_measure {f : α → E} {ν : Measure α} (hle : μ ≤ ν) (hf : 0 ≤ᵐ[ν] f) (hfi : Integrable f ν) : ∫ (a : α), f a ∂μ ≤ ∫ (a : α), f a ∂ν := by by_cases hE : CompleteSpace E swap; · simp [integral, hE] borelize E obtain ⟨g, hg, hg_nonneg, hfg⟩ := hfi.1.exists_stronglyMeasurable_range_subset isClosed_Ici.measurableSet (Set.nonempty_Ici (a := 0)) hf rw [integrable_congr hfg] at hfi simp only [integral_congr_ae hfg, integral_congr_ae (ae_mono hle hfg)] have _ := hg.separableSpace_range_union_singleton (b := 0) have h₁ := tendsto_integral_approxOn_of_measurable_of_range_subset hg.measurable hfi _ le_rfl have h₂ := tendsto_integral_approxOn_of_measurable_of_range_subset hg.measurable (hfi.mono_measure hle) _ le_rfl apply le_of_tendsto_of_tendsto' h₂ h₁ exact fun n ↦ SimpleFunc.integral_mono_measure (Eventually.of_forall <| SimpleFunc.approxOn_range_nonneg hg_nonneg n) hle (SimpleFunc.integrable_approxOn_range _ hfi n) lemma integral_monotoneOn_of_integrand_ae {β : Type*} [Preorder β] {f : α → β → E} {s : Set β} (hf_mono : ∀ᵐ x ∂μ, MonotoneOn (f x) s) (hf_int : ∀ a ∈ s, Integrable (f · a) μ) : MonotoneOn (fun b => ∫ x, f x b ∂μ) s := by intro a ha b hb hab refine integral_mono_ae (hf_int a ha) (hf_int b hb) ?_ filter_upwards [hf_mono] with x hx exact hx ha hb hab lemma integral_antitoneOn_of_integrand_ae {β : Type*} [Preorder β] {f : α → β → E} {s : Set β} (hf_anti : ∀ᵐ x ∂μ, AntitoneOn (f x) s) (hf_int : ∀ a ∈ s, Integrable (f · a) μ) : AntitoneOn (fun b => ∫ x, f x b ∂μ) s := by intro a ha b hb hab refine integral_mono_ae (hf_int b hb) (hf_int a ha) ?_ filter_upwards [hf_anti] with x hx exact hx ha hb hab lemma integral_convexOn_of_integrand_ae {β : Type*} [AddCommMonoid β] [Module ℝ β] {f : α → β → E} {s : Set β} (hs : Convex ℝ s) (hf_conv : ∀ᵐ x ∂μ, ConvexOn ℝ s (f x)) (hf_int : ∀ a ∈ s, Integrable (f · a) μ) : ConvexOn ℝ s (fun b => ∫ x, f x b ∂μ) := by refine ⟨hs, ?_⟩ intro a ha b hb p q hp hq hpq calc ∫ x, f x (p • a + q • b) ∂μ ≤ ∫ x, p • f x a + q • f x b ∂μ := by refine integral_mono_ae ?lhs ?rhs ?ae_le case lhs => refine hf_int _ ?_ rw [convex_iff_add_mem] at hs exact hs ha hb hp hq hpq case rhs => fun_prop (disch := aesop) case ae_le => filter_upwards [hf_conv] with x hx exact hx.2 ha hb hp hq hpq _ = ∫ x, p • f x a ∂μ + ∫ x, q • f x b ∂μ := by apply integral_add all_goals fun_prop (disch := aesop) _ = p • ∫ x, f x a ∂μ + q • ∫ x, f x b ∂μ := by simp [integral_smul] lemma integral_concaveOn_of_integrand_ae {β : Type*} [AddCommMonoid β] [Module ℝ β] {f : α → β → E} {s : Set β} (hs : Convex ℝ s) (hf_conc : ∀ᵐ x ∂μ, ConcaveOn ℝ s (f x)) (hf_int : ∀ a ∈ s, Integrable (f · a) μ) : ConcaveOn ℝ s (fun b => ∫ x, f x b ∂μ) := by simp_rw [← neg_convexOn_iff] at hf_conc ⊢ simpa only [Pi.neg_apply, integral_neg] using integral_convexOn_of_integrand_ae hs hf_conc (hf_int · · |>.neg) end Order variable [hE : CompleteSpace E] theorem lintegral_coe_eq_integral (f : α → ℝ≥0) (hfi : Integrable (fun x => (f x : ℝ)) μ) : ∫⁻ a, f a ∂μ = ENNReal.ofReal (∫ a, f a ∂μ) := by simp_rw [integral_eq_lintegral_of_nonneg_ae (Eventually.of_forall fun x => (f x).coe_nonneg) hfi.aestronglyMeasurable, ← ENNReal.coe_nnreal_eq] rw [ENNReal.ofReal_toReal] simpa [← lt_top_iff_ne_top, hasFiniteIntegral_iff_enorm, NNReal.enorm_eq] using hfi.hasFiniteIntegral theorem ofReal_integral_eq_lintegral_ofReal {f : α → ℝ} (hfi : Integrable f μ) (f_nn : 0 ≤ᵐ[μ] f) : ENNReal.ofReal (∫ x, f x ∂μ) = ∫⁻ x, ENNReal.ofReal (f x) ∂μ := by have : f =ᵐ[μ] (‖f ·‖) := f_nn.mono fun _x hx ↦ (abs_of_nonneg hx).symm simp_rw [integral_congr_ae this, ofReal_integral_norm_eq_lintegral_enorm hfi, ← ofReal_norm_eq_enorm] exact lintegral_congr_ae (this.symm.fun_comp ENNReal.ofReal) theorem integral_toReal {f : α → ℝ≥0∞} (hfm : AEMeasurable f μ) (hf : ∀ᵐ x ∂μ, f x < ∞) : ∫ a, (f a).toReal ∂μ = (∫⁻ a, f a ∂μ).toReal := by rw [integral_eq_lintegral_of_nonneg_ae _ hfm.ennreal_toReal.aestronglyMeasurable, lintegral_congr_ae (ofReal_toReal_ae_eq hf)] exact Eventually.of_forall fun x => ENNReal.toReal_nonneg theorem lintegral_coe_le_coe_iff_integral_le {f : α → ℝ≥0} (hfi : Integrable (fun x => (f x : ℝ)) μ) {b : ℝ≥0} : ∫⁻ a, f a ∂μ ≤ b ↔ ∫ a, (f a : ℝ) ∂μ ≤ b := by rw [lintegral_coe_eq_integral f hfi, ENNReal.ofReal, ENNReal.coe_le_coe, Real.toNNReal_le_iff_le_coe] theorem integral_coe_le_of_lintegral_coe_le {f : α → ℝ≥0} {b : ℝ≥0} (h : ∫⁻ a, f a ∂μ ≤ b) : ∫ a, (f a : ℝ) ∂μ ≤ b := by by_cases hf : Integrable (fun a => (f a : ℝ)) μ · exact (lintegral_coe_le_coe_iff_integral_le hf).1 h · rw [integral_undef hf]; exact b.2 theorem integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : Integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := by simp_rw [integral_eq_lintegral_of_nonneg_ae hf hfi.1, ENNReal.toReal_eq_zero_iff, ← ENNReal.not_lt_top, ← hasFiniteIntegral_iff_ofReal hf, hfi.2, not_true_eq_false, or_false] rw [lintegral_eq_zero_iff'] · rw [← hf.ge_iff_eq', Filter.EventuallyEq, Filter.EventuallyLE] simp only [Pi.zero_apply, ofReal_eq_zero] · exact (ENNReal.measurable_ofReal.comp_aemeasurable hfi.1.aemeasurable) theorem integral_eq_zero_iff_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : Integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := integral_eq_zero_iff_of_nonneg_ae (Eventually.of_forall hf) hfi lemma integral_eq_iff_of_ae_le {f g : α → ℝ} (hf : Integrable f μ) (hg : Integrable g μ) (hfg : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ = ∫ a, g a ∂μ ↔ f =ᵐ[μ] g := by refine ⟨fun h_le ↦ EventuallyEq.symm ?_, fun h ↦ integral_congr_ae h⟩ rw [← sub_ae_eq_zero, ← integral_eq_zero_iff_of_nonneg_ae ((sub_nonneg_ae _ _).mpr hfg) (hg.sub hf)] simpa [Pi.sub_apply, integral_sub hg hf, sub_eq_zero, eq_comm] theorem integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : Integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (Function.support f) := by simp_rw [(integral_nonneg_of_ae hf).lt_iff_ne, pos_iff_ne_zero, Ne, @eq_comm ℝ 0, integral_eq_zero_iff_of_nonneg_ae hf hfi, Filter.EventuallyEq, ae_iff, Pi.zero_apply, Function.support] theorem integral_pos_iff_support_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : Integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (Function.support f) := integral_pos_iff_support_of_nonneg_ae (Eventually.of_forall hf) hfi lemma integral_exp_pos {μ : Measure α} {f : α → ℝ} [hμ : NeZero μ] (hf : Integrable (fun x ↦ Real.exp (f x)) μ) : 0 < ∫ x, Real.exp (f x) ∂μ := by rw [integral_pos_iff_support_of_nonneg (fun x ↦ (Real.exp_pos _).le) hf] suffices (Function.support fun x ↦ Real.exp (f x)) = Set.univ by simp [this, hμ.out] ext1 x simp only [Function.mem_support, ne_eq, (Real.exp_pos _).ne', not_false_eq_true, Set.mem_univ] /-- Monotone convergence theorem for real-valued functions and Bochner integrals -/ lemma integral_tendsto_of_tendsto_of_monotone {μ : Measure α} {f : ℕ → α → ℝ} {F : α → ℝ} (hf : ∀ n, Integrable (f n) μ) (hF : Integrable F μ) (h_mono : ∀ᵐ x ∂μ, Monotone fun n ↦ f n x) (h_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n ↦ f n x) atTop (𝓝 (F x))) : Tendsto (fun n ↦ ∫ x, f n x ∂μ) atTop (𝓝 (∫ x, F x ∂μ)) := by -- switch from the Bochner to the Lebesgue integral let f' := fun n x ↦ f n x - f 0 x have hf'_nonneg : ∀ᵐ x ∂μ, ∀ n, 0 ≤ f' n x := by filter_upwards [h_mono] with a ha n simp [f', ha (zero_le n)] have hf'_meas : ∀ n, Integrable (f' n) μ := fun n ↦ (hf n).sub (hf 0) suffices Tendsto (fun n ↦ ∫ x, f' n x ∂μ) atTop (𝓝 (∫ x, (F - f 0) x ∂μ)) by simp_rw [f', integral_sub (hf _) (hf _), integral_sub' hF (hf 0), tendsto_sub_const_iff] at this exact this have hF_ge : 0 ≤ᵐ[μ] fun x ↦ (F - f 0) x := by filter_upwards [h_tendsto, h_mono] with x hx_tendsto hx_mono simp only [Pi.zero_apply, Pi.sub_apply, sub_nonneg] exact ge_of_tendsto' hx_tendsto (fun n ↦ hx_mono (zero_le _)) rw [ae_all_iff] at hf'_nonneg simp_rw [integral_eq_lintegral_of_nonneg_ae (hf'_nonneg _) (hf'_meas _).1] rw [integral_eq_lintegral_of_nonneg_ae hF_ge (hF.1.sub (hf 0).1)] have h_cont := ENNReal.continuousAt_toReal (x := ∫⁻ a, ENNReal.ofReal ((F - f 0) a) ∂μ) ?_ swap · rw [← ofReal_integral_eq_lintegral_ofReal (hF.sub (hf 0)) hF_ge] finiteness refine h_cont.tendsto.comp ?_ -- use the result for the Lebesgue integral refine lintegral_tendsto_of_tendsto_of_monotone ?_ ?_ ?_ · exact fun n ↦ ((hf n).sub (hf 0)).aemeasurable.ennreal_ofReal · filter_upwards [h_mono] with x hx n m hnm refine ENNReal.ofReal_le_ofReal ?_ simp only [f', tsub_le_iff_right, sub_add_cancel] exact hx hnm · filter_upwards [h_tendsto] with x hx refine (ENNReal.continuous_ofReal.tendsto _).comp ?_ simp only [Pi.sub_apply] exact Tendsto.sub hx tendsto_const_nhds /-- Monotone convergence theorem for real-valued functions and Bochner integrals -/ lemma integral_tendsto_of_tendsto_of_antitone {μ : Measure α} {f : ℕ → α → ℝ} {F : α → ℝ} (hf : ∀ n, Integrable (f n) μ) (hF : Integrable F μ) (h_mono : ∀ᵐ x ∂μ, Antitone fun n ↦ f n x) (h_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n ↦ f n x) atTop (𝓝 (F x))) : Tendsto (fun n ↦ ∫ x, f n x ∂μ) atTop (𝓝 (∫ x, F x ∂μ)) := by suffices Tendsto (fun n ↦ ∫ x, -f n x ∂μ) atTop (𝓝 (∫ x, -F x ∂μ)) by suffices Tendsto (fun n ↦ ∫ x, - -f n x ∂μ) atTop (𝓝 (∫ x, - -F x ∂μ)) by simpa [neg_neg] using this convert this.neg <;> rw [integral_neg] refine integral_tendsto_of_tendsto_of_monotone (fun n ↦ (hf n).neg) hF.neg ?_ ?_ · filter_upwards [h_mono] with x hx n m hnm using neg_le_neg_iff.mpr <| hx hnm · filter_upwards [h_tendsto] with x hx using hx.neg /-- If a monotone sequence of functions has an upper bound and the sequence of integrals of these functions tends to the integral of the upper bound, then the sequence of functions converges almost everywhere to the upper bound. -/ lemma tendsto_of_integral_tendsto_of_monotone {μ : Measure α} {f : ℕ → α → ℝ} {F : α → ℝ} (hf_int : ∀ n, Integrable (f n) μ) (hF_int : Integrable F μ) (hf_tendsto : Tendsto (fun i ↦ ∫ a, f i a ∂μ) atTop (𝓝 (∫ a, F a ∂μ))) (hf_mono : ∀ᵐ a ∂μ, Monotone (fun i ↦ f i a)) (hf_bound : ∀ᵐ a ∂μ, ∀ i, f i a ≤ F a) : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F a)) := by -- reduce to the `ℝ≥0∞` case let f' : ℕ → α → ℝ≥0∞ := fun n a ↦ ENNReal.ofReal (f n a - f 0 a) let F' : α → ℝ≥0∞ := fun a ↦ ENNReal.ofReal (F a - f 0 a) have hf'_int_eq : ∀ i, ∫⁻ a, f' i a ∂μ = ENNReal.ofReal (∫ a, f i a ∂μ - ∫ a, f 0 a ∂μ) := by intro i unfold f' rw [← ofReal_integral_eq_lintegral_ofReal, integral_sub (hf_int i) (hf_int 0)] · exact (hf_int i).sub (hf_int 0) · filter_upwards [hf_mono] with a h_mono simp [h_mono (zero_le i)] have hF'_int_eq : ∫⁻ a, F' a ∂μ = ENNReal.ofReal (∫ a, F a ∂μ - ∫ a, f 0 a ∂μ) := by unfold F' rw [← ofReal_integral_eq_lintegral_ofReal, integral_sub hF_int (hf_int 0)] · exact hF_int.sub (hf_int 0) · filter_upwards [hf_bound] with a h_bound simp [h_bound 0] have h_tendsto : Tendsto (fun i ↦ ∫⁻ a, f' i a ∂μ) atTop (𝓝 (∫⁻ a, F' a ∂μ)) := by simp_rw [hf'_int_eq, hF'_int_eq] refine (ENNReal.continuous_ofReal.tendsto _).comp ?_ rwa [tendsto_sub_const_iff] have h_mono : ∀ᵐ a ∂μ, Monotone (fun i ↦ f' i a) := by filter_upwards [hf_mono] with a ha_mono i j hij refine ENNReal.ofReal_le_ofReal ?_ simp [ha_mono hij] have h_bound : ∀ᵐ a ∂μ, ∀ i, f' i a ≤ F' a := by filter_upwards [hf_bound] with a ha_bound i refine ENNReal.ofReal_le_ofReal ?_ simp only [tsub_le_iff_right, sub_add_cancel, ha_bound i] -- use the corresponding lemma for `ℝ≥0∞` have h := tendsto_of_lintegral_tendsto_of_monotone ?_ h_tendsto h_mono h_bound ?_ rotate_left · exact (hF_int.1.aemeasurable.sub (hf_int 0).1.aemeasurable).ennreal_ofReal · exact ((lintegral_ofReal_le_lintegral_enorm _).trans_lt (hF_int.sub (hf_int 0)).2).ne filter_upwards [h, hf_mono, hf_bound] with a ha ha_mono ha_bound have h1 : (fun i ↦ f i a) = fun i ↦ (f' i a).toReal + f 0 a := by unfold f' ext i rw [ENNReal.toReal_ofReal] · abel · simp [ha_mono (zero_le i)] have h2 : F a = (F' a).toReal + f 0 a := by unfold F' rw [ENNReal.toReal_ofReal] · abel · simp [ha_bound 0] rw [h1, h2] refine Filter.Tendsto.add ?_ tendsto_const_nhds exact (ENNReal.continuousAt_toReal (by finiteness)).tendsto.comp ha /-- If an antitone sequence of functions has a lower bound and the sequence of integrals of these functions tends to the integral of the lower bound, then the sequence of functions converges almost everywhere to the lower bound. -/ lemma tendsto_of_integral_tendsto_of_antitone {μ : Measure α} {f : ℕ → α → ℝ} {F : α → ℝ} (hf_int : ∀ n, Integrable (f n) μ) (hF_int : Integrable F μ) (hf_tendsto : Tendsto (fun i ↦ ∫ a, f i a ∂μ) atTop (𝓝 (∫ a, F a ∂μ))) (hf_mono : ∀ᵐ a ∂μ, Antitone (fun i ↦ f i a)) (hf_bound : ∀ᵐ a ∂μ, ∀ i, F a ≤ f i a) : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F a)) := by let f' : ℕ → α → ℝ := fun i a ↦ - f i a let F' : α → ℝ := fun a ↦ - F a suffices ∀ᵐ a ∂μ, Tendsto (fun i ↦ f' i a) atTop (𝓝 (F' a)) by filter_upwards [this] with a ha_tendsto convert ha_tendsto.neg · simp [f'] · simp [F'] refine tendsto_of_integral_tendsto_of_monotone (fun n ↦ (hf_int n).neg) hF_int.neg ?_ ?_ ?_ · convert hf_tendsto.neg · rw [integral_neg] · rw [integral_neg] · filter_upwards [hf_mono] with a ha i j hij simp [f', ha hij] · filter_upwards [hf_bound] with a ha i simp [f', F', ha i] section NormedAddCommGroup variable {H : Type*} [NormedAddCommGroup H] theorem L1.norm_eq_integral_norm (f : α →₁[μ] H) : ‖f‖ = ∫ a, ‖f a‖ ∂μ := by simp only [eLpNorm, eLpNorm'_eq_lintegral_enorm, ENNReal.toReal_one, ENNReal.rpow_one, Lp.norm_def, if_false, ENNReal.one_ne_top, one_ne_zero, _root_.div_one] rw [integral_eq_lintegral_of_nonneg_ae (Eventually.of_forall (by simp [norm_nonneg])) (Lp.aestronglyMeasurable f).norm] simp theorem L1.dist_eq_integral_dist (f g : α →₁[μ] H) : dist f g = ∫ a, dist (f a) (g a) ∂μ := by simp only [dist_eq_norm, L1.norm_eq_integral_norm] exact integral_congr_ae <| (Lp.coeFn_sub _ _).fun_comp norm theorem L1.norm_of_fun_eq_integral_norm {f : α → H} (hf : Integrable f μ) : ‖hf.toL1 f‖ = ∫ a, ‖f a‖ ∂μ := by rw [L1.norm_eq_integral_norm] exact integral_congr_ae <| hf.coeFn_toL1.fun_comp _ theorem MemLp.eLpNorm_eq_integral_rpow_norm {f : α → H} {p : ℝ≥0∞} (hp1 : p ≠ 0) (hp2 : p ≠ ∞) (hf : MemLp f p μ) : eLpNorm f p μ = ENNReal.ofReal ((∫ a, ‖f a‖ ^ p.toReal ∂μ) ^ p.toReal⁻¹) := by have A : ∫⁻ a : α, ENNReal.ofReal (‖f a‖ ^ p.toReal) ∂μ = ∫⁻ a : α, ‖f a‖ₑ ^ p.toReal ∂μ := by simp_rw [← ofReal_rpow_of_nonneg (norm_nonneg _) toReal_nonneg, ofReal_norm_eq_enorm] simp only [eLpNorm_eq_lintegral_rpow_enorm hp1 hp2, one_div] rw [integral_eq_lintegral_of_nonneg_ae]; rotate_left · exact ae_of_all _ fun x => by positivity · exact (hf.aestronglyMeasurable.norm.aemeasurable.pow_const _).aestronglyMeasurable rw [A, ← ofReal_rpow_of_nonneg toReal_nonneg (inv_nonneg.2 toReal_nonneg), ofReal_toReal] exact (lintegral_rpow_enorm_lt_top_of_eLpNorm_lt_top hp1 hp2 hf.2).ne end NormedAddCommGroup theorem norm_integral_le_integral_norm (f : α → G) : ‖∫ a, f a ∂μ‖ ≤ ∫ a, ‖f a‖ ∂μ := by have le_ae : ∀ᵐ a ∂μ, 0 ≤ ‖f a‖ := Eventually.of_forall fun a => norm_nonneg _ by_cases h : AEStronglyMeasurable f μ · calc ‖∫ a, f a ∂μ‖ ≤ ENNReal.toReal (∫⁻ a, ENNReal.ofReal ‖f a‖ ∂μ) := norm_integral_le_lintegral_norm _ _ = ∫ a, ‖f a‖ ∂μ := (integral_eq_lintegral_of_nonneg_ae le_ae <| h.norm).symm · rw [integral_non_aestronglyMeasurable h, norm_zero] exact integral_nonneg_of_ae le_ae lemma abs_integral_le_integral_abs {f : α → ℝ} : |∫ a, f a ∂μ| ≤ ∫ a, |f a| ∂μ := norm_integral_le_integral_norm f theorem norm_integral_le_of_norm_le {f : α → G} {g : α → ℝ} (hg : Integrable g μ) (h : ∀ᵐ x ∂μ, ‖f x‖ ≤ g x) : ‖∫ x, f x ∂μ‖ ≤ ∫ x, g x ∂μ := calc ‖∫ x, f x ∂μ‖ ≤ ∫ x, ‖f x‖ ∂μ := norm_integral_le_integral_norm f _ ≤ ∫ x, g x ∂μ := integral_mono_of_nonneg (Eventually.of_forall fun _ => norm_nonneg _) hg h @[simp] theorem integral_const (c : E) : ∫ _ : α, c ∂μ = μ.real univ • c := by by_cases hμ : IsFiniteMeasure μ · simp only [integral, hE, L1.integral] exact setToFun_const (dominatedFinMeasAdditive_weightedSMul _) _ by_cases hc : c = 0 · simp [hc, integral_zero] · simp [measureReal_def, (integrable_const_iff_isFiniteMeasure hc).not.2 hμ, integral_undef, MeasureTheory.not_isFiniteMeasure_iff.mp hμ] lemma integral_eq_const [IsProbabilityMeasure μ] {f : α → E} {c : E} (hf : ∀ᵐ x ∂μ, f x = c) : ∫ x, f x ∂μ = c := by simp [integral_congr_ae hf] theorem norm_integral_le_of_norm_le_const [IsFiniteMeasure μ] {f : α → G} {C : ℝ} (h : ∀ᵐ x ∂μ, ‖f x‖ ≤ C) : ‖∫ x, f x ∂μ‖ ≤ C * μ.real univ := calc ‖∫ x, f x ∂μ‖ ≤ ∫ _, C ∂μ := norm_integral_le_of_norm_le (integrable_const C) h _ = C * μ.real univ := by rw [integral_const, smul_eq_mul, mul_comm] variable {ν : Measure α} theorem integral_add_measure {f : α → G} (hμ : Integrable f μ) (hν : Integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := by by_cases hG : CompleteSpace G; swap · simp [integral, hG] have hfi := hμ.add_measure hν simp_rw [integral_eq_setToFun] have hμ_dfma : DominatedFinMeasAdditive (μ + ν) (weightedSMul μ : Set α → G →L[ℝ] G) 1 := DominatedFinMeasAdditive.add_measure_right μ ν (dominatedFinMeasAdditive_weightedSMul μ) zero_le_one have hν_dfma : DominatedFinMeasAdditive (μ + ν) (weightedSMul ν : Set α → G →L[ℝ] G) 1 := DominatedFinMeasAdditive.add_measure_left μ ν (dominatedFinMeasAdditive_weightedSMul ν) zero_le_one rw [← setToFun_congr_measure_of_add_right hμ_dfma (dominatedFinMeasAdditive_weightedSMul μ) f hfi, ← setToFun_congr_measure_of_add_left hν_dfma (dominatedFinMeasAdditive_weightedSMul ν) f hfi] refine setToFun_add_left' _ _ _ (fun s _ hμνs => ?_) f rw [Measure.coe_add, Pi.add_apply, add_lt_top] at hμνs rw [weightedSMul, weightedSMul, weightedSMul, ← add_smul, measureReal_add_apply hμνs.1.ne hμνs.2.ne] @[simp] theorem integral_zero_measure {m : MeasurableSpace α} (f : α → G) : (∫ x, f x ∂(0 : Measure α)) = 0 := by by_cases hG : CompleteSpace G · simp only [integral, hG, L1.integral] exact setToFun_measure_zero (dominatedFinMeasAdditive_weightedSMul _) rfl · simp [integral, hG] @[simp] theorem setIntegral_measure_zero (f : α → G) {μ : Measure α} {s : Set α} (hs : μ s = 0) : ∫ x in s, f x ∂μ = 0 := Measure.restrict_eq_zero.mpr hs ▸ integral_zero_measure f @[deprecated (since := "2025-06-17")] alias setIntegral_zero_measure := setIntegral_measure_zero lemma integral_of_isEmpty [IsEmpty α] {f : α → G} : ∫ x, f x ∂μ = 0 := μ.eq_zero_of_isEmpty ▸ integral_zero_measure _ theorem integral_finset_sum_measure {ι} {m : MeasurableSpace α} {f : α → G} {μ : ι → Measure α} {s : Finset ι} (hf : ∀ i ∈ s, Integrable f (μ i)) : ∫ a, f a ∂(∑ i ∈ s, μ i) = ∑ i ∈ s, ∫ a, f a ∂μ i := by induction s using Finset.cons_induction_on with | empty => simp | cons _ _ h ih => rw [Finset.forall_mem_cons] at hf rw [Finset.sum_cons, Finset.sum_cons, ← ih hf.2] exact integral_add_measure hf.1 (integrable_finset_sum_measure.2 hf.2) theorem nndist_integral_add_measure_le_lintegral {f : α → G} (h₁ : Integrable f μ) (h₂ : Integrable f ν) : (nndist (∫ x, f x ∂μ) (∫ x, f x ∂(μ + ν)) : ℝ≥0∞) ≤ ∫⁻ x, ‖f x‖ₑ ∂ν := by rw [integral_add_measure h₁ h₂, nndist_comm, nndist_eq_nnnorm, add_sub_cancel_left] exact enorm_integral_le_lintegral_enorm _ theorem hasSum_integral_measure {ι} {m : MeasurableSpace α} {f : α → G} {μ : ι → Measure α} (hf : Integrable f (Measure.sum μ)) : HasSum (fun i => ∫ a, f a ∂μ i) (∫ a, f a ∂Measure.sum μ) := by have hfi : ∀ i, Integrable f (μ i) := fun i => hf.mono_measure (Measure.le_sum _ _) simp only [HasSum, ← integral_finset_sum_measure fun i _ => hfi i] refine Metric.nhds_basis_ball.tendsto_right_iff.mpr fun ε ε0 => ?_ lift ε to ℝ≥0 using ε0.le have hf_lt : (∫⁻ x, ‖f x‖ₑ ∂Measure.sum μ) < ∞ := hf.2 have hmem : ∀ᶠ y in 𝓝 (∫⁻ x, ‖f x‖ₑ ∂Measure.sum μ), (∫⁻ x, ‖f x‖ₑ ∂Measure.sum μ) < y + ε := by refine tendsto_id.add tendsto_const_nhds (lt_mem_nhds (α := ℝ≥0∞) <| ENNReal.lt_add_right ?_ ?_) exacts [hf_lt.ne, ENNReal.coe_ne_zero.2 (NNReal.coe_ne_zero.1 ε0.ne')] refine ((hasSum_lintegral_measure (fun x => ‖f x‖ₑ) μ).eventually hmem).mono fun s hs => ?_ obtain ⟨ν, hν⟩ : ∃ ν, (∑ i ∈ s, μ i) + ν = Measure.sum μ := by refine ⟨Measure.sum fun i : ↥(sᶜ : Set ι) => μ i, ?_⟩ simpa only [← Measure.sum_coe_finset] using Measure.sum_add_sum_compl (s : Set ι) μ rw [Metric.mem_ball, ← coe_nndist, NNReal.coe_lt_coe, ← ENNReal.coe_lt_coe, ← hν] rw [← hν, integrable_add_measure] at hf refine (nndist_integral_add_measure_le_lintegral hf.1 hf.2).trans_lt ?_ rw [← hν, lintegral_add_measure, lintegral_finset_sum_measure] at hs exact lt_of_add_lt_add_left hs theorem integral_sum_measure {ι} {_ : MeasurableSpace α} {f : α → G} {μ : ι → Measure α} (hf : Integrable f (Measure.sum μ)) : ∫ a, f a ∂Measure.sum μ = ∑' i, ∫ a, f a ∂μ i := (hasSum_integral_measure hf).tsum_eq.symm @[simp] theorem integral_smul_measure (f : α → G) (c : ℝ≥0∞) : ∫ x, f x ∂c • μ = c.toReal • ∫ x, f x ∂μ := by by_cases hG : CompleteSpace G; swap · simp [integral, hG] -- First we consider the “degenerate” case `c = ∞` rcases eq_or_ne c ∞ with (rfl | hc) · rw [ENNReal.toReal_top, zero_smul, integral_eq_setToFun, setToFun_top_smul_measure] -- Main case: `c ≠ ∞` simp_rw [integral_eq_setToFun, ← setToFun_smul_left] have hdfma : DominatedFinMeasAdditive μ (weightedSMul (c • μ) : Set α → G →L[ℝ] G) c.toReal := mul_one c.toReal ▸ (dominatedFinMeasAdditive_weightedSMul (c • μ)).of_smul_measure hc have hdfma_smul := dominatedFinMeasAdditive_weightedSMul (F := G) (c • μ) rw [← setToFun_congr_smul_measure c hc hdfma hdfma_smul f] exact setToFun_congr_left' _ _ (fun s _ _ => weightedSMul_smul_measure μ c) f @[simp] theorem integral_smul_nnreal_measure (f : α → G) (c : ℝ≥0) : ∫ x, f x ∂(c • μ) = c • ∫ x, f x ∂μ := integral_smul_measure f (c : ℝ≥0∞) theorem integral_map_of_stronglyMeasurable {β} [MeasurableSpace β] {φ : α → β} (hφ : Measurable φ) {f : β → G} (hfm : StronglyMeasurable f) : ∫ y, f y ∂Measure.map φ μ = ∫ x, f (φ x) ∂μ := by by_cases hG : CompleteSpace G; swap · simp [integral, hG] by_cases hfi : Integrable f (Measure.map φ μ); swap · rw [integral_undef hfi, integral_undef] exact fun hfφ => hfi ((integrable_map_measure hfm.aestronglyMeasurable hφ.aemeasurable).2 hfφ) borelize G have : SeparableSpace (range f ∪ {0} : Set G) := hfm.separableSpace_range_union_singleton refine tendsto_nhds_unique (tendsto_integral_approxOn_of_measurable_of_range_subset hfm.measurable hfi _ Subset.rfl) ?_ convert tendsto_integral_approxOn_of_measurable_of_range_subset (hfm.measurable.comp hφ) ((integrable_map_measure hfm.aestronglyMeasurable hφ.aemeasurable).1 hfi) (range f ∪ {0}) (union_subset_union_left {0} (range_comp_subset_range φ f)) using 1 ext1 i simp only [SimpleFunc.integral_eq, hφ, SimpleFunc.measurableSet_preimage, map_measureReal_apply, ← preimage_comp] refine (Finset.sum_subset (SimpleFunc.range_comp_subset_range _ hφ) fun y _ hy => ?_).symm rw [SimpleFunc.mem_range, ← Set.preimage_singleton_eq_empty, SimpleFunc.coe_comp] at hy rw [hy] simp theorem integral_map {β} [MeasurableSpace β] {φ : α → β} (hφ : AEMeasurable φ μ) {f : β → G} (hfm : AEStronglyMeasurable f (Measure.map φ μ)) : ∫ y, f y ∂Measure.map φ μ = ∫ x, f (φ x) ∂μ := let g := hfm.mk f calc ∫ y, f y ∂Measure.map φ μ = ∫ y, g y ∂Measure.map φ μ := integral_congr_ae hfm.ae_eq_mk _ = ∫ y, g y ∂Measure.map (hφ.mk φ) μ := by congr 1; exact Measure.map_congr hφ.ae_eq_mk _ = ∫ x, g (hφ.mk φ x) ∂μ := (integral_map_of_stronglyMeasurable hφ.measurable_mk hfm.stronglyMeasurable_mk) _ = ∫ x, g (φ x) ∂μ := integral_congr_ae (hφ.ae_eq_mk.symm.fun_comp _) _ = ∫ x, f (φ x) ∂μ := integral_congr_ae <| ae_eq_comp hφ hfm.ae_eq_mk.symm theorem _root_.MeasurableEmbedding.integral_map {β} {_ : MeasurableSpace β} {f : α → β} (hf : MeasurableEmbedding f) (g : β → G) : ∫ y, g y ∂Measure.map f μ = ∫ x, g (f x) ∂μ := by by_cases hgm : AEStronglyMeasurable g (Measure.map f μ) · exact MeasureTheory.integral_map hf.measurable.aemeasurable hgm · rw [integral_non_aestronglyMeasurable hgm, integral_non_aestronglyMeasurable] exact fun hgf => hgm (hf.aestronglyMeasurable_map_iff.2 hgf) theorem _root_.Topology.IsClosedEmbedding.integral_map {β} [TopologicalSpace α] [BorelSpace α] [TopologicalSpace β] [MeasurableSpace β] [BorelSpace β] {φ : α → β} (hφ : IsClosedEmbedding φ) (f : β → G) : ∫ y, f y ∂Measure.map φ μ = ∫ x, f (φ x) ∂μ := hφ.measurableEmbedding.integral_map _ theorem integral_map_equiv {β} [MeasurableSpace β] (e : α ≃ᵐ β) (f : β → G) : ∫ y, f y ∂Measure.map e μ = ∫ x, f (e x) ∂μ := e.measurableEmbedding.integral_map f omit hE in lemma integral_domSMul {G A : Type*} [Group G] [AddCommGroup A] [DistribMulAction G A] [MeasurableSpace A] [MeasurableConstSMul G A] {μ : Measure A} (g : Gᵈᵐᵃ) (f : A → E) : ∫ x, f x ∂g • μ = ∫ x, f ((DomMulAct.mk.symm g)⁻¹ • x) ∂μ := integral_map_equiv (MeasurableEquiv.smul ((DomMulAct.mk.symm g : G)⁻¹)) f theorem MeasurePreserving.integral_comp {β} {_ : MeasurableSpace β} {f : α → β} {ν} (h₁ : MeasurePreserving f μ ν) (h₂ : MeasurableEmbedding f) (g : β → G) : ∫ x, g (f x) ∂μ = ∫ y, g y ∂ν := h₁.map_eq ▸ (h₂.integral_map g).symm theorem MeasurePreserving.integral_comp' {β} [MeasurableSpace β] {ν} {f : α ≃ᵐ β} (h : MeasurePreserving f μ ν) (g : β → G) : ∫ x, g (f x) ∂μ = ∫ y, g y ∂ν := MeasurePreserving.integral_comp h f.measurableEmbedding _ theorem integral_subtype_comap {α} [MeasurableSpace α] {μ : Measure α} {s : Set α} (hs : MeasurableSet s) (f : α → G) : ∫ x : s, f (x : α) ∂(Measure.comap Subtype.val μ) = ∫ x in s, f x ∂μ := by rw [← map_comap_subtype_coe hs] exact ((MeasurableEmbedding.subtype_coe hs).integral_map _).symm attribute [local instance] Measure.Subtype.measureSpace in theorem integral_subtype {α} [MeasureSpace α] {s : Set α} (hs : MeasurableSet s) (f : α → G) : ∫ x : s, f x = ∫ x in s, f x := integral_subtype_comap hs f @[simp] theorem integral_dirac' [MeasurableSpace α] (f : α → E) (a : α) (hfm : StronglyMeasurable f) : ∫ x, f x ∂Measure.dirac a = f a := by borelize E calc ∫ x, f x ∂Measure.dirac a = ∫ _, f a ∂Measure.dirac a := integral_congr_ae <| ae_eq_dirac' hfm.measurable _ = f a := by simp @[simp] theorem integral_dirac [MeasurableSpace α] [MeasurableSingletonClass α] (f : α → E) (a : α) : ∫ x, f x ∂Measure.dirac a = f a := calc ∫ x, f x ∂Measure.dirac a = ∫ _, f a ∂Measure.dirac a := integral_congr_ae <| ae_eq_dirac f _ = f a := by simp theorem setIntegral_dirac' {mα : MeasurableSpace α} {f : α → E} (hf : StronglyMeasurable f) (a : α) {s : Set α} (hs : MeasurableSet s) [Decidable (a ∈ s)] : ∫ x in s, f x ∂Measure.dirac a = if a ∈ s then f a else 0 := by rw [restrict_dirac' hs] split_ifs · exact integral_dirac' _ _ hf · exact integral_zero_measure _ theorem setIntegral_dirac [MeasurableSpace α] [MeasurableSingletonClass α] (f : α → E) (a : α) (s : Set α) [Decidable (a ∈ s)] : ∫ x in s, f x ∂Measure.dirac a = if a ∈ s then f a else 0 := by rw [restrict_dirac] split_ifs · exact integral_dirac _ _ · exact integral_zero_measure _ /-- **Markov's inequality** also known as **Chebyshev's first inequality**. -/ theorem mul_meas_ge_le_integral_of_nonneg {f : α → ℝ} (hf_nonneg : 0 ≤ᵐ[μ] f) (hf_int : Integrable f μ) (ε : ℝ) : ε * μ.real { x | ε ≤ f x } ≤ ∫ x, f x ∂μ := by rcases eq_top_or_lt_top (μ {x | ε ≤ f x}) with hμ | hμ · simpa [measureReal_def, hμ] using integral_nonneg_of_ae hf_nonneg · have := Fact.mk hμ calc ε * μ.real { x | ε ≤ f x } = ∫ _ in {x | ε ≤ f x}, ε ∂μ := by simp [mul_comm] _ ≤ ∫ x in {x | ε ≤ f x}, f x ∂μ := integral_mono_ae (integrable_const _) (hf_int.mono_measure μ.restrict_le_self) <| ae_restrict_mem₀ <| hf_int.aemeasurable.nullMeasurable measurableSet_Ici _ ≤ _ := integral_mono_measure μ.restrict_le_self hf_nonneg hf_int /-- Hölder's inequality for the integral of a product of norms. The integral of the product of two norms of functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem integral_mul_norm_le_Lp_mul_Lq {E} [NormedAddCommGroup E] {f g : α → E} {p q : ℝ} (hpq : p.HolderConjugate q) (hf : MemLp f (ENNReal.ofReal p) μ) (hg : MemLp g (ENNReal.ofReal q) μ) : ∫ a, ‖f a‖ * ‖g a‖ ∂μ ≤ (∫ a, ‖f a‖ ^ p ∂μ) ^ (1 / p) * (∫ a, ‖g a‖ ^ q ∂μ) ^ (1 / q) := by -- translate the Bochner integrals into Lebesgue integrals. rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae] rotate_left · exact Eventually.of_forall fun x => Real.rpow_nonneg (norm_nonneg _) _ · exact (hg.1.norm.aemeasurable.pow aemeasurable_const).aestronglyMeasurable · exact Eventually.of_forall fun x => Real.rpow_nonneg (norm_nonneg _) _ · exact (hf.1.norm.aemeasurable.pow aemeasurable_const).aestronglyMeasurable · exact Eventually.of_forall fun x => mul_nonneg (norm_nonneg _) (norm_nonneg _) · exact hf.1.norm.mul hg.1.norm rw [ENNReal.toReal_rpow, ENNReal.toReal_rpow, ← ENNReal.toReal_mul] -- replace norms by nnnorm have h_left : ∫⁻ a, ENNReal.ofReal (‖f a‖ * ‖g a‖) ∂μ = ∫⁻ a, ((‖f ·‖ₑ) * (‖g ·‖ₑ)) a ∂μ := by simp_rw [Pi.mul_apply, ← ofReal_norm_eq_enorm, ENNReal.ofReal_mul (norm_nonneg _)] have h_right_f : ∫⁻ a, .ofReal (‖f a‖ ^ p) ∂μ = ∫⁻ a, ‖f a‖ₑ ^ p ∂μ := by refine lintegral_congr fun x => ?_ rw [← ofReal_norm_eq_enorm, ENNReal.ofReal_rpow_of_nonneg (norm_nonneg _) hpq.nonneg] have h_right_g : ∫⁻ a, .ofReal (‖g a‖ ^ q) ∂μ = ∫⁻ a, ‖g a‖ₑ ^ q ∂μ := by refine lintegral_congr fun x => ?_ rw [← ofReal_norm_eq_enorm, ENNReal.ofReal_rpow_of_nonneg (norm_nonneg _) hpq.symm.nonneg] rw [h_left, h_right_f, h_right_g] -- we can now apply `ENNReal.lintegral_mul_le_Lp_mul_Lq` (up to the `toReal` application) refine ENNReal.toReal_mono ?_ ?_ · refine ENNReal.mul_ne_top ?_ ?_ · convert hf.eLpNorm_ne_top rw [eLpNorm_eq_lintegral_rpow_enorm] · rw [ENNReal.toReal_ofReal hpq.nonneg] · rw [Ne, ENNReal.ofReal_eq_zero, not_le] exact hpq.pos · finiteness · convert hg.eLpNorm_ne_top rw [eLpNorm_eq_lintegral_rpow_enorm] · rw [ENNReal.toReal_ofReal hpq.symm.nonneg] · rw [Ne, ENNReal.ofReal_eq_zero, not_le] exact hpq.symm.pos · finiteness · exact ENNReal.lintegral_mul_le_Lp_mul_Lq μ hpq hf.1.nnnorm.aemeasurable.coe_nnreal_ennreal hg.1.nnnorm.aemeasurable.coe_nnreal_ennreal /-- Hölder's inequality for functions `α → ℝ`. The integral of the product of two nonnegative functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem integral_mul_le_Lp_mul_Lq_of_nonneg {p q : ℝ} (hpq : p.HolderConjugate q) {f g : α → ℝ} (hf_nonneg : 0 ≤ᵐ[μ] f) (hg_nonneg : 0 ≤ᵐ[μ] g) (hf : MemLp f (ENNReal.ofReal p) μ) (hg : MemLp g (ENNReal.ofReal q) μ) : ∫ a, f a * g a ∂μ ≤ (∫ a, f a ^ p ∂μ) ^ (1 / p) * (∫ a, g a ^ q ∂μ) ^ (1 / q) := by have h_left : ∫ a, f a * g a ∂μ = ∫ a, ‖f a‖ * ‖g a‖ ∂μ := by refine integral_congr_ae ?_ filter_upwards [hf_nonneg, hg_nonneg] with x hxf hxg rw [Real.norm_of_nonneg hxf, Real.norm_of_nonneg hxg] have h_right_f : ∫ a, f a ^ p ∂μ = ∫ a, ‖f a‖ ^ p ∂μ := by refine integral_congr_ae ?_ filter_upwards [hf_nonneg] with x hxf rw [Real.norm_of_nonneg hxf] have h_right_g : ∫ a, g a ^ q ∂μ = ∫ a, ‖g a‖ ^ q ∂μ := by refine integral_congr_ae ?_ filter_upwards [hg_nonneg] with x hxg rw [Real.norm_of_nonneg hxg] rw [h_left, h_right_f, h_right_g] exact integral_mul_norm_le_Lp_mul_Lq hpq hf hg theorem integral_countable' [Countable α] [MeasurableSingletonClass α] {μ : Measure α} {f : α → E} (hf : Integrable f μ) : ∫ a, f a ∂μ = ∑' a, μ.real {a} • f a := by rw [← Measure.sum_smul_dirac μ] at hf rw [← Measure.sum_smul_dirac μ, integral_sum_measure hf] congr 1 with a : 1 rw [integral_smul_measure, integral_dirac, Measure.sum_smul_dirac, measureReal_def] theorem integral_singleton' {μ : Measure α} {f : α → E} (hf : StronglyMeasurable f) (a : α) : ∫ a in {a}, f a ∂μ = μ.real {a} • f a := by simp only [Measure.restrict_singleton, integral_smul_measure, integral_dirac' f a hf, measureReal_def] theorem integral_singleton [MeasurableSingletonClass α] {μ : Measure α} (f : α → E) (a : α) : ∫ a in {a}, f a ∂μ = μ.real {a} • f a := by simp only [Measure.restrict_singleton, integral_smul_measure, integral_dirac, measureReal_def] theorem integral_countable [MeasurableSingletonClass α] (f : α → E) {s : Set α} (hs : s.Countable) (hf : IntegrableOn f s μ) : ∫ a in s, f a ∂μ = ∑' a : s, μ.real {(a : α)} • f a := by have hi : Countable { x // x ∈ s } := Iff.mpr countable_coe_iff hs have hf' : Integrable (fun (x : s) => f x) (Measure.comap Subtype.val μ) := by rw [IntegrableOn, ← map_comap_subtype_coe, integrable_map_measure] at hf · apply hf · exact Integrable.aestronglyMeasurable hf · exact Measurable.aemeasurable measurable_subtype_coe · exact Countable.measurableSet hs rw [← integral_subtype_comap hs.measurableSet, integral_countable' hf'] congr 1 with a : 1 rw [measureReal_def, Measure.comap_apply Subtype.val Subtype.coe_injective (fun s' hs' => MeasurableSet.subtype_image (Countable.measurableSet hs) hs') _ (MeasurableSet.singleton a)] simp [measureReal_def] theorem integral_finset [MeasurableSingletonClass α] (s : Finset α) (f : α → E) (hf : IntegrableOn f s μ) : ∫ x in s, f x ∂μ = ∑ x ∈ s, μ.real {x} • f x := by rw [integral_countable _ s.countable_toSet hf, ← Finset.tsum_subtype'] theorem integral_fintype [MeasurableSingletonClass α] [Fintype α] (f : α → E) (hf : Integrable f μ) : ∫ x, f x ∂μ = ∑ x, μ.real {x} • f x := by -- NB: Integrable f does not follow from Fintype, because the measure itself could be non-finite rw [← integral_finset .univ, Finset.coe_univ, Measure.restrict_univ] simp [Finset.coe_univ, hf] theorem integral_unique [Unique α] (f : α → E) : ∫ x, f x ∂μ = μ.real univ • f default := calc ∫ x, f x ∂μ = ∫ _, f default ∂μ := by congr with x; congr; exact Unique.uniq _ x _ = μ.real univ • f default := by rw [integral_const] theorem integral_pos_of_integrable_nonneg_nonzero [TopologicalSpace α] [Measure.IsOpenPosMeasure μ] {f : α → ℝ} {x : α} (f_cont : Continuous f) (f_int : Integrable f μ) (f_nonneg : 0 ≤ f) (f_x : f x ≠ 0) : 0 < ∫ x, f x ∂μ := (integral_pos_iff_support_of_nonneg f_nonneg f_int).2 (IsOpen.measure_pos μ f_cont.isOpen_support ⟨x, f_x⟩) @[simp] lemma integral_count [MeasurableSingletonClass α] [Fintype α] (f : α → E) : ∫ a, f a ∂.count = ∑ a, f a := by simp [integral_fintype] end Properties section IntegralTrim variable {β γ : Type*} {m m0 : MeasurableSpace β} {μ : Measure β} /-- Simple function seen as simple function of a larger `MeasurableSpace`. -/ def SimpleFunc.toLargerSpace (hm : m ≤ m0) (f : @SimpleFunc β m γ) : SimpleFunc β γ := ⟨@SimpleFunc.toFun β m γ f, fun x => hm _ (@SimpleFunc.measurableSet_fiber β γ m f x), @SimpleFunc.finite_range β γ m f⟩ theorem SimpleFunc.coe_toLargerSpace_eq (hm : m ≤ m0) (f : @SimpleFunc β m γ) : ⇑(f.toLargerSpace hm) = f := rfl theorem integral_simpleFunc_larger_space (hm : m ≤ m0) (f : @SimpleFunc β m F) (hf_int : Integrable f μ) : ∫ x, f x ∂μ = ∑ x ∈ @SimpleFunc.range β F m f, μ.real (f ⁻¹' {x}) • x := by simp_rw [← f.coe_toLargerSpace_eq hm] rw [SimpleFunc.integral_eq_sum _ hf_int] congr 1 theorem integral_trim_simpleFunc (hm : m ≤ m0) (f : @SimpleFunc β m F) (hf_int : Integrable f μ) : ∫ x, f x ∂μ = ∫ x, f x ∂μ.trim hm := by have hf : StronglyMeasurable[m] f := @SimpleFunc.stronglyMeasurable β F m _ f have hf_int_m := hf_int.trim hm hf rw [integral_simpleFunc_larger_space (le_refl m) f hf_int_m, integral_simpleFunc_larger_space hm f hf_int] congr with x simp only [measureReal_def] congr 2 exact (trim_measurableSet_eq hm (@SimpleFunc.measurableSet_fiber β F m f x)).symm theorem integral_trim (hm : m ≤ m0) {f : β → G} (hf : StronglyMeasurable[m] f) : ∫ x, f x ∂μ = ∫ x, f x ∂μ.trim hm := by by_cases hG : CompleteSpace G; swap · simp [integral, hG] borelize G by_cases hf_int : Integrable f μ swap · have hf_int_m : ¬Integrable f (μ.trim hm) := fun hf_int_m => hf_int (integrable_of_integrable_trim hm hf_int_m) rw [integral_undef hf_int, integral_undef hf_int_m] haveI : SeparableSpace (range f ∪ {0} : Set G) := hf.separableSpace_range_union_singleton let f_seq := @SimpleFunc.approxOn G β _ _ _ m _ hf.measurable (range f ∪ {0}) 0 (by simp) _ have hf_seq_meas : ∀ n, StronglyMeasurable[m] (f_seq n) := fun n => @SimpleFunc.stronglyMeasurable β G m _ (f_seq n) have hf_seq_int : ∀ n, Integrable (f_seq n) μ := SimpleFunc.integrable_approxOn_range (hf.mono hm).measurable hf_int have hf_seq_int_m : ∀ n, Integrable (f_seq n) (μ.trim hm) := fun n => (hf_seq_int n).trim hm (hf_seq_meas n) have hf_seq_eq : ∀ n, ∫ x, f_seq n x ∂μ = ∫ x, f_seq n x ∂μ.trim hm := fun n => integral_trim_simpleFunc hm (f_seq n) (hf_seq_int n) have h_lim_1 : atTop.Tendsto (fun n => ∫ x, f_seq n x ∂μ) (𝓝 (∫ x, f x ∂μ)) := by refine tendsto_integral_of_L1 f hf_int (Eventually.of_forall hf_seq_int) ?_ exact SimpleFunc.tendsto_approxOn_range_L1_enorm (hf.mono hm).measurable hf_int have h_lim_2 : atTop.Tendsto (fun n => ∫ x, f_seq n x ∂μ) (𝓝 (∫ x, f x ∂μ.trim hm)) := by simp_rw [hf_seq_eq] refine @tendsto_integral_of_L1 β G _ _ m (μ.trim hm) _ f (hf_int.trim hm hf) _ _ (Eventually.of_forall hf_seq_int_m) ?_ exact @SimpleFunc.tendsto_approxOn_range_L1_enorm β G m _ _ _ f _ _ hf.measurable (hf_int.trim hm hf) exact tendsto_nhds_unique h_lim_1 h_lim_2 theorem integral_trim_ae (hm : m ≤ m0) {f : β → G} (hf : AEStronglyMeasurable[m] f (μ.trim hm)) : ∫ x, f x ∂μ = ∫ x, f x ∂μ.trim hm := by rw [integral_congr_ae (ae_eq_of_ae_eq_trim hf.ae_eq_mk), integral_congr_ae hf.ae_eq_mk] exact integral_trim hm hf.stronglyMeasurable_mk end IntegralTrim section SnormBound variable {m0 : MeasurableSpace α} {μ : Measure α} {f : α → ℝ} theorem eLpNorm_one_le_of_le {r : ℝ≥0} (hfint : Integrable f μ) (hfint' : 0 ≤ ∫ x, f x ∂μ) (hf : ∀ᵐ ω ∂μ, f ω ≤ r) : eLpNorm f 1 μ ≤ 2 * μ Set.univ * r := by by_cases hr : r = 0 · suffices f =ᵐ[μ] 0 by rw [eLpNorm_congr_ae this, eLpNorm_zero, hr, ENNReal.coe_zero, mul_zero] rw [hr] at hf norm_cast at hf have hnegf : ∫ x, -f x ∂μ = 0 := by rw [integral_neg, neg_eq_zero] exact le_antisymm (integral_nonpos_of_ae hf) hfint' have := (integral_eq_zero_iff_of_nonneg_ae ?_ hfint.neg).1 hnegf · filter_upwards [this] with ω hω rwa [Pi.neg_apply, Pi.zero_apply, neg_eq_zero] at hω · filter_upwards [hf] with ω hω rwa [Pi.zero_apply, Pi.neg_apply, Right.nonneg_neg_iff] by_cases hμ : IsFiniteMeasure μ swap · have : μ Set.univ = ∞ := by by_contra hμ' exact hμ (IsFiniteMeasure.mk <| lt_top_iff_ne_top.2 hμ') rw [this, ENNReal.mul_top', if_neg, ENNReal.top_mul', if_neg] · exact le_top · simp [hr] · simp haveI := hμ rw [integral_eq_integral_pos_part_sub_integral_neg_part hfint, sub_nonneg] at hfint' have hposbdd : ∫ ω, max (f ω) 0 ∂μ ≤ μ.real Set.univ • (r : ℝ) := by rw [← integral_const] refine integral_mono_ae hfint.real_toNNReal (integrable_const (r : ℝ)) ?_ filter_upwards [hf] with ω hω using Real.toNNReal_le_iff_le_coe.2 hω rw [MemLp.eLpNorm_eq_integral_rpow_norm one_ne_zero ENNReal.one_ne_top (memLp_one_iff_integrable.2 hfint), ENNReal.ofReal_le_iff_le_toReal (by finiteness)] simp_rw [ENNReal.toReal_one, _root_.inv_one, Real.rpow_one, Real.norm_eq_abs, ← max_zero_add_max_neg_zero_eq_abs_self, ← Real.coe_toNNReal'] rw [integral_add hfint.real_toNNReal] · simp only [Real.coe_toNNReal', ENNReal.toReal_mul, ENNReal.coe_toReal, toReal_ofNat] at hfint' ⊢ grw [hfint'] rwa [← two_mul, mul_assoc, mul_le_mul_iff_right₀ (two_pos : (0 : ℝ) < 2)] · exact hfint.neg.sup (integrable_zero _ _ μ) theorem eLpNorm_one_le_of_le' {r : ℝ} (hfint : Integrable f μ) (hfint' : 0 ≤ ∫ x, f x ∂μ) (hf : ∀ᵐ ω ∂μ, f ω ≤ r) : eLpNorm f 1 μ ≤ 2 * μ Set.univ * ENNReal.ofReal r := by refine eLpNorm_one_le_of_le hfint hfint' ?_ simp only [Real.coe_toNNReal', le_max_iff] filter_upwards [hf] with ω hω using Or.inl hω end SnormBound end MeasureTheory namespace Mathlib.Meta.Positivity open Qq Lean Meta MeasureTheory attribute [local instance] monadLiftOptionMetaM in /-- Positivity extension for integrals. This extension only proves non-negativity, strict positivity is more delicate for integration and requires more assumptions. -/ @[positivity MeasureTheory.integral _ _] def evalIntegral : PositivityExt where eval {u α} zα pα e := do match u, α, e with | 0, ~q(ℝ), ~q(@MeasureTheory.integral $i ℝ _ $inst2 _ _ $f) => let i : Q($i) ← mkFreshExprMVarQ q($i) .syntheticOpaque have body : Q(ℝ) := .betaRev f #[i] let rbody ← core zα pα body let pbody ← rbody.toNonneg let pr : Q(∀ x, 0 ≤ $f x) ← mkLambdaFVars #[i] pbody assertInstancesCommute return .nonnegative q(integral_nonneg $pr) | _ => throwError "not MeasureTheory.integral" end Mathlib.Meta.Positivity
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Bochner/FundThmCalculus.lean
import Mathlib.MeasureTheory.Integral.Bochner.Set /-! # Fundamental theorem of calculus for set integrals This file proves a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integrals. See `Filter.Tendsto.integral_sub_linear_isLittleO_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ ae μ`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.smallSets`, i.e. for any `ε>0` there exists `t ∈ l` such that `‖∫ x in s, f x ∂μ - μ s • c‖ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. -/ open Filter MeasureTheory Topology Asymptotics Metric variable {X E ι : Type*} [MeasurableSpace X] [NormedAddCommGroup E] [NormedSpace ℝ E] [CompleteSpace E] /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ ae μ`, then `∫ x in s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.smallSets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `μ.real (s i)` in the actual statement. Often there is a good formula for `μ.real (s i)`, so the formalization can take an optional argument `m` with this formula and a proof of `(fun i => μ.real (s i)) =ᶠ[li] m`. Without these arguments, `m i = μ.real (s i)` is used in the output. -/ theorem Filter.Tendsto.integral_sub_linear_isLittleO_ae {μ : Measure X} {l : Filter X} [l.IsMeasurablyGenerated] {f : X → E} {b : E} (h : Tendsto f (l ⊓ ae μ) (𝓝 b)) (hfm : StronglyMeasurableAtFilter f l μ) (hμ : μ.FiniteAtFilter l) {s : ι → Set X} {li : Filter ι} (hs : Tendsto s li l.smallSets) (m : ι → ℝ := fun i => μ.real (s i)) (hsμ : (fun i => μ.real (s i)) =ᶠ[li] m := by rfl) : (fun i => (∫ x in s i, f x ∂μ) - m i • b) =o[li] m := by suffices (fun s => (∫ x in s, f x ∂μ) - μ.real s • b) =o[l.smallSets] fun s => μ.real s from (this.comp_tendsto hs).congr' (hsμ.mono fun a ha => by dsimp only [Function.comp_apply] at ha ⊢; rw [ha]) hsμ refine isLittleO_iff.2 fun ε ε₀ => ?_ have : ∀ᶠ s in l.smallSets, ∀ᵐ x ∂μ, x ∈ s → f x ∈ closedBall b ε := eventually_smallSets_eventually.2 (h.eventually <| closedBall_mem_nhds _ ε₀) filter_upwards [hμ.eventually, (hμ.integrableAtFilter_of_tendsto_ae hfm h).eventually, hfm.eventually, this] simp only [mem_closedBall, dist_eq_norm] intro s hμs h_integrable hfm h_norm rw [← setIntegral_const, ← integral_sub h_integrable (integrableOn_const hμs.ne), Real.norm_eq_abs, abs_of_nonneg measureReal_nonneg] exact norm_setIntegral_le_of_norm_le_const_ae' hμs h_norm /-- Fundamental theorem of calculus for set integrals, `nhdsWithin` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a` within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li` provided that `s i` tends to `(𝓝[t] a).smallSets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `μ.real (s i)` in the actual statement. Often there is a good formula for `μ.real (s i)`, so the formalization can take an optional argument `m` with this formula and a proof of `(fun i => μ.real (s i)) =ᶠ[li] m`. Without these arguments, `m i = μ.real (s i)` is used in the output. -/ theorem ContinuousWithinAt.integral_sub_linear_isLittleO_ae [TopologicalSpace X] [OpensMeasurableSpace X] {μ : Measure X} [IsLocallyFiniteMeasure μ] {x : X} {t : Set X} {f : X → E} (hx : ContinuousWithinAt f t x) (ht : MeasurableSet t) (hfm : StronglyMeasurableAtFilter f (𝓝[t] x) μ) {s : ι → Set X} {li : Filter ι} (hs : Tendsto s li (𝓝[t] x).smallSets) (m : ι → ℝ := fun i => μ.real (s i)) (hsμ : (fun i => μ.real (s i)) =ᶠ[li] m := by rfl) : (fun i => (∫ x in s i, f x ∂μ) - m i • f x) =o[li] m := haveI : (𝓝[t] x).IsMeasurablyGenerated := ht.nhdsWithin_isMeasurablyGenerated _ (hx.mono_left inf_le_left).integral_sub_linear_isLittleO_ae hfm (μ.finiteAt_nhdsWithin x t) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to `(𝓝 a).smallSets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `μ.real (s i)` in the actual statement. Often there is a good formula for `μ.real (s i)`, so the formalization can take an optional argument `m` with this formula and a proof of `(fun i => μ.real (s i)) =ᶠ[li] m`. Without these arguments, `m i = μ.real (s i)` is used in the output. -/ theorem ContinuousAt.integral_sub_linear_isLittleO_ae [TopologicalSpace X] [OpensMeasurableSpace X] {μ : Measure X} [IsLocallyFiniteMeasure μ] {x : X} {f : X → E} (hx : ContinuousAt f x) (hfm : StronglyMeasurableAtFilter f (𝓝 x) μ) {s : ι → Set X} {li : Filter ι} (hs : Tendsto s li (𝓝 x).smallSets) (m : ι → ℝ := fun i => μ.real (s i)) (hsμ : (fun i => μ.real (s i)) =ᶠ[li] m := by rfl) : (fun i => (∫ x in s i, f x ∂μ) - m i • f x) =o[li] m := (hx.mono_left inf_le_left).integral_sub_linear_isLittleO_ae hfm (μ.finiteAt_nhds x) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhdsWithin` version: if `μ` is a locally finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).smallSets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `μ.real (s i)` in the actual statement. Often there is a good formula for `μ.real (s i)`, so the formalization can take an optional argument `m` with this formula and a proof of `(fun i => μ.real (s i)) =ᶠ[li] m`. Without these arguments, `m i = μ.real (s i)` is used in the output. -/ theorem ContinuousOn.integral_sub_linear_isLittleO_ae [TopologicalSpace X] [OpensMeasurableSpace X] [SecondCountableTopologyEither X E] {μ : Measure X} [IsLocallyFiniteMeasure μ] {x : X} {t : Set X} {f : X → E} (hft : ContinuousOn f t) (hx : x ∈ t) (ht : MeasurableSet t) {s : ι → Set X} {li : Filter ι} (hs : Tendsto s li (𝓝[t] x).smallSets) (m : ι → ℝ := fun i => μ.real (s i)) (hsμ : (fun i => μ.real (s i)) =ᶠ[li] m := by rfl) : (fun i => (∫ x in s i, f x ∂μ) - m i • f x) =o[li] m := (hft x hx).integral_sub_linear_isLittleO_ae ht ⟨t, self_mem_nhdsWithin, hft.aestronglyMeasurable ht⟩ hs m hsμ
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Bochner/Set.lean
import Mathlib.Combinatorics.Enumerative.InclusionExclusion import Mathlib.MeasureTheory.Function.LocallyIntegrable import Mathlib.MeasureTheory.Integral.Bochner.Basic import Mathlib.Topology.ContinuousMap.Compact import Mathlib.Topology.MetricSpace.ThickenedIndicator /-! # Set integral In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable function `f` and a measurable set `s` this definition coincides with another natural definition: `∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s` and is zero otherwise. Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ` directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g. `setIntegral_union`, `setIntegral_empty`, `setIntegral_univ`. We use the property `IntegrableOn f s μ := Integrable f (μ.restrict s)`, defined in `MeasureTheory.IntegrableOn`. We also defined in that same file a predicate `IntegrableAtFilter (f : X → E) (l : Filter X) (μ : Measure X)` saying that `f` is integrable at some set `s ∈ l`. ## Notation We provide the following notations for expressing the integral of a function on a set : * `∫ x in s, f x ∂μ` is `MeasureTheory.integral (μ.restrict s) f` * `∫ x in s, f x` is `∫ x in s, f x ∂volume` Note that the set notations are defined in the file `Mathlib/MeasureTheory/Integral/Bochner/Basic.lean`, but we reference them here because all theorems about set integrals are in this file. -/ assert_not_exists InnerProductSpace open Filter Function MeasureTheory RCLike Set TopologicalSpace Topology open scoped ENNReal NNReal Finset variable {X Y E F : Type*} namespace MeasureTheory variable {mX : MeasurableSpace X} section NormedAddCommGroup variable [NormedAddCommGroup E] [NormedSpace ℝ E] {f g : X → E} {s t : Set X} {μ : Measure X} theorem setIntegral_congr_ae₀ (hs : NullMeasurableSet s μ) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := integral_congr_ae ((ae_restrict_iff'₀ hs).2 h) theorem setIntegral_congr_ae (hs : MeasurableSet s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := integral_congr_ae ((ae_restrict_iff' hs).2 h) theorem setIntegral_congr_fun₀ (hs : NullMeasurableSet s μ) (h : EqOn f g s) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := setIntegral_congr_ae₀ hs <| Eventually.of_forall h theorem setIntegral_congr_fun (hs : MeasurableSet s) (h : EqOn f g s) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := setIntegral_congr_ae hs <| Eventually.of_forall h theorem setIntegral_congr_set (hst : s =ᵐ[μ] t) : ∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ := by rw [Measure.restrict_congr_set hst] theorem integral_union_ae (hst : AEDisjoint μ s t) (ht : NullMeasurableSet t μ) (hfs : IntegrableOn f s μ) (hft : IntegrableOn f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := by simp only [Measure.restrict_union₀ hst ht, integral_add_measure hfs hft] theorem setIntegral_union (hst : Disjoint s t) (ht : MeasurableSet t) (hfs : IntegrableOn f s μ) (hft : IntegrableOn f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := integral_union_ae hst.aedisjoint ht.nullMeasurableSet hfs hft theorem integral_diff (ht : MeasurableSet t) (hfs : IntegrableOn f s μ) (hts : t ⊆ s) : ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ - ∫ x in t, f x ∂μ := by rw [eq_sub_iff_add_eq, ← setIntegral_union, diff_union_of_subset hts] exacts [disjoint_sdiff_self_left, ht, hfs.mono_set diff_subset, hfs.mono_set hts] theorem integral_inter_add_diff₀ (ht : NullMeasurableSet t μ) (hfs : IntegrableOn f s μ) : ∫ x in s ∩ t, f x ∂μ + ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ := by rw [← Measure.restrict_inter_add_diff₀ s ht, integral_add_measure] · exact Integrable.mono_measure hfs (Measure.restrict_mono inter_subset_left le_rfl) · exact Integrable.mono_measure hfs (Measure.restrict_mono diff_subset le_rfl) theorem integral_inter_add_diff (ht : MeasurableSet t) (hfs : IntegrableOn f s μ) : ∫ x in s ∩ t, f x ∂μ + ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ := integral_inter_add_diff₀ ht.nullMeasurableSet hfs theorem integral_biUnion_finset {ι : Type*} (t : Finset ι) {s : ι → Set X} (hs : ∀ i ∈ t, MeasurableSet (s i)) (h's : Set.Pairwise (↑t) (Disjoint on s)) (hf : ∀ i ∈ t, IntegrableOn f (s i) μ) : ∫ x in ⋃ i ∈ t, s i, f x ∂μ = ∑ i ∈ t, ∫ x in s i, f x ∂μ := by classical induction t using Finset.induction_on with | empty => simp | insert _ _ hat IH => simp only [Finset.coe_insert, Finset.forall_mem_insert, Set.pairwise_insert, Finset.set_biUnion_insert] at hs hf h's ⊢ rw [setIntegral_union _ _ hf.1 (integrableOn_finset_iUnion.2 hf.2)] · rw [Finset.sum_insert hat, IH hs.2 h's.1 hf.2] · simp only [disjoint_iUnion_right] exact fun i hi => (h's.2 i hi (ne_of_mem_of_not_mem hi hat).symm).1 · exact Finset.measurableSet_biUnion _ hs.2 @[deprecated (since := "2025-08-28")] alias integral_finset_biUnion := integral_biUnion_finset theorem integral_iUnion_fintype {ι : Type*} [Fintype ι] {s : ι → Set X} (hs : ∀ i, MeasurableSet (s i)) (h's : Pairwise (Disjoint on s)) (hf : ∀ i, IntegrableOn f (s i) μ) : ∫ x in ⋃ i, s i, f x ∂μ = ∑ i, ∫ x in s i, f x ∂μ := by convert integral_biUnion_finset Finset.univ (fun i _ => hs i) _ fun i _ => hf i · simp · simp [pairwise_univ, h's] @[deprecated (since := "2025-08-28")] alias integral_fintype_iUnion := integral_iUnion_fintype theorem setIntegral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [Measure.restrict_empty, integral_zero_measure] theorem setIntegral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [Measure.restrict_univ] theorem integral_add_compl₀ (hs : NullMeasurableSet s μ) (hfi : Integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := by rw [ ← integral_union_ae disjoint_compl_right.aedisjoint hs.compl hfi.integrableOn hfi.integrableOn, union_compl_self, setIntegral_univ] theorem integral_add_compl (hs : MeasurableSet s) (hfi : Integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := integral_add_compl₀ hs.nullMeasurableSet hfi theorem setIntegral_compl (hs : MeasurableSet s) (hfi : Integrable f μ) : ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ - ∫ x in s, f x ∂μ := by rw [← integral_add_compl (μ := μ) hs hfi, add_sub_cancel_left] /-- For a function `f` and a measurable set `s`, the integral of `indicator s f` over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/ theorem integral_indicator (hs : MeasurableSet s) : ∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ := by by_cases hfi : IntegrableOn f s μ; swap · rw [integral_undef hfi, integral_undef] rwa [integrable_indicator_iff hs] calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ := (integral_add_compl hs (hfi.integrable_indicator hs)).symm _ = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ := (congr_arg₂ (· + ·) (integral_congr_ae (indicator_ae_eq_restrict hs)) (integral_congr_ae (indicator_ae_eq_restrict_compl hs))) _ = ∫ x in s, f x ∂μ := by simp theorem integral_indicator₀ (hs : NullMeasurableSet s μ) : ∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ := by rw [← integral_congr_ae (indicator_ae_eq_of_ae_eq_set hs.toMeasurable_ae_eq), integral_indicator (measurableSet_toMeasurable _ _), Measure.restrict_congr_set hs.toMeasurable_ae_eq] lemma integral_integral_indicator {mY : MeasurableSpace Y} {ν : Measure Y} (f : X → Y → E) {s : Set X} (hs : MeasurableSet s) : ∫ x, ∫ y, s.indicator (f · y) x ∂ν ∂μ = ∫ x in s, ∫ y, f x y ∂ν ∂μ := by simp_rw [← integral_indicator hs, integral_indicator₂] theorem setIntegral_indicator (ht : MeasurableSet t) : ∫ x in s, t.indicator f x ∂μ = ∫ x in s ∩ t, f x ∂μ := by rw [integral_indicator ht, Measure.restrict_restrict ht, Set.inter_comm] /-- **Inclusion-exclusion principle** for the integral of a function over a union. The integral of a function `f` over the union of the `s i` over `i ∈ t` is the alternating sum of the integrals of `f` over the intersections of the `s i`. -/ theorem integral_biUnion_eq_sum_powerset {ι : Type*} {t : Finset ι} {s : ι → Set X} (hs : ∀ i ∈ t, MeasurableSet (s i)) (hf : ∀ i ∈ t, IntegrableOn f (s i) μ) : ∫ x in ⋃ i ∈ t, s i, f x ∂μ = ∑ u ∈ t.powerset with u.Nonempty, (-1 : ℝ) ^ (#u + 1) • ∫ x in ⋂ i ∈ u, s i, f x ∂μ := by simp_rw [← integral_smul, ← integral_indicator (Finset.measurableSet_biUnion _ hs)] have A (u) (hu : u ∈ t.powerset.filter (·.Nonempty)) : MeasurableSet (⋂ i ∈ u, s i) := by refine u.measurableSet_biInter fun i hi ↦ hs i ?_ aesop have : ∑ x ∈ t.powerset with x.Nonempty, ∫ (a : X) in ⋂ i ∈ x, s i, (-1 : ℝ) ^ (#x + 1) • f a ∂μ = ∑ x ∈ t.powerset with x.Nonempty, ∫ a, indicator (⋂ i ∈ x, s i) (fun a ↦ (-1 : ℝ) ^ (#x + 1) • f a) a ∂μ := by apply Finset.sum_congr rfl (fun x hx ↦ ?_) rw [← integral_indicator (A x hx)] rw [this, ← integral_finset_sum]; swap · intro u hu rw [integrable_indicator_iff (A u hu)] apply Integrable.smul simp only [Finset.mem_filter, Finset.mem_powerset] at hu rcases hu.2 with ⟨i, hi⟩ exact (hf i (hu.1 hi)).mono (biInter_subset_of_mem hi) le_rfl congr with x convert Finset.indicator_biUnion_eq_sum_powerset t s f x with u hu rw [indicator_smul_apply] norm_cast theorem ofReal_setIntegral_one_of_measure_ne_top {X : Type*} {m : MeasurableSpace X} {μ : Measure X} {s : Set X} (hs : μ s ≠ ∞ := by finiteness) : ENNReal.ofReal (∫ _ in s, (1 : ℝ) ∂μ) = μ s := calc ENNReal.ofReal (∫ _ in s, (1 : ℝ) ∂μ) = ENNReal.ofReal (∫ _ in s, ‖(1 : ℝ)‖ ∂μ) := by simp only [norm_one] _ = ∫⁻ _ in s, 1 ∂μ := by simp [measureReal_def, hs] _ = μ s := setLIntegral_one _ theorem ofReal_setIntegral_one {X : Type*} {_ : MeasurableSpace X} (μ : Measure X) [IsFiniteMeasure μ] (s : Set X) : ENNReal.ofReal (∫ _ in s, (1 : ℝ) ∂μ) = μ s := ofReal_setIntegral_one_of_measure_ne_top theorem setIntegral_one_eq_measureReal {X : Type*} {m : MeasurableSpace X} {μ : Measure X} {s : Set X} : ∫ _ in s, (1 : ℝ) ∂μ = μ.real s := by simp /-- **Inclusion-exclusion principle** for the measure of a union of sets of finite measure. The measure of the union of the `s i` over `i ∈ t` is the alternating sum of the measures of the intersections of the `s i`. -/ theorem measureReal_biUnion_eq_sum_powerset {ι : Type*} {t : Finset ι} {s : ι → Set X} (hs : ∀ i ∈ t, MeasurableSet (s i)) (hf : ∀ i ∈ t, μ (s i) ≠ ∞ := by finiteness) : μ.real (⋃ i ∈ t, s i) = ∑ u ∈ t.powerset with u.Nonempty, (-1 : ℝ) ^ (#u + 1) * μ.real (⋂ i ∈ u, s i) := by simp_rw [← setIntegral_one_eq_measureReal] apply integral_biUnion_eq_sum_powerset hs intro i hi simpa using (hf i hi).lt_top theorem integral_piecewise [DecidablePred (· ∈ s)] (hs : MeasurableSet s) (hf : IntegrableOn f s μ) (hg : IntegrableOn g sᶜ μ) : ∫ x, s.piecewise f g x ∂μ = ∫ x in s, f x ∂μ + ∫ x in sᶜ, g x ∂μ := by rw [← Set.indicator_add_compl_eq_piecewise, integral_add' (hf.integrable_indicator hs) (hg.integrable_indicator hs.compl), integral_indicator hs, integral_indicator hs.compl] theorem tendsto_setIntegral_of_monotone {ι : Type*} [Preorder ι] [(atTop : Filter ι).IsCountablyGenerated] {s : ι → Set X} (hsm : ∀ i, MeasurableSet (s i)) (h_mono : Monotone s) (hfi : IntegrableOn f (⋃ n, s n) μ) : Tendsto (fun i => ∫ x in s i, f x ∂μ) atTop (𝓝 (∫ x in ⋃ n, s n, f x ∂μ)) := by refine .of_neBot_imp fun hne ↦ ?_ have := (atTop_neBot_iff.mp hne).2 have hfi' : ∫⁻ x in ⋃ n, s n, ‖f x‖₊ ∂μ < ∞ := hfi.2 set S := ⋃ i, s i have hSm : MeasurableSet S := MeasurableSet.iUnion_of_monotone h_mono hsm have hsub {i} : s i ⊆ S := subset_iUnion s i rw [← withDensity_apply _ hSm] at hfi' set ν := μ.withDensity (‖f ·‖ₑ) with hν refine Metric.nhds_basis_closedBall.tendsto_right_iff.2 fun ε ε0 => ?_ lift ε to ℝ≥0 using ε0.le have : ∀ᶠ i in atTop, ν (s i) ∈ Icc (ν S - ε) (ν S + ε) := tendsto_measure_iUnion_atTop h_mono (ENNReal.Icc_mem_nhds hfi'.ne (ENNReal.coe_pos.2 ε0).ne') filter_upwards [this] with i hi rw [mem_closedBall_iff_norm', ← integral_diff (hsm i) hfi hsub, ← coe_nnnorm, NNReal.coe_le_coe, ← ENNReal.coe_le_coe] refine (enorm_integral_le_lintegral_enorm _).trans ?_ rw [← withDensity_apply _ (hSm.diff (hsm _)), ← hν, measure_diff hsub (hsm _).nullMeasurableSet] exacts [tsub_le_iff_tsub_le.mp hi.1, (hi.2.trans_lt <| ENNReal.add_lt_top.2 ⟨hfi', ENNReal.coe_lt_top⟩).ne] theorem tendsto_setIntegral_of_antitone {ι : Type*} [Preorder ι] [(atTop : Filter ι).IsCountablyGenerated] {s : ι → Set X} (hsm : ∀ i, MeasurableSet (s i)) (h_anti : Antitone s) (hfi : ∃ i, IntegrableOn f (s i) μ) : Tendsto (fun i ↦ ∫ x in s i, f x ∂μ) atTop (𝓝 (∫ x in ⋂ n, s n, f x ∂μ)) := by refine .of_neBot_imp fun hne ↦ ?_ have := (atTop_neBot_iff.mp hne).2 rcases hfi with ⟨i₀, hi₀⟩ suffices Tendsto (∫ x in s i₀, f x ∂μ - ∫ x in s i₀ \ s ·, f x ∂μ) atTop (𝓝 (∫ x in s i₀, f x ∂μ - ∫ x in ⋃ i, s i₀ \ s i, f x ∂μ)) by convert this.congr' <| (eventually_ge_atTop i₀).mono fun i hi ↦ ?_ · rw [← diff_iInter, integral_diff _ hi₀ (iInter_subset _ _), sub_sub_cancel] exact .iInter_of_antitone h_anti hsm · rw [integral_diff (hsm i) hi₀ (h_anti hi), sub_sub_cancel] apply tendsto_const_nhds.sub refine tendsto_setIntegral_of_monotone (by measurability) ?_ ?_ · exact fun i j h ↦ diff_subset_diff_right (h_anti h) · rw [← diff_iInter] exact hi₀.mono_set diff_subset theorem hasSum_integral_iUnion_ae {ι : Type*} [Countable ι] {s : ι → Set X} (hm : ∀ i, NullMeasurableSet (s i) μ) (hd : Pairwise (AEDisjoint μ on s)) (hfi : IntegrableOn f (⋃ i, s i) μ) : HasSum (fun n => ∫ x in s n, f x ∂μ) (∫ x in ⋃ n, s n, f x ∂μ) := by simp only [IntegrableOn, Measure.restrict_iUnion_ae hd hm] at hfi ⊢ exact hasSum_integral_measure hfi theorem hasSum_integral_iUnion {ι : Type*} [Countable ι] {s : ι → Set X} (hm : ∀ i, MeasurableSet (s i)) (hd : Pairwise (Disjoint on s)) (hfi : IntegrableOn f (⋃ i, s i) μ) : HasSum (fun n => ∫ x in s n, f x ∂μ) (∫ x in ⋃ n, s n, f x ∂μ) := hasSum_integral_iUnion_ae (fun i => (hm i).nullMeasurableSet) (hd.mono fun _ _ h => h.aedisjoint) hfi theorem integral_iUnion {ι : Type*} [Countable ι] {s : ι → Set X} (hm : ∀ i, MeasurableSet (s i)) (hd : Pairwise (Disjoint on s)) (hfi : IntegrableOn f (⋃ i, s i) μ) : ∫ x in ⋃ n, s n, f x ∂μ = ∑' n, ∫ x in s n, f x ∂μ := (HasSum.tsum_eq (hasSum_integral_iUnion hm hd hfi)).symm theorem integral_iUnion_ae {ι : Type*} [Countable ι] {s : ι → Set X} (hm : ∀ i, NullMeasurableSet (s i) μ) (hd : Pairwise (AEDisjoint μ on s)) (hfi : IntegrableOn f (⋃ i, s i) μ) : ∫ x in ⋃ n, s n, f x ∂μ = ∑' n, ∫ x in s n, f x ∂μ := (HasSum.tsum_eq (hasSum_integral_iUnion_ae hm hd hfi)).symm theorem setIntegral_eq_zero_of_ae_eq_zero (ht_eq : ∀ᵐ x ∂μ, x ∈ t → f x = 0) : ∫ x in t, f x ∂μ = 0 := by by_cases hf : AEStronglyMeasurable f (μ.restrict t); swap · rw [integral_undef] contrapose! hf exact hf.1 have : ∫ x in t, hf.mk f x ∂μ = 0 := by refine integral_eq_zero_of_ae ?_ rw [EventuallyEq, ae_restrict_iff (hf.stronglyMeasurable_mk.measurableSet_eq_fun stronglyMeasurable_zero)] filter_upwards [ae_imp_of_ae_restrict hf.ae_eq_mk, ht_eq] with x hx h'x h''x rw [← hx h''x] exact h'x h''x rw [← this] exact integral_congr_ae hf.ae_eq_mk theorem setIntegral_eq_zero_of_forall_eq_zero (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in t, f x ∂μ = 0 := setIntegral_eq_zero_of_ae_eq_zero (Eventually.of_forall ht_eq) theorem integral_union_eq_left_of_ae_aux (ht_eq : ∀ᵐ x ∂μ.restrict t, f x = 0) (haux : StronglyMeasurable f) (H : IntegrableOn f (s ∪ t) μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ := by let k := f ⁻¹' {0} have hk : MeasurableSet k := by borelize E; exact haux.measurable (measurableSet_singleton _) have h's : IntegrableOn f s μ := H.mono subset_union_left le_rfl have A : ∀ u : Set X, ∫ x in u ∩ k, f x ∂μ = 0 := fun u => setIntegral_eq_zero_of_forall_eq_zero fun x hx => hx.2 rw [← integral_inter_add_diff hk h's, ← integral_inter_add_diff hk H, A, A, zero_add, zero_add, union_diff_distrib, union_comm] apply setIntegral_congr_set rw [union_ae_eq_right] apply measure_mono_null diff_subset rw [measure_eq_zero_iff_ae_notMem] filter_upwards [ae_imp_of_ae_restrict ht_eq] with x hx h'x using h'x.2 (hx h'x.1) theorem integral_union_eq_left_of_ae (ht_eq : ∀ᵐ x ∂μ.restrict t, f x = 0) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ := by have ht : IntegrableOn f t μ := by apply integrableOn_zero.congr_fun_ae; symm; exact ht_eq by_cases H : IntegrableOn f (s ∪ t) μ; swap · rw [integral_undef H, integral_undef]; simpa [integrableOn_union, ht] using H let f' := H.1.mk f calc ∫ x : X in s ∪ t, f x ∂μ = ∫ x : X in s ∪ t, f' x ∂μ := integral_congr_ae H.1.ae_eq_mk _ = ∫ x in s, f' x ∂μ := by apply integral_union_eq_left_of_ae_aux _ H.1.stronglyMeasurable_mk (H.congr_fun_ae H.1.ae_eq_mk) filter_upwards [ht_eq, ae_mono (Measure.restrict_mono subset_union_right le_rfl) H.1.ae_eq_mk] with x hx h'x rw [← h'x, hx] _ = ∫ x in s, f x ∂μ := integral_congr_ae (ae_mono (Measure.restrict_mono subset_union_left le_rfl) H.1.ae_eq_mk.symm) theorem integral_union_eq_left_of_forall₀ {f : X → E} (ht : NullMeasurableSet t μ) (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ := integral_union_eq_left_of_ae ((ae_restrict_iff'₀ ht).2 (Eventually.of_forall ht_eq)) theorem integral_union_eq_left_of_forall {f : X → E} (ht : MeasurableSet t) (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ := integral_union_eq_left_of_forall₀ ht.nullMeasurableSet ht_eq theorem setIntegral_eq_of_subset_of_ae_diff_eq_zero_aux (hts : s ⊆ t) (h't : ∀ᵐ x ∂μ, x ∈ t \ s → f x = 0) (haux : StronglyMeasurable f) (h'aux : IntegrableOn f t μ) : ∫ x in t, f x ∂μ = ∫ x in s, f x ∂μ := by let k := f ⁻¹' {0} have hk : MeasurableSet k := by borelize E; exact haux.measurable (measurableSet_singleton _) calc ∫ x in t, f x ∂μ = ∫ x in t ∩ k, f x ∂μ + ∫ x in t \ k, f x ∂μ := by rw [integral_inter_add_diff hk h'aux] _ = ∫ x in t \ k, f x ∂μ := by rw [setIntegral_eq_zero_of_forall_eq_zero fun x hx => ?_, zero_add]; exact hx.2 _ = ∫ x in s \ k, f x ∂μ := by apply setIntegral_congr_set filter_upwards [h't] with x hx change (x ∈ t \ k) = (x ∈ s \ k) simp only [eq_iff_iff, and_congr_left_iff, mem_diff] intro h'x by_cases xs : x ∈ s · simp only [xs, hts xs] · simp only [xs, iff_false] intro xt exact h'x (hx ⟨xt, xs⟩) _ = ∫ x in s ∩ k, f x ∂μ + ∫ x in s \ k, f x ∂μ := by have : ∀ x ∈ s ∩ k, f x = 0 := fun x hx => hx.2 rw [setIntegral_eq_zero_of_forall_eq_zero this, zero_add] _ = ∫ x in s, f x ∂μ := by rw [integral_inter_add_diff hk (h'aux.mono hts le_rfl)] /-- If a function vanishes almost everywhere on `t \ s` with `s ⊆ t`, then its integrals on `s` and `t` coincide if `t` is null-measurable. -/ theorem setIntegral_eq_of_subset_of_ae_diff_eq_zero (ht : NullMeasurableSet t μ) (hts : s ⊆ t) (h't : ∀ᵐ x ∂μ, x ∈ t \ s → f x = 0) : ∫ x in t, f x ∂μ = ∫ x in s, f x ∂μ := by by_cases h : IntegrableOn f t μ; swap · have : ¬IntegrableOn f s μ := fun H => h (H.of_ae_diff_eq_zero ht h't) rw [integral_undef h, integral_undef this] let f' := h.1.mk f calc ∫ x in t, f x ∂μ = ∫ x in t, f' x ∂μ := integral_congr_ae h.1.ae_eq_mk _ = ∫ x in s, f' x ∂μ := by apply setIntegral_eq_of_subset_of_ae_diff_eq_zero_aux hts _ h.1.stronglyMeasurable_mk (h.congr h.1.ae_eq_mk) filter_upwards [h't, ae_imp_of_ae_restrict h.1.ae_eq_mk] with x hx h'x h''x rw [← h'x h''x.1, hx h''x] _ = ∫ x in s, f x ∂μ := by apply integral_congr_ae apply ae_restrict_of_ae_restrict_of_subset hts exact h.1.ae_eq_mk.symm /-- If a function vanishes on `t \ s` with `s ⊆ t`, then its integrals on `s` and `t` coincide if `t` is measurable. -/ theorem setIntegral_eq_of_subset_of_forall_diff_eq_zero (ht : MeasurableSet t) (hts : s ⊆ t) (h't : ∀ x ∈ t \ s, f x = 0) : ∫ x in t, f x ∂μ = ∫ x in s, f x ∂μ := setIntegral_eq_of_subset_of_ae_diff_eq_zero ht.nullMeasurableSet hts (Eventually.of_forall fun x hx => h't x hx) /-- If a function vanishes almost everywhere on `sᶜ`, then its integral on `s` coincides with its integral on the whole space. -/ theorem setIntegral_eq_integral_of_ae_compl_eq_zero (h : ∀ᵐ x ∂μ, x ∉ s → f x = 0) : ∫ x in s, f x ∂μ = ∫ x, f x ∂μ := by symm nth_rw 1 [← setIntegral_univ] apply setIntegral_eq_of_subset_of_ae_diff_eq_zero nullMeasurableSet_univ (subset_univ _) filter_upwards [h] with x hx h'x using hx h'x.2 /-- If a function vanishes on `sᶜ`, then its integral on `s` coincides with its integral on the whole space. -/ theorem setIntegral_eq_integral_of_forall_compl_eq_zero (h : ∀ x, x ∉ s → f x = 0) : ∫ x in s, f x ∂μ = ∫ x, f x ∂μ := setIntegral_eq_integral_of_ae_compl_eq_zero (Eventually.of_forall h) theorem setIntegral_neg_eq_setIntegral_nonpos [PartialOrder E] {f : X → E} (hf : AEStronglyMeasurable f μ) : ∫ x in {x | f x < 0}, f x ∂μ = ∫ x in {x | f x ≤ 0}, f x ∂μ := by have h_union : {x | f x ≤ 0} = {x | f x < 0} ∪ {x | f x = 0} := by simp_rw [le_iff_lt_or_eq, setOf_or] rw [h_union] have B : NullMeasurableSet {x | f x = 0} μ := hf.nullMeasurableSet_eq_fun aestronglyMeasurable_zero symm refine integral_union_eq_left_of_ae ?_ filter_upwards [ae_restrict_mem₀ B] with x hx using hx theorem integral_norm_eq_pos_sub_neg {f : X → ℝ} (hfi : Integrable f μ) : ∫ x, ‖f x‖ ∂μ = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ := have h_meas : NullMeasurableSet {x | 0 ≤ f x} μ := aestronglyMeasurable_const.nullMeasurableSet_le hfi.1 calc ∫ x, ‖f x‖ ∂μ = ∫ x in {x | 0 ≤ f x}, ‖f x‖ ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ‖f x‖ ∂μ := by rw [← integral_add_compl₀ h_meas hfi.norm] _ = ∫ x in {x | 0 ≤ f x}, f x ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ‖f x‖ ∂μ := by congr 1 refine setIntegral_congr_fun₀ h_meas fun x hx => ?_ dsimp only rw [Real.norm_eq_abs, abs_eq_self.mpr _] exact hx _ = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | 0 ≤ f x}ᶜ, f x ∂μ := by congr 1 rw [← integral_neg] refine setIntegral_congr_fun₀ h_meas.compl fun x hx => ?_ dsimp only rw [Real.norm_eq_abs, abs_eq_neg_self.mpr _] rw [Set.mem_compl_iff, Set.notMem_setOf_iff] at hx linarith _ = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ := by rw [← setIntegral_neg_eq_setIntegral_nonpos hfi.1, compl_setOf]; simp only [not_le] theorem setIntegral_const [CompleteSpace E] (c : E) : ∫ _ in s, c ∂μ = μ.real s • c := by rw [integral_const, measureReal_restrict_apply_univ] @[simp] theorem integral_indicator_const [CompleteSpace E] (e : E) ⦃s : Set X⦄ (s_meas : MeasurableSet s) : ∫ x : X, s.indicator (fun _ : X => e) x ∂μ = μ.real s • e := by rw [integral_indicator s_meas, ← setIntegral_const] @[simp] theorem integral_indicator_one ⦃s : Set X⦄ (hs : MeasurableSet s) : ∫ x, s.indicator 1 x ∂μ = μ.real s := (integral_indicator_const 1 hs).trans ((smul_eq_mul ..).trans (mul_one _)) theorem setIntegral_indicatorConstLp [CompleteSpace E] {p : ℝ≥0∞} (hs : MeasurableSet s) (ht : MeasurableSet t) (hμt : μ t ≠ ∞) (e : E) : ∫ x in s, indicatorConstLp p ht hμt e x ∂μ = μ.real (t ∩ s) • e := calc ∫ x in s, indicatorConstLp p ht hμt e x ∂μ = ∫ x in s, t.indicator (fun _ => e) x ∂μ := by rw [setIntegral_congr_ae hs (indicatorConstLp_coeFn.mono fun x hx _ => hx)] _ = (μ.real (t ∩ s)) • e := by rw [integral_indicator_const _ ht, measureReal_restrict_apply ht] theorem integral_indicatorConstLp [CompleteSpace E] {p : ℝ≥0∞} (ht : MeasurableSet t) (hμt : μ t ≠ ∞) (e : E) : ∫ x, indicatorConstLp p ht hμt e x ∂μ = μ.real t • e := calc ∫ x, indicatorConstLp p ht hμt e x ∂μ = ∫ x in univ, indicatorConstLp p ht hμt e x ∂μ := by rw [setIntegral_univ] _ = μ.real (t ∩ univ) • e := setIntegral_indicatorConstLp MeasurableSet.univ ht hμt e _ = μ.real t • e := by rw [inter_univ] theorem setIntegral_map {Y} [MeasurableSpace Y] {g : X → Y} {f : Y → E} {s : Set Y} (hs : MeasurableSet s) (hf : AEStronglyMeasurable f (Measure.map g μ)) (hg : AEMeasurable g μ) : ∫ y in s, f y ∂Measure.map g μ = ∫ x in g ⁻¹' s, f (g x) ∂μ := by rw [Measure.restrict_map_of_aemeasurable hg hs, integral_map (hg.mono_measure Measure.restrict_le_self) (hf.mono_measure _)] exact Measure.map_mono_of_aemeasurable Measure.restrict_le_self hg theorem _root_.MeasurableEmbedding.setIntegral_map {Y} {_ : MeasurableSpace Y} {f : X → Y} (hf : MeasurableEmbedding f) (g : Y → E) (s : Set Y) : ∫ y in s, g y ∂Measure.map f μ = ∫ x in f ⁻¹' s, g (f x) ∂μ := by rw [hf.restrict_map, hf.integral_map] theorem _root_.Topology.IsClosedEmbedding.setIntegral_map [TopologicalSpace X] [BorelSpace X] {Y} [MeasurableSpace Y] [TopologicalSpace Y] [BorelSpace Y] {g : X → Y} {f : Y → E} (s : Set Y) (hg : IsClosedEmbedding g) : ∫ y in s, f y ∂Measure.map g μ = ∫ x in g ⁻¹' s, f (g x) ∂μ := hg.measurableEmbedding.setIntegral_map _ _ theorem MeasurePreserving.setIntegral_preimage_emb {Y} {_ : MeasurableSpace Y} {f : X → Y} {ν} (h₁ : MeasurePreserving f μ ν) (h₂ : MeasurableEmbedding f) (g : Y → E) (s : Set Y) : ∫ x in f ⁻¹' s, g (f x) ∂μ = ∫ y in s, g y ∂ν := (h₁.restrict_preimage_emb h₂ s).integral_comp h₂ _ theorem MeasurePreserving.setIntegral_image_emb {Y} {_ : MeasurableSpace Y} {f : X → Y} {ν} (h₁ : MeasurePreserving f μ ν) (h₂ : MeasurableEmbedding f) (g : Y → E) (s : Set X) : ∫ y in f '' s, g y ∂ν = ∫ x in s, g (f x) ∂μ := Eq.symm <| (h₁.restrict_image_emb h₂ s).integral_comp h₂ _ theorem setIntegral_map_equiv {Y} [MeasurableSpace Y] (e : X ≃ᵐ Y) (f : Y → E) (s : Set Y) : ∫ y in s, f y ∂Measure.map e μ = ∫ x in e ⁻¹' s, f (e x) ∂μ := e.measurableEmbedding.setIntegral_map f s theorem norm_setIntegral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ.restrict s, ‖f x‖ ≤ C) : ‖∫ x in s, f x ∂μ‖ ≤ C * μ.real s := by rw [← Measure.restrict_apply_univ] at * haveI : IsFiniteMeasure (μ.restrict s) := ⟨hs⟩ simpa using norm_integral_le_of_norm_le_const hC theorem norm_setIntegral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ, x ∈ s → ‖f x‖ ≤ C) : ‖∫ x in s, f x ∂μ‖ ≤ C * μ.real s := by by_cases hfm : AEStronglyMeasurable f (μ.restrict s) · apply norm_setIntegral_le_of_norm_le_const_ae hs have A : ∀ᵐ x : X ∂μ, x ∈ s → ‖AEStronglyMeasurable.mk f hfm x‖ ≤ C := by filter_upwards [hC, hfm.ae_mem_imp_eq_mk] with _ h1 h2 h3 rw [← h2 h3] exact h1 h3 have B : MeasurableSet {x | ‖hfm.mk f x‖ ≤ C} := hfm.stronglyMeasurable_mk.norm.measurable measurableSet_Iic filter_upwards [hfm.ae_eq_mk, (ae_restrict_iff B).2 A] with _ h1 _ rwa [h1] · rw [integral_non_aestronglyMeasurable hfm] have : ∃ᵐ (x : X) ∂μ, x ∈ s := by apply frequently_ae_mem_iff.mpr contrapose! hfm simp [Measure.restrict_eq_zero.mpr hfm] rcases (this.and_eventually hC).exists with ⟨x, hx, h'x⟩ have : 0 ≤ C := (norm_nonneg _).trans (h'x hx) simp only [norm_zero, ge_iff_le] positivity theorem norm_setIntegral_le_of_norm_le_const {C : ℝ} (hs : μ s < ∞) (hC : ∀ x ∈ s, ‖f x‖ ≤ C) : ‖∫ x in s, f x ∂μ‖ ≤ C * μ.real s := norm_setIntegral_le_of_norm_le_const_ae' hs (Eventually.of_forall hC) theorem norm_integral_sub_setIntegral_le [IsFiniteMeasure μ] {C : ℝ} (hf : ∀ᵐ (x : X) ∂μ, ‖f x‖ ≤ C) {s : Set X} (hs : MeasurableSet s) (hf1 : Integrable f μ) : ‖∫ (x : X), f x ∂μ - ∫ x in s, f x ∂μ‖ ≤ μ.real sᶜ * C := by have h0 : ∫ (x : X), f x ∂μ - ∫ x in s, f x ∂μ = ∫ x in sᶜ, f x ∂μ := by rw [sub_eq_iff_eq_add, add_comm, integral_add_compl hs hf1] have h1 : ∫ x in sᶜ, ‖f x‖ ∂μ ≤ ∫ _ in sᶜ, C ∂μ := integral_mono_ae hf1.norm.restrict (integrable_const C) (ae_restrict_of_ae hf) have h2 : ∫ _ in sᶜ, C ∂μ = μ.real sᶜ * C := by rw [setIntegral_const C, smul_eq_mul] rw [h0, ← h2] exact le_trans (norm_integral_le_integral_norm f) h1 theorem setIntegral_eq_zero_iff_of_nonneg_ae {f : X → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : IntegrableOn f s μ) : ∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 := integral_eq_zero_iff_of_nonneg_ae hf hfi theorem setIntegral_pos_iff_support_of_nonneg_ae {f : X → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : IntegrableOn f s μ) : (0 < ∫ x in s, f x ∂μ) ↔ 0 < μ (support f ∩ s) := by rw [integral_pos_iff_support_of_nonneg_ae hf hfi, Measure.restrict_apply₀] rw [support_eq_preimage] exact hfi.aestronglyMeasurable.aemeasurable.nullMeasurable (measurableSet_singleton 0).compl theorem setIntegral_gt_gt {R : ℝ} {f : X → ℝ} (hR : 0 ≤ R) (hfint : IntegrableOn f {x | ↑R < f x} μ) (hμ : μ {x | ↑R < f x} ≠ 0) : μ.real {x | ↑R < f x} * R < ∫ x in {x | ↑R < f x}, f x ∂μ := by have : IntegrableOn (fun _ => R) {x | ↑R < f x} μ := by refine ⟨aestronglyMeasurable_const, lt_of_le_of_lt ?_ hfint.2⟩ refine setLIntegral_mono_ae hfint.1.enorm <| ae_of_all _ fun x hx => ?_ simp only [ENNReal.coe_le_coe, Real.nnnorm_of_nonneg hR, enorm_eq_nnnorm, Real.nnnorm_of_nonneg (hR.trans <| le_of_lt hx)] exact le_of_lt hx rw [← sub_pos, ← smul_eq_mul, ← setIntegral_const, ← integral_sub hfint this, setIntegral_pos_iff_support_of_nonneg_ae] · rw [← zero_lt_iff] at hμ rwa [Set.inter_eq_self_of_subset_right] exact fun x hx => Ne.symm (ne_of_lt <| sub_pos.2 hx) · rw [Pi.zero_def, EventuallyLE, ae_restrict_iff₀] · exact Eventually.of_forall fun x hx => sub_nonneg.2 <| le_of_lt hx · exact nullMeasurableSet_le aemeasurable_zero (hfint.1.aemeasurable.sub aemeasurable_const) · exact Integrable.sub hfint this theorem setIntegral_trim {X} {m m0 : MeasurableSpace X} {μ : Measure X} (hm : m ≤ m0) {f : X → E} (hf_meas : StronglyMeasurable[m] f) {s : Set X} (hs : MeasurableSet[m] s) : ∫ x in s, f x ∂μ = ∫ x in s, f x ∂μ.trim hm := by rwa [integral_trim hm hf_meas, restrict_trim hm μ] /-! ### Lemmas about adding and removing interval boundaries The primed lemmas take explicit arguments about the endpoint having zero measure, while the unprimed ones use `[NoAtoms μ]`. -/ section PartialOrder variable [PartialOrder X] {x y : X} theorem integral_Icc_eq_integral_Ioc' (hx : μ {x} = 0) : ∫ t in Icc x y, f t ∂μ = ∫ t in Ioc x y, f t ∂μ := setIntegral_congr_set (Ioc_ae_eq_Icc' hx).symm theorem integral_Icc_eq_integral_Ico' (hy : μ {y} = 0) : ∫ t in Icc x y, f t ∂μ = ∫ t in Ico x y, f t ∂μ := setIntegral_congr_set (Ico_ae_eq_Icc' hy).symm theorem integral_Ioc_eq_integral_Ioo' (hy : μ {y} = 0) : ∫ t in Ioc x y, f t ∂μ = ∫ t in Ioo x y, f t ∂μ := setIntegral_congr_set (Ioo_ae_eq_Ioc' hy).symm theorem integral_Ico_eq_integral_Ioo' (hx : μ {x} = 0) : ∫ t in Ico x y, f t ∂μ = ∫ t in Ioo x y, f t ∂μ := setIntegral_congr_set (Ioo_ae_eq_Ico' hx).symm theorem integral_Icc_eq_integral_Ioo' (hx : μ {x} = 0) (hy : μ {y} = 0) : ∫ t in Icc x y, f t ∂μ = ∫ t in Ioo x y, f t ∂μ := setIntegral_congr_set (Ioo_ae_eq_Icc' hx hy).symm theorem integral_Iic_eq_integral_Iio' (hx : μ {x} = 0) : ∫ t in Iic x, f t ∂μ = ∫ t in Iio x, f t ∂μ := setIntegral_congr_set (Iio_ae_eq_Iic' hx).symm theorem integral_Ici_eq_integral_Ioi' (hx : μ {x} = 0) : ∫ t in Ici x, f t ∂μ = ∫ t in Ioi x, f t ∂μ := setIntegral_congr_set (Ioi_ae_eq_Ici' hx).symm variable [NoAtoms μ] theorem integral_Icc_eq_integral_Ioc : ∫ t in Icc x y, f t ∂μ = ∫ t in Ioc x y, f t ∂μ := integral_Icc_eq_integral_Ioc' <| measure_singleton x theorem integral_Icc_eq_integral_Ico : ∫ t in Icc x y, f t ∂μ = ∫ t in Ico x y, f t ∂μ := integral_Icc_eq_integral_Ico' <| measure_singleton y theorem integral_Ioc_eq_integral_Ioo : ∫ t in Ioc x y, f t ∂μ = ∫ t in Ioo x y, f t ∂μ := integral_Ioc_eq_integral_Ioo' <| measure_singleton y theorem integral_Ico_eq_integral_Ioo : ∫ t in Ico x y, f t ∂μ = ∫ t in Ioo x y, f t ∂μ := integral_Ico_eq_integral_Ioo' <| measure_singleton x theorem integral_Icc_eq_integral_Ioo : ∫ t in Icc x y, f t ∂μ = ∫ t in Ioo x y, f t ∂μ := by rw [integral_Icc_eq_integral_Ico, integral_Ico_eq_integral_Ioo] theorem integral_Iic_eq_integral_Iio : ∫ t in Iic x, f t ∂μ = ∫ t in Iio x, f t ∂μ := integral_Iic_eq_integral_Iio' <| measure_singleton x theorem integral_Ici_eq_integral_Ioi : ∫ t in Ici x, f t ∂μ = ∫ t in Ioi x, f t ∂μ := integral_Ici_eq_integral_Ioi' <| measure_singleton x end PartialOrder end NormedAddCommGroup section Mono variable [NormedAddCommGroup E] [NormedSpace ℝ E] [PartialOrder E] [IsOrderedAddMonoid E] [IsOrderedModule ℝ E] [OrderClosedTopology E] {μ : Measure X} {f g : X → E} {s t : Set X} section variable (hf : IntegrableOn f s μ) (hg : IntegrableOn g s μ) include hf hg theorem setIntegral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict s] g) : ∫ x in s, f x ∂μ ≤ ∫ x in s, g x ∂μ := by by_cases hE : CompleteSpace E · exact integral_mono_ae hf hg h · simp [integral, hE] theorem setIntegral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ x in s, f x ∂μ ≤ ∫ x in s, g x ∂μ := setIntegral_mono_ae_restrict hf hg (ae_restrict_of_ae h) theorem setIntegral_mono_on (hs : MeasurableSet s) (h : ∀ x ∈ s, f x ≤ g x) : ∫ x in s, f x ∂μ ≤ ∫ x in s, g x ∂μ := setIntegral_mono_ae_restrict hf hg (by simp [hs, EventuallyLE, eventually_inf_principal, ae_of_all _ h]) theorem setIntegral_mono_on_ae (hs : MeasurableSet s) (h : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) : ∫ x in s, f x ∂μ ≤ ∫ x in s, g x ∂μ := by refine setIntegral_mono_ae_restrict hf hg ?_; rwa [EventuallyLE, ae_restrict_iff' hs] lemma setIntegral_mono_on_ae₀ (hs : NullMeasurableSet s μ) (h : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) : ∫ x in s, f x ∂μ ≤ ∫ x in s, g x ∂μ := by rw [setIntegral_congr_set hs.toMeasurable_ae_eq.symm, setIntegral_congr_set hs.toMeasurable_ae_eq.symm] refine setIntegral_mono_on_ae ?_ ?_ ?_ ?_ · rwa [integrableOn_congr_set_ae hs.toMeasurable_ae_eq] · rwa [integrableOn_congr_set_ae hs.toMeasurable_ae_eq] · exact measurableSet_toMeasurable μ s · filter_upwards [hs.toMeasurable_ae_eq.mem_iff, h] with x hx h rwa [hx] @[gcongr high] -- higher priority than `integral_mono` -- this lemma is better because it also gives the `x ∈ s` hypothesis lemma setIntegral_mono_on₀ (hs : NullMeasurableSet s μ) (h : ∀ x ∈ s, f x ≤ g x) : ∫ x in s, f x ∂μ ≤ ∫ x in s, g x ∂μ := setIntegral_mono_on_ae₀ hf hg hs (Eventually.of_forall h) theorem setIntegral_mono (h : f ≤ g) : ∫ x in s, f x ∂μ ≤ ∫ x in s, g x ∂μ := integral_mono hf hg h end theorem setIntegral_mono_set (hfi : IntegrableOn f t μ) (hf : 0 ≤ᵐ[μ.restrict t] f) (hst : s ≤ᵐ[μ] t) : ∫ x in s, f x ∂μ ≤ ∫ x in t, f x ∂μ := integral_mono_measure (Measure.restrict_mono_ae hst) hf hfi theorem setIntegral_le_integral (hfi : Integrable f μ) (hf : 0 ≤ᵐ[μ] f) : ∫ x in s, f x ∂μ ≤ ∫ x, f x ∂μ := integral_mono_measure (Measure.restrict_le_self) hf hfi theorem setIntegral_ge_of_const_le [CompleteSpace E] {c : E} (hs : MeasurableSet s) (hμs : μ s ≠ ∞) (hf : ∀ x ∈ s, c ≤ f x) (hfint : IntegrableOn (fun x : X => f x) s μ) : μ.real s • c ≤ ∫ x in s, f x ∂μ := by rw [← setIntegral_const c] exact setIntegral_mono_on (integrableOn_const hμs) hfint hs hf theorem setIntegral_ge_of_const_le_real {f : X → ℝ} {c : ℝ} (hs : MeasurableSet s) (hμs : μ s ≠ ∞) (hf : ∀ x ∈ s, c ≤ f x) (hfint : IntegrableOn (fun x : X => f x) s μ) : c * μ.real s ≤ ∫ x in s, f x ∂μ := by simpa [mul_comm] using setIntegral_ge_of_const_le hs hμs hf hfint end Mono section Nonneg variable {μ : Measure X} {f : X → ℝ} {s : Set X} theorem setIntegral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict s] f) : 0 ≤ ∫ x in s, f x ∂μ := integral_nonneg_of_ae hf theorem setIntegral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ x in s, f x ∂μ := setIntegral_nonneg_of_ae_restrict (ae_restrict_of_ae hf) theorem setIntegral_nonneg (hs : MeasurableSet s) (hf : ∀ x, x ∈ s → 0 ≤ f x) : 0 ≤ ∫ x in s, f x ∂μ := setIntegral_nonneg_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf)) theorem setIntegral_nonneg_ae (hs : MeasurableSet s) (hf : ∀ᵐ x ∂μ, x ∈ s → 0 ≤ f x) : 0 ≤ ∫ x in s, f x ∂μ := setIntegral_nonneg_of_ae_restrict <| by rwa [EventuallyLE, ae_restrict_iff' hs] theorem setIntegral_le_nonneg {s : Set X} (hs : MeasurableSet s) (hf : StronglyMeasurable f) (hfi : Integrable f μ) : ∫ x in s, f x ∂μ ≤ ∫ x in {y | 0 ≤ f y}, f x ∂μ := by rw [← integral_indicator hs, ← integral_indicator (stronglyMeasurable_const.measurableSet_le hf)] exact integral_mono (hfi.indicator hs) (hfi.indicator (stronglyMeasurable_const.measurableSet_le hf)) (indicator_le_indicator_nonneg s f) theorem setIntegral_nonpos_of_ae_restrict (hf : f ≤ᵐ[μ.restrict s] 0) : ∫ x in s, f x ∂μ ≤ 0 := integral_nonpos_of_ae hf theorem setIntegral_nonpos_of_ae (hf : f ≤ᵐ[μ] 0) : ∫ x in s, f x ∂μ ≤ 0 := setIntegral_nonpos_of_ae_restrict (ae_restrict_of_ae hf) theorem setIntegral_nonpos_ae (hs : MeasurableSet s) (hf : ∀ᵐ x ∂μ, x ∈ s → f x ≤ 0) : ∫ x in s, f x ∂μ ≤ 0 := setIntegral_nonpos_of_ae_restrict <| by rwa [EventuallyLE, ae_restrict_iff' hs] theorem setIntegral_nonpos (hs : MeasurableSet s) (hf : ∀ x, x ∈ s → f x ≤ 0) : ∫ x in s, f x ∂μ ≤ 0 := setIntegral_nonpos_ae hs <| ae_of_all μ hf theorem setIntegral_nonpos_le {s : Set X} (hs : MeasurableSet s) (hf : StronglyMeasurable f) (hfi : Integrable f μ) : ∫ x in {y | f y ≤ 0}, f x ∂μ ≤ ∫ x in s, f x ∂μ := by rw [← integral_indicator hs, ← integral_indicator (hf.measurableSet_le stronglyMeasurable_const)] exact integral_mono (hfi.indicator (hf.measurableSet_le stronglyMeasurable_const)) (hfi.indicator hs) (indicator_nonpos_le_indicator s f) lemma Integrable.measure_le_integral {f : X → ℝ} (f_int : Integrable f μ) (f_nonneg : 0 ≤ᵐ[μ] f) {s : Set X} (hs : ∀ x ∈ s, 1 ≤ f x) : μ s ≤ ENNReal.ofReal (∫ x, f x ∂μ) := by rw [ofReal_integral_eq_lintegral_ofReal f_int f_nonneg] apply meas_le_lintegral₀ · exact ENNReal.continuous_ofReal.measurable.comp_aemeasurable f_int.1.aemeasurable · intro x hx simpa using ENNReal.ofReal_le_ofReal (hs x hx) lemma integral_le_measure {f : X → ℝ} {s : Set X} (hs : ∀ x ∈ s, f x ≤ 1) (h's : ∀ x ∈ sᶜ, f x ≤ 0) : ENNReal.ofReal (∫ x, f x ∂μ) ≤ μ s := by by_cases H : Integrable f μ; swap · simp [integral_undef H] let g x := max (f x) 0 have g_int : Integrable g μ := H.pos_part have : ENNReal.ofReal (∫ x, f x ∂μ) ≤ ENNReal.ofReal (∫ x, g x ∂μ) := by apply ENNReal.ofReal_le_ofReal exact integral_mono H g_int (fun x ↦ le_max_left _ _) apply this.trans rw [ofReal_integral_eq_lintegral_ofReal g_int (Eventually.of_forall (fun x ↦ le_max_right _ _))] apply lintegral_le_meas · intro x apply ENNReal.ofReal_le_of_le_toReal by_cases H : x ∈ s · simpa [g] using hs x H · apply le_trans _ zero_le_one simpa [g] using h's x H · intro x hx simpa [g] using h's x hx end Nonneg section IntegrableUnion variable {ι : Type*} [Countable ι] {μ : Measure X} [NormedAddCommGroup E] theorem integrableOn_iUnion_of_summable_integral_norm {f : X → E} {s : ι → Set X} (hi : ∀ i : ι, IntegrableOn f (s i) μ) (h : Summable fun i : ι => ∫ x : X in s i, ‖f x‖ ∂μ) : IntegrableOn f (iUnion s) μ := by refine ⟨AEStronglyMeasurable.iUnion fun i => (hi i).1, (lintegral_iUnion_le _ _).trans_lt ?_⟩ have B := fun i => lintegral_coe_eq_integral (fun x : X => ‖f x‖₊) (hi i).norm simp_rw [enorm_eq_nnnorm, tsum_congr B] have S' : Summable fun i : ι => (⟨∫ x : X in s i, ‖f x‖₊ ∂μ, integral_nonneg fun x => NNReal.coe_nonneg _⟩ : NNReal) := by rw [← NNReal.summable_coe]; exact h have S'' := ENNReal.tsum_coe_eq S'.hasSum simp_rw [ENNReal.coe_nnreal_eq, NNReal.coe_mk, coe_nnnorm] at S'' convert ENNReal.ofReal_lt_top variable [TopologicalSpace X] [BorelSpace X] [T2Space X] [IsLocallyFiniteMeasure μ] /-- If `s` is a countable family of compact sets, `f` is a continuous function, and the sequence `‖f.restrict (s i)‖ * μ (s i)` is summable, then `f` is integrable on the union of the `s i`. -/ theorem integrableOn_iUnion_of_summable_norm_restrict {f : C(X, E)} {s : ι → Compacts X} (hf : Summable fun i : ι => ‖f.restrict (s i)‖ * μ.real (s i)) : IntegrableOn f (⋃ i : ι, s i) μ := by refine integrableOn_iUnion_of_summable_integral_norm (fun i => (map_continuous f).continuousOn.integrableOn_compact (s i).isCompact) (.of_nonneg_of_le (fun ι => integral_nonneg fun x => norm_nonneg _) (fun i => ?_) hf) rw [← (Real.norm_of_nonneg (integral_nonneg fun x => norm_nonneg _) : ‖_‖ = ∫ x in s i, ‖f x‖ ∂μ)] exact norm_setIntegral_le_of_norm_le_const (s i).isCompact.measure_lt_top fun x hx => (norm_norm (f x)).symm ▸ (f.restrict (s i : Set X)).norm_coe_le_norm ⟨x, hx⟩ /-- If `s` is a countable family of compact sets covering `X`, `f` is a continuous function, and the sequence `‖f.restrict (s i)‖ * μ (s i)` is summable, then `f` is integrable. -/ theorem integrable_of_summable_norm_restrict {f : C(X, E)} {s : ι → Compacts X} (hf : Summable fun i : ι => ‖f.restrict (s i)‖ * μ.real (s i)) (hs : ⋃ i : ι, ↑(s i) = (univ : Set X)) : Integrable f μ := by simpa only [hs, integrableOn_univ] using integrableOn_iUnion_of_summable_norm_restrict hf end IntegrableUnion /-! ### Continuity of the set integral We prove that for any set `s`, the function `fun f : X →₁[μ] E => ∫ x in s, f x ∂μ` is continuous. -/ section ContinuousSetIntegral variable [NormedAddCommGroup E] {𝕜 : Type*} [NormedRing 𝕜] [NormedAddCommGroup F] [Module 𝕜 F] [IsBoundedSMul 𝕜 F] {p : ℝ≥0∞} {μ : Measure X} /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.memLp f).restrict s).toLp f`. This map is additive. -/ theorem Lp_toLp_restrict_add (f g : Lp E p μ) (s : Set X) : ((Lp.memLp (f + g)).restrict s).toLp (⇑(f + g)) = ((Lp.memLp f).restrict s).toLp f + ((Lp.memLp g).restrict s).toLp g := by ext1 refine (ae_restrict_of_ae (Lp.coeFn_add f g)).mp ?_ refine (Lp.coeFn_add (MemLp.toLp f ((Lp.memLp f).restrict s)) (MemLp.toLp g ((Lp.memLp g).restrict s))).mp ?_ refine (MemLp.coeFn_toLp ((Lp.memLp f).restrict s)).mp ?_ refine (MemLp.coeFn_toLp ((Lp.memLp g).restrict s)).mp ?_ refine (MemLp.coeFn_toLp ((Lp.memLp (f + g)).restrict s)).mono fun x hx1 hx2 hx3 hx4 hx5 => ?_ rw [hx4, hx1, Pi.add_apply, hx2, hx3, hx5, Pi.add_apply] /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.memLp f).restrict s).toLp f`. This map commutes with scalar multiplication. -/ theorem Lp_toLp_restrict_smul (c : 𝕜) (f : Lp F p μ) (s : Set X) : ((Lp.memLp (c • f)).restrict s).toLp (⇑(c • f)) = c • ((Lp.memLp f).restrict s).toLp f := by ext1 refine (ae_restrict_of_ae (Lp.coeFn_smul c f)).mp ?_ refine (MemLp.coeFn_toLp ((Lp.memLp f).restrict s)).mp ?_ refine (MemLp.coeFn_toLp ((Lp.memLp (c • f)).restrict s)).mp ?_ refine (Lp.coeFn_smul c (MemLp.toLp f ((Lp.memLp f).restrict s))).mono fun x hx1 hx2 hx3 hx4 => ?_ simp only [hx2, hx1, hx3, hx4, Pi.smul_apply] /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.memLp f).restrict s).toLp f`. This map is non-expansive. -/ theorem norm_Lp_toLp_restrict_le (s : Set X) (f : Lp E p μ) : ‖((Lp.memLp f).restrict s).toLp f‖ ≤ ‖f‖ := by rw [Lp.norm_def, Lp.norm_def, eLpNorm_congr_ae (MemLp.coeFn_toLp _)] refine ENNReal.toReal_mono (Lp.eLpNorm_ne_top _) ?_ exact eLpNorm_mono_measure _ Measure.restrict_le_self variable (X F 𝕜) in /-- Continuous linear map sending a function of `Lp F p μ` to the same function in `Lp F p (μ.restrict s)`. -/ noncomputable def LpToLpRestrictCLM (μ : Measure X) (p : ℝ≥0∞) [hp : Fact (1 ≤ p)] (s : Set X) : Lp F p μ →L[𝕜] Lp F p (μ.restrict s) := @LinearMap.mkContinuous 𝕜 𝕜 (Lp F p μ) (Lp F p (μ.restrict s)) _ _ _ _ _ _ (RingHom.id 𝕜) ⟨⟨fun f => MemLp.toLp f ((Lp.memLp f).restrict s), fun f g => Lp_toLp_restrict_add f g s⟩, fun c f => Lp_toLp_restrict_smul c f s⟩ 1 (by intro f; rw [one_mul]; exact norm_Lp_toLp_restrict_le s f) variable (𝕜) in theorem LpToLpRestrictCLM_coeFn [Fact (1 ≤ p)] (s : Set X) (f : Lp F p μ) : LpToLpRestrictCLM X F 𝕜 μ p s f =ᵐ[μ.restrict s] f := MemLp.coeFn_toLp ((Lp.memLp f).restrict s) @[continuity] theorem continuous_setIntegral [NormedSpace ℝ E] (s : Set X) : Continuous fun f : X →₁[μ] E => ∫ x in s, f x ∂μ := by haveI : Fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_rfl⟩ have h_comp : (fun f : X →₁[μ] E => ∫ x in s, f x ∂μ) = integral (μ.restrict s) ∘ fun f => LpToLpRestrictCLM X E ℝ μ 1 s f := by ext1 f rw [Function.comp_apply, integral_congr_ae (LpToLpRestrictCLM_coeFn ℝ s f)] rw [h_comp] exact continuous_integral.comp (LpToLpRestrictCLM X E ℝ μ 1 s).continuous end ContinuousSetIntegral end MeasureTheory section OpenPos open Measure variable [MeasurableSpace X] [TopologicalSpace X] [OpensMeasurableSpace X] {μ : Measure X} [IsOpenPosMeasure μ] theorem Continuous.integral_pos_of_hasCompactSupport_nonneg_nonzero [IsFiniteMeasureOnCompacts μ] {f : X → ℝ} {x : X} (f_cont : Continuous f) (f_comp : HasCompactSupport f) (f_nonneg : 0 ≤ f) (f_x : f x ≠ 0) : 0 < ∫ x, f x ∂μ := integral_pos_of_integrable_nonneg_nonzero f_cont (f_cont.integrable_of_hasCompactSupport f_comp) f_nonneg f_x end OpenPos section Support variable {M : Type*} [NormedAddCommGroup M] [NormedSpace ℝ M] {mX : MeasurableSpace X} {ν : Measure X} {F : X → M} theorem MeasureTheory.setIntegral_support : ∫ x in support F, F x ∂ν = ∫ x, F x ∂ν := by nth_rw 2 [← setIntegral_univ] rw [setIntegral_eq_of_subset_of_forall_diff_eq_zero MeasurableSet.univ (subset_univ (support F))] exact fun _ hx => notMem_support.mp <| notMem_of_mem_diff hx theorem MeasureTheory.setIntegral_tsupport [TopologicalSpace X] : ∫ x in tsupport F, F x ∂ν = ∫ x, F x ∂ν := by nth_rw 2 [← setIntegral_univ] rw [setIntegral_eq_of_subset_of_forall_diff_eq_zero MeasurableSet.univ (subset_univ (tsupport F))] exact fun _ hx => image_eq_zero_of_notMem_tsupport <| notMem_of_mem_diff hx end Support section thickenedIndicator variable [MeasurableSpace X] [PseudoEMetricSpace X] theorem measure_le_lintegral_thickenedIndicatorAux (μ : Measure X) {E : Set X} (E_mble : MeasurableSet E) (δ : ℝ) : μ E ≤ ∫⁻ x, (thickenedIndicatorAux δ E x : ℝ≥0∞) ∂μ := by convert_to lintegral μ (E.indicator fun _ => (1 : ℝ≥0∞)) ≤ lintegral μ (thickenedIndicatorAux δ E) · rw [lintegral_indicator E_mble] simp only [lintegral_one, Measure.restrict_apply, MeasurableSet.univ, univ_inter] · apply lintegral_mono apply indicator_le_thickenedIndicatorAux theorem measure_le_lintegral_thickenedIndicator (μ : Measure X) {E : Set X} (E_mble : MeasurableSet E) {δ : ℝ} (δ_pos : 0 < δ) : μ E ≤ ∫⁻ x, (thickenedIndicator δ_pos E x : ℝ≥0∞) ∂μ := by convert measure_le_lintegral_thickenedIndicatorAux μ E_mble δ dsimp simp only [thickenedIndicatorAux_lt_top.ne, ENNReal.coe_toNNReal, Ne, not_false_iff] end thickenedIndicator -- We declare a new `{X : Type*}` to discard the instance `[MeasurableSpace X]` -- which has been in scope for the entire file up to this point. variable {X : Type*} section BilinearMap namespace MeasureTheory variable {X : Type*} {f : X → ℝ} {m m0 : MeasurableSpace X} {μ : Measure X} theorem Integrable.simpleFunc_mul (g : SimpleFunc X ℝ) (hf : Integrable f μ) : Integrable (⇑g * f) μ := by refine SimpleFunc.induction (fun c s hs => ?_) (fun g₁ g₂ _ h_int₁ h_int₂ => (h_int₁.add h_int₂).congr (by rw [SimpleFunc.coe_add, add_mul])) g simp only [SimpleFunc.const_zero, SimpleFunc.coe_piecewise, SimpleFunc.coe_const, SimpleFunc.coe_zero, Set.piecewise_eq_indicator] have : Set.indicator s (Function.const X c) * f = s.indicator (c • f) := by ext1 x by_cases hx : x ∈ s · simp only [hx, Pi.mul_apply, Set.indicator_of_mem, Pi.smul_apply, Algebra.id.smul_eq_mul, ← Function.const_def] · simp only [hx, Pi.mul_apply, Set.indicator_of_notMem, not_false_iff, zero_mul] rw [this, integrable_indicator_iff hs] exact (hf.smul c).integrableOn theorem Integrable.simpleFunc_mul' (hm : m ≤ m0) (g : @SimpleFunc X m ℝ) (hf : Integrable f μ) : Integrable (⇑g * f) μ := by rw [← SimpleFunc.coe_toLargerSpace_eq hm g]; exact hf.simpleFunc_mul (g.toLargerSpace hm) end MeasureTheory end BilinearMap section ParametricIntegral variable {G 𝕜 : Type*} [TopologicalSpace X] [TopologicalSpace Y] [MeasurableSpace Y] [OpensMeasurableSpace Y] {μ : Measure Y} [NontriviallyNormedField 𝕜] [NormedAddCommGroup E] [NormedSpace ℝ E] [NormedAddCommGroup F] [NormedSpace 𝕜 F] [NormedAddCommGroup G] [NormedSpace 𝕜 G] open Metric ContinuousLinearMap /-- The parametric integral over a continuous function on a compact set is continuous, under mild assumptions on the topologies involved. -/ theorem continuous_parametric_integral_of_continuous [FirstCountableTopology X] [LocallyCompactSpace X] [SecondCountableTopologyEither Y E] [IsLocallyFiniteMeasure μ] {f : X → Y → E} (hf : Continuous f.uncurry) {s : Set Y} (hs : IsCompact s) : Continuous (∫ y in s, f · y ∂μ) := by rw [continuous_iff_continuousAt] intro x₀ rcases exists_compact_mem_nhds x₀ with ⟨U, U_cpct, U_nhds⟩ rcases (U_cpct.prod hs).bddAbove_image hf.norm.continuousOn with ⟨M, hM⟩ apply continuousAt_of_dominated · filter_upwards with x using Continuous.aestronglyMeasurable (by fun_prop) · filter_upwards [U_nhds] with x x_in rw [ae_restrict_iff] · filter_upwards with t t_in using hM (mem_image_of_mem _ <| mk_mem_prod x_in t_in) · exact (isClosed_le (by fun_prop) (by fun_prop)).measurableSet · exact integrableOn_const hs.measure_ne_top · filter_upwards using (by fun_prop) /-- Consider a parameterized integral `x ↦ ∫ y, L (g y) (f x y)` where `L` is bilinear, `g` is locally integrable and `f` is continuous and uniformly compactly supported. Then the integral depends continuously on `x`. -/ lemma continuousOn_integral_bilinear_of_locally_integrable_of_compact_support [NormedSpace 𝕜 E] (L : F →L[𝕜] G →L[𝕜] E) {f : X → Y → G} {s : Set X} {k : Set Y} {g : Y → F} (hk : IsCompact k) (hf : ContinuousOn f.uncurry (s ×ˢ univ)) (hfs : ∀ p, ∀ x, p ∈ s → x ∉ k → f p x = 0) (hg : IntegrableOn g k μ) : ContinuousOn (fun x ↦ ∫ y, L (g y) (f x y) ∂μ) s := by have A : ∀ p ∈ s, Continuous (f p) := fun p hp ↦ by refine hf.comp_continuous (.prodMk_right _) fun y => ?_ simpa only [prodMk_mem_set_prod_eq, mem_univ, and_true] using hp intro q hq apply Metric.continuousWithinAt_iff'.2 (fun ε εpos ↦ ?_) obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ), 0 < δ ∧ ∫ x in k, ‖L‖ * ‖g x‖ * δ ∂μ < ε := by simpa [integral_mul_const] using exists_pos_mul_lt εpos _ obtain ⟨v, v_mem, hv⟩ : ∃ v ∈ 𝓝[s] q, ∀ p ∈ v, ∀ x ∈ k, dist (f p x) (f q x) < δ := hk.mem_uniformity_of_prod (hf.mono (Set.prod_mono_right (subset_univ k))) hq (dist_mem_uniformity δpos) simp_rw [dist_eq_norm] at hv ⊢ have I : ∀ p ∈ s, IntegrableOn (fun y ↦ L (g y) (f p y)) k μ := by intro p hp obtain ⟨C, hC⟩ : ∃ C, ∀ y, ‖f p y‖ ≤ C := by have : ContinuousOn (f p) k := by have : ContinuousOn (fun y ↦ (p, y)) k := by fun_prop exact hf.comp this (by simp [MapsTo, hp]) rcases IsCompact.exists_bound_of_continuousOn hk this with ⟨C, hC⟩ refine ⟨max C 0, fun y ↦ ?_⟩ by_cases hx : y ∈ k · exact (hC y hx).trans (le_max_left _ _) · simp [hfs p y hp hx] have : IntegrableOn (fun y ↦ ‖L‖ * ‖g y‖ * C) k μ := (hg.norm.const_mul _).mul_const _ apply Integrable.mono' this ?_ ?_ · borelize G apply L.aestronglyMeasurable_comp₂ hg.aestronglyMeasurable apply StronglyMeasurable.aestronglyMeasurable apply Continuous.stronglyMeasurable_of_support_subset_isCompact (A p hp) hk apply support_subset_iff'.2 (fun y hy ↦ hfs p y hp hy) · apply Eventually.of_forall (fun y ↦ (le_opNorm₂ L (g y) (f p y)).trans ?_) gcongr apply hC filter_upwards [v_mem, self_mem_nhdsWithin] with p hp h'p calc ‖∫ x, L (g x) (f p x) ∂μ - ∫ x, L (g x) (f q x) ∂μ‖ = ‖∫ x in k, L (g x) (f p x) ∂μ - ∫ x in k, L (g x) (f q x) ∂μ‖ := by congr 2 · refine (setIntegral_eq_integral_of_forall_compl_eq_zero (fun y hy ↦ ?_)).symm simp [hfs p y h'p hy] · refine (setIntegral_eq_integral_of_forall_compl_eq_zero (fun y hy ↦ ?_)).symm simp [hfs q y hq hy] _ = ‖∫ x in k, L (g x) (f p x) - L (g x) (f q x) ∂μ‖ := by rw [integral_sub (I p h'p) (I q hq)] _ ≤ ∫ x in k, ‖L (g x) (f p x) - L (g x) (f q x)‖ ∂μ := norm_integral_le_integral_norm _ _ ≤ ∫ x in k, ‖L‖ * ‖g x‖ * δ ∂μ := by apply integral_mono_of_nonneg (Eventually.of_forall (fun y ↦ by positivity)) · exact (hg.norm.const_mul _).mul_const _ · filter_upwards with y by_cases hy : y ∈ k · dsimp only specialize hv p hp y hy calc ‖L (g y) (f p y) - L (g y) (f q y)‖ = ‖L (g y) (f p y - f q y)‖ := by simp only [map_sub] _ ≤ ‖L‖ * ‖g y‖ * ‖f p y - f q y‖ := le_opNorm₂ _ _ _ _ ≤ ‖L‖ * ‖g y‖ * δ := by gcongr · simp only [hfs p y h'p hy, hfs q y hq hy, sub_self, norm_zero] positivity _ < ε := hδ /-- Consider a parameterized integral `x ↦ ∫ y, f x y` where `f` is continuous and uniformly compactly supported. Then the integral depends continuously on `x`. -/ lemma continuousOn_integral_of_compact_support {f : X → Y → E} {s : Set X} {k : Set Y} [IsFiniteMeasureOnCompacts μ] (hk : IsCompact k) (hf : ContinuousOn f.uncurry (s ×ˢ univ)) (hfs : ∀ p, ∀ x, p ∈ s → x ∉ k → f p x = 0) : ContinuousOn (fun x ↦ ∫ y, f x y ∂μ) s := by simpa using continuousOn_integral_bilinear_of_locally_integrable_of_compact_support (lsmul ℝ ℝ) hk hf hfs (integrableOn_const hk.measure_ne_top) (g := fun _ ↦ 1) end ParametricIntegral
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Bochner/VitaliCaratheodory.lean
import Mathlib.MeasureTheory.Measure.Regular import Mathlib.Topology.Semicontinuous import Mathlib.MeasureTheory.Integral.Bochner.Basic import Mathlib.Topology.Instances.EReal.Lemmas /-! # Vitali-Carathéodory theorem Vitali-Carathéodory theorem asserts the following. Consider an integrable function `f : α → ℝ` on a space with a regular measure. Then there exists a function `g : α → EReal` such that `f x < g x` everywhere, `g` is lower semicontinuous, and the integral of `g` is arbitrarily close to that of `f`. This theorem is proved in this file, as `exists_lt_lower_semicontinuous_integral_lt`. Symmetrically, there exists `g < f` which is upper semicontinuous, with integral arbitrarily close to that of `f`. It follows from the previous statement applied to `-f`. It is formalized under the name `exists_upper_semicontinuous_lt_integral_gt`. The most classical version of Vitali-Carathéodory theorem only ensures a large inequality `f x ≤ g x`. For applications to the fundamental theorem of calculus, though, the strict inequality `f x < g x` is important. Therefore, we prove the stronger version with strict inequalities in this file. There is a price to pay: we require that the measure is `σ`-finite, which is not necessary for the classical Vitali-Carathéodory theorem. Since this is satisfied in all applications, this is not a real problem. ## Sketch of proof Decomposing `f` as the difference of its positive and negative parts, it suffices to show that a positive function can be bounded from above by a lower semicontinuous function, and from below by an upper semicontinuous function, with integrals close to that of `f`. For the bound from above, write `f` as a series `∑' n, cₙ * indicator (sₙ)` of simple functions. Then, approximate `sₙ` by a larger open set `uₙ` with measure very close to that of `sₙ` (this is possible by regularity of the measure), and set `g = ∑' n, cₙ * indicator (uₙ)`. It is lower semicontinuous as a series of lower semicontinuous functions, and its integral is arbitrarily close to that of `f`. For the bound from below, use finitely many terms in the series, and approximate `sₙ` from inside by a closed set `Fₙ`. Then `∑ n < N, cₙ * indicator (Fₙ)` is bounded from above by `f`, it is upper semicontinuous as a finite sum of upper semicontinuous functions, and its integral is arbitrarily close to that of `f`. The main pain point in the implementation is that one needs to jump between the spaces `ℝ`, `ℝ≥0`, `ℝ≥0∞` and `EReal` (and be careful that addition is not well behaved on `EReal`), and between `lintegral` and `integral`. We first show the bound from above for simple functions and the nonnegative integral (this is the main nontrivial mathematical point), then deduce it for general nonnegative functions, first for the nonnegative integral and then for the Bochner integral. Then we follow the same steps for the lower bound. Finally, we glue them together to obtain the main statement `exists_lt_lower_semicontinuous_integral_lt`. ## Related results Are you looking for a result on approximation by continuous functions (not just semicontinuous)? See result `MeasureTheory.Lp.boundedContinuousFunction_dense`, in the file `Mathlib/MeasureTheory/Function/ContinuousMapDense.lean`. ## References [Rudin, *Real and Complex Analysis* (Theorem 2.24)][rudin2006real] -/ open scoped ENNReal NNReal open MeasureTheory MeasureTheory.Measure variable {α : Type*} [TopologicalSpace α] [MeasurableSpace α] [BorelSpace α] (μ : Measure α) [WeaklyRegular μ] namespace MeasureTheory local infixr:25 " →ₛ " => SimpleFunc /-! ### Lower semicontinuous upper bound for nonnegative functions -/ /-- Given a simple function `f` with values in `ℝ≥0`, there exists a lower semicontinuous function `g ≥ f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ theorem SimpleFunc.exists_le_lowerSemicontinuous_lintegral_ge (f : α →ₛ ℝ≥0) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0, (∀ x, f x ≤ g x) ∧ LowerSemicontinuous g ∧ (∫⁻ x, g x ∂μ) ≤ (∫⁻ x, f x ∂μ) + ε := by induction f using MeasureTheory.SimpleFunc.induction generalizing ε with | @const c s hs => let f := SimpleFunc.piecewise s hs (SimpleFunc.const α c) (SimpleFunc.const α 0) by_cases h : ∫⁻ x, f x ∂μ = ⊤ · refine ⟨fun _ => c, fun x => ?_, lowerSemicontinuous_const, by simp only [f, _root_.top_add, le_top, h]⟩ simp only [SimpleFunc.coe_const, SimpleFunc.const_zero, SimpleFunc.coe_zero, Set.piecewise_eq_indicator, SimpleFunc.coe_piecewise] exact Set.indicator_le_self _ _ _ by_cases hc : c = 0 · refine ⟨fun _ => 0, ?_, lowerSemicontinuous_const, ?_⟩ · classical simp only [hc, Set.indicator_zero', Pi.zero_apply, SimpleFunc.const_zero, imp_true_iff, SimpleFunc.coe_zero, Set.piecewise_eq_indicator, SimpleFunc.coe_piecewise, le_zero_iff] · simp only [lintegral_const, zero_mul, zero_le, ENNReal.coe_zero] have ne_top : μ s ≠ ⊤ := by classical simpa [f, hs, hc, lt_top_iff_ne_top, SimpleFunc.coe_const, Function.const_apply, lintegral_const, ENNReal.coe_indicator, Set.univ_inter, ENNReal.coe_ne_top, MeasurableSet.univ, ENNReal.mul_eq_top, SimpleFunc.const_zero, lintegral_indicator, ENNReal.coe_eq_zero, Ne, not_false_iff, SimpleFunc.coe_zero, Set.piecewise_eq_indicator, SimpleFunc.coe_piecewise, restrict_apply] using h have : μ s < μ s + ε / c := by have : (0 : ℝ≥0∞) < ε / c := ENNReal.div_pos_iff.2 ⟨ε0, ENNReal.coe_ne_top⟩ simpa using ENNReal.add_lt_add_left ne_top this obtain ⟨u, su, u_open, μu⟩ : ∃ (u : _), u ⊇ s ∧ IsOpen u ∧ μ u < μ s + ε / c := s.exists_isOpen_lt_of_lt _ this refine ⟨Set.indicator u fun _ => c, fun x => ?_, u_open.lowerSemicontinuous_indicator (zero_le _), ?_⟩ · simp only [SimpleFunc.coe_const, SimpleFunc.const_zero, SimpleFunc.coe_zero, Set.piecewise_eq_indicator, SimpleFunc.coe_piecewise] exact Set.indicator_le_indicator_of_subset su (fun x => zero_le _) _ · suffices (c : ℝ≥0∞) * μ u ≤ c * μ s + ε by classical simpa only [ENNReal.coe_indicator, u_open.measurableSet, lintegral_indicator, lintegral_const, MeasurableSet.univ, Measure.restrict_apply, Set.univ_inter, const_zero, coe_piecewise, coe_const, coe_zero, Set.piecewise_eq_indicator, Function.const_apply, hs] calc (c : ℝ≥0∞) * μ u ≤ c * (μ s + ε / c) := by grw [μu] _ = c * μ s + ε := by simp_rw [mul_add] rw [ENNReal.mul_div_cancel _ ENNReal.coe_ne_top] simpa using hc | @add f₁ f₂ _ h₁ h₂ => rcases h₁ (ENNReal.half_pos ε0).ne' with ⟨g₁, f₁_le_g₁, g₁cont, g₁int⟩ rcases h₂ (ENNReal.half_pos ε0).ne' with ⟨g₂, f₂_le_g₂, g₂cont, g₂int⟩ refine ⟨fun x => g₁ x + g₂ x, fun x => add_le_add (f₁_le_g₁ x) (f₂_le_g₂ x), g₁cont.add g₂cont, ?_⟩ simp only [SimpleFunc.coe_add, ENNReal.coe_add, Pi.add_apply] rw [lintegral_add_left f₁.measurable.coe_nnreal_ennreal, lintegral_add_left g₁cont.measurable.coe_nnreal_ennreal] convert add_le_add g₁int g₂int using 1 conv_lhs => rw [← ENNReal.add_halves ε] abel open SimpleFunc in /-- Given a measurable function `f` with values in `ℝ≥0`, there exists a lower semicontinuous function `g ≥ f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ theorem exists_le_lowerSemicontinuous_lintegral_ge (f : α → ℝ≥0∞) (hf : Measurable f) {ε : ℝ≥0∞} (εpos : ε ≠ 0) : ∃ g : α → ℝ≥0∞, (∀ x, f x ≤ g x) ∧ LowerSemicontinuous g ∧ (∫⁻ x, g x ∂μ) ≤ (∫⁻ x, f x ∂μ) + ε := by rcases ENNReal.exists_pos_sum_of_countable' εpos ℕ with ⟨δ, δpos, hδ⟩ have : ∀ n, ∃ g : α → ℝ≥0, (∀ x, eapproxDiff f n x ≤ g x) ∧ LowerSemicontinuous g ∧ (∫⁻ x, g x ∂μ) ≤ (∫⁻ x, eapproxDiff f n x ∂μ) + δ n := fun n => SimpleFunc.exists_le_lowerSemicontinuous_lintegral_ge μ (eapproxDiff f n) (δpos n).ne' choose g f_le_g gcont hg using this refine ⟨fun x => ∑' n, g n x, fun x => ?_, ?_, ?_⟩ · rw [← tsum_eapproxDiff f hf] exact ENNReal.tsum_le_tsum fun n => ENNReal.coe_le_coe.2 (f_le_g n x) · refine lowerSemicontinuous_tsum fun n => ?_ exact ENNReal.continuous_coe.comp_lowerSemicontinuous (gcont n) fun x y hxy => ENNReal.coe_le_coe.2 hxy · calc ∫⁻ x, ∑' n : ℕ, g n x ∂μ = ∑' n, ∫⁻ x, g n x ∂μ := by rw [lintegral_tsum fun n => (gcont n).measurable.coe_nnreal_ennreal.aemeasurable] _ ≤ ∑' n, ((∫⁻ x, eapproxDiff f n x ∂μ) + δ n) := ENNReal.tsum_le_tsum hg _ = ∑' n, ∫⁻ x, eapproxDiff f n x ∂μ + ∑' n, δ n := ENNReal.tsum_add _ ≤ (∫⁻ x : α, f x ∂μ) + ε := by refine add_le_add ?_ hδ.le rw [← lintegral_tsum] · simp_rw [tsum_eapproxDiff f hf, le_refl] · intro n; exact (SimpleFunc.measurable _).coe_nnreal_ennreal.aemeasurable /-- Given a measurable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ theorem exists_lt_lowerSemicontinuous_lintegral_ge [SigmaFinite μ] (f : α → ℝ≥0) (fmeas : Measurable f) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ LowerSemicontinuous g ∧ (∫⁻ x, g x ∂μ) ≤ (∫⁻ x, f x ∂μ) + ε := by have : ε / 2 ≠ 0 := (ENNReal.half_pos ε0).ne' rcases exists_pos_lintegral_lt_of_sigmaFinite μ this with ⟨w, wpos, wmeas, wint⟩ let f' x := ((f x + w x : ℝ≥0) : ℝ≥0∞) rcases exists_le_lowerSemicontinuous_lintegral_ge μ f' (fmeas.add wmeas).coe_nnreal_ennreal this with ⟨g, le_g, gcont, gint⟩ refine ⟨g, fun x => ?_, gcont, ?_⟩ · calc (f x : ℝ≥0∞) < f' x := by simpa only [← ENNReal.coe_lt_coe, add_zero] using add_lt_add_left (wpos x) (f x) _ ≤ g x := le_g x · calc (∫⁻ x : α, g x ∂μ) ≤ (∫⁻ x : α, f x + w x ∂μ) + ε / 2 := gint _ = ((∫⁻ x : α, f x ∂μ) + ∫⁻ x : α, w x ∂μ) + ε / 2 := by rw [lintegral_add_right _ wmeas.coe_nnreal_ennreal] _ ≤ (∫⁻ x : α, f x ∂μ) + ε / 2 + ε / 2 := by grw [wint] _ = (∫⁻ x : α, f x ∂μ) + ε := by rw [add_assoc, ENNReal.add_halves] /-- Given an almost everywhere measurable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ theorem exists_lt_lowerSemicontinuous_lintegral_ge_of_aemeasurable [SigmaFinite μ] (f : α → ℝ≥0) (fmeas : AEMeasurable f μ) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ LowerSemicontinuous g ∧ (∫⁻ x, g x ∂μ) ≤ (∫⁻ x, f x ∂μ) + ε := by have : ε / 2 ≠ 0 := (ENNReal.half_pos ε0).ne' rcases exists_lt_lowerSemicontinuous_lintegral_ge μ (fmeas.mk f) fmeas.measurable_mk this with ⟨g0, f_lt_g0, g0_cont, g0_int⟩ rcases exists_measurable_superset_of_null fmeas.ae_eq_mk with ⟨s, hs, smeas, μs⟩ rcases exists_le_lowerSemicontinuous_lintegral_ge μ (s.indicator fun _x => ∞) (measurable_const.indicator smeas) this with ⟨g1, le_g1, g1_cont, g1_int⟩ refine ⟨fun x => g0 x + g1 x, fun x => ?_, g0_cont.add g1_cont, ?_⟩ · by_cases h : x ∈ s · have := le_g1 x simp only [h, Set.indicator_of_mem, top_le_iff] at this simp [this] · have : f x = fmeas.mk f x := by rw [Set.compl_subset_comm] at hs; exact hs h rw [this] exact (f_lt_g0 x).trans_le le_self_add · calc ∫⁻ x, g0 x + g1 x ∂μ = (∫⁻ x, g0 x ∂μ) + ∫⁻ x, g1 x ∂μ := lintegral_add_left g0_cont.measurable _ _ ≤ (∫⁻ x, f x ∂μ) + ε / 2 + (0 + ε / 2) := by refine add_le_add ?_ ?_ · convert g0_int using 2 exact lintegral_congr_ae (fmeas.ae_eq_mk.fun_comp _) · convert g1_int simp only [smeas, μs, lintegral_const, Set.univ_inter, MeasurableSet.univ, lintegral_indicator, mul_zero, restrict_apply] _ = (∫⁻ x, f x ∂μ) + ε := by simp only [add_assoc, ENNReal.add_halves, zero_add] variable {μ} /-- Given an integrable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`. Formulation in terms of `integral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ theorem exists_lt_lowerSemicontinuous_integral_gt_nnreal [SigmaFinite μ] (f : α → ℝ≥0) (fint : Integrable (fun x => (f x : ℝ)) μ) {ε : ℝ} (εpos : 0 < ε) : ∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ LowerSemicontinuous g ∧ (∀ᵐ x ∂μ, g x < ⊤) ∧ Integrable (fun x => (g x).toReal) μ ∧ (∫ x, (g x).toReal ∂μ) < (∫ x, ↑(f x) ∂μ) + ε := by have fmeas : AEMeasurable f μ := by convert fint.aestronglyMeasurable.real_toNNReal.aemeasurable simp only [Real.toNNReal_coe] lift ε to ℝ≥0 using εpos.le obtain ⟨δ, δpos, hδε⟩ : ∃ δ : ℝ≥0, 0 < δ ∧ δ < ε := exists_between εpos have int_f_ne_top : (∫⁻ a : α, f a ∂μ) ≠ ∞ := (hasFiniteIntegral_iff_ofNNReal.1 fint.hasFiniteIntegral).ne rcases exists_lt_lowerSemicontinuous_lintegral_ge_of_aemeasurable μ f fmeas (ENNReal.coe_ne_zero.2 δpos.ne') with ⟨g, f_lt_g, gcont, gint⟩ have gint_ne : (∫⁻ x : α, g x ∂μ) ≠ ∞ := ne_top_of_le_ne_top (by simpa) gint have g_lt_top : ∀ᵐ x : α ∂μ, g x < ∞ := ae_lt_top gcont.measurable gint_ne have Ig : (∫⁻ a : α, ENNReal.ofReal (g a).toReal ∂μ) = ∫⁻ a : α, g a ∂μ := by apply lintegral_congr_ae filter_upwards [g_lt_top] with _ hx simp only [hx.ne, ENNReal.ofReal_toReal, Ne, not_false_iff] refine ⟨g, f_lt_g, gcont, g_lt_top, ?_, ?_⟩ · refine ⟨gcont.measurable.ennreal_toReal.aemeasurable.aestronglyMeasurable, ?_⟩ simp only [hasFiniteIntegral_iff_norm, Real.norm_eq_abs, abs_of_nonneg ENNReal.toReal_nonneg] convert gint_ne.lt_top using 1 · rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae] · calc ENNReal.toReal (∫⁻ a : α, ENNReal.ofReal (g a).toReal ∂μ) = ENNReal.toReal (∫⁻ a : α, g a ∂μ) := by congr 1 _ ≤ ENNReal.toReal ((∫⁻ a : α, f a ∂μ) + δ) := by apply ENNReal.toReal_mono _ gint simpa using int_f_ne_top _ = ENNReal.toReal (∫⁻ a : α, f a ∂μ) + δ := by rw [ENNReal.toReal_add int_f_ne_top ENNReal.coe_ne_top, ENNReal.coe_toReal] _ < ENNReal.toReal (∫⁻ a : α, f a ∂μ) + ε := by gcongr _ = (∫⁻ a : α, ENNReal.ofReal ↑(f a) ∂μ).toReal + ε := by simp · apply Filter.Eventually.of_forall fun x => _; simp · exact fmeas.coe_nnreal_real.aestronglyMeasurable · apply Filter.Eventually.of_forall fun x => _; simp · apply gcont.measurable.ennreal_toReal.aemeasurable.aestronglyMeasurable /-! ### Upper semicontinuous lower bound for nonnegative functions -/ /-- Given a simple function `f` with values in `ℝ≥0`, there exists an upper semicontinuous function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ theorem SimpleFunc.exists_upperSemicontinuous_le_lintegral_le (f : α →ₛ ℝ≥0) (int_f : (∫⁻ x, f x ∂μ) ≠ ∞) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ UpperSemicontinuous g ∧ (∫⁻ x, f x ∂μ) ≤ (∫⁻ x, g x ∂μ) + ε := by induction f using MeasureTheory.SimpleFunc.induction generalizing ε with | @const c s hs => by_cases hc : c = 0 · refine ⟨fun _ => 0, ?_, upperSemicontinuous_const, ?_⟩ · classical simp only [hc, Set.indicator_zero', Pi.zero_apply, SimpleFunc.const_zero, imp_true_iff, SimpleFunc.coe_zero, Set.piecewise_eq_indicator, SimpleFunc.coe_piecewise, le_zero_iff] · classical simp only [hc, Set.indicator_zero', lintegral_const, zero_mul, Pi.zero_apply, SimpleFunc.const_zero, zero_add, zero_le', SimpleFunc.coe_zero, Set.piecewise_eq_indicator, ENNReal.coe_zero, SimpleFunc.coe_piecewise] have μs_lt_top : μ s < ∞ := by classical simpa only [hs, hc, lt_top_iff_ne_top, true_and, SimpleFunc.coe_const, or_false, lintegral_const, ENNReal.coe_indicator, Set.univ_inter, ENNReal.coe_ne_top, Measure.restrict_apply MeasurableSet.univ, ENNReal.mul_eq_top, SimpleFunc.const_zero, Function.const_apply, lintegral_indicator, ENNReal.coe_eq_zero, Ne, not_false_iff, SimpleFunc.coe_zero, Set.piecewise_eq_indicator, SimpleFunc.coe_piecewise, false_and] using int_f have : (0 : ℝ≥0∞) < ε / c := ENNReal.div_pos_iff.2 ⟨ε0, ENNReal.coe_ne_top⟩ obtain ⟨F, Fs, F_closed, μF⟩ : ∃ (F : _), F ⊆ s ∧ IsClosed F ∧ μ s < μ F + ε / c := hs.exists_isClosed_lt_add μs_lt_top.ne this.ne' refine ⟨Set.indicator F fun _ => c, fun x => ?_, F_closed.upperSemicontinuous_indicator (zero_le _), ?_⟩ · simp only [SimpleFunc.coe_const, SimpleFunc.const_zero, SimpleFunc.coe_zero, Set.piecewise_eq_indicator, SimpleFunc.coe_piecewise] exact Set.indicator_le_indicator_of_subset Fs (fun x => zero_le _) _ · suffices (c : ℝ≥0∞) * μ s ≤ c * μ F + ε by classical simpa only [hs, F_closed.measurableSet, SimpleFunc.coe_const, Function.const_apply, lintegral_const, ENNReal.coe_indicator, Set.univ_inter, MeasurableSet.univ, SimpleFunc.const_zero, lintegral_indicator, SimpleFunc.coe_zero, Set.piecewise_eq_indicator, SimpleFunc.coe_piecewise, Measure.restrict_apply] calc (c : ℝ≥0∞) * μ s ≤ c * (μ F + ε / c) := by grw [μF] _ = c * μ F + ε := by simp_rw [mul_add] rw [ENNReal.mul_div_cancel _ ENNReal.coe_ne_top] simpa using hc | @add f₁ f₂ _ h₁ h₂ => have A : ((∫⁻ x : α, f₁ x ∂μ) + ∫⁻ x : α, f₂ x ∂μ) ≠ ⊤ := by rwa [← lintegral_add_left f₁.measurable.coe_nnreal_ennreal] rcases h₁ (ENNReal.add_ne_top.1 A).1 (ENNReal.half_pos ε0).ne' with ⟨g₁, f₁_le_g₁, g₁cont, g₁int⟩ rcases h₂ (ENNReal.add_ne_top.1 A).2 (ENNReal.half_pos ε0).ne' with ⟨g₂, f₂_le_g₂, g₂cont, g₂int⟩ refine ⟨fun x => g₁ x + g₂ x, fun x => add_le_add (f₁_le_g₁ x) (f₂_le_g₂ x), g₁cont.add g₂cont, ?_⟩ simp only [SimpleFunc.coe_add, ENNReal.coe_add, Pi.add_apply] rw [lintegral_add_left f₁.measurable.coe_nnreal_ennreal, lintegral_add_left g₁cont.measurable.coe_nnreal_ennreal] convert add_le_add g₁int g₂int using 1 conv_lhs => rw [← ENNReal.add_halves ε] abel /-- Given an integrable function `f` with values in `ℝ≥0`, there exists an upper semicontinuous function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ theorem exists_upperSemicontinuous_le_lintegral_le (f : α → ℝ≥0) (int_f : (∫⁻ x, f x ∂μ) ≠ ∞) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ UpperSemicontinuous g ∧ (∫⁻ x, f x ∂μ) ≤ (∫⁻ x, g x ∂μ) + ε := by obtain ⟨fs, fs_le_f, int_fs⟩ : ∃ fs : α →ₛ ℝ≥0, (∀ x, fs x ≤ f x) ∧ (∫⁻ x, f x ∂μ) ≤ (∫⁻ x, fs x ∂μ) + ε / 2 := by have := ENNReal.lt_add_right int_f (ENNReal.half_pos ε0).ne' conv_rhs at this => rw [lintegral_eq_nnreal (fun x => (f x : ℝ≥0∞)) μ] erw [ENNReal.biSup_add] at this <;> [skip; exact ⟨0, fun x => by simp⟩] simp only [lt_iSup_iff] at this rcases this with ⟨fs, fs_le_f, int_fs⟩ refine ⟨fs, fun x => by simpa only [ENNReal.coe_le_coe] using fs_le_f x, ?_⟩ convert int_fs.le rw [← SimpleFunc.lintegral_eq_lintegral] simp only [SimpleFunc.coe_map, Function.comp_apply] have int_fs_lt_top : (∫⁻ x, fs x ∂μ) ≠ ∞ := by refine ne_top_of_le_ne_top int_f (lintegral_mono fun x => ?_) simpa only [ENNReal.coe_le_coe] using fs_le_f x obtain ⟨g, g_le_fs, gcont, gint⟩ : ∃ g : α → ℝ≥0, (∀ x, g x ≤ fs x) ∧ UpperSemicontinuous g ∧ (∫⁻ x, fs x ∂μ) ≤ (∫⁻ x, g x ∂μ) + ε / 2 := fs.exists_upperSemicontinuous_le_lintegral_le int_fs_lt_top (ENNReal.half_pos ε0).ne' refine ⟨g, fun x => (g_le_fs x).trans (fs_le_f x), gcont, ?_⟩ calc (∫⁻ x, f x ∂μ) ≤ (∫⁻ x, fs x ∂μ) + ε / 2 := int_fs _ ≤ (∫⁻ x, g x ∂μ) + ε / 2 + ε / 2 := add_le_add gint le_rfl _ = (∫⁻ x, g x ∂μ) + ε := by rw [add_assoc, ENNReal.add_halves] /-- Given an integrable function `f` with values in `ℝ≥0`, there exists an upper semicontinuous function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of `integral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ theorem exists_upperSemicontinuous_le_integral_le (f : α → ℝ≥0) (fint : Integrable (fun x => (f x : ℝ)) μ) {ε : ℝ} (εpos : 0 < ε) : ∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ UpperSemicontinuous g ∧ Integrable (fun x => (g x : ℝ)) μ ∧ (∫ x, (f x : ℝ) ∂μ) - ε ≤ ∫ x, ↑(g x) ∂μ := by lift ε to ℝ≥0 using εpos.le rw [NNReal.coe_pos, ← ENNReal.coe_pos] at εpos have If : (∫⁻ x, f x ∂μ) < ∞ := hasFiniteIntegral_iff_ofNNReal.1 fint.hasFiniteIntegral rcases exists_upperSemicontinuous_le_lintegral_le f If.ne εpos.ne' with ⟨g, gf, gcont, gint⟩ have Ig : (∫⁻ x, g x ∂μ) < ∞ := by refine lt_of_le_of_lt (lintegral_mono fun x => ?_) If simpa using gf x refine ⟨g, gf, gcont, ?_, ?_⟩ · refine Integrable.mono fint gcont.measurable.coe_nnreal_real.aemeasurable.aestronglyMeasurable ?_ exact Filter.Eventually.of_forall fun x => by simp [gf x] · rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae] · rw [sub_le_iff_le_add] convert ENNReal.toReal_mono _ gint · simp · rw [ENNReal.toReal_add Ig.ne ENNReal.coe_ne_top]; simp · simpa using Ig.ne · apply Filter.Eventually.of_forall; simp · exact gcont.measurable.coe_nnreal_real.aemeasurable.aestronglyMeasurable · apply Filter.Eventually.of_forall; simp · exact fint.aestronglyMeasurable /-! ### Vitali-Carathéodory theorem -/ /-- **Vitali-Carathéodory Theorem**: given an integrable real function `f`, there exists an integrable function `g > f` which is lower semicontinuous, with integral arbitrarily close to that of `f`. This function has to be `EReal`-valued in general. -/ theorem exists_lt_lowerSemicontinuous_integral_lt [SigmaFinite μ] (f : α → ℝ) (hf : Integrable f μ) {ε : ℝ} (εpos : 0 < ε) : ∃ g : α → EReal, (∀ x, (f x : EReal) < g x) ∧ LowerSemicontinuous g ∧ Integrable (fun x => EReal.toReal (g x)) μ ∧ (∀ᵐ x ∂μ, g x < ⊤) ∧ (∫ x, EReal.toReal (g x) ∂μ) < (∫ x, f x ∂μ) + ε := by let δ : ℝ≥0 := ⟨ε / 2, (half_pos εpos).le⟩ have δpos : 0 < δ := half_pos εpos let fp : α → ℝ≥0 := fun x => Real.toNNReal (f x) have int_fp : Integrable (fun x => (fp x : ℝ)) μ := hf.real_toNNReal rcases exists_lt_lowerSemicontinuous_integral_gt_nnreal fp int_fp δpos with ⟨gp, fp_lt_gp, gpcont, gp_lt_top, gp_integrable, gpint⟩ let fm : α → ℝ≥0 := fun x => Real.toNNReal (-f x) have int_fm : Integrable (fun x => (fm x : ℝ)) μ := hf.neg.real_toNNReal rcases exists_upperSemicontinuous_le_integral_le fm int_fm δpos with ⟨gm, gm_le_fm, gmcont, gm_integrable, gmint⟩ let g : α → EReal := fun x => (gp x : EReal) - gm x have ae_g : ∀ᵐ x ∂μ, (g x).toReal = (gp x : EReal).toReal - (gm x : EReal).toReal := by filter_upwards [gp_lt_top] with _ hx rw [EReal.toReal_sub] <;> simp [hx.ne] refine ⟨g, ?lt, ?lsc, ?int, ?aelt, ?intlt⟩ case int => show Integrable (fun x => EReal.toReal (g x)) μ rw [integrable_congr ae_g] convert gp_integrable.sub gm_integrable simp case intlt => show (∫ x : α, (g x).toReal ∂μ) < (∫ x : α, f x ∂μ) + ε exact calc (∫ x : α, (g x).toReal ∂μ) = ∫ x : α, EReal.toReal (gp x) - EReal.toReal (gm x) ∂μ := integral_congr_ae ae_g _ = (∫ x : α, EReal.toReal (gp x) ∂μ) - ∫ x : α, ↑(gm x) ∂μ := by simp only [EReal.toReal_coe_ennreal, ENNReal.coe_toReal] exact integral_sub gp_integrable gm_integrable _ < (∫ x : α, ↑(fp x) ∂μ) + ↑δ - ∫ x : α, ↑(gm x) ∂μ := by apply sub_lt_sub_right convert gpint simp only [EReal.toReal_coe_ennreal] _ ≤ (∫ x : α, ↑(fp x) ∂μ) + ↑δ - ((∫ x : α, ↑(fm x) ∂μ) - δ) := sub_le_sub_left gmint _ _ = (∫ x : α, f x ∂μ) + 2 * δ := by simp_rw [integral_eq_integral_pos_part_sub_integral_neg_part hf]; ring _ = (∫ x : α, f x ∂μ) + ε := by congr 1; simp [field, δ] case aelt => show ∀ᵐ x : α ∂μ, g x < ⊤ filter_upwards [gp_lt_top] with ?_ hx simp only [g, sub_eq_add_neg, Ne, (EReal.add_lt_top _ _).ne, lt_top_iff_ne_top, lt_top_iff_ne_top.1 hx, EReal.coe_ennreal_eq_top_iff, not_false_iff, EReal.neg_eq_top_iff, EReal.coe_ennreal_ne_bot] case lt => show ∀ x, (f x : EReal) < g x intro x rw [EReal.coe_real_ereal_eq_coe_toNNReal_sub_coe_toNNReal (f x)] refine EReal.sub_lt_sub_of_lt_of_le ?_ ?_ ?_ ?_ · simp only [EReal.coe_ennreal_lt_coe_ennreal_iff]; exact fp_lt_gp x · simp only [ENNReal.coe_le_coe, EReal.coe_ennreal_le_coe_ennreal_iff] exact gm_le_fm x · simp only [EReal.coe_ennreal_ne_bot, Ne, not_false_iff] · simp only [EReal.coe_nnreal_ne_top, Ne, not_false_iff] case lsc => show LowerSemicontinuous g apply LowerSemicontinuous.add' · exact continuous_coe_ennreal_ereal.comp_lowerSemicontinuous gpcont fun x y hxy => EReal.coe_ennreal_le_coe_ennreal_iff.2 hxy · apply continuous_neg.comp_upperSemicontinuous_antitone _ fun x y hxy => EReal.neg_le_neg_iff.2 hxy dsimp apply continuous_coe_ennreal_ereal.comp_upperSemicontinuous _ fun x y hxy => EReal.coe_ennreal_le_coe_ennreal_iff.2 hxy exact ENNReal.continuous_coe.comp_upperSemicontinuous gmcont fun x y hxy => ENNReal.coe_le_coe.2 hxy · intro x exact EReal.continuousAt_add (by simp) (by simp) /-- **Vitali-Carathéodory Theorem**: given an integrable real function `f`, there exists an integrable function `g < f` which is upper semicontinuous, with integral arbitrarily close to that of `f`. This function has to be `EReal`-valued in general. -/ theorem exists_upperSemicontinuous_lt_integral_gt [SigmaFinite μ] (f : α → ℝ) (hf : Integrable f μ) {ε : ℝ} (εpos : 0 < ε) : ∃ g : α → EReal, (∀ x, (g x : EReal) < f x) ∧ UpperSemicontinuous g ∧ Integrable (fun x => EReal.toReal (g x)) μ ∧ (∀ᵐ x ∂μ, ⊥ < g x) ∧ (∫ x, f x ∂μ) < (∫ x, EReal.toReal (g x) ∂μ) + ε := by rcases exists_lt_lowerSemicontinuous_integral_lt (fun x => -f x) hf.neg εpos with ⟨g, g_lt_f, gcont, g_integrable, g_lt_top, gint⟩ refine ⟨fun x => -g x, ?_, ?_, ?_, ?_, ?_⟩ · exact fun x => EReal.neg_lt_comm.1 (by simpa only [EReal.coe_neg] using g_lt_f x) · exact continuous_neg.comp_lowerSemicontinuous_antitone gcont fun x y hxy => EReal.neg_le_neg_iff.2 hxy · convert g_integrable.neg simp · simpa [bot_lt_iff_ne_bot, lt_top_iff_ne_top] using g_lt_top · simp_rw [integral_neg, lt_neg_add_iff_add_lt] at gint rw [add_comm] at gint simpa [integral_neg] using gint end MeasureTheory
.lake/packages/mathlib/Mathlib/MeasureTheory/Integral/Bochner/L1.lean
import Mathlib.MeasureTheory.Integral.SetToL1 /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here for L1 functions by extending the integral on simple functions. See the file `Mathlib/MeasureTheory/Integral/Bochner/Basic.lean` for the integral of functions and corresponding API. ## Main definitions The Bochner integral is defined through the extension process described in the file `Mathlib/MeasureTheory/Integral/SetToL1.lean`, which follows these steps: 1. Define the integral of the indicator of a set. This is `weightedSMul μ s x = μ.real s * x`. `weightedSMul μ` is shown to be linear in the value `x` and `DominatedFinMeasAdditive` (defined in the file `Mathlib/MeasureTheory/Integral/SetToL1.lean`) with respect to the set `s`. 2. Define the integral on simple functions of the type `SimpleFunc α E` (notation : `α →ₛ E`) where `E` is a real normed space. (See `SimpleFunc.integral` for details.) 3. Transfer this definition to define the integral on `L1.simpleFunc α E` (notation : `α →₁ₛ[μ] E`), see `L1.simpleFunc.integral`. Show that this integral is a continuous linear map from `α →₁ₛ[μ] E` to `E`. 4. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ[μ] E` using `ContinuousLinearMap.extend` and the fact that the embedding of `α →₁ₛ[μ] E` into `α →₁[μ] E` is dense. ## Notation * `α →ₛ E` : simple functions (defined in `Mathlib/MeasureTheory/Function/SimpleFunc.lean`) * `α →₁[μ] E` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `Mathlib/MeasureTheory/Function/LpSpace/Basic.lean`) * `α →₁ₛ[μ] E` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions (defined in `Mathlib/MeasureTheory/Function/SimpleFuncDense`) We also define notations for integral on a set, which are described in the file `Mathlib/MeasureTheory/Integral/SetIntegral.lean`. Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if the font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ assert_not_exists Differentiable noncomputable section open Filter ENNReal Set open scoped NNReal ENNReal MeasureTheory namespace MeasureTheory variable {α E F 𝕜 : Type*} section WeightedSMul open ContinuousLinearMap variable [NormedAddCommGroup F] [NormedSpace ℝ F] {m : MeasurableSpace α} {μ : Measure α} /-- Given a set `s`, return the continuous linear map `fun x => μ.real s • x`. The extension of that set function through `setToL1` gives the Bochner integral of L1 functions. -/ def weightedSMul {_ : MeasurableSpace α} (μ : Measure α) (s : Set α) : F →L[ℝ] F := μ.real s • ContinuousLinearMap.id ℝ F theorem weightedSMul_apply {m : MeasurableSpace α} (μ : Measure α) (s : Set α) (x : F) : weightedSMul μ s x = μ.real s • x := by simp [weightedSMul] @[simp] theorem weightedSMul_zero_measure {m : MeasurableSpace α} : weightedSMul (0 : Measure α) = (0 : Set α → F →L[ℝ] F) := by ext1; simp [weightedSMul] @[simp] theorem weightedSMul_empty {m : MeasurableSpace α} (μ : Measure α) : weightedSMul μ ∅ = (0 : F →L[ℝ] F) := by ext1 x; rw [weightedSMul_apply]; simp theorem weightedSMul_add_measure {m : MeasurableSpace α} (μ ν : Measure α) {s : Set α} (hμs : μ s ≠ ∞) (hνs : ν s ≠ ∞) : (weightedSMul (μ + ν) s : F →L[ℝ] F) = weightedSMul μ s + weightedSMul ν s := by ext1 x push_cast simp_rw [Pi.add_apply, weightedSMul_apply] rw [measureReal_add_apply, add_smul] theorem weightedSMul_smul_measure {m : MeasurableSpace α} (μ : Measure α) (c : ℝ≥0∞) {s : Set α} : (weightedSMul (c • μ) s : F →L[ℝ] F) = c.toReal • weightedSMul μ s := by ext1 x simp [weightedSMul_apply, smul_smul] theorem weightedSMul_congr (s t : Set α) (hst : μ s = μ t) : (weightedSMul μ s : F →L[ℝ] F) = weightedSMul μ t := by ext1 x; simp_rw [weightedSMul_apply, measureReal_def]; congr 2 theorem weightedSMul_null {s : Set α} (h_zero : μ s = 0) : (weightedSMul μ s : F →L[ℝ] F) = 0 := by ext1 x; rw [weightedSMul_apply, measureReal_def, h_zero]; simp theorem weightedSMul_union' (s t : Set α) (ht : MeasurableSet t) (hs_finite : μ s ≠ ∞) (ht_finite : μ t ≠ ∞) (hdisj : Disjoint s t) : (weightedSMul μ (s ∪ t) : F →L[ℝ] F) = weightedSMul μ s + weightedSMul μ t := by ext1 x simp_rw [add_apply, weightedSMul_apply, measureReal_union hdisj ht,add_smul] @[nolint unusedArguments] theorem weightedSMul_union (s t : Set α) (_hs : MeasurableSet s) (ht : MeasurableSet t) (hs_finite : μ s ≠ ∞) (ht_finite : μ t ≠ ∞) (hdisj : Disjoint s t) : (weightedSMul μ (s ∪ t) : F →L[ℝ] F) = weightedSMul μ s + weightedSMul μ t := weightedSMul_union' s t ht hs_finite ht_finite hdisj theorem weightedSMul_smul [SMul 𝕜 F] [SMulCommClass ℝ 𝕜 F] (c : 𝕜) (s : Set α) (x : F) : weightedSMul μ s (c • x) = c • weightedSMul μ s x := by simp_rw [weightedSMul_apply, smul_comm] theorem norm_weightedSMul_le (s : Set α) : ‖(weightedSMul μ s : F →L[ℝ] F)‖ ≤ μ.real s := calc ‖(weightedSMul μ s : F →L[ℝ] F)‖ = ‖μ.real s‖ * ‖ContinuousLinearMap.id ℝ F‖ := norm_smul (μ.real s) (ContinuousLinearMap.id ℝ F) _ ≤ ‖μ.real s‖ := ((mul_le_mul_of_nonneg_left norm_id_le (norm_nonneg _)).trans (mul_one _).le) _ = abs μ.real s := Real.norm_eq_abs _ _ = μ.real s := abs_eq_self.mpr ENNReal.toReal_nonneg theorem dominatedFinMeasAdditive_weightedSMul {_ : MeasurableSpace α} (μ : Measure α) : DominatedFinMeasAdditive μ (weightedSMul μ : Set α → F →L[ℝ] F) 1 := ⟨weightedSMul_union, fun s _ _ => (norm_weightedSMul_le s).trans (one_mul _).symm.le⟩ theorem weightedSMul_nonneg [PartialOrder F] [IsOrderedModule ℝ F] (s : Set α) (x : F) (hx : 0 ≤ x) : 0 ≤ weightedSMul μ s x := by simp only [weightedSMul, coe_smul', _root_.id, coe_id', Pi.smul_apply] exact smul_nonneg toReal_nonneg hx end WeightedSMul local infixr:25 " →ₛ " => SimpleFunc namespace SimpleFunc section PosPart variable [LinearOrder E] [Zero E] [MeasurableSpace α] /-- Positive part of a simple function. -/ def posPart (f : α →ₛ E) : α →ₛ E := f.map fun b => max b 0 /-- Negative part of a simple function. -/ def negPart [Neg E] (f : α →ₛ E) : α →ₛ E := posPart (-f) theorem posPart_map_norm (f : α →ₛ ℝ) : (posPart f).map norm = posPart f := by ext; rw [map_apply, Real.norm_eq_abs, abs_of_nonneg]; exact le_max_right _ _ theorem negPart_map_norm (f : α →ₛ ℝ) : (negPart f).map norm = negPart f := by rw [negPart]; exact posPart_map_norm _ theorem posPart_sub_negPart (f : α →ₛ ℝ) : f.posPart - f.negPart = f := by simp only [posPart, negPart] ext a rw [coe_sub] exact max_zero_sub_eq_self (f a) end PosPart section Integral /-! ### The Bochner integral of simple functions Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group, and prove basic property of this integral. -/ open Finset variable [NormedAddCommGroup E] [NormedAddCommGroup F] [NormedSpace ℝ F] {m : MeasurableSpace α} {μ : Measure α} /-- Bochner integral of simple functions whose codomain is a real `NormedSpace`. This is equal to `∑ x ∈ f.range, μ.real (f ⁻¹' {x}) • x` (see `integral_eq`). -/ def integral {_ : MeasurableSpace α} (μ : Measure α) (f : α →ₛ F) : F := f.setToSimpleFunc (weightedSMul μ) theorem integral_def {_ : MeasurableSpace α} (μ : Measure α) (f : α →ₛ F) : f.integral μ = f.setToSimpleFunc (weightedSMul μ) := rfl theorem integral_eq {m : MeasurableSpace α} (μ : Measure α) (f : α →ₛ F) : f.integral μ = ∑ x ∈ f.range, μ.real (f ⁻¹' {x}) • x := by simp [integral, setToSimpleFunc, weightedSMul_apply] theorem integral_eq_sum_filter [DecidablePred fun x : F => x ≠ 0] {m : MeasurableSpace α} (f : α →ₛ F) (μ : Measure α) : f.integral μ = ∑ x ∈ {x ∈ f.range | x ≠ 0}, μ.real (f ⁻¹' {x}) • x := by simp_rw [integral_def, setToSimpleFunc_eq_sum_filter, weightedSMul_apply] /-- The Bochner integral is equal to a sum over any set that includes `f.range` (except `0`). -/ theorem integral_eq_sum_of_subset [DecidablePred fun x : F => x ≠ 0] {f : α →ₛ F} {s : Finset F} (hs : {x ∈ f.range | x ≠ 0} ⊆ s) : f.integral μ = ∑ x ∈ s, μ.real (f ⁻¹' {x}) • x := by rw [SimpleFunc.integral_eq_sum_filter, Finset.sum_subset hs] rintro x - hx; rw [Finset.mem_filter, not_and_or, Ne, Classical.not_not] at hx rcases hx.symm with (rfl | hx) · simp rw [SimpleFunc.mem_range] at hx rw [preimage_eq_empty] <;> simp [Set.disjoint_singleton_left, hx] @[simp] theorem integral_const {m : MeasurableSpace α} (μ : Measure α) (y : F) : (const α y).integral μ = μ.real univ • y := by classical calc (const α y).integral μ = ∑ z ∈ {y}, μ.real (const α y ⁻¹' {z}) • z := integral_eq_sum_of_subset <| (filter_subset _ _).trans (range_const_subset _ _) _ = μ.real univ • y := by simp [Set.preimage] @[simp] theorem integral_piecewise_zero {m : MeasurableSpace α} (f : α →ₛ F) (μ : Measure α) {s : Set α} (hs : MeasurableSet s) : (piecewise s hs f 0).integral μ = f.integral (μ.restrict s) := by classical refine (integral_eq_sum_of_subset ?_).trans ((sum_congr rfl fun y hy => ?_).trans (integral_eq_sum_filter _ _).symm) · intro y hy simp only [mem_filter, mem_range, coe_piecewise, coe_zero, piecewise_eq_indicator, mem_range_indicator] at * rcases hy with ⟨⟨rfl, -⟩ | ⟨x, -, rfl⟩, h₀⟩ exacts [(h₀ rfl).elim, ⟨Set.mem_range_self _, h₀⟩] · dsimp rw [Set.piecewise_eq_indicator, indicator_preimage_of_notMem, measureReal_restrict_apply (f.measurableSet_preimage _)] exact fun h₀ => (mem_filter.1 hy).2 (Eq.symm h₀) /-- Calculate the integral of `g ∘ f : α →ₛ F`, where `f` is an integrable function from `α` to `E` and `g` is a function from `E` to `F`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ theorem map_integral (f : α →ₛ E) (g : E → F) (hf : Integrable f μ) (hg : g 0 = 0) : (f.map g).integral μ = ∑ x ∈ f.range, (μ.real (f ⁻¹' {x})) • g x := map_setToSimpleFunc _ weightedSMul_union hf hg /-- `SimpleFunc.integral` and `SimpleFunc.lintegral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` is not a `NormedSpace`, we need some form of coercion. See `integral_eq_lintegral` for a simpler version. -/ theorem integral_eq_lintegral' {f : α →ₛ E} {g : E → ℝ≥0∞} (hf : Integrable f μ) (hg0 : g 0 = 0) (ht : ∀ b, g b ≠ ∞) : (f.map (ENNReal.toReal ∘ g)).integral μ = ENNReal.toReal (∫⁻ a, g (f a) ∂μ) := by have hf' : f.FinMeasSupp μ := integrable_iff_finMeasSupp.1 hf simp only [← map_apply g f, lintegral_eq_lintegral] rw [map_integral f _ hf, map_lintegral, ENNReal.toReal_sum] · refine Finset.sum_congr rfl fun b _ => ?_ rw [smul_eq_mul, toReal_mul, mul_comm, Function.comp_apply, measureReal_def] · rintro a - by_cases a0 : a = 0 · rw [a0, hg0, zero_mul]; exact WithTop.zero_ne_top · apply mul_ne_top (ht a) (hf'.meas_preimage_singleton_ne_zero a0).ne · simp [hg0] variable [NormedSpace ℝ E] theorem integral_congr {f g : α →ₛ E} (hf : Integrable f μ) (h : f =ᵐ[μ] g) : f.integral μ = g.integral μ := setToSimpleFunc_congr (weightedSMul μ) (fun _ _ => weightedSMul_null) weightedSMul_union hf h /-- `SimpleFunc.integral` and `SimpleFunc.lintegral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` is not a `NormedSpace`, we need some form of coercion. -/ theorem integral_eq_lintegral {f : α →ₛ ℝ} (hf : Integrable f μ) (h_pos : 0 ≤ᵐ[μ] f) : f.integral μ = ENNReal.toReal (∫⁻ a, ENNReal.ofReal (f a) ∂μ) := by have : f =ᵐ[μ] f.map (ENNReal.toReal ∘ ENNReal.ofReal) := h_pos.mono fun a h => (ENNReal.toReal_ofReal h).symm rw [← integral_eq_lintegral' hf] exacts [integral_congr hf this, ENNReal.ofReal_zero, fun b => ENNReal.ofReal_ne_top] theorem integral_add {f g : α →ₛ E} (hf : Integrable f μ) (hg : Integrable g μ) : integral μ (f + g) = integral μ f + integral μ g := setToSimpleFunc_add _ weightedSMul_union hf hg theorem integral_neg {f : α →ₛ E} (hf : Integrable f μ) : integral μ (-f) = -integral μ f := setToSimpleFunc_neg _ weightedSMul_union hf theorem integral_sub {f g : α →ₛ E} (hf : Integrable f μ) (hg : Integrable g μ) : integral μ (f - g) = integral μ f - integral μ g := setToSimpleFunc_sub _ weightedSMul_union hf hg theorem integral_smul [DistribSMul 𝕜 E] [SMulCommClass ℝ 𝕜 E] (c : 𝕜) {f : α →ₛ E} (hf : Integrable f μ) : integral μ (c • f) = c • integral μ f := setToSimpleFunc_smul _ weightedSMul_union weightedSMul_smul c hf theorem norm_setToSimpleFunc_le_integral_norm (T : Set α → E →L[ℝ] F) {C : ℝ} (hT_norm : ∀ s, MeasurableSet s → μ s < ∞ → ‖T s‖ ≤ C * μ.real s) {f : α →ₛ E} (hf : Integrable f μ) : ‖f.setToSimpleFunc T‖ ≤ C * (f.map norm).integral μ := calc ‖f.setToSimpleFunc T‖ ≤ C * ∑ x ∈ f.range, μ.real (f ⁻¹' {x}) * ‖x‖ := norm_setToSimpleFunc_le_sum_mul_norm_of_integrable T hT_norm f hf _ = C * (f.map norm).integral μ := by rw [map_integral f norm hf norm_zero]; simp_rw [smul_eq_mul] theorem norm_integral_le_integral_norm (f : α →ₛ E) (hf : Integrable f μ) : ‖f.integral μ‖ ≤ (f.map norm).integral μ := by refine (norm_setToSimpleFunc_le_integral_norm _ (fun s _ _ => ?_) hf).trans (one_mul _).le exact (norm_weightedSMul_le s).trans (one_mul _).symm.le theorem integral_add_measure {ν} (f : α →ₛ E) (hf : Integrable f (μ + ν)) : f.integral (μ + ν) = f.integral μ + f.integral ν := by simp_rw [integral_def] refine setToSimpleFunc_add_left' (weightedSMul μ) (weightedSMul ν) (weightedSMul (μ + ν)) (fun s _ hμνs => ?_) hf rw [lt_top_iff_ne_top, Measure.coe_add, Pi.add_apply, ENNReal.add_ne_top] at hμνs rw [weightedSMul_add_measure _ _ hμνs.1 hμνs.2] section Order variable [PartialOrder F] [IsOrderedAddMonoid F] [IsOrderedModule ℝ F] lemma integral_nonneg {f : α →ₛ F} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ f.integral μ := by rw [integral_eq] apply Finset.sum_nonneg rw [forall_mem_range] intro y by_cases hy : 0 ≤ f y · positivity · suffices μ (f ⁻¹' {f y}) = 0 by simp [this, measureReal_def] rw [← nonpos_iff_eq_zero] refine le_of_le_of_eq (measure_mono fun x hx ↦ ?_) (ae_iff.mp hf) simp only [Set.mem_preimage, mem_singleton_iff, mem_setOf_eq] at hx ⊢ exact hx ▸ hy lemma integral_mono {f g : α →ₛ F} (h : f ≤ᵐ[μ] g) (hf : Integrable f μ) (hg : Integrable g μ) : f.integral μ ≤ g.integral μ := by rw [← sub_nonneg, ← integral_sub hg hf] rw [← sub_nonneg_ae] at h exact integral_nonneg h lemma integral_mono_measure {ν} {f : α →ₛ F} (hf : 0 ≤ᵐ[ν] f) (hμν : μ ≤ ν) (hfν : Integrable f ν) : f.integral μ ≤ f.integral ν := by simp only [integral_eq] apply Finset.sum_le_sum simp only [forall_mem_range] intro x by_cases hx : 0 ≤ f x · obtain (hx | hx) := hx.eq_or_lt · simp [← hx] simp only [measureReal_def] gcongr · exact integrable_iff.mp hfν (f x) hx.ne' |>.ne · exact hμν _ · suffices ν (f ⁻¹' {f x}) = 0 by have A : μ (f ⁻¹' {f x}) = 0 := by simpa using (hμν _ |>.trans_eq this) simp [measureReal_def, A, this] rw [← nonpos_iff_eq_zero, ← ae_iff.mp hf] refine measure_mono fun y hy ↦ ?_ simp_all end Order end Integral end SimpleFunc namespace L1 open AEEqFun Lp.simpleFunc Lp variable [NormedAddCommGroup E] {m : MeasurableSpace α} {μ : Measure α} namespace SimpleFunc theorem norm_eq_integral (f : α →₁ₛ[μ] E) : ‖f‖ = ((toSimpleFunc f).map norm).integral μ := by rw [norm_eq_sum_mul f, (toSimpleFunc f).map_integral norm (SimpleFunc.integrable f) norm_zero] simp_rw [smul_eq_mul] section PosPart /-- Positive part of a simple function in L1 space. -/ nonrec def posPart (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := ⟨Lp.posPart (f : α →₁[μ] ℝ), by rcases f with ⟨f, s, hsf⟩ use s.posPart simp only [SimpleFunc.posPart, SimpleFunc.coe_map, Function.comp_def, coe_posPart, ← hsf, posPart_mk] ⟩ /-- Negative part of a simple function in L1 space. -/ def negPart (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := posPart (-f) @[norm_cast] theorem coe_posPart (f : α →₁ₛ[μ] ℝ) : (posPart f : α →₁[μ] ℝ) = Lp.posPart (f : α →₁[μ] ℝ) := rfl @[norm_cast] theorem coe_negPart (f : α →₁ₛ[μ] ℝ) : (negPart f : α →₁[μ] ℝ) = Lp.negPart (f : α →₁[μ] ℝ) := rfl end PosPart section SimpleFuncIntegral /-! ### The Bochner integral of `L1` Define the Bochner integral on `α →₁ₛ[μ] E` by extension from the simple functions `α →₁ₛ[μ] E`, and prove basic properties of this integral. -/ variable [NormedRing 𝕜] [Module 𝕜 E] [IsBoundedSMul 𝕜 E] [NormedSpace ℝ E] [SMulCommClass ℝ 𝕜 E] attribute [local instance] simpleFunc.isBoundedSMul simpleFunc.module simpleFunc.normedSpace /-- The Bochner integral over simple functions in L1 space. -/ def integral (f : α →₁ₛ[μ] E) : E := (toSimpleFunc f).integral μ theorem integral_eq_integral (f : α →₁ₛ[μ] E) : integral f = (toSimpleFunc f).integral μ := rfl nonrec theorem integral_eq_lintegral {f : α →₁ₛ[μ] ℝ} (h_pos : 0 ≤ᵐ[μ] toSimpleFunc f) : integral f = ENNReal.toReal (∫⁻ a, ENNReal.ofReal ((toSimpleFunc f) a) ∂μ) := by rw [integral, SimpleFunc.integral_eq_lintegral (SimpleFunc.integrable f) h_pos] theorem integral_eq_setToL1S (f : α →₁ₛ[μ] E) : integral f = setToL1S (weightedSMul μ) f := rfl nonrec theorem integral_congr {f g : α →₁ₛ[μ] E} (h : toSimpleFunc f =ᵐ[μ] toSimpleFunc g) : integral f = integral g := SimpleFunc.integral_congr (SimpleFunc.integrable f) h theorem integral_add (f g : α →₁ₛ[μ] E) : integral (f + g) = integral f + integral g := setToL1S_add _ (fun _ _ => weightedSMul_null) weightedSMul_union _ _ theorem integral_smul (c : 𝕜) (f : α →₁ₛ[μ] E) : integral (c • f) = c • integral f := setToL1S_smul _ (fun _ _ => weightedSMul_null) weightedSMul_union weightedSMul_smul c f theorem norm_integral_le_norm (f : α →₁ₛ[μ] E) : ‖integral f‖ ≤ ‖f‖ := by rw [integral, norm_eq_integral] exact (toSimpleFunc f).norm_integral_le_integral_norm (SimpleFunc.integrable f) variable (α E μ 𝕜) /-- The Bochner integral over simple functions in L1 space as a continuous linear map. -/ def integralCLM' : (α →₁ₛ[μ] E) →L[𝕜] E := LinearMap.mkContinuous ⟨⟨integral, integral_add⟩, integral_smul⟩ 1 fun f => le_trans (norm_integral_le_norm _) <| by rw [one_mul] /-- The Bochner integral over simple functions in L1 space as a continuous linear map over ℝ. -/ def integralCLM : (α →₁ₛ[μ] E) →L[ℝ] E := integralCLM' α E ℝ μ variable {α E μ 𝕜} local notation "Integral" => integralCLM α E μ open ContinuousLinearMap theorem norm_Integral_le_one : ‖Integral‖ ≤ 1 := LinearMap.mkContinuous_norm_le _ zero_le_one fun f ↦ by simpa [one_mul] using norm_integral_le_norm f section PosPart theorem posPart_toSimpleFunc (f : α →₁ₛ[μ] ℝ) : toSimpleFunc (posPart f) =ᵐ[μ] (toSimpleFunc f).posPart := by have eq : ∀ a, (toSimpleFunc f).posPart a = max ((toSimpleFunc f) a) 0 := fun a => rfl have ae_eq : ∀ᵐ a ∂μ, toSimpleFunc (posPart f) a = max ((toSimpleFunc f) a) 0 := by filter_upwards [toSimpleFunc_eq_toFun (posPart f), Lp.coeFn_posPart (f : α →₁[μ] ℝ), toSimpleFunc_eq_toFun f] with _ _ h₂ h₃ convert h₂ using 1 rw [h₃] refine ae_eq.mono fun a h => ?_ rw [h, eq] theorem negPart_toSimpleFunc (f : α →₁ₛ[μ] ℝ) : toSimpleFunc (negPart f) =ᵐ[μ] (toSimpleFunc f).negPart := by rw [SimpleFunc.negPart, MeasureTheory.SimpleFunc.negPart] filter_upwards [posPart_toSimpleFunc (-f), neg_toSimpleFunc f] intro a h₁ h₂ rw [h₁] change max _ _ = max _ _ rw [h₂] simp theorem integral_eq_norm_posPart_sub (f : α →₁ₛ[μ] ℝ) : integral f = ‖posPart f‖ - ‖negPart f‖ := by -- Convert things in `L¹` to their `SimpleFunc` counterpart have ae_eq₁ : (toSimpleFunc f).posPart =ᵐ[μ] (toSimpleFunc (posPart f)).map norm := by filter_upwards [posPart_toSimpleFunc f] with _ h rw [SimpleFunc.map_apply, h] conv_lhs => rw [← SimpleFunc.posPart_map_norm, SimpleFunc.map_apply] -- Convert things in `L¹` to their `SimpleFunc` counterpart have ae_eq₂ : (toSimpleFunc f).negPart =ᵐ[μ] (toSimpleFunc (negPart f)).map norm := by filter_upwards [negPart_toSimpleFunc f] with _ h rw [SimpleFunc.map_apply, h] conv_lhs => rw [← SimpleFunc.negPart_map_norm, SimpleFunc.map_apply] rw [integral, norm_eq_integral, norm_eq_integral, ← SimpleFunc.integral_sub] · change (toSimpleFunc f).integral μ = ((toSimpleFunc (posPart f)).map norm - (toSimpleFunc (negPart f)).map norm).integral μ apply MeasureTheory.SimpleFunc.integral_congr (SimpleFunc.integrable f) filter_upwards [ae_eq₁, ae_eq₂] with _ h₁ h₂ rw [SimpleFunc.sub_apply, ← h₁, ← h₂] exact DFunLike.congr_fun (toSimpleFunc f).posPart_sub_negPart.symm _ · exact (SimpleFunc.integrable f).pos_part.congr ae_eq₁ · exact (SimpleFunc.integrable f).neg_part.congr ae_eq₂ end PosPart end SimpleFuncIntegral end SimpleFunc open SimpleFunc local notation "Integral" => @integralCLM α E _ _ _ _ _ μ _ variable [NormedSpace ℝ E] [NormedRing 𝕜] [Module 𝕜 E] [IsBoundedSMul 𝕜 E] [SMulCommClass ℝ 𝕜 E] [CompleteSpace E] section IntegrationInL1 attribute [local instance] simpleFunc.isBoundedSMul simpleFunc.module open ContinuousLinearMap variable (𝕜) in /-- The Bochner integral in L1 space as a continuous linear map. -/ nonrec def integralCLM' : (α →₁[μ] E) →L[𝕜] E := (integralCLM' α E 𝕜 μ).extend (coeToLp α E 𝕜) (simpleFunc.denseRange one_ne_top) simpleFunc.isUniformInducing /-- The Bochner integral in L1 space as a continuous linear map over ℝ. -/ def integralCLM : (α →₁[μ] E) →L[ℝ] E := integralCLM' ℝ /-- The Bochner integral in L1 space -/ irreducible_def integral : (α →₁[μ] E) → E := integralCLM theorem integral_eq (f : α →₁[μ] E) : integral f = integralCLM f := by simp only [integral] theorem integral_eq_setToL1 (f : α →₁[μ] E) : integral f = setToL1 (dominatedFinMeasAdditive_weightedSMul μ) f := by simp only [integral]; rfl @[norm_cast] theorem SimpleFunc.integral_L1_eq_integral (f : α →₁ₛ[μ] E) : L1.integral (f : α →₁[μ] E) = SimpleFunc.integral f := by simp only [integral, L1.integral] exact setToL1_eq_setToL1SCLM (dominatedFinMeasAdditive_weightedSMul μ) f variable (α E) @[simp] theorem integral_zero : integral (0 : α →₁[μ] E) = 0 := by simp only [integral] exact map_zero integralCLM variable {α E} @[integral_simps] theorem integral_add (f g : α →₁[μ] E) : integral (f + g) = integral f + integral g := by simp only [integral] exact map_add integralCLM f g @[integral_simps] theorem integral_neg (f : α →₁[μ] E) : integral (-f) = -integral f := by simp only [integral] exact map_neg integralCLM f @[integral_simps] theorem integral_sub (f g : α →₁[μ] E) : integral (f - g) = integral f - integral g := by simp only [integral] exact map_sub integralCLM f g @[integral_simps] theorem integral_smul (c : 𝕜) (f : α →₁[μ] E) : integral (c • f) = c • integral f := by simp only [integral] change (integralCLM' 𝕜) (c • f) = c • (integralCLM' 𝕜) f exact map_smul (integralCLM' 𝕜) c f theorem norm_Integral_le_one : ‖integralCLM (α := α) (E := E) (μ := μ)‖ ≤ 1 := norm_setToL1_le (dominatedFinMeasAdditive_weightedSMul μ) zero_le_one theorem nnnorm_Integral_le_one : ‖integralCLM (α := α) (E := E) (μ := μ)‖₊ ≤ 1 := norm_Integral_le_one theorem norm_integral_le (f : α →₁[μ] E) : ‖integral f‖ ≤ ‖f‖ := calc ‖integral f‖ = ‖integralCLM f‖ := by simp only [integral] _ ≤ ‖integralCLM (α := α) (μ := μ)‖ * ‖f‖ := le_opNorm _ _ _ ≤ 1 * ‖f‖ := mul_le_mul_of_nonneg_right norm_Integral_le_one <| norm_nonneg _ _ = ‖f‖ := one_mul _ theorem nnnorm_integral_le (f : α →₁[μ] E) : ‖integral f‖₊ ≤ ‖f‖₊ := norm_integral_le f @[continuity] theorem continuous_integral : Continuous fun f : α →₁[μ] E => integral f := by simp only [integral] exact L1.integralCLM.continuous section PosPart theorem integral_eq_norm_posPart_sub (f : α →₁[μ] ℝ) : integral f = ‖Lp.posPart f‖ - ‖Lp.negPart f‖ := by -- Use `isClosed_property` and `isClosed_eq` refine @isClosed_property _ _ _ ((↑) : (α →₁ₛ[μ] ℝ) → α →₁[μ] ℝ) (fun f : α →₁[μ] ℝ => integral f = ‖Lp.posPart f‖ - ‖Lp.negPart f‖) (simpleFunc.denseRange one_ne_top) (isClosed_eq ?_ ?_) ?_ f · simp only [integral] exact cont _ · refine Continuous.sub (continuous_norm.comp Lp.continuous_posPart) (continuous_norm.comp Lp.continuous_negPart) -- Show that the property holds for all simple functions in the `L¹` space. · intro s norm_cast exact SimpleFunc.integral_eq_norm_posPart_sub _ end PosPart end IntegrationInL1 end L1 end MeasureTheory
.lake/packages/mathlib/Mathlib/Combinatorics/Colex.lean
import Mathlib.Algebra.Order.Ring.GeomSum import Mathlib.Data.Finset.Slice import Mathlib.Data.Nat.BitIndices import Mathlib.Order.SupClosed import Mathlib.Order.UpperLower.Closure /-! # Colexigraphic order We define the colex order for finite sets, and give a couple of important lemmas and properties relating to it. The colex ordering likes to avoid large values: If the biggest element of `t` is bigger than all elements of `s`, then `s < t`. In the special case of `ℕ`, it can be thought of as the "binary" ordering. That is, order `s` based on $∑_{i ∈ s} 2^i$. It's defined here on `Finset α` for any linear order `α`. In the context of the Kruskal-Katona theorem, we are interested in how colex behaves for sets of a fixed size. For example, for size 3, the colex order on ℕ starts `012, 013, 023, 123, 014, 024, 124, 034, 134, 234, ...` ## Main statements * Colex order properties - linearity, decidability and so on. * `Finset.Colex.forall_lt_mono`: if `s < t` in colex, and everything in `t` is `< a`, then everything in `s` is `< a`. This confirms the idea that an enumeration under colex will exhaust all sets using elements `< a` before allowing `a` to be included. * `Finset.toColex_image_le_toColex_image`: Strictly monotone functions preserve colex. * `Finset.geomSum_le_geomSum_iff_toColex_le_toColex`: Colex for α = ℕ is the same as binary. This also proves binary expansions are unique. ## See also Related files are: * `Data.List.Lex`: Lexicographic order on lists. * `Data.Pi.Lex`: Lexicographic order on `Πₗ i, α i`. * `Data.PSigma.Order`: Lexicographic order on `Σ' i, α i`. * `Data.Sigma.Order`: Lexicographic order on `Σ i, α i`. * `Data.Prod.Lex`: Lexicographic order on `α × β`. ## TODO * Generalise `Colex.initSeg` so that it applies to `ℕ`. ## References * https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf ## Tags colex, colexicographic, binary -/ open Function variable {α β : Type*} namespace Finset /-- Type synonym of `Finset α` equipped with the colexicographic order rather than the inclusion order. -/ @[deprecated Colex (since := "2025-08-28")] protected structure Colex (α) where /-- `toColex` is the "identity" function between `Finset α` and `Finset.Colex α`. -/ protected toColex :: /-- `ofColex` is the "identity" function between `Finset.Colex α` and `Finset α`. -/ protected (ofColex : Finset α) open Colex instance : Inhabited (Colex (Finset α)) := ⟨toColex ∅⟩ set_option linter.deprecated false in @[deprecated toColex_ofColex (since := "2025-08-28")] protected lemma toColex_ofColex (s : Finset.Colex α) : Finset.Colex.toColex (Finset.Colex.ofColex s) = s := rfl set_option linter.deprecated false in @[deprecated ofColex_toColex (since := "2025-08-28")] protected lemma ofColex_toColex (s : Finset α) : Finset.Colex.ofColex (Finset.Colex.toColex s) = s := rfl set_option linter.deprecated false in @[deprecated toColex_inj (since := "2025-08-28")] protected lemma toColex_inj {s t : Finset α} : Finset.Colex.toColex s = Finset.Colex.toColex t ↔ s = t := by simp set_option linter.deprecated false in @[deprecated ofColex_inj (since := "2025-08-28")] protected lemma ofColex_inj {s t : Finset.Colex α} : Finset.Colex.ofColex s = Finset.Colex.ofColex t ↔ s = t := by cases s; cases t; simp set_option linter.deprecated false in @[deprecated toColex_inj (since := "2025-08-28")] lemma toColex_ne_toColex {s t : Finset α} : Finset.Colex.toColex s ≠ Finset.Colex.toColex t ↔ s ≠ t := by simp set_option linter.deprecated false in @[deprecated ofColex_inj (since := "2025-08-28")] lemma ofColex_ne_ofColex {s t : Finset.Colex α} : Finset.Colex.ofColex s ≠ Finset.Colex.ofColex t ↔ s ≠ t := by simp [Finset.ofColex_inj] set_option linter.deprecated false in @[deprecated toColex_inj (since := "2025-08-28")] lemma toColex_injective : Injective (Finset.Colex.toColex : Finset α → Finset.Colex α) := fun _ _ ↦ Finset.toColex_inj.1 set_option linter.deprecated false in @[deprecated ofColex_inj (since := "2025-08-28")] lemma ofColex_injective : Injective (Finset.Colex.ofColex : Finset.Colex α → Finset α) := fun _ _ ↦ Finset.ofColex_inj.1 namespace Colex section PartialOrder variable [PartialOrder α] [PartialOrder β] {f : α → β} {𝒜 𝒜₁ 𝒜₂ : Finset (Finset α)} {s t u : Finset α} {a b : α} instance instLE : LE (Colex (Finset α)) where le s t := ∀ ⦃a⦄, a ∈ ofColex s → a ∉ ofColex t → ∃ b, b ∈ ofColex t ∧ b ∉ ofColex s ∧ a ≤ b -- TODO: This lemma is weirdly useful given how strange its statement is. -- Is there a nicer statement? Should this lemma be made public? private lemma trans_aux (hst : toColex s ≤ toColex t) (htu : toColex t ≤ toColex u) (has : a ∈ s) (hat : a ∉ t) : ∃ b, b ∈ u ∧ b ∉ s ∧ a ≤ b := by classical let s' : Finset α := {b ∈ s | b ∉ t ∧ a ≤ b} have ⟨b, hb, hbmax⟩ := s'.exists_maximal ⟨a, by simp [s', has, hat]⟩ simp only [s', mem_filter, and_imp] at hb hbmax have ⟨c, hct, hcs, hbc⟩ := hst hb.1 hb.2.1 by_cases hcu : c ∈ u · exact ⟨c, hcu, hcs, hb.2.2.trans hbc⟩ have ⟨d, hdu, hdt, hcd⟩ := htu hct hcu have had : a ≤ d := hb.2.2.trans <| hbc.trans hcd refine ⟨d, hdu, fun hds ↦ not_lt_iff_le_imp_ge.2 (hbmax hds hdt had) ?_, had⟩ exact hbc.trans_lt <| hcd.lt_of_ne <| ne_of_mem_of_not_mem hct hdt private lemma antisymm_aux (hst : toColex s ≤ toColex t) (hts : toColex t ≤ toColex s) : s ⊆ t := by intro a has by_contra! hat have ⟨_b, hb₁, hb₂, _⟩ := trans_aux hst hts has hat exact hb₂ hb₁ instance instPartialOrder : PartialOrder (Colex (Finset α)) where le_refl _ _ ha ha' := (ha' ha).elim le_antisymm _ _ hst hts := (antisymm_aux hst hts).antisymm (antisymm_aux hts hst) le_trans s t u hst htu a has hau := by by_cases hat : a ∈ ofColex t · have ⟨b, hbu, hbt, hab⟩ := htu hat hau by_cases hbs : b ∈ ofColex s · have ⟨c, hcu, hcs, hbc⟩ := trans_aux hst htu hbs hbt exact ⟨c, hcu, hcs, hab.trans hbc⟩ · exact ⟨b, hbu, hbs, hab⟩ · exact trans_aux hst htu has hat lemma le_def {s t : Colex (Finset α)} : s ≤ t ↔ ∀ ⦃a⦄, a ∈ ofColex s → a ∉ ofColex t → ∃ b, b ∈ ofColex t ∧ b ∉ ofColex s ∧ a ≤ b := Iff.rfl lemma toColex_le_toColex : toColex s ≤ toColex t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t → ∃ b, b ∈ t ∧ b ∉ s ∧ a ≤ b := Iff.rfl lemma toColex_lt_toColex : toColex s < toColex t ↔ s ≠ t ∧ ∀ ⦃a⦄, a ∈ s → a ∉ t → ∃ b, b ∈ t ∧ b ∉ s ∧ a ≤ b := by simp [lt_iff_le_and_ne, toColex_le_toColex, and_comm] /-- If `s ⊆ t`, then `s ≤ t` in the colex order. Note the converse does not hold, as inclusion does not form a linear order. -/ lemma toColex_mono : Monotone (@toColex (Finset α)) := fun _s _t hst _a has hat ↦ (hat <| hst has).elim /-- If `s ⊂ t`, then `s < t` in the colex order. Note the converse does not hold, as inclusion does not form a linear order. -/ lemma toColex_strictMono : StrictMono (@toColex (Finset α)) := toColex_mono.strictMono_of_injective toColex.injective /-- If `s ⊆ t`, then `s ≤ t` in the colex order. Note the converse does not hold, as inclusion does not form a linear order. -/ lemma toColex_le_toColex_of_subset (h : s ⊆ t) : toColex s ≤ toColex t := toColex_mono h /-- If `s ⊂ t`, then `s < t` in the colex order. Note the converse does not hold, as inclusion does not form a linear order. -/ lemma toColex_lt_toColex_of_ssubset (h : s ⊂ t) : toColex s < toColex t := toColex_strictMono h instance instOrderBot : OrderBot (Colex (Finset α)) where bot := toColex ∅ bot_le s a ha := by cases ha @[simp] lemma toColex_empty : toColex (∅ : Finset α) = ⊥ := rfl @[simp] lemma ofColex_bot : ofColex (⊥ : Colex (Finset α)) = ∅ := rfl /-- If `s ≤ t` in colex, and all elements in `t` are small, then all elements in `s` are small. -/ lemma forall_le_mono (hst : toColex s ≤ toColex t) (ht : ∀ b ∈ t, b ≤ a) : ∀ b ∈ s, b ≤ a := by rintro b hb by_cases b ∈ t · exact ht _ ‹_› · obtain ⟨c, hct, -, hbc⟩ := hst hb ‹_› exact hbc.trans <| ht _ hct /-- If `s ≤ t` in colex, and all elements in `t` are small, then all elements in `s` are small. -/ lemma forall_lt_mono (hst : toColex s ≤ toColex t) (ht : ∀ b ∈ t, b < a) : ∀ b ∈ s, b < a := by rintro b hb by_cases b ∈ t · exact ht _ ‹_› · obtain ⟨c, hct, -, hbc⟩ := hst hb ‹_› exact hbc.trans_lt <| ht _ hct /-- `s ≤ {a}` in colex iff all elements of `s` are strictly less than `a`, except possibly `a` in which case `s = {a}`. -/ lemma toColex_le_singleton : toColex s ≤ toColex {a} ↔ ∀ b ∈ s, b ≤ a ∧ (a ∈ s → b = a) := by simp only [toColex_le_toColex, mem_singleton, exists_eq_left] refine forall₂_congr fun b _ ↦ ?_; obtain rfl | hba := eq_or_ne b a <;> aesop /-- `s < {a}` in colex iff all elements of `s` are strictly less than `a`. -/ lemma toColex_lt_singleton : toColex s < toColex {a} ↔ ∀ b ∈ s, b < a := by rw [lt_iff_le_and_ne, toColex_le_singleton, ne_eq, toColex_inj] refine ⟨fun h b hb ↦ (h.1 _ hb).1.lt_of_ne ?_, fun h ↦ ⟨fun b hb ↦ ⟨(h _ hb).le, fun ha ↦ (lt_irrefl _ <| h _ ha).elim⟩, ?_⟩⟩ <;> rintro rfl · refine h.2 <| eq_singleton_iff_unique_mem.2 ⟨hb, fun c hc ↦ (h.1 _ hc).2 hb⟩ · simp at h /-- `{a} ≤ s` in colex iff `s` contains an element greater than or equal to `a`. -/ lemma singleton_le_toColex : (toColex {a} : Colex (Finset α)) ≤ toColex s ↔ ∃ x ∈ s, a ≤ x := by simp [toColex_le_toColex]; by_cases a ∈ s <;> aesop /-- Colex is an extension of the base order. -/ lemma singleton_le_singleton : (toColex ({a} : Finset α)) ≤ toColex {b} ↔ a ≤ b := by simp [toColex_le_singleton, eq_comm] /-- Colex is an extension of the base order. -/ lemma singleton_lt_singleton : (toColex ({a} : Finset α)) < toColex {b} ↔ a < b := by simp [toColex_lt_singleton] lemma le_iff_sdiff_subset_lowerClosure {s t : Colex (Finset α)} : s ≤ t ↔ (↑(ofColex s) : Set α) \ ↑(ofColex t) ⊆ lowerClosure (↑(ofColex t) \ ↑(ofColex s) : Set α) := by simp [le_def, Set.subset_def, and_assoc] section DecidableEq variable [DecidableEq α] instance instDecidableLE [DecidableLE α] : DecidableLE (Colex (Finset α)) := fun s t ↦ decidable_of_iff' (∀ ⦃a⦄, a ∈ ofColex s → a ∉ ofColex t → ∃ b, b ∈ ofColex t ∧ b ∉ ofColex s ∧ a ≤ b) Iff.rfl instance instDecidableLT [DecidableLE α] : DecidableLT (Colex (Finset α)) := decidableLTOfDecidableLE /-- The colexigraphic order is insensitive to removing the same elements from both sets. -/ lemma toColex_sdiff_le_toColex_sdiff (hus : u ⊆ s) (hut : u ⊆ t) : toColex (s \ u) ≤ toColex (t \ u) ↔ toColex s ≤ toColex t := by simp_rw [toColex_le_toColex, ← and_imp, ← and_assoc, ← mem_sdiff, sdiff_sdiff_sdiff_cancel_right (show u ≤ s from hus), sdiff_sdiff_sdiff_cancel_right (show u ≤ t from hut)] /-- The colexigraphic order is insensitive to removing the same elements from both sets. -/ lemma toColex_sdiff_lt_toColex_sdiff (hus : u ⊆ s) (hut : u ⊆ t) : toColex (s \ u) < toColex (t \ u) ↔ toColex s < toColex t := lt_iff_lt_of_le_iff_le' (toColex_sdiff_le_toColex_sdiff hut hus) <| toColex_sdiff_le_toColex_sdiff hus hut @[simp] lemma toColex_sdiff_le_toColex_sdiff' : toColex (s \ t) ≤ toColex (t \ s) ↔ toColex s ≤ toColex t := by simpa using toColex_sdiff_le_toColex_sdiff (inter_subset_left (s₁ := s)) inter_subset_right @[simp] lemma toColex_sdiff_lt_toColex_sdiff' : toColex (s \ t) < toColex (t \ s) ↔ toColex s < toColex t := by simpa using toColex_sdiff_lt_toColex_sdiff (inter_subset_left (s₁ := s)) inter_subset_right end DecidableEq @[simp] lemma cons_le_cons (ha hb) : toColex (s.cons a ha) ≤ toColex (s.cons b hb) ↔ a ≤ b := by obtain rfl | hab := eq_or_ne a b · simp classical rw [← toColex_sdiff_le_toColex_sdiff', cons_sdiff_cons hab, cons_sdiff_cons hab.symm, singleton_le_singleton] @[simp] lemma cons_lt_cons (ha hb) : toColex (s.cons a ha) < toColex (s.cons b hb) ↔ a < b := lt_iff_lt_of_le_iff_le' (cons_le_cons _ _) (cons_le_cons _ _) variable [DecidableEq α] lemma insert_le_insert (ha : a ∉ s) (hb : b ∉ s) : toColex (insert a s) ≤ toColex (insert b s) ↔ a ≤ b := by rw [← cons_eq_insert _ _ ha, ← cons_eq_insert _ _ hb, cons_le_cons] lemma insert_lt_insert (ha : a ∉ s) (hb : b ∉ s) : toColex (insert a s) < toColex (insert b s) ↔ a < b := by rw [← cons_eq_insert _ _ ha, ← cons_eq_insert _ _ hb, cons_lt_cons] lemma erase_le_erase (ha : a ∈ s) (hb : b ∈ s) : toColex (s.erase a) ≤ toColex (s.erase b) ↔ b ≤ a := by obtain rfl | hab := eq_or_ne a b · simp classical rw [← toColex_sdiff_le_toColex_sdiff', erase_sdiff_erase hab hb, erase_sdiff_erase hab.symm ha, singleton_le_singleton] lemma erase_lt_erase (ha : a ∈ s) (hb : b ∈ s) : toColex (s.erase a) < toColex (s.erase b) ↔ b < a := lt_iff_lt_of_le_iff_le' (erase_le_erase hb ha) (erase_le_erase ha hb) end PartialOrder variable [LinearOrder α] [LinearOrder β] {f : α → β} {𝒜 𝒜₁ 𝒜₂ : Finset (Finset α)} {s t u : Finset α} {a b : α} {r : ℕ} instance instLinearOrder : LinearOrder (Colex (Finset α)) where le_total s t := by classical obtain rfl | hts := eq_or_ne t s · simp have ⟨a, ha, hamax⟩ := exists_max_image _ id (symmDiff_nonempty.2 <| ofColex.injective.ne_iff.2 hts) simp_rw [mem_symmDiff] at ha hamax exact ha.imp (fun ha b hbs hbt ↦ ⟨a, ha.1, ha.2, hamax _ <| Or.inr ⟨hbs, hbt⟩⟩) (fun ha b hbt hbs ↦ ⟨a, ha.1, ha.2, hamax _ <| Or.inl ⟨hbt, hbs⟩⟩) toDecidableLE := instDecidableLE toDecidableLT := instDecidableLT open scoped symmDiff private lemma max_mem_aux {s t : Colex (Finset α)} (hst : s ≠ t) : (ofColex s ∆ ofColex t).Nonempty := by simpa lemma toColex_lt_toColex_iff_exists_forall_lt : toColex s < toColex t ↔ ∃ a ∈ t, a ∉ s ∧ ∀ b ∈ s, b ∉ t → b < a := by rw [← not_le, toColex_le_toColex, not_forall] simp only [not_forall, not_exists, not_and, not_le, exists_prop] lemma lt_iff_exists_forall_lt {s t : Colex (Finset α)} : s < t ↔ ∃ a ∈ ofColex t, a ∉ ofColex s ∧ ∀ b ∈ ofColex s, b ∉ ofColex t → b < a := toColex_lt_toColex_iff_exists_forall_lt lemma toColex_le_toColex_iff_max'_mem : toColex s ≤ toColex t ↔ ∀ hst : s ≠ t, (s ∆ t).max' (symmDiff_nonempty.2 hst) ∈ t := by refine ⟨fun h hst ↦ ?_, fun h a has hat ↦ ?_⟩ · set m := (s ∆ t).max' (symmDiff_nonempty.2 hst) by_contra hmt have hms : m ∈ s := by simpa [m, mem_symmDiff, hmt] using max'_mem _ <| symmDiff_nonempty.2 hst have ⟨b, hbt, hbs, hmb⟩ := h hms hmt exact lt_irrefl _ <| (max'_lt_iff _ _).1 (hmb.lt_of_ne <| ne_of_mem_of_not_mem hms hbs) _ <| mem_symmDiff.2 <| Or.inr ⟨hbt, hbs⟩ · have hst : s ≠ t := ne_of_mem_of_not_mem' has hat refine ⟨_, h hst, ?_, le_max' _ _ <| mem_symmDiff.2 <| Or.inl ⟨has, hat⟩⟩ simpa [mem_symmDiff, h hst] using max'_mem _ <| symmDiff_nonempty.2 hst lemma le_iff_max'_mem {s t : Colex (Finset α)} : s ≤ t ↔ ∀ h : s ≠ t, (ofColex s ∆ ofColex t).max' (max_mem_aux h) ∈ ofColex t := toColex_le_toColex_iff_max'_mem lemma toColex_lt_toColex_iff_max'_mem : toColex s < toColex t ↔ ∃ hst : s ≠ t, (s ∆ t).max' (symmDiff_nonempty.2 hst) ∈ t := by rw [lt_iff_le_and_ne, toColex_le_toColex_iff_max'_mem]; aesop lemma lt_iff_max'_mem {s t : Colex (Finset α)} : s < t ↔ ∃ h : s ≠ t, (ofColex s ∆ ofColex t).max' (max_mem_aux h) ∈ ofColex t := by rw [lt_iff_le_and_ne, le_iff_max'_mem]; aesop lemma lt_iff_exists_filter_lt : toColex s < toColex t ↔ ∃ w ∈ t \ s, {a ∈ s | w < a} = {a ∈ t | w < a} := by simp only [lt_iff_exists_forall_lt, mem_sdiff, filter_inj, and_assoc] refine ⟨fun h ↦ ?_, ?_⟩ · let u := {w ∈ t \ s | ∀ a ∈ s, a ∉ t → a < w} have mem_u {w : α} : w ∈ u ↔ w ∈ t ∧ w ∉ s ∧ ∀ a ∈ s, a ∉ t → a < w := by simp [u, and_assoc] have hu : u.Nonempty := h.imp fun _ ↦ mem_u.2 let m := max' _ hu have ⟨hmt, hms, hm⟩ : m ∈ t ∧ m ∉ s ∧ ∀ a ∈ s, a ∉ t → a < m := mem_u.1 <| max'_mem _ _ refine ⟨m, hmt, hms, fun a hma ↦ ⟨fun has ↦ not_imp_comm.1 (hm _ has) hma.asymm, fun hat ↦ ?_⟩⟩ by_contra has have hau : a ∈ u := mem_u.2 ⟨hat, has, fun b hbs hbt ↦ (hm _ hbs hbt).trans hma⟩ exact hma.not_ge <| le_max' _ _ hau · rintro ⟨w, hwt, hws, hw⟩ refine ⟨w, hwt, hws, fun a has hat ↦ ?_⟩ by_contra! hwa exact hat <| (hw <| hwa.lt_of_ne <| ne_of_mem_of_not_mem hwt hat).1 has /-- If `s ≤ t` in colex and `#s ≤ #t`, then `s \ {a} ≤ t \ {min t}` for any `a ∈ s`. -/ lemma erase_le_erase_min' (hst : toColex s ≤ toColex t) (hcard : #s ≤ #t) (ha : a ∈ s) : toColex (s.erase a) ≤ toColex (t.erase <| min' t <| card_pos.1 <| (card_pos.2 ⟨a, ha⟩).trans_le hcard) := by generalize_proofs ht set m := min' t ht -- Case on whether `s = t` obtain rfl | h' := eq_or_ne s t -- If `s = t`, then `s \ {a} ≤ s \ {m}` because `m ≤ a` · exact (erase_le_erase ha <| min'_mem _ _).2 <| min'_le _ _ <| ha -- If `s ≠ t`, call `w` the colex witness. Case on whether `w < a` or `a < w` replace hst := hst.lt_of_ne <| toColex_inj.not.2 h' simp only [lt_iff_exists_filter_lt, mem_sdiff, filter_inj, and_assoc] at hst obtain ⟨w, hwt, hws, hw⟩ := hst obtain hwa | haw := (ne_of_mem_of_not_mem ha hws).symm.lt_or_gt -- If `w < a`, then `a` is the colex witness for `s \ {a} < t \ {m}` · have hma : m < a := (min'_le _ _ hwt).trans_lt hwa refine (lt_iff_exists_forall_lt.2 ⟨a, mem_erase.2 ⟨hma.ne', (hw hwa).1 ha⟩, notMem_erase _ _, fun b hbs hbt ↦ ?_⟩).le change b ∉ t.erase m at hbt rw [mem_erase, not_and_or, not_ne_iff] at hbt obtain rfl | hbt := hbt · assumption · by_contra! hab exact hbt <| (hw <| hwa.trans_le hab).1 <| mem_of_mem_erase hbs -- If `a < w`, case on whether `m < w` or `m = w` obtain rfl | hmw : m = w ∨ m < w := (min'_le _ _ hwt).eq_or_lt -- If `m = w`, then `s \ {a} = t \ {m}` · have : erase t m ⊆ erase s a := by rintro b hb rw [mem_erase] at hb ⊢ exact ⟨(haw.trans_le <| min'_le _ _ hb.2).ne', (hw <| hb.1.lt_of_le' <| min'_le _ _ hb.2).2 hb.2⟩ rw [eq_of_subset_of_card_le this] rw [card_erase_of_mem ha, card_erase_of_mem (min'_mem _ _)] exact tsub_le_tsub_right hcard _ -- If `m < w`, then `w` works as the colex witness for `s \ {a} < t \ {m}` · refine (lt_iff_exists_forall_lt.2 ⟨w, mem_erase.2 ⟨hmw.ne', hwt⟩, mt mem_of_mem_erase hws, fun b hbs hbt ↦ ?_⟩).le change b ∉ t.erase m at hbt rw [mem_erase, not_and_or, not_ne_iff] at hbt obtain rfl | hbt := hbt · assumption · by_contra! hwb exact hbt <| (hw <| hwb.lt_of_ne <| ne_of_mem_of_not_mem hwt hbt).1 <| mem_of_mem_erase hbs /-- Strictly monotone functions preserve the colex ordering. -/ lemma toColex_image_le_toColex_image (hf : StrictMono f) : toColex (s.image f) ≤ toColex (t.image f) ↔ toColex s ≤ toColex t := by simp [toColex_le_toColex, hf.le_iff_le, hf.injective.eq_iff] /-- Strictly monotone functions preserve the colex ordering. -/ lemma toColex_image_lt_toColex_image (hf : StrictMono f) : toColex (s.image f) < toColex (t.image f) ↔ toColex s < toColex t := lt_iff_lt_of_le_iff_le <| toColex_image_le_toColex_image hf lemma toColex_image_ofColex_strictMono (hf : StrictMono f) : StrictMono fun s ↦ toColex <| image f <| ofColex s := fun _s _t ↦ (toColex_image_lt_toColex_image hf).2 section Fintype variable [Fintype α] instance instBoundedOrder : BoundedOrder (Colex (Finset α)) where top := toColex univ le_top _x := toColex_le_toColex_of_subset <| subset_univ _ @[simp] lemma toColex_univ : toColex (univ : Finset α) = ⊤ := rfl @[simp] lemma ofColex_top : ofColex (⊤ : Colex (Finset α)) = univ := rfl end Fintype /-! ### Initial segments -/ /-- `𝒜` is an initial segment of the colexigraphic order on sets of `r`, and that if `t` is below `s` in colex where `t` has size `r` and `s` is in `𝒜`, then `t` is also in `𝒜`. In effect, `𝒜` is downwards closed with respect to colex among sets of size `r`. -/ def IsInitSeg (𝒜 : Finset (Finset α)) (r : ℕ) : Prop := (𝒜 : Set (Finset α)).Sized r ∧ ∀ ⦃s t : Finset α⦄, s ∈ 𝒜 → toColex t < toColex s ∧ #t = r → t ∈ 𝒜 @[simp] lemma isInitSeg_empty : IsInitSeg (∅ : Finset (Finset α)) r := by simp [IsInitSeg] /-- Initial segments are nested in some way. In particular, if they're the same size they're equal. -/ lemma IsInitSeg.total (h₁ : IsInitSeg 𝒜₁ r) (h₂ : IsInitSeg 𝒜₂ r) : 𝒜₁ ⊆ 𝒜₂ ∨ 𝒜₂ ⊆ 𝒜₁ := by classical simp_rw [← sdiff_eq_empty_iff_subset, ← not_nonempty_iff_eq_empty] by_contra! h have ⟨⟨s, hs⟩, t, ht⟩ := h rw [mem_sdiff] at hs ht obtain hst | hst | hts := trichotomous_of (α := Colex (Finset α)) (· < ·) (toColex s) (toColex t) · exact hs.2 <| h₂.2 ht.1 ⟨hst, h₁.1 hs.1⟩ · simp only [toColex_inj] at hst exact ht.2 <| hst ▸ hs.1 · exact ht.2 <| h₁.2 hs.1 ⟨hts, h₂.1 ht.1⟩ variable [Fintype α] /-- The initial segment of the colexicographic order on sets with `#s` elements and ending at `s`. -/ def initSeg (s : Finset α) : Finset (Finset α) := {t | #s = #t ∧ toColex t ≤ toColex s} @[simp] lemma mem_initSeg : t ∈ initSeg s ↔ #s = #t ∧ toColex t ≤ toColex s := by simp [initSeg] lemma mem_initSeg_self : s ∈ initSeg s := by simp @[simp] lemma initSeg_nonempty : (initSeg s).Nonempty := ⟨s, mem_initSeg_self⟩ lemma isInitSeg_initSeg : IsInitSeg (initSeg s) #s := by refine ⟨fun t ht => (mem_initSeg.1 ht).1.symm, fun t₁ t₂ ht₁ ht₂ ↦ mem_initSeg.2 ⟨ht₂.2.symm, ?_⟩⟩ rw [mem_initSeg] at ht₁ exact ht₂.1.le.trans ht₁.2 lemma IsInitSeg.exists_initSeg (h𝒜 : IsInitSeg 𝒜 r) (h𝒜₀ : 𝒜.Nonempty) : ∃ s : Finset α, #s = r ∧ 𝒜 = initSeg s := by have hs := sup'_mem (ofColex ⁻¹' 𝒜) (LinearOrder.supClosed _) 𝒜 h𝒜₀ toColex (fun a ha ↦ by simpa using ha) refine ⟨_, h𝒜.1 hs, ?_⟩ ext t rw [mem_initSeg] refine ⟨fun p ↦ ?_, ?_⟩ · rw [h𝒜.1 p, h𝒜.1 hs] exact ⟨rfl, le_sup' _ p⟩ rintro ⟨cards, le⟩ obtain p | p := le.eq_or_lt · rwa [toColex_inj.1 p] · exact h𝒜.2 hs ⟨p, cards ▸ h𝒜.1 hs⟩ /-- Being a nonempty initial segment of colex is equivalent to being an `initSeg`. -/ lemma isInitSeg_iff_exists_initSeg : IsInitSeg 𝒜 r ∧ 𝒜.Nonempty ↔ ∃ s : Finset α, #s = r ∧ 𝒜 = initSeg s := by refine ⟨fun h𝒜 ↦ h𝒜.1.exists_initSeg h𝒜.2, ?_⟩ rintro ⟨s, rfl, rfl⟩ exact ⟨isInitSeg_initSeg, initSeg_nonempty⟩ end Colex /-! ### Colex on `ℕ` The colexicographic order agrees with the order induced by interpreting a set of naturals as a `n`-ary expansion. -/ section Nat variable {s t : Finset ℕ} {n : ℕ} lemma geomSum_ofColex_strictMono (hn : 2 ≤ n) : StrictMono fun s ↦ ∑ k ∈ ofColex s, n ^ k := by intro s t hst rw [lt_iff_exists_forall_lt] at hst obtain ⟨a, hat, has, ha⟩ := hst rw [← sum_sdiff_lt_sum_sdiff] exact (Nat.geomSum_lt hn <| by simpa).trans_le <| single_le_sum (fun _ _ ↦ by cutsat) <| mem_sdiff.2 ⟨hat, has⟩ /-- For finsets of naturals, the colexicographic order is equivalent to the order induced by the `n`-ary expansion. -/ lemma geomSum_le_geomSum_iff_toColex_le_toColex (hn : 2 ≤ n) : ∑ k ∈ s, n ^ k ≤ ∑ k ∈ t, n ^ k ↔ toColex s ≤ toColex t := (geomSum_ofColex_strictMono hn).le_iff_le /-- For finsets of naturals, the colexicographic order is equivalent to the order induced by the `n`-ary expansion. -/ lemma geomSum_lt_geomSum_iff_toColex_lt_toColex (hn : 2 ≤ n) : ∑ i ∈ s, n ^ i < ∑ i ∈ t, n ^ i ↔ toColex s < toColex t := (geomSum_ofColex_strictMono hn).lt_iff_lt theorem geomSum_injective {n : ℕ} (hn : 2 ≤ n) : Function.Injective (fun s : Finset ℕ ↦ ∑ i ∈ s, n ^ i) := by intro _ _ h rwa [le_antisymm_iff, geomSum_le_geomSum_iff_toColex_le_toColex hn, geomSum_le_geomSum_iff_toColex_le_toColex hn, ← le_antisymm_iff] at h theorem lt_geomSum_of_mem {a : ℕ} (hn : 2 ≤ n) (hi : a ∈ s) : a < ∑ i ∈ s, n ^ i := (a.lt_pow_self hn).trans_le <| single_le_sum (by simp) hi @[simp] theorem toFinset_bitIndices_twoPowSum (s : Finset ℕ) : (∑ i ∈ s, 2 ^ i).bitIndices.toFinset = s := by simp [← (geomSum_injective rfl.le).eq_iff, List.sum_toFinset _ Nat.bitIndices_sorted.nodup] @[simp] theorem twoPowSum_toFinset_bitIndices (n : ℕ) : ∑ i ∈ n.bitIndices.toFinset, 2 ^ i = n := by simp [List.sum_toFinset _ Nat.bitIndices_sorted.nodup] /-- The equivalence between `ℕ` and `Finset ℕ` that maps `∑ i ∈ s, 2^i` to `s`. -/ @[simps] def equivBitIndices : ℕ ≃ Finset ℕ where toFun n := n.bitIndices.toFinset invFun s := ∑ i ∈ s, 2^i left_inv := twoPowSum_toFinset_bitIndices right_inv := toFinset_bitIndices_twoPowSum /-- The equivalence `Nat.equivBitIndices` enumerates `Finset ℕ` in colexicographic order. -/ @[simps] def orderIsoColex : ℕ ≃o Colex (Finset ℕ) where toFun n := toColex (equivBitIndices n) invFun s := equivBitIndices.symm (ofColex s) left_inv n := equivBitIndices.symm_apply_apply n right_inv s := equivBitIndices.apply_symm_apply _ map_rel_iff' := by simp [← (Finset.geomSum_le_geomSum_iff_toColex_le_toColex rfl.le)] end Nat end Finset
.lake/packages/mathlib/Mathlib/Combinatorics/Configuration.lean
import Mathlib.Combinatorics.Hall.Basic import Mathlib.LinearAlgebra.Matrix.Rank import Mathlib.LinearAlgebra.Projectivization.Constructions /-! # Configurations of Points and lines This file introduces abstract configurations of points and lines, and proves some basic properties. ## Main definitions * `Configuration.Nondegenerate`: Excludes certain degenerate configurations, and imposes uniqueness of intersection points. * `Configuration.HasPoints`: A nondegenerate configuration in which every pair of lines has an intersection point. * `Configuration.HasLines`: A nondegenerate configuration in which every pair of points has a line through them. * `Configuration.lineCount`: The number of lines through a given point. * `Configuration.pointCount`: The number of lines through a given line. ## Main statements * `Configuration.HasLines.card_le`: `HasLines` implies `|P| ≤ |L|`. * `Configuration.HasPoints.card_le`: `HasPoints` implies `|L| ≤ |P|`. * `Configuration.HasLines.hasPoints`: `HasLines` and `|P| = |L|` implies `HasPoints`. * `Configuration.HasPoints.hasLines`: `HasPoints` and `|P| = |L|` implies `HasLines`. Together, these four statements say that any two of the following properties imply the third: (a) `HasLines`, (b) `HasPoints`, (c) `|P| = |L|`. -/ open Finset namespace Configuration variable (P L : Type*) [Membership P L] /-- A type synonym. -/ def Dual := P instance [h : Inhabited P] : Inhabited (Dual P) := h instance [Finite P] : Finite (Dual P) := ‹Finite P› instance [h : Fintype P] : Fintype (Dual P) := h set_option synthInstance.checkSynthOrder false in instance : Membership (Dual L) (Dual P) := ⟨Function.swap (Membership.mem : L → P → Prop)⟩ /-- A configuration is nondegenerate if: 1) there does not exist a line that passes through all of the points, 2) there does not exist a point that is on all of the lines, 3) there is at most one line through any two points, 4) any two lines have at most one intersection point. Conditions 3 and 4 are equivalent. -/ class Nondegenerate : Prop where exists_point : ∀ l : L, ∃ p, p ∉ l exists_line : ∀ p, ∃ l : L, p ∉ l eq_or_eq : ∀ {p₁ p₂ : P} {l₁ l₂ : L}, p₁ ∈ l₁ → p₂ ∈ l₁ → p₁ ∈ l₂ → p₂ ∈ l₂ → p₁ = p₂ ∨ l₁ = l₂ /-- A nondegenerate configuration in which every pair of lines has an intersection point. -/ class HasPoints extends Nondegenerate P L where /-- Intersection of two lines -/ mkPoint : ∀ {l₁ l₂ : L}, l₁ ≠ l₂ → P mkPoint_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mkPoint h ∈ l₁ ∧ mkPoint h ∈ l₂ /-- A nondegenerate configuration in which every pair of points has a line through them. -/ class HasLines extends Nondegenerate P L where /-- Line through two points -/ mkLine : ∀ {p₁ p₂ : P}, p₁ ≠ p₂ → L mkLine_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mkLine h ∧ p₂ ∈ mkLine h open Nondegenerate open HasPoints (mkPoint mkPoint_ax) open HasLines (mkLine mkLine_ax) instance Dual.Nondegenerate [Nondegenerate P L] : Nondegenerate (Dual L) (Dual P) where exists_point := @exists_line P L _ _ exists_line := @exists_point P L _ _ eq_or_eq := @fun l₁ l₂ p₁ p₂ h₁ h₂ h₃ h₄ => (@eq_or_eq P L _ _ p₁ p₂ l₁ l₂ h₁ h₃ h₂ h₄).symm instance Dual.hasLines [HasPoints P L] : HasLines (Dual L) (Dual P) := { Dual.Nondegenerate _ _ with mkLine := @mkPoint P L _ _ mkLine_ax := @mkPoint_ax P L _ _ } instance Dual.hasPoints [HasLines P L] : HasPoints (Dual L) (Dual P) := { Dual.Nondegenerate _ _ with mkPoint := @mkLine P L _ _ mkPoint_ax := @mkLine_ax P L _ _ } theorem HasPoints.existsUnique_point [HasPoints P L] (l₁ l₂ : L) (hl : l₁ ≠ l₂) : ∃! p, p ∈ l₁ ∧ p ∈ l₂ := ⟨mkPoint hl, mkPoint_ax hl, fun _ hp => (eq_or_eq hp.1 (mkPoint_ax hl).1 hp.2 (mkPoint_ax hl).2).resolve_right hl⟩ theorem HasLines.existsUnique_line [HasLines P L] (p₁ p₂ : P) (hp : p₁ ≠ p₂) : ∃! l : L, p₁ ∈ l ∧ p₂ ∈ l := HasPoints.existsUnique_point (Dual L) (Dual P) p₁ p₂ hp variable {P L} /-- If a nondegenerate configuration has at least as many points as lines, then there exists an injective function `f` from lines to points, such that `f l` does not lie on `l`. -/ theorem Nondegenerate.exists_injective_of_card_le [Nondegenerate P L] [Fintype P] [Fintype L] (h : Fintype.card L ≤ Fintype.card P) : ∃ f : L → P, Function.Injective f ∧ ∀ l, f l ∉ l := by classical let t : L → Finset P := fun l => Set.toFinset { p | p ∉ l } suffices ∀ s : Finset L, #s ≤ (s.biUnion t).card by -- Hall's marriage theorem obtain ⟨f, hf1, hf2⟩ := (Finset.all_card_le_biUnion_card_iff_exists_injective t).mp this exact ⟨f, hf1, fun l => Set.mem_toFinset.mp (hf2 l)⟩ intro s by_cases hs₀ : #s = 0 -- If `s = ∅`, then `#s = 0 ≤ #(s.bUnion t)` · simp_rw [hs₀, zero_le] by_cases hs₁ : #s = 1 -- If `s = {l}`, then pick a point `p ∉ l` · obtain ⟨l, rfl⟩ := Finset.card_eq_one.mp hs₁ obtain ⟨p, hl⟩ := exists_point (P := P) l rw [Finset.card_singleton, Finset.singleton_biUnion, Nat.one_le_iff_ne_zero] exact Finset.card_ne_zero_of_mem (Set.mem_toFinset.mpr hl) suffices #(s.biUnion t)ᶜ ≤ #sᶜ by -- Rephrase in terms of complements (uses `h`) rw [Finset.card_compl, Finset.card_compl, tsub_le_iff_left] at this replace := h.trans this rwa [← add_tsub_assoc_of_le s.card_le_univ, le_tsub_iff_left (le_add_left s.card_le_univ), add_le_add_iff_right] at this have hs₂ : #(s.biUnion t)ᶜ ≤ 1 := by -- At most one line through two points of `s` refine Finset.card_le_one_iff.mpr @fun p₁ p₂ hp₁ hp₂ => ?_ simp_rw [t, Finset.mem_compl, Finset.mem_biUnion, not_exists, not_and, Set.mem_toFinset, Set.mem_setOf_eq, Classical.not_not] at hp₁ hp₂ obtain ⟨l₁, l₂, hl₁, hl₂, hl₃⟩ := Finset.one_lt_card_iff.mp (Nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨hs₀, hs₁⟩) exact (eq_or_eq (hp₁ l₁ hl₁) (hp₂ l₁ hl₁) (hp₁ l₂ hl₂) (hp₂ l₂ hl₂)).resolve_right hl₃ by_cases hs₃ : #sᶜ = 0 · rw [hs₃, Nat.le_zero] rw [Finset.card_compl, tsub_eq_zero_iff_le, (Finset.card_le_univ _).ge_iff_eq', eq_comm, Finset.card_eq_iff_eq_univ] at hs₃ ⊢ rw [hs₃] rw [Finset.eq_univ_iff_forall] at hs₃ ⊢ exact fun p => Exists.elim (exists_line p)-- If `s = univ`, then show `s.bUnion t = univ` fun l hl => Finset.mem_biUnion.mpr ⟨l, Finset.mem_univ l, Set.mem_toFinset.mpr hl⟩ · exact hs₂.trans (Nat.one_le_iff_ne_zero.mpr hs₃) -- If `s < univ`, then consequence of `hs₂` variable (L) /-- Number of points on a given line. -/ noncomputable def lineCount (p : P) : ℕ := Nat.card { l : L // p ∈ l } variable (P) {L} /-- Number of lines through a given point. -/ noncomputable def pointCount (l : L) : ℕ := Nat.card { p : P // p ∈ l } variable (L) theorem sum_lineCount_eq_sum_pointCount [Fintype P] [Fintype L] : ∑ p : P, lineCount L p = ∑ l : L, pointCount P l := by classical simp only [lineCount, pointCount, Nat.card_eq_fintype_card, ← Fintype.card_sigma] apply Fintype.card_congr calc (Σ p, { l : L // p ∈ l }) ≃ { x : P × L // x.1 ∈ x.2 } := (Equiv.subtypeProdEquivSigmaSubtype (· ∈ ·)).symm _ ≃ { x : L × P // x.2 ∈ x.1 } := (Equiv.prodComm P L).subtypeEquiv fun x => Iff.rfl _ ≃ Σ l, { p // p ∈ l } := Equiv.subtypeProdEquivSigmaSubtype fun (l : L) (p : P) => p ∈ l variable {P L} theorem HasLines.pointCount_le_lineCount [HasLines P L] {p : P} {l : L} (h : p ∉ l) [Finite { l : L // p ∈ l }] : pointCount P l ≤ lineCount L p := by by_cases hf : Infinite { p : P // p ∈ l } · exact (le_of_eq Nat.card_eq_zero_of_infinite).trans (zero_le (lineCount L p)) haveI := fintypeOfNotInfinite hf cases nonempty_fintype { l : L // p ∈ l } rw [lineCount, pointCount, Nat.card_eq_fintype_card, Nat.card_eq_fintype_card] have : ∀ p' : { p // p ∈ l }, p ≠ p' := fun p' hp' => h ((congr_arg (· ∈ l) hp').mpr p'.2) exact Fintype.card_le_of_injective (fun p' => ⟨mkLine (this p'), (mkLine_ax (this p')).1⟩) fun p₁ p₂ hp => Subtype.ext ((eq_or_eq p₁.2 p₂.2 (mkLine_ax (this p₁)).2 ((congr_arg (_ ∈ ·) (Subtype.ext_iff.mp hp)).mpr (mkLine_ax (this p₂)).2)).resolve_right fun h' => (congr_arg (p ∉ ·) h').mp h (mkLine_ax (this p₁)).1) theorem HasPoints.lineCount_le_pointCount [HasPoints P L] {p : P} {l : L} (h : p ∉ l) [hf : Finite { p : P // p ∈ l }] : lineCount L p ≤ pointCount P l := @HasLines.pointCount_le_lineCount (Dual L) (Dual P) _ _ l p h hf variable (P L) /-- If a nondegenerate configuration has a unique line through any two points, then `|P| ≤ |L|`. -/ theorem HasLines.card_le [HasLines P L] [Fintype P] [Fintype L] : Fintype.card P ≤ Fintype.card L := by classical by_contra hc₂ obtain ⟨f, hf₁, hf₂⟩ := Nondegenerate.exists_injective_of_card_le (le_of_not_ge hc₂) have := calc ∑ p, lineCount L p = ∑ l, pointCount P l := sum_lineCount_eq_sum_pointCount P L _ ≤ ∑ l, lineCount L (f l) := (Finset.sum_le_sum fun l _ => HasLines.pointCount_le_lineCount (hf₂ l)) _ = ∑ p ∈ univ.map ⟨f, hf₁⟩, lineCount L p := by rw [sum_map]; dsimp _ < ∑ p, lineCount L p := by obtain ⟨p, hp⟩ := not_forall.mp (mt (Fintype.card_le_of_surjective f) hc₂) refine sum_lt_sum_of_subset (subset_univ _) (mem_univ p) ?_ ?_ fun p _ _ ↦ zero_le _ · simpa only [Finset.mem_map, exists_prop, Finset.mem_univ, true_and] · rw [lineCount, Nat.card_eq_fintype_card, Fintype.card_pos_iff] obtain ⟨l, _⟩ := @exists_line P L _ _ p exact let this := not_exists.mp hp l ⟨⟨mkLine this, (mkLine_ax this).2⟩⟩ exact lt_irrefl _ this /-- If a nondegenerate configuration has a unique point on any two lines, then `|L| ≤ |P|`. -/ theorem HasPoints.card_le [HasPoints P L] [Fintype P] [Fintype L] : Fintype.card L ≤ Fintype.card P := @HasLines.card_le (Dual L) (Dual P) _ _ _ _ variable {P L} theorem HasLines.exists_bijective_of_card_eq [HasLines P L] [Fintype P] [Fintype L] (h : Fintype.card P = Fintype.card L) : ∃ f : L → P, Function.Bijective f ∧ ∀ l, pointCount P l = lineCount L (f l) := by classical obtain ⟨f, hf1, hf2⟩ := Nondegenerate.exists_injective_of_card_le (ge_of_eq h) have hf3 := (Fintype.bijective_iff_injective_and_card f).mpr ⟨hf1, h.symm⟩ exact ⟨f, hf3, fun l ↦ (sum_eq_sum_iff_of_le fun l _ ↦ pointCount_le_lineCount (hf2 l)).1 ((hf3.sum_comp _).trans (sum_lineCount_eq_sum_pointCount P L)).symm _ <| mem_univ _⟩ theorem HasLines.lineCount_eq_pointCount [HasLines P L] [Fintype P] [Fintype L] (hPL : Fintype.card P = Fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : lineCount L p = pointCount P l := by classical obtain ⟨f, hf1, hf2⟩ := HasLines.exists_bijective_of_card_eq hPL let s : Finset (P × L) := Set.toFinset { i | i.1 ∈ i.2 } have step1 : ∑ i : P × L, lineCount L i.1 = ∑ i : P × L, pointCount P i.2 := by rw [← Finset.univ_product_univ, Finset.sum_product_right, Finset.sum_product] simp_rw [Finset.sum_const, Finset.card_univ, hPL, sum_lineCount_eq_sum_pointCount] have step2 : ∑ i ∈ s, lineCount L i.1 = ∑ i ∈ s, pointCount P i.2 := by rw [s.sum_finset_product Finset.univ fun p => Set.toFinset { l | p ∈ l }] on_goal 1 => rw [s.sum_finset_product_right Finset.univ fun l => Set.toFinset { p | p ∈ l }, eq_comm] · refine sum_bijective _ hf1 (by simp) fun l _ ↦ ?_ simp_rw [hf2, sum_const, Set.toFinset_card, ← Nat.card_eq_fintype_card] change pointCount P l • _ = lineCount L (f l) • _ rw [hf2] all_goals simp_rw [s, Finset.mem_univ, true_and, Set.mem_toFinset]; exact fun p => Iff.rfl have step3 : ∑ i ∈ sᶜ, lineCount L i.1 = ∑ i ∈ sᶜ, pointCount P i.2 := by rwa [← s.sum_add_sum_compl, ← s.sum_add_sum_compl, step2, add_left_cancel_iff] at step1 rw [← Set.toFinset_compl] at step3 exact ((Finset.sum_eq_sum_iff_of_le fun i hi => HasLines.pointCount_le_lineCount (by exact Set.mem_toFinset.mp hi)).mp step3.symm (p, l) (Set.mem_toFinset.mpr hpl)).symm theorem HasPoints.lineCount_eq_pointCount [HasPoints P L] [Fintype P] [Fintype L] (hPL : Fintype.card P = Fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : lineCount L p = pointCount P l := (@HasLines.lineCount_eq_pointCount (Dual L) (Dual P) _ _ _ _ hPL.symm l p hpl).symm /-- If a nondegenerate configuration has a unique line through any two points, and if `|P| = |L|`, then there is a unique point on any two lines. -/ noncomputable def HasLines.hasPoints [HasLines P L] [Fintype P] [Fintype L] (h : Fintype.card P = Fintype.card L) : HasPoints P L := let this : ∀ l₁ l₂ : L, l₁ ≠ l₂ → ∃ p : P, p ∈ l₁ ∧ p ∈ l₂ := fun l₁ l₂ hl => by classical obtain ⟨f, _, hf2⟩ := HasLines.exists_bijective_of_card_eq h haveI : Nontrivial L := ⟨⟨l₁, l₂, hl⟩⟩ haveI := Fintype.one_lt_card_iff_nontrivial.mp ((congr_arg _ h).mpr Fintype.one_lt_card) have h₁ : ∀ p : P, 0 < lineCount L p := fun p => Exists.elim (exists_ne p) fun q hq => (congr_arg _ Nat.card_eq_fintype_card).mpr (Fintype.card_pos_iff.mpr ⟨⟨mkLine hq, (mkLine_ax hq).2⟩⟩) have h₂ : ∀ l : L, 0 < pointCount P l := fun l => (congr_arg _ (hf2 l)).mpr (h₁ (f l)) obtain ⟨p, hl₁⟩ := Fintype.card_pos_iff.mp ((congr_arg _ Nat.card_eq_fintype_card).mp (h₂ l₁)) by_cases hl₂ : p ∈ l₂ · exact ⟨p, hl₁, hl₂⟩ have key' : Fintype.card { q : P // q ∈ l₂ } = Fintype.card { l : L // p ∈ l } := ((HasLines.lineCount_eq_pointCount h hl₂).trans Nat.card_eq_fintype_card).symm.trans Nat.card_eq_fintype_card have : ∀ q : { q // q ∈ l₂ }, p ≠ q := fun q hq => hl₂ ((congr_arg (· ∈ l₂) hq).mpr q.2) let f : { q : P // q ∈ l₂ } → { l : L // p ∈ l } := fun q => ⟨mkLine (this q), (mkLine_ax (this q)).1⟩ have hf : Function.Injective f := fun q₁ q₂ hq => Subtype.ext ((eq_or_eq q₁.2 q₂.2 (mkLine_ax (this q₁)).2 ((congr_arg (_ ∈ ·) (Subtype.ext_iff.mp hq)).mpr (mkLine_ax (this q₂)).2)).resolve_right fun h => (congr_arg (p ∉ ·) h).mp hl₂ (mkLine_ax (this q₁)).1) have key' := ((Fintype.bijective_iff_injective_and_card f).mpr ⟨hf, key'⟩).2 obtain ⟨q, hq⟩ := key' ⟨l₁, hl₁⟩ exact ⟨q, (congr_arg (_ ∈ ·) (Subtype.ext_iff.mp hq)).mp (mkLine_ax (this q)).2, q.2⟩ { ‹HasLines P L› with mkPoint := fun {l₁ l₂} hl => Classical.choose (this l₁ l₂ hl) mkPoint_ax := fun {l₁ l₂} hl => Classical.choose_spec (this l₁ l₂ hl) } /-- If a nondegenerate configuration has a unique point on any two lines, and if `|P| = |L|`, then there is a unique line through any two points. -/ noncomputable def HasPoints.hasLines [HasPoints P L] [Fintype P] [Fintype L] (h : Fintype.card P = Fintype.card L) : HasLines P L := let this := @HasLines.hasPoints (Dual L) (Dual P) _ _ _ _ h.symm { ‹HasPoints P L› with mkLine := @fun _ _ => this.mkPoint mkLine_ax := @fun _ _ => this.mkPoint_ax } variable (P L) /-- A projective plane is a nondegenerate configuration in which every pair of lines has an intersection point, every pair of points has a line through them, and which has three points in general position. -/ class ProjectivePlane extends HasPoints P L, HasLines P L where exists_config : ∃ (p₁ p₂ p₃ : P) (l₁ l₂ l₃ : L), p₁ ∉ l₂ ∧ p₁ ∉ l₃ ∧ p₂ ∉ l₁ ∧ p₂ ∈ l₂ ∧ p₂ ∈ l₃ ∧ p₃ ∉ l₁ ∧ p₃ ∈ l₂ ∧ p₃ ∉ l₃ namespace ProjectivePlane variable [ProjectivePlane P L] instance : ProjectivePlane (Dual L) (Dual P) := { Dual.hasPoints _ _, Dual.hasLines _ _ with exists_config := let ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _ ⟨l₁, l₂, l₃, p₁, p₂, p₃, h₂₁, h₃₁, h₁₂, h₂₂, h₃₂, h₁₃, h₂₃, h₃₃⟩ } /-- The order of a projective plane is one less than the number of lines through an arbitrary point. Equivalently, it is one less than the number of points on an arbitrary line. -/ noncomputable def order : ℕ := lineCount L (Classical.choose (@exists_config P L _ _)) - 1 theorem card_points_eq_card_lines [Fintype P] [Fintype L] : Fintype.card P = Fintype.card L := le_antisymm (HasLines.card_le P L) (HasPoints.card_le P L) variable {P} theorem lineCount_eq_lineCount [Finite P] [Finite L] (p q : P) : lineCount L p = lineCount L q := by cases nonempty_fintype P cases nonempty_fintype L obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _ have h := card_points_eq_card_lines P L let n := lineCount L p₂ have hp₂ : lineCount L p₂ = n := rfl have hl₁ : pointCount P l₁ = n := (HasLines.lineCount_eq_pointCount h h₂₁).symm.trans hp₂ have hp₃ : lineCount L p₃ = n := (HasLines.lineCount_eq_pointCount h h₃₁).trans hl₁ have hl₃ : pointCount P l₃ = n := (HasLines.lineCount_eq_pointCount h h₃₃).symm.trans hp₃ have hp₁ : lineCount L p₁ = n := (HasLines.lineCount_eq_pointCount h h₁₃).trans hl₃ have hl₂ : pointCount P l₂ = n := (HasLines.lineCount_eq_pointCount h h₁₂).symm.trans hp₁ suffices ∀ p : P, lineCount L p = n by exact (this p).trans (this q).symm refine fun p => or_not.elim (fun h₂ => ?_) fun h₂ => (HasLines.lineCount_eq_pointCount h h₂).trans hl₂ refine or_not.elim (fun h₃ => ?_) fun h₃ => (HasLines.lineCount_eq_pointCount h h₃).trans hl₃ rw [(eq_or_eq h₂ h₂₂ h₃ h₂₃).resolve_right fun h => h₃₃ ((congr_arg (p₃ ∈ ·) h).mp h₃₂)] variable (P) {L} theorem pointCount_eq_pointCount [Finite P] [Finite L] (l m : L) : pointCount P l = pointCount P m := by apply lineCount_eq_lineCount (Dual P) variable {P} theorem lineCount_eq_pointCount [Finite P] [Finite L] (p : P) (l : L) : lineCount L p = pointCount P l := Exists.elim (exists_point l) fun q hq => (lineCount_eq_lineCount L p q).trans <| by cases nonempty_fintype P cases nonempty_fintype L exact HasLines.lineCount_eq_pointCount (card_points_eq_card_lines P L) hq variable (P L) theorem Dual.order [Finite P] [Finite L] : order (Dual L) (Dual P) = order P L := congr_arg (fun n => n - 1) (lineCount_eq_pointCount _ _) variable {P} theorem lineCount_eq [Finite P] [Finite L] (p : P) : lineCount L p = order P L + 1 := by classical obtain ⟨q, -, -, l, -, -, -, -, h, -⟩ := Classical.choose_spec (@exists_config P L _ _) cases nonempty_fintype { l : L // q ∈ l } rw [order, lineCount_eq_lineCount L p q, lineCount_eq_lineCount L (Classical.choose _) q, lineCount, Nat.card_eq_fintype_card, Nat.sub_add_cancel] exact Fintype.card_pos_iff.mpr ⟨⟨l, h⟩⟩ variable (P) {L} theorem pointCount_eq [Finite P] [Finite L] (l : L) : pointCount P l = order P L + 1 := (lineCount_eq (Dual P) _).trans (congr_arg (fun n => n + 1) (Dual.order P L)) variable (L) theorem one_lt_order [Finite P] [Finite L] : 1 < order P L := by obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, -, -, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _ cases nonempty_fintype { p : P // p ∈ l₂ } rw [← add_lt_add_iff_right 1, ← pointCount_eq _ l₂, pointCount, Nat.card_eq_fintype_card, Fintype.two_lt_card_iff] simp_rw [Ne, Subtype.ext_iff] have h := mkPoint_ax (P := P) (L := L) fun h => h₂₁ ((congr_arg (p₂ ∈ ·) h).mpr h₂₂) exact ⟨⟨mkPoint _, h.2⟩, ⟨p₂, h₂₂⟩, ⟨p₃, h₃₂⟩, ne_of_mem_of_not_mem h.1 h₂₁, ne_of_mem_of_not_mem h.1 h₃₁, ne_of_mem_of_not_mem h₂₃ h₃₃⟩ variable {P} theorem two_lt_lineCount [Finite P] [Finite L] (p : P) : 2 < lineCount L p := by simpa only [lineCount_eq L p, Nat.succ_lt_succ_iff] using one_lt_order P L variable (P) {L} theorem two_lt_pointCount [Finite P] [Finite L] (l : L) : 2 < pointCount P l := by simpa only [pointCount_eq P l, Nat.succ_lt_succ_iff] using one_lt_order P L variable (L) theorem card_points [Fintype P] [Finite L] : Fintype.card P = order P L ^ 2 + order P L + 1 := by cases nonempty_fintype L obtain ⟨p, -⟩ := @exists_config P L _ _ let ϕ : { q // q ≠ p } ≃ Σ l : { l : L // p ∈ l }, { q // q ∈ l.1 ∧ q ≠ p } := { toFun := fun q => ⟨⟨mkLine q.2, (mkLine_ax q.2).2⟩, q, (mkLine_ax q.2).1, q.2⟩ invFun := fun lq => ⟨lq.2, lq.2.2.2⟩ right_inv := fun lq => Sigma.subtype_ext (Subtype.ext ((eq_or_eq (mkLine_ax lq.2.2.2).1 (mkLine_ax lq.2.2.2).2 lq.2.2.1 lq.1.2).resolve_left lq.2.2.2)) rfl } classical have h1 : Fintype.card { q // q ≠ p } + 1 = Fintype.card P := by apply (eq_tsub_iff_add_eq_of_le (Nat.succ_le_of_lt (Fintype.card_pos_iff.mpr ⟨p⟩))).mp convert (Fintype.card_subtype_compl _).trans (congr_arg _ (Fintype.card_subtype_eq p)) have h2 : ∀ l : { l : L // p ∈ l }, Fintype.card { q // q ∈ l.1 ∧ q ≠ p } = order P L := by intro l rw [← Fintype.card_congr (Equiv.subtypeSubtypeEquivSubtypeInter (· ∈ l.val) (· ≠ p)), Fintype.card_subtype_compl fun x : Subtype (· ∈ l.val) => x.val = p, ← Nat.card_eq_fintype_card] refine tsub_eq_of_eq_add ((pointCount_eq P l.1).trans ?_) rw [← Fintype.card_subtype_eq (⟨p, l.2⟩ : { q : P // q ∈ l.1 })] simp_rw [Subtype.ext_iff] simp_rw [← h1, Fintype.card_congr ϕ, Fintype.card_sigma, h2, Finset.sum_const, Finset.card_univ] rw [← Nat.card_eq_fintype_card, ← lineCount, lineCount_eq, smul_eq_mul, Nat.succ_mul, sq] theorem card_lines [Finite P] [Fintype L] : Fintype.card L = order P L ^ 2 + order P L + 1 := (card_points (Dual L) (Dual P)).trans (congr_arg (fun n => n ^ 2 + n + 1) (Dual.order P L)) end ProjectivePlane namespace ofField variable {K : Type*} [Field K] open scoped LinearAlgebra.Projectivization open Matrix Projectivization instance : Membership (ℙ K (Fin 3 → K)) (ℙ K (Fin 3 → K)) := ⟨Function.swap orthogonal⟩ lemma mem_iff (v w : ℙ K (Fin 3 → K)) : v ∈ w ↔ orthogonal v w := Iff.rfl -- This lemma can't be moved to the crossProduct file due to heavy imports lemma crossProduct_eq_zero_of_dotProduct_eq_zero {a b c d : Fin 3 → K} (hac : a ⬝ᵥ c = 0) (hbc : b ⬝ᵥ c = 0) (had : a ⬝ᵥ d = 0) (hbd : b ⬝ᵥ d = 0) : crossProduct a b = 0 ∨ crossProduct c d = 0 := by by_contra h simp_rw [not_or, ← ne_eq, crossProduct_ne_zero_iff_linearIndependent] at h rw [← Matrix.of_row (![a,b]), ← Matrix.of_row (![c,d])] at h let A : Matrix (Fin 2) (Fin 3) K := .of ![a, b] let B : Matrix (Fin 2) (Fin 3) K := .of ![c, d] have hAB : A * B.transpose = 0 := by ext i j fin_cases i <;> fin_cases j <;> assumption replace hAB := rank_add_rank_le_card_of_mul_eq_zero hAB rw [rank_transpose, h.1.rank_matrix, h.2.rank_matrix, Fintype.card_fin, Fintype.card_fin] at hAB contradiction lemma eq_or_eq_of_orthogonal {a b c d : ℙ K (Fin 3 → K)} (hac : a.orthogonal c) (hbc : b.orthogonal c) (had : a.orthogonal d) (hbd : b.orthogonal d) : a = b ∨ c = d := by induction a with | h a ha => induction b with | h b hb => induction c with | h c hc => induction d with | h d hd => rw [mk_eq_mk_iff_crossProduct_eq_zero, mk_eq_mk_iff_crossProduct_eq_zero] exact crossProduct_eq_zero_of_dotProduct_eq_zero hac hbc had hbd instance : Nondegenerate (ℙ K (Fin 3 → K)) (ℙ K (Fin 3 → K)) := { exists_point := exists_not_orthogonal_self exists_line := exists_not_self_orthogonal eq_or_eq := eq_or_eq_of_orthogonal } noncomputable instance [DecidableEq K] : ProjectivePlane (ℙ K (Fin 3 → K)) (ℙ K (Fin 3 → K)) := { mkPoint := by intro v w _ exact cross v w mkPoint_ax := fun h ↦ ⟨cross_orthogonal_left h, cross_orthogonal_right h⟩ mkLine := by intro v w _ exact cross v w mkLine_ax := fun h ↦ ⟨orthogonal_cross_left h, orthogonal_cross_right h⟩ exists_config := by refine ⟨mk K ![0, 1, 1] ?_, mk K ![1, 0, 0] ?_, mk K ![1, 0, 1] ?_, mk K ![1, 0, 0] ?_, mk K ![0, 1, 0] ?_, mk K ![0, 0, 1] ?_, ?_⟩ <;> simp [mem_iff, orthogonal_mk] } end ofField end Configuration
.lake/packages/mathlib/Mathlib/Combinatorics/Pigeonhole.lean
import Mathlib.Algebra.Module.BigOperators import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Data.Nat.ModEq import Mathlib.Order.Preorder.Finite /-! # Pigeonhole principles Given pigeons (possibly infinitely many) in pigeonholes, the pigeonhole principle states that, if there are more pigeons than pigeonholes, then there is a pigeonhole with two or more pigeons. There are a few variations on this statement, and the conclusion can be made stronger depending on how many pigeons you know you might have. The basic statements of the pigeonhole principle appear in the following locations: * `Data.Finset.Basic` has `Finset.exists_ne_map_eq_of_card_lt_of_maps_to` * `Data.Fintype.Basic` has `Fintype.exists_ne_map_eq_of_card_lt` * `Data.Fintype.Basic` has `Finite.exists_ne_map_eq_of_infinite` * `Data.Fintype.Basic` has `Finite.exists_infinite_fiber` * `Data.Set.Finite` has `Set.infinite.exists_ne_map_eq_of_mapsTo` This module gives access to these pigeonhole principles along with 20 more. The versions vary by: * using a function between `Fintype`s or a function between possibly infinite types restricted to `Finset`s; * counting pigeons by a general weight function (`∑ x ∈ s, w x`) or by heads (`#s`); * using strict or non-strict inequalities; * establishing upper or lower estimate on the number (or the total weight) of the pigeons in one pigeonhole; * in case when we count pigeons by some weight function `w` and consider a function `f` between `Finset`s `s` and `t`, we can either assume that each pigeon is in one of the pigeonholes (`∀ x ∈ s, f x ∈ t`), or assume that for `y ∉ t`, the total weight of the pigeons in this pigeonhole `∑ x ∈ s with f x = y, w x` is nonpositive or nonnegative depending on the inequality we are proving. Lemma names follow `mathlib` convention (e.g., `Finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`); "pigeonhole principle" is mentioned in the docstrings instead of the names. ## See also * `Ordinal.infinite_pigeonhole`: pigeonhole principle for cardinals, formulated using cofinality; * `MeasureTheory.exists_nonempty_inter_of_measure_univ_lt_tsum_measure`, `MeasureTheory.exists_nonempty_inter_of_measure_univ_lt_sum_measure`: pigeonhole principle in a measure space. ## Tags pigeonhole principle -/ universe u v w variable {α : Type u} {β : Type v} {M : Type w} [DecidableEq β] open Nat namespace Finset variable {s : Finset α} {t : Finset β} {f : α → β} {w : α → M} {b : M} {n : ℕ} /-! ### The pigeonhole principles on `Finset`s, pigeons counted by weight In this section we prove the following version of the pigeonhole principle: if the total weight of a finite set of pigeons is greater than `n • b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than `b`, and a few variations of this theorem. The principle is formalized in the following way, see `Finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`: if `f : α → β` is a function which maps all elements of `s : Finset α` to `t : Finset β` and `#t • b < ∑ x ∈ s, w x`, where `w : α → M` is a weight function taking values in a `LinearOrderedCancelAddCommMonoid`, then for some `y ∈ t`, the sum of the weights of all `x ∈ s` such that `f x = y` is greater than `b`. There are a few bits we can change in this theorem: * reverse all inequalities, with obvious adjustments to the name; * replace the assumption `∀ a ∈ s, f a ∈ t` with `∀ y ∉ t, ∑ x ∈ s with f x = y, w x ≤ 0`, and replace `of_maps_to` with `of_sum_fiber_nonpos` in the name; * use non-strict inequalities assuming `t` is nonempty. We can do all these variations independently, so we have eight versions of the theorem. -/ section variable [AddCommMonoid M] [LinearOrder M] [IsOrderedCancelAddMonoid M] /-! #### Strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n • b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ theorem exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (hf : ∀ a ∈ s, f a ∈ t) (hb : #t • b < ∑ x ∈ s, w x) : ∃ y ∈ t, b < ∑ x ∈ s with f x = y, w x := exists_lt_of_sum_lt <| by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n • b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than `b`. -/ theorem exists_sum_fiber_lt_of_maps_to_of_sum_lt_nsmul (hf : ∀ a ∈ s, f a ∈ t) (hb : ∑ x ∈ s, w x < #t • b) : ∃ y ∈ t, ∑ x ∈ s with f x = y, w x < b := exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (M := Mᵒᵈ) hf hb /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n • b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ theorem exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum (ht : ∀ y ∉ t, ∑ x ∈ s with f x = y, w x ≤ 0) (hb : #t • b < ∑ x ∈ s, w x) : ∃ y ∈ t, b < ∑ x ∈ s with f x = y, w x := exists_lt_of_sum_lt <| calc ∑ _y ∈ t, b < ∑ x ∈ s, w x := by simpa _ ≤ ∑ y ∈ t, ∑ x ∈ s with f x = y, w x := sum_le_sum_fiberwise_of_sum_fiber_nonpos ht /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n • b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than `b`. -/ theorem exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (ht : ∀ y ∉ t, (0 : M) ≤ ∑ x ∈ s with f x = y, w x) (hb : ∑ x ∈ s, w x < #t • b) : ∃ y ∈ t, ∑ x ∈ s with f x = y, w x < b := exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum (M := Mᵒᵈ) ht hb /-! #### Non-strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n • b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ theorem exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (hf : ∀ a ∈ s, f a ∈ t) (ht : t.Nonempty) (hb : #t • b ≤ ∑ x ∈ s, w x) : ∃ y ∈ t, b ≤ ∑ x ∈ s with f x = y, w x := exists_le_of_sum_le ht <| by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n • b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ theorem exists_sum_fiber_le_of_maps_to_of_sum_le_nsmul (hf : ∀ a ∈ s, f a ∈ t) (ht : t.Nonempty) (hb : ∑ x ∈ s, w x ≤ #t • b) : ∃ y ∈ t, ∑ x ∈ s with f x = y, w x ≤ b := exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (M := Mᵒᵈ) hf ht hb /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n • b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ theorem exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum (hf : ∀ y ∉ t, ∑ x ∈ s with f x = y, w x ≤ 0) (ht : t.Nonempty) (hb : #t • b ≤ ∑ x ∈ s, w x) : ∃ y ∈ t, b ≤ ∑ x ∈ s with f x = y, w x := exists_le_of_sum_le ht <| calc ∑ _y ∈ t, b ≤ ∑ x ∈ s, w x := by simpa _ ≤ ∑ y ∈ t, ∑ x ∈ s with f x = y, w x := sum_le_sum_fiberwise_of_sum_fiber_nonpos hf /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n • b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ theorem exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (hf : ∀ y ∉ t, (0 : M) ≤ ∑ x ∈ s with f x = y, w x) (ht : t.Nonempty) (hb : ∑ x ∈ s, w x ≤ #t • b) : ∃ y ∈ t, ∑ x ∈ s with f x = y, w x ≤ b := exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum (M := Mᵒᵈ) hf ht hb end variable [CommSemiring M] [LinearOrder M] [IsStrictOrderedRing M] /-! ### The pigeonhole principles on `Finset`s, pigeons counted by heads In this section we formalize a few versions of the following pigeonhole principle: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. First, we can use strict or non-strict inequalities. While the versions with non-strict inequalities are weaker than those with strict inequalities, sometimes it might be more convenient to apply the weaker version. Second, we can either state that there exists a pigeonhole with at least `n` pigeons, or state that there exists a pigeonhole with at most `n` pigeons. In the latter case we do not need the assumption `∀ a ∈ s, f a ∈ t`. So, we prove four theorems: `Finset.exists_lt_card_fiber_of_maps_to_of_mul_lt_card`, `Finset.exists_le_card_fiber_of_maps_to_of_mul_le_card`, `Finset.exists_card_fiber_lt_of_card_lt_mul`, and `Finset.exists_card_fiber_le_of_card_le_mul`. -/ /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. -/ theorem exists_lt_card_fiber_of_nsmul_lt_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (ht : #t • b < #s) : ∃ y ∈ t, b < #{x ∈ s | f x = y} := by simp_rw [cast_card] at ht ⊢ exact exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum hf ht /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function between finite sets `s` and `t` and a natural number `n` such that `#t * n < #s`, there exists `y ∈ t` such that its preimage in `s` has more than `n` elements. -/ theorem exists_lt_card_fiber_of_mul_lt_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (hn : #t * n < #s) : ∃ y ∈ t, n < #{x ∈ s | f x = y} := exists_lt_card_fiber_of_nsmul_lt_card_of_maps_to hf hn /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. -/ theorem exists_card_fiber_lt_of_card_lt_nsmul (ht : #s < #t • b) : ∃ y ∈ t, #{x ∈ s | f x = y} < b := by simp_rw [cast_card] at ht ⊢ exact exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (fun _ _ => sum_nonneg fun _ _ => zero_le_one) ht /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `#s < #t * n`, there exists `y ∈ t` such that its preimage in `s` has less than `n` elements. -/ theorem exists_card_fiber_lt_of_card_lt_mul (hn : #s < #t * n) : ∃ y ∈ t, #{x ∈ s | f x = y} < n := exists_card_fiber_lt_of_card_lt_nsmul hn /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function between finite sets `s` and `t` and a number `b` such that `#t • b ≤ #s`, there exists `y ∈ t` such that its preimage in `s` has at least `b` elements. See also `Finset.exists_lt_card_fiber_of_nsmul_lt_card_of_maps_to` for a stronger statement. -/ theorem exists_le_card_fiber_of_nsmul_le_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (ht : t.Nonempty) (hb : #t • b ≤ #s) : ∃ y ∈ t, b ≤ #{x ∈ s | f x = y} := by simp_rw [cast_card] at hb ⊢ exact exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum hf ht hb /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function between finite sets `s` and `t` and a natural number `b` such that `#t * n ≤ #s`, there exists `y ∈ t` such that its preimage in `s` has at least `n` elements. See also `Finset.exists_lt_card_fiber_of_mul_lt_card_of_maps_to` for a stronger statement. -/ theorem exists_le_card_fiber_of_mul_le_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (ht : t.Nonempty) (hn : #t * n ≤ #s) : ∃ y ∈ t, n ≤ #{x ∈ s | f x = y} := exists_le_card_fiber_of_nsmul_le_card_of_maps_to hf ht hn /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function `f`, a finite sets `s` and `t`, and a number `b` such that `#s ≤ #t • b`, there exists `y ∈ t` such that its preimage in `s` has no more than `b` elements. See also `Finset.exists_card_fiber_lt_of_card_lt_nsmul` for a stronger statement. -/ theorem exists_card_fiber_le_of_card_le_nsmul (ht : t.Nonempty) (hb : #s ≤ #t • b) : ∃ y ∈ t, #{x ∈ s | f x = y} ≤ b := by simp_rw [cast_card] at hb ⊢ refine exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (fun _ _ => sum_nonneg fun _ _ => zero_le_one) ht hb /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `#s ≤ #t * n`, there exists `y ∈ t` such that its preimage in `s` has no more than `n` elements. See also `Finset.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ theorem exists_card_fiber_le_of_card_le_mul (ht : t.Nonempty) (hn : #s ≤ #t * n) : ∃ y ∈ t, #{x ∈ s | f x = y} ≤ n := exists_card_fiber_le_of_card_le_nsmul ht hn end Finset namespace Fintype open Finset variable [Fintype α] [Fintype β] (f : α → β) {w : α → M} {b : M} {n : ℕ} section variable [AddCommMonoid M] [LinearOrder M] [IsOrderedCancelAddMonoid M] /-! ### The pigeonhole principles on `Fintypes`s, pigeons counted by weight In this section we specialize theorems from the previous section to the special case of functions between `Fintype`s and `s = univ`, `t = univ`. In this case the assumption `∀ x ∈ s, f x ∈ t` always holds, so we have four theorems instead of eight. -/ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than `b` provided that the total number of pigeonholes times `b` is less than the total weight of all pigeons. -/ theorem exists_lt_sum_fiber_of_nsmul_lt_sum (hb : card β • b < ∑ x, w x) : ∃ y, b < ∑ x with f x = y, w x := let ⟨y, _, hy⟩ := exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (fun _ _ => mem_univ _) hb ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than or equal to `b` provided that the total number of pigeonholes times `b` is less than or equal to the total weight of all pigeons. -/ theorem exists_le_sum_fiber_of_nsmul_le_sum [Nonempty β] (hb : card β • b ≤ ∑ x, w x) : ∃ y, b ≤ ∑ x with f x = y, w x := let ⟨y, _, hy⟩ := exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (fun _ _ => mem_univ _) univ_nonempty hb ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than `b` provided that the total number of pigeonholes times `b` is greater than the total weight of all pigeons. -/ theorem exists_sum_fiber_lt_of_sum_lt_nsmul (hb : ∑ x, w x < card β • b) : ∃ y, ∑ x with f x = y, w x < b := exists_lt_sum_fiber_of_nsmul_lt_sum (M := Mᵒᵈ) _ hb /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than or equal to `b` provided that the total number of pigeonholes times `b` is greater than or equal to the total weight of all pigeons. -/ theorem exists_sum_fiber_le_of_sum_le_nsmul [Nonempty β] (hb : ∑ x, w x ≤ card β • b) : ∃ y, ∑ x with f x = y, w x ≤ b := exists_le_sum_fiber_of_nsmul_le_sum (M := Mᵒᵈ) _ hb end variable [CommSemiring M] [LinearOrder M] [IsStrictOrderedRing M] /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. -/ theorem exists_lt_card_fiber_of_nsmul_lt_card (hb : card β • b < card α) : ∃ y : β, b < #{x | f x = y} := let ⟨y, _, h⟩ := exists_lt_card_fiber_of_nsmul_lt_card_of_maps_to (fun _ _ => mem_univ _) hb ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n < card α`, there exists an element `y : β` such that its preimage has more than `n` elements. -/ theorem exists_lt_card_fiber_of_mul_lt_card (hn : card β * n < card α) : ∃ y : β, n < #{x | f x = y} := exists_lt_card_fiber_of_nsmul_lt_card _ hn /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. -/ theorem exists_card_fiber_lt_of_card_lt_nsmul (hb : ↑(card α) < card β • b) : ∃ y : β, #{x | f x = y} < b := let ⟨y, _, h⟩ := Finset.exists_card_fiber_lt_of_card_lt_nsmul (f := f) hb ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card α < card β * n`, there exists an element `y : β` such that its preimage has less than `n` elements. -/ theorem exists_card_fiber_lt_of_card_lt_mul (hn : card α < card β * n) : ∃ y : β, #{x | f x = y} < n := exists_card_fiber_lt_of_card_lt_nsmul _ hn /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `b` such that `card β • b ≤ card α`, there exists an element `y : β` such that its preimage has at least `b` elements. See also `Fintype.exists_lt_card_fiber_of_nsmul_lt_card` for a stronger statement. -/ theorem exists_le_card_fiber_of_nsmul_le_card [Nonempty β] (hb : card β • b ≤ card α) : ∃ y : β, b ≤ #{x | f x = y} := let ⟨y, _, h⟩ := exists_le_card_fiber_of_nsmul_le_card_of_maps_to (fun _ _ => mem_univ _) univ_nonempty hb ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n ≤ card α`, there exists an element `y : β` such that its preimage has at least `n` elements. See also `Fintype.exists_lt_card_fiber_of_mul_lt_card` for a stronger statement. -/ theorem exists_le_card_fiber_of_mul_le_card [Nonempty β] (hn : card β * n ≤ card α) : ∃ y : β, n ≤ #{x | f x = y} := exists_le_card_fiber_of_nsmul_le_card _ hn /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `b` such that `card α ≤ card β • b`, there exists an element `y : β` such that its preimage has at most `b` elements. See also `Fintype.exists_card_fiber_lt_of_card_lt_nsmul` for a stronger statement. -/ theorem exists_card_fiber_le_of_card_le_nsmul [Nonempty β] (hb : ↑(card α) ≤ card β • b) : ∃ y : β, #{x | f x = y} ≤ b := let ⟨y, _, h⟩ := Finset.exists_card_fiber_le_of_card_le_nsmul univ_nonempty hb ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card α ≤ card β * n`, there exists an element `y : β` such that its preimage has at most `n` elements. See also `Fintype.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ theorem exists_card_fiber_le_of_card_le_mul [Nonempty β] (hn : card α ≤ card β * n) : ∃ y : β, #{x | f x = y} ≤ n := exists_card_fiber_le_of_card_le_nsmul _ hn end Fintype namespace Nat open Set /-- If `s` is an infinite set of natural numbers and `k > 0`, then `s` contains two elements `m < n` that are equal mod `k`. -/ theorem exists_lt_modEq_of_infinite {s : Set ℕ} (hs : s.Infinite) {k : ℕ} (hk : 0 < k) : ∃ m ∈ s, ∃ n ∈ s, m < n ∧ m ≡ n [MOD k] := (hs.exists_lt_map_eq_of_mapsTo fun n _ => show n % k ∈ Iio k from Nat.mod_lt n hk) <| finite_lt_nat k end Nat
.lake/packages/mathlib/Mathlib/Combinatorics/Hindman.lean
import Mathlib.Data.Stream.Init import Mathlib.Topology.Algebra.Semigroup import Mathlib.Topology.Compactification.StoneCech import Mathlib.Algebra.BigOperators.Group.Finset.Basic /-! # Hindman's theorem on finite sums We prove Hindman's theorem on finite sums, using idempotent ultrafilters. Given an infinite sequence `a₀, a₁, a₂, …` of positive integers, the set `FS(a₀, …)` is the set of positive integers that can be expressed as a finite sum of `aᵢ`'s, without repetition. Hindman's theorem asserts that whenever the positive integers are finitely colored, there exists a sequence `a₀, a₁, a₂, …` such that `FS(a₀, …)` is monochromatic. There is also a stronger version, saying that whenever a set of the form `FS(a₀, …)` is finitely colored, there exists a sequence `b₀, b₁, b₂, …` such that `FS(b₀, …)` is monochromatic and contained in `FS(a₀, …)`. We prove both these versions for a general semigroup `M` instead of `ℕ+` since it is no harder, although this special case implies the general case. The idea of the proof is to extend the addition `(+) : M → M → M` to addition `(+) : βM → βM → βM` on the space `βM` of ultrafilters on `M`. One can prove that if `U` is an _idempotent_ ultrafilter, i.e. `U + U = U`, then any `U`-large subset of `M` contains some set `FS(a₀, …)` (see `exists_FS_of_large`). And with the help of a general topological argument one can show that any set of the form `FS(a₀, …)` is `U`-large according to some idempotent ultrafilter `U` (see `exists_idempotent_ultrafilter_le_FS`). This is enough to prove the theorem since in any finite partition of a `U`-large set, one of the parts is `U`-large. ## Main results - `FS_partition_regular`: the strong form of Hindman's theorem - `exists_FS_of_finite_cover`: the weak form of Hindman's theorem ## Tags Ramsey theory, ultrafilter -/ open Filter /-- Multiplication of ultrafilters given by `∀ᶠ m in U*V, p m ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m*m')`. -/ @[to_additive /-- Addition of ultrafilters given by `∀ᶠ m in U+V, p m ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m+m')`. -/] def Ultrafilter.mul {M} [Mul M] : Mul (Ultrafilter M) where mul U V := (· * ·) <$> U <*> V attribute [local instance] Ultrafilter.mul Ultrafilter.add /- We could have taken this as the definition of `U * V`, but then we would have to prove that it defines an ultrafilter. -/ @[to_additive] theorem Ultrafilter.eventually_mul {M} [Mul M] (U V : Ultrafilter M) (p : M → Prop) : (∀ᶠ m in ↑(U * V), p m) ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m * m') := Iff.rfl /-- Semigroup structure on `Ultrafilter M` induced by a semigroup structure on `M`. -/ @[to_additive /-- Additive semigroup structure on `Ultrafilter M` induced by an additive semigroup structure on `M`. -/] def Ultrafilter.semigroup {M} [Semigroup M] : Semigroup (Ultrafilter M) := { Ultrafilter.mul with mul_assoc := fun U V W => Ultrafilter.coe_inj.mp <| Filter.ext' fun p => by simp [Ultrafilter.eventually_mul, mul_assoc] } attribute [local instance] Ultrafilter.semigroup Ultrafilter.addSemigroup -- We don't prove `continuous_mul_right`, because in general it is false! @[to_additive] theorem Ultrafilter.continuous_mul_left {M} [Mul M] (V : Ultrafilter M) : Continuous (· * V) := ultrafilterBasis_is_basis.continuous_iff.2 <| Set.forall_mem_range.mpr fun s ↦ ultrafilter_isOpen_basic { m : M | ∀ᶠ m' in V, m * m' ∈ s } namespace Hindman /-- `FS a` is the set of finite sums in `a`, i.e. `m ∈ FS a` if `m` is the sum of a nonempty subsequence of `a`. We give a direct inductive definition instead of talking about subsequences. -/ inductive FS {M} [AddSemigroup M] : Stream' M → Set M | head' (a : Stream' M) : FS a a.head | tail' (a : Stream' M) (m : M) (h : FS a.tail m) : FS a m | cons' (a : Stream' M) (m : M) (h : FS a.tail m) : FS a (a.head + m) /-- `FP a` is the set of finite products in `a`, i.e. `m ∈ FP a` if `m` is the product of a nonempty subsequence of `a`. We give a direct inductive definition instead of talking about subsequences. -/ @[to_additive FS] inductive FP {M} [Semigroup M] : Stream' M → Set M | head' (a : Stream' M) : FP a a.head | tail' (a : Stream' M) (m : M) (h : FP a.tail m) : FP a m | cons' (a : Stream' M) (m : M) (h : FP a.tail m) : FP a (a.head * m) section Aliases /-! Since the constructors for `FS` and `FP` cheat using the `Set M = M → Prop` defeq, we provide match patterns that preserve the defeq correctly in their type. -/ variable {M} [Semigroup M] (a : Stream' M) (m : M) (h : FP a.tail m) /-- Constructor for `FP`. This is the preferred spelling over `FP.head'`. -/ @[to_additive (attr := match_pattern, nolint defLemma) /-- Constructor for `FS`. This is the preferred spelling over `FS.head'`. -/] abbrev FP.head : a.head ∈ FP a := FP.head' a /-- Constructor for `FP`. This is the preferred spelling over `FP.tail'`. -/ @[to_additive (attr := match_pattern, nolint defLemma) /-- Constructor for `FS`. This is the preferred spelling over `FS.tail'`. -/] abbrev FP.tail : m ∈ FP a := FP.tail' a m h /-- Constructor for `FP`. This is the preferred spelling over `FP.cons'`. -/ @[to_additive (attr := match_pattern, nolint defLemma) /-- Constructor for `FS`. This is the preferred spelling over `FS.cons'`. -/] abbrev FP.cons : a.head * m ∈ FP a := FP.cons' a m h end Aliases /-- If `m` and `m'` are finite products in `M`, then so is `m * m'`, provided that `m'` is obtained from a subsequence of `M` starting sufficiently late. -/ @[to_additive /-- If `m` and `m'` are finite sums in `M`, then so is `m + m'`, provided that `m'` is obtained from a subsequence of `M` starting sufficiently late. -/] theorem FP.mul {M} [Semigroup M] {a : Stream' M} {m : M} (hm : m ∈ FP a) : ∃ n, ∀ m' ∈ FP (a.drop n), m * m' ∈ FP a := by induction hm with | head' a => exact ⟨1, fun m hm => FP.cons a m hm⟩ | tail' a m _ ih => obtain ⟨n, hn⟩ := ih use n + 1 intro m' hm' exact FP.tail _ _ (hn _ hm') | cons' a m _ ih => obtain ⟨n, hn⟩ := ih use n + 1 intro m' hm' rw [mul_assoc] exact FP.cons _ _ (hn _ hm') @[to_additive exists_idempotent_ultrafilter_le_FS] theorem exists_idempotent_ultrafilter_le_FP {M} [Semigroup M] (a : Stream' M) : ∃ U : Ultrafilter M, U * U = U ∧ ∀ᶠ m in U, m ∈ FP a := by let S : Set (Ultrafilter M) := ⋂ n, { U | ∀ᶠ m in U, m ∈ FP (a.drop n) } have h := exists_idempotent_in_compact_subsemigroup ?_ S ?_ ?_ ?_ · rcases h with ⟨U, hU, U_idem⟩ refine ⟨U, U_idem, ?_⟩ convert Set.mem_iInter.mp hU 0 · exact Ultrafilter.continuous_mul_left · apply IsCompact.nonempty_iInter_of_sequence_nonempty_isCompact_isClosed · intro n U hU filter_upwards [hU] rw [← Stream'.drop_drop, ← Stream'.tail_eq_drop] exact FP.tail _ · intro n exact ⟨pure _, mem_pure.mpr <| FP.head _⟩ · exact (ultrafilter_isClosed_basic _).isCompact · intro n apply ultrafilter_isClosed_basic · exact IsClosed.isCompact (isClosed_iInter fun i => ultrafilter_isClosed_basic _) · intro U hU V hV rw [Set.mem_iInter] at * intro n rw [Set.mem_setOf_eq, Ultrafilter.eventually_mul] filter_upwards [hU n] with m hm obtain ⟨n', hn⟩ := FP.mul hm filter_upwards [hV (n' + n)] with m' hm' apply hn simpa only [Stream'.drop_drop, add_comm] using hm' @[to_additive exists_FS_of_large] theorem exists_FP_of_large {M} [Semigroup M] (U : Ultrafilter M) (U_idem : U * U = U) (s₀ : Set M) (sU : s₀ ∈ U) : ∃ a, FP a ⊆ s₀ := by /- Informally: given a `U`-large set `s₀`, the set `s₀ ∩ { m | ∀ᶠ m' in U, m * m' ∈ s₀ }` is also `U`-large (since `U` is idempotent). Thus in particular there is an `a₀` in this intersection. Now let `s₁` be the intersection `s₀ ∩ { m | a₀ * m ∈ s₀ }`. By choice of `a₀`, this is again `U`-large, so we can repeat the argument starting from `s₁`, obtaining `a₁`, `s₂`, etc. This gives the desired infinite sequence. -/ have exists_elem : ∀ {s : Set M} (_hs : s ∈ U), (s ∩ { m | ∀ᶠ m' in U, m * m' ∈ s }).Nonempty := fun {s} hs => Ultrafilter.nonempty_of_mem (inter_mem hs <| by rwa [← U_idem] at hs) let elem : { s // s ∈ U } → M := fun p => (exists_elem p.property).some let succ : {s // s ∈ U} → {s // s ∈ U} := fun (p : {s // s ∈ U}) => ⟨p.val ∩ {m : M | elem p * m ∈ p.val}, inter_mem p.property (show (exists_elem p.property).some ∈ {m : M | ∀ᶠ (m' : M) in ↑U, m * m' ∈ p.val} from p.val.inter_subset_right (exists_elem p.property).some_mem)⟩ use Stream'.corec elem succ (Subtype.mk s₀ sU) suffices ∀ (a : Stream' M), ∀ m ∈ FP a, ∀ p, a = Stream'.corec elem succ p → m ∈ p.val by intro m hm exact this _ m hm ⟨s₀, sU⟩ rfl clear sU s₀ intro a m h induction h with | head' b => rintro p rfl rw [Stream'.corec_eq, Stream'.head_cons] exact Set.inter_subset_left (Set.Nonempty.some_mem _) | tail' b n h ih => rintro p rfl refine Set.inter_subset_left (ih (succ p) ?_) rw [Stream'.corec_eq, Stream'.tail_cons] | cons' b n h ih => rintro p rfl have := Set.inter_subset_right (ih (succ p) ?_) · simpa only using this rw [Stream'.corec_eq, Stream'.tail_cons] /-- The strong form of **Hindman's theorem**: in any finite cover of an FP-set, one the parts contains an FP-set. -/ @[to_additive FS_partition_regular /-- The strong form of **Hindman's theorem**: in any finite cover of an FS-set, one the parts contains an FS-set. -/] theorem FP_partition_regular {M} [Semigroup M] (a : Stream' M) (s : Set (Set M)) (sfin : s.Finite) (scov : FP a ⊆ ⋃₀ s) : ∃ c ∈ s, ∃ b : Stream' M, FP b ⊆ c := let ⟨U, idem, aU⟩ := exists_idempotent_ultrafilter_le_FP a let ⟨c, cs, hc⟩ := (Ultrafilter.finite_sUnion_mem_iff sfin).mp (mem_of_superset aU scov) ⟨c, cs, exists_FP_of_large U idem c hc⟩ /-- The weak form of **Hindman's theorem**: in any finite cover of a nonempty semigroup, one of the parts contains an FP-set. -/ @[to_additive exists_FS_of_finite_cover /-- The weak form of **Hindman's theorem**: in any finite cover of a nonempty additive semigroup, one of the parts contains an FS-set. -/] theorem exists_FP_of_finite_cover {M} [Semigroup M] [Nonempty M] (s : Set (Set M)) (sfin : s.Finite) (scov : ⊤ ⊆ ⋃₀ s) : ∃ c ∈ s, ∃ a : Stream' M, FP a ⊆ c := let ⟨U, hU⟩ := exists_idempotent_of_compact_t2_of_continuous_mul_left (@Ultrafilter.continuous_mul_left M _) let ⟨c, c_s, hc⟩ := (Ultrafilter.finite_sUnion_mem_iff sfin).mp (mem_of_superset univ_mem scov) ⟨c, c_s, exists_FP_of_large U hU c hc⟩ @[to_additive FS_iter_tail_sub_FS] theorem FP_drop_subset_FP {M} [Semigroup M] (a : Stream' M) (n : ℕ) : FP (a.drop n) ⊆ FP a := by induction n with | zero => rfl | succ n ih => rw [← Stream'.drop_drop] exact _root_.trans (FP.tail _) ih @[to_additive] theorem FP.singleton {M} [Semigroup M] (a : Stream' M) (i : ℕ) : a.get i ∈ FP a := by induction i generalizing a with | zero => exact FP.head _ | succ i ih => exact FP.tail _ _ (ih _) @[to_additive] theorem FP.mul_two {M} [Semigroup M] (a : Stream' M) (i j : ℕ) (ij : i < j) : a.get i * a.get j ∈ FP a := by refine FP_drop_subset_FP _ i ?_ rw [← Stream'.head_drop] apply FP.cons rcases Nat.exists_eq_add_of_le (Nat.succ_le_of_lt ij) with ⟨d, hd⟩ have := FP.singleton (a.drop i).tail d rw [Stream'.tail_eq_drop, Stream'.get_drop, Stream'.get_drop] at this convert this cutsat @[to_additive] theorem FP.finset_prod {M} [CommMonoid M] (a : Stream' M) (s : Finset ℕ) (hs : s.Nonempty) : (s.prod fun i => a.get i) ∈ FP a := by refine FP_drop_subset_FP _ (s.min' hs) ?_ induction s using Finset.eraseInduction with | H s ih => _ rw [← Finset.mul_prod_erase _ _ (s.min'_mem hs), ← Stream'.head_drop] rcases (s.erase (s.min' hs)).eq_empty_or_nonempty with h | h · rw [h, Finset.prod_empty, mul_one] exact FP.head _ · apply FP.cons rw [Stream'.tail_eq_drop, Stream'.drop_drop, add_comm] refine Set.mem_of_subset_of_mem ?_ (ih _ (s.min'_mem hs) h) have : s.min' hs + 1 ≤ (s.erase (s.min' hs)).min' h := Nat.succ_le_of_lt (Finset.min'_lt_of_mem_erase_min' _ _ <| Finset.min'_mem _ _) obtain ⟨d, hd⟩ := Nat.exists_eq_add_of_le this rw [hd, ← Stream'.drop_drop, add_comm] apply FP_drop_subset_FP end Hindman
.lake/packages/mathlib/Mathlib/Combinatorics/Nullstellensatz.lean
import Mathlib.Algebra.MvPolynomial.Equiv import Mathlib.Algebra.Polynomial.Degree.Definitions import Mathlib.Data.Finsupp.MonomialOrder.DegLex import Mathlib.RingTheory.Ideal.Maps import Mathlib.RingTheory.MvPolynomial.Groebner import Mathlib.RingTheory.MvPolynomial.Homogeneous import Mathlib.RingTheory.MvPolynomial.MonomialOrder.DegLex /-! # Alon's Combinatorial Nullstellensatz This is a formalization of Noga Alon's Combinatorial Nullstellensatz. It follows [Alon_1999]. We consider a family `S : σ → Finset R` of finite subsets of a domain `R` and a multivariate polynomial `f` in `MvPolynomial σ R`. The combinatorial Nullstellensatz gives combinatorial constraints for the vanishing of `f` at any `x : σ → R` such that `x s ∈ S s` for all `s`. - `MvPolynomial.eq_zero_of_eval_zero_at_prod_finset` : if `f` vanishes at any such point and `f.degreeOf s < #(S s)` for all `s`, then `f = 0`. - `combinatorial_nullstellensatz_exists_linearCombination` If `f` vanishes at every such point, then it can be written as a linear combination `f = linearCombination (MvPolynomial σ R) (fun i ↦ ∏ r ∈ S i, (X i - C r)) h`, for some `h : σ →₀ MvPolynomial σ R` such that `((∏ r ∈ S s, (X i - C r)) * h i).totalDegree ≤ f.totalDegree` for all `s`. - `combinatorial_nullstellensatz_exists_eval_nonzero` a multi-index `t : σ →₀ ℕ` such that `t s < (S s).card` for all `s`, `f.totalDegree = t.degree` and `f.coeff t ≠ 0`, there exists a point `x : σ → R` such that `x s ∈ S s` for all `s` and `f.eval s ≠ 0`. ## TODO - Applications - relation with Schwartz–Zippel lemma, as in [Rote_2023] ## References - [Alon, *Combinatorial Nullstellensatz*][Alon_1999] - [Rote, *The Generalized Combinatorial Lason-Alon-Zippel-Schwartz Nullstellensatz Lemma*][Rote_2023] -/ open Finsupp open scoped Finset variable {R : Type*} [CommRing R] namespace MvPolynomial open Finsupp Function /-- A multivariate polynomial that vanishes on a large product finset is the zero polynomial. -/ theorem eq_zero_of_eval_zero_at_prod_finset {σ : Type*} [Finite σ] [IsDomain R] (P : MvPolynomial σ R) (S : σ → Finset R) (Hdeg : ∀ i, P.degreeOf i < #(S i)) (Heval : ∀ (x : σ → R), (∀ i, x i ∈ S i) → eval x P = 0) : P = 0 := by induction σ using Finite.induction_empty_option with | @of_equiv σ τ e h => suffices MvPolynomial.rename e.symm P = 0 by have that := MvPolynomial.rename_injective (R := R) e.symm (e.symm.injective) rw [RingHom.injective_iff_ker_eq_bot] at that rwa [← RingHom.mem_ker, that] at this apply h _ (fun i ↦ S (e i)) · intro i classical convert Hdeg (e i) conv_lhs => rw [← e.symm_apply_apply i, degreeOf_rename_of_injective e.symm.injective] · intro x hx simp only [MvPolynomial.eval_rename] apply Heval intro s simp only [Function.comp_apply] convert hx (e.symm s) simp only [Equiv.apply_symm_apply] | h_empty => suffices P = C (constantCoeff P) by specialize Heval default (fun i ↦ PEmpty.elim i) rw [this, eval_C] at Heval rw [this, Heval, C_0] ext m suffices m = 0 by simp [this, ← constantCoeff_eq] ext d; exact PEmpty.elim d | @h_option σ _ h => set Q := optionEquivLeft R σ P with hQ suffices Q = 0 by rw [← AlgEquiv.symm_apply_apply (optionEquivLeft R σ) P, ← hQ, this, map_zero] have Heval' (x : σ → R) (hx : ∀ i, x i ∈ S (some i)) : Polynomial.map (eval x) Q = 0 := by apply Polynomial.eq_zero_of_natDegree_lt_card_of_eval_eq_zero' _ (S none) · intro y hy rw [← optionEquivLeft_elim_eval] apply Heval simp only [Option.forall, Option.elim_none, hy, Option.elim_some, hx, implies_true, and_self] · apply lt_of_le_of_lt _ (Hdeg none) rw [Polynomial.natDegree_le_iff_coeff_eq_zero] intro d hd simp only [hQ] rw [MvPolynomial.coeff_eval_eq_eval_coeff] convert map_zero (MvPolynomial.eval x) ext m simp only [coeff_zero] set n := (embDomain Function.Embedding.some m).update none d with hn rw [eq_option_embedding_update_none_iff] at hn rw [← hn.1, ← hn.2, optionEquivLeft_coeff_coeff] by_contra hm apply not_le.mpr hd rw [MvPolynomial.degreeOf_eq_sup] rw [← ne_eq, ← MvPolynomial.mem_support_iff] at hm convert Finset.le_sup hm exact hn.1.symm ext m d simp only [Polynomial.coeff_zero, coeff_zero] suffices Q.coeff m = 0 by simp only [this, coeff_zero] apply h _ (fun i ↦ S (some i)) · intro i apply lt_of_le_of_lt _ (Hdeg (some i)) simp only [degreeOf_eq_sup, Finset.sup_le_iff, mem_support_iff, ne_eq] intro e he set n := (embDomain Function.Embedding.some e).update none m with hn rw [eq_option_embedding_update_none_iff] at hn rw [hQ, ← hn.1, ← hn.2, optionEquivLeft_coeff_coeff, ← ne_eq, ← MvPolynomial.mem_support_iff] at he convert Finset.le_sup he rw [← hn.2, some_apply] · intro x hx specialize Heval' x hx rw [Polynomial.ext_iff] at Heval' simpa only [Polynomial.coeff_map, Polynomial.coeff_zero] using Heval' m open MonomialOrder /- Here starts the actual proof of the combinatorial Nullstellensatz -/ variable {σ : Type*} /-- The polynomial in `X i` that vanishes at all elements of `S`. -/ private noncomputable def Alon.P (S : Finset R) (i : σ) : MvPolynomial σ R := ∏ r ∈ S, (X i - C r) /-- The degree of `Alon.P S i` with respect to `X i` is the cardinality of `S`, and `0` otherwise. -/ private theorem Alon.degree_P [Nontrivial R] (m : MonomialOrder σ) (S : Finset R) (i : σ) : m.degree (Alon.P S i) = single i #S := by simp only [P] rw [degree_prod_of_regular] · simp [Finset.sum_congr rfl (fun r _ ↦ m.degree_X_sub_C i r)] · intro r _ rw [m.monic_X_sub_C] exact isRegular_one /-- The leading coefficient of `Alon.P S i` is `1`. -/ private theorem Alon.monic_P [Nontrivial R] (m : MonomialOrder σ) (S : Finset R) (i : σ) : m.Monic (P S i) := Monic.prod (fun r _ ↦ m.monic_X_sub_C i r) /-- The support of `Alon.P S i` is the set of exponents of the form `single i e`, for `e ≤ S.card`. -/ private lemma Alon.of_mem_P_support {ι : Type*} (i : ι) (S : Finset R) (m : ι →₀ ℕ) (hm : m ∈ (Alon.P S i).support) : ∃ e ≤ S.card, m = single i e := by classical have hP : Alon.P S i = .rename (fun _ ↦ i) (Alon.P S ()) := by simp [Alon.P, map_prod] rw [hP, support_rename_of_injective (Function.injective_of_subsingleton _)] at hm simp only [Finset.mem_image, mem_support_iff, ne_eq] at hm obtain ⟨e, he, hm⟩ := hm haveI : Nontrivial R := nontrivial_of_ne _ _ he refine ⟨e (), ?_, ?_⟩ · suffices e ≼[lex] single () #S by simpa [MonomialOrder.lex_le_iff_of_unique] using this rw [← Alon.degree_P] apply MonomialOrder.le_degree rw [mem_support_iff] convert he · rw [← hm] ext j by_cases hj : j = i · rw [hj, mapDomain_apply (Function.injective_of_subsingleton _), single_eq_same] · rw [mapDomain_notin_range, single_eq_of_ne hj] simp [Set.range_const, Set.mem_singleton_iff, hj] variable [Finite σ] open scoped BigOperators /-- The **Combinatorial Nullstellensatz**. If `f` vanishes at every point `x : σ → R` such that `x s ∈ S s` for all `s`, then it can be written as a linear combination `f = linearCombination (MvPolynomial σ R) (fun i ↦ (∏ r ∈ S i, (X i - C r))) h`, for some `h : σ →₀ MvPolynomial σ R` such that `((∏ r ∈ S s, (X i - C r)) * h i).totalDegree ≤ f.totalDegree` for all `s`. [Alon_1999], theorem 1. -/ theorem combinatorial_nullstellensatz_exists_linearCombination [IsDomain R] (S : σ → Finset R) (Sne : ∀ i, (S i).Nonempty) (f : MvPolynomial σ R) (Heval : ∀ (x : σ → R), (∀ i, x i ∈ S i) → eval x f = 0) : ∃ (h : σ →₀ MvPolynomial σ R), (∀ i, ((∏ s ∈ S i, (X i - C s)) * h i).totalDegree ≤ f.totalDegree) ∧ f = linearCombination (MvPolynomial σ R) (fun i ↦ ∏ r ∈ S i, (X i - C r)) h := by letI : LinearOrder σ := WellOrderingRel.isWellOrder.linearOrder obtain ⟨h, r, hf, hh, hr⟩ := degLex.div (b := fun i ↦ Alon.P (S i) i) (fun i ↦ by simp only [(Alon.monic_P ..).leadingCoeff_eq_one, isUnit_one]) f use h suffices r = 0 by rw [this, add_zero] at hf exact ⟨fun i ↦ degLex_totalDegree_monotone (hh i), hf⟩ apply eq_zero_of_eval_zero_at_prod_finset r S · intro i rw [degreeOf_eq_sup, Finset.sup_lt_iff (by simp [Sne i])] intro c hc rw [← not_le] intro h' apply hr c hc i intro j rw [Alon.degree_P, single_apply] split_ifs with hj · rw [← hj] exact h' · exact zero_le _ · intro x hx rw [Iff.symm sub_eq_iff_eq_add'] at hf rw [← hf, map_sub, Heval x hx, zero_sub, neg_eq_zero, linearCombination_apply, map_finsuppSum, Finsupp.sum, Finset.sum_eq_zero] intro i _ rw [smul_eq_mul, map_mul] convert mul_zero _ rw [Alon.P, map_prod] apply Finset.prod_eq_zero (hx i) simp /-- The **Combinatorial Nullstellensatz**. Given a multi-index `t : σ →₀ ℕ` such that `t s < (S s).card` for all `s`, `f.totalDegree = t.degree` and `f.coeff t ≠ 0`, there exists a point `x : σ → R` such that `x s ∈ S s` for all `s` and `f.eval s ≠ 0`. [Alon_1999], theorem 2 -/ theorem combinatorial_nullstellensatz_exists_eval_nonzero [IsDomain R] (f : MvPolynomial σ R) (t : σ →₀ ℕ) (ht : f.coeff t ≠ 0) (ht' : f.totalDegree = t.degree) (S : σ → Finset R) (htS : ∀ i, t i < #(S i)) : ∃ s : σ → R, (∀ i, s i ∈ S i) ∧ eval s f ≠ 0 := by let _ : LinearOrder σ := WellOrderingRel.isWellOrder.linearOrder classical by_contra! Heval apply ht obtain ⟨h, hh, hf⟩ := combinatorial_nullstellensatz_exists_linearCombination S (fun i ↦ by rw [← Finset.card_pos]; exact Nat.zero_lt_of_lt (htS i)) f Heval rw [hf] rw [linearCombination_apply, Finsupp.sum, coeff_sum] apply Finset.sum_eq_zero intro i _ set g := h i * Alon.P (S i) i with hg by_cases hi : h i = 0 · simp [hi] have : g.totalDegree ≤ f.totalDegree := by rw [hg, mul_comm] exact hh i -- one could simplify this by proving `totalDegree_mul_eq` (at least in a domain) rw [hg, ← degree_degLexDegree, degree_mul_of_isRegular_right hi (by simp only [(Alon.monic_P ..).leadingCoeff_eq_one, isRegular_one]), Alon.degree_P, degree_add, degree_degLexDegree, degree_single, ht'] at this rw [smul_eq_mul, coeff_mul, Finset.sum_eq_zero] rintro ⟨p, q⟩ hpq simp only [Finset.mem_antidiagonal] at hpq simp only [mul_eq_zero, Classical.or_iff_not_imp_right] rw [← ne_eq, ← mem_support_iff] intro hq obtain ⟨e, hq', hq⟩ := Alon.of_mem_P_support _ _ _ hq apply coeff_eq_zero_of_totalDegree_lt rw [← Finsupp.degree] apply lt_of_add_lt_add_right (lt_of_le_of_lt this _) rw [← hpq, degree_add, add_lt_add_iff_left, hq, degree_single] apply lt_of_le_of_lt _ (htS i) simp [← hpq, hq] end MvPolynomial
.lake/packages/mathlib/Mathlib/Combinatorics/HalesJewett.lean
import Mathlib.Data.Fintype.Option import Mathlib.Data.Fintype.Shrink import Mathlib.Data.Fintype.Sum import Mathlib.Data.Finite.Prod import Mathlib.Algebra.BigOperators.Group.Finset.Basic /-! # The Hales-Jewett theorem We prove the Hales-Jewett theorem. We deduce Van der Waerden's theorem and the multidimensional Hales-Jewett theorem as corollaries. The Hales-Jewett theorem is a result in Ramsey theory dealing with *combinatorial lines*. Given an 'alphabet' `α : Type*` and `a b : α`, an example of a combinatorial line in `α^5` is `{ (a, x, x, b, x) | x : α }`. See `Combinatorics.Line` for a precise general definition. The Hales-Jewett theorem states that for any fixed finite types `α` and `κ`, there exists a (potentially huge) finite type `ι` such that whenever `ι → α` is `κ`-colored (i.e. for any coloring `C : (ι → α) → κ`), there exists a monochromatic line. We prove the Hales-Jewett theorem using the idea of *color focusing* and a *product argument*. See the proof of `Combinatorics.Line.exists_mono_in_high_dimension'` for details. *Combinatorial subspaces* are higher-dimensional analogues of combinatorial lines. See `Combinatorics.Subspace`. The multidimensional Hales-Jewett theorem generalises the statement above from combinatorial lines to combinatorial subspaces of a fixed dimension. The version of Van der Waerden's theorem in this file states that whenever a commutative monoid `M` is finitely colored and `S` is a finite subset, there exists a monochromatic homothetic copy of `S`. This follows from the Hales-Jewett theorem by considering the map `(ι → S) → M` sending `v` to `∑ i : ι, v i`, which sends a combinatorial line to a homothetic copy of `S`. ## Main results - `Combinatorics.Line.exists_mono_in_high_dimension`: The Hales-Jewett theorem. - `Combinatorics.Subspace.exists_mono_in_high_dimension`: The multidimensional Hales-Jewett theorem. - `Combinatorics.exists_mono_homothetic_copy`: A generalization of Van der Waerden's theorem. ## Implementation details For convenience, we work directly with finite types instead of natural numbers. That is, we write `α, ι, κ` for (finite) types where one might traditionally use natural numbers `n, H, c`. This allows us to work directly with `α`, `Option α`, `(ι → α) → κ`, and `ι ⊕ ι'` instead of `Fin n`, `Fin (n+1)`, `Fin (c^(n^H))`, and `Fin (H + H')`. ## TODO - Prove a finitary version of Van der Waerden's theorem (either by compactness or by modifying the current proof). - One could reformulate the proof of Hales-Jewett to give explicit upper bounds on the number of coordinates needed. ## Tags combinatorial line, Ramsey theory, arithmetic progression ### References * https://en.wikipedia.org/wiki/Hales%E2%80%93Jewett_theorem -/ open Function open scoped Finset universe u v variable {η α ι κ : Type*} namespace Combinatorics /-- The type of combinatorial subspaces. A subspace `l : Subspace η α ι` in the hypercube `ι → α` defines a function `(η → α) → ι → α` from `η → α` to the hypercube, such that for each coordinate `i : ι` and direction `e : η`, the function `fun x ↦ l x i` is either `fun x ↦ x e` for some direction `e : η` or constant. We require subspaces to be non-degenerate in the sense that, for every `e : η`, `fun x ↦ l x i` is `fun x ↦ x e` for at least one `i`. Formally, a subspace is represented by a word `l.idxFun : ι → α ⊕ η` which says whether `fun x ↦ l x i` is `fun x ↦ x e` (corresponding to `l.idxFun i = Sum.inr e`) or constantly `a` (corresponding to `l.idxFun i = Sum.inl a`). When `α` has size `1` there can be many elements of `Subspace η α ι` defining the same function. -/ @[ext] structure Subspace (η α ι : Type*) where /-- The word representing a combinatorial subspace. `l.idxfun i = Sum.inr e` means that `l x i = x e` for all `x` and `l.idxfun i = some a` means that `l x i = a` for all `x`. -/ idxFun : ι → α ⊕ η /-- We require combinatorial subspaces to be nontrivial in the sense that `fun x ↦ l x i` is `fun x ↦ x e` for at least one coordinate `i`. -/ proper : ∀ e, ∃ i, idxFun i = Sum.inr e namespace Subspace variable {η α ι κ : Type*} {l : Subspace η α ι} {x : η → α} {i : ι} {a : α} {e : η} /-- The combinatorial subspace corresponding to the identity embedding `(ι → α) → (ι → α)`. -/ instance : Inhabited (Subspace ι α ι) := ⟨⟨Sum.inr, fun i ↦ ⟨i, rfl⟩⟩⟩ /-- Consider a subspace `l : Subspace η α ι` as a function `(η → α) → ι → α`. -/ @[coe] def toFun (l : Subspace η α ι) (x : η → α) (i : ι) : α := (l.idxFun i).elim id x instance instCoeFun : CoeFun (Subspace η α ι) (fun _ ↦ (η → α) → ι → α) := ⟨toFun⟩ lemma coe_apply (l : Subspace η α ι) (x : η → α) (i : ι) : l x i = (l.idxFun i).elim id x := rfl -- Note: This is not made a `FunLike` instance to avoid having two syntactically different coercions lemma coe_injective [Nontrivial α] : Injective ((⇑) : Subspace η α ι → (η → α) → ι → α) := by classical rintro l m hlm ext i simp only [funext_iff] at hlm cases hl : idxFun l i with | inl a => obtain ⟨b, hba⟩ := exists_ne a cases hm : idxFun m i <;> simpa [hl, hm, hba.symm, coe_apply] using hlm (const _ b) i | inr e => cases hm : idxFun m i with | inl a => obtain ⟨b, hba⟩ := exists_ne a simpa [hl, hm, hba, coe_apply] using hlm (const _ b) i | inr f => obtain ⟨a, b, hab⟩ := exists_pair_ne α simp only [Sum.inr.injEq] by_contra! hef simpa [hl, hm, hef, hab, coe_apply] using hlm (Function.update (const _ a) f b) i lemma apply_def (l : Subspace η α ι) (x : η → α) (i : ι) : l x i = (l.idxFun i).elim id x := rfl lemma apply_inl (h : l.idxFun i = Sum.inl a) : l x i = a := by simp [apply_def, h] lemma apply_inr (h : l.idxFun i = Sum.inr e) : l x i = x e := by simp [apply_def, h] /-- Given a coloring `C` of `ι → α` and a combinatorial subspace `l` of `ι → α`, `l.IsMono C` means that `l` is monochromatic with regard to `C`. -/ def IsMono (C : (ι → α) → κ) (l : Subspace η α ι) : Prop := ∃ c, ∀ x, C (l x) = c variable {η' α' ι' : Type*} /-- Change the index types of a subspace. -/ def reindex (l : Subspace η α ι) (eη : η ≃ η') (eα : α ≃ α') (eι : ι ≃ ι') : Subspace η' α' ι' where idxFun i := (l.idxFun <| eι.symm i).map eα eη proper e := (eι.exists_congr fun i ↦ by cases h : idxFun l i <;> simp [*, Equiv.eq_symm_apply]).1 <| l.proper <| eη.symm e @[simp] lemma reindex_apply (l : Subspace η α ι) (eη : η ≃ η') (eα : α ≃ α') (eι : ι ≃ ι') (x i) : l.reindex eη eα eι x i = eα (l (eα.symm ∘ x ∘ eη) <| eι.symm i) := by cases h : l.idxFun (eι.symm i) <;> simp [h, reindex, coe_apply] @[simp] lemma reindex_isMono {eη : η ≃ η'} {eα : α ≃ α'} {eι : ι ≃ ι'} {C : (ι' → α') → κ} : (l.reindex eη eα eι).IsMono C ↔ l.IsMono fun x ↦ C <| eα ∘ x ∘ eι.symm := by simp only [IsMono, funext (reindex_apply _ _ _ _ _), coe_apply] exact exists_congr fun c ↦ (eη.arrowCongr eα).symm.forall_congr <| by aesop protected lemma IsMono.reindex {eη : η ≃ η'} {eα : α ≃ α'} {eι : ι ≃ ι'} {C : (ι → α) → κ} (hl : l.IsMono C) : (l.reindex eη eα eι).IsMono fun x ↦ C <| eα.symm ∘ x ∘ eι := by simp [reindex_isMono, Function.comp_assoc]; simpa [← Function.comp_assoc] end Subspace /-- The type of combinatorial lines. A line `l : Line α ι` in the hypercube `ι → α` defines a function `α → ι → α` from `α` to the hypercube, such that for each coordinate `i : ι`, the function `fun x ↦ l x i` is either `id` or constant. We require lines to be nontrivial in the sense that `fun x ↦ l x i` is `id` for at least one `i`. Formally, a line is represented by a word `l.idxFun : ι → Option α` which says whether `fun x ↦ l x i` is `id` (corresponding to `l.idxFun i = none`) or constantly `y` (corresponding to `l.idxFun i = some y`). When `α` has size `1` there can be many elements of `Line α ι` defining the same function. -/ @[ext] structure Line (α ι : Type*) where /-- The word representing a combinatorial line. `l.idxfun i = none` means that `l x i = x` for all `x` and `l.idxfun i = some y` means that `l x i = y`. -/ idxFun : ι → Option α /-- We require combinatorial lines to be nontrivial in the sense that `fun x ↦ l x i` is `id` for at least one coordinate `i`. -/ proper : ∃ i, idxFun i = none namespace Line variable {l : Line α ι} {i : ι} {a x : α} /-- Consider a line `l : Line α ι` as a function `α → ι → α`. -/ @[coe] def toFun (l : Line α ι) (x : α) (i : ι) : α := (l.idxFun i).getD x -- This lets us treat a line `l : Line α ι` as a function `α → ι → α`. instance instCoeFun : CoeFun (Line α ι) fun _ => α → ι → α := ⟨toFun⟩ @[simp] lemma coe_apply (l : Line α ι) (x : α) (i : ι) : l x i = (l.idxFun i).getD x := rfl -- Note: This is not made a `FunLike` instance to avoid having two syntactically different coercions lemma coe_injective [Nontrivial α] : Injective ((⇑) : Line α ι → α → ι → α) := by rintro l m hlm ext i a obtain ⟨b, hba⟩ := exists_ne a simp only [funext_iff] at hlm ⊢ refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · cases hi : idxFun m i <;> simpa [@eq_comm _ a, hi, h, hba] using hlm b i · cases hi : idxFun l i <;> simpa [@eq_comm _ a, hi, h, hba] using hlm b i /-- A line is monochromatic if all its points are the same color. -/ def IsMono {α ι κ} (C : (ι → α) → κ) (l : Line α ι) : Prop := ∃ c, ∀ x, C (l x) = c /-- Consider a line as a one-dimensional subspace. -/ def toSubspaceUnit (l : Line α ι) : Subspace Unit α ι where idxFun i := (l.idxFun i).elim (.inr ()) .inl proper _ := l.proper.imp fun i hi ↦ by simp [hi] @[simp] lemma toSubspaceUnit_apply (l : Line α ι) (a) : ⇑l.toSubspaceUnit a = l (a ()) := by ext i; cases h : l.idxFun i <;> simp [toSubspaceUnit, h, Subspace.coe_apply] @[simp] lemma toSubspaceUnit_isMono {C : (ι → α) → κ} : l.toSubspaceUnit.IsMono C ↔ l.IsMono C := by simp only [Subspace.IsMono, toSubspaceUnit_apply, IsMono] exact exists_congr fun c ↦ ⟨fun h a ↦ h fun _ ↦ a, fun h a ↦ h _⟩ protected alias ⟨_, IsMono.toSubspaceUnit⟩ := toSubspaceUnit_isMono /-- Consider a line in `ι → η → α` as a `η`-dimensional subspace in `ι × η → α`. -/ def toSubspace (l : Line (η → α) ι) : Subspace η α (ι × η) where idxFun ie := (l.idxFun ie.1).elim (.inr ie.2) (fun f ↦ .inl <| f ie.2) proper e := let ⟨i, hi⟩ := l.proper; ⟨(i, e), by simp [hi]⟩ @[simp] lemma toSubspace_apply (l : Line (η → α) ι) (a ie) : ⇑l.toSubspace a ie = l a ie.1 ie.2 := by cases h : l.idxFun ie.1 <;> simp [toSubspace, h, coe_apply, Subspace.coe_apply] @[simp] lemma toSubspace_isMono {l : Line (η → α) ι} {C : (ι × η → α) → κ} : l.toSubspace.IsMono C ↔ l.IsMono fun x : ι → η → α ↦ C fun (i, e) ↦ x i e := by simp [Subspace.IsMono, IsMono, funext (toSubspace_apply _ _)] protected alias ⟨_, IsMono.toSubspace⟩ := toSubspace_isMono /-- The diagonal line. It is the identity at every coordinate. -/ def diagonal (α ι) [Nonempty ι] : Line α ι where idxFun _ := none proper := ⟨Classical.arbitrary ι, rfl⟩ instance (α ι) [Nonempty ι] : Inhabited (Line α ι) := ⟨diagonal α ι⟩ /-- The type of lines that are only one color except possibly at their endpoints. -/ structure AlmostMono {α ι κ : Type*} (C : (ι → Option α) → κ) where /-- The underlying line of an almost monochromatic line, where the coordinate dimension `α` is extended by an additional symbol `none`, thought to be marking the endpoint of the line. -/ line : Line (Option α) ι /-- The main color of an almost monochromatic line. -/ color : κ /-- The proposition that the underlying line of an almost monochromatic line assumes its main color except possibly at the endpoints. -/ has_color : ∀ x : α, C (line (some x)) = color instance {α ι κ : Type*} [Nonempty ι] [Inhabited κ] : Inhabited (AlmostMono fun _ : ι → Option α => (default : κ)) := ⟨{ line := default color := default has_color := fun _ ↦ rfl}⟩ /-- The type of collections of lines such that - each line is only one color except possibly at its endpoint - the lines all have the same endpoint - the colors of the lines are distinct. Used in the proof `exists_mono_in_high_dimension`. -/ structure ColorFocused {α ι κ : Type*} (C : (ι → Option α) → κ) where /-- The underlying multiset of almost monochromatic lines of a color-focused collection. -/ lines : Multiset (AlmostMono C) /-- The common endpoint of the lines in the color-focused collection. -/ focus : ι → Option α /-- The proposition that all lines in a color-focused collection have the same endpoint. -/ is_focused : ∀ p ∈ lines, p.line none = focus /-- The proposition that all lines in a color-focused collection of lines have distinct colors. -/ distinct_colors : (lines.map AlmostMono.color).Nodup instance {α ι κ} (C : (ι → Option α) → κ) : Inhabited (ColorFocused C) := by refine ⟨⟨0, fun _ => none, fun h => ?_, Multiset.nodup_zero⟩⟩ simp only [Multiset.notMem_zero, IsEmpty.forall_iff] /-- A function `f : α → α'` determines a function `line α ι → line α' ι`. For a coordinate `i` `l.map f` is the identity at `i` if `l` is, and constantly `f y` if `l` is constantly `y` at `i`. -/ def map {α α' ι} (f : α → α') (l : Line α ι) : Line α' ι where idxFun i := (l.idxFun i).map f proper := ⟨l.proper.choose, by simp only [l.proper.choose_spec, Option.map_none]⟩ /-- A point in `ι → α` and a line in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def vertical {α ι ι'} (v : ι → α) (l : Line α ι') : Line α (ι ⊕ ι') where idxFun := Sum.elim (some ∘ v) l.idxFun proper := ⟨Sum.inr l.proper.choose, l.proper.choose_spec⟩ /-- A line in `ι → α` and a point in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def horizontal {α ι ι'} (l : Line α ι) (v : ι' → α) : Line α (ι ⊕ ι') where idxFun := Sum.elim l.idxFun (some ∘ v) proper := ⟨Sum.inl l.proper.choose, l.proper.choose_spec⟩ /-- One line in `ι → α` and one in `ι' → α` together determine a line in `ι ⊕ ι' → α`. -/ def prod {α ι ι'} (l : Line α ι) (l' : Line α ι') : Line α (ι ⊕ ι') where idxFun := Sum.elim l.idxFun l'.idxFun proper := ⟨Sum.inl l.proper.choose, l.proper.choose_spec⟩ theorem apply_def (l : Line α ι) (x : α) : l x = fun i => (l.idxFun i).getD x := rfl theorem apply_none {α ι} (l : Line α ι) (x : α) (i : ι) (h : l.idxFun i = none) : l x i = x := by simp only [Option.getD_none, h, l.apply_def] lemma apply_some (h : l.idxFun i = some a) : l x i = a := by simp [h] @[simp] theorem map_apply {α α' ι} (f : α → α') (l : Line α ι) (x : α) : l.map f (f x) = f ∘ l x := by simp only [Line.apply_def, Line.map, Option.getD_map, comp_def] @[simp] theorem vertical_apply {α ι ι'} (v : ι → α) (l : Line α ι') (x : α) : l.vertical v x = Sum.elim v (l x) := by funext i cases i <;> rfl @[simp] theorem horizontal_apply {α ι ι'} (l : Line α ι) (v : ι' → α) (x : α) : l.horizontal v x = Sum.elim (l x) v := by funext i cases i <;> rfl @[simp] theorem prod_apply {α ι ι'} (l : Line α ι) (l' : Line α ι') (x : α) : l.prod l' x = Sum.elim (l x) (l' x) := by funext i cases i <;> rfl @[simp] theorem diagonal_apply {α ι} [Nonempty ι] (x : α) : diagonal α ι x = fun _ => x := by ext; simp [diagonal] /-- The **Hales-Jewett theorem**. This version has a restriction on universe levels which is necessary for the proof. See `exists_mono_in_high_dimension` for a fully universe-polymorphic version. -/ private theorem exists_mono_in_high_dimension' : ∀ (α : Type u) [Finite α] (κ : Type max v u) [Finite κ], ∃ (ι : Type) (_ : Fintype ι), ∀ C : (ι → α) → κ, ∃ l : Line α ι, l.IsMono C := -- The proof proceeds by induction on `α`. Finite.induction_empty_option (-- We have to show that the theorem is invariant under `α ≃ α'` for the induction to work. fun {α α'} e => forall_imp fun κ => forall_imp fun _ => Exists.imp fun ι => Exists.imp fun _ h C => let ⟨l, c, lc⟩ := h fun v => C (e ∘ v) ⟨l.map e, c, e.forall_congr_right.mp fun x => by rw [← lc x, Line.map_apply]⟩) (by -- This deals with the degenerate case where `α` is empty. intro κ _ by_cases h : Nonempty κ · refine ⟨Unit, inferInstance, fun C => ⟨default, Classical.arbitrary _, PEmpty.rec⟩⟩ · exact ⟨Empty, inferInstance, fun C => (h ⟨C (Empty.rec)⟩).elim⟩) (by -- Now we have to show that the theorem holds for `Option α` if it holds for `α`. intro α _ ihα κ _ cases nonempty_fintype κ -- Later we'll need `α` to be nonempty. So we first deal with the trivial case where `α` is -- empty. -- Then `Option α` has only one element, so any line is monochromatic. by_cases h : Nonempty α case neg => refine ⟨Unit, inferInstance, fun C => ⟨diagonal _ Unit, C fun _ => none, ?_⟩⟩ rintro (_ | ⟨a⟩) · rfl · exact (h ⟨a⟩).elim -- The key idea is to show that for every `r`, in high dimension we can either find -- `r` color focused lines or a monochromatic line. suffices key : ∀ r : ℕ, ∃ (ι : Type) (_ : Fintype ι), ∀ C : (ι → Option α) → κ, (∃ s : ColorFocused C, Multiset.card s.lines = r) ∨ ∃ l, IsMono C l by -- Given the key claim, we simply take `r = |κ| + 1`. We cannot have this many distinct colors -- so we must be in the second case, where there is a monochromatic line. obtain ⟨ι, _inst, hι⟩ := key (Fintype.card κ + 1) refine ⟨ι, _inst, fun C => (hι C).resolve_left ?_⟩ rintro ⟨s, sr⟩ apply Nat.not_succ_le_self (Fintype.card κ) rw [← Nat.add_one, ← sr, ← Multiset.card_map, ← Finset.card_mk] exact Finset.card_le_univ ⟨_, s.distinct_colors⟩ -- We now prove the key claim, by induction on `r`. intro r induction r with -- The base case `r = 0` is trivial as the empty collection is color-focused. | zero => exact ⟨Empty, inferInstance, fun C => Or.inl ⟨default, Multiset.card_zero⟩⟩ | succ r ihr => -- Supposing the key claim holds for `r`, we need to show it for `r+1`. First pick a high -- enough dimension `ι` for `r`. obtain ⟨ι, _inst, hι⟩ := ihr -- Then since the theorem holds for `α` with any number of colors, pick a dimension `ι'` such -- that `ι' → α` always has a monochromatic line whenever it is `(ι → Option α) → κ`-colored. specialize ihα ((ι → Option α) → κ) obtain ⟨ι', _inst, hι'⟩ := ihα -- We claim that `ι ⊕ ι'` works for `Option α` and `κ`-coloring. refine ⟨ι ⊕ ι', inferInstance, ?_⟩ intro C -- A `κ`-coloring of `ι ⊕ ι' → Option α` induces an `(ι → Option α) → κ`-coloring of `ι' → α`. specialize hι' fun v' v => C (Sum.elim v (some ∘ v')) -- By choice of `ι'` this coloring has a monochromatic line `l'` with color class `C'`, where -- `C'` is a `κ`-coloring of `ι → α`. obtain ⟨l', C', hl'⟩ := hι' -- If `C'` has a monochromatic line, then so does `C`. We use this in two places below. have mono_of_mono : (∃ l, IsMono C' l) → ∃ l, IsMono C l := by rintro ⟨l, c, hl⟩ refine ⟨l.horizontal (some ∘ l' (Classical.arbitrary α)), c, fun x => ?_⟩ rw [Line.horizontal_apply, ← hl, ← hl'] -- By choice of `ι`, `C'` either has `r` color-focused lines or a monochromatic line. specialize hι C' rcases hι with (⟨s, sr⟩ | h) on_goal 2 => exact Or.inr (mono_of_mono h) -- Here we assume `C'` has `r` color focused lines. We split into cases depending on whether -- one of these `r` lines has the same color as the focus point. by_cases h : ∃ p ∈ s.lines, (p : AlmostMono _).color = C' s.focus -- If so then this is a `C'`-monochromatic line and we are done. · obtain ⟨p, p_mem, hp⟩ := h refine Or.inr (mono_of_mono ⟨p.line, p.color, ?_⟩) rintro (_ | _) · rw [hp, s.is_focused p p_mem] · apply p.has_color -- If not, we get `r+1` color focused lines by taking the product of the `r` lines with `l'` -- and adding to this the vertical line obtained by the focus point and `l`. refine Or.inl ⟨⟨(s.lines.map ?_).cons ⟨(l'.map some).vertical s.focus, C' s.focus, fun x => ?_⟩, Sum.elim s.focus (l'.map some none), ?_, ?_⟩, ?_⟩ -- The product lines are almost monochromatic. · refine fun p => ⟨p.line.prod (l'.map some), p.color, fun x => ?_⟩ rw [Line.prod_apply, Line.map_apply, ← p.has_color, ← congr_fun (hl' x)] -- The vertical line is almost monochromatic. · rw [vertical_apply, ← congr_fun (hl' x), Line.map_apply] -- Our `r+1` lines have the same endpoint. · simp_rw [Multiset.mem_cons, Multiset.mem_map] rintro _ (rfl | ⟨q, hq, rfl⟩) · simp only [vertical_apply] · simp only [prod_apply, s.is_focused q hq] -- Our `r+1` lines have distinct colors (this is why we needed to split into cases above). · rw [Multiset.map_cons, Multiset.map_map, Multiset.nodup_cons, Multiset.mem_map] exact ⟨h, s.distinct_colors⟩ -- Finally, we really do have `r+1` lines! · rw [Multiset.card_cons, Multiset.card_map, sr]) /-- The **Hales-Jewett theorem**: For any finite types `α` and `κ`, there exists a finite type `ι` such that whenever the hypercube `ι → α` is `κ`-colored, there is a monochromatic combinatorial line. -/ theorem exists_mono_in_high_dimension (α : Type u) [Finite α] (κ : Type v) [Finite κ] : ∃ (ι : Type) (_ : Fintype ι), ∀ C : (ι → α) → κ, ∃ l : Line α ι, l.IsMono C := let ⟨ι, ιfin, hι⟩ := exists_mono_in_high_dimension'.{u,v} α (ULift.{u,v} κ) ⟨ι, ιfin, fun C => let ⟨l, c, hc⟩ := hι (ULift.up ∘ C) ⟨l, c.down, fun x => by rw [← hc x, Function.comp_apply]⟩⟩ end Line /-- A generalization of Van der Waerden's theorem: if `M` is a finitely colored commutative monoid, and `S` is a finite subset, then there exists a monochromatic homothetic copy of `S`. -/ theorem exists_mono_homothetic_copy {M κ : Type*} [AddCommMonoid M] (S : Finset M) [Finite κ] (C : M → κ) : ∃ a > 0, ∃ (b : M) (c : κ), ∀ s ∈ S, C (a • s + b) = c := by classical obtain ⟨ι, _inst, hι⟩ := Line.exists_mono_in_high_dimension S κ specialize hι fun v => C <| ∑ i, v i obtain ⟨l, c, hl⟩ := hι set s : Finset ι := {i | l.idxFun i = none} with hs refine ⟨#s, Finset.card_pos.mpr ⟨l.proper.choose, ?_⟩, ∑ i ∈ sᶜ, ((l.idxFun i).map ?_).getD 0, c, ?_⟩ · rw [hs, Finset.mem_filter] exact ⟨Finset.mem_univ _, l.proper.choose_spec⟩ · exact fun m => m intro x xs rw [← hl ⟨x, xs⟩] clear hl; congr rw [← Finset.sum_add_sum_compl s] congr 1 · rw [← Finset.sum_const] apply Finset.sum_congr rfl intro i hi rw [hs, Finset.mem_filter] at hi rw [l.apply_none _ _ hi.right, Subtype.coe_mk] · apply Finset.sum_congr rfl intro i hi rw [hs, Finset.compl_filter, Finset.mem_filter] at hi obtain ⟨y, hy⟩ := Option.ne_none_iff_exists.mp hi.right simp [← hy, Option.map_some, Option.getD] namespace Subspace /-- The **multidimensional Hales-Jewett theorem**, aka **extended Hales-Jewett theorem**: For any finite types `η`, `α` and `κ`, there exists a finite type `ι` such that whenever the hypercube `ι → α` is `κ`-colored, there is a monochromatic combinatorial subspace of dimension `η`. -/ theorem exists_mono_in_high_dimension (α κ η) [Finite α] [Finite κ] [Finite η] : ∃ (ι : Type) (_ : Fintype ι), ∀ C : (ι → α) → κ, ∃ l : Subspace η α ι, l.IsMono C := by cases nonempty_fintype η obtain ⟨ι, _, hι⟩ := Line.exists_mono_in_high_dimension (Shrink.{0} η → α) κ refine ⟨ι × Shrink η, inferInstance, fun C ↦ ?_⟩ obtain ⟨l, hl⟩ := hι fun x ↦ C fun (i, e) ↦ x i e refine ⟨l.toSubspace.reindex (equivShrink.{0} η).symm (Equiv.refl _) (Equiv.refl _), ?_⟩ convert hl.toSubspace.reindex simp /-- A variant of the **extended Hales-Jewett theorem** `exists_mono_in_high_dimension` where the returned type is some `Fin n` instead of a general fintype. -/ theorem exists_mono_in_high_dimension_fin (α κ η) [Finite α] [Finite κ] [Finite η] : ∃ n, ∀ C : (Fin n → α) → κ, ∃ l : Subspace η α (Fin n), l.IsMono C := by obtain ⟨ι, ιfin, hι⟩ := exists_mono_in_high_dimension α κ η refine ⟨Fintype.card ι, fun C ↦ ?_⟩ obtain ⟨l, c, cl⟩ := hι fun v ↦ C (v ∘ (Fintype.equivFin _).symm) refine ⟨⟨l.idxFun ∘ (Fintype.equivFin _).symm, fun e ↦ ?_⟩, c, cl⟩ obtain ⟨i, hi⟩ := l.proper e use Fintype.equivFin _ i simpa using hi end Subspace end Combinatorics
.lake/packages/mathlib/Mathlib/Combinatorics/Schnirelmann.lean
import Mathlib.Algebra.Order.Ring.Abs import Mathlib.Data.Nat.ModEq import Mathlib.Data.Nat.Prime.Defs import Mathlib.Data.Real.Archimedean import Mathlib.Order.Interval.Finset.Nat /-! # Schnirelmann density We define the Schnirelmann density of a set `A` of natural numbers as $inf_{n > 0} |A ∩ {1,...,n}| / n$. As this density is very sensitive to changes in small values, we must exclude `0` from the infimum, and from the intersection. ## Main statements * Simple bounds on the Schnirelmann density, that it is between 0 and 1 are given in `schnirelmannDensity_nonneg` and `schnirelmannDensity_le_one`. * `schnirelmannDensity_le_of_notMem`: If `k ∉ A`, the density can be easily upper-bounded by `1 - k⁻¹` ## Implementation notes Despite the definition being noncomputable, we include a decidable instance argument, since this makes the definition easier to use in explicit cases. Further, we use `Finset.Ioc` rather than a set intersection since the set is finite by construction, which reduces the proof obligations later that would arise with `Nat.card`. ## TODO * Give other calculations of the density, for example powers and their sumsets. * Define other densities like the lower and upper asymptotic density, and the natural density, and show how these relate to the Schnirelmann density. * Show that if the sum of two densities is at least one, the sumset covers the positive naturals. * Prove Schnirelmann's theorem and Mann's theorem on the subadditivity of this density. ## References * [Ruzsa, Imre, *Sumsets and structure*][ruzsa2009] -/ open Finset /-- The Schnirelmann density is defined as the infimum of |A ∩ {1, ..., n}| / n as n ranges over the positive naturals. -/ noncomputable def schnirelmannDensity (A : Set ℕ) [DecidablePred (· ∈ A)] : ℝ := ⨅ n : {n : ℕ // 0 < n}, #{a ∈ Ioc 0 n | a ∈ A} / n section variable {A : Set ℕ} [DecidablePred (· ∈ A)] lemma schnirelmannDensity_nonneg : 0 ≤ schnirelmannDensity A := Real.iInf_nonneg (fun _ => by positivity) lemma schnirelmannDensity_le_div {n : ℕ} (hn : n ≠ 0) : schnirelmannDensity A ≤ #{a ∈ Ioc 0 n | a ∈ A} / n := ciInf_le ⟨0, fun _ ⟨_, hx⟩ => hx ▸ by positivity⟩ (⟨n, hn.bot_lt⟩ : {n : ℕ // 0 < n}) /-- For any natural `n`, the Schnirelmann density multiplied by `n` is bounded by `|A ∩ {1, ..., n}|`. Note this property fails for the natural density. -/ lemma schnirelmannDensity_mul_le_card_filter {n : ℕ} : schnirelmannDensity A * n ≤ #{a ∈ Ioc 0 n | a ∈ A} := by rcases eq_or_ne n 0 with rfl | hn · simp exact (le_div_iff₀ (by positivity)).1 (schnirelmannDensity_le_div hn) /-- To show the Schnirelmann density is upper bounded by `x`, it suffices to show `|A ∩ {1, ..., n}| / n ≤ x`, for any chosen positive value of `n`. We provide `n` explicitly here to make this lemma more easily usable in `apply` or `refine`. This lemma is analogous to `ciInf_le_of_le`. -/ lemma schnirelmannDensity_le_of_le {x : ℝ} (n : ℕ) (hn : n ≠ 0) (hx : #{a ∈ Ioc 0 n | a ∈ A} / n ≤ x) : schnirelmannDensity A ≤ x := (schnirelmannDensity_le_div hn).trans hx lemma schnirelmannDensity_le_one : schnirelmannDensity A ≤ 1 := schnirelmannDensity_le_of_le 1 one_ne_zero <| by rw [Nat.cast_one, div_one, Nat.cast_le_one]; exact card_filter_le _ _ /-- If `k` is omitted from the set, its Schnirelmann density is upper bounded by `1 - k⁻¹`. -/ lemma schnirelmannDensity_le_of_notMem {k : ℕ} (hk : k ∉ A) : schnirelmannDensity A ≤ 1 - (k⁻¹ : ℝ) := by rcases k.eq_zero_or_pos with rfl | hk' · simpa using schnirelmannDensity_le_one apply schnirelmannDensity_le_of_le k hk'.ne' rw [← one_div, one_sub_div (Nat.cast_pos.2 hk').ne'] gcongr rw [← Nat.cast_pred hk', Nat.cast_le] suffices {a ∈ Ioc 0 k | a ∈ A} ⊆ Ioo 0 k from (card_le_card this).trans_eq (by simp) rw [← Ioo_insert_right hk', filter_insert, if_neg hk] exact filter_subset _ _ @[deprecated (since := "2025-05-23")] alias schnirelmannDensity_le_of_not_mem := schnirelmannDensity_le_of_notMem /-- The Schnirelmann density of a set not containing `1` is `0`. -/ lemma schnirelmannDensity_eq_zero_of_one_notMem (h : 1 ∉ A) : schnirelmannDensity A = 0 := ((schnirelmannDensity_le_of_notMem h).trans (by simp)).antisymm schnirelmannDensity_nonneg @[deprecated (since := "2025-05-23")] alias schnirelmannDensity_eq_zero_of_one_not_mem := schnirelmannDensity_eq_zero_of_one_notMem /-- The Schnirelmann density is increasing with the set. -/ lemma schnirelmannDensity_le_of_subset {B : Set ℕ} [DecidablePred (· ∈ B)] (h : A ⊆ B) : schnirelmannDensity A ≤ schnirelmannDensity B := ciInf_mono ⟨0, fun _ ⟨_, hx⟩ ↦ hx ▸ by positivity⟩ fun _ ↦ by gcongr /-- The Schnirelmann density of `A` is `1` if and only if `A` contains all the positive naturals. -/ lemma schnirelmannDensity_eq_one_iff : schnirelmannDensity A = 1 ↔ {0}ᶜ ⊆ A := by rw [le_antisymm_iff, and_iff_right schnirelmannDensity_le_one] constructor · rw [← not_imp_not, not_le] simp only [Set.not_subset, forall_exists_index, and_imp] intro x hx hx' apply (schnirelmannDensity_le_of_notMem hx').trans_lt simpa only [one_div, sub_lt_self_iff, inv_pos, Nat.cast_pos, pos_iff_ne_zero] using hx · intro h refine le_ciInf fun ⟨n, hn⟩ => ?_ rw [one_le_div (Nat.cast_pos.2 hn), Nat.cast_le, filter_true_of_mem, Nat.card_Ioc, Nat.sub_zero] rintro x hx exact h (mem_Ioc.1 hx).1.ne' /-- The Schnirelmann density of `A` containing `0` is `1` if and only if `A` is the naturals. -/ lemma schnirelmannDensity_eq_one_iff_of_zero_mem (hA : 0 ∈ A) : schnirelmannDensity A = 1 ↔ A = Set.univ := by rw [schnirelmannDensity_eq_one_iff] constructor · refine fun h => Set.eq_univ_of_forall fun x => ?_ rcases eq_or_ne x 0 with rfl | hx · exact hA · exact h hx · rintro rfl exact Set.subset_univ {0}ᶜ lemma le_schnirelmannDensity_iff {x : ℝ} : x ≤ schnirelmannDensity A ↔ ∀ n : ℕ, 0 < n → x ≤ #{a ∈ Ioc 0 n | a ∈ A} / n := (le_ciInf_iff ⟨0, fun _ ⟨_, hx⟩ => hx ▸ by positivity⟩).trans Subtype.forall lemma schnirelmannDensity_lt_iff {x : ℝ} : schnirelmannDensity A < x ↔ ∃ n : ℕ, 0 < n ∧ #{a ∈ Ioc 0 n | a ∈ A} / n < x := by rw [← not_le, le_schnirelmannDensity_iff]; simp lemma schnirelmannDensity_le_iff_forall {x : ℝ} : schnirelmannDensity A ≤ x ↔ ∀ ε : ℝ, 0 < ε → ∃ n : ℕ, 0 < n ∧ #{a ∈ Ioc 0 n | a ∈ A} / n < x + ε := by rw [le_iff_forall_pos_lt_add] simp only [schnirelmannDensity_lt_iff] lemma schnirelmannDensity_congr' {B : Set ℕ} [DecidablePred (· ∈ B)] (h : ∀ n > 0, n ∈ A ↔ n ∈ B) : schnirelmannDensity A = schnirelmannDensity B := by rw [schnirelmannDensity, schnirelmannDensity]; congr; ext ⟨n, hn⟩; congr 3; ext x; simp_all /-- The Schnirelmann density is unaffected by adding `0`. -/ @[simp] lemma schnirelmannDensity_insert_zero [DecidablePred (· ∈ insert 0 A)] : schnirelmannDensity (insert 0 A) = schnirelmannDensity A := schnirelmannDensity_congr' (by aesop) /-- The Schnirelmann density is unaffected by removing `0`. -/ lemma schnirelmannDensity_diff_singleton_zero [DecidablePred (· ∈ A \ {0})] : schnirelmannDensity (A \ {0}) = schnirelmannDensity A := schnirelmannDensity_congr' (by aesop) lemma schnirelmannDensity_congr {B : Set ℕ} [DecidablePred (· ∈ B)] (h : A = B) : schnirelmannDensity A = schnirelmannDensity B := schnirelmannDensity_congr' (by simp_all) /-- If the Schnirelmann density is `0`, there is a positive natural for which `|A ∩ {1, ..., n}| / n < ε`, for any positive `ε`. Note this cannot be improved to `∃ᶠ n : ℕ in atTop`, as can be seen by `A = {1}ᶜ`. -/ lemma exists_of_schnirelmannDensity_eq_zero {ε : ℝ} (hε : 0 < ε) (hA : schnirelmannDensity A = 0) : ∃ n, 0 < n ∧ #{a ∈ Ioc 0 n | a ∈ A} / n < ε := by by_contra! h rw [← le_schnirelmannDensity_iff] at h linarith end @[simp] lemma schnirelmannDensity_empty : schnirelmannDensity ∅ = 0 := schnirelmannDensity_eq_zero_of_one_notMem (by simp) /-- The Schnirelmann density of any finset is `0`. -/ lemma schnirelmannDensity_finset (A : Finset ℕ) : schnirelmannDensity A = 0 := by refine le_antisymm ?_ schnirelmannDensity_nonneg simp only [schnirelmannDensity_le_iff_forall, zero_add] intro ε hε wlog hε₁ : ε ≤ 1 generalizing ε · obtain ⟨n, hn, hn'⟩ := this 1 zero_lt_one le_rfl exact ⟨n, hn, hn'.trans_le (le_of_not_ge hε₁)⟩ let n : ℕ := ⌊#A / ε⌋₊ + 1 have hn : 0 < n := Nat.succ_pos _ use n, hn rw [div_lt_iff₀ (Nat.cast_pos.2 hn), ← div_lt_iff₀' hε, Nat.cast_add_one] exact (Nat.lt_floor_add_one _).trans_le' <| by gcongr; simp [subset_iff] /-- The Schnirelmann density of any finite set is `0`. -/ lemma schnirelmannDensity_finite {A : Set ℕ} [DecidablePred (· ∈ A)] (hA : A.Finite) : schnirelmannDensity A = 0 := by simpa using schnirelmannDensity_finset hA.toFinset @[simp] lemma schnirelmannDensity_univ : schnirelmannDensity Set.univ = 1 := (schnirelmannDensity_eq_one_iff_of_zero_mem (by simp)).2 (by simp) lemma schnirelmannDensity_setOf_even : schnirelmannDensity (setOf Even) = 0 := schnirelmannDensity_eq_zero_of_one_notMem <| by simp lemma schnirelmannDensity_setOf_prime : schnirelmannDensity (setOf Nat.Prime) = 0 := schnirelmannDensity_eq_zero_of_one_notMem <| by simp [Nat.not_prime_one] /-- The Schnirelmann density of the set of naturals which are `1 mod m` is `m⁻¹`, for any `m ≠ 1`. Note that if `m = 1`, this set is empty. -/ lemma schnirelmannDensity_setOf_mod_eq_one {m : ℕ} (hm : m ≠ 1) : schnirelmannDensity {n | n % m = 1} = (m⁻¹ : ℝ) := by rcases m.eq_zero_or_pos with rfl | hm' · simp only [Nat.cast_zero, inv_zero] refine schnirelmannDensity_finite ?_ simp apply le_antisymm (schnirelmannDensity_le_of_le m hm'.ne' _) _ · rw [← one_div, ← @Nat.cast_one ℝ] gcongr simp only [Set.mem_setOf_eq, card_le_one_iff_subset_singleton, subset_iff, mem_filter, mem_Ioc, mem_singleton, and_imp] use 1 intro x _ hxm h rcases eq_or_lt_of_le hxm with rfl | hxm' · simp at h rwa [Nat.mod_eq_of_lt hxm'] at h rw [le_schnirelmannDensity_iff] intro n hn simp only [Set.mem_setOf_eq] have : (Icc 0 ((n - 1) / m)).image (· * m + 1) ⊆ {x ∈ Ioc 0 n | x % m = 1} := by simp only [subset_iff, mem_image, forall_exists_index, mem_filter, mem_Ioc, mem_Icc, and_imp] rintro _ y _ hy' rfl have hm : 2 ≤ m := hm.lt_of_le' hm' simp only [Nat.mul_add_mod', Nat.mod_eq_of_lt hm, add_pos_iff, or_true, and_true, true_and, ← Nat.le_sub_iff_add_le hn, zero_lt_one] exact Nat.mul_le_of_le_div _ _ _ hy' rw [le_div_iff₀ (Nat.cast_pos.2 hn), mul_comm, ← div_eq_mul_inv] apply (Nat.cast_le.2 (card_le_card this)).trans' rw [card_image_of_injective, Nat.card_Icc, Nat.sub_zero, div_le_iff₀ (Nat.cast_pos.2 hm'), ← Nat.cast_mul, Nat.cast_le, add_one_mul (α := ℕ)] · have := @Nat.lt_div_mul_add n.pred m hm' rwa [← Nat.succ_le, Nat.succ_pred hn.ne'] at this intro a b simp [hm'.ne'] lemma schnirelmannDensity_setOf_modeq_one {m : ℕ} : schnirelmannDensity {n | n ≡ 1 [MOD m]} = (m⁻¹ : ℝ) := by rcases eq_or_ne m 1 with rfl | hm · simp [Nat.modEq_one] rw [← schnirelmannDensity_setOf_mod_eq_one hm] apply schnirelmannDensity_congr ext n simp only [Set.mem_setOf_eq, Nat.ModEq, Nat.one_mod_eq_one.mpr hm] lemma schnirelmannDensity_setOf_Odd : schnirelmannDensity (setOf Odd) = 2⁻¹ := by have h : setOf Odd = {n | n % 2 = 1} := Set.ext fun _ => Nat.odd_iff simp only [h] rw [schnirelmannDensity_setOf_mod_eq_one (by norm_num1), Nat.cast_two]
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/Catalan.lean
import Mathlib.Algebra.BigOperators.Fin import Mathlib.Algebra.BigOperators.NatAntidiagonal import Mathlib.Data.Nat.Choose.Central import Mathlib.Tactic.Field import Mathlib.Tactic.GCongr import Mathlib.Tactic.Positivity /-! # Catalan numbers The Catalan numbers (http://oeis.org/A000108) are probably the most ubiquitous sequence of integers in mathematics. They enumerate several important objects like binary trees, Dyck paths, and triangulations of convex polygons. ## Main definitions * `catalan n`: the `n`th Catalan number, defined recursively as `catalan (n + 1) = ∑ i : Fin n.succ, catalan i * catalan (n - i)`. ## Main results * `catalan_eq_centralBinom_div`: The explicit formula for the Catalan number using the central binomial coefficient, `catalan n = Nat.centralBinom n / (n + 1)`. * `treesOfNumNodesEq_card_eq_catalan`: The number of binary trees with `n` internal nodes is `catalan n` ## Implementation details The proof of `catalan_eq_centralBinom_div` follows https://math.stackexchange.com/questions/3304415 ## TODO * Prove that the Catalan numbers enumerate many interesting objects. * Provide the many variants of Catalan numbers, e.g. associated to complex reflection groups, Fuss-Catalan, etc. -/ open Finset open Finset.antidiagonal (fst_le snd_le) /-- The recursive definition of the sequence of Catalan numbers: `catalan (n + 1) = ∑ i : Fin n.succ, catalan i * catalan (n - i)` -/ def catalan : ℕ → ℕ | 0 => 1 | n + 1 => ∑ i : Fin n.succ, catalan i * catalan (n - i) @[simp] theorem catalan_zero : catalan 0 = 1 := by rw [catalan] theorem catalan_succ (n : ℕ) : catalan (n + 1) = ∑ i : Fin n.succ, catalan i * catalan (n - i) := by rw [catalan] theorem catalan_succ' (n : ℕ) : catalan (n + 1) = ∑ ij ∈ antidiagonal n, catalan ij.1 * catalan ij.2 := by rw [catalan_succ, Nat.sum_antidiagonal_eq_sum_range_succ (fun x y => catalan x * catalan y) n, sum_range] @[simp] theorem catalan_one : catalan 1 = 1 := by simp [catalan_succ] /-- A helper sequence that can be used to prove the equality of the recursive and the explicit definition using a telescoping sum argument. -/ private def gosperCatalan (n j : ℕ) : ℚ := Nat.centralBinom j * Nat.centralBinom (n - j) * (2 * j - n) / (2 * n * (n + 1)) private theorem gosper_trick {n i : ℕ} (h : i ≤ n) : gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i = Nat.centralBinom i / (i + 1) * Nat.centralBinom (n - i) / (n - i + 1) := by have l₁ : (i : ℚ) + 1 ≠ 0 := by norm_cast have l₂ : (n : ℚ) - i + 1 ≠ 0 := by norm_cast have h₁ := (mul_div_cancel_left₀ (↑(Nat.centralBinom (i + 1))) l₁).symm have h₂ := (mul_div_cancel_left₀ (↑(Nat.centralBinom (n - i + 1))) l₂).symm have h₃ : ((i : ℚ) + 1) * (i + 1).centralBinom = 2 * (2 * i + 1) * i.centralBinom := mod_cast Nat.succ_mul_centralBinom_succ i have h₄ : ((n : ℚ) - i + 1) * (n - i + 1).centralBinom = 2 * (2 * (n - i) + 1) * (n - i).centralBinom := mod_cast Nat.succ_mul_centralBinom_succ (n - i) simp only [gosperCatalan] push_cast rw [show n + 1 - i = n - i + 1 by rw [Nat.add_comm (n - i) 1, ← (Nat.add_sub_assoc h 1), add_comm]] rw [h₁, h₂, h₃, h₄] field private theorem gosper_catalan_sub_eq_central_binom_div (n : ℕ) : gosperCatalan (n + 1) (n + 1) - gosperCatalan (n + 1) 0 = Nat.centralBinom (n + 1) / (n + 2) := by simp only [gosperCatalan, tsub_self, Nat.centralBinom_zero, Nat.cast_one, Nat.cast_add, Nat.cast_zero, tsub_zero] field theorem catalan_eq_centralBinom_div (n : ℕ) : catalan n = n.centralBinom / (n + 1) := by suffices (catalan n : ℚ) = Nat.centralBinom n / (n + 1) by have h := Nat.succ_dvd_centralBinom n exact mod_cast this induction n using Nat.caseStrongRecOn with | zero => simp | ind d hd => simp_rw [catalan_succ, Nat.cast_sum, Nat.cast_mul] trans (∑ i : Fin d.succ, Nat.centralBinom i / (i + 1) * (Nat.centralBinom (d - i) / (d - i + 1)) : ℚ) · congr ext1 x have m_le_d : x.val ≤ d := by omega have d_minus_x_le_d : (d - x.val) ≤ d := tsub_le_self rw [hd _ m_le_d, hd _ d_minus_x_le_d] norm_cast · trans (∑ i : Fin d.succ, (gosperCatalan (d + 1) (i + 1) - gosperCatalan (d + 1) i)) · refine sum_congr rfl fun i _ => ?_ rw [gosper_trick i.is_le, mul_div] · rw [← sum_range fun i => gosperCatalan (d + 1) (i + 1) - gosperCatalan (d + 1) i, sum_range_sub, Nat.succ_eq_add_one] rw [gosper_catalan_sub_eq_central_binom_div d] norm_cast theorem succ_mul_catalan_eq_centralBinom (n : ℕ) : (n + 1) * catalan n = n.centralBinom := (Nat.eq_mul_of_div_eq_right n.succ_dvd_centralBinom (catalan_eq_centralBinom_div n).symm).symm theorem catalan_two : catalan 2 = 2 := by norm_num [catalan_eq_centralBinom_div, Nat.centralBinom, Nat.choose] theorem catalan_three : catalan 3 = 5 := by norm_num [catalan_eq_centralBinom_div, Nat.centralBinom, Nat.choose] namespace Tree /-- Given two finsets, find all trees that can be formed with left child in `a` and right child in `b` -/ abbrev pairwiseNode (a b : Finset (Tree Unit)) : Finset (Tree Unit) := (a ×ˢ b).map ⟨fun x => x.1 △ x.2, fun ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ => fun h => by simpa using h⟩ /-- A Finset of all trees with `n` nodes. See `mem_treesOfNodesEq` -/ def treesOfNumNodesEq : ℕ → Finset (Tree Unit) | 0 => {nil} | n + 1 => (antidiagonal n).attach.biUnion fun ijh => pairwiseNode (treesOfNumNodesEq ijh.1.1) (treesOfNumNodesEq ijh.1.2) decreasing_by · simp_wf; have := fst_le ijh.2; cutsat · simp_wf; have := snd_le ijh.2; cutsat @[simp] theorem treesOfNumNodesEq_zero : treesOfNumNodesEq 0 = {nil} := by rw [treesOfNumNodesEq] theorem treesOfNumNodesEq_succ (n : ℕ) : treesOfNumNodesEq (n + 1) = (antidiagonal n).biUnion fun ij => pairwiseNode (treesOfNumNodesEq ij.1) (treesOfNumNodesEq ij.2) := by rw [treesOfNumNodesEq] ext simp @[simp] theorem mem_treesOfNumNodesEq {x : Tree Unit} {n : ℕ} : x ∈ treesOfNumNodesEq n ↔ x.numNodes = n := by induction x using Tree.unitRecOn generalizing n <;> cases n <;> simp [treesOfNumNodesEq_succ, *] theorem mem_treesOfNumNodesEq_numNodes (x : Tree Unit) : x ∈ treesOfNumNodesEq x.numNodes := mem_treesOfNumNodesEq.mpr rfl @[simp, norm_cast] theorem coe_treesOfNumNodesEq (n : ℕ) : ↑(treesOfNumNodesEq n) = { x : Tree Unit | x.numNodes = n } := Set.ext (by simp) theorem treesOfNumNodesEq_card_eq_catalan (n : ℕ) : #(treesOfNumNodesEq n) = catalan n := by induction n using Nat.case_strong_induction_on with | hz => simp | hi n ih => rw [treesOfNumNodesEq_succ, card_biUnion, catalan_succ'] · apply sum_congr rfl rintro ⟨i, j⟩ H rw [card_map, card_product, ih _ (fst_le H), ih _ (snd_le H)] · simp_rw [Set.PairwiseDisjoint, Set.Pairwise, disjoint_left] aesop end Tree
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/DoubleCounting.lean
import Mathlib.Algebra.BigOperators.Ring.Finset import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Algebra.Order.Ring.Nat /-! # Double countings This file gathers a few double counting arguments. ## Bipartite graphs In a bipartite graph (considered as a relation `r : α → β → Prop`), we can bound the number of edges between `s : Finset α` and `t : Finset β` by the minimum/maximum of edges over all `a ∈ s` times the size of `s`. Similarly for `t`. Combining those two yields inequalities between the sizes of `s` and `t`. * `bipartiteBelow`: `s.bipartiteBelow r b` are the elements of `s` below `b` w.r.t. `r`. Its size is the number of edges of `b` in `s`. * `bipartiteAbove`: `t.bipartite_Above r a` are the elements of `t` above `a` w.r.t. `r`. Its size is the number of edges of `a` in `t`. * `card_mul_le_card_mul`, `card_mul_le_card_mul'`: Double counting the edges of a bipartite graph from below and from above. * `card_mul_eq_card_mul`: Equality combination of the previous. ## Implementation notes For the formulation of double-counting arguments where a bipartite graph is considered as a bipartite simple graph `G : SimpleGraph V`, see `Mathlib/Combinatorics/SimpleGraph/Bipartite.lean`. -/ assert_not_exists Field open Finset Function Relator variable {R α β : Type*} /-! ### Bipartite graph -/ namespace Finset section Bipartite variable (r : α → β → Prop) (s : Finset α) (t : Finset β) (a : α) (b : β) [DecidablePred (r a)] [∀ a, Decidable (r a b)] {m n : ℕ} /-- Elements of `s` which are "below" `b` according to relation `r`. -/ def bipartiteBelow : Finset α := {a ∈ s | r a b} /-- Elements of `t` which are "above" `a` according to relation `r`. -/ def bipartiteAbove : Finset β := {b ∈ t | r a b} theorem bipartiteBelow_swap : t.bipartiteBelow (swap r) a = t.bipartiteAbove r a := rfl theorem bipartiteAbove_swap : s.bipartiteAbove (swap r) b = s.bipartiteBelow r b := rfl @[simp, norm_cast] theorem coe_bipartiteBelow : s.bipartiteBelow r b = ({a ∈ s | r a b} : Set α) := coe_filter _ _ @[simp, norm_cast] theorem coe_bipartiteAbove : t.bipartiteAbove r a = ({b ∈ t | r a b} : Set β) := coe_filter _ _ variable {s t a b} @[simp] theorem mem_bipartiteBelow {a : α} : a ∈ s.bipartiteBelow r b ↔ a ∈ s ∧ r a b := mem_filter @[simp] theorem mem_bipartiteAbove {b : β} : b ∈ t.bipartiteAbove r a ↔ b ∈ t ∧ r a b := mem_filter @[to_additive] theorem prod_prod_bipartiteAbove_eq_prod_prod_bipartiteBelow [CommMonoid R] (f : α → β → R) [∀ a b, Decidable (r a b)] : ∏ a ∈ s, ∏ b ∈ t.bipartiteAbove r a, f a b = ∏ b ∈ t, ∏ a ∈ s.bipartiteBelow r b, f a b := by simp_rw [bipartiteAbove, bipartiteBelow, prod_filter] exact prod_comm theorem sum_card_bipartiteAbove_eq_sum_card_bipartiteBelow [∀ a b, Decidable (r a b)] : (∑ a ∈ s, #(t.bipartiteAbove r a)) = ∑ b ∈ t, #(s.bipartiteBelow r b) := by simp_rw [card_eq_sum_ones, sum_sum_bipartiteAbove_eq_sum_sum_bipartiteBelow] section OrderedSemiring variable [Semiring R] [PartialOrder R] [IsOrderedRing R] {m n : R} /-- **Double counting** argument. Considering `r` as a bipartite graph, the LHS is a lower bound on the number of edges while the RHS is an upper bound. -/ theorem card_nsmul_le_card_nsmul [∀ a b, Decidable (r a b)] (hm : ∀ a ∈ s, m ≤ #(t.bipartiteAbove r a)) (hn : ∀ b ∈ t, #(s.bipartiteBelow r b) ≤ n) : #s • m ≤ #t • n := calc _ ≤ ∑ a ∈ s, (#(t.bipartiteAbove r a) : R) := s.card_nsmul_le_sum _ _ hm _ = ∑ b ∈ t, (#(s.bipartiteBelow r b) : R) := by norm_cast; rw [sum_card_bipartiteAbove_eq_sum_card_bipartiteBelow] _ ≤ _ := t.sum_le_card_nsmul _ _ hn /-- **Double counting** argument. Considering `r` as a bipartite graph, the LHS is a lower bound on the number of edges while the RHS is an upper bound. -/ theorem card_nsmul_le_card_nsmul' [∀ a b, Decidable (r a b)] (hn : ∀ b ∈ t, n ≤ #(s.bipartiteBelow r b)) (hm : ∀ a ∈ s, #(t.bipartiteAbove r a) ≤ m) : #t • n ≤ #s • m := card_nsmul_le_card_nsmul (swap r) hn hm end OrderedSemiring section StrictOrderedSemiring variable [Semiring R] [PartialOrder R] [IsStrictOrderedRing R] (r : α → β → Prop) {s : Finset α} {t : Finset β} (a b) {m n : R} /-- **Double counting** argument. Considering `r` as a bipartite graph, the LHS is a strict lower bound on the number of edges while the RHS is an upper bound. -/ theorem card_nsmul_lt_card_nsmul_of_lt_of_le [∀ a b, Decidable (r a b)] (hs : s.Nonempty) (hm : ∀ a ∈ s, m < #(t.bipartiteAbove r a)) (hn : ∀ b ∈ t, #(s.bipartiteBelow r b) ≤ n) : #s • m < #t • n := calc _ = ∑ _a ∈ s, m := by rw [sum_const] _ < ∑ a ∈ s, (#(t.bipartiteAbove r a) : R) := sum_lt_sum_of_nonempty hs hm _ = ∑ b ∈ t, (#(s.bipartiteBelow r b) : R) := by norm_cast; rw [sum_card_bipartiteAbove_eq_sum_card_bipartiteBelow] _ ≤ _ := t.sum_le_card_nsmul _ _ hn /-- **Double counting** argument. Considering `r` as a bipartite graph, the LHS is a lower bound on the number of edges while the RHS is a strict upper bound. -/ theorem card_nsmul_lt_card_nsmul_of_le_of_lt [∀ a b, Decidable (r a b)] (ht : t.Nonempty) (hm : ∀ a ∈ s, m ≤ #(t.bipartiteAbove r a)) (hn : ∀ b ∈ t, #(s.bipartiteBelow r b) < n) : #s • m < #t • n := calc _ ≤ ∑ a ∈ s, (#(t.bipartiteAbove r a) : R) := s.card_nsmul_le_sum _ _ hm _ = ∑ b ∈ t, (#(s.bipartiteBelow r b) : R) := by norm_cast; rw [sum_card_bipartiteAbove_eq_sum_card_bipartiteBelow] _ < ∑ _b ∈ t, n := sum_lt_sum_of_nonempty ht hn _ = _ := sum_const _ /-- **Double counting** argument. Considering `r` as a bipartite graph, the LHS is a strict lower bound on the number of edges while the RHS is an upper bound. -/ theorem card_nsmul_lt_card_nsmul_of_lt_of_le' [∀ a b, Decidable (r a b)] (ht : t.Nonempty) (hn : ∀ b ∈ t, n < #(s.bipartiteBelow r b)) (hm : ∀ a ∈ s, #(t.bipartiteAbove r a) ≤ m) : #t • n < #s • m := card_nsmul_lt_card_nsmul_of_lt_of_le (swap r) ht hn hm /-- **Double counting** argument. Considering `r` as a bipartite graph, the LHS is a lower bound on the number of edges while the RHS is a strict upper bound. -/ theorem card_nsmul_lt_card_nsmul_of_le_of_lt' [∀ a b, Decidable (r a b)] (hs : s.Nonempty) (hn : ∀ b ∈ t, n ≤ #(s.bipartiteBelow r b)) (hm : ∀ a ∈ s, #(t.bipartiteAbove r a) < m) : #t • n < #s • m := card_nsmul_lt_card_nsmul_of_le_of_lt (swap r) hs hn hm end StrictOrderedSemiring /-- **Double counting** argument. Considering `r` as a bipartite graph, the LHS is a lower bound on the number of edges while the RHS is an upper bound. -/ theorem card_mul_le_card_mul [∀ a b, Decidable (r a b)] (hm : ∀ a ∈ s, m ≤ #(t.bipartiteAbove r a)) (hn : ∀ b ∈ t, #(s.bipartiteBelow r b) ≤ n) : #s * m ≤ #t * n := card_nsmul_le_card_nsmul _ hm hn theorem card_mul_le_card_mul' [∀ a b, Decidable (r a b)] (hn : ∀ b ∈ t, n ≤ #(s.bipartiteBelow r b)) (hm : ∀ a ∈ s, #(t.bipartiteAbove r a) ≤ m) : #t * n ≤ #s * m := card_nsmul_le_card_nsmul' _ hn hm theorem card_mul_eq_card_mul [∀ a b, Decidable (r a b)] (hm : ∀ a ∈ s, #(t.bipartiteAbove r a) = m) (hn : ∀ b ∈ t, #(s.bipartiteBelow r b) = n) : #s * m = #t * n := (card_mul_le_card_mul _ (fun a ha ↦ (hm a ha).ge) fun b hb ↦ (hn b hb).le).antisymm <| card_mul_le_card_mul' _ (fun a ha ↦ (hn a ha).ge) fun b hb ↦ (hm b hb).le theorem card_le_card_of_forall_subsingleton (hs : ∀ a ∈ s, ∃ b, b ∈ t ∧ r a b) (ht : ∀ b ∈ t, ({ a ∈ s | r a b } : Set α).Subsingleton) : #s ≤ #t := by classical rw [← mul_one #s, ← mul_one #t] exact card_mul_le_card_mul r (fun a h ↦ card_pos.2 (by rw [← coe_nonempty, coe_bipartiteAbove] exact hs _ h : (t.bipartiteAbove r a).Nonempty)) (fun b h ↦ card_le_one.2 (by simp_rw [mem_bipartiteBelow] exact ht _ h)) theorem card_le_card_of_forall_subsingleton' (ht : ∀ b ∈ t, ∃ a, a ∈ s ∧ r a b) (hs : ∀ a ∈ s, ({ b ∈ t | r a b } : Set β).Subsingleton) : #t ≤ #s := card_le_card_of_forall_subsingleton (swap r) ht hs end Bipartite end Finset namespace Fintype variable [Fintype α] [Fintype β] {r : α → β → Prop} theorem card_le_card_of_leftTotal_unique (h₁ : LeftTotal r) (h₂ : LeftUnique r) : Fintype.card α ≤ Fintype.card β := card_le_card_of_forall_subsingleton r (by simpa using h₁) fun _ _ _ ha₁ _ ha₂ ↦ h₂ ha₁.2 ha₂.2 theorem card_le_card_of_rightTotal_unique (h₁ : RightTotal r) (h₂ : RightUnique r) : Fintype.card β ≤ Fintype.card α := card_le_card_of_forall_subsingleton' r (by simpa using h₁) fun _ _ _ ha₁ _ ha₂ ↦ h₂ ha₁.2 ha₂.2 end Fintype
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/InclusionExclusion.lean
import Mathlib.Algebra.BigOperators.Pi import Mathlib.Algebra.BigOperators.Ring.Finset import Mathlib.Algebra.Module.BigOperators /-! # Inclusion-exclusion principle This file proves several variants of the inclusion-exclusion principle. The inclusion-exclusion principle says that the sum/integral of a function over a finite union of sets can be calculated as the alternating sum over `n > 0` of the sum/integral of the function over the intersection of `n` of the sets. By taking complements, it also says that the sum/integral of a function over a finite intersection of complements of sets can be calculated as the alternating sum over `n ≥ 0` of the sum/integral of the function over the intersection of `n` of the sets. By taking the function to be constant `1`, we instead get a result about the cardinality/measure of the sets. ## Main declarations Per the above explanation, this file contains the following variants of inclusion-exclusion: * `Finset.inclusion_exclusion_sum_biUnion`: Sum of a function over a finite union of sets * `Finset.inclusion_exclusion_card_biUnion`: Cardinality of a finite union of sets * `Finset.inclusion_exclusion_sum_inf_compl`: Sum of a function over a finite intersection of complements of sets * `Finset.inclusion_exclusion_card_inf_compl`: Cardinality of a finite intersection of complements of sets See also `MeasureTheory.integral_biUnion_eq_sum_powerset` for the version with integrals, and `MeasureTheory.measureReal_biUnion_eq_sum_powerset` for the version with measures. ## TODO * Prove that truncating the series alternatively gives an upper/lower bound to the true value. -/ assert_not_exists Field namespace Finset variable {ι α G : Type*} [AddCommGroup G] {s : Finset ι} lemma prod_indicator_biUnion_sub_indicator (hs : s.Nonempty) (S : ι → Set α) (a : α) : ∏ i ∈ s, (Set.indicator (⋃ i ∈ s, S i) 1 a - Set.indicator (S i) 1 a) = (0 : ℤ) := by by_cases ha : a ∈ ⋃ i ∈ s, S i · have ha' := ha simp only [Set.mem_iUnion, exists_prop] at ha obtain ⟨i, hi, ha⟩ := ha apply prod_eq_zero hi (by simp [ha, ha']) · obtain ⟨i, hi⟩ := hs have ha : a ∉ S i := by aesop exact prod_eq_zero hi <| by simp [*, -coe_biUnion] /-- **Inclusion-exclusion principle**, indicator version over a finite union of sets. -/ lemma indicator_biUnion_eq_sum_powerset (s : Finset ι) (S : ι → Set α) (f : α → G) (a : α) : Set.indicator (⋃ i ∈ s, S i) f a = ∑ t ∈ s.powerset with t.Nonempty, (-1) ^ (#t + 1) • Set.indicator (⋂ i ∈ t, S i) f a := by classical by_cases ha : a ∈ ⋃ i ∈ s, S i; swap · simp only [ha, not_false_eq_true, Set.indicator_of_notMem, Int.reduceNeg, pow_succ, mul_neg, mul_one, neg_smul] symm apply sum_eq_zero simp only [Int.reduceNeg, neg_eq_zero, mem_filter, mem_powerset, and_imp] intro t hts ht rw [Set.indicator_of_notMem] · simp · contrapose! ha simp only [Set.mem_iInter] at ha rcases ht with ⟨i, hi⟩ simp only [Set.mem_iUnion, exists_prop] exact ⟨i, hts hi, ha _ hi⟩ rw [← sub_eq_zero] calc Set.indicator (⋃ i ∈ s, S i) f a - ∑ t ∈ s.powerset with t.Nonempty, (-1) ^ (#t + 1) • Set.indicator (⋂ i ∈ t.1, S i) f a _ = ∑ t ∈ s.powerset with t.Nonempty, (-1) ^ #t • Set.indicator (⋂ i ∈ t, S i) f a + ∑ t ∈ s.powerset with ¬ t.Nonempty, (-1) ^ #t • Set.indicator (⋂ i ∈ t, S i) f a := by simp [sub_eq_neg_add, ← sum_neg_distrib, filter_eq', pow_succ, ha] _ = ∑ t ∈ s.powerset, (-1) ^ #t • Set.indicator (⋂ i ∈ t, S i) f a := by rw [sum_filter_add_sum_filter_not] _ = (∏ i ∈ s, (1 - Set.indicator (S i) 1 a : ℤ)) • f a := by simp only [Int.reduceNeg, prod_sub, prod_const_one, mul_one, sum_smul] congr! 1 with t simp only [prod_const_one, prod_indicator_apply] simp [Set.indicator] _ = 0 := by have : Set.indicator (⋃ i ∈ s, S i) 1 a = (1 : ℤ) := Set.indicator_of_mem ha 1 rw [← this, prod_indicator_biUnion_sub_indicator, zero_smul] simp only [Set.mem_iUnion, exists_prop] at ha rcases ha with ⟨i, hi, -⟩ exact ⟨i, hi⟩ variable [DecidableEq α] lemma prod_indicator_biUnion_finset_sub_indicator (hs : s.Nonempty) (S : ι → Finset α) (a : α) : ∏ i ∈ s, (Set.indicator (s.biUnion S) 1 a - Set.indicator (S i) 1 a) = (0 : ℤ) := by convert prod_indicator_biUnion_sub_indicator hs (fun i ↦ S i) a simp /-- **Inclusion-exclusion principle** for the sum of a function over a union. The sum of a function `f` over the union of the `S i` over `i ∈ s` is the alternating sum of the sums of `f` over the intersections of the `S i`. -/ theorem inclusion_exclusion_sum_biUnion (s : Finset ι) (S : ι → Finset α) (f : α → G) : ∑ a ∈ s.biUnion S, f a = ∑ t : s.powerset.filter (·.Nonempty), (-1) ^ (#t.1 + 1) • ∑ a ∈ t.1.inf' (mem_filter.1 t.2).2 S, f a := by classical rw [← sub_eq_zero] calc ∑ a ∈ s.biUnion S, f a - ∑ t : s.powerset.filter (·.Nonempty), (-1) ^ (#t.1 + 1) • ∑ a ∈ t.1.inf' (mem_filter.1 t.2).2 S, f a = ∑ t : s.powerset.filter (·.Nonempty), (-1) ^ #t.1 • ∑ a ∈ t.1.inf' (mem_filter.1 t.2).2 S, f a + ∑ t ∈ s.powerset.filter (¬ ·.Nonempty), (-1) ^ #t • ∑ a ∈ s.biUnion S, f a := by simp [sub_eq_neg_add, ← sum_neg_distrib, filter_eq', pow_succ] _ = ∑ t ∈ s.powerset, (-1) ^ #t • if ht : t.Nonempty then ∑ a ∈ t.inf' ht S, f a else ∑ a ∈ s.biUnion S, f a := by rw [← sum_attach (filter ..)]; simp [sum_dite] _ = ∑ a ∈ s.biUnion S, (∏ i ∈ s, (1 - Set.indicator (S i) 1 a : ℤ)) • f a := by simp only [Int.reduceNeg, prod_sub, sum_comm (s := s.biUnion S), sum_smul, mul_assoc] congr! with t split_ifs with ht · obtain ⟨i, hi⟩ := ht simp only [prod_const_one, prod_indicator_apply] simp only [smul_sum, Set.indicator, Set.mem_iInter, mem_coe, Pi.one_apply, mul_ite, mul_one, mul_zero, ite_smul, zero_smul, sum_ite, not_forall, sum_const_zero, add_zero] congr aesop · obtain rfl := not_nonempty_iff_eq_empty.1 ht simp _ = ∑ a ∈ s.biUnion S, (∏ i ∈ s, (Set.indicator (s.biUnion S) 1 a - Set.indicator (S i) 1 a) : ℤ) • f a := by congr! with t; rw [Set.indicator_of_mem ‹_›, Pi.one_apply] _ = 0 := by obtain rfl | hs := s.eq_empty_or_nonempty <;> simp [-coe_biUnion, prod_indicator_biUnion_finset_sub_indicator, *] /-- **Inclusion-exclusion principle** for the cardinality of a union. The cardinality of the union of the `S i` over `i ∈ s` is the alternating sum of the cardinalities of the intersections of the `S i`. -/ theorem inclusion_exclusion_card_biUnion (s : Finset ι) (S : ι → Finset α) : #(s.biUnion S) = ∑ t : s.powerset.filter (·.Nonempty), (-1 : ℤ) ^ (#t.1 + 1) * #(t.1.inf' (mem_filter.1 t.2).2 S) := by simpa using inclusion_exclusion_sum_biUnion (G := ℤ) s S (f := 1) variable [Fintype α] /-- **Inclusion-exclusion principle** for the sum of a function over an intersection of complements. The sum of a function `f` over the intersection of the complements of the `S i` over `i ∈ s` is the alternating sum of the sums of `f` over the intersections of the `S i`. -/ theorem inclusion_exclusion_sum_inf_compl (s : Finset ι) (S : ι → Finset α) (f : α → G) : ∑ a ∈ s.inf fun i ↦ (S i)ᶜ, f a = ∑ t ∈ s.powerset, (-1) ^ #t • ∑ a ∈ t.inf S, f a := by classical calc ∑ a ∈ s.inf fun i ↦ (S i)ᶜ, f a = ∑ a, f a - ∑ a ∈ s.biUnion S, f a := by rw [← Finset.compl_sup, sup_eq_biUnion, eq_sub_iff_add_eq, sum_compl_add_sum] _ = ∑ t ∈ s.powerset.filter (¬ ·.Nonempty), (-1) ^ #t • ∑ a ∈ t.inf S, f a + ∑ t ∈ s.powerset.filter (·.Nonempty), (-1) ^ #t • ∑ a ∈ t.inf S, f a := by simp [← sum_attach (filter ..), inclusion_exclusion_sum_biUnion, inf'_eq_inf, filter_eq', sub_eq_add_neg, pow_succ] _ = ∑ t ∈ s.powerset, (-1) ^ #t • ∑ a ∈ t.inf S, f a := sum_filter_not_add_sum_filter .. /-- **Inclusion-exclusion principle** for the cardinality of an intersection of complements. The cardinality of the intersection of the complements of the `S i` over `i ∈ s` is the alternating sum of the cardinalities of the intersections of the `S i`. -/ theorem inclusion_exclusion_card_inf_compl (s : Finset ι) (S : ι → Finset α) : #(s.inf fun i ↦ (S i)ᶜ) = ∑ t ∈ s.powerset, (-1 : ℤ) ^ #t * #(t.inf S) := by simpa using inclusion_exclusion_sum_inf_compl (G := ℤ) s S (f := 1) end Finset
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/DyckWord.lean
import Batteries.Data.List.Count import Mathlib.Combinatorics.Enumerative.Catalan import Mathlib.Tactic.Positivity /-! # Dyck words A Dyck word is a sequence consisting of an equal number `n` of symbols of two types such that for all prefixes one symbol occurs at least as many times as the other. If the symbols are `(` and `)` the latter restriction is equivalent to balanced brackets; if they are `U = (1, 1)` and `D = (1, -1)` the sequence is a lattice path from `(0, 0)` to `(0, 2n)` and the restriction requires the path to never go below the x-axis. This file defines Dyck words and constructs their bijection with rooted binary trees, one consequence being that the number of Dyck words with length `2 * n` is `catalan n`. ## Main definitions * `DyckWord`: a list of `U`s and `D`s with as many `U`s as `D`s and with every prefix having at least as many `U`s as `D`s. * `DyckWord.semilength`: semilength (half the length) of a Dyck word. * `DyckWord.firstReturn`: for a nonempty word, the index of the `D` matching the initial `U`. ## Main results * `DyckWord.equivTree`: equivalence between Dyck words and rooted binary trees. See the docstrings of `DyckWord.equivTreeToFun` and `DyckWord.equivTreeInvFun` for details. * `DyckWord.equivTreesOfNumNodesEq`: equivalence between Dyck words of length `2 * n` and rooted binary trees with `n` internal nodes. * `DyckWord.card_dyckWord_semilength_eq_catalan`: there are `catalan n` Dyck words of length `2 * n` or semilength `n`. ## Implementation notes While any two-valued type could have been used for `DyckStep`, a new enumerated type is used here to emphasise that the definition of a Dyck word does not depend on that underlying type. -/ open List /-- A `DyckStep` is either `U` or `D`, corresponding to `(` and `)` respectively. -/ inductive DyckStep | U : DyckStep | D : DyckStep deriving Inhabited, DecidableEq /-- Named in analogy to `Bool.dichotomy`. -/ lemma DyckStep.dichotomy (s : DyckStep) : s = U ∨ s = D := by cases s <;> tauto open DyckStep /-- A Dyck word is a list of `DyckStep`s with as many `U`s as `D`s and with every prefix having at least as many `U`s as `D`s. -/ @[ext] structure DyckWord where /-- The underlying list -/ toList : List DyckStep /-- There are as many `U`s as `D`s -/ count_U_eq_count_D : toList.count U = toList.count D /-- Each prefix has at least as many `U`s as `D`s -/ count_D_le_count_U i : (toList.take i).count D ≤ (toList.take i).count U deriving DecidableEq attribute [coe] DyckWord.toList instance : Coe DyckWord (List DyckStep) := ⟨DyckWord.toList⟩ instance : Add DyckWord where add p q := ⟨p ++ q, by simp only [count_append, p.count_U_eq_count_D, q.count_U_eq_count_D], by simp only [take_append, count_append] exact fun _ ↦ add_le_add (p.count_D_le_count_U _) (q.count_D_le_count_U _)⟩ instance : Zero DyckWord := ⟨[], by simp, by simp⟩ /-- Dyck words form an additive cancellative monoid under concatenation, with the empty word as 0. -/ instance : AddCancelMonoid DyckWord where add_zero p := by ext1; exact append_nil _ zero_add p := by ext1; rfl add_assoc p q r := by ext1; apply append_assoc nsmul := nsmulRec add_left_cancel p q r h := by rw [DyckWord.ext_iff] at *; exact append_cancel_left h add_right_cancel p q r h := by rw [DyckWord.ext_iff] at *; exact append_cancel_right h namespace DyckWord variable {p q : DyckWord} lemma toList_eq_nil : p.toList = [] ↔ p = 0 := by rw [DyckWord.ext_iff]; rfl lemma toList_ne_nil : p.toList ≠ [] ↔ p ≠ 0 := toList_eq_nil.ne /-- The only Dyck word that is an additive unit is the empty word. -/ instance : Unique (AddUnits DyckWord) where uniq p := by obtain ⟨a, b, h, -⟩ := p obtain ⟨ha, hb⟩ := append_eq_nil_iff.mp (toList_eq_nil.mpr h) congr · exact toList_eq_nil.mp ha · exact toList_eq_nil.mp hb variable (h : p ≠ 0) /-- The first element of a nonempty Dyck word is `U`. -/ lemma head_eq_U (p : DyckWord) (h) : p.toList.head h = U := by rcases p with - | s; · tauto rw [head_cons] by_contra f rename_i _ nonneg simpa [s.dichotomy.resolve_left f] using nonneg 1 /-- The last element of a nonempty Dyck word is `D`. -/ lemma getLast_eq_D (p : DyckWord) (h) : p.toList.getLast h = D := by by_contra f; have s := p.count_U_eq_count_D rw [← dropLast_append_getLast h, (dichotomy _).resolve_right f] at s simp_rw [dropLast_eq_take, count_append, count_singleton', ite_true, reduceCtorEq, ite_false] at s have := p.count_D_le_count_U (p.toList.length - 1); cutsat include h in lemma cons_tail_dropLast_concat : U :: p.toList.dropLast.tail ++ [D] = p := by have h' := toList_ne_nil.mpr h have : p.toList.dropLast.take 1 = [p.toList.head h'] := by rcases p with - | ⟨s, ⟨- | ⟨t, r⟩⟩⟩ · tauto · rename_i bal _ cases s <;> simp at bal · tauto nth_rw 2 [← p.toList.dropLast_append_getLast h', ← p.toList.dropLast.take_append_drop 1] rw [getLast_eq_D, drop_one, this, head_eq_U] rfl variable (p) in /-- Prefix of a Dyck word as a Dyck word, given that the count of `U`s and `D`s in it are equal. -/ def take (i : ℕ) (hi : (p.toList.take i).count U = (p.toList.take i).count D) : DyckWord where toList := p.toList.take i count_U_eq_count_D := hi count_D_le_count_U k := by rw [take_take]; exact p.count_D_le_count_U (min k i) variable (p) in /-- Suffix of a Dyck word as a Dyck word, given that the count of `U`s and `D`s in the prefix are equal. -/ def drop (i : ℕ) (hi : (p.toList.take i).count U = (p.toList.take i).count D) : DyckWord where toList := p.toList.drop i count_U_eq_count_D := by have := p.count_U_eq_count_D rw [← take_append_drop i p.toList, count_append, count_append] at this omega count_D_le_count_U k := by rw [show i = min i (i + k) by omega, ← take_take] at hi rw [take_drop, ← add_le_add_iff_left (((p.toList.take (i + k)).take i).count U), ← count_append, hi, ← count_append, take_append_drop] exact p.count_D_le_count_U _ variable (p) in /-- Nest `p` in one pair of brackets, i.e. `x` becomes `(x)`. -/ def nest : DyckWord where toList := [U] ++ p ++ [D] count_U_eq_count_D := by simp [p.count_U_eq_count_D] count_D_le_count_U i := by simp only [take_append, count_append] rw [← add_rotate (count D _), ← add_rotate (count U _)] apply add_le_add _ (p.count_D_le_count_U _) rcases i.eq_zero_or_pos with hi | hi; · simp [hi] rw [take_of_length_le (show [U].length ≤ i by rwa [length_singleton]), count_singleton'] simp only [reduceCtorEq, ite_false] rw [add_comm] exact add_le_add (zero_le _) (count_le_length.trans (by simp)) @[simp] lemma nest_ne_zero : p.nest ≠ 0 := by simp [← toList_ne_nil, nest] variable (p) in /-- A property stating that `p` is nonempty and strictly positive in its interior, i.e. is of the form `(x)` with `x` a Dyck word. -/ def IsNested : Prop := p ≠ 0 ∧ ∀ ⦃i⦄, 0 < i → i < p.toList.length → (p.toList.take i).count D < (p.toList.take i).count U protected lemma IsNested.nest : p.nest.IsNested := ⟨nest_ne_zero, fun i lb ub ↦ by simp_rw [nest, length_append, length_singleton] at ub ⊢ rw [take_append_of_le_length (by rw [singleton_append, length_cons]; cutsat), take_append, take_of_length_le (by rw [length_singleton]; cutsat), length_singleton, singleton_append, count_cons_of_ne (by simp), count_cons_self, Nat.lt_add_one_iff] exact p.count_D_le_count_U _⟩ variable (p) in /-- Denest `p`, i.e. `(x)` becomes `x`, given that `p.IsNested`. -/ def denest (hn : p.IsNested) : DyckWord where toList := p.toList.dropLast.tail count_U_eq_count_D := by have := p.count_U_eq_count_D rw [← cons_tail_dropLast_concat hn.1, count_append, count_cons] at this simpa using this count_D_le_count_U i := by replace h := toList_ne_nil.mpr hn.1 have l1 : p.toList.take 1 = [p.toList.head h] := by rcases p with - | - <;> tauto have l3 : p.toList.length - 1 = p.toList.length - 1 - 1 + 1 := by rcases p with - | ⟨s, ⟨- | ⟨t, r⟩⟩⟩ · tauto · rename_i bal _ cases s <;> simp at bal · tauto rw [← drop_one, take_drop, dropLast_eq_take, take_take] have ub : min (1 + i) (p.toList.length - 1) < p.toList.length := (min_le_right _ p.toList.length.pred).trans_lt (Nat.pred_lt ((length_pos_iff.mpr h).ne')) have lb : 0 < min (1 + i) (p.toList.length - 1) := by omega have eq := hn.2 lb ub set j := min (1 + i) (p.toList.length - 1) rw [← (p.toList.take j).take_append_drop 1, count_append, count_append, take_take, min_eq_left (by omega), l1, head_eq_U] at eq simp only [count_singleton', ite_true] at eq omega variable (p) in lemma nest_denest (hn) : (p.denest hn).nest = p := by simpa [DyckWord.ext_iff] using p.cons_tail_dropLast_concat hn.1 variable (p) in lemma denest_nest : p.nest.denest .nest = p := by simp_rw [nest, denest, DyckWord.ext_iff, dropLast_concat]; rfl section Semilength variable (p) in /-- The semilength of a Dyck word is half of the number of `DyckStep`s in it, or equivalently its number of `U`s. -/ def semilength : ℕ := p.toList.count U @[simp] lemma semilength_zero : semilength 0 = 0 := rfl @[simp] lemma semilength_add : (p + q).semilength = p.semilength + q.semilength := count_append .. @[simp] lemma semilength_nest : p.nest.semilength = p.semilength + 1 := by simp [semilength, nest] lemma semilength_eq_count_D : p.semilength = p.toList.count D := by rw [← count_U_eq_count_D]; rfl @[simp] lemma two_mul_semilength_eq_length : 2 * p.semilength = p.toList.length := by nth_rw 1 [two_mul, semilength, p.count_U_eq_count_D, semilength] convert (p.toList.length_eq_countP_add_countP (· == D)).symm rw [count]; congr!; rename_i s; cases s <;> tauto end Semilength section FirstReturn variable (p) in /-- `p.firstReturn` is 0 if `p = 0` and the index of the `D` matching the initial `U` otherwise. -/ def firstReturn : ℕ := (range p.toList.length).findIdx fun i ↦ (p.toList.take (i + 1)).count U = (p.toList.take (i + 1)).count D @[simp] lemma firstReturn_zero : firstReturn 0 = 0 := rfl include h in lemma firstReturn_pos : 0 < p.firstReturn := by rw [← not_le, Nat.le_zero, firstReturn, findIdx_eq, getElem_range] · simp only [not_lt_zero', IsEmpty.forall_iff] rw [← p.cons_tail_dropLast_concat h] simp · rw [length_range, length_pos_iff] exact toList_ne_nil.mpr h include h in lemma firstReturn_lt_length : p.firstReturn < p.toList.length := by have lp := length_pos_of_ne_nil (toList_ne_nil.mpr h) rw [← length_range (n := p.toList.length)] apply findIdx_lt_length_of_exists simp only [mem_range, decide_eq_true_eq] use p.toList.length - 1 exact ⟨by cutsat, by rw [Nat.sub_add_cancel lp, take_of_length_le (le_refl _), p.count_U_eq_count_D]⟩ include h in lemma count_take_firstReturn_add_one : (p.toList.take (p.firstReturn + 1)).count U = (p.toList.take (p.firstReturn + 1)).count D := by have := findIdx_getElem (w := (length_range (n := p.toList.length)).symm ▸ firstReturn_lt_length h) simpa using this lemma count_D_lt_count_U_of_lt_firstReturn {i : ℕ} (hi : i < p.firstReturn) : (p.toList.take (i + 1)).count D < (p.toList.take (i + 1)).count U := by have ne := not_of_lt_findIdx hi rw [decide_eq_false_iff_not, ← ne_eq, getElem_range] at ne exact lt_of_le_of_ne (p.count_D_le_count_U (i + 1)) ne.symm @[simp] lemma firstReturn_add : (p + q).firstReturn = if p = 0 then q.firstReturn else p.firstReturn := by split_ifs with h; · simp [h] have u : (p + q).toList = p.toList ++ q.toList := rfl rw [firstReturn, findIdx_eq] · simp_rw [u, decide_eq_true_eq, getElem_range] have v := firstReturn_lt_length h constructor · rw [take_append, show p.firstReturn + 1 - p.toList.length = 0 by cutsat, take_zero, append_nil, count_take_firstReturn_add_one h] · intro j hj rw [take_append, show j + 1 - p.toList.length = 0 by cutsat, take_zero, append_nil] simpa using (count_D_lt_count_U_of_lt_firstReturn hj).ne' · rw [length_range, u, length_append] exact Nat.lt_add_right _ (firstReturn_lt_length h) @[simp] lemma firstReturn_nest : p.nest.firstReturn = p.toList.length + 1 := by have u : p.nest.toList = U :: p.toList ++ [D] := rfl rw [firstReturn, findIdx_eq] · simp_rw [u, decide_eq_true_eq, getElem_range] constructor · rw [take_of_length_le (by simp), ← u, p.nest.count_U_eq_count_D] · intro j hj simp_rw [cons_append, take_succ_cons, count_cons, beq_self_eq_true, ite_true, beq_iff_eq, reduceCtorEq, ite_false, take_append, show j - p.toList.length = 0 by cutsat, take_zero, append_nil] have := p.count_D_le_count_U j simp only [add_zero, decide_eq_false_iff_not, ne_eq] cutsat · simp_rw [length_range, u, length_append, length_cons] exact Nat.lt_add_one _ variable (p) in /-- The left part of the Dyck word decomposition, inside the `U, D` pair that `firstReturn` refers to. `insidePart 0 = 0`. -/ def insidePart : DyckWord := if h : p = 0 then 0 else (p.take (p.firstReturn + 1) (count_take_firstReturn_add_one h)).denest ⟨by rw [← toList_ne_nil, take]; simpa using toList_ne_nil.mpr h, fun i lb ub ↦ by simp only [take, length_take, lt_min_iff] at ub ⊢ replace ub := ub.1 rw [take_take, min_eq_left ub.le] rw [show i = i - 1 + 1 by cutsat] at ub ⊢ rw [Nat.add_lt_add_iff_right] at ub exact count_D_lt_count_U_of_lt_firstReturn ub⟩ variable (p) in /-- The right part of the Dyck word decomposition, outside the `U, D` pair that `firstReturn` refers to. `outsidePart 0 = 0`. -/ def outsidePart : DyckWord := if h : p = 0 then 0 else p.drop (p.firstReturn + 1) (count_take_firstReturn_add_one h) @[simp] lemma insidePart_zero : insidePart 0 = 0 := by simp [insidePart] @[simp] lemma outsidePart_zero : outsidePart 0 = 0 := by simp [outsidePart] include h in @[simp] lemma insidePart_add : (p + q).insidePart = p.insidePart := by simp_rw [insidePart, firstReturn_add, add_eq_zero', h, false_and, dite_false, ite_false, DyckWord.ext_iff, take] congr 3 exact take_append_of_le_length (firstReturn_lt_length h) include h in @[simp] lemma outsidePart_add : (p + q).outsidePart = p.outsidePart + q := by simp_rw [outsidePart, firstReturn_add, add_eq_zero', h, false_and, dite_false, ite_false, DyckWord.ext_iff, drop] exact drop_append_of_le_length (firstReturn_lt_length h) @[simp] lemma insidePart_nest : p.nest.insidePart = p := by simp_rw [insidePart, nest_ne_zero, dite_false, firstReturn_nest] convert p.denest_nest; rw [DyckWord.ext_iff]; apply take_of_length_le simp_rw [nest, length_append, length_singleton]; cutsat @[simp] lemma outsidePart_nest : p.nest.outsidePart = 0 := by simp_rw [outsidePart, nest_ne_zero, dite_false, firstReturn_nest] rw [DyckWord.ext_iff]; apply drop_of_length_le simp_rw [nest, length_append, length_singleton]; cutsat include h in @[simp] theorem nest_insidePart_add_outsidePart : p.insidePart.nest + p.outsidePart = p := by simp_rw [insidePart, outsidePart, h, dite_false, nest_denest, DyckWord.ext_iff] apply take_append_drop include h in lemma semilength_insidePart_add_semilength_outsidePart_add_one : p.insidePart.semilength + p.outsidePart.semilength + 1 = p.semilength := by rw [← congrArg semilength (nest_insidePart_add_outsidePart h), semilength_add, semilength_nest, add_right_comm] include h in theorem semilength_insidePart_lt : p.insidePart.semilength < p.semilength := by have := semilength_insidePart_add_semilength_outsidePart_add_one h cutsat include h in theorem semilength_outsidePart_lt : p.outsidePart.semilength < p.semilength := by have := semilength_insidePart_add_semilength_outsidePart_add_one h cutsat end FirstReturn section Order instance : Preorder DyckWord where le := Relation.ReflTransGen (fun p q ↦ p = q.insidePart ∨ p = q.outsidePart) le_refl _ := Relation.ReflTransGen.refl le_trans _ _ _ := Relation.ReflTransGen.trans lemma le_add_self (p q : DyckWord) : q ≤ p + q := by by_cases h : p = 0 · simp [h] · have := semilength_outsidePart_lt h exact (le_add_self p.outsidePart q).trans (Relation.ReflTransGen.single (Or.inr (outsidePart_add h).symm)) termination_by p.semilength variable (p) in protected lemma zero_le : 0 ≤ p := add_zero p ▸ le_add_self p 0 lemma infix_of_le (h : p ≤ q) : p.toList <:+: q.toList := by induction h with | refl => exact infix_refl _ | tail _pm mq ih => rename_i m r rcases eq_or_ne r 0 with rfl | hr · rw [insidePart_zero, outsidePart_zero, or_self] at mq rwa [mq] at ih · have : [U] ++ r.insidePart ++ [D] ++ r.outsidePart = r := DyckWord.ext_iff.mp (nest_insidePart_add_outsidePart hr) grind lemma le_of_suffix (h : p.toList <:+ q.toList) : p ≤ q := by obtain ⟨r', h⟩ := h have hc : (q.toList.take (q.toList.length - p.toList.length)).count U = (q.toList.take (q.toList.length - p.toList.length)).count D := by have hq := q.count_U_eq_count_D rw [← h] at hq ⊢ rw [count_append, count_append, p.count_U_eq_count_D, Nat.add_right_cancel_iff] at hq simp [hq] let r : DyckWord := q.take _ hc have e : r' = r := by simp_rw [r, take, ← h, length_append, add_tsub_cancel_right, take_left'] rw [e] at h; replace h : r + p = q := DyckWord.ext h; rw [← h]; exact le_add_self .. /-- Partial order on Dyck words: `p ≤ q` if a (possibly empty) sequence of `insidePart` and `outsidePart` operations can turn `q` into `p`. -/ instance : PartialOrder DyckWord where le_antisymm p q pq qp := by have h₁ := infix_of_le pq have h₂ := infix_of_le qp exact DyckWord.ext <| h₁.eq_of_length <| h₁.length_le.antisymm h₂.length_le protected lemma pos_iff_ne_zero : 0 < p ↔ p ≠ 0 := by rw [ne_comm, iff_comm, ne_iff_lt_iff_le] exact DyckWord.zero_le p lemma monotone_semilength : Monotone semilength := fun p q pq ↦ by induction pq with | refl => rfl | tail _ mq ih => rename_i m r _ rcases eq_or_ne r 0 with rfl | hr · rw [insidePart_zero, outsidePart_zero, or_self] at mq rwa [mq] at ih · rcases mq with hm | hm · exact ih.trans (hm ▸ semilength_insidePart_lt hr).le · exact ih.trans (hm ▸ semilength_outsidePart_lt hr).le lemma strictMono_semilength : StrictMono semilength := fun p q pq ↦ by obtain ⟨plq, pnq⟩ := lt_iff_le_and_ne.mp pq apply lt_of_le_of_ne (monotone_semilength plq) contrapose! pnq replace pnq := congr(2 * $(pnq)) simp_rw [two_mul_semilength_eq_length] at pnq exact DyckWord.ext ((infix_of_le plq).eq_of_length pnq) end Order section Tree open Tree /-- Convert a Dyck word to a binary rooted tree. `f(0) = nil`. For a nonzero word find the `D` that matches the initial `U`, which has index `p.firstReturn`, then let `x` be everything strictly between said `U` and `D`, and `y` be everything strictly after said `D`. `p = x.nest + y` with `x, y` (possibly empty) Dyck words. `f(p) = f(x) △ f(y)`, where △ (defined in `Mathlib/Data/Tree.lean`) joins two subtrees to a new root node. -/ private def equivTreeToFun (p : DyckWord) : Tree Unit := if h : p = 0 then nil else have := semilength_insidePart_lt h have := semilength_outsidePart_lt h equivTreeToFun p.insidePart △ equivTreeToFun p.outsidePart termination_by p.semilength /-- Convert a binary rooted tree to a Dyck word. `g(nil) = 0`. A nonempty tree with left subtree `l` and right subtree `r` is sent to `g(l).nest + g(r)`. -/ private def equivTreeInvFun : Tree Unit → DyckWord | Tree.nil => 0 | Tree.node _ l r => (equivTreeInvFun l).nest + equivTreeInvFun r @[nolint unusedHavesSuffices] private lemma equivTree_left_inv (p) : equivTreeInvFun (equivTreeToFun p) = p := by by_cases h : p = 0 · simp [h, equivTreeToFun, equivTreeInvFun] · rw [equivTreeToFun] simp_rw [h, dite_false, equivTreeInvFun] have := semilength_insidePart_lt h have := semilength_outsidePart_lt h rw [equivTree_left_inv p.insidePart, equivTree_left_inv p.outsidePart] exact nest_insidePart_add_outsidePart h termination_by p.semilength @[nolint unusedHavesSuffices] private lemma equivTree_right_inv : ∀ t, equivTreeToFun (equivTreeInvFun t) = t | Tree.nil => by simp [equivTreeInvFun, equivTreeToFun] | Tree.node _ _ _ => by simp [equivTreeInvFun, equivTreeToFun, equivTree_right_inv] /-- Equivalence between Dyck words and rooted binary trees. -/ def equivTree : DyckWord ≃ Tree Unit where toFun := equivTreeToFun invFun := equivTreeInvFun left_inv := equivTree_left_inv right_inv := equivTree_right_inv @[nolint unusedHavesSuffices] lemma semilength_eq_numNodes_equivTree (p) : p.semilength = (equivTree p).numNodes := by by_cases h : p = 0 · simp [h, equivTree, equivTreeToFun] · rw [equivTree, Equiv.coe_fn_mk, equivTreeToFun] simp_rw [h, dite_false, numNodes] have := semilength_insidePart_lt h have := semilength_outsidePart_lt h rw [← semilength_insidePart_add_semilength_outsidePart_add_one h, semilength_eq_numNodes_equivTree p.insidePart, semilength_eq_numNodes_equivTree p.outsidePart]; rfl termination_by p.semilength /-- Equivalence between Dyck words of semilength `n` and rooted binary trees with `n` internal nodes. -/ def equivTreesOfNumNodesEq (n : ℕ) : { p : DyckWord // p.semilength = n } ≃ treesOfNumNodesEq n where toFun := fun ⟨p, _⟩ ↦ ⟨equivTree p, by rwa [mem_treesOfNumNodesEq, ← semilength_eq_numNodes_equivTree]⟩ invFun := fun ⟨tr, _⟩ ↦ ⟨equivTree.symm tr, by rwa [semilength_eq_numNodes_equivTree, ← mem_treesOfNumNodesEq, Equiv.apply_symm_apply]⟩ left_inv _ := by simp only [Equiv.symm_apply_apply] right_inv _ := by simp only [Equiv.apply_symm_apply] instance {n : ℕ} : Fintype { p : DyckWord // p.semilength = n } := Fintype.ofEquiv _ (equivTreesOfNumNodesEq n).symm /-- There are `catalan n` Dyck words of semilength `n` (or length `2 * n`). -/ theorem card_dyckWord_semilength_eq_catalan (n : ℕ) : Fintype.card { p : DyckWord // p.semilength = n } = catalan n := by rw [← Fintype.ofEquiv_card (equivTreesOfNumNodesEq n), ← treesOfNumNodesEq_card_eq_catalan] convert Fintype.card_coe _ end Tree end DyckWord namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for the `positivity` tactic: `p.firstReturn` is positive if `p` is nonzero. -/ @[positivity DyckWord.firstReturn _] def evalDyckWordFirstReturn : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℕ), ~q(DyckWord.firstReturn $a) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure (.positive q(DyckWord.firstReturn_pos ($pa).ne')) | .nonzero pa => pure (.positive q(DyckWord.firstReturn_pos $pa)) | _ => pure .none | _, _, _ => throwError "not DyckWord.firstReturn" end Mathlib.Meta.Positivity
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/Composition.lean
import Mathlib.Algebra.BigOperators.Fin import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Data.Finset.Sort /-! # Compositions A composition of a natural number `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of positive integers. Combinatorially, it corresponds to a decomposition of `{0, ..., n-1}` into non-empty blocks of consecutive integers, where the `iⱼ` are the lengths of the blocks. This notion is closely related to that of a partition of `n`, but in a composition of `n` the order of the `iⱼ`s matters. We implement two different structures covering these two viewpoints on compositions. The first one, made of a list of positive integers summing to `n`, is the main one and is called `Composition n`. The second one is useful for combinatorial arguments (for instance to show that the number of compositions of `n` is `2^(n-1)`). It is given by a subset of `{0, ..., n}` containing `0` and `n`, where the elements of the subset (other than `n`) correspond to the leftmost points of each block. The main API is built on `Composition n`, and we provide an equivalence between the two types. ## Main functions * `c : Composition n` is a structure, made of a list of integers which are all positive and add up to `n`. * `composition_card` states that the cardinality of `Composition n` is exactly `2^(n-1)`, which is proved by constructing an equiv with `CompositionAsSet n` (see below), which is itself in bijection with the subsets of `Fin (n-1)` (this holds even for `n = 0`, where `-` is nat subtraction). Let `c : Composition n` be a composition of `n`. Then * `c.blocks` is the list of blocks in `c`. * `c.length` is the number of blocks in the composition. * `c.blocksFun : Fin c.length → ℕ` is the realization of `c.blocks` as a function on `Fin c.length`. This is the main object when using compositions to understand the composition of analytic functions. * `c.sizeUpTo : ℕ → ℕ` is the sum of the size of the blocks up to `i`.; * `c.embedding i : Fin (c.blocksFun i) → Fin n` is the increasing embedding of the `i`-th block in `Fin n`; * `c.index j`, for `j : Fin n`, is the index of the block containing `j`. * `Composition.ones n` is the composition of `n` made of ones, i.e., `[1, ..., 1]`. * `Composition.single n (hn : 0 < n)` is the composition of `n` made of a single block of size `n`. Compositions can also be used to split lists. Let `l` be a list of length `n` and `c` a composition of `n`. * `l.splitWrtComposition c` is a list of lists, made of the slices of `l` corresponding to the blocks of `c`. * `join_splitWrtComposition` states that splitting a list and then joining it gives back the original list. * `splitWrtComposition_join` states that joining a list of lists, and then splitting it back according to the right composition, gives back the original list of lists. We turn to the second viewpoint on compositions, that we realize as a finset of `Fin (n+1)`. `c : CompositionAsSet n` is a structure made of a finset of `Fin (n+1)` called `c.boundaries` and proofs that it contains `0` and `n`. (Taking a finset of `Fin n` containing `0` would not make sense in the edge case `n = 0`, while the previous description works in all cases). The elements of this set (other than `n`) correspond to leftmost points of blocks. Thus, there is an equiv between `Composition n` and `CompositionAsSet n`. We only construct basic API on `CompositionAsSet` (notably `c.length` and `c.blocks`) to be able to construct this equiv, called `compositionEquiv n`. Since there is a straightforward equiv between `CompositionAsSet n` and finsets of `{1, ..., n-1}` (obtained by removing `0` and `n` from a `CompositionAsSet` and called `compositionAsSetEquiv n`), we deduce that `CompositionAsSet n` and `Composition n` are both fintypes of cardinality `2^(n - 1)` (see `compositionAsSet_card` and `composition_card`). ## Implementation details The main motivation for this structure and its API is in the construction of the composition of formal multilinear series, and the proof that the composition of analytic functions is analytic. The representation of a composition as a list is very handy as lists are very flexible and already have a well-developed API. ## Tags Composition, partition ## References <https://en.wikipedia.org/wiki/Composition_(combinatorics)> -/ assert_not_exists Field open List variable {n : ℕ} /-- A composition of `n` is a list of positive integers summing to `n`. -/ @[ext] structure Composition (n : ℕ) where /-- List of positive integers summing to `n` -/ blocks : List ℕ /-- Proof of positivity for `blocks` -/ blocks_pos : ∀ {i}, i ∈ blocks → 0 < i /-- Proof that `blocks` sums to `n` -/ blocks_sum : blocks.sum = n deriving DecidableEq attribute [simp] Composition.blocks_sum /-- Combinatorial viewpoint on a composition of `n`, by seeing it as non-empty blocks of consecutive integers in `{0, ..., n-1}`. We register every block by its left end-point, yielding a finset containing `0`. As this does not make sense for `n = 0`, we add `n` to this finset, and get a finset of `{0, ..., n}` containing `0` and `n`. This is the data in the structure `CompositionAsSet n`. -/ @[ext] structure CompositionAsSet (n : ℕ) where /-- Combinatorial viewpoint on a composition of `n` as consecutive integers `{0, ..., n-1}` -/ boundaries : Finset (Fin n.succ) /-- Proof that `0` is a member of `boundaries` -/ zero_mem : (0 : Fin n.succ) ∈ boundaries /-- Last element of the composition -/ getLast_mem : Fin.last n ∈ boundaries deriving DecidableEq instance {n : ℕ} : Inhabited (CompositionAsSet n) := ⟨⟨Finset.univ, Finset.mem_univ _, Finset.mem_univ _⟩⟩ attribute [simp] CompositionAsSet.zero_mem CompositionAsSet.getLast_mem /-! ### Compositions A composition of an integer `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of positive integers. -/ namespace Composition variable (c : Composition n) instance (n : ℕ) : ToString (Composition n) := ⟨fun c => toString c.blocks⟩ /-- The length of a composition, i.e., the number of blocks in the composition. -/ abbrev length : ℕ := c.blocks.length theorem blocks_length : c.blocks.length = c.length := rfl /-- The blocks of a composition, seen as a function on `Fin c.length`. When composing analytic functions using compositions, this is the main player. -/ def blocksFun : Fin c.length → ℕ := c.blocks.get @[simp] theorem ofFn_blocksFun : ofFn c.blocksFun = c.blocks := ofFn_get _ @[simp] theorem sum_blocksFun : ∑ i, c.blocksFun i = n := by conv_rhs => rw [← c.blocks_sum, ← ofFn_blocksFun, sum_ofFn] @[simp] theorem blocksFun_mem_blocks (i : Fin c.length) : c.blocksFun i ∈ c.blocks := get_mem _ _ theorem one_le_blocks {i : ℕ} (h : i ∈ c.blocks) : 1 ≤ i := c.blocks_pos h theorem blocks_le {i : ℕ} (h : i ∈ c.blocks) : i ≤ n := by rw [← c.blocks_sum] exact List.le_sum_of_mem h @[simp] theorem one_le_blocks' {i : ℕ} (h : i < c.length) : 1 ≤ c.blocks[i] := c.one_le_blocks (get_mem (blocks c) _) @[simp] theorem blocks_pos' (i : ℕ) (h : i < c.length) : 0 < c.blocks[i] := c.one_le_blocks' h @[simp] theorem one_le_blocksFun (i : Fin c.length) : 1 ≤ c.blocksFun i := c.one_le_blocks (c.blocksFun_mem_blocks i) @[simp] theorem blocksFun_le {n} (c : Composition n) (i : Fin c.length) : c.blocksFun i ≤ n := c.blocks_le <| getElem_mem _ @[simp] theorem length_le : c.length ≤ n := by conv_rhs => rw [← c.blocks_sum] exact length_le_sum_of_one_le _ fun i hi => c.one_le_blocks hi @[simp] theorem blocks_eq_nil : c.blocks = [] ↔ n = 0 := by constructor · intro h simpa using congr(List.sum $h) · rintro rfl rw [← length_eq_zero_iff, ← nonpos_iff_eq_zero] exact c.length_le protected theorem length_eq_zero : c.length = 0 ↔ n = 0 := by simp @[simp] theorem length_pos_iff : 0 < c.length ↔ 0 < n := by simp [pos_iff_ne_zero] alias ⟨_, length_pos_of_pos⟩ := length_pos_iff /-- The sum of the sizes of the blocks in a composition up to `i`. -/ def sizeUpTo (i : ℕ) : ℕ := (c.blocks.take i).sum @[simp] theorem sizeUpTo_zero : c.sizeUpTo 0 = 0 := by simp [sizeUpTo] theorem sizeUpTo_ofLength_le (i : ℕ) (h : c.length ≤ i) : c.sizeUpTo i = n := by dsimp [sizeUpTo] convert c.blocks_sum exact take_of_length_le h @[simp] theorem sizeUpTo_length : c.sizeUpTo c.length = n := c.sizeUpTo_ofLength_le c.length le_rfl theorem sizeUpTo_le (i : ℕ) : c.sizeUpTo i ≤ n := by conv_rhs => rw [← c.blocks_sum, ← sum_take_add_sum_drop _ i] exact Nat.le_add_right _ _ theorem sizeUpTo_succ {i : ℕ} (h : i < c.length) : c.sizeUpTo (i + 1) = c.sizeUpTo i + c.blocks[i] := by simp only [sizeUpTo] rw [sum_take_succ _ _ h] theorem sizeUpTo_succ' (i : Fin c.length) : c.sizeUpTo ((i : ℕ) + 1) = c.sizeUpTo i + c.blocksFun i := c.sizeUpTo_succ i.2 theorem sizeUpTo_strict_mono {i : ℕ} (h : i < c.length) : c.sizeUpTo i < c.sizeUpTo (i + 1) := by rw [c.sizeUpTo_succ h] simp theorem monotone_sizeUpTo : Monotone c.sizeUpTo := monotone_sum_take _ /-- The `i`-th boundary of a composition, i.e., the leftmost point of the `i`-th block. We include a virtual point at the right of the last block, to make for a nice equiv with `CompositionAsSet n`. -/ def boundary : Fin (c.length + 1) ↪o Fin (n + 1) := (OrderEmbedding.ofStrictMono fun i => ⟨c.sizeUpTo i, Nat.lt_succ_of_le (c.sizeUpTo_le i)⟩) <| Fin.strictMono_iff_lt_succ.2 fun ⟨_, hi⟩ => c.sizeUpTo_strict_mono hi @[simp] theorem boundary_zero : c.boundary 0 = 0 := by simp [boundary] @[simp] theorem boundary_last : c.boundary (Fin.last c.length) = Fin.last n := by simp [boundary, Fin.ext_iff] /-- The boundaries of a composition, i.e., the leftmost point of all the blocks. We include a virtual point at the right of the last block, to make for a nice equiv with `CompositionAsSet n`. -/ def boundaries : Finset (Fin (n + 1)) := Finset.univ.map c.boundary.toEmbedding theorem card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := by simp [boundaries] /-- To `c : Composition n`, one can associate a `CompositionAsSet n` by registering the leftmost point of each block, and adding a virtual point at the right of the last block. -/ def toCompositionAsSet : CompositionAsSet n where boundaries := c.boundaries zero_mem := by simp only [boundaries, Finset.mem_univ, Finset.mem_map] exact ⟨0, And.intro True.intro rfl⟩ getLast_mem := by simp only [boundaries, Finset.mem_univ, Finset.mem_map] exact ⟨Fin.last c.length, And.intro True.intro c.boundary_last⟩ /-- The canonical increasing bijection between `Fin (c.length + 1)` and `c.boundaries` is exactly `c.boundary`. -/ theorem orderEmbOfFin_boundaries : c.boundaries.orderEmbOfFin c.card_boundaries_eq_succ_length = c.boundary := by refine (Finset.orderEmbOfFin_unique' _ ?_).symm exact fun i => (Finset.mem_map' _).2 (Finset.mem_univ _) /-- Embedding the `i`-th block of a composition (identified with `Fin (c.blocksFun i)`) into `Fin n` at the relevant position. -/ def embedding (i : Fin c.length) : Fin (c.blocksFun i) ↪o Fin n := (Fin.natAddOrderEmb <| c.sizeUpTo i).trans <| Fin.castLEOrderEmb <| calc c.sizeUpTo i + c.blocksFun i = c.sizeUpTo (i + 1) := (c.sizeUpTo_succ i.2).symm _ ≤ c.sizeUpTo c.length := monotone_sum_take _ i.2 _ = n := c.sizeUpTo_length @[simp] theorem coe_embedding (i : Fin c.length) (j : Fin (c.blocksFun i)) : (c.embedding i j : ℕ) = c.sizeUpTo i + j := rfl /-- `index_exists` asserts there is some `i` with `j < c.sizeUpTo (i+1)`. In the next definition `index` we use `Nat.find` to produce the minimal such index. -/ theorem index_exists {j : ℕ} (h : j < n) : ∃ i : ℕ, j < c.sizeUpTo (i + 1) ∧ i < c.length := by have n_pos : 0 < n := lt_of_le_of_lt (zero_le j) h have : 0 < c.blocks.sum := by rwa [← c.blocks_sum] at n_pos have length_pos : 0 < c.blocks.length := length_pos_of_sum_pos (blocks c) this refine ⟨c.length - 1, ?_, Nat.pred_lt (ne_of_gt length_pos)⟩ have : c.length - 1 + 1 = c.length := Nat.succ_pred_eq_of_pos length_pos simp [this, h] /-- `c.index j` is the index of the block in the composition `c` containing `j`. -/ def index (j : Fin n) : Fin c.length := ⟨Nat.find (c.index_exists j.2), (Nat.find_spec (c.index_exists j.2)).2⟩ theorem lt_sizeUpTo_index_succ (j : Fin n) : (j : ℕ) < c.sizeUpTo (c.index j).succ := (Nat.find_spec (c.index_exists j.2)).1 theorem sizeUpTo_index_le (j : Fin n) : c.sizeUpTo (c.index j) ≤ j := by by_contra! H set i := c.index j have i_pos : (0 : ℕ) < i := by by_contra! i_pos revert H simp [nonpos_iff_eq_zero.1 i_pos, c.sizeUpTo_zero] let i₁ := (i : ℕ).pred have i₁_lt_i : i₁ < i := Nat.pred_lt (ne_of_gt i_pos) have i₁_succ : i₁ + 1 = i := Nat.succ_pred_eq_of_pos i_pos have := Nat.find_min (c.index_exists j.2) i₁_lt_i simp_all [lt_trans i₁_lt_i (c.index j).2] /-- Mapping an element `j` of `Fin n` to the element in the block containing it, identified with `Fin (c.blocksFun (c.index j))` through the canonical increasing bijection. -/ def invEmbedding (j : Fin n) : Fin (c.blocksFun (c.index j)) := ⟨j - c.sizeUpTo (c.index j), by rw [tsub_lt_iff_right, add_comm, ← sizeUpTo_succ'] · exact lt_sizeUpTo_index_succ _ _ · exact sizeUpTo_index_le _ _⟩ @[simp] theorem coe_invEmbedding (j : Fin n) : (c.invEmbedding j : ℕ) = j - c.sizeUpTo (c.index j) := rfl @[simp] theorem embedding_comp_inv (j : Fin n) : c.embedding (c.index j) (c.invEmbedding j) = j := by rw [Fin.ext_iff] apply add_tsub_cancel_of_le (c.sizeUpTo_index_le j) theorem mem_range_embedding_iff {j : Fin n} {i : Fin c.length} : j ∈ Set.range (c.embedding i) ↔ c.sizeUpTo i ≤ j ∧ (j : ℕ) < c.sizeUpTo (i : ℕ).succ := by constructor · intro h rcases Set.mem_range.2 h with ⟨k, hk⟩ rw [Fin.ext_iff] at hk dsimp at hk rw [← hk] simp [sizeUpTo_succ', k.is_lt] · intro h apply Set.mem_range.2 refine ⟨⟨j - c.sizeUpTo i, ?_⟩, ?_⟩ · rw [tsub_lt_iff_left, ← sizeUpTo_succ'] · exact h.2 · exact h.1 · rw [Fin.ext_iff] exact add_tsub_cancel_of_le h.1 /-- The embeddings of different blocks of a composition are disjoint. -/ theorem disjoint_range {i₁ i₂ : Fin c.length} (h : i₁ ≠ i₂) : Disjoint (Set.range (c.embedding i₁)) (Set.range (c.embedding i₂)) := by classical wlog h' : i₁ < i₂ · exact (this c h.symm (h.lt_or_gt.resolve_left h')).symm by_contra d obtain ⟨x, hx₁, hx₂⟩ : ∃ x : Fin n, x ∈ Set.range (c.embedding i₁) ∧ x ∈ Set.range (c.embedding i₂) := Set.not_disjoint_iff.1 d have A : (i₁ : ℕ).succ ≤ i₂ := Nat.succ_le_of_lt h' apply lt_irrefl (x : ℕ) calc (x : ℕ) < c.sizeUpTo (i₁ : ℕ).succ := (c.mem_range_embedding_iff.1 hx₁).2 _ ≤ c.sizeUpTo (i₂ : ℕ) := monotone_sum_take _ A _ ≤ x := (c.mem_range_embedding_iff.1 hx₂).1 theorem mem_range_embedding (j : Fin n) : j ∈ Set.range (c.embedding (c.index j)) := by have : c.embedding (c.index j) (c.invEmbedding j) ∈ Set.range (c.embedding (c.index j)) := Set.mem_range_self _ rwa [c.embedding_comp_inv j] at this theorem mem_range_embedding_iff' {j : Fin n} {i : Fin c.length} : j ∈ Set.range (c.embedding i) ↔ i = c.index j := by constructor · rw [← not_imp_not] intro h exact Set.disjoint_right.1 (c.disjoint_range h) (c.mem_range_embedding j) · intro h rw [h] exact c.mem_range_embedding j @[simp] theorem index_embedding (i : Fin c.length) (j : Fin (c.blocksFun i)) : c.index (c.embedding i j) = i := by symm rw [← mem_range_embedding_iff'] apply Set.mem_range_self theorem invEmbedding_comp (i : Fin c.length) (j : Fin (c.blocksFun i)) : (c.invEmbedding (c.embedding i j) : ℕ) = j := by simp_rw [coe_invEmbedding, index_embedding, coe_embedding, add_tsub_cancel_left] /-- Equivalence between the disjoint union of the blocks (each of them seen as `Fin (c.blocksFun i)`) with `Fin n`. -/ def blocksFinEquiv : (Σ i : Fin c.length, Fin (c.blocksFun i)) ≃ Fin n where toFun x := c.embedding x.1 x.2 invFun j := ⟨c.index j, c.invEmbedding j⟩ left_inv x := by rcases x with ⟨i, y⟩ dsimp congr; · exact c.index_embedding _ _ rw [Fin.heq_ext_iff] · exact c.invEmbedding_comp _ _ · rw [c.index_embedding] right_inv j := c.embedding_comp_inv j theorem blocksFun_congr {n₁ n₂ : ℕ} (c₁ : Composition n₁) (c₂ : Composition n₂) (i₁ : Fin c₁.length) (i₂ : Fin c₂.length) (hn : n₁ = n₂) (hc : c₁.blocks = c₂.blocks) (hi : (i₁ : ℕ) = i₂) : c₁.blocksFun i₁ = c₂.blocksFun i₂ := by cases hn rw [← Composition.ext_iff] at hc cases hc congr rwa [Fin.ext_iff] /-- Two compositions (possibly of different integers) coincide if and only if they have the same sequence of blocks. -/ theorem sigma_eq_iff_blocks_eq {c : Σ n, Composition n} {c' : Σ n, Composition n} : c = c' ↔ c.2.blocks = c'.2.blocks := by refine ⟨fun H => by rw [H], fun H => ?_⟩ rcases c with ⟨n, c⟩ rcases c' with ⟨n', c'⟩ have : n = n' := by rw [← c.blocks_sum, ← c'.blocks_sum, H] induction this congr ext1 exact H /-! ### The composition `Composition.ones` -/ /-- The composition made of blocks all of size `1`. -/ def ones (n : ℕ) : Composition n := ⟨replicate n (1 : ℕ), fun {i} hi => by simp [List.eq_of_mem_replicate hi], by simp⟩ instance {n : ℕ} : Inhabited (Composition n) := ⟨Composition.ones n⟩ @[simp] theorem ones_length (n : ℕ) : (ones n).length = n := List.length_replicate @[simp] theorem ones_blocks (n : ℕ) : (ones n).blocks = replicate n (1 : ℕ) := rfl @[simp] theorem ones_blocksFun (n : ℕ) (i : Fin (ones n).length) : (ones n).blocksFun i = 1 := by simp only [blocksFun, ones, get_eq_getElem, getElem_replicate] @[simp] theorem ones_sizeUpTo (n : ℕ) (i : ℕ) : (ones n).sizeUpTo i = min i n := by simp [sizeUpTo, ones_blocks, take_replicate] @[simp] theorem ones_embedding (i : Fin (ones n).length) (h : 0 < (ones n).blocksFun i) : (ones n).embedding i ⟨0, h⟩ = ⟨i, lt_of_lt_of_le i.2 (ones n).length_le⟩ := by ext simpa using i.2.le theorem eq_ones_iff {c : Composition n} : c = ones n ↔ ∀ i ∈ c.blocks, i = 1 := by constructor · rintro rfl exact fun i => eq_of_mem_replicate · intro H ext1 have A : c.blocks = replicate c.blocks.length 1 := eq_replicate_of_mem H have : c.blocks.length = n := by conv_rhs => rw [← c.blocks_sum, A] simp rw [A, this, ones_blocks] theorem ne_ones_iff {c : Composition n} : c ≠ ones n ↔ ∃ i ∈ c.blocks, 1 < i := by refine (not_congr eq_ones_iff).trans ?_ have : ∀ j ∈ c.blocks, j = 1 ↔ j ≤ 1 := fun j hj => by simp [le_antisymm_iff, c.one_le_blocks hj] simp +contextual [this] theorem eq_ones_iff_length {c : Composition n} : c = ones n ↔ c.length = n := by constructor · rintro rfl exact ones_length n · contrapose intro H length_n apply lt_irrefl n calc n = ∑ i : Fin c.length, 1 := by simp [length_n] _ < ∑ i : Fin c.length, c.blocksFun i := by { obtain ⟨i, hi, i_blocks⟩ : ∃ i ∈ c.blocks, 1 < i := ne_ones_iff.1 H rw [← ofFn_blocksFun, mem_ofFn' c.blocksFun, Set.mem_range] at hi obtain ⟨j : Fin c.length, hj : c.blocksFun j = i⟩ := hi rw [← hj] at i_blocks exact Finset.sum_lt_sum (fun i _ => one_le_blocksFun c i) ⟨j, Finset.mem_univ _, i_blocks⟩ } _ = n := c.sum_blocksFun theorem eq_ones_iff_le_length {c : Composition n} : c = ones n ↔ n ≤ c.length := by simp [eq_ones_iff_length, le_antisymm_iff, c.length_le] /-! ### The composition `Composition.single` -/ /-- The composition made of a single block of size `n`. -/ def single (n : ℕ) (h : 0 < n) : Composition n := ⟨[n], by simp [h], by simp⟩ @[simp] theorem single_length {n : ℕ} (h : 0 < n) : (single n h).length = 1 := rfl @[simp] theorem single_blocks {n : ℕ} (h : 0 < n) : (single n h).blocks = [n] := rfl @[simp] theorem single_blocksFun {n : ℕ} (h : 0 < n) (i : Fin (single n h).length) : (single n h).blocksFun i = n := by simp [blocksFun, single] @[simp] theorem single_embedding {n : ℕ} (h : 0 < n) (i : Fin n) : ((single n h).embedding (0 : Fin 1)) i = i := by ext simp theorem eq_single_iff_length {n : ℕ} (h : 0 < n) {c : Composition n} : c = single n h ↔ c.length = 1 := by constructor · intro H rw [H] exact single_length h · intro H ext1 have A : c.blocks.length = 1 := H ▸ c.blocks_length have B : c.blocks.sum = n := c.blocks_sum rw [eq_cons_of_length_one A] at B ⊢ simpa [single_blocks] using B theorem ne_single_iff {n : ℕ} (hn : 0 < n) {c : Composition n} : c ≠ single n hn ↔ ∀ i, c.blocksFun i < n := by rw [← not_iff_not] push_neg constructor · rintro rfl exact ⟨⟨0, by simp⟩, by simp⟩ · rintro ⟨i, hi⟩ rw [eq_single_iff_length] have : ∀ j : Fin c.length, j = i := by intro j by_contra ji apply lt_irrefl (∑ k, c.blocksFun k) calc ∑ k, c.blocksFun k ≤ c.blocksFun i := by simp only [c.sum_blocksFun, hi] _ < ∑ k, c.blocksFun k := Finset.single_lt_sum ji (Finset.mem_univ _) (Finset.mem_univ _) (c.one_le_blocksFun j) fun _ _ _ => zero_le _ simpa using Fintype.card_eq_one_of_forall_eq this variable {m : ℕ} /-- Change `n` in `(c : Composition n)` to a propositionally equal value. -/ @[simps] protected def cast (c : Composition m) (hmn : m = n) : Composition n where __ := c blocks_sum := c.blocks_sum.trans hmn @[simp] theorem cast_rfl (c : Composition n) : c.cast rfl = c := rfl theorem cast_heq (c : Composition m) (hmn : m = n) : c.cast hmn ≍ c := by subst m; rfl theorem cast_eq_cast (c : Composition m) (hmn : m = n) : c.cast hmn = cast (hmn ▸ rfl) c := by subst m rfl /-- Append two compositions to get a composition of the sum of numbers. -/ @[simps] def append (c₁ : Composition m) (c₂ : Composition n) : Composition (m + n) where blocks := c₁.blocks ++ c₂.blocks blocks_pos := by intro i hi rw [mem_append] at hi exact hi.elim c₁.blocks_pos c₂.blocks_pos blocks_sum := by simp /-- Reverse the order of blocks in a composition. -/ @[simps] def reverse (c : Composition n) : Composition n where blocks := c.blocks.reverse blocks_pos hi := c.blocks_pos (mem_reverse.mp hi) blocks_sum := by simp [List.sum_reverse] @[simp] lemma reverse_reverse (c : Composition n) : c.reverse.reverse = c := Composition.ext <| List.reverse_reverse _ lemma reverse_involutive : Function.Involutive (@reverse n) := reverse_reverse lemma reverse_bijective : Function.Bijective (@reverse n) := reverse_involutive.bijective lemma reverse_injective : Function.Injective (@reverse n) := reverse_involutive.injective lemma reverse_surjective : Function.Surjective (@reverse n) := reverse_involutive.surjective @[simp] lemma reverse_inj {c₁ c₂ : Composition n} : c₁.reverse = c₂.reverse ↔ c₁ = c₂ := reverse_injective.eq_iff @[simp] lemma reverse_ones : (ones n).reverse = ones n := by ext1; simp @[simp] lemma reverse_single (hn : 0 < n) : (single n hn).reverse = single n hn := by ext1; simp @[simp] lemma reverse_eq_ones {c : Composition n} : c.reverse = ones n ↔ c = ones n := reverse_injective.eq_iff' reverse_ones @[simp] lemma reverse_eq_single {hn : 0 < n} {c : Composition n} : c.reverse = single n hn ↔ c = single n hn := reverse_injective.eq_iff' <| reverse_single _ lemma reverse_append (c₁ : Composition m) (c₂ : Composition n) : reverse (append c₁ c₂) = (append c₂.reverse c₁.reverse).cast (add_comm _ _) := Composition.ext <| by simp /-- Induction (recursion) principle on `c : Composition _` that corresponds to the usual induction on the list of blocks of `c`. -/ @[elab_as_elim] def recOnSingleAppend {motive : ∀ n, Composition n → Sort*} {n : ℕ} (c : Composition n) (zero : motive 0 (ones 0)) (single_append : ∀ k n c, motive n c → motive (k + 1 + n) (append (single (k + 1) k.succ_pos) c)) : motive n c := match n, c with | _, ⟨blocks, blocks_pos, rfl⟩ => match blocks with | [] => zero | 0 :: _ => by simp at blocks_pos | (k + 1) :: l => single_append k l.sum ⟨l, fun hi ↦ blocks_pos <| mem_cons_of_mem _ hi, rfl⟩ <| recOnSingleAppend _ zero single_append decreasing_by simp /-- Induction (recursion) principle on `c : Composition _` that corresponds to the reverse induction on the list of blocks of `c`. -/ @[elab_as_elim] def recOnAppendSingle {motive : ∀ n, Composition n → Sort*} {n : ℕ} (c : Composition n) (zero : motive 0 (ones 0)) (append_single : ∀ k n c, motive n c → motive (n + (k + 1)) (append c (single (k + 1) k.succ_pos))) : motive n c := reverse_reverse c ▸ c.reverse.recOnSingleAppend zero fun k n c ih ↦ by convert append_single k n c.reverse ih using 1 · apply add_comm · rw [reverse_append, reverse_single] apply cast_heq end Composition /-! ### Splitting a list Given a list of length `n` and a composition `c` of `n`, one can split `l` into `c.length` sublists of respective lengths `c.blocksFun 0`, ..., `c.blocksFun (c.length-1)`. This is inverse to the join operation. -/ namespace List variable {α : Type*} /-- Auxiliary for `List.splitWrtComposition`. -/ def splitWrtCompositionAux : List α → List ℕ → List (List α) | _, [] => [] | l, n::ns => let (l₁, l₂) := l.splitAt n l₁::splitWrtCompositionAux l₂ ns /-- Given a list of length `n` and a composition `[i₁, ..., iₖ]` of `n`, split `l` into a list of `k` lists corresponding to the blocks of the composition, of respective lengths `i₁`, ..., `iₖ`. This makes sense mostly when `n = l.length`, but this is not necessary for the definition. -/ def splitWrtComposition (l : List α) (c : Composition n) : List (List α) := splitWrtCompositionAux l c.blocks @[local simp] theorem splitWrtCompositionAux_cons (l : List α) (n ns) : l.splitWrtCompositionAux (n::ns) = take n l::(drop n l).splitWrtCompositionAux ns := by simp [splitWrtCompositionAux] theorem length_splitWrtCompositionAux (l : List α) (ns) : length (l.splitWrtCompositionAux ns) = ns.length := by induction ns generalizing l · simp [splitWrtCompositionAux, *] · simp [*] /-- When one splits a list along a composition `c`, the number of sublists thus created is `c.length`. -/ @[simp] theorem length_splitWrtComposition (l : List α) (c : Composition n) : length (l.splitWrtComposition c) = c.length := length_splitWrtCompositionAux _ _ theorem map_length_splitWrtCompositionAux {ns : List ℕ} : ∀ {l : List α}, ns.sum ≤ l.length → map length (l.splitWrtCompositionAux ns) = ns := by induction ns with | nil => simp [splitWrtCompositionAux] | cons n ns IH => grind [splitWrtCompositionAux_cons] /-- When one splits a list along a composition `c`, the lengths of the sublists thus created are given by the block sizes in `c`. -/ theorem map_length_splitWrtComposition (l : List α) (c : Composition l.length) : map length (l.splitWrtComposition c) = c.blocks := map_length_splitWrtCompositionAux (le_of_eq c.blocks_sum) theorem length_pos_of_mem_splitWrtComposition {l l' : List α} {c : Composition l.length} (h : l' ∈ l.splitWrtComposition c) : 0 < length l' := by have : l'.length ∈ (l.splitWrtComposition c).map List.length := List.mem_map_of_mem h rw [map_length_splitWrtComposition] at this exact c.blocks_pos this theorem sum_take_map_length_splitWrtComposition (l : List α) (c : Composition l.length) (i : ℕ) : (((l.splitWrtComposition c).map length).take i).sum = c.sizeUpTo i := by congr exact map_length_splitWrtComposition l c theorem getElem_splitWrtCompositionAux (l : List α) (ns : List ℕ) {i : ℕ} (hi : i < (l.splitWrtCompositionAux ns).length) : (l.splitWrtCompositionAux ns)[i] = (l.take (ns.take (i + 1)).sum).drop (ns.take i).sum := by induction ns generalizing l i with | nil => cases hi | cons n ns IH => rcases i with - | i · simp · simp only [splitWrtCompositionAux, getElem_cons_succ, IH, take, sum_cons, splitAt_eq, drop_take, drop_drop] rw [Nat.add_sub_add_left] /-- The `i`-th sublist in the splitting of a list `l` along a composition `c`, is the slice of `l` between the indices `c.sizeUpTo i` and `c.sizeUpTo (i+1)`, i.e., the indices in the `i`-th block of the composition. -/ theorem getElem_splitWrtComposition' (l : List α) (c : Composition n) {i : ℕ} (hi : i < (l.splitWrtComposition c).length) : (l.splitWrtComposition c)[i] = (l.take (c.sizeUpTo (i + 1))).drop (c.sizeUpTo i) := getElem_splitWrtCompositionAux _ _ hi theorem getElem_splitWrtComposition (l : List α) (c : Composition n) (i : Nat) (h : i < (l.splitWrtComposition c).length) : (l.splitWrtComposition c)[i] = (l.take (c.sizeUpTo (i + 1))).drop (c.sizeUpTo i) := getElem_splitWrtComposition' _ _ h theorem flatten_splitWrtCompositionAux {ns : List ℕ} : ∀ {l : List α}, ns.sum = l.length → (l.splitWrtCompositionAux ns).flatten = l := by induction ns with | nil => exact fun h ↦ (length_eq_zero_iff.1 h.symm).symm | cons n ns IH => intro l h; rw [sum_cons] at h simp only [splitWrtCompositionAux_cons]; dsimp rw [IH] · simp · rw [length_drop, ← h, add_tsub_cancel_left] /-- If one splits a list along a composition, and then flattens the sublists, one gets back the original list. -/ @[simp] theorem flatten_splitWrtComposition (l : List α) (c : Composition l.length) : (l.splitWrtComposition c).flatten = l := flatten_splitWrtCompositionAux c.blocks_sum /-- If one joins a list of lists and then splits the flattening along the right composition, one gets back the original list of lists. -/ @[simp] theorem splitWrtComposition_flatten (L : List (List α)) (c : Composition L.flatten.length) (h : map length L = c.blocks) : splitWrtComposition (flatten L) c = L := by simp only [and_self_iff, eq_iff_flatten_eq, flatten_splitWrtComposition, map_length_splitWrtComposition, h] end List /-! ### Compositions as sets Combinatorial viewpoints on compositions, seen as finite subsets of `Fin (n+1)` containing `0` and `n`, where the points of the set (other than `n`) correspond to the leftmost points of each block. -/ /-- Bijection between compositions of `n` and subsets of `{0, ..., n-2}`, defined by considering the restriction of the subset to `{1, ..., n-1}` and shifting to the left by one. -/ def compositionAsSetEquiv (n : ℕ) : CompositionAsSet n ≃ Finset (Fin (n - 1)) where toFun c := { i : Fin (n - 1) | (⟨1 + (i : ℕ), by omega⟩ : Fin n.succ) ∈ c.boundaries }.toFinset invFun s := { boundaries := { i : Fin n.succ | i = 0 ∨ i = Fin.last n ∨ ∃ (j : Fin (n - 1)) (_hj : j ∈ s), (i : ℕ) = j + 1 }.toFinset zero_mem := by simp getLast_mem := by simp } left_inv := by intro c ext i simp only [add_comm, Set.toFinset_setOf, Finset.mem_univ, Finset.mem_filter, true_and, exists_prop] constructor · rintro (rfl | rfl | ⟨j, hj1, hj2⟩) · exact c.zero_mem · exact c.getLast_mem · convert hj1 · simp only [or_iff_not_imp_left, ← ne_eq, ← Fin.exists_succ_eq] rintro i_mem ⟨j, rfl⟩ i_ne_last rcases Nat.exists_add_one_eq.mpr j.pos with ⟨n, rfl⟩ obtain ⟨k, rfl⟩ : ∃ k : Fin n, k.castSucc = j := by simpa [Fin.exists_castSucc_eq] using i_ne_last use k simpa using i_mem right_inv := by intro s ext i have : (i : ℕ) + 1 ≠ n := by cutsat simp_rw [add_comm, Fin.ext_iff, Fin.val_zero, Fin.val_last, exists_prop, Set.toFinset_setOf, Finset.mem_filter_univ, reduceCtorEq, this, false_or, add_left_inj, ← Fin.ext_iff, exists_eq_right'] instance compositionAsSetFintype (n : ℕ) : Fintype (CompositionAsSet n) := Fintype.ofEquiv _ (compositionAsSetEquiv n).symm theorem compositionAsSet_card (n : ℕ) : Fintype.card (CompositionAsSet n) = 2 ^ (n - 1) := by have : Fintype.card (Finset (Fin (n - 1))) = 2 ^ (n - 1) := by simp rw [← this] exact Fintype.card_congr (compositionAsSetEquiv n) namespace CompositionAsSet variable (c : CompositionAsSet n) theorem boundaries_nonempty : c.boundaries.Nonempty := ⟨0, c.zero_mem⟩ theorem card_boundaries_pos : 0 < Finset.card c.boundaries := Finset.card_pos.mpr c.boundaries_nonempty /-- Number of blocks in a `CompositionAsSet`. -/ def length : ℕ := Finset.card c.boundaries - 1 theorem card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := (tsub_eq_iff_eq_add_of_le (Nat.succ_le_of_lt c.card_boundaries_pos)).mp rfl theorem length_lt_card_boundaries : c.length < c.boundaries.card := by rw [c.card_boundaries_eq_succ_length] exact Nat.lt_add_one _ theorem lt_length (i : Fin c.length) : (i : ℕ) + 1 < c.boundaries.card := lt_tsub_iff_right.mp i.2 theorem lt_length' (i : Fin c.length) : (i : ℕ) < c.boundaries.card := lt_of_le_of_lt (Nat.le_succ i) (c.lt_length i) /-- Canonical increasing bijection from `Fin c.boundaries.card` to `c.boundaries`. -/ def boundary : Fin c.boundaries.card ↪o Fin (n + 1) := c.boundaries.orderEmbOfFin rfl @[simp] theorem boundary_zero : (c.boundary ⟨0, c.card_boundaries_pos⟩ : Fin (n + 1)) = 0 := by rw [boundary, Finset.orderEmbOfFin_zero rfl c.card_boundaries_pos] exact le_antisymm (Finset.min'_le _ _ c.zero_mem) (Fin.zero_le _) @[simp] theorem boundary_length : c.boundary ⟨c.length, c.length_lt_card_boundaries⟩ = Fin.last n := by convert Finset.orderEmbOfFin_last rfl c.card_boundaries_pos exact le_antisymm (Finset.le_max' _ _ c.getLast_mem) (Fin.le_last _) /-- Size of the `i`-th block in a `CompositionAsSet`, seen as a function on `Fin c.length`. -/ def blocksFun (i : Fin c.length) : ℕ := c.boundary ⟨(i : ℕ) + 1, c.lt_length i⟩ - c.boundary ⟨i, c.lt_length' i⟩ theorem blocksFun_pos (i : Fin c.length) : 0 < c.blocksFun i := haveI : (⟨i, c.lt_length' i⟩ : Fin c.boundaries.card) < ⟨i + 1, c.lt_length i⟩ := Nat.lt_succ_self _ lt_tsub_iff_left.mpr ((c.boundaries.orderEmbOfFin rfl).strictMono this) /-- List of the sizes of the blocks in a `CompositionAsSet`. -/ def blocks (c : CompositionAsSet n) : List ℕ := ofFn c.blocksFun @[simp] theorem blocks_length : c.blocks.length = c.length := length_ofFn theorem blocks_partial_sum {i : ℕ} (h : i < c.boundaries.card) : (c.blocks.take i).sum = c.boundary ⟨i, h⟩ := by induction i with | zero => simp | succ i IH => have A : i < c.blocks.length := by rw [c.card_boundaries_eq_succ_length] at h simp [blocks, Nat.lt_of_succ_lt_succ h] have B : i < c.boundaries.card := lt_of_lt_of_le A (by simp [blocks, length]) rw [sum_take_succ _ _ A, IH B] simp [blocks, blocksFun] theorem mem_boundaries_iff_exists_blocks_sum_take_eq {j : Fin (n + 1)} : j ∈ c.boundaries ↔ ∃ i < c.boundaries.card, (c.blocks.take i).sum = j := by constructor · intro hj rcases (c.boundaries.orderIsoOfFin rfl).surjective ⟨j, hj⟩ with ⟨i, hi⟩ rw [Subtype.ext_iff, Subtype.coe_mk] at hi refine ⟨i.1, i.2, ?_⟩ dsimp at hi rw [← hi, c.blocks_partial_sum i.2] rfl · rintro ⟨i, hi, H⟩ convert (c.boundaries.orderIsoOfFin rfl ⟨i, hi⟩).2 have : c.boundary ⟨i, hi⟩ = j := by rwa [Fin.ext_iff, ← c.blocks_partial_sum hi] exact this.symm theorem blocks_sum : c.blocks.sum = n := by have : c.blocks.take c.length = c.blocks := take_of_length_le (by simp [blocks]) rw [← this, c.blocks_partial_sum c.length_lt_card_boundaries, c.boundary_length] rfl /-- Associating a `Composition n` to a `CompositionAsSet n`, by registering the sizes of the blocks as a list of positive integers. -/ def toComposition : Composition n where blocks := c.blocks blocks_pos := by simp only [blocks, forall_mem_ofFn_iff, blocksFun_pos c, forall_true_iff] blocks_sum := c.blocks_sum end CompositionAsSet /-! ### Equivalence between compositions and compositions as sets In this section, we explain how to go back and forth between a `Composition` and a `CompositionAsSet`, by showing that their `blocks` and `length` and `boundaries` correspond to each other, and construct an equivalence between them called `compositionEquiv`. -/ @[simp] theorem Composition.toCompositionAsSet_length (c : Composition n) : c.toCompositionAsSet.length = c.length := by simp [Composition.toCompositionAsSet, CompositionAsSet.length, c.card_boundaries_eq_succ_length] @[simp] theorem CompositionAsSet.toComposition_length (c : CompositionAsSet n) : c.toComposition.length = c.length := by simp [CompositionAsSet.toComposition, Composition.length] @[simp] theorem Composition.toCompositionAsSet_blocks (c : Composition n) : c.toCompositionAsSet.blocks = c.blocks := by let d := c.toCompositionAsSet change d.blocks = c.blocks have length_eq : d.blocks.length = c.blocks.length := by simp [d, blocks_length] suffices H : ∀ i ≤ d.blocks.length, (d.blocks.take i).sum = (c.blocks.take i).sum from eq_of_sum_take_eq length_eq H intro i hi have i_lt : i < d.boundaries.card := by simpa [CompositionAsSet.blocks, length_ofFn, d.card_boundaries_eq_succ_length] using Nat.lt_succ_iff.2 hi have i_lt' : i < c.boundaries.card := i_lt have i_lt'' : i < c.length + 1 := by rwa [c.card_boundaries_eq_succ_length] at i_lt' have A : d.boundaries.orderEmbOfFin rfl ⟨i, i_lt⟩ = c.boundaries.orderEmbOfFin c.card_boundaries_eq_succ_length ⟨i, i_lt''⟩ := rfl have B : c.sizeUpTo i = c.boundary ⟨i, i_lt''⟩ := rfl rw [d.blocks_partial_sum i_lt, CompositionAsSet.boundary, ← Composition.sizeUpTo, B, A, c.orderEmbOfFin_boundaries] @[simp] theorem CompositionAsSet.toComposition_blocks (c : CompositionAsSet n) : c.toComposition.blocks = c.blocks := rfl @[simp] theorem CompositionAsSet.toComposition_boundaries (c : CompositionAsSet n) : c.toComposition.boundaries = c.boundaries := by ext ⟨j, hj⟩ simp [c.mem_boundaries_iff_exists_blocks_sum_take_eq, Composition.boundaries, c.card_boundaries_eq_succ_length, Composition.boundary, Composition.sizeUpTo, Fin.exists_iff] @[simp] theorem Composition.toCompositionAsSet_boundaries (c : Composition n) : c.toCompositionAsSet.boundaries = c.boundaries := rfl /-- Equivalence between `Composition n` and `CompositionAsSet n`. -/ def compositionEquiv (n : ℕ) : Composition n ≃ CompositionAsSet n where toFun c := c.toCompositionAsSet invFun c := c.toComposition left_inv c := by ext1 exact c.toCompositionAsSet_blocks right_inv c := by ext1 exact c.toComposition_boundaries instance compositionFintype (n : ℕ) : Fintype (Composition n) := Fintype.ofEquiv _ (compositionEquiv n).symm theorem composition_card (n : ℕ) : Fintype.card (Composition n) = 2 ^ (n - 1) := by rw [← compositionAsSet_card n] exact Fintype.card_congr (compositionEquiv n)
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/Bell.lean
import Mathlib.Data.Nat.Choose.Multinomial import Mathlib.Data.Nat.Choose.Mul /-! # Bell numbers for multisets For `n : ℕ`, the `n`th Bell number is the number of partitions of a set of cardinality `n`. Here, we define a refinement of these numbers, that count, for any `m : Multiset ℕ`, the number of partitions of a set of cardinality `m.sum` whose parts have cardinalities given by `m`. The definition presents it as a natural number. * `Multiset.bell`: number of partitions of a set whose parts have cardinalities a given multiset * `Nat.uniformBell m n` : short name for `Multiset.bell (replicate m n)` * `Multiset.bell_mul_eq` shows that `m.bell * (m.map (fun j ↦ j !)).prod * Π j ∈ (m.toFinset.erase 0), (m.count j)! = m.sum !` * `Nat.uniformBell_mul_eq` shows that `uniformBell m n * n ! ^ m * m ! = (m * n) !` * `Nat.uniformBell_succ_left` computes `Nat.uniformBell (m + 1) n` from `Nat.uniformBell m n` * `Nat.bell n`: the `n`th standard Bell number, which counts the number of partitions of a set of cardinality `n` * `Nat.bell_succ n` shows that `Nat.bell (n + 1) = ∑ k ∈ Finset.range (n + 1), Nat.choose n k * Nat.bell (n - k)` ## TODO Prove that it actually counts the number of partitions as indicated. (When `m` contains `0`, the result requires to admit repetitions of the empty set as a part.) -/ open Multiset Nat namespace Multiset /-- Number of partitions of a set of cardinality `m.sum` whose parts have cardinalities given by `m` -/ def bell (m : Multiset ℕ) : ℕ := Nat.multinomial m.toFinset (fun k ↦ k * m.count k) * ∏ k ∈ m.toFinset.erase 0, ∏ j ∈ .range (m.count k), (j * k + k - 1).choose (k - 1) @[simp] theorem bell_zero : bell 0 = 1 := rfl private theorem bell_mul_eq_lemma {x : ℕ} (hx : x ≠ 0) : ∀ c, x ! ^ c * c ! * ∏ j ∈ Finset.range c, (j * x + x - 1).choose (x - 1) = (x * c)! | 0 => by simp | c + 1 => calc x ! ^ (c + 1) * (c + 1)! * ∏ j ∈ Finset.range (c + 1), (j * x + x - 1).choose (x - 1) = x ! * (c + 1) * x ! ^ c * c ! * ∏ j ∈ Finset.range (c + 1), (j * x + x - 1).choose (x - 1) := by rw [factorial_succ, pow_succ]; ring _ = (x ! ^ c * c ! * ∏ j ∈ Finset.range c, (j * x + x - 1).choose (x - 1)) * (c * x + x - 1).choose (x - 1) * x ! * (c + 1) := by rw [Finset.prod_range_succ]; ring _ = (c + 1) * (c * x + x - 1).choose (x - 1) * (x * c)! * x ! := by rw [bell_mul_eq_lemma hx]; ring _ = (x * (c + 1))! := by rw [← Nat.choose_mul_add hx, mul_comm c x, Nat.add_choose_mul_factorial_mul_factorial] ring_nf theorem bell_mul_eq (m : Multiset ℕ) : m.bell * (m.map (fun j ↦ j !)).prod * ∏ j ∈ (m.toFinset.erase 0), (m.count j)! = m.sum ! := by unfold bell rw [← Nat.mul_right_inj (a := ∏ i ∈ m.toFinset, (i * count i m)!) (by positivity)] simp only [← mul_assoc] rw [Nat.multinomial_spec] simp only [mul_assoc] rw [mul_comm] apply congr_arg₂ · rw [mul_comm, mul_assoc, ← Finset.prod_mul_distrib, Finset.prod_multiset_map_count] suffices this : _ by by_cases hm : 0 ∈ m.toFinset · rw [← Finset.prod_erase_mul _ _ hm] rw [← Finset.prod_erase_mul _ _ hm] simp only [factorial_zero, one_pow, mul_one, zero_mul] exact this · nth_rewrite 1 [← Finset.erase_eq_of_notMem hm] nth_rewrite 3 [← Finset.erase_eq_of_notMem hm] exact this rw [← Finset.prod_mul_distrib] apply Finset.prod_congr rfl intro x hx rw [← mul_assoc, bell_mul_eq_lemma] simp only [Finset.mem_erase, ne_eq, mem_toFinset] at hx simp only [ne_eq, hx.1, not_false_eq_true] · apply congr_arg rw [Finset.sum_multiset_count] simp only [smul_eq_mul, mul_comm] theorem bell_eq (m : Multiset ℕ) : m.bell = m.sum ! / ((m.map (fun j ↦ j !)).prod * ∏ j ∈ (m.toFinset.erase 0), (m.count j)!) := by rw [← Nat.mul_left_inj, Nat.div_mul_cancel _] · rw [← mul_assoc] exact bell_mul_eq m · rw [← bell_mul_eq, mul_assoc] apply Nat.dvd_mul_left · rw [← Nat.pos_iff_ne_zero] apply Nat.mul_pos · simp only [CanonicallyOrderedAdd.multiset_prod_pos, mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] exact fun _ _ ↦ Nat.factorial_pos _ · apply Finset.prod_pos exact fun _ _ ↦ Nat.factorial_pos _ end Multiset namespace Nat /-- Number of possibilities of dividing a set with `m * n` elements into `m` groups of `n`-element subsets. -/ def uniformBell (m n : ℕ) : ℕ := bell (replicate m n) theorem uniformBell_eq (m n : ℕ) : m.uniformBell n = ∏ p ∈ (Finset.range m), Nat.choose (p * n + n - 1) (n - 1) := by unfold uniformBell bell rw [toFinset_replicate] split_ifs with hm · simp [hm] · by_cases hn : n = 0 · simp [hn] · rw [show ({n} : Finset ℕ).erase 0 = {n} by simp [Ne.symm hn]] simp [count_replicate] theorem uniformBell_zero_left (n : ℕ) : uniformBell 0 n = 1 := by simp [uniformBell_eq] theorem uniformBell_zero_right (m : ℕ) : uniformBell m 0 = 1 := by simp [uniformBell_eq] theorem uniformBell_succ_left (m n : ℕ) : uniformBell (m+1) n = choose (m * n + n - 1) (n - 1) * uniformBell m n := by simp only [uniformBell_eq, Finset.prod_range_succ, mul_comm] theorem uniformBell_one_left (n : ℕ) : uniformBell 1 n = 1 := by simp only [uniformBell_eq, Finset.range_one, Finset.prod_singleton, zero_mul, zero_add, choose_self] theorem uniformBell_one_right (m : ℕ) : uniformBell m 1 = 1 := by simp only [uniformBell_eq, mul_one, add_tsub_cancel_right, le_refl, tsub_eq_zero_of_le, choose_zero_right, Finset.prod_const_one] theorem uniformBell_mul_eq (m : ℕ) {n : ℕ} (hn : n ≠ 0) : uniformBell m n * n ! ^ m * m ! = (m * n)! := by convert bell_mul_eq (replicate m n) · simp only [map_replicate, prod_replicate] · simp only [toFinset_replicate] split_ifs with hm · rw [hm, factorial_zero, eq_comm] rw [show (∅ : Finset ℕ).erase 0 = ∅ from rfl, Finset.prod_empty] · rw [show ({n} : Finset ℕ).erase 0 = {n} by simp [Ne.symm hn]] simp only [Finset.prod_singleton, count_replicate_self] · simp theorem uniformBell_eq_div (m : ℕ) {n : ℕ} (hn : n ≠ 0) : uniformBell m n = (m * n) ! / (n ! ^ m * m !) := by rw [eq_comm] apply Nat.div_eq_of_eq_mul_left · exact Nat.mul_pos (Nat.pow_pos (Nat.factorial_pos n)) m.factorial_pos · rw [← mul_assoc, ← uniformBell_mul_eq _ hn] /-- The `n`th standard Bell number, which counts the number of partitions of a set of cardinality `n`. ## TODO Prove that `Nat.bell n` is equal to the sum of `Multiset.bell m` over all multisets `m : Multiset ℕ` such that `m.sum = n`. -/ protected def bell : ℕ → ℕ | 0 => 1 | n + 1 => ∑ i : Fin n.succ, choose n i * Nat.bell (n - i) theorem bell_succ (n : ℕ) : Nat.bell (n + 1) = ∑ i : Fin n.succ, Nat.choose n i * Nat.bell (n - i) := by rw [Nat.bell] theorem bell_succ' (n : ℕ) : Nat.bell (n + 1) = ∑ ij ∈ Finset.antidiagonal n, Nat.choose n ij.1 * Nat.bell ij.2 := by rw [Nat.bell_succ, Finset.Nat.sum_antidiagonal_eq_sum_range_succ (fun x y => Nat.choose n x * Nat.bell y) n, Finset.sum_range] @[simp] theorem bell_zero : Nat.bell 0 = 1 := by simp [Nat.bell] @[simp] theorem bell_one : Nat.bell 1 = 1 := by simp [Nat.bell] @[simp] theorem bell_two : Nat.bell 2 = 2 := by simp [Nat.bell] end Nat
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/Partition.lean
import Mathlib.Combinatorics.Enumerative.Partition.Basic deprecated_module (since := "2025-11-15")
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/IncidenceAlgebra.lean
import Mathlib.Algebra.Algebra.Defs import Mathlib.Algebra.BigOperators.Ring.Finset import Mathlib.Algebra.Module.BigOperators import Mathlib.Algebra.Module.Pi import Mathlib.Algebra.Order.BigOperators.Group.LocallyFinite /-! # Incidence algebras Given a locally finite order `α` the incidence algebra over `α` is the type of functions from non-empty intervals of `α` to some algebraic codomain. This algebra has a natural multiplication operation whereby the product of two such functions is defined on an interval by summing over all divisions into two subintervals the product of the values of the original pair of functions. This structure allows us to interpret many natural invariants of the intervals (such as their cardinality) as elements of the incidence algebra. For instance the cardinality function, viewed as an element of the incidence algebra, is simply the square of the function that takes constant value one on all intervals. This constant function is called the zeta function, after its connection with the Riemann zeta function. The incidence algebra is a good setting for proving many inclusion-exclusion type principles, these go under the name Möbius inversion, and are essentially due to the fact that the zeta function has a multiplicative inverse in the incidence algebra, an inductively definable function called the Möbius function that generalizes the Möbius function in number theory. ## Main definitions * `1 : IncidenceAlgebra 𝕜 α` is the delta function, defined analogously to the identity matrix. * `f * g` is the incidence algebra product, defined analogously to the matrix product. * `IncidenceAlgebra.zeta` is the zeta function, defined analogously to the upper triangular matrix of ones. * `IncidenceAlgebra.mu` is the inverse of the zeta function. ## Implementation notes One has to define `mu` as either the left or right inverse of `zeta`. We define it as the left inverse, and prove it is also a right inverse by defining `mu'` as the right inverse and using that left and right inverses agree if they exist. ## TODOs Here are some additions to this file that could be made in the future: - Generalize the construction of `mu` to invert any element of the incidence algebra `f` which has `f x x` a unit for all `x`. - Give formulas for higher powers of zeta. - A formula for the möbius function on a pi type similar to the one for products - More examples / applications to different posets. - Connection with Galois insertions - Finsum version of Möbius inversion that holds even when an order doesn't have top/bot? - Connect this theory to (infinite) matrices, giving maps of the incidence algebra to matrix rings - Connect to the more advanced theory of arithmetic functions, and Dirichlet convolution. ## References * [Aigner, *Combinatorial Theory, Chapter IV*][aigner1997] * [Jacobson, *Basic Algebra I, 8.6*][jacobson1974] * [Doubilet, Rota, Stanley, *On the foundations of Combinatorial Theory VI*][doubilet_rota_stanley_vi] * [Spiegel, O'Donnell, *Incidence Algebras*][spiegel_odonnel1997] * [Kung, Rota, Yan, *Combinatorics: The Rota Way, Chapter 3*][kung_rota_yan2009] -/ open Finset OrderDual variable {F 𝕜 𝕝 𝕞 α β : Type*} /-- The `𝕜`-incidence algebra over `α`. -/ structure IncidenceAlgebra (𝕜 α : Type*) [Zero 𝕜] [LE α] where /-- The underlying function of an element of the incidence algebra. Do not use this function directly. Instead use the coercion coming from the `FunLike` instance. -/ toFun : α → α → 𝕜 eq_zero_of_not_le' ⦃a b : α⦄ : ¬a ≤ b → toFun a b = 0 namespace IncidenceAlgebra section Zero variable [Zero 𝕜] [LE α] {a b : α} instance instFunLike : FunLike (IncidenceAlgebra 𝕜 α) α (α → 𝕜) where coe := toFun coe_injective' f g h := by cases f; cases g; congr lemma apply_eq_zero_of_not_le (h : ¬a ≤ b) (f : IncidenceAlgebra 𝕜 α) : f a b = 0 := eq_zero_of_not_le' _ h lemma le_of_ne_zero {f : IncidenceAlgebra 𝕜 α} : f a b ≠ 0 → a ≤ b := not_imp_comm.1 fun h ↦ apply_eq_zero_of_not_le h _ section Coes -- this must come after the `FunLike` instance initialize_simps_projections IncidenceAlgebra (toFun → apply) @[simp] lemma toFun_eq_coe (f : IncidenceAlgebra 𝕜 α) : f.toFun = f := rfl @[simp, norm_cast] lemma coe_mk (f : α → α → 𝕜) (h) : (mk f h : α → α → 𝕜) = f := rfl lemma coe_inj {f g : IncidenceAlgebra 𝕜 α} : (f : α → α → 𝕜) = g ↔ f = g := DFunLike.coe_injective.eq_iff @[ext] lemma ext ⦃f g : IncidenceAlgebra 𝕜 α⦄ (h : ∀ a b, a ≤ b → f a b = g a b) : f = g := by refine DFunLike.coe_injective' (funext₂ fun a b ↦ ?_) by_cases hab : a ≤ b · exact h _ _ hab · rw [apply_eq_zero_of_not_le hab, apply_eq_zero_of_not_le hab] @[simp] lemma mk_coe (f : IncidenceAlgebra 𝕜 α) (h) : mk f h = f := rfl end Coes /-! ### Additive and multiplicative structure -/ instance instZero : Zero (IncidenceAlgebra 𝕜 α) := ⟨⟨fun _ _ ↦ 0, fun _ _ _ ↦ rfl⟩⟩ instance instInhabited : Inhabited (IncidenceAlgebra 𝕜 α) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ⇑(0 : IncidenceAlgebra 𝕜 α) = 0 := rfl lemma zero_apply (a b : α) : (0 : IncidenceAlgebra 𝕜 α) a b = 0 := rfl end Zero section Add variable [AddZeroClass 𝕜] [LE α] instance instAdd : Add (IncidenceAlgebra 𝕜 α) where add f g := ⟨f + g, fun a b h ↦ by simp_rw [Pi.add_apply, apply_eq_zero_of_not_le h, zero_add]⟩ @[simp, norm_cast] lemma coe_add (f g : IncidenceAlgebra 𝕜 α) : ⇑(f + g) = f + g := rfl lemma add_apply (f g : IncidenceAlgebra 𝕜 α) (a b : α) : (f + g) a b = f a b + g a b := rfl end Add section Smul variable {M : Type*} [Zero 𝕜] [LE α] [SMulZeroClass M 𝕜] instance instSmulZeroClassRight : SMulZeroClass M (IncidenceAlgebra 𝕜 α) where smul c f := ⟨c • ⇑f, fun a b hab ↦ by simp_rw [Pi.smul_apply, apply_eq_zero_of_not_le hab, smul_zero]⟩ smul_zero c := by ext; exact smul_zero _ @[simp, norm_cast] lemma coe_constSMul (c : M) (f : IncidenceAlgebra 𝕜 α) : ⇑(c • f) = c • ⇑f := rfl lemma constSMul_apply (c : M) (f : IncidenceAlgebra 𝕜 α) (a b : α) : (c • f) a b = c • f a b := rfl end Smul instance instAddMonoid [AddMonoid 𝕜] [LE α] : AddMonoid (IncidenceAlgebra 𝕜 α) := DFunLike.coe_injective.addMonoid _ coe_zero coe_add fun _ _ ↦ rfl instance instAddCommMonoid [AddCommMonoid 𝕜] [LE α] : AddCommMonoid (IncidenceAlgebra 𝕜 α) := DFunLike.coe_injective.addCommMonoid _ coe_zero coe_add fun _ _ ↦ rfl section AddGroup variable [AddGroup 𝕜] [LE α] instance instNeg : Neg (IncidenceAlgebra 𝕜 α) where neg f := ⟨-f, fun a b h ↦ by simp_rw [Pi.neg_apply, apply_eq_zero_of_not_le h, neg_zero]⟩ instance instSub : Sub (IncidenceAlgebra 𝕜 α) where sub f g := ⟨f - g, fun a b h ↦ by simp_rw [Pi.sub_apply, apply_eq_zero_of_not_le h, sub_zero]⟩ @[simp, norm_cast] lemma coe_neg (f : IncidenceAlgebra 𝕜 α) : ⇑(-f) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : IncidenceAlgebra 𝕜 α) : ⇑(f - g) = f - g := rfl lemma neg_apply (f : IncidenceAlgebra 𝕜 α) (a b : α) : (-f) a b = -f a b := rfl lemma sub_apply (f g : IncidenceAlgebra 𝕜 α) (a b : α) : (f - g) a b = f a b - g a b := rfl instance instAddGroup : AddGroup (IncidenceAlgebra 𝕜 α) := DFunLike.coe_injective.addGroup _ coe_zero coe_add coe_neg coe_sub (fun _ _ ↦ rfl) fun _ _ ↦ rfl end AddGroup instance instAddCommGroup [AddCommGroup 𝕜] [LE α] : AddCommGroup (IncidenceAlgebra 𝕜 α) := DFunLike.coe_injective.addCommGroup _ coe_zero coe_add coe_neg coe_sub (fun _ _ ↦ rfl) fun _ _ ↦ rfl section One variable [Preorder α] [DecidableEq α] [Zero 𝕜] [One 𝕜] /-- The unit incidence algebra is the delta function, whose entries are `0` except on the diagonal where they are `1`. -/ instance instOne : One (IncidenceAlgebra 𝕜 α) := ⟨⟨fun a b ↦ if a = b then 1 else 0, fun _a _b h ↦ ite_eq_right_iff.2 fun H ↦ (h H.le).elim⟩⟩ @[simp] lemma one_apply (a b : α) : (1 : IncidenceAlgebra 𝕜 α) a b = if a = b then 1 else 0 := rfl end One section Mul variable [Preorder α] [LocallyFiniteOrder α] [AddCommMonoid 𝕜] [Mul 𝕜] /-- The multiplication operation in incidence algebras is defined on an interval by summing over all divisions into two subintervals the product of the values of the original pair of functions. -/ instance instMul : Mul (IncidenceAlgebra 𝕜 α) where mul f g := ⟨fun a b ↦ ∑ x ∈ Icc a b, f a x * g x b, fun a b h ↦ by dsimp; rw [Icc_eq_empty h, sum_empty]⟩ @[simp] lemma mul_apply (f g : IncidenceAlgebra 𝕜 α) (a b : α) : (f * g) a b = ∑ x ∈ Icc a b, f a x * g x b := rfl end Mul instance instNonUnitalNonAssocSemiring [Preorder α] [LocallyFiniteOrder α] [NonUnitalNonAssocSemiring 𝕜] : NonUnitalNonAssocSemiring (IncidenceAlgebra 𝕜 α) where __ := instAddCommMonoid zero_mul := fun f ↦ by ext; exact sum_eq_zero fun x _ ↦ zero_mul _ mul_zero := fun f ↦ by ext; exact sum_eq_zero fun x _ ↦ mul_zero _ left_distrib := fun f g h ↦ by ext; exact Eq.trans (sum_congr rfl fun x _ ↦ left_distrib _ _ _) sum_add_distrib right_distrib := fun f g h ↦ by ext; exact Eq.trans (sum_congr rfl fun x _ ↦ right_distrib _ _ _) sum_add_distrib instance instNonAssocSemiring [Preorder α] [LocallyFiniteOrder α] [DecidableEq α] [NonAssocSemiring 𝕜] : NonAssocSemiring (IncidenceAlgebra 𝕜 α) where __ := instNonUnitalNonAssocSemiring one_mul := fun f ↦ by ext; simp [*] mul_one := fun f ↦ by ext; simp [*] instance instSemiring [Preorder α] [LocallyFiniteOrder α] [DecidableEq α] [Semiring 𝕜] : Semiring (IncidenceAlgebra 𝕜 α) where __ := instNonAssocSemiring mul_assoc f g h := by ext a b simp only [mul_apply, sum_mul, mul_sum, sum_sigma'] apply sum_nbij' (fun ⟨a, b⟩ ↦ ⟨b, a⟩) (fun ⟨a, b⟩ ↦ ⟨b, a⟩) <;> aesop (add simp mul_assoc) (add unsafe le_trans) instance instRing [Preorder α] [LocallyFiniteOrder α] [DecidableEq α] [Ring 𝕜] : Ring (IncidenceAlgebra 𝕜 α) where __ := instSemiring __ := instAddGroup /-! ### Scalar multiplication between incidence algebras -/ section SMul variable [Preorder α] [LocallyFiniteOrder α] [AddCommMonoid 𝕜] [AddCommMonoid 𝕝] [SMul 𝕜 𝕝] instance instSMul : SMul (IncidenceAlgebra 𝕜 α) (IncidenceAlgebra 𝕝 α) := ⟨fun f g ↦ ⟨fun a b ↦ ∑ x ∈ Icc a b, f a x • g x b, fun a b h ↦ by dsimp; rw [Icc_eq_empty h, sum_empty]⟩⟩ @[simp] lemma smul_apply (f : IncidenceAlgebra 𝕜 α) (g : IncidenceAlgebra 𝕝 α) (a b : α) : (f • g) a b = ∑ x ∈ Icc a b, f a x • g x b := rfl end SMul instance instIsScalarTower [Preorder α] [LocallyFiniteOrder α] [AddCommMonoid 𝕜] [Monoid 𝕜] [Semiring 𝕝] [AddCommMonoid 𝕞] [SMul 𝕜 𝕝] [Module 𝕝 𝕞] [DistribMulAction 𝕜 𝕞] [IsScalarTower 𝕜 𝕝 𝕞] : IsScalarTower (IncidenceAlgebra 𝕜 α) (IncidenceAlgebra 𝕝 α) (IncidenceAlgebra 𝕞 α) where smul_assoc f g h := by ext a b simp only [smul_apply, sum_smul, smul_sum, sum_sigma'] apply sum_nbij' (fun ⟨a, b⟩ ↦ ⟨b, a⟩) (fun ⟨a, b⟩ ↦ ⟨b, a⟩) <;> aesop (add unsafe le_trans) instance [Preorder α] [LocallyFiniteOrder α] [DecidableEq α] [Semiring 𝕜] [Semiring 𝕝] [Module 𝕜 𝕝] : Module (IncidenceAlgebra 𝕜 α) (IncidenceAlgebra 𝕝 α) where one_smul f := by ext a b hab; simp [ite_smul, hab] mul_smul := smul_assoc smul_add f g h := by ext; exact Eq.trans (sum_congr rfl fun x _ ↦ smul_add _ _ _) sum_add_distrib add_smul f g h := by ext; exact Eq.trans (sum_congr rfl fun x _ ↦ add_smul _ _ _) sum_add_distrib zero_smul f := by ext; exact sum_eq_zero fun x _ ↦ zero_smul _ _ smul_zero f := by ext; exact sum_eq_zero fun x _ ↦ smul_zero _ instance smulWithZeroRight [Zero 𝕜] [Zero 𝕝] [SMulWithZero 𝕜 𝕝] [LE α] : SMulWithZero 𝕜 (IncidenceAlgebra 𝕝 α) := DFunLike.coe_injective.smulWithZero ⟨((⇑) : IncidenceAlgebra 𝕝 α → α → α → 𝕝), coe_zero⟩ coe_constSMul instance moduleRight [Preorder α] [Semiring 𝕜] [AddCommMonoid 𝕝] [Module 𝕜 𝕝] : Module 𝕜 (IncidenceAlgebra 𝕝 α) := DFunLike.coe_injective.module _ ⟨⟨((⇑) : IncidenceAlgebra 𝕝 α → α → α → 𝕝), coe_zero⟩, coe_add⟩ coe_constSMul instance algebraRight [PartialOrder α] [LocallyFiniteOrder α] [DecidableEq α] [CommSemiring 𝕜] [CommSemiring 𝕝] [Algebra 𝕜 𝕝] : Algebra 𝕜 (IncidenceAlgebra 𝕝 α) where algebraMap := { toFun c := algebraMap 𝕜 𝕝 c • (1 : IncidenceAlgebra 𝕝 α) map_one' := by ext; simp only [mul_boole, one_apply, Algebra.id.smul_eq_mul, constSMul_apply, map_one] map_mul' c d := by ext a b obtain rfl | h := eq_or_ne a b · simp only [one_apply, Algebra.id.smul_eq_mul, mul_apply, constSMul_apply, map_mul, eq_comm, Icc_self] simp · simp only [one_apply, mul_one, Algebra.id.smul_eq_mul, mul_apply, zero_mul, constSMul_apply, ← ite_and, ite_mul, mul_ite, map_mul, mul_zero, if_neg h] refine (sum_eq_zero fun x _ ↦ ?_).symm exact if_neg fun hx ↦ h <| hx.2.trans hx.1 map_zero' := by rw [map_zero, zero_smul] map_add' c d := by rw [map_add, add_smul] } commutes' c f := by classical ext a b hab; simp [if_pos hab, constSMul_apply, mul_comm] smul_def' c f := by classical ext a b hab; simp [if_pos hab, constSMul_apply, Algebra.smul_def] /-! ### The Lambda function -/ section Lambda variable (𝕜) [Zero 𝕜] [One 𝕜] [Preorder α] [DecidableRel (α := α) (· ⩿ ·)] /-- The lambda function of the incidence algebra is the function that assigns `1` to every nonempty interval of cardinality one or two. -/ @[simps] def lambda : IncidenceAlgebra 𝕜 α := ⟨fun a b ↦ if a ⩿ b then 1 else 0, fun _a _b h ↦ if_neg fun hh ↦ h hh.le⟩ end Lambda /-! ### The Zeta and Möbius functions -/ section Zeta variable (𝕜) [Zero 𝕜] [One 𝕜] [LE α] [DecidableLE α] {a b : α} /-- The zeta function of the incidence algebra is the function that assigns 1 to every nonempty interval, convolution with this function sums functions over intervals. -/ def zeta : IncidenceAlgebra 𝕜 α := ⟨fun a b ↦ if a ≤ b then 1 else 0, fun _a _b h ↦ if_neg h⟩ variable {𝕜} @[simp] lemma zeta_apply (a b : α) : zeta 𝕜 a b = if a ≤ b then 1 else 0 := rfl lemma zeta_of_le (h : a ≤ b) : zeta 𝕜 a b = 1 := if_pos h end Zeta lemma zeta_mul_zeta [NonAssocSemiring 𝕜] [Preorder α] [LocallyFiniteOrder α] [DecidableLE α] (a b : α) : (zeta 𝕜 * zeta 𝕜 : IncidenceAlgebra 𝕜 α) a b = (Icc a b).card := by rw [mul_apply, card_eq_sum_ones, Nat.cast_sum, Nat.cast_one] refine sum_congr rfl fun x hx ↦ ?_ rw [mem_Icc] at hx rw [zeta_of_le hx.1, zeta_of_le hx.2, one_mul] @[deprecated (since := "2025-09-28")] alias zeta_mul_kappa := zeta_mul_zeta section Mu variable (𝕜) [AddCommGroup 𝕜] [One 𝕜] [Preorder α] [LocallyFiniteOrder α] [DecidableEq α] /-- The Möbius function of the incidence algebra as a bare function defined recursively. -/ private def muFun (a : α) : α → 𝕜 | b => if a = b then 1 else -∑ x ∈ (Ico a b).attach, let h := mem_Ico.1 x.2 have : (Icc a x).card < (Icc a b).card := card_lt_card (Icc_ssubset_Icc_right (h.1.trans h.2.le) le_rfl h.2) muFun a x termination_by b => (Icc a b).card private lemma muFun_apply (a b : α) : muFun 𝕜 a b = if a = b then 1 else -∑ x ∈ (Ico a b).attach, muFun 𝕜 a x := by rw [muFun] /-- The Möbius function which inverts `zeta` as an element of the incidence algebra. -/ def mu : IncidenceAlgebra 𝕜 α := ⟨muFun 𝕜, fun a b ↦ not_imp_comm.1 fun h ↦ by rw [muFun_apply] at h split_ifs at h with hab · exact hab.le · rw [neg_eq_zero] at h obtain ⟨⟨x, hx⟩, -⟩ := exists_ne_zero_of_sum_ne_zero h exact (nonempty_Ico.1 ⟨x, hx⟩).le⟩ variable {𝕜} {a b : α} lemma mu_apply (a b : α) : mu 𝕜 a b = if a = b then 1 else -∑ x ∈ Ico a b, mu 𝕜 a x := by rw [mu, coe_mk, muFun_apply, sum_attach] @[simp] lemma mu_self (a : α) : mu 𝕜 a a = 1 := by simp [mu_apply] lemma mu_eq_neg_sum_Ico_of_ne (hab : a ≠ b) : mu 𝕜 a b = -∑ x ∈ Ico a b, mu 𝕜 a x := by rw [mu_apply, if_neg hab] variable (𝕜 α) /-- The Euler characteristic of a finite bounded order. -/ def eulerChar [BoundedOrder α] : 𝕜 := mu 𝕜 (⊥ : α) ⊤ end Mu section MuSpec variable [AddCommGroup 𝕜] [One 𝕜] [PartialOrder α] [LocallyFiniteOrder α] [DecidableEq α] lemma sum_Icc_mu_right (a b : α) : ∑ x ∈ Icc a b, mu 𝕜 a x = if a = b then 1 else 0 := by split_ifs with hab · simp [hab] by_cases hab : a ≤ b · simp [Icc_eq_cons_Ico hab, mu_eq_neg_sum_Ico_of_ne ‹_›] · exact sum_eq_zero fun x hx ↦ apply_eq_zero_of_not_le (fun hax ↦ hab <| hax.trans (mem_Icc.1 hx).2) _ end MuSpec section Mu' variable (𝕜) [AddCommGroup 𝕜] [One 𝕜] [Preorder α] [LocallyFiniteOrder α] [DecidableEq α] /-- `mu'` as a bare function defined recursively. -/ private def muFun' (b : α) : α → 𝕜 | a => if a = b then 1 else -∑ x ∈ (Ioc a b).attach, let h := mem_Ioc.1 x.2 have : (Icc ↑x b).card < (Icc a b).card := card_lt_card (Icc_ssubset_Icc_left (h.1.le.trans h.2) h.1 le_rfl) muFun' b x termination_by a => (Icc a b).card private lemma muFun'_apply (a b : α) : muFun' 𝕜 b a = if a = b then 1 else -∑ x ∈ (Ioc a b).attach, muFun' 𝕜 b x := by rw [muFun'] /-- This is the reversed definition of `mu`, which is equal to `mu` but easiest to prove equal by showing that `zeta * mu = 1` and `mu' * zeta = 1`. -/ private def mu' : IncidenceAlgebra 𝕜 α := ⟨fun a b ↦ muFun' 𝕜 b a, fun a b ↦ not_imp_comm.1 fun h ↦ by dsimp only at h rw [muFun'_apply] at h split_ifs at h with hab · exact hab.le · rw [neg_eq_zero] at h obtain ⟨⟨x, hx⟩, -⟩ := exists_ne_zero_of_sum_ne_zero h exact (nonempty_Ioc.1 ⟨x, hx⟩).le⟩ variable {𝕜} {a b : α} private lemma mu'_apply (a b : α) : mu' 𝕜 a b = if a = b then 1 else -∑ x ∈ Ioc a b, mu' 𝕜 x b := by rw [mu', coe_mk, muFun'_apply, sum_attach] @[simp] private lemma mu'_apply_self (a : α) : mu' 𝕜 a a = 1 := by simp [mu'_apply] private lemma mu'_eq_sum_Ioc_of_ne (h : a ≠ b) : mu' 𝕜 a b = -∑ x ∈ Ioc a b, mu' 𝕜 x b := by rw [mu'_apply, if_neg h] end Mu' section Mu'Spec variable [AddCommGroup 𝕜] [One 𝕜] [PartialOrder α] [LocallyFiniteOrder α] [DecidableEq α] private lemma sum_Icc_mu'_left (a b : α) : ∑ x ∈ Icc a b, mu' 𝕜 x b = if a = b then 1 else 0 := by split_ifs with hab · simp [hab] by_cases hab : a ≤ b · simp [Icc_eq_cons_Ioc hab, mu'_eq_sum_Ioc_of_ne ‹_›] · exact sum_eq_zero fun x hx ↦ apply_eq_zero_of_not_le (fun hxb ↦ hab <| (mem_Icc.1 hx).1.trans hxb) _ end Mu'Spec section MuZeta variable (𝕜 α) [AddCommGroup 𝕜] [MulOneClass 𝕜] [PartialOrder α] [LocallyFiniteOrder α] [DecidableEq α] [DecidableLE α] lemma mu_mul_zeta : (mu 𝕜 * zeta 𝕜 : IncidenceAlgebra 𝕜 α) = 1 := by ext a b calc _ = ∑ x ∈ Icc a b, mu 𝕜 a x := by rw [mul_apply]; congr! with x hx; simp [(mem_Icc.1 hx).2] _ = (1 : IncidenceAlgebra 𝕜 α) a b := sum_Icc_mu_right .. private lemma zeta_mul_mu' : (zeta 𝕜 * mu' 𝕜 : IncidenceAlgebra 𝕜 α) = 1 := by ext a b calc _ = ∑ x ∈ Icc a b, mu' 𝕜 x b := by rw [mul_apply]; congr! with x hx; simp [(mem_Icc.1 hx).1] _ = (1 : IncidenceAlgebra 𝕜 α) a b := sum_Icc_mu'_left .. end MuZeta section MuEqMu' variable [Ring 𝕜] [PartialOrder α] [LocallyFiniteOrder α] [DecidableEq α] {a b : α} private lemma mu_eq_mu' : (mu 𝕜 : IncidenceAlgebra 𝕜 α) = mu' 𝕜 := by classical exact left_inv_eq_right_inv (mu_mul_zeta _ _) (zeta_mul_mu' _ _) lemma mu_eq_neg_sum_Ioc_of_ne (hab : a ≠ b) : mu 𝕜 a b = -∑ x ∈ Ioc a b, mu 𝕜 x b := by rw [mu_eq_mu', mu'_eq_sum_Ioc_of_ne hab] lemma zeta_mul_mu [DecidableLE α] : (zeta 𝕜 * mu 𝕜 : IncidenceAlgebra 𝕜 α) = 1 := by rw [mu_eq_mu', zeta_mul_mu'] lemma sum_Icc_mu_left (a b : α) : ∑ x ∈ Icc a b, mu 𝕜 x b = if a = b then 1 else 0 := by rw [mu_eq_mu', sum_Icc_mu'_left] end MuEqMu' section OrderDual variable (𝕜) [Ring 𝕜] [PartialOrder α] [LocallyFiniteOrder α] [DecidableEq α] @[simp] lemma mu_toDual (a b : α) : mu 𝕜 (toDual a) (toDual b) = mu 𝕜 b a := by letI : DecidableLE α := Classical.decRel _ let mud : IncidenceAlgebra 𝕜 αᵒᵈ := { toFun := fun a b ↦ mu 𝕜 (ofDual b) (ofDual a) eq_zero_of_not_le' := fun a b hab ↦ apply_eq_zero_of_not_le (by exact hab) _ } suffices mu 𝕜 = mud by simp_rw [this, mud, coe_mk, ofDual_toDual] suffices mud * zeta 𝕜 = 1 by rw [← mu_mul_zeta] at this apply_fun (· * mu 𝕜) at this symm simpa [mul_assoc, zeta_mul_mu] using this clear a b ext a b simp only [mul_boole, one_apply, mul_apply, zeta_apply] calc ∑ x ∈ Icc a b, (if x ≤ b then mud a x else 0) = ∑ x ∈ Icc a b, mud a x := by congr! with x hx; exact if_pos (mem_Icc.1 hx).2 _ = ∑ x ∈ Icc (ofDual b) (ofDual a), mu 𝕜 x (ofDual a) := by simp [Icc_orderDual_def, mud] _ = if ofDual b = ofDual a then 1 else 0 := sum_Icc_mu_left .. _ = if a = b then 1 else 0 := by simp [eq_comm] @[simp] lemma mu_ofDual (a b : αᵒᵈ) : mu 𝕜 (ofDual a) (ofDual b) = mu 𝕜 b a := (mu_toDual ..).symm @[simp] lemma eulerChar_orderDual [BoundedOrder α] : eulerChar 𝕜 αᵒᵈ = eulerChar 𝕜 α := by simp [eulerChar, ← mu_toDual 𝕜 (α := α)] end OrderDual section InversionTop variable [Ring 𝕜] [PartialOrder α] [OrderTop α] [LocallyFiniteOrder α] [DecidableEq α] {a b : α} /-- A general form of Möbius inversion. Based on lemma 2.1.2 of Incidence Algebras by Spiegel and O'Donnell. -/ lemma moebius_inversion_top (f g : α → 𝕜) (h : ∀ x, g x = ∑ y ∈ Ici x, f y) (x : α) : f x = ∑ y ∈ Ici x, mu 𝕜 x y * g y := by letI : DecidableLE α := Classical.decRel _ symm calc ∑ y ∈ Ici x, mu 𝕜 x y * g y = ∑ y ∈ Ici x, mu 𝕜 x y * ∑ z ∈ Ici y, f z := by simp_rw [h] _ = ∑ y ∈ Ici x, mu 𝕜 x y * ∑ z ∈ Ici y, zeta 𝕜 y z * f z := by congr with y rw [sum_congr rfl fun z hz ↦ ?_] rw [zeta_apply, if_pos (mem_Ici.mp ‹_›), one_mul] _ = ∑ y ∈ Ici x, ∑ z ∈ Ici y, mu 𝕜 x y * zeta 𝕜 y z * f z := by simp [mul_sum] _ = ∑ z ∈ Ici x, ∑ y ∈ Icc x z, mu 𝕜 x y * zeta 𝕜 y z * f z := by rw [sum_sigma' (Ici x) fun y ↦ Ici y] rw [sum_sigma' (Ici x) fun z ↦ Icc x z] simp only [mul_boole, zero_mul, ite_mul, zeta_apply] apply sum_nbij' (fun ⟨a, b⟩ ↦ ⟨b, a⟩) (fun ⟨a, b⟩ ↦ ⟨b, a⟩) <;> aesop (add simp mul_assoc) (add unsafe le_trans) _ = ∑ z ∈ Ici x, (mu 𝕜 * zeta 𝕜 : IncidenceAlgebra 𝕜 α) x z * f z := by simp_rw [mul_apply, sum_mul] _ = ∑ y ∈ Ici x, ∑ z ∈ Ici y, (1 : IncidenceAlgebra 𝕜 α) x z * f z := by simp only [mu_mul_zeta 𝕜, one_apply, ite_mul, one_mul, zero_mul, sum_ite_eq, mem_Ici, le_refl, ↓reduceIte, ← add_sum_Ioi_eq_sum_Ici, left_eq_add] exact sum_eq_zero fun y hy ↦ if_neg (mem_Ioi.mp hy).not_ge _ = f x := by simp only [one_apply, ite_mul, one_mul, zero_mul, sum_ite_eq, mem_Ici, ← add_sum_Ioi_eq_sum_Ici, le_refl, ↓reduceIte, add_eq_left] exact sum_eq_zero fun y hy ↦ if_neg (mem_Ioi.mp hy).not_ge end InversionTop section InversionBot variable [Ring 𝕜] [PartialOrder α] [OrderBot α] [LocallyFiniteOrder α] [DecidableEq α] /-- A general form of Möbius inversion. Based on lemma 2.1.3 of Incidence Algebras by Spiegel and O'Donnell. -/ lemma moebius_inversion_bot (f g : α → 𝕜) (h : ∀ x, g x = ∑ y ∈ Iic x, f y) (x : α) : f x = ∑ y ∈ Iic x, mu 𝕜 y x * g y := by convert moebius_inversion_top (α := αᵒᵈ) f g h x using 3 rw [← mu_toDual]; rfl end InversionBot section Prod section Preorder section Ring variable (𝕜) [Ring 𝕜] [Preorder α] [Preorder β] section DecidableLe variable [DecidableLE α] [DecidableLE β] lemma zeta_prod_apply (a b : α × β) : zeta 𝕜 a b = zeta 𝕜 a.1 b.1 * zeta 𝕜 a.2 b.2 := by simp [← ite_and, Prod.le_def, and_comm] lemma zeta_prod_mk (a₁ a₂ : α) (b₁ b₂ : β) : zeta 𝕜 (a₁, b₁) (a₂, b₂) = zeta 𝕜 a₁ a₂ * zeta 𝕜 b₁ b₂ := zeta_prod_apply _ _ _ end DecidableLe variable {𝕜} (f f₁ f₂ : IncidenceAlgebra 𝕜 α) (g g₁ g₂ : IncidenceAlgebra 𝕜 β) /-- The Cartesian product of two incidence algebras. -/ protected def prod : IncidenceAlgebra 𝕜 (α × β) where toFun x y := f x.1 y.1 * g x.2 y.2 eq_zero_of_not_le' x y hxy := by rw [Prod.le_def, not_and_or] at hxy obtain hxy | hxy := hxy <;> simp [apply_eq_zero_of_not_le hxy] lemma prod_mk (a₁ a₂ : α) (b₁ b₂ : β) : f.prod g (a₁, b₁) (a₂, b₂) = f a₁ a₂ * g b₁ b₂ := rfl @[simp] lemma prod_apply (x y : α × β) : f.prod g x y = f x.1 y.1 * g x.2 y.2 := rfl /-- This is a version of `IncidenceAlgebra.prod_mul_prod` that works over non-commutative rings. -/ lemma prod_mul_prod' [LocallyFiniteOrder α] [LocallyFiniteOrder β] [DecidableLE (α × β)] (h : ∀ a₁ a₂ a₃ b₁ b₂ b₃, f₁ a₁ a₂ * g₁ b₁ b₂ * (f₂ a₂ a₃ * g₂ b₂ b₃) = f₁ a₁ a₂ * f₂ a₂ a₃ * (g₁ b₁ b₂ * g₂ b₂ b₃)) : f₁.prod g₁ * f₂.prod g₂ = (f₁ * f₂).prod (g₁ * g₂) := by ext x y; simp [Icc_prod_def, sum_mul_sum, h, sum_product] @[simp] lemma one_prod_one [DecidableEq α] [DecidableEq β] : (.prod 1 1 : IncidenceAlgebra 𝕜 (α × β)) = 1 := by ext x y; simp [Prod.ext_iff, ← ite_and, and_comm] @[simp] lemma zeta_prod_zeta [DecidableLE α] [DecidableLE β] : (zeta 𝕜).prod (zeta 𝕜) = (zeta 𝕜 : IncidenceAlgebra 𝕜 (α × β)) := by ext x y hxy; simp [hxy, hxy.1, hxy.2] end Ring section CommRing variable [CommRing 𝕜] [Preorder α] [Preorder β] [LocallyFiniteOrder α] [LocallyFiniteOrder β] [DecidableLE (α × β)] (f₁ f₂ : IncidenceAlgebra 𝕜 α) (g₁ g₂ : IncidenceAlgebra 𝕜 β) @[simp] lemma prod_mul_prod : f₁.prod g₁ * f₂.prod g₂ = (f₁ * f₂).prod (g₁ * g₂) := prod_mul_prod' _ _ _ _ fun _ _ _ _ _ _ ↦ mul_mul_mul_comm .. end CommRing end Preorder section PartialOrder variable (𝕜) [Ring 𝕜] [PartialOrder α] [PartialOrder β] [LocallyFiniteOrder α] [LocallyFiniteOrder β] [DecidableEq α] [DecidableEq β] [DecidableLE α] [DecidableLE β] /-- The Möbius function on a product order. Based on lemma 2.1.13 of Incidence Algebras by Spiegel and O'Donnell. -/ @[simp] lemma mu_prod_mu : (mu 𝕜).prod (mu 𝕜) = (mu 𝕜 : IncidenceAlgebra 𝕜 (α × β)) := by refine left_inv_eq_right_inv ?_ zeta_mul_mu rw [← zeta_prod_zeta, prod_mul_prod', mu_mul_zeta, mu_mul_zeta, one_prod_one] exact fun _ _ _ _ _ _ ↦ Commute.mul_mul_mul_comm (by simp : _ = _) _ _ @[simp] lemma eulerChar_prod [BoundedOrder α] [BoundedOrder β] : eulerChar 𝕜 (α × β) = eulerChar 𝕜 α * eulerChar 𝕜 β := by simp [eulerChar, ← mu_prod_mu] end PartialOrder end Prod end IncidenceAlgebra
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/Stirling.lean
import Mathlib.Tactic.Ring import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Data.Nat.Choose.Basic /-! # Stirling Numbers This file defines Stirling numbers of the first and second kinds, proves their fundamental recurrence relations, and establishes some of their key properties and identities. ## The Stirling numbers of the first kind The unsigned Stirling numbers of the first kind, represent the number of ways to partition `n` distinct elements into `k` non-empty cycles. ## The Stirling numbers of the second kind The Stirling numbers of the second kind, represent the number of ways to partition `n` distinct elements into `k` non-empty subsets. ## Main definitions * `Nat.stirlingFirst`: the number of ways to partition `n` distinct elements into `k` non-empty cycles, defined by the recursive relationship it satisfies. * `Nat.stirlingSecond`: the number of ways to partition `n` distinct elements into `k` non-empty subsets, defined by the recursive relationship it satisfies. ## References * [Knuth, *The Art of Computer Programming*, Volume 1, §1.2.6][knuth1997] -/ open Nat namespace Nat /-- `Nat.stirlingFirst n k` is the (unsigned) Stirling number of the first kind, counting the number of permutations of `n` elements with exactly `k` disjoint cycles. -/ def stirlingFirst : ℕ → ℕ → ℕ | 0, 0 => 1 | 0, _ + 1 => 0 | _ + 1, 0 => 0 | n + 1, k + 1 => n * stirlingFirst n (k + 1) + stirlingFirst n k @[simp] theorem stirlingFirst_zero : stirlingFirst 0 0 = 1 := rfl @[simp] theorem stirlingFirst_zero_succ (k : ℕ) : stirlingFirst 0 (succ k) = 0 := rfl @[simp] theorem stirlingFirst_succ_zero (n : ℕ) : stirlingFirst (succ n) 0 = 0 := rfl theorem stirlingFirst_succ_left (n k : ℕ) (hk : k ≠ 0) : stirlingFirst (n + 1) k = n * stirlingFirst n k + stirlingFirst n (k - 1) := by obtain ⟨l, rfl⟩ := Nat.exists_eq_add_of_le' (Nat.pos_of_ne_zero hk) rfl theorem stirlingFirst_succ_right (n k : ℕ) (hn : n ≠ 0) : stirlingFirst n (k + 1) = (n - 1) * stirlingFirst (n - 1) (k + 1) + stirlingFirst (n - 1) k := by obtain ⟨l, rfl⟩ := Nat.exists_eq_add_of_le' (Nat.pos_of_ne_zero hn) rfl theorem stirlingFirst_succ_succ (n k : ℕ) : stirlingFirst (n + 1) (k + 1) = n * stirlingFirst n (k + 1) + stirlingFirst n k := by rfl theorem stirlingFirst_eq_zero_of_lt : ∀ {n k : ℕ}, n < k → stirlingFirst n k = 0 | _, 0, hk => absurd hk (Nat.not_lt_zero _) | 0, _ + 1, _ => by rw [stirlingFirst] | n + 1, k + 1, hk => by rw [stirlingFirst_succ_succ, stirlingFirst_eq_zero_of_lt (Nat.lt_of_succ_lt_succ hk), stirlingFirst_eq_zero_of_lt (Nat.lt_of_succ_lt hk), mul_zero] theorem stirlingFirst_self (n : ℕ) : stirlingFirst n n = 1 := by induction n <;> simp only [*, stirlingFirst, stirlingFirst_eq_zero_of_lt (Nat.lt_succ_self _), mul_zero] theorem stirlingFirst_succ_self_left (n : ℕ) : stirlingFirst (n + 1) n = (n + 1).choose 2 := by induction n with | zero => simp only [zero_add, stirlingFirst_succ_zero, choose_succ_self] | succ n ih => rw [stirlingFirst_succ_succ, ih, stirlingFirst_self, mul_one, Nat.choose_succ_succ (n + 1), Nat.choose_one_right] theorem stirlingFirst_one_right (n : ℕ) : stirlingFirst (n + 1) 1 = n.factorial := by induction n with | zero => rfl | succ n hn => rw [stirlingFirst_succ_succ, zero_add, hn, stirlingFirst_succ_zero] simp [Nat.factorial_succ] /-- `Nat.stirlingSecond n k` is the Stirling number of the second kind, counting the number of ways to partition a set of `n` elements into `k` nonempty subsets. -/ def stirlingSecond : ℕ → ℕ → ℕ | 0, 0 => 1 | 0, _ + 1 => 0 | _ + 1, 0 => 0 | n + 1, k + 1 => (k + 1) * stirlingSecond n (k + 1) + stirlingSecond n k @[simp] theorem stirlingSecond_zero : stirlingSecond 0 0 = 1 := rfl @[simp] theorem stirlingSecond_zero_succ (k : ℕ) : stirlingSecond 0 (succ k) = 0 := rfl @[simp] theorem stirlingSecond_succ_zero (n : ℕ) : stirlingSecond (succ n) 0 = 0 := rfl theorem stirlingSecond_succ_left (n k : ℕ) (hk : k ≠ 0) : stirlingSecond (n + 1) k = k * stirlingSecond n k + stirlingSecond n (k - 1) := by obtain ⟨l, rfl⟩ := Nat.exists_eq_add_of_le' (Nat.pos_of_ne_zero hk) rfl theorem stirlingSecond_succ_right (n k : ℕ) (hn : n ≠ 0) : stirlingSecond n (k + 1) = (k + 1) * stirlingSecond (n - 1) (k + 1) + stirlingSecond (n - 1) k := by obtain ⟨l, rfl⟩ := Nat.exists_eq_add_of_le' (Nat.pos_of_ne_zero hn) rfl theorem stirlingSecond_succ_succ (n k : ℕ) : stirlingSecond (n + 1) (k + 1) = (k + 1) * stirlingSecond n (k + 1) + stirlingSecond n k := rfl theorem stirlingSecond_eq_zero_of_lt : ∀ {n k : ℕ}, n < k → stirlingSecond n k = 0 | _, 0, hk => absurd hk (Nat.not_lt_zero _) | 0, _ + 1, _ => by rw [stirlingSecond] | n + 1, k + 1, hk => by simp only [stirlingSecond_succ_succ, stirlingSecond_eq_zero_of_lt (Nat.lt_of_succ_lt_succ hk), stirlingSecond_eq_zero_of_lt (Nat.lt_of_succ_lt hk), mul_zero] theorem stirlingSecond_self (n : ℕ) : stirlingSecond n n = 1 := by induction n <;> simp only [*, stirlingSecond, stirlingSecond_eq_zero_of_lt (lt_succ_self _), mul_zero] theorem stirlingSecond_one_right (n : ℕ) : stirlingSecond (n + 1) 1 = 1 := by induction n with | zero => rfl | succ n ih => rw [stirlingSecond, stirlingSecond_succ_zero, ih] theorem stirlingSecond_succ_self_left (n : ℕ) : stirlingSecond (n + 1) n = (n + 1).choose 2 := by induction n with | zero => simp only [zero_add, stirlingSecond_succ_zero, choose_succ_self] | succ n ih => rw [stirlingSecond_succ_succ, ih, stirlingSecond_self, mul_one, Nat.choose_succ_succ (n + 1), Nat.choose_one_right] end Nat
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/Partition/Basic.lean
import Mathlib.Algebra.Order.Antidiag.Finsupp import Mathlib.Combinatorics.Enumerative.Composition import Mathlib.Tactic.ApplyFun /-! # Partitions A partition of a natural number `n` is a way of writing `n` as a sum of positive integers, where the order does not matter: two sums that differ only in the order of their summands are considered the same partition. This notion is closely related to that of a composition of `n`, but in a composition of `n` the order does matter. A summand of the partition is called a part. ## Main functions * `p : Partition n` is a structure, made of a multiset of integers which are all positive and add up to `n`. ## Implementation details The main motivation for this structure and its API is to show Euler's partition theorem, and related results. The representation of a partition as a multiset is very handy as multisets are very flexible and already have a well-developed API. ## TODO Link this to Young diagrams. ## Tags Partition ## References <https://en.wikipedia.org/wiki/Partition_(number_theory)> -/ assert_not_exists Field open Multiset namespace Nat /-- A partition of `n` is a multiset of positive integers summing to `n`. -/ @[ext] structure Partition (n : ℕ) where /-- positive integers summing to `n` -/ parts : Multiset ℕ /-- proof that the `parts` are positive -/ parts_pos : ∀ {i}, i ∈ parts → 0 < i /-- proof that the `parts` sum to `n` -/ parts_sum : parts.sum = n deriving DecidableEq namespace Partition attribute [grind →] parts_pos @[grind →] theorem le_of_mem_parts {n : ℕ} {p : Partition n} {m : ℕ} (h : m ∈ p.parts) : m ≤ n := by simpa [p.parts_sum] using Multiset.le_sum_of_mem h /-- A composition induces a partition (just convert the list to a multiset). -/ @[simps] def ofComposition (n : ℕ) (c : Composition n) : Partition n where parts := c.blocks parts_pos hi := c.blocks_pos hi parts_sum := by rw [Multiset.sum_coe, c.blocks_sum] theorem ofComposition_surj {n : ℕ} : Function.Surjective (ofComposition n) := by rintro ⟨b, hb₁, hb₂⟩ induction b using Quotient.inductionOn with | _ b => ?_ exact ⟨⟨b, hb₁, by simpa using hb₂⟩, Partition.ext rfl⟩ -- The argument `n` is kept explicit here since it is useful in tactic mode proofs to generate the -- proof obligation `l.sum = n`. /-- Given a multiset which sums to `n`, construct a partition of `n` with the same multiset, but without the zeros. -/ @[simps] def ofSums (n : ℕ) (l : Multiset ℕ) (hl : l.sum = n) : Partition n where parts := l.filter (· ≠ 0) parts_pos hi := (of_mem_filter hi).bot_lt parts_sum := by have lz : (l.filter (· = 0)).sum = 0 := by simp [sum_eq_zero_iff] rwa [← filter_add_not (· = 0) l, sum_add, lz, zero_add] at hl /-- A `Multiset ℕ` induces a partition on its sum. -/ @[simps!] def ofMultiset (l : Multiset ℕ) : Partition l.sum := ofSums _ l rfl /-- An element `s` of `Sym σ n` induces a partition given by its multiplicities. -/ def ofSym {n : ℕ} {σ : Type*} (s : Sym σ n) [DecidableEq σ] : n.Partition where parts := s.1.dedup.map s.1.count parts_pos := by simp [Multiset.count_pos] parts_sum := by change ∑ a ∈ s.1.toFinset, count a s.1 = n rw [toFinset_sum_count_eq] exact s.2 variable {n : ℕ} {σ τ : Type*} [DecidableEq σ] [DecidableEq τ] @[simp] lemma ofSym_map (e : σ ≃ τ) (s : Sym σ n) : ofSym (s.map e) = ofSym s := by simp only [ofSym, Sym.val_eq_coe, Sym.coe_map, mk.injEq] rw [Multiset.dedup_map_of_injective e.injective] simp only [map_map, Function.comp_apply] congr; funext i rw [← Multiset.count_map_eq_count' e _ e.injective] /-- An equivalence between `σ` and `τ` induces an equivalence between the subtypes of `Sym σ n` and `Sym τ n` corresponding to a given partition. -/ def ofSymShapeEquiv (μ : Partition n) (e : σ ≃ τ) : {x : Sym σ n // ofSym x = μ} ≃ {x : Sym τ n // ofSym x = μ} where toFun := fun x => ⟨Sym.equivCongr e x, by simp [ofSym_map, x.2]⟩ invFun := fun x => ⟨Sym.equivCongr e.symm x, by simp [ofSym_map, x.2]⟩ left_inv := by intro x; simp right_inv := by intro x; simp /-- Convert a `Partition n` to a member of `(Finset.Icc 1 n).finsuppAntidiag n` (see `Nat.Partition.toFinsuppAntidiag_mem_finsuppAntidiag` for the proof). `p.toFinsuppAntidiag i` is defined as `i` times the number of occurrence of `i` in `p`. -/ def toFinsuppAntidiag {n : ℕ} (p : Partition n) : ℕ →₀ ℕ where toFun m := p.parts.count m * m support := p.parts.toFinset mem_support_toFun m := by suffices m ∈ p.parts → m ≠ 0 by simpa grind theorem toFinsuppAntidiag_injective (n : ℕ) : Function.Injective (toFinsuppAntidiag (n := n)) := by unfold toFinsuppAntidiag intro p q h rw [Finsupp.mk.injEq] at h obtain ⟨hfinset, hcount⟩ := h rw [Nat.Partition.ext_iff, Multiset.ext] intro m obtain rfl | h0 := Nat.eq_zero_or_pos m · grind [Multiset.count_eq_zero] · exact Nat.eq_of_mul_eq_mul_right h0 <| funext_iff.mp hcount m theorem toFinsuppAntidiag_mem_finsuppAntidiag {n : ℕ} (p : Partition n) : p.toFinsuppAntidiag ∈ (Finset.Icc 1 n).finsuppAntidiag n := by have hp : p.parts.toFinset ⊆ Finset.Icc 1 n := by grind [Multiset.mem_toFinset, Finset.mem_Icc] suffices ∑ m ∈ Finset.Icc 1 n, Multiset.count m p.parts * m = n by simpa [toFinsuppAntidiag, hp] convert ← p.parts_sum rw [Finset.sum_multiset_count] apply Finset.sum_subset hp suffices ∀ (x : ℕ), 1 ≤ x → x ≤ n → x ∉ p.parts → x ∉ p.parts ∨ x = 0 by simpa grind /-- The partition of exactly one part. -/ def indiscrete (n : ℕ) : Partition n := ofSums n {n} rfl instance {n : ℕ} : Inhabited (Partition n) := ⟨indiscrete n⟩ @[simp] lemma indiscrete_parts {n : ℕ} (hn : n ≠ 0) : (indiscrete n).parts = {n} := by simp [indiscrete, filter_eq_self, hn] @[simp] lemma partition_zero_parts (p : Partition 0) : p.parts = 0 := eq_zero_of_forall_notMem fun _ h => (p.parts_pos h).ne' <| sum_eq_zero_iff.1 p.parts_sum _ h instance UniquePartitionZero : Unique (Partition 0) where uniq _ := Partition.ext <| by simp @[simp] lemma partition_one_parts (p : Partition 1) : p.parts = {1} := by have h : p.parts = replicate (card p.parts) 1 := eq_replicate_card.2 fun x hx => ((le_sum_of_mem hx).trans_eq p.parts_sum).antisymm (p.parts_pos hx) have h' : card p.parts = 1 := by simpa using (congrArg sum h.symm).trans p.parts_sum rw [h, h', replicate_one] instance UniquePartitionOne : Unique (Partition 1) where uniq _ := Partition.ext <| by simp @[simp] lemma ofSym_one (s : Sym σ 1) : ofSym s = indiscrete 1 := by ext; simp /-- The number of times a positive integer `i` appears in the partition `ofSums n l hl` is the same as the number of times it appears in the multiset `l`. (For `i = 0`, `Partition.non_zero` combined with `Multiset.count_eq_zero_of_notMem` gives that this is `0` instead.) -/ theorem count_ofSums_of_ne_zero {n : ℕ} {l : Multiset ℕ} (hl : l.sum = n) {i : ℕ} (hi : i ≠ 0) : (ofSums n l hl).parts.count i = l.count i := count_filter_of_pos hi theorem count_ofSums_zero {n : ℕ} {l : Multiset ℕ} (hl : l.sum = n) : (ofSums n l hl).parts.count 0 = 0 := count_filter_of_neg fun h => h rfl /-- Show there are finitely many partitions by considering the surjection from compositions to partitions. -/ instance (n : ℕ) : Fintype (Partition n) := Fintype.ofSurjective (ofComposition n) ofComposition_surj /-- The finset of those partitions in which every part is odd. -/ def odds (n : ℕ) : Finset (Partition n) := Finset.univ.filter fun c => ∀ i ∈ c.parts, ¬Even i /-- The finset of those partitions in which each part is used at most once. -/ def distincts (n : ℕ) : Finset (Partition n) := Finset.univ.filter fun c => c.parts.Nodup /-- The finset of those partitions in which every part is odd and used at most once. -/ def oddDistincts (n : ℕ) : Finset (Partition n) := odds n ∩ distincts n end Partition end Nat
.lake/packages/mathlib/Mathlib/Combinatorics/Enumerative/Partition/GenFun.lean
import Mathlib.Combinatorics.Enumerative.Partition.Basic import Mathlib.RingTheory.PowerSeries.PiTopology /-! # Generating functions for partitions This file defines generating functions related to partitions. Given a character function $f(i, c)$ of a part $i$ and the number of occurrences of the part $c$, the related generating function is $$ G_f(X) = \sum_{n = 0}^{\infty} \left(\sum_{p \in P_{n}} \prod_{i \in p} f(i, \#i)\right) X^n = \prod_{i = 1}^{\infty}\left(1 + \sum_{j = 1}^{\infty} f(i, j) X^{ij}\right) $$ where $P_n$ is all partitions of $n$, $\#i$ is the count of $i$ in the partition $p$. We give the definition `Nat.Partition.genFun` using the first equation, and prove the second equation in `Nat.Partition.hasProd_genFun` (with shifted indices). This generating function can be specialized to * When $f(i, c) = 1$, this is the generating function for partition function $p(n)$. * When $f(i, 1) = 1$ and $f(i, c) = 0$ for $c > 1$, this is the generating function for `#(Nat.Partition.distincts n)`. * When $f(i, c) = 1$ for odd $i$ and $f(i, c) = 0$ for even $i$, this is the generating function for `#(Nat.Partition.odds n)`. (TODO: prove these) The definition of `Nat.Partition.genFun` ignores the value of $f(0, c)$ and $f(i, 0)$. The formula can be interpreted as assuming $f(i, 0) = 1$ and $f(0, c) = 0$ for $c \ne 0$. In theory we could respect the actual value of $f(0, c)$ and $f(i, 0)$, but it makes the otherwise finite sum and product potentially infinite. -/ open Finset PowerSeries open scoped PowerSeries.WithPiTopology namespace Nat.Partition variable {R : Type*} [CommSemiring R] /-- Generating function associated with character $f(i, c)$ for partition functions, where $i$ is a part of the partition, and $c$ is the count of that part in the partition. The character function is multiplied within one `n.Partition`, and summed among all `n.Partition` for a fixed `n`. This way, each `n` is assigned a value, which we use as the coefficients of the power series. See the module docstring of `Combinatorics.Enumerative.Partition.GenFun` for more details. -/ def genFun (f : ℕ → ℕ → R) : R⟦X⟧ := PowerSeries.mk fun n ↦ ∑ p : n.Partition, p.parts.toFinsupp.prod f @[simp] lemma coeff_genFun (f : ℕ → ℕ → R) (n : ℕ) : (genFun f).coeff n = ∑ p : n.Partition, p.parts.toFinsupp.prod f := PowerSeries.coeff_mk _ _ variable [TopologicalSpace R] /-- The infinite sum in the formula `Nat.Partition.hasProd_genFun` always converges. -/ theorem summable_genFun_term (f : ℕ → ℕ → R) (i : ℕ) : Summable fun j ↦ f (i + 1) (j + 1) • (X : R⟦X⟧) ^ ((i + 1) * (j + 1)) := by nontriviality R apply WithPiTopology.summable_of_tendsto_order_atTop_nhds_top refine ENat.tendsto_nhds_top_iff_natCast_lt.mpr (fun n ↦ Filter.eventually_atTop.mpr ⟨n, ?_⟩) intro m hm grw [PowerSeries.smul_eq_C_mul, ← le_order_mul] refine lt_add_of_nonneg_of_lt (by simp) ?_ rw [order_X_pow] norm_cast grind /-- Alternative form of `summable_genFun_term` that unshifts the first index. -/ theorem summable_genFun_term' (f : ℕ → ℕ → R) {i : ℕ} (hi : i ≠ 0) : Summable fun j ↦ f i (j + 1) • (X : R⟦X⟧) ^ (i * (j + 1)) := by obtain ⟨a, rfl⟩ := Nat.exists_eq_add_one_of_ne_zero hi apply summable_genFun_term variable [T2Space R] private theorem aux_dvd_of_coeff_ne_zero {f : ℕ → ℕ → R} {d : ℕ} {s : Finset ℕ} (hs0 : 0 ∉ s) {g : ℕ →₀ ℕ} (hg : g ∈ s.finsuppAntidiag d) (hprod : ∀ i ∈ s, (coeff (g i)) (1 + ∑' j, f i (j + 1) • X ^ (i * (j + 1))) ≠ (0 : R)) (x : ℕ) : x ∣ g x := by by_cases hx : x ∈ s · specialize hprod x hx contrapose! hprod have hx0 : x ≠ 0 := fun h ↦ hs0 (h ▸ hx) rw [map_add, (summable_genFun_term' f hx0).map_tsum _ (WithPiTopology.continuous_coeff _ _)] rw [show (0 : R) = 0 + ∑' (i : ℕ), 0 by simp] congrm (?_ + ∑' (i : ℕ), ?_) · suffices g x ≠ 0 by simp [this] contrapose! hprod simp [hprod] · rw [map_smul, coeff_X_pow] apply smul_eq_zero_of_right suffices g x ≠ x * (i + 1) by simp [this] contrapose! hprod simp [hprod] · suffices g x = 0 by simp [this] contrapose! hx exact mem_of_subset (mem_finsuppAntidiag.mp hg).2 <| by simpa using hx private theorem aux_prod_coeff_eq_zero_of_notMem_range (f : ℕ → ℕ → R) {d : ℕ} {s : Finset ℕ} (hs0 : 0 ∉ s) {g : ℕ →₀ ℕ} (hg : g ∈ s.finsuppAntidiag d) (hg' : g ∉ Set.range (toFinsuppAntidiag (n := d))) : ∏ i ∈ s, (coeff (g i)) (1 + ∑' j, f i (j + 1) • X ^ (i * (j + 1)) : R⟦X⟧) = 0 := by suffices ∃ i ∈ s, (coeff (g i)) ((1 : R⟦X⟧) + ∑' j, f i (j + 1) • X ^ (i * (j + 1))) = 0 by obtain ⟨i, hi, hi'⟩ := this apply prod_eq_zero hi hi' contrapose! hg' with hprod rw [Set.mem_range] have hgne0 (i : ℕ) : g i ≠ 0 ↔ i ≠ 0 ∧ i ≤ g i := by refine ⟨fun h ↦ ⟨?_, ?_⟩, by grind⟩ · contrapose! hs0 with rfl exact mem_of_subset (mem_finsuppAntidiag.mp hg).2 (by simpa using h) · exact Nat.le_of_dvd (Nat.pos_of_ne_zero h) <| aux_dvd_of_coeff_ne_zero hs0 hg hprod _ refine ⟨Nat.Partition.mk (Finsupp.mk g.support (fun i ↦ g i / i) ?_).toMultiset ?_ ?_, ?_⟩ · simpa using hgne0 · suffices ∀ i, g i ≠ 0 → i ≠ 0 by simpa [Nat.pos_iff_ne_zero] exact fun i h ↦ ((hgne0 i).mp h).1 · obtain ⟨h1, h2⟩ := mem_finsuppAntidiag.mp hg refine Eq.trans ?_ h1 suffices ∑ x ∈ g.support, g x / x * x = ∑ x ∈ s, g x by simpa [Finsupp.sum] apply sum_subset_zero_on_sdiff h2 (by simp) exact fun x hx ↦ Nat.div_mul_cancel <| aux_dvd_of_coeff_ne_zero hs0 hg hprod x · ext x simpa [toFinsuppAntidiag] using Nat.div_mul_cancel <| aux_dvd_of_coeff_ne_zero hs0 hg hprod x private theorem aux_prod_f_eq_prod_coeff (f : ℕ → ℕ → R) {n : ℕ} (p : Partition n) {s : Finset ℕ} (hs : Icc 1 n ⊆ s) (hs0 : 0 ∉ s) : p.parts.toFinsupp.prod f = ∏ i ∈ s, coeff (p.toFinsuppAntidiag i) (1 + ∑' j, f i (j + 1) • X ^ (i * (j + 1))) := by simp_rw [Finsupp.prod, Multiset.toFinsupp_support, Multiset.toFinsupp_apply] apply prod_subset_one_on_sdiff · grind [Multiset.mem_toFinset, mem_Icc] · intro x hx rw [mem_sdiff, Multiset.mem_toFinset] at hx have hx0 : x ≠ 0 := fun h ↦ hs0 (h ▸ hx.1) have hsum := (summable_genFun_term' f hx0).map_tsum _ (WithPiTopology.continuous_constantCoeff R) simp [toFinsuppAntidiag, hsum, hx.2, hx0] · intro i hi rw [Multiset.mem_toFinset] at hi have hi0 : i ≠ 0 := (p.parts_pos hi).ne.symm rw [map_add, (summable_genFun_term' f hi0).map_tsum _ (WithPiTopology.continuous_coeff _ _)] suffices f i (Multiset.count i p.parts) = ∑' j, if Multiset.count i p.parts * i = i * (j + 1) then f i (j + 1) else 0 by simpa [toFinsuppAntidiag, hi, hi0, coeff_X_pow] rw [tsum_eq_single (Multiset.count i p.parts - 1) ?_] · rw [mul_comm] simp [Nat.sub_add_cancel (Multiset.one_le_count_iff_mem.mpr hi)] intro b hb suffices Multiset.count i p.parts * i ≠ i * (b + 1) by simp [this] rw [mul_comm i, (mul_left_inj' (Nat.ne_zero_of_lt (p.parts_pos hi))).ne] grind theorem hasProd_genFun (f : ℕ → ℕ → R) : HasProd (fun i ↦ 1 + ∑' j, f (i + 1) (j + 1) • X ^ ((i + 1) * (j + 1))) (genFun f) := by rw [HasProd, WithPiTopology.tendsto_iff_coeff_tendsto] refine fun d ↦ tendsto_atTop_of_eventually_const (fun s (hs : s ≥ range d) ↦ ?_) have : ∏ i ∈ s, ((1 : R⟦X⟧) + ∑' j, f (i + 1) (j + 1) • X ^ ((i + 1) * (j + 1))) = ∏ i ∈ s.map (addRightEmbedding 1), (1 + ∑' j, f i (j + 1) • X ^ (i * (j + 1))) := by simp rw [this] have hs : Icc 1 d ⊆ s.map (addRightEmbedding 1) := by intro i suffices 1 ≤ i → i ≤ d → ∃ a ∈ s, a + 1 = i by simpa intro h1 h2 refine ⟨i - 1, mem_of_subset hs ?_, ?_⟩ <;> grind rw [coeff_genFun, coeff_prod] refine (sum_of_injOn toFinsuppAntidiag (toFinsuppAntidiag_injective d).injOn ?_ ?_ ?_).symm · intro p _ exact mem_of_subset (finsuppAntidiag_mono hs.le _) p.toFinsuppAntidiag_mem_finsuppAntidiag · exact fun g hg hg' ↦ aux_prod_coeff_eq_zero_of_notMem_range f (by simp) hg (by simpa using hg') · exact fun p _ ↦ aux_prod_f_eq_prod_coeff f p hs.le (by simp) theorem multipliable_genFun (f : ℕ → ℕ → R) : Multipliable fun i ↦ (1 : R⟦X⟧) + ∑' j, f (i + 1) (j + 1) • X ^ ((i + 1) * (j + 1)) := (hasProd_genFun f).multipliable theorem genFun_eq_tprod (f : ℕ → ℕ → R) : genFun f = ∏' i, (1 + ∑' j, f (i + 1) (j + 1) • X ^ ((i + 1) * (j + 1))) := (hasProd_genFun f).tprod_eq.symm end Nat.Partition
.lake/packages/mathlib/Mathlib/Combinatorics/Optimization/ValuedCSP.lean
import Mathlib.Algebra.BigOperators.Fin import Mathlib.Algebra.Order.BigOperators.Group.Multiset import Mathlib.Data.Fin.VecNotation import Mathlib.LinearAlgebra.Matrix.Notation /-! # General-Valued Constraint Satisfaction Problems General-Valued CSP is a very broad class of problems in discrete optimization. General-Valued CSP subsumes Min-Cost-Hom (including 3-SAT for example) and Finite-Valued CSP. ## Main definitions * `ValuedCSP`: A VCSP template; fixes a domain, a codomain, and allowed cost functions. * `ValuedCSP.Term`: One summand in a VCSP instance; calls a concrete function from given template. * `ValuedCSP.Term.evalSolution`: An evaluation of the VCSP term for given solution. * `ValuedCSP.Instance`: An instance of a VCSP problem over given template. * `ValuedCSP.Instance.evalSolution`: An evaluation of the VCSP instance for given solution. * `ValuedCSP.Instance.IsOptimumSolution`: Is given solution a minimum of the VCSP instance? * `Function.HasMaxCutProperty`: Can given binary function express the Max-Cut problem? * `FractionalOperation`: Multiset of operations on given domain of the same arity. * `FractionalOperation.IsSymmetricFractionalPolymorphismFor`: Is given fractional operation a symmetric fractional polymorphism for given VCSP template? ## References * [D. A. Cohen, M. C. Cooper, P. Creed, P. G. Jeavons, S. Živný, *An Algebraic Theory of Complexity for Discrete Optimisation*][cohen2012] -/ /-- A template for a valued CSP problem over a domain `D` with costs in `C`. Regarding `C` we want to support `Bool`, `Nat`, `ENat`, `Int`, `Rat`, `NNRat`, `Real`, `NNReal`, `EReal`, `ENNReal`, and tuples made of any of those types. -/ @[nolint unusedArguments] abbrev ValuedCSP (D C : Type*) [AddCommMonoid C] [PartialOrder C] [IsOrderedAddMonoid C] := Set (Σ (n : ℕ), (Fin n → D) → C) -- Cost functions `D^n → C` for any `n` variable {D C : Type*} [AddCommMonoid C] [PartialOrder C] [IsOrderedAddMonoid C] /-- A term in a valued CSP instance over the template `Γ`. -/ structure ValuedCSP.Term (Γ : ValuedCSP D C) (ι : Type*) where /-- Arity of the function -/ n : ℕ /-- Which cost function is instantiated -/ f : (Fin n → D) → C /-- The cost function comes from the template -/ inΓ : ⟨n, f⟩ ∈ Γ /-- Which variables are plugged as arguments to the cost function -/ app : Fin n → ι /-- Evaluation of a `Γ` term `t` for given solution `x`. -/ def ValuedCSP.Term.evalSolution {Γ : ValuedCSP D C} {ι : Type*} (t : Γ.Term ι) (x : ι → D) : C := t.f (x ∘ t.app) /-- A valued CSP instance over the template `Γ` with variables indexed by `ι`. -/ abbrev ValuedCSP.Instance (Γ : ValuedCSP D C) (ι : Type*) : Type _ := Multiset (Γ.Term ι) /-- Evaluation of a `Γ` instance `I` for given solution `x`. -/ def ValuedCSP.Instance.evalSolution {Γ : ValuedCSP D C} {ι : Type*} (I : Γ.Instance ι) (x : ι → D) : C := (I.map (·.evalSolution x)).sum /-- Condition for `x` being an optimum solution (min) to given `Γ` instance `I`. -/ def ValuedCSP.Instance.IsOptimumSolution {Γ : ValuedCSP D C} {ι : Type*} (I : Γ.Instance ι) (x : ι → D) : Prop := ∀ y : ι → D, I.evalSolution x ≤ I.evalSolution y /-- Function `f` has Max-Cut property at labels `a` and `b` when `argmin f` is exactly `{ ![a, b], ![b, a] }`. -/ def Function.HasMaxCutPropertyAt (f : (Fin 2 → D) → C) (a b : D) : Prop := f ![a, b] = f ![b, a] ∧ ∀ x y : D, f ![a, b] ≤ f ![x, y] ∧ (f ![a, b] = f ![x, y] → a = x ∧ b = y ∨ a = y ∧ b = x) /-- Function `f` has Max-Cut property at some two non-identical labels. -/ def Function.HasMaxCutProperty (f : (Fin 2 → D) → C) : Prop := ∃ a b : D, a ≠ b ∧ f.HasMaxCutPropertyAt a b /-- Fractional operation is a finite unordered collection of D^m → D possibly with duplicates. -/ abbrev FractionalOperation (D : Type*) (m : ℕ) : Type _ := Multiset ((Fin m → D) → D) variable {m : ℕ} /-- Arity of the "output" of the fractional operation. -/ @[simp] def FractionalOperation.size (ω : FractionalOperation D m) : ℕ := ω.card /-- Fractional operation is valid iff nonempty. -/ def FractionalOperation.IsValid (ω : FractionalOperation D m) : Prop := ω ≠ ∅ /-- Valid fractional operation contains an operation. -/ lemma FractionalOperation.IsValid.contains {ω : FractionalOperation D m} (valid : ω.IsValid) : ∃ g : (Fin m → D) → D, g ∈ ω := Multiset.exists_mem_of_ne_zero valid /-- Fractional operation applied to a transposed table of values. -/ def FractionalOperation.tt {ι : Type*} (ω : FractionalOperation D m) (x : Fin m → ι → D) : Multiset (ι → D) := ω.map (fun (g : (Fin m → D) → D) (i : ι) => g ((Function.swap x) i)) /-- Cost function admits given fractional operation, i.e., `ω` improves `f` in the `≤` sense. -/ def Function.AdmitsFractional {n : ℕ} (f : (Fin n → D) → C) (ω : FractionalOperation D m) : Prop := ∀ x : (Fin m → (Fin n → D)), m • ((ω.tt x).map f).sum ≤ ω.size • Finset.univ.sum (fun i => f (x i)) /-- Fractional operation is a fractional polymorphism for given VCSP template. -/ def FractionalOperation.IsFractionalPolymorphismFor (ω : FractionalOperation D m) (Γ : ValuedCSP D C) : Prop := ∀ f ∈ Γ, f.snd.AdmitsFractional ω /-- Fractional operation is symmetric. -/ def FractionalOperation.IsSymmetric (ω : FractionalOperation D m) : Prop := ∀ x y : (Fin m → D), List.Perm (List.ofFn x) (List.ofFn y) → ∀ g ∈ ω, g x = g y /-- Fractional operation is a symmetric fractional polymorphism for given VCSP template. -/ def FractionalOperation.IsSymmetricFractionalPolymorphismFor (ω : FractionalOperation D m) (Γ : ValuedCSP D C) : Prop := ω.IsFractionalPolymorphismFor Γ ∧ ω.IsSymmetric lemma Function.HasMaxCutPropertyAt.rows_lt_aux {C : Type*} [PartialOrder C] {f : (Fin 2 → D) → C} {a b : D} (mcf : f.HasMaxCutPropertyAt a b) (hab : a ≠ b) {ω : FractionalOperation D 2} (symmega : ω.IsSymmetric) {r : Fin 2 → D} (rin : r ∈ (ω.tt ![![a, b], ![b, a]])) : f ![a, b] < f r := by rw [FractionalOperation.tt, Multiset.mem_map] at rin rw [show r = ![r 0, r 1] by simp [← List.ofFn_inj]] apply lt_of_le_of_ne (mcf.right (r 0) (r 1)).left intro equ have asymm : r 0 ≠ r 1 := by rcases (mcf.right (r 0) (r 1)).right equ with ⟨ha0, hb1⟩ | ⟨ha1, hb0⟩ · rw [ha0, hb1] at hab exact hab · rw [ha1, hb0] at hab exact hab.symm apply asymm obtain ⟨o, in_omega, rfl⟩ := rin change o (fun j => ![![a, b], ![b, a]] j 0) = o (fun j => ![![a, b], ![b, a]] j 1) convert symmega ![a, b] ![b, a] (by simp [List.Perm.swap]) o in_omega using 2 <;> simp [Matrix.const_fin1_eq] variable {C : Type*} [AddCommMonoid C] [PartialOrder C] [IsOrderedCancelAddMonoid C] lemma Function.HasMaxCutProperty.forbids_commutativeFractionalPolymorphism {f : (Fin 2 → D) → C} (mcf : f.HasMaxCutProperty) {ω : FractionalOperation D 2} (valid : ω.IsValid) (symmega : ω.IsSymmetric) : ¬ f.AdmitsFractional ω := by intro contr obtain ⟨a, b, hab, mcfab⟩ := mcf specialize contr ![![a, b], ![b, a]] rw [Fin.sum_univ_two', ← mcfab.left, ← two_nsmul] at contr have sharp : 2 • ((ω.tt ![![a, b], ![b, a]]).map (fun _ => f ![a, b])).sum < 2 • ((ω.tt ![![a, b], ![b, a]]).map f).sum := by have half_sharp : ((ω.tt ![![a, b], ![b, a]]).map (fun _ => f ![a, b])).sum < ((ω.tt ![![a, b], ![b, a]]).map f).sum := by apply Multiset.sum_lt_sum · intro r rin exact le_of_lt (mcfab.rows_lt_aux hab symmega rin) · obtain ⟨g, _⟩ := valid.contains have : (fun i => g ((Function.swap ![![a, b], ![b, a]]) i)) ∈ ω.tt ![![a, b], ![b, a]] := by simp only [FractionalOperation.tt, Multiset.mem_map] use g exact ⟨_, this, mcfab.rows_lt_aux hab symmega this⟩ rw [two_nsmul, two_nsmul] exact add_lt_add half_sharp half_sharp have impos : 2 • (ω.map (fun _ => f ![a, b])).sum < ω.size • 2 • f ![a, b] := by convert lt_of_lt_of_le sharp contr simp [FractionalOperation.tt, Multiset.map_map] have rhs_swap : ω.size • 2 • f ![a, b] = 2 • ω.size • f ![a, b] := nsmul_left_comm .. have distrib : (ω.map (fun _ => f ![a, b])).sum = ω.size • f ![a, b] := by simp rw [rhs_swap, distrib] at impos exact ne_of_lt impos rfl
.lake/packages/mathlib/Mathlib/Combinatorics/Graph/Basic.lean
import Mathlib.Data.Set.Basic import Mathlib.Data.Sym.Sym2 /-! # Multigraphs A multigraph is a set of vertices and a set of edges, together with incidence data that associates each edge `e` with an unordered pair `s(x,y)` of vertices called the *ends* of `e`. The pair of `e` and `s(x,y)` is called a *link*. The vertices `x` and `y` may be equal, in which case `e` is a *loop*. There may be more than one edge with the same ends. If a multigraph has no loops and has at most one edge for every given ends, it is called *simple*, and these objects are also formalized as `SimpleGraph`. This module defines `Graph α β` for a vertex type `α` and an edge type `β`, and gives basic API for incidence, adjacency and extensionality. The design broadly follows [Chou1994]. ## Main definitions For `G : Graph α β`, ... * `V(G)` denotes the vertex set of `G` as a term in `Set α`. * `E(G)` denotes the edge set of `G` as a term in `Set β`. * `G.IsLink e x y` means that the edge `e : β` has vertices `x : α` and `y : α` as its ends. * `G.Inc e x` means that the edge `e : β` has `x` as one of its ends. * `G.Adj x y` means that there is an edge `e` having `x` and `y` as its ends. * `G.IsLoopAt e x` means that `e` is a loop edge with both ends equal to `x`. * `G.IsNonloopAt e x` means that `e` is a non-loop edge with one end equal to `x`. * `G.incidenceSet x` is the set of edges incident to `x`. * `G.loopSet x` is the set of loops with both ends equal to `x`. ## Implementation notes Unlike the design of `SimpleGraph`, the vertex and edge sets of `G` are modelled as sets `V(G) : Set α` and `E(G) : Set β`, within ambient types, rather than being types themselves. This mimics the 'embedded set' design used in `Matroid`, which seems to be more convenient for formalizing real-world proofs in combinatorics. A specific advantage is that this allows subgraphs of `G : Graph α β` to also exist on an equal footing with `G` as terms in `Graph α β`, and so there is no need for a `Graph.subgraph` type and all the associated definitions and canonical coercion maps. The same will go for minors and the various other partial orders on multigraphs. The main tradeoff is that parts of the API will need to care about whether a term `x : α` or `e : β` is a 'real' vertex or edge of the graph, rather than something outside the vertex or edge set. This is an issue, but is likely amenable to automation. ## Notation Reflecting written mathematics, we use the compact notations `V(G)` and `E(G)` to refer to the `vertexSet` and `edgeSet` of `G : Graph α β`. If `G.IsLink e x y` then we refer to `e` as `edge` and `x` and `y` as `left` and `right` in names. -/ variable {α β : Type*} {x y z u v w : α} {e f : β} open Set /-- A multigraph with vertices of type `α` and edges of type `β`, as described by vertex and edge sets `vertexSet : Set α` and `edgeSet : Set β`, and a predicate `IsLink` describing whether an edge `e : β` has vertices `x y : α` as its ends. The `edgeSet` structure field can be inferred from `IsLink` via `edge_mem_iff_exists_isLink` (and this structure provides default values for `edgeSet` and `edge_mem_iff_exists_isLink` that use `IsLink`). While the field is not strictly necessary, when defining a graph we often immediately know what the edge set should be, and furthermore having `edgeSet` separate can be convenient for definitional equality reasons. -/ structure Graph (α β : Type*) where /-- The vertex set. -/ vertexSet : Set α /-- The binary incidence predicate, stating that `x` and `y` are the ends of an edge `e`. If `G.IsLink e x y` then we refer to `e` as `edge` and `x` and `y` as `left` and `right`. -/ IsLink : β → α → α → Prop /-- The edge set. -/ edgeSet : Set β := {e | ∃ x y, IsLink e x y} /-- If `e` goes from `x` to `y`, it goes from `y` to `x`. -/ isLink_symm : ∀ ⦃e⦄, e ∈ edgeSet → (Symmetric <| IsLink e) /-- An edge is incident with at most one pair of vertices. -/ eq_or_eq_of_isLink_of_isLink : ∀ ⦃e x y v w⦄, IsLink e x y → IsLink e v w → x = v ∨ x = w /-- An edge `e` is incident to something if and only if `e` is in the edge set. -/ edge_mem_iff_exists_isLink : ∀ e, e ∈ edgeSet ↔ ∃ x y, IsLink e x y := by exact fun _ ↦ Iff.rfl /-- If some edge `e` is incident to `x`, then `x ∈ V`. -/ left_mem_of_isLink : ∀ ⦃e x y⦄, IsLink e x y → x ∈ vertexSet namespace Graph variable {G : Graph α β} /-- `V(G)` denotes the `vertexSet` of a graph `G`. -/ scoped notation "V(" G ")" => Graph.vertexSet G /-- `E(G)` denotes the `edgeSet` of a graph `G`. -/ scoped notation "E(" G ")" => Graph.edgeSet G /-! ### Edge-vertex-vertex incidence -/ lemma IsLink.edge_mem (h : G.IsLink e x y) : e ∈ E(G) := (edge_mem_iff_exists_isLink ..).2 ⟨x, y, h⟩ protected lemma IsLink.symm (h : G.IsLink e x y) : G.IsLink e y x := G.isLink_symm h.edge_mem h lemma IsLink.left_mem (h : G.IsLink e x y) : x ∈ V(G) := G.left_mem_of_isLink h lemma IsLink.right_mem (h : G.IsLink e x y) : y ∈ V(G) := h.symm.left_mem lemma isLink_comm : G.IsLink e x y ↔ G.IsLink e y x := ⟨.symm, .symm⟩ lemma exists_isLink_of_mem_edgeSet (h : e ∈ E(G)) : ∃ x y, G.IsLink e x y := (edge_mem_iff_exists_isLink ..).1 h lemma edgeSet_eq_setOf_exists_isLink : E(G) = {e | ∃ x y, G.IsLink e x y} := Set.ext G.edge_mem_iff_exists_isLink lemma IsLink.left_eq_or_eq (h : G.IsLink e x y) (h' : G.IsLink e z w) : x = z ∨ x = w := G.eq_or_eq_of_isLink_of_isLink h h' lemma IsLink.right_eq_or_eq (h : G.IsLink e x y) (h' : G.IsLink e z w) : y = z ∨ y = w := h.symm.left_eq_or_eq h' lemma IsLink.left_eq_of_right_ne (h : G.IsLink e x y) (h' : G.IsLink e z w) (hzx : x ≠ z) : x = w := (h.left_eq_or_eq h').elim (False.elim ∘ hzx) id lemma IsLink.right_unique (h : G.IsLink e x y) (h' : G.IsLink e x z) : y = z := by obtain rfl | rfl := h.right_eq_or_eq h'.symm · rfl obtain rfl | rfl := h'.right_eq_or_eq h.symm <;> rfl lemma IsLink.left_unique (h : G.IsLink e x z) (h' : G.IsLink e y z) : x = y := h.symm.right_unique h'.symm lemma IsLink.eq_and_eq_or_eq_and_eq {x' y' : α} (h : G.IsLink e x y) (h' : G.IsLink e x' y') : (x = x' ∧ y = y') ∨ (x = y' ∧ y = x') := by obtain rfl | rfl := h.left_eq_or_eq h' · simp [h.right_unique h'] simp [h'.symm.right_unique h] lemma IsLink.isLink_iff (h : G.IsLink e x y) {x' y' : α} : G.IsLink e x' y' ↔ (x = x' ∧ y = y') ∨ (x = y' ∧ y = x') := by refine ⟨h.eq_and_eq_or_eq_and_eq, ?_⟩ rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) · assumption exact h.symm lemma IsLink.isLink_iff_sym2_eq (h : G.IsLink e x y) {x' y' : α} : G.IsLink e x' y' ↔ s(x, y) = s(x', y') := by rw [h.isLink_iff, Sym2.eq_iff] /-! ### Edge-vertex incidence -/ /-- The unary incidence predicate of `G`. `G.Inc e x` means that the vertex `x` is one or both of the ends of the edge `e`. In the `Inc` namespace, we use `edge` and `vertex` to refer to `e` and `x`. -/ def Inc (G : Graph α β) (e : β) (x : α) : Prop := ∃ y, G.IsLink e x y -- Cannot be @[simp] because `x` cannot be inferred by `simp`. lemma Inc.edge_mem (h : G.Inc e x) : e ∈ E(G) := h.choose_spec.edge_mem -- Cannot be @[simp] because `e` cannot be inferred by `simp`. lemma Inc.vertex_mem (h : G.Inc e x) : x ∈ V(G) := h.choose_spec.left_mem -- Cannot be @[simp] because `y` cannot be inferred by `simp`. lemma IsLink.inc_left (h : G.IsLink e x y) : G.Inc e x := ⟨y, h⟩ -- Cannot be @[simp] because `x` cannot be inferred by `simp`. lemma IsLink.inc_right (h : G.IsLink e x y) : G.Inc e y := ⟨x, h.symm⟩ lemma Inc.eq_or_eq_of_isLink (h : G.Inc e x) (h' : G.IsLink e y z) : x = y ∨ x = z := h.choose_spec.left_eq_or_eq h' lemma Inc.eq_of_isLink_of_ne_left (h : G.Inc e x) (h' : G.IsLink e y z) (hxy : x ≠ y) : x = z := (h.eq_or_eq_of_isLink h').elim (False.elim ∘ hxy) id lemma IsLink.isLink_iff_eq (h : G.IsLink e x y) : G.IsLink e x z ↔ z = y := ⟨fun h' ↦ h'.right_unique h, fun h' ↦ h' ▸ h⟩ /-- The binary incidence predicate can be expressed in terms of the unary one. -/ lemma isLink_iff_inc : G.IsLink e x y ↔ G.Inc e x ∧ G.Inc e y ∧ ∀ z, G.Inc e z → z = x ∨ z = y := by refine ⟨fun h ↦ ⟨h.inc_left, h.inc_right, fun z h' ↦ h'.eq_or_eq_of_isLink h⟩, ?_⟩ rintro ⟨⟨x', hx'⟩, ⟨y', hy'⟩, h⟩ obtain rfl | rfl := h _ hx'.inc_right · obtain rfl | rfl := hx'.left_eq_or_eq hy' · assumption exact hy'.symm assumption /-- Given a proof that the edge `e` is incident with the vertex `x` in `G`, noncomputably find the other end of `e`. (If `e` is a loop, this is equal to `x` itself). -/ protected noncomputable def Inc.other (h : G.Inc e x) : α := h.choose @[simp] lemma Inc.isLink_other (h : G.Inc e x) : G.IsLink e x h.other := h.choose_spec @[simp] lemma Inc.inc_other (h : G.Inc e x) : G.Inc e h.other := h.isLink_other.inc_right lemma Inc.eq_or_eq_or_eq (hx : G.Inc e x) (hy : G.Inc e y) (hz : G.Inc e z) : x = y ∨ x = z ∨ y = z := by by_contra! hcon obtain ⟨x', hx'⟩ := hx obtain rfl := hy.eq_of_isLink_of_ne_left hx' hcon.1.symm obtain rfl := hz.eq_of_isLink_of_ne_left hx' hcon.2.1.symm exact hcon.2.2 rfl /-- `G.IsLoopAt e x` means that both ends of the edge `e` are equal to the vertex `x`. -/ def IsLoopAt (G : Graph α β) (e : β) (x : α) : Prop := G.IsLink e x x @[simp] lemma isLink_self_iff : G.IsLink e x x ↔ G.IsLoopAt e x := Iff.rfl lemma IsLoopAt.inc (h : G.IsLoopAt e x) : G.Inc e x := IsLink.inc_left h lemma IsLoopAt.eq_of_inc (h : G.IsLoopAt e x) (h' : G.Inc e y) : x = y := by obtain rfl | rfl := h'.eq_or_eq_of_isLink h <;> rfl -- Cannot be @[simp] because `x` cannot be inferred by `simp`. lemma IsLoopAt.edge_mem (h : G.IsLoopAt e x) : e ∈ E(G) := h.inc.edge_mem -- Cannot be @[simp] because `e` cannot be inferred by `simp`. lemma IsLoopAt.vertex_mem (h : G.IsLoopAt e x) : x ∈ V(G) := h.inc.vertex_mem /-- `G.IsNonloopAt e x` means that the vertex `x` is one but not both of the ends of the edge =`e`, or equivalently that `e` is incident with `x` but not a loop at `x` - see `Graph.isNonloopAt_iff_inc_not_isLoopAt`. -/ def IsNonloopAt (G : Graph α β) (e : β) (x : α) : Prop := ∃ y ≠ x, G.IsLink e x y lemma IsNonloopAt.inc (h : G.IsNonloopAt e x) : G.Inc e x := h.choose_spec.2.inc_left -- Cannot be @[simp] because `x` cannot be inferred by `simp`. lemma IsNonloopAt.edge_mem (h : G.IsNonloopAt e x) : e ∈ E(G) := h.inc.edge_mem -- Cannot be @[simp] because `e` cannot be inferred by `simp`. lemma IsNonloopAt.vertex_mem (h : G.IsNonloopAt e x) : x ∈ V(G) := h.inc.vertex_mem lemma IsLoopAt.not_isNonloopAt (h : G.IsLoopAt e x) (y : α) : ¬ G.IsNonloopAt e y := by rintro ⟨z, hyz, hy⟩ rw [← h.eq_of_inc hy.inc_left, ← h.eq_of_inc hy.inc_right] at hyz exact hyz rfl lemma IsNonloopAt.not_isLoopAt (h : G.IsNonloopAt e x) (y : α) : ¬ G.IsLoopAt e y := fun h' ↦ h'.not_isNonloopAt x h lemma isNonloopAt_iff_inc_not_isLoopAt : G.IsNonloopAt e x ↔ G.Inc e x ∧ ¬ G.IsLoopAt e x := ⟨fun h ↦ ⟨h.inc, h.not_isLoopAt _⟩, fun ⟨⟨y, hy⟩, hn⟩ ↦ ⟨y, mt (fun h ↦ h ▸ hy) hn, hy⟩⟩ lemma isLoopAt_iff_inc_not_isNonloopAt : G.IsLoopAt e x ↔ G.Inc e x ∧ ¬ G.IsNonloopAt e x := by simp +contextual [isNonloopAt_iff_inc_not_isLoopAt, iff_def, IsLoopAt.inc] lemma Inc.isLoopAt_or_isNonloopAt (h : G.Inc e x) : G.IsLoopAt e x ∨ G.IsNonloopAt e x := by simp [isNonloopAt_iff_inc_not_isLoopAt, h, em] /-! ### Adjacency -/ /-- `G.Adj x y` means that `G` has an edge whose ends are the vertices `x` and `y`. -/ def Adj (G : Graph α β) (x y : α) : Prop := ∃ e, G.IsLink e x y protected lemma Adj.symm (h : G.Adj x y) : G.Adj y x := ⟨_, h.choose_spec.symm⟩ lemma adj_comm (x y) : G.Adj x y ↔ G.Adj y x := ⟨.symm, .symm⟩ -- Cannot be @[simp] because `y` cannot be inferred by `simp`. lemma Adj.left_mem (h : G.Adj x y) : x ∈ V(G) := h.choose_spec.left_mem -- Cannot be @[simp] because `x` cannot be inferred by `simp`. lemma Adj.right_mem (h : G.Adj x y) : y ∈ V(G) := h.symm.left_mem lemma IsLink.adj (h : G.IsLink e x y) : G.Adj x y := ⟨e, h⟩ /-! ### Extensionality -/ /-- `edgeSet` can be determined using `IsLink`, so the graph constructed from `G.vertexSet` and `G.IsLink` using any value for `edgeSet` is equal to `G` itself. -/ @[simp] lemma mk_eq_self (G : Graph α β) {E : Set β} (hE : ∀ e, e ∈ E ↔ ∃ x y, G.IsLink e x y) : Graph.mk V(G) G.IsLink E (by simpa [show E = E(G) by simp [Set.ext_iff, hE, G.edge_mem_iff_exists_isLink]] using G.isLink_symm) (fun _ _ _ _ _ h h' ↦ h.left_eq_or_eq h') hE (fun _ _ _ ↦ IsLink.left_mem) = G := by obtain rfl : E = E(G) := by simp [Set.ext_iff, hE, G.edge_mem_iff_exists_isLink] cases G with | _ _ _ _ _ _ h _ => simp /-- Two graphs with the same vertex set and binary incidences are equal. (We use this as the default extensionality lemma rather than adding `@[ext]` to the definition of `Graph`, so it doesn't require equality of the edge sets.) -/ @[ext] protected lemma ext {G₁ G₂ : Graph α β} (hV : V(G₁) = V(G₂)) (h : ∀ e x y, G₁.IsLink e x y ↔ G₂.IsLink e x y) : G₁ = G₂ := by rw [← G₁.mk_eq_self G₁.edge_mem_iff_exists_isLink, ← G₂.mk_eq_self G₂.edge_mem_iff_exists_isLink] convert rfl using 2 · exact hV.symm · simp [funext_iff, h] simp [edgeSet_eq_setOf_exists_isLink, h] /-- Two graphs with the same vertex set and unary incidences are equal. -/ lemma ext_inc {G₁ G₂ : Graph α β} (hV : V(G₁) = V(G₂)) (h : ∀ e x, G₁.Inc e x ↔ G₂.Inc e x) : G₁ = G₂ := Graph.ext hV fun _ _ _ ↦ by simp_rw [isLink_iff_inc, h] /-! ### Sets of edges or loops incident to a vertex -/ /-- `G.incidenceSet x` is the set of edges incident to `x` in `G`. -/ def incidenceSet (x : α) : Set β := {e | G.Inc e x} @[simp] theorem mem_incidenceSet (x : α) (e : β) : e ∈ G.incidenceSet x ↔ G.Inc e x := Iff.rfl theorem incidenceSet_subset_edgeSet (x : α) : G.incidenceSet x ⊆ E(G) := fun _ ⟨_, hy⟩ ↦ hy.edge_mem /-- `G.loopSet x` is the set of loops at `x` in `G`. -/ def loopSet (x : α) : Set β := {e | G.IsLoopAt e x} @[simp] theorem mem_loopSet (x : α) (e : β) : e ∈ G.loopSet x ↔ G.IsLoopAt e x := Iff.rfl /-- The loopSet is included in the incidenceSet. -/ theorem loopSet_subset_incidenceSet (x : α) : G.loopSet x ⊆ G.incidenceSet x := fun _ he ↦ ⟨x, he⟩ end Graph
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Covering.lean
import Mathlib.Combinatorics.Quiver.Cast import Mathlib.Combinatorics.Quiver.Symmetric import Mathlib.Data.Sigma.Basic import Mathlib.Data.Sum.Basic import Mathlib.Logic.Equiv.Sum import Mathlib.Tactic.Common /-! # Covering This file defines coverings of quivers as prefunctors that are bijective on the so-called stars and costars at each vertex of the domain. ## Main definitions * `Quiver.Star u` is the type of all arrows with source `u`; * `Quiver.Costar u` is the type of all arrows with target `u`; * `Prefunctor.star φ u` is the obvious function `star u → star (φ.obj u)`; * `Prefunctor.costar φ u` is the obvious function `costar u → costar (φ.obj u)`; * `Prefunctor.IsCovering φ` means that `φ.star u` and `φ.costar u` are bijections for all `u`; * `Quiver.PathStar u` is the type of all paths with source `u`; * `Prefunctor.pathStar u` is the obvious function `PathStar u → PathStar (φ.obj u)`. ## Main statements * `Prefunctor.IsCovering.pathStar_bijective` states that if `φ` is a covering, then `φ.pathStar u` is a bijection for all `u`. In other words, every path in the codomain of `φ` lifts uniquely to its domain. ## TODO Clean up the namespaces by renaming `Prefunctor` to `Quiver.Prefunctor`. ## Tags Cover, covering, quiver, path, lift -/ open Function Quiver universe u v w variable {U : Type _} [Quiver.{u + 1} U] {V : Type _} [Quiver.{v + 1} V] (φ : U ⥤q V) {W : Type _} [Quiver.{w + 1} W] (ψ : V ⥤q W) /-- The `Quiver.Star` at a vertex is the collection of arrows whose source is the vertex. The type `Quiver.Star u` is defined to be `Σ (v : U), (u ⟶ v)`. -/ abbrev Quiver.Star (u : U) := Σ v : U, u ⟶ v /-- Constructor for `Quiver.Star`. Defined to be `Sigma.mk`. -/ protected abbrev Quiver.Star.mk {u v : U} (f : u ⟶ v) : Quiver.Star u := ⟨_, f⟩ /-- The `Quiver.Costar` at a vertex is the collection of arrows whose target is the vertex. The type `Quiver.Costar v` is defined to be `Σ (u : U), (u ⟶ v)`. -/ abbrev Quiver.Costar (v : U) := Σ u : U, u ⟶ v /-- Constructor for `Quiver.Costar`. Defined to be `Sigma.mk`. -/ protected abbrev Quiver.Costar.mk {u v : U} (f : u ⟶ v) : Quiver.Costar v := ⟨_, f⟩ /-- A prefunctor induces a map of `Quiver.Star` at every vertex. -/ @[simps] def Prefunctor.star (u : U) : Quiver.Star u → Quiver.Star (φ.obj u) := fun F => Quiver.Star.mk (φ.map F.2) /-- A prefunctor induces a map of `Quiver.Costar` at every vertex. -/ @[simps] def Prefunctor.costar (u : U) : Quiver.Costar u → Quiver.Costar (φ.obj u) := fun F => Quiver.Costar.mk (φ.map F.2) @[simp] theorem Prefunctor.star_apply {u v : U} (e : u ⟶ v) : φ.star u (Quiver.Star.mk e) = Quiver.Star.mk (φ.map e) := rfl @[simp] theorem Prefunctor.costar_apply {u v : U} (e : u ⟶ v) : φ.costar v (Quiver.Costar.mk e) = Quiver.Costar.mk (φ.map e) := rfl theorem Prefunctor.star_comp (u : U) : (φ ⋙q ψ).star u = ψ.star (φ.obj u) ∘ φ.star u := rfl theorem Prefunctor.costar_comp (u : U) : (φ ⋙q ψ).costar u = ψ.costar (φ.obj u) ∘ φ.costar u := rfl /-- A prefunctor is a covering of quivers if it defines bijections on all stars and costars. -/ protected structure Prefunctor.IsCovering : Prop where star_bijective : ∀ u, Bijective (φ.star u) costar_bijective : ∀ u, Bijective (φ.costar u) @[simp] theorem Prefunctor.IsCovering.map_injective (hφ : φ.IsCovering) {u v : U} : Injective fun f : u ⟶ v => φ.map f := by rintro f g he have : φ.star u (Quiver.Star.mk f) = φ.star u (Quiver.Star.mk g) := by simpa using he simpa using (hφ.star_bijective u).left this theorem Prefunctor.IsCovering.comp (hφ : φ.IsCovering) (hψ : ψ.IsCovering) : (φ ⋙q ψ).IsCovering := ⟨fun _ => (hψ.star_bijective _).comp (hφ.star_bijective _), fun _ => (hψ.costar_bijective _).comp (hφ.costar_bijective _)⟩ theorem Prefunctor.IsCovering.of_comp_right (hψ : ψ.IsCovering) (hφψ : (φ ⋙q ψ).IsCovering) : φ.IsCovering := ⟨fun _ => (Bijective.of_comp_iff' (hψ.star_bijective _) _).mp (hφψ.star_bijective _), fun _ => (Bijective.of_comp_iff' (hψ.costar_bijective _) _).mp (hφψ.costar_bijective _)⟩ theorem Prefunctor.IsCovering.of_comp_left (hφ : φ.IsCovering) (hφψ : (φ ⋙q ψ).IsCovering) (φsur : Surjective φ.obj) : ψ.IsCovering := by refine ⟨fun v => ?_, fun v => ?_⟩ <;> obtain ⟨u, rfl⟩ := φsur v exacts [(Bijective.of_comp_iff _ (hφ.star_bijective u)).mp (hφψ.star_bijective u), (Bijective.of_comp_iff _ (hφ.costar_bijective u)).mp (hφψ.costar_bijective u)] /-- The star of the symmetrification of a quiver at a vertex `u` is equivalent to the sum of the star and the costar at `u` in the original quiver. -/ def Quiver.symmetrifyStar (u : U) : Quiver.Star (Symmetrify.of.obj u) ≃ Quiver.Star u ⊕ Quiver.Costar u := Equiv.sigmaSumDistrib _ _ /-- The costar of the symmetrification of a quiver at a vertex `u` is equivalent to the sum of the costar and the star at `u` in the original quiver. -/ def Quiver.symmetrifyCostar (u : U) : Quiver.Costar (Symmetrify.of.obj u) ≃ Quiver.Costar u ⊕ Quiver.Star u := Equiv.sigmaSumDistrib _ _ theorem Prefunctor.symmetrifyStar (u : U) : φ.symmetrify.star u = (Quiver.symmetrifyStar _).symm ∘ Sum.map (φ.star u) (φ.costar u) ∘ Quiver.symmetrifyStar u := by rw [Equiv.eq_symm_comp (e := Quiver.symmetrifyStar (φ.obj u))] ext ⟨v, f | g⟩ <;> -- Porting note (https://github.com/leanprover-community/mathlib4/issues/10745): was `simp [Quiver.symmetrifyStar]` simp only [Quiver.symmetrifyStar, Function.comp_apply] <;> erw [Equiv.sigmaSumDistrib_apply, Equiv.sigmaSumDistrib_apply] <;> simp protected theorem Prefunctor.symmetrifyCostar (u : U) : φ.symmetrify.costar u = (Quiver.symmetrifyCostar _).symm ∘ Sum.map (φ.costar u) (φ.star u) ∘ Quiver.symmetrifyCostar u := by rw [Equiv.eq_symm_comp (e := Quiver.symmetrifyCostar (φ.obj u))] ext ⟨v, f | g⟩ <;> -- Porting note (https://github.com/leanprover-community/mathlib4/issues/10745): was `simp [Quiver.symmetrifyCostar]` simp only [Quiver.symmetrifyCostar, Function.comp_apply] <;> erw [Equiv.sigmaSumDistrib_apply, Equiv.sigmaSumDistrib_apply] <;> simp protected theorem Prefunctor.IsCovering.symmetrify (hφ : φ.IsCovering) : φ.symmetrify.IsCovering := by refine ⟨fun u => ?_, fun u => ?_⟩ <;> simp [φ.symmetrifyStar, φ.symmetrifyCostar, hφ.star_bijective u, hφ.costar_bijective u] /-- The path star at a vertex `u` is the type of all paths starting at `u`. The type `Quiver.PathStar u` is defined to be `Σ v : U, Path u v`. -/ abbrev Quiver.PathStar (u : U) := Σ v : U, Path u v /-- Constructor for `Quiver.PathStar`. Defined to be `Sigma.mk`. -/ protected abbrev Quiver.PathStar.mk {u v : U} (p : Path u v) : Quiver.PathStar u := ⟨_, p⟩ /-- A prefunctor induces a map of path stars. -/ def Prefunctor.pathStar (u : U) : Quiver.PathStar u → Quiver.PathStar (φ.obj u) := fun p => Quiver.PathStar.mk (φ.mapPath p.2) @[simp] theorem Prefunctor.pathStar_apply {u v : U} (p : Path u v) : φ.pathStar u (Quiver.PathStar.mk p) = Quiver.PathStar.mk (φ.mapPath p) := rfl theorem Prefunctor.pathStar_injective (hφ : ∀ u, Injective (φ.star u)) (u : U) : Injective (φ.pathStar u) := by dsimp +unfoldPartialApp [Prefunctor.pathStar, Quiver.PathStar.mk] rintro ⟨v₁, p₁⟩ induction p₁ with | nil => rintro ⟨y₂, p₂⟩ rcases p₂ with - | ⟨p₂, e₂⟩ · intro; rfl -- Porting note: goal not present in lean3. · intro h simp only [mapPath_cons, Sigma.mk.inj_iff] at h exfalso obtain ⟨h, h'⟩ := h rw [← Path.eq_cast_iff_heq rfl h.symm, Path.cast_cons] at h' exact (Path.nil_ne_cons _ _) h' | cons p₁ e₁ ih => rename_i x₁ y₁ rintro ⟨y₂, p₂⟩ rcases p₂ with - | ⟨p₂, e₂⟩ · intro h simp only [mapPath_cons, Sigma.mk.inj_iff] at h exfalso obtain ⟨h, h'⟩ := h rw [← Path.cast_eq_iff_heq rfl h, Path.cast_cons] at h' exact (Path.cons_ne_nil _ _) h' · rename_i x₂ intro h simp only [mapPath_cons, Sigma.mk.inj_iff] at h obtain ⟨hφy, h'⟩ := h rw [← Path.cast_eq_iff_heq rfl hφy, Path.cast_cons, Path.cast_rfl_rfl] at h' have hφx := Path.obj_eq_of_cons_eq_cons h' have hφp := Path.heq_of_cons_eq_cons h' have hφe := HEq.trans (Hom.cast_heq rfl hφy _).symm (Path.hom_heq_of_cons_eq_cons h') have h_path_star : φ.pathStar u ⟨x₁, p₁⟩ = φ.pathStar u ⟨x₂, p₂⟩ := by simp only [Prefunctor.pathStar_apply, Sigma.mk.inj_iff]; exact ⟨hφx, hφp⟩ cases ih h_path_star have h_star : φ.star x₁ ⟨y₁, e₁⟩ = φ.star x₁ ⟨y₂, e₂⟩ := by simp only [Prefunctor.star_apply, Sigma.mk.inj_iff]; exact ⟨hφy, hφe⟩ cases hφ x₁ h_star rfl theorem Prefunctor.pathStar_surjective (hφ : ∀ u, Surjective (φ.star u)) (u : U) : Surjective (φ.pathStar u) := by dsimp +unfoldPartialApp [Prefunctor.pathStar, Quiver.PathStar.mk] rintro ⟨v, p⟩ induction p with | nil => use ⟨u, Path.nil⟩ simp only [Prefunctor.mapPath_nil] | cons p' ev ih => obtain ⟨⟨u', q'⟩, h⟩ := ih simp only at h obtain ⟨rfl, rfl⟩ := h obtain ⟨⟨u'', eu⟩, k⟩ := hφ u' ⟨_, ev⟩ simp only [star_apply, Sigma.mk.inj_iff] at k -- Porting note: was `obtain ⟨rfl, rfl⟩ := k` obtain ⟨rfl, k⟩ := k simp only [heq_eq_eq] at k subst k use ⟨_, q'.cons eu⟩ simp only [Prefunctor.mapPath_cons] theorem Prefunctor.pathStar_bijective (hφ : ∀ u, Bijective (φ.star u)) (u : U) : Bijective (φ.pathStar u) := ⟨φ.pathStar_injective (fun u => (hφ u).1) _, φ.pathStar_surjective (fun u => (hφ u).2) _⟩ namespace Prefunctor.IsCovering variable {φ} protected theorem pathStar_bijective (hφ : φ.IsCovering) (u : U) : Bijective (φ.pathStar u) := φ.pathStar_bijective hφ.1 u end Prefunctor.IsCovering section HasInvolutiveReverse variable [HasInvolutiveReverse U] [HasInvolutiveReverse V] /-- In a quiver with involutive inverses, the star and costar at every vertex are equivalent. This map is induced by `Quiver.reverse`. -/ @[simps] def Quiver.starEquivCostar (u : U) : Quiver.Star u ≃ Quiver.Costar u where toFun e := ⟨e.1, reverse e.2⟩ invFun e := ⟨e.1, reverse e.2⟩ left_inv e := by simp right_inv e := by simp @[simp] theorem Quiver.starEquivCostar_apply {u v : U} (e : u ⟶ v) : Quiver.starEquivCostar u (Quiver.Star.mk e) = Quiver.Costar.mk (reverse e) := rfl @[simp] theorem Quiver.starEquivCostar_symm_apply {u v : U} (e : u ⟶ v) : (Quiver.starEquivCostar v).symm (Quiver.Costar.mk e) = Quiver.Star.mk (reverse e) := rfl variable [Prefunctor.MapReverse φ] theorem Prefunctor.costar_conj_star (u : U) : φ.costar u = Quiver.starEquivCostar (φ.obj u) ∘ φ.star u ∘ (Quiver.starEquivCostar u).symm := by ext ⟨v, f⟩ <;> simp theorem Prefunctor.bijective_costar_iff_bijective_star (u : U) : Bijective (φ.costar u) ↔ Bijective (φ.star u) := by rw [Prefunctor.costar_conj_star φ, EquivLike.comp_bijective, EquivLike.bijective_comp] theorem Prefunctor.isCovering_of_bijective_star (h : ∀ u, Bijective (φ.star u)) : φ.IsCovering := ⟨h, fun u => (φ.bijective_costar_iff_bijective_star u).2 (h u)⟩ theorem Prefunctor.isCovering_of_bijective_costar (h : ∀ u, Bijective (φ.costar u)) : φ.IsCovering := ⟨fun u => (φ.bijective_costar_iff_bijective_star u).1 (h u), h⟩ end HasInvolutiveReverse
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/ReflQuiver.lean
import Mathlib.Data.Set.Function import Mathlib.CategoryTheory.Category.Cat /-! # Reflexive Quivers This module defines reflexive quivers. A reflexive quiver, or "refl quiver" for short, extends a quiver with a specified endoarrow on each term in its type of objects. We also introduce morphisms between reflexive quivers, called reflexive prefunctors or "refl prefunctors" for short. Note: Currently Category does not extend ReflQuiver, although it could. (TODO: do this) -/ namespace CategoryTheory universe v v₁ v₂ u u₁ u₂ /-- A reflexive quiver extends a quiver with a specified arrow `id X : X ⟶ X` for each `X` in its type of objects. We denote these arrows by `id` since categories can be understood as an extension of refl quivers. -/ class ReflQuiver (obj : Type u) : Type max u v extends Quiver.{v} obj where /-- The identity morphism on an object. -/ id : ∀ X : obj, Hom X X /-- Notation for the identity morphism in a category. -/ scoped notation "𝟙rq" => ReflQuiver.id -- type as \b1 @[simp] theorem ReflQuiver.homOfEq_id {V : Type*} [ReflQuiver V] {X X' : V} (hX : X = X') : Quiver.homOfEq (𝟙rq X) hX hX = 𝟙rq X' := by subst hX; rfl instance catToReflQuiver {C : Type u} [inst : Category.{v} C] : ReflQuiver.{v+1, u} C := { inst with } @[simp] theorem ReflQuiver.id_eq_id {C : Type*} [Category C] (X : C) : 𝟙rq X = 𝟙 X := rfl /-- A morphism of reflexive quivers called a `ReflPrefunctor`. -/ structure ReflPrefunctor (V : Type u₁) [ReflQuiver.{v₁} V] (W : Type u₂) [ReflQuiver.{v₂} W] extends Prefunctor V W where /-- A functor preserves identity morphisms. -/ map_id : ∀ X : V, map (𝟙rq X) = 𝟙rq (obj X) := by cat_disch namespace ReflPrefunctor -- These lemmas cannot be `@[simp]` because after `whnfR` they have a variable on the LHS. -- Nevertheless they are sometimes useful when building functors. lemma mk_obj {V W : Type*} [ReflQuiver V] [ReflQuiver W] {obj : V → W} {map} {X : V} : (Prefunctor.mk obj map).obj X = obj X := rfl lemma mk_map {V W : Type*} [ReflQuiver V] [ReflQuiver W] {obj : V → W} {map} {X Y : V} {f : X ⟶ Y} : (Prefunctor.mk obj map).map f = map f := rfl /-- Proving equality between reflexive prefunctors. This isn't an extensionality lemma, because usually you don't really want to do this. -/ theorem ext {V : Type u} [ReflQuiver.{v₁} V] {W : Type u₂} [ReflQuiver.{v₂} W] {F G : ReflPrefunctor V W} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ (X Y : V) (f : X ⟶ Y), F.map f = Eq.recOn (h_obj Y).symm (Eq.recOn (h_obj X).symm (G.map f))) : F = G := by obtain ⟨⟨F_obj⟩⟩ := F obtain ⟨⟨G_obj⟩⟩ := G obtain rfl : F_obj = G_obj := (Set.eqOn_univ F_obj G_obj).mp fun _ _ ↦ h_obj _ congr funext X Y f simpa using h_map X Y f /-- This may be a more useful form of `ReflPrefunctor.ext`. -/ theorem ext' {V W : Type u} [ReflQuiver.{v} V] [ReflQuiver.{v} W] {F G : ReflPrefunctor V W} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ (X Y : V) (f : X ⟶ Y), F.map f = Quiver.homOfEq (G.map f) (h_obj _).symm (h_obj _).symm) : F = G := by obtain ⟨Fpre, Fid⟩ := F obtain ⟨Gpre, Gid⟩ := G obtain rfl : Fpre = Gpre := Prefunctor.ext' (V := V) (W := W) h_obj h_map rfl /-- The identity morphism between reflexive quivers. -/ @[simps!] def id (V : Type*) [ReflQuiver V] : ReflPrefunctor V V where __ := Prefunctor.id _ map_id _ := rfl instance (V : Type*) [ReflQuiver V] : Inhabited (ReflPrefunctor V V) := ⟨id V⟩ /-- Composition of morphisms between reflexive quivers. -/ @[simps!] def comp {U : Type*} [ReflQuiver U] {V : Type*} [ReflQuiver V] {W : Type*} [ReflQuiver W] (F : ReflPrefunctor U V) (G : ReflPrefunctor V W) : ReflPrefunctor U W where __ := F.toPrefunctor.comp G.toPrefunctor map_id _ := by simp [F.map_id, G.map_id] @[simp] theorem comp_id {U V : Type*} [ReflQuiver U] [ReflQuiver V] (F : ReflPrefunctor U V) : F.comp (id _) = F := rfl @[simp] theorem id_comp {U V : Type*} [ReflQuiver U] [ReflQuiver V] (F : ReflPrefunctor U V) : (id _).comp F = F := rfl @[simp] theorem comp_assoc {U V W Z : Type*} [ReflQuiver U] [ReflQuiver V] [ReflQuiver W] [ReflQuiver Z] (F : ReflPrefunctor U V) (G : ReflPrefunctor V W) (H : ReflPrefunctor W Z) : (F.comp G).comp H = F.comp (G.comp H) := rfl /-- Notation for a prefunctor between reflexive quivers. -/ infixl:50 " ⥤rq " => ReflPrefunctor /-- Notation for composition of reflexive prefunctors. -/ infixl:60 " ⋙rq " => ReflPrefunctor.comp /-- Notation for the identity prefunctor on a reflexive quiver. -/ notation "𝟭rq" => id theorem congr_map {U V : Type*} [Quiver U] [Quiver V] (F : U ⥤q V) {X Y : U} {f g : X ⟶ Y} (h : f = g) : F.map f = F.map g := congrArg F.map h /-- An equality of refl prefunctors gives an equality on objects. -/ theorem congr_obj {U V : Type*} [ReflQuiver U] [ReflQuiver V] {F G : U ⥤rq V} (e : F = G) (X : U) : F.obj X = G.obj X := by cases e; rfl /-- An equality of refl prefunctors gives an equality on homs. -/ theorem congr_hom {U V : Type*} [ReflQuiver U] [ReflQuiver V] {F G : U ⥤rq V} (e : F = G) {X Y : U} (f : X ⟶ Y) : Quiver.homOfEq (F.map f) (congr_obj e X) (congr_obj e Y) = G.map f := by subst e simp end ReflPrefunctor /-- A functor has an underlying refl prefunctor. -/ def Functor.toReflPrefunctor {C D} [Category C] [Category D] (F : C ⥤ D) : C ⥤rq D := { F with } theorem Functor.toReflPrefunctor.map_comp {C D E} [Category C] [Category D] [Category E] (F : C ⥤ D) (G : D ⥤ E) : toReflPrefunctor (F ⋙ G) = toReflPrefunctor F ⋙rq toReflPrefunctor G := rfl @[simp] theorem Functor.toReflPrefunctor_toPrefunctor {C D : Cat} (F : C ⥤ D) : (Functor.toReflPrefunctor F).toPrefunctor = F.toPrefunctor := rfl namespace ReflQuiver open Opposite /-- `Vᵒᵖ` reverses the direction of all arrows of `V`. -/ instance opposite {V} [ReflQuiver V] : ReflQuiver Vᵒᵖ where id X := op (𝟙rq X.unop) instance discreteReflQuiver (V : Type u) : ReflQuiver.{u+1} (Discrete V) := { discreteCategory V with } end ReflQuiver end CategoryTheory
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Arborescence.lean
import Mathlib.Combinatorics.Quiver.Path import Mathlib.Combinatorics.Quiver.Subquiver import Mathlib.Order.WellFounded /-! # Arborescences A quiver `V` is an arborescence (or directed rooted tree) when we have a root vertex `root : V` such that for every `b : V` there is a unique path from `root` to `b`. ## Main definitions - `Quiver.Arborescence V`: a typeclass asserting that `V` is an arborescence - `arborescenceMk`: a convenient way of proving that a quiver is an arborescence - `RootedConnected r`: a typeclass asserting that there is at least one path from `r` to `b` for every `b`. - `geodesicSubtree r`: given `[RootedConnected r]`, this is a subquiver of `V` which contains just enough edges to include a shortest path from `r` to `b` for every `b`. - `geodesicArborescence : Arborescence (geodesicSubtree r)`: an instance saying that the geodesic subtree is an arborescence. This proves the directed analogue of 'every connected graph has a spanning tree'. This proof avoids the use of Zorn's lemma. -/ open Opposite universe v u namespace Quiver /-- A quiver is an arborescence when there is a unique path from the default vertex to every other vertex. -/ class Arborescence (V : Type u) [Quiver.{v} V] : Type max u v where /-- The root of the arborescence. -/ root : V /-- There is a unique path from the root to any other vertex. -/ uniquePath : ∀ b : V, Unique (Path root b) /-- The root of an arborescence. -/ def root (V : Type u) [Quiver V] [Arborescence V] : V := Arborescence.root instance {V : Type u} [Quiver V] [Arborescence V] (b : V) : Unique (Path (root V) b) := Arborescence.uniquePath b /-- To show that `[Quiver V]` is an arborescence with root `r : V`, it suffices to - provide a height function `V → ℕ` such that every arrow goes from a lower vertex to a higher vertex, - show that every vertex has at most one arrow to it, and - show that every vertex other than `r` has an arrow to it. -/ noncomputable def arborescenceMk {V : Type u} [Quiver V] (r : V) (height : V → ℕ) (height_lt : ∀ ⦃a b⦄, (a ⟶ b) → height a < height b) (unique_arrow : ∀ ⦃a b c : V⦄ (e : a ⟶ c) (f : b ⟶ c), a = b ∧ e ≍ f) (root_or_arrow : ∀ b, b = r ∨ ∃ a, Nonempty (a ⟶ b)) : Arborescence V where root := r uniquePath b := ⟨Classical.inhabited_of_nonempty (by rcases show ∃ n, height b < n from ⟨_, Nat.lt.base _⟩ with ⟨n, hn⟩ induction n generalizing b with | zero => exact False.elim (Nat.not_lt_zero _ hn) | succ n ih => rcases root_or_arrow b with (⟨⟨⟩⟩ | ⟨a, ⟨e⟩⟩) · exact ⟨Path.nil⟩ · rcases ih a (lt_of_lt_of_le (height_lt e) (Nat.lt_succ_iff.mp hn)) with ⟨p⟩ exact ⟨p.cons e⟩), by have height_le : ∀ {a b}, Path a b → height a ≤ height b := by intro a b p induction p with | nil => rfl | cons _ e ih => exact le_of_lt (lt_of_le_of_lt ih (height_lt e)) suffices ∀ p q : Path r b, p = q by intro p apply this intro p q induction p with | nil => rcases q with _ | ⟨q, f⟩ · rfl · exact False.elim (lt_irrefl _ (lt_of_le_of_lt (height_le q) (height_lt f))) | cons p e ih => rcases q with _ | ⟨q, f⟩ · exact False.elim (lt_irrefl _ (lt_of_le_of_lt (height_le p) (height_lt e))) · rcases unique_arrow e f with ⟨⟨⟩, ⟨⟩⟩ rw [ih]⟩ /-- `RootedConnected r` means that there is a path from `r` to any other vertex. -/ class RootedConnected {V : Type u} [Quiver V] (r : V) : Prop where nonempty_path : ∀ b : V, Nonempty (Path r b) attribute [instance] RootedConnected.nonempty_path section GeodesicSubtree variable {V : Type u} [Quiver.{v + 1} V] (r : V) [RootedConnected r] /-- A path from `r` of minimal length. -/ noncomputable def shortestPath (b : V) : Path r b := WellFounded.min (measure Path.length).wf Set.univ Set.univ_nonempty /-- The length of a path is at least the length of the shortest path -/ theorem shortest_path_spec {a : V} (p : Path r a) : (shortestPath r a).length ≤ p.length := not_lt.mp (WellFounded.not_lt_min (measure _).wf Set.univ _ trivial) /-- A subquiver which by construction is an arborescence. -/ def geodesicSubtree : WideSubquiver V := fun a b => { e | ∃ p : Path r a, shortestPath r b = p.cons e } noncomputable instance geodesicArborescence : Arborescence (geodesicSubtree r) := arborescenceMk r (fun a => (shortestPath r a).length) (by rintro a b ⟨e, p, h⟩ simp_rw [h, Path.length_cons, Nat.lt_succ_iff] apply shortest_path_spec) (by rintro a b c ⟨e, p, h⟩ ⟨f, q, j⟩ cases h.symm.trans j constructor <;> rfl) (by intro b rcases hp : shortestPath r b with (_ | ⟨p, e⟩) · exact Or.inl rfl · exact Or.inr ⟨_, ⟨⟨e, p, hp⟩⟩⟩) end GeodesicSubtree end Quiver
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Basic.lean
import Mathlib.Data.Opposite import Mathlib.Tactic.ToDual /-! # Quivers This module defines quivers. A quiver on a type `V` of vertices assigns to every pair `a b : V` of vertices a type `a ⟶ b` of arrows from `a` to `b`. This is a very permissive notion of directed graph. ## Implementation notes Currently `Quiver` is defined with `Hom : V → V → Sort v`. This is different from the category theory setup, where we insist that morphisms live in some `Type`. There's some balance here: it's nice to allow `Prop` to ensure there are no multiple arrows, but it also results in error-prone universe signatures when constraints require a `Type`. -/ open Opposite -- We use the same universe order as in category theory. -- See note [category theory universes] universe v v₁ v₂ u u₁ u₂ /-- A quiver `G` on a type `V` of vertices assigns to every pair `a b : V` of vertices a type `a ⟶ b` of arrows from `a` to `b`. For graphs with no repeated edges, one can use `Quiver.{0} V`, which ensures `a ⟶ b : Prop`. For multigraphs, one can use `Quiver.{v+1} V`, which ensures `a ⟶ b : Type v`. Because `Category` will later extend this class, we call the field `Hom`. Except when constructing instances, you should rarely see this, and use the `⟶` notation instead. -/ class Quiver (V : Type u) where /-- The type of edges/arrows/morphisms between a given source and target. -/ Hom : V → V → Sort v attribute [to_dual self (reorder := 3 4)] Quiver.Hom /-- Notation for the type of edges/arrows/morphisms between a given source and target in a quiver or category. -/ infixr:10 " ⟶ " => Quiver.Hom namespace Quiver /-- `Vᵒᵖ` reverses the direction of all arrows of `V`. -/ instance opposite {V} [Quiver V] : Quiver Vᵒᵖ := ⟨fun a b => (unop b ⟶ unop a)ᵒᵖ⟩ /-- The opposite of an arrow in `V`. -/ @[to_dual self (reorder := 3 4)] def Hom.op {V} [Quiver V] {X Y : V} (f : X ⟶ Y) : op Y ⟶ op X := ⟨f⟩ /-- Given an arrow in `Vᵒᵖ`, we can take the "unopposite" back in `V`. -/ @[to_dual self (reorder := 3 4)] def Hom.unop {V} [Quiver V] {X Y : Vᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := Opposite.unop f /-- The bijection `(X ⟶ Y) ≃ (op Y ⟶ op X)`. -/ @[simps, to_dual self (reorder := 3 4)] def Hom.opEquiv {V} [Quiver V] {X Y : V} : (X ⟶ Y) ≃ (Opposite.op Y ⟶ Opposite.op X) where toFun := Opposite.op invFun := Opposite.unop /-- A type synonym for a quiver with no arrows. -/ def Empty (V : Type u) : Type u := V instance emptyQuiver (V : Type u) : Quiver.{u} (Empty V) := ⟨fun _ _ => PEmpty⟩ @[simp, to_dual self (reorder := 2 3)] theorem empty_arrow {V : Type u} (a b : Empty V) : (a ⟶ b) = PEmpty := rfl /-- A quiver is thin if it has no parallel arrows. -/ @[to_dual IsThin' /-- `isThin'` is equivalent to `IsThin`. It is used by `@[to_dual]` to be able to translate `IsThin`. -/] abbrev IsThin (V : Type u) [Quiver V] : Prop := ∀ a b : V, Subsingleton (a ⟶ b) section variable {V : Type*} [Quiver V] {X Y X' Y' : V} /-- An arrow in a quiver can be transported across equalities between the source and target objects. -/ @[to_dual self (reorder := 3 4, 5 6, 8 9)] def homOfEq (f : X ⟶ Y) (hX : X = X') (hY : Y = Y') : X' ⟶ Y' := by subst hX hY exact f @[simp, to_dual self (reorder := 3 4, 5 6, 8 9, 10 11, 12 13)] lemma homOfEq_trans (f : X ⟶ Y) (hX : X = X') (hY : Y = Y') {X'' Y'' : V} (hX' : X' = X'') (hY' : Y' = Y'') : homOfEq (homOfEq f hX hY) hX' hY' = homOfEq f (hX.trans hX') (hY.trans hY') := by subst hX hY hX' hY' rfl @[to_dual self (reorder := 3 4, 5 6, 7 8)] lemma homOfEq_injective (hX : X = X') (hY : Y = Y') {f g : X ⟶ Y} (h : Quiver.homOfEq f hX hY = Quiver.homOfEq g hX hY) : f = g := by subst hX hY exact h @[simp, to_dual self (reorder := 3 4)] lemma homOfEq_rfl (f : X ⟶ Y) : Quiver.homOfEq f rfl rfl = f := rfl @[to_dual self (reorder := 3 4, 5 6, 7 8)] lemma heq_of_homOfEq_ext (hX : X = X') (hY : Y = Y') {f : X ⟶ Y} {f' : X' ⟶ Y'} (e : Quiver.homOfEq f hX hY = f') : f ≍ f' := by subst hX hY rw [Quiver.homOfEq_rfl] at e rw [e] @[to_dual self (reorder := 3 4, 5 6, 9 10)] lemma homOfEq_eq_iff (f : X ⟶ Y) (g : X' ⟶ Y') (hX : X = X') (hY : Y = Y') : Quiver.homOfEq f hX hY = g ↔ f = Quiver.homOfEq g hX.symm hY.symm := by subst hX hY; simp @[to_dual self (reorder := 3 4, 5 6, 9 10)] lemma eq_homOfEq_iff (f : X ⟶ Y) (g : X' ⟶ Y') (hX : X' = X) (hY : Y' = Y) : f = Quiver.homOfEq g hX hY ↔ Quiver.homOfEq f hX.symm hY.symm = g := by subst hX hY; simp @[to_dual self (reorder := 3 4, 5 6, 7 8)] lemma homOfEq_heq (hX : X = X') (hY : Y = Y') (f : X ⟶ Y) : homOfEq f hX hY ≍ f := (heq_of_homOfEq_ext hX hY rfl).symm @[to_dual self (reorder := 3 4, 5 6, 9 10)] lemma homOfEq_heq_left_iff (f : X ⟶ Y) (g : X' ⟶ Y') (hX : X = X') (hY : Y = Y') : homOfEq f hX hY ≍ g ↔ f ≍ g := by cases hX; cases hY; rfl @[to_dual self (reorder := 3 4, 5 6, 9 10)] lemma homOfEq_heq_right_iff (f : X ⟶ Y) (g : X' ⟶ Y') (hX : X' = X) (hY : Y' = Y) : f ≍ homOfEq g hX hY ↔ f ≍ g := by cases hX; cases hY; rfl end end Quiver
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Path.lean
import Mathlib.Combinatorics.Quiver.Prefunctor import Mathlib.Logic.Lemmas import Batteries.Data.List.Basic /-! # Paths in quivers Given a quiver `V`, we define the type of paths from `a : V` to `b : V` as an inductive family. We define composition of paths and the action of prefunctors on paths. -/ open Function universe v v₁ v₂ v₃ u u₁ u₂ u₃ namespace Quiver /-- `Path a b` is the type of paths from `a` to `b` through the arrows of `G`. -/ inductive Path {V : Type u} [Quiver.{v} V] (a : V) : V → Sort max (u + 1) v | nil : Path a a | cons : ∀ {b c : V}, Path a b → (b ⟶ c) → Path a c -- See issue https://github.com/leanprover/lean4/issues/2049 compile_inductive% Path /-- An arrow viewed as a path of length one. -/ def Hom.toPath {V} [Quiver V] {a b : V} (e : a ⟶ b) : Path a b := Path.nil.cons e namespace Path variable {V : Type u} [Quiver V] {a b c d : V} lemma nil_ne_cons (p : Path a b) (e : b ⟶ a) : Path.nil ≠ p.cons e := fun h => by injection h lemma cons_ne_nil (p : Path a b) (e : b ⟶ a) : p.cons e ≠ Path.nil := fun h => by injection h lemma obj_eq_of_cons_eq_cons {p : Path a b} {p' : Path a c} {e : b ⟶ d} {e' : c ⟶ d} (h : p.cons e = p'.cons e') : b = c := by injection h lemma heq_of_cons_eq_cons {p : Path a b} {p' : Path a c} {e : b ⟶ d} {e' : c ⟶ d} (h : p.cons e = p'.cons e') : p ≍ p' := by injection h lemma hom_heq_of_cons_eq_cons {p : Path a b} {p' : Path a c} {e : b ⟶ d} {e' : c ⟶ d} (h : p.cons e = p'.cons e') : e ≍ e' := by injection h /-- The length of a path is the number of arrows it uses. -/ def length {a : V} : ∀ {b : V}, Path a b → ℕ | _, nil => 0 | _, cons p _ => p.length + 1 instance {a : V} : Inhabited (Path a a) := ⟨nil⟩ @[simp] theorem length_nil {a : V} : (nil : Path a a).length = 0 := rfl @[simp] theorem length_cons (a b c : V) (p : Path a b) (e : b ⟶ c) : (p.cons e).length = p.length + 1 := rfl theorem eq_of_length_zero (p : Path a b) (hzero : p.length = 0) : a = b := by cases p · rfl · cases Nat.succ_ne_zero _ hzero theorem eq_nil_of_length_zero (p : Path a a) (hzero : p.length = 0) : p = nil := by cases p · rfl · simp at hzero @[simp] lemma length_toPath {a b : V} (e : a ⟶ b) : e.toPath.length = 1 := rfl /-- Composition of paths. -/ def comp {a b : V} : ∀ {c}, Path a b → Path b c → Path a c | _, p, nil => p | _, p, cons q e => (p.comp q).cons e @[simp] theorem comp_cons {a b c d : V} (p : Path a b) (q : Path b c) (e : c ⟶ d) : p.comp (q.cons e) = (p.comp q).cons e := rfl @[simp] theorem comp_nil {a b : V} (p : Path a b) : p.comp Path.nil = p := rfl @[simp] theorem nil_comp {a : V} : ∀ {b} (p : Path a b), Path.nil.comp p = p | _, nil => rfl | _, cons p _ => by rw [comp_cons, nil_comp p] @[simp] theorem comp_assoc {a b c : V} : ∀ {d} (p : Path a b) (q : Path b c) (r : Path c d), (p.comp q).comp r = p.comp (q.comp r) | _, _, _, nil => rfl | _, p, q, cons r _ => by rw [comp_cons, comp_cons, comp_cons, comp_assoc p q r] @[simp] theorem length_comp (p : Path a b) : ∀ {c} (q : Path b c), (p.comp q).length = p.length + q.length | _, nil => rfl | _, cons _ _ => congr_arg Nat.succ (length_comp _ _) theorem comp_inj {p₁ p₂ : Path a b} {q₁ q₂ : Path b c} (hq : q₁.length = q₂.length) : p₁.comp q₁ = p₂.comp q₂ ↔ p₁ = p₂ ∧ q₁ = q₂ := by refine ⟨fun h => ?_, by rintro ⟨rfl, rfl⟩; rfl⟩ induction q₁ with | nil => rcases q₂ with _ | ⟨q₂, f₂⟩ · exact ⟨h, rfl⟩ · cases hq | cons q₁ f₁ ih => rcases q₂ with _ | ⟨q₂, f₂⟩ · cases hq · simp only [comp_cons, cons.injEq] at h obtain rfl := h.1 obtain ⟨rfl, rfl⟩ := ih (Nat.succ.inj hq) h.2.1.eq rw [h.2.2.eq] exact ⟨rfl, rfl⟩ theorem comp_inj' {p₁ p₂ : Path a b} {q₁ q₂ : Path b c} (h : p₁.length = p₂.length) : p₁.comp q₁ = p₂.comp q₂ ↔ p₁ = p₂ ∧ q₁ = q₂ := ⟨fun h_eq => (comp_inj <| Nat.add_left_cancel (n := p₂.length) <| by simpa [h] using congr_arg length h_eq).1 h_eq, by rintro ⟨rfl, rfl⟩; rfl⟩ theorem comp_injective_left (q : Path b c) : Injective fun p : Path a b => p.comp q := fun _ _ h => ((comp_inj rfl).1 h).1 theorem comp_injective_right (p : Path a b) : Injective (p.comp : Path b c → Path a c) := fun _ _ h => ((comp_inj' rfl).1 h).2 @[simp] theorem comp_inj_left {p₁ p₂ : Path a b} {q : Path b c} : p₁.comp q = p₂.comp q ↔ p₁ = p₂ := q.comp_injective_left.eq_iff @[simp] theorem comp_inj_right {p : Path a b} {q₁ q₂ : Path b c} : p.comp q₁ = p.comp q₂ ↔ q₁ = q₂ := p.comp_injective_right.eq_iff lemma eq_toPath_comp_of_length_eq_succ (p : Path a b) {n : ℕ} (hp : p.length = n + 1) : ∃ (c : V) (f : a ⟶ c) (q : Quiver.Path c b) (_ : q.length = n), p = f.toPath.comp q := by induction p generalizing n with | nil => simp at hp | @cons c d p q h => cases n · rw [length_cons, Nat.zero_add, Nat.add_eq_right] at hp obtain rfl := eq_of_length_zero p hp obtain rfl := eq_nil_of_length_zero p hp exact ⟨d, q, nil, rfl, rfl⟩ · rw [length_cons, Nat.add_right_cancel_iff] at hp obtain ⟨x, q'', p'', hl, rfl⟩ := h hp exact ⟨x, q'', p''.cons q, by simpa, rfl⟩ section Decomposition variable {V R : Type*} [Quiver V] {a b : V} (p : Path a b) lemma length_ne_zero_iff_eq_comp (p : Path a b) : p.length ≠ 0 ↔ ∃ (c : V) (e : a ⟶ c) (p' : Path c b), p = e.toPath.comp p' ∧ p.length = p'.length + 1 := by refine ⟨fun h ↦ ?_, ?_⟩ · have h_len : p.length = (p.length - 1) + 1 := by omega obtain ⟨c, e, p', hp', rfl⟩ := Path.eq_toPath_comp_of_length_eq_succ p h_len exact ⟨c, e, p', rfl, by cutsat⟩ · rintro ⟨c, p', e, rfl, h⟩ simp [h] /-- Every non-empty path can be decomposed as an initial path plus a final edge. -/ lemma length_ne_zero_iff_eq_cons : p.length ≠ 0 ↔ ∃ (c : V) (p' : Path a c) (e : c ⟶ b), p = p'.cons e := by refine ⟨fun h ↦ ?_, ?_⟩ · cases p with | nil => simp at h | cons p' e => exact ⟨_, p', e, rfl⟩ · rintro ⟨c, p', e, rfl⟩ simp @[simp] lemma comp_toPath_eq_cons {a b c : V} (p : Path a b) (e : b ⟶ c) : p.comp e.toPath = p.cons e := rfl end Decomposition /-- Turn a path into a list. The list contains `a` at its head, but not `b` a priori. -/ @[simp] def toList : ∀ {b : V}, Path a b → List V | _, nil => [] | _, @cons _ _ _ c _ p _ => c :: p.toList /-- `Quiver.Path.toList` is a contravariant functor. The inversion comes from `Quiver.Path` and `List` having different preferred directions for adding elements. -/ @[simp] theorem toList_comp (p : Path a b) : ∀ {c} (q : Path b c), (p.comp q).toList = q.toList ++ p.toList | _, nil => by simp | _, @cons _ _ _ d _ q _ => by simp [toList_comp] theorem isChain_toList_nonempty : ∀ {b} (p : Path a b), (p.toList).IsChain (fun x y => Nonempty (y ⟶ x)) | _, nil => .nil | _, cons nil _ => .singleton _ | _, cons (cons p g) _ => List.IsChain.cons_cons ⟨g⟩ (isChain_toList_nonempty (cons p g)) theorem isChain_cons_toList_nonempty : ∀ {b} (p : Path a b), (b :: p.toList).IsChain (fun x y => Nonempty (y ⟶ x)) | _, nil => .singleton _ | _, cons p f => p.isChain_cons_toList_nonempty.cons_cons ⟨f⟩ @[deprecated (since := "2025-09-19")] alias toList_chain_nonempty := isChain_cons_toList_nonempty variable [∀ a b : V, Subsingleton (a ⟶ b)] theorem toList_injective (a : V) : ∀ b, Injective (toList : Path a b → List V) | _, nil, nil, _ => rfl | _, nil, @cons _ _ _ c _ p f, h => by cases h | _, @cons _ _ _ c _ p f, nil, h => by cases h | _, @cons _ _ _ c _ p f, @cons _ _ _ t _ C D, h => by simp only [toList, List.cons.injEq] at h obtain ⟨rfl, hAC⟩ := h simp [toList_injective _ _ hAC, eq_iff_true_of_subsingleton] @[simp] theorem toList_inj {p q : Path a b} : p.toList = q.toList ↔ p = q := (toList_injective _ _).eq_iff section BoundedPath variable {V : Type*} [Quiver V] /-- A bounded path is a path with a uniform bound on its length. -/ def BoundedPaths (v w : V) (n : ℕ) : Sort _ := { p : Path v w // p.length ≤ n } /-- Bounded paths of length zero between two vertices form a subsingleton. -/ instance instSubsingletonBddPaths (v w : V) : Subsingleton (BoundedPaths v w 0) where allEq := fun ⟨p, hp⟩ ⟨q, hq⟩ => match v, w, p, q with | _, _, .nil, .nil => rfl | _, _, .cons _ _, _ => by simp [Quiver.Path.length] at hp | _, _, _, .cons _ _ => by simp [Quiver.Path.length] at hq /-- Bounded paths of length zero between two vertices have decidable equality. -/ def decidableEqBddPathsZero (v w : V) : DecidableEq (BoundedPaths v w 0) := fun _ _ => isTrue <| Subsingleton.elim _ _ /-- Given decidable equality on paths of length up to `n`, we can construct decidable equality on paths of length up to `n + 1`. -/ def decidableEqBddPathsOfDecidableEq (n : ℕ) (h₁ : DecidableEq V) (h₂ : ∀ (v w : V), DecidableEq (v ⟶ w)) (h₃ : ∀ (v w : V), DecidableEq (BoundedPaths v w n)) (v w : V) : DecidableEq (BoundedPaths v w (n + 1)) := fun ⟨p, hp⟩ ⟨q, hq⟩ => match v, w, p, q with | _, _, .nil, .nil => isTrue rfl | _, _, .nil, .cons _ _ => isFalse fun h => Quiver.Path.noConfusion <| Subtype.mk.inj h | _, _, .cons _ _, .nil => isFalse fun h => Quiver.Path.noConfusion <| Subtype.mk.inj h | _, _, .cons (b := v') p' α, .cons (b := v'') q' β => match v', v'', h₁ v' v'' with | _, _, isTrue (Eq.refl _) => if h : α = β then have hp' : p'.length ≤ n := by simp [Quiver.Path.length] at hp; cutsat have hq' : q'.length ≤ n := by simp [Quiver.Path.length] at hq; cutsat if h'' : (⟨p', hp'⟩ : BoundedPaths _ _ n) = ⟨q', hq'⟩ then isTrue <| by apply Subtype.ext dsimp rw [h, show p' = q' from Subtype.mk.inj h''] else isFalse fun h => h'' <| Subtype.ext <| eq_of_heq <| (Quiver.Path.cons.inj <| Subtype.mk.inj h).2.1 else isFalse fun h' => h <| eq_of_heq (Quiver.Path.cons.inj <| Subtype.mk.inj h').2.2 | _, _, isFalse h => isFalse fun h' => h (Quiver.Path.cons.inj <| Subtype.mk.inj h').1 /-- Equality is decidable on all uniformly bounded paths given decidable equality on the vertices and the arrows. -/ instance decidableEqBoundedPaths [DecidableEq V] [∀ (v w : V), DecidableEq (v ⟶ w)] (n : ℕ) : (v w : V) → DecidableEq (BoundedPaths v w n) := n.rec decidableEqBddPathsZero fun n decEq => decidableEqBddPathsOfDecidableEq n inferInstance inferInstance decEq /-- Equality is decidable on paths in a quiver given decidable equality on the vertices and arrows. -/ instance instDecidableEq [DecidableEq V] [∀ (v w : V), DecidableEq (v ⟶ w)] : (v w : V) → DecidableEq (Path v w) := fun v w p q => let m := max p.length q.length let p' : BoundedPaths v w m := ⟨p, Nat.le_max_left ..⟩ let q' : BoundedPaths v w m := ⟨q, Nat.le_max_right ..⟩ decidable_of_iff (p' = q') Subtype.ext_iff end BoundedPath end Path end Quiver namespace Prefunctor open Quiver variable {V : Type u₁} [Quiver.{v₁} V] {W : Type u₂} [Quiver.{v₂} W] (F : V ⥤q W) /-- The image of a path under a prefunctor. -/ def mapPath {a : V} : ∀ {b : V}, Path a b → Path (F.obj a) (F.obj b) | _, Path.nil => Path.nil | _, Path.cons p e => Path.cons (mapPath p) (F.map e) @[simp] theorem mapPath_nil (a : V) : F.mapPath (Path.nil : Path a a) = Path.nil := rfl @[simp] theorem mapPath_cons {a b c : V} (p : Path a b) (e : b ⟶ c) : F.mapPath (Path.cons p e) = Path.cons (F.mapPath p) (F.map e) := rfl @[simp] theorem mapPath_comp {a b : V} (p : Path a b) : ∀ {c : V} (q : Path b c), F.mapPath (p.comp q) = (F.mapPath p).comp (F.mapPath q) | _, Path.nil => rfl | c, Path.cons q e => by dsimp; rw [mapPath_comp p q] @[simp] theorem mapPath_toPath {a b : V} (f : a ⟶ b) : F.mapPath f.toPath = (F.map f).toPath := rfl @[simp] theorem mapPath_id {a b : V} : (p : Path a b) → (𝟭q V).mapPath p = p | Path.nil => rfl | Path.cons q e => by dsimp; rw [mapPath_id q] variable {U : Type u₃} [Quiver.{v₃} U] (G : W ⥤q U) @[simp] theorem mapPath_comp_apply {a b : V} (p : Path a b) : (F ⋙q G).mapPath p = G.mapPath (F.mapPath p) := by induction p with | nil => rfl | cons x y h => simp [h] end Prefunctor
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Prefunctor.lean
import Mathlib.Combinatorics.Quiver.Basic /-! # Morphisms of quivers -/ universe v₁ v₂ u u₁ u₂ /-- A morphism of quivers. As we will later have categorical functors extend this structure, we call it a `Prefunctor`. -/ structure Prefunctor (V : Type u₁) [Quiver.{v₁} V] (W : Type u₂) [Quiver.{v₂} W] where /-- The action of a (pre)functor on vertices/objects. -/ obj : V → W /-- The action of a (pre)functor on edges/arrows/morphisms. -/ map : ∀ {X Y : V}, (X ⟶ Y) → (obj X ⟶ obj Y) namespace Prefunctor -- These lemmas cannot be `@[simp]` because after `whnfR` they have a variable on the LHS. -- Nevertheless they are sometimes useful when building functors. lemma mk_obj {V W : Type*} [Quiver V] [Quiver W] {obj : V → W} {map} {X : V} : (Prefunctor.mk obj map).obj X = obj X := rfl lemma mk_map {V W : Type*} [Quiver V] [Quiver W] {obj : V → W} {map} {X Y : V} {f : X ⟶ Y} : (Prefunctor.mk obj map).map f = map f := rfl @[ext (iff := false)] theorem ext {V : Type u} [Quiver.{v₁} V] {W : Type u₂} [Quiver.{v₂} W] {F G : Prefunctor V W} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ (X Y : V) (f : X ⟶ Y), F.map f = Eq.recOn (h_obj Y).symm (Eq.recOn (h_obj X).symm (G.map f))) : F = G := by obtain ⟨F_obj, _⟩ := F obtain ⟨G_obj, _⟩ := G obtain rfl : F_obj = G_obj := by ext X apply h_obj congr funext X Y f simpa using h_map X Y f /-- This may be a more useful form of `Prefunctor.ext`. -/ theorem ext' {V W : Type u} [Quiver V] [Quiver W] {F G : Prefunctor V W} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ (X Y : V) (f : X ⟶ Y), F.map f = Quiver.homOfEq (G.map f) (h_obj _).symm (h_obj _).symm) : F = G := by obtain ⟨Fobj, Fmap⟩ := F obtain ⟨Gobj, Gmap⟩ := G obtain rfl : Fobj = Gobj := funext h_obj simp only [mk.injEq, heq_eq_eq, true_and] ext X Y f simpa only [Quiver.homOfEq_rfl] using h_map X Y f /-- The identity morphism between quivers. -/ @[simps] def id (V : Type*) [Quiver V] : Prefunctor V V where obj := fun X => X map f := f instance (V : Type*) [Quiver V] : Inhabited (Prefunctor V V) := ⟨id V⟩ /-- Composition of morphisms between quivers. -/ @[simps] def comp {U : Type*} [Quiver U] {V : Type*} [Quiver V] {W : Type*} [Quiver W] (F : Prefunctor U V) (G : Prefunctor V W) : Prefunctor U W where obj X := G.obj (F.obj X) map f := G.map (F.map f) @[simp] theorem comp_id {U V : Type*} [Quiver U] [Quiver V] (F : Prefunctor U V) : F.comp (id _) = F := rfl @[simp] theorem id_comp {U V : Type*} [Quiver U] [Quiver V] (F : Prefunctor U V) : (id _).comp F = F := rfl @[simp] theorem comp_assoc {U V W Z : Type*} [Quiver U] [Quiver V] [Quiver W] [Quiver Z] (F : Prefunctor U V) (G : Prefunctor V W) (H : Prefunctor W Z) : (F.comp G).comp H = F.comp (G.comp H) := rfl /-- Notation for a prefunctor between quivers. -/ infixl:50 " ⥤q " => Prefunctor /-- Notation for composition of prefunctors. -/ infixl:60 " ⋙q " => Prefunctor.comp /-- Notation for the identity prefunctor on a quiver. -/ notation "𝟭q" => id theorem congr_map {U V : Type*} [Quiver U] [Quiver V] (F : U ⥤q V) {X Y : U} {f g : X ⟶ Y} (h : f = g) : F.map f = F.map g := by rw [h] /-- An equality of prefunctors gives an equality on objects. -/ theorem congr_obj {U V : Type*} [Quiver U] [Quiver V] {F G : U ⥤q V} (e : F = G) (X : U) : F.obj X = G.obj X := by cases e; rfl /-- An equality of prefunctors gives an equality on homs. -/ theorem congr_hom {U V : Type*} [Quiver U] [Quiver V] {F G : U ⥤q V} (e : F = G) {X Y : U} (f : X ⟶ Y) : Quiver.homOfEq (F.map f) (congr_obj e X) (congr_obj e Y) = G.map f := by subst e simp /-- Prefunctors commute with `homOfEq`. -/ @[simp] theorem homOfEq_map {U V : Type*} [Quiver U] [Quiver V] (F : U ⥤q V) {X Y : U} (f : X ⟶ Y) {X' Y' : U} (hX : X = X') (hY : Y = Y') : F.map (Quiver.homOfEq f hX hY) = Quiver.homOfEq (F.map f) (congr_arg F.obj hX) (congr_arg F.obj hY) := by subst hX hY; simp end Prefunctor
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/SingleObj.lean
import Mathlib.Combinatorics.Quiver.Cast import Mathlib.Combinatorics.Quiver.Symmetric /-! # Single-object quiver Single object quiver with a given arrows type. ## Main definitions Given a type `α`, `SingleObj α` is the `Unit` type, whose single object is called `star α`, with `Quiver` structure such that `star α ⟶ star α` is the type `α`. An element `x : α` can be reinterpreted as an element of `star α ⟶ star α` using `toHom`. More generally, a list of elements of `a` can be reinterpreted as a path from `star α` to itself using `pathEquivList`. -/ namespace Quiver /-- Type tag on `Unit` used to define single-object quivers. -/ @[nolint unusedArguments] def SingleObj (_ : Type*) : Type := Unit deriving Unique namespace SingleObj variable (α β γ : Type*) instance : Quiver (SingleObj α) := ⟨fun _ _ => α⟩ /-- The single object in `SingleObj α`. -/ def star : SingleObj α := default variable {α β γ} lemma ext {x y : SingleObj α} : x = y := Unit.ext x y -- See note [reducible non-instances] /-- Equip `SingleObj α` with a reverse operation. -/ abbrev hasReverse (rev : α → α) : HasReverse (SingleObj α) := ⟨rev⟩ -- See note [reducible non-instances] /-- Equip `SingleObj α` with an involutive reverse operation. -/ abbrev hasInvolutiveReverse (rev : α → α) (h : Function.Involutive rev) : HasInvolutiveReverse (SingleObj α) where toHasReverse := hasReverse rev inv' := h /-- The type of arrows from `star α` to itself is equivalent to the original type `α`. -/ @[simps!] def toHom : α ≃ (star α ⟶ star α) := Equiv.refl _ /-- Prefunctors between two `SingleObj` quivers correspond to functions between the corresponding arrows types. -/ @[simps] def toPrefunctor : (α → β) ≃ SingleObj α ⥤q SingleObj β where toFun f := ⟨id, f⟩ invFun f a := f.map (toHom a) theorem toPrefunctor_id : toPrefunctor id = 𝟭q (SingleObj α) := rfl @[simp] theorem toPrefunctor_symm_id : toPrefunctor.symm (𝟭q (SingleObj α)) = id := rfl theorem toPrefunctor_comp (f : α → β) (g : β → γ) : toPrefunctor (g ∘ f) = toPrefunctor f ⋙q toPrefunctor g := rfl @[simp] theorem toPrefunctor_symm_comp (f : SingleObj α ⥤q SingleObj β) (g : SingleObj β ⥤q SingleObj γ) : toPrefunctor.symm (f ⋙q g) = toPrefunctor.symm g ∘ toPrefunctor.symm f := by simp only [Equiv.symm_apply_eq, toPrefunctor_comp, Equiv.apply_symm_apply] /-- Auxiliary definition for `quiver.SingleObj.pathEquivList`. Converts a path in the quiver `single_obj α` into a list of elements of type `a`. -/ def pathToList : ∀ {x : SingleObj α}, Path (star α) x → List α | _, Path.nil => [] | _, Path.cons p a => a :: pathToList p /-- Auxiliary definition for `quiver.SingleObj.pathEquivList`. Converts a list of elements of type `α` into a path in the quiver `SingleObj α`. -/ @[simp] def listToPath : List α → Path (star α) (star α) | [] => Path.nil | a :: l => (listToPath l).cons a theorem listToPath_pathToList {x : SingleObj α} (p : Path (star α) x) : listToPath (pathToList p) = p.cast rfl ext := by induction p with | nil => rfl | cons _ _ ih => dsimp [pathToList] at *; rw [ih] theorem pathToList_listToPath (l : List α) : pathToList (listToPath l) = l := by induction l with | nil => rfl | cons a l ih => change a :: pathToList (listToPath l) = a :: l; rw [ih] /-- Paths in `SingleObj α` quiver correspond to lists of elements of type `α`. -/ def pathEquivList : Path (star α) (star α) ≃ List α := ⟨pathToList, listToPath, fun p => listToPath_pathToList p, pathToList_listToPath⟩ @[simp] theorem pathEquivList_nil : pathEquivList Path.nil = ([] : List α) := rfl @[simp] theorem pathEquivList_cons (p : Path (star α) (star α)) (a : star α ⟶ star α) : pathEquivList (Path.cons p a) = a :: pathToList p := rfl @[simp] theorem pathEquivList_symm_nil : pathEquivList.symm ([] : List α) = Path.nil := rfl @[simp] theorem pathEquivList_symm_cons (l : List α) (a : α) : pathEquivList.symm (a :: l) = Path.cons (pathEquivList.symm l) a := rfl end SingleObj end Quiver
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Subquiver.lean
import Mathlib.Order.Notation import Mathlib.Combinatorics.Quiver.Basic /-! ## Wide subquivers A wide subquiver `H` of a quiver `H` consists of a subset of the edge set `a ⟶ b` for every pair of vertices `a b : V`. We include 'wide' in the name to emphasize that these subquivers by definition contain all vertices. -/ universe v u /-- A wide subquiver `H` of `G` picks out a set `H a b` of arrows from `a` to `b` for every pair of vertices `a b`. NB: this does not work for `Prop`-valued quivers. It requires `G : Quiver.{v+1} V`. -/ def WideSubquiver (V) [Quiver.{v + 1} V] := ∀ a b : V, Set (a ⟶ b) /-- A type synonym for `V`, when thought of as a quiver having only the arrows from some `WideSubquiver`. -/ @[nolint unusedArguments] def WideSubquiver.toType (V) [Quiver V] (_ : WideSubquiver V) : Type u := V instance wideSubquiverHasCoeToSort {V} [Quiver V] : CoeSort (WideSubquiver V) (Type u) where coe H := WideSubquiver.toType V H /-- A wide subquiver viewed as a quiver on its own. -/ instance WideSubquiver.quiver {V} [Quiver V] (H : WideSubquiver V) : Quiver H := ⟨fun a b ↦ { f // f ∈ H a b }⟩ namespace Quiver instance {V} [Quiver V] : Bot (WideSubquiver V) := ⟨fun _ _ ↦ ∅⟩ instance {V} [Quiver V] : Top (WideSubquiver V) := ⟨fun _ _ ↦ Set.univ⟩ noncomputable instance {V} [Quiver V] : Inhabited (WideSubquiver V) := ⟨⊤⟩ -- TODO Unify with `CategoryTheory.Arrow`? (The fields have been named to match.) /-- `Total V` is the type of _all_ arrows of `V`. -/ @[ext] structure Total (V : Type u) [Quiver.{v} V] : Sort max (u + 1) v where /-- the source vertex of an arrow -/ left : V /-- the target vertex of an arrow -/ right : V /-- an arrow -/ hom : left ⟶ right /-- A wide subquiver of `G` can equivalently be viewed as a total set of arrows. -/ def wideSubquiverEquivSetTotal {V} [Quiver V] : WideSubquiver V ≃ Set (Total V) where toFun H := { e | e.hom ∈ H e.left e.right } invFun S a b := { e | Total.mk a b e ∈ S } /-- An `L`-labelling of a quiver assigns to every arrow an element of `L`. -/ def Labelling (V : Type u) [Quiver V] (L : Sort*) := ∀ ⦃a b : V⦄, (a ⟶ b) → L instance {V : Type u} [Quiver V] (L) [Inhabited L] : Inhabited (Labelling V L) := ⟨fun _ _ _ ↦ default⟩ end Quiver
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Symmetric.lean
import Mathlib.Combinatorics.Quiver.Path import Mathlib.Combinatorics.Quiver.Push /-! ## Symmetric quivers and arrow reversal This file contains constructions related to symmetric quivers: * `Symmetrify V` adds formal inverses to each arrow of `V`. * `HasReverse` is the class of quivers where each arrow has an assigned formal inverse. * `HasInvolutiveReverse` extends `HasReverse` by requiring that the reverse of the reverse is equal to the original arrow. * `Prefunctor.PreserveReverse` is the class of prefunctors mapping reverses to reverses. * `Symmetrify.of`, `Symmetrify.lift`, and the associated lemmas witness the universal property of `Symmetrify`. -/ universe v u w v' namespace Quiver /-- A type synonym for the symmetrized quiver (with an arrow both ways for each original arrow). NB: this does not work for `Prop`-valued quivers. It requires `[Quiver.{v+1} V]`. -/ def Symmetrify (V : Type*) := V instance symmetrifyQuiver (V : Type u) [Quiver V] : Quiver (Symmetrify V) := ⟨fun a b : V ↦ (a ⟶ b) ⊕ (b ⟶ a)⟩ variable (U V W : Type*) [Quiver.{u + 1} U] [Quiver.{v + 1} V] [Quiver.{w + 1} W] /-- A quiver `HasReverse` if we can reverse an arrow `p` from `a` to `b` to get an arrow `p.reverse` from `b` to `a`. -/ class HasReverse where /-- the map which sends an arrow to its reverse -/ reverse' : ∀ {a b : V}, (a ⟶ b) → (b ⟶ a) /-- Reverse the direction of an arrow. -/ def reverse {V} [Quiver.{v + 1} V] [HasReverse V] {a b : V} : (a ⟶ b) → (b ⟶ a) := HasReverse.reverse' /-- A quiver `HasInvolutiveReverse` if reversing twice is the identity. -/ class HasInvolutiveReverse extends HasReverse V where /-- `reverse` is involutive -/ inv' : ∀ {a b : V} (f : a ⟶ b), reverse (reverse f) = f variable {U V W} @[simp] theorem reverse_reverse [h : HasInvolutiveReverse V] {a b : V} (f : a ⟶ b) : reverse (reverse f) = f := by apply h.inv' @[simp] theorem reverse_inj [h : HasInvolutiveReverse V] {a b : V} (f g : a ⟶ b) : reverse f = reverse g ↔ f = g := by constructor · rintro h simpa using congr_arg Quiver.reverse h · rintro h congr theorem eq_reverse_iff [h : HasInvolutiveReverse V] {a b : V} (f : a ⟶ b) (g : b ⟶ a) : f = reverse g ↔ reverse f = g := by rw [← reverse_inj, reverse_reverse] section MapReverse variable [HasReverse U] [HasReverse V] [HasReverse W] /-- A prefunctor preserving reversal of arrows -/ class _root_.Prefunctor.MapReverse (φ : U ⥤q V) : Prop where /-- The image of a reverse is the reverse of the image. -/ map_reverse' : ∀ {u v : U} (e : u ⟶ v), φ.map (reverse e) = reverse (φ.map e) @[simp] theorem _root_.Prefunctor.map_reverse (φ : U ⥤q V) [φ.MapReverse] {u v : U} (e : u ⟶ v) : φ.map (reverse e) = reverse (φ.map e) := Prefunctor.MapReverse.map_reverse' e instance _root_.Prefunctor.mapReverseComp (φ : U ⥤q V) (ψ : V ⥤q W) [φ.MapReverse] [ψ.MapReverse] : (φ ⋙q ψ).MapReverse where map_reverse' e := by simp only [Prefunctor.comp_map, Prefunctor.MapReverse.map_reverse'] instance _root_.Prefunctor.mapReverseId : (Prefunctor.id U).MapReverse where map_reverse' _ := rfl end MapReverse instance : HasReverse (Symmetrify V) := ⟨fun e => e.swap⟩ instance : HasInvolutiveReverse (Symmetrify V) where toHasReverse := ⟨fun e ↦ e.swap⟩ inv' e := congr_fun Sum.swap_swap_eq e @[simp] theorem symmetrify_reverse {a b : Symmetrify V} (e : a ⟶ b) : reverse e = e.swap := rfl section Paths /-- Shorthand for the "forward" arrow corresponding to `f` in `symmetrify V` -/ abbrev Hom.toPos {X Y : V} (f : X ⟶ Y) : (Quiver.symmetrifyQuiver V).Hom X Y := Sum.inl f /-- Shorthand for the "backward" arrow corresponding to `f` in `symmetrify V` -/ abbrev Hom.toNeg {X Y : V} (f : X ⟶ Y) : (Quiver.symmetrifyQuiver V).Hom Y X := Sum.inr f /-- Reverse the direction of a path. -/ @[simp] def Path.reverse [HasReverse V] {a : V} : ∀ {b}, Path a b → Path b a | _, Path.nil => Path.nil | _, Path.cons p e => (Quiver.reverse e).toPath.comp p.reverse @[simp] theorem Path.reverse_toPath [HasReverse V] {a b : V} (f : a ⟶ b) : f.toPath.reverse = (Quiver.reverse f).toPath := rfl @[simp] theorem Path.reverse_comp [HasReverse V] {a b c : V} (p : Path a b) (q : Path b c) : (p.comp q).reverse = q.reverse.comp p.reverse := by induction q with | nil => simp | cons _ _ h => simp [h] @[simp] theorem Path.reverse_reverse [h : HasInvolutiveReverse V] {a b : V} (p : Path a b) : p.reverse.reverse = p := by induction p with | nil => simp | cons _ _ h => rw [Path.reverse, Path.reverse_comp, h, Path.reverse_toPath, Quiver.reverse_reverse] rfl end Paths namespace Symmetrify /-- The inclusion of a quiver in its symmetrification -/ @[simps] def of : Prefunctor V (Symmetrify V) where obj := id map := Sum.inl variable {V' : Type*} [Quiver.{v' + 1} V'] /-- Given a quiver `V'` with reversible arrows, a prefunctor to `V'` can be lifted to one from `Symmetrify V` to `V'` -/ def lift [HasReverse V'] (φ : Prefunctor V V') : Prefunctor (Symmetrify V) V' where obj := φ.obj map | Sum.inl g => φ.map g | Sum.inr g => reverse (φ.map g) theorem lift_spec [HasReverse V'] (φ : Prefunctor V V') : Symmetrify.of.comp (Symmetrify.lift φ) = φ := by fapply Prefunctor.ext · rintro X rfl · rintro X Y f rfl theorem lift_reverse [h : HasInvolutiveReverse V'] (φ : Prefunctor V V') {X Y : Symmetrify V} (f : X ⟶ Y) : (Symmetrify.lift φ).map (Quiver.reverse f) = Quiver.reverse ((Symmetrify.lift φ).map f) := by dsimp [Symmetrify.lift]; cases f · simp only rfl · simp only [reverse_reverse] rfl /-- `lift φ` is the only prefunctor extending `φ` and preserving reverses. -/ theorem lift_unique [HasReverse V'] (φ : V ⥤q V') (Φ : Symmetrify V ⥤q V') (hΦ : (of ⋙q Φ) = φ) (hΦinv : ∀ {X Y : Symmetrify V} (f : X ⟶ Y), Φ.map (Quiver.reverse f) = Quiver.reverse (Φ.map f)) : Φ = Symmetrify.lift φ := by subst_vars fapply Prefunctor.ext · rintro X rfl · rintro X Y f cases f · rfl · exact hΦinv (Sum.inl _) /-- A prefunctor canonically defines a prefunctor of the symmetrifications. -/ @[simps] def _root_.Prefunctor.symmetrify (φ : U ⥤q V) : Symmetrify U ⥤q Symmetrify V where obj := φ.obj map := Sum.map φ.map φ.map instance _root_.Prefunctor.symmetrify_mapReverse (φ : U ⥤q V) : Prefunctor.MapReverse φ.symmetrify := ⟨fun e => by cases e <;> rfl⟩ end Symmetrify namespace Push variable {V' : Type*} (σ : V → V') instance [HasReverse V] : HasReverse (Quiver.Push σ) where reverse' := fun | PushQuiver.arrow f => PushQuiver.arrow (reverse f) instance [h : HasInvolutiveReverse V] : HasInvolutiveReverse (Push σ) where reverse' := fun | PushQuiver.arrow f => PushQuiver.arrow (reverse f) inv' := fun | PushQuiver.arrow f => by dsimp [reverse]; congr; apply h.inv' theorem of_reverse [HasInvolutiveReverse V] (X Y : V) (f : X ⟶ Y) : (reverse <| (Push.of σ).map f) = (Push.of σ).map (reverse f) := rfl instance ofMapReverse [h : HasInvolutiveReverse V] : (Push.of σ).MapReverse := ⟨by simp [of_reverse]⟩ end Push end Quiver
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Cast.lean
import Mathlib.Combinatorics.Quiver.Basic import Mathlib.Combinatorics.Quiver.Path /-! # Rewriting arrows and paths along vertex equalities This file defines `Hom.cast` and `Path.cast` (and associated lemmas) in order to allow rewriting arrows and paths along equalities of their endpoints. -/ universe v v₁ v₂ u u₁ u₂ variable {U : Type*} [Quiver.{u + 1} U] namespace Quiver /-! ### Rewriting arrows along equalities of vertices -/ /-- Change the endpoints of an arrow using equalities. -/ def Hom.cast {u v u' v' : U} (hu : u = u') (hv : v = v') (e : u ⟶ v) : u' ⟶ v' := Eq.ndrec (motive := (· ⟶ v')) (Eq.ndrec e hv) hu theorem Hom.cast_eq_cast {u v u' v' : U} (hu : u = u') (hv : v = v') (e : u ⟶ v) : e.cast hu hv = _root_.cast (by {rw [hu, hv]}) e := by subst_vars rfl @[simp] theorem Hom.cast_rfl_rfl {u v : U} (e : u ⟶ v) : e.cast rfl rfl = e := rfl @[simp] theorem Hom.cast_cast {u v u' v' u'' v'' : U} (e : u ⟶ v) (hu : u = u') (hv : v = v') (hu' : u' = u'') (hv' : v' = v'') : (e.cast hu hv).cast hu' hv' = e.cast (hu.trans hu') (hv.trans hv') := by subst_vars rfl theorem Hom.cast_heq {u v u' v' : U} (hu : u = u') (hv : v = v') (e : u ⟶ v) : e.cast hu hv ≍ e := by subst_vars rfl theorem Hom.cast_eq_iff_heq {u v u' v' : U} (hu : u = u') (hv : v = v') (e : u ⟶ v) (e' : u' ⟶ v') : e.cast hu hv = e' ↔ e ≍ e' := by rw [Hom.cast_eq_cast] exact _root_.cast_eq_iff_heq theorem Hom.eq_cast_iff_heq {u v u' v' : U} (hu : u = u') (hv : v = v') (e : u ⟶ v) (e' : u' ⟶ v') : e' = e.cast hu hv ↔ e' ≍ e := by rw [eq_comm, Hom.cast_eq_iff_heq] exact ⟨HEq.symm, HEq.symm⟩ /-! ### Rewriting paths along equalities of vertices -/ open Path /-- Change the endpoints of a path using equalities. -/ def Path.cast {u v u' v' : U} (hu : u = u') (hv : v = v') (p : Path u v) : Path u' v' := Eq.ndrec (motive := (Path · v')) (Eq.ndrec p hv) hu theorem Path.cast_eq_cast {u v u' v' : U} (hu : u = u') (hv : v = v') (p : Path u v) : p.cast hu hv = _root_.cast (by rw [hu, hv]) p := by subst_vars rfl @[simp] theorem Path.cast_rfl_rfl {u v : U} (p : Path u v) : p.cast rfl rfl = p := rfl @[simp] theorem Path.cast_cast {u v u' v' u'' v'' : U} (p : Path u v) (hu : u = u') (hv : v = v') (hu' : u' = u'') (hv' : v' = v'') : (p.cast hu hv).cast hu' hv' = p.cast (hu.trans hu') (hv.trans hv') := by subst_vars rfl @[simp] theorem Path.cast_nil {u u' : U} (hu : u = u') : (Path.nil : Path u u).cast hu hu = Path.nil := by subst_vars rfl theorem Path.cast_heq {u v u' v' : U} (hu : u = u') (hv : v = v') (p : Path u v) : p.cast hu hv ≍ p := by rw [Path.cast_eq_cast] exact _root_.cast_heq _ _ theorem Path.cast_eq_iff_heq {u v u' v' : U} (hu : u = u') (hv : v = v') (p : Path u v) (p' : Path u' v') : p.cast hu hv = p' ↔ p ≍ p' := by rw [Path.cast_eq_cast] exact _root_.cast_eq_iff_heq theorem Path.eq_cast_iff_heq {u v u' v' : U} (hu : u = u') (hv : v = v') (p : Path u v) (p' : Path u' v') : p' = p.cast hu hv ↔ p' ≍ p := ⟨fun h => ((p.cast_eq_iff_heq hu hv p').1 h.symm).symm, fun h => ((p.cast_eq_iff_heq hu hv p').2 h.symm).symm⟩ theorem Path.cast_cons {u v w u' w' : U} (p : Path u v) (e : v ⟶ w) (hu : u = u') (hw : w = w') : (p.cons e).cast hu hw = (p.cast hu rfl).cons (e.cast rfl hw) := by subst_vars rfl theorem cast_eq_of_cons_eq_cons {u v v' w : U} {p : Path u v} {p' : Path u v'} {e : v ⟶ w} {e' : v' ⟶ w} (h : p.cons e = p'.cons e') : p.cast rfl (obj_eq_of_cons_eq_cons h) = p' := by rw [Path.cast_eq_iff_heq] exact heq_of_cons_eq_cons h theorem hom_cast_eq_of_cons_eq_cons {u v v' w : U} {p : Path u v} {p' : Path u v'} {e : v ⟶ w} {e' : v' ⟶ w} (h : p.cons e = p'.cons e') : e.cast (obj_eq_of_cons_eq_cons h) rfl = e' := by rw [Hom.cast_eq_iff_heq] exact hom_heq_of_cons_eq_cons h theorem eq_nil_of_length_zero {u v : U} (p : Path u v) (hzero : p.length = 0) : p.cast (eq_of_length_zero p hzero) rfl = Path.nil := by cases p · rfl · simp only [Nat.succ_ne_zero, length_cons] at hzero end Quiver
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/ConnectedComponent.lean
import Mathlib.Combinatorics.Quiver.Subquiver import Mathlib.Combinatorics.Quiver.Path import Mathlib.Combinatorics.Quiver.Symmetric /-! ## Weakly and strongly connected components For a quiver `V`, define the type `WeaklyConnectedComponent V` as the quotient of `V` by the relation which identifies `a` with `b` if there is a path from `a` to `b` in `Symmetrify V`. (These zigzags can be seen as a proof-relevant analogue of `EqvGen`.) We define: * `Quiver.IsStronglyConnected V`: every pair of vertices is connected by a (possibly empty) path. * `Quiver.IsSStronglyConnected V`: every pair of vertices is connected by a path of positive length. * `Quiver.StronglyConnectedComponent V`: the quotient by the equivalence relation “paths in both directions”. These concepts relate strong and weak connectivity and let us reason about strongly connected components in directed graphs. -/ universe v u namespace Quiver variable (V : Type*) [Quiver.{u + 1} V] /-- Two vertices are related in the zigzag setoid if there is a zigzag of arrows from one to the other. -/ def zigzagSetoid : Setoid V := ⟨fun a b ↦ Nonempty (@Path (Symmetrify V) _ a b), fun _ ↦ ⟨Path.nil⟩, fun ⟨p⟩ ↦ ⟨p.reverse⟩, fun ⟨p⟩ ⟨q⟩ ↦ ⟨p.comp q⟩⟩ /-- The type of weakly connected components of a directed graph. Two vertices are in the same weakly connected component if there is a zigzag of arrows from one to the other. -/ def WeaklyConnectedComponent : Type _ := Quotient (zigzagSetoid V) namespace WeaklyConnectedComponent variable {V} /-- The weakly connected component corresponding to a vertex. -/ protected def mk : V → WeaklyConnectedComponent V := @Quotient.mk' _ (zigzagSetoid V) instance : CoeTC V (WeaklyConnectedComponent V) := ⟨WeaklyConnectedComponent.mk⟩ instance [Inhabited V] : Inhabited (WeaklyConnectedComponent V) := ⟨show V from default⟩ protected theorem eq (a b : V) : (a : WeaklyConnectedComponent V) = b ↔ Nonempty (@Path (Symmetrify V) _ a b) := Quotient.eq'' end WeaklyConnectedComponent variable {V} /-- A wide subquiver `H` of `Symmetrify V` determines a wide subquiver of `V`, containing an arrow `e` if either `e` or its reversal is in `H`. -/ def wideSubquiverSymmetrify (H : WideSubquiver (Symmetrify V)) : WideSubquiver V := fun _ _ ↦ { e | H _ _ (Sum.inl e) ∨ H _ _ (Sum.inr e) } /-! ## Strongly connected components (directed connectivity) We define strong connectivity (`IsStronglyConnected`), its positive-length refinement (`IsSStronglyConnected`), and strongly connected components. -/ section StronglyConnected variable (V : Type*) [Quiver V] /-- Strong connectivity: every ordered pair of vertices is joined by a (possibly empty) directed path. -/ def IsStronglyConnected : Prop := ∀ i j : V, Nonempty (Path i j) /-- Positive strong connectivity: every ordered pair of vertices is joined by a directed path of positive length. -/ def IsSStronglyConnected : Prop := ∀ i j : V, ∃ p : Path i j, 0 < p.length @[simp] lemma isStronglyConnected_iff : IsStronglyConnected V ↔ ∀ i j : V, Nonempty (Path i j) := Iff.rfl @[simp] lemma isSStronglyConnected_iff : IsSStronglyConnected V ↔ ∀ i j : V, ∃ p : Path i j, 0 < p.length := Iff.rfl lemma IsStronglyConnected.nonempty_path (h : IsStronglyConnected V) (i j : V) : Nonempty (Path i j) := h i j lemma IsSStronglyConnected.exists_pos_path (h : IsSStronglyConnected V) (i j : V) : ∃ p : Path i j, 0 < p.length := h i j lemma IsSStronglyConnected.exists_pos_cycle (h : IsSStronglyConnected V) (i : V) : ∃ p : Path i i, 0 < p.length := h i i lemma IsSStronglyConnected.isStronglyConnected (h : IsSStronglyConnected V) : IsStronglyConnected V := by intro i j; obtain ⟨p, _⟩ := h i j; exact ⟨p⟩ /-- Equivalence relation identifying vertices connected by directed paths in both directions. -/ def stronglyConnectedSetoid : Setoid V := ⟨fun a b => (Nonempty (Path a b)) ∧ (Nonempty (Path b a)), fun _ => ⟨⟨Path.nil⟩, ⟨Path.nil⟩⟩, fun ⟨hab, hba⟩ => ⟨hba, hab⟩, fun ⟨hab, hba⟩ ⟨hbc, hcb⟩ => ⟨⟨hab.some.comp hbc.some⟩, ⟨hcb.some.comp hba.some⟩⟩⟩ /-- The type of strongly connected components (bidirectional reachability classes). -/ def StronglyConnectedComponent : Type _ := Quotient (stronglyConnectedSetoid V) namespace StronglyConnectedComponent variable {V} /-- The canonical map from a vertex to its strongly connected component. -/ protected def mk : V → StronglyConnectedComponent V := @Quotient.mk' _ (stronglyConnectedSetoid V) instance : Coe V (StronglyConnectedComponent V) := ⟨StronglyConnectedComponent.mk⟩ instance [Inhabited V] : Inhabited (StronglyConnectedComponent V) := ⟨(default : V)⟩ protected lemma eq (a b : V) : (a : StronglyConnectedComponent V) = b ↔ (Nonempty (Path a b) ∧ Nonempty (Path b a)) := Quotient.eq'' @[simp] lemma mk_eq_mk {a b : V} : (StronglyConnectedComponent.mk a : StronglyConnectedComponent V) = StronglyConnectedComponent.mk b ↔ (Nonempty (Path a b) ∧ Nonempty (Path b a)) := StronglyConnectedComponent.eq a b lemma IsSStronglyConnected.pos_cycle (h : IsSStronglyConnected V) (v : V) : ∃ p : Path v v, 0 < p.length := h v v end StronglyConnectedComponent variable {V} lemma stronglyConnectedComponent_eq_of_path {a b : V} (hab : Nonempty (Path a b)) (hba : Nonempty (Path b a)) : (a : StronglyConnectedComponent V) = b := (StronglyConnectedComponent.eq (a := a) (b := b)).2 ⟨hab, hba⟩ lemma exists_path_of_stronglyConnectedComponent_eq {a b : V} (h : (a : StronglyConnectedComponent V) = b) : (Nonempty (Path a b)) ∧ (Nonempty (Path b a)) := (StronglyConnectedComponent.eq (a := a) (b := b)).1 h lemma stronglyConnectedComponent_singleton_iff (v : V) : (∀ w : V, (w : StronglyConnectedComponent V) = v → w = v) ↔ (∀ w : V, w ≠ v → ¬(Nonempty (Path v w) ∧ Nonempty (Path w v))) := by constructor · intro h_singleton w hw_ne h_bidir obtain ⟨hab, hba⟩ := h_bidir have h_same_scc : (w : StronglyConnectedComponent V) = v := stronglyConnectedComponent_eq_of_path (a := w) (b := v) hba hab obtain ⟨rfl⟩ := h_singleton w h_same_scc contradiction · intro h_no_bidir w h_same_scc by_contra hw_ne obtain ⟨hab, hba⟩ := exists_path_of_stronglyConnectedComponent_eq (a := w) (b := v) h_same_scc exact (h_no_bidir w hw_ne) ⟨hba, hab⟩ lemma IsStronglyConnected.isStronglyConnected_symmetrify (h : IsStronglyConnected V) : IsStronglyConnected (Symmetrify V) := by intro a b obtain ⟨p⟩ := h a b induction p with | nil => exact ⟨Path.nil⟩ | cons q e ih => exact ⟨ih.some.cons (Sum.inl e)⟩ lemma IsStronglyConnected.isSStronglyConnected_of_hom (h_sc : IsStronglyConnected V) {i₀ j₀ : V} (e₀ : i₀ ⟶ j₀) : IsSStronglyConnected V := by intro i j obtain ⟨p₁⟩ := h_sc i i₀ obtain ⟨p₂⟩ := h_sc j₀ j let p : Path i j := p₁.comp (e₀.toPath.comp p₂) have hp_pos : 0 < p.length := by simpa [p, Path.length_comp, Nat.add_comm, Nat.add_left_comm, Nat.add_assoc] using Nat.succ_pos (p₁.length + p₂.length) exact ⟨p, hp_pos⟩ end StronglyConnected end Quiver
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Push.lean
import Mathlib.Combinatorics.Quiver.Prefunctor /-! # Pushing a quiver structure along a map Given a map `σ : V → W` and a `Quiver` instance on `V`, this file defines a `Quiver` instance on `W` by associating to each arrow `v ⟶ v'` in `V` an arrow `σ v ⟶ σ v'` in `W`. -/ namespace Quiver universe v v₁ v₂ u u₁ u₂ variable {V : Type*} [Quiver V] {W : Type*} (σ : V → W) /-- The `Quiver` instance obtained by pushing arrows of `V` along the map `σ : V → W` -/ @[nolint unusedArguments] def Push (_ : V → W) := W instance [h : Nonempty W] : Nonempty (Push σ) := h /-- The quiver structure obtained by pushing arrows of `V` along the map `σ : V → W` -/ inductive PushQuiver {V : Type u} [Quiver.{v} V] {W : Type u₂} (σ : V → W) : W → W → Type max u u₂ v | arrow {X Y : V} (f : X ⟶ Y) : PushQuiver σ (σ X) (σ Y) instance : Quiver (Push σ) := ⟨PushQuiver σ⟩ namespace Push /-- The prefunctor induced by pushing arrows via `σ` -/ def of : V ⥤q Push σ where obj := σ map f := PushQuiver.arrow f @[simp] theorem of_obj : (of σ).obj = σ := rfl variable {W' : Type*} [Quiver W'] (φ : V ⥤q W') (τ : W → W') (h : ∀ x, φ.obj x = τ (σ x)) /-- Given a function `τ : W → W'` and a prefunctor `φ : V ⥤q W'`, one can extend `τ` to be a prefunctor `W ⥤q W'` if `τ` and `σ` factorize `φ` at the level of objects, where `W` is given the pushforward quiver structure `Push σ`. -/ noncomputable def lift : Push σ ⥤q W' where obj := τ map := @PushQuiver.rec V _ W σ (fun X Y _ => τ X ⟶ τ Y) @fun X Y f => by dsimp only rw [← h X, ← h Y] exact φ.map f theorem lift_obj : (lift σ φ τ h).obj = τ := rfl theorem lift_comp : (of σ ⋙q lift σ φ τ h) = φ := by fapply Prefunctor.ext · rintro X simp only [Prefunctor.comp_obj] apply Eq.symm exact h X · rintro X Y f simp only [Prefunctor.comp_map] apply eq_of_heq iterate 2 apply (cast_heq _ _).trans simp theorem lift_unique (Φ : Push σ ⥤q W') (Φ₀ : Φ.obj = τ) (Φcomp : (of σ ⋙q Φ) = φ) : Φ = lift σ φ τ h := by dsimp only [of, lift] fapply Prefunctor.ext · intro X simp only rw [Φ₀] · rintro _ _ ⟨⟩ subst_vars simp only [Prefunctor.comp_map] rfl end Push end Quiver
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Path/Decomposition.lean
import Mathlib.Algebra.Order.Group.Nat import Mathlib.Combinatorics.Quiver.Path /-! # Path Decomposition and Boundary Crossing This section provides lemmas for decomposing non-empty paths and for reasoning about paths that cross the boundary of a given set of vertices `S`. -/ namespace Quiver.Path section BoundaryEdges variable {V : Type*} [Quiver V] /-- A path from a vertex not in `S` to a vertex in `S` must cross the boundary. -/ theorem exists_notMem_mem_hom_path_path_of_notMem_mem {a b : V} (p : Path a b) (S : Set V) (ha_not_in_S : a ∉ S) (hb_in_S : b ∈ S) : ∃ᵉ (u ∉ S) (v ∈ S) (e : u ⟶ v) (p₁ : Path a u) (p₂ : Path v b), p = p₁.comp (e.toPath.comp p₂) := by induction h_len : p.length generalizing a b S ha_not_in_S hb_in_S with | zero => obtain rfl := eq_of_length_zero p h_len exact (ha_not_in_S hb_in_S).elim | succ n ih => have h_pos : 0 < p.length := by simp [h_len] obtain ⟨c, p', e, rfl⟩ := (length_ne_zero_iff_eq_cons p).mp h_pos.ne' by_cases hc_in_S : c ∈ S · have p'_len : p'.length = n := by simp_all obtain ⟨u, hu_not_S, v, hv_S, e_uv, p₁, p₂, hp'⟩ := ih p' S ha_not_in_S hc_in_S p'_len refine ⟨u, hu_not_S, v, hv_S, e_uv, p₁, p₂.comp e.toPath, ?_⟩ simp [hp', comp_toPath_eq_cons] · refine ⟨c, hc_in_S, b, hb_in_S, e, p', Path.nil, ?_⟩ simp [comp_toPath_eq_cons] theorem exists_mem_notMem_hom_path_path_of_notMem_mem {a b : V} (p : Path a b) (S : Set V) (ha_in_S : a ∈ S) (hb_not_in_S : b ∉ S) : ∃ᵉ (u ∈ S) (v ∉ S) (e : u ⟶ v) (p₁ : Path a u) (p₂ : Path v b), p = p₁.comp (e.toPath.comp p₂) := by classical have ha_not_in_compl : a ∉ Sᶜ := by simpa have hb_in_compl : b ∈ Sᶜ := by simpa obtain ⟨u, hu_not_in_compl, v, hv_in_compl, e, p₁, p₂, hp⟩ := exists_notMem_mem_hom_path_path_of_notMem_mem p Sᶜ ha_not_in_compl hb_in_compl simp only [Set.mem_compl_iff, not_not] at hu_not_in_compl hv_in_compl refine ⟨u, hu_not_in_compl, v, hv_in_compl, e, p₁, p₂, hp⟩ end BoundaryEdges end Quiver.Path
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Path/Vertices.lean
import Mathlib.Algebra.Order.Group.Nat import Mathlib.Combinatorics.Quiver.Path import Mathlib.Data.Set.Insert import Mathlib.Data.List.Basic /-! # Path Vertices This file provides lemmas for reasoning about the vertices of a path. -/ namespace Quiver.Path open List variable {V : Type*} [Quiver V] /-- The end vertex of a path. A path `p : Path a b` has `p.end = b`. -/ def «end» {a : V} : ∀ {b : V}, Path a b → V | b, _ => b @[simp] lemma end_cons {a b c : V} (p : Path a b) (e : b ⟶ c) : (p.cons e).end = c := rfl /-- The list of vertices in a path, including the start and end vertices. -/ def vertices {a : V} : ∀ {b : V}, Path a b → List V | _, nil => [a] | _, cons p e => (p.vertices).concat (p.cons e).end @[simp] lemma vertices_nil (a : V) : (nil : Path a a).vertices = [a] := rfl @[simp] lemma vertices_cons {a b c : V} (p : Path a b) (e : b ⟶ c) : (p.cons e).vertices = p.vertices.concat c := rfl /-- The vertex list of `cons` — convenient `simp` form. -/ lemma mem_vertices_cons {a b c : V} (p : Path a b) (e : b ⟶ c) {x : V} : x ∈ (p.cons e).vertices ↔ x ∈ p.vertices ∨ x = c := by simp only [vertices_cons] simp_all only [concat_eq_append, mem_append, mem_cons, not_mem_nil, or_false] lemma verticesSet_nil {a : V} : {v | v ∈ (nil : Path a a).vertices} = {a} := by simp only [vertices_nil, mem_singleton, Set.ext_iff, Set.mem_singleton_iff] exact fun x ↦ Set.mem_setOf /-- The length of vertices list equals path length plus one -/ @[simp] lemma vertices_length {V : Type*} [Quiver V] {a b : V} (p : Path a b) : p.vertices.length = p.length + 1 := by induction p with | nil => simp | cons p' e ih => simp [vertices_cons, length_cons, ih] lemma length_vertices_pos {a b : V} (p : Path a b) : 0 < p.vertices.length := by simp lemma vertices_ne_nil {a : V} {b : V} (p : Path a b) : p.vertices ≠ [] := by simp [← length_pos_iff_ne_nil] lemma start_mem_vertices {a b : V} (p : Path a b) : a ∈ p.vertices := by induction p with | nil => simp | cons p' e ih => simp [ih] /-- The head of the vertices list is the start vertex -/ @[simp] lemma vertices_head? {a b : V} (p : Path a b) : p.vertices.head? = some a := by induction p with | nil => simp only [vertices_nil, head?_cons] | cons p' e ih => simp [ih] /-- The head of the vertices list is the start vertex. -/ @[simp] lemma vertices_head_eq {a b : V} (p : Path a b) (h : p.vertices ≠ [] := p.vertices_ne_nil) : p.vertices.head h = a := by induction p with | nil => simp only [vertices_nil, head_cons] | cons p' _ ih => simp [head_append_of_ne_nil (vertices_ne_nil p'), ih] @[simp] lemma getElem_vertices_zero {a b : V} (p : Path a b) : p.vertices[0] = a := by induction p with | nil => simp | cons p' e ih => simp [ih] @[simp] lemma vertices_getLast {a b : V} (p : Path a b) (h : p.vertices ≠ [] := p.vertices_ne_nil) : p.vertices.getLast h = b := by induction p with | nil => simp only [vertices_nil, getLast_singleton] | cons p' e ih => simp @[simp] lemma dropLast_append_end_eq {a b : V} (p : Path a b) : p.vertices.dropLast ++ [b] = p.vertices := by simp_rw [← p.vertices_getLast p.vertices_ne_nil, dropLast_concat_getLast] @[simp] lemma vertices_comp {a b c : V} (p : Path a b) (q : Path b c) : (p.comp q).vertices = p.vertices.dropLast ++ q.vertices := by induction q with | nil => simp | cons q' e ih => simp [ih] @[simp] lemma length_eq_zero_iff {a : V} (p : Path a a) : p.length = 0 ↔ p = Path.nil := by cases p <;> tauto lemma vertices_comp_get_length_eq {a b c : V} (p₁ : Path a c) (p₂ : Path c b) (h : p₁.length < (p₁.comp p₂).vertices.length := by simp) : (p₁.comp p₂).vertices.get ⟨p₁.length, h⟩ = c := by simp @[simp] lemma vertices_toPath {i j : V} (e : i ⟶ j) : e.toPath.vertices = [i, j] := by change (Path.nil.cons e).vertices = [i, j] simp lemma vertices_toPath_tail {i j : V} (e : i ⟶ j) : e.toPath.vertices.tail = [j] := by simp /-- If a composition is `nil`, the left component must be `nil` (proved via lengths, avoiding dependent pattern-matching). -/ lemma nil_of_comp_eq_nil_left {a b : V} {p : Path a b} {q : Path b a} (h : p.comp q = Path.nil) : p.length = 0 := by have hlen : (p.comp q).length = 0 := by simpa using congrArg Path.length h have : p.length + q.length = 0 := by simpa [length_comp] using hlen exact Nat.eq_zero_of_add_eq_zero_right this /-- If a composition is `nil`, the right component must be `nil` -/ lemma nil_of_comp_eq_nil_right {a b : V} {p : Path a b} {q : Path b a} (h : p.comp q = Path.nil) : q.length = 0 := by have hlen : (p.comp q).length = 0 := by simpa using congrArg Path.length h have : p.length + q.length = 0 := by simpa [length_comp] using hlen exact Nat.eq_zero_of_add_eq_zero_left this lemma comp_eq_nil_iff {a b : V} {p : Path a b} {q : Path b a} : p.comp q = Path.nil ↔ p.length = 0 ∧ q.length = 0 := by refine ⟨fun h ↦ ⟨nil_of_comp_eq_nil_left h, nil_of_comp_eq_nil_right h⟩, fun ⟨hp, hq⟩ ↦ ?_⟩ induction p with | nil => simpa using (length_eq_zero_iff q).mp hq | cons p' _ ihp => simp at hp @[simp] lemma end_mem_vertices {a b : V} (p : Path a b) : b ∈ p.vertices := by have h₁ : p.vertices.getLast (vertices_ne_nil p) = b := vertices_getLast p (vertices_ne_nil p) have h₂ := getLast_mem (l := p.vertices) (vertices_ne_nil p) simpa [h₁] using h₂ /-! ### Path vertices decomposition -/ section variable {a b : V} (p : Path a b) open List /-- Given a path `p : Path a b` and an index `n ≤ p.length`, we can split `p = p₁.comp p₂` with `p₁.length = n`. -/ theorem exists_eq_comp_of_le_length {n : ℕ} (hn : n ≤ p.length) : ∃ (v : V) (p₁ : Path a v) (p₂ : Path v b), p = p₁.comp p₂ ∧ p₁.length = n := by induction p generalizing n with | nil => obtain ⟨rfl⟩ : n = 0 := by simpa using hn exact ⟨a, Path.nil, Path.nil, by simp, rfl⟩ | @cons _ c p' e ih => rw [length_cons] at hn rcases (Nat.le_succ_iff).1 hn with h | rfl · obtain ⟨d, p₁, p₂, hp, hl⟩ := ih h exact ⟨d, p₁, p₂.cons e, by simp [hp], hl⟩ · exact ⟨c, p'.cons e, Path.nil, by simp, by simp⟩ /-- `split_at_vertex` decomposes a path `p` at the vertex sitting in position `i` of its `vertices` -/ theorem exists_eq_comp_and_length_eq_of_lt_length (n : ℕ) (hn : n < p.vertices.length) : ∃ (v : V) (p₁ : Path a v) (p₂ : Path v b), p = p₁.comp p₂ ∧ p₁.length = n ∧ v = p.vertices[n] := by have hn_le_len : n ≤ p.length := by rw [vertices_length] at hn exact Nat.le_of_lt_succ hn obtain ⟨v, p₁, p₂, rfl, rfl⟩ := p.exists_eq_comp_of_le_length hn_le_len exact ⟨v, p₁, p₂, rfl, rfl, by simp⟩ /-- If a vertex `v` occurs in the list of vertices of a path `p : Path a b`, then `p` can be decomposed as a concatenation of a subpath from `a` to `v` and a subpath from `v` to `b`. -/ theorem exists_eq_comp_of_mem_vertices {v : V} (hv : v ∈ p.vertices) : ∃ (p₁ : Path a v) (p₂ : Path v b), p = p₁.comp p₂ := by obtain ⟨n, hn, rfl⟩ : ∃ n, ∃ hn : n < p.vertices.length, v = p.vertices[n] := exists_mem_iff_getElem.mp ⟨v, hv, rfl⟩ obtain ⟨v, p₁, p₂, hp, hv, rfl⟩ := p.exists_eq_comp_and_length_eq_of_lt_length n hn exact ⟨p₁, p₂, hp⟩ /-- Split a path at the *last* occurrence of a vertex. -/ theorem exists_eq_comp_and_notMem_tail_of_mem_vertices {v : V} (hv : v ∈ p.vertices) : ∃ (p₁ : Path a v) (p₂ : Path v b), p = p₁.comp p₂ ∧ v ∉ p₂.vertices.tail := by induction p with | nil => have hxa : v = a := by simpa [vertices_nil, List.mem_singleton] using hv subst hxa exact ⟨Path.nil, Path.nil, by simp only [comp_nil], by simp only [vertices_nil, tail_cons, not_mem_nil, not_false_eq_true]⟩ | cons pPrev e ih => have hv' : v ∈ pPrev.vertices ∨ v = (pPrev.cons e).end := by simpa using (mem_vertices_cons pPrev e).1 hv have h_case₁ : v = (pPrev.cons e).end → ∃ (p₁ : Path a v) (p₂ : Path v (pPrev.cons e).end), pPrev.cons e = p₁.comp p₂ ∧ v ∉ p₂.vertices.tail := by rintro rfl exact ⟨pPrev.cons e, Path.nil, by simp [comp_nil], by simp [vertices_nil]⟩ have h_case₂ : v ∈ pPrev.vertices → v ≠ (pPrev.cons e).end → ∃ (p₁ : Path a v) (p₂ : Path v (pPrev.cons e).end), pPrev.cons e = p₁.comp p₂ ∧ v ∉ p₂.vertices.tail := by intro hxPrev hxe_ne obtain ⟨q₁, q₂, h_prev, h_not_tail⟩ := ih hxPrev let q₂' : Path v (pPrev.cons e).end := q₂.cons e have h_no_tail : v ∉ q₂'.vertices.tail := by grind [vertices_cons, end_cons] exact ⟨q₁, q₂', by simp [q₂', h_prev], h_no_tail⟩ cases hv' with | inl h_in_prefix => by_cases h_eq_end : v = (pPrev.cons e).end · exact h_case₁ h_eq_end · exact h_case₂ h_in_prefix h_eq_end | inr h_eq_end => exact h_case₁ h_eq_end end end Quiver.Path
.lake/packages/mathlib/Mathlib/Combinatorics/Quiver/Path/Weight.lean
import Mathlib.Combinatorics.Quiver.Path import Mathlib.Algebra.Order.Ring.Defs /-! # Path weights in a Quiver This file defines the weight of a path in a quiver. The weight of a path is the product of the weights of its edges, where weights are taken from a monoid. ## Main definitions * `Quiver.Path.weight`: The weight of a path, defined as the multiplicative product of the weights of its constituent edges. * `Quiver.Path.weightOfEPs`: A convenience version of `weight` where the weight of an edge is determined by a function of its source and target vertices. ## Main results * `Quiver.Path.weight_comp`: The weight of a composition of paths is the product of their weights. * `Quiver.Path.weight_pos`: If all edge weights are positive, the path weight is positive. * `Quiver.Path.weightOfEPs_nonneg`: If all edge weights are non-negative, so is the path weight. -/ namespace Quiver.Path variable {V : Type*} [Quiver V] {R : Type*} section Weight variable [Monoid R] /-- The weight of a path is the product of the weights of its edges. -/ def weight (w : ∀ {i j : V}, (i ⟶ j) → R) : ∀ {i j : V}, Path i j → R | _, _, Path.nil => 1 | _, _, Path.cons p e => weight w p * w e /-- The additive weight of a path is the sum of the weights of its edges. -/ def addWeight {R : Type*} [AddMonoid R] (w : ∀ {i j : V}, (i ⟶ j) → R) : ∀ {i j : V}, Path i j → R | _, _, Path.nil => 0 | _, _, Path.cons p e => addWeight w p + w e attribute [to_additive existing addWeight] weight /-- The weight of a path, where the weight of an edge is defined by a function on its endpoints. -/ @[to_additive addWeightOfEPs /-- The additive weight of a path, where the weight of an edge is defined by a function on its endpoints. -/] def weightOfEPs (w : V → V → R) : ∀ {i j : V}, Path i j → R := weight (fun {i j} (_ : i ⟶ j) => w i j) @[to_additive (attr := simp) addWeight_nil] lemma weight_nil (w : ∀ {i j : V}, (i ⟶ j) → R) (a : V) : weight w (Path.nil : Path a a) = 1 := by simp [weight] @[to_additive (attr := simp) addWeight_cons] lemma weight_cons (w : ∀ {i j : V}, (i ⟶ j) → R) {a b c : V} (p : Path a b) (e : b ⟶ c) : weight w (p.cons e) = weight w p * w e := by simp [weight] @[to_additive addWeightOfEPs_nil] lemma weightOfEPs_nil (w : V → V → R) (a : V) : weightOfEPs w (Path.nil : Path a a) = 1 := by simp [weightOfEPs] @[to_additive addWeightOfEPs_cons] lemma weightOfEPs_cons (w : V → V → R) {a b c : V} (p : Path a b) (e : b ⟶ c) : weightOfEPs w (p.cons e) = weightOfEPs w p * w b c := by unfold weightOfEPs; simp @[to_additive (attr := simp) addWeight_comp] lemma weight_comp (w : ∀ {i j : V}, (i ⟶ j) → R) {a b c : V} (p : Path a b) (q : Path b c) : weight w (p.comp q) = weight w p * weight w q := by induction q with | nil => simp | cons _ _ ih => simp [ih, mul_assoc] @[to_additive addWeightOfEPs_comp] lemma weightOfEPs_comp (w : V → V → R) {a b c : V} (p : Path a b) (q : Path b c) : weightOfEPs w (p.comp q) = weightOfEPs w p * weightOfEPs w q := by simp [weightOfEPs, weight_comp] end Weight section OrderedWeight variable [Semiring R] [LinearOrder R] [IsStrictOrderedRing R] /-- If all edge weights are positive, then the weight of any path is positive. -/ lemma weight_pos {w : ∀ {i j : V}, (i ⟶ j) → R} (hw : ∀ {i j : V} (e : i ⟶ j), 0 < w e) {i j : V} (p : Path i j) : 0 < weight w p := by induction p with | nil => simp | cons p e ih => have he : 0 < w e := hw e simpa [weight_cons] using mul_pos ih he /-- If all edge weights are non-negative, then the weight of any path is non-negative. -/ lemma weight_nonneg {w : ∀ {i j : V}, (i ⟶ j) → R} (hw : ∀ {i j : V} (e : i ⟶ j), 0 ≤ w e) {i j : V} (p : Path i j) : 0 ≤ weight w p := by induction p with | nil => simp | cons p e ih => have he : 0 ≤ w e := hw e simpa [weight_cons] using mul_nonneg ih he /-- If all edge weights (given by a function on vertices) are positive, so is the path weight. -/ lemma weightOfEPs_pos {w : V → V → R} (hw : ∀ i j : V, 0 < w i j) {i j : V} (p : Path i j) : 0 < weightOfEPs w p := by apply weight_pos intro i j e exact hw _ _ /-- If all edge weights (given by a function on vertices) are non-negative, so is the path weight. -/ lemma weightOfEPs_nonneg {w : V → V → R} (hw : ∀ i j : V, 0 ≤ w i j) {i j : V} (p : Path i j) : 0 ≤ weightOfEPs w p := by apply weight_nonneg intro i j e exact hw _ _ end OrderedWeight end Quiver.Path
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Sum.lean
import Mathlib.Combinatorics.Matroid.Map import Mathlib.Logic.Embedding.Set /-! # Sums of matroids The *sum* `M` of a collection `M₁, M₂, ..` of matroids is a matroid on the disjoint union of the ground sets of the summands, in which the independent sets are precisely the unions of independent sets of the summands. We can ask for such a sum both for pairs and for arbitrary indexed collections of matroids, and we can also ask for the 'disjoint union' to be either set-theoretic or type-theoretic. To this end, we define five separate versions of the sum construction. ## Main definitions * For an indexed collection `M : (i : ι) → Matroid (α i)` of matroids on different types, `Matroid.sigma M` is the sum of the `M i`, as a matroid on the sigma type `(Σ i, α i)`. * For an indexed collection `M : ι → Matroid α` of matroids on the same type, `Matroid.sum' M` is the sum of the `M i`, as a matroid on the product type `ι × α`. * For an indexed collection `M : ι → Matroid α` of matroids on the same type, and a proof `h : Pairwise (Disjoint on fun i ↦ (M i).E)` that they have disjoint ground sets, `Matroid.disjointSigma M h` is the sum of the `M` as a `Matroid α` with ground set `⋃ i, (M i).E`. * `Matroid.sum (M : Matroid α) (N : Matroid β)` is the sum of `M` and `N` as a matroid on `α ⊕ β`. * If `M N : Matroid α` and `h : Disjoint M.E N.E`, then `Matroid.disjointSum M N h` is the sum of `M` and `N` as a `Matroid α` with ground set `M.E ∪ N.E`. ## Implementation details We only directly define a matroid for `Matroid.sigma`. All other versions of sum are defined indirectly, using `Matroid.sigma` and the API in `Matroid.map`. -/ assert_not_exists Field universe u v open Set namespace Matroid section Sigma variable {ι : Type*} {α : ι → Type*} {M : (i : ι) → Matroid (α i)} /-- The sum of an indexed collection of matroids, as a matroid on the sigma-type. -/ protected def sigma (M : (i : ι) → Matroid (α i)) : Matroid ((i : ι) × α i) where E := univ.sigma (fun i ↦ (M i).E) Indep I := ∀ i, (M i).Indep (Sigma.mk i ⁻¹' I) IsBase B := ∀ i, (M i).IsBase (Sigma.mk i ⁻¹' B) indep_iff' I := by refine ⟨fun h ↦ ?_, fun ⟨B, hB, hIB⟩ i ↦ (hB i).indep.subset (preimage_mono hIB)⟩ choose Bs hBs using fun i ↦ (h i).exists_isBase_superset refine ⟨univ.sigma Bs, fun i ↦ by simpa using (hBs i).1, ?_⟩ rw [← univ_sigma_preimage_mk I] refine sigma_mono rfl.subset fun i ↦ (hBs i).2 exists_isBase := by choose B hB using fun i ↦ (M i).exists_isBase exact ⟨univ.sigma B, by simpa⟩ isBase_exchange B₁ B₂ h₁ h₂ := by simp only [mem_diff, Sigma.exists, and_imp, Sigma.forall] intro i e he₁ he₂ have hf_ex := (h₁ i).exchange (h₂ i) ⟨he₁, by simpa⟩ obtain ⟨f, ⟨hf₁, hf₂⟩, hfB⟩ := hf_ex refine ⟨i, f, ⟨hf₁, hf₂⟩, fun j ↦ ?_⟩ rw [← union_singleton, preimage_union, preimage_diff] obtain (rfl | hne) := eq_or_ne i j · simpa only [ show ∀ x, {⟨i,x⟩} = Sigma.mk i '' {x} by simp, preimage_image_eq _ sigma_mk_injective, union_singleton] rw [preimage_singleton_eq_empty.2 (by simpa), preimage_singleton_eq_empty.2 (by simpa), diff_empty, union_empty] exact h₁ j maximality X _ I hI hIX := by choose Js hJs using fun i ↦ (hI i).subset_isBasis'_of_subset (preimage_mono (f := Sigma.mk i) hIX) use univ.sigma Js simp only [maximal_subset_iff', mem_univ, mk_preimage_sigma, and_imp] refine ⟨?_, ⟨fun i ↦ (hJs i).1.indep, ?_⟩, fun S hS hSX hJS ↦ ?_⟩ · rw [← univ_sigma_preimage_mk I] exact sigma_mono rfl.subset fun i ↦ (hJs i).2 · rw [← univ_sigma_preimage_mk X] exact sigma_mono rfl.subset fun i ↦ (hJs i).1.subset rw [← univ_sigma_preimage_mk S] refine sigma_mono rfl.subset fun i ↦ ?_ rw [sigma_subset_iff] at hJS rw [(hJs i).1.eq_of_subset_indep (hS i) (hJS <| mem_univ i)] exact preimage_mono hSX subset_ground B hB := by rw [← univ_sigma_preimage_mk B] apply sigma_mono Subset.rfl fun i ↦ (hB i).subset_ground @[simp] lemma sigma_indep_iff {I} : (Matroid.sigma M).Indep I ↔ ∀ i, (M i).Indep (Sigma.mk i ⁻¹' I) := Iff.rfl @[simp] lemma sigma_isBase_iff {B} : (Matroid.sigma M).IsBase B ↔ ∀ i, (M i).IsBase (Sigma.mk i ⁻¹' B) := Iff.rfl @[simp] lemma sigma_ground_eq : (Matroid.sigma M).E = univ.sigma fun i ↦ (M i).E := rfl @[simp] lemma sigma_isBasis_iff {I X} : (Matroid.sigma M).IsBasis I X ↔ ∀ i, (M i).IsBasis (Sigma.mk i ⁻¹' I) (Sigma.mk i ⁻¹' X) := by simp only [IsBasis, sigma_indep_iff, maximal_subset_iff, and_imp, and_assoc, sigma_ground_eq, forall_and, and_congr_right_iff] refine fun hI ↦ ⟨fun ⟨hIX, h, h'⟩ ↦ ⟨fun i ↦ preimage_mono hIX, fun i I₀ hI₀ hI₀X hII₀ ↦ ?_, ?_⟩, fun ⟨hIX, h', h''⟩ ↦ ⟨?_, ?_, ?_⟩⟩ · refine hII₀.antisymm ?_ specialize h (t := I ∪ Sigma.mk i '' I₀) simp only [preimage_union, union_subset_iff, hIX, image_subset_iff, hI₀X, and_self, subset_union_left, true_implies] at h rw [h, preimage_union, sigma_mk_preimage_image_eq_self] · exact subset_union_right intro j obtain (rfl | hij) := eq_or_ne i j · rwa [sigma_mk_preimage_image_eq_self, union_eq_self_of_subset_left hII₀] rw [sigma_mk_preimage_image' hij, union_empty] apply hI · exact fun i ↦ by simpa using preimage_mono (f := Sigma.mk i) h' · exact fun ⟨i, x⟩ hx ↦ by simpa using hIX i hx · refine fun J hJ hJX hIJ ↦ hIJ.antisymm fun ⟨i,x⟩ hx ↦ ?_ simpa using (h' i (hJ i) (preimage_mono hJX) (preimage_mono hIJ)).symm.subset hx exact fun ⟨i,x⟩ hx ↦ by simpa using h'' i hx lemma Finitary.sigma (h : ∀ i, (M i).Finitary) : (Matroid.sigma M).Finitary := by refine ⟨fun I hI ↦ ?_⟩ simp only [sigma_indep_iff] at hI ⊢ intro i apply indep_of_forall_finite_subset_indep intro J hJI hJ convert hI (Sigma.mk i '' J) (by simpa) (hJ.image _) i rw [sigma_mk_preimage_image_eq_self] end Sigma section sum' variable {α ι : Type*} {M : ι → Matroid α} /-- The sum of an indexed family `M : ι → Matroid α` of matroids on the same type, as a matroid on the product type `ι × α`. -/ protected def sum' (M : ι → Matroid α) : Matroid (ι × α) := (Matroid.sigma M).mapEquiv <| Equiv.sigmaEquivProd ι α @[simp] lemma sum'_indep_iff {I} : (Matroid.sum' M).Indep I ↔ ∀ i, (M i).Indep (Prod.mk i ⁻¹' I) := by simp only [Matroid.sum', mapEquiv_indep_iff, Equiv.sigmaEquivProd_symm_apply, sigma_indep_iff] convert Iff.rfl ext simp @[simp] lemma sum'_ground_eq (M : ι → Matroid α) : (Matroid.sum' M).E = ⋃ i, Prod.mk i '' (M i).E := by ext simp [Matroid.sum'] @[simp] lemma sum'_isBase_iff {B} : (Matroid.sum' M).IsBase B ↔ ∀ i, (M i).IsBase (Prod.mk i ⁻¹' B) := by simp only [Matroid.sum', mapEquiv_isBase_iff, Equiv.sigmaEquivProd_symm_apply, sigma_isBase_iff] convert Iff.rfl ext simp @[simp] lemma sum'_isBasis_iff {I X} : (Matroid.sum' M).IsBasis I X ↔ ∀ i, (M i).IsBasis (Prod.mk i ⁻¹' I) (Prod.mk i ⁻¹' X) := by simp only [Matroid.sum', mapEquiv_isBasis_iff, Equiv.sigmaEquivProd_symm_apply, sigma_isBasis_iff] convert Iff.rfl <;> exact ext <| by simp lemma Finitary.sum' (h : ∀ i, (M i).Finitary) : (Matroid.sum' M).Finitary := by have := Finitary.sigma h rw [Matroid.sum'] infer_instance end sum' section disjointSigma open scoped Function -- required for scoped `on` notation variable {α ι : Type*} {M : ι → Matroid α} /-- The sum of an indexed collection of matroids on `α` with pairwise disjoint ground sets, as a matroid on `α` -/ protected def disjointSigma (M : ι → Matroid α) (h : Pairwise (Disjoint on fun i ↦ (M i).E)) : Matroid α := (Matroid.sigma (fun i ↦ (M i).restrictSubtype (M i).E)).mapEmbedding (Function.Embedding.sigmaSet h) @[simp] lemma disjointSigma_ground_eq {h} : (Matroid.disjointSigma M h).E = ⋃ i : ι, (M i).E := by ext; simp [Matroid.disjointSigma, mapEmbedding, restrictSubtype] @[simp] lemma disjointSigma_indep_iff {h I} : (Matroid.disjointSigma M h).Indep I ↔ (∀ i, (M i).Indep (I ∩ (M i).E)) ∧ I ⊆ ⋃ i, (M i).E := by simp [Matroid.disjointSigma, (Function.Embedding.sigmaSet_preimage h)] @[simp] lemma disjointSigma_isBase_iff {h B} : (Matroid.disjointSigma M h).IsBase B ↔ (∀ i, (M i).IsBase (B ∩ (M i).E)) ∧ B ⊆ ⋃ i, (M i).E := by simp [Matroid.disjointSigma, (Function.Embedding.sigmaSet_preimage h)] @[simp] lemma disjointSigma_isBasis_iff {h I X} : (Matroid.disjointSigma M h).IsBasis I X ↔ (∀ i, (M i).IsBasis (I ∩ (M i).E) (X ∩ (M i).E)) ∧ I ⊆ X ∧ X ⊆ ⋃ i, (M i).E := by simp [Matroid.disjointSigma, Function.Embedding.sigmaSet_preimage h] end disjointSigma section Sum variable {α : Type u} {β : Type v} {M N : Matroid α} /-- The sum of two matroids as a matroid on the sum type. -/ protected def sum (M : Matroid α) (N : Matroid β) : Matroid (α ⊕ β) := let S := Matroid.sigma (Bool.rec (M.mapEquiv Equiv.ulift.symm) (N.mapEquiv Equiv.ulift.symm)) let e := Equiv.sumEquivSigmaBool (ULift.{v} α) (ULift.{u} β) (S.mapEquiv e.symm).mapEquiv (Equiv.sumCongr Equiv.ulift Equiv.ulift) @[simp] lemma sum_ground (M : Matroid α) (N : Matroid β) : (M.sum N).E = (.inl '' M.E) ∪ (.inr '' N.E) := by simp [Matroid.sum, Set.ext_iff, mapEquiv, mapEmbedding, Equiv.ulift, Equiv.sumEquivSigmaBool] @[simp] lemma sum_indep_iff (M : Matroid α) (N : Matroid β) {I : Set (α ⊕ β)} : (M.sum N).Indep I ↔ M.Indep (.inl ⁻¹' I) ∧ N.Indep (.inr ⁻¹' I) := by simp only [Matroid.sum, mapEquiv_indep_iff, Equiv.sumCongr_symm, Equiv.sumCongr_apply, Equiv.symm_symm, sigma_indep_iff, Bool.forall_bool] convert Iff.rfl <;> simp [Set.ext_iff, Equiv.ulift, Equiv.sumEquivSigmaBool] @[simp] lemma sum_isBase_iff {M : Matroid α} {N : Matroid β} {B : Set (α ⊕ β)} : (M.sum N).IsBase B ↔ M.IsBase (.inl ⁻¹' B) ∧ N.IsBase (.inr ⁻¹' B) := by simp only [Matroid.sum, mapEquiv_isBase_iff, Equiv.sumCongr_symm, Equiv.sumCongr_apply, Equiv.symm_symm, sigma_isBase_iff, Bool.forall_bool] convert Iff.rfl <;> simp [Set.ext_iff, Equiv.ulift, Equiv.sumEquivSigmaBool] @[simp] lemma sum_isBasis_iff {M : Matroid α} {N : Matroid β} {I X : Set (α ⊕ β)} : (M.sum N).IsBasis I X ↔ (M.IsBasis (Sum.inl ⁻¹' I) (Sum.inl ⁻¹' X) ∧ N.IsBasis (Sum.inr ⁻¹' I) (Sum.inr ⁻¹' X)) := by simp only [Matroid.sum, mapEquiv_isBasis_iff, Equiv.sumCongr_symm, Equiv.sumCongr_apply, Equiv.symm_symm, sigma_isBasis_iff, Bool.forall_bool, Equiv.sumEquivSigmaBool, Equiv.coe_fn_mk, Equiv.ulift] convert Iff.rfl <;> exact ext <| by simp end Sum section disjointSum variable {α : Type*} {M N : Matroid α} /-- The sum of two matroids on `α` with disjoint ground sets, as a `Matroid α`. -/ def disjointSum (M N : Matroid α) (h : Disjoint M.E N.E) : Matroid α := ((M.restrictSubtype M.E).sum (N.restrictSubtype N.E)).mapEmbedding <| Function.Embedding.sumSet h @[simp] lemma disjointSum_ground_eq {h} : (M.disjointSum N h).E = M.E ∪ N.E := by simp [disjointSum, restrictSubtype, mapEmbedding] @[simp] lemma disjointSum_indep_iff {h I} : (M.disjointSum N h).Indep I ↔ M.Indep (I ∩ M.E) ∧ N.Indep (I ∩ N.E) ∧ I ⊆ M.E ∪ N.E := by simp [disjointSum, and_assoc] @[simp] lemma disjointSum_isBase_iff {h B} : (M.disjointSum N h).IsBase B ↔ M.IsBase (B ∩ M.E) ∧ N.IsBase (B ∩ N.E) ∧ B ⊆ M.E ∪ N.E := by simp [disjointSum, and_assoc] @[simp] lemma disjointSum_isBasis_iff {h I X} : (M.disjointSum N h).IsBasis I X ↔ M.IsBasis (I ∩ M.E) (X ∩ M.E) ∧ N.IsBasis (I ∩ N.E) (X ∩ N.E) ∧ I ⊆ X ∧ X ⊆ M.E ∪ N.E := by simp [disjointSum, and_assoc] lemma disjointSum_comm {h} : M.disjointSum N h = N.disjointSum M h.symm := by ext · simp [union_comm] repeat simpa [union_comm] using ⟨fun ⟨m, n, h⟩ ↦ ⟨n, m, M.E.union_comm N.E ▸ h⟩, fun ⟨n, m, h⟩ ↦ ⟨m, n, M.E.union_comm N.E ▸ h⟩⟩ lemma Indep.eq_union_image_of_disjointSum {h I} (hI : (disjointSum M N h).Indep I) : ∃ IM IN, M.Indep IM ∧ N.Indep IN ∧ Disjoint IM IN ∧ I = IM ∪ IN := by rw [disjointSum_indep_iff] at hI refine ⟨_, _, hI.1, hI.2.1, h.mono inter_subset_right inter_subset_right, ?_⟩ rw [← inter_union_distrib_left, inter_eq_self_of_subset_left hI.2.2] lemma IsBase.eq_union_image_of_disjointSum {h B} (hB : (disjointSum M N h).IsBase B) : ∃ BM BN, M.IsBase BM ∧ N.IsBase BN ∧ Disjoint BM BN ∧ B = BM ∪ BN := by rw [disjointSum_isBase_iff] at hB refine ⟨_, _, hB.1, hB.2.1, h.mono inter_subset_right inter_subset_right, ?_⟩ rw [← inter_union_distrib_left, inter_eq_self_of_subset_left hB.2.2] end disjointSum end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Init.lean
import Mathlib.Init import Aesop /-! # Matroid Rule Set This module defines the `Matroid` Aesop rule set which is used by the `aesop_mat` tactic. Aesop rule sets only become visible once the file in which they're declared is imported, so we must put this declaration into its own file. -/ declare_aesop_rule_sets [Matroid]
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Circuit.lean
import Mathlib.Combinatorics.Matroid.Closure /-! # Matroid IsCircuits A 'Circuit' of a matroid `M` is a minimal set `C` that is dependent in `M`. A matroid is determined by its set of circuits, and often the circuits offer a more compact description of a matroid than the collection of independent sets or bases. In matroids arising from graphs, circuits correspond to graphical cycles. ## Main Declarations * `Matroid.IsCircuit M C` means that `C` is minimally dependent in `M`. * For an `Indep`endent set `I` whose closure contains an element `e ∉ I`, `Matroid.fundCircuit M e I` is the unique circuit contained in `insert e I`. * `Matroid.Indep.fundCircuit_isCircuit` states that `Matroid.fundCircuit M e I` is indeed a circuit. * `Matroid.IsCircuit.eq_fundCircuit_of_subset` states that `Matroid.fundCircuit M e I` is the unique circuit contained in `insert e I`. * `Matroid.dep_iff_superset_isCircuit` states that the dependent subsets of the ground set are precisely those that contain a circuit. * `Matroid.ext_isCircuit` : a matroid is determined by its collection of circuits. * `Matroid.IsCircuit.strong_multi_elimination` : the strong circuit elimination rule for an infinite collection of circuits. * `Matroid.IsCircuit.strong_elimination` : the strong circuit elimination rule for two circuits. * `Matroid.finitary_iff_forall_isCircuit_finite` : finitary matroids are precisely those whose circuits are all finite. * `Matroid.IsCocircuit M C` means that `C` is minimally dependent in `M✶`, or equivalently that `M.E \ C` is a hyperplane of `M`. * `Matroid.fundCocircuit M B e` is the unique cocircuit that intersects the base `B` precisely in the element `e`. * `Matroid.IsBase.mem_fundCocircuit_iff_mem_fundCircuit` : `e` is in the fundamental circuit for `B` and `f` iff `f` is in the fundamental cocircuit for `B` and `e`. ## Implementation Details Since `Matroid.fundCircuit M e I` is only sensible if `I` is independent and `e ∈ M.closure I \ I`, to avoid hypotheses being explicitly included in the definition, junk values need to be chosen if either hypothesis fails. The definition is chosen so that the junk values satisfy `M.fundCircuit e I = {e}` for `e ∈ I` or `e ∉ M.E` and `M.fundCircuit e I = insert e I` if `e ∈ M.E \ M.closure I`. These make the useful statement `e ∈ M.fundCircuit e I ⊆ insert e I` true unconditionally. -/ variable {α : Type*} {M : Matroid α} {C C' I X Y R : Set α} {e f x y : α} open Set namespace Matroid /-- `M.IsCircuit C` means that `C` is a minimal dependent set in `M`. -/ def IsCircuit (M : Matroid α) := Minimal M.Dep lemma isCircuit_def : M.IsCircuit C ↔ Minimal M.Dep C := Iff.rfl lemma IsCircuit.dep (hC : M.IsCircuit C) : M.Dep C := hC.prop lemma IsCircuit.not_indep (hC : M.IsCircuit C) : ¬ M.Indep C := hC.dep.not_indep lemma IsCircuit.minimal (hC : M.IsCircuit C) : Minimal M.Dep C := hC @[aesop unsafe 20% (rule_sets := [Matroid])] lemma IsCircuit.subset_ground (hC : M.IsCircuit C) : C ⊆ M.E := hC.dep.subset_ground lemma IsCircuit.nonempty (hC : M.IsCircuit C) : C.Nonempty := hC.dep.nonempty lemma empty_not_isCircuit (M : Matroid α) : ¬M.IsCircuit ∅ := fun h ↦ by simpa using h.nonempty lemma isCircuit_iff : M.IsCircuit C ↔ M.Dep C ∧ ∀ ⦃D⦄, M.Dep D → D ⊆ C → D = C := by simp_rw [isCircuit_def, minimal_subset_iff, eq_comm (a := C)] lemma IsCircuit.ssubset_indep (hC : M.IsCircuit C) (hXC : X ⊂ C) : M.Indep X := by rw [← not_dep_iff (hXC.subset.trans hC.subset_ground)] exact fun h ↦ hXC.ne ((isCircuit_iff.1 hC).2 h hXC.subset) lemma IsCircuit.minimal_not_indep (hC : M.IsCircuit C) : Minimal (¬ M.Indep ·) C := by simp_rw [minimal_iff_forall_ssubset, and_iff_right hC.not_indep, not_not] exact fun ⦃t⦄ a ↦ ssubset_indep hC a lemma isCircuit_iff_minimal_not_indep (hCE : C ⊆ M.E) : M.IsCircuit C ↔ Minimal (¬ M.Indep ·) C := ⟨IsCircuit.minimal_not_indep, fun h ↦ ⟨(not_indep_iff hCE).1 h.prop, fun _ hJ hJC ↦ (h.eq_of_superset hJ.not_indep hJC).le⟩⟩ lemma IsCircuit.diff_singleton_indep (hC : M.IsCircuit C) (he : e ∈ C) : M.Indep (C \ {e}) := hC.ssubset_indep (diff_singleton_ssubset.2 he) lemma isCircuit_iff_forall_ssubset : M.IsCircuit C ↔ M.Dep C ∧ ∀ ⦃I⦄, I ⊂ C → M.Indep I := by rw [IsCircuit, minimal_iff_forall_ssubset, and_congr_right_iff] exact fun h ↦ ⟨fun h' I hIC ↦ ((not_dep_iff (hIC.subset.trans h.subset_ground)).1 (h' hIC)), fun h I hIC ↦ (h hIC).not_dep⟩ lemma isCircuit_antichain : IsAntichain (· ⊆ ·) (setOf M.IsCircuit) := fun _ hC _ hC' hne hss ↦ hne <| (IsCircuit.minimal hC').eq_of_subset hC.dep hss lemma IsCircuit.eq_of_not_indep_subset (hC : M.IsCircuit C) (hX : ¬ M.Indep X) (hXC : X ⊆ C) : X = C := eq_of_le_of_not_lt hXC (hX ∘ hC.ssubset_indep) lemma IsCircuit.eq_of_dep_subset (hC : M.IsCircuit C) (hX : M.Dep X) (hXC : X ⊆ C) : X = C := hC.eq_of_not_indep_subset hX.not_indep hXC lemma IsCircuit.not_ssubset (hC : M.IsCircuit C) (hC' : M.IsCircuit C') : ¬C' ⊂ C := fun h' ↦ h'.ne (hC.eq_of_dep_subset hC'.dep h'.subset) lemma IsCircuit.eq_of_subset_isCircuit (hC : M.IsCircuit C) (hC' : M.IsCircuit C') (h : C ⊆ C') : C = C' := hC'.eq_of_dep_subset hC.dep h lemma IsCircuit.eq_of_superset_isCircuit (hC : M.IsCircuit C) (hC' : M.IsCircuit C') (h : C' ⊆ C) : C = C' := (hC'.eq_of_subset_isCircuit hC h).symm lemma isCircuit_iff_dep_forall_diff_singleton_indep : M.IsCircuit C ↔ M.Dep C ∧ ∀ e ∈ C, M.Indep (C \ {e}) := by wlog hCE : C ⊆ M.E · exact iff_of_false (hCE ∘ IsCircuit.subset_ground) (fun h ↦ hCE h.1.subset_ground) simp [isCircuit_iff_minimal_not_indep hCE, ← not_indep_iff hCE, minimal_iff_forall_diff_singleton (P := (¬ M.Indep ·)) (fun _ _ hY hYX hX ↦ hY <| hX.subset hYX)] /-! ### Independence and bases -/ lemma Indep.insert_isCircuit_of_forall (hI : M.Indep I) (heI : e ∉ I) (he : e ∈ M.closure I) (h : ∀ f ∈ I, e ∉ M.closure (I \ {f})) : M.IsCircuit (insert e I) := by rw [isCircuit_iff_dep_forall_diff_singleton_indep, hI.insert_dep_iff, and_iff_right ⟨he, heI⟩] rintro f (rfl | hfI) · simpa [heI] rw [← insert_diff_singleton_comm (by rintro rfl; contradiction), (hI.diff _).insert_indep_iff_of_notMem (by simp [heI])] exact ⟨mem_ground_of_mem_closure he, h f hfI⟩ lemma Indep.insert_isCircuit_of_forall_of_nontrivial (hI : M.Indep I) (hInt : I.Nontrivial) (he : e ∈ M.closure I) (h : ∀ f ∈ I, e ∉ M.closure (I \ {f})) : M.IsCircuit (insert e I) := by refine hI.insert_isCircuit_of_forall (fun heI ↦ ?_) he h obtain ⟨f, hf, hne⟩ := hInt.exists_ne e exact h f hf (mem_closure_of_mem' _ (by simp [heI, hne.symm])) lemma IsCircuit.diff_singleton_isBasis (hC : M.IsCircuit C) (he : e ∈ C) : M.IsBasis (C \ {e}) C := by nth_rw 2 [← insert_eq_of_mem he] rw [← insert_diff_singleton, (hC.diff_singleton_indep he).isBasis_insert_iff, insert_diff_singleton, insert_eq_of_mem he] exact Or.inl hC.dep lemma IsCircuit.isBasis_iff_eq_diff_singleton (hC : M.IsCircuit C) : M.IsBasis I C ↔ ∃ e ∈ C, I = C \ {e} := by refine ⟨fun h ↦ ?_, ?_⟩ · obtain ⟨e, he⟩ := exists_of_ssubset (h.subset.ssubset_of_ne (by rintro rfl; exact hC.dep.not_indep h.indep)) exact ⟨e, he.1, h.eq_of_subset_indep (hC.diff_singleton_indep he.1) (subset_diff_singleton h.subset he.2) diff_subset⟩ rintro ⟨e, he, rfl⟩ exact hC.diff_singleton_isBasis he lemma IsCircuit.isBasis_iff_insert_eq (hC : M.IsCircuit C) : M.IsBasis I C ↔ ∃ e ∈ C \ I, C = insert e I := by rw [hC.isBasis_iff_eq_diff_singleton] refine ⟨fun ⟨e, he, hI⟩ ↦ ⟨e, ⟨he, fun heI ↦ (hI.subset heI).2 rfl⟩, ?_⟩, fun ⟨e, he, hC⟩ ↦ ⟨e, he.1, ?_⟩⟩ · rw [hI, insert_diff_singleton, insert_eq_of_mem he] rw [hC, insert_diff_self_of_notMem he.2] /-! ### Restriction -/ lemma IsCircuit.isCircuit_restrict_of_subset (hC : M.IsCircuit C) (hCR : C ⊆ R) : (M ↾ R).IsCircuit C := by simp_rw [isCircuit_iff, restrict_dep_iff, dep_iff, and_imp] at * exact ⟨⟨hC.1.1, hCR⟩, fun I hI _ hIC ↦ hC.2 hI (hIC.trans hC.1.2) hIC⟩ lemma restrict_isCircuit_iff (hR : R ⊆ M.E := by aesop_mat) : (M ↾ R).IsCircuit C ↔ M.IsCircuit C ∧ C ⊆ R := by refine ⟨?_, fun h ↦ h.1.isCircuit_restrict_of_subset h.2⟩ simp_rw [isCircuit_iff, restrict_dep_iff, and_imp, dep_iff] exact fun hC hCR h ↦ ⟨⟨⟨hC,hCR.trans hR⟩,fun I hI hIC ↦ h hI.1 (hIC.trans hCR) hIC⟩,hCR⟩ /-! ### Fundamental IsCircuits -/ /-- For an independent set `I` and some `e ∈ M.closure I \ I`, `M.fundCircuit e I` is the unique circuit contained in `insert e I`. For the fact that this is a circuit, see `Matroid.Indep.fundCircuit_isCircuit`, and the fact that it is unique, see `Matroid.IsCircuit.eq_fundCircuit_of_subset`. Has the junk value `{e}` if `e ∈ I` or `e ∉ M.E`, and `insert e I` if `e ∈ M.E \ M.closure I`. -/ def fundCircuit (M : Matroid α) (e : α) (I : Set α) : Set α := insert e (I ∩ ⋂₀ {J | J ⊆ I ∧ M.closure {e} ⊆ M.closure J}) lemma fundCircuit_eq_sInter (he : e ∈ M.closure I) : M.fundCircuit e I = insert e (⋂₀ {J | J ⊆ I ∧ e ∈ M.closure J}) := by rw [fundCircuit] simp_rw [closure_subset_closure_iff_subset_closure (show {e} ⊆ M.E by simpa using mem_ground_of_mem_closure he), singleton_subset_iff] rw [inter_eq_self_of_subset_right (sInter_subset_of_mem (by simpa))] lemma fundCircuit_subset_insert (M : Matroid α) (e : α) (I : Set α) : M.fundCircuit e I ⊆ insert e I := insert_subset_insert inter_subset_left lemma fundCircuit_subset_ground (he : e ∈ M.E) (hI : I ⊆ M.E := by aesop_mat) : M.fundCircuit e I ⊆ M.E := (M.fundCircuit_subset_insert e I).trans (insert_subset he hI) lemma mem_fundCircuit (M : Matroid α) (e : α) (I : Set α) : e ∈ fundCircuit M e I := mem_insert .. lemma fundCircuit_diff_eq_inter (M : Matroid α) (heI : e ∉ I) : (M.fundCircuit e I) \ {e} = (M.fundCircuit e I) ∩ I := (subset_inter diff_subset (by simp [fundCircuit_subset_insert])).antisymm (subset_diff_singleton inter_subset_left (by simp [heI])) /-- The fundamental isCircuit of `e` and `X` has the junk value `{e}` if `e ∈ X` -/ lemma fundCircuit_eq_of_mem (heX : e ∈ X) : M.fundCircuit e X = {e} := by suffices h : ∀ a ∈ X, (∀ t ⊆ X, M.closure {e} ⊆ M.closure t → a ∈ t) → a = e by simpa [subset_antisymm_iff, fundCircuit] exact fun b hbX h ↦ h _ (singleton_subset_iff.2 heX) Subset.rfl lemma fundCircuit_eq_of_notMem_ground (heX : e ∉ M.E) : M.fundCircuit e X = {e} := by suffices h : ∀ a ∈ X, (∀ t ⊆ X, M.closure {e} ⊆ M.closure t → a ∈ t) → a = e by simpa [subset_antisymm_iff, fundCircuit] simp_rw [← M.closure_inter_ground {e}, singleton_inter_eq_empty.2 heX] exact fun a haX h ↦ by simpa using h ∅ (empty_subset X) rfl.subset @[deprecated (since := "2025-05-23")] alias fundCircuit_eq_of_not_mem_ground := fundCircuit_eq_of_notMem_ground lemma Indep.fundCircuit_isCircuit (hI : M.Indep I) (hecl : e ∈ M.closure I) (heI : e ∉ I) : M.IsCircuit (M.fundCircuit e I) := by have aux : ⋂₀ {J | J ⊆ I ∧ e ∈ M.closure J} ⊆ I := sInter_subset_of_mem (by simpa) rw [fundCircuit_eq_sInter hecl] refine (hI.subset aux).insert_isCircuit_of_forall ?_ ?_ ?_ · simp [show ∃ x ⊆ I, e ∈ M.closure x ∧ e ∉ x from ⟨I, by simp [hecl, heI]⟩] · rw [hI.closure_sInter_eq_biInter_closure_of_forall_subset ⟨I, by simpa⟩ (by simp +contextual)] simp simp only [mem_sInter, mem_setOf_eq, and_imp] exact fun f hf hecl ↦ (hf _ (diff_subset.trans aux) hecl).2 rfl lemma Indep.mem_fundCircuit_iff (hI : M.Indep I) (hecl : e ∈ M.closure I) (heI : e ∉ I) : x ∈ M.fundCircuit e I ↔ M.Indep (insert e I \ {x}) := by obtain rfl | hne := eq_or_ne x e · simp [hI.diff, mem_fundCircuit] suffices (∀ t ⊆ I, e ∈ M.closure t → x ∈ t) ↔ e ∉ M.closure (I \ {x}) by simpa [fundCircuit_eq_sInter hecl, hne, ← insert_diff_singleton_comm hne.symm, (hI.diff _).insert_indep_iff, mem_ground_of_mem_closure hecl, heI] refine ⟨fun h hecl ↦ (h _ diff_subset hecl).2 rfl, fun h J hJ heJ ↦ by_contra fun hxJ ↦ h ?_⟩ exact M.closure_subset_closure (subset_diff_singleton hJ hxJ) heJ lemma IsBase.fundCircuit_isCircuit {B : Set α} (hB : M.IsBase B) (hxE : x ∈ M.E) (hxB : x ∉ B) : M.IsCircuit (M.fundCircuit x B) := hB.indep.fundCircuit_isCircuit (by rwa [hB.closure_eq]) hxB /-- For `I` independent, `M.fundCircuit e I` is the only circuit contained in `insert e I`. -/ lemma IsCircuit.eq_fundCircuit_of_subset (hC : M.IsCircuit C) (hI : M.Indep I) (hCs : C ⊆ insert e I) : C = M.fundCircuit e I := by obtain hCI | ⟨heC, hCeI⟩ := subset_insert_iff.1 hCs · exact (hC.not_indep (hI.subset hCI)).elim suffices hss : M.fundCircuit e I ⊆ C by refine hC.eq_of_superset_isCircuit (hI.fundCircuit_isCircuit ?_ fun heI ↦ ?_) hss · rw [hI.mem_closure_iff] exact .inl (hC.dep.superset hCs (insert_subset (hC.subset_ground heC) hI.subset_ground)) exact hC.not_indep (hI.subset (hCs.trans (by simp [heI]))) have heCcl := (hC.diff_singleton_isBasis heC).subset_closure heC have heI : e ∈ M.closure I := M.closure_subset_closure hCeI heCcl rw [fundCircuit_eq_sInter heI] refine insert_subset heC <| (sInter_subset_of_mem (t := C \ {e}) ?_).trans diff_subset exact ⟨hCeI, heCcl⟩ lemma fundCircuit_restrict {R : Set α} (hIR : I ⊆ R) (heR : e ∈ R) (hR : R ⊆ M.E) : (M ↾ R).fundCircuit e I = M.fundCircuit e I := by simp_rw [fundCircuit, M.restrict_closure_eq (R := R) (X := {e}) (by simpa)] apply subset_antisymm · gcongr 5 with J hJI; intro heJ simp only [restrict_closure_eq'] refine (inter_subset_inter_left _ ?_).trans subset_union_left rwa [inter_eq_self_of_subset_left (hJI.trans hIR)] gcongr 5 with J hJI; intro heJ refine closure_subset_closure_of_subset_closure ?_ rw [restrict_closure_eq _ (hJI.trans hIR) hR] at heJ simp only [subset_inter_iff, inter_subset_right, and_true] at heJ exact subset_trans (by simpa [M.mem_closure_of_mem' (mem_singleton e) (hR heR)]) heJ @[simp] lemma fundCircuit_restrict_univ (M : Matroid α) : (M ↾ univ).fundCircuit e I = M.fundCircuit e I := by have aux (A B) : M.closure A ⊆ B ∪ univ \ M.E ↔ M.closure A ⊆ B := by refine ⟨fun h ↦ ?_, fun h ↦ h.trans subset_union_left⟩ refine (subset_inter h (M.closure_subset_ground A)).trans ?_ simp [union_inter_distrib_right] simp [fundCircuit, aux] /-! ### Dependence -/ lemma Dep.exists_isCircuit_subset (hX : M.Dep X) : ∃ C, C ⊆ X ∧ M.IsCircuit C := by obtain ⟨I, hI⟩ := M.exists_isBasis X obtain ⟨e, heX, heI⟩ := exists_of_ssubset (hI.subset.ssubset_of_ne (by rintro rfl; exact hI.indep.not_dep hX)) exact ⟨M.fundCircuit e I, (M.fundCircuit_subset_insert e I).trans (insert_subset heX hI.subset), hI.indep.fundCircuit_isCircuit (hI.subset_closure heX) heI⟩ lemma dep_iff_superset_isCircuit (hX : X ⊆ M.E := by aesop_mat) : M.Dep X ↔ ∃ C, C ⊆ X ∧ M.IsCircuit C := ⟨Dep.exists_isCircuit_subset, fun ⟨C, hCX, hC⟩ ↦ hC.dep.superset hCX⟩ /-- A version of `Matroid.dep_iff_superset_isCircuit` that has the supportedness hypothesis as part of the equivalence, rather than a hypothesis. -/ lemma dep_iff_superset_isCircuit' : M.Dep X ↔ (∃ C, C ⊆ X ∧ M.IsCircuit C) ∧ X ⊆ M.E := ⟨fun h ↦ ⟨h.exists_isCircuit_subset, h.subset_ground⟩, fun ⟨⟨C, hCX, hC⟩, h⟩ ↦ hC.dep.superset hCX⟩ /-- A version of `Matroid.indep_iff_forall_subset_not_isCircuit` that has the supportedness hypothesis as part of the equivalence, rather than a hypothesis. -/ lemma indep_iff_forall_subset_not_isCircuit' : M.Indep I ↔ (∀ C, C ⊆ I → ¬M.IsCircuit C) ∧ I ⊆ M.E := by simp_rw [indep_iff_not_dep, dep_iff_superset_isCircuit'] aesop lemma indep_iff_forall_subset_not_isCircuit (hI : I ⊆ M.E := by aesop_mat) : M.Indep I ↔ ∀ C, C ⊆ I → ¬M.IsCircuit C := by rw [indep_iff_forall_subset_not_isCircuit', and_iff_left hI] /-! ### Closure -/ lemma IsCircuit.closure_diff_singleton_eq (hC : M.IsCircuit C) (e : α) : M.closure (C \ {e}) = M.closure C := (em (e ∈ C)).elim (fun he ↦ by rw [(hC.diff_singleton_isBasis he).closure_eq_closure]) (fun he ↦ by rw [diff_singleton_eq_self he]) lemma IsCircuit.subset_closure_diff_singleton (hC : M.IsCircuit C) (e : α) : C ⊆ M.closure (C \ {e}) := by rw [hC.closure_diff_singleton_eq] exact M.subset_closure _ hC.subset_ground lemma IsCircuit.mem_closure_diff_singleton_of_mem (hC : M.IsCircuit C) (heC : e ∈ C) : e ∈ M.closure (C \ {e}) := hC.subset_closure_diff_singleton e heC lemma exists_isCircuit_of_mem_closure (he : e ∈ M.closure X) (heX : e ∉ X) : ∃ C ⊆ insert e X, M.IsCircuit C ∧ e ∈ C := let ⟨I, hI⟩ := M.exists_isBasis' X ⟨_, (fundCircuit_subset_insert ..).trans (insert_subset_insert hI.subset), hI.indep.fundCircuit_isCircuit (by rwa [hI.closure_eq_closure]) (notMem_subset hI.subset heX), M.mem_fundCircuit e I⟩ lemma mem_closure_iff_exists_isCircuit (he : e ∉ X) : e ∈ M.closure X ↔ ∃ C ⊆ insert e X, M.IsCircuit C ∧ e ∈ C := ⟨fun h ↦ exists_isCircuit_of_mem_closure h he, fun ⟨C, hCX, hC, heC⟩ ↦ mem_of_mem_of_subset (hC.mem_closure_diff_singleton_of_mem heC) (M.closure_subset_closure (by simpa))⟩ /-! ### Extensionality -/ lemma ext_isCircuit {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E) (h : ∀ ⦃C⦄, C ⊆ M₁.E → (M₁.IsCircuit C ↔ M₂.IsCircuit C)) : M₁ = M₂ := by have h' {C} : M₁.IsCircuit C ↔ M₂.IsCircuit C := (em (C ⊆ M₁.E)).elim (h (C := C)) (fun hC ↦ iff_of_false (mt IsCircuit.subset_ground hC) (mt IsCircuit.subset_ground fun hss ↦ hC (hss.trans_eq hE.symm))) refine ext_indep hE fun I hI ↦ ?_ simp_rw [indep_iff_forall_subset_not_isCircuit hI, h', indep_iff_forall_subset_not_isCircuit (hI.trans_eq hE)] /-- A stronger version of `Matroid.ext_isCircuit`: two matroids on the same ground set are equal if no circuit of one is independent in the other. -/ lemma ext_isCircuit_not_indep {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E) (h₁ : ∀ C, M₁.IsCircuit C → ¬ M₂.Indep C) (h₂ : ∀ C, M₂.IsCircuit C → ¬ M₁.Indep C) : M₁ = M₂ := by refine ext_isCircuit hE fun C hCE ↦ ⟨fun hC ↦ ?_, fun hC ↦ ?_⟩ · obtain ⟨C', hC'C, hC'⟩ := ((not_indep_iff (by rwa [← hE])).1 (h₁ C hC)).exists_isCircuit_subset rwa [← hC.eq_of_not_indep_subset (h₂ C' hC') hC'C] obtain ⟨C', hC'C, hC'⟩ := ((not_indep_iff hCE).1 (h₂ C hC)).exists_isCircuit_subset rwa [← hC.eq_of_not_indep_subset (h₁ C' hC') hC'C] lemma ext_iff_isCircuit {M₁ M₂ : Matroid α} : M₁ = M₂ ↔ M₁.E = M₂.E ∧ ∀ C, M₁.IsCircuit C ↔ M₂.IsCircuit C := ⟨fun h ↦ by simp [h], fun h ↦ ext_isCircuit h.1 fun C hC ↦ h.2 (C := C)⟩ section Elimination /-! ### Circuit Elimination -/ variable {ι : Type*} {J C₀ C₁ C₂ : Set α} /-- A version of `Matroid.IsCircuit.strong_multi_elimination` that is phrased using insertion. -/ lemma IsCircuit.strong_multi_elimination_insert (x : ι → α) (I : ι → Set α) (z : α) (hxI : ∀ i, x i ∉ I i) (hC : ∀ i, M.IsCircuit (insert (x i) (I i))) (hJx : M.IsCircuit (J ∪ range x)) (hzJ : z ∈ J) (hzI : ∀ i, z ∉ I i) : ∃ C' ⊆ J ∪ ⋃ i, I i, M.IsCircuit C' ∧ z ∈ C' := by -- we may assume that `ι` is nonempty, and it suffices to show that -- `z` is spanned by the union of the `I` and `J \ {z}`. obtain hι | hι := isEmpty_or_nonempty ι · exact ⟨J, by simp, by simpa [range_eq_empty] using hJx, hzJ⟩ suffices hcl : z ∈ M.closure ((⋃ i, I i) ∪ (J \ {z})) by rw [mem_closure_iff_exists_isCircuit (by simp [hzI])] at hcl obtain ⟨C', hC'ss, hC', hzC'⟩ := hcl refine ⟨C', ?_, hC', hzC'⟩ rwa [union_comm, ← insert_union, insert_diff_singleton, insert_eq_of_mem hzJ] at hC'ss have hC' (i) : M.closure (I i) = M.closure (insert (x i) (I i)) := by simpa [diff_singleton_eq_self (hxI _)] using (hC i).closure_diff_singleton_eq (x i) -- This is true because each `I i` spans `x i` and `(range x) ∪ (J \ {z})` spans `z`. rw [closure_union_congr_left <| closure_iUnion_congr _ _ hC', iUnion_insert_eq_range_union_iUnion, union_right_comm] refine mem_of_mem_of_subset (hJx.mem_closure_diff_singleton_of_mem (.inl hzJ)) (M.closure_subset_closure (subset_trans ?_ subset_union_left)) rw [union_diff_distrib, union_comm] exact union_subset_union_left _ diff_subset /-- A generalization of the strong circuit elimination axiom `Matroid.IsCircuit.strong_elimination` to an infinite collection of circuits. It states that, given a circuit `C₀`, a arbitrary collection `C : ι → Set α` of circuits, an element `x i` of `C₀ ∩ C i` for each `i`, and an element `z ∈ C₀` outside all the `C i`, the union of `C₀` and the `C i` contains a circuit containing `z` but none of the `x i`. This is one of the axioms when defining infinite matroids via circuits. TODO : A similar statement will hold even when all mentions of `z` are removed. -/ lemma IsCircuit.strong_multi_elimination (hC₀ : M.IsCircuit C₀) (x : ι → α) (C : ι → Set α) (z : α) (hC : ∀ i, M.IsCircuit (C i)) (h_mem_C₀ : ∀ i, x i ∈ C₀) (h_mem : ∀ i, x i ∈ C i) (h_unique : ∀ ⦃i i'⦄, x i ∈ C i' → i = i') (hzC₀ : z ∈ C₀) (hzC : ∀ i, z ∉ C i) : ∃ C' ⊆ (C₀ ∪ ⋃ i, C i) \ range x, M.IsCircuit C' ∧ z ∈ C' := by have hwin := IsCircuit.strong_multi_elimination_insert (M := M) x (fun i ↦ (C i \ {x i})) (J := C₀ \ range x) (z := z) (by simp) (fun i ↦ ?_) ?_ ⟨hzC₀, ?_⟩ ?_ · obtain ⟨C', hC'ss, hC', hzC'⟩ := hwin refine ⟨C', hC'ss.trans ?_, hC', hzC'⟩ refine union_subset (diff_subset_diff_left subset_union_left) (iUnion_subset fun i ↦ subset_diff.2 ⟨diff_subset.trans (subset_union_of_subset_right (subset_iUnion ..) _), ?_⟩) rw [disjoint_iff_forall_ne] rintro _ he _ ⟨j, hj, rfl⟩ rfl obtain rfl : j = i := h_unique he.1 simp at he · simpa [insert_eq_of_mem (h_mem i)] using hC i · rwa [diff_union_self, union_eq_self_of_subset_right] rintro _ ⟨i, hi, rfl⟩ exact h_mem_C₀ i · rintro ⟨i, hi, rfl⟩ exact hzC _ (h_mem i) simp only [mem_diff, mem_singleton_iff, not_and, not_not] exact fun i hzi ↦ (hzC i hzi).elim /-- A version of `Circuit.strong_multi_elimination` where the collection of circuits is a `Set (Set α)` and the distinguished elements are a `Set α`, rather than both being indexed. -/ lemma IsCircuit.strong_multi_elimination_set (hC₀ : M.IsCircuit C₀) (X : Set α) (S : Set (Set α)) (z : α) (hCS : ∀ C ∈ S, M.IsCircuit C) (hXC₀ : X ⊆ C₀) (hX : ∀ x ∈ X, ∃ C ∈ S, C ∩ X = {x}) (hzC₀ : z ∈ C₀) (hz : ∀ C ∈ S, z ∉ C) : ∃ C' ⊆ (C₀ ∪ ⋃₀ S) \ X, M.IsCircuit C' ∧ z ∈ C' := by choose! C hC using hX simp only [forall_and] at hC have hwin := hC₀.strong_multi_elimination (fun x : X ↦ x) (fun x ↦ C x) z ?_ ?_ ?_ ?_ hzC₀ ?_ · obtain ⟨C', hC'ss, hC', hz⟩ := hwin refine ⟨C', hC'ss.trans (diff_subset_diff (union_subset_union_right _ ?_) (by simp)), hC', hz⟩ simpa using fun e heX ↦ (subset_sUnion_of_mem (hC.1 e heX)) · simpa using fun e heX ↦ hCS _ <| hC.1 e heX · simpa using fun e heX ↦ hXC₀ heX · simp only [Subtype.forall, ← singleton_subset_iff (s := C _)] exact fun e heX ↦ by simp [← hC.2 e heX] · simp only [Subtype.forall, Subtype.mk.injEq] refine fun e heX f hfX hef ↦ ?_ simpa [hC.2 f hfX] using subset_inter (singleton_subset_iff.2 hef) (singleton_subset_iff.2 heX) simpa using fun e heX heC ↦ hz _ (hC.1 e heX) heC /-- The strong isCircuit elimination axiom. For any pair of distinct circuits `C₁, C₂` and all `e ∈ C₁ ∩ C₂` and `f ∈ C₁ \ C₂`, there is a circuit `C` with `f ∈ C ⊆ (C₁ ∪ C₂) \ {e}`. -/ lemma IsCircuit.strong_elimination (hC₁ : M.IsCircuit C₁) (hC₂ : M.IsCircuit C₂) (heC₁ : e ∈ C₁) (heC₂ : e ∈ C₂) (hfC₁ : f ∈ C₁) (hfC₂ : f ∉ C₂) : ∃ C ⊆ (C₁ ∪ C₂) \ {e}, M.IsCircuit C ∧ f ∈ C := by obtain ⟨C, hCs, hC, hfC⟩ := hC₁.strong_multi_elimination (fun i : Unit ↦ e) (fun _ ↦ C₂) f (by simpa) (by simpa) (by simpa) (by simp) (by simpa) (by simpa) exact ⟨C, hCs.trans (diff_subset_diff (by simp) (by simp)), hC, hfC⟩ /-- The circuit elimination axiom : for any pair of distinct circuits `C₁, C₂` and any `e`, some circuit is contained in `(C₁ ∪ C₂) \ {e}`. This is one of the axioms when defining a finitary matroid via circuits; as an axiom, it is usually stated with the extra assumption that `e ∈ C₁ ∩ C₂`. -/ lemma IsCircuit.elimination (hC₁ : M.IsCircuit C₁) (hC₂ : M.IsCircuit C₂) (h : C₁ ≠ C₂) (e : α) : ∃ C ⊆ (C₁ ∪ C₂) \ {e}, M.IsCircuit C := by have hnss : ¬ (C₁ ⊆ C₂) := fun hss ↦ h <| hC₁.eq_of_subset_isCircuit hC₂ hss obtain ⟨f, hf₁, hf₂⟩ := not_subset.1 hnss by_cases he₁ : e ∈ C₁ · by_cases he₂ : e ∈ C₂ · obtain ⟨C, hC, hC', -⟩ := hC₁.strong_elimination hC₂ he₁ he₂ hf₁ hf₂ exact ⟨C, hC, hC'⟩ exact ⟨C₂, subset_diff_singleton subset_union_right he₂, hC₂⟩ exact ⟨C₁, subset_diff_singleton subset_union_left he₁, hC₁⟩ end Elimination /-! ### Finitary Matroids -/ section Finitary lemma IsCircuit.finite [Finitary M] (hC : M.IsCircuit C) : C.Finite := by have hi := hC.dep.not_indep rw [indep_iff_forall_finite_subset_indep] at hi; push_neg at hi obtain ⟨J, hJC, hJfin, hJ⟩ := hi rwa [← hC.eq_of_not_indep_subset hJ hJC] lemma finitary_iff_forall_isCircuit_finite : M.Finitary ↔ ∀ C, M.IsCircuit C → C.Finite := by refine ⟨fun _ _ ↦ IsCircuit.finite, fun h ↦ ⟨fun I hI ↦ indep_iff_not_dep.2 ⟨fun hd ↦ ?_,fun x hx ↦ ?_⟩⟩⟩ · obtain ⟨C, hCI, hC⟩ := hd.exists_isCircuit_subset exact hC.dep.not_indep <| hI _ hCI (h C hC) simpa using (hI {x} (by simpa) (finite_singleton _)).subset_ground /-- In a finitary matroid, every element spanned by a set `X` is in fact spanned by a finite independent subset of `X`. -/ lemma exists_mem_finite_closure_of_mem_closure [M.Finitary] (he : e ∈ M.closure X) : ∃ I ⊆ X, I.Finite ∧ M.Indep I ∧ e ∈ M.closure I := by by_cases heY : e ∈ X · obtain ⟨J, hJ⟩ := M.exists_isBasis {e} exact ⟨J, hJ.subset.trans (by simpa), (finite_singleton e).subset hJ.subset, hJ.indep, by simpa using hJ.subset_closure⟩ obtain ⟨C, hCs, hC, heC⟩ := exists_isCircuit_of_mem_closure he heY exact ⟨C \ {e}, by simpa, hC.finite.diff, hC.diff_singleton_indep heC, hC.mem_closure_diff_singleton_of_mem heC⟩ /-- In a finitary matroid, each finite set `X` spanned by a set `Y` is in fact spanned by a finite independent subset of `Y`. -/ lemma exists_subset_finite_closure_of_subset_closure [M.Finitary] (hX : X.Finite) (hXY : X ⊆ M.closure Y) : ∃ I ⊆ Y, I.Finite ∧ M.Indep I ∧ X ⊆ M.closure I := by suffices aux : ∃ T ⊆ Y, T.Finite ∧ X ⊆ M.closure T by obtain ⟨T, hT, hTfin, hXT⟩ := aux obtain ⟨I, hI⟩ := M.exists_isBasis' T exact ⟨_, hI.subset.trans hT, hTfin.subset hI.subset, hI.indep, by rwa [hI.closure_eq_closure]⟩ refine Finite.induction_on_subset X hX ⟨∅, by simp⟩ (fun {e Z} heX _ heZ ⟨T, hTY, hTfin, hT⟩ ↦ ?_) obtain ⟨S, hSY, hSfin, -, heS⟩ := exists_mem_finite_closure_of_mem_closure (hXY heX) exact ⟨S ∪ T, union_subset hSY hTY, hSfin.union hTfin, insert_subset (M.closure_mono subset_union_left heS) (hT.trans (M.closure_mono subset_union_right))⟩ end Finitary /-! ### IsCocircuits -/ section IsCocircuit variable {K B : Set α} /-- A cocircuit is a circuit of the dual matroid, or equivalently the complement of a hyperplane. -/ abbrev IsCocircuit (M : Matroid α) (K : Set α) : Prop := M✶.IsCircuit K lemma isCocircuit_def : M.IsCocircuit K ↔ M✶.IsCircuit K := Iff.rfl lemma IsCocircuit.isCircuit (hK : M.IsCocircuit K) : M✶.IsCircuit K := hK lemma IsCircuit.isCocircuit (hC : M.IsCircuit C) : M✶.IsCocircuit C := by rwa [isCocircuit_def, dual_dual] lemma IsCocircuit.nonempty (hC : M.IsCocircuit C) : C.Nonempty := hC.isCircuit.nonempty @[aesop unsafe 10% (rule_sets := [Matroid])] lemma IsCocircuit.subset_ground (hC : M.IsCocircuit C) : C ⊆ M.E := hC.isCircuit.subset_ground @[simp] lemma dual_isCocircuit_iff : M✶.IsCocircuit C ↔ M.IsCircuit C := by rw [isCocircuit_def, dual_dual] lemma coindep_iff_forall_subset_not_isCocircuit : M.Coindep X ↔ (∀ K, K ⊆ X → ¬M.IsCocircuit K) ∧ X ⊆ M.E := indep_iff_forall_subset_not_isCircuit' /-- A cocircuit is a minimal set that intersects every base. -/ lemma isCocircuit_iff_minimal : M.IsCocircuit K ↔ Minimal (fun X ↦ ∀ B, M.IsBase B → (X ∩ B).Nonempty) K := by have aux : M✶.Dep = fun X ↦ (∀ B, M.IsBase B → (X ∩ B).Nonempty) ∧ X ⊆ M.E := by ext; apply dual_dep_iff_forall rw [isCocircuit_def, isCircuit_def, aux, iff_comm] refine minimal_iff_minimal_of_imp_of_forall (fun _ h ↦ h.1) fun X hX ↦ ⟨X ∩ M.E, inter_subset_left, fun B hB ↦ ?_, inter_subset_right⟩ rw [inter_assoc, inter_eq_self_of_subset_right hB.subset_ground] exact hX B hB /-- A cocircuit is a minimal set whose complement is nonspanning. -/ lemma isCocircuit_iff_minimal_compl_nonspanning : M.IsCocircuit K ↔ Minimal (fun X ↦ ¬ M.Spanning (M.E \ X)) K := by convert isCocircuit_iff_minimal with K simp_rw [spanning_iff_exists_isBase_subset (S := M.E \ K), not_exists, subset_diff, not_and, not_disjoint_iff_nonempty_inter, ← and_imp, and_iff_left_of_imp IsBase.subset_ground, inter_comm K] /-- For an element `e` of a base `B`, the complement of the closure of `B \ {e}` is a cocircuit. -/ lemma IsBase.compl_closure_diff_singleton_isCocircuit (hB : M.IsBase B) (he : e ∈ B) : M.IsCocircuit (M.E \ M.closure (B \ {e})) := by rw [isCocircuit_iff_minimal_compl_nonspanning, minimal_subset_iff, diff_diff_cancel_left (M.closure_subset_ground _), closure_spanning_iff (diff_subset.trans hB.subset_ground)] have hB' := (isBase_iff_minimal_spanning.1 hB) refine ⟨fun hsp ↦ hB'.notMem_of_prop_diff_singleton hsp he, fun X hX hXss ↦ hXss.antisymm' ?_⟩ rw [diff_subset_comm] refine fun f hf ↦ by_contra fun fcl ↦ hX ?_ rw [subset_diff] at hXss suffices hsp : M.IsBase (insert f (B \ {e})) by refine hsp.spanning.superset <| insert_subset hf <| (M.subset_closure _ (diff_subset.trans hB.subset_ground)).trans ?_ rw [subset_diff, and_iff_left hXss.2.symm] apply closure_subset_ground exact hB.exchange_base_of_notMem_closure he fcl /-- A version of `Matroid.isCocircuit_iff_minimal_compl_nonspanning` with a support assumption in the minimality. -/ lemma isCocircuit_iff_minimal_compl_nonspanning' : M.IsCocircuit K ↔ Minimal (fun X ↦ ¬ M.Spanning (M.E \ X) ∧ X ⊆ M.E) K := by rw [isCocircuit_iff_minimal_compl_nonspanning] exact minimal_iff_minimal_of_imp_of_forall (fun _ h ↦ h.1) (fun X hX ↦ ⟨X ∩ M.E, inter_subset_left, by rwa [diff_inter_self_eq_diff], inter_subset_right⟩) /-- A cocircuit and a circuit cannot meet in exactly one element. -/ lemma IsCircuit.inter_isCocircuit_ne_singleton (hC : M.IsCircuit C) (hK : M.IsCocircuit K) : C ∩ K ≠ {e} := by intro he have heC : e ∈ C := (he.symm.subset rfl).1 simp_rw [isCocircuit_iff_minimal_compl_nonspanning, minimal_iff_forall_ssubset, not_not] at hK have' hKe := hK.2 (t := K \ {e}) (diff_singleton_ssubset.2 (he.symm.subset rfl).2) apply hK.1 rw [spanning_iff_ground_subset_closure] nth_rw 1 [← hKe.closure_eq, diff_diff_eq_sdiff_union] · refine (M.closure_subset_closure (subset_union_left (t := C))).trans ?_ rw [union_assoc, singleton_union, insert_eq_of_mem heC, ← closure_union_congr_right (hC.closure_diff_singleton_eq e), union_eq_self_of_subset_right] rw [← he, diff_self_inter] exact diff_subset_diff_left hC.subset_ground rw [← he] exact inter_subset_left.trans hC.subset_ground lemma IsCircuit.isCocircuit_inter_nontrivial (hC : M.IsCircuit C) (hK : M.IsCocircuit K) (hCK : (C ∩ K).Nonempty) : (C ∩ K).Nontrivial := by obtain ⟨e, heCK⟩ := hCK rw [nontrivial_iff_ne_singleton heCK] exact hC.inter_isCocircuit_ne_singleton hK lemma IsCircuit.isCocircuit_disjoint_or_nontrivial_inter (hC : M.IsCircuit C) (hK : M.IsCocircuit K) : Disjoint C K ∨ (C ∩ K).Nontrivial := by rw [or_iff_not_imp_left, disjoint_iff_inter_eq_empty, ← ne_eq, ← nonempty_iff_ne_empty] exact hC.isCocircuit_inter_nontrivial hK lemma dual_rankPos_iff_exists_isCircuit : M✶.RankPos ↔ ∃ C, M.IsCircuit C := by rw [rankPos_iff, dual_isBase_iff, diff_empty, not_iff_comm, not_exists, ← ground_indep_iff_isBase, indep_iff_forall_subset_not_isCircuit] exact ⟨fun h C _ ↦ h C, fun h C hC ↦ h C hC.subset_ground hC⟩ lemma IsCircuit.dual_rankPos (hC : M.IsCircuit C) : M✶.RankPos := dual_rankPos_iff_exists_isCircuit.mpr ⟨C, hC⟩ lemma exists_isCircuit [RankPos M✶] : ∃ C, M.IsCircuit C := dual_rankPos_iff_exists_isCircuit.1 (by assumption) lemma rankPos_iff_exists_isCocircuit : M.RankPos ↔ ∃ K, M.IsCocircuit K := by rw [← dual_dual M, dual_rankPos_iff_exists_isCircuit, dual_dual M] /-- The fundamental cocircuit for `B` and `e`: that is, the unique cocircuit `K` of `M` for which `K ∩ B = {e}`. Should be used when `B` is a base and `e ∈ B`. Has the junk value `{e}` if `e ∉ B` or `e ∉ M.E`. -/ def fundCocircuit (M : Matroid α) (e : α) (B : Set α) := M✶.fundCircuit e (M✶.E \ B) lemma fundCocircuit_isCocircuit (he : e ∈ B) (hB : M.IsBase B) : M.IsCocircuit <| M.fundCocircuit e B := by apply hB.compl_isBase_dual.indep.fundCircuit_isCircuit _ (by simp [he]) rw [hB.compl_isBase_dual.closure_eq, dual_ground] exact hB.subset_ground he lemma mem_fundCocircuit (M : Matroid α) (e : α) (B : Set α) : e ∈ M.fundCocircuit e B := mem_insert _ _ lemma fundCocircuit_subset_insert_compl (M : Matroid α) (e : α) (B : Set α) : M.fundCocircuit e B ⊆ insert e (M.E \ B) := fundCircuit_subset_insert .. lemma fundCocircuit_inter_eq (M : Matroid α) {B : Set α} (he : e ∈ B) : (M.fundCocircuit e B) ∩ B = {e} := by refine subset_antisymm ?_ (singleton_subset_iff.2 ⟨M.mem_fundCocircuit _ _, he⟩) refine (inter_subset_inter_left _ (M.fundCocircuit_subset_insert_compl _ _)).trans ?_ simp +contextual /-- The fundamental cocircuit of `X` and `e` has the junk value `{e}` if `e ∉ M.E` -/ lemma fundCocircuit_eq_of_notMem_ground (X : Set α) (he : e ∉ M.E) : M.fundCocircuit e X = {e} := by rwa [fundCocircuit, fundCircuit_eq_of_notMem_ground] @[deprecated (since := "2025-05-23")] alias fundCocircuit_eq_of_not_mem_ground := fundCocircuit_eq_of_notMem_ground /-- The fundamental cocircuit of `X` and `e` has the junk value `{e}` if `e ∉ X` -/ lemma fundCocircuit_eq_of_notMem (M : Matroid α) (heX : e ∉ X) : M.fundCocircuit e X = {e} := by by_cases he : e ∈ M.E · rw [fundCocircuit, fundCircuit_eq_of_mem] exact ⟨he, heX⟩ rw [fundCocircuit_eq_of_notMem_ground _ he] @[deprecated (since := "2025-05-23")] alias fundCocircuit_eq_of_not_mem := fundCocircuit_eq_of_notMem /-- For every element `e` of an independent set `I`, there is a cocircuit whose intersection with `I` is `{e}`. -/ lemma Indep.exists_isCocircuit_inter_eq_mem (hI : M.Indep I) (heI : e ∈ I) : ∃ K, M.IsCocircuit K ∧ K ∩ I = {e} := by obtain ⟨B, hB, hIB⟩ := hI.exists_isBase_superset refine ⟨M.fundCocircuit e B, fundCocircuit_isCocircuit (hIB heI) hB, ?_⟩ rw [subset_antisymm_iff, subset_inter_iff, singleton_subset_iff, and_iff_right (mem_fundCocircuit _ _ _), singleton_subset_iff, and_iff_left heI, ← M.fundCocircuit_inter_eq (hIB heI)] exact inter_subset_inter_right _ hIB /-- Fundamental circuits and cocircuits of a base `B` play dual roles; `e` belongs to the fundamental cocircuit for `B` and `f` if and only if `f` belongs to the fundamental circuit for `e` and `B`. This statement isn't so reasonable unless `f ∈ B` and `e ∉ B`, but holds due to junk values even without these assumptions. -/ lemma IsBase.mem_fundCocircuit_iff_mem_fundCircuit {e f : α} (hB : M.IsBase B) : e ∈ M.fundCocircuit f B ↔ f ∈ M.fundCircuit e B := by -- By symmetry and duality, it suffices to show the implication in one direction. suffices aux : ∀ {N : Matroid α} {B' : Set α} (hB' : N.IsBase B') {e f}, e ∈ N.fundCocircuit f B' → f ∈ N.fundCircuit e B' from ⟨fun h ↦ aux hB h, fun h ↦ aux hB.compl_isBase_dual <| by simpa [fundCocircuit, inter_eq_self_of_subset_right hB.subset_ground]⟩ clear! B M e f intro M B hB e f he -- discharge the various degenerate cases. obtain rfl | hne := eq_or_ne e f · simp [mem_fundCircuit] have hB' : M✶.IsBase (M✶.E \ B) := hB.compl_isBase_dual obtain hfE | hfE := em' <| f ∈ M.E · rw [fundCocircuit, fundCircuit_eq_of_notMem_ground (by simpa)] at he contradiction obtain hfB | hfB := em' <| f ∈ B · rw [fundCocircuit, fundCircuit_eq_of_mem (by simp [hfE, hfB])] at he contradiction obtain ⟨heE, heB⟩ : e ∈ M.E \ B := by simpa [hne] using (M.fundCocircuit_subset_insert_compl f B) he -- Use basis exchange to argue the equivalence. rw [fundCocircuit, hB'.indep.mem_fundCircuit_iff (by rwa [hB'.closure_eq]) (by simp [hfB])] at he rw [hB.indep.mem_fundCircuit_iff (by rwa [hB.closure_eq]) heB] have hB' : M.IsBase (M.E \ (insert f (M✶.E \ B) \ {e})) := (hB'.exchange_isBase_of_indep' ⟨heE, heB⟩ (by simp [hfE, hfB]) he).compl_isBase_of_dual refine hB'.indep.subset ?_ simp only [dual_ground, diff_singleton_subset_iff] rw [diff_diff_right, inter_eq_self_of_subset_right (by simpa), union_singleton, insert_comm, ← union_singleton (s := M.E \ B), ← diff_diff, diff_diff_cancel_left hB.subset_ground] simp [hfB] end IsCocircuit end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Closure.lean
import Mathlib.Combinatorics.Matroid.Map import Mathlib.Order.Closure import Mathlib.Order.CompleteLatticeIntervals /-! # Matroid Closure A flat (`IsFlat`) of a matroid `M` is a combinatorial analogue of a subspace of a vector space, and is defined to be a subset `F` of the ground set of `M` such that for each basis `I` for `F`, every set having `I` as a basis is contained in `F`. The *closure* of a set `X` in a matroid `M` is the intersection of all flats of `M` containing `X`. This is a combinatorial analogue of the linear span of a set of vectors. For `M : Matroid α`, this file defines a predicate `M.IsFlat : Set α → Prop` and a function `M.closure : Set α → Set α` corresponding to these notions, and develops API for the latter. API for `Matroid.IsFlat` will appear in another file; we include the definition here since it is used in the definition of `Matroid.closure`. We also define a predicate `Spanning`, to describe a set whose closure is the entire ground set. ## Main definitions * For `M : Matroid α` and `F : Set α`, `M.IsFlat F` means that `F` is a isFlat of `M`. * For `M : Matroid α` and `X : Set α`, `M.closure X` is the closure of `X` in `M`. * For `M : Matroid α` and `X : ↑(Iic M.E)` (i.e. a bundled subset of `M.E`), `M.subtypeClosure X` is the closure of `X`, viewed as a term in `↑(Iic M.E)`. This is a `ClosureOperator` on `↑(Iic M.E)`. * For `M : Matroid α` and `S ⊆ M.E`, `M.Spanning S` means that `S` has closure equal to `M.E`, or equivalently that `S` contains a isBase of `M`. ## Implementation details If `X : Set α` satisfies `X ⊆ M.E`, then it is clear how `M.closure X` should be defined. But `M.closure X` also needs to be defined for all `X : Set α`, so a convention is needed for how it handles sets containing junk elements outside `M.E`. All such choices come with tradeoffs. Provided that `M.closure X` has already been defined for `X ⊆ M.E`, the two best candidates for extending it to all `X` seem to be: (1) The function for which `M.closure X = M.closure (X ∩ M.E)` for all `X : Set α` (2) The function for which `M.closure X = M.closure (X ∩ M.E) ∪ X` for all `X : Set α` For both options, the function `closure` is monotone and idempotent with no assumptions on `X`. Choice (1) has the advantage that `M.closure X ⊆ M.E` holds for all `X` without the assumption that `X ⊆ M.E`, which is very nice for `aesop_mat`. It is also fairly convenient to rewrite `M.closure X` to `M.closure (X ∩ M.E)` when one needs to work with a subset of the ground set. Its disadvantage is that the statement `X ⊆ M.closure X` is only true provided that `X ⊆ M.E`. Choice (2) has the reverse property: we would have `X ⊆ M.closure X` for all `X`, but the condition `M.closure X ⊆ M.E` requires `X ⊆ M.E` to hold. It has a couple of other advantages too: it is actually the closure function of a matroid on `α` with ground set `univ` (specifically, the direct sum of `M` and a free matroid on `M.Eᶜ`), and because of this, it is an example of a `ClosureOperator` on `α`, which in turn gives access to nice existing API for both `ClosureOperator` and `GaloisInsertion`. This also relates to flats; `F ⊆ M.E ∧ ClosureOperator.IsClosed F` is equivalent to `M.IsFlat F`. (All of this fails for choice (1), since `X ⊆ M.closure X` is required for a `ClosureOperator`, but isn't true for non-subsets of `M.E`) The API that choice (2) would offer is very beguiling, but after extensive experimentation in an external repo, it seems that (1) is far less rough around the edges in practice, so we go with (1). It may be helpful at some point to define a primed version `Matroid.closure' : ClosureOperator (Set α)` corresponding to choice (2). Failing that, the `ClosureOperator`/`GaloisInsertion` API is still available on the subtype `↑(Iic M.E)` via `Matroid.SubtypeClosure`, albeit less elegantly. ## Naming conventions In lemma names, the words `spanning` and `isFlat` are used as suffixes, for instance we have `ground_spanning` rather than `spanning_ground`. -/ assert_not_exists Field open Set namespace Matroid variable {ι α : Type*} {M : Matroid α} {F X Y : Set α} {e f : α} section IsFlat /-- A flat is a maximal set having a given basis -/ @[mk_iff] structure IsFlat (M : Matroid α) (F : Set α) : Prop where subset_of_isBasis_of_isBasis : ∀ ⦃I X⦄, M.IsBasis I F → M.IsBasis I X → X ⊆ F subset_ground : F ⊆ M.E attribute [aesop unsafe 20% (rule_sets := [Matroid])] IsFlat.subset_ground @[simp] lemma ground_isFlat (M : Matroid α) : M.IsFlat M.E := ⟨fun _ _ _ ↦ IsBasis.subset_ground, Subset.rfl⟩ lemma IsFlat.iInter {ι : Type*} [Nonempty ι] {Fs : ι → Set α} (hFs : ∀ i, M.IsFlat (Fs i)) : M.IsFlat (⋂ i, Fs i) := by refine ⟨fun I X hI hIX ↦ subset_iInter fun i ↦ ?_, (iInter_subset _ (Classical.arbitrary _)).trans (hFs _).subset_ground⟩ obtain ⟨J, hIJ, hJ⟩ := hI.indep.subset_isBasis_of_subset (hI.subset.trans (iInter_subset _ i)) refine subset_union_right.trans ((hFs i).1 (X := Fs i ∪ X) hIJ ?_) convert hIJ.isBasis_union (hIX.isBasis_union_of_subset hIJ.indep hJ) using 1 rw [← union_assoc, union_eq_self_of_subset_right hIJ.subset] /-- The property of being a flat gives rise to a `ClosureOperator` on the subsets of `M.E`, in which the `IsClosed` sets correspond to flats. (We can't define such an operator on all of `Set α`, since this would incorrectly force `univ` to always be a flat.) -/ def subtypeClosure (M : Matroid α) : ClosureOperator (Iic M.E) := ClosureOperator.ofCompletePred (fun F ↦ M.IsFlat F.1) fun s hs ↦ by obtain (rfl | hne) := s.eq_empty_or_nonempty · simp have _ := hne.coe_sort convert IsFlat.iInter (M := M) (Fs := fun (F : s) ↦ F.1.1) (fun F ↦ hs F.1 F.2) ext aesop lemma isFlat_iff_isClosed : M.IsFlat F ↔ ∃ h : F ⊆ M.E, M.subtypeClosure.IsClosed ⟨F, h⟩ := by simpa [subtypeClosure] using IsFlat.subset_ground lemma isClosed_iff_isFlat {F : Iic M.E} : M.subtypeClosure.IsClosed F ↔ M.IsFlat F := by simp [subtypeClosure] end IsFlat /-- The closure of `X ⊆ M.E` is the intersection of all the flats of `M` containing `X`. A set `X` that doesn't satisfy `X ⊆ M.E` has the junk value `M.closure X := M.closure (X ∩ M.E)`. -/ def closure (M : Matroid α) (X : Set α) : Set α := ⋂₀ {F | M.IsFlat F ∧ X ∩ M.E ⊆ F} lemma closure_def (M : Matroid α) (X : Set α) : M.closure X = ⋂₀ {F | M.IsFlat F ∧ X ∩ M.E ⊆ F} := rfl lemma closure_def' (M : Matroid α) (X : Set α) (hX : X ⊆ M.E := by aesop_mat) : M.closure X = ⋂₀ {F | M.IsFlat F ∧ X ⊆ F} := by rw [closure, inter_eq_self_of_subset_left hX] instance : Nonempty {F | M.IsFlat F ∧ X ∩ M.E ⊆ F} := ⟨M.E, M.ground_isFlat, inter_subset_right⟩ lemma closure_eq_subtypeClosure (M : Matroid α) (X : Set α) : M.closure X = M.subtypeClosure ⟨X ∩ M.E, inter_subset_right⟩ := by suffices ∀ (x : α), (∀ (t : Set α), M.IsFlat t → X ∩ M.E ⊆ t → x ∈ t) ↔ (x ∈ M.E ∧ ∀ a ⊆ M.E, X ∩ M.E ⊆ a → M.IsFlat a → x ∈ a) by simpa [closure, subtypeClosure, Set.ext_iff] exact fun x ↦ ⟨fun h ↦ ⟨h _ M.ground_isFlat inter_subset_right, fun F _ hXF hF ↦ h F hF hXF⟩, fun ⟨_, h⟩ F hF hXF ↦ h F hF.subset_ground hXF hF⟩ @[aesop unsafe 10% (rule_sets := [Matroid])] lemma closure_subset_ground (M : Matroid α) (X : Set α) : M.closure X ⊆ M.E := sInter_subset_of_mem ⟨M.ground_isFlat, inter_subset_right⟩ @[simp] lemma ground_subset_closure_iff : M.E ⊆ M.closure X ↔ M.closure X = M.E := by simp [M.closure_subset_ground X, subset_antisymm_iff] @[simp] lemma closure_inter_ground (M : Matroid α) (X : Set α) : M.closure (X ∩ M.E) = M.closure X := by simp_rw [closure_def, inter_assoc, inter_self] lemma inter_ground_subset_closure (M : Matroid α) (X : Set α) : X ∩ M.E ⊆ M.closure X := by simp_rw [closure_def, subset_sInter_iff]; simp lemma mem_closure_iff_forall_mem_isFlat (X : Set α) (hX : X ⊆ M.E := by aesop_mat) : e ∈ M.closure X ↔ ∀ F, M.IsFlat F → X ⊆ F → e ∈ F := by simp_rw [M.closure_def' X, mem_sInter, mem_setOf, and_imp] lemma subset_closure_iff_forall_subset_isFlat (X : Set α) (hX : X ⊆ M.E := by aesop_mat) : Y ⊆ M.closure X ↔ ∀ F, M.IsFlat F → X ⊆ F → Y ⊆ F := by simp_rw [M.closure_def' X, subset_sInter_iff, mem_setOf, and_imp] lemma subset_closure (M : Matroid α) (X : Set α) (hX : X ⊆ M.E := by aesop_mat) : X ⊆ M.closure X := by simp [M.closure_def' X, subset_sInter_iff] lemma IsFlat.closure (hF : M.IsFlat F) : M.closure F = F := (sInter_subset_of_mem (by simpa)).antisymm (M.subset_closure F) variable (X) in @[simp] lemma isFlat_closure : M.IsFlat (M.closure X) := by rw [closure, sInter_eq_iInter]; exact .iInter (·.2.1) lemma isFlat_iff_closure_eq : M.IsFlat F ↔ M.closure F = F := ⟨(·.closure), (· ▸ isFlat_closure F)⟩ @[simp] lemma closure_ground (M : Matroid α) : M.closure M.E = M.E := (M.closure_subset_ground M.E).antisymm (M.subset_closure M.E) @[simp] lemma closure_univ (M : Matroid α) : M.closure univ = M.E := by rw [← closure_inter_ground, univ_inter, closure_ground] @[gcongr] lemma closure_subset_closure (M : Matroid α) (h : X ⊆ Y) : M.closure X ⊆ M.closure Y := subset_sInter (fun _ h' ↦ sInter_subset_of_mem ⟨h'.1, subset_trans (inter_subset_inter_left _ h) h'.2⟩) lemma closure_mono (M : Matroid α) : Monotone M.closure := fun _ _ ↦ M.closure_subset_closure @[simp] lemma closure_closure (M : Matroid α) (X : Set α) : M.closure (M.closure X) = M.closure X := (M.subset_closure _).antisymm' (subset_sInter (fun F hF ↦ (closure_subset_closure _ (sInter_subset_of_mem hF)).trans hF.1.closure.subset)) lemma closure_subset_closure_of_subset_closure (hXY : X ⊆ M.closure Y) : M.closure X ⊆ M.closure Y := (M.closure_subset_closure hXY).trans_eq (M.closure_closure Y) lemma closure_subset_closure_iff_subset_closure (hX : X ⊆ M.E := by aesop_mat) : M.closure X ⊆ M.closure Y ↔ X ⊆ M.closure Y := ⟨(M.subset_closure X).trans, closure_subset_closure_of_subset_closure⟩ lemma subset_closure_of_subset (M : Matroid α) (hXY : X ⊆ Y) (hY : Y ⊆ M.E := by aesop_mat) : X ⊆ M.closure Y := hXY.trans (M.subset_closure Y) lemma subset_closure_of_subset' (M : Matroid α) (hXY : X ⊆ Y) (hX : X ⊆ M.E := by aesop_mat) : X ⊆ M.closure Y := by rw [← closure_inter_ground]; exact M.subset_closure_of_subset (subset_inter hXY hX) lemma exists_of_closure_ssubset (hXY : M.closure X ⊂ M.closure Y) : ∃ e ∈ Y, e ∉ M.closure X := by by_contra! hcon exact hXY.not_subset (M.closure_subset_closure_of_subset_closure hcon) lemma mem_closure_of_mem (M : Matroid α) (h : e ∈ X) (hX : X ⊆ M.E := by aesop_mat) : e ∈ M.closure X := (M.subset_closure X) h lemma mem_closure_of_mem' (M : Matroid α) (heX : e ∈ X) (h : e ∈ M.E := by aesop_mat) : e ∈ M.closure X := by rw [← closure_inter_ground] exact M.mem_closure_of_mem ⟨heX, h⟩ lemma notMem_of_mem_diff_closure (he : e ∈ M.E \ M.closure X) : e ∉ X := fun heX ↦ he.2 <| M.mem_closure_of_mem' heX he.1 @[deprecated (since := "2025-05-23")] alias not_mem_of_mem_diff_closure := notMem_of_mem_diff_closure @[aesop unsafe 10% (rule_sets := [Matroid])] lemma mem_ground_of_mem_closure (he : e ∈ M.closure X) : e ∈ M.E := (M.closure_subset_ground _) he lemma closure_iUnion_closure_eq_closure_iUnion (M : Matroid α) (Xs : ι → Set α) : M.closure (⋃ i, M.closure (Xs i)) = M.closure (⋃ i, Xs i) := by simp_rw [closure_eq_subtypeClosure, iUnion_inter, Subtype.coe_inj] convert M.subtypeClosure.closure_iSup_closure (fun i ↦ ⟨Xs i ∩ M.E, inter_subset_right⟩) <;> simp [← iUnion_inter, subtypeClosure] lemma closure_iUnion_congr (Xs Ys : ι → Set α) (h : ∀ i, M.closure (Xs i) = M.closure (Ys i)) : M.closure (⋃ i, Xs i) = M.closure (⋃ i, Ys i) := by simp [h, ← M.closure_iUnion_closure_eq_closure_iUnion] lemma closure_biUnion_closure_eq_closure_sUnion (M : Matroid α) (Xs : Set (Set α)) : M.closure (⋃ X ∈ Xs, M.closure X) = M.closure (⋃₀ Xs) := by rw [sUnion_eq_iUnion, biUnion_eq_iUnion, closure_iUnion_closure_eq_closure_iUnion] lemma closure_biUnion_closure_eq_closure_biUnion (M : Matroid α) (Xs : ι → Set α) (A : Set ι) : M.closure (⋃ i ∈ A, M.closure (Xs i)) = M.closure (⋃ i ∈ A, Xs i) := by rw [biUnion_eq_iUnion, M.closure_iUnion_closure_eq_closure_iUnion, biUnion_eq_iUnion] lemma closure_biUnion_congr (M : Matroid α) (Xs Ys : ι → Set α) (A : Set ι) (h : ∀ i ∈ A, M.closure (Xs i) = M.closure (Ys i)) : M.closure (⋃ i ∈ A, Xs i) = M.closure (⋃ i ∈ A, Ys i) := by rw [← closure_biUnion_closure_eq_closure_biUnion, iUnion₂_congr h, closure_biUnion_closure_eq_closure_biUnion] lemma closure_closure_union_closure_eq_closure_union (M : Matroid α) (X Y : Set α) : M.closure (M.closure X ∪ M.closure Y) = M.closure (X ∪ Y) := by rw [eq_comm, union_eq_iUnion, ← closure_iUnion_closure_eq_closure_iUnion, union_eq_iUnion] simp_rw [Bool.cond_eq_ite, apply_ite] @[simp] lemma closure_union_closure_right_eq (M : Matroid α) (X Y : Set α) : M.closure (X ∪ M.closure Y) = M.closure (X ∪ Y) := by rw [← closure_closure_union_closure_eq_closure_union, closure_closure, closure_closure_union_closure_eq_closure_union] @[simp] lemma closure_union_closure_left_eq (M : Matroid α) (X Y : Set α) : M.closure (M.closure X ∪ Y) = M.closure (X ∪ Y) := by rw [← closure_closure_union_closure_eq_closure_union, closure_closure, closure_closure_union_closure_eq_closure_union] @[simp] lemma closure_insert_closure_eq_closure_insert (M : Matroid α) (e : α) (X : Set α) : M.closure (insert e (M.closure X)) = M.closure (insert e X) := by simp_rw [← singleton_union, closure_union_closure_right_eq] lemma closure_union_congr_left {X' : Set α} (h : M.closure X = M.closure X') : M.closure (X ∪ Y) = M.closure (X' ∪ Y) := by rw [← M.closure_union_closure_left_eq, h, M.closure_union_closure_left_eq] lemma closure_union_congr_right {Y' : Set α} (h : M.closure Y = M.closure Y') : M.closure (X ∪ Y) = M.closure (X ∪ Y') := by rw [← M.closure_union_closure_right_eq, h, M.closure_union_closure_right_eq] lemma closure_insert_congr_right (h : M.closure X = M.closure Y) : M.closure (insert e X) = M.closure (insert e Y) := by simp [← union_singleton, closure_union_congr_left h] @[simp] lemma closure_union_closure_empty_eq (M : Matroid α) (X : Set α) : M.closure X ∪ M.closure ∅ = M.closure X := union_eq_self_of_subset_right (M.closure_subset_closure (empty_subset _)) @[simp] lemma closure_empty_union_closure_eq (M : Matroid α) (X : Set α) : M.closure ∅ ∪ M.closure X = M.closure X := union_eq_self_of_subset_left (M.closure_subset_closure (empty_subset _)) lemma closure_insert_eq_of_mem_closure (he : e ∈ M.closure X) : M.closure (insert e X) = M.closure X := by rw [← closure_insert_closure_eq_closure_insert, insert_eq_of_mem he, closure_closure] lemma mem_closure_self (M : Matroid α) (e : α) (he : e ∈ M.E := by aesop_mat) : e ∈ M.closure {e} := mem_closure_of_mem' M rfl section Indep variable {ι : Sort*} {I J B : Set α} {x : α} lemma Indep.closure_eq_setOf_isBasis_insert (hI : M.Indep I) : M.closure I = {x | M.IsBasis I (insert x I)} := by set F := {x | M.IsBasis I (insert x I)} have hIF : M.IsBasis I F := hI.isBasis_setOf_insert_isBasis have hF : M.IsFlat F := by refine ⟨fun J X hJF hJX e heX ↦ show M.IsBasis _ _ from ?_, hIF.subset_ground⟩ exact (hIF.isBasis_of_isBasis_of_subset_of_subset (hJX.isBasis_union hJF) hJF.subset (hIF.subset.trans subset_union_right)).isBasis_subset (subset_insert _ _) (insert_subset (Or.inl heX) (hIF.subset.trans subset_union_right)) rw [subset_antisymm_iff, closure_def, subset_sInter_iff, and_iff_right (sInter_subset_of_mem _)] · rintro F' ⟨hF', hIF'⟩ e (he : M.IsBasis I (insert e I)) rw [inter_eq_left.mpr (hIF.subset.trans hIF.subset_ground)] at hIF' obtain ⟨J, hJ, hIJ⟩ := hI.subset_isBasis_of_subset hIF' hF'.2 exact (hF'.1 hJ (he.isBasis_union_of_subset hJ.indep hIJ)) (Or.inr (mem_insert _ _)) exact ⟨hF, inter_subset_left.trans hIF.subset⟩ lemma Indep.insert_isBasis_iff_mem_closure (hI : M.Indep I) : M.IsBasis I (insert e I) ↔ e ∈ M.closure I := by rw [hI.closure_eq_setOf_isBasis_insert, mem_setOf] lemma Indep.isBasis_closure (hI : M.Indep I) : M.IsBasis I (M.closure I) := by rw [hI.closure_eq_setOf_isBasis_insert]; exact hI.isBasis_setOf_insert_isBasis lemma IsBasis.closure_eq_closure (h : M.IsBasis I X) : M.closure I = M.closure X := by refine subset_antisymm (M.closure_subset_closure h.subset) ?_ rw [← M.closure_closure I, h.indep.closure_eq_setOf_isBasis_insert] exact M.closure_subset_closure fun e he ↦ (h.isBasis_subset (subset_insert _ _) (insert_subset he h.subset)) lemma IsBasis.closure_eq_right (h : M.IsBasis I (M.closure X)) : M.closure I = M.closure X := M.closure_closure X ▸ h.closure_eq_closure lemma IsBasis'.closure_eq_closure (h : M.IsBasis' I X) : M.closure I = M.closure X := by rw [← closure_inter_ground _ X, h.isBasis_inter_ground.closure_eq_closure] lemma IsBasis.subset_closure (h : M.IsBasis I X) : X ⊆ M.closure I := by rw [← closure_subset_closure_iff_subset_closure, h.closure_eq_closure] lemma IsBasis'.isBasis_closure_right (h : M.IsBasis' I X) : M.IsBasis I (M.closure X) := by rw [← h.closure_eq_closure]; exact h.indep.isBasis_closure lemma IsBasis.isBasis_closure_right (h : M.IsBasis I X) : M.IsBasis I (M.closure X) := h.isBasis'.isBasis_closure_right lemma Indep.mem_closure_iff (hI : M.Indep I) : x ∈ M.closure I ↔ M.Dep (insert x I) ∨ x ∈ I := by rwa [hI.closure_eq_setOf_isBasis_insert, mem_setOf, isBasis_insert_iff] lemma Indep.mem_closure_iff' (hI : M.Indep I) : x ∈ M.closure I ↔ x ∈ M.E ∧ (M.Indep (insert x I) → x ∈ I) := by rw [hI.mem_closure_iff, dep_iff, insert_subset_iff, and_iff_left hI.subset_ground, imp_iff_not_or] have := hI.subset_ground aesop lemma Indep.insert_dep_iff (hI : M.Indep I) : M.Dep (insert e I) ↔ e ∈ M.closure I \ I := by rw [mem_diff, hI.mem_closure_iff, or_and_right, and_not_self_iff, or_false, iff_self_and, imp_not_comm] intro heI; rw [insert_eq_of_mem heI]; exact hI.not_dep lemma Indep.mem_closure_iff_of_notMem (hI : M.Indep I) (heI : e ∉ I) : e ∈ M.closure I ↔ M.Dep (insert e I) := by rw [hI.insert_dep_iff, mem_diff, and_iff_left heI] @[deprecated (since := "2025-05-23")] alias Indep.mem_closure_iff_of_not_mem := Indep.mem_closure_iff_of_notMem lemma Indep.notMem_closure_iff (hI : M.Indep I) (he : e ∈ M.E := by aesop_mat) : e ∉ M.closure I ↔ M.Indep (insert e I) ∧ e ∉ I := by rw [hI.mem_closure_iff, dep_iff, insert_subset_iff, and_iff_right he, and_iff_left hI.subset_ground]; tauto @[deprecated (since := "2025-05-23")] alias Indep.not_mem_closure_iff := Indep.notMem_closure_iff lemma Indep.notMem_closure_iff_of_notMem (hI : M.Indep I) (heI : e ∉ I) (he : e ∈ M.E := by aesop_mat) : e ∉ M.closure I ↔ M.Indep (insert e I) := by rw [hI.notMem_closure_iff, and_iff_left heI] @[deprecated (since := "2025-05-23")] alias Indep.not_mem_closure_iff_of_not_mem := Indep.notMem_closure_iff_of_notMem lemma Indep.insert_indep_iff_of_notMem (hI : M.Indep I) (heI : e ∉ I) : M.Indep (insert e I) ↔ e ∈ M.E \ M.closure I := by rw [mem_diff, hI.mem_closure_iff_of_notMem heI, dep_iff, not_and, not_imp_not, insert_subset_iff, and_iff_left hI.subset_ground] exact ⟨fun h ↦ ⟨h.subset_ground (mem_insert e I), fun _ ↦ h⟩, fun h ↦ h.2 h.1⟩ @[deprecated (since := "2025-05-23")] alias Indep.insert_indep_iff_of_not_mem := Indep.insert_indep_iff_of_notMem lemma Indep.insert_indep_iff (hI : M.Indep I) : M.Indep (insert e I) ↔ e ∈ M.E \ M.closure I ∨ e ∈ I := by obtain (h | h) := em (e ∈ I) · simp_rw [insert_eq_of_mem h, iff_true_intro hI, true_iff, iff_true_intro h, or_true] rw [hI.insert_indep_iff_of_notMem h, or_iff_left h] lemma insert_indep_iff : M.Indep (insert e I) ↔ M.Indep I ∧ (e ∉ I → e ∈ M.E \ M.closure I) := by by_cases hI : M.Indep I · rw [hI.insert_indep_iff, and_iff_right hI, or_iff_not_imp_right] simp [hI, show ¬ M.Indep (insert e I) from fun h ↦ hI <| h.subset <| subset_insert _ _] /-- This can be used for rewriting if the LHS is inside a binder and it is unknown whether `f = e`. -/ lemma Indep.insert_diff_indep_iff (hI : M.Indep (I \ {e})) (heI : e ∈ I) : M.Indep (insert f I \ {e}) ↔ f ∈ M.E \ M.closure (I \ {e}) ∨ f ∈ I := by obtain rfl | hne := eq_or_ne e f · simp [hI, heI] rw [← insert_diff_singleton_comm hne.symm, hI.insert_indep_iff, mem_diff_singleton, and_iff_left hne.symm] lemma Indep.isBasis_of_subset_of_subset_closure (hI : M.Indep I) (hIX : I ⊆ X) (hXI : X ⊆ M.closure I) : M.IsBasis I X := hI.isBasis_closure.isBasis_subset hIX hXI lemma isBasis_iff_indep_subset_closure : M.IsBasis I X ↔ M.Indep I ∧ I ⊆ X ∧ X ⊆ M.closure I := ⟨fun h ↦ ⟨h.indep, h.subset, h.subset_closure⟩, fun h ↦ h.1.isBasis_of_subset_of_subset_closure h.2.1 h.2.2⟩ lemma Indep.isBase_of_ground_subset_closure (hI : M.Indep I) (h : M.E ⊆ M.closure I) : M.IsBase I := by rw [← isBasis_ground_iff]; exact hI.isBasis_of_subset_of_subset_closure hI.subset_ground h lemma IsBase.closure_eq (hB : M.IsBase B) : M.closure B = M.E := by rw [← isBasis_ground_iff] at hB; rw [hB.closure_eq_closure, closure_ground] lemma IsBase.closure_of_superset (hB : M.IsBase B) (hBX : B ⊆ X) : M.closure X = M.E := (M.closure_subset_ground _).antisymm (hB.closure_eq ▸ M.closure_subset_closure hBX) lemma isBase_iff_indep_closure_eq : M.IsBase B ↔ M.Indep B ∧ M.closure B = M.E := by rw [← isBasis_ground_iff, isBasis_iff_indep_subset_closure, and_congr_right_iff] exact fun hI ↦ ⟨fun h ↦ (M.closure_subset_ground _).antisymm h.2, fun h ↦ ⟨(M.subset_closure B).trans_eq h, h.symm.subset⟩⟩ lemma IsBase.exchange_base_of_notMem_closure (hB : M.IsBase B) (he : e ∈ B) (hf : f ∉ M.closure (B \ {e})) (hfE : f ∈ M.E := by aesop_mat) : M.IsBase (insert f (B \ {e})) := by obtain rfl | hne := eq_or_ne f e · simpa [he] have ⟨hi, hfB⟩ : M.Indep (insert f (B \ {e})) ∧ f ∉ B := by simpa [(hB.indep.diff _).notMem_closure_iff, hne] using hf exact hB.exchange_isBase_of_indep hfB hi @[deprecated (since := "2025-05-23")] alias IsBase.exchange_base_of_not_mem_closure := IsBase.exchange_base_of_notMem_closure lemma Indep.isBase_iff_ground_subset_closure (hI : M.Indep I) : M.IsBase I ↔ M.E ⊆ M.closure I := ⟨fun h ↦ h.closure_eq.symm.subset, hI.isBase_of_ground_subset_closure⟩ lemma Indep.closure_inter_eq_self_of_subset (hI : M.Indep I) (hJI : J ⊆ I) : M.closure J ∩ I = J := by have hJ := hI.subset hJI rw [subset_antisymm_iff, and_iff_left (subset_inter (M.subset_closure _) hJI)] rintro e ⟨heJ, heI⟩ exact hJ.isBasis_closure.mem_of_insert_indep heJ (hI.subset (insert_subset heI hJI)) /-- For a nonempty collection of subsets of a given independent set, the closure of the intersection is the intersection of the closure. -/ lemma Indep.closure_sInter_eq_biInter_closure_of_forall_subset {Js : Set (Set α)} (hI : M.Indep I) (hne : Js.Nonempty) (hIs : ∀ J ∈ Js, J ⊆ I) : M.closure (⋂₀ Js) = (⋂ J ∈ Js, M.closure J) := by rw [subset_antisymm_iff, subset_iInter₂_iff] have hiX : ⋂₀ Js ⊆ I := (sInter_subset_of_mem hne.some_mem).trans (hIs _ hne.some_mem) have hiI := hI.subset hiX refine ⟨ fun X hX ↦ M.closure_subset_closure (sInter_subset_of_mem hX), fun e he ↦ by_contra fun he' ↦ ?_⟩ rw [mem_iInter₂] at he have heEI : e ∈ M.E \ I := by refine ⟨M.closure_subset_ground _ (he _ hne.some_mem), fun heI ↦ he' ?_⟩ refine mem_closure_of_mem _ (fun X hX' ↦ ?_) hiI.subset_ground rw [← hI.closure_inter_eq_self_of_subset (hIs X hX')] exact ⟨he X hX', heI⟩ rw [hiI.notMem_closure_iff_of_notMem (notMem_subset hiX heEI.2)] at he' obtain ⟨J, hJI, heJ⟩ := he'.subset_isBasis_of_subset (insert_subset_insert hiX) (insert_subset heEI.1 hI.subset_ground) have hIb : M.IsBasis I (insert e I) := by rw [hI.insert_isBasis_iff_mem_closure] exact (M.closure_subset_closure (hIs _ hne.some_mem)) (he _ hne.some_mem) obtain ⟨f, hfIJ, hfb⟩ := hJI.exchange hIb ⟨heJ (mem_insert e _), heEI.2⟩ obtain rfl := hI.eq_of_isBasis (hfb.isBasis_subset (insert_subset hfIJ.1 (by (rw [diff_subset_iff, singleton_union]; exact hJI.subset))) (subset_insert _ _)) refine hfIJ.2 (heJ (mem_insert_of_mem _ fun X hX' ↦ by_contra fun hfX ↦ ?_)) obtain (hd | heX) := ((hI.subset (hIs X hX')).mem_closure_iff).mp (he _ hX') · refine (hJI.indep.subset (insert_subset (heJ (mem_insert _ _)) ?_)).not_dep hd specialize hIs _ hX' rw [← singleton_union, ← diff_subset_iff, diff_singleton_eq_self hfX] at hIs exact hIs.trans diff_subset exact heEI.2 (hIs _ hX' heX) lemma closure_iInter_eq_iInter_closure_of_iUnion_indep [hι : Nonempty ι] (Is : ι → Set α) (h : M.Indep (⋃ i, Is i)) : M.closure (⋂ i, Is i) = (⋂ i, M.closure (Is i)) := by convert h.closure_sInter_eq_biInter_closure_of_forall_subset (range_nonempty Is) (by simp [subset_iUnion]) simp lemma closure_sInter_eq_biInter_closure_of_sUnion_indep (Is : Set (Set α)) (hIs : Is.Nonempty) (h : M.Indep (⋃₀ Is)) : M.closure (⋂₀ Is) = (⋂ I ∈ Is, M.closure I) := h.closure_sInter_eq_biInter_closure_of_forall_subset hIs (fun _ ↦ subset_sUnion_of_mem) lemma closure_biInter_eq_biInter_closure_of_biUnion_indep {ι : Type*} {A : Set ι} (hA : A.Nonempty) {I : ι → Set α} (h : M.Indep (⋃ i ∈ A, I i)) : M.closure (⋂ i ∈ A, I i) = ⋂ i ∈ A, M.closure (I i) := by have := hA.coe_sort convert closure_iInter_eq_iInter_closure_of_iUnion_indep (Is := fun i : A ↦ I i) (by simpa) <;> simp lemma Indep.closure_iInter_eq_biInter_closure_of_forall_subset [Nonempty ι] {Js : ι → Set α} (hI : M.Indep I) (hJs : ∀ i, Js i ⊆ I) : M.closure (⋂ i, Js i) = ⋂ i, M.closure (Js i) := closure_iInter_eq_iInter_closure_of_iUnion_indep _ (hI.subset <| by simpa) lemma Indep.closure_inter_eq_inter_closure (h : M.Indep (I ∪ J)) : M.closure (I ∩ J) = M.closure I ∩ M.closure J := by rw [inter_eq_iInter, closure_iInter_eq_iInter_closure_of_iUnion_indep, inter_eq_iInter] · exact iInter_congr (by simp) rwa [← union_eq_iUnion] lemma Indep.inter_isBasis_biInter {ι : Type*} (hI : M.Indep I) {X : ι → Set α} {A : Set ι} (hA : A.Nonempty) (h : ∀ i ∈ A, M.IsBasis ((X i) ∩ I) (X i)) : M.IsBasis ((⋂ i ∈ A, X i) ∩ I) (⋂ i ∈ A, X i) := by refine (hI.inter_left _).isBasis_of_subset_of_subset_closure inter_subset_left ?_ simp_rw [← biInter_inter hA, closure_biInter_eq_biInter_closure_of_biUnion_indep hA (I := fun i ↦ (X i) ∩ I) (hI.subset (by simp)), subset_iInter_iff] exact fun i hiA ↦ (biInter_subset_of_mem hiA).trans (h i hiA).subset_closure lemma Indep.inter_isBasis_iInter [Nonempty ι] {X : ι → Set α} (hI : M.Indep I) (h : ∀ i, M.IsBasis ((X i) ∩ I) (X i)) : M.IsBasis ((⋂ i, X i) ∩ I) (⋂ i, X i) := by convert hI.inter_isBasis_biInter (ι := PLift ι) univ_nonempty (X := fun i ↦ X i.down) (by simpa using fun (i : PLift ι) ↦ h i.down) <;> · simp only [mem_univ, iInter_true] exact (iInter_plift_down X).symm lemma Indep.inter_isBasis_sInter {Xs : Set (Set α)} (hI : M.Indep I) (hXs : Xs.Nonempty) (h : ∀ X ∈ Xs, M.IsBasis (X ∩ I) X) : M.IsBasis (⋂₀ Xs ∩ I) (⋂₀ Xs) := by rw [sInter_eq_biInter] exact hI.inter_isBasis_biInter hXs h lemma isBasis_iff_isBasis_closure_of_subset (hIX : I ⊆ X) (hX : X ⊆ M.E := by aesop_mat) : M.IsBasis I X ↔ M.IsBasis I (M.closure X) := ⟨fun h ↦ h.isBasis_closure_right, fun h ↦ h.isBasis_subset hIX (M.subset_closure X hX)⟩ lemma isBasis_iff_isBasis_closure_of_subset' (hIX : I ⊆ X) : M.IsBasis I X ↔ M.IsBasis I (M.closure X) ∧ X ⊆ M.E := ⟨fun h ↦ ⟨h.isBasis_closure_right, h.subset_ground⟩, fun h ↦ h.1.isBasis_subset hIX (M.subset_closure X h.2)⟩ lemma isBasis'_iff_isBasis_closure : M.IsBasis' I X ↔ M.IsBasis I (M.closure X) ∧ I ⊆ X := by rw [← closure_inter_ground, isBasis'_iff_isBasis_inter_ground] exact ⟨fun h ↦ ⟨h.isBasis_closure_right, h.subset.trans inter_subset_left⟩, fun h ↦ h.1.isBasis_subset (subset_inter h.2 h.1.indep.subset_ground) (M.subset_closure _)⟩ lemma exists_isBasis_inter_ground_isBasis_closure (M : Matroid α) (X : Set α) : ∃ I, M.IsBasis I (X ∩ M.E) ∧ M.IsBasis I (M.closure X) := by obtain ⟨I, hI⟩ := M.exists_isBasis (X ∩ M.E) have hI' := hI.isBasis_closure_right; rw [closure_inter_ground] at hI' exact ⟨_, hI, hI'⟩ lemma IsBasis.isBasis_of_closure_eq_closure (hI : M.IsBasis I X) (hY : I ⊆ Y) (h : M.closure X = M.closure Y) (hYE : Y ⊆ M.E := by aesop_mat) : M.IsBasis I Y := by refine hI.indep.isBasis_of_subset_of_subset_closure hY ?_ rw [hI.closure_eq_closure, h] exact M.subset_closure Y lemma isBasis_union_iff_indep_closure : M.IsBasis I (I ∪ X) ↔ M.Indep I ∧ X ⊆ M.closure I := ⟨fun h ↦ ⟨h.indep, subset_union_right.trans h.subset_closure⟩, fun ⟨hI, hXI⟩ ↦ hI.isBasis_closure.isBasis_subset subset_union_left (union_subset (M.subset_closure I) hXI)⟩ lemma isBasis_iff_indep_closure : M.IsBasis I X ↔ M.Indep I ∧ X ⊆ M.closure I ∧ I ⊆ X := ⟨fun h ↦ ⟨h.indep, h.subset_closure, h.subset⟩, fun h ↦ (isBasis_union_iff_indep_closure.mpr ⟨h.1, h.2.1⟩).isBasis_subset h.2.2 subset_union_right⟩ lemma Indep.inter_isBasis_closure_iff_subset_closure_inter {X : Set α} (hI : M.Indep I) : M.IsBasis (X ∩ I) X ↔ X ⊆ M.closure (X ∩ I) := ⟨IsBasis.subset_closure, (hI.inter_left X).isBasis_of_subset_of_subset_closure inter_subset_left⟩ lemma IsBasis.closure_inter_isBasis_closure (h : M.IsBasis (X ∩ I) X) (hI : M.Indep I) : M.IsBasis (M.closure X ∩ I) (M.closure X) := by rw [hI.inter_isBasis_closure_iff_subset_closure_inter] at h ⊢ exact (M.closure_subset_closure_of_subset_closure h).trans (M.closure_subset_closure (inter_subset_inter_left _ (h.trans (M.closure_subset_closure inter_subset_left)))) lemma IsBasis.eq_of_closure_subset (hI : M.IsBasis I X) (hJI : J ⊆ I) (hJ : X ⊆ M.closure J) : J = I := by rw [← hI.indep.closure_inter_eq_self_of_subset hJI, inter_eq_self_of_subset_right] exact hI.subset.trans hJ lemma IsBasis.insert_isBasis_insert_of_notMem_closure (hIX : M.IsBasis I X) (heI : e ∉ M.closure I) (heE : e ∈ M.E := by aesop_mat) : M.IsBasis (insert e I) (insert e X) := hIX.insert_isBasis_insert <| hIX.indep.insert_indep_iff.2 <| .inl ⟨heE, heI⟩ @[deprecated (since := "2025-05-23")] alias IsBasis.insert_isBasis_insert_of_not_mem_closure := IsBasis.insert_isBasis_insert_of_notMem_closure @[simp] lemma empty_isBasis_iff : M.IsBasis ∅ X ↔ X ⊆ M.closure ∅ := by rw [isBasis_iff_indep_closure, and_iff_right M.empty_indep, and_iff_left (empty_subset _)] lemma indep_iff_forall_notMem_closure_diff (hI : I ⊆ M.E := by aesop_mat) : M.Indep I ↔ ∀ ⦃e⦄, e ∈ I → e ∉ M.closure (I \ {e}) := by use fun h e heI he ↦ ((h.closure_inter_eq_self_of_subset diff_subset).subset ⟨he, heI⟩).2 rfl intro h obtain ⟨J, hJ⟩ := M.exists_isBasis I convert hJ.indep refine hJ.subset.antisymm' (fun e he ↦ by_contra fun heJ ↦ h he ?_) exact mem_of_mem_of_subset (hJ.subset_closure he) (M.closure_subset_closure (subset_diff_singleton hJ.subset heJ)) @[deprecated (since := "2025-05-23")] alias indep_iff_forall_not_mem_closure_diff := indep_iff_forall_notMem_closure_diff /-- An alternative version of `Matroid.indep_iff_forall_notMem_closure_diff` where the hypothesis that `I ⊆ M.E` is contained in the RHS rather than the hypothesis. -/ lemma indep_iff_forall_notMem_closure_diff' : M.Indep I ↔ I ⊆ M.E ∧ ∀ e ∈ I, e ∉ M.closure (I \ {e}) := ⟨fun h ↦ ⟨h.subset_ground, (indep_iff_forall_notMem_closure_diff h.subset_ground).mp h⟩, fun h ↦ (indep_iff_forall_notMem_closure_diff h.1).mpr h.2⟩ @[deprecated (since := "2025-05-23")] alias indep_iff_forall_not_mem_closure_diff' := indep_iff_forall_notMem_closure_diff' lemma Indep.notMem_closure_diff_of_mem (hI : M.Indep I) (he : e ∈ I) : e ∉ M.closure (I \ {e}) := (indep_iff_forall_notMem_closure_diff'.1 hI).2 e he @[deprecated (since := "2025-05-23")] alias Indep.not_mem_closure_diff_of_mem := Indep.notMem_closure_diff_of_mem lemma Indep.closure_insert_diff_eq_of_mem_closure (hI : M.Indep I) (hf : f ∈ M.closure I) (he : e ∈ M.closure (insert f I \ {e})) : M.closure (insert f I \ {e}) = M.closure I := by apply subset_antisymm <;> apply closure_subset_closure_of_subset_closure · rintro a (rfl | haI) exacts [hf, M.subset_closure _ hI.subset_ground haI] · intro a haI obtain rfl | ne := eq_or_ne a e exacts [he, M.mem_closure_of_mem' ⟨.inr haI, ne⟩ (hI.subset_ground haI)] lemma Indep.indep_insert_diff_of_mem_closure (hI : M.Indep I) (hfI : f ∈ M.closure I) (he : e ∈ M.closure (insert f I \ {e})) (heI : e ∈ insert f I) : M.Indep (insert f I \ {e}) := by obtain rfl | heI := heI · exact hI.subset (by simp) rw [Indep.insert_diff_indep_iff (hI.subset (diff_subset ..)) heI] refine .inl ⟨mem_ground_of_mem_closure hfI, fun h ↦ hI.notMem_closure_diff_of_mem heI ?_⟩ exact closure_insert_eq_of_mem_closure h ▸ M.closure_subset_closure (by intro; aesop) he lemma IsBasis.isBasis_insert_diff_of_mem_closure (hB : M.IsBasis B X) (he : e ∈ M.closure (insert f B \ {e})) (heB : e ∈ insert f B) (hfX : f ∈ X) : M.IsBasis (insert f B \ {e}) X := by rw [isBasis_iff_indep_closure] at hB ⊢ exact ⟨hB.1.indep_insert_diff_of_mem_closure (hB.2.1 hfX) he heB, hB.2.1.trans_eq (hB.1.closure_insert_diff_eq_of_mem_closure (hB.2.1 hfX) he).symm, diff_subset.trans (insert_subset hfX hB.2.2)⟩ lemma IsBase.isBase_insert_diff_of_mem_closure (hB : M.IsBase B) (he : e ∈ M.closure (insert f B \ {e})) (heB : e ∈ insert f B) : M.IsBase (insert f B \ {e}) := by rw [← isBasis_ground_iff] at hB ⊢ by_cases hf : f ∈ M.E · exact hB.isBasis_insert_diff_of_mem_closure he heB hf obtain rfl | heB := heB · simpa [show e ∉ B from fun h ↦ hf (hB.1.1.2 h)] using hB rw [← closure_inter_ground] at he cases hB.indep.notMem_closure_diff_of_mem heB (M.closure_subset_closure (by intro; aesop) he) lemma indep_iff_forall_closure_diff_ne : M.Indep I ↔ ∀ ⦃e⦄, e ∈ I → M.closure (I \ {e}) ≠ M.closure I := by rw [indep_iff_forall_notMem_closure_diff'] refine ⟨fun ⟨hIE, h⟩ e heI h_eq ↦ h e heI (h_eq.symm.subset (M.mem_closure_of_mem heI)), fun h ↦ ⟨fun e heI ↦ by_contra fun heE ↦ h heI ?_,fun e heI hin ↦ h heI ?_⟩⟩ · rw [← closure_inter_ground, inter_comm, inter_diff_distrib_left, inter_singleton_eq_empty.mpr heE, diff_empty, inter_comm, closure_inter_ground] nth_rw 2 [show I = insert e (I \ {e}) by simp [heI]] rw [← closure_insert_closure_eq_closure_insert, insert_eq_of_mem hin, closure_closure] lemma Indep.union_indep_iff_forall_notMem_closure_right (hI : M.Indep I) (hJ : M.Indep J) : M.Indep (I ∪ J) ↔ ∀ e ∈ J \ I, e ∉ M.closure (I ∪ (J \ {e})) := by refine ⟨fun h e heJ hecl ↦ h.notMem_closure_diff_of_mem (.inr heJ.1) ?_, fun h ↦ ?_⟩ · rwa [union_diff_distrib, diff_singleton_eq_self heJ.2] obtain ⟨K, hKIJ, hK⟩ := hI.subset_isBasis_of_subset (show I ⊆ I ∪ J from subset_union_left) obtain rfl | hssu := hKIJ.subset.eq_or_ssubset · exact hKIJ.indep exfalso obtain ⟨e, heI, heK⟩ := exists_of_ssubset hssu have heJI : e ∈ J \ I := by rw [← union_diff_right, union_comm] exact ⟨heI, notMem_subset hK heK⟩ refine h _ heJI ?_ rw [← diff_singleton_eq_self heJI.2, ← union_diff_distrib] exact M.closure_subset_closure (subset_diff_singleton hKIJ.subset heK) <| hKIJ.subset_closure heI @[deprecated (since := "2025-05-23")] alias Indep.union_indep_iff_forall_not_mem_closure_right := Indep.union_indep_iff_forall_notMem_closure_right lemma Indep.union_indep_iff_forall_notMem_closure_left (hI : M.Indep I) (hJ : M.Indep J) : M.Indep (I ∪ J) ↔ ∀ e ∈ I \ J, e ∉ M.closure ((I \ {e}) ∪ J) := by simp_rw [union_comm I J, hJ.union_indep_iff_forall_notMem_closure_right hI, union_comm] @[deprecated (since := "2025-05-23")] alias Indep.union_indep_iff_forall_not_mem_closure_left := Indep.union_indep_iff_forall_notMem_closure_left lemma Indep.closure_ssubset_closure (hI : M.Indep I) (hJI : J ⊂ I) : M.closure J ⊂ M.closure I := by obtain ⟨e, heI, heJ⟩ := exists_of_ssubset hJI exact (M.closure_subset_closure hJI.subset).ssubset_of_not_subset fun hss ↦ heJ <| (hI.closure_inter_eq_self_of_subset hJI.subset).subset ⟨hss (M.mem_closure_of_mem heI), heI⟩ lemma indep_iff_forall_closure_ssubset_of_ssubset (hI : I ⊆ M.E := by aesop_mat) : M.Indep I ↔ ∀ ⦃J⦄, J ⊂ I → M.closure J ⊂ M.closure I := by refine ⟨fun h _ ↦ h.closure_ssubset_closure, fun h ↦ (indep_iff_forall_notMem_closure_diff hI).2 fun e heI hecl ↦ ?_⟩ refine (h (diff_singleton_ssubset.2 heI)).ne ?_ rw [show I = insert e (I \ {e}) by simp [heI], ← closure_insert_closure_eq_closure_insert, insert_eq_of_mem hecl] simp lemma Indep.closure_diff_ssubset (hI : M.Indep I) (hX : (I ∩ X).Nonempty) : M.closure (I \ X) ⊂ M.closure I := by refine hI.closure_ssubset_closure <| diff_subset.ssubset_of_ne fun h ↦ ?_ rw [sdiff_eq_left, disjoint_iff_inter_eq_empty] at h simp [h] at hX lemma Indep.closure_diff_singleton_ssubset (hI : M.Indep I) (he : e ∈ I) : M.closure (I \ {e}) ⊂ M.closure I := hI.closure_ssubset_closure <| by simpa end Indep section insert lemma mem_closure_insert (he : e ∉ M.closure X) (hef : e ∈ M.closure (insert f X)) : f ∈ M.closure (insert e X) := by rw [← closure_inter_ground] at * have hfE : f ∈ M.E := by by_contra! hfE; rw [insert_inter_of_notMem hfE] at hef; exact he hef have heE : e ∈ M.E := (M.closure_subset_ground _) hef rw [insert_inter_of_mem hfE] at hef; rw [insert_inter_of_mem heE] obtain ⟨I, hI⟩ := M.exists_isBasis (X ∩ M.E) rw [← hI.closure_eq_closure, hI.indep.notMem_closure_iff] at he rw [← closure_insert_closure_eq_closure_insert, ← hI.closure_eq_closure, closure_insert_closure_eq_closure_insert, he.1.mem_closure_iff] at * rw [or_iff_not_imp_left, dep_iff, insert_comm, and_iff_left (insert_subset heE (insert_subset hfE hI.indep.subset_ground)), not_not] intro h rw [(h.subset (subset_insert _ _)).mem_closure_iff, or_iff_right (h.not_dep), mem_insert_iff, or_iff_left he.2] at hef subst hef; apply mem_insert lemma closure_exchange (he : e ∈ M.closure (insert f X) \ M.closure X) : f ∈ M.closure (insert e X) \ M.closure X := ⟨mem_closure_insert he.2 he.1, fun hf ↦ by rwa [closure_insert_eq_of_mem_closure hf, diff_self, iff_false_intro (notMem_empty _)] at he⟩ lemma closure_exchange_iff : e ∈ M.closure (insert f X) \ M.closure X ↔ f ∈ M.closure (insert e X) \ M.closure X := ⟨closure_exchange, closure_exchange⟩ lemma closure_insert_congr (he : e ∈ M.closure (insert f X) \ M.closure X) : M.closure (insert e X) = M.closure (insert f X) := by have hf := closure_exchange he rw [eq_comm, ← closure_closure, ← insert_eq_of_mem he.1, closure_insert_closure_eq_closure_insert, insert_comm, ← closure_closure, ← closure_insert_closure_eq_closure_insert, insert_eq_of_mem hf.1, closure_closure, closure_closure] lemma closure_diff_eq_self (h : Y ⊆ M.closure (X \ Y)) : M.closure (X \ Y) = M.closure X := by rw [← diff_union_inter X Y, ← closure_union_closure_left_eq, union_eq_self_of_subset_right (inter_subset_right.trans h), closure_closure, diff_union_inter] lemma closure_diff_singleton_eq_closure (h : e ∈ M.closure (X \ {e})) : M.closure (X \ {e}) = M.closure X := closure_diff_eq_self (by simpa) lemma subset_closure_diff_iff_closure_eq (h : Y ⊆ X) (hY : Y ⊆ M.E := by aesop_mat) : Y ⊆ M.closure (X \ Y) ↔ M.closure (X \ Y) = M.closure X := ⟨closure_diff_eq_self, fun h' ↦ (M.subset_closure_of_subset' h).trans h'.symm.subset⟩ lemma mem_closure_diff_singleton_iff_closure (he : e ∈ X) (heE : e ∈ M.E := by aesop_mat) : e ∈ M.closure (X \ {e}) ↔ M.closure (X \ {e}) = M.closure X := by simpa using subset_closure_diff_iff_closure_eq (Y := {e}) (X := X) (by simpa) end insert lemma ext_closure {M₁ M₂ : Matroid α} (h : ∀ X, M₁.closure X = M₂.closure X) : M₁ = M₂ := ext_indep (by simpa using h univ) (fun _ _ ↦ by simp_rw [indep_iff_forall_closure_diff_ne, h]) section Spanning variable {S T I B : Set α} /-- A set is `spanning` in `M` if its closure is equal to `M.E`, or equivalently if it contains a base of `M`. -/ @[mk_iff] structure Spanning (M : Matroid α) (S : Set α) : Prop where closure_eq : M.closure S = M.E subset_ground : S ⊆ M.E attribute [aesop unsafe 10% (rule_sets := [Matroid])] Spanning.subset_ground lemma spanning_iff_closure_eq (hS : S ⊆ M.E := by aesop_mat) : M.Spanning S ↔ M.closure S = M.E := by rw [spanning_iff, and_iff_left hS] @[simp] lemma closure_spanning_iff (hS : S ⊆ M.E := by aesop_mat) : M.Spanning (M.closure S) ↔ M.Spanning S := by rw [spanning_iff_closure_eq, closure_closure, ← spanning_iff_closure_eq] lemma spanning_iff_ground_subset_closure (hS : S ⊆ M.E := by aesop_mat) : M.Spanning S ↔ M.E ⊆ M.closure S := by rw [spanning_iff_closure_eq, subset_antisymm_iff, and_iff_right (closure_subset_ground _ _)] lemma not_spanning_iff_closure_ssubset (hS : S ⊆ M.E := by aesop_mat) : ¬M.Spanning S ↔ M.closure S ⊂ M.E := by rw [spanning_iff_closure_eq, ssubset_iff_subset_ne, iff_and_self, iff_true_intro (M.closure_subset_ground _)] exact fun _ ↦ trivial lemma Spanning.superset (hS : M.Spanning S) (hST : S ⊆ T) (hT : T ⊆ M.E := by aesop_mat) : M.Spanning T := ⟨(M.closure_subset_ground _).antisymm (by rw [← hS.closure_eq]; exact M.closure_subset_closure hST), hT⟩ lemma Spanning.closure_eq_of_superset (hS : M.Spanning S) (hST : S ⊆ T) : M.closure T = M.E := by rw [← closure_inter_ground, ← spanning_iff_closure_eq] exact hS.superset (subset_inter hST hS.subset_ground) lemma Spanning.union_left (hS : M.Spanning S) (hX : X ⊆ M.E := by aesop_mat) : M.Spanning (S ∪ X) := hS.superset subset_union_left lemma Spanning.union_right (hS : M.Spanning S) (hX : X ⊆ M.E := by aesop_mat) : M.Spanning (X ∪ S) := hS.superset subset_union_right lemma IsBase.spanning (hB : M.IsBase B) : M.Spanning B := ⟨hB.closure_eq, hB.subset_ground⟩ lemma ground_spanning (M : Matroid α) : M.Spanning M.E := ⟨M.closure_ground, rfl.subset⟩ lemma IsBase.spanning_of_superset (hB : M.IsBase B) (hBX : B ⊆ X) (hX : X ⊆ M.E := by aesop_mat) : M.Spanning X := hB.spanning.superset hBX /-- A version of `Matroid.spanning_iff_exists_isBase_subset` in which the `S ⊆ M.E` condition appears in the RHS of the equivalence rather than as a hypothesis. -/ lemma spanning_iff_exists_isBase_subset' : M.Spanning S ↔ (∃ B, M.IsBase B ∧ B ⊆ S) ∧ S ⊆ M.E := by refine ⟨fun h ↦ ⟨?_, h.subset_ground⟩, fun ⟨⟨B, hB, hBS⟩, hSE⟩ ↦ hB.spanning.superset hBS⟩ obtain ⟨B, hB⟩ := M.exists_isBasis S have hB' := hB.isBasis_closure_right rw [h.closure_eq, isBasis_ground_iff] at hB' exact ⟨B, hB', hB.subset⟩ lemma spanning_iff_exists_isBase_subset (hS : S ⊆ M.E := by aesop_mat) : M.Spanning S ↔ ∃ B, M.IsBase B ∧ B ⊆ S := by rw [spanning_iff_exists_isBase_subset', and_iff_left hS] lemma Spanning.exists_isBase_subset (hS : M.Spanning S) : ∃ B, M.IsBase B ∧ B ⊆ S := by rwa [spanning_iff_exists_isBase_subset] at hS lemma coindep_iff_compl_spanning (hI : I ⊆ M.E := by aesop_mat) : M.Coindep I ↔ M.Spanning (M.E \ I) := by rw [coindep_iff_exists, spanning_iff_exists_isBase_subset] lemma spanning_iff_compl_coindep (hS : S ⊆ M.E := by aesop_mat) : M.Spanning S ↔ M.Coindep (M.E \ S) := by rw [coindep_iff_compl_spanning, diff_diff_cancel_left hS] lemma Coindep.compl_spanning (hI : M.Coindep I) : M.Spanning (M.E \ I) := (coindep_iff_compl_spanning hI.subset_ground).mp hI lemma coindep_iff_closure_compl_eq_ground (hK : X ⊆ M.E := by aesop_mat) : M.Coindep X ↔ M.closure (M.E \ X) = M.E := by rw [coindep_iff_compl_spanning, spanning_iff_closure_eq] lemma Coindep.closure_compl (hX : M.Coindep X) : M.closure (M.E \ X) = M.E := (coindep_iff_closure_compl_eq_ground hX.subset_ground).mp hX lemma Indep.isBase_of_spanning (hI : M.Indep I) (hIs : M.Spanning I) : M.IsBase I := by obtain ⟨B, hB, hBI⟩ := hIs.exists_isBase_subset; rwa [← hB.eq_of_subset_indep hI hBI] lemma Spanning.isBase_of_indep (hIs : M.Spanning I) (hI : M.Indep I) : M.IsBase I := hI.isBase_of_spanning hIs lemma Indep.eq_of_spanning_subset (hI : M.Indep I) (hS : M.Spanning S) (hSI : S ⊆ I) : S = I := ((hI.subset hSI).isBase_of_spanning hS).eq_of_subset_indep hI hSI lemma IsBasis.spanning_iff_spanning (hIX : M.IsBasis I X) : M.Spanning I ↔ M.Spanning X := by rw [spanning_iff_closure_eq, spanning_iff_closure_eq, hIX.closure_eq_closure] lemma Spanning.isBase_restrict_iff (hS : M.Spanning S) : (M ↾ S).IsBase B ↔ M.IsBase B ∧ B ⊆ S := by rw [isBase_restrict_iff', isBasis'_iff_isBasis] refine ⟨fun h ↦ ⟨?_, h.subset⟩, fun h ↦ h.1.indep.isBasis_of_subset_of_subset_closure h.2 ?_⟩ · exact h.indep.isBase_of_spanning <| by rwa [h.spanning_iff_spanning] rw [h.1.closure_eq] exact hS.subset_ground lemma Spanning.compl_coindep (hS : M.Spanning S) : M.Coindep (M.E \ S) := by rwa [← spanning_iff_compl_coindep] lemma IsBasis.isBase_of_spanning (hIX : M.IsBasis I X) (hX : M.Spanning X) : M.IsBase I := hIX.indep.isBase_of_spanning <| by rwa [hIX.spanning_iff_spanning] lemma Indep.exists_isBase_subset_spanning (hI : M.Indep I) (hS : M.Spanning S) (hIS : I ⊆ S) : ∃ B, M.IsBase B ∧ I ⊆ B ∧ B ⊆ S := by obtain ⟨B, hB⟩ := hI.subset_isBasis_of_subset hIS exact ⟨B, hB.1.isBase_of_spanning hS, hB.2, hB.1.subset⟩ lemma Restriction.isBase_iff_of_spanning {N : Matroid α} (hR : N ≤r M) (hN : M.Spanning N.E) : N.IsBase B ↔ (M.IsBase B ∧ B ⊆ N.E) := by obtain ⟨R, hR : R ⊆ M.E, rfl⟩ := hR rw [Spanning.isBase_restrict_iff (show M.Spanning R from hN), restrict_ground_eq] lemma ext_spanning {M M' : Matroid α} (h : M.E = M'.E) (hsp : ∀ S, S ⊆ M.E → (M.Spanning S ↔ M'.Spanning S)) : M = M' := by have hsp' : M.Spanning = M'.Spanning := by ext S refine (em (S ⊆ M.E)).elim (fun hSE ↦ by rw [hsp _ hSE] ) (fun hSE ↦ iff_of_false (fun h ↦ hSE h.subset_ground) (fun h' ↦ hSE (h'.subset_ground.trans h.symm.subset))) rw [← dual_inj, ext_iff_indep, dual_ground, dual_ground, and_iff_right h] intro I hIE rw [← coindep_def, ← coindep_def, coindep_iff_compl_spanning, coindep_iff_compl_spanning, hsp', h] lemma IsBase.eq_of_superset_spanning (hB : M.IsBase B) (hX : M.Spanning X) (hXB : X ⊆ B) : B = X := have ⟨B', hB', hB'X⟩ := hX.exists_isBase_subset subset_antisymm (by rwa [← hB'.eq_of_subset_isBase hB (hB'X.trans hXB)]) hXB theorem isBase_iff_minimal_spanning : M.IsBase B ↔ Minimal M.Spanning B := by rw [minimal_subset_iff] refine ⟨fun h ↦ ⟨h.spanning, fun _ ↦ h.eq_of_superset_spanning⟩, fun ⟨h, h'⟩ ↦ ?_⟩ obtain ⟨B', hB', hBB'⟩ := h.exists_isBase_subset rwa [h' hB'.spanning hBB'] theorem Spanning.isBase_of_minimal (hX : M.Spanning X) (h : ∀ ⦃Y⦄, M.Spanning Y → Y ⊆ X → X = Y) : M.IsBase X := by rwa [isBase_iff_minimal_spanning, minimal_subset_iff, and_iff_right hX] end Spanning section Constructions variable {R S : Set α} @[simp] lemma restrict_closure_eq' (M : Matroid α) (X R : Set α) : (M ↾ R).closure X = (M.closure (X ∩ R) ∩ R) ∪ (R \ M.E) := by obtain ⟨I, hI⟩ := (M ↾ R).exists_isBasis' X obtain ⟨hI', hIR⟩ := isBasis'_restrict_iff.1 hI ext e rw [← hI.closure_eq_closure, ← hI'.closure_eq_closure, hI.indep.mem_closure_iff', mem_union, mem_inter_iff, hI'.indep.mem_closure_iff', restrict_ground_eq, restrict_indep_iff, mem_diff] by_cases he : M.Indep (insert e I) · simp [he, and_comm, insert_subset_iff, hIR, (he.subset_ground (mem_insert ..)), imp_or] tauto lemma restrict_closure_eq (M : Matroid α) (hXR : X ⊆ R) (hR : R ⊆ M.E := by aesop_mat) : (M ↾ R).closure X = M.closure X ∩ R := by rw [restrict_closure_eq', diff_eq_empty.mpr hR, union_empty, inter_eq_self_of_subset_left hXR] @[simp] lemma emptyOn_closure_eq (X : Set α) : (emptyOn α).closure X = ∅ := (closure_subset_ground ..).antisymm <| empty_subset _ @[simp] lemma loopyOn_closure_eq (E X : Set α) : (loopyOn E).closure X = E := by simp [loopyOn, restrict_closure_eq'] @[simp] lemma loopyOn_spanning_iff {E : Set α} : (loopyOn E).Spanning X ↔ X ⊆ E := by rw [spanning_iff, loopyOn_closure_eq, loopyOn_ground, and_iff_right rfl] @[simp] lemma freeOn_closure_eq (E X : Set α) : (freeOn E).closure X = X ∩ E := by simp +contextual [← closure_inter_ground _ X, Set.ext_iff, and_comm, insert_subset_iff, freeOn_indep_iff, (freeOn_indep inter_subset_right).mem_closure_iff'] @[simp] lemma uniqueBaseOn_closure_eq (I E X : Set α) : (uniqueBaseOn I E).closure X = (X ∩ I ∩ E) ∪ (E \ I) := by rw [uniqueBaseOn, restrict_closure_eq', freeOn_closure_eq, inter_right_comm, inter_assoc (c := E), inter_self, inter_right_comm, freeOn_ground] lemma closure_empty_eq_ground_iff : M.closure ∅ = M.E ↔ M = loopyOn M.E := by refine ⟨fun h ↦ ext_closure ?_, fun h ↦ by rw [h, loopyOn_closure_eq, loopyOn_ground]⟩ refine fun X ↦ subset_antisymm (by simp [closure_subset_ground]) ?_ rw [loopyOn_closure_eq, ← h] exact M.closure_mono (empty_subset _) @[simp] lemma comap_closure_eq {β : Type*} (M : Matroid β) (f : α → β) (X : Set α) : (M.comap f).closure X = f ⁻¹' M.closure (f '' X) := by -- Use a choice of basis and extensionality to change the goal to a statement about independence. obtain ⟨I, hI⟩ := (M.comap f).exists_isBasis' X obtain ⟨hI', hIinj, -⟩ := comap_isBasis'_iff.1 hI simp_rw [← hI.closure_eq_closure, ← hI'.closure_eq_closure, Set.ext_iff, hI.indep.mem_closure_iff', comap_ground_eq, mem_preimage, hI'.indep.mem_closure_iff', comap_indep_iff, and_imp, mem_image, and_congr_right_iff, ← image_insert_eq] -- the lemma now easily follows by considering elements/non-elements of `I` separately. intro x hxE by_cases hxI : x ∈ I · simp [hxI, show ∃ y ∈ I, f y = f x from ⟨x, hxI, rfl⟩] simp [hxI, injOn_insert hxI, hIinj] @[simp] lemma map_closure_eq {β : Type*} (M : Matroid α) (f : α → β) (hf) (X : Set β) : (M.map f hf).closure X = f '' M.closure (f ⁻¹' X) := by -- It is enough to prove that `map` and `closure` commute for `M`-independent sets. suffices aux : ∀ ⦃I⦄, M.Indep I → (M.map f hf).closure (f '' I) = f '' (M.closure I) by obtain ⟨I, hI⟩ := M.exists_isBasis (f ⁻¹' X ∩ M.E) rw [← closure_inter_ground, map_ground, ← M.closure_inter_ground, ← hI.closure_eq_closure, ← aux hI.indep, ← image_preimage_inter, ← (hI.map hf).closure_eq_closure] -- Let `I` be independent, and transform the goal using closure/independence lemmas refine fun I hI ↦ Set.ext fun e ↦ ?_ simp only [(hI.map f hf).mem_closure_iff', map_ground, mem_image, map_indep_iff, forall_exists_index, and_imp, hI.mem_closure_iff'] -- The goal now easily follows from the invariance of independence under maps. constructor · rintro ⟨⟨x, hxE, rfl⟩, h2⟩ refine ⟨x, ⟨hxE, fun hI' ↦ ?_⟩, rfl⟩ obtain ⟨y, hyI, hfy⟩ := h2 _ hI' image_insert_eq.symm rw [hf.eq_iff (hI.subset_ground hyI) hxE] at hfy rwa [← hfy] rintro ⟨x, ⟨hxE, hxi⟩, rfl⟩ refine ⟨⟨x, hxE, rfl⟩, fun J hJ hJI ↦ ⟨x, hxi ?_, rfl⟩⟩ replace hJ := hJ.map f hf have hrw := image_insert_eq ▸ hJI rwa [← hrw, map_image_indep_iff (insert_subset hxE hI.subset_ground)] at hJ lemma restrict_spanning_iff (hSR : S ⊆ R) (hR : R ⊆ M.E := by aesop_mat) : (M ↾ R).Spanning S ↔ R ⊆ M.closure S := by rw [spanning_iff, restrict_ground_eq, and_iff_left hSR, restrict_closure_eq _ hSR, inter_eq_right] lemma restrict_spanning_iff' : (M ↾ R).Spanning S ↔ R ∩ M.E ⊆ M.closure S ∧ S ⊆ R := by rw [spanning_iff, restrict_closure_eq', restrict_ground_eq, and_congr_left_iff, diff_eq_compl_inter, ← union_inter_distrib_right, inter_eq_right, union_comm, ← diff_subset_iff, diff_compl] intro hSR rw [inter_eq_self_of_subset_left hSR] end Constructions end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Map.lean
import Mathlib.Combinatorics.Matroid.Constructions import Mathlib.Data.Set.Notation /-! # Maps between matroids This file defines maps and comaps, which move a matroid on one type to a matroid on another using a function between the types. The constructions are (up to isomorphism) just combinations of restrictions and parallel extensions, so are not mathematically difficult. Because a matroid `M : Matroid α` is defined with am embedded ground set `M.E : Set α` which contains all the structure of `M`, there are several types of map and comap one could reasonably ask for; for instance, we could map `M : Matroid α` to a `Matroid β` using either a function `f : α → β`, a function `f : ↑M.E → β` or indeed a function `f : ↑M.E → ↑E` for some `E : Set β`. We attempt to give definitions that capture most reasonable use cases. `Matroid.map` and `Matroid.comap` are defined in terms of bare functions rather than functions defined on subtypes, so are often easier to work in practice than the subtype variants. In fact, the statement that `N = Matroid.map M f _` for some `f : α → β` is equivalent to the existence of an isomorphism from `M` to `N`, except in the trivial degenerate case where `M` is an empty matroid on a nonempty type and `N` is an empty matroid on an empty type. This can be simpler to use than an actual formal isomorphism, which requires subtypes. ## Main definitions In the definitions below, `M` and `N` are matroids on `α` and `β` respectively. * For `f : α → β`, `Matroid.comap N f` is the matroid on `α` with ground set `f ⁻¹' N.E` in which each `I` is independent if and only if `f` is injective on `I` and `f '' I` is independent in `N`. (For each nonloop `x` of `N`, the set `f ⁻¹' {x}` is a parallel class of `N.comap f`) * `Matroid.comapOn N f E` is the restriction of `N.comap f` to `E` for some `E : Set α`. * For an embedding `f : M.E ↪ β` defined on the subtype `↑M.E`, `Matroid.mapSetEmbedding M f` is the matroid on `β` with ground set `range f` whose independent sets are the images of those in `M`. This matroid is isomorphic to `M`. * For a function `f : α → β` and a proof `hf` that `f` is injective on `M.E`, `Matroid.map f hf` is the matroid on `β` with ground set `f '' M.E` whose independent sets are the images of those in `M`. This matroid is isomorphic to `M`, and does not depend on the values `f` takes outside `M.E`. * `Matroid.mapEmbedding f` is a version of `Matroid.map` where `f : α ↪ β` is a bundled embedding. It is defined separately because the global injectivity of `f` gives some nicer `simp` lemmas. * `Matroid.mapEquiv f` is a version of `Matroid.map` where `f : α ≃ β` is a bundled equivalence. It is defined separately because we get even nicer `simp` lemmas. * `Matroid.mapSetEquiv f` is a version of `Matroid.map` where `f : M.E ≃ E` is an equivalence on subtypes. It gives a matroid on `β` with ground set `E`. * For `X : Set α`, `Matroid.restrictSubtype M X` is the `Matroid ↥X` with ground set `univ : Set ↥X`. This matroid is isomorphic to `M ↾ X`. ## Implementation details The definition of `comap` is the only place where we need to actually define a matroid from scratch. After `comap` is defined, we can define `map` and its variants indirectly in terms of `comap`. If `f : α → β` is injective on `M.E`, the independent sets of `M.map f hf` are the images of the independent set of `M`; i.e. `(M.map f hf).Indep I ↔ ∃ I₀, M.Indep I₀ ∧ I = f '' I₀`. But if `f` is globally injective, we can phrase this more directly; indeed, `(M.map f _).Indep I ↔ M.Indep (f ⁻¹' I) ∧ I ⊆ range f`. If `f` is an equivalence we have `(M.map f _).Indep I ↔ M.Indep (f.symm '' I)`. In order that these stronger statements can be `@[simp]`, we define `mapEmbedding` and `mapEquiv` separately from `map`. ## Notes For finite matroids, both maps and comaps are a special case of a construction of Perfect [perfect1969matroid] in which a matroid structure can be transported across an arbitrary bipartite graph that may not correspond to a function at all (See [oxley2011], Theorem 11.2.12). It would have been nice to use this more general construction as a basis for the definition of both `Matroid.map` and `Matroid.comap`. Unfortunately, we can't do this, because the construction doesn't extend to infinite matroids. Specifically, if `M₁` and `M₂` are matroids on the same type `α`, and `f` is the natural function from `α ⊕ α` to `α`, then the images under `f` of the independent sets of the direct sum `M₁ ⊕ M₂` are the independent sets of a matroid if and only if the union of `M₁` and `M₂` is a matroid, and unions do not exist for some pairs of infinite matroids: see [aignerhorev2012infinite]. For this reason, `Matroid.map` requires injectivity to be well-defined in general. ## TODO * Bundled matroid isomorphisms. * Maps of finite matroids across bipartite graphs. ## References * [E. Aigner-Horev, J. Carmesin, J. Fröhlic, Infinite Matroid Union][aignerhorev2012infinite] * [H. Perfect, Independence Spaces and Combinatorial Problems][perfect1969matroid] * [J. Oxley, Matroid Theory][oxley2011] -/ assert_not_exists Field open Set Function Set.Notation namespace Matroid variable {α β : Type*} {f : α → β} {E I : Set α} {M : Matroid α} {N : Matroid β} section comap /-- The pullback of a matroid on `β` by a function `f : α → β` to a matroid on `α`. Elements with the same (nonloop) image are parallel and the ground set is `f ⁻¹' M.E`. The matroids `M.comap f` and `M ↾ range f` have isomorphic simplifications; the preimage of each nonloop of `M ↾ range f` is a parallel class. -/ def comap (N : Matroid β) (f : α → β) : Matroid α := IndepMatroid.matroid <| { E := f ⁻¹' N.E Indep := fun I ↦ N.Indep (f '' I) ∧ InjOn f I indep_empty := by simp indep_subset := fun _ _ h hIJ ↦ ⟨h.1.subset (image_mono hIJ), InjOn.mono hIJ h.2⟩ indep_aug := by rintro I B ⟨hI, hIinj⟩ hImax hBmax obtain ⟨I', hII', hI', hI'inj⟩ := (not_maximal_subset_iff ⟨hI, hIinj⟩).1 hImax have h₁ : ¬(N ↾ range f).IsBase (f '' I) := by refine fun hB ↦ hII'.ne ?_ have h_im := hB.eq_of_subset_indep (by simpa) (image_mono hII'.subset) rwa [hI'inj.image_eq_image_iff hII'.subset Subset.rfl] at h_im have h₂ : (N ↾ range f).IsBase (f '' B) := by refine Indep.isBase_of_forall_insert (by simpa using hBmax.1.1) ?_ rintro _ ⟨⟨e, heB, rfl⟩, hfe⟩ hi rw [restrict_indep_iff, ← image_insert_eq] at hi have hinj : InjOn f (insert e B) := by rw [injOn_insert (fun heB ↦ hfe (mem_image_of_mem f heB))] exact ⟨hBmax.1.2, hfe⟩ refine hBmax.not_prop_of_ssuperset (t := insert e B) (ssubset_insert ?_) ⟨hi.1, hinj⟩ exact fun heB ↦ hfe <| mem_image_of_mem f heB obtain ⟨_, ⟨⟨e, he, rfl⟩, he'⟩, hei⟩ := Indep.exists_insert_of_not_isBase (by simpa) h₁ h₂ have heI : e ∉ I := fun heI ↦ he' (mem_image_of_mem f heI) rw [← image_insert_eq, restrict_indep_iff] at hei exact ⟨e, ⟨he, heI⟩, hei.1, (injOn_insert heI).2 ⟨hIinj, he'⟩⟩ indep_maximal := by rintro X - I ⟨hI, hIinj⟩ hIX obtain ⟨J, hJ⟩ := (N ↾ range f).existsMaximalSubsetProperty_indep (f '' X) (by simp) (f '' I) (by simpa) (image_mono hIX) simp only [restrict_indep_iff, image_subset_iff, maximal_subset_iff, and_imp, and_assoc] at hJ ⊢ obtain ⟨hIJ, hJ, hJf, hJX, hJmax⟩ := hJ obtain ⟨J₀, hIJ₀, hJ₀X, hbj⟩ := hIinj.bijOn_image.exists_extend_of_subset hIX (image_mono hIJ) (image_subset_iff.2 <| preimage_mono hJX) obtain rfl : f '' J₀ = J := by rw [← image_preimage_eq_of_subset hJf, hbj.image_eq] refine ⟨J₀, hIJ₀, hJ, hbj.injOn, hJ₀X, fun K hK hKinj hKX hJ₀K ↦ ?_⟩ rw [← hKinj.image_eq_image_iff hJ₀K Subset.rfl, hJmax hK (image_subset_range _ _) (image_mono hKX) (image_mono hJ₀K)] subset_ground := fun _ hI e heI ↦ hI.1.subset_ground ⟨e, heI, rfl⟩ } @[simp] lemma comap_indep_iff : (N.comap f).Indep I ↔ N.Indep (f '' I) ∧ InjOn f I := Iff.rfl @[simp] lemma comap_ground_eq (N : Matroid β) (f : α → β) : (N.comap f).E = f ⁻¹' N.E := rfl @[simp] lemma comap_dep_iff : (N.comap f).Dep I ↔ N.Dep (f '' I) ∨ (N.Indep (f '' I) ∧ ¬ InjOn f I) := by rw [Dep, comap_indep_iff, not_and, comap_ground_eq, Dep, image_subset_iff] refine ⟨by grind, ?_⟩ rintro (⟨hI, hIE⟩ | hI) · exact ⟨fun h ↦ (hI h).elim, hIE⟩ rw [iff_true_intro hI.1, iff_true_intro hI.2, implies_true, true_and] simpa using hI.1.subset_ground @[simp] lemma comap_id (N : Matroid β) : N.comap id = N := ext_indep rfl <| by simp [injective_id.injOn] lemma comap_indep_iff_of_injOn (hf : InjOn f (f ⁻¹' N.E)) : (N.comap f).Indep I ↔ N.Indep (f '' I) := by rw [comap_indep_iff, and_iff_left_iff_imp] refine fun hi ↦ hf.mono <| subset_trans ?_ (preimage_mono hi.subset_ground) apply subset_preimage_image @[simp] lemma comap_emptyOn (f : α → β) : comap (emptyOn β) f = emptyOn α := by simp [← ground_eq_empty_iff] @[simp] lemma comap_loopyOn (f : α → β) (E : Set β) : comap (loopyOn E) f = loopyOn (f ⁻¹' E) := by rw [eq_loopyOn_iff]; aesop @[simp] lemma comap_isBasis_iff {I X : Set α} : (N.comap f).IsBasis I X ↔ N.IsBasis (f '' I) (f '' X) ∧ I.InjOn f ∧ I ⊆ X := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · obtain ⟨hI, hinj⟩ := comap_indep_iff.1 h.indep refine ⟨hI.isBasis_of_forall_insert (image_mono h.subset) fun e he ↦ ?_, hinj, h.subset⟩ simp only [mem_diff, mem_image, not_exists, not_and] at he obtain ⟨⟨e, heX, rfl⟩, he⟩ := he have heI : e ∉ I := fun heI ↦ (he e heI rfl) replace h := h.insert_dep ⟨heX, heI⟩ simp only [comap_dep_iff, image_insert_eq, or_iff_not_imp_right, injOn_insert heI, hinj, mem_image, not_exists, not_and, true_and, not_forall, not_not] at h exact h (fun _ ↦ he) refine Indep.isBasis_of_forall_insert ?_ h.2.2 fun e ⟨heX, heI⟩ ↦ ?_ · simp [comap_indep_iff, h.1.indep, h.2] have hIE : insert e I ⊆ (N.comap f).E := by simp_rw [comap_ground_eq, ← image_subset_iff] exact (image_mono (insert_subset heX h.2.2)).trans h.1.subset_ground suffices N.Indep (insert (f e) (f '' I)) → ∃ x ∈ I, f x = f e by simpa [← not_indep_iff hIE, injOn_insert heI, h.2.1, image_insert_eq] exact h.1.mem_of_insert_indep (mem_image_of_mem f heX) @[simp] lemma comap_isBase_iff {B : Set α} : (N.comap f).IsBase B ↔ N.IsBasis (f '' B) (f '' (f ⁻¹' N.E)) ∧ B.InjOn f ∧ B ⊆ f ⁻¹' N.E := by rw [← isBasis_ground_iff, comap_isBasis_iff]; rfl @[simp] lemma comap_isBasis'_iff {I X : Set α} : (N.comap f).IsBasis' I X ↔ N.IsBasis' (f '' I) (f '' X) ∧ I.InjOn f ∧ I ⊆ X := by simp only [isBasis'_iff_isBasis_inter_ground, comap_ground_eq, comap_isBasis_iff, image_inter_preimage, subset_inter_iff, ← and_assoc, and_iff_left_iff_imp, and_imp] exact fun h _ _ ↦ (image_subset_iff.1 h.indep.subset_ground) instance comap_finitary (N : Matroid β) [N.Finitary] (f : α → β) : (N.comap f).Finitary := by refine ⟨fun I hI ↦ ?_⟩ rw [comap_indep_iff, indep_iff_forall_finite_subset_indep] simp only [forall_subset_image_iff] refine ⟨fun J hJ hfin ↦ ?_, fun x hx y hy ↦ (hI _ (pair_subset hx hy) (by simp)).2 (by simp) (by simp)⟩ obtain ⟨J', hJ'J, hJ'⟩ := (surjOn_image f J).exists_bijOn_subset rw [← hJ'.image_eq] at hfin ⊢ exact (hI J' (hJ'J.trans hJ) (hfin.of_finite_image hJ'.injOn)).1 instance comap_rankFinite (N : Matroid β) [N.RankFinite] (f : α → β) : (N.comap f).RankFinite := by obtain ⟨B, hB⟩ := (N.comap f).exists_isBase refine hB.rankFinite_of_finite ?_ simp only [comap_isBase_iff] at hB exact (hB.1.indep.finite.of_finite_image hB.2.1) end comap section comapOn variable {E B I : Set α} /-- The pullback of a matroid on `β` by a function `f : α → β` to a matroid on `α`, restricted to a ground set `E`. The matroids `M.comapOn f E` and `M ↾ (f '' E)` have isomorphic simplifications; elements with the same nonloop image are parallel. -/ def comapOn (N : Matroid β) (E : Set α) (f : α → β) : Matroid α := (N.comap f) ↾ E lemma comapOn_preimage_eq (N : Matroid β) (f : α → β) : N.comapOn (f ⁻¹' N.E) f = N.comap f := by rw [comapOn, restrict_eq_self_iff]; rfl @[simp] lemma comapOn_indep_iff : (N.comapOn E f).Indep I ↔ (N.Indep (f '' I) ∧ InjOn f I ∧ I ⊆ E) := by simp [comapOn, and_assoc] @[simp] lemma comapOn_ground_eq : (N.comapOn E f).E = E := rfl lemma comapOn_isBase_iff : (N.comapOn E f).IsBase B ↔ N.IsBasis' (f '' B) (f '' E) ∧ B.InjOn f ∧ B ⊆ E := by rw [comapOn, isBase_restrict_iff', comap_isBasis'_iff] lemma comapOn_isBase_iff_of_surjOn (h : SurjOn f E N.E) : (N.comapOn E f).IsBase B ↔ (N.IsBase (f '' B) ∧ InjOn f B ∧ B ⊆ E) := by simp_rw [comapOn_isBase_iff, and_congr_left_iff, and_imp, isBasis'_iff_isBasis_inter_ground, inter_eq_self_of_subset_right h, isBasis_ground_iff, implies_true] lemma comapOn_isBase_iff_of_bijOn (h : BijOn f E N.E) : (N.comapOn E f).IsBase B ↔ N.IsBase (f '' B) ∧ B ⊆ E := by rw [← and_iff_left_of_imp (IsBase.subset_ground (M := N.comapOn E f) (B := B)), comapOn_ground_eq, and_congr_left_iff] suffices h' : B ⊆ E → InjOn f B from fun hB ↦ by simp [hB, comapOn_isBase_iff_of_surjOn h.surjOn, h'] exact fun hBE ↦ h.injOn.mono hBE lemma comapOn_dual_eq_of_bijOn (h : BijOn f E N.E) : (N.comapOn E f)✶ = N✶.comapOn E f := by refine ext_isBase (by simp) (fun B hB ↦ ?_) rw [comapOn_isBase_iff_of_bijOn (by simpa), dual_isBase_iff, comapOn_isBase_iff_of_bijOn h, dual_isBase_iff _, comapOn_ground_eq, and_iff_left diff_subset, and_iff_left (by simpa), h.injOn.image_diff_subset (by simpa), h.image_eq] exact (h.mapsTo.mono_left (show B ⊆ E by simpa)).image_subset instance comapOn_finitary [N.Finitary] : (N.comapOn E f).Finitary := by rw [comapOn]; infer_instance instance comapOn_rankFinite [N.RankFinite] : (N.comapOn E f).RankFinite := by rw [comapOn]; infer_instance end comapOn section mapSetEmbedding /-- Map a matroid `M` to an isomorphic copy in `β` using an embedding `M.E ↪ β`. -/ def mapSetEmbedding (M : Matroid α) (f : M.E ↪ β) : Matroid β := Matroid.ofExistsMatroid (E := range f) (Indep := fun I ↦ M.Indep ↑(f ⁻¹' I) ∧ I ⊆ range f) (hM := by classical obtain (rfl | ⟨⟨e,he⟩⟩) := eq_emptyOn_or_nonempty M · refine ⟨emptyOn β, ?_⟩ simp only [emptyOn_ground] at f simp [range_eq_empty f, subset_empty_iff] have _ : Nonempty M.E := ⟨⟨e,he⟩⟩ have _ : Nonempty α := ⟨e⟩ refine ⟨M.comapOn (range f) (fun x ↦ ↑(invFunOn f univ x)), rfl, ?_⟩ simp_rw [comapOn_indep_iff, ← and_assoc, and_congr_left_iff, subset_range_iff_exists_image_eq] rintro _ ⟨I, rfl⟩ rw [← image_image, InjOn.invFunOn_image f.injective.injOn (subset_univ _), preimage_image_eq _ f.injective, and_iff_left_iff_imp] rintro - x hx y hy simp only [Subtype.val_inj] exact (invFunOn_injOn_image f univ) (image_mono (subset_univ I) hx) (image_mono (subset_univ I) hy) ) @[simp] lemma mapSetEmbedding_ground (M : Matroid α) (f : M.E ↪ β) : (M.mapSetEmbedding f).E = range f := rfl @[simp] lemma mapSetEmbedding_indep_iff {f : M.E ↪ β} {I : Set β} : (M.mapSetEmbedding f).Indep I ↔ M.Indep ↑(f ⁻¹' I) ∧ I ⊆ range f := Iff.rfl lemma Indep.exists_eq_image_of_mapSetEmbedding {f : M.E ↪ β} {I : Set β} (hI : (M.mapSetEmbedding f).Indep I) : ∃ (I₀ : Set M.E), M.Indep I₀ ∧ I = f '' I₀ := ⟨f ⁻¹' I, hI.1, Eq.symm <| image_preimage_eq_of_subset hI.2⟩ lemma mapSetEmbedding_indep_iff' {f : M.E ↪ β} {I : Set β} : (M.mapSetEmbedding f).Indep I ↔ ∃ (I₀ : Set M.E), M.Indep ↑I₀ ∧ I = f '' I₀ := by simp only [mapSetEmbedding_indep_iff, subset_range_iff_exists_image_eq] constructor · rintro ⟨hI, I, rfl⟩ exact ⟨I, by rwa [preimage_image_eq _ f.injective] at hI, rfl⟩ rintro ⟨I, hI, rfl⟩ rw [preimage_image_eq _ f.injective] exact ⟨hI, _, rfl⟩ end mapSetEmbedding section map /-- Given a function `f` that is injective on `M.E`, the copy of `M` in `β` whose independent sets are the images of those in `M`. If `β` is a nonempty type, then `N : Matroid β` is a map of `M` if and only if `M` and `N` are isomorphic. -/ def map (M : Matroid α) (f : α → β) (hf : InjOn f M.E) : Matroid β := Matroid.ofExistsMatroid (E := f '' M.E) (Indep := fun I ↦ ∃ I₀, M.Indep I₀ ∧ I = f '' I₀) (hM := by refine ⟨M.mapSetEmbedding ⟨_, hf.injective⟩, by simp, fun I ↦ ?_⟩ simp_rw [mapSetEmbedding_indep_iff', Embedding.coeFn_mk, restrict_apply, ← image_image f Subtype.val, Subtype.exists_set_subtype (p := fun J ↦ M.Indep J ∧ I = f '' J)] exact ⟨fun ⟨I₀, _, hI₀⟩ ↦ ⟨I₀, hI₀⟩, fun ⟨I₀, hI₀⟩ ↦ ⟨I₀, hI₀.1.subset_ground, hI₀⟩⟩) @[simp] lemma map_ground (M : Matroid α) (f : α → β) (hf) : (M.map f hf).E = f '' M.E := rfl @[simp] lemma map_indep_iff {hf} {I : Set β} : (M.map f hf).Indep I ↔ ∃ I₀, M.Indep I₀ ∧ I = f '' I₀ := Iff.rfl lemma Indep.map (hI : M.Indep I) (f : α → β) (hf) : (M.map f hf).Indep (f '' I) := map_indep_iff.2 ⟨I, hI, rfl⟩ lemma Indep.exists_bijOn_of_map {I : Set β} (hf) (hI : (M.map f hf).Indep I) : ∃ I₀, M.Indep I₀ ∧ BijOn f I₀ I := by obtain ⟨I₀, hI₀, rfl⟩ := hI exact ⟨I₀, hI₀, (hf.mono hI₀.subset_ground).bijOn_image⟩ lemma map_image_indep_iff {hf} {I : Set α} (hI : I ⊆ M.E) : (M.map f hf).Indep (f '' I) ↔ M.Indep I := by rw [map_indep_iff] refine ⟨fun ⟨J, hJ, hIJ⟩ ↦ ?_, fun h ↦ ⟨I, h, rfl⟩⟩ rw [hf.image_eq_image_iff hI hJ.subset_ground] at hIJ; rwa [hIJ] @[simp] lemma map_isBase_iff (M : Matroid α) (f : α → β) (hf) {B : Set β} : (M.map f hf).IsBase B ↔ ∃ B₀, M.IsBase B₀ ∧ B = f '' B₀ := by rw [isBase_iff_maximal_indep] refine ⟨fun h ↦ ?_, ?_⟩ · obtain ⟨B₀, hB₀, hbij⟩ := h.prop.exists_bijOn_of_map refine ⟨B₀, hB₀.isBase_of_maximal fun J hJ hB₀J ↦ ?_, hbij.image_eq.symm⟩ rw [← hf.image_eq_image_iff hB₀.subset_ground hJ.subset_ground, hbij.image_eq] exact h.eq_of_subset (hJ.map f hf) (hbij.image_eq ▸ image_mono hB₀J) rintro ⟨B, hB, rfl⟩ rw [maximal_subset_iff] refine ⟨hB.indep.map f hf, fun I hI hBI ↦ ?_⟩ obtain ⟨I₀, hI₀, hbij⟩ := hI.exists_bijOn_of_map rw [← hbij.image_eq, hf.image_subset_image_iff hB.subset_ground hI₀.subset_ground] at hBI rw [hB.eq_of_subset_indep hI₀ hBI, hbij.image_eq] lemma IsBase.map {B : Set α} (hB : M.IsBase B) {f : α → β} (hf) : (M.map f hf).IsBase (f '' B) := by rw [map_isBase_iff]; exact ⟨B, hB, rfl⟩ lemma map_dep_iff {hf} {D : Set β} : (M.map f hf).Dep D ↔ ∃ D₀, M.Dep D₀ ∧ D = f '' D₀ := by simp only [Dep, map_indep_iff, not_exists, not_and, map_ground, subset_image_iff] constructor · rintro ⟨h, D₀, hD₀E, rfl⟩ exact ⟨D₀, ⟨fun hd ↦ h _ hd rfl, hD₀E⟩, rfl⟩ rintro ⟨D₀, ⟨hD₀, hD₀E⟩, rfl⟩ refine ⟨fun I hI h_eq ↦ ?_, ⟨_, hD₀E, rfl⟩⟩ rw [hf.image_eq_image_iff hD₀E hI.subset_ground] at h_eq subst h_eq; contradiction lemma map_image_isBase_iff {hf} {B : Set α} (hB : B ⊆ M.E) : (M.map f hf).IsBase (f '' B) ↔ M.IsBase B := by rw [map_isBase_iff] refine ⟨fun ⟨J, hJ, hIJ⟩ ↦ ?_, fun h ↦ ⟨B, h, rfl⟩⟩ rw [hf.image_eq_image_iff hB hJ.subset_ground] at hIJ; rwa [hIJ] lemma IsBasis.map {X : Set α} (hIX : M.IsBasis I X) {f : α → β} (hf) : (M.map f hf).IsBasis (f '' I) (f '' X) := by refine (hIX.indep.map f hf).isBasis_of_forall_insert (image_mono hIX.subset) ?_ rintro _ ⟨⟨e,he,rfl⟩, he'⟩ have hss := insert_subset (hIX.subset_ground he) hIX.indep.subset_ground rw [← not_indep_iff (by simpa [← image_insert_eq] using image_mono hss)] simp only [map_indep_iff, not_exists, not_and] intro J hJ hins rw [← image_insert_eq, hf.image_eq_image_iff hss hJ.subset_ground] at hins obtain rfl := hins exact he' (mem_image_of_mem f (hIX.mem_of_insert_indep he hJ)) lemma map_isBasis_iff {I X : Set α} (f : α → β) (hf) (hI : I ⊆ M.E) (hX : X ⊆ M.E) : (M.map f hf).IsBasis (f '' I) (f '' X) ↔ M.IsBasis I X := by refine ⟨fun h ↦ ?_, fun h ↦ h.map hf⟩ obtain ⟨I', hI', hII'⟩ := map_indep_iff.1 h.indep rw [hf.image_eq_image_iff hI hI'.subset_ground] at hII' obtain rfl := hII' have hss := (hf.image_subset_image_iff hI hX).1 h.subset refine hI'.isBasis_of_maximal_subset hss (fun J hJ hIJ hJX ↦ ?_) have hIJ' := h.eq_of_subset_indep (hJ.map f hf) (image_mono hIJ) (image_mono hJX) rw [hf.image_eq_image_iff hI hJ.subset_ground] at hIJ' exact hIJ'.symm.subset lemma map_isBasis_iff' {I X : Set β} {hf} : (M.map f hf).IsBasis I X ↔ ∃ I₀ X₀, M.IsBasis I₀ X₀ ∧ I = f '' I₀ ∧ X = f '' X₀ := by refine ⟨fun h ↦ ?_, ?_⟩ · obtain ⟨I, hI, rfl⟩ := subset_image_iff.1 h.indep.subset_ground obtain ⟨X, hX, rfl⟩ := subset_image_iff.1 h.subset_ground rw [map_isBasis_iff _ _ hI hX] at h exact ⟨I, X, h, rfl, rfl⟩ rintro ⟨I, X, hIX, rfl, rfl⟩ exact hIX.map hf @[simp] lemma map_dual {hf} : (M.map f hf)✶ = M✶.map f hf := by apply ext_isBase (by simp) simp only [dual_ground, map_ground, subset_image_iff, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, dual_isBase_iff'] intro B hB simp_rw [← hf.image_diff_subset hB, map_image_isBase_iff diff_subset, map_image_isBase_iff (show B ⊆ M✶.E from hB), dual_isBase_iff hB, and_iff_left_iff_imp] exact fun _ ↦ ⟨B, hB, rfl⟩ @[simp] lemma map_emptyOn (f : α → β) : (emptyOn α).map f (by simp) = emptyOn β := by simp [← ground_eq_empty_iff] @[simp] lemma map_loopyOn (f : α → β) (hf) : (loopyOn E).map f hf = loopyOn (f '' E) := by simp [eq_loopyOn_iff] @[simp] lemma map_freeOn (f : α → β) (hf) : (freeOn E).map f hf = freeOn (f '' E) := by rw [← dual_inj]; simp @[simp] lemma map_id : M.map id (injOn_id M.E) = M := by simp [ext_iff_indep] lemma map_comap {f : α → β} (h_range : N.E ⊆ range f) (hf : InjOn f (f ⁻¹' N.E)) : (N.comap f).map f hf = N := by refine ext_indep (by simpa [image_preimage_eq_iff]) ?_ simp only [map_ground, comap_ground_eq, map_indep_iff, comap_indep_iff, forall_subset_image_iff] exact fun I hI ↦ ⟨by grind, fun h ↦ ⟨_, ⟨h, hf.mono hI⟩, rfl⟩⟩ lemma comap_map {f : α → β} (hf : f.Injective) : (M.map f hf.injOn).comap f = M := by simp [ext_iff_indep, preimage_image_eq _ hf, and_iff_left hf.injOn, image_eq_image hf] instance [M.Nonempty] {f : α → β} (hf) : (M.map f hf).Nonempty := ⟨by simp [M.ground_nonempty]⟩ instance [M.Finite] {f : α → β} (hf) : (M.map f hf).Finite := ⟨M.ground_finite.image f⟩ instance [M.Finitary] {f : α → β} (hf) : (M.map f hf).Finitary := by refine ⟨fun I hI ↦ ?_⟩ simp only [map_indep_iff] have h' : I ⊆ f '' M.E := by intro e he obtain ⟨I₀, hI₀, h_eq⟩ := hI {e} (by simpa) (by simp) exact image_mono hI₀.subset_ground <| h_eq.subset rfl obtain ⟨I₀, hI₀E, rfl⟩ := subset_image_iff.1 h' refine ⟨I₀, indep_of_forall_finite_subset_indep _ fun J₀ hJ₀I₀ hJ₀ ↦ ?_, rfl⟩ specialize hI (f '' J₀) (image_mono hJ₀I₀) (hJ₀.image _) rwa [map_image_indep_iff (hJ₀I₀.trans hI₀E)] at hI instance [M.RankFinite] {f : α → β} (hf) : (M.map f hf).RankFinite := let ⟨_, hB⟩ := M.exists_isBase (hB.map hf).rankFinite_of_finite (hB.finite.image _) instance [M.RankPos] {f : α → β} (hf) : (M.map f hf).RankPos := let ⟨_, hB⟩ := M.exists_isBase (hB.map hf).rankPos_of_nonempty (hB.nonempty.image _) end map section mapSetEquiv /-- Map `M : Matroid α` to a `Matroid β` with ground set `E` using an equivalence `M.E ≃ E`. Defined using `Matroid.ofExistsMatroid` for better defeq. -/ def mapSetEquiv (M : Matroid α) {E : Set β} (e : M.E ≃ E) : Matroid β := Matroid.ofExistsMatroid E (fun I ↦ (M.Indep ↑(e.symm '' (E ↓∩ I)) ∧ I ⊆ E)) ⟨M.mapSetEmbedding (e.toEmbedding.trans <| Function.Embedding.subtype _), by have hrw : ∀ I : Set β, Subtype.val ∘ ⇑e ⁻¹' I = ⇑e.symm '' E ↓∩ I := fun I ↦ by ext; simp simp [Equiv.toEmbedding, Embedding.subtype, Embedding.trans, hrw]⟩ @[simp] lemma mapSetEquiv_indep_iff (M : Matroid α) {E : Set β} (e : M.E ≃ E) {I : Set β} : (M.mapSetEquiv e).Indep I ↔ M.Indep ↑(e.symm '' (E ↓∩ I)) ∧ I ⊆ E := Iff.rfl @[simp] lemma mapSetEquiv.ground (M : Matroid α) {E : Set β} (e : M.E ≃ E) : (M.mapSetEquiv e).E = E := rfl end mapSetEquiv section mapEmbedding /-- Map `M : Matroid α` across an embedding defined on all of `α` -/ def mapEmbedding (M : Matroid α) (f : α ↪ β) : Matroid β := M.map f f.injective.injOn @[simp] lemma mapEmbedding_ground_eq (M : Matroid α) (f : α ↪ β) : (M.mapEmbedding f).E = f '' M.E := rfl @[simp] lemma mapEmbedding_indep_iff {f : α ↪ β} {I : Set β} : (M.mapEmbedding f).Indep I ↔ M.Indep (f ⁻¹' I) ∧ I ⊆ range f := by rw [mapEmbedding, map_indep_iff] refine ⟨?_, fun ⟨h,h'⟩ ↦ ⟨f ⁻¹' I, h, by rwa [eq_comm, image_preimage_eq_iff]⟩⟩ rintro ⟨I, hI, rfl⟩ rw [preimage_image_eq _ f.injective] exact ⟨hI, image_subset_range _ _⟩ lemma Indep.mapEmbedding (hI : M.Indep I) (f : α ↪ β) : (M.mapEmbedding f).Indep (f '' I) := by simpa [preimage_image_eq I f.injective] lemma IsBase.mapEmbedding {B : Set α} (hB : M.IsBase B) (f : α ↪ β) : (M.mapEmbedding f).IsBase (f '' B) := by rw [Matroid.mapEmbedding, map_isBase_iff] exact ⟨B, hB, rfl⟩ lemma IsBasis.mapEmbedding {X : Set α} (hIX : M.IsBasis I X) (f : α ↪ β) : (M.mapEmbedding f).IsBasis (f '' I) (f '' X) := by apply hIX.map @[simp] lemma mapEmbedding_isBase_iff {f : α ↪ β} {B : Set β} : (M.mapEmbedding f).IsBase B ↔ M.IsBase (f ⁻¹' B) ∧ B ⊆ range f := by rw [mapEmbedding, map_isBase_iff] refine ⟨?_, fun ⟨h,h'⟩ ↦ ⟨f ⁻¹' B, h, by rwa [eq_comm, image_preimage_eq_iff]⟩⟩ rintro ⟨B, hB, rfl⟩ rw [preimage_image_eq _ f.injective] exact ⟨hB, image_subset_range _ _⟩ @[simp] lemma mapEmbedding_isBasis_iff {f : α ↪ β} {I X : Set β} : (M.mapEmbedding f).IsBasis I X ↔ M.IsBasis (f ⁻¹' I) (f ⁻¹' X) ∧ I ⊆ X ∧ X ⊆ range f := by rw [mapEmbedding, map_isBasis_iff'] refine ⟨?_, fun ⟨hb, hIX, hX⟩ ↦ ?_⟩ · rintro ⟨I, X, hIX, rfl, rfl⟩ simp [preimage_image_eq _ f.injective, image_mono hIX.subset, hIX] obtain ⟨X, rfl⟩ := subset_range_iff_exists_image_eq.1 hX obtain ⟨I, -, rfl⟩ := subset_image_iff.1 hIX exact ⟨I, X, by simpa [preimage_image_eq _ f.injective] using hb⟩ instance [M.Nonempty] {f : α ↪ β} : (M.mapEmbedding f).Nonempty := inferInstanceAs (M.map f f.injective.injOn).Nonempty instance [M.Finite] {f : α ↪ β} : (M.mapEmbedding f).Finite := inferInstanceAs (M.map f f.injective.injOn).Finite instance [M.Finitary] {f : α ↪ β} : (M.mapEmbedding f).Finitary := inferInstanceAs (M.map f f.injective.injOn).Finitary instance [M.RankFinite] {f : α ↪ β} : (M.mapEmbedding f).RankFinite := inferInstanceAs (M.map f f.injective.injOn).RankFinite instance [M.RankPos] {f : α ↪ β} : (M.mapEmbedding f).RankPos := inferInstanceAs (M.map f f.injective.injOn).RankPos end mapEmbedding section mapEquiv variable {f : α ≃ β} /-- Map `M : Matroid α` across an equivalence `α ≃ β` -/ def mapEquiv (M : Matroid α) (f : α ≃ β) : Matroid β := M.mapEmbedding f.toEmbedding @[simp] lemma mapEquiv_ground_eq (M : Matroid α) (f : α ≃ β) : (M.mapEquiv f).E = f '' M.E := rfl lemma mapEquiv_eq_map (f : α ≃ β) : M.mapEquiv f = M.map f f.injective.injOn := rfl @[simp] lemma mapEquiv_indep_iff {I : Set β} : (M.mapEquiv f).Indep I ↔ M.Indep (f.symm '' I) := by rw [mapEquiv_eq_map, map_indep_iff] exact ⟨by rintro ⟨I, hI, rfl⟩; simpa, fun h ↦ ⟨_, h, by simp⟩⟩ @[simp] lemma mapEquiv_dep_iff {D : Set β} : (M.mapEquiv f).Dep D ↔ M.Dep (f.symm '' D) := by rw [mapEquiv_eq_map, map_dep_iff] exact ⟨by rintro ⟨I, hI, rfl⟩; simpa, fun h ↦ ⟨_, h, by simp⟩⟩ @[simp] lemma mapEquiv_isBase_iff {B : Set β} : (M.mapEquiv f).IsBase B ↔ M.IsBase (f.symm '' B) := by rw [mapEquiv_eq_map, map_isBase_iff] exact ⟨by rintro ⟨I, hI, rfl⟩; simpa, fun h ↦ ⟨_, h, by simp⟩⟩ @[simp] lemma mapEquiv_isBasis_iff {α β : Type*} {M : Matroid α} (f : α ≃ β) {I X : Set β} : (M.mapEquiv f).IsBasis I X ↔ M.IsBasis (f.symm '' I) (f.symm '' X) := by rw [mapEquiv_eq_map, map_isBasis_iff'] refine ⟨fun h ↦ ?_, fun h ↦ ⟨_, _, h, by simp, by simp⟩⟩ obtain ⟨I, X, hIX, rfl, rfl⟩ := h simpa instance [M.Nonempty] {f : α ≃ β} : (M.mapEquiv f).Nonempty := inferInstanceAs (M.map f f.injective.injOn).Nonempty instance [M.Finite] {f : α ≃ β} : (M.mapEquiv f).Finite := inferInstanceAs (M.map f f.injective.injOn).Finite instance [M.Finitary] {f : α ≃ β} : (M.mapEquiv f).Finitary := inferInstanceAs (M.map f f.injective.injOn).Finitary instance [M.RankFinite] {f : α ≃ β} : (M.mapEquiv f).RankFinite := inferInstanceAs (M.map f f.injective.injOn).RankFinite instance [M.RankPos] {f : α ≃ β} : (M.mapEquiv f).RankPos := inferInstanceAs (M.map f f.injective.injOn).RankPos end mapEquiv section restrictSubtype variable {E X I : Set α} {M : Matroid α} /-- Given `M : Matroid α` and `X : Set α`, the restriction of `M` to `X`, viewed as a matroid on type `X` with ground set `univ`. Always isomorphic to `M ↾ X`. If `X = M.E`, then isomorphic to `M`. -/ def restrictSubtype (M : Matroid α) (X : Set α) : Matroid X := (M ↾ X).comap (↑) @[simp] lemma restrictSubtype_ground : (M.restrictSubtype X).E = univ := by simp [restrictSubtype] @[simp] lemma restrictSubtype_indep_iff {I : Set X} : (M.restrictSubtype X).Indep I ↔ M.Indep ((↑) '' I) := by simp [restrictSubtype, Subtype.val_injective.injOn] lemma restrictSubtype_indep_iff_of_subset (hIX : I ⊆ X) : (M.restrictSubtype X).Indep (X ↓∩ I) ↔ M.Indep I := by rw [restrictSubtype_indep_iff, image_preimage_eq_iff.2]; simpa lemma restrictSubtype_inter_indep_iff : (M.restrictSubtype X).Indep (X ↓∩ I) ↔ M.Indep (X ∩ I) := by simp [restrictSubtype, Subtype.val_injective.injOn] lemma restrictSubtype_isBasis_iff {Y : Set α} {I X : Set Y} : (M.restrictSubtype Y).IsBasis I X ↔ M.IsBasis' I X := by rw [restrictSubtype, comap_isBasis_iff, and_iff_right Subtype.val_injective.injOn, and_iff_left_of_imp, isBasis_restrict_iff', isBasis'_iff_isBasis_inter_ground] · simp exact fun h ↦ (image_subset_image_iff Subtype.val_injective).1 h.subset lemma restrictSubtype_isBase_iff {B : Set X} : (M.restrictSubtype X).IsBase B ↔ M.IsBasis' B X := by rw [restrictSubtype, comap_isBase_iff] simp [Subtype.val_injective.injOn, isBasis_restrict_iff', isBasis'_iff_isBasis_inter_ground] @[simp] lemma restrictSubtype_ground_isBase_iff {B : Set M.E} : (M.restrictSubtype M.E).IsBase B ↔ M.IsBase B := by rw [restrictSubtype_isBase_iff, isBasis'_iff_isBasis, isBasis_ground_iff] @[simp] lemma restrictSubtype_ground_isBasis_iff {I X : Set M.E} : (M.restrictSubtype M.E).IsBasis I X ↔ M.IsBasis I X := by rw [restrictSubtype_isBasis_iff, isBasis'_iff_isBasis] lemma eq_of_restrictSubtype_eq {N : Matroid α} (hM : M.E = E) (hN : N.E = E) (h : M.restrictSubtype E = N.restrictSubtype E) : M = N := by subst hM refine ext_indep (by rw [hN]) (fun I hI ↦ ?_) rwa [← restrictSubtype_indep_iff_of_subset hI, h, restrictSubtype_indep_iff_of_subset] @[simp] lemma restrictSubtype_dual : (M.restrictSubtype M.E)✶ = M✶.restrictSubtype M.E := by rw [restrictSubtype, ← comapOn_preimage_eq, comapOn_dual_eq_of_bijOn, restrict_ground_eq_self, ← dual_ground, comapOn_preimage_eq, restrictSubtype, restrict_ground_eq_self] exact ⟨by simp [MapsTo], Subtype.val_injective.injOn, by simp [SurjOn]⟩ lemma restrictSubtype_dual' (hM : M.E = E) : (M.restrictSubtype E)✶ = M✶.restrictSubtype E := by rw [← hM, restrictSubtype_dual] /-- `M.restrictSubtype X` is isomorphic to `M ↾ X`. -/ @[simp] lemma map_val_restrictSubtype_eq (M : Matroid α) (X : Set α) : (M.restrictSubtype X).map (↑) Subtype.val_injective.injOn = M ↾ X := by simp [restrictSubtype, map_comap] /-- `M.restrictSubtype M.E` is isomorphic to `M`. -/ lemma map_val_restrictSubtype_ground_eq (M : Matroid α) : (M.restrictSubtype M.E).map (↑) Subtype.val_injective.injOn = M := by simp instance [M.Finitary] {X : Set α} : (M.restrictSubtype X).Finitary := by rw [restrictSubtype]; infer_instance instance [M.RankFinite] {X : Set α} : (M.restrictSubtype X).RankFinite := by rw [restrictSubtype]; infer_instance instance [M.Finite] : (M.restrictSubtype M.E).Finite := have := M.ground_finite.to_subtype ⟨Finite.ground_finite⟩ instance [M.Nonempty] : (M.restrictSubtype M.E).Nonempty := have := M.ground_nonempty.coe_sort ⟨by simp⟩ instance [M.RankPos] : (M.restrictSubtype M.E).RankPos := by obtain ⟨B, hB⟩ := (M.restrictSubtype M.E).exists_isBase have hB' : M.IsBase ↑B := by simpa using hB.map Subtype.val_injective.injOn exact hB.rankPos_of_nonempty <| by simpa using hB'.nonempty end restrictSubtype end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Basic.lean
import Mathlib.Combinatorics.Matroid.Init import Mathlib.Data.Finite.Prod import Mathlib.Data.Set.Card import Mathlib.Data.Set.Finite.Powerset import Mathlib.Order.UpperLower.Closure /-! # Matroids A `Matroid` is a structure that combinatorially abstracts the notion of linear independence and dependence; matroids have connections with graph theory, discrete optimization, additive combinatorics and algebraic geometry. Mathematically, a matroid `M` is a structure on a set `E` comprising a collection of subsets of `E` called the bases of `M`, where the bases are required to obey certain axioms. This file gives a definition of a matroid `M` in terms of its bases, and some API relating independent sets (subsets of bases) and the notion of a basis of a set `X` (a maximal independent subset of `X`). ## Main definitions * a `Matroid α` on a type `α` is a structure comprising a 'ground set' and a suitably behaved 'base' predicate. Given `M : Matroid α` ... * `M.E` denotes the ground set of `M`, which has type `Set α` * For `B : Set α`, `M.IsBase B` means that `B` is a base of `M`. * For `I : Set α`, `M.Indep I` means that `I` is independent in `M` (that is, `I` is contained in a base of `M`). * For `D : Set α`, `M.Dep D` means that `D` is contained in the ground set of `M` but isn't independent. * For `I : Set α` and `X : Set α`, `M.IsBasis I X` means that `I` is a maximal independent subset of `X`. * `M.Finite` means that `M` has finite ground set. * `M.Nonempty` means that the ground set of `M` is nonempty. * `RankFinite M` means that the bases of `M` are finite. * `RankInfinite M` means that the bases of `M` are infinite. * `RankPos M` means that the bases of `M` are nonempty. * `Finitary M` means that a set is independent if and only if all its finite subsets are independent. * `aesop_mat` : a tactic designed to prove `X ⊆ M.E` for some set `X` and matroid `M`. ## Implementation details There are a few design decisions worth discussing. ### Finiteness The first is that our matroids are allowed to be infinite. Unlike with many mathematical structures, this isn't such an obvious choice. Finite matroids have been studied since the 1930's, and there was never controversy as to what is and isn't an example of a finite matroid - in fact, surprisingly many apparently different definitions of a matroid give rise to the same class of objects. However, generalizing different definitions of a finite matroid to the infinite in the obvious way (i.e. by simply allowing the ground set to be infinite) gives a number of different notions of 'infinite matroid' that disagree with each other, and that all lack nice properties. Many different competing notions of infinite matroid were studied through the years; in fact, the problem of which definition is the best was only really solved in 2013, when Bruhn et al. [2] showed that there is a unique 'reasonable' notion of an infinite matroid (these objects had previously defined by Higgs under the name 'B-matroid'). These are defined by adding one carefully chosen axiom to the standard set, and adapting existing axioms to not mention set cardinalities; they enjoy nearly all the nice properties of standard finite matroids. Even though at least 90% of the literature is on finite matroids, B-matroids are the definition we use, because they allow for additional generality, nearly all theorems are still true and just as easy to state, and (hopefully) the more general definition will prevent the need for a costly future refactor. The disadvantage is that developing API for the finite case is harder work (for instance, it is harder to prove that something is a matroid in the first place, and one must deal with `ℕ∞` rather than `ℕ`). For serious work on finite matroids, we provide the typeclasses `[M.Finite]` and `[RankFinite M]` and associated API. ### Cardinality Just as with bases of a vector space, all bases of a finite matroid `M` are finite and have the same cardinality; this cardinality is an important invariant known as the 'rank' of `M`. For infinite matroids, bases are not in general equicardinal; in fact the equicardinality of bases of infinite matroids is independent of ZFC [3]. What is still true is that either all bases are finite and equicardinal, or all bases are infinite. This means that the natural notion of 'size' for a set in matroid theory is given by the function `Set.encard`, which is the cardinality as a term in `ℕ∞`. We use this function extensively in building the API; it is preferable to both `Set.ncard` and `Finset.card` because it allows infinite sets to be handled without splitting into cases. ### The ground `Set` A last place where we make a consequential choice is making the ground set of a matroid a structure field of type `Set α` (where `α` is the type of 'possible matroid elements') rather than just having a type `α` of all the matroid elements. This is because of how common it is to simultaneously consider a number of matroids on different but related ground sets. For example, a matroid `M` on ground set `E` can have its structure 'restricted' to some subset `R ⊆ E` to give a smaller matroid `M ↾ R` with ground set `R`. A statement like `(M ↾ R₁) ↾ R₂ = M ↾ R₂` is mathematically obvious. But if the ground set of a matroid is a type, this doesn't typecheck, and is only true up to canonical isomorphism. Restriction is just the tip of the iceberg here; one can also 'contract' and 'delete' elements and sets of elements in a matroid to give a smaller matroid, and in practice it is common to make statements like `M₁.E = M₂.E ∩ M₃.E` and `((M ⟋ e) ↾ R) ⟋ C = M ⟋ (C ∪ {e}) ↾ R`. Such things are a nightmare to work with unless `=` is actually propositional equality (especially because the relevant coercions are usually between sets and not just elements). So the solution is that the ground set `M.E` has type `Set α`, and there are elements of type `α` that aren't in the matroid. The tradeoff is that for many statements, one now has to add hypotheses of the form `X ⊆ M.E` to make sure than `X` is actually 'in the matroid', rather than letting a 'type of matroid elements' take care of this invisibly. It still seems that this is worth it. The tactic `aesop_mat` exists specifically to discharge such goals with minimal fuss (using default values). The tactic works fairly well, but has room for improvement. A related decision is to not have matroids themselves be a typeclass. This would make things be notationally simpler (having `Base` in the presence of `[Matroid α]` rather than `M.Base` for a term `M : Matroid α`) but is again just too awkward when one has multiple matroids on the same type. In fact, in regular written mathematics, it is normal to explicitly indicate which matroid something is happening in, so our notation mirrors common practice. ### Notation We use a few nonstandard conventions in theorem names that are related to the above. First, we mirror common informal practice by referring explicitly to the `ground` set rather than the notation `E`. (Writing `ground` everywhere in a proof term would be unwieldy, and writing `E` in theorem names would be unnatural to read.) Second, because we are typically interested in subsets of the ground set `M.E`, using `Set.compl` is inconvenient, since `Xᶜ ⊆ M.E` is typically false for `X ⊆ M.E`. On the other hand (especially when duals arise), it is common to complement a set `X ⊆ M.E` *within* the ground set, giving `M.E \ X`. For this reason, we use the term `compl` in theorem names to refer to taking a set difference with respect to the ground set, rather than a complement within a type. The lemma `compl_isBase_dual` is one of the many examples of this. Finally, in theorem names, matroid predicates that apply to sets (such as `Base`, `Indep`, `IsBasis`) are typically used as suffixes rather than prefixes. For instance, we have `ground_indep_iff_isBase` rather than `indep_ground_iff_isBase`. ## References * [J. Oxley, Matroid Theory][oxley2011] * [H. Bruhn, R. Diestel, M. Kriesell, R. Pendavingh, P. Wollan, Axioms for infinite matroids, Adv. Math 239 (2013), 18-46][bruhnDiestelKriesselPendavinghWollan2013] * [N. Bowler, S. Geschke, Self-dual uniform matroids on infinite sets, Proc. Amer. Math. Soc. 144 (2016), 459-471][bowlerGeschke2015] -/ assert_not_exists Field open Set /-- A predicate `P` on sets satisfies the **exchange property** if, for all `X` and `Y` satisfying `P` and all `a ∈ X \ Y`, there exists `b ∈ Y \ X` so that swapping `a` for `b` in `X` maintains `P`. -/ def Matroid.ExchangeProperty {α : Type*} (P : Set α → Prop) : Prop := ∀ X Y, P X → P Y → ∀ a ∈ X \ Y, ∃ b ∈ Y \ X, P (insert b (X \ {a})) /-- A set `X` has the maximal subset property for a predicate `P` if every subset of `X` satisfying `P` is contained in a maximal subset of `X` satisfying `P`. -/ def Matroid.ExistsMaximalSubsetProperty {α : Type*} (P : Set α → Prop) (X : Set α) : Prop := ∀ I, P I → I ⊆ X → ∃ J, I ⊆ J ∧ Maximal (fun K ↦ P K ∧ K ⊆ X) J /-- A `Matroid α` is a ground set `E` of type `Set α`, and a nonempty collection of its subsets satisfying the exchange property and the maximal subset property. Each such set is called a `Base` of `M`. An `Indep`endent set is just a set contained in a base, but we include this predicate as a structure field for better definitional properties. In most cases, using this definition directly is not the best way to construct a matroid, since it requires specifying both the bases and independent sets. If the bases are known, use `Matroid.ofBase` or a variant. If just the independent sets are known, define an `IndepMatroid`, and then use `IndepMatroid.matroid`. -/ structure Matroid (α : Type*) where /-- `M` has a ground set `E`. -/ (E : Set α) /-- `M` has a predicate `Base` defining its bases. -/ (IsBase : Set α → Prop) /-- `M` has a predicate `Indep` defining its independent sets. -/ (Indep : Set α → Prop) /-- The `Indep`endent sets are those contained in `Base`s. -/ (indep_iff' : ∀ ⦃I⦄, Indep I ↔ ∃ B, IsBase B ∧ I ⊆ B) /-- There is at least one `Base`. -/ (exists_isBase : ∃ B, IsBase B) /-- For any bases `B`, `B'` and `e ∈ B \ B'`, there is some `f ∈ B' \ B` for which `B-e+f` is a base. -/ (isBase_exchange : Matroid.ExchangeProperty IsBase) /-- Every independent subset `I` of a set `X` for is contained in a maximal independent subset of `X`. -/ (maximality : ∀ X, X ⊆ E → Matroid.ExistsMaximalSubsetProperty Indep X) /-- Every base is contained in the ground set. -/ (subset_ground : ∀ B, IsBase B → B ⊆ E) attribute [local ext] Matroid namespace Matroid variable {α : Type*} {M : Matroid α} instance (M : Matroid α) : Nonempty {B // M.IsBase B} := nonempty_subtype.2 M.exists_isBase /-- Typeclass for a matroid having finite ground set. Just a wrapper for `M.E.Finite`. -/ @[mk_iff] protected class Finite (M : Matroid α) : Prop where /-- The ground set is finite -/ (ground_finite : M.E.Finite) /-- Typeclass for a matroid having nonempty ground set. Just a wrapper for `M.E.Nonempty`. -/ protected class Nonempty (M : Matroid α) : Prop where /-- The ground set is nonempty -/ (ground_nonempty : M.E.Nonempty) theorem ground_nonempty (M : Matroid α) [M.Nonempty] : M.E.Nonempty := Nonempty.ground_nonempty theorem ground_nonempty_iff (M : Matroid α) : M.E.Nonempty ↔ M.Nonempty := ⟨fun h ↦ ⟨h⟩, fun ⟨h⟩ ↦ h⟩ lemma nonempty_type (M : Matroid α) [h : M.Nonempty] : Nonempty α := ⟨M.ground_nonempty.some⟩ theorem ground_finite (M : Matroid α) [M.Finite] : M.E.Finite := Finite.ground_finite theorem set_finite (M : Matroid α) [M.Finite] (X : Set α) (hX : X ⊆ M.E := by aesop) : X.Finite := M.ground_finite.subset hX instance finite_of_finite [Finite α] {M : Matroid α} : M.Finite := ⟨Set.toFinite _⟩ /-- A `RankFinite` matroid is one whose bases are finite -/ @[mk_iff] class RankFinite (M : Matroid α) : Prop where /-- There is a finite base -/ exists_finite_isBase : ∃ B, M.IsBase B ∧ B.Finite instance rankFinite_of_finite (M : Matroid α) [M.Finite] : RankFinite M := ⟨M.exists_isBase.imp (fun B hB ↦ ⟨hB, M.set_finite B (M.subset_ground _ hB)⟩)⟩ /-- An `RankInfinite` matroid is one whose bases are infinite. -/ @[mk_iff] class RankInfinite (M : Matroid α) : Prop where /-- There is an infinite base -/ exists_infinite_isBase : ∃ B, M.IsBase B ∧ B.Infinite /-- A `RankPos` matroid is one whose bases are nonempty. -/ @[mk_iff] class RankPos (M : Matroid α) : Prop where /-- The empty set isn't a base -/ empty_not_isBase : ¬M.IsBase ∅ instance rankPos_nonempty {M : Matroid α} [M.RankPos] : M.Nonempty := by obtain ⟨B, hB⟩ := M.exists_isBase obtain rfl | ⟨e, heB⟩ := B.eq_empty_or_nonempty · exact False.elim <| RankPos.empty_not_isBase hB exact ⟨e, M.subset_ground B hB heB ⟩ section exchange namespace ExchangeProperty variable {IsBase : Set α → Prop} {B B' : Set α} /-- A family of sets with the exchange property is an antichain. -/ theorem antichain (exch : ExchangeProperty IsBase) (hB : IsBase B) (hB' : IsBase B') (h : B ⊆ B') : B = B' := h.antisymm (fun x hx ↦ by_contra (fun hxB ↦ let ⟨_, hy, _⟩ := exch B' B hB' hB x ⟨hx, hxB⟩; hy.2 <| h hy.1)) theorem encard_diff_le_aux {B₁ B₂ : Set α} (exch : ExchangeProperty IsBase) (hB₁ : IsBase B₁) (hB₂ : IsBase B₂) : (B₁ \ B₂).encard ≤ (B₂ \ B₁).encard := by obtain (he | hinf | ⟨e, he, hcard⟩) := (B₂ \ B₁).eq_empty_or_encard_eq_top_or_encard_diff_singleton_lt · rw [exch.antichain hB₂ hB₁ (diff_eq_empty.mp he)] · exact le_top.trans_eq hinf.symm obtain ⟨f, hf, hB'⟩ := exch B₂ B₁ hB₂ hB₁ e he have : encard (insert f (B₂ \ {e}) \ B₁) < encard (B₂ \ B₁) := by rw [insert_diff_of_mem _ hf.1, diff_diff_comm]; exact hcard have hencard := encard_diff_le_aux exch hB₁ hB' rw [insert_diff_of_mem _ hf.1, diff_diff_comm, ← union_singleton, ← diff_diff, diff_diff_right, inter_singleton_eq_empty.mpr he.2, union_empty] at hencard rw [← encard_diff_singleton_add_one he, ← encard_diff_singleton_add_one hf] gcongr termination_by (B₂ \ B₁).encard variable {B₁ B₂ : Set α} /-- For any two sets `B₁`, `B₂` in a family with the exchange property, the differences `B₁ \ B₂` and `B₂ \ B₁` have the same `ℕ∞`-cardinality. -/ theorem encard_diff_eq (exch : ExchangeProperty IsBase) (hB₁ : IsBase B₁) (hB₂ : IsBase B₂) : (B₁ \ B₂).encard = (B₂ \ B₁).encard := (encard_diff_le_aux exch hB₁ hB₂).antisymm (encard_diff_le_aux exch hB₂ hB₁) /-- Any two sets `B₁`, `B₂` in a family with the exchange property have the same `ℕ∞`-cardinality. -/ theorem encard_isBase_eq (exch : ExchangeProperty IsBase) (hB₁ : IsBase B₁) (hB₂ : IsBase B₂) : B₁.encard = B₂.encard := by rw [← encard_diff_add_encard_inter B₁ B₂, exch.encard_diff_eq hB₁ hB₂, inter_comm, encard_diff_add_encard_inter] end ExchangeProperty end exchange section aesop /-- The `aesop_mat` tactic attempts to prove a set is contained in the ground set of a matroid. It uses a `[Matroid]` ruleset, and is allowed to fail. -/ macro (name := aesop_mat) "aesop_mat" c:Aesop.tactic_clause* : tactic => `(tactic| aesop $c* (config := {terminal := true}) (rule_sets := [$(Lean.mkIdent `Matroid):ident])) /- We add a number of trivial lemmas (deliberately specialized to statements in terms of the ground set of a matroid) to the ruleset `Matroid` for `aesop`. -/ variable {X Y : Set α} {e : α} @[aesop unsafe 5% (rule_sets := [Matroid])] private theorem inter_right_subset_ground (hX : X ⊆ M.E) : X ∩ Y ⊆ M.E := inter_subset_left.trans hX @[aesop unsafe 5% (rule_sets := [Matroid])] private theorem inter_left_subset_ground (hX : X ⊆ M.E) : Y ∩ X ⊆ M.E := inter_subset_right.trans hX @[aesop unsafe 5% (rule_sets := [Matroid])] private theorem diff_subset_ground (hX : X ⊆ M.E) : X \ Y ⊆ M.E := diff_subset.trans hX @[aesop unsafe 10% (rule_sets := [Matroid])] private theorem ground_diff_subset_ground : M.E \ X ⊆ M.E := diff_subset_ground rfl.subset @[aesop unsafe 10% (rule_sets := [Matroid])] private theorem singleton_subset_ground (he : e ∈ M.E) : {e} ⊆ M.E := singleton_subset_iff.mpr he @[aesop unsafe 5% (rule_sets := [Matroid])] private theorem subset_ground_of_subset (hXY : X ⊆ Y) (hY : Y ⊆ M.E) : X ⊆ M.E := hXY.trans hY @[aesop unsafe 5% (rule_sets := [Matroid])] private theorem mem_ground_of_mem_of_subset (hX : X ⊆ M.E) (heX : e ∈ X) : e ∈ M.E := hX heX @[aesop safe (rule_sets := [Matroid])] private theorem insert_subset_ground {e : α} {X : Set α} {M : Matroid α} (he : e ∈ M.E) (hX : X ⊆ M.E) : insert e X ⊆ M.E := insert_subset he hX @[aesop safe (rule_sets := [Matroid])] private theorem ground_subset_ground {M : Matroid α} : M.E ⊆ M.E := rfl.subset attribute [aesop safe (rule_sets := [Matroid])] empty_subset union_subset iUnion_subset end aesop section IsBase variable {B B₁ B₂ : Set α} @[aesop unsafe 10% (rule_sets := [Matroid])] theorem IsBase.subset_ground (hB : M.IsBase B) : B ⊆ M.E := M.subset_ground B hB theorem IsBase.exchange {e : α} (hB₁ : M.IsBase B₁) (hB₂ : M.IsBase B₂) (hx : e ∈ B₁ \ B₂) : ∃ y ∈ B₂ \ B₁, M.IsBase (insert y (B₁ \ {e})) := M.isBase_exchange B₁ B₂ hB₁ hB₂ _ hx theorem IsBase.exchange_mem {e : α} (hB₁ : M.IsBase B₁) (hB₂ : M.IsBase B₂) (hxB₁ : e ∈ B₁) (hxB₂ : e ∉ B₂) : ∃ y, (y ∈ B₂ ∧ y ∉ B₁) ∧ M.IsBase (insert y (B₁ \ {e})) := by simpa using hB₁.exchange hB₂ ⟨hxB₁, hxB₂⟩ theorem IsBase.eq_of_subset_isBase (hB₁ : M.IsBase B₁) (hB₂ : M.IsBase B₂) (hB₁B₂ : B₁ ⊆ B₂) : B₁ = B₂ := M.isBase_exchange.antichain hB₁ hB₂ hB₁B₂ theorem IsBase.not_isBase_of_ssubset {X : Set α} (hB : M.IsBase B) (hX : X ⊂ B) : ¬ M.IsBase X := fun h ↦ hX.ne (h.eq_of_subset_isBase hB hX.subset) theorem IsBase.insert_not_isBase {e : α} (hB : M.IsBase B) (heB : e ∉ B) : ¬ M.IsBase (insert e B) := fun h ↦ h.not_isBase_of_ssubset (ssubset_insert heB) hB theorem IsBase.encard_diff_comm (hB₁ : M.IsBase B₁) (hB₂ : M.IsBase B₂) : (B₁ \ B₂).encard = (B₂ \ B₁).encard := M.isBase_exchange.encard_diff_eq hB₁ hB₂ theorem IsBase.ncard_diff_comm (hB₁ : M.IsBase B₁) (hB₂ : M.IsBase B₂) : (B₁ \ B₂).ncard = (B₂ \ B₁).ncard := by rw [ncard_def, hB₁.encard_diff_comm hB₂, ← ncard_def] theorem IsBase.encard_eq_encard_of_isBase (hB₁ : M.IsBase B₁) (hB₂ : M.IsBase B₂) : B₁.encard = B₂.encard := by rw [M.isBase_exchange.encard_isBase_eq hB₁ hB₂] theorem IsBase.ncard_eq_ncard_of_isBase (hB₁ : M.IsBase B₁) (hB₂ : M.IsBase B₂) : B₁.ncard = B₂.ncard := by rw [ncard_def B₁, hB₁.encard_eq_encard_of_isBase hB₂, ← ncard_def] theorem IsBase.finite_of_finite {B' : Set α} (hB : M.IsBase B) (h : B.Finite) (hB' : M.IsBase B') : B'.Finite := (finite_iff_finite_of_encard_eq_encard (hB.encard_eq_encard_of_isBase hB')).mp h theorem IsBase.infinite_of_infinite (hB : M.IsBase B) (h : B.Infinite) (hB₁ : M.IsBase B₁) : B₁.Infinite := by_contra (fun hB_inf ↦ (hB₁.finite_of_finite (not_infinite.mp hB_inf) hB).not_infinite h) theorem IsBase.finite [RankFinite M] (hB : M.IsBase B) : B.Finite := let ⟨_,hB₀⟩ := ‹RankFinite M›.exists_finite_isBase hB₀.1.finite_of_finite hB₀.2 hB theorem IsBase.infinite [RankInfinite M] (hB : M.IsBase B) : B.Infinite := let ⟨_,hB₀⟩ := ‹RankInfinite M›.exists_infinite_isBase hB₀.1.infinite_of_infinite hB₀.2 hB theorem empty_not_isBase [h : RankPos M] : ¬M.IsBase ∅ := h.empty_not_isBase theorem IsBase.nonempty [RankPos M] (hB : M.IsBase B) : B.Nonempty := by rw [nonempty_iff_ne_empty]; rintro rfl; exact M.empty_not_isBase hB theorem IsBase.rankPos_of_nonempty (hB : M.IsBase B) (h : B.Nonempty) : M.RankPos := by rw [rankPos_iff] intro he obtain rfl := he.eq_of_subset_isBase hB (empty_subset B) simp at h theorem IsBase.rankFinite_of_finite (hB : M.IsBase B) (hfin : B.Finite) : RankFinite M := ⟨⟨B, hB, hfin⟩⟩ theorem IsBase.rankInfinite_of_infinite (hB : M.IsBase B) (h : B.Infinite) : RankInfinite M := ⟨⟨B, hB, h⟩⟩ theorem not_rankFinite (M : Matroid α) [RankInfinite M] : ¬ RankFinite M := by intro h; obtain ⟨B,hB⟩ := M.exists_isBase; exact hB.infinite hB.finite theorem not_rankInfinite (M : Matroid α) [RankFinite M] : ¬ RankInfinite M := by intro h; obtain ⟨B,hB⟩ := M.exists_isBase; exact hB.infinite hB.finite theorem rankFinite_or_rankInfinite (M : Matroid α) : RankFinite M ∨ RankInfinite M := let ⟨B, hB⟩ := M.exists_isBase B.finite_or_infinite.imp hB.rankFinite_of_finite hB.rankInfinite_of_infinite @[simp] theorem not_rankFinite_iff (M : Matroid α) : ¬ RankFinite M ↔ RankInfinite M := M.rankFinite_or_rankInfinite.elim (fun h ↦ iff_of_false (by simpa) M.not_rankInfinite) fun h ↦ iff_of_true M.not_rankFinite h @[simp] theorem not_rankInfinite_iff (M : Matroid α) : ¬ RankInfinite M ↔ RankFinite M := by rw [← not_rankFinite_iff, not_not] theorem IsBase.diff_finite_comm (hB₁ : M.IsBase B₁) (hB₂ : M.IsBase B₂) : (B₁ \ B₂).Finite ↔ (B₂ \ B₁).Finite := finite_iff_finite_of_encard_eq_encard (hB₁.encard_diff_comm hB₂) theorem IsBase.diff_infinite_comm (hB₁ : M.IsBase B₁) (hB₂ : M.IsBase B₂) : (B₁ \ B₂).Infinite ↔ (B₂ \ B₁).Infinite := infinite_iff_infinite_of_encard_eq_encard (hB₁.encard_diff_comm hB₂) theorem ext_isBase {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E) (h : ∀ ⦃B⦄, B ⊆ M₁.E → (M₁.IsBase B ↔ M₂.IsBase B)) : M₁ = M₂ := by have h' : ∀ B, M₁.IsBase B ↔ M₂.IsBase B := fun B ↦ ⟨fun hB ↦ (h hB.subset_ground).1 hB, fun hB ↦ (h <| hB.subset_ground.trans_eq hE.symm).2 hB⟩ ext <;> simp [hE, M₁.indep_iff', M₂.indep_iff', h'] theorem ext_iff_isBase {M₁ M₂ : Matroid α} : M₁ = M₂ ↔ M₁.E = M₂.E ∧ ∀ ⦃B⦄, B ⊆ M₁.E → (M₁.IsBase B ↔ M₂.IsBase B) := ⟨fun h ↦ by simp [h], fun ⟨hE, h⟩ ↦ ext_isBase hE h⟩ theorem isBase_compl_iff_maximal_disjoint_isBase (hB : B ⊆ M.E := by aesop_mat) : M.IsBase (M.E \ B) ↔ Maximal (fun I ↦ I ⊆ M.E ∧ ∃ B, M.IsBase B ∧ Disjoint I B) B := by simp_rw [maximal_iff, and_iff_right hB, and_imp, forall_exists_index] refine ⟨fun h ↦ ⟨⟨_, h, disjoint_sdiff_right⟩, fun I hI B' ⟨hB', hIB'⟩ hBI ↦ hBI.antisymm ?_⟩, fun ⟨⟨B', hB', hBB'⟩,h⟩ ↦ ?_⟩ · rw [hB'.eq_of_subset_isBase h, ← subset_compl_iff_disjoint_right, diff_eq, compl_inter, compl_compl] at hIB' · exact fun e he ↦ (hIB' he).elim (fun h' ↦ (h' (hI he)).elim) id rw [subset_diff, and_iff_right hB'.subset_ground, disjoint_comm] exact disjoint_of_subset_left hBI hIB' rw [h diff_subset B' ⟨hB', disjoint_sdiff_left⟩] · simpa [hB'.subset_ground] simp [subset_diff, hB, hBB'] end IsBase section dep_indep /-- A subset of `M.E` is `Dep`endent if it is not `Indep`endent . -/ def Dep (M : Matroid α) (D : Set α) : Prop := ¬M.Indep D ∧ D ⊆ M.E variable {B B' I J D X : Set α} {e f : α} theorem indep_iff : M.Indep I ↔ ∃ B, M.IsBase B ∧ I ⊆ B := M.indep_iff' (I := I) theorem setOf_indep_eq (M : Matroid α) : {I | M.Indep I} = lowerClosure ({B | M.IsBase B}) := by simp_rw [indep_iff, lowerClosure, LowerSet.coe_mk, mem_setOf, le_eq_subset] theorem Indep.exists_isBase_superset (hI : M.Indep I) : ∃ B, M.IsBase B ∧ I ⊆ B := indep_iff.1 hI theorem dep_iff : M.Dep D ↔ ¬M.Indep D ∧ D ⊆ M.E := Iff.rfl theorem setOf_dep_eq (M : Matroid α) : {D | M.Dep D} = {I | M.Indep I}ᶜ ∩ Iic M.E := rfl @[aesop unsafe 30% (rule_sets := [Matroid])] theorem Indep.subset_ground (hI : M.Indep I) : I ⊆ M.E := by obtain ⟨B, hB, hIB⟩ := hI.exists_isBase_superset exact hIB.trans hB.subset_ground @[aesop unsafe 20% (rule_sets := [Matroid])] theorem Dep.subset_ground (hD : M.Dep D) : D ⊆ M.E := hD.2 theorem indep_or_dep (hX : X ⊆ M.E := by aesop_mat) : M.Indep X ∨ M.Dep X := by rw [Dep, and_iff_left hX] apply em theorem Indep.not_dep (hI : M.Indep I) : ¬ M.Dep I := fun h ↦ h.1 hI theorem Dep.not_indep (hD : M.Dep D) : ¬ M.Indep D := hD.1 theorem dep_of_not_indep (hD : ¬ M.Indep D) (hDE : D ⊆ M.E := by aesop_mat) : M.Dep D := ⟨hD, hDE⟩ theorem indep_of_not_dep (hI : ¬ M.Dep I) (hIE : I ⊆ M.E := by aesop_mat) : M.Indep I := by_contra (fun h ↦ hI ⟨h, hIE⟩) @[simp] theorem not_dep_iff (hX : X ⊆ M.E := by aesop_mat) : ¬ M.Dep X ↔ M.Indep X := by rw [Dep, and_iff_left hX, not_not] @[simp] theorem not_indep_iff (hX : X ⊆ M.E := by aesop_mat) : ¬ M.Indep X ↔ M.Dep X := by rw [Dep, and_iff_left hX] theorem indep_iff_not_dep : M.Indep I ↔ ¬M.Dep I ∧ I ⊆ M.E := by rw [dep_iff, not_and, not_imp_not] exact ⟨fun h ↦ ⟨fun _ ↦ h, h.subset_ground⟩, fun h ↦ h.1 h.2⟩ theorem Indep.subset (hJ : M.Indep J) (hIJ : I ⊆ J) : M.Indep I := by obtain ⟨B, hB, hJB⟩ := hJ.exists_isBase_superset exact indep_iff.2 ⟨B, hB, hIJ.trans hJB⟩ theorem Dep.superset (hD : M.Dep D) (hDX : D ⊆ X) (hXE : X ⊆ M.E := by aesop_mat) : M.Dep X := dep_of_not_indep (fun hI ↦ (hI.subset hDX).not_dep hD) theorem IsBase.indep (hB : M.IsBase B) : M.Indep B := indep_iff.2 ⟨B, hB, subset_rfl⟩ @[simp] theorem empty_indep (M : Matroid α) : M.Indep ∅ := Exists.elim M.exists_isBase (fun _ hB ↦ hB.indep.subset (empty_subset _)) theorem Dep.nonempty (hD : M.Dep D) : D.Nonempty := by rw [nonempty_iff_ne_empty]; rintro rfl; exact hD.not_indep M.empty_indep theorem Indep.finite [RankFinite M] (hI : M.Indep I) : I.Finite := let ⟨_, hB, hIB⟩ := hI.exists_isBase_superset hB.finite.subset hIB theorem Indep.rankPos_of_nonempty (hI : M.Indep I) (hne : I.Nonempty) : M.RankPos := by obtain ⟨B, hB, hIB⟩ := hI.exists_isBase_superset exact hB.rankPos_of_nonempty (hne.mono hIB) theorem Indep.inter_right (hI : M.Indep I) (X : Set α) : M.Indep (I ∩ X) := hI.subset inter_subset_left theorem Indep.inter_left (hI : M.Indep I) (X : Set α) : M.Indep (X ∩ I) := hI.subset inter_subset_right theorem Indep.diff (hI : M.Indep I) (X : Set α) : M.Indep (I \ X) := hI.subset diff_subset theorem IsBase.eq_of_subset_indep (hB : M.IsBase B) (hI : M.Indep I) (hBI : B ⊆ I) : B = I := let ⟨B', hB', hB'I⟩ := hI.exists_isBase_superset hBI.antisymm (by rwa [hB.eq_of_subset_isBase hB' (hBI.trans hB'I)]) theorem isBase_iff_maximal_indep : M.IsBase B ↔ Maximal M.Indep B := by rw [maximal_subset_iff] refine ⟨fun h ↦ ⟨h.indep, fun _ ↦ h.eq_of_subset_indep⟩, fun ⟨h, h'⟩ ↦ ?_⟩ obtain ⟨B', hB', hBB'⟩ := h.exists_isBase_superset rwa [h' hB'.indep hBB'] theorem Indep.isBase_of_maximal (hI : M.Indep I) (h : ∀ ⦃J⦄, M.Indep J → I ⊆ J → I = J) : M.IsBase I := by rwa [isBase_iff_maximal_indep, maximal_subset_iff, and_iff_right hI] theorem IsBase.dep_of_ssubset (hB : M.IsBase B) (h : B ⊂ X) (hX : X ⊆ M.E := by aesop_mat) : M.Dep X := ⟨fun hX ↦ h.ne (hB.eq_of_subset_indep hX h.subset), hX⟩ theorem IsBase.dep_of_insert (hB : M.IsBase B) (heB : e ∉ B) (he : e ∈ M.E := by aesop_mat) : M.Dep (insert e B) := hB.dep_of_ssubset (ssubset_insert heB) (insert_subset he hB.subset_ground) theorem IsBase.mem_of_insert_indep (hB : M.IsBase B) (heB : M.Indep (insert e B)) : e ∈ B := by_contra fun he ↦ (hB.dep_of_insert he (heB.subset_ground (mem_insert _ _))).not_indep heB /-- If the difference of two IsBases is a singleton, then they differ by an insertion/removal -/ theorem IsBase.eq_exchange_of_diff_eq_singleton (hB : M.IsBase B) (hB' : M.IsBase B') (h : B \ B' = {e}) : ∃ f ∈ B' \ B, B' = (insert f B) \ {e} := by obtain ⟨f, hf, hb⟩ := hB.exchange hB' (h.symm.subset (mem_singleton e)) have hne : f ≠ e := by rintro rfl; exact hf.2 (h.symm.subset (mem_singleton f)).1 rw [insert_diff_singleton_comm hne] at hb refine ⟨f, hf, (hb.eq_of_subset_isBase hB' ?_).symm⟩ rw [diff_subset_iff, insert_subset_iff, union_comm, ← diff_subset_iff, h, and_iff_left rfl.subset] exact Or.inl hf.1 theorem IsBase.exchange_isBase_of_indep (hB : M.IsBase B) (hf : f ∉ B) (hI : M.Indep (insert f (B \ {e}))) : M.IsBase (insert f (B \ {e})) := by obtain ⟨B', hB', hIB'⟩ := hI.exists_isBase_superset have hcard := hB'.encard_diff_comm hB rw [insert_subset_iff, ← diff_eq_empty, diff_diff_comm, diff_eq_empty, subset_singleton_iff_eq] at hIB' obtain ⟨hfB, (h | h)⟩ := hIB' · rw [h, encard_empty, encard_eq_zero, eq_empty_iff_forall_notMem] at hcard exact (hcard f ⟨hfB, hf⟩).elim rw [h, encard_singleton, encard_eq_one] at hcard obtain ⟨x, hx⟩ := hcard obtain (rfl : f = x) := hx.subset ⟨hfB, hf⟩ simp_rw [← h, ← singleton_union, ← hx, sdiff_sdiff_right_self, inf_eq_inter, inter_comm B, diff_union_inter] exact hB' theorem IsBase.exchange_isBase_of_indep' (hB : M.IsBase B) (he : e ∈ B) (hf : f ∉ B) (hI : M.Indep (insert f B \ {e})) : M.IsBase (insert f B \ {e}) := by have hfe : f ≠ e := ne_of_mem_of_not_mem he hf |>.symm rw [← insert_diff_singleton_comm hfe] at * exact hB.exchange_isBase_of_indep hf hI lemma insert_isBase_of_insert_indep {M : Matroid α} {I : Set α} {e f : α} (he : e ∉ I) (hf : f ∉ I) (heI : M.IsBase (insert e I)) (hfI : M.Indep (insert f I)) : M.IsBase (insert f I) := by obtain rfl | hef := eq_or_ne e f · assumption simpa [diff_singleton_eq_self he, hfI] using heI.exchange_isBase_of_indep (e := e) (f := f) (by simp [hef.symm, hf]) theorem IsBase.insert_dep (hB : M.IsBase B) (h : e ∈ M.E \ B) : M.Dep (insert e B) := by rw [← not_indep_iff (insert_subset h.1 hB.subset_ground)] exact h.2 ∘ (fun hi ↦ insert_eq_self.mp (hB.eq_of_subset_indep hi (subset_insert e B)).symm) theorem Indep.exists_insert_of_not_isBase (hI : M.Indep I) (hI' : ¬M.IsBase I) (hB : M.IsBase B) : ∃ e ∈ B \ I, M.Indep (insert e I) := by obtain ⟨B', hB', hIB'⟩ := hI.exists_isBase_superset obtain ⟨x, hxB', hx⟩ := exists_of_ssubset (hIB'.ssubset_of_ne (by (rintro rfl; exact hI' hB'))) by_cases hxB : x ∈ B · exact ⟨x, ⟨hxB, hx⟩, hB'.indep.subset (insert_subset hxB' hIB')⟩ obtain ⟨e,he, hBase⟩ := hB'.exchange hB ⟨hxB',hxB⟩ exact ⟨e, ⟨he.1, notMem_subset hIB' he.2⟩, indep_iff.2 ⟨_, hBase, insert_subset_insert (subset_diff_singleton hIB' hx)⟩⟩ /-- This is the same as `Indep.exists_insert_of_not_isBase`, but phrased so that it is defeq to the augmentation axiom for independent sets. -/ theorem Indep.exists_insert_of_not_maximal (M : Matroid α) ⦃I B : Set α⦄ (hI : M.Indep I) (hInotmax : ¬ Maximal M.Indep I) (hB : Maximal M.Indep B) : ∃ x ∈ B \ I, M.Indep (insert x I) := by simp only [maximal_subset_iff, hI, not_and, not_forall, exists_prop, true_imp_iff] at hB hInotmax refine hI.exists_insert_of_not_isBase (fun hIb ↦ ?_) ?_ · obtain ⟨I', hII', hI', hne⟩ := hInotmax exact hne <| hIb.eq_of_subset_indep hII' hI' exact hB.1.isBase_of_maximal fun J hJ hBJ ↦ hB.2 hJ hBJ theorem Indep.isBase_of_forall_insert (hB : M.Indep B) (hBmax : ∀ e ∈ M.E \ B, ¬ M.Indep (insert e B)) : M.IsBase B := by refine by_contra fun hnb ↦ ?_ obtain ⟨B', hB'⟩ := M.exists_isBase obtain ⟨e, he, h⟩ := hB.exists_insert_of_not_isBase hnb hB' exact hBmax e ⟨hB'.subset_ground he.1, he.2⟩ h theorem ground_indep_iff_isBase : M.Indep M.E ↔ M.IsBase M.E := ⟨fun h ↦ h.isBase_of_maximal (fun _ hJ hEJ ↦ hEJ.antisymm hJ.subset_ground), IsBase.indep⟩ theorem IsBase.exists_insert_of_ssubset (hB : M.IsBase B) (hIB : I ⊂ B) (hB' : M.IsBase B') : ∃ e ∈ B' \ I, M.Indep (insert e I) := (hB.indep.subset hIB.subset).exists_insert_of_not_isBase (fun hI ↦ hIB.ne (hI.eq_of_subset_isBase hB hIB.subset)) hB' @[ext] theorem ext_indep {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E) (h : ∀ ⦃I⦄, I ⊆ M₁.E → (M₁.Indep I ↔ M₂.Indep I)) : M₁ = M₂ := have h' : M₁.Indep = M₂.Indep := by ext I by_cases hI : I ⊆ M₁.E · rwa [h] exact iff_of_false (fun hi ↦ hI hi.subset_ground) (fun hi ↦ hI (hi.subset_ground.trans_eq hE.symm)) ext_isBase hE (fun B _ ↦ by simp_rw [isBase_iff_maximal_indep, h']) theorem ext_iff_indep {M₁ M₂ : Matroid α} : M₁ = M₂ ↔ (M₁.E = M₂.E) ∧ ∀ ⦃I⦄, I ⊆ M₁.E → (M₁.Indep I ↔ M₂.Indep I) := ⟨fun h ↦ by (subst h; simp), fun h ↦ ext_indep h.1 h.2⟩ /-- If every base of `M₁` is independent in `M₂` and vice versa, then `M₁ = M₂`. -/ lemma ext_isBase_indep {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E) (hM₁ : ∀ ⦃B⦄, M₁.IsBase B → M₂.Indep B) (hM₂ : ∀ ⦃B⦄, M₂.IsBase B → M₁.Indep B) : M₁ = M₂ := by refine ext_indep hE fun I hIE ↦ ⟨fun hI ↦ ?_, fun hI ↦ ?_⟩ · obtain ⟨B, hB, hIB⟩ := hI.exists_isBase_superset exact (hM₁ hB).subset hIB obtain ⟨B, hB, hIB⟩ := hI.exists_isBase_superset exact (hM₂ hB).subset hIB /-- A `Finitary` matroid is one where a set is independent if and only if it all its finite subsets are independent, or equivalently a matroid whose circuits are finite. -/ @[mk_iff] class Finitary (M : Matroid α) : Prop where /-- `I` is independent if all its finite subsets are independent. -/ indep_of_forall_finite : ∀ I, (∀ J, J ⊆ I → J.Finite → M.Indep J) → M.Indep I theorem indep_of_forall_finite_subset_indep {M : Matroid α} [Finitary M] (I : Set α) (h : ∀ J, J ⊆ I → J.Finite → M.Indep J) : M.Indep I := Finitary.indep_of_forall_finite I h theorem indep_iff_forall_finite_subset_indep {M : Matroid α} [Finitary M] : M.Indep I ↔ ∀ J, J ⊆ I → J.Finite → M.Indep J := ⟨fun h _ hJI _ ↦ h.subset hJI, Finitary.indep_of_forall_finite I⟩ instance finitary_of_rankFinite {M : Matroid α} [RankFinite M] : Finitary M where indep_of_forall_finite I hI := by refine I.finite_or_infinite.elim (hI _ Subset.rfl) (fun h ↦ False.elim ?_) obtain ⟨B, hB⟩ := M.exists_isBase obtain ⟨I₀, hI₀I, hI₀fin, hI₀card⟩ := h.exists_subset_ncard_eq (B.ncard + 1) obtain ⟨B', hB', hI₀B'⟩ := (hI _ hI₀I hI₀fin).exists_isBase_superset have hle := ncard_le_ncard hI₀B' hB'.finite rw [hI₀card, hB'.ncard_eq_ncard_of_isBase hB, Nat.add_one_le_iff] at hle exact hle.ne rfl /-- Matroids obey the maximality axiom -/ theorem existsMaximalSubsetProperty_indep (M : Matroid α) : ∀ X, X ⊆ M.E → ExistsMaximalSubsetProperty M.Indep X := M.maximality end dep_indep section copy /-- create a copy of `M : Matroid α` with independence and base predicates and ground set defeq to supplied arguments that are provably equal to those of `M`. -/ @[simps] def copy (M : Matroid α) (E : Set α) (IsBase Indep : Set α → Prop) (hE : E = M.E) (hB : ∀ B, IsBase B ↔ M.IsBase B) (hI : ∀ I, Indep I ↔ M.Indep I) : Matroid α where E := E IsBase := IsBase Indep := Indep indep_iff' _ := by simp_rw [hI, hB, M.indep_iff] exists_isBase := by simp_rw [hB] exact M.exists_isBase isBase_exchange := by simp_rw [show IsBase = M.IsBase from funext (by simp [hB])] exact M.isBase_exchange maximality := by simp_rw [hE, show Indep = M.Indep from funext (by simp [hI])] exact M.maximality subset_ground := by simp_rw [hE, hB] exact M.subset_ground /-- create a copy of `M : Matroid α` with an independence predicate and ground set defeq to supplied arguments that are provably equal to those of `M`. -/ @[simps!] def copyIndep (M : Matroid α) (E : Set α) (Indep : Set α → Prop) (hE : E = M.E) (h : ∀ I, Indep I ↔ M.Indep I) : Matroid α := M.copy E M.IsBase Indep hE (fun _ ↦ Iff.rfl) h /-- create a copy of `M : Matroid α` with a base predicate and ground set defeq to supplied arguments that are provably equal to those of `M`. -/ @[simps!] def copyBase (M : Matroid α) (E : Set α) (IsBase : Set α → Prop) (hE : E = M.E) (h : ∀ B, IsBase B ↔ M.IsBase B) : Matroid α := M.copy E IsBase M.Indep hE h (fun _ ↦ Iff.rfl) end copy section IsBasis /-- A Basis for a set `X ⊆ M.E` is a maximal independent subset of `X` (Often in the literature, the word 'Basis' is used to refer to what we call a 'Base'). -/ def IsBasis (M : Matroid α) (I X : Set α) : Prop := Maximal (fun A ↦ M.Indep A ∧ A ⊆ X) I ∧ X ⊆ M.E /-- `Matroid.IsBasis' I X` is the same as `Matroid.IsBasis I X`, without the requirement that `X ⊆ M.E`. This is convenient for some API building, especially when working with rank and closure. -/ def IsBasis' (M : Matroid α) (I X : Set α) : Prop := Maximal (fun A ↦ M.Indep A ∧ A ⊆ X) I variable {B I J X Y : Set α} {e : α} theorem IsBasis'.indep (hI : M.IsBasis' I X) : M.Indep I := hI.1.1 theorem IsBasis.indep (hI : M.IsBasis I X) : M.Indep I := hI.1.1.1 theorem IsBasis.subset (hI : M.IsBasis I X) : I ⊆ X := hI.1.1.2 theorem IsBasis.isBasis' (hI : M.IsBasis I X) : M.IsBasis' I X := hI.1 theorem IsBasis'.isBasis (hI : M.IsBasis' I X) (hX : X ⊆ M.E := by aesop_mat) : M.IsBasis I X := ⟨hI, hX⟩ theorem IsBasis'.subset (hI : M.IsBasis' I X) : I ⊆ X := hI.1.2 @[aesop unsafe 15% (rule_sets := [Matroid])] theorem IsBasis.subset_ground (hI : M.IsBasis I X) : X ⊆ M.E := hI.2 theorem IsBasis.isBasis_inter_ground (hI : M.IsBasis I X) : M.IsBasis I (X ∩ M.E) := by convert hI rw [inter_eq_self_of_subset_left hI.subset_ground] @[aesop unsafe 15% (rule_sets := [Matroid])] theorem IsBasis.left_subset_ground (hI : M.IsBasis I X) : I ⊆ M.E := hI.indep.subset_ground theorem IsBasis.eq_of_subset_indep (hI : M.IsBasis I X) (hJ : M.Indep J) (hIJ : I ⊆ J) (hJX : J ⊆ X) : I = J := hIJ.antisymm (hI.1.2 ⟨hJ, hJX⟩ hIJ) theorem IsBasis.Finite (hI : M.IsBasis I X) [RankFinite M] : I.Finite := hI.indep.finite theorem isBasis_iff' : M.IsBasis I X ↔ (M.Indep I ∧ I ⊆ X ∧ ∀ ⦃J⦄, M.Indep J → I ⊆ J → J ⊆ X → I = J) ∧ X ⊆ M.E := by rw [IsBasis, maximal_subset_iff] tauto theorem isBasis_iff (hX : X ⊆ M.E := by aesop_mat) : M.IsBasis I X ↔ (M.Indep I ∧ I ⊆ X ∧ ∀ J, M.Indep J → I ⊆ J → J ⊆ X → I = J) := by rw [isBasis_iff', and_iff_left hX] theorem isBasis'_iff_isBasis_inter_ground : M.IsBasis' I X ↔ M.IsBasis I (X ∩ M.E) := by rw [IsBasis', IsBasis, and_iff_left inter_subset_right, maximal_iff_maximal_of_imp_of_forall] · exact fun I hI ↦ ⟨hI.1, hI.2.trans inter_subset_left⟩ exact fun I hI ↦ ⟨I, rfl.le, hI.1, subset_inter hI.2 hI.1.subset_ground⟩ theorem isBasis'_iff_isBasis (hX : X ⊆ M.E := by aesop_mat) : M.IsBasis' I X ↔ M.IsBasis I X := by rw [isBasis'_iff_isBasis_inter_ground, inter_eq_self_of_subset_left hX] theorem isBasis_iff_isBasis'_subset_ground : M.IsBasis I X ↔ M.IsBasis' I X ∧ X ⊆ M.E := ⟨fun h ↦ ⟨h.isBasis', h.subset_ground⟩, fun h ↦ (isBasis'_iff_isBasis h.2).mp h.1⟩ theorem IsBasis'.isBasis_inter_ground (hIX : M.IsBasis' I X) : M.IsBasis I (X ∩ M.E) := isBasis'_iff_isBasis_inter_ground.mp hIX theorem IsBasis'.eq_of_subset_indep (hI : M.IsBasis' I X) (hJ : M.Indep J) (hIJ : I ⊆ J) (hJX : J ⊆ X) : I = J := hIJ.antisymm (hI.2 ⟨hJ, hJX⟩ hIJ) theorem IsBasis'.insert_not_indep (hI : M.IsBasis' I X) (he : e ∈ X \ I) : ¬ M.Indep (insert e I) := fun hi ↦ he.2 <| insert_eq_self.1 <| Eq.symm <| hI.eq_of_subset_indep hi (subset_insert _ _) (insert_subset he.1 hI.subset) theorem isBasis_iff_maximal (hX : X ⊆ M.E := by aesop_mat) : M.IsBasis I X ↔ Maximal (fun I ↦ M.Indep I ∧ I ⊆ X) I := by rw [IsBasis, and_iff_left hX] theorem Indep.isBasis_of_maximal_subset (hI : M.Indep I) (hIX : I ⊆ X) (hmax : ∀ ⦃J⦄, M.Indep J → I ⊆ J → J ⊆ X → J ⊆ I) (hX : X ⊆ M.E := by aesop_mat) : M.IsBasis I X := by rw [isBasis_iff (by aesop_mat : X ⊆ M.E), and_iff_right hI, and_iff_right hIX] exact fun J hJ hIJ hJX ↦ hIJ.antisymm (hmax hJ hIJ hJX) theorem IsBasis.isBasis_subset (hI : M.IsBasis I X) (hIY : I ⊆ Y) (hYX : Y ⊆ X) : M.IsBasis I Y := by rw [isBasis_iff (hYX.trans hI.subset_ground), and_iff_right hI.indep, and_iff_right hIY] exact fun J hJ hIJ hJY ↦ hI.eq_of_subset_indep hJ hIJ (hJY.trans hYX) @[simp] theorem isBasis_self_iff_indep : M.IsBasis I I ↔ M.Indep I := by rw [isBasis_iff', and_iff_right rfl.subset, and_assoc, and_iff_left_iff_imp] exact fun hi ↦ ⟨fun _ _ ↦ subset_antisymm, hi.subset_ground⟩ theorem Indep.isBasis_self (h : M.Indep I) : M.IsBasis I I := isBasis_self_iff_indep.mpr h @[simp] theorem isBasis_empty_iff (M : Matroid α) : M.IsBasis I ∅ ↔ I = ∅ := ⟨fun h ↦ subset_empty_iff.mp h.subset, fun h ↦ by (rw [h]; exact M.empty_indep.isBasis_self)⟩ theorem IsBasis.dep_of_ssubset (hI : M.IsBasis I X) (hIY : I ⊂ Y) (hYX : Y ⊆ X) : M.Dep Y := by have : X ⊆ M.E := hI.subset_ground rw [← not_indep_iff] exact fun hY ↦ hIY.ne (hI.eq_of_subset_indep hY hIY.subset hYX) theorem IsBasis.insert_dep (hI : M.IsBasis I X) (he : e ∈ X \ I) : M.Dep (insert e I) := hI.dep_of_ssubset (ssubset_insert he.2) (insert_subset he.1 hI.subset) theorem IsBasis.mem_of_insert_indep (hI : M.IsBasis I X) (he : e ∈ X) (hIe : M.Indep (insert e I)) : e ∈ I := by_contra (fun heI ↦ (hI.insert_dep ⟨he, heI⟩).not_indep hIe) theorem IsBasis'.mem_of_insert_indep (hI : M.IsBasis' I X) (he : e ∈ X) (hIe : M.Indep (insert e I)) : e ∈ I := hI.isBasis_inter_ground.mem_of_insert_indep ⟨he, hIe.subset_ground (mem_insert _ _)⟩ hIe theorem IsBasis.not_isBasis_of_ssubset (hI : M.IsBasis I X) (hJI : J ⊂ I) : ¬ M.IsBasis J X := fun h ↦ hJI.ne (h.eq_of_subset_indep hI.indep hJI.subset hI.subset) theorem Indep.subset_isBasis_of_subset (hI : M.Indep I) (hIX : I ⊆ X) (hX : X ⊆ M.E := by aesop_mat) : ∃ J, M.IsBasis J X ∧ I ⊆ J := by obtain ⟨J, hJ, hJmax⟩ := M.maximality X hX I hI hIX exact ⟨J, ⟨hJmax, hX⟩, hJ⟩ theorem Indep.subset_isBasis'_of_subset (hI : M.Indep I) (hIX : I ⊆ X) : ∃ J, M.IsBasis' J X ∧ I ⊆ J := by simp_rw [isBasis'_iff_isBasis_inter_ground] exact hI.subset_isBasis_of_subset (subset_inter hIX hI.subset_ground) theorem exists_isBasis (M : Matroid α) (X : Set α) (hX : X ⊆ M.E := by aesop_mat) : ∃ I, M.IsBasis I X := let ⟨_, hI, _⟩ := M.empty_indep.subset_isBasis_of_subset (empty_subset X) ⟨_, hI⟩ theorem exists_isBasis' (M : Matroid α) (X : Set α) : ∃ I, M.IsBasis' I X := let ⟨_, hI, _⟩ := M.empty_indep.subset_isBasis'_of_subset (empty_subset X) ⟨_, hI⟩ theorem exists_isBasis_subset_isBasis (M : Matroid α) (hXY : X ⊆ Y) (hY : Y ⊆ M.E := by aesop_mat) : ∃ I J, M.IsBasis I X ∧ M.IsBasis J Y ∧ I ⊆ J := by obtain ⟨I, hI⟩ := M.exists_isBasis X (hXY.trans hY) obtain ⟨J, hJ, hIJ⟩ := hI.indep.subset_isBasis_of_subset (hI.subset.trans hXY) exact ⟨_, _, hI, hJ, hIJ⟩ theorem IsBasis.exists_isBasis_inter_eq_of_superset (hI : M.IsBasis I X) (hXY : X ⊆ Y) (hY : Y ⊆ M.E := by aesop_mat) : ∃ J, M.IsBasis J Y ∧ J ∩ X = I := by obtain ⟨J, hJ, hIJ⟩ := hI.indep.subset_isBasis_of_subset (hI.subset.trans hXY) refine ⟨J, hJ, subset_antisymm ?_ (subset_inter hIJ hI.subset)⟩ exact fun e he ↦ hI.mem_of_insert_indep he.2 (hJ.indep.subset (insert_subset he.1 hIJ)) theorem exists_isBasis_union_inter_isBasis (M : Matroid α) (X Y : Set α) (hX : X ⊆ M.E := by aesop_mat) (hY : Y ⊆ M.E := by aesop_mat) : ∃ I, M.IsBasis I (X ∪ Y) ∧ M.IsBasis (I ∩ Y) Y := let ⟨J, hJ⟩ := M.exists_isBasis Y (hJ.exists_isBasis_inter_eq_of_superset subset_union_right).imp (fun I hI ↦ ⟨hI.1, by rwa [hI.2]⟩) theorem Indep.eq_of_isBasis (hI : M.Indep I) (hJ : M.IsBasis J I) : J = I := hJ.eq_of_subset_indep hI hJ.subset rfl.subset theorem IsBasis.exists_isBase (hI : M.IsBasis I X) : ∃ B, M.IsBase B ∧ I = B ∩ X := let ⟨B,hB, hIB⟩ := hI.indep.exists_isBase_superset ⟨B, hB, subset_antisymm (subset_inter hIB hI.subset) (by rw [hI.eq_of_subset_indep (hB.indep.inter_right X) (subset_inter hIB hI.subset) inter_subset_right])⟩ @[simp] theorem isBasis_ground_iff : M.IsBasis B M.E ↔ M.IsBase B := by rw [IsBasis, and_iff_left rfl.subset, isBase_iff_maximal_indep, maximal_and_iff_right_of_imp (fun _ h ↦ h.subset_ground), and_iff_left_of_imp (fun h ↦ h.1.subset_ground)] theorem IsBase.isBasis_ground (hB : M.IsBase B) : M.IsBasis B M.E := isBasis_ground_iff.mpr hB theorem Indep.isBasis_iff_forall_insert_dep (hI : M.Indep I) (hIX : I ⊆ X) : M.IsBasis I X ↔ ∀ e ∈ X \ I, M.Dep (insert e I) := by rw [IsBasis, maximal_iff_forall_insert (fun I J hI hIJ ↦ ⟨hI.1.subset hIJ, hIJ.trans hI.2⟩)] simp only [hI, hIX, and_self, insert_subset_iff, and_true, not_and, true_and, mem_diff, and_imp, Dep, hI.subset_ground] exact ⟨fun h e heX heI ↦ ⟨fun hi ↦ h.1 e heI hi heX, h.2 heX⟩, fun h ↦ ⟨fun e heI hi heX ↦ (h e heX heI).1 hi, fun e heX ↦ (em (e ∈ I)).elim (fun h ↦ hI.subset_ground h) fun heI ↦ (h _ heX heI).2 ⟩⟩ theorem Indep.isBasis_of_forall_insert (hI : M.Indep I) (hIX : I ⊆ X) (he : ∀ e ∈ X \ I, M.Dep (insert e I)) : M.IsBasis I X := (hI.isBasis_iff_forall_insert_dep hIX).mpr he theorem Indep.isBasis_insert_iff (hI : M.Indep I) : M.IsBasis I (insert e I) ↔ M.Dep (insert e I) ∨ e ∈ I := by simp_rw [hI.isBasis_iff_forall_insert_dep (subset_insert _ _), dep_iff, insert_subset_iff, and_iff_left hI.subset_ground, mem_diff, mem_insert_iff, or_and_right, and_not_self, or_false, and_imp, forall_eq] tauto theorem IsBasis.iUnion_isBasis_iUnion {ι : Type _} (X I : ι → Set α) (hI : ∀ i, M.IsBasis (I i) (X i)) (h_ind : M.Indep (⋃ i, I i)) : M.IsBasis (⋃ i, I i) (⋃ i, X i) := by refine h_ind.isBasis_of_forall_insert (iUnion_subset (fun i ↦ (hI i).subset.trans (subset_iUnion _ _))) ?_ rintro e ⟨⟨_, ⟨⟨i, hi, rfl⟩, (hes : e ∈ X i)⟩⟩, he'⟩ rw [mem_iUnion, not_exists] at he' refine ((hI i).insert_dep ⟨hes, he' _⟩).superset (insert_subset_insert (subset_iUnion _ _)) ?_ rw [insert_subset_iff, iUnion_subset_iff, and_iff_left (fun i ↦ (hI i).indep.subset_ground)] exact (hI i).subset_ground hes theorem IsBasis.isBasis_iUnion {ι : Type _} [Nonempty ι] (X : ι → Set α) (hI : ∀ i, M.IsBasis I (X i)) : M.IsBasis I (⋃ i, X i) := by convert IsBasis.iUnion_isBasis_iUnion X (fun _ ↦ I) (fun i ↦ hI i) _ <;> rw [iUnion_const] exact (hI (Classical.arbitrary ι)).indep theorem IsBasis.isBasis_sUnion {Xs : Set (Set α)} (hne : Xs.Nonempty) (h : ∀ X ∈ Xs, M.IsBasis I X) : M.IsBasis I (⋃₀ Xs) := by rw [sUnion_eq_iUnion] have := Iff.mpr nonempty_coe_sort hne exact IsBasis.isBasis_iUnion _ fun X ↦ h X X.prop theorem Indep.isBasis_setOf_insert_isBasis (hI : M.Indep I) : M.IsBasis I {x | M.IsBasis I (insert x I)} := by refine hI.isBasis_of_forall_insert (fun e he ↦ (?_ : M.IsBasis _ _)) (fun e he ↦ ⟨fun hu ↦ he.2 ?_, he.1.subset_ground⟩) · rw [insert_eq_of_mem he]; exact hI.isBasis_self simpa using (hu.eq_of_isBasis he.1).symm theorem IsBasis.union_isBasis_union (hIX : M.IsBasis I X) (hJY : M.IsBasis J Y) (h : M.Indep (I ∪ J)) : M.IsBasis (I ∪ J) (X ∪ Y) := by rw [union_eq_iUnion, union_eq_iUnion] refine IsBasis.iUnion_isBasis_iUnion _ _ ?_ ?_ · simp only [Bool.forall_bool, cond_false, cond_true]; exact ⟨hJY, hIX⟩ rwa [← union_eq_iUnion] theorem IsBasis.isBasis_union (hIX : M.IsBasis I X) (hIY : M.IsBasis I Y) : M.IsBasis I (X ∪ Y) := by convert hIX.union_isBasis_union hIY _ <;> rw [union_self]; exact hIX.indep theorem IsBasis.isBasis_union_of_subset (hI : M.IsBasis I X) (hJ : M.Indep J) (hIJ : I ⊆ J) : M.IsBasis J (J ∪ X) := by convert hJ.isBasis_self.union_isBasis_union hI _ <;> rw [union_eq_self_of_subset_right hIJ] assumption theorem IsBasis.insert_isBasis_insert (hI : M.IsBasis I X) (h : M.Indep (insert e I)) : M.IsBasis (insert e I) (insert e X) := by simp_rw [← union_singleton] at * exact hI.union_isBasis_union (h.subset subset_union_right).isBasis_self h theorem IsBase.isBase_of_isBasis_superset (hB : M.IsBase B) (hBX : B ⊆ X) (hIX : M.IsBasis I X) : M.IsBase I := by by_contra h obtain ⟨e,heBI,he⟩ := hIX.indep.exists_insert_of_not_isBase h hB exact heBI.2 (hIX.mem_of_insert_indep (hBX heBI.1) he) theorem Indep.exists_isBase_subset_union_isBase (hI : M.Indep I) (hB : M.IsBase B) : ∃ B', M.IsBase B' ∧ I ⊆ B' ∧ B' ⊆ I ∪ B := by obtain ⟨B', hB', hIB'⟩ := hI.subset_isBasis_of_subset <| subset_union_left (t := B) exact ⟨B', hB.isBase_of_isBasis_superset subset_union_right hB', hIB', hB'.subset⟩ theorem IsBasis.inter_eq_of_subset_indep (hIX : M.IsBasis I X) (hIJ : I ⊆ J) (hJ : M.Indep J) : J ∩ X = I := (subset_inter hIJ hIX.subset).antisymm' (fun _ he ↦ hIX.mem_of_insert_indep he.2 (hJ.subset (insert_subset he.1 hIJ))) theorem IsBasis'.inter_eq_of_subset_indep (hI : M.IsBasis' I X) (hIJ : I ⊆ J) (hJ : M.Indep J) : J ∩ X = I := by rw [← hI.isBasis_inter_ground.inter_eq_of_subset_indep hIJ hJ, inter_comm X, ← inter_assoc, inter_eq_self_of_subset_left hJ.subset_ground] theorem IsBase.isBasis_of_subset (hX : X ⊆ M.E := by aesop_mat) (hB : M.IsBase B) (hBX : B ⊆ X) : M.IsBasis B X := by rw [isBasis_iff, and_iff_right hB.indep, and_iff_right hBX] exact fun J hJ hBJ _ ↦ hB.eq_of_subset_indep hJ hBJ theorem exists_isBasis_disjoint_isBasis_of_subset (M : Matroid α) {X Y : Set α} (hXY : X ⊆ Y) (hY : Y ⊆ M.E := by aesop_mat) : ∃ I J, M.IsBasis I X ∧ M.IsBasis (I ∪ J) Y ∧ Disjoint X J := by obtain ⟨I, I', hI, hI', hII'⟩ := M.exists_isBasis_subset_isBasis hXY refine ⟨I, I' \ I, hI, by rwa [union_diff_self, union_eq_self_of_subset_left hII'], ?_⟩ rw [disjoint_iff_forall_ne] rintro e heX _ ⟨heI', heI⟩ rfl exact heI <| hI.mem_of_insert_indep heX (hI'.indep.subset (insert_subset heI' hII')) end IsBasis section Finite /-- For finite `E`, finitely many matroids have ground set contained in `E`. -/ theorem finite_setOf_matroid {E : Set α} (hE : E.Finite) : {M : Matroid α | M.E ⊆ E}.Finite := by set f : Matroid α → Set α × (Set (Set α)) := fun M ↦ ⟨M.E, {B | M.IsBase B}⟩ have hf : f.Injective := by refine fun M M' hMM' ↦ ?_ rw [Prod.mk.injEq, and_comm, Set.ext_iff, and_comm] at hMM' exact ext_isBase hMM'.1 (fun B _ ↦ hMM'.2 B) rw [← Set.finite_image_iff hf.injOn] refine (hE.finite_subsets.prod hE.finite_subsets.finite_subsets).subset ?_ rintro _ ⟨M, hE : M.E ⊆ E, rfl⟩ simp only [Set.mem_prod, Set.mem_setOf_eq] exact ⟨hE, fun B hB ↦ hB.subset_ground.trans hE⟩ /-- For finite `E`, finitely many matroids have ground set `E`. -/ theorem finite_setOf_matroid' {E : Set α} (hE : E.Finite) : {M : Matroid α | M.E = E}.Finite := (finite_setOf_matroid hE).subset (fun M ↦ by rintro rfl; exact rfl.subset) end Finite end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Constructions.lean
import Mathlib.Combinatorics.Matroid.Minor.Restrict /-! # Some constructions of matroids This file defines some very elementary examples of matroids, namely those with at most one base. ## Main definitions * `emptyOn α` is the matroid on `α` with empty ground set. For `E : Set α`, ... * `loopyOn E` is the matroid on `E` whose elements are all loops, or equivalently in which `∅` is the only base. * `freeOn E` is the 'free matroid' whose ground set `E` is the only base. * For `I ⊆ E`, `uniqueBaseOn I E` is the matroid with ground set `E` in which `I` is the only base. ## Implementation details To avoid the tedious process of certifying the matroid axioms for each of these easy examples, we bootstrap the definitions starting with `emptyOn α` (which `simp` can prove is a matroid) and then construct the other examples using duality and restriction. -/ assert_not_exists Field variable {α : Type*} {M : Matroid α} {E B I X R J : Set α} namespace Matroid open Set section EmptyOn /-- The `Matroid α` with empty ground set. -/ def emptyOn (α : Type*) : Matroid α where E := ∅ IsBase := (· = ∅) Indep := (· = ∅) indep_iff' := by simp [subset_empty_iff] exists_isBase := ⟨∅, rfl⟩ isBase_exchange := by rintro _ _ rfl; simp maximality := by rintro _ _ _ rfl -; exact ⟨∅, by simp [Maximal]⟩ subset_ground := by simp @[simp] theorem emptyOn_ground : (emptyOn α).E = ∅ := rfl @[simp] theorem emptyOn_isBase_iff : (emptyOn α).IsBase B ↔ B = ∅ := Iff.rfl @[simp] theorem emptyOn_indep_iff : (emptyOn α).Indep I ↔ I = ∅ := Iff.rfl theorem ground_eq_empty_iff : (M.E = ∅) ↔ M = emptyOn α := by simp only [emptyOn, ext_iff_indep, iff_self_and] exact fun h ↦ by simp [h, subset_empty_iff] @[simp] theorem emptyOn_dual_eq : (emptyOn α)✶ = emptyOn α := by rw [← ground_eq_empty_iff]; rfl @[simp] theorem restrict_empty (M : Matroid α) : M ↾ (∅ : Set α) = emptyOn α := by simp [← ground_eq_empty_iff] theorem eq_emptyOn_or_nonempty (M : Matroid α) : M = emptyOn α ∨ Matroid.Nonempty M := by rw [← ground_eq_empty_iff] exact M.E.eq_empty_or_nonempty.elim Or.inl (fun h ↦ Or.inr ⟨h⟩) theorem eq_emptyOn [IsEmpty α] (M : Matroid α) : M = emptyOn α := by rw [← ground_eq_empty_iff] exact M.E.eq_empty_of_isEmpty instance finite_emptyOn (α : Type*) : (emptyOn α).Finite := ⟨finite_empty⟩ end EmptyOn section LoopyOn /-- The `Matroid α` with ground set `E` whose only base is `∅`. The elements are all 'loops' - see `Matroid.IsLoop` and `Matroid.loopyOn_isLoop_iff`. -/ def loopyOn (E : Set α) : Matroid α := emptyOn α ↾ E @[simp] theorem loopyOn_ground (E : Set α) : (loopyOn E).E = E := rfl @[simp] theorem loopyOn_empty (α : Type*) : loopyOn (∅ : Set α) = emptyOn α := by rw [← ground_eq_empty_iff, loopyOn_ground] @[simp] theorem loopyOn_indep_iff : (loopyOn E).Indep I ↔ I = ∅ := by simp only [loopyOn, restrict_indep_iff, emptyOn_indep_iff, and_iff_left_iff_imp] rintro rfl; apply empty_subset theorem eq_loopyOn_iff : M = loopyOn E ↔ M.E = E ∧ ∀ X ⊆ M.E, M.Indep X → X = ∅ := by simp only [ext_iff_indep, loopyOn_ground, loopyOn_indep_iff, and_congr_right_iff] rintro rfl refine ⟨fun h I hI ↦ (h hI).1, fun h I hIE ↦ ⟨h I hIE, by rintro rfl; simp⟩⟩ @[simp] theorem loopyOn_isBase_iff : (loopyOn E).IsBase B ↔ B = ∅ := by simp [Maximal, isBase_iff_maximal_indep] @[simp] theorem loopyOn_isBasis_iff : (loopyOn E).IsBasis I X ↔ I = ∅ ∧ X ⊆ E := ⟨fun h ↦ ⟨loopyOn_indep_iff.mp h.indep, h.subset_ground⟩, by rintro ⟨rfl, hX⟩; rw [isBasis_iff]; simp⟩ instance loopyOn_rankFinite : RankFinite (loopyOn E) := ⟨∅, by simp⟩ theorem Finite.loopyOn_finite (hE : E.Finite) : Matroid.Finite (loopyOn E) := ⟨hE⟩ @[simp] theorem loopyOn_restrict (E R : Set α) : (loopyOn E) ↾ R = loopyOn R := by refine ext_indep rfl ?_ simp only [restrict_ground_eq, restrict_indep_iff, loopyOn_indep_iff, and_iff_left_iff_imp] exact fun _ h _ ↦ h theorem empty_isBase_iff : M.IsBase ∅ ↔ M = loopyOn M.E := by simp only [isBase_iff_maximal_indep, Maximal, empty_indep, le_eq_subset, empty_subset, subset_empty_iff, true_implies, true_and, ext_iff_indep, loopyOn_ground, loopyOn_indep_iff] exact ⟨fun h I _ ↦ ⟨@h _, fun hI ↦ by simp [hI]⟩, fun h I hI ↦ (h hI.subset_ground).1 hI⟩ theorem eq_loopyOn_or_rankPos (M : Matroid α) : M = loopyOn M.E ∨ RankPos M := by rw [← empty_isBase_iff, rankPos_iff]; apply em theorem not_rankPos_iff : ¬RankPos M ↔ M = loopyOn M.E := by rw [rankPos_iff, not_iff_comm, empty_isBase_iff] end LoopyOn section FreeOn /-- The `Matroid α` with ground set `E` whose only base is `E`. -/ def freeOn (E : Set α) : Matroid α := (loopyOn E)✶ @[simp] theorem freeOn_ground : (freeOn E).E = E := rfl @[simp] theorem freeOn_dual_eq : (freeOn E)✶ = loopyOn E := by rw [freeOn, dual_dual] @[simp] theorem loopyOn_dual_eq : (loopyOn E)✶ = freeOn E := rfl @[simp] theorem freeOn_empty (α : Type*) : freeOn (∅ : Set α) = emptyOn α := by simp [freeOn] @[simp] theorem freeOn_isBase_iff : (freeOn E).IsBase B ↔ B = E := by simp only [freeOn, loopyOn_ground, dual_isBase_iff', loopyOn_isBase_iff, diff_eq_empty, ← subset_antisymm_iff, eq_comm (a := E)] @[simp] theorem freeOn_indep_iff : (freeOn E).Indep I ↔ I ⊆ E := by simp [indep_iff] theorem freeOn_indep (hIE : I ⊆ E) : (freeOn E).Indep I := freeOn_indep_iff.2 hIE @[simp] theorem freeOn_isBasis_iff : (freeOn E).IsBasis I X ↔ I = X ∧ X ⊆ E := by use fun h ↦ ⟨(freeOn_indep h.subset_ground).eq_of_isBasis h, h.subset_ground⟩ rintro ⟨rfl, hIE⟩ exact (freeOn_indep hIE).isBasis_self @[simp] theorem freeOn_isBasis'_iff : (freeOn E).IsBasis' I X ↔ I = X ∩ E := by rw [isBasis'_iff_isBasis_inter_ground, freeOn_isBasis_iff, freeOn_ground, and_iff_left inter_subset_right] theorem eq_freeOn_iff : M = freeOn E ↔ M.E = E ∧ M.Indep E := by refine ⟨?_, fun h ↦ ?_⟩ · rintro rfl; simp simp only [ext_iff_indep, freeOn_ground, freeOn_indep_iff, h.1, true_and] exact fun I hIX ↦ iff_of_true (h.2.subset hIX) hIX theorem ground_indep_iff_eq_freeOn : M.Indep M.E ↔ M = freeOn M.E := by simp [eq_freeOn_iff] theorem freeOn_restrict (h : R ⊆ E) : (freeOn E) ↾ R = freeOn R := by simp [h, eq_freeOn_iff] theorem restrict_eq_freeOn_iff : M ↾ I = freeOn I ↔ M.Indep I := by rw [eq_freeOn_iff, and_iff_right M.restrict_ground_eq, restrict_indep_iff, and_iff_left Subset.rfl] theorem Indep.restrict_eq_freeOn (hI : M.Indep I) : M ↾ I = freeOn I := by rwa [restrict_eq_freeOn_iff] instance freeOn_finitary : Finitary (freeOn E) := by simp only [finitary_iff, freeOn_indep_iff] exact fun I h e heI ↦ by simpa using h {e} (by simpa) lemma freeOn_rankPos (hE : E.Nonempty) : RankPos (freeOn E) := by simp [rankPos_iff, hE.ne_empty.symm] end FreeOn section uniqueBaseOn /-- The matroid on `E` whose unique base is the subset `I` of `E`. Intended for use when `I ⊆ E`; if this is not the case, then the base is `I ∩ E`. -/ def uniqueBaseOn (I E : Set α) : Matroid α := freeOn I ↾ E @[simp] theorem uniqueBaseOn_ground : (uniqueBaseOn I E).E = E := rfl theorem uniqueBaseOn_isBase_iff (hIE : I ⊆ E) : (uniqueBaseOn I E).IsBase B ↔ B = I := by rw [uniqueBaseOn, isBase_restrict_iff', freeOn_isBasis'_iff, inter_eq_self_of_subset_right hIE] theorem uniqueBaseOn_inter_ground_eq (I E : Set α) : uniqueBaseOn (I ∩ E) E = uniqueBaseOn I E := by simp only [uniqueBaseOn, restrict_eq_restrict_iff, freeOn_indep_iff, subset_inter_iff] tauto @[simp] theorem uniqueBaseOn_indep_iff' : (uniqueBaseOn I E).Indep J ↔ J ⊆ I ∩ E := by rw [uniqueBaseOn, restrict_indep_iff, freeOn_indep_iff, subset_inter_iff] theorem uniqueBaseOn_indep_iff (hIE : I ⊆ E) : (uniqueBaseOn I E).Indep J ↔ J ⊆ I := by rw [uniqueBaseOn, restrict_indep_iff, freeOn_indep_iff, and_iff_left_iff_imp] exact fun h ↦ h.trans hIE theorem uniqueBaseOn_isBasis_iff (hX : X ⊆ E) : (uniqueBaseOn I E).IsBasis J X ↔ J = X ∩ I := by rw [isBasis_iff_maximal] exact maximal_iff_eq (by simp [inter_subset_left.trans hX]) (by simp +contextual) theorem uniqueBaseOn_inter_isBasis (hX : X ⊆ E) : (uniqueBaseOn I E).IsBasis (X ∩ I) X := by rw [uniqueBaseOn_isBasis_iff hX] @[simp] theorem uniqueBaseOn_dual_eq (I E : Set α) : (uniqueBaseOn I E)✶ = uniqueBaseOn (E \ I) E := by rw [← uniqueBaseOn_inter_ground_eq] refine ext_isBase rfl (fun B (hB : B ⊆ E) ↦ ?_) rw [dual_isBase_iff, uniqueBaseOn_isBase_iff inter_subset_right, uniqueBaseOn_isBase_iff diff_subset, uniqueBaseOn_ground] exact ⟨fun h ↦ by rw [← diff_diff_cancel_left hB, h, diff_inter_self_eq_diff], fun h ↦ by rw [h, inter_comm I]; simp⟩ @[simp] theorem uniqueBaseOn_self (I : Set α) : uniqueBaseOn I I = freeOn I := by rw [uniqueBaseOn, freeOn_restrict rfl.subset] @[simp] theorem uniqueBaseOn_empty (I : Set α) : uniqueBaseOn ∅ I = loopyOn I := by rw [← dual_inj, uniqueBaseOn_dual_eq, diff_empty, uniqueBaseOn_self, loopyOn_dual_eq] theorem uniqueBaseOn_restrict' (I E R : Set α) : (uniqueBaseOn I E) ↾ R = uniqueBaseOn (I ∩ R ∩ E) R := by simp_rw [ext_iff_indep, restrict_ground_eq, uniqueBaseOn_ground, true_and, restrict_indep_iff, uniqueBaseOn_indep_iff', subset_inter_iff] tauto theorem uniqueBaseOn_restrict (h : I ⊆ E) (R : Set α) : (uniqueBaseOn I E) ↾ R = uniqueBaseOn (I ∩ R) R := by rw [uniqueBaseOn_restrict', inter_right_comm, inter_eq_self_of_subset_left h] lemma uniqueBaseOn_rankFinite (hI : I.Finite) : RankFinite (uniqueBaseOn I E) := by rw [← uniqueBaseOn_inter_ground_eq] refine ⟨I ∩ E, ?_⟩ rw [uniqueBaseOn_isBase_iff inter_subset_right, and_iff_right rfl] exact hI.subset inter_subset_left instance uniqueBaseOn_finitary : Finitary (uniqueBaseOn I E) := by refine ⟨fun K hK ↦ ?_⟩ simp only [uniqueBaseOn_indep_iff'] at hK ⊢ exact fun e heK ↦ singleton_subset_iff.1 <| hK _ (by simpa) (by simp) lemma uniqueBaseOn_rankPos (hIE : I ⊆ E) (hI : I.Nonempty) : RankPos (uniqueBaseOn I E) where empty_not_isBase := by simpa [uniqueBaseOn_isBase_iff hIE] using Ne.symm <| hI.ne_empty end uniqueBaseOn end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Loop.lean
import Mathlib.Combinatorics.Matroid.Circuit import Mathlib.Tactic.TFAE /-! # Matroid loops and coloops ## Loops A 'loop' of a matroid `M` is an element `e` satisfying one of the following equivalent conditions: * `e ∈ M.closure ∅`; * `{e}` is dependent in `M`; * `{e}` is a circuit of `M`; * no base of `M` contains `e`. In many mathematical contexts, loops can be thought of as 'trivial' or 'zero' elements; For linearly representable matroids, they correspond to the zero vector, and for graphic matroids, they correspond to edges incident with just one vertex (aka 'loops'). As trivial as they are, loops can be created from matroids with no loops by taking minors or duals, so in many contexts it is unreasonable to simply forbid loops from appearing. For `M : Matroid α`, this file defines a set `Matroid.loops M : Set α`, as well as predicates `Matroid.IsLoop M : α → Prop` and `Matroid.IsNonloop M : α → Prop`, and provides API for interacting with them. ## Coloops The dual notion of a loop is a 'coloop'. Geometrically, these can be thought of elements that are skew to the remainder of the matroid. Coloops in graphic matroids are 'bridge' edges of the graph, and coloops in linearly representable matroids are vectors not spanned by the other vectors in the matroid. Coloops also have many equivalent definitions in abstract matroid language; a coloop is an element of `M.E` if any of the following equivalent conditions holds : * `e` is a loop of `M✶`; * `{e}` is a cocircuit of `M`; * `e` is in no circuit of `M`; * `e` is in every base of `M`; * for all `X ⊆ M.E`, `e ∈ X ↔ e ∈ M.closure X`, * `M.E \ {e}` is nonspanning. ## Main Declarations For `M` : Matroid `α`: * `M.loops` is the set `M.closure ∅`. * `M.IsLoop e` means that `e : α` is a loop of `M`, defined as the statement `e ∈ M.loops`. * `M.isLoop_tfae` gives a number of properties that are equivalent to `IsLoop`. * `M.IsNonloop e` means that `e ∈ M.E`, but `e` is not a loop of `M`. * `M.IsColoop e ` means that `e` is a loop of `M✶`. * `M.coloops` is the set of coloops of `M✶`. * `M.isColoop_tfae` gives a number of properties that are equivalent to `IsColoop`. * `M.Loopless` is a typeclass meaning `M` has no loops. * `M.removeLoops` is the matroid obtained from `M` by restricting to its set of nonloop elements. -/ variable {α β : Type*} {M N : Matroid α} {e f : α} {F X C I : Set α} open Set namespace Matroid /-- `Matroid.loops M` is the closure of the empty set. -/ def loops (M : Matroid α) := M.closure ∅ @[aesop unsafe 20% (rule_sets := [Matroid])] lemma loops_subset_ground (M : Matroid α) : M.loops ⊆ M.E := M.closure_subset_ground ∅ /-- A 'loop' is a member of the closure of the empty set -/ def IsLoop (M : Matroid α) (e : α) : Prop := e ∈ M.loops lemma isLoop_iff : M.IsLoop e ↔ e ∈ M.loops := Iff.rfl lemma closure_empty (M : Matroid α) : M.closure ∅ = M.loops := rfl @[aesop unsafe 20% (rule_sets := [Matroid])] lemma IsLoop.mem_ground (he : M.IsLoop e) : e ∈ M.E := closure_subset_ground M ∅ he lemma isLoop_tfae (M : Matroid α) (e : α) : List.TFAE [ M.IsLoop e, e ∈ M.closure ∅, M.IsCircuit {e}, M.Dep {e}, ∀ ⦃B⦄, M.IsBase B → e ∈ M.E \ B] := by tfae_have 1 ↔ 2 := Iff.rfl tfae_have 2 ↔ 3 := by simp [M.empty_indep.mem_closure_iff_of_notMem (notMem_empty e), isCircuit_def, minimal_iff_forall_ssubset, ssubset_singleton_iff] tfae_have 2 ↔ 4 := by simp [M.empty_indep.mem_closure_iff_of_notMem (notMem_empty e)] tfae_have 4 ↔ 5 := by simp only [dep_iff, singleton_subset_iff, mem_diff, forall_and] refine ⟨fun h ↦ ⟨fun _ _ ↦ h.2, fun B hB heB ↦ h.1 (hB.indep.subset (by simpa))⟩, fun h ↦ ⟨fun hi ↦ ?_, h.1 _ M.exists_isBase.choose_spec⟩⟩ obtain ⟨B, hB, heB⟩ := hi.exists_isBase_superset exact h.2 _ hB (by simpa using heB) tfae_finish @[simp] lemma singleton_dep : M.Dep {e} ↔ M.IsLoop e := (M.isLoop_tfae e).out 3 0 alias ⟨_, IsLoop.dep⟩ := singleton_dep lemma singleton_not_indep (he : e ∈ M.E := by aesop_mat) : ¬ M.Indep {e} ↔ M.IsLoop e := by rw [← singleton_dep, ← not_indep_iff] @[simp] lemma singleton_isCircuit : M.IsCircuit {e} ↔ M.IsLoop e := (M.isLoop_tfae e).out 2 0 alias ⟨_, IsLoop.isCircuit⟩ := singleton_isCircuit lemma isLoop_iff_forall_mem_compl_isBase : M.IsLoop e ↔ ∀ B, M.IsBase B → e ∈ M.E \ B := (M.isLoop_tfae e).out 0 4 lemma isLoop_iff_forall_notMem_isBase (he : e ∈ M.E := by aesop_mat) : M.IsLoop e ↔ ∀ B, M.IsBase B → e ∉ B := by simp_rw [isLoop_iff_forall_mem_compl_isBase, mem_diff, and_iff_right he] @[deprecated (since := "2025-05-23")] alias isLoop_iff_forall_not_mem_isBase := isLoop_iff_forall_notMem_isBase lemma IsLoop.mem_closure (he : M.IsLoop e) (X : Set α) : e ∈ M.closure X := M.closure_mono (empty_subset _) he lemma IsLoop.mem_of_isFlat (he : M.IsLoop e) {F : Set α} (hF : M.IsFlat F) : e ∈ F := hF.closure ▸ he.mem_closure F lemma IsFlat.loops_subset (hF : M.IsFlat F) : M.loops ⊆ F := fun _ he ↦ IsLoop.mem_of_isFlat he hF lemma IsLoop.dep_of_mem (he : M.IsLoop e) (h : e ∈ X) (hXE : X ⊆ M.E := by aesop_mat) : M.Dep X := he.dep.superset (singleton_subset_iff.mpr h) hXE lemma IsLoop.not_indep_of_mem (he : M.IsLoop e) (h : e ∈ X) : ¬M.Indep X := fun hX ↦ he.dep.not_indep (hX.subset (singleton_subset_iff.mpr h)) lemma IsLoop.notMem_of_indep (he : M.IsLoop e) (hI : M.Indep I) : e ∉ I := fun h ↦ he.not_indep_of_mem h hI @[deprecated (since := "2025-05-23")] alias IsLoop.not_mem_of_indep := IsLoop.notMem_of_indep lemma IsLoop.eq_of_isCircuit_mem (he : M.IsLoop e) (hC : M.IsCircuit C) (h : e ∈ C) : C = {e} := by rw [he.isCircuit.eq_of_subset_isCircuit hC (singleton_subset_iff.mpr h)] lemma Indep.disjoint_loops (hI : M.Indep I) : Disjoint I M.loops := by_contra fun h ↦ let ⟨_, ⟨heI, he⟩⟩ := not_disjoint_iff.mp h IsLoop.notMem_of_indep he hI heI lemma Indep.eq_empty_of_subset_loops (hI : M.Indep I) (h : I ⊆ M.loops) : I = ∅ := eq_empty_iff_forall_notMem.mpr fun _ he ↦ IsLoop.notMem_of_indep (h he) hI he @[simp] lemma isBasis_loops_iff : M.IsBasis I M.loops ↔ I = ∅ := ⟨fun h ↦ h.indep.eq_empty_of_subset_loops h.subset, by simp +contextual [closure_empty]⟩ lemma closure_eq_loops_of_subset (h : X ⊆ M.loops) : M.closure X = M.loops := (closure_subset_closure_of_subset_closure h).antisymm (M.closure_mono (empty_subset _)) lemma isBasis_iff_empty_of_subset_loops (hX : X ⊆ M.loops) : M.IsBasis I X ↔ I = ∅ := by refine ⟨fun h ↦ ?_, by rintro rfl; simpa⟩ have := (closure_eq_loops_of_subset hX) ▸ h.isBasis_closure_right simpa using this lemma IsLoop.closure (he : M.IsLoop e) : M.closure {e} = M.loops := closure_eq_loops_of_subset (singleton_subset_iff.mpr he) lemma isLoop_iff_closure_eq_loops_and_mem_ground : M.IsLoop e ↔ M.closure {e} = M.loops ∧ e ∈ M.E where mp h := ⟨h.closure, h.mem_ground⟩ mpr h := by rw [isLoop_iff, ← closure_empty, ← singleton_subset_iff, ← closure_subset_closure_iff_subset_closure, h.1, loops] lemma isLoop_iff_closure_eq_loops (he : e ∈ M.E := by aesop_mat) : M.IsLoop e ↔ M.closure {e} = M.loops := by rw [isLoop_iff_closure_eq_loops_and_mem_ground, and_iff_left he] @[simp] lemma closure_loops (M : Matroid α) : M.closure M.loops = M.loops := M.closure_closure ∅ @[simp] lemma closure_union_loops_eq (M : Matroid α) (X : Set α) : M.closure (X ∪ M.loops) = M.closure X := by rw [← closure_empty, closure_union_closure_right_eq, union_empty] @[simp] lemma closure_loops_union_eq (M : Matroid α) (X : Set α) : M.closure (M.loops ∪ X) = M.closure X := by simp [union_comm] @[simp] lemma closure_diff_loops_eq (M : Matroid α) (X : Set α) : M.closure (X \ M.loops) = M.closure X := by rw [← M.closure_union_loops_eq (X \ M.loops), diff_union_self, ← closure_empty, closure_union_closure_right_eq, union_empty] /-- A version of `restrict_loops_eq` without the hypothesis that `R ⊆ M.E` -/ lemma restrict_loops_eq' (M : Matroid α) (R : Set α) : (M ↾ R).loops = (M.loops ∩ R) ∪ (R \ M.E) := by rw [← closure_empty, ← closure_empty, restrict_closure_eq', empty_inter] lemma restrict_loops_eq {R : Set α} (hR : R ⊆ M.E) : (M ↾ R).loops = M.loops ∩ R := by rw [restrict_loops_eq', diff_eq_empty.2 hR, union_empty] @[simp] lemma restrict_isLoop_iff {R : Set α} : (M ↾ R).IsLoop e ↔ e ∈ R ∧ (M.IsLoop e ∨ e ∉ M.E) := by simp only [isLoop_iff, restrict_closure_eq', empty_inter, mem_union, mem_inter_iff, mem_diff, ← closure_empty] tauto lemma IsRestriction.isLoop_iff (hNM : N ≤r M) : N.IsLoop e ↔ e ∈ N.E ∧ M.IsLoop e := by obtain ⟨R, hR, rfl⟩ := hNM simp only [restrict_isLoop_iff, restrict_ground_eq, and_congr_right_iff, or_iff_left_iff_imp] exact fun heR heE ↦ (heE (hR heR)).elim lemma IsLoop.of_isRestriction (he : N.IsLoop e) (hNM : N ≤r M) : M.IsLoop e := ((hNM.isLoop_iff).1 he).2 lemma IsLoop.isLoop_isRestriction (he : M.IsLoop e) (hNM : N ≤r M) (heN : e ∈ N.E) : N.IsLoop e := (hNM.isLoop_iff).2 ⟨heN, he⟩ @[simp] lemma map_loops {f : α → β} {hf : InjOn f M.E} : (M.map f hf).loops = f '' M.loops := by simp [loops] @[simp] lemma map_isLoop_iff {f : α → β} {hf : InjOn f M.E} (he : e ∈ M.E := by aesop_mat) : (M.map f hf).IsLoop (f e) ↔ M.IsLoop e := by rw [isLoop_iff, map_loops, hf.mem_image_iff M.loops_subset_ground he, isLoop_iff] @[simp] lemma mapEmbedding_isLoop_iff {f : α ↪ β} : (M.mapEmbedding f).IsLoop (f e) ↔ M.IsLoop e := by simp [mapEmbedding, isLoop_iff, isLoop_iff, map_closure_eq, preimage_empty, ← closure_empty] @[simp] lemma comap_loops {M : Matroid β} {f : α → β} : (M.comap f).loops = f ⁻¹' M.loops := by rw [loops, comap_closure_eq, image_empty, loops] @[simp] lemma comap_isLoop_iff {M : Matroid β} {f : α → β} : (M.comap f).IsLoop e ↔ M.IsLoop (f e) := by simp [isLoop_iff] @[simp] lemma loopyOn_isLoop_iff {E : Set α} : (loopyOn E).IsLoop e ↔ e ∈ E := by simp [isLoop_iff, loops] lemma eq_loopyOn_iff_loops {E : Set α} : M = loopyOn E ↔ M.loops = E ∧ M.E = E where mp h := by rw [h, loops]; simp mpr | ⟨h, h'⟩ => by rw [← h', ← closure_empty_eq_ground_iff, ← loops, h, h'] lemma restrict_subset_loops_eq (hX : X ⊆ M.loops) : M ↾ X = loopyOn X := by rw [eq_loopyOn_iff_loops, restrict_loops_eq', inter_eq_self_of_subset_right hX, union_eq_self_of_subset_right diff_subset, and_iff_left M.restrict_ground_eq] @[simp] lemma freeOn_not_isLoop (E : Set α) (e : α) : ¬ (freeOn E).IsLoop e := by simp [isLoop_iff, loops] @[simp] lemma uniqueBaseOn_isLoop_iff {I E : Set α} : (uniqueBaseOn I E).IsLoop e ↔ e ∈ E \ I := by simp [isLoop_iff, loops] lemma eq_loopyOn_iff_loops_eq {E : Set α} : M = loopyOn E ↔ M.loops = E ∧ M.E = E := ⟨fun h ↦ by simp [h, loops], fun ⟨h, h'⟩ ↦ by rw [← h', ← closure_empty_eq_ground_iff, ← loops, h, h']⟩ section IsNonloop /-- `M.IsNonloop e` means that `e` is an element of `M.E` but not a loop of `M`. -/ @[mk_iff] structure IsNonloop (M : Matroid α) (e : α) : Prop where not_isLoop : ¬ M.IsLoop e mem_ground : e ∈ M.E attribute [aesop unsafe 20% (rule_sets := [Matroid])] IsNonloop.mem_ground lemma IsLoop.not_isNonloop (he : M.IsLoop e) : ¬M.IsNonloop e := fun h ↦ h.not_isLoop he lemma compl_loops_eq (M : Matroid α) : M.E \ M.loops = {e | M.IsNonloop e} := by simp [Set.ext_iff, isNonloop_iff, and_comm, isLoop_iff] lemma isNonloop_of_not_isLoop (he : e ∈ M.E := by aesop_mat) (h : ¬ M.IsLoop e) : M.IsNonloop e := ⟨h,he⟩ lemma isLoop_of_not_isNonloop (he : e ∈ M.E := by aesop_mat) (h : ¬ M.IsNonloop e) : M.IsLoop e := by rwa [isNonloop_iff, and_iff_left he, not_not] at h @[simp] lemma not_isLoop_iff (he : e ∈ M.E := by aesop_mat) : ¬M.IsLoop e ↔ M.IsNonloop e := ⟨fun h ↦ ⟨h, he⟩, IsNonloop.not_isLoop⟩ @[simp] lemma not_isNonloop_iff (he : e ∈ M.E := by aesop_mat) : ¬M.IsNonloop e ↔ M.IsLoop e := by rw [← not_isLoop_iff, not_not] lemma isNonloop_iff_mem_compl_loops : M.IsNonloop e ↔ e ∈ M.E \ M.loops := by rw [isNonloop_iff, IsLoop, and_comm, mem_diff] lemma setOf_isNonloop_eq (M : Matroid α) : {e | M.IsNonloop e} = M.E \ M.loops := Set.ext (fun _ ↦ isNonloop_iff_mem_compl_loops) lemma not_isNonloop_iff_closure : ¬ M.IsNonloop e ↔ M.closure {e} = M.loops := by by_cases he : e ∈ M.E · simp [isLoop_iff_closure_eq_loops_and_mem_ground, he] simp [← closure_inter_ground, singleton_inter_eq_empty.2 he, loops, (show ¬ M.IsNonloop e from fun h ↦ he h.mem_ground)] lemma isLoop_or_isNonloop (M : Matroid α) (e : α) (he : e ∈ M.E := by aesop_mat) : M.IsLoop e ∨ M.IsNonloop e := by rw [isNonloop_iff, and_iff_left he]; apply em @[simp] lemma indep_singleton : M.Indep {e} ↔ M.IsNonloop e := by rw [isNonloop_iff, ← singleton_dep, dep_iff, not_and, not_imp_not, singleton_subset_iff] exact ⟨fun h ↦ ⟨fun _ ↦ h, singleton_subset_iff.mp h.subset_ground⟩, fun h ↦ h.1 h.2⟩ alias ⟨Indep.isNonloop, IsNonloop.indep⟩ := indep_singleton lemma Indep.isNonloop_of_mem (hI : M.Indep I) (h : e ∈ I) : M.IsNonloop e := by rw [← not_isLoop_iff (hI.subset_ground h)]; exact fun he ↦ (he.notMem_of_indep hI) h lemma IsNonloop.exists_mem_isBase (he : M.IsNonloop e) : ∃ B, M.IsBase B ∧ e ∈ B := by simpa using (indep_singleton.2 he).exists_isBase_superset lemma IsCocircuit.isNonloop_of_mem {K : Set α} (hK : M.IsCocircuit K) (he : e ∈ K) : M.IsNonloop e := by rw [← not_isLoop_iff (hK.subset_ground he), ← singleton_isCircuit] intro he' obtain ⟨f, ⟨rfl, -⟩, hfe⟩ := (he'.isCocircuit_inter_nontrivial hK ⟨e, by simp [he]⟩).exists_ne e exact hfe rfl lemma IsCircuit.isNonloop_of_mem (hC : M.IsCircuit C) (hC' : C.Nontrivial) (he : e ∈ C) : M.IsNonloop e := isNonloop_of_not_isLoop (hC.subset_ground he) (fun hL ↦ by simp [hL.eq_of_isCircuit_mem hC he] at hC') lemma IsCircuit.isNonloop_of_mem_of_one_lt_card (hC : M.IsCircuit C) (h : 1 < C.encard) (he : e ∈ C) : M.IsNonloop e := by refine isNonloop_of_not_isLoop (hC.subset_ground he) (fun hlp ↦ ?_) rw [hlp.eq_of_isCircuit_mem hC he, encard_singleton] at h exact h.ne rfl lemma isNonloop_of_notMem_closure (h : e ∉ M.closure X) (he : e ∈ M.E := by aesop_mat) : M.IsNonloop e := isNonloop_of_not_isLoop he (fun hel ↦ h (hel.mem_closure X)) @[deprecated (since := "2025-05-23")] alias isNonloop_of_not_mem_closure := isNonloop_of_notMem_closure lemma isNonloop_iff_notMem_loops (he : e ∈ M.E := by aesop_mat) : M.IsNonloop e ↔ e ∉ M.loops := by rw [isNonloop_iff, isLoop_iff, and_iff_left he] @[deprecated (since := "2025-05-23")] alias isNonloop_iff_not_mem_loops := isNonloop_iff_notMem_loops lemma IsNonloop.mem_closure_singleton (he : M.IsNonloop e) (hef : e ∈ M.closure {f}) : f ∈ M.closure {e} := by rw [← union_empty {_}, singleton_union] at * exact (M.closure_exchange (X := ∅) ⟨hef, (isNonloop_iff_notMem_loops he.mem_ground).1 he⟩).1 lemma IsNonloop.mem_closure_comm (he : M.IsNonloop e) (hf : M.IsNonloop f) : f ∈ M.closure {e} ↔ e ∈ M.closure {f} := ⟨hf.mem_closure_singleton, he.mem_closure_singleton⟩ lemma IsNonloop.isNonloop_of_mem_closure (he : M.IsNonloop e) (hef : e ∈ M.closure {f}) : M.IsNonloop f := by rw [isNonloop_iff, and_comm] by_contra! h; apply he.not_isLoop rw [isLoop_iff] at *; convert hef using 1 obtain (hf | hf) := em (f ∈ M.E) · rw [← closure_loops, ← insert_eq_of_mem (h hf), closure_insert_congr_right M.closure_loops, insert_empty_eq] rw [eq_comm, ← closure_inter_ground, inter_comm, inter_singleton_eq_empty.mpr hf, loops] lemma IsNonloop.closure_eq_of_mem_closure (he : M.IsNonloop e) (hef : e ∈ M.closure {f}) : M.closure {e} = M.closure {f} := by rw [← closure_closure _ {f}, ← insert_eq_of_mem hef, closure_insert_closure_eq_closure_insert, ← closure_closure _ {e}, ← insert_eq_of_mem (he.mem_closure_singleton hef), closure_insert_closure_eq_closure_insert, pair_comm] /-- Two distinct nonloops with the same closure form a circuit. -/ lemma IsNonloop.closure_eq_closure_iff_isCircuit_of_ne (he : M.IsNonloop e) (hef : e ≠ f) : M.closure {e} = M.closure {f} ↔ M.IsCircuit {e, f} := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · have hf := he.isNonloop_of_mem_closure (by rw [← h]; exact M.mem_closure_self e) rw [isCircuit_iff_dep_forall_diff_singleton_indep, dep_iff, insert_subset_iff, and_iff_right he.mem_ground, singleton_subset_iff, and_iff_left hf.mem_ground] suffices ¬ M.Indep {e, f} by simpa [pair_diff_left hef, hf, pair_diff_right hef, he] rw [Indep.insert_indep_iff_of_notMem (by simpa) (by simpa)] simp [← h, mem_closure_self _ _ he.mem_ground] have hclosure := (h.closure_diff_singleton_eq e).trans (h.closure_diff_singleton_eq f).symm rwa [pair_diff_left hef, pair_diff_right hef, eq_comm] at hclosure lemma IsNonloop.closure_eq_closure_iff_eq_or_dep (he : M.IsNonloop e) (hf : M.IsNonloop f) : M.closure {e} = M.closure {f} ↔ e = f ∨ ¬M.Indep {e, f} := by obtain (rfl | hne) := eq_or_ne e f · exact iff_of_true rfl (Or.inl rfl) simp_rw [he.closure_eq_closure_iff_isCircuit_of_ne hne, or_iff_right hne, isCircuit_iff_dep_forall_diff_singleton_indep, dep_iff, insert_subset_iff, singleton_subset_iff, and_iff_left hf.mem_ground, and_iff_left he.mem_ground, and_iff_left_iff_imp] rintro hi x (rfl | rfl) · rwa [pair_diff_left hne, indep_singleton] rwa [pair_diff_right hne, indep_singleton] lemma exists_isNonloop (M : Matroid α) [RankPos M] : ∃ e, M.IsNonloop e := let ⟨_, hB⟩ := M.exists_isBase ⟨_, hB.indep.isNonloop_of_mem hB.nonempty.some_mem⟩ lemma IsNonloop.rankPos (h : M.IsNonloop e) : M.RankPos := h.indep.rankPos_of_nonempty (singleton_nonempty e) @[simp] lemma restrict_isNonloop_iff {R : Set α} : (M ↾ R).IsNonloop e ↔ M.IsNonloop e ∧ e ∈ R := by rw [← indep_singleton, restrict_indep_iff, singleton_subset_iff, indep_singleton] lemma IsNonloop.of_restrict {R : Set α} (h : (M ↾ R).IsNonloop e) : M.IsNonloop e := (restrict_isNonloop_iff.1 h).1 lemma IsNonloop.of_isRestriction (h : N.IsNonloop e) (hNM : N ≤r M) : M.IsNonloop e := by obtain ⟨R, -, rfl⟩ := hNM; exact h.of_restrict lemma isNonloop_iff_restrict_of_mem {R : Set α} (he : e ∈ R) : M.IsNonloop e ↔ (M ↾ R).IsNonloop e := ⟨fun h ↦ restrict_isNonloop_iff.2 ⟨h, he⟩, fun h ↦ h.of_restrict⟩ @[simp] lemma comap_isNonloop_iff {M : Matroid β} {f : α → β} : (M.comap f).IsNonloop e ↔ M.IsNonloop (f e) := by rw [← indep_singleton, comap_indep_iff, image_singleton, indep_singleton, and_iff_left (injOn_singleton _ _)] @[simp] lemma freeOn_isNonloop_iff {E : Set α} : (freeOn E).IsNonloop e ↔ e ∈ E := by rw [← indep_singleton, freeOn_indep_iff, singleton_subset_iff] @[simp] lemma uniqueBaseOn_isNonloop_iff {I E : Set α} : (uniqueBaseOn I E).IsNonloop e ↔ e ∈ I ∩ E := by rw [← indep_singleton, uniqueBaseOn_indep_iff', singleton_subset_iff] lemma IsNonloop.exists_mem_isCocircuit (he : M.IsNonloop e) : ∃ K, M.IsCocircuit K ∧ e ∈ K := by obtain ⟨B, hB, heB⟩ := he.exists_mem_isBase exact ⟨_, fundCocircuit_isCocircuit heB hB, mem_fundCocircuit M e B⟩ @[simp] lemma closure_inter_setOf_isNonloop_eq (M : Matroid α) (X : Set α) : M.closure (X ∩ {e | M.IsNonloop e}) = M.closure X := by rw [setOf_isNonloop_eq, ← inter_diff_assoc, closure_diff_loops_eq, closure_inter_ground] end IsNonloop section IsColoop variable {B K : Set α} /-- A coloop is a loop of the dual matroid. See `Matroid.isColoop_tfae` for a number of equivalent definitions. -/ def IsColoop (M : Matroid α) (e : α) : Prop := M✶.IsLoop e /-- `M.coloops` is the set of coloops of `M`. -/ def coloops (M : Matroid α) := M✶.loops @[aesop unsafe 20% (rule_sets := [Matroid])] lemma IsColoop.mem_ground (he : M.IsColoop e) : e ∈ M.E := @IsLoop.mem_ground α (M✶) e he @[aesop unsafe 20% (rule_sets := [Matroid])] lemma coloops_subset_ground (M : Matroid α) : M.coloops ⊆ M.E := fun _ ↦ IsColoop.mem_ground lemma isColoop_iff_mem_coloops : M.IsColoop e ↔ e ∈ M.coloops := Iff.rfl @[simp] lemma dual_loops : M✶.loops = M.coloops := rfl @[simp] lemma dual_coloops : M✶.coloops = M.loops := by rw [coloops, dual_dual] lemma IsColoop.dual_isLoop (he : M.IsColoop e) : M✶.IsLoop e := he lemma IsColoop.isCocircuit (he : M.IsColoop e) : M.IsCocircuit {e} := IsLoop.isCircuit he lemma IsLoop.dual_isColoop (he : M.IsLoop e) : M✶.IsColoop e := by rwa [IsColoop, dual_dual] @[simp] lemma dual_isColoop_iff_isLoop : M✶.IsColoop e ↔ M.IsLoop e := ⟨fun h ↦ by rw [← dual_dual M]; exact h.dual_isLoop, IsLoop.dual_isColoop⟩ @[simp] lemma dual_isLoop_iff_isColoop : M✶.IsLoop e ↔ M.IsColoop e := ⟨fun h ↦ by rw [← dual_dual M]; exact h.dual_isColoop, IsColoop.dual_isLoop⟩ lemma singleton_isCocircuit : M.IsCocircuit {e} ↔ M.IsColoop e := by simp lemma isColoop_tfae (M : Matroid α) (e : α) : List.TFAE [ M.IsColoop e, e ∈ M.coloops, M.IsCocircuit {e}, ∀ ⦃B⦄, M.IsBase B → e ∈ B, (∀ ⦃C⦄, M.IsCircuit C → e ∉ C) ∧ e ∈ M.E, ∀ X, e ∈ M.closure X ↔ e ∈ X, ¬ M.Spanning (M.E \ {e}) ] := by tfae_have 1 <-> 2 := Iff.rfl tfae_have 1 <-> 3 := singleton_isCocircuit.symm tfae_have 1 <-> 4 := by simp_rw [← dual_isLoop_iff_isColoop, isLoop_iff_forall_mem_compl_isBase] refine ⟨fun h B hB ↦ ?_, fun h B hB ↦ h hB.compl_isBase_of_dual⟩ obtain ⟨-, heB : e ∈ B⟩ := by simpa using h (M.E \ B) hB.compl_isBase_dual assumption tfae_have 3 -> 5 := fun h ↦ ⟨fun C hC heC ↦ hC.inter_isCocircuit_ne_singleton h (e := e) (by simpa), h.subset_ground rfl⟩ tfae_have 5 -> 4 := by refine fun ⟨h, heE⟩ B hB ↦ by_contra fun heB ↦ ?_ rw [← hB.closure_eq] at heE obtain ⟨C, -, hC, heC⟩ := (mem_closure_iff_exists_isCircuit heB).1 heE exact h hC heC tfae_have 5 <-> 6 := by refine ⟨fun h X ↦ ⟨fun heX ↦ by_contra fun heX' ↦ ?_, fun heX ↦ M.mem_closure_of_mem' heX h.2⟩, fun h ↦ ⟨fun C hC heC ↦ ?_, M.closure_subset_ground _ <| (h {e}).2 rfl⟩⟩ · obtain ⟨C, -, hC, heC⟩ := (mem_closure_iff_exists_isCircuit heX').1 heX exact h.1 hC heC · simpa [hC.mem_closure_diff_singleton_of_mem heC] using h (C \ {e}) tfae_have 1 <-> 7 := by wlog he : e ∈ M.E · exact iff_of_false (fun h ↦ he h.mem_ground) <| by simp [he, M.ground_spanning] rw [spanning_iff_compl_coindep diff_subset, ← dual_isLoop_iff_isColoop, ← singleton_dep, diff_diff_cancel_left (by simpa), ← not_indep_iff (by simpa)] tfae_finish lemma isColoop_iff_forall_mem_isBase : M.IsColoop e ↔ ∀ ⦃B⦄, M.IsBase B → e ∈ B := (M.isColoop_tfae e).out 0 3 lemma IsBase.mem_of_isColoop (hB : M.IsBase B) (he : M.IsColoop e) : e ∈ B := isColoop_iff_forall_mem_isBase.mp he hB lemma IsColoop.mem_of_isBase (he : M.IsColoop e) (hB : M.IsBase B) : e ∈ B := isColoop_iff_forall_mem_isBase.mp he hB lemma IsBase.coloops_subset (hB : M.IsBase B) : M.coloops ⊆ B := fun _ he ↦ IsColoop.mem_of_isBase he hB lemma IsColoop.isNonloop (h : M.IsColoop e) : M.IsNonloop e := let ⟨_, hB⟩ := M.exists_isBase hB.indep.isNonloop_of_mem ((isColoop_iff_forall_mem_isBase.mp h) hB) lemma IsLoop.not_isColoop (h : M.IsLoop e) : ¬M.IsColoop e := by rw [← dual_isLoop_iff_isColoop]; rw [← dual_dual M, dual_isLoop_iff_isColoop] at h exact h.isNonloop.not_isLoop lemma IsColoop.notMem_isCircuit (he : M.IsColoop e) (hC : M.IsCircuit C) : e ∉ C := fun h ↦ (hC.isCocircuit.isNonloop_of_mem h).not_isLoop he @[deprecated (since := "2025-05-23")] alias IsColoop.not_mem_isCircuit := IsColoop.notMem_isCircuit lemma IsCircuit.disjoint_coloops (hC : M.IsCircuit C) : Disjoint C M.coloops := disjoint_right.2 <| fun _ he ↦ IsColoop.notMem_isCircuit he hC lemma isColoop_iff_forall_notMem_isCircuit (he : e ∈ M.E := by aesop_mat) : M.IsColoop e ↔ ∀ ⦃C⦄, M.IsCircuit C → e ∉ C := by simp_rw [(M.isColoop_tfae e).out 0 4, and_iff_left he] @[deprecated (since := "2025-05-23")] alias isColoop_iff_forall_not_mem_isCircuit := isColoop_iff_forall_notMem_isCircuit lemma isColoop_iff_forall_mem_compl_isCircuit [RankPos M✶] : M.IsColoop e ↔ ∀ C, M.IsCircuit C → e ∈ M.E \ C := by by_cases he : e ∈ M.E · simp [isColoop_iff_forall_notMem_isCircuit, he] obtain ⟨C, hC⟩ := M.exists_isCircuit exact iff_of_false (fun h ↦ he h.mem_ground) fun h ↦ he (h C hC).1 lemma IsCircuit.not_isColoop_of_mem (hC : M.IsCircuit C) (heC : e ∈ C) : ¬ M.IsColoop e := fun h ↦ h.notMem_isCircuit hC heC lemma isColoop_iff_forall_mem_closure_iff_mem : M.IsColoop e ↔ (∀ X, e ∈ M.closure X ↔ e ∈ X) := (M.isColoop_tfae e).out 0 5 /-- A version of `Matroid.isColoop_iff_forall_mem_closure_iff_mem` where we only quantify over subsets of the ground set. -/ lemma isColoop_iff_forall_mem_closure_iff_mem' : M.IsColoop e ↔ (∀ X, X ⊆ M.E → (e ∈ M.closure X ↔ e ∈ X)) ∧ e ∈ M.E := by refine ⟨fun h ↦ ⟨fun X _ ↦ isColoop_iff_forall_mem_closure_iff_mem.1 h X, h.mem_ground⟩, fun ⟨h, he⟩ ↦ isColoop_iff_forall_mem_closure_iff_mem.2 fun X ↦ ?_⟩ rw [← closure_inter_ground, h _ inter_subset_right, mem_inter_iff, and_iff_left he] lemma IsColoop.mem_closure_iff_mem (he : M.IsColoop e) : e ∈ M.closure X ↔ e ∈ X := (isColoop_iff_forall_mem_closure_iff_mem.1 he) X lemma IsColoop.mem_of_mem_closure (he : M.IsColoop e) (heX : e ∈ M.closure X) : e ∈ X := he.mem_closure_iff_mem.1 heX lemma isColoop_iff_diff_not_spanning : M.IsColoop e ↔ ¬ M.Spanning (M.E \ {e}) := (M.isColoop_tfae e).out 0 6 alias ⟨IsColoop.diff_not_spanning, _⟩ := isColoop_iff_diff_not_spanning lemma isColoop_iff_diff_closure : M.IsColoop e ↔ M.closure (M.E \ {e}) ≠ M.E := by rw [isColoop_iff_diff_not_spanning, spanning_iff_closure_eq] lemma isColoop_iff_notMem_closure_compl (he : e ∈ M.E := by aesop_mat) : M.IsColoop e ↔ e ∉ M.closure (M.E \ {e}) := by rw [isColoop_iff_diff_closure, not_iff_not] refine ⟨fun h ↦ by rwa [h], fun h ↦ (M.closure_subset_ground _).antisymm fun x hx ↦ ?_⟩ obtain (rfl | hne) := eq_or_ne x e · assumption exact M.subset_closure (M.E \ {e}) diff_subset (show x ∈ M.E \ {e} from ⟨hx, hne⟩) @[deprecated (since := "2025-05-23")] alias isColoop_iff_not_mem_closure_compl := isColoop_iff_notMem_closure_compl lemma IsBase.isColoop_iff_forall_notMem_fundCircuit (hB : M.IsBase B) (he : e ∈ B) : M.IsColoop e ↔ ∀ x ∈ M.E \ B, e ∉ M.fundCircuit x B := by refine ⟨fun h x hx heC ↦ (h.notMem_isCircuit <| hB.fundCircuit_isCircuit hx.1 hx.2) heC, fun h ↦ ?_⟩ have h' : M.E \ {e} ⊆ M.closure (B \ {e}) := by rintro x ⟨hxE, hne : x ≠ e⟩ obtain (hx | hx) := em (x ∈ B) · exact M.subset_closure (B \ {e}) (diff_subset.trans hB.subset_ground) ⟨hx, hne⟩ have h_cct := (hB.fundCircuit_isCircuit hxE hx).mem_closure_diff_singleton_of_mem (M.mem_fundCircuit x B) refine (M.closure_subset_closure (subset_diff_singleton ?_ ?_)) h_cct · simpa using fundCircuit_subset_insert .. simp [hne.symm, h x ⟨hxE, hx⟩] rw [isColoop_iff_notMem_closure_compl (hB.subset_ground he)] exact notMem_subset (M.closure_subset_closure_of_subset_closure h') <| hB.indep.notMem_closure_diff_of_mem he @[deprecated (since := "2025-05-23")] alias IsBase.isColoop_iff_forall_not_mem_fundCircuit := IsBase.isColoop_iff_forall_notMem_fundCircuit lemma IsBasis'.inter_coloops_subset (hIX : M.IsBasis' I X) : X ∩ M.coloops ⊆ I := by intro e ⟨heX, (heI : M.IsColoop e)⟩ rwa [← heI.mem_closure_iff_mem, hIX.isBasis_closure_right.closure_eq_right, heI.mem_closure_iff_mem] lemma IsBasis.inter_coloops_subset (hIX : M.IsBasis I X) : X ∩ M.coloops ⊆ I := hIX.isBasis'.inter_coloops_subset lemma exists_mem_isCircuit_of_not_isColoop (heE : e ∈ M.E) (he : ¬ M.IsColoop e) : ∃ C, M.IsCircuit C ∧ e ∈ C := by simp only [isColoop_iff_forall_mem_isBase, not_forall, exists_prop] at he obtain ⟨B, hB, heB⟩ := he exact ⟨M.fundCircuit e B, hB.fundCircuit_isCircuit heE heB, .inl rfl⟩ @[simp] lemma closure_inter_coloops_eq (M : Matroid α) (X : Set α) : M.closure X ∩ M.coloops = X ∩ M.coloops := by simp_rw [Set.ext_iff, mem_inter_iff, ← isColoop_iff_mem_coloops, and_congr_left_iff] intro e he rw [he.mem_closure_iff_mem] lemma closure_inter_eq_of_subset_coloops (X : Set α) (hK : K ⊆ M.coloops) : M.closure X ∩ K = X ∩ K := by nth_rw 1 [← inter_eq_self_of_subset_right hK] rw [← inter_assoc, closure_inter_coloops_eq, inter_assoc, inter_eq_self_of_subset_right hK] lemma closure_union_eq_of_subset_coloops (X : Set α) (hK : K ⊆ M.coloops) : M.closure (X ∪ K) = M.closure X ∪ K := by rw [← closure_union_closure_left_eq, subset_antisymm_iff, and_iff_left (M.subset_closure _), ← diff_eq_empty, eq_empty_iff_forall_notMem] refine fun e ⟨hecl, he⟩ ↦ he (.inl ?_) obtain ⟨C, hCss, hC, heC⟩ := (mem_closure_iff_exists_isCircuit he).1 hecl rw [← singleton_union, ← union_assoc, union_comm, ← diff_subset_iff, (hC.disjoint_coloops.mono_right hK).sdiff_eq_left, singleton_union] at hCss exact M.closure_subset_closure_of_subset_closure (by simpa) <| hC.mem_closure_diff_singleton_of_mem heC lemma closure_insert_isColoop_eq (X : Set α) (he : M.IsColoop e) : M.closure (insert e X) = insert e (M.closure X) := by rw [← union_singleton, closure_union_eq_of_subset_coloops _ (by simpa), union_singleton] lemma closure_eq_of_subset_coloops (hK : K ⊆ M.coloops) : M.closure K = K ∪ M.loops := by rw [← empty_union K, closure_union_eq_of_subset_coloops _ hK, empty_union, union_comm, closure_empty] lemma closure_diff_eq_of_subset_coloops (X : Set α) (hK : K ⊆ M.coloops) : M.closure (X \ K) = M.closure X \ K := by nth_rw 2 [← inter_union_diff X K] rw [union_comm, closure_union_eq_of_subset_coloops _ (inter_subset_right.trans hK), union_diff_distrib, diff_eq_empty.mpr inter_subset_right, union_empty, eq_comm, sdiff_eq_self_iff_disjoint, disjoint_iff_forall_ne] rintro e heK _ heX rfl rw [IsColoop.mem_closure_iff_mem (hK heK)] at heX exact heX.2 heK lemma closure_disjoint_of_disjoint_of_subset_coloops (hXK : Disjoint X K) (hK : K ⊆ M.coloops) : Disjoint (M.closure X) K := by rwa [disjoint_iff_inter_eq_empty, closure_inter_eq_of_subset_coloops X hK, ← disjoint_iff_inter_eq_empty] lemma closure_disjoint_coloops_of_disjoint_coloops (hX : Disjoint X (M.coloops)) : Disjoint (M.closure X) M.coloops := closure_disjoint_of_disjoint_of_subset_coloops hX Subset.rfl lemma closure_union_coloops_eq (M : Matroid α) (X : Set α) : M.closure (X ∪ M.coloops) = M.closure X ∪ M.coloops := closure_union_eq_of_subset_coloops _ Subset.rfl lemma IsColoop.notMem_closure_of_notMem (he : M.IsColoop e) (hX : e ∉ X) : e ∉ M.closure X := mt he.mem_closure_iff_mem.mp hX @[deprecated (since := "2025-05-23")] alias IsColoop.not_mem_closure_of_not_mem := IsColoop.notMem_closure_of_notMem lemma IsColoop.insert_indep_of_indep (he : M.IsColoop e) (hI : M.Indep I) : M.Indep (insert e I) := by refine (em (e ∈ I)).elim (fun h ↦ by rwa [insert_eq_of_mem h]) fun h ↦ ?_ rw [← hI.notMem_closure_iff_of_notMem h] exact he.notMem_closure_of_notMem h lemma union_indep_iff_indep_of_subset_coloops (hK : K ⊆ M.coloops) : M.Indep (I ∪ K) ↔ M.Indep I := by refine ⟨fun h ↦ h.subset subset_union_left, fun h ↦ ?_⟩ obtain ⟨B, hB, hIB⟩ := h.exists_isBase_superset exact hB.indep.subset (union_subset hIB (hK.trans fun e he ↦ IsColoop.mem_of_isBase he hB)) lemma diff_indep_iff_indep_of_subset_coloops (hK : K ⊆ M.coloops) : M.Indep (I \ K) ↔ M.Indep I := by rw [← union_indep_iff_indep_of_subset_coloops hK, diff_union_self, union_indep_iff_indep_of_subset_coloops hK] @[simp] lemma union_coloops_indep_iff : M.Indep (I ∪ M.coloops) ↔ M.Indep I := union_indep_iff_indep_of_subset_coloops Subset.rfl @[simp] lemma diff_coloops_indep_iff : M.Indep (I \ M.coloops) ↔ M.Indep I := diff_indep_iff_indep_of_subset_coloops Subset.rfl lemma coloops_indep (M : Matroid α) : M.Indep M.coloops := by rw [← empty_union M.coloops, union_coloops_indep_iff] exact M.empty_indep lemma restrict_isColoop_iff {R : Set α} (hRE : R ⊆ M.E) : (M ↾ R).IsColoop e ↔ e ∉ M.closure (R \ {e}) ∧ e ∈ R := by wlog heR : e ∈ R · exact iff_of_false (fun h ↦ heR h.mem_ground) fun h ↦ heR h.2 rw [isColoop_iff_forall_notMem_isCircuit heR, mem_closure_iff_exists_isCircuit (by simp)] simp only [restrict_isCircuit_iff hRE, insert_diff_singleton] aesop /-- If two matroids agree on loops and coloops, and have the same independent sets after loops/coloops are removed, they are equal. -/ lemma ext_indep_disjoint_loops_coloops {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E) (hl : M₁.loops = M₂.loops) (hc : M₁.coloops = M₂.coloops) (h : ∀ I, I ⊆ M₁.E → Disjoint I (M₁.loops ∪ M₁.coloops) → (M₁.Indep I ↔ M₂.Indep I)) : M₁ = M₂ := by refine ext_indep hE fun I hI ↦ ?_ rw [← diff_coloops_indep_iff, ← @diff_coloops_indep_iff _ M₂, ← hc] obtain hdj | hndj := em (Disjoint I (M₁.loops)) · rw [h _ (diff_subset.trans hI)] rw [disjoint_union_right] exact ⟨disjoint_of_subset_left diff_subset hdj, disjoint_sdiff_left⟩ obtain ⟨e, heI, hel : M₁.IsLoop e⟩ := not_disjoint_iff_nonempty_inter.mp hndj refine iff_of_false (hel.not_indep_of_mem ⟨heI, hel.not_isColoop⟩) ?_ rw [isLoop_iff, hl, ← isLoop_iff] at hel rw [hc] exact hel.not_indep_of_mem ⟨heI, hel.not_isColoop⟩ end IsColoop section Loopless /-- A Matroid is `Loopless` if it has no loop -/ @[mk_iff] class Loopless (M : Matroid α) : Prop where loops_eq_empty : M.loops = ∅ @[simp] lemma loops_eq_empty (M : Matroid α) [Loopless M] : M.loops = ∅ := ‹Loopless M›.loops_eq_empty lemma isNonloop_of_loopless [Loopless M] (he : e ∈ M.E := by aesop_mat) : M.IsNonloop e := by rw [← not_isLoop_iff, isLoop_iff, loops_eq_empty] exact notMem_empty _ lemma subsingleton_indep [M.Loopless] (hI : I.Subsingleton) (hIE : I ⊆ M.E := by aesop_mat) : M.Indep I := by obtain rfl | ⟨x, rfl⟩ := hI.eq_empty_or_singleton · simp simpa using M.isNonloop_of_loopless lemma not_isLoop (M : Matroid α) [Loopless M] (e : α) : ¬ M.IsLoop e := fun h ↦ (isNonloop_of_loopless (e := e)).not_isLoop h lemma loopless_iff_forall_isNonloop : M.Loopless ↔ ∀ e ∈ M.E, M.IsNonloop e := ⟨fun _ _ he ↦ isNonloop_of_loopless he, fun h ↦ ⟨subset_empty_iff.1 (fun e (he : M.IsLoop e) ↦ (h e he.mem_ground).not_isLoop he)⟩⟩ lemma loopless_iff_forall_not_isLoop : M.Loopless ↔ ∀ e ∈ M.E, ¬ M.IsLoop e := ⟨fun _ e _ ↦ M.not_isLoop e, fun h ↦ loopless_iff_forall_isNonloop.2 fun e he ↦ (not_isLoop_iff he).1 (h e he)⟩ lemma loopless_iff_forall_isCircuit : M.Loopless ↔ ∀ C, M.IsCircuit C → C.Nontrivial := by suffices (∃ x ∈ M.E, M.IsLoop x) ↔ ∃ x, M.IsCircuit x ∧ x.Subsingleton by simpa [loopless_iff_forall_not_isLoop, ← not_iff_not (a := ∀ _, _)] refine ⟨fun ⟨e, _, he⟩ ↦ ⟨{e}, he.isCircuit, by simp⟩, fun ⟨C, hC, hCs⟩ ↦ ?_⟩ obtain (rfl | ⟨e, rfl⟩) := hCs.eq_empty_or_singleton · simpa using hC.nonempty exact ⟨e, (singleton_isCircuit.1 hC).mem_ground, singleton_isCircuit.1 hC⟩ lemma Loopless.ground_eq (M : Matroid α) [Loopless M] : M.E = {e | M.IsNonloop e} := Set.ext fun _ ↦ ⟨fun he ↦ isNonloop_of_loopless he, IsNonloop.mem_ground⟩ lemma IsRestriction.loopless [M.Loopless] (hR : N ≤r M) : N.Loopless := by obtain ⟨R, hR, rfl⟩ := hR rw [loopless_iff, restrict_loops_eq hR, M.loops_eq_empty, empty_inter] instance {M : Matroid α} [M.Nonempty] [Loopless M] : RankPos M := M.ground_nonempty.elim fun _ he ↦ (isNonloop_of_loopless he).rankPos @[simp] lemma loopyOn_isLoopless_iff {E : Set α} : Loopless (loopyOn E) ↔ E = ∅ := by simp [loopless_iff_forall_not_isLoop, eq_empty_iff_forall_notMem] /-- The loopless matroid obtained from `M` by deleting all its loops. -/ def removeLoops (M : Matroid α) : Matroid α := M ↾ {e | M.IsNonloop e} lemma removeLoops_eq_restrict (M : Matroid α) : M.removeLoops = M ↾ {e | M.IsNonloop e} := rfl lemma removeLoops_ground_eq (M : Matroid α) : M.removeLoops.E = {e | M.IsNonloop e} := rfl instance removeLoops_loopless (M : Matroid α) : Loopless M.removeLoops := by simp [loopless_iff_forall_isNonloop, removeLoops] @[simp] lemma removeLoops_eq_self (M : Matroid α) [Loopless M] : M.removeLoops = M := by rw [removeLoops, ← Loopless.ground_eq, restrict_ground_eq_self] lemma removeLoops_eq_self_iff : M.removeLoops = M ↔ M.Loopless := by refine ⟨fun h ↦ ?_, fun h ↦ M.removeLoops_eq_self⟩ rw [← h] infer_instance lemma removeLoops_isRestriction (M : Matroid α) : M.removeLoops ≤r M := restrict_isRestriction _ _ (fun _ h ↦ IsNonloop.mem_ground h) lemma eq_restrict_removeLoops (M : Matroid α) : M.removeLoops ↾ M.E = M := by rw [removeLoops, ext_iff_indep] simp only [restrict_ground_eq, restrict_indep_iff, true_and] exact fun I hIE ↦ ⟨ fun hI ↦ hI.1.1, fun hI ↦ ⟨⟨hI,fun e heI ↦ hI.isNonloop_of_mem heI⟩, hIE⟩⟩ @[simp] lemma removeLoops_indep_eq : M.removeLoops.Indep = M.Indep := by ext I rw [removeLoops_eq_restrict, restrict_indep_iff, and_iff_left_iff_imp] exact fun h e ↦ h.isNonloop_of_mem @[simp] lemma removeLoops_isBasis'_eq : M.removeLoops.IsBasis' = M.IsBasis' := by ext simp [IsBasis'] @[simp] lemma removeLoops_isBase_eq : M.removeLoops.IsBase = M.IsBase := by ext B rw [isBase_iff_maximal_indep, removeLoops_indep_eq, isBase_iff_maximal_indep] @[simp] lemma removeLoops_isNonloop_eq : M.removeLoops.IsNonloop = M.IsNonloop := by ext e rw [removeLoops_eq_restrict, restrict_isNonloop_iff, mem_setOf, and_self] lemma IsNonloop.removeLoops_isNonloop (he : M.IsNonloop e) : M.removeLoops.IsNonloop e := by simpa lemma removeLoops_idem (M : Matroid α) : M.removeLoops.removeLoops = M.removeLoops := by simp lemma removeLoops_restrict_eq_restrict (hX : X ⊆ {e | M.IsNonloop e}) : M.removeLoops ↾ X = M ↾ X := by rwa [removeLoops_eq_restrict, restrict_restrict_eq] @[simp] lemma restrict_univ_removeLoops_eq : (M ↾ univ).removeLoops = M.removeLoops := by rw [removeLoops_eq_restrict, restrict_restrict_eq _ (subset_univ _), removeLoops_eq_restrict] simp lemma IsRestriction.isRestriction_removeLoops (hNM : N ≤r M) [N.Loopless] : N ≤r M.removeLoops := by obtain ⟨R, hR, rfl⟩ := hNM.exists_eq_restrict exact IsRestriction.of_subset M fun e heR ↦ ((M ↾ R).isNonloop_of_loopless heR).of_restrict lemma removeLoops_mono_isRestriction (hNM : N ≤r M) : N.removeLoops ≤r M.removeLoops := ((removeLoops_isRestriction _).trans hNM).isRestriction_removeLoops end Loopless end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/IndepAxioms.lean
import Mathlib.Combinatorics.Matroid.Basic import Mathlib.Data.Set.Finite.Lattice import Mathlib.Order.Interval.Finset.Nat /-! # Matroid Independence and Basis axioms Matroids in mathlib are defined axiomatically in terms of bases, but can be described just as naturally via their collections of independent sets, and in fact such a description, being more 'verbose', can often be useful. As well as this, the definition of a `Matroid` uses an unwieldy 'maximality' axiom that can be dropped in cases where there is some finiteness assumption. This file provides several ways to do define a matroid in terms of its independence or base predicates, using axiom sets that are appropriate in different settings, and often much simpler than the general definition. It also contains `simp` lemmas and typeclasses as appropriate. All the independence axiom sets need nontriviality (the empty set is independent), monotonicity (subsets of independent sets are independent), and some form of 'augmentation' axiom, which allows one to enlarge a non-maximal independent set. This augmentation axiom is still required when there are finiteness assumptions, but is simpler. It just states that if `I` is a finite independent set and `J` is a larger finite independent set, then there exists `e ∈ J \ I` for which `insert e I` is independent. This is the axiom that appears in most of the definitions. ## Implementation Details To facilitate building a matroid from its independent sets, we define a structure `IndepMatroid` which has a ground set `E`, an independence predicate `Indep`, and some axioms as its fields. This structure is another encoding of the data in a `Matroid`; the function `IndepMatroid.matroid` constructs a `Matroid` from an `IndepMatroid`. This is convenient because if one wants to define `M : Matroid α` from a known independence predicate `Ind`, it is easier to define an `M' : IndepMatroid α` so that `M'.Indep = Ind` and then set `M = M'.matroid` than it is to directly define `M` with the base axioms. The simp lemma `IndepMatroid.matroid_indep_iff` is important here; it shows that `M.Indep = Ind`, so the `Matroid` constructed is the right one, and the intermediate `IndepMatroid` can be made essentially invisible by the simplifier when working with `M`. Because of this setup, we don't define any API for `IndepMatroid`, as it would be a redundant copy of the existing API for `Matroid.Indep`. (In particular, one could define a natural equivalence `e : IndepMatroid α ≃ Matroid α` with `e.toFun = IndepMatroid.matroid`, but this would be pointless, as there is no need for the inverse of `e`). ## Main definitions * `IndepMatroid α` is a matroid structure on `α` described in terms of its independent sets in full generality, using infinite versions of the axioms. * `IndepMatroid.matroid` turns `M' : IndepMatroid α` into `M : Matroid α` with `M'.Indep = M.Indep`. * `IndepMatroid.ofFinitary` constructs an `IndepMatroid` whose associated `Matroid` is `Finitary` in the special case where independence of a set is determined only by that of its finite subsets. This construction uses Zorn's lemma. * `IndepMatroid.ofFinitaryCardAugment` is a variant of `IndepMatroid.ofFinitary` where the augmentation axiom resembles the finite augmentation axiom. * `IndepMatroid.ofBdd` constructs an `IndepMatroid` in the case where there is some known absolute upper bound on the size of an independent set. This uses the infinite version of the augmentation axiom; the corresponding `Matroid` is `RankFinite`. * `IndepMatroid.ofBddAugment` is the same as the above, but with a finite augmentation axiom. * `IndepMatroid.ofFinite` constructs an `IndepMatroid` from a finite ground set in terms of its independent sets. * `IndepMatroid.ofFinset` constructs an `IndepMatroid α` whose corresponding matroid is `Finitary` from an independence predicate on `Finset α`. * `Matroid.ofExistsMatroid` constructs a 'copy' of a matroid that is known only existentially, but whose independence predicate is known explicitly. * `Matroid.ofExistsFiniteIsBase` constructs a matroid from its bases, if it is known that one of them is finite. This gives a `RankFinite` matroid. * `Matroid.ofIsBaseOfFinite` constructs a `Finite` matroid from its bases. -/ assert_not_exists Field open Set Matroid variable {α : Type*} section IndepMatroid /-- A matroid as defined by a ground set and an independence predicate. This definition is an implementation detail whose purpose is to organize the multiple different versions of the independence axioms; usually, terms of type `IndepMatroid` should either be directly piped into `IndepMatroid.matroid`, or should be constructed as a private definition which is then converted into a matroid via `IndepMatroid.matroid`. To define a `Matroid α` from a known independence predicate `MyIndep : Set α → Prop` and ground set `E : Set α`, one can either write ``` def myMatroid (…) : Matroid α := IndepMatroid.matroid <| IndepMatroid.ofFoo E MyIndep _ _ … _ ``` or, slightly more indirectly, ``` private def myIndepMatroid (…) : IndepMatroid α := IndepMatroid.ofFoo E MyIndep _ _ … _ def myMatroid (…) : Matroid α := (myIndepMatroid …).matroid ``` In both cases, `IndepMatroid.ofFoo` is either `IndepMatroid.mk`, or one of the several other available constructors for `IndepMatroid`, and the `_` represent the proofs that this constructor requires. After such a definition is made, the facts that `myMatroid.Indep = myIndep` and `myMatroid.E = E` are true by either `rfl` or `simp [myMatroid]`, and can be made directly into @[simp] lemmas. -/ structure IndepMatroid (α : Type*) where /-- The ground set -/ (E : Set α) /-- The independence predicate -/ (Indep : Set α → Prop) (indep_empty : Indep ∅) (indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I) (indep_aug : ∀ ⦃I B⦄, Indep I → ¬ Maximal Indep I → Maximal Indep B → ∃ x ∈ B \ I, Indep (insert x I)) (indep_maximal : ∀ X, X ⊆ E → ExistsMaximalSubsetProperty Indep X) (subset_ground : ∀ I, Indep I → I ⊆ E) namespace IndepMatroid /-- An `M : IndepMatroid α` gives a `Matroid α` whose bases are the maximal `M`-independent sets. -/ @[simps] protected def matroid (M : IndepMatroid α) : Matroid α where E := M.E IsBase := Maximal M.Indep Indep := M.Indep indep_iff' := by refine fun I ↦ ⟨fun h ↦ ?_, fun ⟨B, ⟨h, _⟩, hIB'⟩ ↦ M.indep_subset h hIB'⟩ obtain ⟨J, hIJ, hmax⟩ := M.indep_maximal M.E rfl.subset I h (M.subset_ground I h) rw [maximal_and_iff_right_of_imp M.subset_ground] at hmax exact ⟨J, hmax.1, hIJ⟩ exists_isBase := by obtain ⟨B, -, hB⟩ := M.indep_maximal M.E rfl.subset ∅ M.indep_empty <| empty_subset _ rw [maximal_and_iff_right_of_imp M.subset_ground] at hB exact ⟨B, hB.1⟩ isBase_exchange B B' hB hB' e he := by have hnotmax : ¬ Maximal M.Indep (B \ {e}) := fun h ↦ h.not_prop_of_ssuperset (diff_singleton_ssubset.2 he.1) hB.prop obtain ⟨f, hf, hfB⟩ := M.indep_aug (M.indep_subset hB.prop diff_subset) hnotmax hB' replace hf := show f ∈ B' \ B by simpa [show f ≠ e by rintro rfl; exact he.2 hf.1] using hf refine ⟨f, hf, by_contra fun hnot ↦ ?_⟩ obtain ⟨x, hxB, hind⟩ := M.indep_aug hfB hnot hB obtain ⟨-, rfl⟩ : _ ∧ x = e := by simpa [hxB.1] using hxB refine hB.not_prop_of_ssuperset ?_ hind rw [insert_comm, insert_diff_singleton, insert_eq_of_mem he.1] exact ssubset_insert hf.2 maximality := M.indep_maximal subset_ground B hB := M.subset_ground B hB.1 @[simp] theorem matroid_indep_iff {M : IndepMatroid α} {I : Set α} : M.matroid.Indep I ↔ M.Indep I := Iff.rfl /-- If `Indep` has the 'compactness' property that each set `I` satisfies `Indep I` if and only if `Indep J` for every finite subset `J` of `I`, then an `IndepMatroid` can be constructed without proving the maximality axiom. This needs choice, since it can be used to prove that every vector space has a basis. -/ @[simps E] protected def ofFinitary (E : Set α) (Indep : Set α → Prop) (indep_empty : Indep ∅) (indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I) (indep_aug : ∀ ⦃I B⦄, Indep I → ¬ Maximal Indep I → Maximal Indep B → ∃ x ∈ B \ I, Indep (insert x I)) (indep_compact : ∀ I, (∀ J, J ⊆ I → J.Finite → Indep J) → Indep I) (subset_ground : ∀ I, Indep I → I ⊆ E) : IndepMatroid α where E := E Indep := Indep indep_empty := indep_empty indep_subset := indep_subset indep_aug := indep_aug indep_maximal := by refine fun X _ I hI hIX ↦ zorn_subset_nonempty {Y | Indep Y ∧ Y ⊆ X} ?_ I ⟨hI, hIX⟩ refine fun Is hIs hchain _ ↦ ⟨⋃₀ Is, ⟨?_, sUnion_subset fun Y hY ↦ (hIs hY).2⟩, fun _ ↦ subset_sUnion_of_mem⟩ refine indep_compact _ fun J hJ hJfin ↦ ?_ have hchoose : ∀ e, e ∈ J → ∃ I, I ∈ Is ∧ (e : α) ∈ I := fun _ he ↦ mem_sUnion.1 <| hJ he choose! f hf using hchoose refine J.eq_empty_or_nonempty.elim (fun hJ ↦ hJ ▸ indep_empty) (fun hne ↦ ?_) obtain ⟨x, hxJ, hxmax⟩ := Finite.exists_maximalFor f _ hJfin hne refine indep_subset (hIs (hf x hxJ).1).1 fun y hyJ ↦ ?_ obtain (hle | hle) := hchain.total (hf _ hxJ).1 (hf _ hyJ).1 · exact hxmax hyJ hle <| (hf _ hyJ).2 · exact hle (hf _ hyJ).2 subset_ground := subset_ground @[simp] theorem ofFinitary_indep (E : Set α) (Indep : Set α → Prop) indep_empty indep_subset indep_aug indep_compact subset_ground : (IndepMatroid.ofFinitary E Indep indep_empty indep_subset indep_aug indep_compact subset_ground).Indep = Indep := rfl instance ofFinitary_finitary (E : Set α) (Indep : Set α → Prop) indep_empty indep_subset indep_aug indep_compact subset_ground : Finitary (IndepMatroid.ofFinitary E Indep indep_empty indep_subset indep_aug indep_compact subset_ground).matroid := ⟨by simpa⟩ /-- An independence predicate satisfying the finite matroid axioms determines a matroid, provided independence is determined by its behaviour on finite sets. -/ @[simps! E] protected def ofFinitaryCardAugment (E : Set α) (Indep : Set α → Prop) (indep_empty : Indep ∅) (indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I) (indep_aug : ∀ ⦃I J⦄, Indep I → I.Finite → Indep J → J.Finite → I.ncard < J.ncard → ∃ e ∈ J, e ∉ I ∧ Indep (insert e I)) (indep_compact : ∀ I, (∀ J, J ⊆ I → J.Finite → Indep J) → Indep I) (subset_ground : ∀ I, Indep I → I ⊆ E) : IndepMatroid α := IndepMatroid.ofFinitary (E := E) (Indep := Indep) (indep_empty := indep_empty) (indep_subset := indep_subset) (indep_compact := indep_compact) (indep_aug := by have htofin : ∀ I e, Indep I → ¬ Indep (insert e I) → ∃ I₀, I₀ ⊆ I ∧ I₀.Finite ∧ ¬ Indep (insert e I₀) := by by_contra! h obtain ⟨I, e, -, hIe, h⟩ := h refine hIe <| indep_compact _ fun J hJss hJfin ↦ ?_ exact indep_subset (h (J \ {e}) (by rwa [diff_subset_iff]) hJfin.diff) (by simp) intro I B hI hImax hBmax obtain ⟨e, heI, hins⟩ := exists_insert_of_not_maximal indep_subset hI hImax by_cases heB : e ∈ B · exact ⟨e, ⟨heB, heI⟩, hins⟩ by_contra! hcon have heBdep := hBmax.not_prop_of_ssuperset (ssubset_insert heB) -- There is a finite subset `B₀` of `B` so that `B₀ + e` is dependent obtain ⟨B₀, hB₀B, hB₀fin, hB₀e⟩ := htofin B e hBmax.1 heBdep have hB₀ := indep_subset hBmax.1 hB₀B -- `I` has a finite subset `I₀` that doesn't extend into `B₀` have hexI₀ : ∃ I₀, I₀ ⊆ I ∧ I₀.Finite ∧ ∀ x, x ∈ B₀ \ I₀ → ¬Indep (insert x I₀) := by have hch : ∀ (b : ↑(B₀ \ I)), ∃ Ib, Ib ⊆ I ∧ Ib.Finite ∧ ¬Indep (insert (b : α) Ib) := by rintro ⟨b, hb⟩; exact htofin I b hI (hcon b ⟨hB₀B hb.1, hb.2⟩) choose! f hf using hch have : Finite ↑(B₀ \ I) := hB₀fin.diff.to_subtype refine ⟨iUnion f ∪ (B₀ ∩ I), union_subset (iUnion_subset (fun i ↦ (hf i).1)) inter_subset_right, (finite_iUnion fun i ↦ (hf i).2.1).union (hB₀fin.subset inter_subset_left), fun x ⟨hxB₀, hxn⟩ hi ↦ ?_⟩ have hxI : x ∉ I := fun hxI ↦ hxn <| Or.inr ⟨hxB₀, hxI⟩ refine (hf ⟨x, ⟨hxB₀, hxI⟩⟩).2.2 (indep_subset hi <| insert_subset_insert ?_) apply subset_union_of_subset_left apply subset_iUnion obtain ⟨I₀, hI₀I, hI₀fin, hI₀⟩ := hexI₀ set E₀ := insert e (I₀ ∪ B₀) have hE₀fin : E₀.Finite := (hI₀fin.union hB₀fin).insert e -- Extend `B₀` to a maximal independent subset of `I₀ ∪ B₀ + e` obtain ⟨J, ⟨hB₀J, hJ, hJss⟩, hJmax⟩ := Finite.exists_maximalFor (f := id) (s := {J | B₀ ⊆ J ∧ Indep J ∧ J ⊆ E₀}) (hE₀fin.finite_subsets.subset (by simp)) ⟨B₀, Subset.rfl, hB₀, subset_union_right.trans (subset_insert _ _)⟩ have heI₀ : e ∉ I₀ := notMem_subset hI₀I heI have heI₀i : Indep (insert e I₀) := indep_subset hins (insert_subset_insert hI₀I) have heJ : e ∉ J := fun heJ ↦ hB₀e (indep_subset hJ <| insert_subset heJ hB₀J) have hJfin := hE₀fin.subset hJss -- We have `|I₀ + e| ≤ |J|`, since otherwise we could extend the maximal set `J` have hcard : (insert e I₀).ncard ≤ J.ncard := by refine not_lt.1 fun hlt ↦ ?_ obtain ⟨f, hfI, hfJ, hfi⟩ := indep_aug hJ hJfin heI₀i (hI₀fin.insert e) hlt have hfE₀ : f ∈ E₀ := mem_of_mem_of_subset hfI (insert_subset_insert subset_union_left) exact hfJ <| insert_eq_self.1 <| le_imp_eq_iff_le_imp_ge'.2 (hJmax ⟨hB₀J.trans <| subset_insert _ _, hfi, insert_subset hfE₀ hJss⟩) (subset_insert _ _) -- But this means `|I₀| < |J|`, and extending `I₀` into `J` gives a contradiction rw [ncard_insert_of_notMem heI₀ hI₀fin, ← Nat.lt_iff_add_one_le] at hcard obtain ⟨f, hfJ, hfI₀, hfi⟩ := indep_aug (indep_subset hI hI₀I) hI₀fin hJ hJfin hcard exact hI₀ f ⟨Or.elim (hJss hfJ) (fun hfe ↦ (heJ <| hfe ▸ hfJ).elim) (by aesop), hfI₀⟩ hfi ) (subset_ground := subset_ground) @[simp] theorem ofFinitaryCardAugment_indep (E : Set α) (Indep : Set α → Prop) indep_empty indep_subset indep_aug indep_compact subset_ground : (IndepMatroid.ofFinitaryCardAugment E Indep indep_empty indep_subset indep_aug indep_compact subset_ground).Indep = Indep := rfl instance ofFinitaryCardAugment_finitary (E : Set α) (Indep : Set α → Prop) indep_empty indep_subset indep_aug indep_compact subset_ground : Finitary (IndepMatroid.ofFinitaryCardAugment E Indep indep_empty indep_subset indep_aug indep_compact subset_ground).matroid := ⟨by simpa⟩ /-- If there is an absolute upper bound on the size of a set satisfying `P`, then the maximal subset property always holds. -/ theorem _root_.Matroid.existsMaximalSubsetProperty_of_bdd {P : Set α → Prop} (hP : ∃ (n : ℕ), ∀ Y, P Y → Y.encard ≤ n) (X : Set α) : ExistsMaximalSubsetProperty P X := by obtain ⟨n, hP⟩ := hP rintro I hI hIX have hfin : Set.Finite (ncard '' {Y | P Y ∧ I ⊆ Y ∧ Y ⊆ X}) := by rw [finite_iff_bddAbove, bddAbove_def] simp_rw [ENat.le_coe_iff] at hP use n rintro x ⟨Y, ⟨hY,-,-⟩, rfl⟩ obtain ⟨n₀, heq, hle⟩ := hP Y hY rwa [ncard_def, heq, ENat.toNat_coe] obtain ⟨Y, ⟨hY, hIY, hYX⟩, hY'⟩ := Finite.exists_maximalFor' ncard _ hfin ⟨I, hI, rfl.subset, hIX⟩ refine ⟨Y, hIY, ⟨hY, hYX⟩, fun K ⟨hPK, hKX⟩ hYK ↦ ?_⟩ have hKfin : K.Finite := finite_of_encard_le_coe (hP K hPK) refine (eq_of_subset_of_ncard_le hYK ?_ hKfin).symm.subset exact hY' ⟨hPK, hIY.trans hYK, hKX⟩ (ncard_le_ncard hYK hKfin) /-- If there is an absolute upper bound on the size of an independent set, then the maximality axiom isn't needed to define a matroid by independent sets. -/ @[simps E] protected def ofBdd (E : Set α) (Indep : Set α → Prop) (indep_empty : Indep ∅) (indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I) (indep_aug : ∀ ⦃I B⦄, Indep I → ¬ Maximal Indep I → Maximal Indep B → ∃ x ∈ B \ I, Indep (insert x I)) (subset_ground : ∀ I, Indep I → I ⊆ E) (indep_bdd : ∃ (n : ℕ), ∀ I, Indep I → I.encard ≤ n) : IndepMatroid α where E := E Indep := Indep indep_empty := indep_empty indep_subset := indep_subset indep_aug := indep_aug indep_maximal X _ := Matroid.existsMaximalSubsetProperty_of_bdd indep_bdd X subset_ground := subset_ground @[simp] theorem ofBdd_indep (E : Set α) Indep indep_empty indep_subset indep_aug subset_ground h_bdd : (IndepMatroid.ofBdd E Indep indep_empty indep_subset indep_aug subset_ground h_bdd).Indep = Indep := rfl /-- `IndepMatroid.ofBdd` constructs a `RankFinite` matroid. -/ instance (E : Set α) (Indep : Set α → Prop) indep_empty indep_subset indep_aug subset_ground h_bdd : RankFinite (IndepMatroid.ofBdd E Indep indep_empty indep_subset indep_aug subset_ground h_bdd).matroid := by obtain ⟨B, hB⟩ := (IndepMatroid.ofBdd E Indep _ _ _ _ _).matroid.exists_isBase refine hB.rankFinite_of_finite ?_ obtain ⟨n, hn⟩ := h_bdd exact finite_of_encard_le_coe <| hn B (by simpa using hB.indep) /-- If there is an absolute upper bound on the size of an independent set, then matroids can be defined using an 'augmentation' axiom similar to the standard definition of finite matroids for independent sets. -/ protected def ofBddAugment (E : Set α) (Indep : Set α → Prop) (indep_empty : Indep ∅) (indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I) (indep_aug : ∀ ⦃I J⦄, Indep I → Indep J → I.encard < J.encard → ∃ e ∈ J, e ∉ I ∧ Indep (insert e I)) (indep_bdd : ∃ (n : ℕ), ∀ I, Indep I → I.encard ≤ n) (subset_ground : ∀ I, Indep I → I ⊆ E) : IndepMatroid α := IndepMatroid.ofBdd (E := E) (Indep := Indep) (indep_empty := indep_empty) (indep_subset := indep_subset) (indep_aug := by rintro I B hI hImax hBmax suffices hcard : I.encard < B.encard by obtain ⟨e, heB, heI, hi⟩ := indep_aug hI hBmax.prop hcard exact ⟨e, ⟨heB, heI⟩, hi⟩ refine lt_of_not_ge fun hle ↦ ?_ obtain ⟨x, hxnot, hxI⟩ := exists_insert_of_not_maximal indep_subset hI hImax have hlt : B.encard < (insert x I).encard := by rwa [encard_insert_of_notMem hxnot, ← not_le, ENat.add_one_le_iff, not_lt] rw [encard_ne_top_iff] obtain ⟨n, hn⟩ := indep_bdd exact finite_of_encard_le_coe (hn _ hI) obtain ⟨y, -, hyB, hi⟩ := indep_aug hBmax.prop hxI hlt exact hBmax.not_prop_of_ssuperset (ssubset_insert hyB) hi) (indep_bdd := indep_bdd) (subset_ground := subset_ground) @[simp] theorem ofBddAugment_E (E : Set α) Indep indep_empty indep_subset indep_aug indep_bdd subset_ground : (IndepMatroid.ofBddAugment E Indep indep_empty indep_subset indep_aug indep_bdd subset_ground).E = E := rfl @[simp] theorem ofBddAugment_indep (E : Set α) Indep indep_empty indep_subset indep_aug indep_bdd subset_ground : (IndepMatroid.ofBddAugment E Indep indep_empty indep_subset indep_aug indep_bdd subset_ground).Indep = Indep := rfl instance ofBddAugment_rankFinite (E : Set α) Indep indep_empty indep_subset indep_aug indep_bdd subset_ground : RankFinite (IndepMatroid.ofBddAugment E Indep indep_empty indep_subset indep_aug indep_bdd subset_ground).matroid := by rw [IndepMatroid.ofBddAugment] infer_instance /-- If `E` is finite, then any collection of subsets of `E` satisfying the usual independence axioms determines a matroid -/ protected def ofFinite {E : Set α} (hE : E.Finite) (Indep : Set α → Prop) (indep_empty : Indep ∅) (indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I) (indep_aug : ∀ ⦃I J⦄, Indep I → Indep J → I.ncard < J.ncard → ∃ e ∈ J, e ∉ I ∧ Indep (insert e I)) (subset_ground : ∀ ⦃I⦄, Indep I → I ⊆ E) : IndepMatroid α := IndepMatroid.ofBddAugment (E := E) (Indep := Indep) (indep_empty := indep_empty) (indep_subset := indep_subset) (indep_aug := by refine fun {I J} hI hJ hIJ ↦ indep_aug hI hJ ?_ rwa [← Nat.cast_lt (α := ℕ∞), (hE.subset (subset_ground hJ)).cast_ncard_eq, (hE.subset (subset_ground hI)).cast_ncard_eq] ) (indep_bdd := ⟨E.ncard, fun I hI ↦ by rw [hE.cast_ncard_eq] exact encard_le_encard <| subset_ground hI ⟩) (subset_ground := subset_ground) @[simp] theorem ofFinite_E {E : Set α} hE Indep indep_empty indep_subset indep_aug subset_ground : (IndepMatroid.ofFinite (hE : E.Finite) Indep indep_empty indep_subset indep_aug subset_ground).E = E := rfl @[simp] theorem ofFinite_indep {E : Set α} hE Indep indep_empty indep_subset indep_aug subset_ground : (IndepMatroid.ofFinite (hE : E.Finite) Indep indep_empty indep_subset indep_aug subset_ground).Indep = Indep := rfl instance ofFinite_finite {E : Set α} hE Indep indep_empty indep_subset indep_aug subset_ground : (IndepMatroid.ofFinite (hE : E.Finite) Indep indep_empty indep_subset indep_aug subset_ground).matroid.Finite := ⟨hE⟩ /-- An independence predicate on `Finset α` that obeys the finite matroid axioms determines a finitary matroid on `α`. -/ protected def ofFinset [DecidableEq α] (E : Set α) (Indep : Finset α → Prop) (indep_empty : Indep ∅) (indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I) (indep_aug : ∀ ⦃I J⦄, Indep I → Indep J → I.card < J.card → ∃ e ∈ J, e ∉ I ∧ Indep (insert e I)) (subset_ground : ∀ ⦃I⦄, Indep I → (I : Set α) ⊆ E) : IndepMatroid α := IndepMatroid.ofFinitaryCardAugment (E := E) (Indep := (fun I ↦ (∀ (J : Finset α), (J : Set α) ⊆ I → Indep J))) (indep_empty := by simpa [subset_empty_iff]) (indep_subset := ( fun _ _ hJ hIJ _ hKI ↦ hJ _ (hKI.trans hIJ) )) (indep_aug := by intro I J hI hIfin hJ hJfin hIJ rw [ncard_eq_toFinset_card _ hIfin, ncard_eq_toFinset_card _ hJfin] at hIJ have aug := indep_aug (hI _ (by simp)) (hJ _ (by simp)) hIJ simp only [Finite.mem_toFinset] at aug obtain ⟨e, heJ, heI, hi⟩ := aug exact ⟨e, heJ, heI, fun K hK ↦ indep_subset hi <| Finset.coe_subset.1 (by simpa)⟩ ) (indep_compact := fun _ h J hJ ↦ h _ hJ J.finite_toSet _ Subset.rfl ) (subset_ground := fun I hI x hxI ↦ by simpa using subset_ground <| hI {x} (by simpa) ) @[simp] theorem ofFinset_E [DecidableEq α] (E : Set α) Indep indep_empty indep_subset indep_aug subset_ground : (IndepMatroid.ofFinset E Indep indep_empty indep_subset indep_aug subset_ground).E = E := rfl @[simp] theorem ofFinset_indep [DecidableEq α] (E : Set α) Indep indep_empty indep_subset indep_aug subset_ground {I : Finset α} : (IndepMatroid.ofFinset E Indep indep_empty indep_subset indep_aug subset_ground).Indep I ↔ Indep I := by simp only [IndepMatroid.ofFinset, ofFinitaryCardAugment_indep, Finset.coe_subset] exact ⟨fun h ↦ h _ Subset.rfl, fun h J hJI ↦ indep_subset h hJI⟩ /-- This can't be `@[simp]`, because it would cause the more useful `Matroid.ofIndepFinset_apply` not to be in simp normal form. -/ theorem ofFinset_indep' [DecidableEq α] (E : Set α) Indep indep_empty indep_subset indep_aug subset_ground {I : Set α} : (IndepMatroid.ofFinset E Indep indep_empty indep_subset indep_aug subset_ground).Indep I ↔ ∀ (J : Finset α), (J : Set α) ⊆ I → Indep J := by simp only [IndepMatroid.ofFinset, ofFinitaryCardAugment_indep] end IndepMatroid section IsBase namespace Matroid /-- Construct an `Matroid` from an independence predicate that agrees with that of some matroid `M`. This is computable even if `M` is only known existentially, or when `M` exists for different reasons in different cases. This can also be used to change the independence predicate to a more useful definitional form. -/ @[simps! E] protected def ofExistsMatroid (E : Set α) (Indep : Set α → Prop) (hM : ∃ (M : Matroid α), E = M.E ∧ ∀ I, M.Indep I ↔ Indep I) : Matroid α := IndepMatroid.matroid <| have hex : ∃ (M : Matroid α), E = M.E ∧ M.Indep = Indep := by obtain ⟨M, rfl, h⟩ := hM; refine ⟨_, rfl, funext (by simp [h])⟩ IndepMatroid.mk (E := E) (Indep := Indep) (indep_empty := by obtain ⟨M, -, rfl⟩ := hex; exact M.empty_indep) (indep_subset := by obtain ⟨M, -, rfl⟩ := hex; exact fun I J hJ hIJ ↦ hJ.subset hIJ) (indep_aug := by obtain ⟨M, -, rfl⟩ := hex; exact Indep.exists_insert_of_not_maximal M) (indep_maximal := by obtain ⟨M, rfl, rfl⟩ := hex; exact M.existsMaximalSubsetProperty_indep) (subset_ground := by obtain ⟨M, rfl, rfl⟩ := hex; exact fun I ↦ Indep.subset_ground) /-- A matroid defined purely in terms of its bases. -/ @[simps E] protected def ofBase (E : Set α) (IsBase : Set α → Prop) (exists_isBase : ∃ B, IsBase B) (isBase_exchange : ExchangeProperty IsBase) (maximality : ∀ X, X ⊆ E → Matroid.ExistsMaximalSubsetProperty (∃ B, IsBase B ∧ · ⊆ B) X) (subset_ground : ∀ B, IsBase B → B ⊆ E) : Matroid α where E := E IsBase := IsBase Indep I := (∃ B, IsBase B ∧ I ⊆ B) indep_iff' _ := Iff.rfl exists_isBase := exists_isBase isBase_exchange := isBase_exchange maximality := maximality subset_ground := subset_ground /-- A collection of bases with the exchange property and at least one finite member is a matroid -/ @[simps! E] protected def ofExistsFiniteIsBase (E : Set α) (IsBase : Set α → Prop) (exists_finite_base : ∃ B, IsBase B ∧ B.Finite) (isBase_exchange : ExchangeProperty IsBase) (subset_ground : ∀ B, IsBase B → B ⊆ E) : Matroid α := Matroid.ofBase (E := E) (IsBase := IsBase) (exists_isBase := by obtain ⟨B,h⟩ := exists_finite_base; exact ⟨B, h.1⟩) (isBase_exchange := isBase_exchange) (maximality := by obtain ⟨B, hB, hfin⟩ := exists_finite_base refine fun X _ ↦ Matroid.existsMaximalSubsetProperty_of_bdd ⟨B.ncard, fun Y ⟨B', hB', hYB'⟩ ↦ ?_⟩ X rw [hfin.cast_ncard_eq, isBase_exchange.encard_isBase_eq hB hB'] exact encard_mono hYB') (subset_ground := subset_ground) @[simp] theorem ofExistsFiniteIsBase_isBase (E : Set α) IsBase exists_finite_base isBase_exchange subset_ground : (Matroid.ofExistsFiniteIsBase E IsBase exists_finite_base isBase_exchange subset_ground).IsBase = IsBase := rfl instance ofExistsFiniteIsBase_rankFinite (E : Set α) IsBase exists_finite_base isBase_exchange subset_ground : RankFinite (Matroid.ofExistsFiniteIsBase E IsBase exists_finite_base isBase_exchange subset_ground) := by obtain ⟨B, hB, hfin⟩ := exists_finite_base exact Matroid.IsBase.rankFinite_of_finite (by simpa) hfin /-- If `E` is finite, then any nonempty collection of its subsets with the exchange property is the collection of bases of a matroid on `E`. -/ protected def ofIsBaseOfFinite {E : Set α} (hE : E.Finite) (IsBase : Set α → Prop) (exists_isBase : ∃ B, IsBase B) (isBase_exchange : ExchangeProperty IsBase) (subset_ground : ∀ B, IsBase B → B ⊆ E) : Matroid α := Matroid.ofExistsFiniteIsBase (E := E) (IsBase := IsBase) (exists_finite_base := let ⟨B, hB⟩ := exists_isBase ⟨B, hB, hE.subset (subset_ground B hB)⟩) (isBase_exchange := isBase_exchange) (subset_ground := subset_ground) @[simp] theorem ofIsBaseOfFinite_E {E : Set α} (hE : E.Finite) IsBase exists_isBase isBase_exchange subset_ground : (Matroid.ofIsBaseOfFinite hE IsBase exists_isBase isBase_exchange subset_ground).E = E := rfl @[simp] theorem ofIsBaseOfFinite_isBase {E : Set α} (hE : E.Finite) IsBase exists_isBase isBase_exchange subset_ground : (Matroid.ofIsBaseOfFinite hE IsBase exists_isBase isBase_exchange subset_ground).IsBase = IsBase := rfl instance ofBaseOfFinite_finite {E : Set α} (hE : E.Finite) IsBase exists_isBase isBase_exchange subset_ground : (Matroid.ofIsBaseOfFinite hE IsBase exists_isBase isBase_exchange subset_ground).Finite := ⟨hE⟩ end Matroid end IsBase end IndepMatroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Dual.lean
import Mathlib.Combinatorics.Matroid.IndepAxioms /-! # Matroid Duality For a matroid `M` on ground set `E`, the collection of complements of the bases of `M` is the collection of bases of another matroid on `E` called the 'dual' of `M`. The map from `M` to its dual is an involution, interacts nicely with minors, and preserves many important matroid properties such as representability and connectivity. This file defines the dual matroid `M✶` of `M`, and gives associated API. The definition is in terms of its independent sets, using `IndepMatroid.matroid`. We also define 'Co-independence' (independence in the dual) of a set as a predicate `M.Coindep X`. This is an abbreviation for `M✶.Indep X`, but has its own name for the sake of dot notation. ## Main Definitions * `M.Dual`, written `M✶`, is the matroid on `M.E` which a set `B ⊆ M.E` is a base if and only if `M.E \ B` is a base for `M`. * `M.Coindep X` means `M✶.Indep X`, or equivalently that `X` is contained in `M.E \ B` for some base `B` of `M`. -/ assert_not_exists Field open Set namespace Matroid variable {α : Type*} {M : Matroid α} {I B X : Set α} section dual /-- Given `M : Matroid α`, the `IndepMatroid α` whose independent sets are the subsets of `M.E` that are disjoint from some base of `M` -/ @[simps] def dualIndepMatroid (M : Matroid α) : IndepMatroid α where E := M.E Indep I := I ⊆ M.E ∧ ∃ B, M.IsBase B ∧ Disjoint I B indep_empty := ⟨empty_subset M.E, M.exists_isBase.imp (fun _ hB ↦ ⟨hB, empty_disjoint _⟩)⟩ indep_subset := by rintro I J ⟨hJE, B, hB, hJB⟩ hIJ exact ⟨hIJ.trans hJE, ⟨B, hB, disjoint_of_subset_left hIJ hJB⟩⟩ indep_aug := by rintro I X ⟨hIE, B, hB, hIB⟩ hI_not_max hX_max have hXE := hX_max.1.1 have hB' := (isBase_compl_iff_maximal_disjoint_isBase hXE).mpr hX_max set B' := M.E \ X with hX have hI := (not_iff_not.mpr (isBase_compl_iff_maximal_disjoint_isBase)).mpr hI_not_max obtain ⟨B'', hB'', hB''₁, hB''₂⟩ := (hB'.indep.diff I).exists_isBase_subset_union_isBase hB rw [← compl_subset_compl, ← hIB.sdiff_eq_right, ← union_diff_distrib, diff_eq, compl_inter, compl_compl, union_subset_iff, compl_subset_compl] at hB''₂ have hssu := (subset_inter (hB''₂.2) hIE).ssubset_of_ne (by { rintro rfl; apply hI; convert hB''; simp [hB''.subset_ground] }) obtain ⟨e, ⟨(heB'' : e ∉ _), heE⟩, heI⟩ := exists_of_ssubset hssu use e simp_rw [mem_diff, insert_subset_iff, and_iff_left heI, and_iff_right heE, and_iff_right hIE] refine ⟨by_contra (fun heX ↦ heB'' (hB''₁ ⟨?_, heI⟩)), ⟨B'', hB'', ?_⟩⟩ · rw [hX]; exact ⟨heE, heX⟩ rw [← union_singleton, disjoint_union_left, disjoint_singleton_left, and_iff_left heB''] exact disjoint_of_subset_left hB''₂.2 disjoint_compl_left indep_maximal := by rintro X - I' ⟨hI'E, B, hB, hI'B⟩ hI'X obtain ⟨I, hI⟩ := M.exists_isBasis (M.E \ X) obtain ⟨B', hB', hIB', hB'IB⟩ := hI.indep.exists_isBase_subset_union_isBase hB obtain rfl : I = B' \ X := hI.eq_of_subset_indep (hB'.indep.diff _) (subset_diff.2 ⟨hIB', (subset_diff.1 hI.subset).2⟩) (diff_subset_diff_left hB'.subset_ground) simp_rw [maximal_subset_iff'] refine ⟨(X \ B') ∩ M.E, ?_, ⟨⟨inter_subset_right, ?_⟩, ?_⟩, ?_⟩ · rw [subset_inter_iff, and_iff_left hI'E, subset_diff, and_iff_right hI'X] exact Disjoint.mono_right hB'IB <| disjoint_union_right.2 ⟨disjoint_sdiff_right.mono_left hI'X, hI'B⟩ · exact ⟨B', hB', (disjoint_sdiff_left (t := X)).mono_left inter_subset_left⟩ · exact inter_subset_left.trans diff_subset simp only [subset_inter_iff, subset_diff, and_imp, forall_exists_index] refine fun J hJE B'' hB'' hdj hJX hXJ ↦ ⟨⟨hJX, ?_⟩, hJE⟩ have hI' : (B'' ∩ X) ∪ (B' \ X) ⊆ B' := by rw [union_subset_iff, and_iff_left diff_subset, ← union_diff_cancel hJX, inter_union_distrib_left, hdj.symm.inter_eq, empty_union, diff_eq, ← inter_assoc, ← diff_eq, diff_subset_comm, diff_eq, inter_assoc, ← diff_eq, inter_comm] exact subset_trans (inter_subset_inter_right _ hB''.subset_ground) hXJ obtain ⟨B₁,hB₁,hI'B₁,hB₁I⟩ := (hB'.indep.subset hI').exists_isBase_subset_union_isBase hB'' rw [union_comm, ← union_assoc, union_eq_self_of_subset_right inter_subset_left] at hB₁I obtain rfl : B₁ = B' := by refine hB₁.eq_of_subset_indep hB'.indep (fun e he ↦ ?_) refine (hB₁I he).elim (fun heB'' ↦ ?_) (fun h ↦ h.1) refine (em (e ∈ X)).elim (fun heX ↦ hI' (Or.inl ⟨heB'', heX⟩)) (fun heX ↦ hIB' ?_) refine hI.mem_of_insert_indep ⟨hB₁.subset_ground he, heX⟩ ?_ exact hB₁.indep.subset (insert_subset he (subset_union_right.trans hI'B₁)) by_contra hdj' obtain ⟨e, heJ, heB'⟩ := not_disjoint_iff.mp hdj' obtain (heB'' | ⟨-,heX⟩ ) := hB₁I heB' · exact hdj.ne_of_mem heJ heB'' rfl exact heX (hJX heJ) subset_ground := by tauto /-- The dual of a matroid; the bases are the complements (w.r.t. `M.E`) of the bases of `M`. -/ def dual (M : Matroid α) : Matroid α := M.dualIndepMatroid.matroid /-- The `✶` symbol, which denotes matroid duality. (This is distinct from the usual `*` symbol for multiplication, due to precedence issues.) -/ postfix:max "✶" => Matroid.dual theorem dual_indep_iff_exists' : (M✶.Indep I) ↔ I ⊆ M.E ∧ (∃ B, M.IsBase B ∧ Disjoint I B) := Iff.rfl @[simp] theorem dual_ground : M✶.E = M.E := rfl theorem dual_indep_iff_exists (hI : I ⊆ M.E := by aesop_mat) : M✶.Indep I ↔ (∃ B, M.IsBase B ∧ Disjoint I B) := by rw [dual_indep_iff_exists', and_iff_right hI] theorem dual_dep_iff_forall : (M✶.Dep I) ↔ (∀ B, M.IsBase B → (I ∩ B).Nonempty) ∧ I ⊆ M.E := by simp_rw [dep_iff, dual_indep_iff_exists', dual_ground, and_congr_left_iff, not_and, not_exists, not_and, not_disjoint_iff_nonempty_inter, Classical.imp_iff_right_iff, iff_true_intro Or.inl] instance dual_finite [M.Finite] : M✶.Finite := ⟨M.ground_finite⟩ instance dual_nonempty [M.Nonempty] : M✶.Nonempty := ⟨M.ground_nonempty⟩ @[simp] theorem dual_isBase_iff (hB : B ⊆ M.E := by aesop_mat) : M✶.IsBase B ↔ M.IsBase (M.E \ B) := by rw [isBase_compl_iff_maximal_disjoint_isBase, isBase_iff_maximal_indep, maximal_subset_iff, maximal_subset_iff] simp [dual_indep_iff_exists', hB] theorem dual_isBase_iff' : M✶.IsBase B ↔ M.IsBase (M.E \ B) ∧ B ⊆ M.E := (em (B ⊆ M.E)).elim (fun h ↦ by rw [dual_isBase_iff, and_iff_left h]) (fun h ↦ iff_of_false (h ∘ (fun h' ↦ h'.subset_ground)) (h ∘ And.right)) theorem setOf_dual_isBase_eq : {B | M✶.IsBase B} = (fun X ↦ M.E \ X) '' {B | M.IsBase B} := by ext B simp only [mem_setOf_eq, mem_image, dual_isBase_iff'] refine ⟨fun h ↦ ⟨_, h.1, diff_diff_cancel_left h.2⟩, fun ⟨B', hB', h⟩ ↦ ⟨?_,h.symm.trans_subset diff_subset⟩⟩ rwa [← h, diff_diff_cancel_left hB'.subset_ground] @[simp] theorem dual_dual (M : Matroid α) : M✶✶ = M := ext_isBase rfl (fun B (h : B ⊆ M.E) ↦ by rw [dual_isBase_iff, dual_isBase_iff, dual_ground, diff_diff_cancel_left h]) theorem dual_involutive : Function.Involutive (dual : Matroid α → Matroid α) := dual_dual theorem dual_injective : Function.Injective (dual : Matroid α → Matroid α) := dual_involutive.injective @[simp] theorem dual_inj {M₁ M₂ : Matroid α} : M₁✶ = M₂✶ ↔ M₁ = M₂ := dual_injective.eq_iff theorem eq_dual_comm {M₁ M₂ : Matroid α} : M₁ = M₂✶ ↔ M₂ = M₁✶ := by rw [← dual_inj, dual_dual, eq_comm] theorem eq_dual_iff_dual_eq {M₁ M₂ : Matroid α} : M₁ = M₂✶ ↔ M₁✶ = M₂ := dual_involutive.eq_iff.symm theorem IsBase.compl_isBase_of_dual (h : M✶.IsBase B) : M.IsBase (M.E \ B) := (dual_isBase_iff'.1 h).1 theorem IsBase.compl_isBase_dual (h : M.IsBase B) : M✶.IsBase (M.E \ B) := by rwa [dual_isBase_iff, diff_diff_cancel_left h.subset_ground] theorem IsBase.compl_inter_isBasis_of_inter_isBasis (hB : M.IsBase B) (hBX : M.IsBasis (B ∩ X) X) : M✶.IsBasis ((M.E \ B) ∩ (M.E \ X)) (M.E \ X) := by refine Indep.isBasis_of_forall_insert ?_ inter_subset_right (fun e he ↦ ?_) · rw [dual_indep_iff_exists] exact ⟨B, hB, disjoint_of_subset_left inter_subset_left disjoint_sdiff_left⟩ simp only [diff_inter_self_eq_diff, mem_diff, not_and, not_not, imp_iff_right he.1.1] at he simp_rw [dual_dep_iff_forall, insert_subset_iff, and_iff_right he.1.1, and_iff_left (inter_subset_left.trans diff_subset)] refine fun B' hB' ↦ by_contra (fun hem ↦ ?_) rw [nonempty_iff_ne_empty, not_ne_iff, ← union_singleton, diff_inter_diff, union_inter_distrib_right, union_empty_iff, singleton_inter_eq_empty, diff_eq, inter_right_comm, inter_eq_self_of_subset_right hB'.subset_ground, ← diff_eq, diff_eq_empty] at hem obtain ⟨f, hfb, hBf⟩ := hB.exchange hB' ⟨he.2, hem.2⟩ have hi : M.Indep (insert f (B ∩ X)) := by refine hBf.indep.subset (insert_subset_insert ?_) simp_rw [subset_diff, and_iff_right inter_subset_left, disjoint_singleton_right, mem_inter_iff, iff_false_intro he.1.2, and_false, not_false_iff] exact hfb.2 (hBX.mem_of_insert_indep (Or.elim (hem.1 hfb.1) (False.elim ∘ hfb.2) id) hi).1 theorem IsBase.inter_isBasis_iff_compl_inter_isBasis_dual (hB : M.IsBase B) (hX : X ⊆ M.E := by aesop_mat) : M.IsBasis (B ∩ X) X ↔ M✶.IsBasis ((M.E \ B) ∩ (M.E \ X)) (M.E \ X) := by refine ⟨hB.compl_inter_isBasis_of_inter_isBasis, fun h ↦ ?_⟩ simpa [inter_eq_self_of_subset_right hX, inter_eq_self_of_subset_right hB.subset_ground] using hB.compl_isBase_dual.compl_inter_isBasis_of_inter_isBasis h theorem base_iff_dual_isBase_compl (hB : B ⊆ M.E := by aesop_mat) : M.IsBase B ↔ M✶.IsBase (M.E \ B) := by rw [dual_isBase_iff, diff_diff_cancel_left hB] theorem ground_not_isBase (M : Matroid α) [h : RankPos M✶] : ¬M.IsBase M.E := by rwa [rankPos_iff, dual_isBase_iff, diff_empty] at h theorem IsBase.ssubset_ground [h : RankPos M✶] (hB : M.IsBase B) : B ⊂ M.E := hB.subset_ground.ssubset_of_ne (by rintro rfl; exact M.ground_not_isBase hB) theorem Indep.ssubset_ground [h : RankPos M✶] (hI : M.Indep I) : I ⊂ M.E := by obtain ⟨B, hB⟩ := hI.exists_isBase_superset; exact hB.2.trans_ssubset hB.1.ssubset_ground /-- A coindependent set of `M` is an independent set of the dual of `M✶`. we give it a separate definition to enable dot notation. Which spelling is better depends on context. -/ abbrev Coindep (M : Matroid α) (I : Set α) : Prop := M✶.Indep I theorem coindep_def : M.Coindep X ↔ M✶.Indep X := Iff.rfl theorem Coindep.indep (hX : M.Coindep X) : M✶.Indep X := hX @[simp] theorem dual_coindep_iff : M✶.Coindep X ↔ M.Indep X := by rw [Coindep, dual_dual] theorem Indep.coindep (hI : M.Indep I) : M✶.Coindep I := dual_coindep_iff.2 hI theorem coindep_iff_exists' : M.Coindep X ↔ (∃ B, M.IsBase B ∧ B ⊆ M.E \ X) ∧ X ⊆ M.E := by simp_rw [Coindep, dual_indep_iff_exists', and_comm (a := _ ⊆ _), and_congr_left_iff, subset_diff] exact fun _ ↦ ⟨fun ⟨B, hB, hXB⟩ ↦ ⟨B, hB, hB.subset_ground, hXB.symm⟩, fun ⟨B, hB, _, hBX⟩ ↦ ⟨B, hB, hBX.symm⟩⟩ theorem coindep_iff_exists (hX : X ⊆ M.E := by aesop_mat) : M.Coindep X ↔ ∃ B, M.IsBase B ∧ B ⊆ M.E \ X := by rw [coindep_iff_exists', and_iff_left hX] theorem coindep_iff_subset_compl_isBase : M.Coindep X ↔ ∃ B, M.IsBase B ∧ X ⊆ M.E \ B := by simp_rw [coindep_iff_exists', subset_diff] exact ⟨fun ⟨⟨B, hB, _, hBX⟩, hX⟩ ↦ ⟨B, hB, hX, hBX.symm⟩, fun ⟨B, hB, hXE, hXB⟩ ↦ ⟨⟨B, hB, hB.subset_ground, hXB.symm⟩, hXE⟩⟩ @[aesop unsafe 10% (rule_sets := [Matroid])] theorem Coindep.subset_ground (hX : M.Coindep X) : X ⊆ M.E := hX.indep.subset_ground theorem Coindep.exists_isBase_subset_compl (h : M.Coindep X) : ∃ B, M.IsBase B ∧ B ⊆ M.E \ X := (coindep_iff_exists h.subset_ground).1 h theorem Coindep.exists_subset_compl_isBase (h : M.Coindep X) : ∃ B, M.IsBase B ∧ X ⊆ M.E \ B := coindep_iff_subset_compl_isBase.1 h end dual end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Rank/Finite.lean
import Mathlib.Combinatorics.Matroid.Closure /-! # Finite-rank sets `Matroid.IsRkFinite M X` means that every basis of the set `X` in the matroid `M` is finite, or equivalently that the restriction of `M` to `X` is `Matroid.RankFinite`. Sets in a matroid with `IsRkFinite` are the largest class of sets for which one can do nontrivial integer arithmetic involving the rank function. ## Implementation Details Unlike most set predicates on matroids, a set `X` with `M.IsRkFinite X` need not satisfy `X ⊆ M.E`, so may contain junk elements. This seems to be what makes the definition easiest to use. -/ variable {α : Type*} {M : Matroid α} {X Y I : Set α} {e : α} open Set namespace Matroid /-- `Matroid.IsRkFinite M X` means that every basis of `X` in `M` is finite. -/ def IsRkFinite (M : Matroid α) (X : Set α) : Prop := (M ↾ X).RankFinite lemma IsRkFinite.rankFinite (hX : M.IsRkFinite X) : (M ↾ X).RankFinite := hX @[simp] lemma RankFinite.isRkFinite [RankFinite M] (X : Set α) : M.IsRkFinite X := inferInstanceAs (M ↾ X).RankFinite lemma IsBasis'.finite_iff_isRkFinite (hI : M.IsBasis' I X) : I.Finite ↔ M.IsRkFinite X := ⟨fun h ↦ ⟨I, hI, h⟩, fun (_ : (M ↾ X).RankFinite) ↦ hI.isBase_restrict.finite⟩ alias ⟨_, IsBasis'.finite_of_isRkFinite⟩ := IsBasis'.finite_iff_isRkFinite lemma IsBasis.finite_iff_isRkFinite (hI : M.IsBasis I X) : I.Finite ↔ M.IsRkFinite X := hI.isBasis'.finite_iff_isRkFinite alias ⟨_, IsBasis.finite_of_isRkFinite⟩ := IsBasis.finite_iff_isRkFinite lemma IsBasis'.isRkFinite_of_finite (hI : M.IsBasis' I X) (hIfin : I.Finite) : M.IsRkFinite X := ⟨I, hI, hIfin⟩ lemma IsBasis.isRkFinite_of_finite (hI : M.IsBasis I X) (hIfin : I.Finite) : M.IsRkFinite X := ⟨I, hI.isBasis', hIfin⟩ /-- A basis' of an `IsRkFinite` set is finite. -/ lemma IsRkFinite.finite_of_isBasis' (h : M.IsRkFinite X) (hI : M.IsBasis' I X) : I.Finite := have := h.rankFinite (isBase_restrict_iff'.2 hI).finite lemma IsRkFinite.finite_of_isBasis (h : M.IsRkFinite X) (hI : M.IsBasis I X) : I.Finite := h.finite_of_isBasis' hI.isBasis' /-- An `IsRkFinite` set has a finite basis' -/ lemma IsRkFinite.exists_finite_isBasis' (h : M.IsRkFinite X) : ∃ I, M.IsBasis' I X ∧ I.Finite := h.exists_finite_isBase /-- An `IsRkFinite` set has a finset basis' -/ lemma IsRkFinite.exists_finset_isBasis' (h : M.IsRkFinite X) : ∃ (I : Finset α), M.IsBasis' I X := let ⟨I, hI, hIfin⟩ := h.exists_finite_isBasis' ⟨hIfin.toFinset, by simpa⟩ /-- A set satisfies `IsRkFinite` iff it has a finite basis' -/ lemma isRkFinite_iff_exists_isBasis' : M.IsRkFinite X ↔ ∃ I, M.IsBasis' I X ∧ I.Finite := ⟨IsRkFinite.exists_finite_isBasis', fun ⟨_, hIX, hI⟩ ↦ hIX.isRkFinite_of_finite hI⟩ lemma IsRkFinite.subset (h : M.IsRkFinite X) (hXY : Y ⊆ X) : M.IsRkFinite Y := by obtain ⟨I, hI⟩ := M.exists_isBasis' Y obtain ⟨J, hJ, hIJ⟩ := hI.indep.subset_isBasis'_of_subset (hI.subset.trans hXY) exact hI.isRkFinite_of_finite <| (hJ.finite_of_isRkFinite h).subset hIJ @[simp] lemma isRkFinite_inter_ground_iff : M.IsRkFinite (X ∩ M.E) ↔ M.IsRkFinite X := let ⟨_I, hI⟩ := M.exists_isBasis' X ⟨fun h ↦ hI.isRkFinite_of_finite (hI.isBasis_inter_ground.finite_of_isRkFinite h), fun h ↦ h.subset inter_subset_left⟩ lemma IsRkFinite.inter_ground (h : M.IsRkFinite X) : M.IsRkFinite (X ∩ M.E) := isRkFinite_inter_ground_iff.2 h lemma isRkFinite_iff (hX : X ⊆ M.E := by aesop_mat) : M.IsRkFinite X ↔ ∃ I, M.IsBasis I X ∧ I.Finite := by simp_rw [isRkFinite_iff_exists_isBasis', M.isBasis'_iff_isBasis hX] lemma Indep.isRkFinite_iff_finite (hI : M.Indep I) : M.IsRkFinite I ↔ I.Finite := hI.isBasis_self.finite_iff_isRkFinite.symm alias ⟨Indep.finite_of_isRkFinite, _⟩ := Indep.isRkFinite_iff_finite @[simp] lemma isRkFinite_of_finite (M : Matroid α) (hX : X.Finite) : M.IsRkFinite X := let ⟨_, hI⟩ := M.exists_isBasis' X hI.isRkFinite_of_finite (hX.subset hI.subset) lemma Indep.subset_finite_isBasis'_of_subset_of_isRkFinite (hI : M.Indep I) (hIX : I ⊆ X) (hX : M.IsRkFinite X) : ∃ J, M.IsBasis' J X ∧ I ⊆ J ∧ J.Finite := (hI.subset_isBasis'_of_subset hIX).imp fun _ hJ => ⟨hJ.1, hJ.2, hJ.1.finite_of_isRkFinite hX⟩ lemma Indep.subset_finite_isBasis_of_subset_of_isRkFinite (hI : M.Indep I) (hIX : I ⊆ X) (hX : M.IsRkFinite X) (hXE : X ⊆ M.E := by aesop_mat) : ∃ J, M.IsBasis J X ∧ I ⊆ J ∧ J.Finite := (hI.subset_isBasis_of_subset hIX).imp fun _ hJ => ⟨hJ.1, hJ.2, hJ.1.finite_of_isRkFinite hX⟩ lemma isRkFinite_singleton : M.IsRkFinite {e} := by simp lemma IsRkFinite.empty (M : Matroid α) : M.IsRkFinite ∅ := isRkFinite_of_finite M finite_empty lemma IsRkFinite.finite_of_indep_subset (hX : M.IsRkFinite X) (hI : M.Indep I) (hIX : I ⊆ X) : I.Finite := hI.finite_of_isRkFinite <| hX.subset hIX @[simp] lemma isRkFinite_ground_iff_rankFinite : M.IsRkFinite M.E ↔ M.RankFinite := by rw [IsRkFinite, restrict_ground_eq_self] lemma isRkFinite_ground (M : Matroid α) [RankFinite M] : M.IsRkFinite M.E := by rwa [isRkFinite_ground_iff_rankFinite] lemma Indep.finite_of_subset_isRkFinite (hI : M.Indep I) (hIX : I ⊆ X) (hX : M.IsRkFinite X) : I.Finite := hX.finite_of_indep_subset hI hIX lemma IsRkFinite.closure (h : M.IsRkFinite X) : M.IsRkFinite (M.closure X) := let ⟨_, hI⟩ := M.exists_isBasis' X hI.isBasis_closure_right.isRkFinite_of_finite <| hI.finite_of_isRkFinite h @[simp] lemma isRkFinite_closure_iff : M.IsRkFinite (M.closure X) ↔ M.IsRkFinite X := by rw [← isRkFinite_inter_ground_iff (X := X)] exact ⟨fun h ↦ h.subset <| M.inter_ground_subset_closure X, fun h ↦ by simpa using h.closure⟩ lemma IsRkFinite.union (hX : M.IsRkFinite X) (hY : M.IsRkFinite Y) : M.IsRkFinite (X ∪ Y) := by obtain ⟨I, hI, hIfin⟩ := hX.exists_finite_isBasis' obtain ⟨J, hJ, hJfin⟩ := hY.exists_finite_isBasis' rw [← isRkFinite_inter_ground_iff] refine (M.isRkFinite_of_finite (hIfin.union hJfin)).closure.subset ?_ rw [closure_union_congr_left hI.closure_eq_closure, closure_union_congr_right hJ.closure_eq_closure] exact inter_ground_subset_closure M (X ∪ Y) lemma IsRkFinite.isRkFinite_union_iff (hX : M.IsRkFinite X) : M.IsRkFinite (X ∪ Y) ↔ M.IsRkFinite Y := ⟨fun h ↦ h.subset subset_union_right, fun h ↦ hX.union h⟩ lemma IsRkFinite.isRkFinite_diff_iff (hX : M.IsRkFinite X) : M.IsRkFinite (Y \ X) ↔ M.IsRkFinite Y := by rw [← hX.isRkFinite_union_iff, union_diff_self, hX.isRkFinite_union_iff] lemma IsRkFinite.inter_right (hX : M.IsRkFinite X) : M.IsRkFinite (X ∩ Y) := hX.subset inter_subset_left lemma IsRkFinite.inter_left (hX : M.IsRkFinite X) : M.IsRkFinite (Y ∩ X) := hX.subset inter_subset_right lemma IsRkFinite.diff (hX : M.IsRkFinite X) : M.IsRkFinite (X \ Y) := hX.subset diff_subset lemma IsRkFinite.insert (hX : M.IsRkFinite X) (e : α) : M.IsRkFinite (insert e X) := by rw [← union_singleton] exact hX.union M.isRkFinite_singleton @[simp] lemma isRkFinite_insert_iff {e : α} : M.IsRkFinite (insert e X) ↔ M.IsRkFinite X := by rw [← singleton_union, isRkFinite_singleton.isRkFinite_union_iff] @[simp] lemma IsRkFinite.diff_singleton_iff : M.IsRkFinite (X \ {e}) ↔ M.IsRkFinite X := by rw [isRkFinite_singleton.isRkFinite_diff_iff] lemma isRkFinite_set (M : Matroid α) [RankFinite M] (X : Set α) : M.IsRkFinite X := let ⟨_, hI⟩ := M.exists_isBasis' X hI.isRkFinite_of_finite hI.indep.finite /-- A union of finitely many `IsRkFinite` sets is `IsRkFinite`. -/ lemma IsRkFinite.iUnion {ι : Type*} [Finite ι] {Xs : ι → Set α} (h : ∀ i, M.IsRkFinite (Xs i)) : M.IsRkFinite (⋃ i, Xs i) := by choose Is hIs using fun i ↦ M.exists_isBasis' (Xs i) have hfin : (⋃ i, Is i).Finite := finite_iUnion <| fun i ↦ (h i).finite_of_isBasis' (hIs i) refine isRkFinite_inter_ground_iff.1 <| (M.isRkFinite_of_finite hfin).closure.subset ?_ rw [iUnion_inter, iUnion_subset_iff] exact fun i ↦ (hIs i).isBasis_inter_ground.subset_closure.trans <| M.closure_subset_closure <| subset_iUnion .. end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Rank/ENat.lean
import Mathlib.Combinatorics.Matroid.Rank.Finite import Mathlib.Combinatorics.Matroid.Loop import Mathlib.Data.ENat.Lattice import Mathlib.Tactic.TautoSet /-! # `ℕ∞`-valued rank If the 'cardinality' of `s : Set α` is taken to mean the `ℕ∞`-valued term `Set.encard s`, then all bases of any `M : Matroid α` have the same cardinality, and for each `X : Set α` with `X ⊆ M.E`, all `M`-bases for `X` have the same cardinality. The 'rank' of a matroid is the cardinality of all its bases, and the 'rank' of a set `X` in a matroid `M` is the cardinality of each `M`-basis of `X`. This file defines these two concepts as a term `Matroid.eRank M : ℕ∞` and a function `Matroid.eRk M : Set α → ℕ∞` respectively. The rank function `Matroid.eRk` satisfies three properties, often known as (R1), (R2), (R3): * `M.eRk X ≤ Set.encard X`, * `M.eRk X ≤ M.eRk Y` for all `X ⊆ Y`, * `M.eRk X + M.eRk Y ≥ M.eRk (X ∪ Y) + M.eRk (X ∩ Y)` for all `X, Y`. In fact, if `α` is finite, then any function `Set α → ℕ∞` satisfying these properties is the rank function of a `Matroid α`; in other words, properties (R1) - (R3) give an alternative definition of finite matroids, and a finite matroid is determined by its rank function. Because of this, and the convenient quantitative language of these axioms, the rank function is often the preferred perspective on matroids in the literature. (The above doesn't work as well for infinite matroids, which is why mathlib defines matroids using bases/independence. ) ## Main Declarations * `Matroid.eRank M` is the `ℕ∞`-valued cardinality of each base of `M`. * `Matroid.eRk M X` is the `ℕ∞`-valued cardinality of each `M`-basis of `X`. * `Matroid.eRk_inter_add_eRk_union_le` : the function `M.eRk` is submodular. * `Matroid.dual_eRk_add_eRank` : a subtraction-free formula for the dual rank of a set. ## Notes It is natural to ask if equicardinality of bases holds if 'cardinality' refers to a term in `Cardinal` instead of `ℕ∞`, but the answer is that it doesn't. The cardinal-valued rank functions `Matroid.cRank` and `Matroid.cRk` are defined in `Mathlib/Data/Matroid/Rank/Cardinal.lean`, but have less desirable properties in general. See the module docstring of that file for a discussion. ## Implementation Details It would be equivalent to define `Matroid.eRank (M : Matroid α) := (Matroid.cRank M).toENat` and similar for `Matroid.eRk`, and some of the API for `cRank`/`cRk` would carry over in a way that shortens certain proofs in this file (though not substantially). Although this file transitively imports `Cardinal` via `Set.encard`, there are plans to refactor the latter to be independent of the former, which would carry over to the current version of this file. -/ open Set ENat namespace Matroid variable {α : Type*} {M : Matroid α} {I B X Y : Set α} {n : ℕ∞} {e f : α} section Basic /-- The rank `Matroid.eRank M` of `M` is the `ℕ∞`-valued cardinality of each base of `M`. (See `Matroid.cRank` for a worse-behaved cardinal-valued version) -/ noncomputable def eRank (M : Matroid α) : ℕ∞ := ⨆ B : {B // M.IsBase B}, B.1.encard /-- The rank `Matroid.eRk M X` of a set `X` is the `ℕ∞`-valued cardinality of each basis of `X`. (See `Matroid.cRk` for a worse-behaved cardinal-valued version) -/ noncomputable def eRk (M : Matroid α) (X : Set α) : ℕ∞ := (M ↾ X).eRank lemma eRank_def (M : Matroid α) : M.eRank = M.eRk M.E := by rw [eRk, restrict_ground_eq_self] @[simp] lemma eRk_ground (M : Matroid α) : M.eRk M.E = M.eRank := M.eRank_def.symm @[simp] lemma eRank_restrict (M : Matroid α) (X : Set α) : (M ↾ X).eRank = M.eRk X := rfl lemma IsBase.encard_eq_eRank (hB : M.IsBase B) : B.encard = M.eRank := by simp [eRank, show ∀ B' : {B // M.IsBase B}, B'.1.encard = B.encard from fun B' ↦ B'.2.encard_eq_encard_of_isBase hB] lemma IsBasis'.encard_eq_eRk (hI : M.IsBasis' I X) : I.encard = M.eRk X := hI.isBase_restrict.encard_eq_eRank lemma IsBasis.encard_eq_eRk (hI : M.IsBasis I X) : I.encard = M.eRk X := hI.isBasis'.encard_eq_eRk lemma eq_eRk_iff (hX : X ⊆ M.E := by aesop_mat) : M.eRk X = n ↔ ∃ I, M.IsBasis I X ∧ I.encard = n := ⟨fun h ↦ (M.exists_isBasis X).elim (fun I hI ↦ ⟨I, hI, by rw [hI.encard_eq_eRk, ← h]⟩), fun ⟨I, hI, hIc⟩ ↦ by rw [← hI.encard_eq_eRk, hIc]⟩ lemma Indep.eRk_eq_encard (hI : M.Indep I) : M.eRk I = I.encard := (eq_eRk_iff hI.subset_ground).mpr ⟨I, hI.isBasis_self, rfl⟩ lemma IsBasis'.eRk_eq_eRk (hIX : M.IsBasis' I X) : M.eRk I = M.eRk X := by rw [← hIX.encard_eq_eRk, hIX.indep.eRk_eq_encard] lemma IsBasis.eRk_eq_eRk (hIX : M.IsBasis I X) : M.eRk I = M.eRk X := by rw [← hIX.encard_eq_eRk, hIX.indep.eRk_eq_encard] lemma IsBasis'.eRk_eq_encard (hIX : M.IsBasis' I X) : M.eRk X = I.encard := by rw [← hIX.eRk_eq_eRk, hIX.indep.eRk_eq_encard] lemma IsBasis.eRk_eq_encard (hIX : M.IsBasis I X) : M.eRk X = I.encard := by rw [← hIX.eRk_eq_eRk, hIX.indep.eRk_eq_encard] lemma IsBase.eRk_eq_eRank (hB : M.IsBase B) : M.eRk B = M.eRank := by rw [hB.indep.eRk_eq_encard, eRank_def, hB.isBasis_ground.encard_eq_eRk] @[simp] lemma eRk_inter_ground (M : Matroid α) (X : Set α) : M.eRk (X ∩ M.E) = M.eRk X := by obtain ⟨I, hI⟩ := M.exists_isBasis' X rw [← hI.eRk_eq_eRk, hI.isBasis_inter_ground.eRk_eq_eRk] @[simp] lemma eRk_ground_inter (M : Matroid α) (X : Set α) : M.eRk (M.E ∩ X) = M.eRk X := by rw [inter_comm, eRk_inter_ground] @[simp] lemma eRk_union_ground (M : Matroid α) (X : Set α) : M.eRk (X ∪ M.E) = M.eRank := by rw [← eRk_inter_ground, inter_eq_self_of_subset_right subset_union_right, eRank_def] @[simp] lemma eRk_ground_union (M : Matroid α) (X : Set α) : M.eRk (M.E ∪ X) = M.eRank := by rw [union_comm, eRk_union_ground] lemma eRk_insert_of_notMem_ground (X : Set α) (he : e ∉ M.E) : M.eRk (insert e X) = M.eRk X := by rw [← eRk_inter_ground, insert_inter_of_notMem he, eRk_inter_ground] @[deprecated (since := "2025-05-23")] alias eRk_insert_of_not_mem_ground := eRk_insert_of_notMem_ground lemma eRk_eq_eRank (hX : M.E ⊆ X) : M.eRk X = M.eRank := by rw [← eRk_inter_ground, inter_eq_self_of_subset_right hX, eRank_def] lemma eRk_compl_union_of_disjoint (M : Matroid α) (hXY : Disjoint X Y) : M.eRk (M.E \ X ∪ Y) = M.eRk (M.E \ X) := by rw [← eRk_inter_ground, union_inter_distrib_right, inter_eq_self_of_subset_left diff_subset, union_eq_self_of_subset_right (subset_diff.2 ⟨inter_subset_right, hXY.symm.mono_left inter_subset_left⟩)] lemma one_le_eRank (M : Matroid α) [RankPos M] : 1 ≤ M.eRank := by obtain ⟨B, hB⟩ := M.exists_isBase rw [← hB.encard_eq_eRank, one_le_encard_iff_nonempty] exact hB.nonempty @[simp] lemma eRk_univ_eq (M : Matroid α) : M.eRk univ = M.eRank := by rw [← eRk_inter_ground, univ_inter, eRank_def] @[simp] lemma eRk_empty (M : Matroid α) : M.eRk ∅ = 0 := by rw [← M.empty_indep.isBasis_self.encard_eq_eRk, encard_empty] @[simp] lemma eRk_closure_eq (M : Matroid α) (X : Set α) : M.eRk (M.closure X) = M.eRk X := by obtain ⟨I, hI⟩ := M.exists_isBasis' X rw [← hI.closure_eq_closure, ← hI.indep.isBasis_closure.encard_eq_eRk, hI.encard_eq_eRk] @[simp] lemma eRk_union_closure_right_eq (M : Matroid α) (X Y : Set α) : M.eRk (X ∪ M.closure Y) = M.eRk (X ∪ Y) := by rw [← eRk_closure_eq, closure_union_closure_right_eq, eRk_closure_eq] @[simp] lemma eRk_union_closure_left_eq (M : Matroid α) (X Y : Set α) : M.eRk (M.closure X ∪ Y) = M.eRk (X ∪ Y) := by rw [← eRk_closure_eq, closure_union_closure_left_eq, eRk_closure_eq] @[simp] lemma eRk_insert_closure_eq (M : Matroid α) (e : α) (X : Set α) : M.eRk (insert e (M.closure X)) = M.eRk (insert e X) := by rw [← union_singleton, eRk_union_closure_left_eq, union_singleton] /-- A version of `Matroid.restrict_eRk_eq` with no `X ⊆ R` hypothesis and thus a less simple RHS. -/ @[simp] lemma restrict_eRk_eq' (M : Matroid α) (R X : Set α) : (M ↾ R).eRk X = M.eRk (X ∩ R) := by obtain ⟨I, hI⟩ := (M ↾ R).exists_isBasis' X rw [hI.eRk_eq_encard] rw [isBasis'_iff_isBasis_inter_ground, isBasis_restrict_iff', restrict_ground_eq] at hI rw [← eRk_inter_ground, ← hI.1.eRk_eq_encard] lemma restrict_eRk_eq (M : Matroid α) {R : Set α} (h : X ⊆ R) : (M ↾ R).eRk X = M.eRk X := by rw [restrict_eRk_eq', inter_eq_self_of_subset_left h] lemma IsBasis'.eRk_eq_eRk_union (hIX : M.IsBasis' I X) (Y : Set α) : M.eRk (I ∪ Y) = M.eRk (X ∪ Y) := by rw [← eRk_union_closure_left_eq, hIX.closure_eq_closure, eRk_union_closure_left_eq] lemma IsBasis'.eRk_eq_eRk_insert (hIX : M.IsBasis' I X) (e : α) : M.eRk (insert e I) = M.eRk (insert e X) := by rw [← union_singleton, hIX.eRk_eq_eRk_union, union_singleton] lemma IsBasis.eRk_eq_eRk_union (hIX : M.IsBasis I X) (Y : Set α) : M.eRk (I ∪ Y) = M.eRk (X ∪ Y) := hIX.isBasis'.eRk_eq_eRk_union Y lemma IsBasis.eRk_eq_eRk_insert (hIX : M.IsBasis I X) (e : α) : M.eRk (insert e I) = M.eRk (insert e X) := by rw [← union_singleton, hIX.eRk_eq_eRk_union, union_singleton] lemma eRk_le_encard (M : Matroid α) (X : Set α) : M.eRk X ≤ X.encard := by obtain ⟨I, hI⟩ := M.exists_isBasis' X rw [hI.eRk_eq_encard] exact encard_mono hI.subset lemma eRank_le_encard_ground (M : Matroid α) : M.eRank ≤ M.E.encard := M.eRank_def.trans_le <| M.eRk_le_encard M.E lemma eRk_mono (M : Matroid α) : Monotone M.eRk := by rintro X Y (hXY : X ⊆ Y) obtain ⟨I, hI⟩ := M.exists_isBasis' X obtain ⟨J, hJ, hIJ⟩ := hI.indep.subset_isBasis'_of_subset (hI.subset.trans hXY) rw [hI.eRk_eq_encard, hJ.eRk_eq_encard] exact encard_mono hIJ lemma eRk_le_eRank (M : Matroid α) (X : Set α) : M.eRk X ≤ M.eRank := by rw [eRank_def, ← eRk_inter_ground]; exact M.eRk_mono inter_subset_right lemma eRk_eq_eRk_of_subset_of_le (hXY : X ⊆ Y) (hYX : M.eRk Y ≤ M.eRk X) : M.eRk X = M.eRk Y := (M.eRk_mono hXY).antisymm hYX lemma le_eRk_iff : n ≤ M.eRk X ↔ ∃ I, I ⊆ X ∧ M.Indep I ∧ I.encard = n := by refine ⟨fun h ↦ ?_, fun ⟨I, hIX, hI, hIc⟩ ↦ ?_⟩ · obtain ⟨J, hJ⟩ := M.exists_isBasis' X rw [← hJ.encard_eq_eRk] at h obtain ⟨I, hIJ, rfl⟩ := exists_subset_encard_eq h exact ⟨_, hIJ.trans hJ.subset, hJ.indep.subset hIJ, rfl⟩ rw [← hIc, ← hI.eRk_eq_encard] exact M.eRk_mono hIX lemma eRk_le_iff : M.eRk X ≤ n ↔ ∀ ⦃I⦄, I ⊆ X → M.Indep I → I.encard ≤ n := by refine ⟨fun h I hIX hI ↦ (hI.eRk_eq_encard.symm.trans_le ((M.eRk_mono hIX).trans h)), fun h ↦ ?_⟩ obtain ⟨I, hI⟩ := M.exists_isBasis' X rw [← hI.encard_eq_eRk] exact h hI.subset hI.indep lemma Indep.encard_le_eRk_of_subset (hI : M.Indep I) (hIX : I ⊆ X) : I.encard ≤ M.eRk X := hI.eRk_eq_encard ▸ M.eRk_mono hIX lemma Indep.encard_le_eRank (hI : M.Indep I) : I.encard ≤ M.eRank := by rw [← hI.eRk_eq_encard, eRank_def] exact M.eRk_mono hI.subset_ground /-- A version of `erk_eq_zero_iff'` with no supportedness hypothesis. -/ lemma eRk_eq_zero_iff' : M.eRk X = 0 ↔ X ∩ M.E ⊆ M.loops := by obtain ⟨I, hI⟩ := M.exists_isBasis (X ∩ M.E) rw [← eRk_inter_ground, ← hI.encard_eq_eRk, encard_eq_zero] refine ⟨fun h ↦ by simpa [h] using hI, fun h ↦ eq_empty_iff_forall_notMem.2 fun e heI ↦ ?_⟩ exact (hI.indep.isNonloop_of_mem heI).not_isLoop (h (hI.subset heI)) @[deprecated (since := "2025-05-14")] alias erk_eq_zero_iff' := eRk_eq_zero_iff' @[simp] lemma eRk_eq_zero_iff (hX : X ⊆ M.E := by aesop_mat) : M.eRk X = 0 ↔ X ⊆ M.loops := by rw [eRk_eq_zero_iff', inter_eq_self_of_subset_left hX] @[deprecated (since := "2025-05-14")] alias erk_eq_zero_iff := eRk_eq_zero_iff @[simp] lemma eRk_loops : M.eRk M.loops = 0 := by simp [eRk_eq_zero_iff'] /-! ### Submodularity -/ /-- The `ℕ∞`-valued rank function is submodular. -/ lemma eRk_inter_add_eRk_union_le (M : Matroid α) (X Y : Set α) : M.eRk (X ∩ Y) + M.eRk (X ∪ Y) ≤ M.eRk X + M.eRk Y := by obtain ⟨Ii, hIi⟩ := M.exists_isBasis' (X ∩ Y) obtain ⟨IX, hIX, hIX'⟩ := hIi.indep.subset_isBasis'_of_subset (hIi.subset.trans inter_subset_left) obtain ⟨IY, hIY, hIY'⟩ := hIi.indep.subset_isBasis'_of_subset (hIi.subset.trans inter_subset_right) rw [← hIX.eRk_eq_eRk_union, union_comm, ← hIY.eRk_eq_eRk_union, ← hIi.encard_eq_eRk, ← hIX.encard_eq_eRk, ← hIY.encard_eq_eRk, union_comm, ← encard_union_add_encard_inter, add_comm] exact add_le_add (eRk_le_encard _ _) (encard_mono (subset_inter hIX' hIY')) alias eRk_submod := eRk_inter_add_eRk_union_le /-- A version of submodularity applied to the insertion of some `e` into two sets. -/ lemma eRk_insert_inter_add_eRk_insert_union_le (M : Matroid α) (X Y : Set α) : M.eRk (insert e (X ∩ Y)) + M.eRk (insert e (X ∪ Y)) ≤ M.eRk (insert e X) + M.eRk (insert e Y) := by rw [insert_inter_distrib, insert_union_distrib] apply M.eRk_submod /-- A version of submodularity applied to the complements of two sets. -/ lemma eRk_compl_union_add_eRk_compl_inter_le (M : Matroid α) (X Y : Set α) : M.eRk (M.E \ (X ∪ Y)) + M.eRk (M.E \ (X ∩ Y)) ≤ M.eRk (M.E \ X) + M.eRk (M.E \ Y) := by rw [← diff_inter_diff, diff_inter] apply M.eRk_submod /-- A version of submodularity applied to the complements of two insertions. -/ lemma eRk_compl_insert_union_add_eRk_compl_insert_inter_le (M : Matroid α) (X Y : Set α) : M.eRk (M.E \ insert e (X ∪ Y)) + M.eRk (M.E \ insert e (X ∩ Y)) ≤ M.eRk (M.E \ insert e X) + M.eRk (M.E \ insert e Y) := by rw [insert_union_distrib, insert_inter_distrib] exact M.eRk_compl_union_add_eRk_compl_inter_le (insert e X) (insert e Y) lemma eRk_union_le_eRk_add_eRk (M : Matroid α) (X Y : Set α) : M.eRk (X ∪ Y) ≤ M.eRk X + M.eRk Y := le_add_self.trans (M.eRk_submod X Y) lemma eRk_eq_eRk_union_eRk_le_zero (X : Set α) (hY : M.eRk Y ≤ 0) : M.eRk (X ∪ Y) = M.eRk X := (((M.eRk_union_le_eRk_add_eRk X Y).trans (by gcongr)).trans_eq (add_zero _)).antisymm (M.eRk_mono subset_union_left) lemma eRk_eq_eRk_diff_eRk_le_zero (X : Set α) (hY : M.eRk Y ≤ 0) : M.eRk (X \ Y) = M.eRk X := by rw [← eRk_eq_eRk_union_eRk_le_zero (X \ Y) hY, diff_union_self, eRk_eq_eRk_union_eRk_le_zero _ hY] lemma eRk_le_eRk_inter_add_eRk_diff (M : Matroid α) (X Y : Set α) : M.eRk X ≤ M.eRk (X ∩ Y) + M.eRk (X \ Y) := by nth_rw 1 [← inter_union_diff X Y]; apply eRk_union_le_eRk_add_eRk lemma eRk_le_eRk_add_eRk_diff (M : Matroid α) (h : Y ⊆ X) : M.eRk X ≤ M.eRk Y + M.eRk (X \ Y) := by nth_rw 1 [← union_diff_cancel h]; apply eRk_union_le_eRk_add_eRk lemma eRk_union_le_encard_add_eRk (M : Matroid α) (X Y : Set α) : M.eRk (X ∪ Y) ≤ X.encard + M.eRk Y := (M.eRk_union_le_eRk_add_eRk X Y).trans <| by grw [M.eRk_le_encard] lemma eRk_union_le_eRk_add_encard (M : Matroid α) (X Y : Set α) : M.eRk (X ∪ Y) ≤ M.eRk X + Y.encard := (M.eRk_union_le_eRk_add_eRk X Y).trans <| by grw [← M.eRk_le_encard] lemma eRank_le_encard_add_eRk_compl (M : Matroid α) (X : Set α) : M.eRank ≤ X.encard + M.eRk (M.E \ X) := le_trans (by rw [← eRk_inter_ground, eRank_def, union_diff_self, union_inter_cancel_right]) (M.eRk_union_le_encard_add_eRk X (M.E \ X)) end Basic /-! ### Finiteness -/ lemma eRank_ne_top_iff (M : Matroid α) : M.eRank ≠ ⊤ ↔ M.RankFinite := by obtain ⟨B, hB⟩ := M.exists_isBase rw [← hB.encard_eq_eRank, encard_ne_top_iff] exact ⟨fun h ↦ hB.rankFinite_of_finite h, fun h ↦ hB.finite⟩ @[simp] lemma eRank_eq_top_iff (M : Matroid α) : M.eRank = ⊤ ↔ M.RankInfinite := by rw [← not_rankFinite_iff, ← eRank_ne_top_iff, not_not] @[simp] lemma eRank_lt_top_iff : M.eRank < ⊤ ↔ M.RankFinite := by simp [lt_top_iff_ne_top] @[simp] lemma eRank_eq_top [RankInfinite M] : M.eRank = ⊤ := (eRank_eq_top_iff _).2 <| by assumption @[simp] lemma eRk_eq_top_iff : M.eRk X = ⊤ ↔ ¬ M.IsRkFinite X := by obtain ⟨I, hI⟩ := M.exists_isBasis' X rw [hI.eRk_eq_encard, encard_eq_top_iff, ← hI.finite_iff_isRkFinite, Set.Infinite] lemma eRk_ne_top_iff : M.eRk X ≠ ⊤ ↔ M.IsRkFinite X := by simp @[simp] lemma eRk_lt_top_iff : M.eRk X < ⊤ ↔ M.IsRkFinite X := by rw [lt_top_iff_ne_top, eRk_ne_top_iff] lemma IsRkFinite.eRk_lt_top (h : M.IsRkFinite X) : M.eRk X < ⊤ := eRk_lt_top_iff.2 h /-- If `X` is a finite-rank set, and `I` is a subset of `X` of cardinality no larger than the rank of `X` that spans `X`, then `I` is a basis for `X`. -/ lemma IsRkFinite.isBasis_of_subset_closure_of_subset_of_encard_le (hX : M.IsRkFinite X) (hXI : X ⊆ M.closure I) (hIX : I ⊆ X) (hI : I.encard ≤ M.eRk X) : M.IsBasis I X := by obtain ⟨J, hJ⟩ := M.exists_isBasis (I ∩ M.E) have hIJ := hJ.subset.trans inter_subset_left rw [← closure_inter_ground] at hXI replace hXI := hXI.trans <| M.closure_subset_closure_of_subset_closure hJ.subset_closure have hJX := hJ.indep.isBasis_of_subset_of_subset_closure (hIJ.trans hIX) hXI rw [← hJX.encard_eq_eRk] at hI rwa [← Finite.eq_of_subset_of_encard_le (hX.finite_of_isBasis hJX) hIJ hI] /-- If `X` is a finite-rank set, and `Y` is a superset of `X` of rank no larger than that of `X`, then `X` and `Y` have the same closure. -/ lemma IsRkFinite.closure_eq_closure_of_subset_of_eRk_ge_eRk (hX : M.IsRkFinite X) (hXY : X ⊆ Y) (hr : M.eRk Y ≤ M.eRk X) : M.closure X = M.closure Y := by obtain ⟨I, hI⟩ := M.exists_isBasis' X obtain ⟨J, hJ, hIJ⟩ := hI.indep.subset_isBasis'_of_subset (hI.subset.trans hXY) rw [hI.eRk_eq_encard, hJ.eRk_eq_encard] at hr rw [← closure_inter_ground, ← M.closure_inter_ground Y, ← hI.isBasis_inter_ground.closure_eq_closure, ← hJ.isBasis_inter_ground.closure_eq_closure, Finite.eq_of_subset_of_encard_le (hI.indep.finite_of_subset_isRkFinite hI.subset hX) hIJ hr] /-! ### Insertion -/ lemma eRk_insert_le_add_one (M : Matroid α) (e : α) (X : Set α) : M.eRk (insert e X) ≤ M.eRk X + 1 := union_singleton ▸ (M.eRk_union_le_eRk_add_eRk _ _).trans <| by gcongr; simpa using M.eRk_le_encard {e} lemma eRk_insert_eq_add_one (he : e ∈ M.E \ M.closure X) : M.eRk (insert e X) = M.eRk X + 1 := by obtain ⟨I, hI⟩ := M.exists_isBasis' X rw [← hI.closure_eq_closure, mem_diff, hI.indep.mem_closure_iff', not_and] at he rw [← eRk_closure_eq, ← closure_insert_congr_right hI.closure_eq_closure, hI.eRk_eq_encard, eRk_closure_eq, Indep.eRk_eq_encard (by tauto), encard_insert_of_notMem (by tauto)] lemma exists_eRk_insert_eq_add_one_of_lt (h : M.eRk X < M.eRk Y) : ∃ y ∈ Y \ X, M.eRk (insert y X) = M.eRk X + 1 := by have hz : ¬ Y ∩ M.E ⊆ M.closure X := by contrapose! h simpa using M.eRk_mono h obtain ⟨e, ⟨heZ, heE⟩, heX⟩ := not_subset.1 hz refine ⟨e, ⟨heZ, fun heX' ↦ heX (mem_closure_of_mem' _ heX')⟩, eRk_insert_eq_add_one ⟨heE, heX⟩⟩ lemma IsRkFinite.closure_eq_closure_of_subset_of_forall_insert (hX : M.IsRkFinite X) (hXY : X ⊆ Y) (hY : ∀ e ∈ Y \ X, M.eRk (Insert.insert e X) ≤ M.eRk X) : M.closure X = M.closure Y := by refine hX.closure_eq_closure_of_subset_of_eRk_ge_eRk hXY <| not_lt.1 fun hlt ↦ ?_ obtain ⟨z, hz, hr⟩ := exists_eRk_insert_eq_add_one_of_lt hlt simpa [hr, ENat.add_one_le_iff hX.eRk_lt_top.ne] using hY z hz lemma eRk_eq_of_eRk_insert_le_forall (hXY : X ⊆ Y) (hY : ∀ e ∈ Y \ X, M.eRk (insert e X) ≤ M.eRk X) : M.eRk X = M.eRk Y := by by_cases hX : M.IsRkFinite X · rw [← eRk_closure_eq, hX.closure_eq_closure_of_subset_of_forall_insert hXY hY, eRk_closure_eq] rw [eRk_eq_top_iff.2 hX, eRk_eq_top_iff.2 (mt (fun h ↦ h.subset hXY) hX)] /-! ### Independence -/ lemma indep_iff_eRk_eq_encard_of_finite (hI : I.Finite) : M.Indep I ↔ M.eRk I = I.encard := by refine ⟨fun h ↦ by rw [h.eRk_eq_encard], fun h ↦ ?_⟩ obtain ⟨J, hJ⟩ := M.exists_isBasis' I rw [← hI.eq_of_subset_of_encard_le' hJ.subset] · exact hJ.indep rw [← h, ← hJ.eRk_eq_encard] /-- In a matroid known to have finite rank, `Matroid.indep_iff_eRk_eq_encard_of_finite` is true without the finiteness assumption. -/ lemma indep_iff_eRk_eq_encard [M.RankFinite] : M.Indep I ↔ M.eRk I = I.encard := by refine ⟨Indep.eRk_eq_encard, fun h ↦ ?_⟩ obtain hfin | hinf := I.finite_or_infinite · rwa [indep_iff_eRk_eq_encard_of_finite hfin] rw [hinf.encard_eq] at h exact False.elim <| (M.isRkFinite_set I).eRk_lt_top.ne h lemma IsRkFinite.indep_of_encard_le_eRk (hX : M.IsRkFinite I) (h : encard I ≤ M.eRk I) : M.Indep I := by rw [indep_iff_eRk_eq_encard_of_finite _] · exact (M.eRk_le_encard I).antisymm h simpa using h.trans_lt hX.eRk_lt_top lemma eRk_lt_encard_of_dep_of_finite (h : X.Finite) (hX : M.Dep X) : M.eRk X < X.encard := lt_of_le_of_ne (M.eRk_le_encard X) fun h' ↦ ((indep_iff_eRk_eq_encard_of_finite h).mpr h').not_dep hX lemma eRk_lt_encard_iff_dep_of_finite (hX : X.Finite) (hXE : X ⊆ M.E := by aesop_mat) : M.eRk X < X.encard ↔ M.Dep X := by refine ⟨fun h ↦ ?_, fun h ↦ eRk_lt_encard_of_dep_of_finite hX h⟩ rw [← not_indep_iff, indep_iff_eRk_eq_encard_of_finite hX] exact h.ne lemma Dep.eRk_lt_encard [M.RankFinite] (hX : M.Dep X) : M.eRk X < X.encard := by refine (M.eRk_le_encard X).lt_of_ne ?_ rw [ne_eq, ← indep_iff_eRk_eq_encard] exact hX.not_indep lemma eRk_lt_encard_iff_dep [M.RankFinite] (hXE : X ⊆ M.E := by aesop_mat) : M.eRk X < X.encard ↔ M.Dep X := ⟨fun h ↦ (not_indep_iff).1 fun hi ↦ h.ne hi.eRk_eq_encard, Dep.eRk_lt_encard⟩ lemma Indep.exists_insert_of_encard_lt {I J : Set α} (hI : M.Indep I) (hJ : M.Indep J) (hcard : I.encard < J.encard) : ∃ e ∈ J \ I, M.Indep (insert e I) := augment hI hJ hcard lemma isBasis'_iff_indep_encard_eq_of_finite (hIfin : I.Finite) : M.IsBasis' I X ↔ I ⊆ X ∧ M.Indep I ∧ I.encard = M.eRk X := by refine ⟨fun h ↦ ⟨h.subset,h.indep, h.eRk_eq_encard.symm⟩, fun ⟨hIX, hI, hcard⟩ ↦ ?_⟩ obtain ⟨J, hJ, hIJ⟩ := hI.subset_isBasis'_of_subset hIX rwa [hIfin.eq_of_subset_of_encard_le hIJ (hJ.encard_eq_eRk.trans hcard.symm).le] lemma isBasis_iff_indep_encard_eq_of_finite (hIfin : I.Finite) (hX : X ⊆ M.E := by aesop_mat) : M.IsBasis I X ↔ I ⊆ X ∧ M.Indep I ∧ I.encard = M.eRk X := by rw [← isBasis'_iff_isBasis, isBasis'_iff_indep_encard_eq_of_finite hIfin] /-- If `I` is a finite independent subset of `X` for which `M.eRk X ≤ M.eRk I`, then `I` is a `Basis'` for `X`. -/ lemma Indep.isBasis'_of_eRk_ge (hI : M.Indep I) (hIfin : I.Finite) (hIX : I ⊆ X) (h : M.eRk X ≤ M.eRk I) : M.IsBasis' I X := (isBasis'_iff_indep_encard_eq_of_finite hIfin).2 ⟨hIX, hI, by rw [h.antisymm (M.eRk_mono hIX), hI.eRk_eq_encard]⟩ lemma Indep.isBasis_of_eRk_ge (hI : M.Indep I) (hIfin : I.Finite) (hIX : I ⊆ X) (h : M.eRk X ≤ M.eRk I) (hX : X ⊆ M.E := by aesop_mat) : M.IsBasis I X := (hI.isBasis'_of_eRk_ge hIfin hIX h).isBasis lemma Indep.isBase_of_eRk_ge (hI : M.Indep I) (hIfin : I.Finite) (h : M.eRank ≤ M.eRk I) : M.IsBase I := by simpa using hI.isBasis_of_eRk_ge hIfin hI.subset_ground (M.eRk_ground.trans_le h) lemma IsCircuit.eRk_add_one_eq {C : Set α} (hC : M.IsCircuit C) : M.eRk C + 1 = C.encard := by obtain ⟨I, hI⟩ := M.exists_isBasis C obtain ⟨e, ⟨heC, heI⟩, rfl⟩ := hC.isBasis_iff_insert_eq.1 hI rw [hI.eRk_eq_encard, encard_insert_of_notMem heI] /-! ### Singletons -/ lemma IsLoop.eRk_eq (he : M.IsLoop e) : M.eRk {e} = 0 := by rw [← eRk_closure_eq, he.closure, loops, eRk_closure_eq, eRk_empty] lemma IsNonloop.eRk_eq (he : M.IsNonloop e) : M.eRk {e} = 1 := by rw [← he.indep.isBasis_self.encard_eq_eRk, encard_singleton] lemma eRk_singleton_eq [Loopless M] (he : e ∈ M.E := by aesop_mat) : M.eRk {e} = 1 := (M.isNonloop_of_loopless he).eRk_eq @[simp] lemma eRk_singleton_le (M : Matroid α) (e : α) : M.eRk {e} ≤ 1 := (M.eRk_le_encard {e}).trans_eq <| encard_singleton e @[simp] lemma eRk_singleton_eq_one_iff {e : α} : M.eRk {e} = 1 ↔ M.IsNonloop e := by refine ⟨fun h ↦ ?_, fun h ↦ h.eRk_eq⟩ rwa [← indep_singleton, indep_iff_eRk_eq_encard_of_finite (by simp), encard_singleton] lemma eRk_eq_one_iff (hX : X ⊆ M.E := by aesop_mat) : M.eRk X = 1 ↔ ∃ e ∈ X, M.IsNonloop e ∧ X ⊆ M.closure {e} := by refine ⟨?_, fun ⟨e, heX, he, hXe⟩ ↦ ?_⟩ · obtain ⟨I, hI⟩ := M.exists_isBasis X rw [hI.eRk_eq_encard, encard_eq_one] rintro ⟨e, rfl⟩ exact ⟨e, singleton_subset_iff.1 hI.subset, indep_singleton.1 hI.indep, hI.subset_closure⟩ rw [← he.eRk_eq] exact ((M.eRk_mono hXe).trans (M.eRk_closure_eq _).le).antisymm (M.eRk_mono (singleton_subset_iff.2 heX)) lemma eRk_le_one_iff [M.Nonempty] (hX : X ⊆ M.E := by aesop_mat) : M.eRk X ≤ 1 ↔ ∃ e ∈ M.E, X ⊆ M.closure {e} := by refine ⟨fun h ↦ ?_, fun ⟨e, _, he⟩ ↦ ?_⟩ · obtain ⟨I, hI⟩ := M.exists_isBasis X rw [hI.eRk_eq_encard, encard_le_one_iff_eq] at h obtain (rfl | ⟨e, rfl⟩) := h · obtain ⟨e, he⟩ := M.ground_nonempty exact ⟨e, he, hI.subset_closure.trans ((M.closure_subset_closure (empty_subset _)))⟩ exact ⟨e, hI.indep.subset_ground rfl, hI.subset_closure⟩ refine (M.eRk_mono he).trans ?_ rw [eRk_closure_eq, ← encard_singleton e] exact M.eRk_le_encard {e} /-! ### Spanning Sets -/ lemma Spanning.eRk_eq (hX : M.Spanning X) : M.eRk X = M.eRank := by obtain ⟨B, hB⟩ := M.exists_isBasis X exact (M.eRk_le_eRank X).antisymm <| by rw [← hB.encard_eq_eRk, ← (hB.isBase_of_spanning hX).encard_eq_eRank] lemma spanning_iff_eRk_le' [RankFinite M] : M.Spanning X ↔ M.eRank ≤ M.eRk X ∧ X ⊆ M.E := by refine ⟨fun h ↦ ⟨h.eRk_eq.symm.le, h.subset_ground⟩, fun ⟨h, hX⟩ ↦ ?_⟩ obtain ⟨I, hI⟩ := M.exists_isBasis X exact (hI.indep.isBase_of_eRk_ge hI.indep.finite (h.trans hI.eRk_eq_eRk.symm.le)).spanning_of_superset hI.subset lemma spanning_iff_eRk_le [RankFinite M] (hX : X ⊆ M.E := by aesop_mat) : M.Spanning X ↔ M.eRank ≤ M.eRk X := by rw [spanning_iff_eRk_le', and_iff_left hX] lemma Spanning.eRank_restrict (hX : M.Spanning X) : (M ↾ X).eRank = M.eRank := by rw [eRank_def, restrict_ground_eq, restrict_eRk_eq _ rfl.subset, hX.eRk_eq] /-! ### Constructions -/ @[simp] lemma eRank_map {β : Type*} {f : α → β} (M : Matroid α) (hf : InjOn f M.E) : (M.map f hf).eRank = M.eRank := by obtain ⟨B, hB⟩ := M.exists_isBase rw [← (hB.map hf).encard_eq_eRank, ← hB.encard_eq_eRank, (hf.mono hB.subset_ground).encard_image] @[simp] lemma eRk_map {β : Type*} {f : α → β} (M : Matroid α) (hf : InjOn f M.E) (hX : X ⊆ M.E := by aesop_mat) : (M.map f hf).eRk (f '' X) = M.eRk X := by obtain ⟨I, hI⟩ := M.exists_isBasis X rw [hI.eRk_eq_encard, (hI.map hf).eRk_eq_encard, (hf.mono hI.indep.subset_ground).encard_image] @[simp] lemma eRk_comap {β : Type*} {f : α → β} (M : Matroid β) (X : Set α) : (M.comap f).eRk X = M.eRk (f '' X) := by obtain ⟨I, hI⟩ := (M.comap f).exists_isBasis' X obtain ⟨hI', hinj, -⟩ := comap_isBasis'_iff.1 hI rw [← hI.encard_eq_eRk, ← hI'.encard_eq_eRk, hinj.encard_image] @[simp] lemma eRk_loopyOn (X Y : Set α) : (loopyOn Y).eRk X = 0 := by obtain ⟨I, hI⟩ := (loopyOn Y).exists_isBasis' X rw [hI.eRk_eq_encard, loopyOn_indep_iff.1 hI.indep, encard_empty] @[simp] lemma eRank_loopyOn (X : Set α) : (loopyOn X).eRank = 0 := by rw [eRank_def, eRk_loopyOn] lemma eRank_eq_zero_iff : M.eRank = 0 ↔ M = loopyOn M.E := by refine ⟨fun h ↦ closure_empty_eq_ground_iff.1 ?_, fun h ↦ by rw [h, eRank_loopyOn]⟩ obtain ⟨B, hB⟩ := M.exists_isBase rw [← hB.encard_eq_eRank, encard_eq_zero] at h rw [← h, hB.closure_eq] lemma exists_of_eRank_eq_zero (h : M.eRank = 0) : ∃ X, M = loopyOn X := ⟨M.E, by simpa [eRank_eq_zero_iff] using h⟩ @[simp] lemma eRank_emptyOn (α : Type*) : (emptyOn α).eRank = 0 := by rw [eRank_eq_zero_iff, emptyOn_ground, loopyOn_empty] lemma eq_loopyOn_iff_eRank : M = loopyOn X ↔ M.eRank = 0 ∧ M.E = X := ⟨fun h ↦ by rw [h]; simp, fun ⟨h,h'⟩ ↦ by rw [← h', ← eRank_eq_zero_iff, h]⟩ @[simp] lemma eRank_freeOn (X : Set α) : (freeOn X).eRank = X.encard := by rw [eRank_def, freeOn_ground, (freeOn_indep_iff.2 rfl.subset).eRk_eq_encard] lemma eRk_freeOn (hXY : X ⊆ Y) : (freeOn Y).eRk X = X.encard := by obtain ⟨I, hI⟩ := (freeOn Y).exists_isBasis X rw [hI.eRk_eq_encard, (freeOn_indep hXY).eq_of_isBasis hI] /-! ### Duality -/ lemma IsBase.encard_compl_eq (hB : M.IsBase B) : (M.E \ B).encard = M✶.eRank := (hB.compl_isBase_dual).encard_eq_eRank /-- A subtraction-free formula for the rank of a set in the dual matroid. -/ lemma eRk_dual_add_eRank (M : Matroid α) (X : Set α) (hX : X ⊆ M.E := by aesop_mat) : M✶.eRk X + M.eRank = M.eRk (M.E \ X) + X.encard := by obtain ⟨I, hI⟩ := M✶.exists_isBasis X obtain ⟨B, hB, rfl⟩ := hI.exists_isBasis_inter_eq_of_superset hX have hB' : M✶.IsBase B := isBasis_ground_iff.1 hB have hd : M.IsBasis (M.E \ B ∩ (M.E \ X)) (M.E \ X) := by simpa using hB'.inter_isBasis_iff_compl_inter_isBasis_dual.1 hI rw [← hB'.compl_isBase_of_dual.encard_eq_eRank, hI.eRk_eq_encard, hd.eRk_eq_encard, ← encard_union_eq (by tauto_set), ← encard_union_eq (by tauto_set)] exact congr_arg _ (by tauto_set) /-- A version of `Matroid.dual_eRk_add_eRank` for non-subsets of the ground set. -/ lemma eRk_dual_add_eRank' (M : Matroid α) (X : Set α) : M✶.eRk X + M.eRank = M.eRk (M.E \ X) + (X ∩ M.E).encard := by rw [← diff_inter_self_eq_diff, ← eRk_dual_add_eRank .., ← dual_ground, eRk_inter_ground] @[simp] lemma eRank_add_eRank_dual (M : Matroid α) : M.eRank + M✶.eRank = M.E.encard := by obtain ⟨B, hB⟩ := M.exists_isBase rw [← hB.encard_eq_eRank, ← hB.compl_isBase_dual.encard_eq_eRank, ← encard_union_eq disjoint_sdiff_right, union_diff_cancel hB.subset_ground] end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Rank/Cardinal.lean
import Mathlib.Combinatorics.Matroid.Map import Mathlib.Combinatorics.Matroid.Rank.ENat import Mathlib.Combinatorics.Matroid.Rank.Finite import Mathlib.SetTheory.Cardinal.Arithmetic /-! # Cardinal-valued rank In a finitary matroid, all bases have the same cardinality. In fact, something stronger holds: if each of `I` and `J` is a basis for a set `X`, then `#(I \ J) = #(J \ I)` and (consequently) `#I = #J`. This file introduces a typeclass `InvariantCardinalRank` that applies to any matroid such that this property holds for all `I`, `J` and `X`. A matroid satisfying this condition has a well-defined cardinality-valued rank function, both for itself and all its minors. ## Main Declarations * `Matroid.InvariantCardinalRank` : a typeclass capturing the idea that a matroid and all its minors have a well-behaved cardinal-valued rank function. * `Matroid.cRank M` is the supremum of the cardinalities of the bases of matroid `M`. * `Matroid.cRk M X` is the supremum of the cardinalities of the bases of a set `X` in a matroid `M`. * `invariantCardinalRank_of_finitary` is the instance showing that `Finitary` matroids are `InvariantCardinalRank`. * `cRk_inter_add_cRk_union_le` states that cardinal rank is submodular. ## Notes It is not (provably) the case that all matroids are `InvariantCardinalRank`, since the equicardinality of bases in general matroids is independent of ZFC (see the module docstring of `Mathlib/Data/Matroid/Basic.lean`). Lemmas like `Matroid.Base.cardinalMk_diff_comm` become true for all matroids only if they are weakened by replacing `Cardinal.mk` with the cruder `ℕ∞`-valued `Set.encard`. The `ℕ∞`-valued rank and rank functions `Matroid.eRank` and `Matroid.eRk`, which have a more unconditionally strong API, are developed in `Mathlib/Data/Matroid/Rank/ENat.lean`. ## Implementation Details Since the functions `cRank` and `cRk` are defined as suprema, independently of the `Matroid.InvariantCardinalRank` typeclass, they are well-defined for all matroids. However, for matroids that do not satisfy `InvariantCardinalRank`, they are badly behaved. For instance, in general `cRk` is not submodular, and its value may differ on a set `X` and the closure of `X`. We state and prove theorems without `InvariantCardinalRank` whenever possible, which sometime makes their proofs longer than they would be with the instance. ## TODO * Higgs' theorem : if the generalized continuum hypothesis holds, then every matroid is `InvariantCardinalRank`. -/ universe u v variable {α : Type u} {β : Type v} {f : α → β} {M : Matroid α} {I J B B' X Y : Set α} open Cardinal Set namespace Matroid section Rank variable {κ : Cardinal} /-- The rank (supremum of the cardinalities of bases) of a matroid `M` as a `Cardinal`. See `Matroid.eRank` for a better-behaved `ℕ∞`-valued version. -/ noncomputable def cRank (M : Matroid α) := ⨆ B : {B // M.IsBase B}, #B /-- The rank (supremum of the cardinalities of bases) of a set `X` in a matroid `M`, as a `Cardinal`. See `Matroid.eRk` for a better-behaved `ℕ∞`-valued version. -/ noncomputable def cRk (M : Matroid α) (X : Set α) := (M ↾ X).cRank theorem IsBase.cardinalMk_le_cRank (hB : M.IsBase B) : #B ≤ M.cRank := le_ciSup (f := fun B : {B // M.IsBase B} ↦ #B.1) (bddAbove_range _) ⟨B, hB⟩ theorem Indep.cardinalMk_le_cRank (ind : M.Indep I) : #I ≤ M.cRank := have ⟨B, isBase, hIB⟩ := ind.exists_isBase_superset le_ciSup_of_le (bddAbove_range _) ⟨B, isBase⟩ (mk_le_mk_of_subset hIB) theorem cRank_eq_iSup_cardinalMk_indep : M.cRank = ⨆ I : {I // M.Indep I}, #I := (ciSup_le' fun B ↦ le_ciSup_of_le (bddAbove_range _) ⟨B, B.2.indep⟩ <| by rfl).antisymm <| ciSup_le' fun I ↦ have ⟨B, isBase, hIB⟩ := I.2.exists_isBase_superset le_ciSup_of_le (bddAbove_range _) ⟨B, isBase⟩ (mk_le_mk_of_subset hIB) theorem IsBasis'.cardinalMk_le_cRk (hIX : M.IsBasis' I X) : #I ≤ M.cRk X := (isBase_restrict_iff'.2 hIX).cardinalMk_le_cRank theorem IsBasis.cardinalMk_le_cRk (hIX : M.IsBasis I X) : #I ≤ M.cRk X := hIX.isBasis'.cardinalMk_le_cRk theorem cRank_le_iff : M.cRank ≤ κ ↔ ∀ ⦃B⦄, M.IsBase B → #B ≤ κ := ⟨fun h _ hB ↦ (hB.cardinalMk_le_cRank.trans h), fun h ↦ ciSup_le fun ⟨_, hB⟩ ↦ h hB⟩ theorem cRk_le_iff : M.cRk X ≤ κ ↔ ∀ ⦃I⦄, M.IsBasis' I X → #I ≤ κ := by simp_rw [cRk, cRank_le_iff, isBase_restrict_iff'] theorem Indep.cardinalMk_le_cRk_of_subset (hI : M.Indep I) (hIX : I ⊆ X) : #I ≤ M.cRk X := let ⟨_, hJ, hIJ⟩ := hI.subset_isBasis'_of_subset hIX (mk_le_mk_of_subset hIJ).trans hJ.cardinalMk_le_cRk theorem cRk_le_cardinalMk (M : Matroid α) (X : Set α) : M.cRk X ≤ #X := ciSup_le fun ⟨_, hI⟩ ↦ mk_le_mk_of_subset hI.subset_ground @[simp] theorem cRk_ground (M : Matroid α) : M.cRk M.E = M.cRank := by rw [cRk, restrict_ground_eq_self] @[simp] theorem cRank_restrict (M : Matroid α) (X : Set α) : (M ↾ X).cRank = M.cRk X := rfl theorem cRk_mono (M : Matroid α) : Monotone M.cRk := by simp only [Monotone, le_eq_subset, cRk_le_iff] intro X Y hXY I hIX obtain ⟨J, hJ, hIJ⟩ := hIX.indep.subset_isBasis'_of_subset (hIX.subset.trans hXY) exact (mk_le_mk_of_subset hIJ).trans hJ.cardinalMk_le_cRk theorem cRk_le_of_subset (M : Matroid α) (hXY : X ⊆ Y) : M.cRk X ≤ M.cRk Y := M.cRk_mono hXY @[simp] theorem cRk_inter_ground (M : Matroid α) (X : Set α) : M.cRk (X ∩ M.E) = M.cRk X := (M.cRk_le_of_subset inter_subset_left).antisymm <| cRk_le_iff.2 fun _ h ↦ h.isBasis_inter_ground.cardinalMk_le_cRk theorem cRk_restrict_subset (M : Matroid α) (hYX : Y ⊆ X) : (M ↾ X).cRk Y = M.cRk Y := by have aux : ∀ ⦃I⦄, M.IsBasis' I Y ↔ (M ↾ X).IsBasis' I Y := by simp_rw [isBasis'_restrict_iff, inter_eq_self_of_subset_left hYX, iff_self_and] exact fun I h ↦ h.subset.trans hYX simp_rw [le_antisymm_iff, cRk_le_iff] exact ⟨fun I hI ↦ (aux.2 hI).cardinalMk_le_cRk, fun I hI ↦ (aux.1 hI).cardinalMk_le_cRk⟩ theorem cRk_restrict (M : Matroid α) (X Y : Set α) : (M ↾ X).cRk Y = M.cRk (X ∩ Y) := by rw [← cRk_inter_ground, restrict_ground_eq, cRk_restrict_subset _ inter_subset_right, inter_comm] theorem Indep.cRk_eq_cardinalMk (hI : M.Indep I) : #I = M.cRk I := (M.cRk_le_cardinalMk I).antisymm' (hI.isBasis_self.cardinalMk_le_cRk) @[simp] theorem cRk_map_image_lift (M : Matroid α) (hf : InjOn f M.E) (X : Set α) (hX : X ⊆ M.E := by aesop_mat) : lift.{u,v} ((M.map f hf).cRk (f '' X)) = lift (M.cRk X) := by nth_rw 1 [cRk, cRank, le_antisymm_iff, lift_iSup (bddAbove_range _), cRk, cRank, cRk, cRank] nth_rw 2 [lift_iSup (bddAbove_range _)] simp only [ciSup_le_iff (bddAbove_range _), ge_iff_le, Subtype.forall, isBase_restrict_iff', isBasis'_iff_isBasis hX, isBasis'_iff_isBasis (show f '' X ⊆ (M.map f hf).E from image_mono hX)] refine ⟨fun I hI ↦ ?_, fun I hI ↦ ?_⟩ · obtain ⟨I, X', hIX, rfl, hXX'⟩ := map_isBasis_iff'.1 hI rw [mk_image_eq_of_injOn_lift _ _ (hf.mono hIX.indep.subset_ground), lift_le] obtain rfl : X = X' := by rwa [hf.image_eq_image_iff hX hIX.subset_ground] at hXX' exact hIX.cardinalMk_le_cRk rw [← mk_image_eq_of_injOn_lift _ _ (hf.mono hI.indep.subset_ground), lift_le] exact (hI.map hf).cardinalMk_le_cRk @[simp] theorem cRk_map_image {β : Type u} {f : α → β} (M : Matroid α) (hf : InjOn f M.E) (X : Set α) (hX : X ⊆ M.E := by aesop_mat) : (M.map f hf).cRk (f '' X) = M.cRk X := lift_inj.1 <| M.cRk_map_image_lift .. theorem cRk_map_eq {β : Type u} {f : α → β} {X : Set β} (M : Matroid α) (hf : InjOn f M.E) : (M.map f hf).cRk X = M.cRk (f ⁻¹' X) := by rw [← M.cRk_inter_ground, ← M.cRk_map_image hf _, image_preimage_inter, ← map_ground _ _ hf, cRk_inter_ground] @[simp] theorem cRk_comap_lift (M : Matroid β) (f : α → β) (X : Set α) : lift.{v,u} ((M.comap f).cRk X) = lift (M.cRk (f '' X)) := by nth_rw 1 [cRk, cRank, le_antisymm_iff, lift_iSup (bddAbove_range _), cRk, cRank, cRk, cRank] nth_rw 2 [lift_iSup (bddAbove_range _)] simp only [ciSup_le_iff (bddAbove_range _), ge_iff_le, Subtype.forall, isBase_restrict_iff', comap_isBasis'_iff, and_imp] refine ⟨fun I hI hfI hIX ↦ ?_, fun I hIX ↦ ?_⟩ · rw [← mk_image_eq_of_injOn_lift _ _ hfI, lift_le] exact hI.cardinalMk_le_cRk obtain ⟨I₀, hI₀X, rfl, hfI₀⟩ := show ∃ I₀ ⊆ X, f '' I₀ = I ∧ InjOn f I₀ by obtain ⟨I₀, hI₀ss, hbij⟩ := exists_subset_bijOn (f ⁻¹' I ∩ X) f refine ⟨I₀, hI₀ss.trans inter_subset_right, ?_, hbij.injOn⟩ rw [hbij.image_eq, image_preimage_inter, inter_eq_self_of_subset_left hIX.subset] rw [mk_image_eq_of_injOn_lift _ _ hfI₀, lift_le] exact IsBasis'.cardinalMk_le_cRk <| comap_isBasis'_iff.2 ⟨hIX, hfI₀, hI₀X⟩ @[simp] theorem cRk_comap {β : Type u} (M : Matroid β) (f : α → β) (X : Set α) : (M.comap f).cRk X = M.cRk (f '' X) := lift_inj.1 <| M.cRk_comap_lift .. end Rank section Invariant /-- A class stating that cardinality-valued rank is well-defined (i.e. all bases are equicardinal) for a matroid `M` and its minors. Notably, this holds for `Finitary` matroids; see `Matroid.invariantCardinalRank_of_finitary`. -/ @[mk_iff] class InvariantCardinalRank (M : Matroid α) : Prop where forall_card_isBasis_diff : ∀ ⦃I J X⦄, M.IsBasis I X → M.IsBasis J X → #(I \ J : Set α) = #(J \ I : Set α) variable [InvariantCardinalRank M] theorem IsBasis.cardinalMk_diff_comm (hIX : M.IsBasis I X) (hJX : M.IsBasis J X) : #(I \ J : Set α) = #(J \ I : Set α) := InvariantCardinalRank.forall_card_isBasis_diff hIX hJX theorem IsBasis'.cardinalMk_diff_comm (hIX : M.IsBasis' I X) (hJX : M.IsBasis' J X) : #(I \ J : Set α) = #(J \ I : Set α) := hIX.isBasis_inter_ground.cardinalMk_diff_comm hJX.isBasis_inter_ground theorem IsBase.cardinalMk_diff_comm (hB : M.IsBase B) (hB' : M.IsBase B') : #(B \ B' : Set α) = #(B' \ B : Set α) := hB.isBasis_ground.cardinalMk_diff_comm hB'.isBasis_ground theorem IsBasis.cardinalMk_eq (hIX : M.IsBasis I X) (hJX : M.IsBasis J X) : #I = #J := by rw [← diff_union_inter I J, mk_union_of_disjoint (disjoint_sdiff_left.mono_right inter_subset_right), hIX.cardinalMk_diff_comm hJX, ← mk_union_of_disjoint (disjoint_sdiff_left.mono_right inter_subset_left), inter_comm, diff_union_inter] theorem IsBasis'.cardinalMk_eq (hIX : M.IsBasis' I X) (hJX : M.IsBasis' J X) : #I = #J := hIX.isBasis_inter_ground.cardinalMk_eq hJX.isBasis_inter_ground theorem IsBase.cardinalMk_eq (hB : M.IsBase B) (hB' : M.IsBase B') : #B = #B' := hB.isBasis_ground.cardinalMk_eq hB'.isBasis_ground theorem Indep.cardinalMk_le_isBase (hI : M.Indep I) (hB : M.IsBase B) : #I ≤ #B := have ⟨_B', hB', hIB'⟩ := hI.exists_isBase_superset hB'.cardinalMk_eq hB ▸ mk_le_mk_of_subset hIB' theorem Indep.cardinalMk_le_isBasis' (hI : M.Indep I) (hJ : M.IsBasis' J X) (hIX : I ⊆ X) : #I ≤ #J := have ⟨_J', hJ', hIJ'⟩ := hI.subset_isBasis'_of_subset hIX hJ'.cardinalMk_eq hJ ▸ mk_le_mk_of_subset hIJ' theorem Indep.cardinalMk_le_isBasis (hI : M.Indep I) (hJ : M.IsBasis J X) (hIX : I ⊆ X) : #I ≤ #J := hI.cardinalMk_le_isBasis' hJ.isBasis' hIX theorem IsBase.cardinalMk_eq_cRank (hB : M.IsBase B) : #B = M.cRank := by have hrw : ∀ B' : {B : Set α // M.IsBase B}, #B' = #B := fun B' ↦ B'.2.cardinalMk_eq hB simp [cRank, hrw] /-- Restrictions of matroids with cardinal rank functions have cardinal rank functions. -/ instance invariantCardinalRank_restrict [InvariantCardinalRank M] : InvariantCardinalRank (M ↾ X) := by refine ⟨fun I J Y hI hJ ↦ ?_⟩ rw [isBasis_restrict_iff'] at hI hJ exact hI.1.cardinalMk_diff_comm hJ.1 theorem IsBasis'.cardinalMk_eq_cRk (hIX : M.IsBasis' I X) : #I = M.cRk X := by rw [cRk, (isBase_restrict_iff'.2 hIX).cardinalMk_eq_cRank] theorem IsBasis.cardinalMk_eq_cRk (hIX : M.IsBasis I X) : #I = M.cRk X := hIX.isBasis'.cardinalMk_eq_cRk @[simp] theorem cRk_closure (M : Matroid α) [InvariantCardinalRank M] (X : Set α) : M.cRk (M.closure X) = M.cRk X := by obtain ⟨I, hI⟩ := M.exists_isBasis' X rw [← hI.isBasis_closure_right.cardinalMk_eq_cRk, ← hI.cardinalMk_eq_cRk] theorem cRk_closure_congr (hXY : M.closure X = M.closure Y) : M.cRk X = M.cRk Y := by rw [← cRk_closure, hXY, cRk_closure] theorem Spanning.cRank_le_cardinalMk (h : M.Spanning X) : M.cRank ≤ #X := have ⟨_B, hB, hBX⟩ := h.exists_isBase_subset (hB.cardinalMk_eq_cRank).symm.trans_le (mk_le_mk_of_subset hBX) variable (M : Matroid α) [InvariantCardinalRank M] (e : α) (X Y : Set α) @[simp] theorem cRk_union_closure_right_eq : M.cRk (X ∪ M.closure Y) = M.cRk (X ∪ Y) := M.cRk_closure_congr (M.closure_union_closure_right_eq _ _) @[simp] theorem cRk_union_closure_left_eq : M.cRk (M.closure X ∪ Y) = M.cRk (X ∪ Y) := M.cRk_closure_congr (M.closure_union_closure_left_eq _ _) @[simp] theorem cRk_insert_closure_eq : M.cRk (insert e (M.closure X)) = M.cRk (insert e X) := by rw [← union_singleton, cRk_union_closure_left_eq, union_singleton] theorem cRk_union_closure_eq : M.cRk (M.closure X ∪ M.closure Y) = M.cRk (X ∪ Y) := by simp /-- The `Cardinal` rank function is submodular. -/ theorem cRk_inter_add_cRk_union_le : M.cRk (X ∩ Y) + M.cRk (X ∪ Y) ≤ M.cRk X + M.cRk Y := by obtain ⟨Ii, hIi⟩ := M.exists_isBasis' (X ∩ Y) obtain ⟨IX, hIX, hIX'⟩ := hIi.indep.subset_isBasis'_of_subset (hIi.subset.trans inter_subset_left) obtain ⟨IY, hIY, hIY'⟩ := hIi.indep.subset_isBasis'_of_subset (hIi.subset.trans inter_subset_right) rw [← cRk_union_closure_eq, ← hIX.closure_eq_closure, ← hIY.closure_eq_closure, cRk_union_closure_eq, ← hIi.cardinalMk_eq_cRk, ← hIX.cardinalMk_eq_cRk, ← hIY.cardinalMk_eq_cRk, ← mk_union_add_mk_inter, add_comm] exact add_le_add (M.cRk_le_cardinalMk _) (mk_le_mk_of_subset (subset_inter hIX' hIY')) end Invariant section Instances /-- `Finitary` matroids have a cardinality-valued rank function. -/ instance invariantCardinalRank_of_finitary [Finitary M] : InvariantCardinalRank M := by suffices aux : ∀ ⦃B B'⦄ ⦃N : Matroid α⦄, Finitary N → N.IsBase B → N.IsBase B' → #(B \ B' : Set α) ≤ #(B' \ B : Set α) from ⟨fun I J X hI hJ ↦ (aux (restrict_finitary X) hI.isBase_restrict hJ.isBase_restrict).antisymm (aux (restrict_finitary X) hJ.isBase_restrict hI.isBase_restrict)⟩ intro B B' N hfin hB hB' by_cases h : (B' \ B).Finite · rw [← cast_ncard h, ← cast_ncard, hB.ncard_diff_comm hB'] exact (hB'.diff_finite_comm hB).mp h rw [← Set.Infinite, ← infinite_coe_iff] at h have (a : α) (ha : a ∈ B' \ B) : ∃ S : Set α, Finite S ∧ S ⊆ B ∧ ¬ N.Indep (insert a S) := by have := (hB.insert_dep ⟨hB'.subset_ground ha.1, ha.2⟩).1 contrapose! this exact Finitary.indep_of_forall_finite _ fun J hJ fin ↦ (this (J \ {a}) fin.diff.to_subtype <| diff_singleton_subset_iff.mpr hJ).subset (subset_insert_diff_singleton ..) choose S S_fin hSB dep using this let U := ⋃ a : ↥(B' \ B), S a a.2 suffices B \ B' ⊆ U by refine (mk_le_mk_of_subset this).trans <| (mk_iUnion_le ..).trans <| (mul_le_max_of_aleph0_le_left (by simp)).trans ?_ simp only [sup_le_iff, le_refl, true_and] exact ciSup_le' fun e ↦ (lt_aleph0_of_finite _).le.trans <| by simp rw [← diff_inter_self_eq_diff, diff_subset_iff, inter_comm] have hUB : (B ∩ B') ∪ U ⊆ B := union_subset inter_subset_left (iUnion_subset fun e ↦ (hSB e.1 e.2)) by_contra hBU have ⟨a, ha, ind⟩ := hB.exists_insert_of_ssubset ⟨hUB, hBU⟩ hB' have : a ∈ B' \ B := ⟨ha.1, fun haB ↦ ha.2 (.inl ⟨haB, ha.1⟩)⟩ refine dep a this (ind.subset <| insert_subset_insert <| .trans ?_ subset_union_right) exact subset_iUnion_of_subset ⟨a, this⟩ subset_rfl instance invariantCardinalRank_map (M : Matroid α) [InvariantCardinalRank M] (hf : InjOn f M.E) : InvariantCardinalRank (M.map f hf) := by refine ⟨fun I J X hI hJ ↦ ?_⟩ obtain ⟨I, X, hIX, rfl, rfl⟩ := map_isBasis_iff'.1 hI obtain ⟨J, X', hJX, rfl, h'⟩ := map_isBasis_iff'.1 hJ obtain rfl : X = X' := by rwa [InjOn.image_eq_image_iff hf hIX.subset_ground hJX.subset_ground] at h' have hcard := hIX.cardinalMk_diff_comm hJX rwa [← lift_inj.{u,v}, ← mk_image_eq_of_injOn_lift _ _ (hf.mono ((hIX.indep.diff _).subset_ground)), ← mk_image_eq_of_injOn_lift _ _ (hf.mono ((hJX.indep.diff _).subset_ground)), lift_inj, (hf.mono hIX.indep.subset_ground).image_diff, (hf.mono hJX.indep.subset_ground).image_diff, inter_comm, hf.image_inter hJX.indep.subset_ground hIX.indep.subset_ground, diff_inter_self_eq_diff, diff_self_inter] at hcard instance invariantCardinalRank_comap (M : Matroid β) [InvariantCardinalRank M] (f : α → β) : InvariantCardinalRank (M.comap f) := by refine ⟨fun I J X hI hJ ↦ ?_⟩ obtain ⟨hI, hfI, hIX⟩ := comap_isBasis_iff.1 hI obtain ⟨hJ, hfJ, hJX⟩ := comap_isBasis_iff.1 hJ rw [← lift_inj.{u,v}, ← mk_image_eq_of_injOn_lift _ _ (hfI.mono diff_subset), ← mk_image_eq_of_injOn_lift _ _ (hfJ.mono diff_subset), lift_inj, hfI.image_diff, hfJ.image_diff, ← diff_union_diff_cancel inter_subset_left (image_inter_subset f I J), inter_comm, diff_inter_self_eq_diff, mk_union_of_disjoint, hI.cardinalMk_diff_comm hJ, ← diff_union_diff_cancel inter_subset_left (image_inter_subset f J I), inter_comm, diff_inter_self_eq_diff, mk_union_of_disjoint, inter_comm J I] <;> exact disjoint_sdiff_left.mono_right (diff_subset.trans inter_subset_left) end Instances theorem rankFinite_iff_cRank_lt_aleph0 : M.RankFinite ↔ M.cRank < ℵ₀ := by refine ⟨fun h ↦ ?_, fun h ↦ ⟨?_⟩⟩ · have ⟨B, hB, fin⟩ := h exact hB.cardinalMk_eq_cRank ▸ lt_aleph0_iff_finite.mpr fin have ⟨B, hB⟩ := M.exists_isBase simp_rw [← finite_coe_iff, ← lt_aleph0_iff_finite] exact ⟨B, hB, hB.cardinalMk_le_cRank.trans_lt h⟩ theorem rankInfinite_iff_aleph0_le_cRank : M.RankInfinite ↔ ℵ₀ ≤ M.cRank := by rw [← not_lt, ← rankFinite_iff_cRank_lt_aleph0, not_rankFinite_iff] theorem isRkFinite_iff_cRk_lt_aleph0 : M.IsRkFinite X ↔ M.cRk X < ℵ₀ := by rw [IsRkFinite, rankFinite_iff_cRank_lt_aleph0, cRank_restrict] theorem Indep.isBase_of_cRank_le [M.RankFinite] (ind : M.Indep I) (le : M.cRank ≤ #I) : M.IsBase I := ind.isBase_of_maximal fun _J ind_J hIJ ↦ ind.finite.eq_of_subset_of_encard_le hIJ <| toENat.monotone' <| ind_J.cardinalMk_le_cRank.trans le theorem Spanning.isBase_of_le_cRank [M.RankFinite] (h : M.Spanning X) (le : #X ≤ M.cRank) : M.IsBase X := by have ⟨B, hB, hBX⟩ := h.exists_isBase_subset rwa [← hB.finite.eq_of_subset_of_encard_le hBX (toENat.monotone' <| le.trans hB.cardinalMk_eq_cRank.ge)] theorem Indep.isBase_of_cRank_le_of_finite (ind : M.Indep I) (le : M.cRank ≤ #I) (fin : I.Finite) : M.IsBase I := have := rankFinite_iff_cRank_lt_aleph0.mpr (le.trans_lt <| lt_aleph0_iff_finite.mpr fin) ind.isBase_of_cRank_le le theorem Spanning.isBase_of_le_cRank_of_finite (h : M.Spanning X) (le : #X ≤ M.cRank) (fin : X.Finite) : M.IsBase X := have ⟨_B, hB, hBX⟩ := h.exists_isBase_subset have := hB.rankFinite_of_finite (fin.subset hBX) h.isBase_of_le_cRank le @[simp] theorem toENat_cRank_eq (M : Matroid α) : M.cRank.toENat = M.eRank := by obtain h | h := M.rankFinite_or_rankInfinite · obtain ⟨B, hB⟩ := M.exists_isBase rw [← hB.cardinalMk_eq_cRank, ← hB.encard_eq_eRank, toENat_cardinalMk] simp [rankInfinite_iff_aleph0_le_cRank.1 h] @[simp] theorem toENat_cRk_eq (M : Matroid α) (X : Set α) : (M.cRk X).toENat = M.eRk X := by rw [cRk, toENat_cRank_eq, eRk] end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Minor/Order.lean
import Mathlib.Combinatorics.Matroid.Minor.Contract /-! # Matroid Minors A matroid `N = M / C \ D` obtained from a matroid `M` by a contraction then a delete, (or equivalently, by any number of contractions/deletions in any order) is a *minor* of `M`. This gives a partial order on `Matroid α` that is ubiquitous in matroid theory, and interacts nicely with duality and linear representations. Although we provide a `PartialOrder` instance on `Matroid α` corresponding to the minor order, we do not use the `M ≤ N` / `N < M` notation directly, instead writing `N ≤m M` and `N <m M` for more convenient dot notation. ## Main Declarations * `Matroid.IsMinor N M`, written `N ≤m M`, means that `N = M / C \ D` for some subset `C` and `D` of `M.E`. * `Matroid.IsStrictMinor N M`, written `N <m M`, means that `N = M / C \ D` for some subsets `C` and `D` of `M.E` that are not both nonempty. * `Matroid.IsMinor.exists_eq_contract_delete_disjoint` : we can choose `C` and `D` disjoint. -/ namespace Matroid open Set section Minor variable {α : Type*} {M M' N : Matroid α} {e f : α} {I C D : Set α} /-! ### Minors -/ /-- `N` is a minor of `M` if `N = M / C \ D` for some `C` and `D`. The definition itself does not require `C` and `D` to be disjoint, or even to be subsets of the ground set. See `Matroid.IsMinor.exists_eq_contract_delete_disjoint` for the fact that we can choose `C` and `D` with these properties. -/ def IsMinor (N M : Matroid α) : Prop := ∃ C D, N = M / C \ D /-- `≤m` denotes the minor relation on matroids. -/ infixl:50 " ≤m " => Matroid.IsMinor @[simp] lemma contract_delete_isMinor (M : Matroid α) (C D : Set α) : M / C \ D ≤m M := ⟨C, D, rfl⟩ lemma IsMinor.exists_eq_contract_delete_disjoint (h : N ≤m M) : ∃ (C D : Set α), C ⊆ M.E ∧ D ⊆ M.E ∧ Disjoint C D ∧ N = M / C \ D := by obtain ⟨C, D, rfl⟩ := h exact ⟨C ∩ M.E, (D ∩ M.E) \ C, inter_subset_right, diff_subset.trans inter_subset_right, disjoint_sdiff_right.mono_left inter_subset_left, by simp [delete_eq_delete_iff, inter_assoc, inter_diff_assoc]⟩ /-- `N` is a strict minor of `M` if `N` is a minor of `M` and `N ≠ M`. Equivalently, `N` is obtained from `M` by deleting/contracting subsets of the ground set that are not both empty. -/ def IsStrictMinor (N M : Matroid α) : Prop := N ≤m M ∧ ¬ M ≤m N /-- `<m` denotes the strict minor relation on matroids. -/ infixl:50 " <m " => Matroid.IsStrictMinor lemma IsMinor.subset (h : N ≤m M) : N.E ⊆ M.E := by obtain ⟨C, D, rfl⟩ := h exact diff_subset.trans diff_subset lemma IsMinor.refl {M : Matroid α} : M ≤m M := ⟨∅, ∅, by simp⟩ lemma IsMinor.trans {M₁ M₂ M₃ : Matroid α} (h : M₁ ≤m M₂) (h' : M₂ ≤m M₃) : M₁ ≤m M₃ := by obtain ⟨C₁, D₁, rfl⟩ := h obtain ⟨C₂, D₂, rfl⟩ := h' exact ⟨C₂ ∪ C₁ \ D₂, D₂ ∪ D₁, by rw [contract_delete_contract_delete']⟩ lemma IsMinor.eq_of_ground_subset (h : N ≤m M) (hE : M.E ⊆ N.E) : M = N := by obtain ⟨C, D, rfl⟩ := h rw [delete_ground, contract_ground, subset_diff, subset_diff] at hE rw [← contract_inter_ground_eq, hE.1.2.symm.inter_eq, contract_empty, ← delete_inter_ground_eq, hE.2.symm.inter_eq, delete_empty] lemma IsMinor.antisymm (h : N ≤m M) (h' : M ≤m N) : N = M := h'.eq_of_ground_subset h.subset /-- The minor order is a `PartialOrder` on `Matroid α`. We prefer the spelling `N ≤m M` over `N ≤ M` for the dot notation. -/ instance (α : Type*) : PartialOrder (Matroid α) where le N M := N ≤m M lt N M := N <m M le_refl _ := IsMinor.refl le_trans _ _ _ := IsMinor.trans le_antisymm _ _ := IsMinor.antisymm lemma IsMinor.le (h : N ≤m M) : N ≤ M := h lemma IsStrictMinor.lt (h : N <m M) : N < M := h @[simp] lemma le_eq_isMinor : (fun M M' : Matroid α ↦ M ≤ M') = Matroid.IsMinor := rfl @[simp] lemma lt_eq_isStrictMinor : (fun M M' : Matroid α ↦ M < M') = Matroid.IsStrictMinor := rfl lemma isStrictMinor_iff_isMinor_ne : N <m M ↔ N ≤m M ∧ N ≠ M := lt_iff_le_and_ne (α := Matroid α) lemma IsStrictMinor.ne (h : N <m M) : N ≠ M := h.lt.ne lemma isStrictMinor_irrefl (M : Matroid α) : ¬ (M <m M) := lt_irrefl M lemma IsStrictMinor.isMinor (h : N <m M) : N ≤m M := h.lt.le lemma IsStrictMinor.not_isMinor (h : N <m M) : ¬ (M ≤m N) := h.lt.not_ge lemma IsStrictMinor.ssubset (h : N <m M) : N.E ⊂ M.E := h.isMinor.subset.ssubset_of_ne (fun hE ↦ h.ne (h.isMinor.eq_of_ground_subset hE.symm.subset).symm) lemma isStrictMinor_iff_isMinor_ssubset : N <m M ↔ N ≤m M ∧ N.E ⊂ M.E := ⟨fun h ↦ ⟨h.isMinor, h.ssubset⟩, fun ⟨h, hss⟩ ↦ ⟨h, fun h' ↦ hss.ne <| by rw [h'.antisymm h]⟩⟩ lemma IsStrictMinor.trans_isMinor (h : N <m M) (h' : M ≤m M') : N <m M' := h.lt.trans_le h' lemma IsMinor.trans_isStrictMinor (h : N ≤m M) (h' : M <m M') : N <m M' := h.le.trans_lt h' lemma IsStrictMinor.trans (h : N <m M) (h' : M <m M') : N <m M' := h.lt.trans h' lemma Indep.of_isMinor (hI : N.Indep I) (hNM : N ≤m M) : M.Indep I := by obtain ⟨C, D, rfl⟩ := hNM exact hI.of_delete.of_contract lemma IsNonloop.of_isMinor (h : N.IsNonloop e) (hNM : N ≤m M) : M.IsNonloop e := by obtain ⟨C, D, rfl⟩ := hNM exact h.of_delete.of_contract lemma Dep.of_isMinor {D : Set α} (hD : M.Dep D) (hDN : D ⊆ N.E) (hNM : N ≤m M) : N.Dep D := ⟨fun h ↦ hD.not_indep <| h.of_isMinor hNM, hDN⟩ lemma IsLoop.of_isMinor (he : M.IsLoop e) (heN : e ∈ N.E) (hNM : N ≤m M) : N.IsLoop e := by rw [← singleton_dep] at he ⊢ exact he.of_isMinor (by simpa) hNM end Minor end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Minor/Restrict.lean
import Mathlib.Combinatorics.Matroid.Dual /-! # Matroid Restriction Given `M : Matroid α` and `R : Set α`, the independent sets of `M` that are contained in `R` are the independent sets of another matroid `M ↾ R` with ground set `R`, called the 'restriction' of `M` to `R`. For `I ⊆ R ⊆ M.E`, `I` is a basis of `R` in `M` if and only if `I` is a base of the restriction `M ↾ R`, so this construction relates `Matroid.IsBasis` to `Matroid.IsBase`. If `N M : Matroid α` satisfy `N = M ↾ R` for some `R ⊆ M.E`, then we call `N` a 'restriction of `M`', and write `N ≤r M`. This is a partial order. This file proves that the restriction is a matroid and that the `≤r` order is a partial order, and gives related API. It also proves some `Matroid.IsBasis` analogues of `Matroid.IsBase` lemmas that, while they could be stated in `Data.Matroid.Basic`, are hard to prove without `Matroid.restrict` API. ## Main Definitions * `M.restrict R`, written `M ↾ R`, is the restriction of `M : Matroid α` to `R : Set α`: i.e. the matroid with ground set `R` whose independent sets are the `M`-independent subsets of `R`. * `Matroid.Restriction N M`, written `N ≤r M`, means that `N = M ↾ R` for some `R ⊆ M.E`. * `Matroid.IsStrictRestriction N M`, written `N <r M`, means that `N = M ↾ R` for some `R ⊂ M.E`. * `Matroidᵣ α` is a type synonym for `Matroid α`, equipped with the `PartialOrder` `≤r`. ## Implementation Notes Since `R` and `M.E` are both terms in `Set α`, to define the restriction `M ↾ R`, we need to either insist that `R ⊆ M.E`, or to say what happens when `R` contains the junk outside `M.E`. It turns out that `R ⊆ M.E` is just an unnecessary hypothesis; if we say the restriction `M ↾ R` has ground set `R` and its independent sets are the `M`-independent subsets of `R`, we always get a matroid, in which the elements of `R \ M.E` aren't in any independent sets. We could instead define this matroid to always be 'smaller' than `M` by setting `(M ↾ R).E := R ∩ M.E`, but this is worse definitionally, and more generally less convenient. This makes it possible to actually restrict a matroid 'upwards'; for instance, if `M : Matroid α` satisfies `M.E = ∅`, then `M ↾ Set.univ` is the matroid on `α` whose ground set is all of `α`, where the empty set is the only independent set. (In general, elements of `R \ M.E` are all 'loops' of the matroid `M ↾ R`; see `Matroid.loops` and `Matroid.restrict_loops_eq'` for a precise version of this statement.) This is mathematically strange, but is useful for API building. The cost of allowing a restriction of `M` to be 'bigger' than `M` itself is that the statement `M ↾ R ≤r M` is only true with the hypothesis `R ⊆ M.E` (at least, if we want `≤r` to be a partial order). But this isn't too inconvenient in practice. Indeed `(· ⊆ M.E)` proofs can often be automatically provided by `aesop_mat`. We define the restriction order `≤r` to give a `PartialOrder` instance on the type synonym `Matroidᵣ α` rather than `Matroid α` itself, because the `PartialOrder (Matroid α)` instance is reserved for the more mathematically important 'minor' order; see `Matroid.IsMinor`. -/ assert_not_exists Field open Set namespace Matroid variable {α : Type*} {M : Matroid α} {R I X Y : Set α} section restrict /-- The `IndepMatroid` whose independent sets are the independent subsets of `R`. -/ @[simps] def restrictIndepMatroid (M : Matroid α) (R : Set α) : IndepMatroid α where E := R Indep I := M.Indep I ∧ I ⊆ R indep_empty := ⟨M.empty_indep, empty_subset _⟩ indep_subset := fun _ _ h hIJ ↦ ⟨h.1.subset hIJ, hIJ.trans h.2⟩ indep_aug := by rintro I I' ⟨hI, hIY⟩ (hIn : ¬ M.IsBasis' I R) (hI' : M.IsBasis' I' R) rw [isBasis'_iff_isBasis_inter_ground] at hIn hI' obtain ⟨B', hB', rfl⟩ := hI'.exists_isBase obtain ⟨B, hB, hIB, hBIB'⟩ := hI.exists_isBase_subset_union_isBase hB' rw [hB'.inter_isBasis_iff_compl_inter_isBasis_dual, diff_inter_diff] at hI' have hss : M.E \ (B' ∪ (R ∩ M.E)) ⊆ M.E \ (B ∪ (R ∩ M.E)) := by apply diff_subset_diff_right rw [union_subset_iff, and_iff_left subset_union_right, union_comm] exact hBIB'.trans (union_subset_union_left _ (subset_inter hIY hI.subset_ground)) have hi : M✶.Indep (M.E \ (B ∪ (R ∩ M.E))) := by rw [dual_indep_iff_exists] exact ⟨B, hB, disjoint_of_subset_right subset_union_left disjoint_sdiff_left⟩ have h_eq := hI'.eq_of_subset_indep hi hss (diff_subset_diff_right subset_union_right) rw [h_eq, ← diff_inter_diff, ← hB.inter_isBasis_iff_compl_inter_isBasis_dual] at hI' obtain ⟨J, hJ, hIJ⟩ := hI.subset_isBasis_of_subset (subset_inter hIB (subset_inter hIY hI.subset_ground)) obtain rfl := hI'.indep.eq_of_isBasis hJ have hIJ' : I ⊂ B ∩ (R ∩ M.E) := hIJ.ssubset_of_ne (fun he ↦ hIn (by rwa [he])) obtain ⟨e, he⟩ := exists_of_ssubset hIJ' exact ⟨e, ⟨⟨(hBIB' he.1.1).elim (fun h ↦ (he.2 h).elim) id,he.1.2⟩, he.2⟩, hI'.indep.subset (insert_subset he.1 hIJ), insert_subset he.1.2.1 hIY⟩ indep_maximal := by rintro A hAR I ⟨hI, _⟩ hIA obtain ⟨J, hJ, hIJ⟩ := hI.subset_isBasis'_of_subset hIA use J simp only [hIJ, and_assoc, maximal_subset_iff, hJ.indep, hJ.subset, and_imp, true_and, hJ.subset.trans hAR] exact fun K hK _ hKA hJK ↦ hJ.eq_of_subset_indep hK hJK hKA subset_ground _ := And.right /-- Change the ground set of a matroid to some `R : Set α`. The independent sets of the restriction are the independent subsets of the new ground set. Most commonly used when `R ⊆ M.E`, but it is convenient not to require this. The elements of `R \ M.E` become 'loops'. -/ def restrict (M : Matroid α) (R : Set α) : Matroid α := (M.restrictIndepMatroid R).matroid /-- `M ↾ R` means `M.restrict R`. -/ scoped infixl:65 " ↾ " => Matroid.restrict @[simp] theorem restrict_indep_iff : (M ↾ R).Indep I ↔ M.Indep I ∧ I ⊆ R := Iff.rfl theorem Indep.indep_restrict_of_subset (h : M.Indep I) (hIR : I ⊆ R) : (M ↾ R).Indep I := restrict_indep_iff.mpr ⟨h,hIR⟩ theorem Indep.of_restrict (hI : (M ↾ R).Indep I) : M.Indep I := (restrict_indep_iff.1 hI).1 @[simp] theorem restrict_ground_eq : (M ↾ R).E = R := rfl theorem restrict_finite {R : Set α} (hR : R.Finite) : (M ↾ R).Finite := ⟨hR⟩ @[simp] theorem restrict_dep_iff : (M ↾ R).Dep X ↔ ¬ M.Indep X ∧ X ⊆ R := by rw [Dep, restrict_indep_iff, restrict_ground_eq]; tauto @[simp] theorem restrict_ground_eq_self (M : Matroid α) : (M ↾ M.E) = M := by refine ext_indep rfl ?_; simp_all theorem restrict_restrict_eq {R₁ R₂ : Set α} (M : Matroid α) (hR : R₂ ⊆ R₁) : (M ↾ R₁) ↾ R₂ = M ↾ R₂ := by refine ext_indep rfl ?_ simp only [restrict_ground_eq, restrict_indep_iff, and_congr_left_iff, and_iff_left_iff_imp] exact fun _ h _ _ ↦ h.trans hR @[simp] theorem restrict_idem (M : Matroid α) (R : Set α) : M ↾ R ↾ R = M ↾ R := by rw [M.restrict_restrict_eq Subset.rfl] @[simp] theorem isBase_restrict_iff (hX : X ⊆ M.E := by aesop_mat) : (M ↾ X).IsBase I ↔ M.IsBasis I X := by simp_rw [isBase_iff_maximal_indep, IsBasis, and_iff_left hX, maximal_iff, restrict_indep_iff] theorem isBase_restrict_iff' : (M ↾ X).IsBase I ↔ M.IsBasis' I X := by simp_rw [isBase_iff_maximal_indep, IsBasis', maximal_iff, restrict_indep_iff] theorem IsBasis'.isBase_restrict (hI : M.IsBasis' I X) : (M ↾ X).IsBase I := isBase_restrict_iff'.1 hI theorem IsBasis.restrict_isBase (h : M.IsBasis I X) : (M ↾ X).IsBase I := (isBase_restrict_iff h.subset_ground).2 h instance restrict_rankFinite [M.RankFinite] (R : Set α) : (M ↾ R).RankFinite := let ⟨_, hB⟩ := (M ↾ R).exists_isBase hB.rankFinite_of_finite (hB.indep.of_restrict.finite) instance restrict_finitary [Finitary M] (R : Set α) : Finitary (M ↾ R) := by refine ⟨fun I hI ↦ ?_⟩ simp only [restrict_indep_iff] at * rw [indep_iff_forall_finite_subset_indep] exact ⟨fun J hJ hJfin ↦ (hI J hJ hJfin).1, fun e heI ↦ singleton_subset_iff.1 (hI _ (by simpa) (toFinite _)).2⟩ @[simp] theorem IsBasis.isBase_restrict (h : M.IsBasis I X) : (M ↾ X).IsBase I := (isBase_restrict_iff h.subset_ground).mpr h theorem IsBasis.isBasis_restrict_of_subset (hI : M.IsBasis I X) (hXY : X ⊆ Y) : (M ↾ Y).IsBasis I X := by rwa [← isBase_restrict_iff, M.restrict_restrict_eq hXY, isBase_restrict_iff] theorem isBasis'_restrict_iff : (M ↾ R).IsBasis' I X ↔ M.IsBasis' I (X ∩ R) ∧ I ⊆ R := by simp_rw [IsBasis', maximal_iff, restrict_indep_iff, subset_inter_iff, and_imp] tauto theorem isBasis_restrict_iff' : (M ↾ R).IsBasis I X ↔ M.IsBasis I (X ∩ M.E) ∧ X ⊆ R := by rw [isBasis_iff_isBasis'_subset_ground, isBasis'_restrict_iff, restrict_ground_eq, and_congr_left_iff, ← isBasis'_iff_isBasis_inter_ground] intro hXR rw [inter_eq_self_of_subset_left hXR, and_iff_left_iff_imp] exact fun h ↦ h.subset.trans hXR theorem isBasis_restrict_iff (hR : R ⊆ M.E := by aesop_mat) : (M ↾ R).IsBasis I X ↔ M.IsBasis I X ∧ X ⊆ R := by rw [isBasis_restrict_iff', and_congr_left_iff] intro hXR rw [← isBasis'_iff_isBasis_inter_ground, isBasis'_iff_isBasis] lemma isBasis'_iff_isBasis_restrict_univ : M.IsBasis' I X ↔ (M ↾ univ).IsBasis I X := by rw [isBasis_restrict_iff', isBasis'_iff_isBasis_inter_ground, and_iff_left (subset_univ _)] theorem restrict_eq_restrict_iff (M M' : Matroid α) (X : Set α) : M ↾ X = M' ↾ X ↔ ∀ I, I ⊆ X → (M.Indep I ↔ M'.Indep I) := by refine ⟨fun h I hIX ↦ ?_, fun h ↦ ext_indep rfl fun I (hI : I ⊆ X) ↦ ?_⟩ · rw [← and_iff_left (a := (M.Indep I)) hIX, ← and_iff_left (a := (M'.Indep I)) hIX, ← restrict_indep_iff, h, restrict_indep_iff] rw [restrict_indep_iff, and_iff_left hI, restrict_indep_iff, and_iff_left hI, h _ hI] @[simp] theorem restrict_eq_self_iff : M ↾ R = M ↔ R = M.E := ⟨fun h ↦ by rw [← h]; rfl, fun h ↦ by simp [h]⟩ end restrict section IsRestriction variable {N : Matroid α} /-- `Restriction N M` means that `N = M ↾ R` for some subset `R` of `M.E` -/ def IsRestriction (N M : Matroid α) : Prop := ∃ R ⊆ M.E, N = M ↾ R /-- `IsStrictRestriction N M` means that `N = M ↾ R` for some strict subset `R` of `M.E` -/ def IsStrictRestriction (N M : Matroid α) : Prop := IsRestriction N M ∧ ¬ IsRestriction M N /-- `N ≤r M` means that `N` is a `Restriction` of `M`. -/ scoped infix:50 " ≤r " => IsRestriction /-- `N <r M` means that `N` is a `IsStrictRestriction` of `M`. -/ scoped infix:50 " <r " => IsStrictRestriction /-- A type synonym for matroids with the isRestriction order. (The `PartialOrder` on `Matroid α` is reserved for the minor order) -/ @[ext] structure Matroidᵣ (α : Type*) where ofMatroid :: /-- The underlying `Matroid` -/ toMatroid : Matroid α instance {α : Type*} : CoeOut (Matroidᵣ α) (Matroid α) where coe := Matroidᵣ.toMatroid @[simp] theorem Matroidᵣ.coe_inj {M₁ M₂ : Matroidᵣ α} : (M₁ : Matroid α) = (M₂ : Matroid α) ↔ M₁ = M₂ := Matroidᵣ.ext_iff.symm instance {α : Type*} : PartialOrder (Matroidᵣ α) where le := (· ≤r ·) le_refl M := ⟨(M : Matroid α).E, Subset.rfl, (M : Matroid α).restrict_ground_eq_self.symm⟩ le_trans M₁ M₂ M₃ := by rintro ⟨R, hR, h₁⟩ ⟨R', hR', h₂⟩ rw [h₂] at h₁ hR rw [h₁, restrict_restrict_eq _ (show R ⊆ R' from hR)] exact ⟨R, hR.trans hR', rfl⟩ le_antisymm M₁ M₂ := by rintro ⟨R, hR, h⟩ ⟨R', hR', h'⟩ rw [h', restrict_ground_eq] at hR rw [h, restrict_ground_eq] at hR' rw [← Matroidᵣ.coe_inj, h, h', hR.antisymm hR', restrict_idem] @[simp] protected theorem Matroidᵣ.le_iff {M M' : Matroidᵣ α} : M ≤ M' ↔ (M : Matroid α) ≤r (M' : Matroid α) := Iff.rfl @[simp] protected theorem Matroidᵣ.lt_iff {M M' : Matroidᵣ α} : M < M' ↔ (M : Matroid α) <r (M' : Matroid α) := Iff.rfl theorem ofMatroid_le_iff {M M' : Matroid α} : Matroidᵣ.ofMatroid M ≤ Matroidᵣ.ofMatroid M' ↔ M ≤r M' := by simp theorem ofMatroid_lt_iff {M M' : Matroid α} : Matroidᵣ.ofMatroid M < Matroidᵣ.ofMatroid M' ↔ M <r M' := by simp theorem IsRestriction.refl : M ≤r M := le_refl (Matroidᵣ.ofMatroid M) theorem IsRestriction.antisymm {M' : Matroid α} (h : M ≤r M') (h' : M' ≤r M) : M = M' := by simpa using (ofMatroid_le_iff.2 h).antisymm (ofMatroid_le_iff.2 h') theorem IsRestriction.trans {M₁ M₂ M₃ : Matroid α} (h : M₁ ≤r M₂) (h' : M₂ ≤r M₃) : M₁ ≤r M₃ := le_trans (α := Matroidᵣ α) h h' theorem restrict_isRestriction (M : Matroid α) (R : Set α) (hR : R ⊆ M.E := by aesop_mat) : M ↾ R ≤r M := ⟨R, hR, rfl⟩ theorem IsRestriction.eq_restrict (h : N ≤r M) : M ↾ N.E = N := by obtain ⟨R, -, rfl⟩ := h; rw [restrict_ground_eq] theorem IsRestriction.subset (h : N ≤r M) : N.E ⊆ M.E := by obtain ⟨R, hR, rfl⟩ := h; exact hR theorem IsRestriction.exists_eq_restrict (h : N ≤r M) : ∃ R ⊆ M.E, N = M ↾ R := h theorem IsRestriction.of_subset {R' : Set α} (M : Matroid α) (h : R ⊆ R') : (M ↾ R) ≤r (M ↾ R') := by rw [← restrict_restrict_eq M h]; exact restrict_isRestriction _ _ h theorem isRestriction_iff_exists : (N ≤r M) ↔ ∃ R, R ⊆ M.E ∧ N = M ↾ R := by use IsRestriction.exists_eq_restrict; rintro ⟨R, hR, rfl⟩; exact restrict_isRestriction M R hR theorem IsStrictRestriction.isRestriction (h : N <r M) : N ≤r M := h.1 theorem IsStrictRestriction.ne (h : N <r M) : N ≠ M := by rintro rfl; rw [← ofMatroid_lt_iff] at h; simp at h theorem IsStrictRestriction.irrefl (M : Matroid α) : ¬ (M <r M) := fun h ↦ h.ne rfl theorem IsStrictRestriction.ssubset (h : N <r M) : N.E ⊂ M.E := by obtain ⟨R, -, rfl⟩ := h.1 refine h.isRestriction.subset.ssubset_of_ne (fun h' ↦ h.2 ⟨R, Subset.rfl, ?_⟩) rw [show R = M.E from h', restrict_idem, restrict_ground_eq_self] theorem IsStrictRestriction.eq_restrict (h : N <r M) : M ↾ N.E = N := h.isRestriction.eq_restrict theorem IsStrictRestriction.exists_eq_restrict (h : N <r M) : ∃ R, R ⊂ M.E ∧ N = M ↾ R := ⟨N.E, h.ssubset, by rw [h.eq_restrict]⟩ theorem IsRestriction.isStrictRestriction_of_ne (h : N ≤r M) (hne : N ≠ M) : N <r M := ⟨h, fun h' ↦ hne <| h.antisymm h'⟩ theorem IsRestriction.eq_or_isStrictRestriction (h : N ≤r M) : N = M ∨ N <r M := by simpa using eq_or_lt_of_le (ofMatroid_le_iff.2 h) theorem restrict_isStrictRestriction {M : Matroid α} (hR : R ⊂ M.E) : M ↾ R <r M := by refine (M.restrict_isRestriction R hR.subset).isStrictRestriction_of_ne (fun h ↦ ?_) rw [← h, restrict_ground_eq] at hR exact hR.ne rfl theorem IsRestriction.isStrictRestriction_of_ground_ne (h : N ≤r M) (hne : N.E ≠ M.E) : N <r M := by rw [← h.eq_restrict] exact restrict_isStrictRestriction (h.subset.ssubset_of_ne hne) theorem IsStrictRestriction.of_ssubset {R' : Set α} (M : Matroid α) (h : R ⊂ R') : (M ↾ R) <r (M ↾ R') := (IsRestriction.of_subset M h.subset).isStrictRestriction_of_ground_ne h.ne theorem IsRestriction.finite {M : Matroid α} [M.Finite] (h : N ≤r M) : N.Finite := by obtain ⟨R, hR, rfl⟩ := h exact restrict_finite <| M.ground_finite.subset hR theorem IsRestriction.rankFinite {M : Matroid α} [RankFinite M] (h : N ≤r M) : N.RankFinite := by obtain ⟨R, -, rfl⟩ := h infer_instance theorem IsRestriction.finitary {M : Matroid α} [Finitary M] (h : N ≤r M) : N.Finitary := by obtain ⟨R, -, rfl⟩ := h infer_instance theorem finite_setOf_isRestriction (M : Matroid α) [M.Finite] : {N | N ≤r M}.Finite := (M.ground_finite.finite_subsets.image (fun R ↦ M ↾ R)).subset <| by rintro _ ⟨R, hR, rfl⟩; exact ⟨_, hR, rfl⟩ theorem Indep.of_isRestriction (hI : N.Indep I) (hNM : N ≤r M) : M.Indep I := by obtain ⟨R, -, rfl⟩ := hNM; exact hI.of_restrict theorem Indep.indep_isRestriction (hI : M.Indep I) (hNM : N ≤r M) (hIN : I ⊆ N.E) : N.Indep I := by obtain ⟨R, -, rfl⟩ := hNM; simpa [hI] theorem IsRestriction.indep_iff (hMN : N ≤r M) : N.Indep I ↔ M.Indep I ∧ I ⊆ N.E := ⟨fun h ↦ ⟨h.of_isRestriction hMN, h.subset_ground⟩, fun h ↦ h.1.indep_isRestriction hMN h.2⟩ theorem IsBasis.isBasis_isRestriction (hI : M.IsBasis I X) (hNM : N ≤r M) (hX : X ⊆ N.E) : N.IsBasis I X := by obtain ⟨R, hR, rfl⟩ := hNM; rwa [isBasis_restrict_iff, and_iff_left (show X ⊆ R from hX)] theorem IsBasis.of_isRestriction (hI : N.IsBasis I X) (hNM : N ≤r M) : M.IsBasis I X := by obtain ⟨R, hR, rfl⟩ := hNM; exact ((isBasis_restrict_iff hR).1 hI).1 theorem IsBase.isBasis_of_isRestriction (hI : N.IsBase I) (hNM : N ≤r M) : M.IsBasis I N.E := by obtain ⟨R, hR, rfl⟩ := hNM; rwa [isBase_restrict_iff] at hI theorem IsRestriction.base_iff (hMN : N ≤r M) {B : Set α} : N.IsBase B ↔ M.IsBasis B N.E := ⟨fun h ↦ IsBase.isBasis_of_isRestriction h hMN, fun h ↦ by simpa [hMN.eq_restrict] using h.restrict_isBase⟩ theorem IsRestriction.isBasis_iff (hMN : N ≤r M) : N.IsBasis I X ↔ M.IsBasis I X ∧ X ⊆ N.E := ⟨fun h ↦ ⟨h.of_isRestriction hMN, h.subset_ground⟩, fun h ↦ h.1.isBasis_isRestriction hMN h.2⟩ theorem Dep.of_isRestriction (hX : N.Dep X) (hNM : N ≤r M) : M.Dep X := by obtain ⟨R, hR, rfl⟩ := hNM rw [restrict_dep_iff] at hX exact ⟨hX.1, hX.2.trans hR⟩ theorem Dep.dep_isRestriction (hX : M.Dep X) (hNM : N ≤r M) (hXE : X ⊆ N.E := by aesop_mat) : N.Dep X := by obtain ⟨R, -, rfl⟩ := hNM; simpa [hX.not_indep] theorem IsRestriction.dep_iff (hMN : N ≤r M) : N.Dep X ↔ M.Dep X ∧ X ⊆ N.E := ⟨fun h ↦ ⟨h.of_isRestriction hMN, h.subset_ground⟩, fun h ↦ h.1.dep_isRestriction hMN h.2⟩ end IsRestriction /-! ### `IsBasis` and `Base` The lemmas below exploit the fact that `(M ↾ X).Base I ↔ M.IsBasis I X` to transfer facts about `Matroid.Base` to facts about `Matroid.IsBasis`. Their statements thematically belong in `Data.Matroid.Basic`, but they appear here because their proofs depend on the API for `Matroid.restrict`, -/ section IsBasis variable {B J : Set α} {e : α} theorem IsBasis.transfer (hIX : M.IsBasis I X) (hJX : M.IsBasis J X) (hXY : X ⊆ Y) (hJY : M.IsBasis J Y) : M.IsBasis I Y := by rw [← isBase_restrict_iff]; rw [← isBase_restrict_iff] at hJY exact hJY.isBase_of_isBasis_superset hJX.subset (hIX.isBasis_restrict_of_subset hXY) theorem IsBasis.isBasis_of_isBasis_of_subset_of_subset (hI : M.IsBasis I X) (hJ : M.IsBasis J Y) (hJX : J ⊆ X) (hIY : I ⊆ Y) : M.IsBasis I Y := by have hI' := hI.isBasis_subset (subset_inter hI.subset hIY) inter_subset_left have hJ' := hJ.isBasis_subset (subset_inter hJX hJ.subset) inter_subset_right exact hI'.transfer hJ' inter_subset_right hJ theorem Indep.exists_isBasis_subset_union_isBasis (hI : M.Indep I) (hIX : I ⊆ X) (hJ : M.IsBasis J X) : ∃ I', M.IsBasis I' X ∧ I ⊆ I' ∧ I' ⊆ I ∪ J := by obtain ⟨I', hI', hII', hI'IJ⟩ := (hI.indep_restrict_of_subset hIX).exists_isBase_subset_union_isBase (IsBasis.isBase_restrict hJ) rw [isBase_restrict_iff] at hI' exact ⟨I', hI', hII', hI'IJ⟩ theorem Indep.exists_insert_of_not_isBasis (hI : M.Indep I) (hIX : I ⊆ X) (hI' : ¬M.IsBasis I X) (hJ : M.IsBasis J X) : ∃ e ∈ J \ I, M.Indep (insert e I) := by rw [← isBase_restrict_iff] at hI'; rw [← isBase_restrict_iff] at hJ obtain ⟨e, he, hi⟩ := (hI.indep_restrict_of_subset hIX).exists_insert_of_not_isBase hI' hJ exact ⟨e, he, (restrict_indep_iff.mp hi).1⟩ theorem IsBasis.isBase_of_isBase_subset (hIX : M.IsBasis I X) (hB : M.IsBase B) (hBX : B ⊆ X) : M.IsBase I := hB.isBase_of_isBasis_superset hBX hIX theorem IsBasis.exchange (hIX : M.IsBasis I X) (hJX : M.IsBasis J X) (he : e ∈ I \ J) : ∃ f ∈ J \ I, M.IsBasis (insert f (I \ {e})) X := by obtain ⟨y,hy, h⟩ := hIX.restrict_isBase.exchange hJX.restrict_isBase he exact ⟨y, hy, by rwa [isBase_restrict_iff] at h⟩ theorem IsBasis.eq_exchange_of_diff_eq_singleton (hI : M.IsBasis I X) (hJ : M.IsBasis J X) (hIJ : I \ J = {e}) : ∃ f ∈ J \ I, J = insert f I \ {e} := by rw [← isBase_restrict_iff] at hI hJ; exact hI.eq_exchange_of_diff_eq_singleton hJ hIJ theorem IsBasis'.encard_eq_encard (hI : M.IsBasis' I X) (hJ : M.IsBasis' J X) : I.encard = J.encard := by rw [← isBase_restrict_iff'] at hI hJ; exact hI.encard_eq_encard_of_isBase hJ theorem IsBasis.encard_eq_encard (hI : M.IsBasis I X) (hJ : M.IsBasis J X) : I.encard = J.encard := hI.isBasis'.encard_eq_encard hJ.isBasis' /-- Any independent set can be extended into a larger independent set. -/ theorem Indep.augment (hI : M.Indep I) (hJ : M.Indep J) (hIJ : I.encard < J.encard) : ∃ e ∈ J \ I, M.Indep (insert e I) := by by_contra! he have hb : M.IsBasis I (I ∪ J) := by simp_rw [hI.isBasis_iff_forall_insert_dep subset_union_left, union_diff_left, mem_diff, and_imp, dep_iff, insert_subset_iff, and_iff_left hI.subset_ground] exact fun e heJ heI ↦ ⟨he e ⟨heJ, heI⟩, hJ.subset_ground heJ⟩ obtain ⟨J', hJ', hJJ'⟩ := hJ.subset_isBasis_of_subset I.subset_union_right rw [← hJ'.encard_eq_encard hb] at hIJ exact hIJ.not_ge (encard_mono hJJ') lemma Indep.augment_finset {I J : Finset α} (hI : M.Indep I) (hJ : M.Indep J) (hIJ : I.card < J.card) : ∃ e ∈ J, e ∉ I ∧ M.Indep (insert e I) := by obtain ⟨x, hx, hxI⟩ := hI.augment hJ (by simpa [encard_eq_coe_toFinset_card]) simp only [mem_diff, Finset.mem_coe] at hx exact ⟨x, hx.1, hx.2, hxI⟩ end IsBasis end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Minor/Contract.lean
import Mathlib.Combinatorics.Matroid.Minor.Delete import Mathlib.Tactic.TautoSet /-! # Matroid Contraction Instead of deleting the elements of `X : Set α` from `M : Matroid α`, we can contract them. The *contraction* of `X` from `M`, denoted `M / X`, is the matroid on ground set `M.E \ X` in which a set `I` is independent if and only if `I ∪ J` is independent in `M`, where `J` is an arbitrarily chosen basis for `X`. Contraction corresponds to contracting edges in graphic matroids (hence the name) and corresponds to projecting to a quotient space in the case of linearly representable matroids. It is an important notion in both these settings. We can also define contraction much more tersely in terms of deletion and duality with `M / X = (M✶ \ X)✶`: that is, contraction is the dual operation of deletion. While this is perhaps less intuitive, we use this very concise expression as the definition, and prove with the lemma `Matroid.IsBasis.contract_indep_iff` that this is equivalent to the more verbose definition above. ## Main Declarations * `Matroid.contract M C`, written `M / C`, is the matroid on ground set `M.E \ C` in which a set `I ⊆ M.E \ C` is independent if and only if `I ∪ J` is independent in `M`, where `J` is an arbitrary basis for `C`. * `Matroid.contract_dual M C : (M / X)✶ = M✶ \ X`; the dual of contraction is deletion. * `Matroid.delete_dual M C : (M \ X)✶ = M✶ / X`; the dual of deletion is contraction. * `Matroid.IsBasis.contract_indep_iff`; if `I` is a basis for `C`, then the independent sets of `M / C` are exactly the `J ⊆ M.E \ C` for which `I ∪ J` is independent in `M`. * `Matroid.contract_delete_comm` : `M / C \ D = M \ D / C` for disjoint `C` and `D`. ## Naming conventions Mirroring the convention for deletion, we use the abbreviation `contractElem` in lemma names to refer to the contraction `M / {e}` of a single element `e : α` from `M : Matroid α`. -/ open Set variable {α : Type*} {M M' N : Matroid α} {e f : α} {I J R D B X Y Z K : Set α} namespace Matroid section Contract variable {C C₁ C₂ : Set α} /-- The contraction `M / C` is the matroid on `M.E \ C` in which a set `I ⊆ M.E \ C` is independent if and only if `I ∪ J` is independent, where `J` is an arbitrarily chosen basis for `C`. It is also equal by definition to `(M✶ \ C)✶`; see `Matroid.IsBasis.contract_indep_iff` for a proof that its independent sets are the claimed ones. -/ def contract (M : Matroid α) (C : Set α) : Matroid α := (M✶ \ C)✶ /-- `M / C` refers to the contraction of a set `C` from the matroid `M`. -/ scoped infixl:75 " / " => Matroid.contract @[simp] lemma contract_ground (M : Matroid α) (C : Set α) : (M / C).E = M.E \ C := rfl lemma dual_delete_dual (M : Matroid α) (X : Set α) : (M✶ \ X)✶ = M / X := rfl @[simp] lemma dual_delete (M : Matroid α) (X : Set α) : (M \ X)✶ = M✶ / X := by rw [← dual_dual M, dual_delete_dual, dual_dual] @[simp] lemma dual_contract (M : Matroid α) (X : Set α) : (M / X)✶ = M✶ \ X := by rw [← dual_delete_dual, dual_dual] lemma dual_contract_dual (M : Matroid α) (X : Set α) : (M✶ / X)✶ = M \ X := by simp @[simp] lemma contract_contract (M : Matroid α) (C₁ C₂ : Set α) : M / C₁ / C₂ = M / (C₁ ∪ C₂) := by simp [← dual_inj] lemma contract_comm (M : Matroid α) (C₁ C₂ : Set α) : M / C₁ / C₂ = M / C₂ / C₁ := by simp [union_comm] lemma dual_contract_delete (M : Matroid α) (X Y : Set α) : (M / X \ Y)✶ = M✶ \ X / Y := by simp lemma dual_delete_contract (M : Matroid α) (X Y : Set α) : (M \ X / Y)✶ = M✶ / X \ Y := by simp lemma contract_eq_self_iff : M / C = M ↔ Disjoint C M.E := by rw [← dual_delete_dual, ← dual_inj, dual_dual, delete_eq_self_iff, dual_ground] lemma contractElem_eq_self (he : e ∉ M.E) : M / {e} = M := by rw [← dual_delete_dual, deleteElem_eq_self (by simpa), dual_dual] @[simp] lemma contract_empty (M : Matroid α) : M / ∅ = M := by rw [← dual_delete_dual, delete_empty, dual_dual] lemma contract_contract_eq_contract_diff (M : Matroid α) (C₁ C₂ : Set α) : M / C₁ / C₂ = M / C₁ / (C₂ \ C₁) := by simp lemma contract_eq_contract_iff : M / C₁ = M / C₂ ↔ C₁ ∩ M.E = C₂ ∩ M.E := by rw [← dual_delete_dual, ← dual_delete_dual, dual_inj, delete_eq_delete_iff, dual_ground] @[simp] lemma contract_inter_ground_eq (M : Matroid α) (C : Set α) : M / (C ∩ M.E) = M / C := by rw [← dual_delete_dual, ← dual_ground, delete_inter_ground_eq, dual_delete_dual] @[aesop unsafe 10% (rule_sets := [Matroid])] lemma contract_ground_subset_ground (M : Matroid α) (C : Set α) : (M / C).E ⊆ M.E := (M.contract_ground C).trans_subset diff_subset /-! ### Independence and Coindependence -/ lemma coindep_contract_iff : (M / C).Coindep X ↔ M.Coindep X ∧ Disjoint X C := by rw [coindep_def, dual_contract, delete_indep_iff, ← coindep_def] lemma Coindep.coindep_contract_of_disjoint (hX : M.Coindep X) (hXC : Disjoint X C) : (M / C).Coindep X := coindep_contract_iff.2 ⟨hX, hXC⟩ @[simp] lemma contract_isCocircuit_iff : (M / C).IsCocircuit K ↔ M.IsCocircuit K ∧ Disjoint K C := by rw [isCocircuit_def, dual_contract, delete_isCircuit_iff] lemma Indep.contract_isBase_iff (hI : M.Indep I) : (M / I).IsBase B ↔ M.IsBase (B ∪ I) ∧ Disjoint B I := by rw [← dual_delete_dual, dual_isBase_iff', delete_ground, dual_ground, delete_isBase_iff, subset_diff, ← and_assoc, and_congr_left_iff, ← dual_dual M, dual_isBase_iff', dual_dual, dual_dual, union_comm, dual_ground, union_subset_iff, and_iff_right hI.subset_ground, and_congr_left_iff, ← isBase_restrict_iff, diff_diff, Spanning.isBase_restrict_iff, and_iff_left (diff_subset_diff_right subset_union_left)] · simp rwa [← dual_ground, ← coindep_iff_compl_spanning, dual_coindep_iff] lemma Indep.contract_indep_iff (hI : M.Indep I) : (M / I).Indep J ↔ Disjoint J I ∧ M.Indep (J ∪ I) := by simp_rw [indep_iff, hI.contract_isBase_iff, union_subset_iff] exact ⟨fun ⟨B, ⟨hBI, hdj⟩, hJB⟩ ↦ ⟨disjoint_of_subset_left hJB hdj, _, hBI, hJB.trans subset_union_left, subset_union_right⟩, fun ⟨hdj, B, hB, hJB, hIB⟩ ↦ ⟨B \ I,⟨by simpa [union_eq_self_of_subset_right hIB], disjoint_sdiff_left⟩, subset_diff.2 ⟨hJB, hdj⟩ ⟩⟩ lemma IsNonloop.contractElem_indep_iff (he : M.IsNonloop e) : (M / {e}).Indep I ↔ e ∉ I ∧ M.Indep (insert e I) := by simp [he.indep.contract_indep_iff] lemma Indep.union_indep_iff_contract_indep (hI : M.Indep I) : M.Indep (I ∪ J) ↔ (M / I).Indep (J \ I) := by rw [hI.contract_indep_iff, and_iff_right disjoint_sdiff_left, diff_union_self, union_comm] lemma Indep.diff_indep_contract_of_subset (hJ : M.Indep J) (hIJ : I ⊆ J) : (M / I).Indep (J \ I) := by rwa [← (hJ.subset hIJ).union_indep_iff_contract_indep, union_eq_self_of_subset_left hIJ] lemma Indep.contract_dep_iff (hI : M.Indep I) : (M / I).Dep J ↔ Disjoint J I ∧ M.Dep (J ∪ I) := by rw [dep_iff, hI.contract_indep_iff, dep_iff, contract_ground, subset_diff, disjoint_comm, union_subset_iff, and_iff_left hI.subset_ground] tauto /-! ### Bases -/ /-- Contracting a set is the same as contracting a basis for the set, and deleting the rest. -/ lemma IsBasis.contract_eq_contract_delete (hI : M.IsBasis I X) : M / X = M / I \ (X \ I) := by nth_rw 1 [← diff_union_of_subset hI.subset, ← dual_inj, dual_contract_delete, dual_contract, union_comm, ← delete_delete, ext_iff_indep] refine ⟨rfl, fun J hJ ↦ ?_⟩ have hss : X \ I ⊆ (M✶ \ I).coloops := fun e he ↦ by rw [← dual_contract, dual_coloops, ← IsLoop, ← singleton_dep, hI.indep.contract_dep_iff, singleton_union, and_iff_right (by simpa using he.2), hI.indep.insert_dep_iff, hI.closure_eq_closure] exact diff_subset_diff_left (M.subset_closure X) he rw [((coloops_indep _).subset hss).contract_indep_iff, delete_indep_iff, union_indep_iff_indep_of_subset_coloops hss, and_comm] lemma Indep.union_isBasis_union_of_contract_isBasis (hI : M.Indep I) (hB : (M / I).IsBasis J X) : M.IsBasis (J ∪ I) (X ∪ I) := by simp_rw [IsBasis, hI.contract_indep_iff, contract_ground, subset_diff, maximal_subset_iff, and_imp] at hB refine hB.1.1.1.2.isBasis_of_maximal_subset (union_subset_union_left _ hB.1.1.2) fun K hK hKJ hKX ↦ ?_ rw [union_subset_iff] at hKJ rw [hB.1.2 (t := K \ I) disjoint_sdiff_left (by simpa [diff_union_of_subset hKJ.2]) (diff_subset_iff.2 (by rwa [union_comm])) (subset_diff.2 ⟨hKJ.1, hB.1.1.1.1⟩), diff_union_of_subset hKJ.2] lemma IsBasis'.contract_isBasis'_diff_diff_of_subset (hIX : M.IsBasis' I X) (hJI : J ⊆ I) : (M / J).IsBasis' (I \ J) (X \ J) := by suffices ∀ ⦃K⦄, Disjoint K J → M.Indep (K ∪ J) → K ⊆ X → I ⊆ K ∪ J → K ⊆ I by simpa +contextual [IsBasis', (hIX.indep.subset hJI).contract_indep_iff, subset_diff, maximal_subset_iff, disjoint_sdiff_left, union_eq_self_of_subset_right hJI, hIX.indep, diff_subset.trans hIX.subset, diff_subset_iff, subset_antisymm_iff, union_comm J] exact fun K hJK hKJi hKX hIJK ↦ by simp [hIX.eq_of_subset_indep hKJi hIJK (union_subset hKX (hJI.trans hIX.subset))] lemma IsBasis'.contract_isBasis'_diff_of_subset (hIX : M.IsBasis' I X) (hJI : J ⊆ I) : (M / J).IsBasis' (I \ J) X := by simpa [isBasis'_iff_isBasis_inter_ground, inter_diff_assoc, ← diff_inter_distrib_right] using (hIX.contract_isBasis'_diff_diff_of_subset hJI).isBasis_inter_ground lemma IsBasis.contract_isBasis_diff_diff_of_subset (hIX : M.IsBasis I X) (hJI : J ⊆ I) : (M / J).IsBasis (I \ J) (X \ J) := by have h := (hIX.isBasis'.contract_isBasis'_diff_of_subset hJI).isBasis_inter_ground rwa [contract_ground, ← inter_diff_assoc, inter_eq_self_of_subset_left hIX.subset_ground] at h lemma IsBasis.contract_diff_isBasis_diff (hIX : M.IsBasis I X) (hJY : M.IsBasis J Y) (hIJ : I ⊆ J) : (M / I).IsBasis (J \ I) (Y \ X) := by refine (hJY.contract_isBasis_diff_diff_of_subset hIJ).isBasis_subset ?_ ?_ · rw [subset_diff, and_iff_right (diff_subset.trans hJY.subset), hIX.eq_of_subset_indep (hJY.indep.inter_right X) (subset_inter hIJ hIX.subset) inter_subset_right, diff_self_inter] exact disjoint_sdiff_left refine diff_subset_diff_right hIX.subset lemma IsBasis'.contract_isBasis_union_union (h : M.IsBasis' (J ∪ I) (X ∪ I)) (hJI : Disjoint J I) (hXI : Disjoint X I) : (M / I).IsBasis' J X := by simpa [hJI.sdiff_eq_left, hXI.sdiff_eq_left] using h.contract_isBasis'_diff_diff_of_subset subset_union_right lemma IsBasis.contract_isBasis_union_union (h : M.IsBasis (J ∪ I) (X ∪ I)) (hJI : Disjoint J I) (hXI : Disjoint X I) : (M / I).IsBasis J X := by refine (isBasis'_iff_isBasis ?_).1 <| h.isBasis'.contract_isBasis_union_union hJI hXI rw [contract_ground, subset_diff, and_iff_left hXI] exact subset_union_left.trans h.subset_ground lemma IsBasis'.contract_eq_contract_delete (hI : M.IsBasis' I X) : M / X = M / I \ (X \ I) := by rw [← contract_inter_ground_eq, hI.isBasis_inter_ground.contract_eq_contract_delete, eq_comm, ← delete_inter_ground_eq, contract_ground, diff_eq, diff_eq, ← inter_inter_distrib_right, ← diff_eq] lemma IsBasis'.contract_indep_iff (hI : M.IsBasis' I X) : (M / X).Indep J ↔ M.Indep (J ∪ I) ∧ Disjoint X J := by rw [hI.contract_eq_contract_delete, delete_indep_iff, hI.indep.contract_indep_iff, and_comm, ← and_assoc, ← disjoint_union_right, diff_union_self, union_eq_self_of_subset_right hI.subset, and_comm, disjoint_comm] lemma IsBasis.contract_indep_iff (hI : M.IsBasis I X) : (M / X).Indep J ↔ M.Indep (J ∪ I) ∧ Disjoint X J := hI.isBasis'.contract_indep_iff lemma IsBasis'.contract_dep_iff (hI : M.IsBasis' I X) {D : Set α} : (M / X).Dep D ↔ M.Dep (D ∪ I) ∧ Disjoint X D := by rw [hI.contract_eq_contract_delete, delete_dep_iff, hI.indep.contract_dep_iff, and_comm, ← and_assoc, ← disjoint_union_right, diff_union_of_subset hI.subset, disjoint_comm, and_comm] lemma IsBasis.contract_dep_iff (hI : M.IsBasis I X) {D : Set α} : (M / X).Dep D ↔ M.Dep (D ∪ I) ∧ Disjoint X D := hI.isBasis'.contract_dep_iff lemma IsBasis.contract_indep_iff_of_disjoint (hI : M.IsBasis I X) (hdj : Disjoint X J) : (M / X).Indep J ↔ M.Indep (J ∪ I) := by rw [hI.contract_indep_iff, and_iff_left hdj] lemma IsBasis.contract_indep_diff_iff (hI : M.IsBasis I X) : (M / X).Indep (J \ X) ↔ M.Indep ((J \ X) ∪ I) := by rw [hI.contract_indep_iff, and_iff_left disjoint_sdiff_right] lemma IsBasis'.contract_indep_diff_iff (hI : M.IsBasis' I X) : (M / X).Indep (J \ X) ↔ M.Indep ((J \ X) ∪ I) := by rw [hI.contract_indep_iff, and_iff_left disjoint_sdiff_right] lemma IsBasis.contract_isBasis_of_isBasis' (h : M.IsBasis I X) (hJC : M.IsBasis' J C) (h_ind : M.Indep (I \ C ∪ J)) : (M / C).IsBasis (I \ C) (X \ C) := by have hIX := h.subset have hJCss := hJC.subset rw [hJC.contract_eq_contract_delete, delete_isBasis_iff] refine ⟨contract_isBasis_union_union (h_ind.isBasis_of_subset_of_subset_closure ?_ ?_) ?_ ?_, ?_⟩ rotate_left · rw [closure_union_congr_right hJC.closure_eq_closure, diff_union_self, closure_union_congr_left h.closure_eq_closure] exact subset_closure_of_subset' _ (by tauto_set) (union_subset (diff_subset.trans h.subset_ground) hJC.indep.subset_ground) all_goals tauto_set lemma IsBasis'.contract_isBasis' (h : M.IsBasis' I X) (hJC : M.IsBasis' J C) (h_ind : M.Indep (I \ C ∪ J)) : (M / C).IsBasis' (I \ C) (X \ C) := by rw [isBasis'_iff_isBasis_inter_ground, contract_ground, ← diff_inter_distrib_right] exact h.isBasis_inter_ground.contract_isBasis_of_isBasis' hJC h_ind lemma IsBasis.contract_isBasis (h : M.IsBasis I X) (hJC : M.IsBasis J C) (h_ind : M.Indep (I \ C ∪ J)) : (M / C).IsBasis (I \ C) (X \ C) := h.contract_isBasis_of_isBasis' hJC.isBasis' h_ind lemma IsBasis.contract_isBasis_of_disjoint (h : M.IsBasis I X) (hJC : M.IsBasis J C) (hdj : Disjoint C X) (h_ind : M.Indep (I ∪ J)) : (M / C).IsBasis I X := by have h' := h.contract_isBasis hJC rwa [(hdj.mono_right h.subset).sdiff_eq_right, hdj.sdiff_eq_right, imp_iff_right h_ind] at h' lemma IsBasis'.contract_isBasis_of_indep (h : M.IsBasis' I X) (h_ind : M.Indep (I ∪ J)) : (M / J).IsBasis' (I \ J) (X \ J) := h.contract_isBasis' (h_ind.subset subset_union_right).isBasis_self.isBasis' (by simpa) lemma IsBasis.contract_isBasis_of_indep (h : M.IsBasis I X) (h_ind : M.Indep (I ∪ J)) : (M / J).IsBasis (I \ J) (X \ J) := h.contract_isBasis (h_ind.subset subset_union_right).isBasis_self (by simpa) lemma IsBasis.contract_isBasis_of_disjoint_indep (h : M.IsBasis I X) (hdj : Disjoint J X) (h_ind : M.Indep (I ∪ J)) : (M / J).IsBasis I X := by rw [← hdj.sdiff_eq_right, ← (hdj.mono_right h.subset).sdiff_eq_right] exact h.contract_isBasis_of_indep h_ind lemma Indep.of_contract (hI : (M / C).Indep I) : M.Indep I := ((M.exists_isBasis' C).choose_spec.contract_indep_iff.1 hI).1.subset subset_union_left lemma Dep.of_contract (h : (M / C).Dep X) (hC : C ⊆ M.E := by aesop_mat) : M.Dep (C ∪ X) := by rw [Dep, and_iff_left (union_subset hC (h.subset_ground.trans diff_subset))] intro hi rw [Dep, (hi.subset subset_union_left).contract_indep_iff, union_comm, and_iff_left hi] at h exact h.1 (subset_diff.1 h.2).2 /-! ### Finiteness -/ instance contract_finite [M.Finite] : (M / C).Finite := by rw [← dual_delete_dual] infer_instance instance contract_rankFinite [RankFinite M] : RankFinite (M / C) := let ⟨B, hB⟩ := (M / C).exists_isBase ⟨B, hB, hB.indep.of_contract.finite⟩ instance contract_finitary [Finitary M] : Finitary (M / C) := by obtain ⟨J, hJ⟩ := M.exists_isBasis' C suffices (M / J).Finitary by rw [hJ.contract_eq_contract_delete] infer_instance exact ⟨fun I hI ↦ hJ.indep.contract_indep_iff.2 ⟨disjoint_left.2 fun e heI ↦ ((hI {e} (by simpa) (by simp)).subset_ground rfl).2, indep_of_forall_finite_subset_indep _ fun K hK hKfin ↦ (hJ.indep.contract_indep_iff.1 <| hI (K ∩ I) inter_subset_right (hKfin.inter_of_left _)).2.subset (by tauto_set)⟩⟩ /-! ### Loops and Coloops -/ lemma contract_eq_delete_of_subset_loops (hX : X ⊆ M.loops) : M / X = M \ X := by simp [(empty_isBasis_iff.2 hX).contract_eq_contract_delete] lemma contract_eq_delete_of_subset_coloops (hX : X ⊆ M.coloops) : M / X = M \ X := by rw [← dual_inj, dual_delete, contract_eq_delete_of_subset_loops hX, dual_contract] @[simp] lemma contract_isLoop_iff_mem_closure : (M / C).IsLoop e ↔ e ∈ M.closure C ∧ e ∉ C := by obtain ⟨I, hI⟩ := M.exists_isBasis' C rw [hI.contract_eq_contract_delete, delete_isLoop_iff, ← singleton_dep, hI.indep.contract_dep_iff, singleton_union, hI.indep.insert_dep_iff, hI.closure_eq_closure] by_cases heI : e ∈ I · simp [heI, hI.subset heI] simp [heI, and_comm] @[simp] lemma contract_loops_eq (M : Matroid α) (C : Set α) : (M / C).loops = M.closure C \ C := by simp [Set.ext_iff, ← isLoop_iff, contract_isLoop_iff_mem_closure] @[simp] lemma contract_coloops_eq (M : Matroid α) (C : Set α) : (M / C).coloops = M.coloops \ C := by rw [← dual_delete_dual, dual_coloops, delete_loops_eq, dual_loops] @[simp] lemma contract_isColoop_iff : (M / C).IsColoop e ↔ M.IsColoop e ∧ e ∉ C := by simp [isColoop_iff_mem_coloops] lemma IsNonloop.of_contract (h : (M / C).IsNonloop e) : M.IsNonloop e := by rw [← indep_singleton] at h ⊢ exact h.of_contract @[simp] lemma contract_isNonloop_iff : (M / C).IsNonloop e ↔ e ∈ M.E \ M.closure C := by rw [isNonloop_iff_mem_compl_loops, contract_ground, contract_loops_eq] refine ⟨fun ⟨he,heC⟩ ↦ ⟨he.1, fun h ↦ heC ⟨h, he.2⟩⟩, fun h ↦ ⟨⟨h.1, fun heC ↦ h.2 ?_⟩, fun h' ↦ h.2 h'.1⟩⟩ rw [← closure_inter_ground] exact (M.subset_closure (C ∩ M.E)) ⟨heC, h.1⟩ lemma IsBasis.diff_subset_loops_contract (hIX : M.IsBasis I X) : X \ I ⊆ (M / I).loops := by rw [diff_subset_iff, contract_loops_eq, union_diff_self, union_eq_self_of_subset_left (M.subset_closure I)] exact hIX.subset_closure /-! ### Closure -/ /-- Contracting the closure of a set is the same as contracting the set, and then deleting the rest of its elements. -/ lemma contract_closure_eq_contract_delete (M : Matroid α) (C : Set α) : M / M.closure C = M / C \ (M.closure C \ C) := by wlog hCE : C ⊆ M.E with aux · rw [← M.contract_inter_ground_eq C, ← closure_inter_ground, aux _ _ inter_subset_right, diff_inter, diff_eq_empty.2 (M.closure_subset_ground _), union_empty] obtain ⟨I, hI⟩ := M.exists_isBasis C rw [hI.isBasis_closure_right.contract_eq_contract_delete, hI.contract_eq_contract_delete, delete_delete, union_comm, diff_union_diff_cancel (M.subset_closure C) hI.subset] @[simp] lemma contract_closure_eq (M : Matroid α) (C X : Set α) : (M / C).closure X = M.closure (X ∪ C) \ C := by rw [← diff_union_inter (M.closure (X ∪ C) \ C) X, diff_diff, union_comm C, ← contract_loops_eq, union_comm X, ← contract_contract, contract_loops_eq, subset_antisymm_iff, union_subset_iff, and_iff_right diff_subset, ← diff_subset_iff] simp only [sdiff_sdiff_right_self, inf_eq_inter, subset_inter_iff, inter_subset_right, and_true] refine ⟨fun e ⟨he, he'⟩ ↦ ⟨mem_closure_of_mem' _ (.inr he') (mem_ground_of_mem_closure he).1, (closure_subset_ground _ _ he).2⟩, fun e ⟨⟨he, heC⟩, he'⟩ ↦ mem_closure_of_mem' _ he' ⟨M.closure_subset_ground _ he, heC⟩⟩ lemma contract_spanning_iff (hC : C ⊆ M.E := by aesop_mat) : (M / C).Spanning X ↔ M.Spanning (X ∪ C) ∧ Disjoint X C := by rw [spanning_iff, contract_closure_eq, contract_ground, spanning_iff, union_subset_iff, subset_diff, ← and_assoc, and_congr_left_iff, and_comm (a := X ⊆ _), ← and_assoc, and_congr_left_iff] refine fun hdj hX ↦ ⟨fun h ↦ ⟨?_, hC⟩, fun h ↦ by simp [h]⟩ rwa [← union_diff_cancel (M.subset_closure_of_subset' subset_union_right hC), h, union_diff_cancel] /-- A version of `Matroid.contract_spanning_iff` without the supportedness hypothesis. -/ lemma contract_spanning_iff' : (M / C).Spanning X ↔ M.Spanning (X ∪ (C ∩ M.E)) ∧ Disjoint X C := by rw [← contract_inter_ground_eq, contract_spanning_iff, and_congr_right_iff] refine fun h ↦ ⟨fun hdj ↦ ?_, Disjoint.mono_right inter_subset_left⟩ rw [← diff_union_inter C M.E, disjoint_union_right, and_iff_left hdj] exact disjoint_sdiff_right.mono_left (subset_union_left.trans h.subset_ground) lemma Spanning.contract (hX : M.Spanning X) (C : Set α) : (M / C).Spanning (X \ C) := by have hXE := hX.subset_ground rw [contract_spanning_iff', and_iff_left disjoint_sdiff_left] exact hX.superset (by tauto_set) (by tauto_set) lemma Spanning.contract_eq_loopyOn (hX : M.Spanning X) : M / X = loopyOn (M.E \ X) := by rw [eq_loopyOn_iff_loops_eq] simp [hX.closure_eq] /-! ### Circuits -/ lemma IsCircuit.contract_isCircuit (hK : M.IsCircuit K) (hC : C ⊂ K) : (M / C).IsCircuit (K \ C) := by suffices ∀ e ∈ K, e ∉ C → M.Indep (K \ {e} ∪ C) by simpa [isCircuit_iff_dep_forall_diff_singleton_indep, diff_diff_comm (s := K) (t := C), dep_iff, (hK.ssubset_indep hC).contract_indep_iff, diff_subset_diff_left hK.subset_ground, disjoint_sdiff_left, diff_union_of_subset hC.subset, hK.not_indep] exact fun e heK heC ↦ (hK.diff_singleton_indep heK).subset <| by simp [subset_diff_singleton hC.subset heC] lemma IsCircuit.contractElem_isCircuit (hC : M.IsCircuit C) (hnt : C.Nontrivial) (heC : e ∈ C) : (M / {e}).IsCircuit (C \ {e}) := hC.contract_isCircuit (ssubset_of_ne_of_subset hnt.ne_singleton.symm (by simpa)) lemma IsCircuit.contract_dep (hK : M.IsCircuit K) (hCK : Disjoint C K) : (M / C).Dep K := by obtain ⟨I, hI⟩ := M.exists_isBasis (C ∩ M.E) rw [← contract_inter_ground_eq, Dep, hI.contract_indep_iff, and_iff_left (hCK.mono_left inter_subset_left), contract_ground, subset_diff, and_iff_left (hCK.symm.mono_right inter_subset_left), and_iff_left hK.subset_ground] exact fun hi ↦ hK.dep.not_indep (hi.subset subset_union_left) lemma IsCircuit.contract_dep_of_not_subset (hK : M.IsCircuit K) {C : Set α} (hKC : ¬ K ⊆ C) : (M / C).Dep (K \ C) := by have h' := hK.contract_isCircuit (C := C ∩ K) (inter_subset_right.ssubset_of_ne (by simpa)) simp only [diff_inter_self_eq_diff] at h' have hwin := h'.contract_dep (C := C \ K) disjoint_sdiff_sdiff rwa [contract_contract, inter_union_diff] at hwin lemma IsCircuit.contract_diff_isCircuit (hC : M.IsCircuit C) (hK : K.Nonempty) (hKC : K ⊆ C) : (M / (C \ K)).IsCircuit K := by simpa [inter_eq_self_of_subset_right hKC] using hC.contract_isCircuit (C := C \ K) <| by rwa [diff_ssubset_left_iff, inter_eq_self_of_subset_right hKC] /-- If `C` is a circuit of `M / K`, then `M` has a circuit in the interval `[C, C ∪ K]`. -/ lemma IsCircuit.exists_subset_isCircuit_of_contract (hC : (M / K).IsCircuit C) : ∃ C', M.IsCircuit C' ∧ C ⊆ C' ∧ C' ⊆ C ∪ K := by wlog hKi : M.Indep K generalizing K with aux · obtain ⟨I, hI⟩ := M.exists_isBasis' K rw [hI.contract_eq_contract_delete, delete_isCircuit_iff] at hC obtain ⟨C', hC', hCC', hC'ss⟩ := aux hC.1 hI.indep exact ⟨C', hC', hCC', hC'ss.trans (union_subset_union_right _ hI.subset)⟩ obtain ⟨hCE : C ⊆ M.E, hCK : Disjoint C K⟩ := subset_diff.1 hC.subset_ground obtain ⟨C', hC'ss, hC'⟩ := (hKi.contract_dep_iff.1 hC.dep).2.exists_isCircuit_subset refine ⟨C', hC', ?_, hC'ss⟩ have hdep2 : (M / K).Dep (C' \ K) := by rw [hKi.contract_dep_iff, and_iff_right disjoint_sdiff_left] refine hC'.dep.superset (by simp) rw [← (hC.eq_of_dep_subset hdep2 (diff_subset_iff.2 (union_comm _ _ ▸ hC'ss)))] exact diff_subset lemma IsCocircuit.of_contract (hK : (M / C).IsCocircuit K) : M.IsCocircuit K := by rw [isCocircuit_def, dual_contract] at hK exact hK.of_delete lemma IsCocircuit.delete_isCocircuit {D : Set α} (hK : M.IsCocircuit K) (hD : D ⊂ K) : (M \ D).IsCocircuit (K \ D) := by rw [isCocircuit_def, dual_delete] exact hK.isCircuit.contract_isCircuit hD lemma IsCocircuit.delete_diff_isCocircuit {X : Set α} (hK : M.IsCocircuit K) (hXK : X ⊆ K) (hX : X.Nonempty) : (M \ (K \ X)).IsCocircuit X := by rw [isCocircuit_def, dual_delete] exact hK.isCircuit.contract_diff_isCircuit hX hXK /-! ### Commutativity -/ lemma contract_delete_diff (M : Matroid α) (C D : Set α) : M / C \ D = M / C \ (D \ C) := by rw [delete_eq_delete_iff, contract_ground, diff_eq, diff_eq, ← inter_inter_distrib_right, inter_assoc] lemma contract_restrict_eq_restrict_contract (M : Matroid α) (h : Disjoint C R) : (M / C) ↾ R = (M ↾ (R ∪ C)) / C := by refine ext_indep (by simp [h.sdiff_eq_right]) fun I (hI : I ⊆ R) ↦ ?_ obtain ⟨J, hJ⟩ := (M ↾ (R ∪ C)).exists_isBasis' C have hJ' : M.IsBasis' J C := by simpa [inter_eq_self_of_subset_left subset_union_right] using (isBasis'_restrict_iff.1 hJ).1 rw [restrict_indep_iff, hJ.contract_indep_iff, hJ'.contract_indep_iff, restrict_indep_iff] have hJC := hJ'.subset tauto_set lemma restrict_contract_eq_contract_restrict (M : Matroid α) (hCR : C ⊆ R) : (M ↾ R) / C = (M / C) ↾ (R \ C) := by rw [contract_restrict_eq_restrict_contract _ disjoint_sdiff_right] simp [union_eq_self_of_subset_right hCR] /-- Contraction and deletion commute for disjoint sets. -/ lemma contract_delete_comm (M : Matroid α) (hCD : Disjoint C D) : M / C \ D = M \ D / C := by wlog hCE : C ⊆ M.E generalizing C with aux · rw [← contract_inter_ground_eq, aux (hCD.mono_left inter_subset_left) inter_subset_right, contract_eq_contract_iff, inter_assoc, delete_ground, inter_eq_self_of_subset_right diff_subset] rw [delete_eq_restrict, delete_eq_restrict, contract_ground, diff_diff_comm, restrict_contract_eq_contract_restrict _ (by simpa [hCE, subset_diff])] /-- A version of `contract_delete_comm` without the disjointness hypothesis, and hence a less simple RHS. -/ lemma contract_delete_comm' (M : Matroid α) (C D : Set α) : M / C \ D = M \ (D \ C) / C := by rw [contract_delete_diff, contract_delete_comm _ disjoint_sdiff_right] lemma delete_contract_eq_diff (M : Matroid α) (D C : Set α) : M \ D / C = M \ D / (C \ D) := by rw [contract_eq_contract_iff, delete_ground, ← diff_inter_distrib_right, diff_eq, diff_eq, inter_assoc] /-- A version of `delete_contract_comm'` without the disjointness hypothesis, and hence a less simple RHS. -/ lemma delete_contract_comm' (M : Matroid α) (D C : Set α) : M \ D / C = M / (C \ D) \ D := by rw [delete_contract_eq_diff, ← contract_delete_comm _ disjoint_sdiff_left] /-- A version of `contract_delete_contract` without the disjointness hypothesis, and hence a less simple RHS. -/ lemma contract_delete_contract' (M : Matroid α) (C D C' : Set α) : M / C \ D / C' = M / (C ∪ C' \ D) \ D := by rw [delete_contract_eq_diff, ← contract_delete_comm _ disjoint_sdiff_left, contract_contract] lemma contract_delete_contract (M : Matroid α) (C D C' : Set α) (h : Disjoint C' D) : M / C \ D / C' = M / (C ∪ C') \ D := by rw [contract_delete_contract', sdiff_eq_left.mpr h] /-- A version of `contract_delete_contract_delete` without the disjointness hypothesis, and hence a less simple RHS. -/ lemma contract_delete_contract_delete' (M : Matroid α) (C D C' D' : Set α) : M / C \ D / C' \ D' = M / (C ∪ C' \ D) \ (D ∪ D') := by rw [contract_delete_contract', delete_delete] lemma contract_delete_contract_delete (M : Matroid α) (C D C' D' : Set α) (h : Disjoint C' D) : M / C \ D / C' \ D' = M / (C ∪ C') \ (D ∪ D') := by rw [contract_delete_contract_delete', sdiff_eq_left.mpr h] /-- A version of `delete_contract_delete` without the disjointness hypothesis, and hence a less simple RHS. -/ lemma delete_contract_delete' (M : Matroid α) (D C D' : Set α) : M \ D / C \ D' = M / (C \ D) \ (D ∪ D') := by rw [delete_contract_comm', delete_delete] lemma delete_contract_delete (M : Matroid α) (D C D' : Set α) (h : Disjoint C D) : M \ D / C \ D' = M / C \ (D ∪ D') := by rw [delete_contract_delete', sdiff_eq_left.mpr h] end Contract end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/Matroid/Minor/Delete.lean
import Mathlib.Combinatorics.Matroid.Loop /-! # Matroid Deletion For `M : Matroid α` and `X : Set α`, the *deletion* of `X` from `M` is the matroid `M \ X` with ground set `M.E \ X`, in which a subset of `M.E \ X` is independent if and only if it is independent in `M`. The deletion `M \ X` is equal to the restriction `M ↾ (M.E \ X)`, but is of special importance in the theory because it is the dual notion of *contraction*, and thus plays a more central and natural role than restriction in many contexts. Because of the implementation of the restriction `M ↾ R` allowing `R` to not be a subset of `M.E`, the relation `M ↾ R ≤r M` holds only with the assumption `R ⊆ M.E`, whereas `M \ D`, being defined as `M ↾ (M.E \ D)`, satisfies `M \ D ≤r M` unconditionally. This is often quite convenient. ## Main Declarations * `Matroid.delete M D`, written `M \ D`, is the restriction of `M` to the set `M.E \ D`, or equivalently the matroid on `M.E \ D` whose independent sets are the `M`-independent sets. ## Naming conventions We use the abbreviation `deleteElem` in lemma names to refer to the deletion `M \ {e}` of a single element `e : α` from `M : Matroid α`. -/ open Set variable {α : Type*} {M M' N : Matroid α} {e f : α} {I B D R X : Set α} namespace Matroid /-! ## Deletion -/ section Delete /-- The deletion `M \ D` is the restriction of a matroid `M` to `M.E \ D`. Its independent sets are the `M`-independent subsets of `M.E \ D`. -/ def delete (M : Matroid α) (D : Set α) : Matroid α := M ↾ (M.E \ D) /-- `M \ D` refers to the deletion of a set `D` from the matroid `M`. -/ scoped infixl:75 " \ " => Matroid.delete lemma delete_eq_restrict (M : Matroid α) (D : Set α) : M \ D = M ↾ (M.E \ D) := rfl lemma restrict_compl (M : Matroid α) (D : Set α) : M ↾ (M.E \ D) = M \ D := rfl @[simp] lemma delete_compl (hR : R ⊆ M.E := by aesop_mat) : M \ (M.E \ R) = M ↾ R := by rw [← restrict_compl, diff_diff_cancel_left hR] @[simp] lemma delete_isRestriction (M : Matroid α) (D : Set α) : M \ D ≤r M := restrict_isRestriction _ _ diff_subset lemma IsRestriction.exists_eq_delete (hNM : N ≤r M) : ∃ D ⊆ M.E, N = M \ D := ⟨M.E \ N.E, diff_subset, by obtain ⟨R, hR, rfl⟩ := hNM; rw [delete_compl, restrict_ground_eq]⟩ lemma isRestriction_iff_exists_eq_delete : N ≤r M ↔ ∃ D ⊆ M.E, N = M \ D := ⟨IsRestriction.exists_eq_delete, by rintro ⟨D, -, rfl⟩; apply delete_isRestriction⟩ @[simp] lemma delete_ground (M : Matroid α) (D : Set α) : (M \ D).E = M.E \ D := rfl @[aesop unsafe 10% (rule_sets := [Matroid])] lemma delete_subset_ground (M : Matroid α) (D : Set α) : (M \ D).E ⊆ M.E := diff_subset @[simp] lemma delete_eq_self_iff : M \ D = M ↔ Disjoint D M.E := by rw [← restrict_compl, restrict_eq_self_iff, sdiff_eq_left, disjoint_comm] alias ⟨_, delete_eq_self⟩ := delete_eq_self_iff lemma deleteElem_eq_self (he : e ∉ M.E) : M \ {e} = M := by simpa @[simp] lemma delete_delete (M : Matroid α) (D₁ D₂ : Set α) : M \ D₁ \ D₂ = M \ (D₁ ∪ D₂) := by rw [← restrict_compl, ← restrict_compl, ← restrict_compl, restrict_restrict_eq, restrict_ground_eq, diff_diff] simp [diff_subset] lemma delete_comm (M : Matroid α) (D₁ D₂ : Set α) : M \ D₁ \ D₂ = M \ D₂ \ D₁ := by rw [delete_delete, union_comm, delete_delete] lemma delete_inter_ground_eq (M : Matroid α) (D : Set α) : M \ (D ∩ M.E) = M \ D := by rw [← restrict_compl, ← restrict_compl, diff_inter_self_eq_diff] lemma delete_eq_delete_iff {D₁ D₂ : Set α} : M \ D₁ = M \ D₂ ↔ D₁ ∩ M.E = D₂ ∩ M.E := by rw [← delete_inter_ground_eq, ← M.delete_inter_ground_eq D₂] refine ⟨fun h ↦ ?_, fun h ↦ by rw [h]⟩ apply_fun (M.E \ Matroid.E ·) at h simp_rw [delete_ground, diff_diff_cancel_left inter_subset_right] at h assumption @[simp] lemma delete_empty (M : Matroid α) : M \ ∅ = M := by rw [delete_eq_self_iff] exact empty_disjoint _ lemma delete_delete_eq_delete_diff (M : Matroid α) (D₁ D₂ : Set α) : M \ D₁ \ D₂ = M \ D₁ \ (D₂ \ D₁) := by simp lemma IsRestriction.restrict_delete_of_disjoint (h : N ≤r M) (hX : Disjoint X N.E) : N ≤r (M \ X) := by obtain ⟨D, hD, rfl⟩ := isRestriction_iff_exists_eq_delete.1 h refine isRestriction_iff_exists_eq_delete.2 ⟨D \ X, diff_subset_diff_left hD, ?_⟩ rwa [delete_delete, union_diff_self, union_comm, ← delete_delete, eq_comm, delete_eq_self_iff] lemma IsRestriction.isRestriction_deleteElem (h : N ≤r M) (he : e ∉ N.E) : N ≤r M \ {e} := h.restrict_delete_of_disjoint (by simpa) /-! ### Independence and Bases -/ @[simp] lemma delete_indep_iff : (M \ D).Indep I ↔ M.Indep I ∧ Disjoint I D := by rw [← restrict_compl, restrict_indep_iff, subset_diff, ← and_assoc, and_iff_left_of_imp Indep.subset_ground] lemma deleteElem_indep_iff : (M \ {e}).Indep I ↔ M.Indep I ∧ e ∉ I := by simp lemma Indep.of_delete (h : (M \ D).Indep I) : M.Indep I := (delete_indep_iff.mp h).1 lemma Indep.indep_delete_of_disjoint (h : M.Indep I) (hID : Disjoint I D) : (M \ D).Indep I := delete_indep_iff.mpr ⟨h, hID⟩ lemma indep_iff_delete_of_disjoint (hID : Disjoint I D) : M.Indep I ↔ (M \ D).Indep I := ⟨fun h ↦ h.indep_delete_of_disjoint hID, fun h ↦ h.of_delete⟩ @[simp] lemma delete_dep_iff : (M \ D).Dep X ↔ M.Dep X ∧ Disjoint X D := by rw [dep_iff, dep_iff, delete_indep_iff, delete_ground, subset_diff]; tauto @[simp] lemma delete_isBase_iff : (M \ D).IsBase B ↔ M.IsBasis B (M.E \ D) := by rw [← restrict_compl, isBase_restrict_iff] @[simp] lemma delete_isBasis_iff : (M \ D).IsBasis I X ↔ M.IsBasis I X ∧ Disjoint X D := by rw [← restrict_compl, isBasis_restrict_iff, subset_diff, ← and_assoc, and_iff_left_of_imp IsBasis.subset_ground] @[simp] lemma delete_isBasis'_iff : (M \ D).IsBasis' I X ↔ M.IsBasis' I (X \ D) := by rw [isBasis'_iff_isBasis_inter_ground, delete_isBasis_iff, delete_ground, diff_eq, inter_comm M.E, ← inter_assoc, ← diff_eq, ← isBasis'_iff_isBasis_inter_ground, and_iff_left_iff_imp, inter_comm, ← inter_diff_assoc] exact fun _ ↦ disjoint_sdiff_left lemma IsBasis.of_delete (h : (M \ D).IsBasis I X) : M.IsBasis I X := (delete_isBasis_iff.mp h).1 lemma IsBasis.delete (h : M.IsBasis I X) (hX : Disjoint X D) : (M \ D).IsBasis I X := by rw [delete_isBasis_iff]; exact ⟨h, hX⟩ lemma Coindep.delete_isBase_iff (hD : M.Coindep D) : (M \ D).IsBase B ↔ M.IsBase B ∧ Disjoint B D := by rw [Matroid.delete_isBase_iff] refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · have hss := h.subset rw [subset_diff] at hss have hcl := h.isBasis_closure_right rw [hD.closure_compl, isBasis_ground_iff] at hcl exact ⟨hcl, hss.2⟩ exact h.1.isBasis_ground.isBasis_subset (by simp [subset_diff, h.1.subset_ground, h.2]) diff_subset lemma Coindep.delete_rankPos [M.RankPos] (hD : M.Coindep D) : (M \ D).RankPos := by rw [rankPos_iff, hD.delete_isBase_iff] simp [M.empty_not_isBase] lemma Coindep.delete_spanning_iff {S : Set α} (hD : M.Coindep D) : (M \ D).Spanning S ↔ M.Spanning S ∧ Disjoint S D := by simp only [spanning_iff_exists_isBase_subset', hD.delete_isBase_iff, and_assoc, delete_ground, subset_diff, and_congr_left_iff, and_imp] refine fun hSE hSD ↦ ⟨fun ⟨B, hB, hBD, hBS⟩ ↦ ⟨B, hB, hBS⟩, fun ⟨B, hB, hBS⟩ ↦ ⟨B, hB, ?_, hBS⟩⟩ exact hSD.mono_left hBS /-! ### Loops, circuits and closure -/ @[simp] lemma delete_isLoop_iff : (M \ D).IsLoop e ↔ M.IsLoop e ∧ e ∉ D := by rw [← singleton_dep, delete_dep_iff, disjoint_singleton_left, singleton_dep] @[simp] lemma delete_isNonloop_iff : (M \ D).IsNonloop e ↔ M.IsNonloop e ∧ e ∉ D := by rw [← indep_singleton, delete_indep_iff, disjoint_singleton_left, indep_singleton] lemma IsNonloop.of_delete (h : (M \ D).IsNonloop e) : M.IsNonloop e := (delete_isNonloop_iff.1 h).1 lemma isNonloop_iff_delete_of_notMem (he : e ∉ D) : M.IsNonloop e ↔ (M \ D).IsNonloop e := ⟨fun h ↦ delete_isNonloop_iff.2 ⟨h, he⟩, fun h ↦ h.of_delete⟩ @[deprecated (since := "2025-05-23")] alias isNonloop_iff_delete_of_not_mem := isNonloop_iff_delete_of_notMem lemma delete_loops_eq_removeLoops (M : Matroid α) : M \ M.loops = M.removeLoops := by rw [removeLoops, delete_eq_restrict, compl_loops_eq] @[simp] lemma delete_isCircuit_iff {C : Set α} : (M \ D).IsCircuit C ↔ M.IsCircuit C ∧ Disjoint C D := by rw [delete_eq_restrict, restrict_isCircuit_iff, and_congr_right_iff, subset_diff, and_iff_right_iff_imp] exact fun h _ ↦ h.subset_ground lemma IsCircuit.of_delete {C : Set α} (h : (M \ D).IsCircuit C) : M.IsCircuit C := (delete_isCircuit_iff.1 h).1 lemma circuit_iff_delete_of_disjoint {C : Set α} (hCD : Disjoint C D) : M.IsCircuit C ↔ (M \ D).IsCircuit C := ⟨fun h ↦ delete_isCircuit_iff.2 ⟨h, hCD⟩, fun h ↦ h.of_delete⟩ @[simp] lemma delete_closure_eq (M : Matroid α) (D X : Set α) : (M \ D).closure X = M.closure (X \ D) \ D := by rw [← restrict_compl, restrict_closure_eq', sdiff_sdiff_self, bot_eq_empty, union_empty, diff_eq, inter_comm M.E, ← inter_assoc X, ← diff_eq, closure_inter_ground, ← inter_assoc, ← diff_eq, inter_eq_left] exact diff_subset.trans (M.closure_subset_ground _) lemma delete_closure_eq_of_disjoint (M : Matroid α) {D X : Set α} (hXD : Disjoint X D) : (M \ D).closure X = M.closure X \ D := by rw [delete_closure_eq, hXD.sdiff_eq_left] @[simp] lemma delete_loops_eq (M : Matroid α) (D : Set α) : (M \ D).loops = M.loops \ D := by simp [loops] lemma delete_isColoop_iff (M : Matroid α) (D : Set α) : (M \ D).IsColoop e ↔ e ∉ M.closure ((M.E \ D) \ {e}) ∧ e ∈ M.E ∧ e ∉ D := by rw [delete_eq_restrict, restrict_isColoop_iff diff_subset, mem_diff, and_congr_left_iff, and_imp] simp /-! ### Finiteness -/ instance delete_finitary (M : Matroid α) [Finitary M] (D : Set α) : Finitary (M \ D) := inferInstanceAs <| Finitary (M ↾ (M.E \ D)) instance delete_finite [M.Finite] : (M \ D).Finite := ⟨M.ground_finite.diff⟩ instance delete_rankFinite [RankFinite M] : RankFinite (M \ D) := restrict_rankFinite _ end Delete end Matroid
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Paths.lean
import Mathlib.Combinatorics.SimpleGraph.Connectivity.WalkDecomp import Mathlib.Combinatorics.SimpleGraph.Walk /-! # Trail, Path, and Cycle In a simple graph, * A *trail* is a walk whose edges each appear no more than once. * A *circuit* is a nonempty trail whose first and last vertices are the same. * A *path* is a trail whose vertices appear no more than once. * A *cycle* is a nonempty trail whose first and last vertices are the same and whose vertices except for the first appear no more than once. **Warning:** graph theorists mean something different by "path" than do homotopy theorists. A "walk" in graph theory is a "path" in homotopy theory. Another warning: some graph theorists use "path" and "simple path" for "walk" and "path." Some definitions and theorems have inspiration from multigraph counterparts in [Chou1994]. ## Main definitions * `SimpleGraph.Walk.IsTrail`, `SimpleGraph.Walk.IsPath`, and `SimpleGraph.Walk.IsCycle`. * `SimpleGraph.Path` * `SimpleGraph.Path.map` for the induced map on paths, given an (injective) graph homomorphism. ## Tags trails, paths, circuits, cycles -/ open Function universe u v w namespace SimpleGraph variable {V : Type u} {V' : Type v} variable (G : SimpleGraph V) (G' : SimpleGraph V') namespace Walk variable {G} {u v w : V} /-! ### Trails, paths, circuits, cycles -/ /-- A *trail* is a walk with no repeating edges. -/ @[mk_iff isTrail_def] structure IsTrail {u v : V} (p : G.Walk u v) : Prop where edges_nodup : p.edges.Nodup /-- A *path* is a walk with no repeating vertices. Use `SimpleGraph.Walk.IsPath.mk'` for a simpler constructor. -/ structure IsPath {u v : V} (p : G.Walk u v) : Prop extends isTrail : IsTrail p where support_nodup : p.support.Nodup /-- A *circuit* at `u : V` is a nonempty trail beginning and ending at `u`. -/ @[mk_iff isCircuit_def] structure IsCircuit {u : V} (p : G.Walk u u) : Prop extends isTrail : IsTrail p where ne_nil : p ≠ nil /-- A *cycle* at `u : V` is a circuit at `u` whose only repeating vertex is `u` (which appears exactly twice). -/ structure IsCycle {u : V} (p : G.Walk u u) : Prop extends isCircuit : IsCircuit p where support_nodup : p.support.tail.Nodup @[deprecated (since := "2025-08-26")] protected alias IsPath.toIsTrail := IsPath.isTrail @[deprecated (since := "2025-08-26")] protected alias IsCircuit.toIsTrail := IsCircuit.isTrail @[deprecated (since := "2025-08-26")] protected alias IsCycle.toIsCircuit := IsCycle.isCircuit @[simp] theorem isTrail_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).IsTrail ↔ p.IsTrail := by subst_vars rfl theorem IsPath.mk' {u v : V} {p : G.Walk u v} (h : p.support.Nodup) : p.IsPath := ⟨⟨edges_nodup_of_support_nodup h⟩, h⟩ theorem isPath_def {u v : V} (p : G.Walk u v) : p.IsPath ↔ p.support.Nodup := ⟨IsPath.support_nodup, IsPath.mk'⟩ theorem isPath_iff_injective_get_support {u v : V} (p : G.Walk u v) : p.IsPath ↔ (p.support.get ·).Injective := p.isPath_def.trans List.nodup_iff_injective_get @[simp] theorem isPath_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).IsPath ↔ p.IsPath := by subst_vars rfl @[simp] theorem isCircuit_copy {u u'} (p : G.Walk u u) (hu : u = u') : (p.copy hu hu).IsCircuit ↔ p.IsCircuit := by subst_vars rfl lemma IsCircuit.not_nil {p : G.Walk v v} (hp : IsCircuit p) : ¬ p.Nil := (hp.ne_nil ·.eq_nil) theorem isCycle_def {u : V} (p : G.Walk u u) : p.IsCycle ↔ p.IsTrail ∧ p ≠ nil ∧ p.support.tail.Nodup := Iff.intro (fun h => ⟨h.1.1, h.1.2, h.2⟩) fun h => ⟨⟨h.1, h.2.1⟩, h.2.2⟩ @[simp] theorem isCycle_copy {u u'} (p : G.Walk u u) (hu : u = u') : (p.copy hu hu).IsCycle ↔ p.IsCycle := by subst_vars rfl lemma IsCycle.not_nil {p : G.Walk v v} (hp : IsCycle p) : ¬ p.Nil := (hp.ne_nil ·.eq_nil) @[simp] theorem IsTrail.nil {u : V} : (nil : G.Walk u u).IsTrail := ⟨by simp [edges]⟩ theorem IsTrail.of_cons {u v w : V} {h : G.Adj u v} {p : G.Walk v w} : (cons h p).IsTrail → p.IsTrail := by simp [isTrail_def] @[simp] theorem cons_isTrail_iff {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h p).IsTrail ↔ p.IsTrail ∧ s(u, v) ∉ p.edges := by simp [isTrail_def, and_comm] theorem IsTrail.reverse {u v : V} (p : G.Walk u v) (h : p.IsTrail) : p.reverse.IsTrail := by simpa [isTrail_def] using h @[simp] theorem reverse_isTrail_iff {u v : V} (p : G.Walk u v) : p.reverse.IsTrail ↔ p.IsTrail := by constructor <;> · intro h convert h.reverse _ try rw [reverse_reverse] theorem IsTrail.of_append_left {u v w : V} {p : G.Walk u v} {q : G.Walk v w} (h : (p.append q).IsTrail) : p.IsTrail := by rw [isTrail_def, edges_append, List.nodup_append] at h exact ⟨h.1⟩ theorem IsTrail.of_append_right {u v w : V} {p : G.Walk u v} {q : G.Walk v w} (h : (p.append q).IsTrail) : q.IsTrail := by rw [isTrail_def, edges_append, List.nodup_append] at h exact ⟨h.2.1⟩ theorem IsTrail.count_edges_le_one [DecidableEq V] {u v : V} {p : G.Walk u v} (h : p.IsTrail) (e : Sym2 V) : p.edges.count e ≤ 1 := List.nodup_iff_count_le_one.mp h.edges_nodup e theorem IsTrail.count_edges_eq_one [DecidableEq V] {u v : V} {p : G.Walk u v} (h : p.IsTrail) {e : Sym2 V} (he : e ∈ p.edges) : p.edges.count e = 1 := List.count_eq_one_of_mem h.edges_nodup he theorem IsTrail.length_le_card_edgeFinset [Fintype G.edgeSet] {u v : V} {w : G.Walk u v} (h : w.IsTrail) : w.length ≤ G.edgeFinset.card := by classical let edges := w.edges.toFinset have : edges.card = w.length := length_edges _ ▸ List.toFinset_card_of_nodup h.edges_nodup rw [← this] have : edges ⊆ G.edgeFinset := by intro e h refine mem_edgeFinset.mpr ?_ apply w.edges_subset_edgeSet simpa [edges] using h exact Finset.card_le_card this theorem IsPath.nil {u : V} : (nil : G.Walk u u).IsPath := by constructor <;> simp theorem IsPath.of_cons {u v w : V} {h : G.Adj u v} {p : G.Walk v w} : (cons h p).IsPath → p.IsPath := by simp [isPath_def] @[simp] theorem cons_isPath_iff {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h p).IsPath ↔ p.IsPath ∧ u ∉ p.support := by constructor <;> simp +contextual [isPath_def] protected lemma IsPath.cons {p : Walk G v w} (hp : p.IsPath) (hu : u ∉ p.support) {h : G.Adj u v} : (cons h p).IsPath := (cons_isPath_iff _ _).2 ⟨hp, hu⟩ @[simp] theorem isPath_iff_eq_nil {u : V} (p : G.Walk u u) : p.IsPath ↔ p = nil := by cases p <;> simp [IsPath.nil] theorem IsPath.reverse {u v : V} {p : G.Walk u v} (h : p.IsPath) : p.reverse.IsPath := by simpa [isPath_def] using h @[simp] theorem isPath_reverse_iff {u v : V} (p : G.Walk u v) : p.reverse.IsPath ↔ p.IsPath := by constructor <;> intro h <;> convert h.reverse; simp theorem IsPath.of_append_left {u v w : V} {p : G.Walk u v} {q : G.Walk v w} : (p.append q).IsPath → p.IsPath := by simp only [isPath_def, support_append] exact List.Nodup.of_append_left theorem IsPath.of_append_right {u v w : V} {p : G.Walk u v} {q : G.Walk v w} (h : (p.append q).IsPath) : q.IsPath := by rw [← isPath_reverse_iff] at h ⊢ rw [reverse_append] at h apply h.of_append_left theorem isTrail_of_isSubwalk {v w v' w'} {p₁ : G.Walk v w} {p₂ : G.Walk v' w'} (h : p₁.IsSubwalk p₂) (h₂ : p₂.IsTrail) : p₁.IsTrail := by obtain ⟨_, _, h⟩ := h rw [h] at h₂ exact h₂.of_append_left.of_append_right theorem isPath_of_isSubwalk {v w v' w' : V} {p₁ : G.Walk v w} {p₂ : G.Walk v' w'} (h : p₁.IsSubwalk p₂) (h₂ : p₂.IsPath) : p₁.IsPath := by obtain ⟨_, _, h⟩ := h rw [h] at h₂ exact h₂.of_append_left.of_append_right lemma IsPath.of_adj {G : SimpleGraph V} {u v : V} (h : G.Adj u v) : h.toWalk.IsPath := by aesop theorem concat_isPath_iff {p : G.Walk u v} (h : G.Adj v w) : (p.concat h).IsPath ↔ p.IsPath ∧ w ∉ p.support := by rw [← (p.concat h).isPath_reverse_iff, ← p.isPath_reverse_iff, reverse_concat, ← List.mem_reverse, ← support_reverse] exact cons_isPath_iff h.symm p.reverse theorem IsPath.concat {p : G.Walk u v} (hp : p.IsPath) (hw : w ∉ p.support) (h : G.Adj v w) : (p.concat h).IsPath := (concat_isPath_iff h).mpr ⟨hp, hw⟩ lemma IsPath.mem_support_iff_exists_append {p : G.Walk u v} (hp : p.IsPath) : w ∈ p.support ↔ ∃ (q : G.Walk u w) (r : G.Walk w v), q.IsPath ∧ r.IsPath ∧ p = q.append r := by refine ⟨fun hw ↦ ?_, fun ⟨q, r, hq, hr, hqr⟩ ↦ p.mem_support_iff_exists_append.mpr ⟨q, r, hqr⟩⟩ obtain ⟨q, r, hqr⟩ := p.mem_support_iff_exists_append.mp hw have : (q.append r).IsPath := hqr ▸ hp exact ⟨q, r, this.of_append_left, this.of_append_right, hqr⟩ lemma IsPath.disjoint_support_of_append {p : G.Walk u v} {q : G.Walk v w} (hpq : (p.append q).IsPath) (hq : ¬q.Nil) : p.support.Disjoint q.tail.support := by have hpq' := hpq.support_nodup rw [support_append] at hpq' rw [support_tail_of_not_nil q hq] exact List.disjoint_of_nodup_append hpq' lemma IsPath.ne_of_mem_support_of_append {p : G.Walk u v} {q : G.Walk v w} (hpq : (p.append q).IsPath) {x y : V} (hyv : y ≠ v) (hx : x ∈ p.support) (hy : y ∈ q.support) : x ≠ y := by rintro rfl have hq : ¬q.Nil := by intro hq simp [nil_iff_support_eq.mp hq, hyv] at hy have hx' : x ∈ q.tail.support := by rw [support_tail_of_not_nil q hq] rw [mem_support_iff] at hy exact hy.resolve_left hyv exact IsPath.disjoint_support_of_append hpq hq hx hx' @[simp] theorem IsCycle.not_of_nil {u : V} : ¬(nil : G.Walk u u).IsCycle := fun h => h.ne_nil rfl lemma IsCycle.ne_bot : ∀ {p : G.Walk u u}, p.IsCycle → G ≠ ⊥ | nil, hp => by cases hp.ne_nil rfl | cons h _, hp => by rintro rfl; exact h lemma IsCycle.three_le_length {v : V} {p : G.Walk v v} (hp : p.IsCycle) : 3 ≤ p.length := by have ⟨⟨hp, hp'⟩, _⟩ := hp match p with | .nil => simp at hp' | .cons h .nil => simp at h | .cons _ (.cons _ .nil) => simp at hp | .cons _ (.cons _ (.cons _ _)) => simp_rw [SimpleGraph.Walk.length_cons]; cutsat lemma not_nil_of_isCycle_cons {p : G.Walk u v} {h : G.Adj v u} (hc : (Walk.cons h p).IsCycle) : ¬ p.Nil := by have := Walk.length_cons _ _ ▸ Walk.IsCycle.three_le_length hc rw [Walk.not_nil_iff_lt_length] cutsat theorem cons_isCycle_iff {u v : V} (p : G.Walk v u) (h : G.Adj u v) : (Walk.cons h p).IsCycle ↔ p.IsPath ∧ s(u, v) ∉ p.edges := by simp only [Walk.isCycle_def, Walk.isPath_def, Walk.isTrail_def, edges_cons, List.nodup_cons, support_cons, List.tail_cons] have : p.support.Nodup → p.edges.Nodup := edges_nodup_of_support_nodup tauto protected lemma IsCycle.reverse {p : G.Walk u u} (h : p.IsCycle) : p.reverse.IsCycle := by simp only [Walk.isCycle_def, nodup_tail_support_reverse] at h ⊢ exact ⟨h.1.reverse, fun h' ↦ h.2.1 (by simp_all [← Walk.length_eq_zero_iff]), h.2.2⟩ @[simp] lemma isCycle_reverse {p : G.Walk u u} : p.reverse.IsCycle ↔ p.IsCycle where mp h := by simpa using h.reverse mpr := .reverse lemma IsCycle.isPath_of_append_right {p : G.Walk u v} {q : G.Walk v u} (h : ¬ p.Nil) (hcyc : (p.append q).IsCycle) : q.IsPath := by have := hcyc.2 rw [tail_support_append, List.nodup_append'] at this rw [isPath_def, support_eq_cons, List.nodup_cons] exact ⟨this.2.2 (p.end_mem_tail_support h), this.2.1⟩ lemma IsCycle.isPath_of_append_left {p : G.Walk u v} {q : G.Walk v u} (h : ¬ q.Nil) (hcyc : (p.append q).IsCycle) : p.IsPath := p.isPath_reverse_iff.mp ((reverse_append _ _ ▸ hcyc.reverse).isPath_of_append_right (by simpa)) lemma IsPath.tail {p : G.Walk u v} (hp : p.IsPath) : p.tail.IsPath := by cases p with | nil => simp | cons hadj p => simp_all [Walk.isPath_def] /-! ### About paths -/ instance [DecidableEq V] {u v : V} (p : G.Walk u v) : Decidable p.IsPath := by rw [isPath_def] infer_instance theorem IsPath.length_lt [Fintype V] {u v : V} {p : G.Walk u v} (hp : p.IsPath) : p.length < Fintype.card V := by rw [Nat.lt_iff_add_one_le, ← length_support] exact hp.support_nodup.length_le_card lemma IsPath.getVert_injOn {p : G.Walk u v} (hp : p.IsPath) : Set.InjOn p.getVert {i | i ≤ p.length} := by intro n hn m hm hnm induction p generalizing n m with | nil => simp_all | @cons v w u h p ihp => simp only [length_cons, Set.mem_setOf_eq] at hn hm hnm by_cases hn0 : n = 0 <;> by_cases hm0 : m = 0 · cutsat · simp only [hn0, getVert_zero, Walk.getVert_cons p h hm0] at hnm have hvp : v ∉ p.support := by aesop exact (hvp (Walk.mem_support_iff_exists_getVert.mpr ⟨(m - 1), ⟨hnm.symm, by cutsat⟩⟩)).elim · simp only [hm0, Walk.getVert_cons p h hn0] at hnm have hvp : v ∉ p.support := by simp_all exact (hvp (Walk.mem_support_iff_exists_getVert.mpr ⟨(n - 1), ⟨hnm, by cutsat⟩⟩)).elim · simp only [Walk.getVert_cons _ _ hn0, Walk.getVert_cons _ _ hm0] at hnm have := ihp hp.of_cons (by cutsat : (n - 1) ≤ p.length) (by cutsat : (m - 1) ≤ p.length) hnm cutsat lemma IsPath.getVert_eq_start_iff {i : ℕ} {p : G.Walk u w} (hp : p.IsPath) (hi : i ≤ p.length) : p.getVert i = u ↔ i = 0 := by refine ⟨?_, by simp_all⟩ intro h by_cases hi : i = 0 · exact hi · apply hp.getVert_injOn (by rw [Set.mem_setOf]; cutsat) (by rw [Set.mem_setOf]; cutsat) simp [h] lemma IsPath.getVert_eq_end_iff {i : ℕ} {p : G.Walk u w} (hp : p.IsPath) (hi : i ≤ p.length) : p.getVert i = w ↔ i = p.length := by have := hp.reverse.getVert_eq_start_iff (by cutsat : p.reverse.length - i ≤ p.reverse.length) simp only [length_reverse, getVert_reverse, show p.length - (p.length - i) = i by cutsat] at this rw [this] cutsat lemma IsPath.getVert_injOn_iff (p : G.Walk u v) : Set.InjOn p.getVert {i | i ≤ p.length} ↔ p.IsPath := by refine ⟨?_, fun a => a.getVert_injOn⟩ induction p with | nil => simp | cons h q ih => intro hinj rw [cons_isPath_iff] refine ⟨ih (by intro n hn m hm hnm simp only [Set.mem_setOf_eq] at hn hm have := hinj (by rw [length_cons]; cutsat : n + 1 ≤ (q.cons h).length) (by rw [length_cons]; cutsat : m + 1 ≤ (q.cons h).length) (by simpa [getVert_cons] using hnm) cutsat), fun h' => ?_⟩ obtain ⟨n, ⟨hn, hnl⟩⟩ := mem_support_iff_exists_getVert.mp h' have := hinj (by rw [length_cons]; cutsat : (n + 1) ≤ (q.cons h).length) (by cutsat : 0 ≤ (q.cons h).length) (by rwa [getVert_cons _ _ n.add_one_ne_zero, getVert_zero]) omega /-! ### About cycles -/ -- TODO: These results could possibly be less laborious with a periodic function getCycleVert lemma IsCycle.getVert_injOn {p : G.Walk u u} (hpc : p.IsCycle) : Set.InjOn p.getVert {i | 1 ≤ i ∧ i ≤ p.length} := by rw [← p.cons_tail_eq hpc.not_nil] at hpc intro n hn m hm hnm rw [← SimpleGraph.Walk.length_tail_add_one (p.not_nil_of_tail_not_nil (not_nil_of_isCycle_cons hpc)), Set.mem_setOf] at hn hm have := ((Walk.cons_isCycle_iff _ _).mp hpc).1.getVert_injOn (by cutsat : n - 1 ≤ p.tail.length) (by cutsat : m - 1 ≤ p.tail.length) (by simp_all [SimpleGraph.Walk.getVert_tail, Nat.sub_add_cancel hn.1, Nat.sub_add_cancel hm.1]) omega lemma IsCycle.getVert_injOn' {p : G.Walk u u} (hpc : p.IsCycle) : Set.InjOn p.getVert {i | i ≤ p.length - 1} := by intro n hn m hm hnm simp only [Set.mem_setOf_eq] at * have := hpc.three_le_length have : p.length - n = p.length - m := Walk.length_reverse _ ▸ hpc.reverse.getVert_injOn (by simp only [Walk.length_reverse, Set.mem_setOf_eq]; cutsat) (by simp only [Walk.length_reverse, Set.mem_setOf_eq]; cutsat) (by simp [Walk.getVert_reverse, show p.length - (p.length - n) = n by cutsat, hnm, show p.length - (p.length - m) = m by cutsat]) cutsat lemma IsCycle.snd_ne_penultimate {p : G.Walk u u} (hp : p.IsCycle) : p.snd ≠ p.penultimate := by intro h have := hp.three_le_length apply hp.getVert_injOn (by simp; cutsat) (by simp; cutsat) at h cutsat lemma IsCycle.getVert_endpoint_iff {i : ℕ} {p : G.Walk u u} (hpc : p.IsCycle) (hl : i ≤ p.length) : p.getVert i = u ↔ i = 0 ∨ i = p.length := by refine ⟨?_, by aesop⟩ rw [or_iff_not_imp_left] intro h hi exact hpc.getVert_injOn (by simp only [Set.mem_setOf_eq]; cutsat) (by simp only [Set.mem_setOf_eq]; cutsat) (h.symm ▸ (Walk.getVert_length p).symm) lemma IsCycle.getVert_sub_one_ne_getVert_add_one {i : ℕ} {p : G.Walk u u} (hpc : p.IsCycle) (h : i ≤ p.length) : p.getVert (i - 1) ≠ p.getVert (i + 1) := by intro h' have hl := hpc.three_le_length by_cases hi' : i ≥ p.length - 1 · rw [p.getVert_of_length_le (by cutsat : p.length ≤ i + 1), hpc.getVert_endpoint_iff (by cutsat)] at h' cutsat have := hpc.getVert_injOn' (by simp only [Set.mem_setOf_eq, Nat.sub_le_iff_le_add]; cutsat) (by simp only [Set.mem_setOf_eq]; cutsat) h' cutsat @[deprecated (since := "2025-04-27")] alias IsCycle.getVert_sub_one_neq_getVert_add_one := IsCycle.getVert_sub_one_ne_getVert_add_one /-! ### Walk decompositions -/ section WalkDecomp variable [DecidableEq V] protected theorem IsTrail.takeUntil {u v w : V} {p : G.Walk v w} (hc : p.IsTrail) (h : u ∈ p.support) : (p.takeUntil u h).IsTrail := IsTrail.of_append_left (q := p.dropUntil u h) (by rwa [← take_spec _ h] at hc) protected theorem IsTrail.dropUntil {u v w : V} {p : G.Walk v w} (hc : p.IsTrail) (h : u ∈ p.support) : (p.dropUntil u h).IsTrail := IsTrail.of_append_right (p := p.takeUntil u h) (q := p.dropUntil u h) (by rwa [← take_spec _ h] at hc) protected theorem IsPath.takeUntil {u v w : V} {p : G.Walk v w} (hc : p.IsPath) (h : u ∈ p.support) : (p.takeUntil u h).IsPath := IsPath.of_append_left (q := p.dropUntil u h) (by rwa [← take_spec _ h] at hc) protected theorem IsPath.dropUntil {u v w : V} {p : G.Walk v w} (hc : p.IsPath) (h : u ∈ p.support) : (p.dropUntil u h).IsPath := IsPath.of_append_right (p := p.takeUntil u h) (q := p.dropUntil u h) (by rwa [← take_spec _ h] at hc) lemma IsTrail.disjoint_edges_takeUntil_dropUntil {x : V} {w : G.Walk u v} (hw : w.IsTrail) (hx : x ∈ w.support) : (w.takeUntil x hx).edges.Disjoint (w.dropUntil x hx).edges := List.disjoint_of_nodup_append <| by simpa [← edges_append] using hw.edges_nodup protected theorem IsTrail.rotate {u v : V} {c : G.Walk v v} (hc : c.IsTrail) (h : u ∈ c.support) : (c.rotate h).IsTrail := by rw [isTrail_def, (c.rotate_edges h).perm.nodup_iff] exact hc.edges_nodup protected theorem IsCircuit.rotate {u v : V} {c : G.Walk v v} (hc : c.IsCircuit) (h : u ∈ c.support) : (c.rotate h).IsCircuit := by refine ⟨hc.isTrail.rotate _, ?_⟩ cases c · exact (hc.ne_nil rfl).elim · intro hn have hn' := congr_arg length hn rw [rotate, length_append, add_comm, ← length_append, take_spec] at hn' simp at hn' protected theorem IsCycle.rotate {u v : V} {c : G.Walk v v} (hc : c.IsCycle) (h : u ∈ c.support) : (c.rotate h).IsCycle := by refine ⟨hc.isCircuit.rotate _, ?_⟩ rw [List.IsRotated.nodup_iff (support_rotate _ _)] exact hc.support_nodup lemma IsCycle.isPath_takeUntil {c : G.Walk v v} (hc : c.IsCycle) (h : w ∈ c.support) : (c.takeUntil w h).IsPath := by by_cases hvw : v = w · subst hvw simp rw [← isCycle_reverse, ← take_spec c h, reverse_append] at hc exact (c.takeUntil w h).isPath_reverse_iff.mp (hc.isPath_of_append_right (not_nil_of_ne hvw)) /-- Taking a strict initial segment of a path removes the end vertex from the support. -/ lemma endpoint_notMem_support_takeUntil {p : G.Walk u v} (hp : p.IsPath) (hw : w ∈ p.support) (h : v ≠ w) : v ∉ (p.takeUntil w hw).support := by intro hv rw [Walk.mem_support_iff_exists_getVert] at hv obtain ⟨n, ⟨hn, hnl⟩⟩ := hv rw [getVert_takeUntil hw hnl] at hn have := p.length_takeUntil_lt hw h.symm have : n = p.length := hp.getVert_injOn (by rw [Set.mem_setOf]; cutsat) (by simp) (hn.symm ▸ p.getVert_length.symm) cutsat @[deprecated (since := "2025-05-23")] alias endpoint_not_mem_support_takeUntil := endpoint_notMem_support_takeUntil end WalkDecomp end Walk /-! ### Type of paths -/ /-- The type for paths between two vertices. -/ abbrev Path (u v : V) := { p : G.Walk u v // p.IsPath } namespace Path variable {G G'} @[simp] protected theorem isPath {u v : V} (p : G.Path u v) : (p : G.Walk u v).IsPath := p.property @[simp] protected theorem isTrail {u v : V} (p : G.Path u v) : (p : G.Walk u v).IsTrail := p.property.isTrail /-- The length-0 path at a vertex. -/ @[refl, simps] protected def nil {u : V} : G.Path u u := ⟨Walk.nil, Walk.IsPath.nil⟩ /-- The length-1 path between a pair of adjacent vertices. -/ @[simps] def singleton {u v : V} (h : G.Adj u v) : G.Path u v := ⟨Walk.cons h Walk.nil, by simp [h.ne]⟩ theorem mk'_mem_edges_singleton {u v : V} (h : G.Adj u v) : s(u, v) ∈ (singleton h : G.Walk u v).edges := by simp [singleton] /-- The reverse of a path is another path. See also `SimpleGraph.Walk.reverse`. -/ @[symm, simps] def reverse {u v : V} (p : G.Path u v) : G.Path v u := ⟨Walk.reverse p, p.property.reverse⟩ theorem count_support_eq_one [DecidableEq V] {u v w : V} {p : G.Path u v} (hw : w ∈ (p : G.Walk u v).support) : (p : G.Walk u v).support.count w = 1 := List.count_eq_one_of_mem p.property.support_nodup hw theorem count_edges_eq_one [DecidableEq V] {u v : V} {p : G.Path u v} (e : Sym2 V) (hw : e ∈ (p : G.Walk u v).edges) : (p : G.Walk u v).edges.count e = 1 := List.count_eq_one_of_mem p.property.isTrail.edges_nodup hw @[simp] theorem nodup_support {u v : V} (p : G.Path u v) : (p : G.Walk u v).support.Nodup := (Walk.isPath_def _).mp p.property theorem loop_eq {v : V} (p : G.Path v v) : p = Path.nil := by obtain ⟨_ | _, h⟩ := p · rfl · simp at h theorem notMem_edges_of_loop {v : V} {e : Sym2 V} {p : G.Path v v} : e ∉ (p : G.Walk v v).edges := by simp [p.loop_eq] @[deprecated (since := "2025-05-23")] alias not_mem_edges_of_loop := notMem_edges_of_loop theorem cons_isCycle {u v : V} (p : G.Path v u) (h : G.Adj u v) (he : s(u, v) ∉ (p : G.Walk v u).edges) : (Walk.cons h ↑p).IsCycle := by simp [Walk.isCycle_def, Walk.cons_isTrail_iff, he] end Path /-! ### Walks to paths -/ namespace Walk variable {G} [DecidableEq V] /-- Given a walk, produces a walk from it by bypassing subwalks between repeated vertices. The result is a path, as shown in `SimpleGraph.Walk.bypass_isPath`. This is packaged up in `SimpleGraph.Walk.toPath`. -/ def bypass {u v : V} : G.Walk u v → G.Walk u v | nil => nil | cons ha p => let p' := p.bypass if hs : u ∈ p'.support then p'.dropUntil u hs else cons ha p' @[simp] theorem bypass_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).bypass = p.bypass.copy hu hv := by subst_vars rfl theorem bypass_isPath {u v : V} (p : G.Walk u v) : p.bypass.IsPath := by induction p with | nil => simp! | cons _ p' ih => simp only [bypass] split_ifs with hs · exact ih.dropUntil hs · simp [*, cons_isPath_iff] theorem length_bypass_le {u v : V} (p : G.Walk u v) : p.bypass.length ≤ p.length := by induction p with | nil => rfl | cons _ _ ih => simp only [bypass] split_ifs · trans · apply length_dropUntil_le rw [length_cons] cutsat · rw [length_cons, length_cons] exact Nat.add_le_add_right ih 1 lemma bypass_eq_self_of_length_le {u v : V} (p : G.Walk u v) (h : p.length ≤ p.bypass.length) : p.bypass = p := by induction p with | nil => rfl | cons h p ih => simp only [Walk.bypass] split_ifs with hb · exfalso simp only [hb, Walk.bypass, Walk.length_cons, dif_pos] at h apply Nat.not_succ_le_self p.length calc p.length + 1 _ ≤ (p.bypass.dropUntil _ _).length := h _ ≤ p.bypass.length := Walk.length_dropUntil_le p.bypass hb _ ≤ p.length := Walk.length_bypass_le _ · simp only [hb, Walk.bypass, Walk.length_cons, not_false_iff, dif_neg, Nat.add_le_add_iff_right] at h rw [ih h] /-- Given a walk, produces a path with the same endpoints using `SimpleGraph.Walk.bypass`. -/ def toPath {u v : V} (p : G.Walk u v) : G.Path u v := ⟨p.bypass, p.bypass_isPath⟩ theorem support_bypass_subset {u v : V} (p : G.Walk u v) : p.bypass.support ⊆ p.support := by induction p with | nil => simp! | cons _ _ ih => simp! only split_ifs · apply List.Subset.trans (support_dropUntil_subset _ _) apply List.subset_cons_of_subset assumption · rw [support_cons] apply List.cons_subset_cons assumption theorem support_toPath_subset {u v : V} (p : G.Walk u v) : (p.toPath : G.Walk u v).support ⊆ p.support := support_bypass_subset _ theorem darts_bypass_subset {u v : V} (p : G.Walk u v) : p.bypass.darts ⊆ p.darts := by induction p with | nil => simp! | cons _ _ ih => simp! only split_ifs · apply List.Subset.trans (darts_dropUntil_subset _ _) apply List.subset_cons_of_subset _ ih · rw [darts_cons] exact List.cons_subset_cons _ ih theorem edges_bypass_subset {u v : V} (p : G.Walk u v) : p.bypass.edges ⊆ p.edges := List.map_subset _ p.darts_bypass_subset theorem darts_toPath_subset {u v : V} (p : G.Walk u v) : (p.toPath : G.Walk u v).darts ⊆ p.darts := darts_bypass_subset _ theorem edges_toPath_subset {u v : V} (p : G.Walk u v) : (p.toPath : G.Walk u v).edges ⊆ p.edges := edges_bypass_subset _ end Walk /-! ### Mapping paths -/ namespace Walk variable {G G'} variable (f : G →g G') {u v : V} (p : G.Walk u v) variable {p f} theorem map_isPath_of_injective (hinj : Function.Injective f) (hp : p.IsPath) : (p.map f).IsPath := by induction p with | nil => simp | cons _ _ ih => rw [Walk.cons_isPath_iff] at hp simp only [map_cons, cons_isPath_iff, ih hp.1, support_map, List.mem_map, not_exists, not_and, true_and] intro x hx hf cases hinj hf exact hp.2 hx protected theorem IsPath.of_map {f : G →g G'} (hp : (p.map f).IsPath) : p.IsPath := by induction p with | nil => simp | cons _ _ ih => grind [map_cons, Walk.cons_isPath_iff, support_map] theorem map_isPath_iff_of_injective (hinj : Function.Injective f) : (p.map f).IsPath ↔ p.IsPath := ⟨IsPath.of_map, map_isPath_of_injective hinj⟩ theorem map_isTrail_iff_of_injective (hinj : Function.Injective f) : (p.map f).IsTrail ↔ p.IsTrail := by induction p with | nil => simp | cons _ _ ih => rw [map_cons, cons_isTrail_iff, ih, cons_isTrail_iff] apply and_congr_right' rw [← Sym2.map_pair_eq, edges_map, ← List.mem_map_of_injective (Sym2.map.injective hinj)] alias ⟨_, map_isTrail_of_injective⟩ := map_isTrail_iff_of_injective theorem map_isCycle_iff_of_injective {p : G.Walk u u} (hinj : Function.Injective f) : (p.map f).IsCycle ↔ p.IsCycle := by rw [isCycle_def, isCycle_def, map_isTrail_iff_of_injective hinj, Ne, map_eq_nil_iff, support_map, ← List.map_tail, List.nodup_map_iff hinj] alias ⟨_, IsCycle.map⟩ := map_isCycle_iff_of_injective @[simp] theorem mapLe_isTrail {G G' : SimpleGraph V} (h : G ≤ G') {u v : V} {p : G.Walk u v} : (p.mapLe h).IsTrail ↔ p.IsTrail := map_isTrail_iff_of_injective Function.injective_id alias ⟨IsTrail.of_mapLe, IsTrail.mapLe⟩ := mapLe_isTrail @[simp] theorem mapLe_isPath {G G' : SimpleGraph V} (h : G ≤ G') {u v : V} {p : G.Walk u v} : (p.mapLe h).IsPath ↔ p.IsPath := map_isPath_iff_of_injective Function.injective_id alias ⟨IsPath.of_mapLe, IsPath.mapLe⟩ := mapLe_isPath @[simp] theorem mapLe_isCycle {G G' : SimpleGraph V} (h : G ≤ G') {u : V} {p : G.Walk u u} : (p.mapLe h).IsCycle ↔ p.IsCycle := map_isCycle_iff_of_injective Function.injective_id alias ⟨IsCycle.of_mapLe, IsCycle.mapLe⟩ := mapLe_isCycle end Walk namespace Path variable {G G'} /-- Given an injective graph homomorphism, map paths to paths. -/ @[simps] protected def map (f : G →g G') (hinj : Function.Injective f) {u v : V} (p : G.Path u v) : G'.Path (f u) (f v) := ⟨Walk.map f p, Walk.map_isPath_of_injective hinj p.2⟩ theorem map_injective {f : G →g G'} (hinj : Function.Injective f) (u v : V) : Function.Injective (Path.map f hinj : G.Path u v → G'.Path (f u) (f v)) := by rintro ⟨p, hp⟩ ⟨p', hp'⟩ h simp only [Path.map, Subtype.mk.injEq] at h simp [Walk.map_injective_of_injective hinj u v h] /-- Given a graph embedding, map paths to paths. -/ @[simps!] protected def mapEmbedding (f : G ↪g G') {u v : V} (p : G.Path u v) : G'.Path (f u) (f v) := Path.map f.toHom f.injective p theorem mapEmbedding_injective (f : G ↪g G') (u v : V) : Function.Injective (Path.mapEmbedding f : G.Path u v → G'.Path (f u) (f v)) := map_injective f.injective u v end Path /-! ### Transferring between graphs -/ namespace Walk variable {G} {u v : V} {H : SimpleGraph V} variable {p : G.Walk u v} protected theorem IsPath.transfer (hp) (pp : p.IsPath) : (p.transfer H hp).IsPath := by induction p with | nil => simp | cons _ _ ih => simp only [Walk.transfer, cons_isPath_iff, support_transfer _ ] at pp ⊢ exact ⟨ih _ pp.1, pp.2⟩ protected theorem IsCycle.transfer {q : G.Walk u u} (qc : q.IsCycle) (hq) : (q.transfer H hq).IsCycle := by cases q with | nil => simp at qc | cons _ q => simp only [edges_cons, List.mem_cons, forall_eq_or_imp] at hq simp only [Walk.transfer, cons_isCycle_iff, edges_transfer q hq.2] at qc ⊢ exact ⟨qc.1.transfer hq.2, qc.2⟩ end Walk /-! ## Deleting edges -/ namespace Walk variable {v w : V} protected theorem IsPath.toDeleteEdges (s : Set (Sym2 V)) {p : G.Walk v w} (h : p.IsPath) (hp) : (p.toDeleteEdges s hp).IsPath := h.transfer _ protected theorem IsCycle.toDeleteEdges (s : Set (Sym2 V)) {p : G.Walk v v} (h : p.IsCycle) (hp) : (p.toDeleteEdges s hp).IsCycle := h.transfer _ @[simp] theorem toDeleteEdges_copy {v u u' v' : V} (s : Set (Sym2 V)) (p : G.Walk u v) (hu : u = u') (hv : v = v') (h) : (p.copy hu hv).toDeleteEdges s h = (p.toDeleteEdges s (by subst_vars; exact h)).copy hu hv := by subst_vars rfl end Walk end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Finite.lean
import Mathlib.Combinatorics.SimpleGraph.Maps import Mathlib.Data.Finset.Max import Mathlib.Data.Sym.Card /-! # Definitions for finite and locally finite graphs This file defines finite versions of `edgeSet`, `neighborSet` and `incidenceSet` and proves some of their basic properties. It also defines the notion of a locally finite graph, which is one whose vertices have finite degree. The design for finiteness is that each definition takes the smallest finiteness assumption necessary. For example, `SimpleGraph.neighborFinset v` only requires that `v` have finitely many neighbors. ## Main definitions * `SimpleGraph.edgeFinset` is the `Finset` of edges in a graph, if `edgeSet` is finite * `SimpleGraph.neighborFinset` is the `Finset` of vertices adjacent to a given vertex, if `neighborSet` is finite * `SimpleGraph.incidenceFinset` is the `Finset` of edges containing a given vertex, if `incidenceSet` is finite ## Naming conventions If the vertex type of a graph is finite, we refer to its cardinality as `CardVerts` or `card_verts`. ## Implementation notes * A locally finite graph is one with instances `Π v, Fintype (G.neighborSet v)`. * Given instances `DecidableRel G.Adj` and `Fintype V`, then the graph is locally finite, too. -/ open Finset Function namespace SimpleGraph variable {V : Type*} (G : SimpleGraph V) {e : Sym2 V} section EdgeFinset variable {G₁ G₂ : SimpleGraph V} [Fintype G.edgeSet] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] /-- The `edgeSet` of the graph as a `Finset`. -/ abbrev edgeFinset : Finset (Sym2 V) := Set.toFinset G.edgeSet @[norm_cast] theorem coe_edgeFinset : (G.edgeFinset : Set (Sym2 V)) = G.edgeSet := Set.coe_toFinset _ variable {G} theorem mem_edgeFinset : e ∈ G.edgeFinset ↔ e ∈ G.edgeSet := Set.mem_toFinset theorem not_isDiag_of_mem_edgeFinset : e ∈ G.edgeFinset → ¬e.IsDiag := not_isDiag_of_mem_edgeSet _ ∘ mem_edgeFinset.1 /-- Mapping an edge to a finite set produces a finset of size `2`. -/ theorem card_toFinset_mem_edgeFinset [DecidableEq V] (e : G.edgeFinset) : (e : Sym2 V).toFinset.card = 2 := Sym2.card_toFinset_of_not_isDiag e.val (G.not_isDiag_of_mem_edgeFinset e.prop) theorem edgeFinset_inj : G₁.edgeFinset = G₂.edgeFinset ↔ G₁ = G₂ := by simp theorem edgeFinset_subset_edgeFinset : G₁.edgeFinset ⊆ G₂.edgeFinset ↔ G₁ ≤ G₂ := by simp theorem edgeFinset_ssubset_edgeFinset : G₁.edgeFinset ⊂ G₂.edgeFinset ↔ G₁ < G₂ := by simp @[mono, gcongr] alias ⟨_, edgeFinset_mono⟩ := edgeFinset_subset_edgeFinset @[mono, gcongr] alias ⟨_, edgeFinset_strict_mono⟩ := edgeFinset_ssubset_edgeFinset @[simp] theorem edgeFinset_bot : (⊥ : SimpleGraph V).edgeFinset = ∅ := by simp [edgeFinset] @[simp] theorem edgeFinset_sup [Fintype (edgeSet (G₁ ⊔ G₂))] [DecidableEq V] : (G₁ ⊔ G₂).edgeFinset = G₁.edgeFinset ∪ G₂.edgeFinset := by simp [edgeFinset] @[simp] theorem edgeFinset_inf [DecidableEq V] : (G₁ ⊓ G₂).edgeFinset = G₁.edgeFinset ∩ G₂.edgeFinset := by simp [edgeFinset] @[simp] theorem edgeFinset_sdiff [DecidableEq V] : (G₁ \ G₂).edgeFinset = G₁.edgeFinset \ G₂.edgeFinset := by simp [edgeFinset] lemma disjoint_edgeFinset : Disjoint G₁.edgeFinset G₂.edgeFinset ↔ Disjoint G₁ G₂ := by simp_rw [← Finset.disjoint_coe, coe_edgeFinset, disjoint_edgeSet] lemma edgeFinset_eq_empty : G.edgeFinset = ∅ ↔ G = ⊥ := by rw [← edgeFinset_bot, edgeFinset_inj] lemma edgeFinset_nonempty : G.edgeFinset.Nonempty ↔ G ≠ ⊥ := by rw [Finset.nonempty_iff_ne_empty, edgeFinset_eq_empty.ne] theorem edgeFinset_card : #G.edgeFinset = Fintype.card G.edgeSet := Set.toFinset_card _ @[simp] theorem edgeSet_univ_card : #(univ : Finset G.edgeSet) = #G.edgeFinset := Fintype.card_of_subtype G.edgeFinset fun _ => mem_edgeFinset variable [Fintype V] @[simp] theorem edgeFinset_top [DecidableEq V] : (⊤ : SimpleGraph V).edgeFinset = ({e | ¬e.IsDiag} : Finset _) := by simp [← coe_inj] /-- The complete graph on `n` vertices has `n.choose 2` edges. -/ theorem card_edgeFinset_top_eq_card_choose_two [DecidableEq V] : #(⊤ : SimpleGraph V).edgeFinset = (Fintype.card V).choose 2 := by simp_rw [Set.toFinset_card, edgeSet_top, Set.coe_setOf, ← Sym2.card_subtype_not_diag] /-- Any graph on `n` vertices has at most `n.choose 2` edges. -/ theorem card_edgeFinset_le_card_choose_two : #G.edgeFinset ≤ (Fintype.card V).choose 2 := by classical rw [← card_edgeFinset_top_eq_card_choose_two] exact card_le_card (edgeFinset_mono le_top) end EdgeFinset namespace Iso variable {G} {W : Type*} {G' : SimpleGraph W} theorem card_edgeFinset_eq (f : G ≃g G') [Fintype G.edgeSet] [Fintype G'.edgeSet] : #G.edgeFinset = #G'.edgeFinset := by apply Finset.card_eq_of_equiv simp only [Set.mem_toFinset] exact f.mapEdgeSet end Iso section FiniteAt /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `Fintype (G.neighborSet v)`. We define `G.neighborFinset v` to be the `Finset` version of `G.neighborSet v`. Use `neighborFinset_eq_filter` to rewrite this definition as a `Finset.filter` expression. -/ variable (v) [Fintype (G.neighborSet v)] /-- `G.neighborFinset v` is the `Finset` version of `G.neighborSet v` in case `G` is locally finite at `v`. -/ def neighborFinset : Finset V := (G.neighborSet v).toFinset theorem neighborFinset_def : G.neighborFinset v = (G.neighborSet v).toFinset := rfl @[simp] theorem mem_neighborFinset (w : V) : w ∈ G.neighborFinset v ↔ G.Adj v w := Set.mem_toFinset theorem notMem_neighborFinset_self : v ∉ G.neighborFinset v := by simp @[deprecated (since := "2025-05-23")] alias not_mem_neighborFinset_self := notMem_neighborFinset_self theorem neighborFinset_disjoint_singleton : Disjoint (G.neighborFinset v) {v} := Finset.disjoint_singleton_right.mpr <| notMem_neighborFinset_self _ _ theorem singleton_disjoint_neighborFinset : Disjoint {v} (G.neighborFinset v) := Finset.disjoint_singleton_left.mpr <| notMem_neighborFinset_self _ _ /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := #(G.neighborFinset v) @[simp] theorem card_neighborFinset_eq_degree : #(G.neighborFinset v) = G.degree v := rfl @[simp] theorem card_neighborSet_eq_degree : Fintype.card (G.neighborSet v) = G.degree v := (Set.toFinset_card _).symm theorem degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.Adj v w := by simp only [degree, card_pos, Finset.Nonempty, mem_neighborFinset] theorem degree_pos_iff_mem_support : 0 < G.degree v ↔ v ∈ G.support := by rw [G.degree_pos_iff_exists_adj v, mem_support] theorem degree_eq_zero_iff_notMem_support : G.degree v = 0 ↔ v ∉ G.support := by rw [← G.degree_pos_iff_mem_support v, Nat.pos_iff_ne_zero, not_ne_iff] @[deprecated (since := "2025-05-23")] alias degree_eq_zero_iff_not_mem_support := degree_eq_zero_iff_notMem_support @[simp] theorem degree_eq_zero_of_subsingleton {G : SimpleGraph V} (v : V) [Fintype (G.neighborSet v)] [Subsingleton V] : G.degree v = 0 := by have := G.degree_pos_iff_exists_adj v simp_all [subsingleton_iff_forall_eq v] theorem degree_eq_one_iff_existsUnique_adj {G : SimpleGraph V} {v : V} [Fintype (G.neighborSet v)] : G.degree v = 1 ↔ ∃! w : V, G.Adj v w := by rw [degree, Finset.card_eq_one, Finset.singleton_iff_unique_mem] simp only [mem_neighborFinset] theorem nontrivial_of_degree_ne_zero {G : SimpleGraph V} {v : V} [Fintype (G.neighborSet v)] (h : G.degree v ≠ 0) : Nontrivial V := by apply not_subsingleton_iff_nontrivial.mp by_contra simp_all [degree_eq_zero_of_subsingleton] theorem degree_compl [Fintype (Gᶜ.neighborSet v)] [Fintype V] : Gᶜ.degree v = Fintype.card V - 1 - G.degree v := by classical rw [← card_neighborSet_union_compl_neighborSet G v, Set.toFinset_union] simp [card_union_of_disjoint (Set.disjoint_toFinset.mpr (compl_neighborSet_disjoint G v))] instance incidenceSetFintype [DecidableEq V] : Fintype (G.incidenceSet v) := Fintype.ofEquiv (G.neighborSet v) (G.incidenceSetEquivNeighborSet v).symm /-- This is the `Finset` version of `incidenceSet`. -/ def incidenceFinset [DecidableEq V] : Finset (Sym2 V) := (G.incidenceSet v).toFinset @[simp] theorem card_incidenceSet_eq_degree [DecidableEq V] : Fintype.card (G.incidenceSet v) = G.degree v := by rw [Fintype.card_congr (G.incidenceSetEquivNeighborSet v)] simp @[simp] theorem card_incidenceFinset_eq_degree [DecidableEq V] : #(G.incidenceFinset v) = G.degree v := by rw [← G.card_incidenceSet_eq_degree] apply Set.toFinset_card @[simp] theorem mem_incidenceFinset [DecidableEq V] (e : Sym2 V) : e ∈ G.incidenceFinset v ↔ e ∈ G.incidenceSet v := Set.mem_toFinset theorem incidenceFinset_eq_filter [DecidableEq V] [Fintype G.edgeSet] : G.incidenceFinset v = {e ∈ G.edgeFinset | v ∈ e} := by ext e induction e simp [mk'_mem_incidenceSet_iff] theorem incidenceFinset_subset [DecidableEq V] [Fintype G.edgeSet] : G.incidenceFinset v ⊆ G.edgeFinset := Set.toFinset_subset_toFinset.mpr (G.incidenceSet_subset v) /-- The degree of a vertex is at most the number of edges. -/ theorem degree_le_card_edgeFinset [Fintype G.edgeSet] : G.degree v ≤ #G.edgeFinset := by classical rw [← card_incidenceFinset_eq_degree] exact card_le_card (G.incidenceFinset_subset v) variable {G v} /-- If `G ≤ H` then `G.degree v ≤ H.degree v` for any vertex `v`. -/ lemma degree_le_of_le {H : SimpleGraph V} [Fintype (H.neighborSet v)] (hle : G ≤ H) : G.degree v ≤ H.degree v := by simp_rw [← card_neighborSet_eq_degree] exact Set.card_le_card fun v hv => hle hv end FiniteAt section LocallyFinite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ abbrev LocallyFinite := ∀ v : V, Fintype (G.neighborSet v) variable [LocallyFinite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def IsRegularOfDegree (d : ℕ) : Prop := ∀ v : V, G.degree v = d variable {G} theorem IsRegularOfDegree.degree_eq {d : ℕ} (h : G.IsRegularOfDegree d) (v : V) : G.degree v = d := h v theorem IsRegularOfDegree.compl [Fintype V] [DecidableEq V] {G : SimpleGraph V} [DecidableRel G.Adj] {k : ℕ} (h : G.IsRegularOfDegree k) : Gᶜ.IsRegularOfDegree (Fintype.card V - 1 - k) := by intro v rw [degree_compl, h v] end LocallyFinite section Finite variable [Fintype V] instance neighborSetFintype [DecidableRel G.Adj] (v : V) : Fintype (G.neighborSet v) := @Subtype.fintype _ (· ∈ G.neighborSet v) (by simp_rw [mem_neighborSet] infer_instance) _ theorem neighborFinset_eq_filter {v : V} [DecidableRel G.Adj] : G.neighborFinset v = ({w | G.Adj v w} : Finset _) := by ext; simp theorem neighborFinset_compl [DecidableEq V] [DecidableRel G.Adj] (v : V) : Gᶜ.neighborFinset v = (G.neighborFinset v)ᶜ \ {v} := by simp only [neighborFinset, neighborSet_compl, Set.toFinset_diff, Set.toFinset_compl, Set.toFinset_singleton] @[simp] theorem complete_graph_degree [DecidableEq V] (v : V) : (completeGraph V).degree v = Fintype.card V - 1 := by simp_rw [degree, neighborFinset_eq_filter, top_adj, filter_ne] rw [card_erase_of_mem (mem_univ v), card_univ] @[simp] theorem bot_degree (v : V) : (⊥ : SimpleGraph V).degree v = 0 := by simp_rw [degree, neighborFinset_eq_filter, bot_adj, filter_false] exact Finset.card_empty theorem IsRegularOfDegree.top [DecidableEq V] : (⊤ : SimpleGraph V).IsRegularOfDegree (Fintype.card V - 1) := by intro v simp /-- The minimum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_minimal_degree_vertex`, `minDegree_le_degree` and `le_minDegree_of_forall_le_degree`. -/ def minDegree [DecidableRel G.Adj] : ℕ := WithTop.untopD 0 (univ.image fun v => G.degree v).min /-- There exists a vertex of minimal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ theorem exists_minimal_degree_vertex [DecidableRel G.Adj] [Nonempty V] : ∃ v, G.minDegree = G.degree v := by obtain ⟨t, ht : _ = _⟩ := min_of_nonempty (univ_nonempty.image fun v => G.degree v) obtain ⟨v, _, rfl⟩ := mem_image.mp (mem_of_min ht) exact ⟨v, by simp [minDegree, ht]⟩ /-- The minimum degree in the graph is at most the degree of any particular vertex. -/ theorem minDegree_le_degree [DecidableRel G.Adj] (v : V) : G.minDegree ≤ G.degree v := by obtain ⟨t, ht⟩ := Finset.min_of_mem (mem_image_of_mem (fun v => G.degree v) (mem_univ v)) have := Finset.min_le_of_eq (mem_image_of_mem _ (mem_univ v)) ht rwa [minDegree, ht] /-- In a nonempty graph, if `k` is at most the degree of every vertex, it is at most the minimum degree. Note the assumption that the graph is nonempty is necessary as long as `G.minDegree` is defined to be a natural. -/ theorem le_minDegree_of_forall_le_degree [DecidableRel G.Adj] [Nonempty V] (k : ℕ) (h : ∀ v, k ≤ G.degree v) : k ≤ G.minDegree := by rcases G.exists_minimal_degree_vertex with ⟨v, hv⟩ rw [hv] apply h /-- If there are no vertices then the `minDegree` is zero. -/ @[simp] lemma minDegree_of_isEmpty [DecidableRel G.Adj] [IsEmpty V] : G.minDegree = 0 := by rw [minDegree, WithTop.untopD_eq_self_iff] simp variable {G} in /-- If `G` is a subgraph of `H` then `G.minDegree ≤ H.minDegree`. -/ lemma minDegree_le_minDegree {H : SimpleGraph V} [DecidableRel G.Adj] [DecidableRel H.Adj] (hle : G ≤ H) : G.minDegree ≤ H.minDegree := by by_cases! hne : Nonempty V · apply le_minDegree_of_forall_le_degree exact fun v ↦ (G.minDegree_le_degree v).trans (G.degree_le_of_le hle) · simp /-- In a nonempty graph, the minimal degree is less than the number of vertices. -/ theorem minDegree_lt_card [DecidableRel G.Adj] [Nonempty V] : G.minDegree < Fintype.card V := by obtain ⟨v, hδ⟩ := G.exists_minimal_degree_vertex rw [hδ, ← card_neighborFinset_eq_degree, ← card_univ] have h : v ∉ G.neighborFinset v := (G.mem_neighborFinset v v).not.mpr (G.loopless v) contrapose! h rw [eq_of_subset_of_card_le (subset_univ _) h] exact mem_univ v /-- The maximum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_maximal_degree_vertex`, `degree_le_maxDegree` and `maxDegree_le_of_forall_degree_le`. -/ def maxDegree [DecidableRel G.Adj] : ℕ := WithBot.unbotD 0 (univ.image fun v => G.degree v).max /-- There exists a vertex of maximal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ theorem exists_maximal_degree_vertex [DecidableRel G.Adj] [Nonempty V] : ∃ v, G.maxDegree = G.degree v := by obtain ⟨t, ht⟩ := max_of_nonempty (univ_nonempty.image fun v => G.degree v) have ht₂ := mem_of_max ht simp only [mem_image, mem_univ, true_and] at ht₂ rcases ht₂ with ⟨v, rfl⟩ refine ⟨v, ?_⟩ rw [maxDegree, ht, WithBot.unbotD_coe] /-- The maximum degree in the graph is at least the degree of any particular vertex. -/ theorem degree_le_maxDegree [DecidableRel G.Adj] (v : V) : G.degree v ≤ G.maxDegree := by obtain ⟨t, ht : _ = _⟩ := Finset.max_of_mem (mem_image_of_mem (fun v => G.degree v) (mem_univ v)) have := Finset.le_max_of_eq (mem_image_of_mem _ (mem_univ v)) ht rwa [maxDegree, ht, WithBot.unbotD_coe] @[simp] lemma maxDegree_of_isEmpty [DecidableRel G.Adj] [IsEmpty V] : G.maxDegree = 0 := by rw [maxDegree, univ_eq_empty, image_empty, max_empty, WithBot.unbotD_bot] /-- In a graph, if `k` is at least the degree of every vertex, then it is at least the maximum degree. -/ theorem maxDegree_le_of_forall_degree_le [DecidableRel G.Adj] (k : ℕ) (h : ∀ v, G.degree v ≤ k) : G.maxDegree ≤ k := by by_cases! hV : IsEmpty V · simp · obtain ⟨_, hv⟩ := G.exists_maximal_degree_vertex exact hv ▸ h _ @[simp] lemma maxDegree_bot_eq_zero : (⊥ : SimpleGraph V).maxDegree = 0 := Nat.le_zero.1 <| maxDegree_le_of_forall_degree_le _ _ (by simp) @[simp] lemma minDegree_le_maxDegree [DecidableRel G.Adj] : G.minDegree ≤ G.maxDegree := by by_cases! he : IsEmpty V · simp · exact he.elim fun v ↦ (minDegree_le_degree _ v).trans (degree_le_maxDegree _ v) @[simp] lemma minDegree_bot_eq_zero : (⊥ : SimpleGraph V).minDegree = 0 := Nat.le_zero.1 <| (minDegree_le_maxDegree _).trans (by simp) theorem degree_lt_card_verts [DecidableRel G.Adj] (v : V) : G.degree v < Fintype.card V := by classical apply Finset.card_lt_card rw [Finset.ssubset_iff] exact ⟨v, by simp, Finset.subset_univ _⟩ /-- The maximum degree of a nonempty graph is less than the number of vertices. Note that the assumption that `V` is nonempty is necessary, as otherwise this would assert the existence of a natural number less than zero. -/ theorem maxDegree_lt_card_verts [DecidableRel G.Adj] [Nonempty V] : G.maxDegree < Fintype.card V := by obtain ⟨v, hv⟩ := G.exists_maximal_degree_vertex rw [hv] apply G.degree_lt_card_verts v theorem card_commonNeighbors_le_degree_left [DecidableRel G.Adj] (v w : V) : Fintype.card (G.commonNeighbors v w) ≤ G.degree v := by rw [← card_neighborSet_eq_degree] exact Set.card_le_card Set.inter_subset_left theorem card_commonNeighbors_le_degree_right [DecidableRel G.Adj] (v w : V) : Fintype.card (G.commonNeighbors v w) ≤ G.degree w := by simp_rw [commonNeighbors_symm _ v w, card_commonNeighbors_le_degree_left] theorem card_commonNeighbors_lt_card_verts [DecidableRel G.Adj] (v w : V) : Fintype.card (G.commonNeighbors v w) < Fintype.card V := Nat.lt_of_le_of_lt (G.card_commonNeighbors_le_degree_left _ _) (G.degree_lt_card_verts v) /-- If the condition `G.Adj v w` fails, then `card_commonNeighbors_le_degree` is the best we can do in general. -/ theorem Adj.card_commonNeighbors_lt_degree {G : SimpleGraph V} [DecidableRel G.Adj] {v w : V} (h : G.Adj v w) : Fintype.card (G.commonNeighbors v w) < G.degree v := by classical rw [← Set.toFinset_card] apply Finset.card_lt_card rw [Finset.ssubset_iff] use w constructor · rw [Set.mem_toFinset] apply notMem_commonNeighbors_right · rw [Finset.insert_subset_iff] constructor · simpa · rw [neighborFinset, Set.toFinset_subset_toFinset] exact G.commonNeighbors_subset_neighborSet_left _ _ theorem card_commonNeighbors_top [DecidableEq V] {v w : V} (h : v ≠ w) : Fintype.card ((⊤ : SimpleGraph V).commonNeighbors v w) = Fintype.card V - 2 := by simp only [commonNeighbors_top_eq, ← Set.toFinset_card, Set.toFinset_diff] simp [Finset.card_sdiff, h] end Finite section Support variable {s : Set V} [DecidablePred (· ∈ s)] [Fintype V] {G : SimpleGraph V} [DecidableRel G.Adj] lemma edgeFinset_subset_sym2_of_support_subset (h : G.support ⊆ s) : G.edgeFinset ⊆ s.toFinset.sym2 := by simp_rw [subset_iff, Sym2.forall, mem_edgeFinset, mem_edgeSet, mk_mem_sym2_iff, Set.mem_toFinset] intro _ _ hadj exact ⟨h ⟨_, hadj⟩, h ⟨_, hadj.symm⟩⟩ instance : DecidablePred (· ∈ G.support) := inferInstanceAs <| DecidablePred (· ∈ { v | ∃ w, G.Adj v w }) theorem map_edgeFinset_induce [DecidableEq V] : (G.induce s).edgeFinset.map (Embedding.subtype s).sym2Map = G.edgeFinset ∩ s.toFinset.sym2 := by simp_rw [Finset.ext_iff, Sym2.forall, mem_inter, mk_mem_sym2_iff, mem_map, Sym2.exists, Set.mem_toFinset, mem_edgeSet, comap_adj, Embedding.sym2Map_apply, Embedding.coe_subtype, Sym2.map_pair_eq, Sym2.eq_iff] intro v w constructor · rintro ⟨x, y, hadj, ⟨hv, hw⟩ | ⟨hw, hv⟩⟩ all_goals rw [← hv, ← hw] · exact ⟨hadj, x.prop, y.prop⟩ · exact ⟨hadj.symm, y.prop, x.prop⟩ · intro ⟨hadj, hv, hw⟩ use ⟨v, hv⟩, ⟨w, hw⟩, hadj tauto theorem map_edgeFinset_induce_of_support_subset (h : G.support ⊆ s) : (G.induce s).edgeFinset.map (Embedding.subtype s).sym2Map = G.edgeFinset := by classical simpa [map_edgeFinset_induce] using edgeFinset_subset_sym2_of_support_subset h /-- If the support of the simple graph `G` is a subset of the set `s`, then the induced subgraph of `s` has the same number of edges as `G`. -/ theorem card_edgeFinset_induce_of_support_subset (h : G.support ⊆ s) : #(G.induce s).edgeFinset = #G.edgeFinset := by rw [← map_edgeFinset_induce_of_support_subset h, card_map] theorem card_edgeFinset_induce_support : #(G.induce G.support).edgeFinset = #G.edgeFinset := card_edgeFinset_induce_of_support_subset subset_rfl theorem map_neighborFinset_induce [DecidableEq V] (v : s) : ((G.induce s).neighborFinset v).map (.subtype (· ∈ s)) = G.neighborFinset v ∩ s.toFinset := by ext; simp theorem map_neighborFinset_induce_of_neighborSet_subset {v : s} (h : G.neighborSet v ⊆ s) : ((G.induce s).neighborFinset v).map (.subtype s) = G.neighborFinset v := by classical rwa [← Set.toFinset_subset_toFinset, ← neighborFinset_def, ← inter_eq_left, ← map_neighborFinset_induce v] at h /-- If the neighbor set of a vertex `v` is a subset of `s`, then the degree of the vertex in the induced subgraph of `s` is the same as in `G`. -/ theorem degree_induce_of_neighborSet_subset {v : s} (h : G.neighborSet v ⊆ s) : (G.induce s).degree v = G.degree v := by simp_rw [← card_neighborFinset_eq_degree, ← map_neighborFinset_induce_of_neighborSet_subset h, card_map] /-- If the support of the simple graph `G` is a subset of the set `s`, then the degree of vertices in the induced subgraph of `s` are the same as in `G`. -/ theorem degree_induce_of_support_subset (h : G.support ⊆ s) (v : s) : (G.induce s).degree v = G.degree v := degree_induce_of_neighborSet_subset <| (G.neighborSet_subset_support v).trans h @[simp] theorem degree_induce_support (v : G.support) : (G.induce G.support).degree v = G.degree v := degree_induce_of_support_subset subset_rfl v end Support section Map variable [Fintype V] {W : Type*} [Fintype W] [DecidableEq W] @[simp] theorem edgeFinset_map (f : V ↪ W) (G : SimpleGraph V) [DecidableRel G.Adj] : (G.map f).edgeFinset = G.edgeFinset.map f.sym2Map := by rw [Finset.map_eq_image, ← Set.toFinset_image, Set.toFinset_inj] exact G.edgeSet_map f theorem card_edgeFinset_map (f : V ↪ W) (G : SimpleGraph V) [DecidableRel G.Adj] : #(G.map f).edgeFinset = #G.edgeFinset := by rw [edgeFinset_map] exact G.edgeFinset.card_map f.sym2Map end Map end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/UniversalVerts.lean
import Mathlib.Combinatorics.SimpleGraph.Clique import Mathlib.Combinatorics.SimpleGraph.Connectivity.Represents import Mathlib.Combinatorics.SimpleGraph.Matching /-! # Universal Vertices This file defines the set of universal vertices: those vertices that are connected to all others. In addition, it describes results when considering connected components of the graph where universal vertices are deleted. This particular graph plays a role in the proof of Tutte's Theorem. ## Main definitions * `G.universalVerts` is the set of vertices that are connected to all other vertices. * `G.deleteUniversalVerts` is the subgraph of `G` with the universal vertices removed. -/ assert_not_exists Field TwoSidedIdeal namespace SimpleGraph variable {V : Type*} {G : SimpleGraph V} /-- The set of vertices that are connected to all other vertices. -/ def universalVerts (G : SimpleGraph V) : Set V := {v : V | ∀ ⦃w⦄, v ≠ w → G.Adj w v} lemma isClique_universalVerts (G : SimpleGraph V) : G.IsClique G.universalVerts := fun _ _ _ hy hxy ↦ hy hxy.symm /-- The subgraph of `G` with the universal vertices removed. -/ @[simps!] def deleteUniversalVerts (G : SimpleGraph V) : Subgraph G := (⊤ : Subgraph G).deleteVerts G.universalVerts lemma Subgraph.IsMatching.exists_of_universalVerts [Finite V] {s : Set V} (h : Disjoint G.universalVerts s) (hc : s.ncard ≤ G.universalVerts.ncard) : ∃ t ⊆ G.universalVerts, ∃ (M : Subgraph G), M.verts = s ∪ t ∧ M.IsMatching := by obtain ⟨t, ht⟩ := Set.exists_subset_card_eq hc refine ⟨t, ht.1, ?_⟩ obtain ⟨f⟩ : Nonempty (s ≃ t) := by rw [← Cardinal.eq, ← t.cast_ncard t.toFinite, ← s.cast_ncard s.toFinite, ht.2] letI hd := Set.disjoint_of_subset_left ht.1 h have hadj (v : s) : G.Adj v (f v) := ht.1 (f v).2 (hd.ne_of_mem (f v).2 v.2) exact Subgraph.IsMatching.exists_of_disjoint_sets_of_equiv hd.symm f hadj lemma disjoint_image_val_universalVerts (s : Set G.deleteUniversalVerts.verts) : Disjoint (Subtype.val '' s) G.universalVerts := by simpa [← Set.disjoint_compl_right_iff_subset, Set.compl_eq_univ_diff] using Subtype.coe_image_subset _ s /-- A component of the graph with universal vertices is even if we remove a set of representatives of odd components and a subset of universal vertices. This is because the number of vertices in the even components is not affected, and from odd components exactly one vertex is removed. -/ lemma even_ncard_image_val_supp_sdiff_image_val_rep_union {t : Set V} {s : Set G.deleteUniversalVerts.verts} (K : G.deleteUniversalVerts.coe.ConnectedComponent) (h : t ⊆ G.universalVerts) (hrep : ConnectedComponent.Represents s G.deleteUniversalVerts.coe.oddComponents) : Even (Subtype.val '' K.supp \ (Subtype.val '' s ∪ t)).ncard := by simp [-deleteUniversalVerts_verts, ← Set.diff_inter_diff, ← Set.image_diff Subtype.val_injective, sdiff_eq_left.mpr <| Set.disjoint_of_subset_right h (disjoint_image_val_universalVerts _), Set.inter_diff_distrib_right, ← Set.image_inter Subtype.val_injective, Set.ncard_image_of_injective _ Subtype.val_injective, K.even_ncard_supp_sdiff_rep hrep] end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Sum.lean
import Mathlib.Combinatorics.SimpleGraph.Basic import Mathlib.Combinatorics.SimpleGraph.Coloring import Mathlib.Combinatorics.SimpleGraph.Maps /-! # Disjoint sum of graphs This file defines the disjoint sum of graphs. The disjoint sum of `G : SimpleGraph α` and `H : SimpleGraph β` is a graph on `α ⊕ β` where `u` and `v` are adjacent if and only if they are both in `G` and adjacent in `G`, or they are both in `H` and adjacent in `H`. ## Main declarations * `SimpleGraph.Sum`: The disjoint sum of graphs. ## Notation * `G ⊕g H`: The disjoint sum of `G` and `H`. -/ variable {α β γ : Type*} namespace SimpleGraph /-- Disjoint sum of `G` and `H`. -/ @[simps!] protected def sum (G : SimpleGraph α) (H : SimpleGraph β) : SimpleGraph (α ⊕ β) where Adj | Sum.inl u, Sum.inl v => G.Adj u v | Sum.inr u, Sum.inr v => H.Adj u v | _, _ => false symm | Sum.inl u, Sum.inl v => G.adj_symm | Sum.inr u, Sum.inr v => H.adj_symm | Sum.inl _, Sum.inr _ | Sum.inr _, Sum.inl _ => id loopless u := by cases u <;> simp @[inherit_doc] infixl:60 " ⊕g " => SimpleGraph.sum variable {G : SimpleGraph α} {H : SimpleGraph β} /-- The disjoint sum is commutative up to isomorphism. `Iso.sumComm` as a graph isomorphism. -/ @[simps!] def Iso.sumComm : G ⊕g H ≃g H ⊕g G := ⟨Equiv.sumComm α β, by rintro (u | u) (v | v) <;> simp⟩ /-- The disjoint sum is associative up to isomorphism. `Iso.sumAssoc` as a graph isomorphism. -/ @[simps!] def Iso.sumAssoc {I : SimpleGraph γ} : (G ⊕g H) ⊕g I ≃g G ⊕g (H ⊕g I) := ⟨Equiv.sumAssoc α β γ, by rintro ((u | u) | u) ((v | v) | v) <;> simp⟩ /-- The embedding of `G` into `G ⊕g H`. -/ @[simps] def Embedding.sumInl : G ↪g G ⊕g H where toFun u := _root_.Sum.inl u inj' u v := by simp map_rel_iff' := by simp /-- The embedding of `H` into `G ⊕g H`. -/ @[simps] def Embedding.sumInr : H ↪g G ⊕g H where toFun u := _root_.Sum.inr u inj' u v := by simp map_rel_iff' := by simp /-- Color `G ⊕g H` with colorings of `G` and `H` -/ def Coloring.sum (cG : G.Coloring γ) (cH : H.Coloring γ) : (G ⊕g H).Coloring γ where toFun := Sum.elim cG cH map_rel' {u v} huv := by cases u <;> cases v <;> simp_all [cG.valid, cH.valid] /-- Get coloring of `G` from coloring of `G ⊕g H` -/ def Coloring.sumLeft (c : (G ⊕g H).Coloring γ) : G.Coloring γ := c.comp Embedding.sumInl.toHom /-- Get coloring of `H` from coloring of `G ⊕g H` -/ def Coloring.sumRight (c : (G ⊕g H).Coloring γ) : H.Coloring γ := c.comp Embedding.sumInr.toHom @[simp] theorem Coloring.sumLeft_sum (cG : G.Coloring γ) (cH : H.Coloring γ) : (cG.sum cH).sumLeft = cG := rfl @[simp] theorem Coloring.sumRight_sum (cG : G.Coloring γ) (cH : H.Coloring γ) : (cG.sum cH).sumRight = cH := rfl @[simp] theorem Coloring.sum_sumLeft_sumRight (c : (G ⊕g H).Coloring γ) : c.sumLeft.sum c.sumRight = c := by ext (u | u) <;> rfl /-- Bijection between `(G ⊕g H).Coloring γ` and `G.Coloring γ × H.Coloring γ` -/ def Coloring.sumEquiv : (G ⊕g H).Coloring γ ≃ G.Coloring γ × H.Coloring γ where toFun c := ⟨c.sumLeft, c.sumRight⟩ invFun p := p.1.sum p.2 left_inv c := by simp [sum_sumLeft_sumRight c] /-- Color `G ⊕g H` with `Fin (n + m)` given a coloring of `G` with `Fin n` and a coloring of `H` with `Fin m` -/ def Coloring.sumFin {n m : ℕ} (cG : G.Coloring (Fin n)) (cH : H.Coloring (Fin m)) : (G ⊕g H).Coloring (Fin (max n m)) := sum (G.recolorOfEmbedding (Fin.castLEEmb (n.le_max_left m)) cG) (H.recolorOfEmbedding (Fin.castLEEmb (n.le_max_right m)) cH) theorem Colorable.sum_max {n m : ℕ} (hG : G.Colorable n) (hH : H.Colorable m) : (G ⊕g H).Colorable (max n m) := Nonempty.intro (hG.some.sumFin hH.some) theorem Colorable.of_sum_left {n : ℕ} (h : (G ⊕g H).Colorable n) : G.Colorable n := Nonempty.intro (h.some.sumLeft) theorem Colorable.of_sum_right {n : ℕ} (h : (G ⊕g H).Colorable n) : H.Colorable n := Nonempty.intro (h.some.sumRight) @[simp] theorem colorable_sum {n : ℕ} : (G ⊕g H).Colorable n ↔ G.Colorable n ∧ H.Colorable n := ⟨fun cGH => ⟨cGH.of_sum_left, cGH.of_sum_right⟩, fun ⟨cG, cH⟩ => by rw [← n.max_self]; exact cG.sum_max cH⟩ theorem chromaticNumber_le_sum_left : G.chromaticNumber ≤ (G ⊕g H).chromaticNumber := chromaticNumber_le_of_forall_imp (fun _ h ↦ h.of_sum_left) theorem chromaticNumber_le_sum_right : H.chromaticNumber ≤ (G ⊕g H).chromaticNumber := chromaticNumber_le_of_forall_imp (fun _ h ↦ h.of_sum_right) @[simp] theorem chromaticNumber_sum : (G ⊕g H).chromaticNumber = max G.chromaticNumber H.chromaticNumber := by refine eq_max chromaticNumber_le_sum_left chromaticNumber_le_sum_right fun {d} hG hH => ?_ cases d with | top => simp | coe n => let cG : G.Coloring (Fin n) := (chromaticNumber_le_iff_colorable.mp hG).some let cH : H.Coloring (Fin n) := (chromaticNumber_le_iff_colorable.mp hH).some exact chromaticNumber_le_iff_colorable.mpr (Nonempty.intro (cG.sum cH)) end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Finsubgraph.lean
import Mathlib.CategoryTheory.CofilteredSystem import Mathlib.Combinatorics.SimpleGraph.Subgraph /-! # Homomorphisms from finite subgraphs This file defines the type of finite subgraphs of a `SimpleGraph` and proves a compactness result for homomorphisms to a finite codomain. ## Main statements * `SimpleGraph.nonempty_hom_of_forall_finite_subgraph_hom`: If every finite subgraph of a (possibly infinite) graph `G` has a homomorphism to some finite graph `F`, then there is also a homomorphism `G →g F`. ## Notation `→fg` is a module-local variant on `→g` where the domain is a finite subgraph of some supergraph `G`. ## Implementation notes The proof here uses compactness as formulated in `nonempty_sections_of_finite_inverse_system`. For finite subgraphs `G'' ≤ G'`, the inverse system `finsubgraphHomFunctor` restricts homomorphisms `G' →fg F` to domain `G''`. -/ open Set CategoryTheory universe u v variable {V : Type u} {W : Type v} {G : SimpleGraph V} {F : SimpleGraph W} namespace SimpleGraph /-- The subtype of `G.subgraph` comprising those subgraphs with finite vertex sets. -/ abbrev Finsubgraph (G : SimpleGraph V) := { G' : G.Subgraph // G'.verts.Finite } /-- A graph homomorphism from a finite subgraph of G to F. -/ abbrev FinsubgraphHom (G' : G.Finsubgraph) (F : SimpleGraph W) := G'.val.coe →g F local infixl:50 " →fg " => FinsubgraphHom namespace Finsubgraph instance : OrderBot G.Finsubgraph where bot := ⟨⊥, finite_empty⟩ bot_le _ := bot_le (α := G.Subgraph) instance : Max G.Finsubgraph := ⟨fun G₁ G₂ => ⟨G₁ ⊔ G₂, G₁.2.union G₂.2⟩⟩ instance : Min G.Finsubgraph := ⟨fun G₁ G₂ => ⟨G₁ ⊓ G₂, G₁.2.subset inter_subset_left⟩⟩ instance instSDiff : SDiff G.Finsubgraph where sdiff G₁ G₂ := ⟨G₁ \ G₂, G₁.2.subset (Subgraph.verts_mono sdiff_le)⟩ @[simp, norm_cast] lemma coe_bot : (⊥ : G.Finsubgraph) = (⊥ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_sup (G₁ G₂ : G.Finsubgraph) : ↑(G₁ ⊔ G₂) = (G₁ ⊔ G₂ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_inf (G₁ G₂ : G.Finsubgraph) : ↑(G₁ ⊓ G₂) = (G₁ ⊓ G₂ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_sdiff (G₁ G₂ : G.Finsubgraph) : ↑(G₁ \ G₂) = (G₁ \ G₂ : G.Subgraph) := rfl instance instGeneralizedCoheytingAlgebra : GeneralizedCoheytingAlgebra G.Finsubgraph := Subtype.coe_injective.generalizedCoheytingAlgebra _ coe_sup coe_inf coe_bot coe_sdiff section Finite variable [Finite V] instance instTop : Top G.Finsubgraph where top := ⟨⊤, finite_univ⟩ instance instHasCompl : HasCompl G.Finsubgraph where compl G' := ⟨G'ᶜ, Set.toFinite _⟩ instance instHNot : HNot G.Finsubgraph where hnot G' := ⟨¬G', Set.toFinite _⟩ instance instHImp : HImp G.Finsubgraph where himp G₁ G₂ := ⟨G₁ ⇨ G₂, Set.toFinite _⟩ instance instSupSet : SupSet G.Finsubgraph where sSup s := ⟨⨆ G ∈ s, ↑G, Set.toFinite _⟩ instance instInfSet : InfSet G.Finsubgraph where sInf s := ⟨⨅ G ∈ s, ↑G, Set.toFinite _⟩ @[simp, norm_cast] lemma coe_top : (⊤ : G.Finsubgraph) = (⊤ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_compl (G' : G.Finsubgraph) : ↑(G'ᶜ) = (G'ᶜ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_hnot (G' : G.Finsubgraph) : ↑(¬G') = (¬G' : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_himp (G₁ G₂ : G.Finsubgraph) : ↑(G₁ ⇨ G₂) = (G₁ ⇨ G₂ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_sSup (s : Set G.Finsubgraph) : sSup s = (⨆ G ∈ s, G : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_sInf (s : Set G.Finsubgraph) : sInf s = (⨅ G ∈ s, G : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_iSup {ι : Sort*} (f : ι → G.Finsubgraph) : ⨆ i, f i = (⨆ i, f i : G.Subgraph) := by rw [iSup, coe_sSup, iSup_range] @[simp, norm_cast] lemma coe_iInf {ι : Sort*} (f : ι → G.Finsubgraph) : ⨅ i, f i = (⨅ i, f i : G.Subgraph) := by rw [iInf, coe_sInf, iInf_range] instance instCompletelyDistribLattice : CompletelyDistribLattice G.Finsubgraph := Subtype.coe_injective.completelyDistribLattice _ coe_sup coe_inf coe_sSup coe_sInf coe_top coe_bot coe_compl coe_himp coe_hnot coe_sdiff end Finite end Finsubgraph /-- The finite subgraph of G generated by a single vertex. -/ def singletonFinsubgraph (v : V) : G.Finsubgraph := ⟨SimpleGraph.singletonSubgraph _ v, by simp⟩ /-- The finite subgraph of G generated by a single edge. -/ def finsubgraphOfAdj {u v : V} (e : G.Adj u v) : G.Finsubgraph := ⟨SimpleGraph.subgraphOfAdj _ e, by simp⟩ -- Lemmas establishing the ordering between edge- and vertex-generated subgraphs. theorem singletonFinsubgraph_le_adj_left {u v : V} {e : G.Adj u v} : singletonFinsubgraph u ≤ finsubgraphOfAdj e := by simp [singletonFinsubgraph, finsubgraphOfAdj] theorem singletonFinsubgraph_le_adj_right {u v : V} {e : G.Adj u v} : singletonFinsubgraph v ≤ finsubgraphOfAdj e := by simp [singletonFinsubgraph, finsubgraphOfAdj] /-- Given a homomorphism from a subgraph to `F`, construct its restriction to a sub-subgraph. -/ def FinsubgraphHom.restrict {G' G'' : G.Finsubgraph} (h : G'' ≤ G') (f : G' →fg F) : G'' →fg F := by refine ⟨fun ⟨v, hv⟩ => f.toFun ⟨v, h.1 hv⟩, ?_⟩ rintro ⟨u, hu⟩ ⟨v, hv⟩ huv exact f.map_rel' (h.2 huv) /-- The inverse system of finite homomorphisms. -/ def finsubgraphHomFunctor (G : SimpleGraph V) (F : SimpleGraph W) : G.Finsubgraphᵒᵖ ⥤ Type max u v where obj G' := G'.unop →fg F map g f := f.restrict (CategoryTheory.leOfHom g.unop) /-- If every finite subgraph of a graph `G` has a homomorphism to a finite graph `F`, then there is a homomorphism from the whole of `G` to `F`. -/ theorem nonempty_hom_of_forall_finite_subgraph_hom [Finite W] (h : ∀ G' : G.Subgraph, G'.verts.Finite → G'.coe →g F) : Nonempty (G →g F) := by -- Obtain a `Fintype` instance for `W`. cases nonempty_fintype W -- Establish the required interface instances. haveI : ∀ G' : G.Finsubgraphᵒᵖ, Nonempty ((finsubgraphHomFunctor G F).obj G') := fun G' => ⟨h G'.unop G'.unop.property⟩ haveI : ∀ G' : G.Finsubgraphᵒᵖ, Fintype ((finsubgraphHomFunctor G F).obj G') := by intro G' haveI : Fintype (G'.unop.val.verts : Type u) := G'.unop.property.fintype haveI : Fintype (↥G'.unop.val.verts → W) := by classical exact Pi.instFintype exact Fintype.ofInjective (fun f => f.toFun) RelHom.coe_fn_injective -- Use compactness to obtain a section. obtain ⟨u, hu⟩ := nonempty_sections_of_finite_inverse_system (finsubgraphHomFunctor G F) refine ⟨⟨fun v => ?_, ?_⟩⟩ · -- Map each vertex using the homomorphism provided for its singleton subgraph. exact (u (Opposite.op (singletonFinsubgraph v))).toFun ⟨v, by unfold singletonFinsubgraph simp⟩ · -- Prove that the above mapping preserves adjacency. intro v v' e simp only /- The homomorphism for each edge's singleton subgraph agrees with those for its source and target vertices. -/ have hv : Opposite.op (finsubgraphOfAdj e) ⟶ Opposite.op (singletonFinsubgraph v) := Quiver.Hom.op (CategoryTheory.homOfLE singletonFinsubgraph_le_adj_left) have hv' : Opposite.op (finsubgraphOfAdj e) ⟶ Opposite.op (singletonFinsubgraph v') := Quiver.Hom.op (CategoryTheory.homOfLE singletonFinsubgraph_le_adj_right) rw [← hu hv, ← hu hv'] -- Porting note: was `apply Hom.map_adj` apply Hom.map_adj (u _) ?_ -- `v` and `v'` are definitionally adjacent in `finsubgraphOfAdj e` simp [finsubgraphOfAdj] end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/CompleteMultipartite.lean
import Mathlib.Combinatorics.SimpleGraph.Coloring import Mathlib.Combinatorics.SimpleGraph.Copy import Mathlib.Combinatorics.SimpleGraph.DegreeSum import Mathlib.Combinatorics.SimpleGraph.Extremal.Turan import Mathlib.Combinatorics.SimpleGraph.Hasse /-! # Complete Multipartite Graphs A graph is complete multipartite iff non-adjacency is transitive. ## Main declarations * `SimpleGraph.IsCompleteMultipartite`: predicate for a graph to be complete multipartite. * `SimpleGraph.IsCompleteMultipartite.setoid`: the `Setoid` given by non-adjacency. * `SimpleGraph.IsCompleteMultipartite.iso`: the graph isomorphism from a graph that `IsCompleteMultipartite` to the corresponding `completeMultipartiteGraph`. * `SimpleGraph.IsPathGraph3Compl`: predicate for three vertices to witness the non-complete-multipartiteness of a graph `G`. (The name refers to the fact that the three vertices form the complement of `pathGraph 3`.) * See also: `Mathlib/Combinatorics/SimpleGraph/FiveWheelLike.lean`. The lemma `colorable_iff_isCompleteMultipartite_of_maximal_cliqueFree` states that a maximally `r + 1`-cliquefree graph is `r`-colorable iff it is complete multipartite. * `SimpleGraph.completeEquipartiteGraph`: the **complete equipartite graph** in parts of *equal* size such that two vertices are adjacent if and only if they are in different parts. ## Implementation Notes The definition of `completeEquipartiteGraph` is similar to `completeMultipartiteGraph` except that `Sigma.fst` is replaced by `Prod.fst` in the definition. The difference is that the former vertices are a product type whereas the latter vertices are a *dependent* product type. While `completeEquipartiteGraph r t` could have been defined as the specialisation `completeMultipartiteGraph (const (Fin r) (Fin t))` (or `turanGraph (r * t) r`), it is convenient to instead have a *non-dependent* *product* type for the vertices. See `completeEquipartiteGraph.completeMultipartiteGraph`, `completeEquipartiteGraph.turanGraph` for the isomorphisms between a `completeEquipartiteGraph` and a corresponding `completeMultipartiteGraph`, `turanGraph`. -/ open Finset Fintype universe u namespace SimpleGraph variable {α : Type u} /-- `G` is `IsCompleteMultipartite` iff non-adjacency is transitive -/ def IsCompleteMultipartite (G : SimpleGraph α) : Prop := Transitive (¬ G.Adj · ·) theorem bot_isCompleteMultipartite : (⊥ : SimpleGraph α).IsCompleteMultipartite := by simp [IsCompleteMultipartite, Transitive] variable {G : SimpleGraph α} /-- The setoid given by non-adjacency -/ def IsCompleteMultipartite.setoid (h : G.IsCompleteMultipartite) : Setoid α := ⟨(¬ G.Adj · ·), ⟨G.loopless, fun h' ↦ by rwa [adj_comm] at h', fun h1 h2 ↦ h h1 h2⟩⟩ lemma completeMultipartiteGraph.isCompleteMultipartite {ι : Type*} (V : ι → Type*) : (completeMultipartiteGraph V).IsCompleteMultipartite := by intro simp_all /-- The graph isomorphism from a graph `G` that `IsCompleteMultipartite` to the corresponding `completeMultipartiteGraph` (see also `isCompleteMultipartite_iff`) -/ def IsCompleteMultipartite.iso (h : G.IsCompleteMultipartite) : G ≃g completeMultipartiteGraph (fun (c : Quotient h.setoid) ↦ {x // h.setoid.r c.out x}) where toFun := fun x ↦ ⟨_, ⟨_, Quotient.mk_out x⟩⟩ invFun := fun ⟨_, x⟩ ↦ x.1 right_inv := fun ⟨_, x⟩ ↦ Sigma.subtype_ext (Quotient.mk_eq_iff_out.2 <| h.setoid.symm x.2) rfl map_rel_iff' := by simp_rw [Equiv.coe_fn_mk, comap_adj, top_adj, ne_eq, Quotient.eq] intros change ¬¬ G.Adj _ _ ↔ _ rw [not_not] lemma isCompleteMultipartite_iff : G.IsCompleteMultipartite ↔ ∃ (ι : Type u) (V : ι → Type u) (_ : ∀ i, Nonempty (V i)), Nonempty (G ≃g completeMultipartiteGraph V) := by constructor <;> intro h · exact ⟨_, _, fun _ ↦ ⟨_, h.setoid.refl _⟩, ⟨h.iso⟩⟩ · obtain ⟨_, _, _, ⟨e⟩⟩ := h intro _ _ _ h1 h2 rw [← e.map_rel_iff] at * exact completeMultipartiteGraph.isCompleteMultipartite _ h1 h2 lemma IsCompleteMultipartite.colorable_of_cliqueFree {n : ℕ} (h : G.IsCompleteMultipartite) (hc : G.CliqueFree n) : G.Colorable (n - 1) := (completeMultipartiteGraph.colorable_of_cliqueFree _ (fun _ ↦ ⟨_, h.setoid.refl _⟩) <| hc.comap h.iso.symm.toEmbedding).of_hom h.iso variable (G) in /-- The vertices `v, w₁, w₂` form an `IsPathGraph3Compl` in `G` iff `w₁w₂` is the only edge present between these three vertices. It is a witness to the non-complete-multipartite-ness of `G` (see `not_isCompleteMultipartite_iff_exists_isPathGraph3Compl`). This structure is an explicit way of saying that the induced graph on `{v, w₁, w₂}` is the complement of `P3`. -/ structure IsPathGraph3Compl (v w₁ w₂ : α) : Prop where adj : G.Adj w₁ w₂ not_adj_fst : ¬ G.Adj v w₁ not_adj_snd : ¬ G.Adj v w₂ namespace IsPathGraph3Compl variable {v w₁ w₂ : α} @[grind →] lemma ne_fst (h2 : G.IsPathGraph3Compl v w₁ w₂) : v ≠ w₁ := fun h ↦ h2.not_adj_snd (h.symm ▸ h2.adj) @[grind →] lemma ne_snd (h2 : G.IsPathGraph3Compl v w₁ w₂) : v ≠ w₂ := fun h ↦ h2.not_adj_fst (h ▸ h2.adj.symm) @[grind →] lemma fst_ne_snd (h2 : G.IsPathGraph3Compl v w₁ w₂) : w₁ ≠ w₂ := h2.adj.ne @[symm] lemma symm (h : G.IsPathGraph3Compl v w₁ w₂) : G.IsPathGraph3Compl v w₂ w₁ := by obtain ⟨h1, h2, h3⟩ := h exact ⟨h1.symm, h3, h2⟩ end IsPathGraph3Compl lemma exists_isPathGraph3Compl_of_not_isCompleteMultipartite (h : ¬ IsCompleteMultipartite G) : ∃ v w₁ w₂, G.IsPathGraph3Compl v w₁ w₂ := by rw [IsCompleteMultipartite, Transitive] at h push_neg at h obtain ⟨_, _, _, h1, h2, h3⟩ := h rw [adj_comm] at h1 exact ⟨_, _, _, h3, h1, h2⟩ lemma not_isCompleteMultipartite_iff_exists_isPathGraph3Compl : ¬ IsCompleteMultipartite G ↔ ∃ v w₁ w₂, G.IsPathGraph3Compl v w₁ w₂ := ⟨fun h ↦ G.exists_isPathGraph3Compl_of_not_isCompleteMultipartite h, fun ⟨_, _, _, h1, h2, h3⟩ ↦ fun h ↦ h (by rwa [adj_comm] at h2) h3 h1⟩ /-- Any `IsPathGraph3Compl` in `G` gives rise to a graph embedding of the complement of the path graph -/ def IsPathGraph3Compl.pathGraph3ComplEmbedding {v w₁ w₂ : α} (h : G.IsPathGraph3Compl v w₁ w₂) : (pathGraph 3)ᶜ ↪g G where toFun := fun x ↦ match x with | 0 => w₁ | 1 => v | 2 => w₂ inj' := by intro _ _ _ have := h.ne_fst have := h.ne_snd have := h.adj.ne aesop map_rel_iff' := by intro _ _ simp_rw [Function.Embedding.coeFn_mk, compl_adj, ne_eq, pathGraph_adj, not_or] have := h.adj have := h.adj.symm have h1 := h.not_adj_fst have h2 := h.not_adj_snd have ⟨_, _⟩ : ¬ G.Adj w₁ v ∧ ¬ G.Adj w₂ v := by rw [adj_comm] at h1 h2; exact ⟨h1, h2⟩ aesop /-- Embedding of `(pathGraph 3)ᶜ` into `G` that is not complete-multipartite. -/ noncomputable def pathGraph3ComplEmbeddingOf (h : ¬ G.IsCompleteMultipartite) : (pathGraph 3)ᶜ ↪g G := IsPathGraph3Compl.pathGraph3ComplEmbedding (exists_isPathGraph3Compl_of_not_isCompleteMultipartite h).choose_spec.choose_spec.choose_spec lemma not_isCompleteMultipartite_of_pathGraph3ComplEmbedding (e : (pathGraph 3)ᶜ ↪g G) : ¬ IsCompleteMultipartite G := by intro h have h0 : ¬ G.Adj (e 0) (e 1) := by simp [pathGraph_adj] have h1 : ¬ G.Adj (e 1) (e 2) := by simp [pathGraph_adj] have h2 : G.Adj (e 0) (e 2) := by simp [pathGraph_adj] exact h h0 h1 h2 theorem IsCompleteMultipartite.comap {β : Type*} {H : SimpleGraph β} (f : H ↪g G) : G.IsCompleteMultipartite → H.IsCompleteMultipartite := by intro h; contrapose h exact not_isCompleteMultipartite_of_pathGraph3ComplEmbedding <| f.comp (pathGraph3ComplEmbeddingOf h) section CompleteEquipartiteGraph variable {r t : ℕ} /-- The **complete equipartite graph** in `r` parts each of *equal* size `t` such that two vertices are adjacent if and only if they are in different parts, often denoted $K_r(t)$. This is isomorphic to a corresponding `completeMultipartiteGraph` and `turanGraph`. The difference is that the former vertices are a product type. See `completeEquipartiteGraph.completeMultipartiteGraph`, `completeEquipartiteGraph.turanGraph`. -/ abbrev completeEquipartiteGraph (r t : ℕ) : SimpleGraph (Fin r × Fin t) := SimpleGraph.comap Prod.fst ⊤ lemma completeEquipartiteGraph_adj {v w} : (completeEquipartiteGraph r t).Adj v w ↔ v.1 ≠ w.1 := by rfl /-- A `completeEquipartiteGraph` is isomorphic to a corresponding `completeMultipartiteGraph`. The difference is that the former vertices are a product type whereas the latter vertices are a *dependent* product type. -/ def completeEquipartiteGraph.completeMultipartiteGraph : completeEquipartiteGraph r t ≃g completeMultipartiteGraph (Function.const (Fin r) (Fin t)) := { (Equiv.sigmaEquivProd (Fin r) (Fin t)).symm with map_rel_iff' := by simp } /-- A `completeEquipartiteGraph` is isomorphic to a corresponding `turanGraph`. The difference is that the former vertices are a product type whereas the latter vertices are not. -/ def completeEquipartiteGraph.turanGraph : completeEquipartiteGraph r t ≃g turanGraph (r * t) r where toFun := by refine fun v ↦ ⟨v.2 * r + v.1, ?_⟩ conv_rhs => rw [← Nat.sub_one_add_one_eq_of_pos v.2.pos, Nat.mul_add_one, mul_comm r (t - 1)] exact add_lt_add_of_le_of_lt (Nat.mul_le_mul_right r (Nat.le_pred_of_lt v.2.prop)) v.1.prop invFun := by refine fun v ↦ (⟨v % r, ?_⟩, ⟨v / r, ?_⟩) · have ⟨hr, _⟩ := CanonicallyOrderedAdd.mul_pos.mp v.pos exact Nat.mod_lt v hr · exact Nat.div_lt_of_lt_mul v.prop left_inv v := by refine Prod.ext (Fin.ext ?_) (Fin.ext ?_) · conv => enter [1, 1, 1, 1, 1] rw [Nat.mul_add_mod_self_right] exact Nat.mod_eq_of_lt v.1.prop · apply le_antisymm · rw [Nat.div_le_iff_le_mul_add_pred v.1.pos, mul_comm r ↑v.2] exact Nat.add_le_add_left (Nat.le_pred_of_lt v.1.prop) (↑v.2 * r) · rw [Nat.le_div_iff_mul_le v.1.pos] exact Nat.le_add_right (↑v.2 * r) ↑v.1 right_inv v := Fin.ext (Nat.div_add_mod' v r) map_rel_iff' {v w} := by rw [turanGraph_adj, Equiv.coe_fn_mk, Nat.mul_add_mod_self_right, Nat.mod_eq_of_lt v.1.prop, Nat.mul_add_mod_self_right, Nat.mod_eq_of_lt w.1.prop, ← Fin.ext_iff.ne, ← completeEquipartiteGraph_adj] /-- `completeEquipartiteGraph r t` contains no edges when `r ≤ 1` or `t = 0`. -/ lemma completeEquipartiteGraph_eq_bot_iff : completeEquipartiteGraph r t = ⊥ ↔ r ≤ 1 ∨ t = 0 := by rw [← not_iff_not, not_or, ← ne_eq, ← edgeSet_nonempty, not_le, ← Nat.succ_le_iff, ← Fin.nontrivial_iff_two_le, ← ne_eq, ← Nat.pos_iff_ne_zero, Fin.pos_iff_nonempty] refine ⟨fun ⟨e, he⟩ ↦ ?_, fun ⟨⟨i₁, i₂, hv⟩, ⟨x⟩⟩ ↦ ?_⟩ · induction e with | _ v₁ v₂ rw [mem_edgeSet, completeEquipartiteGraph_adj] at he exact ⟨⟨v₁.1, v₂.1, he⟩, ⟨v₁.2⟩⟩ · use s((i₁, x), (i₂, x)) rw [mem_edgeSet, completeEquipartiteGraph_adj] exact hv theorem completeEquipartiteGraph.isCompleteMultipartite : (completeEquipartiteGraph r t).IsCompleteMultipartite := by rcases t.eq_zero_or_pos with ht_eq0 | ht_pos · rw [completeEquipartiteGraph_eq_bot_iff.mpr (Or.inr ht_eq0)] exact bot_isCompleteMultipartite · rw [isCompleteMultipartite_iff] use (Fin r), Function.const (Fin r) (Fin t) simp_rw [Function.const_apply, exists_prop] exact ⟨Function.const (Fin r) (Fin.pos_iff_nonempty.mp ht_pos), ⟨completeEquipartiteGraph.completeMultipartiteGraph⟩⟩ theorem neighborSet_completeEquipartiteGraph (v) : (completeEquipartiteGraph r t).neighborSet v = {v.1}ᶜ ×ˢ Set.univ := by ext; simp [ne_comm] theorem neighborFinset_completeEquipartiteGraph (v) : (completeEquipartiteGraph r t).neighborFinset v = {v.1}ᶜ ×ˢ univ := by ext; simp [ne_comm] theorem degree_completeEquipartiteGraph (v) : (completeEquipartiteGraph r t).degree v = (r - 1) * t := by rw [← card_neighborFinset_eq_degree, neighborFinset_completeEquipartiteGraph v, card_product, card_compl, card_singleton, Fintype.card_fin, card_univ, Fintype.card_fin] theorem card_edgeFinset_completeEquipartiteGraph : #(completeEquipartiteGraph r t).edgeFinset = r.choose 2 * t ^ 2 := by rw [← mul_right_inj' two_ne_zero, ← sum_degrees_eq_twice_card_edges] conv_lhs => rhs; intro v rw [degree_completeEquipartiteGraph v] rw [sum_const, smul_eq_mul, card_univ, card_prod, Fintype.card_fin, Fintype.card_fin] conv_rhs => rw [← Nat.mul_assoc, Nat.choose_two_right, Nat.mul_div_cancel' r.even_mul_pred_self.two_dvd] rw [← mul_assoc, mul_comm r _, mul_assoc t _ _, mul_comm t, mul_assoc _ t, ← pow_two] variable [Fintype α] /-- Every `n`-colorable graph is contained in a `completeEquipartiteGraph` in `n` parts (as long as the parts are at least as large as the largest color class). -/ theorem isContained_completeEquipartiteGraph_of_colorable {n : ℕ} (C : G.Coloring (Fin n)) (t : ℕ) (h : ∀ c, card (C.colorClass c) ≤ t) : G ⊑ completeEquipartiteGraph n t := by have (c : Fin n) : Nonempty (C.colorClass c ↪ Fin t) := by rw [Function.Embedding.nonempty_iff_card_le, Fintype.card_fin] exact h c have F (c : Fin n) := Classical.arbitrary (C.colorClass c ↪ Fin t) have hF {c₁ c₂ v₁ v₂} (hc : c₁ = c₂) (hv : F c₁ v₁ = F c₂ v₂) : v₁.val = v₂.val := by let v₁' : C.colorClass c₂ := ⟨v₁, by simp [← hc]⟩ have hv' : F c₁ v₁ = F c₂ v₁' := by apply congr_heq · rw [hc] · rw [Subtype.heq_iff_coe_eq] simp [hc] rw [hv'] at hv simpa [Subtype.ext_iff] using (F c₂).injective hv use ⟨fun v ↦ (C v, F (C v) ⟨v, C.mem_colorClass v⟩), C.valid⟩ intro v w h rw [Prod.mk.injEq] at h exact hF h.1 h.2 end CompleteEquipartiteGraph end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/AdjMatrix.lean
import Mathlib.Combinatorics.SimpleGraph.Connectivity.WalkCounting import Mathlib.LinearAlgebra.Matrix.Symmetric import Mathlib.LinearAlgebra.Matrix.Trace /-! # Adjacency Matrices This module defines the adjacency matrix of a graph, and provides theorems connecting graph properties to computational properties of the matrix. ## Main definitions * `Matrix.IsAdjMatrix`: `A : Matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. * `Matrix.IsAdjMatrix.to_graph`: for `A : Matrix V V α` and `h : A.IsAdjMatrix`, `h.to_graph` is the simple graph induced by `A`. * `Matrix.compl`: for `A : Matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A`. * `SimpleGraph.adjMatrix`: the adjacency matrix of a `SimpleGraph`. * `SimpleGraph.adjMatrix_pow_apply_eq_card_walk`: each entry of the `n`th power of a graph's adjacency matrix counts the number of length-`n` walks between the corresponding pair of vertices. -/ open Matrix open Finset SimpleGraph variable {V α : Type*} namespace Matrix /-- `A : Matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. -/ structure IsAdjMatrix [Zero α] [One α] (A : Matrix V V α) : Prop where zero_or_one : ∀ i j, A i j = 0 ∨ A i j = 1 := by aesop symm : A.IsSymm := by aesop apply_diag : ∀ i, A i i = 0 := by aesop namespace IsAdjMatrix variable {A : Matrix V V α} @[simp] theorem apply_diag_ne [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) (i : V) : ¬A i i = 1 := by simp [h.apply_diag i] @[simp] theorem apply_ne_one_iff [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) (i j : V) : ¬A i j = 1 ↔ A i j = 0 := by obtain h | h := h.zero_or_one i j <;> simp [h] @[simp] theorem apply_ne_zero_iff [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) (i j : V) : ¬A i j = 0 ↔ A i j = 1 := by rw [← apply_ne_one_iff h, Classical.not_not] /-- For `A : Matrix V V α` and `h : IsAdjMatrix A`, `h.toGraph` is the simple graph whose adjacency matrix is `A`. -/ @[simps] def toGraph [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) : SimpleGraph V where Adj i j := A i j = 1 symm i j hij := by simp only; rwa [h.symm.apply i j] loopless i := by simp [h] instance [MulZeroOneClass α] [Nontrivial α] [DecidableEq α] (h : IsAdjMatrix A) : DecidableRel h.toGraph.Adj := by simp only [toGraph] infer_instance end IsAdjMatrix /-- For `A : Matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A.adjMatrix`. -/ def compl [Zero α] [One α] [DecidableEq α] [DecidableEq V] (A : Matrix V V α) : Matrix V V α := fun i j => ite (i = j) 0 (ite (A i j = 0) 1 0) section Compl variable [DecidableEq α] [DecidableEq V] (A : Matrix V V α) @[simp] theorem compl_apply_diag [Zero α] [One α] (i : V) : A.compl i i = 0 := by simp [compl] @[simp] theorem compl_apply [Zero α] [One α] (i j : V) : A.compl i j = 0 ∨ A.compl i j = 1 := by unfold compl split_ifs <;> simp @[simp] theorem isSymm_compl [Zero α] [One α] (h : A.IsSymm) : A.compl.IsSymm := by ext simp [compl, h.apply, eq_comm] @[simp] theorem isAdjMatrix_compl [Zero α] [One α] (h : A.IsSymm) : IsAdjMatrix A.compl := { symm := by simp [h] } namespace IsAdjMatrix variable {A} @[simp] theorem compl [Zero α] [One α] (h : IsAdjMatrix A) : IsAdjMatrix A.compl := isAdjMatrix_compl A h.symm theorem toGraph_compl_eq [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) : h.compl.toGraph = h.toGraphᶜ := by ext v w rcases h.zero_or_one v w with h | h <;> by_cases hvw : v = w <;> simp [Matrix.compl, h, hvw] end IsAdjMatrix end Compl end Matrix namespace SimpleGraph variable (G : SimpleGraph V) [DecidableRel G.Adj] variable (α) in /-- `adjMatrix G α` is the matrix `A` such that `A i j = (1 : α)` if `i` and `j` are adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/ def adjMatrix [Zero α] [One α] : Matrix V V α := of fun i j => if G.Adj i j then (1 : α) else 0 -- TODO: set as an equation lemma for `adjMatrix`, see https://github.com/leanprover-community/mathlib4/pull/3024 @[simp] theorem adjMatrix_apply (v w : V) [Zero α] [One α] : G.adjMatrix α v w = if G.Adj v w then 1 else 0 := rfl @[simp] theorem transpose_adjMatrix [Zero α] [One α] : (G.adjMatrix α)ᵀ = G.adjMatrix α := by ext simp [adj_comm] @[simp] theorem isSymm_adjMatrix [Zero α] [One α] : (G.adjMatrix α).IsSymm := transpose_adjMatrix G variable (α) /-- The adjacency matrix of `G` is an adjacency matrix. -/ @[simp] theorem isAdjMatrix_adjMatrix [Zero α] [One α] : (G.adjMatrix α).IsAdjMatrix := { zero_or_one := fun i j => by by_cases h : G.Adj i j <;> simp [h] } /-- The graph induced by the adjacency matrix of `G` is `G` itself. -/ theorem toGraph_adjMatrix_eq [MulZeroOneClass α] [Nontrivial α] : (G.isAdjMatrix_adjMatrix α).toGraph = G := by ext simp only [IsAdjMatrix.toGraph_adj, adjMatrix_apply, ite_eq_left_iff, zero_ne_one] apply Classical.not_not variable {α} /-- The sum of the identity, the adjacency matrix, and its complement is the all-ones matrix. -/ theorem one_add_adjMatrix_add_compl_adjMatrix_eq_allOnes [DecidableEq V] [DecidableEq α] [AddMonoidWithOne α] : 1 + G.adjMatrix α + (G.adjMatrix α).compl = Matrix.of fun _ _ ↦ 1 := by ext i j unfold Matrix.compl rw [of_apply, add_apply, adjMatrix_apply, add_apply, adjMatrix_apply, one_apply] by_cases h : G.Adj i j · aesop · split_ifs <;> simp_all variable [Fintype V] @[simp] theorem adjMatrix_dotProduct [NonAssocSemiring α] (v : V) (vec : V → α) : G.adjMatrix α v ⬝ᵥ vec = ∑ u ∈ G.neighborFinset v, vec u := by simp [neighborFinset_eq_filter, dotProduct, sum_filter] @[simp] theorem dotProduct_adjMatrix [NonAssocSemiring α] (v : V) (vec : V → α) : vec ⬝ᵥ G.adjMatrix α v = ∑ u ∈ G.neighborFinset v, vec u := by simp [neighborFinset_eq_filter, dotProduct, sum_filter] @[simp] theorem adjMatrix_mulVec_apply [NonAssocSemiring α] (v : V) (vec : V → α) : (G.adjMatrix α *ᵥ vec) v = ∑ u ∈ G.neighborFinset v, vec u := by rw [mulVec, adjMatrix_dotProduct] @[simp] theorem adjMatrix_vecMul_apply [NonAssocSemiring α] (v : V) (vec : V → α) : (vec ᵥ* G.adjMatrix α) v = ∑ u ∈ G.neighborFinset v, vec u := by simp only [← dotProduct_adjMatrix, vecMul] refine congr rfl ?_; ext x rw [← transpose_apply (adjMatrix α G) x v, transpose_adjMatrix] @[simp] theorem adjMatrix_mul_apply [NonAssocSemiring α] (M : Matrix V V α) (v w : V) : (G.adjMatrix α * M) v w = ∑ u ∈ G.neighborFinset v, M u w := by simp [mul_apply, neighborFinset_eq_filter, sum_filter] @[simp] theorem mul_adjMatrix_apply [NonAssocSemiring α] (M : Matrix V V α) (v w : V) : (M * G.adjMatrix α) v w = ∑ u ∈ G.neighborFinset w, M v u := by simp [mul_apply, neighborFinset_eq_filter, sum_filter, adj_comm] variable (α) in @[simp] theorem trace_adjMatrix [AddCommMonoid α] [One α] : Matrix.trace (G.adjMatrix α) = 0 := by simp [Matrix.trace] theorem adjMatrix_mul_self_apply_self [NonAssocSemiring α] (i : V) : (G.adjMatrix α * G.adjMatrix α) i i = degree G i := by simp [filter_true_of_mem] variable {G} theorem adjMatrix_mulVec_const_apply [NonAssocSemiring α] {a : α} {v : V} : (G.adjMatrix α *ᵥ Function.const _ a) v = G.degree v * a := by simp theorem adjMatrix_mulVec_const_apply_of_regular [NonAssocSemiring α] {d : ℕ} {a : α} (hd : G.IsRegularOfDegree d) {v : V} : (G.adjMatrix α *ᵥ Function.const _ a) v = d * a := by simp [hd v] theorem adjMatrix_pow_apply_eq_card_walk [DecidableEq V] [Semiring α] (n : ℕ) (u v : V) : (G.adjMatrix α ^ n) u v = Fintype.card { p : G.Walk u v | p.length = n } := by rw [card_set_walk_length_eq] induction n generalizing u v with | zero => obtain rfl | h := eq_or_ne u v <;> simp [finsetWalkLength, *] | succ n ih => simp only [pow_succ', finsetWalkLength, ih, adjMatrix_mul_apply] rw [Finset.card_biUnion] · norm_cast simp only [Nat.cast_sum, card_map, neighborFinset_def] apply Finset.sum_toFinset_eq_subtype -- Disjointness for card_bUnion · rintro ⟨x, hx⟩ - ⟨y, hy⟩ - hxy rw [Function.onFun, disjoint_iff_inf_le] intro p hp simp only [inf_eq_inter, mem_inter, mem_map, Function.Embedding.coeFn_mk] at hp obtain ⟨⟨px, _, rfl⟩, ⟨py, hpy, hp⟩⟩ := hp cases hp simp at hxy theorem dotProduct_mulVec_adjMatrix [NonAssocSemiring α] (x y : V → α) : x ⬝ᵥ G.adjMatrix α *ᵥ y = ∑ i : V, ∑ j : V, if G.Adj i j then x i * y j else 0 := by simp only [dotProduct, mulVec, adjMatrix_apply, ite_mul, one_mul, zero_mul, mul_sum, mul_ite, mul_zero] end SimpleGraph namespace Matrix.IsAdjMatrix variable [MulZeroOneClass α] [Nontrivial α] variable {A : Matrix V V α} (h : IsAdjMatrix A) /-- If `A` is qualified as an adjacency matrix, then the adjacency matrix of the graph induced by `A` is itself. -/ theorem adjMatrix_toGraph_eq [DecidableEq α] : h.toGraph.adjMatrix α = A := by ext i j obtain h' | h' := h.zero_or_one i j <;> simp [h'] end Matrix.IsAdjMatrix
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Circulant.lean
import Mathlib.Algebra.Group.Fin.Basic import Mathlib.Combinatorics.SimpleGraph.Hasse import Mathlib.Algebra.Group.Pointwise.Set.Basic /-! # Definition of circulant graphs This file defines and proves several fact about circulant graphs. A circulant graph over type `G` with jumps `s : Set G` is a graph in which two vertices `u` and `v` are adjacent if and only if `u - v ∈ s` or `v - u ∈ s`. The elements of `s` are called jumps. ## Main declarations * `SimpleGraph.circulantGraph s`: the circulant graph over `G` with jumps `s`. * `SimpleGraph.cycleGraph n`: the cycle graph over `Fin n`. -/ namespace SimpleGraph /-- Circulant graph over additive group `G` with jumps `s` -/ @[simps!] def circulantGraph {G : Type*} [AddGroup G] (s : Set G) : SimpleGraph G := fromRel (· - · ∈ s) variable {G : Type*} [AddGroup G] (s : Set G) theorem circulantGraph_eq_erase_zero : circulantGraph s = circulantGraph (s \ {0}) := by ext (u v : G) simp only [circulantGraph, fromRel_adj, and_congr_right_iff] intro (h : u ≠ v) apply Iff.intro · intro h1 cases h1 with | inl h1 => exact Or.inl ⟨h1, sub_ne_zero_of_ne h⟩ | inr h1 => exact Or.inr ⟨h1, sub_ne_zero_of_ne h.symm⟩ · intro h1 cases h1 with | inl h1 => exact Or.inl h1.left | inr h1 => exact Or.inr h1.left theorem circulantGraph_eq_symm : circulantGraph s = circulantGraph (s ∪ (-s)) := by ext simp only [circulantGraph_adj, Set.mem_union, Set.mem_neg, neg_sub] grind instance [DecidableEq G] [DecidablePred (· ∈ s)] : DecidableRel (circulantGraph s).Adj := fun _ _ => inferInstanceAs (Decidable (_ ∧ _)) theorem circulantGraph_adj_translate {s : Set G} {u v d : G} : (circulantGraph s).Adj (u + d) (v + d) ↔ (circulantGraph s).Adj u v := by simp /-- Cycle graph over `Fin n` -/ def cycleGraph : (n : ℕ) → SimpleGraph (Fin n) | 0 => ⊥ | _ + 1 => circulantGraph {1} instance : (n : ℕ) → DecidableRel (cycleGraph n).Adj | 0 => fun _ _ => inferInstanceAs (Decidable False) | _ + 1 => inferInstanceAs (DecidableRel (circulantGraph _).Adj) theorem cycleGraph_zero_adj {u v : Fin 0} : ¬(cycleGraph 0).Adj u v := id theorem cycleGraph_zero_eq_bot : cycleGraph 0 = ⊥ := Subsingleton.elim _ _ theorem cycleGraph_one_eq_bot : cycleGraph 1 = ⊥ := Subsingleton.elim _ _ theorem cycleGraph_zero_eq_top : cycleGraph 0 = ⊤ := Subsingleton.elim _ _ theorem cycleGraph_one_eq_top : cycleGraph 1 = ⊤ := Subsingleton.elim _ _ theorem cycleGraph_two_eq_top : cycleGraph 2 = ⊤ := by simp only [SimpleGraph.ext_iff, funext_iff] decide theorem cycleGraph_three_eq_top : cycleGraph 3 = ⊤ := by simp only [SimpleGraph.ext_iff, funext_iff] decide theorem cycleGraph_one_adj {u v : Fin 1} : ¬(cycleGraph 1).Adj u v := by rw [cycleGraph_one_eq_bot] exact id theorem cycleGraph_adj {n : ℕ} {u v : Fin (n + 2)} : (cycleGraph (n + 2)).Adj u v ↔ u - v = 1 ∨ v - u = 1 := by simp only [cycleGraph, circulantGraph_adj, Set.mem_singleton_iff, and_iff_right_iff_imp] intro _ _ simp_all theorem cycleGraph_adj' {n : ℕ} {u v : Fin n} : (cycleGraph n).Adj u v ↔ (u - v).val = 1 ∨ (v - u).val = 1 := by match n with | 0 => exact u.elim0 | 1 => simp [cycleGraph_one_adj] | n + 2 => simp [cycleGraph_adj, Fin.ext_iff] theorem cycleGraph_neighborSet {n : ℕ} {v : Fin (n + 2)} : (cycleGraph (n + 2)).neighborSet v = {v - 1, v + 1} := by ext w simp only [mem_neighborSet, Set.mem_insert_iff, Set.mem_singleton_iff] rw [cycleGraph_adj, sub_eq_iff_eq_add', sub_eq_iff_eq_add', eq_sub_iff_add_eq, eq_comm] theorem cycleGraph_neighborFinset {n : ℕ} {v : Fin (n + 2)} : (cycleGraph (n + 2)).neighborFinset v = {v - 1, v + 1} := by simp [neighborFinset, cycleGraph_neighborSet] theorem cycleGraph_degree_two_le {n : ℕ} {v : Fin (n + 2)} : (cycleGraph (n + 2)).degree v = Finset.card {v - 1, v + 1} := by rw [SimpleGraph.degree, cycleGraph_neighborFinset] theorem cycleGraph_degree_three_le {n : ℕ} {v : Fin (n + 3)} : (cycleGraph (n + 3)).degree v = 2 := by rw [cycleGraph_degree_two_le, Finset.card_pair] simp only [ne_eq, sub_eq_iff_eq_add, add_assoc v, left_eq_add] exact ne_of_beq_false rfl theorem pathGraph_le_cycleGraph {n : ℕ} : pathGraph n ≤ cycleGraph n := by match n with | 0 | 1 => simp | n + 2 => intro u v h rw [pathGraph_adj] at h rw [cycleGraph_adj'] cases h with | inl h | inr h => simp [Fin.coe_sub_iff_le.mpr (Nat.lt_of_succ_le h.le).le, Nat.eq_sub_of_add_eq' h] theorem cycleGraph_preconnected {n : ℕ} : (cycleGraph n).Preconnected := (pathGraph_preconnected n).mono pathGraph_le_cycleGraph theorem cycleGraph_connected {n : ℕ} : (cycleGraph (n + 1)).Connected := (pathGraph_connected n).mono pathGraph_le_cycleGraph private def cycleGraph_EulerianCircuit_cons (n : ℕ) : ∀ m : Fin (n + 3), (cycleGraph (n + 3)).Walk m 0 | ⟨0, h⟩ => Walk.nil | ⟨m + 1, h⟩ => have hadj : (cycleGraph (n + 3)).Adj ⟨m + 1, h⟩ ⟨m, Nat.lt_of_succ_lt h⟩ := by simp [cycleGraph_adj, Fin.ext_iff, Fin.sub_val_of_le] Walk.cons hadj (cycleGraph_EulerianCircuit_cons n ⟨m, Nat.lt_of_succ_lt h⟩) /-- Eulerian trail of `cycleGraph (n + 3)` -/ def cycleGraph_EulerianCircuit (n : ℕ) : (cycleGraph (n + 3)).Walk 0 0 := have hadj : (cycleGraph (n + 3)).Adj 0 (Fin.last (n + 2)) := by simp [cycleGraph_adj] Walk.cons hadj (cycleGraph_EulerianCircuit_cons n (Fin.last (n + 2))) private theorem cycleGraph_EulerianCircuit_cons_length (n : ℕ) : ∀ m : Fin (n + 3), (cycleGraph_EulerianCircuit_cons n m).length = m.val | ⟨0, h⟩ => by unfold cycleGraph_EulerianCircuit_cons rfl | ⟨m + 1, h⟩ => by unfold cycleGraph_EulerianCircuit_cons simp only [Walk.length_cons] rw [cycleGraph_EulerianCircuit_cons_length n] theorem cycleGraph_EulerianCircuit_length {n : ℕ} : (cycleGraph_EulerianCircuit n).length = n + 3 := by unfold cycleGraph_EulerianCircuit simp [cycleGraph_EulerianCircuit_cons_length] end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Dart.lean
import Mathlib.Combinatorics.SimpleGraph.Basic import Mathlib.Data.Fintype.Sigma /-! # Darts in graphs A `Dart` or half-edge or bond in a graph is an ordered pair of adjacent vertices, regarded as an oriented edge. This file defines darts and proves some of their basic properties. -/ namespace SimpleGraph variable {V : Type*} (G : SimpleGraph V) /-- A `Dart` is an oriented edge, implemented as an ordered pair of adjacent vertices. This terminology comes from combinatorial maps, and they are also known as "half-edges" or "bonds." -/ structure Dart extends V × V where adj : G.Adj fst snd deriving DecidableEq initialize_simps_projections Dart (+toProd, -fst, -snd) attribute [simp] Dart.adj variable {G} theorem Dart.ext_iff (d₁ d₂ : G.Dart) : d₁ = d₂ ↔ d₁.toProd = d₂.toProd := by cases d₁; cases d₂; simp @[ext] theorem Dart.ext (d₁ d₂ : G.Dart) (h : d₁.toProd = d₂.toProd) : d₁ = d₂ := (Dart.ext_iff d₁ d₂).mpr h @[simp] theorem Dart.fst_ne_snd (d : G.Dart) : d.fst ≠ d.snd := fun h ↦ G.irrefl (h ▸ d.adj) @[simp] theorem Dart.snd_ne_fst (d : G.Dart) : d.snd ≠ d.fst := fun h ↦ G.irrefl (h ▸ d.adj) theorem Dart.toProd_injective : Function.Injective (Dart.toProd : G.Dart → V × V) := Dart.ext instance Dart.fintype [Fintype V] [DecidableRel G.Adj] : Fintype G.Dart := Fintype.ofEquiv (Σ v, G.neighborSet v) { toFun := fun s => ⟨(s.fst, s.snd), s.snd.property⟩ invFun := fun d => ⟨d.fst, d.snd, d.adj⟩ } /-- The edge associated to the dart. -/ def Dart.edge (d : G.Dart) : Sym2 V := Sym2.mk d.toProd @[simp] theorem Dart.edge_mk {p : V × V} (h : G.Adj p.1 p.2) : (Dart.mk p h).edge = Sym2.mk p := rfl @[simp] theorem Dart.edge_mem (d : G.Dart) : d.edge ∈ G.edgeSet := d.adj /-- The dart with reversed orientation from a given dart. -/ @[simps] def Dart.symm (d : G.Dart) : G.Dart := ⟨d.toProd.swap, G.symm d.adj⟩ @[simp] theorem Dart.symm_mk {p : V × V} (h : G.Adj p.1 p.2) : (Dart.mk p h).symm = Dart.mk p.swap h.symm := rfl @[simp] theorem Dart.edge_symm (d : G.Dart) : d.symm.edge = d.edge := Sym2.mk_prod_swap_eq @[simp] theorem Dart.edge_comp_symm : Dart.edge ∘ Dart.symm = (Dart.edge : G.Dart → Sym2 V) := funext Dart.edge_symm @[simp] theorem Dart.symm_symm (d : G.Dart) : d.symm.symm = d := Dart.ext _ _ <| Prod.swap_swap _ @[simp] theorem Dart.symm_involutive : Function.Involutive (Dart.symm : G.Dart → G.Dart) := Dart.symm_symm theorem Dart.symm_ne (d : G.Dart) : d.symm ≠ d := ne_of_apply_ne (Prod.snd ∘ Dart.toProd) d.adj.ne theorem dart_edge_eq_iff : ∀ d₁ d₂ : G.Dart, d₁.edge = d₂.edge ↔ d₁ = d₂ ∨ d₁ = d₂.symm := by rintro ⟨p, hp⟩ ⟨q, hq⟩ simp theorem dart_edge_eq_mk'_iff : ∀ {d : G.Dart} {p : V × V}, d.edge = Sym2.mk p ↔ d.toProd = p ∨ d.toProd = p.swap := by rintro ⟨p, h⟩ apply Sym2.mk_eq_mk_iff theorem dart_edge_eq_mk'_iff' : ∀ {d : G.Dart} {u v : V}, d.edge = s(u, v) ↔ d.fst = u ∧ d.snd = v ∨ d.fst = v ∧ d.snd = u := by rintro ⟨⟨a, b⟩, h⟩ u v rw [dart_edge_eq_mk'_iff] simp variable (G) /-- Two darts are said to be adjacent if they could be consecutive darts in a walk -- that is, the first dart's second vertex is equal to the second dart's first vertex. -/ def DartAdj (d d' : G.Dart) : Prop := d.snd = d'.fst /-- For a given vertex `v`, this is the bijective map from the neighbor set at `v` to the darts `d` with `d.fst = v`. -/ @[simps] def dartOfNeighborSet (v : V) (w : G.neighborSet v) : G.Dart := ⟨(v, w), w.property⟩ theorem dartOfNeighborSet_injective (v : V) : Function.Injective (G.dartOfNeighborSet v) := fun e₁ e₂ h => Subtype.ext <| by injection h with h' convert congr_arg Prod.snd h' instance nonempty_dart_top [Nontrivial V] : Nonempty (⊤ : SimpleGraph V).Dart := by obtain ⟨v, w, h⟩ := exists_pair_ne V exact ⟨⟨(v, w), h⟩⟩ end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Metric.lean
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected import Mathlib.Data.ENat.Lattice /-! # Graph metric This module defines the `SimpleGraph.edist` function, which takes pairs of vertices to the length of the shortest walk between them, or `⊤` if they are disconnected. It also defines `SimpleGraph.dist` which is the `ℕ`-valued version of `SimpleGraph.edist`. ## Main definitions - `SimpleGraph.edist` is the graph extended metric. - `SimpleGraph.dist` is the graph metric. ## TODO - Provide an additional computable version of `SimpleGraph.dist` for when `G` is connected. - When directed graphs exist, a directed notion of distance, likely `ENat`-valued. ## Tags graph metric, distance -/ assert_not_exists Field namespace SimpleGraph variable {V : Type*} (G : SimpleGraph V) /-! ## Metric -/ section edist /-- The extended distance between two vertices is the length of the shortest walk between them. It is `⊤` if no such walk exists. -/ noncomputable def edist (u v : V) : ℕ∞ := ⨅ w : G.Walk u v, w.length variable {G} {u v w : V} theorem edist_eq_sInf : G.edist u v = sInf (Set.range fun w : G.Walk u v ↦ (w.length : ℕ∞)) := rfl protected theorem Reachable.exists_walk_length_eq_edist (hr : G.Reachable u v) : ∃ p : G.Walk u v, p.length = G.edist u v := csInf_mem <| Set.range_nonempty_iff_nonempty.mpr hr protected theorem Connected.exists_walk_length_eq_edist (hconn : G.Connected) (u v : V) : ∃ p : G.Walk u v, p.length = G.edist u v := (hconn u v).exists_walk_length_eq_edist theorem edist_le (p : G.Walk u v) : G.edist u v ≤ p.length := sInf_le ⟨p, rfl⟩ protected alias Walk.edist_le := edist_le @[simp] theorem edist_eq_zero_iff : G.edist u v = 0 ↔ u = v := by apply Iff.intro <;> simp [edist, ENat.iInf_eq_zero] @[simp] theorem edist_self : edist G v v = 0 := edist_eq_zero_iff.mpr rfl theorem edist_pos_of_ne (hne : u ≠ v) : 0 < G.edist u v := pos_iff_ne_zero.mpr <| edist_eq_zero_iff.ne.mpr hne lemma edist_eq_top_of_not_reachable (h : ¬G.Reachable u v) : G.edist u v = ⊤ := by simp [edist, not_reachable_iff_isEmpty_walk.mp h] theorem reachable_of_edist_ne_top (h : G.edist u v ≠ ⊤) : G.Reachable u v := not_not.mp <| edist_eq_top_of_not_reachable.mt h lemma exists_walk_of_edist_ne_top (h : G.edist u v ≠ ⊤) : ∃ p : G.Walk u v, p.length = G.edist u v := (reachable_of_edist_ne_top h).exists_walk_length_eq_edist protected theorem edist_triangle : G.edist u w ≤ G.edist u v + G.edist v w := by cases eq_or_ne (G.edist u v) ⊤ with | inl huv => simp [huv] | inr huv => cases eq_or_ne (G.edist v w) ⊤ with | inl hvw => simp [hvw] | inr hvw => obtain ⟨p, hp⟩ := exists_walk_of_edist_ne_top huv obtain ⟨q, hq⟩ := exists_walk_of_edist_ne_top hvw rw [← hp, ← hq, ← Nat.cast_add, ← Walk.length_append] exact edist_le _ theorem edist_comm : G.edist u v = G.edist v u := by rw [edist_eq_sInf, ← Set.image_univ, ← Set.image_univ_of_surjective Walk.reverse_surjective, ← Set.image_comp, Set.image_univ, Function.comp_def] simp_rw [Walk.length_reverse, ← edist_eq_sInf] lemma exists_walk_of_edist_eq_coe {k : ℕ} (h : G.edist u v = k) : ∃ p : G.Walk u v, p.length = k := have : G.edist u v ≠ ⊤ := by rw [h]; exact ENat.coe_ne_top _ have ⟨p, hp⟩ := exists_walk_of_edist_ne_top this ⟨p, Nat.cast_injective (hp.trans h)⟩ lemma edist_ne_top_iff_reachable : G.edist u v ≠ ⊤ ↔ G.Reachable u v := by refine ⟨reachable_of_edist_ne_top, fun h ↦ ?_⟩ by_contra hx simp only [edist, iInf_eq_top, ENat.coe_ne_top] at hx exact h.elim hx /-- The extended distance between vertices is equal to `1` if and only if these vertices are adjacent. -/ @[simp] theorem edist_eq_one_iff_adj : G.edist u v = 1 ↔ G.Adj u v := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · obtain ⟨w, hw⟩ := exists_walk_of_edist_ne_top <| by rw [h]; simp exact w.adj_of_length_eq_one <| Nat.cast_eq_one.mp <| h ▸ hw · exact le_antisymm (edist_le h.toWalk) (Order.one_le_iff_pos.mpr <| edist_pos_of_ne h.ne) lemma edist_bot_of_ne (h : u ≠ v) : (⊥ : SimpleGraph V).edist u v = ⊤ := by rwa [ne_eq, ← reachable_bot.not, ← edist_ne_top_iff_reachable.not, not_not] at h lemma edist_bot [DecidableEq V] : (⊥ : SimpleGraph V).edist u v = (if u = v then 0 else ⊤) := by by_cases h : u = v <;> simp [h, edist_bot_of_ne] lemma edist_top_of_ne (h : u ≠ v) : (⊤ : SimpleGraph V).edist u v = 1 := by simp [h] lemma edist_top [DecidableEq V] : (⊤ : SimpleGraph V).edist u v = (if u = v then 0 else 1) := by by_cases h : u = v <;> simp [h] /-- Supergraphs have smaller or equal extended distances to their subgraphs. -/ @[gcongr] theorem edist_anti {G' : SimpleGraph V} (h : G ≤ G') : G'.edist u v ≤ G.edist u v := by by_cases hr : G.Reachable u v · obtain ⟨_, hw⟩ := hr.exists_walk_length_eq_edist rw [← hw, ← Walk.length_map (.ofLE h)] apply edist_le · exact edist_eq_top_of_not_reachable hr ▸ le_top end edist section dist /-- The distance between two vertices is the length of the shortest walk between them. If no such walk exists, this uses the junk value of `0`. -/ noncomputable def dist (u v : V) : ℕ := (G.edist u v).toNat variable {G} {u v w : V} theorem dist_eq_sInf : G.dist u v = sInf (Set.range (Walk.length : G.Walk u v → ℕ)) := ENat.iInf_toNat protected theorem Reachable.exists_walk_length_eq_dist (hr : G.Reachable u v) : ∃ p : G.Walk u v, p.length = G.dist u v := dist_eq_sInf ▸ Nat.sInf_mem (Set.range_nonempty_iff_nonempty.mpr hr) protected theorem Connected.exists_walk_length_eq_dist (hconn : G.Connected) (u v : V) : ∃ p : G.Walk u v, p.length = G.dist u v := dist_eq_sInf ▸ (hconn u v).exists_walk_length_eq_dist theorem dist_le (p : G.Walk u v) : G.dist u v ≤ p.length := dist_eq_sInf ▸ Nat.sInf_le ⟨p, rfl⟩ @[simp] theorem dist_eq_zero_iff_eq_or_not_reachable : G.dist u v = 0 ↔ u = v ∨ ¬G.Reachable u v := by simp [dist_eq_sInf, Nat.sInf_eq_zero, Reachable] theorem dist_self : dist G v v = 0 := by simp protected theorem Reachable.dist_eq_zero_iff (hr : G.Reachable u v) : G.dist u v = 0 ↔ u = v := by simp [hr] protected theorem Reachable.pos_dist_of_ne (h : G.Reachable u v) (hne : u ≠ v) : 0 < G.dist u v := Nat.pos_of_ne_zero (by simp [h, hne]) protected theorem Reachable.one_lt_dist_of_ne_of_not_adj (h : G.Reachable u v) (hne : u ≠ v) (hnadj : ¬G.Adj u v) : 1 < G.dist u v := Nat.lt_of_le_of_ne (h.pos_dist_of_ne hne) (by by_contra! hc obtain ⟨p, hp⟩ := Reachable.exists_walk_length_eq_dist h exact hnadj (Walk.exists_length_eq_one_iff.mp ⟨p, hc ▸ hp⟩)) protected theorem Connected.dist_eq_zero_iff (hconn : G.Connected) : G.dist u v = 0 ↔ u = v := by simp [hconn u v] protected theorem Connected.pos_dist_of_ne (hconn : G.Connected) (hne : u ≠ v) : 0 < G.dist u v := Nat.pos_of_ne_zero fun h ↦ False.elim <| hne <| (hconn.dist_eq_zero_iff).mp h protected theorem Connected.one_lt_dist_of_ne_of_not_adj (h : G.Connected) (hne : u ≠ v) (hnadj : ¬G.Adj u v) : 1 < G.dist u v := Reachable.one_lt_dist_of_ne_of_not_adj (h u v) hne hnadj theorem dist_eq_zero_of_not_reachable (h : ¬G.Reachable u v) : G.dist u v = 0 := by simp [h] theorem nonempty_of_pos_dist (h : 0 < G.dist u v) : (Set.univ : Set (G.Walk u v)).Nonempty := by rw [dist_eq_sInf] at h simpa [Set.range_nonempty_iff_nonempty, Set.nonempty_iff_univ_nonempty] using Nat.nonempty_of_pos_sInf h protected theorem Connected.dist_triangle (hconn : G.Connected) : G.dist u w ≤ G.dist u v + G.dist v w := by obtain ⟨p, hp⟩ := hconn.exists_walk_length_eq_dist u v obtain ⟨q, hq⟩ := hconn.exists_walk_length_eq_dist v w rw [← hp, ← hq, ← Walk.length_append] apply dist_le theorem dist_comm : G.dist u v = G.dist v u := by rw [dist, dist, edist_comm] lemma dist_ne_zero_iff_ne_and_reachable : G.dist u v ≠ 0 ↔ u ≠ v ∧ G.Reachable u v := by simp lemma Reachable.of_dist_ne_zero (h : G.dist u v ≠ 0) : G.Reachable u v := (dist_ne_zero_iff_ne_and_reachable.mp h).2 lemma exists_walk_of_dist_ne_zero (h : G.dist u v ≠ 0) : ∃ p : G.Walk u v, p.length = G.dist u v := (Reachable.of_dist_ne_zero h).exists_walk_length_eq_dist /-- The distance between vertices is equal to `1` if and only if these vertices are adjacent. -/ @[simp] theorem dist_eq_one_iff_adj : G.dist u v = 1 ↔ G.Adj u v := by rw [dist, ENat.toNat_eq_iff, ENat.coe_one, edist_eq_one_iff_adj] decide theorem Connected.diff_dist_adj (hG : G.Connected) (hadj : G.Adj v w) : G.dist u w = G.dist u v ∨ G.dist u w = G.dist u v + 1 ∨ G.dist u w = G.dist u v - 1 := by have : G.dist v w = 1 := dist_eq_one_iff_adj.mpr hadj have : G.dist w v = 1 := dist_eq_one_iff_adj.mpr hadj.symm have : G.dist u w ≤ G.dist u v + G.dist v w := hG.dist_triangle have : G.dist u v ≤ G.dist u w + G.dist w v := hG.dist_triangle omega theorem Walk.isPath_of_length_eq_dist (p : G.Walk u v) (hp : p.length = G.dist u v) : p.IsPath := by classical have : p.bypass = p := by apply Walk.bypass_eq_self_of_length_le calc p.length _ = G.dist u v := hp _ ≤ p.bypass.length := dist_le p.bypass rw [← this] apply Walk.bypass_isPath lemma Reachable.exists_path_of_dist (hr : G.Reachable u v) : ∃ (p : G.Walk u v), p.IsPath ∧ p.length = G.dist u v := by obtain ⟨p, h⟩ := hr.exists_walk_length_eq_dist exact ⟨p, p.isPath_of_length_eq_dist h, h⟩ lemma Connected.exists_path_of_dist (hconn : G.Connected) (u v : V) : ∃ (p : G.Walk u v), p.IsPath ∧ p.length = G.dist u v := by obtain ⟨p, h⟩ := hconn.exists_walk_length_eq_dist u v exact ⟨p, p.isPath_of_length_eq_dist h, h⟩ @[simp] lemma dist_bot : (⊥ : SimpleGraph V).dist u v = 0 := by by_cases h : u = v <;> simp [h] lemma dist_top_of_ne (h : u ≠ v) : (⊤ : SimpleGraph V).dist u v = 1 := by simp [h] lemma dist_top [DecidableEq V] : (⊤ : SimpleGraph V).dist u v = (if u = v then 0 else 1) := by by_cases h : u = v <;> simp [h] lemma length_eq_dist_of_subwalk {u' v' : V} {p₁ : G.Walk u v} {p₂ : G.Walk u' v'} (h₁ : p₁.length = G.dist u v) (h₂ : p₂.IsSubwalk p₁) : p₂.length = G.dist u' v' := by refine (dist_le _).eq_of_not_lt' fun hh ↦ ?_ obtain ⟨ru, rv, h⟩ := h₂ obtain ⟨s, _⟩ := p₂.reachable.exists_path_of_dist let r := ru.append s |>.append rv have : p₁.length = ru.length + p₂.length + rv.length := by simp [h] have : r.length = ru.length + s.length + rv.length := by simp [r] have := dist_le r cutsat /-- Supergraphs have smaller or equal distances to their subgraphs. -/ @[gcongr] protected theorem Reachable.dist_anti {G' : SimpleGraph V} (h : G ≤ G') (hr : G.Reachable u v) : G'.dist u v ≤ G.dist u v := by obtain ⟨_, hw⟩ := hr.exists_walk_length_eq_dist rw [← hw, ← Walk.length_map (.ofLE h)] apply dist_le /-- This bundles and abstracts some facts about the first three vertices of a shortest walk of length at least two: the first and third nodes are different and not connected. -/ lemma Walk.exists_adj_adj_not_adj_ne {p : G.Walk v w} (hp : p.length = G.dist v w) (hl : 1 < G.dist v w) : ∃ (x a b : V), G.Adj x a ∧ G.Adj a b ∧ ¬ G.Adj x b ∧ x ≠ b := by use v, p.getVert 1, p.getVert 2 have hnp : ¬p.Nil := by simpa [nil_iff_length_eq, hp] using Nat.ne_zero_of_lt hl have : p.tail.tail.length < p.tail.length := by rw [← p.tail.length_tail_add_one (by simp only [not_nil_iff_lt_length, ← p.length_tail_add_one hnp] at hp ⊢ cutsat)] omega have : p.tail.length < p.length := by rw [← p.length_tail_add_one hnp]; omega by_cases hv : v = p.getVert 2 · have : G.dist v w ≤ p.tail.tail.length := by simpa [hv, p.getVert_tail] using dist_le p.tail.tail cutsat by_cases hadj : G.Adj v (p.getVert 2) · have : G.dist v w ≤ p.tail.tail.length + 1 := dist_le <| p.tail.tail.cons <| p.getVert_tail ▸ hadj cutsat exact ⟨p.adj_snd hnp, p.adj_getVert_succ (hp ▸ hl), hadj, hv⟩ end dist end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Acyclic.lean
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected import Mathlib.Combinatorics.SimpleGraph.DegreeSum /-! # Acyclic graphs and trees This module introduces *acyclic graphs* (a.k.a. *forests*) and *trees*. ## Main definitions * `SimpleGraph.IsAcyclic` is a predicate for a graph having no cyclic walks. * `SimpleGraph.IsTree` is a predicate for a graph being a tree (a connected acyclic graph). ## Main statements * `SimpleGraph.isAcyclic_iff_path_unique` characterizes acyclicity in terms of uniqueness of paths between pairs of vertices. * `SimpleGraph.isAcyclic_iff_forall_edge_isBridge` characterizes acyclicity in terms of every edge being a bridge edge. * `SimpleGraph.isTree_iff_existsUnique_path` characterizes trees in terms of existence and uniqueness of paths between pairs of vertices from a nonempty vertex type. ## References The structure of the proofs for `SimpleGraph.IsAcyclic` and `SimpleGraph.IsTree`, including supporting lemmas about `SimpleGraph.IsBridge`, generally follows the high-level description for these theorems for multigraphs from [Chou1994]. ## Tags acyclic graphs, trees -/ namespace SimpleGraph open Walk variable {V V' : Type*} (G : SimpleGraph V) (G' : SimpleGraph V') /-- A graph is *acyclic* (or a *forest*) if it has no cycles. -/ def IsAcyclic : Prop := ∀ ⦃v : V⦄ (c : G.Walk v v), ¬c.IsCycle /-- A *tree* is a connected acyclic graph. -/ @[mk_iff] structure IsTree : Prop where /-- Graph is connected. -/ protected isConnected : G.Connected /-- Graph is acyclic. -/ protected IsAcyclic : G.IsAcyclic variable {G G'} @[simp] lemma isAcyclic_bot : IsAcyclic (⊥ : SimpleGraph V) := fun _a _w hw ↦ hw.ne_bot rfl /-- A graph that has an injective homomorphism to an acyclic graph is acyclic. -/ lemma IsAcyclic.comap (f : G →g G') (hinj : Function.Injective f) (h : G'.IsAcyclic) : G.IsAcyclic := fun _ _ ↦ map_isCycle_iff_of_injective hinj |>.not.mp <| h _ lemma IsAcyclic.embedding (f : G ↪g G') (h : G'.IsAcyclic) : G.IsAcyclic := h.comap f f.injective /-- Isomorphic graphs are acyclic together. -/ lemma Iso.isAcyclic_iff (f : G ≃g G') : G.IsAcyclic ↔ G'.IsAcyclic := ⟨fun h ↦ h.embedding f.symm, fun h ↦ h.embedding f⟩ /-- Isomorphic graphs are trees together. -/ lemma Iso.isTree_iff (f : G ≃g G') : G.IsTree ↔ G'.IsTree := ⟨fun ⟨hc, ha⟩ ↦ ⟨f.connected_iff.mp hc, f.isAcyclic_iff.mp ha⟩, fun ⟨hc, ha⟩ ↦ ⟨f.connected_iff.mpr hc, f.isAcyclic_iff.mpr ha⟩⟩ lemma IsAcyclic.of_map (f : V ↪ V') (h : G.map f |>.IsAcyclic) : G.IsAcyclic := h.embedding <| SimpleGraph.Embedding.map .. lemma IsAcyclic.of_comap (f : V' ↪ V) (h : G.IsAcyclic) : G.comap f |>.IsAcyclic := h.embedding <| SimpleGraph.Embedding.comap .. /-- A graph induced from an acyclic graph is acyclic. -/ lemma IsAcyclic.induce (h : G.IsAcyclic) (s : Set V) : G.induce s |>.IsAcyclic := h.of_comap _ /-- A subgraph of an acyclic graph is acyclic. -/ lemma IsAcyclic.subgraph (h : G.IsAcyclic) (H : G.Subgraph) : H.coe.IsAcyclic := h.comap _ H.hom_injective /-- A spanning subgraph of an acyclic graph is acyclic. -/ lemma IsAcyclic.anti {G' : SimpleGraph V} (hsub : G ≤ G') (h : G'.IsAcyclic) : G.IsAcyclic := h.comap ⟨_, fun h ↦ hsub h⟩ Function.injective_id /-- A connected component of an acyclic graph is a tree. -/ lemma IsAcyclic.isTree_connectedComponent (h : G.IsAcyclic) (c : G.ConnectedComponent) : c.toSimpleGraph.IsTree where isConnected := c.connected_toSimpleGraph IsAcyclic := h.comap c.toSimpleGraph_hom <| by simp [ConnectedComponent.toSimpleGraph_hom] theorem isAcyclic_iff_forall_adj_isBridge : G.IsAcyclic ↔ ∀ ⦃v w : V⦄, G.Adj v w → G.IsBridge s(v, w) := by simp_rw [isBridge_iff_adj_and_forall_cycle_notMem] constructor · intro ha v w hvw apply And.intro hvw intro u p hp cases ha p hp · rintro hb v (_ | ⟨ha, p⟩) hp · exact hp.not_of_nil · apply (hb ha).2 _ hp rw [Walk.edges_cons] apply List.mem_cons_self theorem isAcyclic_iff_forall_edge_isBridge : G.IsAcyclic ↔ ∀ ⦃e⦄, e ∈ (G.edgeSet) → G.IsBridge e := by simp [isAcyclic_iff_forall_adj_isBridge, Sym2.forall] theorem IsAcyclic.path_unique {G : SimpleGraph V} (h : G.IsAcyclic) {v w : V} (p q : G.Path v w) : p = q := by obtain ⟨p, hp⟩ := p obtain ⟨q, hq⟩ := q rw [Subtype.mk.injEq] induction p with | nil => cases (Walk.isPath_iff_eq_nil _).mp hq rfl | cons ph p ih => rw [isAcyclic_iff_forall_adj_isBridge] at h specialize h ph rw [isBridge_iff_adj_and_forall_walk_mem_edges] at h replace h := h.2 (q.append p.reverse) simp only [Walk.edges_append, Walk.edges_reverse, List.mem_append, List.mem_reverse] at h rcases h with h | h · cases q with | nil => simp at hp | cons _ q => rw [Walk.cons_isPath_iff] at hp hq simp only [Walk.edges_cons, List.mem_cons, Sym2.eq_iff, true_and] at h rcases h with (⟨h, rfl⟩ | ⟨rfl, rfl⟩) | h · cases ih hp.1 q hq.1 rfl · simp at hq · exact absurd (Walk.fst_mem_support_of_mem_edges _ h) hq.2 · rw [Walk.cons_isPath_iff] at hp exact absurd (Walk.fst_mem_support_of_mem_edges _ h) hp.2 theorem isAcyclic_of_path_unique (h : ∀ (v w : V) (p q : G.Path v w), p = q) : G.IsAcyclic := by intro v c hc simp only [Walk.isCycle_def, Ne] at hc cases c with | nil => cases hc.2.1 rfl | cons ha c' => simp only [Walk.cons_isTrail_iff, Walk.support_cons, List.tail_cons] at hc specialize h _ _ ⟨c', by simp only [Walk.isPath_def, hc.2]⟩ (Path.singleton ha.symm) rw [Path.singleton, Subtype.mk.injEq] at h simp [h] at hc theorem isAcyclic_iff_path_unique : G.IsAcyclic ↔ ∀ ⦃v w : V⦄ (p q : G.Path v w), p = q := ⟨IsAcyclic.path_unique, isAcyclic_of_path_unique⟩ theorem isTree_iff_existsUnique_path : G.IsTree ↔ Nonempty V ∧ ∀ v w : V, ∃! p : G.Walk v w, p.IsPath := by classical rw [isTree_iff, isAcyclic_iff_path_unique] constructor · rintro ⟨hc, hu⟩ refine ⟨hc.nonempty, ?_⟩ intro v w let q := (hc v w).some.toPath use q simp only [true_and, Path.isPath] intro p hp specialize hu ⟨p, hp⟩ q exact Subtype.ext_iff.mp hu · rintro ⟨hV, h⟩ refine ⟨Connected.mk ?_, ?_⟩ · intro v w obtain ⟨p, _⟩ := h v w exact p.reachable · rintro v w ⟨p, hp⟩ ⟨q, hq⟩ simp only [ExistsUnique.unique (h v w) hp hq] lemma IsTree.existsUnique_path (hG : G.IsTree) : ∀ v w, ∃! p : G.Walk v w, p.IsPath := (isTree_iff_existsUnique_path.1 hG).2 lemma IsTree.card_edgeFinset [Fintype V] [Fintype G.edgeSet] (hG : G.IsTree) : Finset.card G.edgeFinset + 1 = Fintype.card V := by have := hG.isConnected.nonempty inhabit V classical have : Finset.card ({default} : Finset V)ᶜ + 1 = Fintype.card V := by rw [Finset.card_compl, Finset.card_singleton, Nat.sub_add_cancel Fintype.card_pos] rw [← this, add_left_inj] choose f hf hf' using (hG.existsUnique_path · default) refine Eq.symm <| Finset.card_bij (fun w hw => ((f w).firstDart <| ?notNil).edge) (fun a ha => ?memEdges) ?inj ?surj case notNil => exact not_nil_of_ne (by simpa using hw) case memEdges => simp case inj => intro a ha b hb h wlog h' : (f a).length ≤ (f b).length generalizing a b · exact Eq.symm (this _ hb _ ha h.symm (le_of_not_ge h')) rw [dart_edge_eq_iff] at h obtain (h | h) := h · exact (congrArg (·.fst) h) · have h1 : ((f a).firstDart <| not_nil_of_ne (by simpa using ha)).snd = b := congrArg (·.snd) h have h3 := congrArg length (hf' _ ((f _).tail.copy h1 rfl) ?_) · rw [length_copy, ← add_left_inj 1, length_tail_add_one (not_nil_of_ne (by simpa using ha))] at h3 cutsat · simp only [isPath_copy] exact (hf _).tail case surj => simp only [mem_edgeFinset, Finset.mem_compl, Finset.mem_singleton, Sym2.forall, mem_edgeSet] intro x y h wlog h' : (f x).length ≤ (f y).length generalizing x y · rw [Sym2.eq_swap] exact this y x h.symm (le_of_not_ge h') refine ⟨y, ?_, dart_edge_eq_mk'_iff.2 <| Or.inr ?_⟩ · rintro rfl rw [← hf' _ nil IsPath.nil, length_nil, ← hf' _ (.cons h .nil) (IsPath.nil.cons <| by simpa using h.ne), length_cons, length_nil] at h' simp at h' rw [← hf' _ (.cons h.symm (f x)) ((cons_isPath_iff _ _).2 ⟨hf _, fun hy => ?contra⟩)] · simp only [firstDart_toProd, getVert_cons_succ, getVert_zero, Prod.swap_prod_mk] case contra => suffices (f x).takeUntil y hy = .cons h .nil by rw [← take_spec _ hy] at h' simp [this, hf' _ _ ((hf _).dropUntil hy)] at h' refine (hG.existsUnique_path _ _).unique ((hf _).takeUntil _) ?_ simp [h.ne] /-- A minimally connected graph is a tree. -/ lemma isTree_of_minimal_connected (h : Minimal Connected G) : IsTree G := by rw [isTree_iff, and_iff_right h.prop, isAcyclic_iff_forall_adj_isBridge] exact fun _ _ _ ↦ by_contra fun hbr ↦ h.not_prop_of_lt (by simpa [deleteEdges, ← edgeSet_ssubset_edgeSet]) <| h.prop.connected_delete_edge_of_not_isBridge hbr lemma isTree_iff_minimal_connected : IsTree G ↔ Minimal Connected G := by refine ⟨fun htree ↦ ⟨htree.isConnected, fun G' h' hle u v hadj ↦ ?_⟩, isTree_of_minimal_connected⟩ have ⟨p, hp⟩ := h'.exists_isPath u v have := congrArg Walk.edges <| congrArg Subtype.val <| htree.IsAcyclic.path_unique ⟨p.mapLe hle, hp.mapLe hle⟩ <| Path.singleton hadj simp only [edges_map, Hom.coe_ofLE, Sym2.map_id, List.map_id_fun, id_eq] at this simp [this, p.adj_of_mem_edges] /-- Every connected graph has a spanning tree. -/ lemma Connected.exists_isTree_le [Finite V] (h : G.Connected) : ∃ T ≤ G, IsTree T := by obtain ⟨T, hTG, hmin⟩ := {H : SimpleGraph V | H.Connected}.toFinite.exists_le_minimal h exact ⟨T, hTG, isTree_of_minimal_connected hmin⟩ /-- Every connected graph on `n` vertices has at least `n-1` edges. -/ lemma Connected.card_vert_le_card_edgeSet_add_one (h : G.Connected) : Nat.card V ≤ Nat.card G.edgeSet + 1 := by obtain hV | hV := (finite_or_infinite V).symm · simp have := Fintype.ofFinite obtain ⟨T, hle, hT⟩ := h.exists_isTree_le rw [Nat.card_eq_fintype_card, ← hT.card_edgeFinset, add_le_add_iff_right, Nat.card_eq_fintype_card, ← edgeFinset_card] exact Finset.card_mono <| by simpa lemma isTree_iff_connected_and_card [Finite V] : G.IsTree ↔ G.Connected ∧ Nat.card G.edgeSet + 1 = Nat.card V := by have := Fintype.ofFinite V classical refine ⟨fun h ↦ ⟨h.isConnected, by simpa using h.card_edgeFinset⟩, fun ⟨h₁, h₂⟩ ↦ ⟨h₁, ?_⟩⟩ simp_rw [isAcyclic_iff_forall_adj_isBridge] refine fun x y h ↦ by_contra fun hbr ↦ (h₁.connected_delete_edge_of_not_isBridge hbr).card_vert_le_card_edgeSet_add_one.not_gt ?_ rw [Nat.card_eq_fintype_card, ← edgeFinset_card, ← h₂, Nat.card_eq_fintype_card, ← edgeFinset_card, add_lt_add_iff_right] exact Finset.card_lt_card <| by simpa [deleteEdges] /-- The minimum degree of all vertices in a nontrivial tree is one. -/ lemma IsTree.minDegree_eq_one_of_nontrivial (h : G.IsTree) [Fintype V] [Nontrivial V] [DecidableRel G.Adj] : G.minDegree = 1 := by by_cases q : 2 ≤ G.minDegree · have := h.card_edgeFinset have := G.sum_degrees_eq_twice_card_edges have hle : ∑ v : V, 2 ≤ ∑ v, G.degree v := by gcongr exact le_trans q (G.minDegree_le_degree _) rw [Finset.sum_const, Finset.card_univ, smul_eq_mul] at hle cutsat · have := h.isConnected.preconnected.minDegree_pos_of_nontrivial cutsat /-- A nontrivial tree has a vertex of degree one. -/ lemma IsTree.exists_vert_degree_one_of_nontrivial [Fintype V] [Nontrivial V] [DecidableRel G.Adj] (h : G.IsTree) : ∃ v, G.degree v = 1 := by obtain ⟨v, hv⟩ := G.exists_minimal_degree_vertex use v rw [← hv] exact h.minDegree_eq_one_of_nontrivial end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/LineGraph.lean
import Mathlib.Combinatorics.SimpleGraph.Basic /-! # LineGraph ## Main definitions * `SimpleGraph.lineGraph` is the line graph of a simple graph `G`, with vertices as the edges of `G` and two vertices of the line graph adjacent if the corresponding edges share a vertex in `G`. ## Tags line graph -/ namespace SimpleGraph variable {V : Type*} {G : SimpleGraph V} /-- The line graph of a simple graph `G` has its vertex set as the edges of `G`, and two vertices of the line graph are adjacent if the corresponding edges share a vertex in `G`. -/ def lineGraph {V : Type*} (G : SimpleGraph V) : SimpleGraph G.edgeSet where Adj e₁ e₂ := e₁ ≠ e₂ ∧ (e₁ ∩ e₂ : Set V).Nonempty symm e₁ e₂ := by intro h; rwa [ne_comm, Set.inter_comm] lemma lineGraph_adj_iff_exists {e₁ e₂ : G.edgeSet} : (G.lineGraph).Adj e₁ e₂ ↔ e₁ ≠ e₂ ∧ ∃ v, v ∈ (e₁ : Sym2 V) ∧ v ∈ (e₂ : Sym2 V) := by simp [Set.Nonempty, lineGraph] @[simp] lemma lineGraph_bot : (⊥ : SimpleGraph V).lineGraph = ⊥ := by aesop (add simp lineGraph) end SimpleGraph
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Maps.lean
import Mathlib.Combinatorics.SimpleGraph.Dart import Mathlib.Data.FunLike.Fintype import Mathlib.Logic.Embedding.Set /-! # Maps between graphs This file defines two functions and three structures relating graphs. The structures directly correspond to the classification of functions as injective, surjective and bijective, and have corresponding notation. ## Main definitions * `SimpleGraph.map`: the graph obtained by pushing the adjacency relation through an injective function between vertex types. * `SimpleGraph.comap`: the graph obtained by pulling the adjacency relation behind an arbitrary function between vertex types. * `SimpleGraph.induce`: the subgraph induced by the given vertex set, a wrapper around `comap`. * `SimpleGraph.spanningCoe`: the supergraph without any additional edges, a wrapper around `map`. * `SimpleGraph.Hom`, `G →g H`: a graph homomorphism from `G` to `H`. * `SimpleGraph.Embedding`, `G ↪g H`: a graph embedding of `G` in `H`. * `SimpleGraph.Iso`, `G ≃g H`: a graph isomorphism between `G` and `H`. Note that a graph embedding is a stronger notion than an injective graph homomorphism, since its image is an induced subgraph. ## Implementation notes Morphisms of graphs are abbreviations for `RelHom`, `RelEmbedding` and `RelIso`. To make use of pre-existing simp lemmas, definitions involving morphisms are abbreviations as well. -/ open Function namespace SimpleGraph variable {V W X : Type*} (G : SimpleGraph V) (G' : SimpleGraph W) {u v : V} /-! ## Map and comap -/ /-- Given an injective function, there is a covariant induced map on graphs by pushing forward the adjacency relation. This is injective (see `SimpleGraph.map_injective`). -/ protected def map (f : V ↪ W) (G : SimpleGraph V) : SimpleGraph W where Adj := Relation.Map G.Adj f f symm a b := by rintro ⟨v, w, h, _⟩ aesop (add norm unfold Relation.Map) (add forward safe Adj.symm) loopless a := by aesop (add norm unfold Relation.Map) instance instDecidableMapAdj {f : V ↪ W} {a b} [Decidable (Relation.Map G.Adj f f a b)] : Decidable ((G.map f).Adj a b) := ‹Decidable (Relation.Map G.Adj f f a b)› @[simp] theorem map_adj (f : V ↪ W) (G : SimpleGraph V) (u v : W) : (G.map f).Adj u v ↔ ∃ u' v' : V, G.Adj u' v' ∧ f u' = u ∧ f v' = v := Iff.rfl theorem edgeSet_map (f : V ↪ W) (G : SimpleGraph V) : (G.map f).edgeSet = f.sym2Map '' G.edgeSet := by ext v induction v rw [mem_edgeSet, map_adj, Set.mem_image] constructor · intro ⟨a, b, hadj, ha, hb⟩ use s(a, b), hadj rw [Embedding.sym2Map_apply, Sym2.map_pair_eq, ha, hb] · intro ⟨e, hadj, he⟩ induction e rw [Embedding.sym2Map_apply, Sym2.map_pair_eq, Sym2.eq_iff] at he exact he.elim (fun ⟨h, h'⟩ ↦ ⟨_, _, hadj, h, h'⟩) (fun ⟨h', h⟩ ↦ ⟨_, _, hadj.symm, h, h'⟩) lemma map_adj_apply {G : SimpleGraph V} {f : V ↪ W} {a b : V} : (G.map f).Adj (f a) (f b) ↔ G.Adj a b := by simp theorem map_monotone (f : V ↪ W) : Monotone (SimpleGraph.map f) := by rintro G G' h _ _ ⟨u, v, ha, rfl, rfl⟩ exact ⟨_, _, h ha, rfl, rfl⟩ @[simp] lemma map_id : G.map (Function.Embedding.refl _) = G := SimpleGraph.ext <| Relation.map_id_id _ @[simp] lemma map_map (f : V ↪ W) (g : W ↪ X) : (G.map f).map g = G.map (f.trans g) := SimpleGraph.ext <| Relation.map_map _ _ _ _ _ theorem support_map (f : V ↪ W) (G : SimpleGraph V) : (G.map f).support = f '' G.support := by ext; simp [mem_support] /-- Given a function, there is a contravariant induced map on graphs by pulling back the adjacency relation. This is one of the ways of creating induced graphs. See `SimpleGraph.induce` for a wrapper. This is surjective when `f` is injective (see `SimpleGraph.comap_surjective`). -/ protected def comap (f : V → W) (G : SimpleGraph W) : SimpleGraph V where Adj u v := G.Adj (f u) (f v) symm _ _ h := h.symm loopless _ := G.loopless _ @[simp] lemma comap_adj {G : SimpleGraph W} {f : V → W} : (G.comap f).Adj u v ↔ G.Adj (f u) (f v) := Iff.rfl @[simp] lemma comap_id {G : SimpleGraph V} : G.comap id = G := SimpleGraph.ext rfl @[simp] lemma comap_comap {G : SimpleGraph X} (f : V → W) (g : W → X) : (G.comap g).comap f = G.comap (g ∘ f) := rfl instance instDecidableComapAdj (f : V → W) (G : SimpleGraph W) [DecidableRel G.Adj] : DecidableRel (G.comap f).Adj := fun _ _ ↦ ‹DecidableRel G.Adj› _ _ lemma comap_symm (G : SimpleGraph V) (e : V ≃ W) : G.comap e.symm.toEmbedding = G.map e.toEmbedding := by ext; simp only [Equiv.apply_eq_iff_eq_symm_apply, comap_adj, map_adj, Equiv.toEmbedding_apply, exists_eq_right_right, exists_eq_right] lemma map_symm (G : SimpleGraph W) (e : V ≃ W) : G.map e.symm.toEmbedding = G.comap e.toEmbedding := by rw [← comap_symm, e.symm_symm] theorem comap_monotone (f : V ↪ W) : Monotone (SimpleGraph.comap f) := fun _ _ h _ _ ha ↦ h ha @[simp] lemma comap_bot (f : V → W) : (emptyGraph W).comap f = emptyGraph V := rfl lemma comap_top {f : V → W} (hf : f.Injective) : (completeGraph W).comap f = completeGraph V := by ext; simp [hf.eq_iff] @[simp] theorem comap_map_eq (f : V ↪ W) (G : SimpleGraph V) : (G.map f).comap f = G := by ext simp theorem leftInverse_comap_map (f : V ↪ W) : Function.LeftInverse (SimpleGraph.comap f) (SimpleGraph.map f) := comap_map_eq f theorem map_injective (f : V ↪ W) : Function.Injective (SimpleGraph.map f) := (leftInverse_comap_map f).injective theorem comap_surjective (f : V ↪ W) : Function.Surjective (SimpleGraph.comap f) := (leftInverse_comap_map f).surjective theorem map_le_iff_le_comap (f : V ↪ W) (G : SimpleGraph V) (G' : SimpleGraph W) : G.map f ≤ G' ↔ G ≤ G'.comap f := ⟨fun h _ _ ha => h ⟨_, _, ha, rfl, rfl⟩, by rintro h _ _ ⟨u, v, ha, rfl, rfl⟩ exact h ha⟩ theorem map_comap_le (f : V ↪ W) (G : SimpleGraph W) : (G.comap f).map f ≤ G := by rw [map_le_iff_le_comap] lemma le_comap_of_subsingleton (f : V → W) [Subsingleton V] : G ≤ G'.comap f := by intro v w; simp [Subsingleton.elim v w] lemma map_le_of_subsingleton (f : V ↪ W) [Subsingleton V] : G.map f ≤ G' := by rw [map_le_iff_le_comap]; apply le_comap_of_subsingleton /-- Given a family of vertex types indexed by `ι`, pulling back from `⊤ : SimpleGraph ι` yields the complete multipartite graph on the family. Two vertices are adjacent if and only if their indices are not equal. -/ abbrev completeMultipartiteGraph {ι : Type*} (V : ι → Type*) : SimpleGraph (Σ i, V i) := SimpleGraph.comap Sigma.fst ⊤ /-- Equivalent types have equivalent simple graphs. -/ @[simps apply] protected def _root_.Equiv.simpleGraph (e : V ≃ W) : SimpleGraph V ≃ SimpleGraph W where toFun := SimpleGraph.comap e.symm invFun := SimpleGraph.comap e left_inv _ := by simp right_inv _ := by simp @[simp] lemma _root_.Equiv.simpleGraph_refl : (Equiv.refl V).simpleGraph = Equiv.refl _ := by ext; rfl @[simp] lemma _root_.Equiv.simpleGraph_trans (e₁ : V ≃ W) (e₂ : W ≃ X) : (e₁.trans e₂).simpleGraph = e₁.simpleGraph.trans e₂.simpleGraph := rfl @[simp] lemma _root_.Equiv.symm_simpleGraph (e : V ≃ W) : e.simpleGraph.symm = e.symm.simpleGraph := rfl /-! ## Induced graphs -/ /- Given a set `s` of vertices, we can restrict a graph to those vertices by restricting its adjacency relation. This gives a map between `SimpleGraph V` and `SimpleGraph s`. There is also a notion of induced subgraphs (see `SimpleGraph.Subgraph.induce`). -/ /-- Restrict a graph to the vertices in the set `s`, deleting all edges incident to vertices outside the set. This is a wrapper around `SimpleGraph.comap`. -/ abbrev induce (s : Set V) (G : SimpleGraph V) : SimpleGraph s := G.comap (Function.Embedding.subtype _) variable {G} in lemma induce_adj {s : Set V} {u v : s} : (G.induce s).Adj u v ↔ G.Adj u v := .rfl @[simp] lemma induce_top (s : Set V) : (completeGraph V).induce s = completeGraph s := comap_top Subtype.val_injective @[simp] lemma induce_singleton_eq_top (v : V) : G.induce {v} = ⊤ := by rw [eq_top_iff]; apply le_comap_of_subsingleton /-- Given a graph on a set of vertices, we can make it be a `SimpleGraph V` by adding in the remaining vertices without adding in any additional edges. This is a wrapper around `SimpleGraph.map`. -/ abbrev spanningCoe {s : Set V} (G : SimpleGraph s) : SimpleGraph V := G.map (Function.Embedding.subtype _) theorem induce_spanningCoe {s : Set V} {G : SimpleGraph s} : G.spanningCoe.induce s = G := comap_map_eq _ _ theorem spanningCoe_induce_le (s : Set V) : (G.induce s).spanningCoe ≤ G := map_comap_le _ _ open Set.Notation in theorem IsCompleteBetween.induce {s t : Set V} (h : G.IsCompleteBetween s t) (u : Set V) : (G.induce u).IsCompleteBetween (u ↓∩ s) (u ↓∩ t) := by intro _ hs _ ht rw [comap_adj, Embedding.coe_subtype] exact h hs ht /-! ## Homomorphisms, embeddings and isomorphisms -/ /-- A graph homomorphism is a map on vertex sets that respects adjacency relations. The notation `G →g G'` represents the type of graph homomorphisms. -/ abbrev Hom := RelHom G.Adj G'.Adj /-- A graph embedding is an embedding `f` such that for vertices `v w : V`, `G'.Adj (f v) (f w) ↔ G.Adj v w`. Its image is an induced subgraph of G'. The notation `G ↪g G'` represents the type of graph embeddings. -/ abbrev Embedding := RelEmbedding G.Adj G'.Adj /-- A graph isomorphism is a bijective map on vertex sets that respects adjacency relations. The notation `G ≃g G'` represents the type of graph isomorphisms. -/ abbrev Iso := RelIso G.Adj G'.Adj @[inherit_doc] infixl:50 " →g " => Hom @[inherit_doc] infixl:50 " ↪g " => Embedding @[inherit_doc] infixl:50 " ≃g " => Iso namespace Hom variable {G G'} {G₁ G₂ : SimpleGraph V} {H : SimpleGraph W} (f : G →g G') /-- The identity homomorphism from a graph to itself. -/ protected abbrev id : G →g G := RelHom.id _ @[simp, norm_cast] lemma coe_id : ⇑(Hom.id : G →g G) = id := rfl instance [Subsingleton (V → W)] : Subsingleton (G →g H) := DFunLike.coe_injective.subsingleton instance [IsEmpty V] : Unique (G →g H) where default := ⟨isEmptyElim, fun {a} ↦ isEmptyElim a⟩ uniq _ := Subsingleton.elim _ _ instance [Finite V] [Finite W] : Finite (G →g H) := DFunLike.finite _ theorem map_adj {v w : V} (h : G.Adj v w) : G'.Adj (f v) (f w) := f.map_rel' h theorem map_mem_edgeSet {e : Sym2 V} (h : e ∈ G.edgeSet) : e.map f ∈ G'.edgeSet := Sym2.ind (fun _ _ => f.map_rel') e h theorem apply_mem_neighborSet {v w : V} (h : w ∈ G.neighborSet v) : f w ∈ G'.neighborSet (f v) := map_adj f h /-- The map between edge sets induced by a homomorphism. The underlying map on edges is given by `Sym2.map`. -/ @[simps] def mapEdgeSet (e : G.edgeSet) : G'.edgeSet := ⟨Sym2.map f e, f.map_mem_edgeSet e.property⟩ /-- The map between neighbor sets induced by a homomorphism. -/ @[simps] def mapNeighborSet (v : V) (w : G.neighborSet v) : G'.neighborSet (f v) := ⟨f w, f.apply_mem_neighborSet w.property⟩ /-- The map between darts induced by a homomorphism. -/ def mapDart (d : G.Dart) : G'.Dart := ⟨d.1.map f f, f.map_adj d.2⟩ @[simp] theorem mapDart_apply (d : G.Dart) : f.mapDart d = ⟨d.1.map f f, f.map_adj d.2⟩ := rfl /-- The graph homomorphism from a smaller graph to a bigger one. -/ def ofLE (h : G₁ ≤ G₂) : G₁ →g G₂ := ⟨id, @h⟩ @[simp, norm_cast] lemma coe_ofLE (h : G₁ ≤ G₂) : ⇑(ofLE h) = id := rfl lemma ofLE_apply (h : G₁ ≤ G₂) (v : V) : ofLE h v = v := rfl theorem mapEdgeSet.injective (hinj : Function.Injective f) : Function.Injective f.mapEdgeSet := by rintro ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ dsimp [Hom.mapEdgeSet] repeat rw [Subtype.mk_eq_mk] apply Sym2.map.injective hinj /-- Every graph homomorphism from a complete graph is injective. -/ theorem injective_of_top_hom (f : (⊤ : SimpleGraph V) →g G') : Function.Injective f := by intro v w h contrapose! h exact G'.ne_of_adj (map_adj _ ((top_adj _ _).mpr h)) /-- There is a homomorphism to a graph from a comapped graph. When the function is injective, this is an embedding (see `SimpleGraph.Embedding.comap`). -/ @[simps] protected def comap (f : V → W) (G : SimpleGraph W) : G.comap f →g G where toFun := f map_rel' := by simp variable {G'' : SimpleGraph X} /-- Composition of graph homomorphisms. -/ abbrev comp (f' : G' →g G'') (f : G →g G') : G →g G'' := RelHom.comp f' f @[simp] theorem coe_comp (f' : G' →g G'') (f : G →g G') : ⇑(f'.comp f) = f' ∘ f := rfl end Hom namespace Embedding variable {G G'} {H : SimpleGraph W} (f : G ↪g G') /-- The identity embedding from a graph to itself. -/ abbrev refl : G ↪g G := RelEmbedding.refl _ /-- An embedding of graphs gives rise to a homomorphism of graphs. -/ abbrev toHom : G →g G' := f.toRelHom @[simp] lemma coe_toHom (f : G ↪g H) : ⇑f.toHom = f := rfl @[simp] theorem map_adj_iff {v w : V} : G'.Adj (f v) (f w) ↔ G.Adj v w := f.map_rel_iff theorem map_mem_edgeSet_iff {e : Sym2 V} : e.map f ∈ G'.edgeSet ↔ e ∈ G.edgeSet := Sym2.ind (fun _ _ => f.map_adj_iff) e theorem apply_mem_neighborSet_iff {v w : V} : f w ∈ G'.neighborSet (f v) ↔ w ∈ G.neighborSet v := map_adj_iff f /-- A graph embedding induces an embedding of edge sets. -/ @[simps] def mapEdgeSet : G.edgeSet ↪ G'.edgeSet where toFun := Hom.mapEdgeSet f inj' := Hom.mapEdgeSet.injective f.toRelHom f.injective /-- A graph embedding induces an embedding of neighbor sets. -/ @[simps] def mapNeighborSet (v : V) : G.neighborSet v ↪ G'.neighborSet (f v) where toFun w := ⟨f w, f.apply_mem_neighborSet_iff.mpr w.2⟩ inj' := by rintro ⟨w₁, h₁⟩ ⟨w₂, h₂⟩ h rw [Subtype.mk_eq_mk] at h ⊢ exact f.inj' h /-- Given an injective function, there is an embedding from the comapped graph into the original graph. -/ -- Porting note: @[simps] does not work here since `f` is not a constructor application. -- `@[simps toEmbedding]` could work, but Floris suggested writing `comap_apply` for now. protected def comap (f : V ↪ W) (G : SimpleGraph W) : G.comap f ↪g G := { f with map_rel_iff' := by simp } @[simp] theorem comap_apply (f : V ↪ W) (G : SimpleGraph W) (v : V) : SimpleGraph.Embedding.comap f G v = f v := rfl /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ -- Porting note: @[simps] does not work here since `f` is not a constructor application. -- `@[simps toEmbedding]` could work, but Floris suggested writing `map_apply` for now. protected def map (f : V ↪ W) (G : SimpleGraph V) : G ↪g G.map f := { f with map_rel_iff' := by simp } @[simp] theorem map_apply (f : V ↪ W) (G : SimpleGraph V) (v : V) : SimpleGraph.Embedding.map f G v = f v := rfl /-- Induced graphs embed in the original graph. Note that if `G.induce s = ⊤` (i.e., if `s` is a clique) then this gives the embedding of a complete graph. -/ protected abbrev induce (s : Set V) : G.induce s ↪g G := SimpleGraph.Embedding.comap (Function.Embedding.subtype _) G /-- Graphs on a set of vertices embed in their `spanningCoe`. -/ protected abbrev spanningCoe {s : Set V} (G : SimpleGraph s) : G ↪g G.spanningCoe := SimpleGraph.Embedding.map (Function.Embedding.subtype _) G /-- Embeddings of types induce embeddings of complete graphs on those types. -/ protected def completeGraph {α β : Type*} (f : α ↪ β) : completeGraph α ↪g completeGraph β := { f with map_rel_iff' := by simp } @[simp] lemma coe_completeGraph {α β : Type*} (f : α ↪ β) : ⇑(Embedding.completeGraph f) = f := rfl variable {G'' : SimpleGraph X} /-- Composition of graph embeddings. -/ abbrev comp (f' : G' ↪g G'') (f : G ↪g G') : G ↪g G'' := f.trans f' @[simp] theorem coe_comp (f' : G' ↪g G'') (f : G ↪g G') : ⇑(f'.comp f) = f' ∘ f := rfl /-- Graph embeddings from `G` to `H` are the same thing as graph embeddings from `Gᶜ` to `Hᶜ`. -/ def complEquiv : G ↪g H ≃ Gᶜ ↪g Hᶜ where toFun f := ⟨f.toEmbedding, by simp⟩ invFun f := ⟨f.toEmbedding, fun {v w} ↦ by obtain rfl | hvw := eq_or_ne v w · simp · simpa [hvw, not_iff_not] using f.map_adj_iff (v := v) (w := w)⟩ end Embedding section induceHom variable {G G'} {G'' : SimpleGraph X} {s : Set V} {t : Set W} {r : Set X} (φ : G →g G') (φst : Set.MapsTo φ s t) (ψ : G' →g G'') (ψtr : Set.MapsTo ψ t r) /-- The restriction of a morphism of graphs to induced subgraphs. -/ def induceHom : G.induce s →g G'.induce t where toFun := Set.MapsTo.restrict φ s t φst map_rel' := φ.map_rel' @[simp, norm_cast] lemma coe_induceHom : ⇑(induceHom φ φst) = Set.MapsTo.restrict φ s t φst := rfl @[simp] lemma induceHom_id (G : SimpleGraph V) (s) : induceHom (Hom.id : G →g G) (Set.mapsTo_id s) = Hom.id := by ext x rfl @[simp] lemma induceHom_comp : (induceHom ψ ψtr).comp (induceHom φ φst) = induceHom (ψ.comp φ) (ψtr.comp φst) := by ext x rfl lemma induceHom_injective (hi : Set.InjOn φ s) : Function.Injective (induceHom φ φst) := by simpa [Set.MapsTo.restrict_inj] end induceHom section induceHomLE variable {s s' : Set V} (h : s ≤ s') /-- Given an inclusion of vertex subsets, the induced embedding on induced graphs. This is not an abbreviation for `induceHom` since we get an embedding in this case. -/ def induceHomOfLE (h : s ≤ s') : G.induce s ↪g G.induce s' where toEmbedding := Set.embeddingOfSubset s s' h map_rel_iff' := by simp @[simp] lemma induceHomOfLE_apply (v : s) : (G.induceHomOfLE h) v = Set.inclusion h v := rfl @[simp] lemma induceHomOfLE_toHom : (G.induceHomOfLE h).toHom = induceHom (.id : G →g G) ((Set.mapsTo_id s).mono_right h) := by ext; simp end induceHomLE namespace Iso variable {G G'} (f : G ≃g G') /-- The identity isomorphism of a graph with itself. -/ abbrev refl : G ≃g G := RelIso.refl _ /-- An isomorphism of graphs gives rise to an embedding of graphs. -/ abbrev toEmbedding : G ↪g G' := f.toRelEmbedding /-- An isomorphism of graphs gives rise to a homomorphism of graphs. -/ abbrev toHom : G →g G' := f.toEmbedding.toHom /-- The inverse of a graph isomorphism. -/ abbrev symm : G' ≃g G := RelIso.symm f theorem map_adj_iff {v w : V} : G'.Adj (f v) (f w) ↔ G.Adj v w := f.map_rel_iff theorem map_mem_edgeSet_iff {e : Sym2 V} : e.map f ∈ G'.edgeSet ↔ e ∈ G.edgeSet := Sym2.ind (fun _ _ => f.map_adj_iff) e theorem apply_mem_neighborSet_iff {v w : V} : f w ∈ G'.neighborSet (f v) ↔ w ∈ G.neighborSet v := map_adj_iff f @[simp] theorem symm_toHom_comp_toHom : f.symm.toHom.comp f.toHom = Hom.id := by ext v simp only [RelHom.comp_apply, RelEmbedding.coe_toRelHom, RelIso.coe_toRelEmbedding, RelIso.symm_apply_apply, RelHom.id_apply] @[simp] theorem toHom_comp_symm_toHom : f.toHom.comp f.symm.toHom = Hom.id := by ext v simp only [RelHom.comp_apply, RelEmbedding.coe_toRelHom, RelIso.coe_toRelEmbedding, RelIso.apply_symm_apply, RelHom.id_apply] /-- An isomorphism of graphs induces an equivalence of edge sets. -/ @[simps] def mapEdgeSet : G.edgeSet ≃ G'.edgeSet where toFun := Hom.mapEdgeSet f invFun := Hom.mapEdgeSet f.symm left_inv := by rintro ⟨e, h⟩ simp only [Hom.mapEdgeSet, RelEmbedding.toRelHom, Embedding.toFun_eq_coe, RelEmbedding.coe_toEmbedding, RelIso.coe_toRelEmbedding, Sym2.map_map, comp_apply, Subtype.mk.injEq] convert congr_fun Sym2.map_id e exact RelIso.symm_apply_apply _ _ right_inv := by rintro ⟨e, h⟩ simp only [Hom.mapEdgeSet, RelEmbedding.toRelHom, Embedding.toFun_eq_coe, RelEmbedding.coe_toEmbedding, RelIso.coe_toRelEmbedding, Sym2.map_map, comp_apply, Subtype.mk.injEq] convert congr_fun Sym2.map_id e exact RelIso.apply_symm_apply _ _ /-- A graph isomorphism induces an equivalence of neighbor sets. -/ @[simps] def mapNeighborSet (v : V) : G.neighborSet v ≃ G'.neighborSet (f v) where toFun w := ⟨f w, f.apply_mem_neighborSet_iff.mpr w.2⟩ invFun w := ⟨f.symm w, by simpa [RelIso.symm_apply_apply] using f.symm.apply_mem_neighborSet_iff.mpr w.2⟩ left_inv w := by simp right_inv w := by simp include f in theorem card_eq [Fintype V] [Fintype W] : Fintype.card V = Fintype.card W := by rw [← Fintype.ofEquiv_card f.toEquiv] convert rfl /-- Given a bijection, there is an embedding from the comapped graph into the original graph. -/ -- Porting note: `@[simps]` does not work here anymore since `f` is not a constructor application. -- `@[simps toEmbedding]` could work, but Floris suggested writing `comap_apply` for now. protected def comap (f : V ≃ W) (G : SimpleGraph W) : G.comap f.toEmbedding ≃g G := { f with map_rel_iff' := by simp } @[simp] lemma comap_apply (f : V ≃ W) (G : SimpleGraph W) (v : V) : SimpleGraph.Iso.comap f G v = f v := rfl @[simp] lemma comap_symm_apply (f : V ≃ W) (G : SimpleGraph W) (w : W) : (SimpleGraph.Iso.comap f G).symm w = f.symm w := rfl /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ -- Porting note: `@[simps]` does not work here anymore since `f` is not a constructor application. -- `@[simps toEmbedding]` could work, but Floris suggested writing `map_apply` for now. protected def map (f : V ≃ W) (G : SimpleGraph V) : G ≃g G.map f.toEmbedding := { f with map_rel_iff' := by simp } @[simp] lemma map_apply (f : V ≃ W) (G : SimpleGraph V) (v : V) : SimpleGraph.Iso.map f G v = f v := rfl @[simp] lemma map_symm_apply (f : V ≃ W) (G : SimpleGraph V) (w : W) : (SimpleGraph.Iso.map f G).symm w = f.symm w := rfl /-- Equivalences of types induce isomorphisms of complete graphs on those types. -/ protected def completeGraph {α β : Type*} (f : α ≃ β) : completeGraph α ≃g completeGraph β := { f with map_rel_iff' := by simp } theorem toEmbedding_completeGraph {α β : Type*} (f : α ≃ β) : (Iso.completeGraph f).toEmbedding = Embedding.completeGraph f.toEmbedding := rfl variable {G'' : SimpleGraph X} /-- Composition of graph isomorphisms. -/ abbrev comp (f' : G' ≃g G'') (f : G ≃g G') : G ≃g G'' := f.trans f' @[simp] theorem coe_comp (f' : G' ≃g G'') (f : G ≃g G') : ⇑(f'.comp f) = f' ∘ f := rfl end Iso /-- The graph induced on `Set.univ` is isomorphic to the original graph. -/ @[simps!] def induceUnivIso (G : SimpleGraph V) : G.induce Set.univ ≃g G where toEquiv := Equiv.Set.univ V map_rel_iff' := by simp only [Equiv.Set.univ, Equiv.coe_fn_mk, comap_adj, Embedding.coe_subtype, implies_true] section Finite variable [Fintype V] {n : ℕ} /-- Given a graph over a finite vertex type `V` and a proof `hc` that `Fintype.card V = n`, `G.overFin n` is an isomorphic (as shown in `overFinIso`) graph over `Fin n`. -/ def overFin (hc : Fintype.card V = n) : SimpleGraph (Fin n) where Adj x y := G.Adj ((Fintype.equivFinOfCardEq hc).symm x) ((Fintype.equivFinOfCardEq hc).symm y) symm x y := by simp_rw [adj_comm, imp_self] /-- The isomorphism between `G` and `G.overFin hc`. -/ noncomputable def overFinIso (hc : Fintype.card V = n) : G ≃g G.overFin hc := by use Fintype.equivFinOfCardEq hc; simp [overFin] end Finite end SimpleGraph