path
stringlengths
11
71
content
stringlengths
75
124k
Tactic\NormNum\Eq.lean
/- Copyright (c) 2022 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Tactic.NormNum.Inv /-! # `norm_num` extension for equalities -/ variable {α : Type*} open Lean Meta Qq namespace Mathlib.Meta.NormNum theorem isNat_eq_false [AddMonoidWithOne α] [CharZero α] : {a b : α} → {a' b' : ℕ} → IsNat a a' → IsNat b b' → Nat.beq a' b' = false → ¬a = b | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => by simpa using Nat.ne_of_beq_eq_false h theorem isInt_eq_false [Ring α] [CharZero α] : {a b : α} → {a' b' : ℤ} → IsInt a a' → IsInt b b' → decide (a' = b') = false → ¬a = b | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => by simpa using of_decide_eq_false h theorem Rat.invOf_denom_swap [Ring α] (n₁ n₂ : ℤ) (a₁ a₂ : α) [Invertible a₁] [Invertible a₂] : n₁ * ⅟a₁ = n₂ * ⅟a₂ ↔ n₁ * a₂ = n₂ * a₁ := by rw [mul_invOf_eq_iff_eq_mul_right, ← Int.commute_cast, mul_assoc, ← mul_left_eq_iff_eq_invOf_mul, Int.commute_cast] theorem isRat_eq_false [Ring α] [CharZero α] : {a b : α} → {na nb : ℤ} → {da db : ℕ} → IsRat a na da → IsRat b nb db → decide (Int.mul na (.ofNat db) = Int.mul nb (.ofNat da)) = false → ¬a = b | _, _, _, _, _, _, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by rw [Rat.invOf_denom_swap]; exact mod_cast of_decide_eq_false h /-- The `norm_num` extension which identifies expressions of the form `a = b`, such that `norm_num` successfully recognises both `a` and `b`. -/ @[norm_num _ = _] def evalEq : NormNumExt where eval {v β} e := do haveI' : v =QL 0 := ⟨⟩; haveI' : $β =Q Prop := ⟨⟩ let .app (.app f a) b ← whnfR e | failure let ⟨u, α, a⟩ ← inferTypeQ' a have b : Q($α) := b haveI' : $e =Q ($a = $b) := ⟨⟩ guard <|← withNewMCtxDepth <| isDefEq f q(Eq (α := $α)) let ra ← derive a; let rb ← derive b let rec intArm (rα : Q(Ring $α)) := do let ⟨za, na, pa⟩ ← ra.toInt rα; let ⟨zb, nb, pb⟩ ← rb.toInt rα if za = zb then haveI' : $na =Q $nb := ⟨⟩ return .isTrue q(isInt_eq_true $pa $pb) else if let some _i ← inferCharZeroOfRing? rα then let r : Q(decide ($na = $nb) = false) := (q(Eq.refl false) : Expr) return .isFalse q(isInt_eq_false $pa $pb $r) else failure --TODO: nonzero characteristic ≠ let rec ratArm (dα : Q(DivisionRing $α)) := do let ⟨qa, na, da, pa⟩ ← ra.toRat' dα; let ⟨qb, nb, db, pb⟩ ← rb.toRat' dα if qa = qb then haveI' : $na =Q $nb := ⟨⟩ haveI' : $da =Q $db := ⟨⟩ return .isTrue q(isRat_eq_true $pa $pb) else if let some _i ← inferCharZeroOfDivisionRing? dα then let r : Q(decide (Int.mul $na (.ofNat $db) = Int.mul $nb (.ofNat $da)) = false) := (q(Eq.refl false) : Expr) return .isFalse q(isRat_eq_false $pa $pb $r) else failure --TODO: nonzero characteristic ≠ match ra, rb with | .isBool b₁ p₁, .isBool b₂ p₂ => have a : Q(Prop) := a; have b : Q(Prop) := b match b₁, p₁, b₂, p₂ with | true, (p₁ : Q($a)), true, (p₂ : Q($b)) => return .isTrue q(eq_of_true $p₁ $p₂) | false, (p₁ : Q(¬$a)), false, (p₂ : Q(¬$b)) => return .isTrue q(eq_of_false $p₁ $p₂) | false, (p₁ : Q(¬$a)), true, (p₂ : Q($b)) => return .isFalse q(ne_of_false_of_true $p₁ $p₂) | true, (p₁ : Q($a)), false, (p₂ : Q(¬$b)) => return .isFalse q(ne_of_true_of_false $p₁ $p₂) | .isBool .., _ | _, .isBool .. => failure | .isRat dα .., _ | _, .isRat dα .. => ratArm dα | .isNegNat rα .., _ | _, .isNegNat rα .. => intArm rα | .isNat _ na pa, .isNat mα nb pb => assumeInstancesCommute if na.natLit! = nb.natLit! then haveI' : $na =Q $nb := ⟨⟩ return .isTrue q(isNat_eq_true $pa $pb) else if let some _i ← inferCharZeroOfAddMonoidWithOne? mα then let r : Q(Nat.beq $na $nb = false) := (q(Eq.refl false) : Expr) return .isFalse q(isNat_eq_false $pa $pb $r) else failure --TODO: nonzero characteristic ≠ end Mathlib.Meta.NormNum
Tactic\NormNum\GCD.lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kyle Miller -/ import Mathlib.Data.Int.GCD import Mathlib.Tactic.NormNum /-! # `norm_num` extensions for GCD-adjacent functions This module defines some `norm_num` extensions for functions such as `Nat.gcd`, `Nat.lcm`, `Int.gcd`, and `Int.lcm`. Note that `Nat.coprime` is reducible and defined in terms of `Nat.gcd`, so the `Nat.gcd` extension also indirectly provides a `Nat.coprime` extension. -/ namespace Tactic namespace NormNum theorem int_gcd_helper' {d : ℕ} {x y : ℤ} (a b : ℤ) (h₁ : (d : ℤ) ∣ x) (h₂ : (d : ℤ) ∣ y) (h₃ : x * a + y * b = d) : Int.gcd x y = d := by refine Nat.dvd_antisymm ?_ (Int.natCast_dvd_natCast.1 (Int.dvd_gcd h₁ h₂)) rw [← Int.natCast_dvd_natCast, ← h₃] apply dvd_add · exact Int.gcd_dvd_left.mul_right _ · exact Int.gcd_dvd_right.mul_right _ theorem nat_gcd_helper_dvd_left (x y : ℕ) (h : y % x = 0) : Nat.gcd x y = x := Nat.gcd_eq_left (Nat.dvd_of_mod_eq_zero h) theorem nat_gcd_helper_dvd_right (x y : ℕ) (h : x % y = 0) : Nat.gcd x y = y := Nat.gcd_eq_right (Nat.dvd_of_mod_eq_zero h) theorem nat_gcd_helper_2 (d x y a b : ℕ) (hu : x % d = 0) (hv : y % d = 0) (h : x * a = y * b + d) : Nat.gcd x y = d := by rw [← Int.gcd_natCast_natCast] apply int_gcd_helper' a (-b) (Int.natCast_dvd_natCast.mpr (Nat.dvd_of_mod_eq_zero hu)) (Int.natCast_dvd_natCast.mpr (Nat.dvd_of_mod_eq_zero hv)) rw [mul_neg, ← sub_eq_add_neg, sub_eq_iff_eq_add'] exact mod_cast h theorem nat_gcd_helper_1 (d x y a b : ℕ) (hu : x % d = 0) (hv : y % d = 0) (h : y * b = x * a + d) : Nat.gcd x y = d := (Nat.gcd_comm _ _).trans <| nat_gcd_helper_2 _ _ _ _ _ hv hu h theorem nat_gcd_helper_1' (x y a b : ℕ) (h : y * b = x * a + 1) : Nat.gcd x y = 1 := nat_gcd_helper_1 1 _ _ _ _ (Nat.mod_one _) (Nat.mod_one _) h theorem nat_gcd_helper_2' (x y a b : ℕ) (h : x * a = y * b + 1) : Nat.gcd x y = 1 := nat_gcd_helper_2 1 _ _ _ _ (Nat.mod_one _) (Nat.mod_one _) h theorem nat_lcm_helper (x y d m : ℕ) (hd : Nat.gcd x y = d) (d0 : Nat.beq d 0 = false) (dm : x * y = d * m) : Nat.lcm x y = m := mul_right_injective₀ (Nat.ne_of_beq_eq_false d0) <| by dsimp only -- Porting note: the `dsimp only` was not necessary in Lean3. rw [← dm, ← hd, Nat.gcd_mul_lcm] theorem int_gcd_helper {x y : ℤ} {x' y' d : ℕ} (hx : x.natAbs = x') (hy : y.natAbs = y') (h : Nat.gcd x' y' = d) : Int.gcd x y = d := by subst_vars; rw [Int.gcd_def] theorem int_lcm_helper {x y : ℤ} {x' y' d : ℕ} (hx : x.natAbs = x') (hy : y.natAbs = y') (h : Nat.lcm x' y' = d) : Int.lcm x y = d := by subst_vars; rw [Int.lcm_def] open Qq Lean Elab.Tactic Mathlib.Meta.NormNum theorem isNat_gcd : {x y nx ny z : ℕ} → IsNat x nx → IsNat y ny → Nat.gcd nx ny = z → IsNat (Nat.gcd x y) z | _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩ theorem isNat_lcm : {x y nx ny z : ℕ} → IsNat x nx → IsNat y ny → Nat.lcm nx ny = z → IsNat (Nat.lcm x y) z | _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩ theorem isInt_gcd : {x y nx ny : ℤ} → {z : ℕ} → IsInt x nx → IsInt y ny → Int.gcd nx ny = z → IsNat (Int.gcd x y) z | _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩ theorem isInt_lcm : {x y nx ny : ℤ} → {z : ℕ} → IsInt x nx → IsInt y ny → Int.lcm nx ny = z → IsNat (Int.lcm x y) z | _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩ /-- Given natural number literals `ex` and `ey`, return their GCD as a natural number literal and an equality proof. Panics if `ex` or `ey` aren't natural number literals. -/ def proveNatGCD (ex ey : Q(ℕ)) : (ed : Q(ℕ)) × Q(Nat.gcd $ex $ey = $ed) := match ex.natLit!, ey.natLit! with | 0, _ => show (ed : Q(ℕ)) × Q(Nat.gcd 0 $ey = $ed) from ⟨ey, q(Nat.gcd_zero_left $ey)⟩ | _, 0 => show (ed : Q(ℕ)) × Q(Nat.gcd $ex 0 = $ed) from ⟨ex, q(Nat.gcd_zero_right $ex)⟩ | 1, _ => show (ed : Q(ℕ)) × Q(Nat.gcd 1 $ey = $ed) from ⟨mkRawNatLit 1, q(Nat.gcd_one_left $ey)⟩ | _, 1 => show (ed : Q(ℕ)) × Q(Nat.gcd $ex 1 = $ed) from ⟨mkRawNatLit 1, q(Nat.gcd_one_right $ex)⟩ | x, y => let (d, a, b) := Nat.xgcdAux x 1 0 y 0 1 if d = x then have pq : Q(Nat.mod $ey $ex = 0) := (q(Eq.refl (nat_lit 0)) : Expr) ⟨ex, q(nat_gcd_helper_dvd_left $ex $ey $pq)⟩ else if d = y then have pq : Q(Nat.mod $ex $ey = 0) := (q(Eq.refl (nat_lit 0)) : Expr) ⟨ey, q(nat_gcd_helper_dvd_right $ex $ey $pq)⟩ else have ea' : Q(ℕ) := mkRawNatLit a.natAbs have eb' : Q(ℕ) := mkRawNatLit b.natAbs if d = 1 then if a ≥ 0 then have pt : Q($ex * $ea' = $ey * $eb' + 1) := (q(Eq.refl ($ex * $ea')) : Expr) ⟨mkRawNatLit 1, q(nat_gcd_helper_2' $ex $ey $ea' $eb' $pt)⟩ else have pt : Q($ey * $eb' = $ex * $ea' + 1) := (q(Eq.refl ($ey * $eb')) : Expr) ⟨mkRawNatLit 1, q(nat_gcd_helper_1' $ex $ey $ea' $eb' $pt)⟩ else have ed : Q(ℕ) := mkRawNatLit d have pu : Q(Nat.mod $ex $ed = 0) := (q(Eq.refl (nat_lit 0)) : Expr) have pv : Q(Nat.mod $ey $ed = 0) := (q(Eq.refl (nat_lit 0)) : Expr) if a ≥ 0 then have pt : Q($ex * $ea' = $ey * $eb' + $ed) := (q(Eq.refl ($ex * $ea')) : Expr) ⟨ed, q(nat_gcd_helper_2 $ed $ex $ey $ea' $eb' $pu $pv $pt)⟩ else have pt : Q($ey * $eb' = $ex * $ea' + $ed) := (q(Eq.refl ($ey * $eb')) : Expr) ⟨ed, q(nat_gcd_helper_1 $ed $ex $ey $ea' $eb' $pu $pv $pt)⟩ @[norm_num Nat.gcd _ _] def evalNatGCD : NormNumExt where eval {u α} e := do let .app (.app _ (x : Q(ℕ))) (y : Q(ℕ)) ← Meta.whnfR e | failure haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩ haveI' : $e =Q Nat.gcd $x $y := ⟨⟩ let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat) let ⟨ex, p⟩ ← deriveNat x sℕ let ⟨ey, q⟩ ← deriveNat y sℕ let ⟨ed, pf⟩ := proveNatGCD ex ey return .isNat sℕ ed q(isNat_gcd $p $q $pf) /-- Given natural number literals `ex` and `ey`, return their LCM as a natural number literal and an equality proof. Panics if `ex` or `ey` aren't natural number literals. -/ def proveNatLCM (ex ey : Q(ℕ)) : (ed : Q(ℕ)) × Q(Nat.lcm $ex $ey = $ed) := match ex.natLit!, ey.natLit! with | 0, _ => show (ed : Q(ℕ)) × Q(Nat.lcm 0 $ey = $ed) from ⟨mkRawNatLit 0, q(Nat.lcm_zero_left $ey)⟩ | _, 0 => show (ed : Q(ℕ)) × Q(Nat.lcm $ex 0 = $ed) from ⟨mkRawNatLit 0, q(Nat.lcm_zero_right $ex)⟩ | 1, _ => show (ed : Q(ℕ)) × Q(Nat.lcm 1 $ey = $ed) from ⟨ey, q(Nat.lcm_one_left $ey)⟩ | _, 1 => show (ed : Q(ℕ)) × Q(Nat.lcm $ex 1 = $ed) from ⟨ex, q(Nat.lcm_one_right $ex)⟩ | x, y => let ⟨ed, pd⟩ := proveNatGCD ex ey have p0 : Q(Nat.beq $ed 0 = false) := (q(Eq.refl false) : Expr) have em : Q(ℕ) := mkRawNatLit (x * y / ed.natLit!) have pm : Q($ex * $ey = $ed * $em) := (q(Eq.refl ($ex * $ey)) : Expr) ⟨em, q(nat_lcm_helper $ex $ey $ed $em $pd $p0 $pm)⟩ /-- Evaluates the `Nat.lcm` function. -/ @[norm_num Nat.lcm _ _] def evalNatLCM : NormNumExt where eval {u α} e := do let .app (.app _ (x : Q(ℕ))) (y : Q(ℕ)) ← Meta.whnfR e | failure haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩ haveI' : $e =Q Nat.lcm $x $y := ⟨⟩ let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat) let ⟨ex, p⟩ ← deriveNat x sℕ let ⟨ey, q⟩ ← deriveNat y sℕ let ⟨ed, pf⟩ := proveNatLCM ex ey return .isNat sℕ ed q(isNat_lcm $p $q $pf) /-- Given two integers, return their GCD and an equality proof. Panics if `ex` or `ey` aren't integer literals. -/ def proveIntGCD (ex ey : Q(ℤ)) : (ed : Q(ℕ)) × Q(Int.gcd $ex $ey = $ed) := let ⟨ex', hx⟩ := rawIntLitNatAbs ex let ⟨ey', hy⟩ := rawIntLitNatAbs ey let ⟨ed, pf⟩ := proveNatGCD ex' ey' ⟨ed, q(int_gcd_helper $hx $hy $pf)⟩ /-- Evaluates the `Int.gcd` function. -/ @[norm_num Int.gcd _ _] def evalIntGCD : NormNumExt where eval {u α} e := do let .app (.app _ (x : Q(ℤ))) (y : Q(ℤ)) ← Meta.whnfR e | failure let ⟨ex, p⟩ ← deriveInt x _ let ⟨ey, q⟩ ← deriveInt y _ haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩ haveI' : $e =Q Int.gcd $x $y := ⟨⟩ let ⟨ed, pf⟩ := proveIntGCD ex ey return .isNat _ ed q(isInt_gcd $p $q $pf) /-- Given two integers, return their LCM and an equality proof. Panics if `ex` or `ey` aren't integer literals. -/ def proveIntLCM (ex ey : Q(ℤ)) : (ed : Q(ℕ)) × Q(Int.lcm $ex $ey = $ed) := let ⟨ex', hx⟩ := rawIntLitNatAbs ex let ⟨ey', hy⟩ := rawIntLitNatAbs ey let ⟨ed, pf⟩ := proveNatLCM ex' ey' ⟨ed, q(int_lcm_helper $hx $hy $pf)⟩ /-- Evaluates the `Int.lcm` function. -/ @[norm_num Int.lcm _ _] def evalIntLCM : NormNumExt where eval {u α} e := do let .app (.app _ (x : Q(ℤ))) (y : Q(ℤ)) ← Meta.whnfR e | failure let ⟨ex, p⟩ ← deriveInt x _ let ⟨ey, q⟩ ← deriveInt y _ haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩ haveI' : $e =Q Int.lcm $x $y := ⟨⟩ let ⟨ed, pf⟩ := proveIntLCM ex ey return .isNat _ ed q(isInt_lcm $p $q $pf) end NormNum end Tactic
Tactic\NormNum\Ineq.lean
/- Copyright (c) 2022 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Tactic.NormNum.Eq import Mathlib.Algebra.Order.Field.Defs import Mathlib.Algebra.Order.Invertible import Mathlib.Algebra.Order.Monoid.WithTop import Mathlib.Algebra.Order.Ring.Cast /-! # `norm_num` extensions for inequalities. -/ open Lean Meta Qq namespace Mathlib.Meta.NormNum variable {u : Level} /-- Helper function to synthesize a typed `OrderedSemiring α` expression. -/ def inferOrderedSemiring (α : Q(Type u)) : MetaM Q(OrderedSemiring $α) := return ← synthInstanceQ (q(OrderedSemiring $α) : Q(Type u)) <|> throwError "not an ordered semiring" /-- Helper function to synthesize a typed `OrderedRing α` expression. -/ def inferOrderedRing (α : Q(Type u)) : MetaM Q(OrderedRing $α) := return ← synthInstanceQ (q(OrderedRing $α) : Q(Type u)) <|> throwError "not an ordered ring" /-- Helper function to synthesize a typed `LinearOrderedField α` expression. -/ def inferLinearOrderedField (α : Q(Type u)) : MetaM Q(LinearOrderedField $α) := return ← synthInstanceQ (q(LinearOrderedField $α) : Q(Type u)) <|> throwError "not a linear ordered field" variable {α : Type*} theorem isNat_le_true [OrderedSemiring α] : {a b : α} → {a' b' : ℕ} → IsNat a a' → IsNat b b' → Nat.ble a' b' = true → a ≤ b | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => Nat.mono_cast (Nat.le_of_ble_eq_true h) theorem isNat_lt_false [OrderedSemiring α] {a b : α} {a' b' : ℕ} (ha : IsNat a a') (hb : IsNat b b') (h : Nat.ble b' a' = true) : ¬a < b := not_lt_of_le (isNat_le_true hb ha h) theorem isRat_le_true [LinearOrderedRing α] : {a b : α} → {na nb : ℤ} → {da db : ℕ} → IsRat a na da → IsRat b nb db → decide (Int.mul na (.ofNat db) ≤ Int.mul nb (.ofNat da)) → a ≤ b | _, _, _, _, da, db, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by have h := Int.cast_mono (R := α) <| of_decide_eq_true h have ha : 0 ≤ ⅟(da : α) := invOf_nonneg.mpr <| Nat.cast_nonneg da have hb : 0 ≤ ⅟(db : α) := invOf_nonneg.mpr <| Nat.cast_nonneg db have h := (mul_le_mul_of_nonneg_left · hb) <| mul_le_mul_of_nonneg_right h ha rw [← mul_assoc, Int.commute_cast] at h simp at h; rwa [Int.commute_cast] at h theorem isRat_lt_true [LinearOrderedRing α] [Nontrivial α] : {a b : α} → {na nb : ℤ} → {da db : ℕ} → IsRat a na da → IsRat b nb db → decide (na * db < nb * da) → a < b | _, _, _, _, da, db, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by have h := Int.cast_strictMono (R := α) <| of_decide_eq_true h have ha : 0 < ⅟(da : α) := pos_invOf_of_invertible_cast da have hb : 0 < ⅟(db : α) := pos_invOf_of_invertible_cast db have h := (mul_lt_mul_of_pos_left · hb) <| mul_lt_mul_of_pos_right h ha rw [← mul_assoc, Int.commute_cast] at h simp? at h says simp only [Int.cast_mul, Int.cast_natCast, mul_mul_invOf_self_cancel'] at h rwa [Int.commute_cast] at h theorem isRat_le_false [LinearOrderedRing α] [Nontrivial α] {a b : α} {na nb : ℤ} {da db : ℕ} (ha : IsRat a na da) (hb : IsRat b nb db) (h : decide (nb * da < na * db)) : ¬a ≤ b := not_le_of_lt (isRat_lt_true hb ha h) theorem isRat_lt_false [LinearOrderedRing α] {a b : α} {na nb : ℤ} {da db : ℕ} (ha : IsRat a na da) (hb : IsRat b nb db) (h : decide (nb * da ≤ na * db)) : ¬a < b := not_lt_of_le (isRat_le_true hb ha h) /-! # (In)equalities -/ theorem isNat_lt_true [OrderedSemiring α] [CharZero α] : {a b : α} → {a' b' : ℕ} → IsNat a a' → IsNat b b' → Nat.ble b' a' = false → a < b | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => Nat.cast_lt.2 <| ble_eq_false.1 h theorem isNat_le_false [OrderedSemiring α] [CharZero α] {a b : α} {a' b' : ℕ} (ha : IsNat a a') (hb : IsNat b b') (h : Nat.ble a' b' = false) : ¬a ≤ b := not_le_of_lt (isNat_lt_true hb ha h) theorem isInt_le_true [OrderedRing α] : {a b : α} → {a' b' : ℤ} → IsInt a a' → IsInt b b' → decide (a' ≤ b') → a ≤ b | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => Int.cast_mono <| of_decide_eq_true h theorem isInt_lt_true [OrderedRing α] [Nontrivial α] : {a b : α} → {a' b' : ℤ} → IsInt a a' → IsInt b b' → decide (a' < b') → a < b | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => Int.cast_lt.2 <| of_decide_eq_true h theorem isInt_le_false [OrderedRing α] [Nontrivial α] {a b : α} {a' b' : ℤ} (ha : IsInt a a') (hb : IsInt b b') (h : decide (b' < a')) : ¬a ≤ b := not_le_of_lt (isInt_lt_true hb ha h) theorem isInt_lt_false [OrderedRing α] {a b : α} {a' b' : ℤ} (ha : IsInt a a') (hb : IsInt b b') (h : decide (b' ≤ a')) : ¬a < b := not_lt_of_le (isInt_le_true hb ha h) /-- The `norm_num` extension which identifies expressions of the form `a ≤ b`, such that `norm_num` successfully recognises both `a` and `b`. -/ @[norm_num _ ≤ _] def evalLE : NormNumExt where eval {v β} e := do haveI' : v =QL 0 := ⟨⟩; haveI' : $β =Q Prop := ⟨⟩ let .app (.app f a) b ← whnfR e | failure let ⟨u, α, a⟩ ← inferTypeQ' a have b : Q($α) := b let ra ← derive a; let rb ← derive b let rec intArm : MetaM (Result e) := do let _i ← inferOrderedRing α guard <|← withNewMCtxDepth <| isDefEq f q(LE.le (α := $α)) haveI' : $e =Q ($a ≤ $b) := ⟨⟩ let ⟨za, na, pa⟩ ← ra.toInt q(OrderedRing.toRing) let ⟨zb, nb, pb⟩ ← rb.toInt q(OrderedRing.toRing) if decide (za ≤ zb) then let r : Q(decide ($na ≤ $nb) = true) := (q(Eq.refl true) : Expr) return .isTrue q(isInt_le_true $pa $pb $r) else if let .some _i ← trySynthInstanceQ (q(@Nontrivial $α) : Q(Prop)) then let r : Q(decide ($nb < $na) = true) := (q(Eq.refl true) : Expr) return .isFalse q(isInt_le_false $pa $pb $r) else failure let rec ratArm : MetaM (Result e) := do -- We need a division ring with an order, and `LinearOrderedField` is the closest mathlib has. let _i ← inferLinearOrderedField α guard <|← withNewMCtxDepth <| isDefEq f q(LE.le (α := $α)) haveI' : $e =Q ($a ≤ $b) := ⟨⟩ let ⟨qa, na, da, pa⟩ ← ra.toRat' q(Field.toDivisionRing) let ⟨qb, nb, db, pb⟩ ← rb.toRat' q(Field.toDivisionRing) if decide (qa ≤ qb) then let r : Q(decide ($na * $db ≤ $nb * $da) = true) := (q(Eq.refl true) : Expr) return (.isTrue q(isRat_le_true $pa $pb $r)) else let _i : Q(Nontrivial $α) := q(StrictOrderedRing.toNontrivial) let r : Q(decide ($nb * $da < $na * $db) = true) := (q(Eq.refl true) : Expr) return .isFalse q(isRat_le_false $pa $pb $r) match ra, rb with | .isBool .., _ | _, .isBool .. => failure | .isRat _ .., _ | _, .isRat _ .. => ratArm | .isNegNat _ .., _ | _, .isNegNat _ .. => intArm | .isNat ra na pa, .isNat rb nb pb => let _i ← inferOrderedSemiring α haveI' : $ra =Q by clear! $ra $rb; infer_instance := ⟨⟩ haveI' : $rb =Q by clear! $ra $rb; infer_instance := ⟨⟩ guard <|← withNewMCtxDepth <| isDefEq f q(LE.le (α := $α)) haveI' : $e =Q ($a ≤ $b) := ⟨⟩ if na.natLit! ≤ nb.natLit! then let r : Q(Nat.ble $na $nb = true) := (q(Eq.refl true) : Expr) return .isTrue q(isNat_le_true $pa $pb $r) else if let .some _i ← trySynthInstanceQ (q(CharZero $α) : Q(Prop)) then let r : Q(Nat.ble $na $nb = false) := (q(Eq.refl false) : Expr) return .isFalse q(isNat_le_false $pa $pb $r) else -- Nats can appear in an `OrderedRing` without `CharZero`. intArm /-- The `norm_num` extension which identifies expressions of the form `a < b`, such that `norm_num` successfully recognises both `a` and `b`. -/ @[norm_num _ < _] def evalLT : NormNumExt where eval {v β} e := do haveI' : v =QL 0 := ⟨⟩; haveI' : $β =Q Prop := ⟨⟩ let .app (.app f a) b ← whnfR e | failure let ⟨u, α, a⟩ ← inferTypeQ' a have b : Q($α) := b let ra ← derive a; let rb ← derive b let rec intArm : MetaM (Result e) := do let _i ← inferOrderedRing α assumeInstancesCommute guard <|← withNewMCtxDepth <| isDefEq f q(LT.lt (α := $α)) haveI' : $e =Q ($a < $b) := ⟨⟩ let ⟨za, na, pa⟩ ← ra.toInt q(OrderedRing.toRing) let ⟨zb, nb, pb⟩ ← rb.toInt q(OrderedRing.toRing) if za < zb then if let .some _i ← trySynthInstanceQ (q(@Nontrivial $α) : Q(Prop)) then let r : Q(decide ($na < $nb) = true) := (q(Eq.refl true) : Expr) return .isTrue q(isInt_lt_true $pa $pb $r) else failure else let r : Q(decide ($nb ≤ $na) = true) := (q(Eq.refl true) : Expr) return .isFalse q(isInt_lt_false $pa $pb $r) let rec ratArm : MetaM (Result e) := do -- We need a division ring with an order, and `LinearOrderedField` is the closest mathlib has. let _i ← inferLinearOrderedField α assumeInstancesCommute haveI' : $e =Q ($a < $b) := ⟨⟩ guard <|← withNewMCtxDepth <| isDefEq f q(LT.lt (α := $α)) let ⟨qa, na, da, pa⟩ ← ra.toRat' q(Field.toDivisionRing) let ⟨qb, nb, db, pb⟩ ← rb.toRat' q(Field.toDivisionRing) if qa < qb then let r : Q(decide ($na * $db < $nb * $da) = true) := (q(Eq.refl true) : Expr) return .isTrue q(isRat_lt_true $pa $pb $r) else let r : Q(decide ($nb * $da ≤ $na * $db) = true) := (q(Eq.refl true) : Expr) return .isFalse q(isRat_lt_false $pa $pb $r) match ra, rb with | .isBool .., _ | _, .isBool .. => failure | .isRat _ .., _ | _, .isRat _ .. => ratArm | .isNegNat _ .., _ | _, .isNegNat _ .. => intArm | .isNat ra na pa, .isNat rb nb pb => let _i ← inferOrderedSemiring α haveI' : $ra =Q by clear! $ra $rb; infer_instance := ⟨⟩ haveI' : $rb =Q by clear! $ra $rb; infer_instance := ⟨⟩ haveI' : $e =Q ($a < $b) := ⟨⟩ guard <|← withNewMCtxDepth <| isDefEq f q(LT.lt (α := $α)) if na.natLit! < nb.natLit! then if let .some _i ← trySynthInstanceQ q(CharZero $α) then let r : Q(Nat.ble $nb $na = false) := (q(Eq.refl false) : Expr) return .isTrue q(isNat_lt_true $pa $pb $r) else -- Nats can appear in an `OrderedRing` without `CharZero`. intArm else let r : Q(Nat.ble $nb $na = true) := (q(Eq.refl true) : Expr) return .isFalse q(isNat_lt_false $pa $pb $r) end Mathlib.Meta.NormNum
Tactic\NormNum\Inv.lean
/- Copyright (c) 2022 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Tactic.NormNum.Basic import Mathlib.Data.Rat.Cast.CharZero import Mathlib.Algebra.Field.Basic /-! # `norm_num` plugins for `Rat.cast` and `⁻¹`. -/ variable {u : Lean.Level} namespace Mathlib.Meta.NormNum open Lean.Meta Qq /-- Helper function to synthesize a typed `CharZero α` expression given `Ring α`. -/ def inferCharZeroOfRing {α : Q(Type u)} (_i : Q(Ring $α) := by with_reducible assumption) : MetaM Q(CharZero $α) := return ← synthInstanceQ (q(CharZero $α) : Q(Prop)) <|> throwError "not a characteristic zero ring" /-- Helper function to synthesize a typed `CharZero α` expression given `Ring α`, if it exists. -/ def inferCharZeroOfRing? {α : Q(Type u)} (_i : Q(Ring $α) := by with_reducible assumption) : MetaM (Option Q(CharZero $α)) := return (← trySynthInstanceQ (q(CharZero $α) : Q(Prop))).toOption /-- Helper function to synthesize a typed `CharZero α` expression given `AddMonoidWithOne α`. -/ def inferCharZeroOfAddMonoidWithOne {α : Q(Type u)} (_i : Q(AddMonoidWithOne $α) := by with_reducible assumption) : MetaM Q(CharZero $α) := return ← synthInstanceQ (q(CharZero $α) : Q(Prop)) <|> throwError "not a characteristic zero AddMonoidWithOne" /-- Helper function to synthesize a typed `CharZero α` expression given `AddMonoidWithOne α`, if it exists. -/ def inferCharZeroOfAddMonoidWithOne? {α : Q(Type u)} (_i : Q(AddMonoidWithOne $α) := by with_reducible assumption) : MetaM (Option Q(CharZero $α)) := return (← trySynthInstanceQ (q(CharZero $α) : Q(Prop))).toOption /-- Helper function to synthesize a typed `CharZero α` expression given `DivisionRing α`. -/ def inferCharZeroOfDivisionRing {α : Q(Type u)} (_i : Q(DivisionRing $α) := by with_reducible assumption) : MetaM Q(CharZero $α) := return ← synthInstanceQ (q(CharZero $α) : Q(Prop)) <|> throwError "not a characteristic zero division ring" /-- Helper function to synthesize a typed `CharZero α` expression given `DivisionRing α`, if it exists. -/ def inferCharZeroOfDivisionRing? {α : Q(Type u)} (_i : Q(DivisionRing $α) := by with_reducible assumption) : MetaM (Option Q(CharZero $α)) := return (← trySynthInstanceQ (q(CharZero $α) : Q(Prop))).toOption theorem isRat_mkRat : {a na n : ℤ} → {b nb d : ℕ} → IsInt a na → IsNat b nb → IsRat (na / nb : ℚ) n d → IsRat (mkRat a b) n d | _, _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, ⟨_, h⟩ => by rw [Rat.mkRat_eq_div]; exact ⟨_, h⟩ /-- The `norm_num` extension which identifies expressions of the form `mkRat a b`, such that `norm_num` successfully recognises both `a` and `b`, and returns `a / b`. -/ @[norm_num mkRat _ _] def evalMkRat : NormNumExt where eval {u α} (e : Q(ℚ)) : MetaM (Result e) := do let .app (.app (.const ``mkRat _) (a : Q(ℤ))) (b : Q(ℕ)) ← whnfR e | failure haveI' : $e =Q mkRat $a $b := ⟨⟩ let ra ← derive a let some ⟨_, na, pa⟩ := ra.toInt (q(Int.instRing) : Q(Ring Int)) | failure let ⟨nb, pb⟩ ← deriveNat q($b) q(AddCommMonoidWithOne.toAddMonoidWithOne) let rab ← derive q($na / $nb : Rat) let ⟨q, n, d, p⟩ ← rab.toRat' q(Rat.instDivisionRing) return .isRat' _ q n d q(isRat_mkRat $pa $pb $p) theorem isNat_ratCast {R : Type*} [DivisionRing R] : {q : ℚ} → {n : ℕ} → IsNat q n → IsNat (q : R) n | _, _, ⟨rfl⟩ => ⟨by simp⟩ theorem isInt_ratCast {R : Type*} [DivisionRing R] : {q : ℚ} → {n : ℤ} → IsInt q n → IsInt (q : R) n | _, _, ⟨rfl⟩ => ⟨by simp⟩ theorem isRat_ratCast {R : Type*} [DivisionRing R] [CharZero R] : {q : ℚ} → {n : ℤ} → {d : ℕ} → IsRat q n d → IsRat (q : R) n d | _, _, _, ⟨⟨qi,_,_⟩, rfl⟩ => ⟨⟨qi, by norm_cast, by norm_cast⟩, by simp only []; norm_cast⟩ /-- The `norm_num` extension which identifies an expression `RatCast.ratCast q` where `norm_num` recognizes `q`, returning the cast of `q`. -/ @[norm_num Rat.cast _, RatCast.ratCast _] def evalRatCast : NormNumExt where eval {u α} e := do let dα ← inferDivisionRing α let .app r (a : Q(ℚ)) ← whnfR e | failure guard <|← withNewMCtxDepth <| isDefEq r q(Rat.cast (K := $α)) let r ← derive q($a) haveI' : $e =Q Rat.cast $a := ⟨⟩ match r with | .isNat _ na pa => assumeInstancesCommute return .isNat _ na q(isNat_ratCast $pa) | .isNegNat _ na pa => assumeInstancesCommute return .isNegNat _ na q(isInt_ratCast $pa) | .isRat _ qa na da pa => assumeInstancesCommute let i ← inferCharZeroOfDivisionRing dα return .isRat dα qa na da q(isRat_ratCast $pa) | _ => failure theorem isRat_inv_pos {α} [DivisionRing α] [CharZero α] {a : α} {n d : ℕ} : IsRat a (.ofNat (Nat.succ n)) d → IsRat a⁻¹ (.ofNat d) (Nat.succ n) := by rintro ⟨_, rfl⟩ have := invertibleOfNonzero (α := α) (Nat.cast_ne_zero.2 (Nat.succ_ne_zero n)) exact ⟨this, by simp⟩ theorem isRat_inv_one {α} [DivisionRing α] : {a : α} → IsNat a (nat_lit 1) → IsNat a⁻¹ (nat_lit 1) | _, ⟨rfl⟩ => ⟨by simp⟩ theorem isRat_inv_zero {α} [DivisionRing α] : {a : α} → IsNat a (nat_lit 0) → IsNat a⁻¹ (nat_lit 0) | _, ⟨rfl⟩ => ⟨by simp⟩ theorem isRat_inv_neg_one {α} [DivisionRing α] : {a : α} → IsInt a (.negOfNat (nat_lit 1)) → IsInt a⁻¹ (.negOfNat (nat_lit 1)) | _, ⟨rfl⟩ => ⟨by simp [inv_neg_one]⟩ theorem isRat_inv_neg {α} [DivisionRing α] [CharZero α] {a : α} {n d : ℕ} : IsRat a (.negOfNat (Nat.succ n)) d → IsRat a⁻¹ (.negOfNat d) (Nat.succ n) := by rintro ⟨_, rfl⟩ simp only [Int.negOfNat_eq] have := invertibleOfNonzero (α := α) (Nat.cast_ne_zero.2 (Nat.succ_ne_zero n)) generalize Nat.succ n = n at * use this; simp only [Int.ofNat_eq_coe, Int.cast_neg, Int.cast_natCast, invOf_eq_inv, inv_neg, neg_mul, mul_inv_rev, inv_inv] open Lean /-- The `norm_num` extension which identifies expressions of the form `a⁻¹`, such that `norm_num` successfully recognises `a`. -/ @[norm_num _⁻¹] def evalInv : NormNumExt where eval {u α} e := do let .app f (a : Q($α)) ← whnfR e | failure let ra ← derive a let dα ← inferDivisionRing α let i ← inferCharZeroOfDivisionRing? dα guard <|← withNewMCtxDepth <| isDefEq f q(Inv.inv (α := $α)) haveI' : $e =Q $a⁻¹ := ⟨⟩ assumeInstancesCommute let rec /-- Main part of `evalInv`. -/ core : Option (Result e) := do let ⟨qa, na, da, pa⟩ ← ra.toRat' dα let qb := qa⁻¹ if qa > 0 then if let some i := i then have lit : Q(ℕ) := na.appArg! haveI : $na =Q Int.ofNat $lit := ⟨⟩ have lit2 : Q(ℕ) := mkRawNatLit (lit.natLit! - 1) haveI : $lit =Q ($lit2).succ := ⟨⟩ return .isRat' dα qb q(.ofNat $da) lit q(isRat_inv_pos $pa) else guard (qa = 1) let .isNat inst n pa := ra | failure haveI' : $n =Q nat_lit 1 := ⟨⟩ assumeInstancesCommute return .isNat inst n q(isRat_inv_one $pa) else if qa < 0 then if let some i := i then have lit : Q(ℕ) := na.appArg! haveI : $na =Q Int.negOfNat $lit := ⟨⟩ have lit2 : Q(ℕ) := mkRawNatLit (lit.natLit! - 1) haveI : $lit =Q ($lit2).succ := ⟨⟩ return .isRat' dα qb q(.negOfNat $da) lit q(isRat_inv_neg $pa) else guard (qa = -1) let .isNegNat inst n pa := ra | failure haveI' : $n =Q nat_lit 1 := ⟨⟩ assumeInstancesCommute return .isNegNat inst n q(isRat_inv_neg_one $pa) else let .isNat inst n pa := ra | failure haveI' : $n =Q nat_lit 0 := ⟨⟩ assumeInstancesCommute return .isNat inst n q(isRat_inv_zero $pa) core end Mathlib.Meta.NormNum
Tactic\NormNum\IsCoprime.lean
/- Copyright (c) 2023 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.RingTheory.Coprime.Lemmas import Mathlib.Tactic.NormNum.GCD /-! # `norm_num` extension for `IsCoprime` This module defines a `norm_num` extension for `IsCoprime` over `ℤ`. (While `IsCoprime` is defined over `ℕ`, since it uses Bezout's identity with `ℕ` coefficients it does not correspond to the usual notion of coprime.) -/ namespace Tactic namespace NormNum open Qq Lean Elab.Tactic Mathlib.Meta.NormNum theorem int_not_isCoprime_helper (x y : ℤ) (d : ℕ) (hd : Int.gcd x y = d) (h : Nat.beq d 1 = false) : ¬ IsCoprime x y := by rw [Int.isCoprime_iff_gcd_eq_one, hd] exact Nat.ne_of_beq_eq_false h theorem isInt_isCoprime : {x y nx ny : ℤ} → IsInt x nx → IsInt y ny → IsCoprime nx ny → IsCoprime x y | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => h theorem isInt_not_isCoprime : {x y nx ny : ℤ} → IsInt x nx → IsInt y ny → ¬ IsCoprime nx ny → ¬ IsCoprime x y | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => h /-- Evaluates `IsCoprime` for the given integer number literals. Panics if `ex` or `ey` aren't integer number literals. -/ def proveIntIsCoprime (ex ey : Q(ℤ)) : Q(IsCoprime $ex $ey) ⊕ Q(¬ IsCoprime $ex $ey) := let ⟨ed, pf⟩ := proveIntGCD ex ey if ed.natLit! = 1 then have pf' : Q(Int.gcd $ex $ey = 1) := pf Sum.inl q(Int.isCoprime_iff_gcd_eq_one.mpr $pf') else have h : Q(Nat.beq $ed 1 = false) := (q(Eq.refl false) : Expr) Sum.inr q(int_not_isCoprime_helper $ex $ey $ed $pf $h) /-- Evaluates the `IsCoprime` predicate over `ℤ`. -/ @[norm_num IsCoprime (_ : ℤ) (_ : ℤ)] def evalIntIsCoprime : NormNumExt where eval {u α} e := do let .app (.app _ (x : Q(ℤ))) (y : Q(ℤ)) ← Meta.whnfR e | failure let ⟨ex, p⟩ ← deriveInt x _ let ⟨ey, q⟩ ← deriveInt y _ match proveIntIsCoprime ex ey with | .inl pf => have pf' : Q(IsCoprime $x $y) := q(isInt_isCoprime $p $q $pf) return .isTrue pf' | .inr pf => have pf' : Q(¬ IsCoprime $x $y) := q(isInt_not_isCoprime $p $q $pf) return .isFalse pf' end NormNum end Tactic
Tactic\NormNum\LegendreSymbol.lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import Mathlib.NumberTheory.LegendreSymbol.JacobiSymbol /-! # A `norm_num` extension for Jacobi and Legendre symbols We extend the `norm_num` tactic so that it can be used to provably compute the value of the Jacobi symbol `J(a | b)` or the Legendre symbol `legendreSym p a` when the arguments are numerals. ## Implementation notes We use the Law of Quadratic Reciprocity for the Jacobi symbol to compute the value of `J(a | b)` efficiently, roughly comparable in effort with the euclidean algorithm for the computation of the gcd of `a` and `b`. More precisely, the computation is done in the following steps. * Use `J(a | 0) = 1` (an artifact of the definition) and `J(a | 1) = 1` to deal with corner cases. * Use `J(a | b) = J(a % b | b)` to reduce to the case that `a` is a natural number. We define a version of the Jacobi symbol restricted to natural numbers for use in the following steps; see `NormNum.jacobiSymNat`. (But we'll continue to write `J(a | b)` in this description.) * Remove powers of two from `b`. This is done via `J(2a | 2b) = 0` and `J(2a+1 | 2b) = J(2a+1 | b)` (another artifact of the definition). * Now `0 ≤ a < b` and `b` is odd. If `b = 1`, then the value is `1`. If `a = 0` (and `b > 1`), then the value is `0`. Otherwise, we remove powers of two from `a` via `J(4a | b) = J(a | b)` and `J(2a | b) = ±J(a | b)`, where the sign is determined by the residue class of `b` mod 8, to reduce to `a` odd. * Once `a` is odd, we use Quadratic Reciprocity (QR) in the form `J(a | b) = ±J(b % a | a)`, where the sign is determined by the residue classes of `a` and `b` mod 4. We are then back in the previous case. We provide customized versions of these results for the various reduction steps, where we encode the residue classes mod 2, mod 4, or mod 8 by using hypotheses like `a % n = b`. In this way, the only divisions we have to compute and prove are the ones occurring in the use of QR above. -/ section Lemmas namespace Mathlib.Meta.NormNum /-- The Jacobi symbol restricted to natural numbers in both arguments. -/ def jacobiSymNat (a b : ℕ) : ℤ := jacobiSym a b /-! ### API Lemmas We repeat part of the API for `jacobiSym` with `NormNum.jacobiSymNat` and without implicit arguments, in a form that is suitable for constructing proofs in `norm_num`. -/ /-- Base cases: `b = 0`, `b = 1`, `a = 0`, `a = 1`. -/ theorem jacobiSymNat.zero_right (a : ℕ) : jacobiSymNat a 0 = 1 := by rw [jacobiSymNat, jacobiSym.zero_right] theorem jacobiSymNat.one_right (a : ℕ) : jacobiSymNat a 1 = 1 := by rw [jacobiSymNat, jacobiSym.one_right] theorem jacobiSymNat.zero_left (b : ℕ) (hb : Nat.beq (b / 2) 0 = false) : jacobiSymNat 0 b = 0 := by rw [jacobiSymNat, Nat.cast_zero, jacobiSym.zero_left ?_] calc 1 < 2 * 1 := by decide _ ≤ 2 * (b / 2) := Nat.mul_le_mul_left _ (Nat.succ_le.mpr (Nat.pos_of_ne_zero (Nat.ne_of_beq_eq_false hb))) _ ≤ b := Nat.mul_div_le b 2 theorem jacobiSymNat.one_left (b : ℕ) : jacobiSymNat 1 b = 1 := by rw [jacobiSymNat, Nat.cast_one, jacobiSym.one_left] /-- Turn a Legendre symbol into a Jacobi symbol. -/ theorem LegendreSym.to_jacobiSym (p : ℕ) (pp : Fact p.Prime) (a r : ℤ) (hr : IsInt (jacobiSym a p) r) : IsInt (legendreSym p a) r := by rwa [@jacobiSym.legendreSym.to_jacobiSym p pp a] /-- The value depends only on the residue class of `a` mod `b`. -/ theorem JacobiSym.mod_left (a : ℤ) (b ab' : ℕ) (ab r b' : ℤ) (hb' : (b : ℤ) = b') (hab : a % b' = ab) (h : (ab' : ℤ) = ab) (hr : jacobiSymNat ab' b = r) : jacobiSym a b = r := by rw [← hr, jacobiSymNat, jacobiSym.mod_left, hb', hab, ← h] theorem jacobiSymNat.mod_left (a b ab : ℕ) (r : ℤ) (hab : a % b = ab) (hr : jacobiSymNat ab b = r) : jacobiSymNat a b = r := by rw [← hr, jacobiSymNat, jacobiSymNat, _root_.jacobiSym.mod_left a b, ← hab]; rfl /-- The symbol vanishes when both entries are even (and `b / 2 ≠ 0`). -/ theorem jacobiSymNat.even_even (a b : ℕ) (hb₀ : Nat.beq (b / 2) 0 = false) (ha : a % 2 = 0) (hb₁ : b % 2 = 0) : jacobiSymNat a b = 0 := by refine jacobiSym.eq_zero_iff.mpr ⟨ne_of_gt ((Nat.pos_of_ne_zero (Nat.ne_of_beq_eq_false hb₀)).trans_le (Nat.div_le_self b 2)), fun hf => ?_⟩ have h : 2 ∣ a.gcd b := Nat.dvd_gcd (Nat.dvd_of_mod_eq_zero ha) (Nat.dvd_of_mod_eq_zero hb₁) change 2 ∣ (a : ℤ).gcd b at h rw [hf, ← even_iff_two_dvd] at h exact Nat.not_even_one h /-- When `a` is odd and `b` is even, we can replace `b` by `b / 2`. -/ theorem jacobiSymNat.odd_even (a b c : ℕ) (r : ℤ) (ha : a % 2 = 1) (hb : b % 2 = 0) (hc : b / 2 = c) (hr : jacobiSymNat a c = r) : jacobiSymNat a b = r := by have ha' : legendreSym 2 a = 1 := by simp only [legendreSym.mod 2 a, Int.ofNat_mod_ofNat, ha] decide rcases eq_or_ne c 0 with (rfl | hc') · rw [← hr, Nat.eq_zero_of_dvd_of_div_eq_zero (Nat.dvd_of_mod_eq_zero hb) hc] · haveI : NeZero c := ⟨hc'⟩ -- for `jacobiSym.mul_right` rwa [← Nat.mod_add_div b 2, hb, hc, Nat.zero_add, jacobiSymNat, jacobiSym.mul_right, ← jacobiSym.legendreSym.to_jacobiSym, ha', one_mul] /-- If `a` is divisible by `4` and `b` is odd, then we can remove the factor `4` from `a`. -/ theorem jacobiSymNat.double_even (a b c : ℕ) (r : ℤ) (ha : a % 4 = 0) (hb : b % 2 = 1) (hc : a / 4 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = r := by simp only [jacobiSymNat, ← hr, ← hc, Int.ofNat_ediv, Nat.cast_ofNat] exact (jacobiSym.div_four_left (mod_cast ha) hb).symm /-- If `a` is even and `b` is odd, then we can remove a factor `2` from `a`, but we may have to change the sign, depending on `b % 8`. We give one version for each of the four odd residue classes mod `8`. -/ theorem jacobiSymNat.even_odd₁ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 1) (hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = r := by simp only [jacobiSymNat, ← hr, ← hc, Int.ofNat_ediv, Nat.cast_ofNat] rw [← jacobiSym.even_odd (mod_cast ha), if_neg (by simp [hb])] rw [← Nat.mod_mod_of_dvd, hb]; norm_num theorem jacobiSymNat.even_odd₇ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 7) (hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = r := by simp only [jacobiSymNat, ← hr, ← hc, Int.ofNat_ediv, Nat.cast_ofNat] rw [← jacobiSym.even_odd (mod_cast ha), if_neg (by simp [hb])] rw [← Nat.mod_mod_of_dvd, hb]; norm_num theorem jacobiSymNat.even_odd₃ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 3) (hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = -r := by simp only [jacobiSymNat, ← hr, ← hc, Int.ofNat_ediv, Nat.cast_ofNat] rw [← jacobiSym.even_odd (mod_cast ha), if_pos (by simp [hb])] rw [← Nat.mod_mod_of_dvd, hb]; norm_num theorem jacobiSymNat.even_odd₅ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 5) (hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = -r := by simp only [jacobiSymNat, ← hr, ← hc, Int.ofNat_ediv, Nat.cast_ofNat] rw [← jacobiSym.even_odd (mod_cast ha), if_pos (by simp [hb])] rw [← Nat.mod_mod_of_dvd, hb]; norm_num /-- Use quadratic reciproity to reduce to smaller `b`. -/ theorem jacobiSymNat.qr₁ (a b : ℕ) (r : ℤ) (ha : a % 4 = 1) (hb : b % 2 = 1) (hr : jacobiSymNat b a = r) : jacobiSymNat a b = r := by rwa [jacobiSymNat, jacobiSym.quadratic_reciprocity_one_mod_four ha (Nat.odd_iff.mpr hb)] theorem jacobiSymNat.qr₁_mod (a b ab : ℕ) (r : ℤ) (ha : a % 4 = 1) (hb : b % 2 = 1) (hab : b % a = ab) (hr : jacobiSymNat ab a = r) : jacobiSymNat a b = r := jacobiSymNat.qr₁ _ _ _ ha hb <| jacobiSymNat.mod_left _ _ ab r hab hr theorem jacobiSymNat.qr₁' (a b : ℕ) (r : ℤ) (ha : a % 2 = 1) (hb : b % 4 = 1) (hr : jacobiSymNat b a = r) : jacobiSymNat a b = r := by rwa [jacobiSymNat, ← jacobiSym.quadratic_reciprocity_one_mod_four hb (Nat.odd_iff.mpr ha)] theorem jacobiSymNat.qr₁'_mod (a b ab : ℕ) (r : ℤ) (ha : a % 2 = 1) (hb : b % 4 = 1) (hab : b % a = ab) (hr : jacobiSymNat ab a = r) : jacobiSymNat a b = r := jacobiSymNat.qr₁' _ _ _ ha hb <| jacobiSymNat.mod_left _ _ ab r hab hr theorem jacobiSymNat.qr₃ (a b : ℕ) (r : ℤ) (ha : a % 4 = 3) (hb : b % 4 = 3) (hr : jacobiSymNat b a = r) : jacobiSymNat a b = -r := by rwa [jacobiSymNat, jacobiSym.quadratic_reciprocity_three_mod_four ha hb, neg_inj] theorem jacobiSymNat.qr₃_mod (a b ab : ℕ) (r : ℤ) (ha : a % 4 = 3) (hb : b % 4 = 3) (hab : b % a = ab) (hr : jacobiSymNat ab a = r) : jacobiSymNat a b = -r := jacobiSymNat.qr₃ _ _ _ ha hb <| jacobiSymNat.mod_left _ _ ab r hab hr theorem isInt_jacobiSym : {a na : ℤ} → {b nb : ℕ} → {r : ℤ} → IsInt a na → IsNat b nb → jacobiSym na nb = r → IsInt (jacobiSym a b) r | _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩ theorem isInt_jacobiSymNat : {a na : ℕ} → {b nb : ℕ} → {r : ℤ} → IsNat a na → IsNat b nb → jacobiSymNat na nb = r → IsInt (jacobiSymNat a b) r | _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩ end Mathlib.Meta.NormNum end Lemmas section Evaluation /-! ### Certified evaluation of the Jacobi symbol The following functions recursively evaluate a Jacobi symbol and construct the corresponding proof term. -/ namespace Mathlib.Meta.NormNum open Lean Elab Tactic Qq /-- This evaluates `r := jacobiSymNat a b` recursively using quadratic reciprocity and produces a proof term for the equality, assuming that `a < b` and `b` is odd. -/ partial def proveJacobiSymOdd (ea eb : Q(ℕ)) : (er : Q(ℤ)) × Q(jacobiSymNat $ea $eb = $er) := match eb.natLit! with | 1 => haveI : $eb =Q 1 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSymNat.one_right $ea)⟩ | b => match ea.natLit! with | 0 => haveI : $ea =Q 0 := ⟨⟩ have hb : Q(Nat.beq ($eb / 2) 0 = false) := (q(Eq.refl false) : Expr) ⟨mkRawIntLit 0, q(jacobiSymNat.zero_left $eb $hb)⟩ | 1 => haveI : $ea =Q 1 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSymNat.one_left $eb)⟩ | a => match a % 2 with | 0 => match a % 4 with | 0 => have ha : Q(Nat.mod $ea 4 = 0) := (q(Eq.refl 0) : Expr) have hb : Q(Nat.mod $eb 2 = 1) := (q(Eq.refl 1) : Expr) have ec : Q(ℕ) := mkRawNatLit (a / 4) have hc : Q(Nat.div $ea 4 = $ec) := (q(Eq.refl $ec) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd ec eb ⟨er, q(jacobiSymNat.double_even $ea $eb $ec $er $ha $hb $hc $p)⟩ | _ => have ha : Q(Nat.mod $ea 2 = 0) := (q(Eq.refl 0) : Expr) have ec : Q(ℕ) := mkRawNatLit (a / 2) have hc : Q(Nat.div $ea 2 = $ec) := (q(Eq.refl $ec) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd ec eb match b % 8 with | 1 => have hb : Q(Nat.mod $eb 8 = 1) := (q(Eq.refl 1) : Expr) ⟨er, q(jacobiSymNat.even_odd₁ $ea $eb $ec $er $ha $hb $hc $p)⟩ | 3 => have er' := mkRawIntLit (-er.intLit!) have hb : Q(Nat.mod $eb 8 = 3) := (q(Eq.refl 3) : Expr) show (_ : Q(ℤ)) × Q(jacobiSymNat $ea $eb = -$er) from ⟨er', q(jacobiSymNat.even_odd₃ $ea $eb $ec $er $ha $hb $hc $p)⟩ | 5 => have er' := mkRawIntLit (-er.intLit!) haveI : $er' =Q -$er := ⟨⟩ have hb : Q(Nat.mod $eb 8 = 5) := (q(Eq.refl 5) : Expr) ⟨er', q(jacobiSymNat.even_odd₅ $ea $eb $ec $er $ha $hb $hc $p)⟩ | _ => have hb : Q(Nat.mod $eb 8 = 7) := (q(Eq.refl 7) : Expr) ⟨er, q(jacobiSymNat.even_odd₇ $ea $eb $ec $er $ha $hb $hc $p)⟩ | _ => have eab : Q(ℕ) := mkRawNatLit (b % a) have hab : Q(Nat.mod $eb $ea = $eab) := (q(Eq.refl $eab) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd eab ea match a % 4 with | 1 => have ha : Q(Nat.mod $ea 4 = 1) := (q(Eq.refl 1) : Expr) have hb : Q(Nat.mod $eb 2 = 1) := (q(Eq.refl 1) : Expr) ⟨er, q(jacobiSymNat.qr₁_mod $ea $eb $eab $er $ha $hb $hab $p)⟩ | _ => match b % 4 with | 1 => have ha : Q(Nat.mod $ea 2 = 1) := (q(Eq.refl 1) : Expr) have hb : Q(Nat.mod $eb 4 = 1) := (q(Eq.refl 1) : Expr) ⟨er, q(jacobiSymNat.qr₁'_mod $ea $eb $eab $er $ha $hb $hab $p)⟩ | _ => have er' := mkRawIntLit (-er.intLit!) haveI : $er' =Q -$er := ⟨⟩ have ha : Q(Nat.mod $ea 4 = 3) := (q(Eq.refl 3) : Expr) have hb : Q(Nat.mod $eb 4 = 3) := (q(Eq.refl 3) : Expr) ⟨er', q(jacobiSymNat.qr₃_mod $ea $eb $eab $er $ha $hb $hab $p)⟩ /-- This evaluates `r := jacobiSymNat a b` and produces a proof term for the equality by removing powers of `2` from `b` and then calling `proveJacobiSymOdd`. -/ partial def proveJacobiSymNat (ea eb : Q(ℕ)) : (er : Q(ℤ)) × Q(jacobiSymNat $ea $eb = $er) := match eb.natLit! with | 0 => haveI : $eb =Q 0 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSymNat.zero_right $ea)⟩ | 1 => haveI : $eb =Q 1 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSymNat.one_right $ea)⟩ | b => match b % 2 with | 0 => match ea.natLit! with | 0 => have hb : Q(Nat.beq ($eb / 2) 0 = false) := (q(Eq.refl false) : Expr) show (er : Q(ℤ)) × Q(jacobiSymNat 0 $eb = $er) from ⟨mkRawIntLit 0, q(jacobiSymNat.zero_left $eb $hb)⟩ | 1 => show (er : Q(ℤ)) × Q(jacobiSymNat 1 $eb = $er) from ⟨mkRawIntLit 1, q(jacobiSymNat.one_left $eb)⟩ | a => match a % 2 with | 0 => have hb₀ : Q(Nat.beq ($eb / 2) 0 = false) := (q(Eq.refl false) : Expr) have ha : Q(Nat.mod $ea 2 = 0) := (q(Eq.refl 0) : Expr) have hb₁ : Q(Nat.mod $eb 2 = 0) := (q(Eq.refl 0) : Expr) ⟨mkRawIntLit 0, q(jacobiSymNat.even_even $ea $eb $hb₀ $ha $hb₁)⟩ | _ => have ha : Q(Nat.mod $ea 2 = 1) := (q(Eq.refl 1) : Expr) have hb : Q(Nat.mod $eb 2 = 0) := (q(Eq.refl 0) : Expr) have ec : Q(ℕ) := mkRawNatLit (b / 2) have hc : Q(Nat.div $eb 2 = $ec) := (q(Eq.refl $ec) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd ea ec ⟨er, q(jacobiSymNat.odd_even $ea $eb $ec $er $ha $hb $hc $p)⟩ | _ => have a := ea.natLit! if b ≤ a then have eab : Q(ℕ) := mkRawNatLit (a % b) have hab : Q(Nat.mod $ea $eb = $eab) := (q(Eq.refl $eab) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd eab eb ⟨er, q(jacobiSymNat.mod_left $ea $eb $eab $er $hab $p)⟩ else proveJacobiSymOdd ea eb /-- This evaluates `r := jacobiSym a b` and produces a proof term for the equality. This is done by reducing to `r := jacobiSymNat (a % b) b`. -/ partial def proveJacobiSym (ea : Q(ℤ)) (eb : Q(ℕ)) : (er : Q(ℤ)) × Q(jacobiSym $ea $eb = $er) := match eb.natLit! with | 0 => haveI : $eb =Q 0 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSym.zero_right $ea)⟩ | 1 => haveI : $eb =Q 1 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSym.one_right $ea)⟩ | b => have eb' := mkRawIntLit b have hb' : Q(($eb : ℤ) = $eb') := (q(Eq.refl $eb') : Expr) have ab := ea.intLit! % b have eab := mkRawIntLit ab have hab : Q(Int.emod $ea $eb' = $eab) := (q(Eq.refl $eab) : Expr) have eab' : Q(ℕ) := mkRawNatLit ab.toNat have hab' : Q(($eab' : ℤ) = $eab) := (q(Eq.refl $eab) : Expr) have ⟨er, p⟩ := proveJacobiSymNat eab' eb ⟨er, q(JacobiSym.mod_left $ea $eb $eab' $eab $er $eb' $hb' $hab $hab' $p)⟩ end Mathlib.Meta.NormNum end Evaluation section Tactic /-! ### The `norm_num` plug-in -/ namespace Tactic namespace NormNum open Lean Elab Tactic Qq Mathlib.Meta.NormNum /-- This is the `norm_num` plug-in that evaluates Jacobi symbols. -/ @[norm_num jacobiSym _ _] def evalJacobiSym : NormNumExt where eval {u α} e := do let .app (.app _ (a : Q(ℤ))) (b : Q(ℕ)) ← Meta.whnfR e | failure let ⟨ea, pa⟩ ← deriveInt a _ let ⟨eb, pb⟩ ← deriveNat b _ haveI' : u =QL 0 := ⟨⟩ haveI' : $α =Q ℤ := ⟨⟩ have ⟨er, pr⟩ := proveJacobiSym ea eb haveI' : $e =Q jacobiSym $a $b := ⟨⟩ return .isInt _ er er.intLit! q(isInt_jacobiSym $pa $pb $pr) /-- This is the `norm_num` plug-in that evaluates Jacobi symbols on natural numbers. -/ @[norm_num jacobiSymNat _ _] def evalJacobiSymNat : NormNumExt where eval {u α} e := do let .app (.app _ (a : Q(ℕ))) (b : Q(ℕ)) ← Meta.whnfR e | failure let ⟨ea, pa⟩ ← deriveNat a _ let ⟨eb, pb⟩ ← deriveNat b _ haveI' : u =QL 0 := ⟨⟩ haveI' : $α =Q ℤ := ⟨⟩ have ⟨er, pr⟩ := proveJacobiSymNat ea eb haveI' : $e =Q jacobiSymNat $a $b := ⟨⟩ return .isInt _ er er.intLit! q(isInt_jacobiSymNat $pa $pb $pr) /-- This is the `norm_num` plug-in that evaluates Legendre symbols. -/ @[norm_num legendreSym _ _] def evalLegendreSym : NormNumExt where eval {u α} e := do let .app (.app (.app _ (p : Q(ℕ))) (fp : Q(Fact (Nat.Prime $p)))) (a : Q(ℤ)) ← Meta.whnfR e | failure let ⟨ea, pa⟩ ← deriveInt a _ let ⟨ep, pp⟩ ← deriveNat p _ haveI' : u =QL 0 := ⟨⟩ haveI' : $α =Q ℤ := ⟨⟩ have ⟨er, pr⟩ := proveJacobiSym ea ep haveI' : $e =Q legendreSym $p $a := ⟨⟩ return .isInt _ er er.intLit! q(LegendreSym.to_jacobiSym $p $fp $a $er (isInt_jacobiSym $pa $pp $pr)) end NormNum end Tactic end Tactic
Tactic\NormNum\NatFib.lean
/- Copyright (c) 2023 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Mario Carneiro -/ import Mathlib.Data.Nat.Fib.Basic import Mathlib.Tactic.NormNum /-! # `norm_num` extension for `Nat.fib` This `norm_num` extension uses a strategy parallel to that of `Nat.fastFib`, but it instead produces proofs of what `Nat.fib` evaluates to. -/ namespace Mathlib.Meta.NormNum open Qq Lean Elab.Tactic open Nat /-- Auxiliary definition for `proveFib` extension. -/ def IsFibAux (n a b : ℕ) := fib n = a ∧ fib (n + 1) = b theorem isFibAux_zero : IsFibAux 0 0 1 := ⟨fib_zero, fib_one⟩ theorem isFibAux_one : IsFibAux 1 1 1 := ⟨fib_one, fib_two⟩ theorem isFibAux_two_mul {n a b n' a' b' : ℕ} (H : IsFibAux n a b) (hn : 2 * n = n') (h1 : a * (2 * b - a) = a') (h2 : a * a + b * b = b') : IsFibAux n' a' b' := ⟨by rw [← hn, fib_two_mul, H.1, H.2, ← h1], by rw [← hn, fib_two_mul_add_one, H.1, H.2, pow_two, pow_two, add_comm, h2]⟩ theorem isFibAux_two_mul_add_one {n a b n' a' b' : ℕ} (H : IsFibAux n a b) (hn : 2 * n + 1 = n') (h1 : a * a + b * b = a') (h2 : b * (2 * a + b) = b') : IsFibAux n' a' b' := ⟨by rw [← hn, fib_two_mul_add_one, H.1, H.2, pow_two, pow_two, add_comm, h1], by rw [← hn, fib_two_mul_add_two, H.1, H.2, h2]⟩ partial def proveNatFibAux (en' : Q(ℕ)) : (ea' eb' : Q(ℕ)) × Q(IsFibAux $en' $ea' $eb') := match en'.natLit! with | 0 => show (ea' eb' : Q(ℕ)) × Q(IsFibAux 0 $ea' $eb') from ⟨mkRawNatLit 0, mkRawNatLit 1, q(isFibAux_zero)⟩ | 1 => show (ea' eb' : Q(ℕ)) × Q(IsFibAux 1 $ea' $eb') from ⟨mkRawNatLit 1, mkRawNatLit 1, q(isFibAux_one)⟩ | n' => have en : Q(ℕ) := mkRawNatLit <| n' / 2 let ⟨ea, eb, H⟩ := proveNatFibAux en let a := ea.natLit! let b := eb.natLit! if n' % 2 == 0 then have hn : Q(2 * $en = $en') := (q(Eq.refl $en') : Expr) have ea' : Q(ℕ) := mkRawNatLit <| a * (2 * b - a) have eb' : Q(ℕ) := mkRawNatLit <| a * a + b * b have h1 : Q($ea * (2 * $eb - $ea) = $ea') := (q(Eq.refl $ea') : Expr) have h2 : Q($ea * $ea + $eb * $eb = $eb') := (q(Eq.refl $eb') : Expr) ⟨ea', eb', q(isFibAux_two_mul $H $hn $h1 $h2)⟩ else have hn : Q(2 * $en + 1 = $en') := (q(Eq.refl $en') : Expr) have ea' : Q(ℕ) := mkRawNatLit <| a * a + b * b have eb' : Q(ℕ) := mkRawNatLit <| b * (2 * a + b) have h1 : Q($ea * $ea + $eb * $eb = $ea') := (q(Eq.refl $ea') : Expr) have h2 : Q($eb * (2 * $ea + $eb) = $eb') := (q(Eq.refl $eb') : Expr) ⟨ea', eb', q(isFibAux_two_mul_add_one $H $hn $h1 $h2)⟩ theorem isFibAux_two_mul_done {n a b n' a' : ℕ} (H : IsFibAux n a b) (hn : 2 * n = n') (h : a * (2 * b - a) = a') : fib n' = a' := (isFibAux_two_mul H hn h rfl).1 theorem isFibAux_two_mul_add_one_done {n a b n' a' : ℕ} (H : IsFibAux n a b) (hn : 2 * n + 1 = n') (h : a * a + b * b = a') : fib n' = a' := (isFibAux_two_mul_add_one H hn h rfl).1 /-- Given the natural number literal `ex`, returns `Nat.fib ex` as a natural number literal and an equality proof. Panics if `ex` isn't a natural number literal. -/ def proveNatFib (en' : Q(ℕ)) : (em : Q(ℕ)) × Q(Nat.fib $en' = $em) := match en'.natLit! with | 0 => show (em : Q(ℕ)) × Q(Nat.fib 0 = $em) from ⟨mkRawNatLit 0, q(Nat.fib_zero)⟩ | 1 => show (em : Q(ℕ)) × Q(Nat.fib 1 = $em) from ⟨mkRawNatLit 1, q(Nat.fib_one)⟩ | 2 => show (em : Q(ℕ)) × Q(Nat.fib 2 = $em) from ⟨mkRawNatLit 1, q(Nat.fib_two)⟩ | n' => have en : Q(ℕ) := mkRawNatLit <| n' / 2 let ⟨ea, eb, H⟩ := proveNatFibAux en let a := ea.natLit! let b := eb.natLit! if n' % 2 == 0 then have hn : Q(2 * $en = $en') := (q(Eq.refl $en') : Expr) have ea' : Q(ℕ) := mkRawNatLit <| a * (2 * b - a) have h1 : Q($ea * (2 * $eb - $ea) = $ea') := (q(Eq.refl $ea') : Expr) ⟨ea', q(isFibAux_two_mul_done $H $hn $h1)⟩ else have hn : Q(2 * $en + 1 = $en') := (q(Eq.refl $en') : Expr) have ea' : Q(ℕ) := mkRawNatLit <| a * a + b * b have h1 : Q($ea * $ea + $eb * $eb = $ea') := (q(Eq.refl $ea') : Expr) ⟨ea', q(isFibAux_two_mul_add_one_done $H $hn $h1)⟩ theorem isNat_fib : {x nx z : ℕ} → IsNat x nx → Nat.fib nx = z → IsNat (Nat.fib x) z | _, _, _, ⟨rfl⟩, rfl => ⟨rfl⟩ /-- Evaluates the `Nat.fib` function. -/ @[norm_num Nat.fib _] def evalNatFib : NormNumExt where eval {u α} e := do let .app _ (x : Q(ℕ)) ← Meta.whnfR e | failure let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat) let ⟨ex, p⟩ ← deriveNat x sℕ let ⟨ey, pf⟩ := proveNatFib ex let pf' : Q(IsNat (Nat.fib $x) $ey) := q(isNat_fib $p $pf) return .isNat sℕ ey pf' end NormNum end Meta end Mathlib
Tactic\NormNum\NatSqrt.lean
/- Copyright (c) 2022 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kyle Miller -/ import Mathlib.Data.Nat.Defs import Mathlib.Tactic.NormNum /-! # `norm_num` extension for `Nat.sqrt` This module defines a `norm_num` extension for `Nat.sqrt`. -/ namespace Tactic namespace NormNum open Qq Lean Elab.Tactic Mathlib.Meta.NormNum lemma nat_sqrt_helper {x y r : ℕ} (hr : y * y + r = x) (hle : Nat.ble r (2 * y)) : Nat.sqrt x = y := by rw [← hr, ← pow_two] rw [two_mul] at hle exact Nat.sqrt_add_eq' _ (Nat.le_of_ble_eq_true hle) theorem isNat_sqrt : {x nx z : ℕ} → IsNat x nx → Nat.sqrt nx = z → IsNat (Nat.sqrt x) z | _, _, _, ⟨rfl⟩, rfl => ⟨rfl⟩ /-- Given the natural number literal `ex`, returns its square root as a natural number literal and an equality proof. Panics if `ex` isn't a natural number literal. -/ def proveNatSqrt (ex : Q(ℕ)) : (ey : Q(ℕ)) × Q(Nat.sqrt $ex = $ey) := match ex.natLit! with | 0 => show (ey : Q(ℕ)) × Q(Nat.sqrt 0 = $ey) from ⟨mkRawNatLit 0, q(Nat.sqrt_zero)⟩ | 1 => show (ey : Q(ℕ)) × Q(Nat.sqrt 1 = $ey) from ⟨mkRawNatLit 1, q(Nat.sqrt_one)⟩ | x => let y := Nat.sqrt x have ey : Q(ℕ) := mkRawNatLit y have er : Q(ℕ) := mkRawNatLit (x - y * y) have hr : Q($ey * $ey + $er = $ex) := (q(Eq.refl $ex) : Expr) have hle : Q(Nat.ble $er (2 * $ey)) := (q(Eq.refl true) : Expr) ⟨ey, q(nat_sqrt_helper $hr $hle)⟩ /-- Evaluates the `Nat.sqrt` function. -/ @[norm_num Nat.sqrt _] def evalNatSqrt : NormNumExt where eval {u α} e := do let .app _ (x : Q(ℕ)) ← Meta.whnfR e | failure let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat) let ⟨ex, p⟩ ← deriveNat x sℕ let ⟨ey, pf⟩ := proveNatSqrt ex let pf' : Q(IsNat (Nat.sqrt $x) $ey) := q(isNat_sqrt $p $pf) return .isNat sℕ ey pf' end NormNum end Tactic
Tactic\NormNum\OfScientific.lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Thomas Murrills -/ import Mathlib.Tactic.NormNum.Basic import Mathlib.Data.Rat.Cast.Lemmas /-! ## `norm_num` plugin for scientific notation. -/ namespace Mathlib open Lean hiding Rat mkRat open Meta namespace Meta.NormNum open Qq variable {α : Type*} -- see note [norm_num lemma function equality] theorem isRat_ofScientific_of_true [DivisionRing α] : {m e : ℕ} → {n : ℤ} → {d : ℕ} → IsRat (mkRat m (10 ^ e) : α) n d → IsRat (OfScientific.ofScientific m true e : α) n d | _, _, _, _, ⟨_, eq⟩ => ⟨‹_›, by rwa [← Rat.cast_ofScientific, ← Rat.ofScientific_eq_ofScientific, Rat.ofScientific_true_def]⟩ -- see note [norm_num lemma function equality] theorem isNat_ofScientific_of_false [DivisionRing α] : {m e nm ne n : ℕ} → IsNat m nm → IsNat e ne → n = Nat.mul nm ((10 : ℕ) ^ ne) → IsNat (OfScientific.ofScientific m false e : α) n | _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => ⟨by rw [← Rat.cast_ofScientific, ← Rat.ofScientific_eq_ofScientific] simp only [Nat.cast_id, Rat.ofScientific_false_def, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, h, Nat.mul_eq] norm_cast⟩ /-- The `norm_num` extension which identifies expressions in scientific notation, normalizing them to rat casts if the scientific notation is inherited from the one for rationals. -/ @[norm_num OfScientific.ofScientific _ _ _] def evalOfScientific : NormNumExt where eval {u α} e := do let .app (.app (.app f (m : Q(ℕ))) (b : Q(Bool))) (exp : Q(ℕ)) ← whnfR e | failure let dα ← inferDivisionRing α guard <|← withNewMCtxDepth <| isDefEq f q(OfScientific.ofScientific (α := $α)) assumeInstancesCommute haveI' : $e =Q OfScientific.ofScientific $m $b $exp := ⟨⟩ match b with | ~q(true) => let rme ← derive (q(mkRat $m (10 ^ $exp)) : Q($α)) let some ⟨q, n, d, p⟩ := rme.toRat' dα | failure return .isRat' dα q n d q(isRat_ofScientific_of_true $p) | ~q(false) => let ⟨nm, pm⟩ ← deriveNat m q(AddCommMonoidWithOne.toAddMonoidWithOne) let ⟨ne, pe⟩ ← deriveNat exp q(AddCommMonoidWithOne.toAddMonoidWithOne) have pm : Q(IsNat $m $nm) := pm have pe : Q(IsNat $exp $ne) := pe let m' := nm.natLit! let exp' := ne.natLit! let n' := Nat.mul m' (Nat.pow (10 : ℕ) exp') have n : Q(ℕ) := mkRawNatLit n' haveI : $n =Q Nat.mul $nm ((10 : ℕ) ^ $ne) := ⟨⟩ return .isNat _ n q(isNat_ofScientific_of_false $pm $pe (.refl $n)) end NormNum end Meta end Mathlib
Tactic\NormNum\Pow.lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Thomas Murrills -/ import Mathlib.Data.Int.Cast.Lemmas import Mathlib.Tactic.NormNum.Basic /-! ## `norm_num` plugin for `^`. -/ namespace Mathlib open Lean hiding Rat mkRat open Meta namespace Meta.NormNum open Qq variable {a b c : ℕ} theorem natPow_zero : Nat.pow a (nat_lit 0) = nat_lit 1 := rfl theorem natPow_one : Nat.pow a (nat_lit 1) = a := Nat.pow_one _ theorem zero_natPow : Nat.pow (nat_lit 0) (Nat.succ b) = nat_lit 0 := rfl theorem one_natPow : Nat.pow (nat_lit 1) b = nat_lit 1 := Nat.one_pow _ /-- This is an opaque wrapper around `Nat.pow` to prevent lean from unfolding the definition of `Nat.pow` on numerals. The arbitrary precondition `p` is actually a formula of the form `Nat.pow a' b' = c'` but we usually don't care to unfold this proposition so we just carry a reference to it. -/ structure IsNatPowT (p : Prop) (a b c : Nat) : Prop where /-- Unfolds the assertion. -/ run' : p → Nat.pow a b = c theorem IsNatPowT.run (p : IsNatPowT (Nat.pow a (nat_lit 1) = a) a b c) : Nat.pow a b = c := p.run' (Nat.pow_one _) /-- This is the key to making the proof proceed as a balanced tree of applications instead of a linear sequence. It is just modus ponens after unwrapping the definitions. -/ theorem IsNatPowT.trans {p : Prop} {b' c' : ℕ} (h1 : IsNatPowT p a b c) (h2 : IsNatPowT (Nat.pow a b = c) a b' c') : IsNatPowT p a b' c' := ⟨h2.run' ∘ h1.run'⟩ theorem IsNatPowT.bit0 : IsNatPowT (Nat.pow a b = c) a (nat_lit 2 * b) (Nat.mul c c) := ⟨fun h1 => by simp [two_mul, pow_add, ← h1]⟩ theorem IsNatPowT.bit1 : IsNatPowT (Nat.pow a b = c) a (nat_lit 2 * b + nat_lit 1) (Nat.mul c (Nat.mul c a)) := ⟨fun h1 => by simp [two_mul, pow_add, mul_assoc, ← h1]⟩ /-- Proves `Nat.pow a b = c` where `a` and `b` are raw nat literals. This could be done by just `rfl` but the kernel does not have a special case implementation for `Nat.pow` so this would proceed by unary recursion on `b`, which is too slow and also leads to deep recursion. We instead do the proof by binary recursion, but this can still lead to deep recursion, so we use an additional trick to do binary subdivision on `log2 b`. As a result this produces a proof of depth `log (log b)` which will essentially never overflow before the numbers involved themselves exceed memory limits. -/ partial def evalNatPow (a b : Q(ℕ)) : (c : Q(ℕ)) × Q(Nat.pow $a $b = $c) := if b.natLit! = 0 then haveI : $b =Q 0 := ⟨⟩ ⟨q(nat_lit 1), q(natPow_zero)⟩ else if a.natLit! = 0 then haveI : $a =Q 0 := ⟨⟩ have b' : Q(ℕ) := mkRawNatLit (b.natLit! - 1) haveI : $b =Q Nat.succ $b' := ⟨⟩ ⟨q(nat_lit 0), q(zero_natPow)⟩ else if a.natLit! = 1 then haveI : $a =Q 1 := ⟨⟩ ⟨q(nat_lit 1), q(one_natPow)⟩ else if b.natLit! = 1 then haveI : $b =Q 1 := ⟨⟩ ⟨a, q(natPow_one)⟩ else let ⟨c, p⟩ := go b.natLit!.log2 a (mkRawNatLit 1) a b _ .rfl ⟨c, q(($p).run)⟩ where /-- Invariants: `a ^ b₀ = c₀`, `depth > 0`, `b >>> depth = b₀`, `p := Nat.pow $a $b₀ = $c₀` -/ go (depth : Nat) (a b₀ c₀ b : Q(ℕ)) (p : Q(Prop)) (hp : $p =Q (Nat.pow $a $b₀ = $c₀)) : (c : Q(ℕ)) × Q(IsNatPowT $p $a $b $c) := let b' := b.natLit! if depth ≤ 1 then let a' := a.natLit! let c₀' := c₀.natLit! if b' &&& 1 == 0 then have c : Q(ℕ) := mkRawNatLit (c₀' * c₀') haveI : $c =Q Nat.mul $c₀ $c₀ := ⟨⟩ haveI : $b =Q 2 * $b₀ := ⟨⟩ ⟨c, q(IsNatPowT.bit0)⟩ else have c : Q(ℕ) := mkRawNatLit (c₀' * (c₀' * a')) haveI : $c =Q Nat.mul $c₀ (Nat.mul $c₀ $a) := ⟨⟩ haveI : $b =Q 2 * $b₀ + 1 := ⟨⟩ ⟨c, q(IsNatPowT.bit1)⟩ else let d := depth >>> 1 have hi : Q(ℕ) := mkRawNatLit (b' >>> d) let ⟨c1, p1⟩ := go (depth - d) a b₀ c₀ hi p (by exact hp) let ⟨c2, p2⟩ := go d a hi c1 b q(Nat.pow $a $hi = $c1) ⟨⟩ ⟨c2, q(($p1).trans $p2)⟩ theorem intPow_ofNat (h1 : Nat.pow a b = c) : Int.pow (Int.ofNat a) b = Int.ofNat c := by simp [← h1] theorem intPow_negOfNat_bit0 {b' c' : ℕ} (h1 : Nat.pow a b' = c') (hb : nat_lit 2 * b' = b) (hc : c' * c' = c) : Int.pow (Int.negOfNat a) b = Int.ofNat c := by rw [← hb, Int.negOfNat_eq, Int.pow_eq, pow_mul, neg_pow_two, ← pow_mul, two_mul, pow_add, ← hc, ← h1] simp theorem intPow_negOfNat_bit1 {b' c' : ℕ} (h1 : Nat.pow a b' = c') (hb : nat_lit 2 * b' + nat_lit 1 = b) (hc : c' * (c' * a) = c) : Int.pow (Int.negOfNat a) b = Int.negOfNat c := by rw [← hb, Int.negOfNat_eq, Int.negOfNat_eq, Int.pow_eq, pow_succ, pow_mul, neg_pow_two, ← pow_mul, two_mul, pow_add, ← hc, ← h1] simp [mul_assoc, mul_comm, mul_left_comm] /-- Evaluates `Int.pow a b = c` where `a` and `b` are raw integer literals. -/ partial def evalIntPow (za : ℤ) (a : Q(ℤ)) (b : Q(ℕ)) : ℤ × (c : Q(ℤ)) × Q(Int.pow $a $b = $c) := have a' : Q(ℕ) := a.appArg! if 0 ≤ za then haveI : $a =Q .ofNat $a' := ⟨⟩ let ⟨c, p⟩ := evalNatPow a' b ⟨c.natLit!, q(.ofNat $c), q(intPow_ofNat $p)⟩ else haveI : $a =Q .negOfNat $a' := ⟨⟩ let b' := b.natLit! have b₀ : Q(ℕ) := mkRawNatLit (b' >>> 1) let ⟨c₀, p⟩ := evalNatPow a' b₀ let c' := c₀.natLit! if b' &&& 1 == 0 then have c : Q(ℕ) := mkRawNatLit (c' * c') have pc : Q($c₀ * $c₀ = $c) := (q(Eq.refl $c) : Expr) have pb : Q(2 * $b₀ = $b) := (q(Eq.refl $b) : Expr) ⟨c.natLit!, q(.ofNat $c), q(intPow_negOfNat_bit0 $p $pb $pc)⟩ else have c : Q(ℕ) := mkRawNatLit (c' * (c' * a'.natLit!)) have pc : Q($c₀ * ($c₀ * $a') = $c) := (q(Eq.refl $c) : Expr) have pb : Q(2 * $b₀ + 1 = $b) := (q(Eq.refl $b) : Expr) ⟨-c.natLit!, q(.negOfNat $c), q(intPow_negOfNat_bit1 $p $pb $pc)⟩ -- see note [norm_num lemma function equality] theorem isNat_pow {α} [Semiring α] : ∀ {f : α → ℕ → α} {a : α} {b a' b' c : ℕ}, f = HPow.hPow → IsNat a a' → IsNat b b' → Nat.pow a' b' = c → IsNat (f a b) c | _, _, _, _, _, _, rfl, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨by simp⟩ -- see note [norm_num lemma function equality] theorem isInt_pow {α} [Ring α] : ∀ {f : α → ℕ → α} {a : α} {b : ℕ} {a' : ℤ} {b' : ℕ} {c : ℤ}, f = HPow.hPow → IsInt a a' → IsNat b b' → Int.pow a' b' = c → IsInt (f a b) c | _, _, _, _, _, _, rfl, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨by simp⟩ -- see note [norm_num lemma function equality] theorem isRat_pow {α} [Ring α] {f : α → ℕ → α} {a : α} {an cn : ℤ} {ad b b' cd : ℕ} : f = HPow.hPow → IsRat a an ad → IsNat b b' → Int.pow an b' = cn → Nat.pow ad b' = cd → IsRat (f a b) cn cd := by rintro rfl ⟨_, rfl⟩ ⟨rfl⟩ (rfl : an ^ b = _) (rfl : ad ^ b = _) have := invertiblePow (ad:α) b rw [← Nat.cast_pow] at this use this; simp [invOf_pow, Commute.mul_pow] /-- The `norm_num` extension which identifies expressions of the form `a ^ b`, such that `norm_num` successfully recognises both `a` and `b`, with `b : ℕ`. -/ @[norm_num _ ^ (_ : ℕ)] def evalPow : NormNumExt where eval {u α} e := do let .app (.app (f : Q($α → ℕ → $α)) (a : Q($α))) (b : Q(ℕ)) ← whnfR e | failure let ⟨nb, pb⟩ ← deriveNat b q(instAddMonoidWithOneNat) let sα ← inferSemiring α let ra ← derive a guard <|← withDefault <| withNewMCtxDepth <| isDefEq f q(HPow.hPow (α := $α)) haveI' : $e =Q $a ^ $b := ⟨⟩ haveI' : $f =Q HPow.hPow := ⟨⟩ let rec /-- Main part of `evalPow`. -/ core : Option (Result e) := do match ra with | .isBool .. => failure | .isNat sα na pa => assumeInstancesCommute have ⟨c, r⟩ := evalNatPow na nb return .isNat sα c q(isNat_pow (f := $f) (.refl $f) $pa $pb $r) | .isNegNat rα .. => assumeInstancesCommute let ⟨za, na, pa⟩ ← ra.toInt rα have ⟨zc, c, r⟩ := evalIntPow za na nb return .isInt rα c zc q(isInt_pow (f := $f) (.refl $f) $pa $pb $r) | .isRat dα qa na da pa => assumeInstancesCommute have ⟨zc, nc, r1⟩ := evalIntPow qa.num na nb have ⟨dc, r2⟩ := evalNatPow da nb let qc := mkRat zc dc.natLit! return .isRat' dα qc nc dc q(isRat_pow (f := $f) (.refl $f) $pa $pb $r1 $r2) core theorem isNat_zpow_pos {α : Type*} [DivisionSemiring α] {a : α} {b : ℤ} {nb ne : ℕ} (pb : IsNat b nb) (pe' : IsNat (a ^ nb) ne) : IsNat (a ^ b) ne := by rwa [pb.out, zpow_natCast] theorem isNat_zpow_neg {α : Type*} [DivisionSemiring α] {a : α} {b : ℤ} {nb ne : ℕ} (pb : IsInt b (Int.negOfNat nb)) (pe' : IsNat (a ^ nb)⁻¹ ne) : IsNat (a ^ b) ne := by rwa [pb.out, Int.cast_negOfNat, zpow_neg, zpow_natCast] theorem isInt_zpow_pos {α : Type*} [DivisionRing α] {a : α} {b : ℤ} {nb ne : ℕ} (pb : IsNat b nb) (pe' : IsInt (a ^ nb) (Int.negOfNat ne)) : IsInt (a ^ b) (Int.negOfNat ne) := by rwa [pb.out, zpow_natCast] theorem isInt_zpow_neg {α : Type*} [DivisionRing α] {a : α} {b : ℤ} {nb ne : ℕ} (pb : IsInt b (Int.negOfNat nb)) (pe' : IsInt (a ^ nb)⁻¹ (Int.negOfNat ne)) : IsInt (a ^ b) (Int.negOfNat ne) := by rwa [pb.out, Int.cast_negOfNat, zpow_neg, zpow_natCast] theorem isRat_zpow_pos {α : Type*} [DivisionRing α] {a : α} {b : ℤ} {nb : ℕ} {num : ℤ} {den : ℕ} (pb : IsNat b nb) (pe' : IsRat (a^nb) num den) : IsRat (a^b) num den := by rwa [pb.out, zpow_natCast] theorem isRat_zpow_neg {α : Type*} [DivisionRing α] {a : α} {b : ℤ} {nb : ℕ} {num : ℤ} {den : ℕ} (pb : IsInt b (Int.negOfNat nb)) (pe' : IsRat ((a^nb)⁻¹) num den) : IsRat (a^b) num den := by rwa [pb.out, Int.cast_negOfNat, zpow_neg, zpow_natCast] #adaptation_note /-- Prior to https://github.com/leanprover/lean4/pull/4096, the repeated ``` have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩ h.check ``` blocks below were not necessary: we just did it once outside the `match rb with` block. -/ /-- The `norm_num` extension which identifies expressions of the form `a ^ b`, such that `norm_num` successfully recognises both `a` and `b`, with `b : ℤ`. -/ @[norm_num _ ^ (_ : ℤ)] def evalZPow : NormNumExt where eval {u α} e := do let .app (.app (f : Q($α → ℤ → $α)) (a : Q($α))) (b : Q(ℤ)) ← whnfR e | failure let _c ← synthInstanceQ q(DivisionSemiring $α) let rb ← derive (α := q(ℤ)) b match rb with | .isBool .. | .isRat _ .. => failure | .isNat sβ nb pb => match ← derive q($a ^ $nb) with | .isBool .. => failure | .isNat sα' ne' pe' => have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩ h.check assumeInstancesCommute return .isNat sα' ne' q(isNat_zpow_pos $pb $pe') | .isNegNat sα' ne' pe' => have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩ h.check let _c ← synthInstanceQ q(DivisionRing $α) assumeInstancesCommute return .isNegNat sα' ne' q(isInt_zpow_pos $pb $pe') | .isRat sα' qe' nume' dene' pe' => have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩ h.check assumeInstancesCommute return .isRat sα' qe' nume' dene' q(isRat_zpow_pos $pb $pe') | .isNegNat sβ nb pb => match ← derive q(($a ^ $nb)⁻¹) with | .isBool .. => failure | .isNat sα' ne' pe' => have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩ h.check assumeInstancesCommute return .isNat sα' ne' q(isNat_zpow_neg $pb $pe') | .isNegNat sα' ne' pe' => have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩ h.check let _c ← synthInstanceQ q(DivisionRing $α) assumeInstancesCommute return .isNegNat sα' ne' q(isInt_zpow_neg $pb $pe') | .isRat sα' qe' nume' dene' pe' => have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩ h.check assumeInstancesCommute return .isRat sα' qe' nume' dene' q(isRat_zpow_neg $pb $pe') end NormNum end Meta end Mathlib
Tactic\NormNum\Prime.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Tactic.NormNum.Basic import Mathlib.Data.Nat.Prime.Defs /-! # `norm_num` extensions on natural numbers This file provides a `norm_num` extension to prove that natural numbers are prime and compute its minimal factor. Todo: compute the list of all factors. ## Implementation Notes For numbers larger than 25 bits, the primality proof produced by `norm_num` is an expression that is thousands of levels deep, and the Lean kernel seems to raise a stack overflow when type-checking that proof. If we want an implementation that works for larger primes, we should generate a proof that has a smaller depth. Note: `evalMinFac.aux` does not raise a stack overflow, which can be checked by replacing the `prf'` in the recursive call by something like `(.sort .zero)` -/ open Nat Qq Lean Meta namespace Mathlib.Meta.NormNum theorem not_prime_mul_of_ble (a b n : ℕ) (h : a * b = n) (h₁ : a.ble 1 = false) (h₂ : b.ble 1 = false) : ¬ n.Prime := not_prime_mul' h (ble_eq_false.mp h₁).ne' (ble_eq_false.mp h₂).ne' /-- Produce a proof that `n` is not prime from a factor `1 < d < n`. `en` should be the expression that is the natural number literal `n`. -/ def deriveNotPrime (n d : ℕ) (en : Q(ℕ)) : Q(¬ Nat.Prime $en) := Id.run <| do let d' : ℕ := n / d let prf : Q($d * $d' = $en) := (q(Eq.refl $en) : Expr) let r : Q(Nat.ble $d 1 = false) := (q(Eq.refl false) : Expr) let r' : Q(Nat.ble $d' 1 = false) := (q(Eq.refl false) : Expr) return q(not_prime_mul_of_ble _ _ _ $prf $r $r') /-- A predicate representing partial progress in a proof of `minFac`. -/ def MinFacHelper (n k : ℕ) : Prop := 2 < k ∧ k % 2 = 1 ∧ k ≤ minFac n theorem MinFacHelper.one_lt {n k : ℕ} (h : MinFacHelper n k) : 1 < n := by have : 2 < minFac n := h.1.trans_le h.2.2 obtain rfl | h := n.eq_zero_or_pos · contradiction rcases (succ_le_of_lt h).eq_or_lt with rfl|h · simp_all exact h theorem minFacHelper_0 (n : ℕ) (h1 : Nat.ble (nat_lit 2) n = true) (h2 : nat_lit 1 = n % (nat_lit 2)) : MinFacHelper n (nat_lit 3) := by refine ⟨by norm_num, by norm_num, ?_⟩ refine (le_minFac'.mpr λ p hp hpn ↦ ?_).resolve_left (Nat.ne_of_gt (Nat.le_of_ble_eq_true h1)) rcases hp.eq_or_lt with rfl|h · simp [(Nat.dvd_iff_mod_eq_zero ..).1 hpn] at h2 · exact h theorem minFacHelper_1 {n k k' : ℕ} (e : k + 2 = k') (h : MinFacHelper n k) (np : minFac n ≠ k) : MinFacHelper n k' := by rw [← e] refine ⟨Nat.lt_add_right _ h.1, ?_, ?_⟩ · rw [add_mod, mod_self, add_zero, mod_mod] exact h.2.1 rcases h.2.2.eq_or_lt with rfl|h2 · exact (np rfl).elim rcases (succ_le_of_lt h2).eq_or_lt with h2|h2 · refine ((h.1.trans_le h.2.2).ne ?_).elim have h3 : 2 ∣ minFac n := by rw [Nat.dvd_iff_mod_eq_zero, ← h2, succ_eq_add_one, add_mod, h.2.1] rw [dvd_prime <| minFac_prime h.one_lt.ne'] at h3 norm_num at h3 exact h3 exact h2 theorem minFacHelper_2 {n k k' : ℕ} (e : k + 2 = k') (nk : ¬ Nat.Prime k) (h : MinFacHelper n k) : MinFacHelper n k' := by refine minFacHelper_1 e h λ h2 ↦ ?_ rw [← h2] at nk exact nk <| minFac_prime h.one_lt.ne' theorem minFacHelper_3 {n k k' : ℕ} (e : k + 2 = k') (nk : (n % k).beq 0 = false) (h : MinFacHelper n k) : MinFacHelper n k' := by refine minFacHelper_1 e h λ h2 ↦ ?_ have nk := Nat.ne_of_beq_eq_false nk rw [← Nat.dvd_iff_mod_eq_zero, ← h2] at nk exact nk <| minFac_dvd n theorem isNat_minFac_1 : {a : ℕ} → IsNat a (nat_lit 1) → IsNat a.minFac 1 | _, ⟨rfl⟩ => ⟨minFac_one⟩ theorem isNat_minFac_2 : {a a' : ℕ} → IsNat a a' → a' % 2 = 0 → IsNat a.minFac 2 | a, _, ⟨rfl⟩, h => ⟨by rw [cast_ofNat, minFac_eq_two_iff, Nat.dvd_iff_mod_eq_zero, h]⟩ theorem isNat_minFac_3 : {n n' : ℕ} → (k : ℕ) → IsNat n n' → MinFacHelper n' k → nat_lit 0 = n' % k → IsNat (minFac n) k | n, _, k, ⟨rfl⟩, h1, h2 => by rw [eq_comm, ← Nat.dvd_iff_mod_eq_zero] at h2 exact ⟨le_antisymm (minFac_le_of_dvd h1.1.le h2) h1.2.2⟩ theorem isNat_minFac_4 : {n n' k : ℕ} → IsNat n n' → MinFacHelper n' k → (k * k).ble n' = false → IsNat (minFac n) n' | n, _, k, ⟨rfl⟩, h1, h2 => by refine ⟨(Nat.prime_def_minFac.mp ?_).2⟩ rw [Nat.prime_def_le_sqrt] refine ⟨h1.one_lt, λ m hm hmn h2mn ↦ ?_⟩ exact lt_irrefl m <| calc m ≤ sqrt n := hmn _ < k := sqrt_lt.mpr (ble_eq_false.mp h2) _ ≤ n.minFac := h1.2.2 _ ≤ m := Nat.minFac_le_of_dvd hm h2mn /-- The `norm_num` extension which identifies expressions of the form `minFac n`. -/ @[norm_num Nat.minFac _] partial def evalMinFac : NormNumExt where eval {u α} e := do let .app (.const ``Nat.minFac _) (n : Q(ℕ)) ← whnfR e | failure let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat) let ⟨nn, pn⟩ ← deriveNat n sℕ let n' := nn.natLit! let rec aux (ek : Q(ℕ)) (prf : Q(MinFacHelper $nn $ek)) : (c : Q(ℕ)) × Q(IsNat (Nat.minFac $n) $c) := let k := ek.natLit! -- remark: `deriveBool q($nn < $ek * $ek)` is 2x slower than the following test. if n' < k * k then let r : Q(Nat.ble ($ek * $ek) $nn = false) := (q(Eq.refl false) : Expr) ⟨nn, q(isNat_minFac_4 $pn $prf $r)⟩ else let d : ℕ := k.minFac -- the following branch is not necessary for the correctness, -- but makes the algorithm 2x faster if d < k then have ek' : Q(ℕ) := mkRawNatLit <| k + 2 let pk' : Q($ek + 2 = $ek') := (q(Eq.refl $ek') : Expr) let pd := deriveNotPrime k d ek aux ek' q(minFacHelper_2 $pk' $pd $prf) -- remark: `deriveBool q($nn % $ek = 0)` is 5x slower than the following test else if n' % k = 0 then let r : Q(nat_lit 0 = $nn % $ek) := (q(Eq.refl 0) : Expr) let r' : Q(IsNat (minFac $n) $ek) := q(isNat_minFac_3 _ $pn $prf $r) ⟨ek, r'⟩ else let r : Q(Nat.beq ($nn % $ek) 0 = false) := (q(Eq.refl false) : Expr) have ek' : Q(ℕ) := mkRawNatLit <| k + 2 let pk' : Q($ek + 2 = $ek') := (q(Eq.refl $ek') : Expr) aux ek' q(minFacHelper_3 $pk' $r $prf) let rec core : MetaM <| Result q(Nat.minFac $n) := do if n' = 1 then let pn : Q(IsNat $n (nat_lit 1)) := pn return .isNat sℕ q(nat_lit 1) q(isNat_minFac_1 $pn) if n' % 2 = 0 then let pq : Q($nn % 2 = 0) := (q(Eq.refl 0) : Expr) return .isNat sℕ q(nat_lit 2) q(isNat_minFac_2 $pn $pq) let pp : Q(Nat.ble 2 $nn = true) := (q(Eq.refl true) : Expr) let pq : Q(1 = $nn % 2) := (q(Eq.refl (nat_lit 1)) : Expr) let ⟨c, pc⟩ := aux q(nat_lit 3) q(minFacHelper_0 $nn $pp $pq) return .isNat sℕ c pc core theorem isNat_prime_0 : {n : ℕ} → IsNat n (nat_lit 0) → ¬ n.Prime | _, ⟨rfl⟩ => not_prime_zero theorem isNat_prime_1 : {n : ℕ} → IsNat n (nat_lit 1) → ¬ n.Prime | _, ⟨rfl⟩ => not_prime_one theorem isNat_prime_2 : {n n' : ℕ} → IsNat n n' → Nat.ble 2 n' = true → IsNat (minFac n') n' → n.Prime | _, _, ⟨rfl⟩, h1, ⟨h2⟩ => prime_def_minFac.mpr ⟨ble_eq.mp h1, h2⟩ theorem isNat_not_prime {n n' : ℕ} (h : IsNat n n') : ¬n'.Prime → ¬n.Prime := isNat.natElim h /-- The `norm_num` extension which identifies expressions of the form `Nat.Prime n`. -/ @[norm_num Nat.Prime _] def evalNatPrime : NormNumExt where eval {u α} e := do let .app (.const `Nat.Prime _) (n : Q(ℕ)) ← whnfR e | failure let ⟨nn, pn⟩ ← deriveNat n _ let n' := nn.natLit! -- note: if `n` is not prime, we don't have to verify the calculation of `n.minFac`, we just have -- to compute it, which is a lot quicker let rec core : MetaM (Result q(Nat.Prime $n)) := do match n' with | 0 => haveI' : $nn =Q 0 := ⟨⟩; return .isFalse q(isNat_prime_0 $pn) | 1 => haveI' : $nn =Q 1 := ⟨⟩; return .isFalse q(isNat_prime_1 $pn) | _ => let d := n'.minFac if d < n' then let prf : Q(¬ Nat.Prime $nn) := deriveNotPrime n' d nn return .isFalse q(isNat_not_prime $pn $prf) let r : Q(Nat.ble 2 $nn = true) := (q(Eq.refl true) : Expr) let .isNat _ _lit (p2n : Q(IsNat (minFac $nn) $nn)) ← evalMinFac.core nn _ nn q(.raw_refl _) nn.natLit! | failure return .isTrue q(isNat_prime_2 $pn $r $p2n) core /- /-- A partial proof of `factors`. Asserts that `l` is a sorted list of primes, lower bounded by a prime `p`, which multiplies to `n`. -/ def FactorsHelper (n p : ℕ) (l : List ℕ) : Prop := p.Prime → List.Chain (· ≤ ·) p l ∧ (∀ a ∈ l, Nat.Prime a) ∧ List.prod l = n theorem factorsHelper_nil (a : ℕ) : FactorsHelper 1 a [] := fun _ => ⟨List.Chain.nil, by rintro _ ⟨⟩, List.prod_nil⟩ theorem factorsHelper_cons' (n m a b : ℕ) (l : List ℕ) (h₁ : b * m = n) (h₂ : a ≤ b) (h₃ : minFac b = b) (H : FactorsHelper m b l) : FactorsHelper n a (b :: l) := fun pa => have pb : b.Prime := Nat.prime_def_minFac.2 ⟨le_trans pa.two_le h₂, h₃⟩ let ⟨f₁, f₂, f₃⟩ := H pb ⟨List.Chain.cons h₂ f₁, fun c h => (List.eq_or_mem_of_mem_cons h).elim (fun e => e.symm ▸ pb) (f₂ _), by rw [List.prod_cons, f₃, h₁]⟩ theorem factorsHelper_cons (n m a b : ℕ) (l : List ℕ) (h₁ : b * m = n) (h₂ : a < b) (h₃ : minFac b = b) (H : FactorsHelper m b l) : FactorsHelper n a (b :: l) := factorsHelper_cons' _ _ _ _ _ h₁ h₂.le h₃ H theorem factorsHelper_sn (n a : ℕ) (h₁ : a < n) (h₂ : minFac n = n) : FactorsHelper n a [n] := factorsHelper_cons _ _ _ _ _ (mul_one _) h₁ h₂ (factorsHelper_nil _) theorem factorsHelper_same (n m a : ℕ) (l : List ℕ) (h : a * m = n) (H : FactorsHelper m a l) : FactorsHelper n a (a :: l) := fun pa => factorsHelper_cons' _ _ _ _ _ h le_rfl (Nat.prime_def_minFac.1 pa).2 H pa theorem factorsHelper_same_sn (a : ℕ) : FactorsHelper a a [a] := factorsHelper_same _ _ _ _ (mul_one _) (factorsHelper_nil _) theorem factorsHelper_end (n : ℕ) (l : List ℕ) (H : FactorsHelper n 2 l) : Nat.factors n = l := let ⟨h₁, h₂, h₃⟩ := H Nat.prime_two have := List.chain'_iff_pairwise.1 (@List.Chain'.tail _ _ (_ :: _) h₁) (List.eq_of_perm_of_sorted (Nat.factors_unique h₃ h₂) this (Nat.factors_sorted _)).symm -/ end NormNum end Meta end Mathlib
Tactic\NormNum\Result.lean
/- Copyright (c) 2022 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.GroupWithZero.Invertible import Mathlib.Data.Sigma.Basic import Mathlib.Algebra.Ring.Nat import Mathlib.Data.Int.Cast.Basic import Qq.MetaM /-! ## The `Result` type for `norm_num` We set up predicates `IsNat`, `IsInt`, and `IsRat`, stating that an element of a ring is equal to the "normal form" of a natural number, integer, or rational number coerced into that ring. We then define `Result e`, which contains a proof that a typed expression `e : Q($α)` is equal to the coercion of an explicit natural number, integer, or rational number, or is either `true` or `false`. -/ universe u variable {α : Type u} open Lean hiding Rat mkRat open Lean.Meta Qq Lean.Elab Term namespace Mathlib namespace Meta.NormNum variable {u : Level} /-- A shortcut (non)instance for `AddMonoidWithOne ℕ` to shrink generated proofs. -/ def instAddMonoidWithOneNat : AddMonoidWithOne ℕ := inferInstance /-- A shortcut (non)instance for `AddMonoidWithOne α` from `Ring α` to shrink generated proofs. -/ def instAddMonoidWithOne {α : Type u} [Ring α] : AddMonoidWithOne α := inferInstance /-- Helper function to synthesize a typed `AddMonoidWithOne α` expression. -/ def inferAddMonoidWithOne (α : Q(Type u)) : MetaM Q(AddMonoidWithOne $α) := return ← synthInstanceQ (q(AddMonoidWithOne $α) : Q(Type u)) <|> throwError "not an AddMonoidWithOne" /-- Helper function to synthesize a typed `Semiring α` expression. -/ def inferSemiring (α : Q(Type u)) : MetaM Q(Semiring $α) := return ← synthInstanceQ (q(Semiring $α) : Q(Type u)) <|> throwError "not a semiring" /-- Helper function to synthesize a typed `Ring α` expression. -/ def inferRing (α : Q(Type u)) : MetaM Q(Ring $α) := return ← synthInstanceQ (q(Ring $α) : Q(Type u)) <|> throwError "not a ring" /-- Represent an integer as a "raw" typed expression. This uses `.lit (.natVal n)` internally to represent a natural number, rather than the preferred `OfNat.ofNat` form. We use this internally to avoid unnecessary typeclass searches. This function is the inverse of `Expr.intLit!`. -/ def mkRawIntLit (n : ℤ) : Q(ℤ) := let lit : Q(ℕ) := mkRawNatLit n.natAbs if 0 ≤ n then q(.ofNat $lit) else q(.negOfNat $lit) /-- Represent an integer as a "raw" typed expression. This `.lit (.natVal n)` internally to represent a natural number, rather than the preferred `OfNat.ofNat` form. We use this internally to avoid unnecessary typeclass searches. -/ def mkRawRatLit (q : ℚ) : Q(ℚ) := let nlit : Q(ℤ) := mkRawIntLit q.num let dlit : Q(ℕ) := mkRawNatLit q.den q(mkRat $nlit $dlit) /-- Extract the raw natlit representing the absolute value of a raw integer literal (of the type produced by `Mathlib.Meta.NormNum.mkRawIntLit`) along with an equality proof. -/ def rawIntLitNatAbs (n : Q(ℤ)) : (m : Q(ℕ)) × Q(Int.natAbs $n = $m) := if n.isAppOfArity ``Int.ofNat 1 then have m : Q(ℕ) := n.appArg! ⟨m, show Q(Int.natAbs (Int.ofNat $m) = $m) from q(Int.natAbs_ofNat $m)⟩ else if n.isAppOfArity ``Int.negOfNat 1 then have m : Q(ℕ) := n.appArg! ⟨m, show Q(Int.natAbs (Int.negOfNat $m) = $m) from q(Int.natAbs_neg $m)⟩ else panic! "not a raw integer literal" /-- Constructs an `ofNat` application `a'` with the canonical instance, together with a proof that the instance is equal to the result of `Nat.cast` on the given `AddMonoidWithOne` instance. This function is performance-critical, as many higher level tactics have to construct numerals. So rather than using typeclass search we hardcode the (relatively small) set of solutions to the typeclass problem. -/ def mkOfNat (α : Q(Type u)) (_sα : Q(AddMonoidWithOne $α)) (lit : Q(ℕ)) : MetaM ((a' : Q($α)) × Q($lit = $a')) := do if α.isConstOf ``Nat then let a' : Q(ℕ) := q(OfNat.ofNat $lit : ℕ) pure ⟨a', (q(Eq.refl $a') : Expr)⟩ else if α.isConstOf ``Int then let a' : Q(ℤ) := q(OfNat.ofNat $lit : ℤ) pure ⟨a', (q(Eq.refl $a') : Expr)⟩ else if α.isConstOf ``Rat then let a' : Q(ℚ) := q(OfNat.ofNat $lit : ℚ) pure ⟨a', (q(Eq.refl $a') : Expr)⟩ else let some n := lit.rawNatLit? | failure match n with | 0 => pure ⟨q(0 : $α), (q(Nat.cast_zero (R := $α)) : Expr)⟩ | 1 => pure ⟨q(1 : $α), (q(Nat.cast_one (R := $α)) : Expr)⟩ | k+2 => let k : Q(ℕ) := mkRawNatLit k let _x : Q(Nat.AtLeastTwo $lit) := (q(instNatAtLeastTwo (n := $k)) : Expr) let a' : Q($α) := q(OfNat.ofNat $lit) pure ⟨a', (q(Eq.refl $a') : Expr)⟩ /-- Assert that an element of a semiring is equal to the coercion of some natural number. -/ structure IsNat {α : Type u} [AddMonoidWithOne α] (a : α) (n : ℕ) : Prop where /-- The element is equal to the coercion of the natural number. -/ out : a = n theorem IsNat.raw_refl (n : ℕ) : IsNat n n := ⟨rfl⟩ /-- A "raw nat cast" is an expression of the form `(Nat.rawCast lit : α)` where `lit` is a raw natural number literal. These expressions are used by tactics like `ring` to decrease the number of typeclass arguments required in each use of a number literal at type `α`. -/ @[simp] def _root_.Nat.rawCast {α : Type u} [AddMonoidWithOne α] (n : ℕ) : α := n theorem IsNat.to_eq {α : Type u} [AddMonoidWithOne α] {n} : {a a' : α} → IsNat a n → n = a' → a = a' | _, _, ⟨rfl⟩, rfl => rfl theorem IsNat.to_raw_eq {a : α} {n : ℕ} [AddMonoidWithOne α] : IsNat (a : α) n → a = n.rawCast | ⟨e⟩ => e theorem IsNat.of_raw (α) [AddMonoidWithOne α] (n : ℕ) : IsNat (n.rawCast : α) n := ⟨rfl⟩ @[elab_as_elim] theorem isNat.natElim {p : ℕ → Prop} : {n : ℕ} → {n' : ℕ} → IsNat n n' → p n' → p n | _, _, ⟨rfl⟩, h => h /-- Assert that an element of a ring is equal to the coercion of some integer. -/ structure IsInt [Ring α] (a : α) (n : ℤ) : Prop where /-- The element is equal to the coercion of the integer. -/ out : a = n /-- A "raw int cast" is an expression of the form: * `(Nat.rawCast lit : α)` where `lit` is a raw natural number literal * `(Int.rawCast (Int.negOfNat lit) : α)` where `lit` is a nonzero raw natural number literal (That is, we only actually use this function for negative integers.) This representation is used by tactics like `ring` to decrease the number of typeclass arguments required in each use of a number literal at type `α`. -/ @[simp] def _root_.Int.rawCast [Ring α] (n : ℤ) : α := n theorem IsInt.to_isNat {α} [Ring α] : ∀ {a : α} {n}, IsInt a (.ofNat n) → IsNat a n | _, _, ⟨rfl⟩ => ⟨by simp⟩ theorem IsNat.to_isInt {α} [Ring α] : ∀ {a : α} {n}, IsNat a n → IsInt a (.ofNat n) | _, _, ⟨rfl⟩ => ⟨by simp⟩ theorem IsInt.to_raw_eq {a : α} {n : ℤ} [Ring α] : IsInt (a : α) n → a = n.rawCast | ⟨e⟩ => e theorem IsInt.of_raw (α) [Ring α] (n : ℤ) : IsInt (n.rawCast : α) n := ⟨rfl⟩ theorem IsInt.neg_to_eq {α} [Ring α] {n} : {a a' : α} → IsInt a (.negOfNat n) → n = a' → a = -a' | _, _, ⟨rfl⟩, rfl => by simp [Int.negOfNat_eq, Int.cast_neg] theorem IsInt.nonneg_to_eq {α} [Ring α] {n} {a a' : α} (h : IsInt a (.ofNat n)) (e : n = a') : a = a' := h.to_isNat.to_eq e /-- Assert that an element of a ring is equal to `num / denom` (and `denom` is invertible so that this makes sense). We will usually also have `num` and `denom` coprime, although this is not part of the definition. -/ inductive IsRat [Ring α] (a : α) (num : ℤ) (denom : ℕ) : Prop | mk (inv : Invertible (denom : α)) (eq : a = num * ⅟(denom : α)) /-- A "raw rat cast" is an expression of the form: * `(Nat.rawCast lit : α)` where `lit` is a raw natural number literal * `(Int.rawCast (Int.negOfNat lit) : α)` where `lit` is a nonzero raw natural number literal * `(Rat.rawCast n d : α)` where `n` is a raw int literal, `d` is a raw nat literal, and `d` is not `1` or `0`. (where a raw int literal is of the form `Int.ofNat lit` or `Int.negOfNat nzlit` where `lit` is a raw nat literal) This representation is used by tactics like `ring` to decrease the number of typeclass arguments required in each use of a number literal at type `α`. -/ @[simp] def _root_.Rat.rawCast [DivisionRing α] (n : ℤ) (d : ℕ) : α := n / d theorem IsRat.to_isNat {α} [Ring α] : ∀ {a : α} {n}, IsRat a (.ofNat n) (nat_lit 1) → IsNat a n | _, _, ⟨inv, rfl⟩ => have := @invertibleOne α _; ⟨by simp⟩ theorem IsNat.to_isRat {α} [Ring α] : ∀ {a : α} {n}, IsNat a n → IsRat a (.ofNat n) (nat_lit 1) | _, _, ⟨rfl⟩ => ⟨⟨1, by simp, by simp⟩, by simp⟩ theorem IsRat.to_isInt {α} [Ring α] : ∀ {a : α} {n}, IsRat a n (nat_lit 1) → IsInt a n | _, _, ⟨inv, rfl⟩ => have := @invertibleOne α _; ⟨by simp⟩ theorem IsInt.to_isRat {α} [Ring α] : ∀ {a : α} {n}, IsInt a n → IsRat a n (nat_lit 1) | _, _, ⟨rfl⟩ => ⟨⟨1, by simp, by simp⟩, by simp⟩ theorem IsRat.to_raw_eq {n : ℤ} {d : ℕ} [DivisionRing α] : ∀ {a}, IsRat (a : α) n d → a = Rat.rawCast n d | _, ⟨inv, rfl⟩ => by simp [div_eq_mul_inv] theorem IsRat.neg_to_eq {α} [DivisionRing α] {n d} : {a n' d' : α} → IsRat a (.negOfNat n) d → n = n' → d = d' → a = -(n' / d') | _, _, _, ⟨_, rfl⟩, rfl, rfl => by simp [div_eq_mul_inv] theorem IsRat.nonneg_to_eq {α} [DivisionRing α] {n d} : {a n' d' : α} → IsRat a (.ofNat n) d → n = n' → d = d' → a = n' / d' | _, _, _, ⟨_, rfl⟩, rfl, rfl => by simp [div_eq_mul_inv] theorem IsRat.of_raw (α) [DivisionRing α] (n : ℤ) (d : ℕ) (h : (d : α) ≠ 0) : IsRat (Rat.rawCast n d : α) n d := have := invertibleOfNonzero h ⟨this, by simp [div_eq_mul_inv]⟩ theorem IsRat.den_nz {α} [DivisionRing α] {a n d} : IsRat (a : α) n d → (d : α) ≠ 0 | ⟨_, _⟩ => nonzero_of_invertible (d : α) /-- The result of `norm_num` running on an expression `x` of type `α`. Untyped version of `Result`. -/ inductive Result' where /-- Untyped version of `Result.isBool`. -/ | isBool (val : Bool) (proof : Expr) /-- Untyped version of `Result.isNat`. -/ | isNat (inst lit proof : Expr) /-- Untyped version of `Result.isNegNat`. -/ | isNegNat (inst lit proof : Expr) /-- Untyped version of `Result.isRat`. -/ | isRat (inst : Expr) (q : Rat) (n d proof : Expr) deriving Inhabited section set_option linter.unusedVariables false /-- The result of `norm_num` running on an expression `x` of type `α`. -/ @[nolint unusedArguments] def Result {α : Q(Type u)} (x : Q($α)) := Result' instance {α : Q(Type u)} {x : Q($α)} : Inhabited (Result x) := inferInstanceAs (Inhabited Result') /-- The result is `proof : x`, where `x` is a (true) proposition. -/ @[match_pattern, inline] def Result.isTrue {x : Q(Prop)} : ∀ (proof : Q($x)), @Result _ (q(Prop) : Q(Type)) x := Result'.isBool true /-- The result is `proof : ¬x`, where `x` is a (false) proposition. -/ @[match_pattern, inline] def Result.isFalse {x : Q(Prop)} : ∀ (proof : Q(¬$x)), @Result _ (q(Prop) : Q(Type)) x := Result'.isBool false /-- The result is `lit : ℕ` (a raw nat literal) and `proof : isNat x lit`. -/ @[match_pattern, inline] def Result.isNat {α : Q(Type u)} {x : Q($α)} : ∀ (inst : Q(AddMonoidWithOne $α) := by assumption) (lit : Q(ℕ)) (proof : Q(IsNat $x $lit)), Result x := Result'.isNat /-- The result is `-lit` where `lit` is a raw nat literal and `proof : isInt x (.negOfNat lit)`. -/ @[match_pattern, inline] def Result.isNegNat {α : Q(Type u)} {x : Q($α)} : ∀ (inst : Q(Ring $α) := by assumption) (lit : Q(ℕ)) (proof : Q(IsInt $x (.negOfNat $lit))), Result x := Result'.isNegNat /-- The result is `proof : isRat x n d`, where `n` is either `.ofNat lit` or `.negOfNat lit` with `lit` a raw nat literal and `d` is a raw nat literal (not 0 or 1), and `q` is the value of `n / d`. -/ @[match_pattern, inline] def Result.isRat {α : Q(Type u)} {x : Q($α)} : ∀ (inst : Q(DivisionRing $α) := by assumption) (q : Rat) (n : Q(ℤ)) (d : Q(ℕ)) (proof : Q(IsRat $x $n $d)), Result x := Result'.isRat end /-- The result is `z : ℤ` and `proof : isNat x z`. -/ -- Note the independent arguments `z : Q(ℤ)` and `n : ℤ`. -- We ensure these are "the same" when calling. def Result.isInt {α : Q(Type u)} {x : Q($α)} (inst : Q(Ring $α) := by assumption) (z : Q(ℤ)) (n : ℤ) (proof : Q(IsInt $x $z)) : Result x := have lit : Q(ℕ) := z.appArg! if 0 ≤ n then let proof : Q(IsInt $x (.ofNat $lit)) := proof .isNat q(instAddMonoidWithOne) lit q(IsInt.to_isNat $proof) else .isNegNat inst lit proof /-- The result depends on whether `q : ℚ` happens to be an integer, in which case the result is `.isInt ..` whereas otherwise it's `.isRat ..`. -/ def Result.isRat' {α : Q(Type u)} {x : Q($α)} (inst : Q(DivisionRing $α) := by assumption) (q : Rat) (n : Q(ℤ)) (d : Q(ℕ)) (proof : Q(IsRat $x $n $d)) : Result x := if q.den = 1 then have proof : Q(IsRat $x $n (nat_lit 1)) := proof .isInt q(DivisionRing.toRing) n q.num q(IsRat.to_isInt $proof) else .isRat inst q n d proof instance {α : Q(Type u)} {x : Q($α)} : ToMessageData (Result x) where toMessageData | .isBool true proof => m!"isTrue ({proof})" | .isBool false proof => m!"isFalse ({proof})" | .isNat _ lit proof => m!"isNat {lit} ({proof})" | .isNegNat _ lit proof => m!"isNegNat {lit} ({proof})" | .isRat _ q _ _ proof => m!"isRat {q} ({proof})" /-- Returns the rational number that is the result of `norm_num` evaluation. -/ def Result.toRat {α : Q(Type u)} {e : Q($α)} : Result e → Option Rat | .isBool .. => none | .isNat _ lit _ => some lit.natLit! | .isNegNat _ lit _ => some (-lit.natLit!) | .isRat _ q .. => some q /-- Returns the rational number that is the result of `norm_num` evaluation, along with a proof that the denominator is nonzero in the `isRat` case. -/ def Result.toRatNZ {α : Q(Type u)} {e : Q($α)} : Result e → Option (Rat × Option Expr) | .isBool .. => none | .isNat _ lit _ => some (lit.natLit!, none) | .isNegNat _ lit _ => some (-lit.natLit!, none) | .isRat _ q _ _ p => some (q, q(IsRat.den_nz $p)) /-- Extract from a `Result` the integer value (as both a term and an expression), and the proof that the original expression is equal to this integer. -/ def Result.toInt {α : Q(Type u)} {e : Q($α)} (_i : Q(Ring $α) := by with_reducible assumption) : Result e → Option (ℤ × (lit : Q(ℤ)) × Q(IsInt $e $lit)) | .isNat _ lit proof => do have proof : Q(@IsNat _ instAddMonoidWithOne $e $lit) := proof pure ⟨lit.natLit!, q(.ofNat $lit), q(($proof).to_isInt)⟩ | .isNegNat _ lit proof => pure ⟨-lit.natLit!, q(.negOfNat $lit), proof⟩ | _ => failure /-- Extract from a `Result` the rational value (as both a term and an expression), and the proof that the original expression is equal to this rational number. -/ def Result.toRat' {α : Q(Type u)} {e : Q($α)} (_i : Q(DivisionRing $α) := by with_reducible assumption) : Result e → Option (ℚ × (n : Q(ℤ)) × (d : Q(ℕ)) × Q(IsRat $e $n $d)) | .isBool .. => none | .isNat _ lit proof => have proof : Q(@IsNat _ instAddMonoidWithOne $e $lit) := proof some ⟨lit.natLit!, q(.ofNat $lit), q(nat_lit 1), q(($proof).to_isRat)⟩ | .isNegNat _ lit proof => have proof : Q(@IsInt _ DivisionRing.toRing $e (.negOfNat $lit)) := proof some ⟨-lit.natLit!, q(.negOfNat $lit), q(nat_lit 1), (q(@IsInt.to_isRat _ DivisionRing.toRing _ _ $proof) : Expr)⟩ | .isRat _ q n d proof => some ⟨q, n, d, proof⟩ /-- Given a `NormNum.Result e` (which uses `IsNat`, `IsInt`, `IsRat` to express equality to a rational numeral), converts it to an equality `e = Nat.rawCast n`, `e = Int.rawCast n`, or `e = Rat.rawCast n d` to a raw cast expression, so it can be used for rewriting. -/ def Result.toRawEq {α : Q(Type u)} {e : Q($α)} : Result e → (e' : Q($α)) × Q($e = $e') | .isBool false p => have e : Q(Prop) := e; have p : Q(¬$e) := p ⟨(q(False) : Expr), (q(eq_false $p) : Expr)⟩ | .isBool true p => have e : Q(Prop) := e; have p : Q($e) := p ⟨(q(True) : Expr), (q(eq_true $p) : Expr)⟩ | .isNat _ lit p => ⟨q(Nat.rawCast $lit), q(IsNat.to_raw_eq $p)⟩ | .isNegNat _ lit p => ⟨q(Int.rawCast (.negOfNat $lit)), q(IsInt.to_raw_eq $p)⟩ | .isRat _ _ n d p => ⟨q(Rat.rawCast $n $d), q(IsRat.to_raw_eq $p)⟩ /-- `Result.toRawEq` but providing an integer. Given a `NormNum.Result e` for something known to be an integer (which uses `IsNat` or `IsInt` to express equality to an integer numeral), converts it to an equality `e = Nat.rawCast n` or `e = Int.rawCast n` to a raw cast expression, so it can be used for rewriting. Gives `none` if not an integer. -/ def Result.toRawIntEq {α : Q(Type u)} {e : Q($α)} : Result e → Option (ℤ × (e' : Q($α)) × Q($e = $e')) | .isNat _ lit p => some ⟨lit.natLit!, q(Nat.rawCast $lit), q(IsNat.to_raw_eq $p)⟩ | .isNegNat _ lit p => some ⟨-lit.natLit!, q(Int.rawCast (.negOfNat $lit)), q(IsInt.to_raw_eq $p)⟩ | .isRat _ .. | .isBool .. => none /-- Constructs a `Result` out of a raw nat cast. Assumes `e` is a raw nat cast expression. -/ def Result.ofRawNat {α : Q(Type u)} (e : Q($α)) : Result e := Id.run do let .app (.app _ (sα : Q(AddMonoidWithOne $α))) (lit : Q(ℕ)) := e | panic! "not a raw nat cast" .isNat sα lit (q(IsNat.of_raw $α $lit) : Expr) /-- Constructs a `Result` out of a raw int cast. Assumes `e` is a raw int cast expression denoting `n`. -/ def Result.ofRawInt {α : Q(Type u)} (n : ℤ) (e : Q($α)) : Result e := if 0 ≤ n then Result.ofRawNat e else Id.run do let .app (.app _ (rα : Q(Ring $α))) (.app _ (lit : Q(ℕ))) := e | panic! "not a raw int cast" .isNegNat rα lit (q(IsInt.of_raw $α (.negOfNat $lit)) : Expr) /-- Constructs a `Result` out of a raw rat cast. Assumes `e` is a raw rat cast expression denoting `n`. -/ def Result.ofRawRat {α : Q(Type u)} (q : ℚ) (e : Q($α)) (hyp : Option Expr := none) : Result e := if q.den = 1 then Result.ofRawInt q.num e else Id.run do let .app (.app (.app _ (dα : Q(DivisionRing $α))) (n : Q(ℤ))) (d : Q(ℕ)) := e | panic! "not a raw rat cast" let hyp : Q(($d : $α) ≠ 0) := hyp.get! .isRat dα q n d (q(IsRat.of_raw $α $n $d $hyp) : Expr) /-- Convert a `Result` to a `Simp.Result`. -/ def Result.toSimpResult {α : Q(Type u)} {e : Q($α)} : Result e → MetaM Simp.Result | r@(.isBool ..) => let ⟨expr, proof?⟩ := r.toRawEq; pure { expr, proof? } | .isNat sα lit p => do let ⟨a', pa'⟩ ← mkOfNat α sα lit return { expr := a', proof? := q(IsNat.to_eq $p $pa') } | .isNegNat _rα lit p => do let ⟨a', pa'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) lit return { expr := q(-$a'), proof? := q(IsInt.neg_to_eq $p $pa') } | .isRat _ q n d p => do have lit : Q(ℕ) := n.appArg! if q < 0 then let p : Q(IsRat $e (.negOfNat $lit) $d) := p let ⟨n', pn'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) lit let ⟨d', pd'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) d return { expr := q(-($n' / $d')), proof? := q(IsRat.neg_to_eq $p $pn' $pd') } else let p : Q(IsRat $e (.ofNat $lit) $d) := p let ⟨n', pn'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) lit let ⟨d', pd'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) d return { expr := q($n' / $d'), proof? := q(IsRat.nonneg_to_eq $p $pn' $pd') } /-- Given `Mathlib.Meta.NormNum.Result.isBool p b`, this is the type of `p`. Note that `BoolResult p b` is definitionally equal to `Expr`, and if you write `match b with ...`, then in the `true` branch `BoolResult p true` is reducibly equal to `Q($p)` and in the `false` branch it is reducibly equal to `Q(¬ $p)`. -/ abbrev BoolResult (p : Q(Prop)) (b : Bool) : Type := Q(Bool.rec (¬ $p) ($p) $b) /-- Obtain a `Result` from a `BoolResult`. -/ def Result.ofBoolResult {p : Q(Prop)} {b : Bool} (prf : BoolResult p b) : Result q(Prop) := Result'.isBool b prf /-- If `a = b` and we can evaluate `b`, then we can evaluate `a`. -/ def Result.eqTrans {α : Q(Type u)} {a b : Q($α)} (eq : Q($a = $b)) : Result b → Result a | .isBool true proof => have a : Q(Prop) := a have b : Q(Prop) := b have eq : Q($a = $b) := eq have proof : Q($b) := proof Result.isTrue (x := a) q($eq ▸ $proof) | .isBool false proof => have a : Q(Prop) := a have b : Q(Prop) := b have eq : Q($a = $b) := eq have proof : Q(¬ $b) := proof Result.isFalse (x := a) q($eq ▸ $proof) | .isNat inst lit proof => Result.isNat inst lit q($eq ▸ $proof) | .isNegNat inst lit proof => Result.isNegNat inst lit q($eq ▸ $proof) | .isRat inst q n d proof => Result.isRat inst q n d q($eq ▸ $proof) end Meta.NormNum
Tactic\Positivity\Basic.lean
/- Copyright (c) 2022 Mario Carneiro, Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Heather Macbeth, Yaël Dillies -/ import Mathlib.Algebra.Order.Group.PosPart import Mathlib.Algebra.Order.Ring.Basic import Mathlib.Algebra.Order.Ring.Rat import Mathlib.Data.Int.CharZero import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Data.NNRat.Defs import Mathlib.Data.PNat.Defs import Mathlib.Tactic.Positivity.Core import Qq /-! ## `positivity` core extensions This file sets up the basic `positivity` extensions tagged with the `@[positivity]` attribute. -/ variable {α : Type*} namespace Mathlib.Meta.Positivity open Lean Meta Qq Function section ite variable [Zero α] (p : Prop) [Decidable p] {a b : α} private lemma ite_pos [LT α] (ha : 0 < a) (hb : 0 < b) : 0 < ite p a b := by by_cases p <;> simp [*] private lemma ite_nonneg [LE α] (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ ite p a b := by by_cases p <;> simp [*] private lemma ite_nonneg_of_pos_of_nonneg [Preorder α] (ha : 0 < a) (hb : 0 ≤ b) : 0 ≤ ite p a b := ite_nonneg _ ha.le hb private lemma ite_nonneg_of_nonneg_of_pos [Preorder α] (ha : 0 ≤ a) (hb : 0 < b) : 0 ≤ ite p a b := ite_nonneg _ ha hb.le private lemma ite_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : ite p a b ≠ 0 := by by_cases p <;> simp [*] private lemma ite_ne_zero_of_pos_of_ne_zero [Preorder α] (ha : 0 < a) (hb : b ≠ 0) : ite p a b ≠ 0 := ite_ne_zero _ ha.ne' hb private lemma ite_ne_zero_of_ne_zero_of_pos [Preorder α] (ha : a ≠ 0) (hb : 0 < b) : ite p a b ≠ 0 := ite_ne_zero _ ha hb.ne' end ite /-- The `positivity` extension which identifies expressions of the form `ite p a b`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity ite _ _ _] def evalIte : PositivityExt where eval {u α} zα pα e := do let .app (.app (.app (.app f (p : Q(Prop))) (_ : Q(Decidable $p))) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not ite" haveI' : $e =Q ite $p $a $b := ⟨⟩ let ra ← core zα pα a; let rb ← core zα pα b guard <|← withDefault <| withNewMCtxDepth <| isDefEq f q(ite (α := $α)) match ra, rb with | .positive pa, .positive pb => pure (.positive q(ite_pos $p $pa $pb)) | .positive pa, .nonnegative pb => let _b ← synthInstanceQ q(Preorder $α) assumeInstancesCommute pure (.nonnegative q(ite_nonneg_of_pos_of_nonneg $p $pa $pb)) | .nonnegative pa, .positive pb => let _b ← synthInstanceQ q(Preorder $α) assumeInstancesCommute pure (.nonnegative q(ite_nonneg_of_nonneg_of_pos $p $pa $pb)) | .nonnegative pa, .nonnegative pb => pure (.nonnegative q(ite_nonneg $p $pa $pb)) | .positive pa, .nonzero pb => let _b ← synthInstanceQ q(Preorder $α) assumeInstancesCommute pure (.nonzero q(ite_ne_zero_of_pos_of_ne_zero $p $pa $pb)) | .nonzero pa, .positive pb => let _b ← synthInstanceQ q(Preorder $α) assumeInstancesCommute pure (.nonzero q(ite_ne_zero_of_ne_zero_of_pos $p $pa $pb)) | .nonzero pa, .nonzero pb => pure (.nonzero q(ite_ne_zero $p $pa $pb)) | _, _ => pure .none section LinearOrder variable {R : Type*} [LinearOrder R] {a b c : R} private lemma le_min_of_lt_of_le (ha : a < b) (hb : a ≤ c) : a ≤ min b c := le_min ha.le hb private lemma le_min_of_le_of_lt (ha : a ≤ b) (hb : a < c) : a ≤ min b c := le_min ha hb.le private lemma min_ne (ha : a ≠ c) (hb : b ≠ c) : min a b ≠ c := by rw [min_def]; split_ifs <;> assumption private lemma min_ne_of_ne_of_lt (ha : a ≠ c) (hb : c < b) : min a b ≠ c := min_ne ha hb.ne' private lemma min_ne_of_lt_of_ne (ha : c < a) (hb : b ≠ c) : min a b ≠ c := min_ne ha.ne' hb private lemma max_ne (ha : a ≠ c) (hb : b ≠ c) : max a b ≠ c := by rw [max_def]; split_ifs <;> assumption end LinearOrder /-- The `positivity` extension which identifies expressions of the form `min a b`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity min _ _] def evalMin : PositivityExt where eval {u α} zα pα e := do let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not min" let _e_eq : $e =Q $f $a $b := ⟨⟩ let _a ← synthInstanceQ (q(LinearOrder $α) : Q(Type u)) assumeInstancesCommute let ⟨_f_eq⟩ ← withDefault <| withNewMCtxDepth <| assertDefEqQ (u := u.succ) f q(min) match ← core zα pα a, ← core zα pα b with | .positive pa, .positive pb => pure (.positive q(lt_min $pa $pb)) | .positive pa, .nonnegative pb => pure (.nonnegative q(le_min_of_lt_of_le $pa $pb)) | .nonnegative pa, .positive pb => pure (.nonnegative q(le_min_of_le_of_lt $pa $pb)) | .nonnegative pa, .nonnegative pb => pure (.nonnegative q(le_min $pa $pb)) | .positive pa, .nonzero pb => pure (.nonzero q(min_ne_of_lt_of_ne $pa $pb)) | .nonzero pa, .positive pb => pure (.nonzero q(min_ne_of_ne_of_lt $pa $pb)) | .nonzero pa, .nonzero pb => pure (.nonzero q(min_ne $pa $pb)) | _, _ => pure .none /-- Extension for the `max` operator. The `max` of two numbers is nonnegative if at least one is nonnegative, strictly positive if at least one is positive, and nonzero if both are nonzero. -/ @[positivity max _ _] def evalMax : PositivityExt where eval {u α} zα pα e := do let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not max" let _e_eq : $e =Q $f $a $b := ⟨⟩ let _a ← synthInstanceQ (q(LinearOrder $α) : Q(Type u)) assumeInstancesCommute let ⟨_f_eq⟩ ← withDefault <| withNewMCtxDepth <| assertDefEqQ (u := u.succ) f q(max) let result : Strictness zα pα e ← catchNone do let ra ← core zα pα a match ra with | .positive pa => pure (.positive q(lt_max_of_lt_left $pa)) | .nonnegative pa => pure (.nonnegative q(le_max_of_le_left $pa)) -- If `a ≠ 0`, we might prove `max a b ≠ 0` if `b ≠ 0` but we don't want to evaluate -- `b` before having ruled out `0 < a`, for performance. So we do that in the second branch -- of the `orElse'`. | _ => pure .none orElse result do let rb ← core zα pα b match rb with | .positive pb => pure (.positive q(lt_max_of_lt_right $pb)) | .nonnegative pb => pure (.nonnegative q(le_max_of_le_right $pb)) | .nonzero pb => do match ← core zα pα a with | .nonzero pa => pure (.nonzero q(max_ne $pa $pb)) | _ => pure .none | _ => pure .none /-- The `positivity` extension which identifies expressions of the form `a + b`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity _ + _] def evalAdd : PositivityExt where eval {u α} zα pα e := do let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not +" let _e_eq : $e =Q $f $a $b := ⟨⟩ let _a ← synthInstanceQ (q(AddZeroClass $α) : Q(Type u)) assumeInstancesCommute let ⟨_f_eq⟩ ← withDefault <| withNewMCtxDepth <| assertDefEqQ (u := u.succ) f q(HAdd.hAdd) let ra ← core zα pα a; let rb ← core zα pα b match ra, rb with | .positive pa, .positive pb => let _a ← synthInstanceQ (q(CovariantClass $α $α (·+·) (·<·)) : Q(Prop)) pure (.positive q(add_pos $pa $pb)) | .positive pa, .nonnegative pb => let _a ← synthInstanceQ (q(CovariantClass $α $α (swap (·+·)) (·<·)) : Q(Prop)) pure (.positive q(lt_add_of_pos_of_le $pa $pb)) | .nonnegative pa, .positive pb => let _a ← synthInstanceQ (q(CovariantClass $α $α (·+·) (·<·)) : Q(Prop)) pure (.positive q(lt_add_of_le_of_pos $pa $pb)) | .nonnegative pa, .nonnegative pb => let _a ← synthInstanceQ (q(CovariantClass $α $α (·+·) (·≤·)) : Q(Prop)) pure (.nonnegative q(add_nonneg $pa $pb)) | _, _ => failure private theorem mul_nonneg_of_pos_of_nonneg [OrderedSemiring α] {a b : α} (ha : 0 < a) (hb : 0 ≤ b) : 0 ≤ a * b := mul_nonneg ha.le hb private theorem mul_nonneg_of_nonneg_of_pos [OrderedSemiring α] {a b : α} (ha : 0 ≤ a) (hb : 0 < b) : 0 ≤ a * b := mul_nonneg ha hb.le private theorem mul_ne_zero_of_ne_zero_of_pos [OrderedSemiring α] [NoZeroDivisors α] {a b : α} (ha : a ≠ 0) (hb : 0 < b) : a * b ≠ 0 := mul_ne_zero ha (ne_of_gt hb) private theorem mul_ne_zero_of_pos_of_ne_zero [OrderedSemiring α] [NoZeroDivisors α] {a b : α} (ha : 0 < a) (hb : b ≠ 0) : a * b ≠ 0 := mul_ne_zero (ne_of_gt ha) hb /-- The `positivity` extension which identifies expressions of the form `a * b`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity _ * _] def evalMul : PositivityExt where eval {u α} zα pα e := do let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not *" let _e_eq : $e =Q $f $a $b := ⟨⟩ let _a ← synthInstanceQ q(StrictOrderedSemiring $α) assumeInstancesCommute let ⟨_f_eq⟩ ← withDefault <| withNewMCtxDepth <| assertDefEqQ (u := u.succ) f q(HMul.hMul) let ra ← core zα pα a; let rb ← core zα pα b match ra, rb with | .positive pa, .positive pb => pure (.positive q(mul_pos $pa $pb)) | .positive pa, .nonnegative pb => pure (.nonnegative q(mul_nonneg_of_pos_of_nonneg $pa $pb)) | .nonnegative pa, .positive pb => pure (.nonnegative q(mul_nonneg_of_nonneg_of_pos $pa $pb)) | .nonnegative pa, .nonnegative pb => pure (.nonnegative q(mul_nonneg $pa $pb)) | .positive pa, .nonzero pb => let _a ← synthInstanceQ (q(NoZeroDivisors $α) : Q(Prop)) pure (.nonzero q(mul_ne_zero_of_pos_of_ne_zero $pa $pb)) | .nonzero pa, .positive pb => let _a ← synthInstanceQ (q(NoZeroDivisors $α) : Q(Prop)) pure (.nonzero q(mul_ne_zero_of_ne_zero_of_pos $pa $pb)) | .nonzero pa, .nonzero pb => let _a ← synthInstanceQ (q(NoZeroDivisors $α) : Q(Prop)) pure (.nonzero q(mul_ne_zero $pa $pb)) | _, _ => pure .none private lemma int_div_self_pos {a : ℤ} (ha : 0 < a) : 0 < a / a := by rw [Int.ediv_self ha.ne']; exact zero_lt_one private lemma int_div_nonneg_of_pos_of_nonneg {a b : ℤ} (ha : 0 < a) (hb : 0 ≤ b) : 0 ≤ a / b := Int.ediv_nonneg ha.le hb private lemma int_div_nonneg_of_nonneg_of_pos {a b : ℤ} (ha : 0 ≤ a) (hb : 0 < b) : 0 ≤ a / b := Int.ediv_nonneg ha hb.le private lemma int_div_nonneg_of_pos_of_pos {a b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 ≤ a / b := Int.ediv_nonneg ha.le hb.le /-- The `positivity` extension which identifies expressions of the form `a / b`, where `a` and `b` are integers. -/ @[positivity (_ : ℤ) / (_ : ℤ)] def evalIntDiv : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℤ), ~q($a / $b) => let ra ← core q(inferInstance) q(inferInstance) a let rb ← core q(inferInstance) q(inferInstance) b assertInstancesCommute match ra, rb with | .positive (pa : Q(0 < $a)), .positive (pb : Q(0 < $b)) => -- Only attempts to prove `0 < a / a`, otherwise falls back to `0 ≤ a / b` match ← isDefEqQ a b with | .defEq _ => pure (.positive q(int_div_self_pos $pa)) | .notDefEq => pure (.nonnegative q(int_div_nonneg_of_pos_of_pos $pa $pb)) | .positive (pa : Q(0 < $a)), .nonnegative (pb : Q(0 ≤ $b)) => pure (.nonnegative q(int_div_nonneg_of_pos_of_nonneg $pa $pb)) | .nonnegative (pa : Q(0 ≤ $a)), .positive (pb : Q(0 < $b)) => pure (.nonnegative q(int_div_nonneg_of_nonneg_of_pos $pa $pb)) | .nonnegative (pa : Q(0 ≤ $a)), .nonnegative (pb : Q(0 ≤ $b)) => pure (.nonnegative q(Int.ediv_nonneg $pa $pb)) | _, _ => pure .none | _, _, _ => throwError "not /" private theorem pow_zero_pos [OrderedSemiring α] [Nontrivial α] (a : α) : 0 < a ^ 0 := zero_lt_one.trans_le (pow_zero a).ge /-- The `positivity` extension which identifies expressions of the form `a ^ (0:ℕ)`. This extension is run in addition to the general `a ^ b` extension (they are overlapping). -/ @[positivity _ ^ (0:ℕ)] def evalPowZeroNat : PositivityExt where eval {u α} _zα _pα e := do let .app (.app _ (a : Q($α))) _ ← withReducible (whnf e) | throwError "not ^" _ ← synthInstanceQ (q(OrderedSemiring $α) : Q(Type u)) _ ← synthInstanceQ (q(Nontrivial $α) : Q(Prop)) pure (.positive (q(pow_zero_pos $a) : Expr)) /-- The `positivity` extension which identifies expressions of the form `a ^ (b : ℕ)`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity _ ^ (_ : ℕ)] def evalPow : PositivityExt where eval {u α} zα pα e := do let .app (.app _ (a : Q($α))) (b : Q(ℕ)) ← withReducible (whnf e) | throwError "not ^" let result ← catchNone do let .true := b.isAppOfArity ``OfNat.ofNat 3 | throwError "not a ^ n where n is a literal" let some n := (b.getRevArg! 1).rawNatLit? | throwError "not a ^ n where n is a literal" guard (n % 2 = 0) have m : Q(ℕ) := mkRawNatLit (n / 2) haveI' : $b =Q 2 * $m := ⟨⟩ let _a ← synthInstanceQ q(LinearOrderedRing $α) haveI' : $e =Q $a ^ $b := ⟨⟩ assumeInstancesCommute pure (.nonnegative q((even_two_mul $m).pow_nonneg $a)) orElse result do let ra ← core zα pα a let ofNonneg (pa : Q(0 ≤ $a)) (_oα : Q(OrderedSemiring $α)) : MetaM (Strictness zα pα e) := do haveI' : $e =Q $a ^ $b := ⟨⟩ assumeInstancesCommute pure (.nonnegative q(pow_nonneg $pa $b)) let ofNonzero (pa : Q($a ≠ 0)) (_oα : Q(OrderedSemiring $α)) : MetaM (Strictness zα pα e) := do haveI' : $e =Q $a ^ $b := ⟨⟩ assumeInstancesCommute let _a ← synthInstanceQ q(NoZeroDivisors $α) pure (.nonzero q(pow_ne_zero $b $pa)) match ra with | .positive pa => try let _a ← synthInstanceQ (q(StrictOrderedSemiring $α) : Q(Type u)) haveI' : $e =Q $a ^ $b := ⟨⟩ assumeInstancesCommute pure (.positive q(pow_pos $pa $b)) catch e : Exception => trace[Tactic.positivity.failure] "{e.toMessageData}" let oα ← synthInstanceQ q(OrderedSemiring $α) orElse (← catchNone (ofNonneg q(le_of_lt $pa) oα)) (ofNonzero q(ne_of_gt $pa) oα) | .nonnegative pa => ofNonneg pa (← synthInstanceQ (_ : Q(Type u))) | .nonzero pa => ofNonzero pa (← synthInstanceQ (_ : Q(Type u))) | .none => pure .none private theorem abs_pos_of_ne_zero {α : Type*} [AddGroup α] [LinearOrder α] [CovariantClass α α (·+·) (·≤·)] {a : α} : a ≠ 0 → 0 < |a| := abs_pos.mpr /-- The `positivity` extension which identifies expressions of the form `|a|`. -/ @[positivity |_|] def evalAbs : PositivityExt where eval {u} (α : Q(Type u)) zα pα (e : Q($α)) := do let ~q(@abs _ (_) (_) $a) := e | throwError "not |·|" try match ← core zα pα a with | .positive pa => let pa' ← mkAppM ``abs_pos_of_pos #[pa] pure (.positive pa') | .nonzero pa => let pa' ← mkAppM ``abs_pos_of_ne_zero #[pa] pure (.positive pa') | _ => pure .none catch _ => do let pa' ← mkAppM ``abs_nonneg #[a] pure (.nonnegative pa') private theorem int_natAbs_pos {n : ℤ} (hn : 0 < n) : 0 < n.natAbs := Int.natAbs_pos.mpr hn.ne' /-- Extension for the `positivity` tactic: `Int.natAbs` is positive when its input is. Since the output type of `Int.natAbs` is `ℕ`, the nonnegative case is handled by the default `positivity` tactic. -/ @[positivity Int.natAbs _] def evalNatAbs : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℕ), ~q(Int.natAbs $a) => let zα' : Q(Zero Int) := q(inferInstance) let pα' : Q(PartialOrder Int) := q(inferInstance) let ra ← core zα' pα' a match ra with | .positive pa => assertInstancesCommute pure (.positive q(int_natAbs_pos $pa)) | .nonzero pa => assertInstancesCommute pure (.positive q(Int.natAbs_pos.mpr $pa)) | .nonnegative _pa => pure .none | .none => pure .none | _, _, _ => throwError "not Int.natAbs" /-- Extension for the `positivity` tactic: `Nat.cast` is always non-negative, and positive when its input is. -/ @[positivity Nat.cast _] def evalNatCast : PositivityExt where eval {u α} _zα _pα e := do let ~q(@Nat.cast _ (_) ($a : ℕ)) := e | throwError "not Nat.cast" let zα' : Q(Zero Nat) := q(inferInstance) let pα' : Q(PartialOrder Nat) := q(inferInstance) let (_oα : Q(OrderedSemiring $α)) ← synthInstanceQ q(OrderedSemiring $α) assumeInstancesCommute match ← core zα' pα' a with | .positive pa => let _nt ← synthInstanceQ q(Nontrivial $α) pure (.positive q(Nat.cast_pos.mpr $pa)) | _ => pure (.nonnegative q(Nat.cast_nonneg _)) /-- Extension for the `positivity` tactic: `Int.cast` is positive (resp. non-negative) if its input is. -/ @[positivity Int.cast _] def evalIntCast : PositivityExt where eval {u α} _zα _pα e := do let ~q(@Int.cast _ (_) ($a : ℤ)) := e | throwError "not Int.cast" let zα' : Q(Zero Int) := q(inferInstance) let pα' : Q(PartialOrder Int) := q(inferInstance) let ra ← core zα' pα' a match ra with | .positive pa => let _oα ← synthInstanceQ (q(OrderedRing $α) : Q(Type u)) let _nt ← synthInstanceQ q(Nontrivial $α) assumeInstancesCommute pure (.positive q(Int.cast_pos.mpr $pa)) | .nonnegative pa => let _oα ← synthInstanceQ q(OrderedRing $α) let _nt ← synthInstanceQ q(Nontrivial $α) assumeInstancesCommute pure (.nonnegative q(Int.cast_nonneg.mpr $pa)) | .nonzero pa => let _oα ← synthInstanceQ (q(AddGroupWithOne $α) : Q(Type $u)) let _nt ← synthInstanceQ (q(CharZero $α) : Q(Prop)) assumeInstancesCommute pure (.nonzero q(Int.cast_ne_zero.mpr $pa)) | .none => pure .none /-- Extension for `Nat.succ`. -/ @[positivity Nat.succ _] def evalNatSucc : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.succ $a) => assertInstancesCommute pure (.positive q(Nat.succ_pos $a)) | _, _, _ => throwError "not Nat.succ" /-- Extension for `PNat.val`. -/ @[positivity PNat.val _] def evalPNatVal : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℕ), ~q(PNat.val $a) => assertInstancesCommute pure (.positive q(PNat.pos $a)) | _, _, _ => throwError "not PNat.val" /-- Extension for `Nat.factorial`. -/ @[positivity Nat.factorial _] def evalFactorial : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.factorial $a) => assertInstancesCommute pure (.positive q(Nat.factorial_pos $a)) | _, _, _ => throwError "failed to match Nat.factorial" /-- Extension for `Nat.ascFactorial`. -/ @[positivity Nat.ascFactorial _ _] def evalAscFactorial : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.ascFactorial ($n + 1) $k) => assertInstancesCommute pure (.positive q(Nat.ascFactorial_pos $n $k)) | _, _, _ => throwError "failed to match Nat.ascFactorial" section NNRat open NNRat private alias ⟨_, NNRat.num_pos_of_pos⟩ := num_pos private alias ⟨_, NNRat.num_ne_zero_of_ne_zero⟩ := num_ne_zero /-- The `positivity` extension which identifies expressions of the form `NNRat.num q`, such that `positivity` successfully recognises `q`. -/ @[positivity NNRat.num _] def evalNNRatNum : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(NNRat.num $a) => let zα : Q(Zero ℚ≥0) := q(inferInstance) let pα : Q(PartialOrder ℚ≥0) := q(inferInstance) assumeInstancesCommute match ← core zα pα a with | .positive pa => return .positive q(NNRat.num_pos_of_pos $pa) | .nonzero pa => return .nonzero q(NNRat.num_ne_zero_of_ne_zero $pa) | _ => return .none | _, _, _ => throwError "not NNRat.num" /-- The `positivity` extension which identifies expressions of the form `Rat.den a`. -/ @[positivity NNRat.den _] def evalNNRatDen : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(NNRat.den $a) => assumeInstancesCommute return .positive q(den_pos $a) | _, _, _ => throwError "not NNRat.den" variable {q : ℚ≥0} example (hq : 0 < q) : 0 < q.num := by positivity example (hq : q ≠ 0) : q.num ≠ 0 := by positivity example : 0 < q.den := by positivity end NNRat open Rat private alias ⟨_, num_pos_of_pos⟩ := num_pos private alias ⟨_, num_nonneg_of_nonneg⟩ := num_nonneg private alias ⟨_, num_ne_zero_of_ne_zero⟩ := num_ne_zero /-- The `positivity` extension which identifies expressions of the form `Rat.num a`, such that `positivity` successfully recognises `a`. -/ @[positivity Rat.num _] def evalRatNum : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℤ), ~q(Rat.num $a) => let zα : Q(Zero ℚ) := q(inferInstance) let pα : Q(PartialOrder ℚ) := q(inferInstance) assumeInstancesCommute match ← core zα pα a with | .positive pa => pure $ .positive q(num_pos_of_pos $pa) | .nonnegative pa => pure $ .nonnegative q(num_nonneg_of_nonneg $pa) | .nonzero pa => pure $ .nonzero q(num_ne_zero_of_ne_zero $pa) | .none => pure .none | _, _ => throwError "not Rat.num" /-- The `positivity` extension which identifies expressions of the form `Rat.den a`. -/ @[positivity Rat.den _] def evalRatDen : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Rat.den $a) => assumeInstancesCommute pure $ .positive q(den_pos $a) | _, _ => throwError "not Rat.num" /-- Extension for `posPart`. `a⁺` is always nonegative, and positive if `a` is. -/ @[positivity _⁺] def evalPosPart : PositivityExt where eval zα pα e := do match e with | ~q(@posPart _ $instαlat $instαgrp $a) => assertInstancesCommute -- FIXME: There seems to be a bug in `Positivity.core` that makes it fail (instead of returning -- `.none`) here sometimes. See eg the first test for `posPart`. This is why we need `catchNone` match ← catchNone (core zα pα a) with | .positive pf => return .positive q(posPart_pos $pf) | _ => return .nonnegative q(posPart_nonneg $a) | _ => throwError "not `posPart`" /-- Extension for `negPart`. `a⁻` is always nonegative. -/ @[positivity _⁻] def evalNegPart : PositivityExt where eval _ _ e := do match e with | ~q(@negPart _ $instαlat $instαgrp $a) => assertInstancesCommute return .nonnegative q(negPart_nonneg $a) | _ => throwError "not `negPart`" end Positivity end Meta end Mathlib
Tactic\Positivity\Core.lean
/- Copyright (c) 2022 Mario Carneiro, Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Heather Macbeth, Yaël Dillies -/ import Mathlib.Tactic.NormNum.Core import Mathlib.Tactic.HaveI import Mathlib.Algebra.Order.Invertible import Mathlib.Algebra.Order.Ring.Cast import Mathlib.Data.Nat.Cast.Basic import Qq /-! ## `positivity` core functionality This file sets up the `positivity` tactic and the `@[positivity]` attribute, which allow for plugging in new positivity functionality around a positivity-based driver. The actual behavior is in `@[positivity]`-tagged definitions in `Tactic.Positivity.Basic` and elsewhere. -/ open Lean hiding Rat open Lean.Meta Qq Lean.Elab Term /-- Attribute for identifying `positivity` extensions. -/ syntax (name := positivity) "positivity " term,+ : attr lemma ne_of_ne_of_eq' {α : Sort*} {a c b : α} (hab : (a : α) ≠ c) (hbc : a = b) : b ≠ c := hbc ▸ hab namespace Mathlib.Meta.Positivity variable {u : Level} {α : Q(Type u)} (zα : Q(Zero $α)) (pα : Q(PartialOrder $α)) /-- The result of `positivity` running on an expression `e` of type `α`. -/ inductive Strictness (e : Q($α)) where | positive (pf : Q(0 < $e)) | nonnegative (pf : Q(0 ≤ $e)) | nonzero (pf : Q($e ≠ 0)) | none deriving Repr /-- Gives a generic description of the `positivity` result. -/ def Strictness.toString {e : Q($α)} : Strictness zα pα e → String | positive _ => "positive" | nonnegative _ => "nonnegative" | nonzero _ => "nonzero" | none => "none" /-- Extract a proof that `e` is nonnegative, if possible, from `Strictness` information about `e`. -/ def Strictness.toNonneg {e} : Strictness zα pα e → Option Q(0 ≤ $e) | .positive pf => some q(le_of_lt $pf) | .nonnegative pf => some pf | _ => .none /-- Extract a proof that `e` is nonzero, if possible, from `Strictness` information about `e`. -/ def Strictness.toNonzero {e} : Strictness zα pα e → Option Q($e ≠ 0) | .positive pf => some q(ne_of_gt $pf) | .nonzero pf => some pf | _ => .none /-- An extension for `positivity`. -/ structure PositivityExt where /-- Attempts to prove an expression `e : α` is `>0`, `≥0`, or `≠0`. -/ eval {u} {α : Q(Type u)} (zα : Q(Zero $α)) (pα : Q(PartialOrder $α)) (e : Q($α)) : MetaM (Strictness zα pα e) /-- Read a `positivity` extension from a declaration of the right type. -/ def mkPositivityExt (n : Name) : ImportM PositivityExt := do let { env, opts, .. } ← read IO.ofExcept <| unsafe env.evalConstCheck PositivityExt opts ``PositivityExt n /-- Configuration for `DiscrTree`. -/ def discrTreeConfig : WhnfCoreConfig := {} /-- Each `positivity` extension is labelled with a collection of patterns which determine the expressions to which it should be applied. -/ abbrev Entry := Array (Array DiscrTree.Key) × Name /-- Environment extensions for `positivity` declarations -/ initialize positivityExt : PersistentEnvExtension Entry (Entry × PositivityExt) (List Entry × DiscrTree PositivityExt) ← -- we only need this to deduplicate entries in the DiscrTree have : BEq PositivityExt := ⟨fun _ _ => false⟩ let insert kss v dt := kss.foldl (fun dt ks => dt.insertCore ks v) dt registerPersistentEnvExtension { mkInitial := pure ([], {}) addImportedFn := fun s => do let dt ← s.foldlM (init := {}) fun dt s => s.foldlM (init := dt) fun dt (kss, n) => do pure (insert kss (← mkPositivityExt n) dt) pure ([], dt) addEntryFn := fun (entries, s) ((kss, n), ext) => ((kss, n) :: entries, insert kss ext s) exportEntriesFn := fun s => s.1.reverse.toArray } initialize registerBuiltinAttribute { name := `positivity descr := "adds a positivity extension" applicationTime := .afterCompilation add := fun declName stx kind => match stx with | `(attr| positivity $es,*) => do unless kind == AttributeKind.global do throwError "invalid attribute 'positivity', must be global" let env ← getEnv unless (env.getModuleIdxFor? declName).isNone do throwError "invalid attribute 'positivity', declaration is in an imported module" if (IR.getSorryDep env declName).isSome then return -- ignore in progress definitions let ext ← mkPositivityExt declName let keys ← MetaM.run' <| es.getElems.mapM fun stx => do let e ← TermElabM.run' <| withSaveInfoContext <| withAutoBoundImplicit <| withReader ({ · with ignoreTCFailures := true }) do let e ← elabTerm stx none let (_, _, e) ← lambdaMetaTelescope (← mkLambdaFVars (← getLCtx).getFVars e) return e DiscrTree.mkPath e discrTreeConfig setEnv <| positivityExt.addEntry env ((keys, declName), ext) | _ => throwUnsupportedSyntax } variable {A : Type*} {e : A} lemma lt_of_le_of_ne' {a b : A} [PartialOrder A] : (a : A) ≤ b → b ≠ a → a < b := fun h₁ h₂ => lt_of_le_of_ne h₁ h₂.symm lemma pos_of_isNat {n : ℕ} [StrictOrderedSemiring A] (h : NormNum.IsNat e n) (w : Nat.ble 1 n = true) : 0 < (e : A) := by rw [NormNum.IsNat.to_eq h rfl] apply Nat.cast_pos.2 simpa using w lemma nonneg_of_isNat {n : ℕ} [OrderedSemiring A] (h : NormNum.IsNat e n) : 0 ≤ (e : A) := by rw [NormNum.IsNat.to_eq h rfl] exact Nat.cast_nonneg n lemma nz_of_isNegNat {n : ℕ} [StrictOrderedRing A] (h : NormNum.IsInt e (.negOfNat n)) (w : Nat.ble 1 n = true) : (e : A) ≠ 0 := by rw [NormNum.IsInt.neg_to_eq h rfl] simp only [ne_eq, neg_eq_zero] apply ne_of_gt simpa using w lemma pos_of_isRat {n : ℤ} {d : ℕ} [LinearOrderedRing A] : (NormNum.IsRat e n d) → (decide (0 < n)) → ((0 : A) < (e : A)) | ⟨inv, eq⟩, h => by have pos_invOf_d : (0 < ⅟ (d : A)) := pos_invOf_of_invertible_cast d have pos_n : (0 < (n : A)) := Int.cast_pos (n := n) |>.2 (of_decide_eq_true h) rw [eq] exact mul_pos pos_n pos_invOf_d lemma nonneg_of_isRat {n : ℤ} {d : ℕ} [LinearOrderedRing A] : (NormNum.IsRat e n d) → (decide (n = 0)) → (0 ≤ (e : A)) | ⟨inv, eq⟩, h => by rw [eq, of_decide_eq_true h]; simp lemma nz_of_isRat {n : ℤ} {d : ℕ} [LinearOrderedRing A] : (NormNum.IsRat e n d) → (decide (n < 0)) → ((e : A) ≠ 0) | ⟨inv, eq⟩, h => by have pos_invOf_d : (0 < ⅟ (d : A)) := pos_invOf_of_invertible_cast d have neg_n : ((n : A) < 0) := Int.cast_lt_zero (n := n) |>.2 (of_decide_eq_true h) have neg := mul_neg_of_neg_of_pos neg_n pos_invOf_d rw [eq] exact ne_iff_lt_or_gt.2 (Or.inl neg) variable {zα pα} in /-- Converts a `MetaM Strictness` which can fail into one that never fails and returns `.none` instead. -/ def catchNone {e : Q($α)} (t : MetaM (Strictness zα pα e)) : MetaM (Strictness zα pα e) := try t catch e => trace[Tactic.positivity.failure] "{e.toMessageData}" pure .none variable {zα pα} in /-- Converts a `MetaM Strictness` which can return `.none` into one which never returns `.none` but fails instead. -/ def throwNone {m : Type → Type*} {e : Q($α)} [Monad m] [Alternative m] (t : m (Strictness zα pα e)) : m (Strictness zα pα e) := do match ← t with | .none => failure | r => pure r /-- Attempts to prove a `Strictness` result when `e` evaluates to a literal number. -/ def normNumPositivity (e : Q($α)) : MetaM (Strictness zα pα e) := catchNone do match ← NormNum.derive e with | .isBool .. => failure | .isNat _ lit p => if 0 < lit.natLit! then let _a ← synthInstanceQ q(StrictOrderedSemiring $α) assumeInstancesCommute have p : Q(NormNum.IsNat $e $lit) := p haveI' p' : Nat.ble 1 $lit =Q true := ⟨⟩ pure (.positive q(@pos_of_isNat $α _ _ _ $p $p')) else let _a ← synthInstanceQ q(OrderedSemiring $α) assumeInstancesCommute have p : Q(NormNum.IsNat $e $lit) := p pure (.nonnegative q(nonneg_of_isNat $p)) | .isNegNat _ lit p => let _a ← synthInstanceQ q(StrictOrderedRing $α) assumeInstancesCommute have p : Q(NormNum.IsInt $e (Int.negOfNat $lit)) := p haveI' p' : Nat.ble 1 $lit =Q true := ⟨⟩ pure (.nonzero q(nz_of_isNegNat $p $p')) | .isRat _i q n d p => let _a ← synthInstanceQ q(LinearOrderedRing $α) assumeInstancesCommute have p : Q(NormNum.IsRat $e $n $d) := p if 0 < q then haveI' w : decide (0 < $n) =Q true := ⟨⟩ pure (.positive q(pos_of_isRat $p $w)) else if q = 0 then -- should not be reachable, but just in case haveI' w : decide ($n = 0) =Q true := ⟨⟩ pure (.nonnegative q(nonneg_of_isRat $p $w)) else haveI' w : decide ($n < 0) =Q true := ⟨⟩ pure (.nonzero q(nz_of_isRat $p $w)) /-- Attempts to prove that `e ≥ 0` using `zero_le` in a `CanonicallyOrderedAddCommMonoid`. -/ def positivityCanon (e : Q($α)) : MetaM (Strictness zα pα e) := do let _i ← synthInstanceQ (q(CanonicallyOrderedAddCommMonoid $α) : Q(Type u)) assumeInstancesCommute pure (.nonnegative q(zero_le $e)) /-- A variation on `assumption` when the hypothesis is `lo ≤ e` where `lo` is a numeral. -/ def compareHypLE (lo e : Q($α)) (p₂ : Q($lo ≤ $e)) : MetaM (Strictness zα pα e) := do match ← normNumPositivity zα pα lo with | .positive p₁ => pure (.positive q(lt_of_lt_of_le $p₁ $p₂)) | .nonnegative p₁ => pure (.nonnegative q(le_trans $p₁ $p₂)) | _ => pure .none /-- A variation on `assumption` when the hypothesis is `lo < e` where `lo` is a numeral. -/ def compareHypLT (lo e : Q($α)) (p₂ : Q($lo < $e)) : MetaM (Strictness zα pα e) := do match ← normNumPositivity zα pα lo with | .positive p₁ => pure (.positive q(lt_trans $p₁ $p₂)) | .nonnegative p₁ => pure (.positive q(lt_of_le_of_lt $p₁ $p₂)) | _ => pure .none /-- A variation on `assumption` when the hypothesis is `x = e` where `x` is a numeral. -/ def compareHypEq (e x : Q($α)) (p₂ : Q($x = $e)) : MetaM (Strictness zα pα e) := do match ← normNumPositivity zα pα x with | .positive p₁ => pure (.positive q(lt_of_lt_of_eq $p₁ $p₂)) | .nonnegative p₁ => pure (.nonnegative q(le_of_le_of_eq $p₁ $p₂)) | .nonzero p₁ => pure (.nonzero q(ne_of_ne_of_eq' $p₁ $p₂)) | .none => pure .none initialize registerTraceClass `Tactic.positivity initialize registerTraceClass `Tactic.positivity.failure /-- A variation on `assumption` which checks if the hypothesis `ldecl` is `a [</≤/=] e` where `a` is a numeral. -/ def compareHyp (e : Q($α)) (ldecl : LocalDecl) : MetaM (Strictness zα pα e) := do have e' : Q(Prop) := ldecl.type let p : Q($e') := .fvar ldecl.fvarId match e' with | ~q(@LE.le.{u} $β $_le $lo $hi) => let .defEq (_ : $α =Q $β) ← isDefEqQ α β | return .none let .defEq _ ← isDefEqQ e hi | return .none match lo with | ~q(0) => assertInstancesCommute return .nonnegative q($p) | _ => compareHypLE zα pα lo e p | ~q(@LT.lt.{u} $β $_lt $lo $hi) => let .defEq (_ : $α =Q $β) ← isDefEqQ α β | return .none let .defEq _ ← isDefEqQ e hi | return .none match lo with | ~q(0) => assertInstancesCommute return .positive q($p) | _ => compareHypLT zα pα lo e p | ~q(@Eq.{u+1} $α' $lhs $rhs) => let .defEq (_ : $α =Q $α') ← isDefEqQ α α' | pure .none match ← isDefEqQ e rhs with | .defEq _ => match lhs with | ~q(0) => pure <| .nonnegative q(le_of_eq $p) | _ => compareHypEq zα pα e lhs q($p) | .notDefEq => let .defEq _ ← isDefEqQ e lhs | pure .none match rhs with | ~q(0) => pure <| .nonnegative q(ge_of_eq $p) | _ => compareHypEq zα pα e rhs q(Eq.symm $p) | ~q(@Ne.{u + 1} $α' $lhs $rhs) => let .defEq (_ : $α =Q $α') ← isDefEqQ α α' | pure .none match lhs, rhs with | ~q(0), _ => let .defEq _ ← isDefEqQ e rhs | pure .none pure <| .nonzero q(Ne.symm $p) | _, ~q(0) => let .defEq _ ← isDefEqQ e lhs | pure .none pure <| .nonzero q($p) | _, _ => pure .none | _ => pure .none variable {zα pα} in /-- The main combinator which combines multiple `positivity` results. It assumes `t₁` has already been run for a result, and runs `t₂` and takes the best result. It will skip `t₂` if `t₁` is already a proof of `.positive`, and can also combine `.nonnegative` and `.nonzero` to produce a `.positive` result. -/ def orElse {e : Q($α)} (t₁ : Strictness zα pα e) (t₂ : MetaM (Strictness zα pα e)) : MetaM (Strictness zα pα e) := do match t₁ with | .none => catchNone t₂ | p@(.positive _) => pure p | .nonnegative p₁ => match ← catchNone t₂ with | p@(.positive _) => pure p | .nonzero p₂ => pure (.positive q(lt_of_le_of_ne' $p₁ $p₂)) | _ => pure (.nonnegative p₁) | .nonzero p₁ => match ← catchNone t₂ with | p@(.positive _) => pure p | .nonnegative p₂ => pure (.positive q(lt_of_le_of_ne' $p₂ $p₁)) | _ => pure (.nonzero p₁) /-- Run each registered `positivity` extension on an expression, returning a `NormNum.Result`. -/ def core (e : Q($α)) : MetaM (Strictness zα pα e) := do let mut result := .none trace[Tactic.positivity] "trying to prove positivity of {e}" for ext in ← (positivityExt.getState (← getEnv)).2.getMatch e discrTreeConfig do try result ← orElse result <| ext.eval zα pα e catch err => trace[Tactic.positivity] "{e} failed: {err.toMessageData}" result ← orElse result <| normNumPositivity zα pα e result ← orElse result <| positivityCanon zα pα e if let .positive _ := result then trace[Tactic.positivity] "{e} => {result.toString}" return result for ldecl in ← getLCtx do if !ldecl.isImplementationDetail then result ← orElse result <| compareHyp zα pα e ldecl trace[Tactic.positivity] "{e} => {result.toString}" throwNone (pure result) private inductive OrderRel : Type | le : OrderRel -- `0 ≤ a` | lt : OrderRel -- `0 < a` | ne : OrderRel -- `a ≠ 0` | ne' : OrderRel -- `0 ≠ a` end Meta.Positivity namespace Meta.Positivity /-- An auxillary entry point to the `positivity` tactic. Given a proposition `t` of the form `0 [≤/</≠] e`, attempts to recurse on the structure of `t` to prove it. It returns a proof or fails. -/ def solve (t : Q(Prop)) : MetaM Expr := do let rest {u : Level} (α : Q(Type u)) z e (relDesired : OrderRel) : MetaM Expr := do let zα ← synthInstanceQ q(Zero $α) assumeInstancesCommute let .true ← isDefEq z q(0 : $α) | throwError "not a positivity goal" let pα ← synthInstanceQ q(PartialOrder $α) assumeInstancesCommute let r ← catchNone <| Meta.Positivity.core zα pα e let throw (a b : String) : MetaM Expr := throwError "failed to prove {a}, but it would be possible to prove {b} if desired" let p ← show MetaM Expr from match relDesired, r with | .lt, .positive p | .le, .nonnegative p | .ne, .nonzero p => pure p | .le, .positive p => pure q(le_of_lt $p) | .ne, .positive p => pure q(ne_of_gt $p) | .ne', .positive p => pure q(ne_of_lt $p) | .ne', .nonzero p => pure q(Ne.symm $p) | .lt, .nonnegative _ => throw "strict positivity" "nonnegativity" | .lt, .nonzero _ => throw "strict positivity" "nonzeroness" | .le, .nonzero _ => throw "nonnegativity" "nonzeroness" | .ne, .nonnegative _ | .ne', .nonnegative _ => throw "nonzeroness" "nonnegativity" | _, .none => throwError "failed to prove positivity/nonnegativity/nonzeroness" pure p match t with | ~q(@LE.le $α $_a $z $e) => rest α z e .le | ~q(@LT.lt $α $_a $z $e) => rest α z e .lt | ~q($a ≠ ($b : ($α : Type _))) => let _zα ← synthInstanceQ (q(Zero $α) : Q(Type u_1)) if ← isDefEq b q((0 : $α)) then rest α b a .ne else let .true ← isDefEq a q((0 : $α)) | throwError "not a positivity goal" rest α a b .ne' | _ => throwError "not a positivity goal" /-- The main entry point to the `positivity` tactic. Given a goal `goal` of the form `0 [≤/</≠] e`, attempts to recurse on the structure of `e` to prove the goal. It will either close `goal` or fail. -/ def positivity (goal : MVarId) : MetaM Unit := do let t : Q(Prop) ← withReducible goal.getType' let p ← solve t goal.assign p end Meta.Positivity namespace Tactic.Positivity open Lean Elab Tactic /-- Tactic solving goals of the form `0 ≤ x`, `0 < x` and `x ≠ 0`. The tactic works recursively according to the syntax of the expression `x`, if the atoms composing the expression all have numeric lower bounds which can be proved positive/nonnegative/nonzero by `norm_num`. This tactic either closes the goal or fails. Examples: ``` example {a : ℤ} (ha : 3 < a) : 0 ≤ a ^ 3 + a := by positivity example {a : ℤ} (ha : 1 < a) : 0 < |(3:ℤ) + a| := by positivity example {b : ℤ} : 0 ≤ max (-3) (b ^ 2) := by positivity ``` -/ elab (name := positivity) "positivity" : tactic => do liftMetaTactic fun g => do Meta.Positivity.positivity g; pure [] end Positivity end Tactic end Mathlib
Tactic\Positivity\Finset.lean
/- Copyright (c) 2023 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Data.Finset.Density import Mathlib.Tactic.Positivity.Core /-! # Positivity extensions for finsets This file provides a few `positivity` extensions that cannot be in either the finset files (because they don't know about ordered fields) or in `Tactic.Positivity.Basic` (because it doesn't want to know about finiteness). -/ namespace Mathlib.Meta.Positivity open Qq Lean Meta Finset /-- Extension for `Finset.card`. `s.card` is positive if `s` is nonempty. It calls `Mathlib.Meta.proveFinsetNonempty` to attempt proving that the finset is nonempty. -/ @[positivity Finset.card _] def evalFinsetCard : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Finset.card $s) => let some ps ← proveFinsetNonempty s | return .none assertInstancesCommute return .positive q(Finset.Nonempty.card_pos $ps) | _ => throwError "not Finset.card" /-- Extension for `Fintype.card`. `Fintype.card α` is positive if `α` is nonempty. -/ @[positivity Fintype.card _] def evalFintypeCard : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(@Fintype.card $β $instβ) => let instβno ← synthInstanceQ q(Nonempty $β) assumeInstancesCommute return .positive q(@Fintype.card_pos $β $instβ $instβno) | _ => throwError "not Fintype.card" /-- Extension for `Finset.dens`. `s.card` is positive if `s` is nonempty. It calls `Mathlib.Meta.proveFinsetNonempty` to attempt proving that the finset is nonempty. -/ @[positivity Finset.dens _] def evalFinsetDens : PositivityExt where eval {u 𝕜} _ _ e := do match u, 𝕜, e with | 0, ~q(ℚ≥0), ~q(@Finset.dens $α $instα $s) => let some ps ← proveFinsetNonempty s | return .none assumeInstancesCommute return .positive q(@Nonempty.dens_pos $α $instα $s $ps) | _, _, _ => throwError "not Finset.dens" variable {α : Type*} {s : Finset α} example : 0 ≤ s.card := by positivity example (hs : s.Nonempty) : 0 < s.card := by positivity variable [Fintype α] example : 0 ≤ Fintype.card α := by positivity example : 0 ≤ dens s := by positivity example (hs : s.Nonempty) : 0 < dens s := by positivity example (hs : s.Nonempty) : dens s ≠ 0 := by positivity example [Nonempty α] : 0 < (univ : Finset α).card := by positivity example [Nonempty α] : 0 < Fintype.card α := by positivity example [Nonempty α] : 0 < dens (univ : Finset α) := by positivity example [Nonempty α] : dens (univ : Finset α) ≠ 0 := by positivity example {G : Type*} {A : Finset G} : let f := fun _ : G ↦ 1; (∀ s, f s ^ 2 = 1) → 0 ≤ A.card := by intros positivity -- Should succeed despite failing to prove `A` is nonempty. end Mathlib.Meta.Positivity
Tactic\ReduceModChar\Ext.lean
/- Copyright (c) 2023 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Lean.Meta.Tactic.Simp.Attr /-! # `@[reduce_mod_char]` attribute This file registers `@[reduce_mod_char]` as a `simp` attribute. -/ open Lean Meta /-- `@[reduce_mod_char]` is an attribute that tags lemmas for preprocessing and cleanup in the `reduce_mod_char` tactic -/ initialize reduceModCharExt : SimpExtension ← registerSimpAttr `reduce_mod_char "lemmas for preprocessing and cleanup in the `reduce_mod_char` tactic"
Tactic\Relation\Rfl.lean
/- Copyright (c) 2022 Newell Jensen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Newell Jensen -/ import Lean.Meta.Tactic.Rfl /-! # `Lean.MVarId.liftReflToEq` Convert a goal of the form `x ~ y` into the form `x = y`, where `~` is a reflexive relation, that is, a relation which has a reflexive lemma tagged with the attribute `[refl]`. If this can't be done, returns the original `MVarId`. -/ namespace Mathlib.Tactic open Lean Meta Elab Tactic Rfl /-- This tactic applies to a goal whose target has the form `x ~ x`, where `~` is a reflexive relation, that is, a relation which has a reflexive lemma tagged with the attribute [refl]. -/ def rflTac : TacticM Unit := withMainContext do liftMetaFinishingTactic (·.applyRfl) /-- If `e` is the form `@R .. x y`, where `R` is a reflexive relation, return `some (R, x, y)`. As a special case, if `e` is `@HEq α a β b`, return ``some (`HEq, a, b)``. -/ def _root_.Lean.Expr.relSidesIfRefl? (e : Expr) : MetaM (Option (Name × Expr × Expr)) := do if let some (_, lhs, rhs) := e.eq? then return (``Eq, lhs, rhs) if let some (lhs, rhs) := e.iff? then return (``Iff, lhs, rhs) if let some (_, lhs, _, rhs) := e.heq? then return (``HEq, lhs, rhs) if let .app (.app rel lhs) rhs := e then unless (← (reflExt.getState (← getEnv)).getMatch rel reflExt.config).isEmpty do match rel.getAppFn.constName? with | some n => return some (n, lhs, rhs) | none => return none return none
Tactic\Relation\Symm.lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Lean.Meta.Tactic.Symm /-! # `relSidesIfSymm?` -/ open Lean Meta Symm namespace Mathlib.Tactic open Lean.Elab.Tactic /-- If `e` is the form `@R .. x y`, where `R` is a symmetric relation, return `some (R, x, y)`. As a special case, if `e` is `@HEq α a β b`, return ``some (`HEq, a, b)``. -/ def _root_.Lean.Expr.relSidesIfSymm? (e : Expr) : MetaM (Option (Name × Expr × Expr)) := do if let some (_, lhs, rhs) := e.eq? then return (``Eq, lhs, rhs) if let some (lhs, rhs) := e.iff? then return (``Iff, lhs, rhs) if let some (_, lhs, _, rhs) := e.heq? then return (``HEq, lhs, rhs) if let .app (.app rel lhs) rhs := e then unless (← (symmExt.getState (← getEnv)).getMatch rel symmExt.config).isEmpty do match rel.getAppFn.constName? with | some n => return some (n, lhs, rhs) | none => return none return none
Tactic\Relation\Trans.lean
/- Copyright (c) 2022 Siddhartha Gadgil. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Siddhartha Gadgil, Mario Carneiro -/ import Mathlib.Lean.Meta import Mathlib.Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm import Mathlib.Tactic.TypeStar /-! # `trans` tactic This implements the `trans` tactic, which can apply transitivity theorems with an optional middle variable argument. -/ namespace Mathlib.Tactic open Lean Meta Elab initialize registerTraceClass `Tactic.trans /-- Discrimation tree settings for the `trans` extension. -/ def transExt.config : WhnfCoreConfig := {} /-- Environment extension storing transitivity lemmas -/ initialize transExt : SimpleScopedEnvExtension (Name × Array DiscrTree.Key) (DiscrTree Name) ← registerSimpleScopedEnvExtension { addEntry := fun dt (n, ks) ↦ dt.insertCore ks n initial := {} } initialize registerBuiltinAttribute { name := `trans descr := "transitive relation" add := fun decl _ kind ↦ MetaM.run' do let declTy := (← getConstInfo decl).type let (xs, _, targetTy) ← withReducible <| forallMetaTelescopeReducing declTy let fail := throwError "@[trans] attribute only applies to lemmas proving x ∼ y → y ∼ z → x ∼ z, got {indentExpr declTy} with target {indentExpr targetTy}" let .app (.app rel _) _ := targetTy | fail let some yzHyp := xs.back? | fail let some xyHyp := xs.pop.back? | fail let .app (.app _ _) _ ← inferType yzHyp | fail let .app (.app _ _) _ ← inferType xyHyp | fail let key ← withReducible <| DiscrTree.mkPath rel transExt.config transExt.add (decl, key) kind } universe u v in /-- Composition using the `Trans` class in the homogeneous case. -/ def _root_.Trans.simple {α : Sort u} {r : α → α → Sort v} {a b c : α} [Trans r r r] : r a b → r b c → r a c := trans universe u v w in /-- Composition using the `Trans` class in the general case. -/ def _root_.Trans.het {α β γ : Sort*} {a : α} {b : β} {c : γ} {r : α → β → Sort u} {s : β → γ → Sort v} {t : outParam (α → γ → Sort w)} [Trans r s t] : r a b → s b c → t a c := trans open Lean.Elab.Tactic /-- solving `e ← mkAppM' f #[x]` -/ def getExplicitFuncArg? (e : Expr) : MetaM (Option <| Expr × Expr) := do match e with | Expr.app f a => do if ← isDefEq (← mkAppM' f #[a]) e then return some (f, a) else getExplicitFuncArg? f | _ => return none /-- solving `tgt ← mkAppM' rel #[x, z]` given `tgt = f z` -/ def getExplicitRelArg? (tgt f z : Expr) : MetaM (Option <| Expr × Expr) := do match f with | Expr.app rel x => do let check: Bool ← do try let folded ← mkAppM' rel #[x, z] isDefEq folded tgt catch _ => pure false if check then return some (rel, x) else getExplicitRelArg? tgt rel z | _ => return none /-- refining `tgt ← mkAppM' rel #[x, z]` dropping more arguments if possible -/ def getExplicitRelArgCore (tgt rel x z : Expr) : MetaM (Expr × Expr) := do match rel with | Expr.app rel' _ => do let check: Bool ← do try let folded ← mkAppM' rel' #[x, z] isDefEq folded tgt catch _ => pure false if !check then return (rel, x) else getExplicitRelArgCore tgt rel' x z | _ => return (rel ,x) /-- Internal definition for `trans` tactic. Either a binary relation or a non-dependent arrow. -/ inductive TransRelation | app (rel : Expr) | implies (name : Name) (bi : BinderInfo) /-- Finds an explicit binary relation in the argument, if possible. -/ def getRel (tgt : Expr) : MetaM (Option (TransRelation × Expr × Expr)) := do match tgt with | .forallE name binderType body info => return .some (.implies name info, binderType, body) | .app f z => match (← getExplicitRelArg? tgt f z) with | some (rel, x) => let (rel, x) ← getExplicitRelArgCore tgt rel x z return some (.app rel, x, z) | none => return none | _ => return none /-- `trans` applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute [trans]. * `trans s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. * If `s` is omitted, then a metavariable is used instead. Additionally, `trans` also applies to a goal whose target has the form `t → u`, in which case it replaces the goal with `t → s` and `s → u`. -/ elab "trans" t?:(ppSpace colGt term)? : tactic => withMainContext do let tgt ← getMainTarget'' let .some (rel, x, z) ← getRel tgt | throwError (m!"transitivity lemmas only apply to binary relations and " ++ m!"non-dependent arrows, not {indentExpr tgt}") match rel with | .implies name info => -- only consider non-dependent arrows if z.hasLooseBVars then throwError "`trans` is not implemented for dependent arrows{indentExpr tgt}" -- parse the intermeditate term let middleType ← mkFreshExprMVar none let t'? ← t?.mapM (elabTermWithHoles · middleType (← getMainTag)) let middle ← (t'?.map (pure ·.1)).getD (mkFreshExprMVar middleType) liftMetaTactic fun goal => do -- create two new goals let g₁ ← mkFreshExprMVar (some <| .forallE name x middle info) .synthetic let g₂ ← mkFreshExprMVar (some <| .forallE name middle z info) .synthetic -- close the original goal with `fun x => g₂ (g₁ x)` goal.assign (.lam name x (.app g₂ (.app g₁ (.bvar 0))) .default) pure <| [g₁.mvarId!, g₂.mvarId!] ++ if let some (_, gs') := t'? then gs' else [middle.mvarId!] return | .app rel => trace[Tactic.trans]"goal decomposed" trace[Tactic.trans]"rel: {indentExpr rel}" trace[Tactic.trans]"x: {indentExpr x}" trace[Tactic.trans]"z: {indentExpr z}" -- first trying the homogeneous case try let ty ← inferType x let t'? ← t?.mapM (elabTermWithHoles · ty (← getMainTag)) let s ← saveState trace[Tactic.trans]"trying homogeneous case" let lemmas := (← (transExt.getState (← getEnv)).getUnify rel transExt.config).push ``Trans.simple for lem in lemmas do trace[Tactic.trans]"trying lemma {lem}" try liftMetaTactic fun g ↦ do let lemTy ← inferType (← mkConstWithLevelParams lem) let arity ← withReducible <| forallTelescopeReducing lemTy fun es _ ↦ pure es.size let y ← (t'?.map (pure ·.1)).getD (mkFreshExprMVar ty) let g₁ ← mkFreshExprMVar (some <| ← mkAppM' rel #[x, y]) .synthetic let g₂ ← mkFreshExprMVar (some <| ← mkAppM' rel #[y, z]) .synthetic g.assign (← mkAppOptM lem (mkArray (arity - 2) none ++ #[some g₁, some g₂])) pure <| [g₁.mvarId!, g₂.mvarId!] ++ if let some (_, gs') := t'? then gs' else [y.mvarId!] return catch _ => s.restore pure () catch _ => trace[Tactic.trans]"trying heterogeneous case" let t'? ← t?.mapM (elabTermWithHoles · none (← getMainTag)) let s ← saveState for lem in (← (transExt.getState (← getEnv)).getUnify rel transExt.config).push ``HEq.trans |>.push ``HEq.trans do try liftMetaTactic fun g ↦ do trace[Tactic.trans]"trying lemma {lem}" let lemTy ← inferType (← mkConstWithLevelParams lem) let arity ← withReducible <| forallTelescopeReducing lemTy fun es _ ↦ pure es.size trace[Tactic.trans]"arity: {arity}" trace[Tactic.trans]"lemma-type: {lemTy}" let y ← (t'?.map (pure ·.1)).getD (mkFreshExprMVar none) trace[Tactic.trans]"obtained y: {y}" trace[Tactic.trans]"rel: {indentExpr rel}" trace[Tactic.trans]"x:{indentExpr x}" trace[Tactic.trans]"z: {indentExpr z}" let g₂ ← mkFreshExprMVar (some <| ← mkAppM' rel #[y, z]) .synthetic trace[Tactic.trans]"obtained g₂: {g₂}" let g₁ ← mkFreshExprMVar (some <| ← mkAppM' rel #[x, y]) .synthetic trace[Tactic.trans]"obtained g₁: {g₁}" g.assign (← mkAppOptM lem (mkArray (arity - 2) none ++ #[some g₁, some g₂])) pure <| [g₁.mvarId!, g₂.mvarId!] ++ if let some (_, gs') := t'? then gs' else [y.mvarId!] return catch e => trace[Tactic.trans]"failed: {e.toMessageData}" s.restore throwError m!"no applicable transitivity lemma found for {indentExpr tgt}" syntax "transitivity" (ppSpace colGt term)? : tactic set_option hygiene false in macro_rules | `(tactic| transitivity) => `(tactic| trans) | `(tactic| transitivity $e) => `(tactic| trans $e)
Tactic\Ring\Basic.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Aurélien Saue, Anne Baanen -/ import Mathlib.Algebra.Order.Ring.Rat import Mathlib.Tactic.NormNum.Inv import Mathlib.Tactic.NormNum.Pow import Mathlib.Util.AtomM /-! # `ring` tactic A tactic for solving equations in commutative (semi)rings, where the exponents can also contain variables. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . More precisely, expressions of the following form are supported: - constants (non-negative integers) - variables - coefficients (any rational number, embedded into the (semi)ring) - addition of expressions - multiplication of expressions (`a * b`) - scalar multiplication of expressions (`n • a`; the multiplier must have type `ℕ`) - exponentiation of expressions (the exponent must have type `ℕ`) - subtraction and negation of expressions (if the base is a full ring) The extension to exponents means that something like `2 * 2^n * b = b * 2^(n+1)` can be proved, even though it is not strictly speaking an equation in the language of commutative rings. ## Implementation notes The basic approach to prove equalities is to normalise both sides and check for equality. The normalisation is guided by building a value in the type `ExSum` at the meta level, together with a proof (at the base level) that the original value is equal to the normalised version. The outline of the file: - Define a mutual inductive family of types `ExSum`, `ExProd`, `ExBase`, which can represent expressions with `+`, `*`, `^` and rational numerals. The mutual induction ensures that associativity and distributivity are applied, by restricting which kinds of subexpressions appear as arguments to the various operators. - Represent addition, multiplication and exponentiation in the `ExSum` type, thus allowing us to map expressions to `ExSum` (the `eval` function drives this). We apply associativity and distributivity of the operators here (helped by `Ex*` types) and commutativity as well (by sorting the subterms; unfortunately not helped by anything). Any expression not of the above formats is treated as an atom (the same as a variable). There are some details we glossed over which make the plan more complicated: - The order on atoms is not initially obvious. We construct a list containing them in order of initial appearance in the expression, then use the index into the list as a key to order on. - For `pow`, the exponent must be a natural number, while the base can be any semiring `α`. We swap out operations for the base ring `α` with those for the exponent ring `ℕ` as soon as we deal with exponents. ## Caveats and future work The normalized form of an expression is the one that is useful for the tactic, but not as nice to read. To remedy this, the user-facing normalization calls `ringNFCore`. Subtraction cancels out identical terms, but division does not. That is: `a - a = 0 := by ring` solves the goal, but `a / a := 1 by ring` doesn't. Note that `0 / 0` is generally defined to be `0`, so division cancelling out is not true in general. Multiplication of powers can be simplified a little bit further: `2 ^ n * 2 ^ n = 4 ^ n := by ring` could be implemented in a similar way that `2 * a + 2 * a = 4 * a := by ring` already works. This feature wasn't needed yet, so it's not implemented yet. ## Tags ring, semiring, exponent, power -/ namespace Mathlib.Tactic namespace Ring open Mathlib.Meta Qq NormNum Lean.Meta AtomM open Lean (MetaM Expr mkRawNatLit) /-- A shortcut instance for `CommSemiring ℕ` used by ring. -/ def instCommSemiringNat : CommSemiring ℕ := inferInstance /-- A typed expression of type `CommSemiring ℕ` used when we are working on ring subexpressions of type `ℕ`. -/ def sℕ : Q(CommSemiring ℕ) := q(instCommSemiringNat) mutual /-- The base `e` of a normalized exponent expression. -/ inductive ExBase : ∀ {u : Lean.Level} {α : Q(Type u)}, Q(CommSemiring $α) → (e : Q($α)) → Type /-- An atomic expression `e` with id `id`. Atomic expressions are those which `ring` cannot parse any further. For instance, `a + (a % b)` has `a` and `(a % b)` as atoms. The `ring1` tactic does not normalize the subexpressions in atoms, but `ring_nf` does. Atoms in fact represent equivalence classes of expressions, modulo definitional equality. The field `index : ℕ` should be a unique number for each class, while `value : expr` contains a representative of this class. The function `resolve_atom` determines the appropriate atom for a given expression. -/ | atom {sα} {e} (id : ℕ) : ExBase sα e /-- A sum of monomials. -/ | sum {sα} {e} (_ : ExSum sα e) : ExBase sα e /-- A monomial, which is a product of powers of `ExBase` expressions, terminated by a (nonzero) constant coefficient. -/ inductive ExProd : ∀ {u : Lean.Level} {α : Q(Type u)}, Q(CommSemiring $α) → (e : Q($α)) → Type /-- A coefficient `value`, which must not be `0`. `e` is a raw rat cast. If `value` is not an integer, then `hyp` should be a proof of `(value.den : α) ≠ 0`. -/ | const {sα} {e} (value : ℚ) (hyp : Option Expr := none) : ExProd sα e /-- A product `x ^ e * b` is a monomial if `b` is a monomial. Here `x` is an `ExBase` and `e` is an `ExProd` representing a monomial expression in `ℕ` (it is a monomial instead of a polynomial because we eagerly normalize `x ^ (a + b) = x ^ a * x ^ b`.) -/ | mul {u : Lean.Level} {α : Q(Type u)} {sα} {x : Q($α)} {e : Q(ℕ)} {b : Q($α)} : ExBase sα x → ExProd sℕ e → ExProd sα b → ExProd sα q($x ^ $e * $b) /-- A polynomial expression, which is a sum of monomials. -/ inductive ExSum : ∀ {u : Lean.Level} {α : Q(Type u)}, Q(CommSemiring $α) → (e : Q($α)) → Type /-- Zero is a polynomial. `e` is the expression `0`. -/ | zero {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} : ExSum sα q(0 : $α) /-- A sum `a + b` is a polynomial if `a` is a monomial and `b` is another polynomial. -/ | add {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExProd sα a → ExSum sα b → ExSum sα q($a + $b) end -- In this file, we would like to use multi-character auto-implicits. set_option relaxedAutoImplicit true set_option autoImplicit true mutual -- partial only to speed up compilation /-- Equality test for expressions. This is not a `BEq` instance because it is heterogeneous. -/ partial def ExBase.eq : ExBase sα a → ExBase sα b → Bool | .atom i, .atom j => i == j | .sum a, .sum b => a.eq b | _, _ => false @[inherit_doc ExBase.eq] partial def ExProd.eq : ExProd sα a → ExProd sα b → Bool | .const i _, .const j _ => i == j | .mul a₁ a₂ a₃, .mul b₁ b₂ b₃ => a₁.eq b₁ && a₂.eq b₂ && a₃.eq b₃ | _, _ => false @[inherit_doc ExBase.eq] partial def ExSum.eq : ExSum sα a → ExSum sα b → Bool | .zero, .zero => true | .add a₁ a₂, .add b₁ b₂ => a₁.eq b₁ && a₂.eq b₂ | _, _ => false end mutual -- partial only to speed up compilation /-- A total order on normalized expressions. This is not an `Ord` instance because it is heterogeneous. -/ partial def ExBase.cmp : ExBase sα a → ExBase sα b → Ordering | .atom i, .atom j => compare i j | .sum a, .sum b => a.cmp b | .atom .., .sum .. => .lt | .sum .., .atom .. => .gt @[inherit_doc ExBase.cmp] partial def ExProd.cmp : ExProd sα a → ExProd sα b → Ordering | .const i _, .const j _ => compare i j | .mul a₁ a₂ a₃, .mul b₁ b₂ b₃ => (a₁.cmp b₁).then (a₂.cmp b₂) |>.then (a₃.cmp b₃) | .const _ _, .mul .. => .lt | .mul .., .const _ _ => .gt @[inherit_doc ExBase.cmp] partial def ExSum.cmp : ExSum sα a → ExSum sα b → Ordering | .zero, .zero => .eq | .add a₁ a₂, .add b₁ b₂ => (a₁.cmp b₁).then (a₂.cmp b₂) | .zero, .add .. => .lt | .add .., .zero => .gt end variable {u : Lean.Level} {arg : Q(Type u)} {sα : Q(CommSemiring $arg)} instance : Inhabited (Σ e, (ExBase sα) e) := ⟨default, .atom 0⟩ instance : Inhabited (Σ e, (ExSum sα) e) := ⟨_, .zero⟩ instance : Inhabited (Σ e, (ExProd sα) e) := ⟨default, .const 0 none⟩ mutual /-- Converts `ExBase sα` to `ExBase sβ`, assuming `sα` and `sβ` are defeq. -/ partial def ExBase.cast {a : Q($arg)} : ExBase sα a → Σ a, ExBase sβ a | .atom i => ⟨a, .atom i⟩ | .sum a => let ⟨_, vb⟩ := a.cast; ⟨_, .sum vb⟩ /-- Converts `ExProd sα` to `ExProd sβ`, assuming `sα` and `sβ` are defeq. -/ partial def ExProd.cast {a : Q($arg)} : ExProd sα a → Σ a, ExProd sβ a | .const i h => ⟨a, .const i h⟩ | .mul a₁ a₂ a₃ => ⟨_, .mul a₁.cast.2 a₂ a₃.cast.2⟩ /-- Converts `ExSum sα` to `ExSum sβ`, assuming `sα` and `sβ` are defeq. -/ partial def ExSum.cast {a : Q($arg)} : ExSum sα a → Σ a, ExSum sβ a | .zero => ⟨_, .zero⟩ | .add a₁ a₂ => ⟨_, .add a₁.cast.2 a₂.cast.2⟩ end set_option autoImplicit false set_option relaxedAutoImplicit false variable {u : Lean.Level} /-- The result of evaluating an (unnormalized) expression `e` into the type family `E` (one of `ExSum`, `ExProd`, `ExBase`) is a (normalized) element `e'` and a representation `E e'` for it, and a proof of `e = e'`. -/ structure Result {α : Q(Type u)} (E : Q($α) → Type) (e : Q($α)) where /-- The normalized result. -/ expr : Q($α) /-- The data associated to the normalization. -/ val : E expr /-- A proof that the original expression is equal to the normalized result. -/ proof : Q($e = $expr) instance {α : Q(Type u)} {E : Q($α) → Type} {e : Q($α)} [Inhabited (Σ e, E e)] : Inhabited (Result E e) := let ⟨e', v⟩ : Σ e, E e := default; ⟨e', v, default⟩ variable {α : Q(Type u)} (sα : Q(CommSemiring $α)) {R : Type*} [CommSemiring R] /-- Constructs the expression corresponding to `.const n`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkNat (n : ℕ) : (e : Q($α)) × ExProd sα e := let lit : Q(ℕ) := mkRawNatLit n ⟨q(($lit).rawCast : $α), .const n none⟩ /-- Constructs the expression corresponding to `.const (-n)`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkNegNat (_ : Q(Ring $α)) (n : ℕ) : (e : Q($α)) × ExProd sα e := let lit : Q(ℕ) := mkRawNatLit n ⟨q((Int.negOfNat $lit).rawCast : $α), .const (-n) none⟩ /-- Constructs the expression corresponding to `.const (-n)`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkRat (_ : Q(DivisionRing $α)) (q : ℚ) (n : Q(ℤ)) (d : Q(ℕ)) (h : Expr) : (e : Q($α)) × ExProd sα e := ⟨q(Rat.rawCast $n $d : $α), .const q h⟩ section /-- Embed an exponent (an `ExBase, ExProd` pair) as an `ExProd` by multiplying by 1. -/ def ExBase.toProd {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a : Q($α)} {b : Q(ℕ)} (va : ExBase sα a) (vb : ExProd sℕ b) : ExProd sα q($a ^ $b * (nat_lit 1).rawCast) := .mul va vb (.const 1 none) /-- Embed `ExProd` in `ExSum` by adding 0. -/ def ExProd.toSum {sα : Q(CommSemiring $α)} {e : Q($α)} (v : ExProd sα e) : ExSum sα q($e + 0) := .add v .zero /-- Get the leading coefficient of an `ExProd`. -/ def ExProd.coeff {sα : Q(CommSemiring $α)} {e : Q($α)} : ExProd sα e → ℚ | .const q _ => q | .mul _ _ v => v.coeff end /-- Two monomials are said to "overlap" if they differ by a constant factor, in which case the constants just add. When this happens, the constant may be either zero (if the monomials cancel) or nonzero (if they add up); the zero case is handled specially. -/ inductive Overlap (e : Q($α)) where /-- The expression `e` (the sum of monomials) is equal to `0`. -/ | zero (_ : Q(IsNat $e (nat_lit 0))) /-- The expression `e` (the sum of monomials) is equal to another monomial (with nonzero leading coefficient). -/ | nonzero (_ : Result (ExProd sα) e) variable {a a' a₁ a₂ a₃ b b' b₁ b₂ b₃ c c₁ c₂ : R} theorem add_overlap_pf (x : R) (e) (pq_pf : a + b = c) : x ^ e * a + x ^ e * b = x ^ e * c := by subst_vars; simp [mul_add] theorem add_overlap_pf_zero (x : R) (e) : IsNat (a + b) (nat_lit 0) → IsNat (x ^ e * a + x ^ e * b) (nat_lit 0) | ⟨h⟩ => ⟨by simp [h, ← mul_add]⟩ /-- Given monomials `va, vb`, attempts to add them together to get another monomial. If the monomials are not compatible, returns `none`. For example, `xy + 2xy = 3xy` is a `.nonzero` overlap, while `xy + xz` returns `none` and `xy + -xy = 0` is a `.zero` overlap. -/ def evalAddOverlap {a b : Q($α)} (va : ExProd sα a) (vb : ExProd sα b) : Option (Overlap sα q($a + $b)) := match va, vb with | .const za ha, .const zb hb => do let ra := Result.ofRawRat za a ha; let rb := Result.ofRawRat zb b hb let res ← NormNum.evalAdd.core q($a + $b) q(HAdd.hAdd) a b ra rb match res with | .isNat _ (.lit (.natVal 0)) p => pure <| .zero p | rc => let ⟨zc, hc⟩ ← rc.toRatNZ let ⟨c, pc⟩ := rc.toRawEq pure <| .nonzero ⟨c, .const zc hc, pc⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃, .mul vb₁ vb₂ vb₃ => do guard (va₁.eq vb₁ && va₂.eq vb₂) match ← evalAddOverlap va₃ vb₃ with | .zero p => pure <| .zero (q(add_overlap_pf_zero $a₁ $a₂ $p) : Expr) | .nonzero ⟨_, vc, p⟩ => pure <| .nonzero ⟨_, .mul va₁ va₂ vc, (q(add_overlap_pf $a₁ $a₂ $p) : Expr)⟩ | _, _ => none theorem add_pf_zero_add (b : R) : 0 + b = b := by simp theorem add_pf_add_zero (a : R) : a + 0 = a := by simp theorem add_pf_add_overlap (_ : a₁ + b₁ = c₁) (_ : a₂ + b₂ = c₂) : (a₁ + a₂ : R) + (b₁ + b₂) = c₁ + c₂ := by subst_vars; simp [add_assoc, add_left_comm] theorem add_pf_add_overlap_zero (h : IsNat (a₁ + b₁) (nat_lit 0)) (h₄ : a₂ + b₂ = c) : (a₁ + a₂ : R) + (b₁ + b₂) = c := by subst_vars; rw [add_add_add_comm, h.1, Nat.cast_zero, add_pf_zero_add] theorem add_pf_add_lt (a₁ : R) (_ : a₂ + b = c) : (a₁ + a₂) + b = a₁ + c := by simp [*, add_assoc] theorem add_pf_add_gt (b₁ : R) (_ : a + b₂ = c) : a + (b₁ + b₂) = b₁ + c := by subst_vars; simp [add_left_comm] /-- Adds two polynomials `va, vb` together to get a normalized result polynomial. * `0 + b = b` * `a + 0 = a` * `a * x + a * y = a * (x + y)` (for `x`, `y` coefficients; uses `evalAddOverlap`) * `(a₁ + a₂) + (b₁ + b₂) = a₁ + (a₂ + (b₁ + b₂))` (if `a₁.lt b₁`) * `(a₁ + a₂) + (b₁ + b₂) = b₁ + ((a₁ + a₂) + b₂)` (if not `a₁.lt b₁`) -/ partial def evalAdd {a b : Q($α)} (va : ExSum sα a) (vb : ExSum sα b) : Result (ExSum sα) q($a + $b) := match va, vb with | .zero, vb => ⟨b, vb, q(add_pf_zero_add $b)⟩ | va, .zero => ⟨a, va, q(add_pf_add_zero $a)⟩ | .add (a := a₁) (b := _a₂) va₁ va₂, .add (a := b₁) (b := _b₂) vb₁ vb₂ => match evalAddOverlap sα va₁ vb₁ with | some (.nonzero ⟨_, vc₁, pc₁⟩) => let ⟨_, vc₂, pc₂⟩ := evalAdd va₂ vb₂ ⟨_, .add vc₁ vc₂, q(add_pf_add_overlap $pc₁ $pc₂)⟩ | some (.zero pc₁) => let ⟨c₂, vc₂, pc₂⟩ := evalAdd va₂ vb₂ ⟨c₂, vc₂, q(add_pf_add_overlap_zero $pc₁ $pc₂)⟩ | none => if let .lt := va₁.cmp vb₁ then let ⟨_c, vc, (pc : Q($_a₂ + ($b₁ + $_b₂) = $_c))⟩ := evalAdd va₂ vb ⟨_, .add va₁ vc, q(add_pf_add_lt $a₁ $pc)⟩ else let ⟨_c, vc, (pc : Q($a₁ + $_a₂ + $_b₂ = $_c))⟩ := evalAdd va vb₂ ⟨_, .add vb₁ vc, q(add_pf_add_gt $b₁ $pc)⟩ theorem one_mul (a : R) : (nat_lit 1).rawCast * a = a := by simp [Nat.rawCast] theorem mul_one (a : R) : a * (nat_lit 1).rawCast = a := by simp [Nat.rawCast] theorem mul_pf_left (a₁ : R) (a₂) (_ : a₃ * b = c) : (a₁ ^ a₂ * a₃ : R) * b = a₁ ^ a₂ * c := by subst_vars; rw [mul_assoc] theorem mul_pf_right (b₁ : R) (b₂) (_ : a * b₃ = c) : a * (b₁ ^ b₂ * b₃) = b₁ ^ b₂ * c := by subst_vars; rw [mul_left_comm] theorem mul_pp_pf_overlap {ea eb e : ℕ} (x : R) (_ : ea + eb = e) (_ : a₂ * b₂ = c) : (x ^ ea * a₂ : R) * (x ^ eb * b₂) = x ^ e * c := by subst_vars; simp [pow_add, mul_mul_mul_comm] /-- Multiplies two monomials `va, vb` together to get a normalized result monomial. * `x * y = (x * y)` (for `x`, `y` coefficients) * `x * (b₁ * b₂) = b₁ * (b₂ * x)` (for `x` coefficient) * `(a₁ * a₂) * y = a₁ * (a₂ * y)` (for `y` coefficient) * `(x ^ ea * a₂) * (x ^ eb * b₂) = x ^ (ea + eb) * (a₂ * b₂)` (if `ea` and `eb` are identical except coefficient) * `(a₁ * a₂) * (b₁ * b₂) = a₁ * (a₂ * (b₁ * b₂))` (if `a₁.lt b₁`) * `(a₁ * a₂) * (b₁ * b₂) = b₁ * ((a₁ * a₂) * b₂)` (if not `a₁.lt b₁`) -/ partial def evalMulProd {a b : Q($α)} (va : ExProd sα a) (vb : ExProd sα b) : Result (ExProd sα) q($a * $b) := match va, vb with | .const za ha, .const zb hb => if za = 1 then ⟨b, .const zb hb, (q(one_mul $b) : Expr)⟩ else if zb = 1 then ⟨a, .const za ha, (q(mul_one $a) : Expr)⟩ else let ra := Result.ofRawRat za a ha; let rb := Result.ofRawRat zb b hb let rc := (NormNum.evalMul.core q($a * $b) q(HMul.hMul) _ _ q(CommSemiring.toSemiring) ra rb).get! let ⟨zc, hc⟩ := rc.toRatNZ.get! let ⟨c, pc⟩ := rc.toRawEq ⟨c, .const zc hc, pc⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃, .const _ _ => let ⟨_, vc, pc⟩ := evalMulProd va₃ vb ⟨_, .mul va₁ va₂ vc, (q(mul_pf_left $a₁ $a₂ $pc) : Expr)⟩ | .const _ _, .mul (x := b₁) (e := b₂) vb₁ vb₂ vb₃ => let ⟨_, vc, pc⟩ := evalMulProd va vb₃ ⟨_, .mul vb₁ vb₂ vc, (q(mul_pf_right $b₁ $b₂ $pc) : Expr)⟩ | .mul (x := xa) (e := ea) vxa vea va₂, .mul (x := xb) (e := eb) vxb veb vb₂ => Id.run do if vxa.eq vxb then if let some (.nonzero ⟨_, ve, pe⟩) := evalAddOverlap sℕ vea veb then let ⟨_, vc, pc⟩ := evalMulProd va₂ vb₂ return ⟨_, .mul vxa ve vc, (q(mul_pp_pf_overlap $xa $pe $pc) : Expr)⟩ if let .lt := (vxa.cmp vxb).then (vea.cmp veb) then let ⟨_, vc, pc⟩ := evalMulProd va₂ vb ⟨_, .mul vxa vea vc, (q(mul_pf_left $xa $ea $pc) : Expr)⟩ else let ⟨_, vc, pc⟩ := evalMulProd va vb₂ ⟨_, .mul vxb veb vc, (q(mul_pf_right $xb $eb $pc) : Expr)⟩ theorem mul_zero (a : R) : a * 0 = 0 := by simp theorem mul_add {d : R} (_ : (a : R) * b₁ = c₁) (_ : a * b₂ = c₂) (_ : c₁ + 0 + c₂ = d) : a * (b₁ + b₂) = d := by subst_vars; simp [_root_.mul_add] /-- Multiplies a monomial `va` to a polynomial `vb` to get a normalized result polynomial. * `a * 0 = 0` * `a * (b₁ + b₂) = (a * b₁) + (a * b₂)` -/ def evalMul₁ {a b : Q($α)} (va : ExProd sα a) (vb : ExSum sα b) : Result (ExSum sα) q($a * $b) := match vb with | .zero => ⟨_, .zero, q(mul_zero $a)⟩ | .add vb₁ vb₂ => let ⟨_, vc₁, pc₁⟩ := evalMulProd sα va vb₁ let ⟨_, vc₂, pc₂⟩ := evalMul₁ va vb₂ let ⟨_, vd, pd⟩ := evalAdd sα vc₁.toSum vc₂ ⟨_, vd, q(mul_add $pc₁ $pc₂ $pd)⟩ theorem zero_mul (b : R) : 0 * b = 0 := by simp theorem add_mul {d : R} (_ : (a₁ : R) * b = c₁) (_ : a₂ * b = c₂) (_ : c₁ + c₂ = d) : (a₁ + a₂) * b = d := by subst_vars; simp [_root_.add_mul] /-- Multiplies two polynomials `va, vb` together to get a normalized result polynomial. * `0 * b = 0` * `(a₁ + a₂) * b = (a₁ * b) + (a₂ * b)` -/ def evalMul {a b : Q($α)} (va : ExSum sα a) (vb : ExSum sα b) : Result (ExSum sα) q($a * $b) := match va with | .zero => ⟨_, .zero, q(zero_mul $b)⟩ | .add va₁ va₂ => let ⟨_, vc₁, pc₁⟩ := evalMul₁ sα va₁ vb let ⟨_, vc₂, pc₂⟩ := evalMul va₂ vb let ⟨_, vd, pd⟩ := evalAdd sα vc₁ vc₂ ⟨_, vd, q(add_mul $pc₁ $pc₂ $pd)⟩ theorem natCast_nat (n) : ((Nat.rawCast n : ℕ) : R) = Nat.rawCast n := by simp theorem natCast_mul {a₁ a₃ : ℕ} (a₂) (_ : ((a₁ : ℕ) : R) = b₁) (_ : ((a₃ : ℕ) : R) = b₃) : ((a₁ ^ a₂ * a₃ : ℕ) : R) = b₁ ^ a₂ * b₃ := by subst_vars; simp theorem natCast_zero : ((0 : ℕ) : R) = 0 := Nat.cast_zero theorem natCast_add {a₁ a₂ : ℕ} (_ : ((a₁ : ℕ) : R) = b₁) (_ : ((a₂ : ℕ) : R) = b₂) : ((a₁ + a₂ : ℕ) : R) = b₁ + b₂ := by subst_vars; simp mutual /-- Applies `Nat.cast` to a nat polynomial to produce a polynomial in `α`. * An atom `e` causes `↑e` to be allocated as a new atom. * A sum delegates to `ExSum.evalNatCast`. -/ partial def ExBase.evalNatCast {a : Q(ℕ)} (va : ExBase sℕ a) : AtomM (Result (ExBase sα) q($a)) := match va with | .atom _ => do let a' : Q($α) := q($a) let i ← addAtom a' pure ⟨a', ExBase.atom i, (q(Eq.refl $a') : Expr)⟩ | .sum va => do let ⟨_, vc, p⟩ ← va.evalNatCast pure ⟨_, .sum vc, p⟩ /-- Applies `Nat.cast` to a nat monomial to produce a monomial in `α`. * `↑c = c` if `c` is a numeric literal * `↑(a ^ n * b) = ↑a ^ n * ↑b` -/ partial def ExProd.evalNatCast {a : Q(ℕ)} (va : ExProd sℕ a) : AtomM (Result (ExProd sα) q($a)) := match va with | .const c hc => have n : Q(ℕ) := a.appArg! pure ⟨q(Nat.rawCast $n), .const c hc, (q(natCast_nat (R := $α) $n) : Expr)⟩ | .mul (e := a₂) va₁ va₂ va₃ => do let ⟨_, vb₁, pb₁⟩ ← va₁.evalNatCast let ⟨_, vb₃, pb₃⟩ ← va₃.evalNatCast pure ⟨_, .mul vb₁ va₂ vb₃, q(natCast_mul $a₂ $pb₁ $pb₃)⟩ /-- Applies `Nat.cast` to a nat polynomial to produce a polynomial in `α`. * `↑0 = 0` * `↑(a + b) = ↑a + ↑b` -/ partial def ExSum.evalNatCast {a : Q(ℕ)} (va : ExSum sℕ a) : AtomM (Result (ExSum sα) q($a)) := match va with | .zero => pure ⟨_, .zero, q(natCast_zero (R := $α))⟩ | .add va₁ va₂ => do let ⟨_, vb₁, pb₁⟩ ← va₁.evalNatCast let ⟨_, vb₂, pb₂⟩ ← va₂.evalNatCast pure ⟨_, .add vb₁ vb₂, q(natCast_add $pb₁ $pb₂)⟩ end theorem smul_nat {a b c : ℕ} (_ : (a * b : ℕ) = c) : a • b = c := by subst_vars; simp theorem smul_eq_cast {a : ℕ} (_ : ((a : ℕ) : R) = a') (_ : a' * b = c) : a • b = c := by subst_vars; simp /-- Constructs the scalar multiplication `n • a`, where both `n : ℕ` and `a : α` are normalized polynomial expressions. * `a • b = a * b` if `α = ℕ` * `a • b = ↑a * b` otherwise -/ def evalNSMul {a : Q(ℕ)} {b : Q($α)} (va : ExSum sℕ a) (vb : ExSum sα b) : AtomM (Result (ExSum sα) q($a • $b)) := do if ← isDefEq sα sℕ then let ⟨_, va'⟩ := va.cast have _b : Q(ℕ) := b let ⟨(_c : Q(ℕ)), vc, (pc : Q($a * $_b = $_c))⟩ := evalMul sα va' vb pure ⟨_, vc, (q(smul_nat $pc) : Expr)⟩ else let ⟨_, va', pa'⟩ ← va.evalNatCast sα let ⟨_, vc, pc⟩ := evalMul sα va' vb pure ⟨_, vc, (q(smul_eq_cast $pa' $pc) : Expr)⟩ theorem neg_one_mul {R} [Ring R] {a b : R} (_ : (Int.negOfNat (nat_lit 1)).rawCast * a = b) : -a = b := by subst_vars; simp [Int.negOfNat] theorem neg_mul {R} [Ring R] (a₁ : R) (a₂) {a₃ b : R} (_ : -a₃ = b) : -(a₁ ^ a₂ * a₃) = a₁ ^ a₂ * b := by subst_vars; simp /-- Negates a monomial `va` to get another monomial. * `-c = (-c)` (for `c` coefficient) * `-(a₁ * a₂) = a₁ * -a₂` -/ def evalNegProd {a : Q($α)} (rα : Q(Ring $α)) (va : ExProd sα a) : Result (ExProd sα) q(-$a) := match va with | .const za ha => let lit : Q(ℕ) := mkRawNatLit 1 let ⟨m1, _⟩ := ExProd.mkNegNat sα rα 1 let rm := Result.isNegNat rα lit (q(IsInt.of_raw $α (.negOfNat $lit)) : Expr) let ra := Result.ofRawRat za a ha let rb := (NormNum.evalMul.core q($m1 * $a) q(HMul.hMul) _ _ q(CommSemiring.toSemiring) rm ra).get! let ⟨zb, hb⟩ := rb.toRatNZ.get! let ⟨b, (pb : Q((Int.negOfNat (nat_lit 1)).rawCast * $a = $b))⟩ := rb.toRawEq ⟨b, .const zb hb, (q(neg_one_mul (R := $α) $pb) : Expr)⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃ => let ⟨_, vb, pb⟩ := evalNegProd rα va₃ ⟨_, .mul va₁ va₂ vb, (q(neg_mul $a₁ $a₂ $pb) : Expr)⟩ theorem neg_zero {R} [Ring R] : -(0 : R) = 0 := by simp theorem neg_add {R} [Ring R] {a₁ a₂ b₁ b₂ : R} (_ : -a₁ = b₁) (_ : -a₂ = b₂) : -(a₁ + a₂) = b₁ + b₂ := by subst_vars; simp [add_comm] /-- Negates a polynomial `va` to get another polynomial. * `-0 = 0` (for `c` coefficient) * `-(a₁ + a₂) = -a₁ + -a₂` -/ def evalNeg {a : Q($α)} (rα : Q(Ring $α)) (va : ExSum sα a) : Result (ExSum sα) q(-$a) := match va with | .zero => ⟨_, .zero, (q(neg_zero (R := $α)) : Expr)⟩ | .add va₁ va₂ => let ⟨_, vb₁, pb₁⟩ := evalNegProd sα rα va₁ let ⟨_, vb₂, pb₂⟩ := evalNeg rα va₂ ⟨_, .add vb₁ vb₂, (q(neg_add $pb₁ $pb₂) : Expr)⟩ theorem sub_pf {R} [Ring R] {a b c d : R} (_ : -b = c) (_ : a + c = d) : a - b = d := by subst_vars; simp [sub_eq_add_neg] /-- Subtracts two polynomials `va, vb` to get a normalized result polynomial. * `a - b = a + -b` -/ def evalSub {α : Q(Type u)} (sα : Q(CommSemiring $α)) {a b : Q($α)} (rα : Q(Ring $α)) (va : ExSum sα a) (vb : ExSum sα b) : Result (ExSum sα) q($a - $b) := let ⟨_c, vc, pc⟩ := evalNeg sα rα vb let ⟨d, vd, (pd : Q($a + $_c = $d))⟩ := evalAdd sα va vc ⟨d, vd, (q(sub_pf $pc $pd) : Expr)⟩ theorem pow_prod_atom (a : R) (b) : a ^ b = (a + 0) ^ b * (nat_lit 1).rawCast := by simp /-- The fallback case for exponentiating polynomials is to use `ExBase.toProd` to just build an exponent expression. (This has a slightly different normalization than `evalPowAtom` because the input types are different.) * `x ^ e = (x + 0) ^ e * 1` -/ def evalPowProdAtom {a : Q($α)} {b : Q(ℕ)} (va : ExProd sα a) (vb : ExProd sℕ b) : Result (ExProd sα) q($a ^ $b) := ⟨_, (ExBase.sum va.toSum).toProd vb, q(pow_prod_atom $a $b)⟩ theorem pow_atom (a : R) (b) : a ^ b = a ^ b * (nat_lit 1).rawCast + 0 := by simp /-- The fallback case for exponentiating polynomials is to use `ExBase.toProd` to just build an exponent expression. * `x ^ e = x ^ e * 1 + 0` -/ def evalPowAtom {a : Q($α)} {b : Q(ℕ)} (va : ExBase sα a) (vb : ExProd sℕ b) : Result (ExSum sα) q($a ^ $b) := ⟨_, (va.toProd vb).toSum, q(pow_atom $a $b)⟩ theorem const_pos (n : ℕ) (h : Nat.ble 1 n = true) : 0 < (n.rawCast : ℕ) := Nat.le_of_ble_eq_true h theorem mul_exp_pos {a₁ a₂ : ℕ} (n) (h₁ : 0 < a₁) (h₂ : 0 < a₂) : 0 < a₁ ^ n * a₂ := Nat.mul_pos (Nat.pos_pow_of_pos _ h₁) h₂ theorem add_pos_left {a₁ : ℕ} (a₂) (h : 0 < a₁) : 0 < a₁ + a₂ := Nat.lt_of_lt_of_le h (Nat.le_add_right ..) theorem add_pos_right {a₂ : ℕ} (a₁) (h : 0 < a₂) : 0 < a₁ + a₂ := Nat.lt_of_lt_of_le h (Nat.le_add_left ..) mutual /-- Attempts to prove that a polynomial expression in `ℕ` is positive. * Atoms are not (necessarily) positive * Sums defer to `ExSum.evalPos` -/ partial def ExBase.evalPos {a : Q(ℕ)} (va : ExBase sℕ a) : Option Q(0 < $a) := match va with | .atom _ => none | .sum va => va.evalPos /-- Attempts to prove that a monomial expression in `ℕ` is positive. * `0 < c` (where `c` is a numeral) is true by the normalization invariant (`c` is not zero) * `0 < x ^ e * b` if `0 < x` and `0 < b` -/ partial def ExProd.evalPos {a : Q(ℕ)} (va : ExProd sℕ a) : Option Q(0 < $a) := match va with | .const _ _ => -- it must be positive because it is a nonzero nat literal have lit : Q(ℕ) := a.appArg! haveI : $a =Q Nat.rawCast $lit := ⟨⟩ haveI p : Nat.ble 1 $lit =Q true := ⟨⟩ some q(const_pos $lit $p) | .mul (e := ea₁) vxa₁ _ va₂ => do let pa₁ ← vxa₁.evalPos let pa₂ ← va₂.evalPos some q(mul_exp_pos $ea₁ $pa₁ $pa₂) /-- Attempts to prove that a polynomial expression in `ℕ` is positive. * `0 < 0` fails * `0 < a + b` if `0 < a` or `0 < b` -/ partial def ExSum.evalPos {a : Q(ℕ)} (va : ExSum sℕ a) : Option Q(0 < $a) := match va with | .zero => none | .add (a := a₁) (b := a₂) va₁ va₂ => do match va₁.evalPos with | some p => some q(add_pos_left $a₂ $p) | none => let p ← va₂.evalPos; some q(add_pos_right $a₁ $p) end theorem pow_one (a : R) : a ^ nat_lit 1 = a := by simp theorem pow_bit0 {k : ℕ} (_ : (a : R) ^ k = b) (_ : b * b = c) : a ^ (Nat.mul (nat_lit 2) k) = c := by subst_vars; simp [Nat.succ_mul, pow_add] theorem pow_bit1 {k : ℕ} {d : R} (_ : (a : R) ^ k = b) (_ : b * b = c) (_ : c * a = d) : a ^ (Nat.add (Nat.mul (nat_lit 2) k) (nat_lit 1)) = d := by subst_vars; simp [Nat.succ_mul, pow_add] /-- The main case of exponentiation of ring expressions is when `va` is a polynomial and `n` is a nonzero literal expression, like `(x + y)^5`. In this case we work out the polynomial completely into a sum of monomials. * `x ^ 1 = x` * `x ^ (2*n) = x ^ n * x ^ n` * `x ^ (2*n+1) = x ^ n * x ^ n * x` -/ partial def evalPowNat {a : Q($α)} (va : ExSum sα a) (n : Q(ℕ)) : Result (ExSum sα) q($a ^ $n) := let nn := n.natLit! if nn = 1 then ⟨_, va, (q(pow_one $a) : Expr)⟩ else let nm := nn >>> 1 have m : Q(ℕ) := mkRawNatLit nm if nn &&& 1 = 0 then let ⟨_, vb, pb⟩ := evalPowNat va m let ⟨_, vc, pc⟩ := evalMul sα vb vb ⟨_, vc, (q(pow_bit0 $pb $pc) : Expr)⟩ else let ⟨_, vb, pb⟩ := evalPowNat va m let ⟨_, vc, pc⟩ := evalMul sα vb vb let ⟨_, vd, pd⟩ := evalMul sα vc va ⟨_, vd, (q(pow_bit1 $pb $pc $pd) : Expr)⟩ theorem one_pow (b : ℕ) : ((nat_lit 1).rawCast : R) ^ b = (nat_lit 1).rawCast := by simp theorem mul_pow {ea₁ b c₁ : ℕ} {xa₁ : R} (_ : ea₁ * b = c₁) (_ : a₂ ^ b = c₂) : (xa₁ ^ ea₁ * a₂ : R) ^ b = xa₁ ^ c₁ * c₂ := by subst_vars; simp [_root_.mul_pow, pow_mul] /-- There are several special cases when exponentiating monomials: * `1 ^ n = 1` * `x ^ y = (x ^ y)` when `x` and `y` are constants * `(a * b) ^ e = a ^ e * b ^ e` In all other cases we use `evalPowProdAtom`. -/ def evalPowProd {a : Q($α)} {b : Q(ℕ)} (va : ExProd sα a) (vb : ExProd sℕ b) : Result (ExProd sα) q($a ^ $b) := let res : Option (Result (ExProd sα) q($a ^ $b)) := do match va, vb with | .const 1, _ => some ⟨_, va, (q(one_pow (R := $α) $b) : Expr)⟩ | .const za ha, .const zb hb => assert! 0 ≤ zb let ra := Result.ofRawRat za a ha have lit : Q(ℕ) := b.appArg! let rb := (q(IsNat.of_raw ℕ $lit) : Expr) let rc ← NormNum.evalPow.core q($a ^ $b) q(HPow.hPow) q($a) q($b) lit rb q(CommSemiring.toSemiring) ra let ⟨zc, hc⟩ ← rc.toRatNZ let ⟨c, pc⟩ := rc.toRawEq some ⟨c, .const zc hc, pc⟩ | .mul vxa₁ vea₁ va₂, vb => do let ⟨_, vc₁, pc₁⟩ := evalMulProd sℕ vea₁ vb let ⟨_, vc₂, pc₂⟩ := evalPowProd va₂ vb some ⟨_, .mul vxa₁ vc₁ vc₂, q(mul_pow $pc₁ $pc₂)⟩ | _, _ => none res.getD (evalPowProdAtom sα va vb) /-- The result of `extractCoeff` is a numeral and a proof that the original expression factors by this numeral. -/ structure ExtractCoeff (e : Q(ℕ)) where /-- A raw natural number literal. -/ k : Q(ℕ) /-- The result of extracting the coefficient is a monic monomial. -/ e' : Q(ℕ) /-- `e'` is a monomial. -/ ve' : ExProd sℕ e' /-- The proof that `e` splits into the coefficient `k` and the monic monomial `e'`. -/ p : Q($e = $e' * $k) theorem coeff_one (k : ℕ) : k.rawCast = (nat_lit 1).rawCast * k := by simp theorem coeff_mul {a₃ c₂ k : ℕ} (a₁ a₂ : ℕ) (_ : a₃ = c₂ * k) : a₁ ^ a₂ * a₃ = (a₁ ^ a₂ * c₂) * k := by subst_vars; rw [mul_assoc] /-- Given a monomial expression `va`, splits off the leading coefficient `k` and the remainder `e'`, stored in the `ExtractCoeff` structure. * `c = 1 * c` (if `c` is a constant) * `a * b = (a * b') * k` if `b = b' * k` -/ def extractCoeff {a : Q(ℕ)} (va : ExProd sℕ a) : ExtractCoeff a := match va with | .const _ _ => have k : Q(ℕ) := a.appArg! ⟨k, q((nat_lit 1).rawCast), .const 1, (q(coeff_one $k) : Expr)⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃ => let ⟨k, _, vc, pc⟩ := extractCoeff va₃ ⟨k, _, .mul va₁ va₂ vc, q(coeff_mul $a₁ $a₂ $pc)⟩ theorem pow_one_cast (a : R) : a ^ (nat_lit 1).rawCast = a := by simp theorem zero_pow {b : ℕ} (_ : 0 < b) : (0 : R) ^ b = 0 := match b with | b+1 => by simp [pow_succ] theorem single_pow {b : ℕ} (_ : (a : R) ^ b = c) : (a + 0) ^ b = c + 0 := by simp [*] theorem pow_nat {b c k : ℕ} {d e : R} (_ : b = c * k) (_ : a ^ c = d) (_ : d ^ k = e) : (a : R) ^ b = e := by subst_vars; simp [pow_mul] /-- Exponentiates a polynomial `va` by a monomial `vb`, including several special cases. * `a ^ 1 = a` * `0 ^ e = 0` if `0 < e` * `(a + 0) ^ b = a ^ b` computed using `evalPowProd` * `a ^ b = (a ^ b') ^ k` if `b = b' * k` and `k > 1` Otherwise `a ^ b` is just encoded as `a ^ b * 1 + 0` using `evalPowAtom`. -/ partial def evalPow₁ {a : Q($α)} {b : Q(ℕ)} (va : ExSum sα a) (vb : ExProd sℕ b) : Result (ExSum sα) q($a ^ $b) := match va, vb with | va, .const 1 => haveI : $b =Q Nat.rawCast (nat_lit 1) := ⟨⟩ ⟨_, va, q(pow_one_cast $a)⟩ | .zero, vb => match vb.evalPos with | some p => ⟨_, .zero, q(zero_pow (R := $α) $p)⟩ | none => evalPowAtom sα (.sum .zero) vb | ExSum.add va .zero, vb => -- TODO: using `.add` here takes a while to compile? let ⟨_, vc, pc⟩ := evalPowProd sα va vb ⟨_, vc.toSum, q(single_pow $pc)⟩ | va, vb => if vb.coeff > 1 then let ⟨k, _, vc, pc⟩ := extractCoeff vb let ⟨_, vd, pd⟩ := evalPow₁ va vc let ⟨_, ve, pe⟩ := evalPowNat sα vd k ⟨_, ve, q(pow_nat $pc $pd $pe)⟩ else evalPowAtom sα (.sum va) vb theorem pow_zero (a : R) : a ^ 0 = (nat_lit 1).rawCast + 0 := by simp theorem pow_add {b₁ b₂ : ℕ} {d : R} (_ : a ^ b₁ = c₁) (_ : a ^ b₂ = c₂) (_ : c₁ * c₂ = d) : (a : R) ^ (b₁ + b₂) = d := by subst_vars; simp [_root_.pow_add] /-- Exponentiates two polynomials `va, vb`. * `a ^ 0 = 1` * `a ^ (b₁ + b₂) = a ^ b₁ * a ^ b₂` -/ def evalPow {a : Q($α)} {b : Q(ℕ)} (va : ExSum sα a) (vb : ExSum sℕ b) : Result (ExSum sα) q($a ^ $b) := match vb with | .zero => ⟨_, (ExProd.mkNat sα 1).2.toSum, q(pow_zero $a)⟩ | .add vb₁ vb₂ => let ⟨_, vc₁, pc₁⟩ := evalPow₁ sα va vb₁ let ⟨_, vc₂, pc₂⟩ := evalPow va vb₂ let ⟨_, vd, pd⟩ := evalMul sα vc₁ vc₂ ⟨_, vd, q(pow_add $pc₁ $pc₂ $pd)⟩ /-- This cache contains data required by the `ring` tactic during execution. -/ structure Cache {α : Q(Type u)} (sα : Q(CommSemiring $α)) := /-- A ring instance on `α`, if available. -/ rα : Option Q(Ring $α) /-- A division ring instance on `α`, if available. -/ dα : Option Q(DivisionRing $α) /-- A characteristic zero ring instance on `α`, if available. -/ czα : Option Q(CharZero $α) /-- Create a new cache for `α` by doing the necessary instance searches. -/ def mkCache {α : Q(Type u)} (sα : Q(CommSemiring $α)) : MetaM (Cache sα) := return { rα := (← trySynthInstanceQ q(Ring $α)).toOption dα := (← trySynthInstanceQ q(DivisionRing $α)).toOption czα := (← trySynthInstanceQ q(CharZero $α)).toOption } theorem cast_pos {n : ℕ} : IsNat (a : R) n → a = n.rawCast + 0 | ⟨e⟩ => by simp [e] theorem cast_zero : IsNat (a : R) (nat_lit 0) → a = 0 | ⟨e⟩ => by simp [e] theorem cast_neg {n : ℕ} {R} [Ring R] {a : R} : IsInt a (.negOfNat n) → a = (Int.negOfNat n).rawCast + 0 | ⟨e⟩ => by simp [e] theorem cast_rat {n : ℤ} {d : ℕ} {R} [DivisionRing R] {a : R} : IsRat a n d → a = Rat.rawCast n d + 0 | ⟨_, e⟩ => by simp [e, div_eq_mul_inv] /-- Converts a proof by `norm_num` that `e` is a numeral, into a normalization as a monomial: * `e = 0` if `norm_num` returns `IsNat e 0` * `e = Nat.rawCast n + 0` if `norm_num` returns `IsNat e n` * `e = Int.rawCast n + 0` if `norm_num` returns `IsInt e n` * `e = Rat.rawCast n d + 0` if `norm_num` returns `IsRat e n d` -/ def evalCast {α : Q(Type u)} (sα : Q(CommSemiring $α)) {e : Q($α)} : NormNum.Result e → Option (Result (ExSum sα) e) | .isNat _ (.lit (.natVal 0)) p => do assumeInstancesCommute pure ⟨_, .zero, q(cast_zero $p)⟩ | .isNat _ lit p => do assumeInstancesCommute pure ⟨_, (ExProd.mkNat sα lit.natLit!).2.toSum, (q(cast_pos $p) :)⟩ | .isNegNat rα lit p => pure ⟨_, (ExProd.mkNegNat _ rα lit.natLit!).2.toSum, (q(cast_neg $p) : Expr)⟩ | .isRat dα q n d p => pure ⟨_, (ExProd.mkRat sα dα q n d q(IsRat.den_nz $p)).2.toSum, (q(cast_rat $p) : Expr)⟩ | _ => none theorem toProd_pf (p : (a : R) = a') : a = a' ^ (nat_lit 1).rawCast * (nat_lit 1).rawCast := by simp [*] theorem atom_pf (a : R) : a = a ^ (nat_lit 1).rawCast * (nat_lit 1).rawCast + 0 := by simp theorem atom_pf' (p : (a : R) = a') : a = a' ^ (nat_lit 1).rawCast * (nat_lit 1).rawCast + 0 := by simp [*] /-- Evaluates an atom, an expression where `ring` can find no additional structure. * `a = a ^ 1 * 1 + 0` -/ def evalAtom (e : Q($α)) : AtomM (Result (ExSum sα) e) := do let r ← (← read).evalAtom e have e' : Q($α) := r.expr let i ← addAtom e' let ve' := (ExBase.atom i (e := e')).toProd (ExProd.mkNat sℕ 1).2 |>.toSum pure ⟨_, ve', match r.proof? with | none => (q(atom_pf $e) : Expr) | some (p : Q($e = $e')) => (q(atom_pf' $p) : Expr)⟩ theorem inv_mul {R} [DivisionRing R] {a₁ a₂ a₃ b₁ b₃ c} (_ : (a₁⁻¹ : R) = b₁) (_ : (a₃⁻¹ : R) = b₃) (_ : b₃ * (b₁ ^ a₂ * (nat_lit 1).rawCast) = c) : (a₁ ^ a₂ * a₃ : R)⁻¹ = c := by subst_vars; simp nonrec theorem inv_zero {R} [DivisionRing R] : (0 : R)⁻¹ = 0 := inv_zero theorem inv_single {R} [DivisionRing R] {a b : R} (_ : (a : R)⁻¹ = b) : (a + 0)⁻¹ = b + 0 := by simp [*] theorem inv_add {a₁ a₂ : ℕ} (_ : ((a₁ : ℕ) : R) = b₁) (_ : ((a₂ : ℕ) : R) = b₂) : ((a₁ + a₂ : ℕ) : R) = b₁ + b₂ := by subst_vars; simp section variable (dα : Q(DivisionRing $α)) /-- Applies `⁻¹` to a polynomial to get an atom. -/ def evalInvAtom (a : Q($α)) : AtomM (Result (ExBase sα) q($a⁻¹)) := do let a' : Q($α) := q($a⁻¹) let i ← addAtom a' pure ⟨a', ExBase.atom i, (q(Eq.refl $a') : Expr)⟩ /-- Inverts a polynomial `va` to get a normalized result polynomial. * `c⁻¹ = (c⁻¹)` if `c` is a constant * `(a ^ b * c)⁻¹ = a⁻¹ ^ b * c⁻¹` -/ def ExProd.evalInv {a : Q($α)} (czα : Option Q(CharZero $α)) (va : ExProd sα a) : AtomM (Result (ExProd sα) q($a⁻¹)) := do match va with | .const c hc => let ra := Result.ofRawRat c a hc match NormNum.evalInv.core q($a⁻¹) a ra dα czα with | some rc => let ⟨zc, hc⟩ := rc.toRatNZ.get! let ⟨c, pc⟩ := rc.toRawEq pure ⟨c, .const zc hc, pc⟩ | none => let ⟨_, vc, pc⟩ ← evalInvAtom sα dα a pure ⟨_, vc.toProd (ExProd.mkNat sℕ 1).2, q(toProd_pf $pc)⟩ | .mul (x := a₁) (e := _a₂) _va₁ va₂ va₃ => do let ⟨_b₁, vb₁, pb₁⟩ ← evalInvAtom sα dα a₁ let ⟨_b₃, vb₃, pb₃⟩ ← va₃.evalInv czα let ⟨c, vc, (pc : Q($_b₃ * ($_b₁ ^ $_a₂ * Nat.rawCast 1) = $c))⟩ := evalMulProd sα vb₃ (vb₁.toProd va₂) pure ⟨c, vc, (q(inv_mul $pb₁ $pb₃ $pc) : Expr)⟩ /-- Inverts a polynomial `va` to get a normalized result polynomial. * `0⁻¹ = 0` * `a⁻¹ = (a⁻¹)` if `a` is a nontrivial sum -/ def ExSum.evalInv {a : Q($α)} (czα : Option Q(CharZero $α)) (va : ExSum sα a) : AtomM (Result (ExSum sα) q($a⁻¹)) := match va with | ExSum.zero => pure ⟨_, .zero, (q(inv_zero (R := $α)) : Expr)⟩ | ExSum.add va ExSum.zero => do let ⟨_, vb, pb⟩ ← va.evalInv dα czα pure ⟨_, vb.toSum, (q(inv_single $pb) : Expr)⟩ | va => do let ⟨_, vb, pb⟩ ← evalInvAtom sα dα a pure ⟨_, vb.toProd (ExProd.mkNat sℕ 1).2 |>.toSum, q(atom_pf' $pb)⟩ end theorem div_pf {R} [DivisionRing R] {a b c d : R} (_ : b⁻¹ = c) (_ : a * c = d) : a / b = d := by subst_vars; simp [div_eq_mul_inv] /-- Divides two polynomials `va, vb` to get a normalized result polynomial. * `a / b = a * b⁻¹` -/ def evalDiv {a b : Q($α)} (rα : Q(DivisionRing $α)) (czα : Option Q(CharZero $α)) (va : ExSum sα a) (vb : ExSum sα b) : AtomM (Result (ExSum sα) q($a / $b)) := do let ⟨_c, vc, pc⟩ ← vb.evalInv sα rα czα let ⟨d, vd, (pd : Q($a * $_c = $d))⟩ := evalMul sα va vc pure ⟨d, vd, (q(div_pf $pc $pd) : Expr)⟩ theorem add_congr (_ : a = a') (_ : b = b') (_ : a' + b' = c) : (a + b : R) = c := by subst_vars; rfl theorem mul_congr (_ : a = a') (_ : b = b') (_ : a' * b' = c) : (a * b : R) = c := by subst_vars; rfl theorem nsmul_congr {a a' : ℕ} (_ : (a : ℕ) = a') (_ : b = b') (_ : a' • b' = c) : (a • (b : R)) = c := by subst_vars; rfl theorem pow_congr {b b' : ℕ} (_ : a = a') (_ : b = b') (_ : a' ^ b' = c) : (a ^ b : R) = c := by subst_vars; rfl theorem neg_congr {R} [Ring R] {a a' b : R} (_ : a = a') (_ : -a' = b) : (-a : R) = b := by subst_vars; rfl theorem sub_congr {R} [Ring R] {a a' b b' c : R} (_ : a = a') (_ : b = b') (_ : a' - b' = c) : (a - b : R) = c := by subst_vars; rfl theorem inv_congr {R} [DivisionRing R] {a a' b : R} (_ : a = a') (_ : a'⁻¹ = b) : (a⁻¹ : R) = b := by subst_vars; rfl theorem div_congr {R} [DivisionRing R] {a a' b b' c : R} (_ : a = a') (_ : b = b') (_ : a' / b' = c) : (a / b : R) = c := by subst_vars; rfl /-- A precomputed `Cache` for `ℕ`. -/ def Cache.nat : Cache sℕ := { rα := none, dα := none, czα := some q(inferInstance) } /-- Checks whether `e` would be processed by `eval` as a ring expression, or otherwise if it is an atom or something simplifiable via `norm_num`. We use this in `ring_nf` to avoid rewriting atoms unnecessarily. Returns: * `none` if `eval` would process `e` as an algebraic ring expression * `some none` if `eval` would treat `e` as an atom. * `some (some r)` if `eval` would not process `e` as an algebraic ring expression, but `NormNum.derive` can nevertheless simplify `e`, with result `r`. -/ -- Note this is not the same as whether the result of `eval` is an atom. (e.g. consider `x + 0`.) def isAtomOrDerivable {u} {α : Q(Type u)} (sα : Q(CommSemiring $α)) (c : Cache sα) (e : Q($α)) : AtomM (Option (Option (Result (ExSum sα) e))) := do let els := try pure <| some (evalCast sα (← derive e)) catch _ => pure (some none) let .const n _ := (← withReducible <| whnf e).getAppFn | els match n, c.rα, c.dα with | ``HAdd.hAdd, _, _ | ``Add.add, _, _ | ``HMul.hMul, _, _ | ``Mul.mul, _, _ | ``HSMul.hSMul, _, _ | ``HPow.hPow, _, _ | ``Pow.pow, _, _ | ``Neg.neg, some _, _ | ``HSub.hSub, some _, _ | ``Sub.sub, some _, _ | ``Inv.inv, _, some _ | ``HDiv.hDiv, _, some _ | ``Div.div, _, some _ => pure none | _, _, _ => els /-- Evaluates expression `e` of type `α` into a normalized representation as a polynomial. This is the main driver of `ring`, which calls out to `evalAdd`, `evalMul` etc. -/ partial def eval {u : Lean.Level} {α : Q(Type u)} (sα : Q(CommSemiring $α)) (c : Cache sα) (e : Q($α)) : AtomM (Result (ExSum sα) e) := Lean.withIncRecDepth do let els := do try evalCast sα (← derive e) catch _ => evalAtom sα e let .const n _ := (← withReducible <| whnf e).getAppFn | els match n, c.rα, c.dα with | ``HAdd.hAdd, _, _ | ``Add.add, _, _ => match e with | ~q($a + $b) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ := evalAdd sα va vb pure ⟨c, vc, (q(add_congr $pa $pb $p) : Expr)⟩ | _ => els | ``HMul.hMul, _, _ | ``Mul.mul, _, _ => match e with | ~q($a * $b) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ := evalMul sα va vb pure ⟨c, vc, (q(mul_congr $pa $pb $p) : Expr)⟩ | _ => els | ``HSMul.hSMul, _, _ => match e with | ~q(($a : ℕ) • ($b : «$α»)) => let ⟨_, va, pa⟩ ← eval sℕ .nat a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ ← evalNSMul sα va vb pure ⟨c, vc, (q(nsmul_congr $pa $pb $p) : Expr)⟩ | _ => els | ``HPow.hPow, _, _ | ``Pow.pow, _, _ => match e with | ~q($a ^ $b) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sℕ .nat b let ⟨c, vc, p⟩ := evalPow sα va vb pure ⟨c, vc, (q(pow_congr $pa $pb $p) : Expr)⟩ | _ => els | ``Neg.neg, some rα, _ => match e with | ~q(-$a) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨b, vb, p⟩ := evalNeg sα rα va pure ⟨b, vb, (q(neg_congr $pa $p) : Expr)⟩ | ``HSub.hSub, some rα, _ | ``Sub.sub, some rα, _ => match e with | ~q($a - $b) => do let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ := evalSub sα rα va vb pure ⟨c, vc, (q(sub_congr $pa $pb $p) : Expr)⟩ | _ => els | ``Inv.inv, _, some dα => match e with | ~q($a⁻¹) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨b, vb, p⟩ ← va.evalInv sα dα c.czα pure ⟨b, vb, (q(inv_congr $pa $p) : Expr)⟩ | ``HDiv.hDiv, _, some dα | ``Div.div, _, some dα => match e with | ~q($a / $b) => do let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ ← evalDiv sα dα c.czα va vb pure ⟨c, vc, (q(div_congr $pa $pb $p) : Expr)⟩ | _ => els | _, _, _ => els universe u /-- `CSLift α β` is a typeclass used by `ring` for lifting operations from `α` (which is not a commutative semiring) into a commutative semiring `β` by using an injective map `lift : α → β`. -/ class CSLift (α : Type u) (β : outParam (Type u)) where /-- `lift` is the "canonical injection" from `α` to `β` -/ lift : α → β /-- `lift` is an injective function -/ inj : Function.Injective lift /-- `CSLiftVal a b` means that `b = lift a`. This is used by `ring` to construct an expression `b` from the input expression `a`, and then run the usual ring algorithm on `b`. -/ class CSLiftVal {α} {β : outParam (Type u)} [CSLift α β] (a : α) (b : outParam β) : Prop where /-- The output value `b` is equal to the lift of `a`. This can be supplied by the default instance which sets `b := lift a`, but `ring` will treat this as an atom so it is more useful when there are other instances which distribute addition or multiplication. -/ eq : b = CSLift.lift a instance (priority := low) {α β} [CSLift α β] (a : α) : CSLiftVal a (CSLift.lift a) := ⟨rfl⟩ theorem of_lift {α β} [inst : CSLift α β] {a b : α} {a' b' : β} [h1 : CSLiftVal a a'] [h2 : CSLiftVal b b'] (h : a' = b') : a = b := inst.2 <| by rwa [← h1.1, ← h2.1] open Lean Parser.Tactic Elab Command Elab.Tactic Meta Qq theorem of_eq {α} {a b c : α} (_ : (a : α) = c) (_ : b = c) : a = b := by subst_vars; rfl /-- This is a routine which is used to clean up the unsolved subgoal of a failed `ring1` application. It is overridden in `Mathlib.Tactic.Ring.RingNF` to apply the `ring_nf` simp set to the goal. -/ initialize ringCleanupRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef pure /-- Frontend of `ring1`: attempt to close a goal `g`, assuming it is an equation of semirings. -/ def proveEq (g : MVarId) : AtomM Unit := do let some (α, e₁, e₂) := (← whnfR <|← instantiateMVars <|← g.getType).eq? | throwError "ring failed: not an equality" let .sort u ← whnf (← inferType α) | unreachable! let v ← try u.dec catch _ => throwError "not a type{indentExpr α}" have α : Q(Type v) := α let sα ← try Except.ok <$> synthInstanceQ q(CommSemiring $α) catch e => pure (.error e) have e₁ : Q($α) := e₁; have e₂ : Q($α) := e₂ let eq ← match sα with | .ok sα => ringCore sα e₁ e₂ | .error e => let β ← mkFreshExprMVarQ q(Type v) let e₁' ← mkFreshExprMVarQ q($β) let e₂' ← mkFreshExprMVarQ q($β) let (sβ, (pf : Q($e₁' = $e₂' → $e₁ = $e₂))) ← try let _l ← synthInstanceQ q(CSLift $α $β) let sβ ← synthInstanceQ q(CommSemiring $β) let _ ← synthInstanceQ q(CSLiftVal $e₁ $e₁') let _ ← synthInstanceQ q(CSLiftVal $e₂ $e₂') pure (sβ, q(of_lift (a := $e₁) (b := $e₂))) catch _ => throw e pure q($pf $(← ringCore sβ e₁' e₂')) g.assign eq where /-- The core of `proveEq` takes expressions `e₁ e₂ : α` where `α` is a `CommSemiring`, and returns a proof that they are equal (or fails). -/ ringCore {v : Level} {α : Q(Type v)} (sα : Q(CommSemiring $α)) (e₁ e₂ : Q($α)) : AtomM Q($e₁ = $e₂) := do let c ← mkCache sα profileitM Exception "ring" (← getOptions) do let ⟨a, va, pa⟩ ← eval sα c e₁ let ⟨b, vb, pb⟩ ← eval sα c e₂ unless va.eq vb do let g ← mkFreshExprMVar (← (← ringCleanupRef.get) q($a = $b)) throwError "ring failed, ring expressions not equal\n{g.mvarId!}" let pb : Q($e₂ = $a) := pb return q(of_eq $pa $pb) /-- Tactic for solving equations of *commutative* (semi)rings, allowing variables in the exponent. * This version of `ring` fails if the target is not an equality. * The variant `ring1!` will use a more aggressive reducibility setting to determine equality of atoms. -/ elab (name := ring1) "ring1" tk:"!"? : tactic => liftMetaMAtMain fun g ↦ do AtomM.run (if tk.isSome then .default else .reducible) (proveEq g) @[inherit_doc ring1] macro "ring1!" : tactic => `(tactic| ring1 !) end Ring end Tactic end Mathlib
Tactic\Ring\PNat.lean
/- Copyright (c) 2023 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Tactic.Ring.Basic import Mathlib.Data.PNat.Basic /-! # Additional instances for `ring` over `PNat` This adds some instances which enable `ring` to work on `PNat` even though it is not a commutative semiring, by lifting to `Nat`. -/ namespace Mathlib.Tactic.Ring instance : CSLift ℕ+ Nat where lift := PNat.val inj := PNat.coe_injective -- FIXME: this `no_index` seems to be in the wrong place, but -- #synth CSLiftVal (3 : ℕ+) _ doesn't work otherwise instance {n} : CSLiftVal (no_index (OfNat.ofNat (n+1)) : ℕ+) (n + 1) := ⟨rfl⟩ instance {n h} : CSLiftVal (Nat.toPNat n h) n := ⟨rfl⟩ instance {n} : CSLiftVal (Nat.succPNat n) (n + 1) := ⟨rfl⟩ instance {n} : CSLiftVal (Nat.toPNat' n) (n.pred + 1) := ⟨rfl⟩ instance {n k} : CSLiftVal (PNat.divExact n k) (n.div k + 1) := ⟨rfl⟩ instance {n n' k k'} [h1 : CSLiftVal (n : ℕ+) n'] [h2 : CSLiftVal (k : ℕ+) k'] : CSLiftVal (n + k) (n' + k') := ⟨by simp [h1.1, h2.1, CSLift.lift]⟩ instance {n n' k k'} [h1 : CSLiftVal (n : ℕ+) n'] [h2 : CSLiftVal (k : ℕ+) k'] : CSLiftVal (n * k) (n' * k') := ⟨by simp [h1.1, h2.1, CSLift.lift]⟩ instance {n n' k} [h1 : CSLiftVal (n : ℕ+) n'] : CSLiftVal (n ^ k) (n' ^ k) := ⟨by simp [h1.1, CSLift.lift]⟩ end Ring end Tactic end Mathlib
Tactic\Ring\RingNF.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Anne Baanen -/ import Mathlib.Tactic.Ring.Basic import Mathlib.Tactic.TryThis import Mathlib.Tactic.Conv import Mathlib.Util.Qq /-! # `ring_nf` tactic A tactic which uses `ring` to rewrite expressions. This can be used non-terminally to normalize ring expressions in the goal such as `⊢ P (x + x + x)` ~> `⊢ P (x * 3)`, as well as being able to prove some equations that `ring` cannot because they involve ring reasoning inside a subterm, such as `sin (x + y) + sin (y + x) = 2 * sin (x + y)`. -/ namespace Mathlib.Tactic open Lean hiding Rat open Qq Meta namespace Ring variable {u : Level} {arg : Q(Type u)} {sα : Q(CommSemiring $arg)} {a : Q($arg)} /-- True if this represents an atomic expression. -/ def ExBase.isAtom : ExBase sα a → Bool | .atom _ => true | _ => false /-- True if this represents an atomic expression. -/ def ExProd.isAtom : ExProd sα a → Bool | .mul va₁ (.const 1 _) (.const 1 _) => va₁.isAtom | _ => false /-- True if this represents an atomic expression. -/ def ExSum.isAtom : ExSum sα a → Bool | .add va₁ va₂ => match va₂ with -- FIXME: this takes a while to compile as one match | .zero => va₁.isAtom | _ => false | _ => false end Ring namespace RingNF open Ring /-- The normalization style for `ring_nf`. -/ inductive RingMode where /-- Sum-of-products form, like `x + x * y * 2 + z ^ 2`. -/ | SOP /-- Raw form: the representation `ring` uses internally. -/ | raw deriving Inhabited, BEq, Repr /-- Configuration for `ring_nf`. -/ structure Config where /-- the reducibility setting to use when comparing atoms for defeq -/ red := TransparencyMode.reducible /-- if true, atoms inside ring expressions will be reduced recursively -/ recursive := true /-- The normalization style. -/ mode := RingMode.SOP deriving Inhabited, BEq, Repr /-- Function elaborating `RingNF.Config`. -/ declare_config_elab elabConfig Config /-- The read-only state of the `RingNF` monad. -/ structure Context where /-- A basically empty simp context, passed to the `simp` traversal in `RingNF.rewrite`. -/ ctx : Simp.Context /-- A cleanup routine, which simplifies normalized polynomials to a more human-friendly format. -/ simp : Simp.Result → SimpM Simp.Result /-- The monad for `RingNF` contains, in addition to the `AtomM` state, a simp context for the main traversal and a simp function (which has another simp context) to simplify normalized polynomials. -/ abbrev M := ReaderT Context AtomM /-- A tactic in the `RingNF.M` monad which will simplify expression `parent` to a normal form. * `root`: true if this is a direct call to the function. `RingNF.M.run` sets this to `false` in recursive mode. -/ def rewrite (parent : Expr) (root := true) : M Simp.Result := fun nctx rctx s ↦ do let pre : Simp.Simproc := fun e => try guard <| root || parent != e -- recursion guard let e ← withReducible <| whnf e guard e.isApp -- all interesting ring expressions are applications let ⟨u, α, e⟩ ← inferTypeQ' e let sα ← synthInstanceQ (q(CommSemiring $α) : Q(Type u)) let c ← mkCache sα let ⟨a, _, pa⟩ ← match ← isAtomOrDerivable sα c e rctx s with | none => eval sα c e rctx s -- `none` indicates that `eval` will find something algebraic. | some none => failure -- No point rewriting atoms | some (some r) => pure r -- Nothing algebraic for `eval` to use, but `norm_num` simplifies. let r ← nctx.simp { expr := a, proof? := pa } if ← withReducible <| isDefEq r.expr e then return .done { expr := r.expr } pure (.done r) catch _ => pure <| .continue let post := Simp.postDefault #[] (·.1) <$> Simp.main parent nctx.ctx (methods := { pre, post }) variable {R : Type*} [CommSemiring R] {n d : ℕ} theorem add_assoc_rev (a b c : R) : a + (b + c) = a + b + c := (add_assoc ..).symm theorem mul_assoc_rev (a b c : R) : a * (b * c) = a * b * c := (mul_assoc ..).symm theorem mul_neg {R} [Ring R] (a b : R) : a * -b = -(a * b) := by simp theorem add_neg {R} [Ring R] (a b : R) : a + -b = a - b := (sub_eq_add_neg ..).symm theorem nat_rawCast_0 : (Nat.rawCast 0 : R) = 0 := by simp theorem nat_rawCast_1 : (Nat.rawCast 1 : R) = 1 := by simp theorem nat_rawCast_2 [Nat.AtLeastTwo n] : (Nat.rawCast n : R) = OfNat.ofNat n := rfl theorem int_rawCast_neg {R} [Ring R] : (Int.rawCast (.negOfNat n) : R) = -Nat.rawCast n := by simp theorem rat_rawCast_pos {R} [DivisionRing R] : (Rat.rawCast (.ofNat n) d : R) = Nat.rawCast n / Nat.rawCast d := by simp theorem rat_rawCast_neg {R} [DivisionRing R] : (Rat.rawCast (.negOfNat n) d : R) = Int.rawCast (.negOfNat n) / Nat.rawCast d := by simp /-- Runs a tactic in the `RingNF.M` monad, given initial data: * `s`: a reference to the mutable state of `ring`, for persisting across calls. This ensures that atom ordering is used consistently. * `cfg`: the configuration options * `x`: the tactic to run -/ partial def M.run {α : Type} (s : IO.Ref AtomM.State) (cfg : RingNF.Config) (x : M α) : MetaM α := do let ctx := { simpTheorems := #[← Elab.Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) {}] congrTheorems := ← getSimpCongrTheorems config.singlePass := cfg.mode matches .raw } let simp ← match cfg.mode with | .raw => pure pure | .SOP => let thms : SimpTheorems := {} let thms ← [``add_zero, ``add_assoc_rev, ``_root_.mul_one, ``mul_assoc_rev, ``_root_.pow_one, ``mul_neg, ``add_neg].foldlM (·.addConst ·) thms let thms ← [``nat_rawCast_0, ``nat_rawCast_1, ``nat_rawCast_2, ``int_rawCast_neg, ``rat_rawCast_neg, ``rat_rawCast_pos].foldlM (·.addConst · (post := false)) thms let ctx' := { ctx with simpTheorems := #[thms] } pure fun r' : Simp.Result ↦ do r'.mkEqTrans (← Simp.main r'.expr ctx' (methods := ← Lean.Meta.Simp.mkDefaultMethods)).1 let nctx := { ctx, simp } let rec /-- The recursive context. -/ rctx := { red := cfg.red, evalAtom }, /-- The atom evaluator calls either `RingNF.rewrite` recursively, or nothing depending on `cfg.recursive`. -/ evalAtom := if cfg.recursive then fun e ↦ rewrite e false nctx rctx s else fun e ↦ pure { expr := e } x nctx rctx s /-- Overrides the default error message in `ring1` to use a prettified version of the goal. -/ initialize ringCleanupRef.set fun e => do M.run (← IO.mkRef {}) { recursive := false } fun nctx _ _ => return (← nctx.simp { expr := e } ({} : Lean.Meta.Simp.Methods).toMethodsRef nctx.ctx |>.run {}).1.expr open Elab.Tactic Parser.Tactic /-- Use `ring_nf` to rewrite the main goal. -/ def ringNFTarget (s : IO.Ref AtomM.State) (cfg : Config) : TacticM Unit := withMainContext do let goal ← getMainGoal let tgt ← instantiateMVars (← goal.getType) let r ← M.run s cfg <| rewrite tgt if r.expr.consumeMData.isConstOf ``True then goal.assign (← mkOfEqTrue (← r.getProof)) replaceMainGoal [] else replaceMainGoal [← applySimpResultToTarget goal tgt r] /-- Use `ring_nf` to rewrite hypothesis `h`. -/ def ringNFLocalDecl (s : IO.Ref AtomM.State) (cfg : Config) (fvarId : FVarId) : TacticM Unit := withMainContext do let tgt ← instantiateMVars (← fvarId.getType) let goal ← getMainGoal let myres ← M.run s cfg <| rewrite tgt match ← applySimpResultToLocalDecl goal fvarId myres false with | none => replaceMainGoal [] | some (_, newGoal) => replaceMainGoal [newGoal] /-- Simplification tactic for expressions in the language of commutative (semi)rings, which rewrites all ring expressions into a normal form. * `ring_nf!` will use a more aggressive reducibility setting to identify atoms. * `ring_nf (config := cfg)` allows for additional configuration: * `red`: the reducibility setting (overridden by `!`) * `recursive`: if true, `ring_nf` will also recurse into atoms * `ring_nf` works as both a tactic and a conv tactic. In tactic mode, `ring_nf at h` can be used to rewrite in a hypothesis. -/ elab (name := ringNF) "ring_nf" tk:"!"? cfg:(config ?) loc:(location)? : tactic => do let mut cfg ← elabConfig cfg if tk.isSome then cfg := { cfg with red := .default } let loc := (loc.map expandLocation).getD (.targets #[] true) let s ← IO.mkRef {} withLocation loc (ringNFLocalDecl s cfg) (ringNFTarget s cfg) fun _ ↦ throwError "ring_nf failed" @[inherit_doc ringNF] macro "ring_nf!" cfg:(config)? loc:(location)? : tactic => `(tactic| ring_nf ! $(cfg)? $(loc)?) @[inherit_doc ringNF] syntax (name := ringNFConv) "ring_nf" "!"? (config)? : conv /-- Tactic for solving equations of *commutative* (semi)rings, allowing variables in the exponent. * This version of `ring1` uses `ring_nf` to simplify in atoms. * The variant `ring1_nf!` will use a more aggressive reducibility setting to determine equality of atoms. -/ elab (name := ring1NF) "ring1_nf" tk:"!"? cfg:(config ?) : tactic => do let mut cfg ← elabConfig cfg if tk.isSome then cfg := { cfg with red := .default } let s ← IO.mkRef {} liftMetaMAtMain fun g ↦ M.run s cfg <| proveEq g @[inherit_doc ring1NF] macro "ring1_nf!" cfg:(config)? : tactic => `(tactic| ring1_nf ! $(cfg)?) /-- Elaborator for the `ring_nf` tactic. -/ @[tactic ringNFConv] def elabRingNFConv : Tactic := fun stx ↦ match stx with | `(conv| ring_nf $[!%$tk]? $(_cfg)?) => withMainContext do let mut cfg ← elabConfig stx[2] if tk.isSome then cfg := { cfg with red := .default } let s ← IO.mkRef {} Conv.applySimpResult (← M.run s cfg <| rewrite (← instantiateMVars (← Conv.getLhs))) | _ => Elab.throwUnsupportedSyntax @[inherit_doc ringNF] macro "ring_nf!" cfg:(config)? : conv => `(conv| ring_nf ! $(cfg)?) /-- Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the exponent. * `ring!` will use a more aggressive reducibility setting to determine equality of atoms. * `ring1` fails if the target is not an equality. For example: ``` example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring example (x y : ℕ) : x + id y = y + id x := by ring! ``` -/ macro (name := ring) "ring" : tactic => `(tactic| first | ring1 | try_this ring_nf) @[inherit_doc ring] macro "ring!" : tactic => `(tactic| first | ring1! | try_this ring_nf!) /-- The tactic `ring` evaluates expressions in *commutative* (semi)rings. This is the conv tactic version, which rewrites a target which is a ring equality to `True`. See also the `ring` tactic. -/ macro (name := ringConv) "ring" : conv => `(conv| first | discharge => ring1 | try_this ring_nf) @[inherit_doc ringConv] macro "ring!" : conv => `(conv| first | discharge => ring1! | try_this ring_nf!) end RingNF end Tactic end Mathlib
Tactic\Sat\FromLRAT.lean
/- Copyright (c) 2022 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Group.Nat /-! # `lrat_proof` command Defines a macro for producing SAT proofs from CNF / LRAT files. These files are commonly used in the SAT community for writing proofs. Most SAT solvers support export to [DRAT](https://arxiv.org/abs/1610.06229) format, but this format can be expensive to reconstruct because it requires recomputing all unit propagation steps. The [LRAT](https://arxiv.org/abs/1612.02353) format solves this issue by attaching a proof to the deduction of each new clause. (The L in LRAT stands for Linear time verification.) There are several verified checkers for the LRAT format, and the program implemented here makes it possible to use the lean kernel as an LRAT checker as well and expose the results as a standard propositional theorem. The input to the `lrat_proof` command is the name of the theorem to define, and the statement (written in CNF format) and the proof (in LRAT format). For example: ``` lrat_proof foo "p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0" "5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0" ``` produces a theorem: ``` foo : ∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1 ``` * You can see the theorem statement by hovering over the word `foo`. * You can use the `example` keyword in place of `foo` to avoid generating a theorem. * You can use the `include_str` macro in place of the two strings to load CNF / LRAT files from disk. -/ open Lean hiding Literal HashMap open Batteries namespace Sat /-- A literal is a positive or negative occurrence of an atomic propositional variable. Note that unlike DIMACS, 0 is a valid variable index. -/ inductive Literal | pos : Nat → Literal | neg : Nat → Literal /-- Construct a literal. Positive numbers are translated to positive literals, and negative numbers become negative literals. The input is assumed to be nonzero. -/ def Literal.ofInt (i : Int) : Literal := if i < 0 then Literal.neg (-i-1).toNat else Literal.pos (i-1).toNat /-- Swap the polarity of a literal. -/ def Literal.negate : Literal → Literal | pos i => neg i | neg i => pos i instance : ToExpr Literal where toTypeExpr := mkConst ``Literal toExpr | Literal.pos i => mkApp (mkConst ``Literal.pos) (mkRawNatLit i) | Literal.neg i => mkApp (mkConst ``Literal.neg) (mkRawNatLit i) /-- A clause is a list of literals, thought of as a disjunction like `a ∨ b ∨ ¬c`. -/ def Clause := List Literal def Clause.nil : Clause := [] def Clause.cons : Literal → Clause → Clause := List.cons /-- A formula is a list of clauses, thought of as a conjunction like `(a ∨ b) ∧ c ∧ (¬c ∨ ¬d)`. -/ abbrev Fmla := List Clause /-- A single clause as a formula. -/ def Fmla.one (c : Clause) : Fmla := [c] /-- A conjunction of formulas. -/ def Fmla.and (a b : Fmla) : Fmla := a ++ b /-- Formula `f` subsumes `f'` if all the clauses in `f'` are in `f`. We use this to prove that all clauses in the formula are subsumed by it. -/ structure Fmla.subsumes (f f' : Fmla) : Prop where prop : ∀ x, x ∈ f' → x ∈ f theorem Fmla.subsumes_self (f : Fmla) : f.subsumes f := ⟨fun _ h ↦ h⟩ theorem Fmla.subsumes_left (f f₁ f₂ : Fmla) (H : f.subsumes (f₁.and f₂)) : f.subsumes f₁ := ⟨fun _ h ↦ H.1 _ <| List.mem_append.2 <| Or.inl h⟩ theorem Fmla.subsumes_right (f f₁ f₂ : Fmla) (H : f.subsumes (f₁.and f₂)) : f.subsumes f₂ := ⟨fun _ h ↦ H.1 _ <| List.mem_append.2 <| Or.inr h⟩ /-- A valuation is an assignment of values to all the propositional variables. -/ def Valuation := Nat → Prop /-- `v.neg lit` asserts that literal `lit` is falsified in the valuation. -/ def Valuation.neg (v : Valuation) : Literal → Prop | Literal.pos i => ¬ v i | Literal.neg i => v i /-- `v.satisfies c` asserts that clause `c` satisfied by the valuation. It is written in a negative way: A clause like `a ∨ ¬b ∨ c` is rewritten as `¬a → b → ¬c → False`, so we are asserting that it is not the case that all literals in the clause are falsified. -/ def Valuation.satisfies (v : Valuation) : Clause → Prop | [] => False | l::c => v.neg l → v.satisfies c /-- `v.satisfies_fmla f` asserts that formula `f` is satisfied by the valuation. A formula is satisfied if all clauses in it are satisfied. -/ structure Valuation.satisfies_fmla (v : Valuation) (f : Fmla) : Prop where prop : ∀ c, c ∈ f → v.satisfies c /-- `f.proof c` asserts that `c` is derivable from `f`. -/ def Fmla.proof (f : Fmla) (c : Clause) : Prop := ∀ v : Valuation, v.satisfies_fmla f → v.satisfies c /-- If `f` subsumes `c` (i.e. `c ∈ f`), then `f.proof c`. -/ theorem Fmla.proof_of_subsumes {f : Fmla} {c : Clause} (H : Fmla.subsumes f (Fmla.one c)) : f.proof c := fun _ h ↦ h.1 _ <| H.1 _ <| List.Mem.head .. /-- The core unit-propagation step. We have a local context of assumptions `¬l'` (sometimes called an assignment) and we wish to add `¬l` to the context, that is, we want to prove `l` is also falsified. This is because there is a clause `a ∨ b ∨ ¬l` in the global context such that all literals in the clause are falsified except for `¬l`; so in the context `h₁` where we suppose that `¬l` is falsified, the clause itself is falsified so we can prove `False`. We continue the proof in `h₂`, with the assumption that `l` is falsified. -/ theorem Valuation.by_cases {v : Valuation} {l} (h₁ : v.neg l.negate → False) (h₂ : v.neg l → False) : False := match l with | Literal.pos _ => h₂ h₁ | Literal.neg _ => h₁ h₂ /-- `v.implies p [a, b, c] 0` definitionally unfolds to `(v 0 ↔ a) → (v 1 ↔ b) → (v 2 ↔ c) → p`. This is used to introduce assumptions about the first `n` values of `v` during reification. -/ def Valuation.implies (v : Valuation) (p : Prop) : List Prop → Nat → Prop | [], _ => p | a::as, n => (v n ↔ a) → v.implies p as (n+1) /-- `Valuation.mk [a, b, c]` is a valuation which is `a` at 0, `b` at 1 and `c` at 2, and false everywhere else. -/ def Valuation.mk : List Prop → Valuation | [], _ => False | a::_, 0 => a | _::as, n+1 => mk as n /-- The fundamental relationship between `mk` and `implies`: `(mk ps).implies p ps 0` is equivalent to `p`. -/ theorem Valuation.mk_implies {p} {as ps} (as₁) : as = List.reverseAux as₁ ps → (Valuation.mk as).implies p ps as₁.length → p := by induction ps generalizing as₁ with | nil => exact fun _ ↦ id | cons a as ih => refine fun e H ↦ @ih (a::as₁) e (H ?_) subst e; clear ih H suffices ∀ n n', n' = List.length as₁ + n → ∀ bs, mk (as₁.reverseAux bs) n' ↔ mk bs n from this 0 _ rfl (a::as) induction as₁ with simp | cons b as₁ ih => exact fun n bs ↦ ih (n+1) _ (Nat.succ_add ..) _ /-- Asserts that `¬⟦f⟧_v` implies `p`. -/ structure Fmla.reify (v : Valuation) (f : Fmla) (p : Prop) : Prop where prop : ¬ v.satisfies_fmla f → p variable {v : Valuation} /-- If `f` is unsatisfiable, and every `v` which agrees with `ps` implies `¬⟦f⟧_v → p`, then `p`. Equivalently, there exists a valuation `v` which agrees with `ps`, and every such valuation yields `¬⟦f⟧_v` because `f` is unsatisfiable. -/ theorem Fmla.refute {p : Prop} {ps} (f : Fmla) (hf : f.proof []) (hv : ∀ v, Valuation.implies v (Fmla.reify v f p) ps 0) : p := (Valuation.mk_implies [] rfl (hv _)).1 (hf _) /-- Negation turns AND into OR, so `¬⟦f₁ ∧ f₂⟧_v ≡ ¬⟦f₁⟧_v ∨ ¬⟦f₂⟧_v`. -/ theorem Fmla.reify_or {f₁ : Fmla} {a : Prop} {f₂ : Fmla} {b : Prop} (h₁ : Fmla.reify v f₁ a) (h₂ : Fmla.reify v f₂ b) : Fmla.reify v (f₁.and f₂) (a ∨ b) := by refine ⟨fun H ↦ by_contra fun hn ↦ H ⟨fun c h ↦ by_contra fun hn' ↦ ?_⟩⟩ rcases List.mem_append.1 h with h | h · exact hn <| Or.inl <| h₁.1 fun Hc ↦ hn' <| Hc.1 _ h · exact hn <| Or.inr <| h₂.1 fun Hc ↦ hn' <| Hc.1 _ h /-- Asserts that `¬⟦c⟧_v` implies `p`. -/ structure Clause.reify (v : Valuation) (c : Clause) (p : Prop) : Prop where prop : ¬ v.satisfies c → p /-- Reification of a single clause formula. -/ theorem Fmla.reify_one {c : Clause} {a : Prop} (h : Clause.reify v c a) : Fmla.reify v (Fmla.one c) a := ⟨fun H ↦ h.1 fun h ↦ H ⟨fun | _, List.Mem.head .. => h⟩⟩ /-- Asserts that `¬⟦l⟧_v` implies `p`. -/ structure Literal.reify (v : Valuation) (l : Literal) (p : Prop) : Prop where prop : v.neg l → p /-- Negation turns OR into AND, so `¬⟦l ∨ c⟧_v ≡ ¬⟦l⟧_v ∧ ¬⟦c⟧_v`. -/ theorem Clause.reify_and {l : Literal} {a : Prop} {c : Clause} {b : Prop} (h₁ : Literal.reify v l a) (h₂ : Clause.reify v c b) : Clause.reify v (Clause.cons l c) (a ∧ b) := ⟨fun H ↦ ⟨h₁.1 (by_contra fun hn ↦ H hn.elim), h₂.1 fun h ↦ H fun _ ↦ h⟩⟩ /-- The reification of the empty clause is `True`: `¬⟦⊥⟧_v ≡ True`. -/ theorem Clause.reify_zero : Clause.reify v Clause.nil True := ⟨fun _ ↦ trivial⟩ /-- The reification of a singleton clause `¬⟦l⟧_v ≡ ¬⟦l⟧_v`. -/ theorem Clause.reify_one {l : Literal} {a : Prop} (h₁ : Literal.reify v l a) : Clause.reify v (Clause.nil.cons l) a := ⟨fun H ↦ ((Clause.reify_and h₁ Clause.reify_zero).1 H).1⟩ /-- The reification of a positive literal `¬⟦a⟧_v ≡ ¬a`. -/ theorem Literal.reify_pos {a : Prop} {n : ℕ} (h : v n ↔ a) : (Literal.pos n).reify v ¬a := ⟨mt h.2⟩ /-- The reification of a negative literal `¬⟦¬a⟧_v ≡ a`. -/ theorem Literal.reify_neg {a : Prop} {n : ℕ} (h : v n ↔ a) : (Literal.neg n).reify v a := ⟨h.1⟩ end Sat namespace Mathlib.Tactic.Sat /-- The representation of a global clause. -/ structure Clause where /-- The list of literals as read from the input file -/ lits : Array Int /-- The clause expression of type `Clause` -/ expr : Expr /-- A proof of `⊢ ctx.proof c`. Note that we do not use `have` statements to cache these proofs: this is literally the proof expression itself. As a result, the proof terms rely heavily on dag-like sharing of the expression, and printing these proof terms directly is likely to crash lean for larger examples. -/ proof : Expr /-- Construct the clause expression from the input list. For example `[1, -2]` is translated to `Clause.cons (Literal.pos 1) (Clause.cons (Literal.neg 2) Clause.nil)`. -/ def buildClause (arr : Array Int) : Expr := let nil := mkConst ``Sat.Clause.nil let cons := mkConst ``Sat.Clause.cons arr.foldr (fun i e ↦ mkApp2 cons (toExpr <| Sat.Literal.ofInt i) e) nil /-- Constructs the formula expression from the input CNF, as a balanced tree of `Fmla.and` nodes. -/ partial def buildConj (arr : Array (Array Int)) (start stop : Nat) : Expr := match stop - start with | 0 => panic! "empty" | 1 => mkApp (mkConst ``Sat.Fmla.one) (buildClause arr[start]!) | len => let mid := start + len / 2 mkApp2 (mkConst ``Sat.Fmla.and) (buildConj arr start mid) (buildConj arr mid stop) /-- Constructs the proofs of `⊢ ctx.proof c` for each clause `c` in `ctx`. The proofs are stashed in a `HashMap` keyed on the clause ID. -/ partial def buildClauses (arr : Array (Array Int)) (ctx : Expr) (start stop : Nat) (f p : Expr) (accum : Nat × HashMap Nat Clause) : Nat × HashMap Nat Clause := match stop - start with | 0 => panic! "empty" | 1 => let c := f.appArg! let proof := mkApp3 (mkConst ``Sat.Fmla.proof_of_subsumes) ctx c p let n := accum.1 + 1 (n, accum.2.insert n { lits := arr[start]!, expr := c, proof }) | len => let mid := start + len / 2 let f₁ := f.appFn!.appArg! let f₂ := f.appArg! let p₁ := mkApp4 (mkConst ``Sat.Fmla.subsumes_left) ctx f₁ f₂ p let p₂ := mkApp4 (mkConst ``Sat.Fmla.subsumes_right) ctx f₁ f₂ p let accum := buildClauses arr ctx start mid f₁ p₁ accum buildClauses arr ctx mid stop f₂ p₂ accum /-- A localized clause reference. It is the same as `Clause` except that the proof is now a local variable. -/ structure LClause where /-- The list of literals as read from the input file -/ lits : Array Int /-- The clause expression of type `Clause` -/ expr : Expr /-- The bound variable index of the hypothesis asserting `⊢ ctx.proof c`, _counting from the outside and 1-based_. (We use this numbering because we will need to reference the variable from multiple binder depths.) -/ depth : Nat /-- Construct an individual proof step `⊢ ctx.proof c`. * `db`: the current global context * `ns`, `clause`: the new clause * `pf`: the LRAT proof trace * `ctx`: the main formula The proof has three steps: 1. Introduce local assumptions `have h1 : ctx.proof c1 := p1` for each clause `c1` referenced in the proof. We actually do all the introductions at once, as in `(fun h1 h2 h3 ↦ ...) p1 p2 p3`, because we want `p_i` to not be under any binders to avoid the cost of `instantiate` during typechecking and get the benefits of dag-like sharing in the `pi` (which are themselves previous proof steps which may be large terms). The hypotheses are in `gctx`, keyed on the clause ID. 2. Unfold `⊢ ctx.proof [a, b, c]` to `∀ v, v.satisfies_fmla ctx → v.neg a → v.neg b → v.neg c → False` and `intro v hv ha hb hc`, storing each `ha : v.neg a` in `lctx`, keyed on the literal `a`. 3. For each LRAT step `hc : ctx.proof [x, y]`, `hc v hv : v.neg x → v.neg y → False`. We look for a literal that is not falsified in the clause. Since it is a unit propagation step, there can be at most one such literal. * If `x` is the non-falsified clause, let `x'` denote the negated literal of `x`. Then `x'.negate` reduces to `x`, so `hnx : v.neg x'.negate |- hc v hv hnx hy : False`, so we construct the term `by_cases (fun hnx : v.neg x'.negate ↦ hc v hv hnx hy) (fun hx : v.neg x ↦ ...)` and `hx` is added to the local context. * If all clauses are falsified, then we are done: `hc v hv hx hy : False`. -/ partial def buildProofStep (db : HashMap Nat Clause) (ns pf : Array Int) (ctx clause : Expr) : Except String Expr := Id.run do let mut lams := #[] let mut args := #[] let mut gctx : HashMap Nat LClause := {} -- step 1 for i in pf do let i := i.natAbs let some cl := db.find? i | return Except.error "missing clause" if !gctx.contains i then lams := lams.push (mkApp2 (mkConst ``Sat.Fmla.proof) ctx cl.expr) args := args.push cl.proof gctx := gctx.insert i { lits := cl.lits expr := cl.expr depth := args.size } let n := args.size -- step 2 let mut f := (mkAppN · args) ∘ lams.foldr (mkLambda `c default) ∘ mkLambda `v default (mkConst ``Sat.Valuation) ∘ mkLambda `hv default (mkApp2 (mkConst ``Sat.Valuation.satisfies_fmla) (mkBVar 0) ctx) let v depth := mkBVar (depth + 1) let hv depth := mkBVar depth lams := #[] let mut clause := clause let mut depth := 0 let mut lctx : HashMap Int Nat := {} for i in ns do let l := clause.appFn!.appArg! clause := clause.appArg! lams := lams.push (mkApp2 (mkConst ``Sat.Valuation.neg) (v depth) l) depth := depth.succ lctx := lctx.insert i depth f := f ∘ lams.foldr (mkLambda `h default) -- step 3 for (step : Int) in pf do if step < 0 then return Except.error "unimplemented: RAT step" let some cl := gctx.find? step.toNat | return Except.error "missing clause" let mut unit := none for i in cl.lits do unless lctx.contains i do if unit.isSome then return Except.error s!"not unit: {cl.lits}" depth := depth.succ unit := some i let mut pr := mkApp2 (mkBVar (depth + n + 2 - cl.depth)) (v depth) (hv depth) for i in cl.lits do pr := mkApp pr <| mkBVar (match lctx.find? i with | some k => depth - k | _ => 0) let some u := unit | return Except.ok <| f pr let lit := toExpr <| Sat.Literal.ofInt u let nlit := toExpr <| Sat.Literal.ofInt (-u) let d1 := depth-1 let app := mkApp3 (mkConst ``Sat.Valuation.by_cases) (v d1) nlit <| mkLambda `h default (mkApp2 (mkConst ``Sat.Valuation.neg) (v d1) lit) pr let dom := mkApp2 (mkConst ``Sat.Valuation.neg) (v d1) nlit f := fun e ↦ f <| mkApp app <| mkLambda `h default dom e lctx := lctx.insert (-u) depth return Except.error s!"no refutation: {ns}, {pf}, {lctx.toList}" /-- An LRAT step is either an addition or a deletion step. -/ inductive LRATStep | /-- An addition step, with the clause ID, the clause literal list, and the proof trace -/ add (id : Nat) (lits : Array Int) (proof : Array Int) : LRATStep | /-- A (multiple) deletion step, which deletes all the listed clause IDs from the context -/ del (ids : Array Nat) : LRATStep /-- Build the main proof of `⊢ ctx.proof []` using the LRAT proof trace. * `arr`: The input CNF * `ctx`: The abbreviated formula, a constant like `foo.ctx_1` * `ctx'`: The definitional expansion of the formula, a tree of `Fmla.and` nodes * `steps`: The input LRAT proof trace -/ partial def buildProof (arr : Array (Array Int)) (ctx ctx' : Expr) (steps : Array LRATStep) : MetaM Expr := do let p := mkApp (mkConst ``Sat.Fmla.subsumes_self) ctx let mut db := (buildClauses arr ctx 0 arr.size ctx' p default).2 for step in steps do match step with | LRATStep.del ds => db := ds.foldl (·.erase ·) db | LRATStep.add i ns pf => let e := buildClause ns match buildProofStep db ns pf ctx e with | Except.ok proof => if ns.isEmpty then return proof db := db.insert i { lits := ns, expr := e, proof } | Except.error msg => throwError msg throwError "failed to prove empty clause" /-- Build the type and value of the reified theorem. This rewrites all the SAT definitions into standard operators on `Prop`, for example if the formula is `[[1, 2], [-1, 2], [-2]]` then this produces a proof of `⊢ ∀ a b : Prop, (a ∧ b) ∨ (¬a ∧ b) ∨ ¬b`. We use the input `nvars` to decide how many quantifiers to use. Most of the proof is under `2 * nvars + 1` quantifiers `a1 .. an : Prop, v : Valuation, h1 : v 0 ↔ a1, ... hn : v (n-1) ↔ an ⊢ ...`, and we do the index arithmetic by hand. 1. First, we call `reifyFormula ctx'` which returns `a` and `pr : reify v ctx' a` 2. Then we build `fun (v : Valuation) (h1 : v 0 ↔ a1) ... (hn : v (n-1) ↔ an) ↦ pr` 3. We have to lower expression `a` from step 1 out of the quantifiers by lowering all variable indices by `nvars+1`. This is okay because `v` and `h1..hn` do not appear in `a`. 4. We construct the expression `ps`, which is `a1 .. an : Prop ⊢ [a1, ..., an] : List Prop` 5. `refute ctx (hf : ctx.proof []) (fun v h1 .. hn ↦ pr) : a` forces some definitional unfolding since `fun h1 .. hn ↦ pr` should have type `implies v (reify v ctx a) [a1, ..., an] a`, which involves unfolding `implies` n times as well as `ctx ↦ ctx'`. 6. Finally, we `intro a1 ... an` so that we have a proof of `∀ a1 ... an, a`. -/ partial def buildReify (ctx ctx' proof : Expr) (nvars : Nat) : Expr × Expr := Id.run do let (e, pr) := reifyFmla ctx' let mut pr := pr for i in [0:nvars] do let j := nvars-i-1 let ty := mkApp2 (mkConst ``Iff) (mkApp (mkBVar j) (mkRawNatLit j)) (mkBVar nvars) pr := mkLambda `h default ty pr pr := mkLambda `v default (mkConst ``Sat.Valuation) pr let mut e := e.lowerLooseBVars (nvars+1) (nvars+1) let cons := mkApp (mkConst ``List.cons [levelZero]) (mkSort levelZero) let nil := mkApp (mkConst ``List.nil [levelZero]) (mkSort levelZero) let rec mkPS depth e | 0 => e | n+1 => mkPS (depth+1) (mkApp2 cons (mkBVar depth) e) n pr := mkApp5 (mkConst ``Sat.Fmla.refute) e (mkPS 0 nil nvars) ctx proof pr for _ in [0:nvars] do e := mkForall `a default (mkSort levelZero) e pr := mkLambda `a default (mkSort levelZero) pr pure (e, pr) where /-- The `v` variable under the `a1 ... an, v, h1 ... hn` context -/ v := mkBVar nvars /-- Returns `a` and `pr : reify v f a` given a formula `f` -/ reifyFmla f := match f.getAppFn.constName! with | ``Sat.Fmla.and => let f₁ := f.appFn!.appArg! let f₂ := f.appArg! let (e₁, h₁) := reifyFmla f₁ let (e₂, h₂) := reifyFmla f₂ (mkApp2 (mkConst ``Or) e₁ e₂, mkApp7 (mkConst ``Sat.Fmla.reify_or) v f₁ e₁ f₂ e₂ h₁ h₂) | ``Sat.Fmla.one => let c := f.appArg! let (e, h) := reifyClause c (e, mkApp4 (mkConst ``Sat.Fmla.reify_one) v c e h) | _ => panic! "not a valid formula" /-- Returns `a` and `pr : reify v c a` given a clause `c` -/ reifyClause c := if c.appFn!.isConst then (mkConst ``True, mkApp (mkConst ``Sat.Clause.reify_zero) v) else reifyClause1 c /-- Returns `a` and `pr : reify v c a` given a nonempty clause `c` -/ reifyClause1 c := let l := c.appFn!.appArg! let c := c.appArg! let (e₁, h₁) := reifyLiteral l if c.isConst then (e₁, mkApp4 (mkConst ``Sat.Clause.reify_one) v l e₁ h₁) else let (e₂, h₂) := reifyClause1 c (mkApp2 (mkConst ``And) e₁ e₂, mkApp7 (mkConst ``Sat.Clause.reify_and) v l e₁ c e₂ h₁ h₂) /-- Returns `a` and `pr : reify v l a` given a literal `c` -/ reifyLiteral l := let n := l.appArg! let (e, h) := reifyVar n match l.appFn!.constName! with | ``Sat.Literal.pos => (mkApp (mkConst ``Not) e, mkApp4 (mkConst ``Sat.Literal.reify_pos) v e n h) | ``Sat.Literal.neg => (e, mkApp4 (mkConst ``Sat.Literal.reify_neg) v e n h) | _ => panic! "not a valid literal" /-- Returns `a` and `pr : v n ↔ a` given a variable index `n`. These are both lookups into the context `(a0 .. a(n-1) : Prop) (v) (h1 : v 0 ↔ a0) ... (hn : v (n-1) ↔ a(n-1))`. -/ reifyVar v := let n := v.rawNatLit?.get! (mkBVar (2 * nvars - n), mkBVar (nvars - n - 1)) open Lean namespace Parser open Lean Parsec /-- Parse a natural number -/ def parseNat : Parsec Nat := Json.Parser.natMaybeZero /-- Parse an integer -/ def parseInt : Parsec Int := do if (← peek!) = '-' then skip; pure <| -(← parseNat) else parseNat /-- Parse a list of integers terminated by 0 -/ partial def parseInts (arr : Array Int := #[]) : Parsec (Array Int) := do match ← parseInt <* ws with | 0 => pure arr | n => parseInts (arr.push n) /-- Parse a list of natural numbers terminated by 0 -/ partial def parseNats (arr : Array Nat := #[]) : Parsec (Array Nat) := do match ← parseNat <* ws with | 0 => pure arr | n => parseNats (arr.push n) /-- Parse a DIMACS format `.cnf` file. This is not very robust; we assume the file has had comments stripped. -/ def parseDimacs : Parsec (Nat × Array (Array Int)) := do pstring "p cnf" *> ws let nvars ← parseNat <* ws let nclauses ← parseNat <* ws let mut clauses := Array.mkEmpty nclauses for _ in [:nclauses] do clauses := clauses.push (← parseInts) pure (nvars, clauses) /-- Parse an LRAT file into a list of steps. -/ def parseLRAT : Parsec (Array LRATStep) := many do let step ← parseNat <* ws if (← peek!) = 'd' then skip <* ws; pure <| LRATStep.del (← parseNats) else ws; pure <| LRATStep.add step (← parseInts) (← parseInts) end Parser /-- Core of `fromLRAT`. Constructs the context and main proof definitions, but not the reification theorem. Returns: * `nvars`: the number of variables specified in the CNF file * `ctx`: The abbreviated formula, a constant like `foo.ctx_1` * `ctx'`: The definitional expansion of the formula, a tree of `Fmla.and` nodes * `proof`: A proof of `ctx.proof []` -/ def fromLRATAux (cnf lrat : String) (name : Name) : MetaM (Nat × Expr × Expr × Expr) := do let Parsec.ParseResult.success _ (nvars, arr) := Parser.parseDimacs cnf.mkIterator | throwError "parse CNF failed" if arr.isEmpty then throwError "empty CNF" let ctx' := buildConj arr 0 arr.size let ctxName ← mkAuxName (name ++ `ctx) 1 addDecl <| Declaration.defnDecl { name := ctxName levelParams := [] type := mkConst ``Sat.Fmla value := ctx' hints := ReducibilityHints.regular 0 safety := DefinitionSafety.safe } let ctx := mkConst ctxName let Parsec.ParseResult.success _ steps := Parser.parseLRAT lrat.mkIterator | throwError "parse LRAT failed" let proof ← buildProof arr ctx ctx' steps let declName ← mkAuxName (name ++ `proof) 1 addDecl <| Declaration.thmDecl { name := declName levelParams := [] type := mkApp2 (mkConst ``Sat.Fmla.proof) ctx (buildClause #[]) value := proof } return (nvars, ctx, ctx', mkConst declName) /-- Main entry point. Given strings `cnf` and `lrat` with unparsed file data, and a name `name`, adds `theorem name : type := proof` where `type` is a propositional theorem like `∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1`. Also creates auxiliaries named `name.ctx_1` (for the CNF formula) and `name.proof_1` (for the LRAT proof), with `name` itself containing the reification proof. -/ def fromLRAT (cnf lrat : String) (name : Name) : MetaM Unit := do let (nvars, ctx, ctx', proof) ← fromLRATAux cnf lrat name let (type, value) := buildReify ctx ctx' proof nvars addDecl <| Declaration.thmDecl { name, levelParams := [], type, value } open Elab Term /-- A macro for producing SAT proofs from CNF / LRAT files. These files are commonly used in the SAT community for writing proofs. The input to the `lrat_proof` command is the name of the theorem to define, and the statement (written in CNF format) and the proof (in LRAT format). For example: ``` lrat_proof foo "p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0" "5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0" ``` produces a theorem: ``` foo : ∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1 ``` * You can see the theorem statement by hovering over the word `foo`. * You can use the `example` keyword in place of `foo` to avoid generating a theorem. * You can use the `include_str` macro in place of the two strings to load CNF / LRAT files from disk. -/ elab "lrat_proof " n:(ident <|> "example") ppSpace cnf:term:max ppSpace lrat:term:max : command => do let name := (← getCurrNamespace) ++ if n.1.isIdent then n.1.getId else `_example Command.liftTermElabM do let cnf ← unsafe evalTerm String (mkConst ``String) cnf let lrat ← unsafe evalTerm String (mkConst ``String) lrat let go := do fromLRAT cnf lrat name withSaveInfoContext do Term.addTermInfo' n (mkConst name) (isBinder := true) if n.1.isIdent then go else withoutModifyingEnv go lrat_proof example -- The CNF file "p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0" -- The LRAT file "5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0" -- lrat_proof full2 -- (include_str "full2.cnf") -- (include_str "full2.lrat") /-- A macro for producing SAT proofs from CNF / LRAT files. These files are commonly used in the SAT community for writing proofs. The input to the `from_lrat` term syntax is two string expressions with the statement (written in CNF format) and the proof (in LRAT format). For example: ``` def foo := from_lrat "p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0" "5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0" ``` produces a theorem: ``` foo : ∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1 ``` * You can use this term after `have :=` or in `def foo :=` to produce the term without constraining the type. * You can use it when a specific type is expected, but it currently does not pay any attention to the shape of the goal and always produces the same theorem, so you can only use this to do alpha renaming. * You can use the `include_str` macro in place of the two strings to load CNF / LRAT files from disk. -/ elab "from_lrat " cnf:term:max ppSpace lrat:term:max : term => do let cnf ← unsafe evalTerm String (mkConst ``String) cnf let lrat ← unsafe evalTerm String (mkConst ``String) lrat let name ← mkAuxName `lrat fromLRAT cnf lrat name return mkConst name example : ∀ (a b : Prop), (¬a ∧ ¬b ∨ a ∧ ¬b) ∨ ¬a ∧ b ∨ a ∧ b := from_lrat "p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0" "5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0"
Tactic\Simps\Basic.lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Lean.Elab.Tactic.Simp import Lean.Elab.App import Mathlib.Tactic.Simps.NotationClass import Batteries.Data.String.Basic import Mathlib.Lean.Expr.Basic /-! # Simps attribute This file defines the `@[simps]` attribute, to automatically generate `simp` lemmas reducing a definition when projections are applied to it. ## Implementation Notes There are three attributes being defined here * `@[simps]` is the attribute for objects of a structure or instances of a class. It will automatically generate simplification lemmas for each projection of the object/instance that contains data. See the doc strings for `Lean.Parser.Attr.simps` and `Simps.Config` for more details and configuration options. * `structureExt` (just an environment extension, not actually an attribute) is automatically added to structures that have been used in `@[simps]` at least once. This attribute contains the data of the projections used for this structure by all following invocations of `@[simps]`. * `@[notation_class]` should be added to all classes that define notation, like `Mul` and `Zero`. This specifies that the projections that `@[simps]` used are the projections from these notation classes instead of the projections of the superclasses. Example: if `Mul` is tagged with `@[notation_class]` then the projection used for `Semigroup` will be `fun α hα ↦ @Mul.mul α (@Semigroup.toMul α hα)` instead of `@Semigroup.mul`. [this is not correctly implemented in Lean 4 yet] ### Possible Future Improvements * If multiple declarations are generated from a `simps` without explicit projection names, then only the first one is shown when mousing over `simps`. ## Changes w.r.t. Lean 3 There are some small changes in the attribute. None of them should have great effects * The attribute will now raise an error if it tries to generate a lemma when there already exists a lemma with that name (in Lean 3 it would generate a different unique name) * `transparency.none` has been replaced by `TransparencyMode.reducible` * The `attr` configuration option has been split into `isSimp` and `attrs` (for extra attributes) * Because Lean 4 uses bundled structures, this means that `simps` applied to anything that implements a notation class will almost certainly require a user-provided custom simps projection. ## Tags structures, projections, simp, simplifier, generates declarations -/ open Lean Elab Parser Command open Meta hiding Config open Elab.Term hiding mkConst /-- `updateName nm s isPrefix` adds `s` to the last component of `nm`, either as prefix or as suffix (specified by `isPrefix`), separated by `_`. Used by `simps_add_projections`. -/ def updateName (nm : Name) (s : String) (isPrefix : Bool) : Name := nm.updateLast fun s' ↦ if isPrefix then s ++ "_" ++ s' else s' ++ "_" ++ s -- move namespace Lean.Meta open Tactic Simp /-- Make `MkSimpContextResult` giving data instead of Syntax. Doesn't support arguments. Intended to be very similar to `Lean.Elab.Tactic.mkSimpContext` Todo: support arguments. -/ def mkSimpContextResult (cfg : Meta.Simp.Config := {}) (simpOnly := false) (kind := SimpKind.simp) (dischargeWrapper := DischargeWrapper.default) (hasStar := false) : MetaM MkSimpContextResult := do match dischargeWrapper with | .default => pure () | _ => if kind == SimpKind.simpAll then throwError "'simp_all' tactic does not support 'discharger' option" if kind == SimpKind.dsimp then throwError "'dsimp' tactic does not support 'discharger' option" let simpTheorems ← if simpOnly then simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) else getSimpTheorems let simprocs := #[← if simpOnly then pure {} else Simp.getSimprocs] let congrTheorems ← getSimpCongrTheorems let ctx : Simp.Context := { config := cfg simpTheorems := #[simpTheorems], congrTheorems } if !hasStar then return { ctx, simprocs, dischargeWrapper } else let mut simpTheorems := ctx.simpTheorems let hs ← getPropHyps for h in hs do unless simpTheorems.isErased (.fvar h) do simpTheorems ← simpTheorems.addTheorem (.fvar h) (← h.getDecl).toExpr let ctx := { ctx with simpTheorems } return { ctx, simprocs, dischargeWrapper } /-- Make `Simp.Context` giving data instead of Syntax. Doesn't support arguments. Intended to be very similar to `Lean.Elab.Tactic.mkSimpContext` Todo: support arguments. -/ def mkSimpContext (cfg : Meta.Simp.Config := {}) (simpOnly := false) (kind := SimpKind.simp) (dischargeWrapper := DischargeWrapper.default) (hasStar := false) : MetaM Simp.Context := do let data ← mkSimpContextResult cfg simpOnly kind dischargeWrapper hasStar return data.ctx end Lean.Meta /-- Tests whether `declName` has the `@[simp]` attribute in `env`. -/ def hasSimpAttribute (env : Environment) (declName : Name) : Bool := simpExtension.getState env |>.lemmaNames.contains <| .decl declName namespace Lean.Parser namespace Attr /-! Declare notation classes. -/ attribute [notation_class add] HAdd attribute [notation_class mul] HMul attribute [notation_class sub] HSub attribute [notation_class div] HDiv attribute [notation_class mod] HMod attribute [notation_class append] HAppend attribute [notation_class pow Simps.copyFirst] HPow attribute [notation_class andThen] HAndThen attribute [notation_class] Neg Dvd LE LT HasEquiv HasSubset HasSSubset Union Inter SDiff Insert Singleton Sep Membership attribute [notation_class one Simps.findOneArgs] OfNat attribute [notation_class zero Simps.findZeroArgs] OfNat /-- arguments to `@[simps]` attribute. -/ syntax simpsArgsRest := (Tactic.config)? (ppSpace ident)* /-- The `@[simps]` attribute automatically derives lemmas specifying the projections of this declaration. Example: ```lean @[simps] def foo : ℕ × ℤ := (1, 2) ``` derives two `simp` lemmas: ```lean @[simp] lemma foo_fst : foo.fst = 1 @[simp] lemma foo_snd : foo.snd = 2 ``` * It does not derive `simp` lemmas for the prop-valued projections. * It will automatically reduce newly created beta-redexes, but will not unfold any definitions. * If the structure has a coercion to either sorts or functions, and this is defined to be one of the projections, then this coercion will be used instead of the projection. * If the structure is a class that has an instance to a notation class, like `Neg` or `Mul`, then this notation is used instead of the corresponding projection. * You can specify custom projections, by giving a declaration with name `{StructureName}.Simps.{projectionName}`. See Note [custom simps projection]. Example: ```lean def Equiv.Simps.invFun (e : α ≃ β) : β → α := e.symm @[simps] def Equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ ``` generates ``` @[simp] lemma Equiv.trans_toFun : ∀ {α β γ} (e₁ e₂) (a : α), ⇑(e₁.trans e₂) a = (⇑e₂ ∘ ⇑e₁) a @[simp] lemma Equiv.trans_invFun : ∀ {α β γ} (e₁ e₂) (a : γ), ⇑((e₁.trans e₂).symm) a = (⇑(e₁.symm) ∘ ⇑(e₂.symm)) a ``` * You can specify custom projection names, by specifying the new projection names using `initialize_simps_projections`. Example: `initialize_simps_projections Equiv (toFun → apply, invFun → symm_apply)`. See `initialize_simps_projections` for more information. * If one of the fields itself is a structure, this command will recursively create `simp` lemmas for all fields in that structure. * Exception: by default it will not recursively create `simp` lemmas for fields in the structures `Prod`, `PProd`, and `Opposite`. You can give explicit projection names or change the value of `Simps.Config.notRecursive` to override this behavior. Example: ```lean structure MyProd (α β : Type*) := (fst : α) (snd : β) @[simps] def foo : Prod ℕ ℕ × MyProd ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩ ``` generates ```lean @[simp] lemma foo_fst : foo.fst = (1, 2) @[simp] lemma foo_snd_fst : foo.snd.fst = 3 @[simp] lemma foo_snd_snd : foo.snd.snd = 4 ``` * You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified projections. * Recursive projection names can be specified using `proj1_proj2_proj3`. This will create a lemma of the form `foo.proj1.proj2.proj3 = ...`. Example: ```lean structure MyProd (α β : Type*) := (fst : α) (snd : β) @[simps fst fst_fst snd] def foo : Prod ℕ ℕ × MyProd ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩ ``` generates ```lean @[simp] lemma foo_fst : foo.fst = (1, 2) @[simp] lemma foo_fst_fst : foo.fst.fst = 1 @[simp] lemma foo_snd : foo.snd = {fst := 3, snd := 4} ``` * If one of the values is an eta-expanded structure, we will eta-reduce this structure. Example: ```lean structure EquivPlusData (α β) extends α ≃ β where data : Bool @[simps] def EquivPlusData.rfl {α} : EquivPlusData α α := { Equiv.refl α with data := true } ``` generates the following: ```lean @[simp] lemma bar_toEquiv : ∀ {α : Sort*}, bar.toEquiv = Equiv.refl α @[simp] lemma bar_data : ∀ {α : Sort*}, bar.data = true ``` This is true, even though Lean inserts an eta-expanded version of `Equiv.refl α` in the definition of `bar`. * For configuration options, see the doc string of `Simps.Config`. * The precise syntax is `simps (config := e)? ident*`, where `e : Expr` is an expression of type `Simps.Config` and `ident*` is a list of desired projection names. * `@[simps]` reduces let-expressions where necessary. * When option `trace.simps.verbose` is true, `simps` will print the projections it finds and the lemmas it generates. The same can be achieved by using `@[simps?]`. * Use `@[to_additive (attr := simps)]` to apply both `to_additive` and `simps` to a definition This will also generate the additive versions of all `simp` lemmas. -/ /- If one of the fields is a partially applied constructor, we will eta-expand it (this likely never happens, so is not included in the official doc). -/ syntax (name := simps) "simps" "!"? "?"? simpsArgsRest : attr @[inherit_doc simps] macro "simps?" rest:simpsArgsRest : attr => `(attr| simps ? $rest) @[inherit_doc simps] macro "simps!" rest:simpsArgsRest : attr => `(attr| simps ! $rest) @[inherit_doc simps] macro "simps!?" rest:simpsArgsRest : attr => `(attr| simps ! ? $rest) @[inherit_doc simps] macro "simps?!" rest:simpsArgsRest : attr => `(attr| simps ! ? $rest) end Attr /-- Linter to check that `simps!` is used when needed -/ register_option linter.simpsNoConstructor : Bool := { defValue := true descr := "Linter to check that `simps!` is used" } /-- Linter to check that no unused custom declarations are declared for simps. -/ register_option linter.simpsUnusedCustomDeclarations : Bool := { defValue := true descr := "Linter to check that no unused custom declarations are declared for simps" } namespace Command /-- Syntax for renaming a projection in `initialize_simps_projections`. -/ syntax simpsRule.rename := ident " → " ident /-- Syntax for making a projection non-default in `initialize_simps_projections`. -/ syntax simpsRule.erase := "-" ident /-- Syntax for making a projection default in `initialize_simps_projections`. -/ syntax simpsRule.add := "+" ident /-- Syntax for making a projection prefix. -/ syntax simpsRule.prefix := &"as_prefix " ident /-- Syntax for a single rule in `initialize_simps_projections`. -/ syntax simpsRule := simpsRule.prefix <|> simpsRule.rename <|> simpsRule.erase <|> simpsRule.add /-- Syntax for `initialize_simps_projections`. -/ syntax simpsProj := ppSpace ident (" (" simpsRule,+ ")")? /-- This command specifies custom names and custom projections for the simp attribute `simpsAttr`. * You can specify custom names by writing e.g. `initialize_simps_projections Equiv (toFun → apply, invFun → symm_apply)`. * See Note [custom simps projection] and the examples below for information how to declare custom projections. * For algebraic structures, we will automatically use the notation (like `Mul`) for the projections if such an instance is available. * By default, the projections to parent structures are not default projections, but all the data-carrying fields are (including those in parent structures). * You can disable a projection by default by running `initialize_simps_projections Equiv (-invFun)` This will ensure that no simp lemmas are generated for this projection, unless this projection is explicitly specified by the user. * Conversely, you can enable a projection by default by running `initialize_simps_projections Equiv (+toEquiv)`. * If you want the projection name added as a prefix in the generated lemma name, you can use `as_prefix fieldName`: `initialize_simps_projections Equiv (toFun → coe, as_prefix coe)` Note that this does not influence the parsing of projection names: if you have a declaration `foo` and you want to apply the projections `snd`, `coe` (which is a prefix) and `fst`, in that order you can run `@[simps snd_coe_fst] def foo ...` and this will generate a lemma with the name `coe_foo_snd_fst`. * Run `initialize_simps_projections?` (or `set_option trace.simps.verbose true`) to see the generated projections. * Running `initialize_simps_projections MyStruc` without arguments is not necessary, it has the same effect if you just add `@[simps]` to a declaration. * It is recommended to call `@[simps]` or `initialize_simps_projections` in the same file as the structure declaration. Otherwise, the projections could be generated multiple times in different files. Some common uses: * If you define a new homomorphism-like structure (like `MulHom`) you can just run `initialize_simps_projections` after defining the `DFunLike` instance (or instance that implies a `DFunLike` instance). ``` instance {mM : Mul M} {mN : Mul N} : DFunLike (MulHom M N) M N := ... initialize_simps_projections MulHom (toFun → apply) ``` This will generate `foo_apply` lemmas for each declaration `foo`. * If you prefer `coe_foo` lemmas that state equalities between functions, use `initialize_simps_projections MulHom (toFun → coe, as_prefix coe)` In this case you have to use `@[simps (config := .asFn)]` or equivalently `@[simps (config := .asFn)]` whenever you call `@[simps]`. * You can also initialize to use both, in which case you have to choose which one to use by default, by using either of the following ``` initialize_simps_projections MulHom (toFun → apply, toFun → coe, as_prefix coe, -coe) initialize_simps_projections MulHom (toFun → apply, toFun → coe, as_prefix coe, -apply) ``` In the first case, you can get both lemmas using `@[simps, simps (config := .asFn) coe]` and in the second case you can get both lemmas using `@[simps (config := .asFn), simps apply]`. * If you declare a new homomorphism-like structure (like `RelEmbedding`), then `initialize_simps_projections` will automatically find any `DFunLike` coercions that will be used as the default projection for the `toFun` field. ``` initialize_simps_projections relEmbedding (toFun → apply) ``` * If you have an isomorphism-like structure (like `Equiv`) you often want to define a custom projection for the inverse: ``` def Equiv.Simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections Equiv (toFun → apply, invFun → symm_apply) ``` -/ syntax (name := initialize_simps_projections) "initialize_simps_projections" "?"? simpsProj : command @[inherit_doc «initialize_simps_projections»] macro "initialize_simps_projections?" rest:simpsProj : command => `(initialize_simps_projections ? $rest) end Command end Lean.Parser initialize registerTraceClass `simps.verbose initialize registerTraceClass `simps.debug namespace Simps /-- Projection data for a single projection of a structure -/ structure ProjectionData where /-- The name used in the generated `simp` lemmas -/ name : Name /-- An Expression used by simps for the projection. It must be definitionally equal to an original projection (or a composition of multiple projections). These Expressions can contain the universe parameters specified in the first argument of `structureExt`. -/ expr : Expr /-- A list of natural numbers, which is the projection number(s) that have to be applied to the Expression. For example the list `[0, 1]` corresponds to applying the first projection of the structure, and then the second projection of the resulting structure (this assumes that the target of the first projection is a structure with at least two projections). The composition of these projections is required to be definitionally equal to the provided Expression. -/ projNrs : List Nat /-- A boolean specifying whether `simp` lemmas are generated for this projection by default. -/ isDefault : Bool /-- A boolean specifying whether this projection is written as prefix. -/ isPrefix : Bool deriving Inhabited instance : ToMessageData ProjectionData where toMessageData | ⟨a, b, c, d, e⟩ => .group <| .nest 1 <| "⟨" ++ .joinSep [toMessageData a, toMessageData b, toMessageData c, toMessageData d, toMessageData e] ("," ++ Format.line) ++ "⟩" /-- The `Simps.structureExt` environment extension specifies the preferred projections of the given structure, used by the `@[simps]` attribute. - You can generate this with the command `initialize_simps_projections`. - If not generated, the `@[simps]` attribute will generate this automatically. - To change the default value, see Note [custom simps projection]. - The first argument is the list of names of the universe variables used in the structure - The second argument is an array that consists of the projection data for each projection. -/ initialize structureExt : NameMapExtension (List Name × Array ProjectionData) ← registerNameMapExtension (List Name × Array ProjectionData) /-- Projection data used internally in `getRawProjections`. -/ structure ParsedProjectionData where /-- name for this projection used in the structure definition -/ strName : Name /-- syntax that might have provided `strName` -/ strStx : Syntax := .missing /-- name for this projection used in the generated `simp` lemmas -/ newName : Name /-- syntax that provided `newName` -/ newStx : Syntax := .missing /-- will simp lemmas be generated for with (without specifically naming this?) -/ isDefault : Bool := true /-- is the projection name a prefix? -/ isPrefix : Bool := false /-- projection expression -/ expr? : Option Expr := none /-- the list of projection numbers this expression corresponds to -/ projNrs : Array Nat := #[] /-- is this a projection that is changed by the user? -/ isCustom : Bool := false /-- Turn `ParsedProjectionData` into `ProjectionData`. -/ def ParsedProjectionData.toProjectionData (p : ParsedProjectionData) : ProjectionData := { p with name := p.newName, expr := p.expr?.getD default, projNrs := p.projNrs.toList } instance : ToMessageData ParsedProjectionData where toMessageData | ⟨x₁, x₂, x₃, x₄, x₅, x₆, x₇, x₈, x₉⟩ => .group <| .nest 1 <| "⟨" ++ .joinSep [toMessageData x₁, toMessageData x₂, toMessageData x₃, toMessageData x₄, toMessageData x₅, toMessageData x₆, toMessageData x₇, toMessageData x₈, toMessageData x₉] ("," ++ Format.line) ++ "⟩" /-- The type of rules that specify how metadata for projections in changes. See `initialize_simps_projections`. -/ inductive ProjectionRule where /-- A renaming rule `before→after` or Each name comes with the syntax used to write the rule, which is used to declare hover information. -/ | rename (oldName : Name) (oldStx : Syntax) (newName : Name) (newStx : Syntax) : ProjectionRule /-- An adding rule `+fieldName` -/ | add : Name → Syntax → ProjectionRule /-- A hiding rule `-fieldName` -/ | erase : Name → Syntax → ProjectionRule /-- A prefix rule `prefix fieldName` -/ | prefix : Name → Syntax → ProjectionRule instance : ToMessageData ProjectionRule where toMessageData | .rename x₁ x₂ x₃ x₄ => .group <| .nest 1 <| "rename ⟨" ++ .joinSep [toMessageData x₁, toMessageData x₂, toMessageData x₃, toMessageData x₄] ("," ++ Format.line) ++ "⟩" | .add x₁ x₂ => .group <| .nest 1 <| "+⟨" ++ .joinSep [toMessageData x₁, toMessageData x₂] ("," ++ Format.line) ++ "⟩" | .erase x₁ x₂ => .group <| .nest 1 <| "-⟨" ++ .joinSep [toMessageData x₁, toMessageData x₂] ("," ++ Format.line) ++ "⟩" | .prefix x₁ x₂ => .group <| .nest 1 <| "prefix ⟨" ++ .joinSep [toMessageData x₁, toMessageData x₂] ("," ++ Format.line) ++ "⟩" /-- Returns the projection information of a structure. -/ def projectionsInfo (l : List ProjectionData) (pref : String) (str : Name) : MessageData := let ⟨defaults, nondefaults⟩ := l.partition (·.isDefault) let toPrint : List MessageData := defaults.map fun s ↦ let prefixStr := if s.isPrefix then "(prefix) " else "" m!"Projection {prefixStr}{s.name}: {s.expr}" let print2 : MessageData := String.join <| (nondefaults.map fun nm : ProjectionData ↦ toString nm.1).intersperse ", " let toPrint := toPrint ++ if nondefaults.isEmpty then [] else [("No lemmas are generated for the projections: " : MessageData) ++ print2 ++ "."] let toPrint := MessageData.joinSep toPrint ("\n" : MessageData) m!"{pref} {str}:\n{toPrint}" /-- Find the indices of the projections that need to be applied to elaborate `$e.$projName`. Example: If `e : α ≃+ β` and ``projName = `invFun`` then this returns `[0, 1]`, because the first projection of `MulEquiv` is `toEquiv` and the second projection of `Equiv` is `invFun`. -/ def findProjectionIndices (strName projName : Name) : MetaM (List Nat) := do let env ← getEnv let .some baseStr := findField? env strName projName | throwError "{strName} has no field {projName} in parent structure" let .some fullProjName := getProjFnForField? env baseStr projName | throwError "no such field {projName}" let .some pathToField := getPathToBaseStructure? env baseStr strName | throwError "no such field {projName}" let allProjs := pathToField ++ [fullProjName] return allProjs.map (env.getProjectionFnInfo? · |>.get!.i) /-- A variant of `Substring.dropPrefix?` that does not consider `toFoo` to be a prefix to `toFoo_1`. This is checked by inspecting whether the first character of the remaining part is a digit. We use this variant because the latter is often a different field with an auto-generated name. -/ private def dropPrefixIfNotNumber? (s : String) (pre : Substring) : Option Substring := do let ret ← Substring.dropPrefix? s pre -- flag is true when the remaning part is nonempty and starts with a digit. let flag := ret.toString.data.head?.elim false Char.isDigit if flag then none else some ret /-- A variant of `String.isPrefixOf` that does not consider `toFoo` to be a prefix to `toFoo_1`. -/ private def isPrefixOfAndNotNumber (s p : String) : Bool := (dropPrefixIfNotNumber? p s).isSome /-- A variant of `String.splitOn` that does not split `toFoo_1` into `toFoo` and `1`. -/ private def splitOnNotNumber (s delim : String) : List String := (process (s.splitOn delim).reverse "").reverse where process (arr : List String) (tail : String) := match arr with | [] => [] | (x :: xs) => -- flag is true when this segment is nonempty and starts with a digit. let flag := x.data.head?.elim false Char.isDigit if flag then process xs (tail ++ delim ++ x) else List.cons (x ++ tail) (process xs "") /-- Auxiliary function of `getCompositeOfProjections`. -/ partial def getCompositeOfProjectionsAux (proj : String) (e : Expr) (pos : Array Nat) (args : Array Expr) : MetaM (Expr × Array Nat) := do let env ← getEnv let .const structName _ := (← whnf (← inferType e)).getAppFn | throwError "{e} doesn't have a structure as type" let projs := getStructureFieldsFlattened env structName let projInfo := projs.toList.map fun p ↦ do ((← dropPrefixIfNotNumber? proj (p.lastComponentAsString ++ "_")).toString, p) let some (projRest, projName) := projInfo.reduceOption.getLast? | throwError "Failed to find constructor {proj.dropRight 1} in structure {structName}." let newE ← mkProjection e projName let newPos := pos ++ (← findProjectionIndices structName projName) -- we do this here instead of in a recursive call in order to not get an unnecessary eta-redex if projRest.isEmpty then let newE ← mkLambdaFVars args newE return (newE, newPos) let type ← inferType newE forallTelescopeReducing type fun typeArgs _tgt ↦ do getCompositeOfProjectionsAux projRest (mkAppN newE typeArgs) newPos (args ++ typeArgs) /-- Suppose we are given a structure `str` and a projection `proj`, that could be multiple nested projections (separated by `_`), where each projection could be a projection of a parent structure. This function returns an expression that is the composition of these projections and a list of natural numbers, that are the projection numbers of the applied projections. Note that this function is similar to elaborating dot notation, but it can do a little more. Example: if we do ``` structure gradedFun (A : ℕ → Type*) where toFun := ∀ i j, A i →+ A j →+ A (i + j) initialize_simps_projections (toFun_toFun_toFun → myMul) ``` we will be able to generate the "projection" `λ {A} (f : gradedFun A) (x : A i) (y : A j) ↦ ↑(↑(f.toFun i j) x) y`, which projection notation cannot do. -/ def getCompositeOfProjections (structName : Name) (proj : String) : MetaM (Expr × Array Nat) := do let strExpr ← mkConstWithLevelParams structName let type ← inferType strExpr forallTelescopeReducing type fun typeArgs _ ↦ withLocalDeclD `x (mkAppN strExpr typeArgs) fun e ↦ getCompositeOfProjectionsAux (proj ++ "_") e #[] <| typeArgs.push e /-- Get the default `ParsedProjectionData` for structure `str`. It first returns the direct fields of the structure in the right order, and then all (non-subobject fields) of all parent structures. The subobject fields are precisely the non-default fields. -/ def mkParsedProjectionData (structName : Name) : CoreM (Array ParsedProjectionData) := do let env ← getEnv let projs := getStructureFields env structName if projs.size == 0 then throwError "Declaration {structName} is not a structure." let projData := projs.map fun fieldName ↦ { strName := fieldName, newName := fieldName, isDefault := isSubobjectField? env structName fieldName |>.isNone } let parentProjs := getStructureFieldsFlattened env structName false let parentProjs := parentProjs.filter (!projs.contains ·) let parentProjData := parentProjs.map fun nm ↦ {strName := nm, newName := nm} return projData ++ parentProjData /-- Execute the projection renamings (and turning off projections) as specified by `rules`. -/ def applyProjectionRules (projs : Array ParsedProjectionData) (rules : Array ProjectionRule) : CoreM (Array ParsedProjectionData) := do let projs : Array ParsedProjectionData := rules.foldl (init := projs) fun projs rule ↦ match rule with | .rename strName strStx newName newStx => if (projs.map (·.newName)).contains strName then projs.map fun proj ↦ if proj.newName == strName then { proj with newName, newStx, strStx := if proj.strStx.isMissing then strStx else proj.strStx } else proj else projs.push {strName, strStx, newName, newStx} | .erase nm stx => if (projs.map (·.newName)).contains nm then projs.map fun proj ↦ if proj.newName = nm then { proj with isDefault := false, strStx := if proj.strStx.isMissing then stx else proj.strStx } else proj else projs.push {strName := nm, newName := nm, strStx := stx, newStx := stx, isDefault := false} | .add nm stx => if (projs.map (·.newName)).contains nm then projs.map fun proj ↦ if proj.newName = nm then { proj with isDefault := true, strStx := if proj.strStx.isMissing then stx else proj.strStx } else proj else projs.push {strName := nm, newName := nm, strStx := stx, newStx := stx} | .prefix nm stx => if (projs.map (·.newName)).contains nm then projs.map fun proj ↦ if proj.newName = nm then { proj with isPrefix := true, strStx := if proj.strStx.isMissing then stx else proj.strStx } else proj else projs.push {strName := nm, newName := nm, strStx := stx, newStx := stx, isPrefix := true} trace[simps.debug] "Projection info after applying the rules: {projs}." unless (projs.map (·.newName)).toList.Nodup do throwError "\ Invalid projection names. Two projections have the same name.\n\ This is likely because a custom composition of projections was given the same name as an \ existing projection. Solution: rename the existing projection (before naming the \ custom projection)." pure projs /-- Auxiliary function for `getRawProjections`. Generates the default projection, and looks for a custom projection declared by the user, and replaces the default projection with the custom one, if it can find it. -/ def findProjection (str : Name) (proj : ParsedProjectionData) (rawUnivs : List Level) : CoreM ParsedProjectionData := do let env ← getEnv let (rawExpr, nrs) ← MetaM.run' <| getCompositeOfProjections str proj.strName.lastComponentAsString if !proj.strStx.isMissing then _ ← MetaM.run' <| TermElabM.run' <| addTermInfo proj.strStx rawExpr trace[simps.debug] "Projection {proj.newName} has default projection {rawExpr} and uses projection indices {nrs}" let customName := str ++ `Simps ++ proj.newName match env.find? customName with | some d@(.defnInfo _) => let customProj := d.instantiateValueLevelParams! rawUnivs trace[simps.verbose] "found custom projection for {proj.newName}:{indentExpr customProj}" match (← MetaM.run' <| isDefEq customProj rawExpr) with | true => _ ← MetaM.run' <| TermElabM.run' <| addTermInfo proj.newStx <| ← mkConstWithLevelParams customName pure { proj with expr? := some customProj, projNrs := nrs, isCustom := true } | false => -- if the type of the Expression is different, we show a different error message, because -- (in Lean 3) just stating that the expressions are different is quite unhelpful let customProjType ← MetaM.run' (inferType customProj) let rawExprType ← MetaM.run' (inferType rawExpr) if (← MetaM.run' (isDefEq customProjType rawExprType)) then throwError "Invalid custom projection:{indentExpr customProj}\n\ Expression is not definitionally equal to {indentExpr rawExpr}" else throwError "Invalid custom projection:{indentExpr customProj}\n\ Expression has different type than {str ++ proj.strName}. Given type:\ {indentExpr customProjType}\nExpected type:{indentExpr rawExprType}\n\ Note: make sure order of implicit arguments is exactly the same." | _ => _ ← MetaM.run' <| TermElabM.run' <| addTermInfo proj.newStx rawExpr pure {proj with expr? := some rawExpr, projNrs := nrs} /-- Checks if there are declarations in the current file in the namespace `{str}.Simps` that are not used. -/ def checkForUnusedCustomProjs (stx : Syntax) (str : Name) (projs : Array ParsedProjectionData) : CoreM Unit := do let nrCustomProjections := projs.toList.countP (·.isCustom) let env ← getEnv let customDeclarations := env.constants.map₂.foldl (init := #[]) fun xs nm _ => if (str ++ `Simps).isPrefixOf nm && !nm.isInternalDetail && !isReservedName env nm then xs.push nm else xs if nrCustomProjections < customDeclarations.size then Linter.logLintIf linter.simpsUnusedCustomDeclarations stx m!"\ Not all of the custom declarations {customDeclarations} are used. Double check the \ spelling, and use `?` to get more information." /-- If a structure has a field that corresponds to a coercion to functions or sets, or corresponds to notation, find the custom projection that uses this coercion or notation. Returns the custom projection and the name of the projection used. We catch most errors this function causes, so that we don't fail if an unrelated projection has an applicable name. (e.g. `Iso.inv`) Implementation note: getting rid of TermElabM is tricky, since `Expr.mkAppOptM` doesn't allow to keep metavariables around, which are necessary for `OutParam`. -/ def findAutomaticProjectionsAux (str : Name) (proj : ParsedProjectionData) (args : Array Expr) : TermElabM <| Option (Expr × Name) := do if let some ⟨className, isNotation, findArgs⟩ := notationClassAttr.find? (← getEnv) proj.strName then let findArgs ← unsafe evalConst findArgType findArgs let classArgs ← try findArgs str className args catch ex => trace[simps.debug] "Projection {proj.strName} is likely unrelated to the projection of \ {className}:\n{ex.toMessageData}" return none let classArgs ← classArgs.mapM fun e => match e with | none => mkFreshExprMVar none | some e => pure e let classArgs := classArgs.map Arg.expr let projName := (getStructureFields (← getEnv) className)[0]! let projName := className ++ projName let eStr := mkAppN (← mkConstWithLevelParams str) args let eInstType ← try withoutErrToSorry (elabAppArgs (← Term.mkConst className) #[] classArgs none true false) catch ex => trace[simps.debug] "Projection doesn't have the right type for the automatic projection:\n\ {ex.toMessageData}" return none return ← withLocalDeclD `self eStr fun instStr ↦ do trace[simps.debug] "found projection {proj.strName}. Trying to synthesize {eInstType}." let eInst ← try synthInstance eInstType catch ex => trace[simps.debug] "Didn't find instance:\n{ex.toMessageData}" return none let projExpr ← elabAppArgs (← Term.mkConst projName) #[] (classArgs.push <| .expr eInst) none true false let projExpr ← mkLambdaFVars (if isNotation then args.push instStr else args) projExpr let projExpr ← instantiateMVars projExpr return (projExpr, projName) return none /-- Auxiliary function for `getRawProjections`. Find custom projections, automatically found by simps. These come from `DFunLike` and `SetLike` instances. -/ def findAutomaticProjections (str : Name) (projs : Array ParsedProjectionData) : CoreM (Array ParsedProjectionData) := do let strDecl ← getConstInfo str trace[simps.debug] "debug: {projs}" MetaM.run' <| TermElabM.run' (s := {levelNames := strDecl.levelParams}) <| forallTelescope strDecl.type fun args _ ↦ do let projs ← projs.mapM fun proj => do if let some (projExpr, projName) := ← findAutomaticProjectionsAux str proj args then unless ← isDefEq projExpr proj.expr?.get! do throwError "The projection {proj.newName} is not definitionally equal to an application \ of {projName}:{indentExpr proj.expr?.get!}\nvs{indentExpr projExpr}" if proj.isCustom then trace[simps.verbose] "Warning: Projection {proj.newName} is given manually by the user, \ but it can be generated automatically." return proj trace[simps.verbose] "Using {indentExpr projExpr}\nfor projection {proj.newName}." return { proj with expr? := some projExpr } return proj return projs /-- Get the projections used by `simps` associated to a given structure `str`. The returned information is also stored in the environment extension `Simps.structureExt`, which is given to `str`. If `str` already has this attribute, the information is read from this extension instead. See the documentation for this extension for the data this tactic returns. The returned universe levels are the universe levels of the structure. For the projections there are three cases * If the declaration `{StructureName}.Simps.{projectionName}` has been declared, then the value of this declaration is used (after checking that it is definitionally equal to the actual projection. If you rename the projection name, the declaration should have the *new* projection name. * You can also declare a custom projection that is a composite of multiple projections. * Otherwise, for every class with the `notation_class` attribute, and the structure has an instance of that notation class, then the projection of that notation class is used for the projection that is definitionally equal to it (if there is such a projection). This means in practice that coercions to function types and sorts will be used instead of a projection, if this coercion is definitionally equal to a projection. Furthermore, for notation classes like `Mul` and `Zero` those projections are used instead of the corresponding projection. Projections for coercions and notation classes are not automatically generated if they are composites of multiple projections (for example when you use `extend` without the `oldStructureCmd` (does this exist?)). * Otherwise, the projection of the structure is chosen. For example: ``getRawProjections env `Prod`` gives the default projections. ``` ([u, v], [(`fst, `(Prod.fst.{u v}), [0], true, false), (`snd, `(@Prod.snd.{u v}), [1], true, false)]) ``` Optionally, this command accepts three optional arguments: * If `traceIfExists` the command will always generate a trace message when the structure already has an entry in `structureExt`. * The `rules` argument specifies whether projections should be added, renamed, used as prefix, and not used by default. * if `trc` is true, this tactic will trace information just as if `set_option trace.simps.verbose true` was set. -/ def getRawProjections (stx : Syntax) (str : Name) (traceIfExists : Bool := false) (rules : Array ProjectionRule := #[]) (trc := false) : CoreM (List Name × Array ProjectionData) := do withOptions (· |>.updateBool `trace.simps.verbose (trc || ·)) <| do let env ← getEnv if let some data := (structureExt.getState env).find? str then -- We always print the projections when they already exists and are called by -- `initialize_simps_projections`. withOptions (· |>.updateBool `trace.simps.verbose (traceIfExists || ·)) <| do trace[simps.debug] projectionsInfo data.2.toList "Already found projection information for structure" str return data trace[simps.verbose] "generating projection information for structure {str}." trace[simps.debug] "Applying the rules {rules}." let strDecl ← getConstInfo str let rawLevels := strDecl.levelParams let rawUnivs := rawLevels.map Level.param let projs ← mkParsedProjectionData str let projs ← applyProjectionRules projs rules let projs ← projs.mapM fun proj ↦ findProjection str proj rawUnivs checkForUnusedCustomProjs stx str projs let projs ← findAutomaticProjections str projs let projs := projs.map (·.toProjectionData) -- make all proofs non-default. let projs ← projs.mapM fun proj ↦ do match (← MetaM.run' <| isProof proj.expr) with | true => pure { proj with isDefault := false } | false => pure proj trace[simps.verbose] projectionsInfo projs.toList "generated projections for" str structureExt.add str (rawLevels, projs) trace[simps.debug] "Generated raw projection data:{indentD <| toMessageData (rawLevels, projs)}" pure (rawLevels, projs) library_note "custom simps projection"/-- You can specify custom projections for the `@[simps]` attribute. To do this for the projection `MyStructure.originalProjection` by adding a declaration `MyStructure.Simps.myProjection` that is definitionally equal to `MyStructure.originalProjection` but has the projection in the desired (simp-normal) form. Then you can call ``` initialize_simps_projections (originalProjection → myProjection, ...) ``` to register this projection. See `elabInitializeSimpsProjections` for more information. You can also specify custom projections that are definitionally equal to a composite of multiple projections. This is often desirable when extending structures (without `oldStructureCmd`). `CoeFun` and notation class (like `Mul`) instances will be automatically used, if they are definitionally equal to a projection of the structure (but not when they are equal to the composite of multiple projections). -/ /-- Parse a rule for `initialize_simps_projections`. It is `<name>→<name>`, `-<name>`, `+<name>` or `as_prefix <name>`. -/ def elabSimpsRule : Syntax → CommandElabM ProjectionRule | `(simpsRule| $id1 → $id2) => return .rename id1.getId id1.raw id2.getId id2.raw | `(simpsRule| - $id) => return .erase id.getId id.raw | `(simpsRule| + $id) => return .add id.getId id.raw | `(simpsRule| as_prefix $id) => return .prefix id.getId id.raw | _ => Elab.throwUnsupportedSyntax /-- Function elaborating `initialize_simps_projections`. -/ @[command_elab «initialize_simps_projections»] def elabInitializeSimpsProjections : CommandElab | stx@`(initialize_simps_projections $[?%$trc]? $id $[($stxs,*)]?) => do let stxs := stxs.getD <| .mk #[] let rules ← stxs.getElems.raw.mapM elabSimpsRule let nm ← resolveGlobalConstNoOverload id _ ← liftTermElabM <| addTermInfo id.raw <| ← mkConstWithLevelParams nm _ ← liftCoreM <| getRawProjections stx nm true rules trc.isSome | _ => throwUnsupportedSyntax /-- Configuration options for `@[simps]` -/ structure Config where /-- Make generated lemmas simp lemmas -/ isSimp := true /-- Other simp-attributes to apply to generated lemmas. Attributes that are currently not simp-attributes are not supported. -/ attrs : List Name := [] /-- simplify the right-hand side of generated simp-lemmas using `dsimp, simp`. -/ simpRhs := false /-- TransparencyMode used to reduce the type in order to detect whether it is a structure. -/ typeMd := TransparencyMode.instances /-- TransparencyMode used to reduce the right-hand side in order to detect whether it is a constructor. Note: was `none` in Lean 3 -/ rhsMd := TransparencyMode.reducible /-- Generated lemmas that are fully applied, i.e. generates equalities between applied functions. Set this to `false` to generate equalities between functions. -/ fullyApplied := true /-- List of types in which we are not recursing to generate simplification lemmas. E.g. if we write `@[simps] def e : α × β ≃ β × α := ...` we will generate `e_apply` and not `e_apply_fst`. -/ notRecursive := [`Prod, `PProd, `Opposite, `PreOpposite] /-- Output debug messages. Not used much, use `set_option simps.debug true` instead. -/ debug := false deriving Inhabited /-- Function elaborating `Config` -/ declare_config_elab elabSimpsConfig Config /-- A common configuration for `@[simps]`: generate equalities between functions instead equalities between fully applied Expressions. Use this using `@[simps (config := .asFn)]`. -/ def Config.asFn : Simps.Config where fullyApplied := false /-- A common configuration for `@[simps]`: don't tag the generated lemmas with `@[simp]`. Use this using `@[simps (config := .lemmasOnly)]`. -/ def Config.lemmasOnly : Config where isSimp := false /-- `instantiateLambdasOrApps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. This is very similar to `expr.substs`, but this also reduces head let-expressions. -/ partial def _root_.Lean.Expr.instantiateLambdasOrApps (es : Array Expr) (e : Expr) : Expr := e.betaRev es.reverse true -- check if this is what I want /-- Get the projections of a structure used by `@[simps]` applied to the appropriate arguments. Returns a list of tuples ``` (corresponding right-hand-side, given projection name, projection Expression, future projection numbers, used by default, is prefix) ``` (where all fields except the first are packed in a `ProjectionData` structure) one for each projection. The given projection name is the name for the projection used by the user used to generate (and parse) projection names. For example, in the structure Example 1: ``getProjectionExprs env `(α × β) `(⟨x, y⟩)`` will give the output ``` [(`(x), `fst, `(@Prod.fst.{u v} α β), [], true, false), (`(y), `snd, `(@Prod.snd.{u v} α β), [], true, false)] ``` Example 2: ``getProjectionExprs env `(α ≃ α) `(⟨id, id, fun _ ↦ rfl, fun _ ↦ rfl⟩)`` will give the output ``` [(`(id), `apply, (Equiv.toFun), [], true, false), (`(id), `symm_apply, (fun e ↦ e.symm.toFun), [], true, false), ..., ...] ``` -/ def getProjectionExprs (stx : Syntax) (tgt : Expr) (rhs : Expr) (cfg : Config) : MetaM <| Array <| Expr × ProjectionData := do -- the parameters of the structure let params := tgt.getAppArgs if cfg.debug && !(← (params.zip rhs.getAppArgs).allM fun ⟨a, b⟩ ↦ isDefEq a b) then throwError "unreachable code: parameters are not definitionally equal" let str := tgt.getAppFn.constName?.getD default -- the fields of the object let rhsArgs := rhs.getAppArgs.toList.drop params.size let (rawUnivs, projDeclata) ← getRawProjections stx str return projDeclata.map fun proj ↦ (rhsArgs.getD (fallback := default) proj.projNrs.head!, { proj with expr := (proj.expr.instantiateLevelParams rawUnivs tgt.getAppFn.constLevels!).instantiateLambdasOrApps params projNrs := proj.projNrs.tail }) variable (ref : Syntax) (univs : List Name) /-- Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`, `args` is the list of local constants occurring, and `univs` is the list of universe variables. -/ def addProjection (declName : Name) (type lhs rhs : Expr) (args : Array Expr) (cfg : Config) : MetaM Unit := do trace[simps.debug] "Planning to add the equality{indentD m!"{lhs} = ({rhs} : {type})"}" let env ← getEnv if (env.find? declName).isSome then -- diverging behavior from Lean 3 throwError "simps tried to add lemma {declName} to the environment, but it already exists." -- simplify `rhs` if `cfg.simpRhs` is true let lvl ← getLevel type let mut (rhs, prf) := (rhs, mkAppN (mkConst `Eq.refl [lvl]) #[type, lhs]) if cfg.simpRhs then let ctx ← mkSimpContext let (rhs2, _) ← dsimp rhs ctx if rhs != rhs2 then trace[simps.debug] "`dsimp` simplified rhs to{indentExpr rhs2}" else trace[simps.debug] "`dsimp` failed to simplify rhs" let (result, _) ← simp rhs2 ctx if rhs2 != result.expr then trace[simps.debug] "`simp` simplified rhs to{indentExpr result.expr}" else trace[simps.debug] "`simp` failed to simplify rhs" rhs := result.expr prf := result.proof?.getD prf let eqAp := mkApp3 (mkConst `Eq [lvl]) type lhs rhs let declType ← mkForallFVars args eqAp let declValue ← mkLambdaFVars args prf trace[simps.verbose] "adding projection {declName}:{indentExpr declType}" try addDecl <| .thmDecl { name := declName levelParams := univs type := declType value := declValue } catch ex => throwError "Failed to add projection lemma {declName}. Nested error:\n{ex.toMessageData}" addDeclarationRanges declName { range := ← getDeclarationRange (← getRef) selectionRange := ← getDeclarationRange ref } _ ← MetaM.run' <| TermElabM.run' <| addTermInfo (isBinder := true) ref <| ← mkConstWithLevelParams declName if cfg.isSimp then addSimpTheorem simpExtension declName true false .global <| eval_prio default _ ← cfg.attrs.mapM fun simpAttr ↦ do let .some simpDecl ← getSimpExtension? simpAttr | throwError "{simpAttr} is not a simp-attribute." addSimpTheorem simpDecl declName true false .global <| eval_prio default /-- Perform head-structure-eta-reduction on expression `e`. That is, if `e` is of the form `⟨f.1, f.2, ..., f.n⟩` with `f` definitionally equal to `e`, then `headStructureEtaReduce e = headStructureEtaReduce f` and `headStructureEtaReduce e = e` otherwise. -/ partial def headStructureEtaReduce (e : Expr) : MetaM Expr := do let env ← getEnv let (ctor, args) := e.getAppFnArgs let some (.ctorInfo { induct := struct, numParams, ..}) := env.find? ctor | pure e let some { fieldNames, .. } := getStructureInfo? env struct | pure e let (params, fields) := args.toList.splitAt numParams -- fix if `Array.take` / `Array.drop` exist trace[simps.debug] "rhs is constructor application with params{indentD params}\nand fields {indentD fields}" let field0 :: fieldsTail := fields | return e let fieldName0 :: fieldNamesTail := fieldNames.toList | return e let (fn0, fieldArgs0) := field0.getAppFnArgs unless fn0 == struct ++ fieldName0 do trace[simps.debug] "{fn0} ≠ {struct ++ fieldName0}" return e let (params', reduct :: _) := fieldArgs0.toList.splitAt numParams | unreachable! unless params' == params do trace[simps.debug] "{params'} ≠ {params}" return e trace[simps.debug] "Potential structure-eta-reduct:{indentExpr e}\nto{indentExpr reduct}" let allArgs := params.toArray.push reduct let isEta ← (fieldsTail.zip fieldNamesTail).allM fun (field, fieldName) ↦ if field.getAppFnArgs == (struct ++ fieldName, allArgs) then pure true else isProof field unless isEta do return e trace[simps.debug] "Structure-eta-reduce:{indentExpr e}\nto{indentExpr reduct}" headStructureEtaReduce reduct /-- Derive lemmas specifying the projections of the declaration. `nm`: name of the lemma If `todo` is non-empty, it will generate exactly the names in `todo`. `toApply` is non-empty after a custom projection that is a composition of multiple projections was just used. In that case we need to apply these projections before we continue changing `lhs`. `simpLemmas`: names of the simp lemmas added so far.(simpLemmas : Array Name) -/ partial def addProjections (nm : Name) (type lhs rhs : Expr) (args : Array Expr) (mustBeStr : Bool) (cfg : Config) (todo : List (String × Syntax)) (toApply : List Nat) : MetaM (Array Name) := do -- we don't want to unfold non-reducible definitions (like `Set`) to apply more arguments trace[simps.debug] "Type of the Expression before normalizing: {type}" withTransparency cfg.typeMd <| forallTelescopeReducing type fun typeArgs tgt ↦ withDefault do trace[simps.debug] "Type after removing pi's: {tgt}" let tgt ← whnfD tgt trace[simps.debug] "Type after reduction: {tgt}" let newArgs := args ++ typeArgs let lhsAp := lhs.instantiateLambdasOrApps typeArgs let rhsAp := rhs.instantiateLambdasOrApps typeArgs let str := tgt.getAppFn.constName trace[simps.debug] "todo: {todo}, toApply: {toApply}" -- We want to generate the current projection if it is in `todo` let todoNext := todo.filter (·.1 ≠ "") let env ← getEnv let stx? := todo.find? (·.1 == "") |>.map (·.2) /- The syntax object associated to the projection we're making now (if any). Note that we use `ref[0]` so that with `simps (config := ...)` we associate it to the word `simps` instead of the application of the attribute to arguments. -/ let stxProj := stx?.getD ref[0] let strInfo? := getStructureInfo? env str /- Don't recursively continue if `str` is not a structure or if the structure is in `notRecursive`. -/ if strInfo?.isNone || (todo.isEmpty && str ∈ cfg.notRecursive && !mustBeStr && toApply.isEmpty) then if mustBeStr then throwError "Invalid `simps` attribute. Target {str} is not a structure" if !todoNext.isEmpty && str ∉ cfg.notRecursive then let firstTodo := todoNext.head!.1 throwError "Invalid simp lemma {nm.appendAfter firstTodo}.\nProjection \ {(splitOnNotNumber firstTodo "_")[1]!} doesn't exist, \ because target {str} is not a structure." if cfg.fullyApplied then addProjection stxProj univs nm tgt lhsAp rhsAp newArgs cfg else addProjection stxProj univs nm type lhs rhs args cfg return #[nm] -- if the type is a structure let some (.inductInfo { isRec := false, ctors := [ctor], .. }) := env.find? str | unreachable! trace[simps.debug] "{str} is a structure with constructor {ctor}." let rhsEta ← headStructureEtaReduce rhsAp -- did the user ask to add this projection? let addThisProjection := stx?.isSome && toApply.isEmpty if addThisProjection then -- we pass the precise argument of simps as syntax argument to `addProjection` if cfg.fullyApplied then addProjection stxProj univs nm tgt lhsAp rhsEta newArgs cfg else addProjection stxProj univs nm type lhs rhs args cfg let rhsWhnf ← withTransparency cfg.rhsMd <| whnf rhsEta trace[simps.debug] "The right-hand-side {indentExpr rhsAp}\n reduces to {indentExpr rhsWhnf}" if !rhsWhnf.getAppFn.isConstOf ctor then -- if I'm about to run into an error, try to set the transparency for `rhsMd` higher. if cfg.rhsMd == .reducible && (mustBeStr || !todoNext.isEmpty || !toApply.isEmpty) then trace[simps.debug] "Using relaxed reducibility." Linter.logLintIf linter.simpsNoConstructor ref m!"\ The definition {nm} is not a constructor application. Please use `@[simps!]` instead.\n\ \n\ Explanation: `@[simps]` uses the definition to find what the simp lemmas should \ be. If the definition is a constructor, then this is easy, since the values of the \ projections are just the arguments to the constructor. If the definition is not a \ constructor, then `@[simps]` will unfold the right-hand side until it has found a \ constructor application, and uses those values.\n\n\ This might not always result in the simp-lemmas you want, so you are advised to use \ `@[simps?]` to double-check whether `@[simps]` generated satisfactory lemmas.\n\ Note 1: `@[simps!]` also calls the `simp` tactic, and this can be expensive in certain \ cases.\n\ Note 2: `@[simps!]` is equivalent to `@[simps (config := \{rhsMd := .default, \ simpRhs := true})]`. You can also try `@[simps (config := \{rhsMd := .default})]` \ to still unfold the definitions, but avoid calling `simp` on the resulting statement.\n\ Note 3: You need `simps!` if not all fields are given explicitly in this definition, \ even if the definition is a constructor application. For example, if you give a \ `MulEquiv` by giving the corresponding `Equiv` and the proof that it respects \ multiplication, then you need to mark it as `@[simps!]`, since the attribute needs to \ unfold the corresponding `Equiv` to get to the `toFun` field." let nms ← addProjections nm type lhs rhs args mustBeStr { cfg with rhsMd := .default, simpRhs := true } todo toApply return if addThisProjection then nms.push nm else nms if !toApply.isEmpty then throwError "Invalid simp lemma {nm}.\nThe given definition is not a constructor \ application:{indentExpr rhsWhnf}" if mustBeStr then throwError "Invalid `simps` attribute. The body is not a constructor application:\ {indentExpr rhsWhnf}" if !todoNext.isEmpty then throwError "Invalid simp lemma {nm.appendAfter todoNext.head!.1}.\n\ The given definition is not a constructor application:{indentExpr rhsWhnf}" if !addThisProjection then if cfg.fullyApplied then addProjection stxProj univs nm tgt lhsAp rhsEta newArgs cfg else addProjection stxProj univs nm type lhs rhs args cfg return #[nm] -- if the value is a constructor application trace[simps.debug] "Generating raw projection information..." let projInfo ← getProjectionExprs ref tgt rhsWhnf cfg trace[simps.debug] "Raw projection information:{indentD m!"{projInfo}"}" -- If we are in the middle of a composite projection. if let idx :: rest := toApply then let some ⟨newRhs, _⟩ := projInfo[idx]? | throwError "unreachable: index of composite projection is out of bounds." let newType ← inferType newRhs trace[simps.debug] "Applying a custom composite projection. Todo: {toApply}. Current lhs:\ {indentExpr lhsAp}" return ← addProjections nm newType lhsAp newRhs newArgs false cfg todo rest trace[simps.debug] "Not in the middle of applying a custom composite projection" /- We stop if no further projection is specified or if we just reduced an eta-expansion and we automatically choose projections -/ if todo.length == 1 && todo.head!.1 == "" then return #[nm] let projs : Array Name := projInfo.map fun x ↦ x.2.name let todo := todoNext trace[simps.debug] "Next todo: {todoNext}" -- check whether all elements in `todo` have a projection as prefix if let some (x, _) := todo.find? fun (x, _) ↦ projs.all fun proj ↦ !isPrefixOfAndNotNumber (proj.lastComponentAsString ++ "_") x then let simpLemma := nm.appendAfter x let neededProj := (splitOnNotNumber x "_")[0]! throwError "Invalid simp lemma {simpLemma}. \ Structure {str} does not have projection {neededProj}.\n\ The known projections are:\ {indentD <| toMessageData projs}\n\ You can also see this information by running\ \n `initialize_simps_projections? {str}`.\n\ Note: these projection names might be customly defined for `simps`, \ and could differ from the projection names of the structure." let nms ← projInfo.concatMapM fun ⟨newRhs, proj, projExpr, projNrs, isDefault, isPrefix⟩ ↦ do let newType ← inferType newRhs let newTodo := todo.filterMap fun (x, stx) ↦ (dropPrefixIfNotNumber? x (proj.lastComponentAsString ++ "_")).map (·.toString, stx) -- we only continue with this field if it is default or mentioned in todo if !(isDefault && todo.isEmpty) && newTodo.isEmpty then return #[] let newLhs := projExpr.instantiateLambdasOrApps #[lhsAp] let newName := updateName nm proj.lastComponentAsString isPrefix trace[simps.debug] "Recursively add projections for:{indentExpr newLhs}" addProjections newName newType newLhs newRhs newArgs false cfg newTodo projNrs return if addThisProjection then nms.push nm else nms end Simps open Simps /-- `simpsTac` derives `simp` lemmas for all (nested) non-Prop projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. If `shortNm` is true, the generated names will only use the last projection name. If `trc` is true, trace as if `trace.simps.verbose` is true. -/ def simpsTac (ref : Syntax) (nm : Name) (cfg : Config := {}) (todo : List (String × Syntax) := []) (trc := false) : AttrM (Array Name) := withOptions (· |>.updateBool `trace.simps.verbose (trc || ·)) <| do let env ← getEnv let some d := env.find? nm | throwError "Declaration {nm} doesn't exist." let lhs : Expr := mkConst d.name <| d.levelParams.map Level.param let todo := todo.pwFilter (·.1 ≠ ·.1) |>.map fun (proj, stx) ↦ (proj ++ "_", stx) let mut cfg := cfg MetaM.run' <| addProjections ref d.levelParams nm d.type lhs (d.value?.getD default) #[] (mustBeStr := true) cfg todo [] /-- elaborate the syntax and run `simpsTac`. -/ def simpsTacFromSyntax (nm : Name) (stx : Syntax) : AttrM (Array Name) := match stx with | `(attr| simps $[!%$bang]? $[?%$trc]? $[(config := $c)]? $[$ids]*) => do let cfg ← MetaM.run' <| TermElabM.run' <| withSaveInfoContext <| elabSimpsConfig stx[3][0] let cfg := if bang.isNone then cfg else { cfg with rhsMd := .default, simpRhs := true } let ids := ids.map fun x => (x.getId.eraseMacroScopes.lastComponentAsString, x.raw) simpsTac stx nm cfg ids.toList trc.isSome | _ => throwUnsupportedSyntax /-- The `simps` attribute. -/ initialize simpsAttr : ParametricAttribute (Array Name) ← registerParametricAttribute { name := `simps descr := "Automatically derive lemmas specifying the projections of this declaration.", getParam := simpsTacFromSyntax }
Tactic\Simps\NotationClass.lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Lean.Elab.Exception import Batteries.Lean.NameMapAttribute import Batteries.Lean.Expr import Batteries.Tactic.Lint /-! # `@[notation_class]` attribute for `@[simps]` This declares the `@[notation_class]` attribute, which is used to give smarter default projections for `@[simps]`. We put this in a separate file so that we can already tag some declarations with this attribute in the file where we declare `@[simps]`. For further documentation, see `Tactic.Simps.Basic`. -/ /-- The `@[notation_class]` attribute specifies that this is a notation class, and this notation should be used instead of projections by `@[simps]`. * This is only important if the projection is written differently using notation, e.g. `+` uses `HAdd.hAdd`, not `Add.add` and `0` uses `OfNat.ofNat` not `Zero.zero`. We also add it to non-heterogenous notation classes, like `Neg`, but it doesn't do much for any class that extends `Neg`. * `@[notation_class * <projName> Simps.findCoercionArgs]` is used to configure the `SetLike` and `DFunLike` coercions. * The first name argument is the projection name we use as the key to search for this class (default: name of first projection of the class). * The second argument is the name of a declaration that has type `findArgType` which is defined to be `Name → Name → Array Expr → MetaM (Array (Option Expr))`. This declaration specifies how to generate the arguments of the notation class from the arguments of classes that use the projection. -/ syntax (name := notation_class) "notation_class" "*"? (ppSpace ident)? (ppSpace ident)? : attr open Lean Meta Elab Term namespace Simps /-- The type of methods to find arguments for automatic projections for `simps`. We partly define this as a separate definition so that the unused arguments linter doesn't complain. -/ def findArgType : Type := Name → Name → Array Expr → MetaM (Array (Option Expr)) /-- Find arguments for a notation class -/ def defaultfindArgs : findArgType := λ _ className args => do let some classExpr := (← getEnv).find? className | throwError "no such class {className}" let arity := classExpr.type.forallArity if arity == args.size then return args.map some else if args.size == 1 then return mkArray arity args[0]! else throwError "initialize_simps_projections cannot automatically find arguments for class \ {className}" /-- Find arguments by duplicating the first argument. Used for `pow`. -/ def copyFirst : findArgType := λ _ _ args => return (args.push <| args[0]?.getD default).map some /-- Find arguments by duplicating the first argument. Used for `smul`. -/ def copySecond : findArgType := λ _ _ args => return (args.push <| args[1]?.getD default).map some /-- Find arguments by prepending `ℕ` and duplicating the first argument. Used for `nsmul`. -/ def nsmulArgs : findArgType := λ _ _ args => return #[Expr.const `Nat [], args[0]?.getD default] ++ args |>.map some /-- Find arguments by prepending `ℤ` and duplicating the first argument. Used for `zsmul`. -/ def zsmulArgs : findArgType := λ _ _ args => return #[Expr.const `Int [], args[0]?.getD default] ++ args |>.map some /-- Find arguments for the `Zero` class. -/ def findZeroArgs : findArgType := λ _ _ args => return #[some <| args[0]?.getD default, some <| mkRawNatLit 0] /-- Find arguments for the `One` class. -/ def findOneArgs : findArgType := λ _ _ args => return #[some <| args[0]?.getD default, some <| mkRawNatLit 1] /-- Find arguments of a coercion class (`DFunLike` or `SetLike`) -/ def findCoercionArgs : findArgType := λ str className args => do let some classExpr := (← getEnv).find? className | throwError "no such class {className}" let arity := classExpr.type.forallArity let eStr := mkAppN (← mkConstWithLevelParams str) args let classArgs := mkArray (arity - 1) none return #[some eStr] ++ classArgs /-- Data needed to generate automatic projections. This data is associated to a name of a projection in a structure that must be used to trigger the search. -/ structure AutomaticProjectionData where /-- `className` is the name of the class we are looking for. -/ className : Name /-- `isNotation` is a boolean that specifies whether this is notation (false for the coercions `DFunLike` and `SetLike`). If this is set to true, we add the current class as hypothesis during type-class synthesis. -/ isNotation := true /-- The method to find the arguments of the class. -/ findArgs : Name := `Simps.defaultfindArgs deriving Inhabited /-- `@[notation_class]` attribute. Note: this is *not* a `NameMapAttribute` because we key on the argument of the attribute, not the declaration name. -/ initialize notationClassAttr : NameMapExtension AutomaticProjectionData ← do let ext ← registerNameMapExtension AutomaticProjectionData registerBuiltinAttribute { name := `notation_class descr := "An attribute specifying that this is a notation class. Used by @[simps]." add := fun src stx _kind => do unless isStructure (← getEnv) src do throwError "@[notation_class] attribute can only be added to classes." match stx with | `(attr|notation_class $[*%$coercion]? $[$projName?]? $[$findArgs?]?) => do let projName ← match projName? with | none => pure (getStructureFields (← getEnv) src)[0]! | some projName => pure projName.getId let findArgs := if findArgs?.isSome then findArgs?.get!.getId else `Simps.defaultfindArgs match (← getEnv).find? findArgs with | none => throwError "no such declaration {findArgs}" | some declInfo => unless ← MetaM.run' <| isDefEq declInfo.type (mkConst ``findArgType) do throwError "declaration {findArgs} has wrong type" ext.add projName ⟨src, coercion.isNone, findArgs⟩ | _ => throwUnsupportedSyntax } return ext end Simps
Tactic\ToAdditive\Frontend.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov, Floris van Doorn, Jon Eugster -/ import Mathlib.Data.Nat.Notation import Mathlib.Data.String.Defs import Mathlib.Data.Array.Defs import Mathlib.Lean.Expr.ReplaceRec import Mathlib.Lean.EnvExtension import Mathlib.Lean.Meta.Simp import Mathlib.Lean.Name import Lean.Elab.Tactic.Ext import Lean.Meta.Tactic.Symm import Lean.Meta.Tactic.Rfl import Batteries.Lean.NameMapAttribute import Batteries.Tactic.Lint -- useful to lint this file and for for DiscrTree.elements import Mathlib.Tactic.Relation.Trans -- just to copy the attribute import Mathlib.Tactic.Eqns -- just to copy the attribute import Mathlib.Tactic.Simps.Basic /-! # The `@[to_additive]` attribute. The attribute `to_additive` can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. To use this attribute, just write: ``` @[to_additive] theorem mul_comm' {α} [CommSemigroup α] (x y : α) : x * y = y * x := mul_comm x y ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration: ``` @[to_additive add_foo] theorem foo := sorry ``` An existing documentation string will _not_ be automatically used, so if the theorem or definition has a doc string, a doc string for the additive version should be passed explicitly to `to_additive`. ``` /-- Multiplication is commutative -/ @[to_additive "Addition is commutative"] theorem mul_comm' {α} [CommSemigroup α] (x y : α) : x * y = y * x := CommSemigroup.mul_comm ``` The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. Use the `(reorder := ...)` syntax to reorder the arguments in the generated additive declaration. This is specified using cycle notation. For example `(reorder := 1 2, 5 6)` swaps the first two arguments with each other and the fifth and the sixth argument and `(reorder := 3 4 5)` will move the fifth argument before the third argument. This is mostly useful to translate declarations using `Pow` to those using `SMul`. Use the `(attr := ...)` syntax to apply attributes to both the multiplicative and the additive version: ``` @[to_additive (attr := simp)] lemma mul_one' {G : Type*} [Group G] (x : G) : x * 1 = x := mul_one x ``` For `simps` this also ensures that some generated lemmas are added to the additive dictionary. `@[to_additive (attr := to_additive)]` is a special case, where the `to_additive` attribute is added to the generated lemma only, to additivize it again. This is useful for lemmas about `Pow` to generate both lemmas about `SMul` and `VAdd`. Example: ``` @[to_additive (attr := to_additive VAdd_lemma, simp) SMul_lemma] lemma Pow_lemma ... := ``` In the above example, the `simp` is added to all 3 lemmas. All other options to `to_additive` (like the generated name or `(reorder := ...)`) are not passed down, and can be given manually to each individual `to_additive` call. ## Implementation notes The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with `to_additive`. In the `mul_comm'` example above, `to_additive` maps: * `mul_comm'` to `add_comm'`, * `CommSemigroup` to `AddCommSemigroup`, * `x * y` to `x + y` and `y * x` to `y + x`, and * `CommSemigroup.mul_comm'` to `AddCommSemigroup.add_comm'`. ### Heuristics `to_additive` uses heuristics to determine whether a particular identifier has to be mapped to its additive version. The basic heuristic is * Only map an identifier to its additive version if its first argument doesn't contain any unapplied identifiers. Examples: * `@Mul.mul Nat n m` (i.e. `(n * m : Nat)`) will not change to `+`, since its first argument is `Nat`, an identifier not applied to any arguments. * `@Mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier `Prod`, but this is applied to arguments, `α` and `β`. * `@Mul.mul (α × Int) x y` will not change to `+`, since its first argument contains `Int`. The reasoning behind the heuristic is that the first argument is the type which is "additivized", and this usually doesn't make sense if this is on a fixed type. There are some exceptions to this heuristic: * Identifiers that have the `@[to_additive]` attribute are ignored. For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`. * If an identifier `d` has attribute `@[to_additive_relevant_arg n]` then the argument in position `n` is checked for a fixed type, instead of checking the first argument. `@[to_additive]` will automatically add the attribute `@[to_additive_relevant_arg n]` to a declaration when the first argument has no multiplicative type-class, but argument `n` does. * If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1). For example, `ContMDiffMap` has attribute `@[to_additive_ignore_args 21]`, which means that its 21st argument `(n : WithTop ℕ)` can contain `ℕ` (usually in the form `Top.top ℕ ...`) and still be additivized. So `@Mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized. ### Troubleshooting If `@[to_additive]` fails because the additive declaration raises a type mismatch, there are various things you can try. The first thing to do is to figure out what `@[to_additive]` did wrong by looking at the type mismatch error. * Option 1: The most common case is that it didn't additivize a declaration that should be additivized. This happened because the heuristic applied, and the first argument contains a fixed type, like `ℕ` or `ℝ`. However, the heuristic misfires on some other declarations. Solutions: * First figure out what the fixed type is in the first argument of the declaration that didn't get additivized. Note that this fixed type can occur in implicit arguments. If manually finding it is hard, you can run `set_option trace.to_additive_detail true` and search the output for the fragment "contains the fixed type" to find what the fixed type is. * If the fixed type has an additive counterpart (like `↥Semigroup`), give it the `@[to_additive]` attribute. * If the fixed type has nothing to do with algebraic operations (like `TopCat`), add the attribute `@[to_additive existing Foo]` to the fixed type `Foo`. * If the fixed type occurs inside the `k`-th argument of a declaration `d`, and the `k`-th argument is not connected to the multiplicative structure on `d`, consider adding attribute `[to_additive_ignore_args k]` to `d`. Example: `ContMDiffMap` ignores the argument `(n : WithTop ℕ)` * Option 2: It additivized a declaration `d` that should remain multiplicative. Solution: * Make sure the first argument of `d` is a type with a multiplicative structure. If not, can you reorder the (implicit) arguments of `d` so that the first argument becomes a type with a multiplicative structure (and not some indexing type)? The reason is that `@[to_additive]` doesn't additivize declarations if their first argument contains fixed types like `ℕ` or `ℝ`. See section Heuristics. If the first argument is not the argument with a multiplicative type-class, `@[to_additive]` should have automatically added the attribute `@[to_additive_relevant_arg]` to the declaration. You can test this by running the following (where `d` is the full name of the declaration): ``` open Lean in run_cmd logInfo m!"{ToAdditive.relevantArgAttr.find? (← getEnv) `d}" ``` The expected output is `n` where the `n`-th (0-indexed) argument of `d` is a type (family) with a multiplicative structure on it. `none` means `0`. If you get a different output (or a failure), you could add the attribute `@[to_additive_relevant_arg n]` manually, where `n` is an (1-indexed) argument with a multiplicative structure. * Option 3: Arguments / universe levels are incorrectly ordered in the additive version. This likely only happens when the multiplicative declaration involves `pow`/`^`. Solutions: * Ensure that the order of arguments of all relevant declarations are the same for the multiplicative and additive version. This might mean that arguments have an "unnatural" order (e.g. `Monoid.npow n x` corresponds to `x ^ n`, but it is convenient that `Monoid.npow` has this argument order, since it matches `AddMonoid.nsmul n x`. * If this is not possible, add `(reorder := ...)` argument to `to_additive`. If neither of these solutions work, and `to_additive` is unable to automatically generate the additive version of a declaration, manually write and prove the additive version. Often the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to `multiplicative G`. Afterwards, apply the attribute manually: ``` attribute [to_additive foo_add_bar] foo_bar ``` This will allow future uses of `to_additive` to recognize that `foo_bar` should be replaced with `foo_add_bar`. ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. In addition to transporting the “main” declaration, `to_additive` transports its equational lemmas and tags them as equational lemmas for the new declaration. ### Structure fields and constructors If `src` is a structure, then the additive version has to be already written manually. In this case `to_additive` adds all structure fields to its mapping. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * [todo] Namespaces can be transformed using `map_namespace`. For example: ``` run_cmd to_additive.map_namespace `QuotientGroup `QuotientAddGroup ``` Later uses of `to_additive` on declarations in the `QuotientGroup` namespace will be created in the `QuotientAddGroup` namespaces. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `NewNamespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first case `to_additive` double checks that the new name differs from the original one. -/ open Lean Meta Elab Command Std /-- The `to_additive_ignore_args` attribute. -/ syntax (name := to_additive_ignore_args) "to_additive_ignore_args" (ppSpace num)* : attr /-- The `to_additive_relevant_arg` attribute. -/ syntax (name := to_additive_relevant_arg) "to_additive_relevant_arg " num : attr /-- The `to_additive_reorder` attribute. -/ syntax (name := to_additive_reorder) "to_additive_reorder " (num+),+ : attr /-- The `to_additive_change_numeral` attribute. -/ syntax (name := to_additive_change_numeral) "to_additive_change_numeral" (ppSpace num)* : attr /-- An `attr := ...` option for `to_additive`. -/ syntax toAdditiveAttrOption := &"attr" " := " Parser.Term.attrInstance,* /-- A `reorder := ...` option for `to_additive`. -/ syntax toAdditiveReorderOption := &"reorder" " := " (num+),+ /-- Options to `to_additive`. -/ syntax toAdditiveParenthesizedOption := "(" toAdditiveAttrOption <|> toAdditiveReorderOption ")" /-- Options to `to_additive`. -/ syntax toAdditiveOption := toAdditiveParenthesizedOption <|> &"existing" /-- Remaining arguments of `to_additive`. -/ syntax toAdditiveRest := (ppSpace toAdditiveOption)* (ppSpace ident)? (ppSpace str)? /-- The `to_additive` attribute. -/ syntax (name := to_additive) "to_additive" "?"? toAdditiveRest : attr /-- The `to_additive` attribute. -/ macro "to_additive?" rest:toAdditiveRest : attr => `(attr| to_additive ? $rest) /-- A set of strings of names that end in a capital letter. * If the string contains a lowercase letter, the string should be split between the first occurrence of a lower-case letter followed by an upper-case letter. * If multiple strings have the same prefix, they should be grouped by prefix * In this case, the second list should be prefix-free (no element can be a prefix of a later element) Todo: automate the translation from `String` to an element in this `RBMap` (but this would require having something similar to the `rb_lmap` from Lean 3). -/ def endCapitalNames : Lean.RBMap String (List String) compare := -- todo: we want something like -- endCapitalNamesOfList ["LE", "LT", "WF", "CoeTC", "CoeT", "CoeHTCT"] .ofList [("LE", [""]), ("LT", [""]), ("WF", [""]), ("Coe", ["TC", "T", "HTCT"])] /-- This function takes a String and splits it into separate parts based on the following (naming conventions)[https://github.com/leanprover-community/mathlib4/wiki#naming-convention]. E.g. `#eval "InvHMulLEConjugate₂SMul_ne_top".splitCase` yields `["Inv", "HMul", "LE", "Conjugate₂", "SMul", "_", "ne", "_", "top"]`. -/ partial def String.splitCase (s : String) (i₀ : Pos := 0) (r : List String := []) : List String := Id.run do -- We test if we need to split between `i₀` and `i₁`. let i₁ := s.next i₀ if s.atEnd i₁ then -- If `i₀` is the last position, return the list. let r := s::r return r.reverse /- We split the string in three cases * We split on both sides of `_` to keep them there when rejoining the string; * We split after a name in `endCapitalNames`; * We split after a lower-case letter that is followed by an upper-case letter (unless it is part of a name in `endCapitalNames`). -/ if s.get i₀ == '_' || s.get i₁ == '_' then return splitCase (s.extract i₁ s.endPos) 0 <| (s.extract 0 i₁)::r if (s.get i₁).isUpper then if let some strs := endCapitalNames.find? (s.extract 0 i₁) then if let some (pref, newS) := strs.findSome? fun x : String ↦ (s.extract i₁ s.endPos).dropPrefix? x |>.map (x, ·.toString) then return splitCase newS 0 <| (s.extract 0 i₁ ++ pref)::r if !(s.get i₀).isUpper then return splitCase (s.extract i₁ s.endPos) 0 <| (s.extract 0 i₁)::r return splitCase s i₁ r namespace ToAdditive initialize registerTraceClass `to_additive initialize registerTraceClass `to_additive_detail /-- Linter to check that the `reorder` attribute is not given manually -/ register_option linter.toAdditiveReorder : Bool := { defValue := true descr := "Linter to check that the reorder attribute is not given manually." } /-- Linter, mostly used by `@[to_additive]`, that checks that the source declaration doesn't have certain attributes -/ register_option linter.existingAttributeWarning : Bool := { defValue := true descr := "Linter, mostly used by `@[to_additive]`, that checks that the source declaration \ doesn't have certain attributes" } /-- Linter to check that the `to_additive` attribute is not given manually -/ register_option linter.toAdditiveGenerateName : Bool := { defValue := true descr := "Linter used by `@[to_additive]` that checks if `@[to_additive]` automatically \ generates the user-given name" } /-- Linter to check whether the user correctly specified that the additive declaration already exists -/ register_option linter.toAdditiveExisting : Bool := { defValue := true descr := "Linter used by `@[to_additive]` that checks whether the user correctly specified that the additive declaration already exists" } /-- An attribute that tells `@[to_additive]` that certain arguments of this definition are not involved when using `@[to_additive]`. This helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another fixed type occurs as one of these arguments. -/ initialize ignoreArgsAttr : NameMapExtension (List Nat) ← registerNameMapAttribute { name := `to_additive_ignore_args descr := "Auxiliary attribute for `to_additive` stating that certain arguments are not additivized." add := fun _ stx ↦ do let ids ← match stx with | `(attr| to_additive_ignore_args $[$ids:num]*) => pure <| ids.map (·.1.isNatLit?.get!) | _ => throwUnsupportedSyntax return ids.toList } /-- An attribute that stores all the declarations that needs their arguments reordered when applying `@[to_additive]`. It is applied automatically by the `(reorder := ...)` syntax of `to_additive`, and should not usually be added manually. -/ initialize reorderAttr : NameMapExtension (List <| List Nat) ← registerNameMapAttribute { name := `to_additive_reorder descr := "\ Auxiliary attribute for `to_additive` that stores arguments that need to be reordered. \ This should not appear in any file. \ We keep it as an attribute for now so that mathport can still use it, and it can generate a \ warning." add := fun | _, stx@`(attr| to_additive_reorder $[$[$reorders:num]*],*) => do Linter.logLintIf linter.toAdditiveReorder stx m!"\ Using this attribute is deprecated. Use `@[to_additive (reorder := <num>)]` instead.\n\n\ That will also generate the additive version with the arguments swapped, \ so you are probably able to remove the manually written additive declaration." pure <| reorders.toList.map (·.toList.map (·.raw.isNatLit?.get! - 1)) | _, _ => throwUnsupportedSyntax } /-- An attribute that is automatically added to declarations tagged with `@[to_additive]`, if needed. This attribute tells which argument is the type where this declaration uses the multiplicative structure. If there are multiple argument, we typically tag the first one. If this argument contains a fixed type, this declaration will note be additivized. See the Heuristics section of `to_additive.attr` for more details. If a declaration is not tagged, it is presumed that the first argument is relevant. `@[to_additive]` uses the function `to_additive.first_multiplicative_arg` to automatically tag declarations. It is ok to update it manually if the automatic tagging made an error. Implementation note: we only allow exactly 1 relevant argument, even though some declarations (like `prod.group`) have multiple arguments with a multiplicative structure on it. The reason is that whether we additivize a declaration is an all-or-nothing decision, and if we will not be able to additivize declarations that (e.g.) talk about multiplication on `ℕ × α` anyway. Warning: interactions between this and the `(reorder := ...)` argument are not well-tested. -/ initialize relevantArgAttr : NameMapExtension Nat ← registerNameMapAttribute { name := `to_additive_relevant_arg descr := "Auxiliary attribute for `to_additive` stating \ which arguments are the types with a multiplicative structure." add := fun | _, `(attr| to_additive_relevant_arg $id) => pure <| id.1.isNatLit?.get!.pred | _, _ => throwUnsupportedSyntax } /-- An attribute that stores all the declarations that deal with numeric literals on variable types. Numeral literals occur in expressions without type information, so in order to decide whether `1` needs to be changed to `0`, the context around the numeral is relevant. Most numerals will be in an `OfNat.ofNat` application, though tactics can add numeral literals inside arbitrary functions. By default we assume that we do not change numerals, unless it is in a function application with the `to_additive_change_numeral` attribute. `@[to_additive_change_numeral n₁ ...]` should be added to all functions that take one or more numerals as argument that should be changed if `additiveTest` succeeds on the first argument, i.e. when the numeral is only translated if the first argument is a variable (or consists of variables). The arguments `n₁ ...` are the positions of the numeral arguments (starting counting from 1). -/ initialize changeNumeralAttr : NameMapExtension (List Nat) ← registerNameMapAttribute { name := `to_additive_change_numeral descr := "Auxiliary attribute for `to_additive` that stores functions that have numerals as argument." add := fun | _, `(attr| to_additive_change_numeral $[$arg]*) => pure <| arg.map (·.1.isNatLit?.get!.pred) |>.toList | _, _ => throwUnsupportedSyntax } /-- Maps multiplicative names to their additive counterparts. -/ initialize translations : NameMapExtension Name ← registerNameMapExtension _ /-- Get the multiplicative → additive translation for the given name. -/ def findTranslation? (env : Environment) : Name → Option Name := (ToAdditive.translations.getState env).find? /-- Add a (multiplicative → additive) name translation to the translations map. -/ def insertTranslation (src tgt : Name) (failIfExists := true) : CoreM Unit := do if let some tgt' := findTranslation? (← getEnv) src then if failIfExists then throwError "The translation {src} ↦ {tgt'} already exists" else trace[to_additive] "The translation {src} ↦ {tgt'} already exists" return modifyEnv (ToAdditive.translations.addEntry · (src, tgt)) trace[to_additive] "Added translation {src} ↦ {tgt}" /-- `Config` is the type of the arguments that can be provided to `to_additive`. -/ structure Config : Type where /-- View the trace of the to_additive procedure. Equivalent to `set_option trace.to_additive true`. -/ trace : Bool := false /-- The name of the target (the additive declaration). -/ tgt : Name := Name.anonymous /-- An optional doc string. -/ doc : Option String := none /-- If `allowAutoName` is `false` (default) then `@[to_additive]` will check whether the given name can be auto-generated. -/ allowAutoName : Bool := false /-- The arguments that should be reordered by `to_additive`, using cycle notation. -/ reorder : List (List Nat) := [] /-- The attributes which we want to give to both the multiplicative and additive versions. For `simps` this will also add generated lemmas to the translation dictionary. -/ attrs : Array Syntax := #[] /-- The `Syntax` element corresponding to the original multiplicative declaration (or the `to_additive` attribute if it is added later), which we need for adding definition ranges. -/ ref : Syntax /-- An optional flag stating whether the additive declaration already exists. If this flag is set but wrong about whether the additive declaration exists, `to_additive` will raise a linter error. Note: the linter will never raise an error for inductive types and structures. -/ existing : Option Bool := none deriving Repr /-- Implementation function for `additiveTest`. We cache previous applications of the function, using an expression cache using ptr equality to avoid visiting the same subexpression many times. Note that we only need to cache the expressions without taking the value of `inApp` into account, since `inApp` only matters when the expression is a constant. However, for this reason we have to make sure that we never cache constant expressions, so that's why the `if`s in the implementation are in this order. Note that this function is still called many times by `applyReplacementFun` and we're not remembering the cache between these calls. -/ unsafe def additiveTestUnsafe (findTranslation? : Name → Option Name) (ignore : Name → Option (List ℕ)) (e : Expr) : Option Name := let rec visit (e : Expr) (inApp := false) : OptionT (StateM (PtrSet Expr)) Name := do if e.isConst then if inApp || (findTranslation? e.constName).isSome then failure else return e.constName if (← get).contains e then failure modify fun s => s.insert e match e with | x@(.app e a) => visit e true <|> do -- make sure that we don't treat `(fun x => α) (n + 1)` as a type that depends on `Nat` guard !x.isConstantApplication if let some n := e.getAppFn.constName? then if let some l := ignore n then if e.getAppNumArgs + 1 ∈ l then failure visit a | .lam _ _ t _ => visit t | .forallE _ _ t _ => visit t | .letE _ _ e body _ => visit e <|> visit body | .mdata _ b => visit b | .proj _ _ b => visit b | _ => failure Id.run <| (visit e).run' mkPtrSet /-- `additiveTest e` tests whether the expression `e` contains a constant `nm` that is not applied to any arguments, and such that `translations.find?[nm] = none`. This is used in `@[to_additive]` for deciding which subexpressions to transform: we only transform constants if `additiveTest` applied to their first argument returns `true`. This means we will replace expression applied to e.g. `α` or `α × β`, but not when applied to e.g. `ℕ` or `ℝ × α`. We ignore all arguments specified by the `ignore` `NameMap`. -/ def additiveTest (findTranslation? : Name → Option Name) (ignore : Name → Option (List ℕ)) (e : Expr) : Option Name := unsafe additiveTestUnsafe findTranslation? ignore e /-- Swap the first two elements of a list -/ def _root_.List.swapFirstTwo {α : Type _} : List α → List α | [] => [] | [x] => [x] | x::y::l => y::x::l /-- Change the numeral `nat_lit 1` to the numeral `nat_lit 0`. Leave all other expressions unchanged. -/ def changeNumeral : Expr → Expr | .lit (.natVal 1) => mkRawNatLit 0 | e => e /-- `applyReplacementFun e` replaces the expression `e` with its additive counterpart. It translates each identifier (inductive type, defined function etc) in an expression, unless * The identifier occurs in an application with first argument `arg`; and * `test arg` is false. However, if `f` is in the dictionary `relevant`, then the argument `relevant.find f` is tested, instead of the first argument. It will also reorder arguments of certain functions, using `reorderFn`: e.g. `g x₁ x₂ x₃ ... xₙ` becomes `g x₂ x₁ x₃ ... xₙ` if `reorderFn g = some [1]`. -/ def applyReplacementFun (e : Expr) : MetaM Expr := do let env ← getEnv let reorderFn : Name → List (List ℕ) := fun nm ↦ (reorderAttr.find? env nm |>.getD []) let relevantArg : Name → ℕ := fun nm ↦ (relevantArgAttr.find? env nm).getD 0 return aux (findTranslation? <| ← getEnv) reorderFn (ignoreArgsAttr.find? env) (changeNumeralAttr.find? env) relevantArg (← getBoolOption `trace.to_additive_detail) e where /-- Implementation of `applyReplacementFun`. -/ aux (findTranslation? : Name → Option Name) (reorderFn : Name → List (List ℕ)) (ignore : Name → Option (List ℕ)) (changeNumeral? : Name → Option (List Nat)) (relevantArg : Name → ℕ) (trace : Bool) : Expr → Expr := Lean.Expr.replaceRec fun r e ↦ Id.run do if trace then dbg_trace s!"replacing at {e}" match e with | .const n₀ ls₀ => do let n₁ := n₀.mapPrefix findTranslation? let ls₁ : List Level := if 0 ∈ (reorderFn n₀).join then ls₀.swapFirstTwo else ls₀ if trace then if n₀ != n₁ then dbg_trace s!"changing {n₀} to {n₁}" if 0 ∈ (reorderFn n₀).join then dbg_trace s!"reordering the universe variables from {ls₀} to {ls₁}" return some <| Lean.mkConst n₁ ls₁ | .app g x => do let gf := g.getAppFn if gf.isBVar && x.isLit then if trace then dbg_trace s!"applyReplacementFun: Variables applied to numerals are not changed {g.app x}" return some <| g.app x let gArgs := g.getAppArgs let mut gAllArgs := gArgs.push x let (gfAdditive, gAllArgsAdditive) ← if let some nm := gf.constName? then -- e = `(nm y₁ .. yₙ x) /- Test if the head should not be replaced. -/ let relevantArgId := relevantArg nm let gfAdditive := if relevantArgId < gAllArgs.size && gf.isConst then if let some fxd := additiveTest findTranslation? ignore gAllArgs[relevantArgId]! then Id.run <| do if trace then dbg_trace s!"The application of {nm} contains the fixed type \ {fxd}, so it is not changed" gf else r gf else r gf /- Test if arguments should be reordered. -/ let reorder := reorderFn nm if !reorder.isEmpty && relevantArgId < gAllArgs.size && (additiveTest findTranslation? ignore gAllArgs[relevantArgId]!).isNone then gAllArgs := gAllArgs.permute! reorder if trace then dbg_trace s!"reordering the arguments of {nm} using the cyclic permutations {reorder}" /- Do not replace numerals in specific types. -/ let firstArg := gAllArgs[0]! if let some changedArgNrs := changeNumeral? nm then if additiveTest findTranslation? ignore firstArg |>.isNone then if trace then dbg_trace s!"applyReplacementFun: We change the numerals in this expression. \ However, we will still recurse into all the non-numeral arguments." -- In this case, we still update all arguments of `g` that are not numerals, -- since all other arguments can contain subexpressions like -- `(fun x ↦ ℕ) (1 : G)`, and we have to update the `(1 : G)` to `(0 : G)` gAllArgs := gAllArgs.mapIdx fun argNr arg ↦ if changedArgNrs.contains argNr then changeNumeral arg else arg pure <| (gfAdditive, ← gAllArgs.mapM r) else pure (← r gf, ← gAllArgs.mapM r) return some <| mkAppN gfAdditive gAllArgsAdditive | .proj n₀ idx e => do let n₁ := n₀.mapPrefix findTranslation? if trace then dbg_trace s!"applyReplacementFun: in projection {e}.{idx} of type {n₀}, \ replace type with {n₁}" return some <| .proj n₁ idx <| ← r e | _ => return none /-- Eta expands `e` at most `n` times. -/ def etaExpandN (n : Nat) (e : Expr) : MetaM Expr := do forallBoundedTelescope (← inferType e) (some n) fun xs _ ↦ mkLambdaFVars xs (mkAppN e xs) /-- `e.expand` eta-expands all expressions that have as head a constant `n` in `reorder`. They are expanded until they are applied to one more argument than the maximum in `reorder.find n`. -/ def expand (e : Expr) : MetaM Expr := do let env ← getEnv let reorderFn : Name → List (List ℕ) := fun nm ↦ (reorderAttr.find? env nm |>.getD []) let e₂ ← Lean.Meta.transform (input := e) (post := fun e => return .done e) fun e ↦ do let e0 := e.getAppFn let es := e.getAppArgs let some e0n := e0.constName? | return .continue let reorder := reorderFn e0n if reorder.isEmpty then -- no need to expand if nothing needs reordering return .continue let needed_n := reorder.join.foldr Nat.max 0 + 1 -- the second disjunct is a temporary fix to avoid infinite loops. -- We may need to use `replaceRec` or something similar to not change the head of an application if needed_n ≤ es.size || es.size == 0 then return .continue else -- in this case, we need to reorder arguments that are not yet -- applied, so first η-expand the function. let e' ← etaExpandN (needed_n - es.size) e trace[to_additive_detail] "expanded {e} to {e'}" return .continue e' if e != e₂ then trace[to_additive_detail] "expand:\nBefore: {e}\nAfter: {e₂}" return e₂ /-- Reorder pi-binders. See doc of `reorderAttr` for the interpretation of the argument -/ def reorderForall (reorder : List (List Nat) := []) (src : Expr) : MetaM Expr := do if reorder == [] then return src forallTelescope src fun xs e => do mkForallFVars (xs.permute! reorder) e /-- Reorder lambda-binders. See doc of `reorderAttr` for the interpretation of the argument -/ def reorderLambda (reorder : List (List Nat) := []) (src : Expr) : MetaM Expr := do if reorder == [] then return src lambdaTelescope src fun xs e => do mkLambdaFVars (xs.permute! reorder) e /-- Run applyReplacementFun on the given `srcDecl` to make a new declaration with name `tgt` -/ def updateDecl (tgt : Name) (srcDecl : ConstantInfo) (reorder : List (List Nat) := []) : MetaM ConstantInfo := do let mut decl := srcDecl.updateName tgt if 0 ∈ reorder.join then decl := decl.updateLevelParams decl.levelParams.swapFirstTwo decl := decl.updateType <| ← applyReplacementFun <| ← reorderForall reorder <| ← expand <| ← unfoldAuxLemmas decl.type if let some v := decl.value? then decl := decl.updateValue <| ← applyReplacementFun <| ← reorderLambda reorder <| ← expand <| ← unfoldAuxLemmas v else if let .opaqueInfo info := decl then -- not covered by `value?` decl := .opaqueInfo { info with value := ← applyReplacementFun <| ← reorderLambda reorder <| ← expand <| ← unfoldAuxLemmas info.value } return decl /-- Find the target name of `pre` and all created auxiliary declarations. -/ def findTargetName (env : Environment) (src pre tgt_pre : Name) : CoreM Name := /- This covers auxiliary declarations like `match_i` and `proof_i`. -/ if let some post := pre.isPrefixOf? src then return tgt_pre ++ post /- This covers equation lemmas (for other declarations). -/ else if let some post := privateToUserName? src then match findTranslation? env post.getPrefix with -- this is an equation lemma for a declaration without `to_additive`. We will skip this. | none => return src -- this is an equation lemma for a declaration with `to_additive`. We will additivize this. -- Note: if this errors we could do this instead by calling `getEqnsFor?` | some addName => return src.updatePrefix <| mkPrivateName env addName else if src.hasMacroScopes then mkFreshUserName src.eraseMacroScopes else throwError "internal @[to_additive] error." /-- Returns a `NameSet` of all auxiliary constants in `e` that might have been generated when adding `pre` to the environment. Examples include `pre.match_5` and `_private.Mathlib.MyFile.someOtherNamespace.someOtherDeclaration._eq_2`. The last two examples may or may not have been generated by this declaration. The last example may or may not be the equation lemma of a declaration with the `@[to_additive]` attribute. We will only translate it has the `@[to_additive]` attribute. -/ def findAuxDecls (e : Expr) (pre : Name) : NameSet := e.foldConsts ∅ fun n l ↦ if n.getPrefix == pre || isPrivateName n || n.hasMacroScopes then l.insert n else l /-- transform the declaration `src` and all declarations `pre._proof_i` occurring in `src` using the transforms dictionary. `replace_all`, `trace`, `ignore` and `reorder` are configuration options. `pre` is the declaration that got the `@[to_additive]` attribute and `tgt_pre` is the target of this declaration. -/ partial def transformDeclAux (cfg : Config) (pre tgt_pre : Name) : Name → CoreM Unit := fun src ↦ do let env ← getEnv trace[to_additive_detail] "visiting {src}" -- if we have already translated this declaration, we do nothing. if (findTranslation? env src).isSome && src != pre then return -- if this declaration is not `pre` and not an internal declaration, we return an error, -- since we should have already translated this declaration. if src != pre && !src.isInternalDetail then throwError "The declaration {pre} depends on the declaration {src} which is in the namespace \ {pre}, but does not have the `@[to_additive]` attribute. This is not supported.\n\ Workaround: move {src} to a different namespace." -- we find the additive name of `src` let tgt ← findTargetName env src pre tgt_pre -- we skip if we already transformed this declaration before. if env.contains tgt then if tgt == src then -- Note: this can happen for equation lemmas of declarations without `@[to_additive]`. trace[to_additive_detail] "Auxiliary declaration {src} will be translated to itself." else trace[to_additive_detail] "Already visited {tgt} as translation of {src}." return let srcDecl ← getConstInfo src -- we first transform all auxiliary declarations generated when elaborating `pre` for n in findAuxDecls srcDecl.type pre do transformDeclAux cfg pre tgt_pre n if let some value := srcDecl.value? then for n in findAuxDecls value pre do transformDeclAux cfg pre tgt_pre n if let .opaqueInfo {value, ..} := srcDecl then for n in findAuxDecls value pre do transformDeclAux cfg pre tgt_pre n -- if the auxiliary declaration doesn't have prefix `pre`, then we have to add this declaration -- to the translation dictionary, since otherwise we cannot find the additive name. if !pre.isPrefixOf src then insertTranslation src tgt -- now transform the source declaration let trgDecl : ConstantInfo ← MetaM.run' <| updateDecl tgt srcDecl <| if src == pre then cfg.reorder else [] let value ← match trgDecl with | .thmInfo { value, .. } | .defnInfo { value, .. } | .opaqueInfo { value, .. } => pure value | _ => throwError "Expected {tgt} to have a value." trace[to_additive] "generating\n{tgt} : {trgDecl.type} :=\n {value}" try -- make sure that the type is correct, -- and emit a more helpful error message if it fails discard <| MetaM.run' <| inferType value catch | Exception.error _ msg => throwError "@[to_additive] failed. \ Type mismatch in additive declaration. For help, see the docstring \ of `to_additive.attr`, section `Troubleshooting`. \ Failed to add declaration\n{tgt}:\n{msg}" | _ => panic! "unreachable" if isNoncomputable env src then addDecl trgDecl.toDeclaration! setEnv <| addNoncomputable (← getEnv) tgt else addAndCompile trgDecl.toDeclaration! -- now add declaration ranges so jump-to-definition works -- note: we currently also do this for auxiliary declarations, while they are not normally -- generated for those. We could change that. addDeclarationRanges tgt { range := ← getDeclarationRange (← getRef) selectionRange := ← getDeclarationRange cfg.ref } if isProtected (← getEnv) src then setEnv <| addProtected (← getEnv) tgt /-- Copy the instance attribute in a `to_additive` [todo] it seems not to work when the `to_additive` is added as an attribute later. -/ def copyInstanceAttribute (src tgt : Name) : CoreM Unit := do if (← isInstance src) then let prio := (← getInstancePriority? src).getD 100 let attr_kind := (← getInstanceAttrKind? src).getD .global trace[to_additive_detail] "Making {tgt} an instance with priority {prio}." addInstance tgt attr_kind prio |>.run' /-- Warn the user when the multiplicative declaration has an attribute. -/ def warnExt {σ α β : Type} [Inhabited σ] (stx : Syntax) (ext : PersistentEnvExtension α β σ) (f : σ → Name → Bool) (thisAttr attrName src tgt : Name) : CoreM Unit := do if f (ext.getState (← getEnv)) src then Linter.logLintIf linter.existingAttributeWarning stx <| m!"The source declaration {src} was given attribute {attrName} before calling @[{thisAttr}]. \ The preferred method is to use `@[{thisAttr} (attr := {attrName})]` to apply the \ attribute to both {src} and the target declaration {tgt}." ++ if thisAttr == `to_additive then m!"\nSpecial case: If this declaration was generated by @[to_additive] \ itself, you can use @[to_additive (attr := to_additive, {attrName})] on the original \ declaration." else "" /-- Warn the user when the multiplicative declaration has a simple scoped attribute. -/ def warnAttr {α β : Type} [Inhabited β] (stx : Syntax) (attr : SimpleScopedEnvExtension α β) (f : β → Name → Bool) (thisAttr attrName src tgt : Name) : CoreM Unit := warnExt stx attr.ext (f ·.stateStack.head!.state ·) thisAttr attrName src tgt /-- Warn the user when the multiplicative declaration has a parametric attribute. -/ def warnParametricAttr {β : Type} (stx : Syntax) (attr : ParametricAttribute β) (thisAttr attrName src tgt : Name) : CoreM Unit := warnExt stx attr.ext (·.contains ·) thisAttr attrName src tgt /-- `additivizeLemmas names desc t` runs `t` on all elements of `names` and adds translations between the generated lemmas (the output of `t`). `names` must be non-empty. -/ def additivizeLemmas {m : Type → Type} [Monad m] [MonadError m] [MonadLiftT CoreM m] (names : Array Name) (desc : String) (t : Name → m (Array Name)) : m Unit := do let auxLemmas ← names.mapM t let nLemmas := auxLemmas[0]!.size for (nm, lemmas) in names.zip auxLemmas do unless lemmas.size == nLemmas do throwError "{names[0]!} and {nm} do not generate the same number of {desc}." for (srcLemmas, tgtLemmas) in auxLemmas.zip <| auxLemmas.eraseIdx 0 do for (srcLemma, tgtLemma) in srcLemmas.zip tgtLemmas do insertTranslation srcLemma tgtLemma /-- Find the first argument of `nm` that has a multiplicative type-class on it. Returns 1 if there are no types with a multiplicative class as arguments. E.g. `Prod.Group` returns 1, and `Pi.One` returns 2. Note: we only consider the first argument of each type-class. E.g. `[Pow A N]` is a multiplicative type-class on `A`, not on `N`. -/ def firstMultiplicativeArg (nm : Name) : MetaM Nat := do forallTelescopeReducing (← getConstInfo nm).type fun xs _ ↦ do -- xs are the arguments to the constant let xs := xs.toList let l ← xs.filterMapM fun x ↦ do -- x is an argument and i is the index -- write `x : (y₀ : α₀) → ... → (yₙ : αₙ) → tgt_fn tgt_args₀ ... tgt_argsₘ` forallTelescopeReducing (← inferType x) fun _ys tgt ↦ do let (_tgt_fn, tgt_args) := tgt.getAppFnArgs if let some c := tgt.getAppFn.constName? then if findTranslation? (← getEnv) c |>.isNone then return none return tgt_args[0]?.bind fun tgtArg ↦ xs.findIdx? fun x ↦ Expr.containsFVar tgtArg x.fvarId! trace[to_additive_detail] "firstMultiplicativeArg: {l}" match l with | [] => return 0 | (head :: tail) => return tail.foldr Nat.min head /-- Helper for `capitalizeLike`. -/ partial def capitalizeLikeAux (s : String) (i : String.Pos := 0) (p : String) : String := if p.atEnd i || s.atEnd i then p else let j := p.next i if (s.get i).isLower then capitalizeLikeAux s j <| p.set i (p.get i |>.toLower) else if (s.get i).isUpper then capitalizeLikeAux s j <| p.set i (p.get i |>.toUpper) else capitalizeLikeAux s j p /-- Capitalizes `s` char-by-char like `r`. If `s` is longer, it leaves the tail untouched. -/ def capitalizeLike (r : String) (s : String) := capitalizeLikeAux r 0 s /-- Capitalize First element of a list like `s`. Note that we need to capitalize multiple characters in some cases, in examples like `HMul` or `hAdd`. -/ def capitalizeFirstLike (s : String) : List String → List String | x :: r => capitalizeLike s x :: r | [] => [] /-- Dictionary used by `guessName` to autogenerate names. Note: `guessName` capitalizes first element of the output according to capitalization of the input. Input and first element should therefore be lower-case, 2nd element should be capitalized properly. -/ def nameDict : String → List String | "one" => ["zero"] | "mul" => ["add"] | "smul" => ["vadd"] | "inv" => ["neg"] | "div" => ["sub"] | "prod" => ["sum"] | "hmul" => ["hadd"] | "hsmul" => ["hvadd"] | "hdiv" => ["hsub"] | "hpow" => ["hsmul"] | "finprod" => ["finsum"] | "tprod" => ["tsum"] | "pow" => ["nsmul"] | "npow" => ["nsmul"] | "zpow" => ["zsmul"] | "mabs" => ["abs"] | "monoid" => ["add", "Monoid"] | "submonoid" => ["add", "Submonoid"] | "group" => ["add", "Group"] | "subgroup" => ["add", "Subgroup"] | "semigroup" => ["add", "Semigroup"] | "magma" => ["add", "Magma"] | "haar" => ["add", "Haar"] | "prehaar" => ["add", "Prehaar"] | "unit" => ["add", "Unit"] | "units" => ["add", "Units"] | "cyclic" => ["add", "Cyclic"] | "rootable" => ["divisible"] | "semigrp" => ["add", "Semigrp"] | "grp" => ["add", "Grp"] | "commute" => ["add", "Commute"] | "semiconj" => ["add", "Semiconj"] | "zpowers" => ["zmultiples"] | "powers" => ["multiples"] | "multipliable"=> ["summable"] | x => [x] /-- Turn each element to lower-case, apply the `nameDict` and capitalize the output like the input. -/ def applyNameDict : List String → List String | x :: s => (capitalizeFirstLike x (nameDict x.toLower)) ++ applyNameDict s | [] => [] /-- There are a few abbreviations we use. For example "Nonneg" instead of "ZeroLE" or "addComm" instead of "commAdd". Note: The input to this function is case sensitive! Todo: A lot of abbreviations here are manual fixes and there might be room to improve the naming logic to reduce the size of `fixAbbreviation`. -/ def fixAbbreviation : List String → List String | "cancel" :: "Add" :: s => "addCancel" :: fixAbbreviation s | "Cancel" :: "Add" :: s => "AddCancel" :: fixAbbreviation s | "left" :: "Cancel" :: "Add" :: s => "addLeftCancel" :: fixAbbreviation s | "Left" :: "Cancel" :: "Add" :: s => "AddLeftCancel" :: fixAbbreviation s | "right" :: "Cancel" :: "Add" :: s => "addRightCancel" :: fixAbbreviation s | "Right" :: "Cancel" :: "Add" :: s => "AddRightCancel" :: fixAbbreviation s | "cancel" :: "Comm" :: "Add" :: s => "addCancelComm" :: fixAbbreviation s | "Cancel" :: "Comm" :: "Add" :: s => "AddCancelComm" :: fixAbbreviation s | "comm" :: "Add" :: s => "addComm" :: fixAbbreviation s | "Comm" :: "Add" :: s => "AddComm" :: fixAbbreviation s | "Zero" :: "LE" :: s => "Nonneg" :: fixAbbreviation s | "zero" :: "_" :: "le" :: s => "nonneg" :: fixAbbreviation s | "Zero" :: "LT" :: s => "Pos" :: fixAbbreviation s | "zero" :: "_" :: "lt" :: s => "pos" :: fixAbbreviation s | "LE" :: "Zero" :: s => "Nonpos" :: fixAbbreviation s | "le" :: "_" :: "zero" :: s => "nonpos" :: fixAbbreviation s | "LT" :: "Zero" :: s => "Neg" :: fixAbbreviation s | "lt" :: "_" :: "zero" :: s => "neg" :: fixAbbreviation s | "Add" :: "Single" :: s => "Single" :: fixAbbreviation s | "add" :: "Single" :: s => "single" :: fixAbbreviation s | "add" :: "_" :: "single" :: s => "single" :: fixAbbreviation s | "Add" :: "Support" :: s => "Support" :: fixAbbreviation s | "add" :: "Support" :: s => "support" :: fixAbbreviation s | "add" :: "_" :: "support" :: s => "support" :: fixAbbreviation s | "Add" :: "TSupport" :: s => "TSupport" :: fixAbbreviation s | "add" :: "TSupport" :: s => "tsupport" :: fixAbbreviation s | "add" :: "_" :: "tsupport" :: s => "tsupport" :: fixAbbreviation s | "Add" :: "Indicator" :: s => "Indicator" :: fixAbbreviation s | "add" :: "Indicator" :: s => "indicator" :: fixAbbreviation s | "add" :: "_" :: "indicator" :: s => "indicator" :: fixAbbreviation s | "is" :: "Square" :: s => "even" :: fixAbbreviation s | "Is" :: "Square" :: s => "Even" :: fixAbbreviation s -- "Regular" is well-used in mathlib with various meanings (e.g. in -- measure theory) and a direct translation -- "regular" --> ["add", "Regular"] in `nameDict` above seems error-prone. | "is" :: "Regular" :: s => "isAddRegular" :: fixAbbreviation s | "Is" :: "Regular" :: s => "IsAddRegular" :: fixAbbreviation s | "is" :: "Left" :: "Regular" :: s => "isAddLeftRegular" :: fixAbbreviation s | "Is" :: "Left" :: "Regular" :: s => "IsAddLeftRegular" :: fixAbbreviation s | "is" :: "Right" :: "Regular" :: s => "isAddRightRegular" :: fixAbbreviation s | "Is" :: "Right" :: "Regular" :: s => "IsAddRightRegular" :: fixAbbreviation s | "Has" :: "Fundamental" :: "Domain" :: s => "HasAddFundamentalDomain" :: fixAbbreviation s | "has" :: "Fundamental" :: "Domain" :: s => "hasAddFundamentalDomain" :: fixAbbreviation s | "Quotient" :: "Measure" :: s => "AddQuotientMeasure" :: fixAbbreviation s | "quotient" :: "Measure" :: s => "addQuotientMeasure" :: fixAbbreviation s -- the capitalization heuristic of `applyNameDict` doesn't work in the following cases | "HSmul" :: s => "HSMul" :: fixAbbreviation s -- from `HPow` | "NSmul" :: s => "NSMul" :: fixAbbreviation s -- from `NPow` | "Nsmul" :: s => "NSMul" :: fixAbbreviation s -- from `Pow` | "ZSmul" :: s => "ZSMul" :: fixAbbreviation s -- from `ZPow` | "neg" :: "Fun" :: s => "invFun" :: fixAbbreviation s | "Neg" :: "Fun" :: s => "InvFun" :: fixAbbreviation s | "unique" :: "Prods" :: s => "uniqueSums" :: fixAbbreviation s | "Unique" :: "Prods" :: s => "UniqueSums" :: fixAbbreviation s | "order" :: "Of" :: s => "addOrderOf" :: fixAbbreviation s | "Order" :: "Of" :: s => "AddOrderOf" :: fixAbbreviation s | "is"::"Of"::"Fin"::"Order"::s => "isOfFinAddOrder" :: fixAbbreviation s | "Is"::"Of"::"Fin"::"Order"::s => "IsOfFinAddOrder" :: fixAbbreviation s | "is" :: "Central" :: "Scalar" :: s => "isCentralVAdd" :: fixAbbreviation s | "Is" :: "Central" :: "Scalar" :: s => "IsCentralVAdd" :: fixAbbreviation s | "function" :: "_" :: "add" :: "Semiconj" :: s => "function" :: "_" :: "semiconj" :: fixAbbreviation s | "function" :: "_" :: "add" :: "Commute" :: s => "function" :: "_" :: "commute" :: fixAbbreviation s | "zero" :: "Le" :: "Part" :: s => "posPart" :: fixAbbreviation s | "le" :: "Zero" :: "Part" :: s => "negPart" :: fixAbbreviation s | "three" :: "GPFree" :: s => "three" :: "APFree" :: fixAbbreviation s | "Three" :: "GPFree" :: s => "Three" :: "APFree" :: fixAbbreviation s | x :: s => x :: fixAbbreviation s | [] => [] /-- Autogenerate additive name. This runs in several steps: 1) Split according to capitalisation rule and at `_`. 2) Apply word-by-word translation rules. 3) Fix up abbreviations that are not word-by-word translations, like "addComm" or "Nonneg". -/ def guessName : String → String := String.mapTokens '\'' <| fun s => String.join <| fixAbbreviation <| applyNameDict <| s.splitCase /-- Return the provided target name or autogenerate one if one was not provided. -/ def targetName (cfg : Config) (src : Name) : CoreM Name := do let .str pre s := src | throwError "to_additive: can't transport {src}" trace[to_additive_detail] "The name {s} splits as {s.splitCase}" let tgt_auto := guessName s let depth := cfg.tgt.getNumParts let pre := pre.mapPrefix <| findTranslation? (← getEnv) let (pre1, pre2) := pre.splitAt (depth - 1) if cfg.tgt == pre2.str tgt_auto && !cfg.allowAutoName && cfg.tgt != src then Linter.logLintIf linter.toAdditiveGenerateName cfg.ref m!"\ to_additive correctly autogenerated target name for {src}.\n\ You may remove the explicit argument {cfg.tgt}." let res := if cfg.tgt == .anonymous then pre.str tgt_auto else pre1 ++ cfg.tgt -- we allow translating to itself if `tgt == src`, which is occasionally useful for `additiveTest` if res == src && cfg.tgt != src then throwError "to_additive: can't transport {src} to itself." if cfg.tgt != .anonymous then trace[to_additive_detail] "The automatically generated name would be {pre.str tgt_auto}" return res /-- if `f src = #[a_1, ..., a_n]` and `f tgt = #[b_1, ... b_n]` then `proceedFieldsAux src tgt f` will insert translations from `src.a_i` to `tgt.b_i`. -/ def proceedFieldsAux (src tgt : Name) (f : Name → CoreM (Array Name)) : CoreM Unit := do let srcFields ← f src let tgtFields ← f tgt if srcFields.size != tgtFields.size then throwError "Failed to map fields of {src}, {tgt} with {srcFields} ↦ {tgtFields}" for (srcField, tgtField) in srcFields.zip tgtFields do if srcField != tgtField then insertTranslation (src ++ srcField) (tgt ++ tgtField) else trace[to_additive] "Translation {src ++ srcField} ↦ {tgt ++ tgtField} is automatic." /-- Add the structure fields of `src` to the translations dictionary so that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/ def proceedFields (src tgt : Name) : CoreM Unit := do let aux := proceedFieldsAux src tgt aux fun declName ↦ do if isStructure (← getEnv) declName then return getStructureFields (← getEnv) declName else return #[] aux fun declName ↦ do match (← getEnv).find? declName with | some (ConstantInfo.inductInfo {ctors := ctors, ..}) => return ctors.toArray.map (.mkSimple ·.lastComponentAsString) | _ => pure #[] /-- Elaboration of the configuration options for `to_additive`. -/ def elabToAdditive : Syntax → CoreM Config | `(attr| to_additive%$tk $[?%$trace]? $[$opts:toAdditiveOption]* $[$tgt]? $[$doc]?) => do let mut attrs := #[] let mut reorder := [] let mut existing := some false for stx in opts do match stx with | `(toAdditiveOption| (attr := $[$stxs],*)) => attrs := attrs ++ stxs | `(toAdditiveOption| (reorder := $[$[$reorders:num]*],*)) => reorder := reorder ++ reorders.toList.map (·.toList.map (·.raw.isNatLit?.get! - 1)) | `(toAdditiveOption| existing) => existing := some true | _ => throwUnsupportedSyntax reorder := reorder.reverse trace[to_additive_detail] "attributes: {attrs}; reorder arguments: {reorder}" return { trace := trace.isSome tgt := match tgt with | some tgt => tgt.getId | none => Name.anonymous doc := doc.bind (·.raw.isStrLit?) allowAutoName := false attrs reorder existing ref := (tgt.map (·.raw)).getD tk } | _ => throwUnsupportedSyntax mutual /-- Apply attributes to the multiplicative and additive declarations. -/ partial def applyAttributes (stx : Syntax) (rawAttrs : Array Syntax) (thisAttr src tgt : Name) : TermElabM (Array Name) := do -- we only copy the `instance` attribute, since `@[to_additive] instance` is nice to allow copyInstanceAttribute src tgt -- Warn users if the multiplicative version has an attribute if linter.existingAttributeWarning.get (← getOptions) then let appliedAttrs ← getAllSimpAttrs src if appliedAttrs.size > 0 then Linter.logLintIf linter.existingAttributeWarning stx m!"\ The source declaration {src} was given the simp-attribute(s) {appliedAttrs} before \ calling @[{thisAttr}]. The preferred method is to use \ `@[{thisAttr} (attr := {appliedAttrs})]` to apply the attribute to both \ {src} and the target declaration {tgt}." warnAttr stx Lean.Elab.Tactic.Ext.extExtension (fun b n => (b.tree.values.any fun t => t.declName = n)) thisAttr `ext src tgt warnAttr stx Lean.Meta.Rfl.reflExt (·.values.contains ·) thisAttr `refl src tgt warnAttr stx Lean.Meta.Symm.symmExt (·.values.contains ·) thisAttr `symm src tgt warnAttr stx Mathlib.Tactic.transExt (·.values.contains ·) thisAttr `trans src tgt warnAttr stx Lean.Meta.coeExt (·.contains ·) thisAttr `coe src tgt warnParametricAttr stx Lean.Linter.deprecatedAttr thisAttr `deprecated src tgt -- the next line also warns for `@[to_additive, simps]`, because of the application times warnParametricAttr stx simpsAttr thisAttr `simps src tgt warnExt stx Term.elabAsElim.ext (·.contains ·) thisAttr `elab_as_elim src tgt -- add attributes -- the following is similar to `Term.ApplyAttributesCore`, but we hijack the implementation of -- `simps` and `to_additive`. let attrs ← elabAttrs rawAttrs let (additiveAttrs, attrs) := attrs.partition (·.name == `to_additive) let nestedDecls ← match additiveAttrs.size with | 0 => pure #[] | 1 => addToAdditiveAttr tgt (← elabToAdditive additiveAttrs[0]!.stx) additiveAttrs[0]!.kind | _ => throwError "cannot apply {thisAttr} multiple times." let allDecls := #[src, tgt] ++ nestedDecls if attrs.size > 0 then trace[to_additive_detail] "Applying attributes {attrs.map (·.stx)} to {allDecls}" for attr in attrs do withRef attr.stx do withLogging do if attr.name == `simps then additivizeLemmas allDecls "simps lemmas" (simpsTacFromSyntax · attr.stx) return let env ← getEnv match getAttributeImpl env attr.name with | Except.error errMsg => throwError errMsg | Except.ok attrImpl => let runAttr := do for decl in allDecls do attrImpl.add decl attr.stx attr.kind -- not truly an elaborator, but a sensible target for go-to-definition let elaborator := attrImpl.ref if (← getInfoState).enabled && (← getEnv).contains elaborator then withInfoContext (mkInfo := return .ofCommandInfo { elaborator, stx := attr.stx }) do try runAttr finally if attr.stx[0].isIdent || attr.stx[0].isAtom then -- Add an additional node over the leading identifier if there is one -- to make it look more function-like. -- Do this last because we want user-created infos to take precedence pushInfoLeaf <| .ofCommandInfo { elaborator, stx := attr.stx[0] } else runAttr return nestedDecls /-- Copies equation lemmas and attributes from `src` to `tgt` -/ partial def copyMetaData (cfg : Config) (src tgt : Name) : CoreM (Array Name) := do if let some eqns := eqnsAttribute.find? (← getEnv) src then unless (eqnsAttribute.find? (← getEnv) tgt).isSome do for eqn in eqns do _ ← addToAdditiveAttr eqn cfg eqnsAttribute.add tgt (eqns.map (findTranslation? (← getEnv) · |>.get!)) else /- We need to generate all equation lemmas for `src` and `tgt`, even for non-recursive definitions. If we don't do that, the equation lemma for `src` might be generated later when doing a `rw`, but it won't be generated for `tgt`. -/ additivizeLemmas #[src, tgt] "equation lemmas" fun nm ↦ (·.getD #[]) <$> MetaM.run' (getEqnsFor? nm true) MetaM.run' <| Elab.Term.TermElabM.run' <| applyAttributes cfg.ref cfg.attrs `to_additive src tgt /-- Make a new copy of a declaration, replacing fragments of the names of identifiers in the type and the body using the `translations` dictionary. This is used to implement `@[to_additive]`. -/ partial def transformDecl (cfg : Config) (src tgt : Name) : CoreM (Array Name) := do transformDeclAux cfg src tgt src copyMetaData cfg src tgt /-- `addToAdditiveAttr src cfg` adds a `@[to_additive]` attribute to `src` with configuration `cfg`. See the attribute implementation for more details. It returns an array with names of additive declarations (usually 1, but more if there are nested `to_additive` calls. -/ partial def addToAdditiveAttr (src : Name) (cfg : Config) (kind := AttributeKind.global) : AttrM (Array Name) := do if (kind != AttributeKind.global) then throwError "`to_additive` can only be used as a global attribute" withOptions (· |>.updateBool `trace.to_additive (cfg.trace || ·)) <| do let tgt ← targetName cfg src let alreadyExists := (← getEnv).contains tgt if cfg.existing == some !alreadyExists && !(← isInductive src) then Linter.logLintIf linter.toAdditiveExisting cfg.ref <| if alreadyExists then m!"The additive declaration already exists. Please specify this explicitly using \ `@[to_additive existing]`." else "The additive declaration doesn't exist. Please remove the option `existing`." if cfg.reorder != [] then trace[to_additive] "@[to_additive] will reorder the arguments of {tgt}." reorderAttr.add src cfg.reorder -- we allow using this attribute if it's only to add the reorder configuration if findTranslation? (← getEnv) src |>.isSome then return #[tgt] let firstMultArg ← MetaM.run' <| firstMultiplicativeArg src if firstMultArg != 0 then trace[to_additive_detail] "Setting relevant_arg for {src} to be {firstMultArg}." relevantArgAttr.add src firstMultArg insertTranslation src tgt alreadyExists let nestedNames ← if alreadyExists then -- since `tgt` already exists, we just need to copy metadata and -- add translations `src.x ↦ tgt.x'` for any subfields. trace[to_additive_detail] "declaration {tgt} already exists." proceedFields src tgt copyMetaData cfg src tgt else -- tgt doesn't exist, so let's make it transformDecl cfg src tgt -- add pop-up information when mousing over `additive_name` of `@[to_additive additive_name]` -- (the information will be over the attribute of no additive name is given) pushInfoLeaf <| .ofTermInfo { elaborator := .anonymous, lctx := {}, expectedType? := none, isBinder := !alreadyExists, stx := cfg.ref, expr := ← mkConstWithLevelParams tgt } if let some doc := cfg.doc then addDocString tgt doc return nestedNames.push tgt end /-- The attribute `to_additive` can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. To use this attribute, just write: ``` @[to_additive] theorem mul_comm' {α} [CommSemigroup α] (x y : α) : x * y = y * x := mul_comm x y ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration: ``` @[to_additive add_foo] theorem foo := sorry ``` An existing documentation string will _not_ be automatically used, so if the theorem or definition has a doc string, a doc string for the additive version should be passed explicitly to `to_additive`. ``` /-- Multiplication is commutative -/ @[to_additive "Addition is commutative"] theorem mul_comm' {α} [CommSemigroup α] (x y : α) : x * y = y * x := CommSemigroup.mul_comm ``` The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. Use the `(reorder := ...)` syntax to reorder the arguments in the generated additive declaration. This is specified using cycle notation. For example `(reorder := 1 2, 5 6)` swaps the first two arguments with each other and the fifth and the sixth argument and `(reorder := 3 4 5)` will move the fifth argument before the third argument. This is mostly useful to translate declarations using `Pow` to those using `SMul`. Use the `(attr := ...)` syntax to apply attributes to both the multiplicative and the additive version: ``` @[to_additive (attr := simp)] lemma mul_one' {G : Type*} [Group G] (x : G) : x * 1 = x := mul_one x ``` For `simps` this also ensures that some generated lemmas are added to the additive dictionary. `@[to_additive (attr := to_additive)]` is a special case, where the `to_additive` attribute is added to the generated lemma only, to additivize it again. This is useful for lemmas about `Pow` to generate both lemmas about `SMul` and `VAdd`. Example: ``` @[to_additive (attr := to_additive VAdd_lemma, simp) SMul_lemma] lemma Pow_lemma ... := ``` In the above example, the `simp` is added to all 3 lemmas. All other options to `to_additive` (like the generated name or `(reorder := ...)`) are not passed down, and can be given manually to each individual `to_additive` call. ## Implementation notes The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with `to_additive`. In the `mul_comm'` example above, `to_additive` maps: * `mul_comm'` to `add_comm'`, * `CommSemigroup` to `AddCommSemigroup`, * `x * y` to `x + y` and `y * x` to `y + x`, and * `CommSemigroup.mul_comm'` to `AddCommSemigroup.add_comm'`. ### Heuristics `to_additive` uses heuristics to determine whether a particular identifier has to be mapped to its additive version. The basic heuristic is * Only map an identifier to its additive version if its first argument doesn't contain any unapplied identifiers. Examples: * `@Mul.mul Nat n m` (i.e. `(n * m : Nat)`) will not change to `+`, since its first argument is `Nat`, an identifier not applied to any arguments. * `@Mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier `Prod`, but this is applied to arguments, `α` and `β`. * `@Mul.mul (α × Int) x y` will not change to `+`, since its first argument contains `Int`. The reasoning behind the heuristic is that the first argument is the type which is "additivized", and this usually doesn't make sense if this is on a fixed type. There are some exceptions to this heuristic: * Identifiers that have the `@[to_additive]` attribute are ignored. For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`. * If an identifier `d` has attribute `@[to_additive_relevant_arg n]` then the argument in position `n` is checked for a fixed type, instead of checking the first argument. `@[to_additive]` will automatically add the attribute `@[to_additive_relevant_arg n]` to a declaration when the first argument has no multiplicative type-class, but argument `n` does. * If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1). For example, `ContMDiffMap` has attribute `@[to_additive_ignore_args 21]`, which means that its 21st argument `(n : WithTop ℕ)` can contain `ℕ` (usually in the form `Top.top ℕ ...`) and still be additivized. So `@Mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized. ### Troubleshooting If `@[to_additive]` fails because the additive declaration raises a type mismatch, there are various things you can try. The first thing to do is to figure out what `@[to_additive]` did wrong by looking at the type mismatch error. * Option 1: The most common case is that it didn't additivize a declaration that should be additivized. This happened because the heuristic applied, and the first argument contains a fixed type, like `ℕ` or `ℝ`. However, the heuristic misfires on some other declarations. Solutions: * First figure out what the fixed type is in the first argument of the declaration that didn't get additivized. Note that this fixed type can occur in implicit arguments. If manually finding it is hard, you can run `set_option trace.to_additive_detail true` and search the output for the fragment "contains the fixed type" to find what the fixed type is. * If the fixed type has an additive counterpart (like `↥Semigroup`), give it the `@[to_additive]` attribute. * If the fixed type has nothing to do with algebraic operations (like `TopCat`), add the attribute `@[to_additive existing Foo]` to the fixed type `Foo`. * If the fixed type occurs inside the `k`-th argument of a declaration `d`, and the `k`-th argument is not connected to the multiplicative structure on `d`, consider adding attribute `[to_additive_ignore_args k]` to `d`. Example: `ContMDiffMap` ignores the argument `(n : WithTop ℕ)` * Option 2: It additivized a declaration `d` that should remain multiplicative. Solution: * Make sure the first argument of `d` is a type with a multiplicative structure. If not, can you reorder the (implicit) arguments of `d` so that the first argument becomes a type with a multiplicative structure (and not some indexing type)? The reason is that `@[to_additive]` doesn't additivize declarations if their first argument contains fixed types like `ℕ` or `ℝ`. See section Heuristics. If the first argument is not the argument with a multiplicative type-class, `@[to_additive]` should have automatically added the attribute `@[to_additive_relevant_arg]` to the declaration. You can test this by running the following (where `d` is the full name of the declaration): ``` open Lean in run_cmd logInfo m!"{ToAdditive.relevantArgAttr.find? (← getEnv) `d}" ``` The expected output is `n` where the `n`-th (0-indexed) argument of `d` is a type (family) with a multiplicative structure on it. `none` means `0`. If you get a different output (or a failure), you could add the attribute `@[to_additive_relevant_arg n]` manually, where `n` is an (1-indexed) argument with a multiplicative structure. * Option 3: Arguments / universe levels are incorrectly ordered in the additive version. This likely only happens when the multiplicative declaration involves `pow`/`^`. Solutions: * Ensure that the order of arguments of all relevant declarations are the same for the multiplicative and additive version. This might mean that arguments have an "unnatural" order (e.g. `Monoid.npow n x` corresponds to `x ^ n`, but it is convenient that `Monoid.npow` has this argument order, since it matches `AddMonoid.nsmul n x`. * If this is not possible, add `(reorder := ...)` argument to `to_additive`. If neither of these solutions work, and `to_additive` is unable to automatically generate the additive version of a declaration, manually write and prove the additive version. Often the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to `multiplicative G`. Afterwards, apply the attribute manually: ``` attribute [to_additive foo_add_bar] foo_bar ``` This will allow future uses of `to_additive` to recognize that `foo_bar` should be replaced with `foo_add_bar`. ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. In addition to transporting the “main” declaration, `to_additive` transports its equational lemmas and tags them as equational lemmas for the new declaration. ### Structure fields and constructors If `src` is a structure, then the additive version has to be already written manually. In this case `to_additive` adds all structure fields to its mapping. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * [todo] Namespaces can be transformed using `map_namespace`. For example: ``` run_cmd to_additive.map_namespace `QuotientGroup `QuotientAddGroup ``` Later uses of `to_additive` on declarations in the `QuotientGroup` namespace will be created in the `QuotientAddGroup` namespaces. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `NewNamespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first case `to_additive` double checks that the new name differs from the original one. -/ initialize registerBuiltinAttribute { name := `to_additive descr := "Transport multiplicative to additive" add := fun src stx kind ↦ do _ ← addToAdditiveAttr src (← elabToAdditive stx) kind -- we (presumably) need to run after compilation to properly add the `simp` attribute applicationTime := .afterCompilation } end ToAdditive
Tactic\Widget\Calc.lean
/- Copyright (c) 2023 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Lean.Elab.Tactic.Calc import Mathlib.Data.String.Defs import Mathlib.Tactic.Widget.SelectPanelUtils import Batteries.CodeAction.Attr import Batteries.Lean.Position /-! # Calc widget This file redefines the `calc` tactic so that it displays a widget panel allowing to create new calc steps with holes specified by selected sub-expressions in the goal. -/ section code_action open Std CodeAction open Lean Server RequestM /-- Code action to create a `calc` tactic from the current goal. -/ @[tactic_code_action calcTactic] def createCalc : TacticCodeAction := fun _params _snap ctx _stack node => do let .node (.ofTacticInfo info) _ := node | return #[] if info.goalsBefore.isEmpty then return #[] let eager := { title := s!"Generate a calc block." kind? := "quickfix" } let doc ← readDoc return #[{ eager lazy? := some do let tacPos := doc.meta.text.utf8PosToLspPos info.stx.getPos?.get! let endPos := doc.meta.text.utf8PosToLspPos info.stx.getTailPos?.get! let goal := info.goalsBefore[0]! let goalFmt ← ctx.runMetaM {} <| goal.withContext do Meta.ppExpr (← goal.getType) return { eager with edit? := some <|.ofTextEdit doc.versionedIdentifier { range := ⟨tacPos, endPos⟩, newText := s!"calc {goalFmt} := by sorry" } } }] end code_action open ProofWidgets open Lean Meta open Lean Server in /-- Parameters for the calc widget. -/ structure CalcParams extends SelectInsertParams where /-- Is this the first calc step? -/ isFirst : Bool /-- indentation level of the calc block. -/ indent : Nat deriving SelectInsertParamsClass, RpcEncodable open Lean Meta /-- Return the link text and inserted text above and below of the calc widget. -/ def suggestSteps (pos : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) (params : CalcParams) : MetaM (String × String × Option (String.Pos × String.Pos)) := do let subexprPos := getGoalLocations pos let some (rel, lhs, rhs) ← Lean.Elab.Term.getCalcRelation? goalType | throwError "invalid 'calc' step, relation expected{indentExpr goalType}" let relApp := mkApp2 rel (← mkFreshExprMVar none) (← mkFreshExprMVar none) let some relStr := (← Meta.ppExpr relApp) |> toString |>.splitOn |>.get? 1 | throwError "could not find relation symbol in {relApp}" let isSelectedLeft := subexprPos.any (fun L ↦ #[0, 1].isPrefixOf L.toArray) let isSelectedRight := subexprPos.any (fun L ↦ #[1].isPrefixOf L.toArray) let mut goalType := goalType for pos in subexprPos do goalType ← insertMetaVar goalType pos let some (_, newLhs, newRhs) ← Lean.Elab.Term.getCalcRelation? goalType | unreachable! let lhsStr := (toString <| ← Meta.ppExpr lhs).renameMetaVar let newLhsStr := (toString <| ← Meta.ppExpr newLhs).renameMetaVar let rhsStr := (toString <| ← Meta.ppExpr rhs).renameMetaVar let newRhsStr := (toString <| ← Meta.ppExpr newRhs).renameMetaVar let spc := String.replicate params.indent ' ' let insertedCode := match isSelectedLeft, isSelectedRight with | true, true => if params.isFirst then s!"{lhsStr} {relStr} {newLhsStr} := by sorry\n{spc}_ {relStr} {newRhsStr} := by sorry\n\ {spc}_ {relStr} {rhsStr} := by sorry" else s!"_ {relStr} {newLhsStr} := by sorry\n{spc}\ _ {relStr} {newRhsStr} := by sorry\n{spc}\ _ {relStr} {rhsStr} := by sorry" | false, true => if params.isFirst then s!"{lhsStr} {relStr} {newRhsStr} := by sorry\n{spc}_ {relStr} {rhsStr} := by sorry" else s!"_ {relStr} {newRhsStr} := by sorry\n{spc}_ {relStr} {rhsStr} := by sorry" | true, false => if params.isFirst then s!"{lhsStr} {relStr} {newLhsStr} := by sorry\n{spc}_ {relStr} {rhsStr} := by sorry" else s!"_ {relStr} {newLhsStr} := by sorry\n{spc}_ {relStr} {rhsStr} := by sorry" | false, false => "This should not happen" let stepInfo := match isSelectedLeft, isSelectedRight with | true, true => "Create two new steps" | true, false | false, true => "Create a new step" | false, false => "This should not happen" let pos : String.Pos := insertedCode.find (fun c => c == '?') return (stepInfo, insertedCode, some (pos, ⟨pos.byteIdx + 2⟩) ) /-- Rpc function for the calc widget. -/ @[server_rpc_method] def CalcPanel.rpc := mkSelectionPanelRPC suggestSteps "Please select subterms." "Calc 🔍" /-- The calc widget. -/ @[widget_module] def CalcPanel : Component CalcParams := mk_rpc_widget% CalcPanel.rpc namespace Lean.Elab.Tactic open Meta /-- Elaborator for the `calc` tactic mode variant with widgets. -/ elab_rules : tactic | `(tactic|calc%$calcstx $stx) => do let steps : TSyntax ``calcSteps := ⟨stx⟩ let some calcRange := (← getFileMap).rangeOfStx? calcstx | unreachable! let indent := calcRange.start.character let mut isFirst := true for step in ← Lean.Elab.Term.getCalcSteps steps do let some replaceRange := (← getFileMap).rangeOfStx? step | unreachable! let `(calcStep| $(_) := $proofTerm) := step | unreachable! let json := json% {"replaceRange": $(replaceRange), "isFirst": $(isFirst), "indent": $(indent)} Widget.savePanelWidgetInfo CalcPanel.javascriptHash (pure json) proofTerm isFirst := false evalCalc (← `(tactic|calc%$calcstx $stx))
Tactic\Widget\CommDiag.lean
/- Copyright (c) 2022 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import ProofWidgets.Component.PenroseDiagram import ProofWidgets.Presentation.Expr import Mathlib.CategoryTheory.Category.Basic /-! This module defines tactic/meta infrastructure for displaying commutative diagrams in the infoview. -/ open Lean in /-- If the expression is a function application of `fName` with 7 arguments, return those arguments. Otherwise return `none`. -/ @[inline] def _root_.Lean.Expr.app7? (e : Expr) (fName : Name) : Option (Expr × Expr × Expr × Expr × Expr × Expr × Expr) := if e.isAppOfArity fName 7 then some ( e.appFn!.appFn!.appFn!.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appArg!, e.appFn!.appArg!, e.appArg! ) else none namespace Mathlib.Tactic.Widget open Lean Meta open ProofWidgets open CategoryTheory /-! ## Metaprogramming utilities for breaking down category theory expressions -/ /-- Given a Hom type `α ⟶ β`, return `(α, β)`. Otherwise `none`. -/ def homType? (e : Expr) : Option (Expr × Expr) := do let some (_, _, A, B) := e.app4? ``Quiver.Hom | none return (A, B) /-- Given composed homs `g ≫ h`, return `(g, h)`. Otherwise `none`. -/ def homComp? (f : Expr) : Option (Expr × Expr) := do let some (_, _, _, _, _, f, g) := f.app7? ``CategoryStruct.comp | none return (f, g) /-- Expressions to display as labels in a diagram. -/ abbrev ExprEmbeds := Array (String × Expr) /-! ## Widget for general commutative diagrams -/ open scoped Jsx in /-- Construct a commutative diagram from a Penrose `sub`stance program and expressions `embeds` to display as labels in the diagram. -/ def mkCommDiag (sub : String) (embeds : ExprEmbeds) : MetaM Html := do let embeds ← embeds.mapM fun (s, h) => return (s, <InteractiveCode fmt={← Widget.ppExprTagged h} />) return ( <PenroseDiagram embeds={embeds} dsl={include_str ".."/".."/".."/"widget"/"src"/"penrose"/"commutative.dsl"} sty={include_str ".."/".."/".."/"widget"/"src"/"penrose"/"commutative.sty"} sub={sub} />) /-! ## Commutative triangles -/ /-- Triangle with `homs = [f,g,h]` and `objs = [A,B,C]` ``` A f B h g C ``` -/ def subTriangle := include_str ".."/".."/".."/"widget"/"src"/"penrose"/"triangle.sub" /-- Given a commutative triangle `f ≫ g = h` or `e ≡ h = f ≫ g`, return a triangle diagram. Otherwise `none`. -/ def commTriangleM? (e : Expr) : MetaM (Option Html) := do let e ← instantiateMVars e let some (_, lhs, rhs) := e.eq? | return none if let some (f, g) := homComp? lhs then let some (A, C) := homType? (← inferType rhs) | return none let some (_, B) := homType? (← inferType f) | return none return some <| ← mkCommDiag subTriangle #[("A", A), ("B", B), ("C", C), ("f", f), ("g", g), ("h", rhs)] let some (f, g) := homComp? rhs | return none let some (A, C) := homType? (← inferType lhs) | return none let some (_, B) := homType? (← inferType f) | return none return some <| ← mkCommDiag subTriangle #[("A", A), ("B", B), ("C", C), ("f", f), ("g", g), ("h", lhs)] @[expr_presenter] def commutativeTrianglePresenter : ExprPresenter where userName := "Commutative triangle" layoutKind := .block present type := do if let some d ← commTriangleM? type then return d throwError "Couldn't find a commutative triangle." /-! ## Commutative squares -/ /-- Square with `homs = [f,g,h,i]` and `objs = [A,B,C,D]` ``` A f B i g D h C ``` -/ def subSquare := include_str ".."/".."/".."/"widget"/"src"/"penrose"/"square.sub" /-- Given a commutative square `f ≫ g = i ≫ h`, return a square diagram. Otherwise `none`. -/ def commSquareM? (e : Expr) : MetaM (Option Html) := do let e ← instantiateMVars e let some (_, lhs, rhs) := e.eq? | return none let some (f, g) := homComp? lhs | return none let some (i, h) := homComp? rhs | return none let some (A, B) := homType? (← inferType f) | return none let some (D, C) := homType? (← inferType h) | return none some <$> mkCommDiag subSquare #[("A", A), ("B", B), ("C", C), ("D", D), ("f", f), ("g", g), ("h", h), ("i", i)] @[expr_presenter] def commutativeSquarePresenter : ExprPresenter where userName := "Commutative square" layoutKind := .block present type := do if let some d ← commSquareM? type then return d throwError "Couldn't find a commutative square." end Widget end Tactic end Mathlib
Tactic\Widget\CongrM.lean
/- Copyright (c) 2023 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.Tactic.Widget.SelectPanelUtils import Mathlib.Tactic.CongrM /-! # CongrM widget This file defines a `congrm?` tactic that displays a widget panel allowing to generate a `congrm` call with holes specified by selecting subexpressions in the goal. -/ open Lean Meta Server ProofWidgets /-! # CongrM widget -/ /-- Return the link text and inserted text above and below of the congrm widget. -/ @[nolint unusedArguments] def makeCongrMString (pos : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) (_ : SelectInsertParams) : MetaM (String × String × Option (String.Pos × String.Pos)) := do let subexprPos := getGoalLocations pos unless goalType.isAppOf `Eq || goalType.isAppOf `Iff do throwError "The goal must be an equality or iff." let mut goalTypeWithMetaVars := goalType for pos in subexprPos do goalTypeWithMetaVars ← insertMetaVar goalTypeWithMetaVars pos let side := if subexprPos[0]!.toArray[0]! = 0 then 1 else 2 let sideExpr := goalTypeWithMetaVars.getAppArgs[side]! let res := "congrm " ++ (toString (← Meta.ppExpr sideExpr)).renameMetaVar return (res, res, none) /-- Rpc function for the congrm widget. -/ @[server_rpc_method] def CongrMSelectionPanel.rpc := mkSelectionPanelRPC makeCongrMString "Use shift-click to select sub-expressions in the goal that should become holes in congrm." "CongrM 🔍" /-- The congrm widget. -/ @[widget_module] def CongrMSelectionPanel : Component SelectInsertParams := mk_rpc_widget% CongrMSelectionPanel.rpc open scoped Json in /-- Display a widget panel allowing to generate a `congrm` call with holes specified by selecting subexpressions in the goal. -/ elab stx:"congrm?" : tactic => do let some replaceRange := (← getFileMap).rangeOfStx? stx | return Widget.savePanelWidgetInfo CongrMSelectionPanel.javascriptHash (pure <| json% { replaceRange: $(replaceRange) }) stx
Tactic\Widget\Conv.lean
/- Copyright (c) 2023 Robin Böhne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robin Böhne, Wojciech Nawrocki, Patrick Massot -/ import Mathlib.Tactic.Widget.SelectPanelUtils import Mathlib.Data.String.Defs import Batteries.Tactic.Lint import Batteries.Lean.Position /-! # Conv widget This is a slightly improved version of one of the examples in the ProofWidget library. It defines a `conv?` tactic that displays a widget panel allowing to generate a `conv` call zooming to the subexpression selected in the goal. -/ open Lean Meta Server ProofWidgets private structure SolveReturn where expr : Expr val? : Option String listRest : List Nat private def solveLevel (expr : Expr) (path : List Nat) : MetaM SolveReturn := match expr with | Expr.app _ _ => do let mut descExp := expr let mut count := 0 let mut explicitList := [] -- we go through the application until we reach the end, counting how many explicit arguments -- it has and noting whether they are explicit or implicit while descExp.isApp do if (← Lean.Meta.inferType descExp.appFn!).bindingInfo!.isExplicit then explicitList := true::explicitList count := count + 1 else explicitList := false::explicitList descExp := descExp.appFn! -- we get the correct `enter` command by subtracting the number of `true`s in our list let mut mutablePath := path let mut length := count explicitList := List.reverse explicitList while !mutablePath.isEmpty && mutablePath.head! == 0 do if explicitList.head! == true then count := count - 1 explicitList := explicitList.tail! mutablePath := mutablePath.tail! let mut nextExp := expr while length > count do nextExp := nextExp.appFn! length := length - 1 nextExp := nextExp.appArg! let pathRest := if mutablePath.isEmpty then [] else mutablePath.tail! return { expr := nextExp, val? := toString count , listRest := pathRest } | Expr.lam n _ b _ => do let name := match n with | Name.str _ s => s | _ => panic! "no name found" return { expr := b, val? := name, listRest := path.tail! } | Expr.forallE n _ b _ => do let name := match n with | Name.str _ s => s | _ => panic! "no name found" return { expr := b, val? := name, listRest := path.tail! } | Expr.mdata _ b => do match b with | Expr.mdata _ _ => return { expr := b, val? := none, listRest := path } | _ => return { expr := b.appFn!.appArg!, val? := none, listRest := path.tail!.tail! } | _ => do return { expr := ← (Lean.Core.viewSubexpr path.head! expr) val? := toString (path.head! + 1) listRest := path.tail! } open Lean Syntax in /-- Return the link text and inserted text above and below of the conv widget. -/ @[nolint unusedArguments] def insertEnter (locations : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) (params : SelectInsertParams): MetaM (String × String × Option (String.Pos × String.Pos)) := do let some pos := locations[0]? | throwError "You must select something." let (fvar, subexprPos) ← match pos with | ⟨_, .target subexprPos⟩ => pure (none, subexprPos) | ⟨_, .hypType fvar subexprPos⟩ => pure (some fvar, subexprPos) | ⟨_, .hypValue fvar subexprPos⟩ => pure (some fvar, subexprPos) | _ => throwError "You must select something in the goal or in a local value." let mut list := (SubExpr.Pos.toArray subexprPos).toList let mut expr := goalType let mut retList := [] -- generate list of commands for `enter` while !list.isEmpty do let res ← solveLevel expr list expr := res.expr retList := match res.val? with | none => retList | some val => val::retList list := res.listRest -- build `enter [...]` string retList := List.reverse retList -- prepare `enter` indentation let spc := String.replicate (SelectInsertParamsClass.replaceRange params).start.character ' ' let loc ← match fvar with | some fvarId => pure s!"at {← fvarId.getUserName} " | none => pure "" let mut enterval := s!"conv {loc}=>\n{spc} enter {retList}" if enterval.contains '0' then enterval := "Error: Not a valid conv target" if retList.isEmpty then enterval := "" return ("Generate conv", enterval, none) /-- Rpc function for the conv widget. -/ @[server_rpc_method] def ConvSelectionPanel.rpc := mkSelectionPanelRPC insertEnter "Use shift-click to select one sub-expression in the goal that you want to zoom on." "Conv 🔍" (onlyGoal := false) (onlyOne := true) /-- The conv widget. -/ @[widget_module] def ConvSelectionPanel : Component SelectInsertParams := mk_rpc_widget% ConvSelectionPanel.rpc open scoped Json in /-- Display a widget panel allowing to generate a `conv` call zooming to the subexpression selected in the goal. -/ elab stx:"conv?" : tactic => do let some replaceRange := (← getFileMap).rangeOfStx? stx | return Widget.savePanelWidgetInfo ConvSelectionPanel.javascriptHash (pure <| json% { replaceRange: $(replaceRange) }) stx
Tactic\Widget\GCongr.lean
/- Copyright (c) 2023 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.Tactic.Widget.SelectPanelUtils import Mathlib.Tactic.GCongr /-! # GCongr widget This file defines a `gcongr?` tactic that displays a widget panel allowing to generate a `gcongr` call with holes specified by selecting subexpressions in the goal. -/ open Lean Meta Server ProofWidgets /-- Return the link text and inserted text above and below of the gcongr widget. -/ @[nolint unusedArguments] def makeGCongrString (pos : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) (_ : SelectInsertParams) : MetaM (String × String × Option (String.Pos × String.Pos)) := do let subexprPos := getGoalLocations pos unless goalType.isAppOf `LE.le || goalType.isAppOf `LT.lt || goalType.isAppOf `Int.ModEq do panic! "The goal must be a ≤ or < or ≡." let mut goalTypeWithMetaVars := goalType for pos in subexprPos do goalTypeWithMetaVars ← insertMetaVar goalTypeWithMetaVars pos let side := if goalType.isAppOf `Int.ModEq then if subexprPos[0]!.toArray[0]! = 0 then 1 else 2 else if subexprPos[0]!.toArray[0]! = 0 then 2 else 3 let sideExpr := goalTypeWithMetaVars.getAppArgs[side]! let res := "gcongr " ++ (toString (← Meta.ppExpr sideExpr)).renameMetaVar return (res, res, none) /-- Rpc function for the gcongr widget. -/ @[server_rpc_method] def GCongrSelectionPanel.rpc := mkSelectionPanelRPC makeGCongrString "Use shift-click to select sub-expressions in the goal that should become holes in gcongr." "GCongr 🔍" /-- The gcongr widget. -/ @[widget_module] def GCongrSelectionPanel : Component SelectInsertParams := mk_rpc_widget% GCongrSelectionPanel.rpc open scoped Json in /-- Display a widget panel allowing to generate a `gcongr` call with holes specified by selecting subexpressions in the goal. -/ elab stx:"gcongr?" : tactic => do let some replaceRange := (← getFileMap).rangeOfStx? stx | return Widget.savePanelWidgetInfo GCongrSelectionPanel.javascriptHash (pure <| json% { replaceRange: $(replaceRange) }) stx
Tactic\Widget\InteractiveUnfold.lean
/- Copyright (c) 2023 Jovan Gerbscheid. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jovan Gerbscheid -/ import Batteries.Lean.Position import Mathlib.Tactic.Widget.SelectPanelUtils import Mathlib.Lean.GoalsLocation import Mathlib.Lean.Meta.KAbstractPositions /-! # Interactive unfolding This file defines the interactive tactic `unfold?`. It allows you to shift-click on an expression in the goal, and then it suggests rewrites to replace the expression with an unfolded version. It can be used on its own, but it can also be used as part of the library rewrite tactic `rw??`, where these unfoldings are a subset of the suggestions. For example, if the goal contains `1+1`, then it will suggest rewriting this into one of - `Nat.add 1 1` - `2` Clicking on a suggestion pastes a rewrite into the editor, which will be of the form - `rw [show 1+1 = Nat.add 1 1 from rfl]` - `rw [show 1+1 = 2 from rfl]` It also takes into account the position of the selected expression if it appears in multiple places, and whether the rewrite is in the goal or a local hypothesis. The rewrite string is created using `mkRewrite`. ## Reduction rules The basic idea is to repeatedly apply `unfoldDefinition?` followed by `whnfCore`, which gives the list of all suggested unfoldings. Each suggested unfolding is in `whnfCore` normal form. Additionally, eta-reduction is tried, and basic natural number reduction is tried. ## Filtering `HAdd.hAdd` in `1+1` actually first unfolds into `Add.add`, but this is not very useful, because this is just unfolding a notational type class. Therefore, unfoldings of default instances are not presented in the list of suggested rewrites. This is implemented with `unfoldProjDefaultInst?`. Additionally, we don't want to unfold into expressions involving `match` terms or other constants marked as `Name.isInternalDetail`. So all such results are filtered out. This is implemented with `isUserFriendly`. -/ open Lean Meta Server Widget ProofWidgets Jsx namespace Mathlib.Tactic.InteractiveUnfold /-- Unfold a class projection if the instance is tagged with `@[default_instance]`. This is used in the `unfold?` tactic in order to not show these unfolds to the user. Similar to `Lean.Meta.unfoldProjInst?`. -/ def unfoldProjDefaultInst? (e : Expr) : MetaM (Option Expr) := do let .const declName _ := e.getAppFn | return none let some { fromClass := true, ctorName, .. } ← getProjectionFnInfo? declName | return none -- get the list of default instances of the class let some (ConstantInfo.ctorInfo ci) := (← getEnv).find? ctorName | return none let defaults ← getDefaultInstances ci.induct if defaults.isEmpty then return none let some e ← withDefault <| unfoldDefinition? e | return none let .proj _ i c := e.getAppFn | return none -- check that the structure `c` comes from one of the default instances let .const inst _ := c.getAppFn | return none unless defaults.any (·.1 == inst) do return none let some r ← withReducibleAndInstances <| project? c i | return none return mkAppN r e.getAppArgs |>.headBeta /-- Return the consecutive unfoldings of `e`. -/ partial def unfolds (e : Expr) : MetaM (Array Expr) := do let e' ← whnfCore e go e' (if e == e' then #[] else #[e']) where /-- Append the unfoldings of `e` to `acc`. Assume `e` is in `whnfCore` form. -/ go (e : Expr) (acc : Array Expr) : MetaM (Array Expr) := tryCatchRuntimeEx (withIncRecDepth do if let some e := e.etaExpandedStrict? then let e ← whnfCore e return ← go e (acc.push e) if let some e ← reduceNat? e then return acc.push e if let some e ← reduceNative? e then return acc.push e if let some e ← unfoldProjDefaultInst? e then -- when unfolding a default instance, don't add it to the array of unfolds. let e ← whnfCore e return ← go e acc if let some e ← unfoldDefinition? e then -- Note: whnfCore can give a recursion depth error let e ← whnfCore e return ← go e (acc.push e) return acc) fun _ => return acc /-- Determine whether `e` contains no internal names. -/ def isUserFriendly (e : Expr) : Bool := !e.foldConsts (init := false) (fun name => (· || name.isInternalDetail)) /-- Return the consecutive unfoldings of `e` that are user friendly. -/ def filteredUnfolds (e : Expr) : MetaM (Array Expr) := return (← unfolds e).filter isUserFriendly end InteractiveUnfold /-- Return the rewrite tactic string `rw (config := ..) [← ..] at ..` -/ def mkRewrite (occ : Option Nat) (symm : Bool) (rewrite : String) (loc : Option Name) : String := let cfg := match occ with | some n => s! " (config := \{ occs := .pos [{n}]})" | none => "" let loc := match loc with | some n => s! " at {n}" | none => "" let symm := if symm then "← " else "" s! "rw{cfg} [{symm}{rewrite}]{loc}" /-- Return a string of the expression suitable for pasting into the editor. We ignore any options set by the user. We set `pp.universes` to false because new universe level metavariables are not understood by the elaborator. We set `pp.unicode.fun` to true as per Mathlib convention. -/ def pasteString (e : Expr) : MetaM String := withOptions (fun _ => Options.empty |>.setBool `pp.universes false |>.setBool `pp.unicode.fun true) do return Format.pretty (← Meta.ppExpr e) (width := 90) (indent := 2) namespace InteractiveUnfold /-- Return the tactic string that does the unfolding. -/ def tacticString (e unfold : Expr) (occ : Option Nat) (loc : Option Name) : MetaM String := do let rfl := s! "show {← pasteString (← mkEq e unfold)} from rfl" return mkRewrite occ false rfl loc /-- Render the unfolds of `e` as given by `filteredUnfolds`, with buttons at each suggestion for pasting the rewrite tactic. Return `none` when there are no unfolds. -/ def renderUnfolds (e : Expr) (occ : Option Nat) (loc : Option Name) (range : Lsp.Range) (doc : FileWorker.EditableDocument) : MetaM (Option Html) := do let results ← filteredUnfolds e if results.isEmpty then return none let core ← results.mapM fun unfold => do let tactic ← tacticString e unfold occ loc return <li> { .element "p" #[] <| #[<span className="font-code" style={json% { "white-space" : "pre-wrap" }}> { Html.ofComponent MakeEditLink (.ofReplaceRange doc.meta range tactic) #[.text $ Format.pretty $ (← Meta.ppExpr unfold)] } </span>] } </li> return <details «open»={true}> <summary className="mv2 pointer"> {.text "Definitional rewrites:"} </summary> {.element "ul" #[("style", json% { "padding-left" : "30px"})] core} </details> @[server_rpc_method_cancellable] private def rpc (props : SelectInsertParams) : RequestM (RequestTask Html) := RequestM.asTask do let doc ← RequestM.readDoc let some loc := props.selectedLocations.back? | return .text "unfold?: Please shift-click an expression." if loc.loc matches .hypValue .. then return .text "unfold? doesn't work on the value of a let-bound free variable." let some goal := props.goals[0]? | return .text "There is no goal to solve!" if loc.mvarId != goal.mvarId then return .text "The selected expression should be in the main goal." goal.ctx.val.runMetaM {} do let md ← goal.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do let rootExpr ← loc.rootExpr let some (subExpr, occ) ← viewKAbstractSubExpr rootExpr loc.pos | return .text "expressions with bound variables are not supported" unless ← kabstractIsTypeCorrect rootExpr subExpr loc.pos do return .text <| "The selected expression cannot be rewritten, because the motive is " ++ "not type correct. This usually occurs when trying to rewrite a term that appears " ++ "as a dependent argument." let html ← renderUnfolds subExpr occ (← loc.location) props.replaceRange doc return html.getD <span> No unfolds found for {<InteractiveCode fmt={← ppExprTagged subExpr}/>} </span> /-- The component called by the `unfold?` tactic -/ @[widget_module] def UnfoldComponent : Component SelectInsertParams := mk_rpc_widget% InteractiveUnfold.rpc /-- Replace the selected expression with a definitional unfolding. - After each unfolding, we apply `whnfCore` to simplify the expression. - Explicit natural number expressions are evaluated. - Unfolds of class projections of instances marked with `@[default_instance]` are not shown. This is relevant for notational type classes like `+`: we don't want to suggest `Add.add a b` as an unfolding of `a + b`. Similarly for `OfNat n : Nat` which unfolds into `n : Nat`. To use `unfold?`, shift-click an expression in the tactic state. This gives a list of rewrite suggestions for the selected expression. Click on a suggestion to replace `unfold?` by a tactic that performs this rewrite. -/ elab stx:"unfold?" : tactic => do let some range := (← getFileMap).rangeOfStx? stx | return Widget.savePanelWidgetInfo (hash UnfoldComponent.javascript) (pure $ json% { replaceRange : $range }) stx /-- `#unfold? e` gives all unfolds of `e`. In tactic mode, use `unfold?` instead. -/ syntax (name := unfoldCommand) "#unfold?" term : command open Elab /-- Elaborate a `#unfold?` command. -/ @[command_elab unfoldCommand] def elabUnfoldCommand : Command.CommandElab := fun stx => withoutModifyingEnv <| Command.runTermElabM fun _ => Term.withDeclName `_unfold do let e ← Term.elabTerm stx[1] none Term.synthesizeSyntheticMVarsNoPostponing let e ← Term.levelMVarToParam (← instantiateMVars e) let e ← instantiateMVars e let unfolds ← filteredUnfolds e if unfolds.isEmpty then logInfo m! "No unfolds found for {e}" else let unfolds := unfolds.toList.map (m! "· {·}") logInfo (m! "Unfolds for {e}:\n" ++ .joinSep unfolds "\n")
Tactic\Widget\SelectInsertParamsClass.lean
/- Copyright (c) 2023 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Lean.Widget.InteractiveGoal import Lean.Elab.Deriving.Basic /-! # SelectInsertParamsClass Defines the basic class of parameters for a select and insert widget. This needs to be in a separate file in order to initialize the deriving handler. -/ open Lean Meta Server /-- Structures providing parameters for a Select and insert widget. -/ class SelectInsertParamsClass (α : Type) where /-- Cursor position in the file at which the widget is being displayed. -/ pos : α → Lsp.Position /-- The current tactic-mode goals. -/ goals : α → Array Widget.InteractiveGoal /-- Locations currently selected in the goal state. -/ selectedLocations : α → Array SubExpr.GoalsLocation /-- The range in the source document where the command will be inserted. -/ replaceRange : α → Lsp.Range namespace Lean.Elab open Command Meta Parser Term private def mkSelectInsertParamsInstance (declName : Name) : TermElabM Syntax.Command := `(command|instance : SelectInsertParamsClass (@$(mkCIdent declName)) := ⟨fun prop => prop.pos, fun prop => prop.goals, fun prop => prop.selectedLocations, fun prop => prop.replaceRange⟩) /-- Handler deriving a `SelectInsertParamsClass` instance. -/ def mkSelectInsertParamsInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if (← declNames.allM isInductive) then for declName in declNames do elabCommand (← liftTermElabM do mkSelectInsertParamsInstance declName) return true else return false initialize registerDerivingHandler `SelectInsertParamsClass mkSelectInsertParamsInstanceHandler end Lean.Elab
Tactic\Widget\SelectPanelUtils.lean
/- Copyright (c) 2023 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Lean.Meta.ExprLens import ProofWidgets.Component.MakeEditLink import ProofWidgets.Component.OfRpcMethod -- needed in all files using this one. import Mathlib.Tactic.Widget.SelectInsertParamsClass /-! # Selection panel utilities The main declaration is `mkSelectionPanelRPC` which helps creating rpc methods for widgets generating tactic calls based on selected sub-expressions in the main goal. There are also some minor helper functions. -/ open Lean Meta Server open Lean.SubExpr in /-- Given a `Array GoalsLocation` return the array of `SubExpr.Pos` for all locations in the targets of the relevant goals. -/ def getGoalLocations (locations : Array GoalsLocation) : Array SubExpr.Pos := Id.run do let mut res := #[] for location in locations do if let .target pos := location.loc then res := res.push pos return res /-- Replace the sub-expression at the given position by a fresh meta-variable. -/ def insertMetaVar (e : Expr) (pos : SubExpr.Pos) : MetaM Expr := replaceSubexpr (fun _ ↦ do mkFreshExprMVar none .synthetic) pos e /-- Replace all meta-variable names by "?_". -/ def String.renameMetaVar (s : String) : String := match s.splitOn "?m." with | [] => "" | [s] => s | head::tail => head ++ "?_" ++ "?_".intercalate (tail.map fun s ↦ s.dropWhile Char.isDigit) open ProofWidgets /-- Structures providing parameters for a Select and insert widget. -/ structure SelectInsertParams where /-- Cursor position in the file at which the widget is being displayed. -/ pos : Lsp.Position /-- The current tactic-mode goals. -/ goals : Array Widget.InteractiveGoal /-- Locations currently selected in the goal state. -/ selectedLocations : Array SubExpr.GoalsLocation /-- The range in the source document where the command will be inserted. -/ replaceRange : Lsp.Range deriving SelectInsertParamsClass, RpcEncodable open scoped Jsx in open SelectInsertParamsClass Lean.SubExpr in /-- Helper function to create a widget allowing to select parts of the main goal and then display a link that will insert some tactic call. The main argument is `mkCmdStr` which is a function creating the link text and the tactic call text. The `helpMsg` argument is displayed when nothing is selected and `title` is used as a panel title. The `onlyGoal` argument says whether the selected has to be in the goal. Otherwise it can be in the local context. The `onlyOne` argument says whether one should select only one sub-expression. In every cases, all selected subexpressions should be in the main goal or its local context. The last arguments `params` should not be provided so that the output has type `Params → RequestM (RequestTask Html)` and can be fed to the `mk_rpc_widget%` elaborator. Note that the `pos` and `goalType` arguments to `mkCmdStr` could be extracted for the `Params` argument but that extraction would happen in every example, hence it is factored out here. We also make sure `mkCmdStr` is executed in the right context. -/ def mkSelectionPanelRPC {Params : Type} [SelectInsertParamsClass Params] (mkCmdStr : (pos : Array GoalsLocation) → (goalType : Expr) → Params → MetaM (String × String × Option (String.Pos × String.Pos))) (helpMsg : String) (title : String) (onlyGoal := true) (onlyOne := false) : (params : Params) → RequestM (RequestTask Html) := fun params ↦ RequestM.asTask do let doc ← RequestM.readDoc if h : 0 < (goals params).size then let mainGoal := (goals params)[0] let mainGoalName := mainGoal.mvarId.name let all := if onlyOne then "The selected sub-expression" else "All selected sub-expressions" let be_where := if onlyGoal then "in the main goal." else "in the main goal or its context." let errorMsg := s!"{all} should be {be_where}" let inner : Html ← (do if onlyOne && (selectedLocations params).size > 1 then return <span>{.text "You should select only one sub-expression"}</span> for selectedLocation in selectedLocations params do if selectedLocation.mvarId.name != mainGoalName then return <span>{.text errorMsg}</span> else if onlyGoal then if !(selectedLocation.loc matches (.target _)) then return <span>{.text errorMsg}</span> if (selectedLocations params).isEmpty then return <span>{.text helpMsg}</span> mainGoal.ctx.val.runMetaM {} do let md ← mainGoal.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do let (linkText, newCode, range?) ← mkCmdStr (selectedLocations params) md.type.consumeMData params return .ofComponent MakeEditLink (.ofReplaceRange doc.meta (replaceRange params) newCode range?) #[ .text linkText ]) return <details «open»={true}> <summary className="mv2 pointer">{.text title}</summary> <div className="ml1">{inner}</div> </details> else return <span>{.text "There is no goal to solve!"}</span> -- This shouldn't happen.
Tactic\Widget\StringDiagram.lean
/- Copyright (c) 2024 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno -/ import ProofWidgets.Component.PenroseDiagram import ProofWidgets.Component.Panel.Basic import ProofWidgets.Presentation.Expr import Mathlib.Tactic.CategoryTheory.Monoidal /-! # String Diagram Widget This file provides meta infrastructure for displaying string diagrams for morphisms in monoidal categories in the infoview. To enable the string diagram widget, you need to import this file and inserting `with_panel_widgets [Mathlib.Tactic.Widget.StringDiagram]` at the beginning of the proof. Alternatively, you can also write ```lean open Mathlib.Tactic.Widget show_panel_widgets [local StringDiagram] ``` to enable the string diagram widget in the current section. String diagrams are graphical representations of morphisms in monoidal categories, which are useful for rewriting computations. More precisely, objects in a monoidal category is represented by strings, and morphisms between two objects is represented by nodes connecting two strings associated with the objects. The tensor product `X ⊗ Y` corresponds to putting strings associated with `X` and `Y` horizontally (from left to right), and the composition of morphisms `f : X ⟶ Y` and `g : Y ⟶ Z` corresponds to connecting two nodes associated with `f` and `g` vertically (from top to bottom) by strings associated with `Y`. Currently, the string diagram widget provided in this file deals with equalities of morphisms in monoidal categories. It displays string diagrams corresponding to the morphisms for the left-hand and right-hand sides of the equality. Some examples can be found in `test/StringDiagram.lean`. When drawing string diagrams, it is common to ignore associators and unitors. We follow this convention. To do this, we need to extract non-structural morphisms that are not associators and unitors from lean expressions. This operation is performed using the `Tactic.Monoidal.eval` function. A monoidal category can be viewed as a bicategory with a single object. The program in this file can also be used to display the string diagram for general bicategories (see the wip PR #12107). With this in mind we will sometimes refer to objects and morphisms in monoidal categories as 1-morphisms and 2-morphisms respectively, borrowing the terminology of bicategories. Note that the relation between monoidal categories and bicategories is formalized in `Mathlib.CategoryTheory.Bicategory.SingleObj`, although the string diagram widget does not use it directly. -/ namespace Mathlib.Tactic open Lean Meta Elab open CategoryTheory open Mathlib.Tactic.Coherence open Mathlib.Tactic.Monoidal namespace Widget.StringDiagram /-! ## Objects in string diagrams -/ /-- Nodes for 2-morphisms in a string diagram. -/ structure AtomNode : Type where /-- The vertical position of the node in the string diagram. -/ vPos : ℕ /-- The horizontal position of the node in the string diagram, counting strings in domains. -/ hPosSrc : ℕ /-- The horizontal position of the node in the string diagram, counting strings in codomains. -/ hPosTar : ℕ /-- The underlying expression of the node. -/ atom : Atom /-- Nodes for identity 2-morphisms in a string diagram. -/ structure IdNode : Type where /-- The vertical position of the node in the string diagram. -/ vPos : ℕ /-- The horizontal position of the node in the string diagram, counting strings in domains. -/ hPosSrc : ℕ /-- The horizontal position of the node in the string diagram, counting strings in codomains. -/ hPosTar : ℕ /-- The underlying expression of the node. -/ id : Atom₁ /-- Nodes in a string diagram. -/ inductive Node : Type | atom : AtomNode → Node | id : IdNode → Node /-- The underlying expression of a node. -/ def Node.e : Node → Expr | Node.atom n => n.atom.e | Node.id n => n.id.e /-- The domain of the 2-morphism associated with a node as a list (the first component is the node itself). -/ def Node.srcList : Node → MetaM (List (Node × Atom₁)) | Node.atom n => return (← n.atom.src).toList.map (fun f ↦ (.atom n, f)) | Node.id n => return [(.id n, n.id)] /-- The codomain of the 2-morphism associated with a node as a list (the first component is the node itself). -/ def Node.tarList : Node → MetaM (List (Node × Atom₁)) | Node.atom n => return (← n.atom.tgt).toList.map (fun f ↦ (.atom n, f)) | Node.id n => return [(.id n, n.id)] /-- The vertical position of a node in a string diagram. -/ def Node.vPos : Node → ℕ | Node.atom n => n.vPos | Node.id n => n.vPos /-- The horizontal position of a node in a string diagram, counting strings in domains. -/ def Node.hPosSrc : Node → ℕ | Node.atom n => n.hPosSrc | Node.id n => n.hPosSrc /-- The horizontal position of a node in a string diagram, counting strings in codomains. -/ def Node.hPosTar : Node → ℕ | Node.atom n => n.hPosTar | Node.id n => n.hPosTar /-- The list of nodes at the top of a string diagram. -/ def topNodes (η : WhiskerLeftExpr) : MetaM (List Node) := do return (← η.src).toList.enum.map (fun (i, f) => .id ⟨0, i, i, f⟩) /-- Strings in a string diagram. -/ structure Strand : Type where /-- The horizontal position of the strand in the string diagram. -/ hPos : ℕ /-- The start point of the strand in the string diagram. -/ startPoint : Node /-- The end point of the strand in the string diagram. -/ endPoint : Node /-- The underlying expression of the strand. -/ atom₁ : Atom₁ /-- The vertical position of a strand in a string diagram. -/ def Strand.vPos (s : Strand) : ℕ := s.startPoint.vPos end Widget.StringDiagram namespace Monoidal open Widget.StringDiagram /-- The list of nodes associated with a 2-morphism. The position is counted from the specified natural numbers. -/ def WhiskerRightExpr.nodes (v h₁ h₂ : ℕ) : WhiskerRightExpr → MetaM (List Node) | WhiskerRightExpr.of η => do return [.atom ⟨v, h₁, h₂, η⟩] | WhiskerRightExpr.whisker η f => do let ηs ← η.nodes v h₁ h₂ let k₁ := (← ηs.mapM (fun n ↦ n.srcList)).join.length let k₂ := (← ηs.mapM (fun n ↦ n.tarList)).join.length let s : Node := .id ⟨v, h₁ + k₁, h₂ + k₂, f⟩ return ηs ++ [s] /-- The list of nodes associated with a 2-morphism. The position is counted from the specified natural numbers. -/ def WhiskerLeftExpr.nodes (v h₁ h₂ : ℕ) : WhiskerLeftExpr → MetaM (List Node) | WhiskerLeftExpr.of η => η.nodes v h₁ h₂ | WhiskerLeftExpr.whisker f η => do let s : Node := .id ⟨v, h₁, h₂, f⟩ let ss ← η.nodes v (h₁ + 1) (h₂ + 1) return s :: ss /-- The list of nodes at the top of a string diagram. The position is counted from the specified natural number. -/ def NormalExpr.nodesAux (v : ℕ) : NormalExpr → MetaM (List (List Node)) | NormalExpr.nil α => return [(α.src).toList.enum.map (fun (i, f) => .id ⟨v, i, i, f⟩)] | NormalExpr.cons _ η ηs => do let s₁ ← η.nodes v 0 0 let s₂ ← ηs.nodesAux (v + 1) return s₁ :: s₂ /-- The list of nodes associated with a 2-morphism. -/ def NormalExpr.nodes (e : NormalExpr) : MetaM (List (List Node)) := do match e with | NormalExpr.nil _ => return [] | NormalExpr.cons _ η _ => return (← topNodes η) :: (← e.nodesAux 1) /-- `pairs [a, b, c, d]` is `[(a, b), (b, c), (c, d)]`. -/ def pairs {α : Type} : List α → List (α × α) | [] => [] | [_] => [] | (x :: y :: ys) => (x, y) :: pairs (y :: ys) /-- The list of strands associated with a 2-morphism. -/ def NormalExpr.strands (e : NormalExpr) : MetaM (List (List Strand)) := do let l ← e.nodes (pairs l).mapM fun (x, y) ↦ do let xs := (← x.mapM (fun n ↦ n.tarList)).join let ys := (← y.mapM (fun n ↦ n.srcList)).join if xs.length ≠ ys.length then throwError "The number of the start and end points of a string does not match." (xs.zip ys).enum.mapM fun (k, (n₁, f₁), (n₂, _)) => do return ⟨n₁.hPosTar + k, n₁, n₂, f₁⟩ end Monoidal namespace Widget.StringDiagram /-- A type for Penrose variables. -/ structure PenroseVar : Type where /-- The identifier of the variable. -/ ident : String /-- The indices of the variable. -/ indices : List ℕ /-- The underlying expression of the variable. -/ e : Expr instance : ToString PenroseVar := ⟨fun v => v.ident ++ v.indices.foldl (fun s x => s ++ s!"_{x}") ""⟩ /-- The penrose variable assciated with a node. -/ def Node.toPenroseVar (n : Node) : PenroseVar := ⟨"E", [n.vPos, n.hPosSrc, n.hPosTar], n.e⟩ /-- The penrose variable assciated with a strand. -/ def Strand.toPenroseVar (s : Strand) : PenroseVar := ⟨"f", [s.vPos, s.hPos], s.atom₁.e⟩ /-! ## Widget for general string diagrams -/ open ProofWidgets Penrose DiagramBuilderM Lean.Server open scoped Jsx in /-- Add the variable `v` with the type `tp` to the substance program. -/ def addPenroseVar (tp : String) (v : PenroseVar) : DiagramBuilderM Unit := do let h := <InteractiveCode fmt={← Widget.ppExprTagged v.e} /> addEmbed (toString v) tp h /-- Add constructor `tp v := nm (vs)` to the substance program. -/ def addConstructor (tp : String) (v : PenroseVar) (nm : String) (vs : List PenroseVar) : DiagramBuilderM Unit := do let vs' := ", ".intercalate (vs.map (fun v => toString v)) addInstruction s!"{tp} {v} := {nm} ({vs'})" open scoped Jsx in /-- Construct a string diagram from a Penrose `sub`stance program and expressions `embeds` to display as labels in the diagram. -/ def mkStringDiagram (e : NormalExpr) : DiagramBuilderM PUnit := do let nodes ← e.nodes let strands ← e.strands /- Add 2-morphisms. -/ for x in nodes.join do match x with | .atom _ => do addPenroseVar "Atom" x.toPenroseVar | .id _ => do addPenroseVar "Id" x.toPenroseVar /- Add constraints. -/ for l in nodes do for (x₁, x₂) in pairs l do addInstruction s!"Left({x₁.toPenroseVar}, {x₂.toPenroseVar})" /- Add constraints. -/ for (l₁, l₂) in pairs nodes do if let .some x₁ := l₁.head? then if let .some x₂ := l₂.head? then addInstruction s!"Above({x₁.toPenroseVar}, {x₂.toPenroseVar})" /- Add 1-morphisms as strings. -/ for l in strands do for s in l do addConstructor "Mor1" s.toPenroseVar "MakeString" [s.startPoint.toPenroseVar, s.endPoint.toPenroseVar] /-- Penrose dsl file for string diagrams. -/ def dsl := include_str ".."/".."/".."/"widget"/"src"/"penrose"/"monoidal.dsl" /-- Penrose sty file for string diagrams. -/ def sty := include_str ".."/".."/".."/"widget"/"src"/"penrose"/"monoidal.sty" open scoped Jsx in /-- Construct a string diagram from the expression of a 2-morphism. -/ def fromExpr (e : Expr) : MonoidalM Html := do let e' := (← eval e).expr DiagramBuilderM.run do mkStringDiagram e' match ← DiagramBuilderM.buildDiagram dsl sty with | some html => return html | none => return <span>No non-structural morphisms found.</span> /-- Given a 2-morphism, return a string diagram. Otherwise `none`. -/ def stringM? (e : Expr) : MetaM (Option Html) := do let e ← instantiateMVars e let some ctx ← mkContext? e | return none return some <| ← MonoidalM.run ctx <| fromExpr e open scoped Jsx in /-- Help function for displaying two string diagrams in an equality. -/ def mkEqHtml (lhs rhs : Html) : Html := <div className="flex"> <div className="w-50"> <details «open»={true}> <summary className="mv2 pointer">String diagram for LHS</summary> {lhs} </details> </div> <div className="w-50"> <details «open»={true}> <summary className="mv2 pointer">String diagram for RHS</summary> {rhs} </details> </div> </div> /-- Given an equality between 2-morphisms, return a string diagram of the LHS and RHS. Otherwise `none`. -/ def stringEqM? (e : Expr) : MetaM (Option Html) := do let e ← instantiateMVars e let some (_, lhs, rhs) := e.eq? | return none let some lhs ← stringM? lhs | return none let some rhs ← stringM? rhs | return none return some <| mkEqHtml lhs rhs /-- Given an 2-morphism or equality between 2-morphisms, return a string diagram. Otherwise `none`. -/ def stringMorOrEqM? (e : Expr) : MetaM (Option Html) := do if let some html ← stringM? e then return some html else if let some html ← stringEqM? e then return some html else return none /-- The `Expr` presenter for displaying string diagrams. -/ @[expr_presenter] def stringPresenter : ExprPresenter where userName := "String diagram" layoutKind := .block present type := do if let some html ← stringMorOrEqM? type then return html throwError "Couldn't find a 2-morphism to display a string diagram." open scoped Jsx in /-- The RPC method for displaying string diagrams. -/ @[server_rpc_method] def rpc (props : PanelWidgetProps) : RequestM (RequestTask Html) := RequestM.asTask do let html : Option Html ← (do if props.goals.isEmpty then return none let some g := props.goals[0]? | unreachable! g.ctx.val.runMetaM {} do g.mvarId.withContext do let type ← g.mvarId.getType stringEqM? type) match html with | none => return <span>No String Diagram.</span> | some inner => return inner end StringDiagram open ProofWidgets /-- Display the string diagrams if the goal is an equality of morphisms in a monoidal category. -/ @[widget_module] def StringDiagram : Component PanelWidgetProps := mk_rpc_widget% StringDiagram.rpc end Mathlib.Tactic.Widget
Testing\SlimCheck\Functions.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Data.List.Sigma import Mathlib.Data.Int.Range import Mathlib.Data.Finsupp.Defs import Mathlib.Data.Finsupp.ToDFinsupp import Mathlib.Testing.SlimCheck.Sampleable import Mathlib.Testing.SlimCheck.Testable /-! ## `slim_check`: generators for functions This file defines `Sampleable` instances for `α → β` functions and `ℤ → ℤ` injective functions. Functions are generated by creating a list of pairs and one more value using the list as a lookup table and resorting to the additional value when a value is not found in the table. Injective functions are generated by creating a list of numbers and a permutation of that list. The permutation insures that every input is mapped to a unique output. When an input is not found in the list the input itself is used as an output. Injective functions `f : α → α` could be generated easily instead of `ℤ → ℤ` by generating a `List α`, removing duplicates and creating a permutation. One has to be careful when generating the domain to make it vast enough that, when generating arguments to apply `f` to, they argument should be likely to lie in the domain of `f`. This is the reason that injective functions `f : ℤ → ℤ` are generated by fixing the domain to the range `[-2*size .. 2*size]`, with `size` the size parameter of the `gen` monad. Much of the machinery provided in this file is applicable to generate injective functions of type `α → α` and new instances should be easy to define. Other classes of functions such as monotone functions can generated using similar techniques. For monotone functions, generating two lists, sorting them and matching them should suffice, with appropriate default values. Some care must be taken for shrinking such functions to make sure their defining property is invariant through shrinking. Injective functions are an example of how complicated it can get. -/ universe u v w variable {α : Type u} {β : Type v} {γ : Sort w} namespace SlimCheck /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `withDefault f y` encodes `x ↦ f x` when `x ∈ f` and `x ↦ y` otherwise. We use `Σ` to encode mappings instead of `×` because we rely on the association list API defined in `Mathlib/Data/List/Sigma.lean`. -/ inductive TotalFunction (α : Type u) (β : Type v) : Type max u v | withDefault : List (Σ _ : α, β) → β → TotalFunction α β instance TotalFunction.inhabited [Inhabited β] : Inhabited (TotalFunction α β) := ⟨TotalFunction.withDefault ∅ default⟩ namespace TotalFunction -- Porting note: new /-- Compose a total function with a regular function on the left -/ def comp {γ : Type w} (f : β → γ) : TotalFunction α β → TotalFunction α γ | TotalFunction.withDefault m y => TotalFunction.withDefault (m.map <| Sigma.map id fun _ => f) (f y) /-- Apply a total function to an argument. -/ def apply [DecidableEq α] : TotalFunction α β → α → β | TotalFunction.withDefault m y, x => (m.dlookup x).getD y /-- Implementation of `Repr (TotalFunction α β)`. Creates a string for a given `Finmap` and output, `x₀ ↦ y₀, .. xₙ ↦ yₙ` for each of the entries. The brackets are provided by the calling function. -/ def reprAux [Repr α] [Repr β] (m : List (Σ _ : α, β)) : String := String.join <| -- Porting note: No `List.qsort`, so convert back and forth to an `Array`. Array.toList <| Array.qsort (lt := fun x y => x < y) (m.map fun x => s!"{(repr <| Sigma.fst x)} ↦ {repr <| Sigma.snd x}, ").toArray /-- Produce a string for a given `TotalFunction`. The output is of the form `[x₀ ↦ f x₀, .. xₙ ↦ f xₙ, _ ↦ y]`. -/ protected def repr [Repr α] [Repr β] : TotalFunction α β → String | TotalFunction.withDefault m y => s!"[{(reprAux m)}_ ↦ {repr y}]" instance (α : Type u) (β : Type v) [Repr α] [Repr β] : Repr (TotalFunction α β) where reprPrec f _ := TotalFunction.repr f /-- Create a `Finmap` from a list of pairs. -/ def List.toFinmap' (xs : List (α × β)) : List (Σ _ : α, β) := xs.map Prod.toSigma section universe ua ub variable [SampleableExt.{_,u} α] [SampleableExt.{_,ub} β] -- Porting note: removed, there is no `SizeOf.sizeOf` in the new `Sampleable` -- /-- Redefine `SizeOf.sizeOf` to follow the structure of `sampleable` instances. -/ -- def Total.sizeof : TotalFunction α β → ℕ -- | ⟨m, x⟩ => 1 + @SizeOf.sizeOf _ Sampleable.wf m + SizeOf.sizeOf x -- instance (priority := 2000) : SizeOf (TotalFunction α β) := -- ⟨Total.sizeof⟩ variable [DecidableEq α] /-- Shrink a total function by shrinking the lists that represent it. -/ def shrink {α β} [DecidableEq α] [Shrinkable α] [Shrinkable β] : TotalFunction α β → List (TotalFunction α β) | ⟨m, x⟩ => (Shrinkable.shrink (m, x)).map fun ⟨m', x'⟩ => ⟨List.dedupKeys m', x'⟩ variable [Repr α] instance Pi.sampleableExt : SampleableExt (α → β) where proxy := TotalFunction α (SampleableExt.proxy β) interp f := SampleableExt.interp ∘ f.apply sample := do let xs : List (_ × _) ← (SampleableExt.sample (α := List (α × β))) let ⟨x⟩ ← ULiftable.up.{max u ub} <| (SampleableExt.sample : Gen (SampleableExt.proxy β)) pure <| TotalFunction.withDefault (List.toFinmap' <| xs.map <| Prod.map SampleableExt.interp id) x -- note: no way of shrinking the domain without an inverse to `interp` shrink := { shrink := letI : Shrinkable α := {}; TotalFunction.shrink } end section Finsupp variable [Zero β] /-- Map a total_function to one whose default value is zero so that it represents a finsupp. -/ @[simp] def zeroDefault : TotalFunction α β → TotalFunction α β | withDefault A _ => withDefault A 0 variable [DecidableEq α] [DecidableEq β] /-- The support of a zero default `TotalFunction`. -/ @[simp] def zeroDefaultSupp : TotalFunction α β → Finset α | withDefault A _ => List.toFinset <| (A.dedupKeys.filter fun ab => Sigma.snd ab ≠ 0).map Sigma.fst /-- Create a finitely supported function from a total function by taking the default value to zero. -/ def applyFinsupp (tf : TotalFunction α β) : α →₀ β where support := zeroDefaultSupp tf toFun := tf.zeroDefault.apply mem_support_toFun := by intro a rcases tf with ⟨A, y⟩ simp only [apply, zeroDefaultSupp, List.mem_map, List.mem_filter, exists_and_right, List.mem_toFinset, exists_eq_right, Sigma.exists, Ne, zeroDefault] constructor · rintro ⟨od, hval, hod⟩ have := List.mem_dlookup (List.nodupKeys_dedupKeys A) hval rw [(_ : List.dlookup a A = od)] · simpa using hod · simpa [List.dlookup_dedupKeys] · intro h use (A.dlookup a).getD (0 : β) rw [← List.dlookup_dedupKeys] at h ⊢ simp only [h, ← List.mem_dlookup_iff A.nodupKeys_dedupKeys, and_true_iff, not_false_iff, Option.mem_def] cases haA : List.dlookup a A.dedupKeys · simp [haA] at h · simp variable [SampleableExt α] [SampleableExt β] [Repr α] instance Finsupp.sampleableExt : SampleableExt (α →₀ β) where proxy := TotalFunction α (SampleableExt.proxy β) interp := fun f => (f.comp SampleableExt.interp).applyFinsupp sample := SampleableExt.sample (α := α → β) -- note: no way of shrinking the domain without an inverse to `interp` shrink := { shrink := letI : Shrinkable α := {}; TotalFunction.shrink } -- TODO: support a non-constant codomain type instance DFinsupp.sampleableExt : SampleableExt (Π₀ _ : α, β) where proxy := TotalFunction α (SampleableExt.proxy β) interp := fun f => (f.comp SampleableExt.interp).applyFinsupp.toDFinsupp sample := SampleableExt.sample (α := α → β) -- note: no way of shrinking the domain without an inverse to `interp` shrink := { shrink := letI : Shrinkable α := {}; TotalFunction.shrink } end Finsupp section SampleableExt open SampleableExt instance (priority := 2000) PiPred.sampleableExt [SampleableExt (α → Bool)] : SampleableExt.{u + 1} (α → Prop) where proxy := proxy (α → Bool) interp m x := interp m x sample := sample shrink := SampleableExt.shrink instance (priority := 2000) PiUncurry.sampleableExt [SampleableExt (α × β → γ)] : SampleableExt.{imax (u + 1) (v + 1) w} (α → β → γ) where proxy := proxy (α × β → γ) interp m x y := interp m (x, y) sample := sample shrink := SampleableExt.shrink end SampleableExt end TotalFunction end SlimCheck -- We need List perm notation from `List` namespace but can't open `_root_.List` directly, -- so have to close the `SlimCheck` namespace first. -- Lean issue: https://github.com/leanprover/lean4/issues/3045 open List namespace SlimCheck /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `mapToSelf f` encodes `x ↦ f x` when `x ∈ f` and `x ↦ x`, i.e. `x` to itself, otherwise. We use `Σ` to encode mappings instead of `×` because we rely on the association list API defined in `Mathlib/Data/List/Sigma.lean`. -/ inductive InjectiveFunction (α : Type u) : Type u | mapToSelf (xs : List (Σ _ : α, α)) : xs.map Sigma.fst ~ xs.map Sigma.snd → List.Nodup (xs.map Sigma.snd) → InjectiveFunction α instance : Inhabited (InjectiveFunction α) := ⟨⟨[], List.Perm.nil, List.nodup_nil⟩⟩ namespace InjectiveFunction /-- Apply a total function to an argument. -/ def apply [DecidableEq α] : InjectiveFunction α → α → α | InjectiveFunction.mapToSelf m _ _, x => (m.dlookup x).getD x /-- Produce a string for a given `InjectiveFunction`. The output is of the form `[x₀ ↦ f x₀, .. xₙ ↦ f xₙ, x ↦ x]`. Unlike for `TotalFunction`, the default value is not a constant but the identity function. -/ protected def repr [Repr α] : InjectiveFunction α → String | InjectiveFunction.mapToSelf m _ _ => s! "[{TotalFunction.reprAux m}x ↦ x]" instance (α : Type u) [Repr α] : Repr (InjectiveFunction α) where reprPrec f _p := InjectiveFunction.repr f /-- Interpret a list of pairs as a total function, defaulting to the identity function when no entries are found for a given function -/ def List.applyId [DecidableEq α] (xs : List (α × α)) (x : α) : α := ((xs.map Prod.toSigma).dlookup x).getD x @[simp] theorem List.applyId_cons [DecidableEq α] (xs : List (α × α)) (x y z : α) : List.applyId ((y, z)::xs) x = if y = x then z else List.applyId xs x := by simp only [List.applyId, List.dlookup, eq_rec_constant, Prod.toSigma, List.map] split_ifs <;> rfl open Function open List open Nat theorem List.applyId_zip_eq [DecidableEq α] {xs ys : List α} (h₀ : List.Nodup xs) (h₁ : xs.length = ys.length) (x y : α) (i : ℕ) (h₂ : xs[i]? = some x) : List.applyId.{u} (xs.zip ys) x = y ↔ ys[i]? = some y := by induction xs generalizing ys i with | nil => cases h₂ | cons x' xs xs_ih => cases i · simp only [length_cons, lt_add_iff_pos_left, add_pos_iff, zero_lt_one, or_true, getElem?_eq_getElem, getElem_cons_zero, Option.some.injEq] at h₂ subst h₂ cases ys · cases h₁ · simp only [applyId, map, Prod.toSigma, dlookup_cons_eq, Option.getD_some, getElem?_cons_zero, Option.some.injEq] · cases ys · cases h₁ · cases' h₀ with _ _ h₀ h₁ simp only [getElem?_cons_succ, zip_cons_cons, applyId_cons] at h₂ ⊢ rw [if_neg] · apply xs_ih <;> solve_by_elim [Nat.succ.inj] · apply h₀; apply List.getElem?_mem h₂ theorem applyId_mem_iff [DecidableEq α] {xs ys : List α} (h₀ : List.Nodup xs) (h₁ : xs ~ ys) (x : α) : List.applyId.{u} (xs.zip ys) x ∈ ys ↔ x ∈ xs := by simp only [List.applyId] cases h₃ : List.dlookup x (List.map Prod.toSigma (xs.zip ys)) with | none => dsimp [Option.getD] rw [h₁.mem_iff] | some val => have h₂ : ys.Nodup := h₁.nodup_iff.1 h₀ replace h₁ : xs.length = ys.length := h₁.length_eq dsimp induction xs generalizing ys with | nil => contradiction | cons x' xs xs_ih => cases' ys with y ys · cases h₃ dsimp [List.dlookup] at h₃; split_ifs at h₃ with h · rw [Option.some_inj] at h₃ subst x'; subst val simp only [List.mem_cons, true_or_iff, eq_self_iff_true] · cases' h₀ with _ _ h₀ h₅ cases' h₂ with _ _ h₂ h₄ have h₆ := Nat.succ.inj h₁ specialize xs_ih h₅ h₃ h₄ h₆ simp only [Ne.symm h, xs_ih, List.mem_cons, false_or_iff] suffices val ∈ ys by tauto erw [← Option.mem_def, List.mem_dlookup_iff] at h₃ · simp only [Prod.toSigma, List.mem_map, heq_iff_eq, Prod.exists] at h₃ rcases h₃ with ⟨a, b, h₃, h₄, h₅⟩ apply (List.of_mem_zip h₃).2 simp only [List.NodupKeys, List.keys, comp, Prod.fst_toSigma, List.map_map] rwa [List.map_fst_zip _ _ (le_of_eq h₆)] theorem List.applyId_eq_self [DecidableEq α] {xs ys : List α} (x : α) : x ∉ xs → List.applyId.{u} (xs.zip ys) x = x := by intro h dsimp [List.applyId] rw [List.dlookup_eq_none.2] · rfl simp only [List.keys, not_exists, Prod.toSigma, exists_and_right, exists_eq_right, List.mem_map, Function.comp_apply, List.map_map, Prod.exists] intro y hy exact h (List.of_mem_zip hy).1 theorem applyId_injective [DecidableEq α] {xs ys : List α} (h₀ : List.Nodup xs) (h₁ : xs ~ ys) : Injective.{u + 1, u + 1} (List.applyId (xs.zip ys)) := by intro x y h by_cases hx : x ∈ xs <;> by_cases hy : y ∈ xs · rw [List.mem_iff_getElem?] at hx hy cases' hx with i hx cases' hy with j hy suffices some x = some y by injection this have h₂ := h₁.length_eq rw [List.applyId_zip_eq h₀ h₂ _ _ _ hx] at h rw [← hx, ← hy]; congr apply List.getElem?_inj _ (h₁.nodup_iff.1 h₀) · symm; rw [h] rw [← List.applyId_zip_eq] <;> assumption · rw [← h₁.length_eq] rw [List.getElem?_eq_some] at hx cases' hx with hx hx' exact hx · rw [← applyId_mem_iff h₀ h₁] at hx hy rw [h] at hx contradiction · rw [← applyId_mem_iff h₀ h₁] at hx hy rw [h] at hx contradiction · rwa [List.applyId_eq_self, List.applyId_eq_self] at h <;> assumption open TotalFunction (List.toFinmap') open SampleableExt /-- Remove a slice of length `m` at index `n` in a list and a permutation, maintaining the property that it is a permutation. -/ def Perm.slice [DecidableEq α] (n m : ℕ) : (Σ' xs ys : List α, xs ~ ys ∧ ys.Nodup) → Σ' xs ys : List α, xs ~ ys ∧ ys.Nodup | ⟨xs, ys, h, h'⟩ => let xs' := List.dropSlice n m xs have h₀ : xs' ~ ys.inter xs' := List.Perm.dropSlice_inter _ _ h h' ⟨xs', ys.inter xs', h₀, h'.inter _⟩ /-- A list, in decreasing order, of sizes that should be sliced off a list of length `n` -/ def sliceSizes : ℕ → MLList Id ℕ+ | n => if h : 0 < n then have : n / 2 < n := Nat.div_lt_self h (by decide : 1 < 2) .cons ⟨_, h⟩ (sliceSizes <| n / 2) else .nil /-- Shrink a permutation of a list, slicing a segment in the middle. The sizes of the slice being removed start at `n` (with `n` the length of the list) and then `n / 2`, then `n / 4`, etc down to 1. The slices will be taken at index `0`, `n / k`, `2n / k`, `3n / k`, etc. -/ protected def shrinkPerm {α : Type} [DecidableEq α] : (Σ' xs ys : List α, xs ~ ys ∧ ys.Nodup) → List (Σ' xs ys : List α, xs ~ ys ∧ ys.Nodup) | xs => do let k := xs.1.length let n ← (sliceSizes k).force let i ← List.finRange <| k / n pure <| Perm.slice (i * n) n xs -- Porting note: removed, there is no `sizeof` in the new `Sampleable` -- instance [SizeOf α] : SizeOf (InjectiveFunction α) := -- ⟨fun ⟨xs, _, _⟩ => SizeOf.sizeOf (xs.map Sigma.fst)⟩ /-- Shrink an injective function slicing a segment in the middle of the domain and removing the corresponding elements in the codomain, hence maintaining the property that one is a permutation of the other. -/ protected def shrink {α : Type} [DecidableEq α] : InjectiveFunction α → List (InjectiveFunction α) | ⟨xs, h₀, h₁⟩ => do let ⟨xs', ys', h₀, h₁⟩ ← InjectiveFunction.shrinkPerm ⟨_, _, h₀, h₁⟩ have h₃ : xs'.length ≤ ys'.length := le_of_eq (List.Perm.length_eq h₀) have h₄ : ys'.length ≤ xs'.length := le_of_eq (List.Perm.length_eq h₀.symm) pure ⟨(List.zip xs' ys').map Prod.toSigma, by simp only [comp, List.map_fst_zip, List.map_snd_zip, *, Prod.fst_toSigma, Prod.snd_toSigma, List.map_map], by simp only [comp, List.map_snd_zip, *, Prod.snd_toSigma, List.map_map]⟩ /-- Create an injective function from one list and a permutation of that list. -/ protected def mk (xs ys : List α) (h : xs ~ ys) (h' : ys.Nodup) : InjectiveFunction α := have h₀ : xs.length ≤ ys.length := le_of_eq h.length_eq have h₁ : ys.length ≤ xs.length := le_of_eq h.length_eq.symm InjectiveFunction.mapToSelf (List.toFinmap' (xs.zip ys)) (by simp only [List.toFinmap', comp, List.map_fst_zip, List.map_snd_zip, *, Prod.fst_toSigma, Prod.snd_toSigma, List.map_map]) (by simp only [List.toFinmap', comp, List.map_snd_zip, *, Prod.snd_toSigma, List.map_map]) protected theorem injective [DecidableEq α] (f : InjectiveFunction α) : Injective (apply f) := by cases' f with xs hperm hnodup generalize h₀ : List.map Sigma.fst xs = xs₀ generalize h₁ : xs.map (@id ((Σ _ : α, α) → α) <| @Sigma.snd α fun _ : α => α) = xs₁ dsimp [id] at h₁ have hxs : xs = TotalFunction.List.toFinmap' (xs₀.zip xs₁) := by rw [← h₀, ← h₁, List.toFinmap']; clear h₀ h₁ xs₀ xs₁ hperm hnodup induction xs with | nil => simp only [List.zip_nil_right, List.map_nil] | cons xs_hd xs_tl xs_ih => simp only [true_and_iff, Prod.toSigma, eq_self_iff_true, Sigma.eta, List.zip_cons_cons, List.map, List.cons_inj_right] exact xs_ih revert hperm hnodup rw [hxs]; intros hperm hnodup apply InjectiveFunction.applyId_injective · rwa [← h₀, hxs, hperm.nodup_iff] · rwa [← hxs, h₀, h₁] at hperm instance PiInjective.sampleableExt : SampleableExt { f : ℤ → ℤ // Function.Injective f } where proxy := InjectiveFunction ℤ interp f := ⟨apply f, f.injective⟩ sample := do let ⟨sz⟩ ← ULiftable.up Gen.getSize let xs' := Int.range (-(2 * sz + 2)) (2 * sz + 2) let ys ← Gen.permutationOf xs' have Hinj : Injective fun r : ℕ => -(2 * sz + 2 : ℤ) + ↑r := fun _x _y h => Int.ofNat.inj (add_right_injective _ h) let r : InjectiveFunction ℤ := InjectiveFunction.mk.{0} xs' ys.1 ys.2 (ys.2.nodup_iff.1 <| (List.nodup_range _).map Hinj) pure r shrink := {shrink := @InjectiveFunction.shrink ℤ _ } end InjectiveFunction open Function instance Injective.testable (f : α → β) [I : Testable (NamedBinder "x" <| ∀ x : α, NamedBinder "y" <| ∀ y : α, NamedBinder "H" <| f x = f y → x = y)] : Testable (Injective f) := I instance Monotone.testable [Preorder α] [Preorder β] (f : α → β) [I : Testable (NamedBinder "x" <| ∀ x : α, NamedBinder "y" <| ∀ y : α, NamedBinder "H" <| x ≤ y → f x ≤ f y)] : Testable (Monotone f) := I instance Antitone.testable [Preorder α] [Preorder β] (f : α → β) [I : Testable (NamedBinder "x" <| ∀ x : α, NamedBinder "y" <| ∀ y : α, NamedBinder "H" <| x ≤ y → f y ≤ f x)] : Testable (Antitone f) := I end SlimCheck
Testing\SlimCheck\Gen.lean
/- Copyright (c) 2021 Henrik Böving. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henrik Böving, Simon Hudon -/ import Mathlib.Control.Random import Batteries.Data.List.Perm /-! # `Gen` Monad This monad is used to formulate randomized computations with a parameter to specify the desired size of the result. This is a port of the Haskell QuickCheck library. ## Main definitions * `Gen` monad ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ universe u v namespace SlimCheck open Random /-- Monad to generate random examples to test properties with. It has a `Nat` parameter so that the caller can decide on the size of the examples. -/ abbrev Gen (α : Type u) := ReaderT (ULift Nat) Rand α namespace Gen /-- Lift `Random.random` to the `Gen` monad. -/ def chooseAny (α : Type u) [Random Id α] : Gen α := fun _ ↦ rand α /-- Lift `BoundedRandom.randomR` to the `Gen` monad. -/ def choose (α : Type u) [Preorder α] [BoundedRandom Id α] (lo hi : α) (h : lo ≤ hi) : Gen {a // lo ≤ a ∧ a ≤ hi} := fun _ ↦ randBound α lo hi h lemma chooseNatLt_aux {lo hi : Nat} (a : Nat) (h : Nat.succ lo ≤ a ∧ a ≤ hi) : lo ≤ Nat.pred a ∧ Nat.pred a < hi := And.intro (Nat.le_sub_one_of_lt (Nat.lt_of_succ_le h.left)) <| show a.pred.succ ≤ hi by rw [Nat.succ_pred_eq_of_pos] · exact h.right · exact lt_of_le_of_lt (Nat.zero_le lo) h.left /-- Generate a `Nat` example between `x` and `y` (exclusively). -/ def chooseNatLt (lo hi : Nat) (h : lo < hi) : Gen {a // lo ≤ a ∧ a < hi} := Subtype.map Nat.pred chooseNatLt_aux <$> choose Nat (lo.succ) hi (Nat.succ_le_of_lt h) /-- Get access to the size parameter of the `Gen` monad. -/ def getSize : Gen Nat := return (← read).down /-- Apply a function to the size parameter. -/ def resize {α : Type*} (f : Nat → Nat) (x : Gen α) : Gen α := withReader (ULift.up ∘ f ∘ ULift.down) x variable {α : Type u} /-- Create an `Array` of examples using `x`. The size is controlled by the size parameter of `Gen`. -/ def arrayOf (x : Gen α) : Gen (Array α) := do let (⟨sz⟩ : ULift ℕ) ← ULiftable.up do choose Nat 0 (← getSize) (Nat.zero_le _) let mut res := #[] for _ in [0:sz] do res := res.push (← x) pure res /-- Create a `List` of examples using `x`. The size is controlled by the size parameter of `Gen`. -/ def listOf (x : Gen α) : Gen (List α) := arrayOf x >>= pure ∘ Array.toList /-- Given a list of example generators, choose one to create an example. -/ def oneOf (xs : Array (Gen α)) (pos : 0 < xs.size := by decide) : Gen α := do let ⟨x, _, h2⟩ ← ULiftable.up <| chooseNatLt 0 xs.size pos xs.get ⟨x, h2⟩ /-- Given a list of examples, choose one to create an example. -/ def elements (xs : List α) (pos : 0 < xs.length) : Gen α := do let ⟨x, _, h2⟩ ← ULiftable.up <| chooseNatLt 0 xs.length pos pure <| xs.get ⟨x, h2⟩ open List in /-- Generate a random permutation of a given list. -/ def permutationOf : (xs : List α) → Gen { ys // xs ~ ys } | [] => pure ⟨[], Perm.nil⟩ | x::xs => do let ⟨ys, h1⟩ ← permutationOf xs let ⟨n, _, h3⟩ ← ULiftable.up <| choose Nat 0 ys.length (Nat.zero_le _) pure ⟨insertNth n x ys, Perm.trans (Perm.cons _ h1) (perm_insertNth _ _ h3).symm⟩ /-- Given two generators produces a tuple consisting out of the result of both -/ def prodOf {α : Type u} {β : Type v} (x : Gen α) (y : Gen β) : Gen (α × β) := do let ⟨a⟩ ← ULiftable.up.{max u v} x let ⟨b⟩ ← ULiftable.up.{max u v} y pure (a, b) end Gen /-- Execute a `Gen` inside the `IO` monad using `size` as the example size-/ def Gen.run {α : Type} (x : Gen α) (size : Nat) : BaseIO α := letI : MonadLift Id BaseIO := ⟨fun f => pure <| Id.run f⟩ IO.runRand (ReaderT.run x ⟨size⟩:) end SlimCheck
Testing\SlimCheck\Sampleable.lean
/- Copyright (c) 2022 Henrik Böving. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henrik Böving, Simon Hudon -/ import Mathlib.Algebra.Order.Ring.Int import Mathlib.Init.Data.List.Instances import Mathlib.Testing.SlimCheck.Gen /-! # `SampleableExt` Class This class permits the creation samples of a given type controlling the size of those values using the `Gen` monad. # `Shrinkable` Class This class helps minimize examples by creating smaller versions of given values. When testing a proposition like `∀ n : ℕ, Prime n → n ≤ 100`, `SlimCheck` requires that `ℕ` have an instance of `SampleableExt` and for `Prime n` to be decidable. `SlimCheck` will then use the instance of `SampleableExt` to generate small examples of ℕ and progressively increase in size. For each example `n`, `Prime n` is tested. If it is false, the example will be rejected (not a test success nor a failure) and `SlimCheck` will move on to other examples. If `Prime n` is true, `n ≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ n : ℕ, Prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, the test passes and `SlimCheck` moves on to trying more examples. This is a port of the Haskell QuickCheck library. ## Main definitions * `SampleableExt` class * `Shrinkable` class ### `SampleableExt` `SampleableExt` can be used in two ways. The first (and most common) is to simply generate values of a type directly using the `Gen` monad, if this is what you want to do then `SampleableExt.mkSelfContained` is the way to go. Furthermore it makes it possible to express generators for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `SampleableExt` provides a proxy representation `proxy` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. If you are using it in the first way, this proxy type will simply be the type itself and the `interp` function `id`. ### `Shrinkable` Given an example `x : α`, `Shrinkable α` gives us a way to shrink it and suggest simpler examples. ## Shrinking Shrinking happens when `SlimCheck` find a counter-example to a property. It is likely that the example will be more complicated than necessary so `SlimCheck` proceeds to shrink it as much as possible. Although equally valid, a smaller counter-example is easier for a user to understand and use. The `Shrinkable` class, , has a `shrink` function so that we can use specialized knowledge while shrinking a value. It is not responsible for the whole shrinking process however. It only has to take one step in the shrinking process. `SlimCheck` will repeatedly call `shrink` until no more steps can be taken. Because `shrink` guarantees that the size of the candidates it produces is strictly smaller than the argument, we know that `SlimCheck` is guaranteed to terminate. ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ namespace SlimCheck open Random Gen universe u v variable {α β : Type*} /-- Given an example `x : α`, `Shrinkable α` gives us a way to shrink it and suggest simpler examples. -/ class Shrinkable (α : Type u) where shrink : (x : α) → List α := fun _ ↦ [] /-- `SampleableExt` can be used in two ways. The first (and most common) is to simply generate values of a type directly using the `Gen` monad, if this is what you want to do then `SampleableExt.mkSelfContained` is the way to go. Furthermore it makes it possible to express generators for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `SampleableExt` provides a proxy representation `proxy` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. -/ class SampleableExt (α : Sort u) where proxy : Type v [proxyRepr : Repr proxy] [shrink : Shrinkable proxy] sample : Gen proxy interp : proxy → α attribute [instance] SampleableExt.proxyRepr attribute [instance] SampleableExt.shrink namespace SampleableExt /-- Use to generate instance whose purpose is to simply generate values of a type directly using the `Gen` monad -/ def mkSelfContained [Repr α] [Shrinkable α] (sample : Gen α) : SampleableExt α where proxy := α proxyRepr := inferInstance shrink := inferInstance sample := sample interp := id /-- First samples a proxy value and interprets it. Especially useful if the proxy and target type are the same. -/ def interpSample (α : Type u) [SampleableExt α] : Gen α := SampleableExt.interp <$> SampleableExt.sample end SampleableExt section Shrinkers /-- `Nat.shrink' n` creates a list of smaller natural numbers by successively dividing `n` by 2 . For example, `Nat.shrink 5 = [2, 1, 0]`. -/ def Nat.shrink (n : Nat) : List Nat := if h : 0 < n then let m := n/2 have : m < n := by apply Nat.div_lt_self h decide m :: shrink m else [] instance Nat.shrinkable : Shrinkable Nat where shrink := Nat.shrink instance Fin.shrinkable {n : Nat} : Shrinkable (Fin n.succ) where shrink m := Nat.shrink m /-- `Int.shrinkable` operates like `Nat.shrinkable` but also includes the negative variants. -/ instance Int.shrinkable : Shrinkable Int where shrink n := Nat.shrink n.natAbs |>.map (fun x ↦ ([x, -x] : List ℤ)) |>.join instance Rat.shrinkable : Shrinkable Rat where shrink r := (Shrinkable.shrink r.num).bind fun d => Nat.shrink r.den |>.map fun n => Rat.divInt d n instance Bool.shrinkable : Shrinkable Bool := {} instance Char.shrinkable : Shrinkable Char := {} instance Prod.shrinkable [shrA : Shrinkable α] [shrB : Shrinkable β] : Shrinkable (Prod α β) where shrink := fun (fst,snd) ↦ let shrink1 := shrA.shrink fst |>.map fun x ↦ (x, snd) let shrink2 := shrB.shrink snd |>.map fun x ↦ (fst, x) shrink1 ++ shrink2 instance Sigma.shrinkable [shrA : Shrinkable α] [shrB : Shrinkable β] : Shrinkable ((_ : α) × β) where shrink := fun ⟨fst,snd⟩ ↦ let shrink1 := shrA.shrink fst |>.map fun x ↦ ⟨x, snd⟩ let shrink2 := shrB.shrink snd |>.map fun x ↦ ⟨fst, x⟩ shrink1 ++ shrink2 open Shrinkable /-- Shrink a list of a shrinkable type, either by discarding an element or shrinking an element. -/ instance List.shrinkable [Shrinkable α] : Shrinkable (List α) where shrink := fun L => (L.mapIdx fun i _ => L.eraseIdx i) ++ (L.mapIdx fun i a => (shrink a).map fun a' => L.modifyNth (fun _ => a') i).join end Shrinkers section Samplers open SampleableExt instance Nat.sampleableExt : SampleableExt Nat := mkSelfContained (do choose Nat 0 (← getSize) (Nat.zero_le _)) instance Fin.sampleableExt {n : Nat} : SampleableExt (Fin (n.succ)) := mkSelfContained (do choose (Fin n.succ) (Fin.ofNat 0) (Fin.ofNat (← getSize)) (by simp only [Fin.ofNat, Fin.val_zero] exact Nat.zero_le _)) instance Int.sampleableExt : SampleableExt Int := mkSelfContained (do choose Int (-(← getSize)) (← getSize) (le_trans (Int.neg_nonpos_of_nonneg (Int.ofNat_zero_le _)) (Int.ofNat_zero_le _))) instance Rat.sampleableExt : SampleableExt Rat := mkSelfContained (do let d ← choose Int (-(← getSize)) (← getSize) (le_trans (Int.neg_nonpos_of_nonneg (Int.ofNat_zero_le _)) (Int.ofNat_zero_le _)) let n ← choose Nat 0 (← getSize) (Nat.zero_le _) return Rat.divInt d n) instance Bool.sampleableExt : SampleableExt Bool := mkSelfContained <| chooseAny Bool /-- This can be specialized into customized `SampleableExt Char` instances. The resulting instance has `1 / length` chances of making an unrestricted choice of characters and it otherwise chooses a character from `chars` with uniform probabilities. -/ def Char.sampleable (length : Nat) (chars : List Char) (pos : 0 < chars.length) : SampleableExt Char := mkSelfContained do let x ← choose Nat 0 length (Nat.zero_le _) if x.val == 0 then let n ← interpSample Nat pure <| Char.ofNat n else elements chars pos instance Char.sampleableDefault : SampleableExt Char := Char.sampleable 3 " 0123abcABC:,;`\\/".toList (by decide) instance Prod.sampleableExt {α : Type u} {β : Type v} [SampleableExt α] [SampleableExt β] : SampleableExt (α × β) where proxy := Prod (proxy α) (proxy β) proxyRepr := inferInstance shrink := inferInstance sample := prodOf sample sample interp := Prod.map interp interp instance Prop.sampleableExt : SampleableExt Prop where proxy := Bool proxyRepr := inferInstance sample := interpSample Bool shrink := inferInstance interp := Coe.coe instance List.sampleableExt [SampleableExt α] : SampleableExt (List α) where proxy := List (proxy α) sample := Gen.listOf sample interp := List.map interp end Samplers /-- An annotation for values that should never get shrinked. -/ def NoShrink (α : Type u) := α namespace NoShrink def mk (x : α) : NoShrink α := x def get (x : NoShrink α) : α := x instance inhabited [inst : Inhabited α] : Inhabited (NoShrink α) := inst instance repr [inst : Repr α] : Repr (NoShrink α) := inst instance shrinkable : Shrinkable (NoShrink α) where shrink := fun _ ↦ [] instance sampleableExt [SampleableExt α] [Repr α] : SampleableExt (NoShrink α) := SampleableExt.mkSelfContained <| (NoShrink.mk ∘ SampleableExt.interp) <$> SampleableExt.sample end NoShrink /-- Print (at most) 10 samples of a given type to stdout for debugging. -/ -- Porting note: if `Control.ULiftable` is ported, make use of that here, as in mathlib3, -- to enable sampling from higher types. def printSamples {t : Type} [Repr t] (g : Gen t) : IO PUnit := do for i in List.range 10 do IO.println s!"{repr (← g.run i)}" open Lean Meta Qq /-- Create a `Gen α` expression from the argument of `#sample` -/ def mkGenerator (e : Expr) : MetaM (Σ (u : Level) (α : Q(Type $u)), Q(Repr $α) × Q(Gen $α)) := do match ← inferTypeQ e with | ⟨.succ u, ~q(Gen $α), gen⟩ => let repr_inst ← synthInstanceQ (q(Repr $α) : Q(Type $u)) pure ⟨u, α, repr_inst, gen⟩ | ⟨.succ u, ~q(Sort u), α⟩ => do let v ← mkFreshLevelMVar let _sampleableExt_inst ← synthInstanceQ (q(SampleableExt.{u,v} $α) : Q(Sort (max u (v + 2)))) let v ← instantiateLevelMVars v let repr_inst := q(SampleableExt.proxyRepr (α := $α)) let gen := q(SampleableExt.sample (α := $α)) pure ⟨v, q(SampleableExt.proxy $α), repr_inst, gen⟩ | ⟨_u, t, _e⟩ => throwError "Must be a Sort u` or a `Gen α`, got value of type{indentExpr t}" open Elab /-- `#sample type`, where `type` has an instance of `SampleableExt`, prints ten random values of type `type` using an increasing size parameter. ```lean #sample Nat -- prints -- 0 -- 0 -- 2 -- 24 -- 64 -- 76 -- 5 -- 132 -- 8 -- 449 -- or some other sequence of numbers #sample List Int -- prints -- [] -- [1, 1] -- [-7, 9, -6] -- [36] -- [-500, 105, 260] -- [-290] -- [17, 156] -- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968] -- [-643] -- [11892, 16329, -15095, -15461] -- or whatever ``` -/ elab "#sample " e:term : command => Command.runTermElabM fun _ => do let e ← Elab.Term.elabTermAndSynthesize e none let g ← mkGenerator e -- `printSamples` only works in `Type 0` (see the porting note) let ⟨0, α, _, gen⟩ := g | throwError "Cannot sample from {g.1} due to its universe" let printSamples := q(printSamples (t := $α) $gen) let code ← unsafe evalExpr (IO PUnit) q(IO PUnit) printSamples _ ← code end SlimCheck
Testing\SlimCheck\Testable.lean
/- Copyright (c) 2022 Henrik Böving. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henrik Böving, Simon Hudon -/ import Mathlib.Testing.SlimCheck.Sampleable import Lean /-! # `Testable` Class Testable propositions have a procedure that can generate counter-examples together with a proof that they invalidate the proposition. This is a port of the Haskell QuickCheck library. ## Creating Customized Instances The type classes `Testable`, `SampleableExt` and `Shrinkable` are the means by which `SlimCheck` creates samples and tests them. For instance, the proposition `∀ i j : ℕ, i ≤ j` has a `Testable` instance because `ℕ` is sampleable and `i ≤ j` is decidable. Once `SlimCheck` finds the `Testable` instance, it can start using the instance to repeatedly creating samples and checking whether they satisfy the property. Once it has found a counter-example it will then use a `Shrinkable` instance to reduce the example. This allows the user to create new instances and apply `SlimCheck` to new situations. ### What do I do if I'm testing a property about my newly defined type? Let us consider a type made for a new formalization: ```lean structure MyType where x : ℕ y : ℕ h : x ≤ y deriving Repr ``` How do we test a property about `MyType`? For instance, let us consider `Testable.check <| ∀ a b : MyType, a.y ≤ b.x → a.x ≤ b.y`. Writing this property as is will give us an error because we do not have an instance of `Shrinkable MyType` and `SampleableExt MyType`. We can define one as follows: ```lean instance : Shrinkable MyType where shrink := fun ⟨x,y,h⟩ ↦ let proxy := Shrinkable.shrink (x, y - x) proxy.map (fun ⟨⟨fst, snd⟩, ha⟩ ↦ ⟨⟨fst, fst + snd, sorry⟩, sorry⟩) instance : SampleableExt MyType := SampleableExt.mkSelfContained do let x ← SampleableExt.interpSample Nat let xyDiff ← SampleableExt.interpSample Nat pure <| ⟨x, x + xyDiff, sorry⟩ ``` Again, we take advantage of the fact that other types have useful `Shrinkable` implementations, in this case `Prod`. Note that the second proof is heavily based on `WellFoundedRelation` since it's used for termination so the first step you want to take is almost always to `simp_wf` in order to get through the `WellFoundedRelation`. ## Main definitions * `Testable` class * `Testable.check`: a way to test a proposition using random examples ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ namespace SlimCheck /-- Result of trying to disprove `p` The constructors are: * `success : (Unit ⊕' p) → TestResult p` succeed when we find another example satisfying `p` In `success h`, `h` is an optional proof of the proposition. Without the proof, all we know is that we found one example where `p` holds. With a proof, the one test was sufficient to prove that `p` holds and we do not need to keep finding examples. * `gaveUp : ℕ → TestResult p` give up when a well-formed example cannot be generated. `gaveUp n` tells us that `n` invalid examples were tried. Above 100, we give up on the proposition and report that we did not find a way to properly test it. * `failure : ¬ p → (List String) → ℕ → TestResult p` a counter-example to `p`; the strings specify values for the relevant variables. `failure h vs n` also carries a proof that `p` does not hold. This way, we can guarantee that there will be no false positive. The last component, `n`, is the number of times that the counter-example was shrunk. -/ inductive TestResult (p : Prop) where | success : Unit ⊕' p → TestResult p | gaveUp : Nat → TestResult p | failure : ¬ p → List String → Nat → TestResult p deriving Inhabited /-- Configuration for testing a property. -/ structure Configuration where numInst : Nat := 100 maxSize : Nat := 100 numRetries : Nat := 10 traceDiscarded : Bool := false traceSuccesses : Bool := false traceShrink : Bool := false traceShrinkCandidates : Bool := false randomSeed : Option Nat := none quiet : Bool := false deriving Inhabited open Lean in instance : ToExpr Configuration where toTypeExpr := mkConst `Configuration toExpr cfg := mkApp9 (mkConst ``Configuration.mk) (toExpr cfg.numInst) (toExpr cfg.maxSize) (toExpr cfg.numRetries) (toExpr cfg.traceDiscarded) (toExpr cfg.traceSuccesses) (toExpr cfg.traceShrink) (toExpr cfg.traceShrinkCandidates) (toExpr cfg.randomSeed) (toExpr cfg.quiet) /-- Allow elaboration of `Configuration` arguments to tactics. -/ declare_config_elab elabConfig Configuration /-- `PrintableProp p` allows one to print a proposition so that `SlimCheck` can indicate how values relate to each other. It's basically a poor man's delaborator. -/ class PrintableProp (p : Prop) where printProp : String export PrintableProp (printProp) variable {p q : Prop} instance (priority := low) : PrintableProp p where printProp := "⋯" /-- `Testable p` uses random examples to try to disprove `p`. -/ class Testable (p : Prop) where run (cfg : Configuration) (minimize : Bool) : Gen (TestResult p) @[nolint unusedArguments] def NamedBinder (_n : String) (p : Prop) : Prop := p namespace TestResult def toString : TestResult p → String | success (PSum.inl _) => "success (no proof)" | success (PSum.inr _) => "success (proof)" | gaveUp n => s!"gave {n} times" | failure _ counters _ => s!"failed {counters}" instance : ToString (TestResult p) := ⟨toString⟩ /-- Applicative combinator proof carrying test results. -/ def combine {p q : Prop} : Unit ⊕' (p → q) → Unit ⊕' p → Unit ⊕' q | PSum.inr f, PSum.inr proof => PSum.inr <| f proof | _, _ => PSum.inl () /-- Combine the test result for properties `p` and `q` to create a test for their conjunction. -/ def and : TestResult p → TestResult q → TestResult (p ∧ q) | failure h xs n, _ => failure (fun h2 ↦ h h2.left) xs n | _, failure h xs n => failure (fun h2 ↦ h h2.right) xs n | success h1, success h2 => success <| combine (combine (PSum.inr And.intro) h1) h2 | gaveUp n, gaveUp m => gaveUp <| n + m | gaveUp n, _ => gaveUp n | _, gaveUp n => gaveUp n /-- Combine the test result for properties `p` and `q` to create a test for their disjunction. -/ def or : TestResult p → TestResult q → TestResult (p ∨ q) | failure h1 xs n, failure h2 ys m => let h3 := fun h ↦ match h with | Or.inl h3 => h1 h3 | Or.inr h3 => h2 h3 failure h3 (xs ++ ys) (n + m) | success h, _ => success <| combine (PSum.inr Or.inl) h | _, success h => success <| combine (PSum.inr Or.inr) h | gaveUp n, gaveUp m => gaveUp <| n + m | gaveUp n, _ => gaveUp n | _, gaveUp n => gaveUp n /-- If `q → p`, then `¬ p → ¬ q` which means that testing `p` can allow us to find counter-examples to `q`. -/ def imp (h : q → p) (r : TestResult p) (p : Unit ⊕' (p → q) := PSum.inl ()) : TestResult q := match r with | failure h2 xs n => failure (mt h h2) xs n | success h2 => success <| combine p h2 | gaveUp n => gaveUp n /-- Test `q` by testing `p` and proving the equivalence between the two. -/ def iff (h : q ↔ p) (r : TestResult p) : TestResult q := imp h.mp r (PSum.inr h.mpr) /-- When we assign a value to a universally quantified variable, we record that value using this function so that our counter-examples can be informative. -/ def addInfo (x : String) (h : q → p) (r : TestResult p) (p : Unit ⊕' (p → q) := PSum.inl ()) : TestResult q := if let failure h2 xs n := r then failure (mt h h2) (x :: xs) n else imp h r p /-- Add some formatting to the information recorded by `addInfo`. -/ def addVarInfo {γ : Type*} [Repr γ] (var : String) (x : γ) (h : q → p) (r : TestResult p) (p : Unit ⊕' (p → q) := PSum.inl ()) : TestResult q := addInfo s!"{var} := {repr x}" h r p def isFailure : TestResult p → Bool | failure _ _ _ => true | _ => false end TestResult namespace Configuration /-- A configuration with all the trace options enabled, useful for debugging. -/ def verbose : Configuration where traceDiscarded := true traceSuccesses := true traceShrink := true traceShrinkCandidates := true end Configuration namespace Testable open TestResult def runProp (p : Prop) [Testable p] : Configuration → Bool → Gen (TestResult p) := Testable.run /-- A `dbgTrace` with special formatting -/ def slimTrace {m : Type → Type*} [Pure m] (s : String) : m PUnit := dbgTrace s!"[SlimCheck: {s}]" (fun _ ↦ pure ()) instance andTestable [Testable p] [Testable q] : Testable (p ∧ q) where run := fun cfg min ↦ do let xp ← runProp p cfg min let xq ← runProp q cfg min pure <| and xp xq instance orTestable [Testable p] [Testable q] : Testable (p ∨ q) where run := fun cfg min ↦ do let xp ← runProp p cfg min -- As a little performance optimization we can just not run the second -- test if the first succeeds match xp with | success (PSum.inl h) => pure <| success (PSum.inl h) | success (PSum.inr h) => pure <| success (PSum.inr <| Or.inl h) | _ => let xq ← runProp q cfg min pure <| or xp xq instance iffTestable [Testable ((p ∧ q) ∨ (¬ p ∧ ¬ q))] : Testable (p ↔ q) where run := fun cfg min ↦ do let h ← runProp ((p ∧ q) ∨ (¬ p ∧ ¬ q)) cfg min pure <| iff iff_iff_and_or_not_and_not h variable {var : String} instance decGuardTestable [PrintableProp p] [Decidable p] {β : p → Prop} [∀ h, Testable (β h)] : Testable (NamedBinder var <| ∀ h, β h) where run := fun cfg min ↦ do if h : p then let res := runProp (β h) cfg min let s := printProp p (fun r ↦ addInfo s!"guard: {s}" (· <| h) r (PSum.inr <| fun q _ ↦ q)) <$> res else if cfg.traceDiscarded || cfg.traceSuccesses then let res := fun _ ↦ pure <| gaveUp 1 let s := printProp p slimTrace s!"discard: Guard {s} does not hold"; res else pure <| gaveUp 1 instance forallTypesTestable {f : Type → Prop} [Testable (f Int)] : Testable (NamedBinder var <| ∀ x, f x) where run := fun cfg min ↦ do let r ← runProp (f Int) cfg min pure <| addVarInfo var "ℤ" (· <| Int) r instance factTestable [Testable p] : Testable (Fact p) where run cfg min := do let h ← runProp p cfg min pure <| iff fact_iff h /-- Format the counter-examples found in a test failure. -/ def formatFailure (s : String) (xs : List String) (n : Nat) : String := let counter := String.intercalate "\n" xs let parts := [ "\n===================", s, counter, s!"({n} shrinks)", "-------------------" ] String.intercalate "\n" parts /-- Increase the number of shrinking steps in a test result. -/ def addShrinks (n : Nat) : TestResult p → TestResult p | TestResult.failure p xs m => TestResult.failure p xs (m + n) | p => p universe u in instance {α : Type u} {m : Type u → Type*} [Pure m] : Inhabited (OptionT m α) := ⟨(pure none : m (Option α))⟩ variable {α : Sort*} /-- Shrink a counter-example `x` by using `Shrinkable.shrink x`, picking the first candidate that falsifies a property and recursively shrinking that one. The process is guaranteed to terminate because `shrink x` produces a proof that all the values it produces are smaller (according to `SizeOf`) than `x`. -/ partial def minimizeAux [SampleableExt α] {β : α → Prop} [∀ x, Testable (β x)] (cfg : Configuration) (var : String) (x : SampleableExt.proxy α) (n : Nat) : OptionT Gen (Σ x, TestResult (β (SampleableExt.interp x))) := do let candidates := SampleableExt.shrink.shrink x if cfg.traceShrinkCandidates then slimTrace s!"Candidates for {var} := {repr x}:\n {repr candidates}" for candidate in candidates do if cfg.traceShrinkCandidates then slimTrace s!"Trying {var} := {repr candidate}" let res ← OptionT.lift <| Testable.runProp (β (SampleableExt.interp candidate)) cfg true if res.isFailure then if cfg.traceShrink then slimTrace s!"{var} shrunk to {repr candidate} from {repr x}" let currentStep := OptionT.lift <| pure <| Sigma.mk candidate (addShrinks (n + 1) res) let nextStep := minimizeAux cfg var candidate (n + 1) return ← (nextStep <|> currentStep) if cfg.traceShrink then slimTrace s!"No shrinking possible for {var} := {repr x}" failure /-- Once a property fails to hold on an example, look for smaller counter-examples to show the user. -/ def minimize [SampleableExt α] {β : α → Prop} [∀ x, Testable (β x)] (cfg : Configuration) (var : String) (x : SampleableExt.proxy α) (r : TestResult (β <| SampleableExt.interp x)) : Gen (Σ x, TestResult (β <| SampleableExt.interp x)) := do if cfg.traceShrink then slimTrace "Shrink" slimTrace s!"Attempting to shrink {var} := {repr x}" let res ← OptionT.run <| minimizeAux cfg var x 0 pure <| res.getD ⟨x, r⟩ /-- Test a universal property by creating a sample of the right type and instantiating the bound variable with it. -/ instance varTestable [SampleableExt α] {β : α → Prop} [∀ x, Testable (β x)] : Testable (NamedBinder var <| ∀ x : α, β x) where run := fun cfg min ↦ do let x ← SampleableExt.sample if cfg.traceSuccesses || cfg.traceDiscarded then slimTrace s!"{var} := {repr x}" let r ← Testable.runProp (β <| SampleableExt.interp x) cfg false let ⟨finalX, finalR⟩ ← if isFailure r then if cfg.traceSuccesses then slimTrace s!"{var} := {repr x} is a failure" if min then minimize cfg var x r else pure <| ⟨x, r⟩ else pure <| ⟨x, r⟩ pure <| addVarInfo var finalX (· <| SampleableExt.interp finalX) finalR /-- Test a universal property about propositions -/ instance propVarTestable {β : Prop → Prop} [∀ b : Bool, Testable (β b)] : Testable (NamedBinder var <| ∀ p : Prop, β p) where run := fun cfg min ↦ imp (fun h (b : Bool) ↦ h b) <$> Testable.runProp (NamedBinder var <| ∀ b : Bool, β b) cfg min instance (priority := high) unusedVarTestable {β : Prop} [Nonempty α] [Testable β] : Testable (NamedBinder var (α → β)) where run := fun cfg min ↦ do if cfg.traceDiscarded || cfg.traceSuccesses then slimTrace s!"{var} is unused" let r ← Testable.runProp β cfg min let finalR := addInfo s!"{var} is irrelevant (unused)" id r pure <| imp (· <| Classical.ofNonempty) finalR (PSum.inr <| fun x _ ↦ x) instance (priority := 2000) subtypeVarTestable {p : α → Prop} {β : α → Prop} [∀ x, PrintableProp (p x)] [∀ x, Testable (β x)] [SampleableExt (Subtype p)] {var'} : Testable (NamedBinder var <| Π x : α, NamedBinder var' <| p x → β x) where run cfg min := letI (x : Subtype p) : Testable (β x) := { run := fun cfg min ↦ do let r ← Testable.runProp (β x.val) cfg min pure <| addInfo s!"guard: {printProp (p x)} (by construction)" id r (PSum.inr id) } do let r ← @Testable.run (∀ x : Subtype p, β x.val) (@varTestable var _ _ _ _) cfg min pure <| iff Subtype.forall' r instance (priority := low) decidableTestable {p : Prop} [PrintableProp p] [Decidable p] : Testable p where run := fun _ _ ↦ if h : p then pure <| success (PSum.inr h) else let s := printProp p pure <| failure h [s!"issue: {s} does not hold"] 0 end Testable section PrintableProp variable {α : Type*} {x y : α} instance Eq.printableProp [Repr α] {x y : α} : PrintableProp (x = y) where printProp := s!"{repr x} = {repr y}" instance Ne.printableProp [Repr α] {x y : α} : PrintableProp (x ≠ y) where printProp := s!"{repr x} ≠ {repr y}" instance LE.printableProp [Repr α] [LE α] {x y : α} : PrintableProp (x ≤ y) where printProp := s!"{repr x} ≤ {repr y}" instance LT.printableProp [Repr α] [LT α] {x y : α} : PrintableProp (x < y) where printProp := s!"{repr x} < {repr y}" variable {x y : Prop} instance And.printableProp [PrintableProp x] [PrintableProp y] : PrintableProp (x ∧ y) where printProp := s!"{printProp x} ∧ {printProp y}" instance Or.printableProp [PrintableProp x] [PrintableProp y] : PrintableProp (x ∨ y) where printProp := s!"{printProp x} ∨ {printProp y}" instance Iff.printableProp [PrintableProp x] [PrintableProp y] : PrintableProp (x ↔ y) where printProp := s!"{printProp x} ↔ {printProp y}" instance Imp.printableProp [PrintableProp x] [PrintableProp y] : PrintableProp (x → y) where printProp := s!"{printProp x} → {printProp y}" instance Not.printableProp [PrintableProp x] : PrintableProp (¬x) where printProp := s!"¬{printProp x}" instance True.printableProp : PrintableProp True where printProp := "True" instance False.printableProp : PrintableProp False where printProp := "False" instance Bool.printableProp {b : Bool} : PrintableProp b where printProp := if b then "true" else "false" instance Fact.printableProp [PrintableProp p] : PrintableProp (Fact p) where printProp := printProp p end PrintableProp section IO open TestResult /-- Execute `cmd` and repeat every time the result is `gave_up` (at most `n` times). -/ def retry (cmd : Rand (TestResult p)) : Nat → Rand (TestResult p) | 0 => pure <| TestResult.gaveUp 1 | n+1 => do let r ← cmd match r with | success hp => pure <| success hp | TestResult.failure h xs n => pure <| failure h xs n | gaveUp _ => retry cmd n /-- Count the number of times the test procedure gave up. -/ def giveUp (x : Nat) : TestResult p → TestResult p | success (PSum.inl ()) => gaveUp x | success (PSum.inr p) => success <| (PSum.inr p) | gaveUp n => gaveUp <| n + x | TestResult.failure h xs n => failure h xs n /-- Try `n` times to find a counter-example for `p`. -/ def Testable.runSuiteAux (p : Prop) [Testable p] (cfg : Configuration) : TestResult p → Nat → Rand (TestResult p) | r, 0 => pure r | r, n+1 => do let size := (cfg.numInst - n - 1) * cfg.maxSize / cfg.numInst if cfg.traceSuccesses then slimTrace s!"New sample" slimTrace s!"Retrying up to {cfg.numRetries} times until guards hold" let x ← retry (ReaderT.run (Testable.runProp p cfg true) ⟨size⟩) cfg.numRetries match x with | (success (PSum.inl ())) => runSuiteAux p cfg r n | (gaveUp g) => runSuiteAux p cfg (giveUp g r) n | _ => pure <| x /-- Try to find a counter-example of `p`. -/ def Testable.runSuite (p : Prop) [Testable p] (cfg : Configuration := {}) : Rand (TestResult p) := Testable.runSuiteAux p cfg (success <| PSum.inl ()) cfg.numInst /-- Run a test suite for `p` in `BaseIO` using the global RNG in `stdGenRef`. -/ def Testable.checkIO (p : Prop) [Testable p] (cfg : Configuration := {}) : BaseIO (TestResult p) := letI : MonadLift Id BaseIO := ⟨fun f => pure <| Id.run f⟩ match cfg.randomSeed with | none => IO.runRand (Testable.runSuite p cfg) | some seed => IO.runRandWith seed (Testable.runSuite p cfg) end IO namespace Decorations open Lean /-- Traverse the syntax of a proposition to find universal quantifiers quantifiers and add `NamedBinder` annotations next to them. -/ partial def addDecorations (e : Expr) : MetaM Expr := Meta.transform e fun expr => do if not (← Meta.inferType expr).isProp then return .done expr else if let Expr.forallE name type body data := expr then let newType ← addDecorations type let newBody ← Meta.withLocalDecl name data type fun fvar => do return (← addDecorations (body.instantiate1 fvar)).abstract #[fvar] let rest := Expr.forallE name newType newBody data return .done <| (← Meta.mkAppM `SlimCheck.NamedBinder #[mkStrLit name.toString, rest]) else return .continue /-- `DecorationsOf p` is used as a hint to `mk_decorations` to specify that the goal should be satisfied with a proposition equivalent to `p` with added annotations. -/ @[nolint unusedArguments] abbrev DecorationsOf (_p : Prop) := Prop open Elab.Tactic open Meta /-- In a goal of the shape `⊢ DecorationsOf p`, `mk_decoration` examines the syntax of `p` and adds `NamedBinder` around universal quantifications to improve error messages. This tool can be used in the declaration of a function as follows: ```lean def foo (p : Prop) (p' : Decorations.DecorationsOf p := by mk_decorations) [Testable p'] : ... ``` `p` is the parameter given by the user, `p'` is a definitionally equivalent proposition where the quantifiers are annotated with `NamedBinder`. -/ scoped elab "mk_decorations" : tactic => do let goal ← getMainGoal let goalType ← goal.getType if let .app (.const ``Decorations.DecorationsOf _) body := goalType then closeMainGoal `mk_decorations (← addDecorations body) end Decorations open Decorations in /-- Run a test suite for `p` and throw an exception if `p` does not hold. -/ def Testable.check (p : Prop) (cfg : Configuration := {}) (p' : Decorations.DecorationsOf p := by mk_decorations) [Testable p'] : Lean.CoreM PUnit := do match ← Testable.checkIO p' cfg with | TestResult.success _ => if !cfg.quiet then Lean.logInfo "Success" | TestResult.gaveUp n => if !cfg.quiet then Lean.logWarning s!"Gave up {n} times" | TestResult.failure _ xs n => Lean.throwError <| formatFailure "Found problems!" xs n -- #eval Testable.check (∀ (x y z a : Nat) (h1 : 3 < x) (h2 : 3 < y), x - y = y - x) -- Configuration.verbose -- #eval Testable.check (∀ x : Nat, ∀ y : Nat, x + y = y + x) Configuration.verbose -- #eval Testable.check (∀ (x : (Nat × Nat)), x.fst - x.snd - 10 = x.snd - x.fst - 10) -- Configuration.verbose -- #eval Testable.check (∀ (x : Nat) (h : 10 < x), 5 < x) Configuration.verbose macro tk:"#test " e:term : command => `(command| #eval%$tk Testable.check $e) -- #test ∀ (x : Nat) (h : 5 < x), 10 < x -- #test ∀ (x : Nat) (h : 10 < x), 5 < x end SlimCheck
Topology\AlexandrovDiscrete.lean
/- Copyright (c) 2023 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Data.Set.Image import Mathlib.Topology.Bases import Mathlib.Topology.Inseparable import Mathlib.Topology.Compactness.Compact /-! # Alexandrov-discrete topological spaces This file defines Alexandrov-discrete spaces, aka finitely generated spaces. A space is Alexandrov-discrete if the (arbitrary) intersection of open sets is open. As such, the intersection of all neighborhoods of a set is a neighborhood itself. Hence every set has a minimal neighborhood, which we call the *exterior* of the set. ## Main declarations * `AlexandrovDiscrete`: Prop-valued typeclass for a topological space to be Alexandrov-discrete * `exterior`: Intersection of all neighborhoods of a set. When the space is Alexandrov-discrete, this is the minimal neighborhood of the set. ## Notes The "minimal neighborhood of a set" construction is not named in the literature. We chose the name "exterior" with analogy to the interior. `interior` and `exterior` have the same properties up to ## TODO Finite product of Alexandrov-discrete spaces is Alexandrov-discrete. ## Tags Alexandroff, discrete, finitely generated, fg space -/ open Filter Set TopologicalSpace open scoped Topology /-- A topological space is **Alexandrov-discrete** or **finitely generated** if the intersection of a family of open sets is open. -/ class AlexandrovDiscrete (α : Type*) [TopologicalSpace α] : Prop where /-- The intersection of a family of open sets is an open set. Use `isOpen_sInter` in the root namespace instead. -/ protected isOpen_sInter : ∀ S : Set (Set α), (∀ s ∈ S, IsOpen s) → IsOpen (⋂₀ S) variable {ι : Sort*} {κ : ι → Sort*} {α β : Type*} section variable [TopologicalSpace α] [TopologicalSpace β] instance DiscreteTopology.toAlexandrovDiscrete [DiscreteTopology α] : AlexandrovDiscrete α where isOpen_sInter _ _ := isOpen_discrete _ instance Finite.toAlexandrovDiscrete [Finite α] : AlexandrovDiscrete α where isOpen_sInter S := (toFinite S).isOpen_sInter section AlexandrovDiscrete variable [AlexandrovDiscrete α] {S : Set (Set α)} {f : ι → Set α} lemma isOpen_sInter : (∀ s ∈ S, IsOpen s) → IsOpen (⋂₀ S) := AlexandrovDiscrete.isOpen_sInter _ lemma isOpen_iInter (hf : ∀ i, IsOpen (f i)) : IsOpen (⋂ i, f i) := isOpen_sInter <| forall_mem_range.2 hf lemma isOpen_iInter₂ {f : ∀ i, κ i → Set α} (hf : ∀ i j, IsOpen (f i j)) : IsOpen (⋂ i, ⋂ j, f i j) := isOpen_iInter fun _ ↦ isOpen_iInter <| hf _ lemma isClosed_sUnion (hS : ∀ s ∈ S, IsClosed s) : IsClosed (⋃₀ S) := by simp only [← isOpen_compl_iff, compl_sUnion] at hS ⊢; exact isOpen_sInter <| forall_mem_image.2 hS lemma isClosed_iUnion (hf : ∀ i, IsClosed (f i)) : IsClosed (⋃ i, f i) := isClosed_sUnion <| forall_mem_range.2 hf lemma isClosed_iUnion₂ {f : ∀ i, κ i → Set α} (hf : ∀ i j, IsClosed (f i j)) : IsClosed (⋃ i, ⋃ j, f i j) := isClosed_iUnion fun _ ↦ isClosed_iUnion <| hf _ lemma isClopen_sInter (hS : ∀ s ∈ S, IsClopen s) : IsClopen (⋂₀ S) := ⟨isClosed_sInter fun s hs ↦ (hS s hs).1, isOpen_sInter fun s hs ↦ (hS s hs).2⟩ lemma isClopen_iInter (hf : ∀ i, IsClopen (f i)) : IsClopen (⋂ i, f i) := ⟨isClosed_iInter fun i ↦ (hf i).1, isOpen_iInter fun i ↦ (hf i).2⟩ lemma isClopen_iInter₂ {f : ∀ i, κ i → Set α} (hf : ∀ i j, IsClopen (f i j)) : IsClopen (⋂ i, ⋂ j, f i j) := isClopen_iInter fun _ ↦ isClopen_iInter <| hf _ lemma isClopen_sUnion (hS : ∀ s ∈ S, IsClopen s) : IsClopen (⋃₀ S) := ⟨isClosed_sUnion fun s hs ↦ (hS s hs).1, isOpen_sUnion fun s hs ↦ (hS s hs).2⟩ lemma isClopen_iUnion (hf : ∀ i, IsClopen (f i)) : IsClopen (⋃ i, f i) := ⟨isClosed_iUnion fun i ↦ (hf i).1, isOpen_iUnion fun i ↦ (hf i).2⟩ lemma isClopen_iUnion₂ {f : ∀ i, κ i → Set α} (hf : ∀ i j, IsClopen (f i j)) : IsClopen (⋃ i, ⋃ j, f i j) := isClopen_iUnion fun _ ↦ isClopen_iUnion <| hf _ lemma interior_iInter (f : ι → Set α) : interior (⋂ i, f i) = ⋂ i, interior (f i) := (interior_maximal (iInter_mono fun _ ↦ interior_subset) <| isOpen_iInter fun _ ↦ isOpen_interior).antisymm' <| subset_iInter fun _ ↦ interior_mono <| iInter_subset _ _ lemma interior_sInter (S : Set (Set α)) : interior (⋂₀ S) = ⋂ s ∈ S, interior s := by simp_rw [sInter_eq_biInter, interior_iInter] lemma closure_iUnion (f : ι → Set α) : closure (⋃ i, f i) = ⋃ i, closure (f i) := compl_injective <| by simpa only [← interior_compl, compl_iUnion] using interior_iInter fun i ↦ (f i)ᶜ lemma closure_sUnion (S : Set (Set α)) : closure (⋃₀ S) = ⋃ s ∈ S, closure s := by simp_rw [sUnion_eq_biUnion, closure_iUnion] end AlexandrovDiscrete variable {s t : Set α} {a x y : α} /-- The *exterior* of a set is the intersection of all its neighborhoods. In an Alexandrov-discrete space, this is the smallest neighborhood of the set. Note that this construction is unnamed in the literature. We choose the name in analogy to `interior`. -/ def exterior (s : Set α) : Set α := (𝓝ˢ s).ker lemma exterior_singleton_eq_ker_nhds (a : α) : exterior {a} = (𝓝 a).ker := by simp [exterior] lemma exterior_def (s : Set α) : exterior s = ⋂₀ {t : Set α | IsOpen t ∧ s ⊆ t} := (hasBasis_nhdsSet _).ker.trans sInter_eq_biInter.symm lemma mem_exterior : a ∈ exterior s ↔ ∀ U, IsOpen U → s ⊆ U → a ∈ U := by simp [exterior_def] lemma subset_exterior_iff : s ⊆ exterior t ↔ ∀ U, IsOpen U → t ⊆ U → s ⊆ U := by simp [exterior_def] lemma subset_exterior : s ⊆ exterior s := subset_exterior_iff.2 fun _ _ ↦ id lemma exterior_minimal (h₁ : s ⊆ t) (h₂ : IsOpen t) : exterior s ⊆ t := by rw [exterior_def]; exact sInter_subset_of_mem ⟨h₂, h₁⟩ lemma IsOpen.exterior_eq (h : IsOpen s) : exterior s = s := (exterior_minimal Subset.rfl h).antisymm subset_exterior lemma IsOpen.exterior_subset_iff (ht : IsOpen t) : exterior s ⊆ t ↔ s ⊆ t := ⟨subset_exterior.trans, fun h ↦ exterior_minimal h ht⟩ @[mono] lemma exterior_mono : Monotone (exterior : Set α → Set α) := fun _s _t h ↦ ker_mono <| nhdsSet_mono h @[simp] lemma exterior_empty : exterior (∅ : Set α) = ∅ := isOpen_empty.exterior_eq @[simp] lemma exterior_univ : exterior (univ : Set α) = univ := isOpen_univ.exterior_eq @[simp] lemma exterior_eq_empty : exterior s = ∅ ↔ s = ∅ := ⟨eq_bot_mono subset_exterior, by rintro rfl; exact exterior_empty⟩ lemma Inducing.alexandrovDiscrete [AlexandrovDiscrete α] {f : β → α} (h : Inducing f) : AlexandrovDiscrete β where isOpen_sInter S hS := by simp_rw [h.isOpen_iff] at hS ⊢ choose U hU htU using hS refine ⟨_, isOpen_iInter₂ hU, ?_⟩ simp_rw [preimage_iInter, htU, sInter_eq_biInter] lemma IsOpen.exterior_subset (ht : IsOpen t) : exterior s ⊆ t ↔ s ⊆ t := ⟨subset_exterior.trans, fun h ↦ exterior_minimal h ht⟩ lemma Set.Finite.isCompact_exterior (hs : s.Finite) : IsCompact (exterior s) := by classical refine isCompact_of_finite_subcover fun f hf hsf ↦ ?_ choose g hg using fun a (ha : a ∈ exterior s) ↦ mem_iUnion.1 (hsf ha) refine ⟨hs.toFinset.attach.image fun a ↦ g a.1 <| subset_exterior <| (Finite.mem_toFinset _).1 a.2, (isOpen_iUnion fun i ↦ isOpen_iUnion ?_).exterior_subset.2 ?_⟩ · exact fun _ ↦ hf _ refine fun a ha ↦ mem_iUnion₂.2 ⟨_, ?_, hg _ <| subset_exterior ha⟩ simp only [Finset.mem_image, Finset.mem_attach, true_and, Subtype.exists, Finite.mem_toFinset] exact ⟨a, ha, rfl⟩ end lemma AlexandrovDiscrete.sup {t₁ t₂ : TopologicalSpace α} (_ : @AlexandrovDiscrete α t₁) (_ : @AlexandrovDiscrete α t₂) : @AlexandrovDiscrete α (t₁ ⊔ t₂) := @AlexandrovDiscrete.mk α (t₁ ⊔ t₂) fun _S hS ↦ ⟨@isOpen_sInter _ t₁ _ _ fun _s hs ↦ (hS _ hs).1, isOpen_sInter fun _s hs ↦ (hS _ hs).2⟩ lemma alexandrovDiscrete_iSup {t : ι → TopologicalSpace α} (_ : ∀ i, @AlexandrovDiscrete α (t i)) : @AlexandrovDiscrete α (⨆ i, t i) := @AlexandrovDiscrete.mk α (⨆ i, t i) fun _S hS ↦ isOpen_iSup_iff.2 fun i ↦ @isOpen_sInter _ (t i) _ _ fun _s hs ↦ isOpen_iSup_iff.1 (hS _ hs) _ section variable [TopologicalSpace α] [TopologicalSpace β] [AlexandrovDiscrete α] [AlexandrovDiscrete β] {s t : Set α} {a x y : α} @[simp] lemma isOpen_exterior : IsOpen (exterior s) := by rw [exterior_def]; exact isOpen_sInter fun _ ↦ And.left lemma exterior_mem_nhdsSet : exterior s ∈ 𝓝ˢ s := isOpen_exterior.mem_nhdsSet.2 subset_exterior @[simp] lemma exterior_eq_iff_isOpen : exterior s = s ↔ IsOpen s := ⟨fun h ↦ h ▸ isOpen_exterior, IsOpen.exterior_eq⟩ @[simp] lemma exterior_subset_iff_isOpen : exterior s ⊆ s ↔ IsOpen s := by simp only [exterior_eq_iff_isOpen.symm, Subset.antisymm_iff, subset_exterior, and_true] lemma exterior_subset_iff : exterior s ⊆ t ↔ ∃ U, IsOpen U ∧ s ⊆ U ∧ U ⊆ t := ⟨fun h ↦ ⟨exterior s, isOpen_exterior, subset_exterior, h⟩, fun ⟨_U, hU, hsU, hUt⟩ ↦ (exterior_minimal hsU hU).trans hUt⟩ lemma exterior_subset_iff_mem_nhdsSet : exterior s ⊆ t ↔ t ∈ 𝓝ˢ s := exterior_subset_iff.trans mem_nhdsSet_iff_exists.symm lemma exterior_singleton_subset_iff_mem_nhds : exterior {a} ⊆ t ↔ t ∈ 𝓝 a := by simp [exterior_subset_iff_mem_nhdsSet] lemma gc_exterior_interior : GaloisConnection (exterior : Set α → Set α) interior := fun s t ↦ by simp [exterior_subset_iff, subset_interior_iff] @[simp] lemma exterior_exterior (s : Set α) : exterior (exterior s) = exterior s := isOpen_exterior.exterior_eq @[simp] lemma exterior_union (s t : Set α) : exterior (s ∪ t) = exterior s ∪ exterior t := gc_exterior_interior.l_sup @[simp] lemma nhdsSet_exterior (s : Set α) : 𝓝ˢ (exterior s) = 𝓝ˢ s := by ext t; simp_rw [← exterior_subset_iff_mem_nhdsSet, exterior_exterior] @[simp] lemma principal_exterior (s : Set α) : 𝓟 (exterior s) = 𝓝ˢ s := by rw [← nhdsSet_exterior, isOpen_exterior.nhdsSet_eq] @[simp] lemma exterior_subset_exterior : exterior s ⊆ exterior t ↔ 𝓝ˢ s ≤ 𝓝ˢ t := by refine ⟨?_, fun h ↦ ker_mono h⟩ simp_rw [le_def, ← exterior_subset_iff_mem_nhdsSet] exact fun h u ↦ h.trans lemma specializes_iff_exterior_subset : x ⤳ y ↔ exterior {x} ⊆ exterior {y} := by simp [Specializes] lemma isOpen_iff_forall_specializes : IsOpen s ↔ ∀ x y, x ⤳ y → y ∈ s → x ∈ s := by refine ⟨fun hs x y hxy ↦ hxy.mem_open hs, fun hs ↦ ?_⟩ simp_rw [specializes_iff_exterior_subset] at hs simp_rw [isOpen_iff_mem_nhds, mem_nhds_iff] rintro a ha refine ⟨_, fun b hb ↦ hs _ _ ?_ ha, isOpen_exterior, subset_exterior <| mem_singleton _⟩ rwa [isOpen_exterior.exterior_subset, singleton_subset_iff] lemma alexandrovDiscrete_coinduced {β : Type*} {f : α → β} : @AlexandrovDiscrete β (coinduced f ‹_›) := @AlexandrovDiscrete.mk β (coinduced f ‹_›) fun S hS ↦ by rw [isOpen_coinduced, preimage_sInter]; exact isOpen_iInter₂ hS instance AlexandrovDiscrete.toFirstCountable : FirstCountableTopology α where nhds_generated_countable a := ⟨{exterior {a}}, countable_singleton _, by simp⟩ instance AlexandrovDiscrete.toLocallyCompactSpace : LocallyCompactSpace α where local_compact_nhds a _U hU := ⟨exterior {a}, isOpen_exterior.mem_nhds <| subset_exterior <| mem_singleton _, exterior_singleton_subset_iff_mem_nhds.2 hU, (finite_singleton _).isCompact_exterior⟩ instance Subtype.instAlexandrovDiscrete {p : α → Prop} : AlexandrovDiscrete {a // p a} := inducing_subtype_val.alexandrovDiscrete instance Quotient.instAlexandrovDiscrete {s : Setoid α} : AlexandrovDiscrete (Quotient s) := alexandrovDiscrete_coinduced instance Sum.instAlexandrovDiscrete : AlexandrovDiscrete (α ⊕ β) := alexandrovDiscrete_coinduced.sup alexandrovDiscrete_coinduced instance Sigma.instAlexandrovDiscrete {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] [∀ i, AlexandrovDiscrete (π i)] : AlexandrovDiscrete (Σ i, π i) := alexandrovDiscrete_iSup fun _ ↦ alexandrovDiscrete_coinduced end
Topology\Bases.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Data.Set.Constructions import Mathlib.Topology.Constructions import Mathlib.Topology.ContinuousOn /-! # Bases of topologies. Countability axioms. A topological basis on a topological space `t` is a collection of sets, such that all open sets can be generated as unions of these sets, without the need to take finite intersections of them. This file introduces a framework for dealing with these collections, and also what more we can say under certain countability conditions on bases, which are referred to as first- and second-countable. We also briefly cover the theory of separable spaces, which are those with a countable, dense subset. If a space is second-countable, and also has a countably generated uniformity filter (for example, if `t` is a metric space), it will automatically be separable (and indeed, these conditions are equivalent in this case). ## Main definitions * `TopologicalSpace.IsTopologicalBasis s`: The topological space `t` has basis `s`. * `TopologicalSpace.SeparableSpace α`: The topological space `t` has a countable, dense subset. * `TopologicalSpace.IsSeparable s`: The set `s` is contained in the closure of a countable set. * `FirstCountableTopology α`: A topology in which `𝓝 x` is countably generated for every `x`. * `SecondCountableTopology α`: A topology which has a topological basis which is countable. ## Main results * `TopologicalSpace.FirstCountableTopology.tendsto_subseq`: In a first-countable space, cluster points are limits of subsequences. * `TopologicalSpace.SecondCountableTopology.isOpen_iUnion_countable`: In a second-countable space, the union of arbitrarily-many open sets is equal to a sub-union of only countably many of these sets. * `TopologicalSpace.SecondCountableTopology.countable_cover_nhds`: Consider `f : α → Set α` with the property that `f x ∈ 𝓝 x` for all `x`. Then there is some countable set `s` whose image covers the space. ## Implementation Notes For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. ## TODO More fine grained instances for `FirstCountableTopology`, `TopologicalSpace.SeparableSpace`, and more. -/ open Set Filter Function Topology noncomputable section namespace TopologicalSpace universe u variable {α : Type u} {β : Type*} [t : TopologicalSpace α] {B : Set (Set α)} {s : Set α} /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ structure IsTopologicalBasis (s : Set (Set α)) : Prop where /-- For every point `x`, the set of `t ∈ s` such that `x ∈ t` is directed downwards. -/ exists_subset_inter : ∀ t₁ ∈ s, ∀ t₂ ∈ s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃ ∈ s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂ /-- The sets from `s` cover the whole space. -/ sUnion_eq : ⋃₀ s = univ /-- The topology is generated by sets from `s`. -/ eq_generateFrom : t = generateFrom s theorem IsTopologicalBasis.insert_empty {s : Set (Set α)} (h : IsTopologicalBasis s) : IsTopologicalBasis (insert ∅ s) := by refine ⟨?_, by rw [sUnion_insert, empty_union, h.sUnion_eq], ?_⟩ · rintro t₁ (rfl | h₁) t₂ (rfl | h₂) x ⟨hx₁, hx₂⟩ · cases hx₁ · cases hx₁ · cases hx₂ · obtain ⟨t₃, h₃, hs⟩ := h.exists_subset_inter _ h₁ _ h₂ x ⟨hx₁, hx₂⟩ exact ⟨t₃, .inr h₃, hs⟩ · rw [h.eq_generateFrom] refine le_antisymm (le_generateFrom fun t => ?_) (generateFrom_anti <| subset_insert ∅ s) rintro (rfl | ht) · exact @isOpen_empty _ (generateFrom s) · exact .basic t ht theorem IsTopologicalBasis.diff_empty {s : Set (Set α)} (h : IsTopologicalBasis s) : IsTopologicalBasis (s \ {∅}) := by refine ⟨?_, by rw [sUnion_diff_singleton_empty, h.sUnion_eq], ?_⟩ · rintro t₁ ⟨h₁, -⟩ t₂ ⟨h₂, -⟩ x hx obtain ⟨t₃, h₃, hs⟩ := h.exists_subset_inter _ h₁ _ h₂ x hx exact ⟨t₃, ⟨h₃, Nonempty.ne_empty ⟨x, hs.1⟩⟩, hs⟩ · rw [h.eq_generateFrom] refine le_antisymm (generateFrom_anti diff_subset) (le_generateFrom fun t ht => ?_) obtain rfl | he := eq_or_ne t ∅ · exact @isOpen_empty _ (generateFrom _) · exact .basic t ⟨ht, he⟩ /-- If a family of sets `s` generates the topology, then intersections of finite subcollections of `s` form a topological basis. -/ theorem isTopologicalBasis_of_subbasis {s : Set (Set α)} (hs : t = generateFrom s) : IsTopologicalBasis ((fun f => ⋂₀ f) '' { f : Set (Set α) | f.Finite ∧ f ⊆ s }) := by subst t; letI := generateFrom s refine ⟨?_, ?_, le_antisymm (le_generateFrom ?_) <| generateFrom_anti fun t ht => ?_⟩ · rintro _ ⟨t₁, ⟨hft₁, ht₁b⟩, rfl⟩ _ ⟨t₂, ⟨hft₂, ht₂b⟩, rfl⟩ x h exact ⟨_, ⟨_, ⟨hft₁.union hft₂, union_subset ht₁b ht₂b⟩, sInter_union t₁ t₂⟩, h, Subset.rfl⟩ · rw [sUnion_image, iUnion₂_eq_univ_iff] exact fun x => ⟨∅, ⟨finite_empty, empty_subset _⟩, sInter_empty.substr <| mem_univ x⟩ · rintro _ ⟨t, ⟨hft, htb⟩, rfl⟩ exact hft.isOpen_sInter fun s hs ↦ GenerateOpen.basic _ <| htb hs · rw [← sInter_singleton t] exact ⟨{t}, ⟨finite_singleton t, singleton_subset_iff.2 ht⟩, rfl⟩ theorem isTopologicalBasis_of_subbasis_of_finiteInter {s : Set (Set α)} (hsg : t = generateFrom s) (hsi : FiniteInter s) : IsTopologicalBasis s := by convert isTopologicalBasis_of_subbasis hsg refine le_antisymm (fun t ht ↦ ⟨{t}, by simpa using ht⟩) ?_ rintro _ ⟨g, ⟨hg, hgs⟩, rfl⟩ lift g to Finset (Set α) using hg exact hsi.finiteInter_mem g hgs theorem isTopologicalBasis_of_subbasis_of_inter {r : Set (Set α)} (hsg : t = generateFrom r) (hsi : ∀ ⦃s⦄, s ∈ r → ∀ ⦃t⦄, t ∈ r → s ∩ t ∈ r) : IsTopologicalBasis (insert univ r) := isTopologicalBasis_of_subbasis_of_finiteInter (by simpa using hsg) (FiniteInter.mk₂ hsi) theorem IsTopologicalBasis.of_hasBasis_nhds {s : Set (Set α)} (h_nhds : ∀ a, (𝓝 a).HasBasis (fun t ↦ t ∈ s ∧ a ∈ t) id) : IsTopologicalBasis s where exists_subset_inter t₁ ht₁ t₂ ht₂ x hx := by simpa only [and_assoc, (h_nhds x).mem_iff] using (inter_mem ((h_nhds _).mem_of_mem ⟨ht₁, hx.1⟩) ((h_nhds _).mem_of_mem ⟨ht₂, hx.2⟩)) sUnion_eq := sUnion_eq_univ_iff.2 fun x ↦ (h_nhds x).ex_mem eq_generateFrom := ext_nhds fun x ↦ by simpa only [nhds_generateFrom, and_comm] using (h_nhds x).eq_biInf /-- If a family of open sets `s` is such that every open neighbourhood contains some member of `s`, then `s` is a topological basis. -/ theorem isTopologicalBasis_of_isOpen_of_nhds {s : Set (Set α)} (h_open : ∀ u ∈ s, IsOpen u) (h_nhds : ∀ (a : α) (u : Set α), a ∈ u → IsOpen u → ∃ v ∈ s, a ∈ v ∧ v ⊆ u) : IsTopologicalBasis s := .of_hasBasis_nhds <| fun a ↦ (nhds_basis_opens a).to_hasBasis' (by simpa [and_assoc] using h_nhds a) fun t ⟨hts, hat⟩ ↦ (h_open _ hts).mem_nhds hat /-- A set `s` is in the neighbourhood of `a` iff there is some basis set `t`, which contains `a` and is itself contained in `s`. -/ theorem IsTopologicalBasis.mem_nhds_iff {a : α} {s : Set α} {b : Set (Set α)} (hb : IsTopologicalBasis b) : s ∈ 𝓝 a ↔ ∃ t ∈ b, a ∈ t ∧ t ⊆ s := by change s ∈ (𝓝 a).sets ↔ ∃ t ∈ b, a ∈ t ∧ t ⊆ s rw [hb.eq_generateFrom, nhds_generateFrom, biInf_sets_eq] · simp [and_assoc, and_left_comm] · rintro s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩ let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ ⟨hs₁, ht₁⟩ exact ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (hu₃.trans inter_subset_left), le_principal_iff.2 (hu₃.trans inter_subset_right)⟩ · rcases eq_univ_iff_forall.1 hb.sUnion_eq a with ⟨i, h1, h2⟩ exact ⟨i, h2, h1⟩ theorem IsTopologicalBasis.isOpen_iff {s : Set α} {b : Set (Set α)} (hb : IsTopologicalBasis b) : IsOpen s ↔ ∀ a ∈ s, ∃ t ∈ b, a ∈ t ∧ t ⊆ s := by simp [isOpen_iff_mem_nhds, hb.mem_nhds_iff] theorem IsTopologicalBasis.nhds_hasBasis {b : Set (Set α)} (hb : IsTopologicalBasis b) {a : α} : (𝓝 a).HasBasis (fun t : Set α => t ∈ b ∧ a ∈ t) fun t => t := ⟨fun s => hb.mem_nhds_iff.trans <| by simp only [and_assoc]⟩ protected theorem IsTopologicalBasis.isOpen {s : Set α} {b : Set (Set α)} (hb : IsTopologicalBasis b) (hs : s ∈ b) : IsOpen s := by rw [hb.eq_generateFrom] exact .basic s hs protected theorem IsTopologicalBasis.mem_nhds {a : α} {s : Set α} {b : Set (Set α)} (hb : IsTopologicalBasis b) (hs : s ∈ b) (ha : a ∈ s) : s ∈ 𝓝 a := (hb.isOpen hs).mem_nhds ha theorem IsTopologicalBasis.exists_subset_of_mem_open {b : Set (Set α)} (hb : IsTopologicalBasis b) {a : α} {u : Set α} (au : a ∈ u) (ou : IsOpen u) : ∃ v ∈ b, a ∈ v ∧ v ⊆ u := hb.mem_nhds_iff.1 <| IsOpen.mem_nhds ou au /-- Any open set is the union of the basis sets contained in it. -/ theorem IsTopologicalBasis.open_eq_sUnion' {B : Set (Set α)} (hB : IsTopologicalBasis B) {u : Set α} (ou : IsOpen u) : u = ⋃₀ { s ∈ B | s ⊆ u } := ext fun _a => ⟨fun ha => let ⟨b, hb, ab, bu⟩ := hB.exists_subset_of_mem_open ha ou ⟨b, ⟨hb, bu⟩, ab⟩, fun ⟨_b, ⟨_, bu⟩, ab⟩ => bu ab⟩ theorem IsTopologicalBasis.open_eq_sUnion {B : Set (Set α)} (hB : IsTopologicalBasis B) {u : Set α} (ou : IsOpen u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{ s ∈ B | s ⊆ u }, fun _ h => h.1, hB.open_eq_sUnion' ou⟩ theorem IsTopologicalBasis.open_iff_eq_sUnion {B : Set (Set α)} (hB : IsTopologicalBasis B) {u : Set α} : IsOpen u ↔ ∃ S ⊆ B, u = ⋃₀ S := ⟨hB.open_eq_sUnion, fun ⟨_S, hSB, hu⟩ => hu.symm ▸ isOpen_sUnion fun _s hs => hB.isOpen (hSB hs)⟩ theorem IsTopologicalBasis.open_eq_iUnion {B : Set (Set α)} (hB : IsTopologicalBasis B) {u : Set α} (ou : IsOpen u) : ∃ (β : Type u) (f : β → Set α), (u = ⋃ i, f i) ∧ ∀ i, f i ∈ B := ⟨↥({ s ∈ B | s ⊆ u }), (↑), by rw [← sUnion_eq_iUnion] apply hB.open_eq_sUnion' ou, fun s => And.left s.2⟩ lemma IsTopologicalBasis.subset_of_forall_subset {t : Set α} (hB : IsTopologicalBasis B) (hs : IsOpen s) (h : ∀ U ∈ B, U ⊆ s → U ⊆ t) : s ⊆ t := by rw [hB.open_eq_sUnion' hs]; simpa [sUnion_subset_iff] lemma IsTopologicalBasis.eq_of_forall_subset_iff {t : Set α} (hB : IsTopologicalBasis B) (hs : IsOpen s) (ht : IsOpen t) (h : ∀ U ∈ B, U ⊆ s ↔ U ⊆ t) : s = t := by rw [hB.open_eq_sUnion' hs, hB.open_eq_sUnion' ht] exact congr_arg _ (Set.ext fun U ↦ and_congr_right <| h _) /-- A point `a` is in the closure of `s` iff all basis sets containing `a` intersect `s`. -/ theorem IsTopologicalBasis.mem_closure_iff {b : Set (Set α)} (hb : IsTopologicalBasis b) {s : Set α} {a : α} : a ∈ closure s ↔ ∀ o ∈ b, a ∈ o → (o ∩ s).Nonempty := (mem_closure_iff_nhds_basis' hb.nhds_hasBasis).trans <| by simp only [and_imp] /-- A set is dense iff it has non-trivial intersection with all basis sets. -/ theorem IsTopologicalBasis.dense_iff {b : Set (Set α)} (hb : IsTopologicalBasis b) {s : Set α} : Dense s ↔ ∀ o ∈ b, Set.Nonempty o → (o ∩ s).Nonempty := by simp only [Dense, hb.mem_closure_iff] exact ⟨fun h o hb ⟨a, ha⟩ => h a o hb ha, fun h a o hb ha => h o hb ⟨a, ha⟩⟩ theorem IsTopologicalBasis.isOpenMap_iff {β} [TopologicalSpace β] {B : Set (Set α)} (hB : IsTopologicalBasis B) {f : α → β} : IsOpenMap f ↔ ∀ s ∈ B, IsOpen (f '' s) := by refine ⟨fun H o ho => H _ (hB.isOpen ho), fun hf o ho => ?_⟩ rw [hB.open_eq_sUnion' ho, sUnion_eq_iUnion, image_iUnion] exact isOpen_iUnion fun s => hf s s.2.1 theorem IsTopologicalBasis.exists_nonempty_subset {B : Set (Set α)} (hb : IsTopologicalBasis B) {u : Set α} (hu : u.Nonempty) (ou : IsOpen u) : ∃ v ∈ B, Set.Nonempty v ∧ v ⊆ u := let ⟨x, hx⟩ := hu let ⟨v, vB, xv, vu⟩ := hb.exists_subset_of_mem_open hx ou ⟨v, vB, ⟨x, xv⟩, vu⟩ theorem isTopologicalBasis_opens : IsTopologicalBasis { U : Set α | IsOpen U } := isTopologicalBasis_of_isOpen_of_nhds (by tauto) (by tauto) protected theorem IsTopologicalBasis.inducing {β} [TopologicalSpace β] {f : α → β} {T : Set (Set β)} (hf : Inducing f) (h : IsTopologicalBasis T) : IsTopologicalBasis ((preimage f) '' T) := .of_hasBasis_nhds fun a ↦ by convert (hf.basis_nhds (h.nhds_hasBasis (a := f a))).to_image_id with s aesop protected theorem IsTopologicalBasis.induced {α} [s : TopologicalSpace β] (f : α → β) {T : Set (Set β)} (h : IsTopologicalBasis T) : IsTopologicalBasis (t := induced f s) ((preimage f) '' T) := h.inducing (t := induced f s) (inducing_induced f) protected theorem IsTopologicalBasis.inf {t₁ t₂ : TopologicalSpace β} {B₁ B₂ : Set (Set β)} (h₁ : IsTopologicalBasis (t := t₁) B₁) (h₂ : IsTopologicalBasis (t := t₂) B₂) : IsTopologicalBasis (t := t₁ ⊓ t₂) (image2 (· ∩ ·) B₁ B₂) := by refine .of_hasBasis_nhds (t := ?_) fun a ↦ ?_ rw [nhds_inf (t₁ := t₁)] convert ((h₁.nhds_hasBasis (t := t₁)).inf (h₂.nhds_hasBasis (t := t₂))).to_image_id aesop theorem IsTopologicalBasis.inf_induced {γ} [s : TopologicalSpace β] {B₁ : Set (Set α)} {B₂ : Set (Set β)} (h₁ : IsTopologicalBasis B₁) (h₂ : IsTopologicalBasis B₂) (f₁ : γ → α) (f₂ : γ → β) : IsTopologicalBasis (t := induced f₁ t ⊓ induced f₂ s) (image2 (f₁ ⁻¹' · ∩ f₂ ⁻¹' ·) B₁ B₂) := by simpa only [image2_image_left, image2_image_right] using (h₁.induced f₁).inf (h₂.induced f₂) protected theorem IsTopologicalBasis.prod {β} [TopologicalSpace β] {B₁ : Set (Set α)} {B₂ : Set (Set β)} (h₁ : IsTopologicalBasis B₁) (h₂ : IsTopologicalBasis B₂) : IsTopologicalBasis (image2 (· ×ˢ ·) B₁ B₂) := h₁.inf_induced h₂ Prod.fst Prod.snd theorem isTopologicalBasis_of_cover {ι} {U : ι → Set α} (Uo : ∀ i, IsOpen (U i)) (Uc : ⋃ i, U i = univ) {b : ∀ i, Set (Set (U i))} (hb : ∀ i, IsTopologicalBasis (b i)) : IsTopologicalBasis (⋃ i : ι, image ((↑) : U i → α) '' b i) := by refine isTopologicalBasis_of_isOpen_of_nhds (fun u hu => ?_) ?_ · simp only [mem_iUnion, mem_image] at hu rcases hu with ⟨i, s, sb, rfl⟩ exact (Uo i).isOpenMap_subtype_val _ ((hb i).isOpen sb) · intro a u ha uo rcases iUnion_eq_univ_iff.1 Uc a with ⟨i, hi⟩ lift a to ↥(U i) using hi rcases (hb i).exists_subset_of_mem_open ha (uo.preimage continuous_subtype_val) with ⟨v, hvb, hav, hvu⟩ exact ⟨(↑) '' v, mem_iUnion.2 ⟨i, mem_image_of_mem _ hvb⟩, mem_image_of_mem _ hav, image_subset_iff.2 hvu⟩ protected theorem IsTopologicalBasis.continuous_iff {β : Type*} [TopologicalSpace β] {B : Set (Set β)} (hB : IsTopologicalBasis B) {f : α → β} : Continuous f ↔ ∀ s ∈ B, IsOpen (f ⁻¹' s) := by rw [hB.eq_generateFrom, continuous_generateFrom_iff] @[deprecated (since := "2023-12-24")] protected theorem IsTopologicalBasis.continuous {β : Type*} [TopologicalSpace β] {B : Set (Set β)} (hB : IsTopologicalBasis B) (f : α → β) (hf : ∀ s ∈ B, IsOpen (f ⁻¹' s)) : Continuous f := hB.continuous_iff.2 hf variable (α) /-- A separable space is one with a countable dense subset, available through `TopologicalSpace.exists_countable_dense`. If `α` is also known to be nonempty, then `TopologicalSpace.denseSeq` provides a sequence `ℕ → α` with dense range, see `TopologicalSpace.denseRange_denseSeq`. If `α` is a uniform space with countably generated uniformity filter (e.g., an `EMetricSpace`), then this condition is equivalent to `SecondCountableTopology α`. In this case the latter should be used as a typeclass argument in theorems because Lean can automatically deduce `TopologicalSpace.SeparableSpace` from `SecondCountableTopology` but it can't deduce `SecondCountableTopology` from `TopologicalSpace.SeparableSpace`. Porting note (#11215): TODO: the previous paragraph describes the state of the art in Lean 3. We can have instance cycles in Lean 4 but we might want to postpone adding them till after the port. -/ @[mk_iff] class SeparableSpace : Prop where /-- There exists a countable dense set. -/ exists_countable_dense : ∃ s : Set α, s.Countable ∧ Dense s theorem exists_countable_dense [SeparableSpace α] : ∃ s : Set α, s.Countable ∧ Dense s := SeparableSpace.exists_countable_dense /-- A nonempty separable space admits a sequence with dense range. Instead of running `cases` on the conclusion of this lemma, you might want to use `TopologicalSpace.denseSeq` and `TopologicalSpace.denseRange_denseSeq`. If `α` might be empty, then `TopologicalSpace.exists_countable_dense` is the main way to use separability of `α`. -/ theorem exists_dense_seq [SeparableSpace α] [Nonempty α] : ∃ u : ℕ → α, DenseRange u := by obtain ⟨s : Set α, hs, s_dense⟩ := exists_countable_dense α cases' Set.countable_iff_exists_subset_range.mp hs with u hu exact ⟨u, s_dense.mono hu⟩ /-- A dense sequence in a non-empty separable topological space. If `α` might be empty, then `TopologicalSpace.exists_countable_dense` is the main way to use separability of `α`. -/ def denseSeq [SeparableSpace α] [Nonempty α] : ℕ → α := Classical.choose (exists_dense_seq α) /-- The sequence `TopologicalSpace.denseSeq α` has dense range. -/ @[simp] theorem denseRange_denseSeq [SeparableSpace α] [Nonempty α] : DenseRange (denseSeq α) := Classical.choose_spec (exists_dense_seq α) variable {α} instance (priority := 100) Countable.to_separableSpace [Countable α] : SeparableSpace α where exists_countable_dense := ⟨Set.univ, Set.countable_univ, dense_univ⟩ /-- If `f` has a dense range and its domain is countable, then its codomain is a separable space. See also `DenseRange.separableSpace`. -/ theorem SeparableSpace.of_denseRange {ι : Sort _} [Countable ι] (u : ι → α) (hu : DenseRange u) : SeparableSpace α := ⟨⟨range u, countable_range u, hu⟩⟩ alias _root_.DenseRange.separableSpace' := SeparableSpace.of_denseRange /-- If `α` is a separable space and `f : α → β` is a continuous map with dense range, then `β` is a separable space as well. E.g., the completion of a separable uniform space is separable. -/ protected theorem _root_.DenseRange.separableSpace [SeparableSpace α] [TopologicalSpace β] {f : α → β} (h : DenseRange f) (h' : Continuous f) : SeparableSpace β := let ⟨s, s_cnt, s_dense⟩ := exists_countable_dense α ⟨⟨f '' s, Countable.image s_cnt f, h.dense_image h' s_dense⟩⟩ theorem _root_.QuotientMap.separableSpace [SeparableSpace α] [TopologicalSpace β] {f : α → β} (hf : QuotientMap f) : SeparableSpace β := hf.surjective.denseRange.separableSpace hf.continuous /-- The product of two separable spaces is a separable space. -/ instance [TopologicalSpace β] [SeparableSpace α] [SeparableSpace β] : SeparableSpace (α × β) := by rcases exists_countable_dense α with ⟨s, hsc, hsd⟩ rcases exists_countable_dense β with ⟨t, htc, htd⟩ exact ⟨⟨s ×ˢ t, hsc.prod htc, hsd.prod htd⟩⟩ /-- The product of a countable family of separable spaces is a separable space. -/ instance {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, SeparableSpace (X i)] [Countable ι] : SeparableSpace (∀ i, X i) := by choose t htc htd using (exists_countable_dense <| X ·) haveI := fun i ↦ (htc i).to_subtype nontriviality ∀ i, X i; inhabit ∀ i, X i classical set f : (Σ I : Finset ι, ∀ i : I, t i) → ∀ i, X i := fun ⟨I, g⟩ i ↦ if hi : i ∈ I then g ⟨i, hi⟩ else (default : ∀ i, X i) i refine ⟨⟨range f, countable_range f, dense_iff_inter_open.2 fun U hU ⟨g, hg⟩ ↦ ?_⟩⟩ rcases isOpen_pi_iff.1 hU g hg with ⟨I, u, huo, huU⟩ have : ∀ i : I, ∃ y ∈ t i, y ∈ u i := fun i ↦ (htd i).exists_mem_open (huo i i.2).1 ⟨_, (huo i i.2).2⟩ choose y hyt hyu using this lift y to ∀ i : I, t i using hyt refine ⟨f ⟨I, y⟩, huU fun i (hi : i ∈ I) ↦ ?_, mem_range_self _⟩ simp only [f, dif_pos hi] exact hyu _ instance [SeparableSpace α] {r : α → α → Prop} : SeparableSpace (Quot r) := quotientMap_quot_mk.separableSpace instance [SeparableSpace α] {s : Setoid α} : SeparableSpace (Quotient s) := quotientMap_quot_mk.separableSpace /-- A topological space with discrete topology is separable iff it is countable. -/ theorem separableSpace_iff_countable [DiscreteTopology α] : SeparableSpace α ↔ Countable α := by simp [separableSpace_iff, countable_univ_iff] /-- In a separable space, a family of nonempty disjoint open sets is countable. -/ theorem _root_.Pairwise.countable_of_isOpen_disjoint [SeparableSpace α] {ι : Type*} {s : ι → Set α} (hd : Pairwise (Disjoint on s)) (ho : ∀ i, IsOpen (s i)) (hne : ∀ i, (s i).Nonempty) : Countable ι := by rcases exists_countable_dense α with ⟨u, u_countable, u_dense⟩ choose f hfu hfs using fun i ↦ u_dense.exists_mem_open (ho i) (hne i) have f_inj : Injective f := fun i j hij ↦ hd.eq <| not_disjoint_iff.2 ⟨f i, hfs i, hij.symm ▸ hfs j⟩ have := u_countable.to_subtype exact (f_inj.codRestrict hfu).countable /-- In a separable space, a family of nonempty disjoint open sets is countable. -/ theorem _root_.Set.PairwiseDisjoint.countable_of_isOpen [SeparableSpace α] {ι : Type*} {s : ι → Set α} {a : Set ι} (h : a.PairwiseDisjoint s) (ho : ∀ i ∈ a, IsOpen (s i)) (hne : ∀ i ∈ a, (s i).Nonempty) : a.Countable := (h.subtype _ _).countable_of_isOpen_disjoint (Subtype.forall.2 ho) (Subtype.forall.2 hne) /-- In a separable space, a family of disjoint sets with nonempty interiors is countable. -/ theorem _root_.Set.PairwiseDisjoint.countable_of_nonempty_interior [SeparableSpace α] {ι : Type*} {s : ι → Set α} {a : Set ι} (h : a.PairwiseDisjoint s) (ha : ∀ i ∈ a, (interior (s i)).Nonempty) : a.Countable := (h.mono fun _ => interior_subset).countable_of_isOpen (fun _ _ => isOpen_interior) ha /-- A set `s` in a topological space is separable if it is contained in the closure of a countable set `c`. Beware that this definition does not require that `c` is contained in `s` (to express the latter, use `TopologicalSpace.SeparableSpace s` or `TopologicalSpace.IsSeparable (univ : Set s))`. In metric spaces, the two definitions are equivalent, see `TopologicalSpace.IsSeparable.separableSpace`. -/ def IsSeparable (s : Set α) := ∃ c : Set α, c.Countable ∧ s ⊆ closure c theorem IsSeparable.mono {s u : Set α} (hs : IsSeparable s) (hu : u ⊆ s) : IsSeparable u := by rcases hs with ⟨c, c_count, hs⟩ exact ⟨c, c_count, hu.trans hs⟩ theorem IsSeparable.iUnion {ι : Sort*} [Countable ι] {s : ι → Set α} (hs : ∀ i, IsSeparable (s i)) : IsSeparable (⋃ i, s i) := by choose c hc h'c using hs refine ⟨⋃ i, c i, countable_iUnion hc, iUnion_subset_iff.2 fun i => ?_⟩ exact (h'c i).trans (closure_mono (subset_iUnion _ i)) @[simp] theorem isSeparable_iUnion {ι : Sort*} [Countable ι] {s : ι → Set α} : IsSeparable (⋃ i, s i) ↔ ∀ i, IsSeparable (s i) := ⟨fun h i ↦ h.mono <| subset_iUnion s i, .iUnion⟩ @[simp] theorem isSeparable_union {s t : Set α} : IsSeparable (s ∪ t) ↔ IsSeparable s ∧ IsSeparable t := by simp [union_eq_iUnion, and_comm] theorem IsSeparable.union {s u : Set α} (hs : IsSeparable s) (hu : IsSeparable u) : IsSeparable (s ∪ u) := isSeparable_union.2 ⟨hs, hu⟩ @[simp] theorem isSeparable_closure : IsSeparable (closure s) ↔ IsSeparable s := by simp only [IsSeparable, isClosed_closure.closure_subset_iff] protected alias ⟨_, IsSeparable.closure⟩ := isSeparable_closure theorem _root_.Set.Countable.isSeparable {s : Set α} (hs : s.Countable) : IsSeparable s := ⟨s, hs, subset_closure⟩ theorem _root_.Set.Finite.isSeparable {s : Set α} (hs : s.Finite) : IsSeparable s := hs.countable.isSeparable theorem IsSeparable.univ_pi {ι : Type*} [Countable ι] {X : ι → Type*} {s : ∀ i, Set (X i)} [∀ i, TopologicalSpace (X i)] (h : ∀ i, IsSeparable (s i)) : IsSeparable (univ.pi s) := by classical rcases eq_empty_or_nonempty (univ.pi s) with he | ⟨f₀, -⟩ · rw [he] exact countable_empty.isSeparable · choose c c_count hc using h haveI := fun i ↦ (c_count i).to_subtype set g : (I : Finset ι) × ((i : I) → c i) → (i : ι) → X i := fun ⟨I, f⟩ i ↦ if hi : i ∈ I then f ⟨i, hi⟩ else f₀ i refine ⟨range g, countable_range g, fun f hf ↦ mem_closure_iff.2 fun o ho hfo ↦ ?_⟩ rcases isOpen_pi_iff.1 ho f hfo with ⟨I, u, huo, hI⟩ rsuffices ⟨f, hf⟩ : ∃ f : (i : I) → c i, g ⟨I, f⟩ ∈ Set.pi I u · exact ⟨g ⟨I, f⟩, hI hf, mem_range_self _⟩ suffices H : ∀ i ∈ I, (u i ∩ c i).Nonempty by choose f hfu hfc using H refine ⟨fun i ↦ ⟨f i i.2, hfc i i.2⟩, fun i (hi : i ∈ I) ↦ ?_⟩ simpa only [g, dif_pos hi] using hfu i hi intro i hi exact mem_closure_iff.1 (hc i <| hf _ trivial) _ (huo i hi).1 (huo i hi).2 lemma isSeparable_pi {ι : Type*} [Countable ι] {α : ι → Type*} {s : ∀ i, Set (α i)} [∀ i, TopologicalSpace (α i)] (h : ∀ i, IsSeparable (s i)) : IsSeparable {f : ∀ i, α i | ∀ i, f i ∈ s i} := by simpa only [← mem_univ_pi] using IsSeparable.univ_pi h lemma IsSeparable.prod {β : Type*} [TopologicalSpace β] {s : Set α} {t : Set β} (hs : IsSeparable s) (ht : IsSeparable t) : IsSeparable (s ×ˢ t) := by rcases hs with ⟨cs, cs_count, hcs⟩ rcases ht with ⟨ct, ct_count, hct⟩ refine ⟨cs ×ˢ ct, cs_count.prod ct_count, ?_⟩ rw [closure_prod_eq] gcongr theorem IsSeparable.image {β : Type*} [TopologicalSpace β] {s : Set α} (hs : IsSeparable s) {f : α → β} (hf : Continuous f) : IsSeparable (f '' s) := by rcases hs with ⟨c, c_count, hc⟩ refine ⟨f '' c, c_count.image _, ?_⟩ rw [image_subset_iff] exact hc.trans (closure_subset_preimage_closure_image hf) theorem _root_.Dense.isSeparable_iff (hs : Dense s) : IsSeparable s ↔ SeparableSpace α := by simp_rw [IsSeparable, separableSpace_iff, dense_iff_closure_eq, ← univ_subset_iff, ← hs.closure_eq, isClosed_closure.closure_subset_iff] theorem isSeparable_univ_iff : IsSeparable (univ : Set α) ↔ SeparableSpace α := dense_univ.isSeparable_iff theorem isSeparable_range [TopologicalSpace β] [SeparableSpace α] {f : α → β} (hf : Continuous f) : IsSeparable (range f) := image_univ (f := f) ▸ (isSeparable_univ_iff.2 ‹_›).image hf theorem IsSeparable.of_subtype (s : Set α) [SeparableSpace s] : IsSeparable s := by simpa using isSeparable_range (continuous_subtype_val (p := (· ∈ s))) @[deprecated (since := "2024-02-05")] alias isSeparable_of_separableSpace_subtype := IsSeparable.of_subtype theorem IsSeparable.of_separableSpace [h : SeparableSpace α] (s : Set α) : IsSeparable s := IsSeparable.mono (isSeparable_univ_iff.2 h) (subset_univ _) @[deprecated (since := "2024-02-05")] alias isSeparable_of_separableSpace := IsSeparable.of_separableSpace end TopologicalSpace open TopologicalSpace protected theorem IsTopologicalBasis.iInf {β : Type*} {ι : Type*} {t : ι → TopologicalSpace β} {T : ι → Set (Set β)} (h_basis : ∀ i, IsTopologicalBasis (t := t i) (T i)) : IsTopologicalBasis (t := ⨅ i, t i) { S | ∃ (U : ι → Set β) (F : Finset ι), (∀ i, i ∈ F → U i ∈ T i) ∧ S = ⋂ i ∈ F, U i } := by let _ := ⨅ i, t i refine isTopologicalBasis_of_isOpen_of_nhds ?_ ?_ · rintro - ⟨U, F, hU, rfl⟩ refine isOpen_biInter_finset fun i hi ↦ (h_basis i).isOpen (t := t i) (hU i hi) |>.mono (iInf_le _ _) · intro a u ha hu rcases (nhds_iInf (t := t) (a := a)).symm ▸ hasBasis_iInf' (fun i ↦ (h_basis i).nhds_hasBasis (t := t i)) |>.mem_iff.1 (hu.mem_nhds ha) with ⟨⟨F, U⟩, ⟨hF, hU⟩, hUu⟩ refine ⟨_, ⟨U, hF.toFinset, ?_, rfl⟩, ?_, ?_⟩ <;> simp only [Finite.mem_toFinset, mem_iInter] · exact fun i hi ↦ (hU i hi).1 · exact fun i hi ↦ (hU i hi).2 · exact hUu theorem IsTopologicalBasis.iInf_induced {β : Type*} {ι : Type*} {X : ι → Type*} [t : Π i, TopologicalSpace (X i)] {T : Π i, Set (Set (X i))} (cond : ∀ i, IsTopologicalBasis (T i)) (f : Π i, β → X i) : IsTopologicalBasis (t := ⨅ i, induced (f i) (t i)) { S | ∃ (U : ∀ i, Set (X i)) (F : Finset ι), (∀ i, i ∈ F → U i ∈ T i) ∧ S = ⋂ (i) (_ : i ∈ F), f i ⁻¹' U i } := by convert IsTopologicalBasis.iInf (fun i ↦ (cond i).induced (f i)) with S constructor <;> rintro ⟨U, F, hUT, hSU⟩ · exact ⟨fun i ↦ (f i) ⁻¹' (U i), F, fun i hi ↦ mem_image_of_mem _ (hUT i hi), hSU⟩ · choose! U' hU' hUU' using hUT exact ⟨U', F, hU', hSU ▸ (.symm <| iInter₂_congr hUU')⟩ theorem isTopologicalBasis_pi {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] {T : ∀ i, Set (Set (X i))} (cond : ∀ i, IsTopologicalBasis (T i)) : IsTopologicalBasis { S | ∃ (U : ∀ i, Set (X i)) (F : Finset ι), (∀ i, i ∈ F → U i ∈ T i) ∧ S = (F : Set ι).pi U } := by simpa only [Set.pi_def] using IsTopologicalBasis.iInf_induced cond eval theorem isTopologicalBasis_singletons (α : Type*) [TopologicalSpace α] [DiscreteTopology α] : IsTopologicalBasis { s | ∃ x : α, (s : Set α) = {x} } := isTopologicalBasis_of_isOpen_of_nhds (fun _ _ => isOpen_discrete _) fun x _ hx _ => ⟨{x}, ⟨x, rfl⟩, mem_singleton x, singleton_subset_iff.2 hx⟩ theorem isTopologicalBasis_subtype {α : Type*} [TopologicalSpace α] {B : Set (Set α)} (h : TopologicalSpace.IsTopologicalBasis B) (p : α → Prop) : IsTopologicalBasis (Set.preimage (Subtype.val (p := p)) '' B) := h.inducing ⟨rfl⟩ section variable {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] lemma isOpenMap_eval (i : ι) : IsOpenMap (Function.eval i : (∀ i, π i) → π i) := by classical refine (isTopologicalBasis_pi fun _ ↦ isTopologicalBasis_opens).isOpenMap_iff.2 ?_ rintro _ ⟨U, s, hU, rfl⟩ obtain h | h := ((s : Set ι).pi U).eq_empty_or_nonempty · simp [h] by_cases hi : i ∈ s · rw [eval_image_pi (mod_cast hi) h] exact hU _ hi · rw [eval_image_pi_of_not_mem (mod_cast hi), if_pos h] exact isOpen_univ end -- Porting note: moved `DenseRange.separableSpace` up theorem Dense.exists_countable_dense_subset {α : Type*} [TopologicalSpace α] {s : Set α} [SeparableSpace s] (hs : Dense s) : ∃ t ⊆ s, t.Countable ∧ Dense t := let ⟨t, htc, htd⟩ := exists_countable_dense s ⟨(↑) '' t, Subtype.coe_image_subset s t, htc.image Subtype.val, hs.denseRange_val.dense_image continuous_subtype_val htd⟩ /-- Let `s` be a dense set in a topological space `α` with partial order structure. If `s` is a separable space (e.g., if `α` has a second countable topology), then there exists a countable dense subset `t ⊆ s` such that `t` contains bottom/top element of `α` when they exist and belong to `s`. For a dense subset containing neither bot nor top elements, see `Dense.exists_countable_dense_subset_no_bot_top`. -/ theorem Dense.exists_countable_dense_subset_bot_top {α : Type*} [TopologicalSpace α] [PartialOrder α] {s : Set α} [SeparableSpace s] (hs : Dense s) : ∃ t ⊆ s, t.Countable ∧ Dense t ∧ (∀ x, IsBot x → x ∈ s → x ∈ t) ∧ ∀ x, IsTop x → x ∈ s → x ∈ t := by rcases hs.exists_countable_dense_subset with ⟨t, hts, htc, htd⟩ refine ⟨(t ∪ ({ x | IsBot x } ∪ { x | IsTop x })) ∩ s, ?_, ?_, ?_, ?_, ?_⟩ exacts [inter_subset_right, (htc.union ((countable_isBot α).union (countable_isTop α))).mono inter_subset_left, htd.mono (subset_inter subset_union_left hts), fun x hx hxs => ⟨Or.inr <| Or.inl hx, hxs⟩, fun x hx hxs => ⟨Or.inr <| Or.inr hx, hxs⟩] instance separableSpace_univ {α : Type*} [TopologicalSpace α] [SeparableSpace α] : SeparableSpace (univ : Set α) := (Equiv.Set.univ α).symm.surjective.denseRange.separableSpace (continuous_id.subtype_mk _) /-- If `α` is a separable topological space with a partial order, then there exists a countable dense set `s : Set α` that contains those of both bottom and top elements of `α` that actually exist. For a dense set containing neither bot nor top elements, see `exists_countable_dense_no_bot_top`. -/ theorem exists_countable_dense_bot_top (α : Type*) [TopologicalSpace α] [SeparableSpace α] [PartialOrder α] : ∃ s : Set α, s.Countable ∧ Dense s ∧ (∀ x, IsBot x → x ∈ s) ∧ ∀ x, IsTop x → x ∈ s := by simpa using dense_univ.exists_countable_dense_subset_bot_top namespace TopologicalSpace universe u variable (α : Type u) [t : TopologicalSpace α] /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class _root_.FirstCountableTopology : Prop where /-- The filter `𝓝 a` is countably generated for all points `a`. -/ nhds_generated_countable : ∀ a : α, (𝓝 a).IsCountablyGenerated attribute [instance] FirstCountableTopology.nhds_generated_countable /-- If `β` is a first-countable space, then its induced topology via `f` on `α` is also first-countable. -/ theorem firstCountableTopology_induced (α β : Type*) [t : TopologicalSpace β] [FirstCountableTopology β] (f : α → β) : @FirstCountableTopology α (t.induced f) := let _ := t.induced f ⟨fun x ↦ nhds_induced f x ▸ inferInstance⟩ variable {α} instance Subtype.firstCountableTopology (s : Set α) [FirstCountableTopology α] : FirstCountableTopology s := firstCountableTopology_induced s α (↑) protected theorem _root_.Inducing.firstCountableTopology {β : Type*} [TopologicalSpace β] [FirstCountableTopology β] {f : α → β} (hf : Inducing f) : FirstCountableTopology α := by rw [hf.1] exact firstCountableTopology_induced α β f protected theorem _root_.Embedding.firstCountableTopology {β : Type*} [TopologicalSpace β] [FirstCountableTopology β] {f : α → β} (hf : Embedding f) : FirstCountableTopology α := hf.1.firstCountableTopology namespace FirstCountableTopology /-- In a first-countable space, a cluster point `x` of a sequence is the limit of some subsequence. -/ theorem tendsto_subseq [FirstCountableTopology α] {u : ℕ → α} {x : α} (hx : MapClusterPt x atTop u) : ∃ ψ : ℕ → ℕ, StrictMono ψ ∧ Tendsto (u ∘ ψ) atTop (𝓝 x) := subseq_tendsto_of_neBot hx end FirstCountableTopology instance {β} [TopologicalSpace β] [FirstCountableTopology α] [FirstCountableTopology β] : FirstCountableTopology (α × β) := ⟨fun ⟨x, y⟩ => by rw [nhds_prod_eq]; infer_instance⟩ section Pi instance {ι : Type*} {π : ι → Type*} [Countable ι] [∀ i, TopologicalSpace (π i)] [∀ i, FirstCountableTopology (π i)] : FirstCountableTopology (∀ i, π i) := ⟨fun f => by rw [nhds_pi]; infer_instance⟩ end Pi instance isCountablyGenerated_nhdsWithin (x : α) [IsCountablyGenerated (𝓝 x)] (s : Set α) : IsCountablyGenerated (𝓝[s] x) := Inf.isCountablyGenerated _ _ variable (α) /-- A second-countable space is one with a countable basis. -/ class _root_.SecondCountableTopology : Prop where /-- There exists a countable set of sets that generates the topology. -/ is_open_generated_countable : ∃ b : Set (Set α), b.Countable ∧ t = TopologicalSpace.generateFrom b variable {α} protected theorem IsTopologicalBasis.secondCountableTopology {b : Set (Set α)} (hb : IsTopologicalBasis b) (hc : b.Countable) : SecondCountableTopology α := ⟨⟨b, hc, hb.eq_generateFrom⟩⟩ lemma SecondCountableTopology.mk' {α} {b : Set (Set α)} (hc : b.Countable) : @SecondCountableTopology α (generateFrom b) := @SecondCountableTopology.mk α (generateFrom b) ⟨b, hc, rfl⟩ instance _root_.Finite.toSecondCountableTopology [Finite α] : SecondCountableTopology α where is_open_generated_countable := ⟨_, {U | IsOpen U}.to_countable, TopologicalSpace.isTopologicalBasis_opens.eq_generateFrom⟩ variable (α) theorem exists_countable_basis [SecondCountableTopology α] : ∃ b : Set (Set α), b.Countable ∧ ∅ ∉ b ∧ IsTopologicalBasis b := by obtain ⟨b, hb₁, hb₂⟩ := @SecondCountableTopology.is_open_generated_countable α _ _ refine ⟨_, ?_, not_mem_diff_of_mem ?_, (isTopologicalBasis_of_subbasis hb₂).diff_empty⟩ exacts [((countable_setOf_finite_subset hb₁).image _).mono diff_subset, rfl] /-- A countable topological basis of `α`. -/ def countableBasis [SecondCountableTopology α] : Set (Set α) := (exists_countable_basis α).choose theorem countable_countableBasis [SecondCountableTopology α] : (countableBasis α).Countable := (exists_countable_basis α).choose_spec.1 instance encodableCountableBasis [SecondCountableTopology α] : Encodable (countableBasis α) := (countable_countableBasis α).toEncodable theorem empty_nmem_countableBasis [SecondCountableTopology α] : ∅ ∉ countableBasis α := (exists_countable_basis α).choose_spec.2.1 theorem isBasis_countableBasis [SecondCountableTopology α] : IsTopologicalBasis (countableBasis α) := (exists_countable_basis α).choose_spec.2.2 theorem eq_generateFrom_countableBasis [SecondCountableTopology α] : ‹TopologicalSpace α› = generateFrom (countableBasis α) := (isBasis_countableBasis α).eq_generateFrom variable {α} theorem isOpen_of_mem_countableBasis [SecondCountableTopology α] {s : Set α} (hs : s ∈ countableBasis α) : IsOpen s := (isBasis_countableBasis α).isOpen hs theorem nonempty_of_mem_countableBasis [SecondCountableTopology α] {s : Set α} (hs : s ∈ countableBasis α) : s.Nonempty := nonempty_iff_ne_empty.2 <| ne_of_mem_of_not_mem hs <| empty_nmem_countableBasis α variable (α) -- see Note [lower instance priority] instance (priority := 100) SecondCountableTopology.to_firstCountableTopology [SecondCountableTopology α] : FirstCountableTopology α := ⟨fun _ => HasCountableBasis.isCountablyGenerated <| ⟨(isBasis_countableBasis α).nhds_hasBasis, (countable_countableBasis α).mono inter_subset_left⟩⟩ /-- If `β` is a second-countable space, then its induced topology via `f` on `α` is also second-countable. -/ theorem secondCountableTopology_induced (α β) [t : TopologicalSpace β] [SecondCountableTopology β] (f : α → β) : @SecondCountableTopology α (t.induced f) := by rcases @SecondCountableTopology.is_open_generated_countable β _ _ with ⟨b, hb, eq⟩ letI := t.induced f refine { is_open_generated_countable := ⟨preimage f '' b, hb.image _, ?_⟩ } rw [eq, induced_generateFrom_eq] variable {α} instance Subtype.secondCountableTopology (s : Set α) [SecondCountableTopology α] : SecondCountableTopology s := secondCountableTopology_induced s α (↑) lemma secondCountableTopology_iInf {α ι} [Countable ι] {t : ι → TopologicalSpace α} (ht : ∀ i, @SecondCountableTopology α (t i)) : @SecondCountableTopology α (⨅ i, t i) := by rw [funext fun i => @eq_generateFrom_countableBasis α (t i) (ht i), ← generateFrom_iUnion] exact SecondCountableTopology.mk' <| countable_iUnion fun i => @countable_countableBasis _ (t i) (ht i) -- TODO: more fine grained instances for `FirstCountableTopology`, `SeparableSpace`, `T2Space`, ... instance {β : Type*} [TopologicalSpace β] [SecondCountableTopology α] [SecondCountableTopology β] : SecondCountableTopology (α × β) := ((isBasis_countableBasis α).prod (isBasis_countableBasis β)).secondCountableTopology <| (countable_countableBasis α).image2 (countable_countableBasis β) _ instance {ι : Type*} {π : ι → Type*} [Countable ι] [∀ a, TopologicalSpace (π a)] [∀ a, SecondCountableTopology (π a)] : SecondCountableTopology (∀ a, π a) := secondCountableTopology_iInf fun _ => secondCountableTopology_induced _ _ _ -- see Note [lower instance priority] instance (priority := 100) SecondCountableTopology.to_separableSpace [SecondCountableTopology α] : SeparableSpace α := by choose p hp using fun s : countableBasis α => nonempty_of_mem_countableBasis s.2 exact ⟨⟨range p, countable_range _, (isBasis_countableBasis α).dense_iff.2 fun o ho _ => ⟨p ⟨o, ho⟩, hp _, mem_range_self _⟩⟩⟩ /-- A countable open cover induces a second-countable topology if all open covers are themselves second countable. -/ theorem secondCountableTopology_of_countable_cover {ι} [Countable ι] {U : ι → Set α} [∀ i, SecondCountableTopology (U i)] (Uo : ∀ i, IsOpen (U i)) (hc : ⋃ i, U i = univ) : SecondCountableTopology α := haveI : IsTopologicalBasis (⋃ i, image ((↑) : U i → α) '' countableBasis (U i)) := isTopologicalBasis_of_cover Uo hc fun i => isBasis_countableBasis (U i) this.secondCountableTopology (countable_iUnion fun _ => (countable_countableBasis _).image _) /-- In a second-countable space, an open set, given as a union of open sets, is equal to the union of countably many of those sets. In particular, any open covering of `α` has a countable subcover: α is a Lindelöf space. -/ theorem isOpen_iUnion_countable [SecondCountableTopology α] {ι} (s : ι → Set α) (H : ∀ i, IsOpen (s i)) : ∃ T : Set ι, T.Countable ∧ ⋃ i ∈ T, s i = ⋃ i, s i := by let B := { b ∈ countableBasis α | ∃ i, b ⊆ s i } choose f hf using fun b : B => b.2.2 haveI : Countable B := ((countable_countableBasis α).mono (sep_subset _ _)).to_subtype refine ⟨_, countable_range f, (iUnion₂_subset_iUnion _ _).antisymm (sUnion_subset ?_)⟩ rintro _ ⟨i, rfl⟩ x xs rcases (isBasis_countableBasis α).exists_subset_of_mem_open xs (H _) with ⟨b, hb, xb, bs⟩ exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ xb⟩ theorem isOpen_biUnion_countable [SecondCountableTopology α] {ι : Type*} (I : Set ι) (s : ι → Set α) (H : ∀ i ∈ I, IsOpen (s i)) : ∃ T ⊆ I, T.Countable ∧ ⋃ i ∈ T, s i = ⋃ i ∈ I, s i := by simp_rw [← Subtype.exists_set_subtype, biUnion_image] rcases isOpen_iUnion_countable (fun i : I ↦ s i) fun i ↦ H i i.2 with ⟨T, hTc, hU⟩ exact ⟨T, hTc.image _, hU.trans <| iUnion_subtype ..⟩ theorem isOpen_sUnion_countable [SecondCountableTopology α] (S : Set (Set α)) (H : ∀ s ∈ S, IsOpen s) : ∃ T : Set (Set α), T.Countable ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := by simpa only [and_left_comm, sUnion_eq_biUnion] using isOpen_biUnion_countable S id H /-- In a topological space with second countable topology, if `f` is a function that sends each point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`, `x ∈ s`, cover the whole space. -/ theorem countable_cover_nhds [SecondCountableTopology α] {f : α → Set α} (hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : Set α, s.Countable ∧ ⋃ x ∈ s, f x = univ := by rcases isOpen_iUnion_countable (fun x => interior (f x)) fun x => isOpen_interior with ⟨s, hsc, hsU⟩ suffices ⋃ x ∈ s, interior (f x) = univ from ⟨s, hsc, flip eq_univ_of_subset this <| iUnion₂_mono fun _ _ => interior_subset⟩ simp only [hsU, eq_univ_iff_forall, mem_iUnion] exact fun x => ⟨x, mem_interior_iff_mem_nhds.2 (hf x)⟩ theorem countable_cover_nhdsWithin [SecondCountableTopology α] {f : α → Set α} {s : Set α} (hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, t.Countable ∧ s ⊆ ⋃ x ∈ t, f x := by have : ∀ x : s, (↑) ⁻¹' f x ∈ 𝓝 x := fun x => preimage_coe_mem_nhds_subtype.2 (hf x x.2) rcases countable_cover_nhds this with ⟨t, htc, htU⟩ refine ⟨(↑) '' t, Subtype.coe_image_subset _ _, htc.image _, fun x hx => ?_⟩ simp only [biUnion_image, eq_univ_iff_forall, ← preimage_iUnion, mem_preimage] at htU ⊢ exact htU ⟨x, hx⟩ section Sigma variable {ι : Type*} {E : ι → Type*} [∀ i, TopologicalSpace (E i)] /-- In a disjoint union space `Σ i, E i`, one can form a topological basis by taking the union of topological bases on each of the parts of the space. -/ theorem IsTopologicalBasis.sigma {s : ∀ i : ι, Set (Set (E i))} (hs : ∀ i, IsTopologicalBasis (s i)) : IsTopologicalBasis (⋃ i : ι, (fun u => (Sigma.mk i '' u : Set (Σi, E i))) '' s i) := by refine .of_hasBasis_nhds fun a ↦ ?_ rw [Sigma.nhds_eq] convert (((hs a.1).nhds_hasBasis).map _).to_image_id aesop /-- A countable disjoint union of second countable spaces is second countable. -/ instance [Countable ι] [∀ i, SecondCountableTopology (E i)] : SecondCountableTopology (Σi, E i) := by let b := ⋃ i : ι, (fun u => (Sigma.mk i '' u : Set (Σi, E i))) '' countableBasis (E i) have A : IsTopologicalBasis b := IsTopologicalBasis.sigma fun i => isBasis_countableBasis _ have B : b.Countable := countable_iUnion fun i => (countable_countableBasis _).image _ exact A.secondCountableTopology B end Sigma section Sum variable {β : Type*} [TopologicalSpace β] /-- In a sum space `α ⊕ β`, one can form a topological basis by taking the union of topological bases on each of the two components. -/ theorem IsTopologicalBasis.sum {s : Set (Set α)} (hs : IsTopologicalBasis s) {t : Set (Set β)} (ht : IsTopologicalBasis t) : IsTopologicalBasis ((fun u => Sum.inl '' u) '' s ∪ (fun u => Sum.inr '' u) '' t) := by apply isTopologicalBasis_of_isOpen_of_nhds · rintro u (⟨w, hw, rfl⟩ | ⟨w, hw, rfl⟩) · exact openEmbedding_inl.isOpenMap w (hs.isOpen hw) · exact openEmbedding_inr.isOpenMap w (ht.isOpen hw) · rintro (x | x) u hxu u_open · obtain ⟨v, vs, xv, vu⟩ : ∃ v ∈ s, x ∈ v ∧ v ⊆ Sum.inl ⁻¹' u := hs.exists_subset_of_mem_open hxu (isOpen_sum_iff.1 u_open).1 exact ⟨Sum.inl '' v, mem_union_left _ (mem_image_of_mem _ vs), mem_image_of_mem _ xv, image_subset_iff.2 vu⟩ · obtain ⟨v, vs, xv, vu⟩ : ∃ v ∈ t, x ∈ v ∧ v ⊆ Sum.inr ⁻¹' u := ht.exists_subset_of_mem_open hxu (isOpen_sum_iff.1 u_open).2 exact ⟨Sum.inr '' v, mem_union_right _ (mem_image_of_mem _ vs), mem_image_of_mem _ xv, image_subset_iff.2 vu⟩ /-- A sum type of two second countable spaces is second countable. -/ instance [SecondCountableTopology α] [SecondCountableTopology β] : SecondCountableTopology (α ⊕ β) := by let b := (fun u => Sum.inl '' u) '' countableBasis α ∪ (fun u => Sum.inr '' u) '' countableBasis β have A : IsTopologicalBasis b := (isBasis_countableBasis α).sum (isBasis_countableBasis β) have B : b.Countable := (Countable.image (countable_countableBasis _) _).union (Countable.image (countable_countableBasis _) _) exact A.secondCountableTopology B end Sum section Quotient variable {X : Type*} [TopologicalSpace X] {Y : Type*} [TopologicalSpace Y] {π : X → Y} /-- The image of a topological basis under an open quotient map is a topological basis. -/ theorem IsTopologicalBasis.quotientMap {V : Set (Set X)} (hV : IsTopologicalBasis V) (h' : QuotientMap π) (h : IsOpenMap π) : IsTopologicalBasis (Set.image π '' V) := by apply isTopologicalBasis_of_isOpen_of_nhds · rintro - ⟨U, U_in_V, rfl⟩ apply h U (hV.isOpen U_in_V) · intro y U y_in_U U_open obtain ⟨x, rfl⟩ := h'.surjective y let W := π ⁻¹' U have x_in_W : x ∈ W := y_in_U have W_open : IsOpen W := U_open.preimage h'.continuous obtain ⟨Z, Z_in_V, x_in_Z, Z_in_W⟩ := hV.exists_subset_of_mem_open x_in_W W_open have πZ_in_U : π '' Z ⊆ U := (Set.image_subset _ Z_in_W).trans (image_preimage_subset π U) exact ⟨π '' Z, ⟨Z, Z_in_V, rfl⟩, ⟨x, x_in_Z, rfl⟩, πZ_in_U⟩ /-- A second countable space is mapped by an open quotient map to a second countable space. -/ theorem _root_.QuotientMap.secondCountableTopology [SecondCountableTopology X] (h' : QuotientMap π) (h : IsOpenMap π) : SecondCountableTopology Y where is_open_generated_countable := by obtain ⟨V, V_countable, -, V_generates⟩ := exists_countable_basis X exact ⟨Set.image π '' V, V_countable.image (Set.image π), (V_generates.quotientMap h' h).eq_generateFrom⟩ variable {S : Setoid X} /-- The image of a topological basis "downstairs" in an open quotient is a topological basis. -/ theorem IsTopologicalBasis.quotient {V : Set (Set X)} (hV : IsTopologicalBasis V) (h : IsOpenMap (Quotient.mk' : X → Quotient S)) : IsTopologicalBasis (Set.image (Quotient.mk' : X → Quotient S) '' V) := hV.quotientMap quotientMap_quotient_mk' h /-- An open quotient of a second countable space is second countable. -/ theorem Quotient.secondCountableTopology [SecondCountableTopology X] (h : IsOpenMap (Quotient.mk' : X → Quotient S)) : SecondCountableTopology (Quotient S) := quotientMap_quotient_mk'.secondCountableTopology h end Quotient end TopologicalSpace open TopologicalSpace variable {α β : Type*} [TopologicalSpace α] {f : α → β} protected theorem Inducing.secondCountableTopology [TopologicalSpace β] [SecondCountableTopology β] (hf : Inducing f) : SecondCountableTopology α := by rw [hf.1] exact secondCountableTopology_induced α β f protected theorem Embedding.secondCountableTopology [TopologicalSpace β] [SecondCountableTopology β] (hf : Embedding f) : SecondCountableTopology α := hf.1.secondCountableTopology protected theorem Embedding.separableSpace [TopologicalSpace β] [SecondCountableTopology β] {f : α → β} (hf : Embedding f) : TopologicalSpace.SeparableSpace α := by have := hf.secondCountableTopology exact SecondCountableTopology.to_separableSpace
Topology\Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Jeremy Avigad -/ import Mathlib.Order.Filter.Lift import Mathlib.Topology.Defs.Filter /-! # Basic theory of topological spaces. The main definition is the type class `TopologicalSpace X` which endows a type `X` with a topology. Then `Set X` gets predicates `IsOpen`, `IsClosed` and functions `interior`, `closure` and `frontier`. Each point `x` of `X` gets a neighborhood filter `𝓝 x`. A filter `F` on `X` has `x` as a cluster point if `ClusterPt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : α → X` clusters at `x` along `F : Filter α` if `MapClusterPt x F f : ClusterPt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `MapClusterPt x atTop u`. For topological spaces `X` and `Y`, a function `f : X → Y` and a point `x : X`, `ContinuousAt f x` means `f` is continuous at `x`, and global continuity is `Continuous f`. There is also a version of continuity `PContinuous` for partially defined functions. ## Notation The following notation is introduced elsewhere and it heavily used in this file. * `𝓝 x`: the filter `nhds x` of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhdsWithin x s` of neighborhoods of a point `x` within a set `s`; * `𝓝[≠] x`: the filter `nhdsWithin x {x}ᶜ` of punctured neighborhoods of `x`. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ noncomputable section open Set Filter universe u v w x /-! ### Topological spaces -/ /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def TopologicalSpace.ofClosed {X : Type u} (T : Set (Set X)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A, A ⊆ T → ⋂₀ A ∈ T) (union_mem : ∀ A, A ∈ T → ∀ B, B ∈ T → A ∪ B ∈ T) : TopologicalSpace X where IsOpen X := Xᶜ ∈ T isOpen_univ := by simp [empty_mem] isOpen_inter s t hs ht := by simpa only [compl_inter] using union_mem sᶜ hs tᶜ ht isOpen_sUnion s hs := by simp only [Set.compl_sUnion] exact sInter_mem (compl '' s) fun z ⟨y, hy, hz⟩ => hz ▸ hs y hy section TopologicalSpace variable {X : Type u} {Y : Type v} {ι : Sort w} {α β : Type*} {x : X} {s s₁ s₂ t : Set X} {p p₁ p₂ : X → Prop} open Topology lemma isOpen_mk {p h₁ h₂ h₃} : IsOpen[⟨p, h₁, h₂, h₃⟩] s ↔ p s := Iff.rfl @[ext (iff := false)] protected theorem TopologicalSpace.ext : ∀ {f g : TopologicalSpace X}, IsOpen[f] = IsOpen[g] → f = g | ⟨_, _, _, _⟩, ⟨_, _, _, _⟩, rfl => rfl section variable [TopologicalSpace X] end protected theorem TopologicalSpace.ext_iff {t t' : TopologicalSpace X} : t = t' ↔ ∀ s, IsOpen[t] s ↔ IsOpen[t'] s := ⟨fun h s => h ▸ Iff.rfl, fun h => by ext; exact h _⟩ theorem isOpen_fold {t : TopologicalSpace X} : t.IsOpen s = IsOpen[t] s := rfl variable [TopologicalSpace X] theorem isOpen_iUnion {f : ι → Set X} (h : ∀ i, IsOpen (f i)) : IsOpen (⋃ i, f i) := isOpen_sUnion (forall_mem_range.2 h) theorem isOpen_biUnion {s : Set α} {f : α → Set X} (h : ∀ i ∈ s, IsOpen (f i)) : IsOpen (⋃ i ∈ s, f i) := isOpen_iUnion fun i => isOpen_iUnion fun hi => h i hi theorem IsOpen.union (h₁ : IsOpen s₁) (h₂ : IsOpen s₂) : IsOpen (s₁ ∪ s₂) := by rw [union_eq_iUnion]; exact isOpen_iUnion (Bool.forall_bool.2 ⟨h₂, h₁⟩) lemma isOpen_iff_of_cover {f : α → Set X} (ho : ∀ i, IsOpen (f i)) (hU : (⋃ i, f i) = univ) : IsOpen s ↔ ∀ i, IsOpen (f i ∩ s) := by refine ⟨fun h i ↦ (ho i).inter h, fun h ↦ ?_⟩ rw [← s.inter_univ, inter_comm, ← hU, iUnion_inter] exact isOpen_iUnion fun i ↦ h i @[simp] theorem isOpen_empty : IsOpen (∅ : Set X) := by rw [← sUnion_empty]; exact isOpen_sUnion fun a => False.elim theorem Set.Finite.isOpen_sInter {s : Set (Set X)} (hs : s.Finite) : (∀ t ∈ s, IsOpen t) → IsOpen (⋂₀ s) := Finite.induction_on hs (fun _ => by rw [sInter_empty]; exact isOpen_univ) fun _ _ ih h => by simp only [sInter_insert, forall_mem_insert] at h ⊢ exact h.1.inter (ih h.2) theorem Set.Finite.isOpen_biInter {s : Set α} {f : α → Set X} (hs : s.Finite) (h : ∀ i ∈ s, IsOpen (f i)) : IsOpen (⋂ i ∈ s, f i) := sInter_image f s ▸ (hs.image _).isOpen_sInter (forall_mem_image.2 h) theorem isOpen_iInter_of_finite [Finite ι] {s : ι → Set X} (h : ∀ i, IsOpen (s i)) : IsOpen (⋂ i, s i) := (finite_range _).isOpen_sInter (forall_mem_range.2 h) theorem isOpen_biInter_finset {s : Finset α} {f : α → Set X} (h : ∀ i ∈ s, IsOpen (f i)) : IsOpen (⋂ i ∈ s, f i) := s.finite_toSet.isOpen_biInter h @[simp] -- Porting note: added `simp` theorem isOpen_const {p : Prop} : IsOpen { _x : X | p } := by by_cases p <;> simp [*] theorem IsOpen.and : IsOpen { x | p₁ x } → IsOpen { x | p₂ x } → IsOpen { x | p₁ x ∧ p₂ x } := IsOpen.inter @[simp] theorem isOpen_compl_iff : IsOpen sᶜ ↔ IsClosed s := ⟨fun h => ⟨h⟩, fun h => h.isOpen_compl⟩ theorem TopologicalSpace.ext_iff_isClosed {X} {t₁ t₂ : TopologicalSpace X} : t₁ = t₂ ↔ ∀ s, IsClosed[t₁] s ↔ IsClosed[t₂] s := by rw [TopologicalSpace.ext_iff, compl_surjective.forall] simp only [@isOpen_compl_iff _ _ t₁, @isOpen_compl_iff _ _ t₂] alias ⟨_, TopologicalSpace.ext_isClosed⟩ := TopologicalSpace.ext_iff_isClosed theorem isClosed_const {p : Prop} : IsClosed { _x : X | p } := ⟨isOpen_const (p := ¬p)⟩ @[simp] theorem isClosed_empty : IsClosed (∅ : Set X) := isClosed_const @[simp] theorem isClosed_univ : IsClosed (univ : Set X) := isClosed_const theorem IsClosed.union : IsClosed s₁ → IsClosed s₂ → IsClosed (s₁ ∪ s₂) := by simpa only [← isOpen_compl_iff, compl_union] using IsOpen.inter theorem isClosed_sInter {s : Set (Set X)} : (∀ t ∈ s, IsClosed t) → IsClosed (⋂₀ s) := by simpa only [← isOpen_compl_iff, compl_sInter, sUnion_image] using isOpen_biUnion theorem isClosed_iInter {f : ι → Set X} (h : ∀ i, IsClosed (f i)) : IsClosed (⋂ i, f i) := isClosed_sInter <| forall_mem_range.2 h theorem isClosed_biInter {s : Set α} {f : α → Set X} (h : ∀ i ∈ s, IsClosed (f i)) : IsClosed (⋂ i ∈ s, f i) := isClosed_iInter fun i => isClosed_iInter <| h i @[simp] theorem isClosed_compl_iff {s : Set X} : IsClosed sᶜ ↔ IsOpen s := by rw [← isOpen_compl_iff, compl_compl] alias ⟨_, IsOpen.isClosed_compl⟩ := isClosed_compl_iff theorem IsOpen.sdiff (h₁ : IsOpen s) (h₂ : IsClosed t) : IsOpen (s \ t) := IsOpen.inter h₁ h₂.isOpen_compl theorem IsClosed.inter (h₁ : IsClosed s₁) (h₂ : IsClosed s₂) : IsClosed (s₁ ∩ s₂) := by rw [← isOpen_compl_iff] at * rw [compl_inter] exact IsOpen.union h₁ h₂ theorem IsClosed.sdiff (h₁ : IsClosed s) (h₂ : IsOpen t) : IsClosed (s \ t) := IsClosed.inter h₁ (isClosed_compl_iff.mpr h₂) theorem Set.Finite.isClosed_biUnion {s : Set α} {f : α → Set X} (hs : s.Finite) (h : ∀ i ∈ s, IsClosed (f i)) : IsClosed (⋃ i ∈ s, f i) := by simp only [← isOpen_compl_iff, compl_iUnion] at * exact hs.isOpen_biInter h lemma isClosed_biUnion_finset {s : Finset α} {f : α → Set X} (h : ∀ i ∈ s, IsClosed (f i)) : IsClosed (⋃ i ∈ s, f i) := s.finite_toSet.isClosed_biUnion h theorem isClosed_iUnion_of_finite [Finite ι] {s : ι → Set X} (h : ∀ i, IsClosed (s i)) : IsClosed (⋃ i, s i) := by simp only [← isOpen_compl_iff, compl_iUnion] at * exact isOpen_iInter_of_finite h theorem isClosed_imp {p q : X → Prop} (hp : IsOpen { x | p x }) (hq : IsClosed { x | q x }) : IsClosed { x | p x → q x } := by simpa only [imp_iff_not_or] using hp.isClosed_compl.union hq theorem IsClosed.not : IsClosed { a | p a } → IsOpen { a | ¬p a } := isOpen_compl_iff.mpr /-! ### Interior of a set -/ theorem mem_interior : x ∈ interior s ↔ ∃ t ⊆ s, IsOpen t ∧ x ∈ t := by simp only [interior, mem_sUnion, mem_setOf_eq, and_assoc, and_left_comm] @[simp] theorem isOpen_interior : IsOpen (interior s) := isOpen_sUnion fun _ => And.left theorem interior_subset : interior s ⊆ s := sUnion_subset fun _ => And.right theorem interior_maximal (h₁ : t ⊆ s) (h₂ : IsOpen t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ theorem IsOpen.interior_eq (h : IsOpen s) : interior s = s := interior_subset.antisymm (interior_maximal (Subset.refl s) h) theorem interior_eq_iff_isOpen : interior s = s ↔ IsOpen s := ⟨fun h => h ▸ isOpen_interior, IsOpen.interior_eq⟩ theorem subset_interior_iff_isOpen : s ⊆ interior s ↔ IsOpen s := by simp only [interior_eq_iff_isOpen.symm, Subset.antisymm_iff, interior_subset, true_and] theorem IsOpen.subset_interior_iff (h₁ : IsOpen s) : s ⊆ interior t ↔ s ⊆ t := ⟨fun h => Subset.trans h interior_subset, fun h₂ => interior_maximal h₂ h₁⟩ theorem subset_interior_iff : t ⊆ interior s ↔ ∃ U, IsOpen U ∧ t ⊆ U ∧ U ⊆ s := ⟨fun h => ⟨interior s, isOpen_interior, h, interior_subset⟩, fun ⟨_U, hU, htU, hUs⟩ => htU.trans (interior_maximal hUs hU)⟩ lemma interior_subset_iff : interior s ⊆ t ↔ ∀ U, IsOpen U → U ⊆ s → U ⊆ t := by simp [interior] @[mono, gcongr] theorem interior_mono (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (Subset.trans interior_subset h) isOpen_interior @[simp] theorem interior_empty : interior (∅ : Set X) = ∅ := isOpen_empty.interior_eq @[simp] theorem interior_univ : interior (univ : Set X) = univ := isOpen_univ.interior_eq @[simp] theorem interior_eq_univ : interior s = univ ↔ s = univ := ⟨fun h => univ_subset_iff.mp <| h.symm.trans_le interior_subset, fun h => h.symm ▸ interior_univ⟩ @[simp] theorem interior_interior : interior (interior s) = interior s := isOpen_interior.interior_eq @[simp] theorem interior_inter : interior (s ∩ t) = interior s ∩ interior t := (Monotone.map_inf_le (fun _ _ ↦ interior_mono) s t).antisymm <| interior_maximal (inter_subset_inter interior_subset interior_subset) <| isOpen_interior.inter isOpen_interior theorem Set.Finite.interior_biInter {ι : Type*} {s : Set ι} (hs : s.Finite) (f : ι → Set X) : interior (⋂ i ∈ s, f i) = ⋂ i ∈ s, interior (f i) := hs.induction_on (by simp) <| by intros; simp [*] theorem Set.Finite.interior_sInter {S : Set (Set X)} (hS : S.Finite) : interior (⋂₀ S) = ⋂ s ∈ S, interior s := by rw [sInter_eq_biInter, hS.interior_biInter] @[simp] theorem Finset.interior_iInter {ι : Type*} (s : Finset ι) (f : ι → Set X) : interior (⋂ i ∈ s, f i) = ⋂ i ∈ s, interior (f i) := s.finite_toSet.interior_biInter f @[simp] theorem interior_iInter_of_finite [Finite ι] (f : ι → Set X) : interior (⋂ i, f i) = ⋂ i, interior (f i) := by rw [← sInter_range, (finite_range f).interior_sInter, biInter_range] @[simp] theorem interior_iInter₂_lt_nat {n : ℕ} (f : ℕ → Set X) : interior (⋂ m < n, f m) = ⋂ m < n, interior (f m) := (finite_lt_nat n).interior_biInter f @[simp] theorem interior_iInter₂_le_nat {n : ℕ} (f : ℕ → Set X) : interior (⋂ m ≤ n, f m) = ⋂ m ≤ n, interior (f m) := (finite_le_nat n).interior_biInter f theorem interior_union_isClosed_of_interior_empty (h₁ : IsClosed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have : interior (s ∪ t) ⊆ s := fun x ⟨u, ⟨(hu₁ : IsOpen u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩ => by_contradiction fun hx₂ : x ∉ s => have : u \ s ⊆ t := fun x ⟨h₁, h₂⟩ => Or.resolve_left (hu₂ h₁) h₂ have : u \ s ⊆ interior t := by rwa [(IsOpen.sdiff hu₁ h₁).subset_interior_iff] have : u \ s ⊆ ∅ := by rwa [h₂] at this this ⟨hx₁, hx₂⟩ Subset.antisymm (interior_maximal this isOpen_interior) (interior_mono subset_union_left) theorem isOpen_iff_forall_mem_open : IsOpen s ↔ ∀ x ∈ s, ∃ t, t ⊆ s ∧ IsOpen t ∧ x ∈ t := by rw [← subset_interior_iff_isOpen] simp only [subset_def, mem_interior] theorem interior_iInter_subset (s : ι → Set X) : interior (⋂ i, s i) ⊆ ⋂ i, interior (s i) := subset_iInter fun _ => interior_mono <| iInter_subset _ _ theorem interior_iInter₂_subset (p : ι → Sort*) (s : ∀ i, p i → Set X) : interior (⋂ (i) (j), s i j) ⊆ ⋂ (i) (j), interior (s i j) := (interior_iInter_subset _).trans <| iInter_mono fun _ => interior_iInter_subset _ theorem interior_sInter_subset (S : Set (Set X)) : interior (⋂₀ S) ⊆ ⋂ s ∈ S, interior s := calc interior (⋂₀ S) = interior (⋂ s ∈ S, s) := by rw [sInter_eq_biInter] _ ⊆ ⋂ s ∈ S, interior s := interior_iInter₂_subset _ _ theorem Filter.HasBasis.lift'_interior {l : Filter X} {p : ι → Prop} {s : ι → Set X} (h : l.HasBasis p s) : (l.lift' interior).HasBasis p fun i => interior (s i) := h.lift' fun _ _ ↦ interior_mono theorem Filter.lift'_interior_le (l : Filter X) : l.lift' interior ≤ l := fun _s hs ↦ mem_of_superset (mem_lift' hs) interior_subset theorem Filter.HasBasis.lift'_interior_eq_self {l : Filter X} {p : ι → Prop} {s : ι → Set X} (h : l.HasBasis p s) (ho : ∀ i, p i → IsOpen (s i)) : l.lift' interior = l := le_antisymm l.lift'_interior_le <| h.lift'_interior.ge_iff.2 fun i hi ↦ by simpa only [(ho i hi).interior_eq] using h.mem_of_mem hi /-! ### Closure of a set -/ @[simp] theorem isClosed_closure : IsClosed (closure s) := isClosed_sInter fun _ => And.left theorem subset_closure : s ⊆ closure s := subset_sInter fun _ => And.right theorem not_mem_of_not_mem_closure {P : X} (hP : P ∉ closure s) : P ∉ s := fun h => hP (subset_closure h) theorem closure_minimal (h₁ : s ⊆ t) (h₂ : IsClosed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ theorem Disjoint.closure_left (hd : Disjoint s t) (ht : IsOpen t) : Disjoint (closure s) t := disjoint_compl_left.mono_left <| closure_minimal hd.subset_compl_right ht.isClosed_compl theorem Disjoint.closure_right (hd : Disjoint s t) (hs : IsOpen s) : Disjoint s (closure t) := (hd.symm.closure_left hs).symm theorem IsClosed.closure_eq (h : IsClosed s) : closure s = s := Subset.antisymm (closure_minimal (Subset.refl s) h) subset_closure theorem IsClosed.closure_subset (hs : IsClosed s) : closure s ⊆ s := closure_minimal (Subset.refl _) hs theorem IsClosed.closure_subset_iff (h₁ : IsClosed t) : closure s ⊆ t ↔ s ⊆ t := ⟨Subset.trans subset_closure, fun h => closure_minimal h h₁⟩ theorem IsClosed.mem_iff_closure_subset (hs : IsClosed s) : x ∈ s ↔ closure ({x} : Set X) ⊆ s := (hs.closure_subset_iff.trans Set.singleton_subset_iff).symm @[mono, gcongr] theorem closure_mono (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (Subset.trans h subset_closure) isClosed_closure theorem monotone_closure (X : Type*) [TopologicalSpace X] : Monotone (@closure X _) := fun _ _ => closure_mono theorem diff_subset_closure_iff : s \ t ⊆ closure t ↔ s ⊆ closure t := by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure] theorem closure_inter_subset_inter_closure (s t : Set X) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure X).map_inf_le s t theorem isClosed_of_closure_subset (h : closure s ⊆ s) : IsClosed s := by rw [subset_closure.antisymm h]; exact isClosed_closure theorem closure_eq_iff_isClosed : closure s = s ↔ IsClosed s := ⟨fun h => h ▸ isClosed_closure, IsClosed.closure_eq⟩ theorem closure_subset_iff_isClosed : closure s ⊆ s ↔ IsClosed s := ⟨isClosed_of_closure_subset, IsClosed.closure_subset⟩ @[simp] theorem closure_empty : closure (∅ : Set X) = ∅ := isClosed_empty.closure_eq @[simp] theorem closure_empty_iff (s : Set X) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, fun h => h.symm ▸ closure_empty⟩ @[simp] theorem closure_nonempty_iff : (closure s).Nonempty ↔ s.Nonempty := by simp only [nonempty_iff_ne_empty, Ne, closure_empty_iff] alias ⟨Set.Nonempty.of_closure, Set.Nonempty.closure⟩ := closure_nonempty_iff @[simp] theorem closure_univ : closure (univ : Set X) = univ := isClosed_univ.closure_eq @[simp] theorem closure_closure : closure (closure s) = closure s := isClosed_closure.closure_eq theorem closure_eq_compl_interior_compl : closure s = (interior sᶜ)ᶜ := by rw [interior, closure, compl_sUnion, compl_image_set_of] simp only [compl_subset_compl, isOpen_compl_iff] @[simp] theorem closure_union : closure (s ∪ t) = closure s ∪ closure t := by simp [closure_eq_compl_interior_compl, compl_inter] theorem Set.Finite.closure_biUnion {ι : Type*} {s : Set ι} (hs : s.Finite) (f : ι → Set X) : closure (⋃ i ∈ s, f i) = ⋃ i ∈ s, closure (f i) := by simp [closure_eq_compl_interior_compl, hs.interior_biInter] theorem Set.Finite.closure_sUnion {S : Set (Set X)} (hS : S.Finite) : closure (⋃₀ S) = ⋃ s ∈ S, closure s := by rw [sUnion_eq_biUnion, hS.closure_biUnion] @[simp] theorem Finset.closure_biUnion {ι : Type*} (s : Finset ι) (f : ι → Set X) : closure (⋃ i ∈ s, f i) = ⋃ i ∈ s, closure (f i) := s.finite_toSet.closure_biUnion f @[simp] theorem closure_iUnion_of_finite [Finite ι] (f : ι → Set X) : closure (⋃ i, f i) = ⋃ i, closure (f i) := by rw [← sUnion_range, (finite_range _).closure_sUnion, biUnion_range] @[simp] theorem closure_iUnion₂_lt_nat {n : ℕ} (f : ℕ → Set X) : closure (⋃ m < n, f m) = ⋃ m < n, closure (f m) := (finite_lt_nat n).closure_biUnion f @[simp] theorem closure_iUnion₂_le_nat {n : ℕ} (f : ℕ → Set X) : closure (⋃ m ≤ n, f m) = ⋃ m ≤ n, closure (f m) := (finite_le_nat n).closure_biUnion f theorem interior_subset_closure : interior s ⊆ closure s := Subset.trans interior_subset subset_closure @[simp] theorem interior_compl : interior sᶜ = (closure s)ᶜ := by simp [closure_eq_compl_interior_compl] @[simp] theorem closure_compl : closure sᶜ = (interior s)ᶜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff : x ∈ closure s ↔ ∀ o, IsOpen o → x ∈ o → (o ∩ s).Nonempty := ⟨fun h o oo ao => by_contradiction fun os => have : s ⊆ oᶜ := fun x xs xo => os ⟨x, xo, xs⟩ closure_minimal this (isClosed_compl_iff.2 oo) h ao, fun H _ ⟨h₁, h₂⟩ => by_contradiction fun nc => let ⟨_, hc, hs⟩ := H _ h₁.isOpen_compl nc hc (h₂ hs)⟩ theorem closure_inter_open_nonempty_iff (h : IsOpen t) : (closure s ∩ t).Nonempty ↔ (s ∩ t).Nonempty := ⟨fun ⟨_x, hxcs, hxt⟩ => inter_comm t s ▸ mem_closure_iff.1 hxcs t h hxt, fun h => h.mono <| inf_le_inf_right t subset_closure⟩ theorem Filter.le_lift'_closure (l : Filter X) : l ≤ l.lift' closure := le_lift'.2 fun _ h => mem_of_superset h subset_closure theorem Filter.HasBasis.lift'_closure {l : Filter X} {p : ι → Prop} {s : ι → Set X} (h : l.HasBasis p s) : (l.lift' closure).HasBasis p fun i => closure (s i) := h.lift' (monotone_closure X) theorem Filter.HasBasis.lift'_closure_eq_self {l : Filter X} {p : ι → Prop} {s : ι → Set X} (h : l.HasBasis p s) (hc : ∀ i, p i → IsClosed (s i)) : l.lift' closure = l := le_antisymm (h.ge_iff.2 fun i hi => (hc i hi).closure_eq ▸ mem_lift' (h.mem_of_mem hi)) l.le_lift'_closure @[simp] theorem Filter.lift'_closure_eq_bot {l : Filter X} : l.lift' closure = ⊥ ↔ l = ⊥ := ⟨fun h => bot_unique <| h ▸ l.le_lift'_closure, fun h => h.symm ▸ by rw [lift'_bot (monotone_closure _), closure_empty, principal_empty]⟩ theorem dense_iff_closure_eq : Dense s ↔ closure s = univ := eq_univ_iff_forall.symm alias ⟨Dense.closure_eq, _⟩ := dense_iff_closure_eq theorem interior_eq_empty_iff_dense_compl : interior s = ∅ ↔ Dense sᶜ := by rw [dense_iff_closure_eq, closure_compl, compl_univ_iff] theorem Dense.interior_compl (h : Dense s) : interior sᶜ = ∅ := interior_eq_empty_iff_dense_compl.2 <| by rwa [compl_compl] /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] theorem dense_closure : Dense (closure s) ↔ Dense s := by rw [Dense, Dense, closure_closure] protected alias ⟨_, Dense.closure⟩ := dense_closure alias ⟨Dense.of_closure, _⟩ := dense_closure @[simp] theorem dense_univ : Dense (univ : Set X) := fun _ => subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ theorem dense_iff_inter_open : Dense s ↔ ∀ U, IsOpen U → U.Nonempty → (U ∩ s).Nonempty := by constructor <;> intro h · rintro U U_op ⟨x, x_in⟩ exact mem_closure_iff.1 (h _) U U_op x_in · intro x rw [mem_closure_iff] intro U U_op x_in exact h U U_op ⟨_, x_in⟩ alias ⟨Dense.inter_open_nonempty, _⟩ := dense_iff_inter_open theorem Dense.exists_mem_open (hs : Dense s) {U : Set X} (ho : IsOpen U) (hne : U.Nonempty) : ∃ x ∈ s, x ∈ U := let ⟨x, hx⟩ := hs.inter_open_nonempty U ho hne ⟨x, hx.2, hx.1⟩ theorem Dense.nonempty_iff (hs : Dense s) : s.Nonempty ↔ Nonempty X := ⟨fun ⟨x, _⟩ => ⟨x⟩, fun ⟨x⟩ => let ⟨y, hy⟩ := hs.inter_open_nonempty _ isOpen_univ ⟨x, trivial⟩ ⟨y, hy.2⟩⟩ theorem Dense.nonempty [h : Nonempty X] (hs : Dense s) : s.Nonempty := hs.nonempty_iff.2 h @[mono] theorem Dense.mono (h : s₁ ⊆ s₂) (hd : Dense s₁) : Dense s₂ := fun x => closure_mono h (hd x) /-- Complement to a singleton is dense if and only if the singleton is not an open set. -/ theorem dense_compl_singleton_iff_not_open : Dense ({x}ᶜ : Set X) ↔ ¬IsOpen ({x} : Set X) := by constructor · intro hd ho exact (hd.inter_open_nonempty _ ho (singleton_nonempty _)).ne_empty (inter_compl_self _) · refine fun ho => dense_iff_inter_open.2 fun U hU hne => inter_compl_nonempty_iff.2 fun hUx => ?_ obtain rfl : U = {x} := eq_singleton_iff_nonempty_unique_mem.2 ⟨hne, hUx⟩ exact ho hU theorem IsOpen.subset_interior_closure {s : Set X} (s_open : IsOpen s) : s ⊆ interior (closure s) := s_open.subset_interior_iff.mpr subset_closure theorem IsClosed.closure_interior_subset {s : Set X} (s_closed : IsClosed s) : closure (interior s) ⊆ s := s_closed.closure_subset_iff.mpr interior_subset /-! ### Frontier of a set -/ @[simp] theorem closure_diff_interior (s : Set X) : closure s \ interior s = frontier s := rfl /-- Interior and frontier are disjoint. -/ lemma disjoint_interior_frontier : Disjoint (interior s) (frontier s) := by rw [disjoint_iff_inter_eq_empty, ← closure_diff_interior, diff_eq, ← inter_assoc, inter_comm, ← inter_assoc, compl_inter_self, empty_inter] @[simp] theorem closure_diff_frontier (s : Set X) : closure s \ frontier s = interior s := by rw [frontier, diff_diff_right_self, inter_eq_self_of_subset_right interior_subset_closure] @[simp] theorem self_diff_frontier (s : Set X) : s \ frontier s = interior s := by rw [frontier, diff_diff_right, diff_eq_empty.2 subset_closure, inter_eq_self_of_subset_right interior_subset, empty_union] theorem frontier_eq_closure_inter_closure : frontier s = closure s ∩ closure sᶜ := by rw [closure_compl, frontier, diff_eq] theorem frontier_subset_closure : frontier s ⊆ closure s := diff_subset theorem frontier_subset_iff_isClosed : frontier s ⊆ s ↔ IsClosed s := by rw [frontier, diff_subset_iff, union_eq_right.mpr interior_subset, closure_subset_iff_isClosed] alias ⟨_, IsClosed.frontier_subset⟩ := frontier_subset_iff_isClosed theorem frontier_closure_subset : frontier (closure s) ⊆ frontier s := diff_subset_diff closure_closure.subset <| interior_mono subset_closure theorem frontier_interior_subset : frontier (interior s) ⊆ frontier s := diff_subset_diff (closure_mono interior_subset) interior_interior.symm.subset /-- The complement of a set has the same frontier as the original set. -/ @[simp] theorem frontier_compl (s : Set X) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] @[simp] theorem frontier_univ : frontier (univ : Set X) = ∅ := by simp [frontier] @[simp] theorem frontier_empty : frontier (∅ : Set X) = ∅ := by simp [frontier] theorem frontier_inter_subset (s t : Set X) : frontier (s ∩ t) ⊆ frontier s ∩ closure t ∪ closure s ∩ frontier t := by simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union] refine (inter_subset_inter_left _ (closure_inter_subset_inter_closure s t)).trans_eq ?_ simp only [inter_union_distrib_left, union_inter_distrib_right, inter_assoc, inter_comm (closure t)] theorem frontier_union_subset (s t : Set X) : frontier (s ∪ t) ⊆ frontier s ∩ closure tᶜ ∪ closure sᶜ ∩ frontier t := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ theorem IsClosed.frontier_eq (hs : IsClosed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] theorem IsOpen.frontier_eq (hs : IsOpen s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] theorem IsOpen.inter_frontier_eq (hs : IsOpen s) : s ∩ frontier s = ∅ := by rw [hs.frontier_eq, inter_diff_self] theorem disjoint_frontier_iff_isOpen : Disjoint (frontier s) s ↔ IsOpen s := by rw [← isClosed_compl_iff, ← frontier_subset_iff_isClosed, frontier_compl, subset_compl_iff_disjoint_right] /-- The frontier of a set is closed. -/ theorem isClosed_frontier : IsClosed (frontier s) := by rw [frontier_eq_closure_inter_closure]; exact IsClosed.inter isClosed_closure isClosed_closure /-- The frontier of a closed set has no interior point. -/ theorem interior_frontier (h : IsClosed s) : interior (frontier s) = ∅ := by have A : frontier s = s \ interior s := h.frontier_eq have B : interior (frontier s) ⊆ interior s := by rw [A]; exact interior_mono diff_subset have C : interior (frontier s) ⊆ frontier s := interior_subset have : interior (frontier s) ⊆ interior s ∩ (s \ interior s) := subset_inter B (by simpa [A] using C) rwa [inter_diff_self, subset_empty_iff] at this theorem closure_eq_interior_union_frontier (s : Set X) : closure s = interior s ∪ frontier s := (union_diff_cancel interior_subset_closure).symm theorem closure_eq_self_union_frontier (s : Set X) : closure s = s ∪ frontier s := (union_diff_cancel' interior_subset subset_closure).symm theorem Disjoint.frontier_left (ht : IsOpen t) (hd : Disjoint s t) : Disjoint (frontier s) t := subset_compl_iff_disjoint_right.1 <| frontier_subset_closure.trans <| closure_minimal (disjoint_left.1 hd) <| isClosed_compl_iff.2 ht theorem Disjoint.frontier_right (hs : IsOpen s) (hd : Disjoint s t) : Disjoint s (frontier t) := (hd.symm.frontier_left hs).symm theorem frontier_eq_inter_compl_interior : frontier s = (interior s)ᶜ ∩ (interior sᶜ)ᶜ := by rw [← frontier_compl, ← closure_compl, ← diff_eq, closure_diff_interior] theorem compl_frontier_eq_union_interior : (frontier s)ᶜ = interior s ∪ interior sᶜ := by rw [frontier_eq_inter_compl_interior] simp only [compl_inter, compl_compl] /-! ### Neighborhoods -/ theorem nhds_def' (x : X) : 𝓝 x = ⨅ (s : Set X) (_ : IsOpen s) (_ : x ∈ s), 𝓟 s := by simp only [nhds_def, mem_setOf_eq, @and_comm (x ∈ _), iInf_and] /-- The open sets containing `x` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ theorem nhds_basis_opens (x : X) : (𝓝 x).HasBasis (fun s : Set X => x ∈ s ∧ IsOpen s) fun s => s := by rw [nhds_def] exact hasBasis_biInf_principal (fun s ⟨has, hs⟩ t ⟨hat, ht⟩ => ⟨s ∩ t, ⟨⟨has, hat⟩, IsOpen.inter hs ht⟩, ⟨inter_subset_left, inter_subset_right⟩⟩) ⟨univ, ⟨mem_univ x, isOpen_univ⟩⟩ theorem nhds_basis_closeds (x : X) : (𝓝 x).HasBasis (fun s : Set X => x ∉ s ∧ IsClosed s) compl := ⟨fun t => (nhds_basis_opens x).mem_iff.trans <| compl_surjective.exists.trans <| by simp only [isOpen_compl_iff, mem_compl_iff]⟩ @[simp] theorem lift'_nhds_interior (x : X) : (𝓝 x).lift' interior = 𝓝 x := (nhds_basis_opens x).lift'_interior_eq_self fun _ ↦ And.right theorem Filter.HasBasis.nhds_interior {x : X} {p : ι → Prop} {s : ι → Set X} (h : (𝓝 x).HasBasis p s) : (𝓝 x).HasBasis p (interior <| s ·) := lift'_nhds_interior x ▸ h.lift'_interior /-- A filter lies below the neighborhood filter at `x` iff it contains every open set around `x`. -/ theorem le_nhds_iff {f} : f ≤ 𝓝 x ↔ ∀ s : Set X, x ∈ s → IsOpen s → s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `x`, it suffices to show that it is above the principal filter of some open set `s` containing `x`. -/ theorem nhds_le_of_le {f} (h : x ∈ s) (o : IsOpen s) (sf : 𝓟 s ≤ f) : 𝓝 x ≤ f := by rw [nhds_def]; exact iInf₂_le_of_le s ⟨h, o⟩ sf theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ t ⊆ s, IsOpen t ∧ x ∈ t := (nhds_basis_opens x).mem_iff.trans <| exists_congr fun _ => ⟨fun h => ⟨h.2, h.1.2, h.1.1⟩, fun h => ⟨⟨h.2.2, h.2.1⟩, h.1⟩⟩ /-- A predicate is true in a neighborhood of `x` iff it is true for all the points in an open set containing `x`. -/ theorem eventually_nhds_iff {p : X → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ t : Set X, (∀ y ∈ t, p y) ∧ IsOpen t ∧ x ∈ t := mem_nhds_iff.trans <| by simp only [subset_def, exists_prop, mem_setOf_eq] theorem frequently_nhds_iff {p : X → Prop} : (∃ᶠ y in 𝓝 x, p y) ↔ ∀ U : Set X, x ∈ U → IsOpen U → ∃ y ∈ U, p y := (nhds_basis_opens x).frequently_iff.trans <| by simp theorem mem_interior_iff_mem_nhds : x ∈ interior s ↔ s ∈ 𝓝 x := mem_interior.trans mem_nhds_iff.symm theorem map_nhds {f : X → α} : map f (𝓝 x) = ⨅ s ∈ { s : Set X | x ∈ s ∧ IsOpen s }, 𝓟 (f '' s) := ((nhds_basis_opens x).map f).eq_biInf theorem mem_of_mem_nhds : s ∈ 𝓝 x → x ∈ s := fun H => let ⟨_t, ht, _, hs⟩ := mem_nhds_iff.1 H; ht hs /-- If a predicate is true in a neighborhood of `x`, then it is true for `x`. -/ theorem Filter.Eventually.self_of_nhds {p : X → Prop} (h : ∀ᶠ y in 𝓝 x, p y) : p x := mem_of_mem_nhds h theorem IsOpen.mem_nhds (hs : IsOpen s) (hx : x ∈ s) : s ∈ 𝓝 x := mem_nhds_iff.2 ⟨s, Subset.refl _, hs, hx⟩ protected theorem IsOpen.mem_nhds_iff (hs : IsOpen s) : s ∈ 𝓝 x ↔ x ∈ s := ⟨mem_of_mem_nhds, fun hx => mem_nhds_iff.2 ⟨s, Subset.rfl, hs, hx⟩⟩ theorem IsClosed.compl_mem_nhds (hs : IsClosed s) (hx : x ∉ s) : sᶜ ∈ 𝓝 x := hs.isOpen_compl.mem_nhds (mem_compl hx) theorem IsOpen.eventually_mem (hs : IsOpen s) (hx : x ∈ s) : ∀ᶠ x in 𝓝 x, x ∈ s := IsOpen.mem_nhds hs hx /-- The open neighborhoods of `x` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `x` instead. -/ theorem nhds_basis_opens' (x : X) : (𝓝 x).HasBasis (fun s : Set X => s ∈ 𝓝 x ∧ IsOpen s) fun x => x := by convert nhds_basis_opens x using 2 exact and_congr_left_iff.2 IsOpen.mem_nhds_iff /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of `s`: it contains an open set containing `s`. -/ theorem exists_open_set_nhds {U : Set X} (h : ∀ x ∈ s, U ∈ 𝓝 x) : ∃ V : Set X, s ⊆ V ∧ IsOpen V ∧ V ⊆ U := ⟨interior U, fun x hx => mem_interior_iff_mem_nhds.2 <| h x hx, isOpen_interior, interior_subset⟩ /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of s: it contains an open set containing `s`. -/ theorem exists_open_set_nhds' {U : Set X} (h : U ∈ ⨆ x ∈ s, 𝓝 x) : ∃ V : Set X, s ⊆ V ∧ IsOpen V ∧ V ⊆ U := exists_open_set_nhds (by simpa using h) /-- If a predicate is true in a neighbourhood of `x`, then for `y` sufficiently close to `x` this predicate is true in a neighbourhood of `y`. -/ theorem Filter.Eventually.eventually_nhds {p : X → Prop} (h : ∀ᶠ y in 𝓝 x, p y) : ∀ᶠ y in 𝓝 x, ∀ᶠ x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h eventually_nhds_iff.2 ⟨t, fun _x hx => eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] theorem eventually_eventually_nhds {p : X → Prop} : (∀ᶠ y in 𝓝 x, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 x, p x := ⟨fun h => h.self_of_nhds, fun h => h.eventually_nhds⟩ @[simp] theorem frequently_frequently_nhds {p : X → Prop} : (∃ᶠ x' in 𝓝 x, ∃ᶠ x'' in 𝓝 x', p x'') ↔ ∃ᶠ x in 𝓝 x, p x := by rw [← not_iff_not] simp only [not_frequently, eventually_eventually_nhds] @[simp] theorem eventually_mem_nhds : (∀ᶠ x' in 𝓝 x, s ∈ 𝓝 x') ↔ s ∈ 𝓝 x := eventually_eventually_nhds @[simp] theorem nhds_bind_nhds : (𝓝 x).bind 𝓝 = 𝓝 x := Filter.ext fun _ => eventually_eventually_nhds @[simp] theorem eventually_eventuallyEq_nhds {f g : X → α} : (∀ᶠ y in 𝓝 x, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 x] g := eventually_eventually_nhds theorem Filter.EventuallyEq.eq_of_nhds {f g : X → α} (h : f =ᶠ[𝓝 x] g) : f x = g x := h.self_of_nhds @[simp] theorem eventually_eventuallyLE_nhds [LE α] {f g : X → α} : (∀ᶠ y in 𝓝 x, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 x] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `x`, then for `y` sufficiently close to `x` these functions are equal in a neighbourhood of `y`. -/ theorem Filter.EventuallyEq.eventuallyEq_nhds {f g : X → α} (h : f =ᶠ[𝓝 x] g) : ∀ᶠ y in 𝓝 x, f =ᶠ[𝓝 y] g := h.eventually_nhds /-- If `f x ≤ g x` in a neighbourhood of `x`, then for `y` sufficiently close to `x` we have `f x ≤ g x` in a neighbourhood of `y`. -/ theorem Filter.EventuallyLE.eventuallyLE_nhds [LE α] {f g : X → α} (h : f ≤ᶠ[𝓝 x] g) : ∀ᶠ y in 𝓝 x, f ≤ᶠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : X) (P : Set X → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ ∀ s, IsOpen s → x ∈ s → P s := ((nhds_basis_opens x).forall_iff hP).trans <| by simp only [@and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : X) (f : Set X → Set α) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : Filter α) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ ∀ s, IsOpen s → x ∈ s → f s ∈ l := all_mem_nhds _ _ fun s t ssubt h => mem_of_superset h (hf s t ssubt) theorem tendsto_nhds {f : α → X} {l : Filter α} : Tendsto f l (𝓝 x) ↔ ∀ s, IsOpen s → x ∈ s → f ⁻¹' s ∈ l := all_mem_nhds_filter _ _ (fun _ _ h => preimage_mono h) _ theorem tendsto_atTop_nhds [Nonempty α] [SemilatticeSup α] {f : α → X} : Tendsto f atTop (𝓝 x) ↔ ∀ U : Set X, x ∈ U → IsOpen U → ∃ N, ∀ n, N ≤ n → f n ∈ U := (atTop_basis.tendsto_iff (nhds_basis_opens x)).trans <| by simp only [and_imp, exists_prop, true_and_iff, mem_Ici] theorem tendsto_const_nhds {f : Filter α} : Tendsto (fun _ : α => x) f (𝓝 x) := tendsto_nhds.mpr fun _ _ ha => univ_mem' fun _ => ha theorem tendsto_atTop_of_eventually_const {ι : Type*} [SemilatticeSup ι] [Nonempty ι] {u : ι → X} {i₀ : ι} (h : ∀ i ≥ i₀, u i = x) : Tendsto u atTop (𝓝 x) := Tendsto.congr' (EventuallyEq.symm (eventually_atTop.mpr ⟨i₀, h⟩)) tendsto_const_nhds theorem tendsto_atBot_of_eventually_const {ι : Type*} [SemilatticeInf ι] [Nonempty ι] {u : ι → X} {i₀ : ι} (h : ∀ i ≤ i₀, u i = x) : Tendsto u atBot (𝓝 x) := Tendsto.congr' (EventuallyEq.symm (eventually_atBot.mpr ⟨i₀, h⟩)) tendsto_const_nhds theorem pure_le_nhds : pure ≤ (𝓝 : X → Filter X) := fun _ _ hs => mem_pure.2 <| mem_of_mem_nhds hs theorem tendsto_pure_nhds (f : α → X) (a : α) : Tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) theorem OrderTop.tendsto_atTop_nhds [PartialOrder α] [OrderTop α] (f : α → X) : Tendsto f atTop (𝓝 (f ⊤)) := (tendsto_atTop_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_neBot : NeBot (𝓝 x) := neBot_of_le (pure_le_nhds x) theorem tendsto_nhds_of_eventually_eq {l : Filter α} {f : α → X} (h : ∀ᶠ x' in l, f x' = x) : Tendsto f l (𝓝 x) := tendsto_const_nhds.congr' (.symm h) theorem Filter.EventuallyEq.tendsto {l : Filter α} {f : α → X} (hf : f =ᶠ[l] fun _ ↦ x) : Tendsto f l (𝓝 x) := tendsto_nhds_of_eventually_eq hf /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ theorem ClusterPt.neBot {F : Filter X} (h : ClusterPt x F) : NeBot (𝓝 x ⊓ F) := h theorem Filter.HasBasis.clusterPt_iff {ιX ιF} {pX : ιX → Prop} {sX : ιX → Set X} {pF : ιF → Prop} {sF : ιF → Set X} {F : Filter X} (hX : (𝓝 x).HasBasis pX sX) (hF : F.HasBasis pF sF) : ClusterPt x F ↔ ∀ ⦃i⦄, pX i → ∀ ⦃j⦄, pF j → (sX i ∩ sF j).Nonempty := hX.inf_basis_neBot_iff hF theorem clusterPt_iff {F : Filter X} : ClusterPt x F ↔ ∀ ⦃U : Set X⦄, U ∈ 𝓝 x → ∀ ⦃V⦄, V ∈ F → (U ∩ V).Nonempty := inf_neBot_iff theorem clusterPt_iff_not_disjoint {F : Filter X} : ClusterPt x F ↔ ¬Disjoint (𝓝 x) F := by rw [disjoint_iff, ClusterPt, neBot_iff] /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. See also `mem_closure_iff_clusterPt`. -/ theorem clusterPt_principal_iff : ClusterPt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).Nonempty := inf_principal_neBot_iff theorem clusterPt_principal_iff_frequently : ClusterPt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [clusterPt_principal_iff, frequently_iff, Set.Nonempty, exists_prop, mem_inter_iff] theorem ClusterPt.of_le_nhds {f : Filter X} (H : f ≤ 𝓝 x) [NeBot f] : ClusterPt x f := by rwa [ClusterPt, inf_eq_right.mpr H] theorem ClusterPt.of_le_nhds' {f : Filter X} (H : f ≤ 𝓝 x) (_hf : NeBot f) : ClusterPt x f := ClusterPt.of_le_nhds H theorem ClusterPt.of_nhds_le {f : Filter X} (H : 𝓝 x ≤ f) : ClusterPt x f := by simp only [ClusterPt, inf_eq_left.mpr H, nhds_neBot] theorem ClusterPt.mono {f g : Filter X} (H : ClusterPt x f) (h : f ≤ g) : ClusterPt x g := NeBot.mono H <| inf_le_inf_left _ h theorem ClusterPt.of_inf_left {f g : Filter X} (H : ClusterPt x <| f ⊓ g) : ClusterPt x f := H.mono inf_le_left theorem ClusterPt.of_inf_right {f g : Filter X} (H : ClusterPt x <| f ⊓ g) : ClusterPt x g := H.mono inf_le_right theorem Ultrafilter.clusterPt_iff {f : Ultrafilter X} : ClusterPt x f ↔ ↑f ≤ 𝓝 x := ⟨f.le_of_inf_neBot', fun h => ClusterPt.of_le_nhds h⟩ theorem clusterPt_iff_ultrafilter {f : Filter X} : ClusterPt x f ↔ ∃ u : Ultrafilter X, u ≤ f ∧ u ≤ 𝓝 x := by simp_rw [ClusterPt, ← le_inf_iff, exists_ultrafilter_iff, inf_comm] theorem mapClusterPt_def {ι : Type*} (x : X) (F : Filter ι) (u : ι → X) : MapClusterPt x F u ↔ ClusterPt x (map u F) := Iff.rfl theorem mapClusterPt_iff {ι : Type*} (x : X) (F : Filter ι) (u : ι → X) : MapClusterPt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by simp_rw [MapClusterPt, ClusterPt, inf_neBot_iff_frequently_left, frequently_map] rfl theorem mapClusterPt_iff_ultrafilter {ι : Type*} (x : X) (F : Filter ι) (u : ι → X) : MapClusterPt x F u ↔ ∃ U : Ultrafilter ι, U ≤ F ∧ Tendsto u U (𝓝 x) := by simp_rw [MapClusterPt, ClusterPt, ← Filter.push_pull', map_neBot_iff, tendsto_iff_comap, ← le_inf_iff, exists_ultrafilter_iff, inf_comm] theorem mapClusterPt_comp {X α β : Type*} {x : X} [TopologicalSpace X] {F : Filter α} {φ : α → β} {u : β → X} : MapClusterPt x F (u ∘ φ) ↔ MapClusterPt x (map φ F) u := Iff.rfl theorem mapClusterPt_of_comp {F : Filter α} {φ : β → α} {p : Filter β} {u : α → X} [NeBot p] (h : Tendsto φ p F) (H : Tendsto (u ∘ φ) p (𝓝 x)) : MapClusterPt x F u := by have := calc map (u ∘ φ) p = map u (map φ p) := map_map _ ≤ map u F := map_mono h have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F := le_inf H this exact neBot_of_le this theorem accPt_sup (x : X) (F G : Filter X) : AccPt x (F ⊔ G) ↔ AccPt x F ∨ AccPt x G := by simp only [AccPt, inf_sup_left, sup_neBot] theorem acc_iff_cluster (x : X) (F : Filter X) : AccPt x F ↔ ClusterPt x (𝓟 {x}ᶜ ⊓ F) := by rw [AccPt, nhdsWithin, ClusterPt, inf_assoc] /-- `x` is an accumulation point of a set `C` iff it is a cluster point of `C ∖ {x}`. -/ theorem acc_principal_iff_cluster (x : X) (C : Set X) : AccPt x (𝓟 C) ↔ ClusterPt x (𝓟 (C \ {x})) := by rw [acc_iff_cluster, inf_principal, inter_comm, diff_eq] /-- `x` is an accumulation point of a set `C` iff every neighborhood of `x` contains a point of `C` other than `x`. -/ theorem accPt_iff_nhds (x : X) (C : Set X) : AccPt x (𝓟 C) ↔ ∀ U ∈ 𝓝 x, ∃ y ∈ U ∩ C, y ≠ x := by simp [acc_principal_iff_cluster, clusterPt_principal_iff, Set.Nonempty, exists_prop, and_assoc, @and_comm (¬_ = x)] /-- `x` is an accumulation point of a set `C` iff there are points near `x` in `C` and different from `x`. -/ theorem accPt_iff_frequently (x : X) (C : Set X) : AccPt x (𝓟 C) ↔ ∃ᶠ y in 𝓝 x, y ≠ x ∧ y ∈ C := by simp [acc_principal_iff_cluster, clusterPt_principal_iff_frequently, and_comm] /-- If `x` is an accumulation point of `F` and `F ≤ G`, then `x` is an accumulation point of `G`. -/ theorem AccPt.mono {F G : Filter X} (h : AccPt x F) (hFG : F ≤ G) : AccPt x G := NeBot.mono h (inf_le_inf_left _ hFG) theorem AccPt.clusterPt (x : X) (F : Filter X) (h : AccPt x F) : ClusterPt x F := ((acc_iff_cluster x F).mp h).mono inf_le_right /-! ### Interior, closure and frontier in terms of neighborhoods -/ theorem interior_eq_nhds' : interior s = { x | s ∈ 𝓝 x } := Set.ext fun x => by simp only [mem_interior, mem_nhds_iff, mem_setOf_eq] theorem interior_eq_nhds : interior s = { x | 𝓝 x ≤ 𝓟 s } := interior_eq_nhds'.trans <| by simp only [le_principal_iff] @[simp] theorem interior_mem_nhds : interior s ∈ 𝓝 x ↔ s ∈ 𝓝 x := ⟨fun h => mem_of_superset h interior_subset, fun h => IsOpen.mem_nhds isOpen_interior (mem_interior_iff_mem_nhds.2 h)⟩ theorem interior_setOf_eq {p : X → Prop} : interior { x | p x } = { x | ∀ᶠ y in 𝓝 x, p y } := interior_eq_nhds' theorem isOpen_setOf_eventually_nhds {p : X → Prop} : IsOpen { x | ∀ᶠ y in 𝓝 x, p y } := by simp only [← interior_setOf_eq, isOpen_interior] theorem subset_interior_iff_nhds {V : Set X} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := by simp_rw [subset_def, mem_interior_iff_mem_nhds] theorem isOpen_iff_nhds : IsOpen s ↔ ∀ x ∈ s, 𝓝 x ≤ 𝓟 s := calc IsOpen s ↔ s ⊆ interior s := subset_interior_iff_isOpen.symm _ ↔ ∀ x ∈ s, 𝓝 x ≤ 𝓟 s := by simp_rw [interior_eq_nhds, subset_def, mem_setOf] theorem TopologicalSpace.ext_iff_nhds {X} {t t' : TopologicalSpace X} : t = t' ↔ ∀ x, @nhds _ t x = @nhds _ t' x := ⟨fun H x ↦ congrFun (congrArg _ H) _, fun H ↦ by ext; simp_rw [@isOpen_iff_nhds _ _ _, H]⟩ alias ⟨_, TopologicalSpace.ext_nhds⟩ := TopologicalSpace.ext_iff_nhds theorem isOpen_iff_mem_nhds : IsOpen s ↔ ∀ x ∈ s, s ∈ 𝓝 x := isOpen_iff_nhds.trans <| forall_congr' fun _ => imp_congr_right fun _ => le_principal_iff /-- A set `s` is open iff for every point `x` in `s` and every `y` close to `x`, `y` is in `s`. -/ theorem isOpen_iff_eventually : IsOpen s ↔ ∀ x, x ∈ s → ∀ᶠ y in 𝓝 x, y ∈ s := isOpen_iff_mem_nhds theorem isOpen_iff_ultrafilter : IsOpen s ↔ ∀ x ∈ s, ∀ (l : Ultrafilter X), ↑l ≤ 𝓝 x → s ∈ l := by simp_rw [isOpen_iff_mem_nhds, ← mem_iff_ultrafilter] theorem isOpen_singleton_iff_nhds_eq_pure (x : X) : IsOpen ({x} : Set X) ↔ 𝓝 x = pure x := by constructor · intro h apply le_antisymm _ (pure_le_nhds x) rw [le_pure_iff] exact h.mem_nhds (mem_singleton x) · intro h simp [isOpen_iff_nhds, h] theorem isOpen_singleton_iff_punctured_nhds (x : X) : IsOpen ({x} : Set X) ↔ 𝓝[≠] x = ⊥ := by rw [isOpen_singleton_iff_nhds_eq_pure, nhdsWithin, ← mem_iff_inf_principal_compl, ← le_pure_iff, nhds_neBot.le_pure_iff] theorem mem_closure_iff_frequently : x ∈ closure s ↔ ∃ᶠ x in 𝓝 x, x ∈ s := by rw [Filter.Frequently, Filter.Eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl, mem_compl_iff, compl_def] alias ⟨_, Filter.Frequently.mem_closure⟩ := mem_closure_iff_frequently /-- A set `s` is closed iff for every point `x`, if there is a point `y` close to `x` that belongs to `s` then `x` is in `s`. -/ theorem isClosed_iff_frequently : IsClosed s ↔ ∀ x, (∃ᶠ y in 𝓝 x, y ∈ s) → x ∈ s := by rw [← closure_subset_iff_isClosed] refine forall_congr' fun x => ?_ rw [mem_closure_iff_frequently] /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ theorem isClosed_setOf_clusterPt {f : Filter X} : IsClosed { x | ClusterPt x f } := by simp only [ClusterPt, inf_neBot_iff_frequently_left, setOf_forall, imp_iff_not_or] refine isClosed_iInter fun p => IsClosed.union ?_ ?_ <;> apply isClosed_compl_iff.2 exacts [isOpen_setOf_eventually_nhds, isOpen_const] theorem mem_closure_iff_clusterPt : x ∈ closure s ↔ ClusterPt x (𝓟 s) := mem_closure_iff_frequently.trans clusterPt_principal_iff_frequently.symm theorem mem_closure_iff_nhds_ne_bot : x ∈ closure s ↔ 𝓝 x ⊓ 𝓟 s ≠ ⊥ := mem_closure_iff_clusterPt.trans neBot_iff @[deprecated (since := "2024-01-28")] alias mem_closure_iff_nhds_neBot := mem_closure_iff_nhds_ne_bot theorem mem_closure_iff_nhdsWithin_neBot : x ∈ closure s ↔ NeBot (𝓝[s] x) := mem_closure_iff_clusterPt lemma nhdsWithin_neBot : (𝓝[s] x).NeBot ↔ ∀ ⦃t⦄, t ∈ 𝓝 x → (t ∩ s).Nonempty := by rw [nhdsWithin, inf_neBot_iff] exact forall₂_congr fun U _ ↦ ⟨fun h ↦ h (mem_principal_self _), fun h u hsu ↦ h.mono $ inter_subset_inter_right _ hsu⟩ @[gcongr] theorem nhdsWithin_mono (x : X) {s t : Set X} (h : s ⊆ t) : 𝓝[s] x ≤ 𝓝[t] x := inf_le_inf_left _ (principal_mono.mpr h) lemma not_mem_closure_iff_nhdsWithin_eq_bot : x ∉ closure s ↔ 𝓝[s] x = ⊥ := by rw [mem_closure_iff_nhdsWithin_neBot, not_neBot] /-- If `x` is not an isolated point of a topological space, then `{x}ᶜ` is dense in the whole space. -/ theorem dense_compl_singleton (x : X) [NeBot (𝓝[≠] x)] : Dense ({x}ᶜ : Set X) := by intro y rcases eq_or_ne y x with (rfl | hne) · rwa [mem_closure_iff_nhdsWithin_neBot] · exact subset_closure hne /-- If `x` is not an isolated point of a topological space, then the closure of `{x}ᶜ` is the whole space. -/ -- Porting note (#10618): was a `@[simp]` lemma but `simp` can prove it theorem closure_compl_singleton (x : X) [NeBot (𝓝[≠] x)] : closure {x}ᶜ = (univ : Set X) := (dense_compl_singleton x).closure_eq /-- If `x` is not an isolated point of a topological space, then the interior of `{x}` is empty. -/ @[simp] theorem interior_singleton (x : X) [NeBot (𝓝[≠] x)] : interior {x} = (∅ : Set X) := interior_eq_empty_iff_dense_compl.2 (dense_compl_singleton x) theorem not_isOpen_singleton (x : X) [NeBot (𝓝[≠] x)] : ¬IsOpen ({x} : Set X) := dense_compl_singleton_iff_not_open.1 (dense_compl_singleton x) theorem closure_eq_cluster_pts : closure s = { a | ClusterPt a (𝓟 s) } := Set.ext fun _ => mem_closure_iff_clusterPt theorem mem_closure_iff_nhds : x ∈ closure s ↔ ∀ t ∈ 𝓝 x, (t ∩ s).Nonempty := mem_closure_iff_clusterPt.trans clusterPt_principal_iff theorem mem_closure_iff_nhds' : x ∈ closure s ↔ ∀ t ∈ 𝓝 x, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, Set.inter_nonempty_iff_exists_right, SetCoe.exists, exists_prop] theorem mem_closure_iff_comap_neBot : x ∈ closure s ↔ NeBot (comap ((↑) : s → X) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_neBot_iff, Set.inter_nonempty_iff_exists_right, SetCoe.exists, exists_prop] theorem mem_closure_iff_nhds_basis' {p : ι → Prop} {s : ι → Set X} (h : (𝓝 x).HasBasis p s) : x ∈ closure t ↔ ∀ i, p i → (s i ∩ t).Nonempty := mem_closure_iff_clusterPt.trans <| (h.clusterPt_iff (hasBasis_principal _)).trans <| by simp only [exists_prop, forall_const] theorem mem_closure_iff_nhds_basis {p : ι → Prop} {s : ι → Set X} (h : (𝓝 x).HasBasis p s) : x ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := (mem_closure_iff_nhds_basis' h).trans <| by simp only [Set.Nonempty, mem_inter_iff, exists_prop, and_comm] theorem clusterPt_iff_forall_mem_closure {F : Filter X} : ClusterPt x F ↔ ∀ s ∈ F, x ∈ closure s := by simp_rw [ClusterPt, inf_neBot_iff, mem_closure_iff_nhds] rw [forall₂_swap] theorem clusterPt_iff_lift'_closure {F : Filter X} : ClusterPt x F ↔ pure x ≤ (F.lift' closure) := by simp_rw [clusterPt_iff_forall_mem_closure, (hasBasis_pure _).le_basis_iff F.basis_sets.lift'_closure, id, singleton_subset_iff, true_and, exists_const] theorem clusterPt_iff_lift'_closure' {F : Filter X} : ClusterPt x F ↔ (F.lift' closure ⊓ pure x).NeBot := by rw [clusterPt_iff_lift'_closure, ← Ultrafilter.coe_pure, inf_comm, Ultrafilter.inf_neBot_iff] @[simp] theorem clusterPt_lift'_closure_iff {F : Filter X} : ClusterPt x (F.lift' closure) ↔ ClusterPt x F := by simp [clusterPt_iff_lift'_closure, lift'_lift'_assoc (monotone_closure X) (monotone_closure X)] /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ theorem mem_closure_iff_ultrafilter : x ∈ closure s ↔ ∃ u : Ultrafilter X, s ∈ u ∧ ↑u ≤ 𝓝 x := by simp [closure_eq_cluster_pts, ClusterPt, ← exists_ultrafilter_iff, and_comm] theorem isClosed_iff_clusterPt : IsClosed s ↔ ∀ a, ClusterPt a (𝓟 s) → a ∈ s := calc IsClosed s ↔ closure s ⊆ s := closure_subset_iff_isClosed.symm _ ↔ ∀ a, ClusterPt a (𝓟 s) → a ∈ s := by simp only [subset_def, mem_closure_iff_clusterPt] theorem isClosed_iff_ultrafilter : IsClosed s ↔ ∀ x, ∀ u : Ultrafilter X, ↑u ≤ 𝓝 x → s ∈ u → x ∈ s := by simp [isClosed_iff_clusterPt, ClusterPt, ← exists_ultrafilter_iff] theorem isClosed_iff_nhds : IsClosed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).Nonempty) → x ∈ s := by simp_rw [isClosed_iff_clusterPt, ClusterPt, inf_principal_neBot_iff] lemma isClosed_iff_forall_filter : IsClosed s ↔ ∀ x, ∀ F : Filter X, F.NeBot → F ≤ 𝓟 s → F ≤ 𝓝 x → x ∈ s := by simp_rw [isClosed_iff_clusterPt] exact ⟨fun hs x F F_ne FS Fx ↦ hs _ <| NeBot.mono F_ne (le_inf Fx FS), fun hs x hx ↦ hs x (𝓝 x ⊓ 𝓟 s) hx inf_le_right inf_le_left⟩ theorem IsClosed.interior_union_left (_ : IsClosed s) : interior (s ∪ t) ⊆ s ∪ interior t := fun a ⟨u, ⟨⟨hu₁, hu₂⟩, ha⟩⟩ => (Classical.em (a ∈ s)).imp_right fun h => mem_interior.mpr ⟨u ∩ sᶜ, fun _x hx => (hu₂ hx.1).resolve_left hx.2, IsOpen.inter hu₁ IsClosed.isOpen_compl, ⟨ha, h⟩⟩ theorem IsClosed.interior_union_right (h : IsClosed t) : interior (s ∪ t) ⊆ interior s ∪ t := by simpa only [union_comm _ t] using h.interior_union_left theorem IsOpen.inter_closure (h : IsOpen s) : s ∩ closure t ⊆ closure (s ∩ t) := compl_subset_compl.mp <| by simpa only [← interior_compl, compl_inter] using IsClosed.interior_union_left h.isClosed_compl theorem IsOpen.closure_inter (h : IsOpen t) : closure s ∩ t ⊆ closure (s ∩ t) := by simpa only [inter_comm t] using h.inter_closure theorem Dense.open_subset_closure_inter (hs : Dense s) (ht : IsOpen t) : t ⊆ closure (t ∩ s) := calc t = t ∩ closure s := by rw [hs.closure_eq, inter_univ] _ ⊆ closure (t ∩ s) := ht.inter_closure theorem mem_closure_of_mem_closure_union (h : x ∈ closure (s₁ ∪ s₂)) (h₁ : s₁ᶜ ∈ 𝓝 x) : x ∈ closure s₂ := by rw [mem_closure_iff_nhds_ne_bot] at * rwa [← sup_principal, inf_sup_left, inf_principal_eq_bot.mpr h₁, bot_sup_eq] at h /-- The intersection of an open dense set with a dense set is a dense set. -/ theorem Dense.inter_of_isOpen_left (hs : Dense s) (ht : Dense t) (hso : IsOpen s) : Dense (s ∩ t) := fun x => closure_minimal hso.inter_closure isClosed_closure <| by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ theorem Dense.inter_of_isOpen_right (hs : Dense s) (ht : Dense t) (hto : IsOpen t) : Dense (s ∩ t) := inter_comm t s ▸ ht.inter_of_isOpen_left hs hto theorem Dense.inter_nhds_nonempty (hs : Dense s) (ht : t ∈ 𝓝 x) : (s ∩ t).Nonempty := let ⟨U, hsub, ho, hx⟩ := mem_nhds_iff.1 ht (hs.inter_open_nonempty U ho ⟨x, hx⟩).mono fun _y hy => ⟨hy.2, hsub hy.1⟩ theorem closure_diff : closure s \ closure t ⊆ closure (s \ t) := calc closure s \ closure t = (closure t)ᶜ ∩ closure s := by simp only [diff_eq, inter_comm] _ ⊆ closure ((closure t)ᶜ ∩ s) := (isOpen_compl_iff.mpr <| isClosed_closure).inter_closure _ = closure (s \ closure t) := by simp only [diff_eq, inter_comm] _ ⊆ closure (s \ t) := closure_mono <| diff_subset_diff (Subset.refl s) subset_closure theorem Filter.Frequently.mem_of_closed (h : ∃ᶠ x in 𝓝 x, x ∈ s) (hs : IsClosed s) : x ∈ s := hs.closure_subset h.mem_closure theorem IsClosed.mem_of_frequently_of_tendsto {f : α → X} {b : Filter α} (hs : IsClosed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : Tendsto f b (𝓝 x)) : x ∈ s := (hf.frequently <| show ∃ᶠ x in b, (fun y => y ∈ s) (f x) from h).mem_of_closed hs theorem IsClosed.mem_of_tendsto {f : α → X} {b : Filter α} [NeBot b] (hs : IsClosed s) (hf : Tendsto f b (𝓝 x)) (h : ∀ᶠ x in b, f x ∈ s) : x ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf theorem mem_closure_of_frequently_of_tendsto {f : α → X} {b : Filter α} (h : ∃ᶠ x in b, f x ∈ s) (hf : Tendsto f b (𝓝 x)) : x ∈ closure s := (hf.frequently h).mem_closure theorem mem_closure_of_tendsto {f : α → X} {b : Filter α} [NeBot b] (hf : Tendsto f b (𝓝 x)) (h : ∀ᶠ x in b, f x ∈ s) : x ∈ closure s := mem_closure_of_frequently_of_tendsto h.frequently hf /-- Suppose that `f` sends the complement to `s` to a single point `x`, and `l` is some filter. Then `f` tends to `x` along `l` restricted to `s` if and only if it tends to `x` along `l`. -/ theorem tendsto_inf_principal_nhds_iff_of_forall_eq {f : α → X} {l : Filter α} {s : Set α} (h : ∀ a ∉ s, f a = x) : Tendsto f (l ⊓ 𝓟 s) (𝓝 x) ↔ Tendsto f l (𝓝 x) := by rw [tendsto_iff_comap, tendsto_iff_comap] replace h : 𝓟 sᶜ ≤ comap f (𝓝 x) := by rintro U ⟨t, ht, htU⟩ x hx have : f x ∈ t := (h x hx).symm ▸ mem_of_mem_nhds ht exact htU this refine ⟨fun h' => ?_, le_trans inf_le_left⟩ have := sup_le h' h rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this exact this.1 /-! ### Limits of filters in topological spaces In this section we define functions that return a limit of a filter (or of a function along a filter), if it exists, and a random point otherwise. These functions are rarely used in Mathlib, most of the theorems are written using `Filter.Tendsto`. One of the reasons is that `Filter.limUnder f g = x` is not equivalent to `Filter.Tendsto g f (𝓝 x)` unless the codomain is a Hausdorff space and `g` has a limit along `f`. -/ section lim -- "Lim" /-- If a filter `f` is majorated by some `𝓝 x`, then it is majorated by `𝓝 (Filter.lim f)`. We formulate this lemma with a `[Nonempty X]` argument of `lim` derived from `h` to make it useful for types without a `[Nonempty X]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ theorem le_nhds_lim {f : Filter X} (h : ∃ x, f ≤ 𝓝 x) : f ≤ 𝓝 (@lim _ _ (nonempty_of_exists h) f) := Classical.epsilon_spec h /-- If `g` tends to some `𝓝 x` along `f`, then it tends to `𝓝 (Filter.limUnder f g)`. We formulate this lemma with a `[Nonempty X]` argument of `lim` derived from `h` to make it useful for types without a `[Nonempty X]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ theorem tendsto_nhds_limUnder {f : Filter α} {g : α → X} (h : ∃ x, Tendsto g f (𝓝 x)) : Tendsto g f (𝓝 (@limUnder _ _ _ (nonempty_of_exists h) f g)) := le_nhds_lim h end lim end TopologicalSpace open Topology /-! ### Continuity -/ section Continuous variable {X Y Z : Type*} open TopologicalSpace -- The curly braces are intentional, so this definition works well with simp -- when topologies are not those provided by instances. theorem continuous_def {_ : TopologicalSpace X} {_ : TopologicalSpace Y} {f : X → Y} : Continuous f ↔ ∀ s, IsOpen s → IsOpen (f ⁻¹' s) := ⟨fun hf => hf.1, fun h => ⟨h⟩⟩ variable [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] variable {f : X → Y} {s : Set X} {x : X} {y : Y} theorem IsOpen.preimage (hf : Continuous f) {t : Set Y} (h : IsOpen t) : IsOpen (f ⁻¹' t) := hf.isOpen_preimage t h theorem continuous_congr {g : X → Y} (h : ∀ x, f x = g x) : Continuous f ↔ Continuous g := .of_eq <| congrArg _ <| funext h theorem Continuous.congr {g : X → Y} (h : Continuous f) (h' : ∀ x, f x = g x) : Continuous g := continuous_congr h' |>.mp h theorem ContinuousAt.tendsto (h : ContinuousAt f x) : Tendsto f (𝓝 x) (𝓝 (f x)) := h theorem continuousAt_def : ContinuousAt f x ↔ ∀ A ∈ 𝓝 (f x), f ⁻¹' A ∈ 𝓝 x := Iff.rfl theorem continuousAt_congr {g : X → Y} (h : f =ᶠ[𝓝 x] g) : ContinuousAt f x ↔ ContinuousAt g x := by simp only [ContinuousAt, tendsto_congr' h, h.eq_of_nhds] theorem ContinuousAt.congr {g : X → Y} (hf : ContinuousAt f x) (h : f =ᶠ[𝓝 x] g) : ContinuousAt g x := (continuousAt_congr h).1 hf theorem ContinuousAt.preimage_mem_nhds {t : Set Y} (h : ContinuousAt f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht /-- If `f x ∈ s ∈ 𝓝 (f x)` for continuous `f`, then `f y ∈ s` near `x`. This is essentially `Filter.Tendsto.eventually_mem`, but infers in more cases when applied. -/ theorem ContinuousAt.eventually_mem {f : X → Y} {x : X} (hf : ContinuousAt f x) {s : Set Y} (hs : s ∈ 𝓝 (f x)) : ∀ᶠ y in 𝓝 x, f y ∈ s := hf hs /-- Deprecated, please use `not_mem_tsupport_iff_eventuallyEq` instead. -/ @[deprecated (since := "2024-01-15")] theorem eventuallyEq_zero_nhds {M₀} [Zero M₀] {f : X → M₀} : f =ᶠ[𝓝 x] 0 ↔ x ∉ closure (Function.support f) := by rw [← mem_compl_iff, ← interior_compl, mem_interior_iff_mem_nhds, Function.compl_support, EventuallyEq, eventually_iff] simp only [Pi.zero_apply] theorem ClusterPt.map {lx : Filter X} {ly : Filter Y} (H : ClusterPt x lx) (hfc : ContinuousAt f x) (hf : Tendsto f lx ly) : ClusterPt (f x) ly := (NeBot.map H f).mono <| hfc.tendsto.inf hf /-- See also `interior_preimage_subset_preimage_interior`. -/ theorem preimage_interior_subset_interior_preimage {t : Set Y} (hf : Continuous f) : f ⁻¹' interior t ⊆ interior (f ⁻¹' t) := interior_maximal (preimage_mono interior_subset) (isOpen_interior.preimage hf) @[continuity] theorem continuous_id : Continuous (id : X → X) := continuous_def.2 fun _ => id -- This is needed due to reducibility issues with the `continuity` tactic. @[continuity, fun_prop] theorem continuous_id' : Continuous (fun (x : X) => x) := continuous_id theorem Continuous.comp {g : Y → Z} (hg : Continuous g) (hf : Continuous f) : Continuous (g ∘ f) := continuous_def.2 fun _ h => (h.preimage hg).preimage hf -- This is needed due to reducibility issues with the `continuity` tactic. @[continuity, fun_prop] theorem Continuous.comp' {g : Y → Z} (hg : Continuous g) (hf : Continuous f) : Continuous (fun x => g (f x)) := hg.comp hf theorem Continuous.iterate {f : X → X} (h : Continuous f) (n : ℕ) : Continuous f^[n] := Nat.recOn n continuous_id fun _ ihn => ihn.comp h nonrec theorem ContinuousAt.comp {g : Y → Z} (hg : ContinuousAt g (f x)) (hf : ContinuousAt f x) : ContinuousAt (g ∘ f) x := hg.comp hf @[fun_prop] theorem ContinuousAt.comp' {g : Y → Z} {x : X} (hg : ContinuousAt g (f x)) (hf : ContinuousAt f x) : ContinuousAt (fun x => g (f x)) x := ContinuousAt.comp hg hf /-- See note [comp_of_eq lemmas] -/ theorem ContinuousAt.comp_of_eq {g : Y → Z} (hg : ContinuousAt g y) (hf : ContinuousAt f x) (hy : f x = y) : ContinuousAt (g ∘ f) x := by subst hy; exact hg.comp hf theorem Continuous.tendsto (hf : Continuous f) (x) : Tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff <| nhds_basis_opens <| f x).2 fun t ⟨hxt, ht⟩ => ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, Subset.rfl⟩ /-- A version of `Continuous.tendsto` that allows one to specify a simpler form of the limit. E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/ theorem Continuous.tendsto' (hf : Continuous f) (x : X) (y : Y) (h : f x = y) : Tendsto f (𝓝 x) (𝓝 y) := h ▸ hf.tendsto x @[fun_prop] theorem Continuous.continuousAt (h : Continuous f) : ContinuousAt f x := h.tendsto x theorem continuous_iff_continuousAt : Continuous f ↔ ∀ x, ContinuousAt f x := ⟨Continuous.tendsto, fun hf => continuous_def.2 fun _U hU => isOpen_iff_mem_nhds.2 fun x hx => hf x <| hU.mem_nhds hx⟩ @[fun_prop] theorem continuousAt_const : ContinuousAt (fun _ : X => y) x := tendsto_const_nhds @[continuity, fun_prop] theorem continuous_const : Continuous fun _ : X => y := continuous_iff_continuousAt.mpr fun _ => continuousAt_const theorem Filter.EventuallyEq.continuousAt (h : f =ᶠ[𝓝 x] fun _ => y) : ContinuousAt f x := (continuousAt_congr h).2 tendsto_const_nhds theorem continuous_of_const (h : ∀ x y, f x = f y) : Continuous f := continuous_iff_continuousAt.mpr fun x => Filter.EventuallyEq.continuousAt <| eventually_of_forall fun y => h y x theorem continuousAt_id : ContinuousAt id x := continuous_id.continuousAt @[fun_prop] theorem continuousAt_id' (y) : ContinuousAt (fun x : X => x) y := continuousAt_id theorem ContinuousAt.iterate {f : X → X} (hf : ContinuousAt f x) (hx : f x = x) (n : ℕ) : ContinuousAt f^[n] x := Nat.recOn n continuousAt_id fun _n ihn ↦ ihn.comp_of_eq hf hx theorem continuous_iff_isClosed : Continuous f ↔ ∀ s, IsClosed s → IsClosed (f ⁻¹' s) := continuous_def.trans <| compl_surjective.forall.trans <| by simp only [isOpen_compl_iff, preimage_compl] theorem IsClosed.preimage (hf : Continuous f) {t : Set Y} (h : IsClosed t) : IsClosed (f ⁻¹' t) := continuous_iff_isClosed.mp hf t h theorem mem_closure_image (hf : ContinuousAt f x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := mem_closure_of_frequently_of_tendsto ((mem_closure_iff_frequently.1 hx).mono fun _ => mem_image_of_mem _) hf theorem continuousAt_iff_ultrafilter : ContinuousAt f x ↔ ∀ g : Ultrafilter X, ↑g ≤ 𝓝 x → Tendsto f g (𝓝 (f x)) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) theorem continuous_iff_ultrafilter : Continuous f ↔ ∀ (x) (g : Ultrafilter X), ↑g ≤ 𝓝 x → Tendsto f g (𝓝 (f x)) := by simp only [continuous_iff_continuousAt, continuousAt_iff_ultrafilter] theorem Continuous.closure_preimage_subset (hf : Continuous f) (t : Set Y) : closure (f ⁻¹' t) ⊆ f ⁻¹' closure t := by rw [← (isClosed_closure.preimage hf).closure_eq] exact closure_mono (preimage_mono subset_closure) theorem Continuous.frontier_preimage_subset (hf : Continuous f) (t : Set Y) : frontier (f ⁻¹' t) ⊆ f ⁻¹' frontier t := diff_subset_diff (hf.closure_preimage_subset t) (preimage_interior_subset_interior_preimage hf) /-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/ protected theorem Set.MapsTo.closure {t : Set Y} (h : MapsTo f s t) (hc : Continuous f) : MapsTo f (closure s) (closure t) := by simp only [MapsTo, mem_closure_iff_clusterPt] exact fun x hx => hx.map hc.continuousAt (tendsto_principal_principal.2 h) /-- See also `IsClosedMap.closure_image_eq_of_continuous`. -/ theorem image_closure_subset_closure_image (h : Continuous f) : f '' closure s ⊆ closure (f '' s) := ((mapsTo_image f s).closure h).image_subset theorem closure_image_closure (h : Continuous f) : closure (f '' closure s) = closure (f '' s) := Subset.antisymm (closure_minimal (image_closure_subset_closure_image h) isClosed_closure) (closure_mono <| image_subset _ subset_closure) theorem closure_subset_preimage_closure_image (h : Continuous f) : closure s ⊆ f ⁻¹' closure (f '' s) := (mapsTo_image _ _).closure h theorem map_mem_closure {t : Set Y} (hf : Continuous f) (hx : x ∈ closure s) (ht : MapsTo f s t) : f x ∈ closure t := ht.closure hf hx /-- If a continuous map `f` maps `s` to a closed set `t`, then it maps `closure s` to `t`. -/ theorem Set.MapsTo.closure_left {t : Set Y} (h : MapsTo f s t) (hc : Continuous f) (ht : IsClosed t) : MapsTo f (closure s) t := ht.closure_eq ▸ h.closure hc theorem Filter.Tendsto.lift'_closure (hf : Continuous f) {l l'} (h : Tendsto f l l') : Tendsto f (l.lift' closure) (l'.lift' closure) := tendsto_lift'.2 fun s hs ↦ by filter_upwards [mem_lift' (h hs)] using (mapsTo_preimage _ _).closure hf theorem tendsto_lift'_closure_nhds (hf : Continuous f) (x : X) : Tendsto f ((𝓝 x).lift' closure) ((𝓝 (f x)).lift' closure) := (hf.tendsto x).lift'_closure hf /-! ### Function with dense range -/ section DenseRange variable {α ι : Type*} (f : α → X) (g : X → Y) variable {f : α → X} {s : Set X} /-- A surjective map has dense range. -/ theorem Function.Surjective.denseRange (hf : Function.Surjective f) : DenseRange f := fun x => by simp [hf.range_eq] theorem denseRange_id : DenseRange (id : X → X) := Function.Surjective.denseRange Function.surjective_id theorem denseRange_iff_closure_range : DenseRange f ↔ closure (range f) = univ := dense_iff_closure_eq theorem DenseRange.closure_range (h : DenseRange f) : closure (range f) = univ := h.closure_eq @[simp] lemma denseRange_subtype_val {p : X → Prop} : DenseRange (@Subtype.val _ p) ↔ Dense {x | p x} := by simp [DenseRange] theorem Dense.denseRange_val (h : Dense s) : DenseRange ((↑) : s → X) := denseRange_subtype_val.2 h theorem Continuous.range_subset_closure_image_dense {f : X → Y} (hf : Continuous f) (hs : Dense s) : range f ⊆ closure (f '' s) := by rw [← image_univ, ← hs.closure_eq] exact image_closure_subset_closure_image hf /-- The image of a dense set under a continuous map with dense range is a dense set. -/ theorem DenseRange.dense_image {f : X → Y} (hf' : DenseRange f) (hf : Continuous f) (hs : Dense s) : Dense (f '' s) := (hf'.mono <| hf.range_subset_closure_image_dense hs).of_closure /-- If `f` has dense range and `s` is an open set in the codomain of `f`, then the image of the preimage of `s` under `f` is dense in `s`. -/ theorem DenseRange.subset_closure_image_preimage_of_isOpen (hf : DenseRange f) (hs : IsOpen s) : s ⊆ closure (f '' (f ⁻¹' s)) := by rw [image_preimage_eq_inter_range] exact hf.open_subset_closure_inter hs /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ theorem DenseRange.dense_of_mapsTo {f : X → Y} (hf' : DenseRange f) (hf : Continuous f) (hs : Dense s) {t : Set Y} (ht : MapsTo f s t) : Dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ theorem DenseRange.comp {g : Y → Z} {f : α → Y} (hg : DenseRange g) (hf : DenseRange f) (cg : Continuous g) : DenseRange (g ∘ f) := by rw [DenseRange, range_comp] exact hg.dense_image cg hf nonrec theorem DenseRange.nonempty_iff (hf : DenseRange f) : Nonempty α ↔ Nonempty X := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff theorem DenseRange.nonempty [h : Nonempty X] (hf : DenseRange f) : Nonempty α := hf.nonempty_iff.mpr h /-- Given a function `f : X → Y` with dense range and `y : Y`, returns some `x : X`. -/ def DenseRange.some (hf : DenseRange f) (x : X) : α := Classical.choice <| hf.nonempty_iff.mpr ⟨x⟩ nonrec theorem DenseRange.exists_mem_open (hf : DenseRange f) (ho : IsOpen s) (hs : s.Nonempty) : ∃ a, f a ∈ s := exists_range_iff.1 <| hf.exists_mem_open ho hs theorem DenseRange.mem_nhds (h : DenseRange f) (hs : s ∈ 𝓝 x) : ∃ a, f a ∈ s := let ⟨a, ha⟩ := h.exists_mem_open isOpen_interior ⟨x, mem_interior_iff_mem_nhds.2 hs⟩ ⟨a, interior_subset ha⟩ end DenseRange end Continuous library_note "continuity lemma statement"/-- The library contains many lemmas stating that functions/operations are continuous. There are many ways to formulate the continuity of operations. Some are more convenient than others. Note: for the most part this note also applies to other properties (`Measurable`, `Differentiable`, `ContinuousOn`, ...). ### The traditional way As an example, let's look at addition `(+) : M → M → M`. We can state that this is continuous in different definitionally equal ways (omitting some typing information) * `Continuous (fun p ↦ p.1 + p.2)`; * `Continuous (Function.uncurry (+))`; * `Continuous ↿(+)`. (`↿` is notation for recursively uncurrying a function) However, lemmas with this conclusion are not nice to use in practice because 1. They confuse the elaborator. The following two examples fail, because of limitations in the elaboration process. ``` variable {M : Type*} [Add M] [TopologicalSpace M] [ContinuousAdd M] example : Continuous (fun x : M ↦ x + x) := continuous_add.comp _ example : Continuous (fun x : M ↦ x + x) := continuous_add.comp (continuous_id.prod_mk continuous_id) ``` The second is a valid proof, which is accepted if you write it as `continuous_add.comp (continuous_id.prod_mk continuous_id : _)` 2. If the operation has more than 2 arguments, they are impractical to use, because in your application the arguments in the domain might be in a different order or associated differently. ### The convenient way A much more convenient way to write continuity lemmas is like `Continuous.add`: ``` Continuous.add {f g : X → M} (hf : Continuous f) (hg : Continuous g) : Continuous (fun x ↦ f x + g x) ``` The conclusion can be `Continuous (f + g)`, which is definitionally equal. This has the following advantages * It supports projection notation, so is shorter to write. * `Continuous.add _ _` is recognized correctly by the elaborator and gives useful new goals. * It works generally, since the domain is a variable. As an example for a unary operation, we have `Continuous.neg`. ``` Continuous.neg {f : X → G} (hf : Continuous f) : Continuous (fun x ↦ -f x) ``` For unary functions, the elaborator is not confused when applying the traditional lemma (like `continuous_neg`), but it's still convenient to have the short version available (compare `hf.neg.neg.neg` with `continuous_neg.comp <| continuous_neg.comp <| continuous_neg.comp hf`). As a harder example, consider an operation of the following type: ``` def strans {x : F} (γ γ' : Path x x) (t₀ : I) : Path x x ``` The precise definition is not important, only its type. The correct continuity principle for this operation is something like this: ``` {f : X → F} {γ γ' : ∀ x, Path (f x) (f x)} {t₀ s : X → I} (hγ : Continuous ↿γ) (hγ' : Continuous ↿γ') (ht : Continuous t₀) (hs : Continuous s) : Continuous (fun x ↦ strans (γ x) (γ' x) (t x) (s x)) ``` Note that *all* arguments of `strans` are indexed over `X`, even the basepoint `x`, and the last argument `s` that arises since `Path x x` has a coercion to `I → F`. The paths `γ` and `γ'` (which are unary functions from `I`) become binary functions in the continuity lemma. ### Summary * Make sure that your continuity lemmas are stated in the most general way, and in a convenient form. That means that: - The conclusion has a variable `X` as domain (not something like `Y × Z`); - Wherever possible, all point arguments `c : Y` are replaced by functions `c : X → Y`; - All `n`-ary function arguments are replaced by `n+1`-ary functions (`f : Y → Z` becomes `f : X → Y → Z`); - All (relevant) arguments have continuity assumptions, and perhaps there are additional assumptions needed to make the operation continuous; - The function in the conclusion is fully applied. * These remarks are mostly about the format of the *conclusion* of a continuity lemma. In assumptions it's fine to state that a function with more than 1 argument is continuous using `↿` or `Function.uncurry`. ### Functions with discontinuities In some cases, you want to work with discontinuous functions, and in certain expressions they are still continuous. For example, consider the fractional part of a number, `Int.fract : ℝ → ℝ`. In this case, you want to add conditions to when a function involving `fract` is continuous, so you get something like this: (assumption `hf` could be weakened, but the important thing is the shape of the conclusion) ``` lemma ContinuousOn.comp_fract {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {f : X → ℝ → Y} {g : X → ℝ} (hf : Continuous ↿f) (hg : Continuous g) (h : ∀ s, f s 0 = f s 1) : Continuous (fun x ↦ f x (fract (g x))) ``` With `ContinuousAt` you can be even more precise about what to prove in case of discontinuities, see e.g. `ContinuousAt.comp_div_cases`. -/ library_note "comp_of_eq lemmas"/-- Lean's elaborator has trouble elaborating applications of lemmas that state that the composition of two functions satisfy some property at a point, like `ContinuousAt.comp` / `ContDiffAt.comp` and `ContMDiffWithinAt.comp`. The reason is that a lemma like this looks like `ContinuousAt g (f x) → ContinuousAt f x → ContinuousAt (g ∘ f) x`. Since Lean's elaborator elaborates the arguments from left-to-right, when you write `hg.comp hf`, the elaborator will try to figure out *both* `f` and `g` from the type of `hg`. It tries to figure out `f` just from the point where `g` is continuous. For example, if `hg : ContinuousAt g (a, x)` then the elaborator will assign `f` to the function `Prod.mk a`, since in that case `f x = (a, x)`. This is undesirable in most cases where `f` is not a variable. There are some ways to work around this, for example by giving `f` explicitly, or to force Lean to elaborate `hf` before elaborating `hg`, but this is annoying. Another better solution is to reformulate composition lemmas to have the following shape `ContinuousAt g y → ContinuousAt f x → f x = y → ContinuousAt (g ∘ f) x`. This is even useful if the proof of `f x = y` is `rfl`. The reason that this works better is because the type of `hg` doesn't mention `f`. Only after elaborating the two `ContinuousAt` arguments, Lean will try to unify `f x` with `y`, which is often easy after having chosen the correct functions for `f` and `g`. Here is an example that shows the difference: ``` example [TopologicalSpace X] [TopologicalSpace Y] {x₀ : X} (f : X → X → Y) (hf : ContinuousAt (Function.uncurry f) (x₀, x₀)) : ContinuousAt (fun x ↦ f x x) x₀ := -- hf.comp (continuousAt_id.prod continuousAt_id) -- type mismatch -- hf.comp_of_eq (continuousAt_id.prod continuousAt_id) rfl -- works ``` -/
Topology\Clopen.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import Mathlib.Topology.ContinuousOn import Mathlib.Data.Set.BoolIndicator /-! # Clopen sets A clopen set is a set that is both closed and open. -/ open Set Filter Topology TopologicalSpace universe u v variable {X : Type u} {Y : Type v} {ι : Type*} variable [TopologicalSpace X] [TopologicalSpace Y] {s t : Set X} section Clopen protected theorem IsClopen.isOpen (hs : IsClopen s) : IsOpen s := hs.2 protected theorem IsClopen.isClosed (hs : IsClopen s) : IsClosed s := hs.1 theorem isClopen_iff_frontier_eq_empty : IsClopen s ↔ frontier s = ∅ := by rw [IsClopen, ← closure_eq_iff_isClosed, ← interior_eq_iff_isOpen, frontier, diff_eq_empty] refine ⟨fun h => (h.1.trans h.2.symm).subset, fun h => ?_⟩ exact ⟨(h.trans interior_subset).antisymm subset_closure, interior_subset.antisymm (subset_closure.trans h)⟩ @[simp] alias ⟨IsClopen.frontier_eq, _⟩ := isClopen_iff_frontier_eq_empty theorem IsClopen.union (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ∪ t) := ⟨hs.1.union ht.1, hs.2.union ht.2⟩ theorem IsClopen.inter (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ∩ t) := ⟨hs.1.inter ht.1, hs.2.inter ht.2⟩ theorem isClopen_empty : IsClopen (∅ : Set X) := ⟨isClosed_empty, isOpen_empty⟩ theorem isClopen_univ : IsClopen (univ : Set X) := ⟨isClosed_univ, isOpen_univ⟩ theorem IsClopen.compl (hs : IsClopen s) : IsClopen sᶜ := ⟨hs.2.isClosed_compl, hs.1.isOpen_compl⟩ @[simp] theorem isClopen_compl_iff : IsClopen sᶜ ↔ IsClopen s := ⟨fun h => compl_compl s ▸ IsClopen.compl h, IsClopen.compl⟩ theorem IsClopen.diff (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s \ t) := hs.inter ht.compl lemma IsClopen.himp (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ⇨ t) := by simpa [himp_eq] using ht.union hs.compl theorem IsClopen.prod {t : Set Y} (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ×ˢ t) := ⟨hs.1.prod ht.1, hs.2.prod ht.2⟩ theorem isClopen_iUnion_of_finite {Y} [Finite Y] {s : Y → Set X} (h : ∀ i, IsClopen (s i)) : IsClopen (⋃ i, s i) := ⟨isClosed_iUnion_of_finite (forall_and.1 h).1, isOpen_iUnion (forall_and.1 h).2⟩ theorem Set.Finite.isClopen_biUnion {Y} {s : Set Y} {f : Y → Set X} (hs : s.Finite) (h : ∀ i ∈ s, IsClopen <| f i) : IsClopen (⋃ i ∈ s, f i) := ⟨hs.isClosed_biUnion fun i hi => (h i hi).1, isOpen_biUnion fun i hi => (h i hi).2⟩ theorem isClopen_biUnion_finset {Y} {s : Finset Y} {f : Y → Set X} (h : ∀ i ∈ s, IsClopen <| f i) : IsClopen (⋃ i ∈ s, f i) := s.finite_toSet.isClopen_biUnion h theorem isClopen_iInter_of_finite {Y} [Finite Y] {s : Y → Set X} (h : ∀ i, IsClopen (s i)) : IsClopen (⋂ i, s i) := ⟨isClosed_iInter (forall_and.1 h).1, isOpen_iInter_of_finite (forall_and.1 h).2⟩ theorem Set.Finite.isClopen_biInter {Y} {s : Set Y} (hs : s.Finite) {f : Y → Set X} (h : ∀ i ∈ s, IsClopen (f i)) : IsClopen (⋂ i ∈ s, f i) := ⟨isClosed_biInter fun i hi => (h i hi).1, hs.isOpen_biInter fun i hi => (h i hi).2⟩ theorem isClopen_biInter_finset {Y} {s : Finset Y} {f : Y → Set X} (h : ∀ i ∈ s, IsClopen (f i)) : IsClopen (⋂ i ∈ s, f i) := s.finite_toSet.isClopen_biInter h theorem IsClopen.preimage {s : Set Y} (h : IsClopen s) {f : X → Y} (hf : Continuous f) : IsClopen (f ⁻¹' s) := ⟨h.1.preimage hf, h.2.preimage hf⟩ theorem ContinuousOn.preimage_isClopen_of_isClopen {f : X → Y} {s : Set X} {t : Set Y} (hf : ContinuousOn f s) (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ∩ f ⁻¹' t) := ⟨ContinuousOn.preimage_isClosed_of_isClosed hf hs.1 ht.1, ContinuousOn.isOpen_inter_preimage hf hs.2 ht.2⟩ /-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/ theorem isClopen_inter_of_disjoint_cover_clopen {s a b : Set X} (h : IsClopen s) (cover : s ⊆ a ∪ b) (ha : IsOpen a) (hb : IsOpen b) (hab : Disjoint a b) : IsClopen (s ∩ a) := by refine ⟨?_, IsOpen.inter h.2 ha⟩ have : IsClosed (s ∩ bᶜ) := IsClosed.inter h.1 (isClosed_compl_iff.2 hb) convert this using 1 refine (inter_subset_inter_right s hab.subset_compl_right).antisymm ?_ rintro x ⟨hx₁, hx₂⟩ exact ⟨hx₁, by simpa [not_mem_of_mem_compl hx₂] using cover hx₁⟩ @[simp] theorem isClopen_discrete [DiscreteTopology X] (s : Set X) : IsClopen s := ⟨isClosed_discrete _, isOpen_discrete _⟩ theorem isClopen_range_inl : IsClopen (range (Sum.inl : X → X ⊕ Y)) := ⟨isClosed_range_inl, isOpen_range_inl⟩ theorem isClopen_range_inr : IsClopen (range (Sum.inr : Y → X ⊕ Y)) := ⟨isClosed_range_inr, isOpen_range_inr⟩ theorem isClopen_range_sigmaMk {X : ι → Type*} [∀ i, TopologicalSpace (X i)] {i : ι} : IsClopen (Set.range (@Sigma.mk ι X i)) := ⟨closedEmbedding_sigmaMk.isClosed_range, openEmbedding_sigmaMk.isOpen_range⟩ protected theorem QuotientMap.isClopen_preimage {f : X → Y} (hf : QuotientMap f) {s : Set Y} : IsClopen (f ⁻¹' s) ↔ IsClopen s := and_congr hf.isClosed_preimage hf.isOpen_preimage theorem continuous_boolIndicator_iff_isClopen (U : Set X) : Continuous U.boolIndicator ↔ IsClopen U := by rw [continuous_bool_rng true, preimage_boolIndicator_true] theorem continuousOn_boolIndicator_iff_isClopen (s U : Set X) : ContinuousOn U.boolIndicator s ↔ IsClopen (((↑) : s → X) ⁻¹' U) := by rw [continuousOn_iff_continuous_restrict, ← continuous_boolIndicator_iff_isClopen] rfl end Clopen
Topology\ClopenBox.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Topology.CompactOpen import Mathlib.Topology.Sets.Closeds /-! # Clopen subsets in cartesian products In general, a clopen subset in a cartesian product of topological spaces cannot be written as a union of "clopen boxes", i.e. products of clopen subsets of the components (see [buzyakovaClopenBox] for counterexamples). However, when one of the factors is compact, a clopen subset can be written as such a union. Our argument in `TopologicalSpace.Clopens.exists_prod_subset` follows the one given in [buzyakovaClopenBox]. We deduce that in a product of compact spaces, a clopen subset is a finite union of clopen boxes, and use that to prove that the property of having countably many clopens is preserved by taking cartesian products of compact spaces (this is relevant to the theory of light profinite sets). ## References - [buzyakovaClopenBox]: *On clopen sets in Cartesian products*, 2001. - [engelking1989]: *General Topology*, 1989. -/ open Function Set Filter TopologicalSpace open scoped Topology variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [CompactSpace Y] theorem TopologicalSpace.Clopens.exists_prod_subset (W : Clopens (X × Y)) {a : X × Y} (h : a ∈ W) : ∃ U : Clopens X, a.1 ∈ U ∧ ∃ V : Clopens Y, a.2 ∈ V ∧ U ×ˢ V ≤ W := by have hp : Continuous (fun y : Y ↦ (a.1, y)) := Continuous.Prod.mk _ let V : Set Y := {y | (a.1, y) ∈ W} have hV : IsCompact V := (W.2.1.preimage hp).isCompact let U : Set X := {x | MapsTo (Prod.mk x) V W} have hUV : U ×ˢ V ⊆ W := fun ⟨_, _⟩ hw ↦ hw.1 hw.2 exact ⟨⟨U, (ContinuousMap.isClopen_setOf_mapsTo hV W.2).preimage (ContinuousMap.id (X × Y)).curry.2⟩, by simp [U, V, MapsTo], ⟨V, W.2.preimage hp⟩, h, hUV⟩ variable [CompactSpace X] /-- Every clopen set in a product of two compact spaces is a union of finitely many clopen boxes. -/ theorem TopologicalSpace.Clopens.exists_finset_eq_sup_prod (W : Clopens (X × Y)) : ∃ (I : Finset (Clopens X × Clopens Y)), W = I.sup fun i ↦ i.1 ×ˢ i.2 := by choose! U hxU V hxV hUV using fun x ↦ W.exists_prod_subset (a := x) rcases W.2.1.isCompact.elim_nhds_subcover (fun x ↦ U x ×ˢ V x) (fun x hx ↦ (U x ×ˢ V x).2.isOpen.mem_nhds ⟨hxU x hx, hxV x hx⟩) with ⟨I, hIW, hWI⟩ classical use I.image fun x ↦ (U x, V x) rw [Finset.sup_image] refine le_antisymm (fun x hx ↦ ?_) (Finset.sup_le fun x hx ↦ ?_) · rcases Set.mem_iUnion₂.1 (hWI hx) with ⟨i, hi, hxi⟩ exact SetLike.le_def.1 (Finset.le_sup hi) hxi · exact hUV _ <| hIW _ hx lemma TopologicalSpace.Clopens.surjective_finset_sup_prod : Surjective fun I : Finset (Clopens X × Clopens Y) ↦ I.sup fun i ↦ i.1 ×ˢ i.2 := fun W ↦ let ⟨I, hI⟩ := W.exists_finset_eq_sup_prod; ⟨I, hI.symm⟩ instance TopologicalSpace.Clopens.countable_prod [Countable (Clopens X)] [Countable (Clopens Y)] : Countable (Clopens (X × Y)) := surjective_finset_sup_prod.countable instance TopologicalSpace.Clopens.finite_prod [Finite (Clopens X)] [Finite (Clopens Y)] : Finite (Clopens (X × Y)) := by cases nonempty_fintype (Clopens X) cases nonempty_fintype (Clopens Y) exact .of_surjective _ surjective_finset_sup_prod lemma TopologicalSpace.Clopens.countable_iff_second_countable [T2Space X] [TotallyDisconnectedSpace X] : Countable (Clopens X) ↔ SecondCountableTopology X := by refine ⟨fun h ↦ ⟨{s : Set X | IsClopen s}, ?_, ?_⟩, fun h ↦ ?_⟩ · let f : {s : Set X | IsClopen s} → Clopens X := fun s ↦ ⟨s.1, s.2⟩ exact (injective_of_le_imp_le f fun a ↦ a).countable · apply IsTopologicalBasis.eq_generateFrom exact loc_compact_Haus_tot_disc_of_zero_dim · have : ∀ (s : Clopens X), ∃ (t : Finset (countableBasis X)), s.1 = t.toSet.sUnion := fun s ↦ eq_sUnion_finset_of_isTopologicalBasis_of_isCompact_open _ (isBasis_countableBasis X) s.1 s.2.1.isCompact s.2.2 let f : Clopens X → Finset (countableBasis X) := fun s ↦ (this s).choose have hf : f.Injective := by intro s t (h : Exists.choose _ = Exists.choose _) ext1; change s.carrier = t.carrier rw [(this s).choose_spec, (this t).choose_spec, h] exact hf.countable
Topology\CompactOpen.lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import Mathlib.Topology.ContinuousFunction.Basic /-! # The compact-open topology In this file, we define the compact-open topology on the set of continuous maps between two topological spaces. ## Main definitions * `ContinuousMap.compactOpen` is the compact-open topology on `C(X, Y)`. It is declared as an instance. * `ContinuousMap.coev` is the coevaluation map `Y → C(X, Y × X)`. It is always continuous. * `ContinuousMap.curry` is the currying map `C(X × Y, Z) → C(X, C(Y, Z))`. This map always exists and it is continuous as long as `X × Y` is locally compact. * `ContinuousMap.uncurry` is the uncurrying map `C(X, C(Y, Z)) → C(X × Y, Z)`. For this map to exist, we need `Y` to be locally compact. If `X` is also locally compact, then this map is continuous. * `Homeomorph.curry` combines the currying and uncurrying operations into a homeomorphism `C(X × Y, Z) ≃ₜ C(X, C(Y, Z))`. This homeomorphism exists if `X` and `Y` are locally compact. ## Tags compact-open, curry, function space -/ open Set Filter TopologicalSpace open scoped Topology namespace ContinuousMap section CompactOpen variable {α X Y Z T : Type*} variable [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] [TopologicalSpace T] variable {K : Set X} {U : Set Y} /-- The compact-open topology on the space of continuous maps `C(X, Y)`. -/ instance compactOpen : TopologicalSpace C(X, Y) := .generateFrom <| image2 (fun K U ↦ {f | MapsTo f K U}) {K | IsCompact K} {U | IsOpen U} /-- Definition of `ContinuousMap.compactOpen`. -/ theorem compactOpen_eq : @compactOpen X Y _ _ = .generateFrom (image2 (fun K U ↦ {f | MapsTo f K U}) {K | IsCompact K} {t | IsOpen t}) := rfl theorem isOpen_setOf_mapsTo (hK : IsCompact K) (hU : IsOpen U) : IsOpen {f : C(X, Y) | MapsTo f K U} := isOpen_generateFrom_of_mem <| mem_image2_of_mem hK hU lemma eventually_mapsTo {f : C(X, Y)} (hK : IsCompact K) (hU : IsOpen U) (h : MapsTo f K U) : ∀ᶠ g : C(X, Y) in 𝓝 f, MapsTo g K U := (isOpen_setOf_mapsTo hK hU).mem_nhds h lemma nhds_compactOpen (f : C(X, Y)) : 𝓝 f = ⨅ (K : Set X) (_ : IsCompact K) (U : Set Y) (_ : IsOpen U) (_ : MapsTo f K U), 𝓟 {g : C(X, Y) | MapsTo g K U} := by simp_rw [compactOpen_eq, nhds_generateFrom, mem_setOf_eq, @and_comm (f ∈ _), iInf_and, ← image_prod, iInf_image, biInf_prod, mem_setOf_eq] lemma tendsto_nhds_compactOpen {l : Filter α} {f : α → C(Y, Z)} {g : C(Y, Z)} : Tendsto f l (𝓝 g) ↔ ∀ K, IsCompact K → ∀ U, IsOpen U → MapsTo g K U → ∀ᶠ a in l, MapsTo (f a) K U := by simp [nhds_compactOpen] lemma continuous_compactOpen {f : X → C(Y, Z)} : Continuous f ↔ ∀ K, IsCompact K → ∀ U, IsOpen U → IsOpen {x | MapsTo (f x) K U} := continuous_generateFrom_iff.trans forall_image2_iff section Functorial /-- `C(X, ·)` is a functor. -/ theorem continuous_comp (g : C(Y, Z)) : Continuous (ContinuousMap.comp g : C(X, Y) → C(X, Z)) := continuous_compactOpen.2 fun _K hK _U hU ↦ isOpen_setOf_mapsTo hK (hU.preimage g.2) /-- If `g : C(Y, Z)` is a topology inducing map, then the composition `ContinuousMap.comp g : C(X, Y) → C(X, Z)` is a topology inducing map too. -/ theorem inducing_comp (g : C(Y, Z)) (hg : Inducing g) : Inducing (g.comp : C(X, Y) → C(X, Z)) where induced := by simp only [compactOpen_eq, induced_generateFrom_eq, image_image2, hg.setOf_isOpen, image2_image_right, MapsTo, mem_preimage, preimage_setOf_eq, comp_apply] /-- If `g : C(Y, Z)` is a topological embedding, then the composition `ContinuousMap.comp g : C(X, Y) → C(X, Z)` is an embedding too. -/ theorem embedding_comp (g : C(Y, Z)) (hg : Embedding g) : Embedding (g.comp : C(X, Y) → C(X, Z)) := ⟨inducing_comp g hg.1, fun _ _ ↦ (cancel_left hg.2).1⟩ /-- `C(·, Z)` is a functor. -/ theorem continuous_comp_left (f : C(X, Y)) : Continuous (fun g => g.comp f : C(Y, Z) → C(X, Z)) := continuous_compactOpen.2 fun K hK U hU ↦ by simpa only [mapsTo_image_iff] using isOpen_setOf_mapsTo (hK.image f.2) hU /-- Any pair of homeomorphisms `X ≃ₜ Z` and `Y ≃ₜ T` gives rise to a homeomorphism `C(X, Y) ≃ₜ C(Z, T)`. -/ protected def _root_.Homeomorph.arrowCongr (φ : X ≃ₜ Z) (ψ : Y ≃ₜ T) : C(X, Y) ≃ₜ C(Z, T) where toFun f := .comp ψ <| f.comp φ.symm invFun f := .comp ψ.symm <| f.comp φ left_inv f := ext fun _ ↦ ψ.left_inv (f _) |>.trans <| congrArg f <| φ.left_inv _ right_inv f := ext fun _ ↦ ψ.right_inv (f _) |>.trans <| congrArg f <| φ.right_inv _ continuous_toFun := continuous_comp _ |>.comp <| continuous_comp_left _ continuous_invFun := continuous_comp _ |>.comp <| continuous_comp_left _ variable [LocallyCompactPair Y Z] /-- Composition is a continuous map from `C(X, Y) × C(Y, Z)` to `C(X, Z)`, provided that `Y` is locally compact. This is Prop. 9 of Chap. X, §3, №. 4 of Bourbaki's *Topologie Générale*. -/ theorem continuous_comp' : Continuous fun x : C(X, Y) × C(Y, Z) => x.2.comp x.1 := by simp_rw [continuous_iff_continuousAt, ContinuousAt, tendsto_nhds_compactOpen] intro ⟨f, g⟩ K hK U hU (hKU : MapsTo (g ∘ f) K U) obtain ⟨L, hKL, hLc, hLU⟩ : ∃ L ∈ 𝓝ˢ (f '' K), IsCompact L ∧ MapsTo g L U := exists_mem_nhdsSet_isCompact_mapsTo g.continuous (hK.image f.continuous) hU (mapsTo_image_iff.2 hKU) rw [← subset_interior_iff_mem_nhdsSet, ← mapsTo'] at hKL exact ((eventually_mapsTo hK isOpen_interior hKL).prod_nhds (eventually_mapsTo hLc hU hLU)).mono fun ⟨f', g'⟩ ⟨hf', hg'⟩ ↦ hg'.comp <| hf'.mono_right interior_subset lemma _root_.Filter.Tendsto.compCM {α : Type*} {l : Filter α} {g : α → C(Y, Z)} {g₀ : C(Y, Z)} {f : α → C(X, Y)} {f₀ : C(X, Y)} (hg : Tendsto g l (𝓝 g₀)) (hf : Tendsto f l (𝓝 f₀)) : Tendsto (fun a ↦ (g a).comp (f a)) l (𝓝 (g₀.comp f₀)) := (continuous_comp'.tendsto (f₀, g₀)).comp (hf.prod_mk_nhds hg) variable {X' : Type*} [TopologicalSpace X'] {a : X'} {g : X' → C(Y, Z)} {f : X' → C(X, Y)} {s : Set X'} nonrec lemma _root_.ContinuousAt.compCM (hg : ContinuousAt g a) (hf : ContinuousAt f a) : ContinuousAt (fun x ↦ (g x).comp (f x)) a := hg.compCM hf nonrec lemma _root_.ContinuousWithinAt.compCM (hg : ContinuousWithinAt g s a) (hf : ContinuousWithinAt f s a) : ContinuousWithinAt (fun x ↦ (g x).comp (f x)) s a := hg.compCM hf lemma _root_.ContinuousOn.compCM (hg : ContinuousOn g s) (hf : ContinuousOn f s) : ContinuousOn (fun x ↦ (g x).comp (f x)) s := fun a ha ↦ (hg a ha).compCM (hf a ha) lemma _root_.Continuous.compCM (hg : Continuous g) (hf : Continuous f) : Continuous fun x => (g x).comp (f x) := continuous_comp'.comp (hf.prod_mk hg) @[deprecated _root_.Continuous.compCM (since := "2024-01-30")] lemma continuous.comp' (hf : Continuous f) (hg : Continuous g) : Continuous fun x => (g x).comp (f x) := hg.compCM hf end Functorial section Ev /-- The evaluation map `C(X, Y) × X → Y` is continuous if `X, Y` is a locally compact pair of spaces. -/ @[continuity] theorem continuous_eval [LocallyCompactPair X Y] : Continuous fun p : C(X, Y) × X => p.1 p.2 := by simp_rw [continuous_iff_continuousAt, ContinuousAt, (nhds_basis_opens _).tendsto_right_iff] rintro ⟨f, x⟩ U ⟨hx : f x ∈ U, hU : IsOpen U⟩ rcases exists_mem_nhds_isCompact_mapsTo f.continuous (hU.mem_nhds hx) with ⟨K, hxK, hK, hKU⟩ filter_upwards [prod_mem_nhds (eventually_mapsTo hK hU hKU) hxK] using fun _ h ↦ h.1 h.2 @[deprecated (since := "2023-12-26")] alias continuous_eval' := continuous_eval /-- Evaluation of a continuous map `f` at a point `x` is continuous in `f`. Porting note: merged `continuous_eval_const` with `continuous_eval_const'` removing unneeded assumptions. -/ @[continuity] theorem continuous_eval_const (a : X) : Continuous fun f : C(X, Y) => f a := continuous_def.2 fun U hU ↦ by simpa using isOpen_setOf_mapsTo (isCompact_singleton (x := a)) hU /-- Coercion from `C(X, Y)` with compact-open topology to `X → Y` with pointwise convergence topology is a continuous map. Porting note: merged `continuous_coe` with `continuous_coe'` removing unneeded assumptions. -/ theorem continuous_coe : Continuous ((⇑) : C(X, Y) → (X → Y)) := continuous_pi continuous_eval_const lemma isClosed_setOf_mapsTo {t : Set Y} (ht : IsClosed t) (s : Set X) : IsClosed {f : C(X, Y) | MapsTo f s t} := ht.setOf_mapsTo fun _ _ ↦ continuous_eval_const _ lemma isClopen_setOf_mapsTo (hK : IsCompact K) (hU : IsClopen U) : IsClopen {f : C(X, Y) | MapsTo f K U} := ⟨isClosed_setOf_mapsTo hU.isClosed K, isOpen_setOf_mapsTo hK hU.isOpen⟩ @[norm_cast] lemma specializes_coe {f g : C(X, Y)} : ⇑f ⤳ ⇑g ↔ f ⤳ g := by refine ⟨fun h ↦ ?_, fun h ↦ h.map continuous_coe⟩ suffices ∀ K, IsCompact K → ∀ U, IsOpen U → MapsTo g K U → MapsTo f K U by simpa [specializes_iff_pure, nhds_compactOpen] exact fun K _ U hU hg x hx ↦ (h.map (continuous_apply x)).mem_open hU (hg hx) @[norm_cast] lemma inseparable_coe {f g : C(X, Y)} : Inseparable (f : X → Y) g ↔ Inseparable f g := by simp only [inseparable_iff_specializes_and, specializes_coe] instance [T0Space Y] : T0Space C(X, Y) := t0Space_of_injective_of_continuous DFunLike.coe_injective continuous_coe instance [R0Space Y] : R0Space C(X, Y) where specializes_symmetric f g h := by rw [← specializes_coe] at h ⊢ exact h.symm instance [T1Space Y] : T1Space C(X, Y) := t1Space_of_injective_of_continuous DFunLike.coe_injective continuous_coe instance [R1Space Y] : R1Space C(X, Y) := .of_continuous_specializes_imp continuous_coe fun _ _ ↦ specializes_coe.1 instance [T2Space Y] : T2Space C(X, Y) := inferInstance instance [RegularSpace Y] : RegularSpace C(X, Y) := .of_lift'_closure_le fun f ↦ by rw [← tendsto_id', tendsto_nhds_compactOpen] intro K hK U hU hf rcases (hK.image f.continuous).exists_isOpen_closure_subset (hU.mem_nhdsSet.2 hf.image_subset) with ⟨V, hVo, hKV, hVU⟩ filter_upwards [mem_lift' (eventually_mapsTo hK hVo (mapsTo'.2 hKV))] with g hg refine ((isClosed_setOf_mapsTo isClosed_closure K).closure_subset ?_).mono_right hVU exact closure_mono (fun _ h ↦ h.mono_right subset_closure) hg instance [T3Space Y] : T3Space C(X, Y) := inferInstance end Ev section InfInduced /-- For any subset `s` of `X`, the restriction of continuous functions to `s` is continuous as a function from `C(X, Y)` to `C(s, Y)` with their respective compact-open topologies. -/ theorem continuous_restrict (s : Set X) : Continuous fun F : C(X, Y) => F.restrict s := continuous_comp_left <| restrict s <| .id X theorem compactOpen_le_induced (s : Set X) : (ContinuousMap.compactOpen : TopologicalSpace C(X, Y)) ≤ .induced (restrict s) ContinuousMap.compactOpen := (continuous_restrict s).le_induced /-- The compact-open topology on `C(X, Y)` is equal to the infimum of the compact-open topologies on `C(s, Y)` for `s` a compact subset of `X`. The key point of the proof is that for every compact set `K`, the universal set `Set.univ : Set K` is a compact set as well. -/ theorem compactOpen_eq_iInf_induced : (ContinuousMap.compactOpen : TopologicalSpace C(X, Y)) = ⨅ (K : Set X) (_ : IsCompact K), .induced (.restrict K) ContinuousMap.compactOpen := by refine le_antisymm (le_iInf₂ fun s _ ↦ compactOpen_le_induced s) ?_ refine le_generateFrom <| forall_image2_iff.2 fun K (hK : IsCompact K) U hU ↦ ?_ refine TopologicalSpace.le_def.1 (iInf₂_le K hK) _ ?_ convert isOpen_induced (isOpen_setOf_mapsTo (isCompact_iff_isCompact_univ.1 hK) hU) simp [mapsTo_univ_iff, Subtype.forall, MapsTo] @[deprecated (since := "2024-03-05")] alias compactOpen_eq_sInf_induced := compactOpen_eq_iInf_induced theorem nhds_compactOpen_eq_iInf_nhds_induced (f : C(X, Y)) : 𝓝 f = ⨅ (s) (hs : IsCompact s), (𝓝 (f.restrict s)).comap (ContinuousMap.restrict s) := by rw [compactOpen_eq_iInf_induced] simp only [nhds_iInf, nhds_induced] @[deprecated (since := "2024-03-05")] alias nhds_compactOpen_eq_sInf_nhds_induced := nhds_compactOpen_eq_iInf_nhds_induced theorem tendsto_compactOpen_restrict {ι : Type*} {l : Filter ι} {F : ι → C(X, Y)} {f : C(X, Y)} (hFf : Filter.Tendsto F l (𝓝 f)) (s : Set X) : Tendsto (fun i => (F i).restrict s) l (𝓝 (f.restrict s)) := (continuous_restrict s).continuousAt.tendsto.comp hFf theorem tendsto_compactOpen_iff_forall {ι : Type*} {l : Filter ι} (F : ι → C(X, Y)) (f : C(X, Y)) : Tendsto F l (𝓝 f) ↔ ∀ K, IsCompact K → Tendsto (fun i => (F i).restrict K) l (𝓝 (f.restrict K)) := by rw [compactOpen_eq_iInf_induced] simp [nhds_iInf, nhds_induced, Filter.tendsto_comap_iff, Function.comp] /-- A family `F` of functions in `C(X, Y)` converges in the compact-open topology, if and only if it converges in the compact-open topology on each compact subset of `X`. -/ theorem exists_tendsto_compactOpen_iff_forall [WeaklyLocallyCompactSpace X] [T2Space Y] {ι : Type*} {l : Filter ι} [Filter.NeBot l] (F : ι → C(X, Y)) : (∃ f, Filter.Tendsto F l (𝓝 f)) ↔ ∀ s : Set X, IsCompact s → ∃ f, Filter.Tendsto (fun i => (F i).restrict s) l (𝓝 f) := by constructor · rintro ⟨f, hf⟩ s _ exact ⟨f.restrict s, tendsto_compactOpen_restrict hf s⟩ · intro h choose f hf using h -- By uniqueness of limits in a `T2Space`, since `fun i ↦ F i x` tends to both `f s₁ hs₁ x` and -- `f s₂ hs₂ x`, we have `f s₁ hs₁ x = f s₂ hs₂ x` have h : ∀ (s₁) (hs₁ : IsCompact s₁) (s₂) (hs₂ : IsCompact s₂) (x : X) (hxs₁ : x ∈ s₁) (hxs₂ : x ∈ s₂), f s₁ hs₁ ⟨x, hxs₁⟩ = f s₂ hs₂ ⟨x, hxs₂⟩ := by rintro s₁ hs₁ s₂ hs₂ x hxs₁ hxs₂ haveI := isCompact_iff_compactSpace.mp hs₁ haveI := isCompact_iff_compactSpace.mp hs₂ have h₁ := (continuous_eval_const (⟨x, hxs₁⟩ : s₁)).continuousAt.tendsto.comp (hf s₁ hs₁) have h₂ := (continuous_eval_const (⟨x, hxs₂⟩ : s₂)).continuousAt.tendsto.comp (hf s₂ hs₂) exact tendsto_nhds_unique h₁ h₂ -- So glue the `f s hs` together and prove that this glued function `f₀` is a limit on each -- compact set `s` refine ⟨liftCover' _ _ h exists_compact_mem_nhds, ?_⟩ rw [tendsto_compactOpen_iff_forall] intro s hs rw [liftCover_restrict'] exact hf s hs end InfInduced section Coev variable (X Y) /-- The coevaluation map `Y → C(X, Y × X)` sending a point `x : Y` to the continuous function on `X` sending `y` to `(x, y)`. -/ @[simps (config := .asFn)] def coev (b : Y) : C(X, Y × X) := { toFun := Prod.mk b } variable {X Y} theorem image_coev {y : Y} (s : Set X) : coev X Y y '' s = {y} ×ˢ s := by simp /-- The coevaluation map `Y → C(X, Y × X)` is continuous (always). -/ theorem continuous_coev : Continuous (coev X Y) := by have : ∀ {a K U}, MapsTo (coev X Y a) K U ↔ {a} ×ˢ K ⊆ U := by simp [mapsTo'] simp only [continuous_iff_continuousAt, ContinuousAt, tendsto_nhds_compactOpen, this] intro x K hK U hU hKU rcases generalized_tube_lemma isCompact_singleton hK hU hKU with ⟨V, W, hV, -, hxV, hKW, hVWU⟩ filter_upwards [hV.mem_nhds (hxV rfl)] with a ha exact (prod_mono (singleton_subset_iff.mpr ha) hKW).trans hVWU end Coev section Curry /-- The curried form of a continuous map `α × β → γ` as a continuous map `α → C(β, γ)`. If `a × β` is locally compact, this is continuous. If `α` and `β` are both locally compact, then this is a homeomorphism, see `Homeomorph.curry`. -/ def curry (f : C(X × Y, Z)) : C(X, C(Y, Z)) where toFun a := ⟨Function.curry f a, f.continuous.comp <| by fun_prop⟩ continuous_toFun := (continuous_comp f).comp continuous_coev @[simp] theorem curry_apply (f : C(X × Y, Z)) (a : X) (b : Y) : f.curry a b = f (a, b) := rfl /-- Auxiliary definition, see `ContinuousMap.curry` and `Homeomorph.curry`. -/ @[deprecated ContinuousMap.curry (since := "2024-03-05")] def curry' (f : C(X × Y, Z)) (a : X) : C(Y, Z) := curry f a set_option linter.deprecated false in /-- If a map `α × β → γ` is continuous, then its curried form `α → C(β, γ)` is continuous. -/ @[deprecated ContinuousMap.curry (since := "2024-03-05")] theorem continuous_curry' (f : C(X × Y, Z)) : Continuous (curry' f) := (curry f).continuous /-- To show continuity of a map `α → C(β, γ)`, it suffices to show that its uncurried form `α × β → γ` is continuous. -/ theorem continuous_of_continuous_uncurry (f : X → C(Y, Z)) (h : Continuous (Function.uncurry fun x y => f x y)) : Continuous f := (curry ⟨_, h⟩).2 /-- The currying process is a continuous map between function spaces. -/ theorem continuous_curry [LocallyCompactSpace (X × Y)] : Continuous (curry : C(X × Y, Z) → C(X, C(Y, Z))) := by apply continuous_of_continuous_uncurry apply continuous_of_continuous_uncurry rw [← (Homeomorph.prodAssoc _ _ _).symm.comp_continuous_iff'] exact continuous_eval /-- The uncurried form of a continuous map `X → C(Y, Z)` is a continuous map `X × Y → Z`. -/ theorem continuous_uncurry_of_continuous [LocallyCompactSpace Y] (f : C(X, C(Y, Z))) : Continuous (Function.uncurry fun x y => f x y) := continuous_eval.comp <| f.continuous.prod_map continuous_id /-- The uncurried form of a continuous map `X → C(Y, Z)` as a continuous map `X × Y → Z` (if `Y` is locally compact). If `X` is also locally compact, then this is a homeomorphism between the two function spaces, see `Homeomorph.curry`. -/ @[simps] def uncurry [LocallyCompactSpace Y] (f : C(X, C(Y, Z))) : C(X × Y, Z) := ⟨_, continuous_uncurry_of_continuous f⟩ /-- The uncurrying process is a continuous map between function spaces. -/ theorem continuous_uncurry [LocallyCompactSpace X] [LocallyCompactSpace Y] : Continuous (uncurry : C(X, C(Y, Z)) → C(X × Y, Z)) := by apply continuous_of_continuous_uncurry rw [← (Homeomorph.prodAssoc _ _ _).comp_continuous_iff'] apply continuous_eval.comp (continuous_eval.prod_map continuous_id) /-- The family of constant maps: `Y → C(X, Y)` as a continuous map. -/ def const' : C(Y, C(X, Y)) := curry ContinuousMap.fst @[simp] theorem coe_const' : (const' : Y → C(X, Y)) = const X := rfl theorem continuous_const' : Continuous (const X : Y → C(X, Y)) := const'.continuous end Curry end CompactOpen end ContinuousMap open ContinuousMap namespace Homeomorph variable {X : Type*} {Y : Type*} {Z : Type*} variable [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] /-- Currying as a homeomorphism between the function spaces `C(X × Y, Z)` and `C(X, C(Y, Z))`. -/ def curry [LocallyCompactSpace X] [LocallyCompactSpace Y] : C(X × Y, Z) ≃ₜ C(X, C(Y, Z)) := ⟨⟨ContinuousMap.curry, uncurry, by intro; ext; rfl, by intro; ext; rfl⟩, continuous_curry, continuous_uncurry⟩ /-- If `X` has a single element, then `Y` is homeomorphic to `C(X, Y)`. -/ def continuousMapOfUnique [Unique X] : Y ≃ₜ C(X, Y) where toFun := const X invFun f := f default left_inv _ := rfl right_inv f := by ext x rw [Unique.eq_default x] rfl continuous_toFun := continuous_const' continuous_invFun := continuous_eval_const _ @[simp] theorem continuousMapOfUnique_apply [Unique X] (y : Y) (x : X) : continuousMapOfUnique y x = y := rfl @[simp] theorem continuousMapOfUnique_symm_apply [Unique X] (f : C(X, Y)) : continuousMapOfUnique.symm f = f default := rfl end Homeomorph section QuotientMap variable {X₀ X Y Z : Type*} [TopologicalSpace X₀] [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] [LocallyCompactSpace Y] {f : X₀ → X} theorem QuotientMap.continuous_lift_prod_left (hf : QuotientMap f) {g : X × Y → Z} (hg : Continuous fun p : X₀ × Y => g (f p.1, p.2)) : Continuous g := by let Gf : C(X₀, C(Y, Z)) := ContinuousMap.curry ⟨_, hg⟩ have h : ∀ x : X, Continuous fun y => g (x, y) := by intro x obtain ⟨x₀, rfl⟩ := hf.surjective x exact (Gf x₀).continuous let G : X → C(Y, Z) := fun x => ⟨_, h x⟩ have : Continuous G := by rw [hf.continuous_iff] exact Gf.continuous exact ContinuousMap.continuous_uncurry_of_continuous ⟨G, this⟩ theorem QuotientMap.continuous_lift_prod_right (hf : QuotientMap f) {g : Y × X → Z} (hg : Continuous fun p : Y × X₀ => g (p.1, f p.2)) : Continuous g := by have : Continuous fun p : X₀ × Y => g ((Prod.swap p).1, f (Prod.swap p).2) := hg.comp continuous_swap have : Continuous fun p : X₀ × Y => (g ∘ Prod.swap) (f p.1, p.2) := this exact (hf.continuous_lift_prod_left this).comp continuous_swap end QuotientMap
Topology\CompletelyRegular.lean
/- Copyright (c) 2023 Matias Heikkilä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Matias Heikkilä -/ import Mathlib.Topology.UrysohnsLemma import Mathlib.Topology.UnitInterval import Mathlib.Topology.StoneCech /-! # Completely regular topological spaces. This file defines `CompletelyRegularSpace` and `T35Space`. ## Main definitions * `CompletelyRegularSpace`: A completely regular space `X` is such that each closed set `K ⊆ X` and a point `x ∈ Kᶜ`, there is a continuous function `f` from `X` to the unit interval, so that `f x = 0` and `f k = 1` for all `k ∈ K`. A completely regular space is a regular space, and a normal space is a completely regular space. * `T35Space`: A T₃.₅ space is a completely regular space that is also T₁. A T₃.₅ space is a T₃ space and a T₄ space is a T₃.₅ space. ## Main results ### Completely regular spaces * `CompletelyRegularSpace.regularSpace`: A completely regular space is a regular space. * `NormalSpace.completelyRegularSpace`: A normal space is a completely regular space. ### T₃.₅ spaces * `T35Space.instT3Space`: A T₃.₅ space is a T₃ space. * `T4Space.instT35Space`: A T₄ space is a T₃.₅ space. ## Implementation notes The present definition `CompletelyRegularSpace` is a slight modification of the one given in [russell1974]. There it's assumed that any point `x ∈ Kᶜ` is separated from the closed set `K` by a continuous *real* valued function `f` (as opposed to `f` being unit-interval-valued). This can be converted to the present definition by replacing a real-valued `f` by `h ∘ g ∘ f`, with `g : x ↦ max(x, 0)` and `h : x ↦ min(x, 1)`. Some sources (e.g. [russell1974]) also assume that a completely regular space is T₁. Here a completely regular space that is also T₁ is called a T₃.₅ space. ## References * [Russell C. Walker, *The Stone-Čech Compactification*][russell1974] -/ universe u noncomputable section open Set Topology Filter unitInterval variable {X : Type u} [TopologicalSpace X] [T1Space X] /-- A space is completely regular if points can be separated from closed sets via continuous functions to the unit interval. -/ @[mk_iff] class CompletelyRegularSpace (X : Type u) [TopologicalSpace X] : Prop where completely_regular : ∀ (x : X), ∀ K : Set X, IsClosed K → x ∉ K → ∃ f : X → I, Continuous f ∧ f x = 0 ∧ EqOn f 1 K instance CompletelyRegularSpace.instRegularSpace [CompletelyRegularSpace X] : RegularSpace X := by rw [regularSpace_iff] intro s a hs ha obtain ⟨f, cf, hf, hhf⟩ := CompletelyRegularSpace.completely_regular a s hs ha apply disjoint_of_map (f := f) apply Disjoint.mono (cf.tendsto_nhdsSet_nhds hhf) cf.continuousAt exact disjoint_nhds_nhds.mpr (hf.symm ▸ zero_ne_one).symm instance NormalSpace.instCompletelyRegularSpace [NormalSpace X] : CompletelyRegularSpace X := by rw [completelyRegularSpace_iff] intro x K hK hx have cx : IsClosed {x} := T1Space.t1 x have d : Disjoint {x} K := by rwa [Set.disjoint_iff, subset_empty_iff, singleton_inter_eq_empty] let ⟨⟨f, cf⟩, hfx, hfK, hficc⟩ := exists_continuous_zero_one_of_isClosed cx hK d let g : X → I := fun x => ⟨f x, hficc x⟩ have cg : Continuous g := cf.subtype_mk hficc have hgx : g x = 0 := Subtype.ext (hfx (mem_singleton_iff.mpr (Eq.refl x))) have hgK : EqOn g 1 K := fun k hk => Subtype.ext (hfK hk) exact ⟨g, cg, hgx, hgK⟩ /-- A T₃.₅ space is a completely regular space that is also T1. -/ @[mk_iff] class T35Space (X : Type u) [TopologicalSpace X] extends T1Space X, CompletelyRegularSpace X : Prop instance T35Space.instT3space [T35Space X] : T3Space X := {} instance T4Space.instT35Space [T4Space X] : T35Space X := {} lemma separatesPoints_continuous_of_t35Space [T35Space X] : SeparatesPoints (Continuous : Set (X → ℝ)) := by intro x y x_ne_y obtain ⟨f, f_cont, f_zero, f_one⟩ := CompletelyRegularSpace.completely_regular x {y} isClosed_singleton x_ne_y exact ⟨fun x ↦ f x, continuous_subtype_val.comp f_cont, by aesop⟩ lemma separatesPoints_continuous_of_t35Space_Icc [T35Space X] : SeparatesPoints (Continuous : Set (X → I)) := by intro x y x_ne_y obtain ⟨f, f_cont, f_zero, f_one⟩ := CompletelyRegularSpace.completely_regular x {y} isClosed_singleton x_ne_y exact ⟨f, f_cont, by aesop⟩ lemma injective_stoneCechUnit_of_t35Space [T35Space X] : Function.Injective (stoneCechUnit : X → StoneCech X) := by intros a b hab contrapose hab obtain ⟨f, fc, fab⟩ := separatesPoints_continuous_of_t35Space_Icc hab exact fun q ↦ fab (eq_if_stoneCechUnit_eq fc q)
Topology\Constructions.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import Mathlib.Topology.Maps.Basic import Mathlib.Topology.NhdsSet /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable section open Topology TopologicalSpace Set Filter Function universe u v variable {X : Type u} {Y : Type v} {Z W ε ζ : Type*} section Constructions instance {r : X → X → Prop} [t : TopologicalSpace X] : TopologicalSpace (Quot r) := coinduced (Quot.mk r) t instance instTopologicalSpaceQuotient {s : Setoid X} [t : TopologicalSpace X] : TopologicalSpace (Quotient s) := coinduced Quotient.mk' t instance instTopologicalSpaceProd [t₁ : TopologicalSpace X] [t₂ : TopologicalSpace Y] : TopologicalSpace (X × Y) := induced Prod.fst t₁ ⊓ induced Prod.snd t₂ instance instTopologicalSpaceSum [t₁ : TopologicalSpace X] [t₂ : TopologicalSpace Y] : TopologicalSpace (X ⊕ Y) := coinduced Sum.inl t₁ ⊔ coinduced Sum.inr t₂ instance instTopologicalSpaceSigma {ι : Type*} {X : ι → Type v} [t₂ : ∀ i, TopologicalSpace (X i)] : TopologicalSpace (Sigma X) := ⨆ i, coinduced (Sigma.mk i) (t₂ i) instance Pi.topologicalSpace {ι : Type*} {Y : ι → Type v} [t₂ : (i : ι) → TopologicalSpace (Y i)] : TopologicalSpace ((i : ι) → Y i) := ⨅ i, induced (fun f => f i) (t₂ i) instance ULift.topologicalSpace [t : TopologicalSpace X] : TopologicalSpace (ULift.{v, u} X) := t.induced ULift.down /-! ### `Additive`, `Multiplicative` The topology on those type synonyms is inherited without change. -/ section variable [TopologicalSpace X] open Additive Multiplicative instance : TopologicalSpace (Additive X) := ‹TopologicalSpace X› instance : TopologicalSpace (Multiplicative X) := ‹TopologicalSpace X› instance [DiscreteTopology X] : DiscreteTopology (Additive X) := ‹DiscreteTopology X› instance [DiscreteTopology X] : DiscreteTopology (Multiplicative X) := ‹DiscreteTopology X› theorem continuous_ofMul : Continuous (ofMul : X → Additive X) := continuous_id theorem continuous_toMul : Continuous (toMul : Additive X → X) := continuous_id theorem continuous_ofAdd : Continuous (ofAdd : X → Multiplicative X) := continuous_id theorem continuous_toAdd : Continuous (toAdd : Multiplicative X → X) := continuous_id theorem isOpenMap_ofMul : IsOpenMap (ofMul : X → Additive X) := IsOpenMap.id theorem isOpenMap_toMul : IsOpenMap (toMul : Additive X → X) := IsOpenMap.id theorem isOpenMap_ofAdd : IsOpenMap (ofAdd : X → Multiplicative X) := IsOpenMap.id theorem isOpenMap_toAdd : IsOpenMap (toAdd : Multiplicative X → X) := IsOpenMap.id theorem isClosedMap_ofMul : IsClosedMap (ofMul : X → Additive X) := IsClosedMap.id theorem isClosedMap_toMul : IsClosedMap (toMul : Additive X → X) := IsClosedMap.id theorem isClosedMap_ofAdd : IsClosedMap (ofAdd : X → Multiplicative X) := IsClosedMap.id theorem isClosedMap_toAdd : IsClosedMap (toAdd : Multiplicative X → X) := IsClosedMap.id theorem nhds_ofMul (x : X) : 𝓝 (ofMul x) = map ofMul (𝓝 x) := rfl theorem nhds_ofAdd (x : X) : 𝓝 (ofAdd x) = map ofAdd (𝓝 x) := rfl theorem nhds_toMul (x : Additive X) : 𝓝 (toMul x) = map toMul (𝓝 x) := rfl theorem nhds_toAdd (x : Multiplicative X) : 𝓝 (toAdd x) = map toAdd (𝓝 x) := rfl end /-! ### Order dual The topology on this type synonym is inherited without change. -/ section variable [TopologicalSpace X] open OrderDual instance OrderDual.instTopologicalSpace : TopologicalSpace Xᵒᵈ := ‹_› instance OrderDual.instDiscreteTopology [DiscreteTopology X] : DiscreteTopology Xᵒᵈ := ‹_› theorem continuous_toDual : Continuous (toDual : X → Xᵒᵈ) := continuous_id theorem continuous_ofDual : Continuous (ofDual : Xᵒᵈ → X) := continuous_id theorem isOpenMap_toDual : IsOpenMap (toDual : X → Xᵒᵈ) := IsOpenMap.id theorem isOpenMap_ofDual : IsOpenMap (ofDual : Xᵒᵈ → X) := IsOpenMap.id theorem isClosedMap_toDual : IsClosedMap (toDual : X → Xᵒᵈ) := IsClosedMap.id theorem isClosedMap_ofDual : IsClosedMap (ofDual : Xᵒᵈ → X) := IsClosedMap.id theorem nhds_toDual (x : X) : 𝓝 (toDual x) = map toDual (𝓝 x) := rfl theorem nhds_ofDual (x : X) : 𝓝 (ofDual x) = map ofDual (𝓝 x) := rfl variable [Preorder X] {x : X} instance OrderDual.instNeBotNhdsWithinIoi [(𝓝[<] x).NeBot] : (𝓝[>] toDual x).NeBot := ‹_› instance OrderDual.instNeBotNhdsWithinIio [(𝓝[>] x).NeBot] : (𝓝[<] toDual x).NeBot := ‹_› end theorem Quotient.preimage_mem_nhds [TopologicalSpace X] [s : Setoid X] {V : Set <| Quotient s} {x : X} (hs : V ∈ 𝓝 (Quotient.mk' x)) : Quotient.mk' ⁻¹' V ∈ 𝓝 x := preimage_nhds_coinduced hs /-- The image of a dense set under `Quotient.mk'` is a dense set. -/ theorem Dense.quotient [Setoid X] [TopologicalSpace X] {s : Set X} (H : Dense s) : Dense (Quotient.mk' '' s) := Quotient.surjective_Quotient_mk''.denseRange.dense_image continuous_coinduced_rng H /-- The composition of `Quotient.mk'` and a function with dense range has dense range. -/ theorem DenseRange.quotient [Setoid X] [TopologicalSpace X] {f : Y → X} (hf : DenseRange f) : DenseRange (Quotient.mk' ∘ f) := Quotient.surjective_Quotient_mk''.denseRange.comp hf continuous_coinduced_rng theorem continuous_map_of_le {α : Type*} [TopologicalSpace α] {s t : Setoid α} (h : s ≤ t) : Continuous (Setoid.map_of_le h) := continuous_coinduced_rng theorem continuous_map_sInf {α : Type*} [TopologicalSpace α] {S : Set (Setoid α)} {s : Setoid α} (h : s ∈ S) : Continuous (Setoid.map_sInf h) := continuous_coinduced_rng instance {p : X → Prop} [TopologicalSpace X] [DiscreteTopology X] : DiscreteTopology (Subtype p) := ⟨bot_unique fun s _ => ⟨(↑) '' s, isOpen_discrete _, preimage_image_eq _ Subtype.val_injective⟩⟩ instance Sum.discreteTopology [TopologicalSpace X] [TopologicalSpace Y] [h : DiscreteTopology X] [hY : DiscreteTopology Y] : DiscreteTopology (X ⊕ Y) := ⟨sup_eq_bot_iff.2 <| by simp [h.eq_bot, hY.eq_bot]⟩ instance Sigma.discreteTopology {ι : Type*} {Y : ι → Type v} [∀ i, TopologicalSpace (Y i)] [h : ∀ i, DiscreteTopology (Y i)] : DiscreteTopology (Sigma Y) := ⟨iSup_eq_bot.2 fun _ => by simp only [(h _).eq_bot, coinduced_bot]⟩ @[simp] lemma comap_nhdsWithin_range {α β} [TopologicalSpace β] (f : α → β) (y : β) : comap f (𝓝[range f] y) = comap f (𝓝 y) := comap_inf_principal_range section Top variable [TopologicalSpace X] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : Set X) (x : { x // x ∈ s }) (t : Set { x // x ∈ s }) : t ∈ 𝓝 x ↔ ∃ u ∈ 𝓝 (x : X), Subtype.val ⁻¹' u ⊆ t := mem_nhds_induced _ x t theorem nhds_subtype (s : Set X) (x : { x // x ∈ s }) : 𝓝 x = comap (↑) (𝓝 (x : X)) := nhds_induced _ x lemma nhds_subtype_eq_comap_nhdsWithin (s : Set X) (x : { x // x ∈ s }) : 𝓝 x = comap (↑) (𝓝[s] (x : X)) := by rw [nhds_subtype, ← comap_nhdsWithin_range, Subtype.range_val] theorem nhdsWithin_subtype_eq_bot_iff {s t : Set X} {x : s} : 𝓝[((↑) : s → X) ⁻¹' t] x = ⊥ ↔ 𝓝[t] (x : X) ⊓ 𝓟 s = ⊥ := by rw [inf_principal_eq_bot_iff_comap, nhdsWithin, nhdsWithin, comap_inf, comap_principal, nhds_induced] theorem nhds_ne_subtype_eq_bot_iff {S : Set X} {x : S} : 𝓝[≠] x = ⊥ ↔ 𝓝[≠] (x : X) ⊓ 𝓟 S = ⊥ := by rw [← nhdsWithin_subtype_eq_bot_iff, preimage_compl, ← image_singleton, Subtype.coe_injective.preimage_image] theorem nhds_ne_subtype_neBot_iff {S : Set X} {x : S} : (𝓝[≠] x).NeBot ↔ (𝓝[≠] (x : X) ⊓ 𝓟 S).NeBot := by rw [neBot_iff, neBot_iff, not_iff_not, nhds_ne_subtype_eq_bot_iff] theorem discreteTopology_subtype_iff {S : Set X} : DiscreteTopology S ↔ ∀ x ∈ S, 𝓝[≠] x ⊓ 𝓟 S = ⊥ := by simp_rw [discreteTopology_iff_nhds_ne, SetCoe.forall', nhds_ne_subtype_eq_bot_iff] end Top /-- A type synonym equipped with the topology whose open sets are the empty set and the sets with finite complements. -/ def CofiniteTopology (X : Type*) := X namespace CofiniteTopology /-- The identity equivalence between `` and `CofiniteTopology `. -/ def of : X ≃ CofiniteTopology X := Equiv.refl X instance [Inhabited X] : Inhabited (CofiniteTopology X) where default := of default instance : TopologicalSpace (CofiniteTopology X) where IsOpen s := s.Nonempty → Set.Finite sᶜ isOpen_univ := by simp isOpen_inter s t := by rintro hs ht ⟨x, hxs, hxt⟩ rw [compl_inter] exact (hs ⟨x, hxs⟩).union (ht ⟨x, hxt⟩) isOpen_sUnion := by rintro s h ⟨x, t, hts, hzt⟩ rw [compl_sUnion] exact Finite.sInter (mem_image_of_mem _ hts) (h t hts ⟨x, hzt⟩) theorem isOpen_iff {s : Set (CofiniteTopology X)} : IsOpen s ↔ s.Nonempty → sᶜ.Finite := Iff.rfl theorem isOpen_iff' {s : Set (CofiniteTopology X)} : IsOpen s ↔ s = ∅ ∨ sᶜ.Finite := by simp only [isOpen_iff, nonempty_iff_ne_empty, or_iff_not_imp_left] theorem isClosed_iff {s : Set (CofiniteTopology X)} : IsClosed s ↔ s = univ ∨ s.Finite := by simp only [← isOpen_compl_iff, isOpen_iff', compl_compl, compl_empty_iff] theorem nhds_eq (x : CofiniteTopology X) : 𝓝 x = pure x ⊔ cofinite := by ext U rw [mem_nhds_iff] constructor · rintro ⟨V, hVU, V_op, haV⟩ exact mem_sup.mpr ⟨hVU haV, mem_of_superset (V_op ⟨_, haV⟩) hVU⟩ · rintro ⟨hU : x ∈ U, hU' : Uᶜ.Finite⟩ exact ⟨U, Subset.rfl, fun _ => hU', hU⟩ theorem mem_nhds_iff {x : CofiniteTopology X} {s : Set (CofiniteTopology X)} : s ∈ 𝓝 x ↔ x ∈ s ∧ sᶜ.Finite := by simp [nhds_eq] end CofiniteTopology end Constructions section Prod variable [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] [TopologicalSpace W] [TopologicalSpace ε] [TopologicalSpace ζ] -- Porting note (#11215): TODO: Lean 4 fails to deduce implicit args @[simp] theorem continuous_prod_mk {f : X → Y} {g : X → Z} : (Continuous fun x => (f x, g x)) ↔ Continuous f ∧ Continuous g := (@continuous_inf_rng X (Y × Z) _ _ (TopologicalSpace.induced Prod.fst _) (TopologicalSpace.induced Prod.snd _)).trans <| continuous_induced_rng.and continuous_induced_rng @[continuity] theorem continuous_fst : Continuous (@Prod.fst X Y) := (continuous_prod_mk.1 continuous_id).1 /-- Postcomposing `f` with `Prod.fst` is continuous -/ @[fun_prop] theorem Continuous.fst {f : X → Y × Z} (hf : Continuous f) : Continuous fun x : X => (f x).1 := continuous_fst.comp hf /-- Precomposing `f` with `Prod.fst` is continuous -/ theorem Continuous.fst' {f : X → Z} (hf : Continuous f) : Continuous fun x : X × Y => f x.fst := hf.comp continuous_fst theorem continuousAt_fst {p : X × Y} : ContinuousAt Prod.fst p := continuous_fst.continuousAt /-- Postcomposing `f` with `Prod.fst` is continuous at `x` -/ @[fun_prop] theorem ContinuousAt.fst {f : X → Y × Z} {x : X} (hf : ContinuousAt f x) : ContinuousAt (fun x : X => (f x).1) x := continuousAt_fst.comp hf /-- Precomposing `f` with `Prod.fst` is continuous at `(x, y)` -/ theorem ContinuousAt.fst' {f : X → Z} {x : X} {y : Y} (hf : ContinuousAt f x) : ContinuousAt (fun x : X × Y => f x.fst) (x, y) := ContinuousAt.comp hf continuousAt_fst /-- Precomposing `f` with `Prod.fst` is continuous at `x : X × Y` -/ theorem ContinuousAt.fst'' {f : X → Z} {x : X × Y} (hf : ContinuousAt f x.fst) : ContinuousAt (fun x : X × Y => f x.fst) x := hf.comp continuousAt_fst theorem Filter.Tendsto.fst_nhds {X} {l : Filter X} {f : X → Y × Z} {p : Y × Z} (h : Tendsto f l (𝓝 p)) : Tendsto (fun a ↦ (f a).1) l (𝓝 <| p.1) := continuousAt_fst.tendsto.comp h @[continuity] theorem continuous_snd : Continuous (@Prod.snd X Y) := (continuous_prod_mk.1 continuous_id).2 /-- Postcomposing `f` with `Prod.snd` is continuous -/ @[fun_prop] theorem Continuous.snd {f : X → Y × Z} (hf : Continuous f) : Continuous fun x : X => (f x).2 := continuous_snd.comp hf /-- Precomposing `f` with `Prod.snd` is continuous -/ theorem Continuous.snd' {f : Y → Z} (hf : Continuous f) : Continuous fun x : X × Y => f x.snd := hf.comp continuous_snd theorem continuousAt_snd {p : X × Y} : ContinuousAt Prod.snd p := continuous_snd.continuousAt /-- Postcomposing `f` with `Prod.snd` is continuous at `x` -/ @[fun_prop] theorem ContinuousAt.snd {f : X → Y × Z} {x : X} (hf : ContinuousAt f x) : ContinuousAt (fun x : X => (f x).2) x := continuousAt_snd.comp hf /-- Precomposing `f` with `Prod.snd` is continuous at `(x, y)` -/ theorem ContinuousAt.snd' {f : Y → Z} {x : X} {y : Y} (hf : ContinuousAt f y) : ContinuousAt (fun x : X × Y => f x.snd) (x, y) := ContinuousAt.comp hf continuousAt_snd /-- Precomposing `f` with `Prod.snd` is continuous at `x : X × Y` -/ theorem ContinuousAt.snd'' {f : Y → Z} {x : X × Y} (hf : ContinuousAt f x.snd) : ContinuousAt (fun x : X × Y => f x.snd) x := hf.comp continuousAt_snd theorem Filter.Tendsto.snd_nhds {X} {l : Filter X} {f : X → Y × Z} {p : Y × Z} (h : Tendsto f l (𝓝 p)) : Tendsto (fun a ↦ (f a).2) l (𝓝 <| p.2) := continuousAt_snd.tendsto.comp h @[continuity, fun_prop] theorem Continuous.prod_mk {f : Z → X} {g : Z → Y} (hf : Continuous f) (hg : Continuous g) : Continuous fun x => (f x, g x) := continuous_prod_mk.2 ⟨hf, hg⟩ @[continuity] theorem Continuous.Prod.mk (x : X) : Continuous fun y : Y => (x, y) := continuous_const.prod_mk continuous_id @[continuity] theorem Continuous.Prod.mk_left (y : Y) : Continuous fun x : X => (x, y) := continuous_id.prod_mk continuous_const /-- If `f x y` is continuous in `x` for all `y ∈ s`, then the set of `x` such that `f x` maps `s` to `t` is closed. -/ lemma IsClosed.setOf_mapsTo {α : Type*} {f : X → α → Z} {s : Set α} {t : Set Z} (ht : IsClosed t) (hf : ∀ a ∈ s, Continuous (f · a)) : IsClosed {x | MapsTo (f x) s t} := by simpa only [MapsTo, setOf_forall] using isClosed_biInter fun y hy ↦ ht.preimage (hf y hy) theorem Continuous.comp₂ {g : X × Y → Z} (hg : Continuous g) {e : W → X} (he : Continuous e) {f : W → Y} (hf : Continuous f) : Continuous fun w => g (e w, f w) := hg.comp <| he.prod_mk hf theorem Continuous.comp₃ {g : X × Y × Z → ε} (hg : Continuous g) {e : W → X} (he : Continuous e) {f : W → Y} (hf : Continuous f) {k : W → Z} (hk : Continuous k) : Continuous fun w => g (e w, f w, k w) := hg.comp₂ he <| hf.prod_mk hk theorem Continuous.comp₄ {g : X × Y × Z × ζ → ε} (hg : Continuous g) {e : W → X} (he : Continuous e) {f : W → Y} (hf : Continuous f) {k : W → Z} (hk : Continuous k) {l : W → ζ} (hl : Continuous l) : Continuous fun w => g (e w, f w, k w, l w) := hg.comp₃ he hf <| hk.prod_mk hl @[continuity] theorem Continuous.prod_map {f : Z → X} {g : W → Y} (hf : Continuous f) (hg : Continuous g) : Continuous fun p : Z × W => (f p.1, g p.2) := hf.fst'.prod_mk hg.snd' /-- A version of `continuous_inf_dom_left` for binary functions -/ theorem continuous_inf_dom_left₂ {X Y Z} {f : X → Y → Z} {ta1 ta2 : TopologicalSpace X} {tb1 tb2 : TopologicalSpace Y} {tc1 : TopologicalSpace Z} (h : by haveI := ta1; haveI := tb1; exact Continuous fun p : X × Y => f p.1 p.2) : by haveI := ta1 ⊓ ta2; haveI := tb1 ⊓ tb2; exact Continuous fun p : X × Y => f p.1 p.2 := by have ha := @continuous_inf_dom_left _ _ id ta1 ta2 ta1 (@continuous_id _ (id _)) have hb := @continuous_inf_dom_left _ _ id tb1 tb2 tb1 (@continuous_id _ (id _)) have h_continuous_id := @Continuous.prod_map _ _ _ _ ta1 tb1 (ta1 ⊓ ta2) (tb1 ⊓ tb2) _ _ ha hb exact @Continuous.comp _ _ _ (id _) (id _) _ _ _ h h_continuous_id /-- A version of `continuous_inf_dom_right` for binary functions -/ theorem continuous_inf_dom_right₂ {X Y Z} {f : X → Y → Z} {ta1 ta2 : TopologicalSpace X} {tb1 tb2 : TopologicalSpace Y} {tc1 : TopologicalSpace Z} (h : by haveI := ta2; haveI := tb2; exact Continuous fun p : X × Y => f p.1 p.2) : by haveI := ta1 ⊓ ta2; haveI := tb1 ⊓ tb2; exact Continuous fun p : X × Y => f p.1 p.2 := by have ha := @continuous_inf_dom_right _ _ id ta1 ta2 ta2 (@continuous_id _ (id _)) have hb := @continuous_inf_dom_right _ _ id tb1 tb2 tb2 (@continuous_id _ (id _)) have h_continuous_id := @Continuous.prod_map _ _ _ _ ta2 tb2 (ta1 ⊓ ta2) (tb1 ⊓ tb2) _ _ ha hb exact @Continuous.comp _ _ _ (id _) (id _) _ _ _ h h_continuous_id /-- A version of `continuous_sInf_dom` for binary functions -/ theorem continuous_sInf_dom₂ {X Y Z} {f : X → Y → Z} {tas : Set (TopologicalSpace X)} {tbs : Set (TopologicalSpace Y)} {tX : TopologicalSpace X} {tY : TopologicalSpace Y} {tc : TopologicalSpace Z} (hX : tX ∈ tas) (hY : tY ∈ tbs) (hf : Continuous fun p : X × Y => f p.1 p.2) : by haveI := sInf tas; haveI := sInf tbs exact @Continuous _ _ _ tc fun p : X × Y => f p.1 p.2 := by have hX := continuous_sInf_dom hX continuous_id have hY := continuous_sInf_dom hY continuous_id have h_continuous_id := @Continuous.prod_map _ _ _ _ tX tY (sInf tas) (sInf tbs) _ _ hX hY exact @Continuous.comp _ _ _ (id _) (id _) _ _ _ hf h_continuous_id theorem Filter.Eventually.prod_inl_nhds {p : X → Prop} {x : X} (h : ∀ᶠ x in 𝓝 x, p x) (y : Y) : ∀ᶠ x in 𝓝 (x, y), p (x : X × Y).1 := continuousAt_fst h theorem Filter.Eventually.prod_inr_nhds {p : Y → Prop} {y : Y} (h : ∀ᶠ x in 𝓝 y, p x) (x : X) : ∀ᶠ x in 𝓝 (x, y), p (x : X × Y).2 := continuousAt_snd h theorem Filter.Eventually.prod_mk_nhds {px : X → Prop} {x} (hx : ∀ᶠ x in 𝓝 x, px x) {py : Y → Prop} {y} (hy : ∀ᶠ y in 𝓝 y, py y) : ∀ᶠ p in 𝓝 (x, y), px (p : X × Y).1 ∧ py p.2 := (hx.prod_inl_nhds y).and (hy.prod_inr_nhds x) theorem continuous_swap : Continuous (Prod.swap : X × Y → Y × X) := continuous_snd.prod_mk continuous_fst lemma isClosedMap_swap : IsClosedMap (Prod.swap : X × Y → Y × X) := fun s hs ↦ by rw [image_swap_eq_preimage_swap] exact hs.preimage continuous_swap theorem Continuous.uncurry_left {f : X → Y → Z} (x : X) (h : Continuous (uncurry f)) : Continuous (f x) := h.comp (Continuous.Prod.mk _) theorem Continuous.uncurry_right {f : X → Y → Z} (y : Y) (h : Continuous (uncurry f)) : Continuous fun a => f a y := h.comp (Continuous.Prod.mk_left _) @[deprecated (since := "2024-03-09")] alias continuous_uncurry_left := Continuous.uncurry_left @[deprecated (since := "2024-03-09")] alias continuous_uncurry_right := Continuous.uncurry_right theorem continuous_curry {g : X × Y → Z} (x : X) (h : Continuous g) : Continuous (curry g x) := Continuous.uncurry_left x h theorem IsOpen.prod {s : Set X} {t : Set Y} (hs : IsOpen s) (ht : IsOpen t) : IsOpen (s ×ˢ t) := (hs.preimage continuous_fst).inter (ht.preimage continuous_snd) -- Porting note (#11215): TODO: Lean fails to find `t₁` and `t₂` by unification theorem nhds_prod_eq {x : X} {y : Y} : 𝓝 (x, y) = 𝓝 x ×ˢ 𝓝 y := by dsimp only [SProd.sprod] rw [Filter.prod, instTopologicalSpaceProd, nhds_inf (t₁ := TopologicalSpace.induced Prod.fst _) (t₂ := TopologicalSpace.induced Prod.snd _), nhds_induced, nhds_induced] -- Porting note: moved from `Topology.ContinuousOn` theorem nhdsWithin_prod_eq (x : X) (y : Y) (s : Set X) (t : Set Y) : 𝓝[s ×ˢ t] (x, y) = 𝓝[s] x ×ˢ 𝓝[t] y := by simp only [nhdsWithin, nhds_prod_eq, ← prod_inf_prod, prod_principal_principal] instance Prod.instNeBotNhdsWithinIio [Preorder X] [Preorder Y] {x : X × Y} [hx₁ : (𝓝[<] x.1).NeBot] [hx₂ : (𝓝[<] x.2).NeBot] : (𝓝[<] x).NeBot := by refine (hx₁.prod hx₂).mono ?_ rw [← nhdsWithin_prod_eq] exact nhdsWithin_mono _ fun _ ⟨h₁, h₂⟩ ↦ Prod.lt_iff.2 <| .inl ⟨h₁, h₂.le⟩ instance Prod.instNeBotNhdsWithinIoi [Preorder X] [Preorder Y] {x : X × Y} [(𝓝[>] x.1).NeBot] [(𝓝[>] x.2).NeBot] : (𝓝[>] x).NeBot := Prod.instNeBotNhdsWithinIio (X := Xᵒᵈ) (Y := Yᵒᵈ) (x := (OrderDual.toDual x.1, OrderDual.toDual x.2)) theorem mem_nhds_prod_iff {x : X} {y : Y} {s : Set (X × Y)} : s ∈ 𝓝 (x, y) ↔ ∃ u ∈ 𝓝 x, ∃ v ∈ 𝓝 y, u ×ˢ v ⊆ s := by rw [nhds_prod_eq, mem_prod_iff] theorem mem_nhdsWithin_prod_iff {x : X} {y : Y} {s : Set (X × Y)} {tx : Set X} {ty : Set Y} : s ∈ 𝓝[tx ×ˢ ty] (x, y) ↔ ∃ u ∈ 𝓝[tx] x, ∃ v ∈ 𝓝[ty] y, u ×ˢ v ⊆ s := by rw [nhdsWithin_prod_eq, mem_prod_iff] -- Porting note: moved up theorem Filter.HasBasis.prod_nhds {ιX ιY : Type*} {px : ιX → Prop} {py : ιY → Prop} {sx : ιX → Set X} {sy : ιY → Set Y} {x : X} {y : Y} (hx : (𝓝 x).HasBasis px sx) (hy : (𝓝 y).HasBasis py sy) : (𝓝 (x, y)).HasBasis (fun i : ιX × ιY => px i.1 ∧ py i.2) fun i => sx i.1 ×ˢ sy i.2 := by rw [nhds_prod_eq] exact hx.prod hy -- Porting note: moved up theorem Filter.HasBasis.prod_nhds' {ιX ιY : Type*} {pX : ιX → Prop} {pY : ιY → Prop} {sx : ιX → Set X} {sy : ιY → Set Y} {p : X × Y} (hx : (𝓝 p.1).HasBasis pX sx) (hy : (𝓝 p.2).HasBasis pY sy) : (𝓝 p).HasBasis (fun i : ιX × ιY => pX i.1 ∧ pY i.2) fun i => sx i.1 ×ˢ sy i.2 := hx.prod_nhds hy theorem mem_nhds_prod_iff' {x : X} {y : Y} {s : Set (X × Y)} : s ∈ 𝓝 (x, y) ↔ ∃ u v, IsOpen u ∧ x ∈ u ∧ IsOpen v ∧ y ∈ v ∧ u ×ˢ v ⊆ s := ((nhds_basis_opens x).prod_nhds (nhds_basis_opens y)).mem_iff.trans <| by simp only [Prod.exists, and_comm, and_assoc, and_left_comm] theorem Prod.tendsto_iff {X} (seq : X → Y × Z) {f : Filter X} (p : Y × Z) : Tendsto seq f (𝓝 p) ↔ Tendsto (fun n => (seq n).fst) f (𝓝 p.fst) ∧ Tendsto (fun n => (seq n).snd) f (𝓝 p.snd) := by rw [nhds_prod_eq, Filter.tendsto_prod_iff'] instance [DiscreteTopology X] [DiscreteTopology Y] : DiscreteTopology (X × Y) := discreteTopology_iff_nhds.2 fun (a, b) => by rw [nhds_prod_eq, nhds_discrete X, nhds_discrete Y, prod_pure_pure] theorem prod_mem_nhds_iff {s : Set X} {t : Set Y} {x : X} {y : Y} : s ×ˢ t ∈ 𝓝 (x, y) ↔ s ∈ 𝓝 x ∧ t ∈ 𝓝 y := by rw [nhds_prod_eq, prod_mem_prod_iff] theorem prod_mem_nhds {s : Set X} {t : Set Y} {x : X} {y : Y} (hx : s ∈ 𝓝 x) (hy : t ∈ 𝓝 y) : s ×ˢ t ∈ 𝓝 (x, y) := prod_mem_nhds_iff.2 ⟨hx, hy⟩ theorem isOpen_setOf_disjoint_nhds_nhds : IsOpen { p : X × X | Disjoint (𝓝 p.1) (𝓝 p.2) } := by simp only [isOpen_iff_mem_nhds, Prod.forall, mem_setOf_eq] intro x y h obtain ⟨U, hU, V, hV, hd⟩ := ((nhds_basis_opens x).disjoint_iff (nhds_basis_opens y)).mp h exact mem_nhds_prod_iff'.mpr ⟨U, V, hU.2, hU.1, hV.2, hV.1, fun ⟨x', y'⟩ ⟨hx', hy'⟩ => disjoint_of_disjoint_of_mem hd (hU.2.mem_nhds hx') (hV.2.mem_nhds hy')⟩ theorem Filter.Eventually.prod_nhds {p : X → Prop} {q : Y → Prop} {x : X} {y : Y} (hx : ∀ᶠ x in 𝓝 x, p x) (hy : ∀ᶠ y in 𝓝 y, q y) : ∀ᶠ z : X × Y in 𝓝 (x, y), p z.1 ∧ q z.2 := prod_mem_nhds hx hy theorem nhds_swap (x : X) (y : Y) : 𝓝 (x, y) = (𝓝 (y, x)).map Prod.swap := by rw [nhds_prod_eq, Filter.prod_comm, nhds_prod_eq]; rfl theorem Filter.Tendsto.prod_mk_nhds {γ} {x : X} {y : Y} {f : Filter γ} {mx : γ → X} {my : γ → Y} (hx : Tendsto mx f (𝓝 x)) (hy : Tendsto my f (𝓝 y)) : Tendsto (fun c => (mx c, my c)) f (𝓝 (x, y)) := by rw [nhds_prod_eq]; exact Filter.Tendsto.prod_mk hx hy theorem Filter.Eventually.curry_nhds {p : X × Y → Prop} {x : X} {y : Y} (h : ∀ᶠ x in 𝓝 (x, y), p x) : ∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') := by rw [nhds_prod_eq] at h exact h.curry @[fun_prop] theorem ContinuousAt.prod {f : X → Y} {g : X → Z} {x : X} (hf : ContinuousAt f x) (hg : ContinuousAt g x) : ContinuousAt (fun x => (f x, g x)) x := hf.prod_mk_nhds hg theorem ContinuousAt.prod_map {f : X → Z} {g : Y → W} {p : X × Y} (hf : ContinuousAt f p.fst) (hg : ContinuousAt g p.snd) : ContinuousAt (fun p : X × Y => (f p.1, g p.2)) p := hf.fst''.prod hg.snd'' theorem ContinuousAt.prod_map' {f : X → Z} {g : Y → W} {x : X} {y : Y} (hf : ContinuousAt f x) (hg : ContinuousAt g y) : ContinuousAt (fun p : X × Y => (f p.1, g p.2)) (x, y) := hf.fst'.prod hg.snd' theorem ContinuousAt.comp₂ {f : Y × Z → W} {g : X → Y} {h : X → Z} {x : X} (hf : ContinuousAt f (g x, h x)) (hg : ContinuousAt g x) (hh : ContinuousAt h x) : ContinuousAt (fun x ↦ f (g x, h x)) x := ContinuousAt.comp hf (hg.prod hh) theorem ContinuousAt.comp₂_of_eq {f : Y × Z → W} {g : X → Y} {h : X → Z} {x : X} {y : Y × Z} (hf : ContinuousAt f y) (hg : ContinuousAt g x) (hh : ContinuousAt h x) (e : (g x, h x) = y) : ContinuousAt (fun x ↦ f (g x, h x)) x := by rw [← e] at hf exact hf.comp₂ hg hh /-- Continuous functions on products are continuous in their first argument -/ theorem Continuous.curry_left {f : X × Y → Z} (hf : Continuous f) {y : Y} : Continuous fun x ↦ f (x, y) := hf.comp (continuous_id.prod_mk continuous_const) alias Continuous.along_fst := Continuous.curry_left /-- Continuous functions on products are continuous in their second argument -/ theorem Continuous.curry_right {f : X × Y → Z} (hf : Continuous f) {x : X} : Continuous fun y ↦ f (x, y) := hf.comp (continuous_const.prod_mk continuous_id) alias Continuous.along_snd := Continuous.curry_right -- todo: prove a version of `generateFrom_union` with `image2 (∩) s t` in the LHS and use it here theorem prod_generateFrom_generateFrom_eq {X Y : Type*} {s : Set (Set X)} {t : Set (Set Y)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @instTopologicalSpaceProd X Y (generateFrom s) (generateFrom t) = generateFrom (image2 (· ×ˢ ·) s t) := let G := generateFrom (image2 (· ×ˢ ·) s t) le_antisymm (le_generateFrom fun g ⟨u, hu, v, hv, g_eq⟩ => g_eq.symm ▸ @IsOpen.prod _ _ (generateFrom s) (generateFrom t) _ _ (GenerateOpen.basic _ hu) (GenerateOpen.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp <| le_generateFrom fun u hu => have : ⋃ v ∈ t, u ×ˢ v = Prod.fst ⁻¹' u := by simp_rw [← prod_iUnion, ← sUnion_eq_biUnion, ht, prod_univ] show G.IsOpen (Prod.fst ⁻¹' u) by rw [← this] exact isOpen_iUnion fun v => isOpen_iUnion fun hv => GenerateOpen.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp <| le_generateFrom fun v hv => have : ⋃ u ∈ s, u ×ˢ v = Prod.snd ⁻¹' v := by simp_rw [← iUnion_prod_const, ← sUnion_eq_biUnion, hs, univ_prod] show G.IsOpen (Prod.snd ⁻¹' v) by rw [← this] exact isOpen_iUnion fun u => isOpen_iUnion fun hu => GenerateOpen.basic _ ⟨_, hu, _, hv, rfl⟩)) -- todo: use the previous lemma? theorem prod_eq_generateFrom : instTopologicalSpaceProd = generateFrom { g | ∃ (s : Set X) (t : Set Y), IsOpen s ∧ IsOpen t ∧ g = s ×ˢ t } := le_antisymm (le_generateFrom fun g ⟨s, t, hs, ht, g_eq⟩ => g_eq.symm ▸ hs.prod ht) (le_inf (forall_mem_image.2 fun t ht => GenerateOpen.basic _ ⟨t, univ, by simpa [Set.prod_eq] using ht⟩) (forall_mem_image.2 fun t ht => GenerateOpen.basic _ ⟨univ, t, by simpa [Set.prod_eq] using ht⟩)) -- Porting note (#11215): TODO: align with `mem_nhds_prod_iff'` theorem isOpen_prod_iff {s : Set (X × Y)} : IsOpen s ↔ ∀ a b, (a, b) ∈ s → ∃ u v, IsOpen u ∧ IsOpen v ∧ a ∈ u ∧ b ∈ v ∧ u ×ˢ v ⊆ s := isOpen_iff_mem_nhds.trans <| by simp_rw [Prod.forall, mem_nhds_prod_iff', and_left_comm] /-- A product of induced topologies is induced by the product map -/ theorem prod_induced_induced {X Z} (f : X → Y) (g : Z → W) : @instTopologicalSpaceProd X Z (induced f ‹_›) (induced g ‹_›) = induced (fun p => (f p.1, g p.2)) instTopologicalSpaceProd := by delta instTopologicalSpaceProd simp_rw [induced_inf, induced_compose] rfl /-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood that is a subset of `s`. -/ theorem exists_nhds_square {s : Set (X × X)} {x : X} (hx : s ∈ 𝓝 (x, x)) : ∃ U : Set X, IsOpen U ∧ x ∈ U ∧ U ×ˢ U ⊆ s := by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and_assoc, and_left_comm] using hx /-- `Prod.fst` maps neighborhood of `x : X × Y` within the section `Prod.snd ⁻¹' {x.2}` to `𝓝 x.1`. -/ theorem map_fst_nhdsWithin (x : X × Y) : map Prod.fst (𝓝[Prod.snd ⁻¹' {x.2}] x) = 𝓝 x.1 := by refine le_antisymm (continuousAt_fst.mono_left inf_le_left) fun s hs => ?_ rcases x with ⟨x, y⟩ rw [mem_map, nhdsWithin, mem_inf_principal, mem_nhds_prod_iff] at hs rcases hs with ⟨u, hu, v, hv, H⟩ simp only [prod_subset_iff, mem_singleton_iff, mem_setOf_eq, mem_preimage] at H exact mem_of_superset hu fun z hz => H _ hz _ (mem_of_mem_nhds hv) rfl @[simp] theorem map_fst_nhds (x : X × Y) : map Prod.fst (𝓝 x) = 𝓝 x.1 := le_antisymm continuousAt_fst <| (map_fst_nhdsWithin x).symm.trans_le (map_mono inf_le_left) /-- The first projection in a product of topological spaces sends open sets to open sets. -/ theorem isOpenMap_fst : IsOpenMap (@Prod.fst X Y) := isOpenMap_iff_nhds_le.2 fun x => (map_fst_nhds x).ge /-- `Prod.snd` maps neighborhood of `x : X × Y` within the section `Prod.fst ⁻¹' {x.1}` to `𝓝 x.2`. -/ theorem map_snd_nhdsWithin (x : X × Y) : map Prod.snd (𝓝[Prod.fst ⁻¹' {x.1}] x) = 𝓝 x.2 := by refine le_antisymm (continuousAt_snd.mono_left inf_le_left) fun s hs => ?_ rcases x with ⟨x, y⟩ rw [mem_map, nhdsWithin, mem_inf_principal, mem_nhds_prod_iff] at hs rcases hs with ⟨u, hu, v, hv, H⟩ simp only [prod_subset_iff, mem_singleton_iff, mem_setOf_eq, mem_preimage] at H exact mem_of_superset hv fun z hz => H _ (mem_of_mem_nhds hu) _ hz rfl @[simp] theorem map_snd_nhds (x : X × Y) : map Prod.snd (𝓝 x) = 𝓝 x.2 := le_antisymm continuousAt_snd <| (map_snd_nhdsWithin x).symm.trans_le (map_mono inf_le_left) /-- The second projection in a product of topological spaces sends open sets to open sets. -/ theorem isOpenMap_snd : IsOpenMap (@Prod.snd X Y) := isOpenMap_iff_nhds_le.2 fun x => (map_snd_nhds x).ge /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ theorem isOpen_prod_iff' {s : Set X} {t : Set Y} : IsOpen (s ×ˢ t) ↔ IsOpen s ∧ IsOpen t ∨ s = ∅ ∨ t = ∅ := by rcases (s ×ˢ t).eq_empty_or_nonempty with h | h · simp [h, prod_eq_empty_iff.1 h] · have st : s.Nonempty ∧ t.Nonempty := prod_nonempty_iff.1 h constructor · intro (H : IsOpen (s ×ˢ t)) refine Or.inl ⟨?_, ?_⟩ · show IsOpen s rw [← fst_image_prod s st.2] exact isOpenMap_fst _ H · show IsOpen t rw [← snd_image_prod st.1 t] exact isOpenMap_snd _ H · intro H simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false_iff] at H exact H.1.prod H.2 theorem closure_prod_eq {s : Set X} {t : Set Y} : closure (s ×ˢ t) = closure s ×ˢ closure t := ext fun ⟨a, b⟩ => by simp_rw [mem_prod, mem_closure_iff_nhdsWithin_neBot, nhdsWithin_prod_eq, prod_neBot] theorem interior_prod_eq (s : Set X) (t : Set Y) : interior (s ×ˢ t) = interior s ×ˢ interior t := ext fun ⟨a, b⟩ => by simp only [mem_interior_iff_mem_nhds, mem_prod, prod_mem_nhds_iff] theorem frontier_prod_eq (s : Set X) (t : Set Y) : frontier (s ×ˢ t) = closure s ×ˢ frontier t ∪ frontier s ×ˢ closure t := by simp only [frontier, closure_prod_eq, interior_prod_eq, prod_diff_prod] @[simp] theorem frontier_prod_univ_eq (s : Set X) : frontier (s ×ˢ (univ : Set Y)) = frontier s ×ˢ univ := by simp [frontier_prod_eq] @[simp] theorem frontier_univ_prod_eq (s : Set Y) : frontier ((univ : Set X) ×ˢ s) = univ ×ˢ frontier s := by simp [frontier_prod_eq] theorem map_mem_closure₂ {f : X → Y → Z} {x : X} {y : Y} {s : Set X} {t : Set Y} {u : Set Z} (hf : Continuous (uncurry f)) (hx : x ∈ closure s) (hy : y ∈ closure t) (h : ∀ a ∈ s, ∀ b ∈ t, f a b ∈ u) : f x y ∈ closure u := have H₁ : (x, y) ∈ closure (s ×ˢ t) := by simpa only [closure_prod_eq] using mk_mem_prod hx hy have H₂ : MapsTo (uncurry f) (s ×ˢ t) u := forall_prod_set.2 h H₂.closure hf H₁ theorem IsClosed.prod {s₁ : Set X} {s₂ : Set Y} (h₁ : IsClosed s₁) (h₂ : IsClosed s₂) : IsClosed (s₁ ×ˢ s₂) := closure_eq_iff_isClosed.mp <| by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq] /-- The product of two dense sets is a dense set. -/ theorem Dense.prod {s : Set X} {t : Set Y} (hs : Dense s) (ht : Dense t) : Dense (s ×ˢ t) := fun x => by rw [closure_prod_eq] exact ⟨hs x.1, ht x.2⟩ /-- If `f` and `g` are maps with dense range, then `Prod.map f g` has dense range. -/ theorem DenseRange.prod_map {ι : Type*} {κ : Type*} {f : ι → Y} {g : κ → Z} (hf : DenseRange f) (hg : DenseRange g) : DenseRange (Prod.map f g) := by simpa only [DenseRange, prod_range_range_eq] using hf.prod hg theorem Inducing.prod_map {f : X → Y} {g : Z → W} (hf : Inducing f) (hg : Inducing g) : Inducing (Prod.map f g) := inducing_iff_nhds.2 fun (x, z) => by simp_rw [Prod.map_def, nhds_prod_eq, hf.nhds_eq_comap, hg.nhds_eq_comap, prod_comap_comap_eq] @[simp] theorem inducing_const_prod {x : X} {f : Y → Z} : (Inducing fun x' => (x, f x')) ↔ Inducing f := by simp_rw [inducing_iff, instTopologicalSpaceProd, induced_inf, induced_compose, Function.comp, induced_const, top_inf_eq] @[simp] theorem inducing_prod_const {y : Y} {f : X → Z} : (Inducing fun x => (f x, y)) ↔ Inducing f := by simp_rw [inducing_iff, instTopologicalSpaceProd, induced_inf, induced_compose, Function.comp, induced_const, inf_top_eq] theorem Embedding.prod_map {f : X → Y} {g : Z → W} (hf : Embedding f) (hg : Embedding g) : Embedding (Prod.map f g) := { hf.toInducing.prod_map hg.toInducing with inj := fun ⟨x₁, z₁⟩ ⟨x₂, z₂⟩ => by simp [hf.inj.eq_iff, hg.inj.eq_iff] } protected theorem IsOpenMap.prod {f : X → Y} {g : Z → W} (hf : IsOpenMap f) (hg : IsOpenMap g) : IsOpenMap fun p : X × Z => (f p.1, g p.2) := by rw [isOpenMap_iff_nhds_le] rintro ⟨a, b⟩ rw [nhds_prod_eq, nhds_prod_eq, ← Filter.prod_map_map_eq] exact Filter.prod_mono (hf.nhds_le a) (hg.nhds_le b) protected theorem OpenEmbedding.prod {f : X → Y} {g : Z → W} (hf : OpenEmbedding f) (hg : OpenEmbedding g) : OpenEmbedding fun x : X × Z => (f x.1, g x.2) := openEmbedding_of_embedding_open (hf.1.prod_map hg.1) (hf.isOpenMap.prod hg.isOpenMap) theorem embedding_graph {f : X → Y} (hf : Continuous f) : Embedding fun x => (x, f x) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id theorem embedding_prod_mk (x : X) : Embedding (Prod.mk x : Y → X × Y) := embedding_of_embedding_compose (Continuous.Prod.mk x) continuous_snd embedding_id end Prod section Bool lemma continuous_bool_rng [TopologicalSpace X] {f : X → Bool} (b : Bool) : Continuous f ↔ IsClopen (f ⁻¹' {b}) := by rw [continuous_discrete_rng, Bool.forall_bool' b, IsClopen, ← isOpen_compl_iff, ← preimage_compl, Bool.compl_singleton, and_comm] end Bool section Sum open Sum variable [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] [TopologicalSpace W] theorem continuous_sum_dom {f : X ⊕ Y → Z} : Continuous f ↔ Continuous (f ∘ Sum.inl) ∧ Continuous (f ∘ Sum.inr) := (continuous_sup_dom (t₁ := TopologicalSpace.coinduced Sum.inl _) (t₂ := TopologicalSpace.coinduced Sum.inr _)).trans <| continuous_coinduced_dom.and continuous_coinduced_dom theorem continuous_sum_elim {f : X → Z} {g : Y → Z} : Continuous (Sum.elim f g) ↔ Continuous f ∧ Continuous g := continuous_sum_dom @[continuity, fun_prop] theorem Continuous.sum_elim {f : X → Z} {g : Y → Z} (hf : Continuous f) (hg : Continuous g) : Continuous (Sum.elim f g) := continuous_sum_elim.2 ⟨hf, hg⟩ @[continuity, fun_prop] theorem continuous_isLeft : Continuous (isLeft : X ⊕ Y → Bool) := continuous_sum_dom.2 ⟨continuous_const, continuous_const⟩ @[continuity, fun_prop] theorem continuous_isRight : Continuous (isRight : X ⊕ Y → Bool) := continuous_sum_dom.2 ⟨continuous_const, continuous_const⟩ @[continuity, fun_prop] -- Porting note: the proof was `continuous_sup_rng_left continuous_coinduced_rng` theorem continuous_inl : Continuous (@inl X Y) := ⟨fun _ => And.left⟩ @[continuity, fun_prop] -- Porting note: the proof was `continuous_sup_rng_right continuous_coinduced_rng` theorem continuous_inr : Continuous (@inr X Y) := ⟨fun _ => And.right⟩ theorem isOpen_sum_iff {s : Set (X ⊕ Y)} : IsOpen s ↔ IsOpen (inl ⁻¹' s) ∧ IsOpen (inr ⁻¹' s) := Iff.rfl theorem isClosed_sum_iff {s : Set (X ⊕ Y)} : IsClosed s ↔ IsClosed (inl ⁻¹' s) ∧ IsClosed (inr ⁻¹' s) := by simp only [← isOpen_compl_iff, isOpen_sum_iff, preimage_compl] theorem isOpenMap_inl : IsOpenMap (@inl X Y) := fun u hu => by simpa [isOpen_sum_iff, preimage_image_eq u Sum.inl_injective] theorem isOpenMap_inr : IsOpenMap (@inr X Y) := fun u hu => by simpa [isOpen_sum_iff, preimage_image_eq u Sum.inr_injective] theorem openEmbedding_inl : OpenEmbedding (@inl X Y) := openEmbedding_of_continuous_injective_open continuous_inl inl_injective isOpenMap_inl theorem openEmbedding_inr : OpenEmbedding (@inr X Y) := openEmbedding_of_continuous_injective_open continuous_inr inr_injective isOpenMap_inr theorem embedding_inl : Embedding (@inl X Y) := openEmbedding_inl.1 theorem embedding_inr : Embedding (@inr X Y) := openEmbedding_inr.1 theorem isOpen_range_inl : IsOpen (range (inl : X → X ⊕ Y)) := openEmbedding_inl.2 theorem isOpen_range_inr : IsOpen (range (inr : Y → X ⊕ Y)) := openEmbedding_inr.2 theorem isClosed_range_inl : IsClosed (range (inl : X → X ⊕ Y)) := by rw [← isOpen_compl_iff, compl_range_inl] exact isOpen_range_inr theorem isClosed_range_inr : IsClosed (range (inr : Y → X ⊕ Y)) := by rw [← isOpen_compl_iff, compl_range_inr] exact isOpen_range_inl theorem closedEmbedding_inl : ClosedEmbedding (inl : X → X ⊕ Y) := ⟨embedding_inl, isClosed_range_inl⟩ theorem closedEmbedding_inr : ClosedEmbedding (inr : Y → X ⊕ Y) := ⟨embedding_inr, isClosed_range_inr⟩ theorem nhds_inl (x : X) : 𝓝 (inl x : X ⊕ Y) = map inl (𝓝 x) := (openEmbedding_inl.map_nhds_eq _).symm theorem nhds_inr (y : Y) : 𝓝 (inr y : X ⊕ Y) = map inr (𝓝 y) := (openEmbedding_inr.map_nhds_eq _).symm @[simp] theorem continuous_sum_map {f : X → Y} {g : Z → W} : Continuous (Sum.map f g) ↔ Continuous f ∧ Continuous g := continuous_sum_elim.trans <| embedding_inl.continuous_iff.symm.and embedding_inr.continuous_iff.symm @[continuity, fun_prop] theorem Continuous.sum_map {f : X → Y} {g : Z → W} (hf : Continuous f) (hg : Continuous g) : Continuous (Sum.map f g) := continuous_sum_map.2 ⟨hf, hg⟩ theorem isOpenMap_sum {f : X ⊕ Y → Z} : IsOpenMap f ↔ (IsOpenMap fun a => f (inl a)) ∧ IsOpenMap fun b => f (inr b) := by simp only [isOpenMap_iff_nhds_le, Sum.forall, nhds_inl, nhds_inr, Filter.map_map, comp] @[simp] theorem isOpenMap_sum_elim {f : X → Z} {g : Y → Z} : IsOpenMap (Sum.elim f g) ↔ IsOpenMap f ∧ IsOpenMap g := by simp only [isOpenMap_sum, elim_inl, elim_inr] theorem IsOpenMap.sum_elim {f : X → Z} {g : Y → Z} (hf : IsOpenMap f) (hg : IsOpenMap g) : IsOpenMap (Sum.elim f g) := isOpenMap_sum_elim.2 ⟨hf, hg⟩ theorem isClosedMap_sum {f : X ⊕ Y → Z} : IsClosedMap f ↔ (IsClosedMap fun a => f (.inl a)) ∧ IsClosedMap fun b => f (.inr b) := by constructor · intro h exact ⟨h.comp closedEmbedding_inl.isClosedMap, h.comp closedEmbedding_inr.isClosedMap⟩ · rintro h Z hZ rw [isClosed_sum_iff] at hZ convert (h.1 _ hZ.1).union (h.2 _ hZ.2) ext simp only [mem_image, Sum.exists, mem_union, mem_preimage] end Sum section Subtype variable [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] {p : X → Prop} theorem inducing_subtype_val {t : Set Y} : Inducing ((↑) : t → Y) := ⟨rfl⟩ theorem Inducing.of_codRestrict {f : X → Y} {t : Set Y} (ht : ∀ x, f x ∈ t) (h : Inducing (t.codRestrict f ht)) : Inducing f := inducing_subtype_val.comp h theorem embedding_subtype_val : Embedding ((↑) : Subtype p → X) := ⟨inducing_subtype_val, Subtype.coe_injective⟩ theorem closedEmbedding_subtype_val (h : IsClosed { a | p a }) : ClosedEmbedding ((↑) : Subtype p → X) := ⟨embedding_subtype_val, by rwa [Subtype.range_coe_subtype]⟩ @[continuity, fun_prop] theorem continuous_subtype_val : Continuous (@Subtype.val X p) := continuous_induced_dom theorem Continuous.subtype_val {f : Y → Subtype p} (hf : Continuous f) : Continuous fun x => (f x : X) := continuous_subtype_val.comp hf theorem IsOpen.openEmbedding_subtype_val {s : Set X} (hs : IsOpen s) : OpenEmbedding ((↑) : s → X) := ⟨embedding_subtype_val, (@Subtype.range_coe _ s).symm ▸ hs⟩ theorem IsOpen.isOpenMap_subtype_val {s : Set X} (hs : IsOpen s) : IsOpenMap ((↑) : s → X) := hs.openEmbedding_subtype_val.isOpenMap theorem IsOpenMap.restrict {f : X → Y} (hf : IsOpenMap f) {s : Set X} (hs : IsOpen s) : IsOpenMap (s.restrict f) := hf.comp hs.isOpenMap_subtype_val nonrec theorem IsClosed.closedEmbedding_subtype_val {s : Set X} (hs : IsClosed s) : ClosedEmbedding ((↑) : s → X) := closedEmbedding_subtype_val hs theorem IsClosed.isClosedMap_subtype_val {s : Set X} (hs : IsClosed s) : IsClosedMap ((↑) : s → X) := hs.closedEmbedding_subtype_val.isClosedMap @[continuity, fun_prop] theorem Continuous.subtype_mk {f : Y → X} (h : Continuous f) (hp : ∀ x, p (f x)) : Continuous fun x => (⟨f x, hp x⟩ : Subtype p) := continuous_induced_rng.2 h theorem Continuous.subtype_map {f : X → Y} (h : Continuous f) {q : Y → Prop} (hpq : ∀ x, p x → q (f x)) : Continuous (Subtype.map f hpq) := (h.comp continuous_subtype_val).subtype_mk _ theorem continuous_inclusion {s t : Set X} (h : s ⊆ t) : Continuous (inclusion h) := continuous_id.subtype_map h theorem continuousAt_subtype_val {p : X → Prop} {x : Subtype p} : ContinuousAt ((↑) : Subtype p → X) x := continuous_subtype_val.continuousAt theorem Subtype.dense_iff {s : Set X} {t : Set s} : Dense t ↔ s ⊆ closure ((↑) '' t) := by rw [inducing_subtype_val.dense_iff, SetCoe.forall] rfl theorem map_nhds_subtype_val {s : Set X} (x : s) : map ((↑) : s → X) (𝓝 x) = 𝓝[s] ↑x := by rw [inducing_subtype_val.map_nhds_eq, Subtype.range_val] theorem map_nhds_subtype_coe_eq_nhds {x : X} (hx : p x) (h : ∀ᶠ x in 𝓝 x, p x) : map ((↑) : Subtype p → X) (𝓝 ⟨x, hx⟩) = 𝓝 x := map_nhds_induced_of_mem <| by rw [Subtype.range_val]; exact h theorem nhds_subtype_eq_comap {x : X} {h : p x} : 𝓝 (⟨x, h⟩ : Subtype p) = comap (↑) (𝓝 x) := nhds_induced _ _ theorem tendsto_subtype_rng {Y : Type*} {p : X → Prop} {l : Filter Y} {f : Y → Subtype p} : ∀ {x : Subtype p}, Tendsto f l (𝓝 x) ↔ Tendsto (fun x => (f x : X)) l (𝓝 (x : X)) | ⟨a, ha⟩ => by rw [nhds_subtype_eq_comap, tendsto_comap_iff]; rfl theorem closure_subtype {x : { a // p a }} {s : Set { a // p a }} : x ∈ closure s ↔ (x : X) ∈ closure (((↑) : _ → X) '' s) := closure_induced @[simp] theorem continuousAt_codRestrict_iff {f : X → Y} {t : Set Y} (h1 : ∀ x, f x ∈ t) {x : X} : ContinuousAt (codRestrict f t h1) x ↔ ContinuousAt f x := inducing_subtype_val.continuousAt_iff alias ⟨_, ContinuousAt.codRestrict⟩ := continuousAt_codRestrict_iff theorem ContinuousAt.restrict {f : X → Y} {s : Set X} {t : Set Y} (h1 : MapsTo f s t) {x : s} (h2 : ContinuousAt f x) : ContinuousAt (h1.restrict f s t) x := (h2.comp continuousAt_subtype_val).codRestrict _ theorem ContinuousAt.restrictPreimage {f : X → Y} {s : Set Y} {x : f ⁻¹' s} (h : ContinuousAt f x) : ContinuousAt (s.restrictPreimage f) x := h.restrict _ @[continuity, fun_prop] theorem Continuous.codRestrict {f : X → Y} {s : Set Y} (hf : Continuous f) (hs : ∀ a, f a ∈ s) : Continuous (s.codRestrict f hs) := hf.subtype_mk hs @[continuity, fun_prop] theorem Continuous.restrict {f : X → Y} {s : Set X} {t : Set Y} (h1 : MapsTo f s t) (h2 : Continuous f) : Continuous (h1.restrict f s t) := (h2.comp continuous_subtype_val).codRestrict _ @[continuity, fun_prop] theorem Continuous.restrictPreimage {f : X → Y} {s : Set Y} (h : Continuous f) : Continuous (s.restrictPreimage f) := h.restrict _ theorem Inducing.codRestrict {e : X → Y} (he : Inducing e) {s : Set Y} (hs : ∀ x, e x ∈ s) : Inducing (codRestrict e s hs) := inducing_of_inducing_compose (he.continuous.codRestrict hs) continuous_subtype_val he theorem Embedding.codRestrict {e : X → Y} (he : Embedding e) (s : Set Y) (hs : ∀ x, e x ∈ s) : Embedding (codRestrict e s hs) := embedding_of_embedding_compose (he.continuous.codRestrict hs) continuous_subtype_val he theorem embedding_inclusion {s t : Set X} (h : s ⊆ t) : Embedding (inclusion h) := embedding_subtype_val.codRestrict _ _ /-- Let `s, t ⊆ X` be two subsets of a topological space `X`. If `t ⊆ s` and the topology induced by `X`on `s` is discrete, then also the topology induces on `t` is discrete. -/ theorem DiscreteTopology.of_subset {X : Type*} [TopologicalSpace X] {s t : Set X} (_ : DiscreteTopology s) (ts : t ⊆ s) : DiscreteTopology t := (embedding_inclusion ts).discreteTopology /-- Let `s` be a discrete subset of a topological space. Then the preimage of `s` by a continuous injective map is also discrete. -/ theorem DiscreteTopology.preimage_of_continuous_injective {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] (s : Set Y) [DiscreteTopology s] {f : X → Y} (hc : Continuous f) (hinj : Function.Injective f) : DiscreteTopology (f ⁻¹' s) := DiscreteTopology.of_continuous_injective (β := s) (Continuous.restrict (by exact fun _ x ↦ x) hc) ((MapsTo.restrict_inj _).mpr hinj.injOn) /-- If `f : X → Y` is a quotient map, then its restriction to the preimage of an open set is a quotient map too. -/ theorem QuotientMap.restrictPreimage_isOpen {f : X → Y} (hf : QuotientMap f) {s : Set Y} (hs : IsOpen s) : QuotientMap (s.restrictPreimage f) := by refine quotientMap_iff.2 ⟨hf.surjective.restrictPreimage _, fun U ↦ ?_⟩ rw [hs.openEmbedding_subtype_val.open_iff_image_open, ← hf.isOpen_preimage, (hs.preimage hf.continuous).openEmbedding_subtype_val.open_iff_image_open, image_val_preimage_restrictPreimage] open scoped Set.Notation in lemma isClosed_preimage_val {s t : Set X} : IsClosed (s ↓∩ t) ↔ s ∩ closure (s ∩ t) ⊆ t := by rw [← closure_eq_iff_isClosed, embedding_subtype_val.closure_eq_preimage_closure_image, ← Subtype.val_injective.image_injective.eq_iff, Subtype.image_preimage_coe, Subtype.image_preimage_coe, subset_antisymm_iff, and_iff_left, Set.subset_inter_iff, and_iff_right] exacts [Set.inter_subset_left, Set.subset_inter Set.inter_subset_left subset_closure] end Subtype section Quotient variable [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] variable {r : X → X → Prop} {s : Setoid X} theorem quotientMap_quot_mk : QuotientMap (@Quot.mk X r) := ⟨Quot.exists_rep, rfl⟩ @[continuity, fun_prop] theorem continuous_quot_mk : Continuous (@Quot.mk X r) := continuous_coinduced_rng @[continuity, fun_prop] theorem continuous_quot_lift {f : X → Y} (hr : ∀ a b, r a b → f a = f b) (h : Continuous f) : Continuous (Quot.lift f hr : Quot r → Y) := continuous_coinduced_dom.2 h theorem quotientMap_quotient_mk' : QuotientMap (@Quotient.mk' X s) := quotientMap_quot_mk theorem continuous_quotient_mk' : Continuous (@Quotient.mk' X s) := continuous_coinduced_rng theorem Continuous.quotient_lift {f : X → Y} (h : Continuous f) (hs : ∀ a b, a ≈ b → f a = f b) : Continuous (Quotient.lift f hs : Quotient s → Y) := continuous_coinduced_dom.2 h theorem Continuous.quotient_liftOn' {f : X → Y} (h : Continuous f) (hs : ∀ a b, @Setoid.r _ s a b → f a = f b) : Continuous (fun x => Quotient.liftOn' x f hs : Quotient s → Y) := h.quotient_lift hs @[continuity, fun_prop] theorem Continuous.quotient_map' {t : Setoid Y} {f : X → Y} (hf : Continuous f) (H : (s.r ⇒ t.r) f f) : Continuous (Quotient.map' f H) := (continuous_quotient_mk'.comp hf).quotient_lift _ end Quotient section Pi variable {ι : Type*} {π : ι → Type*} {κ : Type*} [TopologicalSpace X] [T : ∀ i, TopologicalSpace (π i)] {f : X → ∀ i : ι, π i} theorem continuous_pi_iff : Continuous f ↔ ∀ i, Continuous fun a => f a i := by simp only [continuous_iInf_rng, continuous_induced_rng, comp] @[continuity, fun_prop] theorem continuous_pi (h : ∀ i, Continuous fun a => f a i) : Continuous f := continuous_pi_iff.2 h @[continuity, fun_prop] theorem continuous_apply (i : ι) : Continuous fun p : ∀ i, π i => p i := continuous_iInf_dom continuous_induced_dom @[continuity] theorem continuous_apply_apply {ρ : κ → ι → Type*} [∀ j i, TopologicalSpace (ρ j i)] (j : κ) (i : ι) : Continuous fun p : ∀ j, ∀ i, ρ j i => p j i := (continuous_apply i).comp (continuous_apply j) theorem continuousAt_apply (i : ι) (x : ∀ i, π i) : ContinuousAt (fun p : ∀ i, π i => p i) x := (continuous_apply i).continuousAt theorem Filter.Tendsto.apply_nhds {l : Filter Y} {f : Y → ∀ i, π i} {x : ∀ i, π i} (h : Tendsto f l (𝓝 x)) (i : ι) : Tendsto (fun a => f a i) l (𝓝 <| x i) := (continuousAt_apply i _).tendsto.comp h theorem nhds_pi {a : ∀ i, π i} : 𝓝 a = pi fun i => 𝓝 (a i) := by simp only [nhds_iInf, nhds_induced, Filter.pi] theorem tendsto_pi_nhds {f : Y → ∀ i, π i} {g : ∀ i, π i} {u : Filter Y} : Tendsto f u (𝓝 g) ↔ ∀ x, Tendsto (fun i => f i x) u (𝓝 (g x)) := by rw [nhds_pi, Filter.tendsto_pi] theorem continuousAt_pi {f : X → ∀ i, π i} {x : X} : ContinuousAt f x ↔ ∀ i, ContinuousAt (fun y => f y i) x := tendsto_pi_nhds @[fun_prop] theorem continuousAt_pi' {f : X → ∀ i, π i} {x : X} (hf : ∀ i, ContinuousAt (fun y => f y i) x) : ContinuousAt f x := continuousAt_pi.2 hf theorem Pi.continuous_precomp' {ι' : Type*} (φ : ι' → ι) : Continuous (fun (f : (∀ i, π i)) (j : ι') ↦ f (φ j)) := continuous_pi fun j ↦ continuous_apply (φ j) theorem Pi.continuous_precomp {ι' : Type*} (φ : ι' → ι) : Continuous (· ∘ φ : (ι → X) → (ι' → X)) := Pi.continuous_precomp' φ theorem Pi.continuous_postcomp' {X : ι → Type*} [∀ i, TopologicalSpace (X i)] {g : ∀ i, π i → X i} (hg : ∀ i, Continuous (g i)) : Continuous (fun (f : (∀ i, π i)) (i : ι) ↦ g i (f i)) := continuous_pi fun i ↦ (hg i).comp <| continuous_apply i theorem Pi.continuous_postcomp [TopologicalSpace Y] {g : X → Y} (hg : Continuous g) : Continuous (g ∘ · : (ι → X) → (ι → Y)) := Pi.continuous_postcomp' fun _ ↦ hg lemma Pi.induced_precomp' {ι' : Type*} (φ : ι' → ι) : induced (fun (f : (∀ i, π i)) (j : ι') ↦ f (φ j)) Pi.topologicalSpace = ⨅ i', induced (eval (φ i')) (T (φ i')) := by simp [Pi.topologicalSpace, induced_iInf, induced_compose, comp] lemma Pi.induced_precomp [TopologicalSpace Y] {ι' : Type*} (φ : ι' → ι) : induced (· ∘ φ) Pi.topologicalSpace = ⨅ i', induced (eval (φ i')) ‹TopologicalSpace Y› := induced_precomp' φ lemma Pi.continuous_restrict (S : Set ι) : Continuous (S.restrict : (∀ i : ι, π i) → (∀ i : S, π i)) := Pi.continuous_precomp' ((↑) : S → ι) lemma Pi.induced_restrict (S : Set ι) : induced (S.restrict) Pi.topologicalSpace = ⨅ i ∈ S, induced (eval i) (T i) := by simp (config := { unfoldPartialApp := true }) [← iInf_subtype'', ← induced_precomp' ((↑) : S → ι), restrict] lemma Pi.induced_restrict_sUnion (𝔖 : Set (Set ι)) : induced (⋃₀ 𝔖).restrict (Pi.topologicalSpace (Y := fun i : (⋃₀ 𝔖) ↦ π i)) = ⨅ S ∈ 𝔖, induced S.restrict Pi.topologicalSpace := by simp_rw [Pi.induced_restrict, iInf_sUnion] theorem Filter.Tendsto.update [DecidableEq ι] {l : Filter Y} {f : Y → ∀ i, π i} {x : ∀ i, π i} (hf : Tendsto f l (𝓝 x)) (i : ι) {g : Y → π i} {xi : π i} (hg : Tendsto g l (𝓝 xi)) : Tendsto (fun a => update (f a) i (g a)) l (𝓝 <| update x i xi) := tendsto_pi_nhds.2 fun j => by rcases eq_or_ne j i with (rfl | hj) <;> simp [*, hf.apply_nhds] theorem ContinuousAt.update [DecidableEq ι] {x : X} (hf : ContinuousAt f x) (i : ι) {g : X → π i} (hg : ContinuousAt g x) : ContinuousAt (fun a => update (f a) i (g a)) x := hf.tendsto.update i hg theorem Continuous.update [DecidableEq ι] (hf : Continuous f) (i : ι) {g : X → π i} (hg : Continuous g) : Continuous fun a => update (f a) i (g a) := continuous_iff_continuousAt.2 fun _ => hf.continuousAt.update i hg.continuousAt /-- `Function.update f i x` is continuous in `(f, x)`. -/ @[continuity, fun_prop] theorem continuous_update [DecidableEq ι] (i : ι) : Continuous fun f : (∀ j, π j) × π i => update f.1 i f.2 := continuous_fst.update i continuous_snd /-- `Pi.mulSingle i x` is continuous in `x`. -/ -- Porting note (#11215): TODO: restore @[continuity] @[to_additive "`Pi.single i x` is continuous in `x`."] theorem continuous_mulSingle [∀ i, One (π i)] [DecidableEq ι] (i : ι) : Continuous fun x => (Pi.mulSingle i x : ∀ i, π i) := continuous_const.update _ continuous_id theorem Filter.Tendsto.fin_insertNth {n} {π : Fin (n + 1) → Type*} [∀ i, TopologicalSpace (π i)] (i : Fin (n + 1)) {f : Y → π i} {l : Filter Y} {x : π i} (hf : Tendsto f l (𝓝 x)) {g : Y → ∀ j : Fin n, π (i.succAbove j)} {y : ∀ j, π (i.succAbove j)} (hg : Tendsto g l (𝓝 y)) : Tendsto (fun a => i.insertNth (f a) (g a)) l (𝓝 <| i.insertNth x y) := tendsto_pi_nhds.2 fun j => Fin.succAboveCases i (by simpa) (by simpa using tendsto_pi_nhds.1 hg) j theorem ContinuousAt.fin_insertNth {n} {π : Fin (n + 1) → Type*} [∀ i, TopologicalSpace (π i)] (i : Fin (n + 1)) {f : X → π i} {x : X} (hf : ContinuousAt f x) {g : X → ∀ j : Fin n, π (i.succAbove j)} (hg : ContinuousAt g x) : ContinuousAt (fun a => i.insertNth (f a) (g a)) x := hf.tendsto.fin_insertNth i hg theorem Continuous.fin_insertNth {n} {π : Fin (n + 1) → Type*} [∀ i, TopologicalSpace (π i)] (i : Fin (n + 1)) {f : X → π i} (hf : Continuous f) {g : X → ∀ j : Fin n, π (i.succAbove j)} (hg : Continuous g) : Continuous fun a => i.insertNth (f a) (g a) := continuous_iff_continuousAt.2 fun _ => hf.continuousAt.fin_insertNth i hg.continuousAt theorem isOpen_set_pi {i : Set ι} {s : ∀ a, Set (π a)} (hi : i.Finite) (hs : ∀ a ∈ i, IsOpen (s a)) : IsOpen (pi i s) := by rw [pi_def]; exact hi.isOpen_biInter fun a ha => (hs _ ha).preimage (continuous_apply _) theorem isOpen_pi_iff {s : Set (∀ a, π a)} : IsOpen s ↔ ∀ f, f ∈ s → ∃ (I : Finset ι) (u : ∀ a, Set (π a)), (∀ a, a ∈ I → IsOpen (u a) ∧ f a ∈ u a) ∧ (I : Set ι).pi u ⊆ s := by rw [isOpen_iff_nhds] simp_rw [le_principal_iff, nhds_pi, Filter.mem_pi', mem_nhds_iff] refine forall₂_congr fun a _ => ⟨?_, ?_⟩ · rintro ⟨I, t, ⟨h1, h2⟩⟩ refine ⟨I, fun a => eval a '' (I : Set ι).pi fun a => (h1 a).choose, fun i hi => ?_, ?_⟩ · simp_rw [eval_image_pi (Finset.mem_coe.mpr hi) (pi_nonempty_iff.mpr fun i => ⟨_, fun _ => (h1 i).choose_spec.2.2⟩)] exact (h1 i).choose_spec.2 · exact Subset.trans (pi_mono fun i hi => (eval_image_pi_subset hi).trans (h1 i).choose_spec.1) h2 · rintro ⟨I, t, ⟨h1, h2⟩⟩ classical refine ⟨I, fun a => ite (a ∈ I) (t a) univ, fun i => ?_, ?_⟩ · by_cases hi : i ∈ I · use t i simp_rw [if_pos hi] exact ⟨Subset.rfl, (h1 i) hi⟩ · use univ simp_rw [if_neg hi] exact ⟨Subset.rfl, isOpen_univ, mem_univ _⟩ · rw [← univ_pi_ite] simp only [← ite_and, ← Finset.mem_coe, and_self_iff, univ_pi_ite, h2] theorem isOpen_pi_iff' [Finite ι] {s : Set (∀ a, π a)} : IsOpen s ↔ ∀ f, f ∈ s → ∃ u : ∀ a, Set (π a), (∀ a, IsOpen (u a) ∧ f a ∈ u a) ∧ univ.pi u ⊆ s := by cases nonempty_fintype ι rw [isOpen_iff_nhds] simp_rw [le_principal_iff, nhds_pi, Filter.mem_pi', mem_nhds_iff] refine forall₂_congr fun a _ => ⟨?_, ?_⟩ · rintro ⟨I, t, ⟨h1, h2⟩⟩ refine ⟨fun i => (h1 i).choose, ⟨fun i => (h1 i).choose_spec.2, (pi_mono fun i _ => (h1 i).choose_spec.1).trans (Subset.trans ?_ h2)⟩⟩ rw [← pi_inter_compl (I : Set ι)] exact inter_subset_left · exact fun ⟨u, ⟨h1, _⟩⟩ => ⟨Finset.univ, u, ⟨fun i => ⟨u i, ⟨rfl.subset, h1 i⟩⟩, by rwa [Finset.coe_univ]⟩⟩ theorem isClosed_set_pi {i : Set ι} {s : ∀ a, Set (π a)} (hs : ∀ a ∈ i, IsClosed (s a)) : IsClosed (pi i s) := by rw [pi_def]; exact isClosed_biInter fun a ha => (hs _ ha).preimage (continuous_apply _) theorem mem_nhds_of_pi_mem_nhds {I : Set ι} {s : ∀ i, Set (π i)} (a : ∀ i, π i) (hs : I.pi s ∈ 𝓝 a) {i : ι} (hi : i ∈ I) : s i ∈ 𝓝 (a i) := by rw [nhds_pi] at hs; exact mem_of_pi_mem_pi hs hi theorem set_pi_mem_nhds {i : Set ι} {s : ∀ a, Set (π a)} {x : ∀ a, π a} (hi : i.Finite) (hs : ∀ a ∈ i, s a ∈ 𝓝 (x a)) : pi i s ∈ 𝓝 x := by rw [pi_def, biInter_mem hi] exact fun a ha => (continuous_apply a).continuousAt (hs a ha) theorem set_pi_mem_nhds_iff {I : Set ι} (hI : I.Finite) {s : ∀ i, Set (π i)} (a : ∀ i, π i) : I.pi s ∈ 𝓝 a ↔ ∀ i : ι, i ∈ I → s i ∈ 𝓝 (a i) := by rw [nhds_pi, pi_mem_pi_iff hI] theorem interior_pi_set {I : Set ι} (hI : I.Finite) {s : ∀ i, Set (π i)} : interior (pi I s) = I.pi fun i => interior (s i) := by ext a simp only [Set.mem_pi, mem_interior_iff_mem_nhds, set_pi_mem_nhds_iff hI] theorem exists_finset_piecewise_mem_of_mem_nhds [DecidableEq ι] {s : Set (∀ a, π a)} {x : ∀ a, π a} (hs : s ∈ 𝓝 x) (y : ∀ a, π a) : ∃ I : Finset ι, I.piecewise x y ∈ s := by simp only [nhds_pi, Filter.mem_pi'] at hs rcases hs with ⟨I, t, htx, hts⟩ refine ⟨I, hts fun i hi => ?_⟩ simpa [Finset.mem_coe.1 hi] using mem_of_mem_nhds (htx i) theorem pi_generateFrom_eq {π : ι → Type*} {g : ∀ a, Set (Set (π a))} : (@Pi.topologicalSpace ι π fun a => generateFrom (g a)) = generateFrom { t | ∃ (s : ∀ a, Set (π a)) (i : Finset ι), (∀ a ∈ i, s a ∈ g a) ∧ t = pi (↑i) s } := by refine le_antisymm ?_ ?_ · apply le_generateFrom rintro _ ⟨s, i, hi, rfl⟩ letI := fun a => generateFrom (g a) exact isOpen_set_pi i.finite_toSet (fun a ha => GenerateOpen.basic _ (hi a ha)) · classical refine le_iInf fun i => coinduced_le_iff_le_induced.1 <| le_generateFrom fun s hs => ?_ refine GenerateOpen.basic _ ⟨update (fun i => univ) i s, {i}, ?_⟩ simp [hs] theorem pi_eq_generateFrom : Pi.topologicalSpace = generateFrom { g | ∃ (s : ∀ a, Set (π a)) (i : Finset ι), (∀ a ∈ i, IsOpen (s a)) ∧ g = pi (↑i) s } := calc Pi.topologicalSpace _ = @Pi.topologicalSpace ι π fun a => generateFrom { s | IsOpen s } := by simp only [generateFrom_setOf_isOpen] _ = _ := pi_generateFrom_eq theorem pi_generateFrom_eq_finite {π : ι → Type*} {g : ∀ a, Set (Set (π a))} [Finite ι] (hg : ∀ a, ⋃₀ g a = univ) : (@Pi.topologicalSpace ι π fun a => generateFrom (g a)) = generateFrom { t | ∃ s : ∀ a, Set (π a), (∀ a, s a ∈ g a) ∧ t = pi univ s } := by cases nonempty_fintype ι rw [pi_generateFrom_eq] refine le_antisymm (generateFrom_anti ?_) (le_generateFrom ?_) · exact fun s ⟨t, ht, Eq⟩ => ⟨t, Finset.univ, by simp [ht, Eq]⟩ · rintro s ⟨t, i, ht, rfl⟩ letI := generateFrom { t | ∃ s : ∀ a, Set (π a), (∀ a, s a ∈ g a) ∧ t = pi univ s } refine isOpen_iff_forall_mem_open.2 fun f hf => ?_ choose c hcg hfc using fun a => sUnion_eq_univ_iff.1 (hg a) (f a) refine ⟨pi i t ∩ pi ((↑i)ᶜ : Set ι) c, inter_subset_left, ?_, ⟨hf, fun a _ => hfc a⟩⟩ classical rw [← univ_pi_piecewise] refine GenerateOpen.basic _ ⟨_, fun a => ?_, rfl⟩ by_cases a ∈ i <;> simp [*] theorem induced_to_pi {X : Type*} (f : X → ∀ i, π i) : induced f Pi.topologicalSpace = ⨅ i, induced (f · i) inferInstance := by simp_rw [Pi.topologicalSpace, induced_iInf, induced_compose, Function.comp] /-- Suppose `π i` is a family of topological spaces indexed by `i : ι`, and `X` is a type endowed with a family of maps `f i : X → π i` for every `i : ι`, hence inducing a map `g : X → Π i, π i`. This lemma shows that infimum of the topologies on `X` induced by the `f i` as `i : ι` varies is simply the topology on `X` induced by `g : X → Π i, π i` where `Π i, π i` is endowed with the usual product topology. -/ theorem inducing_iInf_to_pi {X : Type*} (f : ∀ i, X → π i) : @Inducing X (∀ i, π i) (⨅ i, induced (f i) inferInstance) _ fun x i => f i x := letI := ⨅ i, induced (f i) inferInstance; ⟨(induced_to_pi _).symm⟩ variable [Finite ι] [∀ i, DiscreteTopology (π i)] /-- A finite product of discrete spaces is discrete. -/ instance Pi.discreteTopology : DiscreteTopology (∀ i, π i) := singletons_open_iff_discrete.mp fun x => by rw [← univ_pi_singleton] exact isOpen_set_pi finite_univ fun i _ => (isOpen_discrete {x i}) end Pi section Sigma variable {ι κ : Type*} {σ : ι → Type*} {τ : κ → Type*} [∀ i, TopologicalSpace (σ i)] [∀ k, TopologicalSpace (τ k)] [TopologicalSpace X] @[continuity, fun_prop] theorem continuous_sigmaMk {i : ι} : Continuous (@Sigma.mk ι σ i) := continuous_iSup_rng continuous_coinduced_rng -- Porting note: the proof was `by simp only [isOpen_iSup_iff, isOpen_coinduced]` theorem isOpen_sigma_iff {s : Set (Sigma σ)} : IsOpen s ↔ ∀ i, IsOpen (Sigma.mk i ⁻¹' s) := by delta instTopologicalSpaceSigma rw [isOpen_iSup_iff] rfl theorem isClosed_sigma_iff {s : Set (Sigma σ)} : IsClosed s ↔ ∀ i, IsClosed (Sigma.mk i ⁻¹' s) := by simp only [← isOpen_compl_iff, isOpen_sigma_iff, preimage_compl] theorem isOpenMap_sigmaMk {i : ι} : IsOpenMap (@Sigma.mk ι σ i) := by intro s hs rw [isOpen_sigma_iff] intro j rcases eq_or_ne j i with (rfl | hne) · rwa [preimage_image_eq _ sigma_mk_injective] · rw [preimage_image_sigmaMk_of_ne hne] exact isOpen_empty theorem isOpen_range_sigmaMk {i : ι} : IsOpen (range (@Sigma.mk ι σ i)) := isOpenMap_sigmaMk.isOpen_range theorem isClosedMap_sigmaMk {i : ι} : IsClosedMap (@Sigma.mk ι σ i) := by intro s hs rw [isClosed_sigma_iff] intro j rcases eq_or_ne j i with (rfl | hne) · rwa [preimage_image_eq _ sigma_mk_injective] · rw [preimage_image_sigmaMk_of_ne hne] exact isClosed_empty theorem isClosed_range_sigmaMk {i : ι} : IsClosed (range (@Sigma.mk ι σ i)) := isClosedMap_sigmaMk.isClosed_range theorem openEmbedding_sigmaMk {i : ι} : OpenEmbedding (@Sigma.mk ι σ i) := openEmbedding_of_continuous_injective_open continuous_sigmaMk sigma_mk_injective isOpenMap_sigmaMk theorem closedEmbedding_sigmaMk {i : ι} : ClosedEmbedding (@Sigma.mk ι σ i) := closedEmbedding_of_continuous_injective_closed continuous_sigmaMk sigma_mk_injective isClosedMap_sigmaMk theorem embedding_sigmaMk {i : ι} : Embedding (@Sigma.mk ι σ i) := closedEmbedding_sigmaMk.1 theorem Sigma.nhds_mk (i : ι) (x : σ i) : 𝓝 (⟨i, x⟩ : Sigma σ) = Filter.map (Sigma.mk i) (𝓝 x) := (openEmbedding_sigmaMk.map_nhds_eq x).symm theorem Sigma.nhds_eq (x : Sigma σ) : 𝓝 x = Filter.map (Sigma.mk x.1) (𝓝 x.2) := by cases x apply Sigma.nhds_mk theorem comap_sigmaMk_nhds (i : ι) (x : σ i) : comap (Sigma.mk i) (𝓝 ⟨i, x⟩) = 𝓝 x := (embedding_sigmaMk.nhds_eq_comap _).symm theorem isOpen_sigma_fst_preimage (s : Set ι) : IsOpen (Sigma.fst ⁻¹' s : Set (Σ a, σ a)) := by rw [← biUnion_of_singleton s, preimage_iUnion₂] simp only [← range_sigmaMk] exact isOpen_biUnion fun _ _ => isOpen_range_sigmaMk /-- A map out of a sum type is continuous iff its restriction to each summand is. -/ @[simp] theorem continuous_sigma_iff {f : Sigma σ → X} : Continuous f ↔ ∀ i, Continuous fun a => f ⟨i, a⟩ := by delta instTopologicalSpaceSigma rw [continuous_iSup_dom] exact forall_congr' fun _ => continuous_coinduced_dom /-- A map out of a sum type is continuous if its restriction to each summand is. -/ @[continuity, fun_prop] theorem continuous_sigma {f : Sigma σ → X} (hf : ∀ i, Continuous fun a => f ⟨i, a⟩) : Continuous f := continuous_sigma_iff.2 hf /-- A map defined on a sigma type (a.k.a. the disjoint union of an indexed family of topological spaces) is inducing iff its restriction to each component is inducing and each the image of each component under `f` can be separated from the images of all other components by an open set. -/ theorem inducing_sigma {f : Sigma σ → X} : Inducing f ↔ (∀ i, Inducing (f ∘ Sigma.mk i)) ∧ (∀ i, ∃ U, IsOpen U ∧ ∀ x, f x ∈ U ↔ x.1 = i) := by refine ⟨fun h ↦ ⟨fun i ↦ h.comp embedding_sigmaMk.1, fun i ↦ ?_⟩, ?_⟩ · rcases h.isOpen_iff.1 (isOpen_range_sigmaMk (i := i)) with ⟨U, hUo, hU⟩ refine ⟨U, hUo, ?_⟩ simpa [Set.ext_iff] using hU · refine fun ⟨h₁, h₂⟩ ↦ inducing_iff_nhds.2 fun ⟨i, x⟩ ↦ ?_ rw [Sigma.nhds_mk, (h₁ i).nhds_eq_comap, comp_apply, ← comap_comap, map_comap_of_mem] rcases h₂ i with ⟨U, hUo, hU⟩ filter_upwards [preimage_mem_comap <| hUo.mem_nhds <| (hU _).2 rfl] with y hy simpa [hU] using hy @[simp 1100] theorem continuous_sigma_map {f₁ : ι → κ} {f₂ : ∀ i, σ i → τ (f₁ i)} : Continuous (Sigma.map f₁ f₂) ↔ ∀ i, Continuous (f₂ i) := continuous_sigma_iff.trans <| by simp only [Sigma.map, embedding_sigmaMk.continuous_iff, comp] @[continuity, fun_prop] theorem Continuous.sigma_map {f₁ : ι → κ} {f₂ : ∀ i, σ i → τ (f₁ i)} (hf : ∀ i, Continuous (f₂ i)) : Continuous (Sigma.map f₁ f₂) := continuous_sigma_map.2 hf theorem isOpenMap_sigma {f : Sigma σ → X} : IsOpenMap f ↔ ∀ i, IsOpenMap fun a => f ⟨i, a⟩ := by simp only [isOpenMap_iff_nhds_le, Sigma.forall, Sigma.nhds_eq, map_map, comp] theorem isOpenMap_sigma_map {f₁ : ι → κ} {f₂ : ∀ i, σ i → τ (f₁ i)} : IsOpenMap (Sigma.map f₁ f₂) ↔ ∀ i, IsOpenMap (f₂ i) := isOpenMap_sigma.trans <| forall_congr' fun i => (@openEmbedding_sigmaMk _ _ _ (f₁ i)).isOpenMap_iff.symm theorem inducing_sigma_map {f₁ : ι → κ} {f₂ : ∀ i, σ i → τ (f₁ i)} (h₁ : Injective f₁) : Inducing (Sigma.map f₁ f₂) ↔ ∀ i, Inducing (f₂ i) := by simp only [inducing_iff_nhds, Sigma.forall, Sigma.nhds_mk, Sigma.map_mk, ← map_sigma_mk_comap h₁, map_inj sigma_mk_injective] theorem embedding_sigma_map {f₁ : ι → κ} {f₂ : ∀ i, σ i → τ (f₁ i)} (h : Injective f₁) : Embedding (Sigma.map f₁ f₂) ↔ ∀ i, Embedding (f₂ i) := by simp only [embedding_iff, Injective.sigma_map, inducing_sigma_map h, forall_and, h.sigma_map_iff] theorem openEmbedding_sigma_map {f₁ : ι → κ} {f₂ : ∀ i, σ i → τ (f₁ i)} (h : Injective f₁) : OpenEmbedding (Sigma.map f₁ f₂) ↔ ∀ i, OpenEmbedding (f₂ i) := by simp only [openEmbedding_iff_embedding_open, isOpenMap_sigma_map, embedding_sigma_map h, forall_and] end Sigma section ULift theorem ULift.isOpen_iff [TopologicalSpace X] {s : Set (ULift.{v} X)} : IsOpen s ↔ IsOpen (ULift.up ⁻¹' s) := by rw [ULift.topologicalSpace, ← Equiv.ulift_apply, ← Equiv.ulift.coinduced_symm, ← isOpen_coinduced] theorem ULift.isClosed_iff [TopologicalSpace X] {s : Set (ULift.{v} X)} : IsClosed s ↔ IsClosed (ULift.up ⁻¹' s) := by rw [← isOpen_compl_iff, ← isOpen_compl_iff, isOpen_iff, preimage_compl] @[continuity] theorem continuous_uLift_down [TopologicalSpace X] : Continuous (ULift.down : ULift.{v, u} X → X) := continuous_induced_dom @[continuity] theorem continuous_uLift_up [TopologicalSpace X] : Continuous (ULift.up : X → ULift.{v, u} X) := continuous_induced_rng.2 continuous_id theorem embedding_uLift_down [TopologicalSpace X] : Embedding (ULift.down : ULift.{v, u} X → X) := ⟨⟨rfl⟩, ULift.down_injective⟩ theorem ULift.closedEmbedding_down [TopologicalSpace X] : ClosedEmbedding (ULift.down : ULift.{v, u} X → X) := ⟨embedding_uLift_down, by simp only [ULift.down_surjective.range_eq, isClosed_univ]⟩ instance [TopologicalSpace X] [DiscreteTopology X] : DiscreteTopology (ULift X) := embedding_uLift_down.discreteTopology end ULift section Monad variable [TopologicalSpace X] {s : Set X} {t : Set s} theorem IsOpen.trans (ht : IsOpen t) (hs : IsOpen s) : IsOpen (t : Set X) := by rcases isOpen_induced_iff.mp ht with ⟨s', hs', rfl⟩ rw [Subtype.image_preimage_coe] exact hs.inter hs' theorem IsClosed.trans (ht : IsClosed t) (hs : IsClosed s) : IsClosed (t : Set X) := by rcases isClosed_induced_iff.mp ht with ⟨s', hs', rfl⟩ rw [Subtype.image_preimage_coe] exact hs.inter hs' end Monad section NhdsSet variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {f : Filter X} {s : Set X} {t : Set Y} {x : X} /-- The product of a neighborhood of `s` and a neighborhood of `t` is a neighborhood of `s ×ˢ t`, formulated in terms of a filter inequality. -/ theorem nhdsSet_prod_le (s : Set X) (t : Set Y) : 𝓝ˢ (s ×ˢ t) ≤ 𝓝ˢ s ×ˢ 𝓝ˢ t := ((hasBasis_nhdsSet _).prod (hasBasis_nhdsSet _)).ge_iff.2 fun (_u, _v) ⟨⟨huo, hsu⟩, hvo, htv⟩ ↦ (huo.prod hvo).mem_nhdsSet.2 <| prod_mono hsu htv theorem Filter.eventually_nhdsSet_prod_iff {p : X × Y → Prop} : (∀ᶠ q in 𝓝ˢ (s ×ˢ t), p q) ↔ ∀ x ∈ s, ∀ y ∈ t, ∃ px : X → Prop, (∀ᶠ x' in 𝓝 x, px x') ∧ ∃ py : Y → Prop, (∀ᶠ y' in 𝓝 y, py y') ∧ ∀ {x : X}, px x → ∀ {y : Y}, py y → p (x, y) := by simp_rw [eventually_nhdsSet_iff_forall, forall_prod_set, nhds_prod_eq, eventually_prod_iff] theorem Filter.Eventually.prod_nhdsSet {p : X × Y → Prop} {px : X → Prop} {py : Y → Prop} (hp : ∀ {x : X}, px x → ∀ {y : Y}, py y → p (x, y)) (hs : ∀ᶠ x in 𝓝ˢ s, px x) (ht : ∀ᶠ y in 𝓝ˢ t, py y) : ∀ᶠ q in 𝓝ˢ (s ×ˢ t), p q := nhdsSet_prod_le _ _ (mem_of_superset (prod_mem_prod hs ht) fun _ ⟨hx, hy⟩ ↦ hp hx hy) end NhdsSet
Topology\ContinuousOn.lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Topology.Constructions /-! # Neighborhoods and continuity relative to a subset This file defines relative versions * `nhdsWithin` of `nhds` * `ContinuousOn` of `Continuous` * `ContinuousWithinAt` of `ContinuousAt` and proves their basic properties, including the relationships between these restricted notions and the corresponding notions for the subtype equipped with the subspace topology. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhdsWithin x s` of neighborhoods of a point `x` within a set `s`. -/ open Set Filter Function Topology Filter variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variable [TopologicalSpace α] @[simp] theorem nhds_bind_nhdsWithin {a : α} {s : Set α} : ((𝓝 a).bind fun x => 𝓝[s] x) = 𝓝[s] a := bind_inf_principal.trans <| congr_arg₂ _ nhds_bind_nhds rfl @[simp] theorem eventually_nhds_nhdsWithin {a : α} {s : Set α} {p : α → Prop} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := Filter.ext_iff.1 nhds_bind_nhdsWithin { x | p x } theorem eventually_nhdsWithin_iff {a : α} {s : Set α} {p : α → Prop} : (∀ᶠ x in 𝓝[s] a, p x) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → p x := eventually_inf_principal theorem frequently_nhdsWithin_iff {z : α} {s : Set α} {p : α → Prop} : (∃ᶠ x in 𝓝[s] z, p x) ↔ ∃ᶠ x in 𝓝 z, p x ∧ x ∈ s := frequently_inf_principal.trans <| by simp only [and_comm] theorem mem_closure_ne_iff_frequently_within {z : α} {s : Set α} : z ∈ closure (s \ {z}) ↔ ∃ᶠ x in 𝓝[≠] z, x ∈ s := by simp [mem_closure_iff_frequently, frequently_nhdsWithin_iff] @[simp] theorem eventually_nhdsWithin_nhdsWithin {a : α} {s : Set α} {p : α → Prop} : (∀ᶠ y in 𝓝[s] a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := by refine ⟨fun h => ?_, fun h => (eventually_nhds_nhdsWithin.2 h).filter_mono inf_le_left⟩ simp only [eventually_nhdsWithin_iff] at h ⊢ exact h.mono fun x hx hxs => (hx hxs).self_of_nhds hxs theorem nhdsWithin_eq (a : α) (s : Set α) : 𝓝[s] a = ⨅ t ∈ { t : Set α | a ∈ t ∧ IsOpen t }, 𝓟 (t ∩ s) := ((nhds_basis_opens a).inf_principal s).eq_biInf @[simp] lemma nhdsWithin_univ (a : α) : 𝓝[Set.univ] a = 𝓝 a := by rw [nhdsWithin, principal_univ, inf_top_eq] theorem nhdsWithin_hasBasis {p : β → Prop} {s : β → Set α} {a : α} (h : (𝓝 a).HasBasis p s) (t : Set α) : (𝓝[t] a).HasBasis p fun i => s i ∩ t := h.inf_principal t theorem nhdsWithin_basis_open (a : α) (t : Set α) : (𝓝[t] a).HasBasis (fun u => a ∈ u ∧ IsOpen u) fun u => u ∩ t := nhdsWithin_hasBasis (nhds_basis_opens a) t theorem mem_nhdsWithin {t : Set α} {a : α} {s : Set α} : t ∈ 𝓝[s] a ↔ ∃ u, IsOpen u ∧ a ∈ u ∧ u ∩ s ⊆ t := by simpa only [and_assoc, and_left_comm] using (nhdsWithin_basis_open a s).mem_iff theorem mem_nhdsWithin_iff_exists_mem_nhds_inter {t : Set α} {a : α} {s : Set α} : t ∈ 𝓝[s] a ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t := (nhdsWithin_hasBasis (𝓝 a).basis_sets s).mem_iff theorem diff_mem_nhdsWithin_compl {x : α} {s : Set α} (hs : s ∈ 𝓝 x) (t : Set α) : s \ t ∈ 𝓝[tᶜ] x := diff_mem_inf_principal_compl hs t theorem diff_mem_nhdsWithin_diff {x : α} {s t : Set α} (hs : s ∈ 𝓝[t] x) (t' : Set α) : s \ t' ∈ 𝓝[t \ t'] x := by rw [nhdsWithin, diff_eq, diff_eq, ← inf_principal, ← inf_assoc] exact inter_mem_inf hs (mem_principal_self _) theorem nhds_of_nhdsWithin_of_nhds {s t : Set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ 𝓝[s] a) : t ∈ 𝓝 a := by rcases mem_nhdsWithin_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩ exact (𝓝 a).sets_of_superset ((𝓝 a).inter_sets Hw h1) hw theorem mem_nhdsWithin_iff_eventually {s t : Set α} {x : α} : t ∈ 𝓝[s] x ↔ ∀ᶠ y in 𝓝 x, y ∈ s → y ∈ t := eventually_inf_principal theorem mem_nhdsWithin_iff_eventuallyEq {s t : Set α} {x : α} : t ∈ 𝓝[s] x ↔ s =ᶠ[𝓝 x] (s ∩ t : Set α) := by simp_rw [mem_nhdsWithin_iff_eventually, eventuallyEq_set, mem_inter_iff, iff_self_and] theorem nhdsWithin_eq_iff_eventuallyEq {s t : Set α} {x : α} : 𝓝[s] x = 𝓝[t] x ↔ s =ᶠ[𝓝 x] t := set_eventuallyEq_iff_inf_principal.symm theorem nhdsWithin_le_iff {s t : Set α} {x : α} : 𝓝[s] x ≤ 𝓝[t] x ↔ t ∈ 𝓝[s] x := set_eventuallyLE_iff_inf_principal_le.symm.trans set_eventuallyLE_iff_mem_inf_principal -- Porting note: golfed, dropped an unneeded assumption theorem preimage_nhdsWithin_coinduced' {π : α → β} {s : Set β} {t : Set α} {a : α} (h : a ∈ t) (hs : s ∈ @nhds β (.coinduced (fun x : t => π x) inferInstance) (π a)) : π ⁻¹' s ∈ 𝓝[t] a := by lift a to t using h replace hs : (fun x : t => π x) ⁻¹' s ∈ 𝓝 a := preimage_nhds_coinduced hs rwa [← map_nhds_subtype_val, mem_map] theorem mem_nhdsWithin_of_mem_nhds {s t : Set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ 𝓝[t] a := mem_inf_of_left h theorem self_mem_nhdsWithin {a : α} {s : Set α} : s ∈ 𝓝[s] a := mem_inf_of_right (mem_principal_self s) theorem eventually_mem_nhdsWithin {a : α} {s : Set α} : ∀ᶠ x in 𝓝[s] a, x ∈ s := self_mem_nhdsWithin theorem inter_mem_nhdsWithin (s : Set α) {t : Set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ 𝓝[s] a := inter_mem self_mem_nhdsWithin (mem_inf_of_left h) theorem pure_le_nhdsWithin {a : α} {s : Set α} (ha : a ∈ s) : pure a ≤ 𝓝[s] a := le_inf (pure_le_nhds a) (le_principal_iff.2 ha) theorem mem_of_mem_nhdsWithin {a : α} {s t : Set α} (ha : a ∈ s) (ht : t ∈ 𝓝[s] a) : a ∈ t := pure_le_nhdsWithin ha ht theorem Filter.Eventually.self_of_nhdsWithin {p : α → Prop} {s : Set α} {x : α} (h : ∀ᶠ y in 𝓝[s] x, p y) (hx : x ∈ s) : p x := mem_of_mem_nhdsWithin hx h theorem tendsto_const_nhdsWithin {l : Filter β} {s : Set α} {a : α} (ha : a ∈ s) : Tendsto (fun _ : β => a) l (𝓝[s] a) := tendsto_const_pure.mono_right <| pure_le_nhdsWithin ha theorem nhdsWithin_restrict'' {a : α} (s : Set α) {t : Set α} (h : t ∈ 𝓝[s] a) : 𝓝[s] a = 𝓝[s ∩ t] a := le_antisymm (le_inf inf_le_left (le_principal_iff.mpr (inter_mem self_mem_nhdsWithin h))) (inf_le_inf_left _ (principal_mono.mpr Set.inter_subset_left)) theorem nhdsWithin_restrict' {a : α} (s : Set α) {t : Set α} (h : t ∈ 𝓝 a) : 𝓝[s] a = 𝓝[s ∩ t] a := nhdsWithin_restrict'' s <| mem_inf_of_left h theorem nhdsWithin_restrict {a : α} (s : Set α) {t : Set α} (h₀ : a ∈ t) (h₁ : IsOpen t) : 𝓝[s] a = 𝓝[s ∩ t] a := nhdsWithin_restrict' s (IsOpen.mem_nhds h₁ h₀) theorem nhdsWithin_le_of_mem {a : α} {s t : Set α} (h : s ∈ 𝓝[t] a) : 𝓝[t] a ≤ 𝓝[s] a := nhdsWithin_le_iff.mpr h theorem nhdsWithin_le_nhds {a : α} {s : Set α} : 𝓝[s] a ≤ 𝓝 a := by rw [← nhdsWithin_univ] apply nhdsWithin_le_of_mem exact univ_mem theorem nhdsWithin_eq_nhdsWithin' {a : α} {s t u : Set α} (hs : s ∈ 𝓝 a) (h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a := by rw [nhdsWithin_restrict' t hs, nhdsWithin_restrict' u hs, h₂] theorem nhdsWithin_eq_nhdsWithin {a : α} {s t u : Set α} (h₀ : a ∈ s) (h₁ : IsOpen s) (h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a := by rw [nhdsWithin_restrict t h₀ h₁, nhdsWithin_restrict u h₀ h₁, h₂] @[simp] theorem nhdsWithin_eq_nhds {a : α} {s : Set α} : 𝓝[s] a = 𝓝 a ↔ s ∈ 𝓝 a := inf_eq_left.trans le_principal_iff theorem IsOpen.nhdsWithin_eq {a : α} {s : Set α} (h : IsOpen s) (ha : a ∈ s) : 𝓝[s] a = 𝓝 a := nhdsWithin_eq_nhds.2 <| h.mem_nhds ha theorem preimage_nhds_within_coinduced {π : α → β} {s : Set β} {t : Set α} {a : α} (h : a ∈ t) (ht : IsOpen t) (hs : s ∈ @nhds β (.coinduced (fun x : t => π x) inferInstance) (π a)) : π ⁻¹' s ∈ 𝓝 a := by rw [← ht.nhdsWithin_eq h] exact preimage_nhdsWithin_coinduced' h hs @[simp] theorem nhdsWithin_empty (a : α) : 𝓝[∅] a = ⊥ := by rw [nhdsWithin, principal_empty, inf_bot_eq] theorem nhdsWithin_union (a : α) (s t : Set α) : 𝓝[s ∪ t] a = 𝓝[s] a ⊔ 𝓝[t] a := by delta nhdsWithin rw [← inf_sup_left, sup_principal] theorem nhdsWithin_biUnion {ι} {I : Set ι} (hI : I.Finite) (s : ι → Set α) (a : α) : 𝓝[⋃ i ∈ I, s i] a = ⨆ i ∈ I, 𝓝[s i] a := Set.Finite.induction_on hI (by simp) fun _ _ hT ↦ by simp only [hT, nhdsWithin_union, iSup_insert, biUnion_insert] theorem nhdsWithin_sUnion {S : Set (Set α)} (hS : S.Finite) (a : α) : 𝓝[⋃₀ S] a = ⨆ s ∈ S, 𝓝[s] a := by rw [sUnion_eq_biUnion, nhdsWithin_biUnion hS] theorem nhdsWithin_iUnion {ι} [Finite ι] (s : ι → Set α) (a : α) : 𝓝[⋃ i, s i] a = ⨆ i, 𝓝[s i] a := by rw [← sUnion_range, nhdsWithin_sUnion (finite_range s), iSup_range] theorem nhdsWithin_inter (a : α) (s t : Set α) : 𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓝[t] a := by delta nhdsWithin rw [inf_left_comm, inf_assoc, inf_principal, ← inf_assoc, inf_idem] theorem nhdsWithin_inter' (a : α) (s t : Set α) : 𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓟 t := by delta nhdsWithin rw [← inf_principal, inf_assoc] theorem nhdsWithin_inter_of_mem {a : α} {s t : Set α} (h : s ∈ 𝓝[t] a) : 𝓝[s ∩ t] a = 𝓝[t] a := by rw [nhdsWithin_inter, inf_eq_right] exact nhdsWithin_le_of_mem h theorem nhdsWithin_inter_of_mem' {a : α} {s t : Set α} (h : t ∈ 𝓝[s] a) : 𝓝[s ∩ t] a = 𝓝[s] a := by rw [inter_comm, nhdsWithin_inter_of_mem h] @[simp] theorem nhdsWithin_singleton (a : α) : 𝓝[{a}] a = pure a := by rw [nhdsWithin, principal_singleton, inf_eq_right.2 (pure_le_nhds a)] @[simp] theorem nhdsWithin_insert (a : α) (s : Set α) : 𝓝[insert a s] a = pure a ⊔ 𝓝[s] a := by rw [← singleton_union, nhdsWithin_union, nhdsWithin_singleton] theorem mem_nhdsWithin_insert {a : α} {s t : Set α} : t ∈ 𝓝[insert a s] a ↔ a ∈ t ∧ t ∈ 𝓝[s] a := by simp theorem insert_mem_nhdsWithin_insert {a : α} {s t : Set α} (h : t ∈ 𝓝[s] a) : insert a t ∈ 𝓝[insert a s] a := by simp [mem_of_superset h] theorem insert_mem_nhds_iff {a : α} {s : Set α} : insert a s ∈ 𝓝 a ↔ s ∈ 𝓝[≠] a := by simp only [nhdsWithin, mem_inf_principal, mem_compl_iff, mem_singleton_iff, or_iff_not_imp_left, insert_def] @[simp] theorem nhdsWithin_compl_singleton_sup_pure (a : α) : 𝓝[≠] a ⊔ pure a = 𝓝 a := by rw [← nhdsWithin_singleton, ← nhdsWithin_union, compl_union_self, nhdsWithin_univ] theorem nhdsWithin_prod {α : Type*} [TopologicalSpace α] {β : Type*} [TopologicalSpace β] {s u : Set α} {t v : Set β} {a : α} {b : β} (hu : u ∈ 𝓝[s] a) (hv : v ∈ 𝓝[t] b) : u ×ˢ v ∈ 𝓝[s ×ˢ t] (a, b) := by rw [nhdsWithin_prod_eq] exact prod_mem_prod hu hv section Pi variable {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] theorem nhdsWithin_pi_eq' {I : Set ι} (hI : I.Finite) (s : ∀ i, Set (π i)) (x : ∀ i, π i) : 𝓝[pi I s] x = ⨅ i, comap (fun x => x i) (𝓝 (x i) ⊓ ⨅ (_ : i ∈ I), 𝓟 (s i)) := by simp only [nhdsWithin, nhds_pi, Filter.pi, comap_inf, comap_iInf, pi_def, comap_principal, ← iInf_principal_finite hI, ← iInf_inf_eq] theorem nhdsWithin_pi_eq {I : Set ι} (hI : I.Finite) (s : ∀ i, Set (π i)) (x : ∀ i, π i) : 𝓝[pi I s] x = (⨅ i ∈ I, comap (fun x => x i) (𝓝[s i] x i)) ⊓ ⨅ (i) (_ : i ∉ I), comap (fun x => x i) (𝓝 (x i)) := by simp only [nhdsWithin, nhds_pi, Filter.pi, pi_def, ← iInf_principal_finite hI, comap_inf, comap_principal, eval] rw [iInf_split _ fun i => i ∈ I, inf_right_comm] simp only [iInf_inf_eq] theorem nhdsWithin_pi_univ_eq [Finite ι] (s : ∀ i, Set (π i)) (x : ∀ i, π i) : 𝓝[pi univ s] x = ⨅ i, comap (fun x => x i) (𝓝[s i] x i) := by simpa [nhdsWithin] using nhdsWithin_pi_eq finite_univ s x theorem nhdsWithin_pi_eq_bot {I : Set ι} {s : ∀ i, Set (π i)} {x : ∀ i, π i} : 𝓝[pi I s] x = ⊥ ↔ ∃ i ∈ I, 𝓝[s i] x i = ⊥ := by simp only [nhdsWithin, nhds_pi, pi_inf_principal_pi_eq_bot] theorem nhdsWithin_pi_neBot {I : Set ι} {s : ∀ i, Set (π i)} {x : ∀ i, π i} : (𝓝[pi I s] x).NeBot ↔ ∀ i ∈ I, (𝓝[s i] x i).NeBot := by simp [neBot_iff, nhdsWithin_pi_eq_bot] instance instNeBotNhdsWithinUnivPi {s : ∀ i, Set (π i)} {x : ∀ i, π i} [∀ i, (𝓝[s i] x i).NeBot] : (𝓝[pi univ s] x).NeBot := by simpa [nhdsWithin_pi_neBot] instance Pi.instNeBotNhdsWithinIio [Nonempty ι] [∀ i, Preorder (π i)] {x : ∀ i, π i} [∀ i, (𝓝[<] x i).NeBot] : (𝓝[<] x).NeBot := have : (𝓝[pi univ fun i ↦ Iio (x i)] x).NeBot := inferInstance this.mono <| nhdsWithin_mono _ fun _y hy ↦ lt_of_strongLT fun i ↦ hy i trivial instance Pi.instNeBotNhdsWithinIoi [Nonempty ι] [∀ i, Preorder (π i)] {x : ∀ i, π i} [∀ i, (𝓝[>] x i).NeBot] : (𝓝[>] x).NeBot := Pi.instNeBotNhdsWithinIio (π := fun i ↦ (π i)ᵒᵈ) (x := fun i ↦ OrderDual.toDual (x i)) theorem Filter.Tendsto.piecewise_nhdsWithin {f g : α → β} {t : Set α} [∀ x, Decidable (x ∈ t)] {a : α} {s : Set α} {l : Filter β} (h₀ : Tendsto f (𝓝[s ∩ t] a) l) (h₁ : Tendsto g (𝓝[s ∩ tᶜ] a) l) : Tendsto (piecewise t f g) (𝓝[s] a) l := by apply Tendsto.piecewise <;> rwa [← nhdsWithin_inter'] theorem Filter.Tendsto.if_nhdsWithin {f g : α → β} {p : α → Prop} [DecidablePred p] {a : α} {s : Set α} {l : Filter β} (h₀ : Tendsto f (𝓝[s ∩ { x | p x }] a) l) (h₁ : Tendsto g (𝓝[s ∩ { x | ¬p x }] a) l) : Tendsto (fun x => if p x then f x else g x) (𝓝[s] a) l := h₀.piecewise_nhdsWithin h₁ theorem map_nhdsWithin (f : α → β) (a : α) (s : Set α) : map f (𝓝[s] a) = ⨅ t ∈ { t : Set α | a ∈ t ∧ IsOpen t }, 𝓟 (f '' (t ∩ s)) := ((nhdsWithin_basis_open a s).map f).eq_biInf theorem tendsto_nhdsWithin_mono_left {f : α → β} {a : α} {s t : Set α} {l : Filter β} (hst : s ⊆ t) (h : Tendsto f (𝓝[t] a) l) : Tendsto f (𝓝[s] a) l := h.mono_left <| nhdsWithin_mono a hst theorem tendsto_nhdsWithin_mono_right {f : β → α} {l : Filter β} {a : α} {s t : Set α} (hst : s ⊆ t) (h : Tendsto f l (𝓝[s] a)) : Tendsto f l (𝓝[t] a) := h.mono_right (nhdsWithin_mono a hst) theorem tendsto_nhdsWithin_of_tendsto_nhds {f : α → β} {a : α} {s : Set α} {l : Filter β} (h : Tendsto f (𝓝 a) l) : Tendsto f (𝓝[s] a) l := h.mono_left inf_le_left theorem eventually_mem_of_tendsto_nhdsWithin {f : β → α} {a : α} {s : Set α} {l : Filter β} (h : Tendsto f l (𝓝[s] a)) : ∀ᶠ i in l, f i ∈ s := by simp_rw [nhdsWithin_eq, tendsto_iInf, mem_setOf_eq, tendsto_principal, mem_inter_iff, eventually_and] at h exact (h univ ⟨mem_univ a, isOpen_univ⟩).2 theorem tendsto_nhds_of_tendsto_nhdsWithin {f : β → α} {a : α} {s : Set α} {l : Filter β} (h : Tendsto f l (𝓝[s] a)) : Tendsto f l (𝓝 a) := h.mono_right nhdsWithin_le_nhds theorem nhdsWithin_neBot_of_mem {s : Set α} {x : α} (hx : x ∈ s) : NeBot (𝓝[s] x) := mem_closure_iff_nhdsWithin_neBot.1 <| subset_closure hx theorem IsClosed.mem_of_nhdsWithin_neBot {s : Set α} (hs : IsClosed s) {x : α} (hx : NeBot <| 𝓝[s] x) : x ∈ s := hs.closure_eq ▸ mem_closure_iff_nhdsWithin_neBot.2 hx theorem DenseRange.nhdsWithin_neBot {ι : Type*} {f : ι → α} (h : DenseRange f) (x : α) : NeBot (𝓝[range f] x) := mem_closure_iff_clusterPt.1 (h x) theorem mem_closure_pi {ι : Type*} {α : ι → Type*} [∀ i, TopologicalSpace (α i)] {I : Set ι} {s : ∀ i, Set (α i)} {x : ∀ i, α i} : x ∈ closure (pi I s) ↔ ∀ i ∈ I, x i ∈ closure (s i) := by simp only [mem_closure_iff_nhdsWithin_neBot, nhdsWithin_pi_neBot] theorem closure_pi_set {ι : Type*} {α : ι → Type*} [∀ i, TopologicalSpace (α i)] (I : Set ι) (s : ∀ i, Set (α i)) : closure (pi I s) = pi I fun i => closure (s i) := Set.ext fun _ => mem_closure_pi theorem dense_pi {ι : Type*} {α : ι → Type*} [∀ i, TopologicalSpace (α i)] {s : ∀ i, Set (α i)} (I : Set ι) (hs : ∀ i ∈ I, Dense (s i)) : Dense (pi I s) := by simp only [dense_iff_closure_eq, closure_pi_set, pi_congr rfl fun i hi => (hs i hi).closure_eq, pi_univ] theorem eventuallyEq_nhdsWithin_iff {f g : α → β} {s : Set α} {a : α} : f =ᶠ[𝓝[s] a] g ↔ ∀ᶠ x in 𝓝 a, x ∈ s → f x = g x := mem_inf_principal theorem eventuallyEq_nhdsWithin_of_eqOn {f g : α → β} {s : Set α} {a : α} (h : EqOn f g s) : f =ᶠ[𝓝[s] a] g := mem_inf_of_right h theorem Set.EqOn.eventuallyEq_nhdsWithin {f g : α → β} {s : Set α} {a : α} (h : EqOn f g s) : f =ᶠ[𝓝[s] a] g := eventuallyEq_nhdsWithin_of_eqOn h theorem tendsto_nhdsWithin_congr {f g : α → β} {s : Set α} {a : α} {l : Filter β} (hfg : ∀ x ∈ s, f x = g x) (hf : Tendsto f (𝓝[s] a) l) : Tendsto g (𝓝[s] a) l := (tendsto_congr' <| eventuallyEq_nhdsWithin_of_eqOn hfg).1 hf theorem eventually_nhdsWithin_of_forall {s : Set α} {a : α} {p : α → Prop} (h : ∀ x ∈ s, p x) : ∀ᶠ x in 𝓝[s] a, p x := mem_inf_of_right h theorem tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within {a : α} {l : Filter β} {s : Set α} (f : β → α) (h1 : Tendsto f l (𝓝 a)) (h2 : ∀ᶠ x in l, f x ∈ s) : Tendsto f l (𝓝[s] a) := tendsto_inf.2 ⟨h1, tendsto_principal.2 h2⟩ theorem tendsto_nhdsWithin_iff {a : α} {l : Filter β} {s : Set α} {f : β → α} : Tendsto f l (𝓝[s] a) ↔ Tendsto f l (𝓝 a) ∧ ∀ᶠ n in l, f n ∈ s := ⟨fun h => ⟨tendsto_nhds_of_tendsto_nhdsWithin h, eventually_mem_of_tendsto_nhdsWithin h⟩, fun h => tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within _ h.1 h.2⟩ @[simp] theorem tendsto_nhdsWithin_range {a : α} {l : Filter β} {f : β → α} : Tendsto f l (𝓝[range f] a) ↔ Tendsto f l (𝓝 a) := ⟨fun h => h.mono_right inf_le_left, fun h => tendsto_inf.2 ⟨h, tendsto_principal.2 <| eventually_of_forall mem_range_self⟩⟩ theorem Filter.EventuallyEq.eq_of_nhdsWithin {s : Set α} {f g : α → β} {a : α} (h : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : f a = g a := h.self_of_nhdsWithin hmem theorem eventually_nhdsWithin_of_eventually_nhds {α : Type*} [TopologicalSpace α] {s : Set α} {a : α} {p : α → Prop} (h : ∀ᶠ x in 𝓝 a, p x) : ∀ᶠ x in 𝓝[s] a, p x := mem_nhdsWithin_of_mem_nhds h /-! ### `nhdsWithin` and subtypes -/ theorem mem_nhdsWithin_subtype {s : Set α} {a : { x // x ∈ s }} {t u : Set { x // x ∈ s }} : t ∈ 𝓝[u] a ↔ t ∈ comap ((↑) : s → α) (𝓝[(↑) '' u] a) := by rw [nhdsWithin, nhds_subtype, principal_subtype, ← comap_inf, ← nhdsWithin] theorem nhdsWithin_subtype (s : Set α) (a : { x // x ∈ s }) (t : Set { x // x ∈ s }) : 𝓝[t] a = comap ((↑) : s → α) (𝓝[(↑) '' t] a) := Filter.ext fun _ => mem_nhdsWithin_subtype theorem nhdsWithin_eq_map_subtype_coe {s : Set α} {a : α} (h : a ∈ s) : 𝓝[s] a = map ((↑) : s → α) (𝓝 ⟨a, h⟩) := (map_nhds_subtype_val ⟨a, h⟩).symm theorem mem_nhds_subtype_iff_nhdsWithin {s : Set α} {a : s} {t : Set s} : t ∈ 𝓝 a ↔ (↑) '' t ∈ 𝓝[s] (a : α) := by rw [← map_nhds_subtype_val, image_mem_map_iff Subtype.val_injective] theorem preimage_coe_mem_nhds_subtype {s t : Set α} {a : s} : (↑) ⁻¹' t ∈ 𝓝 a ↔ t ∈ 𝓝[s] ↑a := by rw [← map_nhds_subtype_val, mem_map] theorem eventually_nhds_subtype_iff (s : Set α) (a : s) (P : α → Prop) : (∀ᶠ x : s in 𝓝 a, P x) ↔ ∀ᶠ x in 𝓝[s] a, P x := preimage_coe_mem_nhds_subtype theorem frequently_nhds_subtype_iff (s : Set α) (a : s) (P : α → Prop) : (∃ᶠ x : s in 𝓝 a, P x) ↔ ∃ᶠ x in 𝓝[s] a, P x := eventually_nhds_subtype_iff s a (¬ P ·) |>.not theorem tendsto_nhdsWithin_iff_subtype {s : Set α} {a : α} (h : a ∈ s) (f : α → β) (l : Filter β) : Tendsto f (𝓝[s] a) l ↔ Tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l := by rw [nhdsWithin_eq_map_subtype_coe h, tendsto_map'_iff]; rfl variable [TopologicalSpace β] [TopologicalSpace γ] [TopologicalSpace δ] /-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition. We register this fact for use with the dot notation, especially to use `Filter.Tendsto.comp` as `ContinuousWithinAt.comp` will have a different meaning. -/ theorem ContinuousWithinAt.tendsto {f : α → β} {s : Set α} {x : α} (h : ContinuousWithinAt f s x) : Tendsto f (𝓝[s] x) (𝓝 (f x)) := h theorem ContinuousOn.continuousWithinAt {f : α → β} {s : Set α} {x : α} (hf : ContinuousOn f s) (hx : x ∈ s) : ContinuousWithinAt f s x := hf x hx theorem continuousWithinAt_univ (f : α → β) (x : α) : ContinuousWithinAt f Set.univ x ↔ ContinuousAt f x := by rw [ContinuousAt, ContinuousWithinAt, nhdsWithin_univ] theorem continuous_iff_continuousOn_univ {f : α → β} : Continuous f ↔ ContinuousOn f univ := by simp [continuous_iff_continuousAt, ContinuousOn, ContinuousAt, ContinuousWithinAt, nhdsWithin_univ] theorem continuousWithinAt_iff_continuousAt_restrict (f : α → β) {x : α} {s : Set α} (h : x ∈ s) : ContinuousWithinAt f s x ↔ ContinuousAt (s.restrict f) ⟨x, h⟩ := tendsto_nhdsWithin_iff_subtype h f _ theorem ContinuousWithinAt.tendsto_nhdsWithin {f : α → β} {x : α} {s : Set α} {t : Set β} (h : ContinuousWithinAt f s x) (ht : MapsTo f s t) : Tendsto f (𝓝[s] x) (𝓝[t] f x) := tendsto_inf.2 ⟨h, tendsto_principal.2 <| mem_inf_of_right <| mem_principal.2 <| ht⟩ theorem ContinuousWithinAt.tendsto_nhdsWithin_image {f : α → β} {x : α} {s : Set α} (h : ContinuousWithinAt f s x) : Tendsto f (𝓝[s] x) (𝓝[f '' s] f x) := h.tendsto_nhdsWithin (mapsTo_image _ _) theorem ContinuousWithinAt.prod_map {f : α → γ} {g : β → δ} {s : Set α} {t : Set β} {x : α} {y : β} (hf : ContinuousWithinAt f s x) (hg : ContinuousWithinAt g t y) : ContinuousWithinAt (Prod.map f g) (s ×ˢ t) (x, y) := by unfold ContinuousWithinAt at * rw [nhdsWithin_prod_eq, Prod.map, nhds_prod_eq] exact hf.prod_map hg theorem continuousWithinAt_prod_of_discrete_left [DiscreteTopology α] {f : α × β → γ} {s : Set (α × β)} {x : α × β} : ContinuousWithinAt f s x ↔ ContinuousWithinAt (f ⟨x.1, ·⟩) {b | (x.1, b) ∈ s} x.2 := by rw [← x.eta]; simp_rw [ContinuousWithinAt, nhdsWithin, nhds_prod_eq, nhds_discrete, pure_prod, ← map_inf_principal_preimage]; rfl theorem continuousWithinAt_prod_of_discrete_right [DiscreteTopology β] {f : α × β → γ} {s : Set (α × β)} {x : α × β} : ContinuousWithinAt f s x ↔ ContinuousWithinAt (f ⟨·, x.2⟩) {a | (a, x.2) ∈ s} x.1 := by rw [← x.eta]; simp_rw [ContinuousWithinAt, nhdsWithin, nhds_prod_eq, nhds_discrete, prod_pure, ← map_inf_principal_preimage]; rfl theorem continuousAt_prod_of_discrete_left [DiscreteTopology α] {f : α × β → γ} {x : α × β} : ContinuousAt f x ↔ ContinuousAt (f ⟨x.1, ·⟩) x.2 := by simp_rw [← continuousWithinAt_univ]; exact continuousWithinAt_prod_of_discrete_left theorem continuousAt_prod_of_discrete_right [DiscreteTopology β] {f : α × β → γ} {x : α × β} : ContinuousAt f x ↔ ContinuousAt (f ⟨·, x.2⟩) x.1 := by simp_rw [← continuousWithinAt_univ]; exact continuousWithinAt_prod_of_discrete_right theorem continuousOn_prod_of_discrete_left [DiscreteTopology α] {f : α × β → γ} {s : Set (α × β)} : ContinuousOn f s ↔ ∀ a, ContinuousOn (f ⟨a, ·⟩) {b | (a, b) ∈ s} := by simp_rw [ContinuousOn, Prod.forall, continuousWithinAt_prod_of_discrete_left]; rfl theorem continuousOn_prod_of_discrete_right [DiscreteTopology β] {f : α × β → γ} {s : Set (α × β)} : ContinuousOn f s ↔ ∀ b, ContinuousOn (f ⟨·, b⟩) {a | (a, b) ∈ s} := by simp_rw [ContinuousOn, Prod.forall, continuousWithinAt_prod_of_discrete_right]; apply forall_swap /-- If a function `f a b` is such that `y ↦ f a b` is continuous for all `a`, and `a` lives in a discrete space, then `f` is continuous, and vice versa. -/ theorem continuous_prod_of_discrete_left [DiscreteTopology α] {f : α × β → γ} : Continuous f ↔ ∀ a, Continuous (f ⟨a, ·⟩) := by simp_rw [continuous_iff_continuousOn_univ]; exact continuousOn_prod_of_discrete_left theorem continuous_prod_of_discrete_right [DiscreteTopology β] {f : α × β → γ} : Continuous f ↔ ∀ b, Continuous (f ⟨·, b⟩) := by simp_rw [continuous_iff_continuousOn_univ]; exact continuousOn_prod_of_discrete_right theorem isOpenMap_prod_of_discrete_left [DiscreteTopology α] {f : α × β → γ} : IsOpenMap f ↔ ∀ a, IsOpenMap (f ⟨a, ·⟩) := by simp_rw [isOpenMap_iff_nhds_le, Prod.forall, nhds_prod_eq, nhds_discrete, pure_prod, map_map] rfl theorem isOpenMap_prod_of_discrete_right [DiscreteTopology β] {f : α × β → γ} : IsOpenMap f ↔ ∀ b, IsOpenMap (f ⟨·, b⟩) := by simp_rw [isOpenMap_iff_nhds_le, Prod.forall, forall_swap (α := α) (β := β), nhds_prod_eq, nhds_discrete, prod_pure, map_map]; rfl theorem continuousWithinAt_pi {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] {f : α → ∀ i, π i} {s : Set α} {x : α} : ContinuousWithinAt f s x ↔ ∀ i, ContinuousWithinAt (fun y => f y i) s x := tendsto_pi_nhds theorem continuousOn_pi {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] {f : α → ∀ i, π i} {s : Set α} : ContinuousOn f s ↔ ∀ i, ContinuousOn (fun y => f y i) s := ⟨fun h i x hx => tendsto_pi_nhds.1 (h x hx) i, fun h x hx => tendsto_pi_nhds.2 fun i => h i x hx⟩ @[fun_prop] theorem continuousOn_pi' {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] {f : α → ∀ i, π i} {s : Set α} (hf : ∀ i, ContinuousOn (fun y => f y i) s) : ContinuousOn f s := continuousOn_pi.2 hf theorem ContinuousWithinAt.fin_insertNth {n} {π : Fin (n + 1) → Type*} [∀ i, TopologicalSpace (π i)] (i : Fin (n + 1)) {f : α → π i} {a : α} {s : Set α} (hf : ContinuousWithinAt f s a) {g : α → ∀ j : Fin n, π (i.succAbove j)} (hg : ContinuousWithinAt g s a) : ContinuousWithinAt (fun a => i.insertNth (f a) (g a)) s a := hf.tendsto.fin_insertNth i hg nonrec theorem ContinuousOn.fin_insertNth {n} {π : Fin (n + 1) → Type*} [∀ i, TopologicalSpace (π i)] (i : Fin (n + 1)) {f : α → π i} {s : Set α} (hf : ContinuousOn f s) {g : α → ∀ j : Fin n, π (i.succAbove j)} (hg : ContinuousOn g s) : ContinuousOn (fun a => i.insertNth (f a) (g a)) s := fun a ha => (hf a ha).fin_insertNth i (hg a ha) theorem continuousOn_iff {f : α → β} {s : Set α} : ContinuousOn f s ↔ ∀ x ∈ s, ∀ t : Set β, IsOpen t → f x ∈ t → ∃ u, IsOpen u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' t := by simp only [ContinuousOn, ContinuousWithinAt, tendsto_nhds, mem_nhdsWithin] theorem continuousOn_iff_continuous_restrict {f : α → β} {s : Set α} : ContinuousOn f s ↔ Continuous (s.restrict f) := by rw [ContinuousOn, continuous_iff_continuousAt]; constructor · rintro h ⟨x, xs⟩ exact (continuousWithinAt_iff_continuousAt_restrict f xs).mp (h x xs) intro h x xs exact (continuousWithinAt_iff_continuousAt_restrict f xs).mpr (h ⟨x, xs⟩) -- Porting note: 2 new lemmas alias ⟨ContinuousOn.restrict, _⟩ := continuousOn_iff_continuous_restrict theorem ContinuousOn.restrict_mapsTo {f : α → β} {s : Set α} {t : Set β} (hf : ContinuousOn f s) (ht : MapsTo f s t) : Continuous (ht.restrict f s t) := hf.restrict.codRestrict _ theorem continuousOn_iff' {f : α → β} {s : Set α} : ContinuousOn f s ↔ ∀ t : Set β, IsOpen t → ∃ u, IsOpen u ∧ f ⁻¹' t ∩ s = u ∩ s := by have : ∀ t, IsOpen (s.restrict f ⁻¹' t) ↔ ∃ u : Set α, IsOpen u ∧ f ⁻¹' t ∩ s = u ∩ s := by intro t rw [isOpen_induced_iff, Set.restrict_eq, Set.preimage_comp] simp only [Subtype.preimage_coe_eq_preimage_coe_iff] constructor <;> · rintro ⟨u, ou, useq⟩ exact ⟨u, ou, by simpa only [Set.inter_comm, eq_comm] using useq⟩ rw [continuousOn_iff_continuous_restrict, continuous_def]; simp only [this] /-- If a function is continuous on a set for some topologies, then it is continuous on the same set with respect to any finer topology on the source space. -/ theorem ContinuousOn.mono_dom {α β : Type*} {t₁ t₂ : TopologicalSpace α} {t₃ : TopologicalSpace β} (h₁ : t₂ ≤ t₁) {s : Set α} {f : α → β} (h₂ : @ContinuousOn α β t₁ t₃ f s) : @ContinuousOn α β t₂ t₃ f s := fun x hx _u hu => map_mono (inf_le_inf_right _ <| nhds_mono h₁) (h₂ x hx hu) /-- If a function is continuous on a set for some topologies, then it is continuous on the same set with respect to any coarser topology on the target space. -/ theorem ContinuousOn.mono_rng {α β : Type*} {t₁ : TopologicalSpace α} {t₂ t₃ : TopologicalSpace β} (h₁ : t₂ ≤ t₃) {s : Set α} {f : α → β} (h₂ : @ContinuousOn α β t₁ t₂ f s) : @ContinuousOn α β t₁ t₃ f s := fun x hx _u hu => h₂ x hx <| nhds_mono h₁ hu theorem continuousOn_iff_isClosed {f : α → β} {s : Set α} : ContinuousOn f s ↔ ∀ t : Set β, IsClosed t → ∃ u, IsClosed u ∧ f ⁻¹' t ∩ s = u ∩ s := by have : ∀ t, IsClosed (s.restrict f ⁻¹' t) ↔ ∃ u : Set α, IsClosed u ∧ f ⁻¹' t ∩ s = u ∩ s := by intro t rw [isClosed_induced_iff, Set.restrict_eq, Set.preimage_comp] simp only [Subtype.preimage_coe_eq_preimage_coe_iff, eq_comm, Set.inter_comm s] rw [continuousOn_iff_continuous_restrict, continuous_iff_isClosed]; simp only [this] theorem ContinuousOn.prod_map {f : α → γ} {g : β → δ} {s : Set α} {t : Set β} (hf : ContinuousOn f s) (hg : ContinuousOn g t) : ContinuousOn (Prod.map f g) (s ×ˢ t) := fun ⟨x, y⟩ ⟨hx, hy⟩ => ContinuousWithinAt.prod_map (hf x hx) (hg y hy) theorem continuous_of_cover_nhds {ι : Sort*} {f : α → β} {s : ι → Set α} (hs : ∀ x : α, ∃ i, s i ∈ 𝓝 x) (hf : ∀ i, ContinuousOn f (s i)) : Continuous f := continuous_iff_continuousAt.mpr fun x ↦ let ⟨i, hi⟩ := hs x; by rw [ContinuousAt, ← nhdsWithin_eq_nhds.2 hi] exact hf _ _ (mem_of_mem_nhds hi) theorem continuousOn_empty (f : α → β) : ContinuousOn f ∅ := fun _ => False.elim @[simp] theorem continuousOn_singleton (f : α → β) (a : α) : ContinuousOn f {a} := forall_eq.2 <| by simpa only [ContinuousWithinAt, nhdsWithin_singleton, tendsto_pure_left] using fun s => mem_of_mem_nhds theorem Set.Subsingleton.continuousOn {s : Set α} (hs : s.Subsingleton) (f : α → β) : ContinuousOn f s := hs.induction_on (continuousOn_empty f) (continuousOn_singleton f) theorem nhdsWithin_le_comap {x : α} {s : Set α} {f : α → β} (ctsf : ContinuousWithinAt f s x) : 𝓝[s] x ≤ comap f (𝓝[f '' s] f x) := ctsf.tendsto_nhdsWithin_image.le_comap theorem ContinuousWithinAt.mono {f : α → β} {s t : Set α} {x : α} (h : ContinuousWithinAt f t x) (hs : s ⊆ t) : ContinuousWithinAt f s x := h.mono_left (nhdsWithin_mono x hs) theorem ContinuousWithinAt.mono_of_mem {f : α → β} {s t : Set α} {x : α} (h : ContinuousWithinAt f t x) (hs : t ∈ 𝓝[s] x) : ContinuousWithinAt f s x := h.mono_left (nhdsWithin_le_of_mem hs) theorem continuousWithinAt_congr_nhds {f : α → β} {s t : Set α} {x : α} (h : 𝓝[s] x = 𝓝[t] x) : ContinuousWithinAt f s x ↔ ContinuousWithinAt f t x := by simp only [ContinuousWithinAt, h] theorem continuousWithinAt_inter' {f : α → β} {s t : Set α} {x : α} (h : t ∈ 𝓝[s] x) : ContinuousWithinAt f (s ∩ t) x ↔ ContinuousWithinAt f s x := by simp [ContinuousWithinAt, nhdsWithin_restrict'' s h] theorem continuousWithinAt_inter {f : α → β} {s t : Set α} {x : α} (h : t ∈ 𝓝 x) : ContinuousWithinAt f (s ∩ t) x ↔ ContinuousWithinAt f s x := by simp [ContinuousWithinAt, nhdsWithin_restrict' s h] theorem continuousWithinAt_union {f : α → β} {s t : Set α} {x : α} : ContinuousWithinAt f (s ∪ t) x ↔ ContinuousWithinAt f s x ∧ ContinuousWithinAt f t x := by simp only [ContinuousWithinAt, nhdsWithin_union, tendsto_sup] theorem ContinuousWithinAt.union {f : α → β} {s t : Set α} {x : α} (hs : ContinuousWithinAt f s x) (ht : ContinuousWithinAt f t x) : ContinuousWithinAt f (s ∪ t) x := continuousWithinAt_union.2 ⟨hs, ht⟩ theorem ContinuousWithinAt.mem_closure_image {f : α → β} {s : Set α} {x : α} (h : ContinuousWithinAt f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := haveI := mem_closure_iff_nhdsWithin_neBot.1 hx mem_closure_of_tendsto h <| mem_of_superset self_mem_nhdsWithin (subset_preimage_image f s) theorem ContinuousWithinAt.mem_closure {f : α → β} {s : Set α} {x : α} {A : Set β} (h : ContinuousWithinAt f s x) (hx : x ∈ closure s) (hA : MapsTo f s A) : f x ∈ closure A := closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx) theorem Set.MapsTo.closure_of_continuousWithinAt {f : α → β} {s : Set α} {t : Set β} (h : MapsTo f s t) (hc : ∀ x ∈ closure s, ContinuousWithinAt f s x) : MapsTo f (closure s) (closure t) := fun x hx => (hc x hx).mem_closure hx h theorem Set.MapsTo.closure_of_continuousOn {f : α → β} {s : Set α} {t : Set β} (h : MapsTo f s t) (hc : ContinuousOn f (closure s)) : MapsTo f (closure s) (closure t) := h.closure_of_continuousWithinAt fun x hx => (hc x hx).mono subset_closure theorem ContinuousWithinAt.image_closure {f : α → β} {s : Set α} (hf : ∀ x ∈ closure s, ContinuousWithinAt f s x) : f '' closure s ⊆ closure (f '' s) := ((mapsTo_image f s).closure_of_continuousWithinAt hf).image_subset theorem ContinuousOn.image_closure {f : α → β} {s : Set α} (hf : ContinuousOn f (closure s)) : f '' closure s ⊆ closure (f '' s) := ContinuousWithinAt.image_closure fun x hx => (hf x hx).mono subset_closure @[simp] theorem continuousWithinAt_singleton {f : α → β} {x : α} : ContinuousWithinAt f {x} x := by simp only [ContinuousWithinAt, nhdsWithin_singleton, tendsto_pure_nhds] @[simp] theorem continuousWithinAt_insert_self {f : α → β} {x : α} {s : Set α} : ContinuousWithinAt f (insert x s) x ↔ ContinuousWithinAt f s x := by simp only [← singleton_union, continuousWithinAt_union, continuousWithinAt_singleton, true_and_iff] alias ⟨_, ContinuousWithinAt.insert_self⟩ := continuousWithinAt_insert_self theorem ContinuousWithinAt.diff_iff {f : α → β} {s t : Set α} {x : α} (ht : ContinuousWithinAt f t x) : ContinuousWithinAt f (s \ t) x ↔ ContinuousWithinAt f s x := ⟨fun h => (h.union ht).mono <| by simp only [diff_union_self, subset_union_left], fun h => h.mono diff_subset⟩ @[simp] theorem continuousWithinAt_diff_self {f : α → β} {s : Set α} {x : α} : ContinuousWithinAt f (s \ {x}) x ↔ ContinuousWithinAt f s x := continuousWithinAt_singleton.diff_iff @[simp] theorem continuousWithinAt_compl_self {f : α → β} {a : α} : ContinuousWithinAt f {a}ᶜ a ↔ ContinuousAt f a := by rw [compl_eq_univ_diff, continuousWithinAt_diff_self, continuousWithinAt_univ] @[simp] theorem continuousWithinAt_update_same [DecidableEq α] {f : α → β} {s : Set α} {x : α} {y : β} : ContinuousWithinAt (update f x y) s x ↔ Tendsto f (𝓝[s \ {x}] x) (𝓝 y) := calc ContinuousWithinAt (update f x y) s x ↔ Tendsto (update f x y) (𝓝[s \ {x}] x) (𝓝 y) := by { rw [← continuousWithinAt_diff_self, ContinuousWithinAt, update_same] } _ ↔ Tendsto f (𝓝[s \ {x}] x) (𝓝 y) := tendsto_congr' <| eventually_nhdsWithin_iff.2 <| eventually_of_forall fun z hz => update_noteq hz.2 _ _ @[simp] theorem continuousAt_update_same [DecidableEq α] {f : α → β} {x : α} {y : β} : ContinuousAt (Function.update f x y) x ↔ Tendsto f (𝓝[≠] x) (𝓝 y) := by rw [← continuousWithinAt_univ, continuousWithinAt_update_same, compl_eq_univ_diff] theorem IsOpenMap.continuousOn_image_of_leftInvOn {f : α → β} {s : Set α} (h : IsOpenMap (s.restrict f)) {finv : β → α} (hleft : LeftInvOn finv f s) : ContinuousOn finv (f '' s) := by refine continuousOn_iff'.2 fun t ht => ⟨f '' (t ∩ s), ?_, ?_⟩ · rw [← image_restrict] exact h _ (ht.preimage continuous_subtype_val) · rw [inter_eq_self_of_subset_left (image_subset f inter_subset_right), hleft.image_inter'] theorem IsOpenMap.continuousOn_range_of_leftInverse {f : α → β} (hf : IsOpenMap f) {finv : β → α} (hleft : Function.LeftInverse finv f) : ContinuousOn finv (range f) := by rw [← image_univ] exact (hf.restrict isOpen_univ).continuousOn_image_of_leftInvOn fun x _ => hleft x theorem ContinuousOn.congr_mono {f g : α → β} {s s₁ : Set α} (h : ContinuousOn f s) (h' : EqOn g f s₁) (h₁ : s₁ ⊆ s) : ContinuousOn g s₁ := by intro x hx unfold ContinuousWithinAt have A := (h x (h₁ hx)).mono h₁ unfold ContinuousWithinAt at A rw [← h' hx] at A exact A.congr' h'.eventuallyEq_nhdsWithin.symm theorem ContinuousOn.congr {f g : α → β} {s : Set α} (h : ContinuousOn f s) (h' : EqOn g f s) : ContinuousOn g s := h.congr_mono h' (Subset.refl _) theorem continuousOn_congr {f g : α → β} {s : Set α} (h' : EqOn g f s) : ContinuousOn g s ↔ ContinuousOn f s := ⟨fun h => ContinuousOn.congr h h'.symm, fun h => h.congr h'⟩ theorem ContinuousAt.continuousWithinAt {f : α → β} {s : Set α} {x : α} (h : ContinuousAt f x) : ContinuousWithinAt f s x := ContinuousWithinAt.mono ((continuousWithinAt_univ f x).2 h) (subset_univ _) theorem continuousWithinAt_iff_continuousAt {f : α → β} {s : Set α} {x : α} (h : s ∈ 𝓝 x) : ContinuousWithinAt f s x ↔ ContinuousAt f x := by rw [← univ_inter s, continuousWithinAt_inter h, continuousWithinAt_univ] theorem ContinuousWithinAt.continuousAt {f : α → β} {s : Set α} {x : α} (h : ContinuousWithinAt f s x) (hs : s ∈ 𝓝 x) : ContinuousAt f x := (continuousWithinAt_iff_continuousAt hs).mp h theorem IsOpen.continuousOn_iff {f : α → β} {s : Set α} (hs : IsOpen s) : ContinuousOn f s ↔ ∀ ⦃a⦄, a ∈ s → ContinuousAt f a := forall₂_congr fun _ => continuousWithinAt_iff_continuousAt ∘ hs.mem_nhds theorem ContinuousOn.continuousAt {f : α → β} {s : Set α} {x : α} (h : ContinuousOn f s) (hx : s ∈ 𝓝 x) : ContinuousAt f x := (h x (mem_of_mem_nhds hx)).continuousAt hx theorem ContinuousAt.continuousOn {f : α → β} {s : Set α} (hcont : ∀ x ∈ s, ContinuousAt f x) : ContinuousOn f s := fun x hx => (hcont x hx).continuousWithinAt theorem ContinuousWithinAt.comp {g : β → γ} {f : α → β} {s : Set α} {t : Set β} {x : α} (hg : ContinuousWithinAt g t (f x)) (hf : ContinuousWithinAt f s x) (h : MapsTo f s t) : ContinuousWithinAt (g ∘ f) s x := hg.tendsto.comp (hf.tendsto_nhdsWithin h) theorem ContinuousWithinAt.comp' {g : β → γ} {f : α → β} {s : Set α} {t : Set β} {x : α} (hg : ContinuousWithinAt g t (f x)) (hf : ContinuousWithinAt f s x) : ContinuousWithinAt (g ∘ f) (s ∩ f ⁻¹' t) x := hg.comp (hf.mono inter_subset_left) inter_subset_right theorem ContinuousAt.comp_continuousWithinAt {g : β → γ} {f : α → β} {s : Set α} {x : α} (hg : ContinuousAt g (f x)) (hf : ContinuousWithinAt f s x) : ContinuousWithinAt (g ∘ f) s x := hg.continuousWithinAt.comp hf (mapsTo_univ _ _) theorem ContinuousOn.comp {g : β → γ} {f : α → β} {s : Set α} {t : Set β} (hg : ContinuousOn g t) (hf : ContinuousOn f s) (h : MapsTo f s t) : ContinuousOn (g ∘ f) s := fun x hx => ContinuousWithinAt.comp (hg _ (h hx)) (hf x hx) h @[fun_prop] theorem ContinuousOn.comp'' {g : β → γ} {f : α → β} {s : Set α} {t : Set β} (hg : ContinuousOn g t) (hf : ContinuousOn f s) (h : Set.MapsTo f s t) : ContinuousOn (fun x => g (f x)) s := ContinuousOn.comp hg hf h theorem ContinuousOn.mono {f : α → β} {s t : Set α} (hf : ContinuousOn f s) (h : t ⊆ s) : ContinuousOn f t := fun x hx => (hf x (h hx)).mono_left (nhdsWithin_mono _ h) theorem antitone_continuousOn {f : α → β} : Antitone (ContinuousOn f) := fun _s _t hst hf => hf.mono hst @[fun_prop] theorem ContinuousOn.comp' {g : β → γ} {f : α → β} {s : Set α} {t : Set β} (hg : ContinuousOn g t) (hf : ContinuousOn f s) : ContinuousOn (g ∘ f) (s ∩ f ⁻¹' t) := hg.comp (hf.mono inter_subset_left) inter_subset_right @[fun_prop] theorem Continuous.continuousOn {f : α → β} {s : Set α} (h : Continuous f) : ContinuousOn f s := by rw [continuous_iff_continuousOn_univ] at h exact h.mono (subset_univ _) theorem Continuous.continuousWithinAt {f : α → β} {s : Set α} {x : α} (h : Continuous f) : ContinuousWithinAt f s x := h.continuousAt.continuousWithinAt theorem Continuous.comp_continuousOn {g : β → γ} {f : α → β} {s : Set α} (hg : Continuous g) (hf : ContinuousOn f s) : ContinuousOn (g ∘ f) s := hg.continuousOn.comp hf (mapsTo_univ _ _) @[fun_prop] theorem Continuous.comp_continuousOn' {α β γ : Type*} [TopologicalSpace α] [TopologicalSpace β] [TopologicalSpace γ] {g : β → γ} {f : α → β} {s : Set α} (hg : Continuous g) (hf : ContinuousOn f s) : ContinuousOn (fun x ↦ g (f x)) s := hg.comp_continuousOn hf theorem ContinuousOn.comp_continuous {g : β → γ} {f : α → β} {s : Set β} (hg : ContinuousOn g s) (hf : Continuous f) (hs : ∀ x, f x ∈ s) : Continuous (g ∘ f) := by rw [continuous_iff_continuousOn_univ] at * exact hg.comp hf fun x _ => hs x @[fun_prop] theorem continuousOn_apply {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] (i : ι) (s) : ContinuousOn (fun p : ∀ i, π i => p i) s := Continuous.continuousOn (continuous_apply i) theorem ContinuousWithinAt.preimage_mem_nhdsWithin {f : α → β} {x : α} {s : Set α} {t : Set β} (h : ContinuousWithinAt f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝[s] x := h ht theorem Set.LeftInvOn.map_nhdsWithin_eq {f : α → β} {g : β → α} {x : β} {s : Set β} (h : LeftInvOn f g s) (hx : f (g x) = x) (hf : ContinuousWithinAt f (g '' s) (g x)) (hg : ContinuousWithinAt g s x) : map g (𝓝[s] x) = 𝓝[g '' s] g x := by apply le_antisymm · exact hg.tendsto_nhdsWithin (mapsTo_image _ _) · have A : g ∘ f =ᶠ[𝓝[g '' s] g x] id := h.rightInvOn_image.eqOn.eventuallyEq_of_mem self_mem_nhdsWithin refine le_map_of_right_inverse A ?_ simpa only [hx] using hf.tendsto_nhdsWithin (h.mapsTo (surjOn_image _ _)) theorem Function.LeftInverse.map_nhds_eq {f : α → β} {g : β → α} {x : β} (h : Function.LeftInverse f g) (hf : ContinuousWithinAt f (range g) (g x)) (hg : ContinuousAt g x) : map g (𝓝 x) = 𝓝[range g] g x := by simpa only [nhdsWithin_univ, image_univ] using (h.leftInvOn univ).map_nhdsWithin_eq (h x) (by rwa [image_univ]) hg.continuousWithinAt theorem ContinuousWithinAt.preimage_mem_nhdsWithin' {f : α → β} {x : α} {s : Set α} {t : Set β} (h : ContinuousWithinAt f s x) (ht : t ∈ 𝓝[f '' s] f x) : f ⁻¹' t ∈ 𝓝[s] x := h.tendsto_nhdsWithin (mapsTo_image _ _) ht theorem ContinuousWithinAt.preimage_mem_nhdsWithin'' {f : α → β} {x : α} {y : β} {s t : Set β} (h : ContinuousWithinAt f (f ⁻¹' s) x) (ht : t ∈ 𝓝[s] y) (hxy : y = f x) : f ⁻¹' t ∈ 𝓝[f ⁻¹' s] x := by rw [hxy] at ht exact h.preimage_mem_nhdsWithin' (nhdsWithin_mono _ (image_preimage_subset f s) ht) theorem Filter.EventuallyEq.congr_continuousWithinAt {f g : α → β} {s : Set α} {x : α} (h : f =ᶠ[𝓝[s] x] g) (hx : f x = g x) : ContinuousWithinAt f s x ↔ ContinuousWithinAt g s x := by rw [ContinuousWithinAt, hx, tendsto_congr' h, ContinuousWithinAt] theorem ContinuousWithinAt.congr_of_eventuallyEq {f f₁ : α → β} {s : Set α} {x : α} (h : ContinuousWithinAt f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : ContinuousWithinAt f₁ s x := (h₁.congr_continuousWithinAt hx).2 h theorem ContinuousWithinAt.congr {f f₁ : α → β} {s : Set α} {x : α} (h : ContinuousWithinAt f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : ContinuousWithinAt f₁ s x := h.congr_of_eventuallyEq (mem_of_superset self_mem_nhdsWithin h₁) hx theorem ContinuousWithinAt.congr_mono {f g : α → β} {s s₁ : Set α} {x : α} (h : ContinuousWithinAt f s x) (h' : EqOn g f s₁) (h₁ : s₁ ⊆ s) (hx : g x = f x) : ContinuousWithinAt g s₁ x := (h.mono h₁).congr h' hx @[fun_prop] theorem continuousOn_const {s : Set α} {c : β} : ContinuousOn (fun _ => c) s := continuous_const.continuousOn theorem continuousWithinAt_const {b : β} {s : Set α} {x : α} : ContinuousWithinAt (fun _ : α => b) s x := continuous_const.continuousWithinAt theorem continuousOn_id {s : Set α} : ContinuousOn id s := continuous_id.continuousOn @[fun_prop] theorem continuousOn_id' (s : Set α) : ContinuousOn (fun x : α => x) s := continuousOn_id theorem continuousWithinAt_id {s : Set α} {x : α} : ContinuousWithinAt id s x := continuous_id.continuousWithinAt protected theorem ContinuousOn.iterate {f : α → α} {s : Set α} (hcont : ContinuousOn f s) (hmaps : MapsTo f s s) : ∀ n, ContinuousOn (f^[n]) s | 0 => continuousOn_id | (n + 1) => (hcont.iterate hmaps n).comp hcont hmaps theorem continuousOn_open_iff {f : α → β} {s : Set α} (hs : IsOpen s) : ContinuousOn f s ↔ ∀ t, IsOpen t → IsOpen (s ∩ f ⁻¹' t) := by rw [continuousOn_iff'] constructor · intro h t ht rcases h t ht with ⟨u, u_open, hu⟩ rw [inter_comm, hu] apply IsOpen.inter u_open hs · intro h t ht refine ⟨s ∩ f ⁻¹' t, h t ht, ?_⟩ rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] theorem ContinuousOn.isOpen_inter_preimage {f : α → β} {s : Set α} {t : Set β} (hf : ContinuousOn f s) (hs : IsOpen s) (ht : IsOpen t) : IsOpen (s ∩ f ⁻¹' t) := (continuousOn_open_iff hs).1 hf t ht theorem ContinuousOn.isOpen_preimage {f : α → β} {s : Set α} {t : Set β} (h : ContinuousOn f s) (hs : IsOpen s) (hp : f ⁻¹' t ⊆ s) (ht : IsOpen t) : IsOpen (f ⁻¹' t) := by convert (continuousOn_open_iff hs).mp h t ht rw [inter_comm, inter_eq_self_of_subset_left hp] theorem ContinuousOn.preimage_isClosed_of_isClosed {f : α → β} {s : Set α} {t : Set β} (hf : ContinuousOn f s) (hs : IsClosed s) (ht : IsClosed t) : IsClosed (s ∩ f ⁻¹' t) := by rcases continuousOn_iff_isClosed.1 hf t ht with ⟨u, hu⟩ rw [inter_comm, hu.2] apply IsClosed.inter hu.1 hs theorem ContinuousOn.preimage_interior_subset_interior_preimage {f : α → β} {s : Set α} {t : Set β} (hf : ContinuousOn f s) (hs : IsOpen s) : s ∩ f ⁻¹' interior t ⊆ s ∩ interior (f ⁻¹' t) := calc s ∩ f ⁻¹' interior t ⊆ interior (s ∩ f ⁻¹' t) := interior_maximal (inter_subset_inter (Subset.refl _) (preimage_mono interior_subset)) (hf.isOpen_inter_preimage hs isOpen_interior) _ = s ∩ interior (f ⁻¹' t) := by rw [interior_inter, hs.interior_eq] theorem continuousOn_of_locally_continuousOn {f : α → β} {s : Set α} (h : ∀ x ∈ s, ∃ t, IsOpen t ∧ x ∈ t ∧ ContinuousOn f (s ∩ t)) : ContinuousOn f s := by intro x xs rcases h x xs with ⟨t, open_t, xt, ct⟩ have := ct x ⟨xs, xt⟩ rwa [ContinuousWithinAt, ← nhdsWithin_restrict _ xt open_t] at this theorem continuousOn_to_generateFrom_iff {β} {s : Set α} {T : Set (Set β)} {f : α → β} : @ContinuousOn α β _ (.generateFrom T) f s ↔ ∀ x ∈ s, ∀ t ∈ T, f x ∈ t → f ⁻¹' t ∈ 𝓝[s] x := forall₂_congr fun x _ => by delta ContinuousWithinAt simp only [TopologicalSpace.nhds_generateFrom, tendsto_iInf, tendsto_principal, mem_setOf_eq, and_imp] exact forall_congr' fun t => forall_swap -- Porting note: dropped an unneeded assumption theorem continuousOn_isOpen_of_generateFrom {β : Type*} {s : Set α} {T : Set (Set β)} {f : α → β} (h : ∀ t ∈ T, IsOpen (s ∩ f ⁻¹' t)) : @ContinuousOn α β _ (.generateFrom T) f s := continuousOn_to_generateFrom_iff.2 fun _x hx t ht hxt => mem_nhdsWithin.2 ⟨_, h t ht, ⟨hx, hxt⟩, fun _y hy => hy.1.2⟩ theorem ContinuousWithinAt.prod {f : α → β} {g : α → γ} {s : Set α} {x : α} (hf : ContinuousWithinAt f s x) (hg : ContinuousWithinAt g s x) : ContinuousWithinAt (fun x => (f x, g x)) s x := hf.prod_mk_nhds hg @[fun_prop] theorem ContinuousOn.prod {f : α → β} {g : α → γ} {s : Set α} (hf : ContinuousOn f s) (hg : ContinuousOn g s) : ContinuousOn (fun x => (f x, g x)) s := fun x hx => ContinuousWithinAt.prod (hf x hx) (hg x hx) theorem ContinuousAt.comp₂_continuousWithinAt {f : β × γ → δ} {g : α → β} {h : α → γ} {x : α} {s : Set α} (hf : ContinuousAt f (g x, h x)) (hg : ContinuousWithinAt g s x) (hh : ContinuousWithinAt h s x) : ContinuousWithinAt (fun x ↦ f (g x, h x)) s x := ContinuousAt.comp_continuousWithinAt hf (hg.prod hh) theorem ContinuousAt.comp₂_continuousWithinAt_of_eq {f : β × γ → δ} {g : α → β} {h : α → γ} {x : α} {s : Set α} {y : β × γ} (hf : ContinuousAt f y) (hg : ContinuousWithinAt g s x) (hh : ContinuousWithinAt h s x) (e : (g x, h x) = y) : ContinuousWithinAt (fun x ↦ f (g x, h x)) s x := by rw [← e] at hf exact hf.comp₂_continuousWithinAt hg hh theorem Inducing.continuousWithinAt_iff {f : α → β} {g : β → γ} (hg : Inducing g) {s : Set α} {x : α} : ContinuousWithinAt f s x ↔ ContinuousWithinAt (g ∘ f) s x := by simp_rw [ContinuousWithinAt, Inducing.tendsto_nhds_iff hg]; rfl theorem Inducing.continuousOn_iff {f : α → β} {g : β → γ} (hg : Inducing g) {s : Set α} : ContinuousOn f s ↔ ContinuousOn (g ∘ f) s := by simp_rw [ContinuousOn, hg.continuousWithinAt_iff] theorem Embedding.continuousOn_iff {f : α → β} {g : β → γ} (hg : Embedding g) {s : Set α} : ContinuousOn f s ↔ ContinuousOn (g ∘ f) s := Inducing.continuousOn_iff hg.1 theorem Embedding.map_nhdsWithin_eq {f : α → β} (hf : Embedding f) (s : Set α) (x : α) : map f (𝓝[s] x) = 𝓝[f '' s] f x := by rw [nhdsWithin, Filter.map_inf hf.inj, hf.map_nhds_eq, map_principal, ← nhdsWithin_inter', inter_eq_self_of_subset_right (image_subset_range _ _)] theorem OpenEmbedding.map_nhdsWithin_preimage_eq {f : α → β} (hf : OpenEmbedding f) (s : Set β) (x : α) : map f (𝓝[f ⁻¹' s] x) = 𝓝[s] f x := by rw [hf.toEmbedding.map_nhdsWithin_eq, image_preimage_eq_inter_range] apply nhdsWithin_eq_nhdsWithin (mem_range_self _) hf.isOpen_range rw [inter_assoc, inter_self] theorem QuotientMap.continuousOn_isOpen_iff {f : α → β} {g : β → γ} (h : QuotientMap f) {s : Set β} (hs : IsOpen s) : ContinuousOn g s ↔ ContinuousOn (g ∘ f) (f ⁻¹' s) := by simp only [continuousOn_iff_continuous_restrict, (h.restrictPreimage_isOpen hs).continuous_iff] rfl theorem continuousWithinAt_of_not_mem_closure {f : α → β} {s : Set α} {x : α} (hx : x ∉ closure s) : ContinuousWithinAt f s x := by rw [mem_closure_iff_nhdsWithin_neBot, not_neBot] at hx rw [ContinuousWithinAt, hx] exact tendsto_bot theorem ContinuousOn.if' {s : Set α} {p : α → Prop} {f g : α → β} [∀ a, Decidable (p a)] (hpf : ∀ a ∈ s ∩ frontier { a | p a }, Tendsto f (𝓝[s ∩ { a | p a }] a) (𝓝 <| if p a then f a else g a)) (hpg : ∀ a ∈ s ∩ frontier { a | p a }, Tendsto g (𝓝[s ∩ { a | ¬p a }] a) (𝓝 <| if p a then f a else g a)) (hf : ContinuousOn f <| s ∩ { a | p a }) (hg : ContinuousOn g <| s ∩ { a | ¬p a }) : ContinuousOn (fun a => if p a then f a else g a) s := by intro x hx by_cases hx' : x ∈ frontier { a | p a } · exact (hpf x ⟨hx, hx'⟩).piecewise_nhdsWithin (hpg x ⟨hx, hx'⟩) · rw [← inter_univ s, ← union_compl_self { a | p a }, inter_union_distrib_left] at hx ⊢ cases' hx with hx hx · apply ContinuousWithinAt.union · exact (hf x hx).congr (fun y hy => if_pos hy.2) (if_pos hx.2) · have : x ∉ closure { a | p a }ᶜ := fun h => hx' ⟨subset_closure hx.2, by rwa [closure_compl] at h⟩ exact continuousWithinAt_of_not_mem_closure fun h => this (closure_inter_subset_inter_closure _ _ h).2 · apply ContinuousWithinAt.union · have : x ∉ closure { a | p a } := fun h => hx' ⟨h, fun h' : x ∈ interior { a | p a } => hx.2 (interior_subset h')⟩ exact continuousWithinAt_of_not_mem_closure fun h => this (closure_inter_subset_inter_closure _ _ h).2 · exact (hg x hx).congr (fun y hy => if_neg hy.2) (if_neg hx.2) theorem ContinuousOn.piecewise' {s t : Set α} {f g : α → β} [∀ a, Decidable (a ∈ t)] (hpf : ∀ a ∈ s ∩ frontier t, Tendsto f (𝓝[s ∩ t] a) (𝓝 (piecewise t f g a))) (hpg : ∀ a ∈ s ∩ frontier t, Tendsto g (𝓝[s ∩ tᶜ] a) (𝓝 (piecewise t f g a))) (hf : ContinuousOn f <| s ∩ t) (hg : ContinuousOn g <| s ∩ tᶜ) : ContinuousOn (piecewise t f g) s := hf.if' hpf hpg hg theorem ContinuousOn.if {α β : Type*} [TopologicalSpace α] [TopologicalSpace β] {p : α → Prop} [∀ a, Decidable (p a)] {s : Set α} {f g : α → β} (hp : ∀ a ∈ s ∩ frontier { a | p a }, f a = g a) (hf : ContinuousOn f <| s ∩ closure { a | p a }) (hg : ContinuousOn g <| s ∩ closure { a | ¬p a }) : ContinuousOn (fun a => if p a then f a else g a) s := by apply ContinuousOn.if' · rintro a ha simp only [← hp a ha, ite_self] apply tendsto_nhdsWithin_mono_left (inter_subset_inter_right s subset_closure) exact hf a ⟨ha.1, ha.2.1⟩ · rintro a ha simp only [hp a ha, ite_self] apply tendsto_nhdsWithin_mono_left (inter_subset_inter_right s subset_closure) rcases ha with ⟨has, ⟨_, ha⟩⟩ rw [← mem_compl_iff, ← closure_compl] at ha apply hg a ⟨has, ha⟩ · exact hf.mono (inter_subset_inter_right s subset_closure) · exact hg.mono (inter_subset_inter_right s subset_closure) theorem ContinuousOn.piecewise {s t : Set α} {f g : α → β} [∀ a, Decidable (a ∈ t)] (ht : ∀ a ∈ s ∩ frontier t, f a = g a) (hf : ContinuousOn f <| s ∩ closure t) (hg : ContinuousOn g <| s ∩ closure tᶜ) : ContinuousOn (piecewise t f g) s := hf.if ht hg theorem continuous_if' {p : α → Prop} {f g : α → β} [∀ a, Decidable (p a)] (hpf : ∀ a ∈ frontier { x | p x }, Tendsto f (𝓝[{ x | p x }] a) (𝓝 <| ite (p a) (f a) (g a))) (hpg : ∀ a ∈ frontier { x | p x }, Tendsto g (𝓝[{ x | ¬p x }] a) (𝓝 <| ite (p a) (f a) (g a))) (hf : ContinuousOn f { x | p x }) (hg : ContinuousOn g { x | ¬p x }) : Continuous fun a => ite (p a) (f a) (g a) := by rw [continuous_iff_continuousOn_univ] apply ContinuousOn.if' <;> simp [*] <;> assumption theorem continuous_if {p : α → Prop} {f g : α → β} [∀ a, Decidable (p a)] (hp : ∀ a ∈ frontier { x | p x }, f a = g a) (hf : ContinuousOn f (closure { x | p x })) (hg : ContinuousOn g (closure { x | ¬p x })) : Continuous fun a => if p a then f a else g a := by rw [continuous_iff_continuousOn_univ] apply ContinuousOn.if <;> simp <;> assumption theorem Continuous.if {p : α → Prop} {f g : α → β} [∀ a, Decidable (p a)] (hp : ∀ a ∈ frontier { x | p x }, f a = g a) (hf : Continuous f) (hg : Continuous g) : Continuous fun a => if p a then f a else g a := continuous_if hp hf.continuousOn hg.continuousOn theorem continuous_if_const (p : Prop) {f g : α → β} [Decidable p] (hf : p → Continuous f) (hg : ¬p → Continuous g) : Continuous fun a => if p then f a else g a := by split_ifs with h exacts [hf h, hg h] theorem Continuous.if_const (p : Prop) {f g : α → β} [Decidable p] (hf : Continuous f) (hg : Continuous g) : Continuous fun a => if p then f a else g a := continuous_if_const p (fun _ => hf) fun _ => hg theorem continuous_piecewise {s : Set α} {f g : α → β} [∀ a, Decidable (a ∈ s)] (hs : ∀ a ∈ frontier s, f a = g a) (hf : ContinuousOn f (closure s)) (hg : ContinuousOn g (closure sᶜ)) : Continuous (piecewise s f g) := continuous_if hs hf hg theorem Continuous.piecewise {s : Set α} {f g : α → β} [∀ a, Decidable (a ∈ s)] (hs : ∀ a ∈ frontier s, f a = g a) (hf : Continuous f) (hg : Continuous g) : Continuous (piecewise s f g) := hf.if hs hg section Indicator variable [One β] {f : α → β} {s : Set α} @[to_additive] lemma continuous_mulIndicator (hs : ∀ a ∈ frontier s, f a = 1) (hf : ContinuousOn f (closure s)) : Continuous (mulIndicator s f) := by classical exact continuous_piecewise hs hf continuousOn_const @[to_additive] protected lemma Continuous.mulIndicator (hs : ∀ a ∈ frontier s, f a = 1) (hf : Continuous f) : Continuous (mulIndicator s f) := by classical exact hf.piecewise hs continuous_const end Indicator theorem IsOpen.ite' {s s' t : Set α} (hs : IsOpen s) (hs' : IsOpen s') (ht : ∀ x ∈ frontier t, x ∈ s ↔ x ∈ s') : IsOpen (t.ite s s') := by classical simp only [isOpen_iff_continuous_mem, Set.ite] at * convert continuous_piecewise (fun x hx => propext (ht x hx)) hs.continuousOn hs'.continuousOn rename_i x by_cases hx : x ∈ t <;> simp [hx] theorem IsOpen.ite {s s' t : Set α} (hs : IsOpen s) (hs' : IsOpen s') (ht : s ∩ frontier t = s' ∩ frontier t) : IsOpen (t.ite s s') := hs.ite' hs' fun x hx => by simpa [hx] using Set.ext_iff.1 ht x theorem ite_inter_closure_eq_of_inter_frontier_eq {s s' t : Set α} (ht : s ∩ frontier t = s' ∩ frontier t) : t.ite s s' ∩ closure t = s ∩ closure t := by rw [closure_eq_self_union_frontier, inter_union_distrib_left, inter_union_distrib_left, ite_inter_self, ite_inter_of_inter_eq _ ht] theorem ite_inter_closure_compl_eq_of_inter_frontier_eq {s s' t : Set α} (ht : s ∩ frontier t = s' ∩ frontier t) : t.ite s s' ∩ closure tᶜ = s' ∩ closure tᶜ := by rw [← ite_compl, ite_inter_closure_eq_of_inter_frontier_eq] rwa [frontier_compl, eq_comm] theorem continuousOn_piecewise_ite' {s s' t : Set α} {f f' : α → β} [∀ x, Decidable (x ∈ t)] (h : ContinuousOn f (s ∩ closure t)) (h' : ContinuousOn f' (s' ∩ closure tᶜ)) (H : s ∩ frontier t = s' ∩ frontier t) (Heq : EqOn f f' (s ∩ frontier t)) : ContinuousOn (t.piecewise f f') (t.ite s s') := by apply ContinuousOn.piecewise · rwa [ite_inter_of_inter_eq _ H] · rwa [ite_inter_closure_eq_of_inter_frontier_eq H] · rwa [ite_inter_closure_compl_eq_of_inter_frontier_eq H] theorem continuousOn_piecewise_ite {s s' t : Set α} {f f' : α → β} [∀ x, Decidable (x ∈ t)] (h : ContinuousOn f s) (h' : ContinuousOn f' s') (H : s ∩ frontier t = s' ∩ frontier t) (Heq : EqOn f f' (s ∩ frontier t)) : ContinuousOn (t.piecewise f f') (t.ite s s') := continuousOn_piecewise_ite' (h.mono inter_subset_left) (h'.mono inter_subset_left) H Heq theorem frontier_inter_open_inter {s t : Set α} (ht : IsOpen t) : frontier (s ∩ t) ∩ t = frontier s ∩ t := by simp only [Set.inter_comm _ t, ← Subtype.preimage_coe_eq_preimage_coe_iff, ht.isOpenMap_subtype_val.preimage_frontier_eq_frontier_preimage continuous_subtype_val, Subtype.preimage_coe_self_inter] theorem continuousOn_fst {s : Set (α × β)} : ContinuousOn Prod.fst s := continuous_fst.continuousOn theorem continuousWithinAt_fst {s : Set (α × β)} {p : α × β} : ContinuousWithinAt Prod.fst s p := continuous_fst.continuousWithinAt @[fun_prop] theorem ContinuousOn.fst {f : α → β × γ} {s : Set α} (hf : ContinuousOn f s) : ContinuousOn (fun x => (f x).1) s := continuous_fst.comp_continuousOn hf theorem ContinuousWithinAt.fst {f : α → β × γ} {s : Set α} {a : α} (h : ContinuousWithinAt f s a) : ContinuousWithinAt (fun x => (f x).fst) s a := continuousAt_fst.comp_continuousWithinAt h theorem continuousOn_snd {s : Set (α × β)} : ContinuousOn Prod.snd s := continuous_snd.continuousOn theorem continuousWithinAt_snd {s : Set (α × β)} {p : α × β} : ContinuousWithinAt Prod.snd s p := continuous_snd.continuousWithinAt @[fun_prop] theorem ContinuousOn.snd {f : α → β × γ} {s : Set α} (hf : ContinuousOn f s) : ContinuousOn (fun x => (f x).2) s := continuous_snd.comp_continuousOn hf theorem ContinuousWithinAt.snd {f : α → β × γ} {s : Set α} {a : α} (h : ContinuousWithinAt f s a) : ContinuousWithinAt (fun x => (f x).snd) s a := continuousAt_snd.comp_continuousWithinAt h theorem continuousWithinAt_prod_iff {f : α → β × γ} {s : Set α} {x : α} : ContinuousWithinAt f s x ↔ ContinuousWithinAt (Prod.fst ∘ f) s x ∧ ContinuousWithinAt (Prod.snd ∘ f) s x := ⟨fun h => ⟨h.fst, h.snd⟩, fun ⟨h1, h2⟩ => h1.prod h2⟩ end Pi
Topology\CountableSeparatingOn.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.Separation import Mathlib.Order.Filter.CountableSeparatingOn /-! # Countable separating families of sets in topological spaces In this file we show that a T₀ topological space with second countable topology has a countable family of open (or closed) sets separating the points. -/ variable {X : Type*} open Set TopologicalSpace /-- If `X` is a topological space, `s` is a set in `X` such that the induced topology is T₀ and is second countable, then there exists a countable family of open sets in `X` that separates points of `s`. -/ instance [TopologicalSpace X] {s : Set X} [T0Space s] [SecondCountableTopology s] : HasCountableSeparatingOn X IsOpen s := by suffices HasCountableSeparatingOn s IsOpen univ from .of_subtype fun _ ↦ isOpen_induced_iff.1 refine ⟨⟨countableBasis s, countable_countableBasis _, fun _ ↦ isOpen_of_mem_countableBasis, fun x _ y _ h ↦ ?_⟩⟩ exact ((isBasis_countableBasis _).inseparable_iff.2 h).eq /-- If there exists a countable family of open sets separating points of `s`, then there exists a countable family of closed sets separating points of `s`. -/ instance [TopologicalSpace X] {s : Set X} [h : HasCountableSeparatingOn X IsOpen s] : HasCountableSeparatingOn X IsClosed s := let ⟨S, hSc, hSo, hS⟩ := h.1 ⟨compl '' S, hSc.image _, forall_mem_image.2 fun U hU ↦ (hSo U hU).isClosed_compl, fun x hx y hy h ↦ hS x hx y hy fun _U hU ↦ not_iff_not.1 <| h _ (mem_image_of_mem _ hU)⟩
Topology\Covering.lean
/- Copyright (c) 2022 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import Mathlib.Topology.IsLocalHomeomorph import Mathlib.Topology.FiberBundle.Basic /-! # Covering Maps This file defines covering maps. ## Main definitions * `IsEvenlyCovered f x I`: A point `x` is evenly covered by `f : E → X` with fiber `I` if `I` is discrete and there is a `Trivialization` of `f` at `x` with fiber `I`. * `IsCoveringMap f`: A function `f : E → X` is a covering map if every point `x` is evenly covered by `f` with fiber `f ⁻¹' {x}`. The fibers `f ⁻¹' {x}` must be discrete, but if `X` is not connected, then the fibers `f ⁻¹' {x}` are not necessarily isomorphic. Also, `f` is not assumed to be surjective, so the fibers are even allowed to be empty. -/ open Bundle variable {E X : Type*} [TopologicalSpace E] [TopologicalSpace X] (f : E → X) (s : Set X) /-- A point `x : X` is evenly covered by `f : E → X` if `x` has an evenly covered neighborhood. -/ def IsEvenlyCovered (x : X) (I : Type*) [TopologicalSpace I] := DiscreteTopology I ∧ ∃ t : Trivialization I f, x ∈ t.baseSet namespace IsEvenlyCovered variable {f} /-- If `x` is evenly covered by `f`, then we can construct a trivialization of `f` at `x`. -/ noncomputable def toTrivialization {x : X} {I : Type*} [TopologicalSpace I] (h : IsEvenlyCovered f x I) : Trivialization (f ⁻¹' {x}) f := (Classical.choose h.2).transFiberHomeomorph ((Classical.choose h.2).preimageSingletonHomeomorph (Classical.choose_spec h.2)).symm theorem mem_toTrivialization_baseSet {x : X} {I : Type*} [TopologicalSpace I] (h : IsEvenlyCovered f x I) : x ∈ h.toTrivialization.baseSet := Classical.choose_spec h.2 theorem toTrivialization_apply {x : E} {I : Type*} [TopologicalSpace I] (h : IsEvenlyCovered f (f x) I) : (h.toTrivialization x).2 = ⟨x, rfl⟩ := let e := Classical.choose h.2 let h := Classical.choose_spec h.2 let he := e.mk_proj_snd' h Subtype.ext ((e.toPartialEquiv.eq_symm_apply (e.mem_source.mpr h) (by rwa [he, e.mem_target, e.coe_fst (e.mem_source.mpr h)])).mpr he.symm).symm protected theorem continuousAt {x : E} {I : Type*} [TopologicalSpace I] (h : IsEvenlyCovered f (f x) I) : ContinuousAt f x := let e := h.toTrivialization e.continuousAt_proj (e.mem_source.mpr (mem_toTrivialization_baseSet h)) theorem to_isEvenlyCovered_preimage {x : X} {I : Type*} [TopologicalSpace I] (h : IsEvenlyCovered f x I) : IsEvenlyCovered f x (f ⁻¹' {x}) := let ⟨_, h2⟩ := h ⟨((Classical.choose h2).preimageSingletonHomeomorph (Classical.choose_spec h2)).embedding.discreteTopology, _, h.mem_toTrivialization_baseSet⟩ end IsEvenlyCovered /-- A covering map is a continuous function `f : E → X` with discrete fibers such that each point of `X` has an evenly covered neighborhood. -/ def IsCoveringMapOn := ∀ x ∈ s, IsEvenlyCovered f x (f ⁻¹' {x}) namespace IsCoveringMapOn theorem mk (F : X → Type*) [∀ x, TopologicalSpace (F x)] [hF : ∀ x, DiscreteTopology (F x)] (e : ∀ x ∈ s, Trivialization (F x) f) (h : ∀ (x : X) (hx : x ∈ s), x ∈ (e x hx).baseSet) : IsCoveringMapOn f s := fun x hx => IsEvenlyCovered.to_isEvenlyCovered_preimage ⟨hF x, e x hx, h x hx⟩ variable {f} {s} protected theorem continuousAt (hf : IsCoveringMapOn f s) {x : E} (hx : f x ∈ s) : ContinuousAt f x := (hf (f x) hx).continuousAt protected theorem continuousOn (hf : IsCoveringMapOn f s) : ContinuousOn f (f ⁻¹' s) := ContinuousAt.continuousOn fun _ => hf.continuousAt protected theorem isLocalHomeomorphOn (hf : IsCoveringMapOn f s) : IsLocalHomeomorphOn f (f ⁻¹' s) := by refine IsLocalHomeomorphOn.mk f (f ⁻¹' s) fun x hx => ?_ let e := (hf (f x) hx).toTrivialization have h := (hf (f x) hx).mem_toTrivialization_baseSet let he := e.mem_source.2 h refine ⟨e.toPartialHomeomorph.trans { toFun := fun p => p.1 invFun := fun p => ⟨p, x, rfl⟩ source := e.baseSet ×ˢ ({⟨x, rfl⟩} : Set (f ⁻¹' {f x})) target := e.baseSet open_source := e.open_baseSet.prod (singletons_open_iff_discrete.2 (hf (f x) hx).1 ⟨x, rfl⟩) open_target := e.open_baseSet map_source' := fun p => And.left map_target' := fun p hp => ⟨hp, rfl⟩ left_inv' := fun p hp => Prod.ext rfl hp.2.symm right_inv' := fun p _ => rfl continuousOn_toFun := continuous_fst.continuousOn continuousOn_invFun := (continuous_id'.prod_mk continuous_const).continuousOn }, ⟨he, by rwa [e.toPartialHomeomorph.symm_symm, e.proj_toFun x he], (hf (f x) hx).toTrivialization_apply⟩, fun p h => (e.proj_toFun p h.1).symm⟩ end IsCoveringMapOn /-- A covering map is a continuous function `f : E → X` with discrete fibers such that each point of `X` has an evenly covered neighborhood. -/ def IsCoveringMap := ∀ x, IsEvenlyCovered f x (f ⁻¹' {x}) variable {f} theorem isCoveringMap_iff_isCoveringMapOn_univ : IsCoveringMap f ↔ IsCoveringMapOn f Set.univ := by simp only [IsCoveringMap, IsCoveringMapOn, Set.mem_univ, forall_true_left] protected theorem IsCoveringMap.isCoveringMapOn (hf : IsCoveringMap f) : IsCoveringMapOn f Set.univ := isCoveringMap_iff_isCoveringMapOn_univ.mp hf variable (f) namespace IsCoveringMap theorem mk (F : X → Type*) [∀ x, TopologicalSpace (F x)] [∀ x, DiscreteTopology (F x)] (e : ∀ x, Trivialization (F x) f) (h : ∀ x, x ∈ (e x).baseSet) : IsCoveringMap f := isCoveringMap_iff_isCoveringMapOn_univ.mpr (IsCoveringMapOn.mk f Set.univ F (fun x _ => e x) fun x _ => h x) variable {f} variable (hf : IsCoveringMap f) protected theorem continuous : Continuous f := continuous_iff_continuousOn_univ.mpr hf.isCoveringMapOn.continuousOn protected theorem isLocalHomeomorph : IsLocalHomeomorph f := isLocalHomeomorph_iff_isLocalHomeomorphOn_univ.mpr hf.isCoveringMapOn.isLocalHomeomorphOn protected theorem isOpenMap : IsOpenMap f := hf.isLocalHomeomorph.isOpenMap protected theorem quotientMap (hf' : Function.Surjective f) : QuotientMap f := hf.isOpenMap.to_quotientMap hf.continuous hf' protected theorem isSeparatedMap : IsSeparatedMap f := fun e₁ e₂ he hne ↦ by obtain ⟨_, t, he₁⟩ := hf (f e₁) have he₂ := he₁; simp_rw [he] at he₂; rw [← t.mem_source] at he₁ he₂ refine ⟨t.source ∩ (Prod.snd ∘ t) ⁻¹' {(t e₁).2}, t.source ∩ (Prod.snd ∘ t) ⁻¹' {(t e₂).2}, ?_, ?_, ⟨he₁, rfl⟩, ⟨he₂, rfl⟩, Set.disjoint_left.mpr fun x h₁ h₂ ↦ hne (t.injOn he₁ he₂ ?_)⟩ iterate 2 exact t.continuousOn_toFun.isOpen_inter_preimage t.open_source (continuous_snd.isOpen_preimage _ <| isOpen_discrete _) refine Prod.ext ?_ (h₁.2.symm.trans h₂.2) rwa [t.proj_toFun e₁ he₁, t.proj_toFun e₂ he₂] variable {A} [TopologicalSpace A] {s : Set A} {g g₁ g₂ : A → E} theorem eq_of_comp_eq [PreconnectedSpace A] (h₁ : Continuous g₁) (h₂ : Continuous g₂) (he : f ∘ g₁ = f ∘ g₂) (a : A) (ha : g₁ a = g₂ a) : g₁ = g₂ := hf.isSeparatedMap.eq_of_comp_eq hf.isLocalHomeomorph.isLocallyInjective h₁ h₂ he a ha theorem const_of_comp [PreconnectedSpace A] (cont : Continuous g) (he : ∀ a a', f (g a) = f (g a')) (a a') : g a = g a' := hf.isSeparatedMap.const_of_comp hf.isLocalHomeomorph.isLocallyInjective cont he a a' theorem eqOn_of_comp_eqOn (hs : IsPreconnected s) (h₁ : ContinuousOn g₁ s) (h₂ : ContinuousOn g₂ s) (he : s.EqOn (f ∘ g₁) (f ∘ g₂)) {a : A} (has : a ∈ s) (ha : g₁ a = g₂ a) : s.EqOn g₁ g₂ := hf.isSeparatedMap.eqOn_of_comp_eqOn hf.isLocalHomeomorph.isLocallyInjective hs h₁ h₂ he has ha theorem constOn_of_comp (hs : IsPreconnected s) (cont : ContinuousOn g s) (he : ∀ a ∈ s, ∀ a' ∈ s, f (g a) = f (g a')) {a a'} (ha : a ∈ s) (ha' : a' ∈ s) : g a = g a' := hf.isSeparatedMap.constOn_of_comp hf.isLocalHomeomorph.isLocallyInjective hs cont he ha ha' end IsCoveringMap variable {f} protected theorem IsFiberBundle.isCoveringMap {F : Type*} [TopologicalSpace F] [DiscreteTopology F] (hf : ∀ x : X, ∃ e : Trivialization F f, x ∈ e.baseSet) : IsCoveringMap f := IsCoveringMap.mk f (fun _ => F) (fun x => Classical.choose (hf x)) fun x => Classical.choose_spec (hf x) protected theorem FiberBundle.isCoveringMap {F : Type*} {E : X → Type*} [TopologicalSpace F] [DiscreteTopology F] [TopologicalSpace (Bundle.TotalSpace F E)] [∀ x, TopologicalSpace (E x)] [FiberBundle F E] : IsCoveringMap (π F E) := IsFiberBundle.isCoveringMap fun x => ⟨trivializationAt F E x, mem_baseSet_trivializationAt F E x⟩
Topology\DenseEmbedding.lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import Mathlib.Topology.Separation import Mathlib.Topology.Bases /-! # Dense embeddings This file defines three properties of functions: * `DenseRange f` means `f` has dense image; * `DenseInducing i` means `i` is also `Inducing`, namely it induces the topology on its codomain; * `DenseEmbedding e` means `e` is further an `Embedding`, namely it is injective and `Inducing`. The main theorem `continuous_extend` gives a criterion for a function `f : X → Z` to a T₃ space Z to extend along a dense embedding `i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only has to be `DenseInducing` (not necessarily injective). -/ noncomputable section open Set Filter open scoped Topology variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α` is the one induced by `i` from the topology on `β`. -/ structure DenseInducing [TopologicalSpace α] [TopologicalSpace β] (i : α → β) extends Inducing i : Prop where /-- The range of a dense inducing map is a dense set. -/ protected dense : DenseRange i namespace DenseInducing variable [TopologicalSpace α] [TopologicalSpace β] variable {i : α → β} theorem nhds_eq_comap (di : DenseInducing i) : ∀ a : α, 𝓝 a = comap i (𝓝 <| i a) := di.toInducing.nhds_eq_comap protected theorem continuous (di : DenseInducing i) : Continuous i := di.toInducing.continuous theorem closure_range (di : DenseInducing i) : closure (range i) = univ := di.dense.closure_range protected theorem preconnectedSpace [PreconnectedSpace α] (di : DenseInducing i) : PreconnectedSpace β := di.dense.preconnectedSpace di.continuous theorem closure_image_mem_nhds {s : Set α} {a : α} (di : DenseInducing i) (hs : s ∈ 𝓝 a) : closure (i '' s) ∈ 𝓝 (i a) := by rw [di.nhds_eq_comap a, ((nhds_basis_opens _).comap _).mem_iff] at hs rcases hs with ⟨U, ⟨haU, hUo⟩, sub : i ⁻¹' U ⊆ s⟩ refine mem_of_superset (hUo.mem_nhds haU) ?_ calc U ⊆ closure (i '' (i ⁻¹' U)) := di.dense.subset_closure_image_preimage_of_isOpen hUo _ ⊆ closure (i '' s) := closure_mono (image_subset i sub) theorem dense_image (di : DenseInducing i) {s : Set α} : Dense (i '' s) ↔ Dense s := by refine ⟨fun H x => ?_, di.dense.dense_image di.continuous⟩ rw [di.toInducing.closure_eq_preimage_closure_image, H.closure_eq, preimage_univ] trivial /-- If `i : α → β` is a dense embedding with dense complement of the range, then any compact set in `α` has empty interior. -/ theorem interior_compact_eq_empty [T2Space β] (di : DenseInducing i) (hd : Dense (range i)ᶜ) {s : Set α} (hs : IsCompact s) : interior s = ∅ := by refine eq_empty_iff_forall_not_mem.2 fun x hx => ?_ rw [mem_interior_iff_mem_nhds] at hx have := di.closure_image_mem_nhds hx rw [(hs.image di.continuous).isClosed.closure_eq] at this rcases hd.inter_nhds_nonempty this with ⟨y, hyi, hys⟩ exact hyi (image_subset_range _ _ hys) /-- The product of two dense inducings is a dense inducing -/ protected theorem prod [TopologicalSpace γ] [TopologicalSpace δ] {e₁ : α → β} {e₂ : γ → δ} (de₁ : DenseInducing e₁) (de₂ : DenseInducing e₂) : DenseInducing fun p : α × γ => (e₁ p.1, e₂ p.2) where toInducing := de₁.toInducing.prod_map de₂.toInducing dense := de₁.dense.prod_map de₂.dense open TopologicalSpace /-- If the domain of a `DenseInducing` map is a separable space, then so is the codomain. -/ protected theorem separableSpace [SeparableSpace α] (di : DenseInducing i) : SeparableSpace β := di.dense.separableSpace di.continuous variable [TopologicalSpace δ] {f : γ → α} {g : γ → δ} {h : δ → β} /-- ``` γ -f→ α g↓ ↓e δ -h→ β ``` -/ theorem tendsto_comap_nhds_nhds {d : δ} {a : α} (di : DenseInducing i) (H : Tendsto h (𝓝 d) (𝓝 (i a))) (comm : h ∘ g = i ∘ f) : Tendsto f (comap g (𝓝 d)) (𝓝 a) := by have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1 rw [Filter.map_map, comm, ← Filter.map_map, map_le_iff_le_comap] at lim1 have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H rw [← di.nhds_eq_comap] at lim2 exact le_trans lim1 lim2 protected theorem nhdsWithin_neBot (di : DenseInducing i) (b : β) : NeBot (𝓝[range i] b) := di.dense.nhdsWithin_neBot b theorem comap_nhds_neBot (di : DenseInducing i) (b : β) : NeBot (comap i (𝓝 b)) := comap_neBot fun s hs => by rcases mem_closure_iff_nhds.1 (di.dense b) s hs with ⟨_, ⟨ha, a, rfl⟩⟩ exact ⟨a, ha⟩ variable [TopologicalSpace γ] /-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends" to a function `g = DenseInducing.extend di f : β → γ`. If `γ` is Hausdorff and `f` has a continuous extension, then `g` is the unique such extension. In general, `g` might not be continuous or even extend `f`. -/ def extend (di : DenseInducing i) (f : α → γ) (b : β) : γ := @limUnder _ _ _ ⟨f (di.dense.some b)⟩ (comap i (𝓝 b)) f theorem extend_eq_of_tendsto [T2Space γ] (di : DenseInducing i) {b : β} {c : γ} {f : α → γ} (hf : Tendsto f (comap i (𝓝 b)) (𝓝 c)) : di.extend f b = c := haveI := di.comap_nhds_neBot hf.limUnder_eq theorem extend_eq_at [T2Space γ] (di : DenseInducing i) {f : α → γ} {a : α} (hf : ContinuousAt f a) : di.extend f (i a) = f a := extend_eq_of_tendsto _ <| di.nhds_eq_comap a ▸ hf theorem extend_eq_at' [T2Space γ] (di : DenseInducing i) {f : α → γ} {a : α} (c : γ) (hf : Tendsto f (𝓝 a) (𝓝 c)) : di.extend f (i a) = f a := di.extend_eq_at (continuousAt_of_tendsto_nhds hf) theorem extend_eq [T2Space γ] (di : DenseInducing i) {f : α → γ} (hf : Continuous f) (a : α) : di.extend f (i a) = f a := di.extend_eq_at hf.continuousAt /-- Variation of `extend_eq` where we ask that `f` has a limit along `comap i (𝓝 b)` for each `b : β`. This is a strictly stronger assumption than continuity of `f`, but in a lot of cases you'd have to prove it anyway to use `continuous_extend`, so this avoids doing the work twice. -/ theorem extend_eq' [T2Space γ] {f : α → γ} (di : DenseInducing i) (hf : ∀ b, ∃ c, Tendsto f (comap i (𝓝 b)) (𝓝 c)) (a : α) : di.extend f (i a) = f a := by rcases hf (i a) with ⟨b, hb⟩ refine di.extend_eq_at' b ?_ rwa [← di.toInducing.nhds_eq_comap] at hb theorem extend_unique_at [T2Space γ] {b : β} {f : α → γ} {g : β → γ} (di : DenseInducing i) (hf : ∀ᶠ x in comap i (𝓝 b), g (i x) = f x) (hg : ContinuousAt g b) : di.extend f b = g b := by refine di.extend_eq_of_tendsto fun s hs => mem_map.2 ?_ suffices ∀ᶠ x : α in comap i (𝓝 b), g (i x) ∈ s from hf.mp (this.mono fun x hgx hfx => hfx ▸ hgx) clear hf f refine eventually_comap.2 ((hg.eventually hs).mono ?_) rintro _ hxs x rfl exact hxs theorem extend_unique [T2Space γ] {f : α → γ} {g : β → γ} (di : DenseInducing i) (hf : ∀ x, g (i x) = f x) (hg : Continuous g) : di.extend f = g := funext fun _ => extend_unique_at di (eventually_of_forall hf) hg.continuousAt theorem continuousAt_extend [T3Space γ] {b : β} {f : α → γ} (di : DenseInducing i) (hf : ∀ᶠ x in 𝓝 b, ∃ c, Tendsto f (comap i <| 𝓝 x) (𝓝 c)) : ContinuousAt (di.extend f) b := by set φ := di.extend f haveI := di.comap_nhds_neBot suffices ∀ V' ∈ 𝓝 (φ b), IsClosed V' → φ ⁻¹' V' ∈ 𝓝 b by simpa [ContinuousAt, (closed_nhds_basis (φ b)).tendsto_right_iff] intro V' V'_in V'_closed set V₁ := { x | Tendsto f (comap i <| 𝓝 x) (𝓝 <| φ x) } have V₁_in : V₁ ∈ 𝓝 b := by filter_upwards [hf] rintro x ⟨c, hc⟩ rwa [← di.extend_eq_of_tendsto hc] at hc obtain ⟨V₂, V₂_in, V₂_op, hV₂⟩ : ∃ V₂ ∈ 𝓝 b, IsOpen V₂ ∧ ∀ x ∈ i ⁻¹' V₂, f x ∈ V' := by simpa [and_assoc] using ((nhds_basis_opens' b).comap i).tendsto_left_iff.mp (mem_of_mem_nhds V₁_in : b ∈ V₁) V' V'_in suffices ∀ x ∈ V₁ ∩ V₂, φ x ∈ V' by filter_upwards [inter_mem V₁_in V₂_in] using this rintro x ⟨x_in₁, x_in₂⟩ have hV₂x : V₂ ∈ 𝓝 x := IsOpen.mem_nhds V₂_op x_in₂ apply V'_closed.mem_of_tendsto x_in₁ use V₂ tauto theorem continuous_extend [T3Space γ] {f : α → γ} (di : DenseInducing i) (hf : ∀ b, ∃ c, Tendsto f (comap i (𝓝 b)) (𝓝 c)) : Continuous (di.extend f) := continuous_iff_continuousAt.mpr fun _ => di.continuousAt_extend <| univ_mem' hf theorem mk' (i : α → β) (c : Continuous i) (dense : ∀ x, x ∈ closure (range i)) (H : ∀ (a : α), ∀ s ∈ 𝓝 a, ∃ t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) : DenseInducing i := { toInducing := inducing_iff_nhds.2 fun a => le_antisymm (c.tendsto _).le_comap (by simpa [Filter.le_def] using H a) dense } end DenseInducing /-- A dense embedding is an embedding with dense image. -/ structure DenseEmbedding [TopologicalSpace α] [TopologicalSpace β] (e : α → β) extends DenseInducing e : Prop where /-- A dense embedding is injective. -/ inj : Function.Injective e theorem DenseEmbedding.mk' [TopologicalSpace α] [TopologicalSpace β] (e : α → β) (c : Continuous e) (dense : DenseRange e) (inj : Function.Injective e) (H : ∀ (a : α), ∀ s ∈ 𝓝 a, ∃ t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) : DenseEmbedding e := { DenseInducing.mk' e c dense H with inj } namespace DenseEmbedding open TopologicalSpace variable [TopologicalSpace α] [TopologicalSpace β] [TopologicalSpace γ] [TopologicalSpace δ] variable {e : α → β} theorem inj_iff (de : DenseEmbedding e) {x y} : e x = e y ↔ x = y := de.inj.eq_iff theorem to_embedding (de : DenseEmbedding e) : Embedding e := { induced := de.induced inj := de.inj } /-- If the domain of a `DenseEmbedding` is a separable space, then so is its codomain. -/ protected theorem separableSpace [SeparableSpace α] (de : DenseEmbedding e) : SeparableSpace β := de.toDenseInducing.separableSpace /-- The product of two dense embeddings is a dense embedding. -/ protected theorem prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : DenseEmbedding e₁) (de₂ : DenseEmbedding e₂) : DenseEmbedding fun p : α × γ => (e₁ p.1, e₂ p.2) := { de₁.toDenseInducing.prod de₂.toDenseInducing with inj := de₁.inj.prodMap de₂.inj } /-- The dense embedding of a subtype inside its closure. -/ @[simps] def subtypeEmb {α : Type*} (p : α → Prop) (e : α → β) (x : { x // p x }) : { x // x ∈ closure (e '' { x | p x }) } := ⟨e x, subset_closure <| mem_image_of_mem e x.prop⟩ protected theorem subtype (de : DenseEmbedding e) (p : α → Prop) : DenseEmbedding (subtypeEmb p e) := { dense := dense_iff_closure_eq.2 <| by ext ⟨x, hx⟩ rw [image_eq_range] at hx simpa [closure_subtype, ← range_comp, (· ∘ ·)] inj := (de.inj.comp Subtype.coe_injective).codRestrict _ induced := (induced_iff_nhds_eq _).2 fun ⟨x, hx⟩ => by simp [subtypeEmb, nhds_subtype_eq_comap, de.toInducing.nhds_eq_comap, comap_comap, (· ∘ ·)] } theorem dense_image (de : DenseEmbedding e) {s : Set α} : Dense (e '' s) ↔ Dense s := de.toDenseInducing.dense_image end DenseEmbedding theorem denseEmbedding_id {α : Type*} [TopologicalSpace α] : DenseEmbedding (id : α → α) := { embedding_id with dense := denseRange_id } theorem Dense.denseEmbedding_val [TopologicalSpace α] {s : Set α} (hs : Dense s) : DenseEmbedding ((↑) : s → α) := { embedding_subtype_val with dense := hs.denseRange_val } theorem isClosed_property [TopologicalSpace β] {e : α → β} {p : β → Prop} (he : DenseRange e) (hp : IsClosed { x | p x }) (h : ∀ a, p (e a)) : ∀ b, p b := have : univ ⊆ { b | p b } := calc univ = closure (range e) := he.closure_range.symm _ ⊆ closure { b | p b } := closure_mono <| range_subset_iff.mpr h _ = _ := hp.closure_eq fun _ => this trivial theorem isClosed_property2 [TopologicalSpace β] {e : α → β} {p : β → β → Prop} (he : DenseRange e) (hp : IsClosed { q : β × β | p q.1 q.2 }) (h : ∀ a₁ a₂, p (e a₁) (e a₂)) : ∀ b₁ b₂, p b₁ b₂ := have : ∀ q : β × β, p q.1 q.2 := isClosed_property (he.prod_map he) hp fun _ => h _ _ fun b₁ b₂ => this ⟨b₁, b₂⟩ theorem isClosed_property3 [TopologicalSpace β] {e : α → β} {p : β → β → β → Prop} (he : DenseRange e) (hp : IsClosed { q : β × β × β | p q.1 q.2.1 q.2.2 }) (h : ∀ a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀ b₁ b₂ b₃, p b₁ b₂ b₃ := have : ∀ q : β × β × β, p q.1 q.2.1 q.2.2 := isClosed_property (he.prod_map <| he.prod_map he) hp fun _ => h _ _ _ fun b₁ b₂ b₃ => this ⟨b₁, b₂, b₃⟩ @[elab_as_elim] theorem DenseRange.induction_on [TopologicalSpace β] {e : α → β} (he : DenseRange e) {p : β → Prop} (b₀ : β) (hp : IsClosed { b | p b }) (ih : ∀ a : α, p <| e a) : p b₀ := isClosed_property he hp ih b₀ @[elab_as_elim] theorem DenseRange.induction_on₂ [TopologicalSpace β] {e : α → β} {p : β → β → Prop} (he : DenseRange e) (hp : IsClosed { q : β × β | p q.1 q.2 }) (h : ∀ a₁ a₂, p (e a₁) (e a₂)) (b₁ b₂ : β) : p b₁ b₂ := isClosed_property2 he hp h _ _ @[elab_as_elim] theorem DenseRange.induction_on₃ [TopologicalSpace β] {e : α → β} {p : β → β → β → Prop} (he : DenseRange e) (hp : IsClosed { q : β × β × β | p q.1 q.2.1 q.2.2 }) (h : ∀ a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) (b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := isClosed_property3 he hp h _ _ _ section variable [TopologicalSpace β] [TopologicalSpace γ] [T2Space γ] variable {f : α → β} /-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/ theorem DenseRange.equalizer (hfd : DenseRange f) {g h : β → γ} (hg : Continuous g) (hh : Continuous h) (H : g ∘ f = h ∘ f) : g = h := funext fun y => hfd.induction_on y (isClosed_eq hg hh) <| congr_fun H end -- Bourbaki GT III §3 no.4 Proposition 7 (generalised to any dense-inducing map to a T₃ space) theorem Filter.HasBasis.hasBasis_of_denseInducing [TopologicalSpace α] [TopologicalSpace β] [T3Space β] {ι : Type*} {s : ι → Set α} {p : ι → Prop} {x : α} (h : (𝓝 x).HasBasis p s) {f : α → β} (hf : DenseInducing f) : (𝓝 (f x)).HasBasis p fun i => closure <| f '' s i := by rw [Filter.hasBasis_iff] at h ⊢ intro T refine ⟨fun hT => ?_, fun hT => ?_⟩ · obtain ⟨T', hT₁, hT₂, hT₃⟩ := exists_mem_nhds_isClosed_subset hT have hT₄ : f ⁻¹' T' ∈ 𝓝 x := by rw [hf.toInducing.nhds_eq_comap x] exact ⟨T', hT₁, Subset.rfl⟩ obtain ⟨i, hi, hi'⟩ := (h _).mp hT₄ exact ⟨i, hi, (closure_mono (image_subset f hi')).trans (Subset.trans (closure_minimal (image_preimage_subset _ _) hT₂) hT₃)⟩ · obtain ⟨i, hi, hi'⟩ := hT suffices closure (f '' s i) ∈ 𝓝 (f x) by filter_upwards [this] using hi' replace h := (h (s i)).mpr ⟨i, hi, Subset.rfl⟩ exact hf.closure_image_mem_nhds h
Topology\DerivedSet.lean
/- Copyright (c) 2024 Daniel Weber. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Weber -/ import Mathlib.Topology.Perfect import Mathlib.Tactic.Peel /-! # Derived set This file defines the derived set of a set, the set of all `AccPt`s of its principal filter, and proves some properties of it. -/ open Filter Topology variable {X : Type*} [TopologicalSpace X] theorem AccPt.map {β : Type*} [TopologicalSpace β] {F : Filter X} {x : X} (h : AccPt x F) {f : X → β} (hf1 : ContinuousAt f x) (hf2 : Function.Injective f) : AccPt (f x) (map f F) := by apply map_neBot (m := f) (hf := h) |>.mono rw [Filter.map_inf hf2] gcongr apply tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within _ hf1.continuousWithinAt simpa [hf2.eq_iff] using eventually_mem_nhdsWithin /-- The derived set of a set is the set of all accumulation points of it. -/ def derivedSet (A : Set X) : Set X := {x | AccPt x (𝓟 A)} @[simp] lemma mem_derivedSet {A : Set X} {x : X} : x ∈ derivedSet A ↔ AccPt x (𝓟 A) := Iff.rfl lemma derivedSet_union (A B : Set X) : derivedSet (A ∪ B) = derivedSet A ∪ derivedSet B := by ext x simp [derivedSet, ← sup_principal, accPt_sup] lemma derivedSet_mono (A B : Set X) (h : A ⊆ B) : derivedSet A ⊆ derivedSet B := fun _ hx ↦ hx.mono <| le_principal_iff.mpr <| mem_principal.mpr h theorem Continuous.image_derivedSet {β : Type*} [TopologicalSpace β] {A : Set X} {f : X → β} (hf1 : Continuous f) (hf2 : Function.Injective f) : f '' derivedSet A ⊆ derivedSet (f '' A) := by intro x hx simp only [Set.mem_image, mem_derivedSet] at hx obtain ⟨y, hy1, rfl⟩ := hx convert hy1.map hf1.continuousAt hf2 simp lemma derivedSet_subset_closure (A : Set X) : derivedSet A ⊆ closure A := fun _ hx ↦ mem_closure_iff_clusterPt.mpr hx.clusterPt lemma isClosed_iff_derivedSet_subset (A : Set X) : IsClosed A ↔ derivedSet A ⊆ A where mp h := derivedSet_subset_closure A |>.trans h.closure_subset mpr h := by rw [isClosed_iff_clusterPt] intro a ha by_contra! nh have : A = A \ {a} := by simp [nh] rw [this, ← acc_principal_iff_cluster] at ha exact nh (h ha) /-- In a `T1Space`, the `derivedSet` of the closure of a set is equal to the derived set of the set itself. Note: this doesn't hold in a space with the indiscrete topology. For example, if `X` is a type with two elements, `x` and `y`, and `A := {x}`, then `closure A = Set.univ` and `derivedSet A = {y}`, but `derivedSet Set.univ = Set.univ`. -/ lemma derivedSet_closure [T1Space X] (A : Set X) : derivedSet (closure A) = derivedSet A := by refine le_antisymm (fun x hx => ?_) (derivedSet_mono _ _ subset_closure) rw [mem_derivedSet, AccPt, (nhdsWithin_basis_open x {x}ᶜ).inf_principal_neBot_iff] at hx ⊢ peel hx with u hu _ obtain ⟨-, hu_open⟩ := hu exact mem_closure_iff.mp this.some_mem.2 (u ∩ {x}ᶜ) (hu_open.inter isOpen_compl_singleton) this.some_mem.1 @[simp] lemma isClosed_derivedSet [T1Space X] (A : Set X) : IsClosed (derivedSet A) := by rw [← derivedSet_closure, isClosed_iff_derivedSet_subset] apply derivedSet_mono simp [← isClosed_iff_derivedSet_subset] lemma preperfect_iff_subset_derivedSet {U : Set X} : Preperfect U ↔ U ⊆ derivedSet U := Iff.rfl lemma perfect_iff_eq_derivedSet {U : Set X} : Perfect U ↔ U = derivedSet U := by rw [perfect_def, isClosed_iff_derivedSet_subset, preperfect_iff_subset_derivedSet, ← subset_antisymm_iff, eq_comm] lemma IsPreconnected.inter_derivedSet_nonempty [T1Space X] {U : Set X} (hs : IsPreconnected U) (a b : Set X) (h : U ⊆ a ∪ b) (ha : (U ∩ derivedSet a).Nonempty) (hb : (U ∩ derivedSet b).Nonempty) : (U ∩ (derivedSet a ∩ derivedSet b)).Nonempty := by by_cases hu : U.Nontrivial · apply isPreconnected_closed_iff.mp hs · simp · simp · trans derivedSet U · apply hs.preperfect_of_nontrivial hu · rw [← derivedSet_union] exact derivedSet_mono _ _ h · exact ha · exact hb · obtain ⟨x, hx⟩ := ha.left.exists_eq_singleton_or_nontrivial.resolve_right hu simp_all
Topology\DiscreteQuotient.lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne, Adam Topaz -/ import Mathlib.Data.Setoid.Partition import Mathlib.Topology.Separation import Mathlib.Topology.LocallyConstant.Basic /-! # Discrete quotients of a topological space. This file defines the type of discrete quotients of a topological space, denoted `DiscreteQuotient X`. To avoid quantifying over types, we model such quotients as setoids whose equivalence classes are clopen. ## Definitions 1. `DiscreteQuotient X` is the type of discrete quotients of `X`. It is endowed with a coercion to `Type`, which is defined as the quotient associated to the setoid in question, and each such quotient is endowed with the discrete topology. 2. Given `S : DiscreteQuotient X`, the projection `X → S` is denoted `S.proj`. 3. When `X` is compact and `S : DiscreteQuotient X`, the space `S` is endowed with a `Fintype` instance. ## Order structure The type `DiscreteQuotient X` is endowed with an instance of a `SemilatticeInf` with `OrderTop`. The partial ordering `A ≤ B` mathematically means that `B.proj` factors through `A.proj`. The top element `⊤` is the trivial quotient, meaning that every element of `X` is collapsed to a point. Given `h : A ≤ B`, the map `A → B` is `DiscreteQuotient.ofLE h`. Whenever `X` is a locally connected space, the type `DiscreteQuotient X` is also endowed with an instance of an `OrderBot`, where the bot element `⊥` is given by the `connectedComponentSetoid`, i.e., `x ~ y` means that `x` and `y` belong to the same connected component. In particular, if `X` is a discrete topological space, then `x ~ y` is equivalent (propositionally, not definitionally) to `x = y`. Given `f : C(X, Y)`, we define a predicate `DiscreteQuotient.LEComap f A B` for `A : DiscreteQuotient X` and `B : DiscreteQuotient Y`, asserting that `f` descends to `A → B`. If `cond : DiscreteQuotient.LEComap h A B`, the function `A → B` is obtained by `DiscreteQuotient.map f cond`. ## Theorems The two main results proved in this file are: 1. `DiscreteQuotient.eq_of_forall_proj_eq` which states that when `X` is compact, T₂, and totally disconnected, any two elements of `X` are equal if their projections in `Q` agree for all `Q : DiscreteQuotient X`. 2. `DiscreteQuotient.exists_of_compat` which states that when `X` is compact, then any system of elements of `Q` as `Q : DiscreteQuotient X` varies, which is compatible with respect to `DiscreteQuotient.ofLE`, must arise from some element of `X`. ## Remarks The constructions in this file will be used to show that any profinite space is a limit of finite discrete spaces. -/ open Set Function TopologicalSpace variable {α X Y Z : Type*} [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] /-- The type of discrete quotients of a topological space. -/ @[ext] -- Porting note: in Lean 4, uses projection to `r` instead of `Setoid`. structure DiscreteQuotient (X : Type*) [TopologicalSpace X] extends Setoid X where /-- For every point `x`, the set `{ y | Rel x y }` is an open set. -/ protected isOpen_setOf_rel : ∀ x, IsOpen (setOf (toSetoid.Rel x)) namespace DiscreteQuotient variable (S : DiscreteQuotient X) lemma toSetoid_injective : Function.Injective (@toSetoid X _) | ⟨_, _⟩, ⟨_, _⟩, _ => by congr /-- Construct a discrete quotient from a clopen set. -/ def ofIsClopen {A : Set X} (h : IsClopen A) : DiscreteQuotient X where toSetoid := ⟨fun x y => x ∈ A ↔ y ∈ A, fun _ => Iff.rfl, Iff.symm, Iff.trans⟩ isOpen_setOf_rel x := by by_cases hx : x ∈ A <;> simp [Setoid.Rel, hx, h.1, h.2, ← compl_setOf] theorem refl : ∀ x, S.Rel x x := S.refl' theorem symm (x y : X) : S.Rel x y → S.Rel y x := S.symm' theorem trans (x y z : X) : S.Rel x y → S.Rel y z → S.Rel x z := S.trans' /-- The setoid whose quotient yields the discrete quotient. -/ add_decl_doc toSetoid instance : CoeSort (DiscreteQuotient X) (Type _) := ⟨fun S => Quotient S.toSetoid⟩ instance : TopologicalSpace S := inferInstanceAs (TopologicalSpace (Quotient S.toSetoid)) /-- The projection from `X` to the given discrete quotient. -/ def proj : X → S := Quotient.mk'' theorem fiber_eq (x : X) : S.proj ⁻¹' {S.proj x} = setOf (S.Rel x) := Set.ext fun _ => eq_comm.trans Quotient.eq'' theorem proj_surjective : Function.Surjective S.proj := Quotient.surjective_Quotient_mk'' theorem proj_quotientMap : QuotientMap S.proj := quotientMap_quot_mk theorem proj_continuous : Continuous S.proj := S.proj_quotientMap.continuous instance : DiscreteTopology S := singletons_open_iff_discrete.1 <| S.proj_surjective.forall.2 fun x => by rw [← S.proj_quotientMap.isOpen_preimage, fiber_eq] exact S.isOpen_setOf_rel _ theorem proj_isLocallyConstant : IsLocallyConstant S.proj := (IsLocallyConstant.iff_continuous S.proj).2 S.proj_continuous theorem isClopen_preimage (A : Set S) : IsClopen (S.proj ⁻¹' A) := (isClopen_discrete A).preimage S.proj_continuous theorem isOpen_preimage (A : Set S) : IsOpen (S.proj ⁻¹' A) := (S.isClopen_preimage A).2 theorem isClosed_preimage (A : Set S) : IsClosed (S.proj ⁻¹' A) := (S.isClopen_preimage A).1 theorem isClopen_setOf_rel (x : X) : IsClopen (setOf (S.Rel x)) := by rw [← fiber_eq] apply isClopen_preimage instance : Inf (DiscreteQuotient X) := ⟨fun S₁ S₂ => ⟨S₁.1 ⊓ S₂.1, fun x => (S₁.2 x).inter (S₂.2 x)⟩⟩ instance : SemilatticeInf (DiscreteQuotient X) := Injective.semilatticeInf toSetoid toSetoid_injective fun _ _ => rfl instance : OrderTop (DiscreteQuotient X) where top := ⟨⊤, fun _ => isOpen_univ⟩ le_top a := by tauto instance : Inhabited (DiscreteQuotient X) := ⟨⊤⟩ instance inhabitedQuotient [Inhabited X] : Inhabited S := ⟨S.proj default⟩ -- Porting note (#11215): TODO: add instances about `Nonempty (Quot _)`/`Nonempty (Quotient _)` instance [Nonempty X] : Nonempty S := Nonempty.map S.proj ‹_› /-- The quotient by `⊤ : DiscreteQuotient X` is a `Subsingleton`. -/ instance : Subsingleton (⊤ : DiscreteQuotient X) where allEq := by rintro ⟨_⟩ ⟨_⟩; exact Quotient.sound trivial section Comap variable (g : C(Y, Z)) (f : C(X, Y)) /-- Comap a discrete quotient along a continuous map. -/ def comap (S : DiscreteQuotient Y) : DiscreteQuotient X where toSetoid := Setoid.comap f S.1 isOpen_setOf_rel _ := (S.2 _).preimage f.continuous @[simp] theorem comap_id : S.comap (ContinuousMap.id X) = S := rfl @[simp] theorem comap_comp (S : DiscreteQuotient Z) : S.comap (g.comp f) = (S.comap g).comap f := rfl @[mono] theorem comap_mono {A B : DiscreteQuotient Y} (h : A ≤ B) : A.comap f ≤ B.comap f := by tauto end Comap section OfLE variable {A B C : DiscreteQuotient X} /-- The map induced by a refinement of a discrete quotient. -/ def ofLE (h : A ≤ B) : A → B := Quotient.map' (fun x => x) h @[simp] theorem ofLE_refl : ofLE (le_refl A) = id := by ext ⟨⟩ rfl theorem ofLE_refl_apply (a : A) : ofLE (le_refl A) a = a := by simp @[simp] theorem ofLE_ofLE (h₁ : A ≤ B) (h₂ : B ≤ C) (x : A) : ofLE h₂ (ofLE h₁ x) = ofLE (h₁.trans h₂) x := by rcases x with ⟨⟩ rfl @[simp] theorem ofLE_comp_ofLE (h₁ : A ≤ B) (h₂ : B ≤ C) : ofLE h₂ ∘ ofLE h₁ = ofLE (le_trans h₁ h₂) := funext <| ofLE_ofLE _ _ theorem ofLE_continuous (h : A ≤ B) : Continuous (ofLE h) := continuous_of_discreteTopology @[simp] theorem ofLE_proj (h : A ≤ B) (x : X) : ofLE h (A.proj x) = B.proj x := Quotient.sound' (B.refl _) @[simp] theorem ofLE_comp_proj (h : A ≤ B) : ofLE h ∘ A.proj = B.proj := funext <| ofLE_proj _ end OfLE /-- When `X` is a locally connected space, there is an `OrderBot` instance on `DiscreteQuotient X`. The bottom element is given by `connectedComponentSetoid X` -/ instance [LocallyConnectedSpace X] : OrderBot (DiscreteQuotient X) where bot := { toSetoid := connectedComponentSetoid X isOpen_setOf_rel := fun x => by convert isOpen_connectedComponent (x := x) ext y simpa only [connectedComponentSetoid, ← connectedComponent_eq_iff_mem] using eq_comm } bot_le S := fun x y (h : connectedComponent x = connectedComponent y) => (S.isClopen_setOf_rel x).connectedComponent_subset (S.refl _) <| h.symm ▸ mem_connectedComponent @[simp] theorem proj_bot_eq [LocallyConnectedSpace X] {x y : X} : proj ⊥ x = proj ⊥ y ↔ connectedComponent x = connectedComponent y := Quotient.eq'' theorem proj_bot_inj [DiscreteTopology X] {x y : X} : proj ⊥ x = proj ⊥ y ↔ x = y := by simp theorem proj_bot_injective [DiscreteTopology X] : Injective (⊥ : DiscreteQuotient X).proj := fun _ _ => proj_bot_inj.1 theorem proj_bot_bijective [DiscreteTopology X] : Bijective (⊥ : DiscreteQuotient X).proj := ⟨proj_bot_injective, proj_surjective _⟩ section Map variable (f : C(X, Y)) (A A' : DiscreteQuotient X) (B B' : DiscreteQuotient Y) /-- Given `f : C(X, Y)`, `DiscreteQuotient.LEComap f A B` is defined as `A ≤ B.comap f`. Mathematically this means that `f` descends to a morphism `A → B`. -/ def LEComap : Prop := A ≤ B.comap f theorem leComap_id : LEComap (.id X) A A := le_rfl variable {A A' B B'} {f} {g : C(Y, Z)} {C : DiscreteQuotient Z} @[simp] theorem leComap_id_iff : LEComap (ContinuousMap.id X) A A' ↔ A ≤ A' := Iff.rfl theorem LEComap.comp : LEComap g B C → LEComap f A B → LEComap (g.comp f) A C := by tauto @[mono] theorem LEComap.mono (h : LEComap f A B) (hA : A' ≤ A) (hB : B ≤ B') : LEComap f A' B' := hA.trans <| h.trans <| comap_mono _ hB /-- Map a discrete quotient along a continuous map. -/ def map (f : C(X, Y)) (cond : LEComap f A B) : A → B := Quotient.map' f cond theorem map_continuous (cond : LEComap f A B) : Continuous (map f cond) := continuous_of_discreteTopology @[simp] theorem map_comp_proj (cond : LEComap f A B) : map f cond ∘ A.proj = B.proj ∘ f := rfl @[simp] theorem map_proj (cond : LEComap f A B) (x : X) : map f cond (A.proj x) = B.proj (f x) := rfl @[simp] theorem map_id : map _ (leComap_id A) = id := by ext ⟨⟩; rfl -- Porting note (#11215): TODO: figure out why `simpNF` says this is a bad `@[simp]` lemma theorem map_comp (h1 : LEComap g B C) (h2 : LEComap f A B) : map (g.comp f) (h1.comp h2) = map g h1 ∘ map f h2 := by ext ⟨⟩ rfl @[simp] theorem ofLE_map (cond : LEComap f A B) (h : B ≤ B') (a : A) : ofLE h (map f cond a) = map f (cond.mono le_rfl h) a := by rcases a with ⟨⟩ rfl @[simp] theorem ofLE_comp_map (cond : LEComap f A B) (h : B ≤ B') : ofLE h ∘ map f cond = map f (cond.mono le_rfl h) := funext <| ofLE_map cond h @[simp] theorem map_ofLE (cond : LEComap f A B) (h : A' ≤ A) (c : A') : map f cond (ofLE h c) = map f (cond.mono h le_rfl) c := by rcases c with ⟨⟩ rfl @[simp] theorem map_comp_ofLE (cond : LEComap f A B) (h : A' ≤ A) : map f cond ∘ ofLE h = map f (cond.mono h le_rfl) := funext <| map_ofLE cond h end Map theorem eq_of_forall_proj_eq [T2Space X] [CompactSpace X] [disc : TotallyDisconnectedSpace X] {x y : X} (h : ∀ Q : DiscreteQuotient X, Q.proj x = Q.proj y) : x = y := by rw [← mem_singleton_iff, ← connectedComponent_eq_singleton, connectedComponent_eq_iInter_isClopen, mem_iInter] rintro ⟨U, hU1, hU2⟩ exact (Quotient.exact' (h (ofIsClopen hU1))).mpr hU2 theorem fiber_subset_ofLE {A B : DiscreteQuotient X} (h : A ≤ B) (a : A) : A.proj ⁻¹' {a} ⊆ B.proj ⁻¹' {ofLE h a} := by rcases A.proj_surjective a with ⟨a, rfl⟩ rw [fiber_eq, ofLE_proj, fiber_eq] exact fun _ h' => h h' theorem exists_of_compat [CompactSpace X] (Qs : (Q : DiscreteQuotient X) → Q) (compat : ∀ (A B : DiscreteQuotient X) (h : A ≤ B), ofLE h (Qs _) = Qs _) : ∃ x : X, ∀ Q : DiscreteQuotient X, Q.proj x = Qs _ := by have H₁ : ∀ Q₁ Q₂, Q₁ ≤ Q₂ → proj Q₁ ⁻¹' {Qs Q₁} ⊆ proj Q₂ ⁻¹' {Qs Q₂} := fun _ _ h => by rw [← compat _ _ h] exact fiber_subset_ofLE _ _ obtain ⟨x, hx⟩ : Set.Nonempty (⋂ Q, proj Q ⁻¹' {Qs Q}) := IsCompact.nonempty_iInter_of_directed_nonempty_isCompact_isClosed (fun Q : DiscreteQuotient X => Q.proj ⁻¹' {Qs _}) (directed_of_isDirected_ge H₁) (fun Q => (singleton_nonempty _).preimage Q.proj_surjective) (fun Q => (Q.isClosed_preimage {Qs _}).isCompact) fun Q => Q.isClosed_preimage _ exact ⟨x, mem_iInter.1 hx⟩ /-- If `X` is a compact space, then any discrete quotient of `X` is finite. -/ instance [CompactSpace X] : Finite S := by have : CompactSpace S := Quotient.compactSpace rwa [← isCompact_univ_iff, isCompact_iff_finite, finite_univ_iff] at this variable (X) open Classical in /-- If `X` is a compact space, then we associate to any discrete quotient on `X` a finite set of clopen subsets of `X`, given by the fibers of `proj`. TODO: prove that these form a partition of `X`  -/ noncomputable def finsetClopens [CompactSpace X] (d : DiscreteQuotient X) : Finset (Clopens X) := have : Fintype d := Fintype.ofFinite _ (Set.range (fun (x : d) ↦ ⟨_, d.isClopen_preimage {x}⟩) : Set (Clopens X)).toFinset /-- A helper lemma to prove that `finsetClopens X` is injective, see `finsetClopens_inj`. -/ lemma comp_finsetClopens [CompactSpace X] : (Set.image (fun (t : Clopens X) ↦ t.carrier) ∘ Finset.toSet) ∘ finsetClopens X = fun ⟨f, _⟩ ↦ f.classes := by ext d simp only [Setoid.classes, Setoid.Rel, Set.mem_setOf_eq, Function.comp_apply, finsetClopens, Set.coe_toFinset, Set.mem_image, Set.mem_range, exists_exists_eq_and] constructor · refine fun ⟨y, h⟩ ↦ ⟨Quotient.out (s := d.toSetoid) y, ?_⟩ ext simpa [← h] using Quotient.mk_eq_iff_out (s := d.toSetoid) · exact fun ⟨y, h⟩ ↦ ⟨d.proj y, by ext; simp [h, proj]⟩ /-- `finsetClopens X` is injective. -/ theorem finsetClopens_inj [CompactSpace X] : (finsetClopens X).Injective := by apply Function.Injective.of_comp (f := Set.image (fun (t : Clopens X) ↦ t.carrier) ∘ Finset.toSet) rw [comp_finsetClopens] intro ⟨_, _⟩ ⟨_, _⟩ h congr rw [Setoid.classes_inj] exact h /-- The discrete quotients of a compact space are in bijection with a subtype of the type of `Finset (Clopens X)`. TODO: show that this is precisely those finsets of clopens which form a partition of `X`. -/ noncomputable def equivFinsetClopens [CompactSpace X] := Equiv.ofInjective _ (finsetClopens_inj X) variable {X} end DiscreteQuotient namespace LocallyConstant variable (f : LocallyConstant X α) /-- Any locally constant function induces a discrete quotient. -/ def discreteQuotient : DiscreteQuotient X where toSetoid := .comap f ⊥ isOpen_setOf_rel _ := f.isLocallyConstant _ /-- The (locally constant) function from the discrete quotient associated to a locally constant function. -/ def lift : LocallyConstant f.discreteQuotient α := ⟨fun a => Quotient.liftOn' a f fun _ _ => id, fun _ => isOpen_discrete _⟩ @[simp] theorem lift_comp_proj : f.lift ∘ f.discreteQuotient.proj = f := rfl end LocallyConstant
Topology\DiscreteSubset.lean
/- Copyright (c) 2023 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash, Bhavik Mehta -/ import Mathlib.Topology.Constructions import Mathlib.Topology.Separation /-! # Discrete subsets of topological spaces This file contains various additional properties of discrete subsets of topological spaces. ## Discreteness and compact sets Given a topological space `X` together with a subset `s ⊆ X`, there are two distinct concepts of "discreteness" which may hold. These are: (i) Every point of `s` is isolated (i.e., the subset topology induced on `s` is the discrete topology). (ii) Every compact subset of `X` meets `s` only finitely often (i.e., the inclusion map `s → X` tends to the cocompact filter along the cofinite filter on `s`). When `s` is closed, the two conditions are equivalent provided `X` is locally compact and T1, see `IsClosed.tendsto_coe_cofinite_iff`. ### Main statements * `tendsto_cofinite_cocompact_iff`: * `IsClosed.tendsto_coe_cofinite_iff`: ## Co-discrete open sets In a topological space the sets which are open with discrete complement form a filter. We formalise this as `Filter.codiscrete`. -/ open Set Filter Function Topology variable {X Y : Type*} [TopologicalSpace Y] {f : X → Y} section cofinite_cocompact lemma tendsto_cofinite_cocompact_iff : Tendsto f cofinite (cocompact _) ↔ ∀ K, IsCompact K → Set.Finite (f ⁻¹' K) := by rw [hasBasis_cocompact.tendsto_right_iff] refine forall₂_congr (fun K _ ↦ ?_) simp only [mem_compl_iff, eventually_cofinite, not_not, preimage] variable [TopologicalSpace X] lemma Continuous.discrete_of_tendsto_cofinite_cocompact [T1Space X] [WeaklyLocallyCompactSpace Y] (hf' : Continuous f) (hf : Tendsto f cofinite (cocompact _)) : DiscreteTopology X := by refine singletons_open_iff_discrete.mp (fun x ↦ ?_) obtain ⟨K : Set Y, hK : IsCompact K, hK' : K ∈ 𝓝 (f x)⟩ := exists_compact_mem_nhds (f x) obtain ⟨U : Set Y, hU₁ : U ⊆ K, hU₂ : IsOpen U, hU₃ : f x ∈ U⟩ := mem_nhds_iff.mp hK' have hU₄ : Set.Finite (f⁻¹' U) := Finite.subset (tendsto_cofinite_cocompact_iff.mp hf K hK) (preimage_mono hU₁) exact isOpen_singleton_of_finite_mem_nhds _ ((hU₂.preimage hf').mem_nhds hU₃) hU₄ lemma tendsto_cofinite_cocompact_of_discrete [DiscreteTopology X] (hf : Tendsto f (cocompact _) (cocompact _)) : Tendsto f cofinite (cocompact _) := by convert hf rw [cocompact_eq_cofinite X] lemma IsClosed.tendsto_coe_cofinite_of_discreteTopology {s : Set X} (hs : IsClosed s) (_hs' : DiscreteTopology s) : Tendsto ((↑) : s → X) cofinite (cocompact _) := tendsto_cofinite_cocompact_of_discrete hs.closedEmbedding_subtype_val.tendsto_cocompact lemma IsClosed.tendsto_coe_cofinite_iff [T1Space X] [WeaklyLocallyCompactSpace X] {s : Set X} (hs : IsClosed s) : Tendsto ((↑) : s → X) cofinite (cocompact _) ↔ DiscreteTopology s := ⟨continuous_subtype_val.discrete_of_tendsto_cofinite_cocompact, fun _ ↦ hs.tendsto_coe_cofinite_of_discreteTopology inferInstance⟩ end cofinite_cocompact section codiscrete_filter variable [TopologicalSpace X] /-- Criterion for a subset `S ⊆ X` to be closed and discrete in terms of the punctured neighbourhood filter at an arbitrary point of `X`. (Compare `discreteTopology_subtype_iff`.) -/ theorem isClosed_and_discrete_iff {S : Set X} : IsClosed S ∧ DiscreteTopology S ↔ ∀ x, Disjoint (𝓝[≠] x) (𝓟 S) := by rw [discreteTopology_subtype_iff, isClosed_iff_clusterPt, ← forall_and] congrm (∀ x, ?_) rw [← not_imp_not, clusterPt_iff_not_disjoint, not_not, ← disjoint_iff] constructor <;> intro H · by_cases hx : x ∈ S exacts [H.2 hx, (H.1 hx).mono_left nhdsWithin_le_nhds] · refine ⟨fun hx ↦ ?_, fun _ ↦ H⟩ simpa [disjoint_iff, nhdsWithin, inf_assoc, hx] using H /-- In any topological space, the open sets with with discrete complement form a filter. -/ def Filter.codiscrete (X : Type*) [TopologicalSpace X] : Filter X where sets := {U | IsOpen U ∧ DiscreteTopology ↑Uᶜ} univ_sets := ⟨isOpen_univ, compl_univ.symm ▸ Subsingleton.discreteTopology⟩ sets_of_superset := by intro U V hU hV simp_rw [← isClosed_compl_iff, isClosed_and_discrete_iff] at hU ⊢ exact fun x ↦ (hU x).mono_right (principal_mono.mpr <| compl_subset_compl.mpr hV) inter_sets := by intro U V hU hV simp_rw [← isClosed_compl_iff, isClosed_and_discrete_iff] at hU hV ⊢ exact fun x ↦ compl_inter U V ▸ sup_principal ▸ disjoint_sup_right.mpr ⟨hU x, hV x⟩ end codiscrete_filter
Topology\ExtendFrom.lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Anatole Dedecker -/ import Mathlib.Topology.Separation /-! # Extending a function from a subset The main definition of this file is `extendFrom A f` where `f : X → Y` and `A : Set X`. This defines a new function `g : X → Y` which maps any `x₀ : X` to the limit of `f` as `x` tends to `x₀`, if such a limit exists. This is analogous to the way `DenseInducing.extend` "extends" a function `f : X → Z` to a function `g : Y → Z` along a dense inducing `i : X → Y`. The main theorem we prove about this definition is `continuousOn_extendFrom` which states that, for `extendFrom A f` to be continuous on a set `B ⊆ closure A`, it suffices that `f` converges within `A` at any point of `B`, provided that `f` is a function to a T₃ space. -/ noncomputable section open Topology open Filter Set variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] /-- Extend a function from a set `A`. The resulting function `g` is such that at any `x₀`, if `f` converges to some `y` as `x` tends to `x₀` within `A`, then `g x₀` is defined to be one of these `y`. Else, `g x₀` could be anything. -/ def extendFrom (A : Set X) (f : X → Y) : X → Y := fun x ↦ @limUnder _ _ _ ⟨f x⟩ (𝓝[A] x) f /-- If `f` converges to some `y` as `x` tends to `x₀` within `A`, then `f` tends to `extendFrom A f x` as `x` tends to `x₀`. -/ theorem tendsto_extendFrom {A : Set X} {f : X → Y} {x : X} (h : ∃ y, Tendsto f (𝓝[A] x) (𝓝 y)) : Tendsto f (𝓝[A] x) (𝓝 <| extendFrom A f x) := tendsto_nhds_limUnder h theorem extendFrom_eq [T2Space Y] {A : Set X} {f : X → Y} {x : X} {y : Y} (hx : x ∈ closure A) (hf : Tendsto f (𝓝[A] x) (𝓝 y)) : extendFrom A f x = y := haveI := mem_closure_iff_nhdsWithin_neBot.mp hx tendsto_nhds_unique (tendsto_nhds_limUnder ⟨y, hf⟩) hf theorem extendFrom_extends [T2Space Y] {f : X → Y} {A : Set X} (hf : ContinuousOn f A) : ∀ x ∈ A, extendFrom A f x = f x := fun x x_in ↦ extendFrom_eq (subset_closure x_in) (hf x x_in) /-- If `f` is a function to a T₃ space `Y` which has a limit within `A` at any point of a set `B ⊆ closure A`, then `extendFrom A f` is continuous on `B`. -/ theorem continuousOn_extendFrom [RegularSpace Y] {f : X → Y} {A B : Set X} (hB : B ⊆ closure A) (hf : ∀ x ∈ B, ∃ y, Tendsto f (𝓝[A] x) (𝓝 y)) : ContinuousOn (extendFrom A f) B := by set φ := extendFrom A f intro x x_in suffices ∀ V' ∈ 𝓝 (φ x), IsClosed V' → φ ⁻¹' V' ∈ 𝓝[B] x by simpa [ContinuousWithinAt, (closed_nhds_basis (φ x)).tendsto_right_iff] intro V' V'_in V'_closed obtain ⟨V, V_in, V_op, hV⟩ : ∃ V ∈ 𝓝 x, IsOpen V ∧ V ∩ A ⊆ f ⁻¹' V' := by have := tendsto_extendFrom (hf x x_in) rcases (nhdsWithin_basis_open x A).tendsto_left_iff.mp this V' V'_in with ⟨V, ⟨hxV, V_op⟩, hV⟩ exact ⟨V, IsOpen.mem_nhds V_op hxV, V_op, hV⟩ suffices ∀ y ∈ V ∩ B, φ y ∈ V' from mem_of_superset (inter_mem_inf V_in <| mem_principal_self B) this rintro y ⟨hyV, hyB⟩ haveI := mem_closure_iff_nhdsWithin_neBot.mp (hB hyB) have limy : Tendsto f (𝓝[A] y) (𝓝 <| φ y) := tendsto_extendFrom (hf y hyB) have hVy : V ∈ 𝓝 y := IsOpen.mem_nhds V_op hyV have : V ∩ A ∈ 𝓝[A] y := by simpa only [inter_comm] using inter_mem_nhdsWithin A hVy exact V'_closed.mem_of_tendsto limy (mem_of_superset this hV) /-- If a function `f` to a T₃ space `Y` has a limit within a dense set `A` for any `x`, then `extendFrom A f` is continuous. -/ theorem continuous_extendFrom [RegularSpace Y] {f : X → Y} {A : Set X} (hA : Dense A) (hf : ∀ x, ∃ y, Tendsto f (𝓝[A] x) (𝓝 y)) : Continuous (extendFrom A f) := by rw [continuous_iff_continuousOn_univ] exact continuousOn_extendFrom (fun x _ ↦ hA x) (by simpa using hf)
Topology\ExtremallyDisconnected.lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Topology.Homeomorph import Mathlib.Topology.StoneCech /-! # Extremally disconnected spaces An extremally disconnected topological space is a space in which the closure of every open set is open. Such spaces are also called Stonean spaces. They are the projective objects in the category of compact Hausdorff spaces. ## Main declarations * `ExtremallyDisconnected`: Predicate for a space to be extremally disconnected. * `CompactT2.Projective`: Predicate for a topological space to be a projective object in the category of compact Hausdorff spaces. * `CompactT2.Projective.extremallyDisconnected`: Compact Hausdorff spaces that are projective are extremally disconnected. * `CompactT2.ExtremallyDisconnected.projective`: Extremally disconnected spaces are projective objects in the category of compact Hausdorff spaces. ## References [Gleason, *Projective topological spaces*][gleason1958] -/ noncomputable section open Function Set universe u variable (X : Type u) [TopologicalSpace X] /-- An extremally disconnected topological space is a space in which the closure of every open set is open. -/ class ExtremallyDisconnected : Prop where /-- The closure of every open set is open. -/ open_closure : ∀ U : Set X, IsOpen U → IsOpen (closure U) theorem extremallyDisconnected_of_homeo {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [ExtremallyDisconnected X] (e : X ≃ₜ Y) : ExtremallyDisconnected Y where open_closure U hU := by rw [e.symm.inducing.closure_eq_preimage_closure_image, Homeomorph.isOpen_preimage] exact ExtremallyDisconnected.open_closure _ (e.symm.isOpen_image.mpr hU) section TotallySeparated /-- Extremally disconnected spaces are totally separated. -/ instance [ExtremallyDisconnected X] [T2Space X] : TotallySeparatedSpace X := { isTotallySeparated_univ := by intro x _ y _ hxy obtain ⟨U, V, hUV⟩ := T2Space.t2 hxy refine ⟨closure U, (closure U)ᶜ, ExtremallyDisconnected.open_closure U hUV.1, by simp only [isOpen_compl_iff, isClosed_closure], subset_closure hUV.2.2.1, ?_, by simp only [Set.union_compl_self, Set.subset_univ], disjoint_compl_right⟩ rw [Set.mem_compl_iff, mem_closure_iff] push_neg refine ⟨V, ⟨hUV.2.1, hUV.2.2.2.1, ?_⟩⟩ rw [← Set.disjoint_iff_inter_eq_empty, disjoint_comm] exact hUV.2.2.2.2 } end TotallySeparated section /-- The assertion `CompactT2.Projective` states that given continuous maps `f : X → Z` and `g : Y → Z` with `g` surjective between `t_2`, compact topological spaces, there exists a continuous lift `h : X → Y`, such that `f = g ∘ h`. -/ def CompactT2.Projective : Prop := ∀ {Y Z : Type u} [TopologicalSpace Y] [TopologicalSpace Z], ∀ [CompactSpace Y] [T2Space Y] [CompactSpace Z] [T2Space Z], ∀ {f : X → Z} {g : Y → Z} (_ : Continuous f) (_ : Continuous g) (_ : Surjective g), ∃ h : X → Y, Continuous h ∧ g ∘ h = f variable {X} theorem StoneCech.projective [DiscreteTopology X] : CompactT2.Projective (StoneCech X) := by intro Y Z _tsY _tsZ _csY _t2Y _csZ _csZ f g hf hg g_sur let s : Z → Y := fun z => Classical.choose <| g_sur z have hs : g ∘ s = id := funext fun z => Classical.choose_spec (g_sur z) let t := s ∘ f ∘ stoneCechUnit have ht : Continuous t := continuous_of_discreteTopology let h : StoneCech X → Y := stoneCechExtend ht have hh : Continuous h := continuous_stoneCechExtend ht refine ⟨h, hh, denseRange_stoneCechUnit.equalizer (hg.comp hh) hf ?_⟩ rw [comp.assoc, stoneCechExtend_extends ht, ← comp.assoc, hs, id_comp] protected theorem CompactT2.Projective.extremallyDisconnected [CompactSpace X] [T2Space X] (h : CompactT2.Projective X) : ExtremallyDisconnected X := by refine { open_closure := fun U hU => ?_ } let Z₁ : Set (X × Bool) := Uᶜ ×ˢ {true} let Z₂ : Set (X × Bool) := closure U ×ˢ {false} let Z : Set (X × Bool) := Z₁ ∪ Z₂ have hZ₁₂ : Disjoint Z₁ Z₂ := disjoint_left.2 fun x hx₁ hx₂ => by cases hx₁.2.symm.trans hx₂.2 have hZ₁ : IsClosed Z₁ := hU.isClosed_compl.prod (T1Space.t1 _) have hZ₂ : IsClosed Z₂ := isClosed_closure.prod (T1Space.t1 false) have hZ : IsClosed Z := hZ₁.union hZ₂ let f : Z → X := Prod.fst ∘ Subtype.val have f_cont : Continuous f := continuous_fst.comp continuous_subtype_val have f_sur : Surjective f := by intro x by_cases hx : x ∈ U · exact ⟨⟨(x, false), Or.inr ⟨subset_closure hx, mem_singleton _⟩⟩, rfl⟩ · exact ⟨⟨(x, true), Or.inl ⟨hx, mem_singleton _⟩⟩, rfl⟩ haveI : CompactSpace Z := isCompact_iff_compactSpace.mp hZ.isCompact obtain ⟨g, hg, g_sec⟩ := h continuous_id f_cont f_sur let φ := Subtype.val ∘ g have hφ : Continuous φ := continuous_subtype_val.comp hg have hφ₁ : ∀ x, (φ x).1 = x := congr_fun g_sec suffices closure U = φ ⁻¹' Z₂ by rw [this, preimage_comp, ← isClosed_compl_iff, ← preimage_compl, ← preimage_subtype_coe_eq_compl Subset.rfl] · exact hZ₁.preimage hφ · rw [hZ₁₂.inter_eq, inter_empty] refine (closure_minimal ?_ <| hZ₂.preimage hφ).antisymm fun x hx => ?_ · intro x hx have : φ x ∈ Z₁ ∪ Z₂ := (g x).2 -- Porting note: Originally `simpa [hx, hφ₁] using this` cases' this with hφ hφ · exact ((hφ₁ x ▸ hφ.1) hx).elim · exact hφ · rw [← hφ₁ x] exact hx.1 end section variable {A D E : Type u} [TopologicalSpace A] [TopologicalSpace D] [TopologicalSpace E] /-- Lemma 2.4 in [Gleason, *Projective topological spaces*][gleason1958]: a continuous surjection $\pi$ from a compact space $D$ to a Fréchet space $A$ restricts to a compact subset $E$ of $D$, such that $\pi$ maps $E$ onto $A$ and satisfies the "Zorn subset condition", where $\pi(E_0) \ne A$ for any proper closed subset $E_0 \subsetneq E$. -/ lemma exists_compact_surjective_zorn_subset [T1Space A] [CompactSpace D] {π : D → A} (π_cont : Continuous π) (π_surj : π.Surjective) : ∃ E : Set D, CompactSpace E ∧ π '' E = univ ∧ ∀ E₀ : Set E, E₀ ≠ univ → IsClosed E₀ → E.restrict π '' E₀ ≠ univ := by -- suffices to apply Zorn's lemma on the subsets of $D$ that are closed and mapped onto $A$ let S : Set <| Set D := {E : Set D | IsClosed E ∧ π '' E = univ} suffices ∀ (C : Set <| Set D) (_ : C ⊆ S) (_ : IsChain (· ⊆ ·) C), ∃ s ∈ S, ∀ c ∈ C, s ⊆ c by rcases zorn_superset S this with ⟨E, ⟨E_closed, E_surj⟩, E_min⟩ refine ⟨E, isCompact_iff_compactSpace.mp E_closed.isCompact, E_surj, ?_⟩ intro E₀ E₀_min E₀_closed contrapose! E₀_min exact eq_univ_of_image_val_eq <| E_min E₀ ⟨E₀_closed.trans E_closed, image_image_val_eq_restrict_image ▸ E₀_min⟩ image_val_subset -- suffices to prove intersection of chain is minimal intro C C_sub C_chain -- prove intersection of chain is closed refine ⟨iInter (fun c : C => c), ⟨isClosed_iInter fun ⟨_, h⟩ => (C_sub h).left, ?_⟩, fun c hc _ h => mem_iInter.mp h ⟨c, hc⟩⟩ -- prove intersection of chain is mapped onto $A$ by_cases hC : Nonempty C · refine eq_univ_of_forall fun a => inter_nonempty_iff_exists_left.mp ?_ -- apply Cantor's intersection theorem refine iInter_inter (ι := C) (π ⁻¹' {a}) _ ▸ IsCompact.nonempty_iInter_of_directed_nonempty_isCompact_isClosed _ ?_ (fun c => ?_) (fun c => IsClosed.isCompact ?_) (fun c => ?_) · replace C_chain : IsChain (· ⊇ ·) C := C_chain.symm have : ∀ s t : Set D, s ⊇ t → _ ⊇ _ := fun _ _ => inter_subset_inter_left <| π ⁻¹' {a} exact (directedOn_iff_directed.mp C_chain.directedOn).mono_comp (· ⊇ ·) this · rw [← image_inter_nonempty_iff, (C_sub c.mem).right, univ_inter] exact singleton_nonempty a all_goals exact (C_sub c.mem).left.inter <| (T1Space.t1 a).preimage π_cont · rw [@iInter_of_empty _ _ <| not_nonempty_iff.mp hC, image_univ_of_surjective π_surj] /-- Lemma 2.1 in [Gleason, *Projective topological spaces*][gleason1958]: if $\rho$ is a continuous surjection from a topological space $E$ to a topological space $A$ satisfying the "Zorn subset condition", then $\rho(G)$ is contained in the closure of $A \setminus \rho(E \setminus G)$ for any open set $G$ of $E$. -/ lemma image_subset_closure_compl_image_compl_of_isOpen {ρ : E → A} (ρ_cont : Continuous ρ) (ρ_surj : ρ.Surjective) (zorn_subset : ∀ E₀ : Set E, E₀ ≠ univ → IsClosed E₀ → ρ '' E₀ ≠ univ) {G : Set E} (hG : IsOpen G) : ρ '' G ⊆ closure ((ρ '' Gᶜ)ᶜ) := by -- suffices to prove for nonempty $G$ by_cases G_empty : G = ∅ · simpa only [G_empty, image_empty] using empty_subset _ · -- let $a \in \rho(G)$ intro a ha rw [mem_closure_iff] -- let $N$ be a neighbourhood of $a$ intro N N_open hN -- get $x \in A$ from nonempty open $G \cap \rho^{-1}(N)$ rcases (G.mem_image ρ a).mp ha with ⟨e, he, rfl⟩ have nonempty : (G ∩ ρ⁻¹' N).Nonempty := ⟨e, mem_inter he <| mem_preimage.mpr hN⟩ have is_open : IsOpen <| G ∩ ρ⁻¹' N := hG.inter <| N_open.preimage ρ_cont have ne_univ : ρ '' (G ∩ ρ⁻¹' N)ᶜ ≠ univ := zorn_subset _ (compl_ne_univ.mpr nonempty) is_open.isClosed_compl rcases nonempty_compl.mpr ne_univ with ⟨x, hx⟩ -- prove $x \in N \cap (A \setminus \rho(E \setminus G))$ have hx' : x ∈ (ρ '' Gᶜ)ᶜ := fun h => hx <| image_subset ρ (by simp) h rcases ρ_surj x with ⟨y, rfl⟩ have hy : y ∈ G ∩ ρ⁻¹' N := by simpa using mt (mem_image_of_mem ρ) <| mem_compl hx exact ⟨ρ y, mem_inter (mem_preimage.mp <| mem_of_mem_inter_right hy) hx'⟩ /-- Lemma 2.2 in [Gleason, *Projective topological spaces*][gleason1958]: in an extremally disconnected space, if $U_1$ and $U_2$ are disjoint open sets, then $\overline{U_1}$ and $\overline{U_2}$ are also disjoint. -/ lemma ExtremallyDisconnected.disjoint_closure_of_disjoint_isOpen [ExtremallyDisconnected A] {U₁ U₂ : Set A} (h : Disjoint U₁ U₂) (hU₁ : IsOpen U₁) (hU₂ : IsOpen U₂) : Disjoint (closure U₁) (closure U₂) := (h.closure_right hU₁).closure_left <| open_closure U₂ hU₂ private lemma ExtremallyDisconnected.homeoCompactToT2_injective [ExtremallyDisconnected A] [T2Space A] [T2Space E] [CompactSpace E] {ρ : E → A} (ρ_cont : Continuous ρ) (ρ_surj : ρ.Surjective) (zorn_subset : ∀ E₀ : Set E, E₀ ≠ univ → IsClosed E₀ → ρ '' E₀ ≠ univ) : ρ.Injective := by -- let $x_1, x_2 \in E$ be distinct points such that $\rho(x_1) = \rho(x_2)$ intro x₁ x₂ hρx by_contra hx -- let $G_1$ and $G_2$ be disjoint open neighbourhoods of $x_1$ and $x_2$ respectively rcases t2_separation hx with ⟨G₁, G₂, G₁_open, G₂_open, hx₁, hx₂, disj⟩ -- prove $A \setminus \rho(E - G_1)$ and $A \setminus \rho(E - G_2)$ are disjoint have G₁_comp : IsCompact G₁ᶜ := IsClosed.isCompact G₁_open.isClosed_compl have G₂_comp : IsCompact G₂ᶜ := IsClosed.isCompact G₂_open.isClosed_compl have G₁_open' : IsOpen (ρ '' G₁ᶜ)ᶜ := (G₁_comp.image ρ_cont).isClosed.isOpen_compl have G₂_open' : IsOpen (ρ '' G₂ᶜ)ᶜ := (G₂_comp.image ρ_cont).isClosed.isOpen_compl have disj' : Disjoint (ρ '' G₁ᶜ)ᶜ (ρ '' G₂ᶜ)ᶜ := by rw [disjoint_iff_inter_eq_empty, ← compl_union, ← image_union, ← compl_inter, disjoint_iff_inter_eq_empty.mp disj, compl_empty, compl_empty_iff, image_univ_of_surjective ρ_surj] -- apply Lemma 2.2 to prove their closures are disjoint have disj'' : Disjoint (closure (ρ '' G₁ᶜ)ᶜ) (closure (ρ '' G₂ᶜ)ᶜ) := disjoint_closure_of_disjoint_isOpen disj' G₁_open' G₂_open' -- apply Lemma 2.1 to prove $\rho(x_1) = \rho(x_2)$ lies in their intersection have hx₁' := image_subset_closure_compl_image_compl_of_isOpen ρ_cont ρ_surj zorn_subset G₁_open <| mem_image_of_mem ρ hx₁ have hx₂' := image_subset_closure_compl_image_compl_of_isOpen ρ_cont ρ_surj zorn_subset G₂_open <| mem_image_of_mem ρ hx₂ exact disj''.ne_of_mem hx₁' hx₂' hρx /-- Lemma 2.3 in [Gleason, *Projective topological spaces*][gleason1958]: a continuous surjection from a compact Hausdorff space to an extremally disconnected Hausdorff space satisfying the "Zorn subset condition" is a homeomorphism. -/ noncomputable def ExtremallyDisconnected.homeoCompactToT2 [ExtremallyDisconnected A] [T2Space A] [T2Space E] [CompactSpace E] {ρ : E → A} (ρ_cont : Continuous ρ) (ρ_surj : ρ.Surjective) (zorn_subset : ∀ E₀ : Set E, E₀ ≠ univ → IsClosed E₀ → ρ '' E₀ ≠ univ) : E ≃ₜ A := ρ_cont.homeoOfEquivCompactToT2 (f := Equiv.ofBijective ρ ⟨homeoCompactToT2_injective ρ_cont ρ_surj zorn_subset, ρ_surj⟩) /-- Theorem 2.5 in [Gleason, *Projective topological spaces*][gleason1958]: in the category of compact spaces and continuous maps, the projective spaces are precisely the extremally disconnected spaces. -/ protected theorem CompactT2.ExtremallyDisconnected.projective [ExtremallyDisconnected A] [CompactSpace A] [T2Space A] : CompactT2.Projective A := by -- let $B$ and $C$ be compact; let $f : B \twoheadrightarrow C$ and $\phi : A \to C$ be continuous intro B C _ _ _ _ _ _ φ f φ_cont f_cont f_surj -- let $D := \{(a, b) : \phi(a) = f(b)\}$ with projections $\pi_1 : D \to A$ and $\pi_2 : D \to B$ let D : Set <| A × B := {x | φ x.fst = f x.snd} have D_comp : CompactSpace D := isCompact_iff_compactSpace.mp (isClosed_eq (φ_cont.comp continuous_fst) (f_cont.comp continuous_snd)).isCompact -- apply Lemma 2.4 to get closed $E$ satisfying "Zorn subset condition" let π₁ : D → A := Prod.fst ∘ Subtype.val have π₁_cont : Continuous π₁ := continuous_fst.comp continuous_subtype_val have π₁_surj : π₁.Surjective := fun a => ⟨⟨⟨a, _⟩, (f_surj <| φ a).choose_spec.symm⟩, rfl⟩ rcases exists_compact_surjective_zorn_subset π₁_cont π₁_surj with ⟨E, _, E_onto, E_min⟩ -- apply Lemma 2.3 to get homeomorphism $\pi_1|_E : E \to A$ let ρ : E → A := E.restrict π₁ have ρ_cont : Continuous ρ := π₁_cont.continuousOn.restrict have ρ_surj : ρ.Surjective := fun a => by rcases (E_onto ▸ mem_univ a : a ∈ π₁ '' E) with ⟨d, ⟨hd, rfl⟩⟩; exact ⟨⟨d, hd⟩, rfl⟩ let ρ' := ExtremallyDisconnected.homeoCompactToT2 ρ_cont ρ_surj E_min -- prove $\rho := \pi_2|_E \circ \pi_1|_E^{-1}$ satisfies $\phi = f \circ \rho$ let π₂ : D → B := Prod.snd ∘ Subtype.val have π₂_cont : Continuous π₂ := continuous_snd.comp continuous_subtype_val refine ⟨E.restrict π₂ ∘ ρ'.symm, ⟨π₂_cont.continuousOn.restrict.comp ρ'.symm.continuous, ?_⟩⟩ suffices f ∘ E.restrict π₂ = φ ∘ ρ' by rw [← comp.assoc, this, comp.assoc, Homeomorph.self_comp_symm, comp_id] ext x exact x.val.mem.symm protected theorem CompactT2.projective_iff_extremallyDisconnected [CompactSpace A] [T2Space A] : Projective A ↔ ExtremallyDisconnected A := ⟨Projective.extremallyDisconnected, fun _ => ExtremallyDisconnected.projective⟩ @[deprecated (since := "2024-05-26")] alias CompactT2.projective_iff_extremallyDisconnnected := CompactT2.projective_iff_extremallyDisconnected end -- Note: It might be possible to use Gleason for this instead /-- The sigma-type of extremally disconnected spaces is extremally disconnected. -/ instance instExtremallyDisconnected {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] [h₀ : ∀ i, ExtremallyDisconnected (π i)] : ExtremallyDisconnected (Σ i, π i) := by constructor intro s hs rw [isOpen_sigma_iff] at hs ⊢ intro i rcases h₀ i with ⟨h₀⟩ suffices h : Sigma.mk i ⁻¹' closure s = closure (Sigma.mk i ⁻¹' s) by rw [h] exact h₀ _ (hs i) apply IsOpenMap.preimage_closure_eq_closure_preimage · intro U _ rw [isOpen_sigma_iff] intro j by_cases ij : i = j · rwa [← ij, sigma_mk_preimage_image_eq_self] · rw [sigma_mk_preimage_image' ij] exact isOpen_empty · continuity end
Topology\Filter.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Order.Filter.Lift import Mathlib.Topology.Separation import Mathlib.Order.Interval.Set.Monotone /-! # Topology on the set of filters on a type This file introduces a topology on `Filter α`. It is generated by the sets `Set.Iic (𝓟 s) = {l : Filter α | s ∈ l}`, `s : Set α`. A set `s : Set (Filter α)` is open if and only if it is a union of a family of these basic open sets, see `Filter.isOpen_iff`. This topology has the following important properties. * If `X` is a topological space, then the map `𝓝 : X → Filter X` is a topology inducing map. * In particular, it is a continuous map, so `𝓝 ∘ f` tends to `𝓝 (𝓝 a)` whenever `f` tends to `𝓝 a`. * If `X` is an ordered topological space with order topology and no max element, then `𝓝 ∘ f` tends to `𝓝 Filter.atTop` whenever `f` tends to `Filter.atTop`. * It turns `Filter X` into a T₀ space and the order on `Filter X` is the dual of the `specializationOrder (Filter X)`. ## Tags filter, topological space -/ open Set Filter TopologicalSpace open Filter Topology variable {ι : Sort*} {α β X Y : Type*} namespace Filter /-- The topology on `Filter α` is generated by the sets `Set.Iic (𝓟 s) = {l : Filter α | s ∈ l}`, `s : Set α`. A set `s : Set (Filter α)` is open if and only if it is a union of a family of these basic open sets, see `Filter.isOpen_iff`. -/ instance : TopologicalSpace (Filter α) := generateFrom <| range <| Iic ∘ 𝓟 theorem isOpen_Iic_principal {s : Set α} : IsOpen (Iic (𝓟 s)) := GenerateOpen.basic _ (mem_range_self _) theorem isOpen_setOf_mem {s : Set α} : IsOpen { l : Filter α | s ∈ l } := by simpa only [Iic_principal] using isOpen_Iic_principal theorem isTopologicalBasis_Iic_principal : IsTopologicalBasis (range (Iic ∘ 𝓟 : Set α → Set (Filter α))) := { exists_subset_inter := by rintro _ ⟨s, rfl⟩ _ ⟨t, rfl⟩ l hl exact ⟨Iic (𝓟 s) ∩ Iic (𝓟 t), ⟨s ∩ t, by simp⟩, hl, Subset.rfl⟩ sUnion_eq := sUnion_eq_univ_iff.2 fun l => ⟨Iic ⊤, ⟨univ, congr_arg Iic principal_univ⟩, mem_Iic.2 le_top⟩ eq_generateFrom := rfl } theorem isOpen_iff {s : Set (Filter α)} : IsOpen s ↔ ∃ T : Set (Set α), s = ⋃ t ∈ T, Iic (𝓟 t) := isTopologicalBasis_Iic_principal.open_iff_eq_sUnion.trans <| by simp only [exists_subset_range_and_iff, sUnion_image, (· ∘ ·)] theorem nhds_eq (l : Filter α) : 𝓝 l = l.lift' (Iic ∘ 𝓟) := nhds_generateFrom.trans <| by simp only [mem_setOf_eq, @and_comm (l ∈ _), iInf_and, iInf_range, Filter.lift', Filter.lift, (· ∘ ·), mem_Iic, le_principal_iff] theorem nhds_eq' (l : Filter α) : 𝓝 l = l.lift' fun s => { l' | s ∈ l' } := by simpa only [(· ∘ ·), Iic_principal] using nhds_eq l protected theorem tendsto_nhds {la : Filter α} {lb : Filter β} {f : α → Filter β} : Tendsto f la (𝓝 lb) ↔ ∀ s ∈ lb, ∀ᶠ a in la, s ∈ f a := by simp only [nhds_eq', tendsto_lift', mem_setOf_eq] protected theorem HasBasis.nhds {l : Filter α} {p : ι → Prop} {s : ι → Set α} (h : HasBasis l p s) : HasBasis (𝓝 l) p fun i => Iic (𝓟 (s i)) := by rw [nhds_eq] exact h.lift' monotone_principal.Iic protected theorem tendsto_pure_self (l : Filter X) : Tendsto (pure : X → Filter X) l (𝓝 l) := by rw [Filter.tendsto_nhds] exact fun s hs ↦ Eventually.mono hs fun x ↦ id /-- Neighborhoods of a countably generated filter is a countably generated filter. -/ instance {l : Filter α} [IsCountablyGenerated l] : IsCountablyGenerated (𝓝 l) := let ⟨_b, hb⟩ := l.exists_antitone_basis HasCountableBasis.isCountablyGenerated <| ⟨hb.nhds, Set.to_countable _⟩ theorem HasBasis.nhds' {l : Filter α} {p : ι → Prop} {s : ι → Set α} (h : HasBasis l p s) : HasBasis (𝓝 l) p fun i => { l' | s i ∈ l' } := by simpa only [Iic_principal] using h.nhds protected theorem mem_nhds_iff {l : Filter α} {S : Set (Filter α)} : S ∈ 𝓝 l ↔ ∃ t ∈ l, Iic (𝓟 t) ⊆ S := l.basis_sets.nhds.mem_iff theorem mem_nhds_iff' {l : Filter α} {S : Set (Filter α)} : S ∈ 𝓝 l ↔ ∃ t ∈ l, ∀ ⦃l' : Filter α⦄, t ∈ l' → l' ∈ S := l.basis_sets.nhds'.mem_iff @[simp] theorem nhds_bot : 𝓝 (⊥ : Filter α) = pure ⊥ := by simp [nhds_eq, (· ∘ ·), lift'_bot monotone_principal.Iic] @[simp] theorem nhds_top : 𝓝 (⊤ : Filter α) = ⊤ := by simp [nhds_eq] @[simp] theorem nhds_principal (s : Set α) : 𝓝 (𝓟 s) = 𝓟 (Iic (𝓟 s)) := (hasBasis_principal s).nhds.eq_of_same_basis (hasBasis_principal _) @[simp] theorem nhds_pure (x : α) : 𝓝 (pure x : Filter α) = 𝓟 {⊥, pure x} := by rw [← principal_singleton, nhds_principal, principal_singleton, Iic_pure] @[simp] theorem nhds_iInf (f : ι → Filter α) : 𝓝 (⨅ i, f i) = ⨅ i, 𝓝 (f i) := by simp only [nhds_eq] apply lift'_iInf_of_map_univ <;> simp @[simp] theorem nhds_inf (l₁ l₂ : Filter α) : 𝓝 (l₁ ⊓ l₂) = 𝓝 l₁ ⊓ 𝓝 l₂ := by simpa only [iInf_bool_eq] using nhds_iInf fun b => cond b l₁ l₂ theorem monotone_nhds : Monotone (𝓝 : Filter α → Filter (Filter α)) := Monotone.of_map_inf nhds_inf theorem sInter_nhds (l : Filter α) : ⋂₀ { s | s ∈ 𝓝 l } = Iic l := by simp_rw [nhds_eq, (· ∘ ·), sInter_lift'_sets monotone_principal.Iic, Iic, le_principal_iff, ← setOf_forall, ← Filter.le_def] @[simp] theorem nhds_mono {l₁ l₂ : Filter α} : 𝓝 l₁ ≤ 𝓝 l₂ ↔ l₁ ≤ l₂ := by refine ⟨fun h => ?_, fun h => monotone_nhds h⟩ rw [← Iic_subset_Iic, ← sInter_nhds, ← sInter_nhds] exact sInter_subset_sInter h protected theorem mem_interior {s : Set (Filter α)} {l : Filter α} : l ∈ interior s ↔ ∃ t ∈ l, Iic (𝓟 t) ⊆ s := by rw [mem_interior_iff_mem_nhds, Filter.mem_nhds_iff] protected theorem mem_closure {s : Set (Filter α)} {l : Filter α} : l ∈ closure s ↔ ∀ t ∈ l, ∃ l' ∈ s, t ∈ l' := by simp only [closure_eq_compl_interior_compl, Filter.mem_interior, mem_compl_iff, not_exists, not_forall, Classical.not_not, exists_prop, not_and, and_comm, subset_def, mem_Iic, le_principal_iff] @[simp] protected theorem closure_singleton (l : Filter α) : closure {l} = Ici l := by ext l' simp [Filter.mem_closure, Filter.le_def] @[simp] theorem specializes_iff_le {l₁ l₂ : Filter α} : l₁ ⤳ l₂ ↔ l₁ ≤ l₂ := by simp only [specializes_iff_closure_subset, Filter.closure_singleton, Ici_subset_Ici] instance : T0Space (Filter α) := ⟨fun _ _ h => (specializes_iff_le.1 h.specializes).antisymm (specializes_iff_le.1 h.symm.specializes)⟩ theorem nhds_atTop [Preorder α] : 𝓝 atTop = ⨅ x : α, 𝓟 (Iic (𝓟 (Ici x))) := by simp only [atTop, nhds_iInf, nhds_principal] protected theorem tendsto_nhds_atTop_iff [Preorder β] {l : Filter α} {f : α → Filter β} : Tendsto f l (𝓝 atTop) ↔ ∀ y, ∀ᶠ a in l, Ici y ∈ f a := by simp only [nhds_atTop, tendsto_iInf, tendsto_principal, mem_Iic, le_principal_iff] theorem nhds_atBot [Preorder α] : 𝓝 atBot = ⨅ x : α, 𝓟 (Iic (𝓟 (Iic x))) := @nhds_atTop αᵒᵈ _ protected theorem tendsto_nhds_atBot_iff [Preorder β] {l : Filter α} {f : α → Filter β} : Tendsto f l (𝓝 atBot) ↔ ∀ y, ∀ᶠ a in l, Iic y ∈ f a := @Filter.tendsto_nhds_atTop_iff α βᵒᵈ _ _ _ variable [TopologicalSpace X] theorem nhds_nhds (x : X) : 𝓝 (𝓝 x) = ⨅ (s : Set X) (_ : IsOpen s) (_ : x ∈ s), 𝓟 (Iic (𝓟 s)) := by simp only [(nhds_basis_opens x).nhds.eq_biInf, iInf_and, @iInf_comm _ (_ ∈ _)] theorem inducing_nhds : Inducing (𝓝 : X → Filter X) := inducing_iff_nhds.2 fun x => (nhds_def' _).trans <| by simp (config := { contextual := true }) only [nhds_nhds, comap_iInf, comap_principal, Iic_principal, preimage_setOf_eq, ← mem_interior_iff_mem_nhds, setOf_mem_eq, IsOpen.interior_eq] @[continuity] theorem continuous_nhds : Continuous (𝓝 : X → Filter X) := inducing_nhds.continuous protected theorem Tendsto.nhds {f : α → X} {l : Filter α} {x : X} (h : Tendsto f l (𝓝 x)) : Tendsto (𝓝 ∘ f) l (𝓝 (𝓝 x)) := (continuous_nhds.tendsto _).comp h end Filter variable [TopologicalSpace X] [TopologicalSpace Y] {f : X → Y} {x : X} {s : Set X} protected nonrec theorem ContinuousWithinAt.nhds (h : ContinuousWithinAt f s x) : ContinuousWithinAt (𝓝 ∘ f) s x := h.nhds protected nonrec theorem ContinuousAt.nhds (h : ContinuousAt f x) : ContinuousAt (𝓝 ∘ f) x := h.nhds protected nonrec theorem ContinuousOn.nhds (h : ContinuousOn f s) : ContinuousOn (𝓝 ∘ f) s := fun x hx => (h x hx).nhds protected nonrec theorem Continuous.nhds (h : Continuous f) : Continuous (𝓝 ∘ f) := Filter.continuous_nhds.comp h
Topology\GDelta.lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import Mathlib.Topology.UniformSpace.Basic import Mathlib.Order.Filter.CountableInter /-! # `Gδ` sets In this file we define `Gδ` sets and prove their basic properties. ## Main definitions * `IsGδ`: a set `s` is a `Gδ` set if it can be represented as an intersection of countably many open sets; * `residual`: the σ-filter of residual sets. A set `s` is called *residual* if it includes a countable intersection of dense open sets. * `IsNowhereDense`: a set is called *nowhere dense* iff its closure has empty interior * `IsMeagre`: a set `s` is called *meagre* iff its complement is residual ## Main results We prove that finite or countable intersections of Gδ sets are Gδ sets. We also prove that the continuity set of a function from a topological space to an (e)metric space is a Gδ set. - `isClosed_isNowhereDense_iff_compl`: a closed set is nowhere dense iff its complement is open and dense - `isMeagre_iff_countable_union_isNowhereDense`: a set is meagre iff it is contained in a countable union of nowhere dense sets - subsets of meagre sets are meagre; countable unions of meagre sets are meagre ## Tags Gδ set, residual set, nowhere dense set, meagre set -/ noncomputable section open Topology TopologicalSpace Filter Encodable Set open scoped Uniformity variable {X Y ι : Type*} {ι' : Sort*} section IsGδ variable [TopologicalSpace X] /-- A Gδ set is a countable intersection of open sets. -/ def IsGδ (s : Set X) : Prop := ∃ T : Set (Set X), (∀ t ∈ T, IsOpen t) ∧ T.Countable ∧ s = ⋂₀ T /-- An open set is a Gδ set. -/ theorem IsOpen.isGδ {s : Set X} (h : IsOpen s) : IsGδ s := ⟨{s}, by simp [h], countable_singleton _, (Set.sInter_singleton _).symm⟩ @[simp] protected theorem IsGδ.empty : IsGδ (∅ : Set X) := isOpen_empty.isGδ @[deprecated (since := "2024-02-15")] alias isGδ_empty := IsGδ.empty @[simp] protected theorem IsGδ.univ : IsGδ (univ : Set X) := isOpen_univ.isGδ @[deprecated (since := "2024-02-15")] alias isGδ_univ := IsGδ.univ theorem IsGδ.biInter_of_isOpen {I : Set ι} (hI : I.Countable) {f : ι → Set X} (hf : ∀ i ∈ I, IsOpen (f i)) : IsGδ (⋂ i ∈ I, f i) := ⟨f '' I, by rwa [forall_mem_image], hI.image _, by rw [sInter_image]⟩ @[deprecated (since := "2024-02-15")] alias isGδ_biInter_of_isOpen := IsGδ.biInter_of_isOpen theorem IsGδ.iInter_of_isOpen [Countable ι'] {f : ι' → Set X} (hf : ∀ i, IsOpen (f i)) : IsGδ (⋂ i, f i) := ⟨range f, by rwa [forall_mem_range], countable_range _, by rw [sInter_range]⟩ @[deprecated (since := "2024-02-15")] alias isGδ_iInter_of_isOpen := IsGδ.iInter_of_isOpen lemma isGδ_iff_eq_iInter_nat {s : Set X} : IsGδ s ↔ ∃ (f : ℕ → Set X), (∀ n, IsOpen (f n)) ∧ s = ⋂ n, f n := by refine ⟨?_, ?_⟩ · rintro ⟨T, hT, T_count, rfl⟩ rcases Set.eq_empty_or_nonempty T with rfl|hT · exact ⟨fun _n ↦ univ, fun _n ↦ isOpen_univ, by simp⟩ · obtain ⟨f, hf⟩ : ∃ (f : ℕ → Set X), T = range f := Countable.exists_eq_range T_count hT exact ⟨f, by aesop, by simp [hf]⟩ · rintro ⟨f, hf, rfl⟩ exact .iInter_of_isOpen hf alias ⟨IsGδ.eq_iInter_nat, _⟩ := isGδ_iff_eq_iInter_nat /-- The intersection of an encodable family of Gδ sets is a Gδ set. -/ protected theorem IsGδ.iInter [Countable ι'] {s : ι' → Set X} (hs : ∀ i, IsGδ (s i)) : IsGδ (⋂ i, s i) := by choose T hTo hTc hTs using hs obtain rfl : s = fun i => ⋂₀ T i := funext hTs refine ⟨⋃ i, T i, ?_, countable_iUnion hTc, (sInter_iUnion _).symm⟩ simpa [@forall_swap ι'] using hTo @[deprecated (since := "2024.02.15")] alias isGδ_iInter := IsGδ.iInter theorem IsGδ.biInter {s : Set ι} (hs : s.Countable) {t : ∀ i ∈ s, Set X} (ht : ∀ (i) (hi : i ∈ s), IsGδ (t i hi)) : IsGδ (⋂ i ∈ s, t i ‹_›) := by rw [biInter_eq_iInter] haveI := hs.to_subtype exact .iInter fun x => ht x x.2 @[deprecated (since := "2024-02-15")] alias isGδ_biInter := IsGδ.biInter /-- A countable intersection of Gδ sets is a Gδ set. -/ theorem IsGδ.sInter {S : Set (Set X)} (h : ∀ s ∈ S, IsGδ s) (hS : S.Countable) : IsGδ (⋂₀ S) := by simpa only [sInter_eq_biInter] using IsGδ.biInter hS h @[deprecated (since := "2024-02-15")] alias isGδ_sInter := IsGδ.sInter theorem IsGδ.inter {s t : Set X} (hs : IsGδ s) (ht : IsGδ t) : IsGδ (s ∩ t) := by rw [inter_eq_iInter] exact .iInter (Bool.forall_bool.2 ⟨ht, hs⟩) /-- The union of two Gδ sets is a Gδ set. -/ theorem IsGδ.union {s t : Set X} (hs : IsGδ s) (ht : IsGδ t) : IsGδ (s ∪ t) := by rcases hs with ⟨S, Sopen, Scount, rfl⟩ rcases ht with ⟨T, Topen, Tcount, rfl⟩ rw [sInter_union_sInter] refine .biInter_of_isOpen (Scount.prod Tcount) ?_ rintro ⟨a, b⟩ ⟨ha, hb⟩ exact (Sopen a ha).union (Topen b hb) /-- The union of finitely many Gδ sets is a Gδ set, `Set.sUnion` version. -/ theorem IsGδ.sUnion {S : Set (Set X)} (hS : S.Finite) (h : ∀ s ∈ S, IsGδ s) : IsGδ (⋃₀ S) := by induction S, hS using Set.Finite.dinduction_on with | H0 => simp | H1 _ _ ih => simp only [forall_mem_insert, sUnion_insert] at * exact h.1.union (ih h.2) /-- The union of finitely many Gδ sets is a Gδ set, bounded indexed union version. -/ theorem IsGδ.biUnion {s : Set ι} (hs : s.Finite) {f : ι → Set X} (h : ∀ i ∈ s, IsGδ (f i)) : IsGδ (⋃ i ∈ s, f i) := by rw [← sUnion_image] exact .sUnion (hs.image _) (forall_mem_image.2 h) @[deprecated (since := "2024-02-15")] alias isGδ_biUnion := IsGδ.biUnion /-- The union of finitely many Gδ sets is a Gδ set, bounded indexed union version. -/ theorem IsGδ.iUnion [Finite ι'] {f : ι' → Set X} (h : ∀ i, IsGδ (f i)) : IsGδ (⋃ i, f i) := .sUnion (finite_range _) <| forall_mem_range.2 h theorem IsClosed.isGδ {X : Type*} [UniformSpace X] [IsCountablyGenerated (𝓤 X)] {s : Set X} (hs : IsClosed s) : IsGδ s := by rcases (@uniformity_hasBasis_open X _).exists_antitone_subbasis with ⟨U, hUo, hU, -⟩ rw [← hs.closure_eq, ← hU.biInter_biUnion_ball] refine .biInter (to_countable _) fun n _ => IsOpen.isGδ ?_ exact isOpen_biUnion fun x _ => UniformSpace.isOpen_ball _ (hUo _).2 end IsGδ section ContinuousAt variable [TopologicalSpace X] /-- The set of points where a function is continuous is a Gδ set. -/ theorem IsGδ.setOf_continuousAt [UniformSpace Y] [IsCountablyGenerated (𝓤 Y)] (f : X → Y) : IsGδ { x | ContinuousAt f x } := by obtain ⟨U, _, hU⟩ := (@uniformity_hasBasis_open_symmetric Y _).exists_antitone_subbasis simp only [Uniform.continuousAt_iff_prod, nhds_prod_eq] simp only [(nhds_basis_opens _).prod_self.tendsto_iff hU.toHasBasis, forall_prop_of_true, setOf_forall, id] refine .iInter fun k ↦ IsOpen.isGδ <| isOpen_iff_mem_nhds.2 fun x ↦ ?_ rintro ⟨s, ⟨hsx, hso⟩, hsU⟩ filter_upwards [IsOpen.mem_nhds hso hsx] with _ hy using ⟨s, ⟨hy, hso⟩, hsU⟩ @[deprecated (since := "2024-02-15")] alias isGδ_setOf_continuousAt := IsGδ.setOf_continuousAt end ContinuousAt section residual variable [TopologicalSpace X] /-- A set `s` is called *residual* if it includes a countable intersection of dense open sets. -/ def residual (X : Type*) [TopologicalSpace X] : Filter X := Filter.countableGenerate { t | IsOpen t ∧ Dense t } instance countableInterFilter_residual : CountableInterFilter (residual X) := by rw [residual]; infer_instance /-- Dense open sets are residual. -/ theorem residual_of_dense_open {s : Set X} (ho : IsOpen s) (hd : Dense s) : s ∈ residual X := CountableGenerateSets.basic ⟨ho, hd⟩ /-- Dense Gδ sets are residual. -/ theorem residual_of_dense_Gδ {s : Set X} (ho : IsGδ s) (hd : Dense s) : s ∈ residual X := by rcases ho with ⟨T, To, Tct, rfl⟩ exact (countable_sInter_mem Tct).mpr fun t tT => residual_of_dense_open (To t tT) (hd.mono (sInter_subset_of_mem tT)) /-- A set is residual iff it includes a countable intersection of dense open sets. -/ theorem mem_residual_iff {s : Set X} : s ∈ residual X ↔ ∃ S : Set (Set X), (∀ t ∈ S, IsOpen t) ∧ (∀ t ∈ S, Dense t) ∧ S.Countable ∧ ⋂₀ S ⊆ s := mem_countableGenerate_iff.trans <| by simp_rw [subset_def, mem_setOf, forall_and, and_assoc] end residual section meagre open Function TopologicalSpace Set variable {X : Type*} [TopologicalSpace X] /-- A set is called **nowhere dense** iff its closure has empty interior. -/ def IsNowhereDense (s : Set X) := interior (closure s) = ∅ /-- The empty set is nowhere dense. -/ @[simp] lemma isNowhereDense_empty : IsNowhereDense (∅ : Set X) := by rw [IsNowhereDense, closure_empty, interior_empty] /-- A closed set is nowhere dense iff its interior is empty. -/ lemma IsClosed.isNowhereDense_iff {s : Set X} (hs : IsClosed s) : IsNowhereDense s ↔ interior s = ∅ := by rw [IsNowhereDense, IsClosed.closure_eq hs] /-- If a set `s` is nowhere dense, so is its closure. -/ protected lemma IsNowhereDense.closure {s : Set X} (hs : IsNowhereDense s) : IsNowhereDense (closure s) := by rwa [IsNowhereDense, closure_closure] /-- A nowhere dense set `s` is contained in a closed nowhere dense set (namely, its closure). -/ lemma IsNowhereDense.subset_of_closed_isNowhereDense {s : Set X} (hs : IsNowhereDense s) : ∃ t : Set X, s ⊆ t ∧ IsNowhereDense t ∧ IsClosed t := ⟨closure s, subset_closure, ⟨hs.closure, isClosed_closure⟩⟩ /-- A set `s` is closed and nowhere dense iff its complement `sᶜ` is open and dense. -/ lemma isClosed_isNowhereDense_iff_compl {s : Set X} : IsClosed s ∧ IsNowhereDense s ↔ IsOpen sᶜ ∧ Dense sᶜ := by rw [and_congr_right IsClosed.isNowhereDense_iff, isOpen_compl_iff, interior_eq_empty_iff_dense_compl] /-- A set is called **meagre** iff its complement is a residual (or comeagre) set. -/ def IsMeagre (s : Set X) := sᶜ ∈ residual X /-- The empty set is meagre. -/ lemma meagre_empty : IsMeagre (∅ : Set X) := by rw [IsMeagre, compl_empty] exact Filter.univ_mem /-- Subsets of meagre sets are meagre. -/ lemma IsMeagre.mono {s t : Set X} (hs : IsMeagre s) (hts : t ⊆ s) : IsMeagre t := Filter.mem_of_superset hs (compl_subset_compl.mpr hts) /-- An intersection with a meagre set is meagre. -/ lemma IsMeagre.inter {s t : Set X} (hs : IsMeagre s) : IsMeagre (s ∩ t) := hs.mono inter_subset_left /-- A countable union of meagre sets is meagre. -/ lemma isMeagre_iUnion {s : ℕ → Set X} (hs : ∀ n, IsMeagre (s n)) : IsMeagre (⋃ n, s n) := by rw [IsMeagre, compl_iUnion] exact countable_iInter_mem.mpr hs /-- A set is meagre iff it is contained in a countable union of nowhere dense sets. -/ lemma isMeagre_iff_countable_union_isNowhereDense {s : Set X} : IsMeagre s ↔ ∃ S : Set (Set X), (∀ t ∈ S, IsNowhereDense t) ∧ S.Countable ∧ s ⊆ ⋃₀ S := by rw [IsMeagre, mem_residual_iff, compl_bijective.surjective.image_surjective.exists] simp_rw [← and_assoc, ← forall_and, forall_mem_image, ← isClosed_isNowhereDense_iff_compl, sInter_image, ← compl_iUnion₂, compl_subset_compl, ← sUnion_eq_biUnion, and_assoc] refine ⟨fun ⟨S, hS, hc, hsub⟩ ↦ ⟨S, fun s hs ↦ (hS hs).2, ?_, hsub⟩, ?_⟩ · rw [← compl_compl_image S]; exact hc.image _ · intro ⟨S, hS, hc, hsub⟩ use closure '' S rw [forall_mem_image] exact ⟨fun s hs ↦ ⟨isClosed_closure, (hS s hs).closure⟩, (hc.image _).image _, hsub.trans (sUnion_mono_subsets fun s ↦ subset_closure)⟩ end meagre
Topology\Germ.lean
/- Copyright (c) 2023 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.Order.Filter.Germ.Basic import Mathlib.Topology.NhdsSet import Mathlib.Topology.LocallyConstant.Basic import Mathlib.Analysis.Normed.Module.Basic /-! # Germs of functions between topological spaces In this file, we prove basic properties of germs of functions between topological spaces, with respect to the neighbourhood filter `𝓝 x`. ## Main definitions and results * `Filter.Germ.value φ f`: value associated to the germ `φ` at a point `x`, w.r.t. the neighbourhood filter at `x`. This is the common value of all representatives of `φ` at `x`. * `Filter.Germ.valueOrderRingHom` and friends: the map `Germ (𝓝 x) E → E` is a monoid homomorphism, 𝕜-module homomorphism, ring homomorphism, monotone ring homomorphism * `RestrictGermPredicate`: given a predicate on germs `P : Π x : X, germ (𝓝 x) Y → Prop` and `A : set X`, build a new predicate on germs `restrictGermPredicate P A` such that `(∀ x, RestrictGermPredicate P A x f) ↔ ∀ᶠ x near A, P x f`; `forall_restrictRermPredicate_iff` is this equivalence. * `Filter.Germ.sliceLeft, sliceRight`: map the germ of functions `X × Y → Z` at `p = (x,y) ∈ X × Y` to the corresponding germ of functions `X → Z` at `x ∈ X` resp. `Y → Z` at `y ∈ Y`. * `eq_of_germ_isConstant`: if each germ of `f : X → Y` is constant and `X` is pre-connected, `f` is constant. -/ variable {F G : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] [NormedAddCommGroup G] [NormedSpace ℝ G] open scoped Topology open Filter Set variable {X Y Z : Type*} [TopologicalSpace X] {f g : X → Y} {A : Set X} {x : X} namespace Filter.Germ /-- The value associated to a germ at a point. This is the common value shared by all representatives at the given point. -/ def value {X α : Type*} [TopologicalSpace X] {x : X} (φ : Germ (𝓝 x) α) : α := Quotient.liftOn' φ (fun f ↦ f x) fun f g h ↦ by dsimp only; rw [Eventually.self_of_nhds h] theorem value_smul {α β : Type*} [SMul α β] (φ : Germ (𝓝 x) α) (ψ : Germ (𝓝 x) β) : (φ • ψ).value = φ.value • ψ.value := Germ.inductionOn φ fun _ ↦ Germ.inductionOn ψ fun _ ↦ rfl /-- The map `Germ (𝓝 x) E → E` into a monoid `E` as a monoid homomorphism -/ @[to_additive "The map `Germ (𝓝 x) E → E` as an additive monoid homomorphism"] def valueMulHom {X E : Type*} [Monoid E] [TopologicalSpace X] {x : X} : Germ (𝓝 x) E →* E where toFun := Filter.Germ.value map_one' := rfl map_mul' φ ψ := Germ.inductionOn φ fun _ ↦ Germ.inductionOn ψ fun _ ↦ rfl /-- The map `Germ (𝓝 x) E → E` into a `𝕜`-module `E` as a `𝕜`-linear map -/ def valueₗ {X 𝕜 E : Type*} [Semiring 𝕜] [AddCommMonoid E] [Module 𝕜 E] [TopologicalSpace X] {x : X} : Germ (𝓝 x) E →ₗ[𝕜] E where __ := Filter.Germ.valueAddHom map_smul' := fun _ φ ↦ Germ.inductionOn φ fun _ ↦ rfl /-- The map `Germ (𝓝 x) E → E` as a ring homomorphism -/ def valueRingHom {X E : Type*} [Semiring E] [TopologicalSpace X] {x : X} : Germ (𝓝 x) E →+* E := { Filter.Germ.valueMulHom, Filter.Germ.valueAddHom with } /-- The map `Germ (𝓝 x) E → E` as a monotone ring homomorphism -/ def valueOrderRingHom {X E : Type*} [OrderedSemiring E] [TopologicalSpace X] {x : X} : Germ (𝓝 x) E →+*o E where __ := Filter.Germ.valueRingHom monotone' := fun φ ψ ↦ Germ.inductionOn φ fun _ ↦ Germ.inductionOn ψ fun _ h ↦ h.self_of_nhds end Filter.Germ section RestrictGermPredicate /-- Given a predicate on germs `P : Π x : X, germ (𝓝 x) Y → Prop` and `A : set X`, build a new predicate on germs `RestrictGermPredicate P A` such that `(∀ x, RestrictGermPredicate P A x f) ↔ ∀ᶠ x near A, P x f`, see `forall_restrictGermPredicate_iff` for this equivalence. -/ def RestrictGermPredicate (P : ∀ x : X, Germ (𝓝 x) Y → Prop) (A : Set X) : ∀ x : X, Germ (𝓝 x) Y → Prop := fun x φ ↦ Germ.liftOn φ (fun f ↦ x ∈ A → ∀ᶠ y in 𝓝 x, P y f) haveI : ∀ f f' : X → Y, f =ᶠ[𝓝 x] f' → (∀ᶠ y in 𝓝 x, P y f) → ∀ᶠ y in 𝓝 x, P y f' := by intro f f' hff' hf apply (hf.and <| Eventually.eventually_nhds hff').mono rintro y ⟨hy, hy'⟩ rwa [Germ.coe_eq.mpr (EventuallyEq.symm hy')] fun f f' hff' ↦ propext <| forall_congr' fun _ ↦ ⟨this f f' hff', this f' f hff'.symm⟩ theorem Filter.Eventually.germ_congr_set {P : ∀ x : X, Germ (𝓝 x) Y → Prop} (hf : ∀ᶠ x in 𝓝ˢ A, P x f) (h : ∀ᶠ z in 𝓝ˢ A, g z = f z) : ∀ᶠ x in 𝓝ˢ A, P x g := by rw [eventually_nhdsSet_iff_forall] at * intro x hx apply ((hf x hx).and (h x hx).eventually_nhds).mono intro y hy convert hy.1 using 1 exact Germ.coe_eq.mpr hy.2 theorem restrictGermPredicate_congr {P : ∀ x : X, Germ (𝓝 x) Y → Prop} (hf : RestrictGermPredicate P A x f) (h : ∀ᶠ z in 𝓝ˢ A, g z = f z) : RestrictGermPredicate P A x g := by intro hx apply ((hf hx).and <| (eventually_nhdsSet_iff_forall.mp h x hx).eventually_nhds).mono rintro y ⟨hy, h'y⟩ rwa [Germ.coe_eq.mpr h'y] theorem forall_restrictGermPredicate_iff {P : ∀ x : X, Germ (𝓝 x) Y → Prop} : (∀ x, RestrictGermPredicate P A x f) ↔ ∀ᶠ x in 𝓝ˢ A, P x f := by rw [eventually_nhdsSet_iff_forall] rfl theorem forall_restrictGermPredicate_of_forall {P : ∀ x : X, Germ (𝓝 x) Y → Prop} (h : ∀ x, P x f) : ∀ x, RestrictGermPredicate P A x f := forall_restrictGermPredicate_iff.mpr (eventually_of_forall h) end RestrictGermPredicate namespace Filter.Germ /-- Map the germ of functions `X × Y → Z` at `p = (x,y) ∈ X × Y` to the corresponding germ of functions `X → Z` at `x ∈ X` -/ def sliceLeft [TopologicalSpace Y] {p : X × Y} (P : Germ (𝓝 p) Z) : Germ (𝓝 p.1) Z := P.compTendsto (Prod.mk · p.2) (Continuous.Prod.mk_left p.2).continuousAt @[simp] theorem sliceLeft_coe [TopologicalSpace Y] {y : Y} (f : X × Y → Z) : (↑f : Germ (𝓝 (x, y)) Z).sliceLeft = fun x' ↦ f (x', y) := rfl /-- Map the germ of functions `X × Y → Z` at `p = (x,y) ∈ X × Y` to the corresponding germ of functions `Y → Z` at `y ∈ Y` -/ def sliceRight [TopologicalSpace Y] {p : X × Y} (P : Germ (𝓝 p) Z) : Germ (𝓝 p.2) Z := P.compTendsto (Prod.mk p.1) (Continuous.Prod.mk p.1).continuousAt @[simp] theorem sliceRight_coe [TopologicalSpace Y] {y : Y} (f : X × Y → Z) : (↑f : Germ (𝓝 (x, y)) Z).sliceRight = fun y' ↦ f (x, y') := rfl lemma isConstant_comp_subtype {s : Set X} {f : X → Y} {x : s} (hf : (f : Germ (𝓝 (x : X)) Y).IsConstant) : ((f ∘ Subtype.val : s → Y) : Germ (𝓝 x) Y).IsConstant := isConstant_comp_tendsto hf continuousAt_subtype_val end Filter.Germ /-- If the germ of `f` w.r.t. each `𝓝 x` is constant, `f` is locally constant. -/ lemma IsLocallyConstant.of_germ_isConstant (h : ∀ x : X, (f : Germ (𝓝 x) Y).IsConstant) : IsLocallyConstant f := by intro s rw [isOpen_iff_mem_nhds] intro a ha obtain ⟨b, hb⟩ := h a apply mem_of_superset hb intro x hx have : f x = f a := (mem_of_mem_nhds hb) ▸ hx rw [mem_preimage, this] exact ha theorem eq_of_germ_isConstant [i : PreconnectedSpace X] (h : ∀ x : X, (f : Germ (𝓝 x) Y).IsConstant) (x x' : X) : f x = f x' := (IsLocallyConstant.of_germ_isConstant h).apply_eq_of_isPreconnected (preconnectedSpace_iff_univ.mp i) (by trivial) (by trivial) lemma eq_of_germ_isConstant_on {s : Set X} (h : ∀ x ∈ s, (f : Germ (𝓝 x) Y).IsConstant) (hs : IsPreconnected s) {x' : X} (x_in : x ∈ s) (x'_in : x' ∈ s) : f x = f x' := by let i : s → X := fun x ↦ x show (f ∘ i) (⟨x, x_in⟩ : s) = (f ∘ i) (⟨x', x'_in⟩ : s) have : PreconnectedSpace s := Subtype.preconnectedSpace hs exact eq_of_germ_isConstant (fun y ↦ Germ.isConstant_comp_subtype (h y y.2)) _ _ @[to_additive (attr := simp)] theorem Germ.coe_prod {α : Type*} (l : Filter α) (R : Type*) [CommMonoid R] {ι} (f : ι → α → R) (s : Finset ι) : ((∏ i ∈ s, f i : α → R) : Germ l R) = ∏ i ∈ s, (f i : Germ l R) := map_prod (Germ.coeMulHom l : (α → R) →* Germ l R) f s
Topology\Gluing.lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.CategoryTheory.GlueData import Mathlib.Topology.Category.TopCat.Limits.Pullbacks import Mathlib.Topology.Category.TopCat.Opens import Mathlib.Tactic.Generalize import Mathlib.CategoryTheory.Elementwise import Mathlib.CategoryTheory.ConcreteCategory.EpiMono /-! # Gluing Topological spaces Given a family of gluing data (see `Mathlib/CategoryTheory/GlueData.lean`), we can then glue them together. The construction should be "sealed" and considered as a black box, while only using the API provided. ## Main definitions * `TopCat.GlueData`: A structure containing the family of gluing data. * `CategoryTheory.GlueData.glued`: The glued topological space. This is defined as the multicoequalizer of `∐ V i j ⇉ ∐ U i`, so that the general colimit API can be used. * `CategoryTheory.GlueData.ι`: The immersion `ι i : U i ⟶ glued` for each `i : ι`. * `TopCat.GlueData.Rel`: A relation on `Σ i, D.U i` defined by `⟨i, x⟩ ~ ⟨j, y⟩` iff `⟨i, x⟩ = ⟨j, y⟩` or `t i j x = y`. See `TopCat.GlueData.ι_eq_iff_rel`. * `TopCat.GlueData.mk`: A constructor of `GlueData` whose conditions are stated in terms of elements rather than subobjects and pullbacks. * `TopCat.GlueData.ofOpenSubsets`: Given a family of open sets, we may glue them into a new topological space. This new space embeds into the original space, and is homeomorphic to it if the given family is an open cover (`TopCat.GlueData.openCoverGlueHomeo`). ## Main results * `TopCat.GlueData.isOpen_iff`: A set in `glued` is open iff its preimage along each `ι i` is open. * `TopCat.GlueData.ι_jointly_surjective`: The `ι i`s are jointly surjective. * `TopCat.GlueData.rel_equiv`: `Rel` is an equivalence relation. * `TopCat.GlueData.ι_eq_iff_rel`: `ι i x = ι j y ↔ ⟨i, x⟩ ~ ⟨j, y⟩`. * `TopCat.GlueData.image_inter`: The intersection of the images of `U i` and `U j` in `glued` is `V i j`. * `TopCat.GlueData.preimage_range`: The preimage of the image of `U i` in `U j` is `V i j`. * `TopCat.GlueData.preimage_image_eq_image`: The preimage of the image of some `U ⊆ U i` is given by XXX. * `TopCat.GlueData.ι_openEmbedding`: Each of the `ι i`s are open embeddings. -/ noncomputable section open TopologicalSpace CategoryTheory universe v u open CategoryTheory.Limits namespace TopCat /-- A family of gluing data consists of 1. An index type `J` 2. An object `U i` for each `i : J`. 3. An object `V i j` for each `i j : J`. (Note that this is `J × J → TopCat` rather than `J → J → TopCat` to connect to the limits library easier.) 4. An open embedding `f i j : V i j ⟶ U i` for each `i j : ι`. 5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `f i i` is an isomorphism. 7. `t i i` is the identity. 8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some `t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`. (This merely means that `V i j ∩ V i k ⊆ t i j ⁻¹' (V j i ∩ V j k)`.) 9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`. We can then glue the topological spaces `U i` together by identifying `V i j` with `V j i`, such that the `U i`'s are open subspaces of the glued space. Most of the times it would be easier to use the constructor `TopCat.GlueData.mk'` where the conditions are stated in a less categorical way. -/ -- porting note (#5171): removed @[nolint has_nonempty_instance] structure GlueData extends GlueData TopCat where f_open : ∀ i j, OpenEmbedding (f i j) f_mono := fun i j => (TopCat.mono_iff_injective _).mpr (f_open i j).toEmbedding.inj namespace GlueData variable (D : GlueData.{u}) local notation "𝖣" => D.toGlueData theorem π_surjective : Function.Surjective 𝖣.π := (TopCat.epi_iff_surjective 𝖣.π).mp inferInstance theorem isOpen_iff (U : Set 𝖣.glued) : IsOpen U ↔ ∀ i, IsOpen (𝖣.ι i ⁻¹' U) := by delta CategoryTheory.GlueData.ι simp_rw [← Multicoequalizer.ι_sigmaπ 𝖣.diagram] rw [← (homeoOfIso (Multicoequalizer.isoCoequalizer 𝖣.diagram).symm).isOpen_preimage] rw [coequalizer_isOpen_iff] dsimp only [GlueData.diagram_l, GlueData.diagram_left, GlueData.diagram_r, GlueData.diagram_right, parallelPair_obj_one] rw [colimit_isOpen_iff.{_,u}] -- Porting note: changed `.{u}` to `.{_,u}`. fun fact: the proof -- breaks down if this `rw` is merged with the `rw` above. constructor · intro h j; exact h ⟨j⟩ · intro h j; cases j; apply h theorem ι_jointly_surjective (x : 𝖣.glued) : ∃ (i : _) (y : D.U i), 𝖣.ι i y = x := 𝖣.ι_jointly_surjective (forget TopCat) x /-- An equivalence relation on `Σ i, D.U i` that holds iff `𝖣 .ι i x = 𝖣 .ι j y`. See `TopCat.GlueData.ι_eq_iff_rel`. -/ def Rel (a b : Σ i, ((D.U i : TopCat) : Type _)) : Prop := a = b ∨ ∃ x : D.V (a.1, b.1), D.f _ _ x = a.2 ∧ D.f _ _ (D.t _ _ x) = b.2 theorem rel_equiv : Equivalence D.Rel := ⟨fun x => Or.inl (refl x), by rintro a b (⟨⟨⟩⟩ | ⟨x, e₁, e₂⟩) exacts [Or.inl rfl, Or.inr ⟨D.t _ _ x, e₂, by erw [← e₁, D.t_inv_apply]⟩], by -- previous line now `erw` after #13170 rintro ⟨i, a⟩ ⟨j, b⟩ ⟨k, c⟩ (⟨⟨⟩⟩ | ⟨x, e₁, e₂⟩) · exact id rintro (⟨⟨⟩⟩ | ⟨y, e₃, e₄⟩) · exact Or.inr ⟨x, e₁, e₂⟩ let z := (pullbackIsoProdSubtype (D.f j i) (D.f j k)).inv ⟨⟨_, _⟩, e₂.trans e₃.symm⟩ have eq₁ : (D.t j i) ((pullback.fst _ _ : _ /-(D.f j k)-/ ⟶ D.V (j, i)) z) = x := by dsimp only [coe_of, z] erw [pullbackIsoProdSubtype_inv_fst_apply, D.t_inv_apply]-- now `erw` after #13170 have eq₂ : (pullback.snd _ _ : _ ⟶ D.V _) z = y := pullbackIsoProdSubtype_inv_snd_apply _ _ _ clear_value z right use (pullback.fst _ _ : _ ⟶ D.V (i, k)) (D.t' _ _ _ z) dsimp only at * substs eq₁ eq₂ e₁ e₃ e₄ have h₁ : D.t' j i k ≫ pullback.fst _ _ ≫ D.f i k = pullback.fst _ _ ≫ D.t j i ≫ D.f i j := by rw [← 𝖣.t_fac_assoc]; congr 1; exact pullback.condition have h₂ : D.t' j i k ≫ pullback.fst _ _ ≫ D.t i k ≫ D.f k i = pullback.snd _ _ ≫ D.t j k ≫ D.f k j := by rw [← 𝖣.t_fac_assoc] apply @Epi.left_cancellation _ _ _ _ (D.t' k j i) rw [𝖣.cocycle_assoc, 𝖣.t_fac_assoc, 𝖣.t_inv_assoc] exact pullback.condition.symm exact ⟨ContinuousMap.congr_fun h₁ z, ContinuousMap.congr_fun h₂ z⟩⟩ open CategoryTheory.Limits.WalkingParallelPair theorem eqvGen_of_π_eq -- Porting note: was `{x y : ∐ D.U} (h : 𝖣.π x = 𝖣.π y)` {x y : sigmaObj (β := D.toGlueData.J) (C := TopCat) D.toGlueData.U} (h : 𝖣.π x = 𝖣.π y) : EqvGen -- Porting note: was (Types.CoequalizerRel 𝖣.diagram.fstSigmaMap 𝖣.diagram.sndSigmaMap) (Types.CoequalizerRel (X := sigmaObj (β := D.toGlueData.diagram.L) (C := TopCat) (D.toGlueData.diagram).left) (Y := sigmaObj (β := D.toGlueData.diagram.R) (C := TopCat) (D.toGlueData.diagram).right) 𝖣.diagram.fstSigmaMap 𝖣.diagram.sndSigmaMap) x y := by delta GlueData.π Multicoequalizer.sigmaπ at h -- Porting note: inlined `inferInstance` instead of leaving as a side goal. replace h := (TopCat.mono_iff_injective (Multicoequalizer.isoCoequalizer 𝖣.diagram).inv).mp inferInstance h let diagram := parallelPair 𝖣.diagram.fstSigmaMap 𝖣.diagram.sndSigmaMap ⋙ forget _ have : colimit.ι diagram one x = colimit.ι diagram one y := by dsimp only [coequalizer.π, ContinuousMap.toFun_eq_coe] at h -- This used to be `rw`, but we need `erw` after leanprover/lean4#2644 erw [← ι_preservesColimitsIso_hom, forget_map_eq_coe, types_comp_apply, h] simp rfl have : (colimit.ι diagram _ ≫ colim.map _ ≫ (colimit.isoColimitCocone _).hom) _ = (colimit.ι diagram _ ≫ colim.map _ ≫ (colimit.isoColimitCocone _).hom) _ := (congr_arg (colim.map (diagramIsoParallelPair diagram).hom ≫ (colimit.isoColimitCocone (Types.coequalizerColimit _ _)).hom) this : _) -- Porting note: was -- simp only [eqToHom_refl, types_comp_apply, colimit.ι_map_assoc, -- diagramIsoParallelPair_hom_app, colimit.isoColimitCocone_ι_hom, types_id_apply] at this -- See https://github.com/leanprover-community/mathlib4/issues/5026 rw [colimit.ι_map_assoc, diagramIsoParallelPair_hom_app, eqToHom_refl, colimit.isoColimitCocone_ι_hom, types_comp_apply, types_id_apply, types_comp_apply, types_id_apply] at this exact Quot.eq.1 this theorem ι_eq_iff_rel (i j : D.J) (x : D.U i) (y : D.U j) : 𝖣.ι i x = 𝖣.ι j y ↔ D.Rel ⟨i, x⟩ ⟨j, y⟩ := by constructor · delta GlueData.ι simp_rw [← Multicoequalizer.ι_sigmaπ] intro h rw [← show _ = Sigma.mk i x from ConcreteCategory.congr_hom (sigmaIsoSigma.{_, u} D.U).inv_hom_id _] rw [← show _ = Sigma.mk j y from ConcreteCategory.congr_hom (sigmaIsoSigma.{_, u} D.U).inv_hom_id _] change InvImage D.Rel (sigmaIsoSigma.{_, u} D.U).hom _ _ rw [← (InvImage.equivalence _ _ D.rel_equiv).eqvGen_iff] refine EqvGen.mono ?_ (D.eqvGen_of_π_eq h : _) rintro _ _ ⟨x⟩ obtain ⟨⟨⟨i, j⟩, y⟩, rfl⟩ := (ConcreteCategory.bijective_of_isIso (sigmaIsoSigma.{u, u} _).inv).2 x unfold InvImage MultispanIndex.fstSigmaMap MultispanIndex.sndSigmaMap simp only [forget_map_eq_coe] erw [TopCat.comp_app, sigmaIsoSigma_inv_apply, ← comp_apply, ← comp_apply, colimit.ι_desc_assoc, ← comp_apply, ← comp_apply, colimit.ι_desc_assoc] -- previous line now `erw` after #13170 erw [sigmaIsoSigma_hom_ι_apply, sigmaIsoSigma_hom_ι_apply] exact Or.inr ⟨y, ⟨rfl, rfl⟩⟩ · rintro (⟨⟨⟩⟩ | ⟨z, e₁, e₂⟩) · rfl dsimp only at * -- Porting note: there were `subst e₁` and `subst e₂`, instead of the `rw` rw [← e₁, ← e₂] at * erw [D.glue_condition_apply] -- now `erw` after #13170 rfl -- now `rfl` after #13170 theorem ι_injective (i : D.J) : Function.Injective (𝖣.ι i) := by intro x y h rcases (D.ι_eq_iff_rel _ _ _ _).mp h with (⟨⟨⟩⟩ | ⟨_, e₁, e₂⟩) · rfl · dsimp only at * -- Porting note: there were `cases e₁` and `cases e₂`, instead of the `rw` rw [← e₁, ← e₂] simp instance ι_mono (i : D.J) : Mono (𝖣.ι i) := (TopCat.mono_iff_injective _).mpr (D.ι_injective _) theorem image_inter (i j : D.J) : Set.range (𝖣.ι i) ∩ Set.range (𝖣.ι j) = Set.range (D.f i j ≫ 𝖣.ι _) := by ext x constructor · rintro ⟨⟨x₁, eq₁⟩, ⟨x₂, eq₂⟩⟩ obtain ⟨⟨⟩⟩ | ⟨y, e₁, -⟩ := (D.ι_eq_iff_rel _ _ _ _).mp (eq₁.trans eq₂.symm) · exact ⟨inv (D.f i i) x₁, by -- porting note (#10745): was `simp [eq₁]` -- See https://github.com/leanprover-community/mathlib4/issues/5026 rw [TopCat.comp_app] erw [CategoryTheory.IsIso.inv_hom_id_apply] rw [eq₁]⟩ · -- Porting note: was -- dsimp only at *; substs e₁ eq₁; exact ⟨y, by simp⟩ dsimp only at * substs eq₁ exact ⟨y, by simp [e₁]⟩ · rintro ⟨x, hx⟩ refine ⟨⟨D.f i j x, hx⟩, ⟨D.f j i (D.t _ _ x), ?_⟩⟩ erw [D.glue_condition_apply] -- now `erw` after #13170 exact hx theorem preimage_range (i j : D.J) : 𝖣.ι j ⁻¹' Set.range (𝖣.ι i) = Set.range (D.f j i) := by rw [← Set.preimage_image_eq (Set.range (D.f j i)) (D.ι_injective j), ← Set.image_univ, ← Set.image_univ, ← Set.image_comp, ← coe_comp, Set.image_univ, Set.image_univ, ← image_inter, Set.preimage_range_inter] theorem preimage_image_eq_image (i j : D.J) (U : Set (𝖣.U i)) : 𝖣.ι j ⁻¹' (𝖣.ι i '' U) = D.f _ _ '' ((D.t j i ≫ D.f _ _) ⁻¹' U) := by have : D.f _ _ ⁻¹' (𝖣.ι j ⁻¹' (𝖣.ι i '' U)) = (D.t j i ≫ D.f _ _) ⁻¹' U := by ext x conv_rhs => rw [← Set.preimage_image_eq U (D.ι_injective _)] generalize 𝖣.ι i '' U = U' -- next 4 lines were `simp` before #13170 simp only [GlueData.diagram_l, GlueData.diagram_r, Set.mem_preimage, coe_comp, Function.comp_apply] erw [D.glue_condition_apply] rfl rw [← this, Set.image_preimage_eq_inter_range] symm apply Set.inter_eq_self_of_subset_left rw [← D.preimage_range i j] exact Set.preimage_mono (Set.image_subset_range _ _) theorem preimage_image_eq_image' (i j : D.J) (U : Set (𝖣.U i)) : 𝖣.ι j ⁻¹' (𝖣.ι i '' U) = (D.t i j ≫ D.f _ _) '' (D.f _ _ ⁻¹' U) := by convert D.preimage_image_eq_image i j U using 1 rw [coe_comp, coe_comp] -- Porting note: `show` was not needed, since `rw [← Set.image_image]` worked. show (fun x => ((forget TopCat).map _ ((forget TopCat).map _ x))) '' _ = _ rw [← Set.image_image] -- Porting note: `congr 1` was here, instead of `congr_arg`, however, it did nothing. refine congr_arg ?_ ?_ rw [← Set.eq_preimage_iff_image_eq, Set.preimage_preimage] · change _ = (D.t i j ≫ D.t j i ≫ _) ⁻¹' _ rw [𝖣.t_inv_assoc] rw [← isIso_iff_bijective] apply (forget TopCat).map_isIso -- Porting note: the goal was simply `IsOpen (𝖣.ι i '' U)`. -- I had to manually add the explicit type ascription. theorem open_image_open (i : D.J) (U : Opens (𝖣.U i)) : IsOpen (𝖣.ι i '' (U : Set (D.U i))) := by rw [isOpen_iff] intro j rw [preimage_image_eq_image] apply (D.f_open _ _).isOpenMap apply (D.t j i ≫ D.f i j).continuous_toFun.isOpen_preimage exact U.isOpen theorem ι_openEmbedding (i : D.J) : OpenEmbedding (𝖣.ι i) := openEmbedding_of_continuous_injective_open (𝖣.ι i).continuous_toFun (D.ι_injective i) fun U h => D.open_image_open i ⟨U, h⟩ /-- A family of gluing data consists of 1. An index type `J` 2. A bundled topological space `U i` for each `i : J`. 3. An open set `V i j ⊆ U i` for each `i j : J`. 4. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `V i i = U i`. 7. `t i i` is the identity. 8. For each `x ∈ V i j ∩ V i k`, `t i j x ∈ V j k`. 9. `t j k (t i j x) = t i k x`. We can then glue the topological spaces `U i` together by identifying `V i j` with `V j i`. -/ -- Porting note(#5171): removed `@[nolint has_nonempty_instance]` structure MkCore where {J : Type u} U : J → TopCat.{u} V : ∀ i, J → Opens (U i) t : ∀ i j, (Opens.toTopCat _).obj (V i j) ⟶ (Opens.toTopCat _).obj (V j i) V_id : ∀ i, V i i = ⊤ t_id : ∀ i, ⇑(t i i) = id t_inter : ∀ ⦃i j⦄ (k) (x : V i j), ↑x ∈ V i k → (((↑) : (V j i) → (U j)) (t i j x)) ∈ V j k cocycle : ∀ (i j k) (x : V i j) (h : ↑x ∈ V i k), -- Porting note: the underscore in the next line was `↑(t i j x)`, but Lean type-mismatched (((↑) : (V k j) → (U k)) (t j k ⟨_, t_inter k x h⟩)) = ((↑) : (V k i) → (U k)) (t i k ⟨x, h⟩) theorem MkCore.t_inv (h : MkCore) (i j : h.J) (x : h.V j i) : h.t i j ((h.t j i) x) = x := by have := h.cocycle j i j x ?_ · rw [h.t_id] at this · convert Subtype.eq this rw [h.V_id] trivial instance (h : MkCore.{u}) (i j : h.J) : IsIso (h.t i j) := by use h.t j i; constructor <;> ext1; exacts [h.t_inv _ _ _, h.t_inv _ _ _] /-- (Implementation) the restricted transition map to be fed into `TopCat.GlueData`. -/ def MkCore.t' (h : MkCore.{u}) (i j k : h.J) : pullback (h.V i j).inclusion (h.V i k).inclusion ⟶ pullback (h.V j k).inclusion (h.V j i).inclusion := by refine (pullbackIsoProdSubtype _ _).hom ≫ ⟨?_, ?_⟩ ≫ (pullbackIsoProdSubtype _ _).inv · intro x refine ⟨⟨⟨(h.t i j x.1.1).1, ?_⟩, h.t i j x.1.1⟩, rfl⟩ rcases x with ⟨⟨⟨x, hx⟩, ⟨x', hx'⟩⟩, rfl : x = x'⟩ exact h.t_inter _ ⟨x, hx⟩ hx' -- Porting note: was `continuity`, see https://github.com/leanprover-community/mathlib4/issues/5030 have : Continuous (h.t i j) := map_continuous (self := ContinuousMap.toContinuousMapClass) _ set_option tactic.skipAssignedInstances false in exact ((Continuous.subtype_mk (by fun_prop) _).prod_mk (by fun_prop)).subtype_mk _ /-- This is a constructor of `TopCat.GlueData` whose arguments are in terms of elements and intersections rather than subobjects and pullbacks. Please refer to `TopCat.GlueData.MkCore` for details. -/ def mk' (h : MkCore.{u}) : TopCat.GlueData where J := h.J U := h.U V i := (Opens.toTopCat _).obj (h.V i.1 i.2) f i j := (h.V i j).inclusion f_id i := by -- Porting note (#12129): additional beta reduction needed beta_reduce exact (h.V_id i).symm ▸ (Opens.inclusionTopIso (h.U i)).isIso_hom f_open := fun i j : h.J => (h.V i j).openEmbedding t := h.t t_id i := by ext; erw [h.t_id]; rfl -- now `erw` after #13170 t' := h.t' t_fac i j k := by delta MkCore.t' rw [Category.assoc, Category.assoc, pullbackIsoProdSubtype_inv_snd, ← Iso.eq_inv_comp, pullbackIsoProdSubtype_inv_fst_assoc] ext ⟨⟨⟨x, hx⟩, ⟨x', hx'⟩⟩, rfl : x = x'⟩ rfl cocycle i j k := by delta MkCore.t' simp_rw [← Category.assoc] rw [Iso.comp_inv_eq] simp only [Iso.inv_hom_id_assoc, Category.assoc, Category.id_comp] rw [← Iso.eq_inv_comp, Iso.inv_hom_id] ext1 ⟨⟨⟨x, hx⟩, ⟨x', hx'⟩⟩, rfl : x = x'⟩ -- The next 9 tactics (up to `convert ...` were a single `rw` before leanprover/lean4#2644 -- rw [comp_app, ContinuousMap.coe_mk, comp_app, id_app, ContinuousMap.coe_mk, Subtype.mk_eq_mk, -- Prod.mk.inj_iff, Subtype.mk_eq_mk, Subtype.ext_iff, and_self_iff] erw [comp_app] --, comp_app, id_app] -- now `erw` after #13170 -- erw [ContinuousMap.coe_mk] conv_lhs => erw [ContinuousMap.coe_mk] erw [id_app] rw [ContinuousMap.coe_mk] erw [Subtype.mk_eq_mk] rw [Prod.mk.inj_iff] erw [Subtype.mk_eq_mk] rw [Subtype.ext_iff] rw [and_self_iff] convert congr_arg Subtype.val (h.t_inv k i ⟨x, hx'⟩) using 3 refine Subtype.ext ?_ exact h.cocycle i j k ⟨x, hx⟩ hx' -- Porting note: was not necessary in mathlib3 f_mono i j := (TopCat.mono_iff_injective _).mpr fun x y h => Subtype.ext h variable {α : Type u} [TopologicalSpace α] {J : Type u} (U : J → Opens α) /-- We may construct a glue data from a family of open sets. -/ @[simps! toGlueData_J toGlueData_U toGlueData_V toGlueData_t toGlueData_f] def ofOpenSubsets : TopCat.GlueData.{u} := mk'.{u} { J U := fun i => (Opens.toTopCat <| TopCat.of α).obj (U i) V := fun i j => (Opens.map <| Opens.inclusion _).obj (U j) t := fun i j => ⟨fun x => ⟨⟨x.1.1, x.2⟩, x.1.2⟩, by -- Porting note: was `continuity`, see https://github.com/leanprover-community/mathlib4/issues/5030 refine Continuous.subtype_mk ?_ ?_ refine Continuous.subtype_mk ?_ ?_ continuity⟩ V_id := fun i => by ext -- Porting note: no longer needed `cases U i`! simp t_id := fun i => by ext; rfl t_inter := fun i j k x hx => hx cocycle := fun i j k x h => rfl } /-- The canonical map from the glue of a family of open subsets `α` into `α`. This map is an open embedding (`fromOpenSubsetsGlue_openEmbedding`), and its range is `⋃ i, (U i : Set α)` (`range_fromOpenSubsetsGlue`). -/ def fromOpenSubsetsGlue : (ofOpenSubsets U).toGlueData.glued ⟶ TopCat.of α := Multicoequalizer.desc _ _ (fun x => Opens.inclusion _) (by rintro ⟨i, j⟩; ext x; rfl) -- Porting note: `elementwise` here produces a bad lemma, -- where too much has been simplified, despite the `nosimp`. @[simp, elementwise nosimp] theorem ι_fromOpenSubsetsGlue (i : J) : (ofOpenSubsets U).toGlueData.ι i ≫ fromOpenSubsetsGlue U = Opens.inclusion _ := Multicoequalizer.π_desc _ _ _ _ _ theorem fromOpenSubsetsGlue_injective : Function.Injective (fromOpenSubsetsGlue U) := by intro x y e obtain ⟨i, ⟨x, hx⟩, rfl⟩ := (ofOpenSubsets U).ι_jointly_surjective x obtain ⟨j, ⟨y, hy⟩, rfl⟩ := (ofOpenSubsets U).ι_jointly_surjective y -- Porting note: now it is `erw`, it was `rw` -- see the porting note on `ι_fromOpenSubsetsGlue` erw [ι_fromOpenSubsetsGlue_apply, ι_fromOpenSubsetsGlue_apply] at e change x = y at e subst e rw [(ofOpenSubsets U).ι_eq_iff_rel] right exact ⟨⟨⟨x, hx⟩, hy⟩, rfl, rfl⟩ theorem fromOpenSubsetsGlue_isOpenMap : IsOpenMap (fromOpenSubsetsGlue U) := by intro s hs rw [(ofOpenSubsets U).isOpen_iff] at hs rw [isOpen_iff_forall_mem_open] rintro _ ⟨x, hx, rfl⟩ obtain ⟨i, ⟨x, hx'⟩, rfl⟩ := (ofOpenSubsets U).ι_jointly_surjective x use fromOpenSubsetsGlue U '' s ∩ Set.range (@Opens.inclusion (TopCat.of α) (U i)) use Set.inter_subset_left constructor · erw [← Set.image_preimage_eq_inter_range] apply (Opens.openEmbedding (X := TopCat.of α) (U i)).isOpenMap convert hs i using 1 erw [← ι_fromOpenSubsetsGlue, coe_comp, Set.preimage_comp] -- porting note: `congr 1` did nothing, so I replaced it with `apply congr_arg` apply congr_arg exact Set.preimage_image_eq _ (fromOpenSubsetsGlue_injective U) · refine ⟨Set.mem_image_of_mem _ hx, ?_⟩ -- Porting note: another `rw ↦ erw` -- See above. erw [ι_fromOpenSubsetsGlue_apply] exact Set.mem_range_self _ theorem fromOpenSubsetsGlue_openEmbedding : OpenEmbedding (fromOpenSubsetsGlue U) := openEmbedding_of_continuous_injective_open (ContinuousMap.continuous_toFun _) (fromOpenSubsetsGlue_injective U) (fromOpenSubsetsGlue_isOpenMap U) theorem range_fromOpenSubsetsGlue : Set.range (fromOpenSubsetsGlue U) = ⋃ i, (U i : Set α) := by ext constructor · rintro ⟨x, rfl⟩ obtain ⟨i, ⟨x, hx'⟩, rfl⟩ := (ofOpenSubsets U).ι_jointly_surjective x -- Porting note: another `rw ↦ erw` -- See above erw [ι_fromOpenSubsetsGlue_apply] exact Set.subset_iUnion _ i hx' · rintro ⟨_, ⟨i, rfl⟩, hx⟩ rename_i x exact ⟨(ofOpenSubsets U).toGlueData.ι i ⟨x, hx⟩, ι_fromOpenSubsetsGlue_apply _ _ _⟩ /-- The gluing of an open cover is homeomomorphic to the original space. -/ def openCoverGlueHomeo (h : ⋃ i, (U i : Set α) = Set.univ) : (ofOpenSubsets U).toGlueData.glued ≃ₜ α := Homeomorph.homeomorphOfContinuousOpen (Equiv.ofBijective (fromOpenSubsetsGlue U) ⟨fromOpenSubsetsGlue_injective U, Set.range_iff_surjective.mp ((range_fromOpenSubsetsGlue U).symm ▸ h)⟩) (fromOpenSubsetsGlue U).2 (fromOpenSubsetsGlue_isOpenMap U) end GlueData end TopCat
Topology\Homeomorph.lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton -/ import Mathlib.Logic.Equiv.Fin import Mathlib.Topology.DenseEmbedding import Mathlib.Topology.Support import Mathlib.Topology.Connected.LocallyConnected /-! # Homeomorphisms This file defines homeomorphisms between two topological spaces. They are bijections with both directions continuous. We denote homeomorphisms with the notation `≃ₜ`. # Main definitions * `Homeomorph X Y`: The type of homeomorphisms from `X` to `Y`. This type can be denoted using the following notation: `X ≃ₜ Y`. # Main results * Pretty much every topological property is preserved under homeomorphisms. * `Homeomorph.homeomorphOfContinuousOpen`: A continuous bijection that is an open map is a homeomorphism. -/ open Set Filter open Topology variable {X : Type*} {Y : Type*} {Z : Type*} -- not all spaces are homeomorphic to each other /-- Homeomorphism between `X` and `Y`, also called topological isomorphism -/ structure Homeomorph (X : Type*) (Y : Type*) [TopologicalSpace X] [TopologicalSpace Y] extends X ≃ Y where /-- The forward map of a homeomorphism is a continuous function. -/ continuous_toFun : Continuous toFun := by continuity /-- The inverse map of a homeomorphism is a continuous function. -/ continuous_invFun : Continuous invFun := by continuity @[inherit_doc] infixl:25 " ≃ₜ " => Homeomorph namespace Homeomorph variable [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] {X' Y' : Type*} [TopologicalSpace X'] [TopologicalSpace Y'] theorem toEquiv_injective : Function.Injective (toEquiv : X ≃ₜ Y → X ≃ Y) | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl instance : EquivLike (X ≃ₜ Y) X Y where coe := fun h => h.toEquiv inv := fun h => h.toEquiv.symm left_inv := fun h => h.left_inv right_inv := fun h => h.right_inv coe_injective' := fun _ _ H _ => toEquiv_injective <| DFunLike.ext' H instance : CoeFun (X ≃ₜ Y) fun _ ↦ X → Y := ⟨DFunLike.coe⟩ @[simp] theorem homeomorph_mk_coe (a : X ≃ Y) (b c) : (Homeomorph.mk a b c : X → Y) = a := rfl /-- The unique homeomorphism between two empty types. -/ protected def empty [IsEmpty X] [IsEmpty Y] : X ≃ₜ Y where __ := Equiv.equivOfIsEmpty X Y /-- Inverse of a homeomorphism. -/ @[symm] protected def symm (h : X ≃ₜ Y) : Y ≃ₜ X where continuous_toFun := h.continuous_invFun continuous_invFun := h.continuous_toFun toEquiv := h.toEquiv.symm @[simp] theorem symm_symm (h : X ≃ₜ Y) : h.symm.symm = h := rfl theorem symm_bijective : Function.Bijective (Homeomorph.symm : (X ≃ₜ Y) → Y ≃ₜ X) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ /-- See Note [custom simps projection] -/ def Simps.symm_apply (h : X ≃ₜ Y) : Y → X := h.symm initialize_simps_projections Homeomorph (toFun → apply, invFun → symm_apply) @[simp] theorem coe_toEquiv (h : X ≃ₜ Y) : ⇑h.toEquiv = h := rfl @[simp] theorem coe_symm_toEquiv (h : X ≃ₜ Y) : ⇑h.toEquiv.symm = h.symm := rfl @[ext] theorem ext {h h' : X ≃ₜ Y} (H : ∀ x, h x = h' x) : h = h' := DFunLike.ext _ _ H /-- Identity map as a homeomorphism. -/ @[simps! (config := .asFn) apply] protected def refl (X : Type*) [TopologicalSpace X] : X ≃ₜ X where continuous_toFun := continuous_id continuous_invFun := continuous_id toEquiv := Equiv.refl X /-- Composition of two homeomorphisms. -/ @[trans] protected def trans (h₁ : X ≃ₜ Y) (h₂ : Y ≃ₜ Z) : X ≃ₜ Z where continuous_toFun := h₂.continuous_toFun.comp h₁.continuous_toFun continuous_invFun := h₁.continuous_invFun.comp h₂.continuous_invFun toEquiv := Equiv.trans h₁.toEquiv h₂.toEquiv @[simp] theorem trans_apply (h₁ : X ≃ₜ Y) (h₂ : Y ≃ₜ Z) (x : X) : h₁.trans h₂ x = h₂ (h₁ x) := rfl @[simp] theorem symm_trans_apply (f : X ≃ₜ Y) (g : Y ≃ₜ Z) (z : Z) : (f.trans g).symm z = f.symm (g.symm z) := rfl @[simp] theorem homeomorph_mk_coe_symm (a : X ≃ Y) (b c) : ((Homeomorph.mk a b c).symm : Y → X) = a.symm := rfl @[simp] theorem refl_symm : (Homeomorph.refl X).symm = Homeomorph.refl X := rfl @[continuity, fun_prop] protected theorem continuous (h : X ≃ₜ Y) : Continuous h := h.continuous_toFun -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm` @[continuity] protected theorem continuous_symm (h : X ≃ₜ Y) : Continuous h.symm := h.continuous_invFun @[simp] theorem apply_symm_apply (h : X ≃ₜ Y) (y : Y) : h (h.symm y) = y := h.toEquiv.apply_symm_apply y @[simp] theorem symm_apply_apply (h : X ≃ₜ Y) (x : X) : h.symm (h x) = x := h.toEquiv.symm_apply_apply x @[simp] theorem self_trans_symm (h : X ≃ₜ Y) : h.trans h.symm = Homeomorph.refl X := by ext apply symm_apply_apply @[simp] theorem symm_trans_self (h : X ≃ₜ Y) : h.symm.trans h = Homeomorph.refl Y := by ext apply apply_symm_apply protected theorem bijective (h : X ≃ₜ Y) : Function.Bijective h := h.toEquiv.bijective protected theorem injective (h : X ≃ₜ Y) : Function.Injective h := h.toEquiv.injective protected theorem surjective (h : X ≃ₜ Y) : Function.Surjective h := h.toEquiv.surjective /-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/ def changeInv (f : X ≃ₜ Y) (g : Y → X) (hg : Function.RightInverse g f) : X ≃ₜ Y := haveI : g = f.symm := (f.left_inv.eq_rightInverse hg).symm { toFun := f invFun := g left_inv := by convert f.left_inv right_inv := by convert f.right_inv using 1 continuous_toFun := f.continuous continuous_invFun := by convert f.symm.continuous } @[simp] theorem symm_comp_self (h : X ≃ₜ Y) : h.symm ∘ h = id := funext h.symm_apply_apply @[simp] theorem self_comp_symm (h : X ≃ₜ Y) : h ∘ h.symm = id := funext h.apply_symm_apply @[simp] theorem range_coe (h : X ≃ₜ Y) : range h = univ := h.surjective.range_eq theorem image_symm (h : X ≃ₜ Y) : image h.symm = preimage h := funext h.symm.toEquiv.image_eq_preimage theorem preimage_symm (h : X ≃ₜ Y) : preimage h.symm = image h := (funext h.toEquiv.image_eq_preimage).symm @[simp] theorem image_preimage (h : X ≃ₜ Y) (s : Set Y) : h '' (h ⁻¹' s) = s := h.toEquiv.image_preimage s @[simp] theorem preimage_image (h : X ≃ₜ Y) (s : Set X) : h ⁻¹' (h '' s) = s := h.toEquiv.preimage_image s lemma image_compl (h : X ≃ₜ Y) (s : Set X) : h '' (sᶜ) = (h '' s)ᶜ := h.toEquiv.image_compl s protected theorem inducing (h : X ≃ₜ Y) : Inducing h := inducing_of_inducing_compose h.continuous h.symm.continuous <| by simp only [symm_comp_self, inducing_id] theorem induced_eq (h : X ≃ₜ Y) : TopologicalSpace.induced h ‹_› = ‹_› := h.inducing.1.symm protected theorem quotientMap (h : X ≃ₜ Y) : QuotientMap h := QuotientMap.of_quotientMap_compose h.symm.continuous h.continuous <| by simp only [self_comp_symm, QuotientMap.id] theorem coinduced_eq (h : X ≃ₜ Y) : TopologicalSpace.coinduced h ‹_› = ‹_› := h.quotientMap.2.symm protected theorem embedding (h : X ≃ₜ Y) : Embedding h := ⟨h.inducing, h.injective⟩ /-- Homeomorphism given an embedding. -/ noncomputable def ofEmbedding (f : X → Y) (hf : Embedding f) : X ≃ₜ Set.range f where continuous_toFun := hf.continuous.subtype_mk _ continuous_invFun := hf.continuous_iff.2 <| by simp [continuous_subtype_val] toEquiv := Equiv.ofInjective f hf.inj protected theorem secondCountableTopology [SecondCountableTopology Y] (h : X ≃ₜ Y) : SecondCountableTopology X := h.inducing.secondCountableTopology /-- If `h : X → Y` is a homeomorphism, `h(s)` is compact iff `s` is. -/ @[simp] theorem isCompact_image {s : Set X} (h : X ≃ₜ Y) : IsCompact (h '' s) ↔ IsCompact s := h.embedding.isCompact_iff.symm /-- If `h : X → Y` is a homeomorphism, `h⁻¹(s)` is compact iff `s` is. -/ @[simp] theorem isCompact_preimage {s : Set Y} (h : X ≃ₜ Y) : IsCompact (h ⁻¹' s) ↔ IsCompact s := by rw [← image_symm]; exact h.symm.isCompact_image /-- If `h : X → Y` is a homeomorphism, `s` is σ-compact iff `h(s)` is. -/ @[simp] theorem isSigmaCompact_image {s : Set X} (h : X ≃ₜ Y) : IsSigmaCompact (h '' s) ↔ IsSigmaCompact s := h.embedding.isSigmaCompact_iff.symm /-- If `h : X → Y` is a homeomorphism, `h⁻¹(s)` is σ-compact iff `s` is. -/ @[simp] theorem isSigmaCompact_preimage {s : Set Y} (h : X ≃ₜ Y) : IsSigmaCompact (h ⁻¹' s) ↔ IsSigmaCompact s := by rw [← image_symm]; exact h.symm.isSigmaCompact_image @[simp] theorem isPreconnected_image {s : Set X} (h : X ≃ₜ Y) : IsPreconnected (h '' s) ↔ IsPreconnected s := ⟨fun hs ↦ by simpa only [image_symm, preimage_image] using hs.image _ h.symm.continuous.continuousOn, fun hs ↦ hs.image _ h.continuous.continuousOn⟩ @[simp] theorem isPreconnected_preimage {s : Set Y} (h : X ≃ₜ Y) : IsPreconnected (h ⁻¹' s) ↔ IsPreconnected s := by rw [← image_symm, isPreconnected_image] @[simp] theorem isConnected_image {s : Set X} (h : X ≃ₜ Y) : IsConnected (h '' s) ↔ IsConnected s := image_nonempty.and h.isPreconnected_image @[simp] theorem isConnected_preimage {s : Set Y} (h : X ≃ₜ Y) : IsConnected (h ⁻¹' s) ↔ IsConnected s := by rw [← image_symm, isConnected_image] theorem image_connectedComponentIn {s : Set X} (h : X ≃ₜ Y) {x : X} (hx : x ∈ s) : h '' connectedComponentIn s x = connectedComponentIn (h '' s) (h x) := by refine (h.continuous.image_connectedComponentIn_subset hx).antisymm ?_ have := h.symm.continuous.image_connectedComponentIn_subset (mem_image_of_mem h hx) rwa [image_subset_iff, h.preimage_symm, h.image_symm, h.preimage_image, h.symm_apply_apply] at this @[simp] theorem comap_cocompact (h : X ≃ₜ Y) : comap h (cocompact Y) = cocompact X := (comap_cocompact_le h.continuous).antisymm <| (hasBasis_cocompact.le_basis_iff (hasBasis_cocompact.comap h)).2 fun K hK => ⟨h ⁻¹' K, h.isCompact_preimage.2 hK, Subset.rfl⟩ @[simp] theorem map_cocompact (h : X ≃ₜ Y) : map h (cocompact X) = cocompact Y := by rw [← h.comap_cocompact, map_comap_of_surjective h.surjective] protected theorem compactSpace [CompactSpace X] (h : X ≃ₜ Y) : CompactSpace Y where isCompact_univ := h.symm.isCompact_preimage.2 isCompact_univ protected theorem t0Space [T0Space X] (h : X ≃ₜ Y) : T0Space Y := h.symm.embedding.t0Space protected theorem t1Space [T1Space X] (h : X ≃ₜ Y) : T1Space Y := h.symm.embedding.t1Space protected theorem t2Space [T2Space X] (h : X ≃ₜ Y) : T2Space Y := h.symm.embedding.t2Space protected theorem t3Space [T3Space X] (h : X ≃ₜ Y) : T3Space Y := h.symm.embedding.t3Space protected theorem denseEmbedding (h : X ≃ₜ Y) : DenseEmbedding h := { h.embedding with dense := h.surjective.denseRange } @[simp] theorem isOpen_preimage (h : X ≃ₜ Y) {s : Set Y} : IsOpen (h ⁻¹' s) ↔ IsOpen s := h.quotientMap.isOpen_preimage @[simp] theorem isOpen_image (h : X ≃ₜ Y) {s : Set X} : IsOpen (h '' s) ↔ IsOpen s := by rw [← preimage_symm, isOpen_preimage] protected theorem isOpenMap (h : X ≃ₜ Y) : IsOpenMap h := fun _ => h.isOpen_image.2 @[simp] theorem isClosed_preimage (h : X ≃ₜ Y) {s : Set Y} : IsClosed (h ⁻¹' s) ↔ IsClosed s := by simp only [← isOpen_compl_iff, ← preimage_compl, isOpen_preimage] @[simp] theorem isClosed_image (h : X ≃ₜ Y) {s : Set X} : IsClosed (h '' s) ↔ IsClosed s := by rw [← preimage_symm, isClosed_preimage] protected theorem isClosedMap (h : X ≃ₜ Y) : IsClosedMap h := fun _ => h.isClosed_image.2 protected theorem openEmbedding (h : X ≃ₜ Y) : OpenEmbedding h := openEmbedding_of_embedding_open h.embedding h.isOpenMap protected theorem closedEmbedding (h : X ≃ₜ Y) : ClosedEmbedding h := closedEmbedding_of_embedding_closed h.embedding h.isClosedMap protected theorem normalSpace [NormalSpace X] (h : X ≃ₜ Y) : NormalSpace Y := h.symm.closedEmbedding.normalSpace protected theorem t4Space [T4Space X] (h : X ≃ₜ Y) : T4Space Y := h.symm.closedEmbedding.t4Space theorem preimage_closure (h : X ≃ₜ Y) (s : Set Y) : h ⁻¹' closure s = closure (h ⁻¹' s) := h.isOpenMap.preimage_closure_eq_closure_preimage h.continuous _ theorem image_closure (h : X ≃ₜ Y) (s : Set X) : h '' closure s = closure (h '' s) := by rw [← preimage_symm, preimage_closure] theorem preimage_interior (h : X ≃ₜ Y) (s : Set Y) : h ⁻¹' interior s = interior (h ⁻¹' s) := h.isOpenMap.preimage_interior_eq_interior_preimage h.continuous _ theorem image_interior (h : X ≃ₜ Y) (s : Set X) : h '' interior s = interior (h '' s) := by rw [← preimage_symm, preimage_interior] theorem preimage_frontier (h : X ≃ₜ Y) (s : Set Y) : h ⁻¹' frontier s = frontier (h ⁻¹' s) := h.isOpenMap.preimage_frontier_eq_frontier_preimage h.continuous _ theorem image_frontier (h : X ≃ₜ Y) (s : Set X) : h '' frontier s = frontier (h '' s) := by rw [← preimage_symm, preimage_frontier] @[to_additive] theorem _root_.HasCompactMulSupport.comp_homeomorph {M} [One M] {f : Y → M} (hf : HasCompactMulSupport f) (φ : X ≃ₜ Y) : HasCompactMulSupport (f ∘ φ) := hf.comp_closedEmbedding φ.closedEmbedding @[simp] theorem map_nhds_eq (h : X ≃ₜ Y) (x : X) : map h (𝓝 x) = 𝓝 (h x) := h.embedding.map_nhds_of_mem _ (by simp) @[simp] theorem map_punctured_nhds_eq (h : X ≃ₜ Y) (x : X) : map h (𝓝[≠] x) = 𝓝[≠] (h x) := by convert h.embedding.map_nhdsWithin_eq ({x}ᶜ) x rw [h.image_compl, Set.image_singleton] theorem symm_map_nhds_eq (h : X ≃ₜ Y) (x : X) : map h.symm (𝓝 (h x)) = 𝓝 x := by rw [h.symm.map_nhds_eq, h.symm_apply_apply] theorem nhds_eq_comap (h : X ≃ₜ Y) (x : X) : 𝓝 x = comap h (𝓝 (h x)) := h.inducing.nhds_eq_comap x @[simp] theorem comap_nhds_eq (h : X ≃ₜ Y) (y : Y) : comap h (𝓝 y) = 𝓝 (h.symm y) := by rw [h.nhds_eq_comap, h.apply_symm_apply] /-- If the codomain of a homeomorphism is a locally connected space, then the domain is also a locally connected space. -/ theorem locallyConnectedSpace [i : LocallyConnectedSpace Y] (h : X ≃ₜ Y) : LocallyConnectedSpace X := by have : ∀ x, (𝓝 x).HasBasis (fun s ↦ IsOpen s ∧ h x ∈ s ∧ IsConnected s) (h.symm '' ·) := fun x ↦ by rw [← h.symm_map_nhds_eq] exact (i.1 _).map _ refine locallyConnectedSpace_of_connected_bases _ _ this fun _ _ hs ↦ ?_ exact hs.2.2.2.image _ h.symm.continuous.continuousOn /-- The codomain of a homeomorphism is a locally compact space if and only if the domain is a locally compact space. -/ theorem locallyCompactSpace_iff (h : X ≃ₜ Y) : LocallyCompactSpace X ↔ LocallyCompactSpace Y := by exact ⟨fun _ => h.symm.openEmbedding.locallyCompactSpace, fun _ => h.closedEmbedding.locallyCompactSpace⟩ /-- If a bijective map `e : X ≃ Y` is continuous and open, then it is a homeomorphism. -/ def homeomorphOfContinuousOpen (e : X ≃ Y) (h₁ : Continuous e) (h₂ : IsOpenMap e) : X ≃ₜ Y where continuous_toFun := h₁ continuous_invFun := by rw [continuous_def] intro s hs convert ← h₂ s hs using 1 apply e.image_eq_preimage toEquiv := e @[simp] theorem comp_continuousOn_iff (h : X ≃ₜ Y) (f : Z → X) (s : Set Z) : ContinuousOn (h ∘ f) s ↔ ContinuousOn f s := h.inducing.continuousOn_iff.symm @[simp] theorem comp_continuous_iff (h : X ≃ₜ Y) {f : Z → X} : Continuous (h ∘ f) ↔ Continuous f := h.inducing.continuous_iff.symm @[simp] theorem comp_continuous_iff' (h : X ≃ₜ Y) {f : Y → Z} : Continuous (f ∘ h) ↔ Continuous f := h.quotientMap.continuous_iff.symm theorem comp_continuousAt_iff (h : X ≃ₜ Y) (f : Z → X) (z : Z) : ContinuousAt (h ∘ f) z ↔ ContinuousAt f z := h.inducing.continuousAt_iff.symm theorem comp_continuousAt_iff' (h : X ≃ₜ Y) (f : Y → Z) (x : X) : ContinuousAt (f ∘ h) x ↔ ContinuousAt f (h x) := h.inducing.continuousAt_iff' (by simp) theorem comp_continuousWithinAt_iff (h : X ≃ₜ Y) (f : Z → X) (s : Set Z) (z : Z) : ContinuousWithinAt f s z ↔ ContinuousWithinAt (h ∘ f) s z := h.inducing.continuousWithinAt_iff @[simp] theorem comp_isOpenMap_iff (h : X ≃ₜ Y) {f : Z → X} : IsOpenMap (h ∘ f) ↔ IsOpenMap f := by refine ⟨?_, fun hf => h.isOpenMap.comp hf⟩ intro hf rw [← Function.id_comp f, ← h.symm_comp_self, Function.comp.assoc] exact h.symm.isOpenMap.comp hf @[simp] theorem comp_isOpenMap_iff' (h : X ≃ₜ Y) {f : Y → Z} : IsOpenMap (f ∘ h) ↔ IsOpenMap f := by refine ⟨?_, fun hf => hf.comp h.isOpenMap⟩ intro hf rw [← Function.comp_id f, ← h.self_comp_symm, ← Function.comp.assoc] exact hf.comp h.symm.isOpenMap /-- A homeomorphism `h : X ≃ₜ Y` lifts to a homeomorphism between subtypes corresponding to predicates `p : X → Prop` and `q : Y → Prop` so long as `p = q ∘ h`. -/ @[simps!] def subtype {p : X → Prop} {q : Y → Prop} (h : X ≃ₜ Y) (h_iff : ∀ x, p x ↔ q (h x)) : {x // p x} ≃ₜ {y // q y} where continuous_toFun := by simpa [Equiv.coe_subtypeEquiv_eq_map] using h.continuous.subtype_map _ continuous_invFun := by simpa [Equiv.coe_subtypeEquiv_eq_map] using h.symm.continuous.subtype_map _ __ := h.subtypeEquiv h_iff @[simp] lemma subtype_toEquiv {p : X → Prop} {q : Y → Prop} (h : X ≃ₜ Y) (h_iff : ∀ x, p x ↔ q (h x)) : (h.subtype h_iff).toEquiv = h.toEquiv.subtypeEquiv h_iff := rfl /-- A homeomorphism `h : X ≃ₜ Y` lifts to a homeomorphism between sets `s : Set X` and `t : Set Y` whenever `h` maps `s` onto `t`. -/ abbrev sets {s : Set X} {t : Set Y} (h : X ≃ₜ Y) (h_eq : s = h ⁻¹' t) : s ≃ₜ t := h.subtype <| Set.ext_iff.mp h_eq /-- If two sets are equal, then they are homeomorphic. -/ def setCongr {s t : Set X} (h : s = t) : s ≃ₜ t where continuous_toFun := continuous_inclusion h.subset continuous_invFun := continuous_inclusion h.symm.subset toEquiv := Equiv.setCongr h /-- Sum of two homeomorphisms. -/ def sumCongr (h₁ : X ≃ₜ X') (h₂ : Y ≃ₜ Y') : X ⊕ Y ≃ₜ X' ⊕ Y' where continuous_toFun := h₁.continuous.sum_map h₂.continuous continuous_invFun := h₁.symm.continuous.sum_map h₂.symm.continuous toEquiv := h₁.toEquiv.sumCongr h₂.toEquiv /-- Product of two homeomorphisms. -/ def prodCongr (h₁ : X ≃ₜ X') (h₂ : Y ≃ₜ Y') : X × Y ≃ₜ X' × Y' where continuous_toFun := h₁.continuous.prod_map h₂.continuous continuous_invFun := h₁.symm.continuous.prod_map h₂.symm.continuous toEquiv := h₁.toEquiv.prodCongr h₂.toEquiv @[simp] theorem prodCongr_symm (h₁ : X ≃ₜ X') (h₂ : Y ≃ₜ Y') : (h₁.prodCongr h₂).symm = h₁.symm.prodCongr h₂.symm := rfl @[simp] theorem coe_prodCongr (h₁ : X ≃ₜ X') (h₂ : Y ≃ₜ Y') : ⇑(h₁.prodCongr h₂) = Prod.map h₁ h₂ := rfl section variable (X Y Z) /-- `X × Y` is homeomorphic to `Y × X`. -/ def prodComm : X × Y ≃ₜ Y × X where continuous_toFun := continuous_snd.prod_mk continuous_fst continuous_invFun := continuous_snd.prod_mk continuous_fst toEquiv := Equiv.prodComm X Y @[simp] theorem prodComm_symm : (prodComm X Y).symm = prodComm Y X := rfl @[simp] theorem coe_prodComm : ⇑(prodComm X Y) = Prod.swap := rfl /-- `(X × Y) × Z` is homeomorphic to `X × (Y × Z)`. -/ def prodAssoc : (X × Y) × Z ≃ₜ X × Y × Z where continuous_toFun := continuous_fst.fst.prod_mk (continuous_fst.snd.prod_mk continuous_snd) continuous_invFun := (continuous_fst.prod_mk continuous_snd.fst).prod_mk continuous_snd.snd toEquiv := Equiv.prodAssoc X Y Z /-- `X × {*}` is homeomorphic to `X`. -/ @[simps! (config := .asFn) apply] def prodPUnit : X × PUnit ≃ₜ X where toEquiv := Equiv.prodPUnit X continuous_toFun := continuous_fst continuous_invFun := continuous_id.prod_mk continuous_const /-- `{*} × X` is homeomorphic to `X`. -/ def punitProd : PUnit × X ≃ₜ X := (prodComm _ _).trans (prodPUnit _) @[simp] theorem coe_punitProd : ⇑(punitProd X) = Prod.snd := rfl /-- If both `X` and `Y` have a unique element, then `X ≃ₜ Y`. -/ @[simps!] def homeomorphOfUnique [Unique X] [Unique Y] : X ≃ₜ Y := { Equiv.equivOfUnique X Y with continuous_toFun := continuous_const continuous_invFun := continuous_const } end /-- `Equiv.piCongrLeft` as a homeomorphism: this is the natural homeomorphism `Π i, Y (e i) ≃ₜ Π j, Y j` obtained from a bijection `ι ≃ ι'`. -/ @[simps! apply toEquiv] def piCongrLeft {ι ι' : Type*} {Y : ι' → Type*} [∀ j, TopologicalSpace (Y j)] (e : ι ≃ ι') : (∀ i, Y (e i)) ≃ₜ ∀ j, Y j where continuous_toFun := continuous_pi <| e.forall_congr_right.mp fun i ↦ by simpa only [Equiv.toFun_as_coe, Equiv.piCongrLeft_apply_apply] using continuous_apply i continuous_invFun := Pi.continuous_precomp' e toEquiv := Equiv.piCongrLeft _ e /-- `Equiv.piCongrRight` as a homeomorphism: this is the natural homeomorphism `Π i, Y₁ i ≃ₜ Π j, Y₂ i` obtained from homeomorphisms `Y₁ i ≃ₜ Y₂ i` for each `i`. -/ @[simps! apply toEquiv] def piCongrRight {ι : Type*} {Y₁ Y₂ : ι → Type*} [∀ i, TopologicalSpace (Y₁ i)] [∀ i, TopologicalSpace (Y₂ i)] (F : ∀ i, Y₁ i ≃ₜ Y₂ i) : (∀ i, Y₁ i) ≃ₜ ∀ i, Y₂ i where continuous_toFun := Pi.continuous_postcomp' fun i ↦ (F i).continuous continuous_invFun := Pi.continuous_postcomp' fun i ↦ (F i).symm.continuous toEquiv := Equiv.piCongrRight fun i => (F i).toEquiv @[simp] theorem piCongrRight_symm {ι : Type*} {Y₁ Y₂ : ι → Type*} [∀ i, TopologicalSpace (Y₁ i)] [∀ i, TopologicalSpace (Y₂ i)] (F : ∀ i, Y₁ i ≃ₜ Y₂ i) : (piCongrRight F).symm = piCongrRight fun i => (F i).symm := rfl /-- `Equiv.piCongr` as a homeomorphism: this is the natural homeomorphism `Π i₁, Y₁ i ≃ₜ Π i₂, Y₂ i₂` obtained from a bijection `ι₁ ≃ ι₂` and homeomorphisms `Y₁ i₁ ≃ₜ Y₂ (e i₁)` for each `i₁ : ι₁`. -/ @[simps! apply toEquiv] def piCongr {ι₁ ι₂ : Type*} {Y₁ : ι₁ → Type*} {Y₂ : ι₂ → Type*} [∀ i₁, TopologicalSpace (Y₁ i₁)] [∀ i₂, TopologicalSpace (Y₂ i₂)] (e : ι₁ ≃ ι₂) (F : ∀ i₁, Y₁ i₁ ≃ₜ Y₂ (e i₁)) : (∀ i₁, Y₁ i₁) ≃ₜ ∀ i₂, Y₂ i₂ := (Homeomorph.piCongrRight F).trans (Homeomorph.piCongrLeft e) -- Porting note (#11215): TODO: align the order of universes with `Equiv.ulift` /-- `ULift X` is homeomorphic to `X`. -/ def ulift.{u, v} {X : Type u} [TopologicalSpace X] : ULift.{v, u} X ≃ₜ X where continuous_toFun := continuous_uLift_down continuous_invFun := continuous_uLift_up toEquiv := Equiv.ulift section Distrib /-- `(X ⊕ Y) × Z` is homeomorphic to `X × Z ⊕ Y × Z`. -/ def sumProdDistrib : (X ⊕ Y) × Z ≃ₜ (X × Z) ⊕ (Y × Z) := Homeomorph.symm <| homeomorphOfContinuousOpen (Equiv.sumProdDistrib X Y Z).symm ((continuous_inl.prod_map continuous_id).sum_elim (continuous_inr.prod_map continuous_id)) <| (isOpenMap_inl.prod IsOpenMap.id).sum_elim (isOpenMap_inr.prod IsOpenMap.id) /-- `X × (Y ⊕ Z)` is homeomorphic to `X × Y ⊕ X × Z`. -/ def prodSumDistrib : X × (Y ⊕ Z) ≃ₜ (X × Y) ⊕ (X × Z) := (prodComm _ _).trans <| sumProdDistrib.trans <| sumCongr (prodComm _ _) (prodComm _ _) variable {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] /-- `(Σ i, X i) × Y` is homeomorphic to `Σ i, (X i × Y)`. -/ def sigmaProdDistrib : (Σ i, X i) × Y ≃ₜ Σ i, X i × Y := Homeomorph.symm <| homeomorphOfContinuousOpen (Equiv.sigmaProdDistrib X Y).symm (continuous_sigma fun _ => continuous_sigmaMk.fst'.prod_mk continuous_snd) (isOpenMap_sigma.2 fun _ => isOpenMap_sigmaMk.prod IsOpenMap.id) end Distrib /-- If `ι` has a unique element, then `ι → X` is homeomorphic to `X`. -/ @[simps! (config := .asFn)] def funUnique (ι X : Type*) [Unique ι] [TopologicalSpace X] : (ι → X) ≃ₜ X where toEquiv := Equiv.funUnique ι X continuous_toFun := continuous_apply _ continuous_invFun := continuous_pi fun _ => continuous_id /-- Homeomorphism between dependent functions `Π i : Fin 2, X i` and `X 0 × X 1`. -/ @[simps! (config := .asFn)] def piFinTwo.{u} (X : Fin 2 → Type u) [∀ i, TopologicalSpace (X i)] : (∀ i, X i) ≃ₜ X 0 × X 1 where toEquiv := piFinTwoEquiv X continuous_toFun := (continuous_apply 0).prod_mk (continuous_apply 1) continuous_invFun := continuous_pi <| Fin.forall_fin_two.2 ⟨continuous_fst, continuous_snd⟩ /-- Homeomorphism between `X² = Fin 2 → X` and `X × X`. -/ @[simps! (config := .asFn)] def finTwoArrow : (Fin 2 → X) ≃ₜ X × X := { piFinTwo fun _ => X with toEquiv := finTwoArrowEquiv X } /-- A subset of a topological space is homeomorphic to its image under a homeomorphism. -/ @[simps!] def image (e : X ≃ₜ Y) (s : Set X) : s ≃ₜ e '' s where -- Porting note (#11215): TODO: by continuity! continuous_toFun := e.continuous.continuousOn.restrict_mapsTo (mapsTo_image _ _) continuous_invFun := (e.symm.continuous.comp continuous_subtype_val).codRestrict _ toEquiv := e.toEquiv.image s /-- `Set.univ X` is homeomorphic to `X`. -/ @[simps! (config := .asFn)] def Set.univ (X : Type*) [TopologicalSpace X] : (univ : Set X) ≃ₜ X where toEquiv := Equiv.Set.univ X continuous_toFun := continuous_subtype_val continuous_invFun := continuous_id.subtype_mk _ /-- `s ×ˢ t` is homeomorphic to `s × t`. -/ @[simps!] def Set.prod (s : Set X) (t : Set Y) : ↥(s ×ˢ t) ≃ₜ s × t where toEquiv := Equiv.Set.prod s t continuous_toFun := (continuous_subtype_val.fst.subtype_mk _).prod_mk (continuous_subtype_val.snd.subtype_mk _) continuous_invFun := (continuous_subtype_val.fst'.prod_mk continuous_subtype_val.snd').subtype_mk _ section variable {ι : Type*} /-- The topological space `Π i, Y i` can be split as a product by separating the indices in ι depending on whether they satisfy a predicate p or not. -/ @[simps!] def piEquivPiSubtypeProd (p : ι → Prop) (Y : ι → Type*) [∀ i, TopologicalSpace (Y i)] [DecidablePred p] : (∀ i, Y i) ≃ₜ (∀ i : { x // p x }, Y i) × ∀ i : { x // ¬p x }, Y i where toEquiv := Equiv.piEquivPiSubtypeProd p Y continuous_toFun := by apply Continuous.prod_mk <;> exact continuous_pi fun j => continuous_apply j.1 continuous_invFun := continuous_pi fun j => by dsimp only [Equiv.piEquivPiSubtypeProd]; split_ifs exacts [(continuous_apply _).comp continuous_fst, (continuous_apply _).comp continuous_snd] variable [DecidableEq ι] (i : ι) /-- A product of topological spaces can be split as the binary product of one of the spaces and the product of all the remaining spaces. -/ @[simps!] def piSplitAt (Y : ι → Type*) [∀ j, TopologicalSpace (Y j)] : (∀ j, Y j) ≃ₜ Y i × ∀ j : { j // j ≠ i }, Y j where toEquiv := Equiv.piSplitAt i Y continuous_toFun := (continuous_apply i).prod_mk (continuous_pi fun j => continuous_apply j.1) continuous_invFun := continuous_pi fun j => by dsimp only [Equiv.piSplitAt] split_ifs with h · subst h exact continuous_fst · exact (continuous_apply _).comp continuous_snd variable (Y) /-- A product of copies of a topological space can be split as the binary product of one copy and the product of all the remaining copies. -/ @[simps!] def funSplitAt : (ι → Y) ≃ₜ Y × ({ j // j ≠ i } → Y) := piSplitAt i _ end end Homeomorph namespace Equiv variable {Z : Type*} [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] /-- An equiv between topological spaces respecting openness is a homeomorphism. -/ @[simps toEquiv] def toHomeomorph (e : X ≃ Y) (he : ∀ s, IsOpen (e ⁻¹' s) ↔ IsOpen s) : X ≃ₜ Y where toEquiv := e continuous_toFun := continuous_def.2 fun s ↦ (he _).2 continuous_invFun := continuous_def.2 fun s ↦ by convert (he _).1; simp @[simp] lemma coe_toHomeomorph (e : X ≃ Y) (he) : ⇑(e.toHomeomorph he) = e := rfl lemma toHomeomorph_apply (e : X ≃ Y) (he) (x : X) : e.toHomeomorph he x = e x := rfl @[simp] lemma toHomeomorph_refl : (Equiv.refl X).toHomeomorph (fun _s ↦ Iff.rfl) = Homeomorph.refl _ := rfl @[simp] lemma toHomeomorph_symm (e : X ≃ Y) (he) : (e.toHomeomorph he).symm = e.symm.toHomeomorph fun s ↦ by convert (he _).symm; simp := rfl lemma toHomeomorph_trans (e : X ≃ Y) (f : Y ≃ Z) (he hf) : (e.trans f).toHomeomorph (fun _s ↦ (he _).trans (hf _)) = (e.toHomeomorph he).trans (f.toHomeomorph hf) := rfl /-- An inducing equiv between topological spaces is a homeomorphism. -/ @[simps toEquiv] -- Porting note (#11215): TODO: was `@[simps]` def toHomeomorphOfInducing (f : X ≃ Y) (hf : Inducing f) : X ≃ₜ Y := { f with continuous_toFun := hf.continuous continuous_invFun := hf.continuous_iff.2 <| by simpa using continuous_id } end Equiv namespace Continuous variable [TopologicalSpace X] [TopologicalSpace Y] theorem continuous_symm_of_equiv_compact_to_t2 [CompactSpace X] [T2Space Y] {f : X ≃ Y} (hf : Continuous f) : Continuous f.symm := by rw [continuous_iff_isClosed] intro C hC have hC' : IsClosed (f '' C) := (hC.isCompact.image hf).isClosed rwa [Equiv.image_eq_preimage] at hC' /-- Continuous equivalences from a compact space to a T2 space are homeomorphisms. This is not true when T2 is weakened to T1 (see `Continuous.homeoOfEquivCompactToT2.t1_counterexample`). -/ @[simps toEquiv] -- Porting note: was `@[simps]` def homeoOfEquivCompactToT2 [CompactSpace X] [T2Space Y] {f : X ≃ Y} (hf : Continuous f) : X ≃ₜ Y := { f with continuous_toFun := hf continuous_invFun := hf.continuous_symm_of_equiv_compact_to_t2 } end Continuous
Topology\IndicatorConstPointwise.lean
/- Copyright (c) 2023 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import Mathlib.Topology.Separation /-! # Pointwise convergence of indicator functions In this file, we prove the equivalence of three different ways to phrase that the indicator functions of sets converge pointwise. ## Main results For `A` a set, `(Asᵢ)` an indexed collection of sets, under mild conditions, the following are equivalent: (a) the indicator functions of `Asᵢ` tend to the indicator function of `A` pointwise; (b) for every `x`, we eventually have that `x ∈ Asᵢ` holds iff `x ∈ A` holds; (c) `Tendsto As _ <| Filter.pi (pure <| · ∈ A)`. The results stating these in the case when the indicators take values in a Fréchet space are: * `tendsto_indicator_const_iff_forall_eventually` is the equivalence (a) ↔ (b); * `tendsto_indicator_const_iff_tendsto_pi_pure` is the equivalence (a) ↔ (c). -/ open Filter Topology variable {α : Type*} {A : Set α} variable {β : Type*} [Zero β] [TopologicalSpace β] variable {ι : Type*} (L : Filter ι) {As : ι → Set α} lemma tendsto_ite {β : Type*} {p : ι → Prop} [DecidablePred p] {q : Prop} [Decidable q] {a b : β} {F G : Filter β} (haG : {a}ᶜ ∈ G) (hbF : {b}ᶜ ∈ F) (haF : principal {a} ≤ F) (hbG : principal {b} ≤ G) : Tendsto (fun i ↦ if p i then a else b) L (if q then F else G) ↔ ∀ᶠ i in L, p i ↔ q := by constructor <;> intro h · by_cases hq : q · simp only [hq, ite_true] at h filter_upwards [mem_map.mp (h hbF)] with i hi simp only [Set.preimage_compl, Set.mem_compl_iff, Set.mem_preimage, Set.mem_singleton_iff, ite_eq_right_iff, not_forall, exists_prop] at hi tauto · simp only [hq, ite_false] at h filter_upwards [mem_map.mp (h haG)] with i hi simp only [Set.preimage_compl, Set.mem_compl_iff, Set.mem_preimage, Set.mem_singleton_iff, ite_eq_left_iff, not_forall, exists_prop] at hi tauto · have obs : (fun _ ↦ if q then a else b) =ᶠ[L] (fun i ↦ if p i then a else b) := by filter_upwards [h] with i hi simp only [hi] apply Tendsto.congr' obs by_cases hq : q · simp only [hq, iff_true, ite_true] apply le_trans _ haF simp only [principal_singleton, le_pure_iff, mem_map, Set.mem_singleton_iff, Set.preimage_const_of_mem, univ_mem] · simp only [hq, ite_false] apply le_trans _ hbG simp only [principal_singleton, le_pure_iff, mem_map, Set.mem_singleton_iff, Set.preimage_const_of_mem, univ_mem] lemma tendsto_indicator_const_apply_iff_eventually' (b : β) (nhd_b : {0}ᶜ ∈ 𝓝 b) (nhd_o : {b}ᶜ ∈ 𝓝 0) (x : α) : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b) x) L (𝓝 (A.indicator (fun (_ : α) ↦ b) x)) ↔ ∀ᶠ i in L, (x ∈ As i ↔ x ∈ A) := by classical have heart := @tendsto_ite ι L β (fun i ↦ x ∈ As i) _ (x ∈ A) _ b 0 (𝓝 b) (𝓝 (0 : β)) nhd_o nhd_b ?_ ?_ · convert heart by_cases hxA : x ∈ A <;> simp [hxA] · simp only [principal_singleton, le_def, mem_pure] exact fun s s_nhd ↦ mem_of_mem_nhds s_nhd · simp only [principal_singleton, le_def, mem_pure] exact fun s s_nhd ↦ mem_of_mem_nhds s_nhd lemma tendsto_indicator_const_iff_forall_eventually' (b : β) (nhd_b : {0}ᶜ ∈ 𝓝 b) (nhd_o : {b}ᶜ ∈ 𝓝 0) : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b)) L (𝓝 (A.indicator (fun (_ : α) ↦ b))) ↔ ∀ x, ∀ᶠ i in L, (x ∈ As i ↔ x ∈ A) := by simp_rw [tendsto_pi_nhds] apply forall_congr' exact tendsto_indicator_const_apply_iff_eventually' L b nhd_b nhd_o /-- The indicator functions of `Asᵢ` evaluated at `x` tend to the indicator function of `A` evaluated at `x` if and only if we eventually have the equivalence `x ∈ Asᵢ ↔ x ∈ A`. -/ @[simp] lemma tendsto_indicator_const_apply_iff_eventually [T1Space β] (b : β) [NeZero b] (x : α) : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b) x) L (𝓝 (A.indicator (fun (_ : α) ↦ b) x)) ↔ ∀ᶠ i in L, (x ∈ As i ↔ x ∈ A) := by apply tendsto_indicator_const_apply_iff_eventually' _ b · simp only [compl_singleton_mem_nhds_iff, ne_eq, NeZero.ne, not_false_eq_true] · simp only [compl_singleton_mem_nhds_iff, ne_eq, (NeZero.ne b).symm, not_false_eq_true] /-- The indicator functions of `Asᵢ` tend to the indicator function of `A` pointwise if and only if for every `x`, we eventually have the equivalence `x ∈ Asᵢ ↔ x ∈ A`. -/ @[simp] lemma tendsto_indicator_const_iff_forall_eventually [T1Space β] (b : β) [NeZero b] : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b)) L (𝓝 (A.indicator (fun (_ : α) ↦ b))) ↔ ∀ x, ∀ᶠ i in L, (x ∈ As i ↔ x ∈ A) := by apply tendsto_indicator_const_iff_forall_eventually' _ b · simp only [compl_singleton_mem_nhds_iff, ne_eq, NeZero.ne, not_false_eq_true] · simp only [compl_singleton_mem_nhds_iff, ne_eq, (NeZero.ne b).symm, not_false_eq_true] lemma tendsto_indicator_const_iff_tendsto_pi_pure' (b : β) (nhd_b : {0}ᶜ ∈ 𝓝 b) (nhd_o : {b}ᶜ ∈ 𝓝 0) : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b)) L (𝓝 (A.indicator (fun (_ : α) ↦ b))) ↔ (Tendsto As L <| Filter.pi (pure <| · ∈ A)) := by rw [tendsto_indicator_const_iff_forall_eventually' _ b nhd_b nhd_o, tendsto_pi] simp_rw [tendsto_pure] aesop lemma tendsto_indicator_const_iff_tendsto_pi_pure [T1Space β] (b : β) [NeZero b] : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b)) L (𝓝 (A.indicator (fun (_ : α) ↦ b))) ↔ (Tendsto As L <| Filter.pi (pure <| · ∈ A)) := by rw [tendsto_indicator_const_iff_forall_eventually _ b, tendsto_pi] simp_rw [tendsto_pure] aesop
Topology\Inseparable.lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang, Yury G. Kudryashov -/ import Mathlib.Tactic.TFAE import Mathlib.Topology.ContinuousOn /-! # Inseparable points in a topological space In this file we prove basic properties of the following notions defined elsewhere. * `Specializes` (notation: `x ⤳ y`) : a relation saying that `𝓝 x ≤ 𝓝 y`; * `Inseparable`: a relation saying that two points in a topological space have the same neighbourhoods; equivalently, they can't be separated by an open set; * `InseparableSetoid X`: same relation, as a `Setoid`; * `SeparationQuotient X`: the quotient of `X` by its `InseparableSetoid`. We also prove various basic properties of the relation `Inseparable`. ## Notations - `x ⤳ y`: notation for `Specializes x y`; - `x ~ᵢ y` is used as a local notation for `Inseparable x y`; - `𝓝 x` is the neighbourhoods filter `nhds x` of a point `x`, defined elsewhere. ## Tags topological space, separation setoid -/ open Set Filter Function Topology List variable {X Y Z α ι : Type*} {π : ι → Type*} [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] [∀ i, TopologicalSpace (π i)] {x y z : X} {s : Set X} {f g : X → Y} /-! ### `Specializes` relation -/ /-- A collection of equivalent definitions of `x ⤳ y`. The public API is given by `iff` lemmas below. -/ theorem specializes_TFAE (x y : X) : TFAE [x ⤳ y, pure x ≤ 𝓝 y, ∀ s : Set X , IsOpen s → y ∈ s → x ∈ s, ∀ s : Set X , IsClosed s → x ∈ s → y ∈ s, y ∈ closure ({ x } : Set X), closure ({ y } : Set X) ⊆ closure { x }, ClusterPt y (pure x)] := by tfae_have 1 → 2 · exact (pure_le_nhds _).trans tfae_have 2 → 3 · exact fun h s hso hy => h (hso.mem_nhds hy) tfae_have 3 → 4 · exact fun h s hsc hx => of_not_not fun hy => h sᶜ hsc.isOpen_compl hy hx tfae_have 4 → 5 · exact fun h => h _ isClosed_closure (subset_closure <| mem_singleton _) tfae_have 6 ↔ 5 · exact isClosed_closure.closure_subset_iff.trans singleton_subset_iff tfae_have 5 ↔ 7 · rw [mem_closure_iff_clusterPt, principal_singleton] tfae_have 5 → 1 · refine fun h => (nhds_basis_opens _).ge_iff.2 ?_ rintro s ⟨hy, ho⟩ rcases mem_closure_iff.1 h s ho hy with ⟨z, hxs, rfl : z = x⟩ exact ho.mem_nhds hxs tfae_finish theorem specializes_iff_nhds : x ⤳ y ↔ 𝓝 x ≤ 𝓝 y := Iff.rfl theorem Specializes.not_disjoint (h : x ⤳ y) : ¬Disjoint (𝓝 x) (𝓝 y) := fun hd ↦ absurd (hd.mono_right h) <| by simp [NeBot.ne'] theorem specializes_iff_pure : x ⤳ y ↔ pure x ≤ 𝓝 y := (specializes_TFAE x y).out 0 1 alias ⟨Specializes.nhds_le_nhds, _⟩ := specializes_iff_nhds alias ⟨Specializes.pure_le_nhds, _⟩ := specializes_iff_pure theorem ker_nhds_eq_specializes : (𝓝 x).ker = {y | y ⤳ x} := by ext; simp [specializes_iff_pure, le_def] theorem specializes_iff_forall_open : x ⤳ y ↔ ∀ s : Set X, IsOpen s → y ∈ s → x ∈ s := (specializes_TFAE x y).out 0 2 theorem Specializes.mem_open (h : x ⤳ y) (hs : IsOpen s) (hy : y ∈ s) : x ∈ s := specializes_iff_forall_open.1 h s hs hy theorem IsOpen.not_specializes (hs : IsOpen s) (hx : x ∉ s) (hy : y ∈ s) : ¬x ⤳ y := fun h => hx <| h.mem_open hs hy theorem specializes_iff_forall_closed : x ⤳ y ↔ ∀ s : Set X, IsClosed s → x ∈ s → y ∈ s := (specializes_TFAE x y).out 0 3 theorem Specializes.mem_closed (h : x ⤳ y) (hs : IsClosed s) (hx : x ∈ s) : y ∈ s := specializes_iff_forall_closed.1 h s hs hx theorem IsClosed.not_specializes (hs : IsClosed s) (hx : x ∈ s) (hy : y ∉ s) : ¬x ⤳ y := fun h => hy <| h.mem_closed hs hx theorem specializes_iff_mem_closure : x ⤳ y ↔ y ∈ closure ({x} : Set X) := (specializes_TFAE x y).out 0 4 alias ⟨Specializes.mem_closure, _⟩ := specializes_iff_mem_closure theorem specializes_iff_closure_subset : x ⤳ y ↔ closure ({y} : Set X) ⊆ closure {x} := (specializes_TFAE x y).out 0 5 alias ⟨Specializes.closure_subset, _⟩ := specializes_iff_closure_subset theorem specializes_iff_clusterPt : x ⤳ y ↔ ClusterPt y (pure x) := (specializes_TFAE x y).out 0 6 theorem Filter.HasBasis.specializes_iff {ι} {p : ι → Prop} {s : ι → Set X} (h : (𝓝 y).HasBasis p s) : x ⤳ y ↔ ∀ i, p i → x ∈ s i := specializes_iff_pure.trans h.ge_iff theorem specializes_rfl : x ⤳ x := le_rfl @[refl] theorem specializes_refl (x : X) : x ⤳ x := specializes_rfl @[trans] theorem Specializes.trans : x ⤳ y → y ⤳ z → x ⤳ z := le_trans theorem specializes_of_eq (e : x = y) : x ⤳ y := e ▸ specializes_refl x theorem specializes_of_nhdsWithin (h₁ : 𝓝[s] x ≤ 𝓝[s] y) (h₂ : x ∈ s) : x ⤳ y := specializes_iff_pure.2 <| calc pure x ≤ 𝓝[s] x := le_inf (pure_le_nhds _) (le_principal_iff.2 h₂) _ ≤ 𝓝[s] y := h₁ _ ≤ 𝓝 y := inf_le_left theorem Specializes.map_of_continuousAt (h : x ⤳ y) (hy : ContinuousAt f y) : f x ⤳ f y := specializes_iff_pure.2 fun _s hs => mem_pure.2 <| mem_preimage.1 <| mem_of_mem_nhds <| hy.mono_left h hs theorem Specializes.map (h : x ⤳ y) (hf : Continuous f) : f x ⤳ f y := h.map_of_continuousAt hf.continuousAt theorem Inducing.specializes_iff (hf : Inducing f) : f x ⤳ f y ↔ x ⤳ y := by simp only [specializes_iff_mem_closure, hf.closure_eq_preimage_closure_image, image_singleton, mem_preimage] theorem subtype_specializes_iff {p : X → Prop} (x y : Subtype p) : x ⤳ y ↔ (x : X) ⤳ y := inducing_subtype_val.specializes_iff.symm @[simp] theorem specializes_prod {x₁ x₂ : X} {y₁ y₂ : Y} : (x₁, y₁) ⤳ (x₂, y₂) ↔ x₁ ⤳ x₂ ∧ y₁ ⤳ y₂ := by simp only [Specializes, nhds_prod_eq, prod_le_prod] theorem Specializes.prod {x₁ x₂ : X} {y₁ y₂ : Y} (hx : x₁ ⤳ x₂) (hy : y₁ ⤳ y₂) : (x₁, y₁) ⤳ (x₂, y₂) := specializes_prod.2 ⟨hx, hy⟩ theorem Specializes.fst {a b : X × Y} (h : a ⤳ b) : a.1 ⤳ b.1 := (specializes_prod.1 h).1 theorem Specializes.snd {a b : X × Y} (h : a ⤳ b) : a.2 ⤳ b.2 := (specializes_prod.1 h).2 @[simp] theorem specializes_pi {f g : ∀ i, π i} : f ⤳ g ↔ ∀ i, f i ⤳ g i := by simp only [Specializes, nhds_pi, pi_le_pi] theorem not_specializes_iff_exists_open : ¬x ⤳ y ↔ ∃ S : Set X, IsOpen S ∧ y ∈ S ∧ x ∉ S := by rw [specializes_iff_forall_open] push_neg rfl theorem not_specializes_iff_exists_closed : ¬x ⤳ y ↔ ∃ S : Set X, IsClosed S ∧ x ∈ S ∧ y ∉ S := by rw [specializes_iff_forall_closed] push_neg rfl theorem IsOpen.continuous_piecewise_of_specializes [DecidablePred (· ∈ s)] (hs : IsOpen s) (hf : Continuous f) (hg : Continuous g) (hspec : ∀ x, f x ⤳ g x) : Continuous (s.piecewise f g) := by have : ∀ U, IsOpen U → g ⁻¹' U ⊆ f ⁻¹' U := fun U hU x hx ↦ (hspec x).mem_open hU hx rw [continuous_def] intro U hU rw [piecewise_preimage, ite_eq_of_subset_right _ (this U hU)] exact hU.preimage hf |>.inter hs |>.union (hU.preimage hg) theorem IsClosed.continuous_piecewise_of_specializes [DecidablePred (· ∈ s)] (hs : IsClosed s) (hf : Continuous f) (hg : Continuous g) (hspec : ∀ x, g x ⤳ f x) : Continuous (s.piecewise f g) := by simpa only [piecewise_compl] using hs.isOpen_compl.continuous_piecewise_of_specializes hg hf hspec attribute [local instance] specializationPreorder /-- A continuous function is monotone with respect to the specialization preorders on the domain and the codomain. -/ theorem Continuous.specialization_monotone (hf : Continuous f) : Monotone f := fun _ _ h => h.map hf lemma closure_singleton_eq_Iic (x : X) : closure {x} = Iic x := Set.ext fun _ ↦ specializes_iff_mem_closure.symm /-- A subset `S` of a topological space is stable under specialization if `x ∈ S → y ∈ S` for all `x ⤳ y`. -/ def StableUnderSpecialization (s : Set X) : Prop := ∀ ⦃x y⦄, x ⤳ y → x ∈ s → y ∈ s /-- A subset `S` of a topological space is stable under specialization if `x ∈ S → y ∈ S` for all `y ⤳ x`. -/ def StableUnderGeneralization (s : Set X) : Prop := ∀ ⦃x y⦄, y ⤳ x → x ∈ s → y ∈ s example {s : Set X} : StableUnderSpecialization s ↔ IsLowerSet s := Iff.rfl example {s : Set X} : StableUnderGeneralization s ↔ IsUpperSet s := Iff.rfl lemma IsClosed.stableUnderSpecialization {s : Set X} (hs : IsClosed s) : StableUnderSpecialization s := fun _ _ e ↦ e.mem_closed hs lemma IsOpen.stableUnderGeneralization {s : Set X} (hs : IsOpen s) : StableUnderGeneralization s := fun _ _ e ↦ e.mem_open hs @[simp] lemma stableUnderSpecialization_compl_iff {s : Set X} : StableUnderSpecialization sᶜ ↔ StableUnderGeneralization s := isLowerSet_compl @[simp] lemma stableUnderGeneralization_compl_iff {s : Set X} : StableUnderGeneralization sᶜ ↔ StableUnderSpecialization s := isUpperSet_compl alias ⟨_, StableUnderGeneralization.compl⟩ := stableUnderSpecialization_compl_iff alias ⟨_, StableUnderSpecialization.compl⟩ := stableUnderGeneralization_compl_iff lemma stableUnderSpecialization_univ : StableUnderSpecialization (univ : Set X) := isLowerSet_univ lemma stableUnderSpecialization_empty : StableUnderSpecialization (∅ : Set X) := isLowerSet_empty lemma stableUnderGeneralization_univ : StableUnderGeneralization (univ : Set X) := isUpperSet_univ lemma stableUnderGeneralization_empty : StableUnderGeneralization (∅ : Set X) := isUpperSet_empty lemma stableUnderSpecialization_sUnion (S : Set (Set X)) (H : ∀ s ∈ S, StableUnderSpecialization s) : StableUnderSpecialization (⋃₀ S) := isLowerSet_sUnion H lemma stableUnderSpecialization_sInter (S : Set (Set X)) (H : ∀ s ∈ S, StableUnderSpecialization s) : StableUnderSpecialization (⋂₀ S) := isLowerSet_sInter H lemma stableUnderGeneralization_sUnion (S : Set (Set X)) (H : ∀ s ∈ S, StableUnderGeneralization s) : StableUnderGeneralization (⋃₀ S) := isUpperSet_sUnion H lemma stableUnderGeneralization_sInter (S : Set (Set X)) (H : ∀ s ∈ S, StableUnderGeneralization s) : StableUnderGeneralization (⋂₀ S) := isUpperSet_sInter H lemma stableUnderSpecialization_iUnion {ι : Sort*} (S : ι → Set X) (H : ∀ i, StableUnderSpecialization (S i)) : StableUnderSpecialization (⋃ i, S i) := isLowerSet_iUnion H lemma stableUnderSpecialization_iInter {ι : Sort*} (S : ι → Set X) (H : ∀ i, StableUnderSpecialization (S i)) : StableUnderSpecialization (⋂ i, S i) := isLowerSet_iInter H lemma stableUnderGeneralization_iUnion {ι : Sort*} (S : ι → Set X) (H : ∀ i, StableUnderGeneralization (S i)) : StableUnderGeneralization (⋃ i, S i) := isUpperSet_iUnion H lemma stableUnderGeneralization_iInter {ι : Sort*} (S : ι → Set X) (H : ∀ i, StableUnderGeneralization (S i)) : StableUnderGeneralization (⋂ i, S i) := isUpperSet_iInter H lemma Union_closure_singleton_eq_iff {s : Set X} : (⋃ x ∈ s, closure {x}) = s ↔ StableUnderSpecialization s := show _ ↔ IsLowerSet s by simp only [closure_singleton_eq_Iic, ← lowerClosure_eq, coe_lowerClosure] lemma stableUnderSpecialization_iff_Union_eq {s : Set X} : StableUnderSpecialization s ↔ (⋃ x ∈ s, closure {x}) = s := Union_closure_singleton_eq_iff.symm alias ⟨StableUnderSpecialization.Union_eq, _⟩ := stableUnderSpecialization_iff_Union_eq /-- A set is stable under specialization iff it is a union of closed sets. -/ lemma stableUnderSpecialization_iff_exists_sUnion_eq {s : Set X} : StableUnderSpecialization s ↔ ∃ (S : Set (Set X)), (∀ s ∈ S, IsClosed s) ∧ ⋃₀ S = s := by refine ⟨fun H ↦ ⟨(fun x : X ↦ closure {x}) '' s, ?_, ?_⟩, fun ⟨S, hS, e⟩ ↦ e ▸ stableUnderSpecialization_sUnion S (fun x hx ↦ (hS x hx).stableUnderSpecialization)⟩ · rintro _ ⟨_, _, rfl⟩; exact isClosed_closure · conv_rhs => rw [← H.Union_eq] simp /-- A set is stable under generalization iff it is an intersection of open sets. -/ lemma stableUnderGeneralization_iff_exists_sInter_eq {s : Set X} : StableUnderGeneralization s ↔ ∃ (S : Set (Set X)), (∀ s ∈ S, IsOpen s) ∧ ⋂₀ S = s := by refine ⟨?_, fun ⟨S, hS, e⟩ ↦ e ▸ stableUnderGeneralization_sInter S (fun x hx ↦ (hS x hx).stableUnderGeneralization)⟩ rw [← stableUnderSpecialization_compl_iff, stableUnderSpecialization_iff_exists_sUnion_eq] exact fun ⟨S, h₁, h₂⟩ ↦ ⟨(·ᶜ) '' S, fun s ⟨t, ht, e⟩ ↦ e ▸ (h₁ t ht).isOpen_compl, compl_injective ((sUnion_eq_compl_sInter_compl S).symm.trans h₂)⟩ lemma StableUnderSpecialization.preimage {s : Set Y} (hs : StableUnderSpecialization s) (hf : Continuous f) : StableUnderSpecialization (f ⁻¹' s) := IsLowerSet.preimage hs hf.specialization_monotone lemma StableUnderGeneralization.preimage {s : Set Y} (hs : StableUnderGeneralization s) (hf : Continuous f) : StableUnderGeneralization (f ⁻¹' s) := IsUpperSet.preimage hs hf.specialization_monotone /-- A map `f` between topological spaces is specializing if specializations lifts along `f`, i.e. for each `f x' ⤳ y` there is some `x` with `x' ⤳ x` whose image is `y`. -/ def SpecializingMap (f : X → Y) : Prop := Relation.Fibration (flip (· ⤳ ·)) (flip (· ⤳ ·)) f /-- A map `f` between topological spaces is generalizing if generalizations lifts along `f`, i.e. for each `y ⤳ f x'` there is some `x ⤳ x'` whose image is `y`. -/ def GeneralizingMap (f : X → Y) : Prop := Relation.Fibration (· ⤳ ·) (· ⤳ ·) f lemma specializingMap_iff_closure_singleton_subset : SpecializingMap f ↔ ∀ x, closure {f x} ⊆ f '' closure {x} := by simp only [SpecializingMap, Relation.Fibration, flip, specializes_iff_mem_closure]; rfl alias ⟨SpecializingMap.closure_singleton_subset, _⟩ := specializingMap_iff_closure_singleton_subset lemma SpecializingMap.stableUnderSpecialization_image (hf : SpecializingMap f) {s : Set X} (hs : StableUnderSpecialization s) : StableUnderSpecialization (f '' s) := IsLowerSet.image_fibration hf hs alias StableUnderSpecialization.image := SpecializingMap.stableUnderSpecialization_image lemma specializingMap_iff_stableUnderSpecialization_image_singleton : SpecializingMap f ↔ ∀ x, StableUnderSpecialization (f '' closure {x}) := by simpa only [closure_singleton_eq_Iic] using Relation.fibration_iff_isLowerSet_image_Iic lemma specializingMap_iff_stableUnderSpecialization_image : SpecializingMap f ↔ ∀ s, StableUnderSpecialization s → StableUnderSpecialization (f '' s) := Relation.fibration_iff_isLowerSet_image lemma specializingMap_iff_closure_singleton (hf : Continuous f) : SpecializingMap f ↔ ∀ x, f '' closure {x} = closure {f x} := by simpa only [closure_singleton_eq_Iic] using Relation.fibration_iff_image_Iic hf.specialization_monotone lemma specializingMap_iff_isClosed_image_closure_singleton (hf : Continuous f) : SpecializingMap f ↔ ∀ x, IsClosed (f '' closure {x}) := by refine ⟨fun h x ↦ ?_, fun h ↦ specializingMap_iff_stableUnderSpecialization_image_singleton.mpr (fun x ↦ (h x).stableUnderSpecialization)⟩ rw [(specializingMap_iff_closure_singleton hf).mp h x] exact isClosed_closure lemma IsClosedMap.specializingMap (hf : IsClosedMap f) : SpecializingMap f := specializingMap_iff_stableUnderSpecialization_image_singleton.mpr $ fun _ ↦ (hf _ isClosed_closure).stableUnderSpecialization lemma Inducing.specializingMap (hf : Inducing f) (h : StableUnderSpecialization (range f)) : SpecializingMap f := by intros x y e obtain ⟨y, rfl⟩ := h e ⟨x, rfl⟩ exact ⟨_, hf.specializes_iff.mp e, rfl⟩ lemma Inducing.generalizingMap (hf : Inducing f) (h : StableUnderGeneralization (range f)) : GeneralizingMap f := by intros x y e obtain ⟨y, rfl⟩ := h e ⟨x, rfl⟩ exact ⟨_, hf.specializes_iff.mp e, rfl⟩ lemma OpenEmbedding.generalizingMap (hf : OpenEmbedding f) : GeneralizingMap f := hf.toInducing.generalizingMap hf.isOpen_range.stableUnderGeneralization lemma SpecializingMap.stableUnderSpecialization_range (h : SpecializingMap f) : StableUnderSpecialization (range f) := @image_univ _ _ f ▸ stableUnderSpecialization_univ.image h lemma GeneralizingMap.stableUnderGeneralization_image (hf : GeneralizingMap f) {s : Set X} (hs : StableUnderGeneralization s) : StableUnderGeneralization (f '' s) := IsUpperSet.image_fibration hf hs lemma GeneralizingMap_iff_stableUnderGeneralization_image : GeneralizingMap f ↔ ∀ s, StableUnderGeneralization s → StableUnderGeneralization (f '' s) := Relation.fibration_iff_isUpperSet_image alias StableUnderGeneralization.image := GeneralizingMap.stableUnderGeneralization_image lemma GeneralizingMap.stableUnderGeneralization_range (h : GeneralizingMap f) : StableUnderGeneralization (range f) := @image_univ _ _ f ▸ stableUnderGeneralization_univ.image h /-! ### `Inseparable` relation -/ local infixl:0 " ~ᵢ " => Inseparable theorem inseparable_def : (x ~ᵢ y) ↔ 𝓝 x = 𝓝 y := Iff.rfl theorem inseparable_iff_specializes_and : (x ~ᵢ y) ↔ x ⤳ y ∧ y ⤳ x := le_antisymm_iff theorem Inseparable.specializes (h : x ~ᵢ y) : x ⤳ y := h.le theorem Inseparable.specializes' (h : x ~ᵢ y) : y ⤳ x := h.ge theorem Specializes.antisymm (h₁ : x ⤳ y) (h₂ : y ⤳ x) : x ~ᵢ y := le_antisymm h₁ h₂ theorem inseparable_iff_forall_open : (x ~ᵢ y) ↔ ∀ s : Set X, IsOpen s → (x ∈ s ↔ y ∈ s) := by simp only [inseparable_iff_specializes_and, specializes_iff_forall_open, ← forall_and, ← iff_def, Iff.comm] theorem not_inseparable_iff_exists_open : ¬(x ~ᵢ y) ↔ ∃ s : Set X, IsOpen s ∧ Xor' (x ∈ s) (y ∈ s) := by simp [inseparable_iff_forall_open, ← xor_iff_not_iff] theorem inseparable_iff_forall_closed : (x ~ᵢ y) ↔ ∀ s : Set X, IsClosed s → (x ∈ s ↔ y ∈ s) := by simp only [inseparable_iff_specializes_and, specializes_iff_forall_closed, ← forall_and, ← iff_def] theorem inseparable_iff_mem_closure : (x ~ᵢ y) ↔ x ∈ closure ({y} : Set X) ∧ y ∈ closure ({x} : Set X) := inseparable_iff_specializes_and.trans <| by simp only [specializes_iff_mem_closure, and_comm] theorem inseparable_iff_closure_eq : (x ~ᵢ y) ↔ closure ({x} : Set X) = closure {y} := by simp only [inseparable_iff_specializes_and, specializes_iff_closure_subset, ← subset_antisymm_iff, eq_comm] theorem inseparable_of_nhdsWithin_eq (hx : x ∈ s) (hy : y ∈ s) (h : 𝓝[s] x = 𝓝[s] y) : x ~ᵢ y := (specializes_of_nhdsWithin h.le hx).antisymm (specializes_of_nhdsWithin h.ge hy) theorem Inducing.inseparable_iff (hf : Inducing f) : (f x ~ᵢ f y) ↔ (x ~ᵢ y) := by simp only [inseparable_iff_specializes_and, hf.specializes_iff] theorem subtype_inseparable_iff {p : X → Prop} (x y : Subtype p) : (x ~ᵢ y) ↔ ((x : X) ~ᵢ y) := inducing_subtype_val.inseparable_iff.symm @[simp] theorem inseparable_prod {x₁ x₂ : X} {y₁ y₂ : Y} : ((x₁, y₁) ~ᵢ (x₂, y₂)) ↔ (x₁ ~ᵢ x₂) ∧ (y₁ ~ᵢ y₂) := by simp only [Inseparable, nhds_prod_eq, prod_inj] theorem Inseparable.prod {x₁ x₂ : X} {y₁ y₂ : Y} (hx : x₁ ~ᵢ x₂) (hy : y₁ ~ᵢ y₂) : (x₁, y₁) ~ᵢ (x₂, y₂) := inseparable_prod.2 ⟨hx, hy⟩ @[simp] theorem inseparable_pi {f g : ∀ i, π i} : (f ~ᵢ g) ↔ ∀ i, f i ~ᵢ g i := by simp only [Inseparable, nhds_pi, funext_iff, pi_inj] namespace Inseparable @[refl] theorem refl (x : X) : x ~ᵢ x := Eq.refl (𝓝 x) theorem rfl : x ~ᵢ x := refl x theorem of_eq (e : x = y) : Inseparable x y := e ▸ refl x @[symm] nonrec theorem symm (h : x ~ᵢ y) : y ~ᵢ x := h.symm @[trans] nonrec theorem trans (h₁ : x ~ᵢ y) (h₂ : y ~ᵢ z) : x ~ᵢ z := h₁.trans h₂ theorem nhds_eq (h : x ~ᵢ y) : 𝓝 x = 𝓝 y := h theorem mem_open_iff (h : x ~ᵢ y) (hs : IsOpen s) : x ∈ s ↔ y ∈ s := inseparable_iff_forall_open.1 h s hs theorem mem_closed_iff (h : x ~ᵢ y) (hs : IsClosed s) : x ∈ s ↔ y ∈ s := inseparable_iff_forall_closed.1 h s hs theorem map_of_continuousAt (h : x ~ᵢ y) (hx : ContinuousAt f x) (hy : ContinuousAt f y) : f x ~ᵢ f y := (h.specializes.map_of_continuousAt hy).antisymm (h.specializes'.map_of_continuousAt hx) theorem map (h : x ~ᵢ y) (hf : Continuous f) : f x ~ᵢ f y := h.map_of_continuousAt hf.continuousAt hf.continuousAt end Inseparable theorem IsClosed.not_inseparable (hs : IsClosed s) (hx : x ∈ s) (hy : y ∉ s) : ¬(x ~ᵢ y) := fun h => hy <| (h.mem_closed_iff hs).1 hx theorem IsOpen.not_inseparable (hs : IsOpen s) (hx : x ∈ s) (hy : y ∉ s) : ¬(x ~ᵢ y) := fun h => hy <| (h.mem_open_iff hs).1 hx /-! ### Separation quotient In this section we define the quotient of a topological space by the `Inseparable` relation. -/ variable (X) instance : TopologicalSpace (SeparationQuotient X) := instTopologicalSpaceQuotient variable {X} variable {t : Set (SeparationQuotient X)} namespace SeparationQuotient /-- The natural map from a topological space to its separation quotient. -/ def mk : X → SeparationQuotient X := Quotient.mk'' theorem quotientMap_mk : QuotientMap (mk : X → SeparationQuotient X) := quotientMap_quot_mk @[fun_prop, continuity] theorem continuous_mk : Continuous (mk : X → SeparationQuotient X) := continuous_quot_mk @[simp] theorem mk_eq_mk : mk x = mk y ↔ (x ~ᵢ y) := Quotient.eq'' theorem surjective_mk : Surjective (mk : X → SeparationQuotient X) := surjective_quot_mk _ @[simp] theorem range_mk : range (mk : X → SeparationQuotient X) = univ := surjective_mk.range_eq instance [Nonempty X] : Nonempty (SeparationQuotient X) := Nonempty.map mk ‹_› instance [Inhabited X] : Inhabited (SeparationQuotient X) := ⟨mk default⟩ instance [Subsingleton X] : Subsingleton (SeparationQuotient X) := surjective_mk.subsingleton theorem preimage_image_mk_open (hs : IsOpen s) : mk ⁻¹' (mk '' s) = s := by refine Subset.antisymm ?_ (subset_preimage_image _ _) rintro x ⟨y, hys, hxy⟩ exact ((mk_eq_mk.1 hxy).mem_open_iff hs).1 hys theorem isOpenMap_mk : IsOpenMap (mk : X → SeparationQuotient X) := fun s hs => quotientMap_mk.isOpen_preimage.1 <| by rwa [preimage_image_mk_open hs] theorem preimage_image_mk_closed (hs : IsClosed s) : mk ⁻¹' (mk '' s) = s := by refine Subset.antisymm ?_ (subset_preimage_image _ _) rintro x ⟨y, hys, hxy⟩ exact ((mk_eq_mk.1 hxy).mem_closed_iff hs).1 hys theorem inducing_mk : Inducing (mk : X → SeparationQuotient X) := ⟨le_antisymm (continuous_iff_le_induced.1 continuous_mk) fun s hs => ⟨mk '' s, isOpenMap_mk s hs, preimage_image_mk_open hs⟩⟩ theorem isClosedMap_mk : IsClosedMap (mk : X → SeparationQuotient X) := inducing_mk.isClosedMap <| by rw [range_mk]; exact isClosed_univ @[simp] theorem comap_mk_nhds_mk : comap mk (𝓝 (mk x)) = 𝓝 x := (inducing_mk.nhds_eq_comap _).symm @[simp] theorem comap_mk_nhdsSet_image : comap mk (𝓝ˢ (mk '' s)) = 𝓝ˢ s := (inducing_mk.nhdsSet_eq_comap _).symm theorem map_mk_nhds : map mk (𝓝 x) = 𝓝 (mk x) := by rw [← comap_mk_nhds_mk, map_comap_of_surjective surjective_mk] theorem map_mk_nhdsSet : map mk (𝓝ˢ s) = 𝓝ˢ (mk '' s) := by rw [← comap_mk_nhdsSet_image, map_comap_of_surjective surjective_mk] theorem comap_mk_nhdsSet : comap mk (𝓝ˢ t) = 𝓝ˢ (mk ⁻¹' t) := by conv_lhs => rw [← image_preimage_eq t surjective_mk, comap_mk_nhdsSet_image] theorem preimage_mk_closure : mk ⁻¹' closure t = closure (mk ⁻¹' t) := isOpenMap_mk.preimage_closure_eq_closure_preimage continuous_mk t theorem preimage_mk_interior : mk ⁻¹' interior t = interior (mk ⁻¹' t) := isOpenMap_mk.preimage_interior_eq_interior_preimage continuous_mk t theorem preimage_mk_frontier : mk ⁻¹' frontier t = frontier (mk ⁻¹' t) := isOpenMap_mk.preimage_frontier_eq_frontier_preimage continuous_mk t theorem image_mk_closure : mk '' closure s = closure (mk '' s) := (image_closure_subset_closure_image continuous_mk).antisymm <| isClosedMap_mk.closure_image_subset _ theorem map_prod_map_mk_nhds (x : X) (y : Y) : map (Prod.map mk mk) (𝓝 (x, y)) = 𝓝 (mk x, mk y) := by rw [nhds_prod_eq, ← prod_map_map_eq', map_mk_nhds, map_mk_nhds, nhds_prod_eq] theorem map_mk_nhdsWithin_preimage (s : Set (SeparationQuotient X)) (x : X) : map mk (𝓝[mk ⁻¹' s] x) = 𝓝[s] mk x := by rw [nhdsWithin, ← comap_principal, Filter.push_pull, nhdsWithin, map_mk_nhds] /-- The map `(x, y) ↦ (mk x, mk y)` is a quotient map. -/ theorem quotientMap_prodMap_mk : QuotientMap (Prod.map mk mk : X × Y → _) := by have hsurj : Surjective (Prod.map mk mk : X × Y → _) := surjective_mk.prodMap surjective_mk refine quotientMap_iff.2 ⟨hsurj, fun s ↦ ?_⟩ refine ⟨fun hs ↦ hs.preimage (continuous_mk.prod_map continuous_mk), fun hs ↦ ?_⟩ refine isOpen_iff_mem_nhds.2 <| hsurj.forall.2 fun (x, y) h ↦ ?_ rw [Prod.map_mk, nhds_prod_eq, ← map_mk_nhds, ← map_mk_nhds, Filter.prod_map_map_eq', ← nhds_prod_eq, Filter.mem_map] exact hs.mem_nhds h /-- Lift a map `f : X → α` such that `Inseparable x y → f x = f y` to a map `SeparationQuotient X → α`. -/ def lift (f : X → α) (hf : ∀ x y, (x ~ᵢ y) → f x = f y) : SeparationQuotient X → α := fun x => Quotient.liftOn' x f hf @[simp] theorem lift_mk {f : X → α} (hf : ∀ x y, (x ~ᵢ y) → f x = f y) (x : X) : lift f hf (mk x) = f x := rfl @[simp] theorem lift_comp_mk {f : X → α} (hf : ∀ x y, (x ~ᵢ y) → f x = f y) : lift f hf ∘ mk = f := rfl @[simp] theorem tendsto_lift_nhds_mk {f : X → α} {hf : ∀ x y, (x ~ᵢ y) → f x = f y} {l : Filter α} : Tendsto (lift f hf) (𝓝 <| mk x) l ↔ Tendsto f (𝓝 x) l := by simp only [← map_mk_nhds, tendsto_map'_iff, lift_comp_mk] @[simp] theorem tendsto_lift_nhdsWithin_mk {f : X → α} {hf : ∀ x y, (x ~ᵢ y) → f x = f y} {s : Set (SeparationQuotient X)} {l : Filter α} : Tendsto (lift f hf) (𝓝[s] mk x) l ↔ Tendsto f (𝓝[mk ⁻¹' s] x) l := by simp only [← map_mk_nhdsWithin_preimage, tendsto_map'_iff, lift_comp_mk] @[simp] theorem continuousAt_lift {hf : ∀ x y, (x ~ᵢ y) → f x = f y} : ContinuousAt (lift f hf) (mk x) ↔ ContinuousAt f x := tendsto_lift_nhds_mk @[simp] theorem continuousWithinAt_lift {hf : ∀ x y, (x ~ᵢ y) → f x = f y} {s : Set (SeparationQuotient X)} : ContinuousWithinAt (lift f hf) s (mk x) ↔ ContinuousWithinAt f (mk ⁻¹' s) x := tendsto_lift_nhdsWithin_mk @[simp] theorem continuousOn_lift {hf : ∀ x y, (x ~ᵢ y) → f x = f y} {s : Set (SeparationQuotient X)} : ContinuousOn (lift f hf) s ↔ ContinuousOn f (mk ⁻¹' s) := by simp only [ContinuousOn, surjective_mk.forall, continuousWithinAt_lift, mem_preimage] @[simp] theorem continuous_lift {hf : ∀ x y, (x ~ᵢ y) → f x = f y} : Continuous (lift f hf) ↔ Continuous f := by simp only [continuous_iff_continuousOn_univ, continuousOn_lift, preimage_univ] /-- Lift a map `f : X → Y → α` such that `Inseparable a b → Inseparable c d → f a c = f b d` to a map `SeparationQuotient X → SeparationQuotient Y → α`. -/ def lift₂ (f : X → Y → α) (hf : ∀ a b c d, (a ~ᵢ c) → (b ~ᵢ d) → f a b = f c d) : SeparationQuotient X → SeparationQuotient Y → α := fun x y => Quotient.liftOn₂' x y f hf @[simp] theorem lift₂_mk {f : X → Y → α} (hf : ∀ a b c d, (a ~ᵢ c) → (b ~ᵢ d) → f a b = f c d) (x : X) (y : Y) : lift₂ f hf (mk x) (mk y) = f x y := rfl @[simp] theorem tendsto_lift₂_nhds {f : X → Y → α} {hf : ∀ a b c d, (a ~ᵢ c) → (b ~ᵢ d) → f a b = f c d} {x : X} {y : Y} {l : Filter α} : Tendsto (uncurry <| lift₂ f hf) (𝓝 (mk x, mk y)) l ↔ Tendsto (uncurry f) (𝓝 (x, y)) l := by rw [← map_prod_map_mk_nhds, tendsto_map'_iff] rfl @[simp] theorem tendsto_lift₂_nhdsWithin {f : X → Y → α} {hf : ∀ a b c d, (a ~ᵢ c) → (b ~ᵢ d) → f a b = f c d} {x : X} {y : Y} {s : Set (SeparationQuotient X × SeparationQuotient Y)} {l : Filter α} : Tendsto (uncurry <| lift₂ f hf) (𝓝[s] (mk x, mk y)) l ↔ Tendsto (uncurry f) (𝓝[Prod.map mk mk ⁻¹' s] (x, y)) l := by rw [nhdsWithin, ← map_prod_map_mk_nhds, ← Filter.push_pull, comap_principal] rfl @[simp] theorem continuousAt_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, (a ~ᵢ c) → (b ~ᵢ d) → f a b = f c d} {x : X} {y : Y} : ContinuousAt (uncurry <| lift₂ f hf) (mk x, mk y) ↔ ContinuousAt (uncurry f) (x, y) := tendsto_lift₂_nhds @[simp] theorem continuousWithinAt_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, (a ~ᵢ c) → (b ~ᵢ d) → f a b = f c d} {s : Set (SeparationQuotient X × SeparationQuotient Y)} {x : X} {y : Y} : ContinuousWithinAt (uncurry <| lift₂ f hf) s (mk x, mk y) ↔ ContinuousWithinAt (uncurry f) (Prod.map mk mk ⁻¹' s) (x, y) := tendsto_lift₂_nhdsWithin @[simp] theorem continuousOn_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, (a ~ᵢ c) → (b ~ᵢ d) → f a b = f c d} {s : Set (SeparationQuotient X × SeparationQuotient Y)} : ContinuousOn (uncurry <| lift₂ f hf) s ↔ ContinuousOn (uncurry f) (Prod.map mk mk ⁻¹' s) := by simp_rw [ContinuousOn, (surjective_mk.prodMap surjective_mk).forall, Prod.forall, Prod.map, continuousWithinAt_lift₂] rfl @[simp] theorem continuous_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, (a ~ᵢ c) → (b ~ᵢ d) → f a b = f c d} : Continuous (uncurry <| lift₂ f hf) ↔ Continuous (uncurry f) := by simp only [continuous_iff_continuousOn_univ, continuousOn_lift₂, preimage_univ] end SeparationQuotient theorem continuous_congr_of_inseparable (h : ∀ x, f x ~ᵢ g x) : Continuous f ↔ Continuous g := by simp_rw [SeparationQuotient.inducing_mk.continuous_iff (Y := Y)] exact continuous_congr fun x ↦ SeparationQuotient.mk_eq_mk.mpr (h x)
Topology\Irreducible.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import Mathlib.Topology.ContinuousOn import Mathlib.Order.Minimal /-! # Irreducibility in topological spaces ## Main definitions * `IrreducibleSpace`: a typeclass applying to topological spaces, stating that the space is not the union of a nontrivial pair of disjoint opens. * `IsIrreducible`: for a nonempty set in a topological space, the property that the set is an irreducible space in the subspace topology. ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible spaces are assumed to be nonempty. We formalise the predicate without that assumption as `IsPreirreducible`. In other words, the only difference is whether the empty space counts as irreducible. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open Set variable {X : Type*} {Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {s t : Set X} section Preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def IsPreirreducible (s : Set X) : Prop := ∀ u v : Set X, IsOpen u → IsOpen v → (s ∩ u).Nonempty → (s ∩ v).Nonempty → (s ∩ (u ∩ v)).Nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def IsIrreducible (s : Set X) : Prop := s.Nonempty ∧ IsPreirreducible s theorem IsIrreducible.nonempty (h : IsIrreducible s) : s.Nonempty := h.1 theorem IsIrreducible.isPreirreducible (h : IsIrreducible s) : IsPreirreducible s := h.2 theorem isPreirreducible_empty : IsPreirreducible (∅ : Set X) := fun _ _ _ _ _ ⟨_, h1, _⟩ => h1.elim theorem Set.Subsingleton.isPreirreducible (hs : s.Subsingleton) : IsPreirreducible s := fun _u _v _ _ ⟨_x, hxs, hxu⟩ ⟨y, hys, hyv⟩ => ⟨y, hys, hs hxs hys ▸ hxu, hyv⟩ theorem isPreirreducible_singleton {x} : IsPreirreducible ({x} : Set X) := subsingleton_singleton.isPreirreducible theorem isIrreducible_singleton {x} : IsIrreducible ({x} : Set X) := ⟨singleton_nonempty x, isPreirreducible_singleton⟩ theorem isPreirreducible_iff_closure : IsPreirreducible (closure s) ↔ IsPreirreducible s := forall₄_congr fun u v hu hv => by iterate 3 rw [closure_inter_open_nonempty_iff] exacts [hu.inter hv, hv, hu] theorem isIrreducible_iff_closure : IsIrreducible (closure s) ↔ IsIrreducible s := and_congr closure_nonempty_iff isPreirreducible_iff_closure protected alias ⟨_, IsPreirreducible.closure⟩ := isPreirreducible_iff_closure protected alias ⟨_, IsIrreducible.closure⟩ := isIrreducible_iff_closure theorem exists_preirreducible (s : Set X) (H : IsPreirreducible s) : ∃ t : Set X, IsPreirreducible t ∧ s ⊆ t ∧ ∀ u, IsPreirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn_subset_nonempty { t : Set X | IsPreirreducible t } (fun c hc hcc _ => ⟨⋃₀ c, fun u v hu hv ⟨y, hy, hyu⟩ ⟨x, hx, hxv⟩ => let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy let ⟨q, hqc, hxq⟩ := mem_sUnion.1 hx Or.casesOn (hcc.total hpc hqc) (fun hpq : p ⊆ q => let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨x, hxq, hxv⟩ ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) fun hqp : q ⊆ p => let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨x, hqp hxq, hxv⟩ ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩, fun _ hxc => subset_sUnion_of_mem hxc⟩) s H ⟨m, hm, hsm, fun _u hu hmu => hmm _ hu hmu⟩ /-- The set of irreducible components of a topological space. -/ def irreducibleComponents (X : Type*) [TopologicalSpace X] : Set (Set X) := {s | Maximal IsIrreducible s} theorem isClosed_of_mem_irreducibleComponents (s) (H : s ∈ irreducibleComponents X) : IsClosed s := by rw [← closure_eq_iff_isClosed, eq_comm] exact subset_closure.antisymm (H.2 H.1.closure subset_closure) theorem irreducibleComponents_eq_maximals_closed (X : Type*) [TopologicalSpace X] : irreducibleComponents X = { s | Maximal (fun x ↦ IsClosed x ∧ IsIrreducible x) s} := by ext s constructor · intro H exact ⟨⟨isClosed_of_mem_irreducibleComponents _ H, H.1⟩, fun x h e => H.2 h.2 e⟩ · intro H refine ⟨H.1.2, fun x h e => ?_⟩ have : closure x ≤ s := H.2 ⟨isClosed_closure, h.closure⟩ (e.trans subset_closure) exact le_trans subset_closure this /-- A maximal irreducible set that contains a given point. -/ def irreducibleComponent (x : X) : Set X := Classical.choose (exists_preirreducible {x} isPreirreducible_singleton) theorem irreducibleComponent_property (x : X) : IsPreirreducible (irreducibleComponent x) ∧ {x} ⊆ irreducibleComponent x ∧ ∀ u, IsPreirreducible u → irreducibleComponent x ⊆ u → u = irreducibleComponent x := Classical.choose_spec (exists_preirreducible {x} isPreirreducible_singleton) theorem mem_irreducibleComponent {x : X} : x ∈ irreducibleComponent x := singleton_subset_iff.1 (irreducibleComponent_property x).2.1 theorem isIrreducible_irreducibleComponent {x : X} : IsIrreducible (irreducibleComponent x) := ⟨⟨x, mem_irreducibleComponent⟩, (irreducibleComponent_property x).1⟩ theorem eq_irreducibleComponent {x : X} : IsPreirreducible s → irreducibleComponent x ⊆ s → s = irreducibleComponent x := (irreducibleComponent_property x).2.2 _ theorem irreducibleComponent_mem_irreducibleComponents (x : X) : irreducibleComponent x ∈ irreducibleComponents X := ⟨isIrreducible_irreducibleComponent, fun _ h₁ h₂ => (eq_irreducibleComponent h₁.2 h₂).le⟩ theorem isClosed_irreducibleComponent {x : X} : IsClosed (irreducibleComponent x) := isClosed_of_mem_irreducibleComponents _ (irreducibleComponent_mem_irreducibleComponents x) /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class PreirreducibleSpace (X : Type*) [TopologicalSpace X] : Prop where /-- In a preirreducible space, `Set.univ` is a preirreducible set. -/ isPreirreducible_univ : IsPreirreducible (univ : Set X) /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class IrreducibleSpace (X : Type*) [TopologicalSpace X] extends PreirreducibleSpace X : Prop where toNonempty : Nonempty X -- see Note [lower instance priority] attribute [instance 50] IrreducibleSpace.toNonempty theorem IrreducibleSpace.isIrreducible_univ (X : Type*) [TopologicalSpace X] [IrreducibleSpace X] : IsIrreducible (univ : Set X) := ⟨univ_nonempty, PreirreducibleSpace.isPreirreducible_univ⟩ theorem irreducibleSpace_def (X : Type*) [TopologicalSpace X] : IrreducibleSpace X ↔ IsIrreducible (⊤ : Set X) := ⟨@IrreducibleSpace.isIrreducible_univ X _, fun h => haveI : PreirreducibleSpace X := ⟨h.2⟩ ⟨⟨h.1.some⟩⟩⟩ theorem nonempty_preirreducible_inter [PreirreducibleSpace X] : IsOpen s → IsOpen t → s.Nonempty → t.Nonempty → (s ∩ t).Nonempty := by simpa only [univ_inter, univ_subset_iff] using @PreirreducibleSpace.isPreirreducible_univ X _ _ s t /-- In a (pre)irreducible space, a nonempty open set is dense. -/ protected theorem IsOpen.dense [PreirreducibleSpace X] (ho : IsOpen s) (hne : s.Nonempty) : Dense s := dense_iff_inter_open.2 fun _t hto htne => nonempty_preirreducible_inter hto ho htne hne theorem IsPreirreducible.image (H : IsPreirreducible s) (f : X → Y) (hf : ContinuousOn f s) : IsPreirreducible (f '' s) := by rintro u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩ rw [← mem_preimage] at hxu hyv rcases continuousOn_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩ rcases continuousOn_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩ have := H u' v' hu' hv' rw [inter_comm s u', ← u'_eq] at this rw [inter_comm s v', ← v'_eq] at this rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨x, hxs, hxu', hxv'⟩ refine ⟨f x, mem_image_of_mem f hxs, ?_, ?_⟩ all_goals rw [← mem_preimage] apply mem_of_mem_inter_left show x ∈ _ ∩ s simp [*] theorem IsIrreducible.image (H : IsIrreducible s) (f : X → Y) (hf : ContinuousOn f s) : IsIrreducible (f '' s) := ⟨H.nonempty.image _, H.isPreirreducible.image f hf⟩ theorem Subtype.preirreducibleSpace (h : IsPreirreducible s) : PreirreducibleSpace s where isPreirreducible_univ := by rintro _ _ ⟨u, hu, rfl⟩ ⟨v, hv, rfl⟩ ⟨⟨x, hxs⟩, -, hxu⟩ ⟨⟨y, hys⟩, -, hyv⟩ rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨x, hxs, ⟨hxu, hxv⟩⟩ exact ⟨⟨x, hxs⟩, ⟨Set.mem_univ _, ⟨hxu, hxv⟩⟩⟩ theorem Subtype.irreducibleSpace (h : IsIrreducible s) : IrreducibleSpace s where isPreirreducible_univ := (Subtype.preirreducibleSpace h.isPreirreducible).isPreirreducible_univ toNonempty := h.nonempty.to_subtype /-- An infinite type with cofinite topology is an irreducible topological space. -/ instance (priority := 100) {X} [Infinite X] : IrreducibleSpace (CofiniteTopology X) where isPreirreducible_univ u v := by haveI : Infinite (CofiniteTopology X) := ‹_› simp only [CofiniteTopology.isOpen_iff, univ_inter] intro hu hv hu' hv' simpa only [compl_union, compl_compl] using ((hu hu').union (hv hv')).infinite_compl.nonempty toNonempty := (inferInstance : Nonempty X) /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ theorem isIrreducible_iff_sInter : IsIrreducible s ↔ ∀ (U : Finset (Set X)), (∀ u ∈ U, IsOpen u) → (∀ u ∈ U, (s ∩ u).Nonempty) → (s ∩ ⋂₀ ↑U).Nonempty := by classical refine ⟨fun h U hu hU => ?_, fun h => ⟨?_, ?_⟩⟩ · induction U using Finset.induction_on with | empty => simpa using h.nonempty | @insert u U _ IH => rw [Finset.coe_insert, sInter_insert] rw [Finset.forall_mem_insert] at hu hU exact h.2 _ _ hu.1 (U.finite_toSet.isOpen_sInter hu.2) hU.1 (IH hu.2 hU.2) · simpa using h ∅ · intro u v hu hv hu' hv' simpa [*] using h {u, v} /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ theorem isPreirreducible_iff_closed_union_closed : IsPreirreducible s ↔ ∀ z₁ z₂ : Set X, IsClosed z₁ → IsClosed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := by refine compl_surjective.forall.trans <| forall_congr' fun z₁ => compl_surjective.forall.trans <| forall_congr' fun z₂ => ?_ simp only [isOpen_compl_iff, ← compl_union, inter_compl_nonempty_iff] refine forall₂_congr fun _ _ => ?_ rw [← and_imp, ← not_or, not_imp_not] /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ theorem isIrreducible_iff_sUnion_closed : IsIrreducible s ↔ ∀ t : Finset (Set X), (∀ z ∈ t, IsClosed z) → (s ⊆ ⋃₀ ↑t) → ∃ z ∈ t, s ⊆ z := by simp only [isIrreducible_iff_sInter] refine ((@compl_involutive (Set X) _).toPerm _).finsetCongr.forall_congr fun {t} => ?_ simp_rw [Equiv.finsetCongr_apply, Finset.forall_mem_map, Finset.mem_map, Finset.coe_map, sUnion_image, Equiv.coe_toEmbedding, Function.Involutive.coe_toPerm, isClosed_compl_iff, exists_exists_and_eq_and] refine forall_congr' fun _ => Iff.trans ?_ not_imp_not simp only [not_exists, not_and, ← compl_iInter₂, ← sInter_eq_biInter, subset_compl_iff_disjoint_right, not_disjoint_iff_nonempty_inter] /-- A nonempty open subset of a preirreducible subspace is dense in the subspace. -/ theorem subset_closure_inter_of_isPreirreducible_of_isOpen {S U : Set X} (hS : IsPreirreducible S) (hU : IsOpen U) (h : (S ∩ U).Nonempty) : S ⊆ closure (S ∩ U) := by by_contra h' obtain ⟨x, h₁, h₂, h₃⟩ := hS _ (closure (S ∩ U))ᶜ hU isClosed_closure.isOpen_compl h (inter_compl_nonempty_iff.mpr h') exact h₃ (subset_closure ⟨h₁, h₂⟩) /-- If `∅ ≠ U ⊆ S ⊆ t` such that `U` is open and `t` is preirreducible, then `S` is irreducible. -/ theorem IsPreirreducible.subset_irreducible {S U : Set X} (ht : IsPreirreducible t) (hU : U.Nonempty) (hU' : IsOpen U) (h₁ : U ⊆ S) (h₂ : S ⊆ t) : IsIrreducible S := by obtain ⟨z, hz⟩ := hU replace ht : IsIrreducible t := ⟨⟨z, h₂ (h₁ hz)⟩, ht⟩ refine ⟨⟨z, h₁ hz⟩, ?_⟩ rintro u v hu hv ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ classical obtain ⟨x, -, hx'⟩ : Set.Nonempty (t ∩ ⋂₀ ↑({U, u, v} : Finset (Set X))) := by refine isIrreducible_iff_sInter.mp ht {U, u, v} ?_ ?_ · simp [*] · intro U H simp only [Finset.mem_insert, Finset.mem_singleton] at H rcases H with (rfl | rfl | rfl) exacts [⟨z, h₂ (h₁ hz), hz⟩, ⟨x, h₂ hx, hx'⟩, ⟨y, h₂ hy, hy'⟩] replace hx' : x ∈ U ∧ x ∈ u ∧ x ∈ v := by simpa using hx' exact ⟨x, h₁ hx'.1, hx'.2⟩ theorem IsPreirreducible.open_subset {U : Set X} (ht : IsPreirreducible t) (hU : IsOpen U) (hU' : U ⊆ t) : IsPreirreducible U := U.eq_empty_or_nonempty.elim (fun h => h.symm ▸ isPreirreducible_empty) fun h => (ht.subset_irreducible h hU (fun _ => id) hU').2 theorem IsPreirreducible.interior (ht : IsPreirreducible t) : IsPreirreducible (interior t) := ht.open_subset isOpen_interior interior_subset theorem IsPreirreducible.preimage (ht : IsPreirreducible t) {f : Y → X} (hf : OpenEmbedding f) : IsPreirreducible (f ⁻¹' t) := by rintro U V hU hV ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ obtain ⟨_, h₁, ⟨y, h₂, rfl⟩, ⟨y', h₃, h₄⟩⟩ := ht _ _ (hf.isOpenMap _ hU) (hf.isOpenMap _ hV) ⟨f x, hx, Set.mem_image_of_mem f hx'⟩ ⟨f y, hy, Set.mem_image_of_mem f hy'⟩ cases hf.inj h₄ exact ⟨y, h₁, h₂, h₃⟩ end Preirreducible
Topology\IsLocalHomeomorph.lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import Mathlib.Topology.PartialHomeomorph import Mathlib.Topology.SeparatedMap /-! # Local homeomorphisms This file defines local homeomorphisms. ## Main definitions For a function `f : X → Y ` between topological spaces, we say * `IsLocalHomeomorphOn f s` if `f` is a local homeomorphism around each point of `s`: for each `x : X`, the restriction of `f` to some open neighborhood `U` of `x` gives a homeomorphism between `U` and an open subset of `Y`. * `IsLocalHomeomorph f`: `f` is a local homeomorphism, i.e. it's a local homeomorphism on `univ`. Note that `IsLocalHomeomorph` is a global condition. This is in contrast to `PartialHomeomorph`, which is a homeomorphism between specific open subsets. ## Main results * local homeomorphisms are locally injective open maps * more! -/ open Topology variable {X Y Z : Type*} [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] (g : Y → Z) (f : X → Y) (s : Set X) (t : Set Y) /-- A function `f : X → Y` satisfies `IsLocalHomeomorphOn f s` if each `x ∈ s` is contained in the source of some `e : PartialHomeomorph X Y` with `f = e`. -/ def IsLocalHomeomorphOn := ∀ x ∈ s, ∃ e : PartialHomeomorph X Y, x ∈ e.source ∧ f = e theorem isLocalHomeomorphOn_iff_openEmbedding_restrict {f : X → Y} : IsLocalHomeomorphOn f s ↔ ∀ x ∈ s, ∃ U ∈ 𝓝 x, OpenEmbedding (U.restrict f) := by refine ⟨fun h x hx ↦ ?_, fun h x hx ↦ ?_⟩ · obtain ⟨e, hxe, rfl⟩ := h x hx exact ⟨e.source, e.open_source.mem_nhds hxe, e.openEmbedding_restrict⟩ · obtain ⟨U, hU, emb⟩ := h x hx have : OpenEmbedding ((interior U).restrict f) := by refine emb.comp ⟨embedding_inclusion interior_subset, ?_⟩ rw [Set.range_inclusion]; exact isOpen_induced isOpen_interior obtain ⟨cont, inj, openMap⟩ := openEmbedding_iff_continuous_injective_open.mp this haveI : Nonempty X := ⟨x⟩ exact ⟨PartialHomeomorph.ofContinuousOpenRestrict (Set.injOn_iff_injective.mpr inj).toPartialEquiv (continuousOn_iff_continuous_restrict.mpr cont) openMap isOpen_interior, mem_interior_iff_mem_nhds.mpr hU, rfl⟩ namespace IsLocalHomeomorphOn /-- Proves that `f` satisfies `IsLocalHomeomorphOn f s`. The condition `h` is weaker than the definition of `IsLocalHomeomorphOn f s`, since it only requires `e : PartialHomeomorph X Y` to agree with `f` on its source `e.source`, as opposed to on the whole space `X`. -/ theorem mk (h : ∀ x ∈ s, ∃ e : PartialHomeomorph X Y, x ∈ e.source ∧ Set.EqOn f e e.source) : IsLocalHomeomorphOn f s := by intro x hx obtain ⟨e, hx, he⟩ := h x hx exact ⟨{ e with toFun := f map_source' := fun _x hx ↦ by rw [he hx]; exact e.map_source' hx left_inv' := fun _x hx ↦ by rw [he hx]; exact e.left_inv' hx right_inv' := fun _y hy ↦ by rw [he (e.map_target' hy)]; exact e.right_inv' hy continuousOn_toFun := (continuousOn_congr he).mpr e.continuousOn_toFun }, hx, rfl⟩ /-- A `PartialHomeomorph` is a local homeomorphism on its source. -/ lemma PartialHomeomorph.isLocalHomeomorphOn (e : PartialHomeomorph X Y) : IsLocalHomeomorphOn e e.source := fun _ hx ↦ ⟨e, hx, rfl⟩ variable {g f s t} theorem mono {t : Set X} (hf : IsLocalHomeomorphOn f t) (hst : s ⊆ t) : IsLocalHomeomorphOn f s := fun x hx ↦ hf x (hst hx) theorem of_comp_left (hgf : IsLocalHomeomorphOn (g ∘ f) s) (hg : IsLocalHomeomorphOn g (f '' s)) (cont : ∀ x ∈ s, ContinuousAt f x) : IsLocalHomeomorphOn f s := mk f s fun x hx ↦ by obtain ⟨g, hxg, rfl⟩ := hg (f x) ⟨x, hx, rfl⟩ obtain ⟨gf, hgf, he⟩ := hgf x hx refine ⟨(gf.restr <| f ⁻¹' g.source).trans g.symm, ⟨⟨hgf, mem_interior_iff_mem_nhds.mpr ((cont x hx).preimage_mem_nhds <| g.open_source.mem_nhds hxg)⟩, he ▸ g.map_source hxg⟩, fun y hy ↦ ?_⟩ change f y = g.symm (gf y) have : f y ∈ g.source := by apply interior_subset hy.1.2 rw [← he, g.eq_symm_apply this (by apply g.map_source this), Function.comp_apply] theorem of_comp_right (hgf : IsLocalHomeomorphOn (g ∘ f) s) (hf : IsLocalHomeomorphOn f s) : IsLocalHomeomorphOn g (f '' s) := mk g _ <| by rintro _ ⟨x, hx, rfl⟩ obtain ⟨f, hxf, rfl⟩ := hf x hx obtain ⟨gf, hgf, he⟩ := hgf x hx refine ⟨f.symm.trans gf, ⟨f.map_source hxf, ?_⟩, fun y hy ↦ ?_⟩ · apply (f.left_inv hxf).symm ▸ hgf · change g y = gf (f.symm y) rw [← he, Function.comp_apply, f.right_inv hy.1] theorem map_nhds_eq (hf : IsLocalHomeomorphOn f s) {x : X} (hx : x ∈ s) : (𝓝 x).map f = 𝓝 (f x) := let ⟨e, hx, he⟩ := hf x hx he.symm ▸ e.map_nhds_eq hx protected theorem continuousAt (hf : IsLocalHomeomorphOn f s) {x : X} (hx : x ∈ s) : ContinuousAt f x := (hf.map_nhds_eq hx).le protected theorem continuousOn (hf : IsLocalHomeomorphOn f s) : ContinuousOn f s := ContinuousAt.continuousOn fun _x ↦ hf.continuousAt protected theorem comp (hg : IsLocalHomeomorphOn g t) (hf : IsLocalHomeomorphOn f s) (h : Set.MapsTo f s t) : IsLocalHomeomorphOn (g ∘ f) s := by intro x hx obtain ⟨eg, hxg, rfl⟩ := hg (f x) (h hx) obtain ⟨ef, hxf, rfl⟩ := hf x hx exact ⟨ef.trans eg, ⟨hxf, hxg⟩, rfl⟩ end IsLocalHomeomorphOn /-- A function `f : X → Y` satisfies `IsLocalHomeomorph f` if each `x : x` is contained in the source of some `e : PartialHomeomorph X Y` with `f = e`. -/ def IsLocalHomeomorph := ∀ x : X, ∃ e : PartialHomeomorph X Y, x ∈ e.source ∧ f = e theorem Homeomorph.isLocalHomeomorph (f : X ≃ₜ Y) : IsLocalHomeomorph f := fun _ ↦ ⟨f.toPartialHomeomorph, trivial, rfl⟩ variable {f s} theorem isLocalHomeomorph_iff_isLocalHomeomorphOn_univ : IsLocalHomeomorph f ↔ IsLocalHomeomorphOn f Set.univ := ⟨fun h x _ ↦ h x, fun h x ↦ h x trivial⟩ protected theorem IsLocalHomeomorph.isLocalHomeomorphOn (hf : IsLocalHomeomorph f) : IsLocalHomeomorphOn f s := fun x _ ↦ hf x theorem isLocalHomeomorph_iff_openEmbedding_restrict {f : X → Y} : IsLocalHomeomorph f ↔ ∀ x : X, ∃ U ∈ 𝓝 x, OpenEmbedding (U.restrict f) := by simp_rw [isLocalHomeomorph_iff_isLocalHomeomorphOn_univ, isLocalHomeomorphOn_iff_openEmbedding_restrict, imp_iff_right (Set.mem_univ _)] theorem OpenEmbedding.isLocalHomeomorph (hf : OpenEmbedding f) : IsLocalHomeomorph f := isLocalHomeomorph_iff_openEmbedding_restrict.mpr fun _ ↦ ⟨_, Filter.univ_mem, hf.comp (Homeomorph.Set.univ X).openEmbedding⟩ variable (f) namespace IsLocalHomeomorph /-- Proves that `f` satisfies `IsLocalHomeomorph f`. The condition `h` is weaker than the definition of `IsLocalHomeomorph f`, since it only requires `e : PartialHomeomorph X Y` to agree with `f` on its source `e.source`, as opposed to on the whole space `X`. -/ theorem mk (h : ∀ x : X, ∃ e : PartialHomeomorph X Y, x ∈ e.source ∧ Set.EqOn f e e.source) : IsLocalHomeomorph f := isLocalHomeomorph_iff_isLocalHomeomorphOn_univ.mpr (IsLocalHomeomorphOn.mk f Set.univ fun x _hx ↦ h x) /-- A homeomorphism is a local homeomorphism. -/ lemma Homeomorph.isLocalHomeomorph (h : X ≃ₜ Y) : IsLocalHomeomorph h := fun _ ↦ ⟨h.toPartialHomeomorph, trivial, rfl⟩ variable {g f} lemma isLocallyInjective (hf : IsLocalHomeomorph f) : IsLocallyInjective f := fun x ↦ by obtain ⟨f, hx, rfl⟩ := hf x; exact ⟨f.source, f.open_source, hx, f.injOn⟩ theorem of_comp (hgf : IsLocalHomeomorph (g ∘ f)) (hg : IsLocalHomeomorph g) (cont : Continuous f) : IsLocalHomeomorph f := isLocalHomeomorph_iff_isLocalHomeomorphOn_univ.mpr <| hgf.isLocalHomeomorphOn.of_comp_left hg.isLocalHomeomorphOn fun _ _ ↦ cont.continuousAt theorem map_nhds_eq (hf : IsLocalHomeomorph f) (x : X) : (𝓝 x).map f = 𝓝 (f x) := hf.isLocalHomeomorphOn.map_nhds_eq (Set.mem_univ x) /-- A local homeomorphism is continuous. -/ protected theorem continuous (hf : IsLocalHomeomorph f) : Continuous f := continuous_iff_continuousOn_univ.mpr hf.isLocalHomeomorphOn.continuousOn /-- A local homeomorphism is an open map. -/ protected theorem isOpenMap (hf : IsLocalHomeomorph f) : IsOpenMap f := IsOpenMap.of_nhds_le fun x ↦ ge_of_eq (hf.map_nhds_eq x) /-- The composition of local homeomorphisms is a local homeomorphism. -/ protected theorem comp (hg : IsLocalHomeomorph g) (hf : IsLocalHomeomorph f) : IsLocalHomeomorph (g ∘ f) := isLocalHomeomorph_iff_isLocalHomeomorphOn_univ.mpr (hg.isLocalHomeomorphOn.comp hf.isLocalHomeomorphOn (Set.univ.mapsTo_univ f)) /-- An injective local homeomorphism is an open embedding. -/ theorem openEmbedding_of_injective (hf : IsLocalHomeomorph f) (hi : f.Injective) : OpenEmbedding f := openEmbedding_of_continuous_injective_open hf.continuous hi hf.isOpenMap /-- A surjective embedding is a homeomorphism. -/ noncomputable def _root_.Embedding.toHomeomeomorph_of_surjective (hf : Embedding f) (hsurj : Function.Surjective f) : X ≃ₜ Y := Homeomorph.homeomorphOfContinuousOpen (Equiv.ofBijective f ⟨hf.inj, hsurj⟩) hf.continuous (hf.toOpenEmbedding_of_surjective hsurj).isOpenMap /-- A bijective local homeomorphism is a homeomorphism. -/ noncomputable def toHomeomorph_of_bijective (hf : IsLocalHomeomorph f) (hb : f.Bijective) : X ≃ₜ Y := Homeomorph.homeomorphOfContinuousOpen (Equiv.ofBijective f hb) hf.continuous hf.isOpenMap /-- Continuous local sections of a local homeomorphism are open embeddings. -/ theorem openEmbedding_of_comp (hf : IsLocalHomeomorph g) (hgf : OpenEmbedding (g ∘ f)) (cont : Continuous f) : OpenEmbedding f := (hgf.isLocalHomeomorph.of_comp hf cont).openEmbedding_of_injective hgf.inj.of_comp open TopologicalSpace in /-- Ranges of continuous local sections of a local homeomorphism form a basis of the source space. -/ theorem isTopologicalBasis (hf : IsLocalHomeomorph f) : IsTopologicalBasis {U : Set X | ∃ V : Set Y, IsOpen V ∧ ∃ s : C(V,X), f ∘ s = (↑) ∧ Set.range s = U} := by refine isTopologicalBasis_of_isOpen_of_nhds ?_ fun x U hx hU ↦ ?_ · rintro _ ⟨U, hU, s, hs, rfl⟩ refine (openEmbedding_of_comp hf (hs ▸ ⟨embedding_subtype_val, ?_⟩) s.continuous).isOpen_range rwa [Subtype.range_val] · obtain ⟨f, hxf, rfl⟩ := hf x refine ⟨f.source ∩ U, ⟨f.target ∩ f.symm ⁻¹' U, f.symm.isOpen_inter_preimage hU, ⟨_, continuousOn_iff_continuous_restrict.mp (f.continuousOn_invFun.mono fun _ h ↦ h.1)⟩, ?_, (Set.range_restrict _ _).trans ?_⟩, ⟨hxf, hx⟩, fun _ h ↦ h.2⟩ · ext y; exact f.right_inv y.2.1 · apply (f.symm_image_target_inter_eq _).trans rw [Set.preimage_inter, ← Set.inter_assoc, Set.inter_eq_self_of_subset_left f.source_preimage_target, f.source_inter_preimage_inv_preimage] end IsLocalHomeomorph
Topology\KrullDimension.lean
/- Copyright (c) 2024 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Fangming Li -/ import Mathlib.Order.KrullDimension import Mathlib.Topology.Sets.Closeds /-! # The Krull dimension of a topological space The Krull dimension of a topological space is the order theoretic Krull dimension applied to the collection of all its subsets that are closed and irreducible. Unfolding this definition, it is the length of longest series of closed irreducible subsets ordered by inclusion. TODO: The Krull dimension of `Spec(R)` equals the Krull dimension of `R`, for `R` a commutative ring. -/ open TopologicalSpace /-- The Krull dimension of a topological space is the supremum of lengths of chains of closed irreducible sets. -/ noncomputable def topologicalKrullDim (T : Type _) [TopologicalSpace T] : WithBot (WithTop ℕ) := krullDim (IrreducibleCloseds T)
Topology\List.lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Topology.Constructions import Mathlib.Topology.Algebra.Monoid import Mathlib.Order.Filter.ListTraverse import Mathlib.Tactic.AdaptationNote /-! # Topology on lists and vectors -/ open TopologicalSpace Set Filter open Topology Filter variable {α : Type*} {β : Type*} [TopologicalSpace α] [TopologicalSpace β] instance : TopologicalSpace (List α) := TopologicalSpace.mkOfNhds (traverse nhds) theorem nhds_list (as : List α) : 𝓝 as = traverse 𝓝 as := by refine nhds_mkOfNhds _ _ ?_ ?_ · intro l induction l with | nil => exact le_rfl | cons a l ih => suffices List.cons <$> pure a <*> pure l ≤ List.cons <$> 𝓝 a <*> traverse 𝓝 l by simpa only [functor_norm] using this exact Filter.seq_mono (Filter.map_mono <| pure_le_nhds a) ih · intro l s hs rcases (mem_traverse_iff _ _).1 hs with ⟨u, hu, hus⟩ clear as hs have : ∃ v : List (Set α), l.Forall₂ (fun a s => IsOpen s ∧ a ∈ s) v ∧ sequence v ⊆ s := by induction hu generalizing s with | nil => exists [] simp only [List.forall₂_nil_left_iff, exists_eq_left] exact ⟨trivial, hus⟩ -- porting note -- renamed reordered variables based on previous types | cons ht _ ih => rcases mem_nhds_iff.1 ht with ⟨u, hut, hu⟩ rcases ih _ Subset.rfl with ⟨v, hv, hvss⟩ exact ⟨u::v, List.Forall₂.cons hu hv, Subset.trans (Set.seq_mono (Set.image_subset _ hut) hvss) hus⟩ rcases this with ⟨v, hv, hvs⟩ have : sequence v ∈ traverse 𝓝 l := mem_traverse _ _ <| hv.imp fun a s ⟨hs, ha⟩ => IsOpen.mem_nhds hs ha refine mem_of_superset this fun u hu ↦ ?_ have hu := (List.mem_traverse _ _).1 hu have : List.Forall₂ (fun a s => IsOpen s ∧ a ∈ s) u v := by refine List.Forall₂.flip ?_ replace hv := hv.flip #adaptation_note /-- nightly-2024-03-16: simp was simp only [List.forall₂_and_left, flip] at hv ⊢ -/ simp only [List.forall₂_and_left, Function.flip_def] at hv ⊢ exact ⟨hv.1, hu.flip⟩ refine mem_of_superset ?_ hvs exact mem_traverse _ _ (this.imp fun a s ⟨hs, ha⟩ => IsOpen.mem_nhds hs ha) @[simp] theorem nhds_nil : 𝓝 ([] : List α) = pure [] := by rw [nhds_list, List.traverse_nil _] theorem nhds_cons (a : α) (l : List α) : 𝓝 (a::l) = List.cons <$> 𝓝 a <*> 𝓝 l := by rw [nhds_list, List.traverse_cons _, ← nhds_list] theorem List.tendsto_cons {a : α} {l : List α} : Tendsto (fun p : α × List α => List.cons p.1 p.2) (𝓝 a ×ˢ 𝓝 l) (𝓝 (a::l)) := by rw [nhds_cons, Tendsto, Filter.map_prod]; exact le_rfl theorem Filter.Tendsto.cons {α : Type*} {f : α → β} {g : α → List β} {a : Filter α} {b : β} {l : List β} (hf : Tendsto f a (𝓝 b)) (hg : Tendsto g a (𝓝 l)) : Tendsto (fun a => List.cons (f a) (g a)) a (𝓝 (b::l)) := List.tendsto_cons.comp (Tendsto.prod_mk hf hg) namespace List theorem tendsto_cons_iff {β : Type*} {f : List α → β} {b : Filter β} {a : α} {l : List α} : Tendsto f (𝓝 (a::l)) b ↔ Tendsto (fun p : α × List α => f (p.1::p.2)) (𝓝 a ×ˢ 𝓝 l) b := by have : 𝓝 (a::l) = (𝓝 a ×ˢ 𝓝 l).map fun p : α × List α => p.1::p.2 := by simp only [nhds_cons, Filter.prod_eq, (Filter.map_def _ _).symm, (Filter.seq_eq_filter_seq _ _).symm] simp [-Filter.map_def, (· ∘ ·), functor_norm] rw [this, Filter.tendsto_map'_iff]; rfl theorem continuous_cons : Continuous fun x : α × List α => (x.1::x.2 : List α) := continuous_iff_continuousAt.mpr fun ⟨_x, _y⟩ => continuousAt_fst.cons continuousAt_snd theorem tendsto_nhds {β : Type*} {f : List α → β} {r : List α → Filter β} (h_nil : Tendsto f (pure []) (r [])) (h_cons : ∀ l a, Tendsto f (𝓝 l) (r l) → Tendsto (fun p : α × List α => f (p.1::p.2)) (𝓝 a ×ˢ 𝓝 l) (r (a::l))) : ∀ l, Tendsto f (𝓝 l) (r l) | [] => by rwa [nhds_nil] | a::l => by rw [tendsto_cons_iff]; exact h_cons l a (@tendsto_nhds _ _ _ h_nil h_cons l) instance [DiscreteTopology α] : DiscreteTopology (List α) := by rw [discreteTopology_iff_nhds]; intro l; induction l <;> simp [*, nhds_cons] theorem continuousAt_length : ∀ l : List α, ContinuousAt List.length l := by simp only [ContinuousAt, nhds_discrete] refine tendsto_nhds ?_ ?_ · exact tendsto_pure_pure _ _ · intro l a ih dsimp only [List.length] refine Tendsto.comp (tendsto_pure_pure (fun x => x + 1) _) ?_ exact Tendsto.comp ih tendsto_snd theorem tendsto_insertNth' {a : α} : ∀ {n : ℕ} {l : List α}, Tendsto (fun p : α × List α => insertNth n p.1 p.2) (𝓝 a ×ˢ 𝓝 l) (𝓝 (insertNth n a l)) | 0, l => tendsto_cons | n + 1, [] => by simp | n + 1, a'::l => by have : 𝓝 a ×ˢ 𝓝 (a'::l) = (𝓝 a ×ˢ (𝓝 a' ×ˢ 𝓝 l)).map fun p : α × α × List α => (p.1, p.2.1::p.2.2) := by simp only [nhds_cons, Filter.prod_eq, ← Filter.map_def, ← Filter.seq_eq_filter_seq] simp [-Filter.map_def, (· ∘ ·), functor_norm] rw [this, tendsto_map'_iff] exact (tendsto_fst.comp tendsto_snd).cons ((@tendsto_insertNth' _ n l).comp <| tendsto_fst.prod_mk <| tendsto_snd.comp tendsto_snd) theorem tendsto_insertNth {β} {n : ℕ} {a : α} {l : List α} {f : β → α} {g : β → List α} {b : Filter β} (hf : Tendsto f b (𝓝 a)) (hg : Tendsto g b (𝓝 l)) : Tendsto (fun b : β => insertNth n (f b) (g b)) b (𝓝 (insertNth n a l)) := tendsto_insertNth'.comp (Tendsto.prod_mk hf hg) theorem continuous_insertNth {n : ℕ} : Continuous fun p : α × List α => insertNth n p.1 p.2 := continuous_iff_continuousAt.mpr fun ⟨a, l⟩ => by rw [ContinuousAt, nhds_prod_eq]; exact tendsto_insertNth' theorem tendsto_eraseIdx : ∀ {n : ℕ} {l : List α}, Tendsto (eraseIdx · n) (𝓝 l) (𝓝 (eraseIdx l n)) | _, [] => by rw [nhds_nil]; exact tendsto_pure_nhds _ _ | 0, a::l => by rw [tendsto_cons_iff]; exact tendsto_snd | n + 1, a::l => by rw [tendsto_cons_iff] dsimp [eraseIdx] exact tendsto_fst.cons ((@tendsto_eraseIdx n l).comp tendsto_snd) @[deprecated (since := "2024-05-04")] alias tendsto_removeNth := tendsto_eraseIdx theorem continuous_eraseIdx {n : ℕ} : Continuous fun l : List α => eraseIdx l n := continuous_iff_continuousAt.mpr fun _a => tendsto_eraseIdx @[deprecated (since := "2024-05-04")] alias continuous_removeNth := continuous_eraseIdx @[to_additive] theorem tendsto_prod [Monoid α] [ContinuousMul α] {l : List α} : Tendsto List.prod (𝓝 l) (𝓝 l.prod) := by induction' l with x l ih · simp (config := { contextual := true }) [nhds_nil, mem_of_mem_nhds, tendsto_pure_left] simp_rw [tendsto_cons_iff, prod_cons] have := continuous_iff_continuousAt.mp continuous_mul (x, l.prod) rw [ContinuousAt, nhds_prod_eq] at this exact this.comp (tendsto_id.prod_map ih) @[to_additive] theorem continuous_prod [Monoid α] [ContinuousMul α] : Continuous (prod : List α → α) := continuous_iff_continuousAt.mpr fun _l => tendsto_prod end List namespace Vector open List open Mathlib (Vector) instance (n : ℕ) : TopologicalSpace (Vector α n) := by unfold Vector; infer_instance theorem tendsto_cons {n : ℕ} {a : α} {l : Vector α n} : Tendsto (fun p : α × Vector α n => p.1 ::ᵥ p.2) (𝓝 a ×ˢ 𝓝 l) (𝓝 (a ::ᵥ l)) := by rw [tendsto_subtype_rng, Vector.cons_val] exact tendsto_fst.cons (Tendsto.comp continuousAt_subtype_val tendsto_snd) theorem tendsto_insertNth {n : ℕ} {i : Fin (n + 1)} {a : α} : ∀ {l : Vector α n}, Tendsto (fun p : α × Vector α n => Vector.insertNth p.1 i p.2) (𝓝 a ×ˢ 𝓝 l) (𝓝 (Vector.insertNth a i l)) | ⟨l, hl⟩ => by rw [Vector.insertNth, tendsto_subtype_rng] simp only [Vector.insertNth_val] exact List.tendsto_insertNth tendsto_fst (Tendsto.comp continuousAt_subtype_val tendsto_snd : _) theorem continuous_insertNth' {n : ℕ} {i : Fin (n + 1)} : Continuous fun p : α × Vector α n => Vector.insertNth p.1 i p.2 := continuous_iff_continuousAt.mpr fun ⟨a, l⟩ => by rw [ContinuousAt, nhds_prod_eq]; exact tendsto_insertNth theorem continuous_insertNth {n : ℕ} {i : Fin (n + 1)} {f : β → α} {g : β → Vector α n} (hf : Continuous f) (hg : Continuous g) : Continuous fun b => Vector.insertNth (f b) i (g b) := continuous_insertNth'.comp (hf.prod_mk hg : _) theorem continuousAt_eraseIdx {n : ℕ} {i : Fin (n + 1)} : ∀ {l : Vector α (n + 1)}, ContinuousAt (Vector.eraseIdx i) l | ⟨l, hl⟩ => by rw [ContinuousAt, Vector.eraseIdx, tendsto_subtype_rng] simp only [Vector.eraseIdx_val] exact Tendsto.comp List.tendsto_eraseIdx continuousAt_subtype_val @[deprecated (since := "2024-05-04")] alias continuousAt_removeNth := continuousAt_eraseIdx theorem continuous_eraseIdx {n : ℕ} {i : Fin (n + 1)} : Continuous (Vector.eraseIdx i : Vector α (n + 1) → Vector α n) := continuous_iff_continuousAt.mpr fun ⟨_a, _l⟩ => continuousAt_eraseIdx @[deprecated (since := "2024-05-04")] alias continuous_removeNth := continuous_eraseIdx end Vector
Topology\LocalAtTarget.lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Topology.Sets.Opens import Mathlib.Topology.LocallyClosed /-! # Properties of maps that are local at the target. We show that the following properties of continuous maps are local at the target : - `Inducing` - `Embedding` - `OpenEmbedding` - `ClosedEmbedding` -/ open TopologicalSpace Set Filter open Topology Filter variable {α β : Type*} [TopologicalSpace α] [TopologicalSpace β] {f : α → β} variable {s : Set β} {ι : Type*} {U : ι → Opens β} (hU : iSup U = ⊤) theorem Set.restrictPreimage_inducing (s : Set β) (h : Inducing f) : Inducing (s.restrictPreimage f) := by simp_rw [← inducing_subtype_val.of_comp_iff, inducing_iff_nhds, restrictPreimage, MapsTo.coe_restrict, restrict_eq, ← @Filter.comap_comap _ _ _ _ _ f, Function.comp_apply] at h ⊢ intro a rw [← h, ← inducing_subtype_val.nhds_eq_comap] alias Inducing.restrictPreimage := Set.restrictPreimage_inducing theorem Set.restrictPreimage_embedding (s : Set β) (h : Embedding f) : Embedding (s.restrictPreimage f) := ⟨h.1.restrictPreimage s, h.2.restrictPreimage s⟩ alias Embedding.restrictPreimage := Set.restrictPreimage_embedding theorem Set.restrictPreimage_openEmbedding (s : Set β) (h : OpenEmbedding f) : OpenEmbedding (s.restrictPreimage f) := ⟨h.1.restrictPreimage s, (s.range_restrictPreimage f).symm ▸ continuous_subtype_val.isOpen_preimage _ h.isOpen_range⟩ alias OpenEmbedding.restrictPreimage := Set.restrictPreimage_openEmbedding theorem Set.restrictPreimage_closedEmbedding (s : Set β) (h : ClosedEmbedding f) : ClosedEmbedding (s.restrictPreimage f) := ⟨h.1.restrictPreimage s, (s.range_restrictPreimage f).symm ▸ inducing_subtype_val.isClosed_preimage _ h.isClosed_range⟩ alias ClosedEmbedding.restrictPreimage := Set.restrictPreimage_closedEmbedding theorem IsClosedMap.restrictPreimage (H : IsClosedMap f) (s : Set β) : IsClosedMap (s.restrictPreimage f) := by intro t suffices ∀ u, IsClosed u → Subtype.val ⁻¹' u = t → ∃ v, IsClosed v ∧ Subtype.val ⁻¹' v = s.restrictPreimage f '' t by simpa [isClosed_induced_iff] exact fun u hu e => ⟨f '' u, H u hu, by simp [← e, image_restrictPreimage]⟩ @[deprecated (since := "2024-04-02")] theorem Set.restrictPreimage_isClosedMap (s : Set β) (H : IsClosedMap f) : IsClosedMap (s.restrictPreimage f) := H.restrictPreimage s theorem IsOpenMap.restrictPreimage (H : IsOpenMap f) (s : Set β) : IsOpenMap (s.restrictPreimage f) := by intro t suffices ∀ u, IsOpen u → Subtype.val ⁻¹' u = t → ∃ v, IsOpen v ∧ Subtype.val ⁻¹' v = s.restrictPreimage f '' t by simpa [isOpen_induced_iff] exact fun u hu e => ⟨f '' u, H u hu, by simp [← e, image_restrictPreimage]⟩ @[deprecated (since := "2024-04-02")] theorem Set.restrictPreimage_isOpenMap (s : Set β) (H : IsOpenMap f) : IsOpenMap (s.restrictPreimage f) := H.restrictPreimage s theorem isOpen_iff_inter_of_iSup_eq_top (s : Set β) : IsOpen s ↔ ∀ i, IsOpen (s ∩ U i) := by constructor · exact fun H i => H.inter (U i).2 · intro H have : ⋃ i, (U i : Set β) = Set.univ := by convert congr_arg (SetLike.coe) hU simp rw [← s.inter_univ, ← this, Set.inter_iUnion] exact isOpen_iUnion H theorem isOpen_iff_coe_preimage_of_iSup_eq_top (s : Set β) : IsOpen s ↔ ∀ i, IsOpen ((↑) ⁻¹' s : Set (U i)) := by -- Porting note: rewrote to avoid ´simp´ issues rw [isOpen_iff_inter_of_iSup_eq_top hU s] refine forall_congr' fun i => ?_ rw [(U _).2.openEmbedding_subtype_val.open_iff_image_open] erw [Set.image_preimage_eq_inter_range] rw [Subtype.range_coe, Opens.carrier_eq_coe] theorem isClosed_iff_coe_preimage_of_iSup_eq_top (s : Set β) : IsClosed s ↔ ∀ i, IsClosed ((↑) ⁻¹' s : Set (U i)) := by simpa using isOpen_iff_coe_preimage_of_iSup_eq_top hU sᶜ theorem isLocallyClosed_iff_coe_preimage_of_iSup_eq_top (s : Set β) : IsLocallyClosed s ↔ ∀ i, IsLocallyClosed ((↑) ⁻¹' s : Set (U i)) := by simp_rw [isLocallyClosed_iff_isOpen_coborder] rw [isOpen_iff_coe_preimage_of_iSup_eq_top hU] exact forall_congr' fun i ↦ by rw [(U i).isOpen.openEmbedding_subtype_val.coborder_preimage] theorem isOpenMap_iff_isOpenMap_of_iSup_eq_top : IsOpenMap f ↔ ∀ i, IsOpenMap ((U i).1.restrictPreimage f) := by refine ⟨fun h i => h.restrictPreimage _, ?_⟩ rintro H s hs rw [isOpen_iff_coe_preimage_of_iSup_eq_top hU] intro i convert H i _ (hs.preimage continuous_subtype_val) ext ⟨x, hx⟩ suffices (∃ y, y ∈ s ∧ f y = x) ↔ ∃ y, y ∈ s ∧ f y ∈ U i ∧ f y = x by simpa [Set.restrictPreimage, ← Subtype.coe_inj] exact ⟨fun ⟨a, b, c⟩ => ⟨a, b, c.symm ▸ hx, c⟩, fun ⟨a, b, _, c⟩ => ⟨a, b, c⟩⟩ theorem isClosedMap_iff_isClosedMap_of_iSup_eq_top : IsClosedMap f ↔ ∀ i, IsClosedMap ((U i).1.restrictPreimage f) := by refine ⟨fun h i => h.restrictPreimage _, ?_⟩ rintro H s hs rw [isClosed_iff_coe_preimage_of_iSup_eq_top hU] intro i convert H i _ ⟨⟨_, hs.1, eq_compl_comm.mpr rfl⟩⟩ ext ⟨x, hx⟩ suffices (∃ y, y ∈ s ∧ f y = x) ↔ ∃ y, y ∈ s ∧ f y ∈ U i ∧ f y = x by simpa [Set.restrictPreimage, ← Subtype.coe_inj] exact ⟨fun ⟨a, b, c⟩ => ⟨a, b, c.symm ▸ hx, c⟩, fun ⟨a, b, _, c⟩ => ⟨a, b, c⟩⟩ theorem inducing_iff_inducing_of_iSup_eq_top (h : Continuous f) : Inducing f ↔ ∀ i, Inducing ((U i).1.restrictPreimage f) := by simp_rw [← inducing_subtype_val.of_comp_iff, inducing_iff_nhds, restrictPreimage, MapsTo.coe_restrict, restrict_eq, ← @Filter.comap_comap _ _ _ _ _ f] constructor · intro H i x rw [Function.comp_apply, ← H, ← inducing_subtype_val.nhds_eq_comap] · intro H x obtain ⟨i, hi⟩ := Opens.mem_iSup.mp (show f x ∈ iSup U by rw [hU] trivial) erw [← OpenEmbedding.map_nhds_eq (h.1 _ (U i).2).openEmbedding_subtype_val ⟨x, hi⟩] rw [(H i) ⟨x, hi⟩, Filter.subtype_coe_map_comap, Function.comp_apply, Subtype.coe_mk, inf_eq_left, Filter.le_principal_iff] exact Filter.preimage_mem_comap ((U i).2.mem_nhds hi) theorem embedding_iff_embedding_of_iSup_eq_top (h : Continuous f) : Embedding f ↔ ∀ i, Embedding ((U i).1.restrictPreimage f) := by simp_rw [embedding_iff] rw [forall_and] apply and_congr · apply inducing_iff_inducing_of_iSup_eq_top <;> assumption · apply Set.injective_iff_injective_of_iUnion_eq_univ convert congr_arg SetLike.coe hU simp theorem openEmbedding_iff_openEmbedding_of_iSup_eq_top (h : Continuous f) : OpenEmbedding f ↔ ∀ i, OpenEmbedding ((U i).1.restrictPreimage f) := by simp_rw [openEmbedding_iff] rw [forall_and] apply and_congr · apply embedding_iff_embedding_of_iSup_eq_top <;> assumption · simp_rw [Set.range_restrictPreimage] apply isOpen_iff_coe_preimage_of_iSup_eq_top hU theorem closedEmbedding_iff_closedEmbedding_of_iSup_eq_top (h : Continuous f) : ClosedEmbedding f ↔ ∀ i, ClosedEmbedding ((U i).1.restrictPreimage f) := by simp_rw [closedEmbedding_iff] rw [forall_and] apply and_congr · apply embedding_iff_embedding_of_iSup_eq_top <;> assumption · simp_rw [Set.range_restrictPreimage] apply isClosed_iff_coe_preimage_of_iSup_eq_top hU
Topology\LocallyClosed.lean
/- Copyright (c) 2024 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Topology.Constructions import Mathlib.Tactic.TFAE /-! # Locally closed sets ## Main definitions * `IsLocallyClosed`: Predicate saying that a set is locally closed ## Main results * `isLocallyClosed_tfae`: A set `s` is locally closed if one of the equivalent conditions below hold 1. It is the intersection of some open set and some closed set. 2. The coborder `(closure s \ s)ᶜ` is open. 3. `s` is closed in some neighborhood of `x` for all `x ∈ s`. 4. Every `x ∈ s` has some open neighborhood `U` such that `U ∩ closure s ⊆ s`. 5. `s` is open in the closure of `s`. -/ variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {s t : Set X} {f : X → Y} open scoped Topology Set.Notation open Set lemma subset_coborder : s ⊆ coborder s := by rw [coborder, subset_compl_iff_disjoint_right] exact disjoint_sdiff_self_right lemma coborder_inter_closure : coborder s ∩ closure s = s := by rw [coborder, ← diff_eq_compl_inter, diff_diff_right_self, inter_eq_right] exact subset_closure lemma closure_inter_coborder : closure s ∩ coborder s = s := by rw [inter_comm, coborder_inter_closure] lemma coborder_eq_union_frontier_compl : coborder s = s ∪ (frontier s)ᶜ := by rw [coborder, compl_eq_comm, compl_union, compl_compl, ← diff_eq_compl_inter, ← union_diff_right, union_comm, ← closure_eq_self_union_frontier] lemma coborder_eq_univ_iff : coborder s = univ ↔ IsClosed s := by simp [coborder, diff_eq_empty, closure_subset_iff_isClosed] alias ⟨_, IsClosed.coborder_eq⟩ := coborder_eq_univ_iff lemma coborder_eq_compl_frontier_iff : coborder s = (frontier s)ᶜ ↔ IsOpen s := by simp_rw [coborder_eq_union_frontier_compl, union_eq_right, subset_compl_iff_disjoint_left, disjoint_frontier_iff_isOpen] alias ⟨_, IsOpen.coborder_eq⟩ := coborder_eq_compl_frontier_iff lemma IsOpenMap.coborder_preimage_subset (hf : IsOpenMap f) (s : Set Y) : coborder (f ⁻¹' s) ⊆ f ⁻¹' (coborder s) := by rw [coborder, coborder, preimage_compl, preimage_diff, compl_subset_compl] apply diff_subset_diff_left exact hf.preimage_closure_subset_closure_preimage lemma Continuous.preimage_coborder_subset (hf : Continuous f) (s : Set Y) : f ⁻¹' (coborder s) ⊆ coborder (f ⁻¹' s) := by rw [coborder, coborder, preimage_compl, preimage_diff, compl_subset_compl] apply diff_subset_diff_left exact hf.closure_preimage_subset s lemma coborder_preimage (hf : IsOpenMap f) (hf' : Continuous f) (s : Set Y) : coborder (f ⁻¹' s) = f ⁻¹' (coborder s) := (hf.coborder_preimage_subset s).antisymm (hf'.preimage_coborder_subset s) protected lemma OpenEmbedding.coborder_preimage (hf : OpenEmbedding f) (s : Set Y) : coborder (f ⁻¹' s) = f ⁻¹' (coborder s) := coborder_preimage hf.isOpenMap hf.continuous s lemma isClosed_preimage_val_coborder : IsClosed (coborder s ↓∩ s) := by rw [isClosed_preimage_val, inter_eq_right.mpr subset_coborder, coborder_inter_closure] lemma IsOpen.isLocallyClosed (hs : IsOpen s) : IsLocallyClosed s := ⟨_, _, hs, isClosed_univ, (inter_univ _).symm⟩ lemma IsClosed.isLocallyClosed (hs : IsClosed s) : IsLocallyClosed s := ⟨_, _, isOpen_univ, hs, (univ_inter _).symm⟩ lemma IsLocallyClosed.inter (hs : IsLocallyClosed s) (ht : IsLocallyClosed t) : IsLocallyClosed (s ∩ t) := by obtain ⟨U₁, Z₁, hU₁, hZ₁, rfl⟩ := hs obtain ⟨U₂, Z₂, hU₂, hZ₂, rfl⟩ := ht refine ⟨_, _, hU₁.inter hU₂, hZ₁.inter hZ₂, inter_inter_inter_comm U₁ Z₁ U₂ Z₂⟩ lemma IsLocallyClosed.preimage {s : Set Y} (hs : IsLocallyClosed s) {f : X → Y} (hf : Continuous f) : IsLocallyClosed (f ⁻¹' s) := by obtain ⟨U, Z, hU, hZ, rfl⟩ := hs exact ⟨_, _, hU.preimage hf, hZ.preimage hf, preimage_inter⟩ nonrec lemma Inducing.isLocallyClosed_iff {s : Set X} {f : X → Y} (hf : Inducing f) : IsLocallyClosed s ↔ ∃ s' : Set Y, IsLocallyClosed s' ∧ f ⁻¹' s' = s := by simp_rw [IsLocallyClosed, hf.isOpen_iff, hf.isClosed_iff] constructor · rintro ⟨_, _, ⟨U, hU, rfl⟩, ⟨Z, hZ, rfl⟩, rfl⟩ exact ⟨_, ⟨U, Z, hU, hZ, rfl⟩, rfl⟩ · rintro ⟨_, ⟨U, Z, hU, hZ, rfl⟩, rfl⟩ exact ⟨_, _, ⟨U, hU, rfl⟩, ⟨Z, hZ, rfl⟩, rfl⟩ lemma Embedding.isLocallyClosed_iff {s : Set X} {f : X → Y} (hf : Embedding f) : IsLocallyClosed s ↔ ∃ s' : Set Y, IsLocallyClosed s' ∧ s' ∩ range f = f '' s := by simp_rw [hf.toInducing.isLocallyClosed_iff, ← (image_injective.mpr hf.inj).eq_iff, image_preimage_eq_inter_range] lemma IsLocallyClosed.image {s : Set X} (hs : IsLocallyClosed s) {f : X → Y} (hf : Inducing f) (hf' : IsLocallyClosed (range f)) : IsLocallyClosed (f '' s) := by obtain ⟨t, ht, rfl⟩ := hf.isLocallyClosed_iff.mp hs rw [image_preimage_eq_inter_range] exact ht.inter hf' /-- A set `s` is locally closed if one of the equivalent conditions below hold 1. It is the intersection of some open set and some closed set. 2. The coborder `(closure s \ s)ᶜ` is open. 3. `s` is closed in some neighborhood of `x` for all `x ∈ s`. 4. Every `x ∈ s` has some open neighborhood `U` such that `U ∩ closure s ⊆ s`. 5. `s` is open in the closure of `s`. -/ lemma isLocallyClosed_tfae (s : Set X) : List.TFAE [ IsLocallyClosed s, IsOpen (coborder s), ∀ x ∈ s, ∃ U ∈ 𝓝 x, IsClosed (U ↓∩ s), ∀ x ∈ s, ∃ U, x ∈ U ∧ IsOpen U ∧ U ∩ closure s ⊆ s, IsOpen (closure s ↓∩ s)] := by tfae_have 1 → 2 · rintro ⟨U, Z, hU, hZ, rfl⟩ have : Z ∪ (frontier (U ∩ Z))ᶜ = univ := by nth_rw 1 [← hZ.closure_eq] rw [← compl_subset_iff_union, compl_subset_compl] refine frontier_subset_closure.trans (closure_mono inter_subset_right) rw [coborder_eq_union_frontier_compl, inter_union_distrib_right, this, inter_univ] exact hU.union isClosed_frontier.isOpen_compl tfae_have 2 → 3 · exact fun h x ↦ (⟨coborder s, h.mem_nhds <| subset_coborder ·, isClosed_preimage_val_coborder⟩) tfae_have 3 → 4 · intro h x hx obtain ⟨t, ht, ht'⟩ := h x hx obtain ⟨U, hUt, hU, hxU⟩ := mem_nhds_iff.mp ht rw [isClosed_preimage_val] at ht' exact ⟨U, hxU, hU, (subset_inter (inter_subset_left.trans hUt) (hU.inter_closure.trans (closure_mono <| inter_subset_inter hUt subset_rfl))).trans ht'⟩ tfae_have 4 → 5 · intro H choose U hxU hU e using H refine ⟨⋃ x ∈ s, U x ‹_›, isOpen_iUnion (isOpen_iUnion <| hU ·), ext fun x ↦ ⟨?_, ?_⟩⟩ · rintro ⟨_, ⟨⟨y, rfl⟩, ⟨_, ⟨hy, rfl⟩, hxU⟩⟩⟩ exact e y hy ⟨hxU, x.2⟩ · exact (subset_iUnion₂ _ _ <| hxU x ·) tfae_have 5 → 1 · intro H convert H.isLocallyClosed.image inducing_subtype_val (by simpa using isClosed_closure.isLocallyClosed) simpa using subset_closure tfae_finish lemma isLocallyClosed_iff_isOpen_coborder : IsLocallyClosed s ↔ IsOpen (coborder s) := (isLocallyClosed_tfae s).out 0 1 alias ⟨IsLocallyClosed.isOpen_coborder, _⟩ := isLocallyClosed_iff_isOpen_coborder lemma IsLocallyClosed.isOpen_preimage_val_closure (hs : IsLocallyClosed s) : IsOpen (closure s ↓∩ s) := ((isLocallyClosed_tfae s).out 0 4).mp hs
Topology\LocallyFinite.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.ContinuousOn import Mathlib.Order.Filter.SmallSets /-! ### Locally finite families of sets We say that a family of sets in a topological space is *locally finite* if at every point `x : X`, there is a neighborhood of `x` which meets only finitely many sets in the family. In this file we give the definition and prove basic properties of locally finite families of sets. -/ -- locally finite family [General Topology (Bourbaki, 1995)] open Set Function Filter Topology variable {ι ι' α X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {f g : ι → Set X} /-- A family of sets in `Set X` is locally finite if at every point `x : X`, there is a neighborhood of `x` which meets only finitely many sets in the family. -/ def LocallyFinite (f : ι → Set X) := ∀ x : X, ∃ t ∈ 𝓝 x, { i | (f i ∩ t).Nonempty }.Finite theorem locallyFinite_of_finite [Finite ι] (f : ι → Set X) : LocallyFinite f := fun _ => ⟨univ, univ_mem, toFinite _⟩ namespace LocallyFinite theorem point_finite (hf : LocallyFinite f) (x : X) : { b | x ∈ f b }.Finite := let ⟨_t, hxt, ht⟩ := hf x ht.subset fun _b hb => ⟨x, hb, mem_of_mem_nhds hxt⟩ protected theorem subset (hf : LocallyFinite f) (hg : ∀ i, g i ⊆ f i) : LocallyFinite g := fun a => let ⟨t, ht₁, ht₂⟩ := hf a ⟨t, ht₁, ht₂.subset fun i hi => hi.mono <| inter_subset_inter (hg i) Subset.rfl⟩ theorem comp_injOn {g : ι' → ι} (hf : LocallyFinite f) (hg : InjOn g { i | (f (g i)).Nonempty }) : LocallyFinite (f ∘ g) := fun x => by let ⟨t, htx, htf⟩ := hf x refine ⟨t, htx, htf.preimage <| ?_⟩ exact hg.mono fun i (hi : Set.Nonempty _) => hi.left theorem comp_injective {g : ι' → ι} (hf : LocallyFinite f) (hg : Injective g) : LocallyFinite (f ∘ g) := hf.comp_injOn hg.injOn theorem _root_.locallyFinite_iff_smallSets : LocallyFinite f ↔ ∀ x, ∀ᶠ s in (𝓝 x).smallSets, { i | (f i ∩ s).Nonempty }.Finite := forall_congr' fun _ => Iff.symm <| eventually_smallSets' fun _s _t hst ht => ht.subset fun _i hi => hi.mono <| inter_subset_inter_right _ hst protected theorem eventually_smallSets (hf : LocallyFinite f) (x : X) : ∀ᶠ s in (𝓝 x).smallSets, { i | (f i ∩ s).Nonempty }.Finite := locallyFinite_iff_smallSets.mp hf x theorem exists_mem_basis {ι' : Sort*} (hf : LocallyFinite f) {p : ι' → Prop} {s : ι' → Set X} {x : X} (hb : (𝓝 x).HasBasis p s) : ∃ i, p i ∧ { j | (f j ∩ s i).Nonempty }.Finite := let ⟨i, hpi, hi⟩ := hb.smallSets.eventually_iff.mp (hf.eventually_smallSets x) ⟨i, hpi, hi Subset.rfl⟩ protected theorem nhdsWithin_iUnion (hf : LocallyFinite f) (a : X) : 𝓝[⋃ i, f i] a = ⨆ i, 𝓝[f i] a := by rcases hf a with ⟨U, haU, hfin⟩ refine le_antisymm ?_ (Monotone.le_map_iSup fun _ _ ↦ nhdsWithin_mono _) calc 𝓝[⋃ i, f i] a = 𝓝[⋃ i, f i ∩ U] a := by rw [← iUnion_inter, ← nhdsWithin_inter_of_mem' (nhdsWithin_le_nhds haU)] _ = 𝓝[⋃ i ∈ {j | (f j ∩ U).Nonempty}, (f i ∩ U)] a := by simp only [mem_setOf_eq, iUnion_nonempty_self] _ = ⨆ i ∈ {j | (f j ∩ U).Nonempty}, 𝓝[f i ∩ U] a := nhdsWithin_biUnion hfin _ _ _ ≤ ⨆ i, 𝓝[f i ∩ U] a := iSup₂_le_iSup _ _ _ ≤ ⨆ i, 𝓝[f i] a := iSup_mono fun i ↦ nhdsWithin_mono _ inter_subset_left theorem continuousOn_iUnion' {g : X → Y} (hf : LocallyFinite f) (hc : ∀ i x, x ∈ closure (f i) → ContinuousWithinAt g (f i) x) : ContinuousOn g (⋃ i, f i) := by rintro x - rw [ContinuousWithinAt, hf.nhdsWithin_iUnion, tendsto_iSup] intro i by_cases hx : x ∈ closure (f i) · exact hc i _ hx · rw [mem_closure_iff_nhdsWithin_neBot, not_neBot] at hx rw [hx] exact tendsto_bot theorem continuousOn_iUnion {g : X → Y} (hf : LocallyFinite f) (h_cl : ∀ i, IsClosed (f i)) (h_cont : ∀ i, ContinuousOn g (f i)) : ContinuousOn g (⋃ i, f i) := hf.continuousOn_iUnion' fun i x hx ↦ h_cont i x <| (h_cl i).closure_subset hx protected theorem continuous' {g : X → Y} (hf : LocallyFinite f) (h_cov : ⋃ i, f i = univ) (hc : ∀ i x, x ∈ closure (f i) → ContinuousWithinAt g (f i) x) : Continuous g := continuous_iff_continuousOn_univ.2 <| h_cov ▸ hf.continuousOn_iUnion' hc protected theorem continuous {g : X → Y} (hf : LocallyFinite f) (h_cov : ⋃ i, f i = univ) (h_cl : ∀ i, IsClosed (f i)) (h_cont : ∀ i, ContinuousOn g (f i)) : Continuous g := continuous_iff_continuousOn_univ.2 <| h_cov ▸ hf.continuousOn_iUnion h_cl h_cont protected theorem closure (hf : LocallyFinite f) : LocallyFinite fun i => closure (f i) := by intro x rcases hf x with ⟨s, hsx, hsf⟩ refine ⟨interior s, interior_mem_nhds.2 hsx, hsf.subset fun i hi => ?_⟩ exact (hi.mono isOpen_interior.closure_inter).of_closure.mono (inter_subset_inter_right _ interior_subset) theorem closure_iUnion (h : LocallyFinite f) : closure (⋃ i, f i) = ⋃ i, closure (f i) := by ext x simp only [mem_closure_iff_nhdsWithin_neBot, h.nhdsWithin_iUnion, iSup_neBot, mem_iUnion] theorem isClosed_iUnion (hf : LocallyFinite f) (hc : ∀ i, IsClosed (f i)) : IsClosed (⋃ i, f i) := by simp only [← closure_eq_iff_isClosed, hf.closure_iUnion, (hc _).closure_eq] /-- If `f : β → Set α` is a locally finite family of closed sets, then for any `x : α`, the intersection of the complements to `f i`, `x ∉ f i`, is a neighbourhood of `x`. -/ theorem iInter_compl_mem_nhds (hf : LocallyFinite f) (hc : ∀ i, IsClosed (f i)) (x : X) : (⋂ (i) (_ : x ∉ f i), (f i)ᶜ) ∈ 𝓝 x := by refine IsOpen.mem_nhds ?_ (mem_iInter₂.2 fun i => id) suffices IsClosed (⋃ i : { i // x ∉ f i }, f i) by rwa [← isOpen_compl_iff, compl_iUnion, iInter_subtype] at this exact (hf.comp_injective Subtype.val_injective).isClosed_iUnion fun i => hc _ /-- Let `f : ℕ → Π a, β a` be a sequence of (dependent) functions on a topological space. Suppose that the family of sets `s n = {x | f (n + 1) x ≠ f n x}` is locally finite. Then there exists a function `F : Π a, β a` such that for any `x`, we have `f n x = F x` on the product of an infinite interval `[N, +∞)` and a neighbourhood of `x`. We formulate the conclusion in terms of the product of filter `Filter.atTop` and `𝓝 x`. -/ theorem exists_forall_eventually_eq_prod {π : X → Sort*} {f : ℕ → ∀ x : X, π x} (hf : LocallyFinite fun n => { x | f (n + 1) x ≠ f n x }) : ∃ F : ∀ x : X, π x, ∀ x, ∀ᶠ p : ℕ × X in atTop ×ˢ 𝓝 x, f p.1 p.2 = F p.2 := by choose U hUx hU using hf choose N hN using fun x => (hU x).bddAbove replace hN : ∀ (x), ∀ n > N x, ∀ y ∈ U x, f (n + 1) y = f n y := fun x n hn y hy => by_contra fun hne => hn.lt.not_le <| hN x ⟨y, hne, hy⟩ replace hN : ∀ (x), ∀ n ≥ N x + 1, ∀ y ∈ U x, f n y = f (N x + 1) y := fun x n hn y hy => Nat.le_induction rfl (fun k hle => (hN x _ hle _ hy).trans) n hn refine ⟨fun x => f (N x + 1) x, fun x => ?_⟩ filter_upwards [Filter.prod_mem_prod (eventually_gt_atTop (N x)) (hUx x)] rintro ⟨n, y⟩ ⟨hn : N x < n, hy : y ∈ U x⟩ calc f n y = f (N x + 1) y := hN _ _ hn _ hy _ = f (max (N x + 1) (N y + 1)) y := (hN _ _ (le_max_left _ _) _ hy).symm _ = f (N y + 1) y := hN _ _ (le_max_right _ _) _ (mem_of_mem_nhds <| hUx y) /-- Let `f : ℕ → Π a, β a` be a sequence of (dependent) functions on a topological space. Suppose that the family of sets `s n = {x | f (n + 1) x ≠ f n x}` is locally finite. Then there exists a function `F : Π a, β a` such that for any `x`, for sufficiently large values of `n`, we have `f n y = F y` in a neighbourhood of `x`. -/ theorem exists_forall_eventually_atTop_eventually_eq' {π : X → Sort*} {f : ℕ → ∀ x : X, π x} (hf : LocallyFinite fun n => { x | f (n + 1) x ≠ f n x }) : ∃ F : ∀ x : X, π x, ∀ x, ∀ᶠ n : ℕ in atTop, ∀ᶠ y : X in 𝓝 x, f n y = F y := hf.exists_forall_eventually_eq_prod.imp fun _F hF x => (hF x).curry /-- Let `f : ℕ → α → β` be a sequence of functions on a topological space. Suppose that the family of sets `s n = {x | f (n + 1) x ≠ f n x}` is locally finite. Then there exists a function `F : α → β` such that for any `x`, for sufficiently large values of `n`, we have `f n =ᶠ[𝓝 x] F`. -/ theorem exists_forall_eventually_atTop_eventuallyEq {f : ℕ → X → α} (hf : LocallyFinite fun n => { x | f (n + 1) x ≠ f n x }) : ∃ F : X → α, ∀ x, ∀ᶠ n : ℕ in atTop, f n =ᶠ[𝓝 x] F := hf.exists_forall_eventually_atTop_eventually_eq' theorem preimage_continuous {g : Y → X} (hf : LocallyFinite f) (hg : Continuous g) : LocallyFinite (g ⁻¹' f ·) := fun x => let ⟨s, hsx, hs⟩ := hf (g x) ⟨g ⁻¹' s, hg.continuousAt hsx, hs.subset fun _ ⟨y, hy⟩ => ⟨g y, hy⟩⟩ theorem prod_right (hf : LocallyFinite f) (g : ι → Set Y) : LocallyFinite (fun i ↦ f i ×ˢ g i) := (hf.preimage_continuous continuous_fst).subset fun _ ↦ prod_subset_preimage_fst _ _ theorem prod_left {g : ι → Set Y} (hg : LocallyFinite g) (f : ι → Set X) : LocallyFinite (fun i ↦ f i ×ˢ g i) := (hg.preimage_continuous continuous_snd).subset fun _ ↦ prod_subset_preimage_snd _ _ end LocallyFinite @[simp] theorem Equiv.locallyFinite_comp_iff (e : ι' ≃ ι) : LocallyFinite (f ∘ e) ↔ LocallyFinite f := ⟨fun h => by simpa only [(· ∘ ·), e.apply_symm_apply] using h.comp_injective e.symm.injective, fun h => h.comp_injective e.injective⟩ theorem locallyFinite_sum {f : ι ⊕ ι' → Set X} : LocallyFinite f ↔ LocallyFinite (f ∘ Sum.inl) ∧ LocallyFinite (f ∘ Sum.inr) := by simp only [locallyFinite_iff_smallSets, ← forall_and, ← finite_preimage_inl_and_inr, preimage_setOf_eq, (· ∘ ·), eventually_and] theorem LocallyFinite.sum_elim {g : ι' → Set X} (hf : LocallyFinite f) (hg : LocallyFinite g) : LocallyFinite (Sum.elim f g) := locallyFinite_sum.mpr ⟨hf, hg⟩ theorem locallyFinite_option {f : Option ι → Set X} : LocallyFinite f ↔ LocallyFinite (f ∘ some) := by rw [← (Equiv.optionEquivSumPUnit.{_, 0} ι).symm.locallyFinite_comp_iff, locallyFinite_sum] simp only [locallyFinite_of_finite, and_true] rfl theorem LocallyFinite.option_elim' (hf : LocallyFinite f) (s : Set X) : LocallyFinite (Option.elim' s f) := locallyFinite_option.2 hf theorem LocallyFinite.eventually_subset {s : ι → Set X} (hs : LocallyFinite s) (hs' : ∀ i, IsClosed (s i)) (x : X) : ∀ᶠ y in 𝓝 x, {i | y ∈ s i} ⊆ {i | x ∈ s i} := by filter_upwards [hs.iInter_compl_mem_nhds hs' x] with y hy i hi simp only [mem_iInter, mem_compl_iff] at hy exact not_imp_not.mp (hy i) hi
Topology\NhdsSet.lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Patrick Massot -/ import Mathlib.Topology.Basic /-! # Neighborhoods of a set In this file we define the filter `𝓝ˢ s` or `nhdsSet s` consisting of all neighborhoods of a set `s`. ## Main Properties There are a couple different notions equivalent to `s ∈ 𝓝ˢ t`: * `s ⊆ interior t` using `subset_interior_iff_mem_nhdsSet` * `∀ x : X, x ∈ t → s ∈ 𝓝 x` using `mem_nhdsSet_iff_forall` * `∃ U : Set X, IsOpen U ∧ t ⊆ U ∧ U ⊆ s` using `mem_nhdsSet_iff_exists` Furthermore, we have the following results: * `monotone_nhdsSet`: `𝓝ˢ` is monotone * In T₁-spaces, `𝓝ˢ`is strictly monotone and hence injective: `strict_mono_nhdsSet`/`injective_nhdsSet`. These results are in `Mathlib.Topology.Separation`. -/ open Set Filter Topology variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {f : Filter X} {s t s₁ s₂ t₁ t₂ : Set X} {x : X} theorem nhdsSet_diagonal (X) [TopologicalSpace (X × X)] : 𝓝ˢ (diagonal X) = ⨆ (x : X), 𝓝 (x, x) := by rw [nhdsSet, ← range_diag, ← range_comp] rfl theorem mem_nhdsSet_iff_forall : s ∈ 𝓝ˢ t ↔ ∀ x : X, x ∈ t → s ∈ 𝓝 x := by simp_rw [nhdsSet, Filter.mem_sSup, forall_mem_image] lemma nhdsSet_le : 𝓝ˢ s ≤ f ↔ ∀ x ∈ s, 𝓝 x ≤ f := by simp [nhdsSet] theorem bUnion_mem_nhdsSet {t : X → Set X} (h : ∀ x ∈ s, t x ∈ 𝓝 x) : (⋃ x ∈ s, t x) ∈ 𝓝ˢ s := mem_nhdsSet_iff_forall.2 fun x hx => mem_of_superset (h x hx) <| subset_iUnion₂ (s := fun x _ => t x) x hx -- Porting note: fails to find `s` theorem subset_interior_iff_mem_nhdsSet : s ⊆ interior t ↔ t ∈ 𝓝ˢ s := by simp_rw [mem_nhdsSet_iff_forall, subset_interior_iff_nhds] theorem disjoint_principal_nhdsSet : Disjoint (𝓟 s) (𝓝ˢ t) ↔ Disjoint (closure s) t := by rw [disjoint_principal_left, ← subset_interior_iff_mem_nhdsSet, interior_compl, subset_compl_iff_disjoint_left] theorem disjoint_nhdsSet_principal : Disjoint (𝓝ˢ s) (𝓟 t) ↔ Disjoint s (closure t) := by rw [disjoint_comm, disjoint_principal_nhdsSet, disjoint_comm] theorem mem_nhdsSet_iff_exists : s ∈ 𝓝ˢ t ↔ ∃ U : Set X, IsOpen U ∧ t ⊆ U ∧ U ⊆ s := by rw [← subset_interior_iff_mem_nhdsSet, subset_interior_iff] /-- A proposition is true on a set neighborhood of `s` iff it is true on a larger open set -/ theorem eventually_nhdsSet_iff_exists {p : X → Prop} : (∀ᶠ x in 𝓝ˢ s, p x) ↔ ∃ t, IsOpen t ∧ s ⊆ t ∧ ∀ x, x ∈ t → p x := mem_nhdsSet_iff_exists /-- A proposition is true on a set neighborhood of `s` iff it is eventually true near each point in the set. -/ theorem eventually_nhdsSet_iff_forall {p : X → Prop} : (∀ᶠ x in 𝓝ˢ s, p x) ↔ ∀ x, x ∈ s → ∀ᶠ y in 𝓝 x, p y := mem_nhdsSet_iff_forall theorem hasBasis_nhdsSet (s : Set X) : (𝓝ˢ s).HasBasis (fun U => IsOpen U ∧ s ⊆ U) fun U => U := ⟨fun t => by simp [mem_nhdsSet_iff_exists, and_assoc]⟩ @[simp] lemma lift'_nhdsSet_interior (s : Set X) : (𝓝ˢ s).lift' interior = 𝓝ˢ s := (hasBasis_nhdsSet s).lift'_interior_eq_self fun _ ↦ And.left lemma Filter.HasBasis.nhdsSet_interior {ι : Sort*} {p : ι → Prop} {s : ι → Set X} {t : Set X} (h : (𝓝ˢ t).HasBasis p s) : (𝓝ˢ t).HasBasis p (interior <| s ·) := lift'_nhdsSet_interior t ▸ h.lift'_interior theorem IsOpen.mem_nhdsSet (hU : IsOpen s) : s ∈ 𝓝ˢ t ↔ t ⊆ s := by rw [← subset_interior_iff_mem_nhdsSet, hU.interior_eq] /-- An open set belongs to its own set neighborhoods filter. -/ theorem IsOpen.mem_nhdsSet_self (ho : IsOpen s) : s ∈ 𝓝ˢ s := ho.mem_nhdsSet.mpr Subset.rfl theorem principal_le_nhdsSet : 𝓟 s ≤ 𝓝ˢ s := fun _s hs => (subset_interior_iff_mem_nhdsSet.mpr hs).trans interior_subset theorem subset_of_mem_nhdsSet (h : t ∈ 𝓝ˢ s) : s ⊆ t := principal_le_nhdsSet h theorem Filter.Eventually.self_of_nhdsSet {p : X → Prop} (h : ∀ᶠ x in 𝓝ˢ s, p x) : ∀ x ∈ s, p x := principal_le_nhdsSet h nonrec theorem Filter.EventuallyEq.self_of_nhdsSet {Y} {f g : X → Y} (h : f =ᶠ[𝓝ˢ s] g) : EqOn f g s := h.self_of_nhdsSet @[simp] theorem nhdsSet_eq_principal_iff : 𝓝ˢ s = 𝓟 s ↔ IsOpen s := by rw [← principal_le_nhdsSet.le_iff_eq, le_principal_iff, mem_nhdsSet_iff_forall, isOpen_iff_mem_nhds] alias ⟨_, IsOpen.nhdsSet_eq⟩ := nhdsSet_eq_principal_iff @[simp] theorem nhdsSet_interior : 𝓝ˢ (interior s) = 𝓟 (interior s) := isOpen_interior.nhdsSet_eq @[simp] theorem nhdsSet_singleton : 𝓝ˢ {x} = 𝓝 x := by simp [nhdsSet] theorem mem_nhdsSet_interior : s ∈ 𝓝ˢ (interior s) := subset_interior_iff_mem_nhdsSet.mp Subset.rfl @[simp] theorem nhdsSet_empty : 𝓝ˢ (∅ : Set X) = ⊥ := by rw [isOpen_empty.nhdsSet_eq, principal_empty] theorem mem_nhdsSet_empty : s ∈ 𝓝ˢ (∅ : Set X) := by simp @[simp] theorem nhdsSet_univ : 𝓝ˢ (univ : Set X) = ⊤ := by rw [isOpen_univ.nhdsSet_eq, principal_univ] @[mono] theorem nhdsSet_mono (h : s ⊆ t) : 𝓝ˢ s ≤ 𝓝ˢ t := sSup_le_sSup <| image_subset _ h theorem monotone_nhdsSet : Monotone (𝓝ˢ : Set X → Filter X) := fun _ _ => nhdsSet_mono theorem nhds_le_nhdsSet (h : x ∈ s) : 𝓝 x ≤ 𝓝ˢ s := le_sSup <| mem_image_of_mem _ h @[simp] theorem nhdsSet_union (s t : Set X) : 𝓝ˢ (s ∪ t) = 𝓝ˢ s ⊔ 𝓝ˢ t := by simp only [nhdsSet, image_union, sSup_union] theorem union_mem_nhdsSet (h₁ : s₁ ∈ 𝓝ˢ t₁) (h₂ : s₂ ∈ 𝓝ˢ t₂) : s₁ ∪ s₂ ∈ 𝓝ˢ (t₁ ∪ t₂) := by rw [nhdsSet_union] exact union_mem_sup h₁ h₂ @[simp] theorem nhdsSet_insert (x : X) (s : Set X) : 𝓝ˢ (insert x s) = 𝓝 x ⊔ 𝓝ˢ s := by rw [insert_eq, nhdsSet_union, nhdsSet_singleton] /-- Preimage of a set neighborhood of `t` under a continuous map `f` is a set neighborhood of `s` provided that `f` maps `s` to `t`. -/ theorem Continuous.tendsto_nhdsSet {f : X → Y} {t : Set Y} (hf : Continuous f) (hst : MapsTo f s t) : Tendsto f (𝓝ˢ s) (𝓝ˢ t) := ((hasBasis_nhdsSet s).tendsto_iff (hasBasis_nhdsSet t)).mpr fun U hU => ⟨f ⁻¹' U, ⟨hU.1.preimage hf, hst.mono Subset.rfl hU.2⟩, fun _ => id⟩ lemma Continuous.tendsto_nhdsSet_nhds {y : Y} {f : X → Y} (h : Continuous f) (h' : EqOn f (fun _ ↦ y) s) : Tendsto f (𝓝ˢ s) (𝓝 y) := by rw [← nhdsSet_singleton] exact h.tendsto_nhdsSet h' /- This inequality cannot be improved to an equality. For instance, if `X` has two elements and the coarse topology and `s` and `t` are distinct singletons then `𝓝ˢ (s ∩ t) = ⊥` while `𝓝ˢ s ⊓ 𝓝ˢ t = ⊤` and those are different. -/ theorem nhdsSet_inter_le (s t : Set X) : 𝓝ˢ (s ∩ t) ≤ 𝓝ˢ s ⊓ 𝓝ˢ t := (monotone_nhdsSet (X := X)).map_inf_le s t variable (s) in theorem IsClosed.nhdsSet_le_sup (h : IsClosed t) : 𝓝ˢ s ≤ 𝓝ˢ (s ∩ t) ⊔ 𝓟 (tᶜ) := calc 𝓝ˢ s = 𝓝ˢ (s ∩ t ∪ s ∩ tᶜ) := by rw [Set.inter_union_compl s t] _ = 𝓝ˢ (s ∩ t) ⊔ 𝓝ˢ (s ∩ tᶜ) := by rw [nhdsSet_union] _ ≤ 𝓝ˢ (s ∩ t) ⊔ 𝓝ˢ (tᶜ) := sup_le_sup_left (monotone_nhdsSet inter_subset_right) _ _ = 𝓝ˢ (s ∩ t) ⊔ 𝓟 (tᶜ) := by rw [h.isOpen_compl.nhdsSet_eq] variable (s) in theorem IsClosed.nhdsSet_le_sup' (h : IsClosed t) : 𝓝ˢ s ≤ 𝓝ˢ (t ∩ s) ⊔ 𝓟 (tᶜ) := by rw [Set.inter_comm]; exact h.nhdsSet_le_sup s theorem Filter.Eventually.eventually_nhdsSet {p : X → Prop} (h : ∀ᶠ y in 𝓝ˢ s, p y) : ∀ᶠ y in 𝓝ˢ s, ∀ᶠ x in 𝓝 y, p x := eventually_nhdsSet_iff_forall.mpr fun x x_in ↦ (eventually_nhdsSet_iff_forall.mp h x x_in).eventually_nhds theorem Filter.Eventually.union_nhdsSet {p : X → Prop} : (∀ᶠ x in 𝓝ˢ (s ∪ t), p x) ↔ (∀ᶠ x in 𝓝ˢ s, p x) ∧ ∀ᶠ x in 𝓝ˢ t, p x := by rw [nhdsSet_union, eventually_sup] theorem Filter.Eventually.union {p : X → Prop} (hs : ∀ᶠ x in 𝓝ˢ s, p x) (ht : ∀ᶠ x in 𝓝ˢ t, p x) : ∀ᶠ x in 𝓝ˢ (s ∪ t), p x := Filter.Eventually.union_nhdsSet.mpr ⟨hs, ht⟩ theorem nhdsSet_iUnion {ι : Sort*} (s : ι → Set X) : 𝓝ˢ (⋃ i, s i) = ⨆ i, 𝓝ˢ (s i) := by simp only [nhdsSet, image_iUnion, sSup_iUnion (β := Filter X)] theorem eventually_nhdsSet_iUnion₂ {ι : Sort*} {p : ι → Prop} {s : ι → Set X} {P : X → Prop} : (∀ᶠ x in 𝓝ˢ (⋃ (i) (_ : p i), s i), P x) ↔ ∀ i, p i → ∀ᶠ x in 𝓝ˢ (s i), P x := by simp only [nhdsSet_iUnion, eventually_iSup] theorem eventually_nhdsSet_iUnion {ι : Sort*} {s : ι → Set X} {P : X → Prop} : (∀ᶠ x in 𝓝ˢ (⋃ i, s i), P x) ↔ ∀ i, ∀ᶠ x in 𝓝ˢ (s i), P x := by simp only [nhdsSet_iUnion, eventually_iSup]
Topology\NoetherianSpace.lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Topology.Sets.Closeds /-! # Noetherian space A Noetherian space is a topological space that satisfies any of the following equivalent conditions: - `WellFounded ((· > ·) : TopologicalSpace.Opens α → TopologicalSpace.Opens α → Prop)` - `WellFounded ((· < ·) : TopologicalSpace.Closeds α → TopologicalSpace.Closeds α → Prop)` - `∀ s : Set α, IsCompact s` - `∀ s : TopologicalSpace.Opens α, IsCompact s` The first is chosen as the definition, and the equivalence is shown in `TopologicalSpace.noetherianSpace_TFAE`. Many examples of noetherian spaces come from algebraic topology. For example, the underlying space of a noetherian scheme (e.g., the spectrum of a noetherian ring) is noetherian. ## Main Results - `TopologicalSpace.NoetherianSpace.set`: Every subspace of a noetherian space is noetherian. - `TopologicalSpace.NoetherianSpace.isCompact`: Every set in a noetherian space is a compact set. - `TopologicalSpace.noetherianSpace_TFAE`: Describes the equivalent definitions of noetherian spaces. - `TopologicalSpace.NoetherianSpace.range`: The image of a noetherian space under a continuous map is noetherian. - `TopologicalSpace.NoetherianSpace.iUnion`: The finite union of noetherian spaces is noetherian. - `TopologicalSpace.NoetherianSpace.discrete`: A noetherian and Hausdorff space is discrete. - `TopologicalSpace.NoetherianSpace.exists_finset_irreducible`: Every closed subset of a noetherian space is a finite union of irreducible closed subsets. - `TopologicalSpace.NoetherianSpace.finite_irreducibleComponents`: The number of irreducible components of a noetherian space is finite. -/ variable (α β : Type*) [TopologicalSpace α] [TopologicalSpace β] namespace TopologicalSpace /-- Type class for noetherian spaces. It is defined to be spaces whose open sets satisfies ACC. -/ @[mk_iff] class NoetherianSpace : Prop where wellFounded_opens : WellFounded ((· > ·) : Opens α → Opens α → Prop) theorem noetherianSpace_iff_opens : NoetherianSpace α ↔ ∀ s : Opens α, IsCompact (s : Set α) := by rw [noetherianSpace_iff, CompleteLattice.wellFounded_iff_isSupFiniteCompact, CompleteLattice.isSupFiniteCompact_iff_all_elements_compact] exact forall_congr' Opens.isCompactElement_iff instance (priority := 100) NoetherianSpace.compactSpace [h : NoetherianSpace α] : CompactSpace α := ⟨(noetherianSpace_iff_opens α).mp h ⊤⟩ variable {α β} /-- In a Noetherian space, all sets are compact. -/ protected theorem NoetherianSpace.isCompact [NoetherianSpace α] (s : Set α) : IsCompact s := by refine isCompact_iff_finite_subcover.2 fun U hUo hs => ?_ rcases ((noetherianSpace_iff_opens α).mp ‹_› ⟨⋃ i, U i, isOpen_iUnion hUo⟩).elim_finite_subcover U hUo Set.Subset.rfl with ⟨t, ht⟩ exact ⟨t, hs.trans ht⟩ -- Porting note: fixed NS protected theorem _root_.Inducing.noetherianSpace [NoetherianSpace α] {i : β → α} (hi : Inducing i) : NoetherianSpace β := (noetherianSpace_iff_opens _).2 fun _ => hi.isCompact_iff.2 (NoetherianSpace.isCompact _) /-- [Stacks: Lemma 0052 (1)](https://stacks.math.columbia.edu/tag/0052)-/ instance NoetherianSpace.set [NoetherianSpace α] (s : Set α) : NoetherianSpace s := inducing_subtype_val.noetherianSpace variable (α) open List in theorem noetherianSpace_TFAE : TFAE [NoetherianSpace α, WellFounded fun s t : Closeds α => s < t, ∀ s : Set α, IsCompact s, ∀ s : Opens α, IsCompact (s : Set α)] := by tfae_have 1 ↔ 2 · refine (noetherianSpace_iff α).trans (Opens.compl_bijective.2.wellFounded_iff ?_) exact (@OrderIso.compl (Set α)).lt_iff_lt.symm tfae_have 1 ↔ 4 · exact noetherianSpace_iff_opens α tfae_have 1 → 3 · exact @NoetherianSpace.isCompact α _ tfae_have 3 → 4 · exact fun h s => h s tfae_finish variable {α} theorem noetherianSpace_iff_isCompact : NoetherianSpace α ↔ ∀ s : Set α, IsCompact s := (noetherianSpace_TFAE α).out 0 2 theorem NoetherianSpace.wellFounded_closeds [NoetherianSpace α] : WellFounded fun s t : Closeds α => s < t := Iff.mp ((noetherianSpace_TFAE α).out 0 1) ‹_› instance {α} : NoetherianSpace (CofiniteTopology α) := by simp only [noetherianSpace_iff_isCompact, isCompact_iff_ultrafilter_le_nhds, CofiniteTopology.nhds_eq, Ultrafilter.le_sup_iff, Filter.le_principal_iff] intro s f hs rcases f.le_cofinite_or_eq_pure with (hf | ⟨a, rfl⟩) · rcases Filter.nonempty_of_mem hs with ⟨a, ha⟩ exact ⟨a, ha, Or.inr hf⟩ · exact ⟨a, hs, Or.inl le_rfl⟩ theorem noetherianSpace_of_surjective [NoetherianSpace α] (f : α → β) (hf : Continuous f) (hf' : Function.Surjective f) : NoetherianSpace β := noetherianSpace_iff_isCompact.2 <| (Set.image_surjective.mpr hf').forall.2 fun s => (NoetherianSpace.isCompact s).image hf theorem noetherianSpace_iff_of_homeomorph (f : α ≃ₜ β) : NoetherianSpace α ↔ NoetherianSpace β := ⟨fun _ => noetherianSpace_of_surjective f f.continuous f.surjective, fun _ => noetherianSpace_of_surjective f.symm f.symm.continuous f.symm.surjective⟩ theorem NoetherianSpace.range [NoetherianSpace α] (f : α → β) (hf : Continuous f) : NoetherianSpace (Set.range f) := noetherianSpace_of_surjective (Set.rangeFactorization f) (hf.subtype_mk _) Set.surjective_onto_range theorem noetherianSpace_set_iff (s : Set α) : NoetherianSpace s ↔ ∀ t, t ⊆ s → IsCompact t := by simp only [noetherianSpace_iff_isCompact, embedding_subtype_val.isCompact_iff, Subtype.forall_set_subtype] @[simp] theorem noetherian_univ_iff : NoetherianSpace (Set.univ : Set α) ↔ NoetherianSpace α := noetherianSpace_iff_of_homeomorph (Homeomorph.Set.univ α) theorem NoetherianSpace.iUnion {ι : Type*} (f : ι → Set α) [Finite ι] [hf : ∀ i, NoetherianSpace (f i)] : NoetherianSpace (⋃ i, f i) := by simp_rw [noetherianSpace_set_iff] at hf ⊢ intro t ht rw [← Set.inter_eq_left.mpr ht, Set.inter_iUnion] exact isCompact_iUnion fun i => hf i _ Set.inter_subset_right -- This is not an instance since it makes a loop with `t2_space_discrete`. theorem NoetherianSpace.discrete [NoetherianSpace α] [T2Space α] : DiscreteTopology α := ⟨eq_bot_iff.mpr fun _ _ => isClosed_compl_iff.mp (NoetherianSpace.isCompact _).isClosed⟩ attribute [local instance] NoetherianSpace.discrete /-- Spaces that are both Noetherian and Hausdorff are finite. -/ theorem NoetherianSpace.finite [NoetherianSpace α] [T2Space α] : Finite α := Finite.of_finite_univ (NoetherianSpace.isCompact Set.univ).finite_of_discrete instance (priority := 100) Finite.to_noetherianSpace [Finite α] : NoetherianSpace α := ⟨Finite.wellFounded_of_trans_of_irrefl _⟩ /-- In a Noetherian space, every closed set is a finite union of irreducible closed sets. -/ theorem NoetherianSpace.exists_finite_set_closeds_irreducible [NoetherianSpace α] (s : Closeds α) : ∃ S : Set (Closeds α), S.Finite ∧ (∀ t ∈ S, IsIrreducible (t : Set α)) ∧ s = sSup S := by apply wellFounded_closeds.induction s; clear s intro s H rcases eq_or_ne s ⊥ with rfl | h₀ · use ∅; simp · by_cases h₁ : IsPreirreducible (s : Set α) · replace h₁ : IsIrreducible (s : Set α) := ⟨Closeds.coe_nonempty.2 h₀, h₁⟩ use {s}; simp [h₁] · simp only [isPreirreducible_iff_closed_union_closed, not_forall, not_or] at h₁ obtain ⟨z₁, z₂, hz₁, hz₂, h, hz₁', hz₂'⟩ := h₁ lift z₁ to Closeds α using hz₁ lift z₂ to Closeds α using hz₂ rcases H (s ⊓ z₁) (inf_lt_left.2 hz₁') with ⟨S₁, hSf₁, hS₁, h₁⟩ rcases H (s ⊓ z₂) (inf_lt_left.2 hz₂') with ⟨S₂, hSf₂, hS₂, h₂⟩ refine ⟨S₁ ∪ S₂, hSf₁.union hSf₂, Set.union_subset_iff.2 ⟨hS₁, hS₂⟩, ?_⟩ rwa [sSup_union, ← h₁, ← h₂, ← inf_sup_left, left_eq_inf] /-- In a Noetherian space, every closed set is a finite union of irreducible closed sets. -/ theorem NoetherianSpace.exists_finite_set_isClosed_irreducible [NoetherianSpace α] {s : Set α} (hs : IsClosed s) : ∃ S : Set (Set α), S.Finite ∧ (∀ t ∈ S, IsClosed t) ∧ (∀ t ∈ S, IsIrreducible t) ∧ s = ⋃₀ S := by lift s to Closeds α using hs rcases NoetherianSpace.exists_finite_set_closeds_irreducible s with ⟨S, hSf, hS, rfl⟩ refine ⟨(↑) '' S, hSf.image _, Set.forall_mem_image.2 fun S _ ↦ S.2, Set.forall_mem_image.2 hS, ?_⟩ lift S to Finset (Closeds α) using hSf simp [← Finset.sup_id_eq_sSup, Closeds.coe_finset_sup] /-- In a Noetherian space, every closed set is a finite union of irreducible closed sets. -/ theorem NoetherianSpace.exists_finset_irreducible [NoetherianSpace α] (s : Closeds α) : ∃ S : Finset (Closeds α), (∀ k : S, IsIrreducible (k : Set α)) ∧ s = S.sup id := by simpa [Set.exists_finite_iff_finset, Finset.sup_id_eq_sSup] using NoetherianSpace.exists_finite_set_closeds_irreducible s /-- [Stacks: Lemma 0052 (2)](https://stacks.math.columbia.edu/tag/0052) -/ theorem NoetherianSpace.finite_irreducibleComponents [NoetherianSpace α] : (irreducibleComponents α).Finite := by obtain ⟨S : Set (Set α), hSf, hSc, hSi, hSU⟩ := NoetherianSpace.exists_finite_set_isClosed_irreducible isClosed_univ (α := α) refine hSf.subset fun s hs => ?_ lift S to Finset (Set α) using hSf rcases isIrreducible_iff_sUnion_closed.1 hs.1 S hSc (hSU ▸ Set.subset_univ _) with ⟨t, htS, ht⟩ rwa [ht.antisymm (hs.2 (hSi _ htS) ht)] /-- [Stacks: Lemma 0052 (3)](https://stacks.math.columbia.edu/tag/0052) -/ theorem NoetherianSpace.exists_open_ne_empty_le_irreducibleComponent [NoetherianSpace α] (Z : Set α) (H : Z ∈ irreducibleComponents α) : ∃ o : Set α, IsOpen o ∧ o ≠ ∅ ∧ o ≤ Z := by classical let ι : Set (Set α) := irreducibleComponents α \ {Z} have hι : ι.Finite := NoetherianSpace.finite_irreducibleComponents.subset Set.diff_subset have hι' : Finite ι := by rwa [Set.finite_coe_iff] let U := Z \ ⋃ (x : ι), x have hU0 : U ≠ ∅ := fun r ↦ by obtain ⟨Z', hZ'⟩ := isIrreducible_iff_sUnion_closed.mp H.1 hι.toFinset (fun z hz ↦ by simp only [Set.Finite.mem_toFinset, Set.mem_diff, Set.mem_singleton_iff] at hz exact isClosed_of_mem_irreducibleComponents _ hz.1) (by rw [Set.Finite.coe_toFinset, Set.sUnion_eq_iUnion] rw [Set.diff_eq_empty] at r exact r) simp only [Set.Finite.mem_toFinset, Set.mem_diff, Set.mem_singleton_iff] at hZ' exact hZ'.1.2 <| le_antisymm (H.2 hZ'.1.1.1 hZ'.2) hZ'.2 have hU1 : U = (⋃ (x : ι), x.1) ᶜ := by rw [Set.compl_eq_univ_diff] refine le_antisymm (Set.diff_subset_diff le_top <| subset_refl _) ?_ rw [← Set.compl_eq_univ_diff] refine Set.compl_subset_iff_union.mpr (le_antisymm le_top ?_) rw [Set.union_comm, ← Set.sUnion_eq_iUnion, ← Set.sUnion_insert] rintro a - by_cases h : a ∈ U · exact ⟨U, Set.mem_insert _ _, h⟩ · rw [Set.mem_diff, Decidable.not_and_iff_or_not_not, not_not, Set.mem_iUnion] at h rcases h with (h|⟨i, hi⟩) · refine ⟨irreducibleComponent a, Or.inr ?_, mem_irreducibleComponent⟩ simp only [ι, Set.mem_diff, Set.mem_singleton_iff] refine ⟨irreducibleComponent_mem_irreducibleComponents _, ?_⟩ rintro rfl exact h mem_irreducibleComponent · exact ⟨i, Or.inr i.2, hi⟩ refine ⟨U, hU1 ▸ isOpen_compl_iff.mpr ?_, hU0, sdiff_le⟩ exact isClosed_iUnion_of_finite fun i ↦ isClosed_of_mem_irreducibleComponents i.1 i.2.1 end TopologicalSpace
Topology\OmegaCompletePartialOrder.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Topology.Basic import Mathlib.Order.UpperLower.Basic import Mathlib.Order.OmegaCompletePartialOrder /-! # Scott Topological Spaces A type of topological spaces whose notion of continuity is equivalent to continuity in ωCPOs. ## Reference * https://ncatlab.org/nlab/show/Scott+topology -/ open Set OmegaCompletePartialOrder open scoped Classical universe u -- "Scott", "ωSup" namespace Scott /-- `x` is an `ω`-Sup of a chain `c` if it is the least upper bound of the range of `c`. -/ def IsωSup {α : Type u} [Preorder α] (c : Chain α) (x : α) : Prop := (∀ i, c i ≤ x) ∧ ∀ y, (∀ i, c i ≤ y) → x ≤ y theorem isωSup_iff_isLUB {α : Type u} [Preorder α] {c : Chain α} {x : α} : IsωSup c x ↔ IsLUB (range c) x := by simp [IsωSup, IsLUB, IsLeast, upperBounds, lowerBounds] variable (α : Type u) [OmegaCompletePartialOrder α] /-- The characteristic function of open sets is monotone and preserves the limits of chains. -/ def IsOpen (s : Set α) : Prop := Continuous' fun x ↦ x ∈ s theorem isOpen_univ : IsOpen α univ := ⟨fun _ _ _ _ ↦ mem_univ _, @CompleteLattice.top_continuous α Prop _ _⟩ theorem IsOpen.inter (s t : Set α) : IsOpen α s → IsOpen α t → IsOpen α (s ∩ t) := CompleteLattice.inf_continuous' theorem isOpen_sUnion (s : Set (Set α)) (hs : ∀ t ∈ s, IsOpen α t) : IsOpen α (⋃₀ s) := by simp only [IsOpen] at hs ⊢ convert CompleteLattice.sSup_continuous' (setOf ⁻¹' s) hs simp only [sSup_apply, setOf_bijective.surjective.exists, exists_prop, mem_preimage, SetCoe.exists, iSup_Prop_eq, mem_setOf_eq, mem_sUnion] theorem IsOpen.isUpperSet {s : Set α} (hs : IsOpen α s) : IsUpperSet s := hs.fst end Scott /-- A Scott topological space is defined on preorders such that their open sets, seen as a function `α → Prop`, preserves the joins of ω-chains -/ abbrev Scott (α : Type u) := α instance Scott.topologicalSpace (α : Type u) [OmegaCompletePartialOrder α] : TopologicalSpace (Scott α) where IsOpen := Scott.IsOpen α isOpen_univ := Scott.isOpen_univ α isOpen_inter := Scott.IsOpen.inter α isOpen_sUnion := Scott.isOpen_sUnion α section notBelow variable {α : Type*} [OmegaCompletePartialOrder α] (y : Scott α) /-- `notBelow` is an open set in `Scott α` used to prove the monotonicity of continuous functions -/ def notBelow := { x | ¬x ≤ y } theorem notBelow_isOpen : IsOpen (notBelow y) := by have h : Monotone (notBelow y) := fun x z hle ↦ mt hle.trans refine ⟨h, fun c ↦ eq_of_forall_ge_iff fun z ↦ ?_⟩ simp only [ωSup_le_iff, notBelow, mem_setOf_eq, le_Prop_eq, OrderHom.coe_mk, Chain.map_coe, Function.comp_apply, exists_imp, not_forall] end notBelow open Scott hiding IsOpen open OmegaCompletePartialOrder theorem isωSup_ωSup {α} [OmegaCompletePartialOrder α] (c : Chain α) : IsωSup c (ωSup c) := by constructor · apply le_ωSup · apply ωSup_le theorem scottContinuous_of_continuous {α β} [OmegaCompletePartialOrder α] [OmegaCompletePartialOrder β] (f : Scott α → Scott β) (hf : Continuous f) : OmegaCompletePartialOrder.Continuous' f := by have h : Monotone f := fun x y h ↦ by have hf : IsUpperSet {x | ¬f x ≤ f y} := ((notBelow_isOpen (f y)).preimage hf).isUpperSet simpa only [mem_setOf_eq, le_refl, not_true, imp_false, not_not] using hf h refine ⟨h, fun c ↦ eq_of_forall_ge_iff fun z ↦ ?_⟩ rcases (notBelow_isOpen z).preimage hf with ⟨hf, hf'⟩ specialize hf' c simp only [OrderHom.coe_mk, mem_preimage, notBelow, mem_setOf_eq] at hf' rw [← not_iff_not] simp only [ωSup_le_iff, hf', ωSup, iSup, sSup, mem_range, Chain.map_coe, Function.comp_apply, eq_iff_iff, not_forall, OrderHom.coe_mk] tauto theorem continuous_of_scottContinuous {α β} [OmegaCompletePartialOrder α] [OmegaCompletePartialOrder β] (f : Scott α → Scott β) (hf : OmegaCompletePartialOrder.Continuous' f) : Continuous f := by rw [continuous_def] intro s hs change Continuous' (s ∘ f) cases' hs with hs hs' cases' hf with hf hf' apply Continuous.of_bundled apply continuous_comp _ _ hf' hs'
Topology\Order.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Topology.Defs.Induced import Mathlib.Topology.Basic /-! # Ordering on topologies and (co)induced topologies Topologies on a fixed type `α` are ordered, by reverse inclusion. That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂` if every set open in `t₂` is also open in `t₁`. (One also calls `t₁` *finer* than `t₂`, and `t₂` *coarser* than `t₁`.) Any function `f : α → β` induces * `TopologicalSpace.induced f : TopologicalSpace β → TopologicalSpace α`; * `TopologicalSpace.coinduced f : TopologicalSpace α → TopologicalSpace β`. Continuity, the ordering on topologies and (co)induced topologies are related as follows: * The identity map `(α, t₁) → (α, t₂)` is continuous iff `t₁ ≤ t₂`. * A map `f : (α, t) → (β, u)` is continuous * iff `t ≤ TopologicalSpace.induced f u` (`continuous_iff_le_induced`) * iff `TopologicalSpace.coinduced f t ≤ u` (`continuous_iff_coinduced_le`). Topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. For a function `f : α → β`, `(TopologicalSpace.coinduced f, TopologicalSpace.induced f)` is a Galois connection between topologies on `α` and topologies on `β`. ## Implementation notes There is a Galois insertion between topologies on `α` (with the inclusion ordering) and all collections of sets in `α`. The complete lattice structure on topologies on `α` is defined as the reverse of the one obtained via this Galois insertion. More precisely, we use the corresponding Galois coinsertion between topologies on `α` (with the reversed inclusion ordering) and collections of sets in `α` (with the reversed inclusion ordering). ## Tags finer, coarser, induced topology, coinduced topology -/ open Function Set Filter Topology universe u v w namespace TopologicalSpace variable {α : Type u} /-- The open sets of the least topology containing a collection of basic sets. -/ inductive GenerateOpen (g : Set (Set α)) : Set α → Prop | basic : ∀ s ∈ g, GenerateOpen g s | univ : GenerateOpen g univ | inter : ∀ s t, GenerateOpen g s → GenerateOpen g t → GenerateOpen g (s ∩ t) | sUnion : ∀ S : Set (Set α), (∀ s ∈ S, GenerateOpen g s) → GenerateOpen g (⋃₀ S) /-- The smallest topological space containing the collection `g` of basic sets -/ def generateFrom (g : Set (Set α)) : TopologicalSpace α where IsOpen := GenerateOpen g isOpen_univ := GenerateOpen.univ isOpen_inter := GenerateOpen.inter isOpen_sUnion := GenerateOpen.sUnion theorem isOpen_generateFrom_of_mem {g : Set (Set α)} {s : Set α} (hs : s ∈ g) : IsOpen[generateFrom g] s := GenerateOpen.basic s hs theorem nhds_generateFrom {g : Set (Set α)} {a : α} : @nhds α (generateFrom g) a = ⨅ s ∈ { s | a ∈ s ∧ s ∈ g }, 𝓟 s := by letI := generateFrom g rw [nhds_def] refine le_antisymm (biInf_mono fun s ⟨as, sg⟩ => ⟨as, .basic _ sg⟩) <| le_iInf₂ ?_ rintro s ⟨ha, hs⟩ induction hs with | basic _ hs => exact iInf₂_le _ ⟨ha, hs⟩ | univ => exact le_top.trans_eq principal_univ.symm | inter _ _ _ _ hs ht => exact (le_inf (hs ha.1) (ht ha.2)).trans_eq inf_principal | sUnion _ _ hS => let ⟨t, htS, hat⟩ := ha exact (hS t htS hat).trans (principal_mono.2 <| subset_sUnion_of_mem htS) lemma tendsto_nhds_generateFrom_iff {β : Type*} {m : α → β} {f : Filter α} {g : Set (Set β)} {b : β} : Tendsto m f (@nhds β (generateFrom g) b) ↔ ∀ s ∈ g, b ∈ s → m ⁻¹' s ∈ f := by simp only [nhds_generateFrom, @forall_swap (b ∈ _), tendsto_iInf, mem_setOf_eq, and_imp, tendsto_principal]; rfl @[deprecated (since := "2023-12-24")] alias ⟨_, tendsto_nhds_generateFrom⟩ := tendsto_nhds_generateFrom_iff /-- Construct a topology on α given the filter of neighborhoods of each point of α. -/ protected def mkOfNhds (n : α → Filter α) : TopologicalSpace α where IsOpen s := ∀ a ∈ s, s ∈ n a isOpen_univ _ _ := univ_mem isOpen_inter := fun _s _t hs ht x ⟨hxs, hxt⟩ => inter_mem (hs x hxs) (ht x hxt) isOpen_sUnion := fun _s hs _a ⟨x, hx, hxa⟩ => mem_of_superset (hs x hx _ hxa) (subset_sUnion_of_mem hx) theorem nhds_mkOfNhds_of_hasBasis {n : α → Filter α} {ι : α → Sort*} {p : ∀ a, ι a → Prop} {s : ∀ a, ι a → Set α} (hb : ∀ a, (n a).HasBasis (p a) (s a)) (hpure : ∀ a i, p a i → a ∈ s a i) (hopen : ∀ a i, p a i → ∀ᶠ x in n a, s a i ∈ n x) (a : α) : @nhds α (.mkOfNhds n) a = n a := by let t : TopologicalSpace α := .mkOfNhds n apply le_antisymm · intro U hU replace hpure : pure ≤ n := fun x ↦ (hb x).ge_iff.2 (hpure x) refine mem_nhds_iff.2 ⟨{x | U ∈ n x}, fun x hx ↦ hpure x hx, fun x hx ↦ ?_, hU⟩ rcases (hb x).mem_iff.1 hx with ⟨i, hpi, hi⟩ exact (hopen x i hpi).mono fun y hy ↦ mem_of_superset hy hi · exact (nhds_basis_opens a).ge_iff.2 fun U ⟨haU, hUo⟩ ↦ hUo a haU theorem nhds_mkOfNhds (n : α → Filter α) (a : α) (h₀ : pure ≤ n) (h₁ : ∀ a, ∀ s ∈ n a, ∀ᶠ y in n a, s ∈ n y) : @nhds α (TopologicalSpace.mkOfNhds n) a = n a := nhds_mkOfNhds_of_hasBasis (fun a ↦ (n a).basis_sets) h₀ h₁ _ theorem nhds_mkOfNhds_single [DecidableEq α] {a₀ : α} {l : Filter α} (h : pure a₀ ≤ l) (b : α) : @nhds α (TopologicalSpace.mkOfNhds (update pure a₀ l)) b = (update pure a₀ l : α → Filter α) b := by refine nhds_mkOfNhds _ _ (le_update_iff.mpr ⟨h, fun _ _ => le_rfl⟩) fun a s hs => ?_ rcases eq_or_ne a a₀ with (rfl | ha) · filter_upwards [hs] with b hb rcases eq_or_ne b a with (rfl | hb) · exact hs · rwa [update_noteq hb] · simpa only [update_noteq ha, mem_pure, eventually_pure] using hs theorem nhds_mkOfNhds_filterBasis (B : α → FilterBasis α) (a : α) (h₀ : ∀ x, ∀ n ∈ B x, x ∈ n) (h₁ : ∀ x, ∀ n ∈ B x, ∃ n₁ ∈ B x, ∀ x' ∈ n₁, ∃ n₂ ∈ B x', n₂ ⊆ n) : @nhds α (TopologicalSpace.mkOfNhds fun x => (B x).filter) a = (B a).filter := nhds_mkOfNhds_of_hasBasis (fun a ↦ (B a).hasBasis) h₀ h₁ a section Lattice variable {α : Type u} {β : Type v} /-- The ordering on topologies on the type `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : PartialOrder (TopologicalSpace α) := { PartialOrder.lift (fun t => OrderDual.toDual IsOpen[t]) (fun _ _ => TopologicalSpace.ext) with le := fun s t => ∀ U, IsOpen[t] U → IsOpen[s] U } protected theorem le_def {α} {t s : TopologicalSpace α} : t ≤ s ↔ IsOpen[s] ≤ IsOpen[t] := Iff.rfl theorem le_generateFrom_iff_subset_isOpen {g : Set (Set α)} {t : TopologicalSpace α} : t ≤ generateFrom g ↔ g ⊆ { s | IsOpen[t] s } := ⟨fun ht s hs => ht _ <| .basic s hs, fun hg _s hs => hs.recOn (fun _ h => hg h) isOpen_univ (fun _ _ _ _ => IsOpen.inter) fun _ _ => isOpen_sUnion⟩ /-- If `s` equals the collection of open sets in the topology it generates, then `s` defines a topology. -/ protected def mkOfClosure (s : Set (Set α)) (hs : { u | GenerateOpen s u } = s) : TopologicalSpace α where IsOpen u := u ∈ s isOpen_univ := hs ▸ TopologicalSpace.GenerateOpen.univ isOpen_inter := hs ▸ TopologicalSpace.GenerateOpen.inter isOpen_sUnion := hs ▸ TopologicalSpace.GenerateOpen.sUnion theorem mkOfClosure_sets {s : Set (Set α)} {hs : { u | GenerateOpen s u } = s} : TopologicalSpace.mkOfClosure s hs = generateFrom s := TopologicalSpace.ext hs.symm theorem gc_generateFrom (α) : GaloisConnection (fun t : TopologicalSpace α => OrderDual.toDual { s | IsOpen[t] s }) (generateFrom ∘ OrderDual.ofDual) := fun _ _ => le_generateFrom_iff_subset_isOpen.symm /-- The Galois coinsertion between `TopologicalSpace α` and `(Set (Set α))ᵒᵈ` whose lower part sends a topology to its collection of open subsets, and whose upper part sends a collection of subsets of `α` to the topology they generate. -/ def gciGenerateFrom (α : Type*) : GaloisCoinsertion (fun t : TopologicalSpace α => OrderDual.toDual { s | IsOpen[t] s }) (generateFrom ∘ OrderDual.ofDual) where gc := gc_generateFrom α u_l_le _ s hs := TopologicalSpace.GenerateOpen.basic s hs choice g hg := TopologicalSpace.mkOfClosure g (Subset.antisymm hg <| le_generateFrom_iff_subset_isOpen.1 <| le_rfl) choice_eq _ _ := mkOfClosure_sets /-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of topologies is the topology generated by all their open sets, while the supremum is the topology whose open sets are those sets open in every member of the collection. -/ instance : CompleteLattice (TopologicalSpace α) := (gciGenerateFrom α).liftCompleteLattice @[mono] theorem generateFrom_anti {α} {g₁ g₂ : Set (Set α)} (h : g₁ ⊆ g₂) : generateFrom g₂ ≤ generateFrom g₁ := (gc_generateFrom _).monotone_u h theorem generateFrom_setOf_isOpen (t : TopologicalSpace α) : generateFrom { s | IsOpen[t] s } = t := (gciGenerateFrom α).u_l_eq t theorem leftInverse_generateFrom : LeftInverse generateFrom fun t : TopologicalSpace α => { s | IsOpen[t] s } := (gciGenerateFrom α).u_l_leftInverse theorem generateFrom_surjective : Surjective (generateFrom : Set (Set α) → TopologicalSpace α) := (gciGenerateFrom α).u_surjective theorem setOf_isOpen_injective : Injective fun t : TopologicalSpace α => { s | IsOpen[t] s } := (gciGenerateFrom α).l_injective end Lattice end TopologicalSpace section Lattice variable {α : Type*} {t t₁ t₂ : TopologicalSpace α} {s : Set α} theorem IsOpen.mono (hs : IsOpen[t₂] s) (h : t₁ ≤ t₂) : IsOpen[t₁] s := h s hs theorem IsClosed.mono (hs : IsClosed[t₂] s) (h : t₁ ≤ t₂) : IsClosed[t₁] s := (@isOpen_compl_iff α s t₁).mp <| hs.isOpen_compl.mono h theorem closure.mono (h : t₁ ≤ t₂) : closure[t₁] s ⊆ closure[t₂] s := @closure_minimal _ s (@closure _ t₂ s) t₁ subset_closure (IsClosed.mono isClosed_closure h) theorem isOpen_implies_isOpen_iff : (∀ s, IsOpen[t₁] s → IsOpen[t₂] s) ↔ t₂ ≤ t₁ := Iff.rfl /-- The only open sets in the indiscrete topology are the empty set and the whole space. -/ theorem TopologicalSpace.isOpen_top_iff {α} (U : Set α) : IsOpen[⊤] U ↔ U = ∅ ∨ U = univ := ⟨fun h => by induction h with | basic _ h => exact False.elim h | univ => exact .inr rfl | inter _ _ _ _ h₁ h₂ => rcases h₁ with (rfl | rfl) <;> rcases h₂ with (rfl | rfl) <;> simp | sUnion _ _ ih => exact sUnion_mem_empty_univ ih, by rintro (rfl | rfl) exacts [@isOpen_empty _ ⊤, @isOpen_univ _ ⊤]⟩ /-- A topological space is discrete if every set is open, that is, its topology equals the discrete topology `⊥`. -/ class DiscreteTopology (α : Type*) [t : TopologicalSpace α] : Prop where /-- The `TopologicalSpace` structure on a type with discrete topology is equal to `⊥`. -/ eq_bot : t = ⊥ theorem discreteTopology_bot (α : Type*) : @DiscreteTopology α ⊥ := @DiscreteTopology.mk α ⊥ rfl section DiscreteTopology variable [TopologicalSpace α] [DiscreteTopology α] {β : Type*} @[simp] theorem isOpen_discrete (s : Set α) : IsOpen s := (@DiscreteTopology.eq_bot α _).symm ▸ trivial @[simp] theorem isClosed_discrete (s : Set α) : IsClosed s := ⟨isOpen_discrete _⟩ @[simp] theorem closure_discrete (s : Set α) : closure s = s := (isClosed_discrete _).closure_eq @[simp] theorem dense_discrete {s : Set α} : Dense s ↔ s = univ := by simp [dense_iff_closure_eq] @[simp] theorem denseRange_discrete {ι : Type*} {f : ι → α} : DenseRange f ↔ Surjective f := by rw [DenseRange, dense_discrete, range_iff_surjective] @[nontriviality, continuity, fun_prop] theorem continuous_of_discreteTopology [TopologicalSpace β] {f : α → β} : Continuous f := continuous_def.2 fun _ _ => isOpen_discrete _ /-- A function to a discrete topological space is continuous if and only if the preimage of every singleton is open. -/ theorem continuous_discrete_rng {α} [TopologicalSpace α] [TopologicalSpace β] [DiscreteTopology β] {f : α → β} : Continuous f ↔ ∀ b : β, IsOpen (f ⁻¹' {b}) := ⟨fun h b => (isOpen_discrete _).preimage h, fun h => ⟨fun s _ => by rw [← biUnion_of_singleton s, preimage_iUnion₂] exact isOpen_biUnion fun _ _ => h _⟩⟩ @[simp] theorem nhds_discrete (α : Type*) [TopologicalSpace α] [DiscreteTopology α] : @nhds α _ = pure := le_antisymm (fun _ s hs => (isOpen_discrete s).mem_nhds hs) pure_le_nhds theorem mem_nhds_discrete {x : α} {s : Set α} : s ∈ 𝓝 x ↔ x ∈ s := by rw [nhds_discrete, mem_pure] end DiscreteTopology theorem le_of_nhds_le_nhds (h : ∀ x, @nhds α t₁ x ≤ @nhds α t₂ x) : t₁ ≤ t₂ := fun s => by rw [@isOpen_iff_mem_nhds _ _ t₁, @isOpen_iff_mem_nhds α _ t₂] exact fun hs a ha => h _ (hs _ ha) @[deprecated (since := "2024-03-01")] alias eq_of_nhds_eq_nhds := TopologicalSpace.ext_nhds theorem eq_bot_of_singletons_open {t : TopologicalSpace α} (h : ∀ x, IsOpen[t] {x}) : t = ⊥ := bot_unique fun s _ => biUnion_of_singleton s ▸ isOpen_biUnion fun x _ => h x theorem forall_open_iff_discrete {X : Type*} [TopologicalSpace X] : (∀ s : Set X, IsOpen s) ↔ DiscreteTopology X := ⟨fun h => ⟨eq_bot_of_singletons_open fun _ => h _⟩, @isOpen_discrete _ _⟩ theorem discreteTopology_iff_forall_isClosed [TopologicalSpace α] : DiscreteTopology α ↔ ∀ s : Set α, IsClosed s := forall_open_iff_discrete.symm.trans <| compl_surjective.forall.trans <| forall_congr' fun _ ↦ isOpen_compl_iff theorem singletons_open_iff_discrete {X : Type*} [TopologicalSpace X] : (∀ a : X, IsOpen ({a} : Set X)) ↔ DiscreteTopology X := ⟨fun h => ⟨eq_bot_of_singletons_open h⟩, fun a _ => @isOpen_discrete _ _ a _⟩ theorem discreteTopology_iff_singleton_mem_nhds [TopologicalSpace α] : DiscreteTopology α ↔ ∀ x : α, {x} ∈ 𝓝 x := by simp only [← singletons_open_iff_discrete, isOpen_iff_mem_nhds, mem_singleton_iff, forall_eq] /-- This lemma characterizes discrete topological spaces as those whose singletons are neighbourhoods. -/ theorem discreteTopology_iff_nhds [TopologicalSpace α] : DiscreteTopology α ↔ ∀ x : α, 𝓝 x = pure x := by simp only [discreteTopology_iff_singleton_mem_nhds, ← nhds_neBot.le_pure_iff, le_pure_iff] theorem discreteTopology_iff_nhds_ne [TopologicalSpace α] : DiscreteTopology α ↔ ∀ x : α, 𝓝[≠] x = ⊥ := by simp only [discreteTopology_iff_singleton_mem_nhds, nhdsWithin, inf_principal_eq_bot, compl_compl] /-- If the codomain of a continuous injective function has discrete topology, then so does the domain. See also `Embedding.discreteTopology` for an important special case. -/ theorem DiscreteTopology.of_continuous_injective {β : Type*} [TopologicalSpace α] [TopologicalSpace β] [DiscreteTopology β] {f : α → β} (hc : Continuous f) (hinj : Injective f) : DiscreteTopology α := forall_open_iff_discrete.1 fun s ↦ hinj.preimage_image s ▸ (isOpen_discrete _).preimage hc end Lattice section GaloisConnection variable {α β γ : Type*} theorem isOpen_induced_iff [t : TopologicalSpace β] {s : Set α} {f : α → β} : IsOpen[t.induced f] s ↔ ∃ t, IsOpen t ∧ f ⁻¹' t = s := Iff.rfl theorem isClosed_induced_iff [t : TopologicalSpace β] {s : Set α} {f : α → β} : IsClosed[t.induced f] s ↔ ∃ t, IsClosed t ∧ f ⁻¹' t = s := by letI := t.induced f simp only [← isOpen_compl_iff, isOpen_induced_iff] exact compl_surjective.exists.trans (by simp only [preimage_compl, compl_inj_iff]) theorem isOpen_coinduced {t : TopologicalSpace α} {s : Set β} {f : α → β} : IsOpen[t.coinduced f] s ↔ IsOpen (f ⁻¹' s) := Iff.rfl theorem isClosed_coinduced {t : TopologicalSpace α} {s : Set β} {f : α → β} : IsClosed[t.coinduced f] s ↔ IsClosed (f ⁻¹' s) := by simp only [← isOpen_compl_iff, isOpen_coinduced (f := f), preimage_compl] theorem preimage_nhds_coinduced [TopologicalSpace α] {π : α → β} {s : Set β} {a : α} (hs : s ∈ @nhds β (TopologicalSpace.coinduced π ‹_›) (π a)) : π ⁻¹' s ∈ 𝓝 a := by letI := TopologicalSpace.coinduced π ‹_› rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩ exact mem_nhds_iff.mpr ⟨π ⁻¹' V, Set.preimage_mono hVs, V_op, mem_V⟩ variable {t t₁ t₂ : TopologicalSpace α} {t' : TopologicalSpace β} {f : α → β} {g : β → α} theorem Continuous.coinduced_le (h : Continuous[t, t'] f) : t.coinduced f ≤ t' := (@continuous_def α β t t').1 h theorem coinduced_le_iff_le_induced {f : α → β} {tα : TopologicalSpace α} {tβ : TopologicalSpace β} : tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f := ⟨fun h _s ⟨_t, ht, hst⟩ => hst ▸ h _ ht, fun h s hs => h _ ⟨s, hs, rfl⟩⟩ theorem Continuous.le_induced (h : Continuous[t, t'] f) : t ≤ t'.induced f := coinduced_le_iff_le_induced.1 h.coinduced_le theorem gc_coinduced_induced (f : α → β) : GaloisConnection (TopologicalSpace.coinduced f) (TopologicalSpace.induced f) := fun _ _ => coinduced_le_iff_le_induced theorem induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_coinduced_induced g).monotone_u h theorem coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_coinduced_induced f).monotone_l h @[simp] theorem induced_top : (⊤ : TopologicalSpace α).induced g = ⊤ := (gc_coinduced_induced g).u_top @[simp] theorem induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g := (gc_coinduced_induced g).u_inf @[simp] theorem induced_iInf {ι : Sort w} {t : ι → TopologicalSpace α} : (⨅ i, t i).induced g = ⨅ i, (t i).induced g := (gc_coinduced_induced g).u_iInf @[simp] theorem coinduced_bot : (⊥ : TopologicalSpace α).coinduced f = ⊥ := (gc_coinduced_induced f).l_bot @[simp] theorem coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f := (gc_coinduced_induced f).l_sup @[simp] theorem coinduced_iSup {ι : Sort w} {t : ι → TopologicalSpace α} : (⨆ i, t i).coinduced f = ⨆ i, (t i).coinduced f := (gc_coinduced_induced f).l_iSup theorem induced_id [t : TopologicalSpace α] : t.induced id = t := TopologicalSpace.ext <| funext fun s => propext <| ⟨fun ⟨_, hs, h⟩ => h ▸ hs, fun hs => ⟨s, hs, rfl⟩⟩ theorem induced_compose {tγ : TopologicalSpace γ} {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := TopologicalSpace.ext <| funext fun _ => propext ⟨fun ⟨_, ⟨s, hs, h₂⟩, h₁⟩ => h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩, fun ⟨s, hs, h⟩ => ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ theorem induced_const [t : TopologicalSpace α] {x : α} : (t.induced fun _ : β => x) = ⊤ := le_antisymm le_top (@continuous_const β α ⊤ t x).le_induced theorem coinduced_id [t : TopologicalSpace α] : t.coinduced id = t := TopologicalSpace.ext rfl theorem coinduced_compose [tα : TopologicalSpace α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := TopologicalSpace.ext rfl theorem Equiv.induced_symm {α β : Type*} (e : α ≃ β) : TopologicalSpace.induced e.symm = TopologicalSpace.coinduced e := by ext t U rw [isOpen_induced_iff, isOpen_coinduced] simp only [e.symm.preimage_eq_iff_eq_image, exists_eq_right, ← preimage_equiv_eq_image_symm] theorem Equiv.coinduced_symm {α β : Type*} (e : α ≃ β) : TopologicalSpace.coinduced e.symm = TopologicalSpace.induced e := e.symm.induced_symm.symm end GaloisConnection -- constructions using the complete lattice structure section Constructions open TopologicalSpace variable {α : Type u} {β : Type v} instance inhabitedTopologicalSpace {α : Type u} : Inhabited (TopologicalSpace α) := ⟨⊥⟩ instance (priority := 100) Subsingleton.uniqueTopologicalSpace [Subsingleton α] : Unique (TopologicalSpace α) where default := ⊥ uniq t := eq_bot_of_singletons_open fun x => Subsingleton.set_cases (@isOpen_empty _ t) (@isOpen_univ _ t) ({x} : Set α) instance (priority := 100) Subsingleton.discreteTopology [t : TopologicalSpace α] [Subsingleton α] : DiscreteTopology α := ⟨Unique.eq_default t⟩ instance : TopologicalSpace Empty := ⊥ instance : DiscreteTopology Empty := ⟨rfl⟩ instance : TopologicalSpace PEmpty := ⊥ instance : DiscreteTopology PEmpty := ⟨rfl⟩ instance : TopologicalSpace PUnit := ⊥ instance : DiscreteTopology PUnit := ⟨rfl⟩ instance : TopologicalSpace Bool := ⊥ instance : DiscreteTopology Bool := ⟨rfl⟩ instance : TopologicalSpace ℕ := ⊥ instance : DiscreteTopology ℕ := ⟨rfl⟩ instance : TopologicalSpace ℤ := ⊥ instance : DiscreteTopology ℤ := ⟨rfl⟩ instance {n} : TopologicalSpace (Fin n) := ⊥ instance {n} : DiscreteTopology (Fin n) := ⟨rfl⟩ instance sierpinskiSpace : TopologicalSpace Prop := generateFrom {{True}} theorem continuous_empty_function [TopologicalSpace α] [TopologicalSpace β] [IsEmpty β] (f : α → β) : Continuous f := letI := Function.isEmpty f continuous_of_discreteTopology theorem le_generateFrom {t : TopologicalSpace α} {g : Set (Set α)} (h : ∀ s ∈ g, IsOpen s) : t ≤ generateFrom g := le_generateFrom_iff_subset_isOpen.2 h theorem induced_generateFrom_eq {α β} {b : Set (Set β)} {f : α → β} : (generateFrom b).induced f = generateFrom (preimage f '' b) := le_antisymm (le_generateFrom <| forall_mem_image.2 fun s hs => ⟨s, GenerateOpen.basic _ hs, rfl⟩) (coinduced_le_iff_le_induced.1 <| le_generateFrom fun _s hs => .basic _ (mem_image_of_mem _ hs)) theorem le_induced_generateFrom {α β} [t : TopologicalSpace α] {b : Set (Set β)} {f : α → β} (h : ∀ a : Set β, a ∈ b → IsOpen (f ⁻¹' a)) : t ≤ induced f (generateFrom b) := by rw [induced_generateFrom_eq] apply le_generateFrom simp only [mem_image, and_imp, forall_apply_eq_imp_iff₂, exists_imp] exact h lemma generateFrom_insert_of_generateOpen {α : Type*} {s : Set (Set α)} {t : Set α} (ht : GenerateOpen s t) : generateFrom (insert t s) = generateFrom s := by refine le_antisymm (generateFrom_anti <| subset_insert t s) (le_generateFrom ?_) rintro t (rfl | h) · exact ht · exact isOpen_generateFrom_of_mem h @[simp] lemma generateFrom_insert_univ {α : Type*} {s : Set (Set α)} : generateFrom (insert univ s) = generateFrom s := generateFrom_insert_of_generateOpen .univ /-- This construction is left adjoint to the operation sending a topology on `α` to its neighborhood filter at a fixed point `a : α`. -/ def nhdsAdjoint (a : α) (f : Filter α) : TopologicalSpace α where IsOpen s := a ∈ s → s ∈ f isOpen_univ _ := univ_mem isOpen_inter := fun _s _t hs ht ⟨has, hat⟩ => inter_mem (hs has) (ht hat) isOpen_sUnion := fun _k hk ⟨u, hu, hau⟩ => mem_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) theorem gc_nhds (a : α) : GaloisConnection (nhdsAdjoint a) fun t => @nhds α t a := fun f t => by rw [le_nhds_iff] exact ⟨fun H s hs has => H _ has hs, fun H s has hs => H _ hs has⟩ theorem nhds_mono {t₁ t₂ : TopologicalSpace α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h theorem le_iff_nhds {α : Type*} (t t' : TopologicalSpace α) : t ≤ t' ↔ ∀ x, @nhds α t x ≤ @nhds α t' x := ⟨fun h _ => nhds_mono h, le_of_nhds_le_nhds⟩ theorem isOpen_singleton_nhdsAdjoint {α : Type*} {a b : α} (f : Filter α) (hb : b ≠ a) : IsOpen[nhdsAdjoint a f] {b} := fun h ↦ absurd h hb.symm theorem nhds_nhdsAdjoint_same (a : α) (f : Filter α) : @nhds α (nhdsAdjoint a f) a = pure a ⊔ f := by let _ := nhdsAdjoint a f apply le_antisymm · rintro t ⟨hat : a ∈ t, htf : t ∈ f⟩ exact IsOpen.mem_nhds (fun _ ↦ htf) hat · exact sup_le (pure_le_nhds _) ((gc_nhds a).le_u_l f) @[deprecated (since := "2024-02-10")] alias nhdsAdjoint_nhds := nhds_nhdsAdjoint_same theorem nhds_nhdsAdjoint_of_ne {a b : α} (f : Filter α) (h : b ≠ a) : @nhds α (nhdsAdjoint a f) b = pure b := let _ := nhdsAdjoint a f (isOpen_singleton_iff_nhds_eq_pure _).1 <| isOpen_singleton_nhdsAdjoint f h @[deprecated nhds_nhdsAdjoint_of_ne (since := "2024-02-10")] theorem nhdsAdjoint_nhds_of_ne (a : α) (f : Filter α) {b : α} (h : b ≠ a) : @nhds α (nhdsAdjoint a f) b = pure b := nhds_nhdsAdjoint_of_ne f h theorem nhds_nhdsAdjoint [DecidableEq α] (a : α) (f : Filter α) : @nhds α (nhdsAdjoint a f) = update pure a (pure a ⊔ f) := eq_update_iff.2 ⟨nhds_nhdsAdjoint_same .., fun _ ↦ nhds_nhdsAdjoint_of_ne _⟩ theorem le_nhdsAdjoint_iff' {a : α} {f : Filter α} {t : TopologicalSpace α} : t ≤ nhdsAdjoint a f ↔ @nhds α t a ≤ pure a ⊔ f ∧ ∀ b ≠ a, @nhds α t b = pure b := by classical simp_rw [le_iff_nhds, nhds_nhdsAdjoint, forall_update_iff, (pure_le_nhds _).le_iff_eq] theorem le_nhdsAdjoint_iff {α : Type*} (a : α) (f : Filter α) (t : TopologicalSpace α) : t ≤ nhdsAdjoint a f ↔ @nhds α t a ≤ pure a ⊔ f ∧ ∀ b ≠ a, IsOpen[t] {b} := by simp only [le_nhdsAdjoint_iff', @isOpen_singleton_iff_nhds_eq_pure α t] theorem nhds_iInf {ι : Sort*} {t : ι → TopologicalSpace α} {a : α} : @nhds α (iInf t) a = ⨅ i, @nhds α (t i) a := (gc_nhds a).u_iInf theorem nhds_sInf {s : Set (TopologicalSpace α)} {a : α} : @nhds α (sInf s) a = ⨅ t ∈ s, @nhds α t a := (gc_nhds a).u_sInf -- Porting note (#11215): TODO: timeouts without `b₁ := t₁` theorem nhds_inf {t₁ t₂ : TopologicalSpace α} {a : α} : @nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf (b₁ := t₁) theorem nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top theorem isOpen_sup {t₁ t₂ : TopologicalSpace α} {s : Set α} : IsOpen[t₁ ⊔ t₂] s ↔ IsOpen[t₁] s ∧ IsOpen[t₂] s := Iff.rfl open TopologicalSpace variable {γ : Type*} {f : α → β} {ι : Sort*} theorem continuous_iff_coinduced_le {t₁ : TopologicalSpace α} {t₂ : TopologicalSpace β} : Continuous[t₁, t₂] f ↔ coinduced f t₁ ≤ t₂ := continuous_def theorem continuous_iff_le_induced {t₁ : TopologicalSpace α} {t₂ : TopologicalSpace β} : Continuous[t₁, t₂] f ↔ t₁ ≤ induced f t₂ := Iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _) lemma continuous_generateFrom_iff {t : TopologicalSpace α} {b : Set (Set β)} : Continuous[t, generateFrom b] f ↔ ∀ s ∈ b, IsOpen (f ⁻¹' s) := by rw [continuous_iff_coinduced_le, le_generateFrom_iff_subset_isOpen] simp only [isOpen_coinduced, preimage_id', subset_def, mem_setOf] @[deprecated (since := "2023-12-24")] alias ⟨_, continuous_generateFrom⟩ := continuous_generateFrom_iff @[continuity, fun_prop] theorem continuous_induced_dom {t : TopologicalSpace β} : Continuous[induced f t, t] f := continuous_iff_le_induced.2 le_rfl theorem continuous_induced_rng {g : γ → α} {t₂ : TopologicalSpace β} {t₁ : TopologicalSpace γ} : Continuous[t₁, induced f t₂] g ↔ Continuous[t₁, t₂] (f ∘ g) := by simp only [continuous_iff_le_induced, induced_compose] theorem continuous_coinduced_rng {t : TopologicalSpace α} : Continuous[t, coinduced f t] f := continuous_iff_coinduced_le.2 le_rfl theorem continuous_coinduced_dom {g : β → γ} {t₁ : TopologicalSpace α} {t₂ : TopologicalSpace γ} : Continuous[coinduced f t₁, t₂] g ↔ Continuous[t₁, t₂] (g ∘ f) := by simp only [continuous_iff_coinduced_le, coinduced_compose] theorem continuous_le_dom {t₁ t₂ : TopologicalSpace α} {t₃ : TopologicalSpace β} (h₁ : t₂ ≤ t₁) (h₂ : Continuous[t₁, t₃] f) : Continuous[t₂, t₃] f := by rw [continuous_iff_le_induced] at h₂ ⊢ exact le_trans h₁ h₂ theorem continuous_le_rng {t₁ : TopologicalSpace α} {t₂ t₃ : TopologicalSpace β} (h₁ : t₂ ≤ t₃) (h₂ : Continuous[t₁, t₂] f) : Continuous[t₁, t₃] f := by rw [continuous_iff_coinduced_le] at h₂ ⊢ exact le_trans h₂ h₁ theorem continuous_sup_dom {t₁ t₂ : TopologicalSpace α} {t₃ : TopologicalSpace β} : Continuous[t₁ ⊔ t₂, t₃] f ↔ Continuous[t₁, t₃] f ∧ Continuous[t₂, t₃] f := by simp only [continuous_iff_le_induced, sup_le_iff] theorem continuous_sup_rng_left {t₁ : TopologicalSpace α} {t₃ t₂ : TopologicalSpace β} : Continuous[t₁, t₂] f → Continuous[t₁, t₂ ⊔ t₃] f := continuous_le_rng le_sup_left theorem continuous_sup_rng_right {t₁ : TopologicalSpace α} {t₃ t₂ : TopologicalSpace β} : Continuous[t₁, t₃] f → Continuous[t₁, t₂ ⊔ t₃] f := continuous_le_rng le_sup_right theorem continuous_sSup_dom {T : Set (TopologicalSpace α)} {t₂ : TopologicalSpace β} : Continuous[sSup T, t₂] f ↔ ∀ t ∈ T, Continuous[t, t₂] f := by simp only [continuous_iff_le_induced, sSup_le_iff] theorem continuous_sSup_rng {t₁ : TopologicalSpace α} {t₂ : Set (TopologicalSpace β)} {t : TopologicalSpace β} (h₁ : t ∈ t₂) (hf : Continuous[t₁, t] f) : Continuous[t₁, sSup t₂] f := continuous_iff_coinduced_le.2 <| le_sSup_of_le h₁ <| continuous_iff_coinduced_le.1 hf theorem continuous_iSup_dom {t₁ : ι → TopologicalSpace α} {t₂ : TopologicalSpace β} : Continuous[iSup t₁, t₂] f ↔ ∀ i, Continuous[t₁ i, t₂] f := by simp only [continuous_iff_le_induced, iSup_le_iff] theorem continuous_iSup_rng {t₁ : TopologicalSpace α} {t₂ : ι → TopologicalSpace β} {i : ι} (h : Continuous[t₁, t₂ i] f) : Continuous[t₁, iSup t₂] f := continuous_sSup_rng ⟨i, rfl⟩ h theorem continuous_inf_rng {t₁ : TopologicalSpace α} {t₂ t₃ : TopologicalSpace β} : Continuous[t₁, t₂ ⊓ t₃] f ↔ Continuous[t₁, t₂] f ∧ Continuous[t₁, t₃] f := by simp only [continuous_iff_coinduced_le, le_inf_iff] theorem continuous_inf_dom_left {t₁ t₂ : TopologicalSpace α} {t₃ : TopologicalSpace β} : Continuous[t₁, t₃] f → Continuous[t₁ ⊓ t₂, t₃] f := continuous_le_dom inf_le_left theorem continuous_inf_dom_right {t₁ t₂ : TopologicalSpace α} {t₃ : TopologicalSpace β} : Continuous[t₂, t₃] f → Continuous[t₁ ⊓ t₂, t₃] f := continuous_le_dom inf_le_right theorem continuous_sInf_dom {t₁ : Set (TopologicalSpace α)} {t₂ : TopologicalSpace β} {t : TopologicalSpace α} (h₁ : t ∈ t₁) : Continuous[t, t₂] f → Continuous[sInf t₁, t₂] f := continuous_le_dom <| sInf_le h₁ theorem continuous_sInf_rng {t₁ : TopologicalSpace α} {T : Set (TopologicalSpace β)} : Continuous[t₁, sInf T] f ↔ ∀ t ∈ T, Continuous[t₁, t] f := by simp only [continuous_iff_coinduced_le, le_sInf_iff] theorem continuous_iInf_dom {t₁ : ι → TopologicalSpace α} {t₂ : TopologicalSpace β} {i : ι} : Continuous[t₁ i, t₂] f → Continuous[iInf t₁, t₂] f := continuous_le_dom <| iInf_le _ _ theorem continuous_iInf_rng {t₁ : TopologicalSpace α} {t₂ : ι → TopologicalSpace β} : Continuous[t₁, iInf t₂] f ↔ ∀ i, Continuous[t₁, t₂ i] f := by simp only [continuous_iff_coinduced_le, le_iInf_iff] @[continuity, fun_prop] theorem continuous_bot {t : TopologicalSpace β} : Continuous[⊥, t] f := continuous_iff_le_induced.2 bot_le @[continuity, fun_prop] theorem continuous_top {t : TopologicalSpace α} : Continuous[t, ⊤] f := continuous_iff_coinduced_le.2 le_top theorem continuous_id_iff_le {t t' : TopologicalSpace α} : Continuous[t, t'] id ↔ t ≤ t' := @continuous_def _ _ t t' id theorem continuous_id_of_le {t t' : TopologicalSpace α} (h : t ≤ t') : Continuous[t, t'] id := continuous_id_iff_le.2 h -- 𝓝 in the induced topology theorem mem_nhds_induced [T : TopologicalSpace α] (f : β → α) (a : β) (s : Set β) : s ∈ @nhds β (TopologicalSpace.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s := by letI := T.induced f simp_rw [mem_nhds_iff, isOpen_induced_iff] constructor · rintro ⟨u, usub, ⟨v, openv, rfl⟩, au⟩ exact ⟨v, ⟨v, Subset.rfl, openv, au⟩, usub⟩ · rintro ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩ exact ⟨f ⁻¹' v, (Set.preimage_mono vsubu).trans finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩ theorem nhds_induced [T : TopologicalSpace α] (f : β → α) (a : β) : @nhds β (TopologicalSpace.induced f T) a = comap f (𝓝 (f a)) := by ext s rw [mem_nhds_induced, mem_comap] theorem induced_iff_nhds_eq [tα : TopologicalSpace α] [tβ : TopologicalSpace β] (f : β → α) : tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 <| f b) := by simp only [ext_iff_nhds, nhds_induced] theorem map_nhds_induced_of_surjective [T : TopologicalSpace α] {f : β → α} (hf : Surjective f) (a : β) : map f (@nhds β (TopologicalSpace.induced f T) a) = 𝓝 (f a) := by rw [nhds_induced, map_comap_of_surjective hf] end Constructions section Induced open TopologicalSpace variable {α : Type*} {β : Type*} variable [t : TopologicalSpace β] {f : α → β} theorem isOpen_induced_eq {s : Set α} : IsOpen[induced f t] s ↔ s ∈ preimage f '' { s | IsOpen s } := Iff.rfl theorem isOpen_induced {s : Set β} (h : IsOpen s) : IsOpen[induced f t] (f ⁻¹' s) := ⟨s, h, rfl⟩ theorem map_nhds_induced_eq (a : α) : map f (@nhds α (induced f t) a) = 𝓝[range f] f a := by rw [nhds_induced, Filter.map_comap, nhdsWithin] theorem map_nhds_induced_of_mem {a : α} (h : range f ∈ 𝓝 (f a)) : map f (@nhds α (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, Filter.map_comap_of_mem h] theorem closure_induced {f : α → β} {a : α} {s : Set α} : a ∈ @closure α (t.induced f) s ↔ f a ∈ closure (f '' s) := by letI := t.induced f simp only [mem_closure_iff_frequently, nhds_induced, frequently_comap, mem_image, and_comm] theorem isClosed_induced_iff' {f : α → β} {s : Set α} : IsClosed[t.induced f] s ↔ ∀ a, f a ∈ closure (f '' s) → a ∈ s := by letI := t.induced f simp only [← closure_subset_iff_isClosed, subset_def, closure_induced] end Induced section Sierpinski variable {α : Type*} @[simp] theorem isOpen_singleton_true : IsOpen ({True} : Set Prop) := TopologicalSpace.GenerateOpen.basic _ (mem_singleton _) @[simp] theorem nhds_true : 𝓝 True = pure True := le_antisymm (le_pure_iff.2 <| isOpen_singleton_true.mem_nhds <| mem_singleton _) (pure_le_nhds _) @[simp] theorem nhds_false : 𝓝 False = ⊤ := TopologicalSpace.nhds_generateFrom.trans <| by simp [@and_comm (_ ∈ _), iInter_and] theorem tendsto_nhds_true {l : Filter α} {p : α → Prop} : Tendsto p l (𝓝 True) ↔ ∀ᶠ x in l, p x := by simp theorem tendsto_nhds_Prop {l : Filter α} {p : α → Prop} {q : Prop} : Tendsto p l (𝓝 q) ↔ (q → ∀ᶠ x in l, p x) := by by_cases q <;> simp [*] variable [TopologicalSpace α] theorem continuous_Prop {p : α → Prop} : Continuous p ↔ IsOpen { x | p x } := by simp only [continuous_iff_continuousAt, ContinuousAt, tendsto_nhds_Prop, isOpen_iff_mem_nhds]; rfl theorem isOpen_iff_continuous_mem {s : Set α} : IsOpen s ↔ Continuous (· ∈ s) := continuous_Prop.symm end Sierpinski section iInf open TopologicalSpace variable {α : Type u} {ι : Sort v} theorem generateFrom_union (a₁ a₂ : Set (Set α)) : generateFrom (a₁ ∪ a₂) = generateFrom a₁ ⊓ generateFrom a₂ := (gc_generateFrom α).u_inf theorem setOf_isOpen_sup (t₁ t₂ : TopologicalSpace α) : { s | IsOpen[t₁ ⊔ t₂] s } = { s | IsOpen[t₁] s } ∩ { s | IsOpen[t₂] s } := rfl theorem generateFrom_iUnion {f : ι → Set (Set α)} : generateFrom (⋃ i, f i) = ⨅ i, generateFrom (f i) := (gc_generateFrom α).u_iInf theorem setOf_isOpen_iSup {t : ι → TopologicalSpace α} : { s | IsOpen[⨆ i, t i] s } = ⋂ i, { s | IsOpen[t i] s } := (gc_generateFrom α).l_iSup theorem generateFrom_sUnion {S : Set (Set (Set α))} : generateFrom (⋃₀ S) = ⨅ s ∈ S, generateFrom s := (gc_generateFrom α).u_sInf theorem setOf_isOpen_sSup {T : Set (TopologicalSpace α)} : { s | IsOpen[sSup T] s } = ⋂ t ∈ T, { s | IsOpen[t] s } := (gc_generateFrom α).l_sSup theorem generateFrom_union_isOpen (a b : TopologicalSpace α) : generateFrom ({ s | IsOpen[a] s } ∪ { s | IsOpen[b] s }) = a ⊓ b := (gciGenerateFrom α).u_inf_l _ _ theorem generateFrom_iUnion_isOpen (f : ι → TopologicalSpace α) : generateFrom (⋃ i, { s | IsOpen[f i] s }) = ⨅ i, f i := (gciGenerateFrom α).u_iInf_l _ theorem generateFrom_inter (a b : TopologicalSpace α) : generateFrom ({ s | IsOpen[a] s } ∩ { s | IsOpen[b] s }) = a ⊔ b := (gciGenerateFrom α).u_sup_l _ _ theorem generateFrom_iInter (f : ι → TopologicalSpace α) : generateFrom (⋂ i, { s | IsOpen[f i] s }) = ⨆ i, f i := (gciGenerateFrom α).u_iSup_l _ theorem generateFrom_iInter_of_generateFrom_eq_self (f : ι → Set (Set α)) (hf : ∀ i, { s | IsOpen[generateFrom (f i)] s } = f i) : generateFrom (⋂ i, f i) = ⨆ i, generateFrom (f i) := (gciGenerateFrom α).u_iSup_of_lu_eq_self f hf variable {t : ι → TopologicalSpace α} theorem isOpen_iSup_iff {s : Set α} : IsOpen[⨆ i, t i] s ↔ ∀ i, IsOpen[t i] s := show s ∈ {s | IsOpen[iSup t] s} ↔ s ∈ { x : Set α | ∀ i : ι, IsOpen[t i] x } by simp [setOf_isOpen_iSup] set_option tactic.skipAssignedInstances false in theorem isClosed_iSup_iff {s : Set α} : IsClosed[⨆ i, t i] s ↔ ∀ i, IsClosed[t i] s := by simp [← @isOpen_compl_iff _ _ (⨆ i, t i), ← @isOpen_compl_iff _ _ (t _), isOpen_iSup_iff] end iInf
Topology\Partial.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import Mathlib.Order.Filter.Partial import Mathlib.Topology.Basic /-! # Partial functions and topological spaces In this file we prove properties of `Filter.PTendsto` etc in topological spaces. We also introduce `PContinuous`, a version of `Continuous` for partially defined functions. -/ open Filter open Topology variable {X Y : Type*} [TopologicalSpace X] theorem rtendsto_nhds {r : Rel Y X} {l : Filter Y} {x : X} : RTendsto r l (𝓝 x) ↔ ∀ s, IsOpen s → x ∈ s → r.core s ∈ l := all_mem_nhds_filter _ _ (fun _s _t => id) _ theorem rtendsto'_nhds {r : Rel Y X} {l : Filter Y} {x : X} : RTendsto' r l (𝓝 x) ↔ ∀ s, IsOpen s → x ∈ s → r.preimage s ∈ l := by rw [rtendsto'_def] apply all_mem_nhds_filter apply Rel.preimage_mono theorem ptendsto_nhds {f : Y →. X} {l : Filter Y} {x : X} : PTendsto f l (𝓝 x) ↔ ∀ s, IsOpen s → x ∈ s → f.core s ∈ l := rtendsto_nhds theorem ptendsto'_nhds {f : Y →. X} {l : Filter Y} {x : X} : PTendsto' f l (𝓝 x) ↔ ∀ s, IsOpen s → x ∈ s → f.preimage s ∈ l := rtendsto'_nhds /-! ### Continuity and partial functions -/ variable [TopologicalSpace Y] /-- Continuity of a partial function -/ def PContinuous (f : X →. Y) := ∀ s, IsOpen s → IsOpen (f.preimage s) theorem open_dom_of_pcontinuous {f : X →. Y} (h : PContinuous f) : IsOpen f.Dom := by rw [← PFun.preimage_univ]; exact h _ isOpen_univ theorem pcontinuous_iff' {f : X →. Y} : PContinuous f ↔ ∀ {x y} (h : y ∈ f x), PTendsto' f (𝓝 x) (𝓝 y) := by constructor · intro h x y h' simp only [ptendsto'_def, mem_nhds_iff] rintro s ⟨t, tsubs, opent, yt⟩ exact ⟨f.preimage t, PFun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ intro hf s os rw [isOpen_iff_nhds] rintro x ⟨y, ys, fxy⟩ t rw [mem_principal] intro (h : f.preimage s ⊆ t) change t ∈ 𝓝 x apply mem_of_superset _ h have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x := by intro s hs have : PTendsto' f (𝓝 x) (𝓝 y) := hf fxy rw [ptendsto'_def] at this exact this s hs show f.preimage s ∈ 𝓝 x apply h' rw [mem_nhds_iff] exact ⟨s, Set.Subset.refl _, os, ys⟩ theorem continuousWithinAt_iff_ptendsto_res (f : X → Y) {x : X} {s : Set X} : ContinuousWithinAt f s x ↔ PTendsto (PFun.res f s) (𝓝 x) (𝓝 (f x)) := tendsto_iff_ptendsto _ _ _ _
Topology\PartialHomeomorph.lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Logic.Equiv.PartialEquiv import Mathlib.Topology.Sets.Opens /-! # Partial homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `PartialHomeomorph X Y` is an extension of `PartialEquiv X Y`, i.e., it is a pair of functions `e.toFun` and `e.invFun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.toFun x` and `e.invFun x`. ## Main definitions * `Homeomorph.toPartialHomeomorph`: associating a partial homeomorphism to a homeomorphism, with `source = target = Set.univ`; * `PartialHomeomorph.symm`: the inverse of a partial homeomorphism * `PartialHomeomorph.trans`: the composition of two partial homeomorphisms * `PartialHomeomorph.refl`: the identity partial homeomorphism * `PartialHomeomorph.ofSet`: the identity on a set `s` * `PartialHomeomorph.EqOnSource`: equivalence relation describing the "right" notion of equality for partial homeomorphisms ## Implementation notes Most statements are copied from their `PartialEquiv` versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `PartialEquiv.lean`. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `PartialEquiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ open Function Set Filter Topology variable {X X' : Type*} {Y Y' : Type*} {Z Z' : Type*} [TopologicalSpace X] [TopologicalSpace X'] [TopologicalSpace Y] [TopologicalSpace Y'] [TopologicalSpace Z] [TopologicalSpace Z'] /-- Partial homeomorphisms, defined on open subsets of the space -/ -- Porting note(#5171): this linter isn't ported yet. @[nolint has_nonempty_instance] structure PartialHomeomorph (X : Type*) (Y : Type*) [TopologicalSpace X] [TopologicalSpace Y] extends PartialEquiv X Y where open_source : IsOpen source open_target : IsOpen target continuousOn_toFun : ContinuousOn toFun source continuousOn_invFun : ContinuousOn invFun target namespace PartialHomeomorph variable (e : PartialHomeomorph X Y) /-! Basic properties; inverse (symm instance) -/ section Basic /-- Coercion of a partial homeomorphisms to a function. We don't use `e.toFun` because it is actually `e.toPartialEquiv.toFun`, so `simp` will apply lemmas about `toPartialEquiv`. While we may want to switch to this behavior later, doing it mid-port will break a lot of proofs. -/ @[coe] def toFun' : X → Y := e.toFun /-- Coercion of a `PartialHomeomorph` to function. Note that a `PartialHomeomorph` is not `DFunLike`. -/ instance : CoeFun (PartialHomeomorph X Y) fun _ => X → Y := ⟨fun e => e.toFun'⟩ /-- The inverse of a partial homeomorphism -/ @[symm] protected def symm : PartialHomeomorph Y X where toPartialEquiv := e.toPartialEquiv.symm open_source := e.open_target open_target := e.open_source continuousOn_toFun := e.continuousOn_invFun continuousOn_invFun := e.continuousOn_toFun /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def Simps.apply (e : PartialHomeomorph X Y) : X → Y := e /-- See Note [custom simps projection] -/ def Simps.symm_apply (e : PartialHomeomorph X Y) : Y → X := e.symm initialize_simps_projections PartialHomeomorph (toFun → apply, invFun → symm_apply) protected theorem continuousOn : ContinuousOn e e.source := e.continuousOn_toFun theorem continuousOn_symm : ContinuousOn e.symm e.target := e.continuousOn_invFun @[simp, mfld_simps] theorem mk_coe (e : PartialEquiv X Y) (a b c d) : (PartialHomeomorph.mk e a b c d : X → Y) = e := rfl @[simp, mfld_simps] theorem mk_coe_symm (e : PartialEquiv X Y) (a b c d) : ((PartialHomeomorph.mk e a b c d).symm : Y → X) = e.symm := rfl theorem toPartialEquiv_injective : Injective (toPartialEquiv : PartialHomeomorph X Y → PartialEquiv X Y) | ⟨_, _, _, _, _⟩, ⟨_, _, _, _, _⟩, rfl => rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] theorem toFun_eq_coe (e : PartialHomeomorph X Y) : e.toFun = e := rfl @[simp, mfld_simps] theorem invFun_eq_coe (e : PartialHomeomorph X Y) : e.invFun = e.symm := rfl @[simp, mfld_simps] theorem coe_coe : (e.toPartialEquiv : X → Y) = e := rfl @[simp, mfld_simps] theorem coe_coe_symm : (e.toPartialEquiv.symm : Y → X) = e.symm := rfl @[simp, mfld_simps] theorem map_source {x : X} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h /-- Variant of `map_source`, stated for images of subsets of `source`. -/ lemma map_source'' : e '' e.source ⊆ e.target := fun _ ⟨_, hx, hex⟩ ↦ mem_of_eq_of_mem (id hex.symm) (e.map_source' hx) @[simp, mfld_simps] theorem map_target {x : Y} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] theorem left_inv {x : X} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] theorem right_inv {x : Y} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h theorem eq_symm_apply {x : X} {y : Y} (hx : x ∈ e.source) (hy : y ∈ e.target) : x = e.symm y ↔ e x = y := e.toPartialEquiv.eq_symm_apply hx hy protected theorem mapsTo : MapsTo e e.source e.target := fun _ => e.map_source protected theorem symm_mapsTo : MapsTo e.symm e.target e.source := e.symm.mapsTo protected theorem leftInvOn : LeftInvOn e.symm e e.source := fun _ => e.left_inv protected theorem rightInvOn : RightInvOn e.symm e e.target := fun _ => e.right_inv protected theorem invOn : InvOn e.symm e e.source e.target := ⟨e.leftInvOn, e.rightInvOn⟩ protected theorem injOn : InjOn e e.source := e.leftInvOn.injOn protected theorem bijOn : BijOn e e.source e.target := e.invOn.bijOn e.mapsTo e.symm_mapsTo protected theorem surjOn : SurjOn e e.source e.target := e.bijOn.surjOn end Basic /-- Interpret a `Homeomorph` as a `PartialHomeomorph` by restricting it to an open set `s` in the domain and to `t` in the codomain. -/ @[simps! (config := .asFn) apply symm_apply toPartialEquiv, simps! (config := .lemmasOnly) source target] def _root_.Homeomorph.toPartialHomeomorphOfImageEq (e : X ≃ₜ Y) (s : Set X) (hs : IsOpen s) (t : Set Y) (h : e '' s = t) : PartialHomeomorph X Y where toPartialEquiv := e.toPartialEquivOfImageEq s t h open_source := hs open_target := by simpa [← h] continuousOn_toFun := e.continuous.continuousOn continuousOn_invFun := e.symm.continuous.continuousOn /-- A homeomorphism induces a partial homeomorphism on the whole space -/ @[simps! (config := mfld_cfg)] def _root_.Homeomorph.toPartialHomeomorph (e : X ≃ₜ Y) : PartialHomeomorph X Y := e.toPartialHomeomorphOfImageEq univ isOpen_univ univ <| by rw [image_univ, e.surjective.range_eq] /-- Replace `toPartialEquiv` field to provide better definitional equalities. -/ def replaceEquiv (e : PartialHomeomorph X Y) (e' : PartialEquiv X Y) (h : e.toPartialEquiv = e') : PartialHomeomorph X Y where toPartialEquiv := e' open_source := h ▸ e.open_source open_target := h ▸ e.open_target continuousOn_toFun := h ▸ e.continuousOn_toFun continuousOn_invFun := h ▸ e.continuousOn_invFun theorem replaceEquiv_eq_self (e' : PartialEquiv X Y) (h : e.toPartialEquiv = e') : e.replaceEquiv e' h = e := by cases e subst e' rfl theorem source_preimage_target : e.source ⊆ e ⁻¹' e.target := e.mapsTo @[deprecated toPartialEquiv_injective (since := "2023-02-18")] theorem eq_of_partialEquiv_eq {e e' : PartialHomeomorph X Y} (h : e.toPartialEquiv = e'.toPartialEquiv) : e = e' := toPartialEquiv_injective h theorem eventually_left_inverse {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := (e.open_source.eventually_mem hx).mono e.left_inv' theorem eventually_left_inverse' {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y := e.eventually_left_inverse (e.map_target hx) theorem eventually_right_inverse {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 x, e (e.symm y) = y := (e.open_target.eventually_mem hx).mono e.right_inv' theorem eventually_right_inverse' {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 (e x), e (e.symm y) = y := e.eventually_right_inverse (e.map_source hx) theorem eventually_ne_nhdsWithin {x} (hx : x ∈ e.source) : ∀ᶠ x' in 𝓝[≠] x, e x' ≠ e x := eventually_nhdsWithin_iff.2 <| (e.eventually_left_inverse hx).mono fun x' hx' => mt fun h => by rw [mem_singleton_iff, ← e.left_inv hx, ← h, hx'] theorem nhdsWithin_source_inter {x} (hx : x ∈ e.source) (s : Set X) : 𝓝[e.source ∩ s] x = 𝓝[s] x := nhdsWithin_inter_of_mem (mem_nhdsWithin_of_mem_nhds <| IsOpen.mem_nhds e.open_source hx) theorem nhdsWithin_target_inter {x} (hx : x ∈ e.target) (s : Set Y) : 𝓝[e.target ∩ s] x = 𝓝[s] x := e.symm.nhdsWithin_source_inter hx s theorem image_eq_target_inter_inv_preimage {s : Set X} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := e.toPartialEquiv.image_eq_target_inter_inv_preimage h theorem image_source_inter_eq' (s : Set X) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := e.toPartialEquiv.image_source_inter_eq' s theorem image_source_inter_eq (s : Set X) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := e.toPartialEquiv.image_source_inter_eq s theorem symm_image_eq_source_inter_preimage {s : Set Y} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h theorem symm_image_target_inter_eq (s : Set Y) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ theorem source_inter_preimage_inv_preimage (s : Set X) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := e.toPartialEquiv.source_inter_preimage_inv_preimage s theorem target_inter_inv_preimage_preimage (s : Set Y) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ theorem source_inter_preimage_target_inter (s : Set Y) : e.source ∩ e ⁻¹' (e.target ∩ s) = e.source ∩ e ⁻¹' s := e.toPartialEquiv.source_inter_preimage_target_inter s theorem image_source_eq_target : e '' e.source = e.target := e.toPartialEquiv.image_source_eq_target theorem symm_image_target_eq_source : e.symm '' e.target = e.source := e.symm.image_source_eq_target /-- Two partial homeomorphisms are equal when they have equal `toFun`, `invFun` and `source`. It is not sufficient to have equal `toFun` and `source`, as this only determines `invFun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `EqOnSource`. -/ @[ext] protected theorem ext (e' : PartialHomeomorph X Y) (h : ∀ x, e x = e' x) (hinv : ∀ x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := toPartialEquiv_injective (PartialEquiv.ext h hinv hs) @[simp, mfld_simps] theorem symm_toPartialEquiv : e.symm.toPartialEquiv = e.toPartialEquiv.symm := rfl -- The following lemmas are already simp via `PartialEquiv` theorem symm_source : e.symm.source = e.target := rfl theorem symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] theorem symm_symm : e.symm.symm = e := rfl theorem symm_bijective : Function.Bijective (PartialHomeomorph.symm : PartialHomeomorph X Y → PartialHomeomorph Y X) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ /-- A partial homeomorphism is continuous at any point of its source -/ protected theorem continuousAt {x : X} (h : x ∈ e.source) : ContinuousAt e x := (e.continuousOn x h).continuousAt (e.open_source.mem_nhds h) /-- A partial homeomorphism inverse is continuous at any point of its target -/ theorem continuousAt_symm {x : Y} (h : x ∈ e.target) : ContinuousAt e.symm x := e.symm.continuousAt h theorem tendsto_symm {x} (hx : x ∈ e.source) : Tendsto e.symm (𝓝 (e x)) (𝓝 x) := by simpa only [ContinuousAt, e.left_inv hx] using e.continuousAt_symm (e.map_source hx) theorem map_nhds_eq {x} (hx : x ∈ e.source) : map e (𝓝 x) = 𝓝 (e x) := le_antisymm (e.continuousAt hx) <| le_map_of_right_inverse (e.eventually_right_inverse' hx) (e.tendsto_symm hx) theorem symm_map_nhds_eq {x} (hx : x ∈ e.source) : map e.symm (𝓝 (e x)) = 𝓝 x := (e.symm.map_nhds_eq <| e.map_source hx).trans <| by rw [e.left_inv hx] theorem image_mem_nhds {x} (hx : x ∈ e.source) {s : Set X} (hs : s ∈ 𝓝 x) : e '' s ∈ 𝓝 (e x) := e.map_nhds_eq hx ▸ Filter.image_mem_map hs theorem map_nhdsWithin_eq {x} (hx : x ∈ e.source) (s : Set X) : map e (𝓝[s] x) = 𝓝[e '' (e.source ∩ s)] e x := calc map e (𝓝[s] x) = map e (𝓝[e.source ∩ s] x) := congr_arg (map e) (e.nhdsWithin_source_inter hx _).symm _ = 𝓝[e '' (e.source ∩ s)] e x := (e.leftInvOn.mono inter_subset_left).map_nhdsWithin_eq (e.left_inv hx) (e.continuousAt_symm (e.map_source hx)).continuousWithinAt (e.continuousAt hx).continuousWithinAt theorem map_nhdsWithin_preimage_eq {x} (hx : x ∈ e.source) (s : Set Y) : map e (𝓝[e ⁻¹' s] x) = 𝓝[s] e x := by rw [e.map_nhdsWithin_eq hx, e.image_source_inter_eq', e.target_inter_inv_preimage_preimage, e.nhdsWithin_target_inter (e.map_source hx)] theorem eventually_nhds {x : X} (p : Y → Prop) (hx : x ∈ e.source) : (∀ᶠ y in 𝓝 (e x), p y) ↔ ∀ᶠ x in 𝓝 x, p (e x) := Iff.trans (by rw [e.map_nhds_eq hx]) eventually_map theorem eventually_nhds' {x : X} (p : X → Prop) (hx : x ∈ e.source) : (∀ᶠ y in 𝓝 (e x), p (e.symm y)) ↔ ∀ᶠ x in 𝓝 x, p x := by rw [e.eventually_nhds _ hx] refine eventually_congr ((e.eventually_left_inverse hx).mono fun y hy => ?_) rw [hy] theorem eventually_nhdsWithin {x : X} (p : Y → Prop) {s : Set X} (hx : x ∈ e.source) : (∀ᶠ y in 𝓝[e.symm ⁻¹' s] e x, p y) ↔ ∀ᶠ x in 𝓝[s] x, p (e x) := by refine Iff.trans ?_ eventually_map rw [e.map_nhdsWithin_eq hx, e.image_source_inter_eq', e.nhdsWithin_target_inter (e.mapsTo hx)] theorem eventually_nhdsWithin' {x : X} (p : X → Prop) {s : Set X} (hx : x ∈ e.source) : (∀ᶠ y in 𝓝[e.symm ⁻¹' s] e x, p (e.symm y)) ↔ ∀ᶠ x in 𝓝[s] x, p x := by rw [e.eventually_nhdsWithin _ hx] refine eventually_congr <| (eventually_nhdsWithin_of_eventually_nhds <| e.eventually_left_inverse hx).mono fun y hy => ?_ rw [hy] /-- This lemma is useful in the manifold library in the case that `e` is a chart. It states that locally around `e x` the set `e.symm ⁻¹' s` is the same as the set intersected with the target of `e` and some other neighborhood of `f x` (which will be the source of a chart on `Z`). -/ theorem preimage_eventuallyEq_target_inter_preimage_inter {e : PartialHomeomorph X Y} {s : Set X} {t : Set Z} {x : X} {f : X → Z} (hf : ContinuousWithinAt f s x) (hxe : x ∈ e.source) (ht : t ∈ 𝓝 (f x)) : e.symm ⁻¹' s =ᶠ[𝓝 (e x)] (e.target ∩ e.symm ⁻¹' (s ∩ f ⁻¹' t) : Set Y) := by rw [eventuallyEq_set, e.eventually_nhds _ hxe] filter_upwards [e.open_source.mem_nhds hxe, mem_nhdsWithin_iff_eventually.mp (hf.preimage_mem_nhdsWithin ht)] intro y hy hyu simp_rw [mem_inter_iff, mem_preimage, mem_inter_iff, e.mapsTo hy, true_and_iff, iff_self_and, e.left_inv hy, iff_true_intro hyu] theorem isOpen_inter_preimage {s : Set Y} (hs : IsOpen s) : IsOpen (e.source ∩ e ⁻¹' s) := e.continuousOn.isOpen_inter_preimage e.open_source hs theorem isOpen_inter_preimage_symm {s : Set X} (hs : IsOpen s) : IsOpen (e.target ∩ e.symm ⁻¹' s) := e.symm.continuousOn.isOpen_inter_preimage e.open_target hs /-- A partial homeomorphism is an open map on its source: the image of an open subset of the source is open. -/ lemma isOpen_image_of_subset_source {s : Set X} (hs : IsOpen s) (hse : s ⊆ e.source) : IsOpen (e '' s) := by rw [(image_eq_target_inter_inv_preimage (e := e) hse)] exact e.continuousOn_invFun.isOpen_inter_preimage e.open_target hs /-- The image of the restriction of an open set to the source is open. -/ theorem isOpen_image_source_inter {s : Set X} (hs : IsOpen s) : IsOpen (e '' (e.source ∩ s)) := e.isOpen_image_of_subset_source (e.open_source.inter hs) inter_subset_left /-- The inverse of a partial homeomorphism `e` is an open map on `e.target`. -/ lemma isOpen_image_symm_of_subset_target {t : Set Y} (ht : IsOpen t) (hte : t ⊆ e.target) : IsOpen (e.symm '' t) := isOpen_image_of_subset_source e.symm ht (e.symm_source ▸ hte) lemma isOpen_symm_image_iff_of_subset_target {t : Set Y} (hs : t ⊆ e.target) : IsOpen (e.symm '' t) ↔ IsOpen t := by refine ⟨fun h ↦ ?_, fun h ↦ e.symm.isOpen_image_of_subset_source h hs⟩ have hs' : e.symm '' t ⊆ e.source := by rw [e.symm_image_eq_source_inter_preimage hs] apply Set.inter_subset_left rw [← e.image_symm_image_of_subset_target hs] exact e.isOpen_image_of_subset_source h hs' theorem isOpen_image_iff_of_subset_source {s : Set X} (hs : s ⊆ e.source) : IsOpen (e '' s) ↔ IsOpen s := by rw [← e.symm.isOpen_symm_image_iff_of_subset_target hs, e.symm_symm] section IsImage /-! ### `PartialHomeomorph.IsImage` relation We say that `t : Set Y` is an image of `s : Set X` under a partial homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). This definition is a restatement of `PartialEquiv.IsImage` for partial homeomorphisms. In this section we transfer API about `PartialEquiv.IsImage` to partial homeomorphisms and add a few `PartialHomeomorph`-specific lemmas like `PartialHomeomorph.IsImage.closure`. -/ /-- We say that `t : Set Y` is an image of `s : Set X` under a partial homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def IsImage (s : Set X) (t : Set Y) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace IsImage variable {e} {s : Set X} {t : Set Y} {x : X} {y : Y} theorem toPartialEquiv (h : e.IsImage s t) : e.toPartialEquiv.IsImage s t := h theorem apply_mem_iff (h : e.IsImage s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx protected theorem symm (h : e.IsImage s t) : e.symm.IsImage t s := h.toPartialEquiv.symm theorem symm_apply_mem_iff (h : e.IsImage s t) (hy : y ∈ e.target) : e.symm y ∈ s ↔ y ∈ t := h.symm hy @[simp] theorem symm_iff : e.symm.IsImage t s ↔ e.IsImage s t := ⟨fun h => h.symm, fun h => h.symm⟩ protected theorem mapsTo (h : e.IsImage s t) : MapsTo e (e.source ∩ s) (e.target ∩ t) := h.toPartialEquiv.mapsTo theorem symm_mapsTo (h : e.IsImage s t) : MapsTo e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.mapsTo theorem image_eq (h : e.IsImage s t) : e '' (e.source ∩ s) = e.target ∩ t := h.toPartialEquiv.image_eq theorem symm_image_eq (h : e.IsImage s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq theorem iff_preimage_eq : e.IsImage s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := PartialEquiv.IsImage.iff_preimage_eq alias ⟨preimage_eq, of_preimage_eq⟩ := iff_preimage_eq theorem iff_symm_preimage_eq : e.IsImage s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias ⟨symm_preimage_eq, of_symm_preimage_eq⟩ := iff_symm_preimage_eq theorem iff_symm_preimage_eq' : e.IsImage s t ↔ e.target ∩ e.symm ⁻¹' (e.source ∩ s) = e.target ∩ t := by rw [iff_symm_preimage_eq, ← image_source_inter_eq, ← image_source_inter_eq'] alias ⟨symm_preimage_eq', of_symm_preimage_eq'⟩ := iff_symm_preimage_eq' theorem iff_preimage_eq' : e.IsImage s t ↔ e.source ∩ e ⁻¹' (e.target ∩ t) = e.source ∩ s := symm_iff.symm.trans iff_symm_preimage_eq' alias ⟨preimage_eq', of_preimage_eq'⟩ := iff_preimage_eq' theorem of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.IsImage s t := PartialEquiv.IsImage.of_image_eq h theorem of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.IsImage s t := PartialEquiv.IsImage.of_symm_image_eq h protected theorem compl (h : e.IsImage s t) : e.IsImage sᶜ tᶜ := fun _ hx => (h hx).not protected theorem inter {s' t'} (h : e.IsImage s t) (h' : e.IsImage s' t') : e.IsImage (s ∩ s') (t ∩ t') := fun _ hx => (h hx).and (h' hx) protected theorem union {s' t'} (h : e.IsImage s t) (h' : e.IsImage s' t') : e.IsImage (s ∪ s') (t ∪ t') := fun _ hx => (h hx).or (h' hx) protected theorem diff {s' t'} (h : e.IsImage s t) (h' : e.IsImage s' t') : e.IsImage (s \ s') (t \ t') := h.inter h'.compl theorem leftInvOn_piecewise {e' : PartialHomeomorph X Y} [∀ i, Decidable (i ∈ s)] [∀ i, Decidable (i ∈ t)] (h : e.IsImage s t) (h' : e'.IsImage s t) : LeftInvOn (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := h.toPartialEquiv.leftInvOn_piecewise h' theorem inter_eq_of_inter_eq_of_eqOn {e' : PartialHomeomorph X Y} (h : e.IsImage s t) (h' : e'.IsImage s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : EqOn e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := h.toPartialEquiv.inter_eq_of_inter_eq_of_eqOn h' hs Heq theorem symm_eqOn_of_inter_eq_of_eqOn {e' : PartialHomeomorph X Y} (h : e.IsImage s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : EqOn e e' (e.source ∩ s)) : EqOn e.symm e'.symm (e.target ∩ t) := h.toPartialEquiv.symm_eq_on_of_inter_eq_of_eqOn hs Heq theorem map_nhdsWithin_eq (h : e.IsImage s t) (hx : x ∈ e.source) : map e (𝓝[s] x) = 𝓝[t] e x := by rw [e.map_nhdsWithin_eq hx, h.image_eq, e.nhdsWithin_target_inter (e.map_source hx)] protected theorem closure (h : e.IsImage s t) : e.IsImage (closure s) (closure t) := fun x hx => by simp only [mem_closure_iff_nhdsWithin_neBot, ← h.map_nhdsWithin_eq hx, map_neBot_iff] protected theorem interior (h : e.IsImage s t) : e.IsImage (interior s) (interior t) := by simpa only [closure_compl, compl_compl] using h.compl.closure.compl protected theorem frontier (h : e.IsImage s t) : e.IsImage (frontier s) (frontier t) := h.closure.diff h.interior theorem isOpen_iff (h : e.IsImage s t) : IsOpen (e.source ∩ s) ↔ IsOpen (e.target ∩ t) := ⟨fun hs => h.symm_preimage_eq' ▸ e.symm.isOpen_inter_preimage hs, fun hs => h.preimage_eq' ▸ e.isOpen_inter_preimage hs⟩ /-- Restrict a `PartialHomeomorph` to a pair of corresponding open sets. -/ @[simps toPartialEquiv] def restr (h : e.IsImage s t) (hs : IsOpen (e.source ∩ s)) : PartialHomeomorph X Y where toPartialEquiv := h.toPartialEquiv.restr open_source := hs open_target := h.isOpen_iff.1 hs continuousOn_toFun := e.continuousOn.mono inter_subset_left continuousOn_invFun := e.symm.continuousOn.mono inter_subset_left end IsImage theorem isImage_source_target : e.IsImage e.source e.target := e.toPartialEquiv.isImage_source_target theorem isImage_source_target_of_disjoint (e' : PartialHomeomorph X Y) (hs : Disjoint e.source e'.source) (ht : Disjoint e.target e'.target) : e.IsImage e'.source e'.target := e.toPartialEquiv.isImage_source_target_of_disjoint e'.toPartialEquiv hs ht /-- Preimage of interior or interior of preimage coincide for partial homeomorphisms, when restricted to the source. -/ theorem preimage_interior (s : Set Y) : e.source ∩ e ⁻¹' interior s = e.source ∩ interior (e ⁻¹' s) := (IsImage.of_preimage_eq rfl).interior.preimage_eq theorem preimage_closure (s : Set Y) : e.source ∩ e ⁻¹' closure s = e.source ∩ closure (e ⁻¹' s) := (IsImage.of_preimage_eq rfl).closure.preimage_eq theorem preimage_frontier (s : Set Y) : e.source ∩ e ⁻¹' frontier s = e.source ∩ frontier (e ⁻¹' s) := (IsImage.of_preimage_eq rfl).frontier.preimage_eq end IsImage /-- A `PartialEquiv` with continuous open forward map and open source is a `PartialHomeomorph`. -/ def ofContinuousOpenRestrict (e : PartialEquiv X Y) (hc : ContinuousOn e e.source) (ho : IsOpenMap (e.source.restrict e)) (hs : IsOpen e.source) : PartialHomeomorph X Y where toPartialEquiv := e open_source := hs open_target := by simpa only [range_restrict, e.image_source_eq_target] using ho.isOpen_range continuousOn_toFun := hc continuousOn_invFun := e.image_source_eq_target ▸ ho.continuousOn_image_of_leftInvOn e.leftInvOn /-- A `PartialEquiv` with continuous open forward map and open source is a `PartialHomeomorph`. -/ def ofContinuousOpen (e : PartialEquiv X Y) (hc : ContinuousOn e e.source) (ho : IsOpenMap e) (hs : IsOpen e.source) : PartialHomeomorph X Y := ofContinuousOpenRestrict e hc (ho.restrict hs) hs /-- Restricting a partial homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its `PartialEquiv` is defeq to `PartialEquiv.restr`. -/ protected def restrOpen (s : Set X) (hs : IsOpen s) : PartialHomeomorph X Y := (@IsImage.of_symm_preimage_eq X Y _ _ e s (e.symm ⁻¹' s) rfl).restr (IsOpen.inter e.open_source hs) @[simp, mfld_simps] theorem restrOpen_toPartialEquiv (s : Set X) (hs : IsOpen s) : (e.restrOpen s hs).toPartialEquiv = e.toPartialEquiv.restr s := rfl -- Already simp via `PartialEquiv` theorem restrOpen_source (s : Set X) (hs : IsOpen s) : (e.restrOpen s hs).source = e.source ∩ s := rfl /-- Restricting a partial homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since partial homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of partial equivalences -/ @[simps! (config := mfld_cfg) apply symm_apply, simps! (config := .lemmasOnly) source target] protected def restr (s : Set X) : PartialHomeomorph X Y := e.restrOpen (interior s) isOpen_interior @[simp, mfld_simps] theorem restr_toPartialEquiv (s : Set X) : (e.restr s).toPartialEquiv = e.toPartialEquiv.restr (interior s) := rfl theorem restr_source' (s : Set X) (hs : IsOpen s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, hs.interior_eq] theorem restr_toPartialEquiv' (s : Set X) (hs : IsOpen s) : (e.restr s).toPartialEquiv = e.toPartialEquiv.restr s := by rw [e.restr_toPartialEquiv, hs.interior_eq] theorem restr_eq_of_source_subset {e : PartialHomeomorph X Y} {s : Set X} (h : e.source ⊆ s) : e.restr s = e := toPartialEquiv_injective <| PartialEquiv.restr_eq_of_source_subset <| interior_maximal h e.open_source @[simp, mfld_simps] theorem restr_univ {e : PartialHomeomorph X Y} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) theorem restr_source_inter (s : Set X) : e.restr (e.source ∩ s) = e.restr s := by refine PartialHomeomorph.ext _ _ (fun x => rfl) (fun x => rfl) ?_ simp [e.open_source.interior_eq, ← inter_assoc] /-- The identity on the whole space as a partial homeomorphism. -/ @[simps! (config := mfld_cfg) apply, simps! (config := .lemmasOnly) source target] protected def refl (X : Type*) [TopologicalSpace X] : PartialHomeomorph X X := (Homeomorph.refl X).toPartialHomeomorph @[simp, mfld_simps] theorem refl_partialEquiv : (PartialHomeomorph.refl X).toPartialEquiv = PartialEquiv.refl X := rfl @[simp, mfld_simps] theorem refl_symm : (PartialHomeomorph.refl X).symm = PartialHomeomorph.refl X := rfl /-! ofSet: the identity on a set `s` -/ section ofSet variable {s : Set X} (hs : IsOpen s) /-- The identity partial equivalence on a set `s` -/ @[simps! (config := mfld_cfg) apply, simps! (config := .lemmasOnly) source target] def ofSet (s : Set X) (hs : IsOpen s) : PartialHomeomorph X X where toPartialEquiv := PartialEquiv.ofSet s open_source := hs open_target := hs continuousOn_toFun := continuous_id.continuousOn continuousOn_invFun := continuous_id.continuousOn @[simp, mfld_simps] theorem ofSet_toPartialEquiv : (ofSet s hs).toPartialEquiv = PartialEquiv.ofSet s := rfl @[simp, mfld_simps] theorem ofSet_symm : (ofSet s hs).symm = ofSet s hs := rfl @[simp, mfld_simps] theorem ofSet_univ_eq_refl : ofSet univ isOpen_univ = PartialHomeomorph.refl X := by ext <;> simp end ofSet /-! `trans`: composition of two partial homeomorphisms -/ section trans variable (e' : PartialHomeomorph Y Z) /-- Composition of two partial homeomorphisms when the target of the first and the source of the second coincide. -/ @[simps! apply symm_apply toPartialEquiv, simps! (config := .lemmasOnly) source target] protected def trans' (h : e.target = e'.source) : PartialHomeomorph X Z where toPartialEquiv := PartialEquiv.trans' e.toPartialEquiv e'.toPartialEquiv h open_source := e.open_source open_target := e'.open_target continuousOn_toFun := e'.continuousOn.comp e.continuousOn <| h ▸ e.mapsTo continuousOn_invFun := e.continuousOn_symm.comp e'.continuousOn_symm <| h.symm ▸ e'.symm_mapsTo /-- Composing two partial homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ @[trans] protected def trans : PartialHomeomorph X Z := PartialHomeomorph.trans' (e.symm.restrOpen e'.source e'.open_source).symm (e'.restrOpen e.target e.open_target) (by simp [inter_comm]) @[simp, mfld_simps] theorem trans_toPartialEquiv : (e.trans e').toPartialEquiv = e.toPartialEquiv.trans e'.toPartialEquiv := rfl @[simp, mfld_simps] theorem coe_trans : (e.trans e' : X → Z) = e' ∘ e := rfl @[simp, mfld_simps] theorem coe_trans_symm : ((e.trans e').symm : Z → X) = e.symm ∘ e'.symm := rfl theorem trans_apply {x : X} : (e.trans e') x = e' (e x) := rfl theorem trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := rfl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ theorem trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := PartialEquiv.trans_source e.toPartialEquiv e'.toPartialEquiv theorem trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := PartialEquiv.trans_source' e.toPartialEquiv e'.toPartialEquiv theorem trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := PartialEquiv.trans_source'' e.toPartialEquiv e'.toPartialEquiv theorem image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := PartialEquiv.image_trans_source e.toPartialEquiv e'.toPartialEquiv theorem trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl theorem trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm theorem trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm theorem inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm theorem trans_assoc (e'' : PartialHomeomorph Z Z') : (e.trans e').trans e'' = e.trans (e'.trans e'') := toPartialEquiv_injective <| e.1.trans_assoc _ _ @[simp, mfld_simps] theorem trans_refl : e.trans (PartialHomeomorph.refl Y) = e := toPartialEquiv_injective e.1.trans_refl @[simp, mfld_simps] theorem refl_trans : (PartialHomeomorph.refl X).trans e = e := toPartialEquiv_injective e.1.refl_trans theorem trans_ofSet {s : Set Y} (hs : IsOpen s) : e.trans (ofSet s hs) = e.restr (e ⁻¹' s) := PartialHomeomorph.ext _ _ (fun _ => rfl) (fun _ => rfl) <| by rw [trans_source, restr_source, ofSet_source, ← preimage_interior, hs.interior_eq] theorem trans_of_set' {s : Set Y} (hs : IsOpen s) : e.trans (ofSet s hs) = e.restr (e.source ∩ e ⁻¹' s) := by rw [trans_ofSet, restr_source_inter] theorem ofSet_trans {s : Set X} (hs : IsOpen s) : (ofSet s hs).trans e = e.restr s := PartialHomeomorph.ext _ _ (fun x => rfl) (fun x => rfl) <| by simp [hs.interior_eq, inter_comm] theorem ofSet_trans' {s : Set X} (hs : IsOpen s) : (ofSet s hs).trans e = e.restr (e.source ∩ s) := by rw [ofSet_trans, restr_source_inter] @[simp, mfld_simps] theorem ofSet_trans_ofSet {s : Set X} (hs : IsOpen s) {s' : Set X} (hs' : IsOpen s') : (ofSet s hs).trans (ofSet s' hs') = ofSet (s ∩ s') (IsOpen.inter hs hs') := by rw [(ofSet s hs).trans_ofSet hs'] ext <;> simp [hs'.interior_eq] theorem restr_trans (s : Set X) : (e.restr s).trans e' = (e.trans e').restr s := toPartialEquiv_injective <| PartialEquiv.restr_trans e.toPartialEquiv e'.toPartialEquiv (interior s) end trans /-! `EqOnSource`: equivalence on their source -/ section EqOnSource /-- `EqOnSource e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same partial equivalence. -/ def EqOnSource (e e' : PartialHomeomorph X Y) : Prop := e.source = e'.source ∧ EqOn e e' e.source theorem eqOnSource_iff (e e' : PartialHomeomorph X Y) : EqOnSource e e' ↔ PartialEquiv.EqOnSource e.toPartialEquiv e'.toPartialEquiv := Iff.rfl /-- `EqOnSource` is an equivalence relation. -/ instance eqOnSourceSetoid : Setoid (PartialHomeomorph X Y) := { PartialEquiv.eqOnSourceSetoid.comap toPartialEquiv with r := EqOnSource } theorem eqOnSource_refl : e ≈ e := Setoid.refl _ /-- If two partial homeomorphisms are equivalent, so are their inverses. -/ theorem EqOnSource.symm' {e e' : PartialHomeomorph X Y} (h : e ≈ e') : e.symm ≈ e'.symm := PartialEquiv.EqOnSource.symm' h /-- Two equivalent partial homeomorphisms have the same source. -/ theorem EqOnSource.source_eq {e e' : PartialHomeomorph X Y} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent partial homeomorphisms have the same target. -/ theorem EqOnSource.target_eq {e e' : PartialHomeomorph X Y} (h : e ≈ e') : e.target = e'.target := h.symm'.1 /-- Two equivalent partial homeomorphisms have coinciding `toFun` on the source -/ theorem EqOnSource.eqOn {e e' : PartialHomeomorph X Y} (h : e ≈ e') : EqOn e e' e.source := h.2 /-- Two equivalent partial homeomorphisms have coinciding `invFun` on the target -/ theorem EqOnSource.symm_eqOn_target {e e' : PartialHomeomorph X Y} (h : e ≈ e') : EqOn e.symm e'.symm e.target := h.symm'.2 /-- Composition of partial homeomorphisms respects equivalence. -/ theorem EqOnSource.trans' {e e' : PartialHomeomorph X Y} {f f' : PartialHomeomorph Y Z} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := PartialEquiv.EqOnSource.trans' he hf /-- Restriction of partial homeomorphisms respects equivalence -/ theorem EqOnSource.restr {e e' : PartialHomeomorph X Y} (he : e ≈ e') (s : Set X) : e.restr s ≈ e'.restr s := PartialEquiv.EqOnSource.restr he _ /-- Two equivalent partial homeomorphisms are equal when the source and target are `univ`. -/ theorem Set.EqOn.restr_eqOn_source {e e' : PartialHomeomorph X Y} (h : EqOn e e' (e.source ∩ e'.source)) : e.restr e'.source ≈ e'.restr e.source := by constructor · rw [e'.restr_source' _ e.open_source] rw [e.restr_source' _ e'.open_source] exact Set.inter_comm _ _ · rw [e.restr_source' _ e'.open_source] refine (EqOn.trans ?_ h).trans ?_ <;> simp only [mfld_simps, eqOn_refl] /-- Composition of a partial homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ theorem self_trans_symm : e.trans e.symm ≈ PartialHomeomorph.ofSet e.source e.open_source := PartialEquiv.self_trans_symm _ theorem symm_trans_self : e.symm.trans e ≈ PartialHomeomorph.ofSet e.target e.open_target := e.symm.self_trans_symm theorem eq_of_eqOnSource_univ {e e' : PartialHomeomorph X Y} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := toPartialEquiv_injective <| PartialEquiv.eq_of_eqOnSource_univ _ _ h s t end EqOnSource /-! product of two partial homeomorphisms -/ section Prod /-- The product of two partial homeomorphisms, as a partial homeomorphism on the product space. -/ @[simps! (config := mfld_cfg) toPartialEquiv apply, simps! (config := .lemmasOnly) source target symm_apply] def prod (eX : PartialHomeomorph X X') (eY : PartialHomeomorph Y Y') : PartialHomeomorph (X × Y) (X' × Y') where open_source := eX.open_source.prod eY.open_source open_target := eX.open_target.prod eY.open_target continuousOn_toFun := eX.continuousOn.prod_map eY.continuousOn continuousOn_invFun := eX.continuousOn_symm.prod_map eY.continuousOn_symm toPartialEquiv := eX.toPartialEquiv.prod eY.toPartialEquiv @[simp, mfld_simps] theorem prod_symm (eX : PartialHomeomorph X X') (eY : PartialHomeomorph Y Y') : (eX.prod eY).symm = eX.symm.prod eY.symm := rfl @[simp] theorem refl_prod_refl : (PartialHomeomorph.refl X).prod (PartialHomeomorph.refl Y) = PartialHomeomorph.refl (X × Y) := PartialHomeomorph.ext _ _ (fun _ => rfl) (fun _ => rfl) univ_prod_univ @[simp, mfld_simps] theorem prod_trans (e : PartialHomeomorph X Y) (f : PartialHomeomorph Y Z) (e' : PartialHomeomorph X' Y') (f' : PartialHomeomorph Y' Z') : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := toPartialEquiv_injective <| e.1.prod_trans .. theorem prod_eq_prod_of_nonempty {eX eX' : PartialHomeomorph X X'} {eY eY' : PartialHomeomorph Y Y'} (h : (eX.prod eY).source.Nonempty) : eX.prod eY = eX'.prod eY' ↔ eX = eX' ∧ eY = eY' := by obtain ⟨⟨x, y⟩, -⟩ := id h haveI : Nonempty X := ⟨x⟩ haveI : Nonempty X' := ⟨eX x⟩ haveI : Nonempty Y := ⟨y⟩ haveI : Nonempty Y' := ⟨eY y⟩ simp_rw [PartialHomeomorph.ext_iff, prod_apply, prod_symm_apply, prod_source, Prod.ext_iff, Set.prod_eq_prod_iff_of_nonempty h, forall_and, Prod.forall, forall_const, and_assoc, and_left_comm] theorem prod_eq_prod_of_nonempty' {eX eX' : PartialHomeomorph X X'} {eY eY' : PartialHomeomorph Y Y'} (h : (eX'.prod eY').source.Nonempty) : eX.prod eY = eX'.prod eY' ↔ eX = eX' ∧ eY = eY' := by rw [eq_comm, prod_eq_prod_of_nonempty h, eq_comm, @eq_comm _ eY'] end Prod /-! finite product of partial homeomorphisms -/ section Pi variable {ι : Type*} [Finite ι] {X Y : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, TopologicalSpace (Y i)] (ei : ∀ i, PartialHomeomorph (X i) (Y i)) /-- The product of a finite family of `PartialHomeomorph`s. -/ @[simps toPartialEquiv] def pi : PartialHomeomorph (∀ i, X i) (∀ i, Y i) where toPartialEquiv := PartialEquiv.pi fun i => (ei i).toPartialEquiv open_source := isOpen_set_pi finite_univ fun i _ => (ei i).open_source open_target := isOpen_set_pi finite_univ fun i _ => (ei i).open_target continuousOn_toFun := continuousOn_pi.2 fun i => (ei i).continuousOn.comp (continuous_apply _).continuousOn fun _f hf => hf i trivial continuousOn_invFun := continuousOn_pi.2 fun i => (ei i).continuousOn_symm.comp (continuous_apply _).continuousOn fun _f hf => hf i trivial end Pi /-! combining two partial homeomorphisms using `Set.piecewise` -/ section Piecewise /-- Combine two `PartialHomeomorph`s using `Set.piecewise`. The source of the new `PartialHomeomorph` is `s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`, and similarly for the inverse function. To ensure the maps `toFun` and `invFun` are inverse of each other on the new `source` and `target`, the definition assumes that the sets `s` and `t` are related both by `e.is_image` and `e'.is_image`. To ensure that the new maps are continuous on `source`/`target`, it also assumes that `e.source` and `e'.source` meet `frontier s` on the same set and `e x = e' x` on this intersection. -/ @[simps! (config := .asFn) toPartialEquiv apply] def piecewise (e e' : PartialHomeomorph X Y) (s : Set X) (t : Set Y) [∀ x, Decidable (x ∈ s)] [∀ y, Decidable (y ∈ t)] (H : e.IsImage s t) (H' : e'.IsImage s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : EqOn e e' (e.source ∩ frontier s)) : PartialHomeomorph X Y where toPartialEquiv := e.toPartialEquiv.piecewise e'.toPartialEquiv s t H H' open_source := e.open_source.ite e'.open_source Hs open_target := e.open_target.ite e'.open_target <| H.frontier.inter_eq_of_inter_eq_of_eqOn H'.frontier Hs Heq continuousOn_toFun := continuousOn_piecewise_ite e.continuousOn e'.continuousOn Hs Heq continuousOn_invFun := continuousOn_piecewise_ite e.continuousOn_symm e'.continuousOn_symm (H.frontier.inter_eq_of_inter_eq_of_eqOn H'.frontier Hs Heq) (H.frontier.symm_eqOn_of_inter_eq_of_eqOn Hs Heq) @[simp] theorem symm_piecewise (e e' : PartialHomeomorph X Y) {s : Set X} {t : Set Y} [∀ x, Decidable (x ∈ s)] [∀ y, Decidable (y ∈ t)] (H : e.IsImage s t) (H' : e'.IsImage s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : EqOn e e' (e.source ∩ frontier s)) : (e.piecewise e' s t H H' Hs Heq).symm = e.symm.piecewise e'.symm t s H.symm H'.symm (H.frontier.inter_eq_of_inter_eq_of_eqOn H'.frontier Hs Heq) (H.frontier.symm_eqOn_of_inter_eq_of_eqOn Hs Heq) := rfl /-- Combine two `PartialHomeomorph`s with disjoint sources and disjoint targets. We reuse `PartialHomeomorph.piecewise` then override `toPartialEquiv` to `PartialEquiv.disjointUnion`. This way we have better definitional equalities for `source` and `target`. -/ def disjointUnion (e e' : PartialHomeomorph X Y) [∀ x, Decidable (x ∈ e.source)] [∀ y, Decidable (y ∈ e.target)] (Hs : Disjoint e.source e'.source) (Ht : Disjoint e.target e'.target) : PartialHomeomorph X Y := (e.piecewise e' e.source e.target e.isImage_source_target (e'.isImage_source_target_of_disjoint e Hs.symm Ht.symm) (by rw [e.open_source.inter_frontier_eq, (Hs.symm.frontier_right e'.open_source).inter_eq]) (by rw [e.open_source.inter_frontier_eq] exact eqOn_empty _ _)).replaceEquiv (e.toPartialEquiv.disjointUnion e'.toPartialEquiv Hs Ht) (PartialEquiv.disjointUnion_eq_piecewise _ _ _ _).symm end Piecewise section Continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ theorem continuousWithinAt_iff_continuousWithinAt_comp_right {f : Y → Z} {s : Set Y} {x : Y} (h : x ∈ e.target) : ContinuousWithinAt f s x ↔ ContinuousWithinAt (f ∘ e) (e ⁻¹' s) (e.symm x) := by simp_rw [ContinuousWithinAt, ← @tendsto_map'_iff _ _ _ _ e, e.map_nhdsWithin_preimage_eq (e.map_target h), (· ∘ ·), e.right_inv h] /-- Continuity at a point can be read under right composition with a partial homeomorphism, if the point is in its target -/ theorem continuousAt_iff_continuousAt_comp_right {f : Y → Z} {x : Y} (h : x ∈ e.target) : ContinuousAt f x ↔ ContinuousAt (f ∘ e) (e.symm x) := by rw [← continuousWithinAt_univ, e.continuousWithinAt_iff_continuousWithinAt_comp_right h, preimage_univ, continuousWithinAt_univ] /-- A function is continuous on a set if and only if its composition with a partial homeomorphism on the right is continuous on the corresponding set. -/ theorem continuousOn_iff_continuousOn_comp_right {f : Y → Z} {s : Set Y} (h : s ⊆ e.target) : ContinuousOn f s ↔ ContinuousOn (f ∘ e) (e.source ∩ e ⁻¹' s) := by simp only [← e.symm_image_eq_source_inter_preimage h, ContinuousOn, forall_mem_image] refine forall₂_congr fun x hx => ?_ rw [e.continuousWithinAt_iff_continuousWithinAt_comp_right (h hx), e.symm_image_eq_source_inter_preimage h, inter_comm, continuousWithinAt_inter] exact IsOpen.mem_nhds e.open_source (e.map_target (h hx)) /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ theorem continuousWithinAt_iff_continuousWithinAt_comp_left {f : Z → X} {s : Set Z} {x : Z} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ 𝓝[s] x) : ContinuousWithinAt f s x ↔ ContinuousWithinAt (e ∘ f) s x := by refine ⟨(e.continuousAt hx).comp_continuousWithinAt, fun fe_cont => ?_⟩ rw [← continuousWithinAt_inter' h] at fe_cont ⊢ have : ContinuousWithinAt (e.symm ∘ e ∘ f) (s ∩ f ⁻¹' e.source) x := haveI : ContinuousWithinAt e.symm univ (e (f x)) := (e.continuousAt_symm (e.map_source hx)).continuousWithinAt ContinuousWithinAt.comp this fe_cont (subset_univ _) exact this.congr (fun y hy => by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) /-- Continuity at a point can be read under left composition with a partial homeomorphism if a neighborhood of the initial point is sent to the source of the partial homeomorphism-/ theorem continuousAt_iff_continuousAt_comp_left {f : Z → X} {x : Z} (h : f ⁻¹' e.source ∈ 𝓝 x) : ContinuousAt f x ↔ ContinuousAt (e ∘ f) x := by have hx : f x ∈ e.source := (mem_of_mem_nhds h : _) have h' : f ⁻¹' e.source ∈ 𝓝[univ] x := by rwa [nhdsWithin_univ] rw [← continuousWithinAt_univ, ← continuousWithinAt_univ, e.continuousWithinAt_iff_continuousWithinAt_comp_left hx h'] /-- A function is continuous on a set if and only if its composition with a partial homeomorphism on the left is continuous on the corresponding set. -/ theorem continuousOn_iff_continuousOn_comp_left {f : Z → X} {s : Set Z} (h : s ⊆ f ⁻¹' e.source) : ContinuousOn f s ↔ ContinuousOn (e ∘ f) s := forall₂_congr fun _x hx => e.continuousWithinAt_iff_continuousWithinAt_comp_left (h hx) (mem_of_superset self_mem_nhdsWithin h) /-- A function is continuous if and only if its composition with a partial homeomorphism on the left is continuous and its image is contained in the source. -/ theorem continuous_iff_continuous_comp_left {f : Z → X} (h : f ⁻¹' e.source = univ) : Continuous f ↔ Continuous (e ∘ f) := by simp only [continuous_iff_continuousOn_univ] exact e.continuousOn_iff_continuousOn_comp_left (Eq.symm h).subset end Continuity /-- The homeomorphism obtained by restricting a `PartialHomeomorph` to a subset of the source. -/ @[simps] def homeomorphOfImageSubsetSource {s : Set X} {t : Set Y} (hs : s ⊆ e.source) (ht : e '' s = t) : s ≃ₜ t := have h₁ : MapsTo e s t := mapsTo'.2 ht.subset have h₂ : t ⊆ e.target := ht ▸ e.image_source_eq_target ▸ image_subset e hs have h₃ : MapsTo e.symm t s := ht ▸ forall_mem_image.2 fun _x hx => (e.left_inv (hs hx)).symm ▸ hx { toFun := MapsTo.restrict e s t h₁ invFun := MapsTo.restrict e.symm t s h₃ left_inv := fun a => Subtype.ext (e.left_inv (hs a.2)) right_inv := fun b => Subtype.eq <| e.right_inv (h₂ b.2) continuous_toFun := (e.continuousOn.mono hs).restrict_mapsTo h₁ continuous_invFun := (e.continuousOn_symm.mono h₂).restrict_mapsTo h₃ } /-- A partial homeomorphism defines a homeomorphism between its source and target. -/ @[simps!] -- Porting note: new `simps` def toHomeomorphSourceTarget : e.source ≃ₜ e.target := e.homeomorphOfImageSubsetSource subset_rfl e.image_source_eq_target theorem secondCountableTopology_source [SecondCountableTopology Y] : SecondCountableTopology e.source := e.toHomeomorphSourceTarget.secondCountableTopology theorem nhds_eq_comap_inf_principal {x} (hx : x ∈ e.source) : 𝓝 x = comap e (𝓝 (e x)) ⊓ 𝓟 e.source := by lift x to e.source using hx rw [← e.open_source.nhdsWithin_eq x.2, ← map_nhds_subtype_val, ← map_comap_setCoe_val, e.toHomeomorphSourceTarget.nhds_eq_comap, nhds_subtype_eq_comap] simp only [(· ∘ ·), toHomeomorphSourceTarget_apply_coe, comap_comap] /-- If a partial homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ @[simps (config := mfld_cfg) apply symm_apply] -- Porting note (#11215): TODO: add a `PartialEquiv` version def toHomeomorphOfSourceEqUnivTargetEqUniv (h : e.source = (univ : Set X)) (h' : e.target = univ) : X ≃ₜ Y where toFun := e invFun := e.symm left_inv x := e.left_inv <| by rw [h] exact mem_univ _ right_inv x := e.right_inv <| by rw [h'] exact mem_univ _ continuous_toFun := by simpa only [continuous_iff_continuousOn_univ, h] using e.continuousOn continuous_invFun := by simpa only [continuous_iff_continuousOn_univ, h'] using e.continuousOn_symm theorem openEmbedding_restrict : OpenEmbedding (e.source.restrict e) := by refine openEmbedding_of_continuous_injective_open (e.continuousOn.comp_continuous continuous_subtype_val Subtype.prop) e.injOn.injective fun V hV ↦ ?_ rw [Set.restrict_eq, Set.image_comp] exact e.isOpen_image_of_subset_source (e.open_source.isOpenMap_subtype_val V hV) fun _ ⟨x, _, h⟩ ↦ h ▸ x.2 /-- A partial homeomorphism whose source is all of `X` defines an open embedding of `X` into `Y`. The converse is also true; see `OpenEmbedding.toPartialHomeomorph`. -/ theorem to_openEmbedding (h : e.source = Set.univ) : OpenEmbedding e := e.openEmbedding_restrict.comp ((Homeomorph.setCongr h).trans <| Homeomorph.Set.univ X).symm.openEmbedding end PartialHomeomorph namespace Homeomorph variable (e : X ≃ₜ Y) (e' : Y ≃ₜ Z) /- Register as simp lemmas that the fields of a partial homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ @[simp, mfld_simps] theorem refl_toPartialHomeomorph : (Homeomorph.refl X).toPartialHomeomorph = PartialHomeomorph.refl X := rfl @[simp, mfld_simps] theorem symm_toPartialHomeomorph : e.symm.toPartialHomeomorph = e.toPartialHomeomorph.symm := rfl @[simp, mfld_simps] theorem trans_toPartialHomeomorph : (e.trans e').toPartialHomeomorph = e.toPartialHomeomorph.trans e'.toPartialHomeomorph := PartialHomeomorph.toPartialEquiv_injective <| Equiv.trans_toPartialEquiv _ _ /-- Precompose a partial homeomorphism with a homeomorphism. We modify the source and target to have better definitional behavior. -/ @[simps! (config := .asFn)] def transPartialHomeomorph (e : X ≃ₜ Y) (f' : PartialHomeomorph Y Z) : PartialHomeomorph X Z where toPartialEquiv := e.toEquiv.transPartialEquiv f'.toPartialEquiv open_source := f'.open_source.preimage e.continuous open_target := f'.open_target continuousOn_toFun := f'.continuousOn.comp e.continuous.continuousOn fun _ => id continuousOn_invFun := e.symm.continuous.comp_continuousOn f'.symm.continuousOn theorem transPartialHomeomorph_eq_trans (e : X ≃ₜ Y) (f' : PartialHomeomorph Y Z) : e.transPartialHomeomorph f' = e.toPartialHomeomorph.trans f' := PartialHomeomorph.toPartialEquiv_injective <| Equiv.transPartialEquiv_eq_trans _ _ @[simp, mfld_simps] theorem transPartialHomeomorph_trans (e : X ≃ₜ Y) (f : PartialHomeomorph Y Z) (f' : PartialHomeomorph Z Z') : (e.transPartialHomeomorph f).trans f' = e.transPartialHomeomorph (f.trans f') := by simp only [transPartialHomeomorph_eq_trans, PartialHomeomorph.trans_assoc] @[simp, mfld_simps] theorem trans_transPartialHomeomorph (e : X ≃ₜ Y) (e' : Y ≃ₜ Z) (f'' : PartialHomeomorph Z Z') : (e.trans e').transPartialHomeomorph f'' = e.transPartialHomeomorph (e'.transPartialHomeomorph f'') := by simp only [transPartialHomeomorph_eq_trans, PartialHomeomorph.trans_assoc, trans_toPartialHomeomorph] end Homeomorph namespace OpenEmbedding variable (f : X → Y) (h : OpenEmbedding f) /-- An open embedding of `X` into `Y`, with `X` nonempty, defines a partial homeomorphism whose source is all of `X`. The converse is also true; see `PartialHomeomorph.to_openEmbedding`. -/ @[simps! (config := mfld_cfg) apply source target] noncomputable def toPartialHomeomorph [Nonempty X] : PartialHomeomorph X Y := PartialHomeomorph.ofContinuousOpen (h.toEmbedding.inj.injOn.toPartialEquiv f univ) h.continuous.continuousOn h.isOpenMap isOpen_univ variable [Nonempty X] lemma toPartialHomeomorph_left_inv {x : X} : (h.toPartialHomeomorph f).symm (f x) = x := by rw [← congr_fun (h.toPartialHomeomorph_apply f), PartialHomeomorph.left_inv] exact Set.mem_univ _ lemma toPartialHomeomorph_right_inv {x : Y} (hx : x ∈ Set.range f) : f ((h.toPartialHomeomorph f).symm x) = x := by rw [← congr_fun (h.toPartialHomeomorph_apply f), PartialHomeomorph.right_inv] rwa [toPartialHomeomorph_target] end OpenEmbedding /-! inclusion of an open set in a topological space -/ namespace TopologicalSpace.Opens /- `Nonempty s` is not a type class argument because `s`, being a subset, rarely comes with a type class instance. Then we'd have to manually provide the instance every time we use the following lemmas, tediously using `haveI := ...` or `@foobar _ _ _ ...`. -/ variable (s : Opens X) (hs : Nonempty s) /-- The inclusion of an open subset `s` of a space `X` into `X` is a partial homeomorphism from the subtype `s` to `X`. -/ noncomputable def partialHomeomorphSubtypeCoe : PartialHomeomorph s X := OpenEmbedding.toPartialHomeomorph _ s.2.openEmbedding_subtype_val @[simp, mfld_simps] theorem partialHomeomorphSubtypeCoe_coe : (s.partialHomeomorphSubtypeCoe hs : s → X) = (↑) := rfl @[simp, mfld_simps] theorem partialHomeomorphSubtypeCoe_source : (s.partialHomeomorphSubtypeCoe hs).source = Set.univ := rfl @[simp, mfld_simps] theorem partialHomeomorphSubtypeCoe_target : (s.partialHomeomorphSubtypeCoe hs).target = s := by simp only [partialHomeomorphSubtypeCoe, Subtype.range_coe_subtype, mfld_simps] rfl end TopologicalSpace.Opens namespace PartialHomeomorph /- post-compose with a partial homeomorphism -/ section transHomeomorph /-- Postcompose a partial homeomorphism with a homeomorphism. We modify the source and target to have better definitional behavior. -/ @[simps! (config := .asFn)] def transHomeomorph (e : PartialHomeomorph X Y) (f' : Y ≃ₜ Z) : PartialHomeomorph X Z where toPartialEquiv := e.toPartialEquiv.transEquiv f'.toEquiv open_source := e.open_source open_target := e.open_target.preimage f'.symm.continuous continuousOn_toFun := f'.continuous.comp_continuousOn e.continuousOn continuousOn_invFun := e.symm.continuousOn.comp f'.symm.continuous.continuousOn fun _ => id theorem transHomeomorph_eq_trans (e : PartialHomeomorph X Y) (f' : Y ≃ₜ Z) : e.transHomeomorph f' = e.trans f'.toPartialHomeomorph := toPartialEquiv_injective <| PartialEquiv.transEquiv_eq_trans _ _ @[simp, mfld_simps] theorem transHomeomorph_transHomeomorph (e : PartialHomeomorph X Y) (f' : Y ≃ₜ Z) (f'' : Z ≃ₜ Z') : (e.transHomeomorph f').transHomeomorph f'' = e.transHomeomorph (f'.trans f'') := by simp only [transHomeomorph_eq_trans, trans_assoc, Homeomorph.trans_toPartialHomeomorph] @[simp, mfld_simps] theorem trans_transHomeomorph (e : PartialHomeomorph X Y) (e' : PartialHomeomorph Y Z) (f'' : Z ≃ₜ Z') : (e.trans e').transHomeomorph f'' = e.trans (e'.transHomeomorph f'') := by simp only [transHomeomorph_eq_trans, trans_assoc, Homeomorph.trans_toPartialHomeomorph] end transHomeomorph /-! `subtypeRestr`: restriction to a subtype -/ section subtypeRestr open TopologicalSpace variable (e : PartialHomeomorph X Y) variable {s : Opens X} (hs : Nonempty s) /-- The restriction of a partial homeomorphism `e` to an open subset `s` of the domain type produces a partial homeomorphism whose domain is the subtype `s`. -/ noncomputable def subtypeRestr : PartialHomeomorph s Y := (s.partialHomeomorphSubtypeCoe hs).trans e theorem subtypeRestr_def : e.subtypeRestr hs = (s.partialHomeomorphSubtypeCoe hs).trans e := rfl @[simp, mfld_simps] theorem subtypeRestr_coe : ((e.subtypeRestr hs : PartialHomeomorph s Y) : s → Y) = Set.restrict ↑s (e : X → Y) := rfl @[simp, mfld_simps] theorem subtypeRestr_source : (e.subtypeRestr hs).source = (↑) ⁻¹' e.source := by simp only [subtypeRestr_def, mfld_simps] theorem map_subtype_source {x : s} (hxe : (x : X) ∈ e.source) : e x ∈ (e.subtypeRestr hs).target := by refine ⟨e.map_source hxe, ?_⟩ rw [s.partialHomeomorphSubtypeCoe_target, mem_preimage, e.leftInvOn hxe] exact x.prop /-- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ theorem subtypeRestr_symm_trans_subtypeRestr (f f' : PartialHomeomorph X Y) : (f.subtypeRestr hs).symm.trans (f'.subtypeRestr hs) ≈ (f.symm.trans f').restr (f.target ∩ f.symm ⁻¹' s) := by simp only [subtypeRestr_def, trans_symm_eq_symm_trans_symm] have openness₁ : IsOpen (f.target ∩ f.symm ⁻¹' s) := f.isOpen_inter_preimage_symm s.2 rw [← ofSet_trans _ openness₁, ← trans_assoc, ← trans_assoc] refine EqOnSource.trans' ?_ (eqOnSource_refl _) -- f' has been eliminated !!! have set_identity : f.symm.source ∩ (f.target ∩ f.symm ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s := by mfld_set_tac have openness₂ : IsOpen (s : Set X) := s.2 rw [ofSet_trans', set_identity, ← trans_of_set' _ openness₂, trans_assoc] refine EqOnSource.trans' (eqOnSource_refl _) ?_ -- f has been eliminated !!! refine Setoid.trans (symm_trans_self (s.partialHomeomorphSubtypeCoe hs)) ?_ simp only [mfld_simps, Setoid.refl] theorem subtypeRestr_symm_eqOn {U : Opens X} (hU : Nonempty U) : EqOn e.symm (Subtype.val ∘ (e.subtypeRestr hU).symm) (e.subtypeRestr hU).target := by intro y hy rw [eq_comm, eq_symm_apply _ _ hy.1] · change restrict _ e _ = _ rw [← subtypeRestr_coe, (e.subtypeRestr hU).right_inv hy] · have := map_target _ hy; rwa [subtypeRestr_source] at this theorem subtypeRestr_symm_eqOn_of_le {U V : Opens X} (hU : Nonempty U) (hV : Nonempty V) (hUV : U ≤ V) : EqOn (e.subtypeRestr hV).symm (Set.inclusion hUV ∘ (e.subtypeRestr hU).symm) (e.subtypeRestr hU).target := by set i := Set.inclusion hUV intro y hy dsimp [PartialHomeomorph.subtypeRestr_def] at hy ⊢ have hyV : e.symm y ∈ (V.partialHomeomorphSubtypeCoe hV).target := by rw [Opens.partialHomeomorphSubtypeCoe_target] at hy ⊢ exact hUV hy.2 refine (V.partialHomeomorphSubtypeCoe hV).injOn ?_ trivial ?_ · rw [← PartialHomeomorph.symm_target] apply PartialHomeomorph.map_source rw [PartialHomeomorph.symm_source] exact hyV · rw [(V.partialHomeomorphSubtypeCoe hV).right_inv hyV] show _ = U.partialHomeomorphSubtypeCoe hU _ rw [(U.partialHomeomorphSubtypeCoe hU).right_inv hy.2] end subtypeRestr end PartialHomeomorph
Topology\PartitionOfUnity.lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Algebra.BigOperators.Finprod import Mathlib.SetTheory.Ordinal.Basic import Mathlib.Topology.ContinuousFunction.Algebra import Mathlib.Topology.Compactness.Paracompact import Mathlib.Topology.ShrinkingLemma import Mathlib.Topology.UrysohnsLemma /-! # Continuous partition of unity In this file we define `PartitionOfUnity (ι X : Type*) [TopologicalSpace X] (s : Set X := univ)` to be a continuous partition of unity on `s` indexed by `ι`. More precisely, `f : PartitionOfUnity ι X s` is a collection of continuous functions `f i : C(X, ℝ)`, `i : ι`, such that * the supports of `f i` form a locally finite family of sets; * each `f i` is nonnegative; * `∑ᶠ i, f i x = 1` for all `x ∈ s`; * `∑ᶠ i, f i x ≤ 1` for all `x : X`. In the case `s = univ` the last assumption follows from the previous one but it is convenient to have this assumption in the case `s ≠ univ`. We also define a bump function covering, `BumpCovering (ι X : Type*) [TopologicalSpace X] (s : Set X := univ)`, to be a collection of functions `f i : C(X, ℝ)`, `i : ι`, such that * the supports of `f i` form a locally finite family of sets; * each `f i` is nonnegative; * for each `x ∈ s` there exists `i : ι` such that `f i y = 1` in a neighborhood of `x`. The term is motivated by the smooth case. If `f` is a bump function covering indexed by a linearly ordered type, then `g i x = f i x * ∏ᶠ j < i, (1 - f j x)` is a partition of unity, see `BumpCovering.toPartitionOfUnity`. Note that only finitely many terms `1 - f j x` are not equal to one, so this product is well-defined. Note that `g i x = ∏ᶠ j ≤ i, (1 - f j x) - ∏ᶠ j < i, (1 - f j x)`, so most terms in the sum `∑ᶠ i, g i x` cancel, and we get `∑ᶠ i, g i x = 1 - ∏ᶠ i, (1 - f i x)`, and the latter product equals zero because one of `f i x` is equal to one. We say that a partition of unity or a bump function covering `f` is *subordinate* to a family of sets `U i`, `i : ι`, if the closure of the support of each `f i` is included in `U i`. We use Urysohn's Lemma to prove that a locally finite open covering of a normal topological space admits a subordinate bump function covering (hence, a subordinate partition of unity), see `BumpCovering.exists_isSubordinate_of_locallyFinite`. If `X` is a paracompact space, then any open covering admits a locally finite refinement, hence it admits a subordinate bump function covering and a subordinate partition of unity, see `BumpCovering.exists_isSubordinate`. We also provide two slightly more general versions of these lemmas, `BumpCovering.exists_isSubordinate_of_locallyFinite_of_prop` and `BumpCovering.exists_isSubordinate_of_prop`, to be used later in the construction of a smooth partition of unity. ## Implementation notes Most (if not all) books only define a partition of unity of the whole space. However, quite a few proofs only deal with `f i` such that `tsupport (f i)` meets a specific closed subset, and it is easier to formalize these proofs if we don't have other functions right away. We use `WellOrderingRel j i` instead of `j < i` in the definition of `BumpCovering.toPartitionOfUnity` to avoid a `[LinearOrder ι]` assumption. While `WellOrderingRel j i` is a well order, not only a strict linear order, we never use this property. ## Tags partition of unity, bump function, Urysohn's lemma, normal space, paracompact space -/ universe u v open Function Set Filter Topology noncomputable section /-- A continuous partition of unity on a set `s : Set X` is a collection of continuous functions `f i` such that * the supports of `f i` form a locally finite family of sets, i.e., for every point `x : X` there exists a neighborhood `U ∋ x` such that all but finitely many functions `f i` are zero on `U`; * the functions `f i` are nonnegative; * the sum `∑ᶠ i, f i x` is equal to one for every `x ∈ s` and is less than or equal to one otherwise. If `X` is a normal paracompact space, then `PartitionOfUnity.exists_isSubordinate` guarantees that for every open covering `U : Set (Set X)` of `s` there exists a partition of unity that is subordinate to `U`. -/ structure PartitionOfUnity (ι X : Type*) [TopologicalSpace X] (s : Set X := univ) where /-- The collection of continuous functions underlying this partition of unity -/ toFun : ι → C(X, ℝ) /-- the supports of the underlying functions are a locally finite family of sets -/ locallyFinite' : LocallyFinite fun i => support (toFun i) /-- the functions are non-negative -/ nonneg' : 0 ≤ toFun /-- the functions sum up to one on `s` -/ sum_eq_one' : ∀ x ∈ s, ∑ᶠ i, toFun i x = 1 /-- the functions sum up to at most one, globally -/ sum_le_one' : ∀ x, ∑ᶠ i, toFun i x ≤ 1 /-- A `BumpCovering ι X s` is an indexed family of functions `f i`, `i : ι`, such that * the supports of `f i` form a locally finite family of sets, i.e., for every point `x : X` there exists a neighborhood `U ∋ x` such that all but finitely many functions `f i` are zero on `U`; * for all `i`, `x` we have `0 ≤ f i x ≤ 1`; * each point `x ∈ s` belongs to the interior of `{x | f i x = 1}` for some `i`. One of the main use cases for a `BumpCovering` is to define a `PartitionOfUnity`, see `BumpCovering.toPartitionOfUnity`, but some proofs can directly use a `BumpCovering` instead of a `PartitionOfUnity`. If `X` is a normal paracompact space, then `BumpCovering.exists_isSubordinate` guarantees that for every open covering `U : Set (Set X)` of `s` there exists a `BumpCovering` of `s` that is subordinate to `U`. -/ structure BumpCovering (ι X : Type*) [TopologicalSpace X] (s : Set X := univ) where /-- The collections of continuous functions underlying this bump covering -/ toFun : ι → C(X, ℝ) /-- the supports of the underlying functions are a locally finite family of sets -/ locallyFinite' : LocallyFinite fun i => support (toFun i) /-- the functions are non-negative -/ nonneg' : 0 ≤ toFun /-- the functions are each at most one -/ le_one' : toFun ≤ 1 /-- Each point `x ∈ s` belongs to the interior of `{x | f i x = 1}` for some `i`. -/ eventuallyEq_one' : ∀ x ∈ s, ∃ i, toFun i =ᶠ[𝓝 x] 1 variable {ι : Type u} {X : Type v} [TopologicalSpace X] namespace PartitionOfUnity variable {E : Type*} [AddCommMonoid E] [SMulWithZero ℝ E] [TopologicalSpace E] [ContinuousSMul ℝ E] {s : Set X} (f : PartitionOfUnity ι X s) instance : FunLike (PartitionOfUnity ι X s) ι C(X, ℝ) where coe := toFun coe_injective' := fun f g h ↦ by cases f; cases g; congr protected theorem locallyFinite : LocallyFinite fun i => support (f i) := f.locallyFinite' theorem locallyFinite_tsupport : LocallyFinite fun i => tsupport (f i) := f.locallyFinite.closure theorem nonneg (i : ι) (x : X) : 0 ≤ f i x := f.nonneg' i x theorem sum_eq_one {x : X} (hx : x ∈ s) : ∑ᶠ i, f i x = 1 := f.sum_eq_one' x hx /-- If `f` is a partition of unity on `s`, then for every `x ∈ s` there exists an index `i` such that `0 < f i x`. -/ theorem exists_pos {x : X} (hx : x ∈ s) : ∃ i, 0 < f i x := by have H := f.sum_eq_one hx contrapose! H simpa only [fun i => (H i).antisymm (f.nonneg i x), finsum_zero] using zero_ne_one theorem sum_le_one (x : X) : ∑ᶠ i, f i x ≤ 1 := f.sum_le_one' x theorem sum_nonneg (x : X) : 0 ≤ ∑ᶠ i, f i x := finsum_nonneg fun i => f.nonneg i x theorem le_one (i : ι) (x : X) : f i x ≤ 1 := (single_le_finsum i (f.locallyFinite.point_finite x) fun j => f.nonneg j x).trans (f.sum_le_one x) section finsupport variable {s : Set X} (ρ : PartitionOfUnity ι X s) (x₀ : X) /-- The support of a partition of unity at a point `x₀` as a `Finset`. This is the set of `i : ι` such that `x₀ ∈ support f i`, i.e. `f i ≠ x₀`. -/ def finsupport : Finset ι := (ρ.locallyFinite.point_finite x₀).toFinset @[simp] theorem mem_finsupport (x₀ : X) {i} : i ∈ ρ.finsupport x₀ ↔ i ∈ support fun i ↦ ρ i x₀ := by simp only [finsupport, mem_support, Finite.mem_toFinset, mem_setOf_eq] @[simp] theorem coe_finsupport (x₀ : X) : (ρ.finsupport x₀ : Set ι) = support fun i ↦ ρ i x₀ := by ext rw [Finset.mem_coe, mem_finsupport] variable {x₀ : X} theorem sum_finsupport (hx₀ : x₀ ∈ s) : ∑ i ∈ ρ.finsupport x₀, ρ i x₀ = 1 := by rw [← ρ.sum_eq_one hx₀, finsum_eq_sum_of_support_subset _ (ρ.coe_finsupport x₀).superset] theorem sum_finsupport' (hx₀ : x₀ ∈ s) {I : Finset ι} (hI : ρ.finsupport x₀ ⊆ I) : ∑ i ∈ I, ρ i x₀ = 1 := by classical rw [← Finset.sum_sdiff hI, ρ.sum_finsupport hx₀] suffices ∑ i ∈ I \ ρ.finsupport x₀, (ρ i) x₀ = ∑ i ∈ I \ ρ.finsupport x₀, 0 by rw [this, add_left_eq_self, Finset.sum_const_zero] apply Finset.sum_congr rfl rintro x hx simp only [Finset.mem_sdiff, ρ.mem_finsupport, mem_support, Classical.not_not] at hx exact hx.2 theorem sum_finsupport_smul_eq_finsum {M : Type*} [AddCommGroup M] [Module ℝ M] (φ : ι → X → M) : ∑ i ∈ ρ.finsupport x₀, ρ i x₀ • φ i x₀ = ∑ᶠ i, ρ i x₀ • φ i x₀ := by apply (finsum_eq_sum_of_support_subset _ _).symm have : (fun i ↦ (ρ i) x₀ • φ i x₀) = (fun i ↦ (ρ i) x₀) • (fun i ↦ φ i x₀) := funext fun _ => (Pi.smul_apply' _ _ _).symm rw [ρ.coe_finsupport x₀, this, support_smul] exact inter_subset_left end finsupport section fintsupport -- partitions of unity have locally finite `tsupport` variable {s : Set X} (ρ : PartitionOfUnity ι X s) (x₀ : X) /-- The `tsupport`s of a partition of unity are locally finite. -/ theorem finite_tsupport : {i | x₀ ∈ tsupport (ρ i)}.Finite := by rcases ρ.locallyFinite x₀ with ⟨t, t_in, ht⟩ apply ht.subset rintro i hi simp only [inter_comm] exact mem_closure_iff_nhds.mp hi t t_in /-- The tsupport of a partition of unity at a point `x₀` as a `Finset`. This is the set of `i : ι` such that `x₀ ∈ tsupport f i`. -/ def fintsupport (x₀ : X) : Finset ι := (ρ.finite_tsupport x₀).toFinset theorem mem_fintsupport_iff (i : ι) : i ∈ ρ.fintsupport x₀ ↔ x₀ ∈ tsupport (ρ i) := Finite.mem_toFinset _ theorem eventually_fintsupport_subset : ∀ᶠ y in 𝓝 x₀, ρ.fintsupport y ⊆ ρ.fintsupport x₀ := by apply (ρ.locallyFinite.closure.eventually_subset (fun _ ↦ isClosed_closure) x₀).mono intro y hy z hz rw [PartitionOfUnity.mem_fintsupport_iff] at * exact hy hz theorem finsupport_subset_fintsupport : ρ.finsupport x₀ ⊆ ρ.fintsupport x₀ := fun i hi ↦ by rw [ρ.mem_fintsupport_iff] apply subset_closure exact (ρ.mem_finsupport x₀).mp hi theorem eventually_finsupport_subset : ∀ᶠ y in 𝓝 x₀, ρ.finsupport y ⊆ ρ.fintsupport x₀ := (ρ.eventually_fintsupport_subset x₀).mono fun y hy ↦ (ρ.finsupport_subset_fintsupport y).trans hy end fintsupport /-- If `f` is a partition of unity on `s : Set X` and `g : X → E` is continuous at every point of the topological support of some `f i`, then `fun x ↦ f i x • g x` is continuous on the whole space. -/ theorem continuous_smul {g : X → E} {i : ι} (hg : ∀ x ∈ tsupport (f i), ContinuousAt g x) : Continuous fun x => f i x • g x := continuous_of_tsupport fun x hx => ((f i).continuousAt x).smul <| hg x <| tsupport_smul_subset_left _ _ hx /-- If `f` is a partition of unity on a set `s : Set X` and `g : ι → X → E` is a family of functions such that each `g i` is continuous at every point of the topological support of `f i`, then the sum `fun x ↦ ∑ᶠ i, f i x • g i x` is continuous on the whole space. -/ theorem continuous_finsum_smul [ContinuousAdd E] {g : ι → X → E} (hg : ∀ (i), ∀ x ∈ tsupport (f i), ContinuousAt (g i) x) : Continuous fun x => ∑ᶠ i, f i x • g i x := (continuous_finsum fun i => f.continuous_smul (hg i)) <| f.locallyFinite.subset fun _ => support_smul_subset_left _ _ /-- A partition of unity `f i` is subordinate to a family of sets `U i` indexed by the same type if for each `i` the closure of the support of `f i` is a subset of `U i`. -/ def IsSubordinate (U : ι → Set X) : Prop := ∀ i, tsupport (f i) ⊆ U i variable {f} theorem exists_finset_nhd' {s : Set X} (ρ : PartitionOfUnity ι X s) (x₀ : X) : ∃ I : Finset ι, (∀ᶠ x in 𝓝[s] x₀, ∑ i ∈ I, ρ i x = 1) ∧ ∀ᶠ x in 𝓝 x₀, support (ρ · x) ⊆ I := by rcases ρ.locallyFinite.exists_finset_support x₀ with ⟨I, hI⟩ refine ⟨I, eventually_nhdsWithin_iff.mpr (hI.mono fun x hx x_in ↦ ?_), hI⟩ have : ∑ᶠ i : ι, ρ i x = ∑ i ∈ I, ρ i x := finsum_eq_sum_of_support_subset _ hx rwa [eq_comm, ρ.sum_eq_one x_in] at this theorem exists_finset_nhd (ρ : PartitionOfUnity ι X univ) (x₀ : X) : ∃ I : Finset ι, ∀ᶠ x in 𝓝 x₀, ∑ i ∈ I, ρ i x = 1 ∧ support (ρ · x) ⊆ I := by rcases ρ.exists_finset_nhd' x₀ with ⟨I, H⟩ use I rwa [nhdsWithin_univ, ← eventually_and] at H theorem exists_finset_nhd_support_subset {U : ι → Set X} (hso : f.IsSubordinate U) (ho : ∀ i, IsOpen (U i)) (x : X) : ∃ is : Finset ι, ∃ n ∈ 𝓝 x, n ⊆ ⋂ i ∈ is, U i ∧ ∀ z ∈ n, (support (f · z)) ⊆ is := f.locallyFinite.exists_finset_nhd_support_subset hso ho x /-- If `f` is a partition of unity that is subordinate to a family of open sets `U i` and `g : ι → X → E` is a family of functions such that each `g i` is continuous on `U i`, then the sum `fun x ↦ ∑ᶠ i, f i x • g i x` is a continuous function. -/ theorem IsSubordinate.continuous_finsum_smul [ContinuousAdd E] {U : ι → Set X} (ho : ∀ i, IsOpen (U i)) (hf : f.IsSubordinate U) {g : ι → X → E} (hg : ∀ i, ContinuousOn (g i) (U i)) : Continuous fun x => ∑ᶠ i, f i x • g i x := f.continuous_finsum_smul fun i _ hx => (hg i).continuousAt <| (ho i).mem_nhds <| hf i hx end PartitionOfUnity namespace BumpCovering variable {s : Set X} (f : BumpCovering ι X s) instance : FunLike (BumpCovering ι X s) ι C(X, ℝ) where coe := toFun coe_injective' := fun f g h ↦ by cases f; cases g; congr protected theorem locallyFinite : LocallyFinite fun i => support (f i) := f.locallyFinite' theorem locallyFinite_tsupport : LocallyFinite fun i => tsupport (f i) := f.locallyFinite.closure protected theorem point_finite (x : X) : { i | f i x ≠ 0 }.Finite := f.locallyFinite.point_finite x theorem nonneg (i : ι) (x : X) : 0 ≤ f i x := f.nonneg' i x theorem le_one (i : ι) (x : X) : f i x ≤ 1 := f.le_one' i x open Classical in /-- A `BumpCovering` that consists of a single function, uniformly equal to one, defined as an example for `Inhabited` instance. -/ protected def single (i : ι) (s : Set X) : BumpCovering ι X s where toFun := Pi.single i 1 locallyFinite' x := by refine ⟨univ, univ_mem, (finite_singleton i).subset ?_⟩ rintro j ⟨x, hx, -⟩ contrapose! hx rw [mem_singleton_iff] at hx simp [hx] nonneg' := le_update_iff.2 ⟨fun x => zero_le_one, fun _ _ => le_rfl⟩ le_one' := update_le_iff.2 ⟨le_rfl, fun _ _ _ => zero_le_one⟩ eventuallyEq_one' x _ := ⟨i, by rw [Pi.single_eq_same, ContinuousMap.coe_one]⟩ open Classical in @[simp] theorem coe_single (i : ι) (s : Set X) : ⇑(BumpCovering.single i s) = Pi.single i 1 := by rfl instance [Inhabited ι] : Inhabited (BumpCovering ι X s) := ⟨BumpCovering.single default s⟩ /-- A collection of bump functions `f i` is subordinate to a family of sets `U i` indexed by the same type if for each `i` the closure of the support of `f i` is a subset of `U i`. -/ def IsSubordinate (f : BumpCovering ι X s) (U : ι → Set X) : Prop := ∀ i, tsupport (f i) ⊆ U i theorem IsSubordinate.mono {f : BumpCovering ι X s} {U V : ι → Set X} (hU : f.IsSubordinate U) (hV : ∀ i, U i ⊆ V i) : f.IsSubordinate V := fun i => Subset.trans (hU i) (hV i) /-- If `X` is a normal topological space and `U i`, `i : ι`, is a locally finite open covering of a closed set `s`, then there exists a `BumpCovering ι X s` that is subordinate to `U`. If `X` is a paracompact space, then the assumption `hf : LocallyFinite U` can be omitted, see `BumpCovering.exists_isSubordinate`. This version assumes that `p : (X → ℝ) → Prop` is a predicate that satisfies Urysohn's lemma, and provides a `BumpCovering` such that each function of the covering satisfies `p`. -/ theorem exists_isSubordinate_of_locallyFinite_of_prop [NormalSpace X] (p : (X → ℝ) → Prop) (h01 : ∀ s t, IsClosed s → IsClosed t → Disjoint s t → ∃ f : C(X, ℝ), p f ∧ EqOn f 0 s ∧ EqOn f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1) (hs : IsClosed s) (U : ι → Set X) (ho : ∀ i, IsOpen (U i)) (hf : LocallyFinite U) (hU : s ⊆ ⋃ i, U i) : ∃ f : BumpCovering ι X s, (∀ i, p (f i)) ∧ f.IsSubordinate U := by rcases exists_subset_iUnion_closure_subset hs ho (fun x _ => hf.point_finite x) hU with ⟨V, hsV, hVo, hVU⟩ have hVU' : ∀ i, V i ⊆ U i := fun i => Subset.trans subset_closure (hVU i) rcases exists_subset_iUnion_closure_subset hs hVo (fun x _ => (hf.subset hVU').point_finite x) hsV with ⟨W, hsW, hWo, hWV⟩ choose f hfp hf0 hf1 hf01 using fun i => h01 _ _ (isClosed_compl_iff.2 <| hVo i) isClosed_closure (disjoint_right.2 fun x hx => Classical.not_not.2 (hWV i hx)) have hsupp : ∀ i, support (f i) ⊆ V i := fun i => support_subset_iff'.2 (hf0 i) refine ⟨⟨f, hf.subset fun i => Subset.trans (hsupp i) (hVU' i), fun i x => (hf01 i x).1, fun i x => (hf01 i x).2, fun x hx => ?_⟩, hfp, fun i => Subset.trans (closure_mono (hsupp i)) (hVU i)⟩ rcases mem_iUnion.1 (hsW hx) with ⟨i, hi⟩ exact ⟨i, ((hf1 i).mono subset_closure).eventuallyEq_of_mem ((hWo i).mem_nhds hi)⟩ /-- If `X` is a normal topological space and `U i`, `i : ι`, is a locally finite open covering of a closed set `s`, then there exists a `BumpCovering ι X s` that is subordinate to `U`. If `X` is a paracompact space, then the assumption `hf : LocallyFinite U` can be omitted, see `BumpCovering.exists_isSubordinate`. -/ theorem exists_isSubordinate_of_locallyFinite [NormalSpace X] (hs : IsClosed s) (U : ι → Set X) (ho : ∀ i, IsOpen (U i)) (hf : LocallyFinite U) (hU : s ⊆ ⋃ i, U i) : ∃ f : BumpCovering ι X s, f.IsSubordinate U := let ⟨f, _, hfU⟩ := exists_isSubordinate_of_locallyFinite_of_prop (fun _ => True) (fun _ _ hs ht hd => (exists_continuous_zero_one_of_isClosed hs ht hd).imp fun _ hf => ⟨trivial, hf⟩) hs U ho hf hU ⟨f, hfU⟩ /-- If `X` is a paracompact normal topological space and `U` is an open covering of a closed set `s`, then there exists a `BumpCovering ι X s` that is subordinate to `U`. This version assumes that `p : (X → ℝ) → Prop` is a predicate that satisfies Urysohn's lemma, and provides a `BumpCovering` such that each function of the covering satisfies `p`. -/ theorem exists_isSubordinate_of_prop [NormalSpace X] [ParacompactSpace X] (p : (X → ℝ) → Prop) (h01 : ∀ s t, IsClosed s → IsClosed t → Disjoint s t → ∃ f : C(X, ℝ), p f ∧ EqOn f 0 s ∧ EqOn f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1) (hs : IsClosed s) (U : ι → Set X) (ho : ∀ i, IsOpen (U i)) (hU : s ⊆ ⋃ i, U i) : ∃ f : BumpCovering ι X s, (∀ i, p (f i)) ∧ f.IsSubordinate U := by rcases precise_refinement_set hs _ ho hU with ⟨V, hVo, hsV, hVf, hVU⟩ rcases exists_isSubordinate_of_locallyFinite_of_prop p h01 hs V hVo hVf hsV with ⟨f, hfp, hf⟩ exact ⟨f, hfp, hf.mono hVU⟩ /-- If `X` is a paracompact normal topological space and `U` is an open covering of a closed set `s`, then there exists a `BumpCovering ι X s` that is subordinate to `U`. -/ theorem exists_isSubordinate [NormalSpace X] [ParacompactSpace X] (hs : IsClosed s) (U : ι → Set X) (ho : ∀ i, IsOpen (U i)) (hU : s ⊆ ⋃ i, U i) : ∃ f : BumpCovering ι X s, f.IsSubordinate U := by rcases precise_refinement_set hs _ ho hU with ⟨V, hVo, hsV, hVf, hVU⟩ rcases exists_isSubordinate_of_locallyFinite hs V hVo hVf hsV with ⟨f, hf⟩ exact ⟨f, hf.mono hVU⟩ /-- Index of a bump function such that `fs i =ᶠ[𝓝 x] 1`. -/ def ind (x : X) (hx : x ∈ s) : ι := (f.eventuallyEq_one' x hx).choose theorem eventuallyEq_one (x : X) (hx : x ∈ s) : f (f.ind x hx) =ᶠ[𝓝 x] 1 := (f.eventuallyEq_one' x hx).choose_spec theorem ind_apply (x : X) (hx : x ∈ s) : f (f.ind x hx) x = 1 := (f.eventuallyEq_one x hx).eq_of_nhds /-- Partition of unity defined by a `BumpCovering`. We use this auxiliary definition to prove some properties of the new family of functions before bundling it into a `PartitionOfUnity`. Do not use this definition, use `BumpCovering.toPartitionOfUnity` instead. The partition of unity is given by the formula `g i x = f i x * ∏ᶠ j < i, (1 - f j x)`. In other words, `g i x = ∏ᶠ j < i, (1 - f j x) - ∏ᶠ j ≤ i, (1 - f j x)`, so `∑ᶠ i, g i x = 1 - ∏ᶠ j, (1 - f j x)`. If `x ∈ s`, then one of `f j x` equals one, hence the product of `1 - f j x` vanishes, and `∑ᶠ i, g i x = 1`. In order to avoid an assumption `LinearOrder ι`, we use `WellOrderingRel` instead of `(<)`. -/ def toPOUFun (i : ι) (x : X) : ℝ := f i x * ∏ᶠ (j) (_ : WellOrderingRel j i), (1 - f j x) theorem toPOUFun_zero_of_zero {i : ι} {x : X} (h : f i x = 0) : f.toPOUFun i x = 0 := by rw [toPOUFun, h, zero_mul] theorem support_toPOUFun_subset (i : ι) : support (f.toPOUFun i) ⊆ support (f i) := fun _ => mt <| f.toPOUFun_zero_of_zero open Classical in theorem toPOUFun_eq_mul_prod (i : ι) (x : X) (t : Finset ι) (ht : ∀ j, WellOrderingRel j i → f j x ≠ 0 → j ∈ t) : f.toPOUFun i x = f i x * ∏ j ∈ t.filter fun j => WellOrderingRel j i, (1 - f j x) := by refine congr_arg _ (finprod_cond_eq_prod_of_cond_iff _ fun {j} hj => ?_) rw [Ne, sub_eq_self] at hj rw [Finset.mem_filter, Iff.comm, and_iff_right_iff_imp] exact flip (ht j) hj theorem sum_toPOUFun_eq (x : X) : ∑ᶠ i, f.toPOUFun i x = 1 - ∏ᶠ i, (1 - f i x) := by set s := (f.point_finite x).toFinset have hs : (s : Set ι) = { i | f i x ≠ 0 } := Finite.coe_toFinset _ have A : (support fun i => toPOUFun f i x) ⊆ s := by rw [hs] exact fun i hi => f.support_toPOUFun_subset i hi have B : (mulSupport fun i => 1 - f i x) ⊆ s := by rw [hs, mulSupport_one_sub] exact fun i => id classical letI : LinearOrder ι := linearOrderOfSTO WellOrderingRel rw [finsum_eq_sum_of_support_subset _ A, finprod_eq_prod_of_mulSupport_subset _ B, Finset.prod_one_sub_ordered, sub_sub_cancel] refine Finset.sum_congr rfl fun i _ => ?_ convert f.toPOUFun_eq_mul_prod _ _ _ fun j _ hj => _ rwa [Finite.mem_toFinset] open Classical in theorem exists_finset_toPOUFun_eventuallyEq (i : ι) (x : X) : ∃ t : Finset ι, f.toPOUFun i =ᶠ[𝓝 x] f i * ∏ j ∈ t.filter fun j => WellOrderingRel j i, (1 - f j) := by rcases f.locallyFinite x with ⟨U, hU, hf⟩ use hf.toFinset filter_upwards [hU] with y hyU simp only [ContinuousMap.coe_prod, Pi.mul_apply, Finset.prod_apply] apply toPOUFun_eq_mul_prod intro j _ hj exact hf.mem_toFinset.2 ⟨y, ⟨hj, hyU⟩⟩ theorem continuous_toPOUFun (i : ι) : Continuous (f.toPOUFun i) := by refine (f i).continuous.mul <| continuous_finprod_cond (fun j _ => continuous_const.sub (f j).continuous) ?_ simp only [mulSupport_one_sub] exact f.locallyFinite /-- The partition of unity defined by a `BumpCovering`. The partition of unity is given by the formula `g i x = f i x * ∏ᶠ j < i, (1 - f j x)`. In other words, `g i x = ∏ᶠ j < i, (1 - f j x) - ∏ᶠ j ≤ i, (1 - f j x)`, so `∑ᶠ i, g i x = 1 - ∏ᶠ j, (1 - f j x)`. If `x ∈ s`, then one of `f j x` equals one, hence the product of `1 - f j x` vanishes, and `∑ᶠ i, g i x = 1`. In order to avoid an assumption `LinearOrder ι`, we use `WellOrderingRel` instead of `(<)`. -/ def toPartitionOfUnity : PartitionOfUnity ι X s where toFun i := ⟨f.toPOUFun i, f.continuous_toPOUFun i⟩ locallyFinite' := f.locallyFinite.subset f.support_toPOUFun_subset nonneg' i x := mul_nonneg (f.nonneg i x) (finprod_cond_nonneg fun j hj => sub_nonneg.2 <| f.le_one j x) sum_eq_one' x hx := by simp only [ContinuousMap.coe_mk, sum_toPOUFun_eq, sub_eq_self] apply finprod_eq_zero (fun i => 1 - f i x) (f.ind x hx) · simp only [f.ind_apply x hx, sub_self] · rw [mulSupport_one_sub] exact f.point_finite x sum_le_one' x := by simp only [ContinuousMap.coe_mk, sum_toPOUFun_eq, sub_le_self_iff] exact finprod_nonneg fun i => sub_nonneg.2 <| f.le_one i x theorem toPartitionOfUnity_apply (i : ι) (x : X) : f.toPartitionOfUnity i x = f i x * ∏ᶠ (j) (_ : WellOrderingRel j i), (1 - f j x) := rfl open Classical in theorem toPartitionOfUnity_eq_mul_prod (i : ι) (x : X) (t : Finset ι) (ht : ∀ j, WellOrderingRel j i → f j x ≠ 0 → j ∈ t) : f.toPartitionOfUnity i x = f i x * ∏ j ∈ t.filter fun j => WellOrderingRel j i, (1 - f j x) := f.toPOUFun_eq_mul_prod i x t ht open Classical in theorem exists_finset_toPartitionOfUnity_eventuallyEq (i : ι) (x : X) : ∃ t : Finset ι, f.toPartitionOfUnity i =ᶠ[𝓝 x] f i * ∏ j ∈ t.filter fun j => WellOrderingRel j i, (1 - f j) := f.exists_finset_toPOUFun_eventuallyEq i x theorem toPartitionOfUnity_zero_of_zero {i : ι} {x : X} (h : f i x = 0) : f.toPartitionOfUnity i x = 0 := f.toPOUFun_zero_of_zero h theorem support_toPartitionOfUnity_subset (i : ι) : support (f.toPartitionOfUnity i) ⊆ support (f i) := f.support_toPOUFun_subset i theorem sum_toPartitionOfUnity_eq (x : X) : ∑ᶠ i, f.toPartitionOfUnity i x = 1 - ∏ᶠ i, (1 - f i x) := f.sum_toPOUFun_eq x theorem IsSubordinate.toPartitionOfUnity {f : BumpCovering ι X s} {U : ι → Set X} (h : f.IsSubordinate U) : f.toPartitionOfUnity.IsSubordinate U := fun i => Subset.trans (closure_mono <| f.support_toPartitionOfUnity_subset i) (h i) end BumpCovering namespace PartitionOfUnity variable {s : Set X} instance [Inhabited ι] : Inhabited (PartitionOfUnity ι X s) := ⟨BumpCovering.toPartitionOfUnity default⟩ /-- If `X` is a normal topological space and `U` is a locally finite open covering of a closed set `s`, then there exists a `PartitionOfUnity ι X s` that is subordinate to `U`. If `X` is a paracompact space, then the assumption `hf : LocallyFinite U` can be omitted, see `BumpCovering.exists_isSubordinate`. -/ theorem exists_isSubordinate_of_locallyFinite [NormalSpace X] (hs : IsClosed s) (U : ι → Set X) (ho : ∀ i, IsOpen (U i)) (hf : LocallyFinite U) (hU : s ⊆ ⋃ i, U i) : ∃ f : PartitionOfUnity ι X s, f.IsSubordinate U := let ⟨f, hf⟩ := BumpCovering.exists_isSubordinate_of_locallyFinite hs U ho hf hU ⟨f.toPartitionOfUnity, hf.toPartitionOfUnity⟩ /-- If `X` is a paracompact normal topological space and `U` is an open covering of a closed set `s`, then there exists a `PartitionOfUnity ι X s` that is subordinate to `U`. -/ theorem exists_isSubordinate [NormalSpace X] [ParacompactSpace X] (hs : IsClosed s) (U : ι → Set X) (ho : ∀ i, IsOpen (U i)) (hU : s ⊆ ⋃ i, U i) : ∃ f : PartitionOfUnity ι X s, f.IsSubordinate U := let ⟨f, hf⟩ := BumpCovering.exists_isSubordinate hs U ho hU ⟨f.toPartitionOfUnity, hf.toPartitionOfUnity⟩ end PartitionOfUnity
Topology\Perfect.lean
/- Copyright (c) 2022 Felix Weilacher. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Felix Weilacher -/ import Mathlib.Topology.Separation /-! # Perfect Sets In this file we define perfect subsets of a topological space, and prove some basic properties, including a version of the Cantor-Bendixson Theorem. ## Main Definitions * `Perfect C`: A set `C` is perfect, meaning it is closed and every point of it is an accumulation point of itself. * `PerfectSpace X`: A topological space `X` is perfect if its universe is a perfect set. ## Main Statements * `Perfect.splitting`: A perfect nonempty set contains two disjoint perfect nonempty subsets. The main inductive step in the construction of an embedding from the Cantor space to a perfect nonempty complete metric space. * `exists_countable_union_perfect_of_isClosed`: One version of the **Cantor-Bendixson Theorem**: A closed set in a second countable space can be written as the union of a countable set and a perfect set. ## Implementation Notes We do not require perfect sets to be nonempty. We define a nonstandard predicate, `Preperfect`, which drops the closed-ness requirement from the definition of perfect. In T1 spaces, this is equivalent to having a perfect closure, see `preperfect_iff_perfect_closure`. ## See also `Mathlib.Topology.MetricSpace.Perfect`, for properties of perfect sets in metric spaces, namely Polish spaces. ## References * [kechris1995] (Chapters 6-7) ## Tags accumulation point, perfect set, cantor-bendixson. -/ open Topology Filter Set TopologicalSpace section Basic variable {α : Type*} [TopologicalSpace α] {C : Set α} /-- If `x` is an accumulation point of a set `C` and `U` is a neighborhood of `x`, then `x` is an accumulation point of `U ∩ C`. -/ theorem AccPt.nhds_inter {x : α} {U : Set α} (h_acc : AccPt x (𝓟 C)) (hU : U ∈ 𝓝 x) : AccPt x (𝓟 (U ∩ C)) := by have : 𝓝[≠] x ≤ 𝓟 U := by rw [le_principal_iff] exact mem_nhdsWithin_of_mem_nhds hU rw [AccPt, ← inf_principal, ← inf_assoc, inf_of_le_left this] exact h_acc /-- A set `C` is preperfect if all of its points are accumulation points of itself. If `C` is nonempty and `α` is a T1 space, this is equivalent to the closure of `C` being perfect. See `preperfect_iff_perfect_closure`. -/ def Preperfect (C : Set α) : Prop := ∀ x ∈ C, AccPt x (𝓟 C) /-- A set `C` is called perfect if it is closed and all of its points are accumulation points of itself. Note that we do not require `C` to be nonempty. -/ @[mk_iff perfect_def] structure Perfect (C : Set α) : Prop where closed : IsClosed C acc : Preperfect C theorem preperfect_iff_nhds : Preperfect C ↔ ∀ x ∈ C, ∀ U ∈ 𝓝 x, ∃ y ∈ U ∩ C, y ≠ x := by simp only [Preperfect, accPt_iff_nhds] section PerfectSpace variable (α) /-- A topological space `X` is said to be perfect if its universe is a perfect set. Equivalently, this means that `𝓝[≠] x ≠ ⊥` for every point `x : X`. -/ @[mk_iff perfectSpace_def] class PerfectSpace : Prop := univ_preperfect : Preperfect (Set.univ : Set α) theorem PerfectSpace.univ_perfect [PerfectSpace α] : Perfect (Set.univ : Set α) := ⟨isClosed_univ, PerfectSpace.univ_preperfect⟩ end PerfectSpace section Preperfect /-- The intersection of a preperfect set and an open set is preperfect. -/ theorem Preperfect.open_inter {U : Set α} (hC : Preperfect C) (hU : IsOpen U) : Preperfect (U ∩ C) := by rintro x ⟨xU, xC⟩ apply (hC _ xC).nhds_inter exact hU.mem_nhds xU /-- The closure of a preperfect set is perfect. For a converse, see `preperfect_iff_perfect_closure`. -/ theorem Preperfect.perfect_closure (hC : Preperfect C) : Perfect (closure C) := by constructor; · exact isClosed_closure intro x hx by_cases h : x ∈ C <;> apply AccPt.mono _ (principal_mono.mpr subset_closure) · exact hC _ h have : {x}ᶜ ∩ C = C := by simp [h] rw [AccPt, nhdsWithin, inf_assoc, inf_principal, this] rw [closure_eq_cluster_pts] at hx exact hx /-- In a T1 space, being preperfect is equivalent to having perfect closure. -/ theorem preperfect_iff_perfect_closure [T1Space α] : Preperfect C ↔ Perfect (closure C) := by constructor <;> intro h · exact h.perfect_closure intro x xC have H : AccPt x (𝓟 (closure C)) := h.acc _ (subset_closure xC) rw [accPt_iff_frequently] at * have : ∀ y, y ≠ x ∧ y ∈ closure C → ∃ᶠ z in 𝓝 y, z ≠ x ∧ z ∈ C := by rintro y ⟨hyx, yC⟩ simp only [← mem_compl_singleton_iff, and_comm, ← frequently_nhdsWithin_iff, hyx.nhdsWithin_compl_singleton, ← mem_closure_iff_frequently] exact yC rw [← frequently_frequently_nhds] exact H.mono this theorem Perfect.closure_nhds_inter {U : Set α} (hC : Perfect C) (x : α) (xC : x ∈ C) (xU : x ∈ U) (Uop : IsOpen U) : Perfect (closure (U ∩ C)) ∧ (closure (U ∩ C)).Nonempty := by constructor · apply Preperfect.perfect_closure exact hC.acc.open_inter Uop apply Nonempty.closure exact ⟨x, ⟨xU, xC⟩⟩ /-- Given a perfect nonempty set in a T2.5 space, we can find two disjoint perfect subsets. This is the main inductive step in the proof of the Cantor-Bendixson Theorem. -/ theorem Perfect.splitting [T25Space α] (hC : Perfect C) (hnonempty : C.Nonempty) : ∃ C₀ C₁ : Set α, (Perfect C₀ ∧ C₀.Nonempty ∧ C₀ ⊆ C) ∧ (Perfect C₁ ∧ C₁.Nonempty ∧ C₁ ⊆ C) ∧ Disjoint C₀ C₁ := by cases' hnonempty with y yC obtain ⟨x, xC, hxy⟩ : ∃ x ∈ C, x ≠ y := by have := hC.acc _ yC rw [accPt_iff_nhds] at this rcases this univ univ_mem with ⟨x, xC, hxy⟩ exact ⟨x, xC.2, hxy⟩ obtain ⟨U, xU, Uop, V, yV, Vop, hUV⟩ := exists_open_nhds_disjoint_closure hxy use closure (U ∩ C), closure (V ∩ C) constructor <;> rw [← and_assoc] · refine ⟨hC.closure_nhds_inter x xC xU Uop, ?_⟩ rw [hC.closed.closure_subset_iff] exact inter_subset_right constructor · refine ⟨hC.closure_nhds_inter y yC yV Vop, ?_⟩ rw [hC.closed.closure_subset_iff] exact inter_subset_right apply Disjoint.mono _ _ hUV <;> apply closure_mono <;> exact inter_subset_left lemma IsPreconnected.preperfect_of_nontrivial [T1Space α] {U : Set α} (hu : U.Nontrivial) (h : IsPreconnected U) : Preperfect U := by intro x hx rw [isPreconnected_closed_iff] at h specialize h {x} (closure (U \ {x})) isClosed_singleton isClosed_closure ?_ ?_ ?_ · trans {x} ∪ (U \ {x}) · simp apply Set.union_subset_union_right exact subset_closure · exact Set.inter_singleton_nonempty.mpr hx · obtain ⟨y, hy⟩ := Set.Nontrivial.exists_ne hu x use y simp only [Set.mem_inter_iff, hy, true_and] apply subset_closure simp [hy] · apply Set.Nonempty.right at h rw [Set.singleton_inter_nonempty, mem_closure_iff_clusterPt, ← acc_principal_iff_cluster] at h exact h end Preperfect section Kernel /-- The **Cantor-Bendixson Theorem**: Any closed subset of a second countable space can be written as the union of a countable set and a perfect set. -/ theorem exists_countable_union_perfect_of_isClosed [SecondCountableTopology α] (hclosed : IsClosed C) : ∃ V D : Set α, V.Countable ∧ Perfect D ∧ C = V ∪ D := by obtain ⟨b, bct, _, bbasis⟩ := TopologicalSpace.exists_countable_basis α let v := { U ∈ b | (U ∩ C).Countable } let V := ⋃ U ∈ v, U let D := C \ V have Vct : (V ∩ C).Countable := by simp only [V, iUnion_inter, mem_sep_iff] apply Countable.biUnion · exact Countable.mono inter_subset_left bct · exact inter_subset_right refine ⟨V ∩ C, D, Vct, ⟨?_, ?_⟩, ?_⟩ · refine hclosed.sdiff (isOpen_biUnion fun _ ↦ ?_) exact fun ⟨Ub, _⟩ ↦ IsTopologicalBasis.isOpen bbasis Ub · rw [preperfect_iff_nhds] intro x xD E xE have : ¬(E ∩ D).Countable := by intro h obtain ⟨U, hUb, xU, hU⟩ : ∃ U ∈ b, x ∈ U ∧ U ⊆ E := (IsTopologicalBasis.mem_nhds_iff bbasis).mp xE have hU_cnt : (U ∩ C).Countable := by apply @Countable.mono _ _ (E ∩ D ∪ V ∩ C) · rintro y ⟨yU, yC⟩ by_cases h : y ∈ V · exact mem_union_right _ (mem_inter h yC) · exact mem_union_left _ (mem_inter (hU yU) ⟨yC, h⟩) exact Countable.union h Vct have : U ∈ v := ⟨hUb, hU_cnt⟩ apply xD.2 exact mem_biUnion this xU by_contra! h exact absurd (Countable.mono h (Set.countable_singleton _)) this · rw [inter_comm, inter_union_diff] /-- Any uncountable closed set in a second countable space contains a nonempty perfect subset. -/ theorem exists_perfect_nonempty_of_isClosed_of_not_countable [SecondCountableTopology α] (hclosed : IsClosed C) (hunc : ¬C.Countable) : ∃ D : Set α, Perfect D ∧ D.Nonempty ∧ D ⊆ C := by rcases exists_countable_union_perfect_of_isClosed hclosed with ⟨V, D, Vct, Dperf, VD⟩ refine ⟨D, ⟨Dperf, ?_⟩⟩ constructor · rw [nonempty_iff_ne_empty] by_contra h rw [h, union_empty] at VD rw [VD] at hunc contradiction rw [VD] exact subset_union_right end Kernel end Basic section PerfectSpace variable {X : Type*} [TopologicalSpace X] theorem perfectSpace_iff_forall_not_isolated : PerfectSpace X ↔ ∀ x : X, Filter.NeBot (𝓝[≠] x) := by simp [perfectSpace_def, Preperfect, AccPt] instance PerfectSpace.not_isolated [PerfectSpace X] (x : X) : Filter.NeBot (𝓝[≠] x) := perfectSpace_iff_forall_not_isolated.mp ‹_› x end PerfectSpace
Topology\QuasiSeparated.lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Topology.Separation import Mathlib.Topology.NoetherianSpace /-! # Quasi-separated spaces A topological space is quasi-separated if the intersections of any pairs of compact open subsets are still compact. Notable examples include spectral spaces, Noetherian spaces, and Hausdorff spaces. A non-example is the interval `[0, 1]` with doubled origin: the two copies of `[0, 1]` are compact open subsets, but their intersection `(0, 1]` is not. ## Main results - `IsQuasiSeparated`: A subset `s` of a topological space is quasi-separated if the intersections of any pairs of compact open subsets of `s` are still compact. - `QuasiSeparatedSpace`: A topological space is quasi-separated if the intersections of any pairs of compact open subsets are still compact. - `QuasiSeparatedSpace.of_openEmbedding`: If `f : α → β` is an open embedding, and `β` is a quasi-separated space, then so is `α`. -/ open TopologicalSpace variable {α β : Type*} [TopologicalSpace α] [TopologicalSpace β] {f : α → β} /-- A subset `s` of a topological space is quasi-separated if the intersections of any pairs of compact open subsets of `s` are still compact. Note that this is equivalent to `s` being a `QuasiSeparatedSpace` only when `s` is open. -/ def IsQuasiSeparated (s : Set α) : Prop := ∀ U V : Set α, U ⊆ s → IsOpen U → IsCompact U → V ⊆ s → IsOpen V → IsCompact V → IsCompact (U ∩ V) /-- A topological space is quasi-separated if the intersections of any pairs of compact open subsets are still compact. -/ @[mk_iff] class QuasiSeparatedSpace (α : Type*) [TopologicalSpace α] : Prop where /-- The intersection of two open compact subsets of a quasi-separated space is compact. -/ inter_isCompact : ∀ U V : Set α, IsOpen U → IsCompact U → IsOpen V → IsCompact V → IsCompact (U ∩ V) theorem isQuasiSeparated_univ_iff {α : Type*} [TopologicalSpace α] : IsQuasiSeparated (Set.univ : Set α) ↔ QuasiSeparatedSpace α := by rw [quasiSeparatedSpace_iff] simp [IsQuasiSeparated] theorem isQuasiSeparated_univ {α : Type*} [TopologicalSpace α] [QuasiSeparatedSpace α] : IsQuasiSeparated (Set.univ : Set α) := isQuasiSeparated_univ_iff.mpr inferInstance theorem IsQuasiSeparated.image_of_embedding {s : Set α} (H : IsQuasiSeparated s) (h : Embedding f) : IsQuasiSeparated (f '' s) := by intro U V hU hU' hU'' hV hV' hV'' convert (H (f ⁻¹' U) (f ⁻¹' V) ?_ (h.continuous.1 _ hU') ?_ ?_ (h.continuous.1 _ hV') ?_).image h.continuous · symm rw [← Set.preimage_inter, Set.image_preimage_eq_inter_range, Set.inter_eq_left] exact Set.inter_subset_left.trans (hU.trans (Set.image_subset_range _ _)) · intro x hx rw [← h.inj.injOn.mem_image_iff (Set.subset_univ _) trivial] exact hU hx · rw [h.isCompact_iff] convert hU'' rw [Set.image_preimage_eq_inter_range, Set.inter_eq_left] exact hU.trans (Set.image_subset_range _ _) · intro x hx rw [← h.inj.injOn.mem_image_iff (Set.subset_univ _) trivial] exact hV hx · rw [h.isCompact_iff] convert hV'' rw [Set.image_preimage_eq_inter_range, Set.inter_eq_left] exact hV.trans (Set.image_subset_range _ _) theorem OpenEmbedding.isQuasiSeparated_iff (h : OpenEmbedding f) {s : Set α} : IsQuasiSeparated s ↔ IsQuasiSeparated (f '' s) := by refine ⟨fun hs => hs.image_of_embedding h.toEmbedding, ?_⟩ intro H U V hU hU' hU'' hV hV' hV'' rw [h.toEmbedding.isCompact_iff, Set.image_inter h.inj] exact H (f '' U) (f '' V) (Set.image_subset _ hU) (h.isOpenMap _ hU') (hU''.image h.continuous) (Set.image_subset _ hV) (h.isOpenMap _ hV') (hV''.image h.continuous) theorem isQuasiSeparated_iff_quasiSeparatedSpace (s : Set α) (hs : IsOpen s) : IsQuasiSeparated s ↔ QuasiSeparatedSpace s := by rw [← isQuasiSeparated_univ_iff] convert (hs.openEmbedding_subtype_val.isQuasiSeparated_iff (s := Set.univ)).symm simp theorem IsQuasiSeparated.of_subset {s t : Set α} (ht : IsQuasiSeparated t) (h : s ⊆ t) : IsQuasiSeparated s := by intro U V hU hU' hU'' hV hV' hV'' exact ht U V (hU.trans h) hU' hU'' (hV.trans h) hV' hV'' instance (priority := 100) T2Space.to_quasiSeparatedSpace [T2Space α] : QuasiSeparatedSpace α := ⟨fun _ _ _ hU' _ hV' => hU'.inter hV'⟩ instance (priority := 100) NoetherianSpace.to_quasiSeparatedSpace [NoetherianSpace α] : QuasiSeparatedSpace α := ⟨fun _ _ _ _ _ _ => NoetherianSpace.isCompact _⟩ theorem IsQuasiSeparated.of_quasiSeparatedSpace (s : Set α) [QuasiSeparatedSpace α] : IsQuasiSeparated s := isQuasiSeparated_univ.of_subset (Set.subset_univ _) theorem QuasiSeparatedSpace.of_openEmbedding (h : OpenEmbedding f) [QuasiSeparatedSpace β] : QuasiSeparatedSpace α := isQuasiSeparated_univ_iff.mp (h.isQuasiSeparated_iff.mpr <| IsQuasiSeparated.of_quasiSeparatedSpace _)
Topology\RestrictGenTopology.lean
/- Copyright (c) 2024 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.Defs.Sequences import Mathlib.Topology.Compactness.Compact /-! # Topology generated by its restrictions to subsets We say that restrictions of the topology on `X` to sets from a family `S` generates the original topology, if either of the following equivalent conditions hold: - a set which is relatively open in each `s ∈ S` is open; - a set which is relatively closed in each `s ∈ S` is closed; - for any topological space `Y`, a function `f : X → Y` is continuous provided that it is continuous on each `s ∈ S`. We use the first condition as the definition (see `RestrictGenTopology` in `Mathlib/Topology/Defs/Induced.lean`), and provide the others as corollaries. ## Main results - `RestrictGenTopology.of_seq`: if `X` is a sequential space and `S` contains all sets of the form `insert x (Set.range u)`, where `u : ℕ → X` is a sequence that converges to `x`, then we have `RestrictGenTopology S`; - `RestrictGenTopology.isCompact_of_seq`: specialization of the previous lemma to the case `S = {K | IsCompact K}`. -/ open Set Filter open scoped Topology variable {X : Type*} [TopologicalSpace X] {S : Set (Set X)} {t : Set X} {x : X} namespace RestrictGenTopology protected theorem isOpen_iff (hS : RestrictGenTopology S) : IsOpen t ↔ ∀ s ∈ S, IsOpen ((↑) ⁻¹' t : Set s) := ⟨fun ht _ _ ↦ ht.preimage continuous_subtype_val, hS.1 t⟩ protected theorem isClosed_iff (hS : RestrictGenTopology S) : IsClosed t ↔ ∀ s ∈ S, IsClosed ((↑) ⁻¹' t : Set s) := by simp only [← isOpen_compl_iff, hS.isOpen_iff, preimage_compl] protected theorem continuous_iff {Y : Type*} [TopologicalSpace Y] {f : X → Y} (hS : RestrictGenTopology S) : Continuous f ↔ ∀ s ∈ S, ContinuousOn f s := ⟨fun h _ _ ↦ h.continuousOn, fun h ↦ continuous_def.2 fun _u hu ↦ hS.isOpen_iff.2 fun s hs ↦ hu.preimage <| (h s hs).restrict⟩ theorem of_continuous_prop (h : ∀ f : X → Prop, (∀ s ∈ S, ContinuousOn f s) → Continuous f) : RestrictGenTopology S where isOpen_of_forall_induced u hu := by simp only [continuousOn_iff_continuous_restrict, continuous_Prop] at * exact h _ hu theorem of_isClosed (h : ∀ t : Set X, (∀ s ∈ S, IsClosed ((↑) ⁻¹' t : Set s)) → IsClosed t) : RestrictGenTopology S := ⟨fun _t ht ↦ isClosed_compl_iff.1 <| h _ fun s hs ↦ (ht s hs).isClosed_compl⟩ protected theorem enlarge {T} (hS : RestrictGenTopology S) (hT : ∀ s ∈ S, ∃ t ∈ T, s ⊆ t) : RestrictGenTopology T := of_continuous_prop fun _f hf ↦ hS.continuous_iff.2 fun s hs ↦ let ⟨t, htT, hst⟩ := hT s hs; (hf t htT).mono hst protected theorem mono {T} (hS : RestrictGenTopology S) (hT : S ⊆ T) : RestrictGenTopology T := hS.enlarge fun s hs ↦ ⟨s, hT hs, Subset.rfl⟩ /-- If `X` is a sequential space and `S` contains each set of the form `insert x (Set.range u)` where `u : ℕ → X` is a sequence and `x` is its limit, then topology on `X` is generated by its restrictions to the sets of `S`. -/ lemma of_seq [SequentialSpace X] (h : ∀ ⦃u : ℕ → X⦄ ⦃x : X⦄, Tendsto u atTop (𝓝 x) → insert x (range u) ∈ S) : RestrictGenTopology S := by refine of_isClosed fun t ht ↦ IsSeqClosed.isClosed fun u x hut hux ↦ ?_ rcases isClosed_induced_iff.1 (ht _ (h hux)) with ⟨s, hsc, hst⟩ rw [Subtype.preimage_val_eq_preimage_val_iff, Set.ext_iff] at hst suffices x ∈ s by specialize hst x; simp_all refine hsc.mem_of_tendsto hux <| eventually_of_forall fun k ↦ ?_ specialize hst (u k) simp_all /-- A sequential space is compactly generated. -/ lemma isCompact_of_seq [SequentialSpace X] : RestrictGenTopology {K : Set X | IsCompact K} := of_seq fun _u _x hux ↦ hux.isCompact_insert_range end RestrictGenTopology
Topology\Semicontinuous.lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Algebra.GroupWithZero.Indicator import Mathlib.Topology.ContinuousOn import Mathlib.Topology.Instances.ENNReal /-! # Semicontinuous maps A function `f` from a topological space `α` to an ordered space `β` is lower semicontinuous at a point `x` if, for any `y < f x`, for any `x'` close enough to `x`, one has `f x' > y`. In other words, `f` can jump up, but it can not jump down. Upper semicontinuous functions are defined similarly. This file introduces these notions, and a basic API around them mimicking the API for continuous functions. ## Main definitions and results We introduce 4 definitions related to lower semicontinuity: * `LowerSemicontinuousWithinAt f s x` * `LowerSemicontinuousAt f x` * `LowerSemicontinuousOn f s` * `LowerSemicontinuous f` We build a basic API using dot notation around these notions, and we prove that * constant functions are lower semicontinuous; * `indicator s (fun _ ↦ y)` is lower semicontinuous when `s` is open and `0 ≤ y`, or when `s` is closed and `y ≤ 0`; * continuous functions are lower semicontinuous; * left composition with a continuous monotone functions maps lower semicontinuous functions to lower semicontinuous functions. If the function is anti-monotone, it instead maps lower semicontinuous functions to upper semicontinuous functions; * right composition with continuous functions preserves lower and upper semicontinuity; * a sum of two (or finitely many) lower semicontinuous functions is lower semicontinuous; * a supremum of a family of lower semicontinuous functions is lower semicontinuous; * An infinite sum of `ℝ≥0∞`-valued lower semicontinuous functions is lower semicontinuous. Similar results are stated and proved for upper semicontinuity. We also prove that a function is continuous if and only if it is both lower and upper semicontinuous. We have some equivalent definitions of lower- and upper-semicontinuity (under certain restrictions on the order on the codomain): * `lowerSemicontinuous_iff_isOpen_preimage` in a linear order; * `lowerSemicontinuous_iff_isClosed_preimage` in a linear order; * `lowerSemicontinuousAt_iff_le_liminf` in a dense complete linear order; * `lowerSemicontinuous_iff_isClosed_epigraph` in a dense complete linear order with the order topology. ## Implementation details All the nontrivial results for upper semicontinuous functions are deduced from the corresponding ones for lower semicontinuous functions using `OrderDual`. ## References * <https://en.wikipedia.org/wiki/Closed_convex_function> * <https://en.wikipedia.org/wiki/Semi-continuity> -/ open Topology ENNReal open Set Function Filter variable {α : Type*} [TopologicalSpace α] {β : Type*} [Preorder β] {f g : α → β} {x : α} {s t : Set α} {y z : β} /-! ### Main definitions -/ /-- A real function `f` is lower semicontinuous at `x` within a set `s` if, for any `ε > 0`, for all `x'` close enough to `x` in `s`, then `f x'` is at least `f x - ε`. We formulate this in a general preordered space, using an arbitrary `y < f x` instead of `f x - ε`. -/ def LowerSemicontinuousWithinAt (f : α → β) (s : Set α) (x : α) := ∀ y < f x, ∀ᶠ x' in 𝓝[s] x, y < f x' /-- A real function `f` is lower semicontinuous on a set `s` if, for any `ε > 0`, for any `x ∈ s`, for all `x'` close enough to `x` in `s`, then `f x'` is at least `f x - ε`. We formulate this in a general preordered space, using an arbitrary `y < f x` instead of `f x - ε`. -/ def LowerSemicontinuousOn (f : α → β) (s : Set α) := ∀ x ∈ s, LowerSemicontinuousWithinAt f s x /-- A real function `f` is lower semicontinuous at `x` if, for any `ε > 0`, for all `x'` close enough to `x`, then `f x'` is at least `f x - ε`. We formulate this in a general preordered space, using an arbitrary `y < f x` instead of `f x - ε`. -/ def LowerSemicontinuousAt (f : α → β) (x : α) := ∀ y < f x, ∀ᶠ x' in 𝓝 x, y < f x' /-- A real function `f` is lower semicontinuous if, for any `ε > 0`, for any `x`, for all `x'` close enough to `x`, then `f x'` is at least `f x - ε`. We formulate this in a general preordered space, using an arbitrary `y < f x` instead of `f x - ε`. -/ def LowerSemicontinuous (f : α → β) := ∀ x, LowerSemicontinuousAt f x /-- A real function `f` is upper semicontinuous at `x` within a set `s` if, for any `ε > 0`, for all `x'` close enough to `x` in `s`, then `f x'` is at most `f x + ε`. We formulate this in a general preordered space, using an arbitrary `y > f x` instead of `f x + ε`. -/ def UpperSemicontinuousWithinAt (f : α → β) (s : Set α) (x : α) := ∀ y, f x < y → ∀ᶠ x' in 𝓝[s] x, f x' < y /-- A real function `f` is upper semicontinuous on a set `s` if, for any `ε > 0`, for any `x ∈ s`, for all `x'` close enough to `x` in `s`, then `f x'` is at most `f x + ε`. We formulate this in a general preordered space, using an arbitrary `y > f x` instead of `f x + ε`. -/ def UpperSemicontinuousOn (f : α → β) (s : Set α) := ∀ x ∈ s, UpperSemicontinuousWithinAt f s x /-- A real function `f` is upper semicontinuous at `x` if, for any `ε > 0`, for all `x'` close enough to `x`, then `f x'` is at most `f x + ε`. We formulate this in a general preordered space, using an arbitrary `y > f x` instead of `f x + ε`. -/ def UpperSemicontinuousAt (f : α → β) (x : α) := ∀ y, f x < y → ∀ᶠ x' in 𝓝 x, f x' < y /-- A real function `f` is upper semicontinuous if, for any `ε > 0`, for any `x`, for all `x'` close enough to `x`, then `f x'` is at most `f x + ε`. We formulate this in a general preordered space, using an arbitrary `y > f x` instead of `f x + ε`. -/ def UpperSemicontinuous (f : α → β) := ∀ x, UpperSemicontinuousAt f x /-! ### Lower semicontinuous functions -/ /-! #### Basic dot notation interface for lower semicontinuity -/ theorem LowerSemicontinuousWithinAt.mono (h : LowerSemicontinuousWithinAt f s x) (hst : t ⊆ s) : LowerSemicontinuousWithinAt f t x := fun y hy => Filter.Eventually.filter_mono (nhdsWithin_mono _ hst) (h y hy) theorem lowerSemicontinuousWithinAt_univ_iff : LowerSemicontinuousWithinAt f univ x ↔ LowerSemicontinuousAt f x := by simp [LowerSemicontinuousWithinAt, LowerSemicontinuousAt, nhdsWithin_univ] theorem LowerSemicontinuousAt.lowerSemicontinuousWithinAt (s : Set α) (h : LowerSemicontinuousAt f x) : LowerSemicontinuousWithinAt f s x := fun y hy => Filter.Eventually.filter_mono nhdsWithin_le_nhds (h y hy) theorem LowerSemicontinuousOn.lowerSemicontinuousWithinAt (h : LowerSemicontinuousOn f s) (hx : x ∈ s) : LowerSemicontinuousWithinAt f s x := h x hx theorem LowerSemicontinuousOn.mono (h : LowerSemicontinuousOn f s) (hst : t ⊆ s) : LowerSemicontinuousOn f t := fun x hx => (h x (hst hx)).mono hst theorem lowerSemicontinuousOn_univ_iff : LowerSemicontinuousOn f univ ↔ LowerSemicontinuous f := by simp [LowerSemicontinuousOn, LowerSemicontinuous, lowerSemicontinuousWithinAt_univ_iff] theorem LowerSemicontinuous.lowerSemicontinuousAt (h : LowerSemicontinuous f) (x : α) : LowerSemicontinuousAt f x := h x theorem LowerSemicontinuous.lowerSemicontinuousWithinAt (h : LowerSemicontinuous f) (s : Set α) (x : α) : LowerSemicontinuousWithinAt f s x := (h x).lowerSemicontinuousWithinAt s theorem LowerSemicontinuous.lowerSemicontinuousOn (h : LowerSemicontinuous f) (s : Set α) : LowerSemicontinuousOn f s := fun x _hx => h.lowerSemicontinuousWithinAt s x /-! #### Constants -/ theorem lowerSemicontinuousWithinAt_const : LowerSemicontinuousWithinAt (fun _x => z) s x := fun _y hy => Filter.eventually_of_forall fun _x => hy theorem lowerSemicontinuousAt_const : LowerSemicontinuousAt (fun _x => z) x := fun _y hy => Filter.eventually_of_forall fun _x => hy theorem lowerSemicontinuousOn_const : LowerSemicontinuousOn (fun _x => z) s := fun _x _hx => lowerSemicontinuousWithinAt_const theorem lowerSemicontinuous_const : LowerSemicontinuous fun _x : α => z := fun _x => lowerSemicontinuousAt_const /-! #### Indicators -/ section variable [Zero β] theorem IsOpen.lowerSemicontinuous_indicator (hs : IsOpen s) (hy : 0 ≤ y) : LowerSemicontinuous (indicator s fun _x => y) := by intro x z hz by_cases h : x ∈ s <;> simp [h] at hz · filter_upwards [hs.mem_nhds h] simp (config := { contextual := true }) [hz] · refine Filter.eventually_of_forall fun x' => ?_ by_cases h' : x' ∈ s <;> simp [h', hz.trans_le hy, hz] theorem IsOpen.lowerSemicontinuousOn_indicator (hs : IsOpen s) (hy : 0 ≤ y) : LowerSemicontinuousOn (indicator s fun _x => y) t := (hs.lowerSemicontinuous_indicator hy).lowerSemicontinuousOn t theorem IsOpen.lowerSemicontinuousAt_indicator (hs : IsOpen s) (hy : 0 ≤ y) : LowerSemicontinuousAt (indicator s fun _x => y) x := (hs.lowerSemicontinuous_indicator hy).lowerSemicontinuousAt x theorem IsOpen.lowerSemicontinuousWithinAt_indicator (hs : IsOpen s) (hy : 0 ≤ y) : LowerSemicontinuousWithinAt (indicator s fun _x => y) t x := (hs.lowerSemicontinuous_indicator hy).lowerSemicontinuousWithinAt t x theorem IsClosed.lowerSemicontinuous_indicator (hs : IsClosed s) (hy : y ≤ 0) : LowerSemicontinuous (indicator s fun _x => y) := by intro x z hz by_cases h : x ∈ s <;> simp [h] at hz · refine Filter.eventually_of_forall fun x' => ?_ by_cases h' : x' ∈ s <;> simp [h', hz, hz.trans_le hy] · filter_upwards [hs.isOpen_compl.mem_nhds h] simp (config := { contextual := true }) [hz] theorem IsClosed.lowerSemicontinuousOn_indicator (hs : IsClosed s) (hy : y ≤ 0) : LowerSemicontinuousOn (indicator s fun _x => y) t := (hs.lowerSemicontinuous_indicator hy).lowerSemicontinuousOn t theorem IsClosed.lowerSemicontinuousAt_indicator (hs : IsClosed s) (hy : y ≤ 0) : LowerSemicontinuousAt (indicator s fun _x => y) x := (hs.lowerSemicontinuous_indicator hy).lowerSemicontinuousAt x theorem IsClosed.lowerSemicontinuousWithinAt_indicator (hs : IsClosed s) (hy : y ≤ 0) : LowerSemicontinuousWithinAt (indicator s fun _x => y) t x := (hs.lowerSemicontinuous_indicator hy).lowerSemicontinuousWithinAt t x end /-! #### Relationship with continuity -/ theorem lowerSemicontinuous_iff_isOpen_preimage : LowerSemicontinuous f ↔ ∀ y, IsOpen (f ⁻¹' Ioi y) := ⟨fun H y => isOpen_iff_mem_nhds.2 fun x hx => H x y hx, fun H _x y y_lt => IsOpen.mem_nhds (H y) y_lt⟩ theorem LowerSemicontinuous.isOpen_preimage (hf : LowerSemicontinuous f) (y : β) : IsOpen (f ⁻¹' Ioi y) := lowerSemicontinuous_iff_isOpen_preimage.1 hf y section variable {γ : Type*} [LinearOrder γ] theorem lowerSemicontinuous_iff_isClosed_preimage {f : α → γ} : LowerSemicontinuous f ↔ ∀ y, IsClosed (f ⁻¹' Iic y) := by rw [lowerSemicontinuous_iff_isOpen_preimage] simp only [← isOpen_compl_iff, ← preimage_compl, compl_Iic] theorem LowerSemicontinuous.isClosed_preimage {f : α → γ} (hf : LowerSemicontinuous f) (y : γ) : IsClosed (f ⁻¹' Iic y) := lowerSemicontinuous_iff_isClosed_preimage.1 hf y variable [TopologicalSpace γ] [OrderTopology γ] theorem ContinuousWithinAt.lowerSemicontinuousWithinAt {f : α → γ} (h : ContinuousWithinAt f s x) : LowerSemicontinuousWithinAt f s x := fun _y hy => h (Ioi_mem_nhds hy) theorem ContinuousAt.lowerSemicontinuousAt {f : α → γ} (h : ContinuousAt f x) : LowerSemicontinuousAt f x := fun _y hy => h (Ioi_mem_nhds hy) theorem ContinuousOn.lowerSemicontinuousOn {f : α → γ} (h : ContinuousOn f s) : LowerSemicontinuousOn f s := fun x hx => (h x hx).lowerSemicontinuousWithinAt theorem Continuous.lowerSemicontinuous {f : α → γ} (h : Continuous f) : LowerSemicontinuous f := fun _x => h.continuousAt.lowerSemicontinuousAt end /-! #### Equivalent definitions -/ section variable {γ : Type*} [CompleteLinearOrder γ] [DenselyOrdered γ] theorem lowerSemicontinuousWithinAt_iff_le_liminf {f : α → γ} : LowerSemicontinuousWithinAt f s x ↔ f x ≤ liminf f (𝓝[s] x) := by constructor · intro hf; unfold LowerSemicontinuousWithinAt at hf contrapose! hf obtain ⟨y, lty, ylt⟩ := exists_between hf; use y exact ⟨ylt, fun h => lty.not_le (le_liminf_of_le (by isBoundedDefault) (h.mono fun _ hx => le_of_lt hx))⟩ exact fun hf y ylt => eventually_lt_of_lt_liminf (ylt.trans_le hf) alias ⟨LowerSemicontinuousWithinAt.le_liminf, _⟩ := lowerSemicontinuousWithinAt_iff_le_liminf theorem lowerSemicontinuousAt_iff_le_liminf {f : α → γ} : LowerSemicontinuousAt f x ↔ f x ≤ liminf f (𝓝 x) := by rw [← lowerSemicontinuousWithinAt_univ_iff, lowerSemicontinuousWithinAt_iff_le_liminf, ← nhdsWithin_univ] alias ⟨LowerSemicontinuousAt.le_liminf, _⟩ := lowerSemicontinuousAt_iff_le_liminf theorem lowerSemicontinuous_iff_le_liminf {f : α → γ} : LowerSemicontinuous f ↔ ∀ x, f x ≤ liminf f (𝓝 x) := by simp only [← lowerSemicontinuousAt_iff_le_liminf, LowerSemicontinuous] alias ⟨LowerSemicontinuous.le_liminf, _⟩ := lowerSemicontinuous_iff_le_liminf theorem lowerSemicontinuousOn_iff_le_liminf {f : α → γ} : LowerSemicontinuousOn f s ↔ ∀ x ∈ s, f x ≤ liminf f (𝓝[s] x) := by simp only [← lowerSemicontinuousWithinAt_iff_le_liminf, LowerSemicontinuousOn] alias ⟨LowerSemicontinuousOn.le_liminf, _⟩ := lowerSemicontinuousOn_iff_le_liminf variable [TopologicalSpace γ] [OrderTopology γ] theorem lowerSemicontinuous_iff_isClosed_epigraph {f : α → γ} : LowerSemicontinuous f ↔ IsClosed {p : α × γ | f p.1 ≤ p.2} := by constructor · rw [lowerSemicontinuous_iff_le_liminf, isClosed_iff_forall_filter] rintro hf ⟨x, y⟩ F F_ne h h' rw [nhds_prod_eq, le_prod] at h' calc f x ≤ liminf f (𝓝 x) := hf x _ ≤ liminf f (map Prod.fst F) := liminf_le_liminf_of_le h'.1 _ = liminf (f ∘ Prod.fst) F := (Filter.liminf_comp _ _ _).symm _ ≤ liminf Prod.snd F := liminf_le_liminf <| by simpa using (eventually_principal.2 fun (_ : α × γ) ↦ id).filter_mono h _ = y := h'.2.liminf_eq · rw [lowerSemicontinuous_iff_isClosed_preimage] exact fun hf y ↦ hf.preimage (Continuous.Prod.mk_left y) @[deprecated (since := "2024-03-02")] alias lowerSemicontinuous_iff_IsClosed_epigraph := lowerSemicontinuous_iff_isClosed_epigraph alias ⟨LowerSemicontinuous.isClosed_epigraph, _⟩ := lowerSemicontinuous_iff_isClosed_epigraph @[deprecated (since := "2024-03-02")] alias LowerSemicontinuous.IsClosed_epigraph := LowerSemicontinuous.isClosed_epigraph end /-! ### Composition -/ section variable {γ : Type*} [LinearOrder γ] [TopologicalSpace γ] [OrderTopology γ] variable {δ : Type*} [LinearOrder δ] [TopologicalSpace δ] [OrderTopology δ] variable {ι : Type*} [TopologicalSpace ι] theorem ContinuousAt.comp_lowerSemicontinuousWithinAt {g : γ → δ} {f : α → γ} (hg : ContinuousAt g (f x)) (hf : LowerSemicontinuousWithinAt f s x) (gmon : Monotone g) : LowerSemicontinuousWithinAt (g ∘ f) s x := by intro y hy by_cases h : ∃ l, l < f x · obtain ⟨z, zlt, hz⟩ : ∃ z < f x, Ioc z (f x) ⊆ g ⁻¹' Ioi y := exists_Ioc_subset_of_mem_nhds (hg (Ioi_mem_nhds hy)) h filter_upwards [hf z zlt] with a ha calc y < g (min (f x) (f a)) := hz (by simp [zlt, ha, le_refl]) _ ≤ g (f a) := gmon (min_le_right _ _) · simp only [not_exists, not_lt] at h exact Filter.eventually_of_forall fun a => hy.trans_le (gmon (h (f a))) theorem ContinuousAt.comp_lowerSemicontinuousAt {g : γ → δ} {f : α → γ} (hg : ContinuousAt g (f x)) (hf : LowerSemicontinuousAt f x) (gmon : Monotone g) : LowerSemicontinuousAt (g ∘ f) x := by simp only [← lowerSemicontinuousWithinAt_univ_iff] at hf ⊢ exact hg.comp_lowerSemicontinuousWithinAt hf gmon theorem Continuous.comp_lowerSemicontinuousOn {g : γ → δ} {f : α → γ} (hg : Continuous g) (hf : LowerSemicontinuousOn f s) (gmon : Monotone g) : LowerSemicontinuousOn (g ∘ f) s := fun x hx => hg.continuousAt.comp_lowerSemicontinuousWithinAt (hf x hx) gmon theorem Continuous.comp_lowerSemicontinuous {g : γ → δ} {f : α → γ} (hg : Continuous g) (hf : LowerSemicontinuous f) (gmon : Monotone g) : LowerSemicontinuous (g ∘ f) := fun x => hg.continuousAt.comp_lowerSemicontinuousAt (hf x) gmon theorem ContinuousAt.comp_lowerSemicontinuousWithinAt_antitone {g : γ → δ} {f : α → γ} (hg : ContinuousAt g (f x)) (hf : LowerSemicontinuousWithinAt f s x) (gmon : Antitone g) : UpperSemicontinuousWithinAt (g ∘ f) s x := @ContinuousAt.comp_lowerSemicontinuousWithinAt α _ x s γ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon theorem ContinuousAt.comp_lowerSemicontinuousAt_antitone {g : γ → δ} {f : α → γ} (hg : ContinuousAt g (f x)) (hf : LowerSemicontinuousAt f x) (gmon : Antitone g) : UpperSemicontinuousAt (g ∘ f) x := @ContinuousAt.comp_lowerSemicontinuousAt α _ x γ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon theorem Continuous.comp_lowerSemicontinuousOn_antitone {g : γ → δ} {f : α → γ} (hg : Continuous g) (hf : LowerSemicontinuousOn f s) (gmon : Antitone g) : UpperSemicontinuousOn (g ∘ f) s := fun x hx => hg.continuousAt.comp_lowerSemicontinuousWithinAt_antitone (hf x hx) gmon theorem Continuous.comp_lowerSemicontinuous_antitone {g : γ → δ} {f : α → γ} (hg : Continuous g) (hf : LowerSemicontinuous f) (gmon : Antitone g) : UpperSemicontinuous (g ∘ f) := fun x => hg.continuousAt.comp_lowerSemicontinuousAt_antitone (hf x) gmon theorem LowerSemicontinuousAt.comp_continuousAt {f : α → β} {g : ι → α} {x : ι} (hf : LowerSemicontinuousAt f (g x)) (hg : ContinuousAt g x) : LowerSemicontinuousAt (fun x ↦ f (g x)) x := fun _ lt ↦ hg.eventually (hf _ lt) theorem LowerSemicontinuousAt.comp_continuousAt_of_eq {f : α → β} {g : ι → α} {y : α} {x : ι} (hf : LowerSemicontinuousAt f y) (hg : ContinuousAt g x) (hy : g x = y) : LowerSemicontinuousAt (fun x ↦ f (g x)) x := by rw [← hy] at hf exact comp_continuousAt hf hg theorem LowerSemicontinuous.comp_continuous {f : α → β} {g : ι → α} (hf : LowerSemicontinuous f) (hg : Continuous g) : LowerSemicontinuous fun x ↦ f (g x) := fun x ↦ (hf (g x)).comp_continuousAt hg.continuousAt end /-! #### Addition -/ section variable {ι : Type*} {γ : Type*} [LinearOrderedAddCommMonoid γ] [TopologicalSpace γ] [OrderTopology γ] /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `EReal`. The unprimed version of the lemma uses `[ContinuousAdd]`. -/ theorem LowerSemicontinuousWithinAt.add' {f g : α → γ} (hf : LowerSemicontinuousWithinAt f s x) (hg : LowerSemicontinuousWithinAt g s x) (hcont : ContinuousAt (fun p : γ × γ => p.1 + p.2) (f x, g x)) : LowerSemicontinuousWithinAt (fun z => f z + g z) s x := by intro y hy obtain ⟨u, v, u_open, xu, v_open, xv, h⟩ : ∃ u v : Set γ, IsOpen u ∧ f x ∈ u ∧ IsOpen v ∧ g x ∈ v ∧ u ×ˢ v ⊆ { p : γ × γ | y < p.fst + p.snd } := mem_nhds_prod_iff'.1 (hcont (isOpen_Ioi.mem_nhds hy)) by_cases hx₁ : ∃ l, l < f x · obtain ⟨z₁, z₁lt, h₁⟩ : ∃ z₁ < f x, Ioc z₁ (f x) ⊆ u := exists_Ioc_subset_of_mem_nhds (u_open.mem_nhds xu) hx₁ by_cases hx₂ : ∃ l, l < g x · obtain ⟨z₂, z₂lt, h₂⟩ : ∃ z₂ < g x, Ioc z₂ (g x) ⊆ v := exists_Ioc_subset_of_mem_nhds (v_open.mem_nhds xv) hx₂ filter_upwards [hf z₁ z₁lt, hg z₂ z₂lt] with z h₁z h₂z have A1 : min (f z) (f x) ∈ u := by by_cases H : f z ≤ f x · simpa [H] using h₁ ⟨h₁z, H⟩ · simpa [le_of_not_le H] have A2 : min (g z) (g x) ∈ v := by by_cases H : g z ≤ g x · simpa [H] using h₂ ⟨h₂z, H⟩ · simpa [le_of_not_le H] have : (min (f z) (f x), min (g z) (g x)) ∈ u ×ˢ v := ⟨A1, A2⟩ calc y < min (f z) (f x) + min (g z) (g x) := h this _ ≤ f z + g z := add_le_add (min_le_left _ _) (min_le_left _ _) · simp only [not_exists, not_lt] at hx₂ filter_upwards [hf z₁ z₁lt] with z h₁z have A1 : min (f z) (f x) ∈ u := by by_cases H : f z ≤ f x · simpa [H] using h₁ ⟨h₁z, H⟩ · simpa [le_of_not_le H] have : (min (f z) (f x), g x) ∈ u ×ˢ v := ⟨A1, xv⟩ calc y < min (f z) (f x) + g x := h this _ ≤ f z + g z := add_le_add (min_le_left _ _) (hx₂ (g z)) · simp only [not_exists, not_lt] at hx₁ by_cases hx₂ : ∃ l, l < g x · obtain ⟨z₂, z₂lt, h₂⟩ : ∃ z₂ < g x, Ioc z₂ (g x) ⊆ v := exists_Ioc_subset_of_mem_nhds (v_open.mem_nhds xv) hx₂ filter_upwards [hg z₂ z₂lt] with z h₂z have A2 : min (g z) (g x) ∈ v := by by_cases H : g z ≤ g x · simpa [H] using h₂ ⟨h₂z, H⟩ · simpa [le_of_not_le H] using h₂ ⟨z₂lt, le_rfl⟩ have : (f x, min (g z) (g x)) ∈ u ×ˢ v := ⟨xu, A2⟩ calc y < f x + min (g z) (g x) := h this _ ≤ f z + g z := add_le_add (hx₁ (f z)) (min_le_left _ _) · simp only [not_exists, not_lt] at hx₁ hx₂ apply Filter.eventually_of_forall intro z have : (f x, g x) ∈ u ×ˢ v := ⟨xu, xv⟩ calc y < f x + g x := h this _ ≤ f z + g z := add_le_add (hx₁ (f z)) (hx₂ (g z)) /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `EReal`. The unprimed version of the lemma uses `[ContinuousAdd]`. -/ theorem LowerSemicontinuousAt.add' {f g : α → γ} (hf : LowerSemicontinuousAt f x) (hg : LowerSemicontinuousAt g x) (hcont : ContinuousAt (fun p : γ × γ => p.1 + p.2) (f x, g x)) : LowerSemicontinuousAt (fun z => f z + g z) x := by simp_rw [← lowerSemicontinuousWithinAt_univ_iff] at * exact hf.add' hg hcont /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `EReal`. The unprimed version of the lemma uses `[ContinuousAdd]`. -/ theorem LowerSemicontinuousOn.add' {f g : α → γ} (hf : LowerSemicontinuousOn f s) (hg : LowerSemicontinuousOn g s) (hcont : ∀ x ∈ s, ContinuousAt (fun p : γ × γ => p.1 + p.2) (f x, g x)) : LowerSemicontinuousOn (fun z => f z + g z) s := fun x hx => (hf x hx).add' (hg x hx) (hcont x hx) /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `EReal`. The unprimed version of the lemma uses `[ContinuousAdd]`. -/ theorem LowerSemicontinuous.add' {f g : α → γ} (hf : LowerSemicontinuous f) (hg : LowerSemicontinuous g) (hcont : ∀ x, ContinuousAt (fun p : γ × γ => p.1 + p.2) (f x, g x)) : LowerSemicontinuous fun z => f z + g z := fun x => (hf x).add' (hg x) (hcont x) variable [ContinuousAdd γ] /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with `[ContinuousAdd]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `EReal`. -/ theorem LowerSemicontinuousWithinAt.add {f g : α → γ} (hf : LowerSemicontinuousWithinAt f s x) (hg : LowerSemicontinuousWithinAt g s x) : LowerSemicontinuousWithinAt (fun z => f z + g z) s x := hf.add' hg continuous_add.continuousAt /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with `[ContinuousAdd]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `EReal`. -/ theorem LowerSemicontinuousAt.add {f g : α → γ} (hf : LowerSemicontinuousAt f x) (hg : LowerSemicontinuousAt g x) : LowerSemicontinuousAt (fun z => f z + g z) x := hf.add' hg continuous_add.continuousAt /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with `[ContinuousAdd]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `EReal`. -/ theorem LowerSemicontinuousOn.add {f g : α → γ} (hf : LowerSemicontinuousOn f s) (hg : LowerSemicontinuousOn g s) : LowerSemicontinuousOn (fun z => f z + g z) s := hf.add' hg fun _x _hx => continuous_add.continuousAt /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with `[ContinuousAdd]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `EReal`. -/ theorem LowerSemicontinuous.add {f g : α → γ} (hf : LowerSemicontinuous f) (hg : LowerSemicontinuous g) : LowerSemicontinuous fun z => f z + g z := hf.add' hg fun _x => continuous_add.continuousAt theorem lowerSemicontinuousWithinAt_sum {f : ι → α → γ} {a : Finset ι} (ha : ∀ i ∈ a, LowerSemicontinuousWithinAt (f i) s x) : LowerSemicontinuousWithinAt (fun z => ∑ i ∈ a, f i z) s x := by classical induction' a using Finset.induction_on with i a ia IH · exact lowerSemicontinuousWithinAt_const · simp only [ia, Finset.sum_insert, not_false_iff] exact LowerSemicontinuousWithinAt.add (ha _ (Finset.mem_insert_self i a)) (IH fun j ja => ha j (Finset.mem_insert_of_mem ja)) theorem lowerSemicontinuousAt_sum {f : ι → α → γ} {a : Finset ι} (ha : ∀ i ∈ a, LowerSemicontinuousAt (f i) x) : LowerSemicontinuousAt (fun z => ∑ i ∈ a, f i z) x := by simp_rw [← lowerSemicontinuousWithinAt_univ_iff] at * exact lowerSemicontinuousWithinAt_sum ha theorem lowerSemicontinuousOn_sum {f : ι → α → γ} {a : Finset ι} (ha : ∀ i ∈ a, LowerSemicontinuousOn (f i) s) : LowerSemicontinuousOn (fun z => ∑ i ∈ a, f i z) s := fun x hx => lowerSemicontinuousWithinAt_sum fun i hi => ha i hi x hx theorem lowerSemicontinuous_sum {f : ι → α → γ} {a : Finset ι} (ha : ∀ i ∈ a, LowerSemicontinuous (f i)) : LowerSemicontinuous fun z => ∑ i ∈ a, f i z := fun x => lowerSemicontinuousAt_sum fun i hi => ha i hi x end /-! #### Supremum -/ section variable {ι : Sort*} {δ δ' : Type*} [CompleteLinearOrder δ] [ConditionallyCompleteLinearOrder δ'] theorem lowerSemicontinuousWithinAt_ciSup {f : ι → α → δ'} (bdd : ∀ᶠ y in 𝓝[s] x, BddAbove (range fun i => f i y)) (h : ∀ i, LowerSemicontinuousWithinAt (f i) s x) : LowerSemicontinuousWithinAt (fun x' => ⨆ i, f i x') s x := by cases isEmpty_or_nonempty ι · simpa only [iSup_of_empty'] using lowerSemicontinuousWithinAt_const · intro y hy rcases exists_lt_of_lt_ciSup hy with ⟨i, hi⟩ filter_upwards [h i y hi, bdd] with y hy hy' using hy.trans_le (le_ciSup hy' i) theorem lowerSemicontinuousWithinAt_iSup {f : ι → α → δ} (h : ∀ i, LowerSemicontinuousWithinAt (f i) s x) : LowerSemicontinuousWithinAt (fun x' => ⨆ i, f i x') s x := lowerSemicontinuousWithinAt_ciSup (by simp) h theorem lowerSemicontinuousWithinAt_biSup {p : ι → Prop} {f : ∀ i, p i → α → δ} (h : ∀ i hi, LowerSemicontinuousWithinAt (f i hi) s x) : LowerSemicontinuousWithinAt (fun x' => ⨆ (i) (hi), f i hi x') s x := lowerSemicontinuousWithinAt_iSup fun i => lowerSemicontinuousWithinAt_iSup fun hi => h i hi theorem lowerSemicontinuousAt_ciSup {f : ι → α → δ'} (bdd : ∀ᶠ y in 𝓝 x, BddAbove (range fun i => f i y)) (h : ∀ i, LowerSemicontinuousAt (f i) x) : LowerSemicontinuousAt (fun x' => ⨆ i, f i x') x := by simp_rw [← lowerSemicontinuousWithinAt_univ_iff] at * rw [← nhdsWithin_univ] at bdd exact lowerSemicontinuousWithinAt_ciSup bdd h theorem lowerSemicontinuousAt_iSup {f : ι → α → δ} (h : ∀ i, LowerSemicontinuousAt (f i) x) : LowerSemicontinuousAt (fun x' => ⨆ i, f i x') x := lowerSemicontinuousAt_ciSup (by simp) h theorem lowerSemicontinuousAt_biSup {p : ι → Prop} {f : ∀ i, p i → α → δ} (h : ∀ i hi, LowerSemicontinuousAt (f i hi) x) : LowerSemicontinuousAt (fun x' => ⨆ (i) (hi), f i hi x') x := lowerSemicontinuousAt_iSup fun i => lowerSemicontinuousAt_iSup fun hi => h i hi theorem lowerSemicontinuousOn_ciSup {f : ι → α → δ'} (bdd : ∀ x ∈ s, BddAbove (range fun i => f i x)) (h : ∀ i, LowerSemicontinuousOn (f i) s) : LowerSemicontinuousOn (fun x' => ⨆ i, f i x') s := fun x hx => lowerSemicontinuousWithinAt_ciSup (eventually_nhdsWithin_of_forall bdd) fun i => h i x hx theorem lowerSemicontinuousOn_iSup {f : ι → α → δ} (h : ∀ i, LowerSemicontinuousOn (f i) s) : LowerSemicontinuousOn (fun x' => ⨆ i, f i x') s := lowerSemicontinuousOn_ciSup (by simp) h theorem lowerSemicontinuousOn_biSup {p : ι → Prop} {f : ∀ i, p i → α → δ} (h : ∀ i hi, LowerSemicontinuousOn (f i hi) s) : LowerSemicontinuousOn (fun x' => ⨆ (i) (hi), f i hi x') s := lowerSemicontinuousOn_iSup fun i => lowerSemicontinuousOn_iSup fun hi => h i hi theorem lowerSemicontinuous_ciSup {f : ι → α → δ'} (bdd : ∀ x, BddAbove (range fun i => f i x)) (h : ∀ i, LowerSemicontinuous (f i)) : LowerSemicontinuous fun x' => ⨆ i, f i x' := fun x => lowerSemicontinuousAt_ciSup (eventually_of_forall bdd) fun i => h i x theorem lowerSemicontinuous_iSup {f : ι → α → δ} (h : ∀ i, LowerSemicontinuous (f i)) : LowerSemicontinuous fun x' => ⨆ i, f i x' := lowerSemicontinuous_ciSup (by simp) h theorem lowerSemicontinuous_biSup {p : ι → Prop} {f : ∀ i, p i → α → δ} (h : ∀ i hi, LowerSemicontinuous (f i hi)) : LowerSemicontinuous fun x' => ⨆ (i) (hi), f i hi x' := lowerSemicontinuous_iSup fun i => lowerSemicontinuous_iSup fun hi => h i hi end /-! #### Infinite sums -/ section variable {ι : Type*} theorem lowerSemicontinuousWithinAt_tsum {f : ι → α → ℝ≥0∞} (h : ∀ i, LowerSemicontinuousWithinAt (f i) s x) : LowerSemicontinuousWithinAt (fun x' => ∑' i, f i x') s x := by simp_rw [ENNReal.tsum_eq_iSup_sum] refine lowerSemicontinuousWithinAt_iSup fun b => ?_ exact lowerSemicontinuousWithinAt_sum fun i _hi => h i theorem lowerSemicontinuousAt_tsum {f : ι → α → ℝ≥0∞} (h : ∀ i, LowerSemicontinuousAt (f i) x) : LowerSemicontinuousAt (fun x' => ∑' i, f i x') x := by simp_rw [← lowerSemicontinuousWithinAt_univ_iff] at * exact lowerSemicontinuousWithinAt_tsum h theorem lowerSemicontinuousOn_tsum {f : ι → α → ℝ≥0∞} (h : ∀ i, LowerSemicontinuousOn (f i) s) : LowerSemicontinuousOn (fun x' => ∑' i, f i x') s := fun x hx => lowerSemicontinuousWithinAt_tsum fun i => h i x hx theorem lowerSemicontinuous_tsum {f : ι → α → ℝ≥0∞} (h : ∀ i, LowerSemicontinuous (f i)) : LowerSemicontinuous fun x' => ∑' i, f i x' := fun x => lowerSemicontinuousAt_tsum fun i => h i x end /-! ### Upper semicontinuous functions -/ /-! #### Basic dot notation interface for upper semicontinuity -/ theorem UpperSemicontinuousWithinAt.mono (h : UpperSemicontinuousWithinAt f s x) (hst : t ⊆ s) : UpperSemicontinuousWithinAt f t x := fun y hy => Filter.Eventually.filter_mono (nhdsWithin_mono _ hst) (h y hy) theorem upperSemicontinuousWithinAt_univ_iff : UpperSemicontinuousWithinAt f univ x ↔ UpperSemicontinuousAt f x := by simp [UpperSemicontinuousWithinAt, UpperSemicontinuousAt, nhdsWithin_univ] theorem UpperSemicontinuousAt.upperSemicontinuousWithinAt (s : Set α) (h : UpperSemicontinuousAt f x) : UpperSemicontinuousWithinAt f s x := fun y hy => Filter.Eventually.filter_mono nhdsWithin_le_nhds (h y hy) theorem UpperSemicontinuousOn.upperSemicontinuousWithinAt (h : UpperSemicontinuousOn f s) (hx : x ∈ s) : UpperSemicontinuousWithinAt f s x := h x hx theorem UpperSemicontinuousOn.mono (h : UpperSemicontinuousOn f s) (hst : t ⊆ s) : UpperSemicontinuousOn f t := fun x hx => (h x (hst hx)).mono hst theorem upperSemicontinuousOn_univ_iff : UpperSemicontinuousOn f univ ↔ UpperSemicontinuous f := by simp [UpperSemicontinuousOn, UpperSemicontinuous, upperSemicontinuousWithinAt_univ_iff] theorem UpperSemicontinuous.upperSemicontinuousAt (h : UpperSemicontinuous f) (x : α) : UpperSemicontinuousAt f x := h x theorem UpperSemicontinuous.upperSemicontinuousWithinAt (h : UpperSemicontinuous f) (s : Set α) (x : α) : UpperSemicontinuousWithinAt f s x := (h x).upperSemicontinuousWithinAt s theorem UpperSemicontinuous.upperSemicontinuousOn (h : UpperSemicontinuous f) (s : Set α) : UpperSemicontinuousOn f s := fun x _hx => h.upperSemicontinuousWithinAt s x /-! #### Constants -/ theorem upperSemicontinuousWithinAt_const : UpperSemicontinuousWithinAt (fun _x => z) s x := fun _y hy => Filter.eventually_of_forall fun _x => hy theorem upperSemicontinuousAt_const : UpperSemicontinuousAt (fun _x => z) x := fun _y hy => Filter.eventually_of_forall fun _x => hy theorem upperSemicontinuousOn_const : UpperSemicontinuousOn (fun _x => z) s := fun _x _hx => upperSemicontinuousWithinAt_const theorem upperSemicontinuous_const : UpperSemicontinuous fun _x : α => z := fun _x => upperSemicontinuousAt_const /-! #### Indicators -/ section variable [Zero β] theorem IsOpen.upperSemicontinuous_indicator (hs : IsOpen s) (hy : y ≤ 0) : UpperSemicontinuous (indicator s fun _x => y) := @IsOpen.lowerSemicontinuous_indicator α _ βᵒᵈ _ s y _ hs hy theorem IsOpen.upperSemicontinuousOn_indicator (hs : IsOpen s) (hy : y ≤ 0) : UpperSemicontinuousOn (indicator s fun _x => y) t := (hs.upperSemicontinuous_indicator hy).upperSemicontinuousOn t theorem IsOpen.upperSemicontinuousAt_indicator (hs : IsOpen s) (hy : y ≤ 0) : UpperSemicontinuousAt (indicator s fun _x => y) x := (hs.upperSemicontinuous_indicator hy).upperSemicontinuousAt x theorem IsOpen.upperSemicontinuousWithinAt_indicator (hs : IsOpen s) (hy : y ≤ 0) : UpperSemicontinuousWithinAt (indicator s fun _x => y) t x := (hs.upperSemicontinuous_indicator hy).upperSemicontinuousWithinAt t x theorem IsClosed.upperSemicontinuous_indicator (hs : IsClosed s) (hy : 0 ≤ y) : UpperSemicontinuous (indicator s fun _x => y) := @IsClosed.lowerSemicontinuous_indicator α _ βᵒᵈ _ s y _ hs hy theorem IsClosed.upperSemicontinuousOn_indicator (hs : IsClosed s) (hy : 0 ≤ y) : UpperSemicontinuousOn (indicator s fun _x => y) t := (hs.upperSemicontinuous_indicator hy).upperSemicontinuousOn t theorem IsClosed.upperSemicontinuousAt_indicator (hs : IsClosed s) (hy : 0 ≤ y) : UpperSemicontinuousAt (indicator s fun _x => y) x := (hs.upperSemicontinuous_indicator hy).upperSemicontinuousAt x theorem IsClosed.upperSemicontinuousWithinAt_indicator (hs : IsClosed s) (hy : 0 ≤ y) : UpperSemicontinuousWithinAt (indicator s fun _x => y) t x := (hs.upperSemicontinuous_indicator hy).upperSemicontinuousWithinAt t x end /-! #### Relationship with continuity -/ theorem upperSemicontinuous_iff_isOpen_preimage : UpperSemicontinuous f ↔ ∀ y, IsOpen (f ⁻¹' Iio y) := ⟨fun H y => isOpen_iff_mem_nhds.2 fun x hx => H x y hx, fun H _x y y_lt => IsOpen.mem_nhds (H y) y_lt⟩ theorem UpperSemicontinuous.isOpen_preimage (hf : UpperSemicontinuous f) (y : β) : IsOpen (f ⁻¹' Iio y) := upperSemicontinuous_iff_isOpen_preimage.1 hf y section variable {γ : Type*} [LinearOrder γ] theorem upperSemicontinuous_iff_isClosed_preimage {f : α → γ} : UpperSemicontinuous f ↔ ∀ y, IsClosed (f ⁻¹' Ici y) := by rw [upperSemicontinuous_iff_isOpen_preimage] simp only [← isOpen_compl_iff, ← preimage_compl, compl_Ici] theorem UpperSemicontinuous.isClosed_preimage {f : α → γ} (hf : UpperSemicontinuous f) (y : γ) : IsClosed (f ⁻¹' Ici y) := upperSemicontinuous_iff_isClosed_preimage.1 hf y variable [TopologicalSpace γ] [OrderTopology γ] theorem ContinuousWithinAt.upperSemicontinuousWithinAt {f : α → γ} (h : ContinuousWithinAt f s x) : UpperSemicontinuousWithinAt f s x := fun _y hy => h (Iio_mem_nhds hy) theorem ContinuousAt.upperSemicontinuousAt {f : α → γ} (h : ContinuousAt f x) : UpperSemicontinuousAt f x := fun _y hy => h (Iio_mem_nhds hy) theorem ContinuousOn.upperSemicontinuousOn {f : α → γ} (h : ContinuousOn f s) : UpperSemicontinuousOn f s := fun x hx => (h x hx).upperSemicontinuousWithinAt theorem Continuous.upperSemicontinuous {f : α → γ} (h : Continuous f) : UpperSemicontinuous f := fun _x => h.continuousAt.upperSemicontinuousAt end /-! #### Equivalent definitions -/ section variable {γ : Type*} [CompleteLinearOrder γ] [DenselyOrdered γ] theorem upperSemicontinuousWithinAt_iff_limsup_le {f : α → γ} : UpperSemicontinuousWithinAt f s x ↔ limsup f (𝓝[s] x) ≤ f x := lowerSemicontinuousWithinAt_iff_le_liminf (γ := γᵒᵈ) alias ⟨UpperSemicontinuousWithinAt.limsup_le, _⟩ := upperSemicontinuousWithinAt_iff_limsup_le theorem upperSemicontinuousAt_iff_limsup_le {f : α → γ} : UpperSemicontinuousAt f x ↔ limsup f (𝓝 x) ≤ f x := lowerSemicontinuousAt_iff_le_liminf (γ := γᵒᵈ) alias ⟨UpperSemicontinuousAt.limsup_le, _⟩ := upperSemicontinuousAt_iff_limsup_le theorem upperSemicontinuous_iff_limsup_le {f : α → γ} : UpperSemicontinuous f ↔ ∀ x, limsup f (𝓝 x) ≤ f x := lowerSemicontinuous_iff_le_liminf (γ := γᵒᵈ) alias ⟨UpperSemicontinuous.limsup_le, _⟩ := upperSemicontinuous_iff_limsup_le theorem upperSemicontinuousOn_iff_limsup_le {f : α → γ} : UpperSemicontinuousOn f s ↔ ∀ x ∈ s, limsup f (𝓝[s] x) ≤ f x := lowerSemicontinuousOn_iff_le_liminf (γ := γᵒᵈ) alias ⟨UpperSemicontinuousOn.limsup_le, _⟩ := upperSemicontinuousOn_iff_limsup_le variable [TopologicalSpace γ] [OrderTopology γ] theorem upperSemicontinuous_iff_IsClosed_hypograph {f : α → γ} : UpperSemicontinuous f ↔ IsClosed {p : α × γ | p.2 ≤ f p.1} := lowerSemicontinuous_iff_isClosed_epigraph (γ := γᵒᵈ) alias ⟨UpperSemicontinuous.IsClosed_hypograph, _⟩ := upperSemicontinuous_iff_IsClosed_hypograph end /-! ### Composition -/ section variable {γ : Type*} [LinearOrder γ] [TopologicalSpace γ] [OrderTopology γ] variable {δ : Type*} [LinearOrder δ] [TopologicalSpace δ] [OrderTopology δ] variable {ι : Type*} [TopologicalSpace ι] theorem ContinuousAt.comp_upperSemicontinuousWithinAt {g : γ → δ} {f : α → γ} (hg : ContinuousAt g (f x)) (hf : UpperSemicontinuousWithinAt f s x) (gmon : Monotone g) : UpperSemicontinuousWithinAt (g ∘ f) s x := @ContinuousAt.comp_lowerSemicontinuousWithinAt α _ x s γᵒᵈ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon.dual theorem ContinuousAt.comp_upperSemicontinuousAt {g : γ → δ} {f : α → γ} (hg : ContinuousAt g (f x)) (hf : UpperSemicontinuousAt f x) (gmon : Monotone g) : UpperSemicontinuousAt (g ∘ f) x := @ContinuousAt.comp_lowerSemicontinuousAt α _ x γᵒᵈ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon.dual theorem Continuous.comp_upperSemicontinuousOn {g : γ → δ} {f : α → γ} (hg : Continuous g) (hf : UpperSemicontinuousOn f s) (gmon : Monotone g) : UpperSemicontinuousOn (g ∘ f) s := fun x hx => hg.continuousAt.comp_upperSemicontinuousWithinAt (hf x hx) gmon theorem Continuous.comp_upperSemicontinuous {g : γ → δ} {f : α → γ} (hg : Continuous g) (hf : UpperSemicontinuous f) (gmon : Monotone g) : UpperSemicontinuous (g ∘ f) := fun x => hg.continuousAt.comp_upperSemicontinuousAt (hf x) gmon theorem ContinuousAt.comp_upperSemicontinuousWithinAt_antitone {g : γ → δ} {f : α → γ} (hg : ContinuousAt g (f x)) (hf : UpperSemicontinuousWithinAt f s x) (gmon : Antitone g) : LowerSemicontinuousWithinAt (g ∘ f) s x := @ContinuousAt.comp_upperSemicontinuousWithinAt α _ x s γ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon theorem ContinuousAt.comp_upperSemicontinuousAt_antitone {g : γ → δ} {f : α → γ} (hg : ContinuousAt g (f x)) (hf : UpperSemicontinuousAt f x) (gmon : Antitone g) : LowerSemicontinuousAt (g ∘ f) x := @ContinuousAt.comp_upperSemicontinuousAt α _ x γ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon theorem Continuous.comp_upperSemicontinuousOn_antitone {g : γ → δ} {f : α → γ} (hg : Continuous g) (hf : UpperSemicontinuousOn f s) (gmon : Antitone g) : LowerSemicontinuousOn (g ∘ f) s := fun x hx => hg.continuousAt.comp_upperSemicontinuousWithinAt_antitone (hf x hx) gmon theorem Continuous.comp_upperSemicontinuous_antitone {g : γ → δ} {f : α → γ} (hg : Continuous g) (hf : UpperSemicontinuous f) (gmon : Antitone g) : LowerSemicontinuous (g ∘ f) := fun x => hg.continuousAt.comp_upperSemicontinuousAt_antitone (hf x) gmon theorem UpperSemicontinuousAt.comp_continuousAt {f : α → β} {g : ι → α} {x : ι} (hf : UpperSemicontinuousAt f (g x)) (hg : ContinuousAt g x) : UpperSemicontinuousAt (fun x ↦ f (g x)) x := fun _ lt ↦ hg.eventually (hf _ lt) theorem UpperSemicontinuousAt.comp_continuousAt_of_eq {f : α → β} {g : ι → α} {y : α} {x : ι} (hf : UpperSemicontinuousAt f y) (hg : ContinuousAt g x) (hy : g x = y) : UpperSemicontinuousAt (fun x ↦ f (g x)) x := by rw [← hy] at hf exact comp_continuousAt hf hg theorem UpperSemicontinuous.comp_continuous {f : α → β} {g : ι → α} (hf : UpperSemicontinuous f) (hg : Continuous g) : UpperSemicontinuous fun x ↦ f (g x) := fun x ↦ (hf (g x)).comp_continuousAt hg.continuousAt end /-! #### Addition -/ section variable {ι : Type*} {γ : Type*} [LinearOrderedAddCommMonoid γ] [TopologicalSpace γ] [OrderTopology γ] /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `EReal`. The unprimed version of the lemma uses `[ContinuousAdd]`. -/ theorem UpperSemicontinuousWithinAt.add' {f g : α → γ} (hf : UpperSemicontinuousWithinAt f s x) (hg : UpperSemicontinuousWithinAt g s x) (hcont : ContinuousAt (fun p : γ × γ => p.1 + p.2) (f x, g x)) : UpperSemicontinuousWithinAt (fun z => f z + g z) s x := @LowerSemicontinuousWithinAt.add' α _ x s γᵒᵈ _ _ _ _ _ hf hg hcont /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `EReal`. The unprimed version of the lemma uses `[ContinuousAdd]`. -/ theorem UpperSemicontinuousAt.add' {f g : α → γ} (hf : UpperSemicontinuousAt f x) (hg : UpperSemicontinuousAt g x) (hcont : ContinuousAt (fun p : γ × γ => p.1 + p.2) (f x, g x)) : UpperSemicontinuousAt (fun z => f z + g z) x := by simp_rw [← upperSemicontinuousWithinAt_univ_iff] at * exact hf.add' hg hcont /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `EReal`. The unprimed version of the lemma uses `[ContinuousAdd]`. -/ theorem UpperSemicontinuousOn.add' {f g : α → γ} (hf : UpperSemicontinuousOn f s) (hg : UpperSemicontinuousOn g s) (hcont : ∀ x ∈ s, ContinuousAt (fun p : γ × γ => p.1 + p.2) (f x, g x)) : UpperSemicontinuousOn (fun z => f z + g z) s := fun x hx => (hf x hx).add' (hg x hx) (hcont x hx) /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `EReal`. The unprimed version of the lemma uses `[ContinuousAdd]`. -/ theorem UpperSemicontinuous.add' {f g : α → γ} (hf : UpperSemicontinuous f) (hg : UpperSemicontinuous g) (hcont : ∀ x, ContinuousAt (fun p : γ × γ => p.1 + p.2) (f x, g x)) : UpperSemicontinuous fun z => f z + g z := fun x => (hf x).add' (hg x) (hcont x) variable [ContinuousAdd γ] /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with `[ContinuousAdd]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `EReal`. -/ theorem UpperSemicontinuousWithinAt.add {f g : α → γ} (hf : UpperSemicontinuousWithinAt f s x) (hg : UpperSemicontinuousWithinAt g s x) : UpperSemicontinuousWithinAt (fun z => f z + g z) s x := hf.add' hg continuous_add.continuousAt /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with `[ContinuousAdd]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `EReal`. -/ theorem UpperSemicontinuousAt.add {f g : α → γ} (hf : UpperSemicontinuousAt f x) (hg : UpperSemicontinuousAt g x) : UpperSemicontinuousAt (fun z => f z + g z) x := hf.add' hg continuous_add.continuousAt /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with `[ContinuousAdd]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `EReal`. -/ theorem UpperSemicontinuousOn.add {f g : α → γ} (hf : UpperSemicontinuousOn f s) (hg : UpperSemicontinuousOn g s) : UpperSemicontinuousOn (fun z => f z + g z) s := hf.add' hg fun _x _hx => continuous_add.continuousAt /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with `[ContinuousAdd]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `EReal`. -/ theorem UpperSemicontinuous.add {f g : α → γ} (hf : UpperSemicontinuous f) (hg : UpperSemicontinuous g) : UpperSemicontinuous fun z => f z + g z := hf.add' hg fun _x => continuous_add.continuousAt theorem upperSemicontinuousWithinAt_sum {f : ι → α → γ} {a : Finset ι} (ha : ∀ i ∈ a, UpperSemicontinuousWithinAt (f i) s x) : UpperSemicontinuousWithinAt (fun z => ∑ i ∈ a, f i z) s x := @lowerSemicontinuousWithinAt_sum α _ x s ι γᵒᵈ _ _ _ _ f a ha theorem upperSemicontinuousAt_sum {f : ι → α → γ} {a : Finset ι} (ha : ∀ i ∈ a, UpperSemicontinuousAt (f i) x) : UpperSemicontinuousAt (fun z => ∑ i ∈ a, f i z) x := by simp_rw [← upperSemicontinuousWithinAt_univ_iff] at * exact upperSemicontinuousWithinAt_sum ha theorem upperSemicontinuousOn_sum {f : ι → α → γ} {a : Finset ι} (ha : ∀ i ∈ a, UpperSemicontinuousOn (f i) s) : UpperSemicontinuousOn (fun z => ∑ i ∈ a, f i z) s := fun x hx => upperSemicontinuousWithinAt_sum fun i hi => ha i hi x hx theorem upperSemicontinuous_sum {f : ι → α → γ} {a : Finset ι} (ha : ∀ i ∈ a, UpperSemicontinuous (f i)) : UpperSemicontinuous fun z => ∑ i ∈ a, f i z := fun x => upperSemicontinuousAt_sum fun i hi => ha i hi x end /-! #### Infimum -/ section variable {ι : Sort*} {δ δ' : Type*} [CompleteLinearOrder δ] [ConditionallyCompleteLinearOrder δ'] theorem upperSemicontinuousWithinAt_ciInf {f : ι → α → δ'} (bdd : ∀ᶠ y in 𝓝[s] x, BddBelow (range fun i => f i y)) (h : ∀ i, UpperSemicontinuousWithinAt (f i) s x) : UpperSemicontinuousWithinAt (fun x' => ⨅ i, f i x') s x := @lowerSemicontinuousWithinAt_ciSup α _ x s ι δ'ᵒᵈ _ f bdd h theorem upperSemicontinuousWithinAt_iInf {f : ι → α → δ} (h : ∀ i, UpperSemicontinuousWithinAt (f i) s x) : UpperSemicontinuousWithinAt (fun x' => ⨅ i, f i x') s x := @lowerSemicontinuousWithinAt_iSup α _ x s ι δᵒᵈ _ f h theorem upperSemicontinuousWithinAt_biInf {p : ι → Prop} {f : ∀ i, p i → α → δ} (h : ∀ i hi, UpperSemicontinuousWithinAt (f i hi) s x) : UpperSemicontinuousWithinAt (fun x' => ⨅ (i) (hi), f i hi x') s x := upperSemicontinuousWithinAt_iInf fun i => upperSemicontinuousWithinAt_iInf fun hi => h i hi theorem upperSemicontinuousAt_ciInf {f : ι → α → δ'} (bdd : ∀ᶠ y in 𝓝 x, BddBelow (range fun i => f i y)) (h : ∀ i, UpperSemicontinuousAt (f i) x) : UpperSemicontinuousAt (fun x' => ⨅ i, f i x') x := @lowerSemicontinuousAt_ciSup α _ x ι δ'ᵒᵈ _ f bdd h theorem upperSemicontinuousAt_iInf {f : ι → α → δ} (h : ∀ i, UpperSemicontinuousAt (f i) x) : UpperSemicontinuousAt (fun x' => ⨅ i, f i x') x := @lowerSemicontinuousAt_iSup α _ x ι δᵒᵈ _ f h theorem upperSemicontinuousAt_biInf {p : ι → Prop} {f : ∀ i, p i → α → δ} (h : ∀ i hi, UpperSemicontinuousAt (f i hi) x) : UpperSemicontinuousAt (fun x' => ⨅ (i) (hi), f i hi x') x := upperSemicontinuousAt_iInf fun i => upperSemicontinuousAt_iInf fun hi => h i hi theorem upperSemicontinuousOn_ciInf {f : ι → α → δ'} (bdd : ∀ x ∈ s, BddBelow (range fun i => f i x)) (h : ∀ i, UpperSemicontinuousOn (f i) s) : UpperSemicontinuousOn (fun x' => ⨅ i, f i x') s := fun x hx => upperSemicontinuousWithinAt_ciInf (eventually_nhdsWithin_of_forall bdd) fun i => h i x hx theorem upperSemicontinuousOn_iInf {f : ι → α → δ} (h : ∀ i, UpperSemicontinuousOn (f i) s) : UpperSemicontinuousOn (fun x' => ⨅ i, f i x') s := fun x hx => upperSemicontinuousWithinAt_iInf fun i => h i x hx theorem upperSemicontinuousOn_biInf {p : ι → Prop} {f : ∀ i, p i → α → δ} (h : ∀ i hi, UpperSemicontinuousOn (f i hi) s) : UpperSemicontinuousOn (fun x' => ⨅ (i) (hi), f i hi x') s := upperSemicontinuousOn_iInf fun i => upperSemicontinuousOn_iInf fun hi => h i hi theorem upperSemicontinuous_ciInf {f : ι → α → δ'} (bdd : ∀ x, BddBelow (range fun i => f i x)) (h : ∀ i, UpperSemicontinuous (f i)) : UpperSemicontinuous fun x' => ⨅ i, f i x' := fun x => upperSemicontinuousAt_ciInf (eventually_of_forall bdd) fun i => h i x theorem upperSemicontinuous_iInf {f : ι → α → δ} (h : ∀ i, UpperSemicontinuous (f i)) : UpperSemicontinuous fun x' => ⨅ i, f i x' := fun x => upperSemicontinuousAt_iInf fun i => h i x theorem upperSemicontinuous_biInf {p : ι → Prop} {f : ∀ i, p i → α → δ} (h : ∀ i hi, UpperSemicontinuous (f i hi)) : UpperSemicontinuous fun x' => ⨅ (i) (hi), f i hi x' := upperSemicontinuous_iInf fun i => upperSemicontinuous_iInf fun hi => h i hi end section variable {γ : Type*} [LinearOrder γ] [TopologicalSpace γ] [OrderTopology γ] theorem continuousWithinAt_iff_lower_upperSemicontinuousWithinAt {f : α → γ} : ContinuousWithinAt f s x ↔ LowerSemicontinuousWithinAt f s x ∧ UpperSemicontinuousWithinAt f s x := by refine ⟨fun h => ⟨h.lowerSemicontinuousWithinAt, h.upperSemicontinuousWithinAt⟩, ?_⟩ rintro ⟨h₁, h₂⟩ intro v hv simp only [Filter.mem_map] by_cases Hl : ∃ l, l < f x · rcases exists_Ioc_subset_of_mem_nhds hv Hl with ⟨l, lfx, hl⟩ by_cases Hu : ∃ u, f x < u · rcases exists_Ico_subset_of_mem_nhds hv Hu with ⟨u, fxu, hu⟩ filter_upwards [h₁ l lfx, h₂ u fxu] with a lfa fau cases' le_or_gt (f a) (f x) with h h · exact hl ⟨lfa, h⟩ · exact hu ⟨le_of_lt h, fau⟩ · simp only [not_exists, not_lt] at Hu filter_upwards [h₁ l lfx] with a lfa using hl ⟨lfa, Hu (f a)⟩ · simp only [not_exists, not_lt] at Hl by_cases Hu : ∃ u, f x < u · rcases exists_Ico_subset_of_mem_nhds hv Hu with ⟨u, fxu, hu⟩ filter_upwards [h₂ u fxu] with a lfa apply hu exact ⟨Hl (f a), lfa⟩ · simp only [not_exists, not_lt] at Hu apply Filter.eventually_of_forall intro a have : f a = f x := le_antisymm (Hu _) (Hl _) rw [this] exact mem_of_mem_nhds hv theorem continuousAt_iff_lower_upperSemicontinuousAt {f : α → γ} : ContinuousAt f x ↔ LowerSemicontinuousAt f x ∧ UpperSemicontinuousAt f x := by simp_rw [← continuousWithinAt_univ, ← lowerSemicontinuousWithinAt_univ_iff, ← upperSemicontinuousWithinAt_univ_iff, continuousWithinAt_iff_lower_upperSemicontinuousWithinAt] theorem continuousOn_iff_lower_upperSemicontinuousOn {f : α → γ} : ContinuousOn f s ↔ LowerSemicontinuousOn f s ∧ UpperSemicontinuousOn f s := by simp only [ContinuousOn, continuousWithinAt_iff_lower_upperSemicontinuousWithinAt] exact ⟨fun H => ⟨fun x hx => (H x hx).1, fun x hx => (H x hx).2⟩, fun H x hx => ⟨H.1 x hx, H.2 x hx⟩⟩ theorem continuous_iff_lower_upperSemicontinuous {f : α → γ} : Continuous f ↔ LowerSemicontinuous f ∧ UpperSemicontinuous f := by simp_rw [continuous_iff_continuousOn_univ, continuousOn_iff_lower_upperSemicontinuousOn, lowerSemicontinuousOn_univ_iff, upperSemicontinuousOn_univ_iff] end
Topology\SeparatedMap.lean
/- Copyright (c) 2023 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import Mathlib.Topology.Connected.Basic import Mathlib.Topology.Separation /-! # Separated maps and locally injective maps out of a topological space. This module introduces a pair of dual notions `IsSeparatedMap` and `IsLocallyInjective`. A function from a topological space `X` to a type `Y` is a separated map if any two distinct points in `X` with the same image in `Y` can be separated by open neighborhoods. A constant function is a separated map if and only if `X` is a `T2Space`. A function from a topological space `X` is locally injective if every point of `X` has a neighborhood on which `f` is injective. A constant function is locally injective if and only if `X` is discrete. Given `f : X → Y` we can form the pullback $X \times_Y X$; the diagonal map $\Delta: X \to X \times_Y X$ is always an embedding. It is a closed embedding iff `f` is a separated map, iff the equal locus of any two continuous maps coequalized by `f` is closed. It is an open embedding iff `f` is locally injective, iff any such equal locus is open. Therefore, if `f` is a locally injective separated map, the equal locus of two continuous maps coequalized by `f` is clopen, so if the two maps agree on a point, then they agree on the whole connected component. The analogue of separated maps and locally injective maps in algebraic geometry are separated morphisms and unramified morphisms, respectively. ## Reference https://stacks.math.columbia.edu/tag/0CY0 -/ open scoped Topology variable {X Y A} [TopologicalSpace X] [TopologicalSpace A] theorem embedding_toPullbackDiag (f : X → Y) : Embedding (toPullbackDiag f) := Embedding.mk' _ (injective_toPullbackDiag f) fun x ↦ by rw [toPullbackDiag, nhds_induced, Filter.comap_comap, nhds_prod_eq, Filter.comap_prod] erw [Filter.comap_id, inf_idem] lemma Continuous.mapPullback {X₁ X₂ Y₁ Y₂ Z₁ Z₂} [TopologicalSpace X₁] [TopologicalSpace X₂] [TopologicalSpace Z₁] [TopologicalSpace Z₂] {f₁ : X₁ → Y₁} {g₁ : Z₁ → Y₁} {f₂ : X₂ → Y₂} {g₂ : Z₂ → Y₂} {mapX : X₁ → X₂} (contX : Continuous mapX) {mapY : Y₁ → Y₂} {mapZ : Z₁ → Z₂} (contZ : Continuous mapZ) {commX : f₂ ∘ mapX = mapY ∘ f₁} {commZ : g₂ ∘ mapZ = mapY ∘ g₁} : Continuous (Function.mapPullback mapX mapY mapZ commX commZ) := by refine continuous_induced_rng.mpr (continuous_prod_mk.mpr ⟨?_, ?_⟩) <;> apply_rules [continuous_fst, continuous_snd, continuous_subtype_val, Continuous.comp] /-- A function from a topological space `X` to a type `Y` is a separated map if any two distinct points in `X` with the same image in `Y` can be separated by open neighborhoods. -/ def IsSeparatedMap (f : X → Y) : Prop := ∀ x₁ x₂, f x₁ = f x₂ → x₁ ≠ x₂ → ∃ s₁ s₂, IsOpen s₁ ∧ IsOpen s₂ ∧ x₁ ∈ s₁ ∧ x₂ ∈ s₂ ∧ Disjoint s₁ s₂ lemma t2space_iff_isSeparatedMap (y : Y) : T2Space X ↔ IsSeparatedMap fun _ : X ↦ y := ⟨fun ⟨t2⟩ _ _ _ hne ↦ t2 hne, fun sep ↦ ⟨fun x₁ x₂ hne ↦ sep x₁ x₂ rfl hne⟩⟩ lemma T2Space.isSeparatedMap [T2Space X] (f : X → Y) : IsSeparatedMap f := fun _ _ _ ↦ t2_separation lemma Function.Injective.isSeparatedMap {f : X → Y} (inj : f.Injective) : IsSeparatedMap f := fun _ _ he hne ↦ (hne (inj he)).elim lemma isSeparatedMap_iff_disjoint_nhds {f : X → Y} : IsSeparatedMap f ↔ ∀ x₁ x₂, f x₁ = f x₂ → x₁ ≠ x₂ → Disjoint (𝓝 x₁) (𝓝 x₂) := forall₃_congr fun x x' _ ↦ by simp only [(nhds_basis_opens x).disjoint_iff (nhds_basis_opens x'), exists_prop, ← exists_and_left, and_assoc, and_comm, and_left_comm] lemma isSeparatedMap_iff_nhds {f : X → Y} : IsSeparatedMap f ↔ ∀ x₁ x₂, f x₁ = f x₂ → x₁ ≠ x₂ → ∃ s₁ ∈ 𝓝 x₁, ∃ s₂ ∈ 𝓝 x₂, Disjoint s₁ s₂ := by simp_rw [isSeparatedMap_iff_disjoint_nhds, Filter.disjoint_iff] open Set Filter in theorem isSeparatedMap_iff_isClosed_diagonal {f : X → Y} : IsSeparatedMap f ↔ IsClosed f.pullbackDiagonal := by simp_rw [isSeparatedMap_iff_nhds, ← isOpen_compl_iff, isOpen_iff_mem_nhds, Subtype.forall, Prod.forall, nhds_induced, nhds_prod_eq] refine forall₄_congr fun x₁ x₂ _ _ ↦ ⟨fun h ↦ ?_, fun ⟨t, ht, t_sub⟩ ↦ ?_⟩ · simp_rw [← Filter.disjoint_iff, ← compl_diagonal_mem_prod] at h exact ⟨_, h, subset_rfl⟩ · obtain ⟨s₁, h₁, s₂, h₂, s_sub⟩ := mem_prod_iff.mp ht exact ⟨s₁, h₁, s₂, h₂, disjoint_left.2 fun x h₁ h₂ ↦ @t_sub ⟨(x, x), rfl⟩ (s_sub ⟨h₁, h₂⟩) rfl⟩ theorem isSeparatedMap_iff_closedEmbedding {f : X → Y} : IsSeparatedMap f ↔ ClosedEmbedding (toPullbackDiag f) := by rw [isSeparatedMap_iff_isClosed_diagonal, ← range_toPullbackDiag] exact ⟨fun h ↦ ⟨embedding_toPullbackDiag f, h⟩, fun h ↦ h.isClosed_range⟩ theorem isSeparatedMap_iff_isClosedMap {f : X → Y} : IsSeparatedMap f ↔ IsClosedMap (toPullbackDiag f) := isSeparatedMap_iff_closedEmbedding.trans ⟨ClosedEmbedding.isClosedMap, closedEmbedding_of_continuous_injective_closed (embedding_toPullbackDiag f).continuous (injective_toPullbackDiag f)⟩ open Function.Pullback in theorem IsSeparatedMap.pullback {f : X → Y} (sep : IsSeparatedMap f) (g : A → Y) : IsSeparatedMap (@snd X Y A f g) := by rw [isSeparatedMap_iff_isClosed_diagonal] at sep ⊢ rw [← preimage_map_fst_pullbackDiagonal] refine sep.preimage (Continuous.mapPullback ?_ ?_) <;> apply_rules [continuous_fst, continuous_subtype_val, Continuous.comp] theorem IsSeparatedMap.comp_left {f : X → Y} (sep : IsSeparatedMap f) {g : Y → A} (inj : g.Injective) : IsSeparatedMap (g ∘ f) := fun x₁ x₂ he ↦ sep x₁ x₂ (inj he) theorem IsSeparatedMap.comp_right {f : X → Y} (sep : IsSeparatedMap f) {g : A → X} (cont : Continuous g) (inj : g.Injective) : IsSeparatedMap (f ∘ g) := by rw [isSeparatedMap_iff_isClosed_diagonal] at sep ⊢ rw [← inj.preimage_pullbackDiagonal] exact sep.preimage (cont.mapPullback cont) /-- A function from a topological space `X` is locally injective if every point of `X` has a neighborhood on which `f` is injective. -/ def IsLocallyInjective (f : X → Y) : Prop := ∀ x : X, ∃ U, IsOpen U ∧ x ∈ U ∧ U.InjOn f lemma Function.Injective.IsLocallyInjective {f : X → Y} (inj : f.Injective) : IsLocallyInjective f := fun _ ↦ ⟨_, isOpen_univ, trivial, fun _ _ _ _ ↦ @inj _ _⟩ lemma isLocallyInjective_iff_nhds {f : X → Y} : IsLocallyInjective f ↔ ∀ x : X, ∃ U ∈ 𝓝 x, U.InjOn f := by constructor <;> intro h x · obtain ⟨U, ho, hm, hi⟩ := h x; exact ⟨U, ho.mem_nhds hm, hi⟩ · obtain ⟨U, hn, hi⟩ := h x exact ⟨interior U, isOpen_interior, mem_interior_iff_mem_nhds.mpr hn, hi.mono interior_subset⟩ theorem isLocallyInjective_iff_isOpen_diagonal {f : X → Y} : IsLocallyInjective f ↔ IsOpen f.pullbackDiagonal := by simp_rw [isLocallyInjective_iff_nhds, isOpen_iff_mem_nhds, Subtype.forall, Prod.forall, nhds_induced, nhds_prod_eq, Filter.mem_comap] refine ⟨?_, fun h x ↦ ?_⟩ · rintro h x x' hx (rfl : x = x') obtain ⟨U, hn, hi⟩ := h x exact ⟨_, Filter.prod_mem_prod hn hn, fun {p} hp ↦ hi hp.1 hp.2 p.2⟩ · obtain ⟨t, ht, t_sub⟩ := h x x rfl rfl obtain ⟨t₁, h₁, t₂, h₂, prod_sub⟩ := Filter.mem_prod_iff.mp ht exact ⟨t₁ ∩ t₂, Filter.inter_mem h₁ h₂, fun x₁ h₁ x₂ h₂ he ↦ @t_sub ⟨(x₁, x₂), he⟩ (prod_sub ⟨h₁.1, h₂.2⟩)⟩ theorem IsLocallyInjective_iff_openEmbedding {f : X → Y} : IsLocallyInjective f ↔ OpenEmbedding (toPullbackDiag f) := by rw [isLocallyInjective_iff_isOpen_diagonal, ← range_toPullbackDiag] exact ⟨fun h ↦ ⟨embedding_toPullbackDiag f, h⟩, fun h ↦ h.isOpen_range⟩ theorem isLocallyInjective_iff_isOpenMap {f : X → Y} : IsLocallyInjective f ↔ IsOpenMap (toPullbackDiag f) := IsLocallyInjective_iff_openEmbedding.trans ⟨OpenEmbedding.isOpenMap, openEmbedding_of_continuous_injective_open (embedding_toPullbackDiag f).continuous (injective_toPullbackDiag f)⟩ theorem discreteTopology_iff_locallyInjective (y : Y) : DiscreteTopology X ↔ IsLocallyInjective fun _ : X ↦ y := by rw [discreteTopology_iff_singleton_mem_nhds, isLocallyInjective_iff_nhds] refine forall_congr' fun x ↦ ⟨fun h ↦ ⟨{x}, h, Set.injOn_singleton _ _⟩, fun ⟨U, hU, inj⟩ ↦ ?_⟩ convert hU; ext x'; refine ⟨?_, fun h ↦ inj h (mem_of_mem_nhds hU) rfl⟩ rintro rfl; exact mem_of_mem_nhds hU theorem IsLocallyInjective.comp_left {f : X → Y} (hf : IsLocallyInjective f) {g : Y → A} (hg : g.Injective) : IsLocallyInjective (g ∘ f) := fun x ↦ let ⟨U, hU, hx, inj⟩ := hf x; ⟨U, hU, hx, hg.comp_injOn inj⟩ theorem IsLocallyInjective.comp_right {f : X → Y} (hf : IsLocallyInjective f) {g : A → X} (cont : Continuous g) (hg : g.Injective) : IsLocallyInjective (f ∘ g) := by rw [isLocallyInjective_iff_isOpen_diagonal] at hf ⊢ rw [← hg.preimage_pullbackDiagonal] apply hf.preimage (cont.mapPullback cont) section eqLocus variable {f : X → Y} (sep : IsSeparatedMap f) (inj : IsLocallyInjective f) {g₁ g₂ : A → X} (h₁ : Continuous g₁) (h₂ : Continuous g₂) theorem IsSeparatedMap.isClosed_eqLocus (he : f ∘ g₁ = f ∘ g₂) : IsClosed {a | g₁ a = g₂ a} := let g : A → f.Pullback f := fun a ↦ ⟨⟨g₁ a, g₂ a⟩, congr_fun he a⟩ (isSeparatedMap_iff_isClosed_diagonal.mp sep).preimage (by fun_prop : Continuous g) theorem IsLocallyInjective.isOpen_eqLocus (he : f ∘ g₁ = f ∘ g₂) : IsOpen {a | g₁ a = g₂ a} := let g : A → f.Pullback f := fun a ↦ ⟨⟨g₁ a, g₂ a⟩, congr_fun he a⟩ (isLocallyInjective_iff_isOpen_diagonal.mp inj).preimage (by fun_prop : Continuous g) end eqLocus variable {E A : Type*} [TopologicalSpace E] [TopologicalSpace A] {p : E → X} namespace IsSeparatedMap variable (sep : IsSeparatedMap p) (inj : IsLocallyInjective p) {s : Set A} (hs : IsPreconnected s) {g g₁ g₂ : A → E} /-- If `p` is a locally injective separated map, and `A` is a connected space, then two lifts `g₁, g₂ : A → E` of a map `f : A → X` are equal if they agree at one point. -/ theorem eq_of_comp_eq [PreconnectedSpace A] (h₁ : Continuous g₁) (h₂ : Continuous g₂) (he : p ∘ g₁ = p ∘ g₂) (a : A) (ha : g₁ a = g₂ a) : g₁ = g₂ := funext fun a' ↦ by apply (IsClopen.eq_univ ⟨sep.isClosed_eqLocus h₁ h₂ he, inj.isOpen_eqLocus h₁ h₂ he⟩ ⟨a, ha⟩).symm ▸ Set.mem_univ a' theorem eqOn_of_comp_eqOn (h₁ : ContinuousOn g₁ s) (h₂ : ContinuousOn g₂ s) (he : s.EqOn (p ∘ g₁) (p ∘ g₂)) {a : A} (has : a ∈ s) (ha : g₁ a = g₂ a) : s.EqOn g₁ g₂ := by rw [← Set.restrict_eq_restrict_iff] at he ⊢ rw [continuousOn_iff_continuous_restrict] at h₁ h₂ rw [isPreconnected_iff_preconnectedSpace] at hs exact sep.eq_of_comp_eq inj h₁ h₂ he ⟨a, has⟩ ha theorem const_of_comp [PreconnectedSpace A] (cont : Continuous g) (he : ∀ a a', p (g a) = p (g a')) (a a') : g a = g a' := congr_fun (sep.eq_of_comp_eq inj cont continuous_const (funext fun a ↦ he a a') a' rfl) a theorem constOn_of_comp (cont : ContinuousOn g s) (he : ∀ a ∈ s, ∀ a' ∈ s, p (g a) = p (g a')) {a a'} (ha : a ∈ s) (ha' : a' ∈ s) : g a = g a' := sep.eqOn_of_comp_eqOn inj hs cont continuous_const.continuousOn (fun a ha ↦ he a ha a' ha') ha' rfl ha end IsSeparatedMap
Topology\Separation.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Topology.Compactness.Lindelof import Mathlib.Topology.Compactness.SigmaCompact import Mathlib.Topology.Connected.TotallyDisconnected import Mathlib.Topology.Inseparable import Mathlib.Topology.GDelta /-! # Separation properties of topological spaces. This file defines the predicate `SeparatedNhds`, and common separation axioms (under the Kolmogorov classification). ## Main definitions * `SeparatedNhds`: Two `Set`s are separated by neighbourhoods if they are contained in disjoint open sets. * `HasSeparatingCover`: A set has a countable cover that can be used with `hasSeparatingCovers_iff_separatedNhds` to witness when two `Set`s have `SeparatedNhds`. * `T0Space`: A T₀/Kolmogorov space is a space where, for every two points `x ≠ y`, there is an open set that contains one, but not the other. * `R0Space`: An R₀ space (sometimes called a *symmetric space*) is a topological space such that the `Specializes` relation is symmetric. * `T1Space`: A T₁/Fréchet space is a space where every singleton set is closed. This is equivalent to, for every pair `x ≠ y`, there existing an open set containing `x` but not `y` (`t1Space_iff_exists_open` shows that these conditions are equivalent.) T₁ implies T₀ and R₀. * `R1Space`: An R₁/preregular space is a space where any two topologically distinguishable points have disjoint neighbourhoods. R₁ implies R₀. * `T2Space`: A T₂/Hausdorff space is a space where, for every two points `x ≠ y`, there is two disjoint open sets, one containing `x`, and the other `y`. T₂ implies T₁ and R₁. * `T25Space`: A T₂.₅/Urysohn space is a space where, for every two points `x ≠ y`, there is two open sets, one containing `x`, and the other `y`, whose closures are disjoint. T₂.₅ implies T₂. * `RegularSpace`: A regular space is one where, given any closed `C` and `x ∉ C`, there are disjoint open sets containing `x` and `C` respectively. Such a space is not necessarily Hausdorff. * `T3Space`: A T₃ space is a regular T₀ space. T₃ implies T₂.₅. * `NormalSpace`: A normal space, is one where given two disjoint closed sets, we can find two open sets that separate them. Such a space is not necessarily Hausdorff, even if it is T₀. * `T4Space`: A T₄ space is a normal T₁ space. T₄ implies T₃. * `CompletelyNormalSpace`: A completely normal space is one in which for any two sets `s`, `t` such that if both `closure s` is disjoint with `t`, and `s` is disjoint with `closure t`, then there exist disjoint neighbourhoods of `s` and `t`. `Embedding.completelyNormalSpace` allows us to conclude that this is equivalent to all subspaces being normal. Such a space is not necessarily Hausdorff or regular, even if it is T₀. * `T5Space`: A T₅ space is a completely normal T₁ space. T₅ implies T₄. * `PerfectlyNormalSpace`: A perfectly normal space is a normal space such that closed sets are Gδ. * `T6Space`: A T₆ space is a Perfectly normal T₁ space. T₆ implies T₅. Note that `mathlib` adopts the modern convention that `m ≤ n` if and only if `T_m → T_n`, but occasionally the literature swaps definitions for e.g. T₃ and regular. ### TODO * Add perfectly normal and T6 spaces. * Use `hasSeparatingCovers_iff_separatedNhds` to prove that perfectly normal spaces are completely normal. ## Main results ### T₀ spaces * `IsClosed.exists_closed_singleton`: Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. * `exists_isOpen_singleton_of_isOpen_finite`: Given an open finite set `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. ### T₁ spaces * `isClosedMap_const`: The constant map is a closed map. * `Finite.instDiscreteTopology`: A finite T₁ space must have the discrete topology. ### T₂ spaces * `t2_iff_nhds`: A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. * `t2_iff_isClosed_diagonal`: A space is T₂ iff the `diagonal` of `X` (that is, the set of all points of the form `(a, a) : X × X`) is closed under the product topology. * `separatedNhds_of_finset_finset`: Any two disjoint finsets are `SeparatedNhds`. * Most topological constructions preserve Hausdorffness; these results are part of the typeclass inference system (e.g. `Embedding.t2Space`) * `Set.EqOn.closure`: If two functions are equal on some set `s`, they are equal on its closure. * `IsCompact.isClosed`: All compact sets are closed. * `WeaklyLocallyCompactSpace.locallyCompactSpace`: If a topological space is both weakly locally compact (i.e., each point has a compact neighbourhood) and is T₂, then it is locally compact. * `totallySeparatedSpace_of_t1_of_basis_clopen`: If `X` has a clopen basis, then it is a `TotallySeparatedSpace`. * `loc_compact_t2_tot_disc_iff_tot_sep`: A locally compact T₂ space is totally disconnected iff it is totally separated. * `t2Quotient`: the largest T2 quotient of a given topological space. If the space is also compact: * `normalOfCompactT2`: A compact T₂ space is a `NormalSpace`. * `connectedComponent_eq_iInter_isClopen`: The connected component of a point is the intersection of all its clopen neighbourhoods. * `compact_t2_tot_disc_iff_tot_sep`: Being a `TotallyDisconnectedSpace` is equivalent to being a `TotallySeparatedSpace`. * `ConnectedComponents.t2`: `ConnectedComponents X` is T₂ for `X` T₂ and compact. ### Regular spaces If the space is also Lindelöf: * `NormalSpace.of_regularSpace_lindelofSpace`: every regular Lindelöf space is normal. ### T₃ spaces * `disjoint_nested_nhds`: Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. ## References * <https://en.wikipedia.org/wiki/Separation_axiom> * <https://en.wikipedia.org/wiki/Normal_space> * [Willard's *General Topology*][zbMATH02107988] -/ open Function Set Filter Topology TopologicalSpace universe u v variable {X : Type*} {Y : Type*} [TopologicalSpace X] section Separation /-- `SeparatedNhds` is a predicate on pairs of sub`Set`s of a topological space. It holds if the two sub`Set`s are contained in disjoint open sets. -/ def SeparatedNhds : Set X → Set X → Prop := fun s t : Set X => ∃ U V : Set X, IsOpen U ∧ IsOpen V ∧ s ⊆ U ∧ t ⊆ V ∧ Disjoint U V theorem separatedNhds_iff_disjoint {s t : Set X} : SeparatedNhds s t ↔ Disjoint (𝓝ˢ s) (𝓝ˢ t) := by simp only [(hasBasis_nhdsSet s).disjoint_iff (hasBasis_nhdsSet t), SeparatedNhds, exists_prop, ← exists_and_left, and_assoc, and_comm, and_left_comm] alias ⟨SeparatedNhds.disjoint_nhdsSet, _⟩ := separatedNhds_iff_disjoint /-- `HasSeparatingCover`s can be useful witnesses for `SeparatedNhds`. -/ def HasSeparatingCover : Set X → Set X → Prop := fun s t ↦ ∃ u : ℕ → Set X, s ⊆ ⋃ n, u n ∧ ∀ n, IsOpen (u n) ∧ Disjoint (closure (u n)) t /-- Used to prove that a regular topological space with Lindelöf topology is a normal space, and (todo) a perfectly normal space is a completely normal space. -/ theorem hasSeparatingCovers_iff_separatedNhds {s t : Set X} : HasSeparatingCover s t ∧ HasSeparatingCover t s ↔ SeparatedNhds s t := by constructor · rintro ⟨⟨u, u_cov, u_props⟩, ⟨v, v_cov, v_props⟩⟩ have open_lemma : ∀ (u₀ a : ℕ → Set X), (∀ n, IsOpen (u₀ n)) → IsOpen (⋃ n, u₀ n \ closure (a n)) := fun _ _ u₀i_open ↦ isOpen_iUnion fun i ↦ (u₀i_open i).sdiff isClosed_closure have cover_lemma : ∀ (h₀ : Set X) (u₀ v₀ : ℕ → Set X), (h₀ ⊆ ⋃ n, u₀ n) → (∀ n, Disjoint (closure (v₀ n)) h₀) → (h₀ ⊆ ⋃ n, u₀ n \ closure (⋃ m ≤ n, v₀ m)) := fun h₀ u₀ v₀ h₀_cov dis x xinh ↦ by rcases h₀_cov xinh with ⟨un , ⟨n, rfl⟩ , xinun⟩ simp only [mem_iUnion] refine ⟨n, xinun, ?_⟩ simp_all only [closure_iUnion₂_le_nat, disjoint_right, mem_setOf_eq, mem_iUnion, exists_false, exists_const, not_false_eq_true] refine ⟨⋃ n : ℕ, u n \ (closure (⋃ m ≤ n, v m)), ⋃ n : ℕ, v n \ (closure (⋃ m ≤ n, u m)), open_lemma u (fun n ↦ ⋃ m ≤ n, v m) (fun n ↦ (u_props n).1), open_lemma v (fun n ↦ ⋃ m ≤ n, u m) (fun n ↦ (v_props n).1), cover_lemma s u v u_cov (fun n ↦ (v_props n).2), cover_lemma t v u v_cov (fun n ↦ (u_props n).2), ?_⟩ rw [Set.disjoint_left] rintro x ⟨un, ⟨n, rfl⟩, xinun⟩ suffices ∀ (m : ℕ), x ∈ v m → x ∈ closure (⋃ m' ∈ {m' | m' ≤ m}, u m') by simpa intro m xinvm have n_le_m : n ≤ m := by by_contra m_gt_n exact xinun.2 (subset_closure (mem_biUnion (le_of_lt (not_le.mp m_gt_n)) xinvm)) exact subset_closure (mem_biUnion n_le_m xinun.1) · rintro ⟨U, V, U_open, V_open, h_sub_U, k_sub_V, UV_dis⟩ exact ⟨⟨fun _ ↦ U, h_sub_U.trans (iUnion_const U).symm.subset, fun _ ↦ ⟨U_open, disjoint_of_subset (fun ⦃a⦄ a ↦ a) k_sub_V (UV_dis.closure_left V_open)⟩⟩, ⟨fun _ ↦ V, k_sub_V.trans (iUnion_const V).symm.subset, fun _ ↦ ⟨V_open, disjoint_of_subset (fun ⦃a⦄ a ↦ a) h_sub_U (UV_dis.closure_right U_open).symm⟩⟩⟩ theorem Set.hasSeparatingCover_empty_left (s : Set X) : HasSeparatingCover ∅ s := ⟨fun _ ↦ ∅, empty_subset (⋃ _, ∅), fun _ ↦ ⟨isOpen_empty, by simp only [closure_empty, empty_disjoint]⟩⟩ theorem Set.hasSeparatingCover_empty_right (s : Set X) : HasSeparatingCover s ∅ := ⟨fun _ ↦ univ, (subset_univ s).trans univ.iUnion_const.symm.subset, fun _ ↦ ⟨isOpen_univ, by apply disjoint_empty⟩⟩ theorem HasSeparatingCover.mono {s₁ s₂ t₁ t₂ : Set X} (sc_st : HasSeparatingCover s₂ t₂) (s_sub : s₁ ⊆ s₂) (t_sub : t₁ ⊆ t₂) : HasSeparatingCover s₁ t₁ := by obtain ⟨u, u_cov, u_props⟩ := sc_st exact ⟨u, s_sub.trans u_cov, fun n ↦ ⟨(u_props n).1, disjoint_of_subset (fun ⦃_⦄ a ↦ a) t_sub (u_props n).2⟩⟩ namespace SeparatedNhds variable {s s₁ s₂ t t₁ t₂ u : Set X} @[symm] theorem symm : SeparatedNhds s t → SeparatedNhds t s := fun ⟨U, V, oU, oV, aU, bV, UV⟩ => ⟨V, U, oV, oU, bV, aU, Disjoint.symm UV⟩ theorem comm (s t : Set X) : SeparatedNhds s t ↔ SeparatedNhds t s := ⟨symm, symm⟩ theorem preimage [TopologicalSpace Y] {f : X → Y} {s t : Set Y} (h : SeparatedNhds s t) (hf : Continuous f) : SeparatedNhds (f ⁻¹' s) (f ⁻¹' t) := let ⟨U, V, oU, oV, sU, tV, UV⟩ := h ⟨f ⁻¹' U, f ⁻¹' V, oU.preimage hf, oV.preimage hf, preimage_mono sU, preimage_mono tV, UV.preimage f⟩ protected theorem disjoint (h : SeparatedNhds s t) : Disjoint s t := let ⟨_, _, _, _, hsU, htV, hd⟩ := h; hd.mono hsU htV theorem disjoint_closure_left (h : SeparatedNhds s t) : Disjoint (closure s) t := let ⟨_U, _V, _, hV, hsU, htV, hd⟩ := h (hd.closure_left hV).mono (closure_mono hsU) htV theorem disjoint_closure_right (h : SeparatedNhds s t) : Disjoint s (closure t) := h.symm.disjoint_closure_left.symm @[simp] theorem empty_right (s : Set X) : SeparatedNhds s ∅ := ⟨_, _, isOpen_univ, isOpen_empty, fun a _ => mem_univ a, Subset.rfl, disjoint_empty _⟩ @[simp] theorem empty_left (s : Set X) : SeparatedNhds ∅ s := (empty_right _).symm theorem mono (h : SeparatedNhds s₂ t₂) (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : SeparatedNhds s₁ t₁ := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h ⟨U, V, hU, hV, hs.trans hsU, ht.trans htV, hd⟩ theorem union_left : SeparatedNhds s u → SeparatedNhds t u → SeparatedNhds (s ∪ t) u := by simpa only [separatedNhds_iff_disjoint, nhdsSet_union, disjoint_sup_left] using And.intro theorem union_right (ht : SeparatedNhds s t) (hu : SeparatedNhds s u) : SeparatedNhds s (t ∪ u) := (ht.symm.union_left hu.symm).symm end SeparatedNhds /-- A T₀ space, also known as a Kolmogorov space, is a topological space such that for every pair `x ≠ y`, there is an open set containing one but not the other. We formulate the definition in terms of the `Inseparable` relation. -/ class T0Space (X : Type u) [TopologicalSpace X] : Prop where /-- Two inseparable points in a T₀ space are equal. -/ t0 : ∀ ⦃x y : X⦄, Inseparable x y → x = y theorem t0Space_iff_inseparable (X : Type u) [TopologicalSpace X] : T0Space X ↔ ∀ x y : X, Inseparable x y → x = y := ⟨fun ⟨h⟩ => h, fun h => ⟨h⟩⟩ theorem t0Space_iff_not_inseparable (X : Type u) [TopologicalSpace X] : T0Space X ↔ Pairwise fun x y : X => ¬Inseparable x y := by simp only [t0Space_iff_inseparable, Ne, not_imp_not, Pairwise] theorem Inseparable.eq [T0Space X] {x y : X} (h : Inseparable x y) : x = y := T0Space.t0 h /-- A topology `Inducing` map from a T₀ space is injective. -/ protected theorem Inducing.injective [TopologicalSpace Y] [T0Space X] {f : X → Y} (hf : Inducing f) : Injective f := fun _ _ h => (hf.inseparable_iff.1 <| .of_eq h).eq /-- A topology `Inducing` map from a T₀ space is a topological embedding. -/ protected theorem Inducing.embedding [TopologicalSpace Y] [T0Space X] {f : X → Y} (hf : Inducing f) : Embedding f := ⟨hf, hf.injective⟩ lemma embedding_iff_inducing [TopologicalSpace Y] [T0Space X] {f : X → Y} : Embedding f ↔ Inducing f := ⟨Embedding.toInducing, Inducing.embedding⟩ theorem t0Space_iff_nhds_injective (X : Type u) [TopologicalSpace X] : T0Space X ↔ Injective (𝓝 : X → Filter X) := t0Space_iff_inseparable X theorem nhds_injective [T0Space X] : Injective (𝓝 : X → Filter X) := (t0Space_iff_nhds_injective X).1 ‹_› theorem inseparable_iff_eq [T0Space X] {x y : X} : Inseparable x y ↔ x = y := nhds_injective.eq_iff @[simp] theorem nhds_eq_nhds_iff [T0Space X] {a b : X} : 𝓝 a = 𝓝 b ↔ a = b := nhds_injective.eq_iff @[simp] theorem inseparable_eq_eq [T0Space X] : Inseparable = @Eq X := funext₂ fun _ _ => propext inseparable_iff_eq theorem TopologicalSpace.IsTopologicalBasis.inseparable_iff {b : Set (Set X)} (hb : IsTopologicalBasis b) {x y : X} : Inseparable x y ↔ ∀ s ∈ b, (x ∈ s ↔ y ∈ s) := ⟨fun h s hs ↦ inseparable_iff_forall_open.1 h _ (hb.isOpen hs), fun h ↦ hb.nhds_hasBasis.eq_of_same_basis <| by convert hb.nhds_hasBasis using 2 exact and_congr_right (h _)⟩ theorem TopologicalSpace.IsTopologicalBasis.eq_iff [T0Space X] {b : Set (Set X)} (hb : IsTopologicalBasis b) {x y : X} : x = y ↔ ∀ s ∈ b, (x ∈ s ↔ y ∈ s) := inseparable_iff_eq.symm.trans hb.inseparable_iff theorem t0Space_iff_exists_isOpen_xor'_mem (X : Type u) [TopologicalSpace X] : T0Space X ↔ Pairwise fun x y => ∃ U : Set X, IsOpen U ∧ Xor' (x ∈ U) (y ∈ U) := by simp only [t0Space_iff_not_inseparable, xor_iff_not_iff, not_forall, exists_prop, inseparable_iff_forall_open, Pairwise] theorem exists_isOpen_xor'_mem [T0Space X] {x y : X} (h : x ≠ y) : ∃ U : Set X, IsOpen U ∧ Xor' (x ∈ U) (y ∈ U) := (t0Space_iff_exists_isOpen_xor'_mem X).1 ‹_› h /-- Specialization forms a partial order on a t0 topological space. -/ def specializationOrder (X) [TopologicalSpace X] [T0Space X] : PartialOrder X := { specializationPreorder X, PartialOrder.lift (OrderDual.toDual ∘ 𝓝) nhds_injective with } instance SeparationQuotient.instT0Space : T0Space (SeparationQuotient X) := ⟨fun x y => Quotient.inductionOn₂' x y fun _ _ h => SeparationQuotient.mk_eq_mk.2 <| SeparationQuotient.inducing_mk.inseparable_iff.1 h⟩ theorem minimal_nonempty_closed_subsingleton [T0Space X] {s : Set X} (hs : IsClosed s) (hmin : ∀ t, t ⊆ s → t.Nonempty → IsClosed t → t = s) : s.Subsingleton := by clear Y -- Porting note: added refine fun x hx y hy => of_not_not fun hxy => ?_ rcases exists_isOpen_xor'_mem hxy with ⟨U, hUo, hU⟩ wlog h : x ∈ U ∧ y ∉ U · refine this hs hmin y hy x hx (Ne.symm hxy) U hUo hU.symm (hU.resolve_left h) cases' h with hxU hyU have : s \ U = s := hmin (s \ U) diff_subset ⟨y, hy, hyU⟩ (hs.sdiff hUo) exact (this.symm.subset hx).2 hxU theorem minimal_nonempty_closed_eq_singleton [T0Space X] {s : Set X} (hs : IsClosed s) (hne : s.Nonempty) (hmin : ∀ t, t ⊆ s → t.Nonempty → IsClosed t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_closed_subsingleton hs hmin⟩ /-- Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. -/ theorem IsClosed.exists_closed_singleton [T0Space X] [CompactSpace X] {S : Set X} (hS : IsClosed S) (hne : S.Nonempty) : ∃ x : X, x ∈ S ∧ IsClosed ({x} : Set X) := by obtain ⟨V, Vsub, Vne, Vcls, hV⟩ := hS.exists_minimal_nonempty_closed_subset hne rcases minimal_nonempty_closed_eq_singleton Vcls Vne hV with ⟨x, rfl⟩ exact ⟨x, Vsub (mem_singleton x), Vcls⟩ theorem minimal_nonempty_open_subsingleton [T0Space X] {s : Set X} (hs : IsOpen s) (hmin : ∀ t, t ⊆ s → t.Nonempty → IsOpen t → t = s) : s.Subsingleton := by clear Y -- Porting note: added refine fun x hx y hy => of_not_not fun hxy => ?_ rcases exists_isOpen_xor'_mem hxy with ⟨U, hUo, hU⟩ wlog h : x ∈ U ∧ y ∉ U · exact this hs hmin y hy x hx (Ne.symm hxy) U hUo hU.symm (hU.resolve_left h) cases' h with hxU hyU have : s ∩ U = s := hmin (s ∩ U) inter_subset_left ⟨x, hx, hxU⟩ (hs.inter hUo) exact hyU (this.symm.subset hy).2 theorem minimal_nonempty_open_eq_singleton [T0Space X] {s : Set X} (hs : IsOpen s) (hne : s.Nonempty) (hmin : ∀ t, t ⊆ s → t.Nonempty → IsOpen t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_open_subsingleton hs hmin⟩ /-- Given an open finite set `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. -/ theorem exists_isOpen_singleton_of_isOpen_finite [T0Space X] {s : Set X} (hfin : s.Finite) (hne : s.Nonempty) (ho : IsOpen s) : ∃ x ∈ s, IsOpen ({x} : Set X) := by lift s to Finset X using hfin induction' s using Finset.strongInductionOn with s ihs rcases em (∃ t, t ⊂ s ∧ t.Nonempty ∧ IsOpen (t : Set X)) with (⟨t, hts, htne, hto⟩ | ht) · rcases ihs t hts htne hto with ⟨x, hxt, hxo⟩ exact ⟨x, hts.1 hxt, hxo⟩ · -- Porting note: was `rcases minimal_nonempty_open_eq_singleton ho hne _ with ⟨x, hx⟩` -- https://github.com/leanprover/std4/issues/116 rsuffices ⟨x, hx⟩ : ∃ x, s.toSet = {x} · exact ⟨x, hx.symm ▸ rfl, hx ▸ ho⟩ refine minimal_nonempty_open_eq_singleton ho hne ?_ refine fun t hts htne hto => of_not_not fun hts' => ht ?_ lift t to Finset X using s.finite_toSet.subset hts exact ⟨t, ssubset_iff_subset_ne.2 ⟨hts, mt Finset.coe_inj.2 hts'⟩, htne, hto⟩ theorem exists_open_singleton_of_finite [T0Space X] [Finite X] [Nonempty X] : ∃ x : X, IsOpen ({x} : Set X) := let ⟨x, _, h⟩ := exists_isOpen_singleton_of_isOpen_finite (Set.toFinite _) univ_nonempty isOpen_univ ⟨x, h⟩ theorem t0Space_of_injective_of_continuous [TopologicalSpace Y] {f : X → Y} (hf : Function.Injective f) (hf' : Continuous f) [T0Space Y] : T0Space X := ⟨fun _ _ h => hf <| (h.map hf').eq⟩ protected theorem Embedding.t0Space [TopologicalSpace Y] [T0Space Y] {f : X → Y} (hf : Embedding f) : T0Space X := t0Space_of_injective_of_continuous hf.inj hf.continuous instance Subtype.t0Space [T0Space X] {p : X → Prop} : T0Space (Subtype p) := embedding_subtype_val.t0Space theorem t0Space_iff_or_not_mem_closure (X : Type u) [TopologicalSpace X] : T0Space X ↔ Pairwise fun a b : X => a ∉ closure ({b} : Set X) ∨ b ∉ closure ({a} : Set X) := by simp only [t0Space_iff_not_inseparable, inseparable_iff_mem_closure, not_and_or] instance Prod.instT0Space [TopologicalSpace Y] [T0Space X] [T0Space Y] : T0Space (X × Y) := ⟨fun _ _ h => Prod.ext (h.map continuous_fst).eq (h.map continuous_snd).eq⟩ instance Pi.instT0Space {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, T0Space (X i)] : T0Space (∀ i, X i) := ⟨fun _ _ h => funext fun i => (h.map (continuous_apply i)).eq⟩ instance ULift.instT0Space [T0Space X] : T0Space (ULift X) := embedding_uLift_down.t0Space theorem T0Space.of_cover (h : ∀ x y, Inseparable x y → ∃ s : Set X, x ∈ s ∧ y ∈ s ∧ T0Space s) : T0Space X := by refine ⟨fun x y hxy => ?_⟩ rcases h x y hxy with ⟨s, hxs, hys, hs⟩ lift x to s using hxs; lift y to s using hys rw [← subtype_inseparable_iff] at hxy exact congr_arg Subtype.val hxy.eq theorem T0Space.of_open_cover (h : ∀ x, ∃ s : Set X, x ∈ s ∧ IsOpen s ∧ T0Space s) : T0Space X := T0Space.of_cover fun x _ hxy => let ⟨s, hxs, hso, hs⟩ := h x ⟨s, hxs, (hxy.mem_open_iff hso).1 hxs, hs⟩ /-- A topological space is called an R₀ space, if `Specializes` relation is symmetric. In other words, given two points `x y : X`, if every neighborhood of `y` contains `x`, then every neighborhood of `x` contains `y`. -/ @[mk_iff] class R0Space (X : Type u) [TopologicalSpace X] : Prop where /-- In an R₀ space, the `Specializes` relation is symmetric. -/ specializes_symmetric : Symmetric (Specializes : X → X → Prop) export R0Space (specializes_symmetric) section R0Space variable [R0Space X] {x y : X} /-- In an R₀ space, the `Specializes` relation is symmetric, dot notation version. -/ theorem Specializes.symm (h : x ⤳ y) : y ⤳ x := specializes_symmetric h /-- In an R₀ space, the `Specializes` relation is symmetric, `Iff` version. -/ theorem specializes_comm : x ⤳ y ↔ y ⤳ x := ⟨Specializes.symm, Specializes.symm⟩ /-- In an R₀ space, `Specializes` is equivalent to `Inseparable`. -/ theorem specializes_iff_inseparable : x ⤳ y ↔ Inseparable x y := ⟨fun h ↦ h.antisymm h.symm, Inseparable.specializes⟩ /-- In an R₀ space, `Specializes` implies `Inseparable`. -/ alias ⟨Specializes.inseparable, _⟩ := specializes_iff_inseparable theorem Inducing.r0Space [TopologicalSpace Y] {f : Y → X} (hf : Inducing f) : R0Space Y where specializes_symmetric a b := by simpa only [← hf.specializes_iff] using Specializes.symm instance {p : X → Prop} : R0Space {x // p x} := inducing_subtype_val.r0Space instance [TopologicalSpace Y] [R0Space Y] : R0Space (X × Y) where specializes_symmetric _ _ h := h.fst.symm.prod h.snd.symm instance {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, R0Space (X i)] : R0Space (∀ i, X i) where specializes_symmetric _ _ h := specializes_pi.2 fun i ↦ (specializes_pi.1 h i).symm /-- In an R₀ space, the closure of a singleton is a compact set. -/ theorem isCompact_closure_singleton : IsCompact (closure {x}) := by refine isCompact_of_finite_subcover fun U hUo hxU ↦ ?_ obtain ⟨i, hi⟩ : ∃ i, x ∈ U i := mem_iUnion.1 <| hxU <| subset_closure rfl refine ⟨{i}, fun y hy ↦ ?_⟩ rw [← specializes_iff_mem_closure, specializes_comm] at hy simpa using hy.mem_open (hUo i) hi theorem Filter.coclosedCompact_le_cofinite : coclosedCompact X ≤ cofinite := le_cofinite_iff_compl_singleton_mem.2 fun _ ↦ compl_mem_coclosedCompact.2 isCompact_closure_singleton variable (X) /-- In an R₀ space, relatively compact sets form a bornology. Its cobounded filter is `Filter.coclosedCompact`. See also `Bornology.inCompact` the bornology of sets contained in a compact set. -/ def Bornology.relativelyCompact : Bornology X where cobounded' := Filter.coclosedCompact X le_cofinite' := Filter.coclosedCompact_le_cofinite variable {X} theorem Bornology.relativelyCompact.isBounded_iff {s : Set X} : @Bornology.IsBounded _ (Bornology.relativelyCompact X) s ↔ IsCompact (closure s) := compl_mem_coclosedCompact /-- In an R₀ space, the closure of a finite set is a compact set. -/ theorem Set.Finite.isCompact_closure {s : Set X} (hs : s.Finite) : IsCompact (closure s) := let _ : Bornology X := .relativelyCompact X Bornology.relativelyCompact.isBounded_iff.1 hs.isBounded end R0Space /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class T1Space (X : Type u) [TopologicalSpace X] : Prop where /-- A singleton in a T₁ space is a closed set. -/ t1 : ∀ x, IsClosed ({x} : Set X) theorem isClosed_singleton [T1Space X] {x : X} : IsClosed ({x} : Set X) := T1Space.t1 x theorem isOpen_compl_singleton [T1Space X] {x : X} : IsOpen ({x}ᶜ : Set X) := isClosed_singleton.isOpen_compl theorem isOpen_ne [T1Space X] {x : X} : IsOpen { y | y ≠ x } := isOpen_compl_singleton @[to_additive] theorem Continuous.isOpen_mulSupport [T1Space X] [One X] [TopologicalSpace Y] {f : Y → X} (hf : Continuous f) : IsOpen (mulSupport f) := isOpen_ne.preimage hf theorem Ne.nhdsWithin_compl_singleton [T1Space X] {x y : X} (h : x ≠ y) : 𝓝[{y}ᶜ] x = 𝓝 x := isOpen_ne.nhdsWithin_eq h theorem Ne.nhdsWithin_diff_singleton [T1Space X] {x y : X} (h : x ≠ y) (s : Set X) : 𝓝[s \ {y}] x = 𝓝[s] x := by rw [diff_eq, inter_comm, nhdsWithin_inter_of_mem] exact mem_nhdsWithin_of_mem_nhds (isOpen_ne.mem_nhds h) lemma nhdsWithin_compl_singleton_le [T1Space X] (x y : X) : 𝓝[{x}ᶜ] x ≤ 𝓝[{y}ᶜ] x := by rcases eq_or_ne x y with rfl|hy · exact Eq.le rfl · rw [Ne.nhdsWithin_compl_singleton hy] exact nhdsWithin_le_nhds theorem isOpen_setOf_eventually_nhdsWithin [T1Space X] {p : X → Prop} : IsOpen { x | ∀ᶠ y in 𝓝[≠] x, p y } := by refine isOpen_iff_mem_nhds.mpr fun a ha => ?_ filter_upwards [eventually_nhds_nhdsWithin.mpr ha] with b hb rcases eq_or_ne a b with rfl | h · exact hb · rw [h.symm.nhdsWithin_compl_singleton] at hb exact hb.filter_mono nhdsWithin_le_nhds protected theorem Set.Finite.isClosed [T1Space X] {s : Set X} (hs : Set.Finite s) : IsClosed s := by rw [← biUnion_of_singleton s] exact hs.isClosed_biUnion fun i _ => isClosed_singleton theorem TopologicalSpace.IsTopologicalBasis.exists_mem_of_ne [T1Space X] {b : Set (Set X)} (hb : IsTopologicalBasis b) {x y : X} (h : x ≠ y) : ∃ a ∈ b, x ∈ a ∧ y ∉ a := by rcases hb.isOpen_iff.1 isOpen_ne x h with ⟨a, ab, xa, ha⟩ exact ⟨a, ab, xa, fun h => ha h rfl⟩ protected theorem Finset.isClosed [T1Space X] (s : Finset X) : IsClosed (s : Set X) := s.finite_toSet.isClosed theorem t1Space_TFAE (X : Type u) [TopologicalSpace X] : List.TFAE [T1Space X, ∀ x, IsClosed ({ x } : Set X), ∀ x, IsOpen ({ x }ᶜ : Set X), Continuous (@CofiniteTopology.of X), ∀ ⦃x y : X⦄, x ≠ y → {y}ᶜ ∈ 𝓝 x, ∀ ⦃x y : X⦄, x ≠ y → ∃ s ∈ 𝓝 x, y ∉ s, ∀ ⦃x y : X⦄, x ≠ y → ∃ U : Set X, IsOpen U ∧ x ∈ U ∧ y ∉ U, ∀ ⦃x y : X⦄, x ≠ y → Disjoint (𝓝 x) (pure y), ∀ ⦃x y : X⦄, x ≠ y → Disjoint (pure x) (𝓝 y), ∀ ⦃x y : X⦄, x ⤳ y → x = y] := by tfae_have 1 ↔ 2 · exact ⟨fun h => h.1, fun h => ⟨h⟩⟩ tfae_have 2 ↔ 3 · simp only [isOpen_compl_iff] tfae_have 5 ↔ 3 · refine forall_swap.trans ?_ simp only [isOpen_iff_mem_nhds, mem_compl_iff, mem_singleton_iff] tfae_have 5 ↔ 6 · simp only [← subset_compl_singleton_iff, exists_mem_subset_iff] tfae_have 5 ↔ 7 · simp only [(nhds_basis_opens _).mem_iff, subset_compl_singleton_iff, exists_prop, and_assoc, and_left_comm] tfae_have 5 ↔ 8 · simp only [← principal_singleton, disjoint_principal_right] tfae_have 8 ↔ 9 · exact forall_swap.trans (by simp only [disjoint_comm, ne_comm]) tfae_have 1 → 4 · simp only [continuous_def, CofiniteTopology.isOpen_iff'] rintro H s (rfl | hs) exacts [isOpen_empty, compl_compl s ▸ (@Set.Finite.isClosed _ _ H _ hs).isOpen_compl] tfae_have 4 → 2 · exact fun h x => (CofiniteTopology.isClosed_iff.2 <| Or.inr (finite_singleton _)).preimage h tfae_have 2 ↔ 10 · simp only [← closure_subset_iff_isClosed, specializes_iff_mem_closure, subset_def, mem_singleton_iff, eq_comm] tfae_finish theorem t1Space_iff_continuous_cofinite_of : T1Space X ↔ Continuous (@CofiniteTopology.of X) := (t1Space_TFAE X).out 0 3 theorem CofiniteTopology.continuous_of [T1Space X] : Continuous (@CofiniteTopology.of X) := t1Space_iff_continuous_cofinite_of.mp ‹_› theorem t1Space_iff_exists_open : T1Space X ↔ Pairwise fun x y => ∃ U : Set X, IsOpen U ∧ x ∈ U ∧ y ∉ U := (t1Space_TFAE X).out 0 6 theorem t1Space_iff_disjoint_pure_nhds : T1Space X ↔ ∀ ⦃x y : X⦄, x ≠ y → Disjoint (pure x) (𝓝 y) := (t1Space_TFAE X).out 0 8 theorem t1Space_iff_disjoint_nhds_pure : T1Space X ↔ ∀ ⦃x y : X⦄, x ≠ y → Disjoint (𝓝 x) (pure y) := (t1Space_TFAE X).out 0 7 theorem t1Space_iff_specializes_imp_eq : T1Space X ↔ ∀ ⦃x y : X⦄, x ⤳ y → x = y := (t1Space_TFAE X).out 0 9 theorem disjoint_pure_nhds [T1Space X] {x y : X} (h : x ≠ y) : Disjoint (pure x) (𝓝 y) := t1Space_iff_disjoint_pure_nhds.mp ‹_› h theorem disjoint_nhds_pure [T1Space X] {x y : X} (h : x ≠ y) : Disjoint (𝓝 x) (pure y) := t1Space_iff_disjoint_nhds_pure.mp ‹_› h theorem Specializes.eq [T1Space X] {x y : X} (h : x ⤳ y) : x = y := t1Space_iff_specializes_imp_eq.1 ‹_› h theorem specializes_iff_eq [T1Space X] {x y : X} : x ⤳ y ↔ x = y := ⟨Specializes.eq, fun h => h ▸ specializes_rfl⟩ @[simp] theorem specializes_eq_eq [T1Space X] : (· ⤳ ·) = @Eq X := funext₂ fun _ _ => propext specializes_iff_eq @[simp] theorem pure_le_nhds_iff [T1Space X] {a b : X} : pure a ≤ 𝓝 b ↔ a = b := specializes_iff_pure.symm.trans specializes_iff_eq @[simp] theorem nhds_le_nhds_iff [T1Space X] {a b : X} : 𝓝 a ≤ 𝓝 b ↔ a = b := specializes_iff_eq instance (priority := 100) [T1Space X] : R0Space X where specializes_symmetric _ _ := by rw [specializes_iff_eq, specializes_iff_eq]; exact Eq.symm instance : T1Space (CofiniteTopology X) := t1Space_iff_continuous_cofinite_of.mpr continuous_id theorem t1Space_antitone {X} : Antitone (@T1Space X) := fun a _ h _ => @T1Space.mk _ a fun x => (T1Space.t1 x).mono h theorem continuousWithinAt_update_of_ne [T1Space X] [DecidableEq X] [TopologicalSpace Y] {f : X → Y} {s : Set X} {x x' : X} {y : Y} (hne : x' ≠ x) : ContinuousWithinAt (Function.update f x y) s x' ↔ ContinuousWithinAt f s x' := EventuallyEq.congr_continuousWithinAt (mem_nhdsWithin_of_mem_nhds <| mem_of_superset (isOpen_ne.mem_nhds hne) fun _y' hy' => Function.update_noteq hy' _ _) (Function.update_noteq hne _ _) theorem continuousAt_update_of_ne [T1Space X] [DecidableEq X] [TopologicalSpace Y] {f : X → Y} {x x' : X} {y : Y} (hne : x' ≠ x) : ContinuousAt (Function.update f x y) x' ↔ ContinuousAt f x' := by simp only [← continuousWithinAt_univ, continuousWithinAt_update_of_ne hne] theorem continuousOn_update_iff [T1Space X] [DecidableEq X] [TopologicalSpace Y] {f : X → Y} {s : Set X} {x : X} {y : Y} : ContinuousOn (Function.update f x y) s ↔ ContinuousOn f (s \ {x}) ∧ (x ∈ s → Tendsto f (𝓝[s \ {x}] x) (𝓝 y)) := by rw [ContinuousOn, ← and_forall_ne x, and_comm] refine and_congr ⟨fun H z hz => ?_, fun H z hzx hzs => ?_⟩ (forall_congr' fun _ => ?_) · specialize H z hz.2 hz.1 rw [continuousWithinAt_update_of_ne hz.2] at H exact H.mono diff_subset · rw [continuousWithinAt_update_of_ne hzx] refine (H z ⟨hzs, hzx⟩).mono_of_mem (inter_mem_nhdsWithin _ ?_) exact isOpen_ne.mem_nhds hzx · exact continuousWithinAt_update_same theorem t1Space_of_injective_of_continuous [TopologicalSpace Y] {f : X → Y} (hf : Function.Injective f) (hf' : Continuous f) [T1Space Y] : T1Space X := t1Space_iff_specializes_imp_eq.2 fun _ _ h => hf (h.map hf').eq protected theorem Embedding.t1Space [TopologicalSpace Y] [T1Space Y] {f : X → Y} (hf : Embedding f) : T1Space X := t1Space_of_injective_of_continuous hf.inj hf.continuous instance Subtype.t1Space {X : Type u} [TopologicalSpace X] [T1Space X] {p : X → Prop} : T1Space (Subtype p) := embedding_subtype_val.t1Space instance [TopologicalSpace Y] [T1Space X] [T1Space Y] : T1Space (X × Y) := ⟨fun ⟨a, b⟩ => @singleton_prod_singleton _ _ a b ▸ isClosed_singleton.prod isClosed_singleton⟩ instance {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, T1Space (X i)] : T1Space (∀ i, X i) := ⟨fun f => univ_pi_singleton f ▸ isClosed_set_pi fun _ _ => isClosed_singleton⟩ instance ULift.instT1Space [T1Space X] : T1Space (ULift X) := embedding_uLift_down.t1Space -- see Note [lower instance priority] instance (priority := 100) TotallyDisconnectedSpace.t1Space [h : TotallyDisconnectedSpace X] : T1Space X := by rw [((t1Space_TFAE X).out 0 1 :)] intro x rw [← totallyDisconnectedSpace_iff_connectedComponent_singleton.mp h x] exact isClosed_connectedComponent -- see Note [lower instance priority] instance (priority := 100) T1Space.t0Space [T1Space X] : T0Space X := ⟨fun _ _ h => h.specializes.eq⟩ @[simp] theorem compl_singleton_mem_nhds_iff [T1Space X] {x y : X} : {x}ᶜ ∈ 𝓝 y ↔ y ≠ x := isOpen_compl_singleton.mem_nhds_iff theorem compl_singleton_mem_nhds [T1Space X] {x y : X} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y := compl_singleton_mem_nhds_iff.mpr h @[simp] theorem closure_singleton [T1Space X] {x : X} : closure ({x} : Set X) = {x} := isClosed_singleton.closure_eq -- Porting note (#11215): TODO: the proof was `hs.induction_on (by simp) fun x => by simp` theorem Set.Subsingleton.closure [T1Space X] {s : Set X} (hs : s.Subsingleton) : (closure s).Subsingleton := by rcases hs.eq_empty_or_singleton with (rfl | ⟨x, rfl⟩) <;> simp @[simp] theorem subsingleton_closure [T1Space X] {s : Set X} : (closure s).Subsingleton ↔ s.Subsingleton := ⟨fun h => h.anti subset_closure, fun h => h.closure⟩ theorem isClosedMap_const {X Y} [TopologicalSpace X] [TopologicalSpace Y] [T1Space Y] {y : Y} : IsClosedMap (Function.const X y) := IsClosedMap.of_nonempty fun s _ h2s => by simp_rw [const, h2s.image_const, isClosed_singleton] theorem nhdsWithin_insert_of_ne [T1Space X] {x y : X} {s : Set X} (hxy : x ≠ y) : 𝓝[insert y s] x = 𝓝[s] x := by refine le_antisymm (Filter.le_def.2 fun t ht => ?_) (nhdsWithin_mono x <| subset_insert y s) obtain ⟨o, ho, hxo, host⟩ := mem_nhdsWithin.mp ht refine mem_nhdsWithin.mpr ⟨o \ {y}, ho.sdiff isClosed_singleton, ⟨hxo, hxy⟩, ?_⟩ rw [inter_insert_of_not_mem <| not_mem_diff_of_mem (mem_singleton y)] exact (inter_subset_inter diff_subset Subset.rfl).trans host /-- If `t` is a subset of `s`, except for one point, then `insert x s` is a neighborhood of `x` within `t`. -/ theorem insert_mem_nhdsWithin_of_subset_insert [T1Space X] {x y : X} {s t : Set X} (hu : t ⊆ insert y s) : insert x s ∈ 𝓝[t] x := by rcases eq_or_ne x y with (rfl | h) · exact mem_of_superset self_mem_nhdsWithin hu refine nhdsWithin_mono x hu ?_ rw [nhdsWithin_insert_of_ne h] exact mem_of_superset self_mem_nhdsWithin (subset_insert x s) @[simp] theorem ker_nhds [T1Space X] (x : X) : (𝓝 x).ker = {x} := by simp [ker_nhds_eq_specializes] theorem biInter_basis_nhds [T1Space X] {ι : Sort*} {p : ι → Prop} {s : ι → Set X} {x : X} (h : (𝓝 x).HasBasis p s) : ⋂ (i) (_ : p i), s i = {x} := by rw [← h.ker, ker_nhds] @[simp] theorem compl_singleton_mem_nhdsSet_iff [T1Space X] {x : X} {s : Set X} : {x}ᶜ ∈ 𝓝ˢ s ↔ x ∉ s := by rw [isOpen_compl_singleton.mem_nhdsSet, subset_compl_singleton_iff] @[simp] theorem nhdsSet_le_iff [T1Space X] {s t : Set X} : 𝓝ˢ s ≤ 𝓝ˢ t ↔ s ⊆ t := by refine ⟨?_, fun h => monotone_nhdsSet h⟩ simp_rw [Filter.le_def]; intro h x hx specialize h {x}ᶜ simp_rw [compl_singleton_mem_nhdsSet_iff] at h by_contra hxt exact h hxt hx @[simp] theorem nhdsSet_inj_iff [T1Space X] {s t : Set X} : 𝓝ˢ s = 𝓝ˢ t ↔ s = t := by simp_rw [le_antisymm_iff] exact and_congr nhdsSet_le_iff nhdsSet_le_iff theorem injective_nhdsSet [T1Space X] : Function.Injective (𝓝ˢ : Set X → Filter X) := fun _ _ hst => nhdsSet_inj_iff.mp hst theorem strictMono_nhdsSet [T1Space X] : StrictMono (𝓝ˢ : Set X → Filter X) := monotone_nhdsSet.strictMono_of_injective injective_nhdsSet @[simp] theorem nhds_le_nhdsSet_iff [T1Space X] {s : Set X} {x : X} : 𝓝 x ≤ 𝓝ˢ s ↔ x ∈ s := by rw [← nhdsSet_singleton, nhdsSet_le_iff, singleton_subset_iff] /-- Removing a non-isolated point from a dense set, one still obtains a dense set. -/ theorem Dense.diff_singleton [T1Space X] {s : Set X} (hs : Dense s) (x : X) [NeBot (𝓝[≠] x)] : Dense (s \ {x}) := hs.inter_of_isOpen_right (dense_compl_singleton x) isOpen_compl_singleton /-- Removing a finset from a dense set in a space without isolated points, one still obtains a dense set. -/ theorem Dense.diff_finset [T1Space X] [∀ x : X, NeBot (𝓝[≠] x)] {s : Set X} (hs : Dense s) (t : Finset X) : Dense (s \ t) := by classical induction t using Finset.induction_on with | empty => simpa using hs | insert _ ih => rw [Finset.coe_insert, ← union_singleton, ← diff_diff] exact ih.diff_singleton _ /-- Removing a finite set from a dense set in a space without isolated points, one still obtains a dense set. -/ theorem Dense.diff_finite [T1Space X] [∀ x : X, NeBot (𝓝[≠] x)] {s : Set X} (hs : Dense s) {t : Set X} (ht : t.Finite) : Dense (s \ t) := by convert hs.diff_finset ht.toFinset exact (Finite.coe_toFinset _).symm /-- If a function to a `T1Space` tends to some limit `y` at some point `x`, then necessarily `y = f x`. -/ theorem eq_of_tendsto_nhds [TopologicalSpace Y] [T1Space Y] {f : X → Y} {x : X} {y : Y} (h : Tendsto f (𝓝 x) (𝓝 y)) : f x = y := by_contra fun hfa : f x ≠ y => have fact₁ : {f x}ᶜ ∈ 𝓝 y := compl_singleton_mem_nhds hfa.symm have fact₂ : Tendsto f (pure x) (𝓝 y) := h.comp (tendsto_id'.2 <| pure_le_nhds x) fact₂ fact₁ (Eq.refl <| f x) theorem Filter.Tendsto.eventually_ne {X} [TopologicalSpace Y] [T1Space Y] {g : X → Y} {l : Filter X} {b₁ b₂ : Y} (hg : Tendsto g l (𝓝 b₁)) (hb : b₁ ≠ b₂) : ∀ᶠ z in l, g z ≠ b₂ := hg.eventually (isOpen_compl_singleton.eventually_mem hb) theorem ContinuousAt.eventually_ne [TopologicalSpace Y] [T1Space Y] {g : X → Y} {x : X} {y : Y} (hg1 : ContinuousAt g x) (hg2 : g x ≠ y) : ∀ᶠ z in 𝓝 x, g z ≠ y := hg1.tendsto.eventually_ne hg2 theorem eventually_ne_nhds [T1Space X] {a b : X} (h : a ≠ b) : ∀ᶠ x in 𝓝 a, x ≠ b := IsOpen.eventually_mem isOpen_ne h theorem eventually_ne_nhdsWithin [T1Space X] {a b : X} {s : Set X} (h : a ≠ b) : ∀ᶠ x in 𝓝[s] a, x ≠ b := Filter.Eventually.filter_mono nhdsWithin_le_nhds <| eventually_ne_nhds h /-- To prove a function to a `T1Space` is continuous at some point `x`, it suffices to prove that `f` admits *some* limit at `x`. -/ theorem continuousAt_of_tendsto_nhds [TopologicalSpace Y] [T1Space Y] {f : X → Y} {x : X} {y : Y} (h : Tendsto f (𝓝 x) (𝓝 y)) : ContinuousAt f x := by rwa [ContinuousAt, eq_of_tendsto_nhds h] @[simp] theorem tendsto_const_nhds_iff [T1Space X] {l : Filter Y} [NeBot l] {c d : X} : Tendsto (fun _ => c) l (𝓝 d) ↔ c = d := by simp_rw [Tendsto, Filter.map_const, pure_le_nhds_iff] /-- A point with a finite neighborhood has to be isolated. -/ theorem isOpen_singleton_of_finite_mem_nhds [T1Space X] (x : X) {s : Set X} (hs : s ∈ 𝓝 x) (hsf : s.Finite) : IsOpen ({x} : Set X) := by have A : {x} ⊆ s := by simp only [singleton_subset_iff, mem_of_mem_nhds hs] have B : IsClosed (s \ {x}) := (hsf.subset diff_subset).isClosed have C : (s \ {x})ᶜ ∈ 𝓝 x := B.isOpen_compl.mem_nhds fun h => h.2 rfl have D : {x} ∈ 𝓝 x := by simpa only [← diff_eq, diff_diff_cancel_left A] using inter_mem hs C rwa [← mem_interior_iff_mem_nhds, ← singleton_subset_iff, subset_interior_iff_isOpen] at D /-- If the punctured neighborhoods of a point form a nontrivial filter, then any neighborhood is infinite. -/ theorem infinite_of_mem_nhds {X} [TopologicalSpace X] [T1Space X] (x : X) [hx : NeBot (𝓝[≠] x)] {s : Set X} (hs : s ∈ 𝓝 x) : Set.Infinite s := by refine fun hsf => hx.1 ?_ rw [← isOpen_singleton_iff_punctured_nhds] exact isOpen_singleton_of_finite_mem_nhds x hs hsf instance Finite.instDiscreteTopology [T1Space X] [Finite X] : DiscreteTopology X := discreteTopology_iff_forall_isClosed.mpr (· |>.toFinite.isClosed) theorem Set.Finite.continuousOn [T1Space X] [TopologicalSpace Y] {s : Set X} (hs : s.Finite) (f : X → Y) : ContinuousOn f s := by rw [continuousOn_iff_continuous_restrict] have : Finite s := hs fun_prop theorem PreconnectedSpace.trivial_of_discrete [PreconnectedSpace X] [DiscreteTopology X] : Subsingleton X := by rw [← not_nontrivial_iff_subsingleton] rintro ⟨x, y, hxy⟩ rw [Ne, ← mem_singleton_iff, (isClopen_discrete _).eq_univ <| singleton_nonempty y] at hxy exact hxy (mem_univ x) theorem IsPreconnected.infinite_of_nontrivial [T1Space X] {s : Set X} (h : IsPreconnected s) (hs : s.Nontrivial) : s.Infinite := by refine mt (fun hf => (subsingleton_coe s).mp ?_) (not_subsingleton_iff.mpr hs) haveI := @Finite.instDiscreteTopology s _ _ hf.to_subtype exact @PreconnectedSpace.trivial_of_discrete _ _ (Subtype.preconnectedSpace h) _ theorem ConnectedSpace.infinite [ConnectedSpace X] [Nontrivial X] [T1Space X] : Infinite X := infinite_univ_iff.mp <| isPreconnected_univ.infinite_of_nontrivial nontrivial_univ /-- A non-trivial connected T1 space has no isolated points. -/ instance (priority := 100) ConnectedSpace.neBot_nhdsWithin_compl_of_nontrivial_of_t1space [ConnectedSpace X] [Nontrivial X] [T1Space X] (x : X) : NeBot (𝓝[≠] x) := by by_contra contra rw [not_neBot, ← isOpen_singleton_iff_punctured_nhds] at contra replace contra := nonempty_inter isOpen_compl_singleton contra (compl_union_self _) (Set.nonempty_compl_of_nontrivial _) (singleton_nonempty _) simp [compl_inter_self {x}] at contra theorem IsGδ.compl_singleton (x : X) [T1Space X] : IsGδ ({x}ᶜ : Set X) := isOpen_compl_singleton.isGδ @[deprecated (since := "2024-02-15")] alias isGδ_compl_singleton := IsGδ.compl_singleton theorem Set.Countable.isGδ_compl {s : Set X} [T1Space X] (hs : s.Countable) : IsGδ sᶜ := by rw [← biUnion_of_singleton s, compl_iUnion₂] exact .biInter hs fun x _ => .compl_singleton x theorem Set.Finite.isGδ_compl {s : Set X} [T1Space X] (hs : s.Finite) : IsGδ sᶜ := hs.countable.isGδ_compl theorem Set.Subsingleton.isGδ_compl {s : Set X} [T1Space X] (hs : s.Subsingleton) : IsGδ sᶜ := hs.finite.isGδ_compl theorem Finset.isGδ_compl [T1Space X] (s : Finset X) : IsGδ (sᶜ : Set X) := s.finite_toSet.isGδ_compl variable [FirstCountableTopology X] protected theorem IsGδ.singleton [T1Space X] (x : X) : IsGδ ({x} : Set X) := by rcases (nhds_basis_opens x).exists_antitone_subbasis with ⟨U, hU, h_basis⟩ rw [← biInter_basis_nhds h_basis.toHasBasis] exact .biInter (to_countable _) fun n _ => (hU n).2.isGδ @[deprecated (since := "2024-02-15")] alias isGδ_singleton := IsGδ.singleton theorem Set.Finite.isGδ {s : Set X} [T1Space X] (hs : s.Finite) : IsGδ s := Finite.induction_on hs .empty fun _ _ ↦ .union (.singleton _) theorem SeparationQuotient.t1Space_iff : T1Space (SeparationQuotient X) ↔ R0Space X := by rw [r0Space_iff, ((t1Space_TFAE (SeparationQuotient X)).out 0 9 :)] constructor · intro h x y xspecy rw [← Inducing.specializes_iff inducing_mk, h xspecy] at * · rintro h ⟨x⟩ ⟨y⟩ sxspecsy have xspecy : x ⤳ y := (Inducing.specializes_iff inducing_mk).mp sxspecsy have yspecx : y ⤳ x := h xspecy erw [mk_eq_mk, inseparable_iff_specializes_and] exact ⟨xspecy, yspecx⟩ lemma Set.Subsingleton.isClosed [T1Space X] {A : Set X} (h : A.Subsingleton) : IsClosed A := by rcases h.eq_empty_or_singleton with rfl | ⟨x, rfl⟩ · exact isClosed_empty · exact isClosed_singleton lemma isClosed_inter_singleton [T1Space X] {A : Set X} {a : X} : IsClosed (A ∩ {a}) := Subsingleton.inter_singleton.isClosed lemma isClosed_singleton_inter [T1Space X] {A : Set X} {a : X} : IsClosed ({a} ∩ A) := Subsingleton.singleton_inter.isClosed theorem singleton_mem_nhdsWithin_of_mem_discrete {s : Set X} [DiscreteTopology s] {x : X} (hx : x ∈ s) : {x} ∈ 𝓝[s] x := by have : ({⟨x, hx⟩} : Set s) ∈ 𝓝 (⟨x, hx⟩ : s) := by simp [nhds_discrete] simpa only [nhdsWithin_eq_map_subtype_coe hx, image_singleton] using @image_mem_map _ _ _ ((↑) : s → X) _ this /-- The neighbourhoods filter of `x` within `s`, under the discrete topology, is equal to the pure `x` filter (which is the principal filter at the singleton `{x}`.) -/ theorem nhdsWithin_of_mem_discrete {s : Set X} [DiscreteTopology s] {x : X} (hx : x ∈ s) : 𝓝[s] x = pure x := le_antisymm (le_pure_iff.2 <| singleton_mem_nhdsWithin_of_mem_discrete hx) (pure_le_nhdsWithin hx) theorem Filter.HasBasis.exists_inter_eq_singleton_of_mem_discrete {ι : Type*} {p : ι → Prop} {t : ι → Set X} {s : Set X} [DiscreteTopology s] {x : X} (hb : (𝓝 x).HasBasis p t) (hx : x ∈ s) : ∃ i, p i ∧ t i ∩ s = {x} := by rcases (nhdsWithin_hasBasis hb s).mem_iff.1 (singleton_mem_nhdsWithin_of_mem_discrete hx) with ⟨i, hi, hix⟩ exact ⟨i, hi, hix.antisymm <| singleton_subset_iff.2 ⟨mem_of_mem_nhds <| hb.mem_of_mem hi, hx⟩⟩ /-- A point `x` in a discrete subset `s` of a topological space admits a neighbourhood that only meets `s` at `x`. -/ theorem nhds_inter_eq_singleton_of_mem_discrete {s : Set X} [DiscreteTopology s] {x : X} (hx : x ∈ s) : ∃ U ∈ 𝓝 x, U ∩ s = {x} := by simpa using (𝓝 x).basis_sets.exists_inter_eq_singleton_of_mem_discrete hx /-- Let `x` be a point in a discrete subset `s` of a topological space, then there exists an open set that only meets `s` at `x`. -/ theorem isOpen_inter_eq_singleton_of_mem_discrete {s : Set X} [DiscreteTopology s] {x : X} (hx : x ∈ s) : ∃ U : Set X, IsOpen U ∧ U ∩ s = {x} := by obtain ⟨U, hU_nhds, hU_inter⟩ := nhds_inter_eq_singleton_of_mem_discrete hx obtain ⟨t, ht_sub, ht_open, ht_x⟩ := mem_nhds_iff.mp hU_nhds refine ⟨t, ht_open, Set.Subset.antisymm ?_ ?_⟩ · exact hU_inter ▸ Set.inter_subset_inter_left s ht_sub · rw [Set.subset_inter_iff, Set.singleton_subset_iff, Set.singleton_subset_iff] exact ⟨ht_x, hx⟩ /-- For point `x` in a discrete subset `s` of a topological space, there is a set `U` such that 1. `U` is a punctured neighborhood of `x` (ie. `U ∪ {x}` is a neighbourhood of `x`), 2. `U` is disjoint from `s`. -/ theorem disjoint_nhdsWithin_of_mem_discrete {s : Set X} [DiscreteTopology s] {x : X} (hx : x ∈ s) : ∃ U ∈ 𝓝[≠] x, Disjoint U s := let ⟨V, h, h'⟩ := nhds_inter_eq_singleton_of_mem_discrete hx ⟨{x}ᶜ ∩ V, inter_mem_nhdsWithin _ h, disjoint_iff_inter_eq_empty.mpr (by rw [inter_assoc, h', compl_inter_self])⟩ theorem closedEmbedding_update {ι : Type*} {β : ι → Type*} [DecidableEq ι] [(i : ι) → TopologicalSpace (β i)] (x : (i : ι) → β i) (i : ι) [(i : ι) → T1Space (β i)] : ClosedEmbedding (update x i) := by apply closedEmbedding_of_continuous_injective_closed · exact continuous_const.update i continuous_id · exact update_injective x i · intro s hs rw [update_image] apply isClosed_set_pi simp [forall_update_iff, hs, isClosed_singleton] /-! ### R₁ (preregular) spaces -/ section R1Space /-- A topological space is called a *preregular* (a.k.a. R₁) space, if any two topologically distinguishable points have disjoint neighbourhoods. -/ @[mk_iff r1Space_iff_specializes_or_disjoint_nhds] class R1Space (X : Type*) [TopologicalSpace X] : Prop where specializes_or_disjoint_nhds (x y : X) : Specializes x y ∨ Disjoint (𝓝 x) (𝓝 y) export R1Space (specializes_or_disjoint_nhds) variable [R1Space X] {x y : X} instance (priority := 100) : R0Space X where specializes_symmetric _ _ h := (specializes_or_disjoint_nhds _ _).resolve_right <| fun hd ↦ h.not_disjoint hd.symm theorem disjoint_nhds_nhds_iff_not_specializes : Disjoint (𝓝 x) (𝓝 y) ↔ ¬x ⤳ y := ⟨fun hd hspec ↦ hspec.not_disjoint hd, (specializes_or_disjoint_nhds _ _).resolve_left⟩ theorem specializes_iff_not_disjoint : x ⤳ y ↔ ¬Disjoint (𝓝 x) (𝓝 y) := disjoint_nhds_nhds_iff_not_specializes.not_left.symm theorem disjoint_nhds_nhds_iff_not_inseparable : Disjoint (𝓝 x) (𝓝 y) ↔ ¬Inseparable x y := by rw [disjoint_nhds_nhds_iff_not_specializes, specializes_iff_inseparable] theorem r1Space_iff_inseparable_or_disjoint_nhds {X : Type*} [TopologicalSpace X] : R1Space X ↔ ∀ x y : X, Inseparable x y ∨ Disjoint (𝓝 x) (𝓝 y) := ⟨fun _h x y ↦ (specializes_or_disjoint_nhds x y).imp_left Specializes.inseparable, fun h ↦ ⟨fun x y ↦ (h x y).imp_left Inseparable.specializes⟩⟩ theorem isClosed_setOf_specializes : IsClosed { p : X × X | p.1 ⤳ p.2 } := by simp only [← isOpen_compl_iff, compl_setOf, ← disjoint_nhds_nhds_iff_not_specializes, isOpen_setOf_disjoint_nhds_nhds] theorem isClosed_setOf_inseparable : IsClosed { p : X × X | Inseparable p.1 p.2 } := by simp only [← specializes_iff_inseparable, isClosed_setOf_specializes] /-- In an R₁ space, a point belongs to the closure of a compact set `K` if and only if it is topologically inseparable from some point of `K`. -/ theorem IsCompact.mem_closure_iff_exists_inseparable {K : Set X} (hK : IsCompact K) : y ∈ closure K ↔ ∃ x ∈ K, Inseparable x y := by refine ⟨fun hy ↦ ?_, fun ⟨x, hxK, hxy⟩ ↦ (hxy.mem_closed_iff isClosed_closure).1 <| subset_closure hxK⟩ contrapose! hy have : Disjoint (𝓝 y) (𝓝ˢ K) := hK.disjoint_nhdsSet_right.2 fun x hx ↦ (disjoint_nhds_nhds_iff_not_inseparable.2 (hy x hx)).symm simpa only [disjoint_iff, not_mem_closure_iff_nhdsWithin_eq_bot] using this.mono_right principal_le_nhdsSet theorem IsCompact.closure_eq_biUnion_inseparable {K : Set X} (hK : IsCompact K) : closure K = ⋃ x ∈ K, {y | Inseparable x y} := by ext; simp [hK.mem_closure_iff_exists_inseparable] /-- In an R₁ space, the closure of a compact set is the union of the closures of its points. -/ theorem IsCompact.closure_eq_biUnion_closure_singleton {K : Set X} (hK : IsCompact K) : closure K = ⋃ x ∈ K, closure {x} := by simp only [hK.closure_eq_biUnion_inseparable, ← specializes_iff_inseparable, specializes_iff_mem_closure, setOf_mem_eq] /-- In an R₁ space, if a compact set `K` is contained in an open set `U`, then its closure is also contained in `U`. -/ theorem IsCompact.closure_subset_of_isOpen {K : Set X} (hK : IsCompact K) {U : Set X} (hU : IsOpen U) (hKU : K ⊆ U) : closure K ⊆ U := by rw [hK.closure_eq_biUnion_inseparable, iUnion₂_subset_iff] exact fun x hx y hxy ↦ (hxy.mem_open_iff hU).1 (hKU hx) /-- The closure of a compact set in an R₁ space is a compact set. -/ protected theorem IsCompact.closure {K : Set X} (hK : IsCompact K) : IsCompact (closure K) := by refine isCompact_of_finite_subcover fun U hUo hKU ↦ ?_ rcases hK.elim_finite_subcover U hUo (subset_closure.trans hKU) with ⟨t, ht⟩ exact ⟨t, hK.closure_subset_of_isOpen (isOpen_biUnion fun _ _ ↦ hUo _) ht⟩ theorem IsCompact.closure_of_subset {s K : Set X} (hK : IsCompact K) (h : s ⊆ K) : IsCompact (closure s) := hK.closure.of_isClosed_subset isClosed_closure (closure_mono h) @[deprecated (since := "2024-01-28")] alias isCompact_closure_of_subset_compact := IsCompact.closure_of_subset @[simp] theorem exists_isCompact_superset_iff {s : Set X} : (∃ K, IsCompact K ∧ s ⊆ K) ↔ IsCompact (closure s) := ⟨fun ⟨_K, hK, hsK⟩ => hK.closure_of_subset hsK, fun h => ⟨closure s, h, subset_closure⟩⟩ @[deprecated (since := "2024-01-28")] alias exists_compact_superset_iff := exists_isCompact_superset_iff /-- If `K` and `L` are disjoint compact sets in an R₁ topological space and `L` is also closed, then `K` and `L` have disjoint neighborhoods. -/ theorem SeparatedNhds.of_isCompact_isCompact_isClosed {K L : Set X} (hK : IsCompact K) (hL : IsCompact L) (h'L : IsClosed L) (hd : Disjoint K L) : SeparatedNhds K L := by simp_rw [separatedNhds_iff_disjoint, hK.disjoint_nhdsSet_left, hL.disjoint_nhdsSet_right, disjoint_nhds_nhds_iff_not_inseparable] intro x hx y hy h exact absurd ((h.mem_closed_iff h'L).2 hy) <| disjoint_left.1 hd hx @[deprecated (since := "2024-01-28")] alias separatedNhds_of_isCompact_isCompact_isClosed := SeparatedNhds.of_isCompact_isCompact_isClosed /-- If a compact set is covered by two open sets, then we can cover it by two compact subsets. -/ theorem IsCompact.binary_compact_cover {K U V : Set X} (hK : IsCompact K) (hU : IsOpen U) (hV : IsOpen V) (h2K : K ⊆ U ∪ V) : ∃ K₁ K₂ : Set X, IsCompact K₁ ∧ IsCompact K₂ ∧ K₁ ⊆ U ∧ K₂ ⊆ V ∧ K = K₁ ∪ K₂ := by have hK' : IsCompact (closure K) := hK.closure have : SeparatedNhds (closure K \ U) (closure K \ V) := by apply SeparatedNhds.of_isCompact_isCompact_isClosed (hK'.diff hU) (hK'.diff hV) (isClosed_closure.sdiff hV) rw [disjoint_iff_inter_eq_empty, diff_inter_diff, diff_eq_empty] exact hK.closure_subset_of_isOpen (hU.union hV) h2K have : SeparatedNhds (K \ U) (K \ V) := this.mono (diff_subset_diff_left (subset_closure)) (diff_subset_diff_left (subset_closure)) rcases this with ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩ exact ⟨K \ O₁, K \ O₂, hK.diff h1O₁, hK.diff h1O₂, diff_subset_comm.mp h2O₁, diff_subset_comm.mp h2O₂, by rw [← diff_inter, hO.inter_eq, diff_empty]⟩ /-- For every finite open cover `Uᵢ` of a compact set, there exists a compact cover `Kᵢ ⊆ Uᵢ`. -/ theorem IsCompact.finite_compact_cover {s : Set X} (hs : IsCompact s) {ι : Type*} (t : Finset ι) (U : ι → Set X) (hU : ∀ i ∈ t, IsOpen (U i)) (hsC : s ⊆ ⋃ i ∈ t, U i) : ∃ K : ι → Set X, (∀ i, IsCompact (K i)) ∧ (∀ i, K i ⊆ U i) ∧ s = ⋃ i ∈ t, K i := by classical induction' t using Finset.induction with x t hx ih generalizing U s · refine ⟨fun _ => ∅, fun _ => isCompact_empty, fun i => empty_subset _, ?_⟩ simpa only [subset_empty_iff, Finset.not_mem_empty, iUnion_false, iUnion_empty] using hsC simp only [Finset.set_biUnion_insert] at hsC simp only [Finset.forall_mem_insert] at hU have hU' : ∀ i ∈ t, IsOpen (U i) := fun i hi => hU.2 i hi rcases hs.binary_compact_cover hU.1 (isOpen_biUnion hU') hsC with ⟨K₁, K₂, h1K₁, h1K₂, h2K₁, h2K₂, hK⟩ rcases ih h1K₂ U hU' h2K₂ with ⟨K, h1K, h2K, h3K⟩ refine ⟨update K x K₁, ?_, ?_, ?_⟩ · intro i rcases eq_or_ne i x with rfl | hi · simp only [update_same, h1K₁] · simp only [update_noteq hi, h1K] · intro i rcases eq_or_ne i x with rfl | hi · simp only [update_same, h2K₁] · simp only [update_noteq hi, h2K] · simp only [Finset.set_biUnion_insert_update _ hx, hK, h3K] theorem R1Space.of_continuous_specializes_imp [TopologicalSpace Y] {f : Y → X} (hc : Continuous f) (hspec : ∀ x y, f x ⤳ f y → x ⤳ y) : R1Space Y where specializes_or_disjoint_nhds x y := (specializes_or_disjoint_nhds (f x) (f y)).imp (hspec x y) <| ((hc.tendsto _).disjoint · (hc.tendsto _)) theorem Inducing.r1Space [TopologicalSpace Y] {f : Y → X} (hf : Inducing f) : R1Space Y := .of_continuous_specializes_imp hf.continuous fun _ _ ↦ hf.specializes_iff.1 protected theorem R1Space.induced (f : Y → X) : @R1Space Y (.induced f ‹_›) := @Inducing.r1Space _ _ _ _ (.induced f _) f (inducing_induced f) instance (p : X → Prop) : R1Space (Subtype p) := .induced _ protected theorem R1Space.sInf {X : Type*} {T : Set (TopologicalSpace X)} (hT : ∀ t ∈ T, @R1Space X t) : @R1Space X (sInf T) := by let _ := sInf T refine ⟨fun x y ↦ ?_⟩ simp only [Specializes, nhds_sInf] rcases em (∃ t ∈ T, Disjoint (@nhds X t x) (@nhds X t y)) with ⟨t, htT, htd⟩ | hTd · exact .inr <| htd.mono (iInf₂_le t htT) (iInf₂_le t htT) · push_neg at hTd exact .inl <| iInf₂_mono fun t ht ↦ ((hT t ht).1 x y).resolve_right (hTd t ht) protected theorem R1Space.iInf {ι X : Type*} {t : ι → TopologicalSpace X} (ht : ∀ i, @R1Space X (t i)) : @R1Space X (iInf t) := .sInf <| forall_mem_range.2 ht protected theorem R1Space.inf {X : Type*} {t₁ t₂ : TopologicalSpace X} (h₁ : @R1Space X t₁) (h₂ : @R1Space X t₂) : @R1Space X (t₁ ⊓ t₂) := by rw [inf_eq_iInf] apply R1Space.iInf simp [*] instance [TopologicalSpace Y] [R1Space Y] : R1Space (X × Y) := .inf (.induced _) (.induced _) instance {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, R1Space (X i)] : R1Space (∀ i, X i) := .iInf fun _ ↦ .induced _ theorem exists_mem_nhds_isCompact_mapsTo_of_isCompact_mem_nhds {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [R1Space Y] {f : X → Y} {x : X} {K : Set X} {s : Set Y} (hf : Continuous f) (hs : s ∈ 𝓝 (f x)) (hKc : IsCompact K) (hKx : K ∈ 𝓝 x) : ∃ K ∈ 𝓝 x, IsCompact K ∧ MapsTo f K s := by have hc : IsCompact (f '' K \ interior s) := (hKc.image hf).diff isOpen_interior obtain ⟨U, V, Uo, Vo, hxU, hV, hd⟩ : SeparatedNhds {f x} (f '' K \ interior s) := by simp_rw [separatedNhds_iff_disjoint, nhdsSet_singleton, hc.disjoint_nhdsSet_right, disjoint_nhds_nhds_iff_not_inseparable] rintro y ⟨-, hys⟩ hxy refine hys <| (hxy.mem_open_iff isOpen_interior).1 ?_ rwa [mem_interior_iff_mem_nhds] refine ⟨K \ f ⁻¹' V, diff_mem hKx ?_, hKc.diff <| Vo.preimage hf, fun y hy ↦ ?_⟩ · filter_upwards [hf.continuousAt <| Uo.mem_nhds (hxU rfl)] with x hx using Set.disjoint_left.1 hd hx · by_contra hys exact hy.2 (hV ⟨mem_image_of_mem _ hy.1, not_mem_subset interior_subset hys⟩) instance (priority := 900) {X Y : Type*} [TopologicalSpace X] [WeaklyLocallyCompactSpace X] [TopologicalSpace Y] [R1Space Y] : LocallyCompactPair X Y where exists_mem_nhds_isCompact_mapsTo hf hs := let ⟨_K, hKc, hKx⟩ := exists_compact_mem_nhds _ exists_mem_nhds_isCompact_mapsTo_of_isCompact_mem_nhds hf hs hKc hKx /-- If a point in an R₁ space has a compact neighborhood, then it has a basis of compact closed neighborhoods. -/ theorem IsCompact.isCompact_isClosed_basis_nhds {x : X} {L : Set X} (hLc : IsCompact L) (hxL : L ∈ 𝓝 x) : (𝓝 x).HasBasis (fun K ↦ K ∈ 𝓝 x ∧ IsCompact K ∧ IsClosed K) (·) := hasBasis_self.2 fun _U hU ↦ let ⟨K, hKx, hKc, hKU⟩ := exists_mem_nhds_isCompact_mapsTo_of_isCompact_mem_nhds continuous_id (interior_mem_nhds.2 hU) hLc hxL ⟨closure K, mem_of_superset hKx subset_closure, ⟨hKc.closure, isClosed_closure⟩, (hKc.closure_subset_of_isOpen isOpen_interior hKU).trans interior_subset⟩ /-- In an R₁ space, the filters `coclosedCompact` and `cocompact` are equal. -/ @[simp] theorem Filter.coclosedCompact_eq_cocompact : coclosedCompact X = cocompact X := by refine le_antisymm ?_ cocompact_le_coclosedCompact rw [hasBasis_coclosedCompact.le_basis_iff hasBasis_cocompact] exact fun K hK ↦ ⟨closure K, ⟨isClosed_closure, hK.closure⟩, compl_subset_compl.2 subset_closure⟩ /-- In an R₁ space, the bornologies `relativelyCompact` and `inCompact` are equal. -/ @[simp] theorem Bornology.relativelyCompact_eq_inCompact : Bornology.relativelyCompact X = Bornology.inCompact X := Bornology.ext _ _ Filter.coclosedCompact_eq_cocompact /-! ### Lemmas about a weakly locally compact R₁ space In fact, a space with these properties is locally compact and regular. Some lemmas are formulated using the latter assumptions below. -/ variable [WeaklyLocallyCompactSpace X] /-- In a (weakly) locally compact R₁ space, compact closed neighborhoods of a point `x` form a basis of neighborhoods of `x`. -/ theorem isCompact_isClosed_basis_nhds (x : X) : (𝓝 x).HasBasis (fun K => K ∈ 𝓝 x ∧ IsCompact K ∧ IsClosed K) (·) := let ⟨_L, hLc, hLx⟩ := exists_compact_mem_nhds x hLc.isCompact_isClosed_basis_nhds hLx /-- In a (weakly) locally compact R₁ space, each point admits a compact closed neighborhood. -/ theorem exists_mem_nhds_isCompact_isClosed (x : X) : ∃ K ∈ 𝓝 x, IsCompact K ∧ IsClosed K := (isCompact_isClosed_basis_nhds x).ex_mem -- see Note [lower instance priority] /-- A weakly locally compact R₁ space is locally compact. -/ instance (priority := 80) WeaklyLocallyCompactSpace.locallyCompactSpace : LocallyCompactSpace X := .of_hasBasis isCompact_isClosed_basis_nhds fun _ _ ⟨_, h, _⟩ ↦ h /-- In a weakly locally compact R₁ space, every compact set has an open neighborhood with compact closure. -/ theorem exists_isOpen_superset_and_isCompact_closure {K : Set X} (hK : IsCompact K) : ∃ V, IsOpen V ∧ K ⊆ V ∧ IsCompact (closure V) := by rcases exists_compact_superset hK with ⟨K', hK', hKK'⟩ exact ⟨interior K', isOpen_interior, hKK', hK'.closure_of_subset interior_subset⟩ @[deprecated (since := "2024-01-28")] alias exists_open_superset_and_isCompact_closure := exists_isOpen_superset_and_isCompact_closure /-- In a weakly locally compact R₁ space, every point has an open neighborhood with compact closure. -/ theorem exists_isOpen_mem_isCompact_closure (x : X) : ∃ U : Set X, IsOpen U ∧ x ∈ U ∧ IsCompact (closure U) := by simpa only [singleton_subset_iff] using exists_isOpen_superset_and_isCompact_closure isCompact_singleton @[deprecated (since := "2024-01-28")] alias exists_open_with_compact_closure := exists_isOpen_mem_isCompact_closure end R1Space /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ @[mk_iff] class T2Space (X : Type u) [TopologicalSpace X] : Prop where /-- Every two points in a Hausdorff space admit disjoint open neighbourhoods. -/ t2 : Pairwise fun x y => ∃ u v : Set X, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v /-- Two different points can be separated by open sets. -/ theorem t2_separation [T2Space X] {x y : X} (h : x ≠ y) : ∃ u v : Set X, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v := T2Space.t2 h -- todo: use this as a definition? theorem t2Space_iff_disjoint_nhds : T2Space X ↔ Pairwise fun x y : X => Disjoint (𝓝 x) (𝓝 y) := by refine (t2Space_iff X).trans (forall₃_congr fun x y _ => ?_) simp only [(nhds_basis_opens x).disjoint_iff (nhds_basis_opens y), exists_prop, ← exists_and_left, and_assoc, and_comm, and_left_comm] @[simp] theorem disjoint_nhds_nhds [T2Space X] {x y : X} : Disjoint (𝓝 x) (𝓝 y) ↔ x ≠ y := ⟨fun hd he => by simp [he, nhds_neBot.ne] at hd, (t2Space_iff_disjoint_nhds.mp ‹_› ·)⟩ theorem pairwise_disjoint_nhds [T2Space X] : Pairwise (Disjoint on (𝓝 : X → Filter X)) := fun _ _ => disjoint_nhds_nhds.2 protected theorem Set.pairwiseDisjoint_nhds [T2Space X] (s : Set X) : s.PairwiseDisjoint 𝓝 := pairwise_disjoint_nhds.set_pairwise s /-- Points of a finite set can be separated by open sets from each other. -/ theorem Set.Finite.t2_separation [T2Space X] {s : Set X} (hs : s.Finite) : ∃ U : X → Set X, (∀ x, x ∈ U x ∧ IsOpen (U x)) ∧ s.PairwiseDisjoint U := s.pairwiseDisjoint_nhds.exists_mem_filter_basis hs nhds_basis_opens -- see Note [lower instance priority] instance (priority := 100) T2Space.t1Space [T2Space X] : T1Space X := t1Space_iff_disjoint_pure_nhds.mpr fun _ _ hne => (disjoint_nhds_nhds.2 hne).mono_left <| pure_le_nhds _ -- see Note [lower instance priority] instance (priority := 100) T2Space.r1Space [T2Space X] : R1Space X := ⟨fun x y ↦ (eq_or_ne x y).imp specializes_of_eq disjoint_nhds_nhds.2⟩ theorem SeparationQuotient.t2Space_iff : T2Space (SeparationQuotient X) ↔ R1Space X := by simp only [t2Space_iff_disjoint_nhds, Pairwise, surjective_mk.forall₂, ne_eq, mk_eq_mk, r1Space_iff_inseparable_or_disjoint_nhds, ← disjoint_comap_iff surjective_mk, comap_mk_nhds_mk, ← or_iff_not_imp_left] instance SeparationQuotient.t2Space [R1Space X] : T2Space (SeparationQuotient X) := t2Space_iff.2 ‹_› instance (priority := 80) [R1Space X] [T0Space X] : T2Space X := t2Space_iff_disjoint_nhds.2 fun _x _y hne ↦ disjoint_nhds_nhds_iff_not_inseparable.2 fun hxy ↦ hne hxy.eq theorem R1Space.t2Space_iff_t0Space [R1Space X] : T2Space X ↔ T0Space X := by constructor <;> intro <;> infer_instance /-- A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. -/ theorem t2_iff_nhds : T2Space X ↔ ∀ {x y : X}, NeBot (𝓝 x ⊓ 𝓝 y) → x = y := by simp only [t2Space_iff_disjoint_nhds, disjoint_iff, neBot_iff, Ne, not_imp_comm, Pairwise] theorem eq_of_nhds_neBot [T2Space X] {x y : X} (h : NeBot (𝓝 x ⊓ 𝓝 y)) : x = y := t2_iff_nhds.mp ‹_› h theorem t2Space_iff_nhds : T2Space X ↔ Pairwise fun x y : X => ∃ U ∈ 𝓝 x, ∃ V ∈ 𝓝 y, Disjoint U V := by simp only [t2Space_iff_disjoint_nhds, Filter.disjoint_iff, Pairwise] theorem t2_separation_nhds [T2Space X] {x y : X} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ Disjoint u v := let ⟨u, v, open_u, open_v, x_in, y_in, huv⟩ := t2_separation h ⟨u, v, open_u.mem_nhds x_in, open_v.mem_nhds y_in, huv⟩ theorem t2_separation_compact_nhds [LocallyCompactSpace X] [T2Space X] {x y : X} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ IsCompact u ∧ IsCompact v ∧ Disjoint u v := by simpa only [exists_prop, ← exists_and_left, and_comm, and_assoc, and_left_comm] using ((compact_basis_nhds x).disjoint_iff (compact_basis_nhds y)).1 (disjoint_nhds_nhds.2 h) theorem t2_iff_ultrafilter : T2Space X ↔ ∀ {x y : X} (f : Ultrafilter X), ↑f ≤ 𝓝 x → ↑f ≤ 𝓝 y → x = y := t2_iff_nhds.trans <| by simp only [← exists_ultrafilter_iff, and_imp, le_inf_iff, exists_imp] theorem t2_iff_isClosed_diagonal : T2Space X ↔ IsClosed (diagonal X) := by simp only [t2Space_iff_disjoint_nhds, ← isOpen_compl_iff, isOpen_iff_mem_nhds, Prod.forall, nhds_prod_eq, compl_diagonal_mem_prod, mem_compl_iff, mem_diagonal_iff, Pairwise] theorem isClosed_diagonal [T2Space X] : IsClosed (diagonal X) := t2_iff_isClosed_diagonal.mp ‹_› -- Porting note: 2 lemmas moved below theorem tendsto_nhds_unique [T2Space X] {f : Y → X} {l : Filter Y} {a b : X} [NeBot l] (ha : Tendsto f l (𝓝 a)) (hb : Tendsto f l (𝓝 b)) : a = b := eq_of_nhds_neBot <| neBot_of_le <| le_inf ha hb theorem tendsto_nhds_unique' [T2Space X] {f : Y → X} {l : Filter Y} {a b : X} (_ : NeBot l) (ha : Tendsto f l (𝓝 a)) (hb : Tendsto f l (𝓝 b)) : a = b := eq_of_nhds_neBot <| neBot_of_le <| le_inf ha hb theorem tendsto_nhds_unique_of_eventuallyEq [T2Space X] {f g : Y → X} {l : Filter Y} {a b : X} [NeBot l] (ha : Tendsto f l (𝓝 a)) (hb : Tendsto g l (𝓝 b)) (hfg : f =ᶠ[l] g) : a = b := tendsto_nhds_unique (ha.congr' hfg) hb theorem tendsto_nhds_unique_of_frequently_eq [T2Space X] {f g : Y → X} {l : Filter Y} {a b : X} (ha : Tendsto f l (𝓝 a)) (hb : Tendsto g l (𝓝 b)) (hfg : ∃ᶠ x in l, f x = g x) : a = b := have : ∃ᶠ z : X × X in 𝓝 (a, b), z.1 = z.2 := (ha.prod_mk_nhds hb).frequently hfg not_not.1 fun hne => this (isClosed_diagonal.isOpen_compl.mem_nhds hne) /-- If `s` and `t` are compact sets in a T₂ space, then the set neighborhoods filter of `s ∩ t` is the infimum of set neighborhoods filters for `s` and `t`. For general sets, only the `≤` inequality holds, see `nhdsSet_inter_le`. -/ theorem IsCompact.nhdsSet_inter_eq [T2Space X] {s t : Set X} (hs : IsCompact s) (ht : IsCompact t) : 𝓝ˢ (s ∩ t) = 𝓝ˢ s ⊓ 𝓝ˢ t := by refine le_antisymm (nhdsSet_inter_le _ _) ?_ simp_rw [hs.nhdsSet_inf_eq_biSup, ht.inf_nhdsSet_eq_biSup, nhdsSet, sSup_image] refine iSup₂_le fun x hxs ↦ iSup₂_le fun y hyt ↦ ?_ rcases eq_or_ne x y with (rfl|hne) · exact le_iSup₂_of_le x ⟨hxs, hyt⟩ (inf_idem _).le · exact (disjoint_nhds_nhds.mpr hne).eq_bot ▸ bot_le /-- If a function `f` is - injective on a compact set `s`; - continuous at every point of this set; - injective on a neighborhood of each point of this set, then it is injective on a neighborhood of this set. -/ theorem Set.InjOn.exists_mem_nhdsSet {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y] {f : X → Y} {s : Set X} (inj : InjOn f s) (sc : IsCompact s) (fc : ∀ x ∈ s, ContinuousAt f x) (loc : ∀ x ∈ s, ∃ u ∈ 𝓝 x, InjOn f u) : ∃ t ∈ 𝓝ˢ s, InjOn f t := by have : ∀ x ∈ s ×ˢ s, ∀ᶠ y in 𝓝 x, f y.1 = f y.2 → y.1 = y.2 := fun (x, y) ⟨hx, hy⟩ ↦ by rcases eq_or_ne x y with rfl | hne · rcases loc x hx with ⟨u, hu, hf⟩ exact Filter.mem_of_superset (prod_mem_nhds hu hu) <| forall_prod_set.2 hf · suffices ∀ᶠ z in 𝓝 (x, y), f z.1 ≠ f z.2 from this.mono fun _ hne h ↦ absurd h hne refine (fc x hx).prod_map' (fc y hy) <| isClosed_diagonal.isOpen_compl.mem_nhds ?_ exact inj.ne hx hy hne rw [← eventually_nhdsSet_iff_forall, sc.nhdsSet_prod_eq sc] at this exact eventually_prod_self_iff.1 this /-- If a function `f` is - injective on a compact set `s`; - continuous at every point of this set; - injective on a neighborhood of each point of this set, then it is injective on an open neighborhood of this set. -/ theorem Set.InjOn.exists_isOpen_superset {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y] {f : X → Y} {s : Set X} (inj : InjOn f s) (sc : IsCompact s) (fc : ∀ x ∈ s, ContinuousAt f x) (loc : ∀ x ∈ s, ∃ u ∈ 𝓝 x, InjOn f u) : ∃ t, IsOpen t ∧ s ⊆ t ∧ InjOn f t := let ⟨_t, hst, ht⟩ := inj.exists_mem_nhdsSet sc fc loc let ⟨u, huo, hsu, hut⟩ := mem_nhdsSet_iff_exists.1 hst ⟨u, huo, hsu, ht.mono hut⟩ section limUnder variable [T2Space X] {f : Filter X} /-! ### Properties of `lim` and `limUnder` In this section we use explicit `Nonempty X` instances for `lim` and `limUnder`. This way the lemmas are useful without a `Nonempty X` instance. -/ theorem lim_eq {x : X} [NeBot f] (h : f ≤ 𝓝 x) : @lim _ _ ⟨x⟩ f = x := tendsto_nhds_unique (le_nhds_lim ⟨x, h⟩) h theorem lim_eq_iff [NeBot f] (h : ∃ x : X, f ≤ 𝓝 x) {x} : @lim _ _ ⟨x⟩ f = x ↔ f ≤ 𝓝 x := ⟨fun c => c ▸ le_nhds_lim h, lim_eq⟩ theorem Ultrafilter.lim_eq_iff_le_nhds [CompactSpace X] {x : X} {F : Ultrafilter X} : F.lim = x ↔ ↑F ≤ 𝓝 x := ⟨fun h => h ▸ F.le_nhds_lim, lim_eq⟩ theorem isOpen_iff_ultrafilter' [CompactSpace X] (U : Set X) : IsOpen U ↔ ∀ F : Ultrafilter X, F.lim ∈ U → U ∈ F.1 := by rw [isOpen_iff_ultrafilter] refine ⟨fun h F hF => h F.lim hF F F.le_nhds_lim, ?_⟩ intro cond x hx f h rw [← Ultrafilter.lim_eq_iff_le_nhds.2 h] at hx exact cond _ hx theorem Filter.Tendsto.limUnder_eq {x : X} {f : Filter Y} [NeBot f] {g : Y → X} (h : Tendsto g f (𝓝 x)) : @limUnder _ _ _ ⟨x⟩ f g = x := lim_eq h theorem Filter.limUnder_eq_iff {f : Filter Y} [NeBot f] {g : Y → X} (h : ∃ x, Tendsto g f (𝓝 x)) {x} : @limUnder _ _ _ ⟨x⟩ f g = x ↔ Tendsto g f (𝓝 x) := ⟨fun c => c ▸ tendsto_nhds_limUnder h, Filter.Tendsto.limUnder_eq⟩ theorem Continuous.limUnder_eq [TopologicalSpace Y] {f : Y → X} (h : Continuous f) (y : Y) : @limUnder _ _ _ ⟨f y⟩ (𝓝 y) f = f y := (h.tendsto y).limUnder_eq @[simp] theorem lim_nhds (x : X) : @lim _ _ ⟨x⟩ (𝓝 x) = x := lim_eq le_rfl @[simp] theorem limUnder_nhds_id (x : X) : @limUnder _ _ _ ⟨x⟩ (𝓝 x) id = x := lim_nhds x @[simp] theorem lim_nhdsWithin {x : X} {s : Set X} (h : x ∈ closure s) : @lim _ _ ⟨x⟩ (𝓝[s] x) = x := haveI : NeBot (𝓝[s] x) := mem_closure_iff_clusterPt.1 h lim_eq inf_le_left @[simp] theorem limUnder_nhdsWithin_id {x : X} {s : Set X} (h : x ∈ closure s) : @limUnder _ _ _ ⟨x⟩ (𝓝[s] x) id = x := lim_nhdsWithin h end limUnder /-! ### `T2Space` constructions We use two lemmas to prove that various standard constructions generate Hausdorff spaces from Hausdorff spaces: * `separated_by_continuous` says that two points `x y : X` can be separated by open neighborhoods provided that there exists a continuous map `f : X → Y` with a Hausdorff codomain such that `f x ≠ f y`. We use this lemma to prove that topological spaces defined using `induced` are Hausdorff spaces. * `separated_by_openEmbedding` says that for an open embedding `f : X → Y` of a Hausdorff space `X`, the images of two distinct points `x y : X`, `x ≠ y` can be separated by open neighborhoods. We use this lemma to prove that topological spaces defined using `coinduced` are Hausdorff spaces. -/ -- see Note [lower instance priority] instance (priority := 100) DiscreteTopology.toT2Space [DiscreteTopology X] : T2Space X := ⟨fun x y h => ⟨{x}, {y}, isOpen_discrete _, isOpen_discrete _, rfl, rfl, disjoint_singleton.2 h⟩⟩ theorem separated_by_continuous [TopologicalSpace Y] [T2Space Y] {f : X → Y} (hf : Continuous f) {x y : X} (h : f x ≠ f y) : ∃ u v : Set X, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h ⟨f ⁻¹' u, f ⁻¹' v, uo.preimage hf, vo.preimage hf, xu, yv, uv.preimage _⟩ theorem separated_by_openEmbedding [TopologicalSpace Y] [T2Space X] {f : X → Y} (hf : OpenEmbedding f) {x y : X} (h : x ≠ y) : ∃ u v : Set Y, IsOpen u ∧ IsOpen v ∧ f x ∈ u ∧ f y ∈ v ∧ Disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h ⟨f '' u, f '' v, hf.isOpenMap _ uo, hf.isOpenMap _ vo, mem_image_of_mem _ xu, mem_image_of_mem _ yv, disjoint_image_of_injective hf.inj uv⟩ instance {p : X → Prop} [T2Space X] : T2Space (Subtype p) := inferInstance instance Prod.t2Space [T2Space X] [TopologicalSpace Y] [T2Space Y] : T2Space (X × Y) := inferInstance /-- If the codomain of an injective continuous function is a Hausdorff space, then so is its domain. -/ theorem T2Space.of_injective_continuous [TopologicalSpace Y] [T2Space Y] {f : X → Y} (hinj : Injective f) (hc : Continuous f) : T2Space X := ⟨fun _ _ h => separated_by_continuous hc (hinj.ne h)⟩ /-- If the codomain of a topological embedding is a Hausdorff space, then so is its domain. See also `T2Space.of_continuous_injective`. -/ theorem Embedding.t2Space [TopologicalSpace Y] [T2Space Y] {f : X → Y} (hf : Embedding f) : T2Space X := .of_injective_continuous hf.inj hf.continuous instance ULift.instT2Space [T2Space X] : T2Space (ULift X) := embedding_uLift_down.t2Space instance [T2Space X] [TopologicalSpace Y] [T2Space Y] : T2Space (X ⊕ Y) := by constructor rintro (x | x) (y | y) h · exact separated_by_openEmbedding openEmbedding_inl <| ne_of_apply_ne _ h · exact separated_by_continuous continuous_isLeft <| by simp · exact separated_by_continuous continuous_isLeft <| by simp · exact separated_by_openEmbedding openEmbedding_inr <| ne_of_apply_ne _ h instance Pi.t2Space {Y : X → Type v} [∀ a, TopologicalSpace (Y a)] [∀ a, T2Space (Y a)] : T2Space (∀ a, Y a) := inferInstance instance Sigma.t2Space {ι} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ a, T2Space (X a)] : T2Space (Σi, X i) := by constructor rintro ⟨i, x⟩ ⟨j, y⟩ neq rcases eq_or_ne i j with (rfl | h) · replace neq : x ≠ y := ne_of_apply_ne _ neq exact separated_by_openEmbedding openEmbedding_sigmaMk neq · let _ := (⊥ : TopologicalSpace ι); have : DiscreteTopology ι := ⟨rfl⟩ exact separated_by_continuous (continuous_def.2 fun u _ => isOpen_sigma_fst_preimage u) h section variable (X) /-- The smallest equivalence relation on a topological space giving a T2 quotient. -/ def t2Setoid : Setoid X := sInf {s | T2Space (Quotient s)} /-- The largest T2 quotient of a topological space. This construction is left-adjoint to the inclusion of T2 spaces into all topological spaces. -/ def t2Quotient := Quotient (t2Setoid X) namespace t2Quotient variable {X} instance : TopologicalSpace (t2Quotient X) := inferInstanceAs <| TopologicalSpace (Quotient _) /-- The map from a topological space to its largest T2 quotient. -/ def mk : X → t2Quotient X := Quotient.mk (t2Setoid X) lemma mk_eq {x y : X} : mk x = mk y ↔ ∀ s : Setoid X, T2Space (Quotient s) → s.Rel x y := Setoid.quotient_mk_sInf_eq variable (X) lemma surjective_mk : Surjective (mk : X → t2Quotient X) := surjective_quotient_mk _ lemma continuous_mk : Continuous (mk : X → t2Quotient X) := continuous_quotient_mk' variable {X} @[elab_as_elim] protected lemma inductionOn {motive : t2Quotient X → Prop} (q : t2Quotient X) (h : ∀ x, motive (t2Quotient.mk x)) : motive q := Quotient.inductionOn q h @[elab_as_elim] protected lemma inductionOn₂ [TopologicalSpace Y] {motive : t2Quotient X → t2Quotient Y → Prop} (q : t2Quotient X) (q' : t2Quotient Y) (h : ∀ x y, motive (mk x) (mk y)) : motive q q' := Quotient.inductionOn₂ q q' h /-- The largest T2 quotient of a topological space is indeed T2. -/ instance : T2Space (t2Quotient X) := by rw [t2Space_iff] rintro ⟨x⟩ ⟨y⟩ (h : ¬ t2Quotient.mk x = t2Quotient.mk y) obtain ⟨s, hs, hsxy⟩ : ∃ s, T2Space (Quotient s) ∧ Quotient.mk s x ≠ Quotient.mk s y := by simpa [t2Quotient.mk_eq] using h exact separated_by_continuous (continuous_map_sInf (by exact hs)) hsxy lemma compatible {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y] {f : X → Y} (hf : Continuous f) : letI _ := t2Setoid X ∀ (a b : X), a ≈ b → f a = f b := by change t2Setoid X ≤ Setoid.ker f exact sInf_le <| .of_injective_continuous (Setoid.ker_lift_injective _) (hf.quotient_lift fun _ _ ↦ id) /-- The universal property of the largest T2 quotient of a topological space `X`: any continuous map from `X` to a T2 space `Y` uniquely factors through `t2Quotient X`. This declaration builds the factored map. Its continuity is `t2Quotient.continuous_lift`, the fact that it indeed factors the original map is `t2Quotient.lift_mk` and uniquenes is `t2Quotient.unique_lift`. -/ def lift {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y] {f : X → Y} (hf : Continuous f) : t2Quotient X → Y := Quotient.lift f (t2Quotient.compatible hf) lemma continuous_lift {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y] {f : X → Y} (hf : Continuous f) : Continuous (t2Quotient.lift hf) := continuous_coinduced_dom.mpr hf @[simp] lemma lift_mk {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y] {f : X → Y} (hf : Continuous f) (x : X) : lift hf (mk x) = f x := Quotient.lift_mk (s := t2Setoid X) f (t2Quotient.compatible hf) x lemma unique_lift {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y] {f : X → Y} (hf : Continuous f) {g : t2Quotient X → Y} (hfg : g ∘ mk = f) : g = lift hf := by apply surjective_mk X |>.right_cancellable |>.mp <| funext _ simp [← hfg] end t2Quotient end variable {Z : Type*} [TopologicalSpace Y] [TopologicalSpace Z] theorem isClosed_eq [T2Space X] {f g : Y → X} (hf : Continuous f) (hg : Continuous g) : IsClosed { y : Y | f y = g y } := continuous_iff_isClosed.mp (hf.prod_mk hg) _ isClosed_diagonal /-- If functions `f` and `g` are continuous on a closed set `s`, then the set of points `x ∈ s` such that `f x = g x` is a closed set. -/ protected theorem IsClosed.isClosed_eq [T2Space Y] {f g : X → Y} {s : Set X} (hs : IsClosed s) (hf : ContinuousOn f s) (hg : ContinuousOn g s) : IsClosed {x ∈ s | f x = g x} := (hf.prod hg).preimage_isClosed_of_isClosed hs isClosed_diagonal theorem isOpen_ne_fun [T2Space X] {f g : Y → X} (hf : Continuous f) (hg : Continuous g) : IsOpen { y : Y | f y ≠ g y } := isOpen_compl_iff.mpr <| isClosed_eq hf hg /-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. See also `Set.EqOn.of_subset_closure` for a more general version. -/ protected theorem Set.EqOn.closure [T2Space X] {s : Set Y} {f g : Y → X} (h : EqOn f g s) (hf : Continuous f) (hg : Continuous g) : EqOn f g (closure s) := closure_minimal h (isClosed_eq hf hg) /-- If two continuous functions are equal on a dense set, then they are equal. -/ theorem Continuous.ext_on [T2Space X] {s : Set Y} (hs : Dense s) {f g : Y → X} (hf : Continuous f) (hg : Continuous g) (h : EqOn f g s) : f = g := funext fun x => h.closure hf hg (hs x) theorem eqOn_closure₂' [T2Space Z] {s : Set X} {t : Set Y} {f g : X → Y → Z} (h : ∀ x ∈ s, ∀ y ∈ t, f x y = g x y) (hf₁ : ∀ x, Continuous (f x)) (hf₂ : ∀ y, Continuous fun x => f x y) (hg₁ : ∀ x, Continuous (g x)) (hg₂ : ∀ y, Continuous fun x => g x y) : ∀ x ∈ closure s, ∀ y ∈ closure t, f x y = g x y := suffices closure s ⊆ ⋂ y ∈ closure t, { x | f x y = g x y } by simpa only [subset_def, mem_iInter] (closure_minimal fun x hx => mem_iInter₂.2 <| Set.EqOn.closure (h x hx) (hf₁ _) (hg₁ _)) <| isClosed_biInter fun y _ => isClosed_eq (hf₂ _) (hg₂ _) theorem eqOn_closure₂ [T2Space Z] {s : Set X} {t : Set Y} {f g : X → Y → Z} (h : ∀ x ∈ s, ∀ y ∈ t, f x y = g x y) (hf : Continuous (uncurry f)) (hg : Continuous (uncurry g)) : ∀ x ∈ closure s, ∀ y ∈ closure t, f x y = g x y := eqOn_closure₂' h hf.uncurry_left hf.uncurry_right hg.uncurry_left hg.uncurry_right /-- If `f x = g x` for all `x ∈ s` and `f`, `g` are continuous on `t`, `s ⊆ t ⊆ closure s`, then `f x = g x` for all `x ∈ t`. See also `Set.EqOn.closure`. -/ theorem Set.EqOn.of_subset_closure [T2Space Y] {s t : Set X} {f g : X → Y} (h : EqOn f g s) (hf : ContinuousOn f t) (hg : ContinuousOn g t) (hst : s ⊆ t) (hts : t ⊆ closure s) : EqOn f g t := by intro x hx have : (𝓝[s] x).NeBot := mem_closure_iff_clusterPt.mp (hts hx) exact tendsto_nhds_unique_of_eventuallyEq ((hf x hx).mono_left <| nhdsWithin_mono _ hst) ((hg x hx).mono_left <| nhdsWithin_mono _ hst) (h.eventuallyEq_of_mem self_mem_nhdsWithin) theorem Function.LeftInverse.isClosed_range [T2Space X] {f : X → Y} {g : Y → X} (h : Function.LeftInverse f g) (hf : Continuous f) (hg : Continuous g) : IsClosed (range g) := have : EqOn (g ∘ f) id (closure <| range g) := h.rightInvOn_range.eqOn.closure (hg.comp hf) continuous_id isClosed_of_closure_subset fun x hx => ⟨f x, this hx⟩ @[deprecated (since := "2024-03-17")] alias Function.LeftInverse.closed_range := Function.LeftInverse.isClosed_range theorem Function.LeftInverse.closedEmbedding [T2Space X] {f : X → Y} {g : Y → X} (h : Function.LeftInverse f g) (hf : Continuous f) (hg : Continuous g) : ClosedEmbedding g := ⟨h.embedding hf hg, h.isClosed_range hf hg⟩ theorem SeparatedNhds.of_isCompact_isCompact [T2Space X] {s t : Set X} (hs : IsCompact s) (ht : IsCompact t) (hst : Disjoint s t) : SeparatedNhds s t := by simp only [SeparatedNhds, prod_subset_compl_diagonal_iff_disjoint.symm] at hst ⊢ exact generalized_tube_lemma hs ht isClosed_diagonal.isOpen_compl hst @[deprecated (since := "2024-01-28")] alias separatedNhds_of_isCompact_isCompact := SeparatedNhds.of_isCompact_isCompact section SeparatedFinset theorem SeparatedNhds.of_finset_finset [T2Space X] (s t : Finset X) (h : Disjoint s t) : SeparatedNhds (s : Set X) t := .of_isCompact_isCompact s.finite_toSet.isCompact t.finite_toSet.isCompact <| mod_cast h @[deprecated (since := "2024-01-28")] alias separatedNhds_of_finset_finset := SeparatedNhds.of_finset_finset theorem SeparatedNhds.of_singleton_finset [T2Space X] {x : X} {s : Finset X} (h : x ∉ s) : SeparatedNhds ({x} : Set X) s := mod_cast .of_finset_finset {x} s (Finset.disjoint_singleton_left.mpr h) @[deprecated (since := "2024-01-28")] alias point_disjoint_finset_opens_of_t2 := SeparatedNhds.of_singleton_finset end SeparatedFinset /-- In a `T2Space`, every compact set is closed. -/ theorem IsCompact.isClosed [T2Space X] {s : Set X} (hs : IsCompact s) : IsClosed s := isOpen_compl_iff.1 <| isOpen_iff_forall_mem_open.mpr fun x hx => let ⟨u, v, _, vo, su, xv, uv⟩ := SeparatedNhds.of_isCompact_isCompact hs isCompact_singleton (disjoint_singleton_right.2 hx) ⟨v, (uv.mono_left <| show s ≤ u from su).subset_compl_left, vo, by simpa using xv⟩ theorem IsCompact.preimage_continuous [CompactSpace X] [T2Space Y] {f : X → Y} {s : Set Y} (hs : IsCompact s) (hf : Continuous f) : IsCompact (f ⁻¹' s) := (hs.isClosed.preimage hf).isCompact lemma Pi.isCompact_iff {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] [∀ i, T2Space (π i)] {s : Set (Π i, π i)} : IsCompact s ↔ IsClosed s ∧ ∀ i, IsCompact (eval i '' s) := by constructor <;> intro H · exact ⟨H.isClosed, fun i ↦ H.image <| continuous_apply i⟩ · exact IsCompact.of_isClosed_subset (isCompact_univ_pi H.2) H.1 (subset_pi_eval_image univ s) lemma Pi.isCompact_closure_iff {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] [∀ i, T2Space (π i)] {s : Set (Π i, π i)} : IsCompact (closure s) ↔ ∀ i, IsCompact (closure <| eval i '' s) := by simp_rw [← exists_isCompact_superset_iff, Pi.exists_compact_superset_iff, image_subset_iff] /-- If `V : ι → Set X` is a decreasing family of compact sets then any neighborhood of `⋂ i, V i` contains some `V i`. This is a version of `exists_subset_nhds_of_isCompact'` where we don't need to assume each `V i` closed because it follows from compactness since `X` is assumed to be Hausdorff. -/ theorem exists_subset_nhds_of_isCompact [T2Space X] {ι : Type*} [Nonempty ι] {V : ι → Set X} (hV : Directed (· ⊇ ·) V) (hV_cpct : ∀ i, IsCompact (V i)) {U : Set X} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := exists_subset_nhds_of_isCompact' hV hV_cpct (fun i => (hV_cpct i).isClosed) hU theorem CompactExhaustion.isClosed [T2Space X] (K : CompactExhaustion X) (n : ℕ) : IsClosed (K n) := (K.isCompact n).isClosed theorem IsCompact.inter [T2Space X] {s t : Set X} (hs : IsCompact s) (ht : IsCompact t) : IsCompact (s ∩ t) := hs.inter_right <| ht.isClosed theorem image_closure_of_isCompact [T2Space Y] {s : Set X} (hs : IsCompact (closure s)) {f : X → Y} (hf : ContinuousOn f (closure s)) : f '' closure s = closure (f '' s) := Subset.antisymm hf.image_closure <| closure_minimal (image_subset f subset_closure) (hs.image_of_continuousOn hf).isClosed /-- A continuous map from a compact space to a Hausdorff space is a closed map. -/ protected theorem Continuous.isClosedMap [CompactSpace X] [T2Space Y] {f : X → Y} (h : Continuous f) : IsClosedMap f := fun _s hs => (hs.isCompact.image h).isClosed /-- A continuous injective map from a compact space to a Hausdorff space is a closed embedding. -/ theorem Continuous.closedEmbedding [CompactSpace X] [T2Space Y] {f : X → Y} (h : Continuous f) (hf : Function.Injective f) : ClosedEmbedding f := closedEmbedding_of_continuous_injective_closed h hf h.isClosedMap /-- A continuous surjective map from a compact space to a Hausdorff space is a quotient map. -/ theorem QuotientMap.of_surjective_continuous [CompactSpace X] [T2Space Y] {f : X → Y} (hsurj : Surjective f) (hcont : Continuous f) : QuotientMap f := hcont.isClosedMap.to_quotientMap hcont hsurj theorem isPreirreducible_iff_subsingleton [T2Space X] {S : Set X} : IsPreirreducible S ↔ S.Subsingleton := by refine ⟨fun h x hx y hy => ?_, Set.Subsingleton.isPreirreducible⟩ by_contra e obtain ⟨U, V, hU, hV, hxU, hyV, h'⟩ := t2_separation e exact ((h U V hU hV ⟨x, hx, hxU⟩ ⟨y, hy, hyV⟩).mono inter_subset_right).not_disjoint h' -- todo: use `alias` + `attribute [protected]` once we get `attribute [protected]` protected lemma IsPreirreducible.subsingleton [T2Space X] {S : Set X} (h : IsPreirreducible S) : S.Subsingleton := isPreirreducible_iff_subsingleton.1 h theorem isIrreducible_iff_singleton [T2Space X] {S : Set X} : IsIrreducible S ↔ ∃ x, S = {x} := by rw [IsIrreducible, isPreirreducible_iff_subsingleton, exists_eq_singleton_iff_nonempty_subsingleton] /-- There does not exist a nontrivial preirreducible T₂ space. -/ theorem not_preirreducible_nontrivial_t2 (X) [TopologicalSpace X] [PreirreducibleSpace X] [Nontrivial X] [T2Space X] : False := (PreirreducibleSpace.isPreirreducible_univ (X := X)).subsingleton.not_nontrivial nontrivial_univ end Separation section RegularSpace /-- A topological space is called a *regular space* if for any closed set `s` and `a ∉ s`, there exist disjoint open sets `U ⊇ s` and `V ∋ a`. We formulate this condition in terms of `Disjoint`ness of filters `𝓝ˢ s` and `𝓝 a`. -/ @[mk_iff] class RegularSpace (X : Type u) [TopologicalSpace X] : Prop where /-- If `a` is a point that does not belong to a closed set `s`, then `a` and `s` admit disjoint neighborhoods. -/ regular : ∀ {s : Set X} {a}, IsClosed s → a ∉ s → Disjoint (𝓝ˢ s) (𝓝 a) theorem regularSpace_TFAE (X : Type u) [TopologicalSpace X] : List.TFAE [RegularSpace X, ∀ (s : Set X) x, x ∉ closure s → Disjoint (𝓝ˢ s) (𝓝 x), ∀ (x : X) (s : Set X), Disjoint (𝓝ˢ s) (𝓝 x) ↔ x ∉ closure s, ∀ (x : X) (s : Set X), s ∈ 𝓝 x → ∃ t ∈ 𝓝 x, IsClosed t ∧ t ⊆ s, ∀ x : X, (𝓝 x).lift' closure ≤ 𝓝 x, ∀ x : X , (𝓝 x).lift' closure = 𝓝 x] := by tfae_have 1 ↔ 5 · rw [regularSpace_iff, (@compl_surjective (Set X) _).forall, forall_swap] simp only [isClosed_compl_iff, mem_compl_iff, Classical.not_not, @and_comm (_ ∈ _), (nhds_basis_opens _).lift'_closure.le_basis_iff (nhds_basis_opens _), and_imp, (nhds_basis_opens _).disjoint_iff_right, exists_prop, ← subset_interior_iff_mem_nhdsSet, interior_compl, compl_subset_compl] tfae_have 5 → 6 · exact fun h a => (h a).antisymm (𝓝 _).le_lift'_closure tfae_have 6 → 4 · intro H a s hs rw [← H] at hs rcases (𝓝 a).basis_sets.lift'_closure.mem_iff.mp hs with ⟨U, hU, hUs⟩ exact ⟨closure U, mem_of_superset hU subset_closure, isClosed_closure, hUs⟩ tfae_have 4 → 2 · intro H s a ha have ha' : sᶜ ∈ 𝓝 a := by rwa [← mem_interior_iff_mem_nhds, interior_compl] rcases H _ _ ha' with ⟨U, hU, hUc, hUs⟩ refine disjoint_of_disjoint_of_mem disjoint_compl_left ?_ hU rwa [← subset_interior_iff_mem_nhdsSet, hUc.isOpen_compl.interior_eq, subset_compl_comm] tfae_have 2 → 3 · refine fun H a s => ⟨fun hd has => mem_closure_iff_nhds_ne_bot.mp has ?_, H s a⟩ exact (hd.symm.mono_right <| @principal_le_nhdsSet _ _ s).eq_bot tfae_have 3 → 1 · exact fun H => ⟨fun hs ha => (H _ _).mpr <| hs.closure_eq.symm ▸ ha⟩ tfae_finish theorem RegularSpace.of_lift'_closure_le (h : ∀ x : X, (𝓝 x).lift' closure ≤ 𝓝 x) : RegularSpace X := Iff.mpr ((regularSpace_TFAE X).out 0 4) h theorem RegularSpace.of_lift'_closure (h : ∀ x : X, (𝓝 x).lift' closure = 𝓝 x) : RegularSpace X := Iff.mpr ((regularSpace_TFAE X).out 0 5) h @[deprecated (since := "2024-02-28")] alias RegularSpace.ofLift'_closure := RegularSpace.of_lift'_closure theorem RegularSpace.of_hasBasis {ι : X → Sort*} {p : ∀ a, ι a → Prop} {s : ∀ a, ι a → Set X} (h₁ : ∀ a, (𝓝 a).HasBasis (p a) (s a)) (h₂ : ∀ a i, p a i → IsClosed (s a i)) : RegularSpace X := .of_lift'_closure fun a => (h₁ a).lift'_closure_eq_self (h₂ a) @[deprecated (since := "2024-02-28")] alias RegularSpace.ofBasis := RegularSpace.of_hasBasis theorem RegularSpace.of_exists_mem_nhds_isClosed_subset (h : ∀ (x : X), ∀ s ∈ 𝓝 x, ∃ t ∈ 𝓝 x, IsClosed t ∧ t ⊆ s) : RegularSpace X := Iff.mpr ((regularSpace_TFAE X).out 0 3) h @[deprecated (since := "2024-02-28")] alias RegularSpace.ofExistsMemNhdsIsClosedSubset := RegularSpace.of_exists_mem_nhds_isClosed_subset /-- A weakly locally compact R₁ space is regular. -/ instance (priority := 100) [WeaklyLocallyCompactSpace X] [R1Space X] : RegularSpace X := .of_hasBasis isCompact_isClosed_basis_nhds fun _ _ ⟨_, _, h⟩ ↦ h variable [RegularSpace X] {x : X} {s : Set X} theorem disjoint_nhdsSet_nhds : Disjoint (𝓝ˢ s) (𝓝 x) ↔ x ∉ closure s := by have h := (regularSpace_TFAE X).out 0 2 exact h.mp ‹_› _ _ theorem disjoint_nhds_nhdsSet : Disjoint (𝓝 x) (𝓝ˢ s) ↔ x ∉ closure s := disjoint_comm.trans disjoint_nhdsSet_nhds /-- A regular space is R₁. -/ instance (priority := 100) : R1Space X where specializes_or_disjoint_nhds _ _ := or_iff_not_imp_left.2 fun h ↦ by rwa [← nhdsSet_singleton, disjoint_nhdsSet_nhds, ← specializes_iff_mem_closure] theorem exists_mem_nhds_isClosed_subset {x : X} {s : Set X} (h : s ∈ 𝓝 x) : ∃ t ∈ 𝓝 x, IsClosed t ∧ t ⊆ s := by have h' := (regularSpace_TFAE X).out 0 3 exact h'.mp ‹_› _ _ h theorem closed_nhds_basis (x : X) : (𝓝 x).HasBasis (fun s : Set X => s ∈ 𝓝 x ∧ IsClosed s) id := hasBasis_self.2 fun _ => exists_mem_nhds_isClosed_subset theorem lift'_nhds_closure (x : X) : (𝓝 x).lift' closure = 𝓝 x := (closed_nhds_basis x).lift'_closure_eq_self fun _ => And.right theorem Filter.HasBasis.nhds_closure {ι : Sort*} {x : X} {p : ι → Prop} {s : ι → Set X} (h : (𝓝 x).HasBasis p s) : (𝓝 x).HasBasis p fun i => closure (s i) := lift'_nhds_closure x ▸ h.lift'_closure theorem hasBasis_nhds_closure (x : X) : (𝓝 x).HasBasis (fun s => s ∈ 𝓝 x) closure := (𝓝 x).basis_sets.nhds_closure theorem hasBasis_opens_closure (x : X) : (𝓝 x).HasBasis (fun s => x ∈ s ∧ IsOpen s) closure := (nhds_basis_opens x).nhds_closure theorem IsCompact.exists_isOpen_closure_subset {K U : Set X} (hK : IsCompact K) (hU : U ∈ 𝓝ˢ K) : ∃ V, IsOpen V ∧ K ⊆ V ∧ closure V ⊆ U := by have hd : Disjoint (𝓝ˢ K) (𝓝ˢ Uᶜ) := by simpa [hK.disjoint_nhdsSet_left, disjoint_nhds_nhdsSet, ← subset_interior_iff_mem_nhdsSet] using hU rcases ((hasBasis_nhdsSet _).disjoint_iff (hasBasis_nhdsSet _)).1 hd with ⟨V, ⟨hVo, hKV⟩, W, ⟨hW, hUW⟩, hVW⟩ refine ⟨V, hVo, hKV, Subset.trans ?_ (compl_subset_comm.1 hUW)⟩ exact closure_minimal hVW.subset_compl_right hW.isClosed_compl theorem IsCompact.lift'_closure_nhdsSet {K : Set X} (hK : IsCompact K) : (𝓝ˢ K).lift' closure = 𝓝ˢ K := by refine le_antisymm (fun U hU ↦ ?_) (le_lift'_closure _) rcases hK.exists_isOpen_closure_subset hU with ⟨V, hVo, hKV, hVU⟩ exact mem_of_superset (mem_lift' <| hVo.mem_nhdsSet.2 hKV) hVU theorem TopologicalSpace.IsTopologicalBasis.nhds_basis_closure {B : Set (Set X)} (hB : IsTopologicalBasis B) (x : X) : (𝓝 x).HasBasis (fun s : Set X => x ∈ s ∧ s ∈ B) closure := by simpa only [and_comm] using hB.nhds_hasBasis.nhds_closure theorem TopologicalSpace.IsTopologicalBasis.exists_closure_subset {B : Set (Set X)} (hB : IsTopologicalBasis B) {x : X} {s : Set X} (h : s ∈ 𝓝 x) : ∃ t ∈ B, x ∈ t ∧ closure t ⊆ s := by simpa only [exists_prop, and_assoc] using hB.nhds_hasBasis.nhds_closure.mem_iff.mp h protected theorem Inducing.regularSpace [TopologicalSpace Y] {f : Y → X} (hf : Inducing f) : RegularSpace Y := .of_hasBasis (fun b => by rw [hf.nhds_eq_comap b]; exact (closed_nhds_basis _).comap _) fun b s hs => by exact hs.2.preimage hf.continuous theorem regularSpace_induced (f : Y → X) : @RegularSpace Y (induced f ‹_›) := letI := induced f ‹_› (inducing_induced f).regularSpace theorem regularSpace_sInf {X} {T : Set (TopologicalSpace X)} (h : ∀ t ∈ T, @RegularSpace X t) : @RegularSpace X (sInf T) := by let _ := sInf T have : ∀ a, (𝓝 a).HasBasis (fun If : Σ I : Set T, I → Set X => If.1.Finite ∧ ∀ i : If.1, If.2 i ∈ @nhds X i a ∧ @IsClosed X i (If.2 i)) fun If => ⋂ i : If.1, If.snd i := fun a ↦ by rw [nhds_sInf, ← iInf_subtype''] exact hasBasis_iInf fun t : T => @closed_nhds_basis X t (h t t.2) a refine .of_hasBasis this fun a If hIf => isClosed_iInter fun i => ?_ exact (hIf.2 i).2.mono (sInf_le (i : T).2) theorem regularSpace_iInf {ι X} {t : ι → TopologicalSpace X} (h : ∀ i, @RegularSpace X (t i)) : @RegularSpace X (iInf t) := regularSpace_sInf <| forall_mem_range.mpr h theorem RegularSpace.inf {X} {t₁ t₂ : TopologicalSpace X} (h₁ : @RegularSpace X t₁) (h₂ : @RegularSpace X t₂) : @RegularSpace X (t₁ ⊓ t₂) := by rw [inf_eq_iInf] exact regularSpace_iInf (Bool.forall_bool.2 ⟨h₂, h₁⟩) instance {p : X → Prop} : RegularSpace (Subtype p) := embedding_subtype_val.toInducing.regularSpace instance [TopologicalSpace Y] [RegularSpace Y] : RegularSpace (X × Y) := (regularSpace_induced (@Prod.fst X Y)).inf (regularSpace_induced (@Prod.snd X Y)) instance {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, RegularSpace (X i)] : RegularSpace (∀ i, X i) := regularSpace_iInf fun _ => regularSpace_induced _ /-- In a regular space, if a compact set and a closed set are disjoint, then they have disjoint neighborhoods. -/ lemma SeparatedNhds.of_isCompact_isClosed {s t : Set X} (hs : IsCompact s) (ht : IsClosed t) (hst : Disjoint s t) : SeparatedNhds s t := by simpa only [separatedNhds_iff_disjoint, hs.disjoint_nhdsSet_left, disjoint_nhds_nhdsSet, ht.closure_eq, disjoint_left] using hst @[deprecated (since := "2024-01-28")] alias separatedNhds_of_isCompact_isClosed := SeparatedNhds.of_isCompact_isClosed /-- This technique to witness `HasSeparatingCover` in regular Lindelöf topological spaces will be used to prove regular Lindelöf spaces are normal. -/ lemma IsClosed.HasSeparatingCover {s t : Set X} [r : RegularSpace X] [LindelofSpace X] (s_cl : IsClosed s) (t_cl : IsClosed t) (st_dis : Disjoint s t) : HasSeparatingCover s t := by -- `IsLindelof.indexed_countable_subcover` requires the space be Nonempty rcases isEmpty_or_nonempty X with empty_X | nonempty_X · rw [subset_eq_empty (t := s) (fun ⦃_⦄ _ ↦ trivial) (univ_eq_empty_iff.mpr empty_X)] exact hasSeparatingCovers_iff_separatedNhds.mpr (SeparatedNhds.empty_left t) |>.1 -- This is almost `HasSeparatingCover`, but is not countable. We define for all `a : X` for use -- with `IsLindelof.indexed_countable_subcover` momentarily. have (a : X) : ∃ n : Set X, IsOpen n ∧ Disjoint (closure n) t ∧ (a ∈ s → a ∈ n) := by wlog ains : a ∈ s · exact ⟨∅, isOpen_empty, SeparatedNhds.empty_left t |>.disjoint_closure_left, fun a ↦ ains a⟩ obtain ⟨n, nna, ncl, nsubkc⟩ := ((regularSpace_TFAE X).out 0 3 :).mp r a tᶜ <| t_cl.compl_mem_nhds (disjoint_left.mp st_dis ains) exact ⟨interior n, isOpen_interior, disjoint_left.mpr fun ⦃_⦄ ain ↦ nsubkc <| (IsClosed.closure_subset_iff ncl).mpr interior_subset ain, fun _ ↦ mem_interior_iff_mem_nhds.mpr nna⟩ -- By Lindelöf, we may obtain a countable subcover witnessing `HasSeparatingCover` choose u u_open u_dis u_nhd using this obtain ⟨f, f_cov⟩ := s_cl.isLindelof.indexed_countable_subcover u u_open (fun a ainh ↦ mem_iUnion.mpr ⟨a, u_nhd a ainh⟩) exact ⟨u ∘ f, f_cov, fun n ↦ ⟨u_open (f n), u_dis (f n)⟩⟩ end RegularSpace section LocallyCompactRegularSpace /-- In a (possibly non-Hausdorff) locally compact regular space, for every containment `K ⊆ U` of a compact set `K` in an open set `U`, there is a compact closed neighborhood `L` such that `K ⊆ L ⊆ U`: equivalently, there is a compact closed set `L` such that `K ⊆ interior L` and `L ⊆ U`. -/ theorem exists_compact_closed_between [LocallyCompactSpace X] [RegularSpace X] {K U : Set X} (hK : IsCompact K) (hU : IsOpen U) (h_KU : K ⊆ U) : ∃ L, IsCompact L ∧ IsClosed L ∧ K ⊆ interior L ∧ L ⊆ U := let ⟨L, L_comp, KL, LU⟩ := exists_compact_between hK hU h_KU ⟨closure L, L_comp.closure, isClosed_closure, KL.trans <| interior_mono subset_closure, L_comp.closure_subset_of_isOpen hU LU⟩ /-- In a locally compact regular space, given a compact set `K` inside an open set `U`, we can find an open set `V` between these sets with compact closure: `K ⊆ V` and the closure of `V` is inside `U`. -/ theorem exists_open_between_and_isCompact_closure [LocallyCompactSpace X] [RegularSpace X] {K U : Set X} (hK : IsCompact K) (hU : IsOpen U) (hKU : K ⊆ U) : ∃ V, IsOpen V ∧ K ⊆ V ∧ closure V ⊆ U ∧ IsCompact (closure V) := by rcases exists_compact_closed_between hK hU hKU with ⟨L, L_compact, L_closed, KL, LU⟩ have A : closure (interior L) ⊆ L := by apply (closure_mono interior_subset).trans (le_of_eq L_closed.closure_eq) refine ⟨interior L, isOpen_interior, KL, A.trans LU, ?_⟩ exact L_compact.closure_of_subset interior_subset @[deprecated WeaklyLocallyCompactSpace.locallyCompactSpace (since := "2023-09-03")] theorem locally_compact_of_compact [T2Space X] [CompactSpace X] : LocallyCompactSpace X := inferInstance end LocallyCompactRegularSpace section T25 /-- A T₂.₅ space, also known as a Urysohn space, is a topological space where for every pair `x ≠ y`, there are two open sets, with the intersection of closures empty, one containing `x` and the other `y` . -/ class T25Space (X : Type u) [TopologicalSpace X] : Prop where /-- Given two distinct points in a T₂.₅ space, their filters of closed neighborhoods are disjoint. -/ t2_5 : ∀ ⦃x y : X⦄, x ≠ y → Disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure) @[simp] theorem disjoint_lift'_closure_nhds [T25Space X] {x y : X} : Disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure) ↔ x ≠ y := ⟨fun h hxy => by simp [hxy, nhds_neBot.ne] at h, fun h => T25Space.t2_5 h⟩ -- see Note [lower instance priority] instance (priority := 100) T25Space.t2Space [T25Space X] : T2Space X := t2Space_iff_disjoint_nhds.2 fun _ _ hne => (disjoint_lift'_closure_nhds.2 hne).mono (le_lift'_closure _) (le_lift'_closure _) theorem exists_nhds_disjoint_closure [T25Space X] {x y : X} (h : x ≠ y) : ∃ s ∈ 𝓝 x, ∃ t ∈ 𝓝 y, Disjoint (closure s) (closure t) := ((𝓝 x).basis_sets.lift'_closure.disjoint_iff (𝓝 y).basis_sets.lift'_closure).1 <| disjoint_lift'_closure_nhds.2 h theorem exists_open_nhds_disjoint_closure [T25Space X] {x y : X} (h : x ≠ y) : ∃ u : Set X, x ∈ u ∧ IsOpen u ∧ ∃ v : Set X, y ∈ v ∧ IsOpen v ∧ Disjoint (closure u) (closure v) := by simpa only [exists_prop, and_assoc] using ((nhds_basis_opens x).lift'_closure.disjoint_iff (nhds_basis_opens y).lift'_closure).1 (disjoint_lift'_closure_nhds.2 h) theorem T25Space.of_injective_continuous [TopologicalSpace Y] [T25Space Y] {f : X → Y} (hinj : Injective f) (hcont : Continuous f) : T25Space X where t2_5 x y hne := (tendsto_lift'_closure_nhds hcont x).disjoint (t2_5 <| hinj.ne hne) (tendsto_lift'_closure_nhds hcont y) theorem Embedding.t25Space [TopologicalSpace Y] [T25Space Y] {f : X → Y} (hf : Embedding f) : T25Space X := .of_injective_continuous hf.inj hf.continuous instance Subtype.instT25Space [T25Space X] {p : X → Prop} : T25Space {x // p x} := embedding_subtype_val.t25Space end T25 section T3 /-- A T₃ space is a T₀ space which is a regular space. Any T₃ space is a T₁ space, a T₂ space, and a T₂.₅ space. -/ class T3Space (X : Type u) [TopologicalSpace X] extends T0Space X, RegularSpace X : Prop instance (priority := 90) instT3Space [T0Space X] [RegularSpace X] : T3Space X := ⟨⟩ theorem RegularSpace.t3Space_iff_t0Space [RegularSpace X] : T3Space X ↔ T0Space X := by constructor <;> intro <;> infer_instance -- see Note [lower instance priority] instance (priority := 100) T3Space.t25Space [T3Space X] : T25Space X := by refine ⟨fun x y hne => ?_⟩ rw [lift'_nhds_closure, lift'_nhds_closure] have : x ∉ closure {y} ∨ y ∉ closure {x} := (t0Space_iff_or_not_mem_closure X).mp inferInstance hne simp only [← disjoint_nhds_nhdsSet, nhdsSet_singleton] at this exact this.elim id fun h => h.symm protected theorem Embedding.t3Space [TopologicalSpace Y] [T3Space Y] {f : X → Y} (hf : Embedding f) : T3Space X := { toT0Space := hf.t0Space toRegularSpace := hf.toInducing.regularSpace } instance Subtype.t3Space [T3Space X] {p : X → Prop} : T3Space (Subtype p) := embedding_subtype_val.t3Space instance ULift.instT3Space [T3Space X] : T3Space (ULift X) := embedding_uLift_down.t3Space instance [TopologicalSpace Y] [T3Space X] [T3Space Y] : T3Space (X × Y) := ⟨⟩ instance {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, T3Space (X i)] : T3Space (∀ i, X i) := ⟨⟩ /-- Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. -/ theorem disjoint_nested_nhds [T3Space X] {x y : X} (h : x ≠ y) : ∃ U₁ ∈ 𝓝 x, ∃ V₁ ∈ 𝓝 x, ∃ U₂ ∈ 𝓝 y, ∃ V₂ ∈ 𝓝 y, IsClosed V₁ ∧ IsClosed V₂ ∧ IsOpen U₁ ∧ IsOpen U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ Disjoint U₁ U₂ := by rcases t2_separation h with ⟨U₁, U₂, U₁_op, U₂_op, x_in, y_in, H⟩ rcases exists_mem_nhds_isClosed_subset (U₁_op.mem_nhds x_in) with ⟨V₁, V₁_in, V₁_closed, h₁⟩ rcases exists_mem_nhds_isClosed_subset (U₂_op.mem_nhds y_in) with ⟨V₂, V₂_in, V₂_closed, h₂⟩ exact ⟨U₁, mem_of_superset V₁_in h₁, V₁, V₁_in, U₂, mem_of_superset V₂_in h₂, V₂, V₂_in, V₁_closed, V₂_closed, U₁_op, U₂_op, h₁, h₂, H⟩ open SeparationQuotient /-- The `SeparationQuotient` of a regular space is a T₃ space. -/ instance [RegularSpace X] : T3Space (SeparationQuotient X) where regular {s a} hs ha := by rcases surjective_mk a with ⟨a, rfl⟩ rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_mk, comap_mk_nhdsSet] exact RegularSpace.regular (hs.preimage continuous_mk) ha end T3 section NormalSpace /-- A topological space is said to be a *normal space* if any two disjoint closed sets have disjoint open neighborhoods. -/ class NormalSpace (X : Type u) [TopologicalSpace X] : Prop where /-- Two disjoint sets in a normal space admit disjoint neighbourhoods. -/ normal : ∀ s t : Set X, IsClosed s → IsClosed t → Disjoint s t → SeparatedNhds s t theorem normal_separation [NormalSpace X] {s t : Set X} (H1 : IsClosed s) (H2 : IsClosed t) (H3 : Disjoint s t) : SeparatedNhds s t := NormalSpace.normal s t H1 H2 H3 theorem disjoint_nhdsSet_nhdsSet [NormalSpace X] {s t : Set X} (hs : IsClosed s) (ht : IsClosed t) (hd : Disjoint s t) : Disjoint (𝓝ˢ s) (𝓝ˢ t) := (normal_separation hs ht hd).disjoint_nhdsSet theorem normal_exists_closure_subset [NormalSpace X] {s t : Set X} (hs : IsClosed s) (ht : IsOpen t) (hst : s ⊆ t) : ∃ u, IsOpen u ∧ s ⊆ u ∧ closure u ⊆ t := by have : Disjoint s tᶜ := Set.disjoint_left.mpr fun x hxs hxt => hxt (hst hxs) rcases normal_separation hs (isClosed_compl_iff.2 ht) this with ⟨s', t', hs', ht', hss', htt', hs't'⟩ refine ⟨s', hs', hss', Subset.trans (closure_minimal ?_ (isClosed_compl_iff.2 ht')) (compl_subset_comm.1 htt')⟩ exact fun x hxs hxt => hs't'.le_bot ⟨hxs, hxt⟩ /-- If the codomain of a closed embedding is a normal space, then so is the domain. -/ protected theorem ClosedEmbedding.normalSpace [TopologicalSpace Y] [NormalSpace Y] {f : X → Y} (hf : ClosedEmbedding f) : NormalSpace X where normal s t hs ht hst := by have H : SeparatedNhds (f '' s) (f '' t) := NormalSpace.normal (f '' s) (f '' t) (hf.isClosedMap s hs) (hf.isClosedMap t ht) (disjoint_image_of_injective hf.inj hst) exact (H.preimage hf.continuous).mono (subset_preimage_image _ _) (subset_preimage_image _ _) instance (priority := 100) NormalSpace.of_compactSpace_r1Space [CompactSpace X] [R1Space X] : NormalSpace X where normal _s _t hs ht := .of_isCompact_isCompact_isClosed hs.isCompact ht.isCompact ht /-- A regular topological space with a Lindelöf topology is a normal space. A consequence of e.g. Corollaries 20.8 and 20.10 of [Willard's *General Topology*][zbMATH02107988] (without the assumption of Hausdorff). -/ instance (priority := 100) NormalSpace.of_regularSpace_lindelofSpace [RegularSpace X] [LindelofSpace X] : NormalSpace X where normal _ _ hcl kcl hkdis := hasSeparatingCovers_iff_separatedNhds.mp ⟨hcl.HasSeparatingCover kcl hkdis, kcl.HasSeparatingCover hcl (Disjoint.symm hkdis)⟩ instance (priority := 100) NormalSpace.of_regularSpace_secondCountableTopology [RegularSpace X] [SecondCountableTopology X] : NormalSpace X := of_regularSpace_lindelofSpace end NormalSpace section Normality /-- A T₄ space is a normal T₁ space. -/ class T4Space (X : Type u) [TopologicalSpace X] extends T1Space X, NormalSpace X : Prop instance (priority := 100) [T1Space X] [NormalSpace X] : T4Space X := ⟨⟩ -- see Note [lower instance priority] instance (priority := 100) T4Space.t3Space [T4Space X] : T3Space X where regular hs hxs := by simpa only [nhdsSet_singleton] using (normal_separation hs isClosed_singleton (disjoint_singleton_right.mpr hxs)).disjoint_nhdsSet @[deprecated inferInstance (since := "2024-01-28")] theorem T4Space.of_compactSpace_t2Space [CompactSpace X] [T2Space X] : T4Space X := inferInstance /-- If the codomain of a closed embedding is a T₄ space, then so is the domain. -/ protected theorem ClosedEmbedding.t4Space [TopologicalSpace Y] [T4Space Y] {f : X → Y} (hf : ClosedEmbedding f) : T4Space X where toT1Space := hf.toEmbedding.t1Space toNormalSpace := hf.normalSpace instance ULift.instT4Space [T4Space X] : T4Space (ULift X) := ULift.closedEmbedding_down.t4Space namespace SeparationQuotient /-- The `SeparationQuotient` of a normal space is a normal space. -/ instance [NormalSpace X] : NormalSpace (SeparationQuotient X) where normal s t hs ht hd := separatedNhds_iff_disjoint.2 <| by rw [← disjoint_comap_iff surjective_mk, comap_mk_nhdsSet, comap_mk_nhdsSet] exact disjoint_nhdsSet_nhdsSet (hs.preimage continuous_mk) (ht.preimage continuous_mk) (hd.preimage mk) end SeparationQuotient variable (X) end Normality section CompletelyNormal /-- A topological space `X` is a *completely normal space* provided that for any two sets `s`, `t` such that if both `closure s` is disjoint with `t`, and `s` is disjoint with `closure t`, then there exist disjoint neighbourhoods of `s` and `t`. -/ class CompletelyNormalSpace (X : Type u) [TopologicalSpace X] : Prop where /-- If `closure s` is disjoint with `t`, and `s` is disjoint with `closure t`, then `s` and `t` admit disjoint neighbourhoods. -/ completely_normal : ∀ ⦃s t : Set X⦄, Disjoint (closure s) t → Disjoint s (closure t) → Disjoint (𝓝ˢ s) (𝓝ˢ t) export CompletelyNormalSpace (completely_normal) -- see Note [lower instance priority] /-- A completely normal space is a normal space. -/ instance (priority := 100) CompletelyNormalSpace.toNormalSpace [CompletelyNormalSpace X] : NormalSpace X where normal s t hs ht hd := separatedNhds_iff_disjoint.2 <| completely_normal (by rwa [hs.closure_eq]) (by rwa [ht.closure_eq]) theorem Embedding.completelyNormalSpace [TopologicalSpace Y] [CompletelyNormalSpace Y] {e : X → Y} (he : Embedding e) : CompletelyNormalSpace X := by refine ⟨fun s t hd₁ hd₂ => ?_⟩ simp only [he.toInducing.nhdsSet_eq_comap] refine disjoint_comap (completely_normal ?_ ?_) · rwa [← subset_compl_iff_disjoint_left, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_left] · rwa [← subset_compl_iff_disjoint_right, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_right] /-- A subspace of a completely normal space is a completely normal space. -/ instance [CompletelyNormalSpace X] {p : X → Prop} : CompletelyNormalSpace { x // p x } := embedding_subtype_val.completelyNormalSpace instance ULift.instCompletelyNormalSpace [CompletelyNormalSpace X] : CompletelyNormalSpace (ULift X) := embedding_uLift_down.completelyNormalSpace /-- A T₅ space is a completely normal T₁ space. -/ class T5Space (X : Type u) [TopologicalSpace X] extends T1Space X, CompletelyNormalSpace X : Prop theorem Embedding.t5Space [TopologicalSpace Y] [T5Space Y] {e : X → Y} (he : Embedding e) : T5Space X where __ := he.t1Space completely_normal := by have := Embedding.completelyNormalSpace he exact completely_normal -- see Note [lower instance priority] /-- A `T₅` space is a `T₄` space. -/ instance (priority := 100) T5Space.toT4Space [T5Space X] : T4Space X where -- follows from type-class inference /-- A subspace of a T₅ space is a T₅ space. -/ instance [T5Space X] {p : X → Prop} : T5Space { x // p x } := embedding_subtype_val.t5Space instance ULift.instT5Space [T5Space X] : T5Space (ULift X) := embedding_uLift_down.t5Space open SeparationQuotient /-- The `SeparationQuotient` of a completely normal R₀ space is a T₅ space. -/ instance [CompletelyNormalSpace X] [R0Space X] : T5Space (SeparationQuotient X) where t1 := by rwa [((t1Space_TFAE (SeparationQuotient X)).out 1 0 :), SeparationQuotient.t1Space_iff] completely_normal s t hd₁ hd₂ := by rw [← disjoint_comap_iff surjective_mk, comap_mk_nhdsSet, comap_mk_nhdsSet] apply completely_normal <;> rw [← preimage_mk_closure] exacts [hd₁.preimage mk, hd₂.preimage mk] end CompletelyNormal section PerfectlyNormal /-- A topological space `X` is a *perfectly normal space* provided it is normal and closed sets are Gδ. -/ class PerfectlyNormalSpace (X : Type u) [TopologicalSpace X] extends NormalSpace X : Prop where closed_gdelta : ∀ ⦃h : Set X⦄, IsClosed h → IsGδ h /-- Lemma that allows the easy conclusion that perfectly normal spaces are completely normal. -/ theorem Disjoint.hasSeparatingCover_closed_gdelta_right {s t : Set X} [NormalSpace X] (st_dis : Disjoint s t) (t_cl : IsClosed t) (t_gd : IsGδ t) : HasSeparatingCover s t := by obtain ⟨T, T_open, T_count, T_int⟩ := t_gd rcases T.eq_empty_or_nonempty with rfl | T_nonempty · rw [T_int, sInter_empty] at st_dis rw [(s.disjoint_univ).mp st_dis] exact t.hasSeparatingCover_empty_left obtain ⟨g, g_surj⟩ := T_count.exists_surjective T_nonempty choose g' g'_open clt_sub_g' clg'_sub_g using fun n ↦ by apply normal_exists_closure_subset t_cl (T_open (g n).1 (g n).2) rw [T_int] exact sInter_subset_of_mem (g n).2 have clg'_int : t = ⋂ i, closure (g' i) := by apply (subset_iInter fun n ↦ (clt_sub_g' n).trans subset_closure).antisymm rw [T_int] refine subset_sInter fun t tinT ↦ ?_ obtain ⟨n, gn⟩ := g_surj ⟨t, tinT⟩ refine iInter_subset_of_subset n <| (clg'_sub_g n).trans ?_ rw [gn] use fun n ↦ (closure (g' n))ᶜ constructor · rw [← compl_iInter, subset_compl_comm, ← clg'_int] exact st_dis.subset_compl_left · refine fun n ↦ ⟨isOpen_compl_iff.mpr isClosed_closure, ?_⟩ simp only [closure_compl, disjoint_compl_left_iff_subset] rw [← closure_eq_iff_isClosed.mpr t_cl] at clt_sub_g' exact subset_closure.trans <| (clt_sub_g' n).trans <| (g'_open n).subset_interior_closure instance (priority := 100) PerfectlyNormalSpace.toCompletelyNormalSpace [PerfectlyNormalSpace X] : CompletelyNormalSpace X where completely_normal _ _ hd₁ hd₂ := separatedNhds_iff_disjoint.mp <| hasSeparatingCovers_iff_separatedNhds.mp ⟨(hd₂.hasSeparatingCover_closed_gdelta_right isClosed_closure <| closed_gdelta isClosed_closure).mono (fun ⦃_⦄ a ↦ a) subset_closure, ((Disjoint.symm hd₁).hasSeparatingCover_closed_gdelta_right isClosed_closure <| closed_gdelta isClosed_closure).mono (fun ⦃_⦄ a ↦ a) subset_closure⟩ /-- A T₆ space is a perfectly normal T₁ space. -/ class T6Space (X : Type u) [TopologicalSpace X] extends T1Space X, PerfectlyNormalSpace X : Prop -- see Note [lower instance priority] /-- A `T₆` space is a `T₅` space. -/ instance (priority := 100) T6Space.toT5Space [T6Space X] : T5Space X where -- follows from type-class inference end PerfectlyNormal /-- In a compact T₂ space, the connected component of a point equals the intersection of all its clopen neighbourhoods. -/ theorem connectedComponent_eq_iInter_isClopen [T2Space X] [CompactSpace X] (x : X) : connectedComponent x = ⋂ s : { s : Set X // IsClopen s ∧ x ∈ s }, s := by apply Subset.antisymm connectedComponent_subset_iInter_isClopen -- Reduce to showing that the clopen intersection is connected. refine IsPreconnected.subset_connectedComponent ?_ (mem_iInter.2 fun s => s.2.2) -- We do this by showing that any disjoint cover by two closed sets implies -- that one of these closed sets must contain our whole thing. -- To reduce to the case where the cover is disjoint on all of `X` we need that `s` is closed have hs : @IsClosed X _ (⋂ s : { s : Set X // IsClopen s ∧ x ∈ s }, s) := isClosed_iInter fun s => s.2.1.1 rw [isPreconnected_iff_subset_of_fully_disjoint_closed hs] intro a b ha hb hab ab_disj -- Since our space is normal, we get two larger disjoint open sets containing the disjoint -- closed sets. If we can show that our intersection is a subset of any of these we can then -- "descend" this to show that it is a subset of either a or b. rcases normal_separation ha hb ab_disj with ⟨u, v, hu, hv, hau, hbv, huv⟩ obtain ⟨s, H⟩ : ∃ s : Set X, IsClopen s ∧ x ∈ s ∧ s ⊆ u ∪ v := by /- Now we find a clopen set `s` around `x`, contained in `u ∪ v`. We utilize the fact that `X \ u ∪ v` will be compact, so there must be some finite intersection of clopen neighbourhoods of `X` disjoint to it, but a finite intersection of clopen sets is clopen, so we let this be our `s`. -/ have H1 := (hu.union hv).isClosed_compl.isCompact.inter_iInter_nonempty (fun s : { s : Set X // IsClopen s ∧ x ∈ s } => s) fun s => s.2.1.1 rw [← not_disjoint_iff_nonempty_inter, imp_not_comm, not_forall] at H1 cases' H1 (disjoint_compl_left_iff_subset.2 <| hab.trans <| union_subset_union hau hbv) with si H2 refine ⟨⋂ U ∈ si, Subtype.val U, ?_, ?_, ?_⟩ · exact isClopen_biInter_finset fun s _ => s.2.1 · exact mem_iInter₂.2 fun s _ => s.2.2 · rwa [← disjoint_compl_left_iff_subset, disjoint_iff_inter_eq_empty, ← not_nonempty_iff_eq_empty] -- So, we get a disjoint decomposition `s = s ∩ u ∪ s ∩ v` of clopen sets. The intersection of all -- clopen neighbourhoods will then lie in whichever of u or v x lies in and hence will be a subset -- of either a or b. · have H1 := isClopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hu hv huv rw [union_comm] at H have H2 := isClopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hv hu huv.symm by_cases hxu : x ∈ u <;> [left; right] -- The x ∈ u case. · suffices ⋂ s : { s : Set X // IsClopen s ∧ x ∈ s }, ↑s ⊆ u from Disjoint.left_le_of_le_sup_right hab (huv.mono this hbv) · apply Subset.trans _ s.inter_subset_right exact iInter_subset (fun s : { s : Set X // IsClopen s ∧ x ∈ s } => s.1) ⟨s ∩ u, H1, mem_inter H.2.1 hxu⟩ -- If x ∉ u, we get x ∈ v since x ∈ u ∪ v. The rest is then like the x ∈ u case. · have h1 : x ∈ v := (hab.trans (union_subset_union hau hbv) (mem_iInter.2 fun i => i.2.2)).resolve_left hxu suffices ⋂ s : { s : Set X // IsClopen s ∧ x ∈ s }, ↑s ⊆ v from (huv.symm.mono this hau).left_le_of_le_sup_left hab · refine Subset.trans ?_ s.inter_subset_right exact iInter_subset (fun s : { s : Set X // IsClopen s ∧ x ∈ s } => s.1) ⟨s ∩ v, H2, mem_inter H.2.1 h1⟩ section Profinite /-- A T1 space with a clopen basis is totally separated. -/ theorem totallySeparatedSpace_of_t1_of_basis_clopen [T1Space X] (h : IsTopologicalBasis { s : Set X | IsClopen s }) : TotallySeparatedSpace X := by constructor rintro x - y - hxy rcases h.mem_nhds_iff.mp (isOpen_ne.mem_nhds hxy) with ⟨U, hU, hxU, hyU⟩ exact ⟨U, Uᶜ, hU.isOpen, hU.compl.isOpen, hxU, fun h => hyU h rfl, (union_compl_self U).superset, disjoint_compl_right⟩ variable [T2Space X] [CompactSpace X] /-- A compact Hausdorff space is totally disconnected if and only if it is totally separated, this is also true for locally compact spaces. -/ theorem compact_t2_tot_disc_iff_tot_sep : TotallyDisconnectedSpace X ↔ TotallySeparatedSpace X := by refine ⟨fun h => ⟨fun x _ y _ => ?_⟩, @TotallySeparatedSpace.totallyDisconnectedSpace _ _⟩ contrapose! intro hyp suffices x ∈ connectedComponent y by simpa [totallyDisconnectedSpace_iff_connectedComponent_singleton.1 h y, mem_singleton_iff] rw [connectedComponent_eq_iInter_isClopen, mem_iInter] rintro ⟨w : Set X, hw : IsClopen w, hy : y ∈ w⟩ by_contra hx exact hyp ⟨wᶜ, w, hw.1.isOpen_compl, hw.2, hx, hy, (@isCompl_compl _ w _).symm.codisjoint.top_le, disjoint_compl_left⟩ variable [TotallyDisconnectedSpace X] /-- A totally disconnected compact Hausdorff space is totally separated. -/ instance (priority := 100) : TotallySeparatedSpace X := compact_t2_tot_disc_iff_tot_sep.mp inferInstance theorem nhds_basis_clopen (x : X) : (𝓝 x).HasBasis (fun s : Set X => x ∈ s ∧ IsClopen s) id := ⟨fun U => by constructor · have hx : connectedComponent x = {x} := totallyDisconnectedSpace_iff_connectedComponent_singleton.mp ‹_› x rw [connectedComponent_eq_iInter_isClopen] at hx intro hU let N := { s // IsClopen s ∧ x ∈ s } rsuffices ⟨⟨s, hs, hs'⟩, hs''⟩ : ∃ s : N, s.val ⊆ U · exact ⟨s, ⟨hs', hs⟩, hs''⟩ haveI : Nonempty N := ⟨⟨univ, isClopen_univ, mem_univ x⟩⟩ have hNcl : ∀ s : N, IsClosed s.val := fun s => s.property.1.1 have hdir : Directed Superset fun s : N => s.val := by rintro ⟨s, hs, hxs⟩ ⟨t, ht, hxt⟩ exact ⟨⟨s ∩ t, hs.inter ht, ⟨hxs, hxt⟩⟩, inter_subset_left, inter_subset_right⟩ have h_nhd : ∀ y ∈ ⋂ s : N, s.val, U ∈ 𝓝 y := fun y y_in => by erw [hx, mem_singleton_iff] at y_in rwa [y_in] exact exists_subset_nhds_of_compactSpace hdir hNcl h_nhd · rintro ⟨V, ⟨hxV, -, V_op⟩, hUV : V ⊆ U⟩ rw [mem_nhds_iff] exact ⟨V, hUV, V_op, hxV⟩⟩ theorem isTopologicalBasis_isClopen : IsTopologicalBasis { s : Set X | IsClopen s } := by apply isTopologicalBasis_of_isOpen_of_nhds fun U (hU : IsClopen U) => hU.2 intro x U hxU U_op have : U ∈ 𝓝 x := IsOpen.mem_nhds U_op hxU rcases (nhds_basis_clopen x).mem_iff.mp this with ⟨V, ⟨hxV, hV⟩, hVU : V ⊆ U⟩ use V tauto /-- Every member of an open set in a compact Hausdorff totally disconnected space is contained in a clopen set contained in the open set. -/ theorem compact_exists_isClopen_in_isOpen {x : X} {U : Set X} (is_open : IsOpen U) (memU : x ∈ U) : ∃ V : Set X, IsClopen V ∧ x ∈ V ∧ V ⊆ U := isTopologicalBasis_isClopen.mem_nhds_iff.1 (is_open.mem_nhds memU) end Profinite section LocallyCompact variable {H : Type*} [TopologicalSpace H] [LocallyCompactSpace H] [T2Space H] /-- A locally compact Hausdorff totally disconnected space has a basis with clopen elements. -/ theorem loc_compact_Haus_tot_disc_of_zero_dim [TotallyDisconnectedSpace H] : IsTopologicalBasis { s : Set H | IsClopen s } := by refine isTopologicalBasis_of_isOpen_of_nhds (fun u hu => hu.2) fun x U memU hU => ?_ obtain ⟨s, comp, xs, sU⟩ := exists_compact_subset hU memU let u : Set s := ((↑) : s → H) ⁻¹' interior s have u_open_in_s : IsOpen u := isOpen_interior.preimage continuous_subtype_val lift x to s using interior_subset xs haveI : CompactSpace s := isCompact_iff_compactSpace.1 comp obtain ⟨V : Set s, VisClopen, Vx, V_sub⟩ := compact_exists_isClopen_in_isOpen u_open_in_s xs have VisClopen' : IsClopen (((↑) : s → H) '' V) := by refine ⟨comp.isClosed.closedEmbedding_subtype_val.closed_iff_image_closed.1 VisClopen.1, ?_⟩ let v : Set u := ((↑) : u → s) ⁻¹' V have : ((↑) : u → H) = ((↑) : s → H) ∘ ((↑) : u → s) := rfl have f0 : Embedding ((↑) : u → H) := embedding_subtype_val.comp embedding_subtype_val have f1 : OpenEmbedding ((↑) : u → H) := by refine ⟨f0, ?_⟩ · have : Set.range ((↑) : u → H) = interior s := by rw [this, Set.range_comp, Subtype.range_coe, Subtype.image_preimage_coe] apply Set.inter_eq_self_of_subset_right interior_subset rw [this] apply isOpen_interior have f2 : IsOpen v := VisClopen.2.preimage continuous_subtype_val have f3 : ((↑) : s → H) '' V = ((↑) : u → H) '' v := by rw [this, image_comp, Subtype.image_preimage_coe, inter_eq_self_of_subset_right V_sub] rw [f3] apply f1.isOpenMap v f2 use (↑) '' V, VisClopen', by simp [Vx], Subset.trans (by simp) sU /-- A locally compact Hausdorff space is totally disconnected if and only if it is totally separated. -/ theorem loc_compact_t2_tot_disc_iff_tot_sep : TotallyDisconnectedSpace H ↔ TotallySeparatedSpace H := by constructor · intro h exact totallySeparatedSpace_of_t1_of_basis_clopen loc_compact_Haus_tot_disc_of_zero_dim apply TotallySeparatedSpace.totallyDisconnectedSpace end LocallyCompact /-- `ConnectedComponents X` is Hausdorff when `X` is Hausdorff and compact -/ instance ConnectedComponents.t2 [T2Space X] [CompactSpace X] : T2Space (ConnectedComponents X) := by -- Proof follows that of: https://stacks.math.columbia.edu/tag/0900 -- Fix 2 distinct connected components, with points a and b refine ⟨ConnectedComponents.surjective_coe.forall₂.2 fun a b ne => ?_⟩ rw [ConnectedComponents.coe_ne_coe] at ne have h := connectedComponent_disjoint ne -- write ↑b as the intersection of all clopen subsets containing it rw [connectedComponent_eq_iInter_isClopen b, disjoint_iff_inter_eq_empty] at h -- Now we show that this can be reduced to some clopen containing `↑b` being disjoint to `↑a` obtain ⟨U, V, hU, ha, hb, rfl⟩ : ∃ (U : Set X) (V : Set (ConnectedComponents X)), IsClopen U ∧ connectedComponent a ∩ U = ∅ ∧ connectedComponent b ⊆ U ∧ (↑) ⁻¹' V = U := by have h := (isClosed_connectedComponent (α := X)).isCompact.elim_finite_subfamily_closed _ (fun s : { s : Set X // IsClopen s ∧ b ∈ s } => s.2.1.1) h cases' h with fin_a ha -- This clopen and its complement will separate the connected components of `a` and `b` set U : Set X := ⋂ (i : { s // IsClopen s ∧ b ∈ s }) (_ : i ∈ fin_a), i have hU : IsClopen U := isClopen_biInter_finset fun i _ => i.2.1 exact ⟨U, (↑) '' U, hU, ha, subset_iInter₂ fun s _ => s.2.1.connectedComponent_subset s.2.2, (connectedComponents_preimage_image U).symm ▸ hU.biUnion_connectedComponent_eq⟩ rw [ConnectedComponents.quotientMap_coe.isClopen_preimage] at hU refine ⟨Vᶜ, V, hU.compl.isOpen, hU.isOpen, ?_, hb mem_connectedComponent, disjoint_compl_left⟩ exact fun h => flip Set.Nonempty.ne_empty ha ⟨a, mem_connectedComponent, h⟩
Topology\Sequences.lean
/- Copyright (c) 2018 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Patrick Massot, Yury Kudryashov -/ import Mathlib.Topology.Defs.Sequences import Mathlib.Topology.UniformSpace.Cauchy /-! # Sequences in topological spaces In this file we prove theorems about relations between closure/compactness/continuity etc and their sequential counterparts. ## Main definitions The following notions are defined in `Topology/Defs/Sequences`. We build theory about these definitions here, so we remind the definitions. ### Set operation * `seqClosure s`: sequential closure of a set, the set of limits of sequences of points of `s`; ### Predicates * `IsSeqClosed s`: predicate saying that a set is sequentially closed, i.e., `seqClosure s ⊆ s`; * `SeqContinuous f`: predicate saying that a function is sequentially continuous, i.e., for any sequence `u : ℕ → X` that converges to a point `x`, the sequence `f ∘ u` converges to `f x`; * `IsSeqCompact s`: predicate saying that a set is sequentially compact, i.e., every sequence taking values in `s` has a converging subsequence. ### Type classes * `FrechetUrysohnSpace X`: a typeclass saying that a topological space is a *Fréchet-Urysohn space*, i.e., the sequential closure of any set is equal to its closure. * `SequentialSpace X`: a typeclass saying that a topological space is a *sequential space*, i.e., any sequentially closed set in this space is closed. This condition is weaker than being a Fréchet-Urysohn space. * `SeqCompactSpace X`: a typeclass saying that a topological space is sequentially compact, i.e., every sequence in `X` has a converging subsequence. ## Main results * `seqClosure_subset_closure`: closure of a set includes its sequential closure; * `IsClosed.isSeqClosed`: a closed set is sequentially closed; * `IsSeqClosed.seqClosure_eq`: sequential closure of a sequentially closed set `s` is equal to `s`; * `seqClosure_eq_closure`: in a Fréchet-Urysohn space, the sequential closure of a set is equal to its closure; * `tendsto_nhds_iff_seq_tendsto`, `FrechetUrysohnSpace.of_seq_tendsto_imp_tendsto`: a topological space is a Fréchet-Urysohn space if and only if sequential convergence implies convergence; * `FirstCountableTopology.frechetUrysohnSpace`: every topological space with first countable topology is a Fréchet-Urysohn space; * `FrechetUrysohnSpace.to_sequentialSpace`: every Fréchet-Urysohn space is a sequential space; * `IsSeqCompact.isCompact`: a sequentially compact set in a uniform space with countably generated uniformity is compact. ## Tags sequentially closed, sequentially compact, sequential space -/ open Set Function Filter TopologicalSpace Bornology open scoped Topology Uniformity variable {X Y : Type*} /-! ### Sequential closures, sequential continuity, and sequential spaces. -/ section TopologicalSpace variable [TopologicalSpace X] [TopologicalSpace Y] theorem subset_seqClosure {s : Set X} : s ⊆ seqClosure s := fun p hp => ⟨const ℕ p, fun _ => hp, tendsto_const_nhds⟩ /-- The sequential closure of a set is contained in the closure of that set. The converse is not true. -/ theorem seqClosure_subset_closure {s : Set X} : seqClosure s ⊆ closure s := fun _p ⟨_x, xM, xp⟩ => mem_closure_of_tendsto xp (univ_mem' xM) /-- The sequential closure of a sequentially closed set is the set itself. -/ theorem IsSeqClosed.seqClosure_eq {s : Set X} (hs : IsSeqClosed s) : seqClosure s = s := Subset.antisymm (fun _p ⟨_x, hx, hp⟩ => hs hx hp) subset_seqClosure /-- If a set is equal to its sequential closure, then it is sequentially closed. -/ theorem isSeqClosed_of_seqClosure_eq {s : Set X} (hs : seqClosure s = s) : IsSeqClosed s := fun x _p hxs hxp => hs ▸ ⟨x, hxs, hxp⟩ /-- A set is sequentially closed iff it is equal to its sequential closure. -/ theorem isSeqClosed_iff {s : Set X} : IsSeqClosed s ↔ seqClosure s = s := ⟨IsSeqClosed.seqClosure_eq, isSeqClosed_of_seqClosure_eq⟩ /-- A set is sequentially closed if it is closed. -/ protected theorem IsClosed.isSeqClosed {s : Set X} (hc : IsClosed s) : IsSeqClosed s := fun _u _x hu hx => hc.mem_of_tendsto hx (eventually_of_forall hu) theorem seqClosure_eq_closure [FrechetUrysohnSpace X] (s : Set X) : seqClosure s = closure s := seqClosure_subset_closure.antisymm <| FrechetUrysohnSpace.closure_subset_seqClosure s /-- In a Fréchet-Urysohn space, a point belongs to the closure of a set iff it is a limit of a sequence taking values in this set. -/ theorem mem_closure_iff_seq_limit [FrechetUrysohnSpace X] {s : Set X} {a : X} : a ∈ closure s ↔ ∃ x : ℕ → X, (∀ n : ℕ, x n ∈ s) ∧ Tendsto x atTop (𝓝 a) := by rw [← seqClosure_eq_closure] rfl /-- If the domain of a function `f : α → β` is a Fréchet-Urysohn space, then convergence is equivalent to sequential convergence. See also `Filter.tendsto_iff_seq_tendsto` for a version that works for any pair of filters assuming that the filter in the domain is countably generated. This property is equivalent to the definition of `FrechetUrysohnSpace`, see `FrechetUrysohnSpace.of_seq_tendsto_imp_tendsto`. -/ theorem tendsto_nhds_iff_seq_tendsto [FrechetUrysohnSpace X] {f : X → Y} {a : X} {b : Y} : Tendsto f (𝓝 a) (𝓝 b) ↔ ∀ u : ℕ → X, Tendsto u atTop (𝓝 a) → Tendsto (f ∘ u) atTop (𝓝 b) := by refine ⟨fun hf u hu => hf.comp hu, fun h => ((nhds_basis_closeds _).tendsto_iff (nhds_basis_closeds _)).2 ?_⟩ rintro s ⟨hbs, hsc⟩ refine ⟨closure (f ⁻¹' s), ⟨mt ?_ hbs, isClosed_closure⟩, fun x => mt fun hx => subset_closure hx⟩ rw [← seqClosure_eq_closure] rintro ⟨u, hus, hu⟩ exact hsc.mem_of_tendsto (h u hu) (eventually_of_forall hus) /-- An alternative construction for `FrechetUrysohnSpace`: if sequential convergence implies convergence, then the space is a Fréchet-Urysohn space. -/ theorem FrechetUrysohnSpace.of_seq_tendsto_imp_tendsto (h : ∀ (f : X → Prop) (a : X), (∀ u : ℕ → X, Tendsto u atTop (𝓝 a) → Tendsto (f ∘ u) atTop (𝓝 (f a))) → ContinuousAt f a) : FrechetUrysohnSpace X := by refine ⟨fun s x hcx => ?_⟩ by_cases hx : x ∈ s · exact subset_seqClosure hx · obtain ⟨u, hux, hus⟩ : ∃ u : ℕ → X, Tendsto u atTop (𝓝 x) ∧ ∃ᶠ x in atTop, u x ∈ s := by simpa only [ContinuousAt, hx, tendsto_nhds_true, (· ∘ ·), ← not_frequently, exists_prop, ← mem_closure_iff_frequently, hcx, imp_false, not_forall, not_not, not_false_eq_true, not_true_eq_false] using h (· ∉ s) x rcases extraction_of_frequently_atTop hus with ⟨φ, φ_mono, hφ⟩ exact ⟨u ∘ φ, hφ, hux.comp φ_mono.tendsto_atTop⟩ -- see Note [lower instance priority] /-- Every first-countable space is a Fréchet-Urysohn space. -/ instance (priority := 100) FirstCountableTopology.frechetUrysohnSpace [FirstCountableTopology X] : FrechetUrysohnSpace X := FrechetUrysohnSpace.of_seq_tendsto_imp_tendsto fun _ _ => tendsto_iff_seq_tendsto.2 -- see Note [lower instance priority] /-- Every Fréchet-Urysohn space is a sequential space. -/ instance (priority := 100) FrechetUrysohnSpace.to_sequentialSpace [FrechetUrysohnSpace X] : SequentialSpace X := ⟨fun s hs => by rw [← closure_eq_iff_isClosed, ← seqClosure_eq_closure, hs.seqClosure_eq]⟩ theorem Inducing.frechetUrysohnSpace [FrechetUrysohnSpace Y] {f : X → Y} (hf : Inducing f) : FrechetUrysohnSpace X := by refine ⟨fun s x hx ↦ ?_⟩ rw [hf.closure_eq_preimage_closure_image, mem_preimage, mem_closure_iff_seq_limit] at hx rcases hx with ⟨u, hus, hu⟩ choose v hv hvu using hus refine ⟨v, hv, ?_⟩ simpa only [hf.tendsto_nhds_iff, (· ∘ ·), hvu] /-- Subtype of a Fréchet-Urysohn space is a Fréchet-Urysohn space. -/ instance Subtype.instFrechetUrysohnSpace [FrechetUrysohnSpace X] {p : X → Prop} : FrechetUrysohnSpace (Subtype p) := inducing_subtype_val.frechetUrysohnSpace /-- In a sequential space, a set is closed iff it's sequentially closed. -/ theorem isSeqClosed_iff_isClosed [SequentialSpace X] {M : Set X} : IsSeqClosed M ↔ IsClosed M := ⟨IsSeqClosed.isClosed, IsClosed.isSeqClosed⟩ /-- The preimage of a sequentially closed set under a sequentially continuous map is sequentially closed. -/ theorem IsSeqClosed.preimage {f : X → Y} {s : Set Y} (hs : IsSeqClosed s) (hf : SeqContinuous f) : IsSeqClosed (f ⁻¹' s) := fun _x _p hx hp => hs hx (hf hp) -- A continuous function is sequentially continuous. protected theorem Continuous.seqContinuous {f : X → Y} (hf : Continuous f) : SeqContinuous f := fun _x p hx => (hf.tendsto p).comp hx /-- A sequentially continuous function defined on a sequential space is continuous. -/ protected theorem SeqContinuous.continuous [SequentialSpace X] {f : X → Y} (hf : SeqContinuous f) : Continuous f := continuous_iff_isClosed.mpr fun _s hs => (hs.isSeqClosed.preimage hf).isClosed /-- If the domain of a function is a sequential space, then continuity of this function is equivalent to its sequential continuity. -/ theorem continuous_iff_seqContinuous [SequentialSpace X] {f : X → Y} : Continuous f ↔ SeqContinuous f := ⟨Continuous.seqContinuous, SeqContinuous.continuous⟩ theorem SequentialSpace.coinduced [SequentialSpace X] {Y} (f : X → Y) : @SequentialSpace Y (.coinduced f ‹_›) := letI : TopologicalSpace Y := .coinduced f ‹_› ⟨fun s hs ↦ isClosed_coinduced.2 (hs.preimage continuous_coinduced_rng.seqContinuous).isClosed⟩ protected theorem SequentialSpace.iSup {X} {ι : Sort*} {t : ι → TopologicalSpace X} (h : ∀ i, @SequentialSpace X (t i)) : @SequentialSpace X (⨆ i, t i) := by letI : TopologicalSpace X := ⨆ i, t i refine ⟨fun s hs ↦ isClosed_iSup_iff.2 fun i ↦ ?_⟩ letI := t i exact IsSeqClosed.isClosed fun u x hus hux ↦ hs hus <| hux.mono_right <| nhds_mono <| le_iSup _ _ protected theorem SequentialSpace.sup {X} {t₁ t₂ : TopologicalSpace X} (h₁ : @SequentialSpace X t₁) (h₂ : @SequentialSpace X t₂) : @SequentialSpace X (t₁ ⊔ t₂) := by rw [sup_eq_iSup] exact .iSup <| Bool.forall_bool.2 ⟨h₂, h₁⟩ theorem QuotientMap.sequentialSpace [SequentialSpace X] {f : X → Y} (hf : QuotientMap f) : SequentialSpace Y := hf.2.symm ▸ .coinduced f /-- The quotient of a sequential space is a sequential space. -/ instance Quotient.instSequentialSpace [SequentialSpace X] {s : Setoid X} : SequentialSpace (Quotient s) := quotientMap_quot_mk.sequentialSpace /-- The sum (disjoint union) of two sequential spaces is a sequential space. -/ instance Sum.instSequentialSpace [SequentialSpace X] [SequentialSpace Y] : SequentialSpace (X ⊕ Y) := .sup (.coinduced Sum.inl) (.coinduced Sum.inr) /-- The disjoint union of an indexed family of sequential spaces is a sequential space. -/ instance Sigma.instSequentialSpace {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, SequentialSpace (X i)] : SequentialSpace (Σ i, X i) := .iSup fun _ ↦ .coinduced _ end TopologicalSpace section SeqCompact open TopologicalSpace FirstCountableTopology variable [TopologicalSpace X] theorem IsSeqCompact.subseq_of_frequently_in {s : Set X} (hs : IsSeqCompact s) {x : ℕ → X} (hx : ∃ᶠ n in atTop, x n ∈ s) : ∃ a ∈ s, ∃ φ : ℕ → ℕ, StrictMono φ ∧ Tendsto (x ∘ φ) atTop (𝓝 a) := let ⟨ψ, hψ, huψ⟩ := extraction_of_frequently_atTop hx let ⟨a, a_in, φ, hφ, h⟩ := hs huψ ⟨a, a_in, ψ ∘ φ, hψ.comp hφ, h⟩ theorem SeqCompactSpace.tendsto_subseq [SeqCompactSpace X] (x : ℕ → X) : ∃ (a : X) (φ : ℕ → ℕ), StrictMono φ ∧ Tendsto (x ∘ φ) atTop (𝓝 a) := let ⟨a, _, φ, mono, h⟩ := isSeqCompact_univ fun n => mem_univ (x n) ⟨a, φ, mono, h⟩ section FirstCountableTopology variable [FirstCountableTopology X] open FirstCountableTopology protected theorem IsCompact.isSeqCompact {s : Set X} (hs : IsCompact s) : IsSeqCompact s := fun _x x_in => let ⟨a, a_in, ha⟩ := hs (tendsto_principal.mpr (eventually_of_forall x_in)) ⟨a, a_in, tendsto_subseq ha⟩ theorem IsCompact.tendsto_subseq' {s : Set X} {x : ℕ → X} (hs : IsCompact s) (hx : ∃ᶠ n in atTop, x n ∈ s) : ∃ a ∈ s, ∃ φ : ℕ → ℕ, StrictMono φ ∧ Tendsto (x ∘ φ) atTop (𝓝 a) := hs.isSeqCompact.subseq_of_frequently_in hx theorem IsCompact.tendsto_subseq {s : Set X} {x : ℕ → X} (hs : IsCompact s) (hx : ∀ n, x n ∈ s) : ∃ a ∈ s, ∃ φ : ℕ → ℕ, StrictMono φ ∧ Tendsto (x ∘ φ) atTop (𝓝 a) := hs.isSeqCompact hx -- see Note [lower instance priority] instance (priority := 100) FirstCountableTopology.seq_compact_of_compact [CompactSpace X] : SeqCompactSpace X := ⟨isCompact_univ.isSeqCompact⟩ theorem CompactSpace.tendsto_subseq [CompactSpace X] (x : ℕ → X) : ∃ (a : _) (φ : ℕ → ℕ), StrictMono φ ∧ Tendsto (x ∘ φ) atTop (𝓝 a) := SeqCompactSpace.tendsto_subseq x end FirstCountableTopology section Image variable [TopologicalSpace Y] {f : X → Y} /-- Sequential compactness of sets is preserved under sequentially continuous functions. -/ theorem IsSeqCompact.image (f_cont : SeqContinuous f) {K : Set X} (K_cpt : IsSeqCompact K) : IsSeqCompact (f '' K) := by intro ys ys_in_fK choose xs xs_in_K fxs_eq_ys using ys_in_fK obtain ⟨a, a_in_K, phi, phi_mono, xs_phi_lim⟩ := K_cpt xs_in_K refine ⟨f a, mem_image_of_mem f a_in_K, phi, phi_mono, ?_⟩ exact (f_cont xs_phi_lim).congr fun x ↦ fxs_eq_ys (phi x) /-- The range of sequentially continuous function on a sequentially compact space is sequentially compact. -/ theorem IsSeqCompact.range [SeqCompactSpace X] (f_cont : SeqContinuous f) : IsSeqCompact (Set.range f) := by simpa using isSeqCompact_univ.image f_cont end Image end SeqCompact section UniformSpaceSeqCompact open uniformity open UniformSpace Prod variable [UniformSpace X] {s : Set X} theorem IsSeqCompact.exists_tendsto_of_frequently_mem (hs : IsSeqCompact s) {u : ℕ → X} (hu : ∃ᶠ n in atTop, u n ∈ s) (huc : CauchySeq u) : ∃ x ∈ s, Tendsto u atTop (𝓝 x) := let ⟨x, hxs, _φ, φ_mono, hx⟩ := hs.subseq_of_frequently_in hu ⟨x, hxs, tendsto_nhds_of_cauchySeq_of_subseq huc φ_mono.tendsto_atTop hx⟩ theorem IsSeqCompact.exists_tendsto (hs : IsSeqCompact s) {u : ℕ → X} (hu : ∀ n, u n ∈ s) (huc : CauchySeq u) : ∃ x ∈ s, Tendsto u atTop (𝓝 x) := hs.exists_tendsto_of_frequently_mem (frequently_of_forall hu) huc /-- A sequentially compact set in a uniform space is totally bounded. -/ protected theorem IsSeqCompact.totallyBounded (h : IsSeqCompact s) : TotallyBounded s := by intro V V_in unfold IsSeqCompact at h contrapose! h obtain ⟨u, u_in, hu⟩ : ∃ u : ℕ → X, (∀ n, u n ∈ s) ∧ ∀ n m, m < n → u m ∉ ball (u n) V := by simp only [not_subset, mem_iUnion₂, not_exists, exists_prop] at h simpa only [forall_and, forall_mem_image, not_and] using seq_of_forall_finite_exists h refine ⟨u, u_in, fun x _ φ hφ huφ => ?_⟩ obtain ⟨N, hN⟩ : ∃ N, ∀ p q, p ≥ N → q ≥ N → (u (φ p), u (φ q)) ∈ V := huφ.cauchySeq.mem_entourage V_in exact hu (φ <| N + 1) (φ N) (hφ <| lt_add_one N) (hN (N + 1) N N.le_succ le_rfl) variable [IsCountablyGenerated (𝓤 X)] /-- A sequentially compact set in a uniform set with countably generated uniformity filter is complete. -/ protected theorem IsSeqCompact.isComplete (hs : IsSeqCompact s) : IsComplete s := fun l hl hls => by have := hl.1 rcases exists_antitone_basis (𝓤 X) with ⟨V, hV⟩ choose W hW hWV using fun n => comp_mem_uniformity_sets (hV.mem n) have hWV' : ∀ n, W n ⊆ V n := fun n ⟨x, y⟩ hx => @hWV n (x, y) ⟨x, refl_mem_uniformity <| hW _, hx⟩ obtain ⟨t, ht_anti, htl, htW, hts⟩ : ∃ t : ℕ → Set X, Antitone t ∧ (∀ n, t n ∈ l) ∧ (∀ n, t n ×ˢ t n ⊆ W n) ∧ ∀ n, t n ⊆ s := by have : ∀ n, ∃ t ∈ l, t ×ˢ t ⊆ W n ∧ t ⊆ s := by rw [le_principal_iff] at hls have : ∀ n, W n ∩ s ×ˢ s ∈ l ×ˢ l := fun n => inter_mem (hl.2 (hW n)) (prod_mem_prod hls hls) simpa only [l.basis_sets.prod_self.mem_iff, true_imp_iff, subset_inter_iff, prod_self_subset_prod_self, and_assoc] using this choose t htl htW hts using this have : ∀ n : ℕ, ⋂ k ≤ n, t k ⊆ t n := fun n => by apply iInter₂_subset; rfl exact ⟨fun n => ⋂ k ≤ n, t k, fun m n h => biInter_subset_biInter_left fun k (hk : k ≤ m) => hk.trans h, fun n => (biInter_mem (finite_le_nat n)).2 fun k _ => htl k, fun n => (prod_mono (this n) (this n)).trans (htW n), fun n => (this n).trans (hts n)⟩ choose u hu using fun n => Filter.nonempty_of_mem (htl n) have huc : CauchySeq u := hV.toHasBasis.cauchySeq_iff.2 fun N _ => ⟨N, fun m hm n hn => hWV' _ <| @htW N (_, _) ⟨ht_anti hm (hu _), ht_anti hn (hu _)⟩⟩ rcases hs.exists_tendsto (fun n => hts n (hu n)) huc with ⟨x, hxs, hx⟩ refine ⟨x, hxs, (nhds_basis_uniformity' hV.toHasBasis).ge_iff.2 fun N _ => ?_⟩ obtain ⟨n, hNn, hn⟩ : ∃ n, N ≤ n ∧ u n ∈ ball x (W N) := ((eventually_ge_atTop N).and (hx <| ball_mem_nhds x (hW N))).exists refine mem_of_superset (htl n) fun y hy => hWV N ⟨u n, hn, htW N ?_⟩ exact ⟨ht_anti hNn (hu n), ht_anti hNn hy⟩ /-- If `𝓤 β` is countably generated, then any sequentially compact set is compact. -/ protected theorem IsSeqCompact.isCompact (hs : IsSeqCompact s) : IsCompact s := isCompact_iff_totallyBounded_isComplete.2 ⟨hs.totallyBounded, hs.isComplete⟩ /-- A version of Bolzano-Weierstrass: in a uniform space with countably generated uniformity filter (e.g., in a metric space), a set is compact if and only if it is sequentially compact. -/ protected theorem UniformSpace.isCompact_iff_isSeqCompact : IsCompact s ↔ IsSeqCompact s := ⟨fun H => H.isSeqCompact, fun H => H.isCompact⟩ theorem UniformSpace.compactSpace_iff_seqCompactSpace : CompactSpace X ↔ SeqCompactSpace X := by simp only [← isCompact_univ_iff, seqCompactSpace_iff, UniformSpace.isCompact_iff_isSeqCompact] end UniformSpaceSeqCompact
Topology\ShrinkingLemma.lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Reid Barton -/ import Mathlib.Topology.Separation /-! # The shrinking lemma In this file we prove a few versions of the shrinking lemma. The lemma says that in a normal topological space a point finite open covering can be “shrunk”: for a point finite open covering `u : ι → Set X` there exists a refinement `v : ι → Set X` such that `closure (v i) ⊆ u i`. For finite or countable coverings this lemma can be proved without the axiom of choice, see [ncatlab](https://ncatlab.org/nlab/show/shrinking+lemma) for details. We only formalize the most general result that works for any covering but needs the axiom of choice. We prove two versions of the lemma: * `exists_subset_iUnion_closure_subset` deals with a covering of a closed set in a normal space; * `exists_iUnion_eq_closure_subset` deals with a covering of the whole space. ## Tags normal space, shrinking lemma -/ open Set Function noncomputable section variable {ι X : Type*} [TopologicalSpace X] namespace ShrinkingLemma -- the trivial refinement needs `u` to be a covering /-- Auxiliary definition for the proof of the shrinking lemma. A partial refinement of a covering `⋃ i, u i` of a set `s` is a map `v : ι → Set X` and a set `carrier : Set ι` such that * `s ⊆ ⋃ i, v i`; * all `v i` are open; * if `i ∈ carrier v`, then `closure (v i) ⊆ u i`; * if `i ∉ carrier`, then `v i = u i`. This type is equipped with the following partial order: `v ≤ v'` if `v.carrier ⊆ v'.carrier` and `v i = v' i` for `i ∈ v.carrier`. We will use Zorn's lemma to prove that this type has a maximal element, then show that the maximal element must have `carrier = univ`. -/ -- Porting note(#5171): this linter isn't ported yet. @[nolint has_nonempty_instance] @[ext] structure PartialRefinement (u : ι → Set X) (s : Set X) where /-- A family of sets that form a partial refinement of `u`. -/ toFun : ι → Set X /-- The set of indexes `i` such that `i`-th set is already shrunk. -/ carrier : Set ι /-- Each set from the partially refined family is open. -/ protected isOpen : ∀ i, IsOpen (toFun i) /-- The partially refined family still covers the set. -/ subset_iUnion : s ⊆ ⋃ i, toFun i /-- For each `i ∈ carrier`, the original set includes the closure of the refined set. -/ closure_subset : ∀ {i}, i ∈ carrier → closure (toFun i) ⊆ u i /-- Sets that correspond to `i ∉ carrier` are not modified. -/ apply_eq : ∀ {i}, i ∉ carrier → toFun i = u i namespace PartialRefinement variable {u : ι → Set X} {s : Set X} instance : CoeFun (PartialRefinement u s) fun _ => ι → Set X := ⟨toFun⟩ protected theorem subset (v : PartialRefinement u s) (i : ι) : v i ⊆ u i := by classical exact if h : i ∈ v.carrier then subset_closure.trans (v.closure_subset h) else (v.apply_eq h).le open Classical in instance : PartialOrder (PartialRefinement u s) where le v₁ v₂ := v₁.carrier ⊆ v₂.carrier ∧ ∀ i ∈ v₁.carrier, v₁ i = v₂ i le_refl v := ⟨Subset.refl _, fun _ _ => rfl⟩ le_trans v₁ v₂ v₃ h₁₂ h₂₃ := ⟨Subset.trans h₁₂.1 h₂₃.1, fun i hi => (h₁₂.2 i hi).trans (h₂₃.2 i <| h₁₂.1 hi)⟩ le_antisymm v₁ v₂ h₁₂ h₂₁ := have hc : v₁.carrier = v₂.carrier := Subset.antisymm h₁₂.1 h₂₁.1 PartialRefinement.ext (funext fun x => if hx : x ∈ v₁.carrier then h₁₂.2 _ hx else (v₁.apply_eq hx).trans (Eq.symm <| v₂.apply_eq <| hc ▸ hx)) hc /-- If two partial refinements `v₁`, `v₂` belong to a chain (hence, they are comparable) and `i` belongs to the carriers of both partial refinements, then `v₁ i = v₂ i`. -/ theorem apply_eq_of_chain {c : Set (PartialRefinement u s)} (hc : IsChain (· ≤ ·) c) {v₁ v₂} (h₁ : v₁ ∈ c) (h₂ : v₂ ∈ c) {i} (hi₁ : i ∈ v₁.carrier) (hi₂ : i ∈ v₂.carrier) : v₁ i = v₂ i := (hc.total h₁ h₂).elim (fun hle => hle.2 _ hi₁) (fun hle => (hle.2 _ hi₂).symm) /-- The carrier of the least upper bound of a non-empty chain of partial refinements is the union of their carriers. -/ def chainSupCarrier (c : Set (PartialRefinement u s)) : Set ι := ⋃ v ∈ c, carrier v open Classical in /-- Choice of an element of a nonempty chain of partial refinements. If `i` belongs to one of `carrier v`, `v ∈ c`, then `find c ne i` is one of these partial refinements. -/ def find (c : Set (PartialRefinement u s)) (ne : c.Nonempty) (i : ι) : PartialRefinement u s := if hi : ∃ v ∈ c, i ∈ carrier v then hi.choose else ne.some theorem find_mem {c : Set (PartialRefinement u s)} (i : ι) (ne : c.Nonempty) : find c ne i ∈ c := by rw [find] split_ifs with h exacts [h.choose_spec.1, ne.some_mem] theorem mem_find_carrier_iff {c : Set (PartialRefinement u s)} {i : ι} (ne : c.Nonempty) : i ∈ (find c ne i).carrier ↔ i ∈ chainSupCarrier c := by rw [find] split_ifs with h · have := h.choose_spec exact iff_of_true this.2 (mem_iUnion₂.2 ⟨_, this.1, this.2⟩) · push_neg at h refine iff_of_false (h _ ne.some_mem) ?_ simpa only [chainSupCarrier, mem_iUnion₂, not_exists] theorem find_apply_of_mem {c : Set (PartialRefinement u s)} (hc : IsChain (· ≤ ·) c) (ne : c.Nonempty) {i v} (hv : v ∈ c) (hi : i ∈ carrier v) : find c ne i i = v i := apply_eq_of_chain hc (find_mem _ _) hv ((mem_find_carrier_iff _).2 <| mem_iUnion₂.2 ⟨v, hv, hi⟩) hi /-- Least upper bound of a nonempty chain of partial refinements. -/ def chainSup (c : Set (PartialRefinement u s)) (hc : IsChain (· ≤ ·) c) (ne : c.Nonempty) (hfin : ∀ x ∈ s, { i | x ∈ u i }.Finite) (hU : s ⊆ ⋃ i, u i) : PartialRefinement u s where toFun i := find c ne i i carrier := chainSupCarrier c isOpen i := (find _ _ _).isOpen i subset_iUnion x hxs := mem_iUnion.2 <| by rcases em (∃ i, i ∉ chainSupCarrier c ∧ x ∈ u i) with (⟨i, hi, hxi⟩ | hx) · use i simpa only [(find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi)] · simp_rw [not_exists, not_and, not_imp_not, chainSupCarrier, mem_iUnion₂] at hx haveI : Nonempty (PartialRefinement u s) := ⟨ne.some⟩ choose! v hvc hiv using hx rcases (hfin x hxs).exists_maximal_wrt v _ (mem_iUnion.1 (hU hxs)) with ⟨i, hxi : x ∈ u i, hmax : ∀ j, x ∈ u j → v i ≤ v j → v i = v j⟩ rcases mem_iUnion.1 ((v i).subset_iUnion hxs) with ⟨j, hj⟩ use j have hj' : x ∈ u j := (v i).subset _ hj have : v j ≤ v i := (hc.total (hvc _ hxi) (hvc _ hj')).elim (fun h => (hmax j hj' h).ge) id simpa only [find_apply_of_mem hc ne (hvc _ hxi) (this.1 <| hiv _ hj')] closure_subset hi := (find c ne _).closure_subset ((mem_find_carrier_iff _).2 hi) apply_eq hi := (find c ne _).apply_eq (mt (mem_find_carrier_iff _).1 hi) /-- `chainSup hu c hc ne hfin hU` is an upper bound of the chain `c`. -/ theorem le_chainSup {c : Set (PartialRefinement u s)} (hc : IsChain (· ≤ ·) c) (ne : c.Nonempty) (hfin : ∀ x ∈ s, { i | x ∈ u i }.Finite) (hU : s ⊆ ⋃ i, u i) {v} (hv : v ∈ c) : v ≤ chainSup c hc ne hfin hU := ⟨fun _ hi => mem_biUnion hv hi, fun _ hi => (find_apply_of_mem hc _ hv hi).symm⟩ /-- If `s` is a closed set, `v` is a partial refinement, and `i` is an index such that `i ∉ v.carrier`, then there exists a partial refinement that is strictly greater than `v`. -/ theorem exists_gt [NormalSpace X] (v : PartialRefinement u s) (hs : IsClosed s) (i : ι) (hi : i ∉ v.carrier) : ∃ v' : PartialRefinement u s, v < v' := by have I : (s ∩ ⋂ (j) (_ : j ≠ i), (v j)ᶜ) ⊆ v i := by simp only [subset_def, mem_inter_iff, mem_iInter, and_imp] intro x hxs H rcases mem_iUnion.1 (v.subset_iUnion hxs) with ⟨j, hj⟩ exact (em (j = i)).elim (fun h => h ▸ hj) fun h => (H j h hj).elim have C : IsClosed (s ∩ ⋂ (j) (_ : j ≠ i), (v j)ᶜ) := IsClosed.inter hs (isClosed_biInter fun _ _ => isClosed_compl_iff.2 <| v.isOpen _) rcases normal_exists_closure_subset C (v.isOpen i) I with ⟨vi, ovi, hvi, cvi⟩ classical refine ⟨⟨update v i vi, insert i v.carrier, ?_, ?_, ?_, ?_⟩, ?_, ?_⟩ · intro j rcases eq_or_ne j i with (rfl| hne) <;> simp [*, v.isOpen] · refine fun x hx => mem_iUnion.2 ?_ rcases em (∃ j ≠ i, x ∈ v j) with (⟨j, hji, hj⟩ | h) · use j rwa [update_noteq hji] · push_neg at h use i rw [update_same] exact hvi ⟨hx, mem_biInter h⟩ · rintro j (rfl | hj) · rwa [update_same, ← v.apply_eq hi] · rw [update_noteq (ne_of_mem_of_not_mem hj hi)] exact v.closure_subset hj · intro j hj rw [mem_insert_iff, not_or] at hj rw [update_noteq hj.1, v.apply_eq hj.2] · refine ⟨subset_insert _ _, fun j hj => ?_⟩ exact (update_noteq (ne_of_mem_of_not_mem hj hi) _ _).symm · exact fun hle => hi (hle.1 <| mem_insert _ _) end PartialRefinement end ShrinkingLemma open ShrinkingLemma variable {u : ι → Set X} {s : Set X} [NormalSpace X] /-- **Shrinking lemma**. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ theorem exists_subset_iUnion_closure_subset (hs : IsClosed s) (uo : ∀ i, IsOpen (u i)) (uf : ∀ x ∈ s, { i | x ∈ u i }.Finite) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → Set X, s ⊆ iUnion v ∧ (∀ i, IsOpen (v i)) ∧ ∀ i, closure (v i) ⊆ u i := by haveI : Nonempty (PartialRefinement u s) := ⟨⟨u, ∅, uo, us, False.elim, fun _ => rfl⟩⟩ have : ∀ c : Set (PartialRefinement u s), IsChain (· ≤ ·) c → c.Nonempty → ∃ ub, ∀ v ∈ c, v ≤ ub := fun c hc ne => ⟨.chainSup c hc ne uf us, fun v hv => PartialRefinement.le_chainSup _ _ _ _ hv⟩ rcases zorn_nonempty_partialOrder this with ⟨v, hv⟩ suffices ∀ i, i ∈ v.carrier from ⟨v, v.subset_iUnion, fun i => v.isOpen _, fun i => v.closure_subset (this i)⟩ contrapose! hv rcases hv with ⟨i, hi⟩ rcases v.exists_gt hs i hi with ⟨v', hlt⟩ exact ⟨v', hlt.le, hlt.ne'⟩ /-- **Shrinking lemma**. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each new closed set is contained in the corresponding original open set. See also `exists_subset_iUnion_closure_subset` for a stronger statement. -/ theorem exists_subset_iUnion_closed_subset (hs : IsClosed s) (uo : ∀ i, IsOpen (u i)) (uf : ∀ x ∈ s, { i | x ∈ u i }.Finite) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → Set X, s ⊆ iUnion v ∧ (∀ i, IsClosed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, hsv, _, hv⟩ := exists_subset_iUnion_closure_subset hs uo uf us ⟨fun i => closure (v i), Subset.trans hsv (iUnion_mono fun _ => subset_closure), fun _ => isClosed_closure, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ theorem exists_iUnion_eq_closure_subset (uo : ∀ i, IsOpen (u i)) (uf : ∀ x, { i | x ∈ u i }.Finite) (uU : ⋃ i, u i = univ) : ∃ v : ι → Set X, iUnion v = univ ∧ (∀ i, IsOpen (v i)) ∧ ∀ i, closure (v i) ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_iUnion_closure_subset isClosed_univ uo (fun x _ => uf x) uU.ge ⟨v, univ_subset_iff.1 vU, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each of the new closed sets is contained in the corresponding original open set. See also `exists_iUnion_eq_closure_subset` for a stronger statement. -/ theorem exists_iUnion_eq_closed_subset (uo : ∀ i, IsOpen (u i)) (uf : ∀ x, { i | x ∈ u i }.Finite) (uU : ⋃ i, u i = univ) : ∃ v : ι → Set X, iUnion v = univ ∧ (∀ i, IsClosed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_iUnion_closed_subset isClosed_univ uo (fun x _ => uf x) uU.ge ⟨v, univ_subset_iff.1 vU, hv⟩
Topology\Sober.lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Topology.Separation import Mathlib.Topology.Sets.Closeds /-! # Sober spaces A quasi-sober space is a topological space where every irreducible closed subset has a generic point. A sober space is a quasi-sober space where every irreducible closed subset has a *unique* generic point. This is if and only if the space is T0, and thus sober spaces can be stated via `[QuasiSober α] [T0Space α]`. ## Main definition * `IsGenericPoint` : `x` is the generic point of `S` if `S` is the closure of `x`. * `QuasiSober` : A space is quasi-sober if every irreducible closed subset has a generic point. -/ open Set variable {α β : Type*} [TopologicalSpace α] [TopologicalSpace β] section genericPoint /-- `x` is a generic point of `S` if `S` is the closure of `x`. -/ def IsGenericPoint (x : α) (S : Set α) : Prop := closure ({x} : Set α) = S theorem isGenericPoint_def {x : α} {S : Set α} : IsGenericPoint x S ↔ closure ({x} : Set α) = S := Iff.rfl theorem IsGenericPoint.def {x : α} {S : Set α} (h : IsGenericPoint x S) : closure ({x} : Set α) = S := h theorem isGenericPoint_closure {x : α} : IsGenericPoint x (closure ({x} : Set α)) := refl _ variable {x y : α} {S U Z : Set α} theorem isGenericPoint_iff_specializes : IsGenericPoint x S ↔ ∀ y, x ⤳ y ↔ y ∈ S := by simp only [specializes_iff_mem_closure, IsGenericPoint, Set.ext_iff] namespace IsGenericPoint theorem specializes_iff_mem (h : IsGenericPoint x S) : x ⤳ y ↔ y ∈ S := isGenericPoint_iff_specializes.1 h y protected theorem specializes (h : IsGenericPoint x S) (h' : y ∈ S) : x ⤳ y := h.specializes_iff_mem.2 h' protected theorem mem (h : IsGenericPoint x S) : x ∈ S := h.specializes_iff_mem.1 specializes_rfl protected theorem isClosed (h : IsGenericPoint x S) : IsClosed S := h.def ▸ isClosed_closure protected theorem isIrreducible (h : IsGenericPoint x S) : IsIrreducible S := h.def ▸ isIrreducible_singleton.closure protected theorem inseparable (h : IsGenericPoint x S) (h' : IsGenericPoint y S) : Inseparable x y := (h.specializes h'.mem).antisymm (h'.specializes h.mem) /-- In a T₀ space, each set has at most one generic point. -/ protected theorem eq [T0Space α] (h : IsGenericPoint x S) (h' : IsGenericPoint y S) : x = y := (h.inseparable h').eq theorem mem_open_set_iff (h : IsGenericPoint x S) (hU : IsOpen U) : x ∈ U ↔ (S ∩ U).Nonempty := ⟨fun h' => ⟨x, h.mem, h'⟩, fun ⟨_y, hyS, hyU⟩ => (h.specializes hyS).mem_open hU hyU⟩ theorem disjoint_iff (h : IsGenericPoint x S) (hU : IsOpen U) : Disjoint S U ↔ x ∉ U := by rw [h.mem_open_set_iff hU, ← not_disjoint_iff_nonempty_inter, Classical.not_not] theorem mem_closed_set_iff (h : IsGenericPoint x S) (hZ : IsClosed Z) : x ∈ Z ↔ S ⊆ Z := by rw [← h.def, hZ.closure_subset_iff, singleton_subset_iff] protected theorem image (h : IsGenericPoint x S) {f : α → β} (hf : Continuous f) : IsGenericPoint (f x) (closure (f '' S)) := by rw [isGenericPoint_def, ← h.def, ← image_singleton, closure_image_closure hf] end IsGenericPoint theorem isGenericPoint_iff_forall_closed (hS : IsClosed S) (hxS : x ∈ S) : IsGenericPoint x S ↔ ∀ Z : Set α, IsClosed Z → x ∈ Z → S ⊆ Z := by have : closure {x} ⊆ S := closure_minimal (singleton_subset_iff.2 hxS) hS simp_rw [IsGenericPoint, subset_antisymm_iff, this, true_and_iff, closure, subset_sInter_iff, mem_setOf_eq, and_imp, singleton_subset_iff] end genericPoint section Sober /-- A space is sober if every irreducible closed subset has a generic point. -/ @[mk_iff] class QuasiSober (α : Type*) [TopologicalSpace α] : Prop where sober : ∀ {S : Set α}, IsIrreducible S → IsClosed S → ∃ x, IsGenericPoint x S /-- A generic point of the closure of an irreducible space. -/ noncomputable def IsIrreducible.genericPoint [QuasiSober α] {S : Set α} (hS : IsIrreducible S) : α := (QuasiSober.sober hS.closure isClosed_closure).choose theorem IsIrreducible.genericPoint_spec [QuasiSober α] {S : Set α} (hS : IsIrreducible S) : IsGenericPoint hS.genericPoint (closure S) := (QuasiSober.sober hS.closure isClosed_closure).choose_spec @[simp] theorem IsIrreducible.genericPoint_closure_eq [QuasiSober α] {S : Set α} (hS : IsIrreducible S) : closure ({hS.genericPoint} : Set α) = closure S := hS.genericPoint_spec variable (α) /-- A generic point of a sober irreducible space. -/ noncomputable def genericPoint [QuasiSober α] [IrreducibleSpace α] : α := (IrreducibleSpace.isIrreducible_univ α).genericPoint theorem genericPoint_spec [QuasiSober α] [IrreducibleSpace α] : IsGenericPoint (genericPoint α) ⊤ := by simpa using (IrreducibleSpace.isIrreducible_univ α).genericPoint_spec @[simp] theorem genericPoint_closure [QuasiSober α] [IrreducibleSpace α] : closure ({genericPoint α} : Set α) = ⊤ := genericPoint_spec α variable {α} theorem genericPoint_specializes [QuasiSober α] [IrreducibleSpace α] (x : α) : genericPoint α ⤳ x := (IsIrreducible.genericPoint_spec _).specializes (by simp) attribute [local instance] specializationOrder /-- The closed irreducible subsets of a sober space bijects with the points of the space. -/ noncomputable def irreducibleSetEquivPoints [QuasiSober α] [T0Space α] : TopologicalSpace.IrreducibleCloseds α ≃o α where toFun s := s.2.genericPoint invFun x := ⟨closure ({x} : Set α), isIrreducible_singleton.closure, isClosed_closure⟩ left_inv s := by refine TopologicalSpace.IrreducibleCloseds.ext ?_ simp only [IsIrreducible.genericPoint_closure_eq, TopologicalSpace.IrreducibleCloseds.coe_mk, closure_eq_iff_isClosed.mpr s.3] rfl right_inv x := isIrreducible_singleton.closure.genericPoint_spec.eq (by rw [closure_closure]; exact isGenericPoint_closure) map_rel_iff' := by rintro ⟨s, hs, hs'⟩ ⟨t, ht, ht'⟩ refine specializes_iff_closure_subset.trans ?_ simp [hs'.closure_eq, ht'.closure_eq] rfl theorem ClosedEmbedding.quasiSober {f : α → β} (hf : ClosedEmbedding f) [QuasiSober β] : QuasiSober α where sober hS hS' := by have hS'' := hS.image f hf.continuous.continuousOn obtain ⟨x, hx⟩ := QuasiSober.sober hS'' (hf.isClosedMap _ hS') obtain ⟨y, -, rfl⟩ := hx.mem use y apply image_injective.mpr hf.inj rw [← hx.def, ← hf.closure_image_eq, image_singleton] theorem OpenEmbedding.quasiSober {f : α → β} (hf : OpenEmbedding f) [QuasiSober β] : QuasiSober α where sober hS hS' := by have hS'' := hS.image f hf.continuous.continuousOn obtain ⟨x, hx⟩ := QuasiSober.sober hS''.closure isClosed_closure obtain ⟨T, hT, rfl⟩ := hf.toInducing.isClosed_iff.mp hS' rw [image_preimage_eq_inter_range] at hx hS'' have hxT : x ∈ T := by rw [← hT.closure_eq] exact closure_mono inter_subset_left hx.mem obtain ⟨y, rfl⟩ : x ∈ range f := by rw [hx.mem_open_set_iff hf.isOpen_range] refine Nonempty.mono ?_ hS''.1 simpa using subset_closure use y change _ = _ rw [hf.toEmbedding.closure_eq_preimage_closure_image, image_singleton, show _ = _ from hx] apply image_injective.mpr hf.inj ext z simp only [image_preimage_eq_inter_range, mem_inter_iff, and_congr_left_iff] exact fun hy => ⟨fun h => hT.closure_eq ▸ closure_mono inter_subset_left h, fun h => subset_closure ⟨h, hy⟩⟩ /-- A space is quasi sober if it can be covered by open quasi sober subsets. -/ theorem quasiSober_of_open_cover (S : Set (Set α)) (hS : ∀ s : S, IsOpen (s : Set α)) [hS' : ∀ s : S, QuasiSober s] (hS'' : ⋃₀ S = ⊤) : QuasiSober α := by rw [quasiSober_iff] intro t h h' obtain ⟨x, hx⟩ := h.1 obtain ⟨U, hU, hU'⟩ : x ∈ ⋃₀ S := by rw [hS''] trivial haveI : QuasiSober U := hS' ⟨U, hU⟩ have H : IsPreirreducible ((↑) ⁻¹' t : Set U) := h.2.preimage (hS ⟨U, hU⟩).openEmbedding_subtype_val replace H : IsIrreducible ((↑) ⁻¹' t : Set U) := ⟨⟨⟨x, hU'⟩, by simpa using hx⟩, H⟩ use H.genericPoint have := continuous_subtype_val.closure_preimage_subset _ H.genericPoint_spec.mem rw [h'.closure_eq] at this apply le_antisymm · apply h'.closure_subset_iff.mpr simpa using this rw [← image_singleton, ← closure_image_closure continuous_subtype_val, H.genericPoint_spec.def] refine (subset_closure_inter_of_isPreirreducible_of_isOpen h.2 (hS ⟨U, hU⟩) ⟨x, hx, hU'⟩).trans (closure_mono ?_) rw [inter_comm t, ← Subtype.image_preimage_coe] exact Set.image_subset _ subset_closure /-- Any Hausdorff space is a quasi-sober space because any irreducible set is a singleton. -/ instance (priority := 100) T2Space.quasiSober [T2Space α] : QuasiSober α where sober h _ := by obtain ⟨x, rfl⟩ := isIrreducible_iff_singleton.mp h exact ⟨x, closure_singleton⟩ end Sober
Topology\Specialization.lean
/- Copyright (c) 2023 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Order.Category.Preord import Mathlib.Topology.Category.TopCat.Basic import Mathlib.Topology.ContinuousFunction.Basic import Mathlib.Topology.Separation import Mathlib.Topology.Order.UpperLowerSetTopology /-! # Specialization order This file defines a type synonym for a topological space considered with its specialisation order. -/ open CategoryTheory Topology /-- Type synonym for a topological space considered with its specialisation order. -/ def Specialization (α : Type*) := α namespace Specialization variable {α β γ : Type*} /-- `toEquiv` is the "identity" function to the `Specialization` of a type. -/ @[match_pattern] def toEquiv : α ≃ Specialization α := Equiv.refl _ /-- `ofEquiv` is the identity function from the `Specialization` of a type. -/ @[match_pattern] def ofEquiv : Specialization α ≃ α := Equiv.refl _ @[simp] lemma toEquiv_symm : (@toEquiv α).symm = ofEquiv := rfl @[simp] lemma ofEquiv_symm : (@ofEquiv α).symm = toEquiv := rfl @[simp] lemma toEquiv_ofEquiv (a : Specialization α) : toEquiv (ofEquiv a) = a := rfl @[simp] lemma ofEquiv_toEquiv (a : α) : ofEquiv (toEquiv a) = a := rfl -- The following two are eligible for `dsimp` @[simp, nolint simpNF] lemma toEquiv_inj {a b : α} : toEquiv a = toEquiv b ↔ a = b := Iff.rfl @[simp, nolint simpNF] lemma ofEquiv_inj {a b : Specialization α} : ofEquiv a = ofEquiv b ↔ a = b := Iff.rfl /-- A recursor for `Specialization`. Use as `induction x`. -/ @[elab_as_elim, cases_eliminator, induction_eliminator] protected def rec {β : Specialization α → Sort*} (h : ∀ a, β (toEquiv a)) (a : Specialization α) : β a := h (ofEquiv a) variable [TopologicalSpace α] [TopologicalSpace β] [TopologicalSpace γ] instance instPreorder : Preorder (Specialization α) := specializationPreorder α instance instPartialOrder [T0Space α] : PartialOrder (Specialization α) := specializationOrder α @[simp] lemma toEquiv_le_toEquiv {a b : α} : toEquiv a ≤ toEquiv b ↔ b ⤳ a := Iff.rfl @[simp] lemma ofEquiv_specializes_ofEquiv {a b : Specialization α} : ofEquiv a ⤳ ofEquiv b ↔ b ≤ a := Iff.rfl @[simp] lemma isOpen_toEquiv_preimage [AlexandrovDiscrete α] {s : Set (Specialization α)} : IsOpen (toEquiv ⁻¹' s) ↔ IsUpperSet s := isOpen_iff_forall_specializes.trans forall_swap @[simp] lemma isUpperSet_ofEquiv_preimage [AlexandrovDiscrete α] {s : Set α} : IsUpperSet (ofEquiv ⁻¹' s) ↔ IsOpen s := isOpen_toEquiv_preimage.symm /-- A continuous map between topological spaces induces a monotone map between their specialization orders. -/ def map (f : C(α, β)) : Specialization α →o Specialization β where toFun := toEquiv ∘ f ∘ ofEquiv monotone' := f.continuous.specialization_monotone @[simp] lemma map_id : map (ContinuousMap.id α) = OrderHom.id := rfl @[simp] lemma map_comp (g : C(β, γ)) (f : C(α, β)) : map (g.comp f) = (map g).comp (map f) := rfl end Specialization open Set Specialization WithUpperSet /-- A preorder is isomorphic to the specialisation order of its upper set topology. -/ def orderIsoSpecializationWithUpperSetTopology (α : Type*) [Preorder α] : α ≃o Specialization (WithUpperSet α) where toEquiv := toUpperSet.trans toEquiv map_rel_iff' := by simp /-- An Alexandrov-discrete space is isomorphic to the upper set topology of its specialisation order. -/ def homeoWithUpperSetTopologyorderIso (α : Type*) [TopologicalSpace α] [AlexandrovDiscrete α] : α ≃ₜ WithUpperSet (Specialization α) := (toEquiv.trans toUpperSet).toHomeomorph fun s ↦ by simp [Set.preimage_comp] /-- Sends a topological space to its specialisation order. -/ @[simps] def topToPreord : TopCat ⥤ Preord where obj X := Preord.of <| Specialization X map := Specialization.map
Topology\StoneCech.lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import Mathlib.Topology.Bases import Mathlib.Topology.DenseEmbedding /-! # Stone-Čech compactification Construction of the Stone-Čech compactification using ultrafilters. For any topological space `α`, we build a compact Hausdorff space `StoneCech α` and a continuous map `stoneCechUnit : α → StoneCech α` which is minimal in the sense of the following universal property: for any compact Hausdorff space `β` and every map `f : α → β` such that `hf : Continuous f`, there is a unique map `stoneCechExtend hf : StoneCech α → β` such that `stoneCechExtend_extends : stoneCechExtend hf ∘ stoneCechUnit = f`. Continuity of this extension is asserted by `continuous_stoneCechExtend` and uniqueness by `stoneCech_hom_ext`. Beware that the terminology “extend” is slightly misleading since `stoneCechUnit` is not always injective, so one cannot always think of `α` as being “inside” its compactification `StoneCech α`. ## Implementation notes Parts of the formalization are based on “Ultrafilters and Topology” by Marius Stekelenburg, particularly section 5. However the construction in the general case is different because the equivalence relation on spaces of ultrafilters described by Stekelenburg causes issues with universes since it involves a condition on all compact Hausdorff spaces. We replace it by a two steps construction. The first step called `PreStoneCech` guarantees the expected universal property but not the Hausdorff condition. We then define `StoneCech α` as `t2Quotient (PreStoneCech α)`. -/ noncomputable section open Filter Set open Topology universe u v section Ultrafilter /- The set of ultrafilters on α carries a natural topology which makes it the Stone-Čech compactification of α (viewed as a discrete space). -/ /-- Basis for the topology on `Ultrafilter α`. -/ def ultrafilterBasis (α : Type u) : Set (Set (Ultrafilter α)) := range fun s : Set α ↦ { u | s ∈ u } variable {α : Type u} instance Ultrafilter.topologicalSpace : TopologicalSpace (Ultrafilter α) := TopologicalSpace.generateFrom (ultrafilterBasis α) theorem ultrafilterBasis_is_basis : TopologicalSpace.IsTopologicalBasis (ultrafilterBasis α) := ⟨by rintro _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩ refine ⟨_, ⟨a ∩ b, rfl⟩, inter_mem ua ub, fun v hv ↦ ⟨?_, ?_⟩⟩ <;> apply mem_of_superset hv <;> simp [inter_subset_right], eq_univ_of_univ_subset <| subset_sUnion_of_mem <| ⟨univ, eq_univ_of_forall fun _ ↦ univ_mem⟩, rfl⟩ /-- The basic open sets for the topology on ultrafilters are open. -/ theorem ultrafilter_isOpen_basic (s : Set α) : IsOpen { u : Ultrafilter α | s ∈ u } := ultrafilterBasis_is_basis.isOpen ⟨s, rfl⟩ /-- The basic open sets for the topology on ultrafilters are also closed. -/ theorem ultrafilter_isClosed_basic (s : Set α) : IsClosed { u : Ultrafilter α | s ∈ u } := by rw [← isOpen_compl_iff] convert ultrafilter_isOpen_basic sᶜ using 1 ext u exact Ultrafilter.compl_mem_iff_not_mem.symm /-- Every ultrafilter `u` on `Ultrafilter α` converges to a unique point of `Ultrafilter α`, namely `joinM u`. -/ theorem ultrafilter_converges_iff {u : Ultrafilter (Ultrafilter α)} {x : Ultrafilter α} : ↑u ≤ 𝓝 x ↔ x = joinM u := by rw [eq_comm, ← Ultrafilter.coe_le_coe] change ↑u ≤ 𝓝 x ↔ ∀ s ∈ x, { v : Ultrafilter α | s ∈ v } ∈ u simp only [TopologicalSpace.nhds_generateFrom, le_iInf_iff, ultrafilterBasis, le_principal_iff, mem_setOf_eq] constructor · intro h a ha exact h _ ⟨ha, a, rfl⟩ · rintro h a ⟨xi, a, rfl⟩ exact h _ xi instance ultrafilter_compact : CompactSpace (Ultrafilter α) := ⟨isCompact_iff_ultrafilter_le_nhds.mpr fun f _ ↦ ⟨joinM f, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩ instance Ultrafilter.t2Space : T2Space (Ultrafilter α) := t2_iff_ultrafilter.mpr fun {x y} f fx fy ↦ have hx : x = joinM f := ultrafilter_converges_iff.mp fx have hy : y = joinM f := ultrafilter_converges_iff.mp fy hx.trans hy.symm instance : TotallyDisconnectedSpace (Ultrafilter α) := by rw [totallyDisconnectedSpace_iff_connectedComponent_singleton] intro A simp only [Set.eq_singleton_iff_unique_mem, mem_connectedComponent, true_and_iff] intro B hB rw [← Ultrafilter.coe_le_coe] intro s hs rw [connectedComponent_eq_iInter_isClopen, Set.mem_iInter] at hB let Z := { F : Ultrafilter α | s ∈ F } have hZ : IsClopen Z := ⟨ultrafilter_isClosed_basic s, ultrafilter_isOpen_basic s⟩ exact hB ⟨Z, hZ, hs⟩ @[simp] theorem Ultrafilter.tendsto_pure_self (b : Ultrafilter α) : Tendsto pure b (𝓝 b) := by rw [Tendsto, ← coe_map, ultrafilter_converges_iff] ext s change s ∈ b ↔ {t | s ∈ t} ∈ map pure b simp_rw [mem_map, preimage_setOf_eq, mem_pure, setOf_mem_eq] theorem ultrafilter_comap_pure_nhds (b : Ultrafilter α) : comap pure (𝓝 b) ≤ b := by rw [TopologicalSpace.nhds_generateFrom] simp only [comap_iInf, comap_principal] intro s hs rw [← le_principal_iff] refine iInf_le_of_le { u | s ∈ u } ?_ refine iInf_le_of_le ⟨hs, ⟨s, rfl⟩⟩ ?_ exact principal_mono.2 fun _ ↦ id section Embedding theorem ultrafilter_pure_injective : Function.Injective (pure : α → Ultrafilter α) := by intro x y h have : {x} ∈ (pure x : Ultrafilter α) := singleton_mem_pure rw [h] at this exact (mem_singleton_iff.mp (mem_pure.mp this)).symm open TopologicalSpace /-- The range of `pure : α → Ultrafilter α` is dense in `Ultrafilter α`. -/ theorem denseRange_pure : DenseRange (pure : α → Ultrafilter α) := fun x ↦ mem_closure_iff_ultrafilter.mpr ⟨x.map pure, range_mem_map, ultrafilter_converges_iff.mpr (bind_pure x).symm⟩ /-- The map `pure : α → Ultrafilter α` induces on `α` the discrete topology. -/ theorem induced_topology_pure : TopologicalSpace.induced (pure : α → Ultrafilter α) Ultrafilter.topologicalSpace = ⊥ := by apply eq_bot_of_singletons_open intro x use { u : Ultrafilter α | {x} ∈ u }, ultrafilter_isOpen_basic _ simp /-- `pure : α → Ultrafilter α` defines a dense inducing of `α` in `Ultrafilter α`. -/ theorem denseInducing_pure : @DenseInducing _ _ ⊥ _ (pure : α → Ultrafilter α) := letI : TopologicalSpace α := ⊥ ⟨⟨induced_topology_pure.symm⟩, denseRange_pure⟩ -- The following refined version will never be used /-- `pure : α → Ultrafilter α` defines a dense embedding of `α` in `Ultrafilter α`. -/ theorem denseEmbedding_pure : @DenseEmbedding _ _ ⊥ _ (pure : α → Ultrafilter α) := letI : TopologicalSpace α := ⊥ { denseInducing_pure with inj := ultrafilter_pure_injective } end Embedding section Extension /- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a unique extension to a continuous function `Ultrafilter α → γ`. We already know it must be unique because `α → Ultrafilter α` is a dense embedding and `γ` is Hausdorff. For existence, we will invoke `DenseInducing.continuous_extend`. -/ variable {γ : Type*} [TopologicalSpace γ] /-- The extension of a function `α → γ` to a function `Ultrafilter α → γ`. When `γ` is a compact Hausdorff space it will be continuous. -/ def Ultrafilter.extend (f : α → γ) : Ultrafilter α → γ := letI : TopologicalSpace α := ⊥ denseInducing_pure.extend f variable [T2Space γ] theorem ultrafilter_extend_extends (f : α → γ) : Ultrafilter.extend f ∘ pure = f := by letI : TopologicalSpace α := ⊥ haveI : DiscreteTopology α := ⟨rfl⟩ exact funext (denseInducing_pure.extend_eq continuous_of_discreteTopology) variable [CompactSpace γ] theorem continuous_ultrafilter_extend (f : α → γ) : Continuous (Ultrafilter.extend f) := by have h (b : Ultrafilter α) : ∃ c, Tendsto f (comap pure (𝓝 b)) (𝓝 c) := -- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ. let ⟨c, _, h'⟩ := isCompact_univ.ultrafilter_le_nhds (b.map f) (by rw [le_principal_iff]; exact univ_mem) ⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h'⟩ let _ : TopologicalSpace α := ⊥ exact denseInducing_pure.continuous_extend h /-- The value of `Ultrafilter.extend f` on an ultrafilter `b` is the unique limit of the ultrafilter `b.map f` in `γ`. -/ theorem ultrafilter_extend_eq_iff {f : α → γ} {b : Ultrafilter α} {c : γ} : Ultrafilter.extend f b = c ↔ ↑(b.map f) ≤ 𝓝 c := ⟨fun h ↦ by -- Write b as an ultrafilter limit of pure ultrafilters, and use -- the facts that ultrafilter.extend is a continuous extension of f. let b' : Ultrafilter (Ultrafilter α) := b.map pure have t : ↑b' ≤ 𝓝 b := ultrafilter_converges_iff.mpr (bind_pure _).symm rw [← h] have := (continuous_ultrafilter_extend f).tendsto b refine le_trans ?_ (le_trans (map_mono t) this) change _ ≤ map (Ultrafilter.extend f ∘ pure) ↑b rw [ultrafilter_extend_extends] exact le_rfl, fun h ↦ let _ : TopologicalSpace α := ⊥ denseInducing_pure.extend_eq_of_tendsto (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩ end Extension end Ultrafilter section PreStoneCech variable (α : Type u) [TopologicalSpace α] /-- Auxilliary construction towards the Stone-Čech compactification of a topological space. It should not be used after the Stone-Čech compactification is constructed. -/ def PreStoneCech : Type u := Quot fun F G : Ultrafilter α ↦ ∃ x, (F : Filter α) ≤ 𝓝 x ∧ (G : Filter α) ≤ 𝓝 x variable {α} instance : TopologicalSpace (PreStoneCech α) := inferInstanceAs (TopologicalSpace <| Quot _) instance : CompactSpace (PreStoneCech α) := Quot.compactSpace instance [Inhabited α] : Inhabited (PreStoneCech α) := inferInstanceAs (Inhabited <| Quot _) /-- The natural map from α to its pre-Stone-Čech compactification. -/ def preStoneCechUnit (x : α) : PreStoneCech α := Quot.mk _ (pure x : Ultrafilter α) theorem continuous_preStoneCechUnit : Continuous (preStoneCechUnit : α → PreStoneCech α) := continuous_iff_ultrafilter.mpr fun x g gx ↦ by have : (g.map pure).toFilter ≤ 𝓝 g := by rw [ultrafilter_converges_iff, ← bind_pure g] rfl have : (map preStoneCechUnit g : Filter (PreStoneCech α)) ≤ 𝓝 (Quot.mk _ g) := (map_mono this).trans (continuous_quot_mk.tendsto _) convert this exact Quot.sound ⟨x, pure_le_nhds x, gx⟩ theorem denseRange_preStoneCechUnit : DenseRange (preStoneCechUnit : α → PreStoneCech α) := (surjective_quot_mk _).denseRange.comp denseRange_pure continuous_coinduced_rng section Extension variable {β : Type v} [TopologicalSpace β] [T2Space β] theorem preStoneCech_hom_ext {g₁ g₂ : PreStoneCech α → β} (h₁ : Continuous g₁) (h₂ : Continuous g₂) (h : g₁ ∘ preStoneCechUnit = g₂ ∘ preStoneCechUnit) : g₁ = g₂ := by apply Continuous.ext_on denseRange_preStoneCechUnit h₁ h₂ rintro x ⟨x, rfl⟩ apply congr_fun h x variable [CompactSpace β] variable {g : α → β} (hg : Continuous g) lemma preStoneCechCompat {F G : Ultrafilter α} {x : α} (hF : ↑F ≤ 𝓝 x) (hG : ↑G ≤ 𝓝 x) : Ultrafilter.extend g F = Ultrafilter.extend g G := by replace hF := (map_mono hF).trans hg.continuousAt replace hG := (map_mono hG).trans hg.continuousAt rwa [show Ultrafilter.extend g G = g x by rwa [ultrafilter_extend_eq_iff, G.coe_map], ultrafilter_extend_eq_iff, F.coe_map] /-- The extension of a continuous function from `α` to a compact Hausdorff space `β` to the pre-Stone-Čech compactification of `α`. -/ def preStoneCechExtend : PreStoneCech α → β := Quot.lift (Ultrafilter.extend g) fun _ _ ⟨_, hF, hG⟩ ↦ preStoneCechCompat hg hF hG theorem preStoneCechExtend_extends : preStoneCechExtend hg ∘ preStoneCechUnit = g := ultrafilter_extend_extends g lemma eq_if_preStoneCechUnit_eq {a b : α} (h : preStoneCechUnit a = preStoneCechUnit b) : g a = g b := by have e := ultrafilter_extend_extends g rw [← congrFun e a, ← congrFun e b, Function.comp_apply, Function.comp_apply] rw [preStoneCechUnit, preStoneCechUnit, Quot.eq] at h generalize (pure a : Ultrafilter α) = F at h generalize (pure b : Ultrafilter α) = G at h induction h with | rel x y a => exact let ⟨a, hx, hy⟩ := a; preStoneCechCompat hg hx hy | refl x => rfl | symm x y _ h => rw [h] | trans x y z _ _ h h' => exact h.trans h' theorem continuous_preStoneCechExtend : Continuous (preStoneCechExtend hg) := continuous_quot_lift _ (continuous_ultrafilter_extend g) end Extension end PreStoneCech section StoneCech variable (α : Type u) [TopologicalSpace α] /-- The Stone-Čech compactification of a topological space. -/ def StoneCech : Type u := t2Quotient (PreStoneCech α) variable {α} instance : TopologicalSpace (StoneCech α) := inferInstanceAs <| TopologicalSpace <| t2Quotient _ instance : T2Space (StoneCech α) := inferInstanceAs <| T2Space <| t2Quotient _ instance : CompactSpace (StoneCech α) := Quot.compactSpace instance [Inhabited α] : Inhabited (StoneCech α) := inferInstanceAs <| Inhabited <| Quotient _ /-- The natural map from α to its Stone-Čech compactification. -/ def stoneCechUnit (x : α) : StoneCech α := t2Quotient.mk (preStoneCechUnit x) theorem continuous_stoneCechUnit : Continuous (stoneCechUnit : α → StoneCech α) := (t2Quotient.continuous_mk _).comp continuous_preStoneCechUnit /-- The image of `stoneCechUnit` is dense. (But `stoneCechUnit` need not be an embedding, for example if the original space is not Hausdorff.) -/ theorem denseRange_stoneCechUnit : DenseRange (stoneCechUnit : α → StoneCech α) := by unfold stoneCechUnit t2Quotient.mk have : Function.Surjective (t2Quotient.mk : PreStoneCech α → StoneCech α) := by exact surjective_quot_mk _ exact this.denseRange.comp denseRange_preStoneCechUnit continuous_coinduced_rng section Extension variable {β : Type v} [TopologicalSpace β] [T2Space β] variable {g : α → β} (hg : Continuous g) theorem stoneCech_hom_ext {g₁ g₂ : StoneCech α → β} (h₁ : Continuous g₁) (h₂ : Continuous g₂) (h : g₁ ∘ stoneCechUnit = g₂ ∘ stoneCechUnit) : g₁ = g₂ := by apply h₁.ext_on denseRange_stoneCechUnit h₂ rintro _ ⟨x, rfl⟩ exact congr_fun h x variable [CompactSpace β] /-- The extension of a continuous function from `α` to a compact Hausdorff space `β` to the Stone-Čech compactification of `α`. This extension implements the universal property of this compactification. -/ def stoneCechExtend : StoneCech α → β := t2Quotient.lift (continuous_preStoneCechExtend hg) theorem stoneCechExtend_extends : stoneCechExtend hg ∘ stoneCechUnit = g := by ext x rw [stoneCechExtend, Function.comp_apply, stoneCechUnit, t2Quotient.lift_mk] apply congrFun (preStoneCechExtend_extends hg) theorem continuous_stoneCechExtend : Continuous (stoneCechExtend hg) := continuous_coinduced_dom.mpr (continuous_preStoneCechExtend hg) lemma eq_if_stoneCechUnit_eq {a b : α} {f : α → β} (hcf : Continuous f) (h : stoneCechUnit a = stoneCechUnit b) : f a = f b := by rw [← congrFun (stoneCechExtend_extends hcf), ← congrFun (stoneCechExtend_extends hcf)] exact congrArg (stoneCechExtend hcf) h end Extension end StoneCech
Topology\Support.lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Patrick Massot -/ import Mathlib.Algebra.GroupWithZero.Indicator import Mathlib.Algebra.Module.Basic import Mathlib.Topology.Separation /-! # The topological support of a function In this file we define the topological support of a function `f`, `tsupport f`, as the closure of the support of `f`. Furthermore, we say that `f` has compact support if the topological support of `f` is compact. ## Main definitions * `mulTSupport` & `tsupport` * `HasCompactMulSupport` & `HasCompactSupport` ## Implementation Notes * We write all lemmas for multiplicative functions, and use `@[to_additive]` to get the more common additive versions. * We do not put the definitions in the `Function` namespace, following many other topological definitions that are in the root namespace (compare `Embedding` vs `Function.Embedding`). -/ open Function Set Filter Topology variable {X α α' β γ δ M E R : Type*} section One variable [One α] [TopologicalSpace X] /-- The topological support of a function is the closure of its support, i.e. the closure of the set of all elements where the function is not equal to 1. -/ @[to_additive " The topological support of a function is the closure of its support. i.e. the closure of the set of all elements where the function is nonzero. "] def mulTSupport (f : X → α) : Set X := closure (mulSupport f) @[to_additive] theorem subset_mulTSupport (f : X → α) : mulSupport f ⊆ mulTSupport f := subset_closure @[to_additive] theorem isClosed_mulTSupport (f : X → α) : IsClosed (mulTSupport f) := isClosed_closure @[to_additive] theorem mulTSupport_eq_empty_iff {f : X → α} : mulTSupport f = ∅ ↔ f = 1 := by rw [mulTSupport, closure_empty_iff, mulSupport_eq_empty_iff] @[to_additive] theorem image_eq_one_of_nmem_mulTSupport {f : X → α} {x : X} (hx : x ∉ mulTSupport f) : f x = 1 := mulSupport_subset_iff'.mp (subset_mulTSupport f) x hx @[to_additive] theorem range_subset_insert_image_mulTSupport (f : X → α) : range f ⊆ insert 1 (f '' mulTSupport f) := (range_subset_insert_image_mulSupport f).trans <| insert_subset_insert <| image_subset _ subset_closure @[to_additive] theorem range_eq_image_mulTSupport_or (f : X → α) : range f = f '' mulTSupport f ∨ range f = insert 1 (f '' mulTSupport f) := (wcovBy_insert _ _).eq_or_eq (image_subset_range _ _) (range_subset_insert_image_mulTSupport f) theorem tsupport_mul_subset_left {α : Type*} [MulZeroClass α] {f g : X → α} : (tsupport fun x => f x * g x) ⊆ tsupport f := closure_mono (support_mul_subset_left _ _) theorem tsupport_mul_subset_right {α : Type*} [MulZeroClass α] {f g : X → α} : (tsupport fun x => f x * g x) ⊆ tsupport g := closure_mono (support_mul_subset_right _ _) end One theorem tsupport_smul_subset_left {M α} [TopologicalSpace X] [Zero M] [Zero α] [SMulWithZero M α] (f : X → M) (g : X → α) : (tsupport fun x => f x • g x) ⊆ tsupport f := closure_mono <| support_smul_subset_left f g theorem tsupport_smul_subset_right {M α} [TopologicalSpace X] [Zero α] [SMulZeroClass M α] (f : X → M) (g : X → α) : (tsupport fun x => f x • g x) ⊆ tsupport g := closure_mono <| support_smul_subset_right f g @[to_additive] theorem mulTSupport_mul [TopologicalSpace X] [Monoid α] {f g : X → α} : (mulTSupport fun x ↦ f x * g x) ⊆ mulTSupport f ∪ mulTSupport g := closure_minimal ((mulSupport_mul f g).trans (union_subset_union (subset_mulTSupport _) (subset_mulTSupport _))) (isClosed_closure.union isClosed_closure) section variable [TopologicalSpace α] [TopologicalSpace α'] variable [One β] [One γ] [One δ] variable {g : β → γ} {f : α → β} {f₂ : α → γ} {m : β → γ → δ} {x : α} @[to_additive] theorem not_mem_mulTSupport_iff_eventuallyEq : x ∉ mulTSupport f ↔ f =ᶠ[𝓝 x] 1 := by simp_rw [mulTSupport, mem_closure_iff_nhds, not_forall, not_nonempty_iff_eq_empty, exists_prop, ← disjoint_iff_inter_eq_empty, disjoint_mulSupport_iff, eventuallyEq_iff_exists_mem] @[to_additive] theorem continuous_of_mulTSupport [TopologicalSpace β] {f : α → β} (hf : ∀ x ∈ mulTSupport f, ContinuousAt f x) : Continuous f := continuous_iff_continuousAt.2 fun x => (em _).elim (hf x) fun hx => (@continuousAt_const _ _ _ _ _ 1).congr (not_mem_mulTSupport_iff_eventuallyEq.mp hx).symm end /-! ## Functions with compact support -/ section CompactSupport variable [TopologicalSpace α] [TopologicalSpace α'] variable [One β] [One γ] [One δ] variable {g : β → γ} {f : α → β} {f₂ : α → γ} {m : β → γ → δ} {x : α} /-- A function `f` *has compact multiplicative support* or is *compactly supported* if the closure of the multiplicative support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `1` outside a compact set. -/ @[to_additive " A function `f` *has compact support* or is *compactly supported* if the closure of the support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `0` outside a compact set. "] def HasCompactMulSupport (f : α → β) : Prop := IsCompact (mulTSupport f) @[to_additive] theorem hasCompactMulSupport_def : HasCompactMulSupport f ↔ IsCompact (closure (mulSupport f)) := by rfl @[to_additive] theorem exists_compact_iff_hasCompactMulSupport [R1Space α] : (∃ K : Set α, IsCompact K ∧ ∀ x, x ∉ K → f x = 1) ↔ HasCompactMulSupport f := by simp_rw [← nmem_mulSupport, ← mem_compl_iff, ← subset_def, compl_subset_compl, hasCompactMulSupport_def, exists_isCompact_superset_iff] namespace HasCompactMulSupport @[to_additive] theorem intro [R1Space α] {K : Set α} (hK : IsCompact K) (hfK : ∀ x, x ∉ K → f x = 1) : HasCompactMulSupport f := exists_compact_iff_hasCompactMulSupport.mp ⟨K, hK, hfK⟩ @[to_additive] theorem intro' {K : Set α} (hK : IsCompact K) (h'K : IsClosed K) (hfK : ∀ x, x ∉ K → f x = 1) : HasCompactMulSupport f := by have : mulTSupport f ⊆ K := by rw [← h'K.closure_eq] apply closure_mono (mulSupport_subset_iff'.2 hfK) exact IsCompact.of_isClosed_subset hK ( isClosed_mulTSupport f) this @[to_additive] theorem of_mulSupport_subset_isCompact [R1Space α] {K : Set α} (hK : IsCompact K) (h : mulSupport f ⊆ K) : HasCompactMulSupport f := hK.closure_of_subset h @[to_additive] theorem isCompact (hf : HasCompactMulSupport f) : IsCompact (mulTSupport f) := hf @[to_additive] theorem _root_.hasCompactMulSupport_iff_eventuallyEq : HasCompactMulSupport f ↔ f =ᶠ[coclosedCompact α] 1 := mem_coclosedCompact_iff.symm @[to_additive] theorem _root_.isCompact_range_of_mulSupport_subset_isCompact [TopologicalSpace β] (hf : Continuous f) {k : Set α} (hk : IsCompact k) (h'f : mulSupport f ⊆ k) : IsCompact (range f) := by cases' range_eq_image_or_of_mulSupport_subset h'f with h2 h2 <;> rw [h2] exacts [hk.image hf, (hk.image hf).insert 1] @[to_additive] theorem isCompact_range [TopologicalSpace β] (h : HasCompactMulSupport f) (hf : Continuous f) : IsCompact (range f) := isCompact_range_of_mulSupport_subset_isCompact hf h (subset_mulTSupport f) @[to_additive] theorem mono' {f' : α → γ} (hf : HasCompactMulSupport f) (hff' : mulSupport f' ⊆ mulTSupport f) : HasCompactMulSupport f' := IsCompact.of_isClosed_subset hf isClosed_closure <| closure_minimal hff' isClosed_closure @[to_additive] theorem mono {f' : α → γ} (hf : HasCompactMulSupport f) (hff' : mulSupport f' ⊆ mulSupport f) : HasCompactMulSupport f' := hf.mono' <| hff'.trans subset_closure @[to_additive] theorem comp_left (hf : HasCompactMulSupport f) (hg : g 1 = 1) : HasCompactMulSupport (g ∘ f) := hf.mono <| mulSupport_comp_subset hg f @[to_additive] theorem _root_.hasCompactMulSupport_comp_left (hg : ∀ {x}, g x = 1 ↔ x = 1) : HasCompactMulSupport (g ∘ f) ↔ HasCompactMulSupport f := by simp_rw [hasCompactMulSupport_def, mulSupport_comp_eq g (@hg) f] @[to_additive] theorem comp_closedEmbedding (hf : HasCompactMulSupport f) {g : α' → α} (hg : ClosedEmbedding g) : HasCompactMulSupport (f ∘ g) := by rw [hasCompactMulSupport_def, Function.mulSupport_comp_eq_preimage] refine IsCompact.of_isClosed_subset (hg.isCompact_preimage hf) isClosed_closure ?_ rw [hg.toEmbedding.closure_eq_preimage_closure_image] exact preimage_mono (closure_mono <| image_preimage_subset _ _) @[to_additive] theorem comp₂_left (hf : HasCompactMulSupport f) (hf₂ : HasCompactMulSupport f₂) (hm : m 1 1 = 1) : HasCompactMulSupport fun x => m (f x) (f₂ x) := by rw [hasCompactMulSupport_iff_eventuallyEq] at hf hf₂ ⊢ #adaptation_note /-- `nightly-2024-03-11` If we *either* (1) remove the type annotations on the binders in the following `fun` or (2) revert `simp only` to `simp_rw`, `to_additive` fails because an `OfNat.ofNat 1` is not replaced with `0`. Notably, as of this nightly, what used to look like `OfNat.ofNat (nat_lit 1) x` in the proof term now looks like `OfNat.ofNat (OfNat.ofNat (α := ℕ) (nat_lit 1)) x`, and this seems to trip up `to_additive`. -/ filter_upwards [hf, hf₂] using fun x (hx : f x = (1 : α → β) x) (hx₂ : f₂ x = (1 : α → γ) x) => by simp only [hx, hx₂, Pi.one_apply, hm] @[to_additive] lemma isCompact_preimage [TopologicalSpace β] (h'f : HasCompactMulSupport f) (hf : Continuous f) {k : Set β} (hk : IsClosed k) (h'k : 1 ∉ k) : IsCompact (f ⁻¹' k) := by apply IsCompact.of_isClosed_subset h'f (hk.preimage hf) (fun x hx ↦ ?_) apply subset_mulTSupport aesop variable [T2Space α'] (hf : HasCompactMulSupport f) {g : α → α'} (cont : Continuous g) @[to_additive] theorem mulTSupport_extend_one_subset : mulTSupport (g.extend f 1) ⊆ g '' mulTSupport f := (hf.image cont).isClosed.closure_subset_iff.mpr <| mulSupport_extend_one_subset.trans (image_subset g subset_closure) @[to_additive] theorem extend_one : HasCompactMulSupport (g.extend f 1) := HasCompactMulSupport.of_mulSupport_subset_isCompact (hf.image cont) (subset_closure.trans <| hf.mulTSupport_extend_one_subset cont) @[to_additive] theorem mulTSupport_extend_one (inj : g.Injective) : mulTSupport (g.extend f 1) = g '' mulTSupport f := (hf.mulTSupport_extend_one_subset cont).antisymm <| (image_closure_subset_closure_image cont).trans (closure_mono (mulSupport_extend_one inj).superset) @[to_additive] theorem continuous_extend_one [TopologicalSpace β] {U : Set α'} (hU : IsOpen U) {f : U → β} (cont : Continuous f) (supp : HasCompactMulSupport f) : Continuous (Subtype.val.extend f 1) := continuous_of_mulTSupport fun x h ↦ by rw [show x = ↑(⟨x, Subtype.coe_image_subset _ _ (supp.mulTSupport_extend_one_subset continuous_subtype_val h)⟩ : U) by rfl, ← (hU.openEmbedding_subtype_val).continuousAt_iff, extend_comp Subtype.val_injective] exact cont.continuousAt /-- If `f` has compact multiplicative support, then `f` tends to 1 at infinity. -/ @[to_additive "If `f` has compact support, then `f` tends to zero at infinity."] theorem is_one_at_infty {f : α → γ} [TopologicalSpace γ] [One γ] (h : HasCompactMulSupport f) : Tendsto f (cocompact α) (𝓝 1) := by intro N hN rw [mem_map, mem_cocompact'] refine ⟨mulTSupport f, h.isCompact, ?_⟩ rw [compl_subset_comm] intro v hv rw [mem_preimage, image_eq_one_of_nmem_mulTSupport hv] exact mem_of_mem_nhds hN end HasCompactMulSupport section Compact variable [CompactSpace α] [One γ] [TopologicalSpace γ] /-- In a compact space `α`, any function has compact support. -/ @[to_additive] theorem HasCompactMulSupport.of_compactSpace (f : α → γ) : HasCompactMulSupport f := IsCompact.of_isClosed_subset isCompact_univ (isClosed_mulTSupport f) (Set.subset_univ (mulTSupport f)) end Compact end CompactSupport /-! ## Functions with compact support: algebraic operations -/ section CompactSupport2 section Monoid variable [TopologicalSpace α] [MulOneClass β] variable {f f' : α → β} {x : α} @[to_additive] theorem HasCompactMulSupport.mul (hf : HasCompactMulSupport f) (hf' : HasCompactMulSupport f') : HasCompactMulSupport (f * f') := hf.comp₂_left hf' (mul_one 1) end Monoid section SMulZeroClass variable [TopologicalSpace α] [Zero M] [SMulZeroClass R M] variable {f : α → R} {f' : α → M} {x : α} theorem HasCompactSupport.smul_left (hf : HasCompactSupport f') : HasCompactSupport (f • f') := by rw [hasCompactSupport_iff_eventuallyEq] at hf ⊢ exact hf.mono fun x hx => by simp_rw [Pi.smul_apply', hx, Pi.zero_apply, smul_zero] end SMulZeroClass section SMulWithZero variable [TopologicalSpace α] [Zero R] [Zero M] [SMulWithZero R M] variable {f : α → R} {f' : α → M} {x : α} theorem HasCompactSupport.smul_right (hf : HasCompactSupport f) : HasCompactSupport (f • f') := by rw [hasCompactSupport_iff_eventuallyEq] at hf ⊢ exact hf.mono fun x hx => by simp_rw [Pi.smul_apply', hx, Pi.zero_apply, zero_smul] @[deprecated (since := "2024-06-05")] alias HasCompactSupport.smul_left' := HasCompactSupport.smul_left end SMulWithZero section MulZeroClass variable [TopologicalSpace α] [MulZeroClass β] variable {f f' : α → β} {x : α} theorem HasCompactSupport.mul_right (hf : HasCompactSupport f) : HasCompactSupport (f * f') := by rw [hasCompactSupport_iff_eventuallyEq] at hf ⊢ exact hf.mono fun x hx => by simp_rw [Pi.mul_apply, hx, Pi.zero_apply, zero_mul] theorem HasCompactSupport.mul_left (hf : HasCompactSupport f') : HasCompactSupport (f * f') := by rw [hasCompactSupport_iff_eventuallyEq] at hf ⊢ exact hf.mono fun x hx => by simp_rw [Pi.mul_apply, hx, Pi.zero_apply, mul_zero] end MulZeroClass section OrderedAddGroup variable {α β : Type*} [TopologicalSpace α] [TopologicalSpace β] [AddGroup β] [Lattice β] [CovariantClass β β (· + ·) (· ≤ ·)] protected theorem HasCompactSupport.abs {f : α → β} (hf : HasCompactSupport f) : HasCompactSupport |f| := hf.comp_left (g := abs) abs_zero end OrderedAddGroup end CompactSupport2 section LocallyFinite variable {ι : Type*} [TopologicalSpace X] -- Porting note (#11215): TODO: reformulate for any locally finite family of sets /-- If a family of functions `f` has locally-finite multiplicative support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are not equal to 1. -/ @[to_additive " If a family of functions `f` has locally-finite support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are non-zero. "] theorem LocallyFinite.exists_finset_nhd_mulSupport_subset {U : ι → Set X} [One R] {f : ι → X → R} (hlf : LocallyFinite fun i => mulSupport (f i)) (hso : ∀ i, mulTSupport (f i) ⊆ U i) (ho : ∀ i, IsOpen (U i)) (x : X) : ∃ (is : Finset ι), ∃ n, n ∈ 𝓝 x ∧ (n ⊆ ⋂ i ∈ is, U i) ∧ ∀ z ∈ n, (mulSupport fun i => f i z) ⊆ is := by obtain ⟨n, hn, hnf⟩ := hlf x classical let is := hnf.toFinset.filter fun i => x ∈ U i let js := hnf.toFinset.filter fun j => x ∉ U j refine ⟨is, (n ∩ ⋂ j ∈ js, (mulTSupport (f j))ᶜ) ∩ ⋂ i ∈ is, U i, inter_mem (inter_mem hn ?_) ?_, inter_subset_right, fun z hz => ?_⟩ · exact (biInter_finset_mem js).mpr fun j hj => IsClosed.compl_mem_nhds (isClosed_mulTSupport _) (Set.not_mem_subset (hso j) (Finset.mem_filter.mp hj).2) · exact (biInter_finset_mem is).mpr fun i hi => (ho i).mem_nhds (Finset.mem_filter.mp hi).2 · have hzn : z ∈ n := by rw [inter_assoc] at hz exact mem_of_mem_inter_left hz replace hz := mem_of_mem_inter_right (mem_of_mem_inter_left hz) simp only [js, Finset.mem_filter, Finite.mem_toFinset, mem_setOf_eq, mem_iInter, and_imp] at hz suffices (mulSupport fun i => f i z) ⊆ hnf.toFinset by refine hnf.toFinset.subset_coe_filter_of_subset_forall _ this fun i hi => ?_ specialize hz i ⟨z, ⟨hi, hzn⟩⟩ contrapose hz simp [hz, subset_mulTSupport (f i) hi] intro i hi simp only [Finite.coe_toFinset, mem_setOf_eq] exact ⟨z, ⟨hi, hzn⟩⟩ @[to_additive] theorem locallyFinite_mulSupport_iff [CommMonoid M] {f : ι → X → M} : (LocallyFinite fun i ↦ mulSupport <| f i) ↔ LocallyFinite fun i ↦ mulTSupport <| f i := ⟨LocallyFinite.closure, fun H ↦ H.subset fun _ ↦ subset_closure⟩ theorem LocallyFinite.smul_left [Zero R] [Zero M] [SMulWithZero R M] {s : ι → X → R} (h : LocallyFinite fun i ↦ support <| s i) (f : ι → X → M) : LocallyFinite fun i ↦ support <| s i • f i := h.subset fun i x ↦ mt <| fun h ↦ by rw [Pi.smul_apply', h, zero_smul] theorem LocallyFinite.smul_right [Zero M] [SMulZeroClass R M] {f : ι → X → M} (h : LocallyFinite fun i ↦ support <| f i) (s : ι → X → R) : LocallyFinite fun i ↦ support <| s i • f i := h.subset fun i x ↦ mt <| fun h ↦ by rw [Pi.smul_apply', h, smul_zero] end LocallyFinite
Topology\TietzeExtension.lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import Mathlib.Analysis.SpecificLimits.Basic import Mathlib.Order.Interval.Set.IsoIoo import Mathlib.Topology.Order.MonotoneContinuity import Mathlib.Topology.UrysohnsBounded /-! # Tietze extension theorem In this file we prove a few version of the Tietze extension theorem. The theorem says that a continuous function `s → ℝ` defined on a closed set in a normal topological space `Y` can be extended to a continuous function on the whole space. Moreover, if all values of the original function belong to some (finite or infinite, open or closed) interval, then the extension can be chosen so that it takes values in the same interval. In particular, if the original function is a bounded function, then there exists a bounded extension of the same norm. The proof mostly follows <https://ncatlab.org/nlab/show/Tietze+extension+theorem>. We patch a small gap in the proof for unbounded functions, see `exists_extension_forall_exists_le_ge_of_closedEmbedding`. In addition we provide a class `TietzeExtension` encoding the idea that a topological space satisfies the Tietze extension theorem. This allows us to get a version of the Tietze extension theorem that simultaneously applies to `ℝ`, `ℝ × ℝ`, `ℂ`, `ι → ℝ`, `ℝ≥0` et cetera. At some point in the future, it may be desirable to provide instead a more general approach via *absolute retracts*, but the current implementation covers the most common use cases easily. ## Implementation notes We first prove the theorems for a closed embedding `e : X → Y` of a topological space into a normal topological space, then specialize them to the case `X = s : Set Y`, `e = (↑)`. ## Tags Tietze extension theorem, Urysohn's lemma, normal topological space -/ /-! ### The `TietzeExtension` class -/ section TietzeExtensionClass universe u u₁ u₂ v w -- TODO: define *absolute retracts* and then prove they satisfy Tietze extension. -- Then make instances of that instead and remove this class. /-- A class encoding the concept that a space satisfies the Tietze extension property. -/ class TietzeExtension (Y : Type v) [TopologicalSpace Y] : Prop where exists_restrict_eq' {X : Type u} [TopologicalSpace X] [NormalSpace X] (s : Set X) (hs : IsClosed s) (f : C(s, Y)) : ∃ (g : C(X, Y)), g.restrict s = f variable {X₁ : Type u₁} [TopologicalSpace X₁] variable {X : Type u} [TopologicalSpace X] [NormalSpace X] {s : Set X} variable {e : X₁ → X} variable {Y : Type v} [TopologicalSpace Y] [TietzeExtension.{u, v} Y] /-- **Tietze extension theorem** for `TietzeExtension` spaces, a version for a closed set. Let `s` be a closed set in a normal topological space `X`. Let `f` be a continuous function on `s` with values in a `TietzeExtension` space `Y`. Then there exists a continuous function `g : C(X, Y)` such that `g.restrict s = f`. -/ theorem ContinuousMap.exists_restrict_eq (hs : IsClosed s) (f : C(s, Y)) : ∃ (g : C(X, Y)), g.restrict s = f := TietzeExtension.exists_restrict_eq' s hs f /-- **Tietze extension theorem** for `TietzeExtension` spaces. Let `e` be a closed embedding of a nonempty topological space `X₁` into a normal topological space `X`. Let `f` be a continuous function on `X₁` with values in a `TietzeExtension` space `Y`. Then there exists a continuous function `g : C(X, Y)` such that `g ∘ e = f`. -/ theorem ContinuousMap.exists_extension (he : ClosedEmbedding e) (f : C(X₁, Y)) : ∃ (g : C(X, Y)), g.comp ⟨e, he.continuous⟩ = f := by let e' : X₁ ≃ₜ Set.range e := Homeomorph.ofEmbedding _ he.toEmbedding obtain ⟨g, hg⟩ := (f.comp e'.symm).exists_restrict_eq he.isClosed_range exact ⟨g, by ext x; simpa using congr($(hg) ⟨e' x, x, rfl⟩)⟩ /-- **Tietze extension theorem** for `TietzeExtension` spaces. Let `e` be a closed embedding of a nonempty topological space `X₁` into a normal topological space `X`. Let `f` be a continuous function on `X₁` with values in a `TietzeExtension` space `Y`. Then there exists a continuous function `g : C(X, Y)` such that `g ∘ e = f`. This version is provided for convenience and backwards compatibility. Here the composition is phrased in terms of bare functions. -/ theorem ContinuousMap.exists_extension' (he : ClosedEmbedding e) (f : C(X₁, Y)) : ∃ (g : C(X, Y)), g ∘ e = f := f.exists_extension he |>.imp fun g hg ↦ by ext x; congrm($(hg) x) /-- This theorem is not intended to be used directly because it is rare for a set alone to satisfy `[TietzeExtension t]`. For example, `Metric.ball` in `ℝ` only satisfies it when the radius is strictly positive, so finding this as an instance will fail. Instead, it is intended to be used as a constructor for theorems about sets which *do* satisfy `[TietzeExtension t]` under some hypotheses. -/ theorem ContinuousMap.exists_forall_mem_restrict_eq (hs : IsClosed s) {Y : Type v} [TopologicalSpace Y] (f : C(s, Y)) {t : Set Y} (hf : ∀ x, f x ∈ t) [ht : TietzeExtension.{u, v} t] : ∃ (g : C(X, Y)), (∀ x, g x ∈ t) ∧ g.restrict s = f := by obtain ⟨g, hg⟩ := mk _ (map_continuous f |>.codRestrict hf) |>.exists_restrict_eq hs exact ⟨comp ⟨Subtype.val, by continuity⟩ g, by simp, by ext x; congrm(($(hg) x : Y))⟩ /-- This theorem is not intended to be used directly because it is rare for a set alone to satisfy `[TietzeExtension t]`. For example, `Metric.ball` in `ℝ` only satisfies it when the radius is strictly positive, so finding this as an instance will fail. Instead, it is intended to be used as a constructor for theorems about sets which *do* satisfy `[TietzeExtension t]` under some hypotheses. -/ theorem ContinuousMap.exists_extension_forall_mem (he : ClosedEmbedding e) {Y : Type v} [TopologicalSpace Y] (f : C(X₁, Y)) {t : Set Y} (hf : ∀ x, f x ∈ t) [ht : TietzeExtension.{u, v} t] : ∃ (g : C(X, Y)), (∀ x, g x ∈ t) ∧ g.comp ⟨e, he.continuous⟩ = f := by obtain ⟨g, hg⟩ := mk _ (map_continuous f |>.codRestrict hf) |>.exists_extension he exact ⟨comp ⟨Subtype.val, by continuity⟩ g, by simp, by ext x; congrm(($(hg) x : Y))⟩ instance Pi.instTietzeExtension {ι : Type*} {Y : ι → Type v} [∀ i, TopologicalSpace (Y i)] [∀ i, TietzeExtension.{u} (Y i)] : TietzeExtension.{u} (∀ i, Y i) where exists_restrict_eq' s hs f := by obtain ⟨g', hg'⟩ := Classical.skolem.mp <| fun i ↦ ContinuousMap.exists_restrict_eq hs (ContinuousMap.piEquiv _ _ |>.symm f i) exact ⟨ContinuousMap.piEquiv _ _ g', by ext x i; congrm($(hg' i) x)⟩ instance Prod.instTietzeExtension {Y : Type v} {Z : Type w} [TopologicalSpace Y] [TietzeExtension.{u, v} Y] [TopologicalSpace Z] [TietzeExtension.{u, w} Z] : TietzeExtension.{u, max w v} (Y × Z) where exists_restrict_eq' s hs f := by obtain ⟨g₁, hg₁⟩ := (ContinuousMap.fst.comp f).exists_restrict_eq hs obtain ⟨g₂, hg₂⟩ := (ContinuousMap.snd.comp f).exists_restrict_eq hs exact ⟨g₁.prodMk g₂, by ext1 x; congrm(($(hg₁) x), $(hg₂) x)⟩ instance Unique.instTietzeExtension {Y : Type v} [TopologicalSpace Y] [Unique Y] : TietzeExtension.{u, v} Y where exists_restrict_eq' _ _ f := ⟨.const _ default, by ext; subsingleton⟩ /-- Any retract of a `TietzeExtension` space is one itself. -/ theorem TietzeExtension.of_retract {Y : Type v} {Z : Type w} [TopologicalSpace Y] [TopologicalSpace Z] [TietzeExtension.{u, w} Z] (ι : C(Y, Z)) (r : C(Z, Y)) (h : r.comp ι = .id Y) : TietzeExtension.{u, v} Y where exists_restrict_eq' s hs f := by obtain ⟨g, hg⟩ := (ι.comp f).exists_restrict_eq hs use r.comp g ext1 x have := congr(r.comp $(hg)) rw [← r.comp_assoc ι, h, f.id_comp] at this congrm($this x) /-- Any homeomorphism from a `TietzeExtension` space is one itself. -/ theorem TietzeExtension.of_homeo {Y : Type v} {Z : Type w} [TopologicalSpace Y] [TopologicalSpace Z] [TietzeExtension.{u, w} Z] (e : Y ≃ₜ Z) : TietzeExtension.{u, v} Y := .of_retract (e : C(Y, Z)) (e.symm : C(Z, Y)) <| by simp end TietzeExtensionClass /-! The Tietze extension theorem for `ℝ`. -/ variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [NormalSpace Y] open Metric Set Filter open BoundedContinuousFunction Topology noncomputable section namespace BoundedContinuousFunction /-- One step in the proof of the Tietze extension theorem. If `e : C(X, Y)` is a closed embedding of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the norm `‖g‖ ≤ ‖f‖ / 3` such that the distance between `g ∘ e` and `f` is at most `(2 / 3) * ‖f‖`. -/ theorem tietze_extension_step (f : X →ᵇ ℝ) (e : C(X, Y)) (he : ClosedEmbedding e) : ∃ g : Y →ᵇ ℝ, ‖g‖ ≤ ‖f‖ / 3 ∧ dist (g.compContinuous e) f ≤ 2 / 3 * ‖f‖ := by have h3 : (0 : ℝ) < 3 := by norm_num1 have h23 : 0 < (2 / 3 : ℝ) := by norm_num1 -- In the trivial case `f = 0`, we take `g = 0` rcases eq_or_ne f 0 with (rfl | hf) · use 0 simp replace hf : 0 < ‖f‖ := norm_pos_iff.2 hf /- Otherwise, the closed sets `e '' (f ⁻¹' (Iic (-‖f‖ / 3)))` and `e '' (f ⁻¹' (Ici (‖f‖ / 3)))` are disjoint, hence by Urysohn's lemma there exists a function `g` that is equal to `-‖f‖ / 3` on the former set and is equal to `‖f‖ / 3` on the latter set. This function `g` satisfies the assertions of the lemma. -/ have hf3 : -‖f‖ / 3 < ‖f‖ / 3 := (div_lt_div_right h3).2 (Left.neg_lt_self hf) have hc₁ : IsClosed (e '' (f ⁻¹' Iic (-‖f‖ / 3))) := he.isClosedMap _ (isClosed_Iic.preimage f.continuous) have hc₂ : IsClosed (e '' (f ⁻¹' Ici (‖f‖ / 3))) := he.isClosedMap _ (isClosed_Ici.preimage f.continuous) have hd : Disjoint (e '' (f ⁻¹' Iic (-‖f‖ / 3))) (e '' (f ⁻¹' Ici (‖f‖ / 3))) := by refine disjoint_image_of_injective he.inj (Disjoint.preimage _ ?_) rwa [Iic_disjoint_Ici, not_le] rcases exists_bounded_mem_Icc_of_closed_of_le hc₁ hc₂ hd hf3.le with ⟨g, hg₁, hg₂, hgf⟩ refine ⟨g, ?_, ?_⟩ · refine (norm_le <| div_nonneg hf.le h3.le).mpr fun y => ?_ simpa [abs_le, neg_div] using hgf y · refine (dist_le <| mul_nonneg h23.le hf.le).mpr fun x => ?_ have hfx : -‖f‖ ≤ f x ∧ f x ≤ ‖f‖ := by simpa only [Real.norm_eq_abs, abs_le] using f.norm_coe_le_norm x rcases le_total (f x) (-‖f‖ / 3) with hle₁ | hle₁ · calc |g (e x) - f x| = -‖f‖ / 3 - f x := by rw [hg₁ (mem_image_of_mem _ hle₁), Function.const_apply, abs_of_nonneg (sub_nonneg.2 hle₁)] _ ≤ 2 / 3 * ‖f‖ := by linarith · rcases le_total (f x) (‖f‖ / 3) with hle₂ | hle₂ · simp only [neg_div] at * calc dist (g (e x)) (f x) ≤ |g (e x)| + |f x| := dist_le_norm_add_norm _ _ _ ≤ ‖f‖ / 3 + ‖f‖ / 3 := (add_le_add (abs_le.2 <| hgf _) (abs_le.2 ⟨hle₁, hle₂⟩)) _ = 2 / 3 * ‖f‖ := by linarith · calc |g (e x) - f x| = f x - ‖f‖ / 3 := by rw [hg₂ (mem_image_of_mem _ hle₂), abs_sub_comm, Function.const_apply, abs_of_nonneg (sub_nonneg.2 hle₂)] _ ≤ 2 / 3 * ‖f‖ := by linarith /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version with a closed embedding and bundled composition. If `e : C(X, Y)` is a closed embedding of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the same norm such that `g ∘ e = f`. -/ theorem exists_extension_norm_eq_of_closedEmbedding' (f : X →ᵇ ℝ) (e : C(X, Y)) (he : ClosedEmbedding e) : ∃ g : Y →ᵇ ℝ, ‖g‖ = ‖f‖ ∧ g.compContinuous e = f := by /- For the proof, we iterate `tietze_extension_step`. Each time we apply it to the difference between the previous approximation and `f`. -/ choose F hF_norm hF_dist using fun f : X →ᵇ ℝ => tietze_extension_step f e he set g : ℕ → Y →ᵇ ℝ := fun n => (fun g => g + F (f - g.compContinuous e))^[n] 0 have g0 : g 0 = 0 := rfl have g_succ : ∀ n, g (n + 1) = g n + F (f - (g n).compContinuous e) := fun n => Function.iterate_succ_apply' _ _ _ have hgf : ∀ n, dist ((g n).compContinuous e) f ≤ (2 / 3) ^ n * ‖f‖ := by intro n induction' n with n ihn · simp [g0] · rw [g_succ n, add_compContinuous, ← dist_sub_right, add_sub_cancel_left, pow_succ', mul_assoc] refine (hF_dist _).trans (mul_le_mul_of_nonneg_left ?_ (by norm_num1)) rwa [← dist_eq_norm'] have hg_dist : ∀ n, dist (g n) (g (n + 1)) ≤ 1 / 3 * ‖f‖ * (2 / 3) ^ n := by intro n calc dist (g n) (g (n + 1)) = ‖F (f - (g n).compContinuous e)‖ := by rw [g_succ, dist_eq_norm', add_sub_cancel_left] _ ≤ ‖f - (g n).compContinuous e‖ / 3 := hF_norm _ _ = 1 / 3 * dist ((g n).compContinuous e) f := by rw [dist_eq_norm', one_div, div_eq_inv_mul] _ ≤ 1 / 3 * ((2 / 3) ^ n * ‖f‖) := mul_le_mul_of_nonneg_left (hgf n) (by norm_num1) _ = 1 / 3 * ‖f‖ * (2 / 3) ^ n := by ac_rfl have hg_cau : CauchySeq g := cauchySeq_of_le_geometric _ _ (by norm_num1) hg_dist have : Tendsto (fun n => (g n).compContinuous e) atTop (𝓝 <| (limUnder atTop g).compContinuous e) := ((continuous_compContinuous e).tendsto _).comp hg_cau.tendsto_limUnder have hge : (limUnder atTop g).compContinuous e = f := by refine tendsto_nhds_unique this (tendsto_iff_dist_tendsto_zero.2 ?_) refine squeeze_zero (fun _ => dist_nonneg) hgf ?_ rw [← zero_mul ‖f‖] refine (tendsto_pow_atTop_nhds_zero_of_lt_one ?_ ?_).mul tendsto_const_nhds <;> norm_num1 refine ⟨limUnder atTop g, le_antisymm ?_ ?_, hge⟩ · rw [← dist_zero_left, ← g0] refine (dist_le_of_le_geometric_of_tendsto₀ _ _ (by norm_num1) hg_dist hg_cau.tendsto_limUnder).trans_eq ?_ field_simp [show (3 - 2 : ℝ) = 1 by norm_num1] · rw [← hge] exact norm_compContinuous_le _ _ /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version with a closed embedding and unbundled composition. If `e : C(X, Y)` is a closed embedding of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the same norm such that `g ∘ e = f`. -/ theorem exists_extension_norm_eq_of_closedEmbedding (f : X →ᵇ ℝ) {e : X → Y} (he : ClosedEmbedding e) : ∃ g : Y →ᵇ ℝ, ‖g‖ = ‖f‖ ∧ g ∘ e = f := by rcases exists_extension_norm_eq_of_closedEmbedding' f ⟨e, he.continuous⟩ he with ⟨g, hg, rfl⟩ exact ⟨g, hg, rfl⟩ /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed set. If `f` is a bounded continuous real-valued function defined on a closed set in a normal topological space, then it can be extended to a bounded continuous function of the same norm defined on the whole space. -/ theorem exists_norm_eq_restrict_eq_of_closed {s : Set Y} (f : s →ᵇ ℝ) (hs : IsClosed s) : ∃ g : Y →ᵇ ℝ, ‖g‖ = ‖f‖ ∧ g.restrict s = f := exists_extension_norm_eq_of_closedEmbedding' f ((ContinuousMap.id _).restrict s) (closedEmbedding_subtype_val hs) /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed embedding and a bounded continuous function that takes values in a non-trivial closed interval. See also `exists_extension_forall_mem_of_closedEmbedding` for a more general statement that works for any interval (finite or infinite, open or closed). If `e : X → Y` is a closed embedding and `f : X →ᵇ ℝ` is a bounded continuous function such that `f x ∈ [a, b]` for all `x`, where `a ≤ b`, then there exists a bounded continuous function `g : Y →ᵇ ℝ` such that `g y ∈ [a, b]` for all `y` and `g ∘ e = f`. -/ theorem exists_extension_forall_mem_Icc_of_closedEmbedding (f : X →ᵇ ℝ) {a b : ℝ} {e : X → Y} (hf : ∀ x, f x ∈ Icc a b) (hle : a ≤ b) (he : ClosedEmbedding e) : ∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ Icc a b) ∧ g ∘ e = f := by rcases exists_extension_norm_eq_of_closedEmbedding (f - const X ((a + b) / 2)) he with ⟨g, hgf, hge⟩ refine ⟨const Y ((a + b) / 2) + g, fun y => ?_, ?_⟩ · suffices ‖f - const X ((a + b) / 2)‖ ≤ (b - a) / 2 by simpa [Real.Icc_eq_closedBall, add_mem_closedBall_iff_norm] using (norm_coe_le_norm g y).trans (hgf.trans_le this) refine (norm_le <| div_nonneg (sub_nonneg.2 hle) zero_le_two).2 fun x => ?_ simpa only [Real.Icc_eq_closedBall] using hf x · ext x have : g (e x) = f x - (a + b) / 2 := congr_fun hge x simp [this] /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a bounded continuous real-valued function on `X`. Then there exists a bounded continuous function `g : Y →ᵇ ℝ` such that `g ∘ e = f` and each value `g y` belongs to a closed interval `[f x₁, f x₂]` for some `x₁` and `x₂`. -/ theorem exists_extension_forall_exists_le_ge_of_closedEmbedding [Nonempty X] (f : X →ᵇ ℝ) {e : X → Y} (he : ClosedEmbedding e) : ∃ g : Y →ᵇ ℝ, (∀ y, ∃ x₁ x₂, g y ∈ Icc (f x₁) (f x₂)) ∧ g ∘ e = f := by inhabit X -- Put `a = ⨅ x, f x` and `b = ⨆ x, f x` obtain ⟨a, ha⟩ : ∃ a, IsGLB (range f) a := ⟨_, isGLB_ciInf f.isBounded_range.bddBelow⟩ obtain ⟨b, hb⟩ : ∃ b, IsLUB (range f) b := ⟨_, isLUB_ciSup f.isBounded_range.bddAbove⟩ -- Then `f x ∈ [a, b]` for all `x` have hmem : ∀ x, f x ∈ Icc a b := fun x => ⟨ha.1 ⟨x, rfl⟩, hb.1 ⟨x, rfl⟩⟩ -- Rule out the trivial case `a = b` have hle : a ≤ b := (hmem default).1.trans (hmem default).2 rcases hle.eq_or_lt with (rfl | hlt) · have : ∀ x, f x = a := by simpa using hmem use const Y a simp [this, Function.funext_iff] -- Put `c = (a + b) / 2`. Then `a < c < b` and `c - a = b - c`. set c := (a + b) / 2 have hac : a < c := left_lt_add_div_two.2 hlt have hcb : c < b := add_div_two_lt_right.2 hlt have hsub : c - a = b - c := by field_simp [c] ring /- Due to `exists_extension_forall_mem_Icc_of_closedEmbedding`, there exists an extension `g` such that `g y ∈ [a, b]` for all `y`. However, if `a` and/or `b` do not belong to the range of `f`, then we need to ensure that these points do not belong to the range of `g`. This is done in two almost identical steps. First we deal with the case `∀ x, f x ≠ a`. -/ obtain ⟨g, hg_mem, hgf⟩ : ∃ g : Y →ᵇ ℝ, (∀ y, ∃ x, g y ∈ Icc (f x) b) ∧ g ∘ e = f := by rcases exists_extension_forall_mem_Icc_of_closedEmbedding f hmem hle he with ⟨g, hg_mem, hgf⟩ -- If `a ∈ range f`, then we are done. rcases em (∃ x, f x = a) with (⟨x, rfl⟩ | ha') · exact ⟨g, fun y => ⟨x, hg_mem _⟩, hgf⟩ /- Otherwise, `g ⁻¹' {a}` is disjoint with `range e ∪ g ⁻¹' (Ici c)`, hence there exists a function `dg : Y → ℝ` such that `dg ∘ e = 0`, `dg y = 0` whenever `c ≤ g y`, `dg y = c - a` whenever `g y = a`, and `0 ≤ dg y ≤ c - a` for all `y`. -/ have hd : Disjoint (range e ∪ g ⁻¹' Ici c) (g ⁻¹' {a}) := by refine disjoint_union_left.2 ⟨?_, Disjoint.preimage _ ?_⟩ · rw [Set.disjoint_left] rintro _ ⟨x, rfl⟩ (rfl : g (e x) = a) exact ha' ⟨x, (congr_fun hgf x).symm⟩ · exact Set.disjoint_singleton_right.2 hac.not_le rcases exists_bounded_mem_Icc_of_closed_of_le (he.isClosed_range.union <| isClosed_Ici.preimage g.continuous) (isClosed_singleton.preimage g.continuous) hd (sub_nonneg.2 hac.le) with ⟨dg, dg0, dga, dgmem⟩ replace hgf : ∀ x, (g + dg) (e x) = f x := by intro x simp [dg0 (Or.inl <| mem_range_self _), ← hgf] refine ⟨g + dg, fun y => ?_, funext hgf⟩ have hay : a < (g + dg) y := by rcases (hg_mem y).1.eq_or_lt with (rfl | hlt) · refine (lt_add_iff_pos_right _).2 ?_ calc 0 < c - g y := sub_pos.2 hac _ = dg y := (dga rfl).symm · exact hlt.trans_le (le_add_of_nonneg_right (dgmem y).1) rcases ha.exists_between hay with ⟨_, ⟨x, rfl⟩, _, hxy⟩ refine ⟨x, hxy.le, ?_⟩ rcases le_total c (g y) with hc | hc · simp [dg0 (Or.inr hc), (hg_mem y).2] · calc g y + dg y ≤ c + (c - a) := add_le_add hc (dgmem _).2 _ = b := by rw [hsub, add_sub_cancel] /- Now we deal with the case `∀ x, f x ≠ b`. The proof is the same as in the first case, with minor modifications that make it hard to deduplicate code. -/ choose xl hxl hgb using hg_mem rcases em (∃ x, f x = b) with (⟨x, rfl⟩ | hb') · exact ⟨g, fun y => ⟨xl y, x, hxl y, hgb y⟩, hgf⟩ have hd : Disjoint (range e ∪ g ⁻¹' Iic c) (g ⁻¹' {b}) := by refine disjoint_union_left.2 ⟨?_, Disjoint.preimage _ ?_⟩ · rw [Set.disjoint_left] rintro _ ⟨x, rfl⟩ (rfl : g (e x) = b) exact hb' ⟨x, (congr_fun hgf x).symm⟩ · exact Set.disjoint_singleton_right.2 hcb.not_le rcases exists_bounded_mem_Icc_of_closed_of_le (he.isClosed_range.union <| isClosed_Iic.preimage g.continuous) (isClosed_singleton.preimage g.continuous) hd (sub_nonneg.2 hcb.le) with ⟨dg, dg0, dgb, dgmem⟩ replace hgf : ∀ x, (g - dg) (e x) = f x := by intro x simp [dg0 (Or.inl <| mem_range_self _), ← hgf] refine ⟨g - dg, fun y => ?_, funext hgf⟩ have hyb : (g - dg) y < b := by rcases (hgb y).eq_or_lt with (rfl | hlt) · refine (sub_lt_self_iff _).2 ?_ calc 0 < g y - c := sub_pos.2 hcb _ = dg y := (dgb rfl).symm · exact ((sub_le_self_iff _).2 (dgmem _).1).trans_lt hlt rcases hb.exists_between hyb with ⟨_, ⟨xu, rfl⟩, hyxu, _⟩ cases' lt_or_le c (g y) with hc hc · rcases em (a ∈ range f) with (⟨x, rfl⟩ | _) · refine ⟨x, xu, ?_, hyxu.le⟩ calc f x = c - (b - c) := by rw [← hsub, sub_sub_cancel] _ ≤ g y - dg y := sub_le_sub hc.le (dgmem _).2 · have hay : a < (g - dg) y := by calc a = c - (b - c) := by rw [← hsub, sub_sub_cancel] _ < g y - (b - c) := sub_lt_sub_right hc _ _ ≤ g y - dg y := sub_le_sub_left (dgmem _).2 _ rcases ha.exists_between hay with ⟨_, ⟨x, rfl⟩, _, hxy⟩ exact ⟨x, xu, hxy.le, hyxu.le⟩ · refine ⟨xl y, xu, ?_, hyxu.le⟩ simp [dg0 (Or.inr hc), hxl] /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a bounded continuous real-valued function on `X`. Let `t` be a nonempty convex set of real numbers (we use `OrdConnected` instead of `Convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x`. Then there exists a bounded continuous real-valued function `g : Y →ᵇ ℝ` such that `g y ∈ t` for all `y` and `g ∘ e = f`. -/ theorem exists_extension_forall_mem_of_closedEmbedding (f : X →ᵇ ℝ) {t : Set ℝ} {e : X → Y} [hs : OrdConnected t] (hf : ∀ x, f x ∈ t) (hne : t.Nonempty) (he : ClosedEmbedding e) : ∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ t) ∧ g ∘ e = f := by cases isEmpty_or_nonempty X · rcases hne with ⟨c, hc⟩ exact ⟨const Y c, fun _ => hc, funext fun x => isEmptyElim x⟩ rcases exists_extension_forall_exists_le_ge_of_closedEmbedding f he with ⟨g, hg, hgf⟩ refine ⟨g, fun y => ?_, hgf⟩ rcases hg y with ⟨xl, xu, h⟩ exact hs.out (hf _) (hf _) h /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed set. Let `s` be a closed set in a normal topological space `Y`. Let `f` be a bounded continuous real-valued function on `s`. Let `t` be a nonempty convex set of real numbers (we use `OrdConnected` instead of `Convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x : s`. Then there exists a bounded continuous real-valued function `g : Y →ᵇ ℝ` such that `g y ∈ t` for all `y` and `g.restrict s = f`. -/ theorem exists_forall_mem_restrict_eq_of_closed {s : Set Y} (f : s →ᵇ ℝ) (hs : IsClosed s) {t : Set ℝ} [OrdConnected t] (hf : ∀ x, f x ∈ t) (hne : t.Nonempty) : ∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ t) ∧ g.restrict s = f := by rcases exists_extension_forall_mem_of_closedEmbedding f hf hne (closedEmbedding_subtype_val hs) with ⟨g, hg, hgf⟩ exact ⟨g, hg, DFunLike.coe_injective hgf⟩ end BoundedContinuousFunction namespace ContinuousMap /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a continuous real-valued function on `X`. Let `t` be a nonempty convex set of real numbers (we use `OrdConnected` instead of `Convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g y ∈ t` for all `y` and `g ∘ e = f`. -/ theorem exists_extension_forall_mem_of_closedEmbedding (f : C(X, ℝ)) {t : Set ℝ} {e : X → Y} [hs : OrdConnected t] (hf : ∀ x, f x ∈ t) (hne : t.Nonempty) (he : ClosedEmbedding e) : ∃ g : C(Y, ℝ), (∀ y, g y ∈ t) ∧ g ∘ e = f := by have h : ℝ ≃o Ioo (-1 : ℝ) 1 := orderIsoIooNegOneOne ℝ let F : X →ᵇ ℝ := { toFun := (↑) ∘ h ∘ f continuous_toFun := continuous_subtype_val.comp (h.continuous.comp f.continuous) map_bounded' := isBounded_range_iff.1 ((isBounded_Ioo (-1 : ℝ) 1).subset <| range_subset_iff.2 fun x => (h (f x)).2) } let t' : Set ℝ := (↑) ∘ h '' t have ht_sub : t' ⊆ Ioo (-1 : ℝ) 1 := image_subset_iff.2 fun x _ => (h x).2 have : OrdConnected t' := by constructor rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ z hz lift z to Ioo (-1 : ℝ) 1 using Icc_subset_Ioo (h x).2.1 (h y).2.2 hz change z ∈ Icc (h x) (h y) at hz rw [← h.image_Icc] at hz rcases hz with ⟨z, hz, rfl⟩ exact ⟨z, hs.out hx hy hz, rfl⟩ have hFt : ∀ x, F x ∈ t' := fun x => mem_image_of_mem _ (hf x) rcases F.exists_extension_forall_mem_of_closedEmbedding hFt (hne.image _) he with ⟨G, hG, hGF⟩ let g : C(Y, ℝ) := ⟨h.symm ∘ codRestrict G _ fun y => ht_sub (hG y), h.symm.continuous.comp <| G.continuous.subtype_mk _⟩ have hgG : ∀ {y a}, g y = a ↔ G y = h a := @fun y a => h.toEquiv.symm_apply_eq.trans Subtype.ext_iff refine ⟨g, fun y => ?_, ?_⟩ · rcases hG y with ⟨a, ha, hay⟩ convert ha exact hgG.2 hay.symm · ext x exact hgG.2 (congr_fun hGF _) @[deprecated (since := "2024-01-16")] alias exists_extension_of_closedEmbedding := exists_extension' /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed set. Let `s` be a closed set in a normal topological space `Y`. Let `f` be a continuous real-valued function on `s`. Let `t` be a nonempty convex set of real numbers (we use `OrdConnected` instead of `Convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x : s`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g y ∈ t` for all `y` and `g.restrict s = f`. -/ theorem exists_restrict_eq_forall_mem_of_closed {s : Set Y} (f : C(s, ℝ)) {t : Set ℝ} [OrdConnected t] (ht : ∀ x, f x ∈ t) (hne : t.Nonempty) (hs : IsClosed s) : ∃ g : C(Y, ℝ), (∀ y, g y ∈ t) ∧ g.restrict s = f := let ⟨g, hgt, hgf⟩ := exists_extension_forall_mem_of_closedEmbedding f ht hne (closedEmbedding_subtype_val hs) ⟨g, hgt, coe_injective hgf⟩ @[deprecated (since := "2024-01-16")] alias exists_restrict_eq_of_closed := exists_restrict_eq end ContinuousMap /-- **Tietze extension theorem** for real-valued continuous maps. `ℝ` is a `TietzeExtension` space. -/ instance Real.instTietzeExtension : TietzeExtension ℝ where exists_restrict_eq' _s hs f := f.exists_restrict_eq_forall_mem_of_closed (fun _ => mem_univ _) univ_nonempty hs |>.imp fun _ ↦ (And.right ·) open NNReal in /-- **Tietze extension theorem** for nonnegative real-valued continuous maps. `ℝ≥0` is a `TietzeExtension` space. -/ instance NNReal.instTietzeExtension : TietzeExtension ℝ≥0 := .of_retract ⟨((↑) : ℝ≥0 → ℝ), by continuity⟩ ⟨Real.toNNReal, continuous_real_toNNReal⟩ <| by ext; simp
Topology\UnitInterval.lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison -/ import Mathlib.Algebra.Order.Interval.Set.Instances import Mathlib.Order.Interval.Set.ProjIcc import Mathlib.Topology.Instances.Real /-! # The unit interval, as a topological space Use `open unitInterval` to turn on the notation `I := Set.Icc (0 : ℝ) (1 : ℝ)`. We provide basic instances, as well as a custom tactic for discharging `0 ≤ ↑x`, `0 ≤ 1 - ↑x`, `↑x ≤ 1`, and `1 - ↑x ≤ 1` when `x : I`. -/ noncomputable section open Topology Filter Set Int Set.Icc /-! ### The unit interval -/ /-- The unit interval `[0,1]` in ℝ. -/ abbrev unitInterval : Set ℝ := Set.Icc 0 1 @[inherit_doc] scoped[unitInterval] notation "I" => unitInterval namespace unitInterval theorem zero_mem : (0 : ℝ) ∈ I := ⟨le_rfl, zero_le_one⟩ theorem one_mem : (1 : ℝ) ∈ I := ⟨zero_le_one, le_rfl⟩ theorem mul_mem {x y : ℝ} (hx : x ∈ I) (hy : y ∈ I) : x * y ∈ I := ⟨mul_nonneg hx.1 hy.1, mul_le_one hx.2 hy.1 hy.2⟩ theorem div_mem {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hxy : x ≤ y) : x / y ∈ I := ⟨div_nonneg hx hy, div_le_one_of_le hxy hy⟩ theorem fract_mem (x : ℝ) : fract x ∈ I := ⟨fract_nonneg _, (fract_lt_one _).le⟩ theorem mem_iff_one_sub_mem {t : ℝ} : t ∈ I ↔ 1 - t ∈ I := by rw [mem_Icc, mem_Icc] constructor <;> intro <;> constructor <;> linarith instance hasZero : Zero I := ⟨⟨0, zero_mem⟩⟩ instance hasOne : One I := ⟨⟨1, by constructor <;> norm_num⟩⟩ instance : ZeroLEOneClass I := ⟨zero_le_one (α := ℝ)⟩ instance : BoundedOrder I := Set.Icc.boundedOrder zero_le_one lemma univ_eq_Icc : (univ : Set I) = Icc (0 : I) (1 : I) := Icc_bot_top.symm theorem coe_ne_zero {x : I} : (x : ℝ) ≠ 0 ↔ x ≠ 0 := not_iff_not.mpr coe_eq_zero theorem coe_ne_one {x : I} : (x : ℝ) ≠ 1 ↔ x ≠ 1 := not_iff_not.mpr coe_eq_one instance : Nonempty I := ⟨0⟩ instance : Mul I := ⟨fun x y => ⟨x * y, mul_mem x.2 y.2⟩⟩ -- todo: we could set up a `LinearOrderedCommMonoidWithZero I` instance theorem mul_le_left {x y : I} : x * y ≤ x := Subtype.coe_le_coe.mp <| mul_le_of_le_one_right x.2.1 y.2.2 theorem mul_le_right {x y : I} : x * y ≤ y := Subtype.coe_le_coe.mp <| mul_le_of_le_one_left y.2.1 x.2.2 /-- Unit interval central symmetry. -/ def symm : I → I := fun t => ⟨1 - t, mem_iff_one_sub_mem.mp t.prop⟩ @[inherit_doc] scoped notation "σ" => unitInterval.symm @[simp] theorem symm_zero : σ 0 = 1 := Subtype.ext <| by simp [symm] @[simp] theorem symm_one : σ 1 = 0 := Subtype.ext <| by simp [symm] @[simp] theorem symm_symm (x : I) : σ (σ x) = x := Subtype.ext <| by simp [symm] theorem symm_involutive : Function.Involutive (symm : I → I) := symm_symm theorem symm_bijective : Function.Bijective (symm : I → I) := symm_involutive.bijective @[simp] theorem coe_symm_eq (x : I) : (σ x : ℝ) = 1 - x := rfl -- Porting note: Proof used to be `by continuity!` @[continuity, fun_prop] theorem continuous_symm : Continuous σ := by apply Continuous.subtype_mk (by fun_prop) /-- `unitInterval.symm` as a `Homeomorph`. -/ @[simps] def symmHomeomorph : I ≃ₜ I where toFun := symm invFun := symm left_inv := symm_symm right_inv := symm_symm theorem strictAnti_symm : StrictAnti σ := fun _ _ h ↦ sub_lt_sub_left (α := ℝ) h _ @[deprecated (since := "2024-02-27")] alias involutive_symm := symm_involutive @[deprecated (since := "2024-02-27")] alias bijective_symm := symm_bijective theorem half_le_symm_iff (t : I) : 1 / 2 ≤ (σ t : ℝ) ↔ (t : ℝ) ≤ 1 / 2 := by rw [coe_symm_eq, le_sub_iff_add_le, add_comm, ← le_sub_iff_add_le, sub_half] instance : ConnectedSpace I := Subtype.connectedSpace ⟨nonempty_Icc.mpr zero_le_one, isPreconnected_Icc⟩ /-- Verify there is an instance for `CompactSpace I`. -/ example : CompactSpace I := by infer_instance theorem nonneg (x : I) : 0 ≤ (x : ℝ) := x.2.1 theorem one_minus_nonneg (x : I) : 0 ≤ 1 - (x : ℝ) := by simpa using x.2.2 theorem le_one (x : I) : (x : ℝ) ≤ 1 := x.2.2 theorem one_minus_le_one (x : I) : 1 - (x : ℝ) ≤ 1 := by simpa using x.2.1 theorem add_pos {t : I} {x : ℝ} (hx : 0 < x) : 0 < (x + t : ℝ) := add_pos_of_pos_of_nonneg hx <| nonneg _ /-- like `unitInterval.nonneg`, but with the inequality in `I`. -/ theorem nonneg' {t : I} : 0 ≤ t := t.2.1 /-- like `unitInterval.le_one`, but with the inequality in `I`. -/ theorem le_one' {t : I} : t ≤ 1 := t.2.2 instance : Nontrivial I := ⟨⟨1, 0, (one_ne_zero <| congrArg Subtype.val ·)⟩⟩ theorem mul_pos_mem_iff {a t : ℝ} (ha : 0 < a) : a * t ∈ I ↔ t ∈ Set.Icc (0 : ℝ) (1 / a) := by constructor <;> rintro ⟨h₁, h₂⟩ <;> constructor · exact nonneg_of_mul_nonneg_right h₁ ha · rwa [le_div_iff ha, mul_comm] · exact mul_nonneg ha.le h₁ · rwa [le_div_iff ha, mul_comm] at h₂ theorem two_mul_sub_one_mem_iff {t : ℝ} : 2 * t - 1 ∈ I ↔ t ∈ Set.Icc (1 / 2 : ℝ) 1 := by constructor <;> rintro ⟨h₁, h₂⟩ <;> constructor <;> linarith end unitInterval section partition namespace Set.Icc variable {α} [LinearOrderedAddCommGroup α] {a b c d : α} (h : a ≤ b) {δ : α} -- TODO: Set.projIci, Set.projIic /-- `Set.projIcc` is a contraction. -/ lemma _root_.Set.abs_projIcc_sub_projIcc : (|projIcc a b h c - projIcc a b h d| : α) ≤ |c - d| := by wlog hdc : d ≤ c generalizing c d · rw [abs_sub_comm, abs_sub_comm c]; exact this (le_of_not_le hdc) rw [abs_eq_self.2 (sub_nonneg.2 hdc), abs_eq_self.2 (sub_nonneg.2 <| monotone_projIcc h hdc)] rw [← sub_nonneg] at hdc refine (max_sub_max_le_max _ _ _ _).trans (max_le (by rwa [sub_self]) ?_) refine ((le_abs_self _).trans <| abs_min_sub_min_le_max _ _ _ _).trans (max_le ?_ ?_) · rwa [sub_self, abs_zero] · exact (abs_eq_self.mpr hdc).le /-- When `h : a ≤ b` and `δ > 0`, `addNSMul h δ` is a sequence of points in the closed interval `[a,b]`, which is initially equally spaced but eventually stays at the right endpoint `b`. -/ def addNSMul (δ : α) (n : ℕ) : Icc a b := projIcc a b h (a + n • δ) lemma addNSMul_zero : addNSMul h δ 0 = a := by rw [addNSMul, zero_smul, add_zero, projIcc_left] lemma addNSMul_eq_right [Archimedean α] (hδ : 0 < δ) : ∃ m, ∀ n ≥ m, addNSMul h δ n = b := by obtain ⟨m, hm⟩ := Archimedean.arch (b - a) hδ refine ⟨m, fun n hn ↦ ?_⟩ rw [addNSMul, coe_projIcc, add_comm, min_eq_left_iff.mpr, max_eq_right h] exact sub_le_iff_le_add.mp (hm.trans <| nsmul_le_nsmul_left hδ.le hn) lemma monotone_addNSMul (hδ : 0 ≤ δ) : Monotone (addNSMul h δ) := fun _ _ hnm ↦ monotone_projIcc h <| (add_le_add_iff_left _).mpr (nsmul_le_nsmul_left hδ hnm) lemma abs_sub_addNSMul_le (hδ : 0 ≤ δ) {t : Icc a b} (n : ℕ) (ht : t ∈ Icc (addNSMul h δ n) (addNSMul h δ (n+1))) : (|t - addNSMul h δ n| : α) ≤ δ := (abs_eq_self.2 <| sub_nonneg.2 ht.1).trans_le <| (sub_le_sub_right (by exact ht.2) _).trans <| (le_abs_self _).trans <| (abs_projIcc_sub_projIcc h).trans <| by rw [add_sub_add_comm, sub_self, zero_add, succ_nsmul', add_sub_cancel_right] exact (abs_eq_self.mpr hδ).le end Set.Icc open scoped unitInterval /-- Any open cover `c` of a closed interval `[a, b]` in ℝ can be refined to a finite partition into subintervals. -/ lemma exists_monotone_Icc_subset_open_cover_Icc {ι} {a b : ℝ} (h : a ≤ b) {c : ι → Set (Icc a b)} (hc₁ : ∀ i, IsOpen (c i)) (hc₂ : univ ⊆ ⋃ i, c i) : ∃ t : ℕ → Icc a b, t 0 = a ∧ Monotone t ∧ (∃ m, ∀ n ≥ m, t n = b) ∧ ∀ n, ∃ i, Icc (t n) (t (n + 1)) ⊆ c i := by obtain ⟨δ, δ_pos, ball_subset⟩ := lebesgue_number_lemma_of_metric isCompact_univ hc₁ hc₂ have hδ := half_pos δ_pos refine ⟨addNSMul h (δ/2), addNSMul_zero h, monotone_addNSMul h hδ.le, addNSMul_eq_right h hδ, fun n ↦ ?_⟩ obtain ⟨i, hsub⟩ := ball_subset (addNSMul h (δ/2) n) trivial exact ⟨i, fun t ht ↦ hsub ((abs_sub_addNSMul_le h hδ.le n ht).trans_lt <| half_lt_self δ_pos)⟩ /-- Any open cover of the unit interval can be refined to a finite partition into subintervals. -/ lemma exists_monotone_Icc_subset_open_cover_unitInterval {ι} {c : ι → Set I} (hc₁ : ∀ i, IsOpen (c i)) (hc₂ : univ ⊆ ⋃ i, c i) : ∃ t : ℕ → I, t 0 = 0 ∧ Monotone t ∧ (∃ n, ∀ m ≥ n, t m = 1) ∧ ∀ n, ∃ i, Icc (t n) (t (n + 1)) ⊆ c i := by simp_rw [← Subtype.coe_inj] exact exists_monotone_Icc_subset_open_cover_Icc zero_le_one hc₁ hc₂ lemma exists_monotone_Icc_subset_open_cover_unitInterval_prod_self {ι} {c : ι → Set (I × I)} (hc₁ : ∀ i, IsOpen (c i)) (hc₂ : univ ⊆ ⋃ i, c i) : ∃ t : ℕ → I, t 0 = 0 ∧ Monotone t ∧ (∃ n, ∀ m ≥ n, t m = 1) ∧ ∀ n m, ∃ i, Icc (t n) (t (n + 1)) ×ˢ Icc (t m) (t (m + 1)) ⊆ c i := by obtain ⟨δ, δ_pos, ball_subset⟩ := lebesgue_number_lemma_of_metric isCompact_univ hc₁ hc₂ have hδ := half_pos δ_pos simp_rw [Subtype.ext_iff] have h : (0 : ℝ) ≤ 1 := zero_le_one refine ⟨addNSMul h (δ/2), addNSMul_zero h, monotone_addNSMul h hδ.le, addNSMul_eq_right h hδ, fun n m ↦ ?_⟩ obtain ⟨i, hsub⟩ := ball_subset (addNSMul h (δ/2) n, addNSMul h (δ/2) m) trivial exact ⟨i, fun t ht ↦ hsub (Metric.mem_ball.mpr <| (max_le (abs_sub_addNSMul_le h hδ.le n ht.1) <| abs_sub_addNSMul_le h hδ.le m ht.2).trans_lt <| half_lt_self δ_pos)⟩ end partition @[simp] theorem projIcc_eq_zero {x : ℝ} : projIcc (0 : ℝ) 1 zero_le_one x = 0 ↔ x ≤ 0 := projIcc_eq_left zero_lt_one @[simp] theorem projIcc_eq_one {x : ℝ} : projIcc (0 : ℝ) 1 zero_le_one x = 1 ↔ 1 ≤ x := projIcc_eq_right zero_lt_one namespace Tactic.Interactive -- Porting note: This replaces an unsafe def tactic /-- A tactic that solves `0 ≤ ↑x`, `0 ≤ 1 - ↑x`, `↑x ≤ 1`, and `1 - ↑x ≤ 1` for `x : I`. -/ macro "unit_interval" : tactic => `(tactic| (first | apply unitInterval.nonneg | apply unitInterval.one_minus_nonneg | apply unitInterval.le_one | apply unitInterval.one_minus_le_one)) example (x : unitInterval) : 0 ≤ (x : ℝ) := by unit_interval end Tactic.Interactive section variable {𝕜 : Type*} [LinearOrderedField 𝕜] [TopologicalSpace 𝕜] [TopologicalRing 𝕜] -- We only need the ordering on `𝕜` here to avoid talking about flipping the interval over. -- At the end of the day I only care about `ℝ`, so I'm hesitant to put work into generalizing. /-- The image of `[0,1]` under the homeomorphism `fun x ↦ a * x + b` is `[b, a+b]`. -/ theorem affineHomeomorph_image_I (a b : 𝕜) (h : 0 < a) : affineHomeomorph a b h.ne.symm '' Set.Icc 0 1 = Set.Icc b (a + b) := by simp [h] /-- The affine homeomorphism from a nontrivial interval `[a,b]` to `[0,1]`. -/ def iccHomeoI (a b : 𝕜) (h : a < b) : Set.Icc a b ≃ₜ Set.Icc (0 : 𝕜) (1 : 𝕜) := by let e := Homeomorph.image (affineHomeomorph (b - a) a (sub_pos.mpr h).ne.symm) (Set.Icc 0 1) refine (e.trans ?_).symm apply Homeomorph.setCongr rw [affineHomeomorph_image_I _ _ (sub_pos.2 h)] simp @[simp] theorem iccHomeoI_apply_coe (a b : 𝕜) (h : a < b) (x : Set.Icc a b) : ((iccHomeoI a b h) x : 𝕜) = (x - a) / (b - a) := rfl @[simp] theorem iccHomeoI_symm_apply_coe (a b : 𝕜) (h : a < b) (x : Set.Icc (0 : 𝕜) (1 : 𝕜)) : ((iccHomeoI a b h).symm x : 𝕜) = (b - a) * x + a := rfl end
Topology\UrysohnsBounded.lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.UrysohnsLemma import Mathlib.Topology.ContinuousFunction.Bounded /-! # Urysohn's lemma for bounded continuous functions In this file we reformulate Urysohn's lemma `exists_continuous_zero_one_of_isClosed` in terms of bounded continuous functions `X →ᵇ ℝ`. These lemmas live in a separate file because `Topology.ContinuousFunction.Bounded` imports too many other files. ## Tags Urysohn's lemma, normal topological space -/ open BoundedContinuousFunction open Set Function /-- **Urysohn's lemma**: if `s` and `t` are two disjoint closed sets in a normal topological space `X`, then there exists a continuous function `f : X → ℝ` such that * `f` equals zero on `s`; * `f` equals one on `t`; * `0 ≤ f x ≤ 1` for all `x`. -/ theorem exists_bounded_zero_one_of_closed {X : Type*} [TopologicalSpace X] [NormalSpace X] {s t : Set X} (hs : IsClosed s) (ht : IsClosed t) (hd : Disjoint s t) : ∃ f : X →ᵇ ℝ, EqOn f 0 s ∧ EqOn f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := let ⟨f, hfs, hft, hf⟩ := exists_continuous_zero_one_of_isClosed hs ht hd ⟨⟨f, 1, fun _ _ => Real.dist_le_of_mem_Icc_01 (hf _) (hf _)⟩, hfs, hft, hf⟩ /-- Urysohn's lemma: if `s` and `t` are two disjoint closed sets in a normal topological space `X`, and `a ≤ b` are two real numbers, then there exists a continuous function `f : X → ℝ` such that * `f` equals `a` on `s`; * `f` equals `b` on `t`; * `a ≤ f x ≤ b` for all `x`. -/ theorem exists_bounded_mem_Icc_of_closed_of_le {X : Type*} [TopologicalSpace X] [NormalSpace X] {s t : Set X} (hs : IsClosed s) (ht : IsClosed t) (hd : Disjoint s t) {a b : ℝ} (hle : a ≤ b) : ∃ f : X →ᵇ ℝ, EqOn f (Function.const X a) s ∧ EqOn f (Function.const X b) t ∧ ∀ x, f x ∈ Icc a b := let ⟨f, hfs, hft, hf01⟩ := exists_bounded_zero_one_of_closed hs ht hd ⟨BoundedContinuousFunction.const X a + (b - a) • f, fun x hx => by simp [hfs hx], fun x hx => by simp [hft hx], fun x => ⟨by dsimp; nlinarith [(hf01 x).1], by dsimp; nlinarith [(hf01 x).2]⟩⟩
Topology\UrysohnsLemma.lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import Mathlib.Analysis.NormedSpace.AddTorsor import Mathlib.LinearAlgebra.AffineSpace.Ordered import Mathlib.Topology.ContinuousFunction.Basic import Mathlib.Topology.GDelta import Mathlib.Analysis.NormedSpace.FunctionSeries import Mathlib.Analysis.SpecificLimits.Basic /-! # Urysohn's lemma In this file we prove Urysohn's lemma `exists_continuous_zero_one_of_isClosed`: for any two disjoint closed sets `s` and `t` in a normal topological space `X` there exists a continuous function `f : X → ℝ` such that * `f` equals zero on `s`; * `f` equals one on `t`; * `0 ≤ f x ≤ 1` for all `x`. We also give versions in a regular locally compact space where one assumes that `s` is compact and `t` is closed, in `exists_continuous_zero_one_of_isCompact` and `exists_continuous_one_zero_of_isCompact` (the latter providing additionally a function with compact support). We write a generic proof so that it applies both to normal spaces and to regular locally compact spaces. ## Implementation notes Most paper sources prove Urysohn's lemma using a family of open sets indexed by dyadic rational numbers on `[0, 1]`. There are many technical difficulties with formalizing this proof (e.g., one needs to formalize the "dyadic induction", then prove that the resulting family of open sets is monotone). So, we formalize a slightly different proof. Let `Urysohns.CU` be the type of pairs `(C, U)` of a closed set `C` and an open set `U` such that `C ⊆ U`. Since `X` is a normal topological space, for each `c : CU` there exists an open set `u` such that `c.C ⊆ u ∧ closure u ⊆ c.U`. We define `c.left` and `c.right` to be `(c.C, u)` and `(closure u, c.U)`, respectively. Then we define a family of functions `Urysohns.CU.approx (c : Urysohns.CU) (n : ℕ) : X → ℝ` by recursion on `n`: * `c.approx 0` is the indicator of `c.Uᶜ`; * `c.approx (n + 1) x = (c.left.approx n x + c.right.approx n x) / 2`. For each `x` this is a monotone family of functions that are equal to zero on `c.C` and are equal to one outside of `c.U`. We also have `c.approx n x ∈ [0, 1]` for all `c`, `n`, and `x`. Let `Urysohns.CU.lim c` be the supremum (or equivalently, the limit) of `c.approx n`. Then properties of `Urysohns.CU.approx` immediately imply that * `c.lim x ∈ [0, 1]` for all `x`; * `c.lim` equals zero on `c.C` and equals one outside of `c.U`; * `c.lim x = (c.left.lim x + c.right.lim x) / 2`. In order to prove that `c.lim` is continuous at `x`, we prove by induction on `n : ℕ` that for `y` in a small neighborhood of `x` we have `|c.lim y - c.lim x| ≤ (3 / 4) ^ n`. Induction base follows from `c.lim x ∈ [0, 1]`, `c.lim y ∈ [0, 1]`. For the induction step, consider two cases: * `x ∈ c.left.U`; then for `y` in a small neighborhood of `x` we have `y ∈ c.left.U ⊆ c.right.C` (hence `c.right.lim x = c.right.lim y = 0`) and `|c.left.lim y - c.left.lim x| ≤ (3 / 4) ^ n`. Then `|c.lim y - c.lim x| = |c.left.lim y - c.left.lim x| / 2 ≤ (3 / 4) ^ n / 2 < (3 / 4) ^ (n + 1)`. * otherwise, `x ∉ c.left.right.C`; then for `y` in a small neighborhood of `x` we have `y ∉ c.left.right.C ⊇ c.left.left.U` (hence `c.left.left.lim x = c.left.left.lim y = 1`), `|c.left.right.lim y - c.left.right.lim x| ≤ (3 / 4) ^ n`, and `|c.right.lim y - c.right.lim x| ≤ (3 / 4) ^ n`. Combining these inequalities, the triangle inequality, and the recurrence formula for `c.lim`, we get `|c.lim x - c.lim y| ≤ (3 / 4) ^ (n + 1)`. The actual formalization uses `midpoint ℝ x y` instead of `(x + y) / 2` because we have more API lemmas about `midpoint`. ## Tags Urysohn's lemma, normal topological space, locally compact topological space -/ variable {X : Type*} [TopologicalSpace X] open Set Filter TopologicalSpace Topology Filter open scoped Pointwise namespace Urysohns /-- An auxiliary type for the proof of Urysohn's lemma: a pair of a closed set `C` and its open neighborhood `U`, together with the assumption that `C` satisfies the property `P C`. The latter assumption will make it possible to prove simultaneously both versions of Urysohn's lemma, in normal spaces (with `P` always true) and in locally compact spaces (with `P = IsCompact`). We put also in the structure the assumption that, for any such pair, one may find an intermediate pair inbetween satisfying `P`, to avoid carrying it around in the argument. -/ structure CU {X : Type*} [TopologicalSpace X] (P : Set X → Prop) where /-- The inner set in the inductive construction towards Urysohn's lemma -/ protected C : Set X /-- The outer set in the inductive construction towards Urysohn's lemma -/ protected U : Set X protected P_C : P C protected closed_C : IsClosed C protected open_U : IsOpen U protected subset : C ⊆ U protected hP : ∀ {c u : Set X}, IsClosed c → P c → IsOpen u → c ⊆ u → ∃ v, IsOpen v ∧ c ⊆ v ∧ closure v ⊆ u ∧ P (closure v) namespace CU variable {P : Set X → Prop} /-- By assumption, for each `c : CU P` there exists an open set `u` such that `c.C ⊆ u` and `closure u ⊆ c.U`. `c.left` is the pair `(c.C, u)`. -/ @[simps C] def left (c : CU P) : CU P where C := c.C U := (c.hP c.closed_C c.P_C c.open_U c.subset).choose closed_C := c.closed_C P_C := c.P_C open_U := (c.hP c.closed_C c.P_C c.open_U c.subset).choose_spec.1 subset := (c.hP c.closed_C c.P_C c.open_U c.subset).choose_spec.2.1 hP := c.hP /-- By assumption, for each `c : CU P` there exists an open set `u` such that `c.C ⊆ u` and `closure u ⊆ c.U`. `c.right` is the pair `(closure u, c.U)`. -/ @[simps U] def right (c : CU P) : CU P where C := closure (c.hP c.closed_C c.P_C c.open_U c.subset).choose U := c.U closed_C := isClosed_closure P_C := (c.hP c.closed_C c.P_C c.open_U c.subset).choose_spec.2.2.2 open_U := c.open_U subset := (c.hP c.closed_C c.P_C c.open_U c.subset).choose_spec.2.2.1 hP := c.hP theorem left_U_subset_right_C (c : CU P) : c.left.U ⊆ c.right.C := subset_closure theorem left_U_subset (c : CU P) : c.left.U ⊆ c.U := Subset.trans c.left_U_subset_right_C c.right.subset theorem subset_right_C (c : CU P) : c.C ⊆ c.right.C := Subset.trans c.left.subset c.left_U_subset_right_C /-- `n`-th approximation to a continuous function `f : X → ℝ` such that `f = 0` on `c.C` and `f = 1` outside of `c.U`. -/ noncomputable def approx : ℕ → CU P → X → ℝ | 0, c, x => indicator c.Uᶜ 1 x | n + 1, c, x => midpoint ℝ (approx n c.left x) (approx n c.right x) theorem approx_of_mem_C (c : CU P) (n : ℕ) {x : X} (hx : x ∈ c.C) : c.approx n x = 0 := by induction' n with n ihn generalizing c · exact indicator_of_not_mem (fun (hU : x ∈ c.Uᶜ) => hU <| c.subset hx) _ · simp only [approx] rw [ihn, ihn, midpoint_self] exacts [c.subset_right_C hx, hx] theorem approx_of_nmem_U (c : CU P) (n : ℕ) {x : X} (hx : x ∉ c.U) : c.approx n x = 1 := by induction' n with n ihn generalizing c · rw [← mem_compl_iff] at hx exact indicator_of_mem hx _ · simp only [approx] rw [ihn, ihn, midpoint_self] exacts [hx, fun hU => hx <| c.left_U_subset hU] theorem approx_nonneg (c : CU P) (n : ℕ) (x : X) : 0 ≤ c.approx n x := by induction' n with n ihn generalizing c · exact indicator_nonneg (fun _ _ => zero_le_one) _ · simp only [approx, midpoint_eq_smul_add, invOf_eq_inv] refine mul_nonneg (inv_nonneg.2 zero_le_two) (add_nonneg ?_ ?_) <;> apply ihn theorem approx_le_one (c : CU P) (n : ℕ) (x : X) : c.approx n x ≤ 1 := by induction' n with n ihn generalizing c · exact indicator_apply_le' (fun _ => le_rfl) fun _ => zero_le_one · simp only [approx, midpoint_eq_smul_add, invOf_eq_inv, smul_eq_mul, ← div_eq_inv_mul] have := add_le_add (ihn (left c)) (ihn (right c)) norm_num at this exact Iff.mpr (div_le_one zero_lt_two) this theorem bddAbove_range_approx (c : CU P) (x : X) : BddAbove (range fun n => c.approx n x) := ⟨1, fun _ ⟨n, hn⟩ => hn ▸ c.approx_le_one n x⟩ theorem approx_le_approx_of_U_sub_C {c₁ c₂ : CU P} (h : c₁.U ⊆ c₂.C) (n₁ n₂ : ℕ) (x : X) : c₂.approx n₂ x ≤ c₁.approx n₁ x := by by_cases hx : x ∈ c₁.U · calc approx n₂ c₂ x = 0 := approx_of_mem_C _ _ (h hx) _ ≤ approx n₁ c₁ x := approx_nonneg _ _ _ · calc approx n₂ c₂ x ≤ 1 := approx_le_one _ _ _ _ = approx n₁ c₁ x := (approx_of_nmem_U _ _ hx).symm theorem approx_mem_Icc_right_left (c : CU P) (n : ℕ) (x : X) : c.approx n x ∈ Icc (c.right.approx n x) (c.left.approx n x) := by induction' n with n ihn generalizing c · exact ⟨le_rfl, indicator_le_indicator_of_subset (compl_subset_compl.2 c.left_U_subset) (fun _ => zero_le_one) _⟩ · simp only [approx, mem_Icc] refine ⟨midpoint_le_midpoint ?_ (ihn _).1, midpoint_le_midpoint (ihn _).2 ?_⟩ <;> apply approx_le_approx_of_U_sub_C exacts [subset_closure, subset_closure] theorem approx_le_succ (c : CU P) (n : ℕ) (x : X) : c.approx n x ≤ c.approx (n + 1) x := by induction' n with n ihn generalizing c · simp only [approx, right_U, right_le_midpoint] exact (approx_mem_Icc_right_left c 0 x).2 · rw [approx, approx] exact midpoint_le_midpoint (ihn _) (ihn _) theorem approx_mono (c : CU P) (x : X) : Monotone fun n => c.approx n x := monotone_nat_of_le_succ fun n => c.approx_le_succ n x /-- A continuous function `f : X → ℝ` such that * `0 ≤ f x ≤ 1` for all `x`; * `f` equals zero on `c.C` and equals one outside of `c.U`; -/ protected noncomputable def lim (c : CU P) (x : X) : ℝ := ⨆ n, c.approx n x theorem tendsto_approx_atTop (c : CU P) (x : X) : Tendsto (fun n => c.approx n x) atTop (𝓝 <| c.lim x) := tendsto_atTop_ciSup (c.approx_mono x) ⟨1, fun _ ⟨_, hn⟩ => hn ▸ c.approx_le_one _ _⟩ theorem lim_of_mem_C (c : CU P) (x : X) (h : x ∈ c.C) : c.lim x = 0 := by simp only [CU.lim, approx_of_mem_C, h, ciSup_const] theorem lim_of_nmem_U (c : CU P) (x : X) (h : x ∉ c.U) : c.lim x = 1 := by simp only [CU.lim, approx_of_nmem_U c _ h, ciSup_const] theorem lim_eq_midpoint (c : CU P) (x : X) : c.lim x = midpoint ℝ (c.left.lim x) (c.right.lim x) := by refine tendsto_nhds_unique (c.tendsto_approx_atTop x) ((tendsto_add_atTop_iff_nat 1).1 ?_) simp only [approx] exact (c.left.tendsto_approx_atTop x).midpoint (c.right.tendsto_approx_atTop x) theorem approx_le_lim (c : CU P) (x : X) (n : ℕ) : c.approx n x ≤ c.lim x := le_ciSup (c.bddAbove_range_approx x) _ theorem lim_nonneg (c : CU P) (x : X) : 0 ≤ c.lim x := (c.approx_nonneg 0 x).trans (c.approx_le_lim x 0) theorem lim_le_one (c : CU P) (x : X) : c.lim x ≤ 1 := ciSup_le fun _ => c.approx_le_one _ _ theorem lim_mem_Icc (c : CU P) (x : X) : c.lim x ∈ Icc (0 : ℝ) 1 := ⟨c.lim_nonneg x, c.lim_le_one x⟩ /-- Continuity of `Urysohns.CU.lim`. See module docstring for a sketch of the proofs. -/ theorem continuous_lim (c : CU P) : Continuous c.lim := by obtain ⟨h0, h1234, h1⟩ : 0 < (2⁻¹ : ℝ) ∧ (2⁻¹ : ℝ) < 3 / 4 ∧ (3 / 4 : ℝ) < 1 := by norm_num refine continuous_iff_continuousAt.2 fun x => (Metric.nhds_basis_closedBall_pow (h0.trans h1234) h1).tendsto_right_iff.2 fun n _ => ?_ simp only [Metric.mem_closedBall] induction' n with n ihn generalizing c · filter_upwards with y rw [pow_zero] exact Real.dist_le_of_mem_Icc_01 (c.lim_mem_Icc _) (c.lim_mem_Icc _) · by_cases hxl : x ∈ c.left.U · filter_upwards [IsOpen.mem_nhds c.left.open_U hxl, ihn c.left] with _ hyl hyd rw [pow_succ', c.lim_eq_midpoint, c.lim_eq_midpoint, c.right.lim_of_mem_C _ (c.left_U_subset_right_C hyl), c.right.lim_of_mem_C _ (c.left_U_subset_right_C hxl)] refine (dist_midpoint_midpoint_le _ _ _ _).trans ?_ rw [dist_self, add_zero, div_eq_inv_mul] gcongr · replace hxl : x ∈ c.left.right.Cᶜ := compl_subset_compl.2 c.left.right.subset hxl filter_upwards [IsOpen.mem_nhds (isOpen_compl_iff.2 c.left.right.closed_C) hxl, ihn c.left.right, ihn c.right] with y hyl hydl hydr replace hxl : x ∉ c.left.left.U := compl_subset_compl.2 c.left.left_U_subset_right_C hxl replace hyl : y ∉ c.left.left.U := compl_subset_compl.2 c.left.left_U_subset_right_C hyl simp only [pow_succ, c.lim_eq_midpoint, c.left.lim_eq_midpoint, c.left.left.lim_of_nmem_U _ hxl, c.left.left.lim_of_nmem_U _ hyl] refine (dist_midpoint_midpoint_le _ _ _ _).trans ?_ refine (div_le_div_of_nonneg_right (add_le_add_right (dist_midpoint_midpoint_le _ _ _ _) _) zero_le_two).trans ?_ rw [dist_self, zero_add] set r := (3 / 4 : ℝ) ^ n calc _ ≤ (r / 2 + r) / 2 := by gcongr _ = _ := by field_simp; ring end CU end Urysohns /-- Urysohn's lemma: if `s` and `t` are two disjoint closed sets in a normal topological space `X`, then there exists a continuous function `f : X → ℝ` such that * `f` equals zero on `s`; * `f` equals one on `t`; * `0 ≤ f x ≤ 1` for all `x`. -/ theorem exists_continuous_zero_one_of_isClosed [NormalSpace X] {s t : Set X} (hs : IsClosed s) (ht : IsClosed t) (hd : Disjoint s t) : ∃ f : C(X, ℝ), EqOn f 0 s ∧ EqOn f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := by -- The actual proof is in the code above. Here we just repack it into the expected format. let P : Set X → Prop := fun _ ↦ True set c : Urysohns.CU P := { C := s U := tᶜ P_C := trivial closed_C := hs open_U := ht.isOpen_compl subset := disjoint_left.1 hd hP := by rintro c u c_closed - u_open cu rcases normal_exists_closure_subset c_closed u_open cu with ⟨v, v_open, cv, hv⟩ exact ⟨v, v_open, cv, hv, trivial⟩ } exact ⟨⟨c.lim, c.continuous_lim⟩, c.lim_of_mem_C, fun x hx => c.lim_of_nmem_U _ fun h => h hx, c.lim_mem_Icc⟩ /-- Urysohn's lemma: if `s` and `t` are two disjoint sets in a regular locally compact topological space `X`, with `s` compact and `t` closed, then there exists a continuous function `f : X → ℝ` such that * `f` equals zero on `s`; * `f` equals one on `t`; * `0 ≤ f x ≤ 1` for all `x`. -/ theorem exists_continuous_zero_one_of_isCompact [RegularSpace X] [LocallyCompactSpace X] {s t : Set X} (hs : IsCompact s) (ht : IsClosed t) (hd : Disjoint s t) : ∃ f : C(X, ℝ), EqOn f 0 s ∧ EqOn f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := by obtain ⟨k, k_comp, k_closed, sk, kt⟩ : ∃ k, IsCompact k ∧ IsClosed k ∧ s ⊆ interior k ∧ k ⊆ tᶜ := exists_compact_closed_between hs ht.isOpen_compl hd.symm.subset_compl_left let P : Set X → Prop := IsCompact set c : Urysohns.CU P := { C := k U := tᶜ P_C := k_comp closed_C := k_closed open_U := ht.isOpen_compl subset := kt hP := by rintro c u - c_comp u_open cu rcases exists_compact_closed_between c_comp u_open cu with ⟨k, k_comp, k_closed, ck, ku⟩ have A : closure (interior k) ⊆ k := (IsClosed.closure_subset_iff k_closed).2 interior_subset refine ⟨interior k, isOpen_interior, ck, A.trans ku, k_comp.of_isClosed_subset isClosed_closure A⟩ } exact ⟨⟨c.lim, c.continuous_lim⟩, fun x hx ↦ c.lim_of_mem_C _ (sk.trans interior_subset hx), fun x hx => c.lim_of_nmem_U _ fun h => h hx, c.lim_mem_Icc⟩ /-- Urysohn's lemma: if `s` and `t` are two disjoint sets in a regular locally compact topological space `X`, with `s` compact and `t` closed, then there exists a continuous compactly supported function `f : X → ℝ` such that * `f` equals one on `s`; * `f` equals zero on `t`; * `0 ≤ f x ≤ 1` for all `x`. -/ theorem exists_continuous_one_zero_of_isCompact [RegularSpace X] [LocallyCompactSpace X] {s t : Set X} (hs : IsCompact s) (ht : IsClosed t) (hd : Disjoint s t) : ∃ f : C(X, ℝ), EqOn f 1 s ∧ EqOn f 0 t ∧ HasCompactSupport f ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := by obtain ⟨k, k_comp, k_closed, sk, kt⟩ : ∃ k, IsCompact k ∧ IsClosed k ∧ s ⊆ interior k ∧ k ⊆ tᶜ := exists_compact_closed_between hs ht.isOpen_compl hd.symm.subset_compl_left rcases exists_continuous_zero_one_of_isCompact hs isOpen_interior.isClosed_compl (disjoint_compl_right_iff_subset.mpr sk) with ⟨⟨f, hf⟩, hfs, hft, h'f⟩ have A : t ⊆ (interior k)ᶜ := subset_compl_comm.mpr (interior_subset.trans kt) refine ⟨⟨fun x ↦ 1 - f x, continuous_const.sub hf⟩, fun x hx ↦ by simpa using hfs hx, fun x hx ↦ by simpa [sub_eq_zero] using (hft (A hx)).symm, ?_, fun x ↦ ?_⟩ · apply HasCompactSupport.intro' k_comp k_closed (fun x hx ↦ ?_) simp only [ContinuousMap.coe_mk, sub_eq_zero] apply (hft _).symm contrapose! hx simp only [mem_compl_iff, not_not] at hx exact interior_subset hx · have : 0 ≤ f x ∧ f x ≤ 1 := by simpa using h'f x simp [this] /-- Urysohn's lemma: if `s` and `t` are two disjoint sets in a regular locally compact topological space `X`, with `s` compact and `t` closed, then there exists a continuous compactly supported function `f : X → ℝ` such that * `f` equals one on `s`; * `f` equals zero on `t`; * `0 ≤ f x ≤ 1` for all `x`. Moreover, if `s` is Gδ, one can ensure that `f ⁻¹ {1}` is exactly `s`. -/ theorem exists_continuous_one_zero_of_isCompact_of_isGδ [RegularSpace X] [LocallyCompactSpace X] {s t : Set X} (hs : IsCompact s) (h's : IsGδ s) (ht : IsClosed t) (hd : Disjoint s t) : ∃ f : C(X, ℝ), s = f ⁻¹' {1} ∧ EqOn f 0 t ∧ HasCompactSupport f ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := by rcases h's.eq_iInter_nat with ⟨U, U_open, hU⟩ obtain ⟨m, m_comp, -, sm, mt⟩ : ∃ m, IsCompact m ∧ IsClosed m ∧ s ⊆ interior m ∧ m ⊆ tᶜ := exists_compact_closed_between hs ht.isOpen_compl hd.symm.subset_compl_left have A n : ∃ f : C(X, ℝ), EqOn f 1 s ∧ EqOn f 0 (U n ∩ interior m)ᶜ ∧ HasCompactSupport f ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := by apply exists_continuous_one_zero_of_isCompact hs ((U_open n).inter isOpen_interior).isClosed_compl rw [disjoint_compl_right_iff_subset] exact subset_inter ((hU.subset.trans (iInter_subset U n))) sm choose f fs fm _hf f_range using A obtain ⟨u, u_pos, u_sum, hu⟩ : ∃ (u : ℕ → ℝ), (∀ i, 0 < u i) ∧ Summable u ∧ ∑' i, u i = 1 := ⟨fun n ↦ 1/2/2^n, fun n ↦ by positivity, summable_geometric_two' 1, tsum_geometric_two' 1⟩ let g : X → ℝ := fun x ↦ ∑' n, u n * f n x have hgmc : EqOn g 0 mᶜ := by intro x hx have B n : f n x = 0 := by have : mᶜ ⊆ (U n ∩ interior m)ᶜ := by simpa using inter_subset_right.trans interior_subset exact fm n (this hx) simp [g, B] have I n x : u n * f n x ≤ u n := mul_le_of_le_one_right (u_pos n).le (f_range n x).2 have S x : Summable (fun n ↦ u n * f n x) := Summable.of_nonneg_of_le (fun n ↦ mul_nonneg (u_pos n).le (f_range n x).1) (fun n ↦ I n x) u_sum refine ⟨⟨g, ?_⟩, ?_, hgmc.mono (subset_compl_comm.mp mt), ?_, fun x ↦ ⟨?_, ?_⟩⟩ · apply continuous_tsum (fun n ↦ continuous_const.mul (f n).continuous) u_sum (fun n x ↦ ?_) simpa [abs_of_nonneg, (u_pos n).le, (f_range n x).1] using I n x · apply Subset.antisymm (fun x hx ↦ by simp [g, fs _ hx, hu]) ?_ apply compl_subset_compl.1 intro x hx obtain ⟨n, hn⟩ : ∃ n, x ∉ U n := by simpa [hU] using hx have fnx : f n x = 0 := fm _ (by simp [hn]) have : g x < 1 := by apply lt_of_lt_of_le ?_ hu.le exact tsum_lt_tsum (i := n) (fun i ↦ I i x) (by simp [fnx, u_pos n]) (S x) u_sum simpa using this.ne · exact HasCompactSupport.of_support_subset_isCompact m_comp (Function.support_subset_iff'.mpr hgmc) · exact tsum_nonneg (fun n ↦ mul_nonneg (u_pos n).le (f_range n x).1) · apply le_trans _ hu.le exact tsum_le_tsum (fun n ↦ I n x) (S x) u_sum theorem exists_continuous_nonneg_pos [RegularSpace X] [LocallyCompactSpace X] (x : X) : ∃ f : C(X, ℝ), HasCompactSupport f ∧ 0 ≤ (f : X → ℝ) ∧ f x ≠ 0 := by rcases exists_compact_mem_nhds x with ⟨k, hk, k_mem⟩ rcases exists_continuous_one_zero_of_isCompact hk isClosed_empty (disjoint_empty k) with ⟨f, fk, -, f_comp, hf⟩ refine ⟨f, f_comp, fun x ↦ (hf x).1, ?_⟩ have := fk (mem_of_mem_nhds k_mem) simp only [ContinuousMap.coe_mk, Pi.one_apply] at this simp [this]
Topology\Algebra\Affine.lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import Mathlib.LinearAlgebra.AffineSpace.AffineMap import Mathlib.Topology.Algebra.Group.Basic import Mathlib.Topology.Algebra.MulAction /-! # Topological properties of affine spaces and maps For now, this contains only a few facts regarding the continuity of affine maps in the special case when the point space and vector space are the same. TODO: Deal with the case where the point spaces are different from the vector spaces. Note that we do have some results in this direction under the assumption that the topologies are induced by (semi)norms. -/ namespace AffineMap variable {R E F : Type*} variable [AddCommGroup E] [TopologicalSpace E] variable [AddCommGroup F] [TopologicalSpace F] [TopologicalAddGroup F] section Ring variable [Ring R] [Module R E] [Module R F] /-- An affine map is continuous iff its underlying linear map is continuous. See also `AffineMap.continuous_linear_iff`. -/ theorem continuous_iff {f : E →ᵃ[R] F} : Continuous f ↔ Continuous f.linear := by constructor · intro hc rw [decomp' f] exact hc.sub continuous_const · intro hc rw [decomp f] exact hc.add continuous_const /-- The line map is continuous. -/ @[continuity] theorem lineMap_continuous [TopologicalSpace R] [ContinuousSMul R F] {p v : F} : Continuous (lineMap p v : R →ᵃ[R] F) := continuous_iff.mpr <| (continuous_id.smul continuous_const).add <| @continuous_const _ _ _ _ (0 : F) end Ring section CommRing variable [CommRing R] [Module R F] [ContinuousConstSMul R F] @[continuity] theorem homothety_continuous (x : F) (t : R) : Continuous <| homothety x t := by suffices ⇑(homothety x t) = fun y => t • (y - x) + x by rw [this] exact ((continuous_id.sub continuous_const).const_smul _).add continuous_const -- Porting note: proof was `by continuity` ext y simp [homothety_apply] end CommRing section Field variable [Field R] [Module R F] [ContinuousConstSMul R F] theorem homothety_isOpenMap (x : F) (t : R) (ht : t ≠ 0) : IsOpenMap <| homothety x t := by apply IsOpenMap.of_inverse (homothety_continuous x t⁻¹) <;> intro e <;> simp [← AffineMap.comp_apply, ← homothety_mul, ht] end Field end AffineMap
Topology\Algebra\Algebra.lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Antoine Chambert-Loir, María Inés de Frutos-Fernández -/ import Mathlib.Algebra.Algebra.Subalgebra.Basic import Mathlib.Topology.Algebra.Module.Basic import Mathlib.RingTheory.Adjoin.Basic /-! # Topological (sub)algebras A topological algebra over a topological semiring `R` is a topological semiring with a compatible continuous scalar multiplication by elements of `R`. We reuse typeclass `ContinuousSMul` for topological algebras. ## Results The topological closure of a subalgebra is still a subalgebra, which as an algebra is a topological algebra. In this file we define continuous algebra homomorphisms, as algebra homomorphisms between topological (semi-)rings which are continuous. The set of continuous algebra homomorphisms between the topological `R`-algebras `A` and `B` is denoted by `A →R[A] B`. TODO: add continuous algebra isomorphisms. -/ open Set TopologicalSpace Algebra universe u v w section TopologicalAlgebra variable (R : Type*) (A : Type u) variable [CommSemiring R] [Semiring A] [Algebra R A] variable [TopologicalSpace R] [TopologicalSpace A] @[continuity, fun_prop] theorem continuous_algebraMap [ContinuousSMul R A] : Continuous (algebraMap R A) := by rw [algebraMap_eq_smul_one'] exact continuous_id.smul continuous_const theorem continuous_algebraMap_iff_smul [TopologicalSemiring A] : Continuous (algebraMap R A) ↔ Continuous fun p : R × A => p.1 • p.2 := by refine ⟨fun h => ?_, fun h => have : ContinuousSMul R A := ⟨h⟩; continuous_algebraMap _ _⟩ simp only [Algebra.smul_def] exact (h.comp continuous_fst).mul continuous_snd theorem continuousSMul_of_algebraMap [TopologicalSemiring A] (h : Continuous (algebraMap R A)) : ContinuousSMul R A := ⟨(continuous_algebraMap_iff_smul R A).1 h⟩ variable [ContinuousSMul R A] /-- The inclusion of the base ring in a topological algebra as a continuous linear map. -/ @[simps] def algebraMapCLM : R →L[R] A := { Algebra.linearMap R A with toFun := algebraMap R A cont := continuous_algebraMap R A } theorem algebraMapCLM_coe : ⇑(algebraMapCLM R A) = algebraMap R A := rfl theorem algebraMapCLM_toLinearMap : (algebraMapCLM R A).toLinearMap = Algebra.linearMap R A := rfl /-- If `R` is a discrete topological ring, then any topological ring `S` which is an `R`-algebra is also a topological `R`-algebra. NB: This could be an instance but the signature makes it very expensive in search. See #15339 for the regressions caused by making this an instance. -/ theorem DiscreteTopology.instContinuousSMul [TopologicalSemiring A] [DiscreteTopology R] : ContinuousSMul R A := continuousSMul_of_algebraMap _ _ continuous_of_discreteTopology end TopologicalAlgebra section TopologicalAlgebra section variable (R : Type*) [CommSemiring R] (A : Type*) [Semiring A] /-- Continuous algebra homomorphisms between algebras. We only put the type classes that are necessary for the definition, although in applications `M` and `B` will be topological algebras over the topological ring `R`. -/ structure ContinuousAlgHom (R : Type*) [CommSemiring R] (A : Type*) [Semiring A] [TopologicalSpace A] (B : Type*) [Semiring B] [TopologicalSpace B] [Algebra R A] [Algebra R B] extends A →ₐ[R] B where -- TODO: replace with `fun_prop` when that is stable cont : Continuous toFun := by continuity @[inherit_doc] notation:25 A " →A[" R "] " B => ContinuousAlgHom R A B namespace ContinuousAlgHom section Semiring variable {R} {A} variable [TopologicalSpace A] variable {B : Type*} [Semiring B] [TopologicalSpace B] [Algebra R A] [Algebra R B] instance : FunLike (A →A[R] B) A B where coe f := f.toAlgHom coe_injective' f g h := by cases f; cases g simp only [mk.injEq] exact AlgHom.ext (congrFun h) instance : AlgHomClass (A →A[R] B) R A B where map_mul f x y := map_mul f.toAlgHom x y map_one f := map_one f.toAlgHom map_add f := map_add f.toAlgHom map_zero f := map_zero f.toAlgHom commutes f r := f.toAlgHom.commutes r @[simp] theorem toAlgHom_eq_coe (f : A →A[R] B) : f.toAlgHom = f := rfl @[simp, norm_cast] theorem coe_inj {f g : A →A[R] B} : (f : A →ₐ[R] B) = g ↔ f = g := by cases f; cases g; simp only [mk.injEq]; exact Eq.congr_right rfl @[simp] theorem coe_mk (f : A →ₐ[R] B) (h) : (mk f h : A →ₐ[R] B) = f := rfl @[simp] theorem coe_mk' (f : A →ₐ[R] B) (h) : (mk f h : A → B) = f := rfl @[simp, norm_cast] theorem coe_coe (f : A →A[R] B) : ⇑(f : A →ₐ[R] B) = f := rfl instance : ContinuousMapClass (A →A[R] B) A B where map_continuous f := f.2 @[fun_prop] protected theorem continuous (f : A →A[R] B) : Continuous f := f.2 protected theorem uniformContinuous {E₁ E₂ : Type*} [UniformSpace E₁] [UniformSpace E₂] [Ring E₁] [Ring E₂] [Algebra R E₁] [Algebra R E₂] [UniformAddGroup E₁] [UniformAddGroup E₂] (f : E₁ →A[R] E₂) : UniformContinuous f := uniformContinuous_addMonoidHom_of_continuous f.continuous /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def Simps.apply (h : A →A[R] B) : A → B := h /-- See Note [custom simps projection]. -/ def Simps.coe (h : A →A[R] B) : A →ₐ[R] B := h initialize_simps_projections ContinuousAlgHom (toAlgHom_toFun → apply, toAlgHom → coe) @[ext] theorem ext {f g : A →A[R] B} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h /-- Copy of a `ContinuousAlgHom` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ def copy (f : A →A[R] B) (f' : A → B) (h : f' = ⇑f) : A →A[R] B where toAlgHom := { toRingHom := (f : A →A[R] B).toRingHom.copy f' h commutes' := fun r => by simp only [AlgHom.toRingHom_eq_coe, h, RingHom.toMonoidHom_eq_coe, OneHom.toFun_eq_coe, MonoidHom.toOneHom_coe, MonoidHom.coe_coe, RingHom.coe_copy, AlgHomClass.commutes f r] } cont := show Continuous f' from h.symm ▸ f.continuous @[simp] theorem coe_copy (f : A →A[R] B) (f' : A → B) (h : f' = ⇑f) : ⇑(f.copy f' h) = f' := rfl theorem copy_eq (f : A →A[R] B) (f' : A → B) (h : f' = ⇑f) : f.copy f' h = f := DFunLike.ext' h protected theorem map_zero (f : A →A[R] B) : f (0 : A) = 0 := map_zero f protected theorem map_add (f : A →A[R] B) (x y : A) : f (x + y) = f x + f y := map_add f x y protected theorem map_smul (f : A →A[R] B) (c : R) (x : A) : f (c • x) = c • f x := map_smul .. theorem map_smul_of_tower {R S : Type*} [CommSemiring S] [SMul R A] [Algebra S A] [SMul R B] [Algebra S B] [MulActionHomClass (A →A[S] B) R A B] (f : A →A[S] B) (c : R) (x : A) : f (c • x) = c • f x := map_smul f c x protected theorem map_sum {ι : Type*} (f : A →A[R] B) (s : Finset ι) (g : ι → A) : f (∑ i in s, g i) = ∑ i in s, f (g i) := map_sum .. /-- Any two continuous `R`-algebra morphisms from `R` are equal -/ @[ext (iff := false)] theorem ext_ring [TopologicalSpace R] {f g : R →A[R] A} : f = g := coe_inj.mp (ext_id _ _ _) theorem ext_ring_iff [TopologicalSpace R] {f g : R →A[R] A} : f = g ↔ f 1 = g 1 := ⟨fun h => h ▸ rfl, fun _ => ext_ring ⟩ /-- If two continuous algebra maps are equal on a set `s`, then they are equal on the closure of the `Algebra.adjoin` of this set. -/ theorem eqOn_closure_adjoin [T2Space B] {s : Set A} {f g : A →A[R] B} (h : Set.EqOn f g s) : Set.EqOn f g (closure (Algebra.adjoin R s : Set A)) := Set.EqOn.closure (AlgHom.eqOn_adjoin_iff.mpr h) f.continuous g.continuous /-- If the subalgebra generated by a set `s` is dense in the ambient module, then two continuous algebra maps equal on `s` are equal. -/ theorem ext_on [T2Space B] {s : Set A} (hs : Dense (Algebra.adjoin R s : Set A)) {f g : A →A[R] B} (h : Set.EqOn f g s) : f = g := ext fun x => eqOn_closure_adjoin h (hs x) variable [TopologicalSemiring A] /-- The topological closure of a subalgebra -/ def _root_.Subalgebra.topologicalClosure (s : Subalgebra R A) : Subalgebra R A where toSubsemiring := s.toSubsemiring.topologicalClosure algebraMap_mem' r := by simp only [Subsemiring.coe_carrier_toSubmonoid, Subsemiring.topologicalClosure_coe, Subalgebra.coe_toSubsemiring] apply subset_closure exact algebraMap_mem s r /-- Under a continuous algebra map, the image of the `TopologicalClosure` of a subalgebra is contained in the `TopologicalClosure` of its image. -/ theorem _root_.Subalgebra.topologicalClosure_map [TopologicalSemiring B] (f : A →A[R] B) (s : Subalgebra R A) : s.topologicalClosure.map f ≤ (s.map f.toAlgHom).topologicalClosure := image_closure_subset_closure_image f.continuous @[simp] theorem _root_.Subalgebra.topologicalClosure_coe (s : Subalgebra R A) : (s.topologicalClosure : Set A) = closure ↑s := rfl /-- Under a dense continuous algebra map, a subalgebra whose `TopologicalClosure` is `⊤` is sent to another such submodule. That is, the image of a dense subalgebra under a map with dense range is dense. -/ theorem _root_.DenseRange.topologicalClosure_map_subalgebra [TopologicalSemiring B] {f : A →A[R] B} (hf' : DenseRange f) {s : Subalgebra R A} (hs : s.topologicalClosure = ⊤) : (s.map (f : A →ₐ[R] B)).topologicalClosure = ⊤ := by rw [SetLike.ext'_iff] at hs ⊢ simp only [Subalgebra.topologicalClosure_coe, coe_top, ← dense_iff_closure_eq, Subalgebra.coe_map, AlgHom.coe_coe] at hs ⊢ exact hf'.dense_image f.continuous hs end Semiring section id variable [TopologicalSpace A] variable [Algebra R A] /-- The identity map as a continuous algebra homomorphism. -/ protected def id : A →A[R] A := ⟨AlgHom.id R A, continuous_id⟩ instance : One (A →A[R] A) := ⟨ContinuousAlgHom.id R A⟩ theorem one_def : (1 : A →A[R] A) = ContinuousAlgHom.id R A := rfl theorem id_apply (x : A) : ContinuousAlgHom.id R A x = x := rfl @[simp, norm_cast] theorem coe_id : ((ContinuousAlgHom.id R A) : A →ₐ[R] A) = AlgHom.id R A:= rfl @[simp, norm_cast] theorem coe_id' : ⇑(ContinuousAlgHom.id R A ) = _root_.id := rfl @[simp, norm_cast] theorem coe_eq_id {f : A →A[R] A} : (f : A →ₐ[R] A) = AlgHom.id R A ↔ f = ContinuousAlgHom.id R A:= by rw [← coe_id, coe_inj] @[simp] theorem one_apply (x : A) : (1 : A →A[R] A) x = x := rfl end id section comp variable {R} {A} variable [TopologicalSpace A] variable {B : Type*} [Semiring B] [TopologicalSpace B] [Algebra R A] [Algebra R B] {C : Type*} [Semiring C] [Algebra R C] [TopologicalSpace C] /-- Composition of continuous algebra homomorphisms. -/ def comp (g : B →A[R] C) (f : A →A[R] B) : A →A[R] C := ⟨(g : B →ₐ[R] C).comp (f : A →ₐ[R] B), g.2.comp f.2⟩ @[simp, norm_cast] theorem coe_comp (h : B →A[R] C) (f : A →A[R] B) : (h.comp f : A →ₐ[R] C) = (h : B →ₐ[R] C).comp (f : A →ₐ[R] B) := rfl @[simp, norm_cast] theorem coe_comp' (h : B →A[R] C) (f : A →A[R] B) : ⇑(h.comp f) = h ∘ f := rfl theorem comp_apply (g : B →A[R] C) (f : A →A[R] B) (x : A) : (g.comp f) x = g (f x) := rfl @[simp] theorem comp_id (f : A →A[R] B) : f.comp (ContinuousAlgHom.id R A) = f := ext fun _x => rfl @[simp] theorem id_comp (f : A →A[R] B) : (ContinuousAlgHom.id R B).comp f = f := ext fun _x => rfl theorem comp_assoc {D : Type*} [Semiring D] [Algebra R D] [TopologicalSpace D] (h : C →A[R] D) (g : B →A[R] C) (f : A →A[R] B) : (h.comp g).comp f = h.comp (g.comp f) := rfl instance : Mul (A →A[R] A) := ⟨comp⟩ theorem mul_def (f g : A →A[R] A) : f * g = f.comp g := rfl @[simp] theorem coe_mul (f g : A →A[R] A) : ⇑(f * g) = f ∘ g := rfl theorem mul_apply (f g : A →A[R] A) (x : A) : (f * g) x = f (g x) := rfl instance : Monoid (A →A[R] A) where mul_one _ := ext fun _ => rfl one_mul _ := ext fun _ => rfl mul_assoc _ _ _ := ext fun _ => rfl theorem coe_pow (f : A →A[R] A) (n : ℕ) : ⇑(f ^ n) = f^[n] := hom_coe_pow _ rfl (fun _ _ ↦ rfl) _ _ /-- coercion from `ContinuousAlgHom` to `AlgHom` as a `RingHom`. -/ @[simps] def toAlgHomMonoidHom : (A →A[R] A) →* A →ₐ[R] A where toFun := (↑) map_one' := rfl map_mul' _ _ := rfl end comp section prod variable {R} {A} variable [TopologicalSpace A] variable {B : Type*} [Semiring B] [TopologicalSpace B] [Algebra R A] [Algebra R B] {C : Type*} [Semiring C] [Algebra R C] [TopologicalSpace C] /-- The cartesian product of two continuous algebra morphisms as a continuous algebra morphism. -/ protected def prod (f₁ : A →A[R] B) (f₂ : A →A[R] C) : A →A[R] B × C := ⟨(f₁ : A →ₐ[R] B).prod f₂, f₁.2.prod_mk f₂.2⟩ @[simp, norm_cast] theorem coe_prod (f₁ : A →A[R] B) (f₂ : A →A[R] C) : (f₁.prod f₂ : A →ₐ[R] B × C) = AlgHom.prod f₁ f₂ := rfl @[simp, norm_cast] theorem prod_apply (f₁ : A →A[R] B) (f₂ : A →A[R] C) (x : A) : f₁.prod f₂ x = (f₁ x, f₂ x) := rfl variable {F : Type*} instance {D : Type*} [UniformSpace D] [CompleteSpace D] [Semiring D] [Algebra R D] [T2Space B] [FunLike F D B] [AlgHomClass F R D B] [ContinuousMapClass F D B] (f g : F) : CompleteSpace (AlgHom.equalizer f g) := isClosed_eq (map_continuous f) (map_continuous g) |>.completeSpace_coe variable (R A B) /-- `Prod.fst` as a `ContinuousAlgHom`. -/ def fst : A × B →A[R] A where cont := continuous_fst toAlgHom := AlgHom.fst R A B /-- `Prod.snd` as a `ContinuousAlgHom`. -/ def snd : A × B →A[R] B where cont := continuous_snd toAlgHom := AlgHom.snd R A B variable {R A B} @[simp, norm_cast] theorem coe_fst : ↑(fst R A B) = AlgHom.fst R A B := rfl @[simp, norm_cast] theorem coe_fst' : ⇑(fst R A B) = Prod.fst := rfl @[simp, norm_cast] theorem coe_snd : ↑(snd R A B) = AlgHom.snd R A B := rfl @[simp, norm_cast] theorem coe_snd' : ⇑(snd R A B) = Prod.snd := rfl @[simp] theorem fst_prod_snd : (fst R A B).prod (snd R A B) = ContinuousAlgHom.id R (A × B) := ext fun ⟨_x, _y⟩ => rfl @[simp] theorem fst_comp_prod (f : A →A[R] B) (g : A →A[R] C) : (fst R B C).comp (f.prod g) = f := ext fun _x => rfl @[simp] theorem snd_comp_prod (f : A →A[R] B) (g : A →A[R] C) : (snd R B C).comp (f.prod g) = g := ext fun _x => rfl /-- `Prod.map` of two continuous algebra homomorphisms. -/ def prodMap {D : Type*} [Semiring D] [TopologicalSpace D] [Algebra R D] (f₁ : A →A[R] B) (f₂ : C →A[R] D) : A × C →A[R] B × D := (f₁.comp (fst R A C)).prod (f₂.comp (snd R A C)) @[simp, norm_cast] theorem coe_prodMap {D : Type*} [Semiring D] [TopologicalSpace D] [Algebra R D] (f₁ : A →A[R] B) (f₂ : C →A[R] D) : (f₁.prodMap f₂ : A × C →ₐ[R] B × D) = (f₁ : A →ₐ[R] B).prodMap (f₂ : C →ₐ[R] D) := rfl @[simp, norm_cast] theorem coe_prodMap' {D : Type*} [Semiring D] [TopologicalSpace D] [Algebra R D] (f₁ : A →A[R] B) (f₂ : C →A[R] D) : ⇑(f₁.prodMap f₂) = Prod.map f₁ f₂ := rfl /-- `ContinuousAlgHom.prod` as an `Equiv`. -/ @[simps apply] def prodEquiv : (A →A[R] B) × (A →A[R] C) ≃ (A →A[R] B × C) where toFun f := f.1.prod f.2 invFun f := ⟨(fst _ _ _).comp f, (snd _ _ _).comp f⟩ left_inv f := by ext <;> rfl right_inv f := by ext <;> rfl end prod section subalgebra variable {R A} variable [TopologicalSpace A] variable {B : Type*} [Semiring B] [TopologicalSpace B] [Algebra R A] [Algebra R B] /-- Restrict codomain of a continuous algebra morphism. -/ def codRestrict (f : A →A[R] B) (p : Subalgebra R B) (h : ∀ x, f x ∈ p) : A →A[R] p where cont := f.continuous.subtype_mk _ toAlgHom := (f : A →ₐ[R] B).codRestrict p h @[norm_cast] theorem coe_codRestrict (f : A →A[R] B) (p : Subalgebra R B) (h : ∀ x, f x ∈ p) : (f.codRestrict p h : A →ₐ[R] p) = (f : A →ₐ[R] B).codRestrict p h := rfl @[simp] theorem coe_codRestrict_apply (f : A →A[R] B) (p : Subalgebra R B) (h : ∀ x, f x ∈ p) (x) : (f.codRestrict p h x : B) = f x := rfl /-- Restrict the codomain of a continuous algebra homomorphism `f` to `f.range`. -/ @[reducible] def rangeRestrict (f : A →A[R] B) := f.codRestrict (@AlgHom.range R A B _ _ _ _ _ f) (@AlgHom.mem_range_self R A B _ _ _ _ _ f) @[simp] theorem coe_rangeRestrict (f : A →A[R] B) : (f.rangeRestrict : A →ₐ[R] (@AlgHom.range R A B _ _ _ _ _ f)) = (f : A →ₐ[R] B).rangeRestrict := rfl /-- `Subalgebra.val` as a `ContinuousAlgHom`. -/ def _root_.Subalgebra.valA (p : Subalgebra R A) : p →A[R] A where cont := continuous_subtype_val toAlgHom := p.val @[simp, norm_cast] theorem _root_.Subalgebra.coe_valA (p : Subalgebra R A) : (p.valA : p →ₐ[R] A) = p.subtype := rfl @[simp] theorem _root_.Subalgebra.coe_valA' (p : Subalgebra R A) : ⇑p.valA = p.subtype := rfl @[simp] theorem _root_.Subalgebra.valA_apply (p : Subalgebra R A) (x : p) : p.valA x = x := rfl @[simp] theorem _root_.Submodule.range_valA (p : Subalgebra R A) : @AlgHom.range R p A _ _ _ _ _ p.valA = p := Subalgebra.range_val p end subalgebra section Ring variable {S : Type*} [Ring S] [TopologicalSpace S] [Algebra R S] {B : Type*} [Ring B] [TopologicalSpace B] [Algebra R B] protected theorem map_neg (f : S →A[R] B) (x : S) : f (-x) = -f x := map_neg f x protected theorem map_sub (f : S →A[R] B) (x y : S) : f (x - y) = f x - f y := map_sub f x y end Ring section RestrictScalars variable {S : Type*} [CommSemiring S] [Algebra R S] {B : Type*} [Ring B] [TopologicalSpace B] [Algebra R B] [Algebra S B] [IsScalarTower R S B] {C : Type*} [Ring C] [TopologicalSpace C] [Algebra R C] [Algebra S C] [IsScalarTower R S C] /-- If `A` is an `R`-algebra, then a continuous `A`-algebra morphism can be interpreted as a continuous `R`-algebra morphism. -/ def restrictScalars (f : B →A[S] C) : B →A[R] C := ⟨(f : B →ₐ[S] C).restrictScalars R, f.continuous⟩ variable {R} @[simp] theorem coe_restrictScalars (f : B →A[S] C) : (f.restrictScalars R : B →ₐ[R] C) = (f : B →ₐ[S] C).restrictScalars R := rfl @[simp] theorem coe_restrictScalars' (f : B →A[S] C) : ⇑(f.restrictScalars R) = f := rfl end RestrictScalars end ContinuousAlgHom end variable {R : Type*} [CommSemiring R] variable {A : Type u} [TopologicalSpace A] variable [Semiring A] [Algebra R A] variable [TopologicalSemiring A] instance (s : Subalgebra R A) : TopologicalSemiring s := s.toSubsemiring.topologicalSemiring theorem Subalgebra.le_topologicalClosure (s : Subalgebra R A) : s ≤ s.topologicalClosure := subset_closure theorem Subalgebra.isClosed_topologicalClosure (s : Subalgebra R A) : IsClosed (s.topologicalClosure : Set A) := by convert @isClosed_closure A s _ theorem Subalgebra.topologicalClosure_minimal (s : Subalgebra R A) {t : Subalgebra R A} (h : s ≤ t) (ht : IsClosed (t : Set A)) : s.topologicalClosure ≤ t := closure_minimal h ht /-- If a subalgebra of a topological algebra is commutative, then so is its topological closure. -/ def Subalgebra.commSemiringTopologicalClosure [T2Space A] (s : Subalgebra R A) (hs : ∀ x y : s, x * y = y * x) : CommSemiring s.topologicalClosure := { s.topologicalClosure.toSemiring, s.toSubmonoid.commMonoidTopologicalClosure hs with } /-- This is really a statement about topological algebra isomorphisms, but we don't have those, so we use the clunky approach of talking about an algebra homomorphism, and a separate homeomorphism, along with a witness that as functions they are the same. -/ theorem Subalgebra.topologicalClosure_comap_homeomorph (s : Subalgebra R A) {B : Type*} [TopologicalSpace B] [Ring B] [TopologicalRing B] [Algebra R B] (f : B →ₐ[R] A) (f' : B ≃ₜ A) (w : (f : B → A) = f') : s.topologicalClosure.comap f = (s.comap f).topologicalClosure := by apply SetLike.ext' simp only [Subalgebra.topologicalClosure_coe] simp only [Subalgebra.coe_comap, Subsemiring.coe_comap, AlgHom.coe_toRingHom] rw [w] exact f'.preimage_closure _ end TopologicalAlgebra section Ring variable {R : Type*} [CommRing R] variable {A : Type u} [TopologicalSpace A] variable [Ring A] variable [Algebra R A] [TopologicalRing A] /-- If a subalgebra of a topological algebra is commutative, then so is its topological closure. See note [reducible non-instances]. -/ abbrev Subalgebra.commRingTopologicalClosure [T2Space A] (s : Subalgebra R A) (hs : ∀ x y : s, x * y = y * x) : CommRing s.topologicalClosure := { s.topologicalClosure.toRing, s.toSubmonoid.commMonoidTopologicalClosure hs with } variable (R) /-- The topological closure of the subalgebra generated by a single element. -/ def Algebra.elementalAlgebra (x : A) : Subalgebra R A := (Algebra.adjoin R ({x} : Set A)).topologicalClosure @[aesop safe apply (rule_sets := [SetLike])] theorem Algebra.self_mem_elementalAlgebra (x : A) : x ∈ Algebra.elementalAlgebra R x := SetLike.le_def.mp (Subalgebra.le_topologicalClosure (Algebra.adjoin R ({x} : Set A))) <| Algebra.self_mem_adjoin_singleton R x variable {R} instance [T2Space A] {x : A} : CommRing (Algebra.elementalAlgebra R x) := Subalgebra.commRingTopologicalClosure _ letI : CommRing (Algebra.adjoin R ({x} : Set A)) := Algebra.adjoinCommRingOfComm R fun y hy z hz => by rw [mem_singleton_iff] at hy hz rw [hy, hz] fun _ _ => mul_comm _ _ end Ring
Topology\Algebra\ConstMulAction.lean
/- Copyright (c) 2021 Alex Kontorovich, Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Kontorovich, Heather Macbeth -/ import Mathlib.Topology.Algebra.Constructions import Mathlib.Topology.Homeomorph import Mathlib.GroupTheory.GroupAction.Basic import Mathlib.Topology.Bases import Mathlib.Topology.Support import Mathlib.Algebra.Module.ULift /-! # Monoid actions continuous in the second variable In this file we define class `ContinuousConstSMul`. We say `ContinuousConstSMul Γ T` if `Γ` acts on `T` and for each `γ`, the map `x ↦ γ • x` is continuous. (This differs from `ContinuousSMul`, which requires simultaneous continuity in both variables.) ## Main definitions * `ContinuousConstSMul Γ T` : typeclass saying that the map `x ↦ γ • x` is continuous on `T`; * `ProperlyDiscontinuousSMul`: says that the scalar multiplication `(•) : Γ → T → T` is properly discontinuous, that is, for any pair of compact sets `K, L` in `T`, only finitely many `γ:Γ` move `K` to have nontrivial intersection with `L`. * `Homeomorph.smul`: scalar multiplication by an element of a group `Γ` acting on `T` is a homeomorphism of `T`. ## Main results * `isOpenMap_quotient_mk'_mul` : The quotient map by a group action is open. * `t2Space_of_properlyDiscontinuousSMul_of_t2Space` : The quotient by a discontinuous group action of a locally compact t2 space is t2. ## Tags Hausdorff, discrete group, properly discontinuous, quotient space -/ open Topology Pointwise Filter Set TopologicalSpace /-- Class `ContinuousConstSMul Γ T` says that the scalar multiplication `(•) : Γ → T → T` is continuous in the second argument. We use the same class for all kinds of multiplicative actions, including (semi)modules and algebras. Note that both `ContinuousConstSMul α α` and `ContinuousConstSMul αᵐᵒᵖ α` are weaker versions of `ContinuousMul α`. -/ class ContinuousConstSMul (Γ : Type*) (T : Type*) [TopologicalSpace T] [SMul Γ T] : Prop where /-- The scalar multiplication `(•) : Γ → T → T` is continuous in the second argument. -/ continuous_const_smul : ∀ γ : Γ, Continuous fun x : T => γ • x /-- Class `ContinuousConstVAdd Γ T` says that the additive action `(+ᵥ) : Γ → T → T` is continuous in the second argument. We use the same class for all kinds of additive actions, including (semi)modules and algebras. Note that both `ContinuousConstVAdd α α` and `ContinuousConstVAdd αᵐᵒᵖ α` are weaker versions of `ContinuousVAdd α`. -/ class ContinuousConstVAdd (Γ : Type*) (T : Type*) [TopologicalSpace T] [VAdd Γ T] : Prop where /-- The additive action `(+ᵥ) : Γ → T → T` is continuous in the second argument. -/ continuous_const_vadd : ∀ γ : Γ, Continuous fun x : T => γ +ᵥ x attribute [to_additive] ContinuousConstSMul export ContinuousConstSMul (continuous_const_smul) export ContinuousConstVAdd (continuous_const_vadd) variable {M α β : Type*} section SMul variable [TopologicalSpace α] [SMul M α] [ContinuousConstSMul M α] @[to_additive] instance : ContinuousConstSMul (ULift M) α := ⟨fun γ ↦ continuous_const_smul (ULift.down γ)⟩ @[to_additive] theorem Filter.Tendsto.const_smul {f : β → α} {l : Filter β} {a : α} (hf : Tendsto f l (𝓝 a)) (c : M) : Tendsto (fun x => c • f x) l (𝓝 (c • a)) := ((continuous_const_smul _).tendsto _).comp hf variable [TopologicalSpace β] {f : β → M} {g : β → α} {b : β} {s : Set β} @[to_additive] nonrec theorem ContinuousWithinAt.const_smul (hg : ContinuousWithinAt g s b) (c : M) : ContinuousWithinAt (fun x => c • g x) s b := hg.const_smul c @[to_additive (attr := fun_prop)] nonrec theorem ContinuousAt.const_smul (hg : ContinuousAt g b) (c : M) : ContinuousAt (fun x => c • g x) b := hg.const_smul c @[to_additive (attr := fun_prop)] theorem ContinuousOn.const_smul (hg : ContinuousOn g s) (c : M) : ContinuousOn (fun x => c • g x) s := fun x hx => (hg x hx).const_smul c @[to_additive (attr := continuity, fun_prop)] theorem Continuous.const_smul (hg : Continuous g) (c : M) : Continuous fun x => c • g x := (continuous_const_smul _).comp hg /-- If a scalar is central, then its right action is continuous when its left action is. -/ @[to_additive "If an additive action is central, then its right action is continuous when its left action is."] instance ContinuousConstSMul.op [SMul Mᵐᵒᵖ α] [IsCentralScalar M α] : ContinuousConstSMul Mᵐᵒᵖ α := ⟨MulOpposite.rec' fun c => by simpa only [op_smul_eq_smul] using continuous_const_smul c⟩ @[to_additive] instance MulOpposite.continuousConstSMul : ContinuousConstSMul M αᵐᵒᵖ := ⟨fun c => MulOpposite.continuous_op.comp <| MulOpposite.continuous_unop.const_smul c⟩ @[to_additive] instance : ContinuousConstSMul M αᵒᵈ := ‹ContinuousConstSMul M α› @[to_additive] instance OrderDual.continuousConstSMul' : ContinuousConstSMul Mᵒᵈ α := ‹ContinuousConstSMul M α› @[to_additive] instance Prod.continuousConstSMul [SMul M β] [ContinuousConstSMul M β] : ContinuousConstSMul M (α × β) := ⟨fun _ => (continuous_fst.const_smul _).prod_mk (continuous_snd.const_smul _)⟩ @[to_additive] instance {ι : Type*} {γ : ι → Type*} [∀ i, TopologicalSpace (γ i)] [∀ i, SMul M (γ i)] [∀ i, ContinuousConstSMul M (γ i)] : ContinuousConstSMul M (∀ i, γ i) := ⟨fun _ => continuous_pi fun i => (continuous_apply i).const_smul _⟩ @[to_additive] theorem IsCompact.smul {α β} [SMul α β] [TopologicalSpace β] [ContinuousConstSMul α β] (a : α) {s : Set β} (hs : IsCompact s) : IsCompact (a • s) := hs.image (continuous_id.const_smul a) @[to_additive] theorem Specializes.const_smul {x y : α} (h : x ⤳ y) (c : M) : (c • x) ⤳ (c • y) := h.map (continuous_const_smul c) @[to_additive] theorem Inseparable.const_smul {x y : α} (h : Inseparable x y) (c : M) : Inseparable (c • x) (c • y) := h.map (continuous_const_smul c) end SMul section Monoid variable [TopologicalSpace α] variable [Monoid M] [MulAction M α] [ContinuousConstSMul M α] @[to_additive] instance Units.continuousConstSMul : ContinuousConstSMul Mˣ α where continuous_const_smul m := (continuous_const_smul (m : M) : _) @[to_additive] theorem smul_closure_subset (c : M) (s : Set α) : c • closure s ⊆ closure (c • s) := ((Set.mapsTo_image _ _).closure <| continuous_const_smul c).image_subset @[to_additive] theorem smul_closure_orbit_subset (c : M) (x : α) : c • closure (MulAction.orbit M x) ⊆ closure (MulAction.orbit M x) := (smul_closure_subset c _).trans <| closure_mono <| MulAction.smul_orbit_subset _ _ theorem isClosed_setOf_map_smul {N : Type*} [Monoid N] (α β) [MulAction M α] [MulAction N β] [TopologicalSpace β] [T2Space β] [ContinuousConstSMul N β] (σ : M → N) : IsClosed { f : α → β | ∀ c x, f (c • x) = σ c • f x } := by simp only [Set.setOf_forall] exact isClosed_iInter fun c => isClosed_iInter fun x => isClosed_eq (continuous_apply _) ((continuous_apply _).const_smul _) end Monoid section Group variable {G : Type*} [TopologicalSpace α] [Group G] [MulAction G α] [ContinuousConstSMul G α] @[to_additive] theorem tendsto_const_smul_iff {f : β → α} {l : Filter β} {a : α} (c : G) : Tendsto (fun x => c • f x) l (𝓝 <| c • a) ↔ Tendsto f l (𝓝 a) := ⟨fun h => by simpa only [inv_smul_smul] using h.const_smul c⁻¹, fun h => h.const_smul _⟩ variable [TopologicalSpace β] {f : β → α} {b : β} {s : Set β} @[to_additive] theorem continuousWithinAt_const_smul_iff (c : G) : ContinuousWithinAt (fun x => c • f x) s b ↔ ContinuousWithinAt f s b := tendsto_const_smul_iff c @[to_additive] theorem continuousOn_const_smul_iff (c : G) : ContinuousOn (fun x => c • f x) s ↔ ContinuousOn f s := forall₂_congr fun _ _ => continuousWithinAt_const_smul_iff c @[to_additive] theorem continuousAt_const_smul_iff (c : G) : ContinuousAt (fun x => c • f x) b ↔ ContinuousAt f b := tendsto_const_smul_iff c @[to_additive] theorem continuous_const_smul_iff (c : G) : (Continuous fun x => c • f x) ↔ Continuous f := by simp only [continuous_iff_continuousAt, continuousAt_const_smul_iff] /-- The homeomorphism given by scalar multiplication by a given element of a group `Γ` acting on `T` is a homeomorphism from `T` to itself. -/ @[to_additive] def Homeomorph.smul (γ : G) : α ≃ₜ α where toEquiv := MulAction.toPerm γ continuous_toFun := continuous_const_smul γ continuous_invFun := continuous_const_smul γ⁻¹ /-- The homeomorphism given by affine-addition by an element of an additive group `Γ` acting on `T` is a homeomorphism from `T` to itself. -/ add_decl_doc Homeomorph.vadd @[to_additive] theorem isOpenMap_smul (c : G) : IsOpenMap fun x : α => c • x := (Homeomorph.smul c).isOpenMap @[to_additive] theorem IsOpen.smul {s : Set α} (hs : IsOpen s) (c : G) : IsOpen (c • s) := isOpenMap_smul c s hs @[to_additive] theorem isClosedMap_smul (c : G) : IsClosedMap fun x : α => c • x := (Homeomorph.smul c).isClosedMap @[to_additive] theorem IsClosed.smul {s : Set α} (hs : IsClosed s) (c : G) : IsClosed (c • s) := isClosedMap_smul c s hs @[to_additive] theorem closure_smul (c : G) (s : Set α) : closure (c • s) = c • closure s := ((Homeomorph.smul c).image_closure s).symm @[to_additive] theorem Dense.smul (c : G) {s : Set α} (hs : Dense s) : Dense (c • s) := by rw [dense_iff_closure_eq] at hs ⊢; rw [closure_smul, hs, smul_set_univ] @[to_additive] theorem interior_smul (c : G) (s : Set α) : interior (c • s) = c • interior s := ((Homeomorph.smul c).image_interior s).symm end Group section GroupWithZero variable {G₀ : Type*} [TopologicalSpace α] [GroupWithZero G₀] [MulAction G₀ α] [ContinuousConstSMul G₀ α] theorem tendsto_const_smul_iff₀ {f : β → α} {l : Filter β} {a : α} {c : G₀} (hc : c ≠ 0) : Tendsto (fun x => c • f x) l (𝓝 <| c • a) ↔ Tendsto f l (𝓝 a) := tendsto_const_smul_iff (Units.mk0 c hc) variable [TopologicalSpace β] {f : β → α} {b : β} {c : G₀} {s : Set β} theorem continuousWithinAt_const_smul_iff₀ (hc : c ≠ 0) : ContinuousWithinAt (fun x => c • f x) s b ↔ ContinuousWithinAt f s b := tendsto_const_smul_iff (Units.mk0 c hc) theorem continuousOn_const_smul_iff₀ (hc : c ≠ 0) : ContinuousOn (fun x => c • f x) s ↔ ContinuousOn f s := continuousOn_const_smul_iff (Units.mk0 c hc) theorem continuousAt_const_smul_iff₀ (hc : c ≠ 0) : ContinuousAt (fun x => c • f x) b ↔ ContinuousAt f b := continuousAt_const_smul_iff (Units.mk0 c hc) theorem continuous_const_smul_iff₀ (hc : c ≠ 0) : (Continuous fun x => c • f x) ↔ Continuous f := continuous_const_smul_iff (Units.mk0 c hc) /-- Scalar multiplication by a non-zero element of a group with zero acting on `α` is a homeomorphism from `α` onto itself. -/ @[simps! (config := .asFn) apply] protected def Homeomorph.smulOfNeZero (c : G₀) (hc : c ≠ 0) : α ≃ₜ α := Homeomorph.smul (Units.mk0 c hc) @[simp] theorem Homeomorph.smulOfNeZero_symm_apply {c : G₀} (hc : c ≠ 0) : ⇑(Homeomorph.smulOfNeZero c hc).symm = (c⁻¹ • · : α → α) := rfl theorem isOpenMap_smul₀ {c : G₀} (hc : c ≠ 0) : IsOpenMap fun x : α => c • x := (Homeomorph.smulOfNeZero c hc).isOpenMap theorem IsOpen.smul₀ {c : G₀} {s : Set α} (hs : IsOpen s) (hc : c ≠ 0) : IsOpen (c • s) := isOpenMap_smul₀ hc s hs theorem interior_smul₀ {c : G₀} (hc : c ≠ 0) (s : Set α) : interior (c • s) = c • interior s := ((Homeomorph.smulOfNeZero c hc).image_interior s).symm theorem closure_smul₀' {c : G₀} (hc : c ≠ 0) (s : Set α) : closure (c • s) = c • closure s := ((Homeomorph.smulOfNeZero c hc).image_closure s).symm theorem closure_smul₀ {E} [Zero E] [MulActionWithZero G₀ E] [TopologicalSpace E] [T1Space E] [ContinuousConstSMul G₀ E] (c : G₀) (s : Set E) : closure (c • s) = c • closure s := by rcases eq_or_ne c 0 with (rfl | hc) · rcases eq_empty_or_nonempty s with (rfl | hs) · simp · rw [zero_smul_set hs, zero_smul_set hs.closure] exact closure_singleton · exact closure_smul₀' hc s /-- `smul` is a closed map in the second argument. The lemma that `smul` is a closed map in the first argument (for a normed space over a complete normed field) is `isClosedMap_smul_left` in `Analysis.Normed.Module.FiniteDimension`. -/ theorem isClosedMap_smul_of_ne_zero {c : G₀} (hc : c ≠ 0) : IsClosedMap fun x : α => c • x := (Homeomorph.smulOfNeZero c hc).isClosedMap theorem IsClosed.smul_of_ne_zero {c : G₀} {s : Set α} (hs : IsClosed s) (hc : c ≠ 0) : IsClosed (c • s) := isClosedMap_smul_of_ne_zero hc s hs /-- `smul` is a closed map in the second argument. The lemma that `smul` is a closed map in the first argument (for a normed space over a complete normed field) is `isClosedMap_smul_left` in `Analysis.Normed.Module.FiniteDimension`. -/ theorem isClosedMap_smul₀ {E : Type*} [Zero E] [MulActionWithZero G₀ E] [TopologicalSpace E] [T1Space E] [ContinuousConstSMul G₀ E] (c : G₀) : IsClosedMap fun x : E => c • x := by rcases eq_or_ne c 0 with (rfl | hne) · simp only [zero_smul] exact isClosedMap_const · exact (Homeomorph.smulOfNeZero c hne).isClosedMap theorem IsClosed.smul₀ {E : Type*} [Zero E] [MulActionWithZero G₀ E] [TopologicalSpace E] [T1Space E] [ContinuousConstSMul G₀ E] (c : G₀) {s : Set E} (hs : IsClosed s) : IsClosed (c • s) := isClosedMap_smul₀ c s hs theorem HasCompactMulSupport.comp_smul {β : Type*} [One β] {f : α → β} (h : HasCompactMulSupport f) {c : G₀} (hc : c ≠ 0) : HasCompactMulSupport fun x => f (c • x) := h.comp_homeomorph (Homeomorph.smulOfNeZero c hc) theorem HasCompactSupport.comp_smul {β : Type*} [Zero β] {f : α → β} (h : HasCompactSupport f) {c : G₀} (hc : c ≠ 0) : HasCompactSupport fun x => f (c • x) := h.comp_homeomorph (Homeomorph.smulOfNeZero c hc) attribute [to_additive existing HasCompactSupport.comp_smul] HasCompactMulSupport.comp_smul end GroupWithZero namespace IsUnit variable [Monoid M] [TopologicalSpace α] [MulAction M α] [ContinuousConstSMul M α] nonrec theorem tendsto_const_smul_iff {f : β → α} {l : Filter β} {a : α} {c : M} (hc : IsUnit c) : Tendsto (fun x => c • f x) l (𝓝 <| c • a) ↔ Tendsto f l (𝓝 a) := let ⟨u, hu⟩ := hc hu ▸ tendsto_const_smul_iff u variable [TopologicalSpace β] {f : β → α} {b : β} {c : M} {s : Set β} nonrec theorem continuousWithinAt_const_smul_iff (hc : IsUnit c) : ContinuousWithinAt (fun x => c • f x) s b ↔ ContinuousWithinAt f s b := let ⟨u, hu⟩ := hc hu ▸ continuousWithinAt_const_smul_iff u nonrec theorem continuousOn_const_smul_iff (hc : IsUnit c) : ContinuousOn (fun x => c • f x) s ↔ ContinuousOn f s := let ⟨u, hu⟩ := hc hu ▸ continuousOn_const_smul_iff u nonrec theorem continuousAt_const_smul_iff (hc : IsUnit c) : ContinuousAt (fun x => c • f x) b ↔ ContinuousAt f b := let ⟨u, hu⟩ := hc hu ▸ continuousAt_const_smul_iff u nonrec theorem continuous_const_smul_iff (hc : IsUnit c) : (Continuous fun x => c • f x) ↔ Continuous f := let ⟨u, hu⟩ := hc hu ▸ continuous_const_smul_iff u nonrec theorem isOpenMap_smul (hc : IsUnit c) : IsOpenMap fun x : α => c • x := let ⟨u, hu⟩ := hc hu ▸ isOpenMap_smul u nonrec theorem isClosedMap_smul (hc : IsUnit c) : IsClosedMap fun x : α => c • x := let ⟨u, hu⟩ := hc hu ▸ isClosedMap_smul u end IsUnit -- Porting note (#11215): TODO: use `Set.Nonempty` /-- Class `ProperlyDiscontinuousSMul Γ T` says that the scalar multiplication `(•) : Γ → T → T` is properly discontinuous, that is, for any pair of compact sets `K, L` in `T`, only finitely many `γ:Γ` move `K` to have nontrivial intersection with `L`. -/ class ProperlyDiscontinuousSMul (Γ : Type*) (T : Type*) [TopologicalSpace T] [SMul Γ T] : Prop where /-- Given two compact sets `K` and `L`, `γ • K ∩ L` is nonempty for finitely many `γ`. -/ finite_disjoint_inter_image : ∀ {K L : Set T}, IsCompact K → IsCompact L → Set.Finite { γ : Γ | (γ • ·) '' K ∩ L ≠ ∅ } /-- Class `ProperlyDiscontinuousVAdd Γ T` says that the additive action `(+ᵥ) : Γ → T → T` is properly discontinuous, that is, for any pair of compact sets `K, L` in `T`, only finitely many `γ:Γ` move `K` to have nontrivial intersection with `L`. -/ class ProperlyDiscontinuousVAdd (Γ : Type*) (T : Type*) [TopologicalSpace T] [VAdd Γ T] : Prop where /-- Given two compact sets `K` and `L`, `γ +ᵥ K ∩ L` is nonempty for finitely many `γ`. -/ finite_disjoint_inter_image : ∀ {K L : Set T}, IsCompact K → IsCompact L → Set.Finite { γ : Γ | (γ +ᵥ ·) '' K ∩ L ≠ ∅ } attribute [to_additive] ProperlyDiscontinuousSMul variable {Γ : Type*} [Group Γ] {T : Type*} [TopologicalSpace T] [MulAction Γ T] /-- A finite group action is always properly discontinuous. -/ @[to_additive "A finite group action is always properly discontinuous."] instance (priority := 100) Finite.to_properlyDiscontinuousSMul [Finite Γ] : ProperlyDiscontinuousSMul Γ T where finite_disjoint_inter_image _ _ := Set.toFinite _ export ProperlyDiscontinuousSMul (finite_disjoint_inter_image) export ProperlyDiscontinuousVAdd (finite_disjoint_inter_image) /-- The quotient map by a group action is open, i.e. the quotient by a group action is an open quotient. -/ @[to_additive "The quotient map by a group action is open, i.e. the quotient by a group action is an open quotient. "] theorem isOpenMap_quotient_mk'_mul [ContinuousConstSMul Γ T] : letI := MulAction.orbitRel Γ T IsOpenMap (Quotient.mk' : T → Quotient (MulAction.orbitRel Γ T)) := fun U hU => by rw [isOpen_coinduced, MulAction.quotient_preimage_image_eq_union_mul U] exact isOpen_iUnion fun γ => isOpenMap_smul γ U hU /-- The quotient by a discontinuous group action of a locally compact t2 space is t2. -/ @[to_additive "The quotient by a discontinuous group action of a locally compact t2 space is t2."] instance (priority := 100) t2Space_of_properlyDiscontinuousSMul_of_t2Space [T2Space T] [LocallyCompactSpace T] [ContinuousConstSMul Γ T] [ProperlyDiscontinuousSMul Γ T] : T2Space (Quotient (MulAction.orbitRel Γ T)) := by letI := MulAction.orbitRel Γ T set Q := Quotient (MulAction.orbitRel Γ T) rw [t2Space_iff_nhds] let f : T → Q := Quotient.mk' have f_op : IsOpenMap f := isOpenMap_quotient_mk'_mul rintro ⟨x₀⟩ ⟨y₀⟩ (hxy : f x₀ ≠ f y₀) show ∃ U ∈ 𝓝 (f x₀), ∃ V ∈ 𝓝 (f y₀), _ have hγx₀y₀ : ∀ γ : Γ, γ • x₀ ≠ y₀ := not_exists.mp (mt Quotient.sound hxy.symm : _) obtain ⟨K₀, hK₀, K₀_in⟩ := exists_compact_mem_nhds x₀ obtain ⟨L₀, hL₀, L₀_in⟩ := exists_compact_mem_nhds y₀ let bad_Γ_set := { γ : Γ | (γ • ·) '' K₀ ∩ L₀ ≠ ∅ } have bad_Γ_finite : bad_Γ_set.Finite := finite_disjoint_inter_image (Γ := Γ) hK₀ hL₀ choose u v hu hv u_v_disjoint using fun γ => t2_separation_nhds (hγx₀y₀ γ) let U₀₀ := ⋂ γ ∈ bad_Γ_set, (γ • ·) ⁻¹' u γ let U₀ := U₀₀ ∩ K₀ let V₀₀ := ⋂ γ ∈ bad_Γ_set, v γ let V₀ := V₀₀ ∩ L₀ have U_nhds : f '' U₀ ∈ 𝓝 (f x₀) := by refine f_op.image_mem_nhds (inter_mem ((biInter_mem bad_Γ_finite).mpr fun γ _ => ?_) K₀_in) exact (continuous_const_smul _).continuousAt (hu γ) have V_nhds : f '' V₀ ∈ 𝓝 (f y₀) := f_op.image_mem_nhds (inter_mem ((biInter_mem bad_Γ_finite).mpr fun γ _ => hv γ) L₀_in) refine ⟨f '' U₀, U_nhds, f '' V₀, V_nhds, MulAction.disjoint_image_image_iff.2 ?_⟩ rintro x ⟨x_in_U₀₀, x_in_K₀⟩ γ by_cases H : γ ∈ bad_Γ_set · exact fun h => (u_v_disjoint γ).le_bot ⟨mem_iInter₂.mp x_in_U₀₀ γ H, mem_iInter₂.mp h.1 γ H⟩ · rintro ⟨-, h'⟩ simp only [bad_Γ_set, image_smul, Classical.not_not, mem_setOf_eq, Ne] at H exact eq_empty_iff_forall_not_mem.mp H (γ • x) ⟨mem_image_of_mem _ x_in_K₀, h'⟩ /-- The quotient of a second countable space by a group action is second countable. -/ @[to_additive "The quotient of a second countable space by an additive group action is second countable."] theorem ContinuousConstSMul.secondCountableTopology [SecondCountableTopology T] [ContinuousConstSMul Γ T] : SecondCountableTopology (Quotient (MulAction.orbitRel Γ T)) := TopologicalSpace.Quotient.secondCountableTopology isOpenMap_quotient_mk'_mul section nhds section MulAction variable {G₀ : Type*} [GroupWithZero G₀] [MulAction G₀ α] [TopologicalSpace α] [ContinuousConstSMul G₀ α] -- Porting note: generalize to a group action + `IsUnit` /-- Scalar multiplication preserves neighborhoods. -/ theorem set_smul_mem_nhds_smul {c : G₀} {s : Set α} {x : α} (hs : s ∈ 𝓝 x) (hc : c ≠ 0) : c • s ∈ 𝓝 (c • x : α) := by rw [mem_nhds_iff] at hs ⊢ obtain ⟨U, hs', hU, hU'⟩ := hs exact ⟨c • U, Set.smul_set_mono hs', hU.smul₀ hc, Set.smul_mem_smul_set hU'⟩ theorem set_smul_mem_nhds_smul_iff {c : G₀} {s : Set α} {x : α} (hc : c ≠ 0) : c • s ∈ 𝓝 (c • x : α) ↔ s ∈ 𝓝 x := by refine ⟨fun h => ?_, fun h => set_smul_mem_nhds_smul h hc⟩ rw [← inv_smul_smul₀ hc x, ← inv_smul_smul₀ hc s] exact set_smul_mem_nhds_smul h (inv_ne_zero hc) end MulAction section DistribMulAction variable {G₀ : Type*} [GroupWithZero G₀] [AddMonoid α] [DistribMulAction G₀ α] [TopologicalSpace α] [ContinuousConstSMul G₀ α] theorem set_smul_mem_nhds_zero_iff {s : Set α} {c : G₀} (hc : c ≠ 0) : c • s ∈ 𝓝 (0 : α) ↔ s ∈ 𝓝 (0 : α) := by refine Iff.trans ?_ (set_smul_mem_nhds_smul_iff hc) rw [smul_zero] end DistribMulAction end nhds
Topology\Algebra\Constructions.lean
/- Copyright (c) 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import Mathlib.Topology.Homeomorph /-! # Topological space structure on the opposite monoid and on the units group In this file we define `TopologicalSpace` structure on `Mᵐᵒᵖ`, `Mᵃᵒᵖ`, `Mˣ`, and `AddUnits M`. This file does not import definitions of a topological monoid and/or a continuous multiplicative action, so we postpone the proofs of `HasContinuousMul Mᵐᵒᵖ` etc till we have these definitions. ## Tags topological space, opposite monoid, units -/ variable {M X : Type*} open Filter Topology namespace MulOpposite /-- Put the same topological space structure on the opposite monoid as on the original space. -/ @[to_additive "Put the same topological space structure on the opposite monoid as on the original space."] instance instTopologicalSpaceMulOpposite [TopologicalSpace M] : TopologicalSpace Mᵐᵒᵖ := TopologicalSpace.induced (unop : Mᵐᵒᵖ → M) ‹_› variable [TopologicalSpace M] @[to_additive (attr := continuity)] theorem continuous_unop : Continuous (unop : Mᵐᵒᵖ → M) := continuous_induced_dom @[to_additive (attr := continuity)] theorem continuous_op : Continuous (op : M → Mᵐᵒᵖ) := continuous_induced_rng.2 continuous_id /-- `MulOpposite.op` as a homeomorphism. -/ @[to_additive (attr := simps!) "`AddOpposite.op` as a homeomorphism."] def opHomeomorph : M ≃ₜ Mᵐᵒᵖ where toEquiv := opEquiv continuous_toFun := continuous_op continuous_invFun := continuous_unop @[to_additive] instance instT2Space [T2Space M] : T2Space Mᵐᵒᵖ := opHomeomorph.symm.embedding.t2Space @[to_additive] instance instDiscreteTopology [DiscreteTopology M] : DiscreteTopology Mᵐᵒᵖ := opHomeomorph.symm.embedding.discreteTopology @[to_additive (attr := simp)] theorem map_op_nhds (x : M) : map (op : M → Mᵐᵒᵖ) (𝓝 x) = 𝓝 (op x) := opHomeomorph.map_nhds_eq x @[to_additive (attr := simp)] theorem map_unop_nhds (x : Mᵐᵒᵖ) : map (unop : Mᵐᵒᵖ → M) (𝓝 x) = 𝓝 (unop x) := opHomeomorph.symm.map_nhds_eq x @[to_additive (attr := simp)] theorem comap_op_nhds (x : Mᵐᵒᵖ) : comap (op : M → Mᵐᵒᵖ) (𝓝 x) = 𝓝 (unop x) := opHomeomorph.comap_nhds_eq x @[to_additive (attr := simp)] theorem comap_unop_nhds (x : M) : comap (unop : Mᵐᵒᵖ → M) (𝓝 x) = 𝓝 (op x) := opHomeomorph.symm.comap_nhds_eq x end MulOpposite namespace Units open MulOpposite variable [TopologicalSpace M] [Monoid M] [TopologicalSpace X] /-- The units of a monoid are equipped with a topology, via the embedding into `M × M`. -/ @[to_additive "The additive units of a monoid are equipped with a topology, via the embedding into `M × M`."] instance instTopologicalSpaceUnits : TopologicalSpace Mˣ := TopologicalSpace.induced (embedProduct M) inferInstance @[to_additive] theorem inducing_embedProduct : Inducing (embedProduct M) := ⟨rfl⟩ @[to_additive] theorem embedding_embedProduct : Embedding (embedProduct M) := ⟨inducing_embedProduct, embedProduct_injective M⟩ @[to_additive] instance instT2Space [T2Space M] : T2Space Mˣ := embedding_embedProduct.t2Space @[to_additive] instance instDiscreteTopology [DiscreteTopology M] : DiscreteTopology Mˣ := embedding_embedProduct.discreteTopology @[to_additive] lemma topology_eq_inf : instTopologicalSpaceUnits = .induced (val : Mˣ → M) ‹_› ⊓ .induced (fun u ↦ ↑u⁻¹ : Mˣ → M) ‹_› := by simp only [inducing_embedProduct.1, instTopologicalSpaceProd, induced_inf, instTopologicalSpaceMulOpposite, induced_compose]; rfl /-- An auxiliary lemma that can be used to prove that coercion `Mˣ → M` is a topological embedding. Use `Units.embedding_val₀`, `Units.embedding_val`, or `toUnits_homeomorph` instead. -/ @[to_additive "An auxiliary lemma that can be used to prove that coercion `AddUnits M → M` is a topological embedding. Use `AddUnits.embedding_val` or `toAddUnits_homeomorph` instead."] lemma embedding_val_mk' {M : Type*} [Monoid M] [TopologicalSpace M] {f : M → M} (hc : ContinuousOn f {x : M | IsUnit x}) (hf : ∀ u : Mˣ, f u.1 = ↑u⁻¹) : Embedding (val : Mˣ → M) := by refine ⟨⟨?_⟩, ext⟩ rw [topology_eq_inf, inf_eq_left, ← continuous_iff_le_induced, @continuous_iff_continuousAt _ _ (.induced _ _)] intros u s hs simp only [← hf, nhds_induced, Filter.mem_map] at hs ⊢ exact ⟨_, mem_inf_principal.1 (hc u u.isUnit hs), fun u' hu' ↦ hu' u'.isUnit⟩ /-- An auxiliary lemma that can be used to prove that coercion `Mˣ → M` is a topological embedding. Use `Units.embedding_val₀`, `Units.embedding_val`, or `toUnits_homeomorph` instead. -/ @[to_additive "An auxiliary lemma that can be used to prove that coercion `AddUnits M → M` is a topological embedding. Use `AddUnits.embedding_val` or `toAddUnits_homeomorph` instead."] lemma embedding_val_mk {M : Type*} [DivisionMonoid M] [TopologicalSpace M] (h : ContinuousOn Inv.inv {x : M | IsUnit x}) : Embedding (val : Mˣ → M) := embedding_val_mk' h fun u ↦ (val_inv_eq_inv_val u).symm @[to_additive] theorem continuous_embedProduct : Continuous (embedProduct M) := continuous_induced_dom @[to_additive] theorem continuous_val : Continuous ((↑) : Mˣ → M) := (@continuous_embedProduct M _ _).fst @[to_additive] protected theorem continuous_iff {f : X → Mˣ} : Continuous f ↔ Continuous (val ∘ f) ∧ Continuous (fun x => ↑(f x)⁻¹ : X → M) := by simp only [inducing_embedProduct.continuous_iff, embedProduct_apply, (· ∘ ·), continuous_prod_mk, opHomeomorph.symm.inducing.continuous_iff, opHomeomorph_symm_apply, unop_op] @[to_additive] theorem continuous_coe_inv : Continuous (fun u => ↑u⁻¹ : Mˣ → M) := (Units.continuous_iff.1 continuous_id).2 end Units
Topology\Algebra\ContinuousAffineMap.lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import Mathlib.LinearAlgebra.AffineSpace.AffineMap import Mathlib.Topology.ContinuousFunction.Basic import Mathlib.Topology.Algebra.Module.Basic /-! # Continuous affine maps. This file defines a type of bundled continuous affine maps. Note that the definition and basic properties established here require minimal assumptions, and do not even assume compatibility between the topological and algebraic structures. Of course it is necessary to assume some compatibility in order to obtain a useful theory. Such a theory is developed elsewhere for affine spaces modelled on _normed_ vector spaces, but not yet for general topological affine spaces (since we have not defined these yet). ## Main definitions: * `ContinuousAffineMap` ## Notation: We introduce the notation `P →ᴬ[R] Q` for `ContinuousAffineMap R P Q`. Note that this is parallel to the notation `E →L[R] F` for `ContinuousLinearMap R E F`. -/ /-- A continuous map of affine spaces. -/ structure ContinuousAffineMap (R : Type*) {V W : Type*} (P Q : Type*) [Ring R] [AddCommGroup V] [Module R V] [TopologicalSpace P] [AddTorsor V P] [AddCommGroup W] [Module R W] [TopologicalSpace Q] [AddTorsor W Q] extends P →ᵃ[R] Q where cont : Continuous toFun /-- A continuous map of affine spaces. -/ notation:25 P " →ᴬ[" R "] " Q => ContinuousAffineMap R P Q namespace ContinuousAffineMap variable {R V W P Q : Type*} [Ring R] variable [AddCommGroup V] [Module R V] [TopologicalSpace P] [AddTorsor V P] variable [AddCommGroup W] [Module R W] [TopologicalSpace Q] [AddTorsor W Q] instance : Coe (P →ᴬ[R] Q) (P →ᵃ[R] Q) := ⟨toAffineMap⟩ theorem to_affineMap_injective {f g : P →ᴬ[R] Q} (h : (f : P →ᵃ[R] Q) = (g : P →ᵃ[R] Q)) : f = g := by cases f cases g congr instance : FunLike (P →ᴬ[R] Q) P Q where coe f := f.toAffineMap coe_injective' _ _ h := to_affineMap_injective <| DFunLike.coe_injective h instance : ContinuousMapClass (P →ᴬ[R] Q) P Q where map_continuous := cont theorem toFun_eq_coe (f : P →ᴬ[R] Q) : f.toFun = ⇑f := rfl theorem coe_injective : @Function.Injective (P →ᴬ[R] Q) (P → Q) (⇑) := DFunLike.coe_injective @[ext] theorem ext {f g : P →ᴬ[R] Q} (h : ∀ x, f x = g x) : f = g := DFunLike.ext _ _ h theorem congr_fun {f g : P →ᴬ[R] Q} (h : f = g) (x : P) : f x = g x := DFunLike.congr_fun h _ /-- Forgetting its algebraic properties, a continuous affine map is a continuous map. -/ def toContinuousMap (f : P →ᴬ[R] Q) : C(P, Q) := ⟨f, f.cont⟩ -- Porting note: changed to CoeHead due to difficulty with synthesization order instance : CoeHead (P →ᴬ[R] Q) C(P, Q) := ⟨toContinuousMap⟩ @[simp] theorem toContinuousMap_coe (f : P →ᴬ[R] Q) : f.toContinuousMap = ↑f := rfl @[simp] -- Porting note: removed `norm_cast` theorem coe_to_affineMap (f : P →ᴬ[R] Q) : ((f : P →ᵃ[R] Q) : P → Q) = f := rfl -- Porting note: removed `norm_cast` and `simp` since proof is `simp only [ContinuousMap.coe_mk]` theorem coe_to_continuousMap (f : P →ᴬ[R] Q) : ((f : C(P, Q)) : P → Q) = f := rfl theorem to_continuousMap_injective {f g : P →ᴬ[R] Q} (h : (f : C(P, Q)) = (g : C(P, Q))) : f = g := by ext a exact ContinuousMap.congr_fun h a -- Porting note: removed `norm_cast` theorem coe_affineMap_mk (f : P →ᵃ[R] Q) (h) : ((⟨f, h⟩ : P →ᴬ[R] Q) : P →ᵃ[R] Q) = f := rfl @[norm_cast] theorem coe_continuousMap_mk (f : P →ᵃ[R] Q) (h) : ((⟨f, h⟩ : P →ᴬ[R] Q) : C(P, Q)) = ⟨f, h⟩ := rfl @[simp] theorem coe_mk (f : P →ᵃ[R] Q) (h) : ((⟨f, h⟩ : P →ᴬ[R] Q) : P → Q) = f := rfl @[simp] theorem mk_coe (f : P →ᴬ[R] Q) (h) : (⟨(f : P →ᵃ[R] Q), h⟩ : P →ᴬ[R] Q) = f := by ext rfl @[continuity] protected theorem continuous (f : P →ᴬ[R] Q) : Continuous f := f.2 variable (R P) /-- The constant map is a continuous affine map. -/ def const (q : Q) : P →ᴬ[R] Q := { AffineMap.const R P q with toFun := AffineMap.const R P q cont := continuous_const } @[simp] theorem coe_const (q : Q) : (const R P q : P → Q) = Function.const P q := rfl noncomputable instance : Inhabited (P →ᴬ[R] Q) := ⟨const R P <| Nonempty.some (by infer_instance : Nonempty Q)⟩ variable {R P} {W₂ Q₂ : Type*} variable [AddCommGroup W₂] [Module R W₂] [TopologicalSpace Q₂] [AddTorsor W₂ Q₂] /-- The composition of morphisms is a morphism. -/ def comp (f : Q →ᴬ[R] Q₂) (g : P →ᴬ[R] Q) : P →ᴬ[R] Q₂ := { (f : Q →ᵃ[R] Q₂).comp (g : P →ᵃ[R] Q) with cont := f.cont.comp g.cont } @[simp, norm_cast] theorem coe_comp (f : Q →ᴬ[R] Q₂) (g : P →ᴬ[R] Q) : (f.comp g : P → Q₂) = (f : Q → Q₂) ∘ (g : P → Q) := rfl theorem comp_apply (f : Q →ᴬ[R] Q₂) (g : P →ᴬ[R] Q) (x : P) : f.comp g x = f (g x) := rfl section ModuleValuedMaps variable {S : Type*} variable [TopologicalSpace W] instance : Zero (P →ᴬ[R] W) := ⟨ContinuousAffineMap.const R P 0⟩ @[norm_cast, simp] theorem coe_zero : ((0 : P →ᴬ[R] W) : P → W) = 0 := rfl theorem zero_apply (x : P) : (0 : P →ᴬ[R] W) x = 0 := rfl section MulAction variable [Monoid S] [DistribMulAction S W] [SMulCommClass R S W] variable [ContinuousConstSMul S W] instance : SMul S (P →ᴬ[R] W) where smul t f := { t • (f : P →ᵃ[R] W) with cont := f.continuous.const_smul t } @[norm_cast, simp] theorem coe_smul (t : S) (f : P →ᴬ[R] W) : ⇑(t • f) = t • ⇑f := rfl theorem smul_apply (t : S) (f : P →ᴬ[R] W) (x : P) : (t • f) x = t • f x := rfl instance [DistribMulAction Sᵐᵒᵖ W] [IsCentralScalar S W] : IsCentralScalar S (P →ᴬ[R] W) where op_smul_eq_smul _ _ := ext fun _ ↦ op_smul_eq_smul _ _ instance : MulAction S (P →ᴬ[R] W) := Function.Injective.mulAction _ coe_injective coe_smul end MulAction variable [TopologicalAddGroup W] instance : Add (P →ᴬ[R] W) where add f g := { (f : P →ᵃ[R] W) + (g : P →ᵃ[R] W) with cont := f.continuous.add g.continuous } @[norm_cast, simp] theorem coe_add (f g : P →ᴬ[R] W) : ⇑(f + g) = f + g := rfl theorem add_apply (f g : P →ᴬ[R] W) (x : P) : (f + g) x = f x + g x := rfl instance : Sub (P →ᴬ[R] W) where sub f g := { (f : P →ᵃ[R] W) - (g : P →ᵃ[R] W) with cont := f.continuous.sub g.continuous } @[norm_cast, simp] theorem coe_sub (f g : P →ᴬ[R] W) : ⇑(f - g) = f - g := rfl theorem sub_apply (f g : P →ᴬ[R] W) (x : P) : (f - g) x = f x - g x := rfl instance : Neg (P →ᴬ[R] W) := { neg := fun f => { -(f : P →ᵃ[R] W) with cont := f.continuous.neg } } @[norm_cast, simp] theorem coe_neg (f : P →ᴬ[R] W) : ⇑(-f) = -f := rfl theorem neg_apply (f : P →ᴬ[R] W) (x : P) : (-f) x = -f x := rfl instance : AddCommGroup (P →ᴬ[R] W) := coe_injective.addCommGroup _ coe_zero coe_add coe_neg coe_sub (fun _ _ ↦ coe_smul _ _) fun _ _ ↦ coe_smul _ _ instance [Monoid S] [DistribMulAction S W] [SMulCommClass R S W] [ContinuousConstSMul S W] : DistribMulAction S (P →ᴬ[R] W) := Function.Injective.distribMulAction ⟨⟨fun f ↦ f.toAffineMap.toFun, rfl⟩, coe_add⟩ coe_injective coe_smul instance [Semiring S] [Module S W] [SMulCommClass R S W] [ContinuousConstSMul S W] : Module S (P →ᴬ[R] W) := Function.Injective.module S ⟨⟨fun f ↦ f.toAffineMap.toFun, rfl⟩, coe_add⟩ coe_injective coe_smul end ModuleValuedMaps end ContinuousAffineMap namespace ContinuousLinearMap variable {R V W : Type*} [Ring R] variable [AddCommGroup V] [Module R V] [TopologicalSpace V] variable [AddCommGroup W] [Module R W] [TopologicalSpace W] /-- A continuous linear map can be regarded as a continuous affine map. -/ def toContinuousAffineMap (f : V →L[R] W) : V →ᴬ[R] W where toFun := f linear := f map_vadd' := by simp cont := f.cont @[simp] theorem coe_toContinuousAffineMap (f : V →L[R] W) : ⇑f.toContinuousAffineMap = f := rfl @[simp] theorem toContinuousAffineMap_map_zero (f : V →L[R] W) : f.toContinuousAffineMap 0 = 0 := by simp end ContinuousLinearMap
Topology\Algebra\ContinuousMonoidHom.lean
/- Copyright (c) 2022 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import Mathlib.Topology.Algebra.Equicontinuity import Mathlib.Topology.Algebra.Group.Compact import Mathlib.Topology.ContinuousFunction.Algebra import Mathlib.Topology.UniformSpace.Ascoli /-! # Continuous Monoid Homs This file defines the space of continuous homomorphisms between two topological groups. ## Main definitions * `ContinuousMonoidHom A B`: The continuous homomorphisms `A →* B`. * `ContinuousAddMonoidHom A B`: The continuous additive homomorphisms `A →+ B`. -/ open Pointwise Function variable (F A B C D E : Type*) [Monoid A] [Monoid B] [Monoid C] [Monoid D] [CommGroup E] [TopologicalSpace A] [TopologicalSpace B] [TopologicalSpace C] [TopologicalSpace D] [TopologicalSpace E] [TopologicalGroup E] /-- The type of continuous additive monoid homomorphisms from `A` to `B`. When possible, instead of parametrizing results over `(f : ContinuousAddMonoidHom A B)`, you should parametrize over `(F : Type*) [ContinuousAddMonoidHomClass F A B] (f : F)`. When you extend this structure, make sure to extend `ContinuousAddMonoidHomClass`. -/ structure ContinuousAddMonoidHom (A B : Type*) [AddMonoid A] [AddMonoid B] [TopologicalSpace A] [TopologicalSpace B] extends A →+ B where /-- Proof of continuity of the Hom. -/ continuous_toFun : @Continuous A B _ _ toFun /-- The type of continuous monoid homomorphisms from `A` to `B`. When possible, instead of parametrizing results over `(f : ContinuousMonoidHom A B)`, you should parametrize over `(F : Type*) [ContinuousMonoidHomClass F A B] (f : F)`. When you extend this structure, make sure to extend `ContinuousAddMonoidHomClass`. -/ @[to_additive "The type of continuous additive monoid homomorphisms from `A` to `B`."] structure ContinuousMonoidHom extends A →* B where /-- Proof of continuity of the Hom. -/ continuous_toFun : @Continuous A B _ _ toFun section /-- `ContinuousAddMonoidHomClass F A B` states that `F` is a type of continuous additive monoid homomorphisms. You should also extend this typeclass when you extend `ContinuousAddMonoidHom`. -/ -- Porting note: Changed A B to outParam to help synthesizing order class ContinuousAddMonoidHomClass (A B : outParam Type*) [AddMonoid A] [AddMonoid B] [TopologicalSpace A] [TopologicalSpace B] [FunLike F A B] extends AddMonoidHomClass F A B : Prop where /-- Proof of the continuity of the map. -/ map_continuous (f : F) : Continuous f /-- `ContinuousMonoidHomClass F A B` states that `F` is a type of continuous monoid homomorphisms. You should also extend this typeclass when you extend `ContinuousMonoidHom`. -/ -- Porting note: Changed A B to outParam to help synthesizing order @[to_additive] class ContinuousMonoidHomClass (A B : outParam Type*) [Monoid A] [Monoid B] [TopologicalSpace A] [TopologicalSpace B] [FunLike F A B] extends MonoidHomClass F A B : Prop where /-- Proof of the continuity of the map. -/ map_continuous (f : F) : Continuous f end /-- Reinterpret a `ContinuousMonoidHom` as a `MonoidHom`. -/ add_decl_doc ContinuousMonoidHom.toMonoidHom /-- Reinterpret a `ContinuousAddMonoidHom` as an `AddMonoidHom`. -/ add_decl_doc ContinuousAddMonoidHom.toAddMonoidHom -- See note [lower instance priority] @[to_additive] instance (priority := 100) ContinuousMonoidHomClass.toContinuousMapClass [FunLike F A B] [ContinuousMonoidHomClass F A B] : ContinuousMapClass F A B := { ‹ContinuousMonoidHomClass F A B› with } namespace ContinuousMonoidHom variable {A B C D E} @[to_additive] instance funLike : FunLike (ContinuousMonoidHom A B) A B where coe f := f.toFun coe_injective' f g h := by obtain ⟨⟨⟨ _ , _ ⟩, _⟩, _⟩ := f obtain ⟨⟨⟨ _ , _ ⟩, _⟩, _⟩ := g congr @[to_additive] instance ContinuousMonoidHomClass : ContinuousMonoidHomClass (ContinuousMonoidHom A B) A B where map_mul f := f.map_mul' map_one f := f.map_one' map_continuous f := f.continuous_toFun @[to_additive (attr := ext)] theorem ext {f g : ContinuousMonoidHom A B} (h : ∀ x, f x = g x) : f = g := DFunLike.ext _ _ h /-- Reinterpret a `ContinuousMonoidHom` as a `ContinuousMap`. -/ @[to_additive "Reinterpret a `ContinuousAddMonoidHom` as a `ContinuousMap`."] def toContinuousMap (f : ContinuousMonoidHom A B) : C(A, B) := { f with } @[to_additive] theorem toContinuousMap_injective : Injective (toContinuousMap : _ → C(A, B)) := fun f g h => ext <| by convert DFunLike.ext_iff.1 h -- Porting note: Removed simps because given definition is not a constructor application /-- Construct a `ContinuousMonoidHom` from a `Continuous` `MonoidHom`. -/ @[to_additive "Construct a `ContinuousAddMonoidHom` from a `Continuous` `AddMonoidHom`."] def mk' (f : A →* B) (hf : Continuous f) : ContinuousMonoidHom A B := { f with continuous_toFun := (hf : Continuous f.toFun)} /-- Composition of two continuous homomorphisms. -/ @[to_additive (attr := simps!) "Composition of two continuous homomorphisms."] def comp (g : ContinuousMonoidHom B C) (f : ContinuousMonoidHom A B) : ContinuousMonoidHom A C := mk' (g.toMonoidHom.comp f.toMonoidHom) (g.continuous_toFun.comp f.continuous_toFun) /-- Product of two continuous homomorphisms on the same space. -/ @[to_additive (attr := simps!) "Product of two continuous homomorphisms on the same space."] def prod (f : ContinuousMonoidHom A B) (g : ContinuousMonoidHom A C) : ContinuousMonoidHom A (B × C) := mk' (f.toMonoidHom.prod g.toMonoidHom) (f.continuous_toFun.prod_mk g.continuous_toFun) /-- Product of two continuous homomorphisms on different spaces. -/ @[to_additive (attr := simps!) "Product of two continuous homomorphisms on different spaces."] def prod_map (f : ContinuousMonoidHom A C) (g : ContinuousMonoidHom B D) : ContinuousMonoidHom (A × B) (C × D) := mk' (f.toMonoidHom.prodMap g.toMonoidHom) (f.continuous_toFun.prod_map g.continuous_toFun) variable (A B C D E) /-- The trivial continuous homomorphism. -/ @[to_additive (attr := simps!) "The trivial continuous homomorphism."] def one : ContinuousMonoidHom A B := mk' 1 continuous_const @[to_additive] instance : Inhabited (ContinuousMonoidHom A B) := ⟨one A B⟩ /-- The identity continuous homomorphism. -/ @[to_additive (attr := simps!) "The identity continuous homomorphism."] def id : ContinuousMonoidHom A A := mk' (MonoidHom.id A) continuous_id /-- The continuous homomorphism given by projection onto the first factor. -/ @[to_additive (attr := simps!) "The continuous homomorphism given by projection onto the first factor."] def fst : ContinuousMonoidHom (A × B) A := mk' (MonoidHom.fst A B) continuous_fst /-- The continuous homomorphism given by projection onto the second factor. -/ @[to_additive (attr := simps!) "The continuous homomorphism given by projection onto the second factor."] def snd : ContinuousMonoidHom (A × B) B := mk' (MonoidHom.snd A B) continuous_snd /-- The continuous homomorphism given by inclusion of the first factor. -/ @[to_additive (attr := simps!) "The continuous homomorphism given by inclusion of the first factor."] def inl : ContinuousMonoidHom A (A × B) := prod (id A) (one A B) /-- The continuous homomorphism given by inclusion of the second factor. -/ @[to_additive (attr := simps!) "The continuous homomorphism given by inclusion of the second factor."] def inr : ContinuousMonoidHom B (A × B) := prod (one B A) (id B) /-- The continuous homomorphism given by the diagonal embedding. -/ @[to_additive (attr := simps!) "The continuous homomorphism given by the diagonal embedding."] def diag : ContinuousMonoidHom A (A × A) := prod (id A) (id A) /-- The continuous homomorphism given by swapping components. -/ @[to_additive (attr := simps!) "The continuous homomorphism given by swapping components."] def swap : ContinuousMonoidHom (A × B) (B × A) := prod (snd A B) (fst A B) /-- The continuous homomorphism given by multiplication. -/ @[to_additive (attr := simps!) "The continuous homomorphism given by addition."] def mul : ContinuousMonoidHom (E × E) E := mk' mulMonoidHom continuous_mul /-- The continuous homomorphism given by inversion. -/ @[to_additive (attr := simps!) "The continuous homomorphism given by negation."] def inv : ContinuousMonoidHom E E := mk' invMonoidHom continuous_inv variable {A B C D E} /-- Coproduct of two continuous homomorphisms to the same space. -/ @[to_additive (attr := simps!) "Coproduct of two continuous homomorphisms to the same space."] def coprod (f : ContinuousMonoidHom A E) (g : ContinuousMonoidHom B E) : ContinuousMonoidHom (A × B) E := (mul E).comp (f.prod_map g) @[to_additive] instance : CommGroup (ContinuousMonoidHom A E) where mul f g := (mul E).comp (f.prod g) mul_comm f g := ext fun x => mul_comm (f x) (g x) mul_assoc f g h := ext fun x => mul_assoc (f x) (g x) (h x) one := one A E one_mul f := ext fun x => one_mul (f x) mul_one f := ext fun x => mul_one (f x) inv f := (inv E).comp f mul_left_inv f := ext fun x => mul_left_inv (f x) @[to_additive] instance : TopologicalSpace (ContinuousMonoidHom A B) := TopologicalSpace.induced toContinuousMap ContinuousMap.compactOpen variable (A B C D E) @[to_additive] theorem inducing_toContinuousMap : Inducing (toContinuousMap : ContinuousMonoidHom A B → C(A, B)) := ⟨rfl⟩ @[to_additive] theorem embedding_toContinuousMap : Embedding (toContinuousMap : ContinuousMonoidHom A B → C(A, B)) := ⟨inducing_toContinuousMap A B, toContinuousMap_injective⟩ @[to_additive] lemma range_toContinuousMap : Set.range (toContinuousMap : ContinuousMonoidHom A B → C(A, B)) = {f : C(A, B) | f 1 = 1 ∧ ∀ x y, f (x * y) = f x * f y} := by refine Set.Subset.antisymm (Set.range_subset_iff.2 fun f ↦ ⟨map_one f, map_mul f⟩) ?_ rintro f ⟨h1, hmul⟩ exact ⟨{ f with map_one' := h1, map_mul' := hmul }, rfl⟩ @[to_additive] theorem closedEmbedding_toContinuousMap [ContinuousMul B] [T2Space B] : ClosedEmbedding (toContinuousMap : ContinuousMonoidHom A B → C(A, B)) where toEmbedding := embedding_toContinuousMap A B isClosed_range := by simp only [range_toContinuousMap, Set.setOf_and, Set.setOf_forall] refine .inter (isClosed_singleton.preimage (ContinuousMap.continuous_eval_const 1)) <| isClosed_iInter fun x ↦ isClosed_iInter fun y ↦ ?_ exact isClosed_eq (ContinuousMap.continuous_eval_const (x * y)) <| .mul (ContinuousMap.continuous_eval_const x) (ContinuousMap.continuous_eval_const y) variable {A B C D E} @[to_additive] instance [T2Space B] : T2Space (ContinuousMonoidHom A B) := (embedding_toContinuousMap A B).t2Space @[to_additive] instance : TopologicalGroup (ContinuousMonoidHom A E) := let hi := inducing_toContinuousMap A E let hc := hi.continuous { continuous_mul := hi.continuous_iff.mpr (continuous_mul.comp (Continuous.prod_map hc hc)) continuous_inv := hi.continuous_iff.mpr (continuous_inv.comp hc) } @[to_additive] theorem continuous_of_continuous_uncurry {A : Type*} [TopologicalSpace A] (f : A → ContinuousMonoidHom B C) (h : Continuous (Function.uncurry fun x y => f x y)) : Continuous f := (inducing_toContinuousMap _ _).continuous_iff.mpr (ContinuousMap.continuous_of_continuous_uncurry _ h) @[to_additive] theorem continuous_comp [LocallyCompactSpace B] : Continuous fun f : ContinuousMonoidHom A B × ContinuousMonoidHom B C => f.2.comp f.1 := (inducing_toContinuousMap A C).continuous_iff.2 <| ContinuousMap.continuous_comp'.comp ((inducing_toContinuousMap A B).prod_map (inducing_toContinuousMap B C)).continuous @[to_additive] theorem continuous_comp_left (f : ContinuousMonoidHom A B) : Continuous fun g : ContinuousMonoidHom B C => g.comp f := (inducing_toContinuousMap A C).continuous_iff.2 <| f.toContinuousMap.continuous_comp_left.comp (inducing_toContinuousMap B C).continuous @[to_additive] theorem continuous_comp_right (f : ContinuousMonoidHom B C) : Continuous fun g : ContinuousMonoidHom A B => f.comp g := (inducing_toContinuousMap A C).continuous_iff.2 <| f.toContinuousMap.continuous_comp.comp (inducing_toContinuousMap A B).continuous variable (E) /-- `ContinuousMonoidHom _ f` is a functor. -/ @[to_additive "`ContinuousAddMonoidHom _ f` is a functor."] def compLeft (f : ContinuousMonoidHom A B) : ContinuousMonoidHom (ContinuousMonoidHom B E) (ContinuousMonoidHom A E) where toFun g := g.comp f map_one' := rfl map_mul' _g _h := rfl continuous_toFun := f.continuous_comp_left variable (A) {E} /-- `ContinuousMonoidHom f _` is a functor. -/ @[to_additive "`ContinuousAddMonoidHom f _` is a functor."] def compRight {B : Type*} [CommGroup B] [TopologicalSpace B] [TopologicalGroup B] (f : ContinuousMonoidHom B E) : ContinuousMonoidHom (ContinuousMonoidHom A B) (ContinuousMonoidHom A E) where toFun g := f.comp g map_one' := ext fun _a => map_one f map_mul' g h := ext fun a => map_mul f (g a) (h a) continuous_toFun := f.continuous_comp_right section LocallyCompact variable {X Y : Type*} [TopologicalSpace X] [Group X] [TopologicalGroup X] [UniformSpace Y] [CommGroup Y] [UniformGroup Y] [T0Space Y] [CompactSpace Y] @[to_additive] theorem locallyCompactSpace_of_equicontinuousAt (U : Set X) (V : Set Y) (hU : IsCompact U) (hV : V ∈ nhds (1 : Y)) (h : EquicontinuousAt (fun f : {f : X →* Y | Set.MapsTo f U V} ↦ (f : X → Y)) 1) : LocallyCompactSpace (ContinuousMonoidHom X Y) := by replace h := equicontinuous_of_equicontinuousAt_one _ h obtain ⟨W, hWo, hWV, hWc⟩ := local_compact_nhds hV let S1 : Set (X →* Y) := {f | Set.MapsTo f U W} let S2 : Set (ContinuousMonoidHom X Y) := {f | Set.MapsTo f U W} let S3 : Set C(X, Y) := (↑) '' S2 let S4 : Set (X → Y) := (↑) '' S3 replace h : Equicontinuous ((↑) : S1 → X → Y) := h.comp (Subtype.map _root_.id fun f hf ↦ hf.mono_right hWV) have hS4 : S4 = (↑) '' S1 := by ext constructor · rintro ⟨-, ⟨f, hf, rfl⟩, rfl⟩ exact ⟨f, hf, rfl⟩ · rintro ⟨f, hf, rfl⟩ exact ⟨⟨f, h.continuous ⟨f, hf⟩⟩, ⟨⟨f, h.continuous ⟨f, hf⟩⟩, hf, rfl⟩, rfl⟩ replace h : Equicontinuous ((↑) : S3 → X → Y) := by rw [equicontinuous_iff_range, ← Set.image_eq_range] at h ⊢ rwa [← hS4] at h replace hS4 : S4 = Set.pi U (fun _ ↦ W) ∩ Set.range ((↑) : (X →* Y) → (X → Y)) := by simp_rw [hS4, Set.ext_iff, Set.mem_image, S1, Set.mem_setOf_eq] exact fun f ↦ ⟨fun ⟨g, hg, hf⟩ ↦ hf ▸ ⟨hg, g, rfl⟩, fun ⟨hg, g, hf⟩ ↦ ⟨g, hf ▸ hg, hf⟩⟩ replace hS4 : IsClosed S4 := hS4.symm ▸ (isClosed_set_pi (fun _ _ ↦ hWc.isClosed)).inter (MonoidHom.isClosed_range_coe X Y) have hS2 : (interior S2).Nonempty := by let T : Set (ContinuousMonoidHom X Y) := {f | Set.MapsTo f U (interior W)} have h1 : T.Nonempty := ⟨1, fun _ _ ↦ mem_interior_iff_mem_nhds.mpr hWo⟩ have h2 : T ⊆ S2 := fun f hf ↦ hf.mono_right interior_subset have h3 : IsOpen T := isOpen_induced (ContinuousMap.isOpen_setOf_mapsTo hU isOpen_interior) exact h1.mono (interior_maximal h2 h3) exact TopologicalSpace.PositiveCompacts.locallyCompactSpace_of_group ⟨⟨S2, (inducing_toContinuousMap X Y).isCompact_iff.mpr (ArzelaAscoli.isCompact_of_equicontinuous S3 hS4.isCompact h)⟩, hS2⟩ variable [LocallyCompactSpace X] @[to_additive] theorem locallyCompactSpace_of_hasBasis (V : ℕ → Set Y) (hV : ∀ {n x}, x ∈ V n → x * x ∈ V n → x ∈ V (n + 1)) (hVo : Filter.HasBasis (nhds 1) (fun _ ↦ True) V) : LocallyCompactSpace (ContinuousMonoidHom X Y) := by obtain ⟨U0, hU0c, hU0o⟩ := exists_compact_mem_nhds (1 : X) let U_aux : ℕ → {S : Set X | S ∈ nhds 1} := Nat.rec ⟨U0, hU0o⟩ <| fun _ S ↦ let h := exists_closed_nhds_one_inv_eq_mul_subset S.2 ⟨Classical.choose h, (Classical.choose_spec h).1⟩ let U : ℕ → Set X := fun n ↦ (U_aux n).1 have hU1 : ∀ n, U n ∈ nhds 1 := fun n ↦ (U_aux n).2 have hU2 : ∀ n, U (n + 1) * U (n + 1) ⊆ U n := fun n ↦ (Classical.choose_spec (exists_closed_nhds_one_inv_eq_mul_subset (U_aux n).2)).2.2.2 have hU3 : ∀ n, U (n + 1) ⊆ U n := fun n x hx ↦ hU2 n (mul_one x ▸ Set.mul_mem_mul hx (mem_of_mem_nhds (hU1 (n + 1)))) have hU4 : ∀ f : X →* Y, Set.MapsTo f (U 0) (V 0) → ∀ n, Set.MapsTo f (U n) (V n) := by intro f hf n induction' n with n ih · exact hf · exact fun x hx ↦ hV (ih (hU3 n hx)) (map_mul f x x ▸ ih (hU2 n (Set.mul_mem_mul hx hx))) apply locallyCompactSpace_of_equicontinuousAt (U 0) (V 0) hU0c (hVo.mem_of_mem trivial) rw [hVo.uniformity_of_nhds_one.equicontinuousAt_iff_right] refine fun n _ ↦ Filter.eventually_iff_exists_mem.mpr ⟨U n, hU1 n, fun x hx ⟨f, hf⟩ ↦ ?_⟩ rw [Set.mem_setOf_eq, map_one, div_one] exact hU4 f hf n hx end LocallyCompact end ContinuousMonoidHom
Topology\Algebra\Equicontinuity.lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import Mathlib.Topology.Algebra.UniformConvergence /-! # Algebra-related equicontinuity criterions -/ open Function open UniformConvergence @[to_additive] theorem equicontinuous_of_equicontinuousAt_one {ι G M hom : Type*} [TopologicalSpace G] [UniformSpace M] [Group G] [Group M] [TopologicalGroup G] [UniformGroup M] [FunLike hom G M] [MonoidHomClass hom G M] (F : ι → hom) (hf : EquicontinuousAt ((↑) ∘ F) (1 : G)) : Equicontinuous ((↑) ∘ F) := by rw [equicontinuous_iff_continuous] rw [equicontinuousAt_iff_continuousAt] at hf let φ : G →* (ι →ᵤ M) := { toFun := swap ((↑) ∘ F) map_one' := by dsimp [UniformFun]; ext; exact map_one _ map_mul' := fun a b => by dsimp [UniformFun]; ext; exact map_mul _ _ _ } exact continuous_of_continuousAt_one φ hf @[to_additive] theorem uniformEquicontinuous_of_equicontinuousAt_one {ι G M hom : Type*} [UniformSpace G] [UniformSpace M] [Group G] [Group M] [UniformGroup G] [UniformGroup M] [FunLike hom G M] [MonoidHomClass hom G M] (F : ι → hom) (hf : EquicontinuousAt ((↑) ∘ F) (1 : G)) : UniformEquicontinuous ((↑) ∘ F) := by rw [uniformEquicontinuous_iff_uniformContinuous] rw [equicontinuousAt_iff_continuousAt] at hf let φ : G →* (ι →ᵤ M) := { toFun := swap ((↑) ∘ F) map_one' := by dsimp [UniformFun]; ext; exact map_one _ map_mul' := fun a b => by dsimp [UniformFun]; ext; exact map_mul _ _ _ } exact uniformContinuous_of_continuousAt_one φ hf