source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Girth.lean | import Mathlib.Combinatorics.SimpleGraph.Acyclic
import Mathlib.Data.ENat.Lattice
/-!
# Girth of a simple graph
This file defines the girth and the extended girth of a simple graph as the length of its smallest
cycle, they give `0` or `∞` respectively if the graph is acyclic.
## TODO
- Prove that `G.egirth ≤ 2 * G.ediam + 1` and `G.girth ≤ 2 * G.diam + 1` when the diameter is
non-zero.
-/
namespace SimpleGraph
variable {α : Type*} {G : SimpleGraph α}
section egirth
/--
The extended girth of a simple graph is the length of its smallest cycle, or `∞` if the graph is
acyclic.
-/
noncomputable def egirth (G : SimpleGraph α) : ℕ∞ :=
⨅ a, ⨅ w : G.Walk a a, ⨅ _ : w.IsCycle, w.length
@[simp]
lemma le_egirth {n : ℕ∞} : n ≤ G.egirth ↔ ∀ a (w : G.Walk a a), w.IsCycle → n ≤ w.length := by
simp [egirth]
lemma egirth_le_length {a} {w : G.Walk a a} (h : w.IsCycle) : G.egirth ≤ w.length :=
le_egirth.mp le_rfl a w h
@[simp]
lemma egirth_eq_top : G.egirth = ⊤ ↔ G.IsAcyclic := by simp [egirth, IsAcyclic]
protected alias ⟨_, IsAcyclic.egirth_eq_top⟩ := egirth_eq_top
lemma egirth_anti : Antitone (egirth : SimpleGraph α → ℕ∞) :=
fun G H h ↦ iInf_mono fun a ↦ iInf₂_mono' fun w hw ↦ ⟨w.mapLe h, hw.mapLe _, by simp⟩
lemma exists_egirth_eq_length :
(∃ (a : α) (w : G.Walk a a), w.IsCycle ∧ G.egirth = w.length) ↔ ¬ G.IsAcyclic := by
refine ⟨?_, fun h ↦ ?_⟩
· rintro ⟨a, w, hw, _⟩ hG
exact hG _ hw
· simp_rw [← egirth_eq_top, ← Ne.eq_def, egirth, iInf_subtype', iInf_sigma', ENat.iInf_coe_ne_top,
← exists_prop, Subtype.exists', Sigma.exists', eq_comm] at h ⊢
exact ciInf_mem _
lemma three_le_egirth : 3 ≤ G.egirth := by
by_cases h : G.IsAcyclic
· rw [← egirth_eq_top] at h
rw [h]
apply le_top
· rw [← exists_egirth_eq_length] at h
have ⟨_, _, _⟩ := h
simp_all only [Nat.cast_inj, Nat.ofNat_le_cast, Walk.IsCycle.three_le_length]
@[simp] lemma egirth_bot : egirth (⊥ : SimpleGraph α) = ⊤ := by simp
end egirth
section girth
/--
The girth of a simple graph is the length of its smallest cycle, or junk value `0` if the graph is
acyclic.
-/
noncomputable def girth (G : SimpleGraph α) : ℕ :=
G.egirth.toNat
lemma girth_le_length {a} {w : G.Walk a a} (h : w.IsCycle) : G.girth ≤ w.length :=
ENat.coe_le_coe.mp <| G.egirth.coe_toNat_le_self.trans <| egirth_le_length h
lemma three_le_girth (hG : ¬ G.IsAcyclic) : 3 ≤ G.girth :=
ENat.toNat_le_toNat three_le_egirth <| egirth_eq_top.not.mpr hG
lemma girth_eq_zero : G.girth = 0 ↔ G.IsAcyclic :=
⟨fun h ↦ not_not.mp <| three_le_girth.mt <| by cutsat, fun h ↦ by simp [girth, h]⟩
protected alias ⟨_, IsAcyclic.girth_eq_zero⟩ := girth_eq_zero
lemma girth_anti {G' : SimpleGraph α} (hab : G ≤ G') (h : ¬ G.IsAcyclic) : G'.girth ≤ G.girth :=
ENat.toNat_le_toNat (egirth_anti hab) <| egirth_eq_top.not.mpr h
lemma exists_girth_eq_length :
(∃ (a : α) (w : G.Walk a a), w.IsCycle ∧ G.girth = w.length) ↔ ¬ G.IsAcyclic := by
refine ⟨by tauto, fun h ↦ ?_⟩
obtain ⟨_, _, _⟩ := exists_egirth_eq_length.mpr h
simp_all only [girth, ENat.toNat_coe]
tauto
@[simp] lemma girth_bot : girth (⊥ : SimpleGraph α) = 0 := by
simp [girth]
end girth
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Matching.lean | import Mathlib.Combinatorics.SimpleGraph.Clique
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Subgraph
import Mathlib.Combinatorics.SimpleGraph.Connectivity.WalkCounting
import Mathlib.Combinatorics.SimpleGraph.DegreeSum
import Mathlib.Combinatorics.SimpleGraph.Operations
import Mathlib.Data.Set.Card.Arithmetic
import Mathlib.Data.Set.Functor
/-!
# Matchings
A *matching* for a simple graph is a set of disjoint pairs of adjacent vertices, and the set of all
the vertices in a matching is called its *support* (and sometimes the vertices in the support are
said to be *saturated* by the matching). A *perfect matching* is a matching whose support contains
every vertex of the graph.
In this module, we represent a matching as a subgraph whose vertices are each incident to at most
one edge, and the edges of the subgraph represent the paired vertices.
## Main definitions
* `SimpleGraph.Subgraph.IsMatching`: `M.IsMatching` means that `M` is a matching of its
underlying graph.
* `SimpleGraph.Subgraph.IsPerfectMatching` defines when a subgraph `M` of a simple graph is a
perfect matching, denoted `M.IsPerfectMatching`.
* `SimpleGraph.IsMatchingFree` means that a graph `G` has no perfect matchings.
* `SimpleGraph.IsCycles` means that a graph consists of cycles (including cycles of length 0,
also known as isolated vertices)
* `SimpleGraph.IsAlternating` means that edges in a graph `G` are alternatingly
included and not included in some other graph `G'`
## TODO
* Define an `other` function and prove useful results about it (https://leanprover.zulipchat.com/#narrow/stream/252551-graph-theory/topic/matchings/near/266205863)
* Provide a bicoloring for matchings (https://leanprover.zulipchat.com/#narrow/stream/252551-graph-theory/topic/matchings/near/265495120)
* Tutte's Theorem
-/
assert_not_exists Field TwoSidedIdeal
open Function
namespace SimpleGraph
variable {V W : Type*} {G G' : SimpleGraph V} {M M' : Subgraph G} {u v w : V}
namespace Subgraph
/--
The subgraph `M` of `G` is a matching if every vertex of `M` is incident to exactly one edge in `M`.
We say that the vertices in `M.support` are *matched* or *saturated*.
-/
def IsMatching (M : Subgraph G) : Prop := ∀ ⦃v⦄, v ∈ M.verts → ∃! w, M.Adj v w
/-- Given a vertex, returns the unique edge of the matching it is incident to. -/
noncomputable def IsMatching.toEdge (h : M.IsMatching) (v : M.verts) : M.edgeSet :=
⟨s(v, (h v.property).choose), (h v.property).choose_spec.1⟩
theorem IsMatching.toEdge_eq_of_adj (h : M.IsMatching) (hv : v ∈ M.verts) (hvw : M.Adj v w) :
h.toEdge ⟨v, hv⟩ = ⟨s(v, w), hvw⟩ := by
simp only [IsMatching.toEdge, Subtype.mk_eq_mk]
congr
exact ((h (M.edge_vert hvw)).choose_spec.2 w hvw).symm
theorem IsMatching.toEdge.surjective (h : M.IsMatching) : Surjective h.toEdge := by
rintro ⟨⟨x, y⟩, he⟩
exact ⟨⟨x, M.edge_vert he⟩, h.toEdge_eq_of_adj _ he⟩
theorem IsMatching.toEdge_eq_toEdge_of_adj (h : M.IsMatching)
(hv : v ∈ M.verts) (hw : w ∈ M.verts) (ha : M.Adj v w) :
h.toEdge ⟨v, hv⟩ = h.toEdge ⟨w, hw⟩ := by
rw [h.toEdge_eq_of_adj hv ha, h.toEdge_eq_of_adj hw (M.symm ha), Subtype.mk_eq_mk, Sym2.eq_swap]
lemma IsMatching.map_ofLE (h : M.IsMatching) (hGG' : G ≤ G') :
(M.map (Hom.ofLE hGG')).IsMatching := by
intro _ hv
obtain ⟨_, hv, hv'⟩ := Set.mem_image _ _ _ |>.mp hv
obtain ⟨w, hw⟩ := h hv
use w
simpa using hv' ▸ hw
lemma IsMatching.eq_of_adj_left (hM : M.IsMatching) (huv : M.Adj u v) (huw : M.Adj u w) : v = w :=
(hM <| M.edge_vert huv).unique huv huw
lemma IsMatching.eq_of_adj_right (hM : M.IsMatching) (huw : M.Adj u w) (hvw : M.Adj v w) : u = v :=
hM.eq_of_adj_left huw.symm hvw.symm
lemma IsMatching.not_adj_left_of_ne (hM : M.IsMatching) (hvw : v ≠ w) (huv : M.Adj u v) :
¬M.Adj u w := fun huw ↦ hvw <| hM.eq_of_adj_left huv huw
lemma IsMatching.not_adj_right_of_ne (hM : M.IsMatching) (huv : u ≠ v) (huw : M.Adj u w) :
¬M.Adj v w := fun hvw ↦ huv <| hM.eq_of_adj_right huw hvw
lemma IsMatching.sup (hM : M.IsMatching) (hM' : M'.IsMatching)
(hd : Disjoint M.support M'.support) : (M ⊔ M').IsMatching := by
intro v hv
have aux {N N' : Subgraph G} (hN : N.IsMatching) (hd : Disjoint N.support N'.support)
(hmN: v ∈ N.verts) : ∃! w, (N ⊔ N').Adj v w := by
obtain ⟨w, hw⟩ := hN hmN
use w
refine ⟨sup_adj.mpr (.inl hw.1), ?_⟩
intro y hy
cases hy with
| inl h => exact hw.2 y h
| inr h =>
rw [Set.disjoint_left] at hd
simpa [(mem_support _).mpr ⟨w, hw.1⟩, (mem_support _).mpr ⟨y, h⟩] using @hd v
cases Set.mem_or_mem_of_mem_union hv with
| inl hmM => exact aux hM hd hmM
| inr hmM' =>
rw [sup_comm]
exact aux hM' (Disjoint.symm hd) hmM'
lemma IsMatching.iSup {ι : Sort _} {f : ι → Subgraph G} (hM : (i : ι) → (f i).IsMatching)
(hd : Pairwise fun i j ↦ Disjoint (f i).support (f j).support) :
(⨆ i, f i).IsMatching := by
intro v hv
obtain ⟨i, hi⟩ := Set.mem_iUnion.mp (verts_iSup ▸ hv)
obtain ⟨w, hw⟩ := hM i hi
use w
refine ⟨iSup_adj.mpr ⟨i, hw.1⟩, ?_⟩
intro y hy
obtain ⟨i', hi'⟩ := iSup_adj.mp hy
by_cases heq : i = i'
· exact hw.2 y (heq.symm ▸ hi')
· have := hd heq
simp only [Set.disjoint_left] at this
simpa [(mem_support _).mpr ⟨w, hw.1⟩, (mem_support _).mpr ⟨y, hi'⟩] using @this v
lemma IsMatching.subgraphOfAdj (h : G.Adj v w) : (G.subgraphOfAdj h).IsMatching := by
intro _ hv
rw [subgraphOfAdj_verts, Set.mem_insert_iff, Set.mem_singleton_iff] at hv
cases hv with
| inl => use w; aesop
| inr => use v; aesop
lemma IsMatching.coeSubgraph {G' : Subgraph G} {M : Subgraph G'.coe} (hM : M.IsMatching) :
(Subgraph.coeSubgraph M).IsMatching := by
intro _ hv
obtain ⟨w, hw⟩ := hM <| Set.mem_of_mem_image_val <| (Subgraph.verts_coeSubgraph M).symm ▸ hv
use w
refine ⟨?_, fun y hy => ?_⟩
· obtain ⟨v, hv⟩ := (Set.mem_image _ _ _).mp <| (Subgraph.verts_coeSubgraph M).symm ▸ hv
simp only [coeSubgraph_adj, Subtype.coe_eta, Subtype.coe_prop, exists_const]
exact ⟨hv.2 ▸ v.2, hw.1⟩
· obtain ⟨_, hw', hvw⟩ := (coeSubgraph_adj _ _ _).mp hy
rw [← hw.2 ⟨y, hw'⟩ hvw]
lemma IsMatching.exists_of_disjoint_sets_of_equiv {s t : Set V} (h : Disjoint s t)
(f : s ≃ t) (hadj : ∀ v : s, G.Adj v (f v)) :
∃ M : Subgraph G, M.verts = s ∪ t ∧ M.IsMatching := by
use {
verts := s ∪ t
Adj := fun v w ↦ (∃ h : v ∈ s, f ⟨v, h⟩ = w) ∨ (∃ h : w ∈ s, f ⟨w, h⟩ = v)
adj_sub := by
intro v w h
obtain (⟨hv, rfl⟩ | ⟨hw, rfl⟩) := h
· exact hadj ⟨v, _⟩
· exact (hadj ⟨w, _⟩).symm
edge_vert := by aesop }
simp only [Subgraph.IsMatching, Set.mem_union, true_and]
intro v hv
rcases hv with hl | hr
· use f ⟨v, hl⟩
simp only [hl, exists_const, true_or, exists_true_left, true_and]
rintro y (rfl | ⟨hys, rfl⟩)
· rfl
· exact (h.ne_of_mem hl (f ⟨y, hys⟩).coe_prop rfl).elim
· use f.symm ⟨v, hr⟩
simp only [Subtype.coe_eta, Equiv.apply_symm_apply, Subtype.coe_prop, exists_const, or_true,
true_and]
rintro y (⟨hy, rfl⟩ | ⟨hy, rfl⟩)
· exact (h.ne_of_mem hy hr rfl).elim
· simp
protected lemma IsMatching.map {G' : SimpleGraph W} {M : Subgraph G} (f : G →g G')
(hf : Injective f) (hM : M.IsMatching) : (M.map f).IsMatching := by
rintro _ ⟨v, hv, rfl⟩
obtain ⟨v', hv'⟩ := hM hv
use f v'
refine ⟨⟨v, v', hv'.1, rfl, rfl⟩, ?_⟩
rintro _ ⟨w, w', hw, hw', rfl⟩
cases hf hw'.symm
rw [hv'.2 w' hw]
@[simp]
lemma Iso.isMatching_map {G' : SimpleGraph W} {M : Subgraph G} (f : G ≃g G') :
(M.map f.toHom).IsMatching ↔ M.IsMatching where
mp h := by simpa [← map_comp] using h.map f.symm.toHom f.symm.injective
mpr := .map f.toHom f.injective
/--
The subgraph `M` of `G` is a perfect matching on `G` if it's a matching and every vertex `G` is
matched.
-/
def IsPerfectMatching (M : G.Subgraph) : Prop := M.IsMatching ∧ M.IsSpanning
theorem IsMatching.support_eq_verts (h : M.IsMatching) : M.support = M.verts := by
refine M.support_subset_verts.antisymm fun v hv => ?_
obtain ⟨w, hvw, -⟩ := h hv
exact ⟨_, hvw⟩
theorem isMatching_iff_forall_degree [∀ v, Fintype (M.neighborSet v)] :
M.IsMatching ↔ ∀ v : V, v ∈ M.verts → M.degree v = 1 := by
simp only [degree_eq_one_iff_existsUnique_adj, IsMatching]
theorem IsMatching.even_card [Fintype M.verts] (h : M.IsMatching) : Even M.verts.toFinset.card := by
classical
rw [isMatching_iff_forall_degree] at h
use M.coe.edgeFinset.card
rw [← two_mul, ← M.coe.sum_degrees_eq_twice_card_edges]
simp [h, Finset.card_univ]
theorem isPerfectMatching_iff : M.IsPerfectMatching ↔ ∀ v, ∃! w, M.Adj v w := by
refine ⟨?_, fun hm => ⟨fun v _ => hm v, fun v => ?_⟩⟩
· rintro ⟨hm, hs⟩ v
exact hm (hs v)
· obtain ⟨w, hw, -⟩ := hm v
exact M.edge_vert hw
theorem isPerfectMatching_iff_forall_degree [∀ v, Fintype (M.neighborSet v)] :
M.IsPerfectMatching ↔ ∀ v, M.degree v = 1 := by
simp [degree_eq_one_iff_existsUnique_adj, isPerfectMatching_iff]
theorem IsPerfectMatching.even_card [Fintype V] (h : M.IsPerfectMatching) :
Even (Fintype.card V) := by
classical
simpa only [h.2.card_verts] using IsMatching.even_card h.1
lemma IsMatching.induce_connectedComponent (h : M.IsMatching) (c : ConnectedComponent G) :
(M.induce (M.verts ∩ c.supp)).IsMatching := by
intro _ hv
obtain ⟨hv, rfl⟩ := hv
obtain ⟨w, hvw, hw⟩ := h hv
use w
simpa [hv, hvw, M.edge_vert hvw.symm, (M.adj_sub hvw).symm.reachable] using fun _ _ _ ↦ hw _
lemma IsPerfectMatching.induce_connectedComponent_isMatching (h : M.IsPerfectMatching)
(c : ConnectedComponent G) : (M.induce c.supp).IsMatching := by
simpa [h.2.verts_eq_univ] using h.1.induce_connectedComponent c
@[simp]
lemma IsPerfectMatching.toSubgraph_iff (h : M.spanningCoe ≤ G') :
(G'.toSubgraph M.spanningCoe h).IsPerfectMatching ↔ M.IsPerfectMatching := by
simp only [isPerfectMatching_iff, toSubgraph_adj, spanningCoe_adj]
end Subgraph
lemma IsClique.even_iff_exists_isMatching {u : Set V} (hc : G.IsClique u)
(hu : u.Finite) : Even u.ncard ↔ ∃ (M : Subgraph G), M.verts = u ∧ M.IsMatching := by
refine ⟨fun h ↦ ?_, by
rintro ⟨M, rfl, hMr⟩
simpa [Set.ncard_eq_toFinset_card _ hu, Set.toFinite_toFinset,
← Set.toFinset_card] using @hMr.even_card _ _ _ hu.fintype⟩
obtain ⟨t, u, rfl, hd, hcard⟩ := Set.exists_union_disjoint_ncard_eq_of_even h
obtain ⟨f⟩ : Nonempty (t ≃ u) := by
rw [← Cardinal.eq, ← t.cast_ncard (Set.finite_union.mp hu).1,
← u.cast_ncard (Set.finite_union.mp hu).2]
exact congrArg Nat.cast hcard
exact Subgraph.IsMatching.exists_of_disjoint_sets_of_equiv hd f
fun v ↦ hc (by simp) (by simp) <| hd.ne_of_mem (by simp) (by simp)
namespace ConnectedComponent
section Finite
lemma even_card_of_isPerfectMatching [Fintype V] [DecidableEq V] [DecidableRel G.Adj]
(c : ConnectedComponent G) (hM : M.IsPerfectMatching) :
Even (Fintype.card c.supp) := by
#adaptation_note /-- https://github.com/leanprover/lean4/pull/5020
some instances that use the chain of coercions
`[SetLike X], X → Set α → Sort _` are
blocked by the discrimination tree. This can be fixed by redeclaring the instance for `X`
using the double coercion but the proper fix seems to avoid the double coercion. -/
letI : DecidablePred fun x ↦ x ∈ (M.induce c.supp).verts := fun a ↦ G.instDecidableMemSupp c a
simpa using (hM.induce_connectedComponent_isMatching c).even_card
lemma odd_matches_node_outside [Finite V] {u : Set V}
(hM : M.IsPerfectMatching) (c : (Subgraph.deleteVerts ⊤ u).coe.oddComponents) :
∃ᵉ (w ∈ u) (v : ((⊤ : G.Subgraph).deleteVerts u).verts), M.Adj v w ∧ v ∈ c.val.supp := by
by_contra! h
have hMmatch : (M.induce c.val.supp).IsMatching := by
intro v hv
obtain ⟨w, hw⟩ := hM.1 (hM.2 v)
obtain ⟨⟨v', hv'⟩, ⟨hv, rfl⟩⟩ := hv
use w
have hwnu : w ∉ u := fun hw' ↦ h w hw' ⟨v', hv'⟩ (hw.1) hv
refine ⟨⟨⟨⟨v', hv'⟩, hv, rfl⟩, ?_, hw.1⟩, fun _ hy ↦ hw.2 _ hy.2.2⟩
apply ConnectedComponent.mem_coe_supp_of_adj ⟨⟨v', hv'⟩, ⟨hv, rfl⟩⟩ ⟨by trivial, hwnu⟩
simp only [Subgraph.induce_verts, Subgraph.verts_top, Set.mem_diff, Set.mem_univ, true_and,
Subgraph.induce_adj, hwnu, not_false_eq_true, and_self, Subgraph.top_adj, M.adj_sub hw.1,
and_true] at hv' ⊢
trivial
apply Nat.not_even_iff_odd.2 c.prop
haveI : Fintype ↑(Subgraph.induce M (Subtype.val '' supp c.val)).verts := Fintype.ofFinite _
classical
haveI : Fintype (c.val.supp) := Fintype.ofFinite _
simpa [Subgraph.induce_verts, Subgraph.verts_top, Nat.card_eq_fintype_card, Set.toFinset_card,
Finset.card_image_of_injective, ← Nat.card_coe_set_eq] using hMmatch.even_card
end Finite
end ConnectedComponent
/--
A graph is matching free if it has no perfect matching. It does not make much sense to
consider a graph being free of just matchings, because any non-trivial graph has those.
-/
def IsMatchingFree (G : SimpleGraph V) := ∀ M : Subgraph G, ¬ M.IsPerfectMatching
lemma IsMatchingFree.mono {G G' : SimpleGraph V} (h : G ≤ G') (hmf : G'.IsMatchingFree) :
G.IsMatchingFree := by
intro x
by_contra! hc
apply hmf (x.map (SimpleGraph.Hom.ofLE h))
refine ⟨hc.1.map_ofLE h, ?_⟩
intro v
simp only [Subgraph.map_verts, Hom.coe_ofLE, id_eq, Set.image_id']
exact hc.2 v
lemma exists_maximal_isMatchingFree [Finite V] (h : G.IsMatchingFree) :
∃ Gmax : SimpleGraph V, G ≤ Gmax ∧ Gmax.IsMatchingFree ∧
∀ G', G' > Gmax → ∃ M : Subgraph G', M.IsPerfectMatching := by
simp_rw [← @not_forall_not _ Subgraph.IsPerfectMatching]
obtain ⟨Gmax, hGmax⟩ := Finite.exists_le_maximal h
exact ⟨Gmax, ⟨hGmax.1, ⟨hGmax.2.prop, fun _ h' ↦ hGmax.2.not_prop_of_gt h'⟩⟩⟩
/-- A graph `G` consists of a set of cycles, if each vertex is either isolated or connected to
exactly two vertices. This is used to create new matchings by taking the `symmDiff` with cycles.
The definition of `symmDiff` that makes sense is the one for `SimpleGraph`. The `symmDiff`
for `SimpleGraph.Subgraph` deriving from the lattice structure also affects the vertices included,
which we do not want in this case. This is why this property is defined for `SimpleGraph`, rather
than `SimpleGraph.Subgraph`.
-/
def IsCycles (G : SimpleGraph V) := ∀ ⦃v⦄, (G.neighborSet v).Nonempty → (G.neighborSet v).ncard = 2
/--
Given a vertex with one edge in a graph of cycles this gives the other edge incident
to the same vertex.
-/
lemma IsCycles.other_adj_of_adj (h : G.IsCycles) (hadj : G.Adj v w) :
∃ w', w ≠ w' ∧ G.Adj v w' := by
simp_rw [← SimpleGraph.mem_neighborSet] at hadj ⊢
have := h ⟨w, hadj⟩
obtain ⟨w', hww'⟩ := (G.neighborSet v).exists_ne_of_one_lt_ncard (by cutsat) w
exact ⟨w', ⟨hww'.2.symm, hww'.1⟩⟩
lemma IsCycles.existsUnique_ne_adj (h : G.IsCycles) (hadj : G.Adj v w) :
∃! w', w ≠ w' ∧ G.Adj v w' := by
obtain ⟨w', ⟨hww, hww'⟩⟩ := h.other_adj_of_adj hadj
use w'
refine ⟨⟨hww, hww'⟩, ?_⟩
intro y ⟨hwy, hwy'⟩
obtain ⟨x, y', hxy'⟩ := Set.ncard_eq_two.mp (h ⟨w, hadj⟩)
simp_rw [← SimpleGraph.mem_neighborSet] at *
aesop
lemma IsCycles.toSimpleGraph (c : G.ConnectedComponent) (h : G.IsCycles) :
c.toSimpleGraph.spanningCoe.IsCycles := by
intro v ⟨w, hw⟩
rw [mem_neighborSet, c.adj_spanningCoe_toSimpleGraph] at hw
rw [← h ⟨w, hw.2⟩]
congr 1
ext w'
simp only [mem_neighborSet, c.adj_spanningCoe_toSimpleGraph, hw, true_and]
@[deprecated (since := "2025-06-08")] alias IsCycles.induce_supp := IsCycles.toSimpleGraph
lemma Walk.IsCycle.isCycles_spanningCoe_toSubgraph {u : V} {p : G.Walk u u} (hpc : p.IsCycle) :
p.toSubgraph.spanningCoe.IsCycles := by
intro v hv
apply hpc.ncard_neighborSet_toSubgraph_eq_two
obtain ⟨_, hw⟩ := hv
exact p.mem_verts_toSubgraph.mp <| p.toSubgraph.edge_vert hw
lemma Walk.IsPath.isCycles_spanningCoe_toSubgraph_sup_edge {u v} {p : G.Walk u v} (hp : p.IsPath)
(h : u ≠ v) (hs : s(v, u) ∉ p.edges) : (p.toSubgraph.spanningCoe ⊔ edge v u).IsCycles := by
let c := (p.mapLe (OrderTop.le_top G)).cons (by simp [h.symm] : (completeGraph V).Adj v u)
have : p.toSubgraph.spanningCoe ⊔ edge v u = c.toSubgraph.spanningCoe := by
ext w x
simp only [sup_adj, Subgraph.spanningCoe_adj, completeGraph_eq_top, edge_adj, c,
Walk.toSubgraph, Subgraph.sup_adj, subgraphOfAdj_adj, adj_toSubgraph_mapLe]
aesop
exact this ▸ IsCycle.isCycles_spanningCoe_toSubgraph (by simp [Walk.cons_isCycle_iff, c, hp, hs])
lemma Walk.IsCycle.adj_toSubgraph_iff_of_isCycles [LocallyFinite G] {u} {p : G.Walk u u}
(hp : p.IsCycle) (hcyc : G.IsCycles) (hv : v ∈ p.toSubgraph.verts) :
∀ w, p.toSubgraph.Adj v w ↔ G.Adj v w := by
refine fun w ↦ Subgraph.adj_iff_of_neighborSet_equiv (?_ : Inhabited _).default (Set.toFinite _)
apply Classical.inhabited_of_nonempty
rw [← Cardinal.eq, ← Set.cast_ncard (Set.toFinite _),
← Set.cast_ncard (finite_neighborSet_toSubgraph p), hcyc
(Set.Nonempty.mono (p.toSubgraph.neighborSet_subset v) <|
Set.nonempty_of_ncard_ne_zero <| by simp [
hp.ncard_neighborSet_toSubgraph_eq_two (by aesop)]),
hp.ncard_neighborSet_toSubgraph_eq_two (by simp_all)]
open scoped symmDiff
lemma Subgraph.IsPerfectMatching.symmDiff_isCycles
{M : Subgraph G} {M' : Subgraph G'} (hM : M.IsPerfectMatching)
(hM' : M'.IsPerfectMatching) : (M.spanningCoe ∆ M'.spanningCoe).IsCycles := by
intro v
obtain ⟨w, hw⟩ := hM.1 (hM.2 v)
obtain ⟨w', hw'⟩ := hM'.1 (hM'.2 v)
simp only [symmDiff_def, Set.ncard_eq_two, ne_eq, imp_iff_not_or, Set.not_nonempty_iff_eq_empty,
Set.eq_empty_iff_forall_notMem, SimpleGraph.mem_neighborSet, SimpleGraph.sup_adj, sdiff_adj,
spanningCoe_adj, not_or, not_and, not_not]
by_cases hww' : w = w'
· simp_all [← imp_iff_not_or]
· right
use w, w'
aesop
lemma IsCycles.snd_of_mem_support_of_isPath_of_adj [Finite V] {v w w' : V}
(hcyc : G.IsCycles) (p : G.Walk v w) (hw : w ≠ w') (hw' : w' ∈ p.support) (hp : p.IsPath)
(hadj : G.Adj v w') : p.snd = w' := by
classical
apply hp.snd_of_toSubgraph_adj
rw [Walk.mem_support_iff_exists_getVert] at hw'
obtain ⟨n, ⟨rfl, hnl⟩⟩ := hw'
by_cases hn : n = 0 ∨ n = p.length
· aesop
have e : G.neighborSet (p.getVert n) ≃ p.toSubgraph.neighborSet (p.getVert n) := by
refine @Classical.ofNonempty _ ?_
rw [← Cardinal.eq, ← Set.cast_ncard (Set.toFinite _), ← Set.cast_ncard (Set.toFinite _),
hp.ncard_neighborSet_toSubgraph_internal_eq_two (by cutsat) (by cutsat),
hcyc (Set.nonempty_of_mem hadj.symm)]
rw [Subgraph.adj_comm, Subgraph.adj_iff_of_neighborSet_equiv e (Set.toFinite _)]
exact hadj.symm
private lemma IsCycles.reachable_sdiff_toSubgraph_spanningCoe_aux [Fintype V] {v w : V}
(hcyc : G.IsCycles) (p : G.Walk v w) (hp : p.IsPath) :
(G \ p.toSubgraph.spanningCoe).Reachable w v := by
classical
-- Consider the case when p is nil
by_cases hvw : v = w
· subst hvw
use .nil
have hpn : ¬p.Nil := Walk.not_nil_of_ne hvw
obtain ⟨w', ⟨hw'1, hw'2⟩, hwu⟩ := hcyc.existsUnique_ne_adj
(p.toSubgraph_adj_snd hpn).adj_sub
-- The edge (v, w) can't be in p, because then it would be the second node
have hnpvw' : ¬ p.toSubgraph.Adj v w' := by
intro h
exact hw'1 (hp.snd_of_toSubgraph_adj h)
-- If w = w', then the reachability can be proved with just one edge
by_cases hww' : w = w'
· subst hww'
have : (G \ p.toSubgraph.spanningCoe).Adj w v := by
simp only [sdiff_adj, Subgraph.spanningCoe_adj]
exact ⟨hw'2.symm, fun h ↦ hnpvw' h.symm⟩
exact this.reachable
-- Construct the walk needed recursively by extending p
have hle : (G \ (p.cons hw'2.symm).toSubgraph.spanningCoe) ≤ (G \ p.toSubgraph.spanningCoe) := by
apply sdiff_le_sdiff (by rfl) ?hcd
simp
have hp'p : (p.cons hw'2.symm).IsPath := by
rw [Walk.cons_isPath_iff]
refine ⟨hp, fun hw' ↦ ?_⟩
exact hw'1 (hcyc.snd_of_mem_support_of_isPath_of_adj _ hww' hw' hp hw'2)
have : (G \ p.toSubgraph.spanningCoe).Adj w' v := by
simp only [sdiff_adj, Subgraph.spanningCoe_adj]
refine ⟨hw'2.symm, fun h ↦ ?_⟩
exact hnpvw' h.symm
use (((hcyc.reachable_sdiff_toSubgraph_spanningCoe_aux
(p.cons hw'2.symm) hp'p).some).mapLe hle).append this.toWalk
termination_by Fintype.card V + 1 - p.length
decreasing_by
simp_wf
have := Walk.IsPath.length_lt hp
cutsat
lemma IsCycles.reachable_sdiff_toSubgraph_spanningCoe [Finite V] {v w : V} (hcyc : G.IsCycles)
(p : G.Walk v w) (hp : p.IsPath) : (G \ p.toSubgraph.spanningCoe).Reachable w v := by
have : Fintype V := Fintype.ofFinite V
exact reachable_sdiff_toSubgraph_spanningCoe_aux hcyc p hp
lemma IsCycles.reachable_deleteEdges [Finite V] (hadj : G.Adj v w)
(hcyc : G.IsCycles) : (G.deleteEdges {s(v, w)}).Reachable v w := by
have : fromEdgeSet {s(v, w)} = hadj.toWalk.toSubgraph.spanningCoe := by
simp only [Walk.toSubgraph, singletonSubgraph_le_iff, subgraphOfAdj_verts, Set.mem_insert_iff,
Set.mem_singleton_iff, or_true, sup_of_le_left]
exact (Subgraph.spanningCoe_subgraphOfAdj hadj).symm
rw [show G.deleteEdges {s(v, w)} = G \ fromEdgeSet {s(v, w)} from by rfl]
exact this ▸ (hcyc.reachable_sdiff_toSubgraph_spanningCoe hadj.toWalk
(Walk.IsPath.of_adj hadj)).symm
lemma IsCycles.exists_cycle_toSubgraph_verts_eq_connectedComponentSupp [Finite V]
{c : G.ConnectedComponent} (h : G.IsCycles) (hv : v ∈ c.supp)
(hn : (G.neighborSet v).Nonempty) :
∃ (p : G.Walk v v), p.IsCycle ∧ p.toSubgraph.verts = c.supp := by
classical
obtain ⟨w, hw⟩ := hn
obtain ⟨u, p, hp⟩ := SimpleGraph.adj_and_reachable_delete_edges_iff_exists_cycle.mp
⟨hw, h.reachable_deleteEdges hw⟩
have hvp : v ∈ p.support := SimpleGraph.Walk.fst_mem_support_of_mem_edges _ hp.2
have : p.toSubgraph.verts = c.supp := by
obtain ⟨c', hc'⟩ := p.toSubgraph_connected.exists_verts_eq_connectedComponentSupp (by
intro v hv w hadj
refine (Subgraph.adj_iff_of_neighborSet_equiv ?_ (Set.toFinite _)).mpr hadj
have : (G.neighborSet v).Nonempty := by
rw [Walk.mem_verts_toSubgraph] at hv
refine (Set.nonempty_of_ncard_ne_zero ?_).mono (p.toSubgraph.neighborSet_subset v)
rw [hp.1.ncard_neighborSet_toSubgraph_eq_two hv]
omega
refine @Classical.ofNonempty _ ?_
rw [← Cardinal.eq, ← Set.cast_ncard (Set.toFinite _), ← Set.cast_ncard (Set.toFinite _),
h this, hp.1.ncard_neighborSet_toSubgraph_eq_two (p.mem_verts_toSubgraph.mp hv)])
rw [hc']
have : v ∈ c'.supp := by
rw [← hc', Walk.mem_verts_toSubgraph]
exact hvp
simp_all
use p.rotate hvp
rw [← this]
exact ⟨hp.1.rotate _, by simp⟩
/--
A graph `G` is alternating with respect to some other graph `G'`, if exactly every other edge in
`G` is in `G'`. Note that the degree of each vertex needs to be at most 2 for this to be
possible. This property is used to create new matchings using `symmDiff`.
The definition of `symmDiff` that makes sense is the one for `SimpleGraph`. The `symmDiff`
for `SimpleGraph.Subgraph` deriving from the lattice structure also affects the vertices included,
which we do not want in this case. This is why this property, just like `IsCycles`, is defined
for `SimpleGraph` rather than `SimpleGraph.Subgraph`.
-/
def IsAlternating (G G' : SimpleGraph V) :=
∀ ⦃v w w': V⦄, w ≠ w' → G.Adj v w → G.Adj v w' → (G'.Adj v w ↔ ¬ G'.Adj v w')
lemma IsAlternating.mono {G'' : SimpleGraph V} (halt : G.IsAlternating G') (h : G'' ≤ G) :
G''.IsAlternating G' := fun _ _ _ hww' hvw hvw' ↦ halt hww' (h hvw) (h hvw')
lemma IsAlternating.spanningCoe (halt : G.IsAlternating G') (H : Subgraph G) :
H.spanningCoe.IsAlternating G' := by
intro v w w' hww' hvw hvv'
simp only [Subgraph.spanningCoe_adj] at hvw hvv'
exact halt hww' hvw.adj_sub hvv'.adj_sub
lemma IsAlternating.sup_edge {u x : V} (halt : G.IsAlternating G') (hnadj : ¬G'.Adj u x)
(hu' : ∀ u', u' ≠ u → G.Adj x u' → G'.Adj x u')
(hx' : ∀ x', x' ≠ x → G.Adj x' u → G'.Adj x' u) : (G ⊔ edge u x).IsAlternating G' := by
by_cases hadj : G.Adj u x
· rwa [sup_edge_of_adj G hadj]
intro v w w' hww' hvw hvv'
simp only [sup_adj, edge_adj] at hvw hvv'
obtain hl | hr := hvw <;> obtain h1 | h2 := hvv'
· exact halt hww' hl h1
· rw [G'.adj_congr_of_sym2 (by aesop : s(v, w') = s(u, x))]
simp only [hnadj, not_false_eq_true, iff_true]
rcases h2.1 with ⟨h2l1, h2l2⟩ | ⟨h2r1,h2r2⟩
· subst h2l1 h2l2
exact (hx' _ hww' hl.symm).symm
· simp_all
· rw [G'.adj_congr_of_sym2 (by aesop : s(v, w) = s(u, x))]
simp only [hnadj, false_iff, not_not]
rcases hr.1 with ⟨hrl1, hrl2⟩ | ⟨hrr1, hrr2⟩
· subst hrl1 hrl2
exact (hx' _ hww'.symm h1.symm).symm
· aesop
· aesop
lemma Subgraph.IsPerfectMatching.symmDiff_of_isAlternating (hM : M.IsPerfectMatching)
(hG' : G'.IsAlternating M.spanningCoe) (hG'cyc : G'.IsCycles) :
(⊤ : Subgraph (M.spanningCoe ∆ G')).IsPerfectMatching := by
rw [Subgraph.isPerfectMatching_iff]
intro v
simp only [symmDiff_def]
obtain ⟨w, hw⟩ := hM.1 (hM.2 v)
by_cases h : G'.Adj v w
· obtain ⟨w', hw'⟩ := hG'cyc.other_adj_of_adj h
have hmadj : M.Adj v w ↔ ¬M.Adj v w' := by simpa using hG' hw'.1 h hw'.2
use w'
simp only [Subgraph.top_adj, SimpleGraph.sup_adj, sdiff_adj, Subgraph.spanningCoe_adj,
hmadj.mp hw.1, hw'.2, not_true_eq_false, and_self, not_false_eq_true, or_true, true_and]
rintro y (hl | hr)
· aesop
· obtain ⟨w'', hw''⟩ := hG'cyc.other_adj_of_adj hr.1
by_contra! hc
simp_all [show M.Adj v y ↔ ¬M.Adj v w' from by simpa using hG' hc hr.1 hw'.2]
· use w
simp only [Subgraph.top_adj, SimpleGraph.sup_adj, sdiff_adj, Subgraph.spanningCoe_adj, hw.1, h,
not_false_eq_true, and_self, not_true_eq_false, or_false, true_and]
rintro y (hl | hr)
· exact hw.2 _ hl.1
· have ⟨w', hw'⟩ := hG'cyc.other_adj_of_adj hr.1
simp_all [show M.Adj v y ↔ ¬M.Adj v w' from by simpa using hG' hw'.1 hr.1 hw'.2]
lemma Subgraph.IsPerfectMatching.isAlternating_symmDiff_left {M' : Subgraph G'}
(hM : M.IsPerfectMatching) (hM' : M'.IsPerfectMatching) :
(M.spanningCoe ∆ M'.spanningCoe).IsAlternating M.spanningCoe := by
intro v w w' hww' hvw hvw'
obtain ⟨v1, hm1, hv1⟩ := hM.1 (hM.2 v)
obtain ⟨v2, hm2, hv2⟩ := hM'.1 (hM'.2 v)
simp only [symmDiff_def] at *
aesop
lemma Subgraph.IsPerfectMatching.isAlternating_symmDiff_right
{M' : Subgraph G'} (hM : M.IsPerfectMatching) (hM' : M'.IsPerfectMatching) :
(M.spanningCoe ∆ M'.spanningCoe).IsAlternating M'.spanningCoe := by
simpa [symmDiff_comm] using isAlternating_symmDiff_left hM' hM
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Init.lean | import Mathlib.Init
import Aesop
/-!
# SimpleGraph Rule Set
This module defines the `SimpleGraph` Aesop rule set which is used by the
`aesop_graph` 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 [SimpleGraph] |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Prod.lean | import Mathlib.Combinatorics.SimpleGraph.Paths
import Mathlib.Combinatorics.SimpleGraph.Metric
/-!
# Graph products
This file defines the box product of graphs and other product constructions. The box product of `G`
and `H` is the graph on the product of the vertices such that `x` and `y` are related iff they agree
on one component and the other one is related via either `G` or `H`. For example, the box product of
two edges is a square.
## Main declarations
* `SimpleGraph.boxProd`: The box product.
## Notation
* `G □ H`: The box product of `G` and `H`.
## TODO
Define all other graph products!
-/
variable {α β γ : Type*}
namespace SimpleGraph
variable {G : SimpleGraph α} {H : SimpleGraph β}
/-- Box product of simple graphs. It relates `(a₁, b)` and `(a₂, b)` if `G` relates `a₁` and `a₂`,
and `(a, b₁)` and `(a, b₂)` if `H` relates `b₁` and `b₂`. -/
def boxProd (G : SimpleGraph α) (H : SimpleGraph β) : SimpleGraph (α × β) where
Adj x y := G.Adj x.1 y.1 ∧ x.2 = y.2 ∨ H.Adj x.2 y.2 ∧ x.1 = y.1
symm x y := by simp [and_comm, eq_comm, adj_comm]
loopless x := by simp
/-- Box product of simple graphs. It relates `(a₁, b)` and `(a₂, b)` if `G` relates `a₁` and `a₂`,
and `(a, b₁)` and `(a, b₂)` if `H` relates `b₁` and `b₂`. -/
infixl:70 " □ " => boxProd
@[simp]
theorem boxProd_adj {x y : α × β} :
(G □ H).Adj x y ↔ G.Adj x.1 y.1 ∧ x.2 = y.2 ∨ H.Adj x.2 y.2 ∧ x.1 = y.1 :=
Iff.rfl
theorem boxProd_adj_left {a₁ : α} {b : β} {a₂ : α} :
(G □ H).Adj (a₁, b) (a₂, b) ↔ G.Adj a₁ a₂ := by
simp only [boxProd_adj, and_true, SimpleGraph.irrefl, false_and, or_false]
theorem boxProd_adj_right {a : α} {b₁ b₂ : β} : (G □ H).Adj (a, b₁) (a, b₂) ↔ H.Adj b₁ b₂ := by
simp only [boxProd_adj, SimpleGraph.irrefl, false_and, and_true, false_or]
theorem neighborSet_boxProd (x : α × β) :
(G □ H).neighborSet x = G.neighborSet x.1 ×ˢ {x.2} ∪ {x.1} ×ˢ H.neighborSet x.2 := by
ext ⟨a', b'⟩
simp only [mem_neighborSet, Set.mem_union, boxProd_adj, Set.mem_prod, Set.mem_singleton_iff]
simp only [eq_comm, and_comm]
@[deprecated (since := "2025-05-08")] alias boxProd_neighborSet := neighborSet_boxProd
variable (G H)
/-- The box product is commutative up to isomorphism. `Equiv.prodComm` as a graph isomorphism. -/
@[simps!]
def boxProdComm : G □ H ≃g H □ G := ⟨Equiv.prodComm _ _, or_comm⟩
/-- The box product is associative up to isomorphism. `Equiv.prodAssoc` as a graph isomorphism. -/
@[simps!]
def boxProdAssoc (I : SimpleGraph γ) : G □ H □ I ≃g G □ (H □ I) :=
⟨Equiv.prodAssoc _ _ _, fun {x y} => by
simp only [boxProd_adj, Equiv.prodAssoc_apply, or_and_right, or_assoc, Prod.ext_iff,
and_assoc, @and_comm (x.fst.fst = _)]⟩
/-- The embedding of `G` into `G □ H` given by `b`. -/
@[simps]
def boxProdLeft (b : β) : G ↪g G □ H where
toFun a := (a, b)
inj' _ _ := congr_arg Prod.fst
map_rel_iff' {_ _} := boxProd_adj_left
/-- The embedding of `H` into `G □ H` given by `a`. -/
@[simps]
def boxProdRight (a : α) : H ↪g G □ H where
toFun := Prod.mk a
inj' _ _ := congr_arg Prod.snd
map_rel_iff' {_ _} := boxProd_adj_right
namespace Walk
variable {G}
/-- Turn a walk on `G` into a walk on `G □ H`. -/
protected def boxProdLeft {a₁ a₂ : α} (b : β) : G.Walk a₁ a₂ → (G □ H).Walk (a₁, b) (a₂, b) :=
Walk.map (G.boxProdLeft H b).toHom
variable (G) {H}
/-- Turn a walk on `H` into a walk on `G □ H`. -/
protected def boxProdRight {b₁ b₂ : β} (a : α) : H.Walk b₁ b₂ → (G □ H).Walk (a, b₁) (a, b₂) :=
Walk.map (G.boxProdRight H a).toHom
variable {G}
/-- Project a walk on `G □ H` to a walk on `G` by discarding the moves in the direction of `H`. -/
def ofBoxProdLeft [DecidableEq β] [DecidableRel G.Adj] {x y : α × β} :
(G □ H).Walk x y → G.Walk x.1 y.1
| nil => nil
| cons h w =>
Or.by_cases h
(fun hG => w.ofBoxProdLeft.cons hG.1)
(fun hH => hH.2 ▸ w.ofBoxProdLeft)
/-- Project a walk on `G □ H` to a walk on `H` by discarding the moves in the direction of `G`. -/
def ofBoxProdRight [DecidableEq α] [DecidableRel H.Adj] {x y : α × β} :
(G □ H).Walk x y → H.Walk x.2 y.2
| nil => nil
| cons h w =>
(Or.symm h).by_cases
(fun hH => w.ofBoxProdRight.cons hH.1)
(fun hG => hG.2 ▸ w.ofBoxProdRight)
@[simp]
theorem ofBoxProdLeft_boxProdLeft [DecidableEq β] [DecidableRel G.Adj] {a₁ a₂ : α} {b : β} :
∀ (w : G.Walk a₁ a₂), (w.boxProdLeft H b).ofBoxProdLeft = w
| nil => rfl
| cons' x y z h w => by
rw [Walk.boxProdLeft, map_cons, ofBoxProdLeft, Or.by_cases, dif_pos, ← Walk.boxProdLeft]
· simp [ofBoxProdLeft_boxProdLeft]
· exact ⟨h, rfl⟩
@[simp]
theorem ofBoxProdRight_boxProdRight [DecidableEq α] [DecidableRel G.Adj] {a b₁ b₂ : α} :
∀ (w : G.Walk b₁ b₂), (w.boxProdRight G a).ofBoxProdRight = w
| nil => rfl
| cons' x y z h w => by
rw [Walk.boxProdRight, map_cons, ofBoxProdRight, Or.by_cases, dif_pos, ←
Walk.boxProdRight]
· simp [ofBoxProdRight_boxProdRight]
· exact ⟨h, rfl⟩
lemma length_boxProd {a₁ a₂ : α} {b₁ b₂ : β} [DecidableEq α] [DecidableEq β]
[DecidableRel G.Adj] [DecidableRel H.Adj] (w : (G □ H).Walk (a₁, b₁) (a₂, b₂)) :
w.length = w.ofBoxProdLeft.length + w.ofBoxProdRight.length := by
match w with
| .nil => simp [ofBoxProdLeft, ofBoxProdRight]
| .cons x w' => next c =>
unfold ofBoxProdLeft ofBoxProdRight
rw [length_cons, length_boxProd w']
have disj : (G.Adj a₁ c.1 ∧ b₁ = c.2) ∨ (H.Adj b₁ c.2 ∧ a₁ = c.1) := by simp_all
rcases disj with h₁ | h₂
· simp only [h₁, and_self, ↓reduceDIte, length_cons, Or.by_cases]
rw [add_comm, add_comm w'.ofBoxProdLeft.length 1, add_assoc]
congr <;> simp [h₁.2.symm]
· simp only [h₂, add_assoc, Or.by_cases]
congr <;> simp [h₂.2.symm]
end Walk
variable {G H}
protected theorem Preconnected.boxProd (hG : G.Preconnected) (hH : H.Preconnected) :
(G □ H).Preconnected := by
rintro x y
obtain ⟨w₁⟩ := hG x.1 y.1
obtain ⟨w₂⟩ := hH x.2 y.2
exact ⟨(w₁.boxProdLeft _ _).append (w₂.boxProdRight _ _)⟩
protected theorem Preconnected.ofBoxProdLeft [Nonempty β] (h : (G □ H).Preconnected) :
G.Preconnected := by
classical
rintro a₁ a₂
obtain ⟨w⟩ := h (a₁, Classical.arbitrary _) (a₂, Classical.arbitrary _)
exact ⟨w.ofBoxProdLeft⟩
protected theorem Preconnected.ofBoxProdRight [Nonempty α] (h : (G □ H).Preconnected) :
H.Preconnected := by
classical
rintro b₁ b₂
obtain ⟨w⟩ := h (Classical.arbitrary _, b₁) (Classical.arbitrary _, b₂)
exact ⟨w.ofBoxProdRight⟩
protected theorem Connected.boxProd (hG : G.Connected) (hH : H.Connected) : (G □ H).Connected := by
haveI := hG.nonempty
haveI := hH.nonempty
exact ⟨hG.preconnected.boxProd hH.preconnected⟩
protected theorem Connected.ofBoxProdLeft (h : (G □ H).Connected) : G.Connected := by
haveI := (nonempty_prod.1 h.nonempty).1
haveI := (nonempty_prod.1 h.nonempty).2
exact ⟨h.preconnected.ofBoxProdLeft⟩
protected theorem Connected.ofBoxProdRight (h : (G □ H).Connected) : H.Connected := by
haveI := (nonempty_prod.1 h.nonempty).1
haveI := (nonempty_prod.1 h.nonempty).2
exact ⟨h.preconnected.ofBoxProdRight⟩
@[simp]
theorem connected_boxProd : (G □ H).Connected ↔ G.Connected ∧ H.Connected :=
⟨fun h => ⟨h.ofBoxProdLeft, h.ofBoxProdRight⟩, fun h => h.1.boxProd h.2⟩
@[deprecated (since := "2025-05-08")] alias boxProd_connected := connected_boxProd
instance boxProdFintypeNeighborSet (x : α × β)
[Fintype (G.neighborSet x.1)] [Fintype (H.neighborSet x.2)] :
Fintype ((G □ H).neighborSet x) :=
Fintype.ofEquiv
((G.neighborFinset x.1 ×ˢ {x.2}).disjUnion ({x.1} ×ˢ H.neighborFinset x.2) <|
Finset.disjoint_product.mpr <| Or.inl <| neighborFinset_disjoint_singleton _ _)
((Equiv.refl _).subtypeEquiv fun y => by
simp_rw [Finset.mem_disjUnion, Finset.mem_product, Finset.mem_singleton, mem_neighborFinset,
mem_neighborSet, Equiv.refl_apply, boxProd_adj]
simp only [eq_comm, and_comm])
theorem neighborFinset_boxProd (x : α × β)
[Fintype (G.neighborSet x.1)] [Fintype (H.neighborSet x.2)] [Fintype ((G □ H).neighborSet x)] :
(G □ H).neighborFinset x =
(G.neighborFinset x.1 ×ˢ {x.2}).disjUnion ({x.1} ×ˢ H.neighborFinset x.2)
(Finset.disjoint_product.mpr <| Or.inl <| neighborFinset_disjoint_singleton _ _) := by
-- swap out the fintype instance for the canonical one
letI : Fintype ((G □ H).neighborSet x) := SimpleGraph.boxProdFintypeNeighborSet _
convert_to (G □ H).neighborFinset x = _ using 2
exact Eq.trans (Finset.map_map _ _ _) Finset.attach_map_val
@[deprecated (since := "2025-05-08")] alias boxProd_neighborFinset := neighborFinset_boxProd
theorem degree_boxProd (x : α × β)
[Fintype (G.neighborSet x.1)] [Fintype (H.neighborSet x.2)] [Fintype ((G □ H).neighborSet x)] :
(G □ H).degree x = G.degree x.1 + H.degree x.2 := by
rw [degree, degree, degree, neighborFinset_boxProd, Finset.card_disjUnion]
simp_rw [Finset.card_product, Finset.card_singleton, mul_one, one_mul]
@[deprecated (since := "2025-05-08")] alias boxProd_degree := degree_boxProd
lemma reachable_boxProd {x y : α × β} :
(G □ H).Reachable x y ↔ G.Reachable x.1 y.1 ∧ H.Reachable x.2 y.2 := by
classical
constructor
· intro ⟨w⟩
exact ⟨⟨w.ofBoxProdLeft⟩, ⟨w.ofBoxProdRight⟩⟩
· intro ⟨⟨w₁⟩, ⟨w₂⟩⟩
exact ⟨(w₁.boxProdLeft _ _).append (w₂.boxProdRight _ _)⟩
@[deprecated (since := "2025-05-08")] alias boxProd_reachable := reachable_boxProd
@[simp]
lemma edist_boxProd (x y : α × β) :
(G □ H).edist x y = G.edist x.1 y.1 + H.edist x.2 y.2 := by
classical
-- The case `(G □ H).edist x y = ⊤` is used twice, so better to factor it out.
have top_case : (G □ H).edist x y = ⊤ ↔ G.edist x.1 y.1 = ⊤ ∨ H.edist x.2 y.2 = ⊤ := by
simp_rw [← not_ne_iff, edist_ne_top_iff_reachable, reachable_boxProd, not_and_or]
by_cases h : (G □ H).edist x y = ⊤
· rw [top_case] at h
aesop
· have rGH : G.edist x.1 y.1 ≠ ⊤ ∧ H.edist x.2 y.2 ≠ ⊤ := by rw [top_case] at h; aesop
have ⟨wG, hwG⟩ := exists_walk_of_edist_ne_top rGH.1
have ⟨wH, hwH⟩ := exists_walk_of_edist_ne_top rGH.2
let w_app := (wG.boxProdLeft _ _).append (wH.boxProdRight _ _)
have w_len : w_app.length = wG.length + wH.length := by
unfold w_app Walk.boxProdLeft Walk.boxProdRight; simp
refine le_antisymm ?_ ?_
· calc (G □ H).edist x y ≤ w_app.length := by exact edist_le _
_ = wG.length + wH.length := by exact_mod_cast w_len
_ = G.edist x.1 y.1 + H.edist x.2 y.2 := by simp only [hwG, hwH]
· have ⟨w, hw⟩ := exists_walk_of_edist_ne_top h
rw [← hw, Walk.length_boxProd]
exact add_le_add (edist_le w.ofBoxProdLeft) (edist_le w.ofBoxProdRight)
@[deprecated (since := "2025-05-08")] alias boxProd_edist := edist_boxProd
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/DeleteEdges.lean | import Mathlib.Algebra.Ring.Defs
import Mathlib.Combinatorics.SimpleGraph.Finite
import Mathlib.Combinatorics.SimpleGraph.Maps
import Mathlib.Data.Int.Cast.Basic
/-!
# Edge deletion
This file defines operations deleting the edges of a simple graph and proves theorems in the finite
case.
## Main definitions
* `SimpleGraph.deleteEdges G s` is the simple graph `G` with the edges `s : Set (Sym2 V)` removed
from the edge set.
* `SimpleGraph.deleteIncidenceSet G v` is the simple graph `G` with the incidence set of `v`
removed from the edge set.
* `SimpleGraph.deleteFar G p r` is the predicate that a graph is `r`-*delete-far* from a property
`p`, that is, at least `r` edges must be deleted to satisfy `p`.
-/
open Finset Fintype
namespace SimpleGraph
variable {V : Type*} {v w : V} (G : SimpleGraph V)
section DeleteEdges
/-- Given a set of vertex pairs, remove all of the corresponding edges from the
graph's edge set, if present.
See also: `SimpleGraph.Subgraph.deleteEdges`. -/
def deleteEdges (s : Set (Sym2 V)) : SimpleGraph V := G \ fromEdgeSet s
variable {G} {H : SimpleGraph V} {s s₁ s₂ : Set (Sym2 V)}
instance [DecidableRel G.Adj] [DecidablePred (· ∈ s)] [DecidableEq V] :
DecidableRel (G.deleteEdges s).Adj :=
inferInstanceAs <| DecidableRel (G \ fromEdgeSet s).Adj
@[simp] lemma deleteEdges_adj : (G.deleteEdges s).Adj v w ↔ G.Adj v w ∧ s(v, w) ∉ s :=
and_congr_right fun h ↦ (and_iff_left h.ne).not
@[simp] lemma deleteEdges_edgeSet (G G' : SimpleGraph V) : G.deleteEdges G'.edgeSet = G \ G' := by
ext; simp
@[simp]
theorem deleteEdges_deleteEdges (s s' : Set (Sym2 V)) :
(G.deleteEdges s).deleteEdges s' = G.deleteEdges (s ∪ s') := by simp [deleteEdges, sdiff_sdiff]
@[simp] lemma deleteEdges_empty : G.deleteEdges ∅ = G := by simp [deleteEdges]
@[simp] lemma deleteEdges_univ : G.deleteEdges Set.univ = ⊥ := by simp [deleteEdges]
lemma deleteEdges_le (s : Set (Sym2 V)) : G.deleteEdges s ≤ G := sdiff_le
lemma deleteEdges_anti (h : s₁ ⊆ s₂) : G.deleteEdges s₂ ≤ G.deleteEdges s₁ :=
sdiff_le_sdiff_left <| fromEdgeSet_mono h
lemma deleteEdges_mono (h : G ≤ H) : G.deleteEdges s ≤ H.deleteEdges s := sdiff_le_sdiff_right h
@[simp] lemma deleteEdges_eq_self : G.deleteEdges s = G ↔ Disjoint G.edgeSet s := by
rw [deleteEdges, sdiff_eq_left, disjoint_fromEdgeSet]
theorem deleteEdges_eq_inter_edgeSet (s : Set (Sym2 V)) :
G.deleteEdges s = G.deleteEdges (s ∩ G.edgeSet) := by
ext
simp +contextual [imp_false]
theorem deleteEdges_sdiff_eq_of_le {H : SimpleGraph V} (h : H ≤ G) :
G.deleteEdges (G.edgeSet \ H.edgeSet) = H := by
rw [← edgeSet_sdiff, deleteEdges_edgeSet, sdiff_sdiff_eq_self h]
theorem edgeSet_deleteEdges (s : Set (Sym2 V)) : (G.deleteEdges s).edgeSet = G.edgeSet \ s := by
simp [deleteEdges]
theorem edgeFinset_deleteEdges [DecidableEq V] [Fintype G.edgeSet] (s : Finset (Sym2 V))
[Fintype (G.deleteEdges s).edgeSet] :
(G.deleteEdges s).edgeFinset = G.edgeFinset \ s := by
ext e
simp [edgeSet_deleteEdges]
end DeleteEdges
section DeleteIncidenceSet
/-- Given a vertex `x`, remove the edges incident to `x` from the edge set. -/
def deleteIncidenceSet (G : SimpleGraph V) (x : V) : SimpleGraph V :=
G.deleteEdges (G.incidenceSet x)
lemma deleteIncidenceSet_adj {G : SimpleGraph V} {x v₁ v₂ : V} :
(G.deleteIncidenceSet x).Adj v₁ v₂ ↔ G.Adj v₁ v₂ ∧ v₁ ≠ x ∧ v₂ ≠ x := by
rw [deleteIncidenceSet, deleteEdges_adj, mk'_mem_incidenceSet_iff]
tauto
lemma deleteIncidenceSet_le (G : SimpleGraph V) (x : V) : G.deleteIncidenceSet x ≤ G :=
deleteEdges_le (G.incidenceSet x)
lemma edgeSet_fromEdgeSet_incidenceSet (G : SimpleGraph V) (x : V) :
(fromEdgeSet (G.incidenceSet x)).edgeSet = G.incidenceSet x := by
rw [edgeSet_fromEdgeSet, sdiff_eq_left, ← Set.subset_compl_iff_disjoint_right, Set.compl_setOf]
exact (incidenceSet_subset G x).trans G.edgeSet_subset_setOf_not_isDiag
/-- The edge set of `G.deleteIncidenceSet x` is the edge set of `G` set difference the incidence
set of the vertex `x`. -/
theorem edgeSet_deleteIncidenceSet (G : SimpleGraph V) (x : V) :
(G.deleteIncidenceSet x).edgeSet = G.edgeSet \ G.incidenceSet x := by
simp_rw [deleteIncidenceSet, deleteEdges, edgeSet_sdiff, edgeSet_fromEdgeSet_incidenceSet]
/-- The support of `G.deleteIncidenceSet x` is a subset of the support of `G` set difference the
singleton set `{x}`. -/
theorem support_deleteIncidenceSet_subset (G : SimpleGraph V) (x : V) :
(G.deleteIncidenceSet x).support ⊆ G.support \ {x} :=
fun _ ↦ by simp_rw [mem_support, deleteIncidenceSet_adj]; tauto
/-- If the vertex `x` is not in the set `s`, then the induced subgraph in `G.deleteIncidenceSet x`
by `s` is equal to the induced subgraph in `G` by `s`. -/
theorem induce_deleteIncidenceSet_of_notMem (G : SimpleGraph V) {s : Set V} {x : V} (h : x ∉ s) :
(G.deleteIncidenceSet x).induce s = G.induce s := by
ext v₁ v₂
simp_rw [comap_adj, Function.Embedding.coe_subtype, deleteIncidenceSet_adj, and_iff_left_iff_imp]
exact fun _ ↦ ⟨v₁.prop.ne_of_notMem h, v₂.prop.ne_of_notMem h⟩
@[deprecated (since := "2025-05-23")]
alias induce_deleteIncidenceSet_of_not_mem := induce_deleteIncidenceSet_of_notMem
variable [Fintype V] [DecidableEq V]
instance {G : SimpleGraph V} [DecidableRel G.Adj] {x : V} :
DecidableRel (G.deleteIncidenceSet x).Adj :=
inferInstanceAs <| DecidableRel (G.deleteEdges (G.incidenceSet x)).Adj
/-- Deleting the incidence set of the vertex `x` retains the same number of edges as in the induced
subgraph of the vertices `{x}ᶜ`. -/
theorem card_edgeFinset_induce_compl_singleton (G : SimpleGraph V) [DecidableRel G.Adj] (x : V) :
#(G.induce {x}ᶜ).edgeFinset = #(G.deleteIncidenceSet x).edgeFinset := by
have h_notMem : x ∉ ({x}ᶜ : Set V) := Set.notMem_compl_iff.mpr (Set.mem_singleton x)
simp_rw [Set.toFinset_card,
← G.induce_deleteIncidenceSet_of_notMem h_notMem, ← Set.toFinset_card]
apply card_edgeFinset_induce_of_support_subset
trans G.support \ {x}
· exact support_deleteIncidenceSet_subset G x
· rw [Set.compl_eq_univ_diff]
exact Set.diff_subset_diff_left (Set.subset_univ G.support)
/-- The finite edge set of `G.deleteIncidenceSet x` is the finite edge set of the simple graph `G`
set difference the finite incidence set of the vertex `x`. -/
theorem edgeFinset_deleteIncidenceSet_eq_sdiff (G : SimpleGraph V) [DecidableRel G.Adj] (x : V) :
(G.deleteIncidenceSet x).edgeFinset = G.edgeFinset \ G.incidenceFinset x := by
rw [incidenceFinset, ← Set.toFinset_diff, Set.toFinset_inj]
exact G.edgeSet_deleteIncidenceSet x
/-- Deleting the incident set of the vertex `x` deletes exactly `G.degree x` edges from the edge
set of the simple graph `G`. -/
theorem card_edgeFinset_deleteIncidenceSet (G : SimpleGraph V) [DecidableRel G.Adj] (x : V) :
#(G.deleteIncidenceSet x).edgeFinset = #G.edgeFinset - G.degree x := by
simp_rw [← card_incidenceFinset_eq_degree, ← card_sdiff_of_subset (G.incidenceFinset_subset x),
edgeFinset_deleteIncidenceSet_eq_sdiff]
/-- Deleting the incident set of the vertex `x` is equivalent to filtering the edges of the simple
graph `G` that do not contain `x`. -/
theorem edgeFinset_deleteIncidenceSet_eq_filter (G : SimpleGraph V) [DecidableRel G.Adj] (x : V) :
(G.deleteIncidenceSet x).edgeFinset = G.edgeFinset.filter (x ∉ ·) := by
rw [edgeFinset_deleteIncidenceSet_eq_sdiff, sdiff_eq_filter]
apply filter_congr
intro _ h
rw [incidenceFinset, Set.mem_toFinset, incidenceSet,
Set.mem_setOf_eq, not_and, Classical.imp_iff_right_iff]
left
rwa [mem_edgeFinset] at h
/-- The support of `G.deleteIncidenceSet x` is at most `1` less than the support of the simple
graph `G`. -/
theorem card_support_deleteIncidenceSet
(G : SimpleGraph V) [DecidableRel G.Adj] {x : V} (hx : x ∈ G.support) :
card (G.deleteIncidenceSet x).support ≤ card G.support - 1 := by
rw [← Set.singleton_subset_iff, ← Set.toFinset_subset_toFinset] at hx
simp_rw [← Set.card_singleton x, ← Set.toFinset_card, ← card_sdiff_of_subset hx,
← Set.toFinset_diff]
apply card_le_card
rw [Set.toFinset_subset_toFinset]
exact G.support_deleteIncidenceSet_subset x
end DeleteIncidenceSet
section DeleteFar
variable {𝕜 : Type*} [Ring 𝕜] [PartialOrder 𝕜]
[Fintype G.edgeSet] {p : SimpleGraph V → Prop} {r r₁ r₂ : 𝕜}
/-- A graph is `r`-*delete-far* from a property `p` if we must delete at least `r` edges from it to
get a graph with the property `p`. -/
def DeleteFar (p : SimpleGraph V → Prop) (r : 𝕜) : Prop :=
∀ ⦃s⦄, s ⊆ G.edgeFinset → p (G.deleteEdges s) → r ≤ #s
variable {G}
theorem deleteFar_iff [Fintype (Sym2 V)] :
G.DeleteFar p r ↔ ∀ ⦃H : SimpleGraph _⦄ [DecidableRel H.Adj],
H ≤ G → p H → r ≤ #G.edgeFinset - #H.edgeFinset := by
classical
refine ⟨fun h H _ hHG hH ↦ ?_, fun h s hs hG ↦ ?_⟩
· have := h (sdiff_subset (t := H.edgeFinset))
simp only [deleteEdges_sdiff_eq_of_le hHG, edgeFinset_mono hHG, card_sdiff_of_subset,
card_le_card, coe_sdiff, coe_edgeFinset, Nat.cast_sub] at this
exact this hH
· classical
simpa [card_sdiff_of_subset hs, edgeFinset_deleteEdges, -Set.toFinset_card, Nat.cast_sub,
card_le_card hs] using h (G.deleteEdges_le s) hG
alias ⟨DeleteFar.le_card_sub_card, _⟩ := deleteFar_iff
theorem DeleteFar.mono (h : G.DeleteFar p r₂) (hr : r₁ ≤ r₂) : G.DeleteFar p r₁ := fun _ hs hG =>
hr.trans <| h hs hG
lemma DeleteFar.le_card_edgeFinset (h : G.DeleteFar p r) (hp : p ⊥) : r ≤ #G.edgeFinset :=
h subset_rfl (by simpa)
end DeleteFar
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Hasse.lean | import Mathlib.Combinatorics.SimpleGraph.Prod
import Mathlib.Data.Fin.SuccPredOrder
import Mathlib.Data.Nat.SuccPred
import Mathlib.Order.SuccPred.Relation
import Mathlib.Tactic.FinCases
/-!
# The Hasse diagram as a graph
This file defines the Hasse diagram of an order (graph of `CovBy`, the covering relation) and the
path graph on `n` vertices.
## Main declarations
* `SimpleGraph.hasse`: Hasse diagram of an order.
* `SimpleGraph.pathGraph`: Path graph on `n` vertices.
-/
open Order OrderDual Relation
namespace SimpleGraph
variable (α β : Type*)
section Preorder
variable [Preorder α]
/-- The Hasse diagram of an order as a simple graph. The graph of the covering relation. -/
def hasse : SimpleGraph α where
Adj a b := a ⋖ b ∨ b ⋖ a
symm _a _b := Or.symm
loopless _a h := h.elim (irrefl _) (irrefl _)
variable {α β} {a b : α}
@[simp]
theorem hasse_adj : (hasse α).Adj a b ↔ a ⋖ b ∨ b ⋖ a :=
Iff.rfl
/-- `αᵒᵈ` and `α` have the same Hasse diagram. -/
def hasseDualIso : hasse αᵒᵈ ≃g hasse α :=
{ ofDual with map_rel_iff' := by simp [or_comm] }
@[simp]
theorem hasseDualIso_apply (a : αᵒᵈ) : hasseDualIso a = ofDual a :=
rfl
@[simp]
theorem hasseDualIso_symm_apply (a : α) : hasseDualIso.symm a = toDual a :=
rfl
end Preorder
section PartialOrder
variable [PartialOrder α] [PartialOrder β]
@[simp]
theorem hasse_prod : hasse (α × β) = hasse α □ hasse β := by
ext x y
simp_rw [boxProd_adj, hasse_adj, Prod.covBy_iff, or_and_right, @eq_comm _ y.1, @eq_comm _ y.2,
or_or_or_comm]
end PartialOrder
section LinearOrder
variable [LinearOrder α]
theorem hasse_preconnected_of_succ [SuccOrder α] [IsSuccArchimedean α] : (hasse α).Preconnected :=
fun a b => by
rw [reachable_iff_reflTransGen]
exact
reflTransGen_of_succ _ (fun c hc => Or.inl <| covBy_succ_of_not_isMax hc.2.not_isMax)
fun c hc => Or.inr <| covBy_succ_of_not_isMax hc.2.not_isMax
theorem hasse_preconnected_of_pred [PredOrder α] [IsPredArchimedean α] : (hasse α).Preconnected :=
fun a b => by
rw [reachable_iff_reflTransGen, ← reflTransGen_swap]
exact
reflTransGen_of_pred _ (fun c hc => Or.inl <| pred_covBy_of_not_isMin hc.1.not_isMin)
fun c hc => Or.inr <| pred_covBy_of_not_isMin hc.1.not_isMin
end LinearOrder
/-- The path graph on `n` vertices. -/
def pathGraph (n : ℕ) : SimpleGraph (Fin n) :=
hasse _
theorem pathGraph_adj {n : ℕ} {u v : Fin n} :
(pathGraph n).Adj u v ↔ u.val + 1 = v.val ∨ v.val + 1 = u.val := by
simp only [pathGraph, hasse]
simp_rw [← Fin.coe_covBy_iff, covBy_iff_add_one_eq]
theorem pathGraph_preconnected (n : ℕ) : (pathGraph n).Preconnected :=
hasse_preconnected_of_succ _
theorem pathGraph_connected (n : ℕ) : (pathGraph (n + 1)).Connected :=
⟨pathGraph_preconnected _⟩
theorem pathGraph_two_eq_top : pathGraph 2 = ⊤ := by
ext u v
fin_cases u <;> fin_cases v <;> simp [pathGraph, ← Fin.coe_covBy_iff, covBy_iff_add_one_eq]
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Tutte.lean | import Mathlib.Combinatorics.SimpleGraph.Matching
import Mathlib.Combinatorics.SimpleGraph.Metric
import Mathlib.Combinatorics.SimpleGraph.Operations
import Mathlib.Combinatorics.SimpleGraph.UniversalVerts
import Mathlib.Data.Fintype.Card
/-!
# Tutte's theorem
## Main definitions
* `SimpleGraph.TutteViolator G u` is a set of vertices `u` such that the amount of
odd components left after deleting `u` from `G` is larger than the number of vertices in `u`.
This certifies non-existence of a perfect matching.
## Main results
* `SimpleGraph.tutte` states Tutte's theorem: A graph has a perfect matching, if and
only if no Tutte violators exist.
-/
namespace SimpleGraph
variable {V : Type*} {G G' : SimpleGraph V} {u x v' w : V}
/-- A set certifying non-existence of a perfect matching -/
def IsTutteViolator (G : SimpleGraph V) (u : Set V) : Prop :=
u.ncard < ((⊤ : G.Subgraph).deleteVerts u).coe.oddComponents.ncard
/-- This lemma shows an alternating cycle exists in a specific subcase of the proof
of Tutte's theorem. -/
private lemma tutte_exists_isAlternating_isCycles {x b a c : V} {M : Subgraph (G ⊔ edge a c)}
(p : G'.Walk a x) (hp : p.IsPath) (hcalt : G'.IsAlternating M.spanningCoe)
(hM2nadj : ¬M.Adj x a) (hpac : p.toSubgraph.Adj a c) (hnpxb : ¬p.toSubgraph.Adj x b)
(hM2ac : M.Adj a c) (hgadj : G.Adj x a) (hnxc : x ≠ c) (hnab : a ≠ b)
(hle : p.toSubgraph.spanningCoe ≤ G ⊔ edge a c)
(aux : (c' : V) → c' ≠ a → p.toSubgraph.Adj c' x → M.Adj c' x) :
∃ G', G'.IsAlternating M.spanningCoe ∧ G'.IsCycles ∧
¬ G'.Adj x b ∧ G'.Adj a c ∧ G' ≤ G ⊔ edge a c := by
refine ⟨p.toSubgraph.spanningCoe ⊔ edge x a, (hcalt.spanningCoe p.toSubgraph).sup_edge (by simpa)
(fun u' hu'x hadj ↦ ?_) aux, ?_, ?_, by aesop, sup_le_iff.mpr ⟨hle, fun v w hvw ↦ ?_⟩⟩
· simpa [← hp.snd_of_toSubgraph_adj hadj, hp.snd_of_toSubgraph_adj hpac]
· refine hp.isCycles_spanningCoe_toSubgraph_sup_edge hgadj.ne.symm fun hadj ↦ ?_
rw [← Walk.mem_edges_toSubgraph, Subgraph.mem_edgeSet] at hadj
simp [← hp.snd_of_toSubgraph_adj hadj.symm, hp.snd_of_toSubgraph_adj hpac] at hnxc
· simp +contextual [hnpxb, edge_adj, hnab.symm]
· simpa [edge_adj, adj_congr_of_sym2 _ ((adj_edge _ _).mp hvw).1.symm] using .inl hgadj
variable [Finite V]
lemma IsTutteViolator.mono {u : Set V} (h : G ≤ G') (ht : G'.IsTutteViolator u) :
G.IsTutteViolator u := by
simp only [IsTutteViolator, Subgraph.induce_verts, Subgraph.verts_top] at *
have := ncard_oddComponents_mono _ (Subgraph.deleteVerts_mono' (G := G) (G' := G') u h)
simp only [oddComponents] at *
cutsat
/-- Given a graph in which the universal vertices do not violate Tutte's condition,
if the graph decomposes into cliques, there exists a matching that covers
everything except some universal vertices.
This lemma is marked private, because
it is strictly weaker than `IsPerfectMatching.exists_of_isClique_supp`. -/
private lemma Subgraph.IsMatching.exists_verts_compl_subset_universalVerts
(h : ¬IsTutteViolator G G.universalVerts)
(h' : ∀ (K : G.deleteUniversalVerts.coe.ConnectedComponent),
G.deleteUniversalVerts.coe.IsClique K.supp) :
∃ M : Subgraph G, M.IsMatching ∧ M.vertsᶜ ⊆ G.universalVerts := by
classical
have hrep := ConnectedComponent.Represents.image_out G.deleteUniversalVerts.coe.oddComponents
-- First we match one node from each odd component to a universal vertex
obtain ⟨t, ht, M1, hM1⟩ := Subgraph.IsMatching.exists_of_universalVerts
(disjoint_image_val_universalVerts _).symm (by
simp only [IsTutteViolator, not_lt] at h
rwa [Set.ncard_image_of_injective _ Subtype.val_injective, hrep.ncard_eq])
-- Then we match all other nodes in components internally
have exists_complMatch (K : G.deleteUniversalVerts.coe.ConnectedComponent) :
∃ M : Subgraph G, M.verts = Subtype.val '' K.supp \ M1.verts ∧ M.IsMatching := by
have : G.IsClique (Subtype.val '' K.supp \ M1.verts) :=
((h' K).of_induce).subset Set.diff_subset
rw [← this.even_iff_exists_isMatching (Set.toFinite _), hM1.1]
exact even_ncard_image_val_supp_sdiff_image_val_rep_union _ ht hrep
choose complMatch hcomplMatch_compl hcomplMatch_match using exists_complMatch
let M2 : Subgraph G := ⨆ K, complMatch K
have hM2 : M2.IsMatching := by
refine .iSup hcomplMatch_match fun i j hij ↦ (?_ : Disjoint _ _)
rw [(hcomplMatch_match i).support_eq_verts, hcomplMatch_compl i,
(hcomplMatch_match j).support_eq_verts, hcomplMatch_compl j]
exact Set.disjoint_of_subset Set.diff_subset Set.diff_subset <|
Set.disjoint_image_of_injective Subtype.val_injective <|
SimpleGraph.pairwise_disjoint_supp_connectedComponent _ hij
have disjointM12 : Disjoint M1.support M2.support := by
rw [hM1.2.support_eq_verts, hM2.support_eq_verts, Subgraph.verts_iSup,
Set.disjoint_iUnion_right]
exact fun K ↦ hcomplMatch_compl K ▸ Set.disjoint_sdiff_right
-- The only vertices left are indeed contained in universalVerts
have : (M1.verts ∪ M2.verts)ᶜ ⊆ G.universalVerts := by
rw [Set.compl_subset_comm, Set.compl_eq_univ_diff]
intro v hv
by_cases h : v ∈ M1.verts
· exact M1.verts.mem_union_left _ h
right
simp only [deleteUniversalVerts_verts, Subgraph.verts_iSup, Set.mem_iUnion, M2,
hcomplMatch_compl]
use G.deleteUniversalVerts.coe.connectedComponentMk ⟨v, hv⟩
aesop
exact ⟨M1 ⊔ M2, hM1.2.sup hM2 disjointM12, this⟩
/-- If the universal vertices of a graph `G` decompose `G` into cliques such that the Tutte isn't
violated, then `G` has a perfect matching. -/
theorem Subgraph.IsPerfectMatching.exists_of_isClique_supp
(hveven : Even (Nat.card V)) (h : ¬G.IsTutteViolator G.universalVerts)
(h' : ∀ (K : G.deleteUniversalVerts.coe.ConnectedComponent),
G.deleteUniversalVerts.coe.IsClique K.supp) :
∃ (M : Subgraph G), M.IsPerfectMatching := by
classical
cases nonempty_fintype V
obtain ⟨M, hM, hsub⟩ := IsMatching.exists_verts_compl_subset_universalVerts h h'
obtain ⟨M', hM'⟩ := ((G.isClique_universalVerts.subset hsub).even_iff_exists_isMatching
(Set.toFinite _)).mp (by simpa [Set.even_ncard_compl_iff hveven, -Set.toFinset_card,
← Set.ncard_eq_toFinset_card'] using hM.even_card)
refine ⟨M ⊔ M', hM.sup hM'.2 ?_, ?_⟩
· simp [hM.support_eq_verts, hM'.2.support_eq_verts, hM'.1, disjoint_compl_right]
· rw [Subgraph.isSpanning_iff, Subgraph.verts_sup, hM'.1]
exact M.verts.union_compl_self
theorem IsTutteViolator.empty (hodd : Odd (Nat.card V)) : G.IsTutteViolator ∅ := by
rw [IsTutteViolator, Set.ncard_empty]
exact ((odd_ncard_oddComponents _).mpr <| by simpa using hodd).pos
/-- Proves the necessity part of Tutte's theorem -/
lemma not_isTutteViolator_of_isPerfectMatching {M : Subgraph G} (hM : M.IsPerfectMatching)
(u : Set V) :
¬G.IsTutteViolator u := by
choose f hf g hgf hg using ConnectedComponent.odd_matches_node_outside hM (u := u)
have hfinj : f.Injective := fun c d hcd ↦ by
replace hcd : g c = g d := Subtype.val_injective <| hM.1.eq_of_adj_right (hgf c) (hcd ▸ hgf d)
exact Subtype.val_injective <| ConnectedComponent.eq_of_common_vertex (hg c) (hcd ▸ hg d)
simpa [IsTutteViolator] using
Nat.card_le_card_of_injective (fun c ↦ ⟨f c, hf c⟩) (fun c d ↦ by simp [hfinj.eq_iff])
open scoped symmDiff
/-- This lemma constructs a perfect matching on `G` from two near-matchings. -/
private theorem tutte_exists_isPerfectMatching_of_near_matchings {x a b c : V}
{M1 : Subgraph (G ⊔ edge x b)} {M2 : Subgraph (G ⊔ edge a c)} (hxa : G.Adj x a)
(hab : G.Adj a b) (hnGxb : ¬G.Adj x b) (hnGac : ¬G.Adj a c) (hnxb : x ≠ b) (hnxc : x ≠ c)
(hnac : a ≠ c) (hnbc : b ≠ c) (hM1 : M1.IsPerfectMatching) (hM2 : M2.IsPerfectMatching) :
∃ (M : Subgraph G), M.IsPerfectMatching := by
classical
-- If either matching does not contain their extra edge, we just use it as a perfect matching
by_cases hM1xb : ¬M1.Adj x b
· use G.toSubgraph M1.spanningCoe (M1.spanningCoe_sup_edge_le _ hM1xb)
exact (Subgraph.IsPerfectMatching.toSubgraph_iff (M1.spanningCoe_sup_edge_le _ hM1xb)).mpr hM1
by_cases hM2ac : ¬M2.Adj a c
· use G.toSubgraph M2.spanningCoe (M2.spanningCoe_sup_edge_le _ hM2ac)
exact (Subgraph.IsPerfectMatching.toSubgraph_iff (M2.spanningCoe_sup_edge_le _ hM2ac)).mpr hM2
simp only [not_not] at hM1xb hM2ac
-- Neither matching contains the edge that would make the other matching of G perfect
have hM1nac : ¬M1.Adj a c := fun h ↦ by simpa [hnGac, edge_adj, hnac, hxa.ne, hnbc.symm, hab.ne]
using h.adj_sub
have hsupG : G ⊔ edge x b ⊔ (G ⊔ edge a c) = (G ⊔ edge a c) ⊔ edge x b := by aesop
-- We state conditions for our cycle that hold in all cases and show that this suffices
suffices ∃ (G' : SimpleGraph V), G'.IsAlternating M2.spanningCoe ∧ G'.IsCycles ∧ ¬G'.Adj x b ∧
G'.Adj a c ∧ G' ≤ G ⊔ edge a c by
obtain ⟨G', hG', hG'cyc, hG'xb, hnG'ac, hle⟩ := this
have : M2.spanningCoe ∆ G' ≤ G := by
apply Disjoint.left_le_of_le_sup_right (symmDiff_le (le_sup_of_le_right M2.spanningCoe_le)
(le_sup_of_le_right hle))
simp [disjoint_edge, symmDiff_def, hM2ac, hnG'ac]
use (G.toSubgraph (symmDiff M2.spanningCoe G') this)
apply hM2.symmDiff_of_isAlternating hG' hG'cyc
-- We consider the symmetric difference of the two matchings
let cycles := M1.spanningCoe ∆ M2.spanningCoe
have hcalt : cycles.IsAlternating M2.spanningCoe := hM1.isAlternating_symmDiff_right hM2
have hcycles := Subgraph.IsPerfectMatching.symmDiff_isCycles hM1 hM2
have hcac : cycles.Adj a c := by simp [cycles, symmDiff_def, hM2ac, hM1nac]
have hM1sub := Subgraph.spanningCoe_le M1
have hM2sub := Subgraph.spanningCoe_le M2
-- We consider the cycle that contains the vertex `c`
have induce_le : ((cycles.connectedComponentMk c).toSimpleGraph).spanningCoe ≤
(G ⊔ edge a c) ⊔ edge x b := by
refine le_trans (spanningCoe_induce_le cycles (cycles.connectedComponentMk c).supp) ?_
simp only [← hsupG, cycles]
exact le_trans (by apply symmDiff_le_sup) (sup_le_sup hM1sub hM2sub)
-- If that cycle does not contain the vertex `x`, we use it as an alternating cycle
by_cases! hxc : x ∉ (cycles.connectedComponentMk c).supp
· use (cycles.connectedComponentMk c).toSimpleGraph.spanningCoe
refine ⟨hcalt.mono (spanningCoe_induce_le cycles (cycles.connectedComponentMk c).supp), ?_⟩
simp only [ConnectedComponent.adj_spanningCoe_toSimpleGraph, hxc, hcac, false_and,
not_false_eq_true, ConnectedComponent.mem_supp_iff, ConnectedComponent.eq, and_true,
true_and, hcac.reachable]
refine ⟨hcycles.toSimpleGraph (cycles.connectedComponentMk c),
Disjoint.left_le_of_le_sup_right induce_le ?_⟩
rw [disjoint_edge]
rw [ConnectedComponent.adj_spanningCoe_toSimpleGraph]
simp_all
have hacc := ((cycles.connectedComponentMk c).mem_supp_congr_adj hcac.symm).mp rfl
have (G : SimpleGraph V) : LocallyFinite G := fun _ ↦ Fintype.ofFinite _
have hnM2 (x' : V) (h : x' ≠ c) : ¬ M2.Adj x' a := by
rw [M2.adj_comm]
exact hM2.1.not_adj_left_of_ne h.symm hM2ac
-- Else we construct a path that contain the edge `a c`, but not the edge `x b`
obtain ⟨x', hx', p, hp, hpac, hnpxb⟩ :
∃ x' ∈ ({x, b} : Finset V), ∃ (p : cycles.Walk a x'), p.IsPath ∧
p.toSubgraph.Adj a c ∧ ¬p.toSubgraph.Adj x b := by
obtain ⟨p, hp⟩ := hcycles.exists_cycle_toSubgraph_verts_eq_connectedComponentSupp hacc
⟨_, hcac⟩
obtain ⟨p', hp'⟩ := hp.1.exists_isCycle_snd_verts_eq (by
rwa [hp.1.adj_toSubgraph_iff_of_isCycles hcycles (hp.2 ▸ hacc)])
obtain ⟨x', hx', hx'p, htw⟩ := Walk.exists_mem_support_forall_mem_support_imp_eq {x, b} <| by
use x
simp only [Finset.mem_filter, Finset.mem_insert, Finset.mem_singleton, true_or, true_and]
rwa [← @Walk.mem_verts_toSubgraph, hp'.2.2, hp.2]
refine ⟨x', hx', p'.takeUntil x' hx'p, hp'.1.isPath_takeUntil hx'p, ?_, fun h ↦ ?_⟩; swap
· simp [htw _ (by simp) (Walk.mem_support_of_adj_toSubgraph h.symm),
htw _ (by simp) (Walk.mem_support_of_adj_toSubgraph h)] at hnxb
have : (p'.takeUntil x' hx'p).toSubgraph.Adj a (p'.takeUntil x' hx'p).snd := by
apply Walk.toSubgraph_adj_snd
rw [Walk.nil_takeUntil]
aesop
rwa [Walk.snd_takeUntil, hp'.2.1] at this
simp only [Finset.mem_insert, Finset.mem_singleton] at hx'
obtain rfl | rfl := hx'
exacts [hxa.ne, hab.ne.symm]
-- We show this path satisfies all requirements
have hle : p.toSubgraph.spanningCoe ≤ G ⊔ edge a c := by
rw [← sdiff_edge _ (by simpa : ¬p.toSubgraph.spanningCoe.Adj x b), sdiff_le_iff']
intro v w hvw
apply hsupG ▸ sup_le_sup hM1sub hM2sub
have := p.toSubgraph.spanningCoe_le hvw
simp only [cycles, symmDiff_def] at this
aesop
-- Helper condition to show that `p` ends with an edge in `M2`
have aux {x' : V} (hx' : x' ∈ ({x, b} : Set V)) (c' : V) (hc : c' ≠ a)
(hadj : p.toSubgraph.Adj c' x') : M2.Adj c' x' := by
refine (hadj.adj_sub.resolve_left fun hl ↦ hnpxb ?_).1
obtain ⟨w, -, hw⟩ := hM1.1 (hM1.2 x')
obtain rfl | rfl := hx'
· rw [hw _ hM1xb, ← hw _ hl.1.symm]
exact hadj.symm
· rw [hw _ hM1xb.symm, ← hw _ hl.1.symm]
exact hadj
simp only [Finset.mem_insert, Finset.mem_singleton] at hx'
obtain rfl | rfl := hx'
· exact tutte_exists_isAlternating_isCycles p hp hcalt (hnM2 x' hnxc) hpac hnpxb hM2ac
hxa hnxc hab.ne hle (aux (by simp))
· conv =>
enter [1, G', 2, 2, 1, 1]
rw [adj_comm]
rw [Subgraph.adj_comm] at hnpxb
exact tutte_exists_isAlternating_isCycles p hp hcalt (hnM2 _ hnbc) hpac hnpxb hM2ac
hab.symm hnbc hxa.ne.symm hle (aux (by simp))
/-- From a graph on an even number of vertices with no perfect matching, we can remove an odd number
of vertices such that there are more odd components in the resulting graph than vertices we removed.
This is the sufficiency side of Tutte's theorem. -/
lemma exists_isTutteViolator (h : ∀ (M : G.Subgraph), ¬M.IsPerfectMatching)
(hvEven : Even (Nat.card V)) :
∃ u, G.IsTutteViolator u := by
classical
cases nonempty_fintype V
-- It suffices to consider the edge-maximal case
obtain ⟨Gmax, hSubgraph, hMatchingFree, hMaximal⟩ := exists_maximal_isMatchingFree h
refine ⟨Gmax.universalVerts, .mono hSubgraph ?_⟩
by_contra! hc
simp only [IsTutteViolator, Set.ncard_eq_toFinset_card', Set.toFinset_card] at hc
by_cases! h' : ∀ (K : ConnectedComponent Gmax.deleteUniversalVerts.coe),
Gmax.deleteUniversalVerts.coe.IsClique K.supp
· -- Deleting universal vertices splits the graph into cliques
rw [Fintype.card_eq_nat_card] at hc
simp_rw [Fintype.card_eq_nat_card, Nat.card_coe_set_eq] at hc
push_neg at hc
obtain ⟨M, hM⟩ := Subgraph.IsPerfectMatching.exists_of_isClique_supp hvEven
(by simpa [IsTutteViolator] using hc) h'
exact hMatchingFree M hM
· -- Deleting universal vertices does not result in only cliques
obtain ⟨K, hK⟩ := h'
obtain ⟨x, y, hxy⟩ := (not_isClique_iff _).mp hK
obtain ⟨p, hp⟩ := Reachable.exists_path_of_dist (K.connected_toSimpleGraph x y)
obtain ⟨x, a, b, hxa, hxb, hnadjxb, hnxb⟩ := Walk.exists_adj_adj_not_adj_ne hp.2
(p.reachable.one_lt_dist_of_ne_of_not_adj hxy.1 hxy.2)
simp only [ConnectedComponent.toSimpleGraph, deleteUniversalVerts, universalVerts, ne_eq,
Subgraph.induce_verts, Subgraph.verts_top, comap_adj, Function.Embedding.coe_subtype,
Subgraph.coe_adj, Subgraph.induce_adj, Subtype.coe_prop, Subgraph.top_adj, true_and]
at hxa hxb hnadjxb
obtain ⟨c, hc⟩ : ∃ (c : V), (a : V) ≠ c ∧ ¬ Gmax.Adj c a := by
simpa [universalVerts] using a.1.2.2
have hbnec : b.val.val ≠ c := by rintro rfl; exact hc.2 hxb.symm
obtain ⟨_, hG1⟩ := hMaximal _ <| left_lt_sup.mpr (by
rw [edge_le_iff (v := x.1.1) (w := b.1.1)]
simp [hnadjxb, Subtype.val_injective.ne <| Subtype.val_injective.ne hnxb])
obtain ⟨_, hG2⟩ := hMaximal _ <| left_lt_sup.mpr (by
rwa [edge_le_iff (v := a.1.1) (w := c), adj_comm, not_or])
have hcnex : c ≠ x.val.val := by rintro rfl; exact hc.2 hxa
obtain ⟨Mcon, hMcon⟩ := tutte_exists_isPerfectMatching_of_near_matchings hxa
hxb hnadjxb (fun hadj ↦ hc.2 hadj.symm) (by aesop) hcnex.symm hc.1 hbnec hG1 hG2
exact hMatchingFree Mcon hMcon
/-- **Tutte's theorem**
A graph has a perfect matching if and only if: For every subset `u` of vertices, removing this
subset induces at most `u.ncard` components of odd size. This is formally stated using the
predicate `IsTutteViolator`, which is satisfied exactly when this condition does not hold. -/
theorem tutte : (∃ M : Subgraph G, M.IsPerfectMatching) ↔ ∀ u, ¬ G.IsTutteViolator u := by
classical
refine ⟨by rintro ⟨M, hM⟩; apply not_isTutteViolator_of_isPerfectMatching hM, ?_⟩
contrapose!
intro h
by_cases hvOdd : Odd (Nat.card V)
· exact ⟨∅, .empty hvOdd⟩
· exact exists_isTutteViolator h (Nat.not_odd_iff_even.mp hvOdd)
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/FiveWheelLike.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Combinatorics.SimpleGraph.CompleteMultipartite
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.Ring
/-!
# Five-wheel like graphs
This file defines an `IsFiveWheelLike` structure in a graph, and describes properties of these
structures as well as graphs which avoid this structure. These have two key uses:
* We use them to prove that a maximally `Kᵣ₊₁`-free graph is `r`-colorable iff it is
complete-multipartite: `colorable_iff_isCompleteMultipartite_of_maximal_cliqueFree`.
* They play a key role in Brandt's proof of the Andrásfai-Erdős-Sós theorem, which is where they
first appeared. We give this proof below, see `colorable_of_cliqueFree_lt_minDegree`.
If `G` is maximally `Kᵣ₊₂`-free and `¬ G.Adj x y` (with `x ≠ y`) then there exists an `r`-set `s`
such that `s ∪ {x}` and `s ∪ {y}` are both `r + 1`-cliques.
If `¬ G.IsCompleteMultipartite` then it contains a `G.IsPathGraph3Compl v w₁ w₂` consisting of
an edge `w₁w₂` and a vertex `v` such that `vw₁` and `vw₂` are non-edges.
Hence any maximally `Kᵣ₊₂`-free graph that is not complete-multipartite must contain distinct
vertices `v, w₁, w₂`, together with `r`-sets `s` and `t`, such that `{v, w₁, w₂}` induces the
single edge `w₁w₂`, `s ∪ t` is disjoint from `{v, w₁, w₂}`, and `s ∪ {v}`, `t ∪ {v}`, `s ∪ {w₁}` and
`t ∪ {w₂}` are all `r + 1`-cliques.
This leads to the definition of an `IsFiveWheelLike` structure which can be found in any maximally
`Kᵣ₊₂`-free graph that is not complete-multipartite (see
`exists_isFiveWheelLike_of_maximal_cliqueFree_not_isCompleteMultipartite`).
One key parameter in any such structure is the number of vertices common to all of the cliques: we
denote this quantity by `k = #(s ∩ t)` (and we will refer to such a structure as `Wᵣ,ₖ` below.)
The first interesting cases of such structures are `W₁,₀` and `W₂,₁`: `W₁,₀` is a 5-cycle,
while `W₂,₁` is a 5-cycle with an extra central hub vertex adjacent to all other vertices
(i.e. `W₂,₁` resembles a wheel with five spokes).
`W₁,₀` v `W₂,₁` v
/ \ / | \
s t s ─ u ─ t
\ / \ / \ /
w₁ ─ w₂ w₁ ─ w₂
## Main definitions
* `SimpleGraph.IsFiveWheelLike`: predicate for `v w₁ w₂ s t` to form a 5-wheel-like subgraph of
`G` with `r`-sets `s` and `t`, and vertices `v w₁ w₂` forming an `IsPathGraph3Compl` and
`#(s ∩ t) = k`.
* `SimpleGraph.FiveWheelLikeFree`: predicate for `G` to have no `IsFiveWheelLike r k` subgraph.
## Implementation notes
The definitions of `IsFiveWheelLike` and `IsFiveWheelLikeFree` in this file have `r` shifted by two
compared to the definitions in Brandt **On the structure of graphs with bounded clique number**
The definition of `IsFiveWheelLike` does not contain the facts that `#s = r` and `#t = r` but we
deduce these later as `card_left` and `card_right`.
Although `#(s ∩ t)` can easily be derived from `s` and `t` we include the `IsFiveWheelLike` field
`card_inter : #(s ∩ t) = k` to match the informal / paper definitions and to simplify some
statements of results and match our definition of `IsFiveWheelLikeFree`.
The vertex set of an `IsFiveWheel` structure `Wᵣ,ₖ` is `{v, w₁, w₂} ∪ s ∪ t : Finset α`.
We will need to refer to this consistently and choose the following formulation:
`{v} ∪ ({w₁} ∪ ({w₂} ∪ (s ∪ t)))` which is definitionally equal to
`insert v <| insert w₁ <| insert w₂ <| s ∪ t`.
## References
* [B. Andrasfái, P Erdős, V. T. Sós
**On the connection between chromatic number, maximal clique, and minimal degree of a graph**
https://doi.org/10.1016/0012-365X(74)90133-2][andrasfaiErdosSos1974]
* [S. Brandt **On the structure of graphs with bounded clique number**
https://doi.org/10.1007/s00493-003-0042-z][brandt2003]
-/
local notation "‖" x "‖" => Fintype.card x
open Finset SimpleGraph
variable {α : Type*} {a b c : α} {s : Finset α} {G : SimpleGraph α} {r k : ℕ}
namespace SimpleGraph
section withDecEq
variable [DecidableEq α]
private lemma IsNClique.insert_insert (h1 : G.IsNClique r (insert a s))
(h2 : G.IsNClique r (insert b s)) (h3 : b ∉ s) (ha : G.Adj a b) :
G.IsNClique (r + 1) (insert b (insert a s)) := by
apply h1.insert (fun b hb ↦ ?_)
obtain (rfl | h) := mem_insert.1 hb
· exact ha.symm
· exact h2.1 (mem_insert_self _ s) (mem_insert_of_mem h) <| fun h' ↦ (h3 (h' ▸ h)).elim
private lemma IsNClique.insert_insert_erase (hs : G.IsNClique r (insert a s)) (hc : c ∈ s)
(ha : a ∉ s) (hd : ∀ w ∈ insert a s, w ≠ c → G.Adj w b) :
G.IsNClique r (insert a (insert b (erase s c))) := by
rw [insert_comm, ← erase_insert_of_ne (fun h : a = c ↦ ha (h ▸ hc)|>.elim)]
simp_rw [adj_comm, ← notMem_singleton] at hd
exact hs.insert_erase (fun _ h ↦ hd _ (mem_sdiff.1 h).1 (mem_sdiff.1 h).2) (mem_insert_of_mem hc)
/--
An `IsFiveWheelLike r k v w₁ w₂ s t` structure in `G` consists of vertices `v w₁ w₂` and `r`-sets
`s` and `t` such that `{v, w₁, w₂}` induces the single edge `w₁w₂` (i.e. they form an
`IsPathGraph3Compl`), `v, w₁, w₂ ∉ s ∪ t`, `s ∪ {v}, t ∪ {v}, s ∪ {w₁}, t ∪ {w₂}` are all
`(r + 1)`-cliques and `#(s ∩ t) = k`. (If `G` is maximally `(r + 2)`-cliquefree and not complete
multipartite then `G` will contain such a structure: see
`exists_isFiveWheelLike_of_maximal_cliqueFree_not_isCompleteMultipartite`.)
-/
@[grind]
structure IsFiveWheelLike (G : SimpleGraph α) (r k : ℕ) (v w₁ w₂ : α) (s t : Finset α) :
Prop where
/-- `{v, w₁, w₂}` induces the single edge `w₁w₂` -/
isPathGraph3Compl : G.IsPathGraph3Compl v w₁ w₂
notMem_left : v ∉ s
notMem_right : v ∉ t
fst_notMem : w₁ ∉ s
snd_notMem : w₂ ∉ t
isNClique_left : G.IsNClique (r + 1) (insert v s)
isNClique_fst_left : G.IsNClique (r + 1) (insert w₁ s)
isNClique_right : G.IsNClique (r + 1) (insert v t)
isNClique_snd_right : G.IsNClique (r + 1) (insert w₂ t)
card_inter : #(s ∩ t) = k
lemma exists_isFiveWheelLike_of_maximal_cliqueFree_not_isCompleteMultipartite
(h : Maximal (fun H => H.CliqueFree (r + 2)) G) (hnc : ¬ G.IsCompleteMultipartite) :
∃ v w₁ w₂ s t, G.IsFiveWheelLike r #(s ∩ t) v w₁ w₂ s t := by
obtain ⟨v, w₁, w₂, p3⟩ := exists_isPathGraph3Compl_of_not_isCompleteMultipartite hnc
obtain ⟨s, h1, h2, h3, h4⟩ := exists_of_maximal_cliqueFree_not_adj h p3.ne_fst p3.not_adj_fst
obtain ⟨t, h5, h6, h7, h8⟩ := exists_of_maximal_cliqueFree_not_adj h p3.ne_snd p3.not_adj_snd
exact ⟨_, _, _, _, _, p3, h1, h5, h2, h6, h3, h4, h7, h8, rfl⟩
/-- `G.FiveWheelLikeFree r k` means there is no `IsFiveWheelLike r k` structure in `G`. -/
def FiveWheelLikeFree (G : SimpleGraph α) (r k : ℕ) : Prop :=
∀ {v w₁ w₂ s t}, ¬ G.IsFiveWheelLike r k v w₁ w₂ s t
namespace IsFiveWheelLike
variable {v w₁ w₂ : α} {t : Finset α} (hw : G.IsFiveWheelLike r k v w₁ w₂ s t)
include hw
@[symm] lemma symm : G.IsFiveWheelLike r k v w₂ w₁ t s :=
let ⟨p2, d1, d2, d3, d4, c1, c2, c3, c4, hk⟩ := hw
⟨p2.symm, d2, d1, d4, d3, c3, c4, c1, c2, by rwa [inter_comm]⟩
@[grind →]
lemma fst_notMem_right : w₁ ∉ t :=
fun h ↦ hw.isPathGraph3Compl.not_adj_fst <| hw.isNClique_right.1 (mem_insert_self ..)
(mem_insert_of_mem h) hw.isPathGraph3Compl.ne_fst
@[grind →]
lemma snd_notMem_left : w₂ ∉ s := hw.symm.fst_notMem_right
/--
Any graph containing an `IsFiveWheelLike r k` structure is not `(r + 1)`-colorable.
-/
lemma not_colorable_succ : ¬ G.Colorable (r + 1) := by
intro ⟨C⟩
have h := C.surjOn_of_card_le_isClique hw.isNClique_fst_left.1 (by simp [hw.isNClique_fst_left.2])
have := C.surjOn_of_card_le_isClique hw.isNClique_snd_right.1 (by simp [hw.isNClique_snd_right.2])
-- Since `C` is an `r + 1`-coloring and `insert w₁ s` is an `r + 1`-clique, it contains a vertex
-- `x` which shares its colour with `v`
obtain ⟨x, hx, hcx⟩ := h (a := C v) trivial
-- Similarly there is a vertex `y` in `insert w₂ t` which shares its colour with `v`.
obtain ⟨y, hy, hcy⟩ := this (a := C v) trivial
rw [coe_insert] at *
-- However since `insert v s` and `insert v t` are cliques, we must have `x = w₁` and `y = w₂`.
cases hx with
| inl hx =>
cases hy with
| inl hy =>
-- But this is a contradiction since `w₁` and `w₂` are adjacent.
subst_vars; exact C.valid hw.isPathGraph3Compl.adj (hcy ▸ hcx)
| inr hy =>
apply (C.valid _ hcy.symm).elim
exact hw.isNClique_right.1 (by simp) (by simp [hy]) fun h ↦ hw.notMem_right (h ▸ hy)
| inr hx =>
apply (C.valid _ hcx.symm).elim
exact hw.isNClique_left.1 (by simp) (by simp [hx]) fun h ↦ hw.notMem_left (h ▸ hx)
@[grind →]
lemma card_left : s.card = r := by
simp [← Nat.succ_inj, ← hw.isNClique_left.2, hw.notMem_left]
@[grind →]
lemma card_right : t.card = r := hw.symm.card_left
lemma card_inter_lt_of_cliqueFree (h : G.CliqueFree (r + 2)) : k < r := by
contrapose! h
-- If `r ≤ k` then `s = t` and so `s ∪ {w₁, w₂}` is an `r + 2`-clique, a contradiction.
have hs := eq_of_subset_of_card_le inter_subset_left (hw.card_inter ▸ hw.card_left ▸ h)
have := eq_of_subset_of_card_le inter_subset_right (hw.card_inter ▸ hw.card_right ▸ h)
exact (hw.isNClique_fst_left.insert_insert (hs ▸ this.symm ▸ hw.isNClique_snd_right)
hw.snd_notMem_left hw.isPathGraph3Compl.adj).not_cliqueFree
end IsFiveWheelLike
/--
Any maximally `Kᵣ₊₂`-free graph that is not complete-multipartite contains a maximal
`IsFiveWheelLike` structure `Wᵣ,ₖ` for some `k < r`. (It is maximal in terms of `k`.)
-/
lemma exists_max_isFiveWheelLike_of_maximal_cliqueFree_not_isCompleteMultipartite
(h : Maximal (fun H => H.CliqueFree (r + 2)) G) (hnc : ¬ G.IsCompleteMultipartite) :
∃ k v w₁ w₂ s t, G.IsFiveWheelLike r k v w₁ w₂ s t ∧ k < r ∧
∀ j, k < j → G.FiveWheelLikeFree r j := by
obtain ⟨_, _, _, s, t, hw⟩ :=
exists_isFiveWheelLike_of_maximal_cliqueFree_not_isCompleteMultipartite h hnc
let P : ℕ → Prop := fun k ↦ ∃ v w₁ w₂ s t, G.IsFiveWheelLike r k v w₁ w₂ s t
have hk : P #(s ∩ t) := ⟨_, _, _, _, _, hw⟩
classical
obtain ⟨_, _, _, _, _, hw⟩ := Nat.findGreatest_spec (hw.card_inter_lt_of_cliqueFree h.1).le hk
exact ⟨_, _, _, _, _, _, hw, hw.card_inter_lt_of_cliqueFree h.1,
fun _ hj _ _ _ _ _ hv ↦ hj.not_ge <| Nat.le_findGreatest
(hv.card_inter_lt_of_cliqueFree h.1).le ⟨_, _, _, _, _, hv⟩⟩
lemma CliqueFree.fiveWheelLikeFree_of_le (h : G.CliqueFree (r + 2)) (hk : r ≤ k) :
G.FiveWheelLikeFree r k := fun hw ↦ (hw.card_inter_lt_of_cliqueFree h).not_ge hk
/-- A maximally `Kᵣ₊₁`-free graph is `r`-colorable iff it is complete-multipartite. -/
theorem colorable_iff_isCompleteMultipartite_of_maximal_cliqueFree
(h : Maximal (fun H => H.CliqueFree (r + 1)) G) : G.Colorable r ↔ G.IsCompleteMultipartite := by
match r with
| 0 => exact ⟨fun _ ↦ fun x ↦ cliqueFree_one.1 h.1 |>.elim' x,
fun _ ↦ G.colorable_zero_iff.2 <| cliqueFree_one.1 h.1⟩
| r + 1 =>
refine ⟨fun hc ↦ ?_, fun hc ↦ hc.colorable_of_cliqueFree h.1⟩
contrapose! hc
obtain ⟨_, _, _, _, _, hw⟩ :=
exists_isFiveWheelLike_of_maximal_cliqueFree_not_isCompleteMultipartite h hc
exact hw.not_colorable_succ
end withDecEq
section AES
variable {i j n : ℕ} {d x v w₁ w₂ : α} {s t : Finset α}
section Counting
/--
Given lower bounds on non-adjacencies from `W` into `X`,`Xᶜ` we can bound the degree sum over `W`.
-/
private lemma sum_degree_le_of_le_not_adj [Fintype α] [DecidableEq α] [DecidableRel G.Adj]
{W X : Finset α} (hx : ∀ x ∈ X, i ≤ #{z ∈ W | ¬ G.Adj x z})
(hxc : ∀ y ∈ Xᶜ, j ≤ #{z ∈ W | ¬ G.Adj y z}) :
∑ w ∈ W, G.degree w ≤ #X * (#W - i) + #Xᶜ * (#W - j) := calc
_ = ∑ v, #(G.neighborFinset v ∩ W) := by
simp_rw [degree, card_eq_sum_ones]
exact sum_comm' (by simp [and_comm, adj_comm])
_ ≤ _ := by
simp_rw [← union_compl X, sum_union disjoint_compl_right (s₁ := X), neighborFinset_eq_filter,
filter_inter, univ_inter, card_eq_sum_ones X, card_eq_sum_ones Xᶜ, sum_mul, one_mul]
gcongr <;> grind [filter_card_add_filter_neg_card_eq_card]
end Counting
namespace IsFiveWheelLike
variable [DecidableEq α] (hw : G.IsFiveWheelLike r k v w₁ w₂ s t) (hcf : G.CliqueFree (r + 2))
include hw hcf
/--
If `G` is `Kᵣ₊₂`-free and contains a `Wᵣ,ₖ` together with a vertex `x` adjacent to all of its common
clique vertices then there exist (not necessarily distinct) vertices `a, b, c, d`, one from each of
the four `r + 1`-cliques of `Wᵣ,ₖ`, none of which are adjacent to `x`.
-/
private lemma exist_not_adj_of_adj_inter (hW : ∀ ⦃y⦄, y ∈ s ∩ t → G.Adj x y) :
∃ a b c d, a ∈ insert w₁ s ∧ ¬ G.Adj x a ∧ b ∈ insert w₂ t ∧ ¬ G.Adj x b ∧ c ∈ insert v s ∧
¬ G.Adj x c ∧ d ∈ insert v t ∧ ¬ G.Adj x d ∧ a ≠ b ∧ a ≠ d ∧ b ≠ c ∧ a ∉ t ∧ b ∉ s := by
obtain ⟨a, ha, haj⟩ := hw.isNClique_fst_left.exists_not_adj_of_cliqueFree_succ hcf x
obtain ⟨b, hb, hbj⟩ := hw.isNClique_snd_right.exists_not_adj_of_cliqueFree_succ hcf x
obtain ⟨c, hc, hcj⟩ := hw.isNClique_left.exists_not_adj_of_cliqueFree_succ hcf x
obtain ⟨d, hd, hdj⟩ := hw.isNClique_right.exists_not_adj_of_cliqueFree_succ hcf x
exact ⟨_, _, _, _, ha, haj, hb, hbj, hc, hcj, hd, hdj, by grind⟩
variable [DecidableRel G.Adj]
/--
If `G` is `Kᵣ₊₂`-free and contains a `Wᵣ,ₖ` together with a vertex `x` adjacent to all but at most
two vertices of `Wᵣ,ₖ`, including all of its common clique vertices, then `G` contains a `Wᵣ,ₖ₊₁`.
-/
lemma exists_isFiveWheelLike_succ_of_not_adj_le_two (hW : ∀ ⦃y⦄, y ∈ s ∩ t → G.Adj x y)
(h2 : #{z ∈ {v} ∪ ({w₁} ∪ ({w₂} ∪ (s ∪ t))) | ¬ G.Adj x z} ≤ 2) :
∃ a b, G.IsFiveWheelLike r (k + 1) v w₁ w₂ (insert x (s.erase a)) (insert x (t.erase b)) := by
obtain ⟨a, b, c, d, ha, haj, hb, hbj, hc, hcj, hd, hdj, hab, had, hbc, hat, hbs⟩ :=
hw.exist_not_adj_of_adj_inter hcf hW
-- Let `W` denote the vertices of the copy of `Wᵣ,ₖ` in `G`
let W := {v} ∪ ({w₁} ∪ ({w₂} ∪ (s ∪ t)))
have ⟨hca, hdb⟩ : c = a ∧ d = b := by
by_contra! hf
apply h2.not_gt <| two_lt_card_iff.2 _
by_cases h : a = c
· exact ⟨a, b, d, by grind⟩
· exact ⟨a, b, c, by grind⟩
simp_rw [hca, hdb, mem_insert] at *
have ⟨has, hbt, hav, hbv, haw, hbw⟩ : a ∈ s ∧ b ∈ t ∧ a ≠ v ∧ b ≠ v ∧ a ≠ w₂ ∧ b ≠ w₁ := by grind
have ⟨hxv, hxw₁, hxw₂⟩ : v ≠ x ∧ w₁ ≠ x ∧ w₂ ≠ x := by
refine ⟨?_, ?_, ?_⟩
· by_cases hax : x = a <;> rintro rfl
· grind
· exact haj <| hw.isNClique_left.1 (mem_insert_self ..) (mem_insert_of_mem has) hax
· by_cases hax : x = a <;> rintro rfl
· grind
· exact haj <| hw.isNClique_fst_left.1 (mem_insert_self ..) (mem_insert_of_mem has) hax
· by_cases hbx : x = b <;> rintro rfl
· grind
· exact hbj <| hw.isNClique_snd_right.1 (mem_insert_self ..) (mem_insert_of_mem hbt) hbx
-- Since `x` is not adjacent to `a` and `b` but is adjacent to all but at most two vertices
-- from `W` we have `∀ w ∈ W, w ≠ a → w ≠ b → G.Adj w x`
have wa : ∀ ⦃w⦄, w ∈ W → w ≠ a → w ≠ b → G.Adj w x := by
intro _ hz haz hbz
by_contra! hf
apply h2.not_gt
exact two_lt_card.2 ⟨_, by simp [has, hcj], _, by simp [hbt, hdj], _,
mem_filter.2 ⟨hz, by rwa [adj_comm] at hf⟩, hab, haz.symm, hbz.symm⟩
have ⟨h1s, h2t⟩ : insert w₁ s ⊆ W ∧ insert w₂ t ⊆ W := by grind
-- We now check that we can build a `Wᵣ,ₖ₊₁` by inserting `x` and erasing `a` and `b`
refine ⟨a, b, ⟨by grind, by grind, by grind, by grind, by grind, ?h5, ?h6, ?h7, ?h8, ?h9⟩⟩
-- Check that the new cliques are indeed cliques
case h5 => exact hw.isNClique_left.insert_insert_erase has hw.notMem_left fun _ hz hZ ↦
wa ((insert_subset_insert _ fun _ hx ↦ (by simp [hx])) hz) hZ
fun h ↦ hbv <| (mem_insert.1 (h ▸ hz)).resolve_right hbs
case h6 => exact hw.isNClique_fst_left.insert_insert_erase has hw.fst_notMem fun _ hz hZ ↦
wa (h1s hz) hZ fun h ↦ hbw <| (mem_insert.1 (h ▸ hz)).resolve_right hbs
case h7 => exact hw.isNClique_right.insert_insert_erase hbt hw.notMem_right fun _ hz hZ ↦
wa ((insert_subset_insert _ fun _ hx ↦ (by simp [hx])) hz)
(fun h ↦ hav <| (mem_insert.1 (h ▸ hz)).resolve_right hat) hZ
case h8 => exact hw.isNClique_snd_right.insert_insert_erase hbt hw.snd_notMem fun _ hz hZ ↦
wa (h2t hz) (fun h ↦ haw <| (mem_insert.1 (h ▸ hz)).resolve_right hat) hZ
case h9 =>
-- Finally check that this new `IsFiveWheelLike` structure has `k + 1` common clique
-- vertices i.e. `#((insert x (s.erase a)) ∩ (insert x (s.erase b))) = k + 1`.
rw [← insert_inter_distrib, erase_inter, inter_erase, erase_eq_of_notMem <|
notMem_mono inter_subset_left hbs, erase_eq_of_notMem <| notMem_mono inter_subset_right hat,
card_insert_of_notMem (fun h ↦ G.irrefl (hW h)), hw.card_inter]
/--
If `G` is a `Kᵣ₊₂`-free graph with `n` vertices containing a `Wᵣ,ₖ` but no `Wᵣ,ₖ₊₁`
then `G.minDegree ≤ (2 * r + k) * n / (2 * r + k + 3)`
-/
lemma minDegree_le_of_cliqueFree_fiveWheelLikeFree_succ [Fintype α]
(hm : G.FiveWheelLikeFree r (k + 1)) : G.minDegree ≤ (2 * r + k) * ‖α‖ / (2 * r + k + 3) := by
let X : Finset α := {x | ∀ ⦃y⦄, y ∈ s ∩ t → G.Adj x y}
let W := {v} ∪ ({w₁} ∪ ({w₂} ∪ (s ∪ t)))
-- Any vertex in `X` has at least 3 non-neighbors in `W` (otherwise we could build a bigger wheel)
have dXle : ∀ x ∈ X, 3 ≤ #{z ∈ W | ¬ G.Adj x z} := by
intro _ hx
by_contra! h
obtain ⟨_, _, hW⟩ := hw.exists_isFiveWheelLike_succ_of_not_adj_le_two hcf
(by simpa [X] using hx) <| Nat.le_of_succ_le_succ h
exact hm hW
-- Since `G` is `Kᵣ₊₂`-free and contains a `Wᵣ,ₖ`, every vertex is not adjacent to at least one
-- wheel vertex.
have one_le (x : α) : 1 ≤ #{z ∈ {v} ∪ ({w₁} ∪ ({w₂} ∪ (s ∪ t))) | ¬ G.Adj x z} :=
let ⟨_, hz⟩ := hw.isNClique_fst_left.exists_not_adj_of_cliqueFree_succ hcf x
card_pos.2 ⟨_, mem_filter.2 ⟨by grind, hz.2⟩⟩
-- Since every vertex has at least one non-neighbor in `W` we now have the following upper bound
-- `∑ w ∈ W, H.degree w ≤ #X * (#W - 3) + #Xᶜ * (#W - 1)`
have bdW := sum_degree_le_of_le_not_adj dXle (fun y _ ↦ one_le y)
-- By the definition of `X`, any `x ∈ Xᶜ` has at least one non-neighbour in `X`.
have xcle : ∀ x ∈ Xᶜ, 1 ≤ #{z ∈ s ∩ t | ¬ G.Adj x z} := by
intro x hx
apply card_pos.2
obtain ⟨_, hy⟩ : ∃ y ∈ s ∩ t, ¬ G.Adj x y := by
contrapose! hx
simpa [X] using hx
exact ⟨_, mem_filter.2 hy⟩
-- So we also have an upper bound on the degree sum over `s ∩ t`
-- `∑ w ∈ s ∩ t, H.degree w ≤ #Xᶜ * (#(s ∩ t) - 1) + #X * #(s ∩ t)`
have bdX := sum_degree_le_of_le_not_adj xcle (fun _ _ ↦ Nat.zero_le _)
rw [compl_compl, tsub_zero, add_comm] at bdX
rw [Nat.le_div_iff_mul_le <| Nat.add_pos_right _ zero_lt_three]
have Wc : #W + k = 2 * r + 3 := by
change #(insert _ <| insert _ <| insert _ _) + _ = _
grind [card_inter_add_card_union]
-- The sum of the degree sum over `W` and twice the degree sum over `s ∩ t`
-- is at least `G.minDegree * (#W + 2 * #(s ∩ t))` which implies the result
calc
_ ≤ ∑ w ∈ W, G.degree w + 2 * ∑ w ∈ s ∩ t, G.degree w := by
simp_rw [add_assoc, add_comm k, ← add_assoc, ← Wc, add_assoc, ← two_mul, mul_add,
← hw.card_inter, card_eq_sum_ones, ← mul_assoc, mul_sum, mul_one, mul_comm 2]
gcongr with i <;> exact minDegree_le_degree ..
_ ≤ #X * (#W - 3 + 2 * k) + #Xᶜ * ((#W - 1) + 2 * (k - 1)) := by grind
_ ≤ _ := by
by_cases hk : k = 0 -- so `s ∩ t = ∅` and hence `Xᶜ = ∅`
· have Xu : X = univ := by
rw [← hw.card_inter, card_eq_zero] at hk
exact eq_univ_of_forall fun _ ↦ by simp [X, hk]
subst k
rw [add_zero] at Wc
simp [Xu, Wc, mul_comm]
have w3 : 3 ≤ #W := two_lt_card.2 ⟨_, mem_insert_self .., _, by simp [W], _, by simp [W],
hw.isPathGraph3Compl.ne_fst, hw.isPathGraph3Compl.ne_snd, hw.isPathGraph3Compl.fst_ne_snd⟩
have hap : #W - 1 + 2 * (k - 1) = #W - 3 + 2 * k := by omega
rw [hap, ← add_mul, card_add_card_compl, mul_comm, two_mul, ← add_assoc]
gcongr
cutsat
end IsFiveWheelLike
variable [DecidableEq α]
/-- **Andrasfái-Erdős-Sós** theorem
If `G` is a `Kᵣ₊₁`-free graph with `n` vertices and `(3 * r - 4) * n / (3 * r - 1) < G.minDegree`
then `G` is `r + 1`-colorable, e.g. if `G` is `K₃`-free and `2 * n / 5 < G.minDegree` then `G`
is `2`-colorable.
-/
theorem colorable_of_cliqueFree_lt_minDegree [Fintype α] [DecidableRel G.Adj]
(hf : G.CliqueFree (r + 1)) (hd : (3 * r - 4) * ‖α‖ / (3 * r - 1) < G.minDegree) :
G.Colorable r := by
match r with
| 0 | 1 => aesop
| r + 2 =>
-- There is an edge maximal `Kᵣ₊₃`-free supergraph `H` of `G`
obtain ⟨H, hle, hmcf⟩ := @Finite.exists_le_maximal _ _ _ (fun H ↦ H.CliqueFree (r + 3)) G hf
-- If `H` is `r + 2`-colorable then so is `G`
apply Colorable.mono_left hle
-- Suppose, for a contradiction, that `H` is not `r + 2`-colorable
by_contra! hnotcol
-- so `H` is not complete-multipartite
have hn : ¬ H.IsCompleteMultipartite := fun hc ↦ hnotcol <| hc.colorable_of_cliqueFree hmcf.1
-- Hence `H` contains `Wᵣ₊₁,ₖ` but not `Wᵣ₊₁,ₖ₊₁`, for some `k < r + 1`
obtain ⟨k, _, _, _, _, _, hw, hlt, hm⟩ :=
exists_max_isFiveWheelLike_of_maximal_cliqueFree_not_isCompleteMultipartite hmcf hn
classical
-- But the minimum degree of `G`, and hence of `H`, is too large for it to be `Wᵣ₊₁,ₖ₊₁`-free,
-- a contradiction.
have hD := hw.minDegree_le_of_cliqueFree_fiveWheelLikeFree_succ hmcf.1 <| hm _ <| lt_add_one _
have : (2 * (r + 1) + k) * ‖α‖ / (2 * (r + 1) + k + 3) ≤ (3 * r + 2) * ‖α‖ / (3 * r + 5) := by
apply (Nat.le_div_iff_mul_le <| Nat.succ_pos _).2
<| (mul_le_mul_iff_right₀ (_ + 2).succ_pos).1 _
rw [← mul_assoc, mul_comm (2 * r + 2 + k + 3), mul_comm _ (_ * ‖α‖)]
apply (Nat.mul_le_mul_right _ (Nat.div_mul_le_self ..)).trans
nlinarith
exact (hd.trans_le <| minDegree_le_minDegree hle).not_ge <| hD.trans <| this
end AES
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Density.lean | import Mathlib.Algebra.Order.Field.Basic
import Mathlib.Combinatorics.SimpleGraph.Basic
import Mathlib.Data.Rat.Cast.Order
import Mathlib.Order.Partition.Finpartition
import Mathlib.Tactic.GCongr
import Mathlib.Tactic.NormNum
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.Ring
/-!
# Edge density
This file defines the number and density of edges of a relation/graph.
## Main declarations
Between two finsets of vertices,
* `Rel.interedges`: Finset of edges of a relation.
* `Rel.edgeDensity`: Edge density of a relation.
* `SimpleGraph.interedges`: Finset of edges of a graph.
* `SimpleGraph.edgeDensity`: Edge density of a graph.
-/
open Finset
variable {𝕜 ι κ α β : Type*}
/-! ### Density of a relation -/
namespace Rel
section Asymmetric
variable [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜]
(r : α → β → Prop) [∀ a, DecidablePred (r a)] {s s₁ s₂ : Finset α}
{t t₁ t₂ : Finset β} {a : α} {b : β} {δ : 𝕜}
/-- Finset of edges of a relation between two finsets of vertices. -/
def interedges (s : Finset α) (t : Finset β) : Finset (α × β) := {e ∈ s ×ˢ t | r e.1 e.2}
/-- Edge density of a relation between two finsets of vertices. -/
def edgeDensity (s : Finset α) (t : Finset β) : ℚ := #(interedges r s t) / (#s * #t)
variable {r}
theorem mem_interedges_iff {x : α × β} : x ∈ interedges r s t ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ r x.1 x.2 := by
rw [interedges, mem_filter, Finset.mem_product, and_assoc]
theorem mk_mem_interedges_iff : (a, b) ∈ interedges r s t ↔ a ∈ s ∧ b ∈ t ∧ r a b :=
mem_interedges_iff
@[simp]
theorem interedges_empty_left (t : Finset β) : interedges r ∅ t = ∅ := by
rw [interedges, Finset.empty_product, filter_empty]
theorem interedges_mono (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) : interedges r s₂ t₂ ⊆ interedges r s₁ t₁ :=
fun x ↦ by
simp_rw [mem_interedges_iff]
exact fun h ↦ ⟨hs h.1, ht h.2.1, h.2.2⟩
variable (r)
theorem card_interedges_add_card_interedges_compl (s : Finset α) (t : Finset β) :
#(interedges r s t) + #(interedges (fun x y ↦ ¬r x y) s t) = #s * #t := by
classical
rw [← card_product, interedges, interedges, ← card_union_of_disjoint, filter_union_filter_neg_eq]
exact disjoint_filter.2 fun _ _ ↦ Classical.not_not.2
theorem interedges_disjoint_left {s s' : Finset α} (hs : Disjoint s s') (t : Finset β) :
Disjoint (interedges r s t) (interedges r s' t) := by
rw [Finset.disjoint_left] at hs ⊢
intro _ hx hy
rw [mem_interedges_iff] at hx hy
exact hs hx.1 hy.1
theorem interedges_disjoint_right (s : Finset α) {t t' : Finset β} (ht : Disjoint t t') :
Disjoint (interedges r s t) (interedges r s t') := by
rw [Finset.disjoint_left] at ht ⊢
intro _ hx hy
rw [mem_interedges_iff] at hx hy
exact ht hx.2.1 hy.2.1
section DecidableEq
variable [DecidableEq α] [DecidableEq β]
lemma interedges_eq_biUnion :
interedges r s t =
s.biUnion fun x ↦ {y ∈ t | r x y}.map ⟨(x, ·), Prod.mk_right_injective x⟩ := by
ext ⟨x, y⟩; simp [mem_interedges_iff]
theorem interedges_biUnion_left (s : Finset ι) (t : Finset β) (f : ι → Finset α) :
interedges r (s.biUnion f) t = s.biUnion fun a ↦ interedges r (f a) t := by
ext
simp only [mem_biUnion, mem_interedges_iff, exists_and_right, ← and_assoc]
theorem interedges_biUnion_right (s : Finset α) (t : Finset ι) (f : ι → Finset β) :
interedges r s (t.biUnion f) = t.biUnion fun b ↦ interedges r s (f b) := by
ext a
simp only [mem_interedges_iff, mem_biUnion]
exact ⟨fun ⟨x₁, ⟨x₂, x₃, x₄⟩, x₅⟩ ↦ ⟨x₂, x₃, x₁, x₄, x₅⟩,
fun ⟨x₂, x₃, x₁, x₄, x₅⟩ ↦ ⟨x₁, ⟨x₂, x₃, x₄⟩, x₅⟩⟩
theorem interedges_biUnion (s : Finset ι) (t : Finset κ) (f : ι → Finset α) (g : κ → Finset β) :
interedges r (s.biUnion f) (t.biUnion g) =
(s ×ˢ t).biUnion fun ab ↦ interedges r (f ab.1) (g ab.2) := by
simp_rw [product_biUnion, interedges_biUnion_left, interedges_biUnion_right]
end DecidableEq
theorem card_interedges_le_mul (s : Finset α) (t : Finset β) :
#(interedges r s t) ≤ #s * #t :=
(card_filter_le _ _).trans (card_product _ _).le
theorem edgeDensity_nonneg (s : Finset α) (t : Finset β) : 0 ≤ edgeDensity r s t := by
apply div_nonneg <;> exact mod_cast Nat.zero_le _
theorem edgeDensity_le_one (s : Finset α) (t : Finset β) : edgeDensity r s t ≤ 1 := by
apply div_le_one_of_le₀
· exact mod_cast card_interedges_le_mul r s t
· exact mod_cast Nat.zero_le _
theorem edgeDensity_add_edgeDensity_compl (hs : s.Nonempty) (ht : t.Nonempty) :
edgeDensity r s t + edgeDensity (fun x y ↦ ¬r x y) s t = 1 := by
rw [edgeDensity, edgeDensity, ← add_div, div_eq_one_iff_eq]
· exact mod_cast card_interedges_add_card_interedges_compl r s t
· exact mod_cast (mul_pos hs.card_pos ht.card_pos).ne'
@[simp]
theorem edgeDensity_empty_left (t : Finset β) : edgeDensity r ∅ t = 0 := by
rw [edgeDensity, Finset.card_empty, Nat.cast_zero, zero_mul, div_zero]
@[simp]
theorem edgeDensity_empty_right (s : Finset α) : edgeDensity r s ∅ = 0 := by
rw [edgeDensity, Finset.card_empty, Nat.cast_zero, mul_zero, div_zero]
theorem card_interedges_finpartition_left [DecidableEq α] (P : Finpartition s) (t : Finset β) :
#(interedges r s t) = ∑ a ∈ P.parts, #(interedges r a t) := by
classical
simp_rw [← P.biUnion_parts, interedges_biUnion_left, id]
rw [card_biUnion]
exact fun x hx y hy h ↦ interedges_disjoint_left r (P.disjoint hx hy h) _
theorem card_interedges_finpartition_right [DecidableEq β] (s : Finset α) (P : Finpartition t) :
#(interedges r s t) = ∑ b ∈ P.parts, #(interedges r s b) := by
classical
simp_rw [← P.biUnion_parts, interedges_biUnion_right, id]
rw [card_biUnion]
exact fun x hx y hy h ↦ interedges_disjoint_right r _ (P.disjoint hx hy h)
theorem card_interedges_finpartition [DecidableEq α] [DecidableEq β] (P : Finpartition s)
(Q : Finpartition t) :
#(interedges r s t) = ∑ ab ∈ P.parts ×ˢ Q.parts, #(interedges r ab.1 ab.2) := by
rw [card_interedges_finpartition_left _ P, sum_product]
congr; ext
rw [card_interedges_finpartition_right]
theorem mul_edgeDensity_le_edgeDensity (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) (hs₂ : s₂.Nonempty)
(ht₂ : t₂.Nonempty) :
(#s₂ : ℚ) / #s₁ * (#t₂ / #t₁) * edgeDensity r s₂ t₂ ≤ edgeDensity r s₁ t₁ := by
have hst : (#s₂ : ℚ) * #t₂ ≠ 0 := by simp [hs₂.ne_empty, ht₂.ne_empty]
rw [edgeDensity, edgeDensity, div_mul_div_comm, mul_comm, div_mul_div_cancel₀ hst]
gcongr
exact interedges_mono hs ht
theorem edgeDensity_sub_edgeDensity_le_one_sub_mul (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) (hs₂ : s₂.Nonempty)
(ht₂ : t₂.Nonempty) :
edgeDensity r s₂ t₂ - edgeDensity r s₁ t₁ ≤ 1 - #s₂ / #s₁ * (#t₂ / #t₁) := by
refine (sub_le_sub_left (mul_edgeDensity_le_edgeDensity r hs ht hs₂ ht₂) _).trans ?_
refine le_trans ?_ (mul_le_of_le_one_right ?_ (edgeDensity_le_one r s₂ t₂))
· rw [sub_mul, one_mul]
refine sub_nonneg_of_le (mul_le_one₀ ?_ ?_ ?_)
· exact div_le_one_of_le₀ ((@Nat.cast_le ℚ).2 (card_le_card hs)) (Nat.cast_nonneg _)
· apply div_nonneg <;> exact mod_cast Nat.zero_le _
· exact div_le_one_of_le₀ ((@Nat.cast_le ℚ).2 (card_le_card ht)) (Nat.cast_nonneg _)
theorem abs_edgeDensity_sub_edgeDensity_le_one_sub_mul (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁)
(hs₂ : s₂.Nonempty) (ht₂ : t₂.Nonempty) :
|edgeDensity r s₂ t₂ - edgeDensity r s₁ t₁| ≤ 1 - #s₂ / #s₁ * (#t₂ / #t₁) := by
refine abs_sub_le_iff.2 ⟨edgeDensity_sub_edgeDensity_le_one_sub_mul r hs ht hs₂ ht₂, ?_⟩
rw [← add_sub_cancel_right (edgeDensity r s₁ t₁) (edgeDensity (fun x y ↦ ¬r x y) s₁ t₁),
← add_sub_cancel_right (edgeDensity r s₂ t₂) (edgeDensity (fun x y ↦ ¬r x y) s₂ t₂),
edgeDensity_add_edgeDensity_compl _ (hs₂.mono hs) (ht₂.mono ht),
edgeDensity_add_edgeDensity_compl _ hs₂ ht₂, sub_sub_sub_cancel_left]
exact edgeDensity_sub_edgeDensity_le_one_sub_mul _ hs ht hs₂ ht₂
theorem abs_edgeDensity_sub_edgeDensity_le_two_mul_sub_sq (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁)
(hδ₀ : 0 ≤ δ) (hδ₁ : δ < 1) (hs₂ : (1 - δ) * #s₁ ≤ #s₂)
(ht₂ : (1 - δ) * #t₁ ≤ #t₂) :
|(edgeDensity r s₂ t₂ : 𝕜) - edgeDensity r s₁ t₁| ≤ 2 * δ - δ ^ 2 := by
have hδ' : 0 ≤ 2 * δ - δ ^ 2 := by
rw [sub_nonneg, sq]
gcongr
exact hδ₁.le.trans (by simp)
rw [← sub_pos] at hδ₁
obtain rfl | hs₂' := s₂.eq_empty_or_nonempty
· rw [Finset.card_empty, Nat.cast_zero] at hs₂
simpa [edgeDensity, (nonpos_of_mul_nonpos_right hs₂ hδ₁).antisymm (Nat.cast_nonneg _)] using hδ'
obtain rfl | ht₂' := t₂.eq_empty_or_nonempty
· rw [Finset.card_empty, Nat.cast_zero] at ht₂
simpa [edgeDensity, (nonpos_of_mul_nonpos_right ht₂ hδ₁).antisymm (Nat.cast_nonneg _)] using hδ'
have hr : 2 * δ - δ ^ 2 = 1 - (1 - δ) * (1 - δ) := by ring
rw [hr]
norm_cast
refine
(Rat.cast_le.2 <| abs_edgeDensity_sub_edgeDensity_le_one_sub_mul r hs ht hs₂' ht₂').trans ?_
push_cast
have h₁ := hs₂'.mono hs
have h₂ := ht₂'.mono ht
gcongr
· refine (le_div_iff₀ ?_).2 hs₂
exact mod_cast h₁.card_pos
· refine (le_div_iff₀ ?_).2 ht₂
exact mod_cast h₂.card_pos
/-- If `s₂ ⊆ s₁`, `t₂ ⊆ t₁` and they take up all but a `δ`-proportion, then the difference in edge
densities is at most `2 * δ`. -/
theorem abs_edgeDensity_sub_edgeDensity_le_two_mul (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) (hδ : 0 ≤ δ)
(hscard : (1 - δ) * #s₁ ≤ #s₂) (htcard : (1 - δ) * #t₁ ≤ #t₂) :
|(edgeDensity r s₂ t₂ : 𝕜) - edgeDensity r s₁ t₁| ≤ 2 * δ := by
rcases lt_or_ge δ 1 with h | h
· exact (abs_edgeDensity_sub_edgeDensity_le_two_mul_sub_sq r hs ht hδ h hscard htcard).trans
((sub_le_self_iff _).2 <| sq_nonneg δ)
rw [two_mul]
refine (abs_sub _ _).trans (add_le_add (le_trans ?_ h) (le_trans ?_ h)) <;>
· rw [abs_of_nonneg]
· exact mod_cast edgeDensity_le_one r _ _
· exact mod_cast edgeDensity_nonneg r _ _
end Asymmetric
section Symmetric
variable {r : α → α → Prop} [DecidableRel r] {s t : Finset α} {a b : α}
@[simp]
theorem swap_mem_interedges_iff (hr : Symmetric r) {x : α × α} :
x.swap ∈ interedges r s t ↔ x ∈ interedges r t s := by
rw [mem_interedges_iff, mem_interedges_iff, hr.iff]
exact and_left_comm
theorem mk_mem_interedges_comm (hr : Symmetric r) :
(a, b) ∈ interedges r s t ↔ (b, a) ∈ interedges r t s :=
@swap_mem_interedges_iff _ _ _ _ _ hr (b, a)
theorem card_interedges_comm (hr : Symmetric r) (s t : Finset α) :
#(interedges r s t) = #(interedges r t s) :=
Finset.card_bij (fun (x : α × α) _ ↦ x.swap) (fun _ ↦ (swap_mem_interedges_iff hr).2)
(fun _ _ _ _ h ↦ Prod.swap_injective h) fun x h ↦
⟨x.swap, (swap_mem_interedges_iff hr).2 h, x.swap_swap⟩
theorem edgeDensity_comm (hr : Symmetric r) (s t : Finset α) :
edgeDensity r s t = edgeDensity r t s := by
rw [edgeDensity, mul_comm, card_interedges_comm hr, edgeDensity]
end Symmetric
end Rel
open Rel
/-! ### Density of a graph -/
namespace SimpleGraph
variable (G : SimpleGraph α) [DecidableRel G.Adj] {s s₁ s₂ t t₁ t₂ : Finset α} {a b : α}
/-- Finset of edges of a relation between two finsets of vertices. -/
def interedges (s t : Finset α) : Finset (α × α) :=
Rel.interedges G.Adj s t
/-- Density of edges of a graph between two finsets of vertices. -/
def edgeDensity : Finset α → Finset α → ℚ :=
Rel.edgeDensity G.Adj
lemma interedges_def (s t : Finset α) : G.interedges s t = {e ∈ s ×ˢ t | G.Adj e.1 e.2} := rfl
lemma edgeDensity_def (s t : Finset α) : G.edgeDensity s t = #(G.interedges s t) / (#s * #t) := rfl
theorem card_interedges_div_card (s t : Finset α) :
(#(G.interedges s t) : ℚ) / (#s * #t) = G.edgeDensity s t :=
rfl
theorem mem_interedges_iff {x : α × α} : x ∈ G.interedges s t ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ G.Adj x.1 x.2 :=
Rel.mem_interedges_iff
theorem mk_mem_interedges_iff : (a, b) ∈ G.interedges s t ↔ a ∈ s ∧ b ∈ t ∧ G.Adj a b :=
Rel.mk_mem_interedges_iff
@[simp]
theorem interedges_empty_left (t : Finset α) : G.interedges ∅ t = ∅ :=
Rel.interedges_empty_left _
theorem interedges_mono : s₂ ⊆ s₁ → t₂ ⊆ t₁ → G.interedges s₂ t₂ ⊆ G.interedges s₁ t₁ :=
Rel.interedges_mono
theorem interedges_disjoint_left (hs : Disjoint s₁ s₂) (t : Finset α) :
Disjoint (G.interedges s₁ t) (G.interedges s₂ t) :=
Rel.interedges_disjoint_left _ hs _
theorem interedges_disjoint_right (s : Finset α) (ht : Disjoint t₁ t₂) :
Disjoint (G.interedges s t₁) (G.interedges s t₂) :=
Rel.interedges_disjoint_right _ _ ht
section DecidableEq
variable [DecidableEq α]
theorem interedges_biUnion_left (s : Finset ι) (t : Finset α) (f : ι → Finset α) :
G.interedges (s.biUnion f) t = s.biUnion fun a ↦ G.interedges (f a) t :=
Rel.interedges_biUnion_left _ _ _ _
theorem interedges_biUnion_right (s : Finset α) (t : Finset ι) (f : ι → Finset α) :
G.interedges s (t.biUnion f) = t.biUnion fun b ↦ G.interedges s (f b) :=
Rel.interedges_biUnion_right _ _ _ _
theorem interedges_biUnion (s : Finset ι) (t : Finset κ) (f : ι → Finset α) (g : κ → Finset α) :
G.interedges (s.biUnion f) (t.biUnion g) =
(s ×ˢ t).biUnion fun ab ↦ G.interedges (f ab.1) (g ab.2) :=
Rel.interedges_biUnion _ _ _ _ _
theorem card_interedges_add_card_interedges_compl (h : Disjoint s t) :
#(G.interedges s t) + #(Gᶜ.interedges s t) = #s * #t := by
rw [← card_product, interedges_def, interedges_def]
have : {e ∈ s ×ˢ t | Gᶜ.Adj e.1 e.2} = {e ∈ s ×ˢ t | ¬G.Adj e.1 e.2} := by
refine filter_congr fun x hx ↦ ?_
rw [mem_product] at hx
rw [compl_adj, and_iff_right (h.forall_ne_finset hx.1 hx.2)]
rw [this, ← card_union_of_disjoint, filter_union_filter_neg_eq]
exact disjoint_filter.2 fun _ _ ↦ Classical.not_not.2
theorem edgeDensity_add_edgeDensity_compl (hs : s.Nonempty) (ht : t.Nonempty) (h : Disjoint s t) :
G.edgeDensity s t + Gᶜ.edgeDensity s t = 1 := by
rw [edgeDensity_def, edgeDensity_def, ← add_div, div_eq_one_iff_eq]
· exact mod_cast card_interedges_add_card_interedges_compl _ h
· positivity
end DecidableEq
theorem card_interedges_le_mul (s t : Finset α) : #(G.interedges s t) ≤ #s * #t :=
Rel.card_interedges_le_mul _ _ _
theorem edgeDensity_nonneg (s t : Finset α) : 0 ≤ G.edgeDensity s t :=
Rel.edgeDensity_nonneg _ _ _
theorem edgeDensity_le_one (s t : Finset α) : G.edgeDensity s t ≤ 1 :=
Rel.edgeDensity_le_one _ _ _
@[simp]
theorem edgeDensity_empty_left (t : Finset α) : G.edgeDensity ∅ t = 0 :=
Rel.edgeDensity_empty_left _ _
@[simp]
theorem edgeDensity_empty_right (s : Finset α) : G.edgeDensity s ∅ = 0 :=
Rel.edgeDensity_empty_right _ _
@[simp]
theorem swap_mem_interedges_iff {x : α × α} : x.swap ∈ G.interedges s t ↔ x ∈ G.interedges t s :=
Rel.swap_mem_interedges_iff G.symm
theorem mk_mem_interedges_comm : (a, b) ∈ G.interedges s t ↔ (b, a) ∈ G.interedges t s :=
Rel.mk_mem_interedges_comm G.symm
theorem edgeDensity_comm (s t : Finset α) : G.edgeDensity s t = G.edgeDensity t s :=
Rel.edgeDensity_comm G.symm s t
end SimpleGraph
/- Porting note: Commented out `Tactic` namespace.
namespace Tactic
open Positivity
/-- Extension for the `positivity` tactic: `Rel.edgeDensity` and `SimpleGraph.edgeDensity` are
always nonnegative. -/
@[positivity]
unsafe def positivity_edge_density : expr → tactic strictness
| q(Rel.edgeDensity $(r) $(s) $(t)) =>
nonnegative <$> mk_mapp `` Rel.edgeDensity_nonneg [none, none, r, none, s, t]
| q(SimpleGraph.edgeDensity $(G) $(s) $(t)) =>
nonnegative <$> mk_mapp `` SimpleGraph.edgeDensity_nonneg [none, G, none, s, t]
| e =>
pp e >>=
fail ∘
format.bracket "The expression `"
"` isn't of the form `Rel.edgeDensity r s t` nor `SimpleGraph.edgeDensity G s t`"
end Tactic
-/ |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Basic.lean | import Mathlib.Combinatorics.SimpleGraph.Init
import Mathlib.Data.Finite.Prod
import Mathlib.Data.Rel
import Mathlib.Data.Set.Finite.Basic
import Mathlib.Data.Sym.Sym2
import Mathlib.Order.CompleteBooleanAlgebra
/-!
# Simple graphs
This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation.
## Main definitions
* `SimpleGraph` is a structure for symmetric, irreflexive relations.
* `SimpleGraph.neighborSet` is the `Set` of vertices adjacent to a given vertex.
* `SimpleGraph.commonNeighbors` is the intersection of the neighbor sets of two given vertices.
* `SimpleGraph.incidenceSet` is the `Set` of edges containing a given vertex.
* `CompleteAtomicBooleanAlgebra` instance: Under the subgraph relation, `SimpleGraph` forms a
`CompleteAtomicBooleanAlgebra`. In other words, this is the complete lattice of spanning subgraphs
of the complete graph.
## TODO
* This is the simplest notion of an unoriented graph.
This should eventually fit into a more complete combinatorics hierarchy which includes
multigraphs and directed graphs.
We begin with simple graphs in order to start learning what the combinatorics hierarchy should
look like.
-/
attribute [aesop norm unfold (rule_sets := [SimpleGraph])] Symmetric
attribute [aesop norm unfold (rule_sets := [SimpleGraph])] Irreflexive
/--
A variant of the `aesop` tactic for use in the graph library. Changes relative
to standard `aesop`:
- We use the `SimpleGraph` rule set in addition to the default rule sets.
- We instruct Aesop's `intro` rule to unfold with `default` transparency.
- We instruct Aesop to fail if it can't fully solve the goal. This allows us to
use `aesop_graph` for auto-params.
-/
macro (name := aesop_graph) "aesop_graph" c:Aesop.tactic_clause* : tactic =>
`(tactic|
aesop $c*
(config := { introsTransparency? := some .default, terminal := true })
(rule_sets := [$(Lean.mkIdent `SimpleGraph):ident]))
/--
Use `aesop_graph?` to pass along a `Try this` suggestion when using `aesop_graph`
-/
macro (name := aesop_graph?) "aesop_graph?" c:Aesop.tactic_clause* : tactic =>
`(tactic|
aesop? $c*
(config := { introsTransparency? := some .default, terminal := true })
(rule_sets := [$(Lean.mkIdent `SimpleGraph):ident]))
/--
A variant of `aesop_graph` which does not fail if it is unable to solve the goal.
Use this only for exploration! Nonterminal Aesop is even worse than nonterminal `simp`.
-/
macro (name := aesop_graph_nonterminal) "aesop_graph_nonterminal" c:Aesop.tactic_clause* : tactic =>
`(tactic|
aesop $c*
(config := { introsTransparency? := some .default, warnOnNonterminal := false })
(rule_sets := [$(Lean.mkIdent `SimpleGraph):ident]))
open Finset Function
universe u v w
/-- A simple graph is an irreflexive symmetric relation `Adj` on a vertex type `V`.
The relation describes which pairs of vertices are adjacent.
There is exactly one edge for every pair of adjacent vertices;
see `SimpleGraph.edgeSet` for the corresponding edge set.
-/
@[ext, aesop safe constructors (rule_sets := [SimpleGraph])]
structure SimpleGraph (V : Type u) where
/-- The adjacency relation of a simple graph. -/
Adj : V → V → Prop
symm : Symmetric Adj := by aesop_graph
loopless : Irreflexive Adj := by aesop_graph
initialize_simps_projections SimpleGraph (Adj → adj)
/-- Constructor for simple graphs using a symmetric irreflexive Boolean function. -/
@[simps]
def SimpleGraph.mk' {V : Type u} :
{adj : V → V → Bool // (∀ x y, adj x y = adj y x) ∧ (∀ x, ¬ adj x x)} ↪ SimpleGraph V where
toFun x := ⟨fun v w ↦ x.1 v w, fun v w ↦ by simp [x.2.1], fun v ↦ by simp [x.2.2]⟩
inj' := by
rintro ⟨adj, _⟩ ⟨adj', _⟩
simp only [mk.injEq, Subtype.mk.injEq]
intro h
funext v w
simpa [Bool.coe_iff_coe] using congr_fun₂ h v w
/-- We can enumerate simple graphs by enumerating all functions `V → V → Bool`
and filtering on whether they are symmetric and irreflexive. -/
instance {V : Type u} [Fintype V] [DecidableEq V] : Fintype (SimpleGraph V) where
elems := Finset.univ.map SimpleGraph.mk'
complete := by
classical
rintro ⟨Adj, hs, hi⟩
simp only [mem_map, mem_univ, true_and, Subtype.exists, Bool.not_eq_true]
refine ⟨fun v w ↦ Adj v w, ⟨?_, ?_⟩, ?_⟩
· simp [hs.iff]
· intro v; simp [hi v]
· ext
simp
/-- There are finitely many simple graphs on a given finite type. -/
instance SimpleGraph.instFinite {V : Type u} [Finite V] : Finite (SimpleGraph V) :=
.of_injective SimpleGraph.Adj fun _ _ ↦ SimpleGraph.ext
/-- Construct the simple graph induced by the given relation. It
symmetrizes the relation and makes it irreflexive. -/
def SimpleGraph.fromRel {V : Type u} (r : V → V → Prop) : SimpleGraph V where
Adj a b := a ≠ b ∧ (r a b ∨ r b a)
symm := fun _ _ ⟨hn, hr⟩ => ⟨hn.symm, hr.symm⟩
loopless := fun _ ⟨hn, _⟩ => hn rfl
@[simp]
theorem SimpleGraph.fromRel_adj {V : Type u} (r : V → V → Prop) (v w : V) :
(SimpleGraph.fromRel r).Adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) :=
Iff.rfl
attribute [aesop safe (rule_sets := [SimpleGraph])] Ne.symm
attribute [aesop safe (rule_sets := [SimpleGraph])] Ne.irrefl
/-- Two vertices are adjacent in the complete bipartite graph on two vertex types
if and only if they are not from the same side.
Any bipartite graph may be regarded as a subgraph of one of these. -/
@[simps]
def completeBipartiteGraph (V W : Type*) : SimpleGraph (V ⊕ W) where
Adj v w := v.isLeft ∧ w.isRight ∨ v.isRight ∧ w.isLeft
symm v w := by cases v <;> cases w <;> simp
loopless v := by cases v <;> simp
namespace SimpleGraph
variable {ι : Sort*} {V : Type u} (G : SimpleGraph V) {a b c u v w : V} {e : Sym2 V}
@[simp]
protected theorem irrefl {v : V} : ¬G.Adj v v :=
G.loopless v
theorem adj_comm (u v : V) : G.Adj u v ↔ G.Adj v u :=
⟨fun x => G.symm x, fun x => G.symm x⟩
@[symm]
theorem adj_symm (h : G.Adj u v) : G.Adj v u :=
G.symm h
theorem Adj.symm {G : SimpleGraph V} {u v : V} (h : G.Adj u v) : G.Adj v u :=
G.symm h
theorem ne_of_adj (h : G.Adj a b) : a ≠ b := by
rintro rfl
exact G.irrefl h
protected theorem Adj.ne {G : SimpleGraph V} {a b : V} (h : G.Adj a b) : a ≠ b :=
G.ne_of_adj h
protected theorem Adj.ne' {G : SimpleGraph V} {a b : V} (h : G.Adj a b) : b ≠ a :=
h.ne.symm
theorem ne_of_adj_of_not_adj {v w x : V} (h : G.Adj v x) (hn : ¬G.Adj w x) : v ≠ w := fun h' =>
hn (h' ▸ h)
theorem adj_injective : Injective (Adj : SimpleGraph V → V → V → Prop) :=
fun _ _ => SimpleGraph.ext
@[simp]
theorem adj_inj {G H : SimpleGraph V} : G.Adj = H.Adj ↔ G = H :=
adj_injective.eq_iff
theorem adj_congr_of_sym2 {u v w x : V} (h : s(u, v) = s(w, x)) : G.Adj u v ↔ G.Adj w x := by
simp only [Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk] at h
rcases h with hl | hr
· rw [hl.1, hl.2]
· rw [hr.1, hr.2, adj_comm]
section Order
/-- The relation that one `SimpleGraph` is a subgraph of another.
Note that this should be spelled `≤`. -/
def IsSubgraph (x y : SimpleGraph V) : Prop :=
∀ ⦃v w : V⦄, x.Adj v w → y.Adj v w
instance : LE (SimpleGraph V) :=
⟨IsSubgraph⟩
lemma le_iff_adj {G H : SimpleGraph V} : G ≤ H ↔ ∀ v w, G.Adj v w → H.Adj v w := .rfl
@[simp]
theorem isSubgraph_eq_le : (IsSubgraph : SimpleGraph V → SimpleGraph V → Prop) = (· ≤ ·) :=
rfl
/-- The supremum of two graphs `x ⊔ y` has edges where either `x` or `y` have edges. -/
instance : Max (SimpleGraph V) where
max x y :=
{ Adj := x.Adj ⊔ y.Adj
symm := fun v w h => by rwa [Pi.sup_apply, Pi.sup_apply, x.adj_comm, y.adj_comm] }
@[simp]
theorem sup_adj (x y : SimpleGraph V) (v w : V) : (x ⊔ y).Adj v w ↔ x.Adj v w ∨ y.Adj v w :=
Iff.rfl
/-- The infimum of two graphs `x ⊓ y` has edges where both `x` and `y` have edges. -/
instance : Min (SimpleGraph V) where
min x y :=
{ Adj := x.Adj ⊓ y.Adj
symm := fun v w h => by rwa [Pi.inf_apply, Pi.inf_apply, x.adj_comm, y.adj_comm] }
@[simp]
theorem inf_adj (x y : SimpleGraph V) (v w : V) : (x ⊓ y).Adj v w ↔ x.Adj v w ∧ y.Adj v w :=
Iff.rfl
/-- We define `Gᶜ` to be the `SimpleGraph V` such that no two adjacent vertices in `G`
are adjacent in the complement, and every nonadjacent pair of vertices is adjacent
(still ensuring that vertices are not adjacent to themselves). -/
instance hasCompl : HasCompl (SimpleGraph V) where
compl G :=
{ Adj := fun v w => v ≠ w ∧ ¬G.Adj v w
symm := fun v w ⟨hne, _⟩ => ⟨hne.symm, by rwa [adj_comm]⟩
loopless := fun _ ⟨hne, _⟩ => (hne rfl).elim }
@[simp]
theorem compl_adj (G : SimpleGraph V) (v w : V) : Gᶜ.Adj v w ↔ v ≠ w ∧ ¬G.Adj v w :=
Iff.rfl
/-- The difference of two graphs `x \ y` has the edges of `x` with the edges of `y` removed. -/
instance sdiff : SDiff (SimpleGraph V) where
sdiff x y :=
{ Adj := x.Adj \ y.Adj
symm := fun v w h => by change x.Adj w v ∧ ¬y.Adj w v; rwa [x.adj_comm, y.adj_comm] }
@[simp]
theorem sdiff_adj (x y : SimpleGraph V) (v w : V) : (x \ y).Adj v w ↔ x.Adj v w ∧ ¬y.Adj v w :=
Iff.rfl
instance supSet : SupSet (SimpleGraph V) where
sSup s :=
{ Adj := fun a b => ∃ G ∈ s, Adj G a b
symm := fun _ _ => Exists.imp fun _ => And.imp_right Adj.symm
loopless := by
rintro a ⟨G, _, ha⟩
exact ha.ne rfl }
instance infSet : InfSet (SimpleGraph V) where
sInf s :=
{ Adj := fun a b => (∀ ⦃G⦄, G ∈ s → Adj G a b) ∧ a ≠ b
symm := fun _ _ => And.imp (forall₂_imp fun _ _ => Adj.symm) Ne.symm
loopless := fun _ h => h.2 rfl }
@[simp]
theorem sSup_adj {s : Set (SimpleGraph V)} {a b : V} : (sSup s).Adj a b ↔ ∃ G ∈ s, Adj G a b :=
Iff.rfl
@[simp]
theorem sInf_adj {s : Set (SimpleGraph V)} : (sInf s).Adj a b ↔ (∀ G ∈ s, Adj G a b) ∧ a ≠ b :=
Iff.rfl
@[simp]
theorem iSup_adj {f : ι → SimpleGraph V} : (⨆ i, f i).Adj a b ↔ ∃ i, (f i).Adj a b := by simp [iSup]
@[simp]
theorem iInf_adj {f : ι → SimpleGraph V} : (⨅ i, f i).Adj a b ↔ (∀ i, (f i).Adj a b) ∧ a ≠ b := by
simp [iInf]
theorem sInf_adj_of_nonempty {s : Set (SimpleGraph V)} (hs : s.Nonempty) :
(sInf s).Adj a b ↔ ∀ G ∈ s, Adj G a b :=
sInf_adj.trans <|
and_iff_left_of_imp <| by
obtain ⟨G, hG⟩ := hs
exact fun h => (h _ hG).ne
theorem iInf_adj_of_nonempty [Nonempty ι] {f : ι → SimpleGraph V} :
(⨅ i, f i).Adj a b ↔ ∀ i, (f i).Adj a b := by
rw [iInf, sInf_adj_of_nonempty (Set.range_nonempty _), Set.forall_mem_range]
/-- For graphs `G`, `H`, `G ≤ H` iff `∀ a b, G.Adj a b → H.Adj a b`. -/
instance distribLattice : DistribLattice (SimpleGraph V) :=
{ show DistribLattice (SimpleGraph V) from
adj_injective.distribLattice _ (fun _ _ => rfl) fun _ _ => rfl with
le := fun G H => ∀ ⦃a b⦄, G.Adj a b → H.Adj a b }
instance completeAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra (SimpleGraph V) where
top.Adj := Ne
bot.Adj _ _ := False
le_top x _ _ h := x.ne_of_adj h
bot_le _ _ _ h := h.elim
sdiff_eq x y := by
ext v w
refine ⟨fun h => ⟨h.1, ⟨?_, h.2⟩⟩, fun h => ⟨h.1, h.2.2⟩⟩
rintro rfl
exact x.irrefl h.1
inf_compl_le_bot _ _ _ h := False.elim <| h.2.2 h.1
top_le_sup_compl G v w hvw := by
by_cases h : G.Adj v w
· exact Or.inl h
· exact Or.inr ⟨hvw, h⟩
le_sSup _ G hG _ _ hab := ⟨G, hG, hab⟩
sSup_le s G hG a b := by
rintro ⟨H, hH, hab⟩
exact hG _ hH hab
sInf_le _ _ hG _ _ hab := hab.1 hG
le_sInf _ _ hG _ _ hab := ⟨fun _ hH => hG _ hH hab, hab.ne⟩
iInf_iSup_eq f := by ext; simp [Classical.skolem]
/-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices. -/
abbrev completeGraph (V : Type u) : SimpleGraph V := ⊤
/-- The graph with no edges on a given vertex type `V`. -/
abbrev emptyGraph (V : Type u) : SimpleGraph V := ⊥
@[simp]
theorem top_adj (v w : V) : (⊤ : SimpleGraph V).Adj v w ↔ v ≠ w :=
Iff.rfl
@[simp]
theorem bot_adj (v w : V) : (⊥ : SimpleGraph V).Adj v w ↔ False :=
Iff.rfl
@[simp]
theorem completeGraph_eq_top (V : Type u) : completeGraph V = ⊤ :=
rfl
@[simp]
theorem emptyGraph_eq_bot (V : Type u) : emptyGraph V = ⊥ :=
rfl
@[simps]
instance (V : Type u) : Inhabited (SimpleGraph V) :=
⟨⊥⟩
instance [Subsingleton V] : Unique (SimpleGraph V) where
default := ⊥
uniq G := by ext a b; have := Subsingleton.elim a b; simp [this]
instance [Nontrivial V] : Nontrivial (SimpleGraph V) :=
⟨⟨⊥, ⊤, fun h ↦ not_subsingleton V ⟨by simpa only [← adj_inj, funext_iff, bot_adj,
top_adj, ne_eq, eq_iff_iff, false_iff, not_not] using h⟩⟩⟩
section Decidable
variable (V) (H : SimpleGraph V) [DecidableRel G.Adj] [DecidableRel H.Adj]
instance Bot.adjDecidable : DecidableRel (⊥ : SimpleGraph V).Adj :=
inferInstanceAs <| DecidableRel fun _ _ => False
instance Sup.adjDecidable : DecidableRel (G ⊔ H).Adj :=
inferInstanceAs <| DecidableRel fun v w => G.Adj v w ∨ H.Adj v w
instance Inf.adjDecidable : DecidableRel (G ⊓ H).Adj :=
inferInstanceAs <| DecidableRel fun v w => G.Adj v w ∧ H.Adj v w
instance Sdiff.adjDecidable : DecidableRel (G \ H).Adj :=
inferInstanceAs <| DecidableRel fun v w => G.Adj v w ∧ ¬H.Adj v w
variable [DecidableEq V]
instance Top.adjDecidable : DecidableRel (⊤ : SimpleGraph V).Adj :=
inferInstanceAs <| DecidableRel fun v w => v ≠ w
instance Compl.adjDecidable : DecidableRel (Gᶜ.Adj) :=
inferInstanceAs <| DecidableRel fun v w => v ≠ w ∧ ¬G.Adj v w
end Decidable
end Order
/-- `G.support` is the set of vertices that form edges in `G`. -/
def support : Set V :=
SetRel.dom {(u, v) : V × V | G.Adj u v}
theorem mem_support {v : V} : v ∈ G.support ↔ ∃ w, G.Adj v w :=
Iff.rfl
theorem support_mono {G G' : SimpleGraph V} (h : G ≤ G') : G.support ⊆ G'.support :=
SetRel.dom_mono fun _uv huv ↦ h huv
/-- `G.neighborSet v` is the set of vertices adjacent to `v` in `G`. -/
def neighborSet (v : V) : Set V := {w | G.Adj v w}
instance neighborSet.memDecidable (v : V) [DecidableRel G.Adj] :
DecidablePred (· ∈ G.neighborSet v) :=
inferInstanceAs <| DecidablePred (Adj G v)
lemma neighborSet_subset_support (v : V) : G.neighborSet v ⊆ G.support :=
fun _ hadj ↦ ⟨v, hadj.symm⟩
section EdgeSet
variable {G₁ G₂ : SimpleGraph V}
/-- The edges of G consist of the unordered pairs of vertices related by
`G.Adj`. This is the order embedding; for the edge set of a particular graph, see
`SimpleGraph.edgeSet`.
The way `edgeSet` is defined is such that `mem_edgeSet` is proved by `Iff.rfl`.
(That is, `s(v, w) ∈ G.edgeSet` is definitionally equal to `G.Adj v w`.)
-/
-- Porting note: We need a separate definition so that dot notation works.
def edgeSetEmbedding (V : Type*) : SimpleGraph V ↪o Set (Sym2 V) :=
OrderEmbedding.ofMapLEIff (fun G => Sym2.fromRel G.symm) fun _ _ =>
⟨fun h a b => @h s(a, b), fun h e => Sym2.ind @h e⟩
/-- `G.edgeSet` is the edge set for `G`.
This is an abbreviation for `edgeSetEmbedding G` that permits dot notation. -/
abbrev edgeSet (G : SimpleGraph V) : Set (Sym2 V) := edgeSetEmbedding V G
@[simp]
theorem mem_edgeSet : s(v, w) ∈ G.edgeSet ↔ G.Adj v w :=
Iff.rfl
theorem not_isDiag_of_mem_edgeSet : e ∈ edgeSet G → ¬e.IsDiag :=
Sym2.ind (fun _ _ => Adj.ne) e
@[simp] lemma not_mem_edgeSet_of_isDiag : e.IsDiag → e ∉ edgeSet G :=
imp_not_comm.1 G.not_isDiag_of_mem_edgeSet
alias _root_.Sym2.IsDiag.not_mem_edgeSet := not_mem_edgeSet_of_isDiag
theorem edgeSet_inj : G₁.edgeSet = G₂.edgeSet ↔ G₁ = G₂ := (edgeSetEmbedding V).eq_iff_eq
@[simp]
theorem edgeSet_subset_edgeSet : edgeSet G₁ ⊆ edgeSet G₂ ↔ G₁ ≤ G₂ :=
(edgeSetEmbedding V).le_iff_le
@[simp]
theorem edgeSet_ssubset_edgeSet : edgeSet G₁ ⊂ edgeSet G₂ ↔ G₁ < G₂ :=
(edgeSetEmbedding V).lt_iff_lt
theorem edgeSet_injective : Injective (edgeSet : SimpleGraph V → Set (Sym2 V)) :=
(edgeSetEmbedding V).injective
alias ⟨_, edgeSet_mono⟩ := edgeSet_subset_edgeSet
alias ⟨_, edgeSet_strict_mono⟩ := edgeSet_ssubset_edgeSet
attribute [mono] edgeSet_mono edgeSet_strict_mono
variable (G₁ G₂)
@[simp]
theorem edgeSet_bot : (⊥ : SimpleGraph V).edgeSet = ∅ :=
Sym2.fromRel_bot
@[simp]
theorem edgeSet_top : (⊤ : SimpleGraph V).edgeSet = {e | ¬e.IsDiag} :=
Sym2.fromRel_ne
@[simp]
theorem edgeSet_subset_setOf_not_isDiag : G.edgeSet ⊆ {e | ¬e.IsDiag} :=
fun _ h => (Sym2.fromRel_irreflexive (sym := G.symm)).mp G.loopless h
@[simp]
theorem edgeSet_sup : (G₁ ⊔ G₂).edgeSet = G₁.edgeSet ∪ G₂.edgeSet := by
ext ⟨x, y⟩
rfl
@[simp]
theorem edgeSet_inf : (G₁ ⊓ G₂).edgeSet = G₁.edgeSet ∩ G₂.edgeSet := by
ext ⟨x, y⟩
rfl
@[simp]
theorem edgeSet_sdiff : (G₁ \ G₂).edgeSet = G₁.edgeSet \ G₂.edgeSet := by
ext ⟨x, y⟩
rfl
variable {G G₁ G₂}
@[simp] lemma disjoint_edgeSet : Disjoint G₁.edgeSet G₂.edgeSet ↔ Disjoint G₁ G₂ := by
rw [Set.disjoint_iff, disjoint_iff_inf_le, ← edgeSet_inf, ← edgeSet_bot, ← Set.le_iff_subset,
OrderEmbedding.le_iff_le]
@[simp] lemma edgeSet_eq_empty : G.edgeSet = ∅ ↔ G = ⊥ := by rw [← edgeSet_bot, edgeSet_inj]
@[simp] lemma edgeSet_nonempty : G.edgeSet.Nonempty ↔ G ≠ ⊥ := by
rw [Set.nonempty_iff_ne_empty, edgeSet_eq_empty.ne]
/-- This lemma, combined with `edgeSet_sdiff` and `edgeSet_from_edgeSet`,
allows proving `(G \ from_edgeSet s).edge_set = G.edgeSet \ s` by `simp`. -/
@[simp]
theorem edgeSet_sdiff_sdiff_isDiag (G : SimpleGraph V) (s : Set (Sym2 V)) :
G.edgeSet \ (s \ { e | e.IsDiag }) = G.edgeSet \ s := by
ext e
simp only [Set.mem_diff, Set.mem_setOf_eq, not_and, not_not, and_congr_right_iff]
intro h
simp only [G.not_isDiag_of_mem_edgeSet h, imp_false]
/-- Two vertices are adjacent iff there is an edge between them. The
condition `v ≠ w` ensures they are different endpoints of the edge,
which is necessary since when `v = w` the existential
`∃ (e ∈ G.edgeSet), v ∈ e ∧ w ∈ e` is satisfied by every edge
incident to `v`. -/
theorem adj_iff_exists_edge {v w : V} : G.Adj v w ↔ v ≠ w ∧ ∃ e ∈ G.edgeSet, v ∈ e ∧ w ∈ e := by
refine ⟨fun _ => ⟨G.ne_of_adj ‹_›, s(v, w), by simpa⟩, ?_⟩
rintro ⟨hne, e, he, hv⟩
rw [Sym2.mem_and_mem_iff hne] at hv
subst e
rwa [mem_edgeSet] at he
theorem adj_iff_exists_edge_coe : G.Adj a b ↔ ∃ e : G.edgeSet, e.val = s(a, b) := by
simp only [mem_edgeSet, exists_prop, SetCoe.exists, exists_eq_right]
theorem ne_bot_iff_exists_adj : G ≠ ⊥ ↔ ∃ a b : V, G.Adj a b := by
simp [← le_bot_iff, le_iff_adj]
theorem ne_top_iff_exists_not_adj : G ≠ ⊤ ↔ ∃ a b : V, a ≠ b ∧ ¬G.Adj a b := by
simp [← top_le_iff, le_iff_adj]
variable (G G₁ G₂)
theorem edge_other_ne {e : Sym2 V} (he : e ∈ G.edgeSet) {v : V} (h : v ∈ e) :
Sym2.Mem.other h ≠ v := by
rw [← Sym2.other_spec h, Sym2.eq_swap] at he
exact G.ne_of_adj he
instance decidableMemEdgeSet [DecidableRel G.Adj] : DecidablePred (· ∈ G.edgeSet) :=
Sym2.fromRel.decidablePred G.symm
instance fintypeEdgeSet [Fintype (Sym2 V)] [DecidableRel G.Adj] : Fintype G.edgeSet :=
Subtype.fintype _
instance fintypeEdgeSetBot : Fintype (⊥ : SimpleGraph V).edgeSet := by
rw [edgeSet_bot]
infer_instance
instance fintypeEdgeSetSup [DecidableEq V] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] :
Fintype (G₁ ⊔ G₂).edgeSet := by
rw [edgeSet_sup]
infer_instance
instance fintypeEdgeSetInf [DecidableEq V] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] :
Fintype (G₁ ⊓ G₂).edgeSet := by
rw [edgeSet_inf]
exact Set.fintypeInter _ _
instance fintypeEdgeSetSdiff [DecidableEq V] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] :
Fintype (G₁ \ G₂).edgeSet := by
rw [edgeSet_sdiff]
exact Set.fintypeDiff _ _
end EdgeSet
section FromEdgeSet
variable (s : Set (Sym2 V))
/-- `fromEdgeSet` constructs a `SimpleGraph` from a set of edges, without loops. -/
def fromEdgeSet : SimpleGraph V where
Adj := Sym2.ToRel s ⊓ Ne
symm _ _ h := ⟨Sym2.toRel_symmetric s h.1, h.2.symm⟩
instance [DecidablePred (· ∈ s)] [DecidableEq V] : DecidableRel (fromEdgeSet s).Adj :=
inferInstanceAs <| DecidableRel fun v w ↦ s(v, w) ∈ s ∧ v ≠ w
@[simp]
theorem fromEdgeSet_adj : (fromEdgeSet s).Adj v w ↔ s(v, w) ∈ s ∧ v ≠ w :=
Iff.rfl
-- Note: we need to make sure `fromEdgeSet_adj` and this lemma are confluent.
-- In particular, both yield `s(u, v) ∈ (fromEdgeSet s).edgeSet` ==> `s(v, w) ∈ s ∧ v ≠ w`.
@[simp]
theorem edgeSet_fromEdgeSet : (fromEdgeSet s).edgeSet = s \ { e | e.IsDiag } := by
ext e
exact Sym2.ind (by simp) e
@[simp]
theorem fromEdgeSet_edgeSet : fromEdgeSet G.edgeSet = G := by
ext v w
exact ⟨fun h => h.1, fun h => ⟨h, G.ne_of_adj h⟩⟩
lemma edgeSet_eq_iff : G.edgeSet = s ↔ G = fromEdgeSet s ∧ Disjoint s {e | e.IsDiag} where
mp := by rintro rfl; simp +contextual [Set.disjoint_right]
mpr := by rintro ⟨rfl, hs⟩; simp [hs]
@[simp]
theorem fromEdgeSet_empty : fromEdgeSet (∅ : Set (Sym2 V)) = ⊥ := by
ext v w
simp only [fromEdgeSet_adj, Set.mem_empty_iff_false, false_and, bot_adj]
@[simp] lemma fromEdgeSet_not_isDiag : fromEdgeSet {e : Sym2 V | ¬ e.IsDiag} = ⊤ := by ext; simp
@[simp]
theorem fromEdgeSet_univ : fromEdgeSet (Set.univ : Set (Sym2 V)) = ⊤ := by
ext v w
simp only [fromEdgeSet_adj, Set.mem_univ, true_and, top_adj]
@[simp]
theorem fromEdgeSet_inter (s t : Set (Sym2 V)) :
fromEdgeSet (s ∩ t) = fromEdgeSet s ⊓ fromEdgeSet t := by
ext v w
simp only [fromEdgeSet_adj, Set.mem_inter_iff, Ne, inf_adj]
tauto
@[simp]
theorem fromEdgeSet_union (s t : Set (Sym2 V)) :
fromEdgeSet (s ∪ t) = fromEdgeSet s ⊔ fromEdgeSet t := by
ext v w
simp [Set.mem_union, or_and_right]
@[simp]
theorem fromEdgeSet_sdiff (s t : Set (Sym2 V)) :
fromEdgeSet (s \ t) = fromEdgeSet s \ fromEdgeSet t := by
ext v w
constructor <;> simp +contextual
@[gcongr, mono]
theorem fromEdgeSet_mono {s t : Set (Sym2 V)} (h : s ⊆ t) : fromEdgeSet s ≤ fromEdgeSet t := by
rintro v w
simp +contextual only [fromEdgeSet_adj, Ne, not_false_iff,
and_true, and_imp]
exact fun vws _ => h vws
@[simp] lemma disjoint_fromEdgeSet : Disjoint G (fromEdgeSet s) ↔ Disjoint G.edgeSet s := by
conv_rhs => rw [← Set.diff_union_inter s {e : Sym2 V | e.IsDiag}]
rw [← disjoint_edgeSet, edgeSet_fromEdgeSet, Set.disjoint_union_right, and_iff_left]
exact Set.disjoint_left.2 fun e he he' ↦ not_isDiag_of_mem_edgeSet _ he he'.2
@[simp] lemma fromEdgeSet_disjoint : Disjoint (fromEdgeSet s) G ↔ Disjoint s G.edgeSet := by
rw [disjoint_comm, disjoint_fromEdgeSet, disjoint_comm]
instance [DecidableEq V] [Fintype s] : Fintype (fromEdgeSet s).edgeSet := by
rw [edgeSet_fromEdgeSet s]
infer_instance
end FromEdgeSet
/-! ### Incidence set -/
/-- Set of edges incident to a given vertex, aka incidence set. -/
def incidenceSet (v : V) : Set (Sym2 V) :=
{ e ∈ G.edgeSet | v ∈ e }
theorem incidenceSet_subset (v : V) : G.incidenceSet v ⊆ G.edgeSet := fun _ h => h.1
theorem mk'_mem_incidenceSet_iff : s(b, c) ∈ G.incidenceSet a ↔ G.Adj b c ∧ (a = b ∨ a = c) :=
and_congr_right' Sym2.mem_iff
theorem mk'_mem_incidenceSet_left_iff : s(a, b) ∈ G.incidenceSet a ↔ G.Adj a b :=
and_iff_left <| Sym2.mem_mk_left _ _
theorem mk'_mem_incidenceSet_right_iff : s(a, b) ∈ G.incidenceSet b ↔ G.Adj a b :=
and_iff_left <| Sym2.mem_mk_right _ _
theorem edge_mem_incidenceSet_iff {e : G.edgeSet} : ↑e ∈ G.incidenceSet a ↔ a ∈ (e : Sym2 V) :=
and_iff_right e.2
theorem incidenceSet_inter_incidenceSet_subset (h : a ≠ b) :
G.incidenceSet a ∩ G.incidenceSet b ⊆ {s(a, b)} := fun _e he =>
(Sym2.mem_and_mem_iff h).1 ⟨he.1.2, he.2.2⟩
theorem incidenceSet_inter_incidenceSet_of_adj (h : G.Adj a b) :
G.incidenceSet a ∩ G.incidenceSet b = {s(a, b)} := by
refine (G.incidenceSet_inter_incidenceSet_subset <| h.ne).antisymm ?_
rintro _ (rfl : _ = s(a, b))
exact ⟨G.mk'_mem_incidenceSet_left_iff.2 h, G.mk'_mem_incidenceSet_right_iff.2 h⟩
theorem adj_of_mem_incidenceSet (h : a ≠ b) (ha : e ∈ G.incidenceSet a)
(hb : e ∈ G.incidenceSet b) : G.Adj a b := by
rwa [← mk'_mem_incidenceSet_left_iff, ←
Set.mem_singleton_iff.1 <| G.incidenceSet_inter_incidenceSet_subset h ⟨ha, hb⟩]
theorem incidenceSet_inter_incidenceSet_of_not_adj (h : ¬G.Adj a b) (hn : a ≠ b) :
G.incidenceSet a ∩ G.incidenceSet b = ∅ := by
simp_rw [Set.eq_empty_iff_forall_notMem, Set.mem_inter_iff, not_and]
intro u ha hb
exact h (G.adj_of_mem_incidenceSet hn ha hb)
instance decidableMemIncidenceSet [DecidableEq V] [DecidableRel G.Adj] (v : V) :
DecidablePred (· ∈ G.incidenceSet v) :=
inferInstanceAs <| DecidablePred fun e => e ∈ G.edgeSet ∧ v ∈ e
@[simp]
theorem mem_neighborSet (v w : V) : w ∈ G.neighborSet v ↔ G.Adj v w :=
Iff.rfl
lemma notMem_neighborSet_self : a ∉ G.neighborSet a := by simp
@[deprecated (since := "2025-05-23")] alias not_mem_neighborSet_self := notMem_neighborSet_self
@[simp]
theorem mem_incidenceSet (v w : V) : s(v, w) ∈ G.incidenceSet v ↔ G.Adj v w := by
simp [incidenceSet]
theorem mem_incidence_iff_neighbor {v w : V} :
s(v, w) ∈ G.incidenceSet v ↔ w ∈ G.neighborSet v := by
simp only [mem_incidenceSet, mem_neighborSet]
theorem adj_incidenceSet_inter {v : V} {e : Sym2 V} (he : e ∈ G.edgeSet) (h : v ∈ e) :
G.incidenceSet v ∩ G.incidenceSet (Sym2.Mem.other h) = {e} := by
ext e'
simp only [incidenceSet, Set.mem_sep_iff, Set.mem_inter_iff, Set.mem_singleton_iff]
refine ⟨fun h' => ?_, ?_⟩
· rw [← Sym2.other_spec h]
exact (Sym2.mem_and_mem_iff (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩
· rintro rfl
exact ⟨⟨he, h⟩, he, Sym2.other_mem _⟩
theorem compl_neighborSet_disjoint (G : SimpleGraph V) (v : V) :
Disjoint (G.neighborSet v) (Gᶜ.neighborSet v) := by
rw [Set.disjoint_iff]
rintro w ⟨h, h'⟩
rw [mem_neighborSet, compl_adj] at h'
exact h'.2 h
theorem neighborSet_union_compl_neighborSet_eq (G : SimpleGraph V) (v : V) :
G.neighborSet v ∪ Gᶜ.neighborSet v = {v}ᶜ := by
ext w
have h := @ne_of_adj _ G
simp_rw [Set.mem_union, mem_neighborSet, compl_adj, Set.mem_compl_iff, Set.mem_singleton_iff]
tauto
theorem card_neighborSet_union_compl_neighborSet [Fintype V] (G : SimpleGraph V) (v : V)
[Fintype (G.neighborSet v ∪ Gᶜ.neighborSet v : Set V)] :
#(G.neighborSet v ∪ Gᶜ.neighborSet v).toFinset = Fintype.card V - 1 := by
classical simp_rw [neighborSet_union_compl_neighborSet_eq, Set.toFinset_compl,
Finset.card_compl, Set.toFinset_card, Set.card_singleton]
theorem neighborSet_compl (G : SimpleGraph V) (v : V) :
Gᶜ.neighborSet v = (G.neighborSet v)ᶜ \ {v} := by
ext w
simp [and_comm, eq_comm]
/-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the
intersection of the neighbor sets of `v` and `w`. -/
def commonNeighbors (v w : V) : Set V :=
G.neighborSet v ∩ G.neighborSet w
theorem commonNeighbors_eq (v w : V) : G.commonNeighbors v w = G.neighborSet v ∩ G.neighborSet w :=
rfl
theorem mem_commonNeighbors {u v w : V} : u ∈ G.commonNeighbors v w ↔ G.Adj v u ∧ G.Adj w u :=
Iff.rfl
theorem commonNeighbors_symm (v w : V) : G.commonNeighbors v w = G.commonNeighbors w v :=
Set.inter_comm _ _
theorem notMem_commonNeighbors_left (v w : V) : v ∉ G.commonNeighbors v w := fun h =>
ne_of_adj G h.1 rfl
@[deprecated (since := "2025-05-23")]
alias not_mem_commonNeighbors_left := notMem_commonNeighbors_left
theorem notMem_commonNeighbors_right (v w : V) : w ∉ G.commonNeighbors v w := fun h =>
ne_of_adj G h.2 rfl
@[deprecated (since := "2025-05-23")]
alias not_mem_commonNeighbors_right := notMem_commonNeighbors_right
theorem commonNeighbors_subset_neighborSet_left (v w : V) :
G.commonNeighbors v w ⊆ G.neighborSet v :=
Set.inter_subset_left
theorem commonNeighbors_subset_neighborSet_right (v w : V) :
G.commonNeighbors v w ⊆ G.neighborSet w :=
Set.inter_subset_right
instance decidableMemCommonNeighbors [DecidableRel G.Adj] (v w : V) :
DecidablePred (· ∈ G.commonNeighbors v w) :=
inferInstanceAs <| DecidablePred fun u => u ∈ G.neighborSet v ∧ u ∈ G.neighborSet w
theorem commonNeighbors_top_eq {v w : V} :
(⊤ : SimpleGraph V).commonNeighbors v w = Set.univ \ {v, w} := by
ext u
simp [commonNeighbors, eq_comm, not_or]
section Incidence
variable [DecidableEq V]
/-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/
def otherVertexOfIncident {v : V} {e : Sym2 V} (h : e ∈ G.incidenceSet v) : V :=
Sym2.Mem.other' h.2
theorem edge_other_incident_set {v : V} {e : Sym2 V} (h : e ∈ G.incidenceSet v) :
e ∈ G.incidenceSet (G.otherVertexOfIncident h) := by
use h.1
simp [otherVertexOfIncident, Sym2.other_mem']
theorem incidence_other_prop {v : V} {e : Sym2 V} (h : e ∈ G.incidenceSet v) :
G.otherVertexOfIncident h ∈ G.neighborSet v := by
obtain ⟨he, hv⟩ := h
rwa [← Sym2.other_spec' hv, mem_edgeSet] at he
@[simp]
theorem incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighborSet v) :
G.otherVertexOfIncident (G.mem_incidence_iff_neighbor.mpr h) = w :=
Sym2.congr_right.mp (Sym2.other_spec' (G.mem_incidence_iff_neighbor.mpr h).right)
/-- There is an equivalence between the set of edges incident to a given
vertex and the set of vertices adjacent to the vertex. -/
@[simps]
def incidenceSetEquivNeighborSet (v : V) : G.incidenceSet v ≃ G.neighborSet v where
toFun e := ⟨G.otherVertexOfIncident e.2, G.incidence_other_prop e.2⟩
invFun w := ⟨s(v, w.1), G.mem_incidence_iff_neighbor.mpr w.2⟩
left_inv x := by simp [otherVertexOfIncident]
right_inv := fun ⟨w, hw⟩ => by
simp only [Subtype.mk.injEq]
exact incidence_other_neighbor_edge _ hw
end Incidence
section IsCompleteBetween
variable {s t : Set V}
/-- The condition that the portion of the simple graph `G` _between_ `s` and `t` is complete, that
is, every vertex in `s` is adjacent to every vertex in `t`, and vice versa. -/
def IsCompleteBetween (G : SimpleGraph V) (s t : Set V) :=
∀ ⦃v₁⦄, v₁ ∈ s → ∀ ⦃v₂⦄, v₂ ∈ t → G.Adj v₁ v₂
theorem IsCompleteBetween.disjoint (h : G.IsCompleteBetween s t) : Disjoint s t :=
Set.disjoint_left.mpr fun v hv₁ hv₂ ↦ (G.loopless v) (h hv₁ hv₂)
theorem isCompleteBetween_comm : G.IsCompleteBetween s t ↔ G.IsCompleteBetween t s where
mp h _ h₁ _ h₂ := (h h₂ h₁).symm
mpr h _ h₁ _ h₂ := (h h₂ h₁).symm
alias ⟨IsCompleteBetween.symm, _⟩ := isCompleteBetween_comm
end IsCompleteBetween
section Subsingleton
protected theorem subsingleton_iff : Subsingleton (SimpleGraph V) ↔ Subsingleton V := by
refine ⟨fun h ↦ ?_, fun _ ↦ Unique.instSubsingleton⟩
contrapose! h
exact instNontrivial
protected theorem nontrivial_iff : Nontrivial (SimpleGraph V) ↔ Nontrivial V := by
refine ⟨fun h ↦ ?_, fun _ ↦ instNontrivial⟩
contrapose! h
exact Unique.instSubsingleton
end Subsingleton
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/IncMatrix.lean | import Mathlib.Combinatorics.SimpleGraph.Finite
import Mathlib.Data.Finset.Sym
import Mathlib.Data.Matrix.Mul
/-!
# Incidence matrix of a simple graph
This file defines the unoriented incidence matrix of a simple graph.
## Main definitions
* `SimpleGraph.incMatrix`: `G.incMatrix R` is the incidence matrix of `G` over the ring `R`.
## Main results
* `SimpleGraph.incMatrix_mul_transpose_diag`: The diagonal entries of the product of
`G.incMatrix R` and its transpose are the degrees of the vertices.
* `SimpleGraph.incMatrix_mul_transpose`: Gives a complete description of the product of
`G.incMatrix R` and its transpose; the diagonal is the degrees of each vertex, and the
off-diagonals are 1 or 0 depending on whether or not the vertices are adjacent.
* `SimpleGraph.incMatrix_transpose_mul_diag`: The diagonal entries of the product of the
transpose of `G.incMatrix R` and `G.inc_matrix R` are `2` or `0` depending on whether or
not the unordered pair is an edge of `G`.
## Implementation notes
The usual definition of an incidence matrix has one row per vertex and one column per edge.
However, this definition has columns indexed by all of `Sym2 α`, where `α` is the vertex type.
This appears not to change the theory, and for simple graphs it has the nice effect that every
incidence matrix for each `SimpleGraph α` has the same type.
## TODO
* Define the oriented incidence matrices for oriented graphs.
* Define the graph Laplacian of a simple graph using the oriented incidence matrix from an
arbitrary orientation of a simple graph.
-/
assert_not_exists Field
open Finset Matrix SimpleGraph Sym2
namespace SimpleGraph
variable (R : Type*) {α : Type*} (G : SimpleGraph α)
/-- `G.incMatrix R` is the `α × Sym2 α` matrix whose `(a, e)`-entry is `1` if `e` is incident to
`a` and `0` otherwise. -/
def incMatrix [Zero R] [One R] [DecidableEq α] [DecidableRel G.Adj] : Matrix α (Sym2 α) R :=
.of fun a e =>
if e ∈ G.incidenceSet a then 1 else 0
variable {R}
theorem incMatrix_apply [Zero R] [One R] [DecidableEq α] [DecidableRel G.Adj] {a : α} {e : Sym2 α} :
G.incMatrix R a e = (G.incidenceSet a).indicator 1 e := by
simp [incMatrix, Set.indicator]
/-- Entries of the incidence matrix can be computed given additional decidable instances. -/
theorem incMatrix_apply' [Zero R] [One R] [DecidableEq α] [DecidableRel G.Adj] {a : α}
{e : Sym2 α} : G.incMatrix R a e = if e ∈ G.incidenceSet a then 1 else 0 := rfl
section MulZeroOneClass
variable [MulZeroOneClass R] [DecidableEq α] [DecidableRel G.Adj] {a b : α} {e : Sym2 α}
theorem incMatrix_apply_mul_incMatrix_apply : G.incMatrix R a e * G.incMatrix R b e =
(G.incidenceSet a ∩ G.incidenceSet b).indicator 1 e := by
simp [incMatrix_apply', Set.indicator_apply, ← ite_and, and_comm]
theorem incMatrix_apply_mul_incMatrix_apply_of_not_adj (hab : a ≠ b) (h : ¬G.Adj a b) :
G.incMatrix R a e * G.incMatrix R b e = 0 := by
rw [incMatrix_apply_mul_incMatrix_apply, Set.indicator_of_notMem]
rw [G.incidenceSet_inter_incidenceSet_of_not_adj h hab]
exact Set.notMem_empty e
theorem incMatrix_of_notMem_incidenceSet (h : e ∉ G.incidenceSet a) : G.incMatrix R a e = 0 := by
rw [incMatrix_apply, Set.indicator_of_notMem h]
@[deprecated (since := "2025-05-23")]
alias incMatrix_of_not_mem_incidenceSet := incMatrix_of_notMem_incidenceSet
theorem incMatrix_of_mem_incidenceSet (h : e ∈ G.incidenceSet a) : G.incMatrix R a e = 1 := by
rw [incMatrix_apply, Set.indicator_of_mem h, Pi.one_apply]
variable [Nontrivial R]
theorem incMatrix_apply_eq_zero_iff : G.incMatrix R a e = 0 ↔ e ∉ G.incidenceSet a := by
simp only [incMatrix_apply, Set.indicator_apply_eq_zero, Pi.one_apply, one_ne_zero]
theorem incMatrix_apply_eq_one_iff : G.incMatrix R a e = 1 ↔ e ∈ G.incidenceSet a := by
convert one_ne_zero.ite_eq_left_iff
infer_instance
end MulZeroOneClass
section NonAssocSemiring
variable [NonAssocSemiring R] [DecidableEq α] [DecidableRel G.Adj] {a : α} {e : Sym2 α}
theorem sum_incMatrix_apply [Fintype (Sym2 α)] [Fintype (neighborSet G a)] :
∑ e, G.incMatrix R a e = G.degree a := by
simp [incMatrix_apply', sum_boole, Set.filter_mem_univ_eq_toFinset]
theorem incMatrix_mul_transpose_diag [Fintype (Sym2 α)] [Fintype (neighborSet G a)] :
(G.incMatrix R * (G.incMatrix R)ᵀ) a a = G.degree a := by
rw [← sum_incMatrix_apply]
simp only [mul_apply, incMatrix_apply', transpose_apply, mul_ite, mul_one, mul_zero]
simp_all only [ite_true, sum_boole]
theorem sum_incMatrix_apply_of_mem_edgeSet [Fintype α] :
e ∈ G.edgeSet → ∑ a, G.incMatrix R a e = 2 := by
refine e.ind ?_
intro a b h
rw [mem_edgeSet] at h
rw [← Nat.cast_two, ← card_pair h.ne]
simp only [incMatrix_apply', sum_boole, mk'_mem_incidenceSet_iff, h]
congr 2
ext e
simp
theorem sum_incMatrix_apply_of_notMem_edgeSet [Fintype α] (h : e ∉ G.edgeSet) :
∑ a, G.incMatrix R a e = 0 :=
sum_eq_zero fun _ _ => G.incMatrix_of_notMem_incidenceSet fun he => h he.1
@[deprecated (since := "2025-05-23")]
alias sum_incMatrix_apply_of_not_mem_edgeSet := sum_incMatrix_apply_of_notMem_edgeSet
theorem incMatrix_transpose_mul_diag [Fintype α] [Decidable (e ∈ G.edgeSet)] :
((G.incMatrix R)ᵀ * G.incMatrix R) e e = if e ∈ G.edgeSet then 2 else 0 := by
simp only [Matrix.mul_apply, incMatrix_apply', transpose_apply, ite_zero_mul_ite_zero, one_mul,
sum_boole, and_self_iff]
split_ifs with h
· revert h
refine e.ind ?_
intro v w h
rw [← Nat.cast_two, ← card_pair (G.ne_of_adj h)]
simp only [mk'_mem_incidenceSet_iff, G.mem_edgeSet.mp h, true_and]
congr 2
ext u
simp
· revert h
refine e.ind ?_
intro v w h
simp [mk'_mem_incidenceSet_iff, G.mem_edgeSet.not.mp h]
end NonAssocSemiring
section Semiring
variable [Fintype (Sym2 α)] [DecidableEq α] [DecidableRel G.Adj] [Semiring R] {a b : α}
theorem incMatrix_mul_transpose_apply_of_adj (h : G.Adj a b) :
(G.incMatrix R * (G.incMatrix R)ᵀ) a b = (1 : R) := by
simp_rw [Matrix.mul_apply, Matrix.transpose_apply, incMatrix_apply_mul_incMatrix_apply,
Set.indicator_apply, Pi.one_apply, sum_boole]
convert @Nat.cast_one R _
convert card_singleton s(a, b)
rw [← coe_eq_singleton, coe_filter_univ]
exact G.incidenceSet_inter_incidenceSet_of_adj h
theorem incMatrix_mul_transpose [∀ a, Fintype (neighborSet G a)] :
G.incMatrix R * (G.incMatrix R)ᵀ =
of fun a b => if a = b then (G.degree a : R) else if G.Adj a b then 1 else 0 := by
ext a b
dsimp
split_ifs with h h'
· subst b
exact incMatrix_mul_transpose_diag (R := R) G
· exact G.incMatrix_mul_transpose_apply_of_adj h'
· simp only [Matrix.mul_apply, Matrix.transpose_apply,
G.incMatrix_apply_mul_incMatrix_apply_of_not_adj h h', sum_const_zero]
end Semiring
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Operations.lean | import Mathlib.Combinatorics.SimpleGraph.Finite
import Mathlib.Combinatorics.SimpleGraph.Maps
import Mathlib.Combinatorics.SimpleGraph.Subgraph
/-!
# Local graph operations
This file defines some single-graph operations that modify a finite number of vertices
and proves basic theorems about them. When the graph itself has a finite number of vertices
we also prove theorems about the number of edges in the modified graphs.
## Main definitions
* `G.replaceVertex s t` is `G` with `t` replaced by a copy of `s`,
removing the `s-t` edge if present.
* `edge s t` is the graph with a single `s-t` edge. Adding this edge to a graph `G` is then
`G ⊔ edge s t`.
-/
open Finset
namespace SimpleGraph
variable {V : Type*} (G : SimpleGraph V) (s t : V)
section ReplaceVertex
variable [DecidableEq V]
/-- The graph formed by forgetting `t`'s neighbours and instead giving it those of `s`. The `s-t`
edge is removed if present. -/
def replaceVertex : SimpleGraph V where
Adj v w := if v = t then if w = t then False else G.Adj s w
else if w = t then G.Adj v s else G.Adj v w
symm v w := by dsimp only; split_ifs <;> simp [adj_comm]
/-- There is never an `s-t` edge in `G.replaceVertex s t`. -/
lemma not_adj_replaceVertex_same : ¬(G.replaceVertex s t).Adj s t := by simp [replaceVertex]
@[simp] lemma replaceVertex_self : G.replaceVertex s s = G := by
ext; unfold replaceVertex; aesop (add simp or_iff_not_imp_left)
variable {t}
/-- Except possibly for `t`, the neighbours of `s` in `G.replaceVertex s t` are its neighbours in
`G`. -/
lemma adj_replaceVertex_iff_of_ne_left {w : V} (hw : w ≠ t) :
(G.replaceVertex s t).Adj s w ↔ G.Adj s w := by simp [replaceVertex, hw]
/-- Except possibly for itself, the neighbours of `t` in `G.replaceVertex s t` are the neighbours of
`s` in `G`. -/
lemma adj_replaceVertex_iff_of_ne_right {w : V} (hw : w ≠ t) :
(G.replaceVertex s t).Adj t w ↔ G.Adj s w := by simp [replaceVertex, hw]
/-- Adjacency in `G.replaceVertex s t` which does not involve `t` is the same as that of `G`. -/
lemma adj_replaceVertex_iff_of_ne {v w : V} (hv : v ≠ t) (hw : w ≠ t) :
(G.replaceVertex s t).Adj v w ↔ G.Adj v w := by simp [replaceVertex, hv, hw]
variable {s}
theorem edgeSet_replaceVertex_of_not_adj (hn : ¬G.Adj s t) : (G.replaceVertex s t).edgeSet =
G.edgeSet \ G.incidenceSet t ∪ (s(·, t)) '' (G.neighborSet s) := by
ext e; refine e.inductionOn ?_
simp only [replaceVertex, mem_edgeSet, Set.mem_union, Set.mem_diff, mk'_mem_incidenceSet_iff]
intros; split_ifs; exacts [by simp_all, by aesop, by rw [adj_comm]; aesop, by aesop]
theorem edgeSet_replaceVertex_of_adj (ha : G.Adj s t) : (G.replaceVertex s t).edgeSet =
(G.edgeSet \ G.incidenceSet t ∪ (s(·, t)) '' (G.neighborSet s)) \ {s(t, t)} := by
ext e; refine e.inductionOn ?_
simp only [replaceVertex, mem_edgeSet, Set.mem_union, Set.mem_diff, mk'_mem_incidenceSet_iff]
intros; split_ifs; exacts [by simp_all, by aesop, by rw [adj_comm]; aesop, by aesop]
variable [Fintype V] [DecidableRel G.Adj]
instance : DecidableRel (G.replaceVertex s t).Adj := by unfold replaceVertex; infer_instance
theorem edgeFinset_replaceVertex_of_not_adj (hn : ¬G.Adj s t) : (G.replaceVertex s t).edgeFinset =
G.edgeFinset \ G.incidenceFinset t ∪ (G.neighborFinset s).image (s(·, t)) := by
simp only [incidenceFinset, neighborFinset, ← Set.toFinset_diff, ← Set.toFinset_image,
← Set.toFinset_union]
exact Set.toFinset_congr (G.edgeSet_replaceVertex_of_not_adj hn)
theorem edgeFinset_replaceVertex_of_adj (ha : G.Adj s t) : (G.replaceVertex s t).edgeFinset =
(G.edgeFinset \ G.incidenceFinset t ∪ (G.neighborFinset s).image (s(·, t))) \ {s(t, t)} := by
simp only [incidenceFinset, neighborFinset, ← Set.toFinset_diff, ← Set.toFinset_image,
← Set.toFinset_union, ← Set.toFinset_singleton]
exact Set.toFinset_congr (G.edgeSet_replaceVertex_of_adj ha)
lemma disjoint_sdiff_neighborFinset_image :
Disjoint (G.edgeFinset \ G.incidenceFinset t) ((G.neighborFinset s).image (s(·, t))) := by
rw [disjoint_iff_ne]
intro e he
have : t ∉ e := by
rw [mem_sdiff, mem_incidenceFinset] at he
obtain ⟨_, h⟩ := he
contrapose! h
simp_all [incidenceSet]
aesop
theorem card_edgeFinset_replaceVertex_of_not_adj (hn : ¬G.Adj s t) :
#(G.replaceVertex s t).edgeFinset = #G.edgeFinset + G.degree s - G.degree t := by
have inc : G.incidenceFinset t ⊆ G.edgeFinset := by simp [incidenceFinset, incidenceSet_subset]
rw [G.edgeFinset_replaceVertex_of_not_adj hn,
card_union_of_disjoint G.disjoint_sdiff_neighborFinset_image, card_sdiff_of_subset inc,
← Nat.sub_add_comm <| card_le_card inc, card_incidenceFinset_eq_degree]
congr 2
rw [card_image_of_injective, card_neighborFinset_eq_degree]
unfold Function.Injective
aesop
theorem card_edgeFinset_replaceVertex_of_adj (ha : G.Adj s t) :
#(G.replaceVertex s t).edgeFinset = #G.edgeFinset + G.degree s - G.degree t - 1 := by
have inc : G.incidenceFinset t ⊆ G.edgeFinset := by simp [incidenceFinset, incidenceSet_subset]
rw [G.edgeFinset_replaceVertex_of_adj ha, card_sdiff_of_subset (by simp [ha]),
card_union_of_disjoint G.disjoint_sdiff_neighborFinset_image, card_sdiff_of_subset inc,
← Nat.sub_add_comm <| card_le_card inc, card_incidenceFinset_eq_degree]
congr 2
rw [card_image_of_injective, card_neighborFinset_eq_degree]
unfold Function.Injective
aesop
end ReplaceVertex
section AddEdge
/-- The graph with a single `s-t` edge. It is empty iff `s = t`. -/
def edge : SimpleGraph V := fromEdgeSet {s(s, t)}
lemma edge_adj (v w : V) : (edge s t).Adj v w ↔ (v = s ∧ w = t ∨ v = t ∧ w = s) ∧ v ≠ w := by
rw [edge, fromEdgeSet_adj, Set.mem_singleton_iff, Sym2.eq_iff]
lemma adj_edge {v w : V} : (edge s t).Adj v w ↔ s(s, t) = s(v, w) ∧ v ≠ w := by
simp only [edge_adj, ne_eq, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk,
and_congr_left_iff]
tauto
lemma edge_comm : edge s t = edge t s := by
rw [edge, edge, Sym2.eq_swap]
variable [DecidableEq V] in
instance : DecidableRel (edge s t).Adj := fun _ _ ↦ by
rw [edge_adj]; infer_instance
@[simp]
lemma edge_self_eq_bot : edge s s = ⊥ := by
ext; rw [edge_adj]; simp_all
lemma sup_edge_self : G ⊔ edge s s = G := by simp
lemma lt_sup_edge (hne : s ≠ t) (hn : ¬ G.Adj s t) : G < G ⊔ edge s t :=
left_lt_sup.2 fun h ↦ hn <| h <| (edge_adj ..).mpr ⟨Or.inl ⟨rfl, rfl⟩, hne⟩
lemma edge_le_iff {v w : V} : edge v w ≤ G ↔ v = w ∨ G.Adj v w := by
obtain h | h := eq_or_ne v w
· simp [h]
· refine ⟨fun h ↦ .inr <| h (by simp_all [edge_adj]), fun hadj v' w' hvw' ↦ ?_⟩
aesop (add simp [edge_adj, adj_symm])
variable {s t}
lemma edge_edgeSet_of_ne (h : s ≠ t) : (edge s t).edgeSet = {s(s, t)} := by
rwa [edge, edgeSet_fromEdgeSet, sdiff_eq_left, Set.disjoint_singleton_left, Set.mem_setOf_eq,
Sym2.isDiag_iff_proj_eq]
lemma sup_edge_of_adj (h : G.Adj s t) : G ⊔ edge s t = G := by
rwa [sup_eq_left, ← edgeSet_subset_edgeSet, edge_edgeSet_of_ne h.ne, Set.singleton_subset_iff,
mem_edgeSet]
lemma disjoint_edge {u v : V} : Disjoint G (edge u v) ↔ ¬G.Adj u v := by
by_cases h : u = v
· subst h
simp [edge_self_eq_bot]
simp [← disjoint_edgeSet, edge_edgeSet_of_ne h]
lemma sdiff_edge {u v : V} (h : ¬G.Adj u v) : G \ edge u v = G := by
simp [disjoint_edge, h]
theorem Subgraph.spanningCoe_sup_edge_le {H : Subgraph (G ⊔ edge s t)} (h : ¬ H.Adj s t) :
H.spanningCoe ≤ G := by
intro v w hvw
have := hvw.adj_sub
simp only [Subgraph.spanningCoe_adj, SimpleGraph.sup_adj, SimpleGraph.edge_adj] at *
by_cases hs : s(v, w) = s(s, t)
· exact (h ((Subgraph.adj_congr_of_sym2 hs).mp hvw)).elim
· aesop
variable [Fintype V] [DecidableRel G.Adj]
variable [DecidableEq V] in
instance : Fintype (edge s t).edgeSet := by rw [edge]; infer_instance
theorem edgeFinset_sup_edge [Fintype (edgeSet (G ⊔ edge s t))] (hn : ¬G.Adj s t) (h : s ≠ t) :
(G ⊔ edge s t).edgeFinset = G.edgeFinset.cons s(s, t) (by simp_all) := by
letI := Classical.decEq V
rw [edgeFinset_sup, cons_eq_insert, insert_eq, union_comm]
simp_rw [edgeFinset, edge_edgeSet_of_ne h]; rfl
theorem card_edgeFinset_sup_edge [Fintype (edgeSet (G ⊔ edge s t))] (hn : ¬G.Adj s t) (h : s ≠ t) :
#(G ⊔ edge s t).edgeFinset = #G.edgeFinset + 1 := by
rw [G.edgeFinset_sup_edge hn h, card_cons]
end AddEdge
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Trails.lean | import Mathlib.Algebra.Ring.Parity
import Mathlib.Combinatorics.SimpleGraph.Paths
/-!
# Trails and Eulerian trails
This module contains additional theory about trails, including Eulerian trails (also known
as Eulerian circuits).
## Main definitions
* `SimpleGraph.Walk.IsEulerian` is the predicate that a trail is an Eulerian trail.
* `SimpleGraph.Walk.IsTrail.even_countP_edges_iff` gives a condition on the number of edges
in a trail that can be incident to a given vertex.
* `SimpleGraph.Walk.IsEulerian.even_degree_iff` gives a condition on the degrees of vertices
when there exists an Eulerian trail.
* `SimpleGraph.Walk.IsEulerian.card_odd_degree` gives the possible numbers of odd-degree
vertices when there exists an Eulerian trail.
## TODO
* Prove that there exists an Eulerian trail when the conclusion to
`SimpleGraph.Walk.IsEulerian.card_odd_degree` holds.
## Tags
Eulerian trails
-/
namespace SimpleGraph
variable {V : Type*} {G : SimpleGraph V}
namespace Walk
/-- The edges of a trail as a finset, since each edge in a trail appears exactly once. -/
abbrev IsTrail.edgesFinset {u v : V} {p : G.Walk u v} (h : p.IsTrail) : Finset (Sym2 V) :=
⟨p.edges, h.edges_nodup⟩
variable [DecidableEq V]
theorem IsTrail.even_countP_edges_iff {u v : V} {p : G.Walk u v} (ht : p.IsTrail) (x : V) :
Even (p.edges.countP fun e => x ∈ e) ↔ u ≠ v → x ≠ u ∧ x ≠ v := by
induction p with
| nil => simp
| cons huv p ih =>
rw [cons_isTrail_iff] at ht
specialize ih ht.1
simp only [List.countP_cons, Ne, edges_cons, Sym2.mem_iff]
split_ifs with h
· rw [decide_eq_true_eq] at h
obtain (rfl | rfl) := h
· rw [Nat.even_add_one, ih]
simp only [huv.ne, imp_false, Ne, not_false_iff, true_and, not_forall,
Classical.not_not, exists_prop, not_true, false_and,
and_iff_right_iff_imp]
rintro rfl rfl
exact G.loopless _ huv
· rw [Nat.even_add_one, ih, ← not_iff_not]
simp only [huv.ne.symm, Ne, not_true, false_and, not_forall,
not_false_iff, exists_prop, and_true, Classical.not_not, true_and, iff_and_self]
rintro rfl
exact huv.ne
· grind
/-- An *Eulerian trail* (also known as an "Eulerian path") is a walk
`p` that visits every edge exactly once. The lemma `SimpleGraph.Walk.IsEulerian.IsTrail` shows
that these are trails.
Combine with `p.IsCircuit` to get an Eulerian circuit (also known as an "Eulerian cycle"). -/
def IsEulerian {u v : V} (p : G.Walk u v) : Prop :=
∀ e, e ∈ G.edgeSet → p.edges.count e = 1
theorem IsEulerian.isTrail {u v : V} {p : G.Walk u v} (h : p.IsEulerian) : p.IsTrail := by
rw [isTrail_def, List.nodup_iff_count_le_one]
intro e
by_cases he : e ∈ p.edges
· exact (h e (edges_subset_edgeSet _ he)).le
· simp [List.count_eq_zero_of_not_mem he]
theorem IsEulerian.mem_edges_iff {u v : V} {p : G.Walk u v} (h : p.IsEulerian) {e : Sym2 V} :
e ∈ p.edges ↔ e ∈ G.edgeSet :=
⟨fun h => p.edges_subset_edgeSet h,
fun he => by simpa [Nat.succ_le] using (h e he).ge⟩
/-- The edge set of an Eulerian graph is finite. -/
def IsEulerian.fintypeEdgeSet {u v : V} {p : G.Walk u v} (h : p.IsEulerian) :
Fintype G.edgeSet :=
Fintype.ofFinset h.isTrail.edgesFinset fun e => by
simp only [Finset.mem_mk, Multiset.mem_coe, h.mem_edges_iff]
theorem IsTrail.isEulerian_of_forall_mem {u v : V} {p : G.Walk u v} (h : p.IsTrail)
(hc : ∀ e, e ∈ G.edgeSet → e ∈ p.edges) : p.IsEulerian := fun e he =>
List.count_eq_one_of_mem h.edges_nodup (hc e he)
theorem isEulerian_iff {u v : V} (p : G.Walk u v) :
p.IsEulerian ↔ p.IsTrail ∧ ∀ e, e ∈ G.edgeSet → e ∈ p.edges := by
constructor
· intro h
exact ⟨h.isTrail, fun _ => h.mem_edges_iff.mpr⟩
· rintro ⟨h, hl⟩
exact h.isEulerian_of_forall_mem hl
theorem IsTrail.isEulerian_iff {u v : V} {p : G.Walk u v} (hp : p.IsTrail) :
p.IsEulerian ↔ p.edgeSet = G.edgeSet :=
⟨fun h ↦ Set.Subset.antisymm p.edges_subset_edgeSet (p.isEulerian_iff.mp h).2,
fun h ↦ p.isEulerian_iff.mpr ⟨hp, by simp [← h]⟩⟩
theorem IsEulerian.edgeSet_eq {u v : V} {p : G.Walk u v} (h : p.IsEulerian) :
p.edgeSet = G.edgeSet := by
rwa [← h.isTrail.isEulerian_iff]
theorem IsEulerian.edgesFinset_eq [Fintype G.edgeSet] {u v : V} {p : G.Walk u v}
(h : p.IsEulerian) : h.isTrail.edgesFinset = G.edgeFinset := by
ext e
simp [h.mem_edges_iff]
theorem IsEulerian.even_degree_iff {x u v : V} {p : G.Walk u v} (ht : p.IsEulerian) [Fintype V]
[DecidableRel G.Adj] : Even (G.degree x) ↔ u ≠ v → x ≠ u ∧ x ≠ v := by
convert ht.isTrail.even_countP_edges_iff x
rw [← Multiset.coe_countP, Multiset.countP_eq_card_filter, ← card_incidenceFinset_eq_degree]
change Multiset.card _ = _
congr 1
convert_to _ = (ht.isTrail.edgesFinset.filter (x ∈ ·)).val
rw [ht.edgesFinset_eq, G.incidenceFinset_eq_filter x]
theorem IsEulerian.card_filter_odd_degree [Fintype V] [DecidableRel G.Adj] {u v : V}
{p : G.Walk u v} (ht : p.IsEulerian) {s}
(h : s = (Finset.univ : Finset V).filter fun v => Odd (G.degree v)) :
s.card = 0 ∨ s.card = 2 := by
subst s
simp only [← Nat.not_even_iff_odd, Finset.card_eq_zero]
simp only [ht.even_degree_iff, Ne, not_forall, not_and, Classical.not_not, exists_prop]
obtain rfl | hn := eq_or_ne u v
· simp
· right
convert_to _ = ({u, v} : Finset V).card
· simp [hn]
· congr
ext x
simp [hn, imp_iff_not_or]
theorem IsEulerian.card_odd_degree [Fintype V] [DecidableRel G.Adj] {u v : V} {p : G.Walk u v}
(ht : p.IsEulerian) : Fintype.card { v : V | Odd (G.degree v) } = 0 ∨
Fintype.card { v : V | Odd (G.degree v) } = 2 := by
rw [← Set.toFinset_card]
apply IsEulerian.card_filter_odd_degree ht
ext v
simp
end Walk
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Coloring.lean | import Mathlib.Combinatorics.SimpleGraph.Clique
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected
import Mathlib.Combinatorics.SimpleGraph.Copy
import Mathlib.Data.ENat.Lattice
import Mathlib.Data.Nat.Lattice
import Mathlib.Data.Setoid.Partition
import Mathlib.Order.Antichain
import Mathlib.Data.Nat.Cast.Order.Ring
/-!
# Graph Coloring
This module defines colorings of simple graphs (also known as proper colorings in the literature).
A graph coloring is the attribution of "colors" to all of its vertices such that adjacent vertices
have different colors.
A coloring can be represented as a homomorphism into a complete graph, whose vertices represent
the colors.
## Main definitions
* `G.Coloring α` is the type of `α`-colorings of a simple graph `G`,
with `α` being the set of available colors. The type is defined to
be homomorphisms from `G` into the complete graph on `α`, and
colorings have a coercion to `V → α`.
* `G.Colorable n` is the proposition that `G` is `n`-colorable, which
is whether there exists a coloring with at most *n* colors.
* `G.chromaticNumber` is the minimal `n` such that `G` is `n`-colorable,
or `⊤` if it cannot be colored with finitely many colors.
(Cardinal-valued chromatic numbers are more niche, so we stick to `ℕ∞`.)
We write `G.chromaticNumber ≠ ⊤` to mean a graph is colorable with finitely many colors.
* `C.colorClass c` is the set of vertices colored by `c : α` in the coloring `C : G.Coloring α`.
* `C.colorClasses` is the set containing all color classes.
## TODO
* Gather material from:
* https://github.com/leanprover-community/mathlib/blob/simple_graph_matching/src/combinatorics/simple_graph/coloring.lean
* https://github.com/kmill/lean-graphcoloring/blob/master/src/graph.lean
* Trees
* Planar graphs
* Chromatic polynomials
* develop API for partial colorings, likely as colorings of subgraphs (`H.coe.Coloring α`)
-/
assert_not_exists Field
open Fintype Function
universe u v
namespace SimpleGraph
variable {V : Type u} (G : SimpleGraph V) {n : ℕ}
/-- An `α`-coloring of a simple graph `G` is a homomorphism of `G` into the complete graph on `α`.
This is also known as a proper coloring.
-/
abbrev Coloring (α : Type v) := G →g completeGraph α
variable {G}
variable {α β : Type*} (C : G.Coloring α)
theorem Coloring.valid {v w : V} (h : G.Adj v w) : C v ≠ C w :=
C.map_rel h
/-- Construct a term of `SimpleGraph.Coloring` using a function that
assigns vertices to colors and a proof that it is as proper coloring.
(Note: this is a definitionally the constructor for `SimpleGraph.Hom`,
but with a syntactically better proper coloring hypothesis.)
-/
@[match_pattern]
def Coloring.mk (color : V → α) (valid : ∀ {v w : V}, G.Adj v w → color v ≠ color w) :
G.Coloring α :=
⟨color, @valid⟩
/-- The color class of a given color.
-/
def Coloring.colorClass (c : α) : Set V := { v : V | C v = c }
/-- The set containing all color classes. -/
def Coloring.colorClasses : Set (Set V) := (Setoid.ker C).classes
theorem Coloring.mem_colorClass (v : V) : v ∈ C.colorClass (C v) := rfl
theorem Coloring.colorClasses_isPartition : Setoid.IsPartition C.colorClasses :=
Setoid.isPartition_classes (Setoid.ker C)
theorem Coloring.mem_colorClasses {v : V} : C.colorClass (C v) ∈ C.colorClasses :=
⟨v, rfl⟩
theorem Coloring.colorClasses_finite [Finite α] : C.colorClasses.Finite :=
Setoid.finite_classes_ker _
theorem Coloring.card_colorClasses_le [Fintype α] [Fintype C.colorClasses] :
Fintype.card C.colorClasses ≤ Fintype.card α := by
simp only [colorClasses]
convert Setoid.card_classes_ker_le C
theorem Coloring.not_adj_of_mem_colorClass {c : α} {v w : V} (hv : v ∈ C.colorClass c)
(hw : w ∈ C.colorClass c) : ¬G.Adj v w := fun h => C.valid h (Eq.trans hv (Eq.symm hw))
theorem Coloring.color_classes_independent (c : α) : IsAntichain G.Adj (C.colorClass c) :=
fun _ hv _ hw _ => C.not_adj_of_mem_colorClass hv hw
-- TODO make this computable
noncomputable instance [Fintype V] [Fintype α] : Fintype (Coloring G α) := by
classical
change Fintype (RelHom G.Adj (completeGraph α).Adj)
apply Fintype.ofInjective _ RelHom.coe_fn_injective
instance [DecidableEq α] {c : α} :
DecidablePred (· ∈ C.colorClass c) :=
inferInstanceAs <| DecidablePred (· ∈ { v | C v = c })
variable (G)
/-- Whether a graph can be colored by at most `n` colors. -/
def Colorable (n : ℕ) : Prop := Nonempty (G.Coloring (Fin n))
/-- The coloring of an empty graph. -/
def coloringOfIsEmpty [IsEmpty V] : G.Coloring α :=
Coloring.mk isEmptyElim fun {v} => isEmptyElim v
theorem colorable_of_isEmpty [IsEmpty V] (n : ℕ) : G.Colorable n :=
⟨G.coloringOfIsEmpty⟩
theorem isEmpty_of_colorable_zero (h : G.Colorable 0) : IsEmpty V := by
constructor
intro v
obtain ⟨i, hi⟩ := h.some v
exact Nat.not_lt_zero _ hi
@[simp]
lemma colorable_zero_iff : G.Colorable 0 ↔ IsEmpty V :=
⟨G.isEmpty_of_colorable_zero, fun _ ↦ G.colorable_of_isEmpty 0⟩
/-- If `G` is `n`-colorable, then mapping the vertices of `G` produces an `n`-colorable simple
graph. -/
theorem Colorable.map {β : Type*} (f : V ↪ β) [NeZero n] {G : SimpleGraph V} (hc : G.Colorable n) :
(G.map f).Colorable n := by
obtain ⟨C⟩ := hc
use extend f C (const β default)
intro a b ⟨_, _, hadj, ha, hb⟩
rw [← ha, f.injective.extend_apply, ← hb, f.injective.extend_apply]
exact C.valid hadj
/-- The "tautological" coloring of a graph, using the vertices of the graph as colors. -/
def selfColoring : G.Coloring V := Coloring.mk id fun {_ _} => G.ne_of_adj
/-- The chromatic number of a graph is the minimal number of colors needed to color it.
This is `⊤` (infinity) iff `G` isn't colorable with finitely many colors.
If `G` is colorable, then `ENat.toNat G.chromaticNumber` is the `ℕ`-valued chromatic number. -/
noncomputable def chromaticNumber : ℕ∞ := ⨅ n ∈ setOf G.Colorable, (n : ℕ∞)
lemma chromaticNumber_eq_biInf {G : SimpleGraph V} :
G.chromaticNumber = ⨅ n ∈ setOf G.Colorable, (n : ℕ∞) := rfl
lemma chromaticNumber_eq_iInf {G : SimpleGraph V} :
G.chromaticNumber = ⨅ n : {m | G.Colorable m}, (n : ℕ∞) := by
rw [chromaticNumber, iInf_subtype]
lemma Colorable.chromaticNumber_eq_sInf {G : SimpleGraph V} {n} (h : G.Colorable n) :
G.chromaticNumber = sInf {n' : ℕ | G.Colorable n'} := by
rw [ENat.coe_sInf, chromaticNumber]
exact ⟨_, h⟩
/-- Given an embedding, there is an induced embedding of colorings. -/
def recolorOfEmbedding {α β : Type*} (f : α ↪ β) : G.Coloring α ↪ G.Coloring β where
toFun C := (Embedding.completeGraph f).toHom.comp C
inj' := by -- this was strangely painful; seems like missing lemmas about embeddings
intro C C' h
dsimp only at h
ext v
apply (Embedding.completeGraph f).inj'
change ((Embedding.completeGraph f).toHom.comp C) v = _
rw [h]
rfl
@[simp] lemma coe_recolorOfEmbedding (f : α ↪ β) :
⇑(G.recolorOfEmbedding f) = (Embedding.completeGraph f).toHom.comp := rfl
/-- Given an equivalence, there is an induced equivalence between colorings. -/
def recolorOfEquiv {α β : Type*} (f : α ≃ β) : G.Coloring α ≃ G.Coloring β where
toFun := G.recolorOfEmbedding f.toEmbedding
invFun := G.recolorOfEmbedding f.symm.toEmbedding
left_inv C := by
ext v
apply Equiv.symm_apply_apply
right_inv C := by
ext v
apply Equiv.apply_symm_apply
@[simp] lemma coe_recolorOfEquiv (f : α ≃ β) :
⇑(G.recolorOfEquiv f) = (Embedding.completeGraph f).toHom.comp := rfl
/-- There is a noncomputable embedding of `α`-colorings to `β`-colorings if
`β` has at least as large a cardinality as `α`. -/
noncomputable def recolorOfCardLE {α β : Type*} [Fintype α] [Fintype β]
(hn : Fintype.card α ≤ Fintype.card β) : G.Coloring α ↪ G.Coloring β :=
G.recolorOfEmbedding <| (Function.Embedding.nonempty_of_card_le hn).some
@[simp] lemma coe_recolorOfCardLE [Fintype α] [Fintype β] (hαβ : card α ≤ card β) :
⇑(G.recolorOfCardLE hαβ) =
(Embedding.completeGraph (Embedding.nonempty_of_card_le hαβ).some).toHom.comp := rfl
variable {G}
theorem Colorable.mono {n m : ℕ} (h : n ≤ m) (hc : G.Colorable n) : G.Colorable m :=
⟨G.recolorOfCardLE (by simp [h]) hc.some⟩
theorem Coloring.colorable [Fintype α] (C : G.Coloring α) : G.Colorable (Fintype.card α) :=
⟨G.recolorOfCardLE (by simp) C⟩
theorem colorable_of_fintype (G : SimpleGraph V) [Fintype V] : G.Colorable (Fintype.card V) :=
G.selfColoring.colorable
/-- Noncomputably get a coloring from colorability. -/
noncomputable def Colorable.toColoring [Fintype α] {n : ℕ} (hc : G.Colorable n)
(hn : n ≤ Fintype.card α) : G.Coloring α := by
rw [← Fintype.card_fin n] at hn
exact G.recolorOfCardLE hn hc.some
theorem Colorable.of_hom {V' : Type*} {G' : SimpleGraph V'} (f : G →g G') {n : ℕ}
(h : G'.Colorable n) : G.Colorable n :=
⟨(h.toColoring (by simp)).comp f⟩
@[deprecated SimpleGraph.Colorable.of_hom (since := "2025-09-01")]
theorem Colorable.of_embedding {V' : Type*} {G' : SimpleGraph V'} (f : G ↪g G') {n : ℕ}
(h : G'.Colorable n) : G.Colorable n :=
Colorable.of_hom f h
theorem colorable_iff_exists_bdd_nat_coloring (n : ℕ) :
G.Colorable n ↔ ∃ C : G.Coloring ℕ, ∀ v, C v < n := by
constructor
· rintro hc
have C : G.Coloring (Fin n) := hc.toColoring (by simp)
let f := Embedding.completeGraph (@Fin.valEmbedding n)
use f.toHom.comp C
intro v
exact Fin.is_lt (C.1 v)
· rintro ⟨C, Cf⟩
refine ⟨Coloring.mk ?_ ?_⟩
· exact fun v => ⟨C v, Cf v⟩
· rintro v w hvw
simp only [Fin.mk_eq_mk, Ne]
exact C.valid hvw
theorem colorable_iff_forall_connectedComponents {n : ℕ} :
G.Colorable n ↔ ∀ c : G.ConnectedComponent, (c.toSimpleGraph).Colorable n :=
⟨fun ⟨C⟩ _ ↦ ⟨fun v ↦ C v, fun h h1 ↦ C.valid h h1⟩,
fun h ↦ ⟨G.homOfConnectedComponents (fun c ↦ (h c).some)⟩⟩
theorem colorable_set_nonempty_of_colorable {n : ℕ} (hc : G.Colorable n) :
{ n : ℕ | G.Colorable n }.Nonempty :=
⟨n, hc⟩
theorem chromaticNumber_bddBelow : BddBelow { n : ℕ | G.Colorable n } :=
⟨0, fun _ _ => zero_le _⟩
theorem Colorable.chromaticNumber_le {n : ℕ} (hc : G.Colorable n) : G.chromaticNumber ≤ n := by
rw [hc.chromaticNumber_eq_sInf]
norm_cast
apply csInf_le chromaticNumber_bddBelow
exact hc
theorem chromaticNumber_ne_top_iff_exists : G.chromaticNumber ≠ ⊤ ↔ ∃ n, G.Colorable n := by
rw [chromaticNumber]
convert_to ⨅ n : {m | G.Colorable m}, (n : ℕ∞) ≠ ⊤ ↔ _
· rw [iInf_subtype]
rw [← lt_top_iff_ne_top, ENat.iInf_coe_lt_top]
simp
theorem chromaticNumber_le_iff_colorable {n : ℕ} : G.chromaticNumber ≤ n ↔ G.Colorable n := by
refine ⟨fun h ↦ ?_, Colorable.chromaticNumber_le⟩
have : G.chromaticNumber ≠ ⊤ := (trans h (WithTop.coe_lt_top n)).ne
rw [chromaticNumber_ne_top_iff_exists] at this
obtain ⟨m, hm⟩ := this
rw [hm.chromaticNumber_eq_sInf, Nat.cast_le] at h
have := Nat.sInf_mem (⟨m, hm⟩ : {n' | G.Colorable n'}.Nonempty)
rw [Set.mem_setOf_eq] at this
exact this.mono h
/-- If the chromatic number of `G` is `n + 1`, then `G` is colorable in no fewer than `n + 1`
colors. -/
theorem chromaticNumber_eq_iff_colorable_not_colorable :
G.chromaticNumber = n + 1 ↔ G.Colorable (n + 1) ∧ ¬G.Colorable n := by
rw [eq_iff_le_not_lt, not_lt, ENat.add_one_le_iff (ENat.coe_ne_top n), ← not_le,
chromaticNumber_le_iff_colorable, ← Nat.cast_add_one, chromaticNumber_le_iff_colorable]
theorem colorable_chromaticNumber {m : ℕ} (hc : G.Colorable m) :
G.Colorable (ENat.toNat G.chromaticNumber) := by
classical
rw [hc.chromaticNumber_eq_sInf, Nat.sInf_def]
· apply Nat.find_spec
· exact colorable_set_nonempty_of_colorable hc
theorem colorable_chromaticNumber_of_fintype (G : SimpleGraph V) [Finite V] :
G.Colorable (ENat.toNat G.chromaticNumber) := by
cases nonempty_fintype V
exact colorable_chromaticNumber G.colorable_of_fintype
theorem chromaticNumber_le_one_of_subsingleton (G : SimpleGraph V) [Subsingleton V] :
G.chromaticNumber ≤ 1 := by
rw [← Nat.cast_one, chromaticNumber_le_iff_colorable]
refine ⟨Coloring.mk (fun _ => 0) ?_⟩
intro v w
cases Subsingleton.elim v w
simp
theorem chromaticNumber_pos [Nonempty V] {n : ℕ} (hc : G.Colorable n) : 0 < G.chromaticNumber := by
rw [hc.chromaticNumber_eq_sInf, Nat.cast_pos]
apply le_csInf (colorable_set_nonempty_of_colorable hc)
intro m hm
by_contra h'
simp only [not_le] at h'
obtain ⟨i, hi⟩ := hm.some (Classical.arbitrary V)
have h₁ : i < 0 := lt_of_lt_of_le hi (Nat.le_of_lt_succ h')
exact Nat.not_lt_zero _ h₁
theorem colorable_of_chromaticNumber_ne_top (h : G.chromaticNumber ≠ ⊤) :
G.Colorable (ENat.toNat G.chromaticNumber) := by
rw [chromaticNumber_ne_top_iff_exists] at h
obtain ⟨n, hn⟩ := h
exact colorable_chromaticNumber hn
theorem chromaticNumber_eq_zero_of_isEmpty [IsEmpty V] : G.chromaticNumber = 0 := by
rw [← nonpos_iff_eq_zero, ← Nat.cast_zero, chromaticNumber_le_iff_colorable]
apply colorable_of_isEmpty
@[deprecated (since := "2025-09-15")]
alias chromaticNumber_eq_zero_of_isempty := chromaticNumber_eq_zero_of_isEmpty
theorem isEmpty_of_chromaticNumber_eq_zero (h : G.chromaticNumber = 0) : IsEmpty V := by
have := colorable_of_chromaticNumber_ne_top (h ▸ ENat.zero_ne_top)
rw [h] at this
exact G.isEmpty_of_colorable_zero this
theorem Colorable.mono_left {G' : SimpleGraph V} (h : G ≤ G') {n : ℕ} (hc : G'.Colorable n) :
G.Colorable n :=
⟨hc.some.comp (.ofLE h)⟩
theorem chromaticNumber_le_of_forall_imp {V' : Type*} {G' : SimpleGraph V'}
(h : ∀ n, G'.Colorable n → G.Colorable n) :
G.chromaticNumber ≤ G'.chromaticNumber := by
rw [chromaticNumber, chromaticNumber]
simp only [Set.mem_setOf_eq, le_iInf_iff]
intro m hc
have := h _ hc
rw [← chromaticNumber_le_iff_colorable] at this
exact this
theorem chromaticNumber_mono (G' : SimpleGraph V)
(h : G ≤ G') : G.chromaticNumber ≤ G'.chromaticNumber :=
chromaticNumber_le_of_forall_imp fun _ => Colorable.mono_left h
theorem chromaticNumber_mono_of_hom {V' : Type*} {G' : SimpleGraph V'}
(f : G →g G') : G.chromaticNumber ≤ G'.chromaticNumber :=
chromaticNumber_le_of_forall_imp fun _ => Colorable.of_hom f
@[deprecated SimpleGraph.chromaticNumber_mono_of_hom (since := "2025-09-01")]
theorem chromaticNumber_mono_of_embedding {V' : Type*} {G' : SimpleGraph V'}
(f : G ↪g G') : G.chromaticNumber ≤ G'.chromaticNumber :=
chromaticNumber_mono_of_hom f
lemma card_le_chromaticNumber_iff_forall_surjective [Fintype α] :
card α ≤ G.chromaticNumber ↔ ∀ C : G.Coloring α, Surjective C := by
refine ⟨fun h C ↦ ?_, fun h ↦ ?_⟩
· rw [C.colorable.chromaticNumber_eq_sInf, Nat.cast_le] at h
intro i
by_contra! hi
let D : G.Coloring {a // a ≠ i} := ⟨fun v ↦ ⟨C v, hi v⟩, (C.valid · <| congr_arg Subtype.val ·)⟩
classical
exact Nat.notMem_of_lt_sInf ((Nat.sub_one_lt_of_lt <| card_pos_iff.2 ⟨i⟩).trans_le h)
⟨G.recolorOfEquiv (equivOfCardEq <| by simp) D⟩
· simp only [chromaticNumber, Set.mem_setOf_eq, le_iInf_iff, Nat.cast_le]
rintro i ⟨C⟩
contrapose! h
refine ⟨G.recolorOfCardLE (by simpa using h.le) C, fun hC ↦ ?_⟩
dsimp at hC
simpa [h.not_ge] using Fintype.card_le_of_surjective _ hC.of_comp
lemma le_chromaticNumber_iff_forall_surjective :
n ≤ G.chromaticNumber ↔ ∀ C : G.Coloring (Fin n), Surjective C := by
simp [← card_le_chromaticNumber_iff_forall_surjective]
lemma chromaticNumber_eq_card_iff_forall_surjective [Fintype α] (hG : G.Colorable (card α)) :
G.chromaticNumber = card α ↔ ∀ C : G.Coloring α, Surjective C := by
rw [← hG.chromaticNumber_le.ge_iff_eq, card_le_chromaticNumber_iff_forall_surjective]
lemma chromaticNumber_eq_iff_forall_surjective (hG : G.Colorable n) :
G.chromaticNumber = n ↔ ∀ C : G.Coloring (Fin n), Surjective C := by
rw [← hG.chromaticNumber_le.ge_iff_eq, le_chromaticNumber_iff_forall_surjective]
theorem chromaticNumber_bot [Nonempty V] : (⊥ : SimpleGraph V).chromaticNumber = 1 := by
have : (⊥ : SimpleGraph V).Colorable 1 := ⟨.mk 0 <| by simp⟩
exact this.chromaticNumber_le.antisymm <| Order.one_le_iff_pos.2 <| chromaticNumber_pos this
@[simp]
theorem chromaticNumber_top [Fintype V] : (⊤ : SimpleGraph V).chromaticNumber = Fintype.card V := by
rw [chromaticNumber_eq_card_iff_forall_surjective (selfColoring _).colorable]
intro C
rw [← Finite.injective_iff_surjective]
intro v w
contrapose
intro h
exact C.valid h
theorem chromaticNumber_top_eq_top_of_infinite (V : Type*) [Infinite V] :
(⊤ : SimpleGraph V).chromaticNumber = ⊤ := by
by_contra hc
rw [← Ne, chromaticNumber_ne_top_iff_exists] at hc
obtain ⟨n, ⟨hn⟩⟩ := hc
exact not_injective_infinite_finite _ hn.injective_of_top_hom
theorem eq_top_of_chromaticNumber_eq_card [DecidableEq V] [Fintype V]
(h : G.chromaticNumber = Fintype.card V) : G = ⊤ := by
by_contra! hh
have : G.chromaticNumber ≤ Fintype.card V - 1 := by
obtain ⟨a, b, hne, _⟩ := ne_top_iff_exists_not_adj.mp hh
apply chromaticNumber_le_iff_colorable.mpr
suffices G.Coloring (Finset.univ.erase b) by simpa using Coloring.colorable this
apply Coloring.mk (fun x ↦ if h' : x ≠ b then ⟨x, by simp [h']⟩ else ⟨a, by simp [hne]⟩)
grind [Adj.ne', adj_symm]
rw [h, ← ENat.coe_one, ← ENat.coe_sub, ENat.coe_le_coe] at this
have := Fintype.one_lt_card_iff_nontrivial.mpr <| SimpleGraph.nontrivial_iff.mp ⟨_, _, hh⟩
grind
theorem chromaticNumber_eq_card_iff [DecidableEq V] [Fintype V] :
G.chromaticNumber = Fintype.card V ↔ G = ⊤ :=
⟨eq_top_of_chromaticNumber_eq_card, fun h ↦ h ▸ chromaticNumber_top⟩
theorem chromaticNumber_le_card [Fintype V] : G.chromaticNumber ≤ Fintype.card V := by
rw [← chromaticNumber_top]
exact chromaticNumber_mono_of_hom G.selfColoring
theorem two_le_chromaticNumber_of_adj {u v : V} (hadj : G.Adj u v) : 2 ≤ G.chromaticNumber := by
refine le_of_not_gt fun h ↦ ?_
obtain ⟨c⟩ := chromaticNumber_le_iff_colorable.mp (Order.le_of_lt_add_one h)
exact c.valid hadj (Subsingleton.elim (c u) (c v))
theorem chromaticNumber_eq_one_iff : G.chromaticNumber = 1 ↔ G = ⊥ ∧ Nonempty V := by
refine ⟨fun h ↦ ⟨?_, ?_⟩, fun ⟨h₁, _⟩ ↦ h₁ ▸ chromaticNumber_bot⟩
· contrapose! h
obtain ⟨_, _, h⟩ := ne_bot_iff_exists_adj.mp h
have := two_le_chromaticNumber_of_adj h
contrapose! this
simp [this]
· refine not_isEmpty_iff.mp ?_
contrapose! h
have := G.colorable_zero_iff.mpr h |>.chromaticNumber_le
simp_all
theorem two_le_chromaticNumber_iff_ne_bot : 2 ≤ G.chromaticNumber ↔ G ≠ ⊥ := by
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· contrapose! h
by_cases h' : IsEmpty V
· simp [chromaticNumber_eq_zero_of_isEmpty]
· simp [chromaticNumber_eq_one_iff.mpr ⟨h, by simpa using h'⟩]
· obtain ⟨_, _, h⟩ := ne_bot_iff_exists_adj.mp h
exact two_le_chromaticNumber_of_adj h
/-- The bicoloring of a complete bipartite graph using whether a vertex
is on the left or on the right. -/
def CompleteBipartiteGraph.bicoloring (V W : Type*) : (completeBipartiteGraph V W).Coloring Bool :=
Coloring.mk (fun v => v.isRight)
(by
intro v w
cases v <;> cases w <;> simp)
theorem CompleteBipartiteGraph.chromaticNumber {V W : Type*} [Nonempty V] [Nonempty W] :
(completeBipartiteGraph V W).chromaticNumber = 2 := by
rw [← Nat.cast_two, chromaticNumber_eq_iff_forall_surjective
(by simpa using (CompleteBipartiteGraph.bicoloring V W).colorable)]
intro C b
have v := Classical.arbitrary V
have w := Classical.arbitrary W
have h : (completeBipartiteGraph V W).Adj (Sum.inl v) (Sum.inr w) := by simp
by_cases he : C (Sum.inl v) = b
· exact ⟨_, he⟩
by_cases he' : C (Sum.inr w) = b
· exact ⟨_, he'⟩
· simpa using two_lt_card_iff.2 ⟨_, _, _, C.valid h, he, he'⟩
/-! ### Cliques -/
theorem IsClique.card_le_of_coloring {s : Finset V} (h : G.IsClique s) [Fintype α]
(C : G.Coloring α) : s.card ≤ Fintype.card α := by
rw [isClique_iff_induce_eq] at h
have f : G.induce ↑s ↪g G := Embedding.comap (Function.Embedding.subtype fun x => x ∈ ↑s) G
rw [h] at f
convert Fintype.card_le_of_injective _ (C.comp f.toHom).injective_of_top_hom using 1
simp
theorem IsClique.card_le_of_colorable {s : Finset V} (h : G.IsClique s) {n : ℕ}
(hc : G.Colorable n) : s.card ≤ n := by
convert h.card_le_of_coloring hc.some
simp
theorem IsClique.card_le_chromaticNumber {s : Finset V} (h : G.IsClique s) :
s.card ≤ G.chromaticNumber := by
obtain (hc | hc) := eq_or_ne G.chromaticNumber ⊤
· rw [hc]
exact le_top
· have hc' := hc
rw [chromaticNumber_ne_top_iff_exists] at hc'
obtain ⟨n, c⟩ := hc'
rw [← ENat.coe_toNat_eq_self] at hc
rw [← hc, Nat.cast_le]
exact h.card_le_of_colorable (colorable_chromaticNumber c)
protected theorem Colorable.cliqueFree {n m : ℕ} (hc : G.Colorable n) (hm : n < m) :
G.CliqueFree m := by
by_contra h
simp only [CliqueFree, isNClique_iff, not_forall, Classical.not_not] at h
obtain ⟨s, h, rfl⟩ := h
exact Nat.lt_le_asymm hm (h.card_le_of_colorable hc)
theorem cliqueFree_of_chromaticNumber_lt {n : ℕ} (hc : G.chromaticNumber < n) :
G.CliqueFree n := by
have hne : G.chromaticNumber ≠ ⊤ := hc.ne_top
obtain ⟨m, hc'⟩ := chromaticNumber_ne_top_iff_exists.mp hne
have := colorable_chromaticNumber hc'
refine this.cliqueFree ?_
rw [← ENat.coe_toNat_eq_self] at hne
rw [← hne] at hc
simpa using hc
/--
Given a colouring `α` of `G`, and a clique of size at least the number of colours, the clique
contains a vertex of each colour.
-/
lemma Coloring.surjOn_of_card_le_isClique [Fintype α] {s : Finset V} (h : G.IsClique s)
(hc : Fintype.card α ≤ s.card) (C : G.Coloring α) : Set.SurjOn C s Set.univ := by
intro _ _
obtain ⟨_, hx⟩ := card_le_chromaticNumber_iff_forall_surjective.mp
(by simp_all [isClique_iff_induce_eq]) (C.comp (Embedding.induce s).toHom) _
exact ⟨_, Subtype.coe_prop _, hx⟩
namespace completeMultipartiteGraph
variable {ι : Type*} (V : ι → Type*)
/-- The canonical `ι`-coloring of a `completeMultipartiteGraph` with parts indexed by `ι` -/
def coloring : (completeMultipartiteGraph V).Coloring ι := Coloring.mk (fun v ↦ v.1) (by simp)
lemma colorable [Fintype ι] : (completeMultipartiteGraph V).Colorable (Fintype.card ι) :=
(coloring V).colorable
theorem chromaticNumber [Fintype ι] (f : ∀ (i : ι), V i) :
(completeMultipartiteGraph V).chromaticNumber = Fintype.card ι := by
apply le_antisymm (colorable V).chromaticNumber_le
by_contra! h
exact not_cliqueFree_of_le_card V f le_rfl <| cliqueFree_of_chromaticNumber_lt h
theorem colorable_of_cliqueFree (f : ∀ (i : ι), V i)
(hc : (completeMultipartiteGraph V).CliqueFree n) :
(completeMultipartiteGraph V).Colorable (n - 1) := by
cases n with
| zero => exact absurd hc not_cliqueFree_zero
| succ n =>
have : Fintype ι := fintypeOfNotInfinite
fun hinf ↦ not_cliqueFree_of_infinite V f hc
apply (coloring V).colorable.mono
have := not_cliqueFree_of_le_card V f le_rfl
contrapose! this
exact hc.mono this
end completeMultipartiteGraph
/-- If `H` is not `n`-colorable and `G` is `n`-colorable, then `G` is `H.Free`. -/
theorem free_of_colorable {W : Type*} {H : SimpleGraph W}
(nhc : ¬H.Colorable n) (hc : G.Colorable n) : H.Free G := by
contrapose! nhc with hc'
exact ⟨hc.some.comp hc'.some.toHom⟩
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Hall.lean | import Mathlib.Combinatorics.Hall.Basic
import Mathlib.Combinatorics.SimpleGraph.Bipartite
import Mathlib.Combinatorics.SimpleGraph.Matching
/-!
# Hall's Marriage Theorem
This file derives Hall's Marriage Theorem for bipartite graphs from the combinatorial formulation in
`Mathlib/Combinatorics/Hall/Basic.lean`.
## Main statements
* `exists_isMatching_of_forall_ncard_le`: Hall's marriage theorem for a matching on a single
partition of a bipartite graph.
* `exists_isPerfectMatching_of_forall_ncard_le`: Hall's marriage theorem for a perfect matching on a
bipartite graph.
## Tags
Hall's Marriage Theorem
-/
open Function
namespace SimpleGraph
variable {V : Type*} {G : SimpleGraph V}
/- Given a partition `p` and a function `f` mapping vertices in `p` to the other partition, create
the subgraph including only the edges between `x` and `f x` for all `x` in `p`. -/
private
abbrev hall_subgraph {p : Set V} [DecidablePred (· ∈ p)] (f : p → V) (h₁ : ∀ x : p, f x ∉ p)
(h₂ : ∀ x : p, G.Adj x (f x)) : Subgraph G where
verts := p ∪ Set.range f
Adj v w :=
if h : v ∈ p then f ⟨v, h⟩ = w
else if h : w ∈ p then f ⟨w, h⟩ = v
else False
adj_sub {v w} h := by
repeat' split at h
· exact h ▸ h₂ ⟨v, by assumption⟩
· exact h ▸ h₂ ⟨w, by assumption⟩ |>.symm
· contradiction
edge_vert {v w} := by grind
symm {x y} := by grind
variable [DecidableEq V] [G.LocallyFinite] {p₁ p₂ : Set V}
/-- This is the version of **Hall's marriage theorem** for bipartite graphs that finds a matching
for a single partition given that the neighborhood-condition only holds for elements of that
partition. -/
theorem exists_isMatching_of_forall_ncard_le [DecidablePred (· ∈ p₁)] (h₁ : G.IsBipartiteWith p₁ p₂)
(h₂ : ∀ s ⊆ p₁, s.ncard ≤ (⋃ x ∈ s, G.neighborSet x).ncard) :
∃ M : Subgraph G, p₁ ⊆ M.verts ∧ M.IsMatching := by
obtain ⟨f, hf₁, hf₂⟩ := Finset.all_card_le_biUnion_card_iff_exists_injective
(fun (x : p₁) ↦ G.neighborFinset x) |>.mp fun s ↦ by
have := h₂ (s.image Subtype.val) (by simp)
rw [Set.ncard_coe_finset, Finset.card_image_of_injective _ Subtype.val_injective] at this
simpa [← Set.ncard_coe_finset, neighborFinset_def]
have (x : p₁) : f x ∉ p₁ := h₁.disjoint |>.notMem_of_mem_right <|
isBipartiteWith_neighborSet_subset h₁ x.2 <| Set.mem_toFinset.mp <| hf₂ x
use hall_subgraph f this (fun v ↦ G.mem_neighborFinset _ _ |>.mp <| hf₂ v)
refine ⟨by simp, fun v hv ↦ ?_⟩
simp only [Set.mem_union, Set.mem_range, Subtype.exists] at hv ⊢
rcases hv with h' | ⟨x, hx₁, hx₂⟩
· exact ⟨f ⟨v, h'⟩, by simp_all⟩
· use x
have := hx₂ ▸ this ⟨x, hx₁⟩
simp only [this, ↓reduceDIte, hx₁, hx₂, dite_else_false, forall_exists_index, true_and]
exact fun _ _ k ↦ Subtype.ext_iff.mp <| hf₁ (hx₂ ▸ k)
lemma union_eq_univ_of_forall_ncard_le (h₁ : G.IsBipartiteWith p₁ p₂)
(h₂ : ∀ s : Set V, s.ncard ≤ (⋃ x ∈ s, G.neighborSet x).ncard) : p₁ ∪ p₂ = Set.univ := by
obtain ⟨f, _, hf₂⟩ := Finset.all_card_le_biUnion_card_iff_exists_injective
(fun x ↦ G.neighborFinset x) |>.mp fun s ↦ by
have := h₂ s
simpa [← Set.ncard_coe_finset, neighborFinset_def]
refine Set.eq_univ_iff_forall.mpr fun x ↦ ?_
have := h₁.mem_of_adj <| G.mem_neighborFinset _ _ |>.mp (hf₂ x)
grind
lemma exists_bijective_of_forall_ncard_le (h₁ : G.IsBipartiteWith p₁ p₂)
(h₂ : ∀ s : Set V, s.ncard ≤ (⋃ x ∈ s, G.neighborSet x).ncard) :
∃ (h : p₁ → p₂), Function.Bijective h ∧ ∀ (a : p₁), G.Adj a (h a) := by
obtain ⟨f, hf₁, hf₂⟩ := Finset.all_card_le_biUnion_card_iff_exists_injective
(fun x ↦ G.neighborFinset x) |>.mp fun s ↦ by
have := h₂ s
simpa [← Set.ncard_coe_finset, neighborFinset_def]
have (x : V) (h : x ∈ p₁) : f x ∉ p₁ := h₁.disjoint |>.notMem_of_mem_right <|
isBipartiteWith_neighborSet_subset h₁ h <| Set.mem_toFinset.mp <| hf₂ x
have (x : V) (h : x ∈ p₂) : f x ∉ p₂ := h₁.disjoint |>.notMem_of_mem_left <|
isBipartiteWith_neighborSet_subset h₁.symm h <| Set.mem_toFinset.mp <| hf₂ x
have (x : V) : f x ∈ p₁ ∨ f x ∈ p₂ := by
simp [union_eq_univ_of_forall_ncard_le h₁ h₂, p₁.mem_union (f x) p₂ |>.mp]
let f' (x : p₁) : p₂ := ⟨f x, by grind⟩
let g' (x : p₂) : p₁ := ⟨f x, by grind⟩
refine Embedding.schroeder_bernstein_of_rel (f := f') (g := g') ?_ ?_ (fun x y ↦ G.Adj x y) ?_ ?_
· exact Injective.of_comp (f := Subtype.val) <| hf₁.comp Subtype.val_injective
· exact Injective.of_comp (f := Subtype.val) <| hf₁.comp Subtype.val_injective
· exact fun v ↦ mem_neighborFinset _ _ _ |>.mp (hf₂ v)
· exact fun v ↦ mem_neighborFinset _ _ _ |>.mp (hf₂ v) |>.symm
/-- This is the version of **Hall's marriage theorem** for bipartite graphs that finds a perfect
matching given that the neighborhood-condition holds globally. -/
theorem exists_isPerfectMatching_of_forall_ncard_le [DecidablePred (· ∈ p₁)]
(h₁ : G.IsBipartiteWith p₁ p₂) (h₂ : ∀ s : Set V, s.ncard ≤ (⋃ x ∈ s, G.neighborSet x).ncard) :
∃ M : Subgraph G, M.IsPerfectMatching := by
obtain ⟨b, hb₁, hb₂⟩ := exists_bijective_of_forall_ncard_le h₁ h₂
use hall_subgraph (fun v ↦ b v) (fun v ↦ h₁.disjoint.notMem_of_mem_right (b v).property) hb₂
have : p₁ ∪ Set.range (fun v ↦ (b v).1) = Set.univ := by
rw [Set.range_comp', hb₁.surjective.range_eq, Subtype.coe_image_univ]
exact union_eq_univ_of_forall_ncard_le h₁ h₂
refine ⟨fun v _ ↦ ?_, Subgraph.isSpanning_iff.mpr this⟩
simp only [dite_else_false]
split
· exact existsUnique_eq'
· obtain ⟨x, _⟩ := hb₁.existsUnique ⟨v, by grind⟩
exact ⟨x, by grind⟩
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Path.lean | import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected
import Mathlib.Combinatorics.SimpleGraph.Paths
deprecated_module (since := "2025-06-13") |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/StronglyRegular.lean | import Mathlib.Combinatorics.Enumerative.DoubleCounting
import Mathlib.Combinatorics.SimpleGraph.AdjMatrix
/-!
# Strongly regular graphs
## Main definitions
* `G.IsSRGWith n k ℓ μ` (see `SimpleGraph.IsSRGWith`) is a structure for
a `SimpleGraph` satisfying the following conditions:
* The cardinality of the vertex set is `n`
* `G` is a regular graph with degree `k`
* The number of common neighbors between any two adjacent vertices in `G` is `ℓ`
* The number of common neighbors between any two nonadjacent vertices in `G` is `μ`
## Main theorems
* `IsSRGWith.compl`: the complement of a strongly regular graph is strongly regular.
* `IsSRGWith.param_eq`: `k * (k - ℓ - 1) = (n - k - 1) * μ` when `0 < n`.
* `IsSRGWith.matrix_eq`: let `A` and `C` be `G`'s and `Gᶜ`'s adjacency matrices respectively and
`I` be the identity matrix, then `A ^ 2 = k • I + ℓ • A + μ • C`.
-/
open Finset
universe u
namespace SimpleGraph
variable {V : Type u} [Fintype V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]
/-- A graph is strongly regular with parameters `n k ℓ μ` if
* its vertex set has cardinality `n`
* it is regular with degree `k`
* every pair of adjacent vertices has `ℓ` common neighbors
* every pair of nonadjacent vertices has `μ` common neighbors
-/
structure IsSRGWith (n k ℓ μ : ℕ) : Prop where
card : Fintype.card V = n
regular : G.IsRegularOfDegree k
of_adj : ∀ v w, G.Adj v w → Fintype.card (G.commonNeighbors v w) = ℓ
of_not_adj : Pairwise fun v w ↦ ¬G.Adj v w → Fintype.card (G.commonNeighbors v w) = μ
variable {G} {n k ℓ μ : ℕ}
/-- Empty graphs are strongly regular. Note that `ℓ` can take any value
for empty graphs, since there are no pairs of adjacent vertices. -/
theorem bot_strongly_regular : (⊥ : SimpleGraph V).IsSRGWith (Fintype.card V) 0 ℓ 0 where
card := rfl
regular := bot_degree
of_adj _ _ h := h.elim
of_not_adj v w _ := by
simp only [card_eq_zero, Fintype.card_ofFinset, forall_true_left, not_false_iff, bot_adj]
ext
simp [mem_commonNeighbors]
/-- **Conway's 99-graph problem** (from https://oeis.org/A248380/a248380.pdf)
can be reformulated as the existence of a strongly regular graph with params (99, 14, 1, 2).
This is an open problem, and has no known proof of existence. -/
proof_wanted conway_99 : ∃ α : Type*, ∃ (g : SimpleGraph α), IsSRGWith G 99 14 1 2
variable [DecidableEq V]
/-- Complete graphs are strongly regular. Note that `μ` can take any value
for complete graphs, since there are no distinct pairs of non-adjacent vertices. -/
theorem IsSRGWith.top :
(⊤ : SimpleGraph V).IsSRGWith (Fintype.card V) (Fintype.card V - 1) (Fintype.card V - 2) μ where
card := rfl
regular := IsRegularOfDegree.top
of_adj _ _ := card_commonNeighbors_top
of_not_adj v w h h' := (h' ((top_adj v w).2 h)).elim
theorem IsSRGWith.card_neighborFinset_union_eq {v w : V} (h : G.IsSRGWith n k ℓ μ) :
#(G.neighborFinset v ∪ G.neighborFinset w) =
2 * k - Fintype.card (G.commonNeighbors v w) := by
apply Nat.add_right_cancel (m := Fintype.card (G.commonNeighbors v w))
rw [Nat.sub_add_cancel, ← Set.toFinset_card]
· simp [commonNeighbors, ← neighborFinset_def, Finset.card_union_add_card_inter,
h.regular.degree_eq, two_mul]
· apply le_trans (card_commonNeighbors_le_degree_left _ _ _)
simp [h.regular.degree_eq, two_mul]
/-- Assuming `G` is strongly regular, `2*(k + 1) - m` in `G` is the number of vertices that are
adjacent to either `v` or `w` when `¬G.Adj v w`. So it's the cardinality of
`G.neighborSet v ∪ G.neighborSet w`. -/
theorem IsSRGWith.card_neighborFinset_union_of_not_adj {v w : V} (h : G.IsSRGWith n k ℓ μ)
(hne : v ≠ w) (ha : ¬G.Adj v w) :
#(G.neighborFinset v ∪ G.neighborFinset w) = 2 * k - μ := by
rw [← h.of_not_adj hne ha]
exact h.card_neighborFinset_union_eq
theorem IsSRGWith.card_neighborFinset_union_of_adj {v w : V} (h : G.IsSRGWith n k ℓ μ)
(ha : G.Adj v w) : #(G.neighborFinset v ∪ G.neighborFinset w) = 2 * k - ℓ := by
rw [← h.of_adj v w ha]
exact h.card_neighborFinset_union_eq
theorem compl_neighborFinset_sdiff_inter_eq {v w : V} :
(G.neighborFinset v)ᶜ \ {v} ∩ ((G.neighborFinset w)ᶜ \ {w}) =
((G.neighborFinset v)ᶜ ∩ (G.neighborFinset w)ᶜ) \ ({w} ∪ {v}) := by
grind
theorem sdiff_compl_neighborFinset_inter_eq {v w : V} (h : G.Adj v w) :
((G.neighborFinset v)ᶜ ∩ (G.neighborFinset w)ᶜ) \ ({w} ∪ {v}) =
(G.neighborFinset v)ᶜ ∩ (G.neighborFinset w)ᶜ := by
ext
simp only [and_imp, mem_union, mem_sdiff, mem_compl, and_iff_left_iff_imp, mem_neighborFinset,
mem_inter, mem_singleton]
rintro hnv hnw (rfl | rfl)
· exact hnv h
· apply hnw
rwa [adj_comm]
theorem IsSRGWith.compl_is_regular (h : G.IsSRGWith n k ℓ μ) :
Gᶜ.IsRegularOfDegree (n - k - 1) := by
rw [← h.card, Nat.sub_sub, add_comm, ← Nat.sub_sub]
exact h.regular.compl
theorem IsSRGWith.card_commonNeighbors_eq_of_adj_compl (h : G.IsSRGWith n k ℓ μ) {v w : V}
(ha : Gᶜ.Adj v w) : Fintype.card (Gᶜ.commonNeighbors v w) = n - (2 * k - μ) - 2 := by
simp only [← Set.toFinset_card, commonNeighbors, Set.toFinset_inter, neighborSet_compl,
Set.toFinset_diff, Set.toFinset_singleton, Set.toFinset_compl, ← neighborFinset_def]
simp_rw [compl_neighborFinset_sdiff_inter_eq]
have hne : v ≠ w := ne_of_adj _ ha
rw [compl_adj] at ha
rw [card_sdiff_of_subset, ← insert_eq, card_insert_of_notMem, card_singleton,
← Finset.compl_union]
· rw [card_compl, h.card_neighborFinset_union_of_not_adj hne ha.2, ← h.card]
· simp only [hne.symm, not_false_iff, mem_singleton]
· intro u
simp only [mem_union, mem_compl, mem_neighborFinset, mem_inter, mem_singleton]
rintro (rfl | rfl) <;> simpa [adj_comm] using ha.2
theorem IsSRGWith.card_commonNeighbors_eq_of_not_adj_compl (h : G.IsSRGWith n k ℓ μ) {v w : V}
(hn : v ≠ w) (hna : ¬Gᶜ.Adj v w) :
Fintype.card (Gᶜ.commonNeighbors v w) = n - (2 * k - ℓ) := by
simp only [← Set.toFinset_card, commonNeighbors, Set.toFinset_inter, neighborSet_compl,
Set.toFinset_diff, Set.toFinset_singleton, Set.toFinset_compl, ← neighborFinset_def]
simp only [not_and, Classical.not_not, compl_adj] at hna
have h2' := hna hn
simp_rw [compl_neighborFinset_sdiff_inter_eq, sdiff_compl_neighborFinset_inter_eq h2']
rwa [← Finset.compl_union, card_compl, h.card_neighborFinset_union_of_adj, ← h.card]
/-- The complement of a strongly regular graph is strongly regular. -/
theorem IsSRGWith.compl (h : G.IsSRGWith n k ℓ μ) :
Gᶜ.IsSRGWith n (n - k - 1) (n - (2 * k - μ) - 2) (n - (2 * k - ℓ)) where
card := h.card
regular := h.compl_is_regular
of_adj _ _ := h.card_commonNeighbors_eq_of_adj_compl
of_not_adj _ _ := h.card_commonNeighbors_eq_of_not_adj_compl
/-- The parameters of a strongly regular graph with at least one vertex satisfy
`k * (k - ℓ - 1) = (n - k - 1) * μ`. -/
theorem IsSRGWith.param_eq
{V : Type u} [Fintype V] (G : SimpleGraph V) [DecidableRel G.Adj]
(h : G.IsSRGWith n k ℓ μ) (hn : 0 < n) :
k * (k - ℓ - 1) = (n - k - 1) * μ := by
letI := Classical.decEq V
rw [← h.card, Fintype.card_pos_iff] at hn
obtain ⟨v⟩ := hn
convert card_mul_eq_card_mul G.Adj (s := G.neighborFinset v) (t := Gᶜ.neighborFinset v) _ _
· simp [h.regular v]
· simp [h.compl.regular v]
· intro w hw
rw [mem_neighborFinset] at hw
simp_rw [bipartiteAbove, ← mem_neighborFinset, filter_mem_eq_inter]
have s : {v} ⊆ G.neighborFinset w \ G.neighborFinset v := by
rw [singleton_subset_iff, mem_sdiff, mem_neighborFinset]
exact ⟨hw.symm, G.notMem_neighborFinset_self v⟩
rw [inter_comm, neighborFinset_compl, ← inter_sdiff_assoc, ← sdiff_eq_inter_compl,
card_sdiff_of_subset s, card_singleton, ← sdiff_inter_self_left,
card_sdiff_of_subset inter_subset_left]
congr
· simp [h.regular w]
· simp_rw [inter_comm, neighborFinset_def, ← Set.toFinset_inter, ← h.of_adj v w hw,
← Set.toFinset_card]
congr!
· intro w hw
simp_rw [neighborFinset_compl, mem_sdiff, mem_compl, mem_singleton, mem_neighborFinset,
← Ne.eq_def] at hw
simp_rw [bipartiteBelow, adj_comm, ← mem_neighborFinset, filter_mem_eq_inter,
neighborFinset_def, ← Set.toFinset_inter, ← h.of_not_adj hw.2.symm hw.1,
← Set.toFinset_card]
congr!
/-- Let `A` and `C` be the adjacency matrices of a strongly regular graph with parameters `n k ℓ μ`
and its complement respectively and `I` be the identity matrix,
then `A ^ 2 = k • I + ℓ • A + μ • C`. `C` is equivalent to the expression `J - I - A`
more often found in the literature, where `J` is the all-ones matrix. -/
theorem IsSRGWith.matrix_eq {α : Type*} [Semiring α] (h : G.IsSRGWith n k ℓ μ) :
G.adjMatrix α ^ 2 = k • (1 : Matrix V V α) + ℓ • G.adjMatrix α + μ • Gᶜ.adjMatrix α := by
ext v w
simp only [adjMatrix_pow_apply_eq_card_walk, Set.coe_setOf, Matrix.add_apply, Matrix.smul_apply,
adjMatrix_apply, compl_adj]
rw [Fintype.card_congr (G.walkLengthTwoEquivCommonNeighbors v w)]
obtain rfl | hn := eq_or_ne v w
· rw [← Set.toFinset_card]
simp [commonNeighbors, ← neighborFinset_def, h.regular v]
· simp only [Matrix.one_apply_ne' hn.symm, ne_eq, hn]
by_cases ha : G.Adj v w <;>
simp only [ha, ite_true, ite_false, add_zero, zero_add, nsmul_eq_mul, smul_zero, mul_one,
not_true_eq_false, not_false_eq_true, and_false, and_self]
· rw [h.of_adj v w ha]
· rw [h.of_not_adj hn ha]
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Diam.lean | import Mathlib.Combinatorics.SimpleGraph.Metric
/-!
# Diameter of a simple graph
This module defines the eccentricity of vertices, the diameter, and the radius of a simple graph.
## Main definitions
- `SimpleGraph.eccent`: the eccentricity of a vertex in a simple graph, which is the maximum
distances between it and the other vertices.
- `SimpleGraph.ediam`: the graph extended diameter, which is the maximum eccentricity.
It is `ℕ∞`-valued.
- `SimpleGraph.diam`: the graph diameter, an `ℕ`-valued version of `SimpleGraph.ediam`.
- `SimpleGraph.radius`: the graph radius, which is the minimum eccentricity. It is `ℕ∞`-valued.
- `SimpleGraph.center`: the set of vertices with eccentricity equal to the graph's radius.
-/
assert_not_exists Field
namespace SimpleGraph
variable {α : Type*} {G G' : SimpleGraph α}
section eccent
/-- The eccentricity of a vertex is the greatest distance between it and any other vertex. -/
noncomputable def eccent (G : SimpleGraph α) (u : α) : ℕ∞ :=
⨆ v, G.edist u v
lemma eccent_def : G.eccent = fun u ↦ ⨆ v, G.edist u v := rfl
lemma edist_le_eccent {u v : α} : G.edist u v ≤ G.eccent u :=
le_iSup (G.edist u) v
lemma exists_edist_eq_eccent_of_finite [Finite α] (u : α) :
∃ v, G.edist u v = G.eccent u :=
have : Nonempty α := Nonempty.intro u
exists_eq_ciSup_of_finite
lemma eccent_eq_top_of_not_connected (h : ¬ G.Connected) (u : α) :
G.eccent u = ⊤ := by
rw [connected_iff_exists_forall_reachable] at h
push_neg at h
obtain ⟨v, h⟩ := h u
rw [eq_top_iff, ← edist_eq_top_of_not_reachable h]
exact le_iSup (G.edist u) v
lemma eccent_eq_zero_of_subsingleton [Subsingleton α] (u : α) : G.eccent u = 0 := by
simpa [eccent, edist_eq_zero_iff] using subsingleton_iff.mp ‹_› u
lemma eccent_ne_zero [Nontrivial α] (u : α) : G.eccent u ≠ 0 := by
obtain ⟨v, huv⟩ := exists_ne ‹_›
contrapose! huv
simp only [eccent, ENat.iSup_eq_zero, edist_eq_zero_iff] at huv
exact (huv v).symm
lemma eccent_eq_zero_iff (u : α) : G.eccent u = 0 ↔ Subsingleton α := by
refine ⟨fun h ↦ ?_, fun _ ↦ eccent_eq_zero_of_subsingleton u⟩
contrapose! h
exact eccent_ne_zero u
lemma eccent_pos_iff (u : α) : 0 < G.eccent u ↔ Nontrivial α := by
rw [pos_iff_ne_zero, ← not_subsingleton_iff_nontrivial, ← eccent_eq_zero_iff]
@[simp]
lemma eccent_bot [Nontrivial α] (u : α) : (⊥ : SimpleGraph α).eccent u = ⊤ :=
eccent_eq_top_of_not_connected not_connected_bot u
@[simp]
lemma eccent_top [Nontrivial α] (u : α) : (⊤ : SimpleGraph α).eccent u = 1 := by
apply le_antisymm ?_ <| Order.one_le_iff_pos.mpr <| pos_iff_ne_zero.mpr <| eccent_ne_zero u
rw [eccent, iSup_le_iff]
intro v
cases eq_or_ne u v <;> simp_all [edist_top_of_ne]
lemma eq_top_iff_forall_eccent_eq_one [Nontrivial α] :
G = ⊤ ↔ ∀ u, G.eccent u = 1 := by
refine ⟨fun h ↦ h ▸ eccent_top, fun h ↦ ?_⟩
ext u v
refine ⟨Adj.ne, fun huv ↦ ?_⟩
rw [← edist_eq_one_iff_adj]
apply le_antisymm ((h u).symm ▸ edist_le_eccent)
rw [Order.one_le_iff_pos, pos_iff_ne_zero, edist_eq_zero_iff.ne]
exact huv.ne
end eccent
section ediam
/--
The extended diameter is the greatest distance between any two vertices, with the value `⊤` in
case the distances are not bounded above, or the graph is not connected.
-/
noncomputable def ediam (G : SimpleGraph α) : ℕ∞ :=
⨆ u, G.eccent u
lemma ediam_eq_iSup_iSup_edist : G.ediam = ⨆ u, ⨆ v, G.edist u v :=
rfl
lemma ediam_def : G.ediam = ⨆ p : α × α, G.edist p.1 p.2 := by
rw [ediam, eccent_def, iSup_prod]
lemma eccent_le_ediam {u : α} : G.eccent u ≤ G.ediam :=
le_iSup G.eccent u
lemma edist_le_ediam {u v : α} : G.edist u v ≤ G.ediam :=
le_iSup₂ (f := G.edist) u v
lemma ediam_le_of_edist_le {k : ℕ∞} (h : ∀ u v, G.edist u v ≤ k) : G.ediam ≤ k :=
iSup₂_le h
lemma ediam_le_iff {k : ℕ∞} : G.ediam ≤ k ↔ ∀ u v, G.edist u v ≤ k :=
iSup₂_le_iff
lemma ediam_eq_top : G.ediam = ⊤ ↔ ∀ b < ⊤, ∃ u v, b < G.edist u v := by
simp only [ediam, eccent, iSup_eq_top, lt_iSup_iff]
lemma ediam_eq_zero_of_subsingleton [Subsingleton α] : G.ediam = 0 := by
rw [ediam_def, ENat.iSup_eq_zero]
simpa [edist_eq_zero_iff, Prod.forall] using subsingleton_iff.mp ‹_›
lemma nontrivial_of_ediam_ne_zero (h : G.ediam ≠ 0) : Nontrivial α := by
contrapose! h
exact ediam_eq_zero_of_subsingleton
lemma ediam_ne_zero [Nontrivial α] : G.ediam ≠ 0 := by
obtain ⟨u, v, huv⟩ := exists_pair_ne ‹_›
contrapose! huv
simp only [ediam, eccent, ENat.iSup_eq_zero, edist_eq_zero_iff] at huv
exact huv u v
lemma subsingleton_of_ediam_eq_zero (h : G.ediam = 0) : Subsingleton α := by
contrapose! h
exact ediam_ne_zero
lemma ediam_ne_zero_iff_nontrivial :
G.ediam ≠ 0 ↔ Nontrivial α :=
⟨nontrivial_of_ediam_ne_zero, fun _ ↦ ediam_ne_zero⟩
@[simp]
lemma ediam_eq_zero_iff_subsingleton :
G.ediam = 0 ↔ Subsingleton α :=
⟨subsingleton_of_ediam_eq_zero, fun _ ↦ ediam_eq_zero_of_subsingleton⟩
lemma ediam_eq_top_of_not_connected [Nonempty α] (h : ¬ G.Connected) : G.ediam = ⊤ := by
rw [connected_iff_exists_forall_reachable] at h
push_neg at h
obtain ⟨_, hw⟩ := h Classical.ofNonempty
rw [eq_top_iff, ← edist_eq_top_of_not_reachable hw]
exact edist_le_ediam
lemma ediam_eq_top_of_not_preconnected (h : ¬ G.Preconnected) : G.ediam = ⊤ := by
cases isEmpty_or_nonempty α
· exfalso
exact h <| IsEmpty.forall_iff.mpr trivial
· apply ediam_eq_top_of_not_connected
rw [connected_iff]
tauto
lemma preconnected_of_ediam_ne_top (h : G.ediam ≠ ⊤) : G.Preconnected :=
Not.imp_symm G.ediam_eq_top_of_not_preconnected h
lemma connected_of_ediam_ne_top [Nonempty α] (h : G.ediam ≠ ⊤) : G.Connected :=
G.connected_iff.mpr ⟨preconnected_of_ediam_ne_top h, ‹_›⟩
lemma exists_eccent_eq_ediam_of_ne_top [Nonempty α] (h : G.ediam ≠ ⊤) :
∃ u, G.eccent u = G.ediam :=
ENat.exists_eq_iSup_of_lt_top h.lt_top
-- Note: Neither `Finite α` nor `G.ediam ≠ ⊤` implies the other.
lemma exists_eccent_eq_ediam_of_finite [Nonempty α] [Finite α] :
∃ u, G.eccent u = G.ediam :=
exists_eq_ciSup_of_finite
lemma exists_edist_eq_ediam_of_ne_top [Nonempty α] (h : G.ediam ≠ ⊤) :
∃ u v, G.edist u v = G.ediam :=
ENat.exists_eq_iSup₂_of_lt_top h.lt_top
-- Note: Neither `Finite α` nor `G.ediam ≠ ⊤` implies the other.
lemma exists_edist_eq_ediam_of_finite [Nonempty α] [Finite α] :
∃ u v, G.edist u v = G.ediam :=
Prod.exists'.mp <| ediam_def ▸ exists_eq_ciSup_of_finite
/-- In a finite graph with nontrivial vertex set, the graph is connected
if and only if the extended diameter is not `⊤`.
See `connected_of_ediam_ne_top` for one of the implications without
the finiteness assumptions -/
lemma connected_iff_ediam_ne_top [Nonempty α] [Finite α] : G.Connected ↔ G.ediam ≠ ⊤ :=
have ⟨u, v, huv⟩ := G.exists_edist_eq_ediam_of_finite
⟨fun h ↦ huv ▸ edist_ne_top_iff_reachable.mpr (h u v),
fun h ↦ G.connected_of_ediam_ne_top h⟩
@[gcongr]
lemma ediam_anti (h : G ≤ G') : G'.ediam ≤ G.ediam :=
iSup₂_mono fun _ _ ↦ edist_anti h
@[simp]
lemma ediam_bot [Nontrivial α] : (⊥ : SimpleGraph α).ediam = ⊤ :=
ediam_eq_top_of_not_connected not_connected_bot
@[simp]
lemma ediam_top [Nontrivial α] : (⊤ : SimpleGraph α).ediam = 1 := by
simp [ediam]
@[simp]
lemma ediam_eq_one [Nontrivial α] : G.ediam = 1 ↔ G = ⊤ := by
refine ⟨fun h ↦ ?_, fun h ↦ h ▸ ediam_top⟩
rw [eq_top_iff_forall_eccent_eq_one]
intro u
apply le_antisymm (h ▸ eccent_le_ediam)
rw [Order.one_le_iff_pos, pos_iff_ne_zero]
exact eccent_ne_zero u
end ediam
section diam
/--
The diameter is the greatest distance between any two vertices, with the value `0` in
case the distances are not bounded above, or the graph is not connected.
-/
noncomputable def diam (G : SimpleGraph α) :=
G.ediam.toNat
lemma diam_def : G.diam = (⨆ p : α × α, G.edist p.1 p.2).toNat := by
rw [diam, ediam_def]
lemma dist_le_diam (h : G.ediam ≠ ⊤) {u v : α} : G.dist u v ≤ G.diam :=
ENat.toNat_le_toNat edist_le_ediam h
lemma nontrivial_of_diam_ne_zero (h : G.diam ≠ 0) : Nontrivial α := by
apply G.nontrivial_of_ediam_ne_zero
contrapose! h
simp [diam, h]
lemma diam_eq_zero_of_not_connected (h : ¬ G.Connected) : G.diam = 0 := by
cases isEmpty_or_nonempty α
· rw [diam, ediam, ciSup_of_empty, bot_eq_zero']; rfl
· rw [diam, ediam_eq_top_of_not_connected h, ENat.toNat_top]
lemma diam_eq_zero_of_ediam_eq_top (h : G.ediam = ⊤) : G.diam = 0 := by
rw [diam, h, ENat.toNat_top]
lemma ediam_ne_top_of_diam_ne_zero (h : G.diam ≠ 0) : G.ediam ≠ ⊤ :=
mt diam_eq_zero_of_ediam_eq_top h
lemma exists_dist_eq_diam [Nonempty α] :
∃ u v, G.dist u v = G.diam := by
by_cases h : G.diam = 0
· simp [h]
· obtain ⟨u, v, huv⟩ := exists_edist_eq_ediam_of_ne_top <| ediam_ne_top_of_diam_ne_zero h
use u, v
rw [diam, dist, congrArg ENat.toNat huv]
lemma diam_ne_zero_of_ediam_ne_top [Nontrivial α] (h : G.ediam ≠ ⊤) : G.diam ≠ 0 :=
have ⟨_, _, hne⟩ := exists_pair_ne ‹_›
pos_iff_ne_zero.mp <|
lt_of_lt_of_le ((connected_of_ediam_ne_top h).pos_dist_of_ne hne) <| dist_le_diam h
@[gcongr]
lemma diam_anti_of_ediam_ne_top (h : G ≤ G') (hn : G.ediam ≠ ⊤) : G'.diam ≤ G.diam :=
ENat.toNat_le_toNat (ediam_anti h) hn
@[simp]
lemma diam_bot : (⊥ : SimpleGraph α).diam = 0 := by
rw [diam, ENat.toNat_eq_zero]
cases subsingleton_or_nontrivial α
· exact Or.inl ediam_eq_zero_of_subsingleton
· exact Or.inr ediam_bot
@[simp]
lemma diam_top [Nontrivial α] : (⊤ : SimpleGraph α).diam = 1 := by
rw [diam, ediam_top, ENat.toNat_one]
@[simp]
lemma diam_eq_zero : G.diam = 0 ↔ G.ediam = ⊤ ∨ Subsingleton α := by
rw [diam, ENat.toNat_eq_zero, or_comm, ediam_eq_zero_iff_subsingleton]
@[simp]
lemma diam_eq_one [Nontrivial α] : G.diam = 1 ↔ G = ⊤ := by
rw [diam, ENat.toNat_eq_iff one_ne_zero, Nat.cast_one, ediam_eq_one]
lemma diam_eq_zero_iff_ediam_eq_top [Nontrivial α] : G.diam = 0 ↔ G.ediam = ⊤ := by
rw [← not_iff_not]
exact ⟨ediam_ne_top_of_diam_ne_zero, diam_ne_zero_of_ediam_ne_top⟩
/-- A finite and nontrivial graph is connected if and only if its diameter is not zero.
See also `connected_iff_ediam_ne_top` for the extended diameter version. -/
lemma connected_iff_diam_ne_zero [Finite α] [Nontrivial α] : G.Connected ↔ G.diam ≠ 0 := by
rw [connected_iff_ediam_ne_top, not_iff_not, diam_eq_zero_iff_ediam_eq_top]
end diam
section radius
/-- The radius of a simple graph is the minimum eccentricity of any vertex. -/
noncomputable def radius (G : SimpleGraph α) : ℕ∞ :=
⨅ u, G.eccent u
lemma radius_eq_iInf_iSup_edist : G.radius = ⨅ u, ⨆ v, G.edist u v :=
rfl
lemma radius_le_eccent {u : α} : G.radius ≤ G.eccent u :=
iInf_le G.eccent u
lemma exists_eccent_eq_radius [Nonempty α] : ∃ u, G.eccent u = G.radius :=
ENat.exists_eq_iInf G.eccent
lemma exists_edist_eq_radius_of_finite [Nonempty α] [Finite α] :
∃ u v, G.edist u v = G.radius := by
obtain ⟨w, hw⟩ := G.exists_eccent_eq_radius
obtain ⟨v, hv⟩ := G.exists_edist_eq_eccent_of_finite w
use w, v
rw [hv, hw]
lemma radius_eq_top_of_not_connected (h : ¬ G.Connected) : G.radius = ⊤ := by
simp [radius, eccent_eq_top_of_not_connected h]
lemma radius_eq_top_of_isEmpty [IsEmpty α] : G.radius = ⊤ :=
iInf_of_empty G.eccent
lemma radius_ne_top_iff [Nonempty α] [Finite α] : G.radius ≠ ⊤ ↔ G.Connected := by
refine ⟨Not.imp_symm radius_eq_top_of_not_connected, fun h ↦ ?_⟩
obtain ⟨u, v, huv⟩ := G.exists_edist_eq_radius_of_finite
rw [← huv, edist_ne_top_iff_reachable]
exact h u v
lemma radius_ne_zero_of_nontrivial [Nontrivial α] : G.radius ≠ 0 := by
rw [← ENat.one_le_iff_ne_zero]
apply le_iInf
simp [ENat.one_le_iff_ne_zero, G.eccent_ne_zero]
lemma radius_eq_zero_iff : G.radius = 0 ↔ Nonempty α ∧ Subsingleton α := by
refine ⟨fun h ↦ ⟨?_, ?_⟩, fun ⟨_, _⟩ ↦ ?_⟩
· contrapose! h
simp [radius]
· contrapose! h
simp [radius_ne_zero_of_nontrivial]
· rw [radius, ENat.iInf_eq_zero]
use Classical.ofNonempty
simpa [eccent] using Subsingleton.elim _
lemma radius_le_ediam [Nonempty α] : G.radius ≤ G.ediam :=
iInf_le_iSup
lemma ediam_le_two_mul_radius [Finite α] : G.ediam ≤ 2 * G.radius := by
cases isEmpty_or_nonempty α
· rw [radius_eq_top_of_isEmpty]
exact le_top
· by_cases h : G.Connected
· obtain ⟨w, hw⟩ := G.exists_eccent_eq_radius
obtain ⟨_, _, h⟩ := G.exists_edist_eq_ediam_of_ne_top (connected_iff_ediam_ne_top.mp h)
apply le_trans (h ▸ G.edist_triangle (v := w))
rw [two_mul]
exact hw ▸ add_le_add (G.edist_comm ▸ G.edist_le_eccent) G.edist_le_eccent
· rw [G.radius_eq_top_of_not_connected h]
exact le_top
lemma radius_eq_ediam_iff [Nonempty α] :
G.radius = G.ediam ↔ ∃ e, ∀ u, G.eccent u = e := by
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· use G.radius
intro u
exact le_antisymm (h ▸ eccent_le_ediam) radius_le_eccent
· obtain ⟨e, h⟩ := h
have ediam_eq : G.ediam = e :=
le_antisymm (iSup_le fun u ↦ (h u).le) ((h Classical.ofNonempty) ▸ eccent_le_ediam)
rw [ediam_eq]
exact le_antisymm ((h Classical.ofNonempty) ▸ radius_le_eccent) (le_iInf fun u ↦ (h u).ge)
@[simp]
lemma radius_bot [Nontrivial α] : (⊥ : SimpleGraph α).radius = ⊤ :=
radius_eq_top_of_not_connected not_connected_bot
@[simp]
lemma radius_top [Nontrivial α] : (⊤ : SimpleGraph α).radius = 1 := by
simp [radius]
end radius
section center
/-- The center of a simple graph is the set of vertices with eccentricity equal to the radius. -/
def center (G : SimpleGraph α) : Set α :=
{u | G.eccent u = G.radius}
lemma center_nonempty [Nonempty α] : G.center.Nonempty :=
exists_eccent_eq_radius
lemma mem_center_iff (u : α) : u ∈ G.center ↔ G.eccent u = G.radius := .rfl
lemma center_eq_univ_iff_radius_eq_ediam [Nonempty α] :
G.center = Set.univ ↔ G.radius = G.ediam := by
rw [radius_eq_ediam_iff, ← Set.univ_subset_iff]
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· use G.radius
exact fun _ ↦ h trivial
· obtain ⟨e, h⟩ := h
intro u hu
rw [mem_center_iff, h u]
exact le_antisymm (le_iInf fun u ↦ (h u).ge) ((h Classical.ofNonempty) ▸ radius_le_eccent)
lemma center_eq_univ_of_subsingleton [Subsingleton α] : G.center = Set.univ := by
rw [Set.eq_univ_iff_forall]
intro u
rw [mem_center_iff, eccent_eq_zero_of_subsingleton u, eq_comm, radius_eq_zero_iff]
tauto
lemma center_bot : (⊥ : SimpleGraph α).center = Set.univ := by
cases subsingleton_or_nontrivial α
· exact center_eq_univ_of_subsingleton
· rw [Set.eq_univ_iff_forall]
intro u
rw [mem_center_iff, eccent_bot, radius_bot]
lemma center_top : (⊤ : SimpleGraph α).center = Set.univ := by
cases subsingleton_or_nontrivial α
· exact center_eq_univ_of_subsingleton
· rw [Set.eq_univ_iff_forall]
intro u
rw [mem_center_iff, eccent_top, radius_top]
end center
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Hamiltonian.lean | import Mathlib.Algebra.GroupWithZero.Nat
import Mathlib.Algebra.Order.Group.Nat
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected
/-!
# Hamiltonian Graphs
In this file we introduce Hamiltonian paths, cycles and graphs.
## Main definitions
- `SimpleGraph.Walk.IsHamiltonian`: Predicate for a walk to be Hamiltonian.
- `SimpleGraph.Walk.IsHamiltonianCycle`: Predicate for a walk to be a Hamiltonian cycle.
- `SimpleGraph.IsHamiltonian`: Predicate for a graph to be Hamiltonian.
-/
open Finset Function
namespace SimpleGraph
variable {α β : Type*} [DecidableEq α] [DecidableEq β] {G : SimpleGraph α}
{a b : α} {p : G.Walk a b}
namespace Walk
/-- A Hamiltonian path is a walk `p` that visits every vertex exactly once. Note that while
this definition doesn't contain that `p` is a path, `p.isPath` gives that. -/
def IsHamiltonian (p : G.Walk a b) : Prop := ∀ a, p.support.count a = 1
lemma IsHamiltonian.map {H : SimpleGraph β} (f : G →g H) (hf : Bijective f) (hp : p.IsHamiltonian) :
(p.map f).IsHamiltonian := by
simp [IsHamiltonian, hf.surjective.forall, hf.injective, hp _]
/-- A Hamiltonian path visits every vertex. -/
@[simp] lemma IsHamiltonian.mem_support (hp : p.IsHamiltonian) (c : α) : c ∈ p.support := by
simp only [← List.count_pos_iff, hp _, Nat.zero_lt_one]
/-- Hamiltonian paths are paths. -/
lemma IsHamiltonian.isPath (hp : p.IsHamiltonian) : p.IsPath :=
IsPath.mk' <| List.nodup_iff_count_le_one.2 <| (le_of_eq <| hp ·)
/-- A path whose support contains every vertex is Hamiltonian. -/
lemma IsPath.isHamiltonian_of_mem (hp : p.IsPath) (hp' : ∀ w, w ∈ p.support) :
p.IsHamiltonian := fun _ ↦
le_antisymm (List.nodup_iff_count_le_one.1 hp.support_nodup _) (List.count_pos_iff.2 (hp' _))
lemma IsPath.isHamiltonian_iff (hp : p.IsPath) : p.IsHamiltonian ↔ ∀ w, w ∈ p.support :=
⟨(·.mem_support), hp.isHamiltonian_of_mem⟩
/-- If a path `p` is Hamiltonian then its vertex set must be finite. -/
protected def IsHamiltonian.fintype (hp : p.IsHamiltonian) : Fintype α where
elems := p.support.toFinset
complete x := List.mem_toFinset.mpr (mem_support hp x)
section
variable [Fintype α]
/-- The support of a Hamiltonian walk is the entire vertex set. -/
lemma IsHamiltonian.support_toFinset (hp : p.IsHamiltonian) : p.support.toFinset = Finset.univ := by
simp [eq_univ_iff_forall, hp]
/-- The length of a Hamiltonian path is one less than the number of vertices of the graph. -/
lemma IsHamiltonian.length_eq (hp : p.IsHamiltonian) : p.length = Fintype.card α - 1 :=
eq_tsub_of_add_eq <| by
rw [← length_support, ← List.sum_toFinset_count_eq_length, Finset.sum_congr rfl fun _ _ ↦ hp _,
← card_eq_sum_ones, hp.support_toFinset, card_univ]
/-- The length of the support of a Hamiltonian path equals the number of vertices of the graph. -/
lemma IsHamiltonian.length_support (hp : p.IsHamiltonian) : p.support.length = Fintype.card α := by
have : Inhabited α := ⟨a⟩
grind [Fintype.card_ne_zero, length_support, length_eq]
end
/-- If a path `p` is Hamiltonian, then `p.support.get` defines an equivalence between
`Fin p.support.length` and `α`. -/
@[simps!]
def IsHamiltonian.supportGetEquiv (hp : p.IsHamiltonian) : Fin p.support.length ≃ α :=
p.support.getEquivOfForallCountEqOne hp
/-- If a path `p` is Hamiltonian, then `p.getVert` defines an equivalence between
`Fin p.support.length` and `α`. -/
@[simps]
def IsHamiltonian.getVertEquiv (hp : p.IsHamiltonian) : Fin p.support.length ≃ α where
toFun := p.getVert ∘ Fin.val
invFun := hp.supportGetEquiv.invFun
left_inv := p.getVert_comp_val_eq_get_support ▸ hp.supportGetEquiv.left_inv
right_inv := p.getVert_comp_val_eq_get_support ▸ hp.supportGetEquiv.right_inv
theorem isHamiltonian_iff_support_get_bijective : p.IsHamiltonian ↔ p.support.get.Bijective :=
p.support.get_bijective_iff.symm
theorem IsHamiltonian.getVert_surjective (hp : p.IsHamiltonian) : p.getVert.Surjective :=
.of_comp <| p.getVert_comp_val_eq_get_support ▸
isHamiltonian_iff_support_get_bijective.mp hp |>.surjective
/-- A Hamiltonian cycle is a cycle that visits every vertex once. -/
structure IsHamiltonianCycle (p : G.Walk a a) : Prop extends p.IsCycle where
isHamiltonian_tail : p.tail.IsHamiltonian
variable {p : G.Walk a a}
lemma IsHamiltonianCycle.isCycle (hp : p.IsHamiltonianCycle) : p.IsCycle :=
hp.toIsCycle
lemma IsHamiltonianCycle.map {H : SimpleGraph β} (f : G →g H) (hf : Bijective f)
(hp : p.IsHamiltonianCycle) : (p.map f).IsHamiltonianCycle where
toIsCycle := hp.isCycle.map hf.injective
isHamiltonian_tail := by
simp only [IsHamiltonian, hf.surjective.forall]
intro x
rcases p with (_ | ⟨y, p⟩)
· cases hp.ne_nil rfl
simp only [map_cons, getVert_cons_succ, tail_cons, support_copy,support_map]
rw [List.count_map_of_injective _ _ hf.injective]
simpa using hp.isHamiltonian_tail x
lemma isHamiltonianCycle_isCycle_and_isHamiltonian_tail :
p.IsHamiltonianCycle ↔ p.IsCycle ∧ p.tail.IsHamiltonian :=
⟨fun ⟨h, h'⟩ ↦ ⟨h, h'⟩, fun ⟨h, h'⟩ ↦ ⟨h, h'⟩⟩
lemma isHamiltonianCycle_iff_isCycle_and_support_count_tail_eq_one :
p.IsHamiltonianCycle ↔ p.IsCycle ∧ ∀ a, (support p).tail.count a = 1 := by
simp +contextual [isHamiltonianCycle_isCycle_and_isHamiltonian_tail,
IsHamiltonian, support_tail_of_not_nil, IsCycle.not_nil]
/-- A Hamiltonian cycle visits every vertex. -/
lemma IsHamiltonianCycle.mem_support (hp : p.IsHamiltonianCycle) (b : α) :
b ∈ p.support :=
List.mem_of_mem_tail <|
support_tail_of_not_nil p hp.1.not_nil ▸ hp.isHamiltonian_tail.mem_support _
/-- The length of a Hamiltonian cycle is the number of vertices. -/
lemma IsHamiltonianCycle.length_eq [Fintype α] (hp : p.IsHamiltonianCycle) :
p.length = Fintype.card α := by
rw [← length_tail_add_one hp.not_nil, hp.isHamiltonian_tail.length_eq, Nat.sub_add_cancel]
rw [Nat.succ_le, Fintype.card_pos_iff]
exact ⟨a⟩
lemma IsHamiltonianCycle.count_support_self (hp : p.IsHamiltonianCycle) :
p.support.count a = 2 := by
rw [support_eq_cons, List.count_cons_self,
← support_tail_of_not_nil _ hp.1.not_nil, hp.isHamiltonian_tail]
lemma IsHamiltonianCycle.support_count_of_ne (hp : p.IsHamiltonianCycle) (h : a ≠ b) :
p.support.count b = 1 := by
rw [← cons_support_tail p hp.1.not_nil, List.count_cons_of_ne h, hp.isHamiltonian_tail]
end Walk
variable [Fintype α]
/-- A Hamiltonian graph is a graph that contains a Hamiltonian cycle.
By convention, the singleton graph is considered to be Hamiltonian. -/
def IsHamiltonian (G : SimpleGraph α) : Prop :=
Fintype.card α ≠ 1 → ∃ a, ∃ p : G.Walk a a, p.IsHamiltonianCycle
lemma IsHamiltonian.mono {H : SimpleGraph α} (hGH : G ≤ H) (hG : G.IsHamiltonian) :
H.IsHamiltonian :=
fun hα ↦ let ⟨_, p, hp⟩ := hG hα; ⟨_, p.map <| .ofLE hGH, hp.map _ bijective_id⟩
lemma IsHamiltonian.connected (hG : G.IsHamiltonian) : G.Connected where
preconnected a b := by
obtain rfl | hab := eq_or_ne a b
· rfl
have : Nontrivial α := ⟨a, b, hab⟩
obtain ⟨_, p, hp⟩ := hG Fintype.one_lt_card.ne'
have a_mem := hp.mem_support a
have b_mem := hp.mem_support b
exact ((p.takeUntil a a_mem).reverse.append <| p.takeUntil b b_mem).reachable
nonempty := not_isEmpty_iff.1 fun _ ↦ by simpa using hG <| by simp [@Fintype.card_eq_zero]
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Turan.lean | import Mathlib.Combinatorics.SimpleGraph.Extremal.Turan
deprecated_module (since := "2025-08-21") |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Walk.lean | import Mathlib.Combinatorics.SimpleGraph.DeleteEdges
/-!
# Walk
In a simple graph, a *walk* is a finite sequence of adjacent vertices, and can be
thought of equally well as a sequence of directed edges.
**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` (with accompanying pattern definitions
`SimpleGraph.Walk.nil'` and `SimpleGraph.Walk.cons'`)
* `SimpleGraph.Walk.map` for the induced map on walks,
given an (injective) graph homomorphism.
## Tags
walks
-/
-- TODO: split
open Function
universe u v w
namespace SimpleGraph
variable {V : Type u} {V' : Type v} {V'' : Type w}
variable (G : SimpleGraph V) (G' : SimpleGraph V') (G'' : SimpleGraph V'')
/-- A walk is a sequence of adjacent vertices. For vertices `u v : V`,
the type `walk u v` consists of all walks starting at `u` and ending at `v`.
We say that a walk *visits* the vertices it contains. The set of vertices a
walk visits is `SimpleGraph.Walk.support`.
See `SimpleGraph.Walk.nil'` and `SimpleGraph.Walk.cons'` for patterns that
can be useful in definitions since they make the vertices explicit. -/
inductive Walk : V → V → Type u
| nil {u : V} : Walk u u
| cons {u v w : V} (h : G.Adj u v) (p : Walk v w) : Walk u w
deriving DecidableEq
attribute [refl] Walk.nil
@[simps]
instance Walk.instInhabited (v : V) : Inhabited (G.Walk v v) := ⟨Walk.nil⟩
/-- The one-edge walk associated to a pair of adjacent vertices. -/
@[match_pattern, reducible]
def Adj.toWalk {G : SimpleGraph V} {u v : V} (h : G.Adj u v) : G.Walk u v :=
Walk.cons h Walk.nil
namespace Walk
variable {G}
/-- Pattern to get `Walk.nil` with the vertex as an explicit argument. -/
@[match_pattern]
abbrev nil' (u : V) : G.Walk u u := Walk.nil
/-- Pattern to get `Walk.cons` with the vertices as explicit arguments. -/
@[match_pattern]
abbrev cons' (u v w : V) (h : G.Adj u v) (p : G.Walk v w) : G.Walk u w := Walk.cons h p
/-- Change the endpoints of a walk using equalities. This is helpful for relaxing
definitional equality constraints and to be able to state otherwise difficult-to-state
lemmas. While this is a simple wrapper around `Eq.rec`, it gives a canonical way to write it.
The simp-normal form is for the `copy` to be pushed outward. That way calculations can
occur within the "copy context." -/
protected def copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : G.Walk u' v' :=
hu ▸ hv ▸ p
@[simp]
theorem copy_rfl_rfl {u v} (p : G.Walk u v) : p.copy rfl rfl = p := rfl
@[simp]
theorem copy_copy {u v u' v' u'' v''} (p : G.Walk u v)
(hu : u = u') (hv : v = v') (hu' : u' = u'') (hv' : v' = v'') :
(p.copy hu hv).copy hu' hv' = p.copy (hu.trans hu') (hv.trans hv') := by
subst_vars
rfl
@[simp]
theorem copy_nil {u u'} (hu : u = u') : (Walk.nil : G.Walk u u).copy hu hu = nil := by
subst_vars
rfl
theorem copy_cons {u v w u' w'} (h : G.Adj u v) (p : G.Walk v w) (hu : u = u') (hw : w = w') :
(Walk.cons h p).copy hu hw = Walk.cons (hu ▸ h) (p.copy rfl hw) := by
subst_vars
rfl
@[simp]
theorem cons_copy {u v w v' w'} (h : G.Adj u v) (p : G.Walk v' w') (hv : v' = v) (hw : w' = w) :
cons h (p.copy hv hw) = (Walk.cons (hv ▸ h) p).copy rfl hw := by
subst_vars
rfl
theorem exists_eq_cons_of_ne {u v : V} (hne : u ≠ v) :
∀ (p : G.Walk u v), ∃ (w : V) (h : G.Adj u w) (p' : G.Walk w v), p = cons h p'
| nil => (hne rfl).elim
| cons h p' => ⟨_, h, p', rfl⟩
/-- The length of a walk is the number of edges/darts along it. -/
def length {u v : V} : G.Walk u v → ℕ
| nil => 0
| cons _ q => q.length.succ
/-- The concatenation of two compatible walks. -/
@[trans]
def append {u v w : V} : G.Walk u v → G.Walk v w → G.Walk u w
| nil, q => q
| cons h p, q => cons h (p.append q)
/-- The reversed version of `SimpleGraph.Walk.cons`, concatenating an edge to
the end of a walk. -/
def concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) : G.Walk u w := p.append (cons h nil)
theorem concat_eq_append {u v w : V} (p : G.Walk u v) (h : G.Adj v w) :
p.concat h = p.append (cons h nil) := rfl
/-- The concatenation of the reverse of the first walk with the second walk. -/
protected def reverseAux {u v w : V} : G.Walk u v → G.Walk u w → G.Walk v w
| nil, q => q
| cons h p, q => Walk.reverseAux p (cons (G.symm h) q)
/-- The walk in reverse. -/
@[symm]
def reverse {u v : V} (w : G.Walk u v) : G.Walk v u := w.reverseAux nil
/-- Get the `n`th vertex from a walk, where `n` is generally expected to be
between `0` and `p.length`, inclusive.
If `n` is greater than or equal to `p.length`, the result is the path's endpoint. -/
def getVert {u v : V} : G.Walk u v → ℕ → V
| nil, _ => u
| cons _ _, 0 => u
| cons _ q, n + 1 => q.getVert n
@[simp]
theorem getVert_zero {u v} (w : G.Walk u v) : w.getVert 0 = u := by cases w <;> rfl
@[simp]
theorem getVert_nil (u : V) {i : ℕ} : (@nil _ G u).getVert i = u := rfl
theorem getVert_of_length_le {u v} (w : G.Walk u v) {i : ℕ} (hi : w.length ≤ i) :
w.getVert i = v := by
induction w generalizing i with
| nil => rfl
| cons _ _ ih =>
cases i
· cases hi
· exact ih (Nat.succ_le_succ_iff.1 hi)
@[simp]
theorem getVert_length {u v} (w : G.Walk u v) : w.getVert w.length = v :=
w.getVert_of_length_le rfl.le
theorem adj_getVert_succ {u v} (w : G.Walk u v) {i : ℕ} (hi : i < w.length) :
G.Adj (w.getVert i) (w.getVert (i + 1)) := by
induction w generalizing i with
| nil => cases hi
| cons hxy _ ih =>
cases i
· simp [getVert, hxy]
· exact ih (Nat.succ_lt_succ_iff.1 hi)
@[simp]
lemma getVert_cons_succ {u v w n} (p : G.Walk v w) (h : G.Adj u v) :
(p.cons h).getVert (n + 1) = p.getVert n := rfl
lemma getVert_cons {u v w n} (p : G.Walk v w) (h : G.Adj u v) (hn : n ≠ 0) :
(p.cons h).getVert n = p.getVert (n - 1) := by
obtain ⟨n, rfl⟩ := Nat.exists_eq_add_one_of_ne_zero hn
rw [getVert_cons_succ, Nat.add_sub_cancel]
@[simp]
theorem cons_append {u v w x : V} (h : G.Adj u v) (p : G.Walk v w) (q : G.Walk w x) :
(cons h p).append q = cons h (p.append q) := rfl
@[simp]
theorem cons_nil_append {u v w : V} (h : G.Adj u v) (p : G.Walk v w) :
(cons h nil).append p = cons h p := rfl
@[simp]
theorem nil_append {u v : V} (p : G.Walk u v) : nil.append p = p :=
rfl
@[simp]
theorem append_nil {u v : V} (p : G.Walk u v) : p.append nil = p := by
induction p <;> simp [*]
theorem append_assoc {u v w x : V} (p : G.Walk u v) (q : G.Walk v w) (r : G.Walk w x) :
p.append (q.append r) = (p.append q).append r := by
induction p <;> simp [*]
@[simp]
theorem append_copy_copy {u v w u' v' w'} (p : G.Walk u v) (q : G.Walk v w)
(hu : u = u') (hv : v = v') (hw : w = w') :
(p.copy hu hv).append (q.copy hv hw) = (p.append q).copy hu hw := by
subst_vars
rfl
theorem concat_nil {u v : V} (h : G.Adj u v) : nil.concat h = cons h nil := rfl
@[simp]
theorem concat_cons {u v w x : V} (h : G.Adj u v) (p : G.Walk v w) (h' : G.Adj w x) :
(cons h p).concat h' = cons h (p.concat h') := rfl
theorem append_concat {u v w x : V} (p : G.Walk u v) (q : G.Walk v w) (h : G.Adj w x) :
p.append (q.concat h) = (p.append q).concat h := append_assoc _ _ _
theorem concat_append {u v w x : V} (p : G.Walk u v) (h : G.Adj v w) (q : G.Walk w x) :
(p.concat h).append q = p.append (cons h q) := by
rw [concat_eq_append, ← append_assoc, cons_nil_append]
/-- A non-trivial `cons` walk is representable as a `concat` walk. -/
theorem exists_cons_eq_concat {u v w : V} (h : G.Adj u v) (p : G.Walk v w) :
∃ (x : V) (q : G.Walk u x) (h' : G.Adj x w), cons h p = q.concat h' := by
induction p generalizing u with
| nil => exact ⟨_, nil, h, rfl⟩
| cons h' p ih =>
obtain ⟨y, q, h'', hc⟩ := ih h'
exact ⟨y, cons h q, h'', hc ▸ concat_cons _ _ _ ▸ rfl⟩
/-- A non-trivial `concat` walk is representable as a `cons` walk. -/
theorem exists_concat_eq_cons {u v w : V} :
∀ (p : G.Walk u v) (h : G.Adj v w),
∃ (x : V) (h' : G.Adj u x) (q : G.Walk x w), p.concat h = cons h' q
| nil, h => ⟨_, h, nil, rfl⟩
| cons h' p, h => ⟨_, h', Walk.concat p h, concat_cons _ _ _⟩
@[simp]
theorem reverse_nil {u : V} : (nil : G.Walk u u).reverse = nil := rfl
theorem reverse_singleton {u v : V} (h : G.Adj u v) : (cons h nil).reverse = cons (G.symm h) nil :=
rfl
@[simp]
theorem cons_reverseAux {u v w x : V} (p : G.Walk u v) (q : G.Walk w x) (h : G.Adj w u) :
(cons h p).reverseAux q = p.reverseAux (cons (G.symm h) q) := rfl
@[simp]
protected theorem append_reverseAux {u v w x : V}
(p : G.Walk u v) (q : G.Walk v w) (r : G.Walk u x) :
(p.append q).reverseAux r = q.reverseAux (p.reverseAux r) := by
induction p with
| nil => rfl
| cons h _ ih => exact ih q (cons (G.symm h) r)
@[simp]
protected theorem reverseAux_append {u v w x : V}
(p : G.Walk u v) (q : G.Walk u w) (r : G.Walk w x) :
(p.reverseAux q).append r = p.reverseAux (q.append r) := by
induction p with
| nil => rfl
| cons h _ ih => simp [ih (cons (G.symm h) q)]
protected theorem reverseAux_eq_reverse_append {u v w : V} (p : G.Walk u v) (q : G.Walk u w) :
p.reverseAux q = p.reverse.append q := by simp [reverse]
@[simp]
theorem reverse_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) :
(cons h p).reverse = p.reverse.append (cons (G.symm h) nil) := by simp [reverse]
@[simp]
theorem reverse_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') :
(p.copy hu hv).reverse = p.reverse.copy hv hu := by
subst_vars
rfl
@[simp]
theorem reverse_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) :
(p.append q).reverse = q.reverse.append p.reverse := by simp [reverse]
@[simp]
theorem reverse_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) :
(p.concat h).reverse = cons (G.symm h) p.reverse := by simp [concat_eq_append]
@[simp]
theorem reverse_reverse {u v : V} (p : G.Walk u v) : p.reverse.reverse = p := by
induction p with
| nil => rfl
| cons _ _ ih => simp [ih]
theorem reverse_surjective {u v : V} : Function.Surjective (reverse : G.Walk u v → _) :=
RightInverse.surjective reverse_reverse
theorem reverse_injective {u v : V} : Function.Injective (reverse : G.Walk u v → _) :=
RightInverse.injective reverse_reverse
theorem reverse_bijective {u v : V} : Function.Bijective (reverse : G.Walk u v → _) :=
⟨reverse_injective, reverse_surjective⟩
@[simp]
theorem length_nil {u : V} : (nil : G.Walk u u).length = 0 := rfl
@[simp]
theorem length_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) :
(cons h p).length = p.length + 1 := rfl
@[simp]
theorem length_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') :
(p.copy hu hv).length = p.length := by
subst_vars
rfl
@[simp]
theorem length_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) :
(p.append q).length = p.length + q.length := by
induction p <;> simp [*, add_comm, add_assoc]
@[simp]
theorem length_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) :
(p.concat h).length = p.length + 1 := length_append _ _
@[simp]
protected theorem length_reverseAux {u v w : V} (p : G.Walk u v) (q : G.Walk u w) :
(p.reverseAux q).length = p.length + q.length := by
induction p with
| nil => simp!
| cons _ _ ih => simp [ih, Nat.succ_add, add_assoc]
@[simp]
theorem length_reverse {u v : V} (p : G.Walk u v) : p.reverse.length = p.length := by simp [reverse]
theorem eq_of_length_eq_zero {u v : V} : ∀ {p : G.Walk u v}, p.length = 0 → u = v
| nil, _ => rfl
theorem adj_of_length_eq_one {u v : V} : ∀ {p : G.Walk u v}, p.length = 1 → G.Adj u v
| cons h nil, _ => h
@[simp]
theorem exists_length_eq_zero_iff {u v : V} : (∃ p : G.Walk u v, p.length = 0) ↔ u = v :=
⟨fun ⟨_, h⟩ ↦ (eq_of_length_eq_zero h), (· ▸ ⟨nil, rfl⟩)⟩
@[simp]
lemma exists_length_eq_one_iff {u v : V} : (∃ (p : G.Walk u v), p.length = 1) ↔ G.Adj u v := by
refine ⟨fun ⟨p, hp⟩ ↦ ?_, fun h ↦ ⟨h.toWalk, by simp⟩⟩
induction p with
| nil => simp at hp
| cons h p' =>
simp only [Walk.length_cons, add_eq_right] at hp
exact (p'.eq_of_length_eq_zero hp) ▸ h
@[simp]
theorem length_eq_zero_iff {u : V} {p : G.Walk u u} : p.length = 0 ↔ p = nil := by cases p <;> simp
theorem getVert_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) (i : ℕ) :
(p.append q).getVert i = if i < p.length then p.getVert i else q.getVert (i - p.length) := by
induction p generalizing i <;> cases i <;> simp [*]
theorem getVert_reverse {u v : V} (p : G.Walk u v) (i : ℕ) :
p.reverse.getVert i = p.getVert (p.length - i) := by
induction p with
| nil => rfl
| cons h p ih =>
simp only [reverse_cons, getVert_append, length_reverse, ih, length_cons]
split_ifs
next hi => simp [Nat.succ_sub hi.le]
next hi =>
obtain rfl | hi' := eq_or_gt_of_not_lt hi
· simp
· rw [Nat.eq_add_of_sub_eq (Nat.sub_pos_of_lt hi') rfl, Nat.sub_eq_zero_of_le hi']
simp
section ConcatRec
variable {motive : ∀ u v : V, G.Walk u v → Sort*} (Hnil : ∀ {u : V}, motive u u nil)
(Hconcat : ∀ {u v w : V} (p : G.Walk u v) (h : G.Adj v w), motive u v p → motive u w (p.concat h))
/-- Auxiliary definition for `SimpleGraph.Walk.concatRec` -/
def concatRecAux {u v : V} : (p : G.Walk u v) → motive v u p.reverse
| nil => Hnil
| cons h p => reverse_cons h p ▸ Hconcat p.reverse h.symm (concatRecAux p)
/-- Recursor on walks by inducting on `SimpleGraph.Walk.concat`.
This is inducting from the opposite end of the walk compared
to `SimpleGraph.Walk.rec`, which inducts on `SimpleGraph.Walk.cons`. -/
@[elab_as_elim]
def concatRec {u v : V} (p : G.Walk u v) : motive u v p :=
reverse_reverse p ▸ concatRecAux @Hnil @Hconcat p.reverse
@[simp]
theorem concatRec_nil (u : V) :
@concatRec _ _ motive @Hnil @Hconcat _ _ (nil : G.Walk u u) = Hnil := rfl
@[simp]
theorem concatRec_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) :
@concatRec _ _ motive @Hnil @Hconcat _ _ (p.concat h) =
Hconcat p h (concatRec @Hnil @Hconcat p) := by
simp only [concatRec]
apply eq_of_heq (rec_heq_of_heq _ _)
trans concatRecAux @Hnil @Hconcat (cons h.symm p.reverse)
· congr
simp
· rw [concatRecAux, eqRec_heq_iff_heq]
congr <;> simp
end ConcatRec
theorem concat_ne_nil {u v : V} (p : G.Walk u v) (h : G.Adj v u) : p.concat h ≠ nil := by
cases p <;> simp [concat]
theorem concat_inj {u v v' w : V} {p : G.Walk u v} {h : G.Adj v w} {p' : G.Walk u v'}
{h' : G.Adj v' w} (he : p.concat h = p'.concat h') : ∃ hv : v = v', p.copy rfl hv = p' := by
induction p with
| nil =>
cases p'
· exact ⟨rfl, rfl⟩
· simp only [concat_nil, concat_cons, cons.injEq] at he
obtain ⟨rfl, he⟩ := he
exact (concat_ne_nil _ _ (heq_iff_eq.mp he).symm).elim
| cons _ _ ih =>
rw [concat_cons] at he
cases p'
· simp only [concat_nil, cons.injEq] at he
obtain ⟨rfl, he⟩ := he
exact (concat_ne_nil _ _ (heq_iff_eq.mp he)).elim
· rw [concat_cons, cons.injEq] at he
obtain ⟨rfl, he⟩ := he
obtain ⟨rfl, rfl⟩ := ih (heq_iff_eq.mp he)
exact ⟨rfl, rfl⟩
/-- The `support` of a walk is the list of vertices it visits in order. -/
def support {u v : V} : G.Walk u v → List V
| nil => [u]
| cons _ p => u :: p.support
/-- The `darts` of a walk is the list of darts it visits in order. -/
def darts {u v : V} : G.Walk u v → List G.Dart
| nil => []
| cons h p => ⟨(u, _), h⟩ :: p.darts
/-- The `edges` of a walk is the list of edges it visits in order.
This is defined to be the list of edges underlying `SimpleGraph.Walk.darts`. -/
def edges {u v : V} (p : G.Walk u v) : List (Sym2 V) := p.darts.map Dart.edge
@[simp]
theorem support_nil {u : V} : (nil : G.Walk u u).support = [u] := rfl
@[simp]
theorem support_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) :
(cons h p).support = u :: p.support := rfl
@[simp]
theorem support_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) :
(p.concat h).support = p.support.concat w := by
induction p <;> simp [*, concat_nil]
@[simp]
theorem support_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') :
(p.copy hu hv).support = p.support := by
subst_vars
rfl
theorem support_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) :
(p.append p').support = p.support ++ p'.support.tail := by
induction p <;> cases p' <;> simp [*]
@[simp]
theorem support_reverse {u v : V} (p : G.Walk u v) : p.reverse.support = p.support.reverse := by
induction p <;> simp [support_append, *]
@[simp]
theorem support_ne_nil {u v : V} (p : G.Walk u v) : p.support ≠ [] := by cases p <;> simp
theorem support_append_eq_support_dropLast_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) :
(p.append p').support = p.support.dropLast ++ p'.support := by
induction p <;> simp_all [List.dropLast_cons_of_ne_nil]
@[simp]
theorem head_support {G : SimpleGraph V} {a b : V} (p : G.Walk a b) :
p.support.head (by simp) = a := by cases p <;> simp
@[simp]
theorem getLast_support {G : SimpleGraph V} {a b : V} (p : G.Walk a b) :
p.support.getLast (by simp) = b := by
induction p <;> simp [*]
theorem tail_support_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) :
(p.append p').support.tail = p.support.tail ++ p'.support.tail := by
rw [support_append, List.tail_append_of_ne_nil (support_ne_nil _)]
theorem support_eq_cons {u v : V} (p : G.Walk u v) : p.support = u :: p.support.tail := by
cases p <;> simp
theorem support_eq_concat {u v : V} (p : G.Walk u v) : p.support = p.support.dropLast.concat v := by
cases p with
| nil => rfl
| cons h p =>
obtain ⟨_, _, _, hq⟩ := exists_cons_eq_concat h p
simp [hq]
@[simp]
theorem start_mem_support {u v : V} (p : G.Walk u v) : u ∈ p.support := by cases p <;> simp
@[simp]
theorem end_mem_support {u v : V} (p : G.Walk u v) : v ∈ p.support := by induction p <;> simp [*]
@[simp]
theorem support_nonempty {u v : V} (p : G.Walk u v) : { w | w ∈ p.support }.Nonempty :=
⟨u, by simp⟩
theorem mem_support_iff {u v w : V} (p : G.Walk u v) :
w ∈ p.support ↔ w = u ∨ w ∈ p.support.tail := by cases p <;> simp
@[simp]
theorem getVert_mem_support {u v : V} (p : G.Walk u v) (i : ℕ) : p.getVert i ∈ p.support := by
induction p generalizing i <;> cases i <;> simp [*]
theorem mem_support_nil_iff {u v : V} : u ∈ (nil : G.Walk v v).support ↔ u = v := by simp
@[simp]
theorem mem_tail_support_append_iff {t u v w : V} (p : G.Walk u v) (p' : G.Walk v w) :
t ∈ (p.append p').support.tail ↔ t ∈ p.support.tail ∨ t ∈ p'.support.tail := by
rw [tail_support_append, List.mem_append]
@[simp]
theorem end_mem_tail_support_of_ne {u v : V} (h : u ≠ v) (p : G.Walk u v) : v ∈ p.support.tail := by
obtain ⟨_, _, _, rfl⟩ := exists_eq_cons_of_ne h p
simp
@[simp, nolint unusedHavesSuffices]
theorem mem_support_append_iff {t u v w : V} (p : G.Walk u v) (p' : G.Walk v w) :
t ∈ (p.append p').support ↔ t ∈ p.support ∨ t ∈ p'.support := by
simp only [mem_support_iff, mem_tail_support_append_iff]
obtain rfl | h := eq_or_ne t v <;> obtain rfl | h' := eq_or_ne t u <;>
-- this `have` triggers the unusedHavesSuffices linter:
(try have := h'.symm) <;> simp [*]
theorem support_subset_support_cons {u v w : V} (p : G.Walk v w) (hadj : G.Adj u v) :
p.support ⊆ (p.cons hadj).support := by
simp
theorem support_subset_support_concat {u v w : V} (p : G.Walk u v) (hadj : G.Adj v w) :
p.support ⊆ (p.concat hadj).support := by
simp
@[simp]
theorem subset_support_append_left {V : Type u} {G : SimpleGraph V} {u v w : V}
(p : G.Walk u v) (q : G.Walk v w) : p.support ⊆ (p.append q).support := by
simp [support_append]
@[simp]
theorem subset_support_append_right {V : Type u} {G : SimpleGraph V} {u v w : V}
(p : G.Walk u v) (q : G.Walk v w) : q.support ⊆ (p.append q).support := by
intro
simp +contextual [mem_support_append_iff]
theorem coe_support {u v : V} (p : G.Walk u v) :
(p.support : Multiset V) = {u} + p.support.tail := by cases p <;> rfl
theorem coe_support_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) :
((p.append p').support : Multiset V) = {u} + p.support.tail + p'.support.tail := by
rw [support_append, ← Multiset.coe_add, coe_support]
theorem coe_support_append' [DecidableEq V] {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) :
((p.append p').support : Multiset V) = p.support + p'.support - {v} := by
simp_rw [support_append, ← Multiset.coe_add, coe_support, add_comm ({v} : Multiset V),
← add_assoc, add_tsub_cancel_right]
theorem isChain_adj_cons_support {u v w : V} (h : G.Adj u v) :
∀ (p : G.Walk v w), List.IsChain G.Adj (u :: p.support)
| nil => .cons_cons h (.singleton _)
| cons h' p => .cons_cons h (isChain_adj_cons_support h' p)
@[deprecated (since := "2025-09-24")] alias chain_adj_support := isChain_adj_cons_support
theorem isChain_adj_support {u v : V} : ∀ (p : G.Walk u v), List.IsChain G.Adj p.support
| nil => .singleton _
| cons h p => isChain_adj_cons_support h p
@[deprecated (since := "2025-09-24")] alias chain'_adj_support := isChain_adj_support
theorem isChain_dartAdj_cons_darts {d : G.Dart} {v w : V} (h : d.snd = v) (p : G.Walk v w) :
List.IsChain G.DartAdj (d :: p.darts) := by
induction p generalizing d with
| nil => exact .singleton _
| cons h' p ih => exact .cons_cons h (ih rfl)
theorem isChain_dartAdj_darts {u v : V} : ∀ (p : G.Walk u v), List.IsChain G.DartAdj p.darts
| nil => .nil
-- Porting note: needed to defer `rfl` to help elaboration
| cons h p => isChain_dartAdj_cons_darts (by rfl) p
@[deprecated (since := "2025-09-24")] alias chain_dartAdj_darts := isChain_dartAdj_cons_darts
@[deprecated (since := "2025-09-24")] alias chain'_dartAdj_darts := isChain_dartAdj_darts
/-- Every edge in a walk's edge list is an edge of the graph.
It is written in this form (rather than using `⊆`) to avoid unsightly coercions. -/
theorem edges_subset_edgeSet {u v : V} :
∀ (p : G.Walk u v) ⦃e : Sym2 V⦄, e ∈ p.edges → e ∈ G.edgeSet
| cons h' p', e, h => by
cases h
· exact h'
next h' => exact edges_subset_edgeSet p' h'
theorem adj_of_mem_edges {u v x y : V} (p : G.Walk u v) (h : s(x, y) ∈ p.edges) : G.Adj x y :=
p.edges_subset_edgeSet h
@[simp]
theorem darts_nil {u : V} : (nil : G.Walk u u).darts = [] := rfl
@[simp]
theorem darts_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) :
(cons h p).darts = ⟨(u, v), h⟩ :: p.darts := rfl
@[simp]
theorem darts_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) :
(p.concat h).darts = p.darts.concat ⟨(v, w), h⟩ := by
induction p <;> simp [*, concat_nil]
@[simp]
theorem darts_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') :
(p.copy hu hv).darts = p.darts := by
subst_vars
rfl
@[simp]
theorem darts_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) :
(p.append p').darts = p.darts ++ p'.darts := by
induction p <;> simp [*]
@[simp]
theorem darts_reverse {u v : V} (p : G.Walk u v) :
p.reverse.darts = (p.darts.map Dart.symm).reverse := by
induction p <;> simp [*]
theorem mem_darts_reverse {u v : V} {d : G.Dart} {p : G.Walk u v} :
d ∈ p.reverse.darts ↔ d.symm ∈ p.darts := by simp
theorem cons_map_snd_darts {u v : V} (p : G.Walk u v) : (u :: p.darts.map (·.snd)) = p.support := by
induction p <;> simp [*]
theorem map_snd_darts {u v : V} (p : G.Walk u v) : p.darts.map (·.snd) = p.support.tail := by
simpa using congr_arg List.tail (cons_map_snd_darts p)
theorem map_fst_darts_append {u v : V} (p : G.Walk u v) :
p.darts.map (·.fst) ++ [v] = p.support := by
induction p <;> simp [*]
theorem map_fst_darts {u v : V} (p : G.Walk u v) : p.darts.map (·.fst) = p.support.dropLast := by
simpa! using congr_arg List.dropLast (map_fst_darts_append p)
@[simp]
theorem head_darts_fst {G : SimpleGraph V} {a b : V} (p : G.Walk a b) (hp : p.darts ≠ []) :
(p.darts.head hp).fst = a := by
cases p
· contradiction
· simp
@[simp]
theorem getLast_darts_snd {G : SimpleGraph V} {a b : V} (p : G.Walk a b) (hp : p.darts ≠ []) :
(p.darts.getLast hp).snd = b := by
rw [← List.getLast_map (f := fun x : G.Dart ↦ x.snd) (by simpa)]
simp_rw [p.map_snd_darts, List.getLast_tail, p.getLast_support]
@[simp]
theorem edges_nil {u : V} : (nil : G.Walk u u).edges = [] := rfl
@[simp]
theorem edges_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) :
(cons h p).edges = s(u, v) :: p.edges := rfl
@[simp]
theorem edges_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) :
(p.concat h).edges = p.edges.concat s(v, w) := by simp [edges]
@[simp]
theorem edges_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') :
(p.copy hu hv).edges = p.edges := by
subst_vars
rfl
@[simp]
theorem edges_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) :
(p.append p').edges = p.edges ++ p'.edges := by simp [edges]
@[simp]
theorem edges_reverse {u v : V} (p : G.Walk u v) : p.reverse.edges = p.edges.reverse := by
simp [edges]
@[simp]
theorem length_support {u v : V} (p : G.Walk u v) : p.support.length = p.length + 1 := by
induction p <;> simp [*]
@[simp]
theorem length_darts {u v : V} (p : G.Walk u v) : p.darts.length = p.length := by
induction p <;> simp [*]
@[simp]
theorem length_edges {u v : V} (p : G.Walk u v) : p.edges.length = p.length := by simp [edges]
theorem dart_fst_mem_support_of_mem_darts {u v : V} :
∀ (p : G.Walk u v) {d : G.Dart}, d ∈ p.darts → d.fst ∈ p.support
| cons h p', d, hd => by
simp only [support_cons, darts_cons, List.mem_cons] at hd ⊢
rcases hd with rfl | hd
· exact .inl rfl
· exact .inr (dart_fst_mem_support_of_mem_darts _ hd)
theorem dart_snd_mem_support_of_mem_darts {u v : V} (p : G.Walk u v) {d : G.Dart}
(h : d ∈ p.darts) : d.snd ∈ p.support := by
simpa using p.reverse.dart_fst_mem_support_of_mem_darts (by simp [h] : d.symm ∈ p.reverse.darts)
theorem fst_mem_support_of_mem_edges {t u v w : V} (p : G.Walk v w) (he : s(t, u) ∈ p.edges) :
t ∈ p.support := by
obtain ⟨d, hd, he⟩ := List.mem_map.mp he
rw [dart_edge_eq_mk'_iff'] at he
rcases he with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩
· exact dart_fst_mem_support_of_mem_darts _ hd
· exact dart_snd_mem_support_of_mem_darts _ hd
theorem snd_mem_support_of_mem_edges {t u v w : V} (p : G.Walk v w) (he : s(t, u) ∈ p.edges) :
u ∈ p.support :=
p.fst_mem_support_of_mem_edges (Sym2.eq_swap ▸ he)
theorem darts_nodup_of_support_nodup {u v : V} {p : G.Walk u v} (h : p.support.Nodup) :
p.darts.Nodup := by
induction p with
| nil => simp
| cons _ p' ih =>
simp only [darts_cons, support_cons, List.nodup_cons] at h ⊢
exact ⟨(h.1 <| dart_fst_mem_support_of_mem_darts p' ·), ih h.2⟩
theorem edges_nodup_of_support_nodup {u v : V} {p : G.Walk u v} (h : p.support.Nodup) :
p.edges.Nodup := by
induction p with
| nil => simp
| cons _ p' ih =>
simp only [support_cons, List.nodup_cons, edges_cons] at h ⊢
exact ⟨(h.1 <| fst_mem_support_of_mem_edges p' ·), ih h.2⟩
lemma getVert_eq_support_getElem {u v : V} {n : ℕ} (p : G.Walk u v) (h : n ≤ p.length) :
p.getVert n = p.support[n]'(p.length_support ▸ Nat.lt_add_one_of_le h) := by
cases p with
| nil => simp
| cons => cases n with
| zero => simp
| succ n =>
simp_rw [support_cons, getVert_cons _ _ n.zero_ne_add_one.symm, List.getElem_cons]
exact getVert_eq_support_getElem _ (Nat.sub_le_of_le_add h)
lemma getVert_eq_support_getElem? {u v : V} {n : ℕ} (p : G.Walk u v) (h : n ≤ p.length) :
some (p.getVert n) = p.support[n]? := by
rw [getVert_eq_support_getElem p h, ← List.getElem?_eq_getElem]
@[deprecated (since := "2025-06-10")]
alias getVert_eq_support_get? := getVert_eq_support_getElem?
lemma getVert_eq_getD_support {u v : V} (p : G.Walk u v) (n : ℕ) :
p.getVert n = p.support.getD n v := by
by_cases h : n ≤ p.length
· simp [← getVert_eq_support_getElem? p h]
grind [getVert_of_length_le, length_support]
theorem getVert_comp_val_eq_get_support {u v : V} (p : G.Walk u v) :
p.getVert ∘ Fin.val = p.support.get := by
grind [getVert_eq_support_getElem, length_support]
theorem range_getVert_eq_range_support_getElem {u v : V} (p : G.Walk u v) :
Set.range p.getVert = Set.range p.support.get :=
Set.ext fun _ ↦ ⟨by grind [Set.range_list_get, getVert_mem_support],
fun ⟨n, _⟩ ↦ ⟨n, by grind [getVert_eq_support_getElem, length_support]⟩⟩
theorem nodup_tail_support_reverse {u : V} {p : G.Walk u u} :
p.reverse.support.tail.Nodup ↔ p.support.tail.Nodup := by
refine p.support_reverse ▸ p.support.nodup_tail_reverse ?_
rw [← getVert_eq_support_getElem? _ (by cutsat), List.getLast?_eq_getElem?,
← getVert_eq_support_getElem? _ (by rw [Walk.length_support]; cutsat)]
simp
theorem edges_eq_zipWith_support {u v : V} {p : G.Walk u v} :
p.edges = List.zipWith (s(·, ·)) p.support p.support.tail := by
induction p with
| nil => simp
| cons _ p' ih => cases p' <;> simp [edges_cons, ih]
theorem darts_getElem_eq_getVert {u v : V} {p : G.Walk u v} (n : ℕ) (h : n < p.darts.length) :
p.darts[n] = ⟨⟨p.getVert n, p.getVert (n + 1)⟩, p.adj_getVert_succ (p.length_darts ▸ h)⟩ := by
rw [p.length_darts] at h
ext
· simp only [p.getVert_eq_support_getElem (le_of_lt h)]
by_cases h' : n = 0
· simp [h', List.getElem_zero]
· have := p.isChain_dartAdj_darts.getElem (n - 1) (by grind)
grind [DartAdj, =_ cons_map_snd_darts]
· simp [p.getVert_eq_support_getElem h, ← p.cons_map_snd_darts]
theorem edges_injective {u v : V} : Function.Injective (Walk.edges : G.Walk u v → List (Sym2 V))
| .nil, .nil, _ => rfl
| .nil, .cons _ _, h => by simp at h
| .cons _ _, .nil, h => by simp at h
| .cons' u v c h₁ w₁, .cons' _ v' _ h₂ w₂, h => by
have h₃ : u ≠ v' := by rintro rfl; exact G.loopless _ h₂
obtain ⟨rfl, h₃⟩ : v = v' ∧ w₁.edges = w₂.edges := by simpa [h₁, h₃] using h
rw [edges_injective h₃]
theorem darts_injective {u v : V} : Function.Injective (Walk.darts : G.Walk u v → List G.Dart) :=
edges_injective.of_comp
/-- The `Set` of edges of a walk. -/
def edgeSet {u v : V} (p : G.Walk u v) : Set (Sym2 V) := {e | e ∈ p.edges}
@[simp]
lemma mem_edgeSet {u v : V} {p : G.Walk u v} {e : Sym2 V} : e ∈ p.edgeSet ↔ e ∈ p.edges := Iff.rfl
@[simp]
lemma edgeSet_nil (u : V) : (nil : G.Walk u u).edgeSet = ∅ := by ext; simp
@[simp]
lemma edgeSet_reverse {u v : V} (p : G.Walk u v) : p.reverse.edgeSet = p.edgeSet := by ext; simp
@[simp]
theorem edgeSet_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) :
(cons h p).edgeSet = insert s(u, v) p.edgeSet := by ext; simp
@[simp]
theorem edgeSet_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) :
(p.concat h).edgeSet = insert s(v, w) p.edgeSet := by ext; simp [or_comm]
theorem edgeSet_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) :
(p.append q).edgeSet = p.edgeSet ∪ q.edgeSet := by ext; simp
@[simp]
theorem edgeSet_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') :
(p.copy hu hv).edgeSet = p.edgeSet := by ext; simp
theorem coe_edges_toFinset [DecidableEq V] {u v : V} (p : G.Walk u v) :
(p.edges.toFinset : Set (Sym2 V)) = p.edgeSet := by
simp [edgeSet]
/-- Predicate for the empty walk.
Solves the dependent type problem where `p = G.Walk.nil` typechecks
only if `p` has defeq endpoints. -/
inductive Nil : {v w : V} → G.Walk v w → Prop
| nil {u : V} : Nil (nil : G.Walk u u)
variable {u v w : V}
@[simp] lemma nil_nil : (nil : G.Walk u u).Nil := Nil.nil
@[simp] lemma not_nil_cons {h : G.Adj u v} {p : G.Walk v w} : ¬ (cons h p).Nil := nofun
instance (p : G.Walk v w) : Decidable p.Nil :=
match p with
| nil => isTrue .nil
| cons _ _ => isFalse nofun
protected lemma Nil.eq {p : G.Walk v w} : p.Nil → v = w | .nil => rfl
lemma not_nil_of_ne {p : G.Walk v w} : v ≠ w → ¬ p.Nil := mt Nil.eq
lemma nil_iff_support_eq {p : G.Walk v w} : p.Nil ↔ p.support = [v] := by
cases p <;> simp
lemma nil_iff_length_eq {p : G.Walk v w} : p.Nil ↔ p.length = 0 := by
cases p <;> simp
lemma not_nil_iff_lt_length {p : G.Walk v w} : ¬ p.Nil ↔ 0 < p.length := by
cases p <;> simp
lemma not_nil_iff {p : G.Walk v w} :
¬ p.Nil ↔ ∃ (u : V) (h : G.Adj v u) (q : G.Walk u w), p = cons h q := by
cases p <;> simp [*]
@[simp]
lemma nil_append_iff {p : G.Walk u v} {q : G.Walk v w} : (p.append q).Nil ↔ p.Nil ∧ q.Nil := by
cases p <;> cases q <;> simp
lemma Nil.append {p : G.Walk u v} {q : G.Walk v w} (hp : p.Nil) (hq : q.Nil) : (p.append q).Nil :=
by simp [hp, hq]
@[simp]
lemma nil_reverse {p : G.Walk v w} : p.reverse.Nil ↔ p.Nil := by
cases p <;> simp
/-- A walk with its endpoints defeq is `Nil` if and only if it is equal to `nil`. -/
lemma nil_iff_eq_nil : ∀ {p : G.Walk v v}, p.Nil ↔ p = nil
| .nil | .cons _ _ => by simp
alias ⟨Nil.eq_nil, _⟩ := nil_iff_eq_nil
/-- The recursion principle for nonempty walks -/
@[elab_as_elim]
def notNilRec {motive : {u w : V} → (p : G.Walk u w) → (h : ¬ p.Nil) → Sort*}
(cons : {u v w : V} → (h : G.Adj u v) → (q : G.Walk v w) → motive (cons h q) not_nil_cons)
(p : G.Walk u w) : (hp : ¬ p.Nil) → motive p hp :=
match p with
| nil => fun hp => absurd .nil hp
| .cons h q => fun _ => cons h q
@[simp]
lemma notNilRec_cons {motive : {u w : V} → (p : G.Walk u w) → ¬ p.Nil → Sort*}
(cons : {u v w : V} → (h : G.Adj u v) → (q : G.Walk v w) →
motive (q.cons h) Walk.not_nil_cons) (h' : G.Adj u v) (q' : G.Walk v w) :
@Walk.notNilRec _ _ _ _ _ cons _ _ = cons h' q' := by rfl
theorem end_mem_tail_support {u v : V} {p : G.Walk u v} (h : ¬ p.Nil) : v ∈ p.support.tail :=
p.notNilRec (by simp) h
/-- The walk obtained by removing the first `n` darts of a walk. -/
def drop {u v : V} (p : G.Walk u v) (n : ℕ) : G.Walk (p.getVert n) v :=
match p, n with
| .nil, _ => .nil
| p, 0 => p.copy (getVert_zero p).symm rfl
| .cons _ q, (n + 1) => q.drop n
@[simp]
lemma drop_length (p : G.Walk u v) (n : ℕ) : (p.drop n).length = p.length - n := by
induction p generalizing n <;> cases n <;> simp [*, drop]
@[simp]
lemma drop_getVert (p : G.Walk u v) (n m : ℕ) : (p.drop n).getVert m = p.getVert (n + m) := by
induction p generalizing n <;> cases n <;> simp [*, drop, add_right_comm]
/-- The second vertex of a walk, or the only vertex in a nil walk. -/
abbrev snd (p : G.Walk u v) : V := p.getVert 1
@[simp] lemma adj_snd {p : G.Walk v w} (hp : ¬ p.Nil) :
G.Adj v p.snd := by
simpa using adj_getVert_succ p (by simpa [not_nil_iff_lt_length] using hp : 0 < p.length)
lemma snd_cons {u v w} (q : G.Walk v w) (hadj : G.Adj u v) :
(q.cons hadj).snd = v := by simp
/-- The walk obtained by taking the first `n` darts of a walk. -/
def take {u v : V} (p : G.Walk u v) (n : ℕ) : G.Walk u (p.getVert n) :=
match p, n with
| .nil, _ => .nil
| p, 0 => nil.copy rfl (getVert_zero p).symm
| .cons h q, (n + 1) => .cons h (q.take n)
@[simp]
lemma take_length (p : G.Walk u v) (n : ℕ) : (p.take n).length = n ⊓ p.length := by
induction p generalizing n <;> cases n <;> simp [*, take]
@[simp]
lemma take_getVert (p : G.Walk u v) (n m : ℕ) : (p.take n).getVert m = p.getVert (n ⊓ m) := by
induction p generalizing n m <;> cases n <;> cases m <;> simp [*, take]
lemma take_support_eq_support_take_succ {u v} (p : G.Walk u v) (n : ℕ) :
(p.take n).support = p.support.take (n + 1) := by
induction p generalizing n <;> cases n <;> simp [*, take]
/-- The penultimate vertex of a walk, or the only vertex in a nil walk. -/
abbrev penultimate (p : G.Walk u v) : V := p.getVert (p.length - 1)
@[simp]
lemma penultimate_nil : (@nil _ G v).penultimate = v := rfl
@[simp]
lemma penultimate_cons_nil (h : G.Adj u v) : (cons h nil).penultimate = u := rfl
@[simp]
lemma penultimate_cons_cons {w'} (h : G.Adj u v) (h₂ : G.Adj v w) (p : G.Walk w w') :
(cons h (cons h₂ p)).penultimate = (cons h₂ p).penultimate := rfl
lemma penultimate_cons_of_not_nil (h : G.Adj u v) (p : G.Walk v w) (hp : ¬ p.Nil) :
(cons h p).penultimate = p.penultimate :=
p.notNilRec (by simp) hp h
@[simp]
lemma penultimate_concat {t u v} (p : G.Walk u v) (h : G.Adj v t) :
(p.concat h).penultimate = v := by simp [concat_eq_append, getVert_append]
@[simp]
lemma adj_penultimate {p : G.Walk v w} (hp : ¬ p.Nil) :
G.Adj p.penultimate w := by
conv => rhs; rw [← getVert_length p]
rw [nil_iff_length_eq] at hp
convert adj_getVert_succ _ _ <;> omega
@[simp]
lemma snd_reverse (p : G.Walk u v) : p.reverse.snd = p.penultimate := by
simpa using getVert_reverse p 1
@[simp]
lemma penultimate_reverse (p : G.Walk u v) : p.reverse.penultimate = p.snd := by
cases p <;> simp [snd, getVert_append]
/-- The walk obtained by removing the first dart of a walk. A nil walk stays nil. -/
def tail (p : G.Walk u v) : G.Walk (p.snd) v := p.drop 1
lemma drop_zero {u v} (p : G.Walk u v) :
p.drop 0 = p.copy (getVert_zero p).symm rfl := by
cases p <;> simp [Walk.drop]
lemma drop_support_eq_support_drop_min {u v} (p : G.Walk u v) (n : ℕ) :
(p.drop n).support = p.support.drop (n ⊓ p.length) := by
induction p generalizing n <;> cases n <;> simp [*, drop]
/-- The walk obtained by removing the last dart of a walk. A nil walk stays nil. -/
def dropLast (p : G.Walk u v) : G.Walk u p.penultimate := p.take (p.length - 1)
@[simp]
lemma tail_nil : (@nil _ G v).tail = .nil := rfl
@[simp]
lemma tail_cons_nil (h : G.Adj u v) : (Walk.cons h .nil).tail = .nil := rfl
@[simp]
lemma tail_cons (h : G.Adj u v) (p : G.Walk v w) :
(p.cons h).tail = p.copy (getVert_zero p).symm rfl := by
cases p <;> rfl
@[deprecated (since := "2025-08-19")] alias tail_cons_eq := tail_cons
@[simp]
lemma dropLast_nil : (@nil _ G v).dropLast = nil := rfl
@[simp]
lemma dropLast_cons_nil (h : G.Adj u v) : (cons h nil).dropLast = nil := rfl
@[simp]
lemma dropLast_cons_cons {w'} (h : G.Adj u v) (h₂ : G.Adj v w) (p : G.Walk w w') :
(cons h (cons h₂ p)).dropLast = cons h (cons h₂ p).dropLast := rfl
lemma dropLast_cons_of_not_nil (h : G.Adj u v) (p : G.Walk v w) (hp : ¬ p.Nil) :
(cons h p).dropLast = cons h (p.dropLast.copy rfl (penultimate_cons_of_not_nil _ _ hp).symm) :=
p.notNilRec (by simp) hp h
@[simp]
lemma dropLast_concat {t u v} (p : G.Walk u v) (h : G.Adj v t) :
(p.concat h).dropLast = p.copy rfl (by simp) := by
induction p
· rfl
· simp_rw [concat_cons]
rw [dropLast_cons_of_not_nil] <;> simp [*, nil_iff_length_eq]
/-- The first dart of a walk. -/
@[simps]
def firstDart (p : G.Walk v w) (hp : ¬ p.Nil) : G.Dart where
fst := v
snd := p.snd
adj := p.adj_snd hp
/-- The last dart of a walk. -/
@[simps]
def lastDart (p : G.Walk v w) (hp : ¬ p.Nil) : G.Dart where
fst := p.penultimate
snd := w
adj := p.adj_penultimate hp
lemma edge_firstDart (p : G.Walk v w) (hp : ¬ p.Nil) :
(p.firstDart hp).edge = s(v, p.snd) := rfl
lemma edge_lastDart (p : G.Walk v w) (hp : ¬ p.Nil) :
(p.lastDart hp).edge = s(p.penultimate, w) := rfl
theorem firstDart_eq {p : G.Walk v w} (h₁ : ¬ p.Nil) (h₂ : 0 < p.darts.length) :
p.firstDart h₁ = p.darts[0] := by
simp [Dart.ext_iff, firstDart_toProd, darts_getElem_eq_getVert]
theorem lastDart_eq {p : G.Walk v w} (h₁ : ¬ p.Nil) (h₂ : 0 < p.darts.length) :
p.lastDart h₁ = p.darts[p.darts.length - 1] := by
simp (disch := grind) [Dart.ext_iff, lastDart_toProd, darts_getElem_eq_getVert,
p.getVert_of_length_le]
lemma cons_tail_eq (p : G.Walk u v) (hp : ¬ p.Nil) :
cons (p.adj_snd hp) p.tail = p := by
cases p <;> simp at hp ⊢
@[simp]
lemma concat_dropLast (p : G.Walk u v) (hp : G.Adj p.penultimate v) :
p.dropLast.concat hp = p := by
induction p with
| nil => simp at hp
| cons hadj p hind =>
cases p with
| nil => rfl
| _ => simp [hind]
@[simp] lemma cons_support_tail (p : G.Walk u v) (hp : ¬p.Nil) :
u :: p.tail.support = p.support := by
rw [← support_cons (p.adj_snd hp), cons_tail_eq _ hp]
@[simp] lemma length_tail_add_one {p : G.Walk u v} (hp : ¬ p.Nil) :
p.tail.length + 1 = p.length := by
rw [← length_cons (p.adj_snd hp), cons_tail_eq _ hp]
protected lemma Nil.tail {p : G.Walk v w} (hp : p.Nil) : p.tail.Nil := by
cases p <;> simp [not_nil_cons] at hp ⊢
lemma not_nil_of_tail_not_nil {p : G.Walk v w} (hp : ¬ p.tail.Nil) : ¬ p.Nil := mt Nil.tail hp
@[simp] lemma nil_copy {u' v' : V} {p : G.Walk u v} (hu : u = u') (hv : v = v') :
(p.copy hu hv).Nil = p.Nil := by
subst_vars
rfl
lemma support_tail_of_not_nil (p : G.Walk u v) (hp : ¬ p.Nil) :
p.tail.support = p.support.tail := by
rw [← cons_support_tail p hp, List.tail_cons]
@[deprecated (since := "2025-08-26")] alias support_tail := support_tail_of_not_nil
/-- Given a set `S` and a walk `w` from `u` to `v` such that `u ∈ S` but `v ∉ S`,
there exists a dart in the walk whose start is in `S` but whose end is not. -/
theorem exists_boundary_dart {u v : V} (p : G.Walk u v) (S : Set V) (uS : u ∈ S) (vS : v ∉ S) :
∃ d : G.Dart, d ∈ p.darts ∧ d.fst ∈ S ∧ d.snd ∉ S := by
induction p with
| nil => cases vS uS
| cons a p' ih =>
rename_i x _
by_cases h : x ∈ S
· obtain ⟨d, hd, hcd⟩ := ih h vS
exact ⟨d, List.Mem.tail _ hd, hcd⟩
· exact ⟨⟨_, a⟩, List.Mem.head _, uS, h⟩
@[simp] lemma getVert_copy {u v w x : V} (p : G.Walk u v) (i : ℕ) (h : u = w) (h' : v = x) :
(p.copy h h').getVert i = p.getVert i := by
subst_vars
rfl
@[simp] lemma getVert_tail {u v n} (p : G.Walk u v) :
p.tail.getVert n = p.getVert (n + 1) := by
cases p <;> simp
lemma ext_support {u v} {p q : G.Walk u v} (h : p.support = q.support) :
p = q := by
induction q with
| nil => exact nil_iff_eq_nil.mp (nil_iff_support_eq.mpr (support_nil ▸ h))
| cons ha q ih =>
cases p with
| nil => simp at h
| cons _ p =>
simp only [support_cons, List.cons.injEq, true_and] at h
apply List.getElem_of_eq at h
specialize h (i := 0) (by simp)
simp_rw [List.getElem_zero, p.head_support, q.head_support] at h
have : (p.copy h rfl).support = q.support := by simpa
simp [← ih this]
lemma support_injective {u v : V} : (support (G := G) (u := u) (v := v)).Injective :=
fun _ _ ↦ ext_support
lemma ext_getVert_le_length {u v} {p q : G.Walk u v} (hl : p.length = q.length)
(h : ∀ k ≤ p.length, p.getVert k = q.getVert k) :
p = q := by
suffices ∀ k : ℕ, p.support[k]? = q.support[k]? by
exact ext_support <| List.ext_getElem?_iff.mpr this
intro k
cases le_or_gt k p.length with
| inl hk =>
rw [← getVert_eq_support_getElem? p hk, ← getVert_eq_support_getElem? q (hl ▸ hk)]
exact congrArg some (h k hk)
| inr hk =>
replace hk : p.length + 1 ≤ k := hk
have ht : q.length + 1 ≤ k := hl ▸ hk
rw [← length_support, ← List.getElem?_eq_none_iff] at hk ht
rw [hk, ht]
lemma ext_getVert {u v} {p q : G.Walk u v} (h : ∀ k, p.getVert k = q.getVert k) :
p = q := by
wlog hpq : p.length ≤ q.length generalizing p q
· exact (this (h · |>.symm) (le_of_not_ge hpq)).symm
refine ext_getVert_le_length (hpq.antisymm ?_) fun k _ ↦ h k
by_contra!
exact (q.adj_getVert_succ this).ne (by simp [← h, getVert_of_length_le])
end Walk
/-! ### Mapping walks -/
namespace Walk
variable {G G' G''}
/-- Given a graph homomorphism, map walks to walks. -/
protected def map (f : G →g G') {u v : V} : G.Walk u v → G'.Walk (f u) (f v)
| nil => nil
| cons h p => cons (f.map_adj h) (p.map f)
variable (f : G →g G') (f' : G' →g G'') {u v u' v' : V} (p : G.Walk u v)
@[simp]
theorem map_nil : (nil : G.Walk u u).map f = nil := rfl
@[simp]
theorem map_cons {w : V} (h : G.Adj w u) : (cons h p).map f = cons (f.map_adj h) (p.map f) := rfl
@[simp]
theorem map_copy (hu : u = u') (hv : v = v') :
(p.copy hu hv).map f = (p.map f).copy (hu ▸ rfl) (hv ▸ rfl) := by
subst_vars
rfl
@[simp]
theorem map_id (p : G.Walk u v) : p.map Hom.id = p := by
induction p <;> simp [*]
@[simp]
theorem map_map : (p.map f).map f' = p.map (f'.comp f) := by
induction p <;> simp [*]
/-- Unlike categories, for graphs vertex equality is an important notion, so needing to be able to
work with equality of graph homomorphisms is a necessary evil. -/
theorem map_eq_of_eq {f : G →g G'} (f' : G →g G') (h : f = f') :
p.map f = (p.map f').copy (h ▸ rfl) (h ▸ rfl) := by
subst_vars
rfl
@[simp]
theorem map_eq_nil_iff {p : G.Walk u u} : p.map f = nil ↔ p = nil := by cases p <;> simp
@[simp]
theorem length_map : (p.map f).length = p.length := by induction p <;> simp [*]
theorem map_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) :
(p.append q).map f = (p.map f).append (q.map f) := by induction p <;> simp [*]
@[simp]
theorem reverse_map : (p.map f).reverse = p.reverse.map f := by induction p <;> simp [map_append, *]
@[simp]
theorem support_map : (p.map f).support = p.support.map f := by induction p <;> simp [*]
@[simp]
theorem darts_map : (p.map f).darts = p.darts.map f.mapDart := by induction p <;> simp [*]
@[simp]
theorem edges_map : (p.map f).edges = p.edges.map (Sym2.map f) := by
induction p <;> simp [*]
@[simp]
theorem edgeSet_map : (p.map f).edgeSet = Sym2.map f '' p.edgeSet := by ext; simp
theorem map_injective_of_injective {f : G →g G'} (hinj : Function.Injective f) (u v : V) :
Function.Injective (Walk.map f : G.Walk u v → G'.Walk (f u) (f v)) := by
intro p p' h
induction p with
| nil => cases p' <;> simp at h ⊢
| cons _ _ ih =>
cases p' with
| nil => simp at h
| cons _ _ =>
simp only [map_cons, cons.injEq] at h
cases hinj h.1
grind
section mapLe
variable {G G' : SimpleGraph V} (h : G ≤ G') {u v : V} (p : G.Walk u v)
/-- The specialization of `SimpleGraph.Walk.map` for mapping walks to supergraphs. -/
abbrev mapLe : G'.Walk u v :=
p.map (.ofLE h)
lemma support_mapLe_eq_support : (p.mapLe h).support = p.support := by simp
lemma edges_mapLe_eq_edges : (p.mapLe h).edges = p.edges := by simp
lemma edgeSet_mapLe_eq_edgeSet : (p.mapLe h).edgeSet = p.edgeSet := by simp
end mapLe
/-! ### Transferring between graphs -/
/-- The walk `p` transferred to lie in `H`, given that `H` contains its edges. -/
@[simp]
protected def transfer {u v : V} (p : G.Walk u v)
(H : SimpleGraph V) (h : ∀ e, e ∈ p.edges → e ∈ H.edgeSet) : H.Walk u v :=
match p with
| nil => nil
| cons' u v w _ p =>
cons (h s(u, v) (by simp)) (p.transfer H fun e he => h e (by simp [he]))
variable {u v : V} (p : G.Walk u v)
theorem transfer_self : p.transfer G p.edges_subset_edgeSet = p := by
induction p <;> simp [*]
variable {H : SimpleGraph V}
theorem transfer_eq_map_ofLE (hp) (GH : G ≤ H) : p.transfer H hp = p.map (.ofLE GH) := by
induction p <;> simp [*]
@[simp]
theorem edges_transfer (hp) : (p.transfer H hp).edges = p.edges := by
induction p <;> simp [*]
@[simp]
theorem edgeSet_transfer (hp) : (p.transfer H hp).edgeSet = p.edgeSet := by ext; simp
@[simp]
theorem support_transfer (hp) : (p.transfer H hp).support = p.support := by
induction p <;> simp [*]
@[simp]
theorem length_transfer (hp) : (p.transfer H hp).length = p.length := by
induction p <;> simp [*]
@[simp]
theorem transfer_transfer (hp) {K : SimpleGraph V} (hp') :
(p.transfer H hp).transfer K hp' = p.transfer K (p.edges_transfer hp ▸ hp') := by
induction p <;> simp [*]
@[simp]
theorem transfer_append {w : V} (q : G.Walk v w) (hpq) :
(p.append q).transfer H hpq =
(p.transfer H fun e he => hpq _ (by simp [he])).append
(q.transfer H fun e he => hpq _ (by simp [he])) := by
induction p <;> simp [*]
@[simp]
theorem reverse_transfer (hp) :
(p.transfer H hp).reverse =
p.reverse.transfer H (by simp only [edges_reverse, List.mem_reverse]; exact hp) := by
induction p <;> simp [*]
/-! ### Inducing a walk -/
variable {s s' : Set V}
variable (s) in
/-- A walk in `G` which is fully contained in a set `s` of vertices lifts to a walk of `G[s]`. -/
protected def induce {u v : V} :
∀ (w : G.Walk u v) (hw : ∀ x ∈ w.support, x ∈ s),
(G.induce s).Walk ⟨u, hw _ w.start_mem_support⟩ ⟨v, hw _ w.end_mem_support⟩
| nil, hw => nil
| cons (v := u') huu' w, hw => .cons (induce_adj.2 huu') <| w.induce <| by simp_all
@[simp] lemma induce_nil (hw) : (.nil : G.Walk u u).induce s hw = .nil := rfl
@[simp] lemma induce_cons (huu' : G.Adj u u') (w : G.Walk u' v) (hw) :
(w.cons huu').induce s hw = .cons (induce_adj.2 huu') (w.induce s <| by simp_all) := rfl
@[simp] lemma support_induce {u v : V} :
∀ (w : G.Walk u v) (hw), (w.induce s hw).support = w.support.attachWith _ hw
| .nil, hw => rfl
| .cons (v := u') hu w, hw => by simp [support_induce]
@[simp] lemma map_induce {u v : V} :
∀ (w : G.Walk u v) (hw), (w.induce s hw).map (Embedding.induce _).toHom = w
| .nil, hw => rfl
| .cons (v := u') huu' w, hw => by simp [map_induce]
lemma map_induce_induceHomOfLE (hs : s ⊆ s') {u v : V} : ∀ (w : G.Walk u v) (hw),
(w.induce s hw).map (G.induceHomOfLE hs).toHom = w.induce s' (subset_trans hw hs)
| .nil, hw => rfl
| .cons (v := u') huu' w, hw => by simp [map_induce_induceHomOfLE]
end Walk
/-! ## Deleting edges -/
namespace Walk
variable {G}
/-- Given a walk that avoids a set of edges, produce a walk in the graph
with those edges deleted. -/
abbrev toDeleteEdges (s : Set (Sym2 V)) {v w : V} (p : G.Walk v w)
(hp : ∀ e, e ∈ p.edges → e ∉ s) : (G.deleteEdges s).Walk v w :=
p.transfer _ <| by
simp only [edgeSet_deleteEdges, Set.mem_diff]
exact fun e ep => ⟨edges_subset_edgeSet p ep, hp e ep⟩
@[simp]
theorem toDeleteEdges_nil (s : Set (Sym2 V)) {v : V} (hp) :
(Walk.nil : G.Walk v v).toDeleteEdges s hp = Walk.nil := rfl
@[simp]
theorem toDeleteEdges_cons (s : Set (Sym2 V)) {u v w : V} (h : G.Adj u v) (p : G.Walk v w) (hp) :
(Walk.cons h p).toDeleteEdges s hp =
Walk.cons (deleteEdges_adj.mpr ⟨h, hp _ (List.Mem.head _)⟩)
(p.toDeleteEdges s fun _ he => hp _ <| List.Mem.tail _ he) :=
rfl
variable {v w : V}
/-- Given a walk that avoids an edge, create a walk in the subgraph with that edge deleted.
This is an abbreviation for `SimpleGraph.Walk.toDeleteEdges`. -/
abbrev toDeleteEdge (e : Sym2 V) (p : G.Walk v w) (hp : e ∉ p.edges) :
(G.deleteEdges {e}).Walk v w :=
p.toDeleteEdges {e} (fun _ => by contrapose!; simp +contextual [hp])
@[simp]
theorem map_toDeleteEdges_eq (s : Set (Sym2 V)) {p : G.Walk v w} (hp) :
Walk.map (.ofLE (G.deleteEdges_le s)) (p.toDeleteEdges s hp) = p := by
rw [← transfer_eq_map_ofLE, transfer_transfer, transfer_self]
apply edges_transfer _ _ ▸ p.edges_subset_edgeSet
end Walk
/-! ## Subwalks -/
namespace Walk
variable {V : Type*} {G : SimpleGraph V}
/-- `p.IsSubwalk q` means that the walk `p` is a contiguous subwalk of the walk `q`. -/
def IsSubwalk {u₁ v₁ u₂ v₂} (p : G.Walk u₁ v₁) (q : G.Walk u₂ v₂) : Prop :=
∃ (ru : G.Walk u₂ u₁) (rv : G.Walk v₁ v₂), q = (ru.append p).append rv
@[refl, simp]
lemma isSubwalk_rfl {u v} (p : G.Walk u v) : p.IsSubwalk p :=
⟨nil, nil, by simp⟩
@[simp]
lemma nil_isSubwalk {u v} (q : G.Walk u v) : (Walk.nil : G.Walk u u).IsSubwalk q :=
⟨nil, q, by simp⟩
protected lemma IsSubwalk.cons {u v u' v' w} {p : G.Walk u v} {q : G.Walk u' v'}
(hpq : p.IsSubwalk q) (h : G.Adj w u') : p.IsSubwalk (q.cons h) := by
obtain ⟨r1, r2, rfl⟩ := hpq
use r1.cons h, r2
simp
@[simp]
lemma isSubwalk_cons {u v w} (p : G.Walk u v) (h : G.Adj w u) : p.IsSubwalk (p.cons h) :=
(isSubwalk_rfl p).cons h
lemma IsSubwalk.trans {u₁ v₁ u₂ v₂ u₃ v₃} {p₁ : G.Walk u₁ v₁} {p₂ : G.Walk u₂ v₂}
{p₃ : G.Walk u₃ v₃} (h₁ : p₁.IsSubwalk p₂) (h₂ : p₂.IsSubwalk p₃) :
p₁.IsSubwalk p₃ := by
obtain ⟨q₁, r₁, rfl⟩ := h₁
obtain ⟨q₂, r₂, rfl⟩ := h₂
use q₂.append q₁, r₁.append r₂
simp only [append_assoc]
lemma isSubwalk_nil_iff {u v u'} (p : G.Walk u v) :
p.IsSubwalk (nil : G.Walk u' u') ↔ ∃ (hu : u' = u) (hv : u' = v), p = nil.copy hu hv := by
cases p with
| nil =>
constructor
· rintro ⟨_ | _, _, ⟨⟩⟩
simp
· rintro ⟨rfl, _, _⟩
simp
| cons h p =>
constructor
· rintro ⟨_ | _, _, h⟩ <;> simp at h
· rintro ⟨rfl, rfl, ⟨⟩⟩
lemma nil_isSubwalk_iff_exists {u' u v} (q : G.Walk u v) :
(Walk.nil : G.Walk u' u').IsSubwalk q ↔
∃ (ru : G.Walk u u') (rv : G.Walk u' v), q = ru.append rv := by
simp [IsSubwalk]
lemma length_le_of_isSubwalk {u₁ v₁ u₂ v₂} {q : G.Walk u₁ v₁} {p : G.Walk u₂ v₂}
(h : p.IsSubwalk q) : p.length ≤ q.length := by
grind [IsSubwalk, length_append]
lemma isSubwalk_of_append_left {v w u : V} {p₁ : G.Walk v w} {p₂ : G.Walk w u} {p₃ : G.Walk v u}
(h : p₃ = p₁.append p₂) : p₁.IsSubwalk p₃ :=
⟨nil, p₂, h⟩
lemma isSubwalk_of_append_right {v w u : V} {p₁ : G.Walk v w} {p₂ : G.Walk w u} {p₃ : G.Walk v u}
(h : p₃ = p₁.append p₂) : p₂.IsSubwalk p₃ :=
⟨p₁, nil, append_nil _ ▸ h⟩
theorem isSubwalk_iff_support_isInfix {v w v' w' : V} {p₁ : G.Walk v w} {p₂ : G.Walk v' w'} :
p₁.IsSubwalk p₂ ↔ p₁.support <:+: p₂.support := by
refine ⟨fun ⟨ru, rv, h⟩ ↦ ?_, fun ⟨s, t, h⟩ ↦ ?_⟩
· grind [support_append, support_append_eq_support_dropLast_append]
· have : (s.length + p₁.length) ≤ p₂.length := by grind [_=_ length_support]
refine ⟨p₂.take s.length |>.copy rfl ?_, p₂.drop (s.length + p₁.length) |>.copy ?_ rfl, ?_⟩
· simp [p₂.getVert_eq_support_getElem (by cutsat : s.length ≤ p₂.length), ← h,
List.getElem_zero]
· simp [p₂.getVert_eq_support_getElem (by omega), ← h, ← p₁.getVert_eq_support_getElem le_rfl]
apply ext_support
simp only [← h, support_append, support_copy, take_support_eq_support_take_succ,
List.take_append, drop_support_eq_support_drop_min, List.tail_drop]
rw [Nat.min_eq_left (by grind [length_support]), List.drop_append, List.drop_append,
List.drop_eq_nil_of_le (by cutsat), List.drop_eq_nil_of_le (by grind [length_support]),
p₁.support_eq_cons]
simp +arith
lemma isSubwalk_antisymm {u v} {p₁ p₂ : G.Walk u v} (h₁ : p₁.IsSubwalk p₂) (h₂ : p₂.IsSubwalk p₁) :
p₁ = p₂ := by
rw [isSubwalk_iff_support_isInfix] at h₁ h₂
exact ext_support <| List.infix_antisymm h₁ h₂
end Walk
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Copy.lean | import Mathlib.Algebra.Order.Group.Nat
import Mathlib.Combinatorics.SimpleGraph.Subgraph
/-!
# Containment of graphs
This file introduces the concept of one simple graph containing a copy of another.
For two simple graphs `G` and `H`, a *copy* of `G` in `H` is a (not necessarily induced) subgraph of
`H` isomorphic to `G`.
If there exists a copy of `G` in `H`, we say that `H` *contains* `G`. This is equivalent to saying
that there is an injective graph homomorphism `G → H` between them (this is **not** the same as a
graph embedding, as we do not require the subgraph to be induced).
If there exists an induced copy of `G` in `H`, we say that `H` *inducingly contains* `G`. This is
equivalent to saying that there is a graph embedding `G ↪ H`.
## Main declarations
Containment:
* `SimpleGraph.Copy G H` is the type of copies of `G` in `H`, implemented as the subtype of
*injective* homomorphisms.
* `SimpleGraph.IsContained G H`, `G ⊑ H` is the relation that `H` contains a copy of `G`, that
is, the type of copies of `G` in `H` is nonempty. This is equivalent to the existence of an
isomorphism from `G` to a subgraph of `H`.
This is similar to `SimpleGraph.IsSubgraph` except that the simple graphs here need not have the
same underlying vertex type.
* `SimpleGraph.Free` is the predicate that `H` is `G`-free, that is, `H` does not contain a copy of
`G`. This is the negation of `SimpleGraph.IsContained` implemented for convenience.
* `SimpleGraph.killCopies G H`: Subgraph of `G` that does not contain `H`. Obtained by arbitrarily
removing an edge from each copy of `H` in `G`.
* `SimpleGraph.copyCount G H`: Number of copies of `H` in `G`, i.e. number of subgraphs of `G`
isomorphic to `H`.
* `SimpleGraph.labelledCopyCount G H`: Number of labelled copies of `H` in `G`, i.e. number of
graph embeddings from `H` to `G`.
Induced containment:
* Induced copies of `G` inside `H` are already defined as `G ↪g H`.
* `SimpleGraph.IsIndContained G H` : `G` is contained as an induced subgraph in `H`.
## Notation
The following notation is declared in scope `SimpleGraph`:
* `G ⊑ H` for `SimpleGraph.IsContained G H`.
* `G ⊴ H` for `SimpleGraph.IsIndContained G H`.
## TODO
* Relate `⊥ ⊴ H` to there being an independent set in `H`.
* Count induced copies of a graph inside another.
* Make `copyCount`/`labelledCopyCount` computable (not necessarily efficiently).
-/
open Finset Function
open Fintype (card)
namespace SimpleGraph
variable {V W X α β γ : Type*} {G G₁ G₂ G₃ : SimpleGraph V} {H : SimpleGraph W} {I : SimpleGraph X}
{A : SimpleGraph α} {B : SimpleGraph β} {C : SimpleGraph γ}
/-!
### Copies
#### Not necessarily induced copies
A copy of a subgraph `G` inside a subgraph `H` is an embedding of the vertices of `G` into the
vertices of `H`, such that adjacency in `G` implies adjacency in `H`.
We capture this concept by injective graph homomorphisms.
-/
section Copy
/-- The type of copies as a subtype of *injective* homomorphisms. -/
structure Copy (A : SimpleGraph α) (B : SimpleGraph β) where
/-- A copy gives rise to a homomorphism. -/
toHom : A →g B
injective' : Injective toHom
/-- An injective homomorphism gives rise to a copy. -/
abbrev Hom.toCopy (f : A →g B) (h : Injective f) : Copy A B := .mk f h
/-- An embedding gives rise to a copy. -/
abbrev Embedding.toCopy (f : A ↪g B) : Copy A B := f.toHom.toCopy f.injective
/-- An isomorphism gives rise to a copy. -/
abbrev Iso.toCopy (f : A ≃g B) : Copy A B := f.toEmbedding.toCopy
namespace Copy
instance : FunLike (Copy A B) α β where
coe f := DFunLike.coe f.toHom
coe_injective' f g h := by obtain ⟨⟨_, _⟩, _⟩ := f; congr!
lemma injective (f : Copy A B) : Injective f.toHom := f.injective'
@[ext] lemma ext {f g : Copy A B} : (∀ a, f a = g a) → f = g := DFunLike.ext _ _
@[simp] lemma coe_toHom (f : Copy A B) : ⇑f.toHom = f := rfl
@[simp] lemma toHom_apply (f : Copy A B) (a : α) : ⇑f.toHom a = f a := rfl
@[simp] lemma coe_mk (f : A →g B) (hf) : ⇑(.mk f hf : Copy A B) = f := rfl
/-- A copy induces an embedding of edge sets. -/
def mapEdgeSet (f : Copy A B) : A.edgeSet ↪ B.edgeSet where
toFun := f.toHom.mapEdgeSet
inj' := Hom.mapEdgeSet.injective f.toHom f.injective
/-- A copy induces an embedding of neighbor sets. -/
def mapNeighborSet (f : Copy A B) (a : α) :
A.neighborSet a ↪ B.neighborSet (f a) where
toFun v := ⟨f v, f.toHom.apply_mem_neighborSet v.prop⟩
inj' _ _ h := by
rw [Subtype.mk_eq_mk] at h ⊢
exact f.injective h
/-- A copy gives rise to an embedding of vertex types. -/
def toEmbedding (f : Copy A B) : α ↪ β := ⟨f, f.injective⟩
/-- The identity copy from a simple graph to itself. -/
@[refl] def id (G : SimpleGraph V) : Copy G G := ⟨Hom.id, Function.injective_id⟩
@[simp, norm_cast] lemma coe_id : ⇑(id G) = _root_.id := rfl
/-- The composition of copies is a copy. -/
def comp (g : Copy B C) (f : Copy A B) : Copy A C := by
use g.toHom.comp f.toHom
rw [Hom.coe_comp]
exact g.injective.comp f.injective
@[simp]
theorem comp_apply (g : Copy B C) (f : Copy A B) (a : α) : g.comp f a = g (f a) :=
RelHom.comp_apply g.toHom f.toHom a
/-- The copy from a subgraph to the supergraph. -/
def ofLE (G₁ G₂ : SimpleGraph V) (h : G₁ ≤ G₂) : Copy G₁ G₂ := ⟨Hom.ofLE h, Function.injective_id⟩
@[simp, norm_cast]
theorem coe_comp (g : Copy B C) (f : Copy A B) : ⇑(g.comp f) = g ∘ f := by ext; simp
@[simp, norm_cast] lemma coe_ofLE (h : G₁ ≤ G₂) : ⇑(ofLE G₁ G₂ h) = _root_.id := rfl
@[simp] theorem ofLE_refl : ofLE G G le_rfl = id G := by ext; simp
@[simp]
theorem ofLE_comp (h₁₂ : G₁ ≤ G₂) (h₂₃ : G₂ ≤ G₃) :
(ofLE _ _ h₂₃).comp (ofLE _ _ h₁₂) = ofLE _ _ (h₁₂.trans h₂₃) := by ext; simp
/-- The copy from an induced subgraph to the initial simple graph. -/
def induce (G : SimpleGraph V) (s : Set V) : Copy (G.induce s) G := (Embedding.induce s).toCopy
/-- The copy of `⊥` in any simple graph that can embed its vertices. -/
protected def bot (f : α ↪ β) : Copy (⊥ : SimpleGraph α) B := ⟨⟨f, False.elim⟩, f.injective⟩
/-- The isomorphism from a subgraph of `A` to its map under a copy `f : Copy A B`. -/
noncomputable def isoSubgraphMap (f : Copy A B) (A' : A.Subgraph) :
A'.coe ≃g (A'.map f.toHom).coe := by
use Equiv.Set.image f.toHom _ f.injective
simp_rw [Subgraph.map_verts, Equiv.Set.image_apply, Subgraph.coe_adj, Subgraph.map_adj,
Relation.map_apply, f.injective.eq_iff, exists_eq_right_right, exists_eq_right, forall_true_iff]
/-- The subgraph of `B` corresponding to a copy of `A` inside `B`. -/
abbrev toSubgraph (f : Copy A B) : B.Subgraph := .map f.toHom ⊤
/-- The isomorphism from `A` to its copy under `f : Copy A B`. -/
noncomputable def isoToSubgraph (f : Copy A B) : A ≃g f.toSubgraph.coe :=
(f.isoSubgraphMap ⊤).comp Subgraph.topIso.symm
@[simp] lemma range_toSubgraph :
.range (toSubgraph (A := A)) = {B' : B.Subgraph | Nonempty (A ≃g B'.coe)} := by
ext H'
constructor
· rintro ⟨f, hf, rfl⟩
simpa [toSubgraph] using ⟨f.isoToSubgraph⟩
· rintro ⟨e⟩
refine ⟨⟨H'.hom.comp e.toHom, Subgraph.hom_injective.comp e.injective⟩, ?_⟩
simp [toSubgraph, Subgraph.map_comp]
lemma toSubgraph_surjOn :
Set.SurjOn (toSubgraph (A := A)) .univ {B' : B.Subgraph | Nonempty (A ≃g B'.coe)} :=
fun H' hH' ↦ by simpa
instance [Subsingleton (V → W)] : Subsingleton (G.Copy H) := DFunLike.coe_injective.subsingleton
instance [Fintype {f : G →g H // Injective f}] : Fintype (G.Copy H) :=
.ofEquiv {f : G →g H // Injective f} {
toFun f := ⟨f.1, f.2⟩
invFun f := ⟨f.1, f.2⟩
}
/-- A copy of `⊤` gives rise to an embedding of `⊤`. -/
@[simps!]
def topEmbedding (f : Copy (⊤ : SimpleGraph α) G) : (⊤ : SimpleGraph α) ↪g G :=
{ f.toEmbedding with
map_rel_iff' := fun {v w} ↦ ⟨fun h ↦ by simpa using h.ne, f.toHom.map_adj⟩}
end Copy
/-- A `Subgraph G` gives rise to a copy from the coercion to `G`. -/
def Subgraph.coeCopy (G' : G.Subgraph) : Copy G'.coe G := G'.hom.toCopy hom_injective
end Copy
/-!
#### Induced copies
An induced copy of a graph `G` inside a graph `H` is an embedding from the vertices of
`G` into the vertices of `H` which preserves the adjacency relation.
This is already captured by the notion of graph embeddings, defined as `G ↪g H`.
### Containment
#### Not necessarily induced containment
A graph `H` *contains* a graph `G` if there is some copy `f : Copy G H` of `G` inside `H`. This
amounts to `H` having a subgraph isomorphic to `G`.
We denote "`G` is contained in `H`" by `G ⊑ H` (`\squb`).
-/
section IsContained
/-- The relation `IsContained A B`, `A ⊑ B` says that `B` contains a copy of `A`.
This is equivalent to the existence of an isomorphism from `A` to a subgraph of `B`. -/
abbrev IsContained (A : SimpleGraph α) (B : SimpleGraph β) := Nonempty (Copy A B)
@[inherit_doc] scoped infixl:50 " ⊑ " => SimpleGraph.IsContained
/-- A simple graph contains itself. -/
@[refl] protected theorem IsContained.refl (G : SimpleGraph V) : G ⊑ G := ⟨.id G⟩
protected theorem IsContained.rfl : G ⊑ G := IsContained.refl G
/-- A simple graph contains its subgraphs. -/
theorem IsContained.of_le (h : G₁ ≤ G₂) : G₁ ⊑ G₂ := ⟨.ofLE G₁ G₂ h⟩
/-- If `A` contains `B` and `B` contains `C`, then `A` contains `C`. -/
theorem IsContained.trans : A ⊑ B → B ⊑ C → A ⊑ C := fun ⟨f⟩ ⟨g⟩ ↦ ⟨g.comp f⟩
/-- If `B` contains `C` and `A` contains `B`, then `A` contains `C`. -/
theorem IsContained.trans' : B ⊑ C → A ⊑ B → A ⊑ C := flip IsContained.trans
lemma IsContained.mono_right {B' : SimpleGraph β} (h_isub : A ⊑ B) (h_sub : B ≤ B') : A ⊑ B' :=
h_isub.trans <| IsContained.of_le h_sub
alias IsContained.trans_le := IsContained.mono_right
lemma IsContained.mono_left {A' : SimpleGraph α} (h_sub : A ≤ A') (h_isub : A' ⊑ B) : A ⊑ B :=
(IsContained.of_le h_sub).trans h_isub
alias IsContained.trans_le' := IsContained.mono_left
/-- If `A ≃g H` and `B ≃g G` then `A` is contained in `B` if and only if `H` is contained
in `G`. -/
theorem isContained_congr (e₁ : A ≃g H) (e₂ : B ≃g G) : A ⊑ B ↔ H ⊑ G :=
⟨.trans' ⟨e₂.toCopy⟩ ∘ .trans ⟨e₁.symm.toCopy⟩, .trans' ⟨e₂.symm.toCopy⟩ ∘ .trans ⟨e₁.toCopy⟩⟩
lemma isContained_congr_left (e₁ : A ≃g B) : A ⊑ C ↔ B ⊑ C := isContained_congr e₁ .refl
alias ⟨_, IsContained.congr_left⟩ := isContained_congr_left
lemma isContained_congr_right (e₂ : B ≃g C) : A ⊑ B ↔ A ⊑ C := isContained_congr .refl e₂
alias ⟨_, IsContained.congr_right⟩ := isContained_congr_right
/-- A simple graph having no vertices is contained in any simple graph. -/
lemma IsContained.of_isEmpty [IsEmpty α] : A ⊑ B :=
⟨⟨isEmptyElim, fun {a} ↦ isEmptyElim a⟩, isEmptyElim⟩
/-- `⊥` is contained in any simple graph having sufficiently many vertices. -/
lemma bot_isContained_iff_card_le [Fintype α] [Fintype β] :
(⊥ : SimpleGraph α) ⊑ B ↔ Fintype.card α ≤ Fintype.card β :=
⟨fun ⟨f⟩ ↦ Fintype.card_le_of_embedding f.toEmbedding,
fun h ↦ ⟨Copy.bot (Function.Embedding.nonempty_of_card_le h).some⟩⟩
protected alias IsContained.bot := bot_isContained_iff_card_le
/-- A simple graph `G` contains all `Subgraph G` coercions. -/
lemma Subgraph.coe_isContained (G' : G.Subgraph) : G'.coe ⊑ G := ⟨G'.coeCopy⟩
/-- `B` contains `A` if and only if `B` has a subgraph `B'` and `B'` is isomorphic to `A`. -/
theorem isContained_iff_exists_iso_subgraph :
A ⊑ B ↔ ∃ B' : B.Subgraph, Nonempty (A ≃g B'.coe) where
mp := fun ⟨f⟩ ↦ ⟨.map f.toHom ⊤, ⟨f.isoToSubgraph⟩⟩
mpr := fun ⟨B', ⟨e⟩⟩ ↦ B'.coe_isContained.trans' ⟨e.toCopy⟩
alias ⟨IsContained.exists_iso_subgraph, IsContained.of_exists_iso_subgraph⟩ :=
isContained_iff_exists_iso_subgraph
end IsContained
section Free
/-- `A.Free B` means that `B` does not contain a copy of `A`. -/
abbrev Free (A : SimpleGraph α) (B : SimpleGraph β) := ¬A ⊑ B
lemma not_free : ¬A.Free B ↔ A ⊑ B := not_not
/-- If `A ≃g H` and `B ≃g G` then `B` is `A`-free if and only if `G` is `H`-free. -/
theorem free_congr (e₁ : A ≃g H) (e₂ : B ≃g G) : A.Free B ↔ H.Free G :=
(isContained_congr e₁ e₂).not
lemma free_congr_left (e₁ : A ≃g B) : A.Free C ↔ B.Free C := free_congr e₁ .refl
alias ⟨_, Free.congr_left⟩ := free_congr_left
lemma free_congr_right (e₂ : B ≃g C) : A.Free B ↔ A.Free C := free_congr .refl e₂
alias ⟨_, Free.congr_right⟩ := free_congr_right
lemma free_bot (h : A ≠ ⊥) : A.Free (⊥ : SimpleGraph β) := by
rw [← edgeSet_nonempty] at h
intro ⟨f, hf⟩
absurd f.map_mem_edgeSet h.choose_spec
rw [edgeSet_bot]
exact Set.notMem_empty (h.choose.map f)
end Free
/-!
#### Induced containment
A graph `H` *inducingly contains* a graph `G` if there is some graph embedding `G ↪ H`. This amounts
to `H` having an induced subgraph isomorphic to `G`.
We denote "`G` is inducingly contained in `H`" by `G ⊴ H` (`\trianglelefteq`).
-/
/-- A simple graph `G` is inducingly contained in a simple graph `H` if there exists an induced
subgraph of `H` isomorphic to `G`. This is denoted by `G ⊴ H`. -/
def IsIndContained (G : SimpleGraph V) (H : SimpleGraph W) : Prop := Nonempty (G ↪g H)
@[inherit_doc] scoped infixl:50 " ⊴ " => SimpleGraph.IsIndContained
protected lemma IsIndContained.isContained : G ⊴ H → G ⊑ H := fun ⟨f⟩ ↦ ⟨f.toCopy⟩
/-- If `G` is isomorphic to `H`, then `G` is inducingly contained in `H`. -/
protected lemma Iso.isIndContained (e : G ≃g H) : G ⊴ H := ⟨e⟩
/-- If `G` is isomorphic to `H`, then `H` is inducingly contained in `G`. -/
protected lemma Iso.isIndContained' (e : G ≃g H) : H ⊴ G := e.symm.isIndContained
protected lemma Subgraph.IsInduced.isIndContained {G' : G.Subgraph} (hG' : G'.IsInduced) :
G'.coe ⊴ G :=
⟨{ toFun := (↑)
inj' := Subtype.coe_injective
map_rel_iff' := hG'.adj.symm }⟩
@[refl] lemma IsIndContained.refl (G : SimpleGraph V) : G ⊴ G := ⟨Embedding.refl⟩
lemma IsIndContained.rfl : G ⊴ G := .refl _
@[trans] lemma IsIndContained.trans : G ⊴ H → H ⊴ I → G ⊴ I := fun ⟨f⟩ ⟨g⟩ ↦ ⟨g.comp f⟩
lemma IsIndContained.of_isEmpty [IsEmpty V] : G ⊴ H :=
⟨{ toFun := isEmptyElim
inj' := isEmptyElim
map_rel_iff' := fun {a} ↦ isEmptyElim a }⟩
lemma isIndContained_iff_exists_iso_subgraph :
G ⊴ H ↔ ∃ (H' : H.Subgraph) (_e : G ≃g H'.coe), H'.IsInduced := by
constructor
· rintro ⟨f⟩
refine ⟨Subgraph.map f.toHom ⊤, f.toCopy.isoToSubgraph, ?_⟩
simp [Subgraph.IsInduced, Relation.map_apply_apply, f.injective]
· rintro ⟨H', e, hH'⟩
exact e.isIndContained.trans hH'.isIndContained
alias ⟨IsIndContained.exists_iso_subgraph, IsIndContained.of_exists_iso_subgraph⟩ :=
isIndContained_iff_exists_iso_subgraph
@[simp] lemma top_isIndContained_iff_top_isContained :
(⊤ : SimpleGraph V) ⊴ H ↔ (⊤ : SimpleGraph V) ⊑ H :=
⟨IsIndContained.isContained, fun ⟨f⟩ ↦ ⟨f.topEmbedding⟩⟩
@[simp] lemma compl_isIndContained_compl : Gᶜ ⊴ Hᶜ ↔ G ⊴ H :=
Embedding.complEquiv.symm.nonempty_congr
protected alias ⟨IsIndContained.of_compl, IsIndContained.compl⟩ := compl_isIndContained_compl
/-!
### Counting the copies
If `G` and `H` are finite graphs, we can count the number of unlabelled and labelled copies of `G`
in `H`.
#### Not necessarily induced copies
-/
section LabelledCopyCount
variable [Fintype V] [Fintype W]
/-- `G.labelledCopyCount H` is the number of labelled copies of `H` in `G`, i.e. the number of graph
embeddings from `H` to `G`. See `SimpleGraph.copyCount` for the number of unlabelled copies. -/
noncomputable def labelledCopyCount (G : SimpleGraph V) (H : SimpleGraph W) : ℕ := by
classical exact Fintype.card (Copy H G)
@[simp] lemma labelledCopyCount_of_isEmpty [IsEmpty W] (G : SimpleGraph V) (H : SimpleGraph W) :
G.labelledCopyCount H = 1 := by
convert Fintype.card_unique
exact { default := ⟨default, isEmptyElim⟩, uniq := fun _ ↦ Subsingleton.elim _ _ }
@[simp] lemma labelledCopyCount_eq_zero : G.labelledCopyCount H = 0 ↔ H.Free G := by
simp [labelledCopyCount, Fintype.card_eq_zero_iff]
@[simp] lemma labelledCopyCount_pos : 0 < G.labelledCopyCount H ↔ H ⊑ G := by
simp [labelledCopyCount, IsContained, Fintype.card_pos_iff]
end LabelledCopyCount
section CopyCount
variable [Fintype V]
/-- `G.copyCount H` is the number of unlabelled copies of `H` in `G`, i.e. the number of subgraphs
of `G` isomorphic to `H`. See `SimpleGraph.labelledCopyCount` for the number of labelled copies. -/
noncomputable def copyCount (G : SimpleGraph V) (H : SimpleGraph W) : ℕ := by
classical exact #{G' : G.Subgraph | Nonempty (H ≃g G'.coe)}
lemma copyCount_eq_card_image_copyToSubgraph [Fintype {f : H →g G // Injective f}]
[DecidableEq G.Subgraph] :
copyCount G H = #((Finset.univ : Finset (H.Copy G)).image Copy.toSubgraph) := by
rw [copyCount]
congr
refine Finset.coe_injective ?_
simpa [-Copy.range_toSubgraph] using Copy.range_toSubgraph.symm
@[simp] lemma copyCount_eq_zero : G.copyCount H = 0 ↔ H.Free G := by
simp [copyCount, Free, -nonempty_subtype, isContained_iff_exists_iso_subgraph,
filter_eq_empty_iff]
@[simp] lemma copyCount_pos : 0 < G.copyCount H ↔ H ⊑ G := by
simp [copyCount, -nonempty_subtype, isContained_iff_exists_iso_subgraph, card_pos,
filter_nonempty_iff]
/-- There's at least as many labelled copies of `H` in `G` than unlabelled ones. -/
lemma copyCount_le_labelledCopyCount [Fintype W] : G.copyCount H ≤ G.labelledCopyCount H := by
classical rw [copyCount_eq_card_image_copyToSubgraph]; exact card_image_le
@[simp] lemma copyCount_bot (G : SimpleGraph V) : copyCount G (⊥ : SimpleGraph V) = 1 := by
classical
rw [copyCount]
convert card_singleton (α := G.Subgraph)
{ verts := .univ
Adj := ⊥
adj_sub := False.elim
edge_vert := False.elim }
simp only [eq_singleton_iff_unique_mem, mem_filter_univ, Nonempty.forall]
refine ⟨⟨⟨(Equiv.Set.univ _).symm, by simp⟩⟩, fun H' e ↦
Subgraph.ext ((set_fintype_card_eq_univ_iff _).1 <| Fintype.card_congr e.toEquiv.symm) ?_⟩
ext a b
simp only [Prop.bot_eq_false, Pi.bot_apply, iff_false]
exact fun hab ↦ e.symm.map_rel_iff.2 hab.coe
@[simp] lemma copyCount_of_isEmpty [IsEmpty W] (G : SimpleGraph V) (H : SimpleGraph W) :
G.copyCount H = 1 := by
cases nonempty_fintype W
exact (copyCount_le_labelledCopyCount.trans_eq <| labelledCopyCount_of_isEmpty ..).antisymm <|
copyCount_pos.2 <| .of_isEmpty
end CopyCount
/-!
#### Induced copies
TODO
### Killing a subgraph
An important aspect of graph containment is that we can remove not too many edges from a graph `H`
to get a graph `H'` that doesn't contain `G`.
#### Killing not necessarily induced copies
`SimpleGraph.killCopies G H` is a subgraph of `G` where an edge was removed from each copy of `H` in
`G`. By construction, it doesn't contain `H` and has at most the number of copies of `H` edges less
than `G`.
-/
private lemma aux (hH : H ≠ ⊥) {G' : G.Subgraph} :
Nonempty (H ≃g G'.coe) → G'.edgeSet.Nonempty := by
obtain ⟨e, he⟩ := edgeSet_nonempty.2 hH
rw [← Subgraph.image_coe_edgeSet_coe]
exact fun ⟨f⟩ ↦ Set.Nonempty.image _ ⟨_, f.map_mem_edgeSet_iff.2 he⟩
/-- `G.killCopies H` is a subgraph of `G` where an *arbitrary* edge was removed from each copy of
`H` in `G`. By construction, it doesn't contain `H` (unless `H` had no edges) and has at most the
number of copies of `H` edges less than `G`. See `free_killCopies` and
`le_card_edgeFinset_killCopies` for these two properties. -/
noncomputable irreducible_def killCopies (G : SimpleGraph V) (H : SimpleGraph W) :
SimpleGraph V := by
classical exact
if hH : H = ⊥ then G
else G.deleteEdges <| ⋃ (G' : G.Subgraph) (hG' : Nonempty (H ≃g G'.coe)), {(aux hH hG').some}
/-- Removing an edge from `G` for each subgraph isomorphic to `H` results in a subgraph of `G`. -/
lemma killCopies_le_left : G.killCopies H ≤ G := by
rw [killCopies]; split_ifs; exacts [le_rfl, deleteEdges_le _]
@[simp] lemma killCopies_bot (G : SimpleGraph V) : G.killCopies (⊥ : SimpleGraph W) = G := by
rw [killCopies]; exact dif_pos rfl
private lemma killCopies_of_ne_bot (hH : H ≠ ⊥) (G : SimpleGraph V) :
G.killCopies H =
G.deleteEdges (⋃ (G' : G.Subgraph) (hG' : Nonempty (H ≃g G'.coe)), {(aux hH hG').some}) := by
rw [killCopies]; exact dif_neg hH
/-- `G.killCopies H` has no effect on `G` if and only if `G` already contained no copies of `H`. See
`Free.killCopies_eq_left` for the reverse implication with no assumption on `H`. -/
lemma killCopies_eq_left (hH : H ≠ ⊥) : G.killCopies H = G ↔ H.Free G := by
simp only [killCopies_of_ne_bot hH, Set.disjoint_left, isContained_iff_exists_iso_subgraph,
@forall_swap _ G.Subgraph, deleteEdges_eq_self, Set.mem_iUnion,
not_exists, not_nonempty_iff, Nonempty.forall, Free]
exact forall_congr' fun G' ↦ ⟨fun h ↦ ⟨fun f ↦ h _
(Subgraph.edgeSet_subset _ <| (aux hH ⟨f⟩).choose_spec) f rfl⟩, fun h _ _ ↦ h.elim⟩
protected lemma Free.killCopies_eq_left (hHG : H.Free G) : G.killCopies H = G := by
obtain rfl | hH := eq_or_ne H ⊥
· exact killCopies_bot _
· exact (killCopies_eq_left hH).2 hHG
/-- Removing an edge from `G` for each subgraph isomorphic to `H` results in a graph that doesn't
contain `H`. -/
lemma free_killCopies (hH : H ≠ ⊥) : H.Free (G.killCopies H) := by
rw [killCopies_of_ne_bot hH, deleteEdges, Free, isContained_iff_exists_iso_subgraph]
rintro ⟨G', hHG'⟩
have hG' : (G'.map <| .ofLE (sdiff_le : G \ _ ≤ G)).edgeSet.Nonempty := by
rw [Subgraph.edgeSet_map]
exact (aux hH hHG').image _
set e := hG'.some with he
have : e ∈ _ := hG'.some_mem
clear_value e
rw [← Subgraph.image_coe_edgeSet_coe] at this
subst he
obtain ⟨e, he₀, he₁⟩ := this
let e' : Sym2 G'.verts := Sym2.map (Copy.isoSubgraphMap (.ofLE _ _ _) _).symm e
have he' : e' ∈ G'.coe.edgeSet := (Iso.map_mem_edgeSet_iff _).2 he₀
rw [Subgraph.edgeSet_coe] at he'
have := Subgraph.edgeSet_subset _ he'
simp only [edgeSet_sdiff, edgeSet_fromEdgeSet, edgeSet_sdiff_sdiff_isDiag, Set.mem_diff,
Set.mem_iUnion, not_exists] at this
refine this.2 (G'.map <| .ofLE sdiff_le) ⟨((Copy.ofLE _ _ _).isoSubgraphMap _).comp hHG'.some⟩ ?_
rw [Sym2.map_map, Set.mem_singleton_iff, ← he₁]
congr 1 with x
exact congr_arg _ (Equiv.Set.image_symm_apply _ _ injective_id _ _)
variable [Fintype G.edgeSet]
noncomputable instance killCopies.edgeSet.instFintype : Fintype (G.killCopies H).edgeSet :=
.ofInjective (Set.inclusion <| edgeSet_mono killCopies_le_left) <| Set.inclusion_injective _
/-- Removing an edge from `H` for each subgraph isomorphic to `G` means that the number of edges
we've removed is at most the number of copies of `G` in `H`. -/
lemma le_card_edgeFinset_killCopies [Fintype V] :
#G.edgeFinset - G.copyCount H ≤ #(G.killCopies H).edgeFinset := by
classical
obtain rfl | hH := eq_or_ne H ⊥
· simp
let f (G' : {G' : G.Subgraph // Nonempty (H ≃g G'.coe)}) := (aux hH G'.2).some
calc
_ = #G.edgeFinset - card {G' : G.Subgraph // Nonempty (H ≃g G'.coe)} := ?_
_ ≤ #G.edgeFinset - #(univ.image f) := Nat.sub_le_sub_left card_image_le _
_ = #G.edgeFinset - #(Set.range f).toFinset := by rw [Set.toFinset_range]
_ ≤ #(G.edgeFinset \ (Set.range f).toFinset) := le_card_sdiff ..
_ = #(G.killCopies H).edgeFinset := ?_
· simp only [Set.toFinset_card]
rw [← Set.toFinset_card, ← edgeFinset, copyCount, ← card_subtype, subtype_univ, card_univ]
simp only [killCopies_of_ne_bot, hH, Ne, not_false_iff,
Set.toFinset_card, edgeSet_deleteEdges]
simp only [Finset.sdiff_eq_inter_compl, Set.diff_eq, ← Set.iUnion_singleton_eq_range,
Set.coe_toFinset, coe_filter, Set.iUnion_subtype, ← Fintype.card_coe,
← Finset.coe_sort_coe, coe_inter, coe_compl, Set.coe_toFinset, Set.compl_iUnion,
Fintype.card_ofFinset, f]
/-- Removing an edge from `H` for each subgraph isomorphic to `G` means that the number of edges
we've removed is at most the number of copies of `G` in `H`. -/
lemma le_card_edgeFinset_killCopies_add_copyCount [Fintype V] :
#G.edgeFinset ≤ #(G.killCopies H).edgeFinset + G.copyCount H :=
tsub_le_iff_right.1 le_card_edgeFinset_killCopies
/-!
#### Killing induced copies
TODO
-/
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/DegreeSum.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Combinatorics.SimpleGraph.Dart
import Mathlib.Combinatorics.SimpleGraph.Finite
import Mathlib.Data.ZMod.Basic
/-!
# Degree-sum formula and handshaking lemma
The degree-sum formula is that the sum of the degrees of the vertices in
a finite graph is equal to twice the number of edges. The handshaking lemma,
a corollary, is that the number of odd-degree vertices is even.
## Main definitions
- `SimpleGraph.sum_degrees_eq_twice_card_edges` is the degree-sum formula.
- `SimpleGraph.even_card_odd_degree_vertices` is the handshaking lemma.
- `SimpleGraph.odd_card_odd_degree_vertices_ne` is that the number of odd-degree
vertices different from a given odd-degree vertex is odd.
- `SimpleGraph.exists_ne_odd_degree_of_exists_odd_degree` is that the existence of an
odd-degree vertex implies the existence of another one.
## Implementation notes
We give a combinatorial proof by using the facts that (1) the map from
darts to vertices is such that each fiber has cardinality the degree
of the corresponding vertex and that (2) the map from darts to edges is 2-to-1.
## Tags
simple graphs, sums, degree-sum formula, handshaking lemma
-/
assert_not_exists Field TwoSidedIdeal
open Finset
namespace SimpleGraph
universe u
variable {V : Type u} (G : SimpleGraph V)
section DegreeSum
variable [Fintype V] [DecidableRel G.Adj]
theorem dart_fst_fiber [DecidableEq V] (v : V) :
({d : G.Dart | d.fst = v} : Finset _) = univ.image (G.dartOfNeighborSet v) := by
ext d
simp only [mem_image, true_and, mem_filter, SetCoe.exists, mem_univ]
constructor
· rintro rfl
exact ⟨_, d.adj, by ext <;> rfl⟩
· rintro ⟨e, he, rfl⟩
rfl
theorem dart_fst_fiber_card_eq_degree [DecidableEq V] (v : V) :
#{d : G.Dart | d.fst = v} = G.degree v := by
simpa only [dart_fst_fiber, Finset.card_univ, card_neighborSet_eq_degree] using
card_image_of_injective univ (G.dartOfNeighborSet_injective v)
theorem dart_card_eq_sum_degrees : Fintype.card G.Dart = ∑ v, G.degree v := by
haveI := Classical.decEq V
simp only [← card_univ, ← dart_fst_fiber_card_eq_degree]
exact card_eq_sum_card_fiberwise (by simp)
variable {G} in
theorem Dart.edge_fiber [DecidableEq V] (d : G.Dart) :
({d' : G.Dart | d'.edge = d.edge} : Finset _) = {d, d.symm} :=
Finset.ext fun d' => by simpa using dart_edge_eq_iff d' d
theorem dart_edge_fiber_card [DecidableEq V] (e : Sym2 V) (h : e ∈ G.edgeSet) :
#{d : G.Dart | d.edge = e} = 2 := by
obtain ⟨v, w⟩ := e
let d : G.Dart := ⟨(v, w), h⟩
convert congr_arg card d.edge_fiber
rw [card_insert_of_notMem, card_singleton]
rw [mem_singleton]
exact d.symm_ne.symm
theorem dart_card_eq_twice_card_edges : Fintype.card G.Dart = 2 * #G.edgeFinset := by
classical
rw [← card_univ]
rw [@card_eq_sum_card_fiberwise _ _ _ Dart.edge _ G.edgeFinset fun d _h =>
by rw [mem_coe, mem_edgeFinset]; apply Dart.edge_mem]
rw [← mul_comm, sum_const_nat]
intro e h
apply G.dart_edge_fiber_card e
rwa [← mem_edgeFinset]
/-- The degree-sum formula. This is also known as the handshaking lemma, which might
more specifically refer to `SimpleGraph.even_card_odd_degree_vertices`. -/
theorem sum_degrees_eq_twice_card_edges : ∑ v, G.degree v = 2 * #G.edgeFinset :=
G.dart_card_eq_sum_degrees.symm.trans G.dart_card_eq_twice_card_edges
lemma two_mul_card_edgeFinset : 2 * #G.edgeFinset = #(univ.filter fun (x, y) ↦ G.Adj x y) := by
rw [← dart_card_eq_twice_card_edges, ← card_univ]
refine card_bij' (fun d _ ↦ (d.fst, d.snd)) (fun xy h ↦ ⟨xy, (mem_filter.1 h).2⟩) ?_ ?_ ?_ ?_
<;> simp
/-- The degree-sum formula only counting over the vertices that form edges.
See `SimpleGraph.sum_degrees_eq_twice_card_edges` for the general version. -/
theorem sum_degrees_support_eq_twice_card_edges :
∑ v ∈ G.support, G.degree v = 2 * #G.edgeFinset := by
classical
simp_rw [← sum_degrees_eq_twice_card_edges,
← sum_add_sum_compl G.support.toFinset, left_eq_add]
apply Finset.sum_eq_zero
intro v hv
rw [degree_eq_zero_iff_notMem_support]
rwa [mem_compl, Set.mem_toFinset] at hv
end DegreeSum
/-- The handshaking lemma. See also `SimpleGraph.sum_degrees_eq_twice_card_edges`. -/
theorem even_card_odd_degree_vertices [Fintype V] [DecidableRel G.Adj] :
Even #{v | Odd (G.degree v)} := by
classical
have h := congr_arg (fun n => ↑n : ℕ → ZMod 2) G.sum_degrees_eq_twice_card_edges
simp only [ZMod.natCast_self, zero_mul, Nat.cast_mul] at h
rw [Nat.cast_sum, ← sum_filter_ne_zero] at h
rw [sum_congr (g := fun _v ↦ (1 : ZMod 2)) rfl] at h
· simp only [mul_one, nsmul_eq_mul, sum_const, Ne] at h
rw [← ZMod.natCast_eq_zero_iff_even]
convert h
exact ZMod.natCast_ne_zero_iff_odd.symm
· intro v
rw [mem_filter_univ, Ne, ZMod.natCast_eq_zero_iff_even, ZMod.natCast_eq_one_iff_odd,
← Nat.not_even_iff_odd]
tauto
theorem odd_card_odd_degree_vertices_ne [Fintype V] [DecidableEq V] [DecidableRel G.Adj] (v : V)
(h : Odd (G.degree v)) : Odd #{w | w ≠ v ∧ Odd (G.degree w)} := by
rcases G.even_card_odd_degree_vertices with ⟨k, hg⟩
have hk : 0 < k := by
have hh : Finset.Nonempty {v : V | Odd (G.degree v)} := by
use v
rw [mem_filter_univ]
exact h
rwa [← card_pos, hg, ← two_mul, mul_pos_iff_of_pos_left] at hh
exact zero_lt_two
have hc : (fun w : V => w ≠ v ∧ Odd (G.degree w)) = fun w : V => Odd (G.degree w) ∧ w ≠ v := by
ext w
rw [and_comm]
simp only [hc]
rw [← filter_filter, filter_ne', card_erase_of_mem]
· refine ⟨k - 1, tsub_eq_of_eq_add <| hg.trans ?_⟩
cutsat
· rwa [mem_filter_univ]
theorem exists_ne_odd_degree_of_exists_odd_degree [Fintype V] [DecidableRel G.Adj] (v : V)
(h : Odd (G.degree v)) : ∃ w : V, w ≠ v ∧ Odd (G.degree w) := by
haveI := Classical.decEq V
rcases G.odd_card_odd_degree_vertices_ne v h with ⟨k, hg⟩
have hg' : 0 < #{w | w ≠ v ∧ Odd (G.degree w)} := by
rw [hg]
apply Nat.succ_pos
rcases card_pos.mp hg' with ⟨w, hw⟩
rw [mem_filter_univ] at hw
exact ⟨w, hw⟩
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Partition.lean | import Mathlib.Combinatorics.SimpleGraph.Coloring
/-!
# Graph partitions
This module provides an interface for dealing with partitions on simple graphs. A partition of
a graph `G`, with vertices `V`, is a set `P` of disjoint nonempty subsets of `V` such that:
* The union of the subsets in `P` is `V`.
* Each element of `P` is an independent set. (Each subset contains no pair of adjacent vertices.)
Graph partitions are graph colorings that do not name their colors. They are adjoint in the
following sense. Given a graph coloring, there is an associated partition from the set of color
classes, and given a partition, there is an associated graph coloring from using the partition's
subsets as colors. Going from graph colorings to partitions and back makes a coloring "canonical":
all colors are given a canonical name and unused colors are removed. Going from partitions to
graph colorings and back is the identity.
## Main definitions
* `SimpleGraph.Partition` is a structure to represent a partition of a simple graph
* `SimpleGraph.Partition.PartsCardLe` is whether a given partition is an `n`-partition.
(a partition with at most `n` parts).
* `SimpleGraph.Partitionable n` is whether a given graph is `n`-partite
* `SimpleGraph.Partition.toColoring` creates colorings from partitions
* `SimpleGraph.Coloring.toPartition` creates partitions from colorings
## Main statements
* `SimpleGraph.partitionable_iff_colorable` is that `n`-partitionability and
`n`-colorability are equivalent.
-/
assert_not_exists Field
universe u v
namespace SimpleGraph
variable {V : Type u} (G : SimpleGraph V)
/-- A `Partition` of a simple graph `G` is a structure constituted by
* `parts`: a set of subsets of the vertices `V` of `G`
* `isPartition`: a proof that `parts` is a proper partition of `V`
* `independent`: a proof that each element of `parts` doesn't have a pair of adjacent vertices
-/
structure Partition where
/-- `parts`: a set of subsets of the vertices `V` of `G`. -/
parts : Set (Set V)
/-- `isPartition`: a proof that `parts` is a proper partition of `V`. -/
isPartition : Setoid.IsPartition parts
/-- `independent`: a proof that each element of `parts` doesn't have a pair of adjacent vertices.
-/
independent : ∀ s ∈ parts, IsAntichain G.Adj s
/-- Whether a partition `P` has at most `n` parts. A graph with a partition
satisfying this predicate called `n`-partite. (See `SimpleGraph.Partitionable`.) -/
def Partition.PartsCardLe {G : SimpleGraph V} (P : G.Partition) (n : ℕ) : Prop :=
∃ h : P.parts.Finite, h.toFinset.card ≤ n
/-- Whether a graph is `n`-partite, which is whether its vertex set
can be partitioned in at most `n` independent sets. -/
def Partitionable (n : ℕ) : Prop := ∃ P : G.Partition, P.PartsCardLe n
namespace Partition
variable {G}
variable (P : G.Partition)
/-- The part in the partition that `v` belongs to -/
def partOfVertex (v : V) : Set V := Classical.choose (P.isPartition.2 v)
theorem partOfVertex_mem (v : V) : P.partOfVertex v ∈ P.parts := by
obtain ⟨h, -⟩ := (P.isPartition.2 v).choose_spec.1
exact h
theorem mem_partOfVertex (v : V) : v ∈ P.partOfVertex v := by
obtain ⟨⟨_, h⟩, _⟩ := (P.isPartition.2 v).choose_spec
exact h
theorem partOfVertex_ne_of_adj {v w : V} (h : G.Adj v w) : P.partOfVertex v ≠ P.partOfVertex w := by
intro hn
have hw := P.mem_partOfVertex w
rw [← hn] at hw
exact P.independent _ (P.partOfVertex_mem v) (P.mem_partOfVertex v) hw (G.ne_of_adj h) h
/-- Create a coloring using the parts themselves as the colors.
Each vertex is colored by the part it's contained in. -/
def toColoring : G.Coloring P.parts :=
Coloring.mk (fun v ↦ ⟨P.partOfVertex v, P.partOfVertex_mem v⟩) fun hvw ↦ by
rw [Ne, Subtype.mk_eq_mk]
exact P.partOfVertex_ne_of_adj hvw
/-- Like `SimpleGraph.Partition.toColoring` but uses `Set V` as the coloring type. -/
def toColoring' : G.Coloring (Set V) :=
Coloring.mk P.partOfVertex fun hvw ↦ P.partOfVertex_ne_of_adj hvw
theorem colorable [Fintype P.parts] : G.Colorable (Fintype.card P.parts) :=
P.toColoring.colorable
end Partition
variable {G}
/-- Creates a partition from a coloring. -/
@[simps]
def Coloring.toPartition {α : Type v} (C : G.Coloring α) : G.Partition where
parts := C.colorClasses
isPartition := C.colorClasses_isPartition
independent := by
rintro s ⟨c, rfl⟩
apply C.color_classes_independent
namespace Partition
/-- The partition where every vertex is in its own part. -/
@[simps]
instance : Inhabited (Partition G) := ⟨G.selfColoring.toPartition⟩
end Partition
theorem partitionable_iff_colorable {n : ℕ} : G.Partitionable n ↔ G.Colorable n := by
constructor
· rintro ⟨P, hf, hc⟩
have : Fintype P.parts := hf.fintype
rw [Set.Finite.card_toFinset hf] at hc
apply P.colorable.mono hc
· rintro ⟨C⟩
refine ⟨C.toPartition, C.colorClasses_finite, le_trans ?_ (Fintype.card_fin n).le⟩
generalize_proofs h
change Set.Finite (Coloring.colorClasses C) at h
have : Fintype C.colorClasses := C.colorClasses_finite.fintype
rw [h.card_toFinset]
exact C.card_colorClasses_le
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Subgraph.lean | import Mathlib.Combinatorics.SimpleGraph.DeleteEdges
import Mathlib.Data.Fintype.Powerset
/-!
# Subgraphs of a simple graph
A subgraph of a simple graph consists of subsets of the graph's vertices and edges such that the
endpoints of each edge are present in the vertex subset. The edge subset is formalized as a
sub-relation of the adjacency relation of the simple graph.
## Main definitions
* `Subgraph G` is the type of subgraphs of a `G : SimpleGraph V`.
* `Subgraph.neighborSet`, `Subgraph.incidenceSet`, and `Subgraph.degree` are like their
`SimpleGraph` counterparts, but they refer to vertices from `G` to avoid subtype coercions.
* `Subgraph.coe` is the coercion from a `G' : Subgraph G` to a `SimpleGraph G'.verts`.
(In Lean 3 this could not be a `Coe` instance since the destination type depends on `G'`.)
* `Subgraph.IsSpanning` for whether a subgraph is a spanning subgraph and
`Subgraph.IsInduced` for whether a subgraph is an induced subgraph.
* Instances for `Lattice (Subgraph G)` and `BoundedOrder (Subgraph G)`.
* `SimpleGraph.toSubgraph`: If a `SimpleGraph` is a subgraph of another, then you can turn it
into a member of the larger graph's `SimpleGraph.Subgraph` type.
* Graph homomorphisms from a subgraph to a graph (`Subgraph.map_top`) and between subgraphs
(`Subgraph.map`).
## Implementation notes
* Recall that subgraphs are not determined by their vertex sets, so `SetLike` does not apply to
this kind of subobject.
## TODO
* Images of graph homomorphisms as subgraphs.
-/
universe u v
namespace SimpleGraph
/-- A subgraph of a `SimpleGraph` is a subset of vertices along with a restriction of the adjacency
relation that is symmetric and is supported by the vertex subset. They also form a bounded lattice.
Thinking of `V → V → Prop` as `Set (V × V)`, a set of darts (i.e., half-edges), then
`Subgraph.adj_sub` is that the darts of a subgraph are a subset of the darts of `G`. -/
@[ext]
structure Subgraph {V : Type u} (G : SimpleGraph V) where
/-- Vertices of the subgraph -/
verts : Set V
/-- Edges of the subgraph -/
Adj : V → V → Prop
adj_sub : ∀ {v w : V}, Adj v w → G.Adj v w
edge_vert : ∀ {v w : V}, Adj v w → v ∈ verts
symm : Symmetric Adj := by aesop_graph
initialize_simps_projections SimpleGraph.Subgraph (Adj → adj)
variable {ι : Sort*} {V : Type u} {W : Type v}
/-- The one-vertex subgraph. -/
@[simps]
protected def singletonSubgraph (G : SimpleGraph V) (v : V) : G.Subgraph where
verts := {v}
Adj := ⊥
adj_sub := False.elim
edge_vert := False.elim
symm _ _ := False.elim
/-- The one-edge subgraph. -/
@[simps]
def subgraphOfAdj (G : SimpleGraph V) {v w : V} (hvw : G.Adj v w) : G.Subgraph where
verts := {v, w}
Adj a b := s(v, w) = s(a, b)
adj_sub h := by
rw [← G.mem_edgeSet, ← h]
exact hvw
edge_vert {a b} h := by
apply_fun fun e ↦ a ∈ e at h
simp only [Sym2.mem_iff, true_or, eq_iff_iff, iff_true] at h
exact h
namespace Subgraph
variable {G : SimpleGraph V} {G₁ G₂ : G.Subgraph} {a b : V}
protected theorem loopless (G' : Subgraph G) : Irreflexive G'.Adj :=
fun v h ↦ G.loopless v (G'.adj_sub h)
theorem adj_comm (G' : Subgraph G) (v w : V) : G'.Adj v w ↔ G'.Adj w v :=
⟨fun x ↦ G'.symm x, fun x ↦ G'.symm x⟩
@[symm]
theorem adj_symm (G' : Subgraph G) {u v : V} (h : G'.Adj u v) : G'.Adj v u :=
G'.symm h
protected theorem Adj.symm {G' : Subgraph G} {u v : V} (h : G'.Adj u v) : G'.Adj v u :=
G'.symm h
protected theorem Adj.adj_sub {H : G.Subgraph} {u v : V} (h : H.Adj u v) : G.Adj u v :=
H.adj_sub h
protected theorem Adj.fst_mem {H : G.Subgraph} {u v : V} (h : H.Adj u v) : u ∈ H.verts :=
H.edge_vert h
protected theorem Adj.snd_mem {H : G.Subgraph} {u v : V} (h : H.Adj u v) : v ∈ H.verts :=
h.symm.fst_mem
protected theorem Adj.ne {H : G.Subgraph} {u v : V} (h : H.Adj u v) : u ≠ v :=
h.adj_sub.ne
theorem adj_congr_of_sym2 {H : G.Subgraph} {u v w x : V} (h2 : s(u, v) = s(w, x)) :
H.Adj u v ↔ H.Adj w x := by
simp only [Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk] at h2
rcases h2 with hl | hr
· rw [hl.1, hl.2]
· rw [hr.1, hr.2, Subgraph.adj_comm]
/-- Coercion from `G' : Subgraph G` to a `SimpleGraph G'.verts`. -/
@[simps]
protected def coe (G' : Subgraph G) : SimpleGraph G'.verts where
Adj v w := G'.Adj v w
symm _ _ h := G'.symm h
loopless v h := loopless G v (G'.adj_sub h)
@[simp]
theorem Adj.adj_sub' (G' : Subgraph G) (u v : G'.verts) (h : G'.Adj u v) : G.Adj u v :=
G'.adj_sub h
theorem coe_adj_sub (G' : Subgraph G) (u v : G'.verts) (h : G'.coe.Adj u v) : G.Adj u v :=
G'.adj_sub h
-- Given `h : H.Adj u v`, then `h.coe : H.coe.Adj ⟨u, _⟩ ⟨v, _⟩`.
protected theorem Adj.coe {H : G.Subgraph} {u v : V} (h : H.Adj u v) :
H.coe.Adj ⟨u, H.edge_vert h⟩ ⟨v, H.edge_vert h.symm⟩ := h
instance (G : SimpleGraph V) (H : Subgraph G) [DecidableRel H.Adj] : DecidableRel H.coe.Adj :=
fun a b ↦ ‹DecidableRel H.Adj› _ _
/-- A subgraph is called a *spanning subgraph* if it contains all the vertices of `G`. -/
def IsSpanning (G' : Subgraph G) : Prop :=
∀ v : V, v ∈ G'.verts
theorem isSpanning_iff {G' : Subgraph G} : G'.IsSpanning ↔ G'.verts = Set.univ :=
Set.eq_univ_iff_forall.symm
protected alias ⟨IsSpanning.verts_eq_univ, _⟩ := isSpanning_iff
/-- Coercion from `Subgraph G` to `SimpleGraph V`. If `G'` is a spanning
subgraph, then `G'.spanningCoe` yields an isomorphic graph.
In general, this adds in all vertices from `V` as isolated vertices. -/
@[simps]
protected def spanningCoe (G' : Subgraph G) : SimpleGraph V where
Adj := G'.Adj
symm := G'.symm
loopless v hv := G.loopless v (G'.adj_sub hv)
theorem Adj.of_spanningCoe {G' : Subgraph G} {u v : G'.verts} (h : G'.spanningCoe.Adj u v) :
G.Adj u v :=
G'.adj_sub h
lemma spanningCoe_le (G' : G.Subgraph) : G'.spanningCoe ≤ G := fun _ _ ↦ G'.3
theorem spanningCoe_inj : G₁.spanningCoe = G₂.spanningCoe ↔ G₁.Adj = G₂.Adj := by
simp [Subgraph.spanningCoe]
lemma mem_of_adj_spanningCoe {v w : V} {s : Set V} (G : SimpleGraph s)
(hadj : G.spanningCoe.Adj v w) : v ∈ s := by aesop
@[simp]
lemma spanningCoe_subgraphOfAdj {v w : V} (hadj : G.Adj v w) :
(G.subgraphOfAdj hadj).spanningCoe = fromEdgeSet {s(v, w)} := by
ext v w
aesop
/-- `spanningCoe` is equivalent to `coe` for a subgraph that `IsSpanning`. -/
@[simps]
def spanningCoeEquivCoeOfSpanning (G' : Subgraph G) (h : G'.IsSpanning) :
G'.spanningCoe ≃g G'.coe where
toFun v := ⟨v, h v⟩
invFun v := v
map_rel_iff' := Iff.rfl
/-- A subgraph is called an *induced subgraph* if vertices of `G'` are adjacent if
they are adjacent in `G`. -/
def IsInduced (G' : Subgraph G) : Prop :=
∀ ⦃v⦄, v ∈ G'.verts → ∀ ⦃w⦄, w ∈ G'.verts → G.Adj v w → G'.Adj v w
@[simp] protected lemma IsInduced.adj {G' : G.Subgraph} (hG' : G'.IsInduced) {a b : G'.verts} :
G'.Adj a b ↔ G.Adj a b :=
⟨coe_adj_sub _ _ _, hG' a.2 b.2⟩
/-- `H.support` is the set of vertices that form edges in the subgraph `H`. -/
def support (H : Subgraph G) : Set V := SetRel.dom {(v, w) | H.Adj v w}
theorem mem_support (H : Subgraph G) {v : V} : v ∈ H.support ↔ ∃ w, H.Adj v w := Iff.rfl
theorem support_subset_verts (H : Subgraph G) : H.support ⊆ H.verts :=
fun _ ⟨_, h⟩ ↦ H.edge_vert h
/-- `G'.neighborSet v` is the set of vertices adjacent to `v` in `G'`. -/
def neighborSet (G' : Subgraph G) (v : V) : Set V := {w | G'.Adj v w}
theorem neighborSet_subset (G' : Subgraph G) (v : V) : G'.neighborSet v ⊆ G.neighborSet v :=
fun _ ↦ G'.adj_sub
theorem neighborSet_subset_verts (G' : Subgraph G) (v : V) : G'.neighborSet v ⊆ G'.verts :=
fun _ h ↦ G'.edge_vert (adj_symm G' h)
@[simp]
theorem mem_neighborSet (G' : Subgraph G) (v w : V) : w ∈ G'.neighborSet v ↔ G'.Adj v w := Iff.rfl
/-- A subgraph as a graph has equivalent neighbor sets. -/
def coeNeighborSetEquiv {G' : Subgraph G} (v : G'.verts) :
G'.coe.neighborSet v ≃ G'.neighborSet v where
toFun w := ⟨w, w.2⟩
invFun w := ⟨⟨w, G'.edge_vert (G'.adj_symm w.2)⟩, w.2⟩
/-- The edge set of `G'` consists of a subset of edges of `G`. -/
def edgeSet (G' : Subgraph G) : Set (Sym2 V) := Sym2.fromRel G'.symm
theorem edgeSet_subset (G' : Subgraph G) : G'.edgeSet ⊆ G.edgeSet :=
Sym2.ind (fun _ _ ↦ G'.adj_sub)
@[simp]
protected lemma mem_edgeSet {G' : Subgraph G} {v w : V} : s(v, w) ∈ G'.edgeSet ↔ G'.Adj v w := .rfl
@[simp] lemma edgeSet_coe {G' : G.Subgraph} : G'.coe.edgeSet = Sym2.map (↑) ⁻¹' G'.edgeSet := by
ext e; induction e using Sym2.ind; simp
lemma image_coe_edgeSet_coe (G' : G.Subgraph) : Sym2.map (↑) '' G'.coe.edgeSet = G'.edgeSet := by
rw [edgeSet_coe, Set.image_preimage_eq_iff]
rintro e he
induction e using Sym2.ind with | h a b =>
rw [Subgraph.mem_edgeSet] at he
exact ⟨s(⟨a, edge_vert _ he⟩, ⟨b, edge_vert _ he.symm⟩), Sym2.map_pair_eq ..⟩
theorem mem_verts_of_mem_edge {G' : Subgraph G} {e : Sym2 V} {v : V} (he : e ∈ G'.edgeSet)
(hv : v ∈ e) : v ∈ G'.verts := by
induction e
rcases Sym2.mem_iff.mp hv with (rfl | rfl)
· exact G'.edge_vert he
· exact G'.edge_vert (G'.symm he)
/-- The `incidenceSet` is the set of edges incident to a given vertex. -/
def incidenceSet (G' : Subgraph G) (v : V) : Set (Sym2 V) := {e ∈ G'.edgeSet | v ∈ e}
theorem incidenceSet_subset_incidenceSet (G' : Subgraph G) (v : V) :
G'.incidenceSet v ⊆ G.incidenceSet v :=
fun _ h ↦ ⟨G'.edgeSet_subset h.1, h.2⟩
theorem incidenceSet_subset (G' : Subgraph G) (v : V) : G'.incidenceSet v ⊆ G'.edgeSet :=
fun _ h ↦ h.1
/-- Give a vertex as an element of the subgraph's vertex type. -/
abbrev vert (G' : Subgraph G) (v : V) (h : v ∈ G'.verts) : G'.verts := ⟨v, h⟩
/--
Create an equal copy of a subgraph (see `copy_eq`) with possibly different definitional equalities.
See Note [range copy pattern].
-/
def copy (G' : Subgraph G) (V'' : Set V) (hV : V'' = G'.verts)
(adj' : V → V → Prop) (hadj : adj' = G'.Adj) : Subgraph G where
verts := V''
Adj := adj'
adj_sub := hadj.symm ▸ G'.adj_sub
edge_vert := hV.symm ▸ hadj.symm ▸ G'.edge_vert
symm := hadj.symm ▸ G'.symm
theorem copy_eq (G' : Subgraph G) (V'' : Set V) (hV : V'' = G'.verts)
(adj' : V → V → Prop) (hadj : adj' = G'.Adj) : G'.copy V'' hV adj' hadj = G' :=
Subgraph.ext hV hadj
/-- The union of two subgraphs. -/
instance : Max G.Subgraph where
max G₁ G₂ :=
{ verts := G₁.verts ∪ G₂.verts
Adj := G₁.Adj ⊔ G₂.Adj
adj_sub := fun hab => Or.elim hab (fun h => G₁.adj_sub h) fun h => G₂.adj_sub h
edge_vert := Or.imp (fun h => G₁.edge_vert h) fun h => G₂.edge_vert h
symm := fun _ _ => Or.imp G₁.adj_symm G₂.adj_symm }
/-- The intersection of two subgraphs. -/
instance : Min G.Subgraph where
min G₁ G₂ :=
{ verts := G₁.verts ∩ G₂.verts
Adj := G₁.Adj ⊓ G₂.Adj
adj_sub := fun hab => G₁.adj_sub hab.1
edge_vert := And.imp (fun h => G₁.edge_vert h) fun h => G₂.edge_vert h
symm := fun _ _ => And.imp G₁.adj_symm G₂.adj_symm }
/-- The `top` subgraph is `G` as a subgraph of itself. -/
instance : Top G.Subgraph where
top :=
{ verts := Set.univ
Adj := G.Adj
adj_sub := id
edge_vert := @fun v _ _ => Set.mem_univ v
symm := G.symm }
/-- The `bot` subgraph is the subgraph with no vertices or edges. -/
instance : Bot G.Subgraph where
bot :=
{ verts := ∅
Adj := ⊥
adj_sub := False.elim
edge_vert := False.elim
symm := fun _ _ => id }
instance : SupSet G.Subgraph where
sSup s :=
{ verts := ⋃ G' ∈ s, verts G'
Adj := fun a b => ∃ G' ∈ s, Adj G' a b
adj_sub := by
rintro a b ⟨G', -, hab⟩
exact G'.adj_sub hab
edge_vert := by
rintro a b ⟨G', hG', hab⟩
exact Set.mem_iUnion₂_of_mem hG' (G'.edge_vert hab)
symm := fun a b h => by simpa [adj_comm] using h }
instance : InfSet G.Subgraph where
sInf s :=
{ verts := ⋂ G' ∈ s, verts G'
Adj := fun a b => (∀ ⦃G'⦄, G' ∈ s → Adj G' a b) ∧ G.Adj a b
adj_sub := And.right
edge_vert := fun hab => Set.mem_iInter₂_of_mem fun G' hG' => G'.edge_vert <| hab.1 hG'
symm := fun _ _ => And.imp (forall₂_imp fun _ _ => Adj.symm) G.adj_symm }
@[simp]
theorem sup_adj : (G₁ ⊔ G₂).Adj a b ↔ G₁.Adj a b ∨ G₂.Adj a b :=
Iff.rfl
@[simp]
theorem inf_adj : (G₁ ⊓ G₂).Adj a b ↔ G₁.Adj a b ∧ G₂.Adj a b :=
Iff.rfl
@[simp]
theorem top_adj : (⊤ : Subgraph G).Adj a b ↔ G.Adj a b :=
Iff.rfl
@[simp]
theorem not_bot_adj : ¬ (⊥ : Subgraph G).Adj a b :=
not_false
@[simp]
theorem verts_sup (G₁ G₂ : G.Subgraph) : (G₁ ⊔ G₂).verts = G₁.verts ∪ G₂.verts :=
rfl
@[simp]
theorem verts_inf (G₁ G₂ : G.Subgraph) : (G₁ ⊓ G₂).verts = G₁.verts ∩ G₂.verts :=
rfl
@[simp]
theorem verts_top : (⊤ : G.Subgraph).verts = Set.univ :=
rfl
@[simp]
theorem verts_bot : (⊥ : G.Subgraph).verts = ∅ :=
rfl
theorem eq_bot_iff_verts_eq_empty (G' : G.Subgraph) : G' = ⊥ ↔ G'.verts = ∅ :=
⟨(· ▸ verts_bot), fun h ↦ Subgraph.ext (h ▸ verts_bot (G := G)) <|
funext₂ fun _ _ ↦ propext ⟨fun h' ↦ (h ▸ h'.fst_mem :), False.elim⟩⟩
theorem ne_bot_iff_nonempty_verts (G' : G.Subgraph) : G' ≠ ⊥ ↔ G'.verts.Nonempty :=
G'.eq_bot_iff_verts_eq_empty.not.trans <| Set.nonempty_iff_ne_empty.symm
@[simp]
theorem sSup_adj {s : Set G.Subgraph} : (sSup s).Adj a b ↔ ∃ G ∈ s, Adj G a b :=
Iff.rfl
@[simp]
theorem sInf_adj {s : Set G.Subgraph} : (sInf s).Adj a b ↔ (∀ G' ∈ s, Adj G' a b) ∧ G.Adj a b :=
Iff.rfl
@[simp]
theorem iSup_adj {f : ι → G.Subgraph} : (⨆ i, f i).Adj a b ↔ ∃ i, (f i).Adj a b := by
simp [iSup]
@[simp]
theorem iInf_adj {f : ι → G.Subgraph} : (⨅ i, f i).Adj a b ↔ (∀ i, (f i).Adj a b) ∧ G.Adj a b := by
simp [iInf]
theorem sInf_adj_of_nonempty {s : Set G.Subgraph} (hs : s.Nonempty) :
(sInf s).Adj a b ↔ ∀ G' ∈ s, Adj G' a b :=
sInf_adj.trans <|
and_iff_left_of_imp <| by
obtain ⟨G', hG'⟩ := hs
exact fun h => G'.adj_sub (h _ hG')
theorem iInf_adj_of_nonempty [Nonempty ι] {f : ι → G.Subgraph} :
(⨅ i, f i).Adj a b ↔ ∀ i, (f i).Adj a b := by
rw [iInf, sInf_adj_of_nonempty (Set.range_nonempty _)]
simp
@[simp]
theorem verts_sSup (s : Set G.Subgraph) : (sSup s).verts = ⋃ G' ∈ s, verts G' :=
rfl
@[simp]
theorem verts_sInf (s : Set G.Subgraph) : (sInf s).verts = ⋂ G' ∈ s, verts G' :=
rfl
@[simp]
theorem verts_iSup {f : ι → G.Subgraph} : (⨆ i, f i).verts = ⋃ i, (f i).verts := by simp [iSup]
@[simp]
theorem verts_iInf {f : ι → G.Subgraph} : (⨅ i, f i).verts = ⋂ i, (f i).verts := by simp [iInf]
@[simp] lemma coe_bot : (⊥ : G.Subgraph).coe = ⊥ := rfl
@[simp] lemma IsInduced.top : (⊤ : G.Subgraph).IsInduced := fun _ _ _ _ ↦ id
/-- The graph isomorphism between the top element of `G.subgraph` and `G`. -/
def topIso : (⊤ : G.Subgraph).coe ≃g G where
toFun := (↑)
invFun a := ⟨a, Set.mem_univ _⟩
left_inv _ := Subtype.eta ..
map_rel_iff' := .rfl
theorem verts_spanningCoe_injective :
(fun G' : Subgraph G => (G'.verts, G'.spanningCoe)).Injective := by
intro G₁ G₂ h
rw [Prod.ext_iff] at h
exact Subgraph.ext h.1 (spanningCoe_inj.1 h.2)
/-- For subgraphs `G₁`, `G₂`, `G₁ ≤ G₂` iff `G₁.verts ⊆ G₂.verts` and
`∀ a b, G₁.adj a b → G₂.adj a b`. -/
instance distribLattice : DistribLattice G.Subgraph :=
{ show DistribLattice G.Subgraph from
verts_spanningCoe_injective.distribLattice _
(fun _ _ => rfl) fun _ _ => rfl with
le := fun x y => x.verts ⊆ y.verts ∧ ∀ ⦃v w : V⦄, x.Adj v w → y.Adj v w }
instance : BoundedOrder (Subgraph G) where
le_top x := ⟨Set.subset_univ _, fun _ _ => x.adj_sub⟩
bot_le _ := ⟨Set.empty_subset _, fun _ _ => False.elim⟩
/-- Note that subgraphs do not form a Boolean algebra, because of `verts`. -/
def completelyDistribLatticeMinimalAxioms : CompletelyDistribLattice.MinimalAxioms G.Subgraph where
le_top G' := ⟨Set.subset_univ _, fun _ _ => G'.adj_sub⟩
bot_le _ := ⟨Set.empty_subset _, fun _ _ => False.elim⟩
-- Porting note: needed `apply` here to modify elaboration; previously the term itself was fine.
le_sSup s G' hG' := ⟨by apply Set.subset_iUnion₂ G' hG', fun _ _ hab => ⟨G', hG', hab⟩⟩
sSup_le s G' hG' :=
⟨Set.iUnion₂_subset fun _ hH => (hG' _ hH).1, by
rintro a b ⟨H, hH, hab⟩
exact (hG' _ hH).2 hab⟩
sInf_le _ G' hG' := ⟨Set.iInter₂_subset G' hG', fun _ _ hab => hab.1 hG'⟩
le_sInf _ G' hG' :=
⟨Set.subset_iInter₂ fun _ hH => (hG' _ hH).1, fun _ _ hab =>
⟨fun _ hH => (hG' _ hH).2 hab, G'.adj_sub hab⟩⟩
iInf_iSup_eq f := Subgraph.ext (by simpa using iInf_iSup_eq)
(by ext; simp [Classical.skolem])
instance : CompletelyDistribLattice G.Subgraph :=
.ofMinimalAxioms completelyDistribLatticeMinimalAxioms
@[gcongr] lemma verts_mono {H H' : G.Subgraph} (h : H ≤ H') : H.verts ⊆ H'.verts := h.1
lemma verts_monotone : Monotone (verts : G.Subgraph → Set V) := fun _ _ h ↦ h.1
@[simps]
instance subgraphInhabited : Inhabited (Subgraph G) := ⟨⊥⟩
@[simp]
theorem neighborSet_sup {H H' : G.Subgraph} (v : V) :
(H ⊔ H').neighborSet v = H.neighborSet v ∪ H'.neighborSet v := rfl
@[simp]
theorem neighborSet_inf {H H' : G.Subgraph} (v : V) :
(H ⊓ H').neighborSet v = H.neighborSet v ∩ H'.neighborSet v := rfl
@[simp]
theorem neighborSet_top (v : V) : (⊤ : G.Subgraph).neighborSet v = G.neighborSet v := rfl
@[simp]
theorem neighborSet_bot (v : V) : (⊥ : G.Subgraph).neighborSet v = ∅ := rfl
@[simp]
theorem neighborSet_sSup (s : Set G.Subgraph) (v : V) :
(sSup s).neighborSet v = ⋃ G' ∈ s, neighborSet G' v := by
ext
simp
@[simp]
theorem neighborSet_sInf (s : Set G.Subgraph) (v : V) :
(sInf s).neighborSet v = (⋂ G' ∈ s, neighborSet G' v) ∩ G.neighborSet v := by
ext
simp
@[simp]
theorem neighborSet_iSup (f : ι → G.Subgraph) (v : V) :
(⨆ i, f i).neighborSet v = ⋃ i, (f i).neighborSet v := by simp [iSup]
@[simp]
theorem neighborSet_iInf (f : ι → G.Subgraph) (v : V) :
(⨅ i, f i).neighborSet v = (⋂ i, (f i).neighborSet v) ∩ G.neighborSet v := by simp [iInf]
@[simp]
theorem edgeSet_top : (⊤ : Subgraph G).edgeSet = G.edgeSet := rfl
@[simp]
theorem edgeSet_bot : (⊥ : Subgraph G).edgeSet = ∅ :=
Set.ext <| Sym2.ind (by simp)
@[simp]
theorem edgeSet_inf {H₁ H₂ : Subgraph G} : (H₁ ⊓ H₂).edgeSet = H₁.edgeSet ∩ H₂.edgeSet :=
Set.ext <| Sym2.ind (by simp)
@[simp]
theorem edgeSet_sup {H₁ H₂ : Subgraph G} : (H₁ ⊔ H₂).edgeSet = H₁.edgeSet ∪ H₂.edgeSet :=
Set.ext <| Sym2.ind (by simp)
@[simp]
theorem edgeSet_sSup (s : Set G.Subgraph) : (sSup s).edgeSet = ⋃ G' ∈ s, edgeSet G' := by
ext e
induction e
simp
@[simp]
theorem edgeSet_sInf (s : Set G.Subgraph) :
(sInf s).edgeSet = (⋂ G' ∈ s, edgeSet G') ∩ G.edgeSet := by
ext e
induction e
simp
@[simp]
theorem edgeSet_iSup (f : ι → G.Subgraph) :
(⨆ i, f i).edgeSet = ⋃ i, (f i).edgeSet := by simp [iSup]
@[simp]
theorem edgeSet_iInf (f : ι → G.Subgraph) :
(⨅ i, f i).edgeSet = (⋂ i, (f i).edgeSet) ∩ G.edgeSet := by
simp [iInf]
@[simp]
theorem spanningCoe_top : (⊤ : Subgraph G).spanningCoe = G := rfl
@[simp]
theorem spanningCoe_bot : (⊥ : Subgraph G).spanningCoe = ⊥ := rfl
/-- Turn a subgraph of a `SimpleGraph` into a member of its subgraph type. -/
@[simps]
def _root_.SimpleGraph.toSubgraph (H : SimpleGraph V) (h : H ≤ G) : G.Subgraph where
verts := Set.univ
Adj := H.Adj
adj_sub e := h e
edge_vert _ := Set.mem_univ _
symm := H.symm
theorem support_mono {H H' : Subgraph G} (h : H ≤ H') : H.support ⊆ H'.support :=
SetRel.dom_mono fun _ hvw ↦ h.2 hvw
theorem _root_.SimpleGraph.toSubgraph.isSpanning (H : SimpleGraph V) (h : H ≤ G) :
(toSubgraph H h).IsSpanning :=
Set.mem_univ
theorem spanningCoe_le_of_le {H H' : Subgraph G} (h : H ≤ H') : H.spanningCoe ≤ H'.spanningCoe :=
h.2
@[simp]
lemma sup_spanningCoe (H H' : Subgraph G) :
(H ⊔ H').spanningCoe = H.spanningCoe ⊔ H'.spanningCoe := rfl
/-- The top of the `Subgraph G` lattice is equivalent to the graph itself. -/
@[deprecated (since := "2025-09-15")] alias topEquiv := topIso
/-- The bottom of the `Subgraph G` lattice is isomorphic to the empty graph on the empty
vertex type. -/
def botIso : (⊥ : Subgraph G).coe ≃g emptyGraph Empty where
toFun v := v.property.elim
invFun v := v.elim
left_inv := fun ⟨_, h⟩ ↦ h.elim
right_inv v := v.elim
map_rel_iff' := Iff.rfl
@[deprecated (since := "2025-09-15")] alias botEquiv := botIso
theorem edgeSet_mono {H₁ H₂ : Subgraph G} (h : H₁ ≤ H₂) : H₁.edgeSet ≤ H₂.edgeSet :=
Sym2.ind h.2
theorem _root_.Disjoint.edgeSet {H₁ H₂ : Subgraph G} (h : Disjoint H₁ H₂) :
Disjoint H₁.edgeSet H₂.edgeSet :=
disjoint_iff_inf_le.mpr <| by simpa using edgeSet_mono h.le_bot
section map
variable {G' : SimpleGraph W} {f : G →g G'}
/-- Graph homomorphisms induce a covariant function on subgraphs. -/
@[simps]
protected def map (f : G →g G') (H : G.Subgraph) : G'.Subgraph where
verts := f '' H.verts
Adj := Relation.Map H.Adj f f
adj_sub := by
rintro _ _ ⟨u, v, h, rfl, rfl⟩
exact f.map_rel (H.adj_sub h)
edge_vert := by
rintro _ _ ⟨u, v, h, rfl, rfl⟩
exact Set.mem_image_of_mem _ (H.edge_vert h)
symm := by
rintro _ _ ⟨u, v, h, rfl, rfl⟩
exact ⟨v, u, H.symm h, rfl, rfl⟩
@[simp] lemma map_id (H : G.Subgraph) : H.map Hom.id = H := by ext <;> simp
lemma map_comp {U : Type*} {G'' : SimpleGraph U} (H : G.Subgraph) (f : G →g G') (g : G' →g G'') :
H.map (g.comp f) = (H.map f).map g := by ext <;> simp [Subgraph.map]
@[gcongr] lemma map_mono {H₁ H₂ : G.Subgraph} (hH : H₁ ≤ H₂) : H₁.map f ≤ H₂.map f := by
constructor
· intro
simp only [map_verts, Set.mem_image, forall_exists_index, and_imp]
rintro v hv rfl
exact ⟨_, hH.1 hv, rfl⟩
· rintro _ _ ⟨u, v, ha, rfl, rfl⟩
exact ⟨_, _, hH.2 ha, rfl, rfl⟩
lemma map_monotone : Monotone (Subgraph.map f) := fun _ _ ↦ map_mono
theorem map_sup (f : G →g G') (H₁ H₂ : G.Subgraph) : (H₁ ⊔ H₂).map f = H₁.map f ⊔ H₂.map f := by
ext <;> simp [Set.image_union, map_adj, sup_adj, Relation.Map, or_and_right, exists_or]
@[simp] lemma map_iso_top {H : SimpleGraph W} (e : G ≃g H) : Subgraph.map e.toHom ⊤ = ⊤ := by
ext <;> simp [Relation.Map, e.apply_eq_iff_eq_symm_apply, ← e.map_rel_iff]
@[simp] lemma edgeSet_map (f : G →g G') (H : G.Subgraph) :
(H.map f).edgeSet = Sym2.map f '' H.edgeSet := Sym2.fromRel_relationMap ..
end map
/-- Graph homomorphisms induce a contravariant function on subgraphs. -/
@[simps]
protected def comap {G' : SimpleGraph W} (f : G →g G') (H : G'.Subgraph) : G.Subgraph where
verts := f ⁻¹' H.verts
Adj u v := G.Adj u v ∧ H.Adj (f u) (f v)
adj_sub h := h.1
edge_vert h := Set.mem_preimage.1 (H.edge_vert h.2)
symm _ _ h := ⟨G.symm h.1, H.symm h.2⟩
theorem comap_monotone {G' : SimpleGraph W} (f : G →g G') : Monotone (Subgraph.comap f) := by
intro H H' h
constructor
· intro
simp only [comap_verts, Set.mem_preimage]
apply h.1
· intro v w
simp +contextual only [comap_adj, and_imp, true_and]
intro
apply h.2
@[simp] lemma comap_equiv_top {H : SimpleGraph W} (f : G →g H) : Subgraph.comap f ⊤ = ⊤ := by
ext <;> simp +contextual [f.map_adj]
theorem map_le_iff_le_comap {G' : SimpleGraph W} (f : G →g G') (H : G.Subgraph) (H' : G'.Subgraph) :
H.map f ≤ H' ↔ H ≤ H'.comap f := by
refine ⟨fun h ↦ ⟨fun v hv ↦ ?_, fun v w hvw ↦ ?_⟩, fun h ↦ ⟨fun v ↦ ?_, fun v w ↦ ?_⟩⟩
· simp only [comap_verts, Set.mem_preimage]
exact h.1 ⟨v, hv, rfl⟩
· simp only [H.adj_sub hvw, comap_adj, true_and]
exact h.2 ⟨v, w, hvw, rfl, rfl⟩
· simp only [map_verts, Set.mem_image, forall_exists_index, and_imp]
rintro w hw rfl
exact h.1 hw
· simp only [Relation.Map, map_adj, forall_exists_index, and_imp]
rintro u u' hu rfl rfl
exact (h.2 hu).2
instance [DecidableEq V] [Fintype V] [DecidableRel G.Adj] : Fintype G.Subgraph := by
refine .ofBijective
(α := {H : Finset V × (V → V → Bool) //
(∀ a b, H.2 a b → G.Adj a b) ∧ (∀ a b, H.2 a b → a ∈ H.1) ∧ ∀ a b, H.2 a b = H.2 b a})
(fun H ↦ ⟨H.1.1, fun a b ↦ H.1.2 a b, @H.2.1, @H.2.2.1, by simp [Symmetric, H.2.2.2]⟩)
⟨?_, fun H ↦ ?_⟩
· rintro ⟨⟨_, _⟩, -⟩ ⟨⟨_, _⟩, -⟩
simp [funext_iff]
· classical
exact ⟨⟨(H.verts.toFinset, fun a b ↦ H.Adj a b), fun a b ↦ by simpa using H.adj_sub,
fun a b ↦ by simpa using H.edge_vert, by simp [H.adj_comm]⟩, by simp⟩
instance [Finite V] : Finite G.Subgraph := by classical cases nonempty_fintype V; infer_instance
/-- Given two subgraphs, one a subgraph of the other, there is an induced injective homomorphism of
the subgraphs as graphs. -/
@[simps]
def inclusion {x y : Subgraph G} (h : x ≤ y) : x.coe →g y.coe where
toFun v := ⟨↑v, And.left h v.property⟩
map_rel' hvw := h.2 hvw
theorem inclusion.injective {x y : Subgraph G} (h : x ≤ y) : Function.Injective (inclusion h) := by
intro v w h
rw [inclusion, DFunLike.coe, Subtype.mk_eq_mk] at h
exact Subtype.ext h
/-- There is an induced injective homomorphism of a subgraph of `G` into `G`. -/
@[simps]
protected def hom (x : Subgraph G) : x.coe →g G where
toFun v := v
map_rel' := x.adj_sub
@[simp] lemma coe_hom (x : Subgraph G) :
(x.hom : x.verts → V) = (fun (v : x.verts) => (v : V)) := rfl
theorem hom_injective {x : Subgraph G} : Function.Injective x.hom :=
fun _ _ ↦ Subtype.ext
@[simp] lemma map_hom_top (G' : G.Subgraph) : Subgraph.map G'.hom ⊤ = G' := by
aesop (add unfold safe Relation.Map, unsafe G'.edge_vert, unsafe Adj.symm)
/-- There is an induced injective homomorphism of a subgraph of `G` as
a spanning subgraph into `G`. -/
@[simps]
def spanningHom (x : Subgraph G) : x.spanningCoe →g G where
toFun := id
map_rel' := x.adj_sub
theorem spanningHom_injective {x : Subgraph G} : Function.Injective x.spanningHom :=
fun _ _ ↦ id
theorem neighborSet_subset_of_subgraph {x y : Subgraph G} (h : x ≤ y) (v : V) :
x.neighborSet v ⊆ y.neighborSet v :=
fun _ h' ↦ h.2 h'
instance neighborSet.decidablePred (G' : Subgraph G) [h : DecidableRel G'.Adj] (v : V) :
DecidablePred (· ∈ G'.neighborSet v) :=
h v
/-- If a graph is locally finite at a vertex, then so is a subgraph of that graph. -/
instance finiteAt {G' : Subgraph G} (v : G'.verts) [DecidableRel G'.Adj]
[Fintype (G.neighborSet v)] : Fintype (G'.neighborSet v) :=
Set.fintypeSubset (G.neighborSet v) (G'.neighborSet_subset v)
/-- If a subgraph is locally finite at a vertex, then so are subgraphs of that subgraph.
This is not an instance because `G''` cannot be inferred. -/
def finiteAtOfSubgraph {G' G'' : Subgraph G} [DecidableRel G'.Adj] (h : G' ≤ G'') (v : G'.verts)
[Fintype (G''.neighborSet v)] : Fintype (G'.neighborSet v) :=
Set.fintypeSubset (G''.neighborSet v) (neighborSet_subset_of_subgraph h v)
instance (G' : Subgraph G) [Fintype G'.verts] (v : V) [DecidablePred (· ∈ G'.neighborSet v)] :
Fintype (G'.neighborSet v) :=
Set.fintypeSubset G'.verts (neighborSet_subset_verts G' v)
instance coeFiniteAt {G' : Subgraph G} (v : G'.verts) [Fintype (G'.neighborSet v)] :
Fintype (G'.coe.neighborSet v) :=
Fintype.ofEquiv _ (coeNeighborSetEquiv v).symm
theorem IsSpanning.card_verts [Fintype V] {G' : Subgraph G} [Fintype G'.verts] (h : G'.IsSpanning) :
G'.verts.toFinset.card = Fintype.card V := by
simp only [isSpanning_iff.1 h, Set.toFinset_univ]
congr
/-- The degree of a vertex in a subgraph. It's zero for vertices outside the subgraph. -/
def degree (G' : Subgraph G) (v : V) [Fintype (G'.neighborSet v)] : ℕ :=
Fintype.card (G'.neighborSet v)
theorem finset_card_neighborSet_eq_degree {G' : Subgraph G} {v : V} [Fintype (G'.neighborSet v)] :
(G'.neighborSet v).toFinset.card = G'.degree v := by
rw [degree, Set.toFinset_card]
theorem degree_of_notMem_verts {G' : Subgraph G} {v : V} [Fintype (G'.neighborSet v)]
(h : v ∉ G'.verts) : G'.degree v = 0 := by
rw [degree, Fintype.card_eq_zero_iff, isEmpty_subtype]
intro w
by_contra hw
exact h hw.fst_mem
theorem degree_le (G' : Subgraph G) (v : V) [Fintype (G'.neighborSet v)]
[Fintype (G.neighborSet v)] : G'.degree v ≤ G.degree v := by
rw [← card_neighborSet_eq_degree]
exact Set.card_le_card (G'.neighborSet_subset v)
theorem degree_le' (G' G'' : Subgraph G) (h : G' ≤ G'') (v : V) [Fintype (G'.neighborSet v)]
[Fintype (G''.neighborSet v)] : G'.degree v ≤ G''.degree v :=
Set.card_le_card (neighborSet_subset_of_subgraph h v)
@[simp]
theorem coe_degree (G' : Subgraph G) (v : G'.verts) [Fintype (G'.coe.neighborSet v)]
[Fintype (G'.neighborSet v)] : G'.coe.degree v = G'.degree v := by
rw [← card_neighborSet_eq_degree]
exact Fintype.card_congr (coeNeighborSetEquiv v)
@[simp]
theorem degree_spanningCoe {G' : G.Subgraph} (v : V) [Fintype (G'.neighborSet v)]
[Fintype (G'.spanningCoe.neighborSet v)] : G'.spanningCoe.degree v = G'.degree v := by
rw [← card_neighborSet_eq_degree, Subgraph.degree]
congr!
theorem degree_pos_iff_exists_adj {G' : Subgraph G} {v : V} [Fintype (G'.neighborSet v)] :
0 < G'.degree v ↔ ∃ w, G'.Adj v w := by
simp only [degree, Fintype.card_pos_iff, nonempty_subtype, mem_neighborSet]
theorem degree_eq_zero_of_subsingleton (G' : Subgraph G) (v : V) [Fintype (G'.neighborSet v)]
(hG : G'.verts.Subsingleton) : G'.degree v = 0 := by
by_cases hv : v ∈ G'.verts
· rw [← G'.coe_degree ⟨v, hv⟩]
have := (Set.subsingleton_coe _).mpr hG
exact G'.coe.degree_eq_zero_of_subsingleton ⟨v, hv⟩
· exact degree_of_notMem_verts hv
theorem degree_eq_one_iff_existsUnique_adj {G' : Subgraph G} {v : V} [Fintype (G'.neighborSet v)] :
G'.degree v = 1 ↔ ∃! w : V, G'.Adj v w := by
rw [← finset_card_neighborSet_eq_degree, Finset.card_eq_one, Finset.singleton_iff_unique_mem]
simp only [Set.mem_toFinset, mem_neighborSet]
@[deprecated (since := "2025-10-31")]
alias degree_eq_one_iff_unique_adj := degree_eq_one_iff_existsUnique_adj
theorem nontrivial_verts_of_degree_ne_zero {G' : Subgraph G} {v : V} [Fintype (G'.neighborSet v)]
(h : G'.degree v ≠ 0) : Nontrivial G'.verts := by
apply not_subsingleton_iff_nontrivial.mp
by_contra
simp_all [G'.degree_eq_zero_of_subsingleton v]
lemma neighborSet_eq_of_equiv {v : V} {H : Subgraph G}
(h : G.neighborSet v ≃ H.neighborSet v) (hfin : (G.neighborSet v).Finite) :
H.neighborSet v = G.neighborSet v := by
lift H.neighborSet v to Finset V using h.set_finite_iff.mp hfin with s hs
lift G.neighborSet v to Finset V using hfin with t ht
refine congrArg _ <| Finset.eq_of_subset_of_card_le ?_ (Finset.card_eq_of_equiv h).le
rw [← Finset.coe_subset, hs, ht]
exact H.neighborSet_subset _
lemma adj_iff_of_neighborSet_equiv {v : V} {H : Subgraph G}
(h : G.neighborSet v ≃ H.neighborSet v) (hfin : (G.neighborSet v).Finite) :
∀ {w}, H.Adj v w ↔ G.Adj v w :=
Set.ext_iff.mp (neighborSet_eq_of_equiv h hfin) _
end Subgraph
@[simp]
theorem card_neighborSet_toSubgraph (G H : SimpleGraph V) (h : H ≤ G)
(v : V) [Fintype ↑((toSubgraph H h).neighborSet v)] [Fintype ↑(H.neighborSet v)] :
Fintype.card ↑((toSubgraph H h).neighborSet v) = H.degree v := by
refine (Finset.card_eq_of_equiv_fintype ?_).symm
simp only [mem_neighborFinset]
rfl
@[simp]
lemma degree_toSubgraph (G H : SimpleGraph V) (h : H ≤ G) {v : V}
[Fintype ↑((toSubgraph H h).neighborSet v)] [Fintype ↑(H.neighborSet v)] :
(toSubgraph H h).degree v = H.degree v := by
simp [Subgraph.degree]
section MkProperties
/-! ### Properties of `singletonSubgraph` and `subgraphOfAdj` -/
variable {G : SimpleGraph V} {G' : SimpleGraph W}
instance nonempty_singletonSubgraph_verts (v : V) : Nonempty (G.singletonSubgraph v).verts :=
⟨⟨v, Set.mem_singleton v⟩⟩
@[simp]
theorem singletonSubgraph_le_iff (v : V) (H : G.Subgraph) :
G.singletonSubgraph v ≤ H ↔ v ∈ H.verts := by
refine ⟨fun h ↦ h.1 (Set.mem_singleton v), ?_⟩
intro h
constructor
· rwa [singletonSubgraph_verts, Set.singleton_subset_iff]
· exact fun _ _ ↦ False.elim
@[simp]
theorem map_singletonSubgraph (f : G →g G') {v : V} :
Subgraph.map f (G.singletonSubgraph v) = G'.singletonSubgraph (f v) := by
ext <;> simp only [Relation.Map, Subgraph.map_adj, singletonSubgraph_adj, Pi.bot_apply,
exists_and_left, and_iff_left_iff_imp, Subgraph.map_verts,
singletonSubgraph_verts, Set.image_singleton]
exact False.elim
@[simp]
theorem neighborSet_singletonSubgraph (v w : V) : (G.singletonSubgraph v).neighborSet w = ∅ :=
rfl
@[simp]
theorem edgeSet_singletonSubgraph (v : V) : (G.singletonSubgraph v).edgeSet = ∅ :=
Sym2.fromRel_bot
theorem eq_singletonSubgraph_iff_verts_eq (H : G.Subgraph) {v : V} :
H = G.singletonSubgraph v ↔ H.verts = {v} := by
refine ⟨fun h ↦ by rw [h, singletonSubgraph_verts], fun h ↦ ?_⟩
ext
· rw [h, singletonSubgraph_verts]
· simp only [Prop.bot_eq_false, singletonSubgraph_adj, Pi.bot_apply, iff_false]
intro ha
have ha1 := ha.fst_mem
have ha2 := ha.snd_mem
rw [h, Set.mem_singleton_iff] at ha1 ha2
subst_vars
exact ha.ne rfl
instance nonempty_subgraphOfAdj_verts {v w : V} (hvw : G.Adj v w) :
Nonempty (G.subgraphOfAdj hvw).verts :=
⟨⟨v, by simp⟩⟩
@[simp]
theorem edgeSet_subgraphOfAdj {v w : V} (hvw : G.Adj v w) :
(G.subgraphOfAdj hvw).edgeSet = {s(v, w)} := by
ext e
refine e.ind ?_
simp only [eq_comm, Set.mem_singleton_iff, Subgraph.mem_edgeSet, subgraphOfAdj_adj,
forall₂_true_iff]
lemma subgraphOfAdj_le_of_adj {v w : V} (H : G.Subgraph) (h : H.Adj v w) :
G.subgraphOfAdj (H.adj_sub h) ≤ H := by
constructor
· intro x
rintro (rfl | rfl) <;> simp [H.edge_vert h, H.edge_vert h.symm]
· simp only [subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff]
rintro _ _ (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) <;> simp [h, h.symm]
theorem subgraphOfAdj_symm {v w : V} (hvw : G.Adj v w) :
G.subgraphOfAdj hvw.symm = G.subgraphOfAdj hvw := by
ext <;> simp [or_comm, and_comm]
@[simp]
theorem map_subgraphOfAdj (f : G →g G') {v w : V} (hvw : G.Adj v w) :
Subgraph.map f (G.subgraphOfAdj hvw) = G'.subgraphOfAdj (f.map_adj hvw) := by
ext
· grind [Subgraph.map_verts, subgraphOfAdj_verts]
· grind [Relation.Map, Subgraph.map_adj, subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff]
theorem neighborSet_subgraphOfAdj_subset {u v w : V} (hvw : G.Adj v w) :
(G.subgraphOfAdj hvw).neighborSet u ⊆ {v, w} :=
(G.subgraphOfAdj hvw).neighborSet_subset_verts _
@[simp]
theorem neighborSet_fst_subgraphOfAdj {v w : V} (hvw : G.Adj v w) :
(G.subgraphOfAdj hvw).neighborSet v = {w} := by
ext u
suffices w = u ↔ u = w by simpa [hvw.ne.symm] using this
rw [eq_comm]
@[simp]
theorem neighborSet_snd_subgraphOfAdj {v w : V} (hvw : G.Adj v w) :
(G.subgraphOfAdj hvw).neighborSet w = {v} := by
rw [subgraphOfAdj_symm hvw.symm]
exact neighborSet_fst_subgraphOfAdj hvw.symm
@[simp]
theorem neighborSet_subgraphOfAdj_of_ne_of_ne {u v w : V} (hvw : G.Adj v w) (hv : u ≠ v)
(hw : u ≠ w) : (G.subgraphOfAdj hvw).neighborSet u = ∅ := by
ext
simp [hv.symm, hw.symm]
theorem neighborSet_subgraphOfAdj [DecidableEq V] {u v w : V} (hvw : G.Adj v w) :
(G.subgraphOfAdj hvw).neighborSet u =
(if u = v then {w} else ∅) ∪ if u = w then {v} else ∅ := by
split_ifs <;> subst_vars <;> simp [*]
theorem singletonSubgraph_fst_le_subgraphOfAdj {u v : V} {h : G.Adj u v} :
G.singletonSubgraph u ≤ G.subgraphOfAdj h := by
simp
theorem singletonSubgraph_snd_le_subgraphOfAdj {u v : V} {h : G.Adj u v} :
G.singletonSubgraph v ≤ G.subgraphOfAdj h := by
simp
@[simp]
lemma support_subgraphOfAdj {u v : V} (h : G.Adj u v) :
(G.subgraphOfAdj h).support = {u, v} := by
ext
rw [Subgraph.mem_support]
simp only [subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk]
refine ⟨?_, fun h ↦ h.elim (fun hl ↦ ⟨v, .inl ⟨hl.symm, rfl⟩⟩) fun hr ↦ ⟨u, .inr ⟨rfl, hr.symm⟩⟩⟩
rintro ⟨_, hw⟩
exact hw.elim (fun h1 ↦ .inl h1.1.symm) fun hr ↦ .inr hr.2.symm
end MkProperties
namespace Subgraph
variable {G : SimpleGraph V}
/-! ### Subgraphs of subgraphs -/
/-- Given a subgraph of a subgraph of `G`, construct a subgraph of `G`. -/
protected abbrev coeSubgraph {G' : G.Subgraph} : G'.coe.Subgraph → G.Subgraph :=
Subgraph.map G'.hom
/-- Given a subgraph of `G`, restrict it to being a subgraph of another subgraph `G'` by
taking the portion of `G` that intersects `G'`. -/
protected abbrev restrict {G' : G.Subgraph} : G.Subgraph → G'.coe.Subgraph :=
Subgraph.comap G'.hom
@[simp]
lemma verts_coeSubgraph {G' : Subgraph G} (G'' : Subgraph G'.coe) :
(Subgraph.coeSubgraph G'').verts = (G''.verts : Set V) := rfl
lemma coeSubgraph_adj {G' : G.Subgraph} (G'' : G'.coe.Subgraph) (v w : V) :
(G'.coeSubgraph G'').Adj v w ↔
∃ (hv : v ∈ G'.verts) (hw : w ∈ G'.verts), G''.Adj ⟨v, hv⟩ ⟨w, hw⟩ := by
simp [Relation.Map]
lemma restrict_adj {G' G'' : G.Subgraph} (v w : G'.verts) :
(G'.restrict G'').Adj v w ↔ G'.Adj v w ∧ G''.Adj v w := Iff.rfl
theorem restrict_coeSubgraph {G' : G.Subgraph} (G'' : G'.coe.Subgraph) :
Subgraph.restrict (Subgraph.coeSubgraph G'') = G'' := by
ext
· simp
· rw [restrict_adj, coeSubgraph_adj]
simpa using G''.adj_sub
theorem coeSubgraph_injective (G' : G.Subgraph) :
Function.Injective (Subgraph.coeSubgraph : G'.coe.Subgraph → G.Subgraph) :=
Function.LeftInverse.injective restrict_coeSubgraph
lemma coeSubgraph_le {H : G.Subgraph} (H' : H.coe.Subgraph) :
Subgraph.coeSubgraph H' ≤ H := by
constructor
· simp
· rintro v w ⟨_, _, h, rfl, rfl⟩
exact H'.adj_sub h
lemma coeSubgraph_restrict_eq {H : G.Subgraph} (H' : G.Subgraph) :
Subgraph.coeSubgraph (H.restrict H') = H ⊓ H' := by
ext
· simp
· simp_rw [coeSubgraph_adj, restrict_adj]
simp only [exists_and_left, exists_prop, inf_adj, and_congr_right_iff]
intro h
simp [H.edge_vert h, H.edge_vert h.symm]
/-! ### Edge deletion -/
/-- Given a subgraph `G'` and a set of vertex pairs, remove all of the corresponding edges
from its edge set, if present.
See also: `SimpleGraph.deleteEdges`. -/
def deleteEdges (G' : G.Subgraph) (s : Set (Sym2 V)) : G.Subgraph where
verts := G'.verts
Adj := G'.Adj \ Sym2.ToRel s
adj_sub h' := G'.adj_sub h'.1
edge_vert h' := G'.edge_vert h'.1
symm a b := by simp [G'.adj_comm, Sym2.eq_swap]
section DeleteEdges
variable {G' : G.Subgraph} (s : Set (Sym2 V))
@[simp]
theorem deleteEdges_verts : (G'.deleteEdges s).verts = G'.verts :=
rfl
@[simp]
theorem deleteEdges_adj (v w : V) : (G'.deleteEdges s).Adj v w ↔ G'.Adj v w ∧ s(v, w) ∉ s :=
Iff.rfl
@[simp]
theorem deleteEdges_deleteEdges (s s' : Set (Sym2 V)) :
(G'.deleteEdges s).deleteEdges s' = G'.deleteEdges (s ∪ s') := by
ext <;> simp [and_assoc, not_or]
@[simp]
theorem deleteEdges_empty_eq : G'.deleteEdges ∅ = G' := by
ext <;> simp
@[simp]
theorem deleteEdges_spanningCoe_eq :
G'.spanningCoe.deleteEdges s = (G'.deleteEdges s).spanningCoe := by
ext
simp
theorem deleteEdges_coe_eq (s : Set (Sym2 G'.verts)) :
G'.coe.deleteEdges s = (G'.deleteEdges (Sym2.map (↑) '' s)).coe := by
ext ⟨v, hv⟩ ⟨w, hw⟩
simp only [SimpleGraph.deleteEdges_adj, coe_adj, deleteEdges_adj, Set.mem_image, not_exists,
not_and, and_congr_right_iff]
intro
constructor
· intro hs
refine Sym2.ind ?_
rintro ⟨v', hv'⟩ ⟨w', hw'⟩
simp only [Sym2.map_pair_eq, Sym2.eq]
contrapose!
rintro (_ | _) <;> simpa only [Sym2.eq_swap]
· intro h' hs
exact h' _ hs rfl
theorem coe_deleteEdges_eq (s : Set (Sym2 V)) :
(G'.deleteEdges s).coe = G'.coe.deleteEdges (Sym2.map (↑) ⁻¹' s) := by
ext ⟨v, hv⟩ ⟨w, hw⟩
simp
theorem deleteEdges_le : G'.deleteEdges s ≤ G' := by
constructor <;> simp +contextual
theorem deleteEdges_le_of_le {s s' : Set (Sym2 V)} (h : s ⊆ s') :
G'.deleteEdges s' ≤ G'.deleteEdges s := by
constructor <;> simp +contextual only [deleteEdges_verts, deleteEdges_adj,
true_and, and_imp, subset_rfl]
exact fun _ _ _ hs' hs ↦ hs' (h hs)
@[simp]
theorem deleteEdges_inter_edgeSet_left_eq :
G'.deleteEdges (G'.edgeSet ∩ s) = G'.deleteEdges s := by
ext <;> simp +contextual
@[simp]
theorem deleteEdges_inter_edgeSet_right_eq :
G'.deleteEdges (s ∩ G'.edgeSet) = G'.deleteEdges s := by
ext <;> simp +contextual [imp_false]
theorem coe_deleteEdges_le : (G'.deleteEdges s).coe ≤ (G'.coe : SimpleGraph G'.verts) := by
intro v w
simp +contextual
theorem spanningCoe_deleteEdges_le (G' : G.Subgraph) (s : Set (Sym2 V)) :
(G'.deleteEdges s).spanningCoe ≤ G'.spanningCoe :=
spanningCoe_le_of_le (deleteEdges_le s)
end DeleteEdges
/-! ### Induced subgraphs -/
/- Given a subgraph, we can change its vertex set while removing any invalid edges, which
gives induced subgraphs. See also `SimpleGraph.induce` for the `SimpleGraph` version, which,
unlike for subgraphs, results in a graph with a different vertex type. -/
/-- The induced subgraph of a subgraph. The expectation is that `s ⊆ G'.verts` for the usual
notion of an induced subgraph, but, in general, `s` is taken to be the new vertex set and edges
are induced from the subgraph `G'`. -/
@[simps]
def induce (G' : G.Subgraph) (s : Set V) : G.Subgraph where
verts := s
Adj u v := u ∈ s ∧ v ∈ s ∧ G'.Adj u v
adj_sub h := G'.adj_sub h.2.2
edge_vert h := h.1
symm _ _ h := ⟨h.2.1, h.1, G'.symm h.2.2⟩
theorem _root_.SimpleGraph.induce_eq_coe_induce_top (s : Set V) :
G.induce s = ((⊤ : G.Subgraph).induce s).coe := by
ext
simp
section Induce
variable {G' G'' : G.Subgraph} {s s' : Set V}
@[simp]
theorem IsInduced.induce_top_verts (h : G'.IsInduced) : induce ⊤ G'.verts = G' :=
Subgraph.ext rfl <| funext₂ fun _ _ ↦ propext
⟨fun ⟨hu, hv, h'⟩ ↦ h hu hv h', fun h ↦ ⟨G'.edge_vert h, G'.edge_vert h.symm, h.adj_sub⟩⟩
theorem isInduced_iff_exists_eq_induce_top (G' : G.Subgraph) :
G'.IsInduced ↔ ∃ s, G' = induce ⊤ s := by
refine ⟨fun h ↦ ⟨G'.verts, h.induce_top_verts.symm⟩, fun ⟨s, h⟩ _ hu _ hv hadj ↦ ?_⟩
rw [h, (h ▸ rfl : s = G'.verts)]
exact ⟨hu, hv, hadj⟩
@[gcongr]
theorem induce_mono (hg : G' ≤ G'') (hs : s ⊆ s') : G'.induce s ≤ G''.induce s' := by
constructor
· simp [hs]
· simp +contextual only [induce_adj, and_imp]
intro v w hv hw ha
exact ⟨hs hv, hs hw, hg.2 ha⟩
@[mono]
theorem induce_mono_left (hg : G' ≤ G'') : G'.induce s ≤ G''.induce s :=
induce_mono hg subset_rfl
@[mono]
theorem induce_mono_right (hs : s ⊆ s') : G'.induce s ≤ G'.induce s' :=
induce_mono le_rfl hs
@[simp]
theorem induce_empty : G'.induce ∅ = ⊥ := by
ext <;> simp
@[simp]
theorem induce_self_verts : G'.induce G'.verts = G' := by
ext
· simp
· constructor <;>
simp +contextual only [induce_adj, imp_true_iff, and_true]
exact fun ha ↦ ⟨G'.edge_vert ha, G'.edge_vert ha.symm⟩
lemma le_induce_top_verts : G' ≤ (⊤ : G.Subgraph).induce G'.verts :=
calc G' = G'.induce G'.verts := Subgraph.induce_self_verts.symm
_ ≤ (⊤ : G.Subgraph).induce G'.verts := Subgraph.induce_mono_left le_top
lemma le_induce_union : G'.induce s ⊔ G'.induce s' ≤ G'.induce (s ∪ s') := by
constructor
· simp only [verts_sup, induce_verts, Set.Subset.rfl]
· simp only [sup_adj, induce_adj, Set.mem_union]
rintro v w (h | h) <;> simp [h]
lemma le_induce_union_left : G'.induce s ≤ G'.induce (s ∪ s') := by
exact (sup_le_iff.mp le_induce_union).1
lemma le_induce_union_right : G'.induce s' ≤ G'.induce (s ∪ s') := by
exact (sup_le_iff.mp le_induce_union).2
theorem singletonSubgraph_eq_induce {v : V} :
G.singletonSubgraph v = (⊤ : G.Subgraph).induce {v} := by
ext <;> simp +contextual [-Set.bot_eq_empty, Prop.bot_eq_false]
theorem subgraphOfAdj_eq_induce {v w : V} (hvw : G.Adj v w) :
G.subgraphOfAdj hvw = (⊤ : G.Subgraph).induce {v, w} := by
ext
· simp
· constructor
· intro h
simp only [subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff] at h
obtain ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ := h <;> simp [hvw, hvw.symm]
· intro h
simp only [induce_adj, Set.mem_insert_iff, Set.mem_singleton_iff, top_adj] at h
obtain ⟨rfl | rfl, rfl | rfl, ha⟩ := h <;> first |exact (ha.ne rfl).elim|simp
instance instDecidableRel_induce_adj (s : Set V) [∀ a, Decidable (a ∈ s)] [DecidableRel G'.Adj] :
DecidableRel (G'.induce s).Adj :=
fun _ _ ↦ instDecidableAnd
end Induce
/-- Given a subgraph and a set of vertices, delete all the vertices from the subgraph,
if present. Any edges incident to the deleted vertices are deleted as well. -/
abbrev deleteVerts (G' : G.Subgraph) (s : Set V) : G.Subgraph :=
G'.induce (G'.verts \ s)
section DeleteVerts
variable {G' : G.Subgraph} {s : Set V}
theorem deleteVerts_verts : (G'.deleteVerts s).verts = G'.verts \ s :=
rfl
theorem deleteVerts_adj {u v : V} :
(G'.deleteVerts s).Adj u v ↔ u ∈ G'.verts ∧ u ∉ s ∧ v ∈ G'.verts ∧ v ∉ s ∧ G'.Adj u v := by
simp [and_assoc]
@[simp]
theorem deleteVerts_deleteVerts (s s' : Set V) :
(G'.deleteVerts s).deleteVerts s' = G'.deleteVerts (s ∪ s') := by
ext <;> simp +contextual [not_or, and_assoc]
@[simp]
theorem deleteVerts_empty : G'.deleteVerts ∅ = G' := by
simp [deleteVerts]
theorem deleteVerts_le : G'.deleteVerts s ≤ G' := by
constructor <;> simp [Set.diff_subset]
@[gcongr, mono]
theorem deleteVerts_mono {G' G'' : G.Subgraph} (h : G' ≤ G'') :
G'.deleteVerts s ≤ G''.deleteVerts s :=
induce_mono h (Set.diff_subset_diff_left h.1)
@[mono]
lemma deleteVerts_mono' {G' : SimpleGraph V} (u : Set V) (h : G ≤ G') :
((⊤ : Subgraph G).deleteVerts u).coe ≤ ((⊤ : Subgraph G').deleteVerts u).coe := by
intro v w hvw
aesop
@[gcongr, mono]
theorem deleteVerts_anti {s s' : Set V} (h : s ⊆ s') : G'.deleteVerts s' ≤ G'.deleteVerts s :=
induce_mono (le_refl _) (Set.diff_subset_diff_right h)
@[simp]
theorem deleteVerts_inter_verts_left_eq : G'.deleteVerts (G'.verts ∩ s) = G'.deleteVerts s := by
ext <;> simp +contextual
@[simp]
theorem deleteVerts_inter_verts_set_right_eq :
G'.deleteVerts (s ∩ G'.verts) = G'.deleteVerts s := by
ext <;> simp +contextual
instance instDecidableRel_deleteVerts_adj (u : Set V) [r : DecidableRel G.Adj] :
DecidableRel ((⊤ : G.Subgraph).deleteVerts u).coe.Adj :=
fun x y =>
if h : G.Adj x y
then
.isTrue <| SimpleGraph.Subgraph.Adj.coe <| Subgraph.deleteVerts_adj.mpr
⟨by trivial, x.2.2, by trivial, y.2.2, h⟩
else
.isFalse <| fun hadj ↦ h <| Subgraph.coe_adj_sub _ _ _ hadj
end DeleteVerts
end Subgraph
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/LapMatrix.lean | import Mathlib.Analysis.Matrix.Order
import Mathlib.Combinatorics.SimpleGraph.AdjMatrix
/-!
# Laplacian Matrix
This module defines the Laplacian matrix of a graph, and proves some of its elementary properties.
## Main definitions & Results
* `SimpleGraph.degMatrix`: The degree matrix of a simple graph
* `SimpleGraph.lapMatrix`: The Laplacian matrix of a simple graph, defined as the difference
between the degree matrix and the adjacency matrix.
* `isPosSemidef_lapMatrix`: The Laplacian matrix is positive semidefinite.
* `card_connectedComponent_eq_finrank_ker_toLin'_lapMatrix`:
The number of connected components in a graph
is the dimension of the nullspace of its Laplacian matrix.
-/
open Finset Matrix Module
namespace SimpleGraph
variable {V : Type*} (R : Type*)
variable [Fintype V] (G : SimpleGraph V) [DecidableRel G.Adj]
theorem degree_eq_sum_if_adj {R : Type*} [AddCommMonoidWithOne R] (i : V) :
(G.degree i : R) = ∑ j : V, if G.Adj i j then 1 else 0 := by
unfold degree neighborFinset neighborSet
rw [sum_boole, Set.toFinset_setOf]
variable [DecidableEq V]
/-- The diagonal matrix consisting of the degrees of the vertices in the graph. -/
def degMatrix [AddMonoidWithOne R] : Matrix V V R := Matrix.diagonal (G.degree ·)
/-- The *Laplacian matrix* `lapMatrix G R` of a graph `G`
is the matrix `L = D - A` where `D` is the degree and `A` the adjacency matrix of `G`. -/
def lapMatrix [AddGroupWithOne R] : Matrix V V R := G.degMatrix R - G.adjMatrix R
variable {R}
theorem isSymm_degMatrix [AddMonoidWithOne R] : (G.degMatrix R).IsSymm :=
isSymm_diagonal _
theorem isSymm_lapMatrix [AddGroupWithOne R] : (G.lapMatrix R).IsSymm :=
(isSymm_degMatrix _).sub (isSymm_adjMatrix _)
theorem degMatrix_mulVec_apply [NonAssocSemiring R] (v : V) (vec : V → R) :
(G.degMatrix R *ᵥ vec) v = G.degree v * vec v := by
rw [degMatrix, mulVec_diagonal]
theorem lapMatrix_mulVec_apply [NonAssocRing R] (v : V) (vec : V → R) :
(G.lapMatrix R *ᵥ vec) v = G.degree v * vec v - ∑ u ∈ G.neighborFinset v, vec u := by
simp_rw [lapMatrix, sub_mulVec, Pi.sub_apply, degMatrix_mulVec_apply, adjMatrix_mulVec_apply]
theorem lapMatrix_mulVec_const_eq_zero [NonAssocRing R] :
mulVec (G.lapMatrix R) (fun _ ↦ 1) = 0 := by
ext1 i
rw [lapMatrix_mulVec_apply]
simp
theorem dotProduct_mulVec_degMatrix [CommSemiring R] (x : V → R) :
x ⬝ᵥ (G.degMatrix R *ᵥ x) = ∑ i : V, G.degree i * x i * x i := by
simp only [dotProduct, degMatrix, mulVec_diagonal, ← mul_assoc, mul_comm]
variable (R)
/-- Let $L$ be the graph Laplacian and let $x \in \mathbb{R}$, then
$$x^{\top} L x = \sum_{i \sim j} (x_{i}-x_{j})^{2}$$,
where $\sim$ denotes the adjacency relation -/
theorem lapMatrix_toLinearMap₂' [Field R] [CharZero R] (x : V → R) :
toLinearMap₂' R (G.lapMatrix R) x x =
(∑ i : V, ∑ j : V, if G.Adj i j then (x i - x j)^2 else 0) / 2 := by
simp_rw [toLinearMap₂'_apply', lapMatrix, sub_mulVec, dotProduct_sub, dotProduct_mulVec_degMatrix,
dotProduct_mulVec_adjMatrix, ← sum_sub_distrib, degree_eq_sum_if_adj, sum_mul, ite_mul, one_mul,
zero_mul, ← sum_sub_distrib, ite_sub_ite, sub_zero]
rw [← add_self_div_two (∑ x_1 : V, ∑ x_2 : V, _)]
conv_lhs => enter [1,2,2,i,2,j]; rw [if_congr (adj_comm G i j) rfl rfl]
conv_lhs => enter [1,2]; rw [Finset.sum_comm]
simp_rw [← sum_add_distrib, ite_add_ite]
congr 2 with i
congr 2 with j
ring_nf
/-- The Laplacian matrix is positive semidefinite -/
theorem posSemidef_lapMatrix [Field R] [LinearOrder R] [IsStrictOrderedRing R] [StarRing R]
[TrivialStar R] : PosSemidef (G.lapMatrix R) := by
constructor
· rw [IsHermitian, conjTranspose_eq_transpose_of_trivial, isSymm_lapMatrix]
· intro x
rw [star_trivial, ← toLinearMap₂'_apply', lapMatrix_toLinearMap₂']
positivity
theorem lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_adj
[Field R] [LinearOrder R] [IsStrictOrderedRing R] (x : V → R) :
Matrix.toLinearMap₂' R (G.lapMatrix R) x x = 0 ↔ ∀ i j : V, G.Adj i j → x i = x j := by
simp (disch := intros; positivity)
[lapMatrix_toLinearMap₂', sum_eq_zero_iff_of_nonneg, sub_eq_zero]
theorem lapMatrix_mulVec_eq_zero_iff_forall_adj {x : V → ℝ} :
G.lapMatrix ℝ *ᵥ x = 0 ↔ ∀ i j : V, G.Adj i j → x i = x j := by
rw [← (posSemidef_lapMatrix ℝ G).toLinearMap₂'_zero_iff, star_trivial,
lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_adj]
@[deprecated lapMatrix_mulVec_eq_zero_iff_forall_adj (since := "2025-05-18")]
theorem lapMatrix_toLin'_apply_eq_zero_iff_forall_adj (x : V → ℝ) :
Matrix.toLin' (G.lapMatrix ℝ) x = 0 ↔ ∀ i j : V, G.Adj i j → x i = x j :=
G.lapMatrix_mulVec_eq_zero_iff_forall_adj
theorem lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_reachable (x : V → ℝ) :
Matrix.toLinearMap₂' ℝ (G.lapMatrix ℝ) x x = 0 ↔
∀ i j : V, G.Reachable i j → x i = x j := by
rw [lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_adj]
refine ⟨?_, fun h i j hA ↦ h i j hA.reachable⟩
intro h i j ⟨w⟩
induction w with
| nil => rfl
| cons hA _ h' => exact (h _ _ hA).trans h'
theorem lapMatrix_mulVec_eq_zero_iff_forall_reachable {x : V → ℝ} :
G.lapMatrix ℝ *ᵥ x = 0 ↔ ∀ i j : V, G.Reachable i j → x i = x j := by
rw [← (posSemidef_lapMatrix ℝ G).toLinearMap₂'_zero_iff, star_trivial,
lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_reachable]
@[deprecated lapMatrix_mulVec_eq_zero_iff_forall_reachable (since := "2025-05-18")]
theorem lapMatrix_toLin'_apply_eq_zero_iff_forall_reachable (x : V → ℝ) :
Matrix.toLin' (G.lapMatrix ℝ) x = 0 ↔ ∀ i j : V, G.Reachable i j → x i = x j :=
G.lapMatrix_mulVec_eq_zero_iff_forall_reachable
@[simp]
theorem det_lapMatrix_eq_zero [h : Nonempty V] : (G.lapMatrix ℝ).det = 0 := by
rw [← Matrix.exists_mulVec_eq_zero_iff]
use fun _ ↦ 1
refine ⟨?_, (lapMatrix_mulVec_eq_zero_iff_forall_adj G).mpr fun _ _ _ ↦ rfl⟩
rw [← Function.support_nonempty_iff]
use Classical.choice h
simp
section
variable [DecidableEq G.ConnectedComponent]
lemma mem_ker_toLin'_lapMatrix_of_connectedComponent {G : SimpleGraph V} [DecidableRel G.Adj]
[DecidableEq G.ConnectedComponent] (c : G.ConnectedComponent) :
(fun i ↦ if connectedComponentMk G i = c then 1 else 0) ∈
LinearMap.ker (toLin' (lapMatrix ℝ G)) := by
rw [LinearMap.mem_ker, toLin'_apply, lapMatrix_mulVec_eq_zero_iff_forall_reachable]
intro i j h
split_ifs with h₁ h₂ h₃
· rfl
· rw [← ConnectedComponent.eq] at h
exact (h₂ (h₁ ▸ h.symm)).elim
· rw [← ConnectedComponent.eq] at h
exact (h₁ (h₃ ▸ h)).elim
· rfl
/-- Given a connected component `c` of a graph `G`, `lapMatrix_ker_basis_aux c` is the map
`V → ℝ` which is `1` on the vertices in `c` and `0` elsewhere.
The family of these maps indexed by the connected components of `G` proves to be a basis
of the kernel of `lapMatrix G R` -/
def lapMatrix_ker_basis_aux (c : G.ConnectedComponent) :
LinearMap.ker (Matrix.toLin' (G.lapMatrix ℝ)) :=
⟨fun i ↦ if G.connectedComponentMk i = c then (1 : ℝ) else 0,
mem_ker_toLin'_lapMatrix_of_connectedComponent c⟩
lemma linearIndependent_lapMatrix_ker_basis_aux :
LinearIndependent ℝ (lapMatrix_ker_basis_aux G) := by
rw [Fintype.linearIndependent_iff]
intro g h0
rw [Subtype.ext_iff] at h0
have h : ∑ c, g c • lapMatrix_ker_basis_aux G c = fun i ↦ g (connectedComponentMk G i) := by
simp only [lapMatrix_ker_basis_aux, SetLike.mk_smul_mk]
repeat rw [AddSubmonoid.coe_finset_sum]
ext i
simp only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul, mul_ite, mul_one, mul_zero, sum_ite_eq,
mem_univ, ↓reduceIte]
rw [h] at h0
intro c
obtain ⟨i, h'⟩ : ∃ i : V, G.connectedComponentMk i = c := Quot.exists_rep c
exact h' ▸ congrFun h0 i
lemma top_le_span_range_lapMatrix_ker_basis_aux :
⊤ ≤ Submodule.span ℝ (Set.range (lapMatrix_ker_basis_aux G)) := by
intro x _
rw [Submodule.mem_span_range_iff_exists_fun]
use Quot.lift x.val (by rw [← lapMatrix_mulVec_eq_zero_iff_forall_reachable,
← toLin'_apply, LinearMap.map_coe_ker])
ext j
simp only [lapMatrix_ker_basis_aux]
rw [AddSubmonoid.coe_finset_sum]
simp only [SetLike.mk_smul_mk, Finset.sum_apply, Pi.smul_apply, smul_eq_mul, mul_ite, mul_one,
mul_zero, sum_ite_eq, mem_univ, ↓reduceIte]
rfl
/-- `lapMatrix_ker_basis G` is a basis of the nullspace indexed by its connected components,
the basis is made up of the functions `V → ℝ` which are `1` on the vertices of the given
connected component and `0` elsewhere. -/
noncomputable def lapMatrix_ker_basis :=
Basis.mk (linearIndependent_lapMatrix_ker_basis_aux G)
(top_le_span_range_lapMatrix_ker_basis_aux G)
end
/-- The number of connected components in `G` is the dimension of the nullspace of its Laplacian. -/
theorem card_connectedComponent_eq_finrank_ker_toLin'_lapMatrix :
Fintype.card G.ConnectedComponent =
Module.finrank ℝ (LinearMap.ker (Matrix.toLin' (G.lapMatrix ℝ))) := by
classical
rw [Module.finrank_eq_card_basis (lapMatrix_ker_basis G)]
@[deprecated (since := "2025-04-29")]
alias card_ConnectedComponent_eq_rank_ker_lapMatrix :=
card_connectedComponent_eq_finrank_ker_toLin'_lapMatrix
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Bipartite.lean | import Mathlib.Algebra.Notation.Indicator
import Mathlib.Combinatorics.Enumerative.DoubleCounting
import Mathlib.Combinatorics.SimpleGraph.Coloring
import Mathlib.Combinatorics.SimpleGraph.DegreeSum
/-!
# Bipartite graphs
This file proves results about bipartite simple graphs, including several double-counting arguments.
## Main definitions
* `SimpleGraph.IsBipartiteWith G s t` is the condition that a simple graph `G` is bipartite in sets
`s`, `t`, that is, `s` and `t` are disjoint and vertices `v`, `w` being adjacent in `G` implies
that `v ∈ s` and `w ∈ t`, or `v ∈ s` and `w ∈ t`.
Note that in this implementation, if `G.IsBipartiteWith s t`, `s ∪ t` need not cover the vertices
of `G`, instead `s ∪ t` is only required to cover the *support* of `G`, that is, the vertices
that form edges in `G`. This definition is equivalent to the expected definition. If `s` and `t`
do not cover all the vertices, one recovers a covering of all the vertices by unioning the
missing vertices `(s ∪ t)ᶜ` to either `s` or `t`.
* `SimpleGraph.IsBipartite`: Predicate for a simple graph to be bipartite.
`G.IsBipartite` is defined as an abbreviation for `G.Colorable 2`.
* `SimpleGraph.isBipartite_iff_exists_isBipartiteWith` is the proof that `G.IsBipartite` iff
`G.IsBipartiteWith s t`.
* `SimpleGraph.isBipartiteWith_sum_degrees_eq` is the proof that if `G.IsBipartiteWith s t`, then
the sum of the degrees of the vertices in `s` is equal to the sum of the degrees of the vertices
in `t`.
* `SimpleGraph.isBipartiteWith_sum_degrees_eq_card_edges` is the proof that if
`G.IsBipartiteWith s t`, then sum of the degrees of the vertices in `s` is equal to the number of
edges in `G`.
See `SimpleGraph.sum_degrees_eq_twice_card_edges` for the general version, and
`SimpleGraph.isBipartiteWith_sum_degrees_eq_card_edges'` for the version from the "right".
* `SimpleGraph.between`; the simple graph `G.between s t` is the subgraph of `G` containing edges
that connect a vertex in the set `s` to a vertex in the set `t`.
## Implementation notes
For the formulation of double-counting arguments where a bipartite graph is considered as a
relation `r : α → β → Prop`, see `Mathlib/Combinatorics/Enumerative/DoubleCounting.lean`.
## TODO
* Prove that `G.IsBipartite` iff `G` does not contain an odd cycle.
I.e., `G.IsBipartite ↔ ∀ n, (cycleGraph (2*n+1)).Free G`.
-/
open BigOperators Finset Fintype
namespace SimpleGraph
variable {V : Type*} {v w : V} {G : SimpleGraph V} {s t : Set V}
section IsBipartiteWith
/-- `G` is bipartite in sets `s` and `t` iff `s` and `t` are disjoint and if vertices `v` and `w`
are adjacent in `G` then `v ∈ s` and `w ∈ t`, or `v ∈ t` and `w ∈ s`. -/
structure IsBipartiteWith (G : SimpleGraph V) (s t : Set V) : Prop where
disjoint : Disjoint s t
mem_of_adj ⦃v w : V⦄ : G.Adj v w → v ∈ s ∧ w ∈ t ∨ v ∈ t ∧ w ∈ s
theorem IsBipartiteWith.symm (h : G.IsBipartiteWith s t) : G.IsBipartiteWith t s where
disjoint := h.disjoint.symm
mem_of_adj v w hadj := by
rw [@and_comm (v ∈ t) (w ∈ s), @and_comm (v ∈ s) (w ∈ t)]
exact h.mem_of_adj hadj.symm
theorem isBipartiteWith_comm : G.IsBipartiteWith s t ↔ G.IsBipartiteWith t s :=
⟨IsBipartiteWith.symm, IsBipartiteWith.symm⟩
/-- If `G.IsBipartiteWith s t` and `v ∈ s`, then if `v` is adjacent to `w` in `G` then `w ∈ t`. -/
theorem IsBipartiteWith.mem_of_mem_adj
(h : G.IsBipartiteWith s t) (hv : v ∈ s) (hadj : G.Adj v w) : w ∈ t := by
apply h.mem_of_adj at hadj
have nhv : v ∉ t := Set.disjoint_left.mp h.disjoint hv
simpa [hv, nhv] using hadj
/-- If `G.IsBipartiteWith s t` and `v ∈ s`, then the neighbor set of `v` is the set of vertices in
`t` adjacent to `v` in `G`. -/
theorem isBipartiteWith_neighborSet (h : G.IsBipartiteWith s t) (hv : v ∈ s) :
G.neighborSet v = { w ∈ t | G.Adj v w } := by
ext w
rw [mem_neighborSet, Set.mem_setOf_eq, iff_and_self]
exact h.mem_of_mem_adj hv
/-- If `G.IsBipartiteWith s t` and `v ∈ s`, then the neighbor set of `v` is a subset of `t`. -/
theorem isBipartiteWith_neighborSet_subset (h : G.IsBipartiteWith s t) (hv : v ∈ s) :
G.neighborSet v ⊆ t := by
rw [isBipartiteWith_neighborSet h hv]
exact Set.sep_subset t (G.Adj v ·)
/-- If `G.IsBipartiteWith s t` and `v ∈ s`, then the neighbor set of `v` is disjoint to `s`. -/
theorem isBipartiteWith_neighborSet_disjoint (h : G.IsBipartiteWith s t) (hv : v ∈ s) :
Disjoint (G.neighborSet v) s :=
Set.disjoint_of_subset_left (isBipartiteWith_neighborSet_subset h hv) h.disjoint.symm
/-- If `G.IsBipartiteWith s t` and `w ∈ t`, then if `v` is adjacent to `w` in `G` then `v ∈ s`. -/
theorem IsBipartiteWith.mem_of_mem_adj'
(h : G.IsBipartiteWith s t) (hw : w ∈ t) (hadj : G.Adj v w) : v ∈ s := by
apply h.mem_of_adj at hadj
have nhw : w ∉ s := Set.disjoint_right.mp h.disjoint hw
simpa [hw, nhw] using hadj
/-- If `G.IsBipartiteWith s t` and `w ∈ t`, then the neighbor set of `w` is the set of vertices in
`s` adjacent to `w` in `G`. -/
theorem isBipartiteWith_neighborSet' (h : G.IsBipartiteWith s t) (hw : w ∈ t) :
G.neighborSet w = { v ∈ s | G.Adj v w } := by
ext v
rw [mem_neighborSet, adj_comm, Set.mem_setOf_eq, iff_and_self]
exact h.mem_of_mem_adj' hw
/-- If `G.IsBipartiteWith s t` and `w ∈ t`, then the neighbor set of `w` is a subset of `s`. -/
theorem isBipartiteWith_neighborSet_subset' (h : G.IsBipartiteWith s t) (hw : w ∈ t) :
G.neighborSet w ⊆ s := by
rw [isBipartiteWith_neighborSet' h hw]
exact Set.sep_subset s (G.Adj · w)
/-- If `G.IsBipartiteWith s t`, then the support of `G` is a subset of `s ∪ t`. -/
theorem isBipartiteWith_support_subset (h : G.IsBipartiteWith s t) : G.support ⊆ s ∪ t := by
intro v ⟨w, hadj⟩
apply h.mem_of_adj at hadj
tauto
/-- If `G.IsBipartiteWith s t` and `w ∈ t`, then the neighbor set of `w` is disjoint to `t`. -/
theorem isBipartiteWith_neighborSet_disjoint' (h : G.IsBipartiteWith s t) (hw : w ∈ t) :
Disjoint (G.neighborSet w) t :=
Set.disjoint_of_subset_left (isBipartiteWith_neighborSet_subset' h hw) h.disjoint
variable {s t : Finset V} [DecidableRel G.Adj]
section
variable [Fintype ↑(G.neighborSet v)] [Fintype ↑(G.neighborSet w)]
/-- If `G.IsBipartiteWith s t` and `v ∈ s`, then the neighbor finset of `v` is the set of vertices
in `s` adjacent to `v` in `G`. -/
theorem isBipartiteWith_neighborFinset (h : G.IsBipartiteWith s t) (hv : v ∈ s) :
G.neighborFinset v = { w ∈ t | G.Adj v w } := by
ext w
rw [mem_neighborFinset, mem_filter, iff_and_self]
exact h.mem_of_mem_adj hv
/-- If `G.IsBipartiteWith s t` and `v ∈ s`, then the neighbor finset of `v` is the set of vertices
"above" `v` according to the adjacency relation of `G`. -/
theorem isBipartiteWith_bipartiteAbove (h : G.IsBipartiteWith s t) (hv : v ∈ s) :
G.neighborFinset v = bipartiteAbove G.Adj t v := by
rw [isBipartiteWith_neighborFinset h hv, bipartiteAbove]
/-- If `G.IsBipartiteWith s t` and `v ∈ s`, then the neighbor finset of `v` is a subset of `s`. -/
theorem isBipartiteWith_neighborFinset_subset (h : G.IsBipartiteWith s t) (hv : v ∈ s) :
G.neighborFinset v ⊆ t := by
rw [isBipartiteWith_neighborFinset h hv]
exact filter_subset (G.Adj v ·) t
omit [DecidableRel G.Adj] in
/-- If `G.IsBipartiteWith s t` and `v ∈ s`, then the neighbor finset of `v` is disjoint to `s`. -/
theorem isBipartiteWith_neighborFinset_disjoint (h : G.IsBipartiteWith s t) (hv : v ∈ s) :
Disjoint (G.neighborFinset v) s := by
rw [neighborFinset_def, ← disjoint_coe, Set.coe_toFinset]
exact isBipartiteWith_neighborSet_disjoint h hv
/-- If `G.IsBipartiteWith s t` and `v ∈ s`, then the degree of `v` in `G` is at most the size of
`t`. -/
theorem isBipartiteWith_degree_le (h : G.IsBipartiteWith s t) (hv : v ∈ s) : G.degree v ≤ #t := by
rw [← card_neighborFinset_eq_degree]
exact card_le_card (isBipartiteWith_neighborFinset_subset h hv)
/-- If `G.IsBipartiteWith s t` and `w ∈ t`, then the neighbor finset of `w` is the set of vertices
in `s` adjacent to `w` in `G`. -/
theorem isBipartiteWith_neighborFinset' (h : G.IsBipartiteWith s t) (hw : w ∈ t) :
G.neighborFinset w = { v ∈ s | G.Adj v w } := by
ext v
rw [mem_neighborFinset, adj_comm, mem_filter, iff_and_self]
exact h.mem_of_mem_adj' hw
/-- If `G.IsBipartiteWith s t` and `w ∈ t`, then the neighbor finset of `w` is the set of vertices
"below" `w` according to the adjacency relation of `G`. -/
theorem isBipartiteWith_bipartiteBelow (h : G.IsBipartiteWith s t) (hw : w ∈ t) :
G.neighborFinset w = bipartiteBelow G.Adj s w := by
rw [isBipartiteWith_neighborFinset' h hw, bipartiteBelow]
/-- If `G.IsBipartiteWith s t` and `w ∈ t`, then the neighbor finset of `w` is a subset of `s`. -/
theorem isBipartiteWith_neighborFinset_subset' (h : G.IsBipartiteWith s t) (hw : w ∈ t) :
G.neighborFinset w ⊆ s := by
rw [isBipartiteWith_neighborFinset' h hw]
exact filter_subset (G.Adj · w) s
omit [DecidableRel G.Adj] in
/-- If `G.IsBipartiteWith s t` and `w ∈ t`, then the neighbor finset of `w` is disjoint to `t`. -/
theorem isBipartiteWith_neighborFinset_disjoint' (h : G.IsBipartiteWith s t) (hw : w ∈ t) :
Disjoint (G.neighborFinset w) t := by
rw [neighborFinset_def, ← disjoint_coe, Set.coe_toFinset]
exact isBipartiteWith_neighborSet_disjoint' h hw
/-- If `G.IsBipartiteWith s t` and `w ∈ t`, then the degree of `w` in `G` is at most the size of
`s`. -/
theorem isBipartiteWith_degree_le' (h : G.IsBipartiteWith s t) (hw : w ∈ t) : G.degree w ≤ #s := by
rw [← card_neighborFinset_eq_degree]
exact card_le_card (isBipartiteWith_neighborFinset_subset' h hw)
end
/-- If `G.IsBipartiteWith s t`, then the sum of the degrees of vertices in `s` is equal to the sum
of the degrees of vertices in `t`.
See `Finset.sum_card_bipartiteAbove_eq_sum_card_bipartiteBelow`. -/
theorem isBipartiteWith_sum_degrees_eq [G.LocallyFinite] (h : G.IsBipartiteWith s t) :
∑ v ∈ s, G.degree v = ∑ w ∈ t, G.degree w := by
simp_rw [← sum_attach t, ← sum_attach s, ← card_neighborFinset_eq_degree]
conv_lhs =>
rhs; intro v
rw [isBipartiteWith_bipartiteAbove h v.prop]
conv_rhs =>
rhs; intro w
rw [isBipartiteWith_bipartiteBelow h w.prop]
simp_rw [sum_attach s fun w ↦ #(bipartiteAbove G.Adj t w),
sum_attach t fun v ↦ #(bipartiteBelow G.Adj s v)]
exact sum_card_bipartiteAbove_eq_sum_card_bipartiteBelow G.Adj
variable [Fintype V]
lemma isBipartiteWith_sum_degrees_eq_twice_card_edges [DecidableEq V] (h : G.IsBipartiteWith s t) :
∑ v ∈ s ∪ t, G.degree v = 2 * #G.edgeFinset := by
have hsub : G.support ⊆ ↑s ∪ ↑t := isBipartiteWith_support_subset h
rw [← coe_union, ← Set.toFinset_subset] at hsub
rw [← Finset.sum_subset hsub, ← sum_degrees_support_eq_twice_card_edges]
intro v _ hv
rwa [Set.mem_toFinset, ← degree_eq_zero_iff_notMem_support] at hv
/-- The degree-sum formula for bipartite graphs, summing over the "left" part.
See `SimpleGraph.sum_degrees_eq_twice_card_edges` for the general version, and
`SimpleGraph.isBipartiteWith_sum_degrees_eq_card_edges'` for the version from the "right". -/
theorem isBipartiteWith_sum_degrees_eq_card_edges (h : G.IsBipartiteWith s t) :
∑ v ∈ s, G.degree v = #G.edgeFinset := by
classical
rw [← Nat.mul_left_cancel_iff zero_lt_two, ← isBipartiteWith_sum_degrees_eq_twice_card_edges h,
sum_union (disjoint_coe.mp h.disjoint), two_mul, add_right_inj]
exact isBipartiteWith_sum_degrees_eq h
/-- The degree-sum formula for bipartite graphs, summing over the "right" part.
See `SimpleGraph.sum_degrees_eq_twice_card_edges` for the general version, and
`SimpleGraph.isBipartiteWith_sum_degrees_eq_card_edges` for the version from the "left". -/
theorem isBipartiteWith_sum_degrees_eq_card_edges' (h : G.IsBipartiteWith s t) :
∑ v ∈ t, G.degree v = #G.edgeFinset := isBipartiteWith_sum_degrees_eq_card_edges h.symm
end IsBipartiteWith
section IsBipartite
/-- The predicate for a simple graph to be bipartite. -/
abbrev IsBipartite (G : SimpleGraph V) : Prop := G.Colorable 2
/-- If a simple graph `G` is bipartite, then there exist disjoint sets `s` and `t`
such that all edges in `G` connect a vertex in `s` to a vertex in `t`. -/
lemma IsBipartite.exists_isBipartiteWith (h : G.IsBipartite) : ∃ s t, G.IsBipartiteWith s t := by
obtain ⟨c, hc⟩ := h
refine ⟨{v | c v = 0}, {v | c v = 1}, by aesop (add simp [Set.disjoint_left]), ?_⟩
rintro v w hvw
apply hc at hvw
simp [Set.mem_setOf_eq] at hvw ⊢
cutsat
/-- If a simple graph `G` has a bipartition, then it is bipartite. -/
lemma IsBipartiteWith.isBipartite {s t : Set V} (h : G.IsBipartiteWith s t) : G.IsBipartite := by
refine ⟨s.indicator 1, fun {v w} hw ↦ ?_⟩
obtain (⟨hs, ht⟩ | ⟨ht, hs⟩) := h.2 hw <;>
{ replace ht : _ ∉ s := h.1.subset_compl_left ht; simp [hs, ht] }
/-- `G.IsBipartite` if and only if `G.IsBipartiteWith s t`. -/
theorem isBipartite_iff_exists_isBipartiteWith :
G.IsBipartite ↔ ∃ s t : Set V, G.IsBipartiteWith s t :=
⟨IsBipartite.exists_isBipartiteWith, fun ⟨_, _, h⟩ ↦ h.isBipartite⟩
end IsBipartite
section Between
/-- The subgraph of `G` containing edges that connect a vertex in the set `s` to a vertex in the
set `t`. -/
def between (s t : Set V) (G : SimpleGraph V) : SimpleGraph V where
Adj v w := G.Adj v w ∧ (v ∈ s ∧ w ∈ t ∨ v ∈ t ∧ w ∈ s)
symm v w := by tauto
lemma between_adj : (G.between s t).Adj v w ↔ G.Adj v w ∧ (v ∈ s ∧ w ∈ t ∨ v ∈ t ∧ w ∈ s) := by rfl
lemma between_le : G.between s t ≤ G := fun _ _ h ↦ h.1
lemma between_comm : G.between s t = G.between t s := by simp [between, or_comm]
instance [DecidableRel G.Adj] [DecidablePred (· ∈ s)] [DecidablePred (· ∈ t)] :
DecidableRel (G.between s t).Adj :=
inferInstanceAs (DecidableRel fun v w ↦ G.Adj v w ∧ (v ∈ s ∧ w ∈ t ∨ v ∈ t ∧ w ∈ s))
/-- `G.between s t` is bipartite if the sets `s` and `t` are disjoint. -/
theorem between_isBipartiteWith (h : Disjoint s t) : (G.between s t).IsBipartiteWith s t where
disjoint := h
mem_of_adj _ _ h := h.2
/-- `G.between s t` is bipartite if the sets `s` and `t` are disjoint. -/
theorem between_isBipartite (h : Disjoint s t) : (G.between s t).IsBipartite :=
(between_isBipartiteWith h).isBipartite
/-- The neighbor set of `v ∈ s` in `G.between s sᶜ` excludes the vertices in `s` adjacent to `v`
in `G`. -/
lemma neighborSet_subset_between_union (hv : v ∈ s) :
G.neighborSet v ⊆ (G.between s sᶜ).neighborSet v ∪ s := by
intro w hadj
rw [neighborSet, Set.mem_union, Set.mem_setOf, between_adj]
by_cases hw : w ∈ s
· exact Or.inr hw
· exact Or.inl ⟨hadj, Or.inl ⟨hv, hw⟩⟩
/-- The neighbor set of `w ∈ sᶜ` in `G.between s sᶜ` excludes the vertices in `sᶜ` adjacent to `w`
in `G`. -/
lemma neighborSet_subset_between_union_compl (hw : w ∈ sᶜ) :
G.neighborSet w ⊆ (G.between s sᶜ).neighborSet w ∪ sᶜ := by
intro v hadj
rw [neighborSet, Set.mem_union, Set.mem_setOf, between_adj]
by_cases hv : v ∈ s
· exact Or.inl ⟨hadj, Or.inr ⟨hw, hv⟩⟩
· exact Or.inr hv
variable [DecidableEq V] [Fintype V] {s t : Finset V} [DecidableRel G.Adj]
/-- The neighbor finset of `v ∈ s` in `G.between s sᶜ` excludes the vertices in `s` adjacent to `v`
in `G`. -/
lemma neighborFinset_subset_between_union (hv : v ∈ s) :
G.neighborFinset v ⊆ (G.between s sᶜ).neighborFinset v ∪ s := by
simpa [neighborFinset_def] using neighborSet_subset_between_union hv
/-- The degree of `v ∈ s` in `G` is at most the degree in `G.between s sᶜ` plus the excluded
vertices from `s`. -/
theorem degree_le_between_add (hv : v ∈ s) :
G.degree v ≤ (G.between s sᶜ).degree v + s.card := by
have h_bipartite : (G.between s sᶜ).IsBipartiteWith s ↑(sᶜ) := by
simpa using between_isBipartiteWith disjoint_compl_right
simp_rw [← card_neighborFinset_eq_degree,
← card_union_of_disjoint (isBipartiteWith_neighborFinset_disjoint h_bipartite hv)]
exact card_le_card (neighborFinset_subset_between_union hv)
/-- The neighbor finset of `w ∈ sᶜ` in `G.between s sᶜ` excludes the vertices in `sᶜ` adjacent to
`w` in `G`. -/
lemma neighborFinset_subset_between_union_compl (hw : w ∈ sᶜ) :
G.neighborFinset w ⊆ (G.between s sᶜ).neighborFinset w ∪ sᶜ := by
simpa [neighborFinset_def] using G.neighborSet_subset_between_union_compl (by simpa using hw)
/-- The degree of `w ∈ sᶜ` in `G` is at most the degree in `G.between s sᶜ` plus the excluded
vertices from `sᶜ`. -/
theorem degree_le_between_add_compl (hw : w ∈ sᶜ) :
G.degree w ≤ (G.between s sᶜ).degree w + sᶜ.card := by
have h_bipartite : (G.between s sᶜ).IsBipartiteWith s ↑(sᶜ) := by
simpa using between_isBipartiteWith disjoint_compl_right
simp_rw [← card_neighborFinset_eq_degree,
← card_union_of_disjoint (isBipartiteWith_neighborFinset_disjoint' h_bipartite hw)]
exact card_le_card (neighborFinset_subset_between_union_compl hw)
end Between
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Clique.lean | import Mathlib.Combinatorics.SimpleGraph.Copy
import Mathlib.Combinatorics.SimpleGraph.Operations
import Mathlib.Combinatorics.SimpleGraph.Paths
import Mathlib.Data.Finset.Pairwise
import Mathlib.Data.Fintype.Pigeonhole
import Mathlib.Data.Fintype.Powerset
import Mathlib.Data.Nat.Lattice
import Mathlib.SetTheory.Cardinal.Finite
/-!
# Graph cliques
This file defines cliques in simple graphs.
A clique is a set of vertices that are pairwise adjacent.
## Main declarations
* `SimpleGraph.IsClique`: Predicate for a set of vertices to be a clique.
* `SimpleGraph.IsNClique`: Predicate for a set of vertices to be an `n`-clique.
* `SimpleGraph.cliqueFinset`: Finset of `n`-cliques of a graph.
* `SimpleGraph.CliqueFree`: Predicate for a graph to have no `n`-cliques.
-/
open Finset Fintype Function SimpleGraph.Walk
namespace SimpleGraph
variable {α β : Type*} (G H : SimpleGraph α)
/-! ### Cliques -/
section Clique
variable {s t : Set α}
/-- A clique in a graph is a set of vertices that are pairwise adjacent. -/
abbrev IsClique (s : Set α) : Prop :=
s.Pairwise G.Adj
theorem isClique_iff : G.IsClique s ↔ s.Pairwise G.Adj :=
Iff.rfl
lemma not_isClique_iff : ¬ G.IsClique s ↔ ∃ (v w : s), v ≠ w ∧ ¬ G.Adj v w := by
aesop (add simp [isClique_iff, Set.Pairwise])
/-- A clique is a set of vertices whose induced graph is complete. -/
theorem isClique_iff_induce_eq : G.IsClique s ↔ G.induce s = ⊤ := by
rw [isClique_iff]
constructor
· intro h
ext ⟨v, hv⟩ ⟨w, hw⟩
simp only [comap_adj, top_adj, Ne, Subtype.mk_eq_mk]
exact ⟨Adj.ne, h hv hw⟩
· intro h v hv w hw hne
have h2 : (G.induce s).Adj ⟨v, hv⟩ ⟨w, hw⟩ = _ := rfl
conv_lhs at h2 => rw [h]
simp only [top_adj, ne_eq, Subtype.mk.injEq, eq_iff_iff] at h2
exact h2.1 hne
instance [DecidableEq α] [DecidableRel G.Adj] {s : Finset α} : Decidable (G.IsClique s) :=
decidable_of_iff' _ G.isClique_iff
variable {G H} {a b : α}
lemma isClique_empty : G.IsClique ∅ := by simp
lemma isClique_singleton (a : α) : G.IsClique {a} := by simp
theorem IsClique.of_subsingleton {G : SimpleGraph α} (hs : s.Subsingleton) : G.IsClique s :=
hs.pairwise G.Adj
lemma isClique_pair : G.IsClique {a, b} ↔ a ≠ b → G.Adj a b := Set.pairwise_pair_of_symmetric G.symm
@[simp]
lemma isClique_insert : G.IsClique (insert a s) ↔ G.IsClique s ∧ ∀ b ∈ s, a ≠ b → G.Adj a b :=
Set.pairwise_insert_of_symmetric G.symm
lemma isClique_insert_of_notMem (ha : a ∉ s) :
G.IsClique (insert a s) ↔ G.IsClique s ∧ ∀ b ∈ s, G.Adj a b :=
Set.pairwise_insert_of_symmetric_of_notMem G.symm ha
@[deprecated (since := "2025-05-23")] alias isClique_insert_of_not_mem := isClique_insert_of_notMem
lemma IsClique.insert (hs : G.IsClique s) (h : ∀ b ∈ s, a ≠ b → G.Adj a b) :
G.IsClique (insert a s) := hs.insert_of_symmetric G.symm h
theorem IsClique.mono (h : G ≤ H) : G.IsClique s → H.IsClique s := Set.Pairwise.mono' h
theorem IsClique.subset (h : t ⊆ s) : G.IsClique s → G.IsClique t := Set.Pairwise.mono h
@[simp]
theorem isClique_bot_iff : (⊥ : SimpleGraph α).IsClique s ↔ (s : Set α).Subsingleton :=
Set.pairwise_bot_iff
alias ⟨IsClique.subsingleton, _⟩ := isClique_bot_iff
protected theorem IsClique.map (h : G.IsClique s) {f : α ↪ β} : (G.map f).IsClique (f '' s) := by
rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ hab
exact ⟨a, b, h ha hb <| ne_of_apply_ne _ hab, rfl, rfl⟩
theorem isClique_map_iff_of_nontrivial {f : α ↪ β} {t : Set β} (ht : t.Nontrivial) :
(G.map f).IsClique t ↔ ∃ (s : Set α), G.IsClique s ∧ f '' s = t := by
refine ⟨fun h ↦ ⟨f ⁻¹' t, ?_, ?_⟩, by rintro ⟨x, hs, rfl⟩; exact hs.map⟩
· rintro x (hx : f x ∈ t) y (hy : f y ∈ t) hne
obtain ⟨u,v, huv, hux, hvy⟩ := h hx hy (by simpa)
rw [EmbeddingLike.apply_eq_iff_eq] at hux hvy
rwa [← hux, ← hvy]
rw [Set.image_preimage_eq_iff]
intro x hxt
obtain ⟨y,hyt, hyne⟩ := ht.exists_ne x
obtain ⟨u,v, -, rfl, rfl⟩ := h hyt hxt hyne
exact Set.mem_range_self _
theorem isClique_map_iff {f : α ↪ β} {t : Set β} :
(G.map f).IsClique t ↔ t.Subsingleton ∨ ∃ (s : Set α), G.IsClique s ∧ f '' s = t := by
obtain (ht | ht) := t.subsingleton_or_nontrivial
· simp [IsClique.of_subsingleton, ht]
simp [isClique_map_iff_of_nontrivial ht, ht.not_subsingleton]
@[simp] theorem isClique_map_image_iff {f : α ↪ β} :
(G.map f).IsClique (f '' s) ↔ G.IsClique s := by
rw [isClique_map_iff, f.injective.subsingleton_image_iff]
obtain (hs | hs) := s.subsingleton_or_nontrivial
· simp [hs, IsClique.of_subsingleton]
simp [or_iff_right hs.not_subsingleton, Set.image_eq_image f.injective]
variable {f : α ↪ β} {t : Finset β}
theorem isClique_map_finset_iff_of_nontrivial (ht : t.Nontrivial) :
(G.map f).IsClique t ↔ ∃ (s : Finset α), G.IsClique s ∧ s.map f = t := by
constructor
· rw [isClique_map_iff_of_nontrivial (by simpa)]
rintro ⟨s, hs, hst⟩
obtain ⟨s, rfl⟩ := Set.Finite.exists_finset_coe <|
(show s.Finite from Set.Finite.of_finite_image (by simp [hst]) f.injective.injOn)
exact ⟨s,hs, Finset.coe_inj.1 (by simpa)⟩
rintro ⟨s, hs, rfl⟩
simpa using hs.map (f := f)
theorem isClique_map_finset_iff :
(G.map f).IsClique t ↔ #t ≤ 1 ∨ ∃ (s : Finset α), G.IsClique s ∧ s.map f = t := by
obtain (ht | ht) := le_or_gt #t 1
· simp only [ht, true_or, iff_true]
exact IsClique.of_subsingleton <| card_le_one.1 ht
rw [isClique_map_finset_iff_of_nontrivial, ← not_lt]
· simp [ht]
exact Finset.one_lt_card_iff_nontrivial.mp ht
protected theorem IsClique.finsetMap {f : α ↪ β} {s : Finset α} (h : G.IsClique s) :
(G.map f).IsClique (s.map f) := by
simpa
/-- If a set of vertices `A` is a clique in subgraph of `G` induced by a superset of `A`,
its embedding is a clique in `G`. -/
theorem IsClique.of_induce {S : Subgraph G} {F : Set α} {A : Set F}
(c : (S.induce F).coe.IsClique A) : G.IsClique (Subtype.val '' A) := by
simp only [Set.Pairwise, Set.mem_image, Subtype.exists, exists_and_right, exists_eq_right]
intro _ ⟨_, ainA⟩ _ ⟨_, binA⟩ anb
exact S.adj_sub (c ainA binA (Subtype.coe_ne_coe.mp anb)).2.2
lemma IsClique.sdiff_of_sup_edge {v w : α} {s : Set α} (hc : (G ⊔ edge v w).IsClique s) :
G.IsClique (s \ {v}) := by
intro _ hx _ hy hxy
have := hc hx.1 hy.1 hxy
simp_all [sup_adj, edge_adj]
lemma isClique_sup_edge_of_ne_sdiff {v w : α} {s : Set α} (h : v ≠ w) (hv : G.IsClique (s \ {v}))
(hw : G.IsClique (s \ {w})) : (G ⊔ edge v w).IsClique s := by
intro x hx y hy hxy
by_cases h' : x ∈ s \ {v} ∧ y ∈ s \ {v} ∨ x ∈ s \ {w} ∧ y ∈ s \ {w}
· obtain (⟨hx, hy⟩ | ⟨hx, hy⟩) := h'
· exact hv.mono le_sup_left hx hy hxy
· exact hw.mono le_sup_left hx hy hxy
· exact Or.inr ⟨by by_cases x = v <;> aesop, hxy⟩
lemma isClique_sup_edge_of_ne_iff {v w : α} {s : Set α} (h : v ≠ w) :
(G ⊔ edge v w).IsClique s ↔ G.IsClique (s \ {v}) ∧ G.IsClique (s \ {w}) :=
⟨fun h' ↦ ⟨h'.sdiff_of_sup_edge, (edge_comm .. ▸ h').sdiff_of_sup_edge⟩,
fun h' ↦ isClique_sup_edge_of_ne_sdiff h h'.1 h'.2⟩
/-- The vertices in a copy of `⊤` are a clique. -/
theorem isClique_range_copy_top (f : Copy (⊤ : SimpleGraph β) G) :
G.IsClique (Set.range f) := by
intro _ ⟨_, h⟩ _ ⟨_, h'⟩ nh
rw [← h, ← Copy.topEmbedding_apply, ← h', ← Copy.topEmbedding_apply] at nh ⊢
rwa [← f.topEmbedding.coe_toEmbedding, (f.topEmbedding.apply_eq_iff_eq _ _).ne,
← top_adj, ← f.topEmbedding.map_adj_iff] at nh
end Clique
/-! ### `n`-cliques -/
section NClique
variable {n : ℕ} {s : Finset α}
/-- An `n`-clique in a graph is a set of `n` vertices which are pairwise connected. -/
structure IsNClique (n : ℕ) (s : Finset α) : Prop where
isClique : G.IsClique s
card_eq : #s = n
theorem isNClique_iff : G.IsNClique n s ↔ G.IsClique s ∧ #s = n :=
⟨fun h ↦ ⟨h.1, h.2⟩, fun h ↦ ⟨h.1, h.2⟩⟩
instance [DecidableEq α] [DecidableRel G.Adj] {n : ℕ} {s : Finset α} :
Decidable (G.IsNClique n s) :=
decidable_of_iff' _ G.isNClique_iff
variable {G H} {a b c : α}
@[simp] lemma isNClique_empty : G.IsNClique n ∅ ↔ n = 0 := by simp [isNClique_iff, eq_comm]
@[simp]
lemma isNClique_singleton : G.IsNClique n {a} ↔ n = 1 := by simp [isNClique_iff, eq_comm]
theorem IsNClique.mono (h : G ≤ H) : G.IsNClique n s → H.IsNClique n s := by
simp_rw [isNClique_iff]
exact And.imp_left (IsClique.mono h)
protected theorem IsNClique.map (h : G.IsNClique n s) {f : α ↪ β} :
(G.map f).IsNClique n (s.map f) :=
⟨by rw [coe_map]; exact h.1.map, (card_map _).trans h.2⟩
theorem isNClique_map_iff (hn : 1 < n) {t : Finset β} {f : α ↪ β} :
(G.map f).IsNClique n t ↔ ∃ s : Finset α, G.IsNClique n s ∧ s.map f = t := by
rw [isNClique_iff, isClique_map_finset_iff, or_and_right,
or_iff_right (by rintro ⟨h', rfl⟩; exact h'.not_gt hn)]
constructor
· rintro ⟨⟨s, hs, rfl⟩, rfl⟩
simp [isNClique_iff, hs]
rintro ⟨s, hs, rfl⟩
simp [hs.card_eq, hs.isClique]
@[simp]
theorem isNClique_bot_iff : (⊥ : SimpleGraph α).IsNClique n s ↔ n ≤ 1 ∧ #s = n := by
rw [isNClique_iff, isClique_bot_iff]
refine and_congr_left ?_
rintro rfl
exact card_le_one.symm
@[simp]
theorem isNClique_zero : G.IsNClique 0 s ↔ s = ∅ := by
simp only [isNClique_iff, Finset.card_eq_zero, and_iff_right_iff_imp]; rintro rfl; simp
@[simp]
theorem isNClique_one : G.IsNClique 1 s ↔ ∃ a, s = {a} := by
simp only [isNClique_iff, card_eq_one, and_iff_right_iff_imp]; rintro ⟨a, rfl⟩; simp
section DecidableEq
variable [DecidableEq α]
protected theorem IsNClique.insert (hs : G.IsNClique n s) (h : ∀ b ∈ s, G.Adj a b) :
G.IsNClique (n + 1) (insert a s) := by
constructor
· push_cast
exact hs.1.insert fun b hb _ => h _ hb
· rw [card_insert_of_notMem fun ha => (h _ ha).ne rfl, hs.2]
lemma IsNClique.erase_of_mem (hs : G.IsNClique n s) (ha : a ∈ s) :
G.IsNClique (n - 1) (s.erase a) where
isClique := hs.isClique.subset <| by simp
card_eq := by rw [card_erase_of_mem ha, hs.2]
protected lemma IsNClique.insert_erase
(hs : G.IsNClique n s) (ha : ∀ w ∈ s \ {b}, G.Adj a w) (hb : b ∈ s) :
G.IsNClique n (insert a (erase s b)) := by
cases n with
| zero => exact False.elim <| notMem_empty _ (isNClique_zero.1 hs ▸ hb)
| succ _ => exact (hs.erase_of_mem hb).insert fun w h ↦ by aesop
theorem is3Clique_triple_iff : G.IsNClique 3 {a, b, c} ↔ G.Adj a b ∧ G.Adj a c ∧ G.Adj b c := by
simp only [isNClique_iff, Set.pairwise_insert_of_symmetric G.symm, coe_insert]
by_cases hab : a = b <;> by_cases hbc : b = c <;> by_cases hac : a = c <;> subst_vars <;>
simp [and_rotate, *]
theorem is3Clique_iff :
G.IsNClique 3 s ↔ ∃ a b c, G.Adj a b ∧ G.Adj a c ∧ G.Adj b c ∧ s = {a, b, c} := by
refine ⟨fun h ↦ ?_, ?_⟩
· obtain ⟨a, b, c, -, -, -, hs⟩ := card_eq_three.1 h.card_eq
refine ⟨a, b, c, ?_⟩
rwa [hs, eq_self_iff_true, and_true, is3Clique_triple_iff.symm, ← hs]
· rintro ⟨a, b, c, hab, hbc, hca, rfl⟩
exact is3Clique_triple_iff.2 ⟨hab, hbc, hca⟩
end DecidableEq
theorem is3Clique_iff_exists_cycle_length_three :
(∃ s : Finset α, G.IsNClique 3 s) ↔ ∃ (u : α) (w : G.Walk u u), w.IsCycle ∧ w.length = 3 := by
classical
simp_rw [is3Clique_iff, isCycle_def]
exact
⟨(fun ⟨_, a, _, _, hab, hac, hbc, _⟩ => ⟨a, cons hab (cons hbc (cons hac.symm nil)), by aesop⟩),
(fun ⟨_, .cons hab (.cons hbc (.cons hca nil)), _, _⟩ => ⟨_, _, _, _, hab, hca.symm, hbc, rfl⟩)⟩
/-- If a set of vertices `A` is an `n`-clique in subgraph of `G` induced by a superset of `A`,
its embedding is an `n`-clique in `G`. -/
theorem IsNClique.of_induce {S : Subgraph G} {F : Set α} {s : Finset { x // x ∈ F }} {n : ℕ}
(cc : (S.induce F).coe.IsNClique n s) :
G.IsNClique n (Finset.map ⟨Subtype.val, Subtype.val_injective⟩ s) := by
rw [isNClique_iff] at cc ⊢
simp only [coe_map, card_map]
exact ⟨cc.left.of_induce, cc.right⟩
lemma IsNClique.erase_of_sup_edge_of_mem [DecidableEq α] {v w : α} {s : Finset α} {n : ℕ}
(hc : (G ⊔ edge v w).IsNClique n s) (hx : v ∈ s) : G.IsNClique (n - 1) (s.erase v) where
isClique := coe_erase v _ ▸ hc.1.sdiff_of_sup_edge
card_eq := by rw [card_erase_of_mem hx, hc.2]
/-- The vertices in a copy of `⊤ : SimpleGraph β` are a `card β`-clique. -/
theorem isNClique_map_copy_top [Fintype β] (f : Copy (⊤ : SimpleGraph β) G) :
G.IsNClique (card β) (univ.map f.toEmbedding) := by
rw [isNClique_iff, card_map, card_univ, coe_map, coe_univ, Set.image_univ]
exact ⟨isClique_range_copy_top f, rfl⟩
end NClique
/-! ### Graphs without cliques -/
section CliqueFree
variable {m n : ℕ}
/-- `G.CliqueFree n` means that `G` has no `n`-cliques. -/
def CliqueFree (n : ℕ) : Prop :=
∀ t, ¬G.IsNClique n t
variable {G H} {s : Finset α}
theorem IsNClique.not_cliqueFree (hG : G.IsNClique n s) : ¬G.CliqueFree n :=
fun h ↦ h _ hG
theorem not_cliqueFree_of_top_embedding {n : ℕ} (f : (⊤ : SimpleGraph (Fin n)) ↪g G) :
¬G.CliqueFree n := by
simp only [CliqueFree, isNClique_iff, isClique_iff_induce_eq, not_forall, Classical.not_not]
use Finset.univ.map f.toEmbedding
simp only [card_map, Finset.card_fin, and_true]
ext ⟨v, hv⟩ ⟨w, hw⟩
simp only [coe_map, Set.mem_image, coe_univ, Set.mem_univ, true_and] at hv hw
obtain ⟨v', rfl⟩ := hv
obtain ⟨w', rfl⟩ := hw
simp_rw [RelEmbedding.coe_toEmbedding, comap_adj, Function.Embedding.coe_subtype, f.map_adj_iff,
top_adj, ne_eq, Subtype.mk.injEq, RelEmbedding.inj]
/-- An embedding of a complete graph that witnesses the fact that the graph is not clique-free. -/
noncomputable def topEmbeddingOfNotCliqueFree {n : ℕ} (h : ¬G.CliqueFree n) :
(⊤ : SimpleGraph (Fin n)) ↪g G := by
simp only [CliqueFree, isNClique_iff, isClique_iff_induce_eq, not_forall, Classical.not_not] at h
obtain ⟨ha, hb⟩ := h.choose_spec
have : (⊤ : SimpleGraph (Fin #h.choose)) ≃g (⊤ : SimpleGraph h.choose) := by
apply Iso.completeGraph
simpa using (Fintype.equivFin h.choose).symm
rw [← ha] at this
convert (Embedding.induce ↑h.choose).comp this.toEmbedding
exact hb.symm
theorem not_cliqueFree_iff (n : ℕ) : ¬G.CliqueFree n ↔ Nonempty (completeGraph (Fin n) ↪g G) :=
⟨fun h ↦ ⟨topEmbeddingOfNotCliqueFree h⟩, fun ⟨f⟩ ↦ not_cliqueFree_of_top_embedding f⟩
theorem cliqueFree_iff {n : ℕ} : G.CliqueFree n ↔ IsEmpty (completeGraph (Fin n) ↪g G) := by
rw [← not_iff_not, not_cliqueFree_iff, not_isEmpty_iff]
/-- A simple graph has no `card β`-cliques iff it does not contain `⊤ : SimpleGraph β`. -/
theorem cliqueFree_iff_top_free {β : Type*} [Fintype β] :
G.CliqueFree (card β) ↔ (⊤ : SimpleGraph β).Free G := by
rw [← not_iff_not, not_free, not_cliqueFree_iff,
isContained_congr (Iso.completeGraph (Fintype.equivFin β)) Iso.refl]
exact ⟨fun ⟨f⟩ ↦ ⟨f.toCopy⟩, fun ⟨f⟩ ↦ ⟨f.topEmbedding⟩⟩
theorem not_cliqueFree_card_of_top_embedding [Fintype α] (f : (⊤ : SimpleGraph α) ↪g G) :
¬G.CliqueFree (card α) := by
rw [not_cliqueFree_iff]
exact ⟨(Iso.completeGraph (Fintype.equivFin α)).symm.toEmbedding.trans f⟩
@[simp] lemma not_cliqueFree_zero : ¬ G.CliqueFree 0 :=
fun h ↦ h ∅ <| isNClique_empty.mpr rfl
@[simp]
theorem cliqueFree_bot (h : 2 ≤ n) : (⊥ : SimpleGraph α).CliqueFree n := by
intro t ht
have := le_trans h (isNClique_bot_iff.1 ht).1
contradiction
theorem CliqueFree.mono (h : m ≤ n) : G.CliqueFree m → G.CliqueFree n := by
intro hG s hs
obtain ⟨t, hts, ht⟩ := exists_subset_card_eq (h.trans hs.card_eq.ge)
exact hG _ ⟨hs.isClique.subset hts, ht⟩
theorem CliqueFree.anti (h : G ≤ H) : H.CliqueFree n → G.CliqueFree n :=
forall_imp fun _ ↦ mt <| IsNClique.mono h
/-- If a graph is cliquefree, any graph that embeds into it is also cliquefree. -/
theorem CliqueFree.comap {H : SimpleGraph β} (f : H ↪g G) : G.CliqueFree n → H.CliqueFree n := by
intro h; contrapose h
exact not_cliqueFree_of_top_embedding <| f.comp (topEmbeddingOfNotCliqueFree h)
@[simp] theorem cliqueFree_map_iff {f : α ↪ β} [Nonempty α] :
(G.map f).CliqueFree n ↔ G.CliqueFree n := by
obtain (hle | hlt) := le_or_gt n 1
· obtain (rfl | rfl) := Nat.le_one_iff_eq_zero_or_eq_one.1 hle
· simp [CliqueFree]
simp [CliqueFree, show ∃ (_ : β), True from ⟨f (Classical.arbitrary _), trivial⟩]
simp [CliqueFree, isNClique_map_iff hlt]
/-- See `SimpleGraph.cliqueFree_of_chromaticNumber_lt` for a tighter bound. -/
theorem cliqueFree_of_card_lt [Fintype α] (hc : card α < n) : G.CliqueFree n := by
rw [cliqueFree_iff]
contrapose! hc
simpa only [Fintype.card_fin] using Fintype.card_le_of_embedding hc.some.toEmbedding
/-- A complete `r`-partite graph has no `n`-cliques for `r < n`. -/
theorem cliqueFree_completeMultipartiteGraph {ι : Type*} [Fintype ι] (V : ι → Type*)
(hc : card ι < n) : (completeMultipartiteGraph V).CliqueFree n := by
rw [cliqueFree_iff, isEmpty_iff]
intro f
obtain ⟨v, w, hn, he⟩ := exists_ne_map_eq_of_card_lt (Sigma.fst ∘ f) (by simp [hc])
rw [← top_adj, ← f.map_adj_iff, comap_adj, top_adj] at hn
exact absurd he hn
namespace completeMultipartiteGraph
variable {ι : Type*} (V : ι → Type*)
/-- Embedding of the complete graph on `ι` into `completeMultipartiteGraph` on `ι` nonempty parts -/
@[simps]
def topEmbedding (f : ∀ (i : ι), V i) :
(⊤ : SimpleGraph ι) ↪g completeMultipartiteGraph V where
toFun := fun i ↦ ⟨i, f i⟩
inj' := fun _ _ h ↦ (Sigma.mk.inj_iff.1 h).1
map_rel_iff' := by simp
theorem not_cliqueFree_of_le_card [Fintype ι] (f : ∀ (i : ι), V i) (hc : n ≤ Fintype.card ι) :
¬ (completeMultipartiteGraph V).CliqueFree n :=
fun hf ↦ (cliqueFree_iff.1 <| hf.mono hc).elim' <|
(topEmbedding V f).comp (Iso.completeGraph (Fintype.equivFin ι).symm).toEmbedding
theorem not_cliqueFree_of_infinite [Infinite ι] (f : ∀ (i : ι), V i) :
¬ (completeMultipartiteGraph V).CliqueFree n :=
fun hf ↦ not_cliqueFree_of_top_embedding (topEmbedding V f |>.comp
<| Embedding.completeGraph <| Fin.valEmbedding.trans <| Infinite.natEmbedding ι) hf
theorem not_cliqueFree_of_le_enatCard (f : ∀ (i : ι), V i) (hc : n ≤ ENat.card ι) :
¬ (completeMultipartiteGraph V).CliqueFree n := by
by_cases h : Infinite ι
· exact not_cliqueFree_of_infinite V f
· have : Fintype ι := fintypeOfNotInfinite h
rw [ENat.card_eq_coe_fintype_card, Nat.cast_le] at hc
exact not_cliqueFree_of_le_card V f hc
end completeMultipartiteGraph
/-- Clique-freeness is preserved by `replaceVertex`. -/
protected theorem CliqueFree.replaceVertex [DecidableEq α] (h : G.CliqueFree n) (s t : α) :
(G.replaceVertex s t).CliqueFree n := by
contrapose h
obtain ⟨φ, hφ⟩ := topEmbeddingOfNotCliqueFree h
rw [not_cliqueFree_iff]
by_cases mt : t ∈ Set.range φ
· obtain ⟨x, hx⟩ := mt
by_cases ms : s ∈ Set.range φ
· obtain ⟨y, hy⟩ := ms
have e := @hφ x y
simp_rw [hx, hy, adj_comm, not_adj_replaceVertex_same, top_adj, false_iff, not_ne_iff] at e
rwa [← hx, e, hy, replaceVertex_self, not_cliqueFree_iff] at h
· unfold replaceVertex at hφ
use φ.setValue x s
intro a b
simp only [Embedding.coeFn_mk, Embedding.setValue, not_exists.mp ms, ite_false]
rw [apply_ite (G.Adj · _), apply_ite (G.Adj _ ·), apply_ite (G.Adj _ ·)]
convert @hφ a b <;> simp only [← φ.apply_eq_iff_eq, SimpleGraph.irrefl, hx]
· use φ
simp_rw [Set.mem_range, not_exists, ← ne_eq] at mt
conv at hφ => enter [a, b]; rw [G.adj_replaceVertex_iff_of_ne _ (mt a) (mt b)]
exact hφ
@[simp]
lemma cliqueFree_one : G.CliqueFree 1 ↔ IsEmpty α := by
simp [CliqueFree, isEmpty_iff]
@[simp]
theorem cliqueFree_two : G.CliqueFree 2 ↔ G = ⊥ := by
classical
constructor
· simp_rw [← edgeSet_eq_empty, Set.eq_empty_iff_forall_notMem, Sym2.forall, mem_edgeSet]
exact fun h a b hab => h _ ⟨by simpa [hab.ne], card_pair hab.ne⟩
· rintro rfl
exact cliqueFree_bot le_rfl
lemma CliqueFree.mem_of_sup_edge_isNClique {x y : α} {t : Finset α} {n : ℕ} (h : G.CliqueFree n)
(hc : (G ⊔ edge x y).IsNClique n t) : x ∈ t := by
by_contra! hf
have ht : (t : Set α) \ {x} = t := sdiff_eq_left.mpr <| Set.disjoint_singleton_right.mpr hf
exact h t ⟨ht ▸ hc.1.sdiff_of_sup_edge, hc.2⟩
open Classical in
/-- Adding an edge increases the clique number by at most one. -/
protected theorem CliqueFree.sup_edge (h : G.CliqueFree n) (v w : α) :
(G ⊔ edge v w).CliqueFree (n + 1) :=
fun _ hs ↦ (hs.erase_of_sup_edge_of_mem <|
(h.mono n.le_succ).mem_of_sup_edge_isNClique hs).not_cliqueFree h
lemma IsNClique.exists_not_adj_of_cliqueFree_succ (hc : G.IsNClique n s)
(h : G.CliqueFree (n + 1)) (x : α) : ∃ y, y ∈ s ∧ ¬ G.Adj x y := by
classical
by_contra! hf
exact (hc.insert hf).not_cliqueFree h
lemma exists_of_maximal_cliqueFree_not_adj [DecidableEq α]
(h : Maximal (fun H ↦ H.CliqueFree (n + 1)) G) {x y : α} (hne : x ≠ y) (hn : ¬ G.Adj x y) :
∃ s, x ∉ s ∧ y ∉ s ∧ G.IsNClique n (insert x s) ∧ G.IsNClique n (insert y s) := by
obtain ⟨t, hc⟩ := not_forall_not.1 <| h.not_prop_of_gt <| G.lt_sup_edge _ _ hne hn
use (t.erase x).erase y, erase_right_comm (a := x) ▸ (notMem_erase _ _), notMem_erase _ _
have h1 := h.1.mem_of_sup_edge_isNClique hc
have h2 := h.1.mem_of_sup_edge_isNClique (edge_comm .. ▸ hc)
rw [insert_erase <| mem_erase_of_ne_of_mem hne.symm h2, erase_right_comm,
insert_erase <| mem_erase_of_ne_of_mem hne h1]
exact ⟨(edge_comm .. ▸ hc).erase_of_sup_edge_of_mem h2, hc.erase_of_sup_edge_of_mem h1⟩
end CliqueFree
section CliqueFreeOn
variable {s s₁ s₂ : Set α} {a : α} {m n : ℕ}
/-- `G.CliqueFreeOn s n` means that `G` has no `n`-cliques contained in `s`. -/
def CliqueFreeOn (G : SimpleGraph α) (s : Set α) (n : ℕ) : Prop :=
∀ ⦃t⦄, ↑t ⊆ s → ¬G.IsNClique n t
theorem CliqueFreeOn.subset (hs : s₁ ⊆ s₂) (h₂ : G.CliqueFreeOn s₂ n) : G.CliqueFreeOn s₁ n :=
fun _t hts => h₂ <| hts.trans hs
theorem CliqueFreeOn.mono (hmn : m ≤ n) (hG : G.CliqueFreeOn s m) : G.CliqueFreeOn s n := by
rintro t hts ht
obtain ⟨u, hut, hu⟩ := exists_subset_card_eq (hmn.trans ht.card_eq.ge)
exact hG ((coe_subset.2 hut).trans hts) ⟨ht.isClique.subset hut, hu⟩
theorem CliqueFreeOn.anti (hGH : G ≤ H) (hH : H.CliqueFreeOn s n) : G.CliqueFreeOn s n :=
fun _t hts ht => hH hts <| ht.mono hGH
@[simp]
theorem cliqueFreeOn_empty : G.CliqueFreeOn ∅ n ↔ n ≠ 0 := by
simp [CliqueFreeOn, Set.subset_empty_iff]
@[simp]
theorem cliqueFreeOn_singleton : G.CliqueFreeOn {a} n ↔ 1 < n := by
obtain _ | _ | n := n <;>
simp [CliqueFreeOn, isNClique_iff, ← subset_singleton_iff', (Nat.succ_ne_zero _).symm]
@[simp]
theorem cliqueFreeOn_univ : G.CliqueFreeOn Set.univ n ↔ G.CliqueFree n := by
simp [CliqueFree, CliqueFreeOn]
protected theorem CliqueFree.cliqueFreeOn (hG : G.CliqueFree n) : G.CliqueFreeOn s n :=
fun _t _ ↦ hG _
theorem cliqueFreeOn_of_card_lt {s : Finset α} (h : #s < n) : G.CliqueFreeOn s n :=
fun _t hts ht => h.not_ge <| ht.2.symm.trans_le <| card_mono hts
-- TODO: Restate using `SimpleGraph.IndepSet` once we have it
@[simp]
theorem cliqueFreeOn_two : G.CliqueFreeOn s 2 ↔ s.Pairwise (G.Adjᶜ) := by
classical
refine ⟨fun h a ha b hb _ hab => h ?_ ⟨by simpa [hab.ne], card_pair hab.ne⟩, ?_⟩
· push_cast
exact Set.insert_subset_iff.2 ⟨ha, Set.singleton_subset_iff.2 hb⟩
simp only [CliqueFreeOn, isNClique_iff, card_eq_two, not_and, not_exists]
rintro h t hst ht a b hab rfl
simp only [coe_insert, coe_singleton, Set.insert_subset_iff, Set.singleton_subset_iff] at hst
refine h hst.1 hst.2 hab (ht ?_ ?_ hab) <;> simp
theorem CliqueFreeOn.of_succ (hs : G.CliqueFreeOn s (n + 1)) (ha : a ∈ s) :
G.CliqueFreeOn (s ∩ G.neighborSet a) n := by
classical
refine fun t hts ht => hs ?_ (ht.insert fun b hb => (hts hb).2)
push_cast
exact Set.insert_subset_iff.2 ⟨ha, hts.trans Set.inter_subset_left⟩
end CliqueFreeOn
/-! ### Set of cliques -/
section CliqueSet
variable {n : ℕ} {s : Finset α}
/-- The `n`-cliques in a graph as a set. -/
def cliqueSet (n : ℕ) : Set (Finset α) :=
{ s | G.IsNClique n s }
variable {G H}
@[simp]
theorem mem_cliqueSet_iff : s ∈ G.cliqueSet n ↔ G.IsNClique n s :=
Iff.rfl
@[simp]
theorem cliqueSet_eq_empty_iff : G.cliqueSet n = ∅ ↔ G.CliqueFree n := by
simp_rw [CliqueFree, Set.eq_empty_iff_forall_notMem, mem_cliqueSet_iff]
protected alias ⟨_, CliqueFree.cliqueSet⟩ := cliqueSet_eq_empty_iff
@[gcongr, mono]
theorem cliqueSet_mono (h : G ≤ H) : G.cliqueSet n ⊆ H.cliqueSet n :=
fun _ ↦ IsNClique.mono h
theorem cliqueSet_mono' (h : G ≤ H) : G.cliqueSet ≤ H.cliqueSet :=
fun _ ↦ cliqueSet_mono h
@[simp]
theorem cliqueSet_zero (G : SimpleGraph α) : G.cliqueSet 0 = {∅} := Set.ext fun s => by simp
@[simp]
theorem cliqueSet_one (G : SimpleGraph α) : G.cliqueSet 1 = Set.range singleton :=
Set.ext fun s => by simp [eq_comm]
@[simp]
theorem cliqueSet_bot (hn : 1 < n) : (⊥ : SimpleGraph α).cliqueSet n = ∅ :=
(cliqueFree_bot hn).cliqueSet
@[simp]
theorem cliqueSet_map (hn : n ≠ 1) (G : SimpleGraph α) (f : α ↪ β) :
(G.map f).cliqueSet n = map f '' G.cliqueSet n := by
ext s
constructor
· rintro ⟨hs, rfl⟩
have hs' : (s.preimage f f.injective.injOn).map f = s := by
classical
rw [map_eq_image, image_preimage, filter_true_of_mem]
rintro a ha
obtain ⟨b, hb, hba⟩ := exists_mem_ne (hn.lt_of_le' <| Finset.card_pos.2 ⟨a, ha⟩) a
obtain ⟨c, _, _, hc, _⟩ := hs ha hb hba.symm
exact ⟨c, hc⟩
refine ⟨s.preimage f f.injective.injOn, ⟨?_, by rw [← card_map f, hs']⟩, hs'⟩
rw [coe_preimage]
exact fun a ha b hb hab => map_adj_apply.1 (hs ha hb <| f.injective.ne hab)
· rintro ⟨s, hs, rfl⟩
exact hs.map
@[simp]
theorem cliqueSet_map_of_equiv (G : SimpleGraph α) (e : α ≃ β) (n : ℕ) :
(G.map e.toEmbedding).cliqueSet n = map e.toEmbedding '' G.cliqueSet n := by
obtain rfl | hn := eq_or_ne n 1
· ext
simp [e.exists_congr_left]
· exact cliqueSet_map hn _ _
end CliqueSet
/-! ### Clique number -/
section CliqueNumber
variable {α : Type*} {G : SimpleGraph α}
/-- The maximum number of vertices in a clique of a graph `G`. -/
noncomputable def cliqueNum (G : SimpleGraph α) : ℕ := sSup {n | ∃ s, G.IsNClique n s}
private lemma fintype_cliqueNum_bddAbove [Fintype α] : BddAbove {n | ∃ s, G.IsNClique n s} := by
use Fintype.card α
rintro y ⟨s, syc⟩
rw [isNClique_iff] at syc
rw [← syc.right]
exact Finset.card_le_card (Finset.subset_univ s)
lemma IsClique.card_le_cliqueNum [Finite α] {t : Finset α} {tc : G.IsClique t} :
#t ≤ G.cliqueNum := by
cases nonempty_fintype α
exact le_csSup G.fintype_cliqueNum_bddAbove (Exists.intro t ⟨tc, rfl⟩)
lemma exists_isNClique_cliqueNum [Finite α] : ∃ s, G.IsNClique G.cliqueNum s := by
cases nonempty_fintype α
exact Nat.sSup_mem ⟨0, by simp⟩ G.fintype_cliqueNum_bddAbove
/-- A maximum clique in a graph `G` is a clique with the largest possible size. -/
structure IsMaximumClique [Fintype α] (G : SimpleGraph α) (s : Finset α) : Prop where
(isClique : G.IsClique s)
(maximum : ∀ t : Finset α, G.IsClique t → #t ≤ #s)
theorem isMaximumClique_iff [Fintype α] {s : Finset α} :
G.IsMaximumClique s ↔ G.IsClique s ∧ ∀ t : Finset α, G.IsClique t → #t ≤ #s :=
⟨fun h ↦ ⟨h.1, h.2⟩, fun h ↦ ⟨h.1, h.2⟩⟩
/-- A maximal clique in a graph `G` is a clique that cannot be extended by adding more vertices. -/
theorem isMaximalClique_iff {s : Set α} :
Maximal G.IsClique s ↔ G.IsClique s ∧ ∀ t : Set α, G.IsClique t → s ⊆ t → t ⊆ s :=
Iff.rfl
lemma IsMaximumClique.isMaximalClique [Fintype α] (s : Finset α) (M : G.IsMaximumClique s) :
Maximal G.IsClique s :=
⟨ M.isClique,
fun t ht hsub => by
by_contra hc
have fint : Fintype t := ofFinite ↑t
have ne : s ≠ t.toFinset := fun a ↦ by subst a; simp_all[Set.coe_toFinset, not_true_eq_false]
have hle : #t.toFinset ≤ #s := M.maximum t.toFinset (by simp [Set.coe_toFinset, ht])
have hlt : #s < #t.toFinset :=
card_lt_card (ssubset_of_ne_of_subset ne (Set.subset_toFinset.mpr hsub))
exact lt_irrefl _ (lt_of_lt_of_le hlt hle) ⟩
lemma maximumClique_card_eq_cliqueNum [Fintype α] (s : Finset α) (sm : G.IsMaximumClique s) :
#s = G.cliqueNum := by
obtain ⟨sc, sm⟩ := sm
obtain ⟨t, tc, tcard⟩ := G.exists_isNClique_cliqueNum
exact eq_of_le_of_not_lt sc.card_le_cliqueNum (by simp [← tcard, sm t tc])
lemma maximumClique_exists [Fintype α] : ∃ (s : Finset α), G.IsMaximumClique s := by
obtain ⟨s, snc⟩ := G.exists_isNClique_cliqueNum
exact ⟨s, ⟨snc.isClique, fun t ht => snc.card_eq.symm ▸ ht.card_le_cliqueNum⟩⟩
end CliqueNumber
/-! ### Finset of cliques -/
section CliqueFinset
variable [Fintype α] [DecidableEq α] [DecidableRel G.Adj] {n : ℕ} {s : Finset α}
/-- The `n`-cliques in a graph as a finset. -/
def cliqueFinset (n : ℕ) : Finset (Finset α) := {s | G.IsNClique n s}
variable {G} in
@[simp]
theorem mem_cliqueFinset_iff : s ∈ G.cliqueFinset n ↔ G.IsNClique n s :=
mem_filter.trans <| and_iff_right <| mem_univ _
@[simp, norm_cast]
theorem coe_cliqueFinset (n : ℕ) : (G.cliqueFinset n : Set (Finset α)) = G.cliqueSet n :=
Set.ext fun _ ↦ mem_cliqueFinset_iff
variable {G}
@[simp]
theorem cliqueFinset_eq_empty_iff : G.cliqueFinset n = ∅ ↔ G.CliqueFree n := by
simp_rw [CliqueFree, eq_empty_iff_forall_notMem, mem_cliqueFinset_iff]
protected alias ⟨_, CliqueFree.cliqueFinset⟩ := cliqueFinset_eq_empty_iff
theorem card_cliqueFinset_le : #(G.cliqueFinset n) ≤ (card α).choose n := by
rw [← card_univ, ← card_powersetCard]
refine card_mono fun s => ?_
simpa [mem_powersetCard_univ] using IsNClique.card_eq
variable [DecidableRel H.Adj]
@[gcongr, mono]
theorem cliqueFinset_mono (h : G ≤ H) : G.cliqueFinset n ⊆ H.cliqueFinset n :=
monotone_filter_right _ fun _ _ ↦ IsNClique.mono h
variable [Fintype β] [DecidableEq β] (G)
@[simp]
theorem cliqueFinset_map (f : α ↪ β) (hn : n ≠ 1) :
(G.map f).cliqueFinset n = (G.cliqueFinset n).map ⟨map f, Finset.map_injective _⟩ :=
coe_injective <| by
simp_rw [coe_cliqueFinset, cliqueSet_map hn, coe_map, coe_cliqueFinset, Embedding.coeFn_mk]
@[simp]
theorem cliqueFinset_map_of_equiv (e : α ≃ β) (n : ℕ) :
(G.map e.toEmbedding).cliqueFinset n =
(G.cliqueFinset n).map ⟨map e.toEmbedding, Finset.map_injective _⟩ :=
coe_injective <| by push_cast; exact cliqueSet_map_of_equiv _ _ _
end CliqueFinset
/-! ### Independent Sets -/
section IndepSet
variable {s : Set α}
/-- An independent set in a graph is a set of vertices that are pairwise not adjacent. -/
abbrev IsIndepSet (s : Set α) : Prop :=
s.Pairwise (fun v w ↦ ¬G.Adj v w)
theorem isIndepSet_iff : G.IsIndepSet s ↔ s.Pairwise (fun v w ↦ ¬G.Adj v w) :=
Iff.rfl
/-- An independent set is a clique in the complement graph and vice versa. -/
@[simp] theorem isClique_compl : Gᶜ.IsClique s ↔ G.IsIndepSet s := by
rw [isIndepSet_iff, isClique_iff]; repeat rw [Set.Pairwise]
simp_all [compl_adj]
/-- An independent set in the complement graph is a clique and vice versa. -/
@[simp] theorem isIndepSet_compl : Gᶜ.IsIndepSet s ↔ G.IsClique s := by
rw [isIndepSet_iff, isClique_iff]; repeat rw [Set.Pairwise]
simp_all [compl_adj]
instance [DecidableEq α] [DecidableRel G.Adj] {s : Finset α} : Decidable (G.IsIndepSet s) :=
decidable_of_iff' _ G.isIndepSet_iff
/-- If `s` is an independent set, its complement meets every edge of `G`. -/
lemma IsIndepSet.nonempty_mem_compl_mem_edge
[Fintype α] [DecidableEq α] {s : Finset α} (indA : G.IsIndepSet s) {e} (he : e ∈ G.edgeSet) :
{ b ∈ sᶜ | b ∈ e }.Nonempty := by
obtain ⟨v, w⟩ := e
by_contra c
rw [IsIndepSet] at indA
rw [mem_edgeSet] at he
rw [not_nonempty_iff_eq_empty, filter_eq_empty_iff] at c
simp_rw [mem_compl, Sym2.mem_iff, not_or] at c
by_cases vins : v ∈ s
· have wins : w ∈ s := by by_contra wnins; exact (c wnins).right rfl
exact (indA vins wins (Adj.ne he)) he
· exact (c vins).left rfl
/-- The neighbors of a vertex `v` form an independent set in a triangle free graph `G`. -/
theorem isIndepSet_neighborSet_of_triangleFree (h : G.CliqueFree 3) (v : α) :
G.IsIndepSet (G.neighborSet v) := by
classical
by_contra nind
rw [IsIndepSet, Set.Pairwise] at nind
push_neg at nind
simp_rw [mem_neighborSet] at nind
obtain ⟨j, avj, k, avk, _, ajk⟩ := nind
exact h {v, j, k} (is3Clique_triple_iff.mpr (by simp [avj, avk, ajk]))
/-- The embedding of an independent set of an induced subgraph of the subgraph `G` is an independent
set in `G` and vice versa. -/
theorem isIndepSet_induce {F : Set α} {s : Set F} :
((⊤ : Subgraph G).induce F).coe.IsIndepSet s ↔ G.IsIndepSet (Subtype.val '' s) := by
simp [Set.Pairwise]
end IndepSet
/-! ### N-Independent sets -/
section NIndepSet
variable {n : ℕ} {s : Finset α}
/-- An `n`-independent set in a graph is a set of `n` vertices which are pairwise nonadjacent. -/
@[mk_iff]
structure IsNIndepSet (n : ℕ) (s : Finset α) : Prop where
isIndepSet : G.IsIndepSet s
card_eq : s.card = n
/-- An `n`-independent set is an `n`-clique in the complement graph and vice versa. -/
@[simp] theorem isNClique_compl : Gᶜ.IsNClique n s ↔ G.IsNIndepSet n s := by
rw [isNIndepSet_iff]
simp [isNClique_iff]
/-- An `n`-independent set in the complement graph is an `n`-clique and vice versa. -/
@[simp] theorem isNIndepSet_compl : Gᶜ.IsNIndepSet n s ↔ G.IsNClique n s := by
rw [isNClique_iff]
simp [isNIndepSet_iff]
instance [DecidableEq α] [DecidableRel G.Adj] {n : ℕ} {s : Finset α} :
Decidable (G.IsNIndepSet n s) :=
decidable_of_iff' _ (G.isNIndepSet_iff n s)
/-- The embedding of an `n`-independent set of an induced subgraph of the subgraph `G` is an
`n`-independent set in `G` and vice versa. -/
theorem isNIndepSet_induce {F : Set α} {s : Finset { x // x ∈ F }} {n : ℕ} :
((⊤ : Subgraph G).induce F).coe.IsNIndepSet n ↑s ↔
G.IsNIndepSet n (Finset.map ⟨Subtype.val, Subtype.val_injective⟩ s) := by
simp [isNIndepSet_iff, (isIndepSet_induce)]
end NIndepSet
/-! ### Graphs without independent sets -/
section IndepSetFree
variable {n : ℕ}
/-- `G.IndepSetFree n` means that `G` has no `n`-independent sets. -/
def IndepSetFree (n : ℕ) : Prop :=
∀ t, ¬G.IsNIndepSet n t
/-- An graph is `n`-independent set free iff its complement is `n`-clique free. -/
@[simp] theorem cliqueFree_compl : Gᶜ.CliqueFree n ↔ G.IndepSetFree n := by
simp [IndepSetFree, CliqueFree]
/-- An graph's complement is `n`-independent set free iff it is `n`-clique free. -/
@[simp] theorem indepSetFree_compl : Gᶜ.IndepSetFree n ↔ G.CliqueFree n := by
simp [IndepSetFree, CliqueFree]
/-- `G.IndepSetFreeOn s n` means that `G` has no `n`-independent sets contained in `s`. -/
def IndepSetFreeOn (G : SimpleGraph α) (s : Set α) (n : ℕ) : Prop :=
∀ ⦃t⦄, ↑t ⊆ s → ¬G.IsNIndepSet n t
end IndepSetFree
/-! ### Set of independent sets -/
section IndepSetSet
variable {n : ℕ} {s : Finset α}
/-- The `n`-independent sets in a graph as a set. -/
def indepSetSet (n : ℕ) : Set (Finset α) :=
{ s | G.IsNIndepSet n s }
variable {G}
@[simp]
theorem mem_indepSetSet_iff : s ∈ G.indepSetSet n ↔ G.IsNIndepSet n s :=
Iff.rfl
end IndepSetSet
/-! ### Independence Number -/
section IndepNumber
variable {α : Type*} {G : SimpleGraph α}
/-- The maximal number of vertices of an independent set in a graph `G`. -/
noncomputable def indepNum (G : SimpleGraph α) : ℕ := sSup {n | ∃ s, G.IsNIndepSet n s}
@[simp] lemma cliqueNum_compl : Gᶜ.cliqueNum = G.indepNum := by
simp [indepNum, cliqueNum]
@[simp] lemma indepNum_compl : Gᶜ.indepNum = G.cliqueNum := by
simp [indepNum, cliqueNum]
theorem IsIndepSet.card_le_indepNum
[Finite α] {t : Finset α} (tc : G.IsIndepSet t) : #t ≤ G.indepNum := by
cases nonempty_fintype α
rw [← isClique_compl] at tc
simp_rw [indepNum, ← isNClique_compl]
exact tc.card_le_cliqueNum
lemma exists_isNIndepSet_indepNum [Finite α] : ∃ s, G.IsNIndepSet G.indepNum s := by
simp_rw [indepNum, ← isNClique_compl]
exact exists_isNClique_cliqueNum
/-- An independent set in a graph `G` such that there is no independent set with more vertices. -/
@[mk_iff]
structure IsMaximumIndepSet [Fintype α] (G : SimpleGraph α) (s : Finset α) : Prop where
isIndepSet : G.IsIndepSet s
maximum : ∀ t : Finset α, G.IsIndepSet t → #t ≤ #s
@[simp] lemma isMaximumClique_compl [Fintype α] (s : Finset α) :
Gᶜ.IsMaximumClique s ↔ G.IsMaximumIndepSet s := by
simp [isMaximumIndepSet_iff, isMaximumClique_iff]
@[simp] lemma isMaximumIndepSet_compl [Fintype α] (s : Finset α) :
Gᶜ.IsMaximumIndepSet s ↔ G.IsMaximumClique s := by
simp [isMaximumIndepSet_iff, isMaximumClique_iff]
/-- An independent set in a graph `G` that cannot be extended by adding more vertices. -/
theorem isMaximalIndepSet_iff {s : Set α} :
Maximal G.IsIndepSet s ↔ G.IsIndepSet s ∧ ∀ t : Set α, G.IsIndepSet t → s ⊆ t → t ⊆ s :=
Iff.rfl
@[simp] lemma isMaximalClique_compl (s : Finset α) :
Maximal Gᶜ.IsClique s ↔ Maximal G.IsIndepSet s := by
simp [isMaximalIndepSet_iff, isMaximalClique_iff]
@[simp] lemma isMaximalIndepSet_compl (s : Finset α) :
Maximal Gᶜ.IsIndepSet s ↔ Maximal G.IsClique s := by
simp [isMaximalIndepSet_iff, isMaximalClique_iff]
lemma IsMaximumIndepSet.isMaximalIndepSet
[Fintype α] (s : Finset α) (M : G.IsMaximumIndepSet s) : Maximal G.IsIndepSet s := by
rw [← isMaximalClique_compl]
rw [← isMaximumClique_compl] at M
exact IsMaximumClique.isMaximalClique s M
theorem maximumIndepSet_card_eq_indepNum
[Fintype α] (t : Finset α) (tmc : G.IsMaximumIndepSet t) : #t = G.indepNum := by
rw [← isMaximumClique_compl] at tmc
simp_rw [indepNum, ← isNClique_compl]
exact Gᶜ.maximumClique_card_eq_cliqueNum t tmc
lemma maximumIndepSet_exists [Fintype α] : ∃ (s : Finset α), G.IsMaximumIndepSet s := by
simp [← isMaximumClique_compl, maximumClique_exists]
end IndepNumber
/-! ### Finset of independent sets -/
section IndepSetFinset
variable [Fintype α] [DecidableEq α] [DecidableRel G.Adj] {n : ℕ} {s : Finset α}
/-- The `n`-independent sets in a graph as a finset. -/
def indepSetFinset (n : ℕ) : Finset (Finset α) := {s | G.IsNIndepSet n s}
variable {G} in
@[simp]
theorem mem_indepSetFinset_iff : s ∈ G.indepSetFinset n ↔ G.IsNIndepSet n s :=
mem_filter.trans <| and_iff_right <| mem_univ _
end IndepSetFinset
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/ConcreteColorings.lean | import Mathlib.Combinatorics.SimpleGraph.Bipartite
import Mathlib.Combinatorics.SimpleGraph.Circulant
import Mathlib.Combinatorics.SimpleGraph.Coloring
import Mathlib.Combinatorics.SimpleGraph.CompleteMultipartite
import Mathlib.Combinatorics.SimpleGraph.Hasse
import Mathlib.Data.Fin.Parity
/-!
# Concrete colorings of common graphs
This file defines colorings for some common graphs.
## Main declarations
* `SimpleGraph.pathGraph.bicoloring`: Bicoloring of a path graph.
-/
assert_not_exists Field
namespace SimpleGraph
theorem chromaticNumber_le_two_iff_isBipartite {V : Type*} {G : SimpleGraph V} :
G.chromaticNumber ≤ 2 ↔ G.IsBipartite :=
chromaticNumber_le_iff_colorable
theorem chromaticNumber_eq_two_iff {V : Type*} {G : SimpleGraph V} :
G.chromaticNumber = 2 ↔ G.IsBipartite ∧ G ≠ ⊥ :=
⟨fun h ↦ ⟨chromaticNumber_le_two_iff_isBipartite.mp (by simp [h]),
two_le_chromaticNumber_iff_ne_bot.mp (by simp [h])⟩,
fun ⟨h₁, h₂⟩ ↦ ENat.eq_of_forall_natCast_le_iff fun _ ↦
⟨fun h ↦ h.trans <| chromaticNumber_le_two_iff_isBipartite.mpr h₁,
fun h ↦ h.trans <| two_le_chromaticNumber_iff_ne_bot.mpr h₂⟩⟩
/-- Bicoloring of a path graph -/
def pathGraph.bicoloring (n : ℕ) :
Coloring (pathGraph n) Bool :=
Coloring.mk (fun u ↦ u.val % 2 = 0) <| by
intro u v
rw [pathGraph_adj]
rintro (h | h) <;> simp [← h, not_iff, Nat.succ_mod_two_eq_zero_iff]
/-- Embedding of `pathGraph 2` into the first two elements of `pathGraph n` for `2 ≤ n` -/
def pathGraph_two_embedding (n : ℕ) (h : 2 ≤ n) : pathGraph 2 ↪g pathGraph n where
toFun v := ⟨v, trans v.2 h⟩
inj' := by
rintro v w
rw [Fin.mk.injEq]
exact Fin.ext
map_rel_iff' := by
intro v w
fin_cases v <;> fin_cases w <;> simp [pathGraph, ← Fin.coe_covBy_iff]
theorem chromaticNumber_pathGraph (n : ℕ) (h : 2 ≤ n) :
(pathGraph n).chromaticNumber = 2 := by
have hc := (pathGraph.bicoloring n).colorable
apply le_antisymm
· exact hc.chromaticNumber_le
· have hadj : (pathGraph n).Adj ⟨0, Nat.zero_lt_of_lt h⟩ ⟨1, h⟩ := by simp [pathGraph_adj]
exact two_le_chromaticNumber_of_adj hadj
theorem Coloring.even_length_iff_congr {α} {G : SimpleGraph α}
(c : G.Coloring Bool) {u v : α} (p : G.Walk u v) :
Even p.length ↔ (c u ↔ c v) := by
induction p with
| nil => simp
| @cons u v w h p ih =>
simp only [Walk.length_cons, Nat.even_add_one]
have : ¬ c u = true ↔ c v = true := by
rw [← not_iff, ← Bool.eq_iff_iff]
exact c.valid h
tauto
theorem Coloring.odd_length_iff_not_congr {α} {G : SimpleGraph α}
(c : G.Coloring Bool) {u v : α} (p : G.Walk u v) :
Odd p.length ↔ (¬c u ↔ c v) := by
rw [← Nat.not_even_iff_odd, c.even_length_iff_congr p]
tauto
theorem Walk.three_le_chromaticNumber_of_odd_loop {α} {G : SimpleGraph α} {u : α} (p : G.Walk u u)
(hOdd : Odd p.length) : 3 ≤ G.chromaticNumber := Classical.by_contradiction <| by
intro h
have h' : G.chromaticNumber ≤ 2 := Order.le_of_lt_add_one <| not_le.mp h
let c : G.Coloring (Fin 2) := (chromaticNumber_le_iff_colorable.mp h').some
let c' : G.Coloring Bool := recolorOfEquiv G finTwoEquiv c
have : ¬c' u ↔ c' u := (c'.odd_length_iff_not_congr p).mp hOdd
simp_all
/-- Bicoloring of a cycle graph of even size -/
def cycleGraph.bicoloring_of_even (n : ℕ) (h : Even n) : Coloring (cycleGraph n) Bool :=
Coloring.mk (fun u ↦ u.val % 2 = 0) <| by
intro u v hadj
match n with
| 0 => exact u.elim0
| 1 => simp at h
| n + 2 =>
simp only [ne_eq, decide_eq_decide]
simp only [cycleGraph_adj] at hadj
cases hadj with
| inl huv | inr huv =>
rw [← add_eq_of_eq_sub' huv.symm, ← Fin.even_iff_mod_of_even h,
← Fin.even_iff_mod_of_even h, Fin.even_add_one_iff_odd]
apply Classical.not_iff.mpr
simp [Fin.not_odd_iff_even_of_even h, Fin.not_even_iff_odd_of_even h]
theorem chromaticNumber_cycleGraph_of_even (n : ℕ) (h : 2 ≤ n) (hEven : Even n) :
(cycleGraph n).chromaticNumber = 2 := by
have hc := (cycleGraph.bicoloring_of_even n hEven).colorable
apply le_antisymm
· apply hc.chromaticNumber_le
· have hadj : (cycleGraph n).Adj ⟨0, Nat.zero_lt_of_lt h⟩ ⟨1, h⟩ := by
simp [cycleGraph_adj', Fin.sub_val_of_le]
exact two_le_chromaticNumber_of_adj hadj
/-- Tricoloring of a cycle graph -/
def cycleGraph.tricoloring (n : ℕ) (h : 2 ≤ n) : Coloring (cycleGraph n)
(Fin 3) := Coloring.mk (fun u ↦ if u.val = n - 1 then 2 else ⟨u.val % 2, by fin_omega⟩) <| by
intro u v hadj
match n with
| 0 => exact u.elim0
| 1 => simp at h
| n + 2 =>
simp only
simp only [cycleGraph_adj] at hadj
split_ifs with hu hv
· simp [Fin.eq_mk_iff_val_eq.mpr hu, Fin.eq_mk_iff_val_eq.mpr hv] at hadj
· refine (Fin.ne_of_lt (Fin.mk_lt_of_lt_val (?_))).symm
exact v.val.mod_lt Nat.zero_lt_two
· refine (Fin.ne_of_lt (Fin.mk_lt_of_lt_val ?_))
exact u.val.mod_lt Nat.zero_lt_two
· simp only [ne_eq, Fin.ext_iff]
have hu' : u.val + (1 : Fin (n + 2)) < n + 2 := by fin_omega
have hv' : v.val + (1 : Fin (n + 2)) < n + 2 := by fin_omega
cases hadj with
| inl huv | inr huv =>
rw [← add_eq_of_eq_sub' huv.symm]
simp only [Fin.val_add_eq_of_add_lt hv', Fin.val_add_eq_of_add_lt hu', Fin.val_one]
rw [show ∀ x y : ℕ, x % 2 = y % 2 ↔ (Even x ↔ Even y) by simp [Nat.even_iff]; cutsat,
Nat.even_add]
simp only [Nat.not_even_one, iff_false, not_iff_self, iff_not_self]
exact id
theorem chromaticNumber_cycleGraph_of_odd (n : ℕ) (h : 2 ≤ n) (hOdd : Odd n) :
(cycleGraph n).chromaticNumber = 3 := by
have hc := (cycleGraph.tricoloring n h).colorable
apply le_antisymm
· apply hc.chromaticNumber_le
· have hn3 : n - 3 + 3 = n := by
refine Nat.sub_add_cancel (Nat.succ_le_of_lt (Nat.lt_of_le_of_ne h ?_))
intro h2
rw [← h2] at hOdd
exact (Nat.not_odd_iff.mpr rfl) hOdd
let w : (cycleGraph (n - 3 + 3)).Walk 0 0 := cycleGraph_EulerianCircuit (n - 3)
have hOdd' : Odd w.length := by
rw [cycleGraph_EulerianCircuit_length, hn3]
exact hOdd
rw [← hn3]
exact Walk.three_le_chromaticNumber_of_odd_loop w hOdd'
section CompleteEquipartiteGraph
variable {r t : ℕ}
/-- The injection `(x₁, x₂) ↦ x₁` is always a `r`-coloring of a `completeEquipartiteGraph r ·`. -/
def Coloring.completeEquipartiteGraph :
(completeEquipartiteGraph r t).Coloring (Fin r) := ⟨Prod.fst, id⟩
/-- The `completeEquipartiteGraph r t` is always `r`-colorable. -/
theorem completeEquipartiteGraph_colorable :
(completeEquipartiteGraph r t).Colorable r := ⟨Coloring.completeEquipartiteGraph⟩
end CompleteEquipartiteGraph
open Walk
lemma two_colorable_iff_forall_loop_even {α : Type*} {G : SimpleGraph α} :
G.Colorable 2 ↔ ∀ u, ∀ (w : G.Walk u u), Even w.length := by
simp_rw [← Nat.not_odd_iff_even]
constructor <;> intro h
· intro _ w ho
have := (w.three_le_chromaticNumber_of_odd_loop ho).trans h.chromaticNumber_le
norm_cast
· apply colorable_iff_forall_connectedComponents.2
intro c
obtain ⟨_, hv⟩ := c.nonempty_supp
use fun a ↦ Fin.ofNat 2 (c.connected_toSimpleGraph ⟨_, hv⟩ a).some.length
intro a b hab he
apply h _ <| (((c.connected_toSimpleGraph ⟨_, hv⟩ a).some.concat hab).append
(c.connected_toSimpleGraph ⟨_, hv⟩ b).some.reverse).map c.toSimpleGraph_hom
rw [length_map, length_append, length_concat, length_reverse, add_right_comm]
have : ((Nonempty.some (c.connected_toSimpleGraph ⟨_, hv⟩ a)).length) % 2 =
(Nonempty.some (c.connected_toSimpleGraph ⟨_, hv⟩ b)).length % 2 := by
simp_rw [← Fin.val_natCast, ← Fin.ofNat_eq_cast, he]
exact (Nat.even_iff.mpr (by cutsat)).add_one
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Connectivity/WalkDecomp.lean | import Mathlib.Combinatorics.SimpleGraph.Walk
/-!
# Decomposing walks
## Main definitions
- `takeUntil`: The path obtained by taking edges of an existing path until a given vertex.
- `dropUntil`: The path obtained by dropping edges of an existing path until a given vertex.
- `rotate`: Rotate a loop walk such that it is centered at the given vertex.
-/
namespace SimpleGraph.Walk
universe u
variable {V : Type u} {G : SimpleGraph V} {v w u : V}
/-! ### Walk decompositions -/
section WalkDecomp
variable [DecidableEq V]
/-- Given a vertex in the support of a path, give the path up until (and including) that vertex. -/
def takeUntil {v w : V} : ∀ (p : G.Walk v w) (u : V), u ∈ p.support → G.Walk v u
| nil, u, h => by rw [mem_support_nil_iff.mp h]
| cons r p, u, h =>
if hx : v = u then
hx ▸ Walk.nil
else
cons r (takeUntil p u <| by
cases h
· exact (hx rfl).elim
· assumption)
@[simp] theorem takeUntil_nil {u : V} {h} : takeUntil (nil : G.Walk u u) u h = nil := rfl
lemma takeUntil_cons {v' : V} {p : G.Walk v' v} (hwp : w ∈ p.support) (h : u ≠ w)
(hadj : G.Adj u v') :
(p.cons hadj).takeUntil w (List.mem_of_mem_tail hwp) = (p.takeUntil w hwp).cons hadj := by
simp [Walk.takeUntil, h]
@[simp]
lemma takeUntil_first (p : G.Walk u v) :
p.takeUntil u p.start_mem_support = .nil := by cases p <;> simp [Walk.takeUntil]
@[simp]
lemma nil_takeUntil (p : G.Walk u v) (hwp : w ∈ p.support) :
(p.takeUntil w hwp).Nil ↔ u = w := by
refine ⟨?_, fun h => by subst h; simp⟩
intro hnil
cases p with
| nil => simp only [takeUntil, eq_mpr_eq_cast] at hnil; exact hnil.eq
| cons h q =>
simp only [support_cons, List.mem_cons] at hwp
obtain hl | hr := hwp
· exact hl.symm
· by_contra! hc
simp [takeUntil_cons hr hc] at hnil
/-- Given a vertex in the support of a path, give the path from (and including) that vertex to
the end. In other words, drop vertices from the front of a path until (and not including)
that vertex. -/
def dropUntil {v w : V} : ∀ (p : G.Walk v w) (u : V), u ∈ p.support → G.Walk u w
| nil, u, h => by rw [mem_support_nil_iff.mp h]
| cons r p, u, h =>
if hx : v = u then by
subst u
exact cons r p
else dropUntil p u <| by
cases h
· exact (hx rfl).elim
· assumption
/-- The `takeUntil` and `dropUntil` functions split a walk into two pieces.
The lemma `SimpleGraph.Walk.count_support_takeUntil_eq_one` specifies where this split occurs. -/
@[simp]
theorem take_spec {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.takeUntil u h).append (p.dropUntil u h) = p := by
induction p
· rw [mem_support_nil_iff] at h
subst u
rfl
· cases h
· simp!
· simp! only
split_ifs with h' <;> subst_vars <;> simp [*]
theorem mem_support_iff_exists_append {V : Type u} {G : SimpleGraph V} {u v w : V}
{p : G.Walk u v} : w ∈ p.support ↔ ∃ (q : G.Walk u w) (r : G.Walk w v), p = q.append r := by
classical
constructor
· exact fun h => ⟨_, _, (p.take_spec h).symm⟩
· rintro ⟨q, r, rfl⟩
simp only [mem_support_append_iff, end_mem_support, start_mem_support, or_self_iff]
@[simp]
theorem count_support_takeUntil_eq_one {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.takeUntil u h).support.count u = 1 := by
induction p
· rw [mem_support_nil_iff] at h
subst u
simp
· cases h
· simp
· simp! only
split_ifs with h' <;> rw [eq_comm] at h' <;> subst_vars <;> simp! [*, List.count_cons]
theorem count_edges_takeUntil_le_one {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) (x : V) :
(p.takeUntil u h).edges.count s(u, x) ≤ 1 := by
induction p with
| nil =>
rw [mem_support_nil_iff] at h
subst u
simp
| cons ha p' ih =>
cases h
· simp
· simp! only
split_ifs with h'
· subst h'
simp
· rw [edges_cons, List.count_cons]
split_ifs with h''
· simp only [beq_iff_eq, Sym2.eq, Sym2.rel_iff'] at h''
obtain ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ := h''
· exact (h' rfl).elim
· cases p' <;> simp!
· apply ih
@[simp]
theorem takeUntil_copy {u v w v' w'} (p : G.Walk v w) (hv : v = v') (hw : w = w')
(h : u ∈ (p.copy hv hw).support) :
(p.copy hv hw).takeUntil u h = (p.takeUntil u (by subst_vars; exact h)).copy hv rfl := by
subst_vars
rfl
@[simp]
theorem dropUntil_copy {u v w v' w'} (p : G.Walk v w) (hv : v = v') (hw : w = w')
(h : u ∈ (p.copy hv hw).support) :
(p.copy hv hw).dropUntil u h = (p.dropUntil u (by subst_vars; exact h)).copy rfl hw := by
subst_vars
rfl
theorem support_takeUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.takeUntil u h).support ⊆ p.support := fun x hx => by
rw [← take_spec p h, mem_support_append_iff]
exact Or.inl hx
theorem support_dropUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.dropUntil u h).support ⊆ p.support := fun x hx => by
rw [← take_spec p h, mem_support_append_iff]
exact Or.inr hx
theorem darts_takeUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.takeUntil u h).darts ⊆ p.darts := fun x hx => by
rw [← take_spec p h, darts_append, List.mem_append]
exact Or.inl hx
theorem darts_dropUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.dropUntil u h).darts ⊆ p.darts := fun x hx => by
rw [← take_spec p h, darts_append, List.mem_append]
exact Or.inr hx
theorem edges_takeUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.takeUntil u h).edges ⊆ p.edges :=
List.map_subset _ (p.darts_takeUntil_subset h)
theorem edges_dropUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.dropUntil u h).edges ⊆ p.edges :=
List.map_subset _ (p.darts_dropUntil_subset h)
theorem length_takeUntil_le {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.takeUntil u h).length ≤ p.length := by
have := congr_arg Walk.length (p.take_spec h)
rw [length_append] at this
exact Nat.le.intro this
theorem length_dropUntil_le {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) :
(p.dropUntil u h).length ≤ p.length := by
have := congr_arg Walk.length (p.take_spec h)
rw [length_append, add_comm] at this
exact Nat.le.intro this
lemma takeUntil_append_of_mem_left {x : V} (p : G.Walk u v) (q : G.Walk v w) (hx : x ∈ p.support) :
(p.append q).takeUntil x (subset_support_append_left _ _ hx) = p.takeUntil _ hx := by
induction p with
| nil => rw [mem_support_nil_iff] at hx; subst_vars; simp
| @cons u _ _ _ _ ih =>
rw [support_cons] at hx
by_cases hxu : u = x
· subst_vars; simp
· have := List.mem_of_ne_of_mem (fun hf ↦ hxu hf.symm) hx
simp_rw [takeUntil_cons this hxu, cons_append,
takeUntil_cons (subset_support_append_left _ _ this) hxu]
simpa using ih _ this
lemma getVert_takeUntil {u v : V} {n : ℕ} {p : G.Walk u v} (hw : w ∈ p.support)
(hn : n ≤ (p.takeUntil w hw).length) : (p.takeUntil w hw).getVert n = p.getVert n := by
conv_rhs => rw [← take_spec p hw, getVert_append]
cases hn.lt_or_eq <;> simp_all
lemma snd_takeUntil (hsu : w ≠ u) (p : G.Walk u v) (h : w ∈ p.support) :
(p.takeUntil w h).snd = p.snd := by
apply p.getVert_takeUntil h
by_contra! hc
simp only [Nat.lt_one_iff, ← nil_iff_length_eq, nil_takeUntil] at hc
exact hsu hc.symm
lemma getVert_length_takeUntil {p : G.Walk v w} (h : u ∈ p.support) :
p.getVert (p.takeUntil _ h).length = u := by
have := congr_arg₂ (y := (p.takeUntil _ h).length) getVert (p.take_spec h) rfl
grind [getVert_append, getVert_zero]
lemma getVert_lt_length_takeUntil_ne {n : ℕ} {p : G.Walk v w} (h : u ∈ p.support)
(hn : n < (p.takeUntil _ h).length) : p.getVert n ≠ u := by
rintro rfl
have h₁ : n < (p.takeUntil _ h).support.dropLast.length := by simpa
have : p.getVert n ∈ (p.takeUntil _ h).support.dropLast := by
simp_rw [p.getVert_takeUntil h hn.le ▸ getVert_eq_support_getElem _ hn.le,
← List.getElem_dropLast h₁, List.getElem_mem h₁]
have := support_eq_concat _ ▸ p.count_support_takeUntil_eq_one h
grind [List.not_mem_of_count_eq_zero]
theorem getVert_le_length_takeUntil_eq_iff {n : ℕ} {p : G.Walk v w} (h : u ∈ p.support)
(hn : n ≤ (p.takeUntil _ h).length) : p.getVert n = u ↔ n = (p.takeUntil _ h).length := by
grind [getVert_length_takeUntil, getVert_lt_length_takeUntil_ne]
lemma length_takeUntil_lt {u v w : V} {p : G.Walk v w} (h : u ∈ p.support) (huw : u ≠ w) :
(p.takeUntil u h).length < p.length := by
rw [(p.length_takeUntil_le h).lt_iff_ne]
exact fun hl ↦ huw (by simpa using (hl ▸ getVert_takeUntil h (by rfl) :
(p.takeUntil u h).getVert (p.takeUntil u h).length = p.getVert p.length))
lemma takeUntil_takeUntil {w x : V} (p : G.Walk u v) (hw : w ∈ p.support)
(hx : x ∈ (p.takeUntil w hw).support) :
(p.takeUntil w hw).takeUntil x hx = p.takeUntil x (p.support_takeUntil_subset hw hx) := by
simp_rw [← takeUntil_append_of_mem_left _ (p.dropUntil w hw) hx, take_spec]
lemma notMem_support_takeUntil_support_takeUntil_subset {p : G.Walk u v} {w x : V} (h : x ≠ w)
(hw : w ∈ p.support) (hx : x ∈ (p.takeUntil w hw).support) :
w ∉ (p.takeUntil x (p.support_takeUntil_subset hw hx)).support := by
rw [← takeUntil_takeUntil p hw hx]
intro hw'
have h1 : (((p.takeUntil w hw).takeUntil x hx).takeUntil w hw').length
< ((p.takeUntil w hw).takeUntil x hx).length := by
exact length_takeUntil_lt _ h.symm
have h2 : ((p.takeUntil w hw).takeUntil x hx).length < (p.takeUntil w hw).length := by
exact length_takeUntil_lt _ h
simp only [takeUntil_takeUntil] at h1 h2
cutsat
@[deprecated (since := "2025-05-23")]
alias not_mem_support_takeUntil_support_takeUntil_subset :=
notMem_support_takeUntil_support_takeUntil_subset
/-- Rotate a loop walk such that it is centered at the given vertex. -/
def rotate {u v : V} (c : G.Walk v v) (h : u ∈ c.support) : G.Walk u u :=
(c.dropUntil u h).append (c.takeUntil u h)
@[simp]
theorem support_rotate {u v : V} (c : G.Walk v v) (h : u ∈ c.support) :
(c.rotate h).support.tail ~r c.support.tail := by
simp only [rotate, tail_support_append]
apply List.IsRotated.trans List.isRotated_append
rw [← tail_support_append, take_spec]
theorem rotate_darts {u v : V} (c : G.Walk v v) (h : u ∈ c.support) :
(c.rotate h).darts ~r c.darts := by
simp only [rotate, darts_append]
apply List.IsRotated.trans List.isRotated_append
rw [← darts_append, take_spec]
theorem rotate_edges {u v : V} (c : G.Walk v v) (h : u ∈ c.support) :
(c.rotate h).edges ~r c.edges :=
(rotate_darts c h).map _
end WalkDecomp
/-- Given a walk `p` and a node in the support, there exists a natural `n`, such that given node
is the `n`-th node (zero-indexed) in the walk. In addition, `n` is at most the length of the walk.
Due to the definition of `getVert` it would otherwise be legal to return a larger `n` for the last
node. -/
theorem mem_support_iff_exists_getVert {u v w : V} {p : G.Walk v w} :
u ∈ p.support ↔ ∃ n, p.getVert n = u ∧ n ≤ p.length := by
classical
exact Iff.intro
(fun h ↦ ⟨_, p.getVert_length_takeUntil h, p.length_takeUntil_le h⟩)
(fun ⟨_, h, _⟩ ↦ h ▸ getVert_mem_support _ _)
end SimpleGraph.Walk |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Connectivity/WalkCounting.lean | import Mathlib.Algebra.BigOperators.Ring.Nat
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected
import Mathlib.Data.Set.Card
import Mathlib.Data.Set.Finite.Lattice
/-!
# Counting walks of a given length
## Main definitions
- `walkLengthTwoEquivCommonNeighbors`: bijective correspondence between walks of length two
from `u` to `v` and common neighbours of `u` and `v`. Note that `u` and `v` may be the same.
- `finsetWalkLength`: the `Finset` of length-`n` walks from `u` to `v`.
This is used to give `{p : G.walk u v | p.length = n}` a `Fintype` instance, and it
can also be useful as a recursive description of this set when `V` is finite.
TODO: should this be extended further?
-/
assert_not_exists Field
open Finset Function
universe u v w
namespace SimpleGraph
variable {V : Type u} (G : SimpleGraph V)
/-! ### Walks of a given length -/
section WalkCounting
theorem set_walk_self_length_zero_eq (u : V) : {p : G.Walk u u | p.length = 0} = {Walk.nil} := by
simp
theorem set_walk_length_zero_eq_of_ne {u v : V} (h : u ≠ v) :
{p : G.Walk u v | p.length = 0} = ∅ := by
ext p
simp only [Set.mem_setOf_eq, Set.mem_empty_iff_false, iff_false]
exact fun h' => absurd (Walk.eq_of_length_eq_zero h') h
theorem set_walk_length_succ_eq (u v : V) (n : ℕ) :
{p : G.Walk u v | p.length = n.succ} =
⋃ (w : V) (h : G.Adj u w), Walk.cons h '' {p' : G.Walk w v | p'.length = n} := by
ext p
cases p with
| nil => simp [eq_comm]
| cons huw pwv =>
simp only [Nat.succ_eq_add_one, Set.mem_setOf_eq, Walk.length_cons, add_left_inj,
Set.mem_iUnion, Set.mem_image]
grind
/-- Walks of length two from `u` to `v` correspond bijectively to common neighbours of `u` and `v`.
Note that `u` and `v` may be the same. -/
@[simps]
def walkLengthTwoEquivCommonNeighbors (u v : V) :
{p : G.Walk u v // p.length = 2} ≃ G.commonNeighbors u v where
toFun p := ⟨p.val.snd, match p with
| ⟨.cons _ (.cons _ .nil), _⟩ => ⟨‹G.Adj u _›, ‹G.Adj _ v›.symm⟩⟩
invFun w := ⟨w.prop.1.toWalk.concat w.prop.2.symm, rfl⟩
left_inv | ⟨.cons _ (.cons _ .nil), hp⟩ => by rfl
section LocallyFinite
variable [DecidableEq V] [LocallyFinite G]
/-- The `Finset` of length-`n` walks from `u` to `v`.
This is used to give `{p : G.walk u v | p.length = n}` a `Fintype` instance, and it
can also be useful as a recursive description of this set when `V` is finite.
See `SimpleGraph.coe_finsetWalkLength_eq` for the relationship between this `Finset` and
the set of length-`n` walks. -/
def finsetWalkLength (n : ℕ) (u v : V) : Finset (G.Walk u v) :=
match n with
| 0 =>
if h : u = v then by
subst u
exact {Walk.nil}
else ∅
| n + 1 =>
Finset.univ.biUnion fun (w : G.neighborSet u) =>
(finsetWalkLength n w v).map ⟨fun p => Walk.cons w.property p, fun _ _ => by simp⟩
theorem coe_finsetWalkLength_eq (n : ℕ) (u v : V) :
(G.finsetWalkLength n u v : Set (G.Walk u v)) = {p : G.Walk u v | p.length = n} := by
induction n generalizing u v with
| zero =>
obtain rfl | huv := eq_or_ne u v <;> simp [finsetWalkLength, set_walk_length_zero_eq_of_ne, *]
| succ n ih =>
simp only [finsetWalkLength, set_walk_length_succ_eq, Finset.coe_biUnion, Finset.mem_coe,
Finset.mem_univ, Set.iUnion_true]
ext p
simp only [mem_neighborSet, Finset.coe_map, Embedding.coeFn_mk, Set.iUnion_coe_set,
Set.mem_iUnion, Set.mem_image, Finset.mem_coe, Set.mem_setOf_eq]
congr!
rename_i w _ q
have := Set.ext_iff.mp (ih w v) q
simp only [Finset.mem_coe, Set.mem_setOf_eq] at this
rw [← this]
variable {G} in
theorem mem_finsetWalkLength_iff {n : ℕ} {u v : V} {p : G.Walk u v} :
p ∈ G.finsetWalkLength n u v ↔ p.length = n :=
Set.ext_iff.mp (G.coe_finsetWalkLength_eq n u v) p
/-- The `Finset` of walks from `u` to `v` with length less than `n`. See `finsetWalkLength` for
context. In particular, we use this definition for `SimpleGraph.Path.instFintype`. -/
def finsetWalkLengthLT (n : ℕ) (u v : V) : Finset (G.Walk u v) :=
(Finset.range n).disjiUnion
(fun l ↦ G.finsetWalkLength l u v)
(fun l _ l' _ hne _ hsl hsl' p hp ↦
have hl : p.length = l := mem_finsetWalkLength_iff.mp (hsl hp)
have hl' : p.length = l' := mem_finsetWalkLength_iff.mp (hsl' hp)
False.elim <| hne <| hl.symm.trans hl')
open Finset in
theorem coe_finsetWalkLengthLT_eq (n : ℕ) (u v : V) :
(G.finsetWalkLengthLT n u v : Set (G.Walk u v)) = {p : G.Walk u v | p.length < n} := by
ext p
simp [finsetWalkLengthLT, mem_finsetWalkLength_iff]
variable {G} in
theorem mem_finsetWalkLengthLT_iff {n : ℕ} {u v : V} {p : G.Walk u v} :
p ∈ G.finsetWalkLengthLT n u v ↔ p.length < n :=
Set.ext_iff.mp (G.coe_finsetWalkLengthLT_eq n u v) p
instance fintypeSetWalkLength (u v : V) (n : ℕ) : Fintype {p : G.Walk u v | p.length = n} :=
Fintype.ofFinset (G.finsetWalkLength n u v) fun p => by
rw [← Finset.mem_coe, coe_finsetWalkLength_eq]
instance fintypeSubtypeWalkLength (u v : V) (n : ℕ) : Fintype {p : G.Walk u v // p.length = n} :=
fintypeSetWalkLength G u v n
theorem set_walk_length_toFinset_eq (n : ℕ) (u v : V) :
{p : G.Walk u v | p.length = n}.toFinset = G.finsetWalkLength n u v := by
simp [← coe_finsetWalkLength_eq]
/- See `SimpleGraph.adjMatrix_pow_apply_eq_card_walk` for the cardinality in terms of the `n`th
power of the adjacency matrix. -/
theorem card_set_walk_length_eq (u v : V) (n : ℕ) :
Fintype.card {p : G.Walk u v | p.length = n} = #(G.finsetWalkLength n u v) :=
Fintype.card_ofFinset (G.finsetWalkLength n u v) fun p => by
rw [← Finset.mem_coe, coe_finsetWalkLength_eq]
instance fintypeSetWalkLengthLT (u v : V) (n : ℕ) : Fintype {p : G.Walk u v | p.length < n} :=
Fintype.ofFinset (G.finsetWalkLengthLT n u v) fun p ↦ by
rw [← Finset.mem_coe, coe_finsetWalkLengthLT_eq]
instance fintypeSubtypeWalkLengthLT (u v : V) (n : ℕ) : Fintype {p : G.Walk u v // p.length < n} :=
fintypeSetWalkLengthLT G u v n
instance fintypeSetPathLength (u v : V) (n : ℕ) :
Fintype {p : G.Walk u v | p.IsPath ∧ p.length = n} :=
Fintype.ofFinset {w ∈ G.finsetWalkLength n u v | w.IsPath} <| by
simp [mem_finsetWalkLength_iff, and_comm]
instance fintypeSubtypePathLength (u v : V) (n : ℕ) :
Fintype {p : G.Walk u v // p.IsPath ∧ p.length = n} :=
fintypeSetPathLength G u v n
instance fintypeSetPathLengthLT (u v : V) (n : ℕ) :
Fintype {p : G.Walk u v | p.IsPath ∧ p.length < n} :=
Fintype.ofFinset {w ∈ G.finsetWalkLengthLT n u v | w.IsPath} <| by
simp [mem_finsetWalkLengthLT_iff, and_comm]
instance fintypeSubtypePathLengthLT (u v : V) (n : ℕ) :
Fintype {p : G.Walk u v // p.IsPath ∧ p.length < n} :=
fintypeSetPathLengthLT G u v n
end LocallyFinite
instance [Finite V] : Finite G.ConnectedComponent := Quot.finite _
theorem ConnectedComponent.card_le_card_of_le [Finite V] {G G' : SimpleGraph V} (h : G ≤ G') :
Nat.card G'.ConnectedComponent ≤ Nat.card G.ConnectedComponent :=
Nat.card_le_card_of_surjective _ <| ConnectedComponent.surjective_map_ofLE h
section Fintype
variable [DecidableEq V] [Fintype V] [DecidableRel G.Adj]
theorem reachable_iff_exists_finsetWalkLength_nonempty (u v : V) :
G.Reachable u v ↔ ∃ n : Fin (Fintype.card V), (G.finsetWalkLength n u v).Nonempty := by
constructor
· intro r
refine r.elim_path fun p => ?_
refine ⟨⟨_, p.isPath.length_lt⟩, p, ?_⟩
simp [mem_finsetWalkLength_iff]
· rintro ⟨_, p, _⟩
exact ⟨p⟩
instance : DecidableRel G.Reachable := fun u v =>
decidable_of_iff' _ (reachable_iff_exists_finsetWalkLength_nonempty G u v)
instance : Fintype G.ConnectedComponent :=
@Quotient.fintype _ _ G.reachableSetoid (inferInstance : DecidableRel G.Reachable)
instance : Decidable G.Preconnected :=
inferInstanceAs <| Decidable (∀ u v, G.Reachable u v)
instance : Decidable G.Connected :=
decidable_of_iff (G.Preconnected ∧ (Finset.univ : Finset V).Nonempty) <| by
rw [connected_iff, ← Finset.univ_nonempty_iff]
instance Path.instFintype {u v : V} : Fintype (G.Path u v) where
elems := (univ (α := { p : G.Walk u v | p.IsPath ∧ p.length < Fintype.card V })).map
⟨fun p ↦ { val := p.val, property := p.prop.left },
fun _ _ h ↦ SetCoe.ext <| Subtype.mk.injEq .. ▸ h⟩
complete p := mem_map.mpr ⟨
⟨p.val, ⟨p.prop, p.prop.length_lt⟩⟩,
⟨mem_univ _, rfl⟩⟩
instance instDecidableMemSupp (c : G.ConnectedComponent) (v : V) : Decidable (v ∈ c.supp) :=
c.recOn (fun w ↦ decidable_of_iff (G.Reachable v w) <| by simp)
(fun _ _ _ _ ↦ Subsingleton.elim _ _)
variable {G} in
lemma disjiUnion_supp_toFinset_eq_supp_toFinset {G' : SimpleGraph V} (h : G ≤ G')
(c' : ConnectedComponent G') [Fintype c'.supp]
[DecidablePred fun c : G.ConnectedComponent ↦ c.supp ⊆ c'.supp] :
.disjiUnion {c : ConnectedComponent G | c.supp ⊆ c'.supp} (fun c ↦ c.supp.toFinset)
(fun x _ y _ hxy ↦ by simpa using pairwise_disjoint_supp_connectedComponent _ hxy) =
c'.supp.toFinset :=
Finset.coe_injective <| by simpa using ConnectedComponent.biUnion_supp_eq_supp h _
end Fintype
/-- The odd components are the connected components of odd cardinality. This definition excludes
infinite components. -/
abbrev oddComponents : Set G.ConnectedComponent := {c : G.ConnectedComponent | Odd c.supp.ncard}
lemma ConnectedComponent.odd_oddComponents_ncard_subset_supp [Finite V] {G'}
(h : G ≤ G') (c' : ConnectedComponent G') :
Odd {c ∈ G.oddComponents | c.supp ⊆ c'.supp}.ncard ↔ Odd c'.supp.ncard := by
simp_rw [← Nat.card_coe_set_eq]
classical
cases nonempty_fintype V
rw [Nat.card_eq_card_toFinset c'.supp, ← disjiUnion_supp_toFinset_eq_supp_toFinset h]
simp only [Finset.card_disjiUnion, Set.toFinset_card, Fintype.card_ofFinset]
rw [Finset.odd_sum_iff_odd_card_odd, Nat.card_eq_fintype_card, Fintype.card_ofFinset]
congr! 2
ext c
simp_rw [Set.toFinset_setOf, mem_filter, ← Set.ncard_coe_finset, coe_filter,
mem_supp_iff, mem_univ, true_and, supp, and_comm]
lemma odd_ncard_oddComponents [Finite V] : Odd G.oddComponents.ncard ↔ Odd (Nat.card V) := by
classical
cases nonempty_fintype V
rw [Nat.card_eq_fintype_card]
simp only [← (set_fintype_card_eq_univ_iff _).mpr G.iUnion_connectedComponentSupp,
← Set.toFinset_card, Set.toFinset_iUnion ConnectedComponent.supp]
rw [Finset.card_biUnion
(fun x _ y _ hxy ↦ Set.disjoint_toFinset.mpr (pairwise_disjoint_supp_connectedComponent _ hxy))]
simp_rw [← Set.ncard_eq_toFinset_card', ← Finset.coe_filter_univ, Set.ncard_coe_finset]
exact (Finset.odd_sum_iff_odd_card_odd (fun x : G.ConnectedComponent ↦ x.supp.ncard)).symm
lemma ncard_oddComponents_mono [Finite V] {G' : SimpleGraph V} (h : G ≤ G') :
G'.oddComponents.ncard ≤ G.oddComponents.ncard := by
have aux (c : G'.ConnectedComponent) (hc : Odd c.supp.ncard) :
{c' : G.ConnectedComponent | Odd c'.supp.ncard ∧ c'.supp ⊆ c.supp}.Nonempty := by
refine Set.nonempty_of_ncard_ne_zero fun h' ↦ ?_
simpa [-Nat.card_eq_fintype_card, -Set.coe_setOf, h']
using (c.odd_oddComponents_ncard_subset_supp _ h).2 hc
let f : G'.oddComponents → G.oddComponents :=
fun ⟨c, hc⟩ ↦ ⟨(aux c hc).choose, (aux c hc).choose_spec.1⟩
refine Nat.card_le_card_of_injective f fun c c' fcc' ↦ ?_
simp only [Subtype.mk.injEq, f] at fcc'
exact Subtype.val_injective (ConnectedComponent.eq_of_common_vertex
((fcc' ▸ (aux c.1 c.2).choose_spec.2) (ConnectedComponent.nonempty_supp _).some_mem)
((aux c'.1 c'.2).choose_spec.2 (ConnectedComponent.nonempty_supp _).some_mem))
end WalkCounting
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Connectivity/Represents.lean | import Mathlib.Combinatorics.SimpleGraph.Connectivity.WalkCounting
import Mathlib.Data.Set.Card
/-!
# Representation of components by a set of vertices
## Main definition
* `SimpleGraph.ConnectedComponent.Represents` says that a set of vertices represents a set of
components if it contains exactly one vertex from each component.
-/
universe u
variable {V : Type u}
variable {G : SimpleGraph V}
namespace SimpleGraph.ConnectedComponent
/-- A set of vertices represents a set of components if it contains exactly one vertex from
each component. -/
def Represents (s : Set V) (C : Set G.ConnectedComponent) : Prop :=
Set.BijOn G.connectedComponentMk s C
namespace Represents
variable {C : Set G.ConnectedComponent} {s : Set V} {c : G.ConnectedComponent}
lemma image_out (C : Set G.ConnectedComponent) :
Represents (Quot.out '' C) C :=
Set.BijOn.mk (by rintro c ⟨x, ⟨hx, rfl⟩⟩; simp_all [connectedComponentMk]) (by
rintro x ⟨c, ⟨hc, rfl⟩⟩ y ⟨d, ⟨hd, rfl⟩⟩ hxy
simp only [connectedComponentMk] at hxy
aesop) (fun _ _ ↦ by simpa [connectedComponentMk])
lemma existsUnique_rep (hrep : Represents s C) (h : c ∈ C) : ∃! x, x ∈ s ∩ c.supp := by
obtain ⟨x, ⟨hx, rfl⟩⟩ := hrep.2.2 h
use x
simp only [Set.mem_inter_iff, hx, mem_supp_iff, and_self, and_imp, true_and]
exact fun y hy hyx ↦ hrep.2.1 hy hx hyx
lemma exists_inter_eq_singleton (hrep : Represents s C) (h : c ∈ C) : ∃ x, s ∩ c.supp = {x} := by
obtain ⟨a, ha⟩ := existsUnique_rep hrep h
aesop
lemma disjoint_supp_of_notMem (hrep : Represents s C) (h : c ∉ C) : Disjoint s c.supp := by
rw [Set.disjoint_left]
intro a ha hc
simp only [mem_supp_iff] at hc
subst hc
exact h (hrep.1 ha)
@[deprecated (since := "2025-05-23")] alias disjoint_supp_of_not_mem := disjoint_supp_of_notMem
lemma ncard_inter (hrep : Represents s C) (h : c ∈ C) : (s ∩ c.supp).ncard = 1 := by
rw [Set.ncard_eq_one]
exact exists_inter_eq_singleton hrep h
lemma ncard_eq (hrep : Represents s C) : s.ncard = C.ncard :=
hrep.image_eq ▸ (Set.ncard_image_of_injOn hrep.injOn).symm
lemma ncard_sdiff_of_mem (hrep : Represents s C) (h : c ∈ C) :
(c.supp \ s).ncard = c.supp.ncard - 1 := by
obtain ⟨a, ha⟩ := exists_inter_eq_singleton hrep h
rw [← Set.diff_inter_self_eq_diff, ha, Set.ncard_diff, Set.ncard_singleton]
simp [← ha]
lemma ncard_sdiff_of_notMem (hrep : Represents s C) (h : c ∉ C) :
(c.supp \ s).ncard = c.supp.ncard := by
rw [(disjoint_supp_of_notMem hrep h).sdiff_eq_right]
@[deprecated (since := "2025-05-23")] alias ncard_sdiff_of_not_mem := ncard_sdiff_of_notMem
end ConnectedComponent.Represents
lemma ConnectedComponent.even_ncard_supp_sdiff_rep {s : Set V} (K : G.ConnectedComponent)
(hrep : ConnectedComponent.Represents s G.oddComponents) :
Even (K.supp \ s).ncard := by
by_cases h : Even K.supp.ncard
· simpa [hrep.ncard_sdiff_of_notMem
(by simpa [Set.ncard_image_of_injective, ← Nat.not_odd_iff_even] using h)] using h
· have : K.supp.ncard ≠ 0 := Nat.ne_of_odd_add (Nat.not_even_iff_odd.mp h)
rw [hrep.ncard_sdiff_of_mem (Nat.not_even_iff_odd.mp h), Nat.even_sub (by cutsat)]
simpa [Nat.even_sub] using Nat.not_even_iff_odd.mp h
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Connectivity/Connected.lean | import Mathlib.Combinatorics.SimpleGraph.Paths
import Mathlib.Combinatorics.SimpleGraph.Subgraph
/-!
## Main definitions
* `SimpleGraph.Reachable` for the relation of whether there exists
a walk between a given pair of vertices
* `SimpleGraph.Preconnected` and `SimpleGraph.Connected` are predicates
on simple graphs for whether every vertex can be reached from every other,
and in the latter case, whether the vertex type is nonempty.
* `SimpleGraph.ConnectedComponent` is the type of connected components of
a given graph.
* `SimpleGraph.IsBridge` for whether an edge is a bridge edge
## Main statements
* `SimpleGraph.isBridge_iff_mem_and_forall_cycle_notMem` characterizes bridge edges in terms of
there being no cycle containing them.
## TODO
`IsBridge` is unpractical: we shouldn't require the edge to be present.
See https://github.com/leanprover-community/mathlib4/issues/31690.
## Tags
trails, paths, cycles, bridge edges
-/
open Function
universe u v w
namespace SimpleGraph
variable {V : Type u} {V' : Type v} {V'' : Type w}
variable (G : SimpleGraph V) (G' : SimpleGraph V') (G'' : SimpleGraph V'')
/-! ## `Reachable` and `Connected` -/
/-- Two vertices are *reachable* if there is a walk between them.
This is equivalent to `Relation.ReflTransGen` of `G.Adj`.
See `SimpleGraph.reachable_iff_reflTransGen`. -/
def Reachable (u v : V) : Prop := Nonempty (G.Walk u v)
variable {G}
theorem reachable_iff_nonempty_univ {u v : V} :
G.Reachable u v ↔ (Set.univ : Set (G.Walk u v)).Nonempty :=
Set.nonempty_iff_univ_nonempty
lemma not_reachable_iff_isEmpty_walk {u v : V} : ¬G.Reachable u v ↔ IsEmpty (G.Walk u v) :=
not_nonempty_iff
protected theorem Reachable.elim {p : Prop} {u v : V} (h : G.Reachable u v)
(hp : G.Walk u v → p) : p :=
Nonempty.elim h hp
protected theorem Reachable.elim_path {p : Prop} {u v : V} (h : G.Reachable u v)
(hp : G.Path u v → p) : p := by classical exact h.elim fun q => hp q.toPath
protected theorem Walk.reachable {G : SimpleGraph V} {u v : V} (p : G.Walk u v) : G.Reachable u v :=
⟨p⟩
protected theorem Adj.reachable {u v : V} (h : G.Adj u v) : G.Reachable u v :=
h.toWalk.reachable
@[refl]
protected theorem Reachable.refl (u : V) : G.Reachable u u := ⟨Walk.nil⟩
@[simp] protected theorem Reachable.rfl {u : V} : G.Reachable u u := Reachable.refl _
@[symm]
protected theorem Reachable.symm {u v : V} (huv : G.Reachable u v) : G.Reachable v u :=
huv.elim fun p => ⟨p.reverse⟩
theorem reachable_comm {u v : V} : G.Reachable u v ↔ G.Reachable v u :=
⟨Reachable.symm, Reachable.symm⟩
@[trans]
protected theorem Reachable.trans {u v w : V} (huv : G.Reachable u v) (hvw : G.Reachable v w) :
G.Reachable u w :=
huv.elim fun puv => hvw.elim fun pvw => ⟨puv.append pvw⟩
theorem reachable_iff_reflTransGen (u v : V) :
G.Reachable u v ↔ Relation.ReflTransGen G.Adj u v := by
constructor
· rintro ⟨h⟩
induction h with
| nil => rfl
| cons h' _ ih => exact (Relation.ReflTransGen.single h').trans ih
· intro h
induction h with
| refl => rfl
| tail _ ha hr => exact Reachable.trans hr ⟨Walk.cons ha Walk.nil⟩
protected theorem Reachable.map {u v : V} {G : SimpleGraph V} {G' : SimpleGraph V'} (f : G →g G')
(h : G.Reachable u v) : G'.Reachable (f u) (f v) :=
h.elim fun p => ⟨p.map f⟩
@[mono]
protected lemma Reachable.mono {u v : V} {G G' : SimpleGraph V}
(h : G ≤ G') (Guv : G.Reachable u v) : G'.Reachable u v := Guv.map (.ofLE h)
theorem Reachable.exists_isPath {u v} (hr : G.Reachable u v) : ∃ p : G.Walk u v, p.IsPath := by
classical
obtain ⟨W⟩ := hr
exact ⟨_, Path.isPath W.toPath⟩
theorem Iso.reachable_iff {G : SimpleGraph V} {G' : SimpleGraph V'} {φ : G ≃g G'} {u v : V} :
G'.Reachable (φ u) (φ v) ↔ G.Reachable u v :=
⟨fun r => φ.left_inv u ▸ φ.left_inv v ▸ r.map φ.symm.toHom, Reachable.map φ.toHom⟩
theorem Iso.symm_apply_reachable {G : SimpleGraph V} {G' : SimpleGraph V'} {φ : G ≃g G'} {u : V}
{v : V'} : G.Reachable (φ.symm v) u ↔ G'.Reachable v (φ u) := by
rw [← Iso.reachable_iff, RelIso.apply_symm_apply]
lemma Reachable.mem_subgraphVerts {u v} {H : G.Subgraph} (hr : G.Reachable u v)
(h : ∀ v ∈ H.verts, ∀ w, G.Adj v w → H.Adj v w)
(hu : u ∈ H.verts) : v ∈ H.verts := by
let rec aux {v' : V} (hv' : v' ∈ H.verts) (p : G.Walk v' v) : v ∈ H.verts := by
by_cases hnp : p.Nil
· exact hnp.eq ▸ hv'
exact aux (H.edge_vert (h _ hv' _ (Walk.adj_snd hnp)).symm) p.tail
termination_by p.length
decreasing_by {
rw [← Walk.length_tail_add_one hnp]
omega
}
exact aux hu hr.some
variable (G)
theorem reachable_is_equivalence : Equivalence G.Reachable :=
Equivalence.mk (@Reachable.refl _ G) (@Reachable.symm _ G) (@Reachable.trans _ G)
/-- Distinct vertices are not reachable in the empty graph. -/
@[simp]
lemma reachable_bot {u v : V} : (⊥ : SimpleGraph V).Reachable u v ↔ u = v :=
⟨fun h ↦ h.elim fun p ↦ match p with | .nil => rfl, fun h ↦ h ▸ .rfl⟩
@[simp] lemma reachable_top {u v : V} : (completeGraph V).Reachable u v := by
obtain rfl | huv := eq_or_ne u v
· simp
· exact ⟨.cons huv .nil⟩
/-- The equivalence relation on vertices given by `SimpleGraph.Reachable`. -/
def reachableSetoid : Setoid V := Setoid.mk _ G.reachable_is_equivalence
/-- A graph is preconnected if every pair of vertices is reachable from one another. -/
def Preconnected : Prop := ∀ u v : V, G.Reachable u v
theorem Preconnected.map {G : SimpleGraph V} {H : SimpleGraph V'} (f : G →g H) (hf : Surjective f)
(hG : G.Preconnected) : H.Preconnected :=
hf.forall₂.2 fun _ _ => Nonempty.map (Walk.map _) <| hG _ _
@[mono]
protected lemma Preconnected.mono {G G' : SimpleGraph V} (h : G ≤ G') (hG : G.Preconnected) :
G'.Preconnected := fun u v => (hG u v).mono h
lemma preconnected_bot_iff_subsingleton : (⊥ : SimpleGraph V).Preconnected ↔ Subsingleton V := by
refine ⟨fun h ↦ ?_, fun h ↦ by simpa [subsingleton_iff, ← reachable_bot] using h⟩
contrapose! h
simp [nontrivial_iff.mp h, Preconnected, reachable_bot]
lemma preconnected_bot [Subsingleton V] : (⊥ : SimpleGraph V).Preconnected :=
preconnected_bot_iff_subsingleton.mpr ‹_›
lemma not_preconnected_bot [Nontrivial V] : ¬(⊥ : SimpleGraph V).Preconnected :=
preconnected_bot_iff_subsingleton.not.mpr <| not_subsingleton_iff_nontrivial.mpr ‹_›
@[simp] lemma preconnected_top : (⊤ : SimpleGraph V).Preconnected := fun x y => by
if h : x = y then rw [h] else exact Adj.reachable h
@[deprecated (since := "2025-09-23")] alias bot_preconnected := preconnected_bot
@[deprecated (since := "2025-09-23")]
alias bot_preconnected_iff_subsingleton := preconnected_bot_iff_subsingleton
@[deprecated (since := "2025-09-23")] alias bot_not_preconnected := not_preconnected_bot
@[deprecated (since := "2025-09-23")] alias top_preconnected := preconnected_top
theorem Iso.preconnected_iff {G : SimpleGraph V} {H : SimpleGraph V'} (e : G ≃g H) :
G.Preconnected ↔ H.Preconnected :=
⟨Preconnected.map e.toHom e.toEquiv.surjective,
Preconnected.map e.symm.toHom e.symm.toEquiv.surjective⟩
lemma Preconnected.support_eq_univ [Nontrivial V] {G : SimpleGraph V}
(h : G.Preconnected) : G.support = Set.univ := by
simp only [Set.eq_univ_iff_forall]
intro v
obtain ⟨w, hw⟩ := exists_ne v
obtain ⟨p⟩ := h v w
cases p with
| nil => contradiction
| @cons _ w => exact ⟨w, ‹_›⟩
lemma Preconnected.degree_pos_of_nontrivial [Nontrivial V] {G : SimpleGraph V} (h : G.Preconnected)
(v : V) [Fintype (G.neighborSet v)] : 0 < G.degree v := by
simp [degree_pos_iff_mem_support, h.support_eq_univ]
lemma Preconnected.minDegree_pos_of_nontrivial [Nontrivial V] [Fintype V] {G : SimpleGraph V}
[DecidableRel G.Adj] (h : G.Preconnected) : 0 < G.minDegree := by
obtain ⟨v, hv⟩ := G.exists_minimal_degree_vertex
rw [hv]
exact h.degree_pos_of_nontrivial v
lemma adj_of_mem_walk_support {G : SimpleGraph V} {u v : V} (p : G.Walk u v) (hp : ¬p.Nil) {x : V}
(hx : x ∈ p.support) : ∃ y ∈ p.support, G.Adj x y := by
induction p with
| nil =>
exact (hp Walk.Nil.nil).elim
| @cons u v w h p ih =>
cases List.mem_cons.mp hx with
| inl hxu =>
rw [hxu]
exact ⟨v, ⟨((Walk.cons h p).mem_support_iff).mpr (Or.inr p.start_mem_support), h⟩⟩
| inr hxp =>
cases Decidable.em p.Nil with
| inl hnil =>
rw [Walk.nil_iff_support_eq.mp hnil] at hxp
rw [show (x = v) by simp_all]
exact ⟨u, ⟨(Walk.cons h p).start_mem_support, G.adj_symm h⟩⟩
| inr hnotnil =>
obtain ⟨y, hy⟩ := ih hnotnil hxp
refine ⟨y, ⟨?_, hy.right⟩⟩
rw [Walk.mem_support_iff]
simp only [Walk.support_cons, List.tail_cons]
exact Or.inr hy.left
lemma mem_support_of_mem_walk_support {G : SimpleGraph V} {u v : V} (p : G.Walk u v) (hp : ¬p.Nil)
{w : V} (hw : w ∈ p.support) : w ∈ G.support := by
obtain ⟨y, hy⟩ := adj_of_mem_walk_support p hp hw
exact (mem_support G).mpr ⟨y, hy.right⟩
lemma mem_support_of_reachable {G : SimpleGraph V} {u v : V} (huv : u ≠ v) (h : G.Reachable u v) :
u ∈ G.support := by
let p : G.Walk u v := Classical.choice h
have hp : ¬p.Nil := Walk.not_nil_of_ne huv
exact mem_support_of_mem_walk_support p hp p.start_mem_support
theorem Preconnected.exists_isPath {G : SimpleGraph V} (h : G.Preconnected) (u v : V) :
∃ p : G.Walk u v, p.IsPath :=
(h u v).exists_isPath
/-- A graph is connected if it's preconnected and contains at least one vertex.
This follows the convention observed by mathlib that something is connected iff it has
exactly one connected component.
There is a `CoeFun` instance so that `h u v` can be used instead of `h.Preconnected u v`. -/
@[mk_iff]
structure Connected : Prop where
protected preconnected : G.Preconnected
protected [nonempty : Nonempty V]
lemma connected_iff_exists_forall_reachable : G.Connected ↔ ∃ v, ∀ w, G.Reachable v w := by
rw [connected_iff]
constructor
· rintro ⟨hp, ⟨v⟩⟩
exact ⟨v, fun w => hp v w⟩
· rintro ⟨v, h⟩
exact ⟨fun u w => (h u).symm.trans (h w), ⟨v⟩⟩
instance : CoeFun G.Connected fun _ => ∀ u v : V, G.Reachable u v := ⟨fun h => h.preconnected⟩
theorem Connected.map {G : SimpleGraph V} {H : SimpleGraph V'} (f : G →g H) (hf : Surjective f)
(hG : G.Connected) : H.Connected :=
haveI := hG.nonempty.map f
⟨hG.preconnected.map f hf⟩
@[mono]
protected lemma Connected.mono {G G' : SimpleGraph V} (h : G ≤ G')
(hG : G.Connected) : G'.Connected where
preconnected := hG.preconnected.mono h
nonempty := hG.nonempty
theorem Connected.exists_isPath {G : SimpleGraph V} (h : G.Connected) (u v : V) :
∃ p : G.Walk u v, p.IsPath :=
(h u v).exists_isPath
lemma connected_bot_iff : (⊥ : SimpleGraph V).Connected ↔ Subsingleton V ∧ Nonempty V := by
simp [preconnected_bot_iff_subsingleton, connected_iff]
lemma not_connected_bot [Nontrivial V] : ¬(⊥ : SimpleGraph V).Connected := by
simp [not_preconnected_bot, connected_iff]
lemma connected_top_iff : (completeGraph V).Connected ↔ Nonempty V := by simp [connected_iff]
@[simp] lemma connected_top [Nonempty V] : (completeGraph V).Connected := by rwa [connected_top_iff]
@[deprecated (since := "2025-09-23")] alias bot_not_connected := not_connected_bot
@[deprecated (since := "2025-09-23")] alias top_connected := connected_top
theorem Iso.connected_iff {G : SimpleGraph V} {H : SimpleGraph V'} (e : G ≃g H) :
G.Connected ↔ H.Connected :=
⟨Connected.map e.toHom e.toEquiv.surjective, Connected.map e.symm.toHom e.symm.toEquiv.surjective⟩
lemma reachable_or_compl_adj (u v : V) : G.Reachable u v ∨ Gᶜ.Adj u v :=
or_iff_not_imp_left.mpr fun huv ↦ ⟨fun heq ↦ huv <| heq ▸ Reachable.rfl, mt Adj.reachable huv⟩
theorem reachable_or_reachable_compl (u v w : V) : G.Reachable u v ∨ Gᶜ.Reachable u w := by
refine or_iff_not_imp_left.mpr fun huv ↦ ?_
by_cases huw : G.Reachable u w
· have huv' := G.reachable_or_compl_adj .. |>.resolve_left huv
have hvw' := G.reachable_or_compl_adj .. |>.resolve_left fun hvw ↦ huv <| huw.trans hvw.symm
exact huv'.reachable.trans hvw'.reachable
exact G.reachable_or_compl_adj .. |>.resolve_left huw |>.reachable
theorem connected_or_preconnected_compl : G.Connected ∨ Gᶜ.Preconnected := by
rw [or_iff_not_imp_left, G.connected_iff_exists_forall_reachable]
intro h u v
push_neg at h
have ⟨w, huw⟩ := h u
exact reachable_or_reachable_compl .. |>.resolve_left huw
theorem connected_or_connected_compl [Nonempty V] : G.Connected ∨ Gᶜ.Connected :=
G.connected_or_preconnected_compl.elim .inl (.inr ⟨·⟩)
/-- The quotient of `V` by the `SimpleGraph.Reachable` relation gives the connected
components of a graph. -/
def ConnectedComponent := Quot G.Reachable
/-- Gives the connected component containing a particular vertex. -/
def connectedComponentMk (v : V) : G.ConnectedComponent := Quot.mk G.Reachable v
variable {G G' G''}
namespace ConnectedComponent
@[simps]
instance inhabited [Inhabited V] : Inhabited G.ConnectedComponent :=
⟨G.connectedComponentMk default⟩
instance isEmpty [IsEmpty V] : IsEmpty G.ConnectedComponent := Quot.instIsEmpty
instance [Subsingleton V] : Subsingleton G.ConnectedComponent := Quot.Subsingleton
instance [Unique V] : Unique G.ConnectedComponent := Quot.instUnique
instance [Nonempty V] : Nonempty G.ConnectedComponent := Nonempty.map G.connectedComponentMk ‹_›
@[elab_as_elim]
protected theorem ind {β : G.ConnectedComponent → Prop}
(h : ∀ v : V, β (G.connectedComponentMk v)) (c : G.ConnectedComponent) : β c :=
Quot.ind h c
@[elab_as_elim]
protected theorem ind₂ {β : G.ConnectedComponent → G.ConnectedComponent → Prop}
(h : ∀ v w : V, β (G.connectedComponentMk v) (G.connectedComponentMk w))
(c d : G.ConnectedComponent) : β c d :=
Quot.induction_on₂ c d h
protected theorem sound {v w : V} :
G.Reachable v w → G.connectedComponentMk v = G.connectedComponentMk w :=
Quot.sound
protected theorem exact {v w : V} :
G.connectedComponentMk v = G.connectedComponentMk w → G.Reachable v w :=
@Quotient.exact _ G.reachableSetoid _ _
@[simp]
protected theorem eq {v w : V} :
G.connectedComponentMk v = G.connectedComponentMk w ↔ G.Reachable v w :=
@Quotient.eq' _ G.reachableSetoid _ _
theorem connectedComponentMk_eq_of_adj {v w : V} (a : G.Adj v w) :
G.connectedComponentMk v = G.connectedComponentMk w :=
ConnectedComponent.sound a.reachable
/-- The `ConnectedComponent` specialization of `Quot.lift`. Provides the stronger
assumption that the vertices are connected by a path. -/
protected def lift {β : Sort*} (f : V → β)
(h : ∀ (v w : V) (p : G.Walk v w), p.IsPath → f v = f w) : G.ConnectedComponent → β :=
Quot.lift f fun v w (h' : G.Reachable v w) => h'.elim_path fun hp => h v w hp hp.2
@[simp]
protected theorem lift_mk {β : Sort*} {f : V → β}
{h : ∀ (v w : V) (p : G.Walk v w), p.IsPath → f v = f w} {v : V} :
ConnectedComponent.lift f h (G.connectedComponentMk v) = f v :=
rfl
protected theorem «exists» {p : G.ConnectedComponent → Prop} :
(∃ c : G.ConnectedComponent, p c) ↔ ∃ v, p (G.connectedComponentMk v) :=
Quot.mk_surjective.exists
protected theorem «forall» {p : G.ConnectedComponent → Prop} :
(∀ c : G.ConnectedComponent, p c) ↔ ∀ v, p (G.connectedComponentMk v) :=
Quot.mk_surjective.forall
theorem _root_.SimpleGraph.Preconnected.subsingleton_connectedComponent (h : G.Preconnected) :
Subsingleton G.ConnectedComponent :=
⟨ConnectedComponent.ind₂ fun v w => ConnectedComponent.sound (h v w)⟩
/-- This is `Quot.recOn` specialized to connected components.
For convenience, it strengthens the assumptions in the hypothesis
to provide a path between the vertices. -/
@[elab_as_elim]
def recOn
{motive : G.ConnectedComponent → Sort*}
(c : G.ConnectedComponent)
(f : (v : V) → motive (G.connectedComponentMk v))
(h : ∀ (u v : V) (p : G.Walk u v) (_ : p.IsPath),
ConnectedComponent.sound p.reachable ▸ f u = f v) :
motive c :=
Quot.recOn c f fun u v r => r.elim_path fun p => h u v p p.2
/-- The map on connected components induced by a graph homomorphism. -/
def map (φ : G →g G') (C : G.ConnectedComponent) : G'.ConnectedComponent :=
C.lift (fun v => G'.connectedComponentMk (φ v)) fun _ _ p _ =>
ConnectedComponent.eq.mpr (p.map φ).reachable
@[simp]
theorem map_mk (φ : G →g G') (v : V) :
(G.connectedComponentMk v).map φ = G'.connectedComponentMk (φ v) :=
rfl
@[simp]
theorem map_id (C : ConnectedComponent G) : C.map Hom.id = C := C.ind (fun _ => rfl)
@[simp]
theorem map_comp (C : G.ConnectedComponent) (φ : G →g G') (ψ : G' →g G'') :
(C.map φ).map ψ = C.map (ψ.comp φ) :=
C.ind (fun _ => rfl)
@[simp]
theorem surjective_map_ofLE {G' : SimpleGraph V} (h : G ≤ G') : (map <| Hom.ofLE h).Surjective :=
Quot.ind fun v ↦ ⟨G.connectedComponentMk v, rfl⟩
variable {φ : G ≃g G'} {v : V} {v' : V'}
@[simp]
theorem iso_image_comp_eq_map_iff_eq_comp {C : G.ConnectedComponent} :
G'.connectedComponentMk (φ v) = C.map ↑(↑φ : G ↪g G') ↔ G.connectedComponentMk v = C := by
refine C.ind fun u => ?_
simp only [Iso.reachable_iff, ConnectedComponent.map_mk, RelEmbedding.coe_toRelHom,
RelIso.coe_toRelEmbedding, ConnectedComponent.eq]
@[simp]
theorem iso_inv_image_comp_eq_iff_eq_map {C : G.ConnectedComponent} :
G.connectedComponentMk (φ.symm v') = C ↔ G'.connectedComponentMk v' = C.map φ := by
refine C.ind fun u => ?_
simp only [Iso.symm_apply_reachable, ConnectedComponent.eq, ConnectedComponent.map_mk,
RelEmbedding.coe_toRelHom, RelIso.coe_toRelEmbedding]
end ConnectedComponent
namespace Iso
/-- An isomorphism of graphs induces a bijection of connected components. -/
@[simps]
def connectedComponentEquiv (φ : G ≃g G') : G.ConnectedComponent ≃ G'.ConnectedComponent where
toFun := ConnectedComponent.map φ
invFun := ConnectedComponent.map φ.symm
left_inv C := C.ind (fun v => congr_arg G.connectedComponentMk (Equiv.left_inv φ.toEquiv v))
right_inv C := C.ind (fun v => congr_arg G'.connectedComponentMk (Equiv.right_inv φ.toEquiv v))
@[simp]
theorem connectedComponentEquiv_refl :
(Iso.refl : G ≃g G).connectedComponentEquiv = Equiv.refl _ := by
ext ⟨v⟩
rfl
@[simp]
theorem connectedComponentEquiv_symm (φ : G ≃g G') :
φ.symm.connectedComponentEquiv = φ.connectedComponentEquiv.symm := by
ext ⟨_⟩
rfl
@[simp]
theorem connectedComponentEquiv_trans (φ : G ≃g G') (φ' : G' ≃g G'') :
connectedComponentEquiv (φ.trans φ') =
φ.connectedComponentEquiv.trans φ'.connectedComponentEquiv := by
ext ⟨_⟩
rfl
end Iso
namespace ConnectedComponent
/-- The set of vertices in a connected component of a graph. -/
def supp (C : G.ConnectedComponent) :=
{ v | G.connectedComponentMk v = C }
@[ext]
theorem supp_injective :
Function.Injective (ConnectedComponent.supp : G.ConnectedComponent → Set V) := by
refine ConnectedComponent.ind₂ ?_
simp only [ConnectedComponent.supp, Set.ext_iff, ConnectedComponent.eq, Set.mem_setOf_eq]
intro v w h
rw [reachable_comm, h]
@[simp]
theorem supp_inj {C D : G.ConnectedComponent} : C.supp = D.supp ↔ C = D :=
ConnectedComponent.supp_injective.eq_iff
instance : SetLike G.ConnectedComponent V where
coe := ConnectedComponent.supp
coe_injective' := ConnectedComponent.supp_injective
@[simp]
theorem mem_supp_iff (C : G.ConnectedComponent) (v : V) :
v ∈ C.supp ↔ G.connectedComponentMk v = C :=
Iff.rfl
lemma mem_supp_congr_adj {v w : V} (c : G.ConnectedComponent) (hadj : G.Adj v w) :
v ∈ c.supp ↔ w ∈ c.supp := by
simp only [ConnectedComponent.mem_supp_iff] at *
constructor <;> intro h <;> simp only [← h] <;> apply connectedComponentMk_eq_of_adj
· exact hadj.symm
· exact hadj
theorem connectedComponentMk_mem {v : V} : v ∈ G.connectedComponentMk v :=
rfl
theorem nonempty_supp (C : G.ConnectedComponent) : C.supp.Nonempty := C.exists_rep
/-- The equivalence between connected components, induced by an isomorphism of graphs,
itself defines an equivalence on the supports of each connected component.
-/
def isoEquivSupp (φ : G ≃g G') (C : G.ConnectedComponent) :
C.supp ≃ (φ.connectedComponentEquiv C).supp where
toFun v := ⟨φ v, ConnectedComponent.iso_image_comp_eq_map_iff_eq_comp.mpr v.prop⟩
invFun v' := ⟨φ.symm v', ConnectedComponent.iso_inv_image_comp_eq_iff_eq_map.mpr v'.prop⟩
left_inv v := Subtype.ext (φ.toEquiv.left_inv ↑v)
right_inv v := Subtype.ext (φ.toEquiv.right_inv ↑v)
lemma mem_coe_supp_of_adj {v w : V} {H : Subgraph G} {c : ConnectedComponent H.coe}
(hv : v ∈ (↑) '' (c : Set H.verts)) (hw : w ∈ H.verts)
(hadj : H.Adj v w) : w ∈ (↑) '' (c : Set H.verts) := by
obtain ⟨_, h⟩ := hv
use ⟨w, hw⟩
rw [← (mem_supp_iff _ _).mp h.1]
exact ⟨connectedComponentMk_eq_of_adj <| Subgraph.Adj.coe <| h.2 ▸ hadj.symm, rfl⟩
lemma eq_of_common_vertex {v : V} {c c' : ConnectedComponent G} (hc : v ∈ c.supp)
(hc' : v ∈ c'.supp) : c = c' := by
simp only [mem_supp_iff] at *
rw [← hc, ← hc']
lemma connectedComponentMk_supp_subset_supp {G'} {v : V} (h : G ≤ G') (c' : G'.ConnectedComponent)
(hc' : v ∈ c'.supp) : (G.connectedComponentMk v).supp ⊆ c'.supp := by
intro v' hv'
simp only [mem_supp_iff, ConnectedComponent.eq] at hv' ⊢
rw [ConnectedComponent.sound (hv'.mono h)]
exact hc'
lemma biUnion_supp_eq_supp {G G' : SimpleGraph V} (h : G ≤ G') (c' : ConnectedComponent G') :
⋃ (c : ConnectedComponent G) (_ : c.supp ⊆ c'.supp), c.supp = c'.supp := by
ext v
simp_rw [Set.mem_iUnion]
refine ⟨fun ⟨_, ⟨hi, hi'⟩⟩ ↦ hi hi', ?_⟩
intro hv
use G.connectedComponentMk v
use c'.connectedComponentMk_supp_subset_supp h hv
simp only [mem_supp_iff]
lemma top_supp_eq_univ (c : ConnectedComponent (⊤ : SimpleGraph V)) :
c.supp = (Set.univ : Set V) := by
obtain ⟨w, rfl⟩ := c.exists_rep
ext v
simpa [-ConnectedComponent.eq] using ConnectedComponent.sound (G := ⊤)
lemma reachable_of_mem_supp {G : SimpleGraph V} (C : G.ConnectedComponent) {u v : V}
(hu : u ∈ C.supp) (hv : v ∈ C.supp) : G.Reachable u v := by
rw [mem_supp_iff] at hu hv
exact ConnectedComponent.exact (hv ▸ hu)
lemma mem_supp_of_adj_mem_supp {G : SimpleGraph V} (C : G.ConnectedComponent) {u v : V}
(hu : u ∈ C.supp) (hadj : G.Adj u v) : v ∈ C.supp := (mem_supp_congr_adj C hadj).mp hu
/--
Given a connected component `C` of a simple graph `G`, produce the induced graph on `C`.
The declaration `connected_toSimpleGraph` shows it is connected, and `toSimpleGraph_hom`
provides the homomorphism back to `G`.
-/
def toSimpleGraph {G : SimpleGraph V} (C : G.ConnectedComponent) : SimpleGraph C := G.induce C.supp
/-- Homomorphism from a connected component graph to the original graph. -/
def toSimpleGraph_hom {G : SimpleGraph V} (C : G.ConnectedComponent) : C.toSimpleGraph →g G where
toFun u := u.val
map_rel' := id
lemma toSimpleGraph_hom_apply {G : SimpleGraph V} (C : G.ConnectedComponent) (u : C) :
C.toSimpleGraph_hom u = u.val := rfl
lemma toSimpleGraph_adj {G : SimpleGraph V} (C : G.ConnectedComponent) {u v : V} (hu : u ∈ C)
(hv : v ∈ C) : C.toSimpleGraph.Adj ⟨u, hu⟩ ⟨v, hv⟩ ↔ G.Adj u v := by
simp [toSimpleGraph]
lemma adj_spanningCoe_toSimpleGraph {v w : V} (C : G.ConnectedComponent) :
C.toSimpleGraph.spanningCoe.Adj v w ↔ v ∈ C.supp ∧ G.Adj v w := by
apply Iff.intro
· intro h
simp_all only [map_adj, SetLike.coe_sort_coe, Subtype.exists, mem_supp_iff]
obtain ⟨_, a, _, _, h₁, h₂, h₃⟩ := h
subst h₂ h₃
exact ⟨a, h₁⟩
· simp only [toSimpleGraph, map_adj, comap_adj, Embedding.subtype_apply, Subtype.exists,
exists_and_left, and_imp]
intro h hadj
exact ⟨v, h, w, hadj, rfl, (C.mem_supp_congr_adj hadj).mp h, rfl⟩
@[deprecated (since := "2025-05-08")]
alias adj_spanningCoe_induce_supp := adj_spanningCoe_toSimpleGraph
/-- Get the walk between two vertices in a connected component from a walk in the original graph. -/
private def walk_toSimpleGraph' {G : SimpleGraph V} (C : G.ConnectedComponent) {u v : V}
(hu : u ∈ C) (hv : v ∈ C) (p : G.Walk u v) : C.toSimpleGraph.Walk ⟨u, hu⟩ ⟨v, hv⟩ := by
cases p with
| nil => exact Walk.nil
| @cons v w u h p =>
have hw : w ∈ C := C.mem_supp_of_adj_mem_supp hu h
have h' : C.toSimpleGraph.Adj ⟨u, hu⟩ ⟨w, hw⟩ := h
exact Walk.cons h' (C.walk_toSimpleGraph' hw hv p)
@[deprecated (since := "2025-05-08")] alias reachable_induce_supp := walk_toSimpleGraph'
/-- There is a walk between every pair of vertices in a connected component. -/
noncomputable def walk_toSimpleGraph {G : SimpleGraph V} (C : G.ConnectedComponent) {u v : V}
(hu : u ∈ C) (hv : v ∈ C) : C.toSimpleGraph.Walk ⟨u, hu⟩ ⟨v, hv⟩ :=
C.walk_toSimpleGraph' hu hv (C.reachable_of_mem_supp hu hv).some
lemma reachable_toSimpleGraph {G : SimpleGraph V} (C : G.ConnectedComponent) {u v : V}
(hu : u ∈ C) (hv : v ∈ C) : C.toSimpleGraph.Reachable ⟨u, hu⟩ ⟨v, hv⟩ :=
Walk.reachable (C.walk_toSimpleGraph hu hv)
lemma connected_toSimpleGraph (C : ConnectedComponent G) : (C.toSimpleGraph).Connected where
preconnected := by
intro ⟨u, hu⟩ ⟨v, hv⟩
exact C.reachable_toSimpleGraph hu hv
nonempty := ⟨C.out, C.out_eq⟩
@[deprecated (since := "2025-05-08")] alias connected_induce_supp := connected_toSimpleGraph
end ConnectedComponent
/-- Given graph homomorphisms from each connected component of `G` to `H` this is the graph
homomorphism from `G` to `H` -/
@[simps]
def homOfConnectedComponents (G : SimpleGraph V) {H : SimpleGraph V'}
(C : (c : G.ConnectedComponent) → c.toSimpleGraph →g H) : G →g H where
toFun := fun x ↦ (C (G.connectedComponentMk _)) _
map_rel' := fun hab ↦ by
have h : (G.connectedComponentMk _).toSimpleGraph.Adj ⟨_, rfl⟩
⟨_, ((G.connectedComponentMk _).mem_supp_congr_adj hab).1 rfl⟩ := by simpa using hab
convert (C (G.connectedComponentMk _)).map_rel h using 3 <;>
rw [ConnectedComponent.connectedComponentMk_eq_of_adj hab]
-- TODO: Extract as lemma about general equivalence relation
lemma pairwise_disjoint_supp_connectedComponent (G : SimpleGraph V) :
Pairwise fun c c' : ConnectedComponent G ↦ Disjoint c.supp c'.supp := by
simp_rw [Set.disjoint_left]
intro _ _ h a hsx hsy
rw [ConnectedComponent.mem_supp_iff] at hsx hsy
rw [hsx] at hsy
exact h hsy
-- TODO: Extract as lemma about general equivalence relation
lemma iUnion_connectedComponentSupp (G : SimpleGraph V) :
⋃ c : G.ConnectedComponent, c.supp = Set.univ := by
refine Set.eq_univ_of_forall fun v ↦ ⟨G.connectedComponentMk v, ?_⟩
simp only [Set.mem_range, SetLike.mem_coe]
exact ⟨⟨G.connectedComponentMk v, rfl⟩, rfl⟩
theorem Preconnected.set_univ_walk_nonempty (hconn : G.Preconnected) (u v : V) :
(Set.univ : Set (G.Walk u v)).Nonempty := by
rw [← Set.nonempty_iff_univ_nonempty]
exact hconn u v
theorem Connected.set_univ_walk_nonempty (hconn : G.Connected) (u v : V) :
(Set.univ : Set (G.Walk u v)).Nonempty :=
hconn.preconnected.set_univ_walk_nonempty u v
/-! ### Bridge edges -/
section BridgeEdges
/-- An edge of a graph is a *bridge* if, after removing it, its incident vertices
are no longer reachable from one another. -/
def IsBridge (G : SimpleGraph V) (e : Sym2 V) : Prop :=
e ∈ G.edgeSet ∧
Sym2.lift ⟨fun v w => ¬(G \ fromEdgeSet {e}).Reachable v w, by simp [reachable_comm]⟩ e
theorem isBridge_iff {u v : V} :
G.IsBridge s(u, v) ↔ G.Adj u v ∧ ¬(G \ fromEdgeSet {s(u, v)}).Reachable u v := Iff.rfl
theorem reachable_delete_edges_iff_exists_walk {v w v' w' : V} :
(G \ fromEdgeSet {s(v, w)}).Reachable v' w' ↔ ∃ p : G.Walk v' w', s(v, w) ∉ p.edges := by
constructor
· rintro ⟨p⟩
use p.map (.ofLE (by simp))
simp_rw [Walk.edges_map, List.mem_map, Hom.ofLE_apply, Sym2.map_id', id]
rintro ⟨e, h, rfl⟩
simpa using p.edges_subset_edgeSet h
· rintro ⟨p, h⟩
refine ⟨p.transfer _ fun e ep => ?_⟩
simp only [edgeSet_sdiff, edgeSet_fromEdgeSet, edgeSet_sdiff_sdiff_isDiag]
exact ⟨p.edges_subset_edgeSet ep, fun h' => h (h' ▸ ep)⟩
theorem isBridge_iff_adj_and_forall_walk_mem_edges {v w : V} :
G.IsBridge s(v, w) ↔ G.Adj v w ∧ ∀ p : G.Walk v w, s(v, w) ∈ p.edges := by
rw [isBridge_iff, and_congr_right']
rw [reachable_delete_edges_iff_exists_walk, not_exists_not]
theorem reachable_deleteEdges_iff_exists_cycle.aux [DecidableEq V] {u v w : V}
(hb : ∀ p : G.Walk v w, s(v, w) ∈ p.edges) (c : G.Walk u u) (hc : c.IsTrail)
(he : s(v, w) ∈ c.edges)
(hw : w ∈ (c.takeUntil v (c.fst_mem_support_of_mem_edges he)).support) : False := by
have hv := c.fst_mem_support_of_mem_edges he
-- decompose c into
-- puw pwv pvu
-- u ----> w ----> v ----> u
let puw := (c.takeUntil v hv).takeUntil w hw
let pwv := (c.takeUntil v hv).dropUntil w hw
let pvu := c.dropUntil v hv
have : c = (puw.append pwv).append pvu := by simp [puw, pwv, pvu]
-- We have two walks from v to w
-- pvu puw
-- v ----> u ----> w
-- | ^
-- `-------------'
-- pwv.reverse
-- so they both contain the edge s(v, w), but that's a contradiction since c is a trail.
have hbq := hb (pvu.append puw)
have hpq' := hb pwv.reverse
rw [Walk.edges_reverse, List.mem_reverse] at hpq'
rw [Walk.isTrail_def, this, Walk.edges_append, Walk.edges_append, List.nodup_append_comm,
← List.append_assoc, ← Walk.edges_append] at hc
exact List.disjoint_of_nodup_append hc hbq hpq'
theorem adj_and_reachable_delete_edges_iff_exists_cycle {v w : V} :
G.Adj v w ∧ (G \ fromEdgeSet {s(v, w)}).Reachable v w ↔
∃ (u : V) (p : G.Walk u u), p.IsCycle ∧ s(v, w) ∈ p.edges := by
classical
rw [reachable_delete_edges_iff_exists_walk]
constructor
· rintro ⟨h, p, hp⟩
refine ⟨w, Walk.cons h.symm p.toPath, ?_, ?_⟩
· apply Path.cons_isCycle
rw [Sym2.eq_swap]
intro h
cases hp (Walk.edges_toPath_subset p h)
· simp only [Sym2.eq_swap, Walk.edges_cons, List.mem_cons, true_or]
· rintro ⟨u, c, hc, he⟩
refine ⟨c.adj_of_mem_edges he, ?_⟩
by_contra! hb
have hb' : ∀ p : G.Walk w v, s(w, v) ∈ p.edges := by
intro p
simpa [Sym2.eq_swap] using hb p.reverse
have hvc : v ∈ c.support := Walk.fst_mem_support_of_mem_edges c he
refine reachable_deleteEdges_iff_exists_cycle.aux hb' (c.rotate hvc) (hc.isTrail.rotate hvc)
?_ (Walk.start_mem_support _)
rwa [(Walk.rotate_edges c hvc).mem_iff, Sym2.eq_swap]
theorem isBridge_iff_adj_and_forall_cycle_notMem {v w : V} : G.IsBridge s(v, w) ↔
G.Adj v w ∧ ∀ ⦃u : V⦄ (p : G.Walk u u), p.IsCycle → s(v, w) ∉ p.edges := by
rw [isBridge_iff, and_congr_right_iff]
intro h
rw [← not_iff_not]
push_neg
rw [← adj_and_reachable_delete_edges_iff_exists_cycle]
simp only [h, true_and]
@[deprecated (since := "2025-05-23")]
alias isBridge_iff_adj_and_forall_cycle_not_mem := isBridge_iff_adj_and_forall_cycle_notMem
theorem isBridge_iff_mem_and_forall_cycle_notMem {e : Sym2 V} :
G.IsBridge e ↔ e ∈ G.edgeSet ∧ ∀ ⦃u : V⦄ (p : G.Walk u u), p.IsCycle → e ∉ p.edges :=
Sym2.ind (fun _ _ => isBridge_iff_adj_and_forall_cycle_notMem) e
@[deprecated (since := "2025-05-23")]
alias isBridge_iff_mem_and_forall_cycle_not_mem := isBridge_iff_mem_and_forall_cycle_notMem
/-- Deleting a non-bridge edge from a connected graph preserves connectedness. -/
lemma Connected.connected_delete_edge_of_not_isBridge (hG : G.Connected) {x y : V}
(h : ¬ G.IsBridge s(x, y)) : (G.deleteEdges {s(x, y)}).Connected := by
classical
simp only [isBridge_iff, not_and, not_not] at h
obtain hxy | hxy := em' <| G.Adj x y
· rwa [deleteEdges, Disjoint.sdiff_eq_left (by simpa)]
refine (connected_iff_exists_forall_reachable _).2 ⟨x, fun w ↦ ?_⟩
obtain ⟨P, hP⟩ := hG.exists_isPath w x
obtain heP | heP := em' <| s(x, y) ∈ P.edges
· exact ⟨(P.toDeleteEdges {s(x, y)} (by aesop)).reverse⟩
have hyP := P.snd_mem_support_of_mem_edges heP
let P₁ := P.takeUntil y hyP
have hxP₁ := Walk.endpoint_notMem_support_takeUntil hP hyP hxy.ne
have heP₁ : s(x, y) ∉ P₁.edges := fun h ↦ hxP₁ <| P₁.fst_mem_support_of_mem_edges h
exact (h hxy).trans (Reachable.symm ⟨P₁.toDeleteEdges {s(x, y)} (by aesop)⟩)
/-- If `e` is an adge in `G` and is a bridge in a larger graph `G'`, then it's a bridge in `G`. -/
theorem IsBridge.anti_of_mem_edgeSet {G' : SimpleGraph V} {e : Sym2 V} (hle : G ≤ G')
(h : e ∈ G.edgeSet) (h' : G'.IsBridge e) : G.IsBridge e :=
isBridge_iff_mem_and_forall_cycle_notMem.mpr ⟨h, fun _ p hp hpe ↦
isBridge_iff_mem_and_forall_cycle_notMem.mp h' |>.right
(p.mapLe hle) (Walk.IsCycle.mapLe hle hp) (p.edges_mapLe_eq_edges hle ▸ hpe)⟩
end BridgeEdges
/-!
### 2-reachability
In this section, we prove results about 2-connected components of a graph, but without naming them.
#### TODO
Should we explicitly have
```
def IsEdgeReachable (k : ℕ) (u v : V) : Prop :=
∀ ⦃s : Set (Sym2 V)⦄, s.encard < k → (G.deleteEdges s).Reachable u v
```
? `G.IsEdgeReachable 2 u v` would then be equivalent to the less idiomatic condition
`∃ x, ¬ (G.deleteEdges {s(x, y)}).Reachable u y` we use below.
See https://github.com/leanprover-community/mathlib4/issues/31691.
-/
namespace Walk
variable {u v x y : V} {w : G.Walk u v}
/-- A walk between two vertices separated by a set of edges must go through one of those edges. -/
lemma exists_mem_edges_of_not_reachable_deleteEdges (w : G.Walk u v) {s : Set (Sym2 V)}
(huv : ¬ (G.deleteEdges s).Reachable u v) : ∃ e ∈ s, e ∈ w.edges := by
contrapose! huv; exact ⟨w.toDeleteEdges _ fun _ ↦ imp_not_comm.1 <| huv _⟩
/-- A walk between two vertices separated by an edge must go through that edge. -/
lemma mem_edges_of_not_reachable_deleteEdges (w : G.Walk u v) {e : Sym2 V}
(huv : ¬ (G.deleteEdges {e}).Reachable u v) : e ∈ w.edges := by
simpa using w.exists_mem_edges_of_not_reachable_deleteEdges huv
/-- A trail doesn't go through an edge that disconnects one of its endpoints from the endpoints of
the trail. -/
lemma IsTrail.not_mem_edges_of_not_reachable (hw : w.IsTrail)
(huy : ¬ (G.deleteEdges {s(x, y)}).Reachable u y)
(hvy : ¬ (G.deleteEdges {s(x, y)}).Reachable v y) : s(x, y) ∉ w.edges := by
classical
exact fun hxy ↦ hw.disjoint_edges_takeUntil_dropUntil (w.snd_mem_support_of_mem_edges hxy)
((w.takeUntil y _).mem_edges_of_not_reachable_deleteEdges huy)
(by simpa using (w.dropUntil y _).reverse.mem_edges_of_not_reachable_deleteEdges hvy)
/-- A trail doesn't go through a vertex that is disconnected from its endpoints by an edge. -/
lemma IsTrail.not_mem_support_of_not_reachable (hw : w.IsTrail)
(huy : ¬ (G.deleteEdges {s(x, y)}).Reachable u y)
(hvy : ¬ (G.deleteEdges {s(x, y)}).Reachable v y) : y ∉ w.support := by
classical
exact fun hy ↦ hw.not_mem_edges_of_not_reachable huy hvy <| w.edges_takeUntil_subset hy <|
mem_edges_of_not_reachable_deleteEdges (w.takeUntil y hy) huy
/-- A trail doesn't go through any leaf vertex, except possibly at its endpoints. -/
lemma IsTrail.not_mem_support_of_subsingleton_neighborSet (hw : w.IsTrail) (hxu : x ≠ u)
(hxv : x ≠ v) (hx : (G.neighborSet x).Subsingleton) : x ∉ w.support := by
rintro hxw
obtain ⟨y, -, hxy⟩ := adj_of_mem_walk_support w (by rintro ⟨⟩; simp_all) hxw
refine hw.not_mem_support_of_not_reachable (x := y) ?_ ?_ hxw <;>
· rintro ⟨p⟩
obtain ⟨hx₂, -, hy₂⟩ : G.Adj x p.penultimate ∧ _ ∧ ¬p.penultimate = y := by
simpa using p.reverse.adj_snd (not_nil_of_ne ‹_›)
exact hy₂ <| hx hx₂ hxy
end Walk
/-- Removing leaves from a connected graph keeps it connected. -/
lemma Preconnected.induce_of_degree_eq_one (hG : G.Preconnected) {s : Set V}
(hs : ∀ v ∉ s, (G.neighborSet v).Subsingleton) : (G.induce s).Preconnected := by
rintro ⟨u, hu⟩ ⟨v, hv⟩
obtain ⟨p, hp⟩ := hG.exists_isPath u v
constructor
convert p.induce s _
rintro w hwp
by_contra hws
exact hp.not_mem_support_of_subsingleton_neighborSet (by grind) (by grind) (hs _ hws) hwp
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Connectivity/Subgraph.lean | import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected
import Mathlib.Data.Set.Card
/-!
# Connectivity of subgraphs and induced graphs
## Main definitions
* `SimpleGraph.Subgraph.Preconnected` and `SimpleGraph.Subgraph.Connected` give subgraphs
connectivity predicates via `SimpleGraph.subgraph.coe`.
-/
namespace SimpleGraph
universe u v
variable {V : Type u} {V' : Type v} {G : SimpleGraph V} {G' : SimpleGraph V'}
namespace Subgraph
/-- A subgraph is preconnected if it is preconnected when coerced to be a simple graph.
Note: This is a structure to make it so one can be precise about how dot notation resolves. -/
protected structure Preconnected (H : G.Subgraph) : Prop where
protected coe : H.coe.Preconnected
instance {H : G.Subgraph} : Coe H.Preconnected H.coe.Preconnected := ⟨Preconnected.coe⟩
instance {H : G.Subgraph} : CoeFun H.Preconnected (fun _ => ∀ u v : H.verts, H.coe.Reachable u v) :=
⟨fun h => h.coe⟩
protected lemma preconnected_iff {H : G.Subgraph} :
H.Preconnected ↔ H.coe.Preconnected := ⟨fun ⟨h⟩ => h, .mk⟩
/-- A subgraph is connected if it is connected when coerced to be a simple graph.
Note: This is a structure to make it so one can be precise about how dot notation resolves. -/
protected structure Connected (H : G.Subgraph) : Prop where
protected coe : H.coe.Connected
instance {H : G.Subgraph} : Coe H.Connected H.coe.Connected := ⟨Connected.coe⟩
instance {H : G.Subgraph} : CoeFun H.Connected (fun _ => ∀ u v : H.verts, H.coe.Reachable u v) :=
⟨fun h => h.coe⟩
protected lemma connected_iff' {H : G.Subgraph} :
H.Connected ↔ H.coe.Connected := ⟨fun ⟨h⟩ => h, .mk⟩
protected lemma connected_iff {H : G.Subgraph} :
H.Connected ↔ H.Preconnected ∧ H.verts.Nonempty := by
rw [H.connected_iff', connected_iff, H.preconnected_iff, Set.nonempty_coe_sort]
protected lemma Connected.preconnected {H : G.Subgraph} (h : H.Connected) : H.Preconnected := by
rw [H.connected_iff] at h; exact h.1
protected lemma Connected.nonempty {H : G.Subgraph} (h : H.Connected) : H.verts.Nonempty := by
rw [H.connected_iff] at h; exact h.2
theorem singletonSubgraph_connected {v : V} : (G.singletonSubgraph v).Connected := by
refine ⟨⟨?_⟩⟩
rintro ⟨a, ha⟩ ⟨b, hb⟩
simp only [singletonSubgraph_verts, Set.mem_singleton_iff] at ha hb
subst_vars
rfl
@[simp]
theorem subgraphOfAdj_connected {v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).Connected := by
refine ⟨⟨?_⟩⟩
rintro ⟨a, ha⟩ ⟨b, hb⟩
simp only [subgraphOfAdj_verts, Set.mem_insert_iff, Set.mem_singleton_iff] at ha hb
obtain rfl | rfl := ha <;> obtain rfl | rfl := hb <;>
first | rfl | (apply Adj.reachable; simp)
lemma top_induce_pair_connected_of_adj {u v : V} (huv : G.Adj u v) :
((⊤ : G.Subgraph).induce {u, v}).Connected := by
rw [← subgraphOfAdj_eq_induce huv]
exact subgraphOfAdj_connected huv
@[mono]
protected lemma Connected.mono {H H' : G.Subgraph} (hle : H ≤ H') (hv : H.verts = H'.verts)
(h : H.Connected) : H'.Connected := by
rw [← Subgraph.copy_eq H' H.verts hv H'.Adj rfl]
refine ⟨h.coe.mono ?_⟩
rintro ⟨v, hv⟩ ⟨w, hw⟩ hvw
exact hle.2 hvw
protected lemma Connected.mono' {H H' : G.Subgraph}
(hle : ∀ v w, H.Adj v w → H'.Adj v w) (hv : H.verts = H'.verts)
(h : H.Connected) : H'.Connected := by
exact h.mono ⟨hv.le, hle⟩ hv
lemma connected_sup {H K : G.Subgraph}
(hH : H.Preconnected) (hK : K.Preconnected) (hn : (H ⊓ K).verts.Nonempty) :
(H ⊔ K).Connected := by
rw [Subgraph.connected_iff', connected_iff_exists_forall_reachable]
obtain ⟨u, hu, hu'⟩ := hn
exists ⟨u, Or.inl hu⟩
rintro ⟨v, (hv|hv)⟩
· exact Reachable.map (Subgraph.inclusion (le_sup_left : H ≤ H ⊔ K)) (hH ⟨u, hu⟩ ⟨v, hv⟩)
· exact Reachable.map (Subgraph.inclusion (le_sup_right : K ≤ H ⊔ K)) (hK ⟨u, hu'⟩ ⟨v, hv⟩)
@[deprecated Subgraph.connected_sup (since := "2025-11-05")]
protected lemma Connected.sup {H K : G.Subgraph}
(hH : H.Connected) (hK : K.Connected) (hn : (H ⊓ K).verts.Nonempty) :
(H ⊔ K).Connected :=
Subgraph.connected_sup hH.preconnected hK.preconnected hn
/--
This lemma establishes a condition under which a subgraph is the same as a connected component.
Note the asymmetry in the hypothesis `h`: `v` is in `H.verts`, but `w` is not required to be.
-/
lemma Connected.exists_verts_eq_connectedComponentSupp {H : Subgraph G}
(hc : H.Connected) (h : ∀ v ∈ H.verts, ∀ w, G.Adj v w → H.Adj v w) :
∃ c : G.ConnectedComponent, H.verts = c.supp := by
rw [SimpleGraph.ConnectedComponent.exists]
obtain ⟨v, hv⟩ := hc.nonempty
use v
ext w
simp only [ConnectedComponent.mem_supp_iff, ConnectedComponent.eq]
exact ⟨fun hw ↦ by simpa using (hc ⟨w, hw⟩ ⟨v, hv⟩).map H.hom,
fun a ↦ a.symm.mem_subgraphVerts h hv⟩
end Subgraph
/-! ### Walks as subgraphs -/
namespace Walk
variable {u v w : V}
/-- The subgraph consisting of the vertices and edges of the walk. -/
@[simp]
protected def toSubgraph {u v : V} : G.Walk u v → G.Subgraph
| nil => G.singletonSubgraph u
| cons h p => G.subgraphOfAdj h ⊔ p.toSubgraph
theorem toSubgraph_cons_nil_eq_subgraphOfAdj (h : G.Adj u v) :
(cons h nil).toSubgraph = G.subgraphOfAdj h := by simp
theorem mem_verts_toSubgraph (p : G.Walk u v) : w ∈ p.toSubgraph.verts ↔ w ∈ p.support := by
induction p with
| nil => simp
| cons h p' ih =>
rename_i x y z
have : w = y ∨ w ∈ p'.support ↔ w ∈ p'.support :=
⟨by rintro (rfl | h) <;> simp [*], by simp +contextual⟩
simp [ih, or_assoc, this]
lemma not_nil_of_adj_toSubgraph {u v} {x : V} {p : G.Walk u v} (hadj : p.toSubgraph.Adj w x) :
¬p.Nil := by
cases p <;> simp_all
lemma start_mem_verts_toSubgraph (p : G.Walk u v) : u ∈ p.toSubgraph.verts := by
simp [mem_verts_toSubgraph]
lemma end_mem_verts_toSubgraph (p : G.Walk u v) : v ∈ p.toSubgraph.verts := by
simp [mem_verts_toSubgraph]
@[simp]
theorem verts_toSubgraph (p : G.Walk u v) : p.toSubgraph.verts = { w | w ∈ p.support } :=
Set.ext fun _ => p.mem_verts_toSubgraph
theorem mem_edges_toSubgraph (p : G.Walk u v) {e : Sym2 V} :
e ∈ p.toSubgraph.edgeSet ↔ e ∈ p.edges := by induction p <;> simp [*]
@[simp]
theorem edgeSet_toSubgraph (p : G.Walk u v) : p.toSubgraph.edgeSet = { e | e ∈ p.edges } :=
Set.ext fun _ => p.mem_edges_toSubgraph
@[simp]
theorem toSubgraph_append (p : G.Walk u v) (q : G.Walk v w) :
(p.append q).toSubgraph = p.toSubgraph ⊔ q.toSubgraph := by induction p <;> simp [*, sup_assoc]
@[simp]
theorem toSubgraph_reverse (p : G.Walk u v) : p.reverse.toSubgraph = p.toSubgraph := by
induction p with
| nil => simp
| cons _ _ _ =>
simp only [*, Walk.toSubgraph, reverse_cons, toSubgraph_append, subgraphOfAdj_symm]
rw [sup_comm]
congr
ext <;> simp [-Set.bot_eq_empty]
@[simp]
theorem toSubgraph_rotate [DecidableEq V] (c : G.Walk v v) (h : u ∈ c.support) :
(c.rotate h).toSubgraph = c.toSubgraph := by
rw [rotate, toSubgraph_append, sup_comm, ← toSubgraph_append, take_spec]
@[simp]
theorem toSubgraph_map (f : G →g G') (p : G.Walk u v) :
(p.map f).toSubgraph = p.toSubgraph.map f := by induction p <;> simp [*, Subgraph.map_sup]
lemma adj_toSubgraph_mapLe {G' : SimpleGraph V} {w x : V} {p : G.Walk u v} (h : G ≤ G') :
(p.mapLe h).toSubgraph.Adj w x ↔ p.toSubgraph.Adj w x := by
simp
@[simp]
theorem finite_neighborSet_toSubgraph (p : G.Walk u v) : (p.toSubgraph.neighborSet w).Finite := by
induction p with
| nil =>
rw [Walk.toSubgraph, neighborSet_singletonSubgraph]
apply Set.toFinite
| cons ha _ ih =>
rw [Walk.toSubgraph, Subgraph.neighborSet_sup]
refine Set.Finite.union ?_ ih
refine Set.Finite.subset ?_ (neighborSet_subgraphOfAdj_subset ha)
apply Set.toFinite
lemma toSubgraph_le_induce_support (p : G.Walk u v) :
p.toSubgraph ≤ (⊤ : G.Subgraph).induce {v | v ∈ p.support} := by
convert Subgraph.le_induce_top_verts
exact p.verts_toSubgraph.symm
theorem toSubgraph_adj_getVert {u v} (w : G.Walk u v) {i : ℕ} (hi : i < w.length) :
w.toSubgraph.Adj (w.getVert i) (w.getVert (i + 1)) := by
induction w generalizing i with
| nil => cases hi
| cons hxy i' ih =>
cases i
· simp only [Walk.toSubgraph, Walk.getVert_zero, zero_add, getVert_cons_succ, Subgraph.sup_adj,
subgraphOfAdj_adj, true_or]
· simp only [Walk.toSubgraph, getVert_cons_succ, Subgraph.sup_adj, subgraphOfAdj_adj, Sym2.eq,
Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk]
right
exact ih (Nat.succ_lt_succ_iff.mp hi)
theorem toSubgraph_adj_snd {u v} (w : G.Walk u v) (h : ¬ w.Nil) : w.toSubgraph.Adj u w.snd := by
simpa using w.toSubgraph_adj_getVert (not_nil_iff_lt_length.mp h)
theorem toSubgraph_adj_penultimate {u v} (w : G.Walk u v) (h : ¬ w.Nil) :
w.toSubgraph.Adj w.penultimate v := by
rw [not_nil_iff_lt_length] at h
simpa [show w.length - 1 + 1 = w.length from by cutsat]
using w.toSubgraph_adj_getVert (by cutsat : w.length - 1 < w.length)
theorem toSubgraph_adj_iff {u v u' v'} (w : G.Walk u v) :
w.toSubgraph.Adj u' v' ↔ ∃ i, s(w.getVert i, w.getVert (i + 1)) =
s(u', v') ∧ i < w.length := by
constructor
· intro hadj
unfold Walk.toSubgraph at hadj
match w with
| .nil =>
simp only [singletonSubgraph_adj, Pi.bot_apply, Prop.bot_eq_false] at hadj
| .cons h p =>
simp only [Subgraph.sup_adj, subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq,
Prod.swap_prod_mk] at hadj
cases hadj with
| inl hl =>
use 0
simp only [Walk.getVert_zero, zero_add, getVert_cons_succ]
refine ⟨?_, by simp only [length_cons, Nat.zero_lt_succ]⟩
exact Sym2.eq_iff.mpr hl
| inr hr =>
obtain ⟨i, hi⟩ := (toSubgraph_adj_iff _).mp hr
use i + 1
simp only [getVert_cons_succ]
constructor
· exact hi.1
· simp only [Walk.length_cons, Nat.add_lt_add_right hi.2 1]
· rintro ⟨i, hi⟩
rw [← Subgraph.mem_edgeSet, ← hi.1, Subgraph.mem_edgeSet]
exact toSubgraph_adj_getVert _ hi.2
lemma mem_support_of_adj_toSubgraph {u v u' v' : V} {p : G.Walk u v} (hp : p.toSubgraph.Adj u' v') :
u' ∈ p.support := p.mem_verts_toSubgraph.mp (p.toSubgraph.edge_vert hp)
namespace IsPath
lemma neighborSet_toSubgraph_startpoint {u v} {p : G.Walk u v}
(hp : p.IsPath) (hnp : ¬ p.Nil) : p.toSubgraph.neighborSet u = {p.snd} := by
have hadj1 := p.toSubgraph_adj_snd hnp
ext v
simp_all only [Subgraph.mem_neighborSet, Set.mem_singleton_iff,
SimpleGraph.Walk.toSubgraph_adj_iff, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk]
refine ⟨?_, by simp_all⟩
rintro ⟨i, hl | hr⟩
· have : i = 0 := by
apply hp.getVert_injOn (by rw [Set.mem_setOf]; cutsat) (by rw [Set.mem_setOf]; cutsat)
simp_all
simp_all
· have : i + 1 = 0 := by
apply hp.getVert_injOn (by rw [Set.mem_setOf]; cutsat) (by rw [Set.mem_setOf]; cutsat)
simp_all
contradiction
lemma neighborSet_toSubgraph_endpoint {u v} {p : G.Walk u v}
(hp : p.IsPath) (hnp : ¬ p.Nil) : p.toSubgraph.neighborSet v = {p.penultimate} := by
simpa using IsPath.neighborSet_toSubgraph_startpoint hp.reverse
(by rw [Walk.not_nil_iff_lt_length, Walk.length_reverse]; exact
Walk.not_nil_iff_lt_length.mp hnp)
lemma neighborSet_toSubgraph_internal {u} {i : ℕ} {p : G.Walk u v} (hp : p.IsPath)
(h : i ≠ 0) (h' : i < p.length) :
p.toSubgraph.neighborSet (p.getVert i) = {p.getVert (i - 1), p.getVert (i + 1)} := by
have hadj1 := ((show i - 1 + 1 = i from by cutsat) ▸
p.toSubgraph_adj_getVert (by cutsat : (i - 1) < p.length)).symm
ext v
simp_all only [ne_eq, Subgraph.mem_neighborSet, Set.mem_insert_iff, Set.mem_singleton_iff,
SimpleGraph.Walk.toSubgraph_adj_iff, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq,
Prod.swap_prod_mk]
refine ⟨?_, by aesop⟩
rintro ⟨i', ⟨hl, _⟩ | ⟨_, hl⟩⟩ <;>
apply hp.getVert_injOn (by rw [Set.mem_setOf_eq]; cutsat)
(by rw [Set.mem_setOf_eq]; cutsat) at hl <;> aesop
lemma ncard_neighborSet_toSubgraph_internal_eq_two {u} {i : ℕ} {p : G.Walk u v} (hp : p.IsPath)
(h : i ≠ 0) (h' : i < p.length) :
(p.toSubgraph.neighborSet (p.getVert i)).ncard = 2 := by
rw [hp.neighborSet_toSubgraph_internal h h']
have : p.getVert (i - 1) ≠ p.getVert (i + 1) := by
intro h
have := hp.getVert_injOn (by rw [Set.mem_setOf_eq]; cutsat) (by rw [Set.mem_setOf_eq]; cutsat) h
omega
simp_all
lemma snd_of_toSubgraph_adj {u v v'} {p : G.Walk u v} (hp : p.IsPath)
(hadj : p.toSubgraph.Adj u v') : p.snd = v' := by
have ⟨i, hi⟩ := p.toSubgraph_adj_iff.mp hadj
simp only [Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk] at hi
rcases hi.1 with ⟨hl1, rfl⟩|⟨hr1, hr2⟩
· have : i = 0 := by
apply hp.getVert_injOn (by rw [Set.mem_setOf]; cutsat) (by rw [Set.mem_setOf]; cutsat)
rw [p.getVert_zero, hl1]
simp [this]
· have : i + 1 = 0 := by
apply hp.getVert_injOn (by rw [Set.mem_setOf]; cutsat) (by rw [Set.mem_setOf]; cutsat)
rw [p.getVert_zero, hr2]
contradiction
end IsPath
namespace IsCycle
lemma neighborSet_toSubgraph_endpoint {u} {p : G.Walk u u} (hpc : p.IsCycle) :
p.toSubgraph.neighborSet u = {p.snd, p.penultimate} := by
have hadj1 := p.toSubgraph_adj_snd hpc.not_nil
have hadj2 := (p.toSubgraph_adj_penultimate hpc.not_nil).symm
ext v
simp_all only [Subgraph.mem_neighborSet, Set.mem_insert_iff, Set.mem_singleton_iff,
SimpleGraph.Walk.toSubgraph_adj_iff, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk]
refine ⟨?_, by aesop⟩
rintro ⟨i, hl | hr⟩
· rw [hpc.getVert_endpoint_iff (by cutsat)] at hl
cases hl.1 <;> aesop
· rcases (hpc.getVert_endpoint_iff (by cutsat)).mp hr.2 with h1 | h2
· contradiction
· simp only [penultimate, ← h2, add_tsub_cancel_right]
simp_all
lemma neighborSet_toSubgraph_internal {u} {i : ℕ} {p : G.Walk u u} (hpc : p.IsCycle)
(h : i ≠ 0) (h' : i < p.length) :
p.toSubgraph.neighborSet (p.getVert i) = {p.getVert (i - 1), p.getVert (i + 1)} := by
have hadj1 := ((show i - 1 + 1 = i from by cutsat) ▸
p.toSubgraph_adj_getVert (by cutsat : (i - 1) < p.length)).symm
ext v
simp_all only [ne_eq, Subgraph.mem_neighborSet, Set.mem_insert_iff, Set.mem_singleton_iff,
SimpleGraph.Walk.toSubgraph_adj_iff, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq,
Prod.swap_prod_mk]
refine ⟨?_, by aesop⟩
rintro ⟨i', ⟨hl1, hl2⟩ | ⟨hr1, hr2⟩⟩
· apply hpc.getVert_injOn' (by rw [Set.mem_setOf_eq]; cutsat)
(by rw [Set.mem_setOf_eq]; cutsat) at hl1
simp_all
· apply hpc.getVert_injOn (by rw [Set.mem_setOf_eq]; cutsat)
(by rw [Set.mem_setOf_eq]; cutsat) at hr2
aesop
lemma ncard_neighborSet_toSubgraph_eq_two {u v} {p : G.Walk u u} (hpc : p.IsCycle)
(h : v ∈ p.support) : (p.toSubgraph.neighborSet v).ncard = 2 := by
simp only [SimpleGraph.Walk.mem_support_iff_exists_getVert] at h ⊢
obtain ⟨i, hi⟩ := h
by_cases! he : i = 0 ∨ i = p.length
· have huv : u = v := by aesop
rw [← huv, hpc.neighborSet_toSubgraph_endpoint]
exact Set.ncard_pair hpc.snd_ne_penultimate
rw [← hi.1, hpc.neighborSet_toSubgraph_internal he.1 (by cutsat)]
exact Set.ncard_pair (hpc.getVert_sub_one_ne_getVert_add_one (by cutsat))
lemma exists_isCycle_snd_verts_eq {p : G.Walk v v} (h : p.IsCycle) (hadj : p.toSubgraph.Adj v w) :
∃ (p' : G.Walk v v), p'.IsCycle ∧ p'.snd = w ∧ p'.toSubgraph.verts = p.toSubgraph.verts := by
have : w ∈ p.toSubgraph.neighborSet v := hadj
rw [h.neighborSet_toSubgraph_endpoint] at this
simp only [Set.mem_insert_iff, Set.mem_singleton_iff] at this
obtain hl | hr := this
· exact ⟨p, ⟨h, hl.symm, rfl⟩⟩
· use p.reverse
rw [penultimate, ← getVert_reverse] at hr
exact ⟨h.reverse, hr.symm, by rw [toSubgraph_reverse _]⟩
end IsCycle
open Finset
variable [DecidableEq V] {u v : V} {p : G.Walk u v}
/-- This lemma states that given some finite set of vertices, of which at least one is in the
support of a given walk, one of them is the first to be encountered. This consequence is encoded
as the set of vertices, restricted to those in the support, except for the first, being empty.
You could interpret this as being `takeUntilSet`, but defining this is slightly involved due to
not knowing what the final vertex is. This could be done by defining a function to obtain the
first encountered vertex and then use that to define `takeUntilSet`. That direction could be
worthwhile if this concept is used more widely. -/
lemma exists_mem_support_mem_erase_mem_support_takeUntil_eq_empty (s : Finset V)
(h : {x ∈ s | x ∈ p.support}.Nonempty) :
∃ x ∈ s, ∃ hx : x ∈ p.support, {t ∈ s.erase x | t ∈ (p.takeUntil x hx).support} = ∅ := by
simp only [← Finset.subset_empty]
induction hp : p.length + #s using Nat.strong_induction_on generalizing s v with | _ n ih
simp only [Finset.Nonempty, mem_filter] at h
obtain ⟨x, hxs, hx⟩ := h
obtain h | h := Finset.eq_empty_or_nonempty {t ∈ s.erase x | t ∈ (p.takeUntil x hx).support}
· use x, hxs, hx, h.le
have : (p.takeUntil x hx).length + #(s.erase x) < n := by
rw [← card_erase_add_one hxs] at hp
have := p.length_takeUntil_le hx
omega
obtain ⟨y, hys, hyp, h⟩ := ih _ this (s.erase x) h rfl
use y, mem_of_mem_erase hys, support_takeUntil_subset p hx hyp
rwa [takeUntil_takeUntil, erase_right_comm, filter_erase, erase_eq_of_notMem] at h
simp only [mem_filter, mem_erase, ne_eq, not_and, and_imp]
rintro hxy -
exact notMem_support_takeUntil_support_takeUntil_subset (Ne.symm hxy) hx hyp
lemma exists_mem_support_forall_mem_support_imp_eq (s : Finset V)
(h : {x ∈ s | x ∈ p.support}.Nonempty) :
∃ x ∈ s, ∃ (hx : x ∈ p.support),
∀ t ∈ s, t ∈ (p.takeUntil x hx).support → t = x := by
obtain ⟨x, hxs, hx, h⟩ := p.exists_mem_support_mem_erase_mem_support_takeUntil_eq_empty s h
use x, hxs, hx
suffices {t ∈ s | t ∈ (p.takeUntil x hx).support} ⊆ {x} by simpa [Finset.subset_iff] using this
rwa [Finset.filter_erase, ← Finset.subset_empty, ← Finset.subset_insert_iff,
LawfulSingleton.insert_empty_eq] at h
end Walk
namespace Subgraph
lemma _root_.SimpleGraph.Walk.toSubgraph_connected {u v : V} (p : G.Walk u v) :
p.toSubgraph.Connected := by
induction p with
| nil => apply singletonSubgraph_connected
| @cons _ w _ h p ih =>
apply Subgraph.connected_sup (subgraphOfAdj_connected h).preconnected ih.preconnected
exists w
simp
lemma induce_union_connected {H : G.Subgraph} {s t : Set V}
(sconn : (H.induce s).Preconnected) (tconn : (H.induce t).Preconnected)
(sintert : (s ⊓ t).Nonempty) :
(H.induce (s ∪ t)).Connected :=
(Subgraph.connected_sup sconn tconn sintert).mono le_induce_union <| by simp
lemma connected_induce_top_sup {H K : G.Subgraph} (Hconn : H.Preconnected) (Kconn : K.Preconnected)
{u v : V} (uH : u ∈ H.verts) (vK : v ∈ K.verts) (huv : G.Adj u v) :
((⊤ : G.Subgraph).induce {u, v} ⊔ H ⊔ K).Connected := by
refine Subgraph.connected_sup (Subgraph.connected_sup ?_ Hconn ?_).preconnected Kconn ?_
· exact (top_induce_pair_connected_of_adj huv).preconnected
· exact ⟨u, by simp [uH]⟩
· exact ⟨v, by simp [vK]⟩
@[deprecated connected_induce_top_sup (since := "2025-11-05")]
lemma Connected.adj_union {H K : G.Subgraph}
(Hconn : H.Connected) (Kconn : K.Connected) {u v : V} (uH : u ∈ H.verts) (vK : v ∈ K.verts)
(huv : G.Adj u v) :
((⊤ : G.Subgraph).induce {u, v} ⊔ H ⊔ K).Connected :=
connected_induce_top_sup Hconn.preconnected Kconn.preconnected uH vK huv
lemma preconnected_iff_forall_exists_walk_subgraph (H : G.Subgraph) :
H.Preconnected ↔ ∀ {u v}, u ∈ H.verts → v ∈ H.verts → ∃ p : G.Walk u v, p.toSubgraph ≤ H := by
constructor
· intro hc u v hu hv
refine (hc ⟨_, hu⟩ ⟨_, hv⟩).elim fun p => ?_
exists p.map (Subgraph.hom _)
simp [coeSubgraph_le]
· intro hw
rw [Subgraph.preconnected_iff]
rintro ⟨u, hu⟩ ⟨v, hv⟩
obtain ⟨p, h⟩ := hw hu hv
exact Reachable.map (Subgraph.inclusion h)
(p.toSubgraph_connected ⟨_, p.start_mem_verts_toSubgraph⟩ ⟨_, p.end_mem_verts_toSubgraph⟩)
lemma connected_iff_forall_exists_walk_subgraph (H : G.Subgraph) :
H.Connected ↔
H.verts.Nonempty ∧
∀ {u v}, u ∈ H.verts → v ∈ H.verts → ∃ p : G.Walk u v, p.toSubgraph ≤ H := by
rw [H.connected_iff, preconnected_iff_forall_exists_walk_subgraph, and_comm]
end Subgraph
section induced_subgraphs
lemma preconnected_induce_iff {s : Set V} :
(G.induce s).Preconnected ↔ ((⊤ : G.Subgraph).induce s).Preconnected := by
rw [induce_eq_coe_induce_top, ← Subgraph.preconnected_iff]
lemma connected_induce_iff {s : Set V} :
(G.induce s).Connected ↔ ((⊤ : G.Subgraph).induce s).Connected := by
rw [induce_eq_coe_induce_top, ← Subgraph.connected_iff']
lemma induce_union_connected {s t : Set V}
(sconn : (G.induce s).Preconnected) (tconn : (G.induce t).Preconnected)
(sintert : (s ∩ t).Nonempty) :
(G.induce (s ∪ t)).Connected := by
rw [connected_induce_iff]
rw [preconnected_induce_iff] at sconn tconn
exact Subgraph.induce_union_connected sconn tconn sintert
lemma induce_pair_connected_of_adj {u v : V} (huv : G.Adj u v) :
(G.induce {u, v}).Connected := by
rw [connected_induce_iff]
exact Subgraph.top_induce_pair_connected_of_adj huv
lemma Subgraph.Connected.induce_verts {H : G.Subgraph} (h : H.Connected) :
(G.induce H.verts).Connected := by
rw [connected_induce_iff]
exact h.mono le_induce_top_verts (by exact rfl)
lemma Walk.connected_induce_support {u v : V} (p : G.Walk u v) :
(G.induce {v | v ∈ p.support}).Connected := by
rw [← p.verts_toSubgraph]
exact p.toSubgraph_connected.induce_verts
lemma connected_induce_union {v w : V} {s t : Set V}
(sconn : (G.induce s).Preconnected) (tconn : (G.induce t).Preconnected)
(hv : v ∈ s) (hw : w ∈ t) (ha : G.Adj v w) :
(G.induce (s ∪ t)).Connected := by
rw [connected_induce_iff]
rw [preconnected_induce_iff] at sconn tconn
apply (Subgraph.connected_induce_top_sup sconn tconn hv hw ha).mono
· simp only [sup_le_iff, Subgraph.le_induce_union_left,
Subgraph.le_induce_union_right, and_true, ← Subgraph.subgraphOfAdj_eq_induce ha]
apply subgraphOfAdj_le_of_adj
simp [hv, hw, ha]
· simp only [Subgraph.verts_sup, Subgraph.induce_verts]
rw [Set.union_assoc]
simp [Set.insert_subset_iff, Set.singleton_subset_iff, hv, hw]
@[deprecated connected_induce_union (since := "2025-11-05")]
lemma induce_connected_adj_union {v w : V} {s t : Set V}
(sconn : (G.induce s).Connected) (tconn : (G.induce t).Connected)
(hv : v ∈ s) (hw : w ∈ t) (ha : G.Adj v w) :
(G.induce (s ∪ t)).Connected :=
connected_induce_union sconn.preconnected tconn.preconnected hv hw ha
lemma induce_connected_of_patches {s : Set V} (u : V) (hu : u ∈ s)
(patches : ∀ {v}, v ∈ s → ∃ s' ⊆ s, ∃ (hu' : u ∈ s') (hv' : v ∈ s'),
(G.induce s').Reachable ⟨u, hu'⟩ ⟨v, hv'⟩) : (G.induce s).Connected := by
rw [connected_iff_exists_forall_reachable]
refine ⟨⟨u, hu⟩, ?_⟩
rintro ⟨v, hv⟩
obtain ⟨sv, svs, hu', hv', uv⟩ := patches hv
exact uv.map (induceHomOfLE _ svs).toHom
lemma induce_sUnion_connected_of_pairwise_not_disjoint {S : Set (Set V)} (Sn : S.Nonempty)
(Snd : ∀ {s t}, s ∈ S → t ∈ S → (s ∩ t).Nonempty)
(Sc : ∀ {s}, s ∈ S → (G.induce s).Connected) :
(G.induce (⋃₀ S)).Connected := by
obtain ⟨s, sS⟩ := Sn
obtain ⟨v, vs⟩ := (Sc sS).nonempty
apply G.induce_connected_of_patches _ (Set.subset_sUnion_of_mem sS vs)
rintro w hw
simp only [Set.mem_sUnion] at hw
obtain ⟨t, tS, wt⟩ := hw
refine ⟨s ∪ t, Set.union_subset (Set.subset_sUnion_of_mem sS) (Set.subset_sUnion_of_mem tS),
Or.inl vs, Or.inr wt,
induce_union_connected (Sc sS).preconnected (Sc tS).preconnected (Snd sS tS) _ _⟩
lemma extend_finset_to_connected (Gpc : G.Preconnected) {t : Finset V} (tn : t.Nonempty) :
∃ (t' : Finset V), t ⊆ t' ∧ (G.induce (t' : Set V)).Connected := by
classical
obtain ⟨u, ut⟩ := tn
refine ⟨t.biUnion (fun v => (Gpc u v).some.support.toFinset), fun v vt => ?_, ?_⟩
· simp only [Finset.mem_biUnion, List.mem_toFinset]
exact ⟨v, vt, Walk.end_mem_support _⟩
· apply G.induce_connected_of_patches u
· simp only [Finset.coe_biUnion, Finset.mem_coe, List.coe_toFinset, Set.mem_iUnion,
Set.mem_setOf_eq, Walk.start_mem_support, exists_prop, and_true]
exact ⟨u, ut⟩
intro v hv
simp only [Finset.mem_coe, Finset.mem_biUnion, List.mem_toFinset] at hv
obtain ⟨w, wt, hw⟩ := hv
refine ⟨{x | x ∈ (Gpc u w).some.support}, ?_, ?_⟩
· simp only [Finset.coe_biUnion, Finset.mem_coe, List.coe_toFinset]
exact fun x xw => Set.mem_iUnion₂.mpr ⟨w, wt, xw⟩
· simp only [Set.mem_setOf_eq, Walk.start_mem_support, exists_true_left]
refine ⟨hw, Walk.connected_induce_support _ _ _⟩
end induced_subgraphs
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Triangle/Tripartite.lean | import Mathlib.Combinatorics.SimpleGraph.Triangle.Basic
/-!
# Construct a tripartite graph from its triangles
This file contains the construction of a simple graph on `α ⊕ β ⊕ γ` from a list of triangles
`(a, b, c)` (with `a` in the first component, `b` in the second, `c` in the third).
We call
* `t : Finset (α × β × γ)` the set of *triangle indices* (its elements are not triangles within the
graph but instead index them).
* *explicit* a triangle of the constructed graph coming from a triangle index.
* *accidental* a triangle of the constructed graph not coming from a triangle index.
The two important properties of this construction are:
* `SimpleGraph.TripartiteFromTriangles.ExplicitDisjoint`: Whether the explicit triangles are
edge-disjoint.
* `SimpleGraph.TripartiteFromTriangles.NoAccidental`: Whether all triangles are explicit.
This construction shows up unrelatedly twice in the theory of Roth numbers:
* The lower bound of the Ruzsa-Szemerédi problem: From a set `s` in a finite abelian group `G` of
odd order, we construct a tripartite graph on `G ⊕ G ⊕ G`. The triangle indices are
`(x, x + a, x + 2 * a)` for `x` any element and `a ∈ s`. The explicit triangles are always
edge-disjoint and there is no accidental triangle if `s` is 3AP-free.
* The proof of the corners theorem from the triangle removal lemma: For a set `s` in a finite
abelian group `G`, we construct a tripartite graph on `G ⊕ G ⊕ G`, whose vertices correspond to
the horizontal, vertical and diagonal lines in `G × G`. The explicit triangles are `(h, v, d)`
where `h`, `v`, `d` are horizontal, vertical, diagonal lines that intersect in an element of `s`.
The explicit triangles are always edge-disjoint and there is no accidental triangle if `s` is
corner-free.
-/
open Finset Function Sum3
variable {α β γ 𝕜 : Type*} [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜]
{t : Finset (α × β × γ)} {a a' : α} {b b' : β} {c c' : γ} {x : α × β × γ}
namespace SimpleGraph
namespace TripartiteFromTriangles
/-- The underlying relation of the tripartite-from-triangles graph.
Two vertices are related iff there exists a triangle index containing them both. -/
@[mk_iff] inductive Rel (t : Finset (α × β × γ)) : α ⊕ β ⊕ γ → α ⊕ β ⊕ γ → Prop
| in₀₁ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₀ a) (in₁ b)
| in₁₀ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₁ b) (in₀ a)
| in₀₂ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₀ a) (in₂ c)
| in₂₀ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₂ c) (in₀ a)
| in₁₂ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₁ b) (in₂ c)
| in₂₁ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₂ c) (in₁ b)
open Rel
lemma rel_irrefl : ∀ x, ¬ Rel t x x := fun _x hx ↦ nomatch hx
lemma rel_symm : Symmetric (Rel t) := fun x y h ↦ by cases h <;> constructor <;> assumption
/-- The tripartite-from-triangles graph. Two vertices are related iff there exists a triangle index
containing them both. -/
def graph (t : Finset (α × β × γ)) : SimpleGraph (α ⊕ β ⊕ γ) := ⟨Rel t, rel_symm, rel_irrefl⟩
namespace Graph
@[simp] lemma not_in₀₀ : ¬ (graph t).Adj (in₀ a) (in₀ a') := fun h ↦ nomatch h
@[simp] lemma not_in₁₁ : ¬ (graph t).Adj (in₁ b) (in₁ b') := fun h ↦ nomatch h
@[simp] lemma not_in₂₂ : ¬ (graph t).Adj (in₂ c) (in₂ c') := fun h ↦ nomatch h
@[simp] lemma in₀₁_iff : (graph t).Adj (in₀ a) (in₁ b) ↔ ∃ c, (a, b, c) ∈ t :=
⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₀₁ h⟩
@[simp] lemma in₁₀_iff : (graph t).Adj (in₁ b) (in₀ a) ↔ ∃ c, (a, b, c) ∈ t :=
⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₁₀ h⟩
@[simp] lemma in₀₂_iff : (graph t).Adj (in₀ a) (in₂ c) ↔ ∃ b, (a, b, c) ∈ t :=
⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₀₂ h⟩
@[simp] lemma in₂₀_iff : (graph t).Adj (in₂ c) (in₀ a) ↔ ∃ b, (a, b, c) ∈ t :=
⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₂₀ h⟩
@[simp] lemma in₁₂_iff : (graph t).Adj (in₁ b) (in₂ c) ↔ ∃ a, (a, b, c) ∈ t :=
⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₁₂ h⟩
@[simp] lemma in₂₁_iff : (graph t).Adj (in₂ c) (in₁ b) ↔ ∃ a, (a, b, c) ∈ t :=
⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₂₁ h⟩
lemma in₀₁_iff' :
(graph t).Adj (in₀ a) (in₁ b) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.1 = a ∧ x.2.1 = b where
mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩
mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption
lemma in₁₀_iff' :
(graph t).Adj (in₁ b) (in₀ a) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.2.1 = b ∧ x.1 = a where
mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩
mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption
lemma in₀₂_iff' :
(graph t).Adj (in₀ a) (in₂ c) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.1 = a ∧ x.2.2 = c where
mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩
mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption
lemma in₂₀_iff' :
(graph t).Adj (in₂ c) (in₀ a) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.2.2 = c ∧ x.1 = a where
mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩
mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption
lemma in₁₂_iff' :
(graph t).Adj (in₁ b) (in₂ c) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.2.1 = b ∧ x.2.2 = c where
mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩
mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption
lemma in₂₁_iff' :
(graph t).Adj (in₂ c) (in₁ b) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.2.2 = c ∧ x.2.1 = b where
mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩
mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption
end Graph
open Graph
/-- Predicate on the triangle indices for the explicit triangles to be edge-disjoint. -/
class ExplicitDisjoint (t : Finset (α × β × γ)) : Prop where
inj₀ : ∀ ⦃a b c a'⦄, (a, b, c) ∈ t → (a', b, c) ∈ t → a = a'
inj₁ : ∀ ⦃a b c b'⦄, (a, b, c) ∈ t → (a, b', c) ∈ t → b = b'
inj₂ : ∀ ⦃a b c c'⦄, (a, b, c) ∈ t → (a, b, c') ∈ t → c = c'
/-- Predicate on the triangle indices for there to be no accidental triangle.
Note that we cheat a bit, since the exact translation of this informal description would have
`(a', b', c') ∈ t` as a conclusion rather than `a = a' ∨ b = b' ∨ c = c'`. Those conditions are
equivalent when the explicit triangles are edge-disjoint (which is the case we care about). -/
class NoAccidental (t : Finset (α × β × γ)) : Prop where
eq_or_eq_or_eq : ∀ ⦃a a' b b' c c'⦄, (a', b, c) ∈ t → (a, b', c) ∈ t → (a, b, c') ∈ t →
a = a' ∨ b = b' ∨ c = c'
section DecidableEq
variable [DecidableEq α] [DecidableEq β] [DecidableEq γ]
instance graph.instDecidableRelAdj : DecidableRel (graph t).Adj
| in₀ _a, in₀ _a' => Decidable.isFalse not_in₀₀
| in₀ _a, in₁ _b' => decidable_of_iff' _ in₀₁_iff'
| in₀ _a, in₂ _c' => decidable_of_iff' _ in₀₂_iff'
| in₁ _b, in₀ _a' => decidable_of_iff' _ in₁₀_iff'
| in₁ _b, in₁ _b' => Decidable.isFalse not_in₁₁
| in₁ _b, in₂ _b' => decidable_of_iff' _ in₁₂_iff'
| in₂ _c, in₀ _a' => decidable_of_iff' _ in₂₀_iff'
| in₂ _c, in₁ _b' => decidable_of_iff' _ in₂₁_iff'
| in₂ _c, in₂ _b' => Decidable.isFalse not_in₂₂
/-- This lemma reorders the elements of a triangle in the tripartite graph. It turns a triangle
`{x, y, z}` into a triangle `{a, b, c}` where `a : α `, `b : β`, `c : γ`. -/
lemma graph_triple ⦃x y z⦄ :
(graph t).Adj x y → (graph t).Adj x z → (graph t).Adj y z → ∃ a b c,
({in₀ a, in₁ b, in₂ c} : Finset (α ⊕ β ⊕ γ)) = {x, y, z} ∧ (graph t).Adj (in₀ a) (in₁ b) ∧
(graph t).Adj (in₀ a) (in₂ c) ∧ (graph t).Adj (in₁ b) (in₂ c) := by
rintro (_ | _ | _) (_ | _ | _) (_ | _ | _) <;>
refine ⟨_, _, _, by ext; simp only [Finset.mem_insert, Finset.mem_singleton]; try tauto,
?_, ?_, ?_⟩ <;> constructor <;> assumption
/-- The map that turns a triangle index into an explicit triangle. -/
@[simps] def toTriangle : α × β × γ ↪ Finset (α ⊕ β ⊕ γ) where
toFun x := {in₀ x.1, in₁ x.2.1, in₂ x.2.2}
inj' := fun ⟨a, b, c⟩ ⟨a', b', c'⟩ ↦ by simpa only [Finset.Subset.antisymm_iff, Finset.subset_iff,
mem_insert, mem_singleton, forall_eq_or_imp, forall_eq, Prod.mk_inj, or_false, false_or,
in₀, in₁, in₂, Sum.inl.inj_iff, Sum.inr.inj_iff, reduceCtorEq] using And.left
lemma toTriangle_is3Clique (hx : x ∈ t) : (graph t).IsNClique 3 (toTriangle x) := by
simp only [toTriangle_apply, is3Clique_triple_iff, in₀₁_iff, in₀₂_iff, in₁₂_iff]
exact ⟨⟨_, hx⟩, ⟨_, hx⟩, _, hx⟩
lemma exists_mem_toTriangle {x y : α ⊕ β ⊕ γ} (hxy : (graph t).Adj x y) :
∃ z ∈ t, x ∈ toTriangle z ∧ y ∈ toTriangle z := by cases hxy <;> exact ⟨_, ‹_›, by simp⟩
nonrec lemma is3Clique_iff [NoAccidental t] {s : Finset (α ⊕ β ⊕ γ)} :
(graph t).IsNClique 3 s ↔ ∃ x, x ∈ t ∧ toTriangle x = s := by
refine ⟨fun h ↦ ?_, ?_⟩
· rw [is3Clique_iff] at h
obtain ⟨x, y, z, hxy, hxz, hyz, rfl⟩ := h
obtain ⟨a, b, c, habc, hab, hac, hbc⟩ := graph_triple hxy hxz hyz
refine ⟨(a, b, c), ?_, habc⟩
obtain ⟨c', hc'⟩ := in₀₁_iff.1 hab
obtain ⟨b', hb'⟩ := in₀₂_iff.1 hac
obtain ⟨a', ha'⟩ := in₁₂_iff.1 hbc
obtain rfl | rfl | rfl := NoAccidental.eq_or_eq_or_eq ha' hb' hc' <;> assumption
· rintro ⟨x, hx, rfl⟩
exact toTriangle_is3Clique hx
lemma toTriangle_surjOn [NoAccidental t] :
(t : Set (α × β × γ)).SurjOn toTriangle ((graph t).cliqueSet 3) := fun _ ↦ is3Clique_iff.1
variable (t)
lemma map_toTriangle_disjoint [ExplicitDisjoint t] :
(t.map toTriangle : Set (Finset (α ⊕ β ⊕ γ))).Pairwise
fun x y ↦ (x ∩ y : Set (α ⊕ β ⊕ γ)).Subsingleton := by
intro
simp only [Finset.coe_map, Set.mem_image, Finset.mem_coe, Prod.exists, Ne,
forall_exists_index, and_imp]
rintro a b c habc rfl e x y z hxyz rfl h'
have := ne_of_apply_ne _ h'
simp only [Ne, Prod.mk_inj, not_and] at this
simp only [toTriangle_apply, in₀, in₁, in₂, Set.mem_inter_iff, mem_insert, mem_singleton,
mem_coe, and_imp, Sum.forall,
Set.Subsingleton]
suffices ¬ (a = x ∧ b = y) ∧ ¬ (a = x ∧ c = z) ∧ ¬ (b = y ∧ c = z) by aesop
refine ⟨?_, ?_, ?_⟩
· rintro ⟨rfl, rfl⟩
exact this rfl rfl (ExplicitDisjoint.inj₂ habc hxyz)
· rintro ⟨rfl, rfl⟩
exact this rfl (ExplicitDisjoint.inj₁ habc hxyz) rfl
· rintro ⟨rfl, rfl⟩
exact this (ExplicitDisjoint.inj₀ habc hxyz) rfl rfl
lemma cliqueSet_eq_image [NoAccidental t] : (graph t).cliqueSet 3 = toTriangle '' t := by
ext; exact is3Clique_iff
section Fintype
variable [Fintype α] [Fintype β] [Fintype γ]
lemma cliqueFinset_eq_image [NoAccidental t] : (graph t).cliqueFinset 3 = t.image toTriangle :=
coe_injective <| by push_cast; exact cliqueSet_eq_image _
lemma cliqueFinset_eq_map [NoAccidental t] : (graph t).cliqueFinset 3 = t.map toTriangle := by
simp [cliqueFinset_eq_image, map_eq_image]
@[simp] lemma card_triangles [NoAccidental t] : #((graph t).cliqueFinset 3) = #t := by
rw [cliqueFinset_eq_map, card_map]
lemma farFromTriangleFree [ExplicitDisjoint t] {ε : 𝕜}
(ht : ε * ((Fintype.card α + Fintype.card β + Fintype.card γ) ^ 2 : ℕ) ≤ #t) :
(graph t).FarFromTriangleFree ε :=
farFromTriangleFree_of_disjoint_triangles (t.map toTriangle)
(map_subset_iff_subset_preimage.2 fun x hx ↦ by simpa using toTriangle_is3Clique hx)
(map_toTriangle_disjoint t) <| by simpa [add_assoc] using ht
end Fintype
end DecidableEq
variable (t)
lemma locallyLinear [ExplicitDisjoint t] [NoAccidental t] : (graph t).LocallyLinear := by
classical
refine ⟨?_, fun x y hxy ↦ ?_⟩
· unfold EdgeDisjointTriangles
convert map_toTriangle_disjoint t
rw [cliqueSet_eq_image, coe_map]
· obtain ⟨z, hz, hxy⟩ := exists_mem_toTriangle hxy
exact ⟨_, toTriangle_is3Clique hz, hxy⟩
end TripartiteFromTriangles
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Triangle/Basic.lean | import Mathlib.Algebra.Order.Field.Basic
import Mathlib.Algebra.Order.Ring.Abs
import Mathlib.Combinatorics.Enumerative.DoubleCounting
import Mathlib.Combinatorics.SimpleGraph.Clique
import Mathlib.Data.Finset.Sym
import Mathlib.Data.Nat.Choose.Bounds
import Mathlib.Tactic.GCongr
import Mathlib.Tactic.Positivity
/-!
# Triangles in graphs
A *triangle* in a simple graph is a `3`-clique, namely a set of three vertices that are
pairwise adjacent.
This module defines and proves properties about triangles in simple graphs.
## Main declarations
* `SimpleGraph.FarFromTriangleFree`: Predicate for a graph such that one must remove a lot of edges
from it for it to become triangle-free. This is the crux of the Triangle Removal Lemma.
## TODO
* Generalise `FarFromTriangleFree` to other graphs, to state and prove the Graph Removal Lemma.
-/
open Finset Nat
open Fintype (card)
namespace SimpleGraph
variable {α β 𝕜 : Type*} [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜]
{G H : SimpleGraph α} {ε δ : 𝕜}
section LocallyLinear
/-- A graph has edge-disjoint triangles if each edge belongs to at most one triangle. -/
def EdgeDisjointTriangles (G : SimpleGraph α) : Prop :=
(G.cliqueSet 3).Pairwise fun x y ↦ (x ∩ y : Set α).Subsingleton
/-- A graph is locally linear if each edge belongs to exactly one triangle. -/
def LocallyLinear (G : SimpleGraph α) : Prop :=
G.EdgeDisjointTriangles ∧ ∀ ⦃x y⦄, G.Adj x y → ∃ s, G.IsNClique 3 s ∧ x ∈ s ∧ y ∈ s
protected lemma LocallyLinear.edgeDisjointTriangles : G.LocallyLinear → G.EdgeDisjointTriangles :=
And.left
nonrec lemma EdgeDisjointTriangles.mono (h : G ≤ H) (hH : H.EdgeDisjointTriangles) :
G.EdgeDisjointTriangles := hH.mono <| cliqueSet_mono h
@[simp] lemma edgeDisjointTriangles_bot : (⊥ : SimpleGraph α).EdgeDisjointTriangles := by
simp [EdgeDisjointTriangles]
@[simp] lemma locallyLinear_bot : (⊥ : SimpleGraph α).LocallyLinear := by simp [LocallyLinear]
lemma EdgeDisjointTriangles.map (f : α ↪ β) (hG : G.EdgeDisjointTriangles) :
(G.map f).EdgeDisjointTriangles := by
rw [EdgeDisjointTriangles, cliqueSet_map (by simp : 3 ≠ 1),
(Finset.map_injective f).injOn.pairwise_image]
classical
rintro s hs t ht hst
dsimp [Function.onFun]
rw [← coe_inter, ← map_inter, coe_map, coe_inter]
exact (hG hs ht hst).image _
lemma LocallyLinear.map (f : α ↪ β) (hG : G.LocallyLinear) : (G.map f).LocallyLinear := by
refine ⟨hG.1.map _, ?_⟩
rintro _ _ ⟨a, b, h, rfl, rfl⟩
obtain ⟨s, hs, ha, hb⟩ := hG.2 h
exact ⟨s.map f, hs.map, mem_map_of_mem _ ha, mem_map_of_mem _ hb⟩
@[simp] lemma locallyLinear_comap {G : SimpleGraph β} {e : α ≃ β} :
(G.comap e).LocallyLinear ↔ G.LocallyLinear := by
refine ⟨fun h ↦ ?_, ?_⟩
· rw [← comap_map_eq e.symm.toEmbedding G, comap_symm, map_symm]
exact h.map _
· rw [← Equiv.coe_toEmbedding, ← map_symm]
exact LocallyLinear.map _
lemma edgeDisjointTriangles_iff_mem_sym2_subsingleton :
G.EdgeDisjointTriangles ↔
∀ ⦃e : Sym2 α⦄, ¬ e.IsDiag → {s ∈ G.cliqueSet 3 | e ∈ (s : Finset α).sym2}.Subsingleton := by
classical
have (a b) (hab : a ≠ b) : {s ∈ (G.cliqueSet 3 : Set (Finset α)) | s(a, b) ∈ (s : Finset α).sym2}
= {s | G.Adj a b ∧ ∃ c, G.Adj a c ∧ G.Adj b c ∧ s = {a, b, c}} := by
ext s
simp only [mem_sym2_iff, Sym2.mem_iff, forall_eq_or_imp, forall_eq,
mem_cliqueSet_iff, Set.mem_setOf_eq,
is3Clique_iff]
constructor
· rintro ⟨⟨c, d, e, hcd, hce, hde, rfl⟩, hab⟩
simp only [mem_insert, mem_singleton] at hab
obtain ⟨rfl | rfl | rfl, rfl | rfl | rfl⟩ := hab
any_goals
simp only [*, adj_comm, true_and, Ne, not_true] at *
any_goals
first
| exact ⟨c, by aesop⟩
| exact ⟨d, by aesop⟩
| exact ⟨e, by aesop⟩
| simp only [*, true_and] at *
exact ⟨c, by aesop⟩
| simp only [*, true_and] at *
exact ⟨d, by aesop⟩
| simp only [*, true_and] at *
exact ⟨e, by aesop⟩
· rintro ⟨hab, c, hac, hbc, rfl⟩
refine ⟨⟨a, b, c, ?_⟩, ?_⟩ <;> simp [*]
constructor
· rw [Sym2.forall]
rintro hG a b hab
simp only [Sym2.isDiag_iff_proj_eq] at hab
rw [this _ _ (Sym2.mk_isDiag_iff.not.2 hab)]
rintro _ ⟨hab, c, hac, hbc, rfl⟩ _ ⟨-, d, had, hbd, rfl⟩
refine hG.eq ?_ ?_ (Set.Nontrivial.not_subsingleton ⟨a, ?_, b, ?_, hab.ne⟩) <;>
simp [is3Clique_triple_iff, *]
· simp only [EdgeDisjointTriangles, is3Clique_iff, Set.Pairwise, mem_cliqueSet_iff, Ne,
forall_exists_index, and_imp, ← Set.not_nontrivial_iff (s := _ ∩ _), not_imp_not,
Set.Nontrivial, Set.mem_inter_iff, mem_coe]
rintro hG _ a b c hab hac hbc rfl _ d e f hde hdf hef rfl g hg₁ hg₂ h hh₁ hh₂ hgh
refine hG (Sym2.mk_isDiag_iff.not.2 hgh) ⟨⟨a, b, c, ?_⟩, by simpa using And.intro hg₁ hh₁⟩
⟨⟨d, e, f, ?_⟩, by simpa using And.intro hg₂ hh₂⟩ <;> simp [*]
alias ⟨EdgeDisjointTriangles.mem_sym2_subsingleton, _⟩ :=
edgeDisjointTriangles_iff_mem_sym2_subsingleton
variable [DecidableEq α] [Fintype α] [DecidableRel G.Adj]
instance EdgeDisjointTriangles.instDecidable : Decidable G.EdgeDisjointTriangles :=
decidable_of_iff ((G.cliqueFinset 3 : Set (Finset α)).Pairwise fun x y ↦ (#(x ∩ y) ≤ 1)) <| by
simp only [coe_cliqueFinset, EdgeDisjointTriangles, Finset.card_le_one, ← coe_inter]; rfl
instance LocallyLinear.instDecidable : Decidable G.LocallyLinear :=
inferInstanceAs (Decidable (_ ∧ _))
lemma EdgeDisjointTriangles.card_edgeFinset_le (hG : G.EdgeDisjointTriangles) :
3 * #(G.cliqueFinset 3) ≤ #G.edgeFinset := by
rw [mul_comm, ← mul_one #G.edgeFinset]
refine card_mul_le_card_mul (fun s e ↦ e ∈ s.sym2) ?_ (fun e he ↦ ?_)
· simp only [is3Clique_iff, mem_cliqueFinset_iff, mem_sym2_iff, forall_exists_index, and_imp]
rintro _ a b c hab hac hbc rfl
have : #{s(a, b), s(a, c), s(b, c)} = 3 := by
refine card_eq_three.2 ⟨_, _, _, ?_, ?_, ?_, rfl⟩ <;> simp [hab.ne, hac.ne, hbc.ne]
rw [← this]
refine card_mono ?_
simp [insert_subset, *]
· simpa only [card_le_one, mem_bipartiteBelow, and_imp, Set.Subsingleton, Set.mem_setOf_eq,
mem_cliqueFinset_iff, mem_cliqueSet_iff]
using hG.mem_sym2_subsingleton (G.not_isDiag_of_mem_edgeSet <| mem_edgeFinset.1 he)
lemma LocallyLinear.card_edgeFinset (hG : G.LocallyLinear) :
#G.edgeFinset = 3 * #(G.cliqueFinset 3) := by
refine hG.edgeDisjointTriangles.card_edgeFinset_le.antisymm' ?_
rw [← mul_comm, ← mul_one #_]
refine card_mul_le_card_mul (fun e s ↦ e ∈ s.sym2) ?_ ?_
· simpa [Sym2.forall, Nat.one_le_iff_ne_zero, -Finset.card_eq_zero, Finset.card_ne_zero,
Finset.Nonempty]
using hG.2
simp only [mem_cliqueFinset_iff, is3Clique_iff, forall_exists_index, and_imp]
rintro _ a b c hab hac hbc rfl
calc
_ ≤ #{s(a, b), s(a, c), s(b, c)} := card_le_card ?_
_ ≤ 3 := (card_insert_le _ _).trans (succ_le_succ <| (card_insert_le _ _).trans_eq <| by
rw [card_singleton])
simp only [subset_iff, Sym2.forall, mem_sym2_iff, mem_bipartiteBelow, mem_insert,
mem_edgeFinset, mem_singleton, and_imp, mem_edgeSet, Sym2.mem_iff, forall_eq_or_imp,
forall_eq]
rintro d e hde (rfl | rfl | rfl) (rfl | rfl | rfl) <;> simp [*] at *
end LocallyLinear
variable (G ε)
variable [Fintype α] [DecidableRel G.Adj] [DecidableRel H.Adj]
/-- A simple graph is *`ε`-far from triangle-free* if one must remove at least
`ε * (card α) ^ 2` edges to make it triangle-free. -/
def FarFromTriangleFree : Prop := G.DeleteFar (fun H ↦ H.CliqueFree 3) <| ε * (card α ^ 2 : ℕ)
variable {G ε}
omit [IsStrictOrderedRing 𝕜] in
theorem farFromTriangleFree_iff :
G.FarFromTriangleFree ε ↔ ∀ ⦃H : SimpleGraph α⦄, [DecidableRel H.Adj] → H ≤ G → H.CliqueFree 3 →
ε * (card α ^ 2 : ℕ) ≤ #G.edgeFinset - #H.edgeFinset := deleteFar_iff
alias ⟨farFromTriangleFree.le_card_sub_card, _⟩ := farFromTriangleFree_iff
nonrec theorem FarFromTriangleFree.mono (hε : G.FarFromTriangleFree ε) (h : δ ≤ ε) :
G.FarFromTriangleFree δ := hε.mono <| by gcongr
section DecidableEq
variable [DecidableEq α]
omit [IsStrictOrderedRing 𝕜] in
theorem FarFromTriangleFree.cliqueFinset_nonempty' (hH : H ≤ G) (hG : G.FarFromTriangleFree ε)
(hcard : #G.edgeFinset - #H.edgeFinset < ε * (card α ^ 2 : ℕ)) :
(H.cliqueFinset 3).Nonempty :=
nonempty_of_ne_empty <|
cliqueFinset_eq_empty_iff.not.2 fun hH' => (hG.le_card_sub_card hH hH').not_gt hcard
private lemma farFromTriangleFree_of_disjoint_triangles_aux {tris : Finset (Finset α)}
(htris : tris ⊆ G.cliqueFinset 3)
(pd : (tris : Set (Finset α)).Pairwise fun x y ↦ (x ∩ y : Set α).Subsingleton) (hHG : H ≤ G)
(hH : H.CliqueFree 3) : #tris ≤ #G.edgeFinset - #H.edgeFinset := by
rw [← card_sdiff_of_subset (edgeFinset_mono hHG), ← card_attach]
by_contra! hG
have ⦃t⦄ (ht : t ∈ tris) :
∃ x y, x ∈ t ∧ y ∈ t ∧ x ≠ y ∧ s(x, y) ∈ G.edgeFinset \ H.edgeFinset := by
by_contra! h
refine hH t ?_
simp only [not_and, mem_sdiff, not_not, mem_edgeFinset, mem_edgeSet] at h
obtain ⟨x, y, z, xy, xz, yz, rfl⟩ := is3Clique_iff.1 (mem_cliqueFinset_iff.1 <| htris ht)
rw [is3Clique_triple_iff]
refine ⟨h _ _ ?_ ?_ xy.ne xy, h _ _ ?_ ?_ xz.ne xz, h _ _ ?_ ?_ yz.ne yz⟩ <;> simp
choose fx fy hfx hfy hfne fmem using this
let f (t : {x // x ∈ tris}) : Sym2 α := s(fx t.2, fy t.2)
have hf (x) (_ : x ∈ tris.attach) : f x ∈ G.edgeFinset \ H.edgeFinset := fmem _
obtain ⟨⟨t₁, ht₁⟩, -, ⟨t₂, ht₂⟩, -, tne, t : s(_, _) = s(_, _)⟩ :=
exists_ne_map_eq_of_card_lt_of_maps_to hG hf
dsimp at t
have i := pd ht₁ ht₂ (Subtype.val_injective.ne tne)
rw [Sym2.eq_iff] at t
obtain t | t := t
· exact hfne _ (i ⟨hfx ht₁, t.1.symm ▸ hfx ht₂⟩ ⟨hfy ht₁, t.2.symm ▸ hfy ht₂⟩)
· exact hfne _ (i ⟨hfx ht₁, t.1.symm ▸ hfy ht₂⟩ ⟨hfy ht₁, t.2.symm ▸ hfx ht₂⟩)
/-- If there are `ε * (card α)^2` disjoint triangles, then the graph is `ε`-far from being
triangle-free. -/
lemma farFromTriangleFree_of_disjoint_triangles (tris : Finset (Finset α))
(htris : tris ⊆ G.cliqueFinset 3)
(pd : (tris : Set (Finset α)).Pairwise fun x y ↦ (x ∩ y : Set α).Subsingleton)
(tris_big : ε * (card α ^ 2 : ℕ) ≤ #tris) :
G.FarFromTriangleFree ε := by
rw [farFromTriangleFree_iff]
intro H _ hG hH
rw [← Nat.cast_sub (card_le_card <| edgeFinset_mono hG)]
exact tris_big.trans
(Nat.cast_le.2 <| farFromTriangleFree_of_disjoint_triangles_aux htris pd hG hH)
protected lemma EdgeDisjointTriangles.farFromTriangleFree (hG : G.EdgeDisjointTriangles)
(tris_big : ε * (card α ^ 2 : ℕ) ≤ #(G.cliqueFinset 3)) :
G.FarFromTriangleFree ε :=
farFromTriangleFree_of_disjoint_triangles _ Subset.rfl (by simpa using hG) tris_big
end DecidableEq
variable [Nonempty α]
lemma FarFromTriangleFree.lt_half (hε : G.FarFromTriangleFree ε) : ε < 2⁻¹ := by
refine lt_of_mul_lt_mul_right (α := 𝕜) (a := Fintype.card α ^ 2) ?_ (by positivity)
calc
ε * Fintype.card α ^ 2
_ ≤ #G.edgeFinset := by simpa using hε.le_card_edgeFinset (by simp)
_ ≤ (Fintype.card α).choose 2 := by gcongr; exact card_edgeFinset_le_card_choose_two
_ < 2⁻¹ * Fintype.card α ^ 2 := by
simpa [← div_eq_inv_mul] using Nat.choose_lt_pow_div (by positivity) le_rfl
lemma FarFromTriangleFree.lt_one (hG : G.FarFromTriangleFree ε) : ε < 1 :=
hG.lt_half.trans two_inv_lt_one
theorem FarFromTriangleFree.nonpos (h₀ : G.FarFromTriangleFree ε) (h₁ : G.CliqueFree 3) :
ε ≤ 0 := by
have := h₀ (empty_subset _)
rw [coe_empty, Finset.card_empty, cast_zero, deleteEdges_empty] at this
exact nonpos_of_mul_nonpos_left (this h₁) (cast_pos.2 <| sq_pos_of_pos Fintype.card_pos)
theorem CliqueFree.not_farFromTriangleFree (hG : G.CliqueFree 3) (hε : 0 < ε) :
¬G.FarFromTriangleFree ε := fun h => (h.nonpos hG).not_gt hε
theorem FarFromTriangleFree.not_cliqueFree (hG : G.FarFromTriangleFree ε) (hε : 0 < ε) :
¬G.CliqueFree 3 := fun h => (hG.nonpos h).not_gt hε
theorem FarFromTriangleFree.cliqueFinset_nonempty [DecidableEq α]
(hG : G.FarFromTriangleFree ε) (hε : 0 < ε) : (G.cliqueFinset 3).Nonempty :=
nonempty_of_ne_empty <| cliqueFinset_eq_empty_iff.not.2 <| hG.not_cliqueFree hε
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Triangle/Counting.lean | import Mathlib.Combinatorics.SimpleGraph.Clique
import Mathlib.Combinatorics.SimpleGraph.Regularity.Uniform
import Mathlib.Data.Real.Basic
import Mathlib.Tactic.Linarith
/-!
# Triangle counting lemma
In this file, we prove the triangle counting lemma.
## References
[Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
-/
-- TODO: This instance is bad because it creates data out of a Prop
attribute [-instance] decidableEq_of_subsingleton
open Finset Fintype
variable {α : Type*} (G : SimpleGraph α) [DecidableRel G.Adj] {ε : ℝ} {s t u : Finset α}
namespace SimpleGraph
/-- The vertices of `s` whose density in `t` is `ε` less than expected. -/
private noncomputable def badVertices (ε : ℝ) (s t : Finset α) : Finset α :=
{x ∈ s | #{y ∈ t | G.Adj x y} < (G.edgeDensity s t - ε) * #t}
private lemma card_interedges_badVertices_le :
#(Rel.interedges G.Adj (badVertices G ε s t) t) ≤
#(badVertices G ε s t) * #t * (G.edgeDensity s t - ε) := by
classical
refine (Nat.cast_le.2 <| (card_le_card <| subset_of_eq (Rel.interedges_eq_biUnion _)).trans
card_biUnion_le).trans ?_
simp_rw [Nat.cast_sum, card_map, ← nsmul_eq_mul, smul_mul_assoc, mul_comm (#t : ℝ)]
exact sum_le_card_nsmul _ _ _ fun x hx ↦ (mem_filter.1 hx).2.le
private lemma edgeDensity_badVertices_le (hε : 0 ≤ ε) (dst : 2 * ε ≤ G.edgeDensity s t) :
G.edgeDensity (badVertices G ε s t) t ≤ G.edgeDensity s t - ε := by
rw [edgeDensity_def]
push_cast
refine div_le_of_le_mul₀ (by positivity) (sub_nonneg_of_le <| by linarith) ?_
rw [mul_comm]
exact G.card_interedges_badVertices_le
private lemma card_badVertices_le (dst : 2 * ε ≤ G.edgeDensity s t) (hst : G.IsUniform ε s t) :
#(badVertices G ε s t) ≤ #s * ε := by
have hε : ε ≤ 1 := (le_mul_of_one_le_left hst.pos.le (by simp)).trans
(dst.trans <| mod_cast edgeDensity_le_one _ _ _)
by_contra! h
have : |(G.edgeDensity (badVertices G ε s t) t - G.edgeDensity s t : ℝ)| < ε :=
hst (filter_subset _ _) Subset.rfl h.le (mul_le_of_le_one_right (Nat.cast_nonneg _) hε)
rw [abs_sub_lt_iff] at this
linarith [G.edgeDensity_badVertices_le hst.pos.le dst]
/-- A subset of the triangles constructed in a weird way to make them easy to count. -/
private lemma triangle_split_helper [DecidableEq α] :
(s \ (badVertices G ε s t ∪ badVertices G ε s u)).biUnion
(fun x ↦ (G.interedges {y ∈ t | G.Adj x y} {y ∈ u | G.Adj x y}).image (x, ·)) ⊆
(s ×ˢ t ×ˢ u).filter (fun (x, y, z) ↦ G.Adj x y ∧ G.Adj x z ∧ G.Adj y z) := by
rintro ⟨x, y, z⟩
simp only [mem_filter, mem_product, mem_biUnion, mem_sdiff, mem_union,
mem_image, Prod.exists, and_assoc, exists_imp, and_imp, Prod.mk_inj, mem_interedges_iff]
rintro x hx - y z hy xy hz xz yz rfl rfl rfl
exact ⟨hx, hy, hz, xy, xz, yz⟩
private lemma good_vertices_triangle_card [DecidableEq α] (dst : 2 * ε ≤ G.edgeDensity s t)
(dsu : 2 * ε ≤ G.edgeDensity s u) (dtu : 2 * ε ≤ G.edgeDensity t u) (utu : G.IsUniform ε t u)
(x : α) (hx : x ∈ s \ (badVertices G ε s t ∪ badVertices G ε s u)) :
ε ^ 3 * #t * #u ≤ #((({y ∈ t | G.Adj x y} ×ˢ {y ∈ u | G.Adj x y}).filter
fun (y, z) ↦ G.Adj y z).image (x, ·)) := by
simp only [mem_sdiff, badVertices, mem_union, not_or, mem_filter, not_and_or, not_lt] at hx
rw [← or_and_left, and_or_left] at hx
simp only [false_or, and_not_self, mul_comm (_ - _)] at hx
obtain ⟨-, hxY, hsu⟩ := hx
have hY : #t * ε ≤ #{y ∈ t | G.Adj x y} := by
refine le_trans ?_ hxY; gcongr; linarith
have hZ : #u * ε ≤ #{y ∈ u | G.Adj x y} := by
refine le_trans ?_ hsu; gcongr; linarith
rw [card_image_of_injective _ (Prod.mk_right_injective _)]
have := utu (filter_subset (G.Adj x) _) (filter_subset (G.Adj x) _) hY hZ
have : ε ≤ G.edgeDensity {y ∈ t | G.Adj x y} {y ∈ u | G.Adj x y} := by
rw [abs_sub_lt_iff] at this; linarith
rw [edgeDensity_def] at this
push_cast at this
have hε := utu.pos.le
refine le_trans ?_ (mul_le_of_le_div₀ (Nat.cast_nonneg _) (by positivity) this)
refine Eq.trans_le ?_
(mul_le_mul_of_nonneg_left (mul_le_mul hY hZ (by positivity) (by positivity)) hε)
ring
/-- The **Triangle Counting Lemma**. If `G` is a graph and `s`, `t`, `u` are sets of vertices such
that each pair is `ε`-uniform and `2 * ε`-dense, then a proportion of at least
`(1 - 2 * ε) * ε ^ 3` of the triples `(a, b, c) ∈ s × t × u` are triangles. -/
lemma triangle_counting'
(dst : 2 * ε ≤ G.edgeDensity s t) (hst : G.IsUniform ε s t)
(dsu : 2 * ε ≤ G.edgeDensity s u) (usu : G.IsUniform ε s u)
(dtu : 2 * ε ≤ G.edgeDensity t u) (utu : G.IsUniform ε t u) :
(1 - 2 * ε) * ε ^ 3 * #s * #t * #u ≤
#((s ×ˢ t ×ˢ u).filter fun (a, b, c) ↦ G.Adj a b ∧ G.Adj a c ∧ G.Adj b c) := by
classical
have h₁ : #(badVertices G ε s t) ≤ #s * ε := G.card_badVertices_le dst hst
have h₂ : #(badVertices G ε s u) ≤ #s * ε := G.card_badVertices_le dsu usu
let X' := s \ (badVertices G ε s t ∪ badVertices G ε s u)
have : X'.biUnion _ ⊆ (s ×ˢ t ×ˢ u).filter fun (a, b, c) ↦ G.Adj a b ∧ G.Adj a c ∧ G.Adj b c :=
triangle_split_helper _
refine le_trans ?_ (Nat.cast_le.2 <| card_le_card this)
rw [card_biUnion, Nat.cast_sum]
· apply le_trans _ (card_nsmul_le_sum X' _ _ <| G.good_vertices_triangle_card dst dsu dtu utu)
rw [nsmul_eq_mul]
have := hst.pos.le
suffices hX' : (1 - 2 * ε) * #s ≤ #X' by
exact Eq.trans_le (by ring) (mul_le_mul_of_nonneg_right hX' <| by positivity)
have i : badVertices G ε s t ∪ badVertices G ε s u ⊆ s :=
union_subset (filter_subset _ _) (filter_subset _ _)
rw [sub_mul, one_mul, card_sdiff_of_subset i, Nat.cast_sub (card_le_card i),
sub_le_sub_iff_left, mul_assoc, mul_comm ε, two_mul]
refine (Nat.cast_le.2 <| card_union_le _ _).trans ?_
rw [Nat.cast_add]
gcongr
rintro a _ b _ t
rw [Function.onFun, disjoint_left]
simp only [Prod.forall, mem_image, not_exists, Prod.mk_inj,
exists_imp, and_imp, not_and]
aesop
variable [DecidableEq α]
private lemma triple_eq_triple_of_mem (hst : Disjoint s t) (hsu : Disjoint s u) (htu : Disjoint t u)
{x₁ x₂ y₁ y₂ z₁ z₂ : α} (h : ({x₁, y₁, z₁} : Finset α) = {x₂, y₂, z₂})
(hx₁ : x₁ ∈ s) (hx₂ : x₂ ∈ s) (hy₁ : y₁ ∈ t) (hy₂ : y₂ ∈ t) (hz₁ : z₁ ∈ u) (hz₂ : z₂ ∈ u) :
(x₁, y₁, z₁) = (x₂, y₂, z₂) := by
simp only [Finset.Subset.antisymm_iff, subset_iff, mem_insert, mem_singleton, forall_eq_or_imp,
forall_eq] at h
grind [disjoint_left]
variable [Fintype α]
/-- The **Triangle Counting Lemma**. If `G` is a graph and `s`, `t`, `u` are disjoint sets of
vertices such that each pair is `ε`-uniform and `2 * ε`-dense, then `G` contains at least
`(1 - 2 * ε) * ε ^ 3 * |s| * |t| * |u|` triangles. -/
lemma triangle_counting
(dst : 2 * ε ≤ G.edgeDensity s t) (ust : G.IsUniform ε s t) (hst : Disjoint s t)
(dsu : 2 * ε ≤ G.edgeDensity s u) (usu : G.IsUniform ε s u) (hsu : Disjoint s u)
(dtu : 2 * ε ≤ G.edgeDensity t u) (utu : G.IsUniform ε t u) (htu : Disjoint t u) :
(1 - 2 * ε) * ε ^ 3 * #s * #t * #u ≤ #(G.cliqueFinset 3) := by
apply (G.triangle_counting' dst ust dsu usu dtu utu).trans _
rw [Nat.cast_le]
refine card_le_card_of_injOn (fun (x, y, z) ↦ {x, y, z}) ?_ ?_
· rintro ⟨x, y, z⟩
simp +contextual [is3Clique_triple_iff]
rintro ⟨x₁, y₁, z₁⟩ h₁ ⟨x₂, y₂, z₂⟩ h₂ t
simp only [mem_coe, mem_filter, mem_product] at h₁ h₂
apply triple_eq_triple_of_mem hst hsu htu t <;> tauto
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Triangle/Removal.lean | import Mathlib.Combinatorics.SimpleGraph.DegreeSum
import Mathlib.Combinatorics.SimpleGraph.Regularity.Lemma
import Mathlib.Combinatorics.SimpleGraph.Triangle.Basic
import Mathlib.Combinatorics.SimpleGraph.Triangle.Counting
import Mathlib.Data.Finset.CastCard
/-!
# Triangle removal lemma
In this file, we prove the triangle removal lemma.
## References
[Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
-/
open Finset Fintype Nat SzemerediRegularity
variable {α : Type*} [DecidableEq α] [Fintype α] {G : SimpleGraph α} [DecidableRel G.Adj]
{s t : Finset α} {P : Finpartition (univ : Finset α)} {ε : ℝ}
namespace SimpleGraph
/-- An explicit form for the constant in the triangle removal lemma.
Note that this depends on `SzemerediRegularity.bound`, which is a tower-type exponential. This means
`triangleRemovalBound` is in practice absolutely tiny.
This definition is meant to be used for small values of `ε`, and in particular is junk for values
of `ε` greater than or equal to `1`. The junk value is chosen to be positive, so that
`0 < ε → 0 < triangleRemovalBound ε` regardless of whether `ε < 1` or not. -/
noncomputable def triangleRemovalBound (ε : ℝ) : ℝ :=
min (2 * ⌈4/ε⌉₊^3)⁻¹ ((1 - min 1 ε/4) * (ε/(16 * bound (ε/8) ⌈4/ε⌉₊))^3)
lemma triangleRemovalBound_pos (hε : 0 < ε) : 0 < triangleRemovalBound ε := by
have : 0 < 1 - min 1 ε/4 := by have := min_le_left 1 ε; linarith
unfold triangleRemovalBound
positivity
lemma triangleRemovalBound_nonpos (hε : ε ≤ 0) : triangleRemovalBound ε ≤ 0 := by
rw [triangleRemovalBound, ceil_eq_zero.2 (div_nonpos_of_nonneg_of_nonpos _ hε)] <;> simp
lemma triangleRemovalBound_mul_cube_lt (hε : 0 < ε) :
triangleRemovalBound ε * ⌈4 / ε⌉₊ ^ 3 < 1 := by
calc
_ ≤ (2 * ⌈4 / ε⌉₊ ^ 3 : ℝ)⁻¹ * ↑⌈4 / ε⌉₊ ^ 3 := by gcongr; exact min_le_left _ _
_ = 2⁻¹ := by rw [mul_inv, inv_mul_cancel_right₀]; positivity
_ < 1 := by norm_num
lemma triangleRemovalBound_le (hε₁ : ε ≤ 1) :
triangleRemovalBound ε ≤ (1 - ε/4) * (ε/(16 * bound (ε/8) ⌈4/ε⌉₊)) ^ 3 := by
simp [triangleRemovalBound, hε₁]
private lemma aux {n k : ℕ} (hk : 0 < k) (hn : k ≤ n) : n < 2 * k * (n / k) := by
rw [mul_assoc, two_mul, ← add_lt_add_iff_right (n % k), add_right_comm, add_assoc,
mod_add_div n k, add_comm, add_lt_add_iff_right]
apply (mod_lt n hk).trans_le
simpa using Nat.mul_le_mul_left k ((Nat.one_le_div_iff hk).2 hn)
private lemma card_bound (hP₁ : P.IsEquipartition) (hP₃ : #P.parts ≤ bound (ε / 8) ⌈4 / ε⌉₊)
(hX : s ∈ P.parts) : card α / (2 * bound (ε / 8) ⌈4 / ε⌉₊ : ℝ) ≤ #s := by
cases isEmpty_or_nonempty α
· simp [Fintype.card_eq_zero]
have := Finset.Nonempty.card_pos ⟨_, hX⟩
calc
_ ≤ card α / (2 * #P.parts : ℝ) := by gcongr
_ ≤ ↑(card α / #P.parts) :=
(div_le_iff₀' (by positivity)).2 <| mod_cast (aux ‹_› P.card_parts_le_card).le
_ ≤ (#s : ℝ) := mod_cast hP₁.average_le_card_part hX
private lemma triangle_removal_aux (hε : 0 < ε) (hε₁ : ε ≤ 1) (hP₁ : P.IsEquipartition)
(hP₃ : #P.parts ≤ bound (ε / 8) ⌈4 / ε⌉₊)
(ht : t ∈ (G.regularityReduced P (ε / 8) (ε / 4)).cliqueFinset 3) :
triangleRemovalBound ε * card α ^ 3 ≤ #(G.cliqueFinset 3) := by
rw [mem_cliqueFinset_iff, is3Clique_iff] at ht
obtain ⟨x, y, z, ⟨-, s, hX, Y, hY, xX, yY, nXY, uXY, dXY⟩,
⟨-, X', hX', Z, hZ, xX', zZ, nXZ, uXZ, dXZ⟩,
⟨-, Y', hY', Z', hZ', yY', zZ', nYZ, uYZ, dYZ⟩, rfl⟩ := ht
cases P.disjoint.elim hX hX' (not_disjoint_iff.2 ⟨x, xX, xX'⟩)
cases P.disjoint.elim hY hY' (not_disjoint_iff.2 ⟨y, yY, yY'⟩)
cases P.disjoint.elim hZ hZ' (not_disjoint_iff.2 ⟨z, zZ, zZ'⟩)
have dXY := P.disjoint hX hY nXY
have dXZ := P.disjoint hX hZ nXZ
have dYZ := P.disjoint hY hZ nYZ
have that : 2 * (ε / 8) = ε / 4 := by ring
have : 0 ≤ 1 - 2 * (ε / 8) := by
have : ε / 4 ≤ 1 := ‹ε / 4 ≤ _›.trans (by exact mod_cast G.edgeDensity_le_one _ _); linarith
calc
_ ≤ (1 - ε/4) * (ε/(16 * bound (ε/8) ⌈4/ε⌉₊))^3 * card α ^ 3 := by
gcongr; exact triangleRemovalBound_le hε₁
_ = (1 - 2 * (ε / 8)) * (ε / 8) ^ 3 * (card α / (2 * bound (ε / 8) ⌈4 / ε⌉₊)) *
(card α / (2 * bound (ε / 8) ⌈4 / ε⌉₊)) * (card α / (2 * bound (ε / 8) ⌈4 / ε⌉₊)) := by
ring
_ ≤ (1 - 2 * (ε / 8)) * (ε / 8) ^ 3 * #s * #Y * #Z := by
gcongr <;> exact card_bound hP₁ hP₃ ‹_›
_ ≤ _ :=
triangle_counting G (by rwa [that]) uXY dXY (by rwa [that]) uXZ dXZ (by rwa [that]) uYZ dYZ
lemma regularityReduced_edges_card_aux [Nonempty α] (hε : 0 < ε) (hP : P.IsEquipartition)
(hPε : P.IsUniform G (ε / 8)) (hP' : 4 / ε ≤ #P.parts) :
2 * (#G.edgeFinset - #(G.regularityReduced P (ε / 8) (ε / 4)).edgeFinset : ℝ)
< 2 * ε * (card α ^ 2 : ℕ) := by
let A := (P.nonUniforms G (ε / 8)).biUnion fun (U, V) ↦ U ×ˢ V
let B := P.parts.biUnion offDiag
let C := (P.sparsePairs G (ε / 4)).biUnion fun (U, V) ↦ G.interedges U V
calc
_ = (#((univ ×ˢ univ).filter fun (x, y) ↦
G.Adj x y ∧ ¬(G.regularityReduced P (ε / 8) (ε /4)).Adj x y) : ℝ) := by
rw [univ_product_univ, mul_sub, filter_and_not, cast_card_sdiff]
· norm_cast
rw [two_mul_card_edgeFinset, two_mul_card_edgeFinset]
· gcongr with xy _
exact fun hxy ↦ regularityReduced_le hxy
_ ≤ #(A ∪ B ∪ C) := by gcongr; exact unreduced_edges_subset
_ ≤ #(A ∪ B) + #C := mod_cast (card_union_le _ _)
_ ≤ #A + #B + #C := by gcongr; exact mod_cast card_union_le _ _
_ < 4 * (ε / 8) * card α ^ 2 + _ + _ := by
gcongr; exact hP.sum_nonUniforms_lt univ_nonempty (by positivity) hPε
_ ≤ _ + ε / 2 * card α ^ 2 + 4 * (ε / 4) * card α ^ 2 := by
gcongr
· exact hP.card_biUnion_offDiag_le hε hP'
· exact hP.card_interedges_sparsePairs_le (G := G) (ε := ε / 4) (by positivity)
_ = 2 * ε * (card α ^ 2 : ℕ) := by norm_cast; ring
/-- **Triangle Removal Lemma**. If not all triangles can be removed by removing few edges (on the
order of `(card α)^2`), then there were many triangles to start with (on the order of
`(card α)^3`). -/
lemma FarFromTriangleFree.le_card_cliqueFinset (hG : G.FarFromTriangleFree ε) :
triangleRemovalBound ε * card α ^ 3 ≤ #(G.cliqueFinset 3) := by
cases isEmpty_or_nonempty α
· simp [Fintype.card_eq_zero]
obtain hε | hε := le_or_gt ε 0
· apply (mul_nonpos_of_nonpos_of_nonneg (triangleRemovalBound_nonpos hε) _).trans <;> positivity
let l : ℕ := ⌈4 / ε⌉₊
have hl : 4 / ε ≤ l := le_ceil (4 / ε)
rcases le_total (card α) l with hl' | hl'
· calc
_ ≤ triangleRemovalBound ε * ↑l ^ 3 := by
gcongr; exact (triangleRemovalBound_pos hε).le
_ ≤ (1 : ℝ) := (triangleRemovalBound_mul_cube_lt hε).le
_ ≤ _ := by simpa [one_le_iff_ne_zero] using (hG.cliqueFinset_nonempty hε).card_pos.ne'
obtain ⟨P, hP₁, hP₂, hP₃, hP₄⟩ := szemeredi_regularity G (by positivity : 0 < ε / 8) hl'
have : 4 / ε ≤ #P.parts := hl.trans (cast_le.2 hP₂)
have k := regularityReduced_edges_card_aux hε hP₁ hP₄ this
rw [mul_assoc] at k
replace k := lt_of_mul_lt_mul_left k zero_le_two
obtain ⟨t, ht⟩ := hG.cliqueFinset_nonempty' regularityReduced_le k
exact triangle_removal_aux hε hG.lt_one.le hP₁ hP₃ ht
/-- **Triangle Removal Lemma**. If there are not too many triangles (on the order of `(card α)^3`)
then they can all be removed by removing a few edges (on the order of `(card α)^2`). -/
lemma triangle_removal (hG : #(G.cliqueFinset 3) < triangleRemovalBound ε * card α ^ 3) :
∃ G' ≤ G, ∃ _ : DecidableRel G'.Adj,
(#G.edgeFinset - #G'.edgeFinset : ℝ) < ε * (card α ^ 2 : ℕ) ∧ G'.CliqueFree 3 := by
by_contra! h
refine hG.not_ge (farFromTriangleFree_iff.2 ?_).le_card_cliqueFinset
intro G' _ hG hG'
exact le_of_not_gt fun i ↦ h G' hG _ i hG'
end SimpleGraph
namespace Mathlib.Meta.Positivity
open Lean.Meta Qq SimpleGraph
/-- Extension for the `positivity` tactic: `SimpleGraph.triangleRemovalBound ε` is positive
if `ε` is.
This exploits the positivity of the junk value of `triangleRemovalBound ε` for `ε ≥ 1`. -/
@[positivity triangleRemovalBound _]
def evalTriangleRemovalBound : PositivityExt where eval {u α} _zα _pα e := do
match u, α, e with
| 0, ~q(ℝ), ~q(triangleRemovalBound $ε) =>
let .positive hε ← core q(inferInstance) q(inferInstance) ε | failure
assertInstancesCommute
pure (.positive q(triangleRemovalBound_pos $hε))
| _, _, _ => throwError "failed to match on Int.ceil application"
example (ε : ℝ) (hε : 0 < ε) : 0 < triangleRemovalBound ε := by positivity
end Mathlib.Meta.Positivity |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Regularity/Energy.lean | import Mathlib.Algebra.Module.NatInt
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Combinatorics.SimpleGraph.Density
import Mathlib.Data.Rat.BigOperators
/-!
# Energy of a partition
This file defines the energy of a partition.
The energy is the auxiliary quantity that drives the induction process in the proof of Szemerédi's
Regularity Lemma. As long as we do not have a suitable equipartition, we will find a new one that
has an energy greater than the previous one plus some fixed constant.
## References
[Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
-/
open Finset
variable {α : Type*} [DecidableEq α] {s : Finset α} (P : Finpartition s) (G : SimpleGraph α)
[DecidableRel G.Adj]
namespace Finpartition
/-- The energy of a partition, also known as index. Auxiliary quantity for Szemerédi's regularity
lemma. -/
def energy : ℚ :=
((∑ uv ∈ P.parts.offDiag, G.edgeDensity uv.1 uv.2 ^ 2) : ℚ) / (#P.parts : ℚ) ^ 2
theorem energy_nonneg : 0 ≤ P.energy G := by
exact div_nonneg (Finset.sum_nonneg fun _ _ => sq_nonneg _) <| sq_nonneg _
theorem energy_le_one : P.energy G ≤ 1 :=
div_le_of_le_mul₀ (sq_nonneg _) zero_le_one <|
calc
∑ uv ∈ P.parts.offDiag, G.edgeDensity uv.1 uv.2 ^ 2 ≤ #P.parts.offDiag • (1 : ℚ) :=
sum_le_card_nsmul _ _ 1 fun _ _ =>
(sq_le_one_iff₀ <| G.edgeDensity_nonneg _ _).2 <| G.edgeDensity_le_one _ _
_ = #P.parts.offDiag := Nat.smul_one_eq_cast _
_ ≤ _ := by
rw [offDiag_card, one_mul]
norm_cast
rw [sq]
exact tsub_le_self
@[simp, norm_cast]
theorem coe_energy {𝕜 : Type*} [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜] :
(P.energy G : 𝕜) =
(∑ uv ∈ P.parts.offDiag, (G.edgeDensity uv.1 uv.2 : 𝕜) ^ 2) / (#P.parts : 𝕜) ^ 2 := by
rw [energy]; norm_cast
end Finpartition |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Regularity/Uniform.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Combinatorics.SimpleGraph.Density
import Mathlib.Data.Nat.Cast.Order.Field
import Mathlib.Order.Partition.Equipartition
import Mathlib.SetTheory.Cardinal.Order
/-!
# Graph uniformity and uniform partitions
In this file we define uniformity of a pair of vertices in a graph and uniformity of a partition of
vertices of a graph. Both are also known as ε-regularity.
Finsets of vertices `s` and `t` are `ε`-uniform in a graph `G` if their edge density is at most
`ε`-far from the density of any big enough `s'` and `t'` where `s' ⊆ s`, `t' ⊆ t`.
The definition is pretty technical, but it amounts to the edges between `s` and `t` being "random"
The literature contains several definitions which are equivalent up to scaling `ε` by some constant
when the partition is equitable.
A partition `P` of the vertices is `ε`-uniform if the proportion of `ε`-uniform pairs of parts is
greater than `(1 - ε)`.
## Main declarations
* `SimpleGraph.IsUniform`: Graph uniformity of a pair of finsets of vertices.
* `SimpleGraph.nonuniformWitness`: `G.nonuniformWitness ε s t` and `G.nonuniformWitness ε t s`
together witness the non-uniformity of `s` and `t`.
* `Finpartition.nonUniforms`: Nonuniform pairs of parts of a partition.
* `Finpartition.IsUniform`: Uniformity of a partition.
* `Finpartition.nonuniformWitnesses`: For each non-uniform pair of parts of a partition, pick
witnesses of non-uniformity and dump them all together.
## References
[Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
-/
open Finset
variable {α 𝕜 : Type*} [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜]
/-! ### Graph uniformity -/
namespace SimpleGraph
variable (G : SimpleGraph α) [DecidableRel G.Adj] (ε : 𝕜) {s t : Finset α} {a b : α}
/-- A pair of finsets of vertices is `ε`-uniform (aka `ε`-regular) iff their edge density is close
to the density of any big enough pair of subsets. Intuitively, the edges between them are
random-like. -/
def IsUniform (s t : Finset α) : Prop :=
∀ ⦃s'⦄, s' ⊆ s → ∀ ⦃t'⦄, t' ⊆ t → (#s : 𝕜) * ε ≤ #s' →
(#t : 𝕜) * ε ≤ #t' → |(G.edgeDensity s' t' : 𝕜) - (G.edgeDensity s t : 𝕜)| < ε
variable {G ε}
instance IsUniform.instDecidableRel : DecidableRel (G.IsUniform ε) := by
unfold IsUniform; infer_instance
theorem IsUniform.mono {ε' : 𝕜} (h : ε ≤ ε') (hε : IsUniform G ε s t) : IsUniform G ε' s t :=
fun s' hs' t' ht' hs ht => by
refine (hε hs' ht' (le_trans ?_ hs) (le_trans ?_ ht)).trans_le h <;> gcongr
omit [IsStrictOrderedRing 𝕜] in
theorem IsUniform.symm : Symmetric (IsUniform G ε) := fun s t h t' ht' s' hs' ht hs => by
rw [edgeDensity_comm _ t', edgeDensity_comm _ t]
exact h hs' ht' hs ht
variable (G)
omit [IsStrictOrderedRing 𝕜] in
theorem isUniform_comm : IsUniform G ε s t ↔ IsUniform G ε t s :=
⟨fun h => h.symm, fun h => h.symm⟩
lemma isUniform_one : G.IsUniform (1 : 𝕜) s t := by
intro s' hs' t' ht' hs ht
rw [mul_one] at hs ht
rw [eq_of_subset_of_card_le hs' (Nat.cast_le.1 hs),
eq_of_subset_of_card_le ht' (Nat.cast_le.1 ht), sub_self, abs_zero]
exact zero_lt_one
variable {G}
lemma IsUniform.pos (hG : G.IsUniform ε s t) : 0 < ε :=
not_le.1 fun hε ↦ (hε.trans <| abs_nonneg _).not_gt <| hG (empty_subset _) (empty_subset _)
(by simpa using mul_nonpos_of_nonneg_of_nonpos (Nat.cast_nonneg _) hε)
(by simpa using mul_nonpos_of_nonneg_of_nonpos (Nat.cast_nonneg _) hε)
@[simp] lemma isUniform_singleton : G.IsUniform ε {a} {b} ↔ 0 < ε := by
refine ⟨IsUniform.pos, fun hε s' hs' t' ht' hs ht ↦ ?_⟩
rw [card_singleton, Nat.cast_one, one_mul] at hs ht
obtain rfl | rfl := Finset.subset_singleton_iff.1 hs'
· replace hs : ε ≤ 0 := by simpa using hs
exact (hε.not_ge hs).elim
obtain rfl | rfl := Finset.subset_singleton_iff.1 ht'
· replace ht : ε ≤ 0 := by simpa using ht
exact (hε.not_ge ht).elim
· rwa [sub_self, abs_zero]
theorem not_isUniform_zero : ¬G.IsUniform (0 : 𝕜) s t := fun h =>
(abs_nonneg _).not_gt <| h (empty_subset _) (empty_subset _) (by simp) (by simp)
theorem not_isUniform_iff :
¬G.IsUniform ε s t ↔ ∃ s', s' ⊆ s ∧ ∃ t', t' ⊆ t ∧ #s * ε ≤ #s' ∧
#t * ε ≤ #t' ∧ ε ≤ |G.edgeDensity s' t' - G.edgeDensity s t| := by
unfold IsUniform
simp only [not_forall, not_lt, exists_prop, Rat.cast_abs, Rat.cast_sub]
variable (G)
/-- An arbitrary pair of subsets witnessing the non-uniformity of `(s, t)`. If `(s, t)` is uniform,
returns `(s, t)`. Witnesses for `(s, t)` and `(t, s)` don't necessarily match. See
`SimpleGraph.nonuniformWitness`. -/
noncomputable def nonuniformWitnesses (ε : 𝕜) (s t : Finset α) : Finset α × Finset α :=
if h : ¬G.IsUniform ε s t then
((not_isUniform_iff.1 h).choose, (not_isUniform_iff.1 h).choose_spec.2.choose)
else (s, t)
theorem left_nonuniformWitnesses_subset (h : ¬G.IsUniform ε s t) :
(G.nonuniformWitnesses ε s t).1 ⊆ s := by
rw [nonuniformWitnesses, dif_pos h]
exact (not_isUniform_iff.1 h).choose_spec.1
theorem left_nonuniformWitnesses_card (h : ¬G.IsUniform ε s t) :
#s * ε ≤ #(G.nonuniformWitnesses ε s t).1 := by
rw [nonuniformWitnesses, dif_pos h]
exact (not_isUniform_iff.1 h).choose_spec.2.choose_spec.2.1
theorem right_nonuniformWitnesses_subset (h : ¬G.IsUniform ε s t) :
(G.nonuniformWitnesses ε s t).2 ⊆ t := by
rw [nonuniformWitnesses, dif_pos h]
exact (not_isUniform_iff.1 h).choose_spec.2.choose_spec.1
theorem right_nonuniformWitnesses_card (h : ¬G.IsUniform ε s t) :
#t * ε ≤ #(G.nonuniformWitnesses ε s t).2 := by
rw [nonuniformWitnesses, dif_pos h]
exact (not_isUniform_iff.1 h).choose_spec.2.choose_spec.2.2.1
theorem nonuniformWitnesses_spec (h : ¬G.IsUniform ε s t) :
ε ≤
|G.edgeDensity (G.nonuniformWitnesses ε s t).1 (G.nonuniformWitnesses ε s t).2 -
G.edgeDensity s t| := by
rw [nonuniformWitnesses, dif_pos h]
exact (not_isUniform_iff.1 h).choose_spec.2.choose_spec.2.2.2
open scoped Classical in
/-- Arbitrary witness of non-uniformity. `G.nonuniformWitness ε s t` and
`G.nonuniformWitness ε t s` form a pair of subsets witnessing the non-uniformity of `(s, t)`. If
`(s, t)` is uniform, returns `s`. -/
noncomputable def nonuniformWitness (ε : 𝕜) (s t : Finset α) : Finset α :=
if WellOrderingRel s t then (G.nonuniformWitnesses ε s t).1 else (G.nonuniformWitnesses ε t s).2
theorem nonuniformWitness_subset (h : ¬G.IsUniform ε s t) : G.nonuniformWitness ε s t ⊆ s := by
unfold nonuniformWitness
split_ifs
· exact G.left_nonuniformWitnesses_subset h
· exact G.right_nonuniformWitnesses_subset fun i => h i.symm
theorem le_card_nonuniformWitness (h : ¬G.IsUniform ε s t) :
#s * ε ≤ #(G.nonuniformWitness ε s t) := by
unfold nonuniformWitness
split_ifs
· exact G.left_nonuniformWitnesses_card h
· exact G.right_nonuniformWitnesses_card fun i => h i.symm
theorem nonuniformWitness_spec (h₁ : s ≠ t) (h₂ : ¬G.IsUniform ε s t) : ε ≤ |G.edgeDensity
(G.nonuniformWitness ε s t) (G.nonuniformWitness ε t s) - G.edgeDensity s t| := by
unfold nonuniformWitness
rcases trichotomous_of WellOrderingRel s t with (lt | rfl | gt)
· rw [if_pos lt, if_neg (asymm lt)]
exact G.nonuniformWitnesses_spec h₂
· cases h₁ rfl
· rw [if_neg (asymm gt), if_pos gt, edgeDensity_comm, edgeDensity_comm _ s]
apply G.nonuniformWitnesses_spec fun i => h₂ i.symm
end SimpleGraph
/-! ### Uniform partitions -/
variable [DecidableEq α] {A : Finset α} (P : Finpartition A) (G : SimpleGraph α)
[DecidableRel G.Adj] {ε δ : 𝕜} {u v : Finset α}
namespace Finpartition
/-- The pairs of parts of a partition `P` which are not `ε`-dense in a graph `G`. Note that we
dismiss the diagonal. We do not care whether `s` is `ε`-dense with itself. -/
def sparsePairs (ε : 𝕜) : Finset (Finset α × Finset α) :=
P.parts.offDiag.filter fun (u, v) ↦ G.edgeDensity u v < ε
omit [IsStrictOrderedRing 𝕜] in
@[simp]
lemma mk_mem_sparsePairs (u v : Finset α) (ε : 𝕜) :
(u, v) ∈ P.sparsePairs G ε ↔ u ∈ P.parts ∧ v ∈ P.parts ∧ u ≠ v ∧ G.edgeDensity u v < ε := by
rw [sparsePairs, mem_filter, mem_offDiag, and_assoc, and_assoc]
omit [IsStrictOrderedRing 𝕜] in
lemma sparsePairs_mono {ε ε' : 𝕜} (h : ε ≤ ε') : P.sparsePairs G ε ⊆ P.sparsePairs G ε' :=
monotone_filter_right _ fun _ _ ↦ h.trans_lt'
/-- The pairs of parts of a partition `P` which are not `ε`-uniform in a graph `G`. Note that we
dismiss the diagonal. We do not care whether `s` is `ε`-uniform with itself. -/
def nonUniforms (ε : 𝕜) : Finset (Finset α × Finset α) :=
P.parts.offDiag.filter fun (u, v) ↦ ¬G.IsUniform ε u v
omit [IsStrictOrderedRing 𝕜] in
@[simp] lemma mk_mem_nonUniforms :
(u, v) ∈ P.nonUniforms G ε ↔ u ∈ P.parts ∧ v ∈ P.parts ∧ u ≠ v ∧ ¬G.IsUniform ε u v := by
rw [nonUniforms, mem_filter, mem_offDiag, and_assoc, and_assoc]
theorem nonUniforms_mono {ε ε' : 𝕜} (h : ε ≤ ε') : P.nonUniforms G ε' ⊆ P.nonUniforms G ε :=
monotone_filter_right _ fun _ _ => mt <| SimpleGraph.IsUniform.mono h
theorem nonUniforms_bot (hε : 0 < ε) : (⊥ : Finpartition A).nonUniforms G ε = ∅ := by
rw [eq_empty_iff_forall_notMem]
rintro ⟨u, v⟩
simp only [mk_mem_nonUniforms, parts_bot, mem_map, not_and,
Classical.not_not, exists_imp]; dsimp
rintro x ⟨_, rfl⟩ y ⟨_, rfl⟩ _
rwa [SimpleGraph.isUniform_singleton]
/-- A finpartition of a graph's vertex set is `ε`-uniform (aka `ε`-regular) iff the proportion of
its pairs of parts that are not `ε`-uniform is at most `ε`. -/
def IsUniform (ε : 𝕜) : Prop :=
(#(P.nonUniforms G ε) : 𝕜) ≤ (#P.parts * (#P.parts - 1) : ℕ) * ε
lemma bot_isUniform (hε : 0 < ε) : (⊥ : Finpartition A).IsUniform G ε := by
rw [Finpartition.IsUniform, Finpartition.card_bot, nonUniforms_bot _ hε, Finset.card_empty,
Nat.cast_zero]
exact mul_nonneg (Nat.cast_nonneg _) hε.le
lemma isUniform_one : P.IsUniform G (1 : 𝕜) := by
rw [IsUniform, mul_one, Nat.cast_le]
refine (card_filter_le _
(fun uv => ¬SimpleGraph.IsUniform G 1 (Prod.fst uv) (Prod.snd uv))).trans ?_
rw [offDiag_card, Nat.mul_sub_left_distrib, mul_one]
variable {P G}
theorem IsUniform.mono {ε ε' : 𝕜} (hP : P.IsUniform G ε) (h : ε ≤ ε') : P.IsUniform G ε' :=
((Nat.cast_le.2 <| card_le_card <| P.nonUniforms_mono G h).trans hP).trans <| by gcongr
omit [IsStrictOrderedRing 𝕜] in
theorem isUniformOfEmpty (hP : P.parts = ∅) : P.IsUniform G ε := by
simp [IsUniform, hP, nonUniforms]
omit [IsStrictOrderedRing 𝕜] in
theorem nonempty_of_not_uniform (h : ¬P.IsUniform G ε) : P.parts.Nonempty :=
nonempty_of_ne_empty fun h₁ => h <| isUniformOfEmpty h₁
variable (P G ε) (s : Finset α)
/-- A choice of witnesses of non-uniformity among the parts of a finpartition. -/
noncomputable def nonuniformWitnesses : Finset (Finset α) :=
{t ∈ P.parts | s ≠ t ∧ ¬G.IsUniform ε s t}.image (G.nonuniformWitness ε s)
variable {P G ε s} {t : Finset α}
lemma card_nonuniformWitnesses_le :
#(P.nonuniformWitnesses G ε s) ≤ #{t ∈ P.parts | s ≠ t ∧ ¬G.IsUniform ε s t} := card_image_le
theorem nonuniformWitness_mem_nonuniformWitnesses (h : ¬G.IsUniform ε s t) (ht : t ∈ P.parts)
(hst : s ≠ t) : G.nonuniformWitness ε s t ∈ P.nonuniformWitnesses G ε s :=
mem_image_of_mem _ <| mem_filter.2 ⟨ht, hst, h⟩
/-! ### Equipartitions -/
open SimpleGraph in
lemma IsEquipartition.card_interedges_sparsePairs_le' (hP : P.IsEquipartition)
(hε : 0 ≤ ε) :
#((P.sparsePairs G ε).biUnion fun (U, V) ↦ G.interedges U V) ≤ ε * (#A + #P.parts) ^ 2 := by
calc
_ ≤ ∑ UV ∈ P.sparsePairs G ε, (#(G.interedges UV.1 UV.2) : 𝕜) := mod_cast card_biUnion_le
_ ≤ ∑ UV ∈ P.sparsePairs G ε, ε * (#UV.1 * #UV.2) := ?_
_ ≤ ∑ UV ∈ P.parts.offDiag, ε * (#UV.1 * #UV.2) := by gcongr; apply filter_subset
_ = ε * ∑ UV ∈ P.parts.offDiag, (#UV.1 * #UV.2 : 𝕜) := (mul_sum _ _ _).symm
_ ≤ _ := ?_
· gcongr with UV hUV
obtain ⟨U, V⟩ := UV
simp [mk_mem_sparsePairs, ← card_interedges_div_card] at hUV
refine ((div_lt_iff₀ ?_).1 hUV.2.2.2).le
exact mul_pos (Nat.cast_pos.2 (P.nonempty_of_mem_parts hUV.1).card_pos)
(Nat.cast_pos.2 (P.nonempty_of_mem_parts hUV.2.1).card_pos)
norm_cast
gcongr
calc
(_ : ℕ) ≤ _ := sum_le_card_nsmul P.parts.offDiag (fun i ↦ #i.1 * #i.2)
((#A / #P.parts + 1) ^ 2 : ℕ) ?_
_ ≤ (#P.parts * (#A / #P.parts) + #P.parts) ^ 2 := ?_
_ ≤ _ := by gcongr; apply Nat.mul_div_le
· simp only [Prod.forall, and_imp, mem_offDiag, sq]
rintro U V hU hV -
exact_mod_cast Nat.mul_le_mul (hP.card_part_le_average_add_one hU)
(hP.card_part_le_average_add_one hV)
· rw [smul_eq_mul, offDiag_card, Nat.mul_sub_right_distrib, ← sq, ← mul_pow, mul_add_one (α := ℕ)]
exact Nat.sub_le _ _
lemma IsEquipartition.card_interedges_sparsePairs_le (hP : P.IsEquipartition) (hε : 0 ≤ ε) :
#((P.sparsePairs G ε).biUnion fun (U, V) ↦ G.interedges U V) ≤ 4 * ε * #A ^ 2 := by
calc
_ ≤ _ := hP.card_interedges_sparsePairs_le' hε
_ ≤ ε * (#A + #A) ^ 2 := by gcongr; exact P.card_parts_le_card
_ = _ := by ring
private lemma aux {i j : ℕ} (hj : 0 < j) : j * (j - 1) * (i / j + 1) ^ 2 < (i + j) ^ 2 := by
have : j * (j - 1) < j ^ 2 := by
rw [sq]; exact Nat.mul_lt_mul_of_pos_left (Nat.sub_lt hj zero_lt_one) hj
apply (Nat.mul_lt_mul_of_pos_right this <| pow_pos Nat.succ_pos' _).trans_le
rw [← mul_pow, Nat.mul_succ]
gcongr
apply Nat.mul_div_le
lemma IsEquipartition.card_biUnion_offDiag_le' (hP : P.IsEquipartition) :
(#(P.parts.biUnion offDiag) : 𝕜) ≤ #A * (#A + #P.parts) / #P.parts := by
obtain h | h := P.parts.eq_empty_or_nonempty
· simp [h]
calc
_ ≤ (#P.parts : 𝕜) * (↑(#A / #P.parts) * ↑(#A / #P.parts + 1)) :=
mod_cast card_biUnion_le_card_mul _ _ _ fun U hU ↦ ?_
_ = #P.parts * ↑(#A / #P.parts) * ↑(#A / #P.parts + 1) := by rw [mul_assoc]
_ ≤ #A * (#A / #P.parts + 1) :=
mul_le_mul (mod_cast Nat.mul_div_le _ _) ?_ (by positivity) (by positivity)
_ = _ := by rw [← div_add_same (mod_cast h.card_pos.ne'), mul_div_assoc]
· simpa using Nat.cast_div_le
suffices (#U - 1) * #U ≤ #A / #P.parts * (#A / #P.parts + 1) by
rwa [Nat.mul_sub_right_distrib, one_mul, ← offDiag_card] at this
have := hP.card_part_le_average_add_one hU
refine Nat.mul_le_mul ((Nat.sub_le_sub_right this 1).trans ?_) this
simp only [Nat.add_succ_sub_one, add_zero, le_rfl]
lemma IsEquipartition.card_biUnion_offDiag_le (hε : 0 < ε) (hP : P.IsEquipartition)
(hP' : 4 / ε ≤ #P.parts) : #(P.parts.biUnion offDiag) ≤ ε / 2 * #A ^ 2 := by
obtain rfl | hA : A = ⊥ ∨ _ := A.eq_empty_or_nonempty
· simp [Subsingleton.elim P ⊥]
apply hP.card_biUnion_offDiag_le'.trans
rw [div_le_iff₀ (Nat.cast_pos.2 (P.parts_nonempty hA.ne_empty).card_pos)]
have : (#A : 𝕜) + #P.parts ≤ 2 * #A := by
rw [two_mul]; gcongr; exact P.card_parts_le_card
refine (mul_le_mul_of_nonneg_left this <| by positivity).trans ?_
suffices 1 ≤ ε / 4 * #P.parts by
rw [mul_left_comm, ← sq]
convert mul_le_mul_of_nonneg_left this (mul_nonneg zero_le_two <| sq_nonneg (#A : 𝕜))
using 1 <;> ring
rwa [← div_le_iff₀', one_div_div]
positivity
lemma IsEquipartition.sum_nonUniforms_lt' (hA : A.Nonempty) (hε : 0 < ε) (hP : P.IsEquipartition)
(hG : P.IsUniform G ε) :
∑ i ∈ P.nonUniforms G ε, (#i.1 * #i.2 : 𝕜) < ε * (#A + #P.parts) ^ 2 := by
calc
_ ≤ #(P.nonUniforms G ε) • (↑(#A / #P.parts + 1) : 𝕜) ^ 2 :=
sum_le_card_nsmul _ _ _ ?_
_ = _ := nsmul_eq_mul _ _
_ ≤ _ := mul_le_mul_of_nonneg_right hG <| by positivity
_ < _ := ?_
· simp only [Prod.forall, Finpartition.mk_mem_nonUniforms, and_imp]
rintro U V hU hV - -
rw [sq, ← Nat.cast_mul, ← Nat.cast_mul, Nat.cast_le]
exact Nat.mul_le_mul (hP.card_part_le_average_add_one hU)
(hP.card_part_le_average_add_one hV)
· rw [mul_right_comm _ ε, mul_comm ε]
apply mul_lt_mul_of_pos_right _ hε
norm_cast
exact aux (P.parts_nonempty hA.ne_empty).card_pos
lemma IsEquipartition.sum_nonUniforms_lt (hA : A.Nonempty) (hε : 0 < ε) (hP : P.IsEquipartition)
(hG : P.IsUniform G ε) :
#((P.nonUniforms G ε).biUnion fun (U, V) ↦ U ×ˢ V) < 4 * ε * #A ^ 2 := by
calc
_ ≤ ∑ i ∈ P.nonUniforms G ε, (#i.1 * #i.2 : 𝕜) := by
norm_cast; simp_rw [← card_product]; exact card_biUnion_le
_ < _ := hP.sum_nonUniforms_lt' hA hε hG
_ ≤ ε * (#A + #A) ^ 2 := by gcongr; exact P.card_parts_le_card
_ = _ := by ring
end Finpartition
/-! ### Reduced graph -/
namespace SimpleGraph
/-- The reduction of the graph `G` along partition `P` has edges between `ε`-uniform pairs of parts
that have edge density at least `δ`. -/
@[simps] def regularityReduced (ε δ : 𝕜) : SimpleGraph α where
Adj a b := G.Adj a b ∧
∃ U ∈ P.parts, ∃ V ∈ P.parts, a ∈ U ∧ b ∈ V ∧ U ≠ V ∧ G.IsUniform ε U V ∧ δ ≤ G.edgeDensity U V
symm a b := by
rintro ⟨ab, U, UP, V, VP, xU, yV, UV, GUV, εUV⟩
refine ⟨G.symm ab, V, VP, U, UP, yV, xU, UV.symm, GUV.symm, ?_⟩
rwa [edgeDensity_comm]
loopless a h := G.loopless a h.1
instance regularityReduced.instDecidableRel_adj : DecidableRel (G.regularityReduced P ε δ).Adj := by
unfold regularityReduced; infer_instance
variable {G P}
omit [IsStrictOrderedRing 𝕜] in
lemma regularityReduced_le : G.regularityReduced P ε δ ≤ G := fun _ _ ↦ And.left
lemma regularityReduced_mono {ε₁ ε₂ : 𝕜} (hε : ε₁ ≤ ε₂) :
G.regularityReduced P ε₁ δ ≤ G.regularityReduced P ε₂ δ :=
fun _a _b ⟨hab, U, hU, V, hV, ha, hb, hUV, hGε, hGδ⟩ ↦
⟨hab, U, hU, V, hV, ha, hb, hUV, hGε.mono hε, hGδ⟩
omit [IsStrictOrderedRing 𝕜] in
lemma regularityReduced_anti {δ₁ δ₂ : 𝕜} (hδ : δ₁ ≤ δ₂) :
G.regularityReduced P ε δ₂ ≤ G.regularityReduced P ε δ₁ :=
fun _a _b ⟨hab, U, hU, V, hV, ha, hb, hUV, hUVε, hUVδ⟩ ↦
⟨hab, U, hU, V, hV, ha, hb, hUV, hUVε, hδ.trans hUVδ⟩
omit [IsStrictOrderedRing 𝕜] in
lemma unreduced_edges_subset :
(A ×ˢ A).filter (fun (x, y) ↦ G.Adj x y ∧ ¬ (G.regularityReduced P (ε / 8) (ε / 4)).Adj x y) ⊆
(P.nonUniforms G (ε / 8)).biUnion (fun (U, V) ↦ U ×ˢ V) ∪ P.parts.biUnion offDiag ∪
(P.sparsePairs G (ε / 4)).biUnion fun (U, V) ↦ G.interedges U V := by
rintro ⟨x, y⟩
simp only [mem_filter, regularityReduced_adj, not_and, not_exists,
not_le, mem_biUnion, mem_union, mem_product, Prod.exists, mem_offDiag, and_imp,
or_assoc, and_assoc, P.mk_mem_nonUniforms, Finpartition.mk_mem_sparsePairs, mem_interedges_iff]
intro hx hy h h'
replace h' := h' h
obtain ⟨U, hU, hx⟩ := P.exists_mem hx
obtain ⟨V, hV, hy⟩ := P.exists_mem hy
obtain rfl | hUV := eq_or_ne U V
· exact Or.inr (Or.inl ⟨U, hU, hx, hy, G.ne_of_adj h⟩)
by_cases h₂ : G.IsUniform (ε / 8) U V
· exact Or.inr <| Or.inr ⟨U, V, hU, hV, hUV, h' _ hU _ hV hx hy hUV h₂, hx, hy, h⟩
· exact Or.inl ⟨U, V, hU, hV, hUV, h₂, hx, hy⟩
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Regularity/Equitabilise.lean | import Mathlib.Algebra.Order.Ring.Canonical
import Mathlib.Order.Partition.Equipartition
/-!
# Equitabilising a partition
This file allows to blow partitions up into parts of controlled size. Given a partition `P` and
`a b m : ℕ`, we want to find a partition `Q` with `a` parts of size `m` and `b` parts of size
`m + 1` such that all parts of `P` are "as close as possible" to unions of parts of `Q`. By
"as close as possible", we mean that each part of `P` can be written as the union of some parts of
`Q` along with at most `m` other elements.
## Main declarations
* `Finpartition.equitabilise`: `P.equitabilise h` where `h : a * m + b * (m + 1)` is a partition
with `a` parts of size `m` and `b` parts of size `m + 1` which almost refines `P`.
* `Finpartition.exists_equipartition_card_eq`: We can find equipartitions of arbitrary size.
## References
[Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
-/
open Finset Nat
namespace Finpartition
variable {α : Type*} [DecidableEq α] {s t : Finset α} {m n a b : ℕ} {P : Finpartition s}
/-- Given a partition `P` of `s`, as well as a proof that `a * m + b * (m + 1) = #s`, we can
find a new partition `Q` of `s` where each part has size `m` or `m + 1`, every part of `P` is the
union of parts of `Q` plus at most `m` extra elements, there are `b` parts of size `m + 1` and
(provided `m > 0`, because a partition does not have parts of size `0`) there are `a` parts of size
`m` and hence `a + b` parts in total. -/
theorem equitabilise_aux (hs : a * m + b * (m + 1) = #s) :
∃ Q : Finpartition s,
(∀ x : Finset α, x ∈ Q.parts → #x = m ∨ #x = m + 1) ∧
(∀ x, x ∈ P.parts → #(x \ {y ∈ Q.parts | y ⊆ x}.biUnion id) ≤ m) ∧
#{i ∈ Q.parts | #i = m + 1} = b := by
-- Get rid of the easy case `m = 0`
obtain rfl | m_pos := m.eq_zero_or_pos
· refine ⟨⊥, by simp, ?_, by simpa [Finset.filter_true_of_mem] using hs.symm⟩
simp only [le_zero_iff, card_eq_zero, mem_biUnion, mem_filter, id,
and_assoc, sdiff_eq_empty_iff_subset, subset_iff]
exact fun x hx a ha =>
⟨{a}, mem_map_of_mem _ (P.le hx ha), singleton_subset_iff.2 ha, mem_singleton_self _⟩
-- Prove the case `m > 0` by strong induction on `s`
induction s using Finset.strongInduction generalizing a b with | H s ih => _
-- If `a = b = 0`, then `s = ∅` and we can partition into zero parts
by_cases hab : a = 0 ∧ b = 0
· -- Rewrite using `← bot_eq_empty` because we have theorems about `Finpartition ⊥`,
-- and nothing about `Finpartition ∅`, even though they are defeq in this case.
-- TODO: specialize the `Finpartition ⊥` lemmas to `Finpartition ∅`?
simp only [hab.1, hab.2, add_zero, zero_mul, eq_comm, card_eq_zero, ← bot_eq_empty] at hs
subst hs
exact ⟨Finpartition.empty _, by simp, by simp [Unique.eq_default P, -bot_eq_empty],
by simp [hab.2]⟩
simp_rw [not_and_or, ← Ne.eq_def, ← pos_iff_ne_zero] at hab
-- `n` will be the size of the smallest part
set n := if 0 < a then m else m + 1 with hn
-- Some easy facts about it
obtain ⟨hn₀, hn₁, hn₂, hn₃⟩ : 0 < n ∧ n ≤ m + 1 ∧ n ≤ a * m + b * (m + 1) ∧
ite (0 < a) (a - 1) a * m + ite (0 < a) b (b - 1) * (m + 1) = #s - n := by
rw [hn, ← hs]
split_ifs with h <;> rw [tsub_mul, one_mul]
· refine ⟨m_pos, le_succ _, le_add_right (Nat.le_mul_of_pos_left _ ‹0 < a›), ?_⟩
rw [tsub_add_eq_add_tsub (Nat.le_mul_of_pos_left _ h)]
· refine ⟨succ_pos', le_rfl,
le_add_left (Nat.le_mul_of_pos_left _ <| hab.resolve_left ‹¬0 < a›), ?_⟩
rw [← add_tsub_assoc_of_le (Nat.le_mul_of_pos_left _ <| hab.resolve_left ‹¬0 < a›)]
/- We will call the inductive hypothesis on a partition of `s \ t` for a carefully chosen `t ⊆ s`.
To decide which, however, we must distinguish the case where all parts of `P` have size `m` (in
which case we take `t` to be an arbitrary subset of `s` of size `n`) from the case where at
least one part `u` of `P` has size `m + 1` (in which case we take `t` to be an arbitrary subset
of `u` of size `n`). The rest of each branch is just tedious calculations to satisfy the
induction hypothesis. -/
by_cases! h : ∀ u ∈ P.parts, #u < m + 1
· obtain ⟨t, hts, htn⟩ := exists_subset_card_eq (hn₂.trans_eq hs)
have ht : t.Nonempty := by rwa [← card_pos, htn]
have hcard : ite (0 < a) (a - 1) a * m + ite (0 < a) b (b - 1) * (m + 1) = #(s \ t) := by
rw [card_sdiff_of_subset ‹t ⊆ s›, htn, hn₃]
obtain ⟨R, hR₁, _, hR₃⟩ :=
@ih (s \ t) (sdiff_ssubset hts ‹t.Nonempty›) (if 0 < a then a - 1 else a)
(if 0 < a then b else b - 1) (P.avoid t) hcard
refine ⟨R.extend ht.ne_empty sdiff_disjoint (sdiff_sup_cancel hts), ?_, ?_, ?_⟩
· simp only [extend_parts, mem_insert, forall_eq_or_imp, and_iff_left hR₁, htn, hn]
exact ite_eq_or_eq _ _ _
· exact fun x hx => (card_le_card sdiff_subset).trans (Nat.lt_succ_iff.1 <| h _ hx)
simp_rw [extend_parts, filter_insert, htn, n, m.succ_ne_self.symm.ite_eq_right_iff]
split_ifs with ha
· rw [hR₃, if_pos ha]
rw [card_insert_of_notMem, hR₃, if_neg ha, tsub_add_cancel_of_le]
· exact hab.resolve_left ha
· intro H; exact ht.ne_empty (le_sdiff_right.1 <| R.le <| filter_subset _ _ H)
obtain ⟨u, hu₁, hu₂⟩ := h
obtain ⟨t, htu, htn⟩ := exists_subset_card_eq (hn₁.trans hu₂)
have ht : t.Nonempty := by rwa [← card_pos, htn]
have hcard : ite (0 < a) (a - 1) a * m + ite (0 < a) b (b - 1) * (m + 1) = #(s \ t) := by
rw [card_sdiff_of_subset (htu.trans <| P.le hu₁), htn, hn₃]
obtain ⟨R, hR₁, hR₂, hR₃⟩ :=
@ih (s \ t) (sdiff_ssubset (htu.trans <| P.le hu₁) ht) (if 0 < a then a - 1 else a)
(if 0 < a then b else b - 1) (P.avoid t) hcard
refine
⟨R.extend ht.ne_empty sdiff_disjoint (sdiff_sup_cancel <| htu.trans <| P.le hu₁), ?_, ?_, ?_⟩
· simp only [mem_insert, forall_eq_or_imp, extend_parts, and_iff_left hR₁, htn, hn]
exact ite_eq_or_eq _ _ _
· conv in _ ∈ _ => rw [← insert_erase hu₁]
simp only [mem_insert, forall_eq_or_imp, extend_parts]
refine ⟨?_, fun x hx => (card_le_card ?_).trans <| hR₂ x ?_⟩
· simp only [filter_insert, if_pos htu, biUnion_insert, id]
obtain rfl | hut := eq_or_ne u t
· rw [sdiff_eq_empty_iff_subset.2 subset_union_left]
exact bot_le
refine
(card_le_card fun i => ?_).trans
(hR₂ (u \ t) <| P.mem_avoid.2 ⟨u, hu₁, fun i => hut <| i.antisymm htu, rfl⟩)
simpa using fun hi₁ hi₂ hi₃ =>
⟨⟨hi₁, hi₂⟩, fun x hx hx' => hi₃ _ hx <| hx'.trans sdiff_subset⟩
· apply sdiff_subset_sdiff Subset.rfl (biUnion_subset_biUnion_of_subset_left _ _)
exact filter_subset_filter _ (subset_insert _ _)
simp only [avoid, ofErase, mem_erase, mem_image, bot_eq_empty]
exact
⟨(nonempty_of_mem_parts _ <| mem_of_mem_erase hx).ne_empty, _, mem_of_mem_erase hx,
(disjoint_of_subset_right htu <|
P.disjoint (mem_of_mem_erase hx) hu₁ <| ne_of_mem_erase hx).sdiff_eq_left⟩
simp only [extend_parts, filter_insert, htn, hn, m.succ_ne_self.symm.ite_eq_right_iff]
split_ifs with h
· rw [hR₃, if_pos h]
· rw [card_insert_of_notMem, hR₃, if_neg h, Nat.sub_add_cancel (hab.resolve_left h)]
intro H; exact ht.ne_empty (le_sdiff_right.1 <| R.le <| filter_subset _ _ H)
variable (h : a * m + b * (m + 1) = #s)
/-- Given a partition `P` of `s`, as well as a proof that `a * m + b * (m + 1) = #s`, build a
new partition `Q` of `s` where each part has size `m` or `m + 1`, every part of `P` is the union of
parts of `Q` plus at most `m` extra elements, there are `b` parts of size `m + 1` and (provided
`m > 0`, because a partition does not have parts of size `0`) there are `a` parts of size `m` and
hence `a + b` parts in total. -/
noncomputable def equitabilise : Finpartition s :=
(P.equitabilise_aux h).choose
variable {h}
theorem card_eq_of_mem_parts_equitabilise :
t ∈ (P.equitabilise h).parts → #t = m ∨ #t = m + 1 :=
(P.equitabilise_aux h).choose_spec.1 _
theorem equitabilise_isEquipartition : (P.equitabilise h).IsEquipartition :=
Set.equitableOn_iff_exists_eq_eq_add_one.2 ⟨m, fun _ => card_eq_of_mem_parts_equitabilise⟩
variable (P h)
theorem card_filter_equitabilise_big : #{u ∈ (P.equitabilise h).parts | #u = m + 1} = b :=
(P.equitabilise_aux h).choose_spec.2.2
theorem card_filter_equitabilise_small (hm : m ≠ 0) :
#{u ∈ (P.equitabilise h).parts | #u = m} = a := by
refine (mul_eq_mul_right_iff.1 <| (add_left_inj (b * (m + 1))).1 ?_).resolve_right hm
rw [h, ← (P.equitabilise h).sum_card_parts]
have hunion :
(P.equitabilise h).parts =
{u ∈ (P.equitabilise h).parts | #u = m} ∪ {u ∈ (P.equitabilise h).parts | #u = m + 1} := by
rw [← filter_or, filter_true_of_mem]
exact fun x => card_eq_of_mem_parts_equitabilise
nth_rw 2 [hunion]
rw [sum_union, sum_const_nat fun x hx => (mem_filter.1 hx).2,
sum_const_nat fun x hx => (mem_filter.1 hx).2, P.card_filter_equitabilise_big]
refine disjoint_filter_filter' _ _ ?_
intro x ha hb i h
apply succ_ne_self m _
exact (hb i h).symm.trans (ha i h)
theorem card_parts_equitabilise (hm : m ≠ 0) : #(P.equitabilise h).parts = a + b := by
rw [← filter_true_of_mem fun x => card_eq_of_mem_parts_equitabilise, filter_or,
card_union_of_disjoint, P.card_filter_equitabilise_small _ hm, P.card_filter_equitabilise_big]
aesop (add norm disjoint_filter)
theorem card_parts_equitabilise_subset_le :
t ∈ P.parts → #(t \ {u ∈ (P.equitabilise h).parts | u ⊆ t}.biUnion id) ≤ m :=
(Classical.choose_spec <| P.equitabilise_aux h).2.1 t
variable (s)
/-- We can find equipartitions of arbitrary size. -/
theorem exists_equipartition_card_eq (hn : n ≠ 0) (hs : n ≤ #s) :
∃ P : Finpartition s, P.IsEquipartition ∧ #P.parts = n := by
rw [← pos_iff_ne_zero] at hn
have : (n - #s % n) * (#s / n) + #s % n * (#s / n + 1) = #s := by
rw [tsub_mul, mul_add, ← add_assoc,
tsub_add_cancel_of_le (Nat.mul_le_mul_right _ (mod_lt _ hn).le), mul_one, add_comm,
mod_add_div]
refine
⟨(indiscrete (card_pos.1 <| hn.trans_le hs).ne_empty).equitabilise this,
equitabilise_isEquipartition, ?_⟩
rw [card_parts_equitabilise _ _ (Nat.div_pos hs hn).ne', tsub_add_cancel_of_le (mod_lt _ hn).le]
end Finpartition |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Regularity/Bound.lean | import Mathlib.Algebra.BigOperators.Field
import Mathlib.Algebra.Order.Chebyshev
import Mathlib.Analysis.SpecialFunctions.Pow.Real
import Mathlib.Order.Partition.Equipartition
/-!
# Numerical bounds for Szemerédi Regularity Lemma
This file gathers the numerical facts required by the proof of Szemerédi's regularity lemma.
This entire file is internal to the proof of Szemerédi Regularity Lemma.
## Main declarations
* `SzemerediRegularity.stepBound`: During the inductive step, a partition of size `n` is blown to
size at most `stepBound n`.
* `SzemerediRegularity.initialBound`: The size of the partition we start the induction with.
* `SzemerediRegularity.bound`: The upper bound on the size of the partition produced by our version
of Szemerédi's regularity lemma.
## References
[Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
-/
open Finset Fintype Function Real
namespace SzemerediRegularity
/-- Auxiliary function for Szemerédi's regularity lemma. Blowing up a partition of size `n` during
the induction results in a partition of size at most `stepBound n`. -/
def stepBound (n : ℕ) : ℕ :=
n * 4 ^ n
theorem le_stepBound : id ≤ stepBound := fun n =>
Nat.le_mul_of_pos_right _ <| pow_pos (by simp) n
theorem stepBound_mono : Monotone stepBound := fun _ _ h => by unfold stepBound; gcongr; decide
theorem stepBound_pos_iff {n : ℕ} : 0 < stepBound n ↔ 0 < n :=
mul_pos_iff_of_pos_right <| by positivity
alias ⟨_, stepBound_pos⟩ := stepBound_pos_iff
@[norm_cast] lemma coe_stepBound {α : Type*} [Semiring α] (n : ℕ) :
(stepBound n : α) = n * 4 ^ n := by unfold stepBound; norm_cast
end SzemerediRegularity
open SzemerediRegularity
variable {α : Type*} [DecidableEq α] [Fintype α] {P : Finpartition (univ : Finset α)}
{u : Finset α} {ε : ℝ}
local notation3 "m" => (card α / stepBound #P.parts : ℕ)
local notation3 "a" => (card α / #P.parts - m * 4 ^ #P.parts : ℕ)
namespace SzemerediRegularity.Positivity
private theorem eps_pos {ε : ℝ} {n : ℕ} (h : 100 ≤ (4 : ℝ) ^ n * ε ^ 5) : 0 < ε :=
(Odd.pow_pos_iff (by decide)).mp
(pos_of_mul_pos_right ((show 0 < (100 : ℝ) by simp).trans_le h) (by positivity))
private theorem m_pos [Nonempty α] (hPα : #P.parts * 16 ^ #P.parts ≤ card α) : 0 < m :=
Nat.div_pos (hPα.trans' <| by unfold stepBound; gcongr; simp) <|
stepBound_pos (P.parts_nonempty <| univ_nonempty.ne_empty).card_pos
/-- Local extension for the `positivity` tactic: A few facts that are needed many times for the
proof of Szemerédi's regularity lemma. -/
scoped macro "sz_positivity" : tactic =>
`(tactic|
{ try have := m_pos ‹_›
try have := eps_pos ‹_›
positivity })
-- Original meta code
/- meta def positivity_szemeredi_regularity : expr → tactic strictness
| `(%%n / step_bound (finpartition.parts %%P).card) := do
p ← to_expr
``((finpartition.parts %%P).card * 16^(finpartition.parts %%P).card ≤ %%n)
>>= find_assumption,
positive <$> mk_app ``m_pos [p]
| ε := do
typ ← infer_type ε,
unify typ `(ℝ),
p ← to_expr ``(100 ≤ 4 ^ _ * %%ε ^ 5) >>= find_assumption,
positive <$> mk_app ``eps_pos [p] -/
end SzemerediRegularity.Positivity
namespace SzemerediRegularity
open scoped SzemerediRegularity.Positivity
theorem m_pos [Nonempty α] (hPα : #P.parts * 16 ^ #P.parts ≤ card α) : 0 < m := by
sz_positivity
theorem coe_m_add_one_pos : 0 < (m : ℝ) + 1 := by positivity
theorem one_le_m_coe [Nonempty α] (hPα : #P.parts * 16 ^ #P.parts ≤ card α) : (1 : ℝ) ≤ m :=
Nat.one_le_cast.2 <| m_pos hPα
theorem eps_pow_five_pos (hPε : 100 ≤ (4 : ℝ) ^ #P.parts * ε ^ 5) : ↑0 < ε ^ 5 :=
pos_of_mul_pos_right ((by simp : (0 : ℝ) < 100).trans_le hPε) <| by positivity
theorem eps_pos (hPε : 100 ≤ (4 : ℝ) ^ #P.parts * ε ^ 5) : 0 < ε :=
(Odd.pow_pos_iff (by decide)).mp (eps_pow_five_pos hPε)
theorem hundred_div_ε_pow_five_le_m [Nonempty α] (hPα : #P.parts * 16 ^ #P.parts ≤ card α)
(hPε : 100 ≤ (4 : ℝ) ^ #P.parts * ε ^ 5) : 100 / ε ^ 5 ≤ m :=
(div_le_of_le_mul₀ (eps_pow_five_pos hPε).le (by positivity) hPε).trans <| by
norm_cast
rwa [Nat.le_div_iff_mul_le (stepBound_pos (P.parts_nonempty <|
univ_nonempty.ne_empty).card_pos), stepBound, mul_left_comm, ← mul_pow]
theorem hundred_le_m [Nonempty α] (hPα : #P.parts * 16 ^ #P.parts ≤ card α)
(hPε : 100 ≤ (4 : ℝ) ^ #P.parts * ε ^ 5) (hε : ε ≤ 1) : 100 ≤ m :=
mod_cast
(hundred_div_ε_pow_five_le_m hPα hPε).trans'
(le_div_self (by simp) (by sz_positivity) <| pow_le_one₀ (by sz_positivity) hε)
theorem a_add_one_le_four_pow_parts_card : a + 1 ≤ 4 ^ #P.parts := by
have h : 1 ≤ 4 ^ #P.parts := one_le_pow₀ (by simp)
rw [stepBound, ← Nat.div_div_eq_div_mul]
conv_rhs => rw [← Nat.sub_add_cancel h]
rw [add_le_add_iff_right, tsub_le_iff_left, ← Nat.add_sub_assoc h]
exact Nat.le_sub_one_of_lt (Nat.lt_div_mul_add h)
theorem card_aux₁ (hucard : #u = m * 4 ^ #P.parts + a) :
(4 ^ #P.parts - a) * m + a * (m + 1) = #u := by
rw [hucard, mul_add, mul_one, ← add_assoc, ← add_mul,
Nat.sub_add_cancel ((Nat.le_succ _).trans a_add_one_le_four_pow_parts_card), mul_comm]
theorem card_aux₂ (hP : P.IsEquipartition) (hu : u ∈ P.parts) (hucard : #u ≠ m * 4 ^ #P.parts + a) :
(4 ^ #P.parts - (a + 1)) * m + (a + 1) * (m + 1) = #u := by
have : m * 4 ^ #P.parts ≤ card α / #P.parts := by
rw [stepBound, ← Nat.div_div_eq_div_mul]
exact Nat.div_mul_le_self _ _
rw [Nat.add_sub_of_le this] at hucard
rw [(hP.card_parts_eq_average hu).resolve_left hucard, mul_add, mul_one, ← add_assoc, ← add_mul,
Nat.sub_add_cancel a_add_one_le_four_pow_parts_card, ← add_assoc, mul_comm,
Nat.add_sub_of_le this, card_univ]
theorem pow_mul_m_le_card_part (hP : P.IsEquipartition) (hu : u ∈ P.parts) :
(4 : ℝ) ^ #P.parts * m ≤ #u := by
norm_cast
rw [stepBound, ← Nat.div_div_eq_div_mul]
exact (Nat.mul_div_le _ _).trans (hP.average_le_card_part hu)
variable (P ε) (l : ℕ)
/-- Auxiliary function for Szemerédi's regularity lemma. The size of the partition by which we start
blowing. -/
noncomputable def initialBound : ℕ :=
max 7 <| max l <| ⌊log (100 / ε ^ 5) / log 4⌋₊ + 1
theorem le_initialBound : l ≤ initialBound ε l :=
(le_max_left _ _).trans <| le_max_right _ _
theorem seven_le_initialBound : 7 ≤ initialBound ε l :=
le_max_left _ _
theorem initialBound_pos : 0 < initialBound ε l :=
Nat.succ_pos'.trans_le <| seven_le_initialBound _ _
theorem hundred_lt_pow_initialBound_mul {ε : ℝ} (hε : 0 < ε) (l : ℕ) :
100 < ↑4 ^ initialBound ε l * ε ^ 5 := by
rw [← rpow_natCast 4, ← div_lt_iff₀ (pow_pos hε 5), lt_rpow_iff_log_lt _ zero_lt_four, ←
div_lt_iff₀, initialBound, Nat.cast_max, Nat.cast_max]
· push_cast
exact lt_max_of_lt_right (lt_max_of_lt_right <| Nat.lt_floor_add_one _)
· exact log_pos (by simp)
· exact div_pos (by simp) (pow_pos hε 5)
/-- An explicit bound on the size of the equipartition whose existence is given by Szemerédi's
regularity lemma. -/
noncomputable def bound : ℕ :=
(stepBound^[⌊4 / ε ^ 5⌋₊] <| initialBound ε l) *
16 ^ (stepBound^[⌊4 / ε ^ 5⌋₊] <| initialBound ε l)
theorem initialBound_le_bound : initialBound ε l ≤ bound ε l :=
(id_le_iterate_of_id_le le_stepBound _ _).trans <| Nat.le_mul_of_pos_right _ <| by positivity
theorem le_bound : l ≤ bound ε l :=
(le_initialBound ε l).trans <| initialBound_le_bound ε l
theorem bound_pos : 0 < bound ε l :=
(initialBound_pos ε l).trans_le <| initialBound_le_bound ε l
variable {ι 𝕜 : Type*} [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜] {s t : Finset ι} {x : 𝕜}
theorem mul_sq_le_sum_sq (hst : s ⊆ t) (f : ι → 𝕜) (hs : x ^ 2 ≤ ((∑ i ∈ s, f i) / #s) ^ 2)
(hs' : (#s : 𝕜) ≠ 0) : (#s : 𝕜) * x ^ 2 ≤ ∑ i ∈ t, f i ^ 2 := calc
_ ≤ (#s : 𝕜) * ((∑ i ∈ s, f i ^ 2) / #s) := by
gcongr
exact hs.trans sum_div_card_sq_le_sum_sq_div_card
_ = ∑ i ∈ s, f i ^ 2 := mul_div_cancel₀ _ hs'
_ ≤ ∑ i ∈ t, f i ^ 2 := by gcongr
theorem add_div_le_sum_sq_div_card (hst : s ⊆ t) (f : ι → 𝕜) (d : 𝕜) (hx : 0 ≤ x)
(hs : x ≤ |(∑ i ∈ s, f i) / #s - (∑ i ∈ t, f i) / #t|) (ht : d ≤ ((∑ i ∈ t, f i) / #t) ^ 2) :
d + #s / #t * x ^ 2 ≤ (∑ i ∈ t, f i ^ 2) / #t := by
obtain hscard | hscard := ((#s).cast_nonneg : (0 : 𝕜) ≤ #s).eq_or_lt
· simpa [← hscard] using ht.trans sum_div_card_sq_le_sum_sq_div_card
have htcard : (0 : 𝕜) < #t := hscard.trans_le (Nat.cast_le.2 (card_le_card hst))
have h₁ : x ^ 2 ≤ ((∑ i ∈ s, f i) / #s - (∑ i ∈ t, f i) / #t) ^ 2 :=
sq_le_sq.2 (by rwa [abs_of_nonneg hx])
have h₂ : x ^ 2 ≤ ((∑ i ∈ s, (f i - (∑ j ∈ t, f j) / #t)) / #s) ^ 2 := by
apply h₁.trans
rw [sum_sub_distrib, sum_const, nsmul_eq_mul, sub_div, mul_div_cancel_left₀ _ hscard.ne']
grw [ht]
rw [← mul_div_right_comm, le_div_iff₀ htcard, add_mul, div_mul_cancel₀ _ htcard.ne']
have h₃ := mul_sq_le_sum_sq hst (fun i => (f i - (∑ j ∈ t, f j) / #t)) h₂ hscard.ne'
grw [h₃]
simp only [sub_div' htcard.ne', div_pow, ← sum_div, ← mul_div_right_comm _ (#t : 𝕜), ← add_div,
div_le_iff₀ (sq_pos_of_ne_zero htcard.ne'), sub_sq, sum_add_distrib, sum_const,
sum_sub_distrib, mul_pow, ← sum_mul, nsmul_eq_mul, two_mul]
ring_nf
rfl
end SzemerediRegularity
namespace Mathlib.Meta.Positivity
open Lean.Meta Qq
/-- Extension for the `positivity` tactic: `SzemerediRegularity.initialBound` is always positive. -/
@[positivity SzemerediRegularity.initialBound _ _]
def evalInitialBound : PositivityExt where eval {u α} _ _ e := do
match u, α, e with
| 0, ~q(ℕ), ~q(SzemerediRegularity.initialBound $ε $l) =>
assertInstancesCommute
pure (.positive q(SzemerediRegularity.initialBound_pos $ε $l))
| _, _, _ => throwError "not initialBound"
example (ε : ℝ) (l : ℕ) : 0 < SzemerediRegularity.initialBound ε l := by positivity
/-- Extension for the `positivity` tactic: `SzemerediRegularity.bound` is always positive. -/
@[positivity SzemerediRegularity.bound _ _]
def evalBound : PositivityExt where eval {u α} _ _ e := do
match u, α, e with
| 0, ~q(ℕ), ~q(SzemerediRegularity.bound $ε $l) =>
assertInstancesCommute
pure (.positive q(SzemerediRegularity.bound_pos $ε $l))
| _, _, _ => throwError "not bound"
example (ε : ℝ) (l : ℕ) : 0 < SzemerediRegularity.bound ε l := by positivity
end Mathlib.Meta.Positivity |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Regularity/Chunk.lean | import Mathlib.Combinatorics.SimpleGraph.Regularity.Bound
import Mathlib.Combinatorics.SimpleGraph.Regularity.Equitabilise
import Mathlib.Combinatorics.SimpleGraph.Regularity.Uniform
/-!
# Chunk of the increment partition for Szemerédi Regularity Lemma
In the proof of Szemerédi Regularity Lemma, we need to partition each part of a starting partition
to increase the energy. This file defines those partitions of parts and shows that they locally
increase the energy.
This entire file is internal to the proof of Szemerédi Regularity Lemma.
## Main declarations
* `SzemerediRegularity.chunk`: The partition of a part of the starting partition.
* `SzemerediRegularity.edgeDensity_chunk_uniform`: `chunk` does not locally decrease the edge
density between uniform parts too much.
* `SzemerediRegularity.edgeDensity_chunk_not_uniform`: `chunk` locally increases the edge density
between non-uniform parts.
## TODO
Once ported to mathlib4, this file will be a great golfing ground for Heather's new tactic
`gcongr`.
## References
[Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
-/
open Finpartition Finset Fintype Rel Nat
open scoped SzemerediRegularity.Positivity
namespace SzemerediRegularity
variable {α : Type*} [Fintype α] [DecidableEq α] {P : Finpartition (univ : Finset α)}
(hP : P.IsEquipartition) (G : SimpleGraph α) [DecidableRel G.Adj] (ε : ℝ) {U : Finset α}
(hU : U ∈ P.parts) (V : Finset α)
local notation3 "m" => (card α / stepBound #P.parts : ℕ)
/-!
### Definitions
We define `chunk`, the partition of a part, and `star`, the sets of parts of `chunk` that are
contained in the corresponding witness of non-uniformity.
-/
/-- The portion of `SzemerediRegularity.increment` which partitions `U`. -/
noncomputable def chunk : Finpartition U :=
if hUcard : #U = m * 4 ^ #P.parts + (card α / #P.parts - m * 4 ^ #P.parts) then
(atomise U <| P.nonuniformWitnesses G ε U).equitabilise <| card_aux₁ hUcard
else (atomise U <| P.nonuniformWitnesses G ε U).equitabilise <| card_aux₂ hP hU hUcard
-- `hP` and `hU` are used to get that `U` has size
-- `m * 4 ^ #P.parts + a or m * 4 ^ #P.parts + a + 1`
/-- The portion of `SzemerediRegularity.chunk` which is contained in the witness of non-uniformity
of `U` and `V`. -/
noncomputable def star (V : Finset α) : Finset (Finset α) :=
{A ∈ (chunk hP G ε hU).parts | A ⊆ G.nonuniformWitness ε U V}
/-!
### Density estimates
We estimate the density between parts of `chunk`.
-/
theorem biUnion_star_subset_nonuniformWitness :
(star hP G ε hU V).biUnion id ⊆ G.nonuniformWitness ε U V :=
biUnion_subset_iff_forall_subset.2 fun _ hA => (mem_filter.1 hA).2
variable {hP G ε hU V} {𝒜 : Finset (Finset α)} {s : Finset α}
theorem star_subset_chunk : star hP G ε hU V ⊆ (chunk hP G ε hU).parts :=
filter_subset _ _
private theorem card_nonuniformWitness_sdiff_biUnion_star (hV : V ∈ P.parts) (hUV : U ≠ V)
(h₂ : ¬G.IsUniform ε U V) :
#(G.nonuniformWitness ε U V \ (star hP G ε hU V).biUnion id) ≤ 2 ^ (#P.parts - 1) * m := by
have hX : G.nonuniformWitness ε U V ∈ P.nonuniformWitnesses G ε U :=
nonuniformWitness_mem_nonuniformWitnesses h₂ hV hUV
have q : G.nonuniformWitness ε U V \ (star hP G ε hU V).biUnion id ⊆
{B ∈ (atomise U <| P.nonuniformWitnesses G ε U).parts |
B ⊆ G.nonuniformWitness ε U V ∧ B.Nonempty}.biUnion
fun B => B \ {A ∈ (chunk hP G ε hU).parts | A ⊆ B}.biUnion id := by
intro x hx
rw [← biUnion_filter_atomise hX (G.nonuniformWitness_subset h₂), star, mem_sdiff,
mem_biUnion] at hx
simp only [not_exists, mem_biUnion, and_imp, mem_filter,
not_and, mem_sdiff, id, mem_sdiff] at hx ⊢
obtain ⟨⟨B, hB₁, hB₂⟩, hx⟩ := hx
exact ⟨B, hB₁, hB₂, fun A hA AB => hx A hA <| AB.trans hB₁.2.1⟩
apply (card_le_card q).trans (card_biUnion_le.trans _)
trans ∑ B ∈ (atomise U <| P.nonuniformWitnesses G ε U).parts with
B ⊆ G.nonuniformWitness ε U V ∧ B.Nonempty, m
· suffices ∀ B ∈ (atomise U <| P.nonuniformWitnesses G ε U).parts,
#(B \ {A ∈ (chunk hP G ε hU).parts | A ⊆ B}.biUnion id) ≤ m by
exact sum_le_sum fun B hB => this B <| filter_subset _ _ hB
intro B hB
unfold chunk
split_ifs with h₁
· convert card_parts_equitabilise_subset_le _ (card_aux₁ h₁) hB
· convert card_parts_equitabilise_subset_le _ (card_aux₂ hP hU h₁) hB
grw [sum_const, smul_eq_mul, card_filter_atomise_le_two_pow (s := U) hX,
Finpartition.card_nonuniformWitnesses_le, filter_subset] <;> simp
private theorem one_sub_eps_mul_card_nonuniformWitness_le_card_star (hV : V ∈ P.parts)
(hUV : U ≠ V) (hunif : ¬G.IsUniform ε U V) (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5)
(hε₁ : ε ≤ 1) :
(1 - ε / 10) * #(G.nonuniformWitness ε U V) ≤ #((star hP G ε hU V).biUnion id) := by
have hP₁ : 0 < #P.parts := Finset.card_pos.2 ⟨_, hU⟩
have : (↑2 ^ #P.parts : ℝ) * m / (#U * ε) ≤ ε / 10 := by
rw [← div_div, div_le_iff₀']
swap
· sz_positivity
refine le_of_mul_le_mul_left ?_ (pow_pos zero_lt_two #P.parts)
calc
↑2 ^ #P.parts * ((↑2 ^ #P.parts * m : ℝ) / #U) =
((2 : ℝ) * 2) ^ #P.parts * m / #U := by
rw [mul_pow, ← mul_div_assoc, mul_assoc]
_ = ↑4 ^ #P.parts * m / #U := by norm_num
_ ≤ 1 := div_le_one_of_le₀ (pow_mul_m_le_card_part hP hU) (cast_nonneg _)
_ ≤ ↑2 ^ #P.parts * ε ^ 2 / 10 := by
refine (one_le_sq_iff₀ <| by positivity).1 ?_
rw [div_pow, mul_pow, pow_right_comm, ← pow_mul ε, one_le_div (by positivity)]
calc
(↑10 ^ 2) = 100 := by norm_num
_ ≤ ↑4 ^ #P.parts * ε ^ 5 := hPε
_ ≤ ↑4 ^ #P.parts * ε ^ 4 := by
gcongr _ * ?_
exact pow_le_pow_of_le_one (by sz_positivity) hε₁ (by decide)
_ = (↑2 ^ 2) ^ #P.parts * ε ^ (2 * 2) := by norm_num
_ = ↑2 ^ #P.parts * (ε * (ε / 10)) := by rw [mul_div_assoc, sq, mul_div_assoc]
calc
(↑1 - ε / 10) * #(G.nonuniformWitness ε U V) ≤
(↑1 - ↑2 ^ #P.parts * m / (#U * ε)) * #(G.nonuniformWitness ε U V) := by gcongr
_ = #(G.nonuniformWitness ε U V) -
↑2 ^ #P.parts * m / (#U * ε) * #(G.nonuniformWitness ε U V) := by
rw [sub_mul, one_mul]
_ ≤ #(G.nonuniformWitness ε U V) - ↑2 ^ (#P.parts - 1) * m := by
refine sub_le_sub_left ?_ _
have : (2 : ℝ) ^ #P.parts = ↑2 ^ (#P.parts - 1) * 2 := by
rw [← _root_.pow_succ, tsub_add_cancel_of_le (succ_le_iff.2 hP₁)]
rw [← mul_div_right_comm, this, mul_right_comm _ (2 : ℝ), mul_assoc, le_div_iff₀]
· gcongr _ * ?_
exact (G.le_card_nonuniformWitness hunif).trans
(le_mul_of_one_le_left (cast_nonneg _) one_le_two)
have := Finset.card_pos.mpr (P.nonempty_of_mem_parts hU)
sz_positivity
_ ≤ #((star hP G ε hU V).biUnion id) := by
rw [sub_le_comm, ←
cast_sub (card_le_card <| biUnion_star_subset_nonuniformWitness hP G ε hU V), ←
card_sdiff_of_subset (biUnion_star_subset_nonuniformWitness hP G ε hU V)]
exact mod_cast card_nonuniformWitness_sdiff_biUnion_star hV hUV hunif
/-! ### `chunk` -/
theorem card_chunk (hm : m ≠ 0) : #(chunk hP G ε hU).parts = 4 ^ #P.parts := by
unfold chunk
split_ifs
· rw [card_parts_equitabilise _ _ hm, tsub_add_cancel_of_le]
exact le_of_lt a_add_one_le_four_pow_parts_card
· rw [card_parts_equitabilise _ _ hm, tsub_add_cancel_of_le a_add_one_le_four_pow_parts_card]
theorem card_eq_of_mem_parts_chunk (hs : s ∈ (chunk hP G ε hU).parts) :
#s = m ∨ #s = m + 1 := by
unfold chunk at hs
split_ifs at hs <;> exact card_eq_of_mem_parts_equitabilise hs
theorem m_le_card_of_mem_chunk_parts (hs : s ∈ (chunk hP G ε hU).parts) : m ≤ #s :=
(card_eq_of_mem_parts_chunk hs).elim ge_of_eq fun i => by simp [i]
theorem card_le_m_add_one_of_mem_chunk_parts (hs : s ∈ (chunk hP G ε hU).parts) : #s ≤ m + 1 :=
(card_eq_of_mem_parts_chunk hs).elim (fun i => by simp [i]) fun i => i.le
theorem card_biUnion_star_le_m_add_one_card_star_mul :
(#((star hP G ε hU V).biUnion id) : ℝ) ≤ #(star hP G ε hU V) * (m + 1) :=
mod_cast card_biUnion_le_card_mul _ _ _ fun _ hs =>
card_le_m_add_one_of_mem_chunk_parts <| star_subset_chunk hs
private theorem le_sum_card_subset_chunk_parts (h𝒜 : 𝒜 ⊆ (chunk hP G ε hU).parts) (hs : s ∈ 𝒜) :
(#𝒜 : ℝ) * #s * (m / (m + 1)) ≤ #(𝒜.sup id) := by
rw [mul_div_assoc', div_le_iff₀ coe_m_add_one_pos, mul_right_comm]
gcongr
· rw [← (ofSubset _ h𝒜 rfl).sum_card_parts, ofSubset_parts, ← cast_mul, cast_le]
exact card_nsmul_le_sum _ _ _ fun x hx => m_le_card_of_mem_chunk_parts <| h𝒜 hx
· exact mod_cast card_le_m_add_one_of_mem_chunk_parts (h𝒜 hs)
private theorem sum_card_subset_chunk_parts_le (m_pos : (0 : ℝ) < m)
(h𝒜 : 𝒜 ⊆ (chunk hP G ε hU).parts) (hs : s ∈ 𝒜) :
(#(𝒜.sup id) : ℝ) ≤ #𝒜 * #s * ((m + 1) / m) := by
rw [sup_eq_biUnion, mul_div_assoc', le_div_iff₀ m_pos, mul_right_comm]
gcongr
· norm_cast
refine card_biUnion_le_card_mul _ _ _ fun x hx => ?_
apply card_le_m_add_one_of_mem_chunk_parts (h𝒜 hx)
· exact mod_cast m_le_card_of_mem_chunk_parts (h𝒜 hs)
private theorem one_sub_le_m_div_m_add_one_sq [Nonempty α]
(hPα : #P.parts * 16 ^ #P.parts ≤ card α) (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5) :
↑1 - ε ^ 5 / ↑50 ≤ (m / (m + 1 : ℝ)) ^ 2 := by
have : (m : ℝ) / (m + 1) = 1 - 1 / (m + 1) := by
rw [one_sub_div coe_m_add_one_pos.ne', add_sub_cancel_right]
rw [this, sub_sq, one_pow, mul_one]
refine le_trans ?_ (le_add_of_nonneg_right <| sq_nonneg _)
rw [sub_le_sub_iff_left, ← le_div_iff₀' (show (0 : ℝ) < 2 by simp), div_div,
one_div_le coe_m_add_one_pos, one_div_div]
· refine le_trans ?_ (le_add_of_nonneg_right zero_le_one)
norm_num
apply hundred_div_ε_pow_five_le_m hPα hPε
sz_positivity
private theorem m_add_one_div_m_le_one_add [Nonempty α]
(hPα : #P.parts * 16 ^ #P.parts ≤ card α) (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5) (hε₁ : ε ≤ 1) :
((m + 1 : ℝ) / m) ^ 2 ≤ ↑1 + ε ^ 5 / 49 := by
have : 0 ≤ ε := by sz_positivity
rw [same_add_div (by sz_positivity)]
calc
_ ≤ (1 + ε ^ 5 / 100) ^ 2 := by
gcongr (1 + ?_) ^ 2
rw [← one_div_div (100 : ℝ)]
exact one_div_le_one_div_of_le (by sz_positivity) (hundred_div_ε_pow_five_le_m hPα hPε)
_ = 1 + ε ^ 5 * (50⁻¹ + ε ^ 5 / 10000) := by ring
_ ≤ 1 + ε ^ 5 * (50⁻¹ + 1 ^ 5 / 10000) := by gcongr
_ ≤ 1 + ε ^ 5 * 49⁻¹ := by gcongr; norm_num
_ = 1 + ε ^ 5 / 49 := by rw [div_eq_mul_inv]
private theorem density_sub_eps_le_sum_density_div_card [Nonempty α]
(hPα : #P.parts * 16 ^ #P.parts ≤ card α) (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5)
{hU : U ∈ P.parts} {hV : V ∈ P.parts} {A B : Finset (Finset α)}
(hA : A ⊆ (chunk hP G ε hU).parts) (hB : B ⊆ (chunk hP G ε hV).parts) :
(G.edgeDensity (A.biUnion id) (B.biUnion id)) - ε ^ 5 / 50 ≤
(∑ ab ∈ A.product B, (G.edgeDensity ab.1 ab.2 : ℝ)) / (#A * #B) := by
have : ↑(G.edgeDensity (A.biUnion id) (B.biUnion id)) - ε ^ 5 / ↑50 ≤
(↑1 - ε ^ 5 / 50) * G.edgeDensity (A.biUnion id) (B.biUnion id) := by
rw [sub_mul, one_mul, sub_le_sub_iff_left]
refine mul_le_of_le_one_right (by sz_positivity) ?_
exact mod_cast G.edgeDensity_le_one _ _
refine this.trans ?_
conv_rhs => -- Porting note: LHS and RHS need separate treatment to get the desired form
simp only [SimpleGraph.edgeDensity_def, sum_div, Rat.cast_div, div_div]
conv_lhs =>
rw [SimpleGraph.edgeDensity_def, SimpleGraph.interedges, ← sup_eq_biUnion, ← sup_eq_biUnion,
Rel.card_interedges_finpartition _ (ofSubset _ hA rfl) (ofSubset _ hB rfl), ofSubset_parts,
ofSubset_parts]
simp only [cast_sum, sum_div, mul_sum, Rat.cast_sum, Rat.cast_div,
mul_div_left_comm ((1 : ℝ) - _)]
push_cast
apply sum_le_sum
simp only [and_imp, Prod.forall, mem_product]
rintro x y hx hy
rw [mul_mul_mul_comm, mul_comm (#x : ℝ), mul_comm (#y : ℝ), le_div_iff₀, mul_assoc]
· refine mul_le_of_le_one_right (cast_nonneg _) ?_
rw [div_mul_eq_mul_div, ← mul_assoc, mul_assoc]
refine div_le_one_of_le₀ ?_ (by positivity)
refine (mul_le_mul_of_nonneg_right (one_sub_le_m_div_m_add_one_sq hPα hPε) ?_).trans ?_
· exact mod_cast _root_.zero_le _
rw [sq, mul_mul_mul_comm, mul_comm ((m : ℝ) / _), mul_comm ((m : ℝ) / _)]
gcongr
· apply le_sum_card_subset_chunk_parts hA hx
· apply le_sum_card_subset_chunk_parts hB hy
refine mul_pos (mul_pos ?_ ?_) (mul_pos ?_ ?_) <;> rw [cast_pos, Finset.card_pos]
exacts [⟨_, hx⟩, nonempty_of_mem_parts _ (hA hx), ⟨_, hy⟩, nonempty_of_mem_parts _ (hB hy)]
private theorem sum_density_div_card_le_density_add_eps [Nonempty α]
(hPα : #P.parts * 16 ^ #P.parts ≤ card α) (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5)
(hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts} {A B : Finset (Finset α)}
(hA : A ⊆ (chunk hP G ε hU).parts) (hB : B ⊆ (chunk hP G ε hV).parts) :
(∑ ab ∈ A.product B, G.edgeDensity ab.1 ab.2 : ℝ) / (#A * #B) ≤
G.edgeDensity (A.biUnion id) (B.biUnion id) + ε ^ 5 / 49 := by
have : (↑1 + ε ^ 5 / ↑49) * G.edgeDensity (A.biUnion id) (B.biUnion id) ≤
G.edgeDensity (A.biUnion id) (B.biUnion id) + ε ^ 5 / 49 := by
rw [add_mul, one_mul, add_le_add_iff_left]
refine mul_le_of_le_one_right (by sz_positivity) ?_
exact mod_cast G.edgeDensity_le_one _ _
refine le_trans ?_ this
conv_lhs => -- Porting note: LHS and RHS need separate treatment to get the desired form
simp only [SimpleGraph.edgeDensity, edgeDensity, sum_div, Rat.cast_div, div_div]
conv_rhs =>
rw [SimpleGraph.edgeDensity, edgeDensity, ← sup_eq_biUnion, ← sup_eq_biUnion,
Rel.card_interedges_finpartition _ (ofSubset _ hA rfl) (ofSubset _ hB rfl)]
simp only [cast_sum, mul_sum, sum_div, Rat.cast_sum, Rat.cast_div,
mul_div_left_comm ((1 : ℝ) + _)]
push_cast
apply sum_le_sum
simp only [and_imp, Prod.forall, mem_product, show A.product B = A ×ˢ B by rfl]
intro x y hx hy
rw [mul_mul_mul_comm, mul_comm (#x : ℝ), mul_comm (#y : ℝ), div_le_iff₀, mul_assoc]
· refine le_mul_of_one_le_right (cast_nonneg _) ?_
rw [div_mul_eq_mul_div, one_le_div]
· refine le_trans ?_ (mul_le_mul_of_nonneg_right (m_add_one_div_m_le_one_add hPα hPε hε₁) ?_)
· rw [sq, mul_mul_mul_comm, mul_comm (_ / (m : ℝ)), mul_comm (_ / (m : ℝ))]
gcongr
exacts [sum_card_subset_chunk_parts_le (by sz_positivity) hA hx,
sum_card_subset_chunk_parts_le (by sz_positivity) hB hy]
· exact mod_cast _root_.zero_le _
rw [← cast_mul, cast_pos]
apply mul_pos <;> rw [Finset.card_pos, sup_eq_biUnion, biUnion_nonempty]
· exact ⟨_, hx, nonempty_of_mem_parts _ (hA hx)⟩
· exact ⟨_, hy, nonempty_of_mem_parts _ (hB hy)⟩
refine mul_pos (mul_pos ?_ ?_) (mul_pos ?_ ?_) <;> rw [cast_pos, Finset.card_pos]
exacts [⟨_, hx⟩, nonempty_of_mem_parts _ (hA hx), ⟨_, hy⟩, nonempty_of_mem_parts _ (hB hy)]
private theorem average_density_near_total_density [Nonempty α]
(hPα : #P.parts * 16 ^ #P.parts ≤ card α) (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5)
(hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts} {A B : Finset (Finset α)}
(hA : A ⊆ (chunk hP G ε hU).parts) (hB : B ⊆ (chunk hP G ε hV).parts) :
|(∑ ab ∈ A.product B, G.edgeDensity ab.1 ab.2 : ℝ) / (#A * #B) -
G.edgeDensity (A.biUnion id) (B.biUnion id)| ≤ ε ^ 5 / 49 := by
rw [abs_sub_le_iff]
constructor
· rw [sub_le_iff_le_add']
exact sum_density_div_card_le_density_add_eps hPα hPε hε₁ hA hB
suffices (G.edgeDensity (A.biUnion id) (B.biUnion id) : ℝ) -
(∑ ab ∈ A.product B, (G.edgeDensity ab.1 ab.2 : ℝ)) / (#A * #B) ≤ ε ^ 5 / 50 by
apply this.trans
gcongr <;> [sz_positivity; norm_num]
rw [sub_le_iff_le_add, ← sub_le_iff_le_add']
apply density_sub_eps_le_sum_density_div_card hPα hPε hA hB
private theorem edgeDensity_chunk_aux [Nonempty α] (hP)
(hPα : #P.parts * 16 ^ #P.parts ≤ card α) (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5)
(hU : U ∈ P.parts) (hV : V ∈ P.parts) :
(G.edgeDensity U V : ℝ) ^ 2 - ε ^ 5 / ↑25 ≤
((∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts,
(G.edgeDensity ab.1 ab.2 : ℝ)) / ↑16 ^ #P.parts) ^ 2 := by
obtain hGε | hGε := le_total (G.edgeDensity U V : ℝ) (ε ^ 5 / 50)
· refine (sub_nonpos_of_le <| (sq_le ?_ ?_).trans <| hGε.trans ?_).trans (sq_nonneg _)
· exact mod_cast G.edgeDensity_nonneg _ _
· exact mod_cast G.edgeDensity_le_one _ _
· exact div_le_div_of_nonneg_left (by sz_positivity) (by simp) (by norm_num)
rw [← sub_nonneg] at hGε
have : 0 ≤ ε := by sz_positivity
calc
_ = G.edgeDensity U V ^ 2 - 1 * ε ^ 5 / 25 + 0 ^ 10 / 2500 := by ring
_ ≤ G.edgeDensity U V ^ 2 - G.edgeDensity U V * ε ^ 5 / 25 + ε ^ 10 / 2500 := by
gcongr; exact mod_cast G.edgeDensity_le_one ..
_ = (G.edgeDensity U V - ε ^ 5 / 50) ^ 2 := by ring
_ ≤ _ := by
gcongr
have rflU := Subset.refl (chunk hP G ε hU).parts
have rflV := Subset.refl (chunk hP G ε hV).parts
refine (le_trans ?_ <| density_sub_eps_le_sum_density_div_card hPα hPε rflU rflV).trans ?_
· rw [biUnion_parts, biUnion_parts]
· rw [card_chunk (m_pos hPα).ne', card_chunk (m_pos hPα).ne', ← cast_mul, ← mul_pow, cast_pow]
norm_cast
private theorem abs_density_star_sub_density_le_eps (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5)
(hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts} (hUV' : U ≠ V) (hUV : ¬G.IsUniform ε U V) :
|(G.edgeDensity ((star hP G ε hU V).biUnion id) ((star hP G ε hV U).biUnion id) : ℝ) -
G.edgeDensity (G.nonuniformWitness ε U V) (G.nonuniformWitness ε V U)| ≤ ε / 5 := by
convert abs_edgeDensity_sub_edgeDensity_le_two_mul G.Adj
(biUnion_star_subset_nonuniformWitness hP G ε hU V)
(biUnion_star_subset_nonuniformWitness hP G ε hV U) (by sz_positivity)
(one_sub_eps_mul_card_nonuniformWitness_le_card_star hV hUV' hUV hPε hε₁)
(one_sub_eps_mul_card_nonuniformWitness_le_card_star hU hUV'.symm (fun hVU => hUV hVU.symm)
hPε hε₁) using 1
linarith
private theorem eps_le_card_star_div [Nonempty α] (hPα : #P.parts * 16 ^ #P.parts ≤ card α)
(hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5) (hε₁ : ε ≤ 1) (hU : U ∈ P.parts) (hV : V ∈ P.parts)
(hUV : U ≠ V) (hunif : ¬G.IsUniform ε U V) :
↑4 / ↑5 * ε ≤ #(star hP G ε hU V) / ↑4 ^ #P.parts := by
have hm : (0 : ℝ) ≤ 1 - (↑m)⁻¹ := sub_nonneg_of_le (inv_le_one_of_one_le₀ <| one_le_m_coe hPα)
have hε : 0 ≤ 1 - ε / 10 :=
sub_nonneg_of_le (div_le_one_of_le₀ (hε₁.trans <| by simp) <| by norm_num)
have hε₀ : 0 < ε := by sz_positivity
calc
4 / 5 * ε = (1 - 1 / 10) * (1 - 9⁻¹) * ε := by norm_num
_ ≤ (1 - ε / 10) * (1 - (↑m)⁻¹) * (#(G.nonuniformWitness ε U V) / #U) := by
gcongr
exacts [mod_cast (show 9 ≤ 100 by simp).trans (hundred_le_m hPα hPε hε₁),
(le_div_iff₀' <| cast_pos.2 (P.nonempty_of_mem_parts hU).card_pos).2 <|
G.le_card_nonuniformWitness hunif]
_ = (1 - ε / 10) * #(G.nonuniformWitness ε U V) * ((1 - (↑m)⁻¹) / #U) := by
rw [mul_assoc, mul_assoc, mul_div_left_comm]
_ ≤ #((star hP G ε hU V).biUnion id) * ((1 - (↑m)⁻¹) / #U) := by
gcongr
exact one_sub_eps_mul_card_nonuniformWitness_le_card_star hV hUV hunif hPε hε₁
_ ≤ #(star hP G ε hU V) * (m + 1) * ((1 - (↑m)⁻¹) / #U) := by
gcongr
exact card_biUnion_star_le_m_add_one_card_star_mul
_ ≤ #(star hP G ε hU V) * (m + ↑1) * ((↑1 - (↑m)⁻¹) / (↑4 ^ #P.parts * m)) := by
gcongr
· sz_positivity
· exact pow_mul_m_le_card_part hP hU
_ ≤ #(star hP G ε hU V) / ↑4 ^ #P.parts := by
rw [mul_assoc, mul_comm ((4 : ℝ) ^ #P.parts), ← div_div, ← mul_div_assoc, ← mul_comm_div]
refine mul_le_of_le_one_right (by positivity) ?_
have hm : (0 : ℝ) < m := by sz_positivity
rw [mul_div_assoc', div_le_one hm, ← one_div, one_sub_div hm.ne', mul_div_assoc',
div_le_iff₀ hm]
linarith
/-!
### Final bounds
Those inequalities are the end result of all this hard work.
-/
/-- Lower bound on the edge densities between non-uniform parts of `SzemerediRegularity.star`. -/
private theorem edgeDensity_star_not_uniform [Nonempty α]
(hPα : #P.parts * 16 ^ #P.parts ≤ card α) (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5)
(hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts} (hUVne : U ≠ V) (hUV : ¬G.IsUniform ε U V) :
↑3 / ↑4 * ε ≤
|(∑ ab ∈ (star hP G ε hU V).product (star hP G ε hV U), (G.edgeDensity ab.1 ab.2 : ℝ)) /
(#(star hP G ε hU V) * #(star hP G ε hV U)) -
(∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts,
(G.edgeDensity ab.1 ab.2 : ℝ)) / (16 : ℝ) ^ #P.parts| := by
rw [show (16 : ℝ) = ↑4 ^ 2 by norm_num, pow_right_comm, sq ((4 : ℝ) ^ _)]
set p : ℝ :=
(∑ ab ∈ (star hP G ε hU V).product (star hP G ε hV U), (G.edgeDensity ab.1 ab.2 : ℝ)) /
(#(star hP G ε hU V) * #(star hP G ε hV U))
set q : ℝ :=
(∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts,
(G.edgeDensity ab.1 ab.2 : ℝ)) / (↑4 ^ #P.parts * ↑4 ^ #P.parts)
set r : ℝ := ↑(G.edgeDensity ((star hP G ε hU V).biUnion id) ((star hP G ε hV U).biUnion id))
set s : ℝ := ↑(G.edgeDensity (G.nonuniformWitness ε U V) (G.nonuniformWitness ε V U))
set t : ℝ := ↑(G.edgeDensity U V)
have hrs : |r - s| ≤ ε / 5 := abs_density_star_sub_density_le_eps hPε hε₁ hUVne hUV
have hst : ε ≤ |s - t| := by
-- After https://github.com/leanprover/lean4/pull/2734, we need to do the zeta reduction before `mod_cast`.
unfold s t
exact mod_cast G.nonuniformWitness_spec hUVne hUV
have hpr : |p - r| ≤ ε ^ 5 / 49 :=
average_density_near_total_density hPα hPε hε₁ star_subset_chunk star_subset_chunk
have hqt : |q - t| ≤ ε ^ 5 / 49 := by
have := average_density_near_total_density hPα hPε hε₁
(Subset.refl (chunk hP G ε hU).parts) (Subset.refl (chunk hP G ε hV).parts)
simp_rw [← sup_eq_biUnion, sup_parts, card_chunk (m_pos hPα).ne', cast_pow] at this
norm_num at this
exact this
have hε' : ε ^ 5 ≤ ε := by
simpa using pow_le_pow_of_le_one (by sz_positivity) hε₁ (show 1 ≤ 5 by simp)
rw [abs_sub_le_iff] at hrs hpr hqt
rw [le_abs] at hst ⊢
cases hst
· left; linarith
· right; linarith
/-- Lower bound on the edge densities between non-uniform parts of `SzemerediRegularity.increment`.
-/
theorem edgeDensity_chunk_not_uniform [Nonempty α] (hPα : #P.parts * 16 ^ #P.parts ≤ card α)
(hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5) (hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts}
(hUVne : U ≠ V) (hUV : ¬G.IsUniform ε U V) :
(G.edgeDensity U V : ℝ) ^ 2 - ε ^ 5 / ↑25 + ε ^ 4 / ↑3 ≤
(∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts,
(G.edgeDensity ab.1 ab.2 : ℝ) ^ 2) / ↑16 ^ #P.parts :=
calc
↑(G.edgeDensity U V) ^ 2 - ε ^ 5 / 25 + ε ^ 4 / ↑3 ≤ ↑(G.edgeDensity U V) ^ 2 - ε ^ 5 / ↑25 +
#(star hP G ε hU V) * #(star hP G ε hV U) / ↑16 ^ #P.parts *
(↑9 / ↑16) * ε ^ 2 := by
gcongr
have Ul : 4 / 5 * ε ≤ #(star hP G ε hU V) / _ :=
eps_le_card_star_div hPα hPε hε₁ hU hV hUVne hUV
have Vl : 4 / 5 * ε ≤ #(star hP G ε hV U) / _ :=
eps_le_card_star_div hPα hPε hε₁ hV hU hUVne.symm fun h => hUV h.symm
rw [show (16 : ℝ) = ↑4 ^ 2 by norm_num, pow_right_comm, sq ((4 : ℝ) ^ _), ←
_root_.div_mul_div_comm, mul_assoc]
have : 0 < ε := by sz_positivity
have UVl := mul_le_mul Ul Vl (by positivity) ?_
swap
· -- This seems faster than `exact div_nonneg (by positivity) (by positivity)` and *much*
-- (tens of seconds) faster than `positivity` on its own.
apply div_nonneg <;> positivity
refine le_trans ?_ (mul_le_mul_of_nonneg_right UVl ?_)
· norm_num
nlinarith
· norm_num
positivity
_ ≤ (∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts,
(G.edgeDensity ab.1 ab.2 : ℝ) ^ 2) / ↑16 ^ #P.parts := by
have t : (star hP G ε hU V).product (star hP G ε hV U) ⊆
(chunk hP G ε hU).parts.product (chunk hP G ε hV).parts :=
product_subset_product star_subset_chunk star_subset_chunk
have hε : 0 ≤ ε := by sz_positivity
have sp : ∀ (a b : Finset (Finset α)), a.product b = a ×ˢ b := fun a b => rfl
have := add_div_le_sum_sq_div_card t (fun x => (G.edgeDensity x.1 x.2 : ℝ))
((G.edgeDensity U V : ℝ) ^ 2 - ε ^ 5 / ↑25) (show 0 ≤ 3 / 4 * ε by linarith) ?_ ?_
· simp_rw [sp, card_product, card_chunk (m_pos hPα).ne', ← mul_pow, cast_pow, mul_pow,
div_pow, ← mul_assoc] at this
norm_num at this
exact this
· simp_rw [sp, card_product, card_chunk (m_pos hPα).ne', ← mul_pow]
norm_num
exact edgeDensity_star_not_uniform hPα hPε hε₁ hUVne hUV
· rw [sp, card_product]
apply (edgeDensity_chunk_aux hP hPα hPε hU hV).trans
· rw [card_chunk (m_pos hPα).ne', card_chunk (m_pos hPα).ne', ← mul_pow]
simp
/-- Lower bound on the edge densities between parts of `SzemerediRegularity.increment`. This is the
blanket lower bound used the uniform parts. -/
theorem edgeDensity_chunk_uniform [Nonempty α] (hPα : #P.parts * 16 ^ #P.parts ≤ card α)
(hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5) (hU : U ∈ P.parts) (hV : V ∈ P.parts) :
(G.edgeDensity U V : ℝ) ^ 2 - ε ^ 5 / ↑25 ≤
(∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts,
(G.edgeDensity ab.1 ab.2 : ℝ) ^ 2) / ↑16 ^ #P.parts := by
apply (edgeDensity_chunk_aux (hP := hP) hPα hPε hU hV).trans
have key : (16 : ℝ) ^ #P.parts = #((chunk hP G ε hU).parts ×ˢ (chunk hP G ε hV).parts) := by
rw [card_product, cast_mul, card_chunk (m_pos hPα).ne', card_chunk (m_pos hPα).ne', ←
cast_mul, ← mul_pow]; norm_cast
simp_rw [key]
convert sum_div_card_sq_le_sum_sq_div_card (α := ℝ)
end SzemerediRegularity |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Regularity/Lemma.lean | import Mathlib.Combinatorics.SimpleGraph.Regularity.Increment
/-!
# Szemerédi's Regularity Lemma
In this file, we prove Szemerédi's Regularity Lemma (aka SRL). This is a landmark result in
combinatorics roughly stating that any sufficiently big graph behaves like a random graph. This is
useful because random graphs are well-behaved in many aspects.
More precisely, SRL states that for any `ε > 0` and integer `l` there exists a bound `M` such that
any graph on at least `l` vertices can be partitioned into at least `l` parts and at most `M` parts
such that the resulting partitioned graph is `ε`-uniform.
This statement is very robust to tweaking and many different versions exist. Here, we prove the
version where the resulting partition is equitable (aka an *equipartition*), namely all parts have
the same size up to a difference of `1`.
The proof we formalise goes as follows:
1. Define an auxiliary measure of edge density, the *energy* of a partition.
2. Start with an arbitrary equipartition of size `l`.
3. Repeatedly break up the parts of the current equipartition in a big but controlled number of
parts. The key point is to break along the witnesses of non-uniformity, so that a lesser portion
of the pairs of parts are non-`ε`-uniform.
4. Check that this results in an equipartition with an energy greater than the energy of the current
partition, plus some constant.
5. Since the energy is between zero and one, we can't run this process forever. Check that when the
process stops we have an `ε`-uniform equipartition.
This file only contains the final result. The supporting material is spread across the
`Combinatorics/SimpleGraph/Regularity` folder:
* `Combinatorics/SimpleGraph/Regularity/Bound`: Definition of the bound on the number of parts.
Numerical inequalities involving the lemma constants.
* `Combinatorics/SimpleGraph/Regularity/Energy`: Definition of the energy of a simple graph along a
partition.
* `Combinatorics/SimpleGraph/Regularity/Uniform`: Definition of uniformity of a simple graph along
a pair of parts and along a partition.
* `Combinatorics/SimpleGraph/Regularity/Equitabilise`: Construction of an equipartition with
a prescribed number of parts of each size and almost refining a given partition.
* `Combinatorics/SimpleGraph/Regularity/Chunk`: Break up one part of the current equipartition.
Check that density between non-uniform parts increases, and that density between uniform parts
doesn't decrease too much.
* `Combinatorics/SimpleGraph/Regularity/Increment`: Gather all those broken up parts into the new
equipartition (aka *increment partition*). Check that energy increases by at least a fixed amount.
* `Combinatorics/SimpleGraph/Regularity/Lemma`: Wrap everything up into an induction on the energy.
## TODO
We currently only prove the equipartition version of SRL.
* Prove the diagonal version.
* Prove the degree version.
* Define the regularity of a partition and prove the corresponding version.
## References
[Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
-/
open Finpartition Finset Fintype Function SzemerediRegularity
variable {α : Type*} [DecidableEq α] [Fintype α] (G : SimpleGraph α) [DecidableRel G.Adj] {ε : ℝ}
{l : ℕ}
/-- Effective **Szemerédi Regularity Lemma**: For any sufficiently large graph, there is an
`ε`-uniform equipartition of bounded size (where the bound does not depend on the graph). -/
theorem szemeredi_regularity (hε : 0 < ε) (hl : l ≤ card α) :
∃ P : Finpartition univ,
P.IsEquipartition ∧ l ≤ #P.parts ∧ #P.parts ≤ bound ε l ∧ P.IsUniform G ε := by
obtain hα | hα := le_total (card α) (bound ε l)
-- If `card α ≤ bound ε l`, then the partition into singletons is acceptable.
· refine ⟨⊥, bot_isEquipartition _, ?_⟩
rw [card_bot, card_univ]
exact ⟨hl, hα, bot_isUniform _ hε⟩
-- Else, let's start from a dummy equipartition of size `initialBound ε l`.
let t := initialBound ε l
have htα : t ≤ #(univ : Finset α) :=
(initialBound_le_bound _ _).trans (by rwa [Finset.card_univ])
obtain ⟨dum, hdum₁, hdum₂⟩ :=
exists_equipartition_card_eq (univ : Finset α) (initialBound_pos _ _).ne' htα
obtain hε₁ | hε₁ := le_total 1 ε
-- If `ε ≥ 1`, then this dummy equipartition is `ε`-uniform, so we're done.
· exact ⟨dum, hdum₁, (le_initialBound ε l).trans hdum₂.ge,
hdum₂.le.trans (initialBound_le_bound ε l), (dum.isUniform_one G).mono hε₁⟩
-- Else, set up the induction on energy. We phrase it through the existence for each `i` of an
-- equipartition of size bounded by `stepBound^[i] (initialBound ε l)` and which is either
-- `ε`-uniform or has energy at least `ε ^ 5 / 4 * i`.
have : Nonempty α := by
rw [← Fintype.card_pos_iff]
exact (bound_pos _ _).trans_le hα
suffices h : ∀ i, ∃ P : Finpartition (univ : Finset α), P.IsEquipartition ∧ t ≤ #P.parts ∧
#P.parts ≤ stepBound^[i] t ∧ (P.IsUniform G ε ∨ ε ^ 5 / 4 * i ≤ P.energy G) by
-- For `i > 4 / ε ^ 5` we know that the partition we get can't have energy `≥ ε ^ 5 / 4 * i > 1`,
-- so it must instead be `ε`-uniform and we won.
obtain ⟨P, hP₁, hP₂, hP₃, hP₄⟩ := h (⌊4 / ε ^ 5⌋₊ + 1)
refine ⟨P, hP₁, (le_initialBound _ _).trans hP₂, hP₃.trans ?_,
hP₄.resolve_right fun hPenergy => lt_irrefl (1 : ℝ) ?_⟩
· rw [iterate_succ_apply', stepBound, bound]
gcongr
simp
calc
(1 : ℝ) = ε ^ 5 / ↑4 * (↑4 / ε ^ 5) := by
rw [mul_comm, div_mul_div_cancel₀ (pow_pos hε 5).ne']; simp
_ < ε ^ 5 / 4 * (⌊4 / ε ^ 5⌋₊ + 1) := by gcongr; exact Nat.lt_floor_add_one _
_ ≤ (P.energy G : ℝ) := by rwa [← Nat.cast_add_one]
_ ≤ 1 := mod_cast P.energy_le_one G
-- Let's do the actual induction.
intro i
induction i with
-- For `i = 0`, the dummy equipartition is enough.
| zero =>
refine ⟨dum, hdum₁, hdum₂.ge, hdum₂.le, Or.inr ?_⟩
rw [Nat.cast_zero, mul_zero]
exact mod_cast dum.energy_nonneg G
-- For the induction step at `i + 1`, find `P` the equipartition at `i`.
| succ i ih =>
obtain ⟨P, hP₁, hP₂, hP₃, hP₄⟩ := ih
by_cases huniform : P.IsUniform G ε
-- If `P` is already uniform, then no need to break it up further. We can just return `P` again.
· refine ⟨P, hP₁, hP₂, ?_, Or.inl huniform⟩
rw [iterate_succ_apply']
exact hP₃.trans (le_stepBound _)
-- Else, `P` must instead have energy at least `ε ^ 5 / 4 * i`.
replace hP₄ := hP₄.resolve_left huniform
-- We gather a few numerical facts.
have hεl' : 100 ≤ 4 ^ #P.parts * ε ^ 5 :=
(hundred_lt_pow_initialBound_mul hε l).le.trans
(mul_le_mul_of_nonneg_right (pow_right_mono₀ (by simp) hP₂) <| by positivity)
have hi : (i : ℝ) ≤ 4 / ε ^ 5 := by
have hi : ε ^ 5 / 4 * ↑i ≤ 1 := hP₄.trans (mod_cast P.energy_le_one G)
rw [div_mul_eq_mul_div, div_le_iff₀ (show (0 : ℝ) < 4 by simp)] at hi
norm_num at hi
rwa [le_div_iff₀' (pow_pos hε _)]
have hsize : #P.parts ≤ stepBound^[⌊4 / ε ^ 5⌋₊] t :=
hP₃.trans (monotone_iterate_of_id_le le_stepBound (Nat.le_floor hi) _)
have hPα : #P.parts * 16 ^ #P.parts ≤ card α :=
(Nat.mul_le_mul hsize (Nat.pow_le_pow_right (by simp) hsize)).trans hα
-- We return the increment equipartition of `P`, which has energy `≥ ε ^ 5 / 4 * (i + 1)`.
refine ⟨increment hP₁ G ε, increment_isEquipartition hP₁ G ε, ?_, ?_, Or.inr <| le_trans ?_ <|
energy_increment hP₁ ((seven_le_initialBound ε l).trans hP₂) hεl' hPα huniform hε.le hε₁⟩
· rw [card_increment hPα huniform]
exact hP₂.trans (le_stepBound _)
· rw [card_increment hPα huniform, iterate_succ_apply']
exact stepBound_mono hP₃
· rw [Nat.cast_succ, mul_add, mul_one]
gcongr |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Regularity/Increment.lean | import Mathlib.Combinatorics.SimpleGraph.Regularity.Chunk
import Mathlib.Combinatorics.SimpleGraph.Regularity.Energy
/-!
# Increment partition for Szemerédi Regularity Lemma
In the proof of Szemerédi Regularity Lemma, we need to partition each part of a starting partition
to increase the energy. This file defines the partition obtained by gluing the parts partitions
together (the *increment partition*) and shows that the energy globally increases.
This entire file is internal to the proof of Szemerédi Regularity Lemma.
## Main declarations
* `SzemerediRegularity.increment`: The increment partition.
* `SzemerediRegularity.card_increment`: The increment partition is much bigger than the original,
but by a controlled amount.
* `SzemerediRegularity.energy_increment`: The increment partition has energy greater than the
original by a known (small) fixed amount.
## TODO
Once ported to mathlib4, this file will be a great golfing ground for Heather's new tactic
`gcongr`.
## References
[Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
-/
open Finset Fintype SimpleGraph SzemerediRegularity
open scoped SzemerediRegularity.Positivity
variable {α : Type*} [Fintype α] [DecidableEq α] {P : Finpartition (univ : Finset α)}
(hP : P.IsEquipartition) (G : SimpleGraph α) [DecidableRel G.Adj] (ε : ℝ)
local notation3 "m" => (card α / stepBound #P.parts : ℕ)
namespace SzemerediRegularity
/-- The **increment partition** in Szemerédi's Regularity Lemma.
If an equipartition is *not* uniform, then the increment partition is a (much bigger) equipartition
with a slightly higher energy. This is helpful since the energy is bounded by a constant (see
`Finpartition.energy_le_one`), so this process eventually terminates and yields a
not-too-big uniform equipartition. -/
noncomputable def increment : Finpartition (univ : Finset α) :=
P.bind fun _ => chunk hP G ε
open Finpartition Finpartition.IsEquipartition
variable {hP G ε}
/-- The increment partition has a prescribed (very big) size in terms of the original partition. -/
theorem card_increment (hPα : #P.parts * 16 ^ #P.parts ≤ card α) (hPG : ¬P.IsUniform G ε) :
#(increment hP G ε).parts = stepBound #P.parts := by
have hPα' : stepBound #P.parts ≤ card α := by grw [← hPα, stepBound]; gcongr; simp
have hPpos : 0 < stepBound #P.parts := stepBound_pos (nonempty_of_not_uniform hPG).card_pos
rw [increment, card_bind]
simp_rw [chunk, apply_dite Finpartition.parts, apply_dite card, sum_dite]
rw [sum_const_nat, sum_const_nat, univ_eq_attach, univ_eq_attach, card_attach, card_attach]
any_goals exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne'
rw [Nat.sub_add_cancel a_add_one_le_four_pow_parts_card,
Nat.sub_add_cancel ((Nat.le_succ _).trans a_add_one_le_four_pow_parts_card), ← add_mul]
congr
rw [filter_card_add_filter_neg_card_eq_card, card_attach]
variable (hP G ε)
theorem increment_isEquipartition : (increment hP G ε).IsEquipartition := by
simp_rw [IsEquipartition, Set.equitableOn_iff_exists_eq_eq_add_one]
refine ⟨m, fun A hA => ?_⟩
rw [mem_coe, increment, mem_bind] at hA
obtain ⟨U, hU, hA⟩ := hA
exact card_eq_of_mem_parts_chunk hA
/-- The contribution to `Finpartition.energy` of a pair of distinct parts of a `Finpartition`. -/
private noncomputable def distinctPairs (x : {x // x ∈ P.parts.offDiag}) :
Finset (Finset α × Finset α) :=
(chunk hP G ε (mem_offDiag.1 x.2).1).parts ×ˢ (chunk hP G ε (mem_offDiag.1 x.2).2.1).parts
variable {hP G ε}
private theorem distinctPairs_increment :
P.parts.offDiag.attach.biUnion (distinctPairs hP G ε) ⊆ (increment hP G ε).parts.offDiag := by
rintro ⟨Ui, Vj⟩
simp only [distinctPairs, increment, mem_offDiag, bind_parts, mem_biUnion, Prod.exists,
mem_product, mem_attach, true_and, Subtype.exists, and_imp,
mem_offDiag, forall_exists_index, Ne]
refine fun U V hUV hUi hVj => ⟨⟨_, hUV.1, hUi⟩, ⟨_, hUV.2.1, hVj⟩, ?_⟩
rintro rfl
obtain ⟨i, hi⟩ := nonempty_of_mem_parts _ hUi
exact hUV.2.2 (P.disjoint.elim_finset hUV.1 hUV.2.1 i (Finpartition.le _ hUi hi) <|
Finpartition.le _ hVj hi)
private lemma pairwiseDisjoint_distinctPairs :
(P.parts.offDiag.attach : Set {x // x ∈ P.parts.offDiag}).PairwiseDisjoint
(distinctPairs hP G ε) := by
simp +unfoldPartialApp only [distinctPairs, Set.PairwiseDisjoint,
Function.onFun, disjoint_left, mem_product]
rintro ⟨⟨s₁, s₂⟩, hs⟩ _ ⟨⟨t₁, t₂⟩, ht⟩ _ hst ⟨u, v⟩ huv₁ huv₂
rw [mem_offDiag] at hs ht
obtain ⟨a, ha⟩ := Finpartition.nonempty_of_mem_parts _ huv₁.1
obtain ⟨b, hb⟩ := Finpartition.nonempty_of_mem_parts _ huv₁.2
exact hst <| Subtype.ext <| Prod.ext
(P.disjoint.elim_finset hs.1 ht.1 a (Finpartition.le _ huv₁.1 ha) <|
Finpartition.le _ huv₂.1 ha) <|
P.disjoint.elim_finset hs.2.1 ht.2.1 b (Finpartition.le _ huv₁.2 hb) <|
Finpartition.le _ huv₂.2 hb
variable [Nonempty α]
lemma le_sum_distinctPairs_edgeDensity_sq (x : {i // i ∈ P.parts.offDiag}) (hε₁ : ε ≤ 1)
(hPα : #P.parts * 16 ^ #P.parts ≤ card α) (hPε : ↑100 ≤ ↑4 ^ #P.parts * ε ^ 5) :
(G.edgeDensity x.1.1 x.1.2 : ℝ) ^ 2 +
((if G.IsUniform ε x.1.1 x.1.2 then 0 else ε ^ 4 / 3) - ε ^ 5 / 25) ≤
(∑ i ∈ distinctPairs hP G ε x, G.edgeDensity i.1 i.2 ^ 2 : ℝ) / 16 ^ #P.parts := by
rw [distinctPairs, ← add_sub_assoc, add_sub_right_comm]
split_ifs with h
· rw [add_zero]
exact edgeDensity_chunk_uniform hPα hPε _ _
· exact edgeDensity_chunk_not_uniform hPα hPε hε₁ (mem_offDiag.1 x.2).2.2 h
/-- The increment partition has energy greater than the original one by a known fixed amount. -/
theorem energy_increment (hP : P.IsEquipartition) (hP₇ : 7 ≤ #P.parts)
(hPε : 100 ≤ 4 ^ #P.parts * ε ^ 5) (hPα : #P.parts * 16 ^ #P.parts ≤ card α)
(hPG : ¬P.IsUniform G ε) (hε₀ : 0 ≤ ε) (hε₁ : ε ≤ 1) :
↑(P.energy G) + ε ^ 5 / 4 ≤ (increment hP G ε).energy G := by
calc
_ = (∑ x ∈ P.parts.offDiag, (G.edgeDensity x.1 x.2 : ℝ) ^ 2 +
#P.parts ^ 2 * (ε ^ 5 / 4) : ℝ) / #P.parts ^ 2 := by
rw [coe_energy, add_div, mul_div_cancel_left₀]; positivity
_ ≤ (∑ x ∈ P.parts.offDiag.attach, (∑ i ∈ distinctPairs hP G ε x,
G.edgeDensity i.1 i.2 ^ 2 : ℝ) / 16 ^ #P.parts) / #P.parts ^ 2 := ?_
_ = (∑ x ∈ P.parts.offDiag.attach, ∑ i ∈ distinctPairs hP G ε x,
G.edgeDensity i.1 i.2 ^ 2 : ℝ) / #(increment hP G ε).parts ^ 2 := by
rw [card_increment hPα hPG, coe_stepBound, mul_pow, pow_right_comm,
div_mul_eq_div_div_swap, ← sum_div]; norm_num
_ ≤ _ := by
rw [coe_energy]
gcongr
rw [← sum_biUnion pairwiseDisjoint_distinctPairs]
exact sum_le_sum_of_subset_of_nonneg distinctPairs_increment fun i _ _ ↦ sq_nonneg _
gcongr
rw [Finpartition.IsUniform, not_le, mul_tsub, mul_one, ← offDiag_card] at hPG
calc
_ ≤ ∑ x ∈ P.parts.offDiag, (edgeDensity G x.1 x.2 : ℝ) ^ 2 +
(#(nonUniforms P G ε) * (ε ^ 4 / 3) - #P.parts.offDiag * (ε ^ 5 / 25)) := ?_
_ = ∑ x ∈ P.parts.offDiag, ((G.edgeDensity x.1 x.2 : ℝ) ^ 2 +
((if G.IsUniform ε x.1 x.2 then (0 : ℝ) else ε ^ 4 / 3) - ε ^ 5 / 25) : ℝ) := by
rw [sum_add_distrib, sum_sub_distrib, sum_const, nsmul_eq_mul, sum_ite, sum_const_zero,
zero_add, sum_const, nsmul_eq_mul, ← Finpartition.nonUniforms, ← add_sub_assoc,
add_sub_right_comm]
_ = _ := (sum_attach ..).symm
_ ≤ _ := sum_le_sum fun i _ ↦ le_sum_distinctPairs_edgeDensity_sq i hε₁ hPα hPε
gcongr
calc
_ = (6/7 * #P.parts ^ 2) * ε ^ 5 * (7 / 24) := by ring
_ ≤ #P.parts.offDiag * ε ^ 5 * (22 / 75) := by
gcongr ?_ * _ * ?_
· rw [← mul_div_right_comm, div_le_iff₀ (by simp), offDiag_card]
norm_cast
rw [tsub_mul]
refine le_tsub_of_add_le_left ?_
nlinarith
· norm_num
_ = (#P.parts.offDiag * ε * (ε ^ 4 / 3) - #P.parts.offDiag * (ε ^ 5 / 25)) := by ring
_ ≤ (#(nonUniforms P G ε) * (ε ^ 4 / 3) - #P.parts.offDiag * (ε ^ 5 / 25)) := by gcongr
end SzemerediRegularity |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Ends/Defs.lean | import Mathlib.CategoryTheory.CofilteredSystem
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected
import Mathlib.Data.Finite.Set
/-!
# Ends
This file contains a definition of the ends of a simple graph, as sections of the inverse system
assigning, to each finite set of vertices, the connected components of its complement.
-/
universe u
variable {V : Type u} (G : SimpleGraph V) (K L M : Set V)
namespace SimpleGraph
/-- The components outside a given set of vertices `K` -/
abbrev ComponentCompl :=
(G.induce Kᶜ).ConnectedComponent
variable {G} {K L M}
/-- The connected component of `v` in `G.induce Kᶜ`. -/
abbrev componentComplMk (G : SimpleGraph V) {v : V} (vK : v ∉ K) : G.ComponentCompl K :=
connectedComponentMk (G.induce Kᶜ) ⟨v, vK⟩
/-- The set of vertices of `G` making up the connected component `C` -/
def ComponentCompl.supp (C : G.ComponentCompl K) : Set V :=
{ v : V | ∃ h : v ∉ K, G.componentComplMk h = C }
@[ext]
theorem ComponentCompl.supp_injective :
Function.Injective (ComponentCompl.supp : G.ComponentCompl K → Set V) := by
refine ConnectedComponent.ind₂ ?_
rintro ⟨v, hv⟩ ⟨w, hw⟩ h
simp only [Set.ext_iff, ConnectedComponent.eq, Set.mem_setOf_eq, ComponentCompl.supp] at h ⊢
exact ((h v).mp ⟨hv, Reachable.refl _⟩).choose_spec
theorem ComponentCompl.supp_inj {C D : G.ComponentCompl K} : C.supp = D.supp ↔ C = D :=
ComponentCompl.supp_injective.eq_iff
instance ComponentCompl.setLike : SetLike (G.ComponentCompl K) V where
coe := ComponentCompl.supp
coe_injective' _ _ := ComponentCompl.supp_inj.mp
@[simp]
theorem ComponentCompl.mem_supp_iff {v : V} {C : ComponentCompl G K} :
v ∈ C ↔ ∃ vK : v ∉ K, G.componentComplMk vK = C :=
Iff.rfl
theorem componentComplMk_mem (G : SimpleGraph V) {v : V} (vK : v ∉ K) : v ∈ G.componentComplMk vK :=
⟨vK, rfl⟩
theorem componentComplMk_eq_of_adj (G : SimpleGraph V) {v w : V} (vK : v ∉ K) (wK : w ∉ K)
(a : G.Adj v w) : G.componentComplMk vK = G.componentComplMk wK := by
rw [ConnectedComponent.eq]
apply Adj.reachable
exact a
/-- In an infinite graph, the set of components out of a finite set is nonempty. -/
instance componentCompl_nonempty_of_infinite (G : SimpleGraph V) [Infinite V] (K : Finset V) :
Nonempty (G.ComponentCompl K) :=
let ⟨_, kK⟩ := K.finite_toSet.infinite_compl.nonempty
⟨componentComplMk _ kK⟩
namespace ComponentCompl
/-- A `ComponentCompl` specialization of `Quot.lift`, where soundness has to be proved only
for adjacent vertices.
-/
protected def lift {β : Sort*} (f : ∀ ⦃v⦄ (_ : v ∉ K), β)
(h : ∀ ⦃v w⦄ (hv : v ∉ K) (hw : w ∉ K), G.Adj v w → f hv = f hw) : G.ComponentCompl K → β :=
ConnectedComponent.lift (fun vv => f vv.prop) fun v w p => by
induction p with
| nil => rintro _; rfl
| cons a q ih => rename_i u v w; rintro h'; exact (h u.prop v.prop a).trans (ih h'.of_cons)
@[elab_as_elim]
protected theorem ind {β : G.ComponentCompl K → Prop}
(f : ∀ ⦃v⦄ (hv : v ∉ K), β (G.componentComplMk hv)) : ∀ C : G.ComponentCompl K, β C := by
apply ConnectedComponent.ind
exact fun ⟨v, vnK⟩ => f vnK
/-- The induced graph on the vertices `C`. -/
protected abbrev coeGraph (C : ComponentCompl G K) : SimpleGraph C :=
G.induce (C : Set V)
theorem coe_inj {C D : G.ComponentCompl K} : (C : Set V) = (D : Set V) ↔ C = D :=
SetLike.coe_set_eq
@[simp]
protected theorem nonempty (C : G.ComponentCompl K) : (C : Set V).Nonempty :=
C.ind fun v vnK => ⟨v, vnK, rfl⟩
protected theorem exists_eq_mk (C : G.ComponentCompl K) :
∃ (v : _) (h : v ∉ K), G.componentComplMk h = C :=
C.nonempty
protected theorem disjoint_right (C : G.ComponentCompl K) : Disjoint K C := by
rw [Set.disjoint_iff]
exact fun v ⟨vK, vC⟩ => vC.choose vK
theorem notMem_of_mem {C : G.ComponentCompl K} {c : V} (cC : c ∈ C) : c ∉ K := fun cK =>
Set.disjoint_iff.mp C.disjoint_right ⟨cK, cC⟩
@[deprecated (since := "2025-05-23")] alias not_mem_of_mem := notMem_of_mem
protected theorem pairwise_disjoint :
Pairwise fun C D : G.ComponentCompl K => Disjoint (C : Set V) (D : Set V) := by
rintro C D ne
rw [Set.disjoint_iff]
exact fun u ⟨uC, uD⟩ => ne (uC.choose_spec.symm.trans uD.choose_spec)
/-- Any vertex adjacent to a vertex of `C` and not lying in `K` must lie in `C`.
-/
theorem mem_of_adj : ∀ {C : G.ComponentCompl K} (c d : V), c ∈ C → d ∉ K → G.Adj c d → d ∈ C :=
fun {C} c d ⟨cnK, h⟩ dnK cd =>
⟨dnK, by
rw [← h, ConnectedComponent.eq]
exact Adj.reachable cd.symm⟩
/--
Assuming `G` is preconnected and `K` not empty, given any connected component `C` outside of `K`,
there exists a vertex `k ∈ K` adjacent to a vertex `v ∈ C`.
-/
theorem exists_adj_boundary_pair (Gc : G.Preconnected) (hK : K.Nonempty) :
∀ C : G.ComponentCompl K, ∃ ck : V × V, ck.1 ∈ C ∧ ck.2 ∈ K ∧ G.Adj ck.1 ck.2 := by
refine ComponentCompl.ind fun v vnK => ?_
let C : G.ComponentCompl K := G.componentComplMk vnK
let dis := Set.disjoint_iff.mp C.disjoint_right
by_contra! h
suffices Set.univ = (C : Set V) by exact dis ⟨hK.choose_spec, this ▸ Set.mem_univ hK.some⟩
symm
rw [Set.eq_univ_iff_forall]
rintro u
by_contra unC
obtain ⟨p⟩ := Gc v u
obtain ⟨⟨⟨x, y⟩, xy⟩, -, xC, ynC⟩ :=
p.exists_boundary_dart (C : Set V) (G.componentComplMk_mem vnK) unC
exact ynC (mem_of_adj x y xC (fun yK : y ∈ K => h ⟨x, y⟩ xC yK xy) xy)
/--
If `K ⊆ L`, the components outside of `L` are all contained in a single component outside of `K`.
-/
abbrev hom (h : K ⊆ L) (C : G.ComponentCompl L) : G.ComponentCompl K :=
C.map <| induceHom Hom.id <| Set.compl_subset_compl.2 h
theorem subset_hom (C : G.ComponentCompl L) (h : K ⊆ L) : (C : Set V) ⊆ (C.hom h : Set V) := by
rintro c ⟨cL, rfl⟩
exact ⟨fun h' => cL (h h'), rfl⟩
theorem _root_.SimpleGraph.componentComplMk_mem_hom
(G : SimpleGraph V) {v : V} (vK : v ∉ K) (h : L ⊆ K) :
v ∈ (G.componentComplMk vK).hom h :=
subset_hom (G.componentComplMk vK) h (G.componentComplMk_mem vK)
theorem hom_eq_iff_le (C : G.ComponentCompl L) (h : K ⊆ L) (D : G.ComponentCompl K) :
C.hom h = D ↔ (C : Set V) ⊆ (D : Set V) :=
⟨fun h' => h' ▸ C.subset_hom h, C.ind fun _ vnL vD => (vD ⟨vnL, rfl⟩).choose_spec⟩
theorem hom_eq_iff_not_disjoint (C : G.ComponentCompl L) (h : K ⊆ L) (D : G.ComponentCompl K) :
C.hom h = D ↔ ¬Disjoint (C : Set V) (D : Set V) := by
rw [Set.not_disjoint_iff]
constructor
· rintro rfl
refine C.ind fun x xnL => ?_
exact ⟨x, ⟨xnL, rfl⟩, ⟨fun xK => xnL (h xK), rfl⟩⟩
· refine C.ind fun x xnL => ?_
rintro ⟨x, ⟨_, e₁⟩, _, rfl⟩
rw [← e₁]
rfl
theorem hom_refl (C : G.ComponentCompl L) : C.hom (subset_refl L) = C := by
change C.map _ = C
rw [induceHom_id G Lᶜ, ConnectedComponent.map_id]
theorem hom_trans (C : G.ComponentCompl L) (h : K ⊆ L) (h' : M ⊆ K) :
C.hom (h'.trans h) = (C.hom h).hom h' := by
change C.map _ = (C.map _).map _
rw [ConnectedComponent.map_comp, induceHom_comp]
rfl
theorem hom_mk {v : V} (vnL : v ∉ L) (h : K ⊆ L) :
(G.componentComplMk vnL).hom h = G.componentComplMk (Set.notMem_subset h vnL) :=
rfl
theorem hom_infinite (C : G.ComponentCompl L) (h : K ⊆ L) (Cinf : (C : Set V).Infinite) :
(C.hom h : Set V).Infinite :=
Set.Infinite.mono (C.subset_hom h) Cinf
theorem infinite_iff_in_all_ranges {K : Finset V} (C : G.ComponentCompl K) :
C.supp.Infinite ↔ ∀ (L) (h : K ⊆ L), ∃ D : G.ComponentCompl L, D.hom h = C := by
classical
constructor
· rintro Cinf L h
obtain ⟨v, ⟨vK, rfl⟩, vL⟩ := Set.Infinite.nonempty (Set.Infinite.diff Cinf L.finite_toSet)
exact ⟨componentComplMk _ vL, rfl⟩
· rintro h Cfin
obtain ⟨D, e⟩ := h (K ∪ Cfin.toFinset) Finset.subset_union_left
obtain ⟨v, vD⟩ := D.nonempty
let Ddis := D.disjoint_right
simp_rw [Finset.coe_union, Set.Finite.coe_toFinset, Set.disjoint_union_left,
Set.disjoint_iff] at Ddis
exact Ddis.right ⟨(ComponentCompl.hom_eq_iff_le _ _ _).mp e vD, vD⟩
end ComponentCompl
/-- For a locally finite preconnected graph, the number of components outside of any finite set
is finite. -/
instance componentCompl_finite [LocallyFinite G] [Gpc : Fact G.Preconnected] (K : Finset V) :
Finite (G.ComponentCompl K) := by
classical
rcases K.eq_empty_or_nonempty with rfl | h
-- If K is empty, then removing K doesn't change the graph, which is connected, hence has a
-- single connected component
· dsimp [ComponentCompl]
rw [Finset.coe_empty, Set.compl_empty]
have := Gpc.out.subsingleton_connectedComponent
exact Finite.of_equiv _ (induceUnivIso G).connectedComponentEquiv.symm
-- Otherwise, we consider the function `touch` mapping a connected component to one of its
-- vertices adjacent to `K`.
· let touch (C : G.ComponentCompl K) : {v : V | ∃ k : V, k ∈ K ∧ G.Adj k v} :=
let p := C.exists_adj_boundary_pair Gpc.out h
⟨p.choose.1, p.choose.2, p.choose_spec.2.1, p.choose_spec.2.2.symm⟩
-- `touch` is injective
have touch_inj : touch.Injective := fun C D h' => ComponentCompl.pairwise_disjoint.eq
(Set.not_disjoint_iff.mpr ⟨touch C, (C.exists_adj_boundary_pair Gpc.out h).choose_spec.1,
h'.symm ▸ (D.exists_adj_boundary_pair Gpc.out h).choose_spec.1⟩)
-- `touch` has finite range
have : Finite (Set.range touch) := by
refine @Subtype.finite _ (Set.Finite.to_subtype ?_) _
apply Set.Finite.ofFinset (K.biUnion (fun v => G.neighborFinset v))
simp only [Finset.mem_biUnion, mem_neighborFinset, Set.mem_setOf_eq, implies_true]
-- hence `touch` has a finite domain
apply Finite.of_injective_finite_range touch_inj
section Ends
variable (G)
open CategoryTheory
/--
The functor assigning, to a finite set in `V`, the set of connected components in its complement.
-/
@[simps]
def componentComplFunctor : (Finset V)ᵒᵖ ⥤ Type u where
obj K := G.ComponentCompl K.unop
map f := ComponentCompl.hom (le_of_op_hom f)
map_id _ := funext fun C => C.hom_refl
map_comp {_ Y Z} h h' := funext fun C => by
convert C.hom_trans (le_of_op_hom h) (le_of_op_hom _)
exact h'
/-- The end of a graph, defined as the sections of the functor `component_compl_functor` . -/
protected def «end» :=
(componentComplFunctor G).sections
theorem end_hom_mk_of_mk {s} (sec : s ∈ G.end) {K L : (Finset V)ᵒᵖ} (h : L ⟶ K) {v : V}
(vnL : v ∉ L.unop) (hs : s L = G.componentComplMk vnL) :
s K = G.componentComplMk (Set.notMem_subset (le_of_op_hom h : _ ⊆ _) vnL) := by
rw [← sec h, hs]
apply ComponentCompl.hom_mk _ (le_of_op_hom h : _ ⊆ _)
theorem infinite_iff_in_eventualRange {K : (Finset V)ᵒᵖ} (C : G.componentComplFunctor.obj K) :
C.supp.Infinite ↔ C ∈ G.componentComplFunctor.eventualRange K := by
simp only [C.infinite_iff_in_all_ranges, CategoryTheory.Functor.eventualRange, Set.mem_iInter,
Set.mem_range, componentComplFunctor_map]
exact
⟨fun h Lop KL => h Lop.unop (le_of_op_hom KL), fun h L KL =>
h (Opposite.op L) (opHomOfLE KL)⟩
end Ends
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Ends/Properties.lean | import Mathlib.Combinatorics.SimpleGraph.Ends.Defs
import Mathlib.CategoryTheory.CofilteredSystem
/-!
# Properties of the ends of graphs
This file is meant to contain results about the ends of (locally finite connected) graphs.
-/
variable {V : Type} (G : SimpleGraph V)
namespace SimpleGraph
instance [Finite V] : IsEmpty G.end where
false := by
rintro ⟨s, _⟩
cases nonempty_fintype V
obtain ⟨v, h⟩ := (s <| Opposite.op Finset.univ).nonempty
exact Set.disjoint_iff.mp (s _).disjoint_right
⟨by simp only [Finset.coe_univ, Set.mem_univ], h⟩
/-- The `componentCompl`s chosen by an end are all infinite. -/
lemma end_componentCompl_infinite (e : G.end) (K : (Finset V)ᵒᵖ) :
((e : (j : (Finset V)ᵒᵖ) → G.componentComplFunctor.obj j) K).supp.Infinite := by
refine (e.val K).infinite_iff_in_all_ranges.mpr (fun L h => ?_)
change Opposite.unop K ⊆ Opposite.unop (Opposite.op L) at h
exact ⟨e.val (Opposite.op L), (e.prop (CategoryTheory.opHomOfLE h))⟩
instance componentComplFunctor_nonempty_of_infinite [Infinite V] (K : (Finset V)ᵒᵖ) :
Nonempty (G.componentComplFunctor.obj K) := G.componentCompl_nonempty_of_infinite K.unop
instance componentComplFunctor_finite [LocallyFinite G] [Fact G.Preconnected]
(K : (Finset V)ᵒᵖ) : Finite (G.componentComplFunctor.obj K) := G.componentCompl_finite K.unop
/-- A locally finite preconnected infinite graph has at least one end. -/
lemma nonempty_ends_of_infinite [LocallyFinite G] [Fact G.Preconnected] [Infinite V] :
G.end.Nonempty := by
classical
apply nonempty_sections_of_finite_inverse_system G.componentComplFunctor
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Extremal/Basic.lean | import Mathlib.Algebra.Order.Floor.Semiring
import Mathlib.Combinatorics.SimpleGraph.Copy
/-!
# Extremal graph theory
This file introduces basic definitions for extremal graph theory, including extremal numbers.
## Main definitions
* `SimpleGraph.IsExtremal` is the predicate that `G` has the maximum number of edges of any simple
graph, with fixed vertices, satisfying `p`.
* `SimpleGraph.extremalNumber` is the maximum number of edges in a `H`-free simple graph on `n`
vertices.
If `H` is contained in all simple graphs on `n` vertices, then this is `0`.
-/
assert_not_exists Field
open Finset Fintype
namespace SimpleGraph
section IsExtremal
variable {V : Type*} [Fintype V] {G : SimpleGraph V} [DecidableRel G.Adj]
/-- `G` is an extremal graph satisfying `p` if `G` has the maximum number of edges of any simple
graph, with fixed vertices, satisfying `p`. -/
def IsExtremal (G : SimpleGraph V) [DecidableRel G.Adj] (p : SimpleGraph V → Prop) :=
p G ∧ ∀ ⦃G' : SimpleGraph V⦄ [DecidableRel G'.Adj], p G' → #G'.edgeFinset ≤ #G.edgeFinset
lemma IsExtremal.prop {p : SimpleGraph V → Prop} (h : G.IsExtremal p) : p G := h.1
open Classical in
/-- If one simple graph satisfies `p`, then there exists an extremal graph satisfying `p`. -/
theorem exists_isExtremal_iff_exists (p : SimpleGraph V → Prop) :
(∃ G : SimpleGraph V, ∃ _ : DecidableRel G.Adj, G.IsExtremal p) ↔ ∃ G, p G := by
refine ⟨fun ⟨_, _, h⟩ ↦ ⟨_, h.1⟩, fun ⟨G, hp⟩ ↦ ?_⟩
obtain ⟨G', hp', h⟩ := by
apply exists_max_image { G | p G } (#·.edgeFinset)
use G, by simpa using hp
use G', inferInstanceAs (DecidableRel G'.Adj)
exact ⟨by simpa using hp', fun _ _ hp ↦ by convert h _ (by simpa using hp)⟩
/-- If `H` has at least one edge, then there exists an extremal `H.Free` graph. -/
theorem exists_isExtremal_free {W : Type*} {H : SimpleGraph W} (h : H ≠ ⊥) :
∃ G : SimpleGraph V, ∃ _ : DecidableRel G.Adj, G.IsExtremal H.Free :=
(exists_isExtremal_iff_exists H.Free).mpr ⟨⊥, free_bot h⟩
end IsExtremal
section ExtremalNumber
open Classical in
/-- The extremal number of a natural number `n` and a simple graph `H` is the maximum number of
edges in a `H`-free simple graph on `n` vertices.
If `H` is contained in all simple graphs on `n` vertices, then this is `0`. -/
noncomputable def extremalNumber (n : ℕ) {W : Type*} (H : SimpleGraph W) : ℕ :=
sup { G : SimpleGraph (Fin n) | H.Free G } (#·.edgeFinset)
variable {n : ℕ} {V W : Type*} {G : SimpleGraph V} {H : SimpleGraph W}
open Classical in
theorem extremalNumber_of_fintypeCard_eq [Fintype V] (hc : card V = n) :
extremalNumber n H = sup { G : SimpleGraph V | H.Free G } (#·.edgeFinset) := by
let e := Fintype.equivFinOfCardEq hc
rw [extremalNumber, le_antisymm_iff]
and_intros
on_goal 1 =>
replace e := e.symm
all_goals
rw [Finset.sup_le_iff]
intro G h
let G' := G.map e.toEmbedding
replace h' : G' ∈ univ.filter (H.Free ·) := by
rw [mem_filter, ← free_congr .refl (.map e G)]
simpa using h
rw [Iso.card_edgeFinset_eq (.map e G)]
convert @le_sup _ _ _ _ { G | H.Free G } (#·.edgeFinset) G' h'
variable [Fintype V] [DecidableRel G.Adj]
/-- If `G` is `H`-free, then `G` has at most `extremalNumber (card V) H` edges. -/
theorem card_edgeFinset_le_extremalNumber (h : H.Free G) :
#G.edgeFinset ≤ extremalNumber (card V) H := by
rw [extremalNumber_of_fintypeCard_eq rfl]
convert @le_sup _ _ _ _ { G | H.Free G } (#·.edgeFinset) G (by simpa using h)
/-- If `G` has more than `extremalNumber (card V) H` edges, then `G` contains a copy of `H`. -/
theorem IsContained.of_extremalNumber_lt_card_edgeFinset
(h : extremalNumber (card V) H < #G.edgeFinset) : H ⊑ G := by
contrapose h; push_neg
exact card_edgeFinset_le_extremalNumber h
/-- `extremalNumber (card V) H` is at most `x` if and only if every `H`-free simple graph `G` has
at most `x` edges. -/
theorem extremalNumber_le_iff (H : SimpleGraph W) (m : ℕ) :
extremalNumber (card V) H ≤ m ↔
∀ ⦃G : SimpleGraph V⦄ [DecidableRel G.Adj], H.Free G → #G.edgeFinset ≤ m := by
simp_rw [extremalNumber_of_fintypeCard_eq rfl, Finset.sup_le_iff, mem_filter_univ]
exact ⟨fun h _ _ h' ↦ by convert h _ h', fun h _ h' ↦ by convert h h'⟩
/-- `extremalNumber (card V) H` is greater than `x` if and only if there exists a `H`-free simple
graph `G` with more than `x` edges. -/
theorem lt_extremalNumber_iff (H : SimpleGraph W) (m : ℕ) :
m < extremalNumber (card V) H ↔
∃ G : SimpleGraph V, ∃ _ : DecidableRel G.Adj, H.Free G ∧ m < #G.edgeFinset := by
simp_rw [extremalNumber_of_fintypeCard_eq rfl, Finset.lt_sup_iff, mem_filter_univ]
exact ⟨fun ⟨_, h, h'⟩ ↦ ⟨_, _, h, h'⟩, fun ⟨_, _, h, h'⟩ ↦ ⟨_, h, by convert h'⟩⟩
variable {R : Type*} [Semiring R] [LinearOrder R] [FloorSemiring R]
@[inherit_doc extremalNumber_le_iff]
theorem extremalNumber_le_iff_of_nonneg (H : SimpleGraph W) {m : R} (h : 0 ≤ m) :
extremalNumber (card V) H ≤ m ↔
∀ ⦃G : SimpleGraph V⦄ [DecidableRel G.Adj], H.Free G → #G.edgeFinset ≤ m := by
simp_rw [← Nat.le_floor_iff h]
exact extremalNumber_le_iff H ⌊m⌋₊
@[inherit_doc lt_extremalNumber_iff]
theorem lt_extremalNumber_iff_of_nonneg (H : SimpleGraph W) {m : R} (h : 0 ≤ m) :
m < extremalNumber (card V) H ↔
∃ G : SimpleGraph V, ∃ _ : DecidableRel G.Adj, H.Free G ∧ m < #G.edgeFinset := by
simp_rw [← Nat.floor_lt h]
exact lt_extremalNumber_iff H ⌊m⌋₊
/-- If `H` contains a copy of `H'`, then `extremalNumber n H` is at most `extremalNumber n H`. -/
theorem IsContained.extremalNumber_le {W' : Type*} {H' : SimpleGraph W'} (h : H' ⊑ H) :
extremalNumber n H' ≤ extremalNumber n H := by
rw [← Fintype.card_fin n, extremalNumber_le_iff]
intro _ _ h'
contrapose! h'
exact h.trans (IsContained.of_extremalNumber_lt_card_edgeFinset h')
/-- If `H₁ ≃g H₂`, then `extremalNumber n H₁` equals `extremalNumber n H₂`. -/
@[congr]
theorem extremalNumber_congr {n₁ n₂ : ℕ} {W₁ W₂ : Type*} {H₁ : SimpleGraph W₁}
{H₂ : SimpleGraph W₂} (h : n₁ = n₂) (e : H₁ ≃g H₂) :
extremalNumber n₁ H₁ = extremalNumber n₂ H₂ := by
rw [h, le_antisymm_iff]
and_intros
on_goal 2 =>
replace e := e.symm
all_goals
rw [← Fintype.card_fin n₂, extremalNumber_le_iff]
intro G _ h
apply card_edgeFinset_le_extremalNumber
contrapose! h
exact h.trans' ⟨e.toCopy⟩
/-- If `H₁ ≃g H₂`, then `extremalNumber n H₁` equals `extremalNumber n H₂`. -/
theorem extremalNumber_congr_right {W₁ W₂ : Type*} {H₁ : SimpleGraph W₁} {H₂ : SimpleGraph W₂}
(e : H₁ ≃g H₂) : extremalNumber n H₁ = extremalNumber n H₂ := extremalNumber_congr rfl e
/-- `H`-free extremal graphs are `H`-free simple graphs having `extremalNumber (card V) H` many
edges. -/
theorem isExtremal_free_iff :
G.IsExtremal H.Free ↔ H.Free G ∧ #G.edgeFinset = extremalNumber (card V) H := by
rw [IsExtremal, and_congr_right_iff, ← extremalNumber_le_iff]
exact fun h ↦ ⟨eq_of_le_of_ge (card_edgeFinset_le_extremalNumber h), ge_of_eq⟩
lemma card_edgeFinset_of_isExtremal_free (h : G.IsExtremal H.Free) :
#G.edgeFinset = extremalNumber (card V) H := (isExtremal_free_iff.mp h).2
/-- If `G` is `H.Free`, then `G.deleteIncidenceSet v` is also `H.Free` and has at most
`extremalNumber (card V-1) H` many edges. -/
theorem card_edgeFinset_deleteIncidenceSet_le_extremalNumber
[DecidableEq V] (h : H.Free G) (v : V) :
#(G.deleteIncidenceSet v).edgeFinset ≤ extremalNumber (card V - 1) H := by
rw [← card_edgeFinset_induce_compl_singleton, ← @card_unique ({v} : Set V), ← card_compl_set]
apply card_edgeFinset_le_extremalNumber
contrapose! h
exact h.trans ⟨Copy.induce G {v}ᶜ⟩
end ExtremalNumber
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Extremal/Turan.lean | import Mathlib.Combinatorics.SimpleGraph.Clique
import Mathlib.Combinatorics.SimpleGraph.DegreeSum
import Mathlib.Order.Partition.Equipartition
/-!
# Turán's theorem
In this file we prove Turán's theorem, the first important result of extremal graph theory,
which states that the `r + 1`-cliquefree graph on `n` vertices with the most edges is the complete
`r`-partite graph with part sizes as equal as possible (`turanGraph n r`).
The forward direction of the proof performs "Zykov symmetrisation", which first shows
constructively that non-adjacency is an equivalence relation in a maximal graph, so it must be
complete multipartite with the parts being the equivalence classes. Then basic manipulations
show that the graph is isomorphic to the Turán graph for the given parameters.
For the reverse direction we first show that a Turán-maximal graph exists, then transfer
the property through `turanGraph n r` using the isomorphism provided by the forward direction.
## Main declarations
* `SimpleGraph.IsTuranMaximal`: `G.IsTuranMaximal r` means that `G` has the most number of edges for
its number of vertices while still being `r + 1`-cliquefree.
* `SimpleGraph.turanGraph n r`: The canonical `r + 1`-cliquefree Turán graph on `n` vertices.
* `SimpleGraph.IsTuranMaximal.finpartition`: The result of Zykov symmetrisation, a finpartition of
the vertices such that two vertices are in the same part iff they are non-adjacent.
* `SimpleGraph.IsTuranMaximal.nonempty_iso_turanGraph`: The forward direction, an isomorphism
between `G` satisfying `G.IsTuranMaximal r` and `turanGraph n r`.
* `isTuranMaximal_of_iso`: the reverse direction, `G.IsTuranMaximal r` given the isomorphism.
* `isTuranMaximal_iff_nonempty_iso_turanGraph`: Turán's theorem in full.
## References
* https://en.wikipedia.org/wiki/Turán%27s_theorem
-/
open Finset
namespace SimpleGraph
variable {V : Type*} [Fintype V] {G : SimpleGraph V} [DecidableRel G.Adj] {n r : ℕ}
variable (G) in
/-- An `r + 1`-cliquefree graph is `r`-Turán-maximal if any other `r + 1`-cliquefree graph on
the same vertex set has the same or fewer number of edges. -/
def IsTuranMaximal (r : ℕ) : Prop :=
G.CliqueFree (r + 1) ∧ ∀ (H : SimpleGraph V) [DecidableRel H.Adj],
H.CliqueFree (r + 1) → #H.edgeFinset ≤ #G.edgeFinset
section Defs
variable {H : SimpleGraph V}
lemma IsTuranMaximal.le_iff_eq (hG : G.IsTuranMaximal r) (hH : H.CliqueFree (r + 1)) :
G ≤ H ↔ G = H := by
classical exact ⟨fun hGH ↦ edgeFinset_inj.1 <| eq_of_subset_of_card_le
(edgeFinset_subset_edgeFinset.2 hGH) (hG.2 _ hH), le_of_eq⟩
/-- The canonical `r + 1`-cliquefree Turán graph on `n` vertices. -/
def turanGraph (n r : ℕ) : SimpleGraph (Fin n) where Adj v w := v % r ≠ w % r
lemma turanGraph_adj {v w} : (turanGraph n r).Adj v w ↔ v % r ≠ w % r :=
.rfl
instance turanGraph.instDecidableRelAdj : DecidableRel (turanGraph n r).Adj := by
dsimp only [turanGraph]; infer_instance
@[simp]
lemma turanGraph_zero : turanGraph n 0 = ⊤ := by
ext a b; simp_rw [turanGraph, top_adj, Nat.mod_zero, not_iff_not, Fin.val_inj]
@[simp]
theorem turanGraph_eq_top : turanGraph n r = ⊤ ↔ r = 0 ∨ n ≤ r := by
simp_rw [SimpleGraph.ext_iff, funext_iff, turanGraph, top_adj, eq_iff_iff, not_iff_not]
refine ⟨fun h ↦ ?_, ?_⟩
· contrapose! h
use ⟨0, (Nat.pos_of_ne_zero h.1).trans h.2⟩, ⟨r, h.2⟩
simp [h.1.symm]
· rintro (rfl | h) a b
· simp [Fin.val_inj]
· rw [Nat.mod_eq_of_lt (a.2.trans_le h), Nat.mod_eq_of_lt (b.2.trans_le h), Fin.val_inj]
theorem turanGraph_cliqueFree (hr : 0 < r) : (turanGraph n r).CliqueFree (r + 1) := by
rw [cliqueFree_iff]
by_contra! h
obtain ⟨f, ha⟩ := h
simp only [turanGraph, top_adj] at ha
obtain ⟨x, y, d, c⟩ := Fintype.exists_ne_map_eq_of_card_lt (fun x ↦
(⟨(f x).1 % r, Nat.mod_lt _ hr⟩ : Fin r)) (by simp)
simp only [Fin.mk.injEq] at c
exact absurd c ((@ha x y).mpr d)
/-- An `r + 1`-cliquefree Turán-maximal graph is _not_ `r`-cliquefree
if it can accommodate such a clique. -/
theorem not_cliqueFree_of_isTuranMaximal (hn : r ≤ Fintype.card V) (hG : G.IsTuranMaximal r) :
¬G.CliqueFree r := by
rintro h
obtain ⟨K, _, rfl⟩ := exists_subset_card_eq hn
obtain ⟨a, -, b, -, hab, hGab⟩ : ∃ a ∈ K, ∃ b ∈ K, a ≠ b ∧ ¬ G.Adj a b := by
simpa only [isNClique_iff, IsClique, Set.Pairwise, mem_coe, ne_eq, and_true, not_forall,
exists_prop, exists_and_right] using h K
exact hGab <| le_sup_right.trans_eq ((hG.le_iff_eq <| h.sup_edge _ _).1 le_sup_left).symm <|
(edge_adj ..).2 ⟨Or.inl ⟨rfl, rfl⟩, hab⟩
lemma exists_isTuranMaximal (hr : 0 < r) :
∃ H : SimpleGraph V, ∃ _ : DecidableRel H.Adj, H.IsTuranMaximal r := by
classical
let c := {H : SimpleGraph V | H.CliqueFree (r + 1)}
have cn : c.toFinset.Nonempty := ⟨⊥, by
rw [Set.toFinset_setOf, mem_filter_univ]
exact cliqueFree_bot (by cutsat)⟩
obtain ⟨S, Sm, Sl⟩ := exists_max_image c.toFinset (#·.edgeFinset) cn
use S, inferInstance
rw [Set.mem_toFinset] at Sm
refine ⟨Sm, fun I _ cf ↦ ?_⟩
by_cases Im : I ∈ c.toFinset
· convert Sl I Im
· rw [Set.mem_toFinset] at Im
contradiction
end Defs
namespace IsTuranMaximal
variable {s t u : V}
/-- In a Turán-maximal graph, non-adjacent vertices have the same degree. -/
lemma degree_eq_of_not_adj (h : G.IsTuranMaximal r) (hn : ¬G.Adj s t) :
G.degree s = G.degree t := by
rw [IsTuranMaximal] at h; contrapose! h; intro cf
wlog hd : G.degree t < G.degree s generalizing G t s
· replace hd : G.degree s < G.degree t := lt_of_le_of_ne (le_of_not_gt hd) h
exact this (by rwa [adj_comm] at hn) hd.ne' cf hd
classical
use G.replaceVertex s t, inferInstance, cf.replaceVertex s t
have := G.card_edgeFinset_replaceVertex_of_not_adj hn
cutsat
/-- In a Turán-maximal graph, non-adjacency is transitive. -/
lemma not_adj_trans (h : G.IsTuranMaximal r) (hts : ¬G.Adj t s) (hsu : ¬G.Adj s u) :
¬G.Adj t u := by
have hst : ¬G.Adj s t := fun a ↦ hts a.symm
have dst := h.degree_eq_of_not_adj hst
have dsu := h.degree_eq_of_not_adj hsu
rw [IsTuranMaximal] at h; contrapose! h; intro cf
classical
use (G.replaceVertex s t).replaceVertex s u, inferInstance,
(cf.replaceVertex s t).replaceVertex s u
have nst : s ≠ t := fun a ↦ hsu (a ▸ h)
have ntu : t ≠ u := G.ne_of_adj h
have := (G.adj_replaceVertex_iff_of_ne s nst ntu.symm).not.mpr hsu
rw [card_edgeFinset_replaceVertex_of_not_adj _ this,
card_edgeFinset_replaceVertex_of_not_adj _ hst, dst, Nat.add_sub_cancel]
have l1 : (G.replaceVertex s t).degree s = G.degree s := by
unfold degree; congr 1; ext v
simp only [mem_neighborFinset]
by_cases eq : v = t
· simpa only [eq, not_adj_replaceVertex_same, false_iff]
· rw [G.adj_replaceVertex_iff_of_ne s nst eq]
have l2 : (G.replaceVertex s t).degree u = G.degree u - 1 := by
rw [degree, degree, ← card_singleton t, ← card_sdiff_of_subset (by simp [h.symm])]
congr 1; ext v
simp only [mem_neighborFinset, mem_sdiff, mem_singleton, replaceVertex]
split_ifs <;> simp_all [adj_comm]
have l3 : 0 < G.degree u := by rw [G.degree_pos_iff_exists_adj u]; use t, h.symm
cutsat
variable (h : G.IsTuranMaximal r)
include h
/-- In a Turán-maximal graph, non-adjacency is an equivalence relation. -/
theorem equivalence_not_adj : Equivalence (¬G.Adj · ·) where
refl := by simp
symm := by simp [adj_comm]
trans := h.not_adj_trans
/-- The non-adjacency setoid over the vertices of a Turán-maximal graph
induced by `equivalence_not_adj`. -/
def setoid : Setoid V := ⟨_, h.equivalence_not_adj⟩
instance : DecidableRel h.setoid.r :=
inferInstanceAs <| DecidableRel (¬G.Adj · ·)
/-- The finpartition derived from `h.setoid`. -/
def finpartition [DecidableEq V] : Finpartition (univ : Finset V) := Finpartition.ofSetoid h.setoid
lemma not_adj_iff_part_eq [DecidableEq V] :
¬G.Adj s t ↔ h.finpartition.part s = h.finpartition.part t := by
change h.setoid.r s t ↔ _
rw [← Finpartition.mem_part_ofSetoid_iff_rel]
let fp := h.finpartition
change t ∈ fp.part s ↔ fp.part s = fp.part t
rw [fp.mem_part_iff_part_eq_part (mem_univ t) (mem_univ s), eq_comm]
lemma degree_eq_card_sub_part_card [DecidableEq V] :
G.degree s = Fintype.card V - #(h.finpartition.part s) :=
calc
_ = #{t | G.Adj s t} := by
simp [← card_neighborFinset_eq_degree, neighborFinset]
_ = Fintype.card V - #{t | ¬G.Adj s t} :=
eq_tsub_of_add_eq (filter_card_add_filter_neg_card_eq_card _)
_ = _ := by
congr; ext; rw [mem_filter]
convert Finpartition.mem_part_ofSetoid_iff_rel.symm
simp [setoid]
/-- The parts of a Turán-maximal graph form an equipartition. -/
theorem isEquipartition [DecidableEq V] : h.finpartition.IsEquipartition := by
set fp := h.finpartition
by_contra hn
rw [Finpartition.not_isEquipartition] at hn
obtain ⟨large, hl, small, hs, ineq⟩ := hn
obtain ⟨w, hw⟩ := fp.nonempty_of_mem_parts hl
obtain ⟨v, hv⟩ := fp.nonempty_of_mem_parts hs
apply absurd h
rw [IsTuranMaximal]; push_neg; intro cf
use G.replaceVertex v w, inferInstance, cf.replaceVertex v w
have large_eq := fp.part_eq_of_mem hl hw
have small_eq := fp.part_eq_of_mem hs hv
have ha : G.Adj v w := by
by_contra hn; rw [h.not_adj_iff_part_eq, small_eq, large_eq] at hn
rw [hn] at ineq; omega
rw [G.card_edgeFinset_replaceVertex_of_adj ha,
degree_eq_card_sub_part_card h, small_eq, degree_eq_card_sub_part_card h, large_eq]
have : #large ≤ Fintype.card V := by simpa using card_le_card large.subset_univ
cutsat
lemma card_parts_le [DecidableEq V] : #h.finpartition.parts ≤ r := by
by_contra! l
obtain ⟨z, -, hz⟩ := h.finpartition.exists_subset_part_bijOn
have ncf : ¬G.CliqueFree #z := by
refine IsNClique.not_cliqueFree ⟨fun v hv w hw hn ↦ ?_, rfl⟩
contrapose! hn
exact hz.injOn hv hw (by rwa [← h.not_adj_iff_part_eq])
rw [Finset.card_eq_of_equiv hz.equiv] at ncf
exact absurd (h.1.mono (Nat.succ_le_of_lt l)) ncf
/-- There are `min n r` parts in a graph on `n` vertices satisfying `G.IsTuranMaximal r`.
`min` handles the `n < r` case, when `G` is complete but still `r + 1`-cliquefree
for having insufficiently many vertices. -/
theorem card_parts [DecidableEq V] : #h.finpartition.parts = min (Fintype.card V) r := by
set fp := h.finpartition
apply le_antisymm (le_min fp.card_parts_le_card h.card_parts_le)
by_contra! l
rw [lt_min_iff] at l
obtain ⟨x, -, y, -, hn, he⟩ :=
exists_ne_map_eq_of_card_lt_of_maps_to l.1 fun a _ ↦ fp.part_mem.2 (mem_univ a)
apply absurd h
rw [IsTuranMaximal]; push_neg; rintro -
have cf : G.CliqueFree r := by
simp_rw [← cliqueFinset_eq_empty_iff, cliqueFinset, filter_eq_empty_iff, mem_univ,
forall_true_left, isNClique_iff, and_comm, not_and, isClique_iff, Set.Pairwise]
intro z zc; push_neg; simp_rw [h.not_adj_iff_part_eq]
exact exists_ne_map_eq_of_card_lt_of_maps_to (zc.symm ▸ l.2) fun a _ ↦
fp.part_mem.2 (mem_univ a)
use G ⊔ edge x y, inferInstance, cf.sup_edge x y
convert Nat.lt.base #G.edgeFinset
convert G.card_edgeFinset_sup_edge _ hn
rwa [h.not_adj_iff_part_eq]
/-- **Turán's theorem**, forward direction.
Any `r + 1`-cliquefree Turán-maximal graph on `n` vertices is isomorphic to `turanGraph n r`. -/
theorem nonempty_iso_turanGraph :
Nonempty (G ≃g turanGraph (Fintype.card V) r) := by
classical
obtain ⟨zm, zp⟩ := h.isEquipartition.exists_partPreservingEquiv
use (Equiv.subtypeUnivEquiv mem_univ).symm.trans zm
intro a b
simp_rw [turanGraph, Equiv.trans_apply, Equiv.subtypeUnivEquiv_symm_apply]
have := zp ⟨a, mem_univ a⟩ ⟨b, mem_univ b⟩
rw [← h.not_adj_iff_part_eq] at this
rw [← not_iff_not, not_ne_iff, this, card_parts]
rcases le_or_gt r (Fintype.card V) with c | c
· rw [min_eq_right c]; rfl
· have lc : ∀ x, zm ⟨x, _⟩ < Fintype.card V := fun x ↦ (zm ⟨x, mem_univ x⟩).2
rw [min_eq_left c.le, Nat.mod_eq_of_lt (lc a), Nat.mod_eq_of_lt (lc b),
← Nat.mod_eq_of_lt ((lc a).trans c), ← Nat.mod_eq_of_lt ((lc b).trans c)]; rfl
end IsTuranMaximal
/-- **Turán's theorem**, reverse direction.
Any graph isomorphic to `turanGraph n r` is itself Turán-maximal if `0 < r`. -/
theorem isTuranMaximal_of_iso (f : G ≃g turanGraph n r) (hr : 0 < r) : G.IsTuranMaximal r := by
obtain ⟨J, _, j⟩ := exists_isTuranMaximal (V := V) hr
obtain ⟨g⟩ := j.nonempty_iso_turanGraph
rw [f.card_eq, Fintype.card_fin] at g
use (turanGraph_cliqueFree (n := n) hr).comap f,
fun H _ cf ↦ (f.symm.comp g).card_edgeFinset_eq ▸ j.2 H cf
/-- Turán-maximality with `0 < r` transfers across graph isomorphisms. -/
theorem IsTuranMaximal.iso {W : Type*} [Fintype W] {H : SimpleGraph W}
[DecidableRel H.Adj] (h : G.IsTuranMaximal r) (f : G ≃g H) (hr : 0 < r) : H.IsTuranMaximal r :=
isTuranMaximal_of_iso (h.nonempty_iso_turanGraph.some.comp f.symm) hr
/-- For `0 < r`, `turanGraph n r` is Turán-maximal. -/
theorem isTuranMaximal_turanGraph (hr : 0 < r) : (turanGraph n r).IsTuranMaximal r :=
isTuranMaximal_of_iso Iso.refl hr
/-- **Turán's theorem**. `turanGraph n r` is, up to isomorphism, the unique
`r + 1`-cliquefree Turán-maximal graph on `n` vertices. -/
theorem isTuranMaximal_iff_nonempty_iso_turanGraph (hr : 0 < r) :
G.IsTuranMaximal r ↔ Nonempty (G ≃g turanGraph (Fintype.card V) r) :=
⟨fun h ↦ h.nonempty_iso_turanGraph, fun h ↦ isTuranMaximal_of_iso h.some hr⟩
/-! ### Number of edges in the Turán graph -/
private lemma sum_ne_add_mod_eq_sub_one {c : ℕ} :
∑ w ∈ range r, (if c % r ≠ (n + w) % r then 1 else 0) = r - 1 := by
rcases r.eq_zero_or_pos with rfl | hr; · simp
suffices #{i ∈ range r | c % r = (n + i) % r} = 1 by
rw [← card_filter, ← this]; apply Nat.eq_sub_of_add_eq'
rw [filter_card_add_filter_neg_card_eq_card, card_range]
apply le_antisymm
· change #{i ∈ range r | _ ≡ _ [MOD r]} ≤ 1
rw [card_le_one_iff]; intro w x mw mx
simp only [mem_filter, mem_range] at mw mx
have := mw.2.symm.trans mx.2
rw [Nat.ModEq.add_iff_left rfl] at this
change w % r = x % r at this
rwa [Nat.mod_eq_of_lt mw.1, Nat.mod_eq_of_lt mx.1] at this
· rw [one_le_card]; use ((r - 1) * n + c) % r
simp only [mem_filter, mem_range]; refine ⟨Nat.mod_lt _ hr, ?_⟩
rw [Nat.add_mod_mod, ← add_assoc, ← one_add_mul, show 1 + (r - 1) = r by cutsat,
Nat.mul_add_mod_self_left]
lemma card_edgeFinset_turanGraph_add :
#(turanGraph (n + r) r).edgeFinset =
#(turanGraph n r).edgeFinset + n * (r - 1) + r.choose 2 := by
rw [← mul_right_inj' two_ne_zero]
simp_rw [mul_add, ← sum_degrees_eq_twice_card_edges,
degree, neighborFinset_eq_filter, turanGraph, card_filter]
conv_lhs =>
enter [2, v]
rw [Fin.sum_univ_eq_sum_range fun w ↦ if v % r ≠ w % r then 1 else 0, sum_range_add]
rw [sum_add_distrib,
Fin.sum_univ_eq_sum_range fun v ↦ ∑ w ∈ range n, if v % r ≠ w % r then 1 else 0,
Fin.sum_univ_eq_sum_range fun v ↦ ∑ w ∈ range r, if v % r ≠ (n + w) % r then 1 else 0,
sum_range_add, sum_range_add, add_assoc, add_assoc]
congr 1; · simp [← Fin.sum_univ_eq_sum_range]
rw [← add_assoc, sum_comm]; simp_rw [ne_comm, ← two_mul]; congr
· conv_rhs => rw [← card_range n, ← smul_eq_mul, ← sum_const]
congr!; exact sum_ne_add_mod_eq_sub_one
· rw [mul_comm 2, Nat.choose_two_right, Nat.div_two_mul_two_of_even (Nat.even_mul_pred_self r)]
conv_rhs => enter [1]; rw [← card_range r]
rw [← smul_eq_mul, ← sum_const]
congr!; exact sum_ne_add_mod_eq_sub_one
/-- The exact formula for the number of edges in `turanGraph n r`. -/
theorem card_edgeFinset_turanGraph {n r : ℕ} :
#(turanGraph n r).edgeFinset =
(n ^ 2 - (n % r) ^ 2) * (r - 1) / (2 * r) + (n % r).choose 2 := by
rcases r.eq_zero_or_pos with rfl | hr
· rw [Nat.mod_zero, tsub_self, zero_mul, Nat.zero_div, zero_add]
have := card_edgeFinset_top_eq_card_choose_two (V := Fin n)
rw [Fintype.card_fin] at this; convert this; exact turanGraph_zero
· have ring₁ (n) : (n ^ 2 - (n % r) ^ 2) * (r - 1) / (2 * r) =
n % r * (n / r) * (r - 1) + r * (r - 1) * (n / r) ^ 2 / 2 := by
nth_rw 1 [← Nat.mod_add_div n r, Nat.sq_sub_sq, add_tsub_cancel_left,
show (n % r + r * (n / r) + n % r) * (r * (n / r)) * (r - 1) =
(2 * ((n % r) * (n / r) * (r - 1)) + r * (r - 1) * (n / r) ^ 2) * r by grind]
rw [Nat.mul_div_mul_right _ _ hr, Nat.mul_add_div zero_lt_two]
rcases lt_or_ge n r with h | h
· rw [Nat.mod_eq_of_lt h, tsub_self, zero_mul, Nat.zero_div, zero_add]
have := card_edgeFinset_top_eq_card_choose_two (V := Fin n)
rw [Fintype.card_fin] at this; convert this
rw [turanGraph_eq_top]; exact .inr h.le
· let n' := n - r
have n'r : n = n' + r := by omega
rw [n'r, card_edgeFinset_turanGraph_add, card_edgeFinset_turanGraph, ring₁, ring₁,
add_rotate, ← add_assoc, Nat.add_mod_right, Nat.add_div_right _ hr]
congr 1
have rd : 2 ∣ r * (r - 1) := (Nat.even_mul_pred_self _).two_dvd
rw [← Nat.div_mul_right_comm rd, ← Nat.div_mul_right_comm rd, ← Nat.choose_two_right]
have ring₂ : n' % r * (n' / r + 1) * (r - 1) + r.choose 2 * (n' / r + 1) ^ 2 =
n' % r * (n' / r + 1) * (r - 1) + r.choose 2 +
r.choose 2 * 2 * (n' / r) + r.choose 2 * (n' / r) ^ 2 := by grind
rw [ring₂, ← add_assoc]; congr 1
rw [← add_rotate, ← add_rotate _ _ (r.choose 2)]; congr 1
rw [Nat.choose_two_right, Nat.div_mul_cancel rd, mul_add_one, add_mul, ← add_assoc,
← add_rotate, add_comm _ (_ *_)]; congr 1
rw [← mul_rotate, ← add_mul, add_comm, mul_comm _ r, Nat.div_add_mod n' r]
/-- A looser (but simpler than `card_edgeFinset_turanGraph`) bound on the number of edges in
`turanGraph n r`. -/
theorem mul_card_edgeFinset_turanGraph_le :
2 * r * #(turanGraph n r).edgeFinset ≤ (r - 1) * n ^ 2 := by
grw [card_edgeFinset_turanGraph, mul_add, Nat.mul_div_le]
rw [tsub_mul, ← Nat.sub_add_comm]; swap
· grw [Nat.mod_le]
exact Nat.zero_le _
rw [Nat.sub_le_iff_le_add, mul_comm, Nat.add_le_add_iff_left, Nat.choose_two_right,
← Nat.mul_div_assoc _ (Nat.even_mul_pred_self _).two_dvd, mul_assoc,
mul_div_cancel_left₀ _ two_ne_zero, ← mul_assoc, ← mul_rotate, sq, ← mul_rotate (r - 1)]
gcongr ?_ * _
rcases r.eq_zero_or_pos with rfl | hr; · cutsat
rw [Nat.sub_one_mul, Nat.sub_one_mul, mul_comm]
exact Nat.sub_le_sub_left (Nat.mod_lt _ hr).le _
theorem CliqueFree.card_edgeFinset_le (cf : G.CliqueFree (r + 1)) :
let n := Fintype.card V;
#G.edgeFinset ≤ (n ^ 2 - (n % r) ^ 2) * (r - 1) / (2 * r) + (n % r).choose 2 := by
rcases r.eq_zero_or_pos with rfl | hr
· rw [cliqueFree_one, ← Fintype.card_eq_zero_iff] at cf
simp_rw [zero_tsub, mul_zero, Nat.mod_zero, Nat.div_zero, zero_add]
exact card_edgeFinset_le_card_choose_two
· obtain ⟨H, _, maxH⟩ := exists_isTuranMaximal (V := V) hr
convert maxH.2 _ cf
rw [((isTuranMaximal_iff_nonempty_iso_turanGraph hr).mp maxH).some.card_edgeFinset_eq,
card_edgeFinset_turanGraph]
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/SimpleGraph/Extremal/TuranDensity.lean | import Mathlib.Analysis.Asymptotics.AsymptoticEquivalent
import Mathlib.Combinatorics.Enumerative.DoubleCounting
import Mathlib.Combinatorics.SimpleGraph.DeleteEdges
import Mathlib.Combinatorics.SimpleGraph.Extremal.Basic
import Mathlib.Data.Nat.Choose.Cast
/-!
# Turán density
This file defines the **Turán density** of a simple graph.
## Main definitions
* `SimpleGraph.turanDensity H` is the **Turán density** of the simple graph `H`, defined as the
limit of `extremalNumber n H / n.choose 2` as `n` approaches `∞`.
* `SimpleGraph.tendsto_turanDensity` is the proof that `SimpleGraph.turanDensity` is well-defined.
* `SimpleGraph.isEquivalent_extremalNumber` is the proof that `extremalNumber n H` is
asymptotically equivalent to `turanDensity H * n.choose 2` as `n` approaches `∞`.
-/
open Asymptotics Filter Finset Fintype Topology
namespace SimpleGraph
variable {V W : Type*} {G : SimpleGraph V} {H : SimpleGraph W}
lemma antitoneOn_extremalNumber_div_choose_two (H : SimpleGraph W) :
AntitoneOn (fun n ↦ (extremalNumber n H / n.choose 2 : ℝ)) (Set.Ici 2) := by
apply antitoneOn_nat_Ici_of_succ_le
intro n hn
conv_lhs =>
enter [1, 1]
rw [← Fintype.card_fin (n+1)]
rw [div_le_iff₀ (mod_cast Nat.choose_pos (by linarith)),
extremalNumber_le_iff_of_nonneg H (by positivity)]
intro G _ h
rw [mul_comm, ← mul_div_assoc, le_div_iff₀' (mod_cast Nat.choose_pos hn), Nat.cast_choose_two,
Nat.cast_choose_two, Nat.cast_add_one, add_sub_cancel_right (n : ℝ) 1,
mul_comm _ (n-1 : ℝ), ← mul_div (n-1 : ℝ), mul_comm _ (n/2 : ℝ), mul_assoc, mul_comm (n-1 : ℝ),
← mul_div (n+1 : ℝ), mul_comm _ (n/2 : ℝ), mul_assoc, mul_le_mul_iff_right₀ (by positivity),
← Nat.cast_pred (by positivity), ←Nat.cast_mul, ←Nat.cast_add_one, ←Nat.cast_mul, Nat.cast_le]
conv_rhs =>
rw [← Fintype.card_fin (n+1), ← card_univ]
-- double counting `(v, e) ↦ v ∉ e`
apply card_nsmul_le_card_nsmul' (r := fun v e ↦ v ∉ e)
-- counting `e`
· intro e he
simp_rw [← Sym2.mem_toFinset, bipartiteBelow, filter_not, filter_mem_eq_inter, univ_inter,
← compl_eq_univ_sdiff, card_compl, Fintype.card_fin, card_toFinset_mem_edgeFinset ⟨e, he⟩,
Nat.cast_id, Nat.reduceSubDiff, le_refl]
-- counting `v`
· intro v hv
simpa [edgeFinset_deleteIncidenceSet_eq_filter]
using card_edgeFinset_deleteIncidenceSet_le_extremalNumber h v
/-- The **Turán density** of a simple graph `H` is the limit of `extremalNumber n H / n.choose 2`
as `n` approaches `∞`.
See `SimpleGraph.tendsto_turanDensity` for proof of existence. -/
noncomputable def turanDensity (H : SimpleGraph W) :=
limUnder atTop fun n ↦ (extremalNumber n H / n.choose 2 : ℝ)
/-- The **Turán density** of a simple graph `H` is well-defined. -/
theorem tendsto_turanDensity (H : SimpleGraph W) :
Tendsto (fun n ↦ (extremalNumber n H / n.choose 2 : ℝ)) atTop (𝓝 (turanDensity H)) := by
let f := fun n ↦ (extremalNumber n H / n.choose 2 : ℝ)
suffices h : ∃ x, Tendsto (fun n ↦ f (n + 2)) atTop (𝓝 x) by
obtain ⟨_, h⟩ := by simpa [tendsto_add_atTop_iff_nat 2] using h
simpa [← Tendsto.limUnder_eq h] using h
use ⨅ n, f (n + 2)
apply tendsto_atTop_ciInf
· rw [antitone_add_nat_iff_antitoneOn_nat_Ici]
exact antitoneOn_extremalNumber_div_choose_two H
· use 0
intro n ⟨_, hn⟩
rw [← hn]
positivity
/-- `extremalNumber n H` is asymptotically equivalent to `turanDensity H * n.choose 2` as `n`
approaches `∞`. -/
theorem isEquivalent_extremalNumber (h : turanDensity H ≠ 0) :
(fun n ↦ (extremalNumber n H : ℝ)) ~[atTop] (fun n ↦ (turanDensity H * n.choose 2 : ℝ)) := by
have hπ := tendsto_turanDensity H
apply Tendsto.const_mul (1/turanDensity H : ℝ) at hπ
simp_rw [one_div_mul_cancel h, div_mul_div_comm, one_mul] at hπ
have hz : ∀ᶠ (x : ℕ) in atTop, turanDensity H * x.choose 2 ≠ 0 := by
rw [eventually_atTop]
use 2
intro n hn
simp [h, Nat.choose_eq_zero_iff, hn]
simpa [isEquivalent_iff_tendsto_one hz] using hπ
end SimpleGraph |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/Energy.lean | import Mathlib.Algebra.Order.BigOperators.Ring.Finset
import Mathlib.Data.Finset.Prod
import Mathlib.Data.Fintype.Prod
import Mathlib.Algebra.Group.Pointwise.Finset.Basic
/-!
# Additive energy
This file defines the additive energy of two finsets of a group. This is a central quantity in
additive combinatorics.
## Main declarations
* `Finset.addEnergy`: The additive energy of two finsets in an additive group.
* `Finset.mulEnergy`: The multiplicative energy of two finsets in a group.
## Notation
The following notations are defined in the `Combinatorics.Additive` scope:
* `E[s, t]` for `Finset.addEnergy s t`.
* `Eₘ[s, t]` for `Finset.mulEnergy s t`.
* `E[s]` for `E[s, s]`.
* `Eₘ[s]` for `Eₘ[s, s]`.
## TODO
It's possibly interesting to have
`(s ×ˢ s) ×ˢ t ×ˢ t).filter (fun x : (α × α) × α × α ↦ x.1.1 * x.2.1 = x.1.2 * x.2.2)`
(whose `card` is `mulEnergy s t`) as a standalone definition.
-/
open scoped Pointwise
variable {α : Type*} [DecidableEq α]
namespace Finset
section Mul
variable [Mul α] {s s₁ s₂ t t₁ t₂ : Finset α}
/-- The multiplicative energy `Eₘ[s, t]` of two finsets `s` and `t` in a group is the number of
quadruples `(a₁, a₂, b₁, b₂) ∈ s × s × t × t` such that `a₁ * b₁ = a₂ * b₂`.
The notation `Eₘ[s, t]` is available in scope `Combinatorics.Additive`. -/
@[to_additive
/-- The additive energy `E[s, t]` of two finsets `s` and `t` in a group is the number of quadruples
`(a₁, a₂, b₁, b₂) ∈ s × s × t × t` such that `a₁ + b₁ = a₂ + b₂`.
The notation `E[s, t]` is available in scope `Combinatorics.Additive`. -/]
def mulEnergy (s t : Finset α) : ℕ :=
#{x ∈ ((s ×ˢ s) ×ˢ t ×ˢ t) | x.1.1 * x.2.1 = x.1.2 * x.2.2}
/-- The multiplicative energy of two finsets `s` and `t` in a group is the number of quadruples
`(a₁, a₂, b₁, b₂) ∈ s × s × t × t` such that `a₁ * b₁ = a₂ * b₂`. -/
scoped[Combinatorics.Additive] notation3:max "Eₘ[" s ", " t "]" => Finset.mulEnergy s t
/-- The additive energy of two finsets `s` and `t` in a group is the number of quadruples
`(a₁, a₂, b₁, b₂) ∈ s × s × t × t` such that `a₁ + b₁ = a₂ + b₂`. -/
scoped[Combinatorics.Additive] notation3:max "E[" s ", " t "]" => Finset.addEnergy s t
/-- The multiplicative energy of a finset `s` in a group is the number of quadruples
`(a₁, a₂, b₁, b₂) ∈ s × s × s × s` such that `a₁ * b₁ = a₂ * b₂`. -/
scoped[Combinatorics.Additive] notation3:max "Eₘ[" s "]" => Finset.mulEnergy s s
/-- The additive energy of a finset `s` in a group is the number of quadruples
`(a₁, a₂, b₁, b₂) ∈ s × s × s × s` such that `a₁ + b₁ = a₂ + b₂`. -/
scoped[Combinatorics.Additive] notation3:max "E[" s "]" => Finset.addEnergy s s
open scoped Combinatorics.Additive
@[to_additive (attr := gcongr)]
lemma mulEnergy_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : Eₘ[s₁, t₁] ≤ Eₘ[s₂, t₂] := by
unfold mulEnergy; gcongr
@[to_additive] lemma mulEnergy_mono_left (hs : s₁ ⊆ s₂) : Eₘ[s₁, t] ≤ Eₘ[s₂, t] :=
mulEnergy_mono hs Subset.rfl
@[to_additive] lemma mulEnergy_mono_right (ht : t₁ ⊆ t₂) : Eₘ[s, t₁] ≤ Eₘ[s, t₂] :=
mulEnergy_mono Subset.rfl ht
@[to_additive] lemma le_mulEnergy : #s * #t ≤ Eₘ[s, t] := by
rw [← card_product]
exact card_le_card_of_injOn (fun x => ((x.1, x.1), x.2, x.2)) (by simp [Set.MapsTo]) (by simp)
@[to_additive] lemma le_mulEnergy_self : #s ^ 2 ≤ Eₘ[s] := sq #s ▸ le_mulEnergy
@[to_additive] lemma mulEnergy_pos (hs : s.Nonempty) (ht : t.Nonempty) : 0 < Eₘ[s, t] :=
(mul_pos hs.card_pos ht.card_pos).trans_le le_mulEnergy
@[to_additive] lemma mulEnergy_self_pos (hs : s.Nonempty) : 0 < Eₘ[s] :=
mulEnergy_pos hs hs
variable (s t)
@[to_additive (attr := simp)] lemma mulEnergy_empty_left : Eₘ[∅, t] = 0 := by simp [mulEnergy]
@[to_additive (attr := simp)] lemma mulEnergy_empty_right : Eₘ[s, ∅] = 0 := by simp [mulEnergy]
variable {s t}
@[to_additive (attr := simp)] lemma mulEnergy_pos_iff : 0 < Eₘ[s, t] ↔ s.Nonempty ∧ t.Nonempty where
mp h := of_not_not fun H => by
simp_rw [not_and_or, not_nonempty_iff_eq_empty] at H
obtain rfl | rfl := H <;> simp at h
mpr h := mulEnergy_pos h.1 h.2
@[to_additive (attr := simp)] lemma mulEnergy_eq_zero_iff : Eₘ[s, t] = 0 ↔ s = ∅ ∨ t = ∅ := by
simp [← (Nat.zero_le _).not_lt_iff_eq', imp_iff_or_not, or_comm]
@[to_additive] lemma mulEnergy_self_pos_iff : 0 < Eₘ[s] ↔ s.Nonempty := by
rw [mulEnergy_pos_iff, and_self_iff]
@[to_additive] lemma mulEnergy_self_eq_zero_iff : Eₘ[s] = 0 ↔ s = ∅ := by
rw [mulEnergy_eq_zero_iff, or_self_iff]
@[to_additive] lemma mulEnergy_eq_card_filter (s t : Finset α) :
Eₘ[s, t] = #{x ∈ ((s ×ˢ t) ×ˢ s ×ˢ t) | x.1.1 * x.1.2 = x.2.1 * x.2.2} :=
card_equiv (.prodProdProdComm _ _ _ _) (by simp [and_and_and_comm])
@[to_additive] lemma mulEnergy_eq_sum_sq' (s t : Finset α) :
Eₘ[s, t] = ∑ a ∈ s * t, #{xy ∈ s ×ˢ t | xy.1 * xy.2 = a} ^ 2 := by
simp_rw [mulEnergy_eq_card_filter, sq, ← card_product]
rw [← card_disjiUnion]
swap
· aesop (add simp [Set.PairwiseDisjoint, Set.Pairwise, disjoint_left])
· congr
aesop (add unsafe mul_mem_mul)
@[to_additive] lemma mulEnergy_eq_sum_sq [Fintype α] (s t : Finset α) :
Eₘ[s, t] = ∑ a, #{xy ∈ s ×ˢ t | xy.1 * xy.2 = a} ^ 2 := by
rw [mulEnergy_eq_sum_sq']
exact Fintype.sum_subset <| by aesop (add simp [filter_eq_empty_iff, mul_mem_mul])
@[to_additive card_sq_le_card_mul_addEnergy]
lemma card_sq_le_card_mul_mulEnergy (s t u : Finset α) :
#{xy ∈ s ×ˢ t | xy.1 * xy.2 ∈ u} ^ 2 ≤ #u * Eₘ[s, t] := by
calc
_ = (∑ c ∈ u, #{xy ∈ s ×ˢ t | xy.1 * xy.2 = c}) ^ 2 := by
rw [← sum_card_fiberwise_eq_card_filter]
_ ≤ #u * ∑ c ∈ u, #{xy ∈ s ×ˢ t | xy.1 * xy.2 = c} ^ 2 := by
simpa using sum_mul_sq_le_sq_mul_sq (R := ℕ) _ 1 _
_ ≤ #u * ∑ c ∈ s * t, #{xy ∈ s ×ˢ t | xy.1 * xy.2 = c} ^ 2 := by
refine mul_le_mul_left' (sum_le_sum_of_ne_zero ?_) _
aesop (add simp [filter_eq_empty_iff]) (add unsafe mul_mem_mul)
_ = #u * Eₘ[s, t] := by rw [mulEnergy_eq_sum_sq']
@[to_additive le_card_add_mul_addEnergy] lemma le_card_mul_mul_mulEnergy (s t : Finset α) :
#s ^ 2 * #t ^ 2 ≤ #(s * t) * Eₘ[s, t] :=
calc
_ = #{xy ∈ s ×ˢ t | xy.1 * xy.2 ∈ s * t} ^ 2 := by
rw [filter_eq_self.2, card_product, mul_pow]; aesop (add unsafe mul_mem_mul)
_ ≤ #(s * t) * Eₘ[s, t] := card_sq_le_card_mul_mulEnergy _ _ _
@[deprecated (since := "2025-07-07")] alias le_card_add_mul_mulEnergy := le_card_mul_mul_mulEnergy
end Mul
open scoped Combinatorics.Additive
section CommMonoid
variable [CommMonoid α]
@[to_additive] lemma mulEnergy_comm (s t : Finset α) : Eₘ[s, t] = Eₘ[t, s] := by
rw [mulEnergy, ← Finset.card_map (Equiv.prodComm _ _).toEmbedding, map_filter]
simp [-Finset.card_map, mulEnergy, mul_comm, map_eq_image, Function.comp_def]
end CommMonoid
section CommGroup
variable [CommGroup α] [Fintype α] (s t : Finset α)
@[to_additive (attr := simp)]
lemma mulEnergy_univ_left : Eₘ[univ, t] = Fintype.card α * t.card ^ 2 := by
simp only [mulEnergy, univ_product_univ, Fintype.card, sq, ← card_product]
let f : α × α × α → (α × α) × α × α := fun x => ((x.1 * x.2.2, x.1 * x.2.1), x.2)
have : (↑((univ : Finset α) ×ˢ t ×ˢ t) : Set (α × α × α)).InjOn f := by
rintro ⟨a₁, b₁, c₁⟩ _ ⟨a₂, b₂, c₂⟩ h₂ h
simp_rw [f, Prod.ext_iff] at h
obtain ⟨h, rfl, rfl⟩ := h
rw [mul_right_cancel h.1]
rw [← card_image_of_injOn this]
congr with a
simp only [mem_filter, mem_product, mem_univ, true_and, mem_image,
Prod.exists]
refine ⟨fun h => ⟨a.1.1 * a.2.2⁻¹, _, _, h.1, by simp [f, mul_right_comm, h.2]⟩, ?_⟩
rintro ⟨b, c, d, hcd, rfl⟩
simpa [f, mul_right_comm]
@[to_additive (attr := simp)]
lemma mulEnergy_univ_right : Eₘ[s, univ] = Fintype.card α * s.card ^ 2 := by
rw [mulEnergy_comm, mulEnergy_univ_left]
end CommGroup
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/RuzsaCovering.lean | import Mathlib.Algebra.Group.Action.Pointwise.Finset
import Mathlib.Data.Real.Basic
import Mathlib.Order.Preorder.Finite
import Mathlib.SetTheory.Cardinal.Finite
import Mathlib.Tactic.Positivity.Finset
/-!
# Ruzsa's covering lemma
This file proves the Ruzsa covering lemma. This says that, for `A`, `B` finsets, we can cover `A`
with at most `#(A + B) / #B` copies of `B - B`.
-/
open scoped Pointwise
variable {G : Type*} [Group G] {K : ℝ}
namespace Finset
variable [DecidableEq G] {A B : Finset G}
/-- **Ruzsa's covering lemma**. -/
@[to_additive /-- **Ruzsa's covering lemma** -/]
theorem ruzsa_covering_mul (hB : B.Nonempty) (hK : #(A * B) ≤ K * #B) :
∃ F ⊆ A, #F ≤ K ∧ A ⊆ F * (B / B) := by
haveI : ∀ F, Decidable ((F : Set G).PairwiseDisjoint (· • B)) := fun F ↦ Classical.dec _
set C := {F ∈ A.powerset | (SetLike.coe F).PairwiseDisjoint (· • B)}
obtain ⟨F, hFmax⟩ := C.exists_maximal <| filter_nonempty_iff.2
⟨∅, empty_mem_powerset _, by simp [coe_empty]⟩
simp only [C, mem_filter, mem_powerset] at hFmax
obtain ⟨hFA, hF⟩ := hFmax.1
refine ⟨F, hFA, le_of_mul_le_mul_right ?_ (by positivity : (0 : ℝ) < #B), fun a ha ↦ ?_⟩
· calc
(#F * #B : ℝ) = #(F * B) := by
rw [card_mul_iff.2 <| pairwiseDisjoint_smul_iff.1 hF, Nat.cast_mul]
_ ≤ #(A * B) := by gcongr
_ ≤ K * #B := hK
by_cases hau : a ∈ F
· exact subset_mul_left _ hB.one_mem_div hau
by_cases! H : ∀ b ∈ F, Disjoint (a • B) (b • B)
· refine (hFmax.not_gt ?_ <| ssubset_insert hau).elim
rw [insert_subset_iff, coe_insert]
exact ⟨⟨ha, hFA⟩, hF.insert fun _ hb _ ↦ H _ hb⟩
simp_rw [not_disjoint_iff, ← inv_smul_mem_iff] at H
obtain ⟨b, hb, c, hc₁, hc₂⟩ := H
exact mem_mul.2 ⟨b, hb, b⁻¹ * a, mem_div.2 ⟨_, hc₂, _, hc₁, by simp⟩, by simp⟩
end Finset
namespace Set
variable {A B : Set G}
/-- **Ruzsa's covering lemma** for sets. See also `Finset.ruzsa_covering_mul`. -/
@[to_additive /-- **Ruzsa's covering lemma** for sets. See also `Finset.ruzsa_covering_add`. -/]
lemma ruzsa_covering_mul (hA : A.Finite) (hB : B.Finite) (hB₀ : B.Nonempty)
(hK : Nat.card (A * B) ≤ K * Nat.card B) :
∃ F ⊆ A, Nat.card F ≤ K ∧ A ⊆ F * (B / B) ∧ F.Finite := by
lift A to Finset G using hA
lift B to Finset G using hB
classical
obtain ⟨F, hFA, hF, hAF⟩ := Finset.ruzsa_covering_mul hB₀ (by simpa [← Finset.coe_mul] using hK)
exact ⟨F, by norm_cast; simp [*]⟩
end Set |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/SmallTripling.lean | import Mathlib.Combinatorics.Additive.PluenneckeRuzsa
import Mathlib.Data.Fin.VecNotation
import Mathlib.Data.Real.Basic
import Mathlib.Tactic.FinCases
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.NormNum
import Mathlib.Tactic.Positivity.Finset
import Mathlib.Tactic.Ring
/-!
# Small tripling implies small powers
This file shows that a set with small tripling has small powers, even in non-abelian groups.
## See also
In abelian groups, the Plünnecke-Ruzsa inequality is the stronger statement that small doubling
implies small powers. See `Mathlib/Combinatorics/Additive/PluenneckeRuzsa.lean`.
-/
open Fin MulOpposite
open List hiding tail
open scoped Pointwise
namespace Finset
variable {G : Type*} [DecidableEq G] [Group G] {A : Finset G} {k K : ℝ} {m : ℕ}
@[to_additive]
private lemma inductive_claim_mul (hm : 3 ≤ m)
(h : ∀ ε : Fin 3 → ℤ, (∀ i, |ε i| = 1) → #((finRange 3).map fun i ↦ A ^ ε i).prod ≤ k * #A)
(ε : Fin m → ℤ) (hε : ∀ i, |ε i| = 1) :
#((finRange m).map fun i ↦ A ^ ε i).prod ≤ k ^ (m - 2) * #A := by
induction m, hm using Nat.le_induction with
| base => simpa using h ε hε
| succ m hm ih =>
obtain _ | m := m
· simp at hm
have hm₀ : m ≠ 0 := by simp at hm; positivity
have hε₀ i : ε i ≠ 0 := fun h ↦ by simpa [h] using hε i
obtain rfl | hA := A.eq_empty_or_nonempty
· simp [hε₀]
have hk : 0 ≤ k :=
nonneg_of_mul_nonneg_left ((h 1 (by simp)).trans' (by positivity)) (by positivity)
let π {n} (δ : Fin n → ℤ) : Finset G := ((finRange _).map fun i ↦ A ^ δ i).prod
let V : Finset G := π ![-ε 1, -ε 0]
let W : Finset G := π <| tail <| tail ε
refine le_of_mul_le_mul_left ?_ (by positivity : (0 : ℝ) < #A)
calc
(#A * #(π ε) : ℝ)
= #A * #(V⁻¹ * W) := by
simp [π, V, W, List.finRange_succ, Fin.tail, Function.comp_def, mul_assoc]
_ ≤ #(A * V) * #(A * W) := by norm_cast; exact ruzsa_triangle_inequality_invMul_mul_mul ..
_ = #(π ![1, -ε 1, -ε 0]) * #(π <| Fin.cons 1 <| tail <| tail ε) := by
simp [π, V, W, List.finRange_succ, Fin.tail, Function.comp_def]
_ ≤ (k * #A) * (k ^ (m - 1) * #A) := by
gcongr
· exact h ![1, -ε 1, -ε 0] fun i ↦ by fin_cases i <;> simp [hε]
· exact ih (Fin.cons 1 <| tail <| tail ε) <| Fin.cons (by simp) (by simp [hε, Fin.tail])
_ = #A * (k ^ m * #A) := by rw [← pow_sub_one_mul hm₀]; ring
@[to_additive]
private lemma small_neg_pos_pos_mul (hA : #(A ^ 3) ≤ K * #A) : #(A⁻¹ * A * A) ≤ K ^ 2 * #A := by
obtain rfl | hA₀ := A.eq_empty_or_nonempty
· simp
have : 0 ≤ K := nonneg_of_mul_nonneg_left (hA.trans' <| by positivity) (by positivity)
refine le_of_mul_le_mul_left ?_ (by positivity : (0 : ℝ) < #A)
calc
(#A * #(A⁻¹ * A * A) : ℝ) = #A * #(A⁻¹ * (A * A)) := by rw [mul_assoc]
_ ≤ #(A * A) * #(A * (A * A)) := by
norm_cast; exact ruzsa_triangle_inequality_invMul_mul_mul A A (A * A)
_ = #(A ^ 2) * #(A ^ 3) := by simp [pow_succ']
_ ≤ (K * #A) * (K * #A) := by
gcongr
calc
(#(A ^ 2) : ℝ) ≤ #(A ^ 3) := mod_cast hA₀.card_pow_mono (by simp)
_ ≤ K * #A := hA
_ = #A * (K ^ 2 * #A) := by ring
@[to_additive]
private lemma small_neg_neg_pos_mul (hA : #(A ^ 3) ≤ K * #A) : #(A⁻¹ * A⁻¹ * A) ≤ K ^ 2 * #A := by
rw [← card_inv]
simpa [mul_assoc] using small_neg_pos_pos_mul (A := A) (K := K) (by simpa)
@[to_additive]
private lemma small_pos_neg_neg_mul (hA : #(A ^ 3) ≤ K * #A) : #(A * A⁻¹ * A⁻¹) ≤ K ^ 2 * #A := by
simpa using small_neg_pos_pos_mul (A := A⁻¹) (by simpa)
@[to_additive]
private lemma small_pos_pos_neg_mul (hA : #(A ^ 3) ≤ K * #A) : #(A * A * A⁻¹) ≤ K ^ 2 * #A := by
rw [← card_inv]
simpa [mul_assoc] using small_pos_neg_neg_mul (A := A) (K := K) (by simpa)
@[to_additive]
private lemma small_pos_neg_pos_mul (hA : #(A ^ 3) ≤ K * #A) : #(A * A⁻¹ * A) ≤ K ^ 3 * #A := by
obtain rfl | hA₀ := A.eq_empty_or_nonempty
· simp
refine le_of_mul_le_mul_left ?_ (by positivity : (0 : ℝ) < #A)
calc
(#A * #(A * A⁻¹ * A) : ℝ) ≤ #(A * (A * A⁻¹)) * #(A * A) := by
norm_cast; simpa using ruzsa_triangle_inequality_invMul_mul_mul (A * A⁻¹) A A
_ = #(A * A * A⁻¹) * #(A ^ 2) := by simp [pow_succ, mul_assoc]
_ ≤ (K ^ 2 * #A) * (K * #A) := by
gcongr
· exact small_pos_pos_neg_mul hA
calc
(#(A ^ 2) : ℝ) ≤ #(A ^ 3) := mod_cast hA₀.card_pow_mono (by simp)
_ ≤ K * #A := hA
_ = #A * (K ^ 3 * #A) := by ring
@[to_additive]
private lemma small_neg_pos_neg_mul (hA : #(A ^ 3) ≤ K * #A) : #(A⁻¹ * A * A⁻¹) ≤ K ^ 3 * #A := by
rw [← card_inv]
simpa [mul_assoc] using small_pos_neg_pos_mul (A := A) (K := K) (by simpa)
/-- If `A` has small tripling, say with constant `K`, then `A` has small alternating powers, in the
sense that `|A^±1 * ... * A^±1|` is at most `|A|` times a constant exponential in the number of
terms in the product.
When `A` is symmetric (`A⁻¹ = A`), the base of the exponential can be lowered from `K ^ 3` to `K`,
where `K` is the tripling constant. See `Finset.small_pow_of_small_tripling`. -/
@[to_additive
/-- If `A` has small tripling, say with constant `K`, then `A` has small alternating powers, in the
sense that `|±A ± ... ± A|` is at most `|A|` times a constant exponential in the number of
terms in the product.
When `A` is symmetric (`-A = A`), the base of the exponential can be lowered from `K ^ 3` to `K`,
where `K` is the tripling constant. See `Finset.small_nsmul_of_small_tripling`. -/]
lemma small_alternating_pow_of_small_tripling (hm : 3 ≤ m) (hA : #(A ^ 3) ≤ K * #A) (ε : Fin m → ℤ)
(hε : ∀ i, |ε i| = 1) :
#((finRange m).map fun i ↦ A ^ ε i).prod ≤ K ^ (3 * (m - 2)) * #A := by
have hm₀ : m ≠ 0 := by positivity
have hε₀ i : ε i ≠ 0 := fun h ↦ by simpa [h] using hε i
obtain rfl | hA₀ := A.eq_empty_or_nonempty
· simp [hm₀, hε₀]
have hK₁ : 1 ≤ K :=
one_le_of_le_mul_right₀ (by positivity)
(hA.trans' <| by norm_cast; exact card_le_card_pow (by simp))
rw [pow_mul]
refine inductive_claim_mul hm (fun δ hδ ↦ ?_) ε hε
simp only [finRange_succ, Nat.reduceAdd, isValue, finRange_zero, map_nil, List.map_cons,
succ_zero_eq_one, succ_one_eq_two, List.prod_cons, prod_nil, mul_one, ← mul_assoc]
simp only [zero_le_one, abs_eq, Int.reduceNeg, forall_iff_succ, isValue, succ_zero_eq_one,
succ_one_eq_two, IsEmpty.forall_iff, and_true] at hδ
have : K ≤ K ^ 3 := le_self_pow₀ hK₁ (by cutsat)
have : K ^ 2 ≤ K ^ 3 := by
gcongr
· exact hK₁
· simp
obtain ⟨hδ₀ | hδ₀, hδ₁ | hδ₁, hδ₂ | hδ₂⟩ := hδ <;> simp [hδ₀, hδ₁, hδ₂]
· simp [pow_succ] at hA
nlinarith
· nlinarith [small_pos_pos_neg_mul hA]
· nlinarith [small_pos_neg_pos_mul hA]
· nlinarith [small_pos_neg_neg_mul hA]
· nlinarith [small_neg_pos_pos_mul hA]
· nlinarith [small_neg_pos_neg_mul hA]
· nlinarith [small_neg_neg_pos_mul hA]
· simp [*, pow_succ', ← mul_inv_rev] at hA ⊢
nlinarith
/-- If `A` is symmetric (`A⁻¹ = A`) and has small tripling, then `A` has small powers,
in the sense that `|A ^ m|` is at most `|A|` times a constant exponential in `m`.
See also `Finset.small_alternating_pow_of_small_tripling` for a version with a weaker constant but
which encompasses non-symmetric sets. -/
@[to_additive
/-- If `A` is symmetric (`-A = A`) and has small tripling, then `A` has small powers,
in the sense that `|m • A|` is at most `|A|` times a constant exponential in `m`.
See also `Finset.small_alternating_nsmul_of_small_tripling` for a version with a weaker constant but
which encompasses non-symmetric sets. -/]
lemma small_pow_of_small_tripling (hm : 3 ≤ m) (hA : #(A ^ 3) ≤ K * #A) (hAsymm : A⁻¹ = A) :
#(A ^ m) ≤ K ^ (m - 2) * #A := by
have (ε : ℤ) (hε : |ε| = 1) : A ^ ε = A := by
obtain rfl | rfl := eq_or_eq_neg_of_abs_eq hε <;> simp [hAsymm]
calc
(#(A ^ m) : ℝ) = #((finRange m).map fun i ↦ A ^ 1).prod := by simp
_ ≤ K ^ (m - 2) * #A :=
inductive_claim_mul hm (fun δ hδ ↦ by simpa [this _ (hδ _), pow_succ'] using hA) _ (by simp)
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/Convolution.lean | import Mathlib.Algebra.Group.Action.Pointwise.Finset
/-!
# Convolution
This file defines convolution of finite subsets `A` and `B` of group `G` as the map `A ⋆ B : G → ℕ`
that maps `x ∈ G` to the number of distinct representations of `x` in the form `x = ab` for
`a ∈ A`, `b ∈ B`. It is shown how convolution behaves under the change of order of `A` and `B`, as
well as under the left and right actions on `A`, `B`, and the function argument.
-/
open MulOpposite MulAction
open scoped Pointwise RightActions
namespace Finset
variable {G : Type*} [Group G] [DecidableEq G] {A B : Finset G} {s x y : G}
/-- Given finite subsets `A` and `B` of a group `G`, convolution of `A` and `B` is a map `G → ℕ`
that maps `x ∈ G` to the number of distinct representations of `x` in the form `x = ab`, where
`a ∈ A`, `b ∈ B`. -/
@[to_additive addConvolution /-- Given finite subsets `A` and `B` of an additive group `G`,
convolution of `A` and `B` is a map `G → ℕ` that maps `x ∈ G` to the number of distinct
representations of `x` in the form `x = a + b`, where `a ∈ A`, `b ∈ B`. -/]
def convolution (A B : Finset G) : G → ℕ := fun x => #{ab ∈ A ×ˢ B | ab.1 * ab.2 = x}
@[to_additive]
lemma card_smul_inter_smul (A B : Finset G) (x y : G) :
#((x • A) ∩ (y • B)) = A.convolution B⁻¹ (x⁻¹ * y) :=
card_nbij' (fun z ↦ (x⁻¹ * z, z⁻¹ * y)) (fun ab' ↦ x • ab'.1)
(by simp +contextual [Set.MapsTo, Set.mem_smul_set_iff_inv_smul_mem, mul_assoc])
(by simp +contextual [Set.MapsTo, Set.mem_smul_set_iff_inv_smul_mem]
simp +contextual [← eq_mul_inv_iff_mul_eq, mul_assoc])
(by simp [Set.LeftInvOn])
(by simp +contextual [Set.LeftInvOn, ← eq_mul_inv_iff_mul_eq, mul_assoc])
@[to_additive]
lemma card_inter_smul (A B : Finset G) (x : G) : #(A ∩ (x • B)) = A.convolution B⁻¹ x := by
simpa using card_smul_inter_smul _ _ 1 x
@[to_additive]
lemma card_smul_inter (A B : Finset G) (x : G) : #((x • A) ∩ B) = A.convolution B⁻¹ x⁻¹ := by
simpa using card_smul_inter_smul _ _ x 1
@[to_additive card_add_neg_eq_addConvolution_neg]
lemma card_mul_inv_eq_convolution_inv (A B : Finset G) (x : G) :
#{ab ∈ A ×ˢ B | ab.1 * ab.2⁻¹ = x} = A.convolution B⁻¹ x :=
card_nbij' (fun ab => (ab.1, ab.2⁻¹)) (fun ab => (ab.1, ab.2⁻¹))
(by simp [Set.MapsTo]) (by simp [Set.MapsTo])
(by simp [Set.LeftInvOn]) (by simp [Set.LeftInvOn])
@[to_additive (attr := simp) addConvolution_pos]
lemma convolution_pos : 0 < A.convolution B x ↔ x ∈ A * B := by
aesop (add simp [convolution, Finset.Nonempty, mem_mul])
@[to_additive addConvolution_ne_zero]
lemma convolution_ne_zero : A.convolution B x ≠ 0 ↔ x ∈ A * B := by
suffices A.convolution B x ≠ 0 ↔ 0 < A.convolution B x by simp [this]
cutsat
@[to_additive (attr := simp) addConvolution_eq_zero]
lemma convolution_eq_zero : A.convolution B x = 0 ↔ x ∉ A * B := by
simp [← convolution_ne_zero]
@[to_additive addConvolution_le_card_left]
lemma convolution_le_card_left : A.convolution B x ≤ #A := by
rw [← inv_inv B, ← card_inter_smul]
exact card_le_card inter_subset_left
@[to_additive addConvolution_le_card_right]
lemma convolution_le_card_right : A.convolution B x ≤ #B := by
rw [← inv_inv B, ← inv_inv x, ← card_smul_inter, card_inv]
exact card_le_card inter_subset_right
@[to_additive (attr := simp) addConvolution_neg]
lemma convolution_inv (A B : Finset G) (x : G) : A.convolution B x⁻¹ = B⁻¹.convolution A⁻¹ x := by
nth_rw 1 [← inv_inv B]
rw [← card_smul_inter, ← card_inter_smul, inter_comm]
@[to_additive (attr := simp) op_vadd_addConvolution_eq_addConvolution_vadd]
lemma op_smul_convolution_eq_convolution_smul (A B : Finset G) (s : G) :
(A <• s).convolution B = A.convolution (s • B) := funext fun x => by
nth_rw 1 [← inv_inv B, ← inv_inv (s • B), inv_smul_finset_distrib s B, ← card_inter_smul,
← card_inter_smul, smul_comm]
simp [← card_smul_finset (op s) (A ∩ _), smul_finset_inter]
@[to_additive (attr := simp) vadd_addConvolution_eq_addConvolution_neg_add]
lemma smul_convolution_eq_convolution_inv_mul (A B : Finset G) (s x : G) :
(s •> A).convolution B x = A.convolution B (s⁻¹ * x) := by
nth_rw 1 [← inv_inv x, ← inv_inv (s⁻¹ * x)]
rw [← inv_inv B, ← card_smul_inter, ← card_smul_inter, mul_inv_rev, inv_inv, smul_smul]
@[to_additive (attr := simp) addConvolution_op_vadd_eq_addConvolution_add_neg]
lemma convolution_op_smul_eq_convolution_mul_inv (A B : Finset G) (s x : G) :
A.convolution (B <• s) x = A.convolution B (x * s⁻¹) := by
nth_rw 2 [← inv_inv B]
rw [← inv_inv (B <• s), inv_op_smul_finset_distrib, ← card_inter_smul, ← card_inter_smul,
smul_smul]
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/ETransform.lean | import Mathlib.Algebra.Group.Action.Pointwise.Finset
import Mathlib.Algebra.Ring.Nat
/-!
# e-transforms
e-transforms are a family of transformations of pairs of finite sets that aim to reduce the size
of the sumset while keeping some invariant the same. This file defines a few of them, to be used
as internals of other proofs.
## Main declarations
* `Finset.mulDysonETransform`: The Dyson e-transform. Replaces `(s, t)` by
`(s ∪ e • t, t ∩ e⁻¹ • s)`. The additive version preserves `|s ∩ [1, m]| + |t ∩ [1, m - e]|`.
* `Finset.mulETransformLeft`/`Finset.mulETransformRight`: Replace `(s, t)` by
`(s ∩ s • e, t ∪ e⁻¹ • t)` and `(s ∪ s • e, t ∩ e⁻¹ • t)`. Preserve (together) the sum of
the cardinalities (see `Finset.MulETransform.card`). In particular, one of the two transforms
increases the sum of the cardinalities and the other one decreases it. See
`le_or_lt_of_add_le_add` and around.
## TODO
Prove the invariance property of the Dyson e-transform.
-/
open MulOpposite
open Pointwise
variable {α : Type*} [DecidableEq α]
namespace Finset
/-! ### Dyson e-transform -/
section CommGroup
variable [CommGroup α] (e : α) (x : Finset α × Finset α)
/-- The **Dyson e-transform**. Turns `(s, t)` into `(s ∪ e • t, t ∩ e⁻¹ • s)`. This reduces the
product of the two sets. -/
@[to_additive (attr := simps) /-- The **Dyson e-transform**.
Turns `(s, t)` into `(s ∪ e +ᵥ t, t ∩ -e +ᵥ s)`. This reduces the sum of the two sets. -/]
def mulDysonETransform : Finset α × Finset α :=
(x.1 ∪ e • x.2, x.2 ∩ e⁻¹ • x.1)
@[to_additive]
theorem mulDysonETransform.subset :
(mulDysonETransform e x).1 * (mulDysonETransform e x).2 ⊆ x.1 * x.2 := by
refine union_mul_inter_subset_union.trans (union_subset Subset.rfl ?_)
rw [mul_smul_comm, smul_mul_assoc, inv_smul_smul, mul_comm]
@[to_additive]
theorem mulDysonETransform.card :
(mulDysonETransform e x).1.card + (mulDysonETransform e x).2.card = x.1.card + x.2.card := by
dsimp
rw [← card_smul_finset e (_ ∩ _), smul_finset_inter, smul_inv_smul, inter_comm,
card_union_add_card_inter, card_smul_finset]
@[to_additive (attr := simp)]
theorem mulDysonETransform_idem :
mulDysonETransform e (mulDysonETransform e x) = mulDysonETransform e x := by
ext : 1 <;> dsimp
· rw [smul_finset_inter, smul_inv_smul, inter_comm, union_eq_left]
exact inter_subset_union
· rw [smul_finset_union, inv_smul_smul, union_comm, inter_eq_left]
exact inter_subset_union
variable {e x}
@[to_additive]
theorem mulDysonETransform.smul_finset_snd_subset_fst :
e • (mulDysonETransform e x).2 ⊆ (mulDysonETransform e x).1 := by
dsimp
rw [smul_finset_inter, smul_inv_smul, inter_comm]
exact inter_subset_union
end CommGroup
/-!
### Two unnamed e-transforms
The following two transforms both reduce the product/sum of the two sets. Further, one of them must
decrease the sum of the size of the sets (and then the other increases it).
This pair of transforms doesn't seem to be named in the literature. It is used by Sanders in his
bound on Roth numbers, and by DeVos in his proof of Cauchy-Davenport.
-/
section Group
variable [Group α] (e : α) (x : Finset α × Finset α)
/-- An **e-transform**. Turns `(s, t)` into `(s ∩ s • e, t ∪ e⁻¹ • t)`. This reduces the
product of the two sets. -/
@[to_additive (attr := simps) /-- An **e-transform**.
Turns `(s, t)` into `(s ∩ s +ᵥ e, t ∪ -e +ᵥ t)`. This reduces the sum of the two sets. -/]
def mulETransformLeft : Finset α × Finset α :=
(x.1 ∩ op e • x.1, x.2 ∪ e⁻¹ • x.2)
/-- An **e-transform**. Turns `(s, t)` into `(s ∪ s • e, t ∩ e⁻¹ • t)`. This reduces the
product of the two sets. -/
@[to_additive (attr := simps) /-- An **e-transform**.
Turns `(s, t)` into `(s ∪ s +ᵥ e, t ∩ -e +ᵥ t)`. This reduces the sum of the two sets. -/]
def mulETransformRight : Finset α × Finset α :=
(x.1 ∪ op e • x.1, x.2 ∩ e⁻¹ • x.2)
@[to_additive (attr := simp)]
theorem mulETransformLeft_one : mulETransformLeft 1 x = x := by simp [mulETransformLeft]
@[to_additive (attr := simp)]
theorem mulETransformRight_one : mulETransformRight 1 x = x := by simp [mulETransformRight]
@[to_additive]
theorem mulETransformLeft.fst_mul_snd_subset :
(mulETransformLeft e x).1 * (mulETransformLeft e x).2 ⊆ x.1 * x.2 := by
refine inter_mul_union_subset_union.trans (union_subset Subset.rfl ?_)
rw [op_smul_finset_mul_eq_mul_smul_finset, smul_inv_smul]
@[to_additive]
theorem mulETransformRight.fst_mul_snd_subset :
(mulETransformRight e x).1 * (mulETransformRight e x).2 ⊆ x.1 * x.2 := by
refine union_mul_inter_subset_union.trans (union_subset Subset.rfl ?_)
rw [op_smul_finset_mul_eq_mul_smul_finset, smul_inv_smul]
@[to_additive]
theorem mulETransformLeft.card :
(mulETransformLeft e x).1.card + (mulETransformRight e x).1.card = 2 * x.1.card :=
(card_inter_add_card_union _ _).trans <| by rw [card_smul_finset, two_mul]
@[to_additive]
theorem mulETransformRight.card :
(mulETransformLeft e x).2.card + (mulETransformRight e x).2.card = 2 * x.2.card :=
(card_union_add_card_inter _ _).trans <| by rw [card_smul_finset, two_mul]
/-- This statement is meant to be combined with `le_or_lt_of_add_le_add` and similar lemmas. -/
@[to_additive AddETransform.card /-- This statement is meant to be combined with
`le_or_lt_of_add_le_add` and similar lemmas. -/]
protected theorem MulETransform.card :
(mulETransformLeft e x).1.card + (mulETransformLeft e x).2.card +
((mulETransformRight e x).1.card + (mulETransformRight e x).2.card) =
x.1.card + x.2.card + (x.1.card + x.2.card) := by
rw [add_add_add_comm, mulETransformLeft.card, mulETransformRight.card, ← mul_add, two_mul]
end Group
section CommGroup
variable [CommGroup α] (e : α) (x : Finset α × Finset α)
@[to_additive (attr := simp)]
theorem mulETransformLeft_inv : mulETransformLeft e⁻¹ x = (mulETransformRight e x.swap).swap := by
simp [-op_inv, op_smul_eq_smul, mulETransformLeft, mulETransformRight]
@[to_additive (attr := simp)]
theorem mulETransformRight_inv : mulETransformRight e⁻¹ x = (mulETransformLeft e x.swap).swap := by
simp [-op_inv, op_smul_eq_smul, mulETransformLeft, mulETransformRight]
end CommGroup
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/Dissociation.lean | import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise
import Mathlib.Algebra.Group.Pointwise.Set.Basic
import Mathlib.Algebra.Group.Units.Equiv
import Mathlib.Algebra.Notation.Indicator
import Mathlib.Data.Finset.Powerset
import Mathlib.Data.Fintype.Pi
import Mathlib.Order.Preorder.Finite
/-!
# Dissociation and span
This file defines dissociation and span of sets in groups. These are analogs to the usual linear
independence and linear span of sets in a vector space but where the scalars are only allowed to be
`0` or `±1`. In characteristic 2 or 3, the two pairs of concepts are actually equivalent.
## Main declarations
* `MulDissociated`/`AddDissociated`: Predicate for a set to be dissociated.
* `Finset.mulSpan`/`Finset.addSpan`: Span of a finset.
-/
variable {α β : Type*} [CommGroup α] [CommGroup β]
section dissociation
variable {s : Set α} {t u : Finset α} {d : ℕ} {a : α}
open Set
/-- A set is dissociated iff all its finite subsets have different products.
This is an analog of linear independence in a vector space, but with the "scalars" restricted to
`0` and `±1`. -/
@[to_additive /-- A set is dissociated iff all its finite subsets have different sums.
This is an analog of linear independence in a vector space, but with the "scalars" restricted to
`0` and `±1`. -/]
def MulDissociated (s : Set α) : Prop := {t : Finset α | ↑t ⊆ s}.InjOn (∏ x ∈ ·, x)
@[to_additive] lemma mulDissociated_iff_sum_eq_subsingleton :
MulDissociated s ↔ ∀ a, {t : Finset α | ↑t ⊆ s ∧ ∏ x ∈ t, x = a}.Subsingleton :=
⟨fun hs _ _t ht _u hu ↦ hs ht.1 hu.1 <| ht.2.trans hu.2.symm,
fun hs _t ht _u hu htu ↦ hs _ ⟨ht, htu⟩ ⟨hu, rfl⟩⟩
@[to_additive] lemma MulDissociated.subset {t : Set α} (hst : s ⊆ t) (ht : MulDissociated t) :
MulDissociated s := ht.mono fun _ ↦ hst.trans'
@[to_additive (attr := simp)] lemma mulDissociated_empty : MulDissociated (∅ : Set α) := by
simp [MulDissociated, subset_empty_iff]
@[to_additive (attr := simp)]
lemma mulDissociated_singleton : MulDissociated ({a} : Set α) ↔ a ≠ 1 := by
simp [MulDissociated, setOf_or, -subset_singleton_iff,
Finset.coe_subset_singleton]
@[to_additive (attr := simp)]
lemma not_mulDissociated :
¬ MulDissociated s ↔
∃ t : Finset α, ↑t ⊆ s ∧ ∃ u : Finset α, ↑u ⊆ s ∧ t ≠ u ∧ ∏ x ∈ t, x = ∏ x ∈ u, x := by
simp [MulDissociated, InjOn]; aesop
@[to_additive]
lemma not_mulDissociated_iff_exists_disjoint :
¬ MulDissociated s ↔
∃ t u : Finset α, ↑t ⊆ s ∧ ↑u ⊆ s ∧ Disjoint t u ∧ t ≠ u ∧ ∏ a ∈ t, a = ∏ a ∈ u, a := by
classical
refine not_mulDissociated.trans
⟨?_, fun ⟨t, u, ht, hu, _, htune, htusum⟩ ↦ ⟨t, ht, u, hu, htune, htusum⟩⟩
rintro ⟨t, ht, u, hu, htu, h⟩
refine ⟨t \ u, u \ t, ?_, ?_, disjoint_sdiff_sdiff, sdiff_ne_sdiff_iff.2 htu,
Finset.prod_sdiff_eq_prod_sdiff_iff.2 h⟩ <;> push_cast <;> exact diff_subset.trans ‹_›
@[to_additive (attr := simp)] lemma MulEquiv.mulDissociated_preimage (e : β ≃* α) :
MulDissociated (e ⁻¹' s) ↔ MulDissociated s := by
simp [MulDissociated, InjOn, ← e.finsetCongr.forall_congr_right, ← e.apply_eq_iff_eq,
(Finset.map_injective _).eq_iff]
@[to_additive (attr := simp)] lemma mulDissociated_inv : MulDissociated s⁻¹ ↔ MulDissociated s :=
(MulEquiv.inv α).mulDissociated_preimage
@[to_additive] protected alias ⟨MulDissociated.of_inv, MulDissociated.inv⟩ := mulDissociated_inv
end dissociation
namespace Finset
variable [DecidableEq α] [Fintype α] {s t u : Finset α} {a : α} {d : ℕ}
/-- The span of a finset `s` is the finset of elements of the form `∏ a ∈ s, a ^ ε a` where
`ε ∈ {-1, 0, 1} ^ s`.
This is an analog of the linear span in a vector space, but with the "scalars" restricted to
`0` and `±1`. -/
@[to_additive /-- The span of a finset `s` is the finset of elements of the form `∑ a ∈ s, ε a • a`
where `ε ∈ {-1, 0, 1} ^ s`.
This is an analog of the linear span in a vector space, but with the "scalars" restricted to
`0` and `±1`. -/]
def mulSpan (s : Finset α) : Finset α :=
(Fintype.piFinset fun _a ↦ ({-1, 0, 1} : Finset ℤ)).image fun ε ↦ ∏ a ∈ s, a ^ ε a
@[to_additive (attr := simp)]
lemma mem_mulSpan :
a ∈ mulSpan s ↔ ∃ ε : α → ℤ, (∀ a, ε a = -1 ∨ ε a = 0 ∨ ε a = 1) ∧ ∏ a ∈ s, a ^ ε a = a := by
simp [mulSpan]
@[to_additive (attr := simp)]
lemma subset_mulSpan : s ⊆ mulSpan s := fun a ha ↦
mem_mulSpan.2 ⟨Pi.single a 1, fun b ↦ by obtain rfl | hab := eq_or_ne a b <;> simp [*], by
simp [Pi.single, Function.update, pow_ite, ha]⟩
@[to_additive]
lemma prod_div_prod_mem_mulSpan (ht : t ⊆ s) (hu : u ⊆ s) :
(∏ a ∈ t, a) / ∏ a ∈ u, a ∈ mulSpan s :=
mem_mulSpan.2 ⟨Set.indicator t 1 - Set.indicator u 1, fun a ↦ by
by_cases a ∈ t <;> by_cases a ∈ u <;> simp [*], by simp [prod_div_distrib, zpow_sub,
← div_eq_mul_inv, Set.indicator, pow_ite, inter_eq_right.2, *]⟩
/-- If every dissociated subset of `s` has size at most `d`, then `s` is actually generated by a
subset of size at most `d`.
This is a dissociation analog of the fact that a set whose linearly independent subsets all have
size at most `d` is of dimension at most `d` itself. -/
@[to_additive /-- If every dissociated subset of `s` has size at most `d`, then `s` is actually
generated by a subset of size at most `d`.
This is a dissociation analog of the fact that a set whose linearly independent subspaces all have
size at most `d` is of dimension at most `d` itself. -/]
lemma exists_subset_mulSpan_card_le_of_forall_mulDissociated
(hs : ∀ s', s' ⊆ s → MulDissociated (s' : Set α) → s'.card ≤ d) :
∃ s', s' ⊆ s ∧ s'.card ≤ d ∧ s ⊆ mulSpan s' := by
classical
obtain ⟨s', hs'⟩ :=
(s.powerset.filter fun s' : Finset α ↦ MulDissociated (s' : Set α)).exists_maximal
⟨∅, mem_filter.2 ⟨empty_mem_powerset _, by simp⟩⟩
simp only [mem_filter, mem_powerset] at hs'
refine ⟨s', hs'.1.1, hs _ hs'.1.1 hs'.1.2, fun a ha ↦ ?_⟩
by_cases ha' : a ∈ s'
· exact subset_mulSpan ha'
obtain ⟨t, u, ht, hu, htu⟩ := not_mulDissociated_iff_exists_disjoint.1 fun h ↦
hs'.not_gt ⟨insert_subset_iff.2 ⟨ha, hs'.1.1⟩, h⟩ <| ssubset_insert ha'
by_cases hat : a ∈ t
· have : a = (∏ b ∈ u, b) / ∏ b ∈ t.erase a, b := by
rw [prod_erase_eq_div hat, htu.2.2, div_div_self']
rw [this]
exact prod_div_prod_mem_mulSpan
((subset_insert_iff_of_notMem <| disjoint_left.1 htu.1 hat).1 hu) (subset_insert_iff.1 ht)
rw [coe_subset, subset_insert_iff_of_notMem hat] at ht
by_cases hau : a ∈ u
· have : a = (∏ b ∈ t, b) / ∏ b ∈ u.erase a, b := by
rw [prod_erase_eq_div hau, htu.2.2, div_div_self']
rw [this]
exact prod_div_prod_mem_mulSpan ht (subset_insert_iff.1 hu)
· rw [coe_subset, subset_insert_iff_of_notMem hau] at hu
cases not_mulDissociated_iff_exists_disjoint.2 ⟨t, u, ht, hu, htu⟩ hs'.1.2
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/VerySmallDoubling.lean | import Mathlib.Algebra.Pointwise.Stabilizer
import Mathlib.Combinatorics.Additive.Convolution
import Mathlib.NumberTheory.Real.GoldenRatio
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.Qify
/-!
# Sets with very small doubling
For a finset `A` in a group, its *doubling* is `#(A * A) / #A`. This file characterises sets with
* no doubling as the sets which are either empty or translates of a subgroup.
For the converse, use the existing facts from the pointwise API: `∅ ^ 2 = ∅` (`Finset.empty_pow`),
`(a • H) ^ 2 = a ^ 2 • H ^ 2 = a ^ 2 • H` (`smul_pow`, `coe_set_pow`).
* doubling strictly less than `3 / 2` as the sets that are contained in a coset of a subgroup of
size strictly less than `3 / 2 * #A`.
* doubling strictly less than `φ` as the set `A` such that `A * A⁻¹` is covered by at most some
constant (depending only on the doubling) number of cosets of a finite subgroup of `G`.
## TODO
* Do we need versions stated using the doubling constant (`Finset.mulConst`)?
* Add characterisation of sets with doubling ≤ 2 - ε. See
https://terrytao.wordpress.com/2011/03/12/hamidounes-freiman-kneser-theorem-for-nonabelian-groups.
## References
* [*An elementary non-commutative Freiman theorem*, Terence Tao](https://terrytao.wordpress.com/2009/11/10/an-elementary-non-commutative-freiman-theorem)
* [*Introduction to approximate groups*, Matthew Tointon][tointon2020]
-/
open MulOpposite MulAction
open scoped Pointwise RightActions
namespace Finset
variable {G : Type*} [Group G] [DecidableEq G] {K : ℝ} {A B S : Finset G} {a b c d x y : G}
/-! ### Doubling exactly `1` -/
@[to_additive]
private lemma smul_stabilizer_of_no_doubling_aux (hA : #(A * A) ≤ #A) (ha : a ∈ A) :
a •> (stabilizer G A : Set G) = A ∧ (stabilizer G A : Set G) <• a = A := by
have smul_A {a} (ha : a ∈ A) : a •> A = A * A :=
eq_of_subset_of_card_le (smul_finset_subset_mul ha) (by simpa)
have A_smul {a} (ha : a ∈ A) : A <• a = A * A :=
eq_of_subset_of_card_le (op_smul_finset_subset_mul ha) (by simpa)
have smul_A_eq_A_smul {a} (ha : a ∈ A) : a •> A = A <• a := by rw [smul_A ha, A_smul ha]
have mul_mem_A_comm {x a} (ha : a ∈ A) : x * a ∈ A ↔ a * x ∈ A := by
rw [← smul_mem_smul_finset_iff a, smul_A_eq_A_smul ha, ← op_smul_eq_mul, smul_comm,
smul_mem_smul_finset_iff, smul_eq_mul]
let H := stabilizer G A
have inv_smul_A {a} (ha : a ∈ A) : a⁻¹ • (A : Set G) = H := by
ext x
rw [Set.mem_inv_smul_set_iff, smul_eq_mul]
refine ⟨fun hx ↦ ?_, fun hx ↦ ?_⟩
· simpa [← smul_A ha, mul_smul] using smul_A hx
· norm_cast
rwa [← mul_mem_A_comm ha, ← smul_eq_mul, ← mem_inv_smul_finset_iff, inv_mem hx]
refine ⟨?_, ?_⟩
· rw [← inv_smul_A ha, smul_inv_smul]
· rw [← inv_smul_A ha, smul_comm]
norm_cast
rw [← smul_A_eq_A_smul ha, inv_smul_smul]
/-- A non-empty set with no doubling is the left translate of its stabilizer. -/
@[to_additive /-- A non-empty set with no doubling is the left-translate of its stabilizer. -/]
lemma smul_stabilizer_of_no_doubling (hA : #(A * A) ≤ #A) (ha : a ∈ A) :
a •> (stabilizer G A : Set G) = A := (smul_stabilizer_of_no_doubling_aux hA ha).1
/-- A non-empty set with no doubling is the right translate of its stabilizer. -/
@[to_additive /-- A non-empty set with no doubling is the right translate of its stabilizer. -/]
lemma op_smul_stabilizer_of_no_doubling (hA : #(A * A) ≤ #A) (ha : a ∈ A) :
(stabilizer G A : Set G) <• a = A := (smul_stabilizer_of_no_doubling_aux hA ha).2
/-! ### Doubling strictly less than `3 / 2` -/
private lemma big_intersection (ha : a ∈ B) (hb : b ∈ B) :
2 * #A ≤ #((a • A) ∩ (b • A)) + #(B * A) := by
have : #((a • A) ∪ (b • A)) ≤ #(B * A) := by
gcongr
rw [union_subset_iff]
exact ⟨smul_finset_subset_mul ha, smul_finset_subset_mul hb⟩
grw [← this, card_inter_add_card_union]
simp [card_smul_finset, two_mul]
private lemma le_card_smul_inter_smul (hA : #(B * A) ≤ K * #A) (ha : a ∈ B) (hb : b ∈ B) :
(2 - K) * #A ≤ #((a • A) ∩ (b • A)) := by
have : 2 * (#A : ℝ) ≤ #(a •> A ∩ b •> A) + #(B * A) := mod_cast big_intersection ha hb; linarith
private lemma lt_card_smul_inter_smul (hA : #(B * A) < K * #A) (ha : a ∈ B) (hb : b ∈ B) :
(2 - K) * #A < #((a • A) ∩ (b • A)) := by
have : 2 * (#A : ℝ) ≤ #(a •> A ∩ b •> A) + #(B * A) := mod_cast big_intersection ha hb; linarith
private lemma le_card_mul_inv_eq (hA : #(B * A) ≤ K * #A) (hx : x ∈ B⁻¹ * B) :
(2 - K) * #A ≤ #{ab ∈ A ×ˢ A | ab.1 * ab.2⁻¹ = x} := by
simp only [mem_mul, mem_inv, exists_exists_and_eq_and] at hx
obtain ⟨a, ha, b, hb, rfl⟩ := hx
rw [card_mul_inv_eq_convolution_inv]
simpa [card_smul_inter_smul] using le_card_smul_inter_smul hA ha hb
private lemma lt_card_mul_inv_eq (hA : #(B * A) < K * #A) (hx : x ∈ B⁻¹ * B) :
(2 - K) * #A < #{ab ∈ A ×ˢ A | ab.1 * ab.2⁻¹ = x} := by
simp only [mem_mul, mem_inv, exists_exists_and_eq_and] at hx
obtain ⟨a, ha, b, hb, rfl⟩ := hx
rw [card_mul_inv_eq_convolution_inv]
simpa [card_smul_inter_smul] using lt_card_smul_inter_smul hA ha hb
private lemma mul_inv_eq_inv_mul_of_doubling_lt_two_aux (h : #(A * A) < 2 * #A) :
A⁻¹ * A ⊆ A * A⁻¹ := by
intro z
simp only [mem_mul, forall_exists_index, and_imp, mem_inv,
exists_exists_and_eq_and]
rintro x hx y hy rfl
have ⟨t, ht⟩ : (x • A ∩ y • A).Nonempty := by
simpa using lt_card_smul_inter_smul (K := 2) (mod_cast h) hx hy
simp only [mem_inter, mem_smul_finset, smul_eq_mul] at ht
obtain ⟨⟨z, hz, hzxwy⟩, w, hw, rfl⟩ := ht
refine ⟨z, hz, w, hw, ?_⟩
rw [mul_inv_eq_iff_eq_mul, mul_assoc, ← hzxwy, inv_mul_cancel_left]
-- TODO: is there a way to get wlog to make `mul_inv_eq_inv_mul_of_doubling_lt_two_aux` a goal?
-- i.e. wlog in the target rather than hypothesis
-- (BM: third time seeing this pattern)
-- I'm thinking something like wlog_suffices, where I could write
-- wlog_suffices : A⁻¹ * A ⊆ A * A⁻¹
-- which reverts *everything* (just like wlog does) and makes the side goal A⁻¹ * A = A * A⁻¹
-- under the assumption A⁻¹ * A ⊆ A * A⁻¹
-- and changes the main goal to A⁻¹ * A ⊆ A * A⁻¹
/-- If `A` has doubling strictly less than `2`, then `A * A⁻¹ = A⁻¹ * A`. -/
lemma mul_inv_eq_inv_mul_of_doubling_lt_two (h : #(A * A) < 2 * #A) : A * A⁻¹ = A⁻¹ * A := by
refine Subset.antisymm ?_ (mul_inv_eq_inv_mul_of_doubling_lt_two_aux h)
simpa using
mul_inv_eq_inv_mul_of_doubling_lt_two_aux (A := A⁻¹) (by simpa [← mul_inv_rev] using h)
private lemma weaken_doubling (h : #(A * A) < (3 / 2 : ℚ) * #A) : #(A * A) < 2 * #A := by
rw [← Nat.cast_lt (α := ℚ), Nat.cast_mul, Nat.cast_two]
linarith only [h]
private lemma nonempty_of_doubling (h : #(A * A) < (3 / 2 : ℚ) * #A) : A.Nonempty := by
rw [nonempty_iff_ne_empty]
rintro rfl
simp at h
/-- If `A` has doubling strictly less than `3 / 2`, then `A⁻¹ * A` is a subgroup.
Note that this is sharp: `A = {0, 1}` in `ℤ` has doubling `3 / 2` and `A⁻¹ * A` isn't a subgroup. -/
def invMulSubgroup (A : Finset G) (h : #(A * A) < (3 / 2 : ℚ) * #A) : Subgroup G where
carrier := A⁻¹ * A
one_mem' := by
have ⟨x, hx⟩ : A.Nonempty := nonempty_of_doubling h
exact ⟨x⁻¹, inv_mem_inv hx, x, by simp [hx]⟩
inv_mem' := by
intro x
simp only [Set.mem_mul, Set.mem_inv, coe_inv, forall_exists_index, mem_coe,
and_imp]
rintro a ha b hb rfl
exact ⟨b⁻¹, by simpa using hb, a⁻¹, ha, by simp⟩
mul_mem' := by
norm_cast
have h₁ x (hx : x ∈ A) y (hy : y ∈ A) : (1 / 2 : ℚ) * #A < #(x • A ∩ y • A) := by
convert lt_card_smul_inter_smul (by simpa using Rat.cast_strictMono (K := ℝ) h) hx hy
norm_num
simp [← Rat.cast_lt (K := ℝ)]
intro a c ha hc
simp only [mem_mul, mem_inv'] at ha hc
obtain ⟨a, ha, b, hb, rfl⟩ := ha
obtain ⟨c, hc, d, hd, rfl⟩ := hc
have h₂ : (1 / 2 : ℚ) * #A < #(A ∩ (a * b)⁻¹ • A) := by
refine (h₁ b hb _ ha).trans_le ?_
rw [← card_smul_finset b⁻¹]
simp [smul_smul, smul_finset_inter]
have h₃ : (1 / 2 : ℚ) * #A < #(A ∩ (c * d) • A) := by
refine (h₁ _ hc d hd).trans_le ?_
rw [← card_smul_finset c]
simp [smul_smul, smul_finset_inter]
have ⟨t, ht⟩ : ((A ∩ (c * d) • A) ∩ (A ∩ (a * b)⁻¹ • A)).Nonempty := by
rw [← card_pos, ← Nat.cast_pos (α := ℚ)]
have := card_inter_add_card_union (A ∩ (c * d) • A) (A ∩ (a * b)⁻¹ • A)
rw [← Nat.cast_inj (R := ℚ), Nat.cast_add, Nat.cast_add] at this
have : (#((A ∩ (c * d) • A) ∪ (A ∩ (a * b)⁻¹ • A)) : ℚ) ≤ #A := by
rw [Nat.cast_le, ← inter_union_distrib_left]
exact card_le_card inter_subset_left
linarith
simp only [inter_inter_inter_comm, inter_self, mem_inter, ← inv_smul_mem_iff, inv_inv,
smul_eq_mul, mul_assoc, mul_inv_rev] at ht
rw [← mul_inv_eq_inv_mul_of_doubling_lt_two (weaken_doubling h), mem_mul]
exact ⟨a * b * t, by simp [ht, mul_assoc], ((c * d)⁻¹ * t)⁻¹, by simp [ht, mul_assoc]⟩
lemma invMulSubgroup_eq_inv_mul (A : Finset G) (h) : (invMulSubgroup A h : Set G) = A⁻¹ * A := rfl
lemma invMulSubgroup_eq_mul_inv (A : Finset G) (h) : (invMulSubgroup A h : Set G) = A * A⁻¹ := by
rw [invMulSubgroup_eq_inv_mul, eq_comm]
norm_cast
exact mul_inv_eq_inv_mul_of_doubling_lt_two (by qify at h ⊢; linarith)
instance (A : Finset G) (h) : Fintype (invMulSubgroup A h) := by
simp only [invMulSubgroup, ← coe_mul, Subgroup.mem_mk, Submonoid.mem_mk, Subsemigroup.mem_mk,
mem_coe]
infer_instance
private lemma weak_invMulSubgroup_bound (h : #(A * A) < (3 / 2 : ℚ) * #A) :
#(A⁻¹ * A) < 2 * #A := by
have h₀ : A.Nonempty := nonempty_of_doubling h
have h₁ a (ha : a ∈ A⁻¹ * A) : (1 / 2 : ℚ) * #A < #{xy ∈ A ×ˢ A | xy.1 * xy.2⁻¹ = a} := by
convert lt_card_mul_inv_eq (by simpa using Rat.cast_strictMono (K := ℝ) h) ha
norm_num
simp [← Rat.cast_lt (K := ℝ)]
have h₂ : ∀ x ∈ A ×ˢ A, (fun ⟨x, y⟩ => x * y⁻¹) x ∈ A⁻¹ * A := by
rw [← mul_inv_eq_inv_mul_of_doubling_lt_two (weaken_doubling h)]
simp only [mem_product, Prod.forall, mem_mul, and_imp, mem_inv]
intro a b ha hb
exact ⟨a, ha, b⁻¹, by simp [hb], rfl⟩
have : ((1 / 2 : ℚ) * #A) * #(A⁻¹ * A) < (#A : ℚ) ^ 2 := by
rw [← Nat.cast_pow, sq, ← card_product, card_eq_sum_card_fiberwise h₂, Nat.cast_sum]
refine (sum_lt_sum_of_nonempty (by simp [h₀]) h₁).trans_eq' ?_
simp only [sum_const, nsmul_eq_mul, mul_comm]
rw [← Nat.cast_lt (α := ℚ), Nat.cast_mul, Nat.cast_two]
-- passing between ℕ- and ℚ-inequalities is annoying, here and above
nlinarith
private lemma A_subset_aH (a : G) (ha : a ∈ A) : A ⊆ a • (A⁻¹ * A) := by
rw [← smul_mul_assoc]
exact subset_mul_right _ (by simp [← inv_smul_mem_iff, inv_mem_inv ha])
private lemma subgroup_strong_bound_left (h : #(A * A) < (3 / 2 : ℚ) * #A) (a : G) (ha : a ∈ A) :
A * A ⊆ a • op a • (A⁻¹ * A) := by
have h₁ : (A⁻¹ * A) * (A⁻¹ * A) = A⁻¹ * A := by
rw [← coe_inj, coe_mul, coe_mul, ← invMulSubgroup_eq_inv_mul _ h, coe_mul_coe]
have h₂ : a • op a • (A⁻¹ * A) = (a • (A⁻¹ * A)) * (op a • (A⁻¹ * A)) := by
rw [mul_smul_comm, smul_mul_assoc, h₁, smul_comm]
rw [h₂]
refine mul_subset_mul (A_subset_aH a ha) ?_
rw [← mul_inv_eq_inv_mul_of_doubling_lt_two (weaken_doubling h), ← mul_smul_comm]
exact subset_mul_left _ (by simp [← inv_smul_mem_iff, inv_mem_inv ha])
private lemma subgroup_strong_bound_right (h : #(A * A) < (3 / 2 : ℚ) * #A) (a : G) (ha : a ∈ A) :
a • op a • (A⁻¹ * A) ⊆ A * A := by
intro z hz
simp only [mem_smul_finset, smul_eq_mul_unop, unop_op, smul_eq_mul, mem_mul, mem_inv,
exists_exists_and_eq_and] at hz
obtain ⟨d, ⟨b, hb, c, hc, rfl⟩, hz⟩ := hz
let l : Finset G := A ∩ ((z * a⁻¹) • (A⁻¹ * A))
-- ^ set of x ∈ A st ∃ y ∈ H a with x y = z
let r : Finset G := (a • (A⁻¹ * A)) ∩ (z • A⁻¹)
-- ^ set of x ∈ a H st ∃ y ∈ A with x y = z
have : (A⁻¹ * A) * (A⁻¹ * A) = A⁻¹ * A := by
rw [← coe_inj, coe_mul, coe_mul, ← invMulSubgroup_eq_inv_mul _ h, coe_mul_coe]
have hl : l = A := by
rw [inter_eq_left, ← this, subset_smul_finset_iff]
simp only [← hz, mul_inv_rev, inv_inv, ← mul_assoc]
refine smul_finset_subset_mul ?_
simp [mul_mem_mul, ha, hb, hc]
have hr : r = z • A⁻¹ := by
rw [inter_eq_right, ← this, mul_assoc _ A,
← mul_inv_eq_inv_mul_of_doubling_lt_two (weaken_doubling h), subset_smul_finset_iff]
simp only [← mul_assoc, smul_smul]
refine smul_finset_subset_mul ?_
simp [← hz, mul_mem_mul, ha, hb, hc]
have lr : l ∪ r ⊆ a • (A⁻¹ * A) := by
rw [union_subset_iff, hl]
exact ⟨A_subset_aH a ha, inter_subset_left⟩
have : #l = #A := by rw [hl]
have : #r = #A := by rw [hr, card_smul_finset, card_inv]
have : #(l ∪ r) < 2 * #A := by
refine (card_le_card lr).trans_lt ?_
rw [card_smul_finset]
exact weak_invMulSubgroup_bound h
have ⟨t, ht⟩ : (l ∩ r).Nonempty := by
rw [← card_pos]
linarith [card_inter_add_card_union l r]
simp only [hl, hr, mem_inter, ← inv_smul_mem_iff, smul_eq_mul, mem_inv', mul_inv_rev,
inv_inv] at ht
rw [mem_mul]
exact ⟨t, ht.1, t⁻¹ * z, ht.2, by simp⟩
open scoped RightActions in
lemma smul_inv_mul_opSMul_eq_mul_of_doubling_lt_three_halves (h : #(A * A) < (3 / 2 : ℚ) * #A)
(ha : a ∈ A) : a •> ((A⁻¹ * A) <• a) = A * A :=
(subgroup_strong_bound_right h a ha).antisymm (subgroup_strong_bound_left h a ha)
lemma card_inv_mul_of_doubling_lt_three_halves (h : #(A * A) < (3 / 2 : ℚ) * #A) :
#(A⁻¹ * A) = #(A * A) := by
obtain ⟨a, ha⟩ := nonempty_of_doubling h
simp_rw [← smul_inv_mul_opSMul_eq_mul_of_doubling_lt_three_halves h ha, card_smul_finset]
lemma smul_inv_mul_eq_inv_mul_opSMul (h : #(A * A) < (3 / 2 : ℚ) * #A) (ha : a ∈ A) :
a •> (A⁻¹ * A) = (A⁻¹ * A) <• a := by
refine subset_antisymm ?_ ?_
· rw [subset_smul_finset_iff, ← op_inv]
calc
a •> (A⁻¹ * A) <• a⁻¹ ⊆ a •> (A⁻¹ * A) * A⁻¹ := op_smul_finset_subset_mul (by simpa)
_ ⊆ A * (A⁻¹ * A) * A⁻¹ := by grw [smul_finset_subset_mul (by simpa)]
_ = A⁻¹ * A := by
simp_rw [← coe_inj, coe_mul]
rw [← mul_assoc, ← invMulSubgroup_eq_mul_inv _ h, mul_assoc,
← invMulSubgroup_eq_mul_inv _ h, coe_mul_coe, invMulSubgroup_eq_inv_mul]
· rw [subset_smul_finset_iff]
calc
a⁻¹ •> ((A⁻¹ * A) <• a) ⊆ A⁻¹ * (A⁻¹ * A) <• a := smul_finset_subset_mul (by simpa)
_ ⊆ A⁻¹ * ((A⁻¹ * A) * A) := by grw [op_smul_finset_subset_mul (by simpa)]
_ = A⁻¹ * A := by
rw [← mul_inv_eq_inv_mul_of_doubling_lt_two <| weaken_doubling h]
simp_rw [← coe_inj, coe_mul]
rw [mul_assoc, ← invMulSubgroup_eq_inv_mul _ h, ← mul_assoc,
← invMulSubgroup_eq_inv_mul _ h, ← invMulSubgroup_eq_mul_inv _ h, coe_mul_coe]
open scoped RightActions in
/-- If `A` has doubling strictly less than `3 / 2`, then there exists a subgroup `H` of the
normaliser of `A` of size strictly less than `3 / 2 * #A` such that `A` is a subset of a coset of
`H` (in fact a subset of `a • H` for every `a ∈ A`).
Note that this is sharp: `A = {0, 1}` in `ℤ` has doubling `3 / 2` and can't be covered by a subgroup
of size at most `2`.
This is Theorem 2.2.1 in [tointon2020]. -/
theorem doubling_lt_three_halves (h : #(A * A) < (3 / 2 : ℚ) * #A) :
∃ (H : Subgroup G) (_ : Fintype H), Fintype.card H < (3 / 2 : ℚ) * #A ∧ ∀ a ∈ A,
(A : Set G) ⊆ a • H ∧ a •> (H : Set G) = H <• a := by
let H := invMulSubgroup A h
refine ⟨H, inferInstance, ?_, fun a ha ↦ ⟨?_, ?_⟩⟩
· simp [← Nat.card_eq_fintype_card, invMulSubgroup, ← coe_mul, - coe_inv, H]
rwa [Nat.card_eq_finsetCard, card_inv_mul_of_doubling_lt_three_halves h]
· rw [invMulSubgroup_eq_inv_mul]
exact_mod_cast A_subset_aH a ha
· simpa [H, invMulSubgroup_eq_inv_mul, ← coe_inv, ← coe_mul, ← coe_smul_finset]
using smul_inv_mul_eq_inv_mul_opSMul h ha
/-! ### Doubling strictly less than `φ` -/
omit [DecidableEq G] in
private lemma op_smul_eq_iff_mem {H : Subgroup G} {c : Set G} {x : G}
(hc : c ∈ orbit Gᵐᵒᵖ (H : Set G)) : x ∈ c ↔ H <• x = c := by
refine ⟨fun hx => ?_, fun hx =>
by simp only [← hx, mem_rightCoset_iff, mul_inv_cancel, SetLike.mem_coe, one_mem]⟩
obtain ⟨⟨a⟩, rfl⟩ := hc
change _ = _ <• _
rw [eq_comm, smul_eq_iff_eq_inv_smul, ← op_inv, op_smul_op_smul, rightCoset_mem_rightCoset]
rwa [← op_smul_eq_mul, op_inv, ← SetLike.mem_coe, ← Set.mem_smul_set_iff_inv_smul_mem]
omit [DecidableEq G] in
private lemma op_smul_eq_op_smul_iff_mem {H : Subgroup G} {x y : G} :
x ∈ (H : Set G) <• y ↔ (H : Set G) <• x = H <• y := op_smul_eq_iff_mem (mem_orbit _ _)
omit [DecidableEq G] in
/-- Given a finite subset `A` of a group `G` and a subgroup `H ≤ G`, there exists a subset `Z ⊆ A`
such that `H * Z = H * A` and the cosets `Hz` are disjoint as `z` runs over `Z`. -/
private lemma exists_subset_mul_eq_mul_injOn (H : Subgroup G) (A : Finset G) :
∃ Z ⊆ A, (H : Set G) * Z = H * A ∧ (Z : Set G).InjOn ((H : Set G) <• ·) := by
obtain ⟨Z, hZA, hZinj, hHZA⟩ :=
((A : Set G).surjOn_image ((H : Set G) <• ·)).exists_subset_injOn_image_eq
lift Z to Finset G using A.finite_toSet.subset hZA
refine ⟨Z, mod_cast hZA, ?_, hZinj⟩
simpa [-SetLike.mem_coe, Set.iUnion_op_smul_set] using congr(Set.sUnion $hHZA)
private lemma card_mul_eq_mul_card_of_injOn_opSMul {H : Subgroup G} [Fintype H]
{Z : Finset G} (hZ : (Z : Set G).InjOn ((H : Set G) <• ·)) :
Fintype.card H * #Z = #(Set.toFinset H * Z) := by
rw [card_mul_iff.2]
· simp
rintro ⟨h₁, z₁⟩ ⟨hh₁, hz₁⟩ ⟨h₂, z₂⟩ ⟨hh₂, hz₂⟩ h
simp only [Set.coe_toFinset, SetLike.mem_coe] at *
obtain rfl := hZ hz₁ hz₂ <| (rightCoset_eq_iff _).2 <| by
simpa [eq_inv_mul_iff_mul_eq.2 h, mul_assoc] using mul_mem (inv_mem hh₂) hh₁
simp_all
open goldenRatio in
/-- If `A` has doubling `K` strictly less than `φ`, then `A * A⁻¹` is covered by
at most a constant number of cosets of a finite subgroup of `G`. -/
theorem doubling_lt_golden_ratio (hK₁ : 1 < K) (hKφ : K < φ)
(hA₁ : #(A⁻¹ * A) ≤ K * #A) (hA₂ : #(A * A⁻¹) ≤ K * #A) :
∃ (H : Subgroup G) (_ : Fintype H) (Z : Finset G),
#Z ≤ (2 - K) * K / ((φ - K) * (K - ψ)) ∧ (H : Set G) * Z = A * A⁻¹ := by
classical
-- Some useful initial calculations
have K_pos : 0 < K := by positivity
have hK₀ : 0 < K := by positivity
have hKφ' : 0 < φ - K := by linarith
have hKψ' : 0 < K - ψ := by linarith [Real.goldenConj_neg]
have hK₂' : 0 < 2 - K := by linarith [Real.goldenRatio_lt_two]
have const_pos : 0 < K * (2 - K) / ((φ - K) * (K - ψ)) := by positivity
-- We dispatch the trivial case `A = ∅` separately.
obtain rfl | A_nonempty := A.eq_empty_or_nonempty
· exact ⟨⊥, inferInstance, ∅, by simp; positivity⟩
-- In the case where `A` is non-empty, we consider the set `S := A * A⁻¹` and its stabilizer `H`.
let S := A * A⁻¹
let H := stabilizer G S
-- `S` is finite and non-empty (because `A` is), and therefore `H` is finite too.
have S_nonempty : S.Nonempty := by simpa [S]
have : Finite H := by simpa [H] using stabilizer_finite (by simpa) S.finite_toSet
cases nonempty_fintype H
-- By definition, `H * S = S`.
have H_mul_S : (H : Set G) * S = S := by simp [H, ← stabilizer_coe_finset]
-- Since `H` is a subgroup, find a finite set `Z ⊆ S` such that `H * Z = S` and `|H| * |Z| = |S|`.
obtain ⟨Z, hZ⟩ := exists_subset_mul_eq_mul_injOn H S
have H_mul_Z : (H : Set G) * Z = S := by simp [hZ.2.1, H_mul_S]
have H_toFinset_mul_Z : Set.toFinset H * Z = S := by simpa [← Finset.coe_inj]
have card_H_mul_card_Z : Fintype.card H * #Z = #S := by
simpa [card_mul_eq_mul_card_of_injOn_opSMul hZ.2.2] using congr_arg _ H_toFinset_mul_Z
-- It remains to show that `|Z| ≤ C(K)` for some `C(K)` depending only on `K`.
refine ⟨H, inferInstance, Z, ?_, mod_cast H_mul_Z⟩
-- This is equivalent to showing that `|H| ≥ c(K)|S|` for some `c(K)` depending only on `K`.
suffices ((φ - K) * (K - ψ)) / ((2 - K) * K) * #S ≤ Fintype.card H by
calc
(#Z : ℝ)
_ = (Fintype.card H / #S : ℝ)⁻¹ := by simp [← card_H_mul_card_Z]
_ ≤ (((φ - K) * (K - ψ) / ((2 - K) * K) * #S) / #S)⁻¹ := by gcongr
_ = (2 - K) * K / ((φ - K) * (K - ψ)) := by
have : (#S : ℝ) ≠ 0 := by positivity
simp [this]
-- Write `r(z)` the number of representations of `z ∈ S` as `x * y⁻¹` for `x, y ∈ A`.
let r z : ℕ := A.convolution A⁻¹ z
-- `r` is invariant under inverses.
have r_inv z : r z⁻¹ = r z := by simp [r, inv_inv]
-- We show that every `z ∈ S` with at least `(K - 1)|A|` representations lies in `H`,
-- and that such `z` make up a proportion of at least `(2 - K) / ((φ - K) * (K - ψ))` of `S`.
calc
(φ - K) * (K - ψ) / ((2 - K) * K) * #S
_ ≤ #{z ∈ S | (K - 1) * #A < r z} := ?_
_ ≤ #(H : Set G).toFinset := ?_
_ = Fintype.card H := by simp
-- First, let's show that a large proportion of all `z ∈ S` have many representations.
· -- Let `l` be that number.
set l : ℕ := #{z ∈ S | (K - 1) * #A < r z} with hk
-- By upper-bounding `r(z)` by `(K - 1)|A|` for the `z` with few representations,
-- and by `|A|` for the `z` with many representations,
-- we get `|A|² ≤ l|A| + (|S| - l)(K - 1)|A| = ((2 - K)l + (K - 1)|S|)|A|`.
have ineq : #A * #A ≤ ((2 - K) * l + (K - 1) * #S) * #A := by
calc
(#A : ℝ) * #A
_ = #A * #A⁻¹ := by simp
_ = #(A ×ˢ A⁻¹) := by simp
_ = ∑ z ∈ S, ↑(r z) := by
norm_cast
exact card_eq_sum_card_fiberwise fun xy hxy ↦
mul_mem_mul (mem_product.mp hxy).1 (mem_product.mp hxy).2
_ = ∑ z ∈ S with (K - 1) * #A < r z, ↑(r z) + ∑ z ∈ S with r z ≤ (K - 1) * #A, ↑(r z) := by
norm_cast; simp_rw [← not_lt, sum_filter_add_sum_filter_not]
_ ≤ ∑ z ∈ S with (K - 1) * #A < r z, ↑(#A)
+ ∑ z ∈ S with r z ≤ (K - 1) * #A, (K - 1) * #A := by
gcongr with z hz z hz
· exact convolution_le_card_left
· simp_all
_ = l * #A + (#S - l) * (K - 1) * #A := by
simp [hk, ← not_lt, mul_assoc,
← S.filter_card_add_filter_neg_card_eq_card fun z ↦ (K - 1) * #A < r z]
_ = ((2 - K) * l + (K - 1) * #S) * #A := by ring
-- By cancelling `|A|` on both sides, we get `|A| ≤ (2 - K)l + (K - 1)|S|`.
-- By composing with `|S| ≤ K|A|`, we get `|S| ≤ (2 - K)Kl + (K - 1)K|S|`.
have : 0 < #A := by positivity
replace ineq := calc
(#S : ℝ)
_ ≤ K * #A := ‹_›
_ ≤ K * ((2 - K) * l + (K - 1) * #S) := by
gcongr; exact le_of_mul_le_mul_right ineq <| by positivity
_ = (2 - K) * K * l + (K - 1) * K * #S := by ring
-- Now, we are done.
calc
(φ - K) * (K - ψ) / ((2 - K) * K) * #S
_ = (φ - K) * (K - ψ) * #S / ((2 - K) * K) := div_mul_eq_mul_div ..
_ ≤ (2 - K) * K * l / ((2 - K) * K) := by
have := Real.goldenRatio_mul_goldenConj
have := Real.goldenRatio_add_goldenConj
rw [show (φ - K) * (K - ψ) = 1 - (K - 1) * K by grind]
gcongr ?_ / _
linarith [ineq]
_ = l := by field
-- Second, let's show that the `z ∈ S` with many representations are in `H`.
· gcongr
simp only [subset_iff, mem_filter, Set.mem_toFinset, SetLike.mem_coe, and_imp]
rintro z hz hrz
-- It's enough to show that `z * w ∈ S` for all `w ∈ S`.
rw [mem_stabilizer_finset']
rintro w hw
-- Since `w ∈ S` and `|A⁻¹ * A| ≤ K|A|`, we know that `r(w) ≥ (2 - K)|A|`.
have hrw : (2 - K) * #A ≤ r w := by
simpa [card_mul_inv_eq_convolution_inv] using le_card_mul_inv_eq hA₁ (by simpa)
-- But also `r(z⁻¹) = r(z) > (K - 1)|A|`.
rw [← r_inv] at hrz
simp only [r, ← card_inter_smul] at hrz hrw
-- By inclusion-exclusion, we get that `(z⁻¹ •> A) ∩ (w •> A)` is non-empty.
have : (0 : ℝ) < #((z⁻¹ •> A) ∩ (w •> A)) := by
have : (#((A ∩ z⁻¹ •> A) ∩ (A ∩ w •> A)) : ℝ) ≤ #(z⁻¹ •> A ∩ w •> A) := by
gcongr <;> exact inter_subset_right
have : (#((A ∩ z⁻¹ •> A) ∪ (A ∩ w •> A)) : ℝ) ≤ #A := by
gcongr; exact union_subset inter_subset_left inter_subset_left
have :
(#((A ∩ z⁻¹ •> A) ∩ (A ∩ w •> A)) + #((A ∩ z⁻¹ •> A) ∪ (A ∩ w •> A)) : ℝ) =
#(A ∩ z⁻¹ •> A) + #(A ∩ w •> A) := mod_cast card_inter_add_card_union ..
linarith
-- This is exactly what we set out to prove.
simpa [S, card_smul_inter_smul, Finset.Nonempty, mem_mul, mem_inv, -mem_inv', and_assoc]
using this
/-! ### Doubling less than `2-ε` -/
variable (ε : ℝ)
/-- Given a constant `K ∈ ℝ` (usually `0 < K ≤ 1`) and a finite subset `S ⊆ G`,
`expansion K S : Finset G → ℝ` measures the extent to which `S` extends the argument, compared
against the reference constant `K`. That is, given a finite `A ⊆ G` (possibly empty),
`expansion K S A` is defined as the value of `#(SA) - K#S`. -/
private def expansion (K : ℝ) (S A : Finset G) : ℝ := #(A * S) - K * #A
@[simp] private lemma expansion_empty (K : ℝ) (S : Finset G) : expansion K S ∅ = 0 := by
simp [expansion]
private lemma mul_card_le_expansion (hS : S.Nonempty) : (1 - K) * #A ≤ expansion K S A := by
rw [one_sub_mul, expansion]; have := card_le_card_mul_right hS (s := A); gcongr
@[simp] private lemma expansion_nonneg (hK : K ≤ 1) (hS : S.Nonempty) : 0 ≤ expansion K S A := by
nlinarith [mul_card_le_expansion (K := K) hS (A := A)]
@[simp] private lemma expansion_pos (hK : K < 1) (hS : S.Nonempty) (hA : A.Nonempty) :
0 < expansion K S A := by
have : (0 : ℝ) < #A := by simp [hA]
nlinarith [mul_card_le_expansion (K := K) hS (A := A)]
@[simp] private lemma expansion_pos_iff (hK : K < 1) (hS : S.Nonempty) :
0 < expansion K S A ↔ A.Nonempty where
mp hA := by rw [nonempty_iff_ne_empty]; rintro rfl; simp at hA
mpr := expansion_pos hK hS
@[simp] private lemma expansion_smul_finset (K : ℝ) (S A : Finset G) (a : G) :
expansion K S (a • A) = expansion K S A := by simp [expansion, smul_mul_assoc]
private lemma expansion_submodularity :
expansion K S (A ∩ B) + expansion K S (A ∪ B) ≤ expansion K S A + expansion K S B := by
have : (#(A ∩ B) + #(A ∪ B) : ℝ) = #A + #B := mod_cast card_inter_add_card_union A B
have : K * #(A ∩ B) + K * #(A ∪ B) = K * #A + K * #B := by simp only [← mul_add, this]
have : (#(A * S ∩ (B * S)) + #(A * S ∪ B * S) : ℝ) = #(A * S) + #(B * S) :=
mod_cast card_inter_add_card_union (A * S) (B * S)
have : (#((A ∩ B) * S) : ℝ) ≤ #(A * S ∩ (B * S)) := by grw [inter_mul_subset]
simp_rw [expansion, union_mul]
nlinarith
private lemma bddBelow_expansion (hK : K ≤ 1) (hS : S.Nonempty) :
BddBelow (Set.range fun A : {A : Finset G // A.Nonempty} ↦ expansion K S A) :=
⟨0, by simp [lowerBounds, *]⟩
/-- Given `K ∈ ℝ` and a finite `S ⊆ G`, the connectivity `κ` of `G` with respect to `K` and `S` is
the infimum of `expansion K S A` over all finite nonempty `A ⊆ G`. Note that when `K ≤ 1`,
`expansion K S A` is nonnegative for all `A`, so the infimum exists. -/
private noncomputable def connectivity (K : ℝ) (S : Finset G) : ℝ :=
⨅ A : {A : Finset G // A.Nonempty}, expansion K S A
@[simp] private lemma le_connectivity_iff (hK : K ≤ 1) (hS : S.Nonempty) {r : ℝ} :
r ≤ connectivity K S ↔ ∀ ⦃A : Finset G⦄, A.Nonempty → r ≤ expansion K S A := by
have : Nonempty {A : Finset G // A.Nonempty} := ⟨{1}, by simp⟩
simp [connectivity, le_ciInf_iff, bddBelow_expansion, *]
@[simp] private lemma connectivity_lt_iff (hK : K ≤ 1) (hS : S.Nonempty) {r : ℝ} :
connectivity K S < r ↔ ∃ A : Finset G, A.Nonempty ∧ expansion K S A < r := by
have : Nonempty {A : Finset G // A.Nonempty} := ⟨{1}, by simp⟩
simp [connectivity, ciInf_lt_iff, bddBelow_expansion, *]
@[simp] private lemma connectivity_le_expansion (hK : K ≤ 1) (hS : S.Nonempty) (hA : A.Nonempty) :
connectivity K S ≤ expansion K S A := (le_connectivity_iff hK hS).1 le_rfl hA
private lemma connectivity_nonneg (hK : K ≤ 1) (hS : S.Nonempty) :
0 ≤ connectivity K S := by simp [*]
/-- Given `K ∈ ℝ` and a finite `S ⊆ G`, a fragment of `G` with respect to `K` and `S` is a finite
nonempty `A ⊆ G` whose expansion attains the value of the connectivity, that is,
`expansion K S A = κ`. -/
private def IsFragment (K : ℝ) (S A : Finset G) : Prop := expansion K S A = connectivity K S
/-- Given `K ∈ ℝ` and a finite `S ⊆ G`, an atom of `G` with respect to `K` and `S` is a (finite
and nonempty) fragment `A` of minimal cardinality. -/
private def IsAtom (K : ℝ) (S A : Finset G) : Prop := MinimalFor (IsFragment K S) card A
private lemma IsAtom.isFragment (hA : IsAtom K S A) : IsFragment K S A := hA.1
@[simp] private lemma isFragment_smul_finset : IsFragment K S (a • A) ↔ IsFragment K S A := by
simp [IsFragment]
@[simp] private lemma isAtom_smul_finset : IsAtom K S (a • A) ↔ IsAtom K S A := by
simp [IsAtom, MinimalFor]
private lemma IsFragment.smul_finset (a : G) (hA : IsFragment K S A) : IsFragment K S (a • A) :=
isFragment_smul_finset.2 hA
private lemma IsAtom.smul_finset (a : G) (hA : IsAtom K S A) : IsAtom K S (a • A) :=
isAtom_smul_finset.2 hA
private lemma IsFragment.inter (hK : K ≤ 1) (hS : S.Nonempty) (hA : IsFragment K S A)
(hB : IsFragment K S B) (hAB : (A ∩ B).Nonempty) : IsFragment K S (A ∩ B) := by
unfold IsFragment at *
have := expansion_submodularity (S := S) (A := A) (B := B) (K := K)
have := connectivity_le_expansion hK hS hAB
have := connectivity_le_expansion hK hS <| hAB.mono inter_subset_union
linarith
private lemma IsAtom.eq_of_inter_nonempty (hK : K ≤ 1) (hS : S.Nonempty)
(hA : IsAtom K S A) (hB : IsAtom K S B) (hAB : (A ∩ B).Nonempty) : A = B := by
replace hAB := hA.isFragment.inter hK hS hB.isFragment hAB
replace hA := hA.2 hAB <| by grw [inter_subset_left]
replace hB := hB.2 hAB <| by grw [inter_subset_right]
replace hA := eq_of_subset_of_card_le inter_subset_left hA
replace hB := eq_of_subset_of_card_le inter_subset_right hB
exact hA.symm.trans hB
/-- For `K < 1` and `S ⊆ G` finite and nonempty, the value of connectivity is attained by a
nonempty finite subset of `G`. That is, a fragment for given `K` and `S` exists. -/
private lemma exists_nonempty_isFragment (hK : K < 1) (hS : S.Nonempty) :
∃ A, A.Nonempty ∧ IsFragment K S A := by
-- We will show this lemma by contradiction. So we suppose that the infimum in the definition of
-- connectivity is not attained by a nonempty finite subset of `G`, or, equivalently, that for
-- every `κ < k` where `κ` is the connectivity, there is nonempty `A` such that `κ < ex A < k`.
by_contra! H
let ex := expansion K S
let κ := connectivity K S
-- Some useful calculations
have κ_add_one_pos : 0 < κ + 1 := by linarith [connectivity_nonneg hK.le hS]
have one_sub_K_pos : 0 < 1 - K := by linarith
-- First we show that for large enough `A`, `κ + 1 < ex A`. Calculations show that
-- `#A > ⌊(κ + 1) / (1 - K)⌋` suffices. We will actually use the contrapositive of this result: if
-- `ex A` is near `κ`, then `A` will need to be small.
let t := Nat.floor ((κ + 1) / (1 - K))
have largeA {A : Finset G} (hA : t < #A) : κ + 1 < ex A := by
rw [Nat.lt_iff_add_one_le] at hA
calc
κ + 1
_ = (κ + 1) / ((κ + 1) / (1 - K)) * ((κ + 1) / (1 - K)) := by field
_ < (κ + 1) / ((κ + 1) / (1 - K)) * (t + 1) := by gcongr; exact Nat.lt_floor_add_one _
_ = (1 - K) * (t + 1) := by field
_ ≤ (1 - K) * #A := by norm_cast; gcongr
_ ≤ ex A := mul_card_le_expansion hS
-- On the other hand, we essentially show that there are only finitely many possible values for
-- `A` with `#A ≤ t`, and these values are found in the set `M = (⟦#S, t#S⟧ - K⟦1, t⟧) ∩ (κ, ∞)`.
let M := {x ∈ ((Icc #S (t * #S)).map Nat.castEmbedding -
K • (Icc 1 t).map Nat.castEmbedding : Finset ℝ) | κ < x}
have smallA {A : Finset G} (hA : A.Nonempty) (hAt : #A ≤ t) : ex A ∈ M := by
rw [mem_filter]
refine ⟨sub_mem_sub ?_ ?_, (connectivity_le_expansion hK.le hS hA).lt_of_ne' <| H _ hA⟩
· apply mem_map_of_mem
exact mem_Icc.2 ⟨card_le_card_mul_left hA, by grw [card_mul_le, hAt]⟩
· apply smul_mem_smul_finset
apply mem_map_of_mem
exact mem_Icc.2 ⟨Nat.one_le_iff_ne_zero.mpr hA.card_ne_zero, hAt⟩
-- Now we take the minimum value of `M` (union `{κ + 1}` to handle the eventual emptiness of `M`
-- and get better bounds). This will be strictly larger than `κ` by definition.
have : (M ∪ {κ + 1}).Nonempty := by simp
let k := (M ∪ {κ + 1}).min' this
have : κ < k := by simp [k, M]
-- By the property of infimum and the previous claim, there is `A` with `κ < ex A < k ≤ κ + 1`.
-- But then the claim about large `A` implies that `#A ≤ t` and thus `ex A ∈ M` and `k ≤ ex A`,
-- a contradiction.
obtain ⟨A, hA, hAk⟩ := (connectivity_lt_iff hK.le hS).mp this
have : ex A ≤ κ + 1 := hAk.le.trans <| min'_le _ _ (by simp)
have := not_lt.mp (mt largeA this.not_gt)
exact hAk.not_ge <| min'_le (M ∪ {κ + 1}) _ <| subset_union_left <| smallA hA this
private lemma exists_isFragment (hK : K < 1) (hS : S.Nonempty) :
∃ A, IsFragment K S A := let ⟨A, _, hA⟩ := exists_nonempty_isFragment hK hS; ⟨A, hA⟩
private lemma exists_isAtom (hK : K < 1) (hS : S.Nonempty) : ∃ A, IsAtom K S A :=
exists_minimalFor_of_wellFoundedLT _ _ <| exists_isFragment hK hS
private lemma connectivity_pos (hK : K < 1) (hS : S.Nonempty) : 0 < connectivity K S := by
obtain ⟨A, hA, hSA⟩ := exists_nonempty_isFragment hK hS
exact (expansion_pos hK hS hA).trans_eq hSA
private lemma not_isFragment_empty (hK : K < 1) (hS : S.Nonempty) : ¬ IsFragment K S ∅ := by
simp [IsFragment, (connectivity_pos hK hS).ne]
private lemma IsFragment.nonempty (hK : K < 1) (hS : S.Nonempty) (hA : IsFragment K S A) :
A.Nonempty := by
rw [nonempty_iff_ne_empty]
rintro rfl
simp [*, not_isFragment_empty hK hS] at hA
private lemma IsAtom.nonempty (hK : K < 1) (hS : S.Nonempty) (hA : IsAtom K S A) : A.Nonempty :=
hA.isFragment.nonempty hK hS
/-- For `K < 1` and finite nonempty `S ⊆ G`, there exists a finite subgroup `H ≤ G` that is also
an atom for `K` and `S`. -/
private lemma exists_subgroup_isAtom (hK : K < 1) (hS : S.Nonempty) :
∃ (H : Subgroup G) (_ : Fintype H), IsAtom K S (Set.toFinset H) := by
-- We take any atom `N` of `G` with respect to `K` and `S`. Since left multiples of `N` (which
-- are atoms as well) partition `G` by `IsAtom.eq_of_inter_nonempty`, we will deduce that a left
-- multiple that contains `1` is a (finite) subgroup of `G`.
obtain ⟨N, hN⟩ := exists_isAtom hK hS
obtain ⟨n, hn⟩ := IsAtom.nonempty hK hS hN
have one_mem_carrier : 1 ∈ n⁻¹ •> N := by simpa [mem_inv_smul_finset_iff]
have self_mem_smul_carrier (x : G) : x ∈ x • n⁻¹ • N := by
apply smul_mem_smul_finset (a := x) at one_mem_carrier
simpa only [smul_eq_mul, mul_one] using one_mem_carrier
let H : Subgroup G := {
carrier := n⁻¹ •> N
one_mem' := mod_cast one_mem_carrier
mul_mem' {a b} ha hb := by
rw [← coe_smul_finset, mem_coe] at *
apply smul_mem_smul_finset (a := a) at hb
rw [smul_eq_mul] at hb
have : (n⁻¹ •> N ∩ a •> n⁻¹ •> N).Nonempty := ⟨a, by
simpa only [mem_inter] using ⟨ha, self_mem_smul_carrier a⟩⟩
simpa only [← (hN.smul_finset n⁻¹).eq_of_inter_nonempty hK.le hS
((hN.smul_finset n⁻¹).smul_finset a) this] using hb
inv_mem' {a} ha := by
rw [← coe_smul_finset, mem_coe] at *
apply smul_mem_smul_finset (a := a⁻¹) at ha
rw [smul_eq_mul, inv_mul_cancel] at ha
have : (n⁻¹ •> N ∩ a⁻¹ •> n⁻¹ •> N).Nonempty := ⟨1, by simpa using ⟨one_mem_carrier, ha⟩⟩
simpa only [← (hN.smul_finset n⁻¹).eq_of_inter_nonempty hK.le hS
((hN.smul_finset n⁻¹).smul_finset a⁻¹) this] using self_mem_smul_carrier a⁻¹
}
refine ⟨H, Fintype.ofFinset (n⁻¹ •> N) fun a => ?_, ?_⟩
· simpa only [← mem_coe, coe_smul_finset] using H.mem_carrier
· simpa [Set.toFinset_smul_set, toFinset_coe, H] using IsAtom.smul_finset n⁻¹ hN
/-- If `S` is nonempty such that there is `A` with `|S| ≤ |A|` such that `|A * S| ≤ (2 - ε) * |S|`
for some `0 < ε ≤ 1`, then there is a finite subgroup `H` of `G` of size `|H| ≤ (2 / ε - 1) * |S|`
such that `S` is covered by at most `2 / ε - 1` right cosets of `H`. -/
theorem card_mul_finset_lt_two {ε : ℝ} (hε₀ : 0 < ε) (hε₁ : ε ≤ 1) (hS : S.Nonempty)
(hA : ∃ A : Finset G, #S ≤ #A ∧ #(A * S) ≤ (2 - ε) * #S) :
∃ (H : Subgroup G) (_ : Fintype H) (Z : Finset G),
Fintype.card H ≤ (2 / ε - 1) * #S ∧ #Z ≤ 2 / ε - 1 ∧ (S : Set G) ⊆ H * Z := by
let K := 1 - ε / 2
have hK : K < 1 := by unfold K; linarith [hε₀]
let ex := expansion K S
let κ := connectivity K S
-- We will show that an atomic subgroup `H ≤ G` with respect to `K` and `S` and the right coset
-- representing finset of `S` acting on `H` are adequate choices for the theorem
obtain ⟨H, _, hH⟩ := exists_subgroup_isAtom hK hS
obtain ⟨Z, hZS, hHZS, hZinj⟩ := exists_subset_mul_eq_mul_injOn H S
-- We only use the existence of `A` given by assumption to get a good bound on `ex H` solely
-- in terms of `#S` and `ε`.
obtain ⟨A, hA₁, hA₂⟩ := hA
have calc₁ : ex (Set.toFinset H) ≤ (1 - ε / 2) * #S := by
calc
ex (Set.toFinset H)
_ = κ := hH.isFragment
_ ≤ #(A * S) - K * #A :=
connectivity_le_expansion hK.le hS <| card_pos.mp <| hS.card_pos.trans_le hA₁
_ ≤ (2 - ε) * #S - (1 - ε / 2) * #S := by gcongr; linarith
_ = (1 - ε / 2) * #S := by linarith
refine ⟨H, inferInstance, Z, ?cardH, ?cardZ, by
simpa only [hHZS] using Set.subset_mul_right _ H.one_mem⟩
-- Bound on `#H` follows easily from the previous calculation.
case cardH =>
rw [← mul_le_mul_iff_right₀ (a := ε / 2) (by positivity)]
calc
ε / 2 * (Fintype.card H)
_ = ε / 2 * #(H : Set G).toFinset := by
simp only [Set.toFinset_card, SetLike.coe_sort_coe]
_ = (1 - K) * #(H : Set G).toFinset := by ring
_ ≤ ex (Set.toFinset H) := mul_card_le_expansion hS
_ ≤ (1 - ε / 2) * #S := calc₁
_ = ε / 2 * ((2 / ε - 1) * #S) := by field
-- To show the bound on `#Z`, we note that `#Z = #(HS) / #H` and show `#(HS) ≤ (2 / ε - 1) * #H`.
case cardZ =>
calc
(#Z : ℝ)
_ = #(H : Set G).toFinset * #Z / #(H : Set G).toFinset := by field
_ = #(Set.toFinset H * Z) / #(H : Set G).toFinset := by
simp [← card_mul_eq_mul_card_of_injOn_opSMul hZinj, Nat.cast_mul]
_ = #(Set.toFinset H * S) / #(H : Set G).toFinset := by
congr 3; simpa using congr(($hHZS).toFinset)
_ ≤ (2 / ε - 1) * #(H : Set G).toFinset / #(H : Set G).toFinset := ?_
_ = 2 / ε - 1 := by field
gcongr
-- Finally, to show `#(HS) ≤ (2 / ε - 1) * #H`, we multiply both sides by `1 - K = ε / 2` and
-- show `#(HS) = K * #H + ex H ≤ K * #H + (1 - ε / 2) * #S ≤ K * #H + (1 - ε / 2) * #(HS)`,
-- where we used `calc₁` again.
rw [← mul_le_mul_iff_right₀ (show 0 < 1 - K by linarith [hK])]
suffices (1 - K) * #(Set.toFinset H * S) ≤ (1 - ε / 2) * #(H : Set G).toFinset by
apply le_of_eq_of_le' _ this; simp [K]; field
rw [sub_mul, one_mul, sub_le_iff_le_add]
calc
(#(Set.toFinset H * S) : ℝ)
_ = K * #(H : Set G).toFinset + (#(Set.toFinset H * S) - K * #(H : Set G).toFinset) := by ring
_ = K * #(H : Set G).toFinset + ex (Set.toFinset H) := rfl
_ ≤ K * #(H : Set G).toFinset + (1 - ε / 2) * #(Set.toFinset H * S) := by
grw [calc₁]
gcongr
· linarith
· simp only [Set.mem_toFinset, SetLike.mem_coe, H.one_mem, subset_mul_right]
/-- Corollary of `card_mul_finset_lt_two` in the case `A = S`, giving characterisation of sets of
doubling less than `2 - ε`. -/
theorem doubling_lt_two {ε : ℝ} (hε₀ : 0 < ε) (hε₁ : ε ≤ 1) (hA₀ : A.Nonempty)
(hA₁ : #(A * A) ≤ (2 - ε) * #A) : ∃ (H : Subgroup G) (_ : Fintype H) (Z : Finset G),
Fintype.card H ≤ (2 / ε - 1) * #A ∧ #Z ≤ 2 / ε - 1 ∧ (A : Set G) ⊆ H * Z :=
card_mul_finset_lt_two hε₀ hε₁ hA₀ ⟨A, by rfl, hA₁⟩
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/ApproximateSubgroup.lean | import Mathlib.Algebra.Group.Subgroup.Pointwise
import Mathlib.Combinatorics.Additive.CovBySMul
import Mathlib.Combinatorics.Additive.RuzsaCovering
import Mathlib.Combinatorics.Additive.SmallTripling
/-!
# Approximate subgroups
This file defines approximate subgroups of a group, namely symmetric sets `A` such that `A * A` can
be covered by a small number of translates of `A`.
## Main results
Approximate subgroups are a central concept in additive combinatorics, as a natural weakening and
flexible substitute of genuine subgroups. As such, they share numerous properties with subgroups:
* `IsApproximateSubgroup.image`: Group homomorphisms send approximate subgroups to approximate
subgroups
* `IsApproximateSubgroup.pow_inter_pow`: The intersection of (non-trivial powers of) two approximate
subgroups is an approximate subgroup. Warning: The intersection of two approximate subgroups isn't
an approximate subgroup in general.
Approximate subgroups are close qualitatively and quantitatively to other concepts in additive
combinatorics:
* `IsApproximateSubgroup.card_pow_le`: An approximate subgroup has small powers.
* `IsApproximateSubgroup.of_small_tripling`: A set of small tripling can be made an approximate
subgroup by squaring.
It can be readily confirmed that approximate subgroups are a weakening of subgroups:
* `isApproximateSubgroup_one`: A 1-approximate subgroup is the same thing as a subgroup.
-/
open scoped Finset Pointwise
variable {G : Type*} [Group G] {A B : Set G} {K L : ℝ} {m n : ℕ}
/--
An approximate subgroup in a group is a symmetric set `A` containing the identity and such that
`A + A` can be covered by a small number of translates of `A`.
In practice, we will take `K` fixed and `A` large but finite.
-/
structure IsApproximateAddSubgroup {G : Type*} [AddGroup G] (K : ℝ) (A : Set G) : Prop where
zero_mem : 0 ∈ A
neg_eq_self : -A = A
two_nsmul_covByVAdd : CovByVAdd G K (2 • A) A
/--
An approximate subgroup in a group is a symmetric set `A` containing the identity and such that
`A * A` can be covered by a small number of translates of `A`.
In practice, we will take `K` fixed and `A` large but finite.
-/
@[to_additive]
structure IsApproximateSubgroup (K : ℝ) (A : Set G) : Prop where
one_mem : 1 ∈ A
inv_eq_self : A⁻¹ = A
sq_covBySMul : CovBySMul G K (A ^ 2) A
namespace IsApproximateSubgroup
@[to_additive] lemma nonempty (hA : IsApproximateSubgroup K A) : A.Nonempty := ⟨1, hA.one_mem⟩
@[to_additive one_le]
lemma one_le (hA : IsApproximateSubgroup K A) : 1 ≤ K := by
obtain ⟨F, hF, hSF⟩ := hA.sq_covBySMul
have hF₀ : F ≠ ∅ := by rintro rfl; simp [hA.nonempty.pow.ne_empty] at hSF
exact hF.trans' <| by simpa [Finset.nonempty_iff_ne_empty]
@[to_additive]
lemma mono (hKL : K ≤ L) (hA : IsApproximateSubgroup K A) : IsApproximateSubgroup L A where
one_mem := hA.one_mem
inv_eq_self := hA.inv_eq_self
sq_covBySMul := hA.sq_covBySMul.mono hKL
@[to_additive]
lemma card_pow_le [DecidableEq G] {A : Finset G} (hA : IsApproximateSubgroup K (A : Set G)) :
∀ {n}, #(A ^ n) ≤ K ^ (n - 1) * #A
| 0 => by simpa using hA.nonempty
| 1 => by simp
| n + 2 => by
obtain ⟨F, hF, hSF⟩ := hA.sq_covBySMul
calc
(#(A ^ (n + 2)) : ℝ) ≤ #(F ^ (n + 1) * A) := by
gcongr; exact mod_cast Set.pow_subset_pow_mul_of_sq_subset_mul hSF (by cutsat)
_ ≤ #(F ^ (n + 1)) * #A := mod_cast Finset.card_mul_le
_ ≤ #F ^ (n + 1) * #A := by gcongr; exact mod_cast Finset.card_pow_le
_ ≤ K ^ (n + 1) * #A := by gcongr
@[to_additive]
lemma card_mul_self_le [DecidableEq G] {A : Finset G} (hA : IsApproximateSubgroup K (A : Set G)) :
#(A * A) ≤ K * #A := by simpa [sq] using hA.card_pow_le (n := 2)
@[to_additive]
lemma image {F H : Type*} [Group H] [FunLike F G H] [MonoidHomClass F G H] (f : F)
(hA : IsApproximateSubgroup K A) : IsApproximateSubgroup K (f '' A) where
one_mem := ⟨1, hA.one_mem, map_one _⟩
inv_eq_self := by simp [← Set.image_inv, hA.inv_eq_self]
sq_covBySMul := by
classical
obtain ⟨F, hF, hAF⟩ := hA.sq_covBySMul
refine ⟨F.image f, ?_, ?_⟩
· calc
(#(F.image f) : ℝ) ≤ #F := mod_cast F.card_image_le
_ ≤ K := hF
· simp only [← Set.image_pow, Finset.coe_image, ← Set.image_mul, smul_eq_mul] at hAF ⊢
gcongr
@[to_additive]
lemma subgroup {S : Type*} [SetLike S G] [SubgroupClass S G] {H : S} :
IsApproximateSubgroup 1 (H : Set G) where
one_mem := OneMemClass.one_mem H
inv_eq_self := inv_coe_set
sq_covBySMul := ⟨{1}, by simp⟩
open Finset in
@[to_additive]
lemma of_small_tripling [DecidableEq G] {A : Finset G} (hA₁ : 1 ∈ A) (hAsymm : A⁻¹ = A)
(hA : #(A ^ 3) ≤ K * #A) : IsApproximateSubgroup (K ^ 3) (A ^ 2 : Set G) where
one_mem := by rw [sq, ← one_mul 1]; exact Set.mul_mem_mul hA₁ hA₁
inv_eq_self := by simp [← inv_pow, hAsymm, ← coe_inv]
sq_covBySMul := by
replace hA := calc (#(A ^ 4 * A) : ℝ)
_ = #(A ^ 5) := by rw [← pow_succ]
_ ≤ K ^ 3 * #A := small_pow_of_small_tripling (by omega) hA hAsymm
have hA₀ : A.Nonempty := ⟨1, hA₁⟩
obtain ⟨F, -, hF, hAF⟩ := ruzsa_covering_mul hA₀ hA
exact ⟨F, hF, by norm_cast; simpa [div_eq_mul_inv, pow_succ, mul_assoc, hAsymm] using hAF⟩
open Set in
@[to_additive]
lemma pow_inter_pow_covBySMul_sq_inter_sq
(hA : IsApproximateSubgroup K A) (hB : IsApproximateSubgroup L B) (hm : 2 ≤ m) (hn : 2 ≤ n) :
CovBySMul G (K ^ (m - 1) * L ^ (n - 1)) (A ^ m ∩ B ^ n) (A ^ 2 ∩ B ^ 2) := by
classical
obtain ⟨F₁, hF₁, hAF₁⟩ := hA.sq_covBySMul
obtain ⟨F₂, hF₂, hBF₂⟩ := hB.sq_covBySMul
have := hA.one_le
choose f hf using exists_smul_inter_smul_subset_smul_inv_mul_inter_inv_mul A B
refine ⟨.image₂ f (F₁ ^ (m - 1)) (F₂ ^ (n - 1)), ?_, ?_⟩
· calc
(#(.image₂ f (F₁ ^ (m - 1)) (F₂ ^ (n - 1))) : ℝ)
_ ≤ #(F₁ ^ (m - 1)) * #(F₂ ^ (n - 1)) := mod_cast Finset.card_image₂_le ..
_ ≤ #F₁ ^ (m - 1) * #F₂ ^ (n - 1) := by gcongr <;> exact mod_cast Finset.card_pow_le
_ ≤ K ^ (m - 1) * L ^ (n - 1) := by gcongr
· calc
A ^ m ∩ B ^ n ⊆ (F₁ ^ (m - 1) * A) ∩ (F₂ ^ (n - 1) * B) := by
gcongr <;> apply pow_subset_pow_mul_of_sq_subset_mul <;> norm_cast <;> omega
_ = ⋃ (a ∈ F₁ ^ (m - 1)) (b ∈ F₂ ^ (n - 1)), a • A ∩ b • B := by
simp_rw [← smul_eq_mul, ← iUnion_smul_set, iUnion₂_inter_iUnion₂]; norm_cast
_ ⊆ ⋃ (a ∈ F₁ ^ (m - 1)) (b ∈ F₂ ^ (n - 1)), f a b • (A⁻¹ * A ∩ (B⁻¹ * B)) := by
gcongr; exact hf ..
_ = (Finset.image₂ f (F₁ ^ (m - 1)) (F₂ ^ (n - 1))) * (A ^ 2 ∩ B ^ 2) := by
simp_rw [hA.inv_eq_self, hB.inv_eq_self, ← sq]
rw [Finset.coe_image₂, ← smul_eq_mul, ← iUnion_smul_set, biUnion_image2]
simp_rw [Finset.mem_coe]
open Set in
@[to_additive]
lemma pow_inter_pow (hA : IsApproximateSubgroup K A) (hB : IsApproximateSubgroup L B) (hm : 2 ≤ m)
(hn : 2 ≤ n) :
IsApproximateSubgroup (K ^ (2 * m - 1) * L ^ (2 * n - 1)) (A ^ m ∩ B ^ n) where
one_mem := ⟨Set.one_mem_pow hA.one_mem, Set.one_mem_pow hB.one_mem⟩
inv_eq_self := by simp_rw [inter_inv, ← inv_pow, hA.inv_eq_self, hB.inv_eq_self]
sq_covBySMul := by
refine (hA.pow_inter_pow_covBySMul_sq_inter_sq hB (by omega) (by omega)).subset ?_
(by gcongr; exacts [hA.one_mem, hB.one_mem])
calc
(A ^ m ∩ B ^ n) ^ 2 ⊆ (A ^ m) ^ 2 ∩ (B ^ n) ^ 2 := Set.inter_pow_subset
_ = A ^ (2 * m) ∩ B ^ (2 * n) := by simp [pow_mul']
end IsApproximateSubgroup
open Set in
/-- A `1`-approximate subgroup is the same thing as a subgroup. -/
@[to_additive (attr := simp)
/-- A `1`-approximate subgroup is the same thing as a subgroup. -/]
lemma isApproximateSubgroup_one {A : Set G} :
IsApproximateSubgroup 1 (A : Set G) ↔ ∃ H : Subgroup G, H = A where
mp hA := by
suffices A * A ⊆ A from
let H : Subgroup G :=
{ carrier := A
one_mem' := hA.one_mem
inv_mem' hx := by rwa [← hA.inv_eq_self, inv_mem_inv]
mul_mem' hx hy := this (mul_mem_mul hx hy) }
⟨H, rfl⟩
obtain ⟨x, hx⟩ : ∃ x : G, A * A ⊆ x • A := by
obtain ⟨K, hK, hKA⟩ := hA.sq_covBySMul
simp only [Nat.cast_le_one, Finset.card_le_one_iff_subset_singleton,
Finset.subset_singleton_iff] at hK
obtain ⟨x, rfl | rfl⟩ := hK
· simp [hA.nonempty.ne_empty] at hKA
· rw [Finset.coe_singleton, singleton_smul, sq] at hKA
use x
have hx' : x ⁻¹ • (A * A) ⊆ A := by rwa [← subset_smul_set_iff]
have hx_inv : x⁻¹ ∈ A := by
simpa using hx' (smul_mem_smul_set (mul_mem_mul hA.one_mem hA.one_mem))
have hx_sq : x * x ∈ A := by
rw [← hA.inv_eq_self]
simpa using hx' (smul_mem_smul_set (mul_mem_mul hx_inv hA.one_mem))
calc A * A ⊆ x • A := by assumption
_ = x⁻¹ • (x * x) • A := by simp [smul_smul]
_ ⊆ x⁻¹ • (A • A) := smul_set_mono (smul_set_subset_smul hx_sq)
_ ⊆ A := hx'
mpr := by rintro ⟨H, rfl⟩; exact .subgroup |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/DoublingConst.lean | import Mathlib.Combinatorics.Additive.PluenneckeRuzsa
import Mathlib.Data.Finset.Density
/-!
# Doubling and difference constants
This file defines the doubling and difference constants of two finsets in a group.
-/
open Finset
open scoped Pointwise
namespace Finset
section Group
variable {G G' : Type*} [Group G] [AddGroup G'] [DecidableEq G] [DecidableEq G'] {A B : Finset G}
/-- The doubling constant `σₘ[A, B]` of two finsets `A` and `B` in a group is `|A * B| / |A|`.
The notation `σₘ[A, B]` is available in scope `Combinatorics.Additive`. -/
@[to_additive
/-- The doubling constant `σ[A, B]` of two finsets `A` and `B` in a group is `|A + B| / |A|`.
The notation `σ[A, B]` is available in scope `Combinatorics.Additive`. -/]
def mulConst (A B : Finset G) : ℚ≥0 := #(A * B) / #A
/-- The difference constant `δₘ[A, B]` of two finsets `A` and `B` in a group is `|A / B| / |A|`.
The notation `δₘ[A, B]` is available in scope `Combinatorics.Additive`. -/
@[to_additive
/-- The difference constant `σ[A, B]` of two finsets `A` and `B` in a group is `|A - B| / |A|`.
The notation `δ[A, B]` is available in scope `Combinatorics.Additive`. -/]
def divConst (A B : Finset G) : ℚ≥0 := #(A / B) / #A
/-- The doubling constant `σₘ[A, B]` of two finsets `A` and `B` in a group is `|A * B| / |A|`. -/
scoped[Combinatorics.Additive] notation3:max "σₘ[" A ", " B "]" => Finset.mulConst A B
/-- The doubling constant `σₘ[A]` of a finset `A` in a group is `|A * A| / |A|`. -/
scoped[Combinatorics.Additive] notation3:max "σₘ[" A "]" => Finset.mulConst A A
/-- The doubling constant `σ[A, B]` of two finsets `A` and `B` in a group is `|A + B| / |A|`. -/
scoped[Combinatorics.Additive] notation3:max "σ[" A ", " B "]" => Finset.addConst A B
/-- The doubling constant `σ[A]` of a finset `A` in a group is `|A + A| / |A|`. -/
scoped[Combinatorics.Additive] notation3:max "σ[" A "]" => Finset.addConst A A
/-- The difference constant `σₘ[A, B]` of two finsets `A` and `B` in a group is `|A / B| / |A|`. -/
scoped[Combinatorics.Additive] notation3:max "δₘ[" A ", " B "]" => Finset.divConst A B
/-- The difference constant `σₘ[A]` of a finset `A` in a group is `|A / A| / |A|`. -/
scoped[Combinatorics.Additive] notation3:max "δₘ[" A "]" => Finset.divConst A A
/-- The difference constant `σ[A, B]` of two finsets `A` and `B` in a group is `|A - B| / |A|`. -/
scoped[Combinatorics.Additive] notation3:max "δ[" A ", " B "]" => Finset.subConst A B
/-- The difference constant `σ[A]` of a finset `A` in a group is `|A - A| / |A|`. -/
scoped[Combinatorics.Additive] notation3:max "δ[" A "]" => Finset.subConst A A
open scoped Combinatorics.Additive
@[to_additive (attr := simp) addConst_mul_card]
lemma mulConst_mul_card (A B : Finset G) : σₘ[A, B] * #A = #(A * B) := by
obtain rfl | hA := A.eq_empty_or_nonempty
· simp
· exact div_mul_cancel₀ _ (by positivity)
@[to_additive (attr := simp) subConst_mul_card]
lemma divConst_mul_card (A B : Finset G) : δₘ[A, B] * #A = #(A / B) := by
obtain rfl | hA := A.eq_empty_or_nonempty
· simp
· exact div_mul_cancel₀ _ (by positivity)
@[to_additive (attr := simp) card_mul_addConst]
lemma card_mul_mulConst (A B : Finset G) : #A * σₘ[A, B] = #(A * B) := by
rw [mul_comm, mulConst_mul_card]
@[to_additive (attr := simp) card_mul_subConst]
lemma card_mul_divConst (A B : Finset G) : #A * δₘ[A, B] = #(A / B) := by
rw [mul_comm, divConst_mul_card]
@[to_additive (attr := simp)]
lemma mulConst_empty_left (B : Finset G) : σₘ[∅, B] = 0 := by simp [mulConst]
@[to_additive (attr := simp)]
lemma divConst_empty_left (B : Finset G) : δₘ[∅, B] = 0 := by simp [divConst]
@[to_additive (attr := simp)]
lemma mulConst_empty_right (A : Finset G) : σₘ[A, ∅] = 0 := by simp [mulConst]
@[to_additive (attr := simp)]
lemma divConst_empty_right (A : Finset G) : δₘ[A, ∅] = 0 := by simp [divConst]
@[to_additive (attr := simp)]
lemma mulConst_inv_right (A B : Finset G) : σₘ[A, B⁻¹] = δₘ[A, B] := by
rw [mulConst, divConst, ← div_eq_mul_inv]
@[to_additive (attr := simp)]
lemma divConst_inv_right (A B : Finset G) : δₘ[A, B⁻¹] = σₘ[A, B] := by
rw [mulConst, divConst, div_inv_eq_mul]
@[to_additive]
lemma one_le_mulConst (hA : A.Nonempty) (hB : B.Nonempty) : 1 ≤ σₘ[A, B] := by
rw [mulConst, one_le_div₀]
· exact mod_cast card_le_card_mul_right hB
· simpa
@[to_additive]
lemma one_le_mulConst_self (hA : A.Nonempty) : 1 ≤ σₘ[A] := one_le_mulConst hA hA
@[to_additive]
lemma one_le_divConst (hA : A.Nonempty) (hB : B.Nonempty) : 1 ≤ δₘ[A, B] := by
rw [← mulConst_inv_right]
apply one_le_mulConst hA (by simpa)
@[to_additive]
lemma one_le_divConst_self (hA : A.Nonempty) : 1 ≤ δₘ[A] := one_le_divConst hA hA
@[to_additive]
lemma mulConst_le_card : σₘ[A, B] ≤ #B := by
obtain rfl | hA' := A.eq_empty_or_nonempty
· simp
rw [mulConst, div_le_iff₀' (by positivity)]
exact mod_cast card_mul_le
@[to_additive]
lemma divConst_le_card : δₘ[A, B] ≤ #B := by
obtain rfl | hA' := A.eq_empty_or_nonempty
· simp
rw [divConst, div_le_iff₀' (by positivity)]
exact mod_cast card_div_le
section Fintype
variable [Fintype G]
/-- Dense sets have small doubling. -/
@[to_additive addConst_le_inv_dens /-- Dense sets have small doubling. -/]
lemma mulConst_le_inv_dens : σₘ[A, B] ≤ A.dens⁻¹ := by
rw [dens, inv_div, mulConst]; gcongr; exact card_le_univ _
/-- Dense sets have small difference constant. -/
@[to_additive subConst_le_inv_dens /-- Dense sets have small difference constant. -/]
lemma divConst_le_inv_dens : δₘ[A, B] ≤ A.dens⁻¹ := by
rw [dens, inv_div, divConst]; gcongr; exact card_le_univ _
end Fintype
variable {𝕜 : Type*} [Semifield 𝕜] [CharZero 𝕜]
-- we can't use `to_additive`, because it tries to translate `/` to `-`
lemma cast_addConst (A B : Finset G') : (σ[A, B] : 𝕜) = #(A + B) / #A := by
simp [addConst]
lemma cast_subConst (A B : Finset G') : (δ[A, B] : 𝕜) = #(A - B) / #A := by
simp [subConst]
lemma cast_mulConst (A B : Finset G) : (σₘ[A, B] : 𝕜) = #(A * B) / #A := by simp [mulConst]
lemma cast_divConst (A B : Finset G) : (δₘ[A, B] : 𝕜) = #(A / B) / #A := by simp [divConst]
lemma cast_addConst_mul_card (A B : Finset G') : (σ[A, B] * #A : 𝕜) = #(A + B) := by
norm_cast; exact addConst_mul_card _ _
lemma cast_subConst_mul_card (A B : Finset G') : (δ[A, B] * #A : 𝕜) = #(A - B) := by
norm_cast; exact subConst_mul_card _ _
lemma card_mul_cast_addConst (A B : Finset G') : (#A * σ[A, B] : 𝕜) = #(A + B) := by
norm_cast; exact card_mul_addConst _ _
lemma card_mul_cast_subConst (A B : Finset G') : (#A * δ[A, B] : 𝕜) = #(A - B) := by
norm_cast; exact card_mul_subConst _ _
@[simp]
lemma cast_mulConst_mul_card (A B : Finset G) : (σₘ[A, B] * #A : 𝕜) = #(A * B) := by
norm_cast; exact mulConst_mul_card _ _
@[simp]
lemma cast_divConst_mul_card (A B : Finset G) : (δₘ[A, B] * #A : 𝕜) = #(A / B) := by
norm_cast; exact divConst_mul_card _ _
@[simp]
lemma card_mul_cast_mulConst (A B : Finset G) : (#A * σₘ[A, B] : 𝕜) = #(A * B) := by
norm_cast; exact card_mul_mulConst _ _
@[simp]
lemma card_mul_cast_divConst (A B : Finset G) : (#A * δₘ[A, B] : 𝕜) = #(A / B) := by
norm_cast; exact card_mul_divConst _ _
/-- If `A` has small doubling, then it has small difference, with the constant squared.
This is a consequence of the Ruzsa triangle inequality. -/
@[to_additive
/-- If `A` has small doubling, then it has small difference, with the constant squared.
This is a consequence of the Ruzsa triangle inequality. -/]
lemma divConst_le_mulConst_sq : δₘ[A] ≤ σₘ[A] ^ 2 := by
obtain rfl | hA' := A.eq_empty_or_nonempty
· simp
refine le_of_mul_le_mul_right ?_ (by positivity : (0 : ℚ≥0) < #A * #A)
calc
_ = #(A / A) * (#A : ℚ≥0) := by rw [← mul_assoc, divConst_mul_card]
_ ≤ #(A * A) * #(A * A) := by norm_cast; exact ruzsa_triangle_inequality_div_mul_mul ..
_ = _ := by rw [← mulConst_mul_card]; ring
end Group
open scoped Combinatorics.Additive
section CommGroup
variable {G : Type*} [CommGroup G] [DecidableEq G] {A B : Finset G}
@[to_additive (attr := simp)]
lemma mulConst_inv_left (A B : Finset G) : σₘ[A⁻¹, B] = δₘ[A, B] := by
rw [mulConst, divConst, card_inv, ← card_inv, mul_inv_rev, inv_inv, inv_mul_eq_div]
@[to_additive (attr := simp)]
lemma divConst_inv_left (A B : Finset G) : δₘ[A⁻¹, B] = σₘ[A, B] := by
rw [mulConst, divConst, card_inv, ← card_inv, inv_div, div_inv_eq_mul, mul_comm]
/-- If `A` has small difference, then it has small doubling, with the constant squared.
This is a consequence of the Ruzsa triangle inequality. -/
@[to_additive
/-- If `A` has small difference, then it has small doubling, with the constant squared.
This is a consequence of the Ruzsa triangle inequality. -/]
lemma mulConst_le_divConst_sq : σₘ[A] ≤ δₘ[A] ^ 2 := by
obtain rfl | hA' := A.eq_empty_or_nonempty
· simp
refine le_of_mul_le_mul_right ?_ (by positivity : (0 : ℚ≥0) < #A * #A)
calc
_ = #(A * A) * (#A : ℚ≥0) := by rw [← mul_assoc, mulConst_mul_card]
_ ≤ #(A / A) * #(A / A) := by norm_cast; exact ruzsa_triangle_inequality_mul_div_div ..
_ = _ := by rw [← divConst_mul_card]; ring
end CommGroup
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/CovBySMul.lean | import Mathlib.Algebra.Group.Action.Pointwise.Set.Basic
import Mathlib.Algebra.Group.Pointwise.Finset.Scalar
import Mathlib.Data.Real.Basic
import Mathlib.Tactic.Positivity.Basic
/-!
# Relation of covering by cosets
This file defines a predicate for a set to be covered by at most `K` cosets of another set.
This is a fundamental relation to study in additive combinatorics.
-/
open scoped Finset Pointwise
variable {M N X : Type*} [Monoid M] [Monoid N] [MulAction M X] [MulAction N X] {K L : ℝ}
{A A₁ A₂ B B₁ B₂ C : Set X}
variable (M) in
/-- Predicate for a set `A` to be covered by at most `K` cosets of another set `B` under the action
by the monoid `M`. -/
@[to_additive /-- Predicate for a set `A` to be covered by at most `K` cosets of another set `B`
under the action by the monoid `M`. -/]
def CovBySMul (K : ℝ) (A B : Set X) : Prop := ∃ F : Finset M, #F ≤ K ∧ A ⊆ (F : Set M) • B
@[to_additive (attr := simp, refl)]
lemma CovBySMul.rfl : CovBySMul M 1 A A := ⟨1, by simp⟩
@[to_additive (attr := simp)]
lemma CovBySMul.of_subset (hAB : A ⊆ B) : CovBySMul M 1 A B := ⟨1, by simpa⟩
@[to_additive] lemma CovBySMul.nonneg : CovBySMul M K A B → 0 ≤ K := by
rintro ⟨F, hF, -⟩; exact (#F).cast_nonneg.trans hF
@[to_additive (attr := simp)]
lemma covBySMul_zero : CovBySMul M 0 A B ↔ A = ∅ := by simp [CovBySMul]
@[to_additive]
lemma CovBySMul.mono (hKL : K ≤ L) : CovBySMul M K A B → CovBySMul M L A B := by
rintro ⟨F, hF, hFAB⟩; exact ⟨F, hF.trans hKL, hFAB⟩
@[to_additive] lemma CovBySMul.trans [SMul M N] [IsScalarTower M N X]
(hAB : CovBySMul M K A B) (hBC : CovBySMul N L B C) : CovBySMul N (K * L) A C := by
classical
have := hAB.nonneg
obtain ⟨F₁, hF₁, hFAB⟩ := hAB
obtain ⟨F₂, hF₂, hFBC⟩ := hBC
refine ⟨F₁ • F₂, ?_, ?_⟩
· calc
(#(F₁ • F₂) : ℝ) ≤ #F₁ * #F₂ := mod_cast Finset.card_smul_le
_ ≤ K * L := by gcongr
· calc
A ⊆ (F₁ : Set M) • B := hFAB
_ ⊆ (F₁ : Set M) • (F₂ : Set N) • C := by gcongr
_ = (↑(F₁ • F₂) : Set N) • C := by simp
@[to_additive]
lemma CovBySMul.subset_left (hA : A₁ ⊆ A₂) (hAB : CovBySMul M K A₂ B) :
CovBySMul M K A₁ B := by simpa using (CovBySMul.of_subset (M := M) hA).trans hAB
@[to_additive]
lemma CovBySMul.subset_right (hB : B₁ ⊆ B₂) (hAB : CovBySMul M K A B₁) :
CovBySMul M K A B₂ := by simpa using hAB.trans (.of_subset (M := M) hB)
@[to_additive]
lemma CovBySMul.subset (hA : A₁ ⊆ A₂) (hB : B₁ ⊆ B₂) (hAB : CovBySMul M K A₂ B₁) :
CovBySMul M K A₁ B₂ := (hAB.subset_left hA).subset_right hB |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/Randomisation.lean | import Mathlib.Analysis.Fourier.FiniteAbelian.Orthogonality
import Mathlib.Combinatorics.Additive.Dissociation
/-!
# Randomising by a function of dissociated support
This file proves that a function from a finite abelian group can be randomised by a function of
dissociated support.
Precisely, for `G` a finite abelian group and two functions `c : AddChar G ℂ → ℝ` and
`d : AddChar G ℂ → ℝ` such that `{ψ | d ψ ≠ 0}` is dissociated, the product of the `c ψ` over `ψ` is
the same as the average over `a` of the product of the `c ψ + Re (d ψ * ψ a)`.
-/
open Finset
open scoped BigOperators ComplexConjugate
variable {G : Type*} [Fintype G] [AddCommGroup G] {p : ℕ}
/-- One can randomise by a function of dissociated support. -/
lemma AddDissociated.randomisation (c : AddChar G ℂ → ℝ) (d : AddChar G ℂ → ℂ)
(hcd : AddDissociated {ψ | d ψ ≠ 0}) : 𝔼 a, ∏ ψ, (c ψ + (d ψ * ψ a).re) = ∏ ψ, c ψ := by
refine Complex.ofReal_injective ?_
push_cast
calc
_ = ∑ t, (𝔼 a, ∏ ψ ∈ t, ((d ψ * ψ a) + conj (d ψ * ψ a)) / 2) * ∏ ψ ∈ tᶜ, (c ψ : ℂ) := by
simp_rw [expect_mul, ← expect_sum_comm, ← Fintype.prod_add, add_comm,
Complex.re_eq_add_conj]
_ = (𝔼 a, ∏ ψ ∈ ∅, ((d ψ * ψ a) + conj (d ψ * ψ a)) / 2) * ∏ ψ ∈ ∅ᶜ, (c ψ : ℂ) :=
Fintype.sum_eq_single ∅ fun t ht ↦ mul_eq_zero_of_left ?_ _
_ = ∏ ψ, (c ψ : ℂ) := by simp
simp only [map_mul, prod_div_distrib, prod_add, prod_const, ← expect_div, expect_sum_comm,
div_eq_zero_iff, pow_eq_zero_iff', OfNat.ofNat_ne_zero, ne_eq, card_eq_zero,
false_and, or_false]
refine sum_eq_zero fun u _ ↦ ?_
calc
𝔼 a, (∏ ψ ∈ u, d ψ * ψ a) * ∏ ψ ∈ t \ u, conj (d ψ) * conj (ψ a)
= ((∏ ψ ∈ u, d ψ) * ∏ ψ ∈ t \ u, conj (d ψ)) * 𝔼 a, (∑ ψ ∈ u, ψ - ∑ ψ ∈ t \ u, ψ) a := by
simp_rw [mul_expect, AddChar.sub_apply, AddChar.sum_apply, mul_mul_mul_comm,
← prod_mul_distrib, AddChar.map_neg_eq_conj]
_ = 0 := ?_
rw [mul_eq_zero, AddChar.expect_eq_zero_iff_ne_zero, sub_ne_zero, or_iff_not_imp_left, ← Ne,
mul_ne_zero_iff, prod_ne_zero_iff, prod_ne_zero_iff]
exact fun h ↦ hcd.ne h.1 (by simpa only [map_ne_zero] using h.2)
(sdiff_ne_right.2 <| .inl ht).symm |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/PluenneckeRuzsa.lean | import Mathlib.Algebra.Order.Field.Rat
import Mathlib.Combinatorics.Enumerative.DoubleCounting
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.GCongr
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.Ring
import Mathlib.Algebra.Group.Pointwise.Finset.Basic
/-!
# The Plünnecke-Ruzsa inequality
This file proves Ruzsa's triangle inequality, the Plünnecke-Petridis lemma, and the Plünnecke-Ruzsa
inequality.
## Main declarations
* `Finset.ruzsa_triangle_inequality_sub_sub_sub`: The Ruzsa triangle inequality, difference version.
* `Finset.ruzsa_triangle_inequality_add_add_add`: The Ruzsa triangle inequality, sum version.
* `Finset.pluennecke_petridis_inequality_add`: The Plünnecke-Petridis inequality.
* `Finset.pluennecke_ruzsa_inequality_nsmul_sub_nsmul_add`: The Plünnecke-Ruzsa inequality.
## References
* [Giorgis Petridis, *The Plünnecke-Ruzsa inequality: an overview*][petridis2014]
* [Terrence Tao, Van Vu, *Additive Combinatorics][tao-vu]
## See also
In general non-abelian groups, small doubling doesn't imply small powers anymore, but small tripling
does. See `Mathlib/Combinatorics/Additive/SmallTripling.lean`.
-/
open MulOpposite Nat
open scoped Pointwise
namespace Finset
variable {G : Type*} [DecidableEq G]
section Group
variable [Group G] {A B C : Finset G}
/-! ### Noncommutative Ruzsa triangle inequality -/
/-- **Ruzsa's triangle inequality**. Division version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Subtraction version. -/]
theorem ruzsa_triangle_inequality_div_div_div (A B C : Finset G) :
#(A / C) * #B ≤ #(A / B) * #(C / B) := by
rw [← card_product (A / B), ← mul_one #((A / B) ×ˢ (C / B))]
refine card_mul_le_card_mul (fun b (a, c) ↦ a / c = b) (fun x hx ↦ ?_)
fun x _ ↦ card_le_one_iff.2 fun hu hv ↦
((mem_bipartiteBelow _).1 hu).2.symm.trans ?_
· obtain ⟨a, ha, c, hc, rfl⟩ := mem_div.1 hx
refine card_le_card_of_injOn (fun b ↦ (a / b, c / b)) (fun b hb ↦ ?_) fun b₁ _ b₂ _ h ↦ ?_
· rw [mem_coe, mem_bipartiteAbove]
exact ⟨mk_mem_product (div_mem_div ha hb) (div_mem_div hc hb), div_div_div_cancel_right ..⟩
· exact div_right_injective (Prod.ext_iff.1 h).1
· exact ((mem_bipartiteBelow _).1 hv).2
/-- **Ruzsa's triangle inequality**. Mulinv-mulinv-mulinv version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Addneg-addneg-addneg version. -/]
theorem ruzsa_triangle_inequality_mulInv_mulInv_mulInv (A B C : Finset G) :
#(A * C⁻¹) * #B ≤ #(A * B⁻¹) * #(C * B⁻¹) := by
simpa [div_eq_mul_inv] using ruzsa_triangle_inequality_div_div_div A B C
/-- **Ruzsa's triangle inequality**. Invmul-invmul-invmul version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Negadd-negadd-negadd version. -/]
theorem ruzsa_triangle_inequality_invMul_invMul_invMul (A B C : Finset G) :
#B * #(A⁻¹ * C) ≤ #(B⁻¹ * A) * #(B⁻¹ * C) := by
simpa [mul_comm, div_eq_mul_inv, ← map_op_mul, ← map_op_inv] using
ruzsa_triangle_inequality_div_div_div (G := Gᵐᵒᵖ) (C.map opEquiv.toEmbedding)
(B.map opEquiv.toEmbedding) (A.map opEquiv.toEmbedding)
/-- **Ruzsa's triangle inequality**. Div-mul-mul version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Sub-add-add version. -/]
theorem ruzsa_triangle_inequality_div_mul_mul (A B C : Finset G) :
#(A / C) * #B ≤ #(A * B) * #(C * B) := by
simpa using ruzsa_triangle_inequality_div_div_div A B⁻¹ C
/-- **Ruzsa's triangle inequality**. Mulinv-mul-mul version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Addneg-add-add version. -/]
theorem ruzsa_triangle_inequality_mulInv_mul_mul (A B C : Finset G) :
#(A * C⁻¹) * #B ≤ #(A * B) * #(C * B) := by
simpa using ruzsa_triangle_inequality_mulInv_mulInv_mulInv A B⁻¹ C
/-- **Ruzsa's triangle inequality**. Invmul-mul-mul version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Negadd-add-add version. -/]
theorem ruzsa_triangle_inequality_invMul_mul_mul (A B C : Finset G) :
#B * #(A⁻¹ * C) ≤ #(B * A) * #(B * C) := by
simpa using ruzsa_triangle_inequality_invMul_invMul_invMul A B⁻¹ C
/-- **Ruzsa's triangle inequality**. Mul-div-mul version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Add-sub-add version. -/]
theorem ruzsa_triangle_inequality_mul_div_mul (A B C : Finset G) :
#B * #(A * C) ≤ #(B / A) * #(B * C) := by
simpa [div_eq_mul_inv] using ruzsa_triangle_inequality_invMul_mul_mul A⁻¹ B C
/-- **Ruzsa's triangle inequality**. Mul-mulinv-mul version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Add-addneg-add version. -/]
theorem ruzsa_triangle_inequality_mul_mulInv_mul (A B C : Finset G) :
#B * #(A * C) ≤ #(B * A⁻¹) * #(B * C) := by
simpa [div_eq_mul_inv] using ruzsa_triangle_inequality_mul_div_mul A B C
/-- **Ruzsa's triangle inequality**. Mul-mul-invmul version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Add-add-negadd version. -/]
theorem ruzsa_triangle_inequality_mul_mul_invMul (A B C : Finset G) :
#(A * C) * #B ≤ #(A * B) * #(C⁻¹ * B) := by
simpa using ruzsa_triangle_inequality_mulInv_mul_mul A B C⁻¹
/-! ### Plünnecke-Petridis inequality -/
@[to_additive]
theorem pluennecke_petridis_inequality_mul (C : Finset G)
(hA : ∀ A' ⊆ A, #(A * B) * #A' ≤ #(A' * B) * #A) :
#(C * A * B) * #A ≤ #(A * B) * #(C * A) := by
induction C using Finset.induction_on with
| empty => simp
| insert x C _ ih =>
set A' := A ∩ ({x}⁻¹ * C * A) with hA'
set C' := insert x C with hC'
have h₀ : {x} * A' = {x} * A ∩ (C * A) := by
rw [hA', mul_assoc, singleton_mul_inter, (isUnit_singleton x).mul_inv_cancel_left]
have h₁ : C' * A * B = C * A * B ∪ ({x} * A * B) \ ({x} * A' * B) := by
rw [hC', insert_eq, union_comm, union_mul, union_mul]
refine (sup_sdiff_eq_sup ?_).symm
rw [h₀]
gcongr
exact inter_subset_right
have h₂ : {x} * A' * B ⊆ {x} * A * B := by gcongr; exact inter_subset_left
have h₃ : #(C' * A * B) ≤ #(C * A * B) + #(A * B) - #(A' * B) := by
rw [h₁]
refine (card_union_le _ _).trans_eq ?_
rw [card_sdiff_of_subset h₂, ← add_tsub_assoc_of_le (card_le_card h₂), mul_assoc {_},
mul_assoc {_}, card_singleton_mul, card_singleton_mul]
refine (mul_le_mul_right' h₃ _).trans ?_
rw [tsub_mul, add_mul]
refine (tsub_le_tsub (add_le_add_right ih _) <| hA _ inter_subset_left).trans_eq ?_
rw [← mul_add, ← mul_tsub, ← hA', hC', insert_eq, union_mul, ← card_singleton_mul x A, ←
card_singleton_mul x A', add_comm #_, h₀, eq_tsub_of_add_eq (card_union_add_card_inter _ _)]
end Group
section CommGroup
variable [CommGroup G] {A B C : Finset G}
/-! ### Commutative Ruzsa triangle inequality -/
-- Auxiliary lemma for Ruzsa's triangle sum inequality, and the Plünnecke-Ruzsa inequality.
@[to_additive]
private theorem mul_aux (hA : A.Nonempty) (hAB : A ⊆ B)
(h : ∀ A' ∈ B.powerset.erase ∅, (#(A * C) : ℚ≥0) / #A ≤ #(A' * C) / #A') :
∀ A' ⊆ A, #(A * C) * #A' ≤ #(A' * C) * #A := by
rintro A' hAA'
obtain rfl | hA' := A'.eq_empty_or_nonempty
· simp
have hA₀ : (0 : ℚ≥0) < #A := cast_pos.2 hA.card_pos
have hA₀' : (0 : ℚ≥0) < #A' := cast_pos.2 hA'.card_pos
exact mod_cast
(div_le_div_iff₀ hA₀ hA₀').1
(h _ <| mem_erase_of_ne_of_mem hA'.ne_empty <| mem_powerset.2 <| hAA'.trans hAB)
/-- **Ruzsa's triangle inequality**. Multiplication version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Addition version. -/]
theorem ruzsa_triangle_inequality_mul_mul_mul (A B C : Finset G) :
#(A * C) * #B ≤ #(A * B) * #(B * C) := by
obtain rfl | hB := B.eq_empty_or_nonempty
· simp
have hB' : B ∈ B.powerset.erase ∅ := mem_erase_of_ne_of_mem hB.ne_empty (mem_powerset_self _)
obtain ⟨U, hU, hUA⟩ :=
exists_min_image (B.powerset.erase ∅) (fun U ↦ #(U * A) / #U : _ → ℚ≥0) ⟨B, hB'⟩
rw [mem_erase, mem_powerset, ← nonempty_iff_ne_empty] at hU
refine cast_le.1 (?_ : (_ : ℚ≥0) ≤ _)
push_cast
rw [← le_div_iff₀ (cast_pos.2 hB.card_pos), mul_div_right_comm, mul_comm _ B]
refine (Nat.cast_le.2 <| card_le_card_mul_left hU.1).trans ?_
refine le_trans ?_
(mul_le_mul (hUA _ hB') (cast_le.2 <| card_le_card <| mul_subset_mul_right hU.2)
(zero_le _) (zero_le _))
rw [← mul_div_right_comm, ← mul_assoc, le_div_iff₀ (cast_pos.2 hU.1.card_pos), mul_comm _ C,
← mul_assoc, mul_comm _ C]
exact mod_cast pluennecke_petridis_inequality_mul C (mul_aux hU.1 hU.2 hUA)
/-- **Ruzsa's triangle inequality**. Mul-div-div version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Add-sub-sub version. -/]
theorem ruzsa_triangle_inequality_mul_div_div (A B C : Finset G) :
#(A * C) * #B ≤ #(A / B) * #(B / C) := by
rw [div_eq_mul_inv, ← card_inv B, ← card_inv (B / C), inv_div', div_inv_eq_mul]
exact ruzsa_triangle_inequality_mul_mul_mul _ _ _
/-- **Ruzsa's triangle inequality**. Div-mul-div version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Sub-add-sub version. -/]
theorem ruzsa_triangle_inequality_div_mul_div (A B C : Finset G) :
#(A / C) * #B ≤ #(A * B) * #(B / C) := by
rw [div_eq_mul_inv, div_eq_mul_inv]
exact ruzsa_triangle_inequality_mul_mul_mul _ _ _
/-- **Ruzsa's triangle inequality**. Div-div-mul version. -/
@[to_additive /-- **Ruzsa's triangle inequality**. Sub-sub-add version. -/]
theorem card_div_mul_le_card_div_mul_card_mul (A B C : Finset G) :
#(A / C) * #B ≤ #(A / B) * #(B * C) := by
rw [← div_inv_eq_mul, div_eq_mul_inv]
exact ruzsa_triangle_inequality_mul_div_div _ _ _
-- Auxiliary lemma towards the Plünnecke-Ruzsa inequality
@[to_additive]
private lemma card_mul_pow_le (hAB : ∀ A' ⊆ A, #(A * B) * #A' ≤ #(A' * B) * #A) (n : ℕ) :
#(A * B ^ n) ≤ (#(A * B) / #A : ℚ≥0) ^ n * #A := by
obtain rfl | hA := A.eq_empty_or_nonempty
· simp
induction n with
| zero => simp
| succ n ih =>
refine le_of_mul_le_mul_right ?_ (by positivity : (0 : ℚ≥0) < #A)
calc
((#(A * B ^ (n + 1))) * #A : ℚ≥0)
= #(B ^ n * A * B) * #A := by rw [pow_succ, mul_left_comm, mul_assoc]
_ ≤ #(A * B) * #(B ^ n * A) := mod_cast pluennecke_petridis_inequality_mul _ hAB
_ ≤ #(A * B) * ((#(A * B) / #A) ^ n * #A) := by rw [mul_comm _ A]; gcongr
_ = (#(A * B) / #A) ^ (n + 1) * #A * #A := by simp [field, pow_add]
/-- The **Plünnecke-Ruzsa inequality**. Multiplication version. Note that this is genuinely harder
than the division version because we cannot use a double counting argument. -/
@[to_additive /-- The **Plünnecke-Ruzsa inequality**. Addition version. Note that this is genuinely
harder than the subtraction version because we cannot use a double counting argument. -/]
theorem pluennecke_ruzsa_inequality_pow_div_pow_mul (hA : A.Nonempty) (B : Finset G) (m n : ℕ) :
#(B ^ m / B ^ n) ≤ (#(A * B) / #A : ℚ≥0) ^ (m + n) * #A := by
have hA' : A ∈ A.powerset.erase ∅ := mem_erase_of_ne_of_mem hA.ne_empty (mem_powerset_self _)
obtain ⟨C, hC, hCmin⟩ :=
exists_min_image (A.powerset.erase ∅) (fun C ↦ #(C * B) / #C : _ → ℚ≥0) ⟨A, hA'⟩
rw [mem_erase, mem_powerset, ← nonempty_iff_ne_empty] at hC
obtain ⟨hC, hCA⟩ := hC
refine le_of_mul_le_mul_right ?_ (by positivity : (0 : ℚ≥0) < #C)
calc
(#(B ^ m / B ^ n) * #C : ℚ≥0)
≤ #(B ^ m * C) * #(B ^ n * C) := mod_cast ruzsa_triangle_inequality_div_mul_mul ..
_ = #(C * B ^ m) * #(C * B ^ n) := by simp_rw [mul_comm]
_ ≤ ((#(C * B) / #C) ^ m * #C) * ((#(C * B) / #C : ℚ≥0) ^ n * #C) := by
gcongr <;> exact card_mul_pow_le (mul_aux hC hCA hCmin) _
_ = (#(C * B) / #C) ^ (m + n) * #C * #C := by ring
_ ≤ (#(A * B) / #A) ^ (m + n) * #A * #C := by gcongr (?_ ^ _) * #?_ * _; exact hCmin _ hA'
/-- The **Plünnecke-Ruzsa inequality**. Division version. -/
@[to_additive /-- The **Plünnecke-Ruzsa inequality**. Subtraction version. -/]
theorem pluennecke_ruzsa_inequality_pow_div_pow_div (hA : A.Nonempty) (B : Finset G) (m n : ℕ) :
#(B ^ m / B ^ n) ≤ (#(A / B) / #A : ℚ≥0) ^ (m + n) * #A := by
rw [← card_inv, inv_div', ← inv_pow, ← inv_pow, div_eq_mul_inv A]
exact pluennecke_ruzsa_inequality_pow_div_pow_mul hA _ _ _
/-- Special case of the **Plünnecke-Ruzsa inequality**. Multiplication version. -/
@[to_additive /-- Special case of the **Plünnecke-Ruzsa inequality**. Addition version. -/]
theorem pluennecke_ruzsa_inequality_pow_mul (hA : A.Nonempty) (B : Finset G) (n : ℕ) :
#(B ^ n) ≤ (#(A * B) / #A : ℚ≥0) ^ n * #A := by
simpa only [_root_.pow_zero, div_one] using pluennecke_ruzsa_inequality_pow_div_pow_mul hA _ _ 0
/-- Special case of the **Plünnecke-Ruzsa inequality**. Division version. -/
@[to_additive /-- Special case of the **Plünnecke-Ruzsa inequality**. Subtraction version. -/]
theorem pluennecke_ruzsa_inequality_pow_div (hA : A.Nonempty) (B : Finset G) (n : ℕ) :
#(B ^ n) ≤ (#(A / B) / #A : ℚ≥0) ^ n * #A := by
simpa only [_root_.pow_zero, div_one] using pluennecke_ruzsa_inequality_pow_div_pow_div hA _ _ 0
end CommGroup
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/ErdosGinzburgZiv.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Data.Multiset.Fintype
import Mathlib.FieldTheory.ChevalleyWarning
/-!
# The Erdős–Ginzburg–Ziv theorem
This file proves the Erdős–Ginzburg–Ziv theorem as a corollary of Chevalley-Warning. This theorem
states that among any (not necessarily distinct) `2 * n - 1` elements of `ZMod n`, we can find `n`
elements of sum zero.
## Main declarations
* `Int.erdos_ginzburg_ziv`: The Erdős–Ginzburg–Ziv theorem stated using sequences in `ℤ`
* `ZMod.erdos_ginzburg_ziv`: The Erdős–Ginzburg–Ziv theorem stated using sequences in `ZMod n`
-/
open Finset MvPolynomial
variable {ι : Type*}
section prime
variable {p : ℕ} [Fact p.Prime] {s : Finset ι}
set_option linter.unusedVariables false in
/-- The first multivariate polynomial used in the proof of Erdős–Ginzburg–Ziv. -/
private noncomputable def f₁ (s : Finset ι) (a : ι → ZMod p) : MvPolynomial s (ZMod p) :=
∑ i, X i ^ (p - 1)
/-- The second multivariate polynomial used in the proof of Erdős–Ginzburg–Ziv. -/
private noncomputable def f₂ (s : Finset ι) (a : ι → ZMod p) : MvPolynomial s (ZMod p) :=
∑ i : s, a i • X i ^ (p - 1)
private lemma totalDegree_f₁_add_totalDegree_f₂ {a : ι → ZMod p} :
(f₁ s a).totalDegree + (f₂ s a).totalDegree < 2 * p - 1 := by
calc
_ ≤ (p - 1) + (p - 1) := by
gcongr <;> apply totalDegree_finsetSum_le <;> rintro i _
· exact (totalDegree_X_pow ..).le
· exact (totalDegree_smul_le ..).trans (totalDegree_X_pow ..).le
_ < 2 * p - 1 := by have := (Fact.out : p.Prime).two_le; cutsat
/-- The prime case of the **Erdős–Ginzburg–Ziv theorem** for `ℤ/pℤ`.
Any sequence of `2 * p - 1` elements of `ZMod p` contains a subsequence of `p` elements whose sum is
zero. -/
private theorem ZMod.erdos_ginzburg_ziv_prime (a : ι → ZMod p) (hs : #s = 2 * p - 1) :
∃ t ⊆ s, #t = p ∧ ∑ i ∈ t, a i = 0 := by
haveI : NeZero p := inferInstance
classical
-- Let `N` be the number of common roots of our polynomials `f₁` and `f₂` (`f s ff` and `f s tt`).
set N := Fintype.card {x // eval x (f₁ s a) = 0 ∧ eval x (f₂ s a) = 0}
-- Zero is a common root to `f₁` and `f₂`, so `N` is nonzero
let zero_sol : {x // eval x (f₁ s a) = 0 ∧ eval x (f₂ s a) = 0} :=
⟨0, by simp [f₁, f₂, map_sum, (Fact.out : p.Prime).one_lt, tsub_eq_zero_iff_le]⟩
have hN₀ : 0 < N := @Fintype.card_pos _ _ ⟨zero_sol⟩
have hs' : 2 * p - 1 = Fintype.card s := by simp [hs]
-- Chevalley-Warning gives us that `p ∣ n` because the total degrees of `f₁` and `f₂` are at most
-- `p - 1`, and we have `2 * p - 1 > 2 * (p - 1)` variables.
have hpN : p ∣ N := char_dvd_card_solutions_of_add_lt p
(totalDegree_f₁_add_totalDegree_f₂.trans_eq hs')
-- Hence, `2 ≤ p ≤ N` and we can make a common root `x ≠ 0`.
obtain ⟨x, hx⟩ := Fintype.exists_ne_of_one_lt_card ((Fact.out : p.Prime).one_lt.trans_le <|
Nat.le_of_dvd hN₀ hpN) zero_sol
-- This common root gives us the required subsequence, namely the `i ∈ s` such that `x i ≠ 0`.
refine ⟨({a | x.1 a ≠ 0} : Finset _).map ⟨(↑), Subtype.val_injective⟩, ?_, ?_, ?_⟩
· simp +contextual [subset_iff]
-- From `f₁ x = 0`, we get that `p` divides the number of `a` such that `x a ≠ 0`.
· rw [card_map]
refine Nat.eq_of_dvd_of_lt_two_mul (Finset.card_pos.2 ?_).ne' ?_ <|
(Finset.card_filter_le _ _).trans_lt ?_
-- This number is nonzero because `x ≠ 0`.
· rw [← Subtype.coe_ne_coe, Function.ne_iff] at hx
exact hx.imp (fun a ha ↦ mem_filter.2 ⟨Finset.mem_attach _ _, ha⟩)
· rw [← CharP.cast_eq_zero_iff (ZMod p), ← Finset.sum_boole]
simpa only [f₁, map_sum, ZMod.pow_card_sub_one, map_pow, eval_X] using x.2.1
-- And it is at most `2 * p - 1`, so it must be `p`.
· rw [univ_eq_attach, card_attach, hs]
exact tsub_lt_self (mul_pos zero_lt_two (Fact.out : p.Prime).pos) zero_lt_one
-- From `f₂ x = 0`, we get that `p` divides the sum of the `a ∈ s` such that `x a ≠ 0`.
· simpa [f₂, ZMod.pow_card_sub_one, Finset.sum_filter] using x.2.2
/-- The prime case of the **Erdős–Ginzburg–Ziv theorem** for `ℤ`.
Any sequence of `2 * p - 1` elements of `ℤ` contains a subsequence of `p` elements whose sum is
divisible by `p`. -/
private theorem Int.erdos_ginzburg_ziv_prime (a : ι → ℤ) (hs : #s = 2 * p - 1) :
∃ t ⊆ s, #t = p ∧ ↑p ∣ ∑ i ∈ t, a i := by
simpa [← Int.cast_sum, ZMod.intCast_zmod_eq_zero_iff_dvd]
using ZMod.erdos_ginzburg_ziv_prime (Int.cast ∘ a) hs
end prime
section composite
variable {n : ℕ} {s : Finset ι}
/-- The **Erdős–Ginzburg–Ziv theorem** for `ℤ`.
Any sequence of at least `2 * n - 1` elements of `ℤ` contains a subsequence of `n` elements whose
sum is divisible by `n`. -/
theorem Int.erdos_ginzburg_ziv (a : ι → ℤ) (hs : 2 * n - 1 ≤ #s) :
∃ t ⊆ s, #t = n ∧ ↑n ∣ ∑ i ∈ t, a i := by
classical
-- Do induction on the prime factorisation of `n`. Note that we will apply the induction
-- hypothesis with `ι := Finset ι`, so we need to generalise.
induction n using Nat.prime_composite_induction generalizing ι with
-- When `n := 0`, we can set `t := ∅`.
| zero => exact ⟨∅, by simp⟩
-- When `n := 1`, we can take `t` to be any subset of `s` of size `2 * n - 1`.
| one => simpa using exists_subset_card_eq hs
-- When `n := p` is prime, we use the prime case `Int.erdos_ginzburg_ziv_prime`.
| prime p hp =>
haveI := Fact.mk hp
obtain ⟨t, hts, ht⟩ := exists_subset_card_eq hs
obtain ⟨u, hut, hu⟩ := Int.erdos_ginzburg_ziv_prime a ht
exact ⟨u, hut.trans hts, hu⟩
-- When `n := m * n` is composite, we pick (by induction hypothesis on `n`) `2 * m - 1` sets of
-- size `n` and sums divisible by `n`. Then by induction hypothesis (on `m`) we can pick `m` of
-- these sets whose sum is divisible by `m * n`.
| composite m hm ihm n hn ihn =>
-- First, show that it is enough to have those `2 * m - 1` sets.
suffices ∀ k ≤ 2 * m - 1, ∃ 𝒜 : Finset (Finset ι), #𝒜 = k ∧
(𝒜 : Set (Finset ι)).Pairwise _root_.Disjoint ∧
∀ ⦃t⦄, t ∈ 𝒜 → t ⊆ s ∧ #t = n ∧ ↑n ∣ ∑ i ∈ t, a i by
-- Assume `𝒜` is a family of `2 * m - 1` sets, each of size `n` and sum divisible by `n`.
obtain ⟨𝒜, h𝒜card, h𝒜disj, h𝒜⟩ := this _ le_rfl
-- By induction hypothesis on `m`, find a subfamily `ℬ` of size `m` such that the sum over
-- `t ∈ ℬ` of `(∑ i ∈ t, a i) / n` is divisible by `m`.
obtain ⟨ℬ, hℬ𝒜, hℬcard, hℬ⟩ := ihm (fun t ↦ (∑ i ∈ t, a i) / n) h𝒜card.ge
-- We are done.
refine ⟨ℬ.biUnion fun x ↦ x, biUnion_subset.2 fun t ht ↦ (h𝒜 <| hℬ𝒜 ht).1, ?_, ?_⟩
· rw [card_biUnion (h𝒜disj.mono hℬ𝒜), sum_const_nat fun t ht ↦ (h𝒜 <| hℬ𝒜 ht).2.1, hℬcard]
rwa [sum_biUnion, Int.natCast_mul, mul_comm, ← Int.dvd_div_iff_mul_dvd, Int.sum_div]
· exact fun t ht ↦ (h𝒜 <| hℬ𝒜 ht).2.2
· exact dvd_sum fun t ht ↦ (h𝒜 <| hℬ𝒜 ht).2.2
· exact h𝒜disj.mono hℬ𝒜
-- Now, let's find those `2 * m - 1` sets.
rintro k hk
-- We induct on the size `k ≤ 2 * m - 1` of the family we are constructing.
induction k with
-- For `k = 0`, the empty family trivially works.
| zero => exact ⟨∅, by simp⟩
| succ k ih =>
-- At `k + 1`, call `𝒜` the existing family of size `k ≤ 2 * m - 2`.
obtain ⟨𝒜, h𝒜card, h𝒜disj, h𝒜⟩ := ih (Nat.le_of_succ_le hk)
-- There are at least `2 * (m * n) - 1 - k * n ≥ 2 * m - 1` elements in `s` that have not been
-- taken in any element of `𝒜`.
have : 2 * n - 1 ≤ #(s \ 𝒜.biUnion id) := by
calc
_ ≤ (2 * m - k) * n - 1 := by gcongr; cutsat
_ = (2 * (m * n) - 1) - ∑ t ∈ 𝒜, #t := by
rw [tsub_mul, mul_assoc, tsub_right_comm, sum_const_nat fun t ht ↦ (h𝒜 ht).2.1, h𝒜card]
_ ≤ #s - #(𝒜.biUnion id) := by gcongr; exact card_biUnion_le
_ ≤ #(s \ 𝒜.biUnion id) := le_card_sdiff ..
-- So by the induction hypothesis on `n` we can find a new set `t` of size `n` and sum divisible
-- by `n`.
obtain ⟨t₀, ht₀, ht₀card, ht₀sum⟩ := ihn a this
-- This set is distinct and disjoint from the previous ones, so we are done.
have : t₀ ∉ 𝒜 := by
rintro h
obtain rfl : n = 0 := by
simpa [← card_eq_zero, ht₀card] using sdiff_disjoint.mono ht₀ <| subset_biUnion_of_mem id h
omega
refine ⟨𝒜.cons t₀ this, by rw [card_cons, h𝒜card], ?_, ?_⟩
· simp only [cons_eq_insert, coe_insert, Set.pairwise_insert_of_symmetric symmetric_disjoint,
mem_coe, ne_eq]
exact ⟨h𝒜disj, fun t ht _ ↦ sdiff_disjoint.mono ht₀ <| subset_biUnion_of_mem id ht⟩
· simp only [cons_eq_insert, mem_insert, forall_eq_or_imp, and_assoc]
exact ⟨ht₀.trans sdiff_subset, ht₀card, ht₀sum, h𝒜⟩
/-- The **Erdős–Ginzburg–Ziv theorem** for `ℤ/nℤ`.
Any sequence of at least `2 * n - 1` elements of `ZMod n` contains a subsequence of `n` elements
whose sum is zero. -/
theorem ZMod.erdos_ginzburg_ziv (a : ι → ZMod n) (hs : 2 * n - 1 ≤ #s) :
∃ t ⊆ s, #t = n ∧ ∑ i ∈ t, a i = 0 := by
simpa [← ZMod.intCast_zmod_eq_zero_iff_dvd] using Int.erdos_ginzburg_ziv (ZMod.cast ∘ a) hs
/-- The **Erdős–Ginzburg–Ziv theorem** for `ℤ` for multiset.
Any multiset of at least `2 * n - 1` elements of `ℤ` contains a submultiset of `n` elements whose
sum is divisible by `n`. -/
theorem Int.erdos_ginzburg_ziv_multiset (s : Multiset ℤ) (hs : 2 * n - 1 ≤ Multiset.card s) :
∃ t ≤ s, Multiset.card t = n ∧ ↑n ∣ t.sum := by
obtain ⟨t, hts, ht⟩ := Int.erdos_ginzburg_ziv (s := s.toEnumFinset) Prod.fst (by simpa using hs)
exact ⟨t.1.map Prod.fst, Multiset.map_fst_le_of_subset_toEnumFinset hts, by simpa using ht⟩
/-- The **Erdős–Ginzburg–Ziv theorem** for `ℤ/nℤ` for multiset.
Any multiset of at least `2 * n - 1` elements of `ℤ` contains a submultiset of `n` elements whose
sum is divisible by `n`. -/
theorem ZMod.erdos_ginzburg_ziv_multiset (s : Multiset (ZMod n))
(hs : 2 * n - 1 ≤ Multiset.card s) : ∃ t ≤ s, Multiset.card t = n ∧ t.sum = 0 := by
obtain ⟨t, hts, ht⟩ := ZMod.erdos_ginzburg_ziv (s := s.toEnumFinset) Prod.fst (by simpa using hs)
exact ⟨t.1.map Prod.fst, Multiset.map_fst_le_of_subset_toEnumFinset hts, by simpa using ht⟩
end composite |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/CauchyDavenport.lean | import Mathlib.Combinatorics.Additive.ETransform
import Mathlib.GroupTheory.Order.Min
/-!
# The Cauchy-Davenport theorem
This file proves a generalisation of the Cauchy-Davenport theorem to arbitrary groups.
Cauchy-Davenport provides a lower bound on the size of `s + t` in terms of the sizes of `s` and `t`,
where `s` and `t` are nonempty finite sets in a monoid. Precisely, it says that
`|s + t| ≥ |s| + |t| - 1` unless the RHS is bigger than the size of the smallest nontrivial subgroup
(in which case taking `s` and `t` to be that subgroup would yield a counterexample). The motivating
example is `s = {0, ..., m}`, `t = {0, ..., n}` in the integers, which gives
`s + t = {0, ..., m + n}` and `|s + t| = m + n + 1 = |s| + |t| - 1`.
There are two kinds of proof of Cauchy-Davenport:
* The first one works in linear orders by writing `a₁ < ... < aₖ` the elements of `s`,
`b₁ < ... < bₗ` the elements of `t`, and arguing that `a₁ + b₁ < ... < aₖ + b₁ < ... < aₖ + bₗ`
are distinct elements of `s + t`.
* The second one works in groups by performing an "e-transform". In an abelian group, the
e-transform replaces `s` and `t` by `s ∩ g • s` and `t ∪ g⁻¹ • t`. For a suitably chosen `g`, this
decreases `|s + t|` and keeps `|s| + |t|` the same. In a general group, we use a trickier
e-transform (in fact, a pair of e-transforms), but the idea is the same.
## Main declarations
* `cauchy_davenport_minOrder_mul`: A generalisation of the Cauchy-Davenport theorem to arbitrary
groups.
* `cauchy_davenport_of_isTorsionFree`: The Cauchy-Davenport theorem in torsion-free groups.
* `ZMod.cauchy_davenport`: The Cauchy-Davenport theorem for `ZMod p`.
* `cauchy_davenport_mul_of_linearOrder_isCancelMul`: The Cauchy-Davenport theorem in linear ordered
cancellative semigroups.
## TODO
Version for `circle`.
## References
* Matt DeVos, *On a generalization of the Cauchy-Davenport theorem*
## Tags
additive combinatorics, number theory, sumset, cauchy-davenport
-/
open Finset Function Monoid MulOpposite Subgroup
open scoped Pointwise
variable {G α : Type*}
/-! ### General case -/
section General
variable [Group α] [DecidableEq α] {x y : Finset α × Finset α} {s t : Finset α}
/-- The relation we induct along in the proof by DeVos of the Cauchy-Davenport theorem.
`(s₁, t₁) < (s₂, t₂)` iff
* `|s₁ * t₁| < |s₂ * t₂|`
* or `|s₁ * t₁| = |s₂ * t₂|` and `|s₂| + |t₂| < |s₁| + |t₁|`
* or `|s₁ * t₁| = |s₂ * t₂|` and `|s₁| + |t₁| = |s₂| + |t₂|` and `|s₁| < |s₂|`. -/
@[to_additive
/-- The relation we induct along in the proof by DeVos of the Cauchy-Davenport theorem.
`(s₁, t₁) < (s₂, t₂)` iff
* `|s₁ + t₁| < |s₂ + t₂|`
* or `|s₁ + t₁| = |s₂ + t₂|` and `|s₂| + |t₂| < |s₁| + |t₁|`
* or `|s₁ + t₁| = |s₂ + t₂|` and `|s₁| + |t₁| = |s₂| + |t₂|` and `|s₁| < |s₂|`. -/]
private def DevosMulRel : Finset α × Finset α → Finset α × Finset α → Prop :=
Prod.Lex (· < ·) (Prod.Lex (· > ·) (· < ·)) on fun x ↦ (#(x.1 * x.2), #x.1 + #x.2, #x.1)
@[to_additive]
private lemma devosMulRel_iff :
DevosMulRel x y ↔
#(x.1 * x.2) < #(y.1 * y.2) ∨
#(x.1 * x.2) = #(y.1 * y.2) ∧ #y.1 + #y.2 < #x.1 + #x.2 ∨
#(x.1 * x.2) = #(y.1 * y.2) ∧ #x.1 + #x.2 = #y.1 + #y.2 ∧ #x.1 < #y.1 := by
simp [DevosMulRel, Prod.lex_iff, and_or_left]
@[to_additive]
private lemma devosMulRel_of_le (mul : #(x.1 * x.2) ≤ #(y.1 * y.2))
(hadd : #y.1 + #y.2 < #x.1 + #x.2) : DevosMulRel x y :=
devosMulRel_iff.2 <| mul.lt_or_eq.imp_right fun h ↦ Or.inl ⟨h, hadd⟩
@[to_additive]
private lemma devosMulRel_of_le_of_le (mul : #(x.1 * x.2) ≤ #(y.1 * y.2))
(hadd : #y.1 + #y.2 ≤ #x.1 + #x.2) (hone : #x.1 < #y.1) : DevosMulRel x y :=
devosMulRel_iff.2 <|
mul.lt_or_eq.imp_right fun h ↦ hadd.lt_or_eq'.imp (And.intro h) fun h' ↦ ⟨h, h', hone⟩
@[to_additive]
private lemma wellFoundedOn_devosMulRel :
{x : Finset α × Finset α | x.1.Nonempty ∧ x.2.Nonempty}.WellFoundedOn
(DevosMulRel : Finset α × Finset α → Finset α × Finset α → Prop) := by
refine wellFounded_lt.onFun.wellFoundedOn.prod_lex_of_wellFoundedOn_fiber fun n ↦
Set.WellFoundedOn.prod_lex_of_wellFoundedOn_fiber ?_ fun n ↦
wellFounded_lt.onFun.wellFoundedOn
exact wellFounded_lt.onFun.wellFoundedOn.mono' fun x hx y _ ↦ tsub_lt_tsub_left_of_le <|
add_le_add ((card_le_card_mul_right hx.1.2).trans_eq hx.2) <|
(card_le_card_mul_left hx.1.1).trans_eq hx.2
/-- A generalisation of the **Cauchy-Davenport theorem** to arbitrary groups. The size of `s * t` is
lower-bounded by `|s| + |t| - 1` unless this quantity is greater than the size of the smallest
subgroup. -/
@[to_additive /-- A generalisation of the **Cauchy-Davenport theorem** to arbitrary groups. The
size of `s + t` is lower-bounded by `|s| + |t| - 1` unless this quantity is greater than the size
of the smallest subgroup. -/]
lemma cauchy_davenport_minOrder_mul (hs : s.Nonempty) (ht : t.Nonempty) :
min (minOrder α) ↑(#s + #t - 1) ≤ #(s * t) := by
-- Set up the induction on `x := (s, t)` along the `DevosMulRel` relation.
set x := (s, t) with hx
clear_value x
simp only [Prod.ext_iff] at hx
obtain ⟨rfl, rfl⟩ := hx
refine wellFoundedOn_devosMulRel.induction (P := fun x : Finset α × Finset α ↦
min (minOrder α) ↑(#x.1 + #x.2 - 1) ≤ #(x.1 * x.2)) ⟨hs, ht⟩ ?_
clear! x
rintro ⟨s, t⟩ ⟨hs, ht⟩ ih
simp only [min_le_iff, tsub_le_iff_right, Prod.forall, Set.mem_setOf_eq, and_imp,
Nat.cast_le] at *
-- If `#t < #s`, we're done by the induction hypothesis on `(t⁻¹, s⁻¹)`.
obtain hts | hst := lt_or_ge #t #s
· simpa only [← mul_inv_rev, add_comm, card_inv] using
ih _ _ ht.inv hs.inv
(devosMulRel_iff.2 <| Or.inr <| Or.inr <| by
simpa only [← mul_inv_rev, add_comm, card_inv, true_and])
-- If `s` is a singleton, then the result is trivial.
obtain ⟨a, rfl⟩ | ⟨a, ha, b, hb, hab⟩ := hs.exists_eq_singleton_or_nontrivial
· simp [add_comm]
-- Else, we have `a, b ∈ s` distinct. So `g := b⁻¹ * a` is a non-identity element such that `s`
-- intersects its right translate by `g`.
obtain ⟨g, hg, hgs⟩ : ∃ g : α, g ≠ 1 ∧ (s ∩ op g • s).Nonempty :=
⟨b⁻¹ * a, inv_mul_eq_one.not.2 hab.symm, _,
mem_inter.2 ⟨ha, mem_smul_finset.2 ⟨_, hb, by simp⟩⟩⟩
-- If `s` is equal to its right translate by `g`, then it contains a nontrivial subgroup, namely
-- the subgroup generated by `g`. So `s * t` has size at least the size of a nontrivial subgroup,
-- as wanted.
obtain hsg | hsg := eq_or_ne (op g • s) s
· have hS : (zpowers g : Set α) ⊆ a⁻¹ • (s : Set α) := by
refine forall_mem_zpowers.2 <| @zpow_induction_right _ _ _ (· ∈ a⁻¹ • (s : Set α))
⟨_, ha, inv_mul_cancel _⟩ (fun c hc ↦ ?_) fun c hc ↦ ?_
· rw [← hsg, coe_smul_finset, smul_comm]
exact Set.smul_mem_smul_set hc
· simp only
rwa [← op_smul_eq_mul, op_inv, ← Set.mem_smul_set_iff_inv_smul_mem, smul_comm,
← coe_smul_finset, hsg]
refine Or.inl ((minOrder_le_natCard (zpowers_ne_bot.2 hg) <|
s.finite_toSet.smul_set.subset hS).trans <| WithTop.coe_le_coe.2 <|
((Nat.card_mono s.finite_toSet.smul_set hS).trans_eq <| ?_).trans <|
card_le_card_mul_right ht)
rw [← coe_smul_finset]
simp [-coe_smul_finset]
-- Else, we can transform `s`, `t` to `s'`, `t'` and `s''`, `t''`, such that one of `(s', t')` and
-- `(s'', t'')` is strictly smaller than `(s, t)` according to `DevosMulRel`.
replace hsg : #(s ∩ op g • s) < #s := card_lt_card ⟨inter_subset_left, fun h ↦
hsg <| eq_of_superset_of_card_ge (h.trans inter_subset_right) (card_smul_finset _ _).le⟩
replace aux1 := card_mono <| mulETransformLeft.fst_mul_snd_subset g (s, t)
replace aux2 := card_mono <| mulETransformRight.fst_mul_snd_subset g (s, t)
-- If the left translate of `t` by `g⁻¹` is disjoint from `t`, then we're easily done.
obtain hgt | hgt := disjoint_or_nonempty_inter t (g⁻¹ • t)
· rw [← card_smul_finset g⁻¹ t]
right
grw [hst, ← card_union_of_disjoint hgt]
exact (card_le_card_mul_left hgs).trans (le_add_of_le_left aux1)
-- Else, we're done by induction on either `(s', t')` or `(s'', t'')` depending on whether
-- `|s| + |t| ≤ |s'| + |t'|` or `|s| + |t| < |s''| + |t''|`. One of those two inequalities must
-- hold since `2 * (|s| + |t|) = |s'| + |t'| + |s''| + |t''|`.
obtain hstg | hstg := le_or_lt_of_add_le_add (MulETransform.card g (s, t)).ge
· exact (ih _ _ hgs (hgt.mono inter_subset_union) <| devosMulRel_of_le_of_le aux1 hstg hsg).imp
(WithTop.coe_le_coe.2 aux1).trans' fun h ↦ hstg.trans <| h.trans <| add_le_add_right aux1 _
· exact (ih _ _ (hgs.mono inter_subset_union) hgt <| devosMulRel_of_le aux2 hstg).imp
(WithTop.coe_le_coe.2 aux2).trans' fun h ↦
hstg.le.trans <| h.trans <| add_le_add_right aux2 _
end General
/-- The **Cauchy-Davenport Theorem** for torsion-free groups. The size of `s * t` is lower-bounded
by `|s| + |t| - 1`. -/
@[to_additive
/-- The **Cauchy-Davenport theorem** for torsion-free groups. The size of `s + t` is lower-bounded
by `|s| + |t| - 1`. -/]
lemma cauchy_davenport_of_isMulTorsionFree [DecidableEq G] [Group G] [IsMulTorsionFree G]
{s t : Finset G} (hs : s.Nonempty) (ht : t.Nonempty) : #s + #t - 1 ≤ #(s * t) := by
simpa only [Monoid.minOrder_eq_top, min_eq_right, le_top, Nat.cast_le]
using cauchy_davenport_minOrder_mul hs ht
@[to_additive (attr := deprecated cauchy_davenport_of_isMulTorsionFree (since := "2025-04-23"))]
alias cauchy_davenport_mul_of_isTorsionFree := cauchy_davenport_of_isMulTorsionFree
/-! ### $$ℤ/nℤ$$ -/
/-- The **Cauchy-Davenport Theorem**. If `s`, `t` are nonempty sets in $$ℤ/pℤ$$, then the size of
`s + t` is lower-bounded by `|s| + |t| - 1`, unless this quantity is greater than `p`. -/
lemma ZMod.cauchy_davenport {p : ℕ} (hp : p.Prime) {s t : Finset (ZMod p)} (hs : s.Nonempty)
(ht : t.Nonempty) : min p (#s + #t - 1) ≤ #(s + t) := by
simpa only [ZMod.minOrder_of_prime hp, min_le_iff, Nat.cast_le]
using cauchy_davenport_minOrder_add hs ht
/-! ### Linearly ordered cancellative semigroups -/
/-- The **Cauchy-Davenport Theorem** for linearly ordered cancellative semigroups. The size of
`s * t` is lower-bounded by `|s| + |t| - 1`. -/
@[to_additive
/-- The **Cauchy-Davenport theorem** for linearly ordered additive cancellative semigroups. The
size of `s + t` is lower-bounded by `|s| + |t| - 1`. -/]
lemma cauchy_davenport_mul_of_linearOrder_isCancelMul [LinearOrder α] [Mul α] [IsCancelMul α]
[MulLeftMono α] [MulRightMono α]
{s t : Finset α} (hs : s.Nonempty) (ht : t.Nonempty) : #s + #t - 1 ≤ #(s * t) := by
suffices s * {t.min' ht} ∩ ({s.max' hs} * t) = {s.max' hs * t.min' ht} by
rw [← card_singleton_mul (s.max' hs) t, ← card_mul_singleton s (t.min' ht),
← card_union_add_card_inter, ← card_singleton _, ← this, Nat.add_sub_cancel]
exact card_mono (union_subset (mul_subset_mul_left <| singleton_subset_iff.2 <| min'_mem _ _) <|
mul_subset_mul_right <| singleton_subset_iff.2 <| max'_mem _ _)
refine eq_singleton_iff_unique_mem.2 ⟨mem_inter.2 ⟨mul_mem_mul (max'_mem _ _) <|
mem_singleton_self _, mul_mem_mul (mem_singleton_self _) <| min'_mem _ _⟩, ?_⟩
simp only [mem_inter, and_imp, mem_mul, mem_singleton, exists_eq_left,
forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, mul_left_inj]
exact fun a' ha' b' hb' h ↦ (le_max' _ _ ha').eq_of_not_lt fun ha ↦
((mul_lt_mul_right' ha _).trans_eq' h).not_ge <| mul_le_mul_left' (min'_le _ _ hb') _ |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/FreimanHom.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Algebra.CharP.Basic
import Mathlib.Algebra.Group.Pointwise.Set.Basic
import Mathlib.Algebra.Group.Submonoid.Defs
import Mathlib.Algebra.Order.BigOperators.Group.Multiset
import Mathlib.Algebra.Order.Group.Nat
import Mathlib.Data.ZMod.Defs
/-!
# Freiman homomorphisms
In this file, we define Freiman homomorphisms and isomorphisms.
An `n`-Freiman homomorphism from `A` to `B` is a function `f : α → β` such that `f '' A ⊆ B` and
`f x₁ * ... * f xₙ = f y₁ * ... * f yₙ` for all `x₁, ..., xₙ, y₁, ..., yₙ ∈ A` such that
`x₁ * ... * xₙ = y₁ * ... * yₙ`. In particular, any `MulHom` is a Freiman homomorphism.
Note a `0`- or `1`-Freiman homomorphism is simply a map, thus a `2`-Freiman homomorphism is the
first interesting case (and the most common). As `n` increases further, the property of being
an `n`-Freiman homomorphism between abelian groups becomes increasingly stronger.
An `n`-Freiman isomorphism from `A` to `B` is a function `f : α → β` bijective between `A` and `B`
such that `f x₁ * ... * f xₙ = f y₁ * ... * f yₙ ↔ x₁ * ... * xₙ = y₁ * ... * yₙ` for all
`x₁, ..., xₙ, y₁, ..., yₙ ∈ A`. In particular, any `MulEquiv` is a Freiman isomorphism.
They are of interest in additive combinatorics.
## Main declarations
* `IsMulFreimanHom`: Predicate for a function to be a multiplicative Freiman homomorphism.
* `IsAddFreimanHom`: Predicate for a function to be an additive Freiman homomorphism.
* `IsMulFreimanIso`: Predicate for a function to be a multiplicative Freiman isomorphism.
* `IsAddFreimanIso`: Predicate for a function to be an additive Freiman isomorphism.
## Main results
* `isMulFreimanHom_two`: Characterisation of `2`-Freiman homomorphisms.
* `IsMulFreimanHom.mono`: If `m ≤ n` and `f` is an `n`-Freiman homomorphism, then it is also an
`m`-Freiman homomorphism.
## Implementation notes
In the context of combinatorics, we are interested in Freiman homomorphisms over sets which are not
necessarily closed under addition/multiplication. This means we must parametrize them with a set in
an `AddMonoid`/`Monoid` instead of the `AddMonoid`/`Monoid` itself.
## References
[Yufei Zhao, *18.225: Graph Theory and Additive Combinatorics*](https://yufeizhao.com/gtac/)
## TODO
* `MonoidHomClass.isMulFreimanHom` could be relaxed to `MulHom.toFreimanHom` by proving
`(s.map f).prod = (t.map f).prod` directly by induction instead of going through `f s.prod`.
* Affine maps are Freiman homomorphisms.
-/
assert_not_exists Field Ideal TwoSidedIdeal
open Multiset Set
open scoped Pointwise
variable {F α β γ : Type*}
section CommMonoid
variable [CommMonoid α] [CommMonoid β] [CommMonoid γ] {A A₁ A₂ : Set α}
{B B₁ B₂ : Set β} {C : Set γ} {f f₁ f₂ : α → β} {g : β → γ} {n : ℕ}
/-- An additive `n`-Freiman homomorphism from a set `A` to a set `B` is a map which preserves sums
of `n` elements. -/
structure IsAddFreimanHom [AddCommMonoid α] [AddCommMonoid β] (n : ℕ) (A : Set α) (B : Set β)
(f : α → β) : Prop where
mapsTo : MapsTo f A B
/-- An additive `n`-Freiman homomorphism preserves sums of `n` elements. -/
map_sum_eq_map_sum ⦃s t : Multiset α⦄ (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A)
(hs : Multiset.card s = n) (ht : Multiset.card t = n) (h : s.sum = t.sum) :
(s.map f).sum = (t.map f).sum
/-- An `n`-Freiman homomorphism from a set `A` to a set `B` is a map which preserves products of `n`
elements. -/
@[to_additive]
structure IsMulFreimanHom (n : ℕ) (A : Set α) (B : Set β) (f : α → β) : Prop where
mapsTo : MapsTo f A B
/-- An `n`-Freiman homomorphism preserves products of `n` elements. -/
map_prod_eq_map_prod ⦃s t : Multiset α⦄ (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A)
(hs : Multiset.card s = n) (ht : Multiset.card t = n) (h : s.prod = t.prod) :
(s.map f).prod = (t.map f).prod
/-- An additive `n`-Freiman homomorphism from a set `A` to a set `B` is a bijective map which
preserves sums of `n` elements. -/
structure IsAddFreimanIso [AddCommMonoid α] [AddCommMonoid β] (n : ℕ) (A : Set α) (B : Set β)
(f : α → β) : Prop where
bijOn : BijOn f A B
/-- An additive `n`-Freiman homomorphism preserves sums of `n` elements. -/
map_sum_eq_map_sum ⦃s t : Multiset α⦄ (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A)
(hs : Multiset.card s = n) (ht : Multiset.card t = n) :
(s.map f).sum = (t.map f).sum ↔ s.sum = t.sum
/-- An `n`-Freiman homomorphism from a set `A` to a set `B` is a map which preserves products of `n`
elements. -/
@[to_additive]
structure IsMulFreimanIso (n : ℕ) (A : Set α) (B : Set β) (f : α → β) : Prop where
bijOn : BijOn f A B
/-- An `n`-Freiman homomorphism preserves products of `n` elements. -/
map_prod_eq_map_prod ⦃s t : Multiset α⦄ (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A)
(hs : Multiset.card s = n) (ht : Multiset.card t = n) :
(s.map f).prod = (t.map f).prod ↔ s.prod = t.prod
@[to_additive]
lemma IsMulFreimanIso.isMulFreimanHom (hf : IsMulFreimanIso n A B f) : IsMulFreimanHom n A B f where
mapsTo := hf.bijOn.mapsTo
map_prod_eq_map_prod _s _t hsA htA hs ht := (hf.map_prod_eq_map_prod hsA htA hs ht).2
lemma IsMulFreimanHom.congr (hf₁ : IsMulFreimanHom n A B f₁) (h : EqOn f₁ f₂ A) :
IsMulFreimanHom n A B f₂ where
mapsTo := hf₁.mapsTo.congr h
map_prod_eq_map_prod s t hsA htA hs ht h' := by
rw [map_congr rfl fun x hx => (h (hsA hx)).symm, map_congr rfl fun x hx => (h (htA hx)).symm,
hf₁.map_prod_eq_map_prod hsA htA hs ht h']
lemma IsMulFreimanIso.congr (hf₁ : IsMulFreimanIso n A B f₁) (h : EqOn f₁ f₂ A) :
IsMulFreimanIso n A B f₂ where
bijOn := hf₁.bijOn.congr h
map_prod_eq_map_prod s t hsA htA hs ht := by
rw [map_congr rfl fun x hx => h.symm (hsA hx), map_congr rfl fun x hx => h.symm (htA hx),
hf₁.map_prod_eq_map_prod hsA htA hs ht]
@[to_additive]
lemma IsMulFreimanHom.mul_eq_mul (hf : IsMulFreimanHom 2 A B f) {a b c d : α}
(ha : a ∈ A) (hb : b ∈ A) (hc : c ∈ A) (hd : d ∈ A) (h : a * b = c * d) :
f a * f b = f c * f d := by
simp_rw [← prod_pair] at h ⊢
refine hf.map_prod_eq_map_prod ?_ ?_ (card_pair _ _) (card_pair _ _) h <;> simp [ha, hb, hc, hd]
@[to_additive]
lemma IsMulFreimanIso.mul_eq_mul (hf : IsMulFreimanIso 2 A B f) {a b c d : α}
(ha : a ∈ A) (hb : b ∈ A) (hc : c ∈ A) (hd : d ∈ A) :
f a * f b = f c * f d ↔ a * b = c * d := by
simp_rw [← prod_pair]
refine hf.map_prod_eq_map_prod ?_ ?_ (card_pair _ _) (card_pair _ _) <;> simp [ha, hb, hc, hd]
/-- Characterisation of `2`-Freiman homomorphisms. -/
@[to_additive /-- Characterisation of `2`-Freiman homomorphisms. -/]
lemma isMulFreimanHom_two :
IsMulFreimanHom 2 A B f ↔ MapsTo f A B ∧ ∀ a ∈ A, ∀ b ∈ A, ∀ c ∈ A, ∀ d ∈ A,
a * b = c * d → f a * f b = f c * f d where
mp hf := ⟨hf.mapsTo, fun _ ha _ hb _ hc _ hd ↦ hf.mul_eq_mul ha hb hc hd⟩
mpr hf := ⟨hf.1, by aesop (add simp card_eq_two)⟩
/-- Characterisation of `2`-Freiman homs. -/
@[to_additive /-- Characterisation of `2`-Freiman isomorphisms. -/]
lemma isMulFreimanIso_two :
IsMulFreimanIso 2 A B f ↔ BijOn f A B ∧ ∀ a ∈ A, ∀ b ∈ A, ∀ c ∈ A, ∀ d ∈ A,
f a * f b = f c * f d ↔ a * b = c * d where
mp hf := ⟨hf.bijOn, fun _ ha _ hb _ hc _ hd => hf.mul_eq_mul ha hb hc hd⟩
mpr hf := ⟨hf.1, by aesop (add simp card_eq_two)⟩
@[to_additive] lemma isMulFreimanHom_id (hA : A₁ ⊆ A₂) : IsMulFreimanHom n A₁ A₂ id where
mapsTo := hA
map_prod_eq_map_prod s t _ _ _ _ h := by simpa using h
@[to_additive] lemma isMulFreimanIso_id : IsMulFreimanIso n A A id where
bijOn := bijOn_id _
map_prod_eq_map_prod s t _ _ _ _ := by simp
@[to_additive] lemma IsMulFreimanHom.comp (hg : IsMulFreimanHom n B C g)
(hf : IsMulFreimanHom n A B f) : IsMulFreimanHom n A C (g ∘ f) where
mapsTo := hg.mapsTo.comp hf.mapsTo
map_prod_eq_map_prod s t hsA htA hs ht h := by
rw [← map_map, ← map_map]
refine hg.map_prod_eq_map_prod ?_ ?_ (by rwa [card_map]) (by rwa [card_map])
(hf.map_prod_eq_map_prod hsA htA hs ht h)
· simpa using fun a h ↦ hf.mapsTo (hsA h)
· simpa using fun a h ↦ hf.mapsTo (htA h)
@[to_additive] lemma IsMulFreimanIso.comp (hg : IsMulFreimanIso n B C g)
(hf : IsMulFreimanIso n A B f) : IsMulFreimanIso n A C (g ∘ f) where
bijOn := hg.bijOn.comp hf.bijOn
map_prod_eq_map_prod s t hsA htA hs ht := by
rw [← map_map, ← map_map]
rw [hg.map_prod_eq_map_prod _ _ (by rwa [card_map]) (by rwa [card_map]),
hf.map_prod_eq_map_prod hsA htA hs ht]
· simpa using fun a h ↦ hf.bijOn.mapsTo (hsA h)
· simpa using fun a h ↦ hf.bijOn.mapsTo (htA h)
@[to_additive] lemma IsMulFreimanHom.subset (hA : A₁ ⊆ A₂) (hf : IsMulFreimanHom n A₂ B₂ f)
(hf' : MapsTo f A₁ B₁) : IsMulFreimanHom n A₁ B₁ f where
mapsTo := hf'
__ := hf.comp (isMulFreimanHom_id hA)
@[to_additive] lemma IsMulFreimanHom.superset (hB : B₁ ⊆ B₂) (hf : IsMulFreimanHom n A B₁ f) :
IsMulFreimanHom n A B₂ f := (isMulFreimanHom_id hB).comp hf
@[to_additive] lemma IsMulFreimanIso.subset (hA : A₁ ⊆ A₂) (hf : IsMulFreimanIso n A₂ B₂ f)
(hf' : BijOn f A₁ B₁) : IsMulFreimanIso n A₁ B₁ f where
bijOn := hf'
map_prod_eq_map_prod s t hsA htA hs ht := by
refine hf.map_prod_eq_map_prod (fun a ha ↦ hA (hsA ha)) (fun a ha ↦ hA (htA ha)) hs ht
@[to_additive]
lemma isMulFreimanHom_const {b : β} (hb : b ∈ B) : IsMulFreimanHom n A B fun _ ↦ b where
mapsTo _ _ := hb
map_prod_eq_map_prod s t _ _ hs ht _ := by simp only [map_const', hs, prod_replicate, ht]
@[to_additive (attr := simp)]
lemma isMulFreimanHom_zero_iff : IsMulFreimanHom 0 A B f ↔ MapsTo f A B :=
⟨fun h => h.mapsTo, fun h => ⟨h, by simp_all⟩⟩
@[to_additive (attr := simp)]
lemma isMulFreimanIso_zero_iff : IsMulFreimanIso 0 A B f ↔ BijOn f A B :=
⟨fun h => h.bijOn, fun h => ⟨h, by simp_all⟩⟩
@[to_additive (attr := simp) isAddFreimanHom_one_iff]
lemma isMulFreimanHom_one_iff : IsMulFreimanHom 1 A B f ↔ MapsTo f A B :=
⟨fun h => h.mapsTo, fun h => ⟨h, by aesop (add simp card_eq_one)⟩⟩
@[to_additive (attr := simp) isAddFreimanIso_one_iff]
lemma isMulFreimanIso_one_iff : IsMulFreimanIso 1 A B f ↔ BijOn f A B :=
⟨fun h => h.bijOn, fun h => ⟨h, by aesop (add simp [card_eq_one, BijOn])⟩⟩
@[to_additive (attr := simp)]
lemma isMulFreimanHom_empty : IsMulFreimanHom n (∅ : Set α) B f where
mapsTo := mapsTo_empty f B
map_prod_eq_map_prod s t := by aesop (add simp eq_zero_of_forall_notMem)
@[to_additive (attr := simp)]
lemma isMulFreimanIso_empty : IsMulFreimanIso n (∅ : Set α) (∅ : Set β) f where
bijOn := bijOn_empty _
map_prod_eq_map_prod s t hs ht := by
simp [eq_zero_of_forall_notMem hs, eq_zero_of_forall_notMem ht]
@[to_additive] lemma IsMulFreimanHom.mul (h₁ : IsMulFreimanHom n A B₁ f₁)
(h₂ : IsMulFreimanHom n A B₂ f₂) : IsMulFreimanHom n A (B₁ * B₂) (f₁ * f₂) where
mapsTo := h₁.mapsTo.mul h₂.mapsTo
map_prod_eq_map_prod s t hsA htA hs ht h := by
rw [Pi.mul_def, prod_map_mul, prod_map_mul, h₁.map_prod_eq_map_prod hsA htA hs ht h,
h₂.map_prod_eq_map_prod hsA htA hs ht h]
@[to_additive] lemma MonoidHomClass.isMulFreimanHom [FunLike F α β] [MonoidHomClass F α β] (f : F)
(hfAB : MapsTo f A B) : IsMulFreimanHom n A B f where
mapsTo := hfAB
map_prod_eq_map_prod s t _ _ _ _ h := by rw [← map_multiset_prod, h, map_multiset_prod]
@[to_additive] lemma MulEquivClass.isMulFreimanIso [EquivLike F α β] [MulEquivClass F α β] (f : F)
(hfAB : BijOn f A B) : IsMulFreimanIso n A B f where
bijOn := hfAB
map_prod_eq_map_prod s t _ _ _ _ := by
rw [← map_multiset_prod, ← map_multiset_prod, EquivLike.apply_eq_iff_eq]
@[to_additive]
lemma IsMulFreimanHom.subtypeVal {S : Type*} [SetLike S α] [SubmonoidClass S α] {s : S} :
IsMulFreimanHom n (univ : Set s) univ Subtype.val :=
MonoidHomClass.isMulFreimanHom (SubmonoidClass.subtype s) (mapsTo_univ ..)
end CommMonoid
section CancelCommMonoid
variable [CommMonoid α] [CancelCommMonoid β] {A : Set α} {B : Set β} {f : α → β} {m n : ℕ}
@[to_additive]
lemma IsMulFreimanHom.mono (hmn : m ≤ n) (hf : IsMulFreimanHom n A B f) :
IsMulFreimanHom m A B f where
mapsTo := hf.mapsTo
map_prod_eq_map_prod s t hsA htA hs ht h := by
obtain rfl | hm := m.eq_zero_or_pos
· rw [card_eq_zero] at hs ht
rw [hs, ht]
simp only [← hs, card_pos_iff_exists_mem] at hm
obtain ⟨a, ha⟩ := hm
suffices ((s + replicate (n - m) a).map f).prod = ((t + replicate (n - m) a).map f).prod by
simp_rw [Multiset.map_add, prod_add] at this
exact mul_right_cancel this
replace ha := hsA ha
refine hf.map_prod_eq_map_prod (fun a ha ↦ ?_) (fun a ha ↦ ?_) ?_ ?_ ?_
· rw [Multiset.mem_add] at ha
obtain ha | ha := ha
· exact hsA ha
· rwa [eq_of_mem_replicate ha]
· rw [Multiset.mem_add] at ha
obtain ha | ha := ha
· exact htA ha
· rwa [eq_of_mem_replicate ha]
· rw [card_add, card_replicate, hs, Nat.add_sub_cancel' hmn]
· rw [card_add, card_replicate, ht, Nat.add_sub_cancel' hmn]
· rw [prod_add, prod_add, h]
end CancelCommMonoid
section CancelCommMonoid
variable [CancelCommMonoid α] [CancelCommMonoid β] {A : Set α} {B : Set β} {f : α → β} {m n : ℕ}
@[to_additive]
lemma IsMulFreimanIso.mono {hmn : m ≤ n} (hf : IsMulFreimanIso n A B f) :
IsMulFreimanIso m A B f where
bijOn := hf.bijOn
map_prod_eq_map_prod s t hsA htA hs ht := by
obtain rfl | hm := m.eq_zero_or_pos
· rw [card_eq_zero] at hs ht
simp [hs, ht]
simp only [← hs, card_pos_iff_exists_mem] at hm
obtain ⟨a, ha⟩ := hm
suffices
((s + replicate (n - m) a).map f).prod = ((t + replicate (n - m) a).map f).prod ↔
(s + replicate (n - m) a).prod = (t + replicate (n - m) a).prod by
simpa only [Multiset.map_add, prod_add, mul_right_cancel_iff] using this
replace ha := hsA ha
refine hf.map_prod_eq_map_prod (fun a ha ↦ ?_) (fun a ha ↦ ?_) ?_ ?_
· rw [Multiset.mem_add] at ha
obtain ha | ha := ha
· exact hsA ha
· rwa [eq_of_mem_replicate ha]
· rw [Multiset.mem_add] at ha
obtain ha | ha := ha
· exact htA ha
· rwa [eq_of_mem_replicate ha]
· rw [card_add, card_replicate, hs, Nat.add_sub_cancel' hmn]
· rw [card_add, card_replicate, ht, Nat.add_sub_cancel' hmn]
end CancelCommMonoid
section DivisionCommMonoid
variable [CommMonoid α] [DivisionCommMonoid β] {A : Set α} {B : Set β} {f : α → β} {n : ℕ}
@[to_additive]
lemma IsMulFreimanHom.inv (hf : IsMulFreimanHom n A B f) : IsMulFreimanHom n A B⁻¹ f⁻¹ where
mapsTo := hf.mapsTo.inv
map_prod_eq_map_prod s t hsA htA hs ht h := by
rw [Pi.inv_def, prod_map_inv, prod_map_inv, hf.map_prod_eq_map_prod hsA htA hs ht h]
@[to_additive] lemma IsMulFreimanHom.div {β : Type*} [DivisionCommMonoid β] {B₁ B₂ : Set β}
{f₁ f₂ : α → β} (h₁ : IsMulFreimanHom n A B₁ f₁) (h₂ : IsMulFreimanHom n A B₂ f₂) :
IsMulFreimanHom n A (B₁ / B₂) (f₁ / f₂) where
mapsTo := h₁.mapsTo.div h₂.mapsTo
map_prod_eq_map_prod s t hsA htA hs ht h := by
rw [Pi.div_def, prod_map_div, prod_map_div, h₁.map_prod_eq_map_prod hsA htA hs ht h,
h₂.map_prod_eq_map_prod hsA htA hs ht h]
end DivisionCommMonoid
section Prod
variable {α₁ α₂ β₁ β₂ : Type*} [CommMonoid α₁] [CommMonoid α₂] [CommMonoid β₁] [CommMonoid β₂]
{A₁ : Set α₁} {A₂ : Set α₂} {B₁ : Set β₁} {B₂ : Set β₂} {f₁ : α₁ → β₁} {f₂ : α₂ → β₂} {n : ℕ}
@[to_additive prodMap]
lemma IsMulFreimanHom.prodMap (h₁ : IsMulFreimanHom n A₁ B₁ f₁) (h₂ : IsMulFreimanHom n A₂ B₂ f₂) :
IsMulFreimanHom n (A₁ ×ˢ A₂) (B₁ ×ˢ B₂) (Prod.map f₁ f₂) where
mapsTo := h₁.mapsTo.prodMap h₂.mapsTo
map_prod_eq_map_prod s t hsA htA hs ht h := by
simp only [mem_prod, forall_and, Prod.forall] at hsA htA
simp only [Prod.ext_iff, fst_prod, snd_prod, map_map, Function.comp_apply, Prod.map_fst,
Prod.map_snd] at h ⊢
rw [← Function.comp_def, ← map_map, ← map_map, ← Function.comp_def f₂, ← map_map, ← map_map]
exact ⟨h₁.map_prod_eq_map_prod (by simpa using hsA.1) (by simpa using htA.1) (by simpa)
(by simpa) h.1, h₂.map_prod_eq_map_prod (by simpa [@forall_swap α₁] using hsA.2)
(by simpa [@forall_swap α₁] using htA.2) (by simpa) (by simpa) h.2⟩
@[to_additive prodMap]
lemma IsMulFreimanIso.prodMap (h₁ : IsMulFreimanIso n A₁ B₁ f₁) (h₂ : IsMulFreimanIso n A₂ B₂ f₂) :
IsMulFreimanIso n (A₁ ×ˢ A₂) (B₁ ×ˢ B₂) (Prod.map f₁ f₂) where
bijOn := h₁.bijOn.prodMap h₂.bijOn
map_prod_eq_map_prod s t hsA htA hs ht := by
simp only [mem_prod, forall_and, Prod.forall] at hsA htA
simp only [Prod.ext_iff, fst_prod, map_map, Function.comp_apply, Prod.map_fst, snd_prod,
Prod.map_snd]
rw [← Function.comp_def, ← map_map, ← map_map, ← Function.comp_def f₂, ← map_map, ← map_map,
h₁.map_prod_eq_map_prod (by simpa using hsA.1) (by simpa using htA.1) (by simpa) (by simpa),
h₂.map_prod_eq_map_prod (by simpa [@forall_swap α₁] using hsA.2)
(by simpa [@forall_swap α₁] using htA.2) (by simpa) (by simpa)]
end Prod
namespace Fin
variable {k m n : ℕ}
open Fin.CommRing
private lemma aux (hm : m ≠ 0) (hkmn : m * k ≤ n) : k < (n + 1) :=
Nat.lt_succ_iff.2 <| le_trans (Nat.le_mul_of_pos_left _ hm.bot_lt) hkmn
/-- **No wrap-around principle**.
The first `k + 1` elements of `Fin (n + 1)` are `m`-Freiman isomorphic to the first `k + 1` elements
of `ℕ` assuming there is no wrap-around. -/
lemma isAddFreimanIso_Iic (hm : m ≠ 0) (hkmn : m * k ≤ n) :
IsAddFreimanIso m (Iic (k : Fin (n + 1))) (Iic k) val where
bijOn.left := by simp [MapsTo, Fin.le_iff_val_le_val, Nat.mod_eq_of_lt, aux hm hkmn]
bijOn.right.left := val_injective.injOn
bijOn.right.right x (hx : x ≤ _) :=
⟨x, by simpa [le_iff_val_le_val, -val_fin_le, Nat.mod_eq_of_lt, aux hm hkmn, hx.trans_lt]⟩
map_sum_eq_map_sum s t hsA htA hs ht := by
have (u : Multiset (Fin (n + 1))) : Nat.castRingHom _ (u.map val).sum = u.sum := by simp
rw [← this, ← this]
have {u : Multiset (Fin (n + 1))} (huk : ∀ x ∈ u, x ≤ k) (hu : card u = m) :
(u.map val).sum < (n + 1) := Nat.lt_succ_iff.2 <| hkmn.trans' <| by
rw [← hu, ← card_map]
refine sum_le_card_nsmul (u.map val) k ?_
simpa [le_iff_val_le_val, -val_fin_le, Nat.mod_eq_of_lt, aux hm hkmn] using huk
exact ⟨congr_arg _, CharP.natCast_injOn_Iio _ (n + 1) (this hsA hs) (this htA ht)⟩
/-- **No wrap-around principle**.
The first `k` elements of `Fin (n + 1)` are `m`-Freiman isomorphic to the first `k` elements of `ℕ`
assuming there is no wrap-around. -/
lemma isAddFreimanIso_Iio (hm : m ≠ 0) (hkmn : m * k ≤ n) :
IsAddFreimanIso m (Iio (k : Fin (n + 1))) (Iio k) val := by
obtain _ | k := k
· simp [← bot_eq_zero]
have hkmn' : m * k ≤ n := (Nat.mul_le_mul_left _ k.le_succ).trans hkmn
convert isAddFreimanIso_Iic hm hkmn' using 1 <;> ext x
· simp [lt_iff_val_lt_val, le_iff_val_le_val, -val_fin_le, -val_fin_lt, Nat.mod_eq_of_lt,
aux hm hkmn']
simp_rw [← Nat.cast_add_one]
rw [Fin.val_cast_of_lt (aux hm hkmn), Nat.lt_succ_iff]
· simp [Nat.lt_succ_iff]
end Fin |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/AP/Three/Behrend.lean | import Mathlib.Analysis.Complex.ExponentialBounds
import Mathlib.Analysis.InnerProductSpace.Convex
import Mathlib.Analysis.InnerProductSpace.PiL2
import Mathlib.Combinatorics.Additive.AP.Three.Defs
import Mathlib.Combinatorics.Pigeonhole
/-!
# Behrend's bound on Roth numbers
This file proves Behrend's lower bound on Roth numbers. This says that we can find a subset of
`{1, ..., n}` of size `n / exp (O (sqrt (log n)))` which does not contain arithmetic progressions of
length `3`.
The idea is that the sphere (in the `n`-dimensional Euclidean space) doesn't contain arithmetic
progressions (literally) because the corresponding ball is strictly convex. Thus we can take
integer points on that sphere and map them onto `ℕ` in a way that preserves arithmetic progressions
(`Behrend.map`).
## Main declarations
* `Behrend.sphere`: The intersection of the Euclidean sphere with the positive integer quadrant.
This is the set that we will map on `ℕ`.
* `Behrend.map`: Given a natural number `d`, `Behrend.map d : ℕⁿ → ℕ` reads off the coordinates as
digits in base `d`.
* `Behrend.card_sphere_le_rothNumberNat`: Implicit lower bound on Roth numbers in terms of
`Behrend.sphere`.
* `Behrend.roth_lower_bound`: Behrend's explicit lower bound on Roth numbers.
## References
* [Bryan Gillespie, *Behrend’s Construction*]
(http://www.epsilonsmall.com/resources/behrends-construction/behrend.pdf)
* Behrend, F. A., "On sets of integers which contain no three terms in arithmetical progression"
* [Wikipedia, *Salem-Spencer set*](https://en.wikipedia.org/wiki/Salem–Spencer_set)
## Tags
3AP-free, Salem-Spencer, Behrend construction, arithmetic progression, sphere, strictly convex
-/
assert_not_exists IsConformalMap Conformal
open Nat hiding log
open Finset Metric Real WithLp
open scoped Pointwise
/-- The frontier of a closed strictly convex set only contains trivial arithmetic progressions.
The idea is that an arithmetic progression is contained on a line and the frontier of a strictly
convex set does not contain lines. -/
lemma threeAPFree_frontier {𝕜 E : Type*} [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜]
[TopologicalSpace E]
[AddCommMonoid E] [Module 𝕜 E] {s : Set E} (hs₀ : IsClosed s) (hs₁ : StrictConvex 𝕜 s) :
ThreeAPFree (frontier s) := by
intro a ha b hb c hc habc
obtain rfl : (1 / 2 : 𝕜) • a + (1 / 2 : 𝕜) • c = b := by
rwa [← smul_add, one_div, inv_smul_eq_iff₀ (show (2 : 𝕜) ≠ 0 by simp), two_smul]
have :=
hs₁.eq (hs₀.frontier_subset ha) (hs₀.frontier_subset hc) one_half_pos one_half_pos
(add_halves _) hb.2
simp [this, ← add_smul]
ring_nf
simp
lemma threeAPFree_sphere {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E]
[StrictConvexSpace ℝ E] (x : E) (r : ℝ) : ThreeAPFree (sphere x r) := by
obtain rfl | hr := eq_or_ne r 0
· rw [sphere_zero]
exact threeAPFree_singleton _
· convert threeAPFree_frontier isClosed_closedBall (strictConvex_closedBall ℝ x r)
exact (frontier_closedBall _ hr).symm
namespace Behrend
variable {n d k N : ℕ} {x : Fin n → ℕ}
/-!
### Turning the sphere into 3AP-free set
We define `Behrend.sphere`, the intersection of the $L^2$ sphere with the positive quadrant of
integer points. Because the $L^2$ closed ball is strictly convex, the $L^2$ sphere and
`Behrend.sphere` are 3AP-free (`threeAPFree_sphere`). Then we can turn this set in
`Fin n → ℕ` into a set in `ℕ` using `Behrend.map`, which preserves `ThreeAPFree` because it is
an additive monoid homomorphism.
-/
/-- The box `{0, ..., d - 1}^n` as a `Finset`. -/
def box (n d : ℕ) : Finset (Fin n → ℕ) :=
Fintype.piFinset fun _ => range d
theorem mem_box : x ∈ box n d ↔ ∀ i, x i < d := by simp only [box, Fintype.mem_piFinset, mem_range]
@[simp]
theorem card_box : #(box n d) = d ^ n := by simp [box]
@[simp]
theorem box_zero : box (n + 1) 0 = ∅ := by simp [box]
/-- The intersection of the sphere of radius `√k` with the integer points in the positive
quadrant. -/
def sphere (n d k : ℕ) : Finset (Fin n → ℕ) := {x ∈ box n d | ∑ i, x i ^ 2 = k}
theorem sphere_zero_subset : sphere n d 0 ⊆ 0 := fun x => by simp [sphere, funext_iff]
@[simp]
theorem sphere_zero_right (n k : ℕ) : sphere (n + 1) 0 k = ∅ := by simp [sphere]
theorem sphere_subset_box : sphere n d k ⊆ box n d :=
filter_subset _ _
theorem norm_of_mem_sphere {x : Fin n → ℕ} (hx : x ∈ sphere n d k) :
‖toLp 2 ((↑) ∘ x : Fin n → ℝ)‖ = √↑k := by
rw [EuclideanSpace.norm_eq]
dsimp
simp_rw [abs_cast, ← cast_pow, ← cast_sum, (mem_filter.1 hx).2]
theorem sphere_subset_preimage_metric_sphere : (sphere n d k : Set (Fin n → ℕ)) ⊆
(fun x : Fin n → ℕ => toLp 2 ((↑) ∘ x : Fin n → ℝ)) ⁻¹'
Metric.sphere (0 : PiLp 2 fun _ : Fin n => ℝ) (√↑k) :=
fun x hx => by rw [Set.mem_preimage, mem_sphere_zero_iff_norm, norm_of_mem_sphere hx]
/-- The map that appears in Behrend's bound on Roth numbers. -/
@[simps]
def map (d : ℕ) : (Fin n → ℕ) →+ ℕ where
toFun a := ∑ i, a i * d ^ (i : ℕ)
map_zero' := by simp_rw [Pi.zero_apply, zero_mul, sum_const_zero]
map_add' a b := by simp_rw [Pi.add_apply, add_mul, sum_add_distrib]
theorem map_zero (d : ℕ) (a : Fin 0 → ℕ) : map d a = 0 := by simp [map]
theorem map_succ (a : Fin (n + 1) → ℕ) :
map d a = a 0 + (∑ x : Fin n, a x.succ * d ^ (x : ℕ)) * d := by
simp [map, Fin.sum_univ_succ, _root_.pow_succ, ← mul_assoc, ← sum_mul]
theorem map_succ' (a : Fin (n + 1) → ℕ) : map d a = a 0 + map d (a ∘ Fin.succ) * d :=
map_succ _
theorem map_monotone (d : ℕ) : Monotone (map d : (Fin n → ℕ) → ℕ) := fun x y h => by
dsimp; exact sum_le_sum fun i _ => Nat.mul_le_mul_right _ <| h i
theorem map_mod (a : Fin n.succ → ℕ) : map d a % d = a 0 % d := by
rw [map_succ, Nat.add_mul_mod_self_right]
theorem map_eq_iff {x₁ x₂ : Fin n.succ → ℕ} (hx₁ : ∀ i, x₁ i < d) (hx₂ : ∀ i, x₂ i < d) :
map d x₁ = map d x₂ ↔ x₁ 0 = x₂ 0 ∧ map d (x₁ ∘ Fin.succ) = map d (x₂ ∘ Fin.succ) := by
refine ⟨fun h => ?_, fun h => by rw [map_succ', map_succ', h.1, h.2]⟩
have : x₁ 0 = x₂ 0 := by
rw [← mod_eq_of_lt (hx₁ _), ← map_mod, ← mod_eq_of_lt (hx₂ _), ← map_mod, h]
rw [map_succ, map_succ, this, add_right_inj, mul_eq_mul_right_iff] at h
exact ⟨this, h.resolve_right (pos_of_gt (hx₁ 0)).ne'⟩
theorem map_injOn : {x : Fin n → ℕ | ∀ i, x i < d}.InjOn (map d) := by
intro x₁ hx₁ x₂ hx₂ h
induction n with
| zero => simp [eq_iff_true_of_subsingleton]
| succ n ih =>
ext i
have x := (map_eq_iff hx₁ hx₂).1 h
exact Fin.cases x.1 (congr_fun <| ih (fun _ => hx₁ _) (fun _ => hx₂ _) x.2) i
theorem map_le_of_mem_box (hx : x ∈ box n d) :
map (2 * d - 1) x ≤ ∑ i : Fin n, (d - 1) * (2 * d - 1) ^ (i : ℕ) :=
map_monotone (2 * d - 1) fun _ => Nat.le_sub_one_of_lt <| mem_box.1 hx _
nonrec theorem threeAPFree_sphere : ThreeAPFree (sphere n d k : Set (Fin n → ℕ)) := by
set f : (Fin n → ℕ) →+ EuclideanSpace ℝ (Fin n) :=
{ toFun := fun f => toLp 2 (((↑) : ℕ → ℝ) ∘ f)
map_zero' := PiLp.ext fun _ => cast_zero
map_add' := fun _ _ => PiLp.ext fun _ => cast_add _ _ }
refine ThreeAPFree.of_image (AddMonoidHomClass.isAddFreimanHom f (Set.mapsTo_image _ _))
((toLp_injective 2).comp_injOn cast_injective.comp_left.injOn) (Set.subset_univ _) ?_
refine (threeAPFree_sphere 0 (√↑k)).mono (Set.image_subset_iff.2 fun x => ?_)
rw [Set.mem_preimage, mem_sphere_zero_iff_norm]
exact norm_of_mem_sphere
theorem threeAPFree_image_sphere :
ThreeAPFree ((sphere n d k).image (map (2 * d - 1)) : Set ℕ) := by
rw [coe_image]
apply ThreeAPFree.image' (α := Fin n → ℕ) (β := ℕ) (s := sphere n d k) (map (2 * d - 1))
(map_injOn.mono _) threeAPFree_sphere
rw [Set.add_subset_iff]
rintro a ha b hb i
have hai := mem_box.1 (sphere_subset_box ha) i
have hbi := mem_box.1 (sphere_subset_box hb) i
rw [lt_tsub_iff_right, ← succ_le_iff, two_mul]
exact (add_add_add_comm _ _ 1 1).trans_le (_root_.add_le_add hai hbi)
theorem sum_sq_le_of_mem_box (hx : x ∈ box n d) : ∑ i : Fin n, x i ^ 2 ≤ n * (d - 1) ^ 2 := by
rw [mem_box] at hx
have : ∀ i, x i ^ 2 ≤ (d - 1) ^ 2 := fun i =>
Nat.pow_le_pow_left (Nat.le_sub_one_of_lt (hx i)) _
exact (sum_le_card_nsmul univ _ _ fun i _ => this i).trans (by rw [Finset.card_fin, smul_eq_mul])
theorem sum_eq : (∑ i : Fin n, d * (2 * d + 1) ^ (i : ℕ)) = ((2 * d + 1) ^ n - 1) / 2 := by
refine (Nat.div_eq_of_eq_mul_left zero_lt_two ?_).symm
rw [← sum_range fun i => d * (2 * d + 1) ^ (i : ℕ), ← mul_sum, mul_right_comm, mul_comm d, ←
geom_sum_mul_add, add_tsub_cancel_right, mul_comm]
theorem sum_lt : (∑ i : Fin n, d * (2 * d + 1) ^ (i : ℕ)) < (2 * d + 1) ^ n :=
sum_eq.trans_lt <| (Nat.div_le_self _ 2).trans_lt <| pred_lt (pow_pos (succ_pos _) _).ne'
theorem card_sphere_le_rothNumberNat (n d k : ℕ) :
#(sphere n d k) ≤ rothNumberNat ((2 * d - 1) ^ n) := by
cases n
· dsimp; refine (card_le_univ _).trans_eq ?_; rfl
cases d
· simp
apply threeAPFree_image_sphere.le_rothNumberNat _ _ (card_image_of_injOn _)
· simp only [mem_image, and_imp, forall_exists_index,
sphere, mem_filter]
rintro _ x hx _ rfl
exact (map_le_of_mem_box hx).trans_lt sum_lt
apply map_injOn.mono fun x => ?_
simp only [mem_coe, sphere, mem_filter, mem_box, and_imp, two_mul]
exact fun h _ i => (h i).trans_le le_self_add
/-!
### Optimization
Now that we know how to turn the integer points of any sphere into a 3AP-free set, we find a
sphere containing many integer points by the pigeonhole principle. This gives us an implicit bound
that we then optimize by tweaking the parameters. The (almost) optimal parameters are
`Behrend.nValue` and `Behrend.dValue`.
-/
theorem exists_large_sphere_aux (n d : ℕ) : ∃ k ∈ range (n * (d - 1) ^ 2 + 1),
(↑(d ^ n) / ((n * (d - 1) ^ 2 :) + 1) : ℝ) ≤ #(sphere n d k) := by
refine exists_le_card_fiber_of_nsmul_le_card_of_maps_to (fun x hx => ?_) nonempty_range_add_one ?_
· rw [mem_range, Nat.lt_succ_iff]
exact sum_sq_le_of_mem_box hx
· rw [card_range, nsmul_eq_mul, mul_div_assoc', cast_add_one, mul_div_cancel_left₀, card_box]
exact (cast_add_one_pos _).ne'
theorem exists_large_sphere (n d : ℕ) :
∃ k, ((d ^ n :) / (n * d ^ 2 :) : ℝ) ≤ #(sphere n d k) := by
obtain ⟨k, -, hk⟩ := exists_large_sphere_aux n d
refine ⟨k, ?_⟩
obtain rfl | hn := n.eq_zero_or_pos
· simp
obtain rfl | hd := d.eq_zero_or_pos
· simp
refine (div_le_div_of_nonneg_left ?_ ?_ ?_).trans hk
· exact cast_nonneg _
· exact cast_add_one_pos _
simp only [← le_sub_iff_add_le', cast_mul, ← mul_sub, cast_pow, cast_sub hd, sub_sq, one_pow,
cast_one, mul_one, sub_add, sub_sub_self]
apply one_le_mul_of_one_le_of_one_le
· rwa [one_le_cast]
rw [_root_.le_sub_iff_add_le]
norm_num
exact one_le_cast.2 hd
theorem bound_aux' (n d : ℕ) : ((d ^ n :) / (n * d ^ 2 :) : ℝ) ≤ rothNumberNat ((2 * d - 1) ^ n) :=
let ⟨_, h⟩ := exists_large_sphere n d
h.trans <| cast_le.2 <| card_sphere_le_rothNumberNat _ _ _
theorem bound_aux (hd : d ≠ 0) (hn : 2 ≤ n) :
(d ^ (n - 2 :) / n : ℝ) ≤ rothNumberNat ((2 * d - 1) ^ n) := by
convert bound_aux' n d using 1
rw [cast_mul, cast_pow, mul_comm, ← div_div, pow_sub₀ _ _ hn, ← div_eq_mul_inv, cast_pow]
rwa [cast_ne_zero]
open scoped Filter Topology
open Real
section NumericalBounds
theorem log_two_mul_two_le_sqrt_log_eight : log 2 * 2 ≤ √(log 8) := by
rw [show (8 : ℝ) = 2 ^ 3 by norm_num1, Real.log_pow, Nat.cast_ofNat]
apply le_sqrt_of_sq_le
rw [mul_pow, sq (log 2), mul_assoc, mul_comm]
gcongr
linarith only [log_two_lt_d9.le]
theorem two_div_one_sub_two_div_e_le_eight : 2 / (1 - 2 / exp 1) ≤ 8 := by
rw [div_le_iff₀, mul_sub, mul_one, mul_div_assoc', le_sub_comm, div_le_iff₀ (exp_pos _)]
· linarith [exp_one_gt_d9]
rw [sub_pos, div_lt_one] <;> exact exp_one_gt_d9.trans' (by norm_num)
theorem le_sqrt_log (hN : 4096 ≤ N) : log (2 / (1 - 2 / exp 1)) * (69 / 50) ≤ √(log ↑N) := by
calc
_ ≤ log (2 ^ 3) * (69 / 50) := by
gcongr
· field_simp
simp (disch := positivity) [show 2 < Real.exp 1 from lt_trans (by norm_num1) exp_one_gt_d9]
· norm_num1
exact two_div_one_sub_two_div_e_le_eight
_ ≤ √(log (2 ^ 12)) := by
simp only [Real.log_pow, Nat.cast_ofNat]
apply le_sqrt_of_sq_le
nlinarith [log_two_lt_d9, log_two_gt_d9]
_ ≤ √(log ↑N) := by
gcongr
exact mod_cast hN
theorem exp_neg_two_mul_le {x : ℝ} (hx : 0 < x) : exp (-2 * x) < exp (2 - ⌈x⌉₊) / ⌈x⌉₊ := by
have h₁ := ceil_lt_add_one hx.le
have h₂ : 1 - x ≤ 2 - ⌈x⌉₊ := by linarith
calc
_ ≤ exp (1 - x) / (x + 1) := ?_
_ ≤ exp (2 - ⌈x⌉₊) / (x + 1) := by gcongr
_ < _ := by gcongr
rw [le_div_iff₀ (add_pos hx zero_lt_one), ← le_div_iff₀' (exp_pos _), ← exp_sub, neg_mul,
sub_neg_eq_add, two_mul, sub_add_add_cancel, add_comm _ x]
exact le_trans (le_add_of_nonneg_right zero_le_one) (add_one_le_exp _)
theorem div_lt_floor {x : ℝ} (hx : 2 / (1 - 2 / exp 1) ≤ x) : x / exp 1 < (⌊x / 2⌋₊ : ℝ) := by
apply lt_of_le_of_lt _ (sub_one_lt_floor _)
have : 0 < 1 - 2 / exp 1 := by
rw [sub_pos, div_lt_one (exp_pos _)]
exact lt_of_le_of_lt (by norm_num) exp_one_gt_d9
rwa [le_sub_comm, div_eq_mul_one_div x, div_eq_mul_one_div x, ← mul_sub, div_sub', ←
div_eq_mul_one_div, mul_div_assoc', one_le_div, ← div_le_iff₀ this]
· exact zero_lt_two
· exact two_ne_zero
theorem ceil_lt_mul {x : ℝ} (hx : 50 / 19 ≤ x) : (⌈x⌉₊ : ℝ) < 1.38 * x := by
refine (ceil_lt_add_one <| hx.trans' <| by norm_num).trans_le ?_
rw [← le_sub_iff_add_le', ← sub_one_mul]
have : (1.38 : ℝ) = 69 / 50 := by norm_num
rwa [this, show (69 / 50 - 1 : ℝ) = (50 / 19)⁻¹ by norm_num1, ←
div_eq_inv_mul, one_le_div]
norm_num1
end NumericalBounds
/-- The (almost) optimal value of `n` in `Behrend.bound_aux`. -/
noncomputable def nValue (N : ℕ) : ℕ :=
⌈√(log N)⌉₊
/-- The (almost) optimal value of `d` in `Behrend.bound_aux`. -/
noncomputable def dValue (N : ℕ) : ℕ := ⌊(N : ℝ) ^ (nValue N : ℝ)⁻¹ / 2⌋₊
theorem nValue_pos (hN : 2 ≤ N) : 0 < nValue N :=
ceil_pos.2 <| Real.sqrt_pos.2 <| log_pos <| one_lt_cast.2 <| hN
theorem three_le_nValue (hN : 64 ≤ N) : 3 ≤ nValue N := by
rw [nValue, ← lt_iff_add_one_le, lt_ceil, cast_two]
apply lt_sqrt_of_sq_lt
have : (2 : ℝ) ^ ((6 : ℕ) : ℝ) ≤ N := by
rw [rpow_natCast]
exact (cast_le.2 hN).trans' (by norm_num1)
apply lt_of_lt_of_le _ (log_le_log (rpow_pos_of_pos zero_lt_two _) this)
rw [log_rpow zero_lt_two, ← div_lt_iff₀']
· exact log_two_gt_d9.trans_le' (by norm_num1)
· norm_num1
theorem dValue_pos (hN₃ : 8 ≤ N) : 0 < dValue N := by
have hN₀ : 0 < (N : ℝ) := cast_pos.2 (succ_pos'.trans_le hN₃)
rw [dValue, floor_pos, ← log_le_log_iff zero_lt_one, log_one, log_div _ two_ne_zero, log_rpow hN₀,
inv_mul_eq_div, sub_nonneg, le_div_iff₀]
· have : (nValue N : ℝ) ≤ 2 * √(log N) := by
apply (ceil_lt_add_one <| sqrt_nonneg _).le.trans
rw [two_mul, add_le_add_iff_left]
apply le_sqrt_of_sq_le
rw [one_pow, le_log_iff_exp_le hN₀]
exact (exp_one_lt_d9.le.trans <| by norm_num).trans (cast_le.2 hN₃)
apply (mul_le_mul_of_nonneg_left this <| log_nonneg one_le_two).trans _
rw [← mul_assoc, ← le_div_iff₀ (Real.sqrt_pos.2 <| log_pos <| one_lt_cast.2 _), div_sqrt]
· apply log_two_mul_two_le_sqrt_log_eight.trans
apply Real.sqrt_le_sqrt
exact log_le_log (by simp) (mod_cast hN₃)
exact hN₃.trans_lt' (by simp)
· exact cast_pos.2 (nValue_pos <| hN₃.trans' <| by simp)
· exact (rpow_pos_of_pos hN₀ _).ne'
· exact div_pos (rpow_pos_of_pos hN₀ _) zero_lt_two
theorem le_N (hN : 2 ≤ N) : (2 * dValue N - 1) ^ nValue N ≤ N := by
have : (2 * dValue N - 1) ^ nValue N ≤ (2 * dValue N) ^ nValue N :=
Nat.pow_le_pow_left (Nat.sub_le _ _) _
apply this.trans
suffices ((2 * dValue N) ^ nValue N : ℝ) ≤ N from mod_cast this
suffices i : (2 * dValue N : ℝ) ≤ (N : ℝ) ^ (nValue N : ℝ)⁻¹ by
rw [← rpow_natCast]
apply (rpow_le_rpow (mul_nonneg zero_le_two (cast_nonneg _)) i (cast_nonneg _)).trans
rw [← rpow_mul (cast_nonneg _), inv_mul_cancel₀, rpow_one]
rw [cast_ne_zero]
apply (nValue_pos hN).ne'
rw [← le_div_iff₀']
· exact floor_le (div_nonneg (rpow_nonneg (cast_nonneg _) _) zero_le_two)
apply zero_lt_two
theorem bound (hN : 4096 ≤ N) : (N : ℝ) ^ (nValue N : ℝ)⁻¹ / exp 1 < dValue N := by
apply div_lt_floor _
rw [← log_le_log_iff, log_rpow, mul_comm, ← div_eq_mul_inv, nValue]
· grw [ceil_lt_mul]
· rw [mul_comm, ← div_div, div_sqrt, le_div_iff₀]
· norm_num [le_sqrt_log hN]
· norm_num1
· rw [cast_pos, lt_ceil, cast_zero, Real.sqrt_pos]
refine log_pos ?_
rw [one_lt_cast]
exact hN.trans_lt' (by norm_num1)
apply le_sqrt_of_sq_le
have : (12 : ℕ) * log 2 ≤ log N := by
rw [← log_rpow zero_lt_two, rpow_natCast]
exact log_le_log (by positivity) (mod_cast hN)
refine le_trans ?_ this
rw [← div_le_iff₀']
· exact log_two_gt_d9.le.trans' (by norm_num1)
· norm_num1
· rw [cast_pos]
exact hN.trans_lt' (by norm_num1)
· refine div_pos zero_lt_two ?_
rw [sub_pos, div_lt_one (exp_pos _)]
exact lt_of_le_of_lt (by norm_num1) exp_one_gt_d9
positivity
theorem roth_lower_bound_explicit (hN : 4096 ≤ N) :
(N : ℝ) * exp (-4 * √(log N)) < rothNumberNat N := by
let n := nValue N
have hn : 0 < (n : ℝ) := cast_pos.2 (nValue_pos <| hN.trans' <| by norm_num1)
have hd : 0 < dValue N := dValue_pos (hN.trans' <| by norm_num1)
have hN₀ : 0 < (N : ℝ) := cast_pos.2 (hN.trans' <| by norm_num1)
have hn₂ : 2 < n := three_le_nValue <| hN.trans' <| by norm_num1
have : (2 * dValue N - 1) ^ n ≤ N := le_N (hN.trans' <| by norm_num1)
calc
_ ≤ (N ^ (nValue N : ℝ)⁻¹ / rexp 1 : ℝ) ^ (n - 2) / n := ?_
_ < _ := by gcongr; exacts [(tsub_pos_of_lt hn₂).ne', bound hN]
_ ≤ rothNumberNat ((2 * dValue N - 1) ^ n) := bound_aux hd.ne' hn₂.le
_ ≤ rothNumberNat N := mod_cast rothNumberNat.mono this
rw [← rpow_natCast, div_rpow (rpow_nonneg hN₀.le _) (exp_pos _).le, ← rpow_mul hN₀.le,
inv_mul_eq_div, cast_sub hn₂.le, cast_two, same_sub_div hn.ne', exp_one_rpow,
div_div, rpow_sub hN₀, rpow_one, div_div, div_eq_mul_inv]
gcongr _ * ?_
rw [mul_inv, mul_inv, ← exp_neg, ← rpow_neg (cast_nonneg _), neg_sub, ← div_eq_mul_inv]
have : exp (-4 * √(log N)) = exp (-2 * √(log N)) * exp (-2 * √(log N)) := by
rw [← exp_add, ← add_mul]
norm_num
rw [this]
gcongr
· rw [← le_log_iff_exp_le (rpow_pos_of_pos hN₀ _), log_rpow hN₀, ← le_div_iff₀, mul_div_assoc,
div_sqrt, neg_mul, neg_le_neg_iff, div_mul_eq_mul_div, div_le_iff₀ hn]
· gcongr
apply le_ceil
refine Real.sqrt_pos.2 (log_pos ?_)
rw [one_lt_cast]
exact hN.trans_lt' (by norm_num1)
· refine (exp_neg_two_mul_le <| Real.sqrt_pos.2 <| log_pos ?_).le
rw [one_lt_cast]
exact hN.trans_lt' (by norm_num1)
theorem exp_four_lt : exp 4 < 64 := by
rw [show (64 : ℝ) = 2 ^ ((6 : ℕ) : ℝ) by rw [rpow_natCast]; norm_num1,
← lt_log_iff_exp_lt (rpow_pos_of_pos zero_lt_two _), log_rpow zero_lt_two, ← div_lt_iff₀']
· exact log_two_gt_d9.trans_le' (by norm_num1)
· simp
theorem four_zero_nine_six_lt_exp_sixteen : 4096 < exp 16 := by
rw [← log_lt_iff_lt_exp (show (0 : ℝ) < 4096 by simp), show (4096 : ℝ) = 2 ^ 12 by norm_cast,
← rpow_natCast, log_rpow zero_lt_two, cast_ofNat]
linarith [log_two_lt_d9]
theorem lower_bound_le_one' (hN : 2 ≤ N) (hN' : N ≤ 4096) :
(N : ℝ) * exp (-4 * √(log N)) ≤ 1 := by
rw [← log_le_log_iff (mul_pos (cast_pos.2 (zero_lt_two.trans_le hN)) (exp_pos _)) zero_lt_one,
log_one, log_mul (cast_pos.2 (zero_lt_two.trans_le hN)).ne' (exp_pos _).ne', log_exp, neg_mul, ←
sub_eq_add_neg, sub_nonpos, ←
div_le_iff₀ (Real.sqrt_pos.2 <| log_pos <| one_lt_cast.2 <| one_lt_two.trans_le hN), div_sqrt,
sqrt_le_left zero_le_four, log_le_iff_le_exp (cast_pos.2 (zero_lt_two.trans_le hN))]
norm_num1
apply le_trans _ four_zero_nine_six_lt_exp_sixteen.le
exact mod_cast hN'
theorem lower_bound_le_one (hN : 1 ≤ N) (hN' : N ≤ 4096) :
(N : ℝ) * exp (-4 * √(log N)) ≤ 1 := by
obtain rfl | hN := hN.eq_or_lt
· simp
· exact lower_bound_le_one' hN hN'
theorem roth_lower_bound : (N : ℝ) * exp (-4 * √(log N)) ≤ rothNumberNat N := by
obtain rfl | hN := Nat.eq_zero_or_pos N
· simp
obtain h₁ | h₁ := le_or_gt 4096 N
· exact (roth_lower_bound_explicit h₁).le
· apply (lower_bound_le_one hN h₁.le).trans
simpa using rothNumberNat.monotone hN
end Behrend |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/AP/Three/Defs.lean | import Mathlib.Algebra.GroupWithZero.Action.Defs
import Mathlib.Algebra.Order.Interval.Finset.Basic
import Mathlib.Combinatorics.Additive.FreimanHom
import Mathlib.Order.Interval.Finset.Fin
import Mathlib.Algebra.Group.Pointwise.Set.Scalar
/-!
# Sets without arithmetic progressions of length three and Roth numbers
This file defines sets without arithmetic progressions of length three, aka 3AP-free sets, and the
Roth number of a set.
The corresponding notion, sets without geometric progressions of length three, are called 3GP-free
sets.
The Roth number of a finset is the size of its biggest 3AP-free subset. This is a more general
definition than the one often found in mathematical literature, where the `n`-th Roth number is
the size of the biggest 3AP-free subset of `{0, ..., n - 1}`.
## Main declarations
* `ThreeGPFree`: Predicate for a set to be 3GP-free.
* `ThreeAPFree`: Predicate for a set to be 3AP-free.
* `mulRothNumber`: The multiplicative Roth number of a finset.
* `addRothNumber`: The additive Roth number of a finset.
* `rothNumberNat`: The Roth number of a natural, namely `addRothNumber (Finset.range n)`.
## TODO
* Can `threeAPFree_iff_eq_right` be made more general?
* Generalize `ThreeGPFree.image` to Freiman homs
## References
* [Wikipedia, *Salem-Spencer set*](https://en.wikipedia.org/wiki/Salem–Spencer_set)
## Tags
3AP-free, Salem-Spencer, Roth, arithmetic progression, average, three-free
-/
assert_not_exists Field Ideal TwoSidedIdeal
open Finset Function
open scoped Pointwise
variable {F α β : Type*}
section ThreeAPFree
open Set
section Monoid
variable [Monoid α] [Monoid β] (s t : Set α)
/-- A set is **3GP-free** if it does not contain any non-trivial geometric progression of length
three. -/
@[to_additive /-- A set is **3AP-free** if it does not contain any non-trivial arithmetic
progression of length three.
This is also sometimes called a **non-averaging set** or **Salem-Spencer set**. -/]
def ThreeGPFree : Prop := ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → ∀ ⦃c⦄, c ∈ s → a * c = b * b → a = b
/-- Whether a given finset is 3GP-free is decidable. -/
@[to_additive /-- Whether a given finset is 3AP-free is decidable. -/]
instance ThreeGPFree.instDecidable [DecidableEq α] {s : Finset α} :
Decidable (ThreeGPFree (s : Set α)) :=
decidable_of_iff (∀ a ∈ s, ∀ b ∈ s, ∀ c ∈ s, a * c = b * b → a = b) Iff.rfl
variable {s t}
@[to_additive]
theorem ThreeGPFree.mono (h : t ⊆ s) (hs : ThreeGPFree s) : ThreeGPFree t :=
fun _ ha _ hb _ hc ↦ hs (h ha) (h hb) (h hc)
@[to_additive (attr := simp)]
theorem threeGPFree_empty : ThreeGPFree (∅ : Set α) := fun _ _ _ ha => ha.elim
@[to_additive]
theorem Set.Subsingleton.threeGPFree (hs : s.Subsingleton) : ThreeGPFree s :=
fun _ ha _ hb _ _ _ ↦ hs ha hb
@[to_additive (attr := simp)]
theorem threeGPFree_singleton (a : α) : ThreeGPFree ({a} : Set α) :=
subsingleton_singleton.threeGPFree
@[to_additive ThreeAPFree.prod]
theorem ThreeGPFree.prod {t : Set β} (hs : ThreeGPFree s) (ht : ThreeGPFree t) :
ThreeGPFree (s ×ˢ t) := fun _ ha _ hb _ hc h ↦
Prod.ext (hs ha.1 hb.1 hc.1 (Prod.ext_iff.1 h).1) (ht ha.2 hb.2 hc.2 (Prod.ext_iff.1 h).2)
@[to_additive]
theorem threeGPFree_pi {ι : Type*} {α : ι → Type*} [∀ i, Monoid (α i)] {s : ∀ i, Set (α i)}
(hs : ∀ i, ThreeGPFree (s i)) : ThreeGPFree ((univ : Set ι).pi s) :=
fun _ ha _ hb _ hc h ↦
funext fun i => hs i (ha i trivial) (hb i trivial) (hc i trivial) <| congr_fun h i
end Monoid
section CommMonoid
variable [CommMonoid α] [CommMonoid β] {s A : Set α} {t : Set β} {f : α → β}
/-- Geometric progressions of length three are reflected under `2`-Freiman homomorphisms. -/
@[to_additive
/-- Arithmetic progressions of length three are reflected under `2`-Freiman homomorphisms. -/]
lemma ThreeGPFree.of_image (hf : IsMulFreimanHom 2 s t f) (hf' : s.InjOn f) (hAs : A ⊆ s)
(hA : ThreeGPFree (f '' A)) : ThreeGPFree A :=
fun _ ha _ hb _ hc habc ↦ hf' (hAs ha) (hAs hb) <| hA (mem_image_of_mem _ ha)
(mem_image_of_mem _ hb) (mem_image_of_mem _ hc) <|
hf.mul_eq_mul (hAs ha) (hAs hc) (hAs hb) (hAs hb) habc
/-- Geometric progressions of length three are unchanged under `2`-Freiman isomorphisms. -/
@[to_additive
/-- Arithmetic progressions of length three are unchanged under `2`-Freiman isomorphisms. -/]
lemma threeGPFree_image (hf : IsMulFreimanIso 2 s t f) (hAs : A ⊆ s) :
ThreeGPFree (f '' A) ↔ ThreeGPFree A := by
rw [ThreeGPFree, ThreeGPFree]
have := (hf.bijOn.injOn.mono hAs).bijOn_image (f := f)
simp +contextual only
[((hf.bijOn.injOn.mono hAs).bijOn_image (f := f)).forall,
hf.mul_eq_mul (hAs _) (hAs _) (hAs _) (hAs _), this.injOn.eq_iff]
@[to_additive] alias ⟨_, ThreeGPFree.image⟩ := threeGPFree_image
/-- Geometric progressions of length three are reflected under `2`-Freiman homomorphisms. -/
@[to_additive
/-- Arithmetic progressions of length three are reflected under `2`-Freiman homomorphisms. -/]
lemma IsMulFreimanHom.threeGPFree (hf : IsMulFreimanHom 2 s t f) (hf' : s.InjOn f)
(ht : ThreeGPFree t) : ThreeGPFree s :=
(ht.mono hf.mapsTo.image_subset).of_image hf hf' subset_rfl
/-- Geometric progressions of length three are unchanged under `2`-Freiman isomorphisms. -/
@[to_additive
/-- Arithmetic progressions of length three are unchanged under `2`-Freiman isomorphisms. -/]
lemma IsMulFreimanIso.threeGPFree_congr (hf : IsMulFreimanIso 2 s t f) :
ThreeGPFree s ↔ ThreeGPFree t := by
rw [← threeGPFree_image hf subset_rfl, hf.bijOn.image_eq]
/-- Geometric progressions of length three are preserved under semigroup homomorphisms. -/
@[to_additive
/-- Arithmetic progressions of length three are preserved under semigroup homomorphisms. -/]
theorem ThreeGPFree.image' [FunLike F α β] [MulHomClass F α β] (f : F) (hf : (s * s).InjOn f)
(h : ThreeGPFree s) : ThreeGPFree (f '' s) := by
rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ _ ⟨c, hc, rfl⟩ habc
rw [h ha hb hc (hf (mul_mem_mul ha hc) (mul_mem_mul hb hb) <| by rwa [map_mul, map_mul])]
end CommMonoid
section CancelCommMonoid
variable [CommMonoid α] [IsCancelMul α] {s : Set α} {a : α}
@[to_additive] lemma ThreeGPFree.eq_right (hs : ThreeGPFree s) :
∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → ∀ ⦃c⦄, c ∈ s → a * c = b * b → b = c := by
rintro a ha b hb c hc habc
obtain rfl := hs ha hb hc habc
simpa using habc.symm
@[to_additive] lemma threeGPFree_insert :
ThreeGPFree (insert a s) ↔ ThreeGPFree s ∧
(∀ ⦃b⦄, b ∈ s → ∀ ⦃c⦄, c ∈ s → a * c = b * b → a = b) ∧
∀ ⦃b⦄, b ∈ s → ∀ ⦃c⦄, c ∈ s → b * c = a * a → b = a := by
refine ⟨fun hs ↦ ⟨hs.mono (subset_insert _ _),
fun b hb c hc ↦ hs (Or.inl rfl) (Or.inr hb) (Or.inr hc),
fun b hb c hc ↦ hs (Or.inr hb) (Or.inl rfl) (Or.inr hc)⟩, ?_⟩
rintro ⟨hs, ha, ha'⟩ b hb c hc d hd h
rw [mem_insert_iff] at hb hc hd
obtain rfl | hb := hb <;> obtain rfl | hc := hc
· rfl
all_goals obtain rfl | hd := hd
· exact (ha' hc hc h.symm).symm
· exact ha hc hd h
· exact mul_right_cancel h
· exact ha' hb hd h
· obtain rfl := ha hc hb ((mul_comm _ _).trans h)
exact ha' hb hc h
· exact hs hb hc hd h
@[to_additive]
theorem ThreeGPFree.smul_set (hs : ThreeGPFree s) : ThreeGPFree (a • s) := by
rintro _ ⟨b, hb, rfl⟩ _ ⟨c, hc, rfl⟩ _ ⟨d, hd, rfl⟩ h
exact congr_arg (a • ·) <| hs hb hc hd <| by simpa [mul_mul_mul_comm _ _ a] using h
@[to_additive] lemma threeGPFree_smul_set : ThreeGPFree (a • s) ↔ ThreeGPFree s where
mp hs b hb c hc d hd h := mul_left_cancel
(hs (mem_image_of_mem _ hb) (mem_image_of_mem _ hc) (mem_image_of_mem _ hd) <| by
rw [mul_mul_mul_comm, smul_eq_mul, smul_eq_mul, mul_mul_mul_comm, h])
mpr := ThreeGPFree.smul_set
end CancelCommMonoid
section OrderedCancelCommMonoid
variable [CommMonoid α] [PartialOrder α] [IsOrderedCancelMonoid α] {s : Set α} {a : α}
@[to_additive]
theorem threeGPFree_insert_of_lt (hs : ∀ i ∈ s, i < a) :
ThreeGPFree (insert a s) ↔
ThreeGPFree s ∧ ∀ ⦃b⦄, b ∈ s → ∀ ⦃c⦄, c ∈ s → a * c = b * b → a = b := by
refine threeGPFree_insert.trans ?_
rw [← and_assoc]
exact and_iff_left fun b hb c hc h => ((mul_lt_mul_of_lt_of_lt (hs _ hb) (hs _ hc)).ne h).elim
end OrderedCancelCommMonoid
section CancelCommMonoidWithZero
variable [CancelCommMonoidWithZero α] [NoZeroDivisors α] {s : Set α} {a : α}
lemma ThreeGPFree.smul_set₀ (hs : ThreeGPFree s) (ha : a ≠ 0) : ThreeGPFree (a • s) := by
rintro _ ⟨b, hb, rfl⟩ _ ⟨c, hc, rfl⟩ _ ⟨d, hd, rfl⟩ h
exact congr_arg (a • ·) <| hs hb hc hd <| by simpa [mul_mul_mul_comm _ _ a, ha] using h
theorem threeGPFree_smul_set₀ (ha : a ≠ 0) : ThreeGPFree (a • s) ↔ ThreeGPFree s :=
⟨fun hs b hb c hc d hd h ↦
mul_left_cancel₀ ha
(hs (Set.mem_image_of_mem _ hb) (Set.mem_image_of_mem _ hc) (Set.mem_image_of_mem _ hd) <| by
rw [smul_eq_mul, smul_eq_mul, mul_mul_mul_comm, h, mul_mul_mul_comm]),
fun hs => hs.smul_set₀ ha⟩
end CancelCommMonoidWithZero
section Nat
theorem threeAPFree_iff_eq_right {s : Set ℕ} :
ThreeAPFree s ↔ ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → ∀ ⦃c⦄, c ∈ s → a + c = b + b → a = c := by
refine forall₄_congr fun a _ha b hb => forall₃_congr fun c hc habc => ⟨?_, ?_⟩
· rintro rfl
exact (add_left_cancel habc).symm
· rintro rfl
simp_rw [← two_mul] at habc
exact mul_left_cancel₀ two_ne_zero habc
end Nat
end ThreeAPFree
open Finset
section RothNumber
variable [DecidableEq α]
section Monoid
variable [Monoid α] [DecidableEq β] [Monoid β] (s t : Finset α)
/-- The multiplicative Roth number of a finset is the cardinality of its biggest 3GP-free subset. -/
@[to_additive /-- The additive Roth number of a finset is the cardinality of its biggest 3AP-free
subset.
The usual Roth number corresponds to `addRothNumber (Finset.range n)`, see `rothNumberNat`. -/]
def mulRothNumber : Finset α →o ℕ :=
⟨fun s ↦ Nat.findGreatest (fun m ↦ ∃ t ⊆ s, #t = m ∧ ThreeGPFree (t : Set α)) #s, by
rintro t u htu
refine Nat.findGreatest_mono (fun m => ?_) (card_le_card htu)
rintro ⟨v, hvt, hv⟩
exact ⟨v, hvt.trans htu, hv⟩⟩
@[to_additive]
theorem mulRothNumber_le : mulRothNumber s ≤ #s := Nat.findGreatest_le #s
@[to_additive]
theorem mulRothNumber_spec :
∃ t ⊆ s, #t = mulRothNumber s ∧ ThreeGPFree (t : Set α) :=
Nat.findGreatest_spec (P := fun m ↦ ∃ t ⊆ s, #t = m ∧ ThreeGPFree (t : Set α))
(Nat.zero_le _) ⟨∅, empty_subset _, card_empty, by norm_cast; exact threeGPFree_empty⟩
variable {s t} {n : ℕ}
@[to_additive]
theorem ThreeGPFree.le_mulRothNumber (hs : ThreeGPFree (s : Set α)) (h : s ⊆ t) :
#s ≤ mulRothNumber t :=
Nat.le_findGreatest (card_le_card h) ⟨s, h, rfl, hs⟩
@[to_additive]
theorem ThreeGPFree.mulRothNumber_eq (hs : ThreeGPFree (s : Set α)) :
mulRothNumber s = #s :=
(mulRothNumber_le _).antisymm <| hs.le_mulRothNumber <| Subset.refl _
@[to_additive (attr := simp)]
theorem mulRothNumber_empty : mulRothNumber (∅ : Finset α) = 0 :=
Nat.eq_zero_of_le_zero <| (mulRothNumber_le _).trans card_empty.le
@[to_additive (attr := simp)]
theorem mulRothNumber_singleton (a : α) : mulRothNumber ({a} : Finset α) = 1 := by
refine ThreeGPFree.mulRothNumber_eq ?_
rw [coe_singleton]
exact threeGPFree_singleton a
@[to_additive]
theorem mulRothNumber_union_le (s t : Finset α) :
mulRothNumber (s ∪ t) ≤ mulRothNumber s + mulRothNumber t :=
let ⟨u, hus, hcard, hu⟩ := mulRothNumber_spec (s ∪ t)
calc
mulRothNumber (s ∪ t) = #u := hcard.symm
_ = #(u ∩ s ∪ u ∩ t) := by rw [← inter_union_distrib_left, inter_eq_left.2 hus]
_ ≤ #(u ∩ s) + #(u ∩ t) := card_union_le _ _
_ ≤ mulRothNumber s + mulRothNumber t := _root_.add_le_add
((hu.mono inter_subset_left).le_mulRothNumber inter_subset_right)
((hu.mono inter_subset_left).le_mulRothNumber inter_subset_right)
@[to_additive]
theorem le_mulRothNumber_product (s : Finset α) (t : Finset β) :
mulRothNumber s * mulRothNumber t ≤ mulRothNumber (s ×ˢ t) := by
obtain ⟨u, hus, hucard, hu⟩ := mulRothNumber_spec s
obtain ⟨v, hvt, hvcard, hv⟩ := mulRothNumber_spec t
rw [← hucard, ← hvcard, ← card_product]
refine ThreeGPFree.le_mulRothNumber ?_ (product_subset_product hus hvt)
rw [coe_product]
exact hu.prod hv
@[to_additive]
theorem mulRothNumber_lt_of_forall_not_threeGPFree
(h : ∀ t ∈ powersetCard n s, ¬ThreeGPFree ((t : Finset α) : Set α)) :
mulRothNumber s < n := by
obtain ⟨t, hts, hcard, ht⟩ := mulRothNumber_spec s
rw [← hcard, ← not_le]
intro hn
obtain ⟨u, hut, rfl⟩ := exists_subset_card_eq hn
exact h _ (mem_powersetCard.2 ⟨hut.trans hts, rfl⟩) (ht.mono hut)
end Monoid
section CommMonoid
variable [CommMonoid α] [CommMonoid β] [DecidableEq β] {A : Finset α} {B : Finset β} {f : α → β}
/-- Arithmetic progressions can be pushed forward along bijective 2-Freiman homs. -/
@[to_additive /-- Arithmetic progressions can be pushed forward along bijective 2-Freiman homs. -/]
lemma IsMulFreimanHom.mulRothNumber_mono (hf : IsMulFreimanHom 2 A B f) (hf' : Set.BijOn f A B) :
mulRothNumber B ≤ mulRothNumber A := by
obtain ⟨s, hsB, hcard, hs⟩ := mulRothNumber_spec B
have hsA : invFunOn f A '' s ⊆ A :=
(hf'.surjOn.mapsTo_invFunOn.mono (coe_subset.2 hsB) Subset.rfl).image_subset
have hfsA : Set.SurjOn f A s := hf'.surjOn.mono Subset.rfl (coe_subset.2 hsB)
rw [← hcard, ← s.card_image_of_injOn ((invFunOn_injOn_image f _).mono hfsA)]
refine ThreeGPFree.le_mulRothNumber ?_ (mod_cast hsA)
rw [coe_image]
simpa using (hf.subset hsA hfsA.bijOn_subset.mapsTo).threeGPFree (hf'.injOn.mono hsA) hs
/-- Arithmetic progressions are preserved under 2-Freiman isos. -/
@[to_additive /-- Arithmetic progressions are preserved under 2-Freiman isos. -/]
lemma IsMulFreimanIso.mulRothNumber_congr (hf : IsMulFreimanIso 2 A B f) :
mulRothNumber A = mulRothNumber B := by
refine le_antisymm ?_ (hf.isMulFreimanHom.mulRothNumber_mono hf.bijOn)
obtain ⟨s, hsA, hcard, hs⟩ := mulRothNumber_spec A
rw [← coe_subset] at hsA
have hfs : Set.InjOn f s := hf.bijOn.injOn.mono hsA
have := (hf.subset hsA hfs.bijOn_image).threeGPFree_congr.1 hs
rw [← coe_image] at this
rw [← hcard, ← Finset.card_image_of_injOn hfs]
refine this.le_mulRothNumber ?_
rw [← coe_subset, coe_image]
exact (hf.bijOn.mapsTo.mono hsA Subset.rfl).image_subset
end CommMonoid
section CancelCommMonoid
variable [CancelCommMonoid α] (s : Finset α) (a : α)
@[to_additive (attr := simp)]
theorem mulRothNumber_map_mul_left :
mulRothNumber (s.map <| mulLeftEmbedding a) = mulRothNumber s := by
refine le_antisymm ?_ ?_
· obtain ⟨u, hus, hcard, hu⟩ := mulRothNumber_spec (s.map <| mulLeftEmbedding a)
rw [subset_map_iff] at hus
obtain ⟨u, hus, rfl⟩ := hus
rw [coe_map] at hu
rw [← hcard, card_map]
exact (threeGPFree_smul_set.1 hu).le_mulRothNumber hus
· obtain ⟨u, hus, hcard, hu⟩ := mulRothNumber_spec s
have h : ThreeGPFree (u.map <| mulLeftEmbedding a : Set α) := by rw [coe_map]; exact hu.smul_set
convert h.le_mulRothNumber (map_subset_map.2 hus) using 1
rw [card_map, hcard]
@[to_additive (attr := simp)]
theorem mulRothNumber_map_mul_right :
mulRothNumber (s.map <| mulRightEmbedding a) = mulRothNumber s := by
rw [← mulLeftEmbedding_eq_mulRightEmbedding, mulRothNumber_map_mul_left s a]
end CancelCommMonoid
end RothNumber
section rothNumberNat
variable {k n : ℕ}
/-- The Roth number of a natural `N` is the largest integer `m` for which there is a subset of
`range N` of size `m` with no arithmetic progression of length 3.
Trivially, `rothNumberNat N ≤ N`, but Roth's theorem (proved in 1953) shows that
`rothNumberNat N = o(N)` and the construction by Behrend gives a lower bound of the form
`N * exp(-C sqrt(log(N))) ≤ rothNumberNat N`.
A significant refinement of Roth's theorem by Bloom and Sisask announced in 2020 gives
`rothNumberNat N = O(N / (log N)^(1+c))` for an absolute constant `c`. -/
def rothNumberNat : ℕ →o ℕ :=
⟨fun n => addRothNumber (range n), addRothNumber.mono.comp range_mono⟩
theorem rothNumberNat_def (n : ℕ) : rothNumberNat n = addRothNumber (range n) :=
rfl
theorem rothNumberNat_le (N : ℕ) : rothNumberNat N ≤ N :=
(addRothNumber_le _).trans (card_range _).le
theorem rothNumberNat_spec (n : ℕ) :
∃ t ⊆ range n, #t = rothNumberNat n ∧ ThreeAPFree (t : Set ℕ) :=
addRothNumber_spec _
/-- A verbose specialization of `threeAPFree.le_addRothNumber`, sometimes convenient in
practice. -/
theorem ThreeAPFree.le_rothNumberNat (s : Finset ℕ) (hs : ThreeAPFree (s : Set ℕ))
(hsn : ∀ x ∈ s, x < n) (hsk : #s = k) : k ≤ rothNumberNat n :=
hsk.ge.trans <| hs.le_addRothNumber fun x hx => mem_range.2 <| hsn x hx
/-- The Roth number is a subadditive function. Note that by Fekete's lemma this shows that
the limit `rothNumberNat N / N` exists, but Roth's theorem gives the stronger result that this
limit is actually `0`. -/
theorem rothNumberNat_add_le (M N : ℕ) :
rothNumberNat (M + N) ≤ rothNumberNat M + rothNumberNat N := by
simp_rw [rothNumberNat_def]
rw [range_add_eq_union, ← addRothNumber_map_add_left (range N) M]
exact addRothNumber_union_le _ _
@[simp]
theorem rothNumberNat_zero : rothNumberNat 0 = 0 :=
rfl
theorem addRothNumber_Ico (a b : ℕ) : addRothNumber (Ico a b) = rothNumberNat (b - a) := by
obtain h | h := le_total b a
· rw [Nat.sub_eq_zero_of_le h, Ico_eq_empty_of_le h, rothNumberNat_zero, addRothNumber_empty]
convert addRothNumber_map_add_left _ a
rw [range_eq_Ico, map_eq_image]
convert (image_add_left_Ico 0 (b - a) _).symm
exact (add_tsub_cancel_of_le h).symm
open Fin.NatCast in -- TODO: should this be refactored to avoid needing the coercion?
lemma Fin.addRothNumber_eq_rothNumberNat (hkn : 2 * k ≤ n) :
addRothNumber (Iio k : Finset (Fin n.succ)) = rothNumberNat k :=
IsAddFreimanIso.addRothNumber_congr <| mod_cast isAddFreimanIso_Iio two_ne_zero hkn
open Fin.CommRing in -- TODO: should this be refactored to avoid needing the coercion?
lemma Fin.addRothNumber_le_rothNumberNat (k n : ℕ) (hkn : k ≤ n) :
addRothNumber (Iio k : Finset (Fin n.succ)) ≤ rothNumberNat k := by
suffices h : Set.BijOn (Nat.cast : ℕ → Fin n.succ) (range k) (Iio k : Finset (Fin n.succ)) by
exact (AddMonoidHomClass.isAddFreimanHom (Nat.castRingHom _) h.mapsTo).addRothNumber_mono h
refine ⟨?_, (CharP.natCast_injOn_Iio _ n.succ).mono (by simp; cutsat), ?_⟩
· simpa using fun x ↦ natCast_strictMono hkn
simp only [Set.SurjOn, coe_Iio, Set.subset_def, Set.mem_Iio, Set.mem_image, lt_iff_val_lt_val,
val_cast_of_lt, Nat.lt_succ_iff.2 hkn, coe_range]
exact fun x hx ↦ ⟨x, hx, by simp⟩
end rothNumberNat |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/Corner/Defs.lean | import Mathlib.Combinatorics.Additive.FreimanHom
/-!
# Corners
This file defines corners, namely triples of the form `(x, y), (x, y + d), (x + d, y)`, and the
property of being corner-free.
## References
* [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
* [Wikipedia, *Corners theorem*](https://en.wikipedia.org/wiki/Corners_theorem)
-/
assert_not_exists Field Ideal TwoSidedIdeal
open Set
variable {G H : Type*}
section AddCommMonoid
variable [AddCommMonoid G] [AddCommMonoid H] {A B : Set (G × G)} {s : Set G} {t : Set H} {f : G → H}
{x₁ y₁ x₂ y₂ : G}
/-- A **corner** of a set `A` in an abelian group is a triple of points of the form
`(x, y), (x + d, y), (x, y + d)`. It is **nontrivial** if `d ≠ 0`.
Here we define it as triples `(x₁, y₁), (x₂, y₁), (x₁, y₂)` where `x₁ + y₂ = x₂ + y₁` in order for
the definition to make sense in commutative monoids, the motivating example being `ℕ`. -/
@[mk_iff]
structure IsCorner (A : Set (G × G)) (x₁ y₁ x₂ y₂ : G) : Prop where
fst_fst_mem : (x₁, y₁) ∈ A
fst_snd_mem : (x₁, y₂) ∈ A
snd_fst_mem : (x₂, y₁) ∈ A
add_eq_add : x₁ + y₂ = x₂ + y₁
/-- A **corner-free set** in an abelian group is a set containing no non-trivial corner. -/
def IsCornerFree (A : Set (G × G)) : Prop := ∀ ⦃x₁ y₁ x₂ y₂⦄, IsCorner A x₁ y₁ x₂ y₂ → x₁ = x₂
/-- A convenient restatement of corner-freeness in terms of an ambient product set. -/
lemma isCornerFree_iff (hAs : A ⊆ s ×ˢ s) :
IsCornerFree A ↔ ∀ ⦃x₁⦄, x₁ ∈ s → ∀ ⦃y₁⦄, y₁ ∈ s → ∀ ⦃x₂⦄, x₂ ∈ s → ∀ ⦃y₂⦄, y₂ ∈ s →
IsCorner A x₁ y₁ x₂ y₂ → x₁ = x₂ where
mp hA _x₁ _ _y₁ _ _x₂ _ _y₂ _ hxy := hA hxy
mpr hA _x₁ _y₁ _x₂ _y₂ hxy := hA (hAs hxy.fst_fst_mem).1 (hAs hxy.fst_fst_mem).2
(hAs hxy.snd_fst_mem).1 (hAs hxy.fst_snd_mem).2 hxy
lemma IsCorner.mono (hAB : A ⊆ B) (hA : IsCorner A x₁ y₁ x₂ y₂) : IsCorner B x₁ y₁ x₂ y₂ where
fst_fst_mem := hAB hA.fst_fst_mem
fst_snd_mem := hAB hA.fst_snd_mem
snd_fst_mem := hAB hA.snd_fst_mem
add_eq_add := hA.add_eq_add
lemma IsCornerFree.mono (hAB : A ⊆ B) (hB : IsCornerFree B) : IsCornerFree A :=
fun _x₁ _y₁ _x₂ _y₂ hxyd ↦ hB <| hxyd.mono hAB
@[simp] lemma not_isCorner_empty : ¬ IsCorner ∅ x₁ y₁ x₂ y₂ := by simp [isCorner_iff]
@[simp] lemma Set.Subsingleton.isCornerFree (hA : A.Subsingleton) : IsCornerFree A :=
fun _x₁ _y₁ _x₂ _y₂ hxyd ↦ by simpa using hA hxyd.fst_fst_mem hxyd.snd_fst_mem
lemma isCornerFree_empty : IsCornerFree (∅ : Set (G × G)) := subsingleton_empty.isCornerFree
lemma isCornerFree_singleton (x : G × G) : IsCornerFree {x} := subsingleton_singleton.isCornerFree
/-- Corners are preserved under `2`-Freiman homomorphisms. -/
lemma IsCorner.image (hf : IsAddFreimanHom 2 s t f) (hAs : (A : Set (G × G)) ⊆ s ×ˢ s)
(hA : IsCorner A x₁ y₁ x₂ y₂) : IsCorner (Prod.map f f '' A) (f x₁) (f y₁) (f x₂) (f y₂) := by
obtain ⟨hx₁y₁, hx₁y₂, hx₂y₁, hxy⟩ := hA
exact ⟨mem_image_of_mem _ hx₁y₁, mem_image_of_mem _ hx₁y₂, mem_image_of_mem _ hx₂y₁,
hf.add_eq_add (hAs hx₁y₁).1 (hAs hx₁y₂).2 (hAs hx₂y₁).1 (hAs hx₁y₁).2 hxy⟩
/-- Corners are preserved under `2`-Freiman homomorphisms. -/
lemma IsCornerFree.of_image (hf : IsAddFreimanHom 2 s t f) (hf' : s.InjOn f)
(hAs : (A : Set (G × G)) ⊆ s ×ˢ s) (hA : IsCornerFree (Prod.map f f '' A)) : IsCornerFree A :=
fun _x₁ _y₁ _x₂ _y₂ hxy ↦
hf' (hAs hxy.fst_fst_mem).1 (hAs hxy.snd_fst_mem).1 <| hA <| hxy.image hf hAs
lemma isCorner_image (hf : IsAddFreimanIso 2 s t f) (hAs : A ⊆ s ×ˢ s)
(hx₁ : x₁ ∈ s) (hy₁ : y₁ ∈ s) (hx₂ : x₂ ∈ s) (hy₂ : y₂ ∈ s) :
IsCorner (Prod.map f f '' A) (f x₁) (f y₁) (f x₂) (f y₂) ↔ IsCorner A x₁ y₁ x₂ y₂ := by
have hf' := hf.bijOn.injOn.prodMap hf.bijOn.injOn
rw [isCorner_iff, isCorner_iff]
congr!
· exact hf'.mem_image_iff hAs (mk_mem_prod hx₁ hy₁)
· exact hf'.mem_image_iff hAs (mk_mem_prod hx₁ hy₂)
· exact hf'.mem_image_iff hAs (mk_mem_prod hx₂ hy₁)
· exact hf.add_eq_add hx₁ hy₂ hx₂ hy₁
lemma isCornerFree_image (hf : IsAddFreimanIso 2 s t f) (hAs : A ⊆ s ×ˢ s) :
IsCornerFree (Prod.map f f '' A) ↔ IsCornerFree A := by
have : Prod.map f f '' A ⊆ t ×ˢ t :=
((hf.bijOn.mapsTo.prodMap hf.bijOn.mapsTo).mono hAs Subset.rfl).image_subset
rw [isCornerFree_iff hAs, isCornerFree_iff this]
simp +contextual only [hf.bijOn.forall, isCorner_image hf hAs, hf.bijOn.injOn.eq_iff]
alias ⟨IsCorner.of_image, _⟩ := isCorner_image
alias ⟨_, IsCornerFree.image⟩ := isCornerFree_image
end AddCommMonoid |
.lake/packages/mathlib/Mathlib/Combinatorics/Additive/Corner/Roth.lean | import Mathlib.Combinatorics.Additive.AP.Three.Defs
import Mathlib.Combinatorics.Additive.Corner.Defs
import Mathlib.Combinatorics.SimpleGraph.Triangle.Removal
import Mathlib.Combinatorics.SimpleGraph.Triangle.Tripartite
/-!
# The corners theorem and Roth's theorem
This file proves the corners theorem and Roth's theorem on arithmetic progressions of length three.
## References
* [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp]
* [Wikipedia, *Corners theorem*](https://en.wikipedia.org/wiki/Corners_theorem)
-/
open Finset SimpleGraph TripartiteFromTriangles
open Function hiding graph
open Fintype (card)
variable {G : Type*} [AddCommGroup G] {A : Finset (G × G)} {a b c : G} {n : ℕ} {ε : ℝ}
namespace Corners
/-- The triangle indices for the proof of the corners theorem construction. -/
private def triangleIndices (A : Finset (G × G)) : Finset (G × G × G) :=
A.map ⟨fun (a, b) ↦ (a, b, a + b), by rintro ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ ⟨⟩; rfl⟩
@[simp]
private lemma mk_mem_triangleIndices : (a, b, c) ∈ triangleIndices A ↔ (a, b) ∈ A ∧ c = a + b := by
simp only [triangleIndices, Prod.ext_iff, mem_map, Embedding.coeFn_mk, Prod.exists,
eq_comm]
refine ⟨?_, fun h ↦ ⟨_, _, h.1, rfl, rfl, h.2⟩⟩
rintro ⟨_, _, h₁, rfl, rfl, h₂⟩
exact ⟨h₁, h₂⟩
@[simp] private lemma card_triangleIndices : #(triangleIndices A) = #A := card_map _
private instance triangleIndices.instExplicitDisjoint : ExplicitDisjoint (triangleIndices A) := by
constructor
all_goals
simp only [mk_mem_triangleIndices, and_imp]
rintro a b _ a' - rfl - h'
simp [*] at * <;> assumption
private lemma noAccidental (hs : IsCornerFree (A : Set (G × G))) :
NoAccidental (triangleIndices A) where
eq_or_eq_or_eq a a' b b' c c' ha hb hc := by
simp only [mk_mem_triangleIndices] at ha hb hc
exact .inl <| hs ⟨hc.1, hb.1, ha.1, hb.2.symm.trans ha.2⟩
private lemma farFromTriangleFree_graph [Fintype G] [DecidableEq G] (hε : ε * card G ^ 2 ≤ #A) :
(graph <| triangleIndices A).FarFromTriangleFree (ε / 9) := by
refine farFromTriangleFree _ ?_
simp_rw [card_triangleIndices, mul_comm_div, Nat.cast_pow, Nat.cast_add]
ring_nf
simpa only [mul_comm] using hε
end Corners
variable [Fintype G]
open Corners
/-- An explicit form for the constant in the corners theorem.
Note that this depends on `SzemerediRegularity.bound`, which is a tower-type exponential. This means
`cornersTheoremBound` is in practice absolutely tiny. -/
noncomputable def cornersTheoremBound (ε : ℝ) : ℕ := ⌊(triangleRemovalBound (ε / 9) * 27)⁻¹⌋₊ + 1
/-- The **corners theorem** for finite abelian groups.
The maximum density of a corner-free set in `G × G` goes to zero as `|G|` tends to infinity. -/
theorem corners_theorem (ε : ℝ) (hε : 0 < ε) (hG : cornersTheoremBound ε ≤ card G)
(A : Finset (G × G)) (hAε : ε * card G ^ 2 ≤ #A) : ¬ IsCornerFree (A : Set (G × G)) := by
rintro hA
rw [cornersTheoremBound, Nat.add_one_le_iff] at hG
have hε₁ : ε ≤ 1 := by
have := hAε.trans (Nat.cast_le.2 A.card_le_univ)
simp only [sq, Nat.cast_mul, Fintype.card_prod] at this
rwa [mul_le_iff_le_one_left] at this
positivity
have := noAccidental hA
rw [Nat.floor_lt' (by positivity), inv_lt_iff_one_lt_mul₀' (by positivity)] at hG
refine hG.not_ge (le_of_mul_le_mul_right ?_ (by positivity : (0 : ℝ) < card G ^ 2))
classical
have h₁ := (farFromTriangleFree_graph hAε).le_card_cliqueFinset
rw [card_triangles, card_triangleIndices] at h₁
convert h₁.trans (Nat.cast_le.2 <| card_le_univ _) using 1 <;> simp <;> ring
open Fin.NatCast in -- TODO: refactor to avoid needing the coercion
/-- The **corners theorem** for `ℕ`.
The maximum density of a corner-free set in `{1, ..., n} × {1, ..., n}` goes to zero as `n` tends to
infinity. -/
theorem corners_theorem_nat (hε : 0 < ε) (hn : cornersTheoremBound (ε / 9) ≤ n)
(A : Finset (ℕ × ℕ)) (hAn : A ⊆ range n ×ˢ range n) (hAε : ε * n ^ 2 ≤ #A) :
¬ IsCornerFree (A : Set (ℕ × ℕ)) := by
rintro hA
rw [← coe_subset, coe_product] at hAn
have : A = Prod.map Fin.val Fin.val ''
(Prod.map Nat.cast Nat.cast '' A : Set (Fin (2 * n).succ × Fin (2 * n).succ)) := by
rw [Set.image_image, Set.image_congr, Set.image_id]
simp only [mem_coe, Nat.succ_eq_add_one, Prod.map_apply, Fin.val_natCast, id_eq, Prod.forall,
Prod.mk.injEq, Nat.mod_succ_eq_iff_lt]
rintro a b hab
have := hAn hab
simp at this
omega
rw [this] at hA
have := Fin.isAddFreimanIso_Iio two_ne_zero (le_refl (2 * n))
have := hA.of_image this.isAddFreimanHom Fin.val_injective.injOn <| by
refine Set.image_subset_iff.2 <| hAn.trans fun x hx ↦ ?_
simp only [coe_range, Set.mem_prod, Set.mem_Iio] at hx
exact ⟨Fin.natCast_strictMono (by cutsat) hx.1, Fin.natCast_strictMono (by cutsat) hx.2⟩
rw [← coe_image] at this
refine corners_theorem (ε / 9) (by positivity) (by simp; cutsat) _ ?_ this
calc
_ = ε / 9 * (2 * n + 1) ^ 2 := by simp
_ ≤ ε / 9 * (2 * n + n) ^ 2 := by gcongr; simp; unfold cornersTheoremBound at hn; cutsat
_ = ε * n ^ 2 := by ring
_ ≤ #A := hAε
_ = _ := by
rw [card_image_of_injOn]
have : Set.InjOn Nat.cast (range n) :=
(CharP.natCast_injOn_Iio (Fin (2 * n).succ) (2 * n).succ).mono (by simp; cutsat)
exact (this.prodMap this).mono hAn
/-- **Roth's theorem** for finite abelian groups.
The maximum density of a 3AP-free set in `G` goes to zero as `|G|` tends to infinity. -/
theorem roth_3ap_theorem (ε : ℝ) (hε : 0 < ε) (hG : cornersTheoremBound ε ≤ card G)
(A : Finset G) (hAε : ε * card G ≤ #A) : ¬ ThreeAPFree (A : Set G) := by
rintro hA
classical
let B : Finset (G × G) := univ.filter fun (x, y) ↦ y - x ∈ A
have : ε * card G ^ 2 ≤ #B := by
calc
_ = card G * (ε * card G) := by ring
_ ≤ card G * #A := by gcongr
_ = #B := ?_
norm_cast
rw [← card_univ, ← card_product]
exact card_equiv ((Equiv.refl _).prodShear fun a ↦ Equiv.addLeft a) (by simp [B])
obtain ⟨x₁, y₁, x₂, y₂, hx₁y₁, hx₁y₂, hx₂y₁, hxy, hx₁x₂⟩ :
∃ x₁ y₁ x₂ y₂, y₁ - x₁ ∈ A ∧ y₂ - x₁ ∈ A ∧ y₁ - x₂ ∈ A ∧ x₁ + y₂ = x₂ + y₁ ∧ x₁ ≠ x₂ := by
simpa [IsCornerFree, isCorner_iff, B, -exists_and_left, -exists_and_right]
using corners_theorem ε hε hG B this
have := hA hx₂y₁ hx₁y₁ hx₁y₂ <| by -- TODO: This really ought to just be `by linear_combination h`
rw [sub_add_sub_comm, add_comm, add_sub_add_comm, add_right_cancel_iff,
sub_eq_sub_iff_add_eq_add, add_comm, hxy, add_comm]
exact hx₁x₂ <| by simpa using this.symm
open Fin.NatCast in -- TODO: refactor to avoid needing the coercion
/-- **Roth's theorem** for `ℕ`.
The maximum density of a 3AP-free set in `{1, ..., n}` goes to zero as `n` tends to infinity. -/
theorem roth_3ap_theorem_nat (ε : ℝ) (hε : 0 < ε) (hG : cornersTheoremBound (ε / 3) ≤ n)
(A : Finset ℕ) (hAn : A ⊆ range n) (hAε : ε * n ≤ #A) : ¬ ThreeAPFree (A : Set ℕ) := by
rintro hA
rw [← coe_subset, coe_range] at hAn
have : A = Fin.val '' (Nat.cast '' A : Set (Fin (2 * n).succ)) := by
rw [Set.image_image, Set.image_congr, Set.image_id]
simp only [mem_coe, Nat.succ_eq_add_one, Fin.val_natCast, id_eq, Nat.mod_succ_eq_iff_lt]
rintro a ha
have := hAn ha
simp at this
omega
rw [this] at hA
have := Fin.isAddFreimanIso_Iio two_ne_zero (le_refl (2 * n))
have := hA.of_image this.isAddFreimanHom Fin.val_injective.injOn <| Set.image_subset_iff.2 <|
hAn.trans fun x hx ↦ Fin.natCast_strictMono (by cutsat) <| by
simpa only [coe_range, Set.mem_Iio] using hx
rw [← coe_image] at this
refine roth_3ap_theorem (ε / 3) (by positivity) (by simp; cutsat) _ ?_ this
calc
_ = ε / 3 * (2 * n + 1) := by simp
_ ≤ ε / 3 * (2 * n + n) := by gcongr; simp; unfold cornersTheoremBound at hG; cutsat
_ = ε * n := by ring
_ ≤ #A := hAε
_ = _ := by
rw [card_image_of_injOn]
exact (CharP.natCast_injOn_Iio (Fin (2 * n).succ) (2 * n).succ).mono <| hAn.trans <| by
simp; cutsat
open Asymptotics Filter
/-- **Roth's theorem** for `ℕ` as an asymptotic statement.
The maximum density of a 3AP-free set in `{1, ..., n}` goes to zero as `n` tends to infinity. -/
theorem rothNumberNat_isLittleO_id :
IsLittleO atTop (fun N ↦ (rothNumberNat N : ℝ)) (fun N ↦ (N : ℝ)) := by
simp only [isLittleO_iff, eventually_atTop, RCLike.norm_natCast]
refine fun ε hε ↦ ⟨cornersTheoremBound (ε / 3), fun n hn ↦ ?_⟩
obtain ⟨A, hs₁, hs₂, hs₃⟩ := rothNumberNat_spec n
rw [← hs₂, ← not_lt]
exact fun hδn ↦ roth_3ap_theorem_nat ε hε hn _ hs₁ hδn.le hs₃ |
.lake/packages/mathlib/Mathlib/Combinatorics/Young/SemistandardTableau.lean | import Mathlib.Combinatorics.Young.YoungDiagram
/-!
# Semistandard Young tableaux
A semistandard Young tableau is a filling of a Young diagram by natural numbers, such that
the entries are weakly increasing left-to-right along rows (i.e. for fixed `i`), and
strictly-increasing top-to-bottom along columns (i.e. for fixed `j`).
An example of an SSYT of shape `μ = [4, 2, 1]` is:
```text
0 0 0 2
1 1
2
```
We represent a semistandard Young tableau as a function `ℕ → ℕ → ℕ`, which is required to be zero
for all pairs `(i, j) ∉ μ` and to satisfy the row-weak and column-strict conditions on `μ`.
## Main definitions
- `SemistandardYoungTableau (μ : YoungDiagram)`: semistandard Young tableaux of shape `μ`. There is
a `coe` instance such that `T i j` is value of the `(i, j)` entry of the semistandard Young
tableau `T`.
- `SemistandardYoungTableau.highestWeight (μ : YoungDiagram)`: the semistandard Young tableau whose
`i`th row consists entirely of `i`s, for each `i`.
## Tags
Semistandard Young tableau
## References
<https://en.wikipedia.org/wiki/Young_tableau>
-/
/-- A semistandard Young tableau is a filling of the cells of a Young diagram by natural
numbers, such that the entries in each row are weakly increasing (left to right), and the entries
in each column are strictly increasing (top to bottom).
Here, a semistandard Young tableau is represented as an unrestricted function `ℕ → ℕ → ℕ` that, for
reasons of extensionality, is required to vanish outside `μ`. -/
structure SemistandardYoungTableau (μ : YoungDiagram) where
/-- `entry i j` is value of the `(i, j)` entry of the SSYT `μ`. -/
entry : ℕ → ℕ → ℕ
/-- The entries in each row are weakly increasing (left to right). -/
row_weak' : ∀ {i j1 j2 : ℕ}, j1 < j2 → (i, j2) ∈ μ → entry i j1 ≤ entry i j2
/-- The entries in each column are strictly increasing (top to bottom). -/
col_strict' : ∀ {i1 i2 j : ℕ}, i1 < i2 → (i2, j) ∈ μ → entry i1 j < entry i2 j
/-- `entry` is required to be zero for all pairs `(i, j) ∉ μ`. -/
zeros' : ∀ {i j}, (i, j) ∉ μ → entry i j = 0
namespace SemistandardYoungTableau
instance instFunLike {μ : YoungDiagram} : FunLike (SemistandardYoungTableau μ) ℕ (ℕ → ℕ) where
coe := SemistandardYoungTableau.entry
coe_injective' T T' h := by
cases T
cases T'
congr
@[simp]
theorem to_fun_eq_coe {μ : YoungDiagram} {T : SemistandardYoungTableau μ} :
T.entry = (T : ℕ → ℕ → ℕ) :=
rfl
@[ext]
theorem ext {μ : YoungDiagram} {T T' : SemistandardYoungTableau μ} (h : ∀ i j, T i j = T' i j) :
T = T' :=
DFunLike.ext T T' fun _ ↦ by
funext
apply h
/-- Copy of an `SemistandardYoungTableau μ` with a new `entry` equal to the old one. Useful to fix
definitional equalities. -/
protected def copy {μ : YoungDiagram} (T : SemistandardYoungTableau μ) (entry' : ℕ → ℕ → ℕ)
(h : entry' = T) : SemistandardYoungTableau μ where
entry := entry'
row_weak' := h.symm ▸ T.row_weak'
col_strict' := h.symm ▸ T.col_strict'
zeros' := h.symm ▸ T.zeros'
@[simp]
theorem coe_copy {μ : YoungDiagram} (T : SemistandardYoungTableau μ) (entry' : ℕ → ℕ → ℕ)
(h : entry' = T) : ⇑(T.copy entry' h) = entry' :=
rfl
theorem copy_eq {μ : YoungDiagram} (T : SemistandardYoungTableau μ) (entry' : ℕ → ℕ → ℕ)
(h : entry' = T) : T.copy entry' h = T :=
DFunLike.ext' h
theorem row_weak {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i j1 j2 : ℕ} (hj : j1 < j2)
(hcell : (i, j2) ∈ μ) : T i j1 ≤ T i j2 :=
T.row_weak' hj hcell
theorem col_strict {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i1 i2 j : ℕ} (hi : i1 < i2)
(hcell : (i2, j) ∈ μ) : T i1 j < T i2 j :=
T.col_strict' hi hcell
theorem zeros {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i j : ℕ}
(not_cell : (i, j) ∉ μ) : T i j = 0 :=
T.zeros' not_cell
theorem row_weak_of_le {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i j1 j2 : ℕ}
(hj : j1 ≤ j2) (cell : (i, j2) ∈ μ) : T i j1 ≤ T i j2 := by
rcases eq_or_lt_of_le hj with h | h
· rw [h]
· exact T.row_weak h cell
theorem col_weak {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i1 i2 j : ℕ} (hi : i1 ≤ i2)
(cell : (i2, j) ∈ μ) : T i1 j ≤ T i2 j := by
rcases eq_or_lt_of_le hi with h | h
· rw [h]
· exact le_of_lt (T.col_strict h cell)
/-- The "highest weight" SSYT of a given shape has all i's in row i, for each i. -/
def highestWeight (μ : YoungDiagram) : SemistandardYoungTableau μ where
entry i j := if (i, j) ∈ μ then i else 0
row_weak' hj hcell := by
rw [if_pos hcell, if_pos (μ.up_left_mem (by rfl) (le_of_lt hj) hcell)]
col_strict' hi hcell := by
rwa [if_pos hcell, if_pos (μ.up_left_mem (le_of_lt hi) (by rfl) hcell)]
zeros' not_cell := if_neg not_cell
@[simp]
theorem highestWeight_apply {μ : YoungDiagram} {i j : ℕ} :
highestWeight μ i j = if (i, j) ∈ μ then i else 0 :=
rfl
instance {μ : YoungDiagram} : Inhabited (SemistandardYoungTableau μ) :=
⟨highestWeight μ⟩
end SemistandardYoungTableau |
.lake/packages/mathlib/Mathlib/Combinatorics/Young/YoungDiagram.lean | import Mathlib.Data.Finset.Preimage
import Mathlib.Data.Finset.Prod
import Mathlib.Data.SetLike.Basic
import Mathlib.Order.UpperLower.Basic
/-!
# Young diagrams
A Young diagram is a finite set of up-left justified boxes:
```text
□□□□□
□□□
□□□
□
```
This Young diagram corresponds to the [5, 3, 3, 1] partition of 12.
We represent it as a lower set in `ℕ × ℕ` in the product partial order. We write `(i, j) ∈ μ`
to say that `(i, j)` (in matrix coordinates) is in the Young diagram `μ`.
## Main definitions
- `YoungDiagram` : Young diagrams
- `YoungDiagram.card` : the number of cells in a Young diagram (its *cardinality*)
- `YoungDiagram.instDistribLatticeYoungDiagram` : a distributive lattice instance for Young diagrams
ordered by containment, with `(⊥ : YoungDiagram)` the empty diagram.
- `YoungDiagram.row` and `YoungDiagram.rowLen`: rows of a Young diagram and their lengths
- `YoungDiagram.col` and `YoungDiagram.colLen`: columns of a Young diagram and their lengths
## Notation
In "English notation", a Young diagram is drawn so that (i1, j1) ≤ (i2, j2)
means (i1, j1) is weakly up-and-left of (i2, j2). This terminology is used
below, e.g. in `YoungDiagram.up_left_mem`.
## Tags
Young diagram
## References
<https://en.wikipedia.org/wiki/Young_tableau>
-/
open Function
/-- A Young diagram is a finite collection of cells on the `ℕ × ℕ` grid such that whenever
a cell is present, so are all the ones above and to the left of it. Like matrices, an `(i, j)` cell
is a cell in row `i` and column `j`, where rows are enumerated downward and columns rightward.
Young diagrams are modeled as finite sets in `ℕ × ℕ` that are lower sets with respect to the
standard order on products. -/
@[ext]
structure YoungDiagram where
/-- A finite set which represents a finite collection of cells on the `ℕ × ℕ` grid. -/
cells : Finset (ℕ × ℕ)
/-- Cells are up-left justified, witnessed by the fact that `cells` is a lower set in `ℕ × ℕ`. -/
isLowerSet : IsLowerSet (cells : Set (ℕ × ℕ))
namespace YoungDiagram
instance : SetLike YoungDiagram (ℕ × ℕ) where
coe y := y.cells
coe_injective' μ ν h := by rwa [YoungDiagram.ext_iff, ← Finset.coe_inj]
@[simp]
theorem mem_cells {μ : YoungDiagram} (c : ℕ × ℕ) : c ∈ μ.cells ↔ c ∈ μ :=
Iff.rfl
@[simp]
theorem mem_mk (c : ℕ × ℕ) (cells) (isLowerSet) :
c ∈ YoungDiagram.mk cells isLowerSet ↔ c ∈ cells :=
Iff.rfl
instance decidableMem (μ : YoungDiagram) : DecidablePred (· ∈ μ) :=
inferInstanceAs (DecidablePred (· ∈ μ.cells))
/-- In "English notation", a Young diagram is drawn so that (i1, j1) ≤ (i2, j2)
means (i1, j1) is weakly up-and-left of (i2, j2). -/
theorem up_left_mem (μ : YoungDiagram) {i1 i2 j1 j2 : ℕ} (hi : i1 ≤ i2) (hj : j1 ≤ j2)
(hcell : (i2, j2) ∈ μ) : (i1, j1) ∈ μ :=
μ.isLowerSet (Prod.mk_le_mk.mpr ⟨hi, hj⟩) hcell
section DistribLattice
@[simp]
theorem cells_subset_iff {μ ν : YoungDiagram} : μ.cells ⊆ ν.cells ↔ μ ≤ ν :=
Iff.rfl
@[simp]
theorem cells_ssubset_iff {μ ν : YoungDiagram} : μ.cells ⊂ ν.cells ↔ μ < ν :=
Iff.rfl
instance : Max YoungDiagram where
max μ ν :=
{ cells := μ.cells ∪ ν.cells
isLowerSet := by
rw [Finset.coe_union]
exact μ.isLowerSet.union ν.isLowerSet }
@[simp]
theorem cells_sup (μ ν : YoungDiagram) : (μ ⊔ ν).cells = μ.cells ∪ ν.cells :=
rfl
@[simp, norm_cast]
theorem coe_sup (μ ν : YoungDiagram) : ↑(μ ⊔ ν) = (μ ∪ ν : Set (ℕ × ℕ)) :=
Finset.coe_union _ _
@[simp]
theorem mem_sup {μ ν : YoungDiagram} {x : ℕ × ℕ} : x ∈ μ ⊔ ν ↔ x ∈ μ ∨ x ∈ ν :=
Finset.mem_union
instance : Min YoungDiagram where
min μ ν :=
{ cells := μ.cells ∩ ν.cells
isLowerSet := by
rw [Finset.coe_inter]
exact μ.isLowerSet.inter ν.isLowerSet }
@[simp]
theorem cells_inf (μ ν : YoungDiagram) : (μ ⊓ ν).cells = μ.cells ∩ ν.cells :=
rfl
@[simp, norm_cast]
theorem coe_inf (μ ν : YoungDiagram) : ↑(μ ⊓ ν) = (μ ∩ ν : Set (ℕ × ℕ)) :=
Finset.coe_inter _ _
@[simp]
theorem mem_inf {μ ν : YoungDiagram} {x : ℕ × ℕ} : x ∈ μ ⊓ ν ↔ x ∈ μ ∧ x ∈ ν :=
Finset.mem_inter
/-- The empty Young diagram is (⊥ : young_diagram). -/
instance : OrderBot YoungDiagram where
bot :=
{ cells := ∅
isLowerSet := by
intro a b _ h
simp only [Finset.coe_empty, Set.mem_empty_iff_false]
simp only [Finset.coe_empty, Set.mem_empty_iff_false] at h }
bot_le _ _ := by
intro y
simp only [mem_mk, Finset.notMem_empty] at y
@[simp]
theorem cells_bot : (⊥ : YoungDiagram).cells = ∅ :=
rfl
@[simp]
theorem notMem_bot (x : ℕ × ℕ) : x ∉ (⊥ : YoungDiagram) :=
Finset.notMem_empty x
@[deprecated (since := "2025-05-23")] alias not_mem_bot := notMem_bot
@[norm_cast]
theorem coe_bot : (⊥ : YoungDiagram) = (∅ : Set (ℕ × ℕ)) := by
ext; simp
instance : Inhabited YoungDiagram :=
⟨⊥⟩
instance : DistribLattice YoungDiagram :=
Function.Injective.distribLattice YoungDiagram.cells (fun μ ν h => by rwa [YoungDiagram.ext_iff])
(fun _ _ => rfl) fun _ _ => rfl
end DistribLattice
/-- Cardinality of a Young diagram -/
protected abbrev card (μ : YoungDiagram) : ℕ :=
μ.cells.card
section Transpose
/-- The `transpose` of a Young diagram is obtained by swapping i's with j's. -/
def transpose (μ : YoungDiagram) : YoungDiagram where
cells := (Equiv.prodComm _ _).finsetCongr μ.cells
isLowerSet _ _ h := by
simp only [Finset.mem_coe, Equiv.finsetCongr_apply, Finset.mem_map_equiv]
intro hcell
apply μ.isLowerSet _ hcell
simp [h]
@[simp]
theorem mem_transpose {μ : YoungDiagram} {c : ℕ × ℕ} : c ∈ μ.transpose ↔ c.swap ∈ μ := by
simp [transpose]
@[simp]
theorem transpose_transpose (μ : YoungDiagram) : μ.transpose.transpose = μ := by
ext x
simp
theorem transpose_eq_iff_eq_transpose {μ ν : YoungDiagram} : μ.transpose = ν ↔ μ = ν.transpose := by
constructor <;>
· rintro rfl
simp
@[simp]
theorem transpose_eq_iff {μ ν : YoungDiagram} : μ.transpose = ν.transpose ↔ μ = ν := by
rw [transpose_eq_iff_eq_transpose]
simp
-- This is effectively both directions of `transpose_le_iff` below.
protected theorem le_of_transpose_le {μ ν : YoungDiagram} (h_le : μ.transpose ≤ ν) :
μ ≤ ν.transpose := fun c hc => by
simp only [mem_cells, mem_transpose]
apply h_le
simpa
@[simp]
theorem transpose_le_iff {μ ν : YoungDiagram} : μ.transpose ≤ ν.transpose ↔ μ ≤ ν :=
⟨fun h => by
convert YoungDiagram.le_of_transpose_le h
simp, fun h => by
rw [← transpose_transpose μ] at h
exact YoungDiagram.le_of_transpose_le h ⟩
@[mono]
protected theorem transpose_mono {μ ν : YoungDiagram} (h_le : μ ≤ ν) : μ.transpose ≤ ν.transpose :=
transpose_le_iff.mpr h_le
/-- Transposing Young diagrams is an `OrderIso`. -/
@[simps]
def transposeOrderIso : YoungDiagram ≃o YoungDiagram :=
⟨⟨transpose, transpose, fun _ => by simp, fun _ => by simp⟩, by simp⟩
end Transpose
section Rows
/-! ### Rows and row lengths of Young diagrams.
This section defines `μ.row` and `μ.rowLen`, with the following API:
1. `(i, j) ∈ μ ↔ j < μ.rowLen i`
2. `μ.row i = {i} ×ˢ (Finset.range (μ.rowLen i))`
3. `μ.rowLen i = (μ.row i).card`
4. `∀ {i1 i2}, i1 ≤ i2 → μ.rowLen i2 ≤ μ.rowLen i1`
Note: #3 is not convenient for defining `μ.rowLen`; instead, `μ.rowLen` is defined
as the smallest `j` such that `(i, j) ∉ μ`. -/
/-- The `i`-th row of a Young diagram consists of the cells whose first coordinate is `i`. -/
def row (μ : YoungDiagram) (i : ℕ) : Finset (ℕ × ℕ) :=
μ.cells.filter fun c => c.fst = i
theorem mem_row_iff {μ : YoungDiagram} {i : ℕ} {c : ℕ × ℕ} : c ∈ μ.row i ↔ c ∈ μ ∧ c.fst = i := by
simp [row]
theorem mk_mem_row_iff {μ : YoungDiagram} {i j : ℕ} : (i, j) ∈ μ.row i ↔ (i, j) ∈ μ := by simp [row]
protected theorem exists_notMem_row (μ : YoungDiagram) (i : ℕ) : ∃ j, (i, j) ∉ μ := by
obtain ⟨j, hj⟩ :=
Infinite.exists_notMem_finset
(μ.cells.preimage (Prod.mk i) fun _ _ _ _ h => by
cases h
rfl)
rw [Finset.mem_preimage] at hj
exact ⟨j, hj⟩
@[deprecated (since := "2025-05-23")]
protected alias exists_not_mem_row := YoungDiagram.exists_notMem_row
/-- Length of a row of a Young diagram -/
def rowLen (μ : YoungDiagram) (i : ℕ) : ℕ :=
Nat.find <| μ.exists_notMem_row i
theorem mem_iff_lt_rowLen {μ : YoungDiagram} {i j : ℕ} : (i, j) ∈ μ ↔ j < μ.rowLen i := by
rw [rowLen, Nat.lt_find_iff]
push_neg
exact ⟨fun h _ hmj => μ.up_left_mem (by rfl) hmj h, fun h => h _ (by rfl)⟩
theorem row_eq_prod {μ : YoungDiagram} {i : ℕ} : μ.row i = {i} ×ˢ Finset.range (μ.rowLen i) := by
ext ⟨a, b⟩
simp only [Finset.mem_product, Finset.mem_singleton, Finset.mem_range, mem_row_iff,
mem_iff_lt_rowLen, and_comm, and_congr_right_iff]
rintro rfl
rfl
theorem rowLen_eq_card (μ : YoungDiagram) {i : ℕ} : μ.rowLen i = (μ.row i).card := by
simp [row_eq_prod]
@[mono]
theorem rowLen_anti (μ : YoungDiagram) (i1 i2 : ℕ) (hi : i1 ≤ i2) : μ.rowLen i2 ≤ μ.rowLen i1 := by
by_contra! h_lt
rw [← lt_self_iff_false (μ.rowLen i1)]
rw [← mem_iff_lt_rowLen] at h_lt ⊢
exact μ.up_left_mem hi (by rfl) h_lt
end Rows
section Columns
/-! ### Columns and column lengths of Young diagrams.
This section has an identical API to the rows section. -/
/-- The `j`-th column of a Young diagram consists of the cells whose second coordinate is `j`. -/
def col (μ : YoungDiagram) (j : ℕ) : Finset (ℕ × ℕ) :=
μ.cells.filter fun c => c.snd = j
theorem mem_col_iff {μ : YoungDiagram} {j : ℕ} {c : ℕ × ℕ} : c ∈ μ.col j ↔ c ∈ μ ∧ c.snd = j := by
simp [col]
theorem mk_mem_col_iff {μ : YoungDiagram} {i j : ℕ} : (i, j) ∈ μ.col j ↔ (i, j) ∈ μ := by simp [col]
protected theorem exists_notMem_col (μ : YoungDiagram) (j : ℕ) : ∃ i, (i, j) ∉ μ.cells := by
convert μ.transpose.exists_notMem_row j using 1
simp
@[deprecated (since := "2025-05-23")]
protected alias exists_not_mem_col := YoungDiagram.exists_notMem_col
/-- Length of a column of a Young diagram -/
def colLen (μ : YoungDiagram) (j : ℕ) : ℕ :=
Nat.find <| μ.exists_notMem_col j
@[simp]
theorem colLen_transpose (μ : YoungDiagram) (j : ℕ) : μ.transpose.colLen j = μ.rowLen j := by
simp [rowLen, colLen]
@[simp]
theorem rowLen_transpose (μ : YoungDiagram) (i : ℕ) : μ.transpose.rowLen i = μ.colLen i := by
simp [rowLen, colLen]
theorem mem_iff_lt_colLen {μ : YoungDiagram} {i j : ℕ} : (i, j) ∈ μ ↔ i < μ.colLen j := by
rw [← rowLen_transpose, ← mem_iff_lt_rowLen]
simp
theorem col_eq_prod {μ : YoungDiagram} {j : ℕ} : μ.col j = Finset.range (μ.colLen j) ×ˢ {j} := by
ext ⟨a, b⟩
simp only [Finset.mem_product, Finset.mem_singleton, Finset.mem_range, mem_col_iff,
mem_iff_lt_colLen, and_comm, and_congr_right_iff]
rintro rfl
rfl
theorem colLen_eq_card (μ : YoungDiagram) {j : ℕ} : μ.colLen j = (μ.col j).card := by
simp [col_eq_prod]
@[mono]
theorem colLen_anti (μ : YoungDiagram) (j1 j2 : ℕ) (hj : j1 ≤ j2) : μ.colLen j2 ≤ μ.colLen j1 := by
convert μ.transpose.rowLen_anti j1 j2 hj using 1 <;> simp
end Columns
section RowLens
/-! ### The list of row lengths of a Young diagram
This section defines `μ.rowLens : List ℕ`, the list of row lengths of a Young diagram `μ`.
1. `YoungDiagram.rowLens_sorted` : It is weakly decreasing (`List.Sorted (· ≥ ·)`).
2. `YoungDiagram.rowLens_pos` : It is strictly positive.
-/
/-- List of row lengths of a Young diagram -/
def rowLens (μ : YoungDiagram) : List ℕ :=
(List.range <| μ.colLen 0).map μ.rowLen
@[simp]
theorem get_rowLens {μ : YoungDiagram} {i : Nat} {h : i < μ.rowLens.length} :
μ.rowLens[i] = μ.rowLen i := by simp only [rowLens, List.getElem_range, List.getElem_map]
@[simp]
theorem length_rowLens {μ : YoungDiagram} : μ.rowLens.length = μ.colLen 0 := by
simp only [rowLens, List.length_map, List.length_range]
theorem rowLens_sorted (μ : YoungDiagram) : μ.rowLens.Sorted (· ≥ ·) :=
List.pairwise_le_range.map _ μ.rowLen_anti
theorem pos_of_mem_rowLens (μ : YoungDiagram) (x : ℕ) (hx : x ∈ μ.rowLens) : 0 < x := by
rw [rowLens, List.mem_map] at hx
obtain ⟨i, hi, rfl : μ.rowLen i = x⟩ := hx
rwa [List.mem_range, ← mem_iff_lt_colLen, mem_iff_lt_rowLen] at hi
end RowLens
section EquivListRowLens
/-! ### Equivalence between Young diagrams and lists of natural numbers
This section defines the equivalence between Young diagrams `μ` and weakly decreasing lists `w`
of positive natural numbers, corresponding to row lengths of the diagram:
`YoungDiagram.equivListRowLens :`
`YoungDiagram ≃ {w : List ℕ // w.Sorted (· ≥ ·) ∧ ∀ x ∈ w, 0 < x}`
The two directions are `YoungDiagram.rowLens` (defined above) and `YoungDiagram.ofRowLens`.
-/
/-- The cells making up a `YoungDiagram` from a list of row lengths -/
protected def cellsOfRowLens : List ℕ → Finset (ℕ × ℕ)
| [] => ∅
| w::ws =>
({0} : Finset ℕ) ×ˢ Finset.range w ∪
(YoungDiagram.cellsOfRowLens ws).map
(Embedding.prodMap ⟨_, Nat.succ_injective⟩ (Embedding.refl ℕ))
protected theorem mem_cellsOfRowLens {w : List ℕ} {c : ℕ × ℕ} :
c ∈ YoungDiagram.cellsOfRowLens w ↔ ∃ h : c.fst < w.length, c.snd < w[c.fst] := by
induction w generalizing c <;> rw [YoungDiagram.cellsOfRowLens]
· simp
· rcases c with ⟨⟨_, _⟩, _⟩ <;> simp_all
/-- Young diagram from a sorted list -/
def ofRowLens (w : List ℕ) (hw : w.Sorted (· ≥ ·)) : YoungDiagram where
cells := YoungDiagram.cellsOfRowLens w
isLowerSet := by
rintro ⟨i2, j2⟩ ⟨i1, j1⟩ ⟨hi : i1 ≤ i2, hj : j1 ≤ j2⟩ hcell
rw [Finset.mem_coe, YoungDiagram.mem_cellsOfRowLens] at hcell ⊢
obtain ⟨h1, h2⟩ := hcell
refine ⟨hi.trans_lt h1, ?_⟩
calc
j1 ≤ j2 := hj
_ < w[i2] := h2
_ ≤ w[i1] := by
obtain rfl | h := eq_or_lt_of_le hi
· rfl
· exact List.pairwise_iff_get.mp hw _ _ h
theorem mem_ofRowLens {w : List ℕ} {hw : w.Sorted (· ≥ ·)} {c : ℕ × ℕ} :
c ∈ ofRowLens w hw ↔ ∃ h : c.fst < w.length, c.snd < w[c.fst] :=
YoungDiagram.mem_cellsOfRowLens
/-- The number of rows in `ofRowLens w hw` is the length of `w` -/
theorem rowLens_length_ofRowLens {w : List ℕ} {hw : w.Sorted (· ≥ ·)} (hpos : ∀ x ∈ w, 0 < x) :
(ofRowLens w hw).rowLens.length = w.length := by
simp only [length_rowLens, colLen, Nat.find_eq_iff, mem_cells, mem_ofRowLens,
lt_self_iff_false, IsEmpty.exists_iff, Classical.not_not]
exact ⟨not_false, fun n hn => ⟨hn, hpos _ (List.getElem_mem hn)⟩⟩
/-- The length of the `i`th row in `ofRowLens w hw` is the `i`th entry of `w` -/
theorem rowLen_ofRowLens {w : List ℕ} {hw : w.Sorted (· ≥ ·)} (i : Fin w.length) :
(ofRowLens w hw).rowLen i = w[i] := by
simp [rowLen, Nat.find_eq_iff, mem_ofRowLens]
/-- The left_inv direction of the equivalence -/
theorem ofRowLens_to_rowLens_eq_self {μ : YoungDiagram} : ofRowLens _ (rowLens_sorted μ) = μ := by
ext ⟨i, j⟩
simp only [mem_cells, mem_ofRowLens, length_rowLens, get_rowLens]
simpa [← mem_iff_lt_colLen, mem_iff_lt_rowLen] using j.zero_le.trans_lt
/-- The right_inv direction of the equivalence -/
theorem rowLens_ofRowLens_eq_self {w : List ℕ} {hw : w.Sorted (· ≥ ·)} (hpos : ∀ x ∈ w, 0 < x) :
(ofRowLens w hw).rowLens = w :=
List.ext_get (rowLens_length_ofRowLens hpos) fun i h₁ h₂ =>
(get_rowLens (h := h₁)).trans <| rowLen_ofRowLens ⟨i, h₂⟩
/-- Equivalence between Young diagrams and weakly decreasing lists of positive natural numbers.
A Young diagram `μ` is equivalent to a list of row lengths. -/
@[simps]
def equivListRowLens : YoungDiagram ≃ { w : List ℕ // w.Sorted (· ≥ ·) ∧ ∀ x ∈ w, 0 < x } where
toFun μ := ⟨μ.rowLens, μ.rowLens_sorted, μ.pos_of_mem_rowLens⟩
invFun ww := ofRowLens ww.1 ww.2.1
left_inv _ := ofRowLens_to_rowLens_eq_self
right_inv := fun ⟨_, hw⟩ => Subtype.mk_eq_mk.mpr (rowLens_ofRowLens_eq_self hw.2)
end EquivListRowLens
end YoungDiagram |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/LYM.lean | import Mathlib.Algebra.Field.Basic
import Mathlib.Algebra.Field.Rat
import Mathlib.Combinatorics.Enumerative.DoubleCounting
import Mathlib.Combinatorics.SetFamily.Shadow
import Mathlib.Data.NNRat.Order
import Mathlib.Data.Nat.Cast.Order.Ring
/-!
# Lubell-Yamamoto-Meshalkin inequality and Sperner's theorem
This file proves the local LYM and LYM inequalities as well as Sperner's theorem.
## Main declarations
* `Finset.local_lubell_yamamoto_meshalkin_inequality_div`: Local Lubell-Yamamoto-Meshalkin
inequality. The shadow of a set `𝒜` in a layer takes a greater proportion of its layer than `𝒜`
does.
* `Finset.lubell_yamamoto_meshalkin_inequality_sum_card_div_choose`: Lubell-Yamamoto-Meshalkin
inequality. The sum of densities of `𝒜` in each layer is at most `1` for any antichain `𝒜`.
* `IsAntichain.sperner`: Sperner's theorem. The size of any antichain in `Finset α` is at most the
size of the maximal layer of `Finset α`. It is a corollary of
`lubell_yamamoto_meshalkin_inequality_sum_card_div_choose`.
## TODO
Prove upward local LYM.
Provide equality cases. Local LYM gives that the equality case of LYM and Sperner is precisely when
`𝒜` is a middle layer.
`falling` could be useful more generally in grade orders.
## References
* http://b-mehta.github.io/maths-notes/iii/mich/combinatorics.pdf
* http://discretemath.imp.fu-berlin.de/DMII-2015-16/kruskal.pdf
## Tags
shadow, lym, slice, sperner, antichain
-/
open Finset Nat
open scoped FinsetFamily
variable {𝕜 α : Type*} [Semifield 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜]
namespace Finset
/-! ### Local LYM inequality -/
section LocalLYM
variable [DecidableEq α] [Fintype α] {𝒜 : Finset (Finset α)} {r : ℕ}
/-- The downward **local LYM inequality**, with cancelled denominators. `𝒜` takes up less of `α^(r)`
(the finsets of card `r`) than `∂𝒜` takes up of `α^(r - 1)`. -/
theorem local_lubell_yamamoto_meshalkin_inequality_mul (h𝒜 : (𝒜 : Set (Finset α)).Sized r) :
#𝒜 * r ≤ #(∂ 𝒜) * (Fintype.card α - r + 1) := by
let i : DecidableRel ((· ⊆ ·) : Finset α → Finset α → Prop) := fun _ _ => Classical.dec _
refine card_mul_le_card_mul' (· ⊆ ·) (fun s hs => ?_) (fun s hs => ?_)
· rw [← h𝒜 hs, ← card_image_of_injOn s.erase_injOn]
refine card_le_card ?_
simp_rw [image_subset_iff, mem_bipartiteBelow]
exact fun a ha => ⟨erase_mem_shadow hs ha, erase_subset _ _⟩
refine le_trans ?_ tsub_tsub_le_tsub_add
rw [← (Set.Sized.shadow h𝒜) hs, ← card_compl, ← card_image_of_injOn (insert_inj_on' _)]
refine card_le_card fun t ht => ?_
rw [mem_bipartiteAbove] at ht
have : ∅ ∉ 𝒜 := by
rw [← mem_coe, h𝒜.empty_mem_iff, coe_eq_singleton]
rintro rfl
rw [shadow_singleton_empty] at hs
exact notMem_empty s hs
have h := exists_eq_insert_iff.2 ⟨ht.2, by
rw [(sized_shadow_iff this).1 (Set.Sized.shadow h𝒜) ht.1, (Set.Sized.shadow h𝒜) hs]⟩
rcases h with ⟨a, ha, rfl⟩
exact mem_image_of_mem _ (mem_compl.2 ha)
@[inherit_doc local_lubell_yamamoto_meshalkin_inequality_mul]
alias card_mul_le_card_shadow_mul := local_lubell_yamamoto_meshalkin_inequality_mul
/-- The downward **local LYM inequality**. `𝒜` takes up less of `α^(r)` (the finsets of card `r`)
than `∂𝒜` takes up of `α^(r - 1)`. -/
theorem local_lubell_yamamoto_meshalkin_inequality_div (hr : r ≠ 0)
(h𝒜 : (𝒜 : Set (Finset α)).Sized r) : (#𝒜 : 𝕜) / (Fintype.card α).choose r
≤ #(∂ 𝒜) / (Fintype.card α).choose (r - 1) := by
obtain hr' | hr' := lt_or_ge (Fintype.card α) r
· rw [choose_eq_zero_of_lt hr', cast_zero, div_zero]
exact div_nonneg (cast_nonneg _) (cast_nonneg _)
replace h𝒜 := local_lubell_yamamoto_meshalkin_inequality_mul h𝒜
rw [div_le_div_iff₀] <;> norm_cast
· rcases r with - | r
· exact (hr rfl).elim
rw [tsub_add_eq_add_tsub hr', add_tsub_add_eq_tsub_right] at h𝒜
apply le_of_mul_le_mul_right _ (pos_iff_ne_zero.2 hr)
convert Nat.mul_le_mul_right ((Fintype.card α).choose r) h𝒜 using 1
· simpa [mul_assoc, Nat.choose_succ_right_eq] using Or.inl (mul_comm _ _)
· simp only [mul_assoc, choose_succ_right_eq, mul_eq_mul_left_iff]
exact Or.inl (mul_comm _ _)
· exact Nat.choose_pos hr'
· exact Nat.choose_pos (r.pred_le.trans hr')
@[inherit_doc local_lubell_yamamoto_meshalkin_inequality_div]
alias card_div_choose_le_card_shadow_div_choose := local_lubell_yamamoto_meshalkin_inequality_div
end LocalLYM
/-! ### LYM inequality -/
section LYM
section Falling
variable [DecidableEq α] (k : ℕ) (𝒜 : Finset (Finset α))
/-- `falling k 𝒜` is all the finsets of cardinality `k` which are a subset of something in `𝒜`. -/
def falling : Finset (Finset α) :=
𝒜.sup <| powersetCard k
variable {𝒜 k} {s : Finset α}
theorem mem_falling : s ∈ falling k 𝒜 ↔ (∃ t ∈ 𝒜, s ⊆ t) ∧ #s = k := by
simp_rw [falling, mem_sup, mem_powersetCard]
aesop
variable (𝒜 k)
theorem sized_falling : (falling k 𝒜 : Set (Finset α)).Sized k := fun _ hs => (mem_falling.1 hs).2
theorem slice_subset_falling : 𝒜 # k ⊆ falling k 𝒜 := fun s hs =>
mem_falling.2 <| (mem_slice.1 hs).imp_left fun h => ⟨s, h, Subset.refl _⟩
theorem falling_zero_subset : falling 0 𝒜 ⊆ {∅} :=
subset_singleton_iff'.2 fun _ ht => card_eq_zero.1 <| sized_falling _ _ ht
theorem slice_union_shadow_falling_succ : 𝒜 # k ∪ ∂ (falling (k + 1) 𝒜) = falling k 𝒜 := by
ext s
simp_rw [mem_union, mem_slice, mem_shadow_iff, mem_falling]
constructor
· rintro (h | ⟨s, ⟨⟨t, ht, hst⟩, hs⟩, a, ha, rfl⟩)
· exact ⟨⟨s, h.1, Subset.refl _⟩, h.2⟩
refine ⟨⟨t, ht, (erase_subset _ _).trans hst⟩, ?_⟩
rw [card_erase_of_mem ha, hs]
rfl
· rintro ⟨⟨t, ht, hst⟩, hs⟩
by_cases h : s ∈ 𝒜
· exact Or.inl ⟨h, hs⟩
obtain ⟨a, ha, hst⟩ := ssubset_iff.1 (ssubset_of_subset_of_ne hst (ht.ne_of_notMem h).symm)
refine Or.inr ⟨insert a s, ⟨⟨t, ht, hst⟩, ?_⟩, a, mem_insert_self _ _, erase_insert ha⟩
rw [card_insert_of_notMem ha, hs]
variable {𝒜 k}
/-- The shadow of `falling m 𝒜` is disjoint from the `n`-sized elements of `𝒜`, thanks to the
antichain property. -/
theorem IsAntichain.disjoint_slice_shadow_falling {m n : ℕ}
(h𝒜 : IsAntichain (· ⊆ ·) (𝒜 : Set (Finset α))) : Disjoint (𝒜 # m) (∂ (falling n 𝒜)) :=
disjoint_right.2 fun s h₁ h₂ => by
simp_rw [mem_shadow_iff, mem_falling] at h₁
obtain ⟨s, ⟨⟨t, ht, hst⟩, _⟩, a, ha, rfl⟩ := h₁
refine h𝒜 (slice_subset h₂) ht ?_ ((erase_subset _ _).trans hst)
rintro rfl
exact notMem_erase _ _ (hst ha)
/-- A bound on any top part of the sum in LYM in terms of the size of `falling k 𝒜`. -/
theorem le_card_falling_div_choose [Fintype α] (hk : k ≤ Fintype.card α)
(h𝒜 : IsAntichain (· ⊆ ·) (𝒜 : Set (Finset α))) :
(∑ r ∈ range (k + 1),
(#(𝒜 # (Fintype.card α - r)) : 𝕜) / (Fintype.card α).choose (Fintype.card α - r)) ≤
(falling (Fintype.card α - k) 𝒜).card / (Fintype.card α).choose (Fintype.card α - k) := by
induction k with
| zero =>
simp only [tsub_zero, cast_one, cast_le, sum_singleton, div_one, choose_self, range_one,
zero_add, range_one, sum_singleton, tsub_zero,
choose_self, cast_one, div_one, cast_le]
exact card_le_card (slice_subset_falling _ _)
| succ k ih =>
rw [sum_range_succ, ← slice_union_shadow_falling_succ,
card_union_of_disjoint (IsAntichain.disjoint_slice_shadow_falling h𝒜),
cast_add, _root_.add_div, add_comm]
rw [← tsub_tsub, tsub_add_cancel_of_le (le_tsub_of_add_le_left hk)]
grw [ih <| le_of_succ_le hk, local_lubell_yamamoto_meshalkin_inequality_div
(tsub_pos_iff_lt.2 <| Nat.succ_le_iff.1 hk).ne' <| sized_falling _ _]
end Falling
variable [Fintype α] {𝒜 : Finset (Finset α)}
/-- The **Lubell-Yamamoto-Meshalkin inequality**, also known as the **LYM inequality**.
If `𝒜` is an antichain, then the sum of the proportion of elements it takes from each layer is less
than `1`. -/
theorem lubell_yamamoto_meshalkin_inequality_sum_card_div_choose
(h𝒜 : IsAntichain (· ⊆ ·) (𝒜 : Set (Finset α))) :
∑ r ∈ range (Fintype.card α + 1), (#(𝒜 # r) / (Fintype.card α).choose r : 𝕜) ≤ 1 := by
classical
rw [← sum_flip]
refine (le_card_falling_div_choose le_rfl h𝒜).trans ?_
rw [div_le_iff₀] <;> norm_cast
· simpa only [Nat.sub_self, one_mul, Nat.choose_zero_right, falling] using
Set.Sized.card_le (sized_falling 0 𝒜)
· rw [tsub_self, choose_zero_right]
exact zero_lt_one
@[inherit_doc lubell_yamamoto_meshalkin_inequality_sum_card_div_choose]
alias sum_card_slice_div_choose_le_one := lubell_yamamoto_meshalkin_inequality_sum_card_div_choose
/-- The **Lubell-Yamamoto-Meshalkin inequality**, also known as the **LYM inequality**.
If `𝒜` is an antichain, then the sum of `(#α.choose #s)⁻¹` over `s ∈ 𝒜` is less than `1`. -/
theorem lubell_yamamoto_meshalkin_inequality_sum_inv_choose
(h𝒜 : IsAntichain (· ⊆ ·) (SetLike.coe 𝒜)) :
∑ s ∈ 𝒜, ((Fintype.card α).choose #s : 𝕜)⁻¹ ≤ 1 := by
calc
_ = ∑ r ∈ range (Fintype.card α + 1),
∑ s ∈ 𝒜 with #s = r, ((Fintype.card α).choose r : 𝕜)⁻¹ := by
rw [sum_fiberwise_of_maps_to']; simp [Nat.lt_succ_iff, card_le_univ]
_ = ∑ r ∈ range (Fintype.card α + 1), (#(𝒜 # r) / (Fintype.card α).choose r : 𝕜) := by
simp [slice, div_eq_mul_inv]
_ ≤ 1 := lubell_yamamoto_meshalkin_inequality_sum_card_div_choose h𝒜
/-! ### Sperner's theorem -/
/-- **Sperner's theorem**. The size of an antichain in `Finset α` is bounded by the size of the
maximal layer in `Finset α`. This precisely means that `Finset α` is a Sperner order. -/
theorem _root_.IsAntichain.sperner (h𝒜 : IsAntichain (· ⊆ ·) (SetLike.coe 𝒜)) :
#𝒜 ≤ (Fintype.card α).choose (Fintype.card α / 2) := by
have : 0 < ((Fintype.card α).choose (Fintype.card α / 2) : ℚ≥0) :=
Nat.cast_pos.2 <| choose_pos (Nat.div_le_self _ _)
have h := calc
∑ s ∈ 𝒜, ((Fintype.card α).choose (Fintype.card α / 2) : ℚ≥0)⁻¹
_ ≤ ∑ s ∈ 𝒜, ((Fintype.card α).choose #s : ℚ≥0)⁻¹ := by
gcongr with s hs
· exact mod_cast choose_pos s.card_le_univ
· exact choose_le_middle _ _
_ ≤ 1 := lubell_yamamoto_meshalkin_inequality_sum_inv_choose h𝒜
simpa [mul_inv_le_iff₀' this] using h
end LYM
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/Shadow.lean | import Mathlib.Data.Finset.Grade
import Mathlib.Data.Finset.Sups
import Mathlib.Logic.Function.Iterate
/-!
# Shadows
This file defines shadows of a set family. The shadow of a set family is the set family of sets we
get by removing any element from any set of the original family. If one pictures `Finset α` as a big
hypercube (each dimension being membership of a given element), then taking the shadow corresponds
to projecting each finset down once in all available directions.
## Main definitions
* `Finset.shadow`: The shadow of a set family. Everything we can get by removing a new element from
some set.
* `Finset.upShadow`: The upper shadow of a set family. Everything we can get by adding an element
to some set.
## Notation
We define notation in scope `FinsetFamily`:
* `∂ 𝒜`: Shadow of `𝒜`.
* `∂⁺ 𝒜`: Upper shadow of `𝒜`.
We also maintain the convention that `a, b : α` are elements of the ground type, `s, t : Finset α`
are finsets, and `𝒜, ℬ : Finset (Finset α)` are finset families.
## References
* https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf
* http://discretemath.imp.fu-berlin.de/DMII-2015-16/kruskal.pdf
## Tags
shadow, set family
-/
open Finset Nat
variable {α : Type*}
namespace Finset
section Shadow
variable [DecidableEq α] {𝒜 ℬ : Finset (Finset α)} {s t : Finset α} {a : α} {k r : ℕ}
/-- The shadow of a set family `𝒜` is all sets we can get by removing one element from any set in
`𝒜`, and the (`k` times) iterated shadow (`shadow^[k]`) is all sets we can get by removing `k`
elements from any set in `𝒜`. -/
def shadow (𝒜 : Finset (Finset α)) : Finset (Finset α) :=
𝒜.sup fun s => s.image (erase s)
@[inherit_doc] scoped[FinsetFamily] notation:max "∂ " => Finset.shadow
open FinsetFamily
/-- The shadow of the empty set is empty. -/
@[simp]
theorem shadow_empty : ∂ (∅ : Finset (Finset α)) = ∅ :=
rfl
@[simp] lemma shadow_iterate_empty (k : ℕ) : ∂^[k] (∅ : Finset (Finset α)) = ∅ := by
induction k <;> simp [*, shadow_empty]
@[simp]
theorem shadow_singleton_empty : ∂ ({∅} : Finset (Finset α)) = ∅ :=
rfl
@[simp]
theorem shadow_singleton (a : α) : ∂ {{a}} = {∅} := by
simp [shadow]
/-- The shadow is monotone. -/
@[mono]
theorem shadow_monotone : Monotone (shadow : Finset (Finset α) → Finset (Finset α)) := fun _ _ =>
sup_mono
@[gcongr] lemma shadow_mono (h𝒜ℬ : 𝒜 ⊆ ℬ) : ∂ 𝒜 ⊆ ∂ ℬ := shadow_monotone h𝒜ℬ
/-- `t` is in the shadow of `𝒜` iff there is a `s ∈ 𝒜` from which we can remove one element to
get `t`. -/
lemma mem_shadow_iff : t ∈ ∂ 𝒜 ↔ ∃ s ∈ 𝒜, ∃ a ∈ s, erase s a = t := by
simp only [shadow, mem_sup, mem_image]
theorem erase_mem_shadow (hs : s ∈ 𝒜) (ha : a ∈ s) : erase s a ∈ ∂ 𝒜 :=
mem_shadow_iff.2 ⟨s, hs, a, ha, rfl⟩
/-- `t ∈ ∂𝒜` iff `t` is exactly one element less than something from `𝒜`.
See also `Finset.mem_shadow_iff_exists_mem_card_add_one`. -/
lemma mem_shadow_iff_exists_sdiff : t ∈ ∂ 𝒜 ↔ ∃ s ∈ 𝒜, t ⊆ s ∧ #(s \ t) = 1 := by
simp_rw [mem_shadow_iff, ← covBy_iff_card_sdiff_eq_one, covBy_iff_exists_erase]
/-- `t` is in the shadow of `𝒜` iff we can add an element to it so that the resulting finset is in
`𝒜`. -/
lemma mem_shadow_iff_insert_mem : t ∈ ∂ 𝒜 ↔ ∃ a ∉ t, insert a t ∈ 𝒜 := by
simp_rw [mem_shadow_iff_exists_sdiff, ← covBy_iff_card_sdiff_eq_one, covBy_iff_exists_insert]
aesop
/-- `s ∈ ∂ 𝒜` iff `s` is exactly one element less than something from `𝒜`.
See also `Finset.mem_shadow_iff_exists_sdiff`. -/
lemma mem_shadow_iff_exists_mem_card_add_one : t ∈ ∂ 𝒜 ↔ ∃ s ∈ 𝒜, t ⊆ s ∧ #s = #t + 1 := by
refine mem_shadow_iff_exists_sdiff.trans <| exists_congr fun t ↦ and_congr_right fun _ ↦
and_congr_right fun hst ↦ ?_
rw [card_sdiff_of_subset hst, tsub_eq_iff_eq_add_of_le, add_comm]
exact card_mono hst
lemma mem_shadow_iterate_iff_exists_card :
t ∈ ∂^[k] 𝒜 ↔ ∃ u : Finset α, #u = k ∧ Disjoint t u ∧ t ∪ u ∈ 𝒜 := by
induction k generalizing t with
| zero => simp
| succ k ih =>
simp only [mem_shadow_iff_insert_mem, ih, Function.iterate_succ_apply', card_eq_succ]
aesop
/-- `t ∈ ∂^k 𝒜` iff `t` is exactly `k` elements less than something from `𝒜`.
See also `Finset.mem_shadow_iff_exists_mem_card_add`. -/
lemma mem_shadow_iterate_iff_exists_sdiff : t ∈ ∂^[k] 𝒜 ↔ ∃ s ∈ 𝒜, t ⊆ s ∧ #(s \ t) = k := by
rw [mem_shadow_iterate_iff_exists_card]
constructor
· rintro ⟨u, rfl, htu, hsuA⟩
exact ⟨_, hsuA, subset_union_left, by rw [union_sdiff_cancel_left htu]⟩
· rintro ⟨s, hs, hts, rfl⟩
refine ⟨s \ t, rfl, disjoint_sdiff, ?_⟩
rwa [union_sdiff_self_eq_union, union_eq_right.2 hts]
/-- `t ∈ ∂^k 𝒜` iff `t` is exactly `k` elements less than something in `𝒜`.
See also `Finset.mem_shadow_iterate_iff_exists_sdiff`. -/
lemma mem_shadow_iterate_iff_exists_mem_card_add :
t ∈ ∂^[k] 𝒜 ↔ ∃ s ∈ 𝒜, t ⊆ s ∧ #s = #t + k := by
refine mem_shadow_iterate_iff_exists_sdiff.trans <| exists_congr fun t ↦ and_congr_right fun _ ↦
and_congr_right fun hst ↦ ?_
rw [card_sdiff_of_subset hst, tsub_eq_iff_eq_add_of_le, add_comm]
exact card_mono hst
/-- The shadow of a family of `r`-sets is a family of `r - 1`-sets. -/
protected theorem _root_.Set.Sized.shadow (h𝒜 : (𝒜 : Set (Finset α)).Sized r) :
(∂ 𝒜 : Set (Finset α)).Sized (r - 1) := by
intro A h
obtain ⟨A, hA, i, hi, rfl⟩ := mem_shadow_iff.1 h
rw [card_erase_of_mem hi, h𝒜 hA]
/-- The `k`-th shadow of a family of `r`-sets is a family of `r - k`-sets. -/
lemma _root_.Set.Sized.shadow_iterate (h𝒜 : (𝒜 : Set (Finset α)).Sized r) :
(∂^[k] 𝒜 : Set (Finset α)).Sized (r - k) := by
simp_rw [Set.Sized, mem_coe, mem_shadow_iterate_iff_exists_sdiff]
rintro t ⟨s, hs, hts, rfl⟩
rw [card_sdiff_of_subset hts, ← h𝒜 hs, Nat.sub_sub_self (card_le_card hts)]
theorem sized_shadow_iff (h : ∅ ∉ 𝒜) :
(∂ 𝒜 : Set (Finset α)).Sized r ↔ (𝒜 : Set (Finset α)).Sized (r + 1) := by
refine ⟨fun h𝒜 s hs => ?_, Set.Sized.shadow⟩
obtain ⟨a, ha⟩ := nonempty_iff_ne_empty.2 (ne_of_mem_of_not_mem hs h)
rw [← h𝒜 (erase_mem_shadow hs ha), card_erase_add_one ha]
/-- Being in the shadow of `𝒜` means we have a superset in `𝒜`. -/
lemma exists_subset_of_mem_shadow (hs : t ∈ ∂ 𝒜) : ∃ s ∈ 𝒜, t ⊆ s :=
let ⟨t, ht, hst⟩ := mem_shadow_iff_exists_mem_card_add_one.1 hs
⟨t, ht, hst.1⟩
end Shadow
open FinsetFamily
section UpShadow
variable [DecidableEq α] [Fintype α] {𝒜 : Finset (Finset α)} {s t : Finset α} {a : α} {k r : ℕ}
/-- The upper shadow of a set family `𝒜` is all sets we can get by adding one element to any set in
`𝒜`, and the (`k` times) iterated upper shadow (`upShadow^[k]`) is all sets we can get by adding
`k` elements from any set in `𝒜`. -/
def upShadow (𝒜 : Finset (Finset α)) : Finset (Finset α) :=
𝒜.sup fun s => sᶜ.image fun a => insert a s
@[inherit_doc] scoped[FinsetFamily] notation:max "∂⁺ " => Finset.upShadow
/-- The upper shadow of the empty set is empty. -/
@[simp]
theorem upShadow_empty : ∂⁺ (∅ : Finset (Finset α)) = ∅ :=
rfl
/-- The upper shadow is monotone. -/
@[mono]
theorem upShadow_monotone : Monotone (upShadow : Finset (Finset α) → Finset (Finset α)) :=
fun _ _ => sup_mono
/-- `t` is in the upper shadow of `𝒜` iff there is a `s ∈ 𝒜` from which we can remove one element
to get `t`. -/
lemma mem_upShadow_iff : t ∈ ∂⁺ 𝒜 ↔ ∃ s ∈ 𝒜, ∃ a ∉ s, insert a s = t := by
simp_rw [upShadow, mem_sup, mem_image, mem_compl]
theorem insert_mem_upShadow (hs : s ∈ 𝒜) (ha : a ∉ s) : insert a s ∈ ∂⁺ 𝒜 :=
mem_upShadow_iff.2 ⟨s, hs, a, ha, rfl⟩
/-- `t` is in the upper shadow of `𝒜` iff `t` is exactly one element more than something from `𝒜`.
See also `Finset.mem_upShadow_iff_exists_mem_card_add_one`. -/
lemma mem_upShadow_iff_exists_sdiff : t ∈ ∂⁺ 𝒜 ↔ ∃ s ∈ 𝒜, s ⊆ t ∧ #(t \ s) = 1 := by
simp_rw [mem_upShadow_iff, ← covBy_iff_card_sdiff_eq_one, covBy_iff_exists_insert]
/-- `t` is in the upper shadow of `𝒜` iff we can remove an element from it so that the resulting
finset is in `𝒜`. -/
lemma mem_upShadow_iff_erase_mem : t ∈ ∂⁺ 𝒜 ↔ ∃ a, a ∈ t ∧ erase t a ∈ 𝒜 := by
simp_rw [mem_upShadow_iff_exists_sdiff, ← covBy_iff_card_sdiff_eq_one, covBy_iff_exists_erase]
aesop
/-- `t` is in the upper shadow of `𝒜` iff `t` is exactly one element less than something from `𝒜`.
See also `Finset.mem_upShadow_iff_exists_sdiff`. -/
lemma mem_upShadow_iff_exists_mem_card_add_one :
t ∈ ∂⁺ 𝒜 ↔ ∃ s ∈ 𝒜, s ⊆ t ∧ #t = #s + 1 := by
refine mem_upShadow_iff_exists_sdiff.trans <| exists_congr fun t ↦ and_congr_right fun _ ↦
and_congr_right fun hst ↦ ?_
rw [card_sdiff_of_subset hst, tsub_eq_iff_eq_add_of_le, add_comm]
exact card_mono hst
lemma mem_upShadow_iterate_iff_exists_card :
t ∈ ∂⁺^[k] 𝒜 ↔ ∃ u : Finset α, #u = k ∧ u ⊆ t ∧ t \ u ∈ 𝒜 := by
induction k generalizing t with
| zero => simp
| succ k ih =>
simp only [mem_upShadow_iff_erase_mem, ih, Function.iterate_succ_apply', card_eq_succ,
subset_erase, erase_sdiff_comm, ← sdiff_insert]
constructor
· rintro ⟨a, hat, u, rfl, ⟨hut, hau⟩, htu⟩
exact ⟨_, ⟨_, _, hau, rfl, rfl⟩, insert_subset hat hut, htu⟩
· rintro ⟨_, ⟨a, u, hau, rfl, rfl⟩, hut, htu⟩
rw [insert_subset_iff] at hut
exact ⟨a, hut.1, _, rfl, ⟨hut.2, hau⟩, htu⟩
/-- `t` is in the upper shadow of `𝒜` iff `t` is exactly `k` elements less than something from `𝒜`.
See also `Finset.mem_upShadow_iff_exists_mem_card_add`. -/
lemma mem_upShadow_iterate_iff_exists_sdiff : t ∈ ∂⁺^[k] 𝒜 ↔ ∃ s ∈ 𝒜, s ⊆ t ∧ #(t \ s) = k := by
rw [mem_upShadow_iterate_iff_exists_card]
constructor
· rintro ⟨u, rfl, hut, htu⟩
exact ⟨_, htu, sdiff_subset, by rw [sdiff_sdiff_eq_self hut]⟩
· rintro ⟨s, hs, hst, rfl⟩
exact ⟨_, rfl, sdiff_subset, by rwa [sdiff_sdiff_eq_self hst]⟩
/-- `t ∈ ∂⁺^k 𝒜` iff `t` is exactly `k` elements less than something in `𝒜`.
See also `Finset.mem_upShadow_iterate_iff_exists_sdiff`. -/
lemma mem_upShadow_iterate_iff_exists_mem_card_add :
t ∈ ∂⁺^[k] 𝒜 ↔ ∃ s ∈ 𝒜, s ⊆ t ∧ #t = #s + k := by
refine mem_upShadow_iterate_iff_exists_sdiff.trans <| exists_congr fun t ↦ and_congr_right fun _ ↦
and_congr_right fun hst ↦ ?_
rw [card_sdiff_of_subset hst, tsub_eq_iff_eq_add_of_le, add_comm]
exact card_mono hst
/-- The upper shadow of a family of `r`-sets is a family of `r + 1`-sets. -/
protected lemma _root_.Set.Sized.upShadow (h𝒜 : (𝒜 : Set (Finset α)).Sized r) :
(∂⁺ 𝒜 : Set (Finset α)).Sized (r + 1) := by
intro A h
obtain ⟨A, hA, i, hi, rfl⟩ := mem_upShadow_iff.1 h
rw [card_insert_of_notMem hi, h𝒜 hA]
/-- Being in the upper shadow of `𝒜` means we have a superset in `𝒜`. -/
theorem exists_subset_of_mem_upShadow (hs : s ∈ ∂⁺ 𝒜) : ∃ t ∈ 𝒜, t ⊆ s :=
let ⟨t, ht, hts, _⟩ := mem_upShadow_iff_exists_mem_card_add_one.1 hs
⟨t, ht, hts⟩
/-- `t ∈ ∂^k 𝒜` iff `t` is exactly `k` elements more than something in `𝒜`. -/
theorem mem_upShadow_iff_exists_mem_card_add :
s ∈ ∂⁺ ^[k] 𝒜 ↔ ∃ t ∈ 𝒜, t ⊆ s ∧ #t + k = #s := by
induction k generalizing 𝒜 s with
| zero =>
refine ⟨fun hs => ⟨s, hs, Subset.refl _, rfl⟩, ?_⟩
rintro ⟨t, ht, hst, hcard⟩
rwa [← eq_of_subset_of_card_le hst hcard.ge]
| succ k ih =>
simp only [Function.comp_apply, Function.iterate_succ]
refine ih.trans ?_
clear ih
constructor
· rintro ⟨t, ht, hts, hcardst⟩
obtain ⟨u, hu, hut, hcardtu⟩ := mem_upShadow_iff_exists_mem_card_add_one.1 ht
refine ⟨u, hu, hut.trans hts, ?_⟩
rw [← hcardst, hcardtu, add_right_comm]
rfl
· rintro ⟨t, ht, hts, hcard⟩
obtain ⟨u, htu, hus, hu⟩ := Finset.exists_subsuperset_card_eq hts (Nat.le_add_right _ 1)
(by cutsat)
refine ⟨u, mem_upShadow_iff_exists_mem_card_add_one.2 ⟨t, ht, htu, hu⟩, hus, ?_⟩
rw [hu, ← hcard, add_right_comm]
rfl
@[simp] lemma shadow_compls : ∂ 𝒜ᶜˢ = (∂⁺ 𝒜)ᶜˢ := by
ext s
simp only [mem_shadow_iff, mem_upShadow_iff, mem_compls]
refine (compl_involutive.toPerm _).exists_congr_left.trans ?_
simp [← compl_involutive.eq_iff]
@[simp] lemma upShadow_compls : ∂⁺ 𝒜ᶜˢ = (∂ 𝒜)ᶜˢ := by
ext s
simp only [mem_shadow_iff, mem_upShadow_iff, mem_compls]
refine (compl_involutive.toPerm _).exists_congr_left.trans ?_
simp [← compl_involutive.eq_iff]
end UpShadow
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/Intersecting.lean | import Mathlib.Data.Fintype.Card
import Mathlib.Order.UpperLower.Basic
/-!
# Intersecting families
This file defines intersecting families and proves their basic properties.
## Main declarations
* `Set.Intersecting`: Predicate for a set of elements in a generalized Boolean algebra to be an
intersecting family.
* `Set.Intersecting.card_le`: An intersecting family can only take up to half the elements, because
`a` and `aᶜ` cannot simultaneously be in it.
* `Set.Intersecting.is_max_iff_card_eq`: Any maximal intersecting family takes up half the elements.
## References
* [D. J. Kleitman, *Families of non-disjoint subsets*][kleitman1966]
-/
assert_not_exists Monoid
open Finset
variable {α : Type*}
namespace Set
section SemilatticeInf
variable [SemilatticeInf α] [OrderBot α] {s t : Set α} {a b c : α}
/-- A set family is intersecting if every pair of elements is non-disjoint. -/
def Intersecting (s : Set α) : Prop :=
∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → ¬Disjoint a b
@[mono]
theorem Intersecting.mono (h : t ⊆ s) (hs : s.Intersecting) : t.Intersecting := fun _a ha _b hb =>
hs (h ha) (h hb)
theorem Intersecting.bot_notMem (hs : s.Intersecting) : ⊥ ∉ s := fun h => hs h h disjoint_bot_left
@[deprecated (since := "2025-05-24")]
alias Intersecting.not_bot_mem := Intersecting.bot_notMem
theorem Intersecting.ne_bot (hs : s.Intersecting) (ha : a ∈ s) : a ≠ ⊥ :=
ne_of_mem_of_not_mem ha hs.bot_notMem
theorem intersecting_empty : (∅ : Set α).Intersecting := fun _ => False.elim
@[simp]
theorem intersecting_singleton : ({a} : Set α).Intersecting ↔ a ≠ ⊥ := by simp [Intersecting]
protected theorem Intersecting.insert (hs : s.Intersecting) (ha : a ≠ ⊥)
(h : ∀ b ∈ s, ¬Disjoint a b) : (insert a s).Intersecting := by
rintro b (rfl | hb) c (rfl | hc)
· rwa [disjoint_self]
· exact h _ hc
· exact fun H => h _ hb H.symm
· exact hs hb hc
theorem intersecting_insert :
(insert a s).Intersecting ↔ s.Intersecting ∧ a ≠ ⊥ ∧ ∀ b ∈ s, ¬Disjoint a b :=
⟨fun h =>
⟨h.mono <| subset_insert _ _, h.ne_bot <| mem_insert _ _, fun _b hb =>
h (mem_insert _ _) <| mem_insert_of_mem _ hb⟩,
fun h => h.1.insert h.2.1 h.2.2⟩
theorem intersecting_iff_pairwise_not_disjoint :
s.Intersecting ↔ (s.Pairwise fun a b => ¬Disjoint a b) ∧ s ≠ {⊥} := by
refine ⟨fun h => ⟨fun a ha b hb _ => h ha hb, ?_⟩, fun h a ha b hb hab => ?_⟩
· rintro rfl
exact intersecting_singleton.1 h rfl
have := h.1.eq ha hb (Classical.not_not.2 hab)
rw [this, disjoint_self] at hab
rw [hab] at hb
exact
h.2
(eq_singleton_iff_unique_mem.2
⟨hb, fun c hc => not_ne_iff.1 fun H => h.1 hb hc H.symm disjoint_bot_left⟩)
protected theorem Subsingleton.intersecting (hs : s.Subsingleton) : s.Intersecting ↔ s ≠ {⊥} :=
intersecting_iff_pairwise_not_disjoint.trans <| and_iff_right <| hs.pairwise _
theorem intersecting_iff_eq_empty_of_subsingleton [Subsingleton α] (s : Set α) :
s.Intersecting ↔ s = ∅ := by
refine
subsingleton_of_subsingleton.intersecting.trans
⟨not_imp_comm.2 fun h => subsingleton_of_subsingleton.eq_singleton_of_mem ?_, ?_⟩
· obtain ⟨a, ha⟩ := nonempty_iff_ne_empty.2 h
rwa [Subsingleton.elim ⊥ a]
· rintro rfl
exact (Set.singleton_nonempty _).ne_empty.symm
/-- Maximal intersecting families are upper sets. -/
protected theorem Intersecting.isUpperSet (hs : s.Intersecting)
(h : ∀ t : Set α, t.Intersecting → s ⊆ t → s = t) : IsUpperSet s := by
classical
rintro a b hab ha
rw [h (Insert.insert b s) _ (subset_insert _ _)]
· exact mem_insert _ _
exact
hs.insert (mt (eq_bot_mono hab) <| hs.ne_bot ha) fun c hc hbc => hs ha hc <| hbc.mono_left hab
/-- Maximal intersecting families are upper sets. Finset version. -/
theorem Intersecting.isUpperSet' {s : Finset α} (hs : (s : Set α).Intersecting)
(h : ∀ t : Finset α, (t : Set α).Intersecting → s ⊆ t → s = t) : IsUpperSet (s : Set α) := by
classical
rintro a b hab ha
rw [h (Insert.insert b s) _ (Finset.subset_insert _ _)]
· exact mem_insert_self _ _
rw [coe_insert]
exact
hs.insert (mt (eq_bot_mono hab) <| hs.ne_bot ha) fun c hc hbc => hs ha hc <| hbc.mono_left hab
end SemilatticeInf
theorem Intersecting.exists_mem_set {𝒜 : Set (Set α)} (h𝒜 : 𝒜.Intersecting) {s t : Set α}
(hs : s ∈ 𝒜) (ht : t ∈ 𝒜) : ∃ a, a ∈ s ∧ a ∈ t :=
not_disjoint_iff.1 <| h𝒜 hs ht
theorem Intersecting.exists_mem_finset [DecidableEq α] {𝒜 : Set (Finset α)} (h𝒜 : 𝒜.Intersecting)
{s t : Finset α} (hs : s ∈ 𝒜) (ht : t ∈ 𝒜) : ∃ a, a ∈ s ∧ a ∈ t :=
not_disjoint_iff.1 <| disjoint_coe.not.2 <| h𝒜 hs ht
variable [BooleanAlgebra α]
theorem Intersecting.compl_notMem {s : Set α} (hs : s.Intersecting) {a : α} (ha : a ∈ s) :
aᶜ ∉ s := fun h => hs ha h disjoint_compl_right
@[deprecated (since := "2025-05-24")]
alias Intersecting.not_compl_mem := Intersecting.compl_notMem
theorem Intersecting.notMem {s : Set α} (hs : s.Intersecting) {a : α} (ha : aᶜ ∈ s) : a ∉ s :=
fun h => hs ha h disjoint_compl_left
@[deprecated (since := "2025-05-23")] alias Intersecting.not_mem := Intersecting.notMem
theorem Intersecting.disjoint_map_compl {s : Finset α} (hs : (s : Set α).Intersecting) :
Disjoint s (s.map ⟨compl, compl_injective⟩) := by
rw [Finset.disjoint_left]
rintro x hx hxc
obtain ⟨x, hx', rfl⟩ := mem_map.mp hxc
exact hs.compl_notMem hx' hx
theorem Intersecting.card_le [Fintype α] {s : Finset α} (hs : (s : Set α).Intersecting) :
2 * #s ≤ Fintype.card α := by
classical
refine (s.disjUnion _ hs.disjoint_map_compl).card_le_univ.trans_eq' ?_
rw [Nat.two_mul, card_disjUnion, card_map]
variable [Nontrivial α] [Fintype α] {s : Finset α}
-- Note, this lemma is false when `α` has exactly one element and boring when `α` is empty.
theorem Intersecting.is_max_iff_card_eq (hs : (s : Set α).Intersecting) :
(∀ t : Finset α, (t : Set α).Intersecting → s ⊆ t → s = t) ↔ 2 * #s = Fintype.card α := by
classical
refine ⟨fun h ↦ ?_, fun h t ht hst ↦ Finset.eq_of_subset_of_card_le hst <|
Nat.le_of_mul_le_mul_left (ht.card_le.trans_eq h.symm) Nat.two_pos⟩
suffices s.disjUnion (s.map ⟨compl, compl_injective⟩) hs.disjoint_map_compl = Finset.univ by
rw [Fintype.card, ← this, Nat.two_mul, card_disjUnion, card_map]
rw [← coe_eq_univ, disjUnion_eq_union, coe_union, coe_map, Function.Embedding.coeFn_mk,
image_eq_preimage_of_inverse compl_compl compl_compl]
refine eq_univ_of_forall fun a => ?_
simp_rw [mem_union, mem_preimage]
by_contra! ha
refine s.ne_insert_of_notMem _ ha.1 (h _ ?_ <| s.subset_insert _)
rw [coe_insert]
refine hs.insert ?_ fun b hb hab => ha.2 <| (hs.isUpperSet' h) hab.le_compl_left hb
rintro rfl
have := h {⊤} (by rw [coe_singleton]; exact intersecting_singleton.2 top_ne_bot)
rw [compl_bot] at ha
rw [coe_eq_empty.1 ((hs.isUpperSet' h).top_notMem.1 ha.2)] at this
exact Finset.singleton_ne_empty _ (this <| Finset.empty_subset _).symm
theorem Intersecting.exists_card_eq (hs : (s : Set α).Intersecting) :
∃ t, s ⊆ t ∧ 2 * #t = Fintype.card α ∧ (t : Set α).Intersecting := by
have := hs.card_le
rw [Nat.mul_comm, ← Nat.le_div_iff_mul_le Nat.two_pos] at this
revert hs
refine s.strongDownwardInductionOn ?_ this
rintro s ih _hcard hs
by_cases! h : ∀ t : Finset α, (t : Set α).Intersecting → s ⊆ t → s = t
· exact ⟨s, Subset.rfl, hs.is_max_iff_card_eq.1 h, hs⟩
obtain ⟨t, ht, hst⟩ := h
refine (ih ?_ (_root_.ssubset_iff_subset_ne.2 hst) ht).imp fun u => And.imp_left hst.1.trans
rw [Nat.le_div_iff_mul_le Nat.two_pos, Nat.mul_comm]
exact ht.card_le
end Set |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/FourFunctions.lean | import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Algebra.Order.Pi
import Mathlib.Algebra.Order.Ring.Nat
import Mathlib.Data.Finset.Sups
import Mathlib.Order.Birkhoff
import Mathlib.Order.Booleanisation
import Mathlib.Order.Sublattice
import Mathlib.Tactic.Positivity.Basic
import Mathlib.Tactic.Ring
import Mathlib.Tactic.GCongr
/-!
# The four functions theorem and corollaries
This file proves the four functions theorem. The statement is that if
`f₁ a * f₂ b ≤ f₃ (a ⊓ b) * f₄ (a ⊔ b)` for all `a`, `b` in a finite distributive lattice, then
`(∑ x ∈ s, f₁ x) * (∑ x ∈ t, f₂ x) ≤ (∑ x ∈ s ⊼ t, f₃ x) * (∑ x ∈ s ⊻ t, f₄ x)` where
`s ⊼ t = {a ⊓ b | a ∈ s, b ∈ t}`, `s ⊻ t = {a ⊔ b | a ∈ s, b ∈ t}`.
The proof uses Birkhoff's representation theorem to restrict to the case where the finite
distributive lattice is in fact a finite powerset algebra, namely `Finset α` for some finite `α`.
Then it proves this new statement by induction on the size of `α`.
## Main declarations
The two versions of the four functions theorem are
* `Finset.four_functions_theorem` for finite powerset algebras.
* `four_functions_theorem` for any finite distributive lattices.
We deduce a number of corollaries:
* `Finset.le_card_infs_mul_card_sups`: Daykin inequality. `|s| |t| ≤ |s ⊼ t| |s ⊻ t|`
* `holley`: Holley inequality.
* `fkg`: Fortuin-Kastelyn-Ginibre inequality.
* `Finset.card_le_card_diffs`: Marica-Schönheim inequality. `|s| ≤ |{a \ b | a, b ∈ s}|`
## TODO
Prove that lattices in which `Finset.le_card_infs_mul_card_sups` holds are distributive. See
Daykin, *A lattice is distributive iff |A| |B| <= |A ∨ B| |A ∧ B|*
Prove the Fishburn-Shepp inequality.
Is `collapse` a construct generally useful for set family inductions? If so, we should move it to an
earlier file and give it a proper API.
## References
[*Applications of the FKG Inequality and Its Relatives*, Graham][Graham1983]
-/
open Finset Fintype Function
open scoped FinsetFamily
variable {α β : Type*}
section Finset
variable [DecidableEq α] [CommSemiring β] [LinearOrder β] [IsStrictOrderedRing β]
{𝒜 : Finset (Finset α)} {a : α} {f f₁ f₂ f₃ f₄ : Finset α → β} {s t u : Finset α}
/-- The `n = 1` case of the Ahlswede-Daykin inequality. Note that we can't just expand everything
out and bound termwise since `c₀ * d₁` appears twice on the RHS of the assumptions while `c₁ * d₀`
does not appear. -/
private lemma ineq [ExistsAddOfLE β] {a₀ a₁ b₀ b₁ c₀ c₁ d₀ d₁ : β}
(ha₀ : 0 ≤ a₀) (ha₁ : 0 ≤ a₁) (hb₀ : 0 ≤ b₀) (hb₁ : 0 ≤ b₁)
(hc₀ : 0 ≤ c₀) (hc₁ : 0 ≤ c₁) (hd₀ : 0 ≤ d₀) (hd₁ : 0 ≤ d₁)
(h₀₀ : a₀ * b₀ ≤ c₀ * d₀) (h₁₀ : a₁ * b₀ ≤ c₀ * d₁)
(h₀₁ : a₀ * b₁ ≤ c₀ * d₁) (h₁₁ : a₁ * b₁ ≤ c₁ * d₁) :
(a₀ + a₁) * (b₀ + b₁) ≤ (c₀ + c₁) * (d₀ + d₁) := by
calc
_ = a₀ * b₀ + (a₀ * b₁ + a₁ * b₀) + a₁ * b₁ := by ring
_ ≤ c₀ * d₀ + (c₀ * d₁ + c₁ * d₀) + c₁ * d₁ := add_le_add_three h₀₀ ?_ h₁₁
_ = (c₀ + c₁) * (d₀ + d₁) := by ring
obtain hcd | hcd := (mul_nonneg hc₀ hd₁).eq_or_lt'
· rw [hcd] at h₀₁ h₁₀
rw [h₀₁.antisymm, h₁₀.antisymm, add_zero] <;> positivity
refine le_of_mul_le_mul_right ?_ hcd
calc (a₀ * b₁ + a₁ * b₀) * (c₀ * d₁)
= a₀ * b₁ * (c₀ * d₁) + c₀ * d₁ * (a₁ * b₀) := by ring
_ ≤ a₀ * b₁ * (a₁ * b₀) + c₀ * d₁ * (c₀ * d₁) := mul_add_mul_le_mul_add_mul h₀₁ h₁₀
_ = a₀ * b₀ * (a₁ * b₁) + c₀ * d₁ * (c₀ * d₁) := by ring
_ ≤ c₀ * d₀ * (c₁ * d₁) + c₀ * d₁ * (c₀ * d₁) := by gcongr
_ = (c₀ * d₁ + c₁ * d₀) * (c₀ * d₁) := by ring
private def collapse (𝒜 : Finset (Finset α)) (a : α) (f : Finset α → β) (s : Finset α) : β :=
∑ t ∈ 𝒜 with t.erase a = s, f t
private lemma erase_eq_iff (hs : a ∉ s) : t.erase a = s ↔ t = s ∨ t = insert a s := by
grind
private lemma filter_collapse_eq (ha : a ∉ s) (𝒜 : Finset (Finset α)) :
{t ∈ 𝒜 | t.erase a = s} =
if s ∈ 𝒜 then
(if insert a s ∈ 𝒜 then {s, insert a s} else {s})
else
(if insert a s ∈ 𝒜 then {insert a s} else ∅) := by
ext t; split_ifs <;> simp [erase_eq_iff ha] <;> aesop
omit [LinearOrder β] [IsStrictOrderedRing β] in
lemma collapse_eq (ha : a ∉ s) (𝒜 : Finset (Finset α)) (f : Finset α → β) :
collapse 𝒜 a f s = (if s ∈ 𝒜 then f s else 0) +
if insert a s ∈ 𝒜 then f (insert a s) else 0 := by
rw [collapse, filter_collapse_eq ha]
split_ifs <;> simp [(ne_of_mem_of_not_mem' (mem_insert_self a s) ha).symm, *]
omit [LinearOrder β] [IsStrictOrderedRing β] in
lemma collapse_of_mem (ha : a ∉ s) (ht : t ∈ 𝒜) (hu : u ∈ 𝒜) (hts : t = s)
(hus : u = insert a s) : collapse 𝒜 a f s = f t + f u := by
subst hts; subst hus; simp_rw [collapse_eq ha, if_pos ht, if_pos hu]
lemma le_collapse_of_mem (ha : a ∉ s) (hf : 0 ≤ f) (hts : t = s) (ht : t ∈ 𝒜) :
f t ≤ collapse 𝒜 a f s := by
subst hts
rw [collapse_eq ha, if_pos ht]
split_ifs
· exact le_add_of_nonneg_right <| hf _
· rw [add_zero]
lemma le_collapse_of_insert_mem (ha : a ∉ s) (hf : 0 ≤ f) (hts : t = insert a s) (ht : t ∈ 𝒜) :
f t ≤ collapse 𝒜 a f s := by
rw [collapse_eq ha, ← hts, if_pos ht]
split_ifs
· exact le_add_of_nonneg_left <| hf _
· rw [zero_add]
lemma collapse_nonneg (hf : 0 ≤ f) : 0 ≤ collapse 𝒜 a f := fun _s ↦ sum_nonneg fun _t _ ↦ hf _
lemma collapse_modular [ExistsAddOfLE β]
(hu : a ∉ u) (h₁ : 0 ≤ f₁) (h₂ : 0 ≤ f₂) (h₃ : 0 ≤ f₃) (h₄ : 0 ≤ f₄)
(h : ∀ ⦃s⦄, s ⊆ insert a u → ∀ ⦃t⦄, t ⊆ insert a u → f₁ s * f₂ t ≤ f₃ (s ∩ t) * f₄ (s ∪ t))
(𝒜 ℬ : Finset (Finset α)) :
∀ ⦃s⦄, s ⊆ u → ∀ ⦃t⦄, t ⊆ u → collapse 𝒜 a f₁ s * collapse ℬ a f₂ t ≤
collapse (𝒜 ⊼ ℬ) a f₃ (s ∩ t) * collapse (𝒜 ⊻ ℬ) a f₄ (s ∪ t) := by
rintro s hsu t htu
-- Gather a bunch of facts we'll need a lot
have := hsu.trans <| subset_insert a _
have := htu.trans <| subset_insert a _
have := insert_subset_insert a hsu
have := insert_subset_insert a htu
have has := notMem_mono hsu hu
have hat := notMem_mono htu hu
have : a ∉ s ∩ t := notMem_mono (inter_subset_left.trans hsu) hu
have := notMem_union.2 ⟨has, hat⟩
rw [collapse_eq has]
split_ifs
· rw [collapse_eq hat]
split_ifs
· rw [collapse_of_mem ‹_› (inter_mem_infs ‹_› ‹_›) (inter_mem_infs ‹_› ‹_›) rfl
(insert_inter_distrib _ _ _).symm, collapse_of_mem ‹_› (union_mem_sups ‹_› ‹_›)
(union_mem_sups ‹_› ‹_›) rfl (insert_union_distrib _ _ _).symm]
refine ineq (h₁ _) (h₁ _) (h₂ _) (h₂ _) (h₃ _) (h₃ _) (h₄ _) (h₄ _) (h ‹_› ‹_›) ?_ ?_ ?_
· simpa [*] using h ‹insert a s ⊆ _› ‹t ⊆ _›
· simpa [*] using h ‹s ⊆ _› ‹insert a t ⊆ _›
· simpa [*] using h ‹insert a s ⊆ _› ‹insert a t ⊆ _›
· rw [add_zero, add_mul]
refine (add_le_add (h ‹_› ‹_›) <| h ‹_› ‹_›).trans ?_
rw [collapse_of_mem ‹_› (union_mem_sups ‹_› ‹_›) (union_mem_sups ‹_› ‹_›) rfl
(insert_union _ _ _), insert_inter_of_notMem ‹_›, ← mul_add]
gcongr
exacts [add_nonneg (h₄ _) <| h₄ _, le_collapse_of_mem ‹_› h₃ rfl <| inter_mem_infs ‹_› ‹_›]
· rw [zero_add, add_mul]
refine (add_le_add (h ‹_› ‹_›) <| h ‹_› ‹_›).trans ?_
rw [collapse_of_mem ‹_› (inter_mem_infs ‹_› ‹_›) (inter_mem_infs ‹_› ‹_›)
(inter_insert_of_notMem ‹_›) (insert_inter_distrib _ _ _).symm, union_insert,
insert_union_distrib, ← add_mul]
gcongr
exacts [add_nonneg (h₃ _) <| h₃ _,
le_collapse_of_insert_mem ‹_› h₄ (insert_union_distrib _ _ _).symm (union_mem_sups ‹_› ‹_›)]
· rw [add_zero, mul_zero]
exact mul_nonneg (collapse_nonneg h₃ _) <| collapse_nonneg h₄ _
· rw [add_zero, collapse_eq hat, mul_add]
split_ifs
· refine (add_le_add (h ‹_› ‹_›) <| h ‹_› ‹_›).trans ?_
rw [collapse_of_mem ‹_› (union_mem_sups ‹_› ‹_›) (union_mem_sups ‹_› ‹_›) rfl
(union_insert _ _ _), inter_insert_of_notMem ‹_›, ← mul_add]
exact mul_le_mul_of_nonneg_right (le_collapse_of_mem ‹_› h₃ rfl <| inter_mem_infs ‹_› ‹_›) <|
add_nonneg (h₄ _) <| h₄ _
· rw [mul_zero, add_zero]
exact (h ‹_› ‹_›).trans <| mul_le_mul (le_collapse_of_mem ‹_› h₃ rfl <|
inter_mem_infs ‹_› ‹_›) (le_collapse_of_mem ‹_› h₄ rfl <| union_mem_sups ‹_› ‹_›)
(h₄ _) <| collapse_nonneg h₃ _
· rw [mul_zero, zero_add]
refine (h ‹_› ‹_›).trans <| mul_le_mul ?_ (le_collapse_of_insert_mem ‹_› h₄
(union_insert _ _ _) <| union_mem_sups ‹_› ‹_›) (h₄ _) <| collapse_nonneg h₃ _
exact le_collapse_of_mem (notMem_mono inter_subset_left ‹_›) h₃
(inter_insert_of_notMem ‹_›) <| inter_mem_infs ‹_› ‹_›
· simp_rw [mul_zero, add_zero]
exact mul_nonneg (collapse_nonneg h₃ _) <| collapse_nonneg h₄ _
· rw [zero_add, collapse_eq hat, mul_add]
split_ifs
· refine (add_le_add (h ‹_› ‹_›) <| h ‹_› ‹_›).trans ?_
rw [collapse_of_mem ‹_› (inter_mem_infs ‹_› ‹_›) (inter_mem_infs ‹_› ‹_›)
(insert_inter_of_notMem ‹_›) (insert_inter_distrib _ _ _).symm,
insert_inter_of_notMem ‹_›, ← insert_inter_distrib, insert_union, insert_union_distrib,
← add_mul]
exact mul_le_mul_of_nonneg_left (le_collapse_of_insert_mem ‹_› h₄
(insert_union_distrib _ _ _).symm <| union_mem_sups ‹_› ‹_›) <| add_nonneg (h₃ _) <| h₃ _
· rw [mul_zero, add_zero]
refine (h ‹_› ‹_›).trans <| mul_le_mul (le_collapse_of_mem ‹_› h₃
(insert_inter_of_notMem ‹_›) <| inter_mem_infs ‹_› ‹_›) (le_collapse_of_insert_mem ‹_› h₄
(insert_union _ _ _) <| union_mem_sups ‹_› ‹_›) (h₄ _) <| collapse_nonneg h₃ _
· rw [mul_zero, zero_add]
exact (h ‹_› ‹_›).trans <| mul_le_mul (le_collapse_of_insert_mem ‹_› h₃
(insert_inter_distrib _ _ _).symm <| inter_mem_infs ‹_› ‹_›) (le_collapse_of_insert_mem ‹_›
h₄ (insert_union_distrib _ _ _).symm <| union_mem_sups ‹_› ‹_›) (h₄ _) <|
collapse_nonneg h₃ _
· simp_rw [mul_zero, add_zero]
exact mul_nonneg (collapse_nonneg h₃ _) <| collapse_nonneg h₄ _
· simp_rw [add_zero, zero_mul]
exact mul_nonneg (collapse_nonneg h₃ _) <| collapse_nonneg h₄ _
omit [LinearOrder β] [IsStrictOrderedRing β] in
lemma sum_collapse (h𝒜 : 𝒜 ⊆ (insert a u).powerset) (hu : a ∉ u) :
∑ s ∈ u.powerset, collapse 𝒜 a f s = ∑ s ∈ 𝒜, f s := by
calc
_ = ∑ s ∈ u.powerset ∩ 𝒜, f s + ∑ s ∈ u.powerset.image (insert a) ∩ 𝒜, f s := ?_
_ = ∑ s ∈ u.powerset ∩ 𝒜, f s + ∑ s ∈ ((insert a u).powerset \ u.powerset) ∩ 𝒜, f s := ?_
_ = ∑ s ∈ 𝒜, f s := ?_
· rw [← Finset.sum_ite_mem, ← Finset.sum_ite_mem, sum_image, ← sum_add_distrib]
· exact sum_congr rfl fun s hs ↦ collapse_eq (notMem_mono (mem_powerset.1 hs) hu) _ _
· exact (insert_erase_invOn.2.injOn).mono fun s hs ↦ notMem_mono (mem_powerset.1 hs) hu
· congr with s
simp only [mem_image, mem_powerset, mem_sdiff, subset_insert_iff]
refine ⟨?_, fun h ↦ ⟨_, h.1, ?_⟩⟩
· rintro ⟨s, hs, rfl⟩
exact ⟨subset_insert_iff.1 <| insert_subset_insert _ hs, fun h ↦
hu <| h <| mem_insert_self _ _⟩
· rw [insert_erase (erase_ne_self.1 fun hs ↦ ?_)]
rw [hs] at h
exact h.2 h.1
· rw [← sum_union (disjoint_sdiff_self_right.mono inf_le_left inf_le_left),
← union_inter_distrib_right, union_sdiff_of_subset (powerset_mono.2 <| subset_insert _ _),
inter_eq_right.2 h𝒜]
variable [ExistsAddOfLE β]
/-- The **Four Functions Theorem** on a powerset algebra. See `four_functions_theorem` for the
finite distributive lattice generalisation. -/
protected lemma Finset.four_functions_theorem (u : Finset α)
(h₁ : 0 ≤ f₁) (h₂ : 0 ≤ f₂) (h₃ : 0 ≤ f₃) (h₄ : 0 ≤ f₄)
(h : ∀ ⦃s⦄, s ⊆ u → ∀ ⦃t⦄, t ⊆ u → f₁ s * f₂ t ≤ f₃ (s ∩ t) * f₄ (s ∪ t))
{𝒜 ℬ : Finset (Finset α)} (h𝒜 : 𝒜 ⊆ u.powerset) (hℬ : ℬ ⊆ u.powerset) :
(∑ s ∈ 𝒜, f₁ s) * ∑ s ∈ ℬ, f₂ s ≤ (∑ s ∈ 𝒜 ⊼ ℬ, f₃ s) * ∑ s ∈ 𝒜 ⊻ ℬ, f₄ s := by
induction u using Finset.induction generalizing f₁ f₂ f₃ f₄ 𝒜 ℬ with
| empty =>
simp only [Finset.powerset_empty, Finset.subset_singleton_iff] at h𝒜 hℬ
obtain rfl | rfl := h𝒜 <;> obtain rfl | rfl := hℬ <;> simp; exact h (subset_refl ∅) subset_rfl
| insert a u hu ih =>
specialize ih (collapse_nonneg h₁) (collapse_nonneg h₂) (collapse_nonneg h₃)
(collapse_nonneg h₄) (collapse_modular hu h₁ h₂ h₃ h₄ h 𝒜 ℬ) Subset.rfl Subset.rfl
have : 𝒜 ⊼ ℬ ⊆ powerset (insert a u) := by simpa using infs_subset h𝒜 hℬ
have : 𝒜 ⊻ ℬ ⊆ powerset (insert a u) := by simpa using sups_subset h𝒜 hℬ
simpa only [powerset_sups_powerset_self, powerset_infs_powerset_self, sum_collapse,
not_false_eq_true, *] using ih
variable (f₁ f₂ f₃ f₄) [Fintype α]
private lemma four_functions_theorem_aux (h₁ : 0 ≤ f₁) (h₂ : 0 ≤ f₂) (h₃ : 0 ≤ f₃) (h₄ : 0 ≤ f₄)
(h : ∀ s t, f₁ s * f₂ t ≤ f₃ (s ∩ t) * f₄ (s ∪ t)) (𝒜 ℬ : Finset (Finset α)) :
(∑ s ∈ 𝒜, f₁ s) * ∑ s ∈ ℬ, f₂ s ≤ (∑ s ∈ 𝒜 ⊼ ℬ, f₃ s) * ∑ s ∈ 𝒜 ⊻ ℬ, f₄ s := by
refine univ.four_functions_theorem h₁ h₂ h₃ h₄ ?_ ?_ ?_ <;> simp [h]
end Finset
section DistribLattice
variable [DistribLattice α] [CommSemiring β] [LinearOrder β] [IsStrictOrderedRing β]
[ExistsAddOfLE β] (f f₁ f₂ f₃ f₄ g μ : α → β)
/-- The **Four Functions Theorem**, aka **Ahlswede-Daykin Inequality**. -/
lemma four_functions_theorem [DecidableEq α] (h₁ : 0 ≤ f₁) (h₂ : 0 ≤ f₂) (h₃ : 0 ≤ f₃) (h₄ : 0 ≤ f₄)
(h : ∀ a b, f₁ a * f₂ b ≤ f₃ (a ⊓ b) * f₄ (a ⊔ b)) (s t : Finset α) :
(∑ a ∈ s, f₁ a) * ∑ a ∈ t, f₂ a ≤ (∑ a ∈ s ⊼ t, f₃ a) * ∑ a ∈ s ⊻ t, f₄ a := by
classical
set L : Sublattice α := ⟨latticeClosure (s ∪ t), isSublattice_latticeClosure.1,
isSublattice_latticeClosure.2⟩
have : Finite L := (s.finite_toSet.union t.finite_toSet).latticeClosure.to_subtype
set s' : Finset L := s.preimage (↑) Subtype.coe_injective.injOn
set t' : Finset L := t.preimage (↑) Subtype.coe_injective.injOn
have hs' : s'.map ⟨L.subtype, Subtype.coe_injective⟩ = s := by
simpa [s', map_eq_image, image_preimage, filter_eq_self] using
fun a ha ↦ subset_latticeClosure <| Set.subset_union_left ha
have ht' : t'.map ⟨L.subtype, Subtype.coe_injective⟩ = t := by
simpa [t', map_eq_image, image_preimage, filter_eq_self] using
fun a ha ↦ subset_latticeClosure <| Set.subset_union_right ha
clear_value s' t'
obtain ⟨β, _, _, g, hg⟩ := exists_birkhoff_representation L
have := four_functions_theorem_aux (extend g (f₁ ∘ (↑)) 0) (extend g (f₂ ∘ (↑)) 0)
(extend g (f₃ ∘ (↑)) 0) (extend g (f₄ ∘ (↑)) 0) (extend_nonneg (fun _ ↦ h₁ _) le_rfl)
(extend_nonneg (fun _ ↦ h₂ _) le_rfl) (extend_nonneg (fun _ ↦ h₃ _) le_rfl)
(extend_nonneg (fun _ ↦ h₄ _) le_rfl) ?_ (s'.map ⟨g, hg⟩) (t'.map ⟨g, hg⟩)
· simpa only [← hs', ← ht', ← map_sups, ← map_infs, sum_map, Embedding.coeFn_mk, hg.extend_apply]
using this
rintro s t
classical
obtain ⟨a, rfl⟩ | hs := em (∃ a, g a = s)
· obtain ⟨b, rfl⟩ | ht := em (∃ b, g b = t)
· simp_rw [← sup_eq_union, ← inf_eq_inter, ← map_sup, ← map_inf, hg.extend_apply]
exact h _ _
· simpa [extend_apply' _ _ _ ht] using mul_nonneg
(extend_nonneg (fun a : L ↦ h₃ a) le_rfl _) (extend_nonneg (fun a : L ↦ h₄ a) le_rfl _)
· simpa [extend_apply' _ _ _ hs] using mul_nonneg
(extend_nonneg (fun a : L ↦ h₃ a) le_rfl _) (extend_nonneg (fun a : L ↦ h₄ a) le_rfl _)
/-- An inequality of Daykin. Interestingly, any lattice in which this inequality holds is
distributive. -/
lemma Finset.le_card_infs_mul_card_sups [DecidableEq α] (s t : Finset α) :
#s * #t ≤ #(s ⊼ t) * #(s ⊻ t) := by
simpa using four_functions_theorem (1 : α → ℕ) 1 1 1 zero_le_one zero_le_one zero_le_one
zero_le_one (fun _ _ ↦ le_rfl) s t
variable [Fintype α]
/-- Special case of the **Four Functions Theorem** when `s = t = univ`. -/
lemma four_functions_theorem_univ (h₁ : 0 ≤ f₁) (h₂ : 0 ≤ f₂) (h₃ : 0 ≤ f₃) (h₄ : 0 ≤ f₄)
(h : ∀ a b, f₁ a * f₂ b ≤ f₃ (a ⊓ b) * f₄ (a ⊔ b)) :
(∑ a, f₁ a) * ∑ a, f₂ a ≤ (∑ a, f₃ a) * ∑ a, f₄ a := by
classical simpa using four_functions_theorem f₁ f₂ f₃ f₄ h₁ h₂ h₃ h₄ h univ univ
/-- The **Holley Inequality**. -/
lemma holley (hμ₀ : 0 ≤ μ) (hf : 0 ≤ f) (hg : 0 ≤ g) (hμ : Monotone μ)
(hfg : ∑ a, f a = ∑ a, g a) (h : ∀ a b, f a * g b ≤ f (a ⊓ b) * g (a ⊔ b)) :
∑ a, μ a * f a ≤ ∑ a, μ a * g a := by
classical
obtain rfl | hf := hf.eq_or_lt
· simp only [Pi.zero_apply, sum_const_zero, eq_comm, Fintype.sum_eq_zero_iff_of_nonneg hg] at hfg
simp [hfg]
obtain rfl | hg := hg.eq_or_lt
· simp only [Pi.zero_apply, sum_const_zero, Fintype.sum_eq_zero_iff_of_nonneg hf.le] at hfg
simp [hfg]
have := four_functions_theorem g (μ * f) f (μ * g) hg.le (mul_nonneg hμ₀ hf.le) hf.le
(mul_nonneg hμ₀ hg.le) (fun a b ↦ ?_) univ univ
· simpa [hfg, sum_pos hg] using this
· simp_rw [Pi.mul_apply, mul_left_comm _ (μ _), mul_comm (g _)]
rw [sup_comm, inf_comm]
exact mul_le_mul (hμ le_sup_left) (h _ _) (mul_nonneg (hf.le _) <| hg.le _) <| hμ₀ _
/-- The **Fortuin-Kastelyn-Ginibre Inequality**. -/
lemma fkg (hμ₀ : 0 ≤ μ) (hf₀ : 0 ≤ f) (hg₀ : 0 ≤ g) (hf : Monotone f) (hg : Monotone g)
(hμ : ∀ a b, μ a * μ b ≤ μ (a ⊓ b) * μ (a ⊔ b)) :
(∑ a, μ a * f a) * ∑ a, μ a * g a ≤ (∑ a, μ a) * ∑ a, μ a * (f a * g a) := by
refine four_functions_theorem_univ (μ * f) (μ * g) μ _ (mul_nonneg hμ₀ hf₀) (mul_nonneg hμ₀ hg₀)
hμ₀ (mul_nonneg hμ₀ <| mul_nonneg hf₀ hg₀) (fun a b ↦ ?_)
dsimp
rw [mul_mul_mul_comm, ← mul_assoc (μ (a ⊓ b))]
exact mul_le_mul (hμ _ _) (mul_le_mul (hf le_sup_left) (hg le_sup_right) (hg₀ _) <| hf₀ _)
(mul_nonneg (hf₀ _) <| hg₀ _) <| mul_nonneg (hμ₀ _) <| hμ₀ _
end DistribLattice
open Booleanisation
variable [DecidableEq α] [GeneralizedBooleanAlgebra α]
/-- A slight generalisation of the **Marica-Schönheim Inequality**. -/
lemma Finset.le_card_diffs_mul_card_diffs (s t : Finset α) :
#s * #t ≤ #(s \\ t) * #(t \\ s) := by
have : ∀ s t : Finset α, (s \\ t).map ⟨_, liftLatticeHom_injective⟩ =
s.map ⟨_, liftLatticeHom_injective⟩ \\ t.map ⟨_, liftLatticeHom_injective⟩ := by
rintro s t
simp_rw [map_eq_image]
exact image_image₂_distrib fun a b ↦ rfl
simpa [← card_compls (_ ⊻ _), ← map_sup, ← map_inf, ← this] using
(s.map ⟨_, liftLatticeHom_injective⟩).le_card_infs_mul_card_sups
(t.map ⟨_, liftLatticeHom_injective⟩)ᶜˢ
/-- The **Marica-Schönheim Inequality**. -/
lemma Finset.card_le_card_diffs (s : Finset α) : #s ≤ #(s \\ s) :=
le_of_pow_le_pow_left₀ two_ne_zero (zero_le _) <| by
simpa [← sq] using s.le_card_diffs_mul_card_diffs s |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/KruskalKatona.lean | import Mathlib.Combinatorics.Colex
import Mathlib.Combinatorics.SetFamily.Compression.UV
import Mathlib.Combinatorics.SetFamily.Intersecting
import Mathlib.Data.Finset.Fin
/-!
# Kruskal-Katona theorem
This file proves the Kruskal-Katona theorem. This is a sharp statement about how many sets of size
`k - 1` are covered by a family of sets of size `k`, given only its size.
## Main declarations
The key results proved here are:
* `Finset.kruskal_katona`: The basic Kruskal-Katona theorem. Given a set family `𝒜` consisting of
`r`-sets, and `𝒞` an initial segment of the colex order of the same size, the shadow of `𝒞` is
smaller than the shadow of `𝒜`. In particular, this shows that the minimum shadow size is
achieved by initial segments of colex.
* `Finset.iterated_kruskal_katona`: An iterated form of the Kruskal-Katona theorem, stating that the
minimum iterated shadow size is given by initial segments of colex.
## TODO
* Define the `k`-cascade representation of a natural and prove the corresponding version of
Kruskal-Katona.
* Abstract away from `Fin n` so that it also applies to `ℕ`. Probably `LocallyFiniteOrderBot`
will help here.
* Characterise the equality case.
## References
* http://b-mehta.github.io/maths-notes/iii/mich/combinatorics.pdf
* http://discretemath.imp.fu-berlin.de/DMII-2015-16/kruskal.pdf
## Tags
kruskal-katona, kruskal, katona, shadow, initial segments, intersecting
-/
open Nat
open scoped FinsetFamily
namespace Finset
namespace Colex
variable {α : Type*} [LinearOrder α] {𝒜 : Finset (Finset α)} {s : Finset α} {r : ℕ}
/-- This is important for iterating Kruskal-Katona: the shadow of an initial segment is also an
initial segment. -/
lemma shadow_initSeg [Fintype α] (hs : s.Nonempty) :
∂ (initSeg s) = initSeg (erase s <| min' s hs) := by
-- This is a pretty painful proof, with lots of cases.
ext t
simp only [mem_shadow_iff_insert_mem, mem_initSeg]
constructor
-- First show that if t ∪ a ≤ s, then t ≤ s - min s
· rintro ⟨a, ha, hst, hts⟩
constructor
· rw [card_erase_of_mem (min'_mem _ _), hst, card_insert_of_notMem ha, add_tsub_cancel_right]
· simpa [ha] using erase_le_erase_min' hts hst.ge (mem_insert_self _ _)
-- Now show that if t ≤ s - min s, there is j such that t ∪ j ≤ s
-- We choose j as the smallest thing not in t
simp_rw [le_iff_eq_or_lt, lt_iff_exists_filter_lt, mem_sdiff, filter_inj, and_assoc]
simp only [toColex_inj, and_imp]
rintro cards' (rfl | ⟨k, hks, hkt, z⟩)
-- If t = s - min s, then use j = min s so t ∪ j = s
· refine ⟨min' s hs, notMem_erase _ _, ?_⟩
rw [insert_erase (min'_mem _ _)]
exact ⟨rfl, Or.inl rfl⟩
set j := min' tᶜ ⟨k, mem_compl.2 hkt⟩
-- Assume first t < s - min s, and take k as the colex witness for this
have hjk : j ≤ k := min'_le _ _ (mem_compl.2 ‹k ∉ t›)
have : j ∉ t := mem_compl.1 (min'_mem _ _)
have hcard : #s = #(insert j t) := by
rw [card_insert_of_notMem ‹j ∉ t›, ← ‹_ = #t›, card_erase_add_one (min'_mem _ _)]
refine ⟨j, ‹_›, hcard, ?_⟩
-- Cases on j < k or j = k
obtain hjk | r₁ := hjk.lt_or_eq
-- if j < k, k is our colex witness for t ∪ {j} < s
· refine Or.inr ⟨k, mem_of_mem_erase ‹_›, fun hk ↦ hkt <| mem_of_mem_insert_of_ne hk hjk.ne',
fun x hx ↦ ?_⟩
simpa only [mem_insert, z hx, (hjk.trans hx).ne', mem_erase, Ne, false_or,
and_iff_right_iff_imp] using fun _ ↦ ((min'_le _ _ <| mem_of_mem_erase hks).trans_lt hx).ne'
-- if j = k, all of range k is in t so by sizes t ∪ {j} = s
refine Or.inl (eq_of_subset_of_card_le (fun a ha ↦ ?_) hcard.ge).symm
rcases lt_trichotomy k a with (lt | rfl | gt)
· apply mem_insert_of_mem
rw [z lt]
refine mem_erase_of_ne_of_mem (lt_of_le_of_lt ?_ lt).ne' ha
apply min'_le _ _ (mem_of_mem_erase ‹_›)
· rw [r₁]; apply mem_insert_self
· apply mem_insert_of_mem
rw [← r₁] at gt
by_contra
apply (min'_le tᶜ _ _).not_gt gt
rwa [mem_compl]
/-- The shadow of an initial segment is also an initial segment. -/
protected lemma IsInitSeg.shadow [Finite α] (h₁ : IsInitSeg 𝒜 r) : IsInitSeg (∂ 𝒜) (r - 1) := by
cases nonempty_fintype α
obtain rfl | hr := Nat.eq_zero_or_pos r
· have : 𝒜 ⊆ {∅} := fun s hs ↦ by rw [mem_singleton, ← Finset.card_eq_zero]; exact h₁.1 hs
have := shadow_monotone this
simp only [subset_empty, le_eq_subset, shadow_singleton_empty] at this
simp [this]
obtain rfl | h𝒜 := 𝒜.eq_empty_or_nonempty
· simp
obtain ⟨s, rfl, rfl⟩ := h₁.exists_initSeg h𝒜
rw [shadow_initSeg (card_pos.1 hr), ← card_erase_of_mem (min'_mem _ _)]
exact isInitSeg_initSeg
end Colex
open Colex UV
open scoped FinsetFamily
variable {α : Type*} [LinearOrder α] {s U V : Finset α} {n : ℕ}
namespace UV
/-- Applying the compression makes the set smaller in colex. This is intuitive since a portion of
the set is being "shifted down" as `max U < max V`. -/
lemma toColex_compress_lt_toColex {hU : U.Nonempty} {hV : V.Nonempty} (h : max' U hU < max' V hV)
(hA : compress U V s ≠ s) : toColex (compress U V s) < toColex s := by
rw [compress, ite_ne_right_iff] at hA
rw [compress, if_pos hA.1, lt_iff_exists_filter_lt]
simp_rw [mem_sdiff (s := s), filter_inj, and_assoc]
refine ⟨_, hA.1.2 <| max'_mem _ hV, notMem_sdiff_of_mem_right <| max'_mem _ _, fun a ha ↦ ?_⟩
have : a ∉ V := fun H ↦ ha.not_ge (le_max' _ _ H)
have : a ∉ U := fun H ↦ ha.not_gt ((le_max' _ _ H).trans_lt h)
simp [‹a ∉ U›, ‹a ∉ V›]
/-- These are the compressions which we will apply to decrease the "measure" of a family of sets. -/
private def UsefulCompression (U V : Finset α) : Prop :=
Disjoint U V ∧ #U = #V ∧ ∃ (HU : U.Nonempty) (HV : V.Nonempty), max' U HU < max' V HV
private instance UsefulCompression.instDecidableRel :
DecidableRel (α := Finset α) UsefulCompression :=
fun _ _ ↦ inferInstanceAs (Decidable (_ ∧ _))
/-- Applying a good compression will decrease measure, keep cardinality, keep sizes and decrease
shadow. In particular, 'good' means it's useful, and every smaller compression won't make a
difference. -/
private lemma compression_improved (𝒜 : Finset (Finset α)) (h₁ : UsefulCompression U V)
(h₂ : ∀ ⦃U₁ V₁⦄, UsefulCompression U₁ V₁ → #U₁ < #U → IsCompressed U₁ V₁ 𝒜) :
#(∂ (𝓒 U V 𝒜)) ≤ #(∂ 𝒜) := by
obtain ⟨UVd, same_size, hU, hV, max_lt⟩ := h₁
refine card_shadow_compression_le _ _ fun x Hx ↦ ⟨min' V hV, min'_mem _ _, ?_⟩
obtain hU' | hU' := eq_or_lt_of_le (succ_le_iff.2 hU.card_pos)
· rw [← hU'] at same_size
have : erase U x = ∅ := by rw [← Finset.card_eq_zero, card_erase_of_mem Hx, ← hU']
have : erase V (min' V hV) = ∅ := by
rw [← Finset.card_eq_zero, card_erase_of_mem (min'_mem _ _), ← same_size]
rw [‹erase U x = ∅›, ‹erase V (min' V hV) = ∅›]
exact isCompressed_self _ _
refine h₂ ⟨UVd.mono (erase_subset ..) (erase_subset ..), ?_, ?_, ?_, ?_⟩ (card_erase_lt_of_mem Hx)
· rw [card_erase_of_mem (min'_mem _ _), card_erase_of_mem Hx, same_size]
· rwa [← card_pos, card_erase_of_mem Hx, tsub_pos_iff_lt]
· rwa [← Finset.card_pos, card_erase_of_mem (min'_mem _ _), ← same_size, tsub_pos_iff_lt]
· exact (Finset.max'_subset _ <| erase_subset _ _).trans_lt (max_lt.trans_le <| le_max' _ _ <|
mem_erase.2 ⟨(min'_lt_max'_of_card _ (by rwa [← same_size])).ne', max'_mem _ _⟩)
/-- If we're compressed by all useful compressions, then we're an initial segment. This is the other
key Kruskal-Katona part. -/
lemma isInitSeg_of_compressed {ℬ : Finset (Finset α)} {r : ℕ} (h₁ : (ℬ : Set (Finset α)).Sized r)
(h₂ : ∀ U V, UsefulCompression U V → IsCompressed U V ℬ) : IsInitSeg ℬ r := by
refine ⟨h₁, ?_⟩
rintro A B hA ⟨hBA, sizeA⟩
by_contra hB
have hAB : A ≠ B := ne_of_mem_of_not_mem hA hB
have hAB' : #A = #B := (h₁ hA).trans sizeA.symm
have hU : (A \ B).Nonempty := sdiff_nonempty.2 fun h ↦ hAB <| eq_of_subset_of_card_le h hAB'.ge
have hV : (B \ A).Nonempty :=
sdiff_nonempty.2 fun h ↦ hAB.symm <| eq_of_subset_of_card_le h hAB'.le
have disj : Disjoint (B \ A) (A \ B) := disjoint_sdiff.mono_left sdiff_subset
have smaller : max' _ hV < max' _ hU := by
obtain hlt | heq | hgt := lt_trichotomy (max' _ hU) (max' _ hV)
· rw [← compress_sdiff_sdiff A B] at hAB hBA
cases hBA.not_gt <| toColex_compress_lt_toColex hlt hAB
· exact (disjoint_right.1 disj (max'_mem _ hU) <| heq.symm ▸ max'_mem _ _).elim
· assumption
refine hB ?_
rw [← (h₂ _ _ ⟨disj, card_sdiff_comm hAB'.symm, hV, hU, smaller⟩).eq]
exact mem_compression.2 (Or.inr ⟨hB, A, hA, compress_sdiff_sdiff _ _⟩)
attribute [-instance] Fintype.decidableForallFintype
/-- This measures roughly how compressed the family is.
Note that this does depend on the order of the ground set, unlike the Kruskal-Katona theorem itself
(although `kruskal_katona` currently is stated in an order-dependent manner). -/
private def familyMeasure (𝒜 : Finset (Finset (Fin n))) : ℕ := ∑ A ∈ 𝒜, ∑ a ∈ A, 2 ^ (a : ℕ)
/-- Applying a compression strictly decreases the measure. This helps show that "compress until we
can't any more" is a terminating process. -/
private lemma familyMeasure_compression_lt_familyMeasure {U V : Finset (Fin n)} {hU : U.Nonempty}
{hV : V.Nonempty} (h : max' U hU < max' V hV) {𝒜 : Finset (Finset (Fin n))} (a : 𝓒 U V 𝒜 ≠ 𝒜) :
familyMeasure (𝓒 U V 𝒜) < familyMeasure 𝒜 := by
rw [compression] at a ⊢
have q : ∀ Q ∈ {A ∈ 𝒜 | compress U V A ∉ 𝒜}, compress U V Q ≠ Q := by grind
have uA : {A ∈ 𝒜 | compress U V A ∈ 𝒜} ∪ {A ∈ 𝒜 | compress U V A ∉ 𝒜} = 𝒜 :=
filter_union_filter_neg_eq _ _
have ne₂ : {A ∈ 𝒜 | compress U V A ∉ 𝒜}.Nonempty := by
refine nonempty_iff_ne_empty.2 fun z ↦ a ?_
rw [filter_image, z, image_empty, union_empty]
rwa [z, union_empty] at uA
rw [familyMeasure, familyMeasure, sum_union compress_disjoint]
conv_rhs => rw [← uA]
rw [sum_union (disjoint_filter_filter_neg _ _ _), add_lt_add_iff_left, filter_image,
sum_image compress_injOn]
refine sum_lt_sum_of_nonempty ne₂ fun A hA ↦ ?_
simp_rw [← sum_image Fin.val_injective.injOn]
rw [geomSum_lt_geomSum_iff_toColex_lt_toColex le_rfl,
toColex_image_lt_toColex_image Fin.val_strictMono]
exact toColex_compress_lt_toColex h <| q _ hA
/-- The main Kruskal-Katona helper: use induction with our measure to keep compressing until
we can't any more, which gives a set family which is fully compressed and has the nice properties we
want. -/
private lemma kruskal_katona_helper {r : ℕ} (𝒜 : Finset (Finset (Fin n)))
(h : (𝒜 : Set (Finset (Fin n))).Sized r) :
∃ ℬ : Finset (Finset (Fin n)), #(∂ ℬ) ≤ #(∂ 𝒜) ∧ #𝒜 = #ℬ ∧
(ℬ : Set (Finset (Fin n))).Sized r ∧ ∀ U V, UsefulCompression U V → IsCompressed U V ℬ := by
classical
-- Are there any compressions we can make now?
set usable : Finset (Finset (Fin n) × Finset (Fin n)) :=
{t | UsefulCompression t.1 t.2 ∧ ¬ IsCompressed t.1 t.2 𝒜}
obtain husable | husable := usable.eq_empty_or_nonempty
-- No. Then where we are is the required set family.
· refine ⟨𝒜, le_rfl, rfl, h, fun U V hUV ↦ ?_⟩
rw [eq_empty_iff_forall_notMem] at husable
by_contra h
exact husable ⟨U, V⟩ <| mem_filter.2 ⟨mem_univ _, hUV, h⟩
-- Yes. Then apply the smallest compression, then keep going
obtain ⟨⟨U, V⟩, hUV, t⟩ := exists_min_image usable (fun t ↦ #t.1) husable
rw [mem_filter] at hUV
have h₂ : ∀ U₁ V₁, UsefulCompression U₁ V₁ → #U₁ < #U → IsCompressed U₁ V₁ 𝒜 := by
rintro U₁ V₁ huseful hUcard
by_contra h
exact hUcard.not_ge <| t ⟨U₁, V₁⟩ <| mem_filter.2 ⟨mem_univ _, huseful, h⟩
have p1 : #(∂ (𝓒 U V 𝒜)) ≤ #(∂ 𝒜) := compression_improved _ hUV.2.1 h₂
obtain ⟨-, hUV', hu, hv, hmax⟩ := hUV.2.1
have := familyMeasure_compression_lt_familyMeasure hmax hUV.2.2
obtain ⟨t, q1, q2, q3, q4⟩ := UV.kruskal_katona_helper (𝓒 U V 𝒜) (h.uvCompression hUV')
exact ⟨t, q1.trans p1, (card_compression _ _ _).symm.trans q2, q3, q4⟩
termination_by familyMeasure 𝒜
end UV
-- Finally we can prove Kruskal-Katona.
section KK
variable {r k i : ℕ} {𝒜 𝒞 : Finset <| Finset <| Fin n}
/-- The **Kruskal-Katona theorem**.
Given a set family `𝒜` consisting of `r`-sets, and `𝒞` an initial segment of the colex order of the
same size, the shadow of `𝒞` is smaller than the shadow of `𝒜`. In particular, this gives that the
minimum shadow size is achieved by initial segments of colex. -/
theorem kruskal_katona (h𝒜r : (𝒜 : Set (Finset (Fin n))).Sized r) (h𝒞𝒜 : #𝒞 ≤ #𝒜)
(h𝒞 : IsInitSeg 𝒞 r) : #(∂ 𝒞) ≤ #(∂ 𝒜) := by
-- WLOG `|𝒜| = |𝒞|`
obtain ⟨𝒜', h𝒜, h𝒜𝒞⟩ := exists_subset_card_eq h𝒞𝒜
-- By `kruskal_katona_helper`, we find a fully compressed family `ℬ` of the same size as `𝒜`
-- whose shadow is no bigger.
obtain ⟨ℬ, hℬ𝒜, h𝒜ℬ, hℬr, hℬ⟩ := UV.kruskal_katona_helper 𝒜' (h𝒜r.mono (by gcongr))
-- This means that `ℬ` is an initial segment of the same size as `𝒞`. Hence they are equal and
-- we are done.
suffices ℬ = 𝒞 by subst 𝒞; exact hℬ𝒜.trans (by gcongr)
have hcard : #ℬ = #𝒞 := h𝒜ℬ.symm.trans h𝒜𝒞
obtain h𝒞ℬ | hℬ𝒞 := h𝒞.total (UV.isInitSeg_of_compressed hℬr hℬ)
· exact (eq_of_subset_of_card_le h𝒞ℬ hcard.le).symm
· exact eq_of_subset_of_card_le hℬ𝒞 hcard.ge
/-- An iterated form of the Kruskal-Katona theorem. In particular, the minimum possible iterated
shadow size is attained by initial segments. -/
theorem iterated_kk (h₁ : (𝒜 : Set (Finset (Fin n))).Sized r) (h₂ : #𝒞 ≤ #𝒜) (h₃ : IsInitSeg 𝒞 r) :
#(∂^[k] 𝒞) ≤ #(∂^[k] 𝒜) := by
induction k generalizing r 𝒜 𝒞 with
| zero => simpa
| succ _ ih =>
refine ih h₁.shadow (kruskal_katona h₁ h₂ h₃) ?_
convert h₃.shadow
/-- The **Lovasz formulation of the Kruskal-Katona theorem**.
If `|𝒜| ≥ k choose r`, (and everything in `𝒜` has size `r`) then the initial segment we compare to
is just all the subsets of `{0, ..., k - 1}` of size `r`. The `i`-th iterated shadow of this is all
the subsets of `{0, ..., k - 1}` of size `r - i`, so the `i`-th iterated shadow of `𝒜` has at least
`k.choose (r - i)` elements. -/
theorem kruskal_katona_lovasz_form (hir : i ≤ r) (hrk : r ≤ k) (hkn : k ≤ n)
(h₁ : (𝒜 : Set (Finset (Fin n))).Sized r) (h₂ : k.choose r ≤ #𝒜) :
k.choose (r - i) ≤ #(∂^[i] 𝒜) := by
set range'k : Finset (Fin n) :=
attachFin (range k) fun m ↦ by rw [mem_range]; apply forall_lt_iff_le.2 hkn
set 𝒞 : Finset (Finset (Fin n)) := powersetCard r range'k
have : (𝒞 : Set (Finset (Fin n))).Sized r := Set.sized_powersetCard _ _
calc
k.choose (r - i)
_ = #(powersetCard (r - i) range'k) := by rw [card_powersetCard, card_attachFin, card_range]
_ = #(∂^[i] 𝒞) := by
congr!
ext B
rw [mem_powersetCard, mem_shadow_iterate_iff_exists_sdiff]
constructor
· rintro ⟨hBk, hB⟩
have := exists_subsuperset_card_eq hBk (Nat.le_add_left _ i) <| by
rwa [hB, card_attachFin, card_range, ← Nat.add_sub_assoc hir, Nat.add_sub_cancel_left]
obtain ⟨C, BsubC, hCrange, hcard⟩ := this
rw [hB, ← Nat.add_sub_assoc hir, Nat.add_sub_cancel_left] at hcard
refine ⟨C, mem_powersetCard.2 ⟨hCrange, hcard⟩, BsubC, ?_⟩
rw [card_sdiff_of_subset BsubC, hcard, hB, Nat.sub_sub_self hir]
· rintro ⟨A, Ah, hBA, card_sdiff_i⟩
rw [mem_powersetCard] at Ah
refine ⟨hBA.trans Ah.1, eq_tsub_of_add_eq ?_⟩
rw [← Ah.2, ← card_sdiff_i, add_comm, card_sdiff_add_card_eq_card hBA]
_ ≤ #(∂ ^[i] 𝒜) := by
refine iterated_kk h₁ ?_ ⟨‹_›, ?_⟩
· rwa [card_powersetCard, card_attachFin, card_range]
simp_rw [𝒞, mem_powersetCard]
rintro A B hA ⟨HB₁, HB₂⟩
refine ⟨fun t ht ↦ ?_, ‹_›⟩
rw [mem_attachFin, mem_range]
have : toColex (image Fin.val B) < toColex (image Fin.val A) := by
rwa [toColex_image_lt_toColex_image Fin.val_strictMono]
apply Colex.forall_lt_mono this.le _ t (mem_image.2 ⟨t, ht, rfl⟩)
simp_rw [mem_image]
rintro _ ⟨a, ha, hab⟩
simpa [range'k, hab] using hA.1 ha
end KK
/-- The **Erdős–Ko–Rado theorem**.
The maximum size of an intersecting family in `α` where all sets have size `r` is bounded by
`(card α - 1).choose (r - 1)`. This bound is sharp. -/
theorem erdos_ko_rado {𝒜 : Finset (Finset (Fin n))} {r : ℕ}
(h𝒜 : (𝒜 : Set (Finset (Fin n))).Intersecting) (h₂ : (𝒜 : Set (Finset (Fin n))).Sized r)
(h₃ : r ≤ n / 2) :
#𝒜 ≤ (n - 1).choose (r - 1) := by
-- Take care of the r=0 case first: it's not very interesting.
rcases Nat.eq_zero_or_pos r with b | h1r
· convert Nat.zero_le _
rw [Finset.card_eq_zero, eq_empty_iff_forall_notMem]
refine fun A HA ↦ h𝒜 HA HA ?_
rw [disjoint_self_iff_empty, ← Finset.card_eq_zero, ← b]
exact h₂ HA
refine le_of_not_gt fun size ↦ ?_
-- Consider 𝒜ᶜˢ = {sᶜ | s ∈ 𝒜}
-- Its iterated shadow (∂^[n-2k] 𝒜ᶜˢ) is disjoint from 𝒜 by intersecting-ness
have : Disjoint 𝒜 (∂^[n - 2 * r] 𝒜ᶜˢ) := disjoint_right.2 fun A hAbar hA ↦ by
simp only [mem_shadow_iterate_iff_exists_sdiff, mem_compls] at hAbar
obtain ⟨C, hC, hAC, _⟩ := hAbar
exact h𝒜 hA hC (disjoint_of_subset_left hAC disjoint_compl_right)
have : r ≤ n := h₃.trans (Nat.div_le_self n 2)
have : 1 ≤ n := ‹1 ≤ r›.trans ‹r ≤ n›
-- We know the size of 𝒜ᶜˢ since it's the same size as 𝒜
have z : (n - 1).choose (n - r) < #𝒜ᶜˢ := by
rwa [card_compls, choose_symm_of_eq_add (tsub_add_tsub_cancel ‹r ≤ n› ‹1 ≤ r›).symm]
-- and everything in 𝒜ᶜˢ has size n-r.
have h𝒜bar : (𝒜ᶜˢ : Set (Finset (Fin n))).Sized (n - r) := by simpa using h₂.compls
-- We can use the Lovasz form of Kruskal-Katona to get |∂^[n-2k] 𝒜ᶜˢ| ≥ (n-1) choose r
have kk := kruskal_katona_lovasz_form (i := n - 2 * r) (by cutsat)
((tsub_le_tsub_iff_left ‹1 ≤ n›).2 h1r) tsub_le_self h𝒜bar z.le
have : n - r - (n - 2 * r) = r := by omega
rw [this] at kk
-- But this gives a contradiction: `n choose r < |𝒜| + |∂^[n-2k] 𝒜ᶜˢ|`
have := calc
n.choose r = (n - 1).choose (r - 1) + (n - 1).choose r := by
convert Nat.choose_succ_succ _ _ using 3 <;> rwa [Nat.sub_one, Nat.succ_pred_eq_of_pos]
_ < #𝒜 + #(∂^[n - 2 * r] 𝒜ᶜˢ) := add_lt_add_of_lt_of_le size kk
_ = #(𝒜 ∪ ∂^[n - 2 * r] 𝒜ᶜˢ) := by rw [card_union_of_disjoint ‹_›]
apply this.not_ge
convert Set.Sized.card_le _
· rw [Fintype.card_fin]
rw [coe_union, Set.sized_union]
refine ⟨‹_›, ?_⟩
convert h𝒜bar.shadow_iterate
cutsat
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/AhlswedeZhang.lean | import Mathlib.Algebra.BigOperators.Intervals
import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Algebra.Order.Field.Basic
import Mathlib.Data.Finset.Sups
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.Ring
import Mathlib.Algebra.BigOperators.Group.Finset.Powerset
/-!
# The Ahlswede-Zhang identity
This file proves the Ahlswede-Zhang identity, which is a nontrivial relation between the size of the
"truncated unions" of a set family. It sharpens the Lubell-Yamamoto-Meshalkin inequality
`Finset.lubell_yamamoto_meshalkin_inequality_sum_card_div_choose`, by making explicit the correction
term.
For a set family `𝒜` over a ground set of size `n`, the Ahlswede-Zhang identity states that the sum
of `|⋂ B ∈ 𝒜, B ⊆ A, B|/(|A| * n.choose |A|)` over all sets `A` is exactly `1`. This implies the LYM
inequality since for an antichain `𝒜` and every `A ∈ 𝒜` we have
`|⋂ B ∈ 𝒜, B ⊆ A, B|/(|A| * n.choose |A|) = 1 / n.choose |A|`.
## Main declarations
* `Finset.truncatedSup`: `s.truncatedSup a` is the supremum of all `b ≥ a` in `𝒜` if there are
some, or `⊤` if there are none.
* `Finset.truncatedInf`: `s.truncatedInf a` is the infimum of all `b ≤ a` in `𝒜` if there are
some, or `⊥` if there are none.
* `AhlswedeZhang.infSum`: LHS of the Ahlswede-Zhang identity.
* `AhlswedeZhang.le_infSum`: The sum of `1 / n.choose |A|` over an antichain is less than the RHS of
the Ahlswede-Zhang identity.
* `AhlswedeZhang.infSum_eq_one`: Ahlswede-Zhang identity.
## References
* [R. Ahlswede, Z. Zhang, *An identity in combinatorial extremal theory*](https://doi.org/10.1016/0001-8708(90)90023-G)
* [D. T. Tru, *An AZ-style identity and Bollobás deficiency*](https://doi.org/10.1016/j.jcta.2007.03.005)
-/
section
variable (α : Type*) [Fintype α] [Nonempty α] {m n : ℕ}
open Finset Fintype Nat
private lemma binomial_sum_eq (h : n < m) :
∑ i ∈ range (n + 1), (n.choose i * (m - n) / ((m - i) * m.choose i) : ℚ) = 1 := by
set f : ℕ → ℚ := fun i ↦ n.choose i * (m.choose i : ℚ)⁻¹ with hf
suffices ∀ i ∈ range (n + 1), f i - f (i + 1) = n.choose i * (m - n) / ((m - i) * m.choose i) by
rw [← sum_congr rfl this, sum_range_sub', hf]
simp [choose_zero_right]
intro i h₁
rw [mem_range] at h₁
have h₁ := le_of_lt_succ h₁
have h₂ := h₁.trans_lt h
have h₃ := h₂.le
have hi₄ : (i + 1 : ℚ) ≠ 0 := i.cast_add_one_ne_zero
have := congr_arg ((↑) : ℕ → ℚ) (choose_succ_right_eq m i)
push_cast at this
dsimp [f, hf]
rw [(eq_mul_inv_iff_mul_eq₀ hi₄).mpr this]
have := congr_arg ((↑) : ℕ → ℚ) (choose_succ_right_eq n i)
push_cast at this
rw [(eq_mul_inv_iff_mul_eq₀ hi₄).mpr this]
have : (m - i : ℚ) ≠ 0 := sub_ne_zero_of_ne (cast_lt.mpr h₂).ne'
have : (m.choose i : ℚ) ≠ 0 := cast_ne_zero.2 (choose_pos h₂.le).ne'
simp [field, *]
private lemma Fintype.sum_div_mul_card_choose_card :
∑ s : Finset α, (card α / ((card α - #s) * (card α).choose #s) : ℚ) =
card α * ∑ k ∈ range (card α), (↑k)⁻¹ + 1 := by
rw [← powerset_univ, powerset_card_disjiUnion, sum_disjiUnion]
have : ∀ {x : ℕ}, ∀ s ∈ powersetCard x (univ : Finset α),
(card α / ((card α - #s) * (card α).choose #s) : ℚ) =
card α / ((card α - x) * (card α).choose x) := by
intro n s hs
rw [mem_powersetCard_univ.1 hs]
simp_rw [sum_congr rfl this, sum_const, card_powersetCard, card_univ, nsmul_eq_mul, mul_div,
mul_comm, ← mul_div]
rw [← mul_sum, ← mul_inv_cancel₀ (cast_ne_zero.mpr card_ne_zero : (card α : ℚ) ≠ 0), ← mul_add,
add_comm _ ((card α)⁻¹ : ℚ), ← sum_insert (f := fun x : ℕ ↦ (x⁻¹ : ℚ)) notMem_range_self,
← range_add_one]
have (n) (hn : n ∈ range (card α + 1)) :
((card α).choose n / ((card α - n) * (card α).choose n) : ℚ) = (card α - n : ℚ)⁻¹ := by
rw [div_mul_cancel_right₀]
exact cast_ne_zero.2 (choose_pos <| mem_range_succ_iff.1 hn).ne'
simp only [sum_congr rfl this, mul_eq_mul_left_iff, cast_eq_zero]
convert Or.inl <| sum_range_reflect _ _ with a ha
rw [add_tsub_cancel_right, cast_sub (mem_range_succ_iff.mp ha)]
end
open scoped FinsetFamily
namespace Finset
variable {α β : Type*}
/-! ### Truncated supremum, truncated infimum -/
section SemilatticeSup
variable [SemilatticeSup α] [SemilatticeSup β] [BoundedOrder β] {s t : Finset α} {a : α}
private lemma sup_aux [DecidableLE α] : a ∈ lowerClosure s → {b ∈ s | a ≤ b}.Nonempty :=
fun ⟨b, hb, hab⟩ ↦ ⟨b, mem_filter.2 ⟨hb, hab⟩⟩
private lemma lower_aux [DecidableEq α] :
a ∈ lowerClosure ↑(s ∪ t) ↔ a ∈ lowerClosure s ∨ a ∈ lowerClosure t := by
rw [coe_union, lowerClosure_union, LowerSet.mem_sup_iff]
variable [DecidableLE α] [OrderTop α]
/-- The supremum of the elements of `s` less than `a` if there are some, otherwise `⊤`. -/
def truncatedSup (s : Finset α) (a : α) : α :=
if h : a ∈ lowerClosure s then {b ∈ s | a ≤ b}.sup' (sup_aux h) id else ⊤
lemma truncatedSup_of_mem (h : a ∈ lowerClosure s) :
truncatedSup s a = {b ∈ s | a ≤ b}.sup' (sup_aux h) id := dif_pos h
lemma truncatedSup_of_notMem (h : a ∉ lowerClosure s) : truncatedSup s a = ⊤ := dif_neg h
@[deprecated (since := "2025-05-23")] alias truncatedSup_of_not_mem := truncatedSup_of_notMem
@[simp] lemma truncatedSup_empty (a : α) : truncatedSup ∅ a = ⊤ := truncatedSup_of_notMem (by simp)
@[simp] lemma truncatedSup_singleton (b a : α) : truncatedSup {b} a = if a ≤ b then b else ⊤ := by
simp [truncatedSup]; split_ifs <;> simp [Finset.filter_true_of_mem, *]
lemma le_truncatedSup : a ≤ truncatedSup s a := by
rw [truncatedSup]
split_ifs with h
· obtain ⟨ℬ, hb, h⟩ := h
exact h.trans <| le_sup' id <| mem_filter.2 ⟨hb, h⟩
· exact le_top
lemma map_truncatedSup [DecidableLE β] (e : α ≃o β) (s : Finset α) (a : α) :
e (truncatedSup s a) = truncatedSup (s.map e.toEquiv.toEmbedding) (e a) := by
have : e a ∈ lowerClosure (s.map e.toEquiv.toEmbedding : Set β) ↔ a ∈ lowerClosure s := by simp
simp_rw [truncatedSup, apply_dite e, map_finset_sup', map_top, this]
congr with h
simp only [filter_map, Function.comp_def, Equiv.coe_toEmbedding, RelIso.coe_fn_toEquiv,
OrderIso.le_iff_le, id, sup'_map]
lemma truncatedSup_of_isAntichain (hs : IsAntichain (· ≤ ·) (s : Set α)) (ha : a ∈ s) :
truncatedSup s a = a := by
refine le_antisymm ?_ le_truncatedSup
simp_rw [truncatedSup_of_mem (subset_lowerClosure ha), sup'_le_iff, mem_filter]
rintro b ⟨hb, hab⟩
exact (hs.eq ha hb hab).ge
variable [DecidableEq α]
lemma truncatedSup_union (hs : a ∈ lowerClosure s) (ht : a ∈ lowerClosure t) :
truncatedSup (s ∪ t) a = truncatedSup s a ⊔ truncatedSup t a := by
simpa only [truncatedSup_of_mem, hs, ht, lower_aux.2 (Or.inl hs), filter_union] using
sup'_union _ _ _
lemma truncatedSup_union_left (hs : a ∈ lowerClosure s) (ht : a ∉ lowerClosure t) :
truncatedSup (s ∪ t) a = truncatedSup s a := by
simp only [mem_lowerClosure, mem_coe, not_exists, not_and] at ht
simp only [truncatedSup_of_mem, hs, filter_union, filter_false_of_mem ht, union_empty,
lower_aux.2 (Or.inl hs)]
lemma truncatedSup_union_right (hs : a ∉ lowerClosure s) (ht : a ∈ lowerClosure t) :
truncatedSup (s ∪ t) a = truncatedSup t a := by rw [union_comm, truncatedSup_union_left ht hs]
lemma truncatedSup_union_of_notMem (hs : a ∉ lowerClosure s) (ht : a ∉ lowerClosure t) :
truncatedSup (s ∪ t) a = ⊤ := truncatedSup_of_notMem fun h ↦ (lower_aux.1 h).elim hs ht
@[deprecated (since := "2025-05-23")]
alias truncatedSup_union_of_not_mem := truncatedSup_union_of_notMem
end SemilatticeSup
section SemilatticeInf
variable [SemilatticeInf α] [SemilatticeInf β]
[BoundedOrder β] [DecidableLE β] {s t : Finset α} {a : α}
private lemma inf_aux [DecidableLE α] : a ∈ upperClosure s → {b ∈ s | b ≤ a}.Nonempty :=
fun ⟨b, hb, hab⟩ ↦ ⟨b, mem_filter.2 ⟨hb, hab⟩⟩
private lemma upper_aux [DecidableEq α] :
a ∈ upperClosure ↑(s ∪ t) ↔ a ∈ upperClosure s ∨ a ∈ upperClosure t := by
rw [coe_union, upperClosure_union, UpperSet.mem_inf_iff]
variable [DecidableLE α] [BoundedOrder α]
/-- The infimum of the elements of `s` less than `a` if there are some, otherwise `⊥`. -/
def truncatedInf (s : Finset α) (a : α) : α :=
if h : a ∈ upperClosure s then {b ∈ s | b ≤ a}.inf' (inf_aux h) id else ⊥
lemma truncatedInf_of_mem (h : a ∈ upperClosure s) :
truncatedInf s a = {b ∈ s | b ≤ a}.inf' (inf_aux h) id := dif_pos h
lemma truncatedInf_of_notMem (h : a ∉ upperClosure s) : truncatedInf s a = ⊥ := dif_neg h
@[deprecated (since := "2025-05-23")] alias truncatedInf_of_not_mem := truncatedInf_of_notMem
lemma truncatedInf_le : truncatedInf s a ≤ a := by
unfold truncatedInf
split_ifs with h
· obtain ⟨b, hb, hba⟩ := h
exact hba.trans' <| inf'_le id <| mem_filter.2 ⟨hb, ‹_›⟩
· exact bot_le
@[simp] lemma truncatedInf_empty (a : α) : truncatedInf ∅ a = ⊥ := truncatedInf_of_notMem (by simp)
@[simp] lemma truncatedInf_singleton (b a : α) : truncatedInf {b} a = if b ≤ a then b else ⊥ := by
simp only [truncatedInf, coe_singleton, upperClosure_singleton, UpperSet.mem_Ici_iff,
id_eq]
split_ifs <;> simp [Finset.filter_true_of_mem, *]
lemma map_truncatedInf (e : α ≃o β) (s : Finset α) (a : α) :
e (truncatedInf s a) = truncatedInf (s.map e.toEquiv.toEmbedding) (e a) := by
have : e a ∈ upperClosure (s.map e.toEquiv.toEmbedding) ↔ a ∈ upperClosure s := by simp
simp_rw [truncatedInf, apply_dite e, map_finset_inf', map_bot, this]
congr with h
simp only [filter_map, Function.comp_def, Equiv.coe_toEmbedding, RelIso.coe_fn_toEquiv,
OrderIso.le_iff_le, id, inf'_map]
lemma truncatedInf_of_isAntichain (hs : IsAntichain (· ≤ ·) (s : Set α)) (ha : a ∈ s) :
truncatedInf s a = a := by
refine le_antisymm truncatedInf_le ?_
simp_rw [truncatedInf_of_mem (subset_upperClosure ha), le_inf'_iff, mem_filter]
rintro b ⟨hb, hba⟩
exact (hs.eq hb ha hba).ge
variable [DecidableEq α]
lemma truncatedInf_union (hs : a ∈ upperClosure s) (ht : a ∈ upperClosure t) :
truncatedInf (s ∪ t) a = truncatedInf s a ⊓ truncatedInf t a := by
simpa only [truncatedInf_of_mem, hs, ht, upper_aux.2 (Or.inl hs), filter_union] using
inf'_union _ _ _
lemma truncatedInf_union_left (hs : a ∈ upperClosure s) (ht : a ∉ upperClosure t) :
truncatedInf (s ∪ t) a = truncatedInf s a := by
simp only [mem_upperClosure, mem_coe, not_exists, not_and] at ht
simp only [truncatedInf_of_mem, hs, filter_union, filter_false_of_mem ht, union_empty,
upper_aux.2 (Or.inl hs)]
lemma truncatedInf_union_right (hs : a ∉ upperClosure s) (ht : a ∈ upperClosure t) :
truncatedInf (s ∪ t) a = truncatedInf t a := by
rw [union_comm, truncatedInf_union_left ht hs]
lemma truncatedInf_union_of_notMem (hs : a ∉ upperClosure s) (ht : a ∉ upperClosure t) :
truncatedInf (s ∪ t) a = ⊥ :=
truncatedInf_of_notMem <| by rw [coe_union, upperClosure_union]; exact fun h ↦ h.elim hs ht
@[deprecated (since := "2025-05-23")]
alias truncatedInf_union_of_not_mem := truncatedInf_union_of_notMem
end SemilatticeInf
section DistribLattice
variable [DistribLattice α] [DecidableEq α] {s t : Finset α} {a : α}
private lemma infs_aux : a ∈ lowerClosure ↑(s ⊼ t) ↔ a ∈ lowerClosure s ∧ a ∈ lowerClosure t := by
rw [coe_infs, lowerClosure_infs, LowerSet.mem_inf_iff]
private lemma sups_aux : a ∈ upperClosure ↑(s ⊻ t) ↔ a ∈ upperClosure s ∧ a ∈ upperClosure t := by
rw [coe_sups, upperClosure_sups, UpperSet.mem_sup_iff]
variable [DecidableLE α] [BoundedOrder α]
lemma truncatedSup_infs (hs : a ∈ lowerClosure s) (ht : a ∈ lowerClosure t) :
truncatedSup (s ⊼ t) a = truncatedSup s a ⊓ truncatedSup t a := by
simp only [truncatedSup_of_mem, hs, ht, infs_aux.2 ⟨hs, ht⟩, sup'_inf_sup', filter_infs_le]
simp_rw [← image_inf_product]
rw [sup'_image]
simp [Function.uncurry_def]
lemma truncatedInf_sups (hs : a ∈ upperClosure s) (ht : a ∈ upperClosure t) :
truncatedInf (s ⊻ t) a = truncatedInf s a ⊔ truncatedInf t a := by
simp only [truncatedInf_of_mem, hs, ht, sups_aux.2 ⟨hs, ht⟩, inf'_sup_inf', filter_sups_le]
simp_rw [← image_sup_product]
rw [inf'_image]
simp [Function.uncurry_def]
lemma truncatedSup_infs_of_notMem (ha : a ∉ lowerClosure s ⊓ lowerClosure t) :
truncatedSup (s ⊼ t) a = ⊤ :=
truncatedSup_of_notMem <| by rwa [coe_infs, lowerClosure_infs]
@[deprecated (since := "2025-05-23")]
alias truncatedSup_infs_of_not_mem := truncatedSup_infs_of_notMem
lemma truncatedInf_sups_of_notMem (ha : a ∉ upperClosure s ⊔ upperClosure t) :
truncatedInf (s ⊻ t) a = ⊥ :=
truncatedInf_of_notMem <| by rwa [coe_sups, upperClosure_sups]
@[deprecated (since := "2025-05-23")]
alias truncatedInf_sups_of_not_mem := truncatedInf_sups_of_notMem
end DistribLattice
section BooleanAlgebra
variable [BooleanAlgebra α] [DecidableLE α]
@[simp] lemma compl_truncatedSup (s : Finset α) (a : α) :
(truncatedSup s a)ᶜ = truncatedInf sᶜˢ aᶜ := map_truncatedSup (OrderIso.compl α) _ _
@[simp] lemma compl_truncatedInf (s : Finset α) (a : α) :
(truncatedInf s a)ᶜ = truncatedSup sᶜˢ aᶜ := map_truncatedInf (OrderIso.compl α) _ _
end BooleanAlgebra
variable [DecidableEq α] [Fintype α]
lemma card_truncatedSup_union_add_card_truncatedSup_infs (𝒜 ℬ : Finset (Finset α)) (s : Finset α) :
#(truncatedSup (𝒜 ∪ ℬ) s) + #(truncatedSup (𝒜 ⊼ ℬ) s) =
#(truncatedSup 𝒜 s) + #(truncatedSup ℬ s) := by
by_cases h𝒜 : s ∈ lowerClosure (𝒜 : Set <| Finset α) <;>
by_cases hℬ : s ∈ lowerClosure (ℬ : Set <| Finset α)
· rw [truncatedSup_union h𝒜 hℬ, truncatedSup_infs h𝒜 hℬ]
exact card_union_add_card_inter _ _
· rw [truncatedSup_union_left h𝒜 hℬ, truncatedSup_of_notMem hℬ,
truncatedSup_infs_of_notMem fun h ↦ hℬ h.2]
· rw [truncatedSup_union_right h𝒜 hℬ, truncatedSup_of_notMem h𝒜,
truncatedSup_infs_of_notMem fun h ↦ h𝒜 h.1, add_comm]
· rw [truncatedSup_of_notMem h𝒜, truncatedSup_of_notMem hℬ,
truncatedSup_union_of_notMem h𝒜 hℬ, truncatedSup_infs_of_notMem fun h ↦ h𝒜 h.1]
lemma card_truncatedInf_union_add_card_truncatedInf_sups (𝒜 ℬ : Finset (Finset α)) (s : Finset α) :
#(truncatedInf (𝒜 ∪ ℬ) s) + #(truncatedInf (𝒜 ⊻ ℬ) s) =
#(truncatedInf 𝒜 s) + #(truncatedInf ℬ s) := by
by_cases h𝒜 : s ∈ upperClosure (𝒜 : Set <| Finset α) <;>
by_cases hℬ : s ∈ upperClosure (ℬ : Set <| Finset α)
· rw [truncatedInf_union h𝒜 hℬ, truncatedInf_sups h𝒜 hℬ]
exact card_inter_add_card_union _ _
· rw [truncatedInf_union_left h𝒜 hℬ, truncatedInf_of_notMem hℬ,
truncatedInf_sups_of_notMem fun h ↦ hℬ h.2]
· rw [truncatedInf_union_right h𝒜 hℬ, truncatedInf_of_notMem h𝒜,
truncatedInf_sups_of_notMem fun h ↦ h𝒜 h.1, add_comm]
· rw [truncatedInf_of_notMem h𝒜, truncatedInf_of_notMem hℬ,
truncatedInf_union_of_notMem h𝒜 hℬ, truncatedInf_sups_of_notMem fun h ↦ h𝒜 h.1]
end Finset
open Finset hiding card
open Fintype Nat
namespace AhlswedeZhang
variable {α : Type*} [Fintype α] [DecidableEq α] {𝒜 : Finset (Finset α)} {s : Finset α}
/-- Weighted sum of the size of the truncated infima of a set family. Relevant to the
Ahlswede-Zhang identity. -/
def infSum (𝒜 : Finset (Finset α)) : ℚ :=
∑ s, #(truncatedInf 𝒜 s) / (#s * (card α).choose #s)
/-- Weighted sum of the size of the truncated suprema of a set family. Relevant to the
Ahlswede-Zhang identity. -/
def supSum (𝒜 : Finset (Finset α)) : ℚ :=
∑ s, #(truncatedSup 𝒜 s) / ((card α - #s) * (card α).choose #s)
lemma supSum_union_add_supSum_infs (𝒜 ℬ : Finset (Finset α)) :
supSum (𝒜 ∪ ℬ) + supSum (𝒜 ⊼ ℬ) = supSum 𝒜 + supSum ℬ := by
unfold supSum
rw [← sum_add_distrib, ← sum_add_distrib, sum_congr rfl fun s _ ↦ _]
simp_rw [← add_div, ← Nat.cast_add, card_truncatedSup_union_add_card_truncatedSup_infs]
simp
lemma infSum_union_add_infSum_sups (𝒜 ℬ : Finset (Finset α)) :
infSum (𝒜 ∪ ℬ) + infSum (𝒜 ⊻ ℬ) = infSum 𝒜 + infSum ℬ := by
unfold infSum
rw [← sum_add_distrib, ← sum_add_distrib, sum_congr rfl fun s _ ↦ _]
simp_rw [← add_div, ← Nat.cast_add, card_truncatedInf_union_add_card_truncatedInf_sups]
simp
lemma IsAntichain.le_infSum (h𝒜 : IsAntichain (· ⊆ ·) (𝒜 : Set (Finset α))) (h𝒜₀ : ∅ ∉ 𝒜) :
∑ s ∈ 𝒜, ((card α).choose #s : ℚ)⁻¹ ≤ infSum 𝒜 := by
calc
_ = ∑ s ∈ 𝒜, #(truncatedInf 𝒜 s) / (#s * (card α).choose #s : ℚ) := ?_
_ ≤ _ := sum_le_univ_sum_of_nonneg fun s ↦ by positivity
refine sum_congr rfl fun s hs ↦ ?_
rw [truncatedInf_of_isAntichain h𝒜 hs, div_mul_cancel_left₀]
have := (nonempty_iff_ne_empty.2 <| ne_of_mem_of_not_mem hs h𝒜₀).card_pos
positivity
variable [Nonempty α]
@[simp] lemma supSum_singleton (hs : s ≠ univ) :
supSum ({s} : Finset (Finset α)) = card α * ∑ k ∈ range (card α), (k : ℚ)⁻¹ := by
have : ∀ t : Finset α,
(card α - #(truncatedSup {s} t) : ℚ) / ((card α - #t) * (card α).choose #t) =
if t ⊆ s then (card α - #s : ℚ) / ((card α - #t) * (card α).choose #t) else 0 := by
rintro t
simp_rw [truncatedSup_singleton, le_iff_subset]
split_ifs <;> simp
simp_rw [← sub_eq_of_eq_add (Fintype.sum_div_mul_card_choose_card α), eq_sub_iff_add_eq,
← eq_sub_iff_add_eq', supSum, ← sum_sub_distrib, ← sub_div]
rw [sum_congr rfl fun t _ ↦ this t, sum_ite, sum_const_zero, add_zero, filter_subset_univ,
sum_powerset, ← binomial_sum_eq ((card_lt_iff_ne_univ _).2 hs), eq_comm]
refine sum_congr rfl fun n _ ↦ ?_
rw [mul_div_assoc, ← nsmul_eq_mul]
exact sum_powersetCard n s fun m ↦ (card α - #s : ℚ) / ((card α - m) * (card α).choose m)
/-- The **Ahlswede-Zhang Identity**. -/
lemma infSum_compls_add_supSum (𝒜 : Finset (Finset α)) :
infSum 𝒜ᶜˢ + supSum 𝒜 = card α * ∑ k ∈ range (card α), (k : ℚ)⁻¹ + 1 := by
unfold infSum supSum
rw [← @map_univ_of_surjective (Finset α) _ _ _ ⟨compl, compl_injective⟩ compl_surjective, sum_map]
simp only [Function.Embedding.coeFn_mk, univ_map_embedding, ← compl_truncatedSup,
← sum_add_distrib, card_compl, cast_sub (card_le_univ _), choose_symm (card_le_univ _),
← add_div, sub_add_cancel, Fintype.sum_div_mul_card_choose_card]
lemma supSum_of_univ_notMem (h𝒜₁ : 𝒜.Nonempty) (h𝒜₂ : univ ∉ 𝒜) :
supSum 𝒜 = card α * ∑ k ∈ range (card α), (k : ℚ)⁻¹ := by
set m := 𝒜.card with hm
clear_value m
induction m using Nat.strongRecOn generalizing 𝒜 with | ind m ih => _
replace ih := fun 𝒜 h𝒜 h𝒜₁ h𝒜₂ ↦ @ih _ h𝒜 𝒜 h𝒜₁ h𝒜₂ rfl
obtain ⟨a, rfl⟩ | h𝒜₃ := h𝒜₁.exists_eq_singleton_or_nontrivial
· refine supSum_singleton ?_
simpa [eq_comm] using h𝒜₂
cases m
· cases h𝒜₁.card_pos.ne hm
obtain ⟨s, 𝒜, hs, rfl, rfl⟩ := card_eq_succ.1 hm.symm
have h𝒜 : 𝒜.Nonempty := nonempty_iff_ne_empty.2 (by rintro rfl; simp at h𝒜₃)
rw [insert_eq, eq_sub_of_add_eq (supSum_union_add_supSum_infs _ _), singleton_infs,
supSum_singleton (ne_of_mem_of_not_mem (mem_insert_self _ _) h𝒜₂), ih, ih, add_sub_cancel_right]
· exact card_image_le.trans_lt (lt_add_one _)
· exact h𝒜.image _
· simpa using fun _ ↦ ne_of_mem_of_not_mem (mem_insert_self _ _) h𝒜₂
· exact lt_add_one _
· exact h𝒜
· exact fun h ↦ h𝒜₂ (mem_insert_of_mem h)
@[deprecated (since := "2025-05-23")]
alias supSum_of_not_univ_mem := supSum_of_univ_notMem
/-- The **Ahlswede-Zhang Identity**. -/
lemma infSum_eq_one (h𝒜₁ : 𝒜.Nonempty) (h𝒜₀ : ∅ ∉ 𝒜) : infSum 𝒜 = 1 := by
rw [← compls_compls 𝒜, eq_sub_of_add_eq (infSum_compls_add_supSum _),
supSum_of_univ_notMem h𝒜₁.compls, add_sub_cancel_left]
simpa
end AhlswedeZhang |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/Kleitman.lean | import Mathlib.Combinatorics.SetFamily.HarrisKleitman
import Mathlib.Combinatorics.SetFamily.Intersecting
/-!
# Kleitman's bound on the size of intersecting families
An intersecting family on `n` elements has size at most `2ⁿ⁻¹`, so we could naïvely think that two
intersecting families could cover all `2ⁿ` sets. But actually that's not case because for example
none of them can contain the empty set. Intersecting families are in some sense correlated.
Kleitman's bound stipulates that `k` intersecting families cover at most `2ⁿ - 2ⁿ⁻ᵏ` sets.
## Main declarations
* `Finset.card_biUnion_le_of_intersecting`: Kleitman's theorem.
## References
* [D. J. Kleitman, *Families of non-disjoint subsets*][kleitman1966]
-/
open Finset
open Fintype (card)
variable {ι α : Type*} [Fintype α] [DecidableEq α] [Nonempty α]
/-- **Kleitman's theorem**. An intersecting family on `n` elements contains at most `2ⁿ⁻¹` sets, and
each further intersecting family takes at most half of the sets that are in no previous family. -/
theorem Finset.card_biUnion_le_of_intersecting (s : Finset ι) (f : ι → Finset (Finset α))
(hf : ∀ i ∈ s, (f i : Set (Finset α)).Intersecting) :
#(s.biUnion f) ≤ 2 ^ Fintype.card α - 2 ^ (Fintype.card α - #s) := by
have : DecidableEq ι := by
classical
infer_instance
obtain hs | hs := le_total (Fintype.card α) #s
· rw [tsub_eq_zero_of_le hs, pow_zero]
refine (card_le_card <| biUnion_subset.2 fun i hi a ha ↦
mem_compl.2 <| notMem_singleton.2 <| (hf _ hi).ne_bot ha).trans_eq ?_
rw [card_compl, Fintype.card_finset, card_singleton]
induction s using Finset.cons_induction generalizing f with
| empty => simp
| cons i s hi ih =>
set f' : ι → Finset (Finset α) :=
fun j ↦ if hj : j ∈ cons i s hi then (hf j hj).exists_card_eq.choose else ∅
have hf₁ : ∀ j, j ∈ cons i s hi → f j ⊆ f' j ∧ 2 * #(f' j) =
2 ^ Fintype.card α ∧ (f' j : Set (Finset α)).Intersecting := by
rintro j hj
simp_rw [f', dif_pos hj, ← Fintype.card_finset]
exact Classical.choose_spec (hf j hj).exists_card_eq
have hf₂ : ∀ j, j ∈ cons i s hi → IsUpperSet (f' j : Set (Finset α)) := by
refine fun j hj ↦ (hf₁ _ hj).2.2.isUpperSet' ((hf₁ _ hj).2.2.is_max_iff_card_eq.2 ?_)
rw [Fintype.card_finset]
exact (hf₁ _ hj).2.1
refine (card_le_card <| biUnion_mono fun j hj ↦ (hf₁ _ hj).1).trans ?_
nth_rw 1 [cons_eq_insert i]
rw [biUnion_insert]
refine (card_mono <| @le_sup_sdiff _ _ _ <| f' i).trans ((card_union_le _ _).trans ?_)
rw [union_sdiff_left, sdiff_eq_inter_compl]
refine le_of_mul_le_mul_left ?_ (pow_pos (zero_lt_two' ℕ) <| Fintype.card α + 1)
rw [pow_succ, mul_add, mul_assoc, mul_comm _ 2, mul_assoc]
refine (add_le_add
((mul_le_mul_iff_right₀ <| pow_pos (zero_lt_two' ℕ) _).2
(hf₁ _ <| mem_cons_self _ _).2.2.card_le) <|
(mul_le_mul_iff_right₀ <| zero_lt_two' ℕ).2 <| IsUpperSet.card_inter_le_finset ?_ ?_).trans ?_
· rw [coe_biUnion]
exact isUpperSet_iUnion₂ fun i hi ↦ hf₂ _ <| subset_cons _ hi
· rw [coe_compl]
exact (hf₂ _ <| mem_cons_self _ _).compl
rw [mul_tsub, card_compl, Fintype.card_finset, mul_left_comm, mul_tsub,
(hf₁ _ <| mem_cons_self _ _).2.1, two_mul, add_tsub_cancel_left, ← mul_tsub, ← mul_two,
mul_assoc, ← add_mul, mul_comm]
gcongr
refine (add_le_add_left
(ih _ (fun i hi ↦ (hf₁ _ <| subset_cons _ hi).2.2)
((card_le_card <| subset_cons _).trans hs)) _).trans ?_
rw [mul_tsub, two_mul, ← pow_succ',
← add_tsub_assoc_of_le (pow_right_mono₀ (one_le_two : (1 : ℕ) ≤ 2) tsub_le_self),
tsub_add_eq_add_tsub hs, card_cons, add_tsub_add_eq_tsub_right] |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/HarrisKleitman.lean | import Mathlib.Algebra.Order.Ring.Canonical
import Mathlib.Algebra.Order.Ring.Nat
import Mathlib.Combinatorics.SetFamily.Compression.Down
import Mathlib.Data.Fintype.Powerset
import Mathlib.Order.UpperLower.Basic
/-!
# Harris-Kleitman inequality
This file proves the Harris-Kleitman inequality. This relates `#𝒜 * #ℬ` and
`2 ^ card α * #(𝒜 ∩ ℬ)` where `𝒜` and `ℬ` are upward- or downcard-closed finite families of
finsets. This can be interpreted as saying that any two lower sets (resp. any two upper sets)
correlate in the uniform measure.
## Main declarations
* `IsLowerSet.le_card_inter_finset`: One form of the Harris-Kleitman inequality.
## References
* [D. J. Kleitman, *Families of non-disjoint subsets*][kleitman1966]
-/
open Finset
variable {α : Type*} [DecidableEq α] {𝒜 ℬ : Finset (Finset α)} {s : Finset α} {a : α}
theorem IsLowerSet.nonMemberSubfamily (h : IsLowerSet (𝒜 : Set (Finset α))) :
IsLowerSet (𝒜.nonMemberSubfamily a : Set (Finset α)) := fun s t hts => by
simp_rw [mem_coe, mem_nonMemberSubfamily]
exact And.imp (h hts) (mt <| @hts _)
theorem IsLowerSet.memberSubfamily (h : IsLowerSet (𝒜 : Set (Finset α))) :
IsLowerSet (𝒜.memberSubfamily a : Set (Finset α)) := by
rintro s t hts
simp_rw [mem_coe, mem_memberSubfamily]
exact And.imp (h <| insert_subset_insert _ hts) (mt <| @hts _)
theorem IsLowerSet.memberSubfamily_subset_nonMemberSubfamily (h : IsLowerSet (𝒜 : Set (Finset α))) :
𝒜.memberSubfamily a ⊆ 𝒜.nonMemberSubfamily a := fun s => by
rw [mem_memberSubfamily, mem_nonMemberSubfamily]
exact And.imp_left (h <| subset_insert _ _)
/-- **Harris-Kleitman inequality**: Any two lower sets of finsets correlate. -/
theorem IsLowerSet.le_card_inter_finset' (h𝒜 : IsLowerSet (𝒜 : Set (Finset α)))
(hℬ : IsLowerSet (ℬ : Set (Finset α))) (h𝒜s : ∀ t ∈ 𝒜, t ⊆ s) (hℬs : ∀ t ∈ ℬ, t ⊆ s) :
#𝒜 * #ℬ ≤ 2 ^ #s * #(𝒜 ∩ ℬ) := by
induction s using Finset.induction generalizing 𝒜 ℬ with
| empty =>
simp_rw [subset_empty, ← subset_singleton_iff', subset_singleton_iff] at h𝒜s hℬs
obtain rfl | rfl := h𝒜s
· simp only [card_empty, zero_mul, empty_inter, mul_zero, le_refl]
obtain rfl | rfl := hℬs
· simp only [card_empty, inter_empty, mul_zero, le_refl]
· simp only [card_empty, pow_zero, inter_singleton_of_mem, mem_singleton, card_singleton,
le_refl]
| insert a s hs ih =>
rw [card_insert_of_notMem hs, ← card_memberSubfamily_add_card_nonMemberSubfamily a 𝒜, ←
card_memberSubfamily_add_card_nonMemberSubfamily a ℬ, add_mul, mul_add, mul_add,
add_comm (_ * _), add_add_add_comm]
grw [mul_add_mul_le_mul_add_mul
(card_le_card h𝒜.memberSubfamily_subset_nonMemberSubfamily) <|
card_le_card hℬ.memberSubfamily_subset_nonMemberSubfamily, ← two_mul, pow_succ', mul_assoc]
have h₀ : ∀ 𝒞 : Finset (Finset α), (∀ t ∈ 𝒞, t ⊆ insert a s) →
∀ t ∈ 𝒞.nonMemberSubfamily a, t ⊆ s := by
rintro 𝒞 h𝒞 t ht
rw [mem_nonMemberSubfamily] at ht
exact (subset_insert_iff_of_notMem ht.2).1 (h𝒞 _ ht.1)
have h₁ : ∀ 𝒞 : Finset (Finset α), (∀ t ∈ 𝒞, t ⊆ insert a s) →
∀ t ∈ 𝒞.memberSubfamily a, t ⊆ s := by
rintro 𝒞 h𝒞 t ht
rw [mem_memberSubfamily] at ht
exact (subset_insert_iff_of_notMem ht.2).1 ((subset_insert _ _).trans <| h𝒞 _ ht.1)
gcongr
refine (add_le_add (ih h𝒜.memberSubfamily hℬ.memberSubfamily (h₁ _ h𝒜s) <| h₁ _ hℬs) <|
ih h𝒜.nonMemberSubfamily hℬ.nonMemberSubfamily (h₀ _ h𝒜s) <| h₀ _ hℬs).trans_eq ?_
rw [← mul_add, ← memberSubfamily_inter, ← nonMemberSubfamily_inter,
card_memberSubfamily_add_card_nonMemberSubfamily]
variable [Fintype α]
/-- **Harris-Kleitman inequality**: Any two lower sets of finsets correlate. -/
theorem IsLowerSet.le_card_inter_finset (h𝒜 : IsLowerSet (𝒜 : Set (Finset α)))
(hℬ : IsLowerSet (ℬ : Set (Finset α))) : #𝒜 * #ℬ ≤ 2 ^ Fintype.card α * #(𝒜 ∩ ℬ) :=
h𝒜.le_card_inter_finset' hℬ (fun _ _ => subset_univ _) fun _ _ => subset_univ _
/-- **Harris-Kleitman inequality**: Upper sets and lower sets of finsets anticorrelate. -/
theorem IsUpperSet.card_inter_le_finset (h𝒜 : IsUpperSet (𝒜 : Set (Finset α)))
(hℬ : IsLowerSet (ℬ : Set (Finset α))) :
2 ^ Fintype.card α * #(𝒜 ∩ ℬ) ≤ #𝒜 * #ℬ := by
rw [← isLowerSet_compl, ← coe_compl] at h𝒜
have := h𝒜.le_card_inter_finset hℬ
rwa [card_compl, Fintype.card_finset, tsub_mul, tsub_le_iff_tsub_le, ← mul_tsub, ←
card_sdiff_of_subset inter_subset_right, sdiff_inter_self_right, sdiff_compl,
_root_.inf_comm] at this
/-- **Harris-Kleitman inequality**: Lower sets and upper sets of finsets anticorrelate. -/
theorem IsLowerSet.card_inter_le_finset (h𝒜 : IsLowerSet (𝒜 : Set (Finset α)))
(hℬ : IsUpperSet (ℬ : Set (Finset α))) :
2 ^ Fintype.card α * #(𝒜 ∩ ℬ) ≤ #𝒜 * #ℬ := by
rw [inter_comm, mul_comm #𝒜]
exact hℬ.card_inter_le_finset h𝒜
/-- **Harris-Kleitman inequality**: Any two upper sets of finsets correlate. -/
theorem IsUpperSet.le_card_inter_finset (h𝒜 : IsUpperSet (𝒜 : Set (Finset α)))
(hℬ : IsUpperSet (ℬ : Set (Finset α))) :
#𝒜 * #ℬ ≤ 2 ^ Fintype.card α * #(𝒜 ∩ ℬ) := by
rw [← isLowerSet_compl, ← coe_compl] at h𝒜
have := h𝒜.card_inter_le_finset hℬ
rwa [card_compl, Fintype.card_finset, tsub_mul, le_tsub_iff_le_tsub, ← mul_tsub, ←
card_sdiff_of_subset inter_subset_right, sdiff_inter_self_right, sdiff_compl,
_root_.inf_comm] at this
· grw [inter_subset_right]
· grw [← Fintype.card_finset, card_le_univ] |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/Shatter.lean | import Mathlib.Combinatorics.SetFamily.Compression.Down
import Mathlib.Data.Fintype.Powerset
import Mathlib.Order.Interval.Finset.Nat
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
/-!
# Shattering families
This file defines the shattering property and VC-dimension of set families.
## Main declarations
* `Finset.Shatters`: The shattering property.
* `Finset.shatterer`: The set family of sets shattered by a set family.
* `Finset.vcDim`: The Vapnik-Chervonenkis dimension.
## TODO
* Order-shattering
* Strong shattering
-/
open scoped FinsetFamily
namespace Finset
variable {α : Type*} [DecidableEq α] {𝒜 ℬ : Finset (Finset α)} {s t : Finset α} {a : α}
/-- A set family `𝒜` shatters a set `s` if all subsets of `s` can be obtained as the intersection
of `s` and some element of the set family, and we denote this `𝒜.Shatters s`. We also say that `s`
is *traced* by `𝒜`. -/
def Shatters (𝒜 : Finset (Finset α)) (s : Finset α) : Prop := ∀ ⦃t⦄, t ⊆ s → ∃ u ∈ 𝒜, s ∩ u = t
instance : DecidablePred 𝒜.Shatters := fun _s ↦ decidableForallOfDecidableSubsets
lemma Shatters.exists_inter_eq_singleton (hs : Shatters 𝒜 s) (ha : a ∈ s) : ∃ t ∈ 𝒜, s ∩ t = {a} :=
hs <| singleton_subset_iff.2 ha
lemma Shatters.mono_left (h : 𝒜 ⊆ ℬ) (h𝒜 : 𝒜.Shatters s) : ℬ.Shatters s :=
fun _t ht ↦ let ⟨u, hu, hut⟩ := h𝒜 ht; ⟨u, h hu, hut⟩
lemma Shatters.mono_right (h : t ⊆ s) (hs : 𝒜.Shatters s) : 𝒜.Shatters t := fun u hu ↦ by
obtain ⟨v, hv, rfl⟩ := hs (hu.trans h); exact ⟨v, hv, inf_congr_right hu <| inf_le_of_left_le h⟩
lemma Shatters.exists_superset (h : 𝒜.Shatters s) : ∃ t ∈ 𝒜, s ⊆ t :=
let ⟨t, ht, hst⟩ := h Subset.rfl; ⟨t, ht, inter_eq_left.1 hst⟩
lemma shatters_of_forall_subset (h : ∀ t, t ⊆ s → t ∈ 𝒜) : 𝒜.Shatters s :=
fun t ht ↦ ⟨t, h _ ht, inter_eq_right.2 ht⟩
protected lemma Shatters.nonempty (h : 𝒜.Shatters s) : 𝒜.Nonempty :=
let ⟨t, ht, _⟩ := h Subset.rfl; ⟨t, ht⟩
@[simp] lemma shatters_empty : 𝒜.Shatters ∅ ↔ 𝒜.Nonempty :=
⟨Shatters.nonempty, fun ⟨s, hs⟩ t ht ↦ ⟨s, hs, by rwa [empty_inter, eq_comm, ← subset_empty]⟩⟩
protected lemma Shatters.subset_iff (h : 𝒜.Shatters s) : t ⊆ s ↔ ∃ u ∈ 𝒜, s ∩ u = t :=
⟨fun ht ↦ h ht, by rintro ⟨u, _, rfl⟩; exact inter_subset_left⟩
lemma shatters_iff : 𝒜.Shatters s ↔ 𝒜.image (fun t ↦ s ∩ t) = s.powerset :=
⟨fun h ↦ by ext t; rw [mem_image, mem_powerset, h.subset_iff],
fun h t ht ↦ by rwa [← mem_powerset, ← h, mem_image] at ht⟩
lemma univ_shatters [Fintype α] : univ.Shatters s :=
shatters_of_forall_subset fun _ _ ↦ mem_univ _
@[simp] lemma shatters_univ [Fintype α] : 𝒜.Shatters univ ↔ 𝒜 = univ := by
rw [shatters_iff, powerset_univ]; simp_rw [univ_inter, image_id']
/-- The set family of sets that are shattered by `𝒜`. -/
def shatterer (𝒜 : Finset (Finset α)) : Finset (Finset α) :=
{s ∈ 𝒜.biUnion powerset | 𝒜.Shatters s}
@[simp] lemma mem_shatterer : s ∈ 𝒜.shatterer ↔ 𝒜.Shatters s := by
refine mem_filter.trans <| and_iff_right_of_imp fun h ↦ ?_
simp_rw [mem_biUnion, mem_powerset]
exact h.exists_superset
@[gcongr] lemma shatterer_mono (h : 𝒜 ⊆ ℬ) : 𝒜.shatterer ⊆ ℬ.shatterer :=
fun _ ↦ by simpa using Shatters.mono_left h
lemma subset_shatterer (h : IsLowerSet (𝒜 : Set (Finset α))) : 𝒜 ⊆ 𝒜.shatterer :=
fun _s hs ↦ mem_shatterer.2 fun t ht ↦ ⟨t, h ht hs, inter_eq_right.2 ht⟩
@[simp] lemma isLowerSet_shatterer (𝒜 : Finset (Finset α)) :
IsLowerSet (𝒜.shatterer : Set (Finset α)) := fun s t ↦ by simpa using Shatters.mono_right
@[simp] lemma shatterer_eq : 𝒜.shatterer = 𝒜 ↔ IsLowerSet (𝒜 : Set (Finset α)) := by
refine ⟨fun h ↦ ?_, fun h ↦ Subset.antisymm (fun s hs ↦ ?_) <| subset_shatterer h⟩
· rw [← h]
exact isLowerSet_shatterer _
· obtain ⟨t, ht, hst⟩ := (mem_shatterer.1 hs).exists_superset
exact h hst ht
@[simp] lemma shatterer_idem : 𝒜.shatterer.shatterer = 𝒜.shatterer := by simp
@[simp] lemma shatters_shatterer : 𝒜.shatterer.Shatters s ↔ 𝒜.Shatters s := by
simp_rw [← mem_shatterer, shatterer_idem]
protected alias ⟨_, Shatters.shatterer⟩ := shatters_shatterer
private lemma aux (h : ∀ t ∈ 𝒜, a ∉ t) (ht : 𝒜.Shatters t) : a ∉ t := by
obtain ⟨u, hu, htu⟩ := ht.exists_superset; exact notMem_mono htu <| h u hu
/-- Pajor's variant of the **Sauer-Shelah lemma**. -/
lemma card_le_card_shatterer (𝒜 : Finset (Finset α)) : #𝒜 ≤ #𝒜.shatterer := by
refine memberFamily_induction_on 𝒜 ?_ ?_ ?_
· simp
· rfl
intro a 𝒜 ih₀ ih₁
set ℬ : Finset (Finset α) :=
((memberSubfamily a 𝒜).shatterer ∩ (nonMemberSubfamily a 𝒜).shatterer).image (insert a)
have hℬ : #ℬ = #((memberSubfamily a 𝒜).shatterer ∩ (nonMemberSubfamily a 𝒜).shatterer) := by
refine card_image_of_injOn <| insert_erase_invOn.2.injOn.mono ?_
simp only [coe_inter, Set.subset_def, Set.mem_inter_iff, mem_coe, Set.mem_setOf_eq, and_imp,
mem_shatterer]
exact fun s _ ↦ aux (fun t ht ↦ (mem_filter.1 ht).2)
rw [← card_memberSubfamily_add_card_nonMemberSubfamily a]
refine (Nat.add_le_add ih₁ ih₀).trans ?_
rw [← card_union_add_card_inter, ← hℬ, ← card_union_of_disjoint]
swap
· simp only [ℬ, disjoint_left, mem_union, mem_shatterer, mem_image, not_exists, not_and]
rintro _ (hs | hs) s - rfl
· exact aux (fun t ht ↦ (mem_memberSubfamily.1 ht).2) hs <| mem_insert_self _ _
· exact aux (fun t ht ↦ (mem_nonMemberSubfamily.1 ht).2) hs <| mem_insert_self _ _
refine card_mono <| union_subset (union_subset ?_ <| shatterer_mono <| filter_subset _ _) ?_
· simp only [subset_iff, mem_shatterer]
rintro s hs t ht
obtain ⟨u, hu, rfl⟩ := hs ht
rw [mem_memberSubfamily] at hu
refine ⟨insert a u, hu.1, inter_insert_of_notMem fun ha ↦ ?_⟩
obtain ⟨v, hv, hsv⟩ := hs.exists_inter_eq_singleton ha
rw [mem_memberSubfamily] at hv
rw [← singleton_subset_iff (a := a), ← hsv] at hv
exact hv.2 inter_subset_right
· refine forall_mem_image.2 fun s hs ↦ mem_shatterer.2 fun t ht ↦ ?_
simp only [mem_inter, mem_shatterer] at hs
rw [subset_insert_iff] at ht
by_cases ha : a ∈ t
· obtain ⟨u, hu, hsu⟩ := hs.1 ht
rw [mem_memberSubfamily] at hu
refine ⟨_, hu.1, ?_⟩
rw [← insert_inter_distrib, hsu, insert_erase ha]
· obtain ⟨u, hu, hsu⟩ := hs.2 ht
rw [mem_nonMemberSubfamily] at hu
refine ⟨_, hu.1, ?_⟩
rwa [insert_inter_of_notMem hu.2, hsu, erase_eq_self]
lemma Shatters.of_compression (hs : (𝓓 a 𝒜).Shatters s) : 𝒜.Shatters s := by
intro t ht
obtain ⟨u, hu, rfl⟩ := hs ht
rw [Down.mem_compression] at hu
obtain hu | hu := hu
· exact ⟨u, hu.1, rfl⟩
by_cases ha : a ∈ s
· obtain ⟨v, hv, hsv⟩ := hs <| insert_subset ha ht
rw [Down.mem_compression] at hv
obtain hv | hv := hv
· refine ⟨erase v a, hv.2, ?_⟩
rw [inter_erase, hsv, erase_insert]
rintro ha
rw [insert_eq_self.2 (mem_inter.1 ha).2] at hu
exact hu.1 hu.2
rw [insert_eq_self.2 <| inter_subset_right (s₁ := s) ?_] at hv
cases hv.1 hv.2
rw [hsv]
exact mem_insert_self _ _
· refine ⟨insert a u, hu.2, ?_⟩
rw [inter_insert_of_notMem ha]
lemma shatterer_compress_subset_shatterer (a : α) (𝒜 : Finset (Finset α)) :
(𝓓 a 𝒜).shatterer ⊆ 𝒜.shatterer := by
simp only [subset_iff, mem_shatterer]; exact fun s hs ↦ hs.of_compression
/-! ### Vapnik-Chervonenkis dimension -/
/-- The Vapnik-Chervonenkis dimension of a set family is the maximal size of a set it shatters. -/
def vcDim (𝒜 : Finset (Finset α)) : ℕ := 𝒜.shatterer.sup card
@[gcongr] lemma vcDim_mono (h𝒜ℬ : 𝒜 ⊆ ℬ) : 𝒜.vcDim ≤ ℬ.vcDim := by unfold vcDim; gcongr
lemma Shatters.card_le_vcDim (hs : 𝒜.Shatters s) : #s ≤ 𝒜.vcDim := le_sup <| mem_shatterer.2 hs
/-- Down-compressing decreases the VC-dimension. -/
lemma vcDim_compress_le (a : α) (𝒜 : Finset (Finset α)) : (𝓓 a 𝒜).vcDim ≤ 𝒜.vcDim :=
sup_mono <| shatterer_compress_subset_shatterer _ _
/-- The **Sauer-Shelah lemma**. -/
lemma card_shatterer_le_sum_vcDim [Fintype α] :
#𝒜.shatterer ≤ ∑ k ∈ Iic 𝒜.vcDim, (Fintype.card α).choose k := by
simp_rw [← card_univ, ← card_powersetCard]
refine (card_le_card fun s hs ↦ mem_biUnion.2 ⟨#s, ?_⟩).trans card_biUnion_le
exact ⟨mem_Iic.2 (mem_shatterer.1 hs).card_le_vcDim, mem_powersetCard_univ.2 rfl⟩
end Finset |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/Compression/UV.lean | import Mathlib.Combinatorics.SetFamily.Shadow
/-!
# UV-compressions
This file defines UV-compression. It is an operation on a set family that reduces its shadow.
UV-compressing `a : α` along `u v : α` means replacing `a` by `(a ⊔ u) \ v` if `a` and `u` are
disjoint and `v ≤ a`. In some sense, it's moving `a` from `v` to `u`.
UV-compressions are immensely useful to prove the Kruskal-Katona theorem. The idea is that
compressing a set family might decrease the size of its shadow, so iterated compressions hopefully
minimise the shadow.
## Main declarations
* `UV.compress`: `compress u v a` is `a` compressed along `u` and `v`.
* `UV.compression`: `compression u v s` is the compression of the set family `s` along `u` and `v`.
It is the compressions of the elements of `s` whose compression is not already in `s` along with
the element whose compression is already in `s`. This way of splitting into what moves and what
does not ensures the compression doesn't squash the set family, which is proved by
`UV.card_compression`.
* `UV.card_shadow_compression_le`: Compressing reduces the size of the shadow. This is a key fact in
the proof of Kruskal-Katona.
## Notation
`𝓒` (typed with `\MCC`) is notation for `UV.compression` in scope `FinsetFamily`.
## Notes
Even though our emphasis is on `Finset α`, we define UV-compressions more generally in a generalized
Boolean algebra, so that one can use it for `Set α`.
## References
* https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf
## Tags
compression, UV-compression, shadow
-/
open Finset
variable {α : Type*}
/-- UV-compression is injective on the elements it moves. See `UV.compress`. -/
theorem sup_sdiff_injOn [GeneralizedBooleanAlgebra α] (u v : α) :
{ x | Disjoint u x ∧ v ≤ x }.InjOn fun x => (x ⊔ u) \ v := by
rintro a ha b hb hab
have h : ((a ⊔ u) \ v) \ u ⊔ v = ((b ⊔ u) \ v) \ u ⊔ v := by
dsimp at hab
rw [hab]
rwa [sdiff_sdiff_comm, ha.1.symm.sup_sdiff_cancel_right, sdiff_sdiff_comm,
hb.1.symm.sup_sdiff_cancel_right, sdiff_sup_cancel ha.2, sdiff_sup_cancel hb.2] at h
-- The namespace is here to distinguish from other compressions.
namespace UV
/-! ### UV-compression in generalized Boolean algebras -/
section GeneralizedBooleanAlgebra
variable [GeneralizedBooleanAlgebra α] [DecidableRel (@Disjoint α _ _)]
[DecidableLE α] {s : Finset α} {u v a : α}
/-- UV-compressing `a` means removing `v` from it and adding `u` if `a` and `u` are disjoint and
`v ≤ a` (it replaces the `v` part of `a` by the `u` part). Else, UV-compressing `a` doesn't do
anything. This is most useful when `u` and `v` are disjoint finsets of the same size. -/
def compress (u v a : α) : α :=
if Disjoint u a ∧ v ≤ a then (a ⊔ u) \ v else a
theorem compress_of_disjoint_of_le (hua : Disjoint u a) (hva : v ≤ a) :
compress u v a = (a ⊔ u) \ v :=
if_pos ⟨hua, hva⟩
theorem compress_of_disjoint_of_le' (hva : Disjoint v a) (hua : u ≤ a) :
compress u v ((a ⊔ v) \ u) = a := by
rw [compress_of_disjoint_of_le disjoint_sdiff_self_right
(le_sdiff.2 ⟨(le_sup_right : v ≤ a ⊔ v), hva.mono_right hua⟩),
sdiff_sup_cancel (le_sup_of_le_left hua), hva.symm.sup_sdiff_cancel_right]
@[simp]
theorem compress_self (u a : α) : compress u u a = a := by
unfold compress
split_ifs with h
· exact h.1.symm.sup_sdiff_cancel_right
· rfl
/-- An element can be compressed to any other element by removing/adding the differences. -/
@[simp]
theorem compress_sdiff_sdiff (a b : α) : compress (a \ b) (b \ a) b = a := by
refine (compress_of_disjoint_of_le disjoint_sdiff_self_left sdiff_le).trans ?_
rw [sup_sdiff_self_right, sup_sdiff, disjoint_sdiff_self_right.sdiff_eq_left, sup_eq_right]
exact sdiff_sdiff_le
/-- Compressing an element is idempotent. -/
@[simp]
theorem compress_idem (u v a : α) : compress u v (compress u v a) = compress u v a := by
unfold compress
split_ifs with h h'
· rw [le_sdiff_right.1 h'.2, sdiff_bot, sdiff_bot, sup_assoc, sup_idem]
· rfl
· rfl
variable [DecidableEq α]
/-- To UV-compress a set family, we compress each of its elements, except that we don't want to
reduce the cardinality, so we keep all elements whose compression is already present. -/
def compression (u v : α) (s : Finset α) :=
{a ∈ s | compress u v a ∈ s} ∪ {a ∈ s.image <| compress u v | a ∉ s}
@[inherit_doc]
scoped[FinsetFamily] notation "𝓒 " => UV.compression
open scoped FinsetFamily
/-- `IsCompressed u v s` expresses that `s` is UV-compressed. -/
def IsCompressed (u v : α) (s : Finset α) :=
𝓒 u v s = s
/-- UV-compression is injective on the sets that are not UV-compressed. -/
theorem compress_injOn : Set.InjOn (compress u v) ↑{a ∈ s | compress u v a ∉ s} := by
intro a ha b hb hab
rw [mem_coe, mem_filter] at ha hb
rw [compress] at ha hab
split_ifs at ha hab with has
· rw [compress] at hb hab
split_ifs at hb hab with hbs
· exact sup_sdiff_injOn u v has hbs hab
· exact (hb.2 hb.1).elim
· exact (ha.2 ha.1).elim
/-- `a` is in the UV-compressed family iff it's in the original and its compression is in the
original, or it's not in the original but it's the compression of something in the original. -/
theorem mem_compression :
a ∈ 𝓒 u v s ↔ a ∈ s ∧ compress u v a ∈ s ∨ a ∉ s ∧ ∃ b ∈ s, compress u v b = a := by
simp_rw [compression, mem_union, mem_filter, mem_image, and_comm]
protected theorem IsCompressed.eq (h : IsCompressed u v s) : 𝓒 u v s = s := h
@[simp]
theorem compression_self (u : α) (s : Finset α) : 𝓒 u u s = s := by
unfold compression
convert union_empty s
· ext a
rw [mem_filter, compress_self, and_self_iff]
· refine eq_empty_of_forall_notMem fun a ha ↦ ?_
simp_rw [mem_filter, mem_image, compress_self] at ha
obtain ⟨⟨b, hb, rfl⟩, hb'⟩ := ha
exact hb' hb
/-- Any family is compressed along two identical elements. -/
theorem isCompressed_self (u : α) (s : Finset α) : IsCompressed u u s := compression_self u s
theorem compress_disjoint :
Disjoint {a ∈ s | compress u v a ∈ s} {a ∈ s.image <| compress u v | a ∉ s} :=
disjoint_left.2 fun _a ha₁ ha₂ ↦ (mem_filter.1 ha₂).2 (mem_filter.1 ha₁).1
theorem compress_mem_compression (ha : a ∈ s) : compress u v a ∈ 𝓒 u v s := by
rw [mem_compression]
by_cases h : compress u v a ∈ s
· rw [compress_idem]
exact Or.inl ⟨h, h⟩
· exact Or.inr ⟨h, a, ha, rfl⟩
-- This is a special case of `compress_mem_compression` once we have `compression_idem`.
theorem compress_mem_compression_of_mem_compression (ha : a ∈ 𝓒 u v s) :
compress u v a ∈ 𝓒 u v s := by
rw [mem_compression] at ha ⊢
simp only [compress_idem]
obtain ⟨_, ha⟩ | ⟨_, b, hb, rfl⟩ := ha
· exact Or.inl ⟨ha, ha⟩
· exact Or.inr ⟨by rwa [compress_idem], b, hb, (compress_idem _ _ _).symm⟩
/-- Compressing a family is idempotent. -/
@[simp]
theorem compression_idem (u v : α) (s : Finset α) : 𝓒 u v (𝓒 u v s) = 𝓒 u v s := by
have h : {a ∈ 𝓒 u v s | compress u v a ∉ 𝓒 u v s} = ∅ :=
filter_false_of_mem fun a ha h ↦ h <| compress_mem_compression_of_mem_compression ha
rw [compression, filter_image, h, image_empty, ← h]
exact filter_union_filter_neg_eq _ (compression u v s)
/-- Compressing a family doesn't change its size. -/
@[simp]
theorem card_compression (u v : α) (s : Finset α) : #(𝓒 u v s) = #s := by
rw [compression, card_union_of_disjoint compress_disjoint, filter_image,
card_image_of_injOn compress_injOn, ← card_union_of_disjoint (disjoint_filter_filter_neg s _ _),
filter_union_filter_neg_eq]
theorem le_of_mem_compression_of_notMem (h : a ∈ 𝓒 u v s) (ha : a ∉ s) : u ≤ a := by
rw [mem_compression] at h
obtain h | ⟨-, b, hb, hba⟩ := h
· cases ha h.1
unfold compress at hba
split_ifs at hba with h
· rw [← hba, le_sdiff]
exact ⟨le_sup_right, h.1.mono_right h.2⟩
· cases ne_of_mem_of_not_mem hb ha hba
@[deprecated (since := "2025-05-23")]
alias le_of_mem_compression_of_not_mem := le_of_mem_compression_of_notMem
theorem disjoint_of_mem_compression_of_notMem (h : a ∈ 𝓒 u v s) (ha : a ∉ s) : Disjoint v a := by
rw [mem_compression] at h
obtain h | ⟨-, b, hb, hba⟩ := h
· cases ha h.1
unfold compress at hba
split_ifs at hba
· rw [← hba]
exact disjoint_sdiff_self_right
· cases ne_of_mem_of_not_mem hb ha hba
@[deprecated (since := "2025-05-23")]
alias disjoint_of_mem_compression_of_not_mem := disjoint_of_mem_compression_of_notMem
theorem sup_sdiff_mem_of_mem_compression_of_notMem (h : a ∈ 𝓒 u v s) (ha : a ∉ s) :
(a ⊔ v) \ u ∈ s := by
rw [mem_compression] at h
obtain h | ⟨-, b, hb, hba⟩ := h
· cases ha h.1
unfold compress at hba
split_ifs at hba with h
· rwa [← hba, sdiff_sup_cancel (le_sup_of_le_left h.2), sup_sdiff_right_self,
h.1.symm.sdiff_eq_left]
· cases ne_of_mem_of_not_mem hb ha hba
@[deprecated (since := "2025-05-23")]
alias sup_sdiff_mem_of_mem_compression_of_not_mem := sup_sdiff_mem_of_mem_compression_of_notMem
/-- If `a` is in the family compression and can be compressed, then its compression is in the
original family. -/
theorem sup_sdiff_mem_of_mem_compression (ha : a ∈ 𝓒 u v s) (hva : v ≤ a) (hua : Disjoint u a) :
(a ⊔ u) \ v ∈ s := by
rw [mem_compression, compress_of_disjoint_of_le hua hva] at ha
obtain ⟨_, ha⟩ | ⟨_, b, hb, rfl⟩ := ha
· exact ha
have hu : u = ⊥ := by
suffices Disjoint u (u \ v) by rwa [(hua.mono_right hva).sdiff_eq_left, disjoint_self] at this
refine hua.mono_right ?_
rw [← compress_idem, compress_of_disjoint_of_le hua hva]
exact sdiff_le_sdiff_right le_sup_right
have hv : v = ⊥ := by
rw [← disjoint_self]
apply Disjoint.mono_right hva
rw [← compress_idem, compress_of_disjoint_of_le hua hva]
exact disjoint_sdiff_self_right
rwa [hu, hv, compress_self, sup_bot_eq, sdiff_bot]
/-- If `a` is in the `u, v`-compression but `v ≤ a`, then `a` must have been in the original
family. -/
theorem mem_of_mem_compression (ha : a ∈ 𝓒 u v s) (hva : v ≤ a) (hvu : v = ⊥ → u = ⊥) :
a ∈ s := by
rw [mem_compression] at ha
obtain ha | ⟨_, b, hb, h⟩ := ha
· exact ha.1
unfold compress at h
split_ifs at h
· rw [← h, le_sdiff_right] at hva
rwa [← h, hvu hva, hva, sup_bot_eq, sdiff_bot]
· rwa [← h]
end GeneralizedBooleanAlgebra
/-! ### UV-compression on finsets -/
open FinsetFamily
variable [DecidableEq α] {𝒜 : Finset (Finset α)} {u v : Finset α} {r : ℕ}
/-- Compressing a finset doesn't change its size. -/
theorem card_compress (huv : #u = #v) (a : Finset α) : #(compress u v a) = #a := by
unfold compress
split_ifs with h
· rw [card_sdiff_of_subset (h.2.trans le_sup_left), sup_eq_union,
card_union_of_disjoint h.1.symm, huv, add_tsub_cancel_right]
· rfl
lemma _root_.Set.Sized.uvCompression (huv : #u = #v) (h𝒜 : (𝒜 : Set (Finset α)).Sized r) :
(𝓒 u v 𝒜 : Set (Finset α)).Sized r := by
simp_rw [Set.Sized, mem_coe, mem_compression]
rintro s (hs | ⟨huvt, t, ht, rfl⟩)
· exact h𝒜 hs.1
· rw [card_compress huv, h𝒜 ht]
private theorem aux (huv : ∀ x ∈ u, ∃ y ∈ v, IsCompressed (u.erase x) (v.erase y) 𝒜) :
v = ∅ → u = ∅ := by
grind
/-- UV-compression reduces the size of the shadow of `𝒜` if, for all `x ∈ u` there is `y ∈ v` such
that `𝒜` is `(u.erase x, v.erase y)`-compressed. This is the key fact about compression for
Kruskal-Katona. -/
theorem shadow_compression_subset_compression_shadow (u v : Finset α)
(huv : ∀ x ∈ u, ∃ y ∈ v, IsCompressed (u.erase x) (v.erase y) 𝒜) :
∂ (𝓒 u v 𝒜) ⊆ 𝓒 u v (∂ 𝒜) := by
set 𝒜' := 𝓒 u v 𝒜
suffices H : ∀ s ∈ ∂ 𝒜',
s ∉ ∂ 𝒜 → u ⊆ s ∧ Disjoint v s ∧ (s ∪ v) \ u ∈ ∂ 𝒜 ∧ (s ∪ v) \ u ∉ ∂ 𝒜' by
rintro s hs'
rw [mem_compression]
by_cases hs : s ∈ 𝒜.shadow
swap
· obtain ⟨hus, hvs, h, _⟩ := H _ hs' hs
exact Or.inr ⟨hs, _, h, compress_of_disjoint_of_le' hvs hus⟩
refine Or.inl ⟨hs, ?_⟩
rw [compress]
split_ifs with huvs
swap
· exact hs
rw [mem_shadow_iff] at hs'
obtain ⟨t, Ht, a, hat, rfl⟩ := hs'
have hav : a ∉ v := notMem_mono huvs.2 (notMem_erase a t)
have hvt : v ≤ t := huvs.2.trans (erase_subset _ t)
have ht : t ∈ 𝒜 := mem_of_mem_compression Ht hvt (aux huv)
by_cases hau : a ∈ u
· obtain ⟨b, hbv, Hcomp⟩ := huv a hau
refine mem_shadow_iff_insert_mem.2 ⟨b, notMem_sdiff_of_mem_right hbv, ?_⟩
rw [← Hcomp.eq] at ht
have hsb :=
sup_sdiff_mem_of_mem_compression ht ((erase_subset _ _).trans hvt)
(disjoint_erase_comm.2 huvs.1)
rwa [sup_eq_union, sdiff_erase (mem_union_left _ <| hvt hbv), union_erase_of_mem hat, ←
erase_union_of_mem hau] at hsb
· refine mem_shadow_iff.2
⟨(t ⊔ u) \ v,
sup_sdiff_mem_of_mem_compression Ht hvt <| disjoint_of_erase_right hau huvs.1, a, ?_, ?_⟩
· rw [sup_eq_union, mem_sdiff, mem_union]
exact ⟨Or.inl hat, hav⟩
· simp [← erase_sdiff_comm, erase_union_distrib, erase_eq_of_notMem hau]
intro s hs𝒜' hs𝒜
-- This is going to be useful a couple of times so let's name it.
have m : ∀ y, y ∉ s → insert y s ∉ 𝒜 := fun y h a => hs𝒜 (mem_shadow_iff_insert_mem.2 ⟨y, h, a⟩)
obtain ⟨x, _, _⟩ := mem_shadow_iff_insert_mem.1 hs𝒜'
have hus : u ⊆ insert x s := le_of_mem_compression_of_notMem ‹_ ∈ 𝒜'› (m _ ‹x ∉ s›)
have hvs : Disjoint v (insert x s) := disjoint_of_mem_compression_of_notMem ‹_› (m _ ‹x ∉ s›)
have : (insert x s ∪ v) \ u ∈ 𝒜 := sup_sdiff_mem_of_mem_compression_of_notMem ‹_› (m _ ‹x ∉ s›)
have hsv : Disjoint s v := hvs.symm.mono_left (subset_insert _ _)
have hvu : Disjoint v u := disjoint_of_subset_right hus hvs
have hxv : x ∉ v := disjoint_right.1 hvs (mem_insert_self _ _)
have : v \ u = v := ‹Disjoint v u›.sdiff_eq_left
-- The first key part is that `x ∉ u`
have : x ∉ u := by
intro hxu
obtain ⟨y, hyv, hxy⟩ := huv x hxu
-- If `x ∈ u`, we can get `y ∈ v` so that `𝒜` is `(u.erase x, v.erase y)`-compressed
apply m y (disjoint_right.1 hsv hyv)
-- and we will use this `y` to contradict `m`, so we would like to show `insert y s ∈ 𝒜`.
-- We do this by showing the below
have : ((insert x s ∪ v) \ u ∪ erase u x) \ erase v y ∈ 𝒜 := by
refine
sup_sdiff_mem_of_mem_compression (by rwa [hxy.eq]) ?_
(disjoint_of_subset_left (erase_subset _ _) disjoint_sdiff)
rw [union_sdiff_distrib, ‹v \ u = v›]
exact (erase_subset _ _).trans subset_union_right
-- and then arguing that it's the same
convert this using 1
rw [sdiff_union_erase_cancel (hus.trans subset_union_left) ‹x ∈ u›, erase_union_distrib,
erase_insert ‹x ∉ s›, erase_eq_of_notMem ‹x ∉ v›, sdiff_erase (mem_union_right _ hyv),
union_sdiff_cancel_right hsv]
-- Now that this is done, it's immediate that `u ⊆ s`
have hus : u ⊆ s := by rwa [← erase_eq_of_notMem ‹x ∉ u›, ← subset_insert_iff]
-- and we already had that `v` and `s` are disjoint,
-- so it only remains to get `(s ∪ v) \ u ∈ ∂ 𝒜 \ ∂ 𝒜'`
simp_rw [mem_shadow_iff_insert_mem]
refine ⟨hus, hsv.symm, ⟨x, ?_, ?_⟩, ?_⟩
-- `(s ∪ v) \ u ∈ ∂ 𝒜` is pretty direct:
· exact notMem_sdiff_of_notMem_left (notMem_union.2 ⟨‹x ∉ s›, ‹x ∉ v›⟩)
· rwa [← insert_sdiff_of_notMem _ ‹x ∉ u›, ← insert_union]
-- For (s ∪ v) \ u ∉ ∂ 𝒜', we split up based on w ∈ u
rintro ⟨w, hwB, hw𝒜'⟩
have : v ⊆ insert w ((s ∪ v) \ u) :=
(subset_sdiff.2 ⟨subset_union_right, hvu⟩).trans (subset_insert _ _)
by_cases hwu : w ∈ u
-- If `w ∈ u`, we find `z ∈ v`, and contradict `m` again
· obtain ⟨z, hz, hxy⟩ := huv w hwu
apply m z (disjoint_right.1 hsv hz)
have : insert w ((s ∪ v) \ u) ∈ 𝒜 := mem_of_mem_compression hw𝒜' ‹_› (aux huv)
have : (insert w ((s ∪ v) \ u) ∪ erase u w) \ erase v z ∈ 𝒜 := by
refine sup_sdiff_mem_of_mem_compression (by rwa [hxy.eq]) ((erase_subset _ _).trans ‹_›) ?_
rw [← sdiff_erase (mem_union_left _ <| hus hwu)]
exact disjoint_sdiff
convert this using 1
rw [insert_union_comm, insert_erase ‹w ∈ u›,
sdiff_union_of_subset (hus.trans subset_union_left),
sdiff_erase (mem_union_right _ ‹z ∈ v›), union_sdiff_cancel_right hsv]
-- If `w ∉ u`, we contradict `m` again
rw [mem_sdiff, ← Classical.not_imp, Classical.not_not] at hwB
apply m w (hwu ∘ hwB ∘ mem_union_left _)
have : (insert w ((s ∪ v) \ u) ∪ u) \ v ∈ 𝒜 :=
sup_sdiff_mem_of_mem_compression ‹insert w ((s ∪ v) \ u) ∈ 𝒜'› ‹_›
(disjoint_insert_right.2 ⟨‹_›, disjoint_sdiff⟩)
convert this using 1
rw [insert_union, sdiff_union_of_subset (hus.trans subset_union_left),
insert_sdiff_of_notMem _ (hwu ∘ hwB ∘ mem_union_right _), union_sdiff_cancel_right hsv]
/-- UV-compression reduces the size of the shadow of `𝒜` if, for all `x ∈ u` there is `y ∈ v`
such that `𝒜` is `(u.erase x, v.erase y)`-compressed. This is the key UV-compression fact needed for
Kruskal-Katona. -/
theorem card_shadow_compression_le (u v : Finset α)
(huv : ∀ x ∈ u, ∃ y ∈ v, IsCompressed (u.erase x) (v.erase y) 𝒜) :
#(∂ (𝓒 u v 𝒜)) ≤ #(∂ 𝒜) :=
(card_le_card <| shadow_compression_subset_compression_shadow _ _ huv).trans
(card_compression _ _ _).le
end UV |
.lake/packages/mathlib/Mathlib/Combinatorics/SetFamily/Compression/Down.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Finset.Lattice.Fold
/-!
# Down-compressions
This file defines down-compression.
Down-compressing `𝒜 : Finset (Finset α)` along `a : α` means removing `a` from the elements of `𝒜`,
when the resulting set is not already in `𝒜`.
## Main declarations
* `Finset.nonMemberSubfamily`: `𝒜.nonMemberSubfamily a` is the subfamily of sets not containing
`a`.
* `Finset.memberSubfamily`: `𝒜.memberSubfamily a` is the image of the subfamily of sets containing
`a` under removing `a`.
* `Down.compression`: Down-compression.
## Notation
`𝓓 a 𝒜` is notation for `Down.compress a 𝒜` in scope `SetFamily`.
## References
* https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf
## Tags
compression, down-compression
-/
variable {α : Type*} [DecidableEq α] {𝒜 : Finset (Finset α)} {s : Finset α} {a : α}
namespace Finset
/-- Elements of `𝒜` that do not contain `a`. -/
def nonMemberSubfamily (a : α) (𝒜 : Finset (Finset α)) : Finset (Finset α) := {s ∈ 𝒜 | a ∉ s}
/-- Image of the elements of `𝒜` which contain `a` under removing `a`. Finsets that do not contain
`a` such that `insert a s ∈ 𝒜`. -/
def memberSubfamily (a : α) (𝒜 : Finset (Finset α)) : Finset (Finset α) :=
{s ∈ 𝒜 | a ∈ s}.image fun s => erase s a
@[simp]
theorem mem_nonMemberSubfamily : s ∈ 𝒜.nonMemberSubfamily a ↔ s ∈ 𝒜 ∧ a ∉ s := by
simp [nonMemberSubfamily]
@[simp]
theorem mem_memberSubfamily : s ∈ 𝒜.memberSubfamily a ↔ insert a s ∈ 𝒜 ∧ a ∉ s := by
simp_rw [memberSubfamily, mem_image, mem_filter]
refine ⟨?_, fun h => ⟨insert a s, ⟨h.1, by simp⟩, erase_insert h.2⟩⟩
rintro ⟨s, ⟨hs1, hs2⟩, rfl⟩
rw [insert_erase hs2]
exact ⟨hs1, notMem_erase _ _⟩
theorem nonMemberSubfamily_inter (a : α) (𝒜 ℬ : Finset (Finset α)) :
(𝒜 ∩ ℬ).nonMemberSubfamily a = 𝒜.nonMemberSubfamily a ∩ ℬ.nonMemberSubfamily a :=
filter_inter_distrib _ _ _
theorem memberSubfamily_inter (a : α) (𝒜 ℬ : Finset (Finset α)) :
(𝒜 ∩ ℬ).memberSubfamily a = 𝒜.memberSubfamily a ∩ ℬ.memberSubfamily a := by
unfold memberSubfamily
rw [filter_inter_distrib, image_inter_of_injOn _ _ ((erase_injOn' _).mono _)]
simp
theorem nonMemberSubfamily_union (a : α) (𝒜 ℬ : Finset (Finset α)) :
(𝒜 ∪ ℬ).nonMemberSubfamily a = 𝒜.nonMemberSubfamily a ∪ ℬ.nonMemberSubfamily a :=
filter_union _ _ _
theorem memberSubfamily_union (a : α) (𝒜 ℬ : Finset (Finset α)) :
(𝒜 ∪ ℬ).memberSubfamily a = 𝒜.memberSubfamily a ∪ ℬ.memberSubfamily a := by
simp_rw [memberSubfamily, filter_union, image_union]
theorem card_memberSubfamily_add_card_nonMemberSubfamily (a : α) (𝒜 : Finset (Finset α)) :
#(𝒜.memberSubfamily a) + #(𝒜.nonMemberSubfamily a) = #𝒜 := by
rw [memberSubfamily, nonMemberSubfamily, card_image_of_injOn]
· conv_rhs => rw [← filter_card_add_filter_neg_card_eq_card (fun s => (a ∈ s))]
· apply (erase_injOn' _).mono
simp
theorem memberSubfamily_union_nonMemberSubfamily (a : α) (𝒜 : Finset (Finset α)) :
𝒜.memberSubfamily a ∪ 𝒜.nonMemberSubfamily a = 𝒜.image fun s => s.erase a := by
ext s
simp only [mem_union, mem_memberSubfamily, mem_nonMemberSubfamily, mem_image]
constructor
· rintro (h | h)
· exact ⟨_, h.1, erase_insert h.2⟩
· exact ⟨_, h.1, erase_eq_of_notMem h.2⟩
· rintro ⟨s, hs, rfl⟩
by_cases ha : a ∈ s
· exact Or.inl ⟨by rwa [insert_erase ha], notMem_erase _ _⟩
· exact Or.inr ⟨by rwa [erase_eq_of_notMem ha], notMem_erase _ _⟩
@[simp]
theorem memberSubfamily_memberSubfamily : (𝒜.memberSubfamily a).memberSubfamily a = ∅ := by
ext
simp
@[simp]
theorem memberSubfamily_nonMemberSubfamily : (𝒜.nonMemberSubfamily a).memberSubfamily a = ∅ := by
ext
simp
@[simp]
theorem nonMemberSubfamily_memberSubfamily :
(𝒜.memberSubfamily a).nonMemberSubfamily a = 𝒜.memberSubfamily a := by
ext
simp
@[simp]
theorem nonMemberSubfamily_nonMemberSubfamily :
(𝒜.nonMemberSubfamily a).nonMemberSubfamily a = 𝒜.nonMemberSubfamily a := by
ext
simp
lemma memberSubfamily_image_insert (h𝒜 : ∀ s ∈ 𝒜, a ∉ s) :
(𝒜.image <| insert a).memberSubfamily a = 𝒜 := by
ext s
simp only [mem_memberSubfamily, mem_image]
refine ⟨?_, fun hs ↦ ⟨⟨s, hs, rfl⟩, h𝒜 _ hs⟩⟩
rintro ⟨⟨t, ht, hts⟩, hs⟩
rwa [← insert_erase_invOn.2.injOn (h𝒜 _ ht) hs hts]
@[simp] lemma nonMemberSubfamily_image_insert : (𝒜.image <| insert a).nonMemberSubfamily a = ∅ := by
simp [eq_empty_iff_forall_notMem]
@[simp] lemma memberSubfamily_image_erase : (𝒜.image (erase · a)).memberSubfamily a = ∅ := by
simp [eq_empty_iff_forall_notMem,
(ne_of_mem_of_not_mem' (mem_insert_self _ _) (notMem_erase _ _)).symm]
lemma image_insert_memberSubfamily (𝒜 : Finset (Finset α)) (a : α) :
(𝒜.memberSubfamily a).image (insert a) = {s ∈ 𝒜 | a ∈ s} := by
ext s
simp only [mem_memberSubfamily, mem_image, mem_filter]
refine ⟨?_, fun ⟨hs, ha⟩ ↦ ⟨erase s a, ⟨?_, notMem_erase _ _⟩, insert_erase ha⟩⟩
· rintro ⟨s, ⟨hs, -⟩, rfl⟩
exact ⟨hs, mem_insert_self _ _⟩
· rwa [insert_erase ha]
/-- Induction principle for finset families. To prove a statement for every finset family,
it suffices to prove it for
* the empty finset family.
* the finset family which only contains the empty finset.
* `ℬ ∪ {s ∪ {a} | s ∈ 𝒞}` assuming the property for `ℬ` and `𝒞`, where `a` is an element of the
ground type and `𝒜` and `ℬ` are families of finsets not containing `a`.
Note that instead of giving `ℬ` and `𝒞`, the `subfamily` case gives you
`𝒜 = ℬ ∪ {s ∪ {a} | s ∈ 𝒞}`, so that `ℬ = 𝒜.nonMemberSubfamily` and `𝒞 = 𝒜.memberSubfamily`.
This is a way of formalising induction on `n` where `𝒜` is a finset family on `n` elements.
See also `Finset.family_induction_on.` -/
@[elab_as_elim]
lemma memberFamily_induction_on {p : Finset (Finset α) → Prop}
(𝒜 : Finset (Finset α)) (empty : p ∅) (singleton_empty : p {∅})
(subfamily : ∀ (a : α) ⦃𝒜 : Finset (Finset α)⦄,
p (𝒜.nonMemberSubfamily a) → p (𝒜.memberSubfamily a) → p 𝒜) : p 𝒜 := by
set u := 𝒜.sup id
have hu : ∀ s ∈ 𝒜, s ⊆ u := fun s ↦ le_sup (f := id)
clear_value u
induction u using Finset.induction generalizing 𝒜 with
| empty =>
simp_rw [subset_empty] at hu
rw [← subset_singleton_iff', subset_singleton_iff] at hu
obtain rfl | rfl := hu <;> assumption
| insert a u _ ih =>
refine subfamily a (ih _ ?_) (ih _ ?_)
· simp only [mem_nonMemberSubfamily, and_imp]
exact fun s hs has ↦ (subset_insert_iff_of_notMem has).1 <| hu _ hs
· simp only [mem_memberSubfamily, and_imp]
exact fun s hs ha ↦ (insert_subset_insert_iff ha).1 <| hu _ hs
/-- Induction principle for finset families. To prove a statement for every finset family,
it suffices to prove it for
* the empty finset family.
* the finset family which only contains the empty finset.
* `{s ∪ {a} | s ∈ 𝒜}` assuming the property for `𝒜` a family of finsets not containing `a`.
* `ℬ ∪ 𝒞` assuming the property for `ℬ` and `𝒞`, where `a` is an element of the ground type and
`ℬ`is a family of finsets not containing `a` and `𝒞` a family of finsets containing `a`.
Note that instead of giving `ℬ` and `𝒞`, the `subfamily` case gives you `𝒜 = ℬ ∪ 𝒞`, so that
`ℬ = {s ∈ 𝒜 | a ∉ s}` and `𝒞 = {s ∈ 𝒜 | a ∈ s}`.
This is a way of formalising induction on `n` where `𝒜` is a finset family on `n` elements.
See also `Finset.memberFamily_induction_on.` -/
@[elab_as_elim]
protected lemma family_induction_on {p : Finset (Finset α) → Prop}
(𝒜 : Finset (Finset α)) (empty : p ∅) (singleton_empty : p {∅})
(image_insert : ∀ (a : α) ⦃𝒜 : Finset (Finset α)⦄,
(∀ s ∈ 𝒜, a ∉ s) → p 𝒜 → p (𝒜.image <| insert a))
(subfamily : ∀ (a : α) ⦃𝒜 : Finset (Finset α)⦄,
p {s ∈ 𝒜 | a ∉ s} → p {s ∈ 𝒜 | a ∈ s} → p 𝒜) : p 𝒜 := by
refine memberFamily_induction_on 𝒜 empty singleton_empty fun a 𝒜 h𝒜₀ h𝒜₁ ↦ subfamily a h𝒜₀ ?_
rw [← image_insert_memberSubfamily]
exact image_insert _ (by simp) h𝒜₁
end Finset
open Finset
-- The namespace is here to distinguish from other compressions.
namespace Down
/-- `a`-down-compressing `𝒜` means removing `a` from the elements of `𝒜` that contain it, when the
resulting Finset is not already in `𝒜`. -/
def compression (a : α) (𝒜 : Finset (Finset α)) : Finset (Finset α) :=
{s ∈ 𝒜 | erase s a ∈ 𝒜}.disjUnion {s ∈ 𝒜.image fun s ↦ erase s a | s ∉ 𝒜} <|
disjoint_left.2 fun _s h₁ h₂ ↦ (mem_filter.1 h₂).2 (mem_filter.1 h₁).1
@[inherit_doc]
scoped[FinsetFamily] notation "𝓓 " => Down.compression
open FinsetFamily
/-- `a` is in the down-compressed family iff it's in the original and its compression is in the
original, or it's not in the original but it's the compression of something in the original. -/
theorem mem_compression : s ∈ 𝓓 a 𝒜 ↔ s ∈ 𝒜 ∧ s.erase a ∈ 𝒜 ∨ s ∉ 𝒜 ∧ insert a s ∈ 𝒜 := by
simp_rw [compression, mem_disjUnion, mem_filter, mem_image, and_comm (a := ( s ∉ 𝒜))]
refine
or_congr_right
(and_congr_left fun hs =>
⟨?_, fun h => ⟨_, h, erase_insert <| insert_ne_self.1 <| ne_of_mem_of_not_mem h hs⟩⟩)
rintro ⟨t, ht, rfl⟩
rwa [insert_erase (erase_ne_self.1 (ne_of_mem_of_not_mem ht hs).symm)]
theorem erase_mem_compression (hs : s ∈ 𝒜) : s.erase a ∈ 𝓓 a 𝒜 := by
simp_rw [mem_compression, erase_idem, and_self_iff]
refine (em _).imp_right fun h => ⟨h, ?_⟩
rwa [insert_erase (erase_ne_self.1 (ne_of_mem_of_not_mem hs h).symm)]
-- This is a special case of `erase_mem_compression` once we have `compression_idem`.
theorem erase_mem_compression_of_mem_compression : s ∈ 𝓓 a 𝒜 → s.erase a ∈ 𝓓 a 𝒜 := by
simp_rw [mem_compression, erase_idem]
refine Or.imp (fun h => ⟨h.2, h.2⟩) fun h => ?_
rwa [erase_eq_of_notMem (insert_ne_self.1 <| ne_of_mem_of_not_mem h.2 h.1)]
theorem mem_compression_of_insert_mem_compression (h : insert a s ∈ 𝓓 a 𝒜) : s ∈ 𝓓 a 𝒜 := by
by_cases ha : a ∈ s
· rwa [insert_eq_of_mem ha] at h
· rw [← erase_insert ha]
exact erase_mem_compression_of_mem_compression h
/-- Down-compressing a family is idempotent. -/
@[simp]
theorem compression_idem (a : α) (𝒜 : Finset (Finset α)) : 𝓓 a (𝓓 a 𝒜) = 𝓓 a 𝒜 := by
ext s
refine mem_compression.trans ⟨?_, fun h => Or.inl ⟨h, erase_mem_compression_of_mem_compression h⟩⟩
rintro (h | h)
· exact h.1
· cases h.1 (mem_compression_of_insert_mem_compression h.2)
/-- Down-compressing a family doesn't change its size. -/
@[simp]
theorem card_compression (a : α) (𝒜 : Finset (Finset α)) : #(𝓓 a 𝒜) = #𝒜 := by
rw [compression, card_disjUnion, filter_image,
card_image_of_injOn ((erase_injOn' _).mono fun s hs => _), ← card_union_of_disjoint]
· conv_rhs => rw [← filter_union_filter_neg_eq (fun s => (erase s a ∈ 𝒜)) 𝒜]
· exact disjoint_filter_filter_neg 𝒜 𝒜 (fun s => (erase s a ∈ 𝒜))
intro s hs
rw [mem_coe, mem_filter] at hs
exact not_imp_comm.1 erase_eq_of_notMem (ne_of_mem_of_not_mem hs.1 hs.2).symm
end Down |
.lake/packages/mathlib/Mathlib/Combinatorics/Hall/Finite.lean | import Mathlib.Data.Fintype.Basic
import Mathlib.Data.Fintype.Powerset
import Mathlib.Data.Set.Finite.Basic
/-!
# Hall's Marriage Theorem for finite index types
This module proves the basic form of Hall's theorem.
In contrast to the theorem described in `Combinatorics.Hall.Basic`, this
version requires that the indexed family `t : ι → Finset α` have `ι` be finite.
The `Combinatorics.Hall.Basic` module applies a compactness argument to this version
to remove the `Finite` constraint on `ι`.
The modules are split like this since the generalized statement
depends on the topology and category theory libraries, but the finite
case in this module has few dependencies.
A description of this formalization is in [Gusakov2021].
## Main statements
* `Finset.all_card_le_biUnion_card_iff_existsInjective'` is Hall's theorem with
a finite index set. This is elsewhere generalized to
`Finset.all_card_le_biUnion_card_iff_existsInjective`.
## Tags
Hall's Marriage Theorem, indexed families
-/
open Finset
universe u v
namespace HallMarriageTheorem
variable {ι : Type u} {α : Type v} [DecidableEq α] {t : ι → Finset α}
section Fintype
variable [Fintype ι]
theorem hall_cond_of_erase {x : ι} (a : α)
(ha : ∀ s : Finset ι, s.Nonempty → s ≠ univ → #s < #(s.biUnion t))
(s' : Finset { x' : ι | x' ≠ x }) : #s' ≤ #(s'.biUnion fun x' => (t x').erase a) := by
haveI := Classical.decEq ι
specialize ha (s'.image fun z => z.1)
rw [image_nonempty, Finset.card_image_of_injective s' Subtype.coe_injective] at ha
by_cases he : s'.Nonempty
· have ha' : #s' < #(s'.biUnion fun x => t x) := by
convert ha he fun h => by simpa [← h] using mem_univ x using 2
ext x
simp only [mem_image, mem_biUnion, SetCoe.exists, exists_and_right,
exists_eq_right]
rw [← erase_biUnion]
by_cases hb : a ∈ s'.biUnion fun x => t x
· rw [card_erase_of_mem hb]
exact Nat.le_sub_one_of_lt ha'
· rw [erase_eq_of_notMem hb]
exact Nat.le_of_lt ha'
· rw [nonempty_iff_ne_empty, not_not] at he
subst s'
simp
/-- First case of the inductive step: assuming that
`∀ (s : Finset ι), s.Nonempty → s ≠ univ → #s < #(s.biUnion t)`
and that the statement of **Hall's Marriage Theorem** is true for all
`ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`.
-/
theorem hall_hard_inductive_step_A {n : ℕ} (hn : Fintype.card ι = n + 1)
(ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t))
(ih :
∀ {ι' : Type u} [Fintype ι'] (t' : ι' → Finset α),
Fintype.card ι' ≤ n →
(∀ s' : Finset ι', #s' ≤ #(s'.biUnion t')) →
∃ f : ι' → α, Function.Injective f ∧ ∀ x, f x ∈ t' x)
(ha : ∀ s : Finset ι, s.Nonempty → s ≠ univ → #s < #(s.biUnion t)) :
∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by
haveI : Nonempty ι := Fintype.card_pos_iff.mp (hn.symm ▸ Nat.succ_pos _)
haveI := Classical.decEq ι
-- Choose an arbitrary element `x : ι` and `y : t x`.
let x := Classical.arbitrary ι
have tx_ne : (t x).Nonempty := by
rw [← Finset.card_pos]
calc
0 < 1 := Nat.one_pos
_ ≤ #(.biUnion {x} t) := ht {x}
_ = (t x).card := by rw [Finset.singleton_biUnion]
choose y hy using tx_ne
-- Restrict to everything except `x` and `y`.
let ι' := { x' : ι | x' ≠ x }
let t' : ι' → Finset α := fun x' => (t x').erase y
have card_ι' : Fintype.card ι' = n :=
calc
Fintype.card ι' = Fintype.card ι - 1 := Set.card_ne_eq _
_ = n := by rw [hn, Nat.add_succ_sub_one, add_zero]
rcases ih t' card_ι'.le (hall_cond_of_erase y ha) with ⟨f', hfinj, hfr⟩
-- Extend the resulting function.
refine ⟨fun z => if h : z = x then y else f' ⟨z, h⟩, ?_, ?_⟩
· rintro z₁ z₂
have key : ∀ {x}, y ≠ f' x := by
intro x h
simpa [t', ← h] using hfr x
by_cases h₁ : z₁ = x <;> by_cases h₂ : z₂ = x <;>
simp [h₁, h₂, hfinj.eq_iff, key, key.symm]
· intro z
simp only
split_ifs with hz
· rwa [hz]
· specialize hfr ⟨z, hz⟩
rw [mem_erase] at hfr
exact hfr.2
theorem hall_cond_of_restrict {ι : Type u} {t : ι → Finset α} {s : Finset ι}
(ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t)) (s' : Finset (s : Set ι)) :
#s' ≤ #(s'.biUnion fun a' => t a') := by
classical
rw [← card_image_of_injective s' Subtype.coe_injective]
convert ht (s'.image fun z => z.1) using 1
apply congr_arg
ext y
simp
theorem hall_cond_of_compl {ι : Type u} {t : ι → Finset α} {s : Finset ι}
(hus : #s = #(s.biUnion t)) (ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t))
(s' : Finset (sᶜ : Set ι)) : #s' ≤ #(s'.biUnion fun x' => t x' \ s.biUnion t) := by
haveI := Classical.decEq ι
have disj : Disjoint s (s'.image fun z => z.1) := by
simp only [disjoint_left, not_exists, mem_image, SetCoe.exists, exists_and_right,
exists_eq_right]
intro x hx hc _
exact absurd hx hc
have : #s' = #(s ∪ s'.image fun z => z.1) - #s := by
simp [disj, card_image_of_injective _ Subtype.coe_injective, Nat.add_sub_cancel_left]
rw [this, hus]
refine (Nat.sub_le_sub_right (ht _) _).trans ?_
rw [← card_sdiff_of_subset]
· gcongr
intro t
simp only [mem_biUnion, mem_sdiff, not_exists, mem_image, and_imp, mem_union,
exists_imp]
rintro x (hx | ⟨x', hx', rfl⟩) rat hs
· exact False.elim <| (hs x) <| And.intro hx rat
· use x', hx', rat, hs
· apply biUnion_subset_biUnion_of_subset_left
apply subset_union_left
/-- Second case of the inductive step: assuming that
`∃ (s : Finset ι), s ≠ univ → #s = #(s.biUnion t)`
and that the statement of **Hall's Marriage Theorem** is true for all
`ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`.
-/
theorem hall_hard_inductive_step_B {n : ℕ} (hn : Fintype.card ι = n + 1)
(ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t))
(ih :
∀ {ι' : Type u} [Fintype ι'] (t' : ι' → Finset α),
Fintype.card ι' ≤ n →
(∀ s' : Finset ι', #s' ≤ #(s'.biUnion t')) →
∃ f : ι' → α, Function.Injective f ∧ ∀ x, f x ∈ t' x)
(s : Finset ι) (hs : s.Nonempty) (hns : s ≠ univ) (hus : #s = #(s.biUnion t)) :
∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by
haveI := Classical.decEq ι
-- Restrict to `s`
rw [Nat.add_one] at hn
have card_ι'_le : Fintype.card s ≤ n := by
apply Nat.le_of_lt_succ
calc
Fintype.card s = #s := Fintype.card_coe _
_ < Fintype.card ι := (card_lt_iff_ne_univ _).mpr hns
_ = n.succ := hn
let t' : s → Finset α := fun x' => t x'
rcases ih t' card_ι'_le (hall_cond_of_restrict ht) with ⟨f', hf', hsf'⟩
-- Restrict to `sᶜ` in the domain and `(s.biUnion t)ᶜ` in the codomain.
set ι'' := (s : Set ι)ᶜ
let t'' : ι'' → Finset α := fun a'' => t a'' \ s.biUnion t
have card_ι''_le : Fintype.card ι'' ≤ n := by
simp_rw [ι'', ← Nat.lt_succ_iff, ← hn, ← Finset.coe_compl, coe_sort_coe]
rwa [Fintype.card_coe, card_compl_lt_iff_nonempty]
rcases ih t'' card_ι''_le (hall_cond_of_compl hus ht) with ⟨f'', hf'', hsf''⟩
-- Put them together
have f''_notMem_biUnion : ∀ (x'') (hx'' : x'' ∉ s), f'' ⟨x'', hx''⟩ ∉ s.biUnion t := by
intro x'' hx''
have h := hsf'' ⟨x'', hx''⟩
rw [mem_sdiff] at h
exact h.2
have im_disj :
∀ (x' x'' : ι) (hx' : x' ∈ s) (hx'' : x'' ∉ s), f' ⟨x', hx'⟩ ≠ f'' ⟨x'', hx''⟩ := by
grind
refine ⟨fun x => if h : x ∈ s then f' ⟨x, h⟩ else f'' ⟨x, h⟩, ?_, ?_⟩
· refine hf'.dite _ hf'' (@fun x x' => im_disj x x' _ _)
· intro x
simp only
split_ifs with h
· exact hsf' ⟨x, h⟩
· exact sdiff_subset (hsf'' ⟨x, h⟩)
end Fintype
variable [Finite ι]
/-- Here we combine the two inductive steps into a full strong induction proof,
completing the proof the harder direction of **Hall's Marriage Theorem**.
-/
theorem hall_hard_inductive (ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t)) :
∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by
cases nonempty_fintype ι
generalize hn : Fintype.card ι = m
induction m using Nat.strongRecOn generalizing ι with | ind n ih => _
rcases n with (_ | n)
· rw [Fintype.card_eq_zero_iff] at hn
exact ⟨isEmptyElim, isEmptyElim, isEmptyElim⟩
· have ih' : ∀ (ι' : Type u) [Fintype ι'] (t' : ι' → Finset α), Fintype.card ι' ≤ n →
(∀ s' : Finset ι', #s' ≤ #(s'.biUnion t')) →
∃ f : ι' → α, Function.Injective f ∧ ∀ x, f x ∈ t' x := by
intro ι' _ _ hι' ht'
exact ih _ (Nat.lt_succ_of_le hι') ht' _ rfl
by_cases! h : ∀ s : Finset ι, s.Nonempty → s ≠ univ → #s < #(s.biUnion t)
· refine hall_hard_inductive_step_A hn ht (@fun ι' => ih' ι') h
· rcases h with ⟨s, sne, snu, sle⟩
exact hall_hard_inductive_step_B hn ht (@fun ι' => ih' ι')
s sne snu (Nat.le_antisymm (ht _) sle)
end HallMarriageTheorem
/-- This is the version of **Hall's Marriage Theorem** in terms of indexed
families of finite sets `t : ι → Finset α` with `ι` finite.
It states that there is a set of distinct representatives if and only
if every union of `k` of the sets has at least `k` elements.
See `Finset.all_card_le_biUnion_card_iff_exists_injective` for a version
where the `Finite ι` constraint is removed.
-/
theorem Finset.all_card_le_biUnion_card_iff_existsInjective' {ι α : Type*} [Finite ι]
[DecidableEq α] (t : ι → Finset α) :
(∀ s : Finset ι, #s ≤ #(s.biUnion t)) ↔
∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by
constructor
· exact HallMarriageTheorem.hall_hard_inductive
· rintro ⟨f, hf₁, hf₂⟩ s
rw [← card_image_of_injective s hf₁]
apply card_le_card
intro
rw [mem_image, mem_biUnion]
rintro ⟨x, hx, rfl⟩
exact ⟨x, hx, hf₂ x⟩ |
.lake/packages/mathlib/Mathlib/Combinatorics/Hall/Basic.lean | import Mathlib.Combinatorics.Hall.Finite
import Mathlib.CategoryTheory.CofilteredSystem
import Mathlib.Data.Rel
/-!
# Hall's Marriage Theorem
Given a list of finite subsets $X_1, X_2, \dots, X_n$ of some given set
$S$, P. Hall in [Hall1935] gave a necessary and sufficient condition for
there to be a list of distinct elements $x_1, x_2, \dots, x_n$ with
$x_i\in X_i$ for each $i$: it is when for each $k$, the union of every
$k$ of these subsets has at least $k$ elements.
Rather than a list of finite subsets, one may consider indexed families
`t : ι → Finset α` of finite subsets with `ι` a `Fintype`, and then the list
of distinct representatives is given by an injective function `f : ι → α`
such that `∀ i, f i ∈ t i`, called a *matching*.
This version is formalized as `Finset.all_card_le_biUnion_card_iff_exists_injective'`
in a separate module.
The theorem can be generalized to remove the constraint that `ι` be a `Fintype`.
As observed in [Halpern1966], one may use the constrained version of the theorem
in a compactness argument to remove this constraint.
The formulation of compactness we use is that inverse limits of nonempty finite sets
are nonempty (`nonempty_sections_of_finite_inverse_system`), which uses the
Tychonoff theorem.
The core of this module is constructing the inverse system: for every finite subset `ι'` of
`ι`, we can consider the matchings on the restriction of the indexed family `t` to `ι'`.
## Main statements
* `Finset.all_card_le_biUnion_card_iff_exists_injective` is in terms of `t : ι → Finset α`.
* `Fintype.all_card_le_rel_image_card_iff_exists_injective` is in terms of a relation
`r : α → β → Prop` such that `R.image {a}` is a finite set for all `a : α`.
* `Fintype.all_card_le_filter_rel_iff_exists_injective` is in terms of a relation
`r : α → β → Prop` on finite types, with the Hall condition given in terms of
`finset.univ.filter`.
## Tags
Hall's Marriage Theorem, indexed families
-/
open Finset Function CategoryTheory
open scoped SetRel
universe u v
/-- The set of matchings for `t` when restricted to a `Finset` of `ι`. -/
def hallMatchingsOn {ι : Type u} {α : Type v} (t : ι → Finset α) (ι' : Finset ι) :=
{ f : ι' → α | Function.Injective f ∧ ∀ (x : {x // x ∈ ι'}), f x ∈ t x }
/-- Given a matching on a finset, construct the restriction of that matching to a subset. -/
def hallMatchingsOn.restrict {ι : Type u} {α : Type v} (t : ι → Finset α) {ι' ι'' : Finset ι}
(h : ι' ⊆ ι'') (f : hallMatchingsOn t ι'') : hallMatchingsOn t ι' := by
refine ⟨fun i => f.val ⟨i, h i.property⟩, ?_⟩
obtain ⟨hinj, hc⟩ := f.property
refine ⟨?_, fun i => hc ⟨i, h i.property⟩⟩
rintro ⟨i, hi⟩ ⟨j, hj⟩ hh
simpa only [Subtype.mk_eq_mk] using hinj hh
/-- When the Hall condition is satisfied, the set of matchings on a finite set is nonempty.
This is where `Finset.all_card_le_biUnion_card_iff_existsInjective'` comes into the argument. -/
theorem hallMatchingsOn.nonempty {ι : Type u} {α : Type v} [DecidableEq α] (t : ι → Finset α)
(h : ∀ s : Finset ι, #s ≤ #(s.biUnion t)) (ι' : Finset ι) :
Nonempty (hallMatchingsOn t ι') := by
classical
refine ⟨Classical.indefiniteDescription _ ?_⟩
apply (all_card_le_biUnion_card_iff_existsInjective' fun i : ι' => t i).mp
intro s'
convert h (s'.image (↑)) using 1
· simp only [card_image_of_injective s' Subtype.coe_injective]
· rw [image_biUnion]
/-- This is the `hallMatchingsOn` sets assembled into a directed system.
-/
def hallMatchingsFunctor {ι : Type u} {α : Type v} (t : ι → Finset α) :
(Finset ι)ᵒᵖ ⥤ Type max u v where
obj ι' := hallMatchingsOn t ι'.unop
map {_ _} g f := hallMatchingsOn.restrict t (CategoryTheory.leOfHom g.unop) f
instance hallMatchingsOn.finite {ι : Type u} {α : Type v} (t : ι → Finset α) (ι' : Finset ι) :
Finite (hallMatchingsOn t ι') := by
classical
rw [hallMatchingsOn]
let g : hallMatchingsOn t ι' → ι' → ι'.biUnion t := by
rintro f i
refine ⟨f.val i, ?_⟩
rw [mem_biUnion]
exact ⟨i, i.property, f.property.2 i⟩
apply Finite.of_injective g
intro f f' h
ext a
rw [funext_iff] at h
simpa [g] using h a
/-- This is the version of **Hall's Marriage Theorem** in terms of indexed
families of finite sets `t : ι → Finset α`. It states that there is a
set of distinct representatives if and only if every union of `k` of the
sets has at least `k` elements.
Recall that `s.biUnion t` is the union of all the sets `t i` for `i ∈ s`.
This theorem is bootstrapped from `Finset.all_card_le_biUnion_card_iff_exists_injective'`,
which has the additional constraint that `ι` is a `Fintype`.
-/
theorem Finset.all_card_le_biUnion_card_iff_exists_injective {ι : Type u} {α : Type v}
[DecidableEq α] (t : ι → Finset α) :
(∀ s : Finset ι, #s ≤ #(s.biUnion t)) ↔
∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by
constructor
· intro h
-- Set up the functor
haveI : ∀ ι' : (Finset ι)ᵒᵖ, Nonempty ((hallMatchingsFunctor t).obj ι') := fun ι' =>
hallMatchingsOn.nonempty t h ι'.unop
classical
haveI : ∀ ι' : (Finset ι)ᵒᵖ, Finite ((hallMatchingsFunctor t).obj ι') := by
intro ι'
rw [hallMatchingsFunctor]
infer_instance
-- Apply the compactness argument
obtain ⟨u, hu⟩ := nonempty_sections_of_finite_inverse_system (hallMatchingsFunctor t)
-- Interpret the resulting section of the inverse limit
refine ⟨?_, ?_, ?_⟩
·-- Build the matching function from the section
exact fun i =>
(u (Opposite.op ({i} : Finset ι))).val ⟨i, by simp only [mem_singleton]⟩
· -- Show that it is injective
intro i i'
have subi : ({i} : Finset ι) ⊆ {i, i'} := by simp
have subi' : ({i'} : Finset ι) ⊆ {i, i'} := by simp
rw [← Finset.le_iff_subset] at subi subi'
simp only
rw [← hu (CategoryTheory.homOfLE subi).op, ← hu (CategoryTheory.homOfLE subi').op]
let uii' := u (Opposite.op ({i, i'} : Finset ι))
exact fun h => Subtype.mk_eq_mk.mp (uii'.property.1 h)
· -- Show that it maps each index to the corresponding finite set
intro i
apply (u (Opposite.op ({i} : Finset ι))).property.2
· -- The reverse direction is a straightforward cardinality argument
rintro ⟨f, hf₁, hf₂⟩ s
rw [← Finset.card_image_of_injective s hf₁]
apply Finset.card_le_card
grind
/-- Given a relation such that the image of every singleton set is finite, then the image of every
finite set is finite. -/
instance {α : Type u} {β : Type v} [DecidableEq β] (R : SetRel α β)
[∀ a : α, Fintype (R.image {a})] (A : Finset α) : Fintype (R.image A) := by
have h : R.image A = (A.biUnion fun a => (R.image {a}).toFinset : Set β) := by
ext
simp [SetRel.image]
rw [h]
apply FinsetCoe.fintype
/-- This is a version of **Hall's Marriage Theorem** in terms of a relation
between types `α` and `β` such that `α` is finite and the image of
each `x : α` is finite (it suffices for `β` to be finite; see
`Fintype.all_card_le_filter_rel_iff_exists_injective`). There is
a transversal of the relation (an injective function `α → β` whose graph is
a subrelation of the relation) iff every subset of
`k` terms of `α` is related to at least `k` terms of `β`.
Note: if `[Fintype β]`, then there exist instances for `[∀ (a : α), Fintype (R.image {a})]`.
-/
theorem Fintype.all_card_le_rel_image_card_iff_exists_injective {α : Type u} {β : Type v}
[DecidableEq β] (R : SetRel α β) [∀ a : α, Fintype (R.image {a})] :
(∀ A : Finset α, #A ≤ Fintype.card (R.image A)) ↔
∃ f : α → β, Function.Injective f ∧ ∀ x, x ~[R] f x := by
let r' a := (R.image {a}).toFinset
have h : ∀ A : Finset α, Fintype.card (R.image A) = #(A.biUnion r') := by
intro A
rw [← Set.toFinset_card]
apply congr_arg
ext b
simp [r', SetRel.image]
have h' : ∀ (f : α → β) (x), x ~[R] f x ↔ f x ∈ r' x := by simp [r', SetRel.image]
simp only [h, h']
apply Finset.all_card_le_biUnion_card_iff_exists_injective
/-- This is a version of **Hall's Marriage Theorem** in terms of a relation to a finite type.
There is a transversal of the relation (an injective function `α → β` whose graph is a subrelation
of the relation) iff every subset of `k` terms of `α` is related to at least `k` terms of `β`.
It is like `Fintype.all_card_le_rel_image_card_iff_exists_injective` but uses `Finset.filter`
rather than `Rel.image`.
-/
theorem Fintype.all_card_le_filter_rel_iff_exists_injective {α : Type u} {β : Type v} [Fintype β]
(r : α → β → Prop) [DecidableRel r] :
(∀ A : Finset α, #A ≤ #{b | ∃ a ∈ A, r a b}) ↔ ∃ f : α → β, Injective f ∧ ∀ x, r x (f x) := by
haveI := Classical.decEq β
let r' a : Finset β := {b | r a b}
have h : ∀ A : Finset α, ({b | ∃ a ∈ A, r a b} : Finset _) = A.biUnion r' := by
intro A
ext b
simp [r']
have h' : ∀ (f : α → β) (x), r x (f x) ↔ f x ∈ r' x := by simp [r']
simp_rw [h, h']
apply Finset.all_card_le_biUnion_card_iff_exists_injective |
.lake/packages/mathlib/Mathlib/Combinatorics/Extremal/RuzsaSzemeredi.lean | import Mathlib.Combinatorics.Additive.AP.Three.Behrend
import Mathlib.Combinatorics.SimpleGraph.Triangle.Tripartite
import Mathlib.Tactic.Rify
/-!
# The Ruzsa-Szemerédi problem
This file proves the lower bound of the Ruzsa-Szemerédi problem. The problem is to find the maximum
number of edges that a graph on `n` vertices can have if all edges belong to at most one triangle.
The lower bound comes from turning the big 3AP-free set from Behrend's construction into a graph
that has the property that every triangle gives a (possibly trivial) arithmetic progression on the
original set.
## Main declarations
* `ruzsaSzemerediNumberNat n`: Maximum number of edges a graph on `n` vertices can have such that
each edge belongs to exactly one triangle.
* `ruzsaSzemerediNumberNat_asymptotic_lower_bound`: There exists a graph with `n` vertices and
`Ω((n ^ 2 * exp (-4 * √(log n))))` edges such that each edge belongs to exactly one triangle.
-/
open Finset Nat Real SimpleGraph Sum3 SimpleGraph.TripartiteFromTriangles
open Fintype (card)
open scoped Pointwise
variable {α β : Type*}
/-! ### The Ruzsa-Szemerédi number -/
section ruzsaSzemerediNumber
variable [DecidableEq α] [DecidableEq β] [Fintype α] [Fintype β] {G H : SimpleGraph α}
variable (α) in
/-- The **Ruzsa-Szemerédi number** of a fintype is the maximum number of edges a locally linear
graph on that type can have.
In other words, `ruzsaSzemerediNumber α` is the maximum number of edges a graph on `α` can have such
that each edge belongs to exactly one triangle. -/
noncomputable def ruzsaSzemerediNumber : ℕ := by
classical
exact Nat.findGreatest (fun m ↦ ∃ (G : SimpleGraph α) (_ : DecidableRel G.Adj),
#(G.cliqueFinset 3) = m ∧ G.LocallyLinear) ((card α).choose 3)
open scoped Classical in
lemma ruzsaSzemerediNumber_le : ruzsaSzemerediNumber α ≤ (card α).choose 3 := Nat.findGreatest_le _
lemma ruzsaSzemerediNumber_spec :
∃ (G : SimpleGraph α) (_ : DecidableRel G.Adj),
#(G.cliqueFinset 3) = ruzsaSzemerediNumber α ∧ G.LocallyLinear := by
classical
exact @Nat.findGreatest_spec _
(fun m ↦ ∃ (G : SimpleGraph α) (_ : DecidableRel G.Adj),
#(G.cliqueFinset 3) = m ∧ G.LocallyLinear) _ _ (Nat.zero_le _)
⟨⊥, inferInstance, by simp, locallyLinear_bot⟩
variable {m n : ℕ}
lemma SimpleGraph.LocallyLinear.le_ruzsaSzemerediNumber [DecidableRel G.Adj]
(hG : G.LocallyLinear) : #(G.cliqueFinset 3) ≤ ruzsaSzemerediNumber α := by
classical
exact le_findGreatest card_cliqueFinset_le ⟨G, inferInstance, by congr, hG⟩
lemma ruzsaSzemerediNumber_mono (f : α ↪ β) : ruzsaSzemerediNumber α ≤ ruzsaSzemerediNumber β := by
classical
refine findGreatest_mono ?_ (choose_mono _ <| Fintype.card_le_of_embedding f)
rintro n ⟨G, _, rfl, hG⟩
refine ⟨G.map f, inferInstance, ?_, hG.map _⟩
rw [← card_map ⟨map f, Finset.map_injective _⟩, ← cliqueFinset_map G f]
decide
lemma ruzsaSzemerediNumber_congr (e : α ≃ β) : ruzsaSzemerediNumber α = ruzsaSzemerediNumber β :=
(ruzsaSzemerediNumber_mono (e : α ↪ β)).antisymm <| ruzsaSzemerediNumber_mono e.symm
/-- The `n`-th **Ruzsa-Szemerédi number** is the maximum number of edges a locally linear graph on
`n` vertices can have.
In other words, `ruzsaSzemerediNumberNat n` is the maximum number of edges a graph on `n` vertices
can have such that each edge belongs to exactly one triangle. -/
noncomputable def ruzsaSzemerediNumberNat (n : ℕ) : ℕ := ruzsaSzemerediNumber (Fin n)
@[simp]
lemma ruzsaSzemerediNumberNat_card : ruzsaSzemerediNumberNat (card α) = ruzsaSzemerediNumber α :=
ruzsaSzemerediNumber_congr (Fintype.equivFin _).symm
@[gcongr]
lemma ruzsaSzemerediNumberNat_mono : Monotone ruzsaSzemerediNumberNat := fun _m _n h =>
ruzsaSzemerediNumber_mono (Fin.castLEEmb h)
lemma ruzsaSzemerediNumberNat_le : ruzsaSzemerediNumberNat n ≤ n.choose 3 :=
ruzsaSzemerediNumber_le.trans_eq <| by rw [Fintype.card_fin]
@[simp] lemma ruzsaSzemerediNumberNat_zero : ruzsaSzemerediNumberNat 0 = 0 :=
le_zero_iff.1 ruzsaSzemerediNumberNat_le
@[simp] lemma ruzsaSzemerediNumberNat_one : ruzsaSzemerediNumberNat 1 = 0 :=
le_zero_iff.1 ruzsaSzemerediNumberNat_le
@[simp] lemma ruzsaSzemerediNumberNat_two : ruzsaSzemerediNumberNat 2 = 0 :=
le_zero_iff.1 ruzsaSzemerediNumberNat_le
end ruzsaSzemerediNumber
/-! ### The Ruzsa-Szemerédi construction -/
section RuzsaSzemeredi
variable [Fintype α] [CommRing α] {s : Finset α} {x : α × α × α}
/-- The triangle indices for the Ruzsa-Szemerédi construction. -/
private def triangleIndices (s : Finset α) : Finset (α × α × α) :=
(univ ×ˢ s).map
⟨fun xa ↦ (xa.1, xa.1 + xa.2, xa.1 + 2 * xa.2), by
rintro ⟨x, a⟩ ⟨y, b⟩ h
simp only [Prod.ext_iff] at h
obtain rfl := h.1
obtain rfl := add_right_injective _ h.2.1
rfl⟩
@[simp]
private lemma mem_triangleIndices :
x ∈ triangleIndices s ↔ ∃ y, ∃ a ∈ s, (y, y + a, y + 2 * a) = x := by simp [triangleIndices]
@[simp]
private lemma card_triangleIndices : #(triangleIndices s) = card α * #s := by
simp [triangleIndices]
private lemma noAccidental (hs : ThreeAPFree (s : Set α)) :
NoAccidental (triangleIndices s : Finset (α × α × α)) where
eq_or_eq_or_eq := by
simp only [mem_triangleIndices, Prod.mk_inj, forall_exists_index, and_imp]
rintro _ _ _ _ _ _ d a ha rfl rfl rfl b' b hb rfl rfl h₁ d' c hc rfl h₂ rfl
have : a + c = b + b := by linear_combination h₁.symm - h₂.symm
obtain rfl := hs ha hb hc this
simp_all
variable [Fact <| IsUnit (2 : α)]
private instance : ExplicitDisjoint (triangleIndices s : Finset (α × α × α)) where
inj₀ := by
simp only [mem_triangleIndices, Prod.mk_inj, forall_exists_index, and_imp]
rintro _ _ _ _ x a ha rfl rfl rfl y b hb rfl h₁ h₂
linear_combination 2 * h₁.symm - h₂.symm
inj₁ := by
simp only [mem_triangleIndices, Prod.mk_inj, forall_exists_index, and_imp]
rintro _ _ _ _ x a ha rfl rfl rfl y b hb rfl rfl h
simpa [(Fact.out (p := IsUnit (2 : α))).mul_right_inj, eq_comm] using h
inj₂ := by
simp only [mem_triangleIndices, Prod.mk_inj, forall_exists_index, and_imp]
rintro _ _ _ _ x a ha rfl rfl rfl y b hb rfl h rfl
simpa [(Fact.out (p := IsUnit (2 : α))).mul_right_inj, eq_comm] using h
private lemma locallyLinear (hs : ThreeAPFree (s : Set α)) :
(graph <| triangleIndices s).LocallyLinear :=
haveI := noAccidental hs; TripartiteFromTriangles.locallyLinear _
private lemma card_edgeFinset (hs : ThreeAPFree (s : Set α)) [DecidableEq α] :
#(graph <| triangleIndices s).edgeFinset = 3 * card α * #s := by
haveI := noAccidental hs
rw [(locallyLinear hs).card_edgeFinset, card_triangles, card_triangleIndices, mul_assoc]
end RuzsaSzemeredi
variable (α) [Fintype α] [DecidableEq α] [CommRing α] [Fact <| IsUnit (2 : α)]
lemma addRothNumber_le_ruzsaSzemerediNumber :
card α * addRothNumber (univ : Finset α) ≤ ruzsaSzemerediNumber (Sum α (Sum α α)) := by
obtain ⟨s, -, hscard, hs⟩ := addRothNumber_spec (univ : Finset α)
haveI := noAccidental hs
rw [← hscard, ← card_triangleIndices, ← card_triangles]
exact (locallyLinear hs).le_ruzsaSzemerediNumber
lemma rothNumberNat_le_ruzsaSzemerediNumberNat (n : ℕ) :
(2 * n + 1) * rothNumberNat n ≤ ruzsaSzemerediNumberNat (6 * n + 3) := by
let α := Fin (2 * n + 1)
have : Nat.Coprime 2 (2 * n + 1) := by simp
haveI : Fact (IsUnit (2 : Fin (2 * n + 1))) := ⟨by simpa using (ZMod.unitOfCoprime 2 this).isUnit⟩
open scoped Fin.CommRing in
calc
(2 * n + 1) * rothNumberNat n
_ = Fintype.card α * addRothNumber (Iio (n : α)) := by
rw [Fin.addRothNumber_eq_rothNumberNat le_rfl, Fintype.card_fin]
_ ≤ Fintype.card α * addRothNumber (univ : Finset α) := by
gcongr; exact subset_univ _
_ ≤ ruzsaSzemerediNumber (Sum α (Sum α α)) := addRothNumber_le_ruzsaSzemerediNumber _
_ = ruzsaSzemerediNumberNat (6 * n + 3) := by
simp_rw [← ruzsaSzemerediNumberNat_card, Fintype.card_sum, α, Fintype.card_fin]
ring_nf
/-- Lower bound on the **Ruzsa-Szemerédi problem** in terms of 3AP-free sets.
If there exists a 3AP-free subset of `[1, ..., (n - 3) / 6]` of size `m`, then there exists a graph
with `n` vertices and `(n / 3 - 2) * m` edges such that each edge belongs to exactly one triangle.
-/
theorem rothNumberNat_le_ruzsaSzemerediNumberNat' :
∀ n : ℕ, (n / 3 - 2 : ℝ) * rothNumberNat ((n - 3) / 6) ≤ ruzsaSzemerediNumberNat n
| 0 => by simp
| 1 => by simp
| 2 => by simp
| n + 3 => by
calc
_ ≤ (↑(2 * (n / 6) + 1) : ℝ) * rothNumberNat (n / 6) :=
mul_le_mul_of_nonneg_right ?_ (Nat.cast_nonneg _)
_ ≤ (ruzsaSzemerediNumberNat (6 * (n / 6) + 3) : ℝ) := ?_
_ ≤ _ := by grw [Nat.mul_div_le]
· norm_num
rw [← div_add_one (three_ne_zero' ℝ), ← le_sub_iff_add_le, div_le_iff₀ (zero_lt_three' ℝ),
add_assoc, add_sub_assoc, add_mul, mul_right_comm]
norm_num
norm_cast
rw [← mul_add_one]
exact (Nat.lt_mul_div_succ _ <| by simp).le
· norm_cast
exact rothNumberNat_le_ruzsaSzemerediNumberNat _
/-- Explicit lower bound on the **Ruzsa-Szemerédi problem**.
There exists a graph with `n` vertices and
`(n / 3 - 2) * (n - 3) / 6 * exp (-4 * √(log ((n - 3) / 6)))` edges such that each edge belongs
to exactly one triangle. -/
theorem ruzsaSzemerediNumberNat_lower_bound (n : ℕ) :
(n / 3 - 2 : ℝ) * ↑((n - 3) / 6) * exp (-4 * √(log ↑((n - 3) / 6))) ≤
ruzsaSzemerediNumberNat n := by
rw [mul_assoc]
obtain hn | hn := le_total (n / 3 - 2 : ℝ) 0
· exact (mul_nonpos_of_nonpos_of_nonneg hn <| by positivity).trans (Nat.cast_nonneg _)
exact
(mul_le_mul_of_nonneg_left Behrend.roth_lower_bound hn).trans
(rothNumberNat_le_ruzsaSzemerediNumberNat' _)
open Asymptotics Filter
/-- Asymptotic lower bound on the **Ruzsa-Szemerédi problem**.
There exists a graph with `n` vertices and `Ω((n ^ 2 * exp (-4 * √(log n))))` edges such that
each edge belongs to exactly one triangle. -/
theorem ruzsaSzemerediNumberNat_asymptotic_lower_bound :
(fun n ↦ n ^ 2 * exp (-4 * √(log n)) : ℕ → ℝ) =O[atTop]
fun n ↦ (ruzsaSzemerediNumberNat n : ℝ) := by
trans fun n ↦ (n / 3 - 2) * ↑((n - 3) / 6) * exp (-4 * √(log ↑((n - 3) / 6)))
· simp_rw [sq]
refine (IsBigO.mul ?_ ?_).mul ?_
· trans fun n ↦ n / 3
· simp_rw [div_eq_inv_mul]
exact (isBigO_refl ..).const_mul_right (by simp)
refine IsLittleO.right_isBigO_sub ?_
simpa [div_eq_inv_mul, Function.comp_def] using
.atTop_of_const_mul₀ zero_lt_three (by simp [tendsto_natCast_atTop_atTop])
· rw [IsBigO_def]
refine ⟨12, ?_⟩
simp only [IsBigOWith, norm_natCast, eventually_atTop]
exact ⟨15, fun x hx ↦ by norm_cast; cutsat⟩
· rw [isBigO_exp_comp_exp_comp]
refine ⟨0, ?_⟩
simp only [neg_mul, eventually_map, Pi.sub_apply, sub_neg_eq_add, neg_add_le_iff_le_add,
add_zero, ofNat_pos, mul_le_mul_iff_right₀, eventually_atTop]
refine ⟨9, fun x hx ↦ ?_⟩
gcongr
· simp
cutsat
· cutsat
· refine .of_norm_eventuallyLE ?_
filter_upwards [eventually_ge_atTop 6] with n hn
have : (0 : ℝ) ≤ n / 3 - 2 := by rify at hn; linarith
simpa [neg_mul, abs_mul, abs_of_nonneg this] using ruzsaSzemerediNumberNat_lower_bound n |
.lake/packages/mathlib/Mathlib/Combinatorics/Derangements/Finite.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Combinatorics.Derangements.Basic
import Mathlib.Data.Fintype.BigOperators
import Mathlib.Tactic.Ring
/-!
# Derangements on fintypes
This file contains lemmas that describe the cardinality of `derangements α` when `α` is a fintype.
## Main definitions
* `card_derangements_invariant`: A lemma stating that the number of derangements on a type `α`
depends only on the cardinality of `α`.
* `numDerangements n`: The number of derangements on an n-element set, defined in a computation-
friendly way.
* `card_derangements_eq_numDerangements`: Proof that `numDerangements` really does compute the
number of derangements.
* `numDerangements_sum`: A lemma giving an expression for `numDerangements n` in terms of
factorials.
-/
open derangements Equiv Fintype
variable {α : Type*} [DecidableEq α] [Fintype α]
instance : DecidablePred (derangements α) := fun _ => Fintype.decidableForallFintype
instance : Fintype (derangements α) :=
inferInstanceAs <| Fintype { f : Perm α | ∀ x : α, f x ≠ x }
theorem card_derangements_invariant {α β : Type*} [Fintype α] [DecidableEq α] [Fintype β]
[DecidableEq β] (h : card α = card β) : card (derangements α) = card (derangements β) :=
Fintype.card_congr (Equiv.derangementsCongr <| equivOfCardEq h)
theorem card_derangements_fin_add_two (n : ℕ) :
card (derangements (Fin (n + 2))) =
(n + 1) * card (derangements (Fin n)) + (n + 1) * card (derangements (Fin (n + 1))) := by
-- get some basic results about the size of Fin (n+1) plus or minus an element
have h1 : ∀ a : Fin (n + 1), card ({a}ᶜ : Set (Fin (n + 1))) = card (Fin n) := by
intro a
simp only
[card_ofFinset (s := Finset.filter (fun x => x ∈ ({a}ᶜ : Set (Fin (n + 1)))) Finset.univ),
Set.mem_compl_singleton_iff, Finset.filter_ne' _ a,
Finset.card_erase_of_mem (Finset.mem_univ a), Finset.card_fin, add_tsub_cancel_right,
card_fin]
have h2 : card (Fin (n + 2)) = card (Option (Fin (n + 1))) := by simp only [card_fin, card_option]
-- rewrite the LHS and substitute in our fintype-level equivalence
simp only [card_derangements_invariant h2,
card_congr
(@derangementsRecursionEquiv (Fin (n + 1))
_),-- push the cardinality through the Σ and ⊕ so that we can use `card_n`
card_sigma,
card_sum, card_derangements_invariant (h1 _), Finset.sum_const, nsmul_eq_mul, Finset.card_fin,
mul_add, Nat.cast_id]
/-- The number of derangements of an `n`-element set. -/
def numDerangements : ℕ → ℕ
| 0 => 1
| 1 => 0
| n + 2 => (n + 1) * (numDerangements n + numDerangements (n + 1))
@[simp]
theorem numDerangements_zero : numDerangements 0 = 1 :=
rfl
@[simp]
theorem numDerangements_one : numDerangements 1 = 0 :=
rfl
theorem numDerangements_add_two (n : ℕ) :
numDerangements (n + 2) = (n + 1) * (numDerangements n + numDerangements (n + 1)) :=
rfl
theorem numDerangements_succ (n : ℕ) :
(numDerangements (n + 1) : ℤ) = (n + 1) * (numDerangements n : ℤ) - (-1) ^ n := by
induction n with
| zero => rfl
| succ n hn =>
simp only [numDerangements_add_two, hn, pow_succ, Int.natCast_mul, Int.natCast_add]
ring
theorem card_derangements_fin_eq_numDerangements {n : ℕ} :
card (derangements (Fin n)) = numDerangements n := by
induction n using Nat.strongRecOn with | ind n hyp => _
rcases n with _ | _ | n
-- knock out cases 0 and 1
· rfl
· rfl
-- now we have n ≥ 2. rewrite everything in terms of card_derangements, so that we can use
-- `card_derangements_fin_add_two`
rw [numDerangements_add_two, card_derangements_fin_add_two, mul_add, hyp, hyp] <;> omega
theorem card_derangements_eq_numDerangements (α : Type*) [Fintype α] [DecidableEq α] :
card (derangements α) = numDerangements (card α) := by
rw [← card_derangements_invariant (card_fin _)]
exact card_derangements_fin_eq_numDerangements
theorem numDerangements_sum (n : ℕ) :
(numDerangements n : ℤ) =
∑ k ∈ Finset.range (n + 1), (-1 : ℤ) ^ k * Nat.ascFactorial (k + 1) (n - k) := by
induction n with
| zero => rfl
| succ n hn =>
rw [Finset.sum_range_succ, numDerangements_succ, hn, Finset.mul_sum, tsub_self,
Nat.ascFactorial_zero, Int.ofNat_one, mul_one, pow_succ', neg_one_mul, sub_eq_add_neg,
add_left_inj, Finset.sum_congr rfl]
-- show that (n + 1) * (-1)^x * asc_fac x (n - x) = (-1)^x * asc_fac x (n.succ - x)
intro x hx
have h_le : x ≤ n := Finset.mem_range_succ_iff.mp hx
rw [Nat.succ_sub h_le, Nat.ascFactorial_succ, add_right_comm, add_tsub_cancel_of_le h_le,
Int.natCast_mul, Int.natCast_add, mul_left_comm, Nat.cast_one] |
.lake/packages/mathlib/Mathlib/Combinatorics/Derangements/Exponential.lean | import Mathlib.Algebra.BigOperators.Field
import Mathlib.Analysis.SpecialFunctions.Exponential
import Mathlib.Combinatorics.Derangements.Finite
import Mathlib.Data.Nat.Cast.Field
/-!
# Derangement exponential series
This file proves that the probability of a permutation on n elements being a derangement is 1/e.
The specific lemma is `numDerangements_tendsto_inv_e`.
-/
open Filter NormedSpace
open scoped Topology
theorem numDerangements_tendsto_inv_e :
Tendsto (fun n => (numDerangements n : ℝ) / n.factorial) atTop (𝓝 (Real.exp (-1))) := by
-- we show that d(n)/n! is the partial sum of exp(-1), but offset by 1.
-- this isn't entirely obvious, since we have to ensure that asc_factorial and
-- factorial interact in the right way, e.g., that k ≤ n always
let s : ℕ → ℝ := fun n => ∑ k ∈ Finset.range n, (-1 : ℝ) ^ k / k.factorial
suffices ∀ n : ℕ, (numDerangements n : ℝ) / n.factorial = s (n + 1) by
simp_rw [this]
-- shift the function by 1, and then use the fact that the partial sums
-- converge to the infinite sum
rw [tendsto_add_atTop_iff_nat
(f := fun n => ∑ k ∈ Finset.range n, (-1 : ℝ) ^ k / k.factorial) 1]
apply HasSum.tendsto_sum_nat
-- there's no specific lemma for ℝ that ∑ x^k/k! sums to exp(x), but it's
-- true in more general fields, so use that lemma
rw [Real.exp_eq_exp_ℝ]
exact expSeries_div_hasSum_exp ℝ (-1 : ℝ)
intro n
rw [← Int.cast_natCast, numDerangements_sum]
push_cast
rw [Finset.sum_div]
-- get down to individual terms
refine Finset.sum_congr (refl _) ?_
intro k hk
have h_le : k ≤ n := Finset.mem_range_succ_iff.mp hk
rw [Nat.ascFactorial_eq_div, add_tsub_cancel_of_le h_le]
push_cast [Nat.factorial_dvd_factorial h_le]
field |
.lake/packages/mathlib/Mathlib/Combinatorics/Derangements/Basic.lean | import Mathlib.Dynamics.FixedPoints.Basic
import Mathlib.GroupTheory.Perm.Option
import Mathlib.Logic.Equiv.Defs
import Mathlib.Logic.Equiv.Option
import Mathlib.Tactic.ApplyFun
/-!
# Derangements on types
In this file we define `derangements α`, the set of derangements on a type `α`.
We also define some equivalences involving various subtypes of `Perm α` and `derangements α`:
* `derangementsOptionEquivSigmaAtMostOneFixedPoint`: An equivalence between
`derangements (Option α)` and the sigma-type `Σ a : α, {f : Perm α // fixed_points f ⊆ a}`.
* `derangementsRecursionEquiv`: An equivalence between `derangements (Option α)` and the
sigma-type `Σ a : α, (derangements (({a}ᶜ : Set α) : Type*) ⊕ derangements α)` which is later
used to inductively count the number of derangements.
In order to prove the above, we also prove some results about the effect of `Equiv.removeNone`
on derangements: `RemoveNone.fiber_none` and `RemoveNone.fiber_some`.
-/
open Equiv Function
/-- A permutation is a derangement if it has no fixed points. -/
def derangements (α : Type*) : Set (Perm α) :=
{ f : Perm α | ∀ x : α, f x ≠ x }
variable {α β : Type*}
theorem mem_derangements_iff_fixedPoints_eq_empty {f : Perm α} :
f ∈ derangements α ↔ fixedPoints f = ∅ :=
Set.eq_empty_iff_forall_notMem.symm
/-- If `α` is equivalent to `β`, then `derangements α` is equivalent to `derangements β`. -/
def Equiv.derangementsCongr (e : α ≃ β) : derangements α ≃ derangements β :=
e.permCongr.subtypeEquiv fun {f} => e.forall_congr <| by
intro b; simp only [ne_eq, permCongr_apply, symm_apply_apply, EmbeddingLike.apply_eq_iff_eq]
namespace derangements
/-- Derangements on a subtype are equivalent to permutations on the original type where points are
fixed iff they are not in the subtype. -/
protected def subtypeEquiv (p : α → Prop) [DecidablePred p] :
derangements (Subtype p) ≃ { f : Perm α // ∀ a, ¬p a ↔ a ∈ fixedPoints f } :=
calc
derangements (Subtype p) ≃ { f : { f : Perm α // ∀ a, ¬p a → a ∈ fixedPoints f } //
∀ a, a ∈ fixedPoints f → ¬p a } := by
refine (Perm.subtypeEquivSubtypePerm p).subtypeEquiv fun f => ⟨fun hf a hfa ha => ?_, ?_⟩
· refine hf ⟨a, ha⟩ (Subtype.ext ?_)
simp_rw [mem_fixedPoints, IsFixedPt, Perm.subtypeEquivSubtypePerm,
Equiv.coe_fn_mk, Perm.ofSubtype_apply_of_mem _ ha] at hfa
assumption
rintro hf ⟨a, ha⟩ hfa
refine hf _ ?_ ha
simp only [Perm.subtypeEquivSubtypePerm_apply_coe, mem_fixedPoints]
dsimp [IsFixedPt]
simp_rw [Perm.ofSubtype_apply_of_mem _ ha, hfa]
_ ≃ { f : Perm α // ∃ _h : ∀ a, ¬p a → a ∈ fixedPoints f, ∀ a, a ∈ fixedPoints f → ¬p a } :=
subtypeSubtypeEquivSubtypeExists _ _
_ ≃ { f : Perm α // ∀ a, ¬p a ↔ a ∈ fixedPoints f } :=
subtypeEquivRight fun f => by
simp_rw [exists_prop, ← forall_and, ← iff_iff_implies_and_implies]
universe u
/-- The set of permutations that fix either `a` or nothing is equivalent to the sum of:
- derangements on `α`
- derangements on `α` minus `a`. -/
def atMostOneFixedPointEquivSum_derangements [DecidableEq α] (a : α) :
{ f : Perm α // fixedPoints f ⊆ {a} } ≃ (derangements ({a}ᶜ : Set α)) ⊕ (derangements α) :=
calc
{ f : Perm α // fixedPoints f ⊆ {a} } ≃
{ f : { f : Perm α // fixedPoints f ⊆ {a} } // a ∈ fixedPoints f } ⊕
{ f : { f : Perm α // fixedPoints f ⊆ {a} } // a ∉ fixedPoints f } :=
(Equiv.sumCompl _).symm
_ ≃ { f : Perm α // fixedPoints f ⊆ {a} ∧ a ∈ fixedPoints f } ⊕
{ f : Perm α // fixedPoints f ⊆ {a} ∧ a ∉ fixedPoints f } := by
refine Equiv.sumCongr ?_ ?_
· exact subtypeSubtypeEquivSubtypeInter
(fun x : Perm α => fixedPoints x ⊆ {a})
(a ∈ fixedPoints ·)
· exact subtypeSubtypeEquivSubtypeInter
(fun x : Perm α => fixedPoints x ⊆ {a})
(a ∉ fixedPoints ·)
_ ≃ { f : Perm α // fixedPoints f = {a} } ⊕ { f : Perm α // fixedPoints f = ∅ } := by
refine Equiv.sumCongr (subtypeEquivRight fun f => ?_) (subtypeEquivRight fun f => ?_)
· rw [Set.eq_singleton_iff_unique_mem, and_comm]
rfl
· rw [Set.eq_empty_iff_forall_notMem]
exact ⟨fun h x hx => h.2 (h.1 hx ▸ hx), fun h => ⟨fun x hx => (h _ hx).elim, h _⟩⟩
_ ≃ derangements ({a}ᶜ : Set α) ⊕ derangements α := by
refine
Equiv.sumCongr ((derangements.subtypeEquiv _).trans <|
subtypeEquivRight fun x => ?_).symm
(subtypeEquivRight fun f => mem_derangements_iff_fixedPoints_eq_empty.symm)
rw [eq_comm, Set.ext_iff]
simp_rw [Set.mem_compl_iff, Classical.not_not]
namespace Equiv
variable [DecidableEq α]
/-- The set of permutations `f` such that the preimage of `(a, f)` under
`Equiv.Perm.decomposeOption` is a derangement. -/
def RemoveNone.fiber (a : Option α) : Set (Perm α) :=
{ f : Perm α | (a, f) ∈ Equiv.Perm.decomposeOption '' derangements (Option α) }
theorem RemoveNone.mem_fiber (a : Option α) (f : Perm α) :
f ∈ RemoveNone.fiber a ↔
∃ F : Perm (Option α), F ∈ derangements (Option α) ∧ F none = a ∧ removeNone F = f := by
simp [RemoveNone.fiber, derangements]
theorem RemoveNone.fiber_none : RemoveNone.fiber (@none α) = ∅ := by
rw [Set.eq_empty_iff_forall_notMem]
intro f hyp
rw [RemoveNone.mem_fiber] at hyp
rcases hyp with ⟨F, F_derangement, F_none, _⟩
exact F_derangement none F_none
/-- For any `a : α`, the fiber over `some a` is the set of permutations
where `a` is the only possible fixed point. -/
theorem RemoveNone.fiber_some (a : α) :
RemoveNone.fiber (some a) = { f : Perm α | fixedPoints f ⊆ {a} } := by
ext f
constructor
· rw [RemoveNone.mem_fiber]
rintro ⟨F, F_derangement, F_none, rfl⟩ x x_fixed
rw [mem_fixedPoints_iff] at x_fixed
apply_fun some at x_fixed
rcases Fx : F (some x) with - | y
· rwa [removeNone_none F Fx, F_none, Option.some_inj, eq_comm] at x_fixed
· exfalso
rw [removeNone_some F ⟨y, Fx⟩] at x_fixed
exact F_derangement _ x_fixed
· intro h_opfp
use Equiv.Perm.decomposeOption.symm (some a, f)
constructor
· intro x
apply_fun fun x => Equiv.swap none (some a) x
simp only [Perm.decomposeOption_symm_apply, Perm.coe_mul]
rcases x with - | x
· simp
simp only [comp, optionCongr_apply, Option.map_some, swap_apply_self]
by_cases x_vs_a : x = a
· rw [x_vs_a, swap_apply_right]
apply Option.some_ne_none
have ne_1 : some x ≠ none := Option.some_ne_none _
have ne_2 : some x ≠ some a := (Option.some_injective α).ne_iff.mpr x_vs_a
rw [swap_apply_of_ne_of_ne ne_1 ne_2, (Option.some_injective α).ne_iff]
intro contra
exact x_vs_a (h_opfp contra)
· rw [apply_symm_apply]
end Equiv
section Option
variable [DecidableEq α]
/-- The set of derangements on `Option α` is equivalent to the union over `a : α`
of "permutations with `a` the only possible fixed point". -/
def derangementsOptionEquivSigmaAtMostOneFixedPoint :
derangements (Option α) ≃ Σ a : α, { f : Perm α | fixedPoints f ⊆ {a} } := by
have fiber_none_is_false : Equiv.RemoveNone.fiber (@none α) → False := by
rw [Equiv.RemoveNone.fiber_none]
exact IsEmpty.false
calc
derangements (Option α) ≃ Equiv.Perm.decomposeOption '' derangements (Option α) :=
Equiv.image _ _
_ ≃ Σ a : Option α, ↥(Equiv.RemoveNone.fiber a) := setProdEquivSigma _
_ ≃ Σ a : α, ↥(Equiv.RemoveNone.fiber (some a)) :=
sigmaOptionEquivOfSome _ fiber_none_is_false
_ ≃ Σ a : α, { f : Perm α | fixedPoints f ⊆ {a} } := by
simp_rw [Equiv.RemoveNone.fiber_some]
rfl
/-- The set of derangements on `Option α` is equivalent to the union over all `a : α` of
"derangements on `α` ⊕ derangements on `{a}ᶜ`". -/
def derangementsRecursionEquiv :
derangements (Option α) ≃
Σ a : α, derangements (({a}ᶜ : Set α) : Type _) ⊕ derangements α :=
derangementsOptionEquivSigmaAtMostOneFixedPoint.trans
(sigmaCongrRight atMostOneFixedPointEquivSum_derangements)
end Option
end derangements |
.lake/packages/mathlib/Mathlib/Combinatorics/Digraph/Orientation.lean | import Mathlib.Combinatorics.Digraph.Basic
import Mathlib.Combinatorics.SimpleGraph.Basic
/-!
# Graph Orientation
This module introduces conversion operations between `Digraph`s and `SimpleGraph`s, by forgetting
the edge orientations of `Digraph`.
## Main Definitions
- `Digraph.toSimpleGraphInclusive`: Converts a `Digraph` to a `SimpleGraph` by creating an
undirected edge if either orientation exists in the digraph.
- `Digraph.toSimpleGraphStrict`: Converts a `Digraph` to a `SimpleGraph` by creating an undirected
edge only if both orientations exist in the digraph.
## TODO
- Show that there is an isomorphism between loopless complete digraphs and oriented graphs.
- Define more ways to orient a `SimpleGraph`.
- Provide lemmas on how `toSimpleGraphInclusive` and `toSimpleGraphStrict` relate to other lattice
structures on `SimpleGraph`s and `Digraph`s.
## Tags
digraph, simple graph, oriented graphs
-/
variable {V : Type*}
namespace Digraph
section toSimpleGraph
/-! ### Orientation-forgetting maps on digraphs -/
/--
Orientation-forgetting map from `Digraph` to `SimpleGraph` that gives an unoriented edge if
either orientation is present.
-/
def toSimpleGraphInclusive (G : Digraph V) : SimpleGraph V := SimpleGraph.fromRel G.Adj
/--
Orientation-forgetting map from `Digraph` to `SimpleGraph` that gives an unoriented edge if
both orientations are present.
-/
def toSimpleGraphStrict (G : Digraph V) : SimpleGraph V where
Adj v w := v ≠ w ∧ G.Adj v w ∧ G.Adj w v
symm _ _ h := And.intro h.1.symm h.2.symm
loopless _ h := h.1 rfl
lemma toSimpleGraphStrict_subgraph_toSimpleGraphInclusive (G : Digraph V) :
G.toSimpleGraphStrict ≤ G.toSimpleGraphInclusive :=
fun _ _ h ↦ ⟨h.1, Or.inl h.2.1⟩
@[mono]
lemma toSimpleGraphInclusive_mono : Monotone (toSimpleGraphInclusive : _ → SimpleGraph V) :=
fun _ _ h₁ _ _ h₂ ↦ ⟨h₂.1, h₂.2.imp (@h₁ _ _) (@h₁ _ _)⟩
@[mono]
lemma toSimpleGraphStrict_mono : Monotone (toSimpleGraphStrict : _ → SimpleGraph V) :=
fun _ _ h₁ _ _ h₂ ↦ ⟨h₂.1, h₁ h₂.2.1, h₁ h₂.2.2⟩
@[simp]
lemma toSimpleGraphInclusive_top : (⊤ : Digraph V).toSimpleGraphInclusive = ⊤ := by
ext; exact ⟨And.left, fun h ↦ ⟨h.ne, Or.inl trivial⟩⟩
@[simp]
lemma toSimpleGraphStrict_top : (⊤ : Digraph V).toSimpleGraphStrict = ⊤ := by
ext; exact ⟨And.left, fun h ↦ ⟨h.ne, trivial, trivial⟩⟩
@[simp]
lemma toSimpleGraphInclusive_bot : (⊥ : Digraph V).toSimpleGraphInclusive = ⊥ := by
ext; exact ⟨fun ⟨_, h⟩ ↦ by tauto, False.elim⟩
@[simp]
lemma toSimpleGraphStrict_bot : (⊥ : Digraph V).toSimpleGraphStrict = ⊥ := by
ext; exact ⟨fun ⟨_, h⟩ ↦ by tauto, False.elim⟩
end toSimpleGraph
end Digraph |
.lake/packages/mathlib/Mathlib/Combinatorics/Digraph/Basic.lean | import Mathlib.Order.CompleteBooleanAlgebra
import Mathlib.Data.Fintype.Pi
/-!
# Digraphs
This module defines directed graphs on a vertex type `V`,
which is the same notion as a relation `V → V → Prop`.
While this might be too simple of a notion to deserve the grandeur of a new definition,
the intention here is to develop relations using the language of graph theory.
Note that in this treatment, a digraph may have self loops.
The type `Digraph V` is structurally equivalent to `Quiver.{0} V`,
but a difference between these is that `Quiver` is a class —
its purpose is to attach a quiver structure to a particular type `V`.
In contrast, for `Digraph V` we are interested in working with the entire lattice
of digraphs on `V`.
## Main definitions
* `Digraph` is a structure for relations. Unlike `SimpleGraph`, the relation does not need to be
symmetric or irreflexive.
* `CompleteAtomicBooleanAlgebra` instance: Under the subgraph relation, `Digraph` forms a
`CompleteAtomicBooleanAlgebra`. In other words, this is the complete lattice of spanning subgraphs
of the complete graph.
-/
open Finset Function
/--
A digraph is a relation `Adj` on a vertex type `V`.
The relation describes which pairs of vertices are adjacent.
In this treatment, a digraph may have self-loops.
-/
@[ext]
structure Digraph (V : Type*) where
/-- The adjacency relation of a digraph. -/
Adj : V → V → Prop
/--
Constructor for digraphs using a Boolean function.
This is useful for creating a digraph with a decidable `Adj` relation,
and it's used in the construction of the `Fintype (Digraph V)` instance.
-/
@[simps]
def Digraph.mk' {V : Type*} : (V → V → Bool) ↪ Digraph V where
toFun x := ⟨fun v w ↦ x v w⟩
inj' adj adj' := by
simp_rw [mk.injEq]
intro h
funext v w
simpa only [eq_iff_iff, Bool.coe_iff_coe] using congr($h v w)
instance {V : Type*} (adj : V → V → Bool) : DecidableRel (Digraph.mk' adj).Adj :=
inferInstanceAs <| DecidableRel (fun v w ↦ adj v w)
instance {V : Type*} [DecidableEq V] [Fintype V] : Fintype (Digraph V) :=
Fintype.ofBijective Digraph.mk' <| by
classical
refine ⟨Embedding.injective _, ?_⟩
intro G
use fun v w ↦ G.Adj v w
ext v w
simp
namespace Digraph
/--
The complete digraph on a type `V` (denoted by `⊤`)
is the digraph whose vertices are all adjacent.
Note that every vertex is adjacent to itself in `⊤`.
-/
protected def completeDigraph (V : Type*) : Digraph V where Adj := ⊤
/--
The empty digraph on a type `V` (denoted by `⊥`)
is the digraph such that no pairs of vertices are adjacent.
Note that `⊥` is called the empty digraph because it has no edges.
-/
protected def emptyDigraph (V : Type*) : Digraph V where Adj _ _ := False
/--
Two vertices are adjacent in the complete bipartite digraph on two vertex types
if and only if they are not from the same side.
Any bipartite digraph may be regarded as a subgraph of one of these.
-/
@[simps]
def completeBipartiteGraph (V W : Type*) : Digraph (Sum V W) where
Adj v w := v.isLeft ∧ w.isRight ∨ v.isRight ∧ w.isLeft
variable {ι : Sort*} {V : Type*} (G : Digraph V) {a b : V}
theorem adj_injective : Injective (Adj : Digraph V → V → V → Prop) := fun _ _ ↦ Digraph.ext
@[simp] theorem adj_inj {G H : Digraph V} : G.Adj = H.Adj ↔ G = H := Digraph.ext_iff.symm
section Order
/--
The relation that one `Digraph` is a spanning subgraph of another.
Note that `Digraph.IsSubgraph G H` should be spelled `G ≤ H`.
-/
protected def IsSubgraph (x y : Digraph V) : Prop :=
∀ ⦃v w : V⦄, x.Adj v w → y.Adj v w
instance : LE (Digraph V) := ⟨Digraph.IsSubgraph⟩
@[simp]
theorem isSubgraph_eq_le : (Digraph.IsSubgraph : Digraph V → Digraph V → Prop) = (· ≤ ·) := rfl
/-- The supremum of two digraphs `x ⊔ y` has edges where either `x` or `y` have edges. -/
instance : Max (Digraph V) where
max x y := { Adj := x.Adj ⊔ y.Adj }
@[simp]
theorem sup_adj (x y : Digraph V) (v w : V) : (x ⊔ y).Adj v w ↔ x.Adj v w ∨ y.Adj v w := Iff.rfl
/-- The infimum of two digraphs `x ⊓ y` has edges where both `x` and `y` have edges. -/
instance : Min (Digraph V) where
min x y := { Adj := x.Adj ⊓ y.Adj }
@[simp]
theorem inf_adj (x y : Digraph V) (v w : V) : (x ⊓ y).Adj v w ↔ x.Adj v w ∧ y.Adj v w := Iff.rfl
/-- We define `Gᶜ` to be the `Digraph V` such that no two adjacent vertices in `G`
are adjacent in the complement, and every nonadjacent pair of vertices is adjacent. -/
instance hasCompl : HasCompl (Digraph V) where
compl G := { Adj := fun v w ↦ ¬G.Adj v w }
@[simp] theorem compl_adj (G : Digraph V) (v w : V) : Gᶜ.Adj v w ↔ ¬G.Adj v w := Iff.rfl
/-- The difference of two digraphs `x \ y` has the edges of `x` with the edges of `y` removed. -/
instance sdiff : SDiff (Digraph V) where
sdiff x y := { Adj := x.Adj \ y.Adj }
@[simp]
theorem sdiff_adj (x y : Digraph V) (v w : V) : (x \ y).Adj v w ↔ x.Adj v w ∧ ¬y.Adj v w := Iff.rfl
instance supSet : SupSet (Digraph V) where
sSup s := { Adj := fun a b ↦ ∃ G ∈ s, Adj G a b }
instance infSet : InfSet (Digraph V) where
sInf s := { Adj := fun a b ↦ (∀ ⦃G⦄, G ∈ s → Adj G a b) }
@[simp]
theorem sSup_adj {s : Set (Digraph V)} : (sSup s).Adj a b ↔ ∃ G ∈ s, Adj G a b := Iff.rfl
@[simp]
theorem sInf_adj {s : Set (Digraph V)} : (sInf s).Adj a b ↔ ∀ G ∈ s, Adj G a b := Iff.rfl
@[simp]
theorem iSup_adj {f : ι → Digraph V} : (⨆ i, f i).Adj a b ↔ ∃ i, (f i).Adj a b := by simp [iSup]
@[simp]
theorem iInf_adj {f : ι → Digraph V} : (⨅ i, f i).Adj a b ↔ (∀ i, (f i).Adj a b) := by simp [iInf]
/-- For digraphs `G`, `H`, `G ≤ H` iff `∀ a b, G.Adj a b → H.Adj a b`. -/
instance distribLattice : DistribLattice (Digraph V) :=
{ adj_injective.distribLattice Digraph.Adj (fun _ _ ↦ rfl) fun _ _ ↦ rfl with
le := fun G H ↦ ∀ ⦃a b⦄, G.Adj a b → H.Adj a b }
instance completeAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra (Digraph V) where
top := Digraph.completeDigraph V
bot := Digraph.emptyDigraph V
le_top _ _ _ _ := trivial
bot_le _ _ _ h := h.elim
inf_compl_le_bot _ _ _ h := absurd h.1 h.2
top_le_sup_compl G v w _ := by tauto
le_sSup _ G hG _ _ hab := ⟨G, hG, hab⟩
sSup_le s G hG a b := by
rintro ⟨H, hH, hab⟩
exact hG _ hH hab
sInf_le _ _ hG _ _ hab := hab hG
le_sInf _ _ hG _ _ hab _ hH := hG _ hH hab
iInf_iSup_eq f := by ext; simp [Classical.skolem]
@[simp] theorem top_adj (v w : V) : (⊤ : Digraph V).Adj v w := trivial
@[simp] theorem bot_adj (v w : V) : (⊥ : Digraph V).Adj v w ↔ False := Iff.rfl
@[simp] theorem completeDigraph_eq_top (V : Type*) : Digraph.completeDigraph V = ⊤ := rfl
@[simp] theorem emptyDigraph_eq_bot (V : Type*) : Digraph.emptyDigraph V = ⊥ := rfl
@[simps] instance (V : Type*) : Inhabited (Digraph V) := ⟨⊥⟩
instance [IsEmpty V] : Unique (Digraph V) where
default := ⊥
uniq G := by ext1; congr!
instance [Nonempty V] : Nontrivial (Digraph V) := by
use ⊥, ⊤
have v := Classical.arbitrary V
exact ne_of_apply_ne (·.Adj v v) (by simp)
section Decidable
variable (V) (H : Digraph V) [DecidableRel G.Adj] [DecidableRel H.Adj]
instance Bot.adjDecidable : DecidableRel (⊥ : Digraph V).Adj :=
inferInstanceAs <| DecidableRel fun _ _ ↦ False
instance Sup.adjDecidable : DecidableRel (G ⊔ H).Adj :=
inferInstanceAs <| DecidableRel fun v w ↦ G.Adj v w ∨ H.Adj v w
instance Inf.adjDecidable : DecidableRel (G ⊓ H).Adj :=
inferInstanceAs <| DecidableRel fun v w ↦ G.Adj v w ∧ H.Adj v w
instance SDiff.adjDecidable : DecidableRel (G \ H).Adj :=
inferInstanceAs <| DecidableRel fun v w ↦ G.Adj v w ∧ ¬H.Adj v w
instance Top.adjDecidable : DecidableRel (⊤ : Digraph V).Adj :=
inferInstanceAs <| DecidableRel fun _ _ ↦ True
instance Compl.adjDecidable : DecidableRel (Gᶜ.Adj) :=
inferInstanceAs <| DecidableRel fun v w ↦ ¬G.Adj v w
end Decidable
end Order
end Digraph |
.lake/packages/mathlib/Mathlib/LinearAlgebra/Ray.lean | import Mathlib.Algebra.BigOperators.Fin
import Mathlib.Algebra.Order.Module.Algebra
import Mathlib.Algebra.Ring.Subring.Units
import Mathlib.LinearAlgebra.LinearIndependent.Defs
import Mathlib.Tactic.LinearCombination
import Mathlib.Tactic.Module
import Mathlib.Tactic.Positivity.Basic
/-!
# Rays in modules
This file defines rays in modules.
## Main definitions
* `SameRay`: two vectors belong to the same ray if they are proportional with a nonnegative
coefficient.
* `Module.Ray` is a type for the equivalence class of nonzero vectors in a module with some
common positive multiple.
-/
noncomputable section
section StrictOrderedCommSemiring
-- TODO: remove `[IsStrictOrderedRing R]` and `@[nolint unusedArguments]`.
/-- Two vectors are in the same ray if either one of them is zero or some positive multiples of them
are equal (in the typical case over a field, this means one of them is a nonnegative multiple of
the other). -/
@[nolint unusedArguments]
def SameRay (R : Type*) [CommSemiring R] [PartialOrder R] [IsStrictOrderedRing R]
{M : Type*} [AddCommMonoid M] [Module R M] (v₁ v₂ : M) : Prop :=
v₁ = 0 ∨ v₂ = 0 ∨ ∃ r₁ r₂ : R, 0 < r₁ ∧ 0 < r₂ ∧ r₁ • v₁ = r₂ • v₂
variable {R : Type*} [CommSemiring R] [PartialOrder R] [IsStrictOrderedRing R]
variable {M : Type*} [AddCommMonoid M] [Module R M]
variable {N : Type*} [AddCommMonoid N] [Module R N]
variable (ι : Type*) [DecidableEq ι]
namespace SameRay
variable {x y z : M}
@[simp]
theorem zero_left (y : M) : SameRay R 0 y :=
Or.inl rfl
@[simp]
theorem zero_right (x : M) : SameRay R x 0 :=
Or.inr <| Or.inl rfl
@[nontriviality]
theorem of_subsingleton [Subsingleton M] (x y : M) : SameRay R x y := by
rw [Subsingleton.elim x 0]
exact zero_left _
@[nontriviality]
theorem of_subsingleton' [Subsingleton R] (x y : M) : SameRay R x y :=
haveI := Module.subsingleton R M
of_subsingleton x y
/-- `SameRay` is reflexive. -/
@[refl]
theorem refl (x : M) : SameRay R x x := by
nontriviality R
exact Or.inr (Or.inr <| ⟨1, 1, zero_lt_one, zero_lt_one, rfl⟩)
protected theorem rfl : SameRay R x x :=
refl _
/-- `SameRay` is symmetric. -/
@[symm]
theorem symm (h : SameRay R x y) : SameRay R y x :=
(or_left_comm.1 h).imp_right <| Or.imp_right fun ⟨r₁, r₂, h₁, h₂, h⟩ => ⟨r₂, r₁, h₂, h₁, h.symm⟩
/-- If `x` and `y` are nonzero vectors on the same ray, then there exist positive numbers `r₁ r₂`
such that `r₁ • x = r₂ • y`. -/
theorem exists_pos (h : SameRay R x y) (hx : x ≠ 0) (hy : y ≠ 0) :
∃ r₁ r₂ : R, 0 < r₁ ∧ 0 < r₂ ∧ r₁ • x = r₂ • y :=
(h.resolve_left hx).resolve_left hy
theorem sameRay_comm : SameRay R x y ↔ SameRay R y x :=
⟨SameRay.symm, SameRay.symm⟩
/-- `SameRay` is transitive unless the vector in the middle is zero and both other vectors are
nonzero. -/
theorem trans (hxy : SameRay R x y) (hyz : SameRay R y z) (hy : y = 0 → x = 0 ∨ z = 0) :
SameRay R x z := by
rcases eq_or_ne x 0 with (rfl | hx); · exact zero_left z
rcases eq_or_ne z 0 with (rfl | hz); · exact zero_right x
rcases eq_or_ne y 0 with (rfl | hy)
· exact (hy rfl).elim (fun h => (hx h).elim) fun h => (hz h).elim
rcases hxy.exists_pos hx hy with ⟨r₁, r₂, hr₁, hr₂, h₁⟩
rcases hyz.exists_pos hy hz with ⟨r₃, r₄, hr₃, hr₄, h₂⟩
refine Or.inr (Or.inr <| ⟨r₃ * r₁, r₂ * r₄, mul_pos hr₃ hr₁, mul_pos hr₂ hr₄, ?_⟩)
rw [mul_smul, mul_smul, h₁, ← h₂, smul_comm]
variable {S : Type*} [CommSemiring S] [PartialOrder S]
[Algebra S R] [Module S M] [SMulPosMono S R]
[IsScalarTower S R M] {a : S}
/-- A vector is in the same ray as a nonnegative multiple of itself. -/
lemma sameRay_nonneg_smul_right (v : M) (h : 0 ≤ a) : SameRay R v (a • v) := by
obtain h | h := (algebraMap_nonneg R h).eq_or_lt'
· rw [← algebraMap_smul R a v, h, zero_smul]
exact zero_right _
· refine Or.inr <| Or.inr ⟨algebraMap S R a, 1, h, by nontriviality R; exact zero_lt_one, ?_⟩
module
/-- A nonnegative multiple of a vector is in the same ray as that vector. -/
lemma sameRay_nonneg_smul_left (v : M) (ha : 0 ≤ a) : SameRay R (a • v) v :=
(sameRay_nonneg_smul_right v ha).symm
/-- A vector is in the same ray as a positive multiple of itself. -/
lemma sameRay_pos_smul_right (v : M) (ha : 0 < a) : SameRay R v (a • v) :=
sameRay_nonneg_smul_right v ha.le
/-- A positive multiple of a vector is in the same ray as that vector. -/
lemma sameRay_pos_smul_left (v : M) (ha : 0 < a) : SameRay R (a • v) v :=
sameRay_nonneg_smul_left v ha.le
/-- A vector is in the same ray as a nonnegative multiple of one it is in the same ray as. -/
lemma nonneg_smul_right (h : SameRay R x y) (ha : 0 ≤ a) : SameRay R x (a • y) :=
h.trans (sameRay_nonneg_smul_right y ha) fun hy => Or.inr <| by rw [hy, smul_zero]
/-- A nonnegative multiple of a vector is in the same ray as one it is in the same ray as. -/
lemma nonneg_smul_left (h : SameRay R x y) (ha : 0 ≤ a) : SameRay R (a • x) y :=
(h.symm.nonneg_smul_right ha).symm
/-- A vector is in the same ray as a positive multiple of one it is in the same ray as. -/
theorem pos_smul_right (h : SameRay R x y) (ha : 0 < a) : SameRay R x (a • y) :=
h.nonneg_smul_right ha.le
/-- A positive multiple of a vector is in the same ray as one it is in the same ray as. -/
theorem pos_smul_left (h : SameRay R x y) (hr : 0 < a) : SameRay R (a • x) y :=
h.nonneg_smul_left hr.le
/-- If two vectors are on the same ray then they remain so after applying a linear map. -/
theorem map (f : M →ₗ[R] N) (h : SameRay R x y) : SameRay R (f x) (f y) :=
(h.imp fun hx => by rw [hx, map_zero]) <|
Or.imp (fun hy => by rw [hy, map_zero]) fun ⟨r₁, r₂, hr₁, hr₂, h⟩ =>
⟨r₁, r₂, hr₁, hr₂, by rw [← f.map_smul, ← f.map_smul, h]⟩
/-- The images of two vectors under an injective linear map are on the same ray if and only if the
original vectors are on the same ray. -/
theorem _root_.Function.Injective.sameRay_map_iff
{F : Type*} [FunLike F M N] [LinearMapClass F R M N]
{f : F} (hf : Function.Injective f) :
SameRay R (f x) (f y) ↔ SameRay R x y := by
simp only [SameRay, map_zero, ← hf.eq_iff, map_smul]
/-- The images of two vectors under a linear equivalence are on the same ray if and only if the
original vectors are on the same ray. -/
@[simp]
theorem sameRay_map_iff (e : M ≃ₗ[R] N) : SameRay R (e x) (e y) ↔ SameRay R x y :=
Function.Injective.sameRay_map_iff (EquivLike.injective e)
/-- If two vectors are on the same ray then both scaled by the same action are also on the same
ray. -/
theorem smul {S : Type*} [Monoid S] [DistribMulAction S M] [SMulCommClass R S M]
(h : SameRay R x y) (s : S) : SameRay R (s • x) (s • y) :=
h.map (s • (LinearMap.id : M →ₗ[R] M))
/-- If `x` and `y` are on the same ray as `z`, then so is `x + y`. -/
theorem add_left (hx : SameRay R x z) (hy : SameRay R y z) : SameRay R (x + y) z := by
rcases eq_or_ne x 0 with (rfl | hx₀); · rwa [zero_add]
rcases eq_or_ne y 0 with (rfl | hy₀); · rwa [add_zero]
rcases eq_or_ne z 0 with (rfl | hz₀); · apply zero_right
rcases hx.exists_pos hx₀ hz₀ with ⟨rx, rz₁, hrx, hrz₁, Hx⟩
rcases hy.exists_pos hy₀ hz₀ with ⟨ry, rz₂, hry, hrz₂, Hy⟩
refine Or.inr (Or.inr ⟨rx * ry, ry * rz₁ + rx * rz₂, mul_pos hrx hry, ?_, ?_⟩)
· positivity
· convert congr(ry • $Hx + rx • $Hy) using 1 <;> module
/-- If `y` and `z` are on the same ray as `x`, then so is `y + z`. -/
theorem add_right (hy : SameRay R x y) (hz : SameRay R x z) : SameRay R x (y + z) :=
(hy.symm.add_left hz.symm).symm
end SameRay
set_option linter.unusedVariables false in
/-- Nonzero vectors, as used to define rays. This type depends on an unused argument `R` so that
`RayVector.Setoid` can be an instance. -/
@[nolint unusedArguments]
def RayVector (R M : Type*) [Zero M] :=
{ v : M // v ≠ 0 }
instance RayVector.coe [Zero M] : CoeOut (RayVector R M) M where
coe := Subtype.val
instance {R M : Type*} [Zero M] [Nontrivial M] : Nonempty (RayVector R M) :=
let ⟨x, hx⟩ := exists_ne (0 : M)
⟨⟨x, hx⟩⟩
variable (R M)
/-- The setoid of the `SameRay` relation for the subtype of nonzero vectors. -/
instance RayVector.Setoid : Setoid (RayVector R M) where
r x y := SameRay R (x : M) y
iseqv :=
⟨fun _ => SameRay.refl _, fun h => h.symm, by
intro x y z hxy hyz
exact hxy.trans hyz fun hy => (y.2 hy).elim⟩
/-- A ray (equivalence class of nonzero vectors with common positive multiples) in a module. -/
def Module.Ray :=
Quotient (RayVector.Setoid R M)
variable {R M}
/-- Equivalence of nonzero vectors, in terms of `SameRay`. -/
theorem equiv_iff_sameRay {v₁ v₂ : RayVector R M} : v₁ ≈ v₂ ↔ SameRay R (v₁ : M) v₂ :=
Iff.rfl
variable (R)
/-- The ray given by a nonzero vector. -/
def rayOfNeZero (v : M) (h : v ≠ 0) : Module.Ray R M :=
⟦⟨v, h⟩⟧
/-- An induction principle for `Module.Ray`, used as `induction x using Module.Ray.ind`. -/
theorem Module.Ray.ind {C : Module.Ray R M → Prop} (h : ∀ (v) (hv : v ≠ 0), C (rayOfNeZero R v hv))
(x : Module.Ray R M) : C x :=
Quotient.ind (Subtype.rec <| h) x
variable {R}
instance [Nontrivial M] : Nonempty (Module.Ray R M) :=
Nonempty.map Quotient.mk' inferInstance
/-- The rays given by two nonzero vectors are equal if and only if those vectors
satisfy `SameRay`. -/
theorem ray_eq_iff {v₁ v₂ : M} (hv₁ : v₁ ≠ 0) (hv₂ : v₂ ≠ 0) :
rayOfNeZero R _ hv₁ = rayOfNeZero R _ hv₂ ↔ SameRay R v₁ v₂ :=
Quotient.eq'
/-- The ray given by a positive multiple of a nonzero vector. -/
@[simp]
theorem ray_pos_smul {v : M} (h : v ≠ 0) {r : R} (hr : 0 < r) (hrv : r • v ≠ 0) :
rayOfNeZero R (r • v) hrv = rayOfNeZero R v h :=
(ray_eq_iff _ _).2 <| SameRay.sameRay_pos_smul_left v hr
/-- An equivalence between modules implies an equivalence between ray vectors. -/
def RayVector.mapLinearEquiv (e : M ≃ₗ[R] N) : RayVector R M ≃ RayVector R N :=
Equiv.subtypeEquiv e.toEquiv fun _ => e.map_ne_zero_iff.symm
/-- An equivalence between modules implies an equivalence between rays. -/
def Module.Ray.map (e : M ≃ₗ[R] N) : Module.Ray R M ≃ Module.Ray R N :=
Quotient.congr (RayVector.mapLinearEquiv e) fun _ _=> (SameRay.sameRay_map_iff _).symm
@[simp]
theorem Module.Ray.map_apply (e : M ≃ₗ[R] N) (v : M) (hv : v ≠ 0) :
Module.Ray.map e (rayOfNeZero _ v hv) = rayOfNeZero _ (e v) (e.map_ne_zero_iff.2 hv) :=
rfl
@[simp]
theorem Module.Ray.map_refl : (Module.Ray.map <| LinearEquiv.refl R M) = Equiv.refl _ :=
Equiv.ext <| Module.Ray.ind R fun _ _ => rfl
@[simp]
theorem Module.Ray.map_symm (e : M ≃ₗ[R] N) : (Module.Ray.map e).symm = Module.Ray.map e.symm :=
rfl
section Action
variable {G : Type*} [Group G] [DistribMulAction G M]
/-- Any invertible action preserves the non-zeroness of ray vectors. This is primarily of interest
when `G = Rˣ` -/
instance {R : Type*} : MulAction G (RayVector R M) where
smul r := Subtype.map (r • ·) fun _ => (smul_ne_zero_iff_ne _).2
mul_smul a b _ := Subtype.ext <| mul_smul a b _
one_smul _ := Subtype.ext <| one_smul _ _
variable [SMulCommClass R G M]
/-- Any invertible action preserves the non-zeroness of rays. This is primarily of interest when
`G = Rˣ` -/
instance : MulAction G (Module.Ray R M) where
smul r := Quotient.map (r • ·) fun _ _ h => h.smul _
mul_smul a b := Quotient.ind fun _ => congr_arg Quotient.mk' <| mul_smul a b _
one_smul := Quotient.ind fun _ => congr_arg Quotient.mk' <| one_smul _ _
/-- The action via `LinearEquiv.apply_distribMulAction` corresponds to `Module.Ray.map`. -/
@[simp]
theorem Module.Ray.linearEquiv_smul_eq_map (e : M ≃ₗ[R] M) (v : Module.Ray R M) :
e • v = Module.Ray.map e v :=
rfl
@[simp]
theorem smul_rayOfNeZero (g : G) (v : M) (hv) :
g • rayOfNeZero R v hv = rayOfNeZero R (g • v) ((smul_ne_zero_iff_ne _).2 hv) :=
rfl
end Action
namespace Module.Ray
/-- Scaling by a positive unit is a no-op. -/
theorem units_smul_of_pos (u : Rˣ) (hu : 0 < (u : R)) (v : Module.Ray R M) : u • v = v := by
induction v using Module.Ray.ind
rw [smul_rayOfNeZero, ray_eq_iff]
exact SameRay.sameRay_pos_smul_left _ hu
/-- An arbitrary `RayVector` giving a ray. -/
def someRayVector (x : Module.Ray R M) : RayVector R M :=
Quotient.out x
/-- The ray of `someRayVector`. -/
@[simp]
theorem someRayVector_ray (x : Module.Ray R M) : (⟦x.someRayVector⟧ : Module.Ray R M) = x :=
Quotient.out_eq _
/-- An arbitrary nonzero vector giving a ray. -/
def someVector (x : Module.Ray R M) : M :=
x.someRayVector
/-- `someVector` is nonzero. -/
@[simp]
theorem someVector_ne_zero (x : Module.Ray R M) : x.someVector ≠ 0 :=
x.someRayVector.property
/-- The ray of `someVector`. -/
@[simp]
theorem someVector_ray (x : Module.Ray R M) : rayOfNeZero R _ x.someVector_ne_zero = x :=
(congr_arg _ (Subtype.coe_eta _ _) :).trans x.out_eq
end Module.Ray
end StrictOrderedCommSemiring
section StrictOrderedCommRing
variable {R : Type*} [CommRing R] [PartialOrder R] [IsStrictOrderedRing R]
variable {M N : Type*} [AddCommGroup M] [AddCommGroup N] [Module R M] [Module R N] {x y : M}
/-- `SameRay.neg` as an `iff`. -/
@[simp]
theorem sameRay_neg_iff : SameRay R (-x) (-y) ↔ SameRay R x y := by
simp only [SameRay, neg_eq_zero, smul_neg, neg_inj]
alias ⟨SameRay.of_neg, SameRay.neg⟩ := sameRay_neg_iff
theorem sameRay_neg_swap : SameRay R (-x) y ↔ SameRay R x (-y) := by rw [← sameRay_neg_iff, neg_neg]
theorem eq_zero_of_sameRay_neg_smul_right [NoZeroSMulDivisors R M] {r : R} (hr : r < 0)
(h : SameRay R x (r • x)) : x = 0 := by
rcases h with (rfl | h₀ | ⟨r₁, r₂, hr₁, hr₂, h⟩)
· rfl
· simpa [hr.ne] using h₀
· rw [← sub_eq_zero, smul_smul, ← sub_smul, smul_eq_zero] at h
refine h.resolve_left (ne_of_gt <| sub_pos.2 ?_)
exact (mul_neg_of_pos_of_neg hr₂ hr).trans hr₁
/-- If a vector is in the same ray as its negation, that vector is zero. -/
theorem eq_zero_of_sameRay_self_neg [NoZeroSMulDivisors R M] (h : SameRay R x (-x)) : x = 0 := by
nontriviality M; haveI : Nontrivial R := Module.nontrivial R M
refine eq_zero_of_sameRay_neg_smul_right (neg_lt_zero.2 (zero_lt_one' R)) ?_
rwa [neg_one_smul]
namespace RayVector
/-- Negating a nonzero vector. -/
instance {R : Type*} : Neg (RayVector R M) :=
⟨fun v => ⟨-v, neg_ne_zero.2 v.prop⟩⟩
/-- Negating a nonzero vector commutes with coercion to the underlying module. -/
@[simp, norm_cast]
theorem coe_neg {R : Type*} (v : RayVector R M) : ↑(-v) = -(v : M) :=
rfl
/-- Negating a nonzero vector twice produces the original vector. -/
instance {R : Type*} : InvolutiveNeg (RayVector R M) where
neg_neg v := by rw [Subtype.ext_iff, coe_neg, coe_neg, neg_neg]
/-- If two nonzero vectors are equivalent, so are their negations. -/
@[simp]
theorem equiv_neg_iff {v₁ v₂ : RayVector R M} : -v₁ ≈ -v₂ ↔ v₁ ≈ v₂ :=
sameRay_neg_iff
end RayVector
variable (R)
/-- Negating a ray. -/
instance : Neg (Module.Ray R M) :=
⟨Quotient.map (fun v => -v) fun _ _ => RayVector.equiv_neg_iff.2⟩
/-- The ray given by the negation of a nonzero vector. -/
@[simp]
theorem neg_rayOfNeZero (v : M) (h : v ≠ 0) :
-rayOfNeZero R _ h = rayOfNeZero R (-v) (neg_ne_zero.2 h) :=
rfl
namespace Module.Ray
variable {R}
/-- Negating a ray twice produces the original ray. -/
instance : InvolutiveNeg (Module.Ray R M) where
neg_neg x := by apply ind R (by simp) x
-- Quotient.ind (fun a => congr_arg Quotient.mk' <| neg_neg _) x
/-- A ray does not equal its own negation. -/
theorem ne_neg_self [NoZeroSMulDivisors R M] (x : Module.Ray R M) : x ≠ -x := by
induction x using Module.Ray.ind with | h x hx =>
rw [neg_rayOfNeZero, Ne, ray_eq_iff]
exact mt eq_zero_of_sameRay_self_neg hx
theorem neg_units_smul (u : Rˣ) (v : Module.Ray R M) : -u • v = -(u • v) := by
induction v using Module.Ray.ind
simp only [smul_rayOfNeZero, Units.smul_def, Units.val_neg, neg_smul, neg_rayOfNeZero]
/-- Scaling by a negative unit is negation. -/
theorem units_smul_of_neg (u : Rˣ) (hu : (u : R) < 0) (v : Module.Ray R M) : u • v = -v := by
rw [← neg_inj, neg_neg, ← neg_units_smul, units_smul_of_pos]
rwa [Units.val_neg, Right.neg_pos_iff]
@[simp]
protected theorem map_neg (f : M ≃ₗ[R] N) (v : Module.Ray R M) : map f (-v) = -map f v := by
induction v using Module.Ray.ind with | h g hg => simp
end Module.Ray
end StrictOrderedCommRing
section LinearOrderedCommRing
variable {R : Type*} [CommRing R] [LinearOrder R] [IsStrictOrderedRing R]
variable {M : Type*} [AddCommGroup M] [Module R M]
/-- `SameRay` follows from membership of `MulAction.orbit` for the `Units.posSubgroup`. -/
theorem sameRay_of_mem_orbit {v₁ v₂ : M} (h : v₁ ∈ MulAction.orbit (Units.posSubgroup R) v₂) :
SameRay R v₁ v₂ := by
rcases h with ⟨⟨r, hr : 0 < r.1⟩, rfl : r • v₂ = v₁⟩
exact SameRay.sameRay_pos_smul_left _ hr
/-- Scaling by an inverse unit is the same as scaling by itself. -/
@[simp]
theorem units_inv_smul (u : Rˣ) (v : Module.Ray R M) : u⁻¹ • v = u • v :=
have := mul_self_pos.2 u.ne_zero
calc
u⁻¹ • v = (u * u) • u⁻¹ • v := Eq.symm <| (u⁻¹ • v).units_smul_of_pos _ (by exact this)
_ = u • v := by rw [mul_smul, smul_inv_smul]
section
variable [NoZeroSMulDivisors R M]
@[simp]
theorem sameRay_smul_right_iff {v : M} {r : R} : SameRay R v (r • v) ↔ 0 ≤ r ∨ v = 0 :=
⟨fun hrv => or_iff_not_imp_left.2 fun hr => eq_zero_of_sameRay_neg_smul_right (not_le.1 hr) hrv,
or_imp.2 ⟨SameRay.sameRay_nonneg_smul_right v, fun h => h.symm ▸ SameRay.zero_left _⟩⟩
/-- A nonzero vector is in the same ray as a multiple of itself if and only if that multiple
is positive. -/
theorem sameRay_smul_right_iff_of_ne {v : M} (hv : v ≠ 0) {r : R} (hr : r ≠ 0) :
SameRay R v (r • v) ↔ 0 < r := by
simp only [sameRay_smul_right_iff, hv, or_false, hr.symm.le_iff_lt]
@[simp]
theorem sameRay_smul_left_iff {v : M} {r : R} : SameRay R (r • v) v ↔ 0 ≤ r ∨ v = 0 :=
SameRay.sameRay_comm.trans sameRay_smul_right_iff
/-- A multiple of a nonzero vector is in the same ray as that vector if and only if that multiple
is positive. -/
theorem sameRay_smul_left_iff_of_ne {v : M} (hv : v ≠ 0) {r : R} (hr : r ≠ 0) :
SameRay R (r • v) v ↔ 0 < r :=
SameRay.sameRay_comm.trans (sameRay_smul_right_iff_of_ne hv hr)
@[simp]
theorem sameRay_neg_smul_right_iff {v : M} {r : R} : SameRay R (-v) (r • v) ↔ r ≤ 0 ∨ v = 0 := by
rw [← sameRay_neg_iff, neg_neg, ← neg_smul, sameRay_smul_right_iff, neg_nonneg]
theorem sameRay_neg_smul_right_iff_of_ne {v : M} {r : R} (hv : v ≠ 0) (hr : r ≠ 0) :
SameRay R (-v) (r • v) ↔ r < 0 := by
simp only [sameRay_neg_smul_right_iff, hv, or_false, hr.le_iff_lt]
@[simp]
theorem sameRay_neg_smul_left_iff {v : M} {r : R} : SameRay R (r • v) (-v) ↔ r ≤ 0 ∨ v = 0 :=
SameRay.sameRay_comm.trans sameRay_neg_smul_right_iff
theorem sameRay_neg_smul_left_iff_of_ne {v : M} {r : R} (hv : v ≠ 0) (hr : r ≠ 0) :
SameRay R (r • v) (-v) ↔ r < 0 :=
SameRay.sameRay_comm.trans <| sameRay_neg_smul_right_iff_of_ne hv hr
@[simp]
theorem units_smul_eq_self_iff {u : Rˣ} {v : Module.Ray R M} : u • v = v ↔ 0 < (u : R) := by
induction v using Module.Ray.ind with | h v hv =>
simp only [smul_rayOfNeZero, ray_eq_iff, Units.smul_def, sameRay_smul_left_iff_of_ne hv u.ne_zero]
@[simp]
theorem units_smul_eq_neg_iff {u : Rˣ} {v : Module.Ray R M} : u • v = -v ↔ u.1 < 0 := by
rw [← neg_inj, neg_neg, ← Module.Ray.neg_units_smul, units_smul_eq_self_iff, Units.val_neg,
neg_pos]
/-- Two vectors are in the same ray, or the first is in the same ray as the negation of the
second, if and only if they are not linearly independent. -/
theorem sameRay_or_sameRay_neg_iff_not_linearIndependent {x y : M} :
SameRay R x y ∨ SameRay R x (-y) ↔ ¬LinearIndependent R ![x, y] := by
by_cases hx : x = 0; · simpa [hx] using fun h : LinearIndependent R ![0, y] => h.ne_zero 0 rfl
by_cases hy : y = 0; · simpa [hy] using fun h : LinearIndependent R ![x, 0] => h.ne_zero 1 rfl
simp_rw [Fintype.not_linearIndependent_iff]
refine ⟨fun h => ?_, fun h => ?_⟩
· rcases h with ((hx0 | hy0 | ⟨r₁, r₂, hr₁, _, h⟩) | (hx0 | hy0 | ⟨r₁, r₂, hr₁, _, h⟩))
· exact False.elim (hx hx0)
· exact False.elim (hy hy0)
· refine ⟨![r₁, -r₂], ?_⟩
rw [Fin.sum_univ_two, Fin.exists_fin_two]
simp [h, hr₁.ne.symm]
· exact False.elim (hx hx0)
· exact False.elim (hy (neg_eq_zero.1 hy0))
· refine ⟨![r₁, r₂], ?_⟩
rw [Fin.sum_univ_two, Fin.exists_fin_two]
simp [h, hr₁.ne.symm]
· rcases h with ⟨m, hm, hmne⟩
rw [Fin.sum_univ_two, add_eq_zero_iff_eq_neg] at hm
dsimp only [Matrix.cons_val] at hm
rcases lt_trichotomy (m 0) 0 with (hm0 | hm0 | hm0) <;>
rcases lt_trichotomy (m 1) 0 with (hm1 | hm1 | hm1)
· refine
Or.inr (Or.inr (Or.inr ⟨-m 0, -m 1, Left.neg_pos_iff.2 hm0, Left.neg_pos_iff.2 hm1, ?_⟩))
linear_combination (norm := module) -hm
· exfalso
simp [hm1, hx, hm0.ne] at hm
· refine Or.inl (Or.inr (Or.inr ⟨-m 0, m 1, Left.neg_pos_iff.2 hm0, hm1, ?_⟩))
linear_combination (norm := module) -hm
· exfalso
simp [hm0, hy, hm1.ne] at hm
· rw [Fin.exists_fin_two] at hmne
exact False.elim (not_and_or.2 hmne ⟨hm0, hm1⟩)
· exfalso
simp [hm0, hy, hm1.ne.symm] at hm
· refine Or.inl (Or.inr (Or.inr ⟨m 0, -m 1, hm0, Left.neg_pos_iff.2 hm1, ?_⟩))
rwa [neg_smul]
· exfalso
simp [hm1, hx, hm0.ne.symm] at hm
· refine Or.inr (Or.inr (Or.inr ⟨m 0, m 1, hm0, hm1, ?_⟩))
rwa [smul_neg]
/-- Two vectors are in the same ray, or they are nonzero and the first is in the same ray as the
negation of the second, if and only if they are not linearly independent. -/
theorem sameRay_or_ne_zero_and_sameRay_neg_iff_not_linearIndependent {x y : M} :
SameRay R x y ∨ x ≠ 0 ∧ y ≠ 0 ∧ SameRay R x (-y) ↔ ¬LinearIndependent R ![x, y] := by
rw [← sameRay_or_sameRay_neg_iff_not_linearIndependent]
by_cases hx : x = 0; · simp [hx]
by_cases hy : y = 0 <;> simp [hx, hy]
end
end LinearOrderedCommRing
namespace SameRay
variable {R : Type*} [Field R] [LinearOrder R] [IsStrictOrderedRing R]
variable {M : Type*} [AddCommGroup M] [Module R M] {x y v₁ v₂ : M}
theorem exists_pos_left (h : SameRay R x y) (hx : x ≠ 0) (hy : y ≠ 0) :
∃ r : R, 0 < r ∧ r • x = y :=
let ⟨r₁, r₂, hr₁, hr₂, h⟩ := h.exists_pos hx hy
⟨r₂⁻¹ * r₁, mul_pos (inv_pos.2 hr₂) hr₁, by rw [mul_smul, h, inv_smul_smul₀ hr₂.ne']⟩
theorem exists_pos_right (h : SameRay R x y) (hx : x ≠ 0) (hy : y ≠ 0) :
∃ r : R, 0 < r ∧ x = r • y :=
(h.symm.exists_pos_left hy hx).imp fun _ => And.imp_right Eq.symm
/-- If a vector `v₂` is on the same ray as a nonzero vector `v₁`, then it is equal to `c • v₁` for
some nonnegative `c`. -/
theorem exists_nonneg_left (h : SameRay R x y) (hx : x ≠ 0) : ∃ r : R, 0 ≤ r ∧ r • x = y := by
obtain rfl | hy := eq_or_ne y 0
· exact ⟨0, le_rfl, zero_smul _ _⟩
· exact (h.exists_pos_left hx hy).imp fun _ => And.imp_left le_of_lt
/-- If a vector `v₁` is on the same ray as a nonzero vector `v₂`, then it is equal to `c • v₂` for
some nonnegative `c`. -/
theorem exists_nonneg_right (h : SameRay R x y) (hy : y ≠ 0) : ∃ r : R, 0 ≤ r ∧ x = r • y :=
(h.symm.exists_nonneg_left hy).imp fun _ => And.imp_right Eq.symm
/-- If vectors `v₁` and `v₂` are on the same ray, then for some nonnegative `a b`, `a + b = 1`, we
have `v₁ = a • (v₁ + v₂)` and `v₂ = b • (v₁ + v₂)`. -/
theorem exists_eq_smul_add (h : SameRay R v₁ v₂) :
∃ a b : R, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • (v₁ + v₂) ∧ v₂ = b • (v₁ + v₂) := by
rcases h with (rfl | rfl | ⟨r₁, r₂, h₁, h₂, H⟩)
· use 0, 1
simp
· use 1, 0
simp
· have h₁₂ : 0 < r₁ + r₂ := add_pos h₁ h₂
refine
⟨r₂ / (r₁ + r₂), r₁ / (r₁ + r₂), div_nonneg h₂.le h₁₂.le, div_nonneg h₁.le h₁₂.le, ?_, ?_, ?_⟩
· rw [← add_div, add_comm, div_self h₁₂.ne']
· rw [div_eq_inv_mul, mul_smul, smul_add, ← H, ← add_smul, add_comm r₂, inv_smul_smul₀ h₁₂.ne']
· rw [div_eq_inv_mul, mul_smul, smul_add, H, ← add_smul, add_comm r₂, inv_smul_smul₀ h₁₂.ne']
/-- If vectors `v₁` and `v₂` are on the same ray, then they are nonnegative multiples of the same
vector. Actually, this vector can be assumed to be `v₁ + v₂`, see `SameRay.exists_eq_smul_add`. -/
theorem exists_eq_smul (h : SameRay R v₁ v₂) :
∃ (u : M) (a b : R), 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • u ∧ v₂ = b • u :=
⟨v₁ + v₂, h.exists_eq_smul_add⟩
end SameRay
section LinearOrderedField
variable {R : Type*} [Field R] [LinearOrder R] [IsStrictOrderedRing R]
variable {M : Type*} [AddCommGroup M] [Module R M] {x y : M}
theorem exists_pos_left_iff_sameRay (hx : x ≠ 0) (hy : y ≠ 0) :
(∃ r : R, 0 < r ∧ r • x = y) ↔ SameRay R x y := by
refine ⟨fun h => ?_, fun h => h.exists_pos_left hx hy⟩
rcases h with ⟨r, hr, rfl⟩
exact SameRay.sameRay_pos_smul_right x hr
theorem exists_pos_left_iff_sameRay_and_ne_zero (hx : x ≠ 0) :
(∃ r : R, 0 < r ∧ r • x = y) ↔ SameRay R x y ∧ y ≠ 0 := by
constructor
· rintro ⟨r, hr, rfl⟩
simp [hx, hr.le, hr.ne']
· rintro ⟨hxy, hy⟩
exact (exists_pos_left_iff_sameRay hx hy).2 hxy
theorem exists_nonneg_left_iff_sameRay (hx : x ≠ 0) :
(∃ r : R, 0 ≤ r ∧ r • x = y) ↔ SameRay R x y := by
refine ⟨fun h => ?_, fun h => h.exists_nonneg_left hx⟩
rcases h with ⟨r, hr, rfl⟩
exact SameRay.sameRay_nonneg_smul_right x hr
theorem exists_pos_right_iff_sameRay (hx : x ≠ 0) (hy : y ≠ 0) :
(∃ r : R, 0 < r ∧ x = r • y) ↔ SameRay R x y := by
rw [SameRay.sameRay_comm]
simp_rw [eq_comm (a := x)]
exact exists_pos_left_iff_sameRay hy hx
theorem exists_pos_right_iff_sameRay_and_ne_zero (hy : y ≠ 0) :
(∃ r : R, 0 < r ∧ x = r • y) ↔ SameRay R x y ∧ x ≠ 0 := by
rw [SameRay.sameRay_comm]
simp_rw [eq_comm (a := x)]
exact exists_pos_left_iff_sameRay_and_ne_zero hy
theorem exists_nonneg_right_iff_sameRay (hy : y ≠ 0) :
(∃ r : R, 0 ≤ r ∧ x = r • y) ↔ SameRay R x y := by
rw [SameRay.sameRay_comm]
simp_rw [eq_comm (a := x)]
exact exists_nonneg_left_iff_sameRay (R := R) hy
end LinearOrderedField |
.lake/packages/mathlib/Mathlib/LinearAlgebra/PiTensorProduct.lean | import Mathlib.LinearAlgebra.Multilinear.TensorProduct
import Mathlib.Tactic.AdaptationNote
import Mathlib.LinearAlgebra.Multilinear.Curry
/-!
# Tensor product of an indexed family of modules over commutative semirings
We define the tensor product of an indexed family `s : ι → Type*` of modules over commutative
semirings. We denote this space by `⨂[R] i, s i` and define it as `FreeAddMonoid (R × Π i, s i)`
quotiented by the appropriate equivalence relation. The treatment follows very closely that of the
binary tensor product in `LinearAlgebra/TensorProduct.lean`.
## Main definitions
* `PiTensorProduct R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product
of all the `s i`'s. This is denoted by `⨂[R] i, s i`.
* `tprod R f` with `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`.
This is bundled as a multilinear map from `Π i, s i` to `⨂[R] i, s i`.
* `liftAddHom` constructs an `AddMonoidHom` from `(⨂[R] i, s i)` to some space `F` from a
function `φ : (R × Π i, s i) → F` with the appropriate properties.
* `lift φ` with `φ : MultilinearMap R s E` is the corresponding linear map
`(⨂[R] i, s i) →ₗ[R] E`. This is bundled as a linear equivalence.
* `PiTensorProduct.reindex e` re-indexes the components of `⨂[R] i : ι, M` along `e : ι ≃ ι₂`.
* `PiTensorProduct.tmulEquiv` equivalence between a `TensorProduct` of `PiTensorProduct`s and
a single `PiTensorProduct`.
## Notation
* `⨂[R] i, s i` is defined as localized notation in scope `TensorProduct`.
* `⨂ₜ[R] i, f i` with `f : ∀ i, s i` is defined globally as the tensor product of all the `f i`'s.
## Implementation notes
* We define it via `FreeAddMonoid (R × Π i, s i)` with the `R` representing a "hidden" tensor
factor, rather than `FreeAddMonoid (Π i, s i)` to ensure that, if `ι` is an empty type,
the space is isomorphic to the base ring `R`.
* We have not restricted the index type `ι` to be a `Fintype`, as nothing we do here strictly
requires it. However, problems may arise in the case where `ι` is infinite; use at your own
caution.
* Instead of requiring `DecidableEq ι` as an argument to `PiTensorProduct` itself, we include it
as an argument in the constructors of the relation. A decidability instance still has to come
from somewhere due to the use of `Function.update`, but this hides it from the downstream user.
See the implementation notes for `MultilinearMap` for an extended discussion of this choice.
## TODO
* Define tensor powers, symmetric subspace, etc.
* API for the various ways `ι` can be split into subsets; connect this with the binary
tensor product.
* Include connection with holors.
* Port more of the API from the binary tensor product over to this case.
## Tags
multilinear, tensor, tensor product
-/
open Function
section Semiring
variable {ι ι₂ ι₃ : Type*}
variable {R : Type*} [CommSemiring R]
variable {R₁ R₂ : Type*}
variable {s : ι → Type*} [∀ i, AddCommMonoid (s i)] [∀ i, Module R (s i)]
variable {M : Type*} [AddCommMonoid M] [Module R M]
variable {E : Type*} [AddCommMonoid E] [Module R E]
variable {F : Type*} [AddCommMonoid F]
namespace PiTensorProduct
variable (R) (s)
/-- The relation on `FreeAddMonoid (R × Π i, s i)` that generates a congruence whose quotient is
the tensor product. -/
inductive Eqv : FreeAddMonoid (R × Π i, s i) → FreeAddMonoid (R × Π i, s i) → Prop
| of_zero : ∀ (r : R) (f : Π i, s i) (i : ι) (_ : f i = 0), Eqv (FreeAddMonoid.of (r, f)) 0
| of_zero_scalar : ∀ f : Π i, s i, Eqv (FreeAddMonoid.of (0, f)) 0
| of_add : ∀ (_ : DecidableEq ι) (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i),
Eqv (FreeAddMonoid.of (r, update f i m₁) + FreeAddMonoid.of (r, update f i m₂))
(FreeAddMonoid.of (r, update f i (m₁ + m₂)))
| of_add_scalar : ∀ (r r' : R) (f : Π i, s i),
Eqv (FreeAddMonoid.of (r, f) + FreeAddMonoid.of (r', f)) (FreeAddMonoid.of (r + r', f))
| of_smul : ∀ (_ : DecidableEq ι) (r : R) (f : Π i, s i) (i : ι) (r' : R),
Eqv (FreeAddMonoid.of (r, update f i (r' • f i))) (FreeAddMonoid.of (r' * r, f))
| add_comm : ∀ x y, Eqv (x + y) (y + x)
end PiTensorProduct
variable (R) (s)
/-- `PiTensorProduct R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor
product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. -/
def PiTensorProduct : Type _ :=
(addConGen (PiTensorProduct.Eqv R s)).Quotient
variable {R}
/-- This enables the notation `⨂[R] i : ι, s i` for the pi tensor product `PiTensorProduct`,
given an indexed family of types `s : ι → Type*`. -/
scoped[TensorProduct] notation3:100"⨂["R"] "(...)", "r:(scoped f => PiTensorProduct R f) => r
open TensorProduct
namespace PiTensorProduct
section Module
instance : AddCommMonoid (⨂[R] i, s i) :=
{ (addConGen (PiTensorProduct.Eqv R s)).addMonoid with
add_comm := fun x y ↦
AddCon.induction_on₂ x y fun _ _ ↦
Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.add_comm _ _ }
instance : Inhabited (⨂[R] i, s i) := ⟨0⟩
variable (R) {s}
/-- `tprodCoeff R r f` with `r : R` and `f : Π i, s i` is the tensor product of the vectors `f i`
over all `i : ι`, multiplied by the coefficient `r`. Note that this is meant as an auxiliary
definition for this file alone, and that one should use `tprod` defined below for most purposes. -/
def tprodCoeff (r : R) (f : Π i, s i) : ⨂[R] i, s i :=
AddCon.mk' _ <| FreeAddMonoid.of (r, f)
variable {R}
theorem zero_tprodCoeff (f : Π i, s i) : tprodCoeff R 0 f = 0 :=
Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_zero_scalar _
theorem zero_tprodCoeff' (z : R) (f : Π i, s i) (i : ι) (hf : f i = 0) : tprodCoeff R z f = 0 :=
Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_zero _ _ i hf
theorem add_tprodCoeff [DecidableEq ι] (z : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i) :
tprodCoeff R z (update f i m₁) + tprodCoeff R z (update f i m₂) =
tprodCoeff R z (update f i (m₁ + m₂)) :=
Quotient.sound' <| AddConGen.Rel.of _ _ (Eqv.of_add _ z f i m₁ m₂)
theorem add_tprodCoeff' (z₁ z₂ : R) (f : Π i, s i) :
tprodCoeff R z₁ f + tprodCoeff R z₂ f = tprodCoeff R (z₁ + z₂) f :=
Quotient.sound' <| AddConGen.Rel.of _ _ (Eqv.of_add_scalar z₁ z₂ f)
theorem smul_tprodCoeff_aux [DecidableEq ι] (z : R) (f : Π i, s i) (i : ι) (r : R) :
tprodCoeff R z (update f i (r • f i)) = tprodCoeff R (r * z) f :=
Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_smul _ _ _ _ _
theorem smul_tprodCoeff [DecidableEq ι] (z : R) (f : Π i, s i) (i : ι) (r : R₁) [SMul R₁ R]
[IsScalarTower R₁ R R] [SMul R₁ (s i)] [IsScalarTower R₁ R (s i)] :
tprodCoeff R z (update f i (r • f i)) = tprodCoeff R (r • z) f := by
have h₁ : r • z = r • (1 : R) * z := by rw [smul_mul_assoc, one_mul]
have h₂ : r • f i = (r • (1 : R)) • f i := (smul_one_smul _ _ _).symm
rw [h₁, h₂]
exact smul_tprodCoeff_aux z f i _
/-- Construct an `AddMonoidHom` from `(⨂[R] i, s i)` to some space `F` from a function
`φ : (R × Π i, s i) → F` with the appropriate properties. -/
def liftAddHom (φ : (R × Π i, s i) → F)
(C0 : ∀ (r : R) (f : Π i, s i) (i : ι) (_ : f i = 0), φ (r, f) = 0)
(C0' : ∀ f : Π i, s i, φ (0, f) = 0)
(C_add : ∀ [DecidableEq ι] (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i),
φ (r, update f i m₁) + φ (r, update f i m₂) = φ (r, update f i (m₁ + m₂)))
(C_add_scalar : ∀ (r r' : R) (f : Π i, s i), φ (r, f) + φ (r', f) = φ (r + r', f))
(C_smul : ∀ [DecidableEq ι] (r : R) (f : Π i, s i) (i : ι) (r' : R),
φ (r, update f i (r' • f i)) = φ (r' * r, f)) :
(⨂[R] i, s i) →+ F :=
(addConGen (PiTensorProduct.Eqv R s)).lift (FreeAddMonoid.lift φ) <|
AddCon.addConGen_le fun x y hxy ↦
match hxy with
| Eqv.of_zero r' f i hf =>
(AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, C0 r' f i hf]
| Eqv.of_zero_scalar f =>
(AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, C0']
| Eqv.of_add inst z f i m₁ m₂ =>
(AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, @C_add inst]
| Eqv.of_add_scalar z₁ z₂ f =>
(AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, C_add_scalar]
| Eqv.of_smul inst z f i r' =>
(AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, @C_smul inst]
| Eqv.add_comm x y =>
(AddCon.ker_rel _).2 <| by simp_rw [AddMonoidHom.map_add, add_comm]
/-- Induct using `tprodCoeff` -/
@[elab_as_elim]
protected theorem induction_on' {motive : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i)
(tprodCoeff : ∀ (r : R) (f : Π i, s i), motive (tprodCoeff R r f))
(add : ∀ x y, motive x → motive y → motive (x + y)) :
motive z := by
have C0 : motive 0 := by
have h₁ := tprodCoeff 0 0
rwa [zero_tprodCoeff] at h₁
refine AddCon.induction_on z fun x ↦ FreeAddMonoid.recOn x C0 ?_
simp_rw [AddCon.coe_add]
refine fun f y ih ↦ add _ _ ?_ ih
convert tprodCoeff f.1 f.2
section DistribMulAction
variable [Monoid R₁] [DistribMulAction R₁ R] [SMulCommClass R₁ R R]
variable [Monoid R₂] [DistribMulAction R₂ R] [SMulCommClass R₂ R R]
-- Most of the time we want the instance below this one, which is easier for typeclass resolution
-- to find.
instance hasSMul' : SMul R₁ (⨂[R] i, s i) :=
⟨fun r ↦
liftAddHom (fun f : R × Π i, s i ↦ tprodCoeff R (r • f.1) f.2)
(fun r' f i hf ↦ by simp_rw [zero_tprodCoeff' _ f i hf])
(fun f ↦ by simp [zero_tprodCoeff]) (fun r' f i m₁ m₂ ↦ by simp [add_tprodCoeff])
(fun r' r'' f ↦ by simp [add_tprodCoeff']) fun z f i r' ↦ by
simp [smul_tprodCoeff, mul_smul_comm]⟩
instance : SMul R (⨂[R] i, s i) :=
PiTensorProduct.hasSMul'
theorem smul_tprodCoeff' (r : R₁) (z : R) (f : Π i, s i) :
r • tprodCoeff R z f = tprodCoeff R (r • z) f := rfl
protected theorem smul_add (r : R₁) (x y : ⨂[R] i, s i) : r • (x + y) = r • x + r • y :=
AddMonoidHom.map_add _ _ _
instance distribMulAction' : DistribMulAction R₁ (⨂[R] i, s i) where
smul_add _ _ _ := AddMonoidHom.map_add _ _ _
mul_smul r r' x :=
PiTensorProduct.induction_on' x (fun {r'' f} ↦ by simp [smul_tprodCoeff', smul_smul])
fun {x y} ihx ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihx, ihy]
one_smul x :=
PiTensorProduct.induction_on' x (fun {r f} ↦ by rw [smul_tprodCoeff', one_smul])
fun {z y} ihz ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihz, ihy]
smul_zero _ := AddMonoidHom.map_zero _
instance smulCommClass' [SMulCommClass R₁ R₂ R] : SMulCommClass R₁ R₂ (⨂[R] i, s i) :=
⟨fun {r' r''} x ↦
PiTensorProduct.induction_on' x (fun {xr xf} ↦ by simp only [smul_tprodCoeff', smul_comm])
fun {z y} ihz ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihz, ihy]⟩
instance isScalarTower' [SMul R₁ R₂] [IsScalarTower R₁ R₂ R] :
IsScalarTower R₁ R₂ (⨂[R] i, s i) :=
⟨fun {r' r''} x ↦
PiTensorProduct.induction_on' x (fun {xr xf} ↦ by simp only [smul_tprodCoeff', smul_assoc])
fun {z y} ihz ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihz, ihy]⟩
end DistribMulAction
-- Most of the time we want the instance below this one, which is easier for typeclass resolution
-- to find.
instance module' [Semiring R₁] [Module R₁ R] [SMulCommClass R₁ R R] : Module R₁ (⨂[R] i, s i) :=
{ PiTensorProduct.distribMulAction' with
add_smul := fun r r' x ↦
PiTensorProduct.induction_on' x
(fun {r f} ↦ by simp_rw [smul_tprodCoeff', add_smul, add_tprodCoeff'])
fun {x y} ihx ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihx, ihy, add_add_add_comm]
zero_smul := fun x ↦
PiTensorProduct.induction_on' x
(fun {r f} ↦ by simp_rw [smul_tprodCoeff', zero_smul, zero_tprodCoeff])
fun {x y} ihx ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihx, ihy, add_zero] }
-- shortcut instances
instance : Module R (⨂[R] i, s i) :=
PiTensorProduct.module'
instance : SMulCommClass R R (⨂[R] i, s i) :=
PiTensorProduct.smulCommClass'
instance : IsScalarTower R R (⨂[R] i, s i) :=
PiTensorProduct.isScalarTower'
variable (R) in
/-- The canonical `MultilinearMap R s (⨂[R] i, s i)`.
`tprod R fun i => f i` has notation `⨂ₜ[R] i, f i`. -/
def tprod : MultilinearMap R s (⨂[R] i, s i) where
toFun := tprodCoeff R 1
map_update_add' {_ f} i x y := (add_tprodCoeff (1 : R) f i x y).symm
map_update_smul' {_ f} i r x := by
rw [smul_tprodCoeff', ← smul_tprodCoeff (1 : R) _ i, update_idem, update_self]
@[inherit_doc tprod]
notation3:100 "⨂ₜ["R"] "(...)", "r:(scoped f => tprod R f) => r
theorem tprod_eq_tprodCoeff_one :
⇑(tprod R : MultilinearMap R s (⨂[R] i, s i)) = tprodCoeff R 1 := rfl
@[simp]
theorem tprodCoeff_eq_smul_tprod (z : R) (f : Π i, s i) : tprodCoeff R z f = z • tprod R f := by
have : z = z • (1 : R) := by simp only [mul_one, Algebra.id.smul_eq_mul]
conv_lhs => rw [this]
rfl
/-- The image of an element `p` of `FreeAddMonoid (R × Π i, s i)` in the `PiTensorProduct` is
equal to the sum of `a • ⨂ₜ[R] i, m i` over all the entries `(a, m)` of `p`.
-/
lemma _root_.FreeAddMonoid.toPiTensorProduct (p : FreeAddMonoid (R × Π i, s i)) :
AddCon.toQuotient (c := addConGen (PiTensorProduct.Eqv R s)) p =
List.sum (List.map (fun x ↦ x.1 • ⨂ₜ[R] i, x.2 i) p.toList) := by
-- TODO: this is defeq abuse: `p` is not a `List`.
match p with
| [] => rw [FreeAddMonoid.toList_nil, List.map_nil, List.sum_nil]; rfl
| x :: ps =>
rw [FreeAddMonoid.toList_cons, List.map_cons, List.sum_cons, ← List.singleton_append,
← toPiTensorProduct ps, ← tprodCoeff_eq_smul_tprod]
rfl
/-- The set of lifts of an element `x` of `⨂[R] i, s i` in `FreeAddMonoid (R × Π i, s i)`. -/
def lifts (x : ⨂[R] i, s i) : Set (FreeAddMonoid (R × Π i, s i)) :=
{p | AddCon.toQuotient (c := addConGen (PiTensorProduct.Eqv R s)) p = x}
/-- An element `p` of `FreeAddMonoid (R × Π i, s i)` lifts an element `x` of `⨂[R] i, s i`
if and only if `x` is equal to the sum of `a • ⨂ₜ[R] i, m i` over all the entries
`(a, m)` of `p`.
-/
lemma mem_lifts_iff (x : ⨂[R] i, s i) (p : FreeAddMonoid (R × Π i, s i)) :
p ∈ lifts x ↔ List.sum (List.map (fun x ↦ x.1 • ⨂ₜ[R] i, x.2 i) p.toList) = x := by
simp only [lifts, Set.mem_setOf_eq, FreeAddMonoid.toPiTensorProduct]
/-- Every element of `⨂[R] i, s i` has a lift in `FreeAddMonoid (R × Π i, s i)`.
-/
lemma nonempty_lifts (x : ⨂[R] i, s i) : Set.Nonempty (lifts x) := by
existsi @Quotient.out _ (addConGen (PiTensorProduct.Eqv R s)).toSetoid x
simp only [lifts, Set.mem_setOf_eq]
rw [← AddCon.quot_mk_eq_coe]
erw [Quot.out_eq]
/-- The empty list lifts the element `0` of `⨂[R] i, s i`.
-/
lemma lifts_zero : 0 ∈ lifts (0 : ⨂[R] i, s i) := by
rw [mem_lifts_iff, FreeAddMonoid.toList_zero, List.map_nil, List.sum_nil]
/-- If elements `p,q` of `FreeAddMonoid (R × Π i, s i)` lift elements `x,y` of `⨂[R] i, s i`
respectively, then `p + q` lifts `x + y`.
-/
lemma lifts_add {x y : ⨂[R] i, s i} {p q : FreeAddMonoid (R × Π i, s i)}
(hp : p ∈ lifts x) (hq : q ∈ lifts y) : p + q ∈ lifts (x + y) := by
simp only [lifts, Set.mem_setOf_eq, AddCon.coe_add]
rw [hp, hq]
/-- If an element `p` of `FreeAddMonoid (R × Π i, s i)` lifts an element `x` of `⨂[R] i, s i`,
and if `a` is an element of `R`, then the list obtained by multiplying the first entry of each
element of `p` by `a` lifts `a • x`.
-/
lemma lifts_smul {x : ⨂[R] i, s i} {p : FreeAddMonoid (R × Π i, s i)} (h : p ∈ lifts x) (a : R) :
p.map (fun (y : R × Π i, s i) ↦ (a * y.1, y.2)) ∈ lifts (a • x) := by
rw [mem_lifts_iff] at h ⊢
rw [← h]
simp [Function.comp_def, mul_smul, List.smul_sum]
/-- Induct using scaled versions of `PiTensorProduct.tprod`. -/
@[elab_as_elim]
protected theorem induction_on {motive : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i)
(smul_tprod : ∀ (r : R) (f : Π i, s i), motive (r • tprod R f))
(add : ∀ x y, motive x → motive y → motive (x + y)) :
motive z := by
simp_rw [← tprodCoeff_eq_smul_tprod] at smul_tprod
exact PiTensorProduct.induction_on' z smul_tprod add
@[ext]
theorem ext {φ₁ φ₂ : (⨂[R] i, s i) →ₗ[R] E}
(H : φ₁.compMultilinearMap (tprod R) = φ₂.compMultilinearMap (tprod R)) : φ₁ = φ₂ := by
refine LinearMap.ext ?_
refine fun z ↦
PiTensorProduct.induction_on' z ?_ fun {x y} hx hy ↦ by rw [φ₁.map_add, φ₂.map_add, hx, hy]
· intro r f
rw [tprodCoeff_eq_smul_tprod, φ₁.map_smul, φ₂.map_smul]
apply congr_arg
exact MultilinearMap.congr_fun H f
/-- The pure tensors (i.e. the elements of the image of `PiTensorProduct.tprod`) span
the tensor product. -/
theorem span_tprod_eq_top :
Submodule.span R (Set.range (tprod R)) = (⊤ : Submodule R (⨂[R] i, s i)) :=
Submodule.eq_top_iff'.mpr fun t ↦ t.induction_on
(fun _ _ ↦ Submodule.smul_mem _ _
(Submodule.subset_span (by simp only [Set.mem_range, exists_apply_eq_apply])))
(fun _ _ hx hy ↦ Submodule.add_mem _ hx hy)
end Module
section Multilinear
open MultilinearMap
variable {s}
section lift
/-- Auxiliary function to constructing a linear map `(⨂[R] i, s i) → E` given a
`MultilinearMap R s E` with the property that its composition with the canonical
`MultilinearMap R s (⨂[R] i, s i)` is the given multilinear map. -/
def liftAux (φ : MultilinearMap R s E) : (⨂[R] i, s i) →+ E :=
liftAddHom (fun p : R × Π i, s i ↦ p.1 • φ p.2)
(fun z f i hf ↦ by simp_rw [map_coord_zero φ i hf, smul_zero])
(fun f ↦ by simp_rw [zero_smul])
(fun z f i m₁ m₂ ↦ by simp_rw [← smul_add, φ.map_update_add])
(fun z₁ z₂ f ↦ by rw [← add_smul])
fun z f i r ↦ by simp [φ.map_update_smul, smul_smul, mul_comm]
theorem liftAux_tprod (φ : MultilinearMap R s E) (f : Π i, s i) : liftAux φ (tprod R f) = φ f := by
simp only [liftAux, liftAddHom, tprod_eq_tprodCoeff_one, tprodCoeff, AddCon.coe_mk']
-- The end of this proof was very different before https://github.com/leanprover/lean4/pull/2644:
-- rw [FreeAddMonoid.of, FreeAddMonoid.ofList, Equiv.refl_apply, AddCon.lift_coe]
-- dsimp [FreeAddMonoid.lift, FreeAddMonoid.sumAux]
-- show _ • _ = _
-- rw [one_smul]
erw [AddCon.lift_coe]
simp
theorem liftAux_tprodCoeff (φ : MultilinearMap R s E) (z : R) (f : Π i, s i) :
liftAux φ (tprodCoeff R z f) = z • φ f := rfl
theorem liftAux.smul {φ : MultilinearMap R s E} (r : R) (x : ⨂[R] i, s i) :
liftAux φ (r • x) = r • liftAux φ x := by
refine PiTensorProduct.induction_on' x ?_ ?_
· intro z f
rw [smul_tprodCoeff' r z f, liftAux_tprodCoeff, liftAux_tprodCoeff, smul_assoc]
· intro z y ihz ihy
rw [smul_add, (liftAux φ).map_add, ihz, ihy, (liftAux φ).map_add, smul_add]
/-- Constructing a linear map `(⨂[R] i, s i) → E` given a `MultilinearMap R s E` with the
property that its composition with the canonical `MultilinearMap R s E` is
the given multilinear map `φ`. -/
def lift : MultilinearMap R s E ≃ₗ[R] (⨂[R] i, s i) →ₗ[R] E where
toFun φ := { liftAux φ with map_smul' := liftAux.smul }
invFun φ' := φ'.compMultilinearMap (tprod R)
left_inv φ := by
ext
simp [liftAux_tprod, LinearMap.compMultilinearMap]
right_inv φ := by
ext
simp [liftAux_tprod]
map_add' φ₁ φ₂ := by
ext
simp [liftAux_tprod]
map_smul' r φ₂ := by
ext
simp [liftAux_tprod]
variable {φ : MultilinearMap R s E}
@[simp]
theorem lift.tprod (f : Π i, s i) : lift φ (tprod R f) = φ f :=
liftAux_tprod φ f
theorem lift.unique' {φ' : (⨂[R] i, s i) →ₗ[R] E}
(H : φ'.compMultilinearMap (PiTensorProduct.tprod R) = φ) : φ' = lift φ :=
ext <| H.symm ▸ (lift.symm_apply_apply φ).symm
theorem lift.unique {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : ∀ f, φ' (PiTensorProduct.tprod R f) = φ f) :
φ' = lift φ :=
lift.unique' (MultilinearMap.ext H)
@[simp]
theorem lift_symm (φ' : (⨂[R] i, s i) →ₗ[R] E) : lift.symm φ' = φ'.compMultilinearMap (tprod R) :=
rfl
@[simp]
theorem lift_tprod : lift (tprod R : MultilinearMap R s _) = LinearMap.id :=
Eq.symm <| lift.unique' rfl
end lift
section map
variable {t t' : ι → Type*}
variable [∀ i, AddCommMonoid (t i)] [∀ i, Module R (t i)]
variable [∀ i, AddCommMonoid (t' i)] [∀ i, Module R (t' i)]
variable (g : Π i, t i →ₗ[R] t' i) (f : Π i, s i →ₗ[R] t i)
/--
Let `sᵢ` and `tᵢ` be two families of `R`-modules.
Let `f` be a family of `R`-linear maps between `sᵢ` and `tᵢ`, i.e. `f : Πᵢ sᵢ → tᵢ`,
then there is an induced map `⨂ᵢ sᵢ → ⨂ᵢ tᵢ` by `⨂ aᵢ ↦ ⨂ fᵢ aᵢ`.
This is `TensorProduct.map` for an arbitrary family of modules.
-/
def map : (⨂[R] i, s i) →ₗ[R] ⨂[R] i, t i :=
lift <| (tprod R).compLinearMap f
@[simp] lemma map_tprod (x : Π i, s i) :
map f (tprod R x) = tprod R fun i ↦ f i (x i) :=
lift.tprod _
-- No lemmas about associativity, because we don't have associativity of `PiTensorProduct` yet.
theorem map_range_eq_span_tprod :
LinearMap.range (map f) =
Submodule.span R {t | ∃ (m : Π i, s i), tprod R (fun i ↦ f i (m i)) = t} := by
rw [← Submodule.map_top, ← span_tprod_eq_top, Submodule.map_span, ← Set.range_comp]
apply congrArg; ext x
simp only [Set.mem_range, comp_apply, map_tprod, Set.mem_setOf_eq]
/-- Given submodules `p i ⊆ s i`, this is the natural map: `⨂[R] i, p i → ⨂[R] i, s i`.
This is `TensorProduct.mapIncl` for an arbitrary family of modules.
-/
@[simp]
def mapIncl (p : Π i, Submodule R (s i)) : (⨂[R] i, p i) →ₗ[R] ⨂[R] i, s i :=
map fun (i : ι) ↦ (p i).subtype
theorem map_comp : map (fun (i : ι) ↦ g i ∘ₗ f i) = map g ∘ₗ map f := by
ext
simp only [LinearMap.compMultilinearMap_apply, map_tprod, LinearMap.coe_comp, Function.comp_apply]
theorem lift_comp_map (h : MultilinearMap R t E) :
lift h ∘ₗ map f = lift (h.compLinearMap f) := by
ext
simp only [LinearMap.compMultilinearMap_apply, LinearMap.coe_comp, Function.comp_apply,
map_tprod, lift.tprod, MultilinearMap.compLinearMap_apply]
attribute [local ext high] ext
@[simp]
theorem map_id : map (fun i ↦ (LinearMap.id : s i →ₗ[R] s i)) = .id := by
ext
simp only [LinearMap.compMultilinearMap_apply, map_tprod, LinearMap.id_coe, id_eq]
@[simp]
protected theorem map_one : map (fun (i : ι) ↦ (1 : s i →ₗ[R] s i)) = 1 :=
map_id
protected theorem map_mul (f₁ f₂ : Π i, s i →ₗ[R] s i) :
map (fun i ↦ f₁ i * f₂ i) = map f₁ * map f₂ :=
map_comp f₁ f₂
/-- Upgrading `PiTensorProduct.map` to a `MonoidHom` when `s = t`. -/
@[simps]
def mapMonoidHom : (Π i, s i →ₗ[R] s i) →* ((⨂[R] i, s i) →ₗ[R] ⨂[R] i, s i) where
toFun := map
map_one' := PiTensorProduct.map_one
map_mul' := PiTensorProduct.map_mul
@[simp]
protected theorem map_pow (f : Π i, s i →ₗ[R] s i) (n : ℕ) :
map (f ^ n) = map f ^ n := MonoidHom.map_pow mapMonoidHom _ _
open Function in
private theorem map_add_smul_aux [DecidableEq ι] (i : ι) (x : Π i, s i) (u : s i →ₗ[R] t i) :
(fun j ↦ update f i u j (x j)) = update (fun j ↦ (f j) (x j)) i (u (x i)) := by
ext j
exact apply_update (fun i F => F (x i)) f i u j
open Function in
protected theorem map_update_add [DecidableEq ι] (i : ι) (u v : s i →ₗ[R] t i) :
map (update f i (u + v)) = map (update f i u) + map (update f i v) := by
ext x
simp only [LinearMap.compMultilinearMap_apply, map_tprod, map_add_smul_aux, LinearMap.add_apply,
MultilinearMap.map_update_add]
open Function in
protected theorem map_update_smul [DecidableEq ι] (i : ι) (c : R) (u : s i →ₗ[R] t i) :
map (update f i (c • u)) = c • map (update f i u) := by
ext x
simp only [LinearMap.compMultilinearMap_apply, map_tprod, map_add_smul_aux, LinearMap.smul_apply,
MultilinearMap.map_update_smul]
variable (R s t)
/-- The tensor of a family of linear maps from `sᵢ` to `tᵢ`, as a multilinear map of
the family.
-/
@[simps]
noncomputable def mapMultilinear :
MultilinearMap R (fun (i : ι) ↦ s i →ₗ[R] t i) ((⨂[R] i, s i) →ₗ[R] ⨂[R] i, t i) where
toFun := map
map_update_smul' _ _ _ _ := PiTensorProduct.map_update_smul _ _ _ _
map_update_add' _ _ _ _ := PiTensorProduct.map_update_add _ _ _ _
variable {R s t}
/--
Let `sᵢ` and `tᵢ` be families of `R`-modules.
Then there is an `R`-linear map between `⨂ᵢ Hom(sᵢ, tᵢ)` and `Hom(⨂ᵢ sᵢ, ⨂ tᵢ)` defined by
`⨂ᵢ fᵢ ↦ ⨂ᵢ aᵢ ↦ ⨂ᵢ fᵢ aᵢ`.
This is `TensorProduct.homTensorHomMap` for an arbitrary family of modules.
Note that `PiTensorProduct.piTensorHomMap (tprod R f)` is equal to `PiTensorProduct.map f`.
-/
def piTensorHomMap : (⨂[R] i, s i →ₗ[R] t i) →ₗ[R] (⨂[R] i, s i) →ₗ[R] ⨂[R] i, t i :=
lift.toLinearMap ∘ₗ lift (MultilinearMap.piLinearMap <| tprod R)
@[simp] lemma piTensorHomMap_tprod_tprod (f : Π i, s i →ₗ[R] t i) (x : Π i, s i) :
piTensorHomMap (tprod R f) (tprod R x) = tprod R fun i ↦ f i (x i) := by
simp [piTensorHomMap]
lemma piTensorHomMap_tprod_eq_map (f : Π i, s i →ₗ[R] t i) :
piTensorHomMap (tprod R f) = map f := by
ext; simp
/-- If `s i` and `t i` are linearly equivalent for every `i` in `ι`, then `⨂[R] i, s i` and
`⨂[R] i, t i` are linearly equivalent.
This is the n-ary version of `TensorProduct.congr`
-/
noncomputable def congr (f : Π i, s i ≃ₗ[R] t i) :
(⨂[R] i, s i) ≃ₗ[R] ⨂[R] i, t i :=
.ofLinear
(map (fun i ↦ f i))
(map (fun i ↦ (f i).symm))
(by ext; simp)
(by ext; simp)
@[simp]
theorem congr_tprod (f : Π i, s i ≃ₗ[R] t i) (m : Π i, s i) :
congr f (tprod R m) = tprod R (fun (i : ι) ↦ (f i) (m i)) := by
simp only [congr, LinearEquiv.ofLinear_apply, map_tprod, LinearEquiv.coe_coe]
@[simp]
theorem congr_symm_tprod (f : Π i, s i ≃ₗ[R] t i) (p : Π i, t i) :
(congr f).symm (tprod R p) = tprod R (fun (i : ι) ↦ (f i).symm (p i)) := by
simp only [congr, LinearEquiv.ofLinear_symm_apply, map_tprod, LinearEquiv.coe_coe]
/--
Let `sᵢ`, `tᵢ` and `t'ᵢ` be families of `R`-modules, then `f : Πᵢ sᵢ → tᵢ → t'ᵢ` induces an
element of `Hom(⨂ᵢ sᵢ, Hom(⨂ tᵢ, ⨂ᵢ t'ᵢ))` defined by `⨂ᵢ aᵢ ↦ ⨂ᵢ bᵢ ↦ ⨂ᵢ fᵢ aᵢ bᵢ`.
This is `PiTensorProduct.map` for two arbitrary families of modules.
This is `TensorProduct.map₂` for families of modules.
-/
def map₂ (f : Π i, s i →ₗ[R] t i →ₗ[R] t' i) :
(⨂[R] i, s i) →ₗ[R] (⨂[R] i, t i) →ₗ[R] ⨂[R] i, t' i :=
lift <| LinearMap.compMultilinearMap piTensorHomMap <| (tprod R).compLinearMap f
lemma map₂_tprod_tprod (f : Π i, s i →ₗ[R] t i →ₗ[R] t' i) (x : Π i, s i) (y : Π i, t i) :
map₂ f (tprod R x) (tprod R y) = tprod R fun i ↦ f i (x i) (y i) := by
simp [map₂]
/--
Let `sᵢ`, `tᵢ` and `t'ᵢ` be families of `R`-modules.
Then there is a function from `⨂ᵢ Hom(sᵢ, Hom(tᵢ, t'ᵢ))` to `Hom(⨂ᵢ sᵢ, Hom(⨂ tᵢ, ⨂ᵢ t'ᵢ))`
defined by `⨂ᵢ fᵢ ↦ ⨂ᵢ aᵢ ↦ ⨂ᵢ bᵢ ↦ ⨂ᵢ fᵢ aᵢ bᵢ`. -/
def piTensorHomMapFun₂ : (⨂[R] i, s i →ₗ[R] t i →ₗ[R] t' i) →
(⨂[R] i, s i) →ₗ[R] (⨂[R] i, t i) →ₗ[R] (⨂[R] i, t' i) :=
fun φ => lift <| LinearMap.compMultilinearMap piTensorHomMap <|
(lift <| MultilinearMap.piLinearMap <| tprod R) φ
theorem piTensorHomMapFun₂_add (φ ψ : ⨂[R] i, s i →ₗ[R] t i →ₗ[R] t' i) :
piTensorHomMapFun₂ (φ + ψ) = piTensorHomMapFun₂ φ + piTensorHomMapFun₂ ψ := by
dsimp [piTensorHomMapFun₂]; ext; simp only [map_add, LinearMap.compMultilinearMap_apply,
lift.tprod, add_apply, LinearMap.add_apply]
theorem piTensorHomMapFun₂_smul (r : R) (φ : ⨂[R] i, s i →ₗ[R] t i →ₗ[R] t' i) :
piTensorHomMapFun₂ (r • φ) = r • piTensorHomMapFun₂ φ := by
dsimp [piTensorHomMapFun₂]; ext; simp only [map_smul, LinearMap.compMultilinearMap_apply,
lift.tprod, smul_apply, LinearMap.smul_apply]
/--
Let `sᵢ`, `tᵢ` and `t'ᵢ` be families of `R`-modules.
Then there is an linear map from `⨂ᵢ Hom(sᵢ, Hom(tᵢ, t'ᵢ))` to `Hom(⨂ᵢ sᵢ, Hom(⨂ tᵢ, ⨂ᵢ t'ᵢ))`
defined by `⨂ᵢ fᵢ ↦ ⨂ᵢ aᵢ ↦ ⨂ᵢ bᵢ ↦ ⨂ᵢ fᵢ aᵢ bᵢ`.
This is `TensorProduct.homTensorHomMap` for two arbitrary families of modules.
-/
def piTensorHomMap₂ : (⨂[R] i, s i →ₗ[R] t i →ₗ[R] t' i) →ₗ[R]
(⨂[R] i, s i) →ₗ[R] (⨂[R] i, t i) →ₗ[R] (⨂[R] i, t' i) where
toFun := piTensorHomMapFun₂
map_add' x y := piTensorHomMapFun₂_add x y
map_smul' x y := piTensorHomMapFun₂_smul x y
@[simp] lemma piTensorHomMap₂_tprod_tprod_tprod
(f : ∀ i, s i →ₗ[R] t i →ₗ[R] t' i) (a : ∀ i, s i) (b : ∀ i, t i) :
piTensorHomMap₂ (tprod R f) (tprod R a) (tprod R b) = tprod R (fun i ↦ f i (a i) (b i)) := by
simp [piTensorHomMapFun₂, piTensorHomMap₂]
end map
section
variable (R M)
variable (s) in
/-- Re-index the components of the tensor power by `e`. -/
def reindex (e : ι ≃ ι₂) : (⨂[R] i : ι, s i) ≃ₗ[R] ⨂[R] i : ι₂, s (e.symm i) :=
let f := domDomCongrLinearEquiv' R R s (⨂[R] (i : ι₂), s (e.symm i)) e
let g := domDomCongrLinearEquiv' R R s (⨂[R] (i : ι), s i) e
LinearEquiv.ofLinear (lift <| f.symm <| tprod R) (lift <| g <| tprod R) (by aesop) (by aesop)
end
@[simp]
theorem reindex_tprod (e : ι ≃ ι₂) (f : Π i, s i) :
reindex R s e (tprod R f) = tprod R fun i ↦ f (e.symm i) := by
dsimp [reindex]
exact liftAux_tprod _ f
@[simp]
theorem reindex_comp_tprod (e : ι ≃ ι₂) :
(reindex R s e).compMultilinearMap (tprod R) =
(domDomCongrLinearEquiv' R R s _ e).symm (tprod R) :=
MultilinearMap.ext <| reindex_tprod e
theorem lift_comp_reindex (e : ι ≃ ι₂) (φ : MultilinearMap R (fun i ↦ s (e.symm i)) E) :
lift φ ∘ₗ (reindex R s e) = lift ((domDomCongrLinearEquiv' R R s _ e).symm φ) := by
ext; simp [reindex]
@[simp]
theorem lift_comp_reindex_symm (e : ι ≃ ι₂) (φ : MultilinearMap R s E) :
lift φ ∘ₗ (reindex R s e).symm = lift (domDomCongrLinearEquiv' R R s _ e φ) := by
ext; simp [reindex]
theorem lift_reindex
(e : ι ≃ ι₂) (φ : MultilinearMap R (fun i ↦ s (e.symm i)) E) (x : ⨂[R] i, s i) :
lift φ (reindex R s e x) = lift ((domDomCongrLinearEquiv' R R s _ e).symm φ) x :=
LinearMap.congr_fun (lift_comp_reindex e φ) x
@[simp]
theorem lift_reindex_symm
(e : ι ≃ ι₂) (φ : MultilinearMap R s E) (x : ⨂[R] i, s (e.symm i)) :
lift φ (reindex R s e |>.symm x) = lift (domDomCongrLinearEquiv' R R s _ e φ) x :=
LinearMap.congr_fun (lift_comp_reindex_symm e φ) x
@[simp]
theorem reindex_trans (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) :
(reindex R s e).trans (reindex R _ e') = reindex R s (e.trans e') := by
apply LinearEquiv.toLinearMap_injective
ext f
simp only [LinearEquiv.trans_apply, LinearEquiv.coe_coe, reindex_tprod,
LinearMap.coe_compMultilinearMap, Function.comp_apply,
reindex_comp_tprod]
congr
theorem reindex_reindex (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) (x : ⨂[R] i, s i) :
reindex R _ e' (reindex R s e x) = reindex R s (e.trans e') x :=
LinearEquiv.congr_fun (reindex_trans e e' : _ = reindex R s (e.trans e')) x
/-- This lemma is impractical to state in the dependent case. -/
@[simp]
theorem reindex_symm (e : ι ≃ ι₂) :
(reindex R (fun _ ↦ M) e).symm = reindex R (fun _ ↦ M) e.symm := by
ext x
simp [reindex]
@[simp]
theorem reindex_refl : reindex R s (Equiv.refl ι) = LinearEquiv.refl R _ := by
apply LinearEquiv.toLinearMap_injective
ext
simp only [Equiv.refl_symm, Equiv.refl_apply, reindex, domDomCongrLinearEquiv',
LinearEquiv.coe_symm_mk, LinearMap.compMultilinearMap_apply, LinearEquiv.coe_coe,
LinearEquiv.refl_toLinearMap, LinearMap.id_coe, id_eq]
simp
variable {t : ι → Type*}
variable [∀ i, AddCommMonoid (t i)] [∀ i, Module R (t i)]
/-- Re-indexing the components of the tensor product by an equivalence `e` is compatible
with `PiTensorProduct.map`. -/
theorem map_comp_reindex_eq (f : Π i, s i →ₗ[R] t i) (e : ι ≃ ι₂) :
map (fun i ↦ f (e.symm i)) ∘ₗ reindex R s e = reindex R t e ∘ₗ map f := by
ext m
simp only [LinearMap.compMultilinearMap_apply, LinearEquiv.coe_coe,
LinearMap.comp_apply, reindex_tprod, map_tprod]
theorem map_reindex (f : Π i, s i →ₗ[R] t i) (e : ι ≃ ι₂) (x : ⨂[R] i, s i) :
map (fun i ↦ f (e.symm i)) (reindex R s e x) = reindex R t e (map f x) :=
DFunLike.congr_fun (map_comp_reindex_eq _ _) _
theorem map_comp_reindex_symm (f : Π i, s i →ₗ[R] t i) (e : ι ≃ ι₂) :
map f ∘ₗ (reindex R s e).symm = (reindex R t e).symm ∘ₗ map (fun i => f (e.symm i)) := by
ext m
apply LinearEquiv.injective (reindex R t e)
simp only [LinearMap.compMultilinearMap_apply, LinearMap.coe_comp, LinearEquiv.coe_coe,
comp_apply, ← map_reindex, LinearEquiv.apply_symm_apply, map_tprod]
theorem map_reindex_symm (f : Π i, s i →ₗ[R] t i) (e : ι ≃ ι₂) (x : ⨂[R] i, s (e.symm i)) :
map f ((reindex R s e).symm x) = (reindex R t e).symm (map (fun i ↦ f (e.symm i)) x) :=
DFunLike.congr_fun (map_comp_reindex_symm _ _) _
variable (ι)
attribute [local simp] eq_iff_true_of_subsingleton in
/-- The tensor product over an empty index type `ι` is isomorphic to the base ring. -/
@[simps symm_apply]
def isEmptyEquiv [IsEmpty ι] : (⨂[R] i : ι, s i) ≃ₗ[R] R where
toFun := lift (constOfIsEmpty R _ 1)
invFun r := r • tprod R (@isEmptyElim _ _ _)
left_inv x := by
refine x.induction_on ?_ ?_
· intro x y
simp only [map_smulₛₗ, RingHom.id_apply, lift.tprod, constOfIsEmpty_apply, const_apply,
smul_eq_mul, mul_one]
congr
aesop
· simp only
intro x y hx hy
rw [map_add, add_smul, hx, hy]
right_inv t := by simp
map_add' := LinearMap.map_add _
map_smul' := fun r x => by
exact LinearMap.map_smul _ r x
@[simp]
theorem isEmptyEquiv_apply_tprod [IsEmpty ι] (f : Π i, s i) :
isEmptyEquiv ι (tprod R f) = 1 :=
lift.tprod _
variable {ι}
/--
Tensor product of `M` over a singleton set is equivalent to `M`
-/
@[simps symm_apply]
def subsingletonEquiv [Subsingleton ι] (i₀ : ι) : (⨂[R] _ : ι, M) ≃ₗ[R] M where
toFun := lift (MultilinearMap.ofSubsingleton R M M i₀ .id)
invFun m := tprod R fun _ ↦ m
left_inv x := by
dsimp only
have : ∀ (f : ι → M) (z : M), (fun _ : ι ↦ z) = update f i₀ z := fun f z ↦ by
ext i
rw [Subsingleton.elim i i₀, Function.update_self]
refine x.induction_on ?_ ?_
· intro r f
simp only [LinearMap.map_smul, LinearMap.id_apply, lift.tprod, ofSubsingleton_apply_apply,
this f, MultilinearMap.map_update_smul, update_eq_self]
· intro x y hx hy
rw [LinearMap.map_add, this 0 (_ + _), MultilinearMap.map_update_add, ← this 0 (lift _ _), hx,
← this 0 (lift _ _), hy]
right_inv t := by simp only [ofSubsingleton_apply_apply, LinearMap.id_apply, lift.tprod]
map_add' := LinearMap.map_add _
map_smul' := fun r x => by
exact LinearMap.map_smul _ r x
@[simp]
theorem subsingletonEquiv_apply_tprod [Subsingleton ι] (i : ι) (f : ι → M) :
subsingletonEquiv i (tprod R f) = f i :=
lift.tprod _
variable (R M)
section tmulEquivDep
variable (N : ι ⊕ ι₂ → Type*) [∀ i, AddCommMonoid (N i)] [∀ i, Module R (N i)]
/-- Equivalence between a `TensorProduct` of `PiTensorProduct`s and a single
`PiTensorProduct` indexed by a `Sum` type. If `N` is a constant family of
modules, use the non-dependent version `PiTensorProduct.tmulEquiv` instead. -/
def tmulEquivDep :
(⨂[R] i₁, N (.inl i₁)) ⊗[R] (⨂[R] i₂, N (.inr i₂)) ≃ₗ[R] ⨂[R] i, N i :=
LinearEquiv.ofLinear
(TensorProduct.lift
{ toFun a := PiTensorProduct.lift (PiTensorProduct.lift
(MultilinearMap.currySumEquiv (tprod R)) a)
map_add' := by simp
map_smul' := by simp })
(PiTensorProduct.lift (MultilinearMap.domCoprodDep (tprod R) (tprod R))) (by
ext
dsimp
simp only [lift.tprod, domCoprodDep_apply, lift.tmul, LinearMap.coe_mk, AddHom.coe_mk,
currySum_apply]
congr
ext (_ | _) <;> simp)
(TensorProduct.ext (by aesop))
@[simp]
lemma tmulEquivDep_apply (a : (i₁ : ι) → N (.inl i₁))
(b : (i₂ : ι₂) → N (.inr i₂)) :
tmulEquivDep R N ((⨂ₜ[R] i₁, a i₁) ⊗ₜ (⨂ₜ[R] i₂, b i₂)) =
(⨂ₜ[R] i, Sum.rec a b i) := by
simp [tmulEquivDep]
@[simp]
lemma tmulEquivDep_symm_apply (f : (i : ι ⊕ ι₂) → N i) :
(tmulEquivDep R N).symm (⨂ₜ[R] i, f i) =
((⨂ₜ[R] i₁, f (.inl i₁)) ⊗ₜ (⨂ₜ[R] i₂, f (.inr i₂))) := by
simp [tmulEquivDep]
end tmulEquivDep
section tmulEquiv
/-- Equivalence between a `TensorProduct` of `PiTensorProduct`s and a single
`PiTensorProduct` indexed by a `Sum` type.
See `PiTensorProduct.tmulEquivDep` for the dependent version. -/
def tmulEquiv :
(⨂[R] (_ : ι), M) ⊗[R] (⨂[R] (_ : ι₂), M) ≃ₗ[R] ⨂[R] (_ : ι ⊕ ι₂), M :=
tmulEquivDep R (fun _ ↦ M)
@[simp]
theorem tmulEquiv_apply (a : ι → M) (b : ι₂ → M) :
tmulEquiv R M ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, Sum.elim a b i := by
simp [tmulEquiv, Sum.elim]
@[simp]
theorem tmulEquiv_symm_apply (a : ι ⊕ ι₂ → M) :
(tmulEquiv R M).symm (⨂ₜ[R] i, a i) =
(⨂ₜ[R] i, a (Sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (Sum.inr i)) := by
simp [tmulEquiv]
end tmulEquiv
end Multilinear
end PiTensorProduct
end Semiring
section Ring
namespace PiTensorProduct
open PiTensorProduct
open TensorProduct
variable {ι : Type*} {R : Type*} [CommRing R]
variable {s : ι → Type*} [∀ i, AddCommGroup (s i)] [∀ i, Module R (s i)]
/- Unlike for the binary tensor product, we require `R` to be a `CommRing` here, otherwise
this is false in the case where `ι` is empty. -/
instance : AddCommGroup (⨂[R] i, s i) :=
Module.addCommMonoidToAddCommGroup R
end PiTensorProduct
end Ring |
.lake/packages/mathlib/Mathlib/LinearAlgebra/LeftExact.lean | import Mathlib.Algebra.Exact
import Mathlib.LinearAlgebra.BilinearMap
/-!
# The Left Exactness of Hom
If `M1 → M2 → M3 → 0` is an exact sequence of `R`-modules and `N` is a `R`-module,
then `0 → (M3 →ₗ[R] N) → (M2 →ₗ[R] N) → (M1 →ₗ[R] N)` is exact. In this file, we
show the exactness at `M2 →ₗ[R] N` (`exact_lcomp_of_exact_of_surjective`);
the injectivity part is `LinearMap.lcomp_injective_of_surjective` in the file
`Mathlib.LinearAlgebra.BilinearMap`.
-/
namespace LinearMap
variable {R : Type*} [CommRing R] {M1 M2 M3 : Type*} (N : Type*)
[AddCommGroup M1] [AddCommGroup M2] [AddCommGroup M3] [AddCommGroup N]
[Module R M1] [Module R M2] [Module R M3] [Module R N]
lemma exact_lcomp_of_exact_of_surjective {f : M1 →ₗ[R] M2} {g : M2 →ₗ[R] M3}
(exac : Function.Exact f g) (surj : Function.Surjective g) :
Function.Exact (LinearMap.lcomp R N g) (LinearMap.lcomp R N f) := by
intro h
simp only [LinearMap.lcomp_apply', Set.mem_range]
refine ⟨fun hh ↦ ?_, fun ⟨y, hy⟩ ↦ ?_⟩
· use ((LinearMap.range f).liftQ h (LinearMap.range_le_ker_iff.mpr hh)).comp
(exac.linearEquivOfSurjective surj).symm.toLinearMap
ext x
simp
· rw [← hy, LinearMap.comp_assoc, exac.linearMap_comp_eq_zero, LinearMap.comp_zero y]
end LinearMap |
.lake/packages/mathlib/Mathlib/LinearAlgebra/CrossProduct.lean | import Mathlib.Algebra.Lie.Basic
import Mathlib.LinearAlgebra.BilinearMap
import Mathlib.LinearAlgebra.LinearIndependent.Lemmas
import Mathlib.LinearAlgebra.Matrix.Determinant.Basic
import Mathlib.LinearAlgebra.Matrix.Notation
/-!
# Cross products
This module defines the cross product of vectors in $R^3$ for $R$ a commutative ring,
as a bilinear map.
## Main definitions
* `crossProduct` is the cross product of pairs of vectors in $R^3$.
## Main results
* `triple_product_eq_det`
* `cross_dot_cross`
* `jacobi_cross`
## Notation
The scope `Matrix` gives the following notation:
* `⨯₃` for the cross product
## Tags
cross product
-/
open Matrix
variable {R : Type*} [CommRing R]
/-- The cross product of two vectors in $R^3$ for $R$ a commutative ring. -/
def crossProduct : (Fin 3 → R) →ₗ[R] (Fin 3 → R) →ₗ[R] Fin 3 → R := by
apply LinearMap.mk₂ R fun a b : Fin 3 → R =>
![a 1 * b 2 - a 2 * b 1, a 2 * b 0 - a 0 * b 2, a 0 * b 1 - a 1 * b 0]
· intros
simp_rw [vec3_add, Pi.add_apply]
apply vec3_eq <;> ring
· intros
simp_rw [smul_vec3, Pi.smul_apply, smul_sub, smul_mul_assoc]
· intros
simp_rw [vec3_add, Pi.add_apply]
apply vec3_eq <;> ring
· intros
simp_rw [smul_vec3, Pi.smul_apply, smul_sub, mul_smul_comm]
@[inherit_doc] scoped[Matrix] infixl:74 " ⨯₃ " => crossProduct
namespace Matrix
/-- A deprecated notation for `⨯₃`. -/
@[deprecated «term_⨯₃_» (since := "2025-07-11")]
scoped syntax:74 (name := _root_.«term_×₃_») term:74 " ×₃ " term:75 : term
end Matrix
open Lean Elab Meta.Tactic Term in
@[term_elab Matrix._root_.«term_×₃_», inherit_doc «term_×₃_»]
def elabDeprecatedCross : TermElab
| `($x ×₃%$tk $y) => fun ty? => do
logWarningAt tk <| .tagged ``Linter.deprecatedAttr <| m!"The ×₃ notation has been deprecated"
TryThis.addSuggestion tk { suggestion := "⨯₃" }
elabTerm (← `($x ⨯₃ $y)) ty?
| _ => fun _ => throwUnsupportedSyntax
theorem cross_apply (a b : Fin 3 → R) :
a ⨯₃ b = ![a 1 * b 2 - a 2 * b 1, a 2 * b 0 - a 0 * b 2, a 0 * b 1 - a 1 * b 0] := rfl
section ProductsProperties
@[simp]
theorem cross_anticomm (v w : Fin 3 → R) : -(v ⨯₃ w) = w ⨯₃ v := by
simp [cross_apply, mul_comm]
alias neg_cross := cross_anticomm
@[simp]
theorem cross_anticomm' (v w : Fin 3 → R) : v ⨯₃ w + w ⨯₃ v = 0 := by
rw [add_eq_zero_iff_eq_neg, cross_anticomm]
@[simp]
theorem cross_self (v : Fin 3 → R) : v ⨯₃ v = 0 := by
simp [cross_apply, mul_comm]
/-- The cross product of two vectors is perpendicular to the first vector. -/
@[simp]
theorem dot_self_cross (v w : Fin 3 → R) : v ⬝ᵥ v ⨯₃ w = 0 := by
rw [cross_apply, vec3_dotProduct]
dsimp only [Matrix.cons_val]
ring
/-- The cross product of two vectors is perpendicular to the second vector. -/
@[simp]
theorem dot_cross_self (v w : Fin 3 → R) : w ⬝ᵥ v ⨯₃ w = 0 := by
rw [← cross_anticomm, dotProduct_neg, dot_self_cross, neg_zero]
/-- Cyclic permutations preserve the triple product. See also `triple_product_eq_det`. -/
theorem triple_product_permutation (u v w : Fin 3 → R) : u ⬝ᵥ v ⨯₃ w = v ⬝ᵥ w ⨯₃ u := by
simp_rw [cross_apply, vec3_dotProduct]
dsimp only [Matrix.cons_val]
ring
/-- The triple product of `u`, `v`, and `w` is equal to the determinant of the matrix
with those vectors as its rows. -/
theorem triple_product_eq_det (u v w : Fin 3 → R) : u ⬝ᵥ v ⨯₃ w = Matrix.det ![u, v, w] := by
rw [vec3_dotProduct, cross_apply, det_fin_three]
dsimp only [Matrix.cons_val]
ring
/-- The scalar quadruple product identity, related to the Binet-Cauchy identity. -/
theorem cross_dot_cross (u v w x : Fin 3 → R) :
u ⨯₃ v ⬝ᵥ w ⨯₃ x = u ⬝ᵥ w * v ⬝ᵥ x - u ⬝ᵥ x * v ⬝ᵥ w := by
simp_rw [cross_apply, vec3_dotProduct]
dsimp only [Matrix.cons_val]
ring
end ProductsProperties
section LeibnizProperties
/-- The cross product satisfies the Leibniz lie property. -/
theorem leibniz_cross (u v w : Fin 3 → R) : u ⨯₃ (v ⨯₃ w) = u ⨯₃ v ⨯₃ w + v ⨯₃ (u ⨯₃ w) := by
simp_rw [cross_apply, vec3_add]
apply vec3_eq <;> dsimp <;> ring
/-- The three-dimensional vectors together with the operations + and ⨯₃ form a Lie ring.
Note we do not make this an instance as a conflicting one already exists
via `LieRing.ofAssociativeRing`. -/
def Cross.lieRing : LieRing (Fin 3 → R) :=
{ Pi.addCommGroup with
bracket := fun u v => u ⨯₃ v
add_lie := LinearMap.map_add₂ _
lie_add := fun _ => LinearMap.map_add _
lie_self := cross_self
leibniz_lie := leibniz_cross }
attribute [local instance] Cross.lieRing
theorem cross_cross (u v w : Fin 3 → R) : u ⨯₃ v ⨯₃ w = u ⨯₃ (v ⨯₃ w) - v ⨯₃ (u ⨯₃ w) :=
lie_lie u v w
/-- **Jacobi identity**: For a cross product of three vectors,
their sum over the three even permutations is equal to the zero vector. -/
theorem jacobi_cross (u v w : Fin 3 → R) : u ⨯₃ (v ⨯₃ w) + v ⨯₃ (w ⨯₃ u) + w ⨯₃ (u ⨯₃ v) = 0 :=
lie_jacobi u v w
end LeibnizProperties
-- this can also be proved via `dotProduct_eq_zero_iff` and `triple_product_eq_det`, but
-- that would require much heavier imports.
lemma crossProduct_ne_zero_iff_linearIndependent {F : Type*} [Field F] {v w : Fin 3 → F} :
crossProduct v w ≠ 0 ↔ LinearIndependent F ![v, w] := by
rw [not_iff_comm]
by_cases hv : v = 0
· rw [hv, map_zero, LinearMap.zero_apply, eq_self, iff_true]
exact fun h ↦ h.ne_zero 0 rfl
constructor
· rw [LinearIndependent.pair_iff' hv, not_forall_not]
rintro ⟨a, rfl⟩
rw [LinearMap.map_smul, cross_self, smul_zero]
have hv' : v = ![v 0, v 1, v 2] := by simp [← List.ofFn_inj]
have hw' : w = ![w 0, w 1, w 2] := by simp [← List.ofFn_inj]
intro h1 h2
simp_rw [cross_apply, cons_eq_zero_iff, zero_empty, and_true, sub_eq_zero] at h1
have h20 := LinearIndependent.pair_iff.mp h2 (- w 0) (v 0)
have h21 := LinearIndependent.pair_iff.mp h2 (- w 1) (v 1)
have h22 := LinearIndependent.pair_iff.mp h2 (- w 2) (v 2)
rw [neg_smul, neg_add_eq_zero, hv', hw', smul_vec3, smul_vec3, ← hv', ← hw'] at h20 h21 h22
simp only [smul_eq_mul, mul_comm (w 0), mul_comm (w 1), mul_comm (w 2), h1] at h20 h21 h22
rw [hv', cons_eq_zero_iff, cons_eq_zero_iff, cons_eq_zero_iff, zero_empty] at hv
exact hv ⟨(h20 trivial).2, (h21 trivial).2, (h22 trivial).2, rfl⟩
/-- The scalar triple product expansion of the vector triple product. -/
theorem cross_cross_eq_smul_sub_smul (u v w : Fin 3 → R) :
u ⨯₃ v ⨯₃ w = (u ⬝ᵥ w) • v - (v ⬝ᵥ w) • u := by
simp_rw [cross_apply, vec3_dotProduct]
ext i
fin_cases i <;>
· simp only [Fin.isValue, Nat.succ_eq_add_one, Nat.reduceAdd, Fin.reduceFinMk, cons_val,
Pi.sub_apply, Pi.smul_apply, smul_eq_mul]
ring
/-- Alternative form of the scalar triple product expansion of the vector triple product. -/
theorem cross_cross_eq_smul_sub_smul' (u v w : Fin 3 → R) :
u ⨯₃ (v ⨯₃ w) = (u ⬝ᵥ w) • v - (v ⬝ᵥ u) • w := by
simp_rw [cross_apply, vec3_dotProduct]
ext i
fin_cases i <;>
· simp only [Nat.succ_eq_add_one, Nat.reduceAdd, Fin.isValue, cons_val, cons_val_one,
cons_val_zero, Fin.reduceFinMk, Pi.sub_apply, Pi.smul_apply, smul_eq_mul]
ring |
.lake/packages/mathlib/Mathlib/LinearAlgebra/SesquilinearForm.lean | import Mathlib.LinearAlgebra.SesquilinearForm.Basic
deprecated_module (since := "2025-10-06") |
.lake/packages/mathlib/Mathlib/LinearAlgebra/Reflection.lean | import Mathlib.Algebra.EuclideanDomain.Basic
import Mathlib.Algebra.EuclideanDomain.Int
import Mathlib.Algebra.Module.LinearMap.Basic
import Mathlib.Algebra.Module.Submodule.Invariant
import Mathlib.Algebra.Module.Torsion.Basic
import Mathlib.GroupTheory.OrderOfElement
import Mathlib.LinearAlgebra.Dual.Defs
import Mathlib.LinearAlgebra.FiniteSpan
import Mathlib.RingTheory.Polynomial.Chebyshev
/-!
# Reflections in linear algebra
Given an element `x` in a module `M` together with a linear form `f` on `M` such that `f x = 2`, the
map `y ↦ y - (f y) • x` is an involutive endomorphism of `M`, such that:
1. the kernel of `f` is fixed,
2. the point `x ↦ -x`.
Such endomorphisms are often called reflections of the module `M`. When `M` carries an inner product
for which `x` is perpendicular to the kernel of `f`, then (with mild assumptions) the endomorphism
is characterised by properties 1 and 2 above, and is a linear isometry.
## Main definitions / results:
* `Module.preReflection`: the definition of the map `y ↦ y - (f y) • x`. Its main utility lies in
the fact that it does not require the assumption `f x = 2`, giving the user freedom to defer
discharging this proof obligation.
* `Module.reflection`: the definition of the map `y ↦ y - (f y) • x`. This requires the assumption
that `f x = 2` but by way of compensation it produces a linear equivalence rather than a mere
linear map.
* `Module.reflection_mul_reflection_pow_apply`: a formula for $(r_1 r_2)^m z$, where $r_1$ and
$r_2$ are reflections and $z \in M$. It involves the Chebyshev polynomials and holds over any
commutative ring. This is used to define reflection representations of Coxeter groups.
* `Module.Dual.eq_of_preReflection_mapsTo`: a uniqueness result about reflections that preserve
finite spanning sets. It is useful in the theory of root data / systems.
## TODO
Related definitions of reflection exists elsewhere in the library. These more specialised
definitions, which require an ambient `InnerProductSpace` structure, are `reflection` (of type
`LinearIsometryEquiv`) and `EuclideanGeometry.reflection` (of type `AffineIsometryEquiv`). We
should connect (or unify) these definitions with `Module.reflection` defined here.
-/
open Function Set
open Module hiding Finite
open Submodule (span)
noncomputable section
variable {R M : Type*} [CommRing R] [AddCommGroup M] [Module R M] (x : M) (f : Dual R M) (y : M)
namespace Module
/-- Given an element `x` in a module `M` and a linear form `f` on `M`, we define the endomorphism
of `M` for which `y ↦ y - (f y) • x`.
One is typically interested in this endomorphism when `f x = 2`; this definition exists to allow the
user defer discharging this proof obligation. See also `Module.reflection`. -/
def preReflection : End R M :=
LinearMap.id - f.smulRight x
lemma preReflection_apply :
preReflection x f y = y - (f y) • x := by
simp [preReflection]
variable {x f}
lemma preReflection_apply_self (h : f x = 2) :
preReflection x f x = - x := by
rw [preReflection_apply, h, two_smul]; abel
lemma involutive_preReflection (h : f x = 2) :
Involutive (preReflection x f) :=
fun y ↦ by simp [map_sub, h, two_smul, preReflection_apply]
lemma preReflection_preReflection (g : Dual R M) (h : f x = 2) :
preReflection (preReflection x f y) (preReflection f (Dual.eval R M x) g) =
(preReflection x f) ∘ₗ (preReflection y g) ∘ₗ (preReflection x f) := by
ext m
simp only [h, preReflection_apply, mul_comm (g x) (f m), mul_two, mul_assoc, Dual.eval_apply,
LinearMap.sub_apply, LinearMap.coe_comp, LinearMap.smul_apply, smul_eq_mul, smul_sub, sub_smul,
smul_smul, sub_mul, comp_apply, map_sub, map_smul, add_smul]
abel
/-- Given an element `x` in a module `M` and a linear form `f` on `M` for which `f x = 2`, we define
the endomorphism of `M` for which `y ↦ y - (f y) • x`.
It is an involutive endomorphism of `M` fixing the kernel of `f` for which `x ↦ -x`. -/
def reflection (h : f x = 2) : M ≃ₗ[R] M :=
{ preReflection x f, (involutive_preReflection h).toPerm with }
lemma reflection_apply (h : f x = 2) :
reflection h y = y - (f y) • x :=
preReflection_apply x f y
@[simp]
lemma reflection_apply_self (h : f x = 2) :
reflection h x = - x :=
preReflection_apply_self h
lemma involutive_reflection (h : f x = 2) :
Involutive (reflection h) :=
involutive_preReflection h
@[simp]
lemma reflection_inv (h : f x = 2) : (reflection h)⁻¹ = reflection h := rfl
@[simp]
lemma reflection_symm (h : f x = 2) :
(reflection h).symm = reflection h :=
rfl
lemma invOn_reflection_of_mapsTo {Φ : Set M} (h : f x = 2) :
InvOn (reflection h) (reflection h) Φ Φ :=
⟨fun x _ ↦ involutive_reflection h x, fun x _ ↦ involutive_reflection h x⟩
lemma bijOn_reflection_of_mapsTo {Φ : Set M} (h : f x = 2) (h' : MapsTo (reflection h) Φ Φ) :
BijOn (reflection h) Φ Φ :=
(invOn_reflection_of_mapsTo h).bijOn h' h'
lemma _root_.Submodule.mem_invtSubmodule_reflection_of_mem (h : f x = 2)
(p : Submodule R M) (hx : x ∈ p) :
p ∈ End.invtSubmodule (reflection h) := by
suffices ∀ y ∈ p, reflection h y ∈ p from
(End.mem_invtSubmodule _).mpr fun y hy ↦ by simpa using this y hy
intro y hy
simpa only [reflection_apply, p.sub_mem_iff_right hy] using p.smul_mem (f y) hx
lemma _root_.Submodule.mem_invtSubmodule_reflection_iff [NeZero (2 : R)] [NoZeroSMulDivisors R M]
(h : f x = 2) {p : Submodule R M} (hp : Disjoint p (R ∙ x)) :
p ∈ End.invtSubmodule (reflection h) ↔ p ≤ LinearMap.ker f := by
refine ⟨fun h' y hy ↦ ?_, fun h' y hy ↦ ?_⟩
· have hx : x ≠ 0 := by rintro rfl; exact two_ne_zero (α := R) <| by simp [← h]
suffices f y • x ∈ p by
have aux : f y • x ∈ p ⊓ (R ∙ x) := ⟨this, Submodule.mem_span_singleton.mpr ⟨f y, rfl⟩⟩
rw [hp.eq_bot, Submodule.mem_bot, smul_eq_zero] at aux
exact aux.resolve_right hx
specialize h' hy
simp only [Submodule.mem_comap, LinearEquiv.coe_coe, reflection_apply] at h'
simpa using p.sub_mem h' hy
· have hy' : f y = 0 := by simpa using h' hy
simpa [reflection_apply, hy']
/-! ### Powers of the product of two reflections
Let $M$ be a module over a commutative ring $R$. Let $x, y \in M$ and $f, g \in M^*$ with
$f(x) = g(y) = 2$. The corresponding reflections $r_1, r_2 \colon M \to M$ (`Module.reflection`) are
given by $r_1z = z - f(z) x$ and $r_2 z = z - g(z) y$. These are linear automorphisms of $M$.
To define reflection representations of a Coxeter group, it is important to be able to compute the
order of the composition $r_1 r_2$.
Note that if $M$ is a real inner product space and $r_1$ and $r_2$ are both orthogonal
reflections (i.e. $f(z) = 2 \langle x, z \rangle / \langle x, x \rangle$ and
$g(z) = 2 \langle y, z\rangle / \langle y, y\rangle$ for all $z \in M$),
then $r_1 r_2$ is a rotation by the angle
$$\cos^{-1}\left(\frac{f(y) g(x) - 2}{2}\right)$$
and one may determine the order of $r_1 r_2$ accordingly.
However, if $M$ does not have an inner product, and even if $R$ is not $\mathbb{R}$, then we may
instead use the formulas in this section. These formulas all involve evaluating Chebyshev
$S$-polynomials (`Polynomial.Chebyshev.S`) at $t = f(y) g(x) - 2$, and they hold over any
commutative ring. -/
section
open Int Polynomial.Chebyshev
variable {x y : M} {f g : Dual R M} (hf : f x = 2) (hg : g y = 2)
/-- A formula for $(r_1 r_2)^m z$, where $m$ is a natural number and $z \in M$. -/
lemma reflection_mul_reflection_pow_apply (m : ℕ) (z : M)
(t : R := f y * g x - 2) (ht : t = f y * g x - 2 := by rfl) :
((reflection hf * reflection hg) ^ m) z =
z +
((S R ((m - 2) / 2)).eval t * ((S R ((m - 1) / 2)).eval t + (S R ((m - 3) / 2)).eval t)) •
((g x * f z - g z) • y - f z • x) +
((S R ((m - 1) / 2)).eval t * ((S R (m / 2)).eval t + (S R ((m - 2) / 2)).eval t)) •
((f y * g z - f z) • x - g z • y) := by
induction m with
| zero => simp
| succ m ih =>
/- Now, let us collect two facts about the evaluations of `S r k`. These easily follow from the
properties of the `S` polynomials. -/
have S_eval_t_sub_two (k : ℤ) :
(S R (k - 2)).eval t = t * (S R (k - 1)).eval t - (S R k).eval t := by
simp [S_sub_two]
have S_eval_t_sq_add_S_eval_t_sq (k : ℤ) :
(S R k).eval t ^ 2 + (S R (k + 1)).eval t ^ 2 - t * (S R k).eval t * (S R (k + 1)).eval t
= 1 := by
simpa using congr_arg (Polynomial.eval t) (S_sq_add_S_sq R k)
-- Apply the inductive hypothesis.
rw [pow_succ', LinearEquiv.mul_apply, ih, LinearEquiv.mul_apply]
-- Expand out all the reflections and use `hf`, `hg`.
simp only [reflection_apply, map_add, map_sub, map_smul, hf, hg]
-- `m` can be written in the form `2 * k + e`, where `e` is `0` or `1`.
push_cast
rw [← Int.mul_ediv_add_emod m 2]
set k : ℤ := m / 2
set e : ℤ := m % 2
simp_rw [add_assoc (2 * k), add_sub_assoc (2 * k), add_comm (2 * k),
add_mul_ediv_left _ k (by simp : (2 : ℤ) ≠ 0)]
have he : e = 0 ∨ e = 1 := by omega
clear_value e
/- Now, equate the coefficients on both sides. These linear combinations were
found using `polyrith`. -/
match_scalars
· rfl
· linear_combination (norm := skip) (-g z * f y * (S R (e - 1 + k)).eval t +
f z * (S R (e - 1 + k)).eval t) * S_eval_t_sub_two (e + k) +
(-g z * f y + f z) * S_eval_t_sq_add_S_eval_t_sq (k - 1)
subst ht
obtain rfl | rfl : e = 0 ∨ e = 1 := he <;> ring_nf
· linear_combination (norm := skip)
g z * (S R (e - 1 + k)).eval t * S_eval_t_sub_two (e + k) +
g z * S_eval_t_sq_add_S_eval_t_sq (k - 1)
subst ht
obtain rfl | rfl : e = 0 ∨ e = 1 := he <;> ring_nf
/-- A formula for $(r_1 r_2)^m$, where $m$ is a natural number. -/
lemma reflection_mul_reflection_pow (m : ℕ)
(t : R := f y * g x - 2) (ht : t = f y * g x - 2 := by rfl) :
((reflection hf * reflection hg) ^ m).toLinearMap =
LinearMap.id (R := R) (M := M) +
((S R ((m - 2) / 2)).eval t * ((S R ((m - 1) / 2)).eval t + (S R ((m - 3) / 2)).eval t)) •
((g x • f - g).smulRight y - f.smulRight x) +
((S R ((m - 1) / 2)).eval t * ((S R (m / 2)).eval t + (S R ((m - 2) / 2)).eval t)) •
((f y • g - f).smulRight x - g.smulRight y) := by
ext z
simpa using reflection_mul_reflection_pow_apply hf hg m z t ht
/-- A formula for $(r_1 r_2)^m z$, where $m$ is an integer and $z \in M$. -/
lemma reflection_mul_reflection_zpow_apply (m : ℤ) (z : M)
(t : R := f y * g x - 2) (ht : t = f y * g x - 2 := by rfl) :
((reflection hf * reflection hg) ^ m) z =
z +
((S R ((m - 2) / 2)).eval t * ((S R ((m - 1) / 2)).eval t + (S R ((m - 3) / 2)).eval t)) •
((g x * f z - g z) • y - f z • x) +
((S R ((m - 1) / 2)).eval t * ((S R (m / 2)).eval t + (S R ((m - 2) / 2)).eval t)) •
((f y * g z - f z) • x - g z • y) := by
induction m using Int.negInduction with
| nat m => exact_mod_cast reflection_mul_reflection_pow_apply hf hg m z t ht
| neg _ m =>
have ht' : t = g x * f y - 2 := by rwa [mul_comm (g x)]
rw [zpow_neg, ← inv_zpow, mul_inv_rev, reflection_inv, reflection_inv, zpow_natCast,
reflection_mul_reflection_pow_apply hg hf m z t ht', add_right_comm z]
have aux (a b : ℤ) (hab : a + b = -3 := by omega) : a / 2 = -(b / 2) - 2 := by omega
rw [aux (-m - 3) m, aux (-m - 2) (m - 1), aux (-m - 1) (m - 2), aux (-m) (m - 3)]
simp only [S_neg_sub_two, Polynomial.eval_neg]
ring_nf
/-- A formula for $(r_1 r_2)^m$, where $m$ is an integer. -/
lemma reflection_mul_reflection_zpow (m : ℤ)
(t : R := f y * g x - 2) (ht : t = f y * g x - 2 := by rfl) :
((reflection hf * reflection hg) ^ m).toLinearMap =
LinearMap.id (R := R) (M := M) +
((S R ((m - 2) / 2)).eval t * ((S R ((m - 1) / 2)).eval t + (S R ((m - 3) / 2)).eval t)) •
((g x • f - g).smulRight y - f.smulRight x) +
((S R ((m - 1) / 2)).eval t * ((S R (m / 2)).eval t + (S R ((m - 2) / 2)).eval t)) •
((f y • g - f).smulRight x - g.smulRight y) := by
ext z
simpa using reflection_mul_reflection_zpow_apply hf hg m z t ht
/-- A formula for $(r_1 r_2)^m x$, where $m$ is an integer. This is the special case of
`Module.reflection_mul_reflection_zpow_apply` with $z = x$. -/
lemma reflection_mul_reflection_zpow_apply_self (m : ℤ)
(t : R := f y * g x - 2) (ht : t = f y * g x - 2 := by rfl) :
((reflection hf * reflection hg) ^ m) x =
((S R m).eval t + (S R (m - 1)).eval t) • x + ((S R (m - 1)).eval t * -g x) • y := by
/- Even though this is a special case of `Module.reflection_mul_reflection_zpow_apply`, it is
easier to prove it from scratch. -/
have S_eval_t_sub_two (k : ℤ) :
(S R (k - 2)).eval t = (f y * g x - 2) * (S R (k - 1)).eval t - (S R k).eval t := by
simp [S_sub_two, ht]
induction m with
| zero => simp
| succ m ih =>
-- Apply the inductive hypothesis.
rw [add_comm (m : ℤ) 1, zpow_one_add, LinearEquiv.mul_apply, LinearEquiv.mul_apply, ih]
-- Expand out all the reflections and use `hf`, `hg`.
simp only [reflection_apply, map_add, map_sub, map_smul, hf, hg]
-- Equate coefficients of `x` and `y`.
match_scalars
· linear_combination (norm := ring_nf) -S_eval_t_sub_two (m + 1)
· ring_nf
| pred m ih =>
-- Apply the inductive hypothesis.
rw [sub_eq_add_neg (-m : ℤ) 1, add_comm (-m : ℤ) (-1), zpow_add, zpow_neg_one, mul_inv_rev,
reflection_inv, reflection_inv, LinearEquiv.mul_apply, LinearEquiv.mul_apply, ih]
-- Expand out all the reflections and use `hf`, `hg`.
simp only [reflection_apply, map_add, map_sub, map_smul, hf, hg]
-- Equate coefficients of `x` and `y`.
match_scalars
· linear_combination (norm := ring_nf) -S_eval_t_sub_two (-m)
· linear_combination (norm := ring_nf) g x * S_eval_t_sub_two (-m)
/-- A formula for $(r_1 r_2)^m x$, where $m$ is a natural number. This is the special case of
`Module.reflection_mul_reflection_pow_apply` with $z = x$. -/
lemma reflection_mul_reflection_pow_apply_self (m : ℕ)
(t : R := f y * g x - 2) (ht : t = f y * g x - 2 := by rfl) :
((reflection hf * reflection hg) ^ m) x =
((S R m).eval t + (S R (m - 1)).eval t) • x + ((S R (m - 1)).eval t * -g x) • y :=
mod_cast reflection_mul_reflection_zpow_apply_self hf hg m t ht
/-- A formula for $r_2 (r_1 r_2)^m x$, where $m$ is an integer. -/
lemma reflection_mul_reflection_mul_reflection_zpow_apply_self (m : ℤ)
(t : R := f y * g x - 2) (ht : t = f y * g x - 2 := by rfl) :
(reflection hg * (reflection hf * reflection hg) ^ m) x =
((S R m).eval t + (S R (m - 1)).eval t) • x + ((S R m).eval t * -g x) • y := by
rw [LinearEquiv.mul_apply, reflection_mul_reflection_zpow_apply_self hf hg m t ht]
-- Expand out all the reflections and use `hf`, `hg`.
simp only [reflection_apply, map_add, map_smul, hg]
-- Equate coefficients of `x` and `y`.
module
/-- A formula for $r_2 (r_1 r_2)^m x$, where $m$ is a natural number. -/
lemma reflection_mul_reflection_mul_reflection_pow_apply_self (m : ℕ)
(t : R := f y * g x - 2) (ht : t = f y * g x - 2 := by rfl) :
(reflection hg * (reflection hf * reflection hg) ^ m) x =
((S R m).eval t + (S R (m - 1)).eval t) • x + ((S R m).eval t * -g x) • y :=
mod_cast reflection_mul_reflection_mul_reflection_zpow_apply_self hf hg m t ht
end
/-! ### Lemmas used to prove uniqueness results for root data -/
/-- See also `Module.Dual.eq_of_preReflection_mapsTo'` for a variant of this lemma which
applies when `Φ` does not span.
This rather technical-looking lemma exists because it is exactly what is needed to establish various
uniqueness results for root data / systems. One might regard this lemma as lying at the boundary of
linear algebra and combinatorics since the finiteness assumption is the key. -/
lemma Dual.eq_of_preReflection_mapsTo [CharZero R] [NoZeroSMulDivisors R M]
{x : M} {Φ : Set M} (hΦ₁ : Φ.Finite) (hΦ₂ : span R Φ = ⊤) {f g : Dual R M}
(hf₁ : f x = 2) (hf₂ : MapsTo (preReflection x f) Φ Φ)
(hg₁ : g x = 2) (hg₂ : MapsTo (preReflection x g) Φ Φ) :
f = g := by
have hx : x ≠ 0 := by rintro rfl; simp at hf₁
let u := reflection hg₁ * reflection hf₁
have hu : u = LinearMap.id (R := R) (M := M) + (f - g).smulRight x := by
ext y
simp only [u, reflection_apply, hg₁, two_smul, LinearEquiv.coe_toLinearMap_mul,
LinearMap.id_coe, LinearEquiv.coe_coe, Module.End.mul_apply, LinearMap.add_apply, id_eq,
LinearMap.coe_smulRight, LinearMap.sub_apply, map_sub, map_smul, sub_add_cancel_left,
smul_neg, sub_neg_eq_add, sub_smul]
abel
replace hu : ∀ (n : ℕ),
↑(u ^ n) = LinearMap.id (R := R) (M := M) + (n : R) • (f - g).smulRight x := by
intro n
induction n with
| zero => simp
| succ n ih =>
have : ((f - g).smulRight x).comp ((n : R) • (f - g).smulRight x) = 0 := by
ext; simp [hf₁, hg₁]
rw [pow_succ', LinearEquiv.coe_toLinearMap_mul, ih, hu, add_mul, mul_add, mul_add]
simp_rw [Module.End.mul_eq_comp, LinearMap.comp_id, LinearMap.id_comp, this, add_zero,
add_assoc, Nat.cast_succ, add_smul, one_smul]
suffices IsOfFinOrder u by
obtain ⟨n, hn₀, hn₁⟩ := isOfFinOrder_iff_pow_eq_one.mp this
replace hn₁ : (↑(u ^ n) : M →ₗ[R] M) = LinearMap.id := LinearEquiv.toLinearMap_inj.mpr hn₁
simpa [hn₁, hn₀.ne', hx, sub_eq_zero] using hu n
exact u.isOfFinOrder_of_finite_of_span_eq_top_of_mapsTo hΦ₁ hΦ₂ (hg₂.comp hf₂)
/-- This rather technical-looking lemma exists because it is exactly what is needed to establish a
uniqueness result for root data. See the doc string of `Module.Dual.eq_of_preReflection_mapsTo` for
further remarks. -/
lemma Dual.eq_of_preReflection_mapsTo' [CharZero R] [NoZeroSMulDivisors R M]
{x : M} {Φ : Set M} (hΦ₁ : Φ.Finite) (hx : x ∈ span R Φ) {f g : Dual R M}
(hf₁ : f x = 2) (hf₂ : MapsTo (preReflection x f) Φ Φ)
(hg₁ : g x = 2) (hg₂ : MapsTo (preReflection x g) Φ Φ) :
(span R Φ).subtype.dualMap f = (span R Φ).subtype.dualMap g := by
set Φ' : Set (span R Φ) := range (inclusion <| Submodule.subset_span (R := R) (s := Φ))
rw [← finite_coe_iff] at hΦ₁
have hΦ'₁ : Φ'.Finite := finite_range (inclusion Submodule.subset_span)
have hΦ'₂ : span R Φ' = ⊤ := by
simp only [Φ']
rw [range_inclusion]
simp
let x' : span R Φ := ⟨x, hx⟩
have this : ∀ {F : Dual R M}, MapsTo (preReflection x F) Φ Φ →
MapsTo (preReflection x' ((span R Φ).subtype.dualMap F)) Φ' Φ' := by
intro F hF ⟨y, hy⟩ hy'
simp only [Φ'] at hy' ⊢
rw [range_inclusion] at hy'
simp only [SetLike.coe_sort_coe, mem_setOf_eq] at hy' ⊢
rw [range_inclusion]
exact hF hy'
exact eq_of_preReflection_mapsTo hΦ'₁ hΦ'₂ hf₁ (this hf₂) hg₁ (this hg₂)
variable {y}
variable {g : Dual R M}
/-- Composite of reflections in "parallel" hyperplanes is a shear (special case). -/
lemma reflection_reflection_iterate
(hfx : f x = 2) (hgy : g y = 2) (hgxfy : f y * g x = 4) (n : ℕ) :
((reflection hgy).trans (reflection hfx))^[n] y = y + n • (f y • x - (2 : R) • y) := by
induction n with
| zero => simp
| succ n ih =>
have hz : ∀ z : M, f y • g x • z = 2 • 2 • z := by
intro z
rw [smul_smul, hgxfy, smul_smul, ← Nat.cast_smul_eq_nsmul R (2 * 2), show 2 * 2 = 4 from rfl,
Nat.cast_ofNat]
simp only [iterate_succ', comp_apply, ih, two_smul, smul_sub, smul_add, map_add,
LinearEquiv.trans_apply, reflection_apply_self, map_neg, reflection_apply, neg_sub, map_sub,
map_nsmul, map_smul, smul_neg, hz, add_smul]
abel
lemma infinite_range_reflection_reflection_iterate_iff [IsAddTorsionFree M]
(hfx : f x = 2) (hgy : g y = 2) (hgxfy : f y * g x = 4) :
(range <| fun n ↦ ((reflection hgy).trans (reflection hfx))^[n] y).Infinite ↔
f y • x ≠ (2 : R) • y := by
simp only [reflection_reflection_iterate hfx hgy hgxfy, infinite_range_add_nsmul_iff, sub_ne_zero]
lemma eq_of_mapsTo_reflection_of_mem [IsAddTorsionFree M] {Φ : Set M} (hΦ : Φ.Finite)
(hfx : f x = 2) (hgy : g y = 2) (hgx : g x = 2) (hfy : f y = 2)
(hxfΦ : MapsTo (preReflection x f) Φ Φ)
(hygΦ : MapsTo (preReflection y g) Φ Φ)
(hyΦ : y ∈ Φ) :
x = y := by
suffices h : f y • x = (2 : R) • y by
rw [hfy, two_smul R x, two_smul R y, ← two_zsmul, ← two_zsmul] at h
exact smul_right_injective _ two_ne_zero h
rw [← not_infinite] at hΦ
contrapose! hΦ
apply ((infinite_range_reflection_reflection_iterate_iff hfx hgy
(by rw [hfy, hgx]; norm_cast)).mpr hΦ).mono
rw [range_subset_iff]
intro n
rw [← IsFixedPt.image_iterate ((bijOn_reflection_of_mapsTo hfx hxfΦ).comp
(bijOn_reflection_of_mapsTo hgy hygΦ)).image_eq n]
exact mem_image_of_mem _ hyΦ
lemma injOn_dualMap_subtype_span_range_range {ι : Type*} [IsAddTorsionFree M]
{r : ι ↪ M} {c : ι → Dual R M} (hfin : (range r).Finite)
(h_two : ∀ i, c i (r i) = 2)
(h_mapsTo : ∀ i, MapsTo (preReflection (r i) (c i)) (range r) (range r)) :
InjOn (span R (range r)).subtype.dualMap (range c) := by
rintro - ⟨i, rfl⟩ - ⟨j, rfl⟩ hij
congr
suffices ∀ k, c i (r k) = c j (r k) by
rw [← EmbeddingLike.apply_eq_iff_eq r]
exact eq_of_mapsTo_reflection_of_mem (f := c i) (g := c j) hfin (h_two i) (h_two j)
(by rw [← this, h_two]) (by rw [this, h_two]) (h_mapsTo i) (h_mapsTo j) (mem_range_self j)
intro k
simpa using LinearMap.congr_fun hij ⟨r k, Submodule.subset_span (mem_range_self k)⟩
end Module |
.lake/packages/mathlib/Mathlib/LinearAlgebra/AnnihilatingPolynomial.lean | import Mathlib.FieldTheory.Minpoly.Field
import Mathlib.RingTheory.PrincipalIdealDomain
import Mathlib.Algebra.Polynomial.Module.AEval
/-!
# Annihilating Ideal
Given a commutative ring `R` and an `R`-algebra `A`
Every element `a : A` defines
an ideal `Polynomial.annIdeal a ⊆ R[X]`.
Simply put, this is the set of polynomials `p` where
the polynomial evaluation `p(a)` is 0.
## Special case where the ground ring is a field
In the special case that `R` is a field, we use the notation `R = 𝕜`.
Here `𝕜[X]` is a PID, so there is a polynomial `g ∈ Polynomial.annIdeal a`
which generates the ideal. We show that if this generator is
chosen to be monic, then it is the minimal polynomial of `a`,
as defined in `FieldTheory.Minpoly`.
## Special case: endomorphism algebra
Given an `R`-module `M` (`[AddCommGroup M] [Module R M]`)
there are some common specializations which may be more familiar.
* Example 1: `A = M →ₗ[R] M`, the endomorphism algebra of an `R`-module M.
* Example 2: `A = n × n` matrices with entries in `R`.
-/
open Polynomial
namespace Polynomial
section Semiring
variable {R A : Type*} [CommSemiring R] [Semiring A] [Algebra R A]
variable (R) in
/-- `annIdeal R a` is the *annihilating ideal* of all `p : R[X]` such that `p(a) = 0`.
The informal notation `p(a)` stand for `Polynomial.aeval a p`.
Again informally, the annihilating ideal of `a` is
`{ p ∈ R[X] | p(a) = 0 }`. This is an ideal in `R[X]`.
The formal definition uses the kernel of the aeval map. -/
noncomputable def annIdeal (a : A) : Ideal R[X] :=
RingHom.ker ((aeval a).toRingHom : R[X] →+* A)
/-- It is useful to refer to ideal membership sometimes
and the annihilation condition other times. -/
theorem mem_annIdeal_iff_aeval_eq_zero {a : A} {p : R[X]} : p ∈ annIdeal R a ↔ aeval a p = 0 :=
Iff.rfl
end Semiring
section Field
variable {𝕜 A : Type*} [Field 𝕜] [Ring A] [Algebra 𝕜 A]
variable (𝕜)
open Submodule
/-- `annIdealGenerator 𝕜 a` is the monic generator of `annIdeal 𝕜 a`
if one exists, otherwise `0`.
Since `𝕜[X]` is a principal ideal domain there is a polynomial `g` such that
`span 𝕜 {g} = annIdeal a`. This picks some generator.
We prefer the monic generator of the ideal. -/
noncomputable def annIdealGenerator (a : A) : 𝕜[X] :=
let g := IsPrincipal.generator <| annIdeal 𝕜 a
g * C g.leadingCoeff⁻¹
section
variable {𝕜}
@[simp]
theorem annIdealGenerator_eq_zero_iff {a : A} : annIdealGenerator 𝕜 a = 0 ↔ annIdeal 𝕜 a = ⊥ := by
simp only [annIdealGenerator, mul_eq_zero, IsPrincipal.eq_bot_iff_generator_eq_zero,
Polynomial.C_eq_zero, inv_eq_zero, Polynomial.leadingCoeff_eq_zero, or_self_iff]
end
/-- `annIdealGenerator 𝕜 a` is indeed a generator. -/
@[simp]
theorem span_singleton_annIdealGenerator (a : A) :
Ideal.span {annIdealGenerator 𝕜 a} = annIdeal 𝕜 a := by
by_cases h : annIdealGenerator 𝕜 a = 0
· rw [h, annIdealGenerator_eq_zero_iff.mp h, Set.singleton_zero, Ideal.span_zero]
· rw [annIdealGenerator, Ideal.span_singleton_mul_right_unit, Ideal.span_singleton_generator]
apply Polynomial.isUnit_C.mpr
apply IsUnit.mk0
apply inv_eq_zero.not.mpr
apply Polynomial.leadingCoeff_eq_zero.not.mpr
apply (mul_ne_zero_iff.mp h).1
/-- The annihilating ideal generator is a member of the annihilating ideal. -/
theorem annIdealGenerator_mem (a : A) : annIdealGenerator 𝕜 a ∈ annIdeal 𝕜 a :=
Ideal.mul_mem_right _ _ (Submodule.IsPrincipal.generator_mem _)
theorem mem_iff_eq_smul_annIdealGenerator {p : 𝕜[X]} (a : A) :
p ∈ annIdeal 𝕜 a ↔ ∃ s : 𝕜[X], p = s • annIdealGenerator 𝕜 a := by
simp_rw [@eq_comm _ p, ← mem_span_singleton, ← span_singleton_annIdealGenerator 𝕜 a, Ideal.span]
/-- The generator we chose for the annihilating ideal is monic when the ideal is non-zero. -/
theorem monic_annIdealGenerator (a : A) (hg : annIdealGenerator 𝕜 a ≠ 0) :
Monic (annIdealGenerator 𝕜 a) :=
monic_mul_leadingCoeff_inv (mul_ne_zero_iff.mp hg).1
/-! We are working toward showing the generator of the annihilating ideal
in the field case is the minimal polynomial. We are going to use a uniqueness
theorem of the minimal polynomial.
This is the first condition: it must annihilate the original element `a : A`. -/
theorem annIdealGenerator_aeval_eq_zero (a : A) : aeval a (annIdealGenerator 𝕜 a) = 0 :=
mem_annIdeal_iff_aeval_eq_zero.mp (annIdealGenerator_mem 𝕜 a)
variable {𝕜}
theorem mem_iff_annIdealGenerator_dvd {p : 𝕜[X]} {a : A} :
p ∈ annIdeal 𝕜 a ↔ annIdealGenerator 𝕜 a ∣ p := by
rw [← Ideal.mem_span_singleton, span_singleton_annIdealGenerator]
/-- The generator of the annihilating ideal has minimal degree among
the non-zero members of the annihilating ideal -/
theorem degree_annIdealGenerator_le_of_mem (a : A) (p : 𝕜[X]) (hp : p ∈ annIdeal 𝕜 a)
(hpn0 : p ≠ 0) : degree (annIdealGenerator 𝕜 a) ≤ degree p :=
degree_le_of_dvd (mem_iff_annIdealGenerator_dvd.1 hp) hpn0
variable (𝕜)
/-- The generator of the annihilating ideal is the minimal polynomial. -/
theorem annIdealGenerator_eq_minpoly (a : A) : annIdealGenerator 𝕜 a = minpoly 𝕜 a := by
by_cases h : annIdealGenerator 𝕜 a = 0
· rw [h, minpoly.eq_zero]
rintro ⟨p, p_monic, hp : aeval a p = 0⟩
refine p_monic.ne_zero (Ideal.mem_bot.mp ?_)
simpa only [annIdealGenerator_eq_zero_iff.mp h] using mem_annIdeal_iff_aeval_eq_zero.mpr hp
· exact minpoly.unique _ _ (monic_annIdealGenerator _ _ h) (annIdealGenerator_aeval_eq_zero _ _)
fun q q_monic hq =>
degree_annIdealGenerator_le_of_mem a q (mem_annIdeal_iff_aeval_eq_zero.mpr hq)
q_monic.ne_zero
/-- If a monic generates the annihilating ideal, it must match our choice
of the annihilating ideal generator. -/
theorem monic_generator_eq_minpoly (a : A) (p : 𝕜[X]) (p_monic : p.Monic)
(p_gen : Ideal.span {p} = annIdeal 𝕜 a) : annIdealGenerator 𝕜 a = p := by
by_cases h : p = 0
· rwa [h, annIdealGenerator_eq_zero_iff, ← p_gen, Ideal.span_singleton_eq_bot.mpr]
· rw [← span_singleton_annIdealGenerator, Ideal.span_singleton_eq_span_singleton] at p_gen
rw [eq_comm]
apply eq_of_monic_of_associated p_monic _ p_gen
apply monic_annIdealGenerator _ _ ((Associated.ne_zero_iff p_gen).mp h)
theorem span_minpoly_eq_annihilator {M} [AddCommGroup M] [Module 𝕜 M] (f : Module.End 𝕜 M) :
Ideal.span {minpoly 𝕜 f} = Module.annihilator 𝕜[X] (Module.AEval' f) := by
rw [← annIdealGenerator_eq_minpoly, span_singleton_annIdealGenerator]; ext
rw [mem_annIdeal_iff_aeval_eq_zero, DFunLike.ext_iff, Module.mem_annihilator]; rfl
end Field
end Polynomial |
.lake/packages/mathlib/Mathlib/LinearAlgebra/GeneralLinearGroup.lean | import Mathlib.Algebra.Module.Equiv.Basic
/-!
# The general linear group of linear maps
The general linear group is defined to be the group of invertible linear maps from `M` to itself.
See also `Matrix.GeneralLinearGroup`
## Main definitions
* `LinearMap.GeneralLinearGroup`
-/
variable (R M : Type*)
namespace LinearMap
variable [Semiring R] [AddCommMonoid M] [Module R M]
/-- The group of invertible linear maps from `M` to itself -/
abbrev GeneralLinearGroup :=
(M →ₗ[R] M)ˣ
namespace GeneralLinearGroup
variable {R M}
/-- An invertible linear map `f` determines an equivalence from `M` to itself. -/
def toLinearEquiv (f : GeneralLinearGroup R M) : M ≃ₗ[R] M :=
{ f.val with
invFun := f.inv.toFun
left_inv := fun m ↦ show (f.inv * f.val) m = m by simp
right_inv := fun m ↦ show (f.val * f.inv) m = m by simp }
@[simp] lemma coe_toLinearEquiv (f : GeneralLinearGroup R M) :
f.toLinearEquiv = (f : M → M) := rfl
theorem toLinearEquiv_mul (f g : GeneralLinearGroup R M) :
(f * g).toLinearEquiv = f.toLinearEquiv * g.toLinearEquiv := by
rfl
theorem toLinearEquiv_inv (f : GeneralLinearGroup R M) :
(f⁻¹).toLinearEquiv = (f.toLinearEquiv)⁻¹ := by
rfl
/-- An equivalence from `M` to itself determines an invertible linear map. -/
def ofLinearEquiv (f : M ≃ₗ[R] M) : GeneralLinearGroup R M where
val := f
inv := (f.symm : M →ₗ[R] M)
val_inv := LinearMap.ext fun _ ↦ f.apply_symm_apply _
inv_val := LinearMap.ext fun _ ↦ f.symm_apply_apply _
@[simp] lemma coe_ofLinearEquiv (f : M ≃ₗ[R] M) :
ofLinearEquiv f = (f : M → M) := rfl
theorem ofLinearEquiv_mul (f g : M ≃ₗ[R] M) :
ofLinearEquiv (f * g) = ofLinearEquiv f * ofLinearEquiv g := by
rfl
theorem ofLinearEquiv_inv (f : M ≃ₗ[R] M) :
ofLinearEquiv (f⁻¹) = (ofLinearEquiv f)⁻¹ := by
rfl
variable (R M) in
/-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear
equivalences between `M` and itself. -/
def generalLinearEquiv : GeneralLinearGroup R M ≃* M ≃ₗ[R] M where
toFun := toLinearEquiv
invFun := ofLinearEquiv
map_mul' x y := by ext; rfl
@[simp]
theorem generalLinearEquiv_to_linearMap (f : GeneralLinearGroup R M) :
(generalLinearEquiv R M f : M →ₗ[R] M) = f := by ext; rfl
@[simp]
theorem coeFn_generalLinearEquiv (f : GeneralLinearGroup R M) :
(generalLinearEquiv R M f) = (f : M → M) := rfl
section Functoriality
variable {R₁ R₂ R₃ M₁ M₂ M₃ : Type*}
[Semiring R₁] [Semiring R₂] [Semiring R₃]
[AddCommMonoid M₁] [AddCommMonoid M₂] [AddCommMonoid M₃]
[Module R₁ M₁] [Module R₂ M₂] [Module R₃ M₃]
{σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃}
{σ₂₁ : R₂ →+* R₁} {σ₃₂ : R₃ →+* R₂} {σ₃₁ : R₃ →+* R₁}
[RingHomInvPair σ₁₂ σ₂₁] [RingHomInvPair σ₂₃ σ₃₂] [RingHomInvPair σ₁₃ σ₃₁]
[RingHomInvPair σ₂₁ σ₁₂] [RingHomInvPair σ₃₂ σ₂₃] [RingHomInvPair σ₃₁ σ₁₃]
[RingHomCompTriple σ₁₂ σ₂₃ σ₁₃] [RingHomCompTriple σ₃₂ σ₂₁ σ₃₁]
/-- A semilinear equivalence from `V` to `W` determines an isomorphism of general linear
groups. -/
def congrLinearEquiv (e₁₂ : M₁ ≃ₛₗ[σ₁₂] M₂) :
GeneralLinearGroup R₁ M₁ ≃* GeneralLinearGroup R₂ M₂ :=
Units.mapEquiv (LinearEquiv.conjRingEquiv e₁₂).toMulEquiv
@[simp] lemma congrLinearEquiv_apply (e₁₂ : M₁ ≃ₛₗ[σ₁₂] M₂) (g : GeneralLinearGroup R₁ M₁) :
congrLinearEquiv e₁₂ g = ofLinearEquiv (e₁₂.symm.trans <| g.toLinearEquiv.trans e₁₂) :=
rfl
@[simp] lemma congrLinearEquiv_symm (e₁₂ : M₁ ≃ₛₗ[σ₁₂] M₂) :
(congrLinearEquiv e₁₂).symm = congrLinearEquiv e₁₂.symm :=
rfl
@[simp]
lemma congrLinearEquiv_trans
{N₁ N₂ N₃ : Type*} [AddCommMonoid N₁] [AddCommMonoid N₂] [AddCommMonoid N₃]
[Module R N₁] [Module R N₂] [Module R N₃] (e₁₂ : N₁ ≃ₗ[R] N₂) (e₂₃ : N₂ ≃ₗ[R] N₃) :
(congrLinearEquiv e₁₂).trans (congrLinearEquiv e₂₃) = congrLinearEquiv (e₁₂.trans e₂₃) :=
rfl
/-- Stronger form of `congrLinearEquiv.trans` applying to semilinear maps. Not a simp lemma as
`σ₁₃` and `σ₃₁` cannot be inferred from the LHS. -/
lemma congrLinearEquiv_trans' (e₁₂ : M₁ ≃ₛₗ[σ₁₂] M₂) (e₂₃ : M₂ ≃ₛₗ[σ₂₃] M₃) :
(congrLinearEquiv e₁₂).trans (congrLinearEquiv e₂₃) =
congrLinearEquiv (e₁₂.trans e₂₃) :=
rfl
@[simp]
lemma congrLinearEquiv_refl :
congrLinearEquiv (LinearEquiv.refl R₁ M₁) = MulEquiv.refl (GeneralLinearGroup R₁ M₁) :=
rfl
end Functoriality
end GeneralLinearGroup
end LinearMap |
.lake/packages/mathlib/Mathlib/LinearAlgebra/BilinearMap.lean | import Mathlib.Algebra.Module.Submodule.Equiv
import Mathlib.Algebra.NoZeroSMulDivisors.Basic
/-!
# Basics on bilinear maps
This file provides basics on bilinear maps. The most general form considered are maps that are
semilinear in both arguments. They are of type `M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P`, where `M` and `N`
are modules over `R` and `S` respectively, `P` is a module over both `R₂` and `S₂` with
commuting actions, and `ρ₁₂ : R →+* R₂` and `σ₁₂ : S →+* S₂`.
## Main declarations
* `LinearMap.mk₂`: a constructor for bilinear maps,
taking an unbundled function together with proof witnesses of bilinearity
* `LinearMap.flip`: turns a bilinear map `M × N → P` into `N × M → P`
* `LinearMap.lflip`: given a linear map from `M` to `N →ₗ[R] P`, i.e., a bilinear map `M → N → P`,
change the order of variables and get a linear map from `N` to `M →ₗ[R] P`.
* `LinearMap.lcomp`: composition of a given linear map `M → N` with a linear map `N → P` as
a linear map from `Nₗ →ₗ[R] Pₗ` to `M →ₗ[R] Pₗ`
* `LinearMap.llcomp`: composition of linear maps as a bilinear map from `(M →ₗ[R] N) × (N →ₗ[R] P)`
to `M →ₗ[R] P`
* `LinearMap.compl₂`: composition of a linear map `Q → N` and a bilinear map `M → N → P` to
form a bilinear map `M → Q → P`.
* `LinearMap.compr₂`: composition of a linear map `P → Q` and a bilinear map `M → N → P` to form a
bilinear map `M → N → Q`.
* `LinearMap.lsmul`: scalar multiplication as a bilinear map `R × M → M`
## Tags
bilinear
-/
open Function
namespace LinearMap
section Semiring
-- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps
variable {R : Type*} [Semiring R] {S : Type*} [Semiring S]
variable {R₂ : Type*} [Semiring R₂] {S₂ : Type*} [Semiring S₂]
variable {M : Type*} {N : Type*} {P : Type*}
variable {M₂ : Type*} {N₂ : Type*} {P₂ : Type*}
variable {Pₗ : Type*}
variable {M' : Type*} {P' : Type*}
variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P]
variable [AddCommMonoid M₂] [AddCommMonoid N₂] [AddCommMonoid P₂] [AddCommMonoid Pₗ]
variable [AddCommGroup M'] [AddCommGroup P']
variable [Module R M] [Module S N] [Module R₂ P] [Module S₂ P]
variable [Module R M₂] [Module S N₂] [Module R P₂] [Module S₂ P₂]
variable [Module R Pₗ] [Module S Pₗ]
variable [Module R M'] [Module R₂ P'] [Module S₂ P']
variable [SMulCommClass S₂ R₂ P] [SMulCommClass S R Pₗ] [SMulCommClass S₂ R₂ P']
variable [SMulCommClass S₂ R P₂]
variable {ρ₁₂ : R →+* R₂} {σ₁₂ : S →+* S₂}
variable (ρ₁₂ σ₁₂)
/-- Create a bilinear map from a function that is semilinear in each component.
See `mk₂'` and `mk₂` for the linear case. -/
def mk₂'ₛₗ (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c : R) (m n), f (c • m) n = ρ₁₂ c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c : S) (m n), f m (c • n) = σ₁₂ c • f m n) : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P where
toFun m :=
{ toFun := f m
map_add' := H3 m
map_smul' := fun c => H4 c m }
map_add' m₁ m₂ := LinearMap.ext <| H1 m₁ m₂
map_smul' c m := LinearMap.ext <| H2 c m
variable {ρ₁₂ σ₁₂}
@[simp]
theorem mk₂'ₛₗ_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂'ₛₗ ρ₁₂ σ₁₂ f H1 H2 H3 H4 : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) m n = f m n := rfl
variable (R S)
/-- Create a bilinear map from a function that is linear in each component.
See `mk₂` for the special case where both arguments come from modules over the same ring. -/
def mk₂' (f : M → N → Pₗ) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c : R) (m n), f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c : S) (m n), f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[S] Pₗ :=
mk₂'ₛₗ (RingHom.id R) (RingHom.id S) f H1 H2 H3 H4
variable {R S}
@[simp]
theorem mk₂'_apply (f : M → N → Pₗ) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂' R S f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[S] Pₗ) m n = f m n := rfl
theorem ext₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (H : ∀ m n, f m n = g m n) : f = g :=
LinearMap.ext fun m => LinearMap.ext fun n => H m n
theorem congr_fun₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (h : f = g) (x y) : f x y = g x y :=
LinearMap.congr_fun (LinearMap.congr_fun h x) y
theorem ext_iff₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} : f = g ↔ ∀ m n, f m n = g m n :=
⟨congr_fun₂, ext₂⟩
section
attribute [local instance] SMulCommClass.symm
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to
`P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def flip (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) : N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P :=
mk₂'ₛₗ σ₁₂ ρ₁₂ (fun n m => f m n) (fun _ _ m => (f m).map_add _ _)
(fun _ _ m => (f m).map_smulₛₗ _ _)
(fun n m₁ m₂ => by simp only [map_add, add_apply])
-- Note: https://github.com/leanprover-community/mathlib4/pull/8386 changed `map_smulₛₗ` into `map_smulₛₗ _`.
-- It looks like we now run out of assignable metavariables.
(fun c n m => by simp only [map_smulₛₗ _, smul_apply])
@[simp]
theorem flip_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (m : M) (n : N) : flip f n m = f m n := rfl
end
section Semiring
variable {R R₂ R₃ R₄ R₅ : Type*}
variable {M N P Q : Type*}
variable [Semiring R] [Semiring R₂] [Semiring R₃] [Semiring R₄] [Semiring R₅]
variable {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} {σ₄₂ : R₄ →+* R₂} {σ₄₃ : R₄ →+* R₃}
variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] [AddCommMonoid Q]
variable [Module R M] [Module R₂ N] [Module R₃ P] [Module R₄ Q] [Module R₅ P]
variable [RingHomCompTriple σ₁₂ σ₂₃ σ₁₃] [RingHomCompTriple σ₄₂ σ₂₃ σ₄₃]
variable [SMulCommClass R₃ R₅ P] {σ₁₅ : R →+* R₅}
variable (R₅ P σ₂₃)
/-- Composing a semilinear map `M → N` and a semilinear map `N → P` to form a semilinear map
`M → P` is itself a linear map. -/
def lcompₛₗ (f : M →ₛₗ[σ₁₂] N) : (N →ₛₗ[σ₂₃] P) →ₗ[R₅] M →ₛₗ[σ₁₃] P :=
letI := SMulCommClass.symm
flip <| LinearMap.comp (flip id) f
variable {P σ₂₃ R₅}
@[simp]
theorem lcompₛₗ_apply (f : M →ₛₗ[σ₁₂] N) (g : N →ₛₗ[σ₂₃] P) (x : M) :
lcompₛₗ R₅ P σ₂₃ f g x = g (f x) := rfl
/-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to
form a bilinear map `M → Q → P`. -/
def compl₂ (h : M →ₛₗ[σ₁₅] N →ₛₗ[σ₂₃] P) (g : Q →ₛₗ[σ₄₂] N) : M →ₛₗ[σ₁₅] Q →ₛₗ[σ₄₃] P where
toFun a := (lcompₛₗ R₅ P σ₂₃ g) (h a)
map_add' _ _ := by
simp [map_add]
map_smul' _ _ := by
simp [LinearMap.map_smulₛₗ, lcompₛₗ]
@[simp]
theorem compl₂_apply (h : M →ₛₗ[σ₁₅] N →ₛₗ[σ₂₃] P) (g : Q →ₛₗ[σ₄₂] N) (m : M) (q : Q) :
h.compl₂ g m q = h m (g q) := rfl
@[simp]
theorem compl₂_id (h : M →ₛₗ[σ₁₅] N →ₛₗ[σ₂₃] P) : h.compl₂ LinearMap.id = h := by
ext
rw [compl₂_apply, id_coe, _root_.id]
end Semiring
section lcomp
variable (S N) [Module R N] [SMulCommClass R S N]
/-- Composing a given linear map `M → N` with a linear map `N → P` as a linear map from
`Nₗ →ₗ[R] Pₗ` to `M →ₗ[R] Pₗ`. -/
def lcomp (f : M →ₗ[R] M₂) : (M₂ →ₗ[R] N) →ₗ[S] M →ₗ[R] N :=
lcompₛₗ _ _ _ f
variable {S N}
@[simp]
theorem lcomp_apply (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] N) (x : M) : lcomp S N f g x = g (f x) := rfl
theorem lcomp_apply' (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] N) : lcomp S N f g = g ∘ₗ f := rfl
lemma lcomp_injective_of_surjective (g : M →ₗ[R] M₂) (surj : Function.Surjective g) :
Function.Injective (LinearMap.lcomp S N g) :=
surj.injective_linearMapComp_right
end lcomp
attribute [local instance] SMulCommClass.symm
@[simp]
theorem flip_flip (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) : f.flip.flip = f :=
LinearMap.ext₂ fun _x _y => (f.flip.flip_apply _ _).trans (f.flip_apply _ _)
theorem flip_inj {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (H : flip f = flip g) : f = g :=
ext₂ fun m n => show flip f n m = flip g n m by rw [H]
theorem map_zero₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (y) : f 0 y = 0 :=
(flip f y).map_zero
theorem map_neg₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y) : f (-x) y = -f x y :=
(flip f y).map_neg _
theorem map_sub₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y z) : f (x - y) z = f x z - f y z :=
(flip f z).map_sub _ _
theorem map_add₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y :=
(flip f y).map_add _ _
theorem map_smul₂ (f : M₂ →ₗ[R] N₂ →ₛₗ[σ₁₂] P₂) (r : R) (x y) : f (r • x) y = r • f x y :=
(flip f y).map_smul _ _
theorem map_smulₛₗ₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (r : R) (x y) : f (r • x) y = ρ₁₂ r • f x y :=
(flip f y).map_smulₛₗ _ _
theorem map_sum₂ {ι : Type*} (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (t : Finset ι) (x : ι → M) (y) :
f (∑ i ∈ t, x i) y = ∑ i ∈ t, f (x i) y :=
_root_.map_sum (flip f y) _ _
/-- Restricting a bilinear map in the second entry -/
def domRestrict₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : Submodule S N) : M →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P where
toFun m := (f m).domRestrict q
map_add' m₁ m₂ := LinearMap.ext fun _ => by simp only [map_add, domRestrict_apply, add_apply]
map_smul' c m :=
LinearMap.ext fun _ => by simp only [f.map_smulₛₗ, domRestrict_apply, smul_apply]
theorem domRestrict₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : Submodule S N) (x : M) (y : q) :
f.domRestrict₂ q x y = f x y := rfl
/-- Restricting a bilinear map in both components -/
def domRestrict₁₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : Submodule R M) (q : Submodule S N) :
p →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P :=
(f.domRestrict p).domRestrict₂ q
theorem domRestrict₁₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : Submodule R M) (q : Submodule S N)
(x : p) (y : q) : f.domRestrict₁₂ p q x y = f x y := rfl
section restrictScalars
variable (R' S' : Type*)
variable [Semiring R'] [Semiring S'] [Module R' M] [Module S' N] [Module R' Pₗ] [Module S' Pₗ]
variable [SMulCommClass S' R' Pₗ]
variable [SMul S' S] [IsScalarTower S' S N] [IsScalarTower S' S Pₗ]
variable [SMul R' R] [IsScalarTower R' R M] [IsScalarTower R' R Pₗ]
/-- If `B : M → N → Pₗ` is `R`-`S` bilinear and `R'` and `S'` are compatible scalar multiplications,
then the restriction of scalars is a `R'`-`S'` bilinear map. -/
@[simps!]
def restrictScalars₁₂ (B : M →ₗ[R] N →ₗ[S] Pₗ) : M →ₗ[R'] N →ₗ[S'] Pₗ :=
LinearMap.mk₂' R' S'
(B · ·)
B.map_add₂
(fun r' m _ ↦ by
dsimp only
rw [← smul_one_smul R r' m, map_smul₂, smul_one_smul])
(fun _ ↦ map_add _)
(fun _ x ↦ (B x).map_smul_of_tower _)
theorem restrictScalars₁₂_injective : Function.Injective
(LinearMap.restrictScalars₁₂ R' S' : (M →ₗ[R] N →ₗ[S] Pₗ) → (M →ₗ[R'] N →ₗ[S'] Pₗ)) :=
fun _ _ h ↦ ext₂ (congr_fun₂ h :)
@[simp]
theorem restrictScalars₁₂_inj {B B' : M →ₗ[R] N →ₗ[S] Pₗ} :
B.restrictScalars₁₂ R' S' = B'.restrictScalars₁₂ R' S' ↔ B = B' :=
(restrictScalars₁₂_injective R' S').eq_iff
end restrictScalars
/-- `LinearMap.flip` as an isomorphism of modules. -/
def lflip {R₀ : Type*} [Semiring R₀] [Module R₀ P] [SMulCommClass S₂ R₀ P] [SMulCommClass R₂ R₀ P] :
(M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) ≃ₗ[R₀] (N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P) where
toFun := flip
invFun := flip
map_add' _ _ := rfl
map_smul' _ _ := rfl
left_inv _ := rfl
right_inv _ := rfl
@[simp] theorem lflip_symm
{R₀ : Type*} [Semiring R₀] [Module R₀ P] [SMulCommClass S₂ R₀ P] [SMulCommClass R₂ R₀ P] :
(lflip : (M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) ≃ₗ[R₀] (N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P)).symm = lflip :=
rfl
@[simp]
theorem lflip_apply {R₀ : Type*} [Semiring R₀] [Module R₀ P] [SMulCommClass S₂ R₀ P]
[SMulCommClass R₂ R₀ P] (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) :
lflip (R₀ := R₀) f = f.flip := rfl
end Semiring
section CommSemiring
variable {R R₁ R₂ : Type*} [CommSemiring R] [Semiring R₁] [Semiring R₂]
variable {A : Type*} [Semiring A] {B : Type*} [Semiring B]
variable {M : Type*} {N : Type*} {P : Type*} {Q : Type*}
variable {Mₗ : Type*} {Nₗ : Type*} {Pₗ : Type*} {Qₗ Qₗ' : Type*}
variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] [AddCommMonoid Q]
variable [AddCommMonoid Mₗ] [AddCommMonoid Nₗ] [AddCommMonoid Pₗ]
variable [AddCommMonoid Qₗ] [AddCommMonoid Qₗ']
variable [Module R M]
variable [Module R Mₗ] [Module R Nₗ] [Module R Pₗ] [Module R Qₗ] [Module R Qₗ']
variable [Module R₁ Mₗ] [Module R₂ N] [Module R₁ Pₗ] [Module R₁ Qₗ]
variable [Module R₂ Pₗ] [Module R₂ Qₗ']
variable (R)
/-- Create a bilinear map from a function that is linear in each component.
This is a shorthand for `mk₂'` for the common case when `R = S`. -/
def mk₂ (f : M → Nₗ → Pₗ) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c : R) (m n), f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c : R) (m n), f m (c • n) = c • f m n) : M →ₗ[R] Nₗ →ₗ[R] Pₗ :=
mk₂' R R f H1 H2 H3 H4
@[simp]
theorem mk₂_apply (f : M → Nₗ → Pₗ) {H1 H2 H3 H4} (m : M) (n : Nₗ) :
(mk₂ R f H1 H2 H3 H4 : M →ₗ[R] Nₗ →ₗ[R] Pₗ) m n = f m n := rfl
variable [Module A Pₗ] [SMulCommClass R A Pₗ] {R}
/-- Composing linear maps `Q → M` and `Q' → N` with a bilinear map `M → N → P` to
form a bilinear map `Q → Q' → P`. -/
def compl₁₂ [SMulCommClass R₂ R₁ Pₗ]
(f : Mₗ →ₗ[R₁] N →ₗ[R₂] Pₗ) (g : Qₗ →ₗ[R₁] Mₗ) (g' : Qₗ' →ₗ[R₂] N) :
Qₗ →ₗ[R₁] Qₗ' →ₗ[R₂] Pₗ :=
(f.comp g).compl₂ g'
@[simp]
theorem compl₁₂_apply [SMulCommClass R₂ R₁ Pₗ]
(f : Mₗ →ₗ[R₁] N →ₗ[R₂] Pₗ) (g : Qₗ →ₗ[R₁] Mₗ) (g' : Qₗ' →ₗ[R₂] N) (x : Qₗ)
(y : Qₗ') : f.compl₁₂ g g' x y = f (g x) (g' y) := rfl
@[simp]
theorem compl₁₂_id_id [SMulCommClass R₂ R₁ Pₗ] (f : Mₗ →ₗ[R₁] N →ₗ[R₂] Pₗ) :
f.compl₁₂ LinearMap.id LinearMap.id = f := by
ext
simp_rw [compl₁₂_apply, id_coe, _root_.id]
theorem compl₁₂_inj [SMulCommClass R₂ R₁ Pₗ]
{f₁ f₂ : Mₗ →ₗ[R₁] N →ₗ[R₂] Pₗ} {g : Qₗ →ₗ[R₁] Mₗ} {g' : Qₗ' →ₗ[R₂] N}
(hₗ : Function.Surjective g) (hᵣ : Function.Surjective g') :
f₁.compl₁₂ g g' = f₂.compl₁₂ g g' ↔ f₁ = f₂ := by
constructor <;> intro h
· -- B₁.comp l r = B₂.comp l r → B₁ = B₂
ext x y
obtain ⟨x', hx⟩ := hₗ x
subst hx
obtain ⟨y', hy⟩ := hᵣ y
subst hy
convert LinearMap.congr_fun₂ h x' y' using 0
· -- B₁ = B₂ → B₁.comp l r = B₂.comp l r
subst h; rfl
omit [Module R M] in
/-- Composing a linear map `P → Q` and a bilinear map `M → N → P` to
form a bilinear map `M → N → Q`.
See `LinearMap.compr₂ₛₗ` for a version of this which does not support towers of scalars but which
does support semi-linear maps. -/
def compr₂ [Module R A] [Module A M] [Module A Qₗ]
[SMulCommClass R A Qₗ] [IsScalarTower R A Qₗ] [IsScalarTower R A Pₗ]
(f : M →ₗ[A] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[A] Qₗ) : M →ₗ[A] Nₗ →ₗ[R] Qₗ where
toFun x := g.restrictScalars R ∘ₗ (f x)
map_add' _ _ := by ext; simp
map_smul' _ _ := by ext; simp
omit [Module R M] in
@[simp]
theorem compr₂_apply [Module R A] [Module A M] [Module A Qₗ]
[SMulCommClass R A Qₗ] [IsScalarTower R A Qₗ] [IsScalarTower R A Pₗ]
(f : M →ₗ[A] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[A] Qₗ) (m : M) (n : Nₗ) :
f.compr₂ g m n = g (f m n) := rfl
/-- A version of `Function.Injective.comp` for composition of a bilinear map with a linear map. -/
theorem injective_compr₂_of_injective (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) (hf : Injective f)
(hg : Injective g) : Injective (f.compr₂ g) :=
hg.injective_linearMapComp_left.comp hf
/-- A version of `Function.Surjective.comp` for composition of a bilinear map with a linear map. -/
theorem surjective_compr₂_of_exists_rightInverse (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ)
(hf : Surjective f) (hg : ∃ g' : Qₗ →ₗ[R] Pₗ, g.comp g' = LinearMap.id) :
Surjective (f.compr₂ g) := (surjective_comp_left_of_exists_rightInverse hg).comp hf
/-- A version of `Function.Surjective.comp` for composition of a bilinear map with a linear map. -/
theorem surjective_compr₂_of_equiv (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ ≃ₗ[R] Qₗ) (hf : Surjective f) :
Surjective (f.compr₂ g.toLinearMap) :=
surjective_compr₂_of_exists_rightInverse f g.toLinearMap hf ⟨g.symm, by simp⟩
/-- A version of `Function.Bijective.comp` for composition of a bilinear map with a linear map. -/
theorem bijective_compr₂_of_equiv (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ ≃ₗ[R] Qₗ) (hf : Bijective f) :
Bijective (f.compr₂ g.toLinearMap) :=
⟨injective_compr₂_of_injective f g.toLinearMap hf.1 g.bijective.1,
surjective_compr₂_of_equiv f g hf.2⟩
section CommSemiringSemilinear
variable {R₂ R₃ R₄ M N P Q : Type*}
variable [CommSemiring R₂] [CommSemiring R₃] [CommSemiring R₄]
variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] [AddCommMonoid Q]
variable [Module R M] [Module R₂ N] [Module R₃ P] [Module R₄ Q]
variable {σ₁₂ : R →+* R₂} {σ₁₃ : R →+* R₃} {σ₁₄ : R →+* R₄} {σ₂₃ : R₂ →+* R₃}
variable {σ₂₄ : R₂ →+* R₄} {σ₃₄ : R₃ →+* R₄} {σ₄₂ : R₄ →+* R₂} {σ₄₃ : R₄ →+* R₃}
variable [RingHomCompTriple σ₁₂ σ₂₃ σ₁₃] [RingHomCompTriple σ₄₂ σ₂₃ σ₄₃]
variable [RingHomCompTriple σ₂₃ σ₃₄ σ₂₄] [RingHomCompTriple σ₁₃ σ₃₄ σ₁₄]
variable [RingHomCompTriple σ₂₄ σ₄₃ σ₂₃]
variable (M N P)
variable (R₃) in
/-- Composing linear maps as a bilinear map from `(M →ₛₗ[σ₁₂] N) × (N →ₛₗ[σ₂₃] P)`
to `M →ₛₗ[σ₁₃] P`. -/
def llcomp : (N →ₛₗ[σ₂₃] P) →ₗ[R₃] (M →ₛₗ[σ₁₂] N) →ₛₗ[σ₂₃] M →ₛₗ[σ₁₃] P :=
flip
{ toFun := lcompₛₗ _ P σ₂₃
map_add' := fun _f _f' => ext₂ fun g _x => g.map_add _ _
map_smul' := fun (_c : R₂) _f => ext₂ fun g _x => g.map_smulₛₗ _ _ }
variable {M N P}
@[simp]
theorem llcomp_apply (f : N →ₛₗ[σ₂₃] P) (g : M →ₛₗ[σ₁₂] N) (x : M) :
llcomp _ M N P f g x = f (g x) := rfl
theorem llcomp_apply' (f : N →ₛₗ[σ₂₃] P) (g : M →ₛₗ[σ₁₂] N) : llcomp _ M N P f g = f ∘ₛₗ g := rfl
omit [Module R M] in
/-- Composing a linear map `P →ₛₗ[σ₃₄] Q` and a bilinear map `M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P` to
form a bilinear map `M →ₛₗ[σ₁₄] N →ₛₗ[σ₂₄] Q`.
See `LinearMap.compr₂` for a version of this definition, which does not support semi-linear maps but
which does support towers of scalars. -/
def compr₂ₛₗ (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P →ₛₗ[σ₃₄] Q) : M →ₛₗ[σ₁₄] N →ₛₗ[σ₂₄] Q :=
llcomp _ N P Q g ∘ₛₗ f
@[simp]
theorem compr₂ₛₗ_apply (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P →ₛₗ[σ₃₄] Q) (m : M) (n : N) :
f.compr₂ₛₗ g m n = g (f m n) := rfl
/-- A version of `Function.Injective.comp` for composition of a bilinear map with a linear map. -/
theorem injective_compr₂ₛₗ_of_injective (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P →ₛₗ[σ₃₄] Q)
(hf : Injective f) (hg : Injective g) : Injective (f.compr₂ₛₗ g) :=
hg.injective_linearMapComp_left.comp hf
/-- A version of `Function.Surjective.comp` for composition of a bilinear map with a linear map. -/
theorem surjective_compr₂ₛₗ_of_exists_rightInverse [RingHomInvPair σ₃₄ σ₄₃]
(f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P →ₛₗ[σ₃₄] Q)
(hf : Surjective f) (hg : ∃ g' : Q →ₛₗ[σ₄₃] P, g.comp g' = LinearMap.id) :
Surjective (f.compr₂ₛₗ g) := (surjective_comp_left_of_exists_rightInverse hg).comp hf
/-- A version of `Function.Surjective.comp` for composition of a bilinear map with a linear map. -/
theorem surjective_compr₂ₛₗ_of_equiv [RingHomInvPair σ₃₄ σ₄₃] [RingHomInvPair σ₄₃ σ₃₄]
(f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P ≃ₛₗ[σ₃₄] Q) (hf : Surjective f) :
Surjective (f.compr₂ₛₗ g.toLinearMap) :=
surjective_compr₂ₛₗ_of_exists_rightInverse f g.toLinearMap hf ⟨g.symm, by simp⟩
/-- A version of `Function.Bijective.comp` for composition of a bilinear map with a linear map. -/
theorem bijective_compr₂ₛₗ_of_equiv [RingHomInvPair σ₃₄ σ₄₃] [RingHomInvPair σ₄₃ σ₃₄]
(f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P ≃ₛₗ[σ₃₄] Q) (hf : Bijective f) :
Bijective (f.compr₂ₛₗ g.toLinearMap) :=
⟨injective_compr₂ₛₗ_of_injective f g.toLinearMap hf.1 g.bijective.1,
surjective_compr₂ₛₗ_of_equiv f g hf.2⟩
end CommSemiringSemilinear
variable (R M)
/-- Scalar multiplication as a bilinear map `R → M → M`. -/
def lsmul : R →ₗ[R] M →ₗ[R] M :=
mk₂ R (· • ·) add_smul (fun _ _ _ => mul_smul _ _ _) smul_add fun r s m => by
simp only [smul_smul, mul_comm]
variable {R}
lemma lsmul_eq_DistribMulAction_toLinearMap (r : R) :
lsmul R M r = DistribMulAction.toLinearMap R M r := rfl
variable {M}
@[simp]
theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl
variable (R M Nₗ) in
/-- A shorthand for the type of `R`-bilinear `Nₗ`-valued maps on `M`. -/
protected abbrev BilinMap : Type _ := M →ₗ[R] M →ₗ[R] Nₗ
variable (R M) in
/-- For convenience, a shorthand for the type of bilinear forms from `M` to `R`. -/
protected abbrev BilinForm : Type _ := LinearMap.BilinMap R M R
end CommSemiring
section CommRing
variable {R M : Type*} [CommRing R]
section AddCommGroup
variable [AddCommGroup M] [Module R M]
theorem lsmul_injective [NoZeroSMulDivisors R M] {x : R} (hx : x ≠ 0) :
Function.Injective (lsmul R M x) :=
smul_right_injective _ hx
theorem ker_lsmul [NoZeroSMulDivisors R M] {a : R} (ha : a ≠ 0) :
LinearMap.ker (LinearMap.lsmul R M a) = ⊥ :=
LinearMap.ker_eq_bot_of_injective (LinearMap.lsmul_injective ha)
end AddCommGroup
end CommRing
open Function
section restrictScalarsRange
variable {R S M P M' P' : Type*}
[Semiring R] [Semiring S] [SMul S R]
[AddCommMonoid M] [Module R M] [AddCommMonoid P] [Module R P]
[Module S M] [Module S P]
[IsScalarTower S R M] [IsScalarTower S R P]
[AddCommMonoid M'] [Module S M'] [AddCommMonoid P'] [Module S P']
variable (i : M' →ₗ[S] M) (k : P' →ₗ[S] P) (hk : Injective k)
(f : M →ₗ[R] P) (hf : ∀ m, f (i m) ∈ LinearMap.range k)
/-- Restrict the scalars and range of a linear map. -/
noncomputable def restrictScalarsRange :
M' →ₗ[S] P' :=
((f.restrictScalars S).comp i).codLift k hk hf
@[simp]
lemma restrictScalarsRange_apply (m : M') :
k (restrictScalarsRange i k hk f hf m) = f (i m) := by
have : k (restrictScalarsRange i k hk f hf m) =
(k ∘ₗ ((f.restrictScalars S).comp i).codLift k hk hf) m :=
rfl
rw [this, comp_codLift, comp_apply, restrictScalars_apply]
@[simp]
lemma eq_restrictScalarsRange_iff (m : M') (p : P') :
p = restrictScalarsRange i k hk f hf m ↔ k p = f (i m) := by
rw [← restrictScalarsRange_apply i k hk f hf m, hk.eq_iff]
@[simp]
lemma restrictScalarsRange_apply_eq_zero_iff (m : M') :
restrictScalarsRange i k hk f hf m = 0 ↔ f (i m) = 0 := by
rw [← hk.eq_iff, restrictScalarsRange_apply, map_zero]
end restrictScalarsRange
section restrictScalarsRange₂
variable {R S M N P M' N' P' : Type*}
[CommSemiring R] [CommSemiring S] [SMul S R]
[AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] [AddCommMonoid P] [Module R P]
[Module S M] [Module S N] [Module S P]
[IsScalarTower S R M] [IsScalarTower S R N] [IsScalarTower S R P]
[AddCommMonoid M'] [Module S M'] [AddCommMonoid N'] [Module S N'] [AddCommMonoid P'] [Module S P']
[SMulCommClass R S P]
variable (i : M' →ₗ[S] M) (j : N' →ₗ[S] N) (k : P' →ₗ[S] P) (hk : Injective k)
(B : M →ₗ[R] N →ₗ[R] P) (hB : ∀ m n, B (i m) (j n) ∈ LinearMap.range k)
/-- Restrict the scalars, domains, and range of a bilinear map. -/
noncomputable def restrictScalarsRange₂ :
M' →ₗ[S] N' →ₗ[S] P' :=
(((LinearMap.restrictScalarsₗ S R _ _ _).comp
(B.restrictScalars S)).compl₁₂ i j).codRestrict₂ k hk hB
@[simp] lemma restrictScalarsRange₂_apply (m : M') (n : N') :
k (restrictScalarsRange₂ i j k hk B hB m n) = B (i m) (j n) := by
simp [restrictScalarsRange₂]
@[simp]
lemma eq_restrictScalarsRange₂_iff (m : M') (n : N') (p : P') :
p = restrictScalarsRange₂ i j k hk B hB m n ↔ k p = B (i m) (j n) := by
rw [← restrictScalarsRange₂_apply i j k hk B hB m n, hk.eq_iff]
@[simp]
lemma restrictScalarsRange₂_apply_eq_zero_iff (m : M') (n : N') :
restrictScalarsRange₂ i j k hk B hB m n = 0 ↔ B (i m) (j n) = 0 := by
rw [← hk.eq_iff, restrictScalarsRange₂_apply, map_zero]
end restrictScalarsRange₂
end LinearMap |
.lake/packages/mathlib/Mathlib/LinearAlgebra/FiniteSpan.lean | import Mathlib.GroupTheory.OrderOfElement
import Mathlib.LinearAlgebra.Span.Defs
import Mathlib.Algebra.Module.Equiv.Basic
/-!
# Additional results about finite spanning sets in linear algebra
-/
open Set Function
open Submodule (span)
/-- A linear equivalence which preserves a finite spanning set must have finite order. -/
lemma LinearEquiv.isOfFinOrder_of_finite_of_span_eq_top_of_mapsTo
{R M : Type*} [Semiring R] [AddCommMonoid M] [Module R M]
{Φ : Set M} (hΦ₁ : Φ.Finite) (hΦ₂ : span R Φ = ⊤) {e : M ≃ₗ[R] M} (he : MapsTo e Φ Φ) :
IsOfFinOrder e := by
replace he : BijOn e Φ Φ := (hΦ₁.injOn_iff_bijOn_of_mapsTo he).mp e.injective.injOn
let e' := he.equiv
have : Finite Φ := finite_coe_iff.mpr hΦ₁
obtain ⟨k, hk₀, hk⟩ := isOfFinOrder_of_finite e'
refine ⟨k, hk₀, ?_⟩
ext m
have hm : m ∈ span R Φ := hΦ₂ ▸ Submodule.mem_top
simp only [mul_left_iterate, mul_one, LinearEquiv.coe_one, id_eq]
refine Submodule.span_induction (fun x hx ↦ ?_) (by simp)
(fun x y _ _ hx hy ↦ by simp [map_add, hx, hy]) (fun t x _ hx ↦ by simp [hx]) hm
rw [LinearEquiv.pow_apply, ← he.1.coe_iterate_restrict ⟨x, hx⟩ k]
replace hk : (e') ^ k = 1 := by simpa [IsPeriodicPt, IsFixedPt] using hk
replace hk := Equiv.congr_fun hk ⟨x, hx⟩
rwa [Equiv.Perm.coe_one, id_eq, Subtype.ext_iff, Equiv.Perm.coe_pow] at hk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.