blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
139
content_id
stringlengths
40
40
detected_licenses
listlengths
0
16
license_type
stringclasses
2 values
repo_name
stringlengths
7
55
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
6 values
visit_date
int64
1,471B
1,694B
revision_date
int64
1,378B
1,694B
committer_date
int64
1,378B
1,694B
github_id
float64
1.33M
604M
star_events_count
int64
0
43.5k
fork_events_count
int64
0
1.5k
gha_license_id
stringclasses
6 values
gha_event_created_at
int64
1,402B
1,695B
gha_created_at
int64
1,359B
1,637B
gha_language
stringclasses
19 values
src_encoding
stringclasses
2 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
3
6.4M
extension
stringclasses
4 values
content
stringlengths
3
6.12M
97d19cac3f4dd0fbc2c39463b86a11558ab95f39
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/types/arrow_2.hlean
646a43250d3b3aaccd3d1e9ea8f64276a360065e
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
7,032
hlean
/- Copyright (c) 2015 Ulrik Buchholtz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ulrik Buchholtz -/ import ..function open eq is_equiv function namespace arrow structure arrow := (dom : Type) (cod : Type) (arrow : dom → cod) abbreviation dom [unfold 2] := @arrow.dom abbreviation cod [unfold 2] := @arrow.cod definition arrow_of_fn {A B : Type} (f : A → B) : arrow := arrow.mk A B f structure morphism (A B : Type) := (mor : A → B) definition morphism_of_arrow [coercion] (f : arrow) : morphism (dom f) (cod f) := morphism.mk (arrow.arrow f) attribute morphism.mor [coercion] structure arrow_hom (f g : arrow) := (on_dom : dom f → dom g) (on_cod : cod f → cod g) (commute : Π(x : dom f), g (on_dom x) = on_cod (f x)) abbreviation on_dom [unfold 2] := @arrow_hom.on_dom abbreviation on_cod [unfold 2] := @arrow_hom.on_cod abbreviation commute [unfold 2] := @arrow_hom.commute variables {f g : arrow} definition on_fiber [reducible] (r : arrow_hom f g) (y : cod f) : fiber f y → fiber g (on_cod r y) := fiber.rec (λx p, fiber.mk (on_dom r x) (commute r x ⬝ ap (on_cod r) p)) structure is_retraction [class] (r : arrow_hom f g) : Type := (sect : arrow_hom g f) (right_inverse_dom : Π(a : dom g), on_dom r (on_dom sect a) = a) (right_inverse_cod : Π(b : cod g), on_cod r (on_cod sect b) = b) (cohere : Π(a : dom g), commute r (on_dom sect a) ⬝ ap (on_cod r) (commute sect a) = ap g (right_inverse_dom a) ⬝ (right_inverse_cod (g a))⁻¹) definition retraction_on_fiber [reducible] (r : arrow_hom f g) [H : is_retraction r] (b : cod g) : fiber f (on_cod (is_retraction.sect r) b) → fiber g b := fiber.rec (λx q, fiber.mk (on_dom r x) (commute r x ⬝ ap (on_cod r) q ⬝ is_retraction.right_inverse_cod r b)) definition retraction_on_fiber_right_inverse' (r : arrow_hom f g) [H : is_retraction r] (a : dom g) (b : cod g) (p : g a = b) : retraction_on_fiber r b (on_fiber (is_retraction.sect r) b (fiber.mk a p)) = fiber.mk a p := begin induction p, unfold on_fiber, unfold retraction_on_fiber, apply @fiber.fiber_eq _ _ g (g a) (fiber.mk (on_dom r (on_dom (is_retraction.sect r) a)) (commute r (on_dom (is_retraction.sect r) a) ⬝ ap (on_cod r) (commute (is_retraction.sect r) a) ⬝ is_retraction.right_inverse_cod r (g a))) (fiber.mk a (refl (g a))) (is_retraction.right_inverse_dom r a), -- everything but this field should be inferred rewrite [is_retraction.cohere r a], apply inv_con_cancel_right end definition retraction_on_fiber_right_inverse (r : arrow_hom f g) [H : is_retraction r] : Π(b : cod g), Π(z : fiber g b), retraction_on_fiber r b (on_fiber (is_retraction.sect r) b z) = z := λb, fiber.rec (λa p, retraction_on_fiber_right_inverse' r a b p) -- Lemma 4.7.3 definition retraction_on_fiber_is_retraction [instance] (r : arrow_hom f g) [H : is_retraction r] (b : cod g) : _root_.is_retraction (retraction_on_fiber r b) := _root_.is_retraction.mk (on_fiber (is_retraction.sect r) b) (retraction_on_fiber_right_inverse r b) -- Theorem 4.7.4 definition retract_of_equivalence_is_equivalence (r : arrow_hom f g) [H : is_retraction r] [K : is_equiv f] : is_equiv g := begin apply @is_equiv_of_is_contr_fun _ _ g, intro b, apply is_contr_retract (retraction_on_fiber r b), exact is_contr_fun_of_is_equiv f (on_cod (is_retraction.sect r) b) end end arrow namespace arrow variables {A B : Type} {f g : A → B} (p : f ~ g) definition arrow_hom_of_homotopy : arrow_hom (arrow_of_fn f) (arrow_of_fn g) := arrow_hom.mk id id (λx, (p x)⁻¹) definition is_retraction_arrow_hom_of_homotopy [instance] : is_retraction (arrow_hom_of_homotopy p) := is_retraction.mk (arrow_hom_of_homotopy (λx, (p x)⁻¹)) (λa, idp) (λb, idp) (λa, con_eq_of_eq_inv_con (ap_id _)) end arrow namespace arrow /- equivalences in the arrow category; could be packaged into structures. cannot be moved to types.pi because of the dependence on types.equiv. -/ variables {A A' B B' : Type} (f : A → B) (f' : A' → B') (α : A → A') (β : B → B') [Hf : is_equiv f] [Hf' : is_equiv f'] include Hf Hf' open function definition inv_commute_of_commute (p : f' ∘ α ~ β ∘ f) : f'⁻¹ ∘ β ~ α ∘ f⁻¹ := begin apply inv_homotopy_of_homotopy_post f' (α ∘ f⁻¹) β, apply homotopy.symm, apply inv_homotopy_of_homotopy_pre f (f' ∘ α) β, apply p end definition inv_commute_of_commute_top (p : f' ∘ α ~ β ∘ f) (a : A) : inv_commute_of_commute f f' α β p (f a) = (ap f'⁻¹ (p a))⁻¹ ⬝ left_inv f' (α a) ⬝ ap α (left_inv f a)⁻¹ := begin unfold inv_commute_of_commute, unfold inv_homotopy_of_homotopy_post, unfold inv_homotopy_of_homotopy_pre, rewrite [adj f a,-(ap_compose β f)], rewrite [eq_of_square (natural_square p (left_inv f a))], rewrite [ap_inv f'⁻¹,ap_con f'⁻¹,con_inv,con.assoc,con.assoc], apply whisker_left (ap f'⁻¹ (p a))⁻¹, apply eq_of_square, rewrite [ap_inv α,-(ap_compose f'⁻¹ (f' ∘ α))], apply hinverse, rewrite [ap_compose (f'⁻¹ ∘ f') α], refine vconcat_eq _ (ap_id (ap α (left_inv f a))), apply natural_square_tr (left_inv f') (ap α (left_inv f a)) end definition ap_bot_inv_commute_of_commute (p : f' ∘ α ~ β ∘ f) (b : B) : ap f' (inv_commute_of_commute f f' α β p b) = right_inv f' (β b) ⬝ ap β (right_inv f b)⁻¹ ⬝ (p (f⁻¹ b))⁻¹ := begin unfold inv_commute_of_commute, unfold inv_homotopy_of_homotopy_post, unfold inv_homotopy_of_homotopy_pre, rewrite [ap_con,-(ap_compose f' f'⁻¹),-(adj f' (α (f⁻¹ b)))], rewrite [con.assoc (right_inv f' (β b)) (ap β (right_inv f b)⁻¹) (p (f⁻¹ b))⁻¹], apply eq_of_square, refine vconcat_eq _ (whisker_right (p (f⁻¹ b))⁻¹ (ap_inv β (right_inv f b)))⁻¹, refine vconcat_eq _ (con_inv (p (f⁻¹ b)) (ap β (right_inv f b))), refine vconcat_eq _ (ap_id (p (f⁻¹ b) ⬝ ap β (right_inv f b))⁻¹), apply natural_square_tr (right_inv f') (p (f⁻¹ b) ⬝ ap β (right_inv f b))⁻¹ end definition is_equiv_inv_commute_of_commute : is_equiv (inv_commute_of_commute f f' α β) := begin unfold inv_commute_of_commute, apply @is_equiv_compose _ _ _ (inv_homotopy_of_homotopy_post f' (α ∘ f⁻¹) β) (homotopy.symm ∘ (inv_homotopy_of_homotopy_pre f (f' ∘ α) β)), { apply @is_equiv_compose _ _ _ homotopy.symm (inv_homotopy_of_homotopy_pre f (f' ∘ α) β), { apply inv_homotopy_of_homotopy_pre.is_equiv }, { apply pi.is_equiv_homotopy_symm } }, { apply inv_homotopy_of_homotopy_post.is_equiv } end end arrow
22d97e7c3ad3b6f165aaa7334d06030cc4b648a7
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/ring_theory/localization.lean
16d99acef6a7fe71c8507d3a5082eaee2b34f99b
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
40,828
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston -/ import data.equiv.ring import tactic.ring_exp import ring_theory.ideal_operations import group_theory.monoid_localization import ring_theory.algebraic import ring_theory.integral_closure /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. Given such a localization map `f : R →+* S`, we can define the surjection `localization_map.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. Similarly, given commutative rings `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `S` to `Q`. We show the localization as a quotient type, defined in `group_theory.monoid_localization` as `submonoid.localization`, is a `comm_ring` and that the natural ring hom `of : R →+* localization M` is a localization map. We prove some lemmas about the `R`-algebra structure of `S`. When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for `localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions. We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field. We use this to show the field of fractions as a quotient type, `fraction_ring`, is a field. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a `submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a `localization_map` `f` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `f.to_localization_map`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `of : localization_map M (localization M)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S] {P : Type*} [comm_ring P] open function set_option old_structure_cmd true /-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S` satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`. We later define an instance coercing a localization map `f` to its codomain `S` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ @[nolint has_inhabited_instance] structure localization_map extends ring_hom R S, submonoid.localization_map M S /-- The ring hom underlying a `localization_map`. -/ add_decl_doc localization_map.to_ring_hom /-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization_map`. See `group_theory.monoid_localization` for its definition. -/ add_decl_doc localization_map.to_localization_map variables {M S} namespace ring_hom /-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/ def to_localization_map (f : R →+* S) (H1 : ∀ y : M, is_unit (f y)) (H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) : localization_map M S := { map_units' := H1, surj' := H2, eq_iff_exists' := H3, .. f } end ring_hom /-- Makes a `comm_ring` localization map from an additive `comm_monoid` localization map of `comm_ring`s. -/ def submonoid.localization_map.to_ring_localization (f : submonoid.localization_map M S) (h : ∀ x y, f.to_map (x + y) = f.to_map x + f.to_map y) : localization_map M S := { ..ring_hom.mk' f.to_monoid_hom h, ..f } namespace localization_map variables (f : localization_map M S) /-- Short for `to_ring_hom`; used for applying a localization map as a function. -/ abbreviation to_map := f.to_ring_hom lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y @[ext] lemma ext {f g : localization_map M S} (h : ∀ x, f.to_map x = g.to_map x) : f = g := begin cases f, cases g, simp only at *, exact funext h end lemma ext_iff {f g : localization_map M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x := ⟨λ h x, h ▸ rfl, ext⟩ lemma to_map_injective : injective (@localization_map.to_map _ _ M S _) := λ _ _ h, ext $ ring_hom.ext_iff.1 h /-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ set.range f.to_map variables {f} lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a + b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' + b', rw [f.to_map.map_add, ha, hb] end lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a * b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' * b', rw [f.to_map.map_mul, ha, hb] end lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) : f.is_integer (f.to_map a * b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, f.to_map.map_mul] end variables (f) /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer f (a * f.to_map b) := let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer f (f.to_map b * a) := by { simp_rw mul_comm _ a, apply exists_integer_multiple' } /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec {f : localization_map M S} (z : S) : z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 := classical.some_spec $ f.surj z /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' {f : localization_map M S} (z : S) : f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z := by rw [mul_comm, sec_spec] open_locale big_operators /-- We can clear the denominators of a finite set of fractions. -/ lemma exist_integer_multiples_of_finset (s : finset S) : ∃ (b : M), ∀ a ∈ s, is_integer f (f.to_map b * a) := begin haveI := classical.prop_decidable, use ∏ a in s, (f.to_localization_map.sec a).2, intros a ha, use (∏ x in s.erase a, (f.to_localization_map.sec x).2) * (f.to_localization_map.sec a).1, rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←f.to_map.map_mul], congr' 2, refine trans _ ((submonoid.subtype M).map_prod _ _).symm, rw [mul_comm, ←finset.prod_insert (s.not_mem_erase a), finset.insert_erase ha], refl, end lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) : f.to_map x = f.to_map y := f.to_localization_map.map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) : f.to_map x = f.to_map y := f.to_localization_map.map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 := by rw [hx, f.to_map.map_zero] at h; exact (is_unit.mul_left_eq_zero_iff_eq_zero (f.map_units y)).1 h /-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (f : localization_map M S) (x : R) (y : M) : S := f.to_localization_map.mk' x y @[simp] lemma mk'_sec (z : S) : f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z := f.to_localization_map.mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := f.to_localization_map.mk'_mul _ _ _ _ lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x := f.to_localization_map.mk'_one _ lemma mk'_spec (x) (y : M) : f.mk' x y * f.to_map y = f.to_map x := f.to_localization_map.mk'_spec _ _ lemma mk'_spec' (x) (y : M) : f.to_map y * f.mk' x y = f.to_map x := f.to_localization_map.mk'_spec' _ _ theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = f.mk' x y ↔ z * f.to_map y = f.to_map x := f.to_localization_map.eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : f.mk' x y = z ↔ f.to_map x = z * f.to_map y := f.to_localization_map.mk'_eq_iff_eq_mul lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) := f.to_localization_map.mk'_eq_iff_eq protected lemma eq {a₁ b₁} {a₂ b₂ : M} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := f.to_localization_map.eq lemma eq_iff_eq (g : localization_map M P) {x y} : f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y := f.to_localization_map.eq_iff_eq g.to_localization_map lemma mk'_eq_iff_mk'_eq (g : localization_map M P) {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.to_localization_map.mk'_eq_of_eq H @[simp] lemma mk'_self {x : R} {hx : x ∈ M} : f.mk' x ⟨x, hx⟩ = 1 := f.to_localization_map.mk'_self' _ hx @[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 := f.to_localization_map.mk'_self _ lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 := f.mk'_self' lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : f.to_map x * f.mk' y z = f.mk' (x * y) z := f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : f.mk' x y = f.to_map x * f.mk' 1 y := (f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : f.mk' (y * x) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : f.mk' (x * y) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_right _ _ lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp f.to_map y) := f.to_localization_map.is_unit_comp j.to_monoid_hom _ /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ := f.mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul, mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc, ←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul], simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul], ring_exp, end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg) $ begin intros x y, rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm, f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq', ←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul], show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _), repeat {rw ←g.map_mul}, rw [←g.map_sub, ←g.map_mul], apply f.eq_of_eq hg, erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub], simp only [f.to_map.map_mul, sec_spec'], ring_exp, end variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ := f.to_localization_map.lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := f.to_localization_map.lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : f.lift hg (f.to_map x) = g x := f.to_localization_map.lift_eq _ _ lemma lift_eq_iff {x y : R × M} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := f.to_localization_map.lift_eq_iff _ @[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : f.lift (f.is_unit_comp j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom lemma epic_of_localization_map {j k : S →+* P} (h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map _ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h lemma lift_unique {j : S →+* P} (hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : f.lift f.map_units x = x := f.to_localization_map.lift_id _ /-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`, the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P` induced by `k`. -/ @[simp] lemma lift_left_inverse {k : localization_map M S} (z : S) : k.lift f.map_units (f.lift k.map_units z) = z := f.to_localization_map.lift_left_inverse _ lemma lift_surjective_iff : surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := f.to_localization_map.lift_surjective_iff hg lemma lift_injective_iff : injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y := f.to_localization_map.lift_injective_iff hg variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) /-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have `g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M` and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map : S →+* Q := @lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩ variables {k} lemma map_eq (x) : f.map hy k (f.to_map x) = k.to_map (g x) := f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x @[simp] lemma map_comp : (f.map hy k).comp f.to_map = k.to_map.comp g := f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩ lemma map_mk' (x) (y : M) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ @[simp] lemma map_id (z : S) : f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z := f.lift_id _ /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ _ _ _ j.to_localization_map l.to_monoid_hom hl /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl /-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ noncomputable def ring_equiv_of_ring_equiv (k : localization_map T Q) (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := (f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $ (@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom) (λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add @[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H x = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (f.ring_equiv_of_ring_equiv k j H).to_monoid_hom = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) := f.to_localization_map.mul_equiv_of_mul_equiv_eq H _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) : f.ring_equiv_of_ring_equiv k j H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _ end localization_map namespace localization variables {M} instance : has_add (localization M) := ⟨λ z w, con.lift_on₂ z w (λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $ λ r1 r2 r3 r4 h1 h2, (con.eq _).2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) = (r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring ... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end⟩ instance : has_neg (localization M) := ⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $ λ r1 r2 h, (con.eq _).2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht], ring, end⟩ instance : has_zero (localization M) := ⟨mk 0 1⟩ private meta def tac := `[{ intros, refine quotient.sound' (r_of_eq _), simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul], ring }] instance : comm_ring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac), zero_add := λ y, quotient.induction_on' y (by tac), add_zero := λ y, quotient.induction_on' y (by tac), neg := has_neg.neg, add_left_neg := λ y, quotient.induction_on' y (by tac), add_comm := λ y z, quotient.induction_on₂' z y (by tac), left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), ..localization.comm_monoid M } variables (M) /-- Natural hom sending `x : R`, `R` a `comm_ring`, to the equivalence class of `(x, 1)` in the localization of `R` at a submonoid. -/ def of : localization_map M (localization M) := (localization.monoid_of M).to_ring_localization $ λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm] variables {M} lemma monoid_of_eq_of (x) : (monoid_of M).to_map x = (of M).to_map x := rfl lemma mk_one_eq_of (x) : mk x 1 = (of M).to_map x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = (of M).mk' x y := mk_eq_monoid_of_mk'_apply _ _ @[simp] lemma mk_eq_mk' : mk = (of M).mk' := mk_eq_monoid_of_mk' variables (f : localization_map M S) /-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/ noncomputable def ring_equiv_of_quotient : localization M ≃+* S := (mul_equiv_of_quotient f.to_localization_map).to_ring_equiv $ ((of M).lift f.map_units).map_add variables {f} @[simp] lemma ring_equiv_of_quotient_apply (x) : ring_equiv_of_quotient f x = (of M).lift f.map_units x := rfl @[simp] lemma ring_equiv_of_quotient_mk' (x y) : ring_equiv_of_quotient f ((of M).mk' x y) = f.mk' x y := mul_equiv_of_quotient_mk' _ _ lemma ring_equiv_of_quotient_mk (x y) : ring_equiv_of_quotient f (mk x y) = f.mk' x y := mul_equiv_of_quotient_mk _ _ @[simp] lemma ring_equiv_of_quotient_of (x) : ring_equiv_of_quotient f ((of M).to_map x) = f.to_map x := mul_equiv_of_quotient_monoid_of _ @[simp] lemma ring_equiv_of_quotient_symm_mk' (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = (of M).mk' x y := mul_equiv_of_quotient_symm_mk' _ _ lemma ring_equiv_of_quotient_symm_mk (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = mk x y := mul_equiv_of_quotient_symm_mk _ _ @[simp] lemma ring_equiv_of_quotient_symm_of (x) : (ring_equiv_of_quotient f).symm (f.to_map x) = (of M).to_map x := mul_equiv_of_quotient_symm_monoid_of _ end localization variables {M} namespace localization_map /-! ### `algebra` section Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map `f` needed to induce the `R`-algebra structure. -/ variables (f : localization_map M S) /-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ @[reducible, nolint unused_arguments] def codomain (f : localization_map M S) := S /-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ instance : algebra R f.codomain := f.to_map.to_algebra @[simp] lemma of_id (a : R) : (algebra.of_id R f.codomain) a = f.to_map a := rfl variables (f) /-- Localization map `f` from `R` to `S` as an `R`-linear map. -/ def lin_coe : R →ₗ[R] f.codomain := { to_fun := f.to_map, map_add' := f.to_map.map_add, map_smul' := f.to_map.map_mul } variables {f} instance coe_submodules : has_coe (ideal R) (submodule R f.codomain) := ⟨λ I, submodule.map f.lin_coe I⟩ lemma mem_coe (I : ideal R) {x : S} : x ∈ (I : submodule R f.codomain) ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x := iff.rfl @[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl variables {g : R →+* P} variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) lemma map_smul (x : f.codomain) (z : R) : f.map hy k (z • x : f.codomain) = @has_scalar.smul P k.codomain _ (g z) (f.map hy k x) := show f.map hy k (f.to_map z * x) = k.to_map (g z) * f.map hy k x, by rw [ring_hom.map_mul, map_eq] section integer_normalization open finsupp polynomial open_locale classical /-- `coeff_integer_normalization p` gives the coefficients of the polynomial `integer_normalization p` -/ noncomputable def coeff_integer_normalization (p : polynomial f.codomain) (i : ℕ) : R := if hi : i ∈ p.support then classical.some (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) else 0 lemma coeff_integer_normalization_mem_support (p : polynomial f.codomain) (i : ℕ) (h : coeff_integer_normalization p i ≠ 0) : i ∈ p.support := begin contrapose h, rw [ne.def, not_not, coeff_integer_normalization, dif_neg h] end /-- `integer_normalization g` normalizes `g` to have integer coefficients by clearing the denominators -/ noncomputable def integer_normalization : polynomial f.codomain → polynomial R := λ p, on_finset p.support (coeff_integer_normalization p) (coeff_integer_normalization_mem_support p) @[simp] lemma integer_normalization_coeff (p : polynomial f.codomain) (i : ℕ) : (integer_normalization p).coeff i = coeff_integer_normalization p i := rfl lemma integer_normalization_spec (p : polynomial f.codomain) : ∃ (b : M), ∀ i, f.to_map ((integer_normalization p).coeff i) = f.to_map b * p.coeff i := begin use classical.some (f.exist_integer_multiples_of_finset (p.support.image p.coeff)), intro i, rw [integer_normalization_coeff, coeff_integer_normalization], split_ifs with hi, { exact classical.some_spec (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) }, { convert (_root_.mul_zero (f.to_map _)).symm, { exact f.to_ring_hom.map_zero }, { exact finsupp.not_mem_support_iff.mp hi } } end lemma integer_normalization_map_to_map (p : polynomial f.codomain) : ∃ (b : M), (integer_normalization p).map f.to_map = f.to_map b • p := let ⟨b, hb⟩ := integer_normalization_spec p in ⟨b, polynomial.ext (λ i, by { rw coeff_map, exact hb i })⟩ variables {R' : Type*} [comm_ring R'] lemma integer_normalization_eval₂_eq_zero (g : f.codomain →+* R') (p : polynomial f.codomain) {x : R'} (hx : eval₂ g x p = 0) : eval₂ (g.comp f.to_map) x (integer_normalization p) = 0 := let ⟨b, hb⟩ := integer_normalization_map_to_map p in trans (eval₂_map f.to_map g x).symm (by rw [hb, eval₂_smul, hx, smul_zero]) lemma integer_normalization_aeval_eq_zero [algebra f.codomain R'] (p : polynomial f.codomain) {x : R'} (hx : aeval _ _ x p = 0) : aeval _ (algebra.comap R f.codomain R') x (integer_normalization p) = 0 := integer_normalization_eval₂_eq_zero (algebra_map f.codomain R') p hx end integer_normalization end localization_map variables (R) /-- The submonoid of non-zero-divisors of a `comm_ring` `R`. -/ def non_zero_divisors : submonoid R := { carrier := {x | ∀ z, z * x = 0 → z = 0}, one_mem' := λ z hz, by rwa mul_one at hz, mul_mem' := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } variables {A : Type*} [integral_domain A] lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : A} (hnx : x ≠ 0) (hxy : y * x = 0) : y = 0 := or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_iff_ne_zero {x : A} : x ∈ non_zero_divisors A ↔ x ≠ 0 := ⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm, λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩ lemma map_ne_zero_of_mem_non_zero_divisors {B : Type*} [ring B] {g : A →+* B} (hg : injective g) {x : non_zero_divisors A} : g x ≠ 0 := λ h0, mem_non_zero_divisors_iff_ne_zero.1 x.2 $ g.injective_iff.1 hg x h0 lemma map_mem_non_zero_divisors {B : Type*} [integral_domain B] {g : A →+* B} (hg : injective g) {x : non_zero_divisors A} : g x ∈ non_zero_divisors B := λ z hz, eq_zero_of_ne_zero_of_mul_eq_zero (map_ne_zero_of_mem_non_zero_divisors hg) hz variables (K : Type*) /-- Localization map from an integral domain `R` to its field of fractions. -/ @[reducible] def fraction_map [comm_ring K] := localization_map (non_zero_divisors R) K namespace fraction_map open localization_map variables {R K} lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} : x = 0 ↔ φ.to_map x = 0 := begin rw ← φ.to_map.map_zero, split; intro h, { rw h }, { cases φ.eq_iff_exists.mp h with c hc, rw zero_mul at hc, exact c.2 x hc } end protected theorem injective [comm_ring K] (φ : fraction_map R K) : injective φ.to_map := φ.to_map.injective_iff.2 (λ _ h, φ.to_map_eq_zero_iff.mpr h) local attribute [instance] classical.dec_eq /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an integral domain. -/ def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases φ.surj z with x hx, cases φ.surj w with y hy, have : z * w * φ.to_map y.2 * φ.to_map x.2 = φ.to_map x.1 * φ.to_map y.1, by rw [mul_assoc z, hy, ←hx]; ac_refl, erw h at this, rw [zero_mul, zero_mul, ←φ.to_map.map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero (φ.to_map_eq_zero_iff.mpr this.symm) with H H, { exact or.inl (φ.eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (φ.eq_zero_of_fst_eq_zero hy H) }, end, zero_ne_one := by erw [←φ.to_map.map_zero, ←φ.to_map.map_one]; exact λ h, zero_ne_one (φ.injective h), ..(infer_instance : comm_ring K) } /-- The inverse of an element in the field of fractions of an integral domain. -/ protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K := if h : z = 0 then 0 else φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩ protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) : x * φ.inv x = 1 := show x * dite _ _ _ = 1, by rw [dif_neg hx, ←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩), one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a field. -/ noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K := { inv := φ.inv, mul_inv_cancel := φ.mul_inv_cancel, inv_zero := dif_pos rfl, ..φ.to_integral_domain } variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L] (f : fraction_map A K) {g : A →+* L} lemma mk'_eq_div {r s} : f.mk' r s = f.to_map r / f.to_map s := f.mk'_eq_iff_eq_mul.2 $ (div_mul_cancel _ (map_ne_zero_of_mem_non_zero_divisors f.injective)).symm lemma is_unit_map_of_injective (hg : injective g) (y : non_zero_divisors A) : is_unit (g y) := is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (hg : injective g) : K →+* L := f.lift $ is_unit_map_of_injective hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all `x : A, y ∈ non_zero_divisors A`. -/ @[simp] lemma lift_mk' (hg : injective g) (x y) : f.lift hg (f.mk' x y) = g x / g y := begin erw f.lift_mk' (is_unit_map_of_injective hg), erw submonoid.localization_map.mul_inv_left (λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from is_unit_map_of_injective hg y), exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg)).symm, end /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L` and an injective ring hom `j : A →+* B`, we get a field hom sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : fraction_map B L) {j : A →+* B} (hj : injective j) : K →+* L := f.map (λ y, mem_non_zero_divisors_iff_ne_zero.2 $ map_ne_zero_of_mem_non_zero_divisors hj) g /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of fields of fractions `K ≃+* L`. -/ noncomputable def field_equiv_of_ring_equiv (g : fraction_map B L) (h : A ≃+* B) : K ≃+* L := f.ring_equiv_of_ring_equiv g h begin ext b, show b ∈ h.to_equiv '' _ ↔ _, erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero], exact h.symm.map_ne_zero_iff end /-- The cast from `int` to `rat` as a `fraction_map`. -/ def int.fraction_map : fraction_map ℤ ℚ := { to_fun := coe, map_units' := begin rintro ⟨x, hx⟩, rw [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hx, simpa only [is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx, end, surj' := begin rintro ⟨n, d, hd, h⟩, refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos] end, eq_iff_exists' := begin intros x y, rw [int.cast_inj], refine ⟨by { rintro rfl, use 1 }, _⟩, rintro ⟨⟨c, hc⟩, h⟩, apply int.eq_of_mul_eq_mul_right _ h, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hc, end, ..int.cast_ring_hom ℚ } lemma integer_normalization_eq_zero_iff {p : polynomial f.codomain} : integer_normalization p = 0 ↔ p = 0 := begin refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm), obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec p, split; intros h i, { apply f.to_map_eq_zero_iff.mpr, rw [hb i, h i], exact _root_.mul_zero _ }, { have hi := h i, rw [polynomial.coeff_zero, f.to_map_eq_zero_iff, hb i] at hi, apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi), intro h, apply mem_non_zero_divisors_iff_ne_zero.mp nonzero, exact f.to_map_eq_zero_iff.mpr h } end /-- A field is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/ lemma comap_is_algebraic_iff [algebra f.codomain L] : algebra.is_algebraic A (algebra.comap A f.codomain L) ↔ algebra.is_algebraic f.codomain L := begin split; intros h x; obtain ⟨p, hp, px⟩ := h x, { refine ⟨p.map f.to_map, λ h, hp (polynomial.ext (λ i, _)), _⟩, { have : f.to_map (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]), exact f.to_map_eq_zero_iff.mpr this }, { exact trans (polynomial.eval₂_map _ _ _) px } }, { exact ⟨integer_normalization p, mt f.integer_normalization_eq_zero_iff.mp hp, integer_normalization_aeval_eq_zero p px⟩ }, end end fraction_map namespace integral_closure variables {L : Type*} [field K] [field L] {f : fraction_map A K} open algebra /-- If the field `L` is an algebraic extension of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_algebraic [algebra A L] (alg : is_algebraic A L) (inj : ∀ x, algebra_map A L x = 0 → x = 0) : fraction_map (integral_closure A L) L := (algebra_map (integral_closure A L) L).to_localization_map (λ ⟨⟨y, integral⟩, nonzero⟩, have y ≠ 0 := λ h, mem_non_zero_divisors_iff_ne_zero.mp nonzero (subtype.ext_iff_val.mpr h), show is_unit y, from ⟨⟨y, y⁻¹, mul_inv_cancel this, inv_mul_cancel this⟩, rfl⟩) (λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in ⟨⟨x, ⟨y, mem_non_zero_divisors_iff_ne_zero.mpr hy⟩⟩, hxy⟩) (λ x y, ⟨ λ (h : x.1 = y.1), ⟨1, by simpa using subtype.ext_iff_val.mpr h⟩, λ ⟨c, hc⟩, congr_arg (algebra_map _ L) (eq_of_mul_eq_mul_right_of_ne_zero (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc) ⟩) /-- If the field `L` is a finite extension of the fraction field of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_finite_extension [algebra f.codomain L] [finite_dimensional f.codomain L] : fraction_map (integral_closure A (algebra.comap A f.codomain L)) (algebra.comap A f.codomain L) := fraction_map_of_algebraic (f.comap_is_algebraic_iff.mpr is_algebraic_of_finite) (λ x hx, f.to_map_eq_zero_iff.mpr ((algebra_map f.codomain L).map_eq_zero.mp hx)) end integral_closure variables (A) /-- The fraction field of an integral domain as a quotient type. -/ @[reducible] def fraction_ring := localization (non_zero_divisors A) /-- Natural hom sending `x : A`, `A` an integral domain, to the equivalence class of `(x, 1)` in the field of fractions of `A`. -/ def of : fraction_map A (localization (non_zero_divisors A)) := localization.of (non_zero_divisors A) namespace fraction_ring variables {A} noncomputable instance : field (fraction_ring A) := (of A).to_field @[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) = ((of A).to_map r / (of A).to_map s : fraction_ring A) := by erw [localization.mk_eq_mk', (of A).mk'_eq_div] /-- Given an integral domain `A` and a localization map to a field of fractions `f : A →+* K`, we get an isomorphism between the field of fractions of `A` as a quotient type and `K`. -/ noncomputable def field_equiv_of_quotient {K : Type*} [field K] (f : fraction_map A K) : fraction_ring A ≃+* K := localization.ring_equiv_of_quotient f end fraction_ring
4b2326fea2f46163f1425849a0fa4c8eb1d5520f
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Lean/Meta/Basic.lean
9dfa41838f0ef90f67778949bc8a3c9fb4eb3633
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,714
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.Reader import Init.Lean.Data.LOption import Init.Lean.Data.NameGenerator import Init.Lean.Environment import Init.Lean.Class import Init.Lean.ReducibilityAttrs import Init.Lean.Util.Trace import Init.Lean.Meta.Exception import Init.Lean.Meta.DiscrTreeTypes import Init.Lean.Eval /- This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean namespace Meta inductive TransparencyMode | all | default | reducible namespace TransparencyMode instance : Inhabited TransparencyMode := ⟨TransparencyMode.default⟩ def beq : TransparencyMode → TransparencyMode → Bool | all, all => true | default, default => true | reducible, reducible => true | _, _ => false instance : HasBeq TransparencyMode := ⟨beq⟩ def hash : TransparencyMode → USize | all => 7 | default => 11 | reducible => 13 instance : Hashable TransparencyMode := ⟨hash⟩ def lt : TransparencyMode → TransparencyMode → Bool | reducible, default => true | reducible, all => true | default, all => true | _, _ => false end TransparencyMode structure Config := (opts : Options := {}) (foApprox : Bool := false) (ctxApprox : Bool := false) (quasiPatternApprox : Bool := false) /- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ (constApprox : Bool := false) /- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ (isDefEqStuckEx : Bool := false) (debug : Bool := false) (transparency : TransparencyMode := TransparencyMode.default) structure ParamInfo := (implicit : Bool := false) (instImplicit : Bool := false) (hasFwdDeps : Bool := false) (backDeps : Array Nat := #[]) instance ParamInfo.inhabited : Inhabited ParamInfo := ⟨{}⟩ structure FunInfo := (paramInfo : Array ParamInfo := #[]) (resultDeps : Array Nat := #[]) structure InfoCacheKey := (transparency : TransparencyMode) (expr : Expr) (nargs? : Option Nat) namespace InfoCacheKey instance : Inhabited InfoCacheKey := ⟨⟨arbitrary _, arbitrary _, arbitrary _⟩⟩ instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) $ mixHash (hash expr) (hash nargs)⟩ instance : HasBeq InfoCacheKey := ⟨fun ⟨t₁, e₁, n₁⟩ ⟨t₂, e₂, n₂⟩ => t₁ == t₂ && n₁ == n₂ && e₁ == e₂⟩ end InfoCacheKey structure Cache := (inferType : PersistentExprStructMap Expr := {}) (funInfo : PersistentHashMap InfoCacheKey FunInfo := {}) (synthInstance : PersistentHashMap Expr (Option Expr) := {}) structure Context := (config : Config := {}) (lctx : LocalContext := {}) (localInstances : LocalInstances := #[]) structure PostponedEntry := (lhs : Level) (rhs : Level) structure State := (env : Environment) (mctx : MetavarContext := {}) (cache : Cache := {}) (ngen : NameGenerator := {}) (traceState : TraceState := {}) (postponed : PersistentArray PostponedEntry := {}) abbrev MetaM := ReaderT Context (EStateM Exception State) instance MetaM.inhabited {α} : Inhabited (MetaM α) := ⟨fun c s => EStateM.Result.error (arbitrary _) s⟩ @[inline] def getLCtx : MetaM LocalContext := do ctx ← read; pure ctx.lctx @[inline] def getLocalInstances : MetaM LocalInstances := do ctx ← read; pure ctx.localInstances @[inline] def getConfig : MetaM Config := do ctx ← read; pure ctx.config @[inline] def getMCtx : MetaM MetavarContext := do s ← get; pure s.mctx @[inline] def getEnv : MetaM Environment := do s ← get; pure s.env def mkWHNFRef : IO (IO.Ref (Expr → MetaM Expr)) := IO.mkRef $ fun _ => throw $ Exception.other "whnf implementation was not set" @[init mkWHNFRef] def whnfRef : IO.Ref (Expr → MetaM Expr) := arbitrary _ def mkInferTypeRef : IO (IO.Ref (Expr → MetaM Expr)) := IO.mkRef $ fun _ => throw $ Exception.other "inferType implementation was not set" @[init mkInferTypeRef] def inferTypeRef : IO.Ref (Expr → MetaM Expr) := arbitrary _ def mkIsExprDefEqAuxRef : IO (IO.Ref (Expr → Expr → MetaM Bool)) := IO.mkRef $ fun _ _ => throw $ Exception.other "isDefEq implementation was not set" @[init mkIsExprDefEqAuxRef] def isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) := arbitrary _ def mkSynthPendingRef : IO (IO.Ref (Expr → MetaM Bool)) := IO.mkRef $ fun _ => pure false @[init mkSynthPendingRef] def synthPendingRef : IO.Ref (Expr → MetaM Bool) := arbitrary _ structure MetaExtState := (whnf : Expr → MetaM Expr) (inferType : Expr → MetaM Expr) (isDefEqAux : Expr → Expr → MetaM Bool) (synthPending : Expr → MetaM Bool) instance MetaExtState.inhabited : Inhabited MetaExtState := ⟨{ whnf := arbitrary _, inferType := arbitrary _, isDefEqAux := arbitrary _, synthPending := arbitrary _ }⟩ def mkMetaExtension : IO (EnvExtension MetaExtState) := registerEnvExtension $ do whnf ← whnfRef.get; inferType ← inferTypeRef.get; isDefEqAux ← isExprDefEqAuxRef.get; synthPending ← synthPendingRef.get; pure { whnf := whnf, inferType := inferType, isDefEqAux := isDefEqAux, synthPending := synthPending } @[init mkMetaExtension] constant metaExt : EnvExtension MetaExtState := arbitrary _ def whnf (e : Expr) : MetaM Expr := do env ← getEnv; (metaExt.getState env).whnf e def whnfForall (e : Expr) : MetaM Expr := do e' ← whnf e; if e'.isForall then pure e' else pure e def inferType (e : Expr) : MetaM Expr := do env ← getEnv; (metaExt.getState env).inferType e def isExprDefEqAux (t s : Expr) : MetaM Bool := do env ← getEnv; (metaExt.getState env).isDefEqAux t s def synthPending (e : Expr) : MetaM Bool := do env ← getEnv; (metaExt.getState env).synthPending e def mkFreshId : MetaM Name := do s ← get; let id := s.ngen.curr; modify $ fun s => { ngen := s.ngen.next, .. s }; pure id def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (userName : Name := Name.anonymous) (kind : MetavarKind := MetavarKind.natural) : MetaM Expr := do mvarId ← mkFreshId; modify $ fun s => { mctx := s.mctx.addExprMVarDecl mvarId userName lctx localInsts type kind, .. s }; pure $ mkMVar mvarId def mkFreshExprMVar (type : Expr) (userName : Name := Name.anonymous) (kind : MetavarKind := MetavarKind.natural) : MetaM Expr := do lctx ← getLCtx; localInsts ← getLocalInstances; mkFreshExprMVarAt lctx localInsts type userName kind def mkFreshLevelMVar : MetaM Level := do mvarId ← mkFreshId; modify $ fun s => { mctx := s.mctx.addLevelMVarDecl mvarId, .. s}; pure $ mkLevelMVar mvarId @[inline] def throwEx {α} (f : ExceptionContext → Exception) : MetaM α := do ctx ← read; s ← get; throw (f {env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts }) def throwBug {α} (b : Bug) : MetaM α := throwEx $ Exception.bug b /-- Execute `x` only in debugging mode. -/ @[inline] private def whenDebugging {α} (x : MetaM α) : MetaM Unit := do ctx ← read; when ctx.config.debug (do x; pure ()) @[inline] def shouldReduceAll : MetaM Bool := do ctx ← read; pure $ ctx.config.transparency == TransparencyMode.all @[inline] def shouldReduceReducibleOnly : MetaM Bool := do ctx ← read; pure $ ctx.config.transparency == TransparencyMode.reducible @[inline] def getTransparency : MetaM TransparencyMode := do ctx ← read; pure $ ctx.config.transparency @[inline] private def getOptions : MetaM Options := do ctx ← read; pure ctx.config.opts -- Remark: wanted to use `private`, but in C++ parser, `private` declarations do not shadow outer public ones. -- TODO: fix this bug @[inline] def isReducible (constName : Name) : MetaM Bool := do env ← getEnv; pure $ isReducible env constName @[inline] def withConfig {α} (f : Config → Config) (x : MetaM α) : MetaM α := adaptReader (fun (ctx : Context) => { config := f ctx.config, .. ctx }) x /-- While executing `x`, ensure the given transparency mode is used. -/ @[inline] def withTransparency {α} (mode : TransparencyMode) (x : MetaM α) : MetaM α := withConfig (fun config => { transparency := mode, .. config }) x @[inline] def withAtLeastTransparency {α} (mode : TransparencyMode) (x : MetaM α) : MetaM α := withConfig (fun config => let oldMode := config.transparency; let mode := if oldMode.lt mode then mode else oldMode; { transparency := mode, .. config }) x def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do mctx ← getMCtx; match mctx.findDecl? mvarId with | some d => pure d | none => throwEx $ Exception.unknownExprMVar mvarId def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do mvarDecl ← getMVarDecl mvarId; mctx ← getMCtx; pure $ mvarDecl.depth != mctx.depth def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do mvarDecl ← getMVarDecl mvarId; match mvarDecl.kind with | MetavarKind.syntheticOpaque => pure true | _ => do mctx ← getMCtx; pure $ mvarDecl.depth != mctx.depth def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do mctx ← getMCtx; match mctx.findLevelDepth? mvarId with | some depth => pure $ depth != mctx.depth | _ => throwEx $ Exception.unknownLevelMVar mvarId @[inline] def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool := do mctx ← getMCtx; pure $ mctx.isExprAssigned mvarId @[inline] def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) := do mctx ← getMCtx; pure (mctx.getExprAssignment? mvarId) def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit := do whenDebugging $ whenM (isExprMVarAssigned mvarId) $ throwBug $ Bug.overwritingExprMVar mvarId; modify $ fun s => { mctx := s.mctx.assignExpr mvarId val, .. s } def hasAssignableMVar (e : Expr) : MetaM Bool := do mctx ← getMCtx; pure $ mctx.hasAssignableMVar e def dbgTrace {α} [HasToString α] (a : α) : MetaM Unit := _root_.dbgTrace (toString a) $ fun _ => pure () @[inline] private def getTraceState : MetaM TraceState := do s ← get; pure s.traceState def addContext (msg : MessageData) : MetaM MessageData := do ctx ← read; s ← get; pure $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } msg instance tracer : SimpleMonadTracerAdapter MetaM := { getOptions := getOptions, getTraceState := getTraceState, addContext := addContext, modifyTraceState := fun f => modify $ fun s => { traceState := f s.traceState, .. s } } def getConstAux (constName : Name) (exception? : Bool) : MetaM (Option ConstantInfo) := do env ← getEnv; match env.find? constName with | some (info@(ConstantInfo.thmInfo _)) => condM shouldReduceAll (pure (some info)) (pure none) | some (info@(ConstantInfo.defnInfo _)) => condM shouldReduceReducibleOnly (condM (isReducible constName) (pure (some info)) (pure none)) (pure (some info)) | some info => pure (some info) | none => if exception? then throwEx $ Exception.unknownConst constName else pure none @[inline] def getConst (constName : Name) : MetaM (Option ConstantInfo) := getConstAux constName true @[inline] def getConstNoEx (constName : Name) : MetaM (Option ConstantInfo) := getConstAux constName false def getConstInfo (constName : Name) : MetaM ConstantInfo := do env ← getEnv; match env.find? constName with | some info => pure info | none => throwEx $ Exception.unknownConst constName def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do lctx ← getLCtx; match lctx.find? fvarId with | some d => pure d | none => throwEx $ Exception.unknownFVar fvarId def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := getLocalDecl fvar.fvarId! def instantiateMVars (e : Expr) : MetaM Expr := if e.hasMVar then modifyGet $ fun s => let (e, mctx) := s.mctx.instantiateMVars e; (e, { mctx := mctx, .. s }) else pure e @[inline] private def liftMkBindingM {α} (x : MetavarContext.MkBindingM α) : MetaM α := fun ctx s => match x ctx.lctx { mctx := s.mctx, ngen := s.ngen } with | EStateM.Result.ok e newS => EStateM.Result.ok e { mctx := newS.mctx, ngen := newS.ngen, .. s} | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => EStateM.Result.error (Exception.revertFailure toRevert decl { lctx := lctx, mctx := mctx, env := s.env, opts := ctx.config.opts }) { mctx := newS.mctx, ngen := newS.ngen, .. s } def mkForall (xs : Array Expr) (e : Expr) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.mkForall xs e def mkLambda (xs : Array Expr) (e : Expr) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.mkLambda xs e /-- Save cache, execute `x`, restore cache -/ @[inline] def savingCache {α} (x : MetaM α) : MetaM α := do s ← get; let savedCache := s.cache; finally x (modify $ fun s => { cache := savedCache, .. s }) def isClassQuickConst (constName : Name) : MetaM (LOption Name) := do env ← getEnv; if isClass env constName then pure (LOption.some constName) else do cinfo? ← getConst constName; match cinfo? with | some _ => pure LOption.undef | none => pure LOption.none partial def isClassQuick : Expr → MetaM (LOption Name) | Expr.bvar _ _ => pure LOption.none | Expr.lit _ _ => pure LOption.none | Expr.fvar _ _ => pure LOption.none | Expr.sort _ _ => pure LOption.none | Expr.lam _ _ _ _ => pure LOption.none | Expr.letE _ _ _ _ _ => pure LOption.undef | Expr.proj _ _ _ _ => pure LOption.undef | Expr.forallE _ _ b _ => isClassQuick b | Expr.mdata _ e _ => isClassQuick e | Expr.const n _ _ => isClassQuickConst n | Expr.mvar mvarId _ => do val? ← getExprMVarAssignment? mvarId; match val? with | some val => isClassQuick val | none => pure LOption.none | Expr.app f _ _ => match f.getAppFn with | Expr.const n _ _ => isClassQuickConst n | Expr.lam _ _ _ _ => pure LOption.undef | _ => pure LOption.none | Expr.localE _ _ _ _ => unreachable! /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache {α} (x : MetaM α) : MetaM α := do s ← get; let savedSythInstance := s.cache.synthInstance; modify $ fun s => { cache := { synthInstance := {}, .. s.cache }, .. s }; finally x (modify $ fun s => { cache := { synthInstance := savedSythInstance, .. s.cache }, .. s }) /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ @[inline] def withNewLocalInstance {α} (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := resettingSynthInstanceCache $ adaptReader (fun (ctx : Context) => { localInstances := ctx.localInstances.push { className := className, fvar := fvar }, .. ctx }) k /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ @[specialize] partial def withNewLocalInstances {α} (isClassExpensive : Expr → MetaM (Option Name)) (fvars : Array Expr) : Nat → MetaM α → MetaM α | i, k => if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩; decl ← getFVarLocalDecl fvar; c? ← isClassQuick decl.type; match c? with | LOption.none => withNewLocalInstances (i+1) k | LOption.undef => do c? ← isClassExpensive decl.type; match c? with | none => withNewLocalInstances (i+1) k | some c => withNewLocalInstance c fvar $ withNewLocalInstances (i+1) k | LOption.some c => withNewLocalInstance c fvar $ withNewLocalInstances (i+1) k else k /-- `forallTelescopeAux whnf k lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context exteded with the declaration for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing? == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing? == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ @[specialize] private partial def forallTelescopeReducingAuxAux {α} (isClassExpensive : Expr → MetaM (Option Name)) (reducing? : Bool) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : LocalContext → Array Expr → Nat → Expr → MetaM α | lctx, fvars, j, type@(Expr.forallE n d b c) => do let process : Unit → MetaM α := fun _ => do { let d := d.instantiateRevRange j fvars.size fvars; fvarId ← mkFreshId; let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo; let fvar := mkFVar fvarId; let fvars := fvars.push fvar; forallTelescopeReducingAuxAux lctx fvars j b }; match maxFVars? with | none => process () | some maxFVars => if fvars.size < maxFVars then process () else let type := type.instantiateRevRange j fvars.size fvars; adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ withNewLocalInstances isClassExpensive fvars j $ k fvars type | lctx, fvars, j, type => let type := type.instantiateRevRange j fvars.size fvars; adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ withNewLocalInstances isClassExpensive fvars j $ if reducing? then do newType ← whnf type; if newType.isForall then forallTelescopeReducingAuxAux lctx fvars fvars.size newType else k fvars type else k fvars type /- We need this auxiliary definition because it depends on `isClassExpensive`, and `isClassExpensive` depends on it. -/ @[specialize] private def forallTelescopeReducingAux {α} (isClassExpensive : Expr → MetaM (Option Name)) (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do newType ← whnf type; if newType.isForall then do lctx ← getLCtx; forallTelescopeReducingAuxAux isClassExpensive true maxFVars? k lctx #[] 0 newType else k #[] type partial def isClassExpensive : Expr → MetaM (Option Name) | type => withTransparency TransparencyMode.reducible $ -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux isClassExpensive type none $ fun xs type => do match type.getAppFn with | Expr.const c _ _ => do env ← getEnv; pure $ if isClass env c then some c else none | _ => pure none /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do lctx ← getLCtx; forallTelescopeReducingAuxAux isClassExpensive false none k lctx #[] 0 type /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux isClassExpensive type none k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux isClassExpensive type maxFVars? k def isClass (type : Expr) : MetaM (Option Name) := do c? ← isClassQuick type; match c? with | LOption.none => pure none | LOption.some c => pure (some c) | LOption.undef => isClassExpensive type /-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/ private partial def lambdaTelescopeAux {α} (k : Array Expr → Expr → MetaM α) : LocalContext → Array Expr → Nat → Expr → MetaM α | lctx, fvars, j, Expr.lam n d b c => do let d := d.instantiateRevRange j fvars.size fvars; fvarId ← mkFreshId; let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo; let fvar := mkFVar fvarId; lambdaTelescopeAux lctx (fvars.push fvar) j b | lctx, fvars, j, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars; let v := v.instantiateRevRange j fvars.size fvars; fvarId ← mkFreshId; let lctx := lctx.mkLetDecl fvarId n t v; let fvar := mkFVar fvarId; lambdaTelescopeAux lctx (fvars.push fvar) j b | lctx, fvars, j, e => let e := e.instantiateRevRange j fvars.size fvars; adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ withNewLocalInstances isClassExpensive fvars j $ do k fvars e /-- Similar to `forallTelescope` but for lambda and let expressions. -/ def lambdaTelescope {α} (e : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do lctx ← getLCtx; lambdaTelescopeAux k lctx #[] 0 e private partial def forallMetaTelescopeReducingAux (reducing? : Bool) (maxMVars? : Option Nat) : Array Expr → Array BinderInfo → Nat → Expr → MetaM (Array Expr × Array BinderInfo × Expr) | mvars, bis, j, type@(Expr.forallE n d b c) => do let process : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do { let d := d.instantiateRevRange j mvars.size mvars; mvar ← mkFreshExprMVar d; let mvars := mvars.push mvar; let bis := bis.push c.binderInfo; forallMetaTelescopeReducingAux mvars bis j b }; match maxMVars? with | none => process () | some maxMVars => if mvars.size < maxMVars then process () else let type := type.instantiateRevRange j mvars.size mvars; pure (mvars, bis, type) | mvars, bis, j, type => let type := type.instantiateRevRange j mvars.size mvars; if reducing? then do newType ← whnf type; if newType.isForall then forallMetaTelescopeReducingAux mvars bis mvars.size newType else pure (mvars, bis, type) else pure (mvars, bis, type) /-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/ def forallMetaTelescope (e : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux false none #[] #[] 0 e /-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux true maxMVars? #[] #[] 0 e /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ private partial def lambdaMetaTelescopeAux (maxMVars? : Option Nat) : Array Expr → Array BinderInfo → Nat → Expr → MetaM (Array Expr × Array BinderInfo × Expr) | mvars, bis, j, type => do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do { let type := type.instantiateRevRange j mvars.size mvars; pure (mvars, bis, type) }; let process : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do { match type with | Expr.lam n d b c => do let d := d.instantiateRevRange j mvars.size mvars; mvar ← mkFreshExprMVar d; let mvars := mvars.push mvar; let bis := bis.push c.binderInfo; lambdaMetaTelescopeAux mvars bis j b | _ => finalize () }; match maxMVars? with | none => process () | some maxMVars => if mvars.size < maxMVars then process () else finalize () /-- Similar to `forallMetaTelescope` but for lambda expressions. -/ def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := lambdaMetaTelescopeAux maxMVars? #[] #[] 0 e @[inline] def liftStateMCtx {α} (x : StateM MetavarContext α) : MetaM α := fun _ s => let (a, mctx) := x.run s.mctx; EStateM.Result.ok a { mctx := mctx, .. s } def instantiateLevelMVars (lvl : Level) : MetaM Level := liftStateMCtx $ MetavarContext.instantiateLevelMVars lvl def assignLevelMVar (mvarId : MVarId) (lvl : Level) : MetaM Unit := modify $ fun s => { mctx := MetavarContext.assignLevel s.mctx mvarId lvl, .. s } def mkFreshLevelMVarId : MetaM MVarId := do mvarId ← mkFreshId; modify $ fun s => { mctx := s.mctx.addLevelMVarDecl mvarId, .. s }; pure mvarId def whnfD : Expr → MetaM Expr := fun e => withTransparency TransparencyMode.default $ whnf e /-- Execute `x` using approximate unification. -/ @[inline] def approxDefEq {α} (x : MetaM α) : MetaM α := adaptReader (fun (ctx : Context) => { config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true, .. ctx.config }, .. ctx }) x @[inline] private def withNewFVar {α} (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do c? ← isClass fvarType; match c? with | none => k fvar | some c => withNewLocalInstance c fvar $ k fvar def withLocalDecl {α} (n : Name) (type : Expr) (bi : BinderInfo) (k : Expr → MetaM α) : MetaM α := do fvarId ← mkFreshId; ctx ← read; let lctx := ctx.lctx.mkLocalDecl fvarId n type bi; let fvar := mkFVar fvarId; adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ withNewFVar fvar type k def withLocalDeclD {α} (n : Name) (type : Expr) (k : Expr → MetaM α) : MetaM α := withLocalDecl n type BinderInfo.default k def withLetDecl {α} (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do fvarId ← mkFreshId; ctx ← read; let lctx := ctx.lctx.mkLetDecl fvarId n type val; let fvar := mkFVar fvarId; adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ withNewFVar fvar type k /-- Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`, and restore saved data. -/ @[inline] def withNewMCtxDepth {α} (x : MetaM α) : MetaM α := do s ← get; let savedMCtx := s.mctx; modify $ fun s => { mctx := s.mctx.incDepth, .. s }; finally x (modify $ fun s => { mctx := savedMCtx, .. s }) /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ @[inline] def withMVarContext {α} (mvarId : MVarId) (x : MetaM α) : MetaM α := do mvarDecl ← getMVarDecl mvarId; localInsts ← getLocalInstances; adaptReader (fun (ctx : Context) => { lctx := mvarDecl.lctx, localInstances := mvarDecl.localInstances, .. ctx }) $ if localInsts == mvarDecl.localInstances then x else resettingSynthInstanceCache x @[inline] def withMCtx {α} (mctx : MetavarContext) (x : MetaM α) : MetaM α := do mctx' ← getMCtx; modify $ fun s => { mctx := mctx, .. s }; finally x (modify $ fun s => { mctx := mctx', .. s }) instance MetaHasEval {α} [MetaHasEval α] : MetaHasEval (MetaM α) := ⟨fun env opts x => do match x { config := { opts := opts } } { env := env } with | EStateM.Result.ok a s => do s.traceState.traces.forM $ fun m => IO.println $ format m; MetaHasEval.eval s.env opts a | EStateM.Result.error err s => do s.traceState.traces.forM $ fun m => IO.println $ format m; throw (IO.userError (toString err))⟩ @[init] private def regTraceClasses : IO Unit := registerTraceClass `Meta end Meta end Lean open Lean open Lean.Meta /-- Helper function for running `MetaM` methods in attributes -/ @[inline] def IO.runMeta {α} (x : MetaM α) (env : Environment) (cfg : Config := {}) : IO (α × Environment) := match (x { config := cfg }).run { env := env } with | EStateM.Result.ok a s => pure (a, s.env) | EStateM.Result.error ex _ => throw (IO.userError (toString ex))
d4fa9d9bce5a7ce8ae4a838000115ed7bb739b0e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/affine_space/ordered.lean
2fd08197141586c51a0ec4686b2f0d8b8bdd62ef
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
12,553
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import algebra.order.invertible import algebra.order.module import linear_algebra.affine_space.midpoint import linear_algebra.affine_space.slope import tactic.field_simp /-! # Ordered modules as affine spaces In this file we prove some theorems about `slope` and `line_map` in the case when the module `E` acting on the codomain `PE` of a function is an ordered module over its domain `k`. We also prove inequalities that can be used to link convexity of a function on an interval to monotonicity of the slope, see section docstring below for details. ## Implementation notes We do not introduce the notion of ordered affine spaces (yet?). Instead, we prove various theorems for an ordered module interpreted as an affine space. ## Tags affine space, ordered module, slope -/ open affine_map variables {k E PE : Type*} /-! ### Monotonicity of `line_map` In this section we prove that `line_map a b r` is monotone (strictly or not) in its arguments if other arguments belong to specific domains. -/ section ordered_ring variables [ordered_ring k] [ordered_add_comm_group E] [module k E] [ordered_smul k E] variables {a a' b b' : E} {r r' : k} lemma line_map_mono_left (ha : a ≤ a') (hr : r ≤ 1) : line_map a b r ≤ line_map a' b r := begin simp only [line_map_apply_module], exact add_le_add_right (smul_le_smul_of_nonneg ha (sub_nonneg.2 hr)) _ end lemma line_map_strict_mono_left (ha : a < a') (hr : r < 1) : line_map a b r < line_map a' b r := begin simp only [line_map_apply_module], exact add_lt_add_right (smul_lt_smul_of_pos ha (sub_pos.2 hr)) _ end lemma line_map_mono_right (hb : b ≤ b') (hr : 0 ≤ r) : line_map a b r ≤ line_map a b' r := begin simp only [line_map_apply_module], exact add_le_add_left (smul_le_smul_of_nonneg hb hr) _ end lemma line_map_strict_mono_right (hb : b < b') (hr : 0 < r) : line_map a b r < line_map a b' r := begin simp only [line_map_apply_module], exact add_lt_add_left (smul_lt_smul_of_pos hb hr) _ end lemma line_map_mono_endpoints (ha : a ≤ a') (hb : b ≤ b') (h₀ : 0 ≤ r) (h₁ : r ≤ 1) : line_map a b r ≤ line_map a' b' r := (line_map_mono_left ha h₁).trans (line_map_mono_right hb h₀) lemma line_map_strict_mono_endpoints (ha : a < a') (hb : b < b') (h₀ : 0 ≤ r) (h₁ : r ≤ 1) : line_map a b r < line_map a' b' r := begin rcases h₀.eq_or_lt with (rfl|h₀), { simpa }, exact (line_map_mono_left ha.le h₁).trans_lt (line_map_strict_mono_right hb h₀) end lemma line_map_lt_line_map_iff_of_lt (h : r < r') : line_map a b r < line_map a b r' ↔ a < b := begin simp only [line_map_apply_module], rw [← lt_sub_iff_add_lt, add_sub_assoc, ← sub_lt_iff_lt_add', ← sub_smul, ← sub_smul, sub_sub_sub_cancel_left, smul_lt_smul_iff_of_pos (sub_pos.2 h)], apply_instance, end lemma left_lt_line_map_iff_lt (h : 0 < r) : a < line_map a b r ↔ a < b := iff.trans (by rw line_map_apply_zero) (line_map_lt_line_map_iff_of_lt h) lemma line_map_lt_left_iff_lt (h : 0 < r) : line_map a b r < a ↔ b < a := @left_lt_line_map_iff_lt k (order_dual E) _ _ _ _ _ _ _ h lemma line_map_lt_right_iff_lt (h : r < 1) : line_map a b r < b ↔ a < b := iff.trans (by rw line_map_apply_one) (line_map_lt_line_map_iff_of_lt h) lemma right_lt_line_map_iff_lt (h : r < 1) : b < line_map a b r ↔ b < a := @line_map_lt_right_iff_lt k (order_dual E) _ _ _ _ _ _ _ h end ordered_ring section linear_ordered_ring variables [linear_ordered_ring k] [ordered_add_comm_group E] [module k E] [ordered_smul k E] [invertible (2:k)] {a a' b b' : E} {r r' : k} lemma midpoint_le_midpoint (ha : a ≤ a') (hb : b ≤ b') : midpoint k a b ≤ midpoint k a' b' := line_map_mono_endpoints ha hb (inv_of_nonneg.2 zero_le_two) $ inv_of_le_one one_le_two end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field k] [ordered_add_comm_group E] variables [module k E] [ordered_smul k E] section variables {a b : E} {r r' : k} lemma line_map_le_line_map_iff_of_lt (h : r < r') : line_map a b r ≤ line_map a b r' ↔ a ≤ b := begin simp only [line_map_apply_module], rw [← le_sub_iff_add_le, add_sub_assoc, ← sub_le_iff_le_add', ← sub_smul, ← sub_smul, sub_sub_sub_cancel_left, smul_le_smul_iff_of_pos (sub_pos.2 h)], apply_instance, end lemma left_le_line_map_iff_le (h : 0 < r) : a ≤ line_map a b r ↔ a ≤ b := iff.trans (by rw line_map_apply_zero) (line_map_le_line_map_iff_of_lt h) @[simp] lemma left_le_midpoint : a ≤ midpoint k a b ↔ a ≤ b := left_le_line_map_iff_le $ inv_pos.2 zero_lt_two lemma line_map_le_left_iff_le (h : 0 < r) : line_map a b r ≤ a ↔ b ≤ a := @left_le_line_map_iff_le k (order_dual E) _ _ _ _ _ _ _ h @[simp] lemma midpoint_le_left : midpoint k a b ≤ a ↔ b ≤ a := line_map_le_left_iff_le $ inv_pos.2 zero_lt_two lemma line_map_le_right_iff_le (h : r < 1) : line_map a b r ≤ b ↔ a ≤ b := iff.trans (by rw line_map_apply_one) (line_map_le_line_map_iff_of_lt h) @[simp] lemma midpoint_le_right : midpoint k a b ≤ b ↔ a ≤ b := line_map_le_right_iff_le $ inv_lt_one one_lt_two lemma right_le_line_map_iff_le (h : r < 1) : b ≤ line_map a b r ↔ b ≤ a := @line_map_le_right_iff_le k (order_dual E) _ _ _ _ _ _ _ h @[simp] lemma right_le_midpoint : b ≤ midpoint k a b ↔ b ≤ a := right_le_line_map_iff_le $ inv_lt_one one_lt_two end /-! ### Convexity and slope Given an interval `[a, b]` and a point `c ∈ (a, b)`, `c = line_map a b r`, there are a few ways to say that the point `(c, f c)` is above/below the segment `[(a, f a), (b, f b)]`: * compare `f c` to `line_map (f a) (f b) r`; * compare `slope f a c` to `slope `f a b`; * compare `slope f c b` to `slope f a b`; * compare `slope f a c` to `slope f c b`. In this section we prove equivalence of these four approaches. In order to make the statements more readable, we introduce local notation `c = line_map a b r`. Then we prove lemmas like ``` lemma map_le_line_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) : f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f a b := ``` For each inequality between `f c` and `line_map (f a) (f b) r` we provide 3 lemmas: * `*_left` relates it to an inequality on `slope f a c` and `slope f a b`; * `*_right` relates it to an inequality on `slope f a b` and `slope f c b`; * no-suffix version relates it to an inequality on `slope f a c` and `slope f c b`. These inequalities can by used in to restate `convex_on` in terms of monotonicity of the slope. -/ variables {f : k → E} {a b r : k} local notation `c` := line_map a b r /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is non-strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c ≤ slope f a b`. -/ lemma map_le_line_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) : f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f a b := begin rw [line_map_apply, line_map_apply, slope, slope, vsub_eq_sub, vsub_eq_sub, vsub_eq_sub, vadd_eq_add, vadd_eq_add, smul_eq_mul, add_sub_cancel, smul_sub, smul_sub, smul_sub, sub_le_iff_le_add, mul_inv_rev₀, mul_smul, mul_smul, ←smul_sub, ←smul_sub, ←smul_add, smul_smul, ← mul_inv_rev₀, smul_le_iff_of_pos (inv_pos.2 h), inv_inv₀, smul_smul, mul_inv_cancel_right₀ (right_ne_zero_of_mul h.ne'), smul_add, smul_inv_smul₀ (left_ne_zero_of_mul h.ne')], apply_instance end /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is non-strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f a b ≤ slope f a c`. -/ lemma line_map_le_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) : line_map (f a) (f b) r ≤ f c ↔ slope f a b ≤ slope f a c := @map_le_line_map_iff_slope_le_slope_left k (order_dual E) _ _ _ _ f a b r h /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c < slope f a b`. -/ lemma map_lt_line_map_iff_slope_lt_slope_left (h : 0 < r * (b - a)) : f c < line_map (f a) (f b) r ↔ slope f a c < slope f a b := lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope_left h) (map_le_line_map_iff_slope_le_slope_left h) /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f a b < slope f a c`. -/ lemma line_map_lt_map_iff_slope_lt_slope_left (h : 0 < r * (b - a)) : line_map (f a) (f b) r < f c ↔ slope f a b < slope f a c := @map_lt_line_map_iff_slope_lt_slope_left k (order_dual E) _ _ _ _ f a b r h /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is non-strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a b ≤ slope f c b`. -/ lemma map_le_line_map_iff_slope_le_slope_right (h : 0 < (1 - r) * (b - a)) : f c ≤ line_map (f a) (f b) r ↔ slope f a b ≤ slope f c b := begin rw [← line_map_apply_one_sub, ← line_map_apply_one_sub _ _ r], revert h, generalize : 1 - r = r', clear r, intro h, simp_rw [line_map_apply, slope, vsub_eq_sub, vadd_eq_add, smul_eq_mul], rw [sub_add_eq_sub_sub_swap, sub_self, zero_sub, le_smul_iff_of_pos, inv_inv₀, smul_smul, neg_mul_eq_mul_neg, neg_sub, mul_inv_cancel_right₀, le_sub, ← neg_sub (f b), smul_neg, neg_add_eq_sub], { exact right_ne_zero_of_mul h.ne' }, { simpa [mul_sub] using h } end /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is non-strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b ≤ slope f a b`. -/ lemma line_map_le_map_iff_slope_le_slope_right (h : 0 < (1 - r) * (b - a)) : line_map (f a) (f b) r ≤ f c ↔ slope f c b ≤ slope f a b := @map_le_line_map_iff_slope_le_slope_right k (order_dual E) _ _ _ _ f a b r h /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a b < slope f c b`. -/ lemma map_lt_line_map_iff_slope_lt_slope_right (h : 0 < (1 - r) * (b - a)) : f c < line_map (f a) (f b) r ↔ slope f a b < slope f c b := lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope_right h) (map_le_line_map_iff_slope_le_slope_right h) /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b < slope f a b`. -/ lemma line_map_lt_map_iff_slope_lt_slope_right (h : 0 < (1 - r) * (b - a)) : line_map (f a) (f b) r < f c ↔ slope f c b < slope f a b := @map_lt_line_map_iff_slope_lt_slope_right k (order_dual E) _ _ _ _ f a b r h /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is non-strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c ≤ slope f c b`. -/ lemma map_le_line_map_iff_slope_le_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f c b := begin rw [map_le_line_map_iff_slope_le_slope_left (mul_pos h₀ (sub_pos.2 hab)), ← line_map_slope_line_map_slope_line_map f a b r, right_le_line_map_iff_le h₁], apply_instance, apply_instance, end /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is non-strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b ≤ slope f a c`. -/ lemma line_map_le_map_iff_slope_le_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : line_map (f a) (f b) r ≤ f c ↔ slope f c b ≤ slope f a c := @map_le_line_map_iff_slope_le_slope k (order_dual E) _ _ _ _ _ _ _ _ hab h₀ h₁ /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c < slope f c b`. -/ lemma map_lt_line_map_iff_slope_lt_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : f c < line_map (f a) (f b) r ↔ slope f a c < slope f c b := lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope hab h₀ h₁) (map_le_line_map_iff_slope_le_slope hab h₀ h₁) /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b < slope f a c`. -/ lemma line_map_lt_map_iff_slope_lt_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : line_map (f a) (f b) r < f c ↔ slope f c b < slope f a c := @map_lt_line_map_iff_slope_lt_slope k (order_dual E) _ _ _ _ _ _ _ _ hab h₀ h₁ end linear_ordered_field
41f60b9ee6d267b31ac2431de0899464be4928b0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/copy.lean
77da359129d7b1e1998da2dd784976556b890faa
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,663
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import order.conditionally_complete_lattice.basic /-! # Tooling to make copies of lattice structures > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Sometimes it is useful to make a copy of a lattice structure where one replaces the data parts with provably equal definitions that have better definitional properties. -/ open order universe u variables {α : Type u} /-- A function to create a provable equal copy of a bounded order with possibly different definitional equalities. -/ def bounded_order.copy {h : has_le α} {h' : has_le α} (c : @bounded_order α h') (top : α) (eq_top : top = @bounded_order.top α _ c) (bot : α) (eq_bot : bot = @bounded_order.bot α _ c) (le_eq : ∀ (x y : α), ((@has_le.le α h) x y) ↔ x ≤ y) : @bounded_order α h := begin refine { top := top, bot := bot, .. }, all_goals { abstract { subst_vars, casesI c, simp_rw le_eq, assumption } } end /-- A function to create a provable equal copy of a lattice with possibly different definitional equalities. -/ def lattice.copy (c : lattice α) (le : α → α → Prop) (eq_le : le = @lattice.le α c) (sup : α → α → α) (eq_sup : sup = @lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @lattice.inf α c) : lattice α := begin refine { le := le, sup := sup, inf := inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a distributive lattice with possibly different definitional equalities. -/ def distrib_lattice.copy (c : distrib_lattice α) (le : α → α → Prop) (eq_le : le = @distrib_lattice.le α c) (sup : α → α → α) (eq_sup : sup = @distrib_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @distrib_lattice.inf α c) : distrib_lattice α := begin refine { le := le, sup := sup, inf := inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a complete lattice with possibly different definitional equalities. -/ def complete_lattice.copy (c : complete_lattice α) (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c) (top : α) (eq_top : top = @complete_lattice.top α c) (bot : α) (eq_bot : bot = @complete_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) : complete_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, .. lattice.copy (@complete_lattice.to_lattice α c) le eq_le sup eq_sup inf eq_inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a frame with possibly different definitional equalities. -/ def frame.copy (c : frame α) (le : α → α → Prop) (eq_le : le = @frame.le α c) (top : α) (eq_top : top = @frame.top α c) (bot : α) (eq_bot : bot = @frame.bot α c) (sup : α → α → α) (eq_sup : sup = @frame.sup α c) (inf : α → α → α) (eq_inf : inf = @frame.inf α c) (Sup : set α → α) (eq_Sup : Sup = @frame.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @frame.Inf α c) : frame α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, .. complete_lattice.copy (@frame.to_complete_lattice α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf Sup eq_Sup Inf eq_Inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a coframe with possibly different definitional equalities. -/ def coframe.copy (c : coframe α) (le : α → α → Prop) (eq_le : le = @coframe.le α c) (top : α) (eq_top : top = @coframe.top α c) (bot : α) (eq_bot : bot = @coframe.bot α c) (sup : α → α → α) (eq_sup : sup = @coframe.sup α c) (inf : α → α → α) (eq_inf : inf = @coframe.inf α c) (Sup : set α → α) (eq_Sup : Sup = @coframe.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @coframe.Inf α c) : coframe α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, .. complete_lattice.copy (@coframe.to_complete_lattice α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf Sup eq_Sup Inf eq_Inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a complete distributive lattice with possibly different definitional equalities. -/ def complete_distrib_lattice.copy (c : complete_distrib_lattice α) (le : α → α → Prop) (eq_le : le = @complete_distrib_lattice.le α c) (top : α) (eq_top : top = @complete_distrib_lattice.top α c) (bot : α) (eq_bot : bot = @complete_distrib_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_distrib_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_distrib_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_distrib_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_distrib_lattice.Inf α c) : complete_distrib_lattice α := { .. frame.copy (@complete_distrib_lattice.to_frame α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf Sup eq_Sup Inf eq_Inf, .. coframe.copy (@complete_distrib_lattice.to_coframe α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf Sup eq_Sup Inf eq_Inf} /-- A function to create a provable equal copy of a conditionally complete lattice with possibly different definitional equalities. -/ def conditionally_complete_lattice.copy (c : conditionally_complete_lattice α) (le : α → α → Prop) (eq_le : le = @conditionally_complete_lattice.le α c) (sup : α → α → α) (eq_sup : sup = @conditionally_complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @conditionally_complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @conditionally_complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @conditionally_complete_lattice.Inf α c) : conditionally_complete_lattice α := begin refine { le := le, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..}, all_goals { abstract { subst_vars, casesI c, assumption } } end
25696a8a783b62ddf85c9aa67b4b298b9e33026f
bb31430994044506fa42fd667e2d556327e18dfe
/src/measure_theory/measure/measure_space_def.lean
1f61e6e5d47b534e977b8b469fb8745e4efa5f2e
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
24,805
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 measure_theory.measure.outer_measure import order.filter.countable_Inter /-! # Measure spaces This file defines measure spaces, the almost-everywhere filter and ae_measurable functions. See `measure_theory.measure_space` for their properties and for extended documentation. Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the extended nonnegative reals that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint sets is equal to the measure of the individual sets. Every measure can be canonically extended to an outer measure, so that it assigns values to all subsets, not just the measurable subsets. On the other hand, a measure that is countably additive on measurable sets can be restricted to measurable sets to obtain a measure. In this file a measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ℝ≥0∞`. ## Implementation notes Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`. This conveniently allows us to apply the measure to sets without proving that they are measurable. We get countable subadditivity for all sets, but only countable additivity for measurable sets. See the documentation of `measure_theory.measure_space` for ways to construct measures and proving that two measure are equal. A `measure_space` is a class that is a measurable space with a canonical measure. The measure is denoted `volume`. This file does not import `measure_theory.measurable_space`, but only `measurable_space_def`. ## References * <https://en.wikipedia.org/wiki/Measure_(mathematics)> * <https://en.wikipedia.org/wiki/Almost_everywhere> ## Tags measure, almost everywhere, measure space -/ noncomputable theory open classical set filter (hiding map) function measurable_space open_locale classical topological_space big_operators filter ennreal nnreal variables {α β γ δ ι : Type*} namespace measure_theory /-- A measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. -/ structure measure (α : Type*) [measurable_space α] extends outer_measure α := (m_Union ⦃f : ℕ → set α⦄ : (∀ i, measurable_set (f i)) → pairwise (disjoint on f) → measure_of (⋃ i, f i) = ∑' i, measure_of (f i)) (trimmed : to_outer_measure.trim = to_outer_measure) /-- Measure projections for a measure space. For measurable sets this returns the measure assigned by the `measure_of` field in `measure`. But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and subadditivity for all sets. -/ instance measure.has_coe_to_fun [measurable_space α] : has_coe_to_fun (measure α) (λ _, set α → ℝ≥0∞) := ⟨λ m, m.to_outer_measure⟩ section variables [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ t : set α} namespace measure /-! ### General facts about measures -/ /-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/ def of_measurable (m : Π (s : set α), measurable_set s → ℝ≥0∞) (m0 : m ∅ measurable_set.empty = 0) (mU : ∀ {{f : ℕ → set α}} (h : ∀ i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃ i, f i) (measurable_set.Union h) = ∑' i, m (f i) (h i)) : measure α := { m_Union := λ f hf hd, show induced_outer_measure m _ m0 (Union f) = ∑' i, induced_outer_measure m _ m0 (f i), begin rw [induced_outer_measure_eq m0 mU, mU hf hd], congr, funext n, rw induced_outer_measure_eq m0 mU end, trimmed := show (induced_outer_measure m _ m0).trim = induced_outer_measure m _ m0, begin unfold outer_measure.trim, congr, funext s hs, exact induced_outer_measure_eq m0 mU hs end, ..induced_outer_measure m _ m0 } lemma of_measurable_apply {m : Π (s : set α), measurable_set s → ℝ≥0∞} {m0 : m ∅ measurable_set.empty = 0} {mU : ∀ {{f : ℕ → set α}} (h : ∀ i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃ i, f i) (measurable_set.Union h) = ∑' i, m (f i) (h i)} (s : set α) (hs : measurable_set s) : of_measurable m m0 mU s = m s hs := induced_outer_measure_eq m0 mU hs lemma to_outer_measure_injective : injective (to_outer_measure : measure α → outer_measure α) := λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h } @[ext] lemma ext (h : ∀ s, measurable_set s → μ₁ s = μ₂ s) : μ₁ = μ₂ := to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed] lemma ext_iff : μ₁ = μ₂ ↔ ∀ s, measurable_set s → μ₁ s = μ₂ s := ⟨by { rintro rfl s hs, refl }, measure.ext⟩ end measure @[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl lemma to_outer_measure_apply (s : set α) : μ.to_outer_measure s = μ s := rfl lemma measure_eq_trim (s : set α) : μ s = μ.to_outer_measure.trim s := by rw μ.trimmed; refl lemma measure_eq_infi (s : set α) : μ s = ⨅ t (st : s ⊆ t) (ht : measurable_set t), μ t := by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl /-- A variant of `measure_eq_infi` which has a single `infi`. This is useful when applying a lemma next that only works for non-empty infima, in which case you can use `nonempty_measurable_superset`. -/ lemma measure_eq_infi' (μ : measure α) (s : set α) : μ s = ⨅ t : { t // s ⊆ t ∧ measurable_set t}, μ t := by simp_rw [infi_subtype, infi_and, subtype.coe_mk, ← measure_eq_infi] lemma measure_eq_induced_outer_measure : μ s = induced_outer_measure (λ s _, μ s) measurable_set.empty μ.empty s := measure_eq_trim _ lemma to_outer_measure_eq_induced_outer_measure : μ.to_outer_measure = induced_outer_measure (λ s _, μ s) measurable_set.empty μ.empty := μ.trimmed.symm lemma measure_eq_extend (hs : measurable_set s) : μ s = extend (λ t (ht : measurable_set t), μ t) s := (extend_eq _ hs).symm @[simp] lemma measure_empty : μ ∅ = 0 := μ.empty lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty := nonempty_iff_ne_empty.2 $ λ h', h $ h'.symm ▸ measure_empty lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 := nonpos_iff_eq_zero.1 $ h₂ ▸ measure_mono h lemma measure_mono_top (h : s₁ ⊆ s₂) (h₁ : μ s₁ = ∞) : μ s₂ = ∞ := top_unique $ h₁ ▸ measure_mono h /-- For every set there exists a measurable superset of the same measure. -/ lemma exists_measurable_superset (μ : measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = μ s := by simpa only [← measure_eq_trim] using μ.to_outer_measure.exists_measurable_superset_eq_trim s /-- For every set `s` and a countable collection of measures `μ i` there exists a measurable superset `t ⊇ s` such that each measure `μ i` takes the same value on `s` and `t`. -/ lemma exists_measurable_superset_forall_eq {ι} [countable ι] (μ : ι → measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ ∀ i, μ i t = μ i s := by simpa only [← measure_eq_trim] using outer_measure.exists_measurable_superset_forall_eq_trim (λ i, (μ i).to_outer_measure) s lemma exists_measurable_superset₂ (μ ν : measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = μ s ∧ ν t = ν s := by simpa only [bool.forall_bool.trans and.comm] using exists_measurable_superset_forall_eq (λ b, cond b μ ν) s lemma exists_measurable_superset_of_null (h : μ s = 0) : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = 0 := h ▸ exists_measurable_superset μ s lemma exists_measurable_superset_iff_measure_eq_zero : (∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = 0) ↔ μ s = 0 := ⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_measurable_superset_of_null⟩ theorem measure_Union_le [countable β] (s : β → set α) : μ (⋃ i, s i) ≤ ∑' i, μ (s i) := μ.to_outer_measure.Union _ lemma measure_bUnion_le {s : set β} (hs : s.countable) (f : β → set α) : μ (⋃ b ∈ s, f b) ≤ ∑' p : s, μ (f p) := by { haveI := hs.to_subtype, rw bUnion_eq_Union, apply measure_Union_le } lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) : μ (⋃ b ∈ s, f b) ≤ ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion_le s.countable_to_set f end lemma measure_Union_fintype_le [fintype β] (f : β → set α) : μ (⋃ b, f b) ≤ ∑ p, μ (f p) := by { convert measure_bUnion_finset_le finset.univ f, simp } lemma measure_bUnion_lt_top {s : set β} {f : β → set α} (hs : s.finite) (hfin : ∀ i ∈ s, μ (f i) ≠ ∞) : μ (⋃ i ∈ s, f i) < ∞ := begin convert (measure_bUnion_finset_le hs.to_finset f).trans_lt _, { ext, rw [finite.mem_to_finset] }, apply ennreal.sum_lt_top, simpa only [finite.mem_to_finset] end lemma measure_Union_null [countable β] {s : β → set α} : (∀ i, μ (s i) = 0) → μ (⋃ i, s i) = 0 := μ.to_outer_measure.Union_null @[simp] lemma measure_Union_null_iff [countable ι] {s : ι → set α} : μ (⋃ i, s i) = 0 ↔ ∀ i, μ (s i) = 0 := μ.to_outer_measure.Union_null_iff /-- A version of `measure_Union_null_iff` for unions indexed by Props TODO: in the long run it would be better to combine this with `measure_Union_null_iff` by generalising to `Sort`. -/ @[simp] lemma measure_Union_null_iff' {ι : Prop} {s : ι → set α} : μ (⋃ i, s i) = 0 ↔ ∀ i, μ (s i) = 0 := μ.to_outer_measure.Union_null_iff' lemma measure_bUnion_null_iff {s : set ι} (hs : s.countable) {t : ι → set α} : μ (⋃ i ∈ s, t i) = 0 ↔ ∀ i ∈ s, μ (t i) = 0 := μ.to_outer_measure.bUnion_null_iff hs lemma measure_sUnion_null_iff {S : set (set α)} (hS : S.countable) : μ (⋃₀ S) = 0 ↔ ∀ s ∈ S, μ s = 0 := μ.to_outer_measure.sUnion_null_iff hS theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ := μ.to_outer_measure.union _ _ lemma measure_union_null : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 := μ.to_outer_measure.union_null @[simp] lemma measure_union_null_iff : μ (s₁ ∪ s₂) = 0 ↔ μ s₁ = 0 ∧ μ s₂ = 0:= ⟨λ h, ⟨measure_mono_null (subset_union_left _ _) h, measure_mono_null (subset_union_right _ _) h⟩, λ h, measure_union_null h.1 h.2⟩ lemma measure_union_lt_top (hs : μ s < ∞) (ht : μ t < ∞) : μ (s ∪ t) < ∞ := (measure_union_le s t).trans_lt (ennreal.add_lt_top.mpr ⟨hs, ht⟩) @[simp] lemma measure_union_lt_top_iff : μ (s ∪ t) < ∞ ↔ μ s < ∞ ∧ μ t < ∞ := begin refine ⟨λ h, ⟨_, _⟩, λ h, measure_union_lt_top h.1 h.2⟩, { exact (measure_mono (set.subset_union_left s t)).trans_lt h, }, { exact (measure_mono (set.subset_union_right s t)).trans_lt h, }, end lemma measure_union_ne_top (hs : μ s ≠ ∞) (ht : μ t ≠ ∞) : μ (s ∪ t) ≠ ∞ := (measure_union_lt_top hs.lt_top ht.lt_top).ne @[simp] lemma measure_union_eq_top_iff : μ (s ∪ t) = ∞ ↔ μ s = ∞ ∨ μ t = ∞ := not_iff_not.1 $ by simp only [← lt_top_iff_ne_top, ← ne.def, not_or_distrib, measure_union_lt_top_iff] lemma exists_measure_pos_of_not_measure_Union_null [countable β] {s : β → set α} (hs : μ (⋃ n, s n) ≠ 0) : ∃ n, 0 < μ (s n) := begin contrapose! hs, exact measure_Union_null (λ n, nonpos_iff_eq_zero.1 (hs n)) end lemma measure_inter_lt_top_of_left_ne_top (hs_finite : μ s ≠ ∞) : μ (s ∩ t) < ∞ := (measure_mono (set.inter_subset_left s t)).trans_lt hs_finite.lt_top lemma measure_inter_lt_top_of_right_ne_top (ht_finite : μ t ≠ ∞) : μ (s ∩ t) < ∞ := inter_comm t s ▸ measure_inter_lt_top_of_left_ne_top ht_finite lemma measure_inter_null_of_null_right (S : set α) {T : set α} (h : μ T = 0) : μ (S ∩ T) = 0 := measure_mono_null (inter_subset_right S T) h lemma measure_inter_null_of_null_left {S : set α} (T : set α) (h : μ S = 0) : μ (S ∩ T) = 0 := measure_mono_null (inter_subset_left S T) h /-! ### The almost everywhere filter -/ /-- The “almost everywhere” filter of co-null sets. -/ def measure.ae {α} {m : measurable_space α} (μ : measure α) : filter α := { sets := {s | μ sᶜ = 0}, univ_sets := by simp, inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq]; exact measure_union_null hs ht, sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs } notation `∀ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.eventually P (measure.ae μ)) := r notation `∃ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.frequently P (measure.ae μ)) := r notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[measure.ae μ] g notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[measure.ae μ] g lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl lemma compl_mem_ae_iff {s : set α} : sᶜ ∈ μ.ae ↔ μ s = 0 := by simp only [mem_ae_iff, compl_compl] lemma frequently_ae_iff {p : α → Prop} : (∃ᵐ a ∂μ, p a) ↔ μ {a | p a} ≠ 0 := not_congr compl_mem_ae_iff lemma frequently_ae_mem_iff {s : set α} : (∃ᵐ a ∂μ, a ∈ s) ↔ μ s ≠ 0 := not_congr compl_mem_ae_iff lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s := compl_mem_ae_iff.symm lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀ a, p a) → ∀ᵐ a ∂ μ, p a := eventually_of_forall --instance ae_is_measurably_generated : is_measurably_generated μ.ae := --⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_measurable_superset_of_null hs in -- ⟨tᶜ, compl_mem_ae_iff.2 htμ, htm.compl, compl_subset_comm.1 hst⟩⟩ instance : countable_Inter_filter μ.ae := ⟨begin intros S hSc hS, rw [mem_ae_iff, compl_sInter, sUnion_image], exact (measure_bUnion_null_iff hSc).2 hS end⟩ lemma ae_all_iff {ι : Sort*} [countable ι] {p : α → ι → Prop} : (∀ᵐ a ∂ μ, ∀ i, p a i) ↔ ∀ i, ∀ᵐ a ∂ μ, p a i := eventually_countable_forall lemma ae_ball_iff {S : set ι} (hS : S.countable) {p : Π (x : α) (i ∈ S), Prop} : (∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› := eventually_countable_ball hS lemma ae_eq_refl (f : α → δ) : f =ᵐ[μ] f := eventually_eq.rfl lemma ae_eq_symm {f g : α → δ} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f := h.symm lemma ae_eq_trans {f g h: α → δ} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) : f =ᵐ[μ] h := h₁.trans h₂ lemma ae_le_of_ae_lt {f g : α → ℝ≥0∞} (h : ∀ᵐ x ∂μ, f x < g x) : f ≤ᵐ[μ] g := begin rw [filter.eventually_le, ae_iff], rw ae_iff at h, refine measure_mono_null (λ x hx, _) h, exact not_lt.2 (le_of_lt (not_le.1 hx)), end @[simp] lemma ae_eq_empty : s =ᵐ[μ] (∅ : set α) ↔ μ s = 0 := eventually_eq_empty.trans $ by simp only [ae_iff, not_not, set_of_mem_eq] @[simp] lemma ae_eq_univ : s =ᵐ[μ] (univ : set α) ↔ μ sᶜ = 0 := eventually_eq_univ lemma ae_le_set : s ≤ᵐ[μ] t ↔ μ (s \ t) = 0 := calc s ≤ᵐ[μ] t ↔ ∀ᵐ x ∂μ, x ∈ s → x ∈ t : iff.rfl ... ↔ μ (s \ t) = 0 : by simp [ae_iff]; refl lemma ae_le_set_inter {s' t' : set α} (h : s ≤ᵐ[μ] t) (h' : s' ≤ᵐ[μ] t') : (s ∩ s' : set α) ≤ᵐ[μ] (t ∩ t' : set α) := h.inter h' lemma ae_le_set_union {s' t' : set α} (h : s ≤ᵐ[μ] t) (h' : s' ≤ᵐ[μ] t') : (s ∪ s' : set α) ≤ᵐ[μ] (t ∪ t' : set α) := h.union h' lemma union_ae_eq_right : (s ∪ t : set α) =ᵐ[μ] t ↔ μ (s \ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, union_diff_right, diff_eq_empty.2 (set.subset_union_right _ _)] lemma diff_ae_eq_self : (s \ t : set α) =ᵐ[μ] s ↔ μ (s ∩ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, diff_diff_right, diff_diff, diff_eq_empty.2 (set.subset_union_right _ _)] lemma diff_null_ae_eq_self (ht : μ t = 0) : (s \ t : set α) =ᵐ[μ] s := diff_ae_eq_self.mpr (measure_mono_null (inter_subset_right _ _) ht) lemma ae_eq_set {s t : set α} : s =ᵐ[μ] t ↔ μ (s \ t) = 0 ∧ μ (t \ s) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set] @[simp] lemma measure_symm_diff_eq_zero_iff {s t : set α} : μ (s ∆ t) = 0 ↔ s =ᵐ[μ] t := by simp [ae_eq_set, symm_diff_def] @[simp] lemma ae_eq_set_compl_compl {s t : set α} : sᶜ =ᵐ[μ] tᶜ ↔ s =ᵐ[μ] t := by simp only [← measure_symm_diff_eq_zero_iff, compl_symm_diff_compl] lemma ae_eq_set_compl {s t : set α} : sᶜ =ᵐ[μ] t ↔ s =ᵐ[μ] tᶜ := by rw [← ae_eq_set_compl_compl, compl_compl] lemma ae_eq_set_inter {s' t' : set α} (h : s =ᵐ[μ] t) (h' : s' =ᵐ[μ] t') : (s ∩ s' : set α) =ᵐ[μ] (t ∩ t' : set α) := h.inter h' lemma ae_eq_set_union {s' t' : set α} (h : s =ᵐ[μ] t) (h' : s' =ᵐ[μ] t') : (s ∪ s' : set α) =ᵐ[μ] (t ∪ t' : set α) := h.union h' lemma union_ae_eq_univ_of_ae_eq_univ_left (h : s =ᵐ[μ] univ) : (s ∪ t : set α) =ᵐ[μ] univ := by { convert ae_eq_set_union h (ae_eq_refl t), rw univ_union, } lemma union_ae_eq_univ_of_ae_eq_univ_right (h : t =ᵐ[μ] univ) : (s ∪ t : set α) =ᵐ[μ] univ := by { convert ae_eq_set_union (ae_eq_refl s) h, rw union_univ, } lemma union_ae_eq_right_of_ae_eq_empty (h : s =ᵐ[μ] (∅ : set α)) : (s ∪ t : set α) =ᵐ[μ] t := by { convert ae_eq_set_union h (ae_eq_refl t), rw empty_union, } lemma union_ae_eq_left_of_ae_eq_empty (h : t =ᵐ[μ] (∅ : set α)) : (s ∪ t : set α) =ᵐ[μ] s := by { convert ae_eq_set_union (ae_eq_refl s) h, rw union_empty, } lemma inter_ae_eq_right_of_ae_eq_univ (h : s =ᵐ[μ] univ) : (s ∩ t : set α) =ᵐ[μ] t := by { convert ae_eq_set_inter h (ae_eq_refl t), rw univ_inter, } lemma inter_ae_eq_left_of_ae_eq_univ (h : t =ᵐ[μ] univ) : (s ∩ t : set α) =ᵐ[μ] s := by { convert ae_eq_set_inter (ae_eq_refl s) h, rw inter_univ, } lemma inter_ae_eq_empty_of_ae_eq_empty_left (h : s =ᵐ[μ] (∅ : set α)) : (s ∩ t : set α) =ᵐ[μ] (∅ : set α) := by { convert ae_eq_set_inter h (ae_eq_refl t), rw empty_inter, } lemma inter_ae_eq_empty_of_ae_eq_empty_right (h : t =ᵐ[μ] (∅ : set α)) : (s ∩ t : set α) =ᵐ[μ] (∅ : set α) := by { convert ae_eq_set_inter (ae_eq_refl s) h, rw inter_empty, } @[to_additive] lemma _root_.set.mul_indicator_ae_eq_one {M : Type*} [has_one M] {f : α → M} {s : set α} (h : s.mul_indicator f =ᵐ[μ] 1) : μ (s ∩ function.mul_support f) = 0 := by simpa [filter.eventually_eq, ae_iff] using h /-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/ @[mono] lemma measure_mono_ae (H : s ≤ᵐ[μ] t) : μ s ≤ μ t := calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t ... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm] ... ≤ μ t + μ (s \ t) : measure_union_le _ _ ... = μ t : by rw [ae_le_set.1 H, add_zero] alias measure_mono_ae ← _root_.filter.eventually_le.measure_le /-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/ lemma measure_congr (H : s =ᵐ[μ] t) : μ s = μ t := le_antisymm H.le.measure_le H.symm.le.measure_le alias measure_congr ← _root_.filter.eventually_eq.measure_eq lemma measure_mono_null_ae (H : s ≤ᵐ[μ] t) (ht : μ t = 0) : μ s = 0 := nonpos_iff_eq_zero.1 $ ht ▸ H.measure_le /-- A measurable set `t ⊇ s` such that `μ t = μ s`. It even satisfies `μ (t ∩ u) = μ (s ∩ u)` for any measurable set `u` if `μ s ≠ ∞`, see `measure_to_measurable_inter`. (This property holds without the assumption `μ s ≠ ∞` when the space is sigma-finite, see `measure_to_measurable_inter_of_sigma_finite`). If `s` is a null measurable set, then we also have `t =ᵐ[μ] s`, see `null_measurable_set.to_measurable_ae_eq`. This notion is sometimes called a "measurable hull" in the literature. -/ @[irreducible] def to_measurable (μ : measure α) (s : set α) : set α := if h : ∃ t ⊇ s, measurable_set t ∧ t =ᵐ[μ] s then h.some else if h' : ∃ t ⊇ s, measurable_set t ∧ (∀ u, measurable_set u → μ (t ∩ u) = μ (s ∩ u)) then h'.some else (exists_measurable_superset μ s).some lemma subset_to_measurable (μ : measure α) (s : set α) : s ⊆ to_measurable μ s := begin rw to_measurable, split_ifs with hs h's, exacts [hs.some_spec.fst, h's.some_spec.fst, (exists_measurable_superset μ s).some_spec.1] end lemma ae_le_to_measurable : s ≤ᵐ[μ] to_measurable μ s := (subset_to_measurable _ _).eventually_le @[simp] lemma measurable_set_to_measurable (μ : measure α) (s : set α) : measurable_set (to_measurable μ s) := begin rw to_measurable, split_ifs with hs h's, exacts [hs.some_spec.snd.1, h's.some_spec.snd.1, (exists_measurable_superset μ s).some_spec.2.1] end @[simp] lemma measure_to_measurable (s : set α) : μ (to_measurable μ s) = μ s := begin rw to_measurable, split_ifs with hs h's, { exact measure_congr hs.some_spec.snd.2 }, { simpa only [inter_univ] using h's.some_spec.snd.2 univ measurable_set.univ }, { exact (exists_measurable_superset μ s).some_spec.2.2 } end /-- A measure space is a measurable space equipped with a measure, referred to as `volume`. -/ class measure_space (α : Type*) extends measurable_space α := (volume : measure α) export measure_space (volume) /-- `volume` is the canonical measure on `α`. -/ add_decl_doc volume section measure_space notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P (measure_theory.measure.ae measure_theory.measure_space.volume)) := r notation `∃ᵐ` binders `, ` r:(scoped P, filter.frequently P (measure_theory.measure.ae measure_theory.measure_space.volume)) := r /-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/ meta def volume_tac : tactic unit := `[exact measure_theory.measure_space.volume] end measure_space end end measure_theory section open measure_theory /-! # Almost everywhere measurable functions A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. We define this property, called `ae_measurable f μ`. It's properties are discussed in `measure_theory.measure_space`. -/ variables {m : measurable_space α} [measurable_space β] {f g : α → β} {μ ν : measure α} /-- A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. -/ def ae_measurable {m : measurable_space α} (f : α → β) (μ : measure α . measure_theory.volume_tac) : Prop := ∃ g : α → β, measurable g ∧ f =ᵐ[μ] g lemma measurable.ae_measurable (h : measurable f) : ae_measurable f μ := ⟨f, h, ae_eq_refl f⟩ namespace ae_measurable /-- Given an almost everywhere measurable function `f`, associate to it a measurable function that coincides with it almost everywhere. `f` is explicit in the definition to make sure that it shows in pretty-printing. -/ def mk (f : α → β) (h : ae_measurable f μ) : α → β := classical.some h lemma measurable_mk (h : ae_measurable f μ) : measurable (h.mk f) := (classical.some_spec h).1 lemma ae_eq_mk (h : ae_measurable f μ) : f =ᵐ[μ] (h.mk f) := (classical.some_spec h).2 lemma congr (hf : ae_measurable f μ) (h : f =ᵐ[μ] g) : ae_measurable g μ := ⟨hf.mk f, hf.measurable_mk, h.symm.trans hf.ae_eq_mk⟩ end ae_measurable lemma ae_measurable_congr (h : f =ᵐ[μ] g) : ae_measurable f μ ↔ ae_measurable g μ := ⟨λ hf, ae_measurable.congr hf h, λ hg, ae_measurable.congr hg h.symm⟩ @[simp] lemma ae_measurable_const {b : β} : ae_measurable (λ a : α, b) μ := measurable_const.ae_measurable lemma ae_measurable_id : ae_measurable id μ := measurable_id.ae_measurable lemma ae_measurable_id' : ae_measurable (λ x, x) μ := measurable_id.ae_measurable lemma measurable.comp_ae_measurable [measurable_space δ] {f : α → δ} {g : δ → β} (hg : measurable g) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ := ⟨g ∘ hf.mk f, hg.comp hf.measurable_mk, eventually_eq.fun_comp hf.ae_eq_mk _⟩ end
88320e6ec332c9605543b7c895e8cf63794cddda
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/field_division_auto.lean
73b2ed3533c05d9f745905c70bdb5e7a35ef815b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
11,888
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.ring_division import Mathlib.data.polynomial.derivative import Mathlib.algebra.gcd_monoid import Mathlib.PostPort universes u y v u_1 namespace Mathlib /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ namespace polynomial protected instance normalization_monoid {R : Type u} [integral_domain R] [normalization_monoid R] : normalization_monoid (polynomial R) := normalization_monoid.mk (fun (p : polynomial R) => units.mk (coe_fn C ↑(norm_unit (leading_coeff p))) (coe_fn C ↑(norm_unit (leading_coeff p)⁻¹)) sorry sorry) sorry sorry sorry @[simp] theorem coe_norm_unit {R : Type u} [integral_domain R] [normalization_monoid R] {p : polynomial R} : ↑(norm_unit p) = coe_fn C ↑(norm_unit (leading_coeff p)) := sorry theorem leading_coeff_normalize {R : Type u} [integral_domain R] [normalization_monoid R] (p : polynomial R) : leading_coeff (coe_fn normalize p) = coe_fn normalize (leading_coeff p) := sorry theorem is_unit_iff_degree_eq_zero {R : Type u} [field R] {p : polynomial R} : is_unit p ↔ degree p = 0 := sorry theorem degree_pos_of_ne_zero_of_nonunit {R : Type u} [field R] {p : polynomial R} (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := sorry theorem monic_mul_leading_coeff_inv {R : Type u} [field R] {p : polynomial R} (h : p ≠ 0) : monic (p * coe_fn C (leading_coeff p⁻¹)) := sorry theorem degree_mul_leading_coeff_inv {R : Type u} [field R] {q : polynomial R} (p : polynomial R) (h : q ≠ 0) : degree (p * coe_fn C (leading_coeff q⁻¹)) = degree p := sorry theorem irreducible_of_monic {R : Type u} [field R] {p : polynomial R} (hp1 : monic p) (hp2 : p ≠ 1) : irreducible p ↔ ∀ (f g : polynomial R), monic f → monic g → f * g = p → f = 1 ∨ g = 1 := sorry /-- Division of polynomials. See polynomial.div_by_monic for more details.-/ def div {R : Type u} [field R] (p : polynomial R) (q : polynomial R) : polynomial R := coe_fn C (leading_coeff q⁻¹) * (p /ₘ (q * coe_fn C (leading_coeff q⁻¹))) /-- Remainder of polynomial division, see the lemma `quotient_mul_add_remainder_eq_aux`. See polynomial.mod_by_monic for more details. -/ def mod {R : Type u} [field R] (p : polynomial R) (q : polynomial R) : polynomial R := p %ₘ (q * coe_fn C (leading_coeff q⁻¹)) protected instance has_div {R : Type u} [field R] : Div (polynomial R) := { div := div } protected instance has_mod {R : Type u} [field R] : Mod (polynomial R) := { mod := mod } theorem div_def {R : Type u} [field R] {p : polynomial R} {q : polynomial R} : p / q = coe_fn C (leading_coeff q⁻¹) * (p /ₘ (q * coe_fn C (leading_coeff q⁻¹))) := rfl theorem mod_def {R : Type u} [field R] {p : polynomial R} {q : polynomial R} : p % q = p %ₘ (q * coe_fn C (leading_coeff q⁻¹)) := rfl theorem mod_by_monic_eq_mod {R : Type u} [field R] {q : polynomial R} (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := sorry theorem div_by_monic_eq_div {R : Type u} [field R] {q : polynomial R} (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := sorry theorem mod_X_sub_C_eq_C_eval {R : Type u} [field R] (p : polynomial R) (a : R) : p % (X - coe_fn C a) = coe_fn C (eval a p) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval p a theorem mul_div_eq_iff_is_root {R : Type u} {a : R} [field R] {p : polynomial R} : (X - coe_fn C a) * (p / (X - coe_fn C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root protected instance euclidean_domain {R : Type u} [field R] : euclidean_domain (polynomial R) := euclidean_domain.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry sorry Div.div sorry Mod.mod quotient_mul_add_remainder_eq_aux (fun (p q : polynomial R) => degree p < degree q) sorry sorry sorry theorem mod_eq_self_iff {R : Type u} [field R] {p : polynomial R} {q : polynomial R} (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := sorry theorem div_eq_zero_iff {R : Type u} [field R] {p : polynomial R} {q : polynomial R} (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := sorry theorem degree_add_div {R : Type u} [field R] {p : polynomial R} {q : polynomial R} (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := sorry theorem degree_div_le {R : Type u} [field R] (p : polynomial R) (q : polynomial R) : degree (p / q) ≤ degree p := sorry theorem degree_div_lt {R : Type u} [field R] {p : polynomial R} {q : polynomial R} (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := sorry @[simp] theorem degree_map {R : Type u} {k : Type y} [field R] [field k] (p : polynomial R) (f : R →+* k) : degree (map f p) = degree p := degree_map_eq_of_injective (ring_hom.injective f) p @[simp] theorem nat_degree_map {R : Type u} {k : Type y} [field R] {p : polynomial R} [field k] (f : R →+* k) : nat_degree (map f p) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map p f) @[simp] theorem leading_coeff_map {R : Type u} {k : Type y} [field R] {p : polynomial R} [field k] (f : R →+* k) : leading_coeff (map f p) = coe_fn f (leading_coeff p) := sorry theorem monic_map_iff {R : Type u} {k : Type y} [field R] [field k] {f : R →+* k} {p : polynomial R} : monic (map f p) ↔ monic p := sorry theorem is_unit_map {R : Type u} {k : Type y} [field R] {p : polynomial R} [field k] (f : R →+* k) : is_unit (map f p) ↔ is_unit p := sorry theorem map_div {R : Type u} {k : Type y} [field R] {p : polynomial R} {q : polynomial R} [field k] (f : R →+* k) : map f (p / q) = map f p / map f q := sorry theorem map_mod {R : Type u} {k : Type y} [field R] {p : polynomial R} {q : polynomial R} [field k] (f : R →+* k) : map f (p % q) = map f p % map f q := sorry theorem gcd_map {R : Type u} {k : Type y} [field R] {p : polynomial R} {q : polynomial R} [field k] (f : R →+* k) : euclidean_domain.gcd (map f p) (map f q) = map f (euclidean_domain.gcd p q) := sorry theorem eval₂_gcd_eq_zero {R : Type u} {k : Type y} [field R] [comm_semiring k] {ϕ : R →+* k} {f : polynomial R} {g : polynomial R} {α : k} (hf : eval₂ ϕ α f = 0) (hg : eval₂ ϕ α g = 0) : eval₂ ϕ α (euclidean_domain.gcd f g) = 0 := sorry theorem eval_gcd_eq_zero {R : Type u} [field R] {f : polynomial R} {g : polynomial R} {α : R} (hf : eval α f = 0) (hg : eval α g = 0) : eval α (euclidean_domain.gcd f g) = 0 := eval₂_gcd_eq_zero hf hg theorem root_left_of_root_gcd {R : Type u} {k : Type y} [field R] [comm_semiring k] {ϕ : R →+* k} {f : polynomial R} {g : polynomial R} {α : k} (hα : eval₂ ϕ α (euclidean_domain.gcd f g) = 0) : eval₂ ϕ α f = 0 := sorry theorem root_right_of_root_gcd {R : Type u} {k : Type y} [field R] [comm_semiring k] {ϕ : R →+* k} {f : polynomial R} {g : polynomial R} {α : k} (hα : eval₂ ϕ α (euclidean_domain.gcd f g) = 0) : eval₂ ϕ α g = 0 := sorry theorem root_gcd_iff_root_left_right {R : Type u} {k : Type y} [field R] [comm_semiring k] {ϕ : R →+* k} {f : polynomial R} {g : polynomial R} {α : k} : eval₂ ϕ α (euclidean_domain.gcd f g) = 0 ↔ eval₂ ϕ α f = 0 ∧ eval₂ ϕ α g = 0 := sorry theorem is_root_gcd_iff_is_root_left_right {R : Type u} [field R] {f : polynomial R} {g : polynomial R} {α : R} : is_root (euclidean_domain.gcd f g) α ↔ is_root f α ∧ is_root g α := root_gcd_iff_root_left_right theorem is_coprime_map {R : Type u} {k : Type y} [field R] {p : polynomial R} {q : polynomial R} [field k] (f : R →+* k) : is_coprime (map f p) (map f q) ↔ is_coprime p q := sorry @[simp] theorem map_eq_zero {R : Type u} {S : Type v} [field R] {p : polynomial R} [semiring S] [nontrivial S] (f : R →+* S) : map f p = 0 ↔ p = 0 := sorry theorem map_ne_zero {R : Type u} {S : Type v} [field R] {p : polynomial R} [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : map f p ≠ 0 := mt (iff.mp (map_eq_zero f)) hp theorem mem_roots_map {R : Type u} {k : Type y} [field R] {p : polynomial R} [field k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ roots (map f p) ↔ eval₂ f x p = 0 := sorry theorem exists_root_of_degree_eq_one {R : Type u} [field R] {p : polynomial R} (h : degree p = 1) : ∃ (x : R), is_root p x := sorry theorem coeff_inv_units {R : Type u} [field R] (u : units (polynomial R)) (n : ℕ) : coeff (↑u) n⁻¹ = coeff (↑(u⁻¹)) n := sorry theorem monic_normalize {R : Type u} [field R] {p : polynomial R} (hp0 : p ≠ 0) : monic (coe_fn normalize p) := sorry theorem coe_norm_unit_of_ne_zero {R : Type u} [field R] {p : polynomial R} (hp : p ≠ 0) : ↑(norm_unit p) = coe_fn C (leading_coeff p⁻¹) := sorry theorem normalize_monic {R : Type u} [field R] {p : polynomial R} (h : monic p) : coe_fn normalize p = p := sorry theorem map_dvd_map' {R : Type u} {k : Type y} [field R] [field k] (f : R →+* k) {x : polynomial R} {y : polynomial R} : map f x ∣ map f y ↔ x ∣ y := sorry theorem degree_normalize {R : Type u} [field R] {p : polynomial R} : degree (coe_fn normalize p) = degree p := sorry theorem prime_of_degree_eq_one {R : Type u} [field R] {p : polynomial R} (hp1 : degree p = 1) : prime p := sorry theorem irreducible_of_degree_eq_one {R : Type u} [field R] {p : polynomial R} (hp1 : degree p = 1) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one hp1) theorem not_irreducible_C {R : Type u} [field R] (x : R) : ¬irreducible (coe_fn C x) := sorry theorem degree_pos_of_irreducible {R : Type u} [field R] {p : polynomial R} (hp : irreducible p) : 0 < degree p := lt_of_not_ge fun (hp0 : 0 ≥ degree p) => (fun (this : p = coe_fn C (coeff p 0)) => not_irreducible_C (coeff p 0) (this ▸ hp)) (eq_C_of_degree_le_zero hp0) theorem pairwise_coprime_X_sub {α : Type u} [field α] {I : Type v} {s : I → α} (H : function.injective s) : pairwise (is_coprime on fun (i : I) => X - coe_fn C (s i)) := sorry /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ theorem is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type u_1} [field K] (f : polynomial K) (a : K) (hf' : eval a (coe_fn derivative f) ≠ 0) : is_coprime (X - coe_fn C a) (f /ₘ (X - coe_fn C a)) := sorry theorem prod_multiset_root_eq_finset_root {R : Type u} [field R] {p : polynomial R} (hzero : p ≠ 0) : multiset.prod (multiset.map (fun (a : R) => X - coe_fn C a) (roots p)) = finset.prod (multiset.to_finset (roots p)) fun (a : R) => (fun (a : R) => (X - coe_fn C a) ^ root_multiplicity a p) a := sorry /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ theorem prod_multiset_X_sub_C_dvd {R : Type u} [field R] (p : polynomial R) : multiset.prod (multiset.map (fun (a : R) => X - coe_fn C a) (roots p)) ∣ p := sorry theorem roots_C_mul {R : Type u} [field R] (p : polynomial R) {a : R} (hzero : a ≠ 0) : roots (coe_fn C a * p) = roots p := sorry theorem roots_normalize {R : Type u} [field R] {p : polynomial R} : roots (coe_fn normalize p) = roots p := sorry end Mathlib
d2219c25c5b4ee446756eaee832a125813034227
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/uniform_space/compare_reals.lean
cab27db711aa95610ec18691fdef2a0f259348b7
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
4,839
lean
/- Copyright (c) 2019 Patrick MAssot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.absolute_value import topology.instances.real import topology.instances.rat import topology.uniform_space.completion /-! # Comparison of Cauchy reals and Bourbaki reals In `data.real.basic` real numbers are defined using the so called Cauchy construction (although it is due to Georg Cantor). More precisely, this construction applies to commutative rings equipped with an absolute value with values in a linear ordered field. On the other hand, in the `uniform_space` folder, we construct completions of general uniform spaces, which allows to construct the Bourbaki real numbers. In this file we build uniformly continuous bijections from Cauchy reals to Bourbaki reals and back. This is a cross sanity check of both constructions. Of course those two constructions are variations on the completion idea, simply with different level of generality. Comparing with Dedekind cuts or quasi-morphisms would be of a completely different nature. Note that `metric_space/cau_seq_filter` also relates the notions of Cauchy sequences in metric spaces and Cauchy filters in general uniform spaces, and `metric_space/completion` makes sure the completion (as a uniform space) of a metric space is a metric space. Historical note: mathlib used to define real numbers in an intermediate way, using completion of uniform spaces but extending multiplication in an ad-hoc way. TODO: * Upgrade this isomorphism to a topological ring isomorphism. * Do the same comparison for p-adic numbers ## Implementation notes The heavy work is done in `topology/uniform_space/abstract_completion` which provides an abstract caracterization of completions of uniform spaces, and isomorphisms between them. The only work left here is to prove the uniform space structure coming from the absolute value on ℚ (with values in ℚ, not referring to ℝ) coincides with the one coming from the metric space structure (which of course does use ℝ). ## References * [N. Bourbaki, *Topologie générale*][bourbaki1966] ## Tags real numbers, completion, uniform spaces -/ open set function filter cau_seq uniform_space /-- The metric space uniform structure on ℚ (which presupposes the existence of real numbers) agrees with the one coming directly from (abs : ℚ → ℚ). -/ lemma rat.uniform_space_eq : is_absolute_value.uniform_space (abs : ℚ → ℚ) = pseudo_metric_space.to_uniform_space := begin ext s, erw [metric.mem_uniformity_dist, is_absolute_value.mem_uniformity], split ; rintro ⟨ε, ε_pos, h⟩, { use [ε, by exact_mod_cast ε_pos], intros a b hab, apply h, rw [rat.dist_eq, abs_sub_comm] at hab, exact_mod_cast hab }, { obtain ⟨ε', h', h''⟩ : ∃ ε' : ℚ, 0 < ε' ∧ (ε' : ℝ) < ε, from exists_pos_rat_lt ε_pos, use [ε', h'], intros a b hab, apply h, rw [rat.dist_eq, abs_sub_comm], refine lt_trans _ h'', exact_mod_cast hab } end /-- Cauchy reals packaged as a completion of ℚ using the absolute value route. -/ noncomputable def rational_cau_seq_pkg : @abstract_completion ℚ $ is_absolute_value.uniform_space (abs : ℚ → ℚ) := { space := ℝ, coe := (coe : ℚ → ℝ), uniform_struct := by apply_instance, complete := by apply_instance, separation := by apply_instance, uniform_inducing := by { rw rat.uniform_space_eq, exact rat.uniform_embedding_coe_real.to_uniform_inducing }, dense := rat.dense_embedding_coe_real.dense } namespace compare_reals /-- Type wrapper around ℚ to make sure the absolute value uniform space instance is picked up instead of the metric space one. We proved in rat.uniform_space_eq that they are equal, but they are not definitionaly equal, so it would confuse the type class system (and probably also human readers). -/ @[derive comm_ring, derive inhabited] def Q := ℚ instance : uniform_space Q := is_absolute_value.uniform_space (abs : ℚ → ℚ) /-- Real numbers constructed as in Bourbaki. -/ @[derive inhabited] def Bourbakiℝ : Type := completion Q instance bourbaki.uniform_space: uniform_space Bourbakiℝ := completion.uniform_space Q /-- Bourbaki reals packaged as a completion of Q using the general theory. -/ def Bourbaki_pkg : abstract_completion Q := completion.cpkg /-- The equivalence between Bourbaki and Cauchy reals-/ noncomputable def compare_equiv : Bourbakiℝ ≃ ℝ := Bourbaki_pkg.compare_equiv rational_cau_seq_pkg lemma compare_uc : uniform_continuous (compare_equiv) := Bourbaki_pkg.uniform_continuous_compare_equiv _ lemma compare_uc_symm : uniform_continuous (compare_equiv).symm := Bourbaki_pkg.uniform_continuous_compare_equiv_symm _ end compare_reals
e72ce5dae28f12c0155bf03a4cd84e6db74ed32c
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/inner_product_space/basic.lean
cdb1c9c6d4b7996351442879e79f2d94a594ebc2
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
82,049
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis -/ import algebra.direct_sum.module import analysis.complex.basic import analysis.normed_space.bounded_linear_maps import linear_algebra.bilinear_form import linear_algebra.sesquilinear_form /-! # Inner product space This file defines inner product spaces and proves the basic properties. We do not formally define Hilbert spaces, but they can be obtained using the pair of assumptions `[inner_product_space E] [complete_space E]`. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. This file proves general results on inner product spaces. For the specific construction of an inner product structure on `n → 𝕜` for `𝕜 = ℝ` or `ℂ`, see `euclidean_space` in `analysis.inner_product_space.pi_L2`. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that the inner product is continuous, `continuous_inner`. - We define `orthonormal`, a predicate on a function `v : ι → E`, and prove the existence of a maximal orthonormal set, `exists_maximal_orthonormal`. Bessel's inequality, `orthonormal.tsum_inner_products_le`, states that given an orthonormal set `v` and a vector `x`, the sum of the norm-squares of the inner products `⟪v i, x⟫` is no more than the norm-square of `x`. For the existence of orthonormal bases, Hilbert bases, etc., see the file `analysis.inner_product_space.projection`. - The `orthogonal_complement` of a submodule `K` is defined, and basic API established. Some of the more subtle results about the orthogonal complement are delayed to `analysis.inner_product_space.projection`. ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the real and complex inner product. The orthogonal complement of a submodule `K` is denoted by `Kᗮ`. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## Tags inner product space, Hilbert space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators classical topological_space complex_conjugate variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) attribute [nolint dangerous_instance] inner_product_space.to_normed_group -- note [is_R_or_C instance] /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [module 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [module 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `absK` := @is_R_or_C.abs 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := star_ring_aut /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp [inner_conj_sym] lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_equiv.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_equiv.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_equiv.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_equiv.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_equiv.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw [←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- **Cauchy–Schwarz inequality**. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul_eq_neg_mul_symm, add_monoid_hom.map_add, mul_re, conj_im, add_monoid_hom.map_sub, mul_neg_eq_neg_mul_symm, conj_re, neg_neg] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, ring_equiv.map_div, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_mul_norm (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw [norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_mul_norm], ring, }, rw H, conv begin to_lhs, congr, rw [inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { intro H, change sqrt (re ⟪x, x⟫) = 0 at H, rw [sqrt_eq_zero inner_self_nonneg] at H, apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp, rw ext_iff, exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ }, { rintro rfl, change sqrt (re ⟪0, 0⟫) = 0, simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] } end, triangle := assume x y, begin have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re], have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥), { simp [←inner_self_eq_norm_mul_norm, inner_add_add_self, add_mul, mul_add, mul_comm], linarith }, exact nonneg_le_nonneg_of_sq_le_sq (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] } local attribute [instance] to_normed_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [module 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sq_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := has_abs.abs local notation `absK` := @is_R_or_C.abs 𝕜 _ local postfix `†`:90 := star_ring_aut export inner_product_space (norm_sq_eq_inner) section basic_properties @[simp] lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := @inner_conj_sym ℝ _ _ _ x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ @[simp] lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by { rw [←inner_conj_sym, inner_add_left, ring_equiv.map_add], simp only [inner_conj_sym] } lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_equiv.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. -/ @[simps] def sesq_form_of_inner : sesq_form 𝕜 E (conj_to_ring_equiv 𝕜) := { sesq := λ x y, ⟪y, x⟫, -- Note that sesquilinear forms are linear in the first argument sesq_add_left := λ x y z, inner_add_right, sesq_add_right := λ x y z, inner_add_left, sesq_smul_left := λ r x y, inner_smul_right, sesq_smul_right := λ r x y, inner_smul_left } /-- The real inner product as a bilinear form. -/ @[simps] def bilin_form_of_real_inner : bilin_form ℝ F := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := sesq_form.sum_right (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := sesq_form.sum_left (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the left, `finsupp` version. -/ lemma finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪l.sum (λ (i : ι) (a : 𝕜), a • v i), x⟫ = l.sum (λ (i : ι) (a : 𝕜), (conj a) • ⟪v i, x⟫) := by { convert sum_inner l.support (λ a, l a • v a) x, simp [inner_smul_left, finsupp.sum] } /-- An inner product with a sum on the right, `finsupp` version. -/ lemma finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪x, l.sum (λ (i : ι) (a : 𝕜), a • v i)⟫ = l.sum (λ (i : ι) (a : 𝕜), a • ⟪x, v i⟫) := by { convert inner_sum l.support (λ a, l a • v a) x, simp [inner_smul_right, finsupp.sum] } @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_equiv.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_equiv.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩ lemma inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (∥x∥ ^ 2 : 𝕜) := begin suffices : (is_R_or_C.re ⟪x, x⟫ : 𝕜) = ∥x∥ ^ 2, { simpa [inner_self_re_to_K] using this }, exact_mod_cast (norm_sq_eq_inner x).symm end lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin conv_rhs { rw [←inner_self_re_to_K] }, symmetry, exact is_R_or_C.abs_of_nonneg inner_self_nonneg, end lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by { rw [←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_equiv.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw [←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_add_add_self, this], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_sub_sub_self, this], ring, end /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul_eq_neg_mul_symm, add_monoid_hom.map_add, conj_im, add_monoid_hom.map_sub, mul_neg_eq_neg_mul_symm, conj_re, neg_neg, mul_re] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, hT, ring_equiv.map_div, h₁, h₃, inner_conj_sym] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section orthonormal_sets variables {ι : Type*} (𝕜) include 𝕜 /-- An orthonormal set of vectors in an `inner_product_space` -/ def orthonormal (v : ι → E) : Prop := (∀ i, ∥v i∥ = 1) ∧ (∀ {i j}, i ≠ j → ⟪v i, v j⟫ = 0) omit 𝕜 variables {𝕜} /-- `if ... then ... else` characterization of an indexed set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ lemma orthonormal_iff_ite {v : ι → E} : orthonormal 𝕜 v ↔ ∀ i j, ⟪v i, v j⟫ = if i = j then (1:𝕜) else (0:𝕜) := begin split, { intros hv i j, split_ifs, { simp [h, inner_self_eq_norm_sq_to_K, hv.1] }, { exact hv.2 h } }, { intros h, split, { intros i, have h' : ∥v i∥ ^ 2 = 1 ^ 2 := by simp [norm_sq_eq_inner, h i i], have h₁ : 0 ≤ ∥v i∥ := norm_nonneg _, have h₂ : (0:ℝ) ≤ 1 := zero_le_one, rwa sq_eq_sq h₁ h₂ at h' }, { intros i j hij, simpa [hij] using h i j } } end /-- `if ... then ... else` characterization of a set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ theorem orthonormal_subtype_iff_ite {s : set E} : orthonormal 𝕜 (coe : s → E) ↔ (∀ v ∈ s, ∀ w ∈ s, ⟪v, w⟫ = if v = w then 1 else 0) := begin rw orthonormal_iff_ite, split, { intros h v hv w hw, convert h ⟨v, hv⟩ ⟨w, hw⟩ using 1, simp }, { rintros h ⟨v, hv⟩ ⟨w, hw⟩, convert h v hv w hw using 1, simp } end /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = l i := by simp [finsupp.total_apply, finsupp.inner_sum, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪v i, ∑ i : ι, (l i) • (v i)⟫ = l i := by simp [inner_sum, inner_smul_right, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = conj (l i) := by rw [← inner_conj_sym, hv.inner_right_finsupp] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪∑ i : ι, (l i) • (v i), v i⟫ = conj (l i) := by simp [sum_inner, inner_smul_left, orthonormal_iff_ite.mp hv] /-- The double sum of weighted inner products of pairs of vectors from an orthonormal sequence is the sum of the weights. -/ lemma orthonormal.inner_left_right_finset {s : finset ι} {v : ι → E} (hv : orthonormal 𝕜 v) {a : ι → ι → 𝕜} : ∑ i in s, ∑ j in s, (a i j) • ⟪v j, v i⟫ = ∑ k in s, a k k := by simp [orthonormal_iff_ite.mp hv, finset.sum_ite_of_true] /-- An orthonormal set is linearly independent. -/ lemma orthonormal.linear_independent {v : ι → E} (hv : orthonormal 𝕜 v) : linear_independent 𝕜 v := begin rw linear_independent_iff, intros l hl, ext i, have key : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = ⟪v i, 0⟫ := by rw hl, simpa [hv.inner_right_finsupp] using key end /-- A subfamily of an orthonormal family (i.e., a composition with an injective map) is an orthonormal family. -/ lemma orthonormal.comp {ι' : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (f : ι' → ι) (hf : function.injective f) : orthonormal 𝕜 (v ∘ f) := begin rw orthonormal_iff_ite at ⊢ hv, intros i j, convert hv (f i) (f j) using 1, simp [hf.eq_iff] end /-- A linear combination of some subset of an orthonormal set is orthogonal to other members of the set. -/ lemma orthonormal.inner_finsupp_eq_zero {v : ι → E} (hv : orthonormal 𝕜 v) {s : set ι} {i : ι} (hi : i ∉ s) {l : ι →₀ 𝕜} (hl : l ∈ finsupp.supported 𝕜 𝕜 s) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = 0 := begin rw finsupp.mem_supported' at hl, simp [hv.inner_left_finsupp, hl i hi], end /- The material that follows, culminating in the existence of a maximal orthonormal subset, is adapted from the corresponding development of the theory of linearly independents sets. See `exists_linear_independent` in particular. -/ variables (𝕜 E) lemma orthonormal_empty : orthonormal 𝕜 (λ x, x : (∅ : set E) → E) := by simp [orthonormal_subtype_iff_ite] variables {𝕜 E} lemma orthonormal_Union_of_directed {η : Type*} {s : η → set E} (hs : directed (⊆) s) (h : ∀ i, orthonormal 𝕜 (λ x, x : s i → E)) : orthonormal 𝕜 (λ x, x : (⋃ i, s i) → E) := begin rw orthonormal_subtype_iff_ite, rintros x ⟨_, ⟨i, rfl⟩, hxi⟩ y ⟨_, ⟨j, rfl⟩, hyj⟩, obtain ⟨k, hik, hjk⟩ := hs i j, have h_orth : orthonormal 𝕜 (λ x, x : (s k) → E) := h k, rw orthonormal_subtype_iff_ite at h_orth, exact h_orth x (hik hxi) y (hjk hyj) end lemma orthonormal_sUnion_of_directed {s : set (set E)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, orthonormal 𝕜 (λ x, x : (a : set E) → E)) : orthonormal 𝕜 (λ x, x : (⋃₀ s) → E) := by rw set.sUnion_eq_Union; exact orthonormal_Union_of_directed hs.directed_coe (by simpa using h) /-- Given an orthonormal set `v` of vectors in `E`, there exists a maximal orthonormal set containing it. -/ lemma exists_maximal_orthonormal {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) : ∃ w ⊇ s, orthonormal 𝕜 (coe : w → E) ∧ ∀ u ⊇ w, orthonormal 𝕜 (coe : u → E) → u = w := begin rcases zorn.zorn_subset_nonempty {b | orthonormal 𝕜 (coe : b → E)} _ _ hs with ⟨b, bi, sb, h⟩, { refine ⟨b, sb, bi, _⟩, exact λ u hus hu, h u hu hus }, { refine λ c hc cc c0, ⟨⋃₀ c, _, _⟩, { exact orthonormal_sUnion_of_directed cc.directed_on (λ x xc, hc xc) }, { exact λ _, set.subset_sUnion_of_mem } } end lemma orthonormal.ne_zero {v : ι → E} (hv : orthonormal 𝕜 v) (i : ι) : v i ≠ 0 := begin have : ∥v i∥ ≠ 0, { rw hv.1 i, norm_num }, simpa using this end open finite_dimensional /-- A family of orthonormal vectors with the correct cardinality forms a basis. -/ def basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : basis ι 𝕜 E := basis_of_linear_independent_of_card_eq_finrank hv.linear_independent card_eq @[simp] lemma coe_basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : (basis_of_orthonormal_of_card_eq_finrank hv card_eq : ι → E) = v := coe_basis_of_linear_independent_of_card_eq_finrank _ _ end orthonormal_sets section norm lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) := begin have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x, have h₂ := congr_arg sqrt h₁, simpa using h₂, end lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_mul_norm (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw [norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma inner_self_eq_norm_sq (x : E) : re ⟪x, x⟫ = ∥x∥^2 := by rw [pow_two, inner_self_eq_norm_mul_norm] lemma real_inner_self_eq_norm_mul_norm (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ := by { have h := @inner_self_eq_norm_mul_norm ℝ F _ _ x, simpa using h } lemma real_inner_self_eq_norm_sq (x : F) : ⟪x, x⟫_ℝ = ∥x∥^2 := by rw [pow_two, real_inner_self_eq_norm_mul_norm] /-- Expand the square -/ lemma norm_add_sq {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [sq, ←inner_self_eq_norm_mul_norm]}, rw [inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end alias norm_add_sq ← norm_add_pow_two /-- Expand the square -/ lemma norm_add_sq_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_add_sq ℝ F _ _, simpa using h } alias norm_add_sq_real ← norm_add_pow_two_real /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ := by { repeat {rw [← sq]}, exact norm_add_sq } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_sq {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [sq, ←inner_self_eq_norm_mul_norm]}, rw [inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw [inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw [conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end alias norm_sub_sq ← norm_sub_pow_two /-- Expand the square -/ lemma norm_sub_sq_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := norm_sub_sq alias norm_sub_sq_real ← norm_sub_pow_two_real /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ := by { repeat {rw [← sq]}, exact norm_sub_sq } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_mul_norm], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end lemma norm_inner_le_norm (x y : E) : ∥⟪x, y⟫∥ ≤ ∥x∥ * ∥y∥ := (is_R_or_C.norm_eq_abs _).le.trans (abs_inner_le_norm x y) /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := le_trans (le_abs_self _) (abs_real_inner_le_norm _ _) include 𝕜 lemma parallelogram_law_with_norm {x y : E} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := begin simp only [← inner_self_eq_norm_mul_norm], rw [← re.map_add, parallelogram_law, two_mul, two_mul], simp only [re.map_add], end omit 𝕜 lemma parallelogram_law_with_norm_real {x y : F} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { have h := @parallelogram_law_with_norm ℝ F _ _ x y, simpa using h } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := by { rw norm_add_mul_self, ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := by { rw [norm_sub_mul_self], ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x - y∥ * ∥x - y∥) / 4 := by { rw [norm_add_mul_self, norm_sub_mul_self], ring } /-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/ lemma im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four (x y : E) : im ⟪x, y⟫ = (∥x - IK • y∥ * ∥x - IK • y∥ - ∥x + IK • y∥ * ∥x + IK • y∥) / 4 := by { simp only [norm_add_mul_self, norm_sub_mul_self, inner_smul_right, I_mul_re], ring } /-- Polarization identity: The inner product, in terms of the norm. -/ lemma inner_eq_sum_norm_sq_div_four (x y : E) : ⟪x, y⟫ = (∥x + y∥ ^ 2 - ∥x - y∥ ^ 2 + (∥x - IK • y∥ ^ 2 - ∥x + IK • y∥ ^ 2) * IK) / 4 := begin rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four, im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four], push_cast, simp only [sq, ← mul_div_right_comm, ← add_div] end section variables {E' : Type*} [inner_product_space 𝕜 E'] /-- A linear isometry preserves the inner product. -/ @[simp] lemma linear_isometry.inner_map_map (f : E →ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := by simp [inner_eq_sum_norm_sq_div_four, ← f.norm_map] /-- A linear isometric equivalence preserves the inner product. -/ @[simp] lemma linear_isometry_equiv.inner_map_map (f : E ≃ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := f.to_linear_isometry.inner_map_map x y /-- A linear map that preserves the inner product is a linear isometry. -/ def linear_map.isometry_of_inner (f : E →ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E →ₗᵢ[𝕜] E' := ⟨f, λ x, by simp only [norm_eq_sqrt_inner, h]⟩ @[simp] lemma linear_map.coe_isometry_of_inner (f : E →ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_map.isometry_of_inner_to_linear_map (f : E →ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_map = f := rfl /-- A linear equivalence that preserves the inner product is a linear isometric equivalence. -/ def linear_equiv.isometry_of_inner (f : E ≃ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E ≃ₗᵢ[𝕜] E' := ⟨f, ((f : E →ₗ[𝕜] E').isometry_of_inner h).norm_map⟩ @[simp] lemma linear_equiv.coe_isometry_of_inner (f : E ≃ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_equiv.isometry_of_inner_to_linear_equiv (f : E ≃ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_equiv = f := rfl end /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_mul_norm, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- Given two orthogonal vectors, their sum and difference have equal norms. -/ lemma norm_sub_eq_norm_add {v w : E} (h : ⟪v, w⟫ = 0) : ∥w - v∥ = ∥w + v∥ := begin rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _), simp [h, ←inner_self_eq_norm_mul_norm, inner_add_left, inner_add_right, inner_sub_left, inner_sub_right, inner_re_symm] end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (∥x∥ * ∥y∥) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (∥x∥ * ∥r • x∥) = 1 := begin have hx' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx], have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr], rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_mul_norm, norm_smul], rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div_eq_div_mul, mul_div_cancel _ hx', ←div_div_eq_div_mul, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw ← abs_to_real, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) : abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, }, refine and.intro hx0 _, set r := ⟪x, y⟫ / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr], norm_cast, rw [←inner_self_eq_norm_mul_norm, inner_self_re_to_K, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, replace h : ∥r • x∥ / ∥t + r • x∥ = 1, { rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_mul_norm] at h, norm_cast at h, rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs, ←norm_smul] at h }, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫, { rw [sq, sq, ←inner_self_eq_norm_mul_norm, ←inner_self_eq_norm_mul_norm ] at h2, have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2, simp_rw [inner_self_re_to_K, inner_add_add_self] at h2', exact h2' }, conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp }, rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw [hy, is_R_or_C.abs_div], norm_cast, rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y, simpa [coe_real_eq_id] using this, end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0): abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := begin have hx0' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx0], have hy0' : ∥y∥ ≠ 0 := by simp [norm_eq_zero, hy0], have hxy0 : ∥x∥ * ∥y∥ ≠ 0 := by simp [hx0', hy0'], have h₁ : abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1, { refine ⟨_ ,_⟩, { intro h, norm_cast, rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact div_self hxy0 }, { intro h, norm_cast at h, rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, div_eq_one_iff_eq hxy0] at h } }, rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y], have : x ≠ 0 := λ h, (hx0' $ norm_eq_zero.mpr h), simp [this] end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff {x y : E} : ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y := begin by_cases h : (x = 0 ∨ y = 0), -- WLOG `x` and `y` are nonzero { cases h; simp [h] }, calc ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ ∥x∥ * ∥y∥ = re ⟪x, y⟫ : begin norm_cast, split, { intros h', simp [h'] }, { have cauchy_schwarz := abs_inner_le_norm x y, intros h', rw h' at ⊢ cauchy_schwarz, rwa re_eq_self_of_le } end ... ↔ 2 * ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥ - re ⟪x, y⟫) = 0 : by simp [h, show (2:ℝ) ≠ 0, by norm_num, sub_eq_zero] ... ↔ ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ * ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ = 0 : begin simp only [norm_sub_mul_self, inner_smul_left, inner_smul_right, norm_smul, conj_of_real, is_R_or_C.norm_eq_abs, abs_of_real, of_real_im, of_real_re, mul_re, abs_norm_eq_norm], refine eq.congr _ rfl, ring end ... ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y : by simp [norm_sub_eq_zero_iff] end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ∥x∥ * ∥y∥ ↔ ∥y∥ • x = ∥x∥ • y := inner_eq_norm_mul_iff /-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_eq_norm_mul_iff_of_norm_one {x y : E} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫ = 1 ↔ x = y := by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] } lemma inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ∥y∥ • x ≠ ∥x∥ • y := calc ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ ≠ ∥x∥ * ∥y∥ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩ ... ↔ ∥y∥ • x ≠ ∥x∥ • y : not_congr inner_eq_norm_mul_iff_real /-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are distinct. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] } /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] /-- The inner product with a fixed left element, as a continuous linear map. This can be upgraded to a continuous map which is jointly conjugate-linear in the left argument and linear in the right argument, once (TODO) conjugate-linear maps have been defined. -/ def inner_right (v : E) : E →L[𝕜] 𝕜 := linear_map.mk_continuous { to_fun := λ w, ⟪v, w⟫, map_add' := λ x y, inner_add_right, map_smul' := λ c x, inner_smul_right } ∥v∥ (by simpa using norm_inner_le_norm v) @[simp] lemma inner_right_coe (v : E) : (inner_right v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma inner_right_apply (v w : E) : inner_right v w = ⟪v, w⟫ := rfl /-- When an inner product space `E` over `𝕜` is considered as a real normed space, its inner product satisfies `is_bounded_bilinear_map`. In order to state these results, we need a `normed_space ℝ E` instance. We will later establish such an instance by restriction-of-scalars, `inner_product_space.is_R_or_C_to_real 𝕜 E`, but this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]` and `[is_scalar_tower ℝ 𝕜 E]`. In both interesting cases `𝕜 = ℝ` and `𝕜 = ℂ` we have these instances. -/ lemma is_bounded_bilinear_map_inner [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E] : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := λ _ _ _, inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := λ _ _ _, inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul], exact norm_inner_le_norm x y, }⟩ } end norm section bessels_inequality variables {ι: Type*} (x : E) {v : ι → E} /-- Bessel's inequality for finite sums. -/ lemma orthonormal.sum_inner_products_le {s : finset ι} (hv : orthonormal 𝕜 v) : ∑ i in s, ∥⟪v i, x⟫∥ ^ 2 ≤ ∥x∥ ^ 2 := begin have h₂ : ∑ i in s, ∑ j in s, ⟪v i, x⟫ * ⟪x, v j⟫ * ⟪v j, v i⟫ = (∑ k in s, (⟪v k, x⟫ * ⟪x, v k⟫) : 𝕜), { exact hv.inner_left_right_finset }, have h₃ : ∀ z : 𝕜, re (z * conj (z)) = ∥z∥ ^ 2, { intro z, simp only [mul_conj, norm_sq_eq_def'], norm_cast, }, suffices hbf: ∥x - ∑ i in s, ⟪v i, x⟫ • (v i)∥ ^ 2 = ∥x∥ ^ 2 - ∑ i in s, ∥⟪v i, x⟫∥ ^ 2, { rw [←sub_nonneg, ←hbf], simp only [norm_nonneg, pow_nonneg], }, rw [norm_sub_sq, sub_add], simp only [inner_product_space.norm_sq_eq_inner, inner_sum], simp only [sum_inner, two_mul, inner_smul_right, inner_conj_sym, ←mul_assoc, h₂, ←h₃, inner_conj_sym, add_monoid_hom.map_sum, finset.mul_sum, ←finset.sum_sub_distrib, inner_smul_left, add_sub_cancel'], end /-- Bessel's inequality. -/ lemma orthonormal.tsum_inner_products_le (hv : orthonormal 𝕜 v) : ∑' i, ∥⟪v i, x⟫∥ ^ 2 ≤ ∥x∥ ^ 2 := begin refine tsum_le_of_sum_le' _ (λ s, hv.sum_inner_products_le x), simp only [norm_nonneg, pow_nonneg] end /-- The sum defined in Bessel's inequality is summable. -/ lemma orthonormal.inner_products_summable (hv : orthonormal 𝕜 v) : summable (λ i, ∥⟪v i, x⟫∥ ^ 2) := begin use ⨆ s : finset ι, ∑ i in s, ∥⟪v i, x⟫∥ ^ 2, apply has_sum_of_is_lub_of_nonneg, { intro b, simp only [norm_nonneg, pow_nonneg], }, { refine is_lub_csupr _, use ∥x∥ ^ 2, rintro y ⟨s, rfl⟩, exact hv.sum_inner_products_le x } end end bessels_inequality /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { inner := (λ x y, (conj x) * y), norm_sq_eq_inner := λ x, by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] }, conj_sym := λ x y, by simp [mul_comm], add_left := λ x y z, by simp [inner, add_mul], smul_left := λ x y z, by simp [inner, mul_assoc] } @[simp] lemma is_R_or_C.inner_apply (x y : 𝕜) : ⟪x, y⟫ = (conj x) * y := rfl /-! ### Inner product space structure on subspaces -/ /-- Induced inner product on a submodule. -/ instance submodule.inner_product_space (W : submodule 𝕜 E) : inner_product_space 𝕜 W := { inner := λ x y, ⟪(x:E), (y:E)⟫, conj_sym := λ _ _, inner_conj_sym _ _ , norm_sq_eq_inner := λ _, norm_sq_eq_inner _, add_left := λ _ _ _ , inner_add_left, smul_left := λ _ _ _, inner_smul_left, ..submodule.normed_space W } /-- The inner product on submodules is the same as on the ambient space. -/ @[simp] lemma submodule.coe_inner (W : submodule 𝕜 E) (x y : W) : ⟪x, y⟫ = ⟪(x:E), ↑y⟫ := rfl /-! ### Families of mutually-orthogonal subspaces of an inner product space -/ section orthogonal_family variables {ι : Type*} (𝕜) open_locale direct_sum /-- An indexed family of mutually-orthogonal subspaces of an inner product space `E`. -/ def orthogonal_family (V : ι → submodule 𝕜 E) : Prop := ∀ ⦃i j⦄, i ≠ j → ∀ {v : E} (hv : v ∈ V i) {w : E} (hw : w ∈ V j), ⟪v, w⟫ = 0 variables {𝕜} {V : ι → submodule 𝕜 E} lemma orthogonal_family.eq_ite (hV : orthogonal_family 𝕜 V) {i j : ι} (v : V i) (w : V j) : ⟪(v:E), w⟫ = ite (i = j) ⟪(v:E), w⟫ 0 := begin split_ifs, { refl }, { exact hV h v.prop w.prop } end lemma orthogonal_family.inner_right_dfinsupp (hV : orthogonal_family 𝕜 V) (l : Π₀ i, V i) (i : ι) (v : V i) : ⟪(v : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) l⟫ = ⟪v, l i⟫ := calc ⟪(v : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) l⟫ = l.sum (λ j, λ w, ⟪(v:E), w⟫) : begin let F : E →+ 𝕜 := (@inner_right 𝕜 E _ _ v).to_linear_map.to_add_monoid_hom, have hF := congr_arg add_monoid_hom.to_fun (dfinsupp.comp_sum_add_hom F (λ j, (V j).subtype.to_add_monoid_hom)), convert congr_fun hF l using 1, simp only [dfinsupp.sum_add_hom_apply, continuous_linear_map.to_linear_map_eq_coe, add_monoid_hom.coe_comp, inner_right_coe, add_monoid_hom.to_fun_eq_coe, linear_map.to_add_monoid_hom_coe, continuous_linear_map.coe_coe], congr end ... = l.sum (λ j, λ w, ite (i=j) ⟪(v:E), w⟫ 0) : congr_arg l.sum $ funext $ λ j, funext $ hV.eq_ite v ... = ⟪v, l i⟫ : begin simp only [dfinsupp.sum, submodule.coe_inner, finset.sum_ite_eq, ite_eq_left_iff, dfinsupp.mem_support_to_fun, not_not], intros h, simp [h] end lemma orthogonal_family.inner_right_fintype [fintype ι] (hV : orthogonal_family 𝕜 V) (l : Π i, V i) (i : ι) (v : V i) : ⟪(v : E), ∑ j : ι, l j⟫ = ⟪v, l i⟫ := calc ⟪(v : E), ∑ j : ι, l j⟫ = ∑ j : ι, ⟪(v : E), l j⟫: by rw inner_sum ... = ∑ j, ite (i = j) ⟪(v : E), l j⟫ 0 : congr_arg (finset.sum finset.univ) $ funext $ λ j, (hV.eq_ite v (l j)) ... = ⟪v, l i⟫ : by simp /-- An orthogonal family forms an independent family of subspaces; that is, any collection of elements each from a different subspace in the family is linearly independent. In particular, the pairwise intersections of elements of the family are 0. -/ lemma orthogonal_family.independent (hV : orthogonal_family 𝕜 V) : complete_lattice.independent V := begin apply complete_lattice.independent_of_dfinsupp_lsum_injective, rw [← @linear_map.ker_eq_bot _ _ _ _ _ _ (direct_sum.add_comm_group (λ i, V i)), submodule.eq_bot_iff], intros v hv, rw linear_map.mem_ker at hv, ext i, have : ⟪(v i : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) v⟫ = 0, { simp [hv] }, simpa only [submodule.coe_zero, submodule.coe_eq_zero, direct_sum.zero_apply, inner_self_eq_zero, hV.inner_right_dfinsupp] using this, end end orthogonal_family section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp [inner_add_left] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp [inner_smul_left] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl lemma real_inner_I_smul_self (x : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x ((I : 𝕜) • x) = 0 := by simp [real_inner_eq_re_inner, inner_smul_right] omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G end is_R_or_C_to_real section continuous /-! ### Continuity of the inner product -/ lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, exact is_bounded_bilinear_map_inner.continuous end variables {α : Type*} lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) := (continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → E} {x : α} {s : set α} include 𝕜 lemma continuous_within_at.inner (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ t, ⟪f t, g t⟫) s x := hf.inner hg lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ t, ⟪f t, g t⟫) x := hf.inner hg lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ t, ⟪f t, g t⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at end continuous section re_apply_inner_self /-- Extract a real bilinear form from an operator `T`, by taking the pairing `λ x, re ⟪T x, x⟫`. -/ def continuous_linear_map.re_apply_inner_self (T : E →L[𝕜] E) (x : E) : ℝ := re ⟪T x, x⟫ lemma continuous_linear_map.re_apply_inner_self_apply (T : E →L[𝕜] E) (x : E) : T.re_apply_inner_self x = re ⟪T x, x⟫ := rfl lemma continuous_linear_map.re_apply_inner_self_continuous (T : E →L[𝕜] E) : continuous T.re_apply_inner_self := re_clm.continuous.comp $ T.continuous.inner continuous_id lemma continuous_linear_map.re_apply_inner_self_smul (T : E →L[𝕜] E) (x : E) {c : 𝕜} : T.re_apply_inner_self (c • x) = ∥c∥ ^ 2 * T.re_apply_inner_self x := by simp only [continuous_linear_map.map_smul, continuous_linear_map.re_apply_inner_self_apply, inner_smul_left, inner_smul_right, ← mul_assoc, mul_conj, norm_sq_eq_def', ← smul_re, algebra.smul_def (∥c∥ ^ 2) ⟪T x, x⟫, algebra_map_eq_of_real] end re_apply_inner_self /-! ### The orthogonal complement -/ section orthogonal variables (K : submodule 𝕜 E) /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } notation K`ᗮ`:1200 := submodule.orthogonal K /-- When a vector is in `Kᗮ`. -/ lemma submodule.mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `Kᗮ`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] variables {K} /-- A vector in `K` is orthogonal to one in `Kᗮ`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `Kᗮ` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_right_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪u, v⟫ = 0 := submodule.inner_right_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_left_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪v, u⟫ = 0 := submodule.inner_left_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv variables (K) /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.inf_orthogonal_eq_bot : K ⊓ Kᗮ = ⊥ := begin rw submodule.eq_bot_iff, intros x, rw submodule.mem_inf, exact λ ⟨hx, ho⟩, inner_self_eq_zero.1 (ho x hx) end /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.orthogonal_disjoint : disjoint K Kᗮ := by simp [disjoint_iff, K.inf_orthogonal_eq_bot] /-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of inner product with each of the elements of `K`. -/ lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, (inner_right (v:E)).ker := begin apply le_antisymm, { rw le_infi_iff, rintros ⟨v, hv⟩ w hw, simpa using hw _ hv }, { intros v hv w hw, simp only [submodule.mem_infi] at hv, exact hv ⟨w, hw⟩ } end /-- The orthogonal complement of any submodule `K` is closed. -/ lemma submodule.is_closed_orthogonal : is_closed (Kᗮ : set E) := begin rw orthogonal_eq_inter K, convert is_closed_Inter (λ v : K, (inner_right (v:E)).is_closed_ker), simp end /-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/ instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (order_dual $ submodule 𝕜 E) _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `submodule.orthogonal.orthogonal` preserves the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_orthogonal_monotone {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₁ᗮᗮ ≤ K₂ᗮᗮ := submodule.orthogonal_le (submodule.orthogonal_le h) /-- `K` is contained in `Kᗮᗮ`. -/ lemma submodule.le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm @[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ := begin ext, rw [submodule.mem_bot, submodule.mem_orthogonal], exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩ end @[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ := begin rw [← submodule.top_orthogonal_eq_bot, eq_top_iff], exact submodule.le_orthogonal_orthogonal ⊤ end @[simp] lemma submodule.orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ := begin refine ⟨_, by { rintro rfl, exact submodule.bot_orthogonal_eq_top }⟩, intro h, have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot, rwa [h, inf_comm, top_inf_eq] at this end end orthogonal /-! ### Self-adjoint operators -/ section is_self_adjoint /-- A (not necessarily bounded) operator on an inner product space is self-adjoint, if for all `x`, `y`, we have `⟪T x, y⟫ = ⟪x, T y⟫`. -/ def is_self_adjoint (T : E →ₗ[𝕜] E) : Prop := ∀ x y, ⟪T x, y⟫ = ⟪x, T y⟫ /-- An operator `T` on a `ℝ`-inner product space is self-adjoint if and only if it is `bilin_form.is_self_adjoint` with respect to the bilinear form given by the inner product. -/ lemma is_self_adjoint_iff_bilin_form (T : F →ₗ[ℝ] F) : is_self_adjoint T ↔ bilin_form_of_real_inner.is_self_adjoint T := by simp [is_self_adjoint, bilin_form.is_self_adjoint, bilin_form.is_adjoint_pair] lemma is_self_adjoint.conj_inner_sym {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) (x y : E) : conj ⟪T x, y⟫ = ⟪T y, x⟫ := by rw [hT x y, inner_conj_sym] @[simp] lemma is_self_adjoint.apply_clm {T : E →L[𝕜] E} (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) (x y : E) : ⟪T x, y⟫ = ⟪x, T y⟫ := hT x y /-- For a self-adjoint operator `T`, the function `λ x, ⟪T x, x⟫` is real-valued. -/ @[simp] lemma is_self_adjoint.coe_re_apply_inner_self_apply {T : E →L[𝕜] E} (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) (x : E) : (T.re_apply_inner_self x : 𝕜) = ⟪T x, x⟫ := begin suffices : ∃ r : ℝ, ⟪T x, x⟫ = r, { obtain ⟨r, hr⟩ := this, simp [hr, T.re_apply_inner_self_apply] }, rw ← eq_conj_iff_real, exact hT.conj_inner_sym x x end end is_self_adjoint
ae318afcbbc55ed90b8bfde321de813b1cce9e81
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/rw1.lean
492a660ed99cc85d8a4a1664ecb73c7ff06c8af5
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
367
lean
(* mk_rewrite_rule_set("rw1") add_rewrite_rules("rw1", "and_assoc") add_rewrite_rules("rw1", "and_truer") show_rewrite_rules("rw1") *) scope print "new scope" (* add_rewrite_rules("rw1", "or_assoc") enable_rewrite_rules("rw1", "and_assoc", false) show_rewrite_rules("rw1") *) end print "after end of scope" (* show_rewrite_rules("rw1") *)
03941815e536b3679d7e32572344d92115246c61
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Init/Data/Nat/Div.lean
47acde42d596acf8ba1911b58eefe1bc93e6ce0b
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
4,782
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.WF import Init.Data.Nat.Basic namespace Nat private def div_rec_lemma {x y : Nat} : 0 < y ∧ y ≤ x → x - y < x := fun ⟨ypos, ylex⟩ => subLt (Nat.ltOfLtOfLe ypos ylex) ypos private def div.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat := if h : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma h) y + 1 else zero @[extern "lean_nat_div"] protected def div (a b : @& Nat) : Nat := WellFounded.fix ltWf div.F a b instance : Div Nat := ⟨Nat.div⟩ private theorem div_eq_aux (x y : Nat) : x / y = if h : 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := congrFun (WellFounded.fixEq ltWf div.F x) y theorem div_eq (x y : Nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := difEqIf (0 < y ∧ y ≤ x) ((x - y) / y + 1) 0 ▸ div_eq_aux x y private theorem div.induction.F.{u} (C : Nat → Nat → Sort u) (ind : ∀ x y, 0 < y ∧ y ≤ x → C (x - y) y → C x y) (base : ∀ x y, ¬(0 < y ∧ y ≤ x) → C x y) (x : Nat) (f : ∀ (x₁ : Nat), x₁ < x → ∀ (y : Nat), C x₁ y) (y : Nat) : C x y := if h : 0 < y ∧ y ≤ x then ind x y h (f (x - y) (div_rec_lemma h) y) else base x y h theorem div.inductionOn.{u} {motive : Nat → Nat → Sort u} (x y : Nat) (ind : ∀ x y, 0 < y ∧ y ≤ x → motive (x - y) y → motive x y) (base : ∀ x y, ¬(0 < y ∧ y ≤ x) → motive x y) : motive x y := WellFounded.fix Nat.ltWf (div.induction.F motive ind base) x y private def mod.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat := if h : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma h) y else x @[extern "lean_nat_mod"] protected def mod (a b : @& Nat) : Nat := WellFounded.fix ltWf mod.F a b instance : Mod Nat := ⟨Nat.mod⟩ private theorem mod_eq_aux (x y : Nat) : x % y = if h : 0 < y ∧ y ≤ x then (x - y) % y else x := congrFun (WellFounded.fixEq ltWf mod.F x) y theorem mod_eq (x y : Nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x := difEqIf (0 < y ∧ y ≤ x) ((x - y) % y) x ▸ mod_eq_aux x y theorem mod.inductionOn.{u} {motive : Nat → Nat → Sort u} (x y : Nat) (ind : ∀ x y, 0 < y ∧ y ≤ x → motive (x - y) y → motive x y) (base : ∀ x y, ¬(0 < y ∧ y ≤ x) → motive x y) : motive x y := div.inductionOn x y ind base theorem mod_zero (a : Nat) : a % 0 = a := have : (if 0 < 0 ∧ 0 ≤ a then (a - 0) % 0 else a) = a := have h : ¬ (0 < 0 ∧ 0 ≤ a) := fun ⟨h₁, _⟩ => absurd h₁ (Nat.ltIrrefl _) ifNeg h (mod_eq a 0).symm ▸ this theorem mod_eq_of_lt {a b : Nat} (h : a < b) : a % b = a := have : (if 0 < b ∧ b ≤ a then (a - b) % b else a) = a := have h' : ¬(0 < b ∧ b ≤ a) := fun ⟨_, h₁⟩ => absurd h₁ (Nat.notLeOfGt h) ifNeg h' (mod_eq a b).symm ▸ this theorem mod_eq_sub_mod {a b : Nat} (h : a ≥ b) : a % b = (a - b) % b := match eqZeroOrPos b with | Or.inl h₁ => h₁.symm ▸ (Nat.sub_zero a).symm ▸ rfl | Or.inr h₁ => (mod_eq a b).symm ▸ ifPos ⟨h₁, h⟩ theorem mod_lt (x : Nat) {y : Nat} : y > 0 → x % y < y := by induction x, y using mod.inductionOn with | base x y h₁ => intro h₂ have h₁ : ¬ 0 < y ∨ ¬ y ≤ x := Iff.mp (Decidable.notAndIffOrNot _ _) h₁ match h₁ with | Or.inl h₁ => exact absurd h₂ h₁ | Or.inr h₁ => have hgt : y > x := gtOfNotLe h₁ have heq : x % y = x := mod_eq_of_lt hgt rw [← heq] at hgt exact hgt | ind x y h h₂ => intro h₃ have ⟨_, h₁⟩ := h rw [mod_eq_sub_mod h₁] exact h₂ h₃ theorem mod_le (x y : Nat) : x % y ≤ x := by match Nat.ltOrGe x y with | Or.inl h₁ => rw [mod_eq_of_lt h₁]; apply Nat.leRefl | Or.inr h₁ => match eqZeroOrPos y with | Or.inl h₂ => rw [h₂, Nat.mod_zero x]; apply Nat.leRefl | Or.inr h₂ => exact Nat.leTrans (Nat.leOfLt (mod_lt _ h₂)) h₁ @[simp] theorem zero_mod (b : Nat) : 0 % b = 0 := by rw [mod_eq] have : ¬ (0 < b ∧ b ≤ 0) := by intro ⟨h₁, h₂⟩ exact absurd (Nat.ltOfLtOfLe h₁ h₂) (Nat.ltIrrefl 0) simp [this] @[simp] theorem mod_self (n : Nat) : n % n = 0 := by rw [mod_eq_sub_mod (Nat.leRefl _), Nat.sub_self, zero_mod] theorem mod_one (x : Nat) : x % 1 = 0 := by have h : x % 1 < 1 := mod_lt x (by decide) have : (y : Nat) → y < 1 → y = 0 := by intro y cases y with | zero => intro h; rfl | succ y => intro h; apply absurd (Nat.lt_of_succ_lt_succ h) (Nat.notLtZero y) exact this _ h end Nat
229d5fe112d00d3877319aff43caa929e4a8bcce
618003631150032a5676f229d13a079ac875ff77
/src/data/real/nnreal.lean
c107d06251ffdc29d38f102d8932be7400b03cb5
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
25,126
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import data.real.basic noncomputable theory open_locale classical /-- Nonnegative real numbers. -/ def nnreal := {r : ℝ // 0 ≤ r} localized "notation ` ℝ≥0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ /- Simp lemma to put back `n.val` into the normal form given by the coercion. -/ @[simp] lemma val_eq_coe (n : nnreal) : n.val = n := rfl instance : can_lift ℝ nnreal := { coe := coe, cond := λ r, r ≥ 0, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y := not_iff_not_of_iff $ nnreal.eq_iff protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r := max_eq_left hr lemma le_coe_of_real (r : ℝ) : r ≤ nnreal.of_real r := le_max_left r 0 lemma coe_nonneg (r : nnreal) : (0 : ℝ) ≤ r := r.2 @[norm_cast] theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩ instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_div ℝ≥0 := ⟨λa b, ⟨a.1 / b.1, div_nonneg' a.2 b.2⟩⟩ instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩ instance : has_bot ℝ≥0 := ⟨0⟩ instance : inhabited ℝ≥0 := ⟨0⟩ @[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := subtype.ext.symm @[simp, norm_cast] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl @[simp, norm_cast] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl @[simp, norm_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl @[simp, norm_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl @[simp, norm_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[simp, norm_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl @[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl @[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl @[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma zero_div (r : ℝ≥0) : 0 / r = 0 := nnreal.eq (zero_div _) @[simp] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := by norm_cast lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast instance : comm_semiring ℝ≥0 := begin refine { zero := 0, add := (+), one := 1, mul := (*), ..}; { intros; apply nnreal.eq; simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib, add_comm_monoid.zero, add_comm, add_left_comm] } end /-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/ def to_real_hom : ℝ≥0 →+* ℝ := ⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩ @[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl instance : comm_group_with_zero ℝ≥0 := { zero_ne_one := assume h, zero_ne_one $ nnreal.eq_iff.2 h, inv_zero := nnreal.eq $ show (0⁻¹ : ℝ) = 0, from inv_zero, mul_inv_cancel := assume x h, nnreal.eq $ mul_inv_cancel $ ne_iff.2 h, .. (by apply_instance : has_inv ℝ≥0), .. (_ : comm_semiring ℝ≥0), .. (_ : semiring ℝ≥0) } @[norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n := to_real_hom.map_pow r n @[norm_cast] lemma coe_list_sum (l : list ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum := to_real_hom.map_list_sum l @[norm_cast] lemma coe_list_prod (l : list ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod := to_real_hom.map_list_prod l @[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum := to_real_hom.map_multiset_sum s @[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod := to_real_hom.map_multiset_prod s @[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.sum f) = s.sum (λa, (f a : ℝ)) := to_real_hom.map_sum _ _ @[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.prod f) = s.prod (λa, (f a : ℝ)) := to_real_hom.map_prod _ _ @[norm_cast] lemma nsmul_coe (r : ℝ≥0) (n : ℕ) : ↑(n •ℕ r) = n •ℕ (r:ℝ) := to_real_hom.to_add_monoid_hom.map_nsmul _ _ @[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n := to_real_hom.map_nat_cast n instance : decidable_linear_order ℝ≥0 := decidable_linear_order.lift (coe : ℝ≥0 → ℝ) subtype.val_injective (by apply_instance) @[norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2 protected lemma of_real_mono : monotone nnreal.of_real := λ x y h, max_le_max h (le_refl 0) @[simp] lemma of_real_coe {r : ℝ≥0} : nnreal.of_real r = r := nnreal.eq $ max_eq_left r.2 /-- `nnreal.of_real` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/ protected def gi : galois_insertion nnreal.of_real coe := galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono le_coe_of_real (λ _, of_real_coe) instance : order_bot ℝ≥0 := { bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.decidable_linear_order } instance : canonically_ordered_add_monoid ℝ≥0 := { add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c, lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c, le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≤ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩, nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.order_bot, ..nnreal.decidable_linear_order } instance : distrib_lattice ℝ≥0 := by apply_instance instance : semilattice_inf_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : semilattice_sup_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : linear_ordered_semiring ℝ≥0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_lt_one := @zero_lt_one ℝ _, .. nnreal.decidable_linear_order, .. nnreal.canonically_ordered_add_monoid, .. nnreal.comm_semiring } instance : canonically_ordered_comm_semiring ℝ≥0 := { zero_ne_one := assume h, zero_ne_one $ congr_arg subtype.val $ h, mul_eq_zero_iff := assume a b, nnreal.eq_iff.symm.trans $ mul_eq_zero.trans $ by simp, .. nnreal.linear_ordered_semiring, .. nnreal.canonically_ordered_add_monoid, .. nnreal.comm_semiring } instance : densely_ordered ℝ≥0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝ≥0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : nnreal → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : nnreal → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ instance : has_Sup ℝ≥0 := ⟨λs, ⟨Sup ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Sup_empty] }, rcases h with ⟨⟨b, hb⟩, hbs⟩, by_cases h' : bdd_above s, { exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb }, { rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] } end⟩⟩ instance : has_Inf ℝ≥0 := ⟨λs, ⟨Inf ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Inf_empty] }, exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq ▸ q.2) end⟩⟩ lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal → ℝ) '' s) := rfl lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal → ℝ) '' s) := rfl instance : conditionally_complete_linear_order_bot ℝ≥0 := { Sup := Sup, Inf := Inf, le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha), cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has), le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice_of_decidable_linear_order, .. nnreal.order_bot } instance : archimedean nnreal := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≤ (n •ℕ y : nnreal), by simp [*, nsmul_coe]⟩ ⟩ lemma le_of_forall_epsilon_le {a b : nnreal} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end lemma lt_iff_exists_rat_btwn (a b : nnreal) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : nnreal) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end @[simp, norm_cast] lemma coe_max (x y : nnreal) : ((max x y : nnreal) : ℝ) = max (x : ℝ) (y : ℝ) := by { delta max, split_ifs; refl } @[simp, norm_cast] lemma coe_min (x y : nnreal) : ((min x y : nnreal) : ℝ) = min (x : ℝ) (y : ℝ) := by { delta min, split_ifs; refl } section of_real @[simp] lemma zero_le_coe {q : nnreal} : 0 ≤ (q : ℝ) := q.2 @[simp] lemma of_real_zero : nnreal.of_real 0 = 0 := by simp [nnreal.of_real]; refl @[simp] lemma of_real_one : nnreal.of_real 1 = 1 := by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl @[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r := by simp [nnreal.of_real, nnreal.coe_lt_coe.symm, lt_irrefl] @[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 := by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r)) lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 := of_real_eq_zero.2 @[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) : nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p := by simp [nnreal.coe_le_coe.symm, nnreal.of_real, hp] @[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} : nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt_coe.symm, nnreal.of_real, lt_irrefl] lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans (and_iff_left h) lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p := nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg] lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) := (of_real_add hr hp).symm lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p := nnreal.of_real_mono h lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p := nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma of_real_le_iff_le_coe {r : ℝ} {p : nnreal} : nnreal.of_real r ≤ p ↔ r ≤ ↑p := nnreal.gi.gc r p lemma le_of_real_iff_coe_le {r : nnreal} {p : ℝ} (hp : p ≥ 0) : r ≤ nnreal.of_real p ↔ ↑r ≤ p := by rw [← nnreal.coe_le_coe, nnreal.coe_of_real p hp] lemma of_real_lt_iff_lt_coe {r : ℝ} {p : nnreal} (ha : r ≥ 0) : nnreal.of_real r < p ↔ r < ↑p := by rw [← nnreal.coe_lt_coe, nnreal.coe_of_real r ha] lemma lt_of_real_iff_coe_lt {r : nnreal} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt_coe, nnreal.coe_of_real p h] }, { rw [of_real_eq_zero.2 h], split, intro, have := not_lt_of_le (zero_le r), contradiction, intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction } end end of_real section mul lemma mul_eq_mul_left {a b c : nnreal} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact eq_of_mul_eq_mul_left (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, have := max_eq_left (mul_nonneg hp hq), simpa [nnreal.of_real, hp, hq, max_eq_left] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] } end @[field_simps] theorem mul_ne_zero' {a b : nnreal} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := mul_ne_zero'' h₁ h₂ end mul section sub lemma sub_def {r p : ℝ≥0} : r - p = nnreal.of_real (r - p) := rfl lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h @[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r := by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe] lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r := of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe protected lemma sub_lt_self {r p : nnreal} : 0 < r → 0 < p → r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _) lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] @[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≤ a) : (a - b) + b = a := nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub h, sub_add_cancel] lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r := by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h, sub_sub_cancel, nnreal.of_real_coe] lemma lt_sub_iff_add_lt {p q r : nnreal} : p < q - r ↔ p + r < q := begin split, { assume H, have : (((q - r) : nnreal) : ℝ) = (q : ℝ) - (r : ℝ) := nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))), rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H }, { assume H, have : r ≤ q := le_trans (le_add_left (le_refl _)) (le_of_lt H), rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] } end end sub section inv lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl @[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero @[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 := inv_eq_zero @[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r := by simp [zero_lt_iff_ne_zero] lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := mul_pos hr (inv_pos.2 hp) @[simp] lemma inv_one : (1:ℝ≥0)⁻¹ = 1 := nnreal.eq $ inv_one @[simp] lemma div_one {r : ℝ≥0} : r / 1 = r := by rw [div_def, inv_one, mul_one] protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv' _ _ protected lemma inv_pow {r : ℝ≥0} {n : ℕ} : (r^n)⁻¹ = (r⁻¹)^n := nnreal.eq $ by { push_cast, exact (inv_pow' _ _).symm } @[simp] lemma inv_mul_cancel {r : ℝ≥0} (h : r ≠ 0) : r⁻¹ * r = 1 := nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h @[simp] lemma mul_inv_cancel {r : ℝ≥0} (h : r ≠ 0) : r * r⁻¹ = 1 := by rw [mul_comm, inv_mul_cancel h] @[simp] lemma div_self {r : ℝ≥0} (h : r ≠ 0) : r / r = 1 := mul_inv_cancel h @[simp] lemma div_mul_cancel {r p : ℝ≥0} (h : p ≠ 0) : r / p * p = r := by rw [div_def, mul_assoc, inv_mul_cancel h, mul_one] @[simp] lemma mul_div_cancel {r p : ℝ≥0} (h : p ≠ 0) : r * p / p = r := by rw [div_def, mul_assoc, mul_inv_cancel h, mul_one] @[simp] lemma mul_div_cancel' {r p : ℝ≥0} (h : r ≠ 0) : r * (p / r) = p := by rw [mul_comm, div_mul_cancel h] @[simp] lemma inv_inv {r : ℝ≥0} : r⁻¹⁻¹ = r := nnreal.eq (inv_inv' _) @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_def, mul_comm, ← mul_le_iff_le_inv hr, mul_comm] lemma le_of_forall_lt_one_mul_lt {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 := by simpa [div_def] using half_lt_self zero_ne_one.symm lemma div_lt_iff {a b c : ℝ≥0} (hc : c ≠ 0) : b / c < a ↔ b < a * c := begin rw [← nnreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_div, nnreal.coe_mul], exact div_lt_iff (zero_lt_iff_ne_zero.mpr hc) end lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] theorem div_pow {a b : ℝ≥0} (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n := div_pow _ _ _ @[field_simps] lemma mul_div_assoc' (a b c : ℝ≥0) : a * (b / c) = (a * b) / c := by rw [div_def, div_def, mul_assoc] @[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnreal.eq_iff, simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma inv_eq_one_div (a : ℝ≥0) : a⁻¹ = 1/a := by rw [div_def, one_mul] @[field_simps] lemma div_mul_eq_mul_div (a b c : ℝ≥0) : (a / b) * c = (a * c) / b := by { rw [div_def, div_def], ac_refl } @[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma one_div_eq_inv (a : ℝ≥0) : 1 / a = a⁻¹ := one_mul a⁻¹ lemma one_div_div (a b : ℝ≥0) : 1 / (a / b) = b / a := by { rw ← nnreal.eq_iff, simp [one_div_div] } lemma div_eq_mul_one_div (a b : ℝ≥0) : a / b = a * (1 / b) := by rw [div_def, div_def, one_mul] @[field_simps] lemma div_div_eq_mul_div (a b c : ℝ≥0) : a / (b / c) = (a * c) / b := by { rw ← nnreal.eq_iff, simp [div_div_eq_mul_div] } @[field_simps] lemma div_div_eq_div_mul (a b c : ℝ≥0) : (a / b) / c = a / (b * c) := by { rw ← nnreal.eq_iff, simp [div_div_eq_div_mul] } @[field_simps] lemma div_eq_div_iff {a b c d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := div_eq_div_iff hb hd @[field_simps] lemma div_eq_iff {a b c : ℝ≥0} (hb : b ≠ 0) : a / b = c ↔ a = c * b := by simpa using @div_eq_div_iff a b c 1 hb one_ne_zero @[field_simps] lemma eq_div_iff {a b c : ℝ≥0} (hb : b ≠ 0) : c = a / b ↔ c * b = a := by simpa using @div_eq_div_iff c 1 a b one_ne_zero hb end inv section pow theorem pow_eq_zero {a : ℝ≥0} {n : ℕ} (h : a^n = 0) : a = 0 := begin rw ← nnreal.eq_iff, rw [← nnreal.eq_iff, coe_pow] at h, exact pow_eq_zero h end @[field_simps] theorem pow_ne_zero {a : ℝ≥0} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h end pow end nnreal
dbfca3b7fa3c392602591bdbaa41927c98844d7d
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/analysis/normed_space/hahn_banach.lean
9cb01fa6896551a41efa99b22f49601ac752d68a
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
7,003
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Heather Macbeth -/ import analysis.normed_space.operator_norm import analysis.normed_space.extend import analysis.convex.cone import data.complex.is_R_or_C /-! # Hahn-Banach theorem In this file we prove a version of Hahn-Banach theorem for continuous linear functions on normed spaces over `ℝ` and `ℂ`. In order to state and prove its corollaries uniformly, we prove the statements for a field `𝕜` satisfying `is_R_or_C 𝕜`. In this setting, `exists_dual_vector` states that, for any nonzero `x`, there exists a continuous linear form `g` of norm `1` with `g x = ∥x∥` (where the norm has to be interpreted as an element of `𝕜`). -/ universes u v /-- The norm of `x` as an element of `𝕜` (a normed algebra over `ℝ`). This is needed in particular to state equalities of the form `g x = norm' 𝕜 x` when `g` is a linear function. For the concrete cases of `ℝ` and `𝕜`, this is just `∥x∥` and `↑∥x∥`, respectively. -/ noncomputable def norm' (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [normed_algebra ℝ 𝕜] {E : Type*} [normed_group E] (x : E) : 𝕜 := algebra_map ℝ 𝕜 ∥x∥ lemma norm'_def (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [normed_algebra ℝ 𝕜] {E : Type*} [normed_group E] (x : E) : norm' 𝕜 x = (algebra_map ℝ 𝕜 ∥x∥) := rfl lemma norm_norm' (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [normed_algebra ℝ 𝕜] (A : Type*) [normed_group A] (x : A) : ∥norm' 𝕜 x∥ = ∥x∥ := by rw [norm'_def, norm_algebra_map_eq, norm_norm] namespace real variables {E : Type*} [normed_group E] [normed_space ℝ E] /-- Hahn-Banach theorem for continuous linear functions over `ℝ`. -/ theorem exists_extension_norm_eq (p : subspace ℝ E) (f : p →L[ℝ] ℝ) : ∃ g : E →L[ℝ] ℝ, (∀ x : p, g x = f x) ∧ ∥g∥ = ∥f∥ := begin rcases exists_extension_of_le_sublinear ⟨p, f⟩ (λ x, ∥f∥ * ∥x∥) (λ c hc x, by simp only [norm_smul c x, real.norm_eq_abs, abs_of_pos hc, mul_left_comm]) (λ x y, _) (λ x, le_trans (le_abs_self _) (f.le_op_norm _)) with ⟨g, g_eq, g_le⟩, set g' := g.mk_continuous (∥f∥) (λ x, abs_le.2 ⟨neg_le.1 $ g.map_neg x ▸ norm_neg x ▸ g_le (-x), g_le x⟩), { refine ⟨g', g_eq, _⟩, { apply le_antisymm (g.mk_continuous_norm_le (norm_nonneg f) _), refine f.op_norm_le_bound (norm_nonneg _) (λ x, _), dsimp at g_eq, rw ← g_eq, apply g'.le_op_norm } }, { simp only [← mul_add], exact mul_le_mul_of_nonneg_left (norm_add_le x y) (norm_nonneg f) } end end real section is_R_or_C open is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] {F : Type*} [normed_group F] [normed_space 𝕜 F] /-- Hahn-Banach theorem for continuous linear functions over `𝕜` satisyfing `is_R_or_C 𝕜`. -/ theorem exists_extension_norm_eq (p : subspace 𝕜 F) (f : p →L[𝕜] 𝕜) : ∃ g : F →L[𝕜] 𝕜, (∀ x : p, g x = f x) ∧ ∥g∥ = ∥f∥ := begin letI : module ℝ F := restrict_scalars.semimodule ℝ 𝕜 F, letI : is_scalar_tower ℝ 𝕜 F := restrict_scalars.is_scalar_tower _ _ _, letI : normed_space ℝ F := normed_space.restrict_scalars _ 𝕜 _, letI : normed_space ℝ p := (by apply_instance : normed_space ℝ (submodule.restrict_scalars ℝ p)), -- Let `fr: p →L[ℝ] ℝ` be the real part of `f`. let fr := re_clm.comp (f.restrict_scalars ℝ), have fr_apply : ∀ x, fr x = re (f x) := λ x, rfl, -- Use the real version to get a norm-preserving extension of `fr`, which -- we'll call `g : F →L[ℝ] ℝ`. rcases real.exists_extension_norm_eq (p.restrict_scalars ℝ) fr with ⟨g, ⟨hextends, hnormeq⟩⟩, -- Now `g` can be extended to the `F →L[𝕜] 𝕜` we need. use g.extend_to_𝕜, -- It is an extension of `f`. have h : ∀ x : p, g.extend_to_𝕜 x = f x, { assume x, change (g (x : F) : 𝕜) - (I : 𝕜) * g ((((I : 𝕜) • x) : p) : F) = f x, rw [hextends, hextends], change (re (f x) : 𝕜) - (I : 𝕜) * (re (f ((I : 𝕜) • x))) = f x, apply ext, { simp only [add_zero, algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im', zero_mul, of_real_re, eq_self_iff_true, sub_zero, mul_neg_eq_neg_mul_symm, of_real_neg, mul_re, mul_zero, sub_neg_eq_add, continuous_linear_map.map_smul] }, { simp only [algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im', zero_mul, of_real_re, mul_neg_eq_neg_mul_symm, mul_im, zero_add, of_real_neg, mul_re, sub_neg_eq_add, continuous_linear_map.map_smul] } }, refine ⟨h, _⟩, -- And we derive the equality of the norms by bounding on both sides. refine le_antisymm _ _, { calc ∥g.extend_to_𝕜∥ ≤ ∥g∥ : g.extend_to_𝕜.op_norm_le_bound g.op_norm_nonneg (norm_bound _) ... = ∥fr∥ : hnormeq ... ≤ ∥re_clm∥ * ∥f∥ : continuous_linear_map.op_norm_comp_le _ _ ... = ∥f∥ : by rw [norm_re_clm, one_mul] }, { exact f.op_norm_le_bound g.extend_to_𝕜.op_norm_nonneg (λ x, h x ▸ g.extend_to_𝕜.le_op_norm x) }, end end is_R_or_C section dual_vector variables {𝕜 : Type v} [is_R_or_C 𝕜] variables {E : Type u} [normed_group E] [normed_space 𝕜 E] open continuous_linear_equiv submodule open_locale classical lemma coord_norm' (x : E) (h : x ≠ 0) : ∥norm' 𝕜 x • coord 𝕜 x h∥ = 1 := by rw [norm_smul, norm_norm', coord_norm, mul_inv_cancel (mt norm_eq_zero.mp h)] /-- Corollary of Hahn-Banach. Given a nonzero element `x` of a normed space, there exists an element of the dual space, of norm `1`, whose value on `x` is `∥x∥`. -/ theorem exists_dual_vector (x : E) (h : x ≠ 0) : ∃ g : E →L[𝕜] 𝕜, ∥g∥ = 1 ∧ g x = norm' 𝕜 x := begin let p : submodule 𝕜 E := 𝕜 ∙ x, let f := norm' 𝕜 x • coord 𝕜 x h, obtain ⟨g, hg⟩ := exists_extension_norm_eq p f, use g, split, { rw [hg.2, coord_norm'] }, { calc g x = g (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw coe_mk ... = (norm' 𝕜 x • coord 𝕜 x h) (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw ← hg.1 ... = norm' 𝕜 x : by simp [coord_self] } end /-- Variant of Hahn-Banach, eliminating the hypothesis that `x` be nonzero, and choosing the dual element arbitrarily when `x = 0`. -/ theorem exists_dual_vector' [nontrivial E] (x : E) : ∃ g : E →L[𝕜] 𝕜, ∥g∥ = 1 ∧ g x = norm' 𝕜 x := begin by_cases hx : x = 0, { obtain ⟨y, hy⟩ := exists_ne (0 : E), obtain ⟨g, hg⟩ : ∃ g : E →L[𝕜] 𝕜, ∥g∥ = 1 ∧ g y = norm' 𝕜 y := exists_dual_vector y hy, refine ⟨g, hg.left, _⟩, rw [norm'_def, hx, norm_zero, ring_hom.map_zero, continuous_linear_map.map_zero] }, { exact exists_dual_vector x hx } end end dual_vector
9a7a21a81f4b5c2306e44cddf51039da354240ff
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/metric_space/kuratowski.lean
b7107bedd165806bfa23184084e79b83bf59b91d
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
5,213
lean
/- Copyright (c) 2018 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 analysis.normed_space.lp_space import topology.sets.compacts /-! # The Kuratowski embedding Any separable metric space can be embedded isometrically in `ℓ^∞(ℝ)`. -/ noncomputable theory open set metric topological_space open_locale ennreal local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace Kuratowski_embedding /-! ### Any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/ variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α) /-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in a fixed countable set, if this set is dense. This map is given in `Kuratowski_embedding`, without density assumptions. -/ def embedding_of_subset : ℓ_infty_ℝ := ⟨ λ n, dist a (x n) - dist (x 0) (x n), begin apply mem_ℓp_infty, use dist a (x 0), rintros - ⟨n, rfl⟩, exact abs_dist_sub_le _ _ _ end ⟩ lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl /-- The embedding map is always a semi-contraction. -/ lemma embedding_of_subset_dist_le (a b : α) : dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b := begin refine lp.norm_le_of_forall_le dist_nonneg (λn, _), simp only [lp.coe_fn_sub, pi.sub_apply, embedding_of_subset_coe, real.dist_eq], convert abs_dist_sub_le a b (x n) using 2, ring end /-- When the reference set is dense, the embedding map is an isometry on its image. -/ lemma embedding_of_subset_isometry (H : dense_range x) : isometry (embedding_of_subset x) := begin refine isometry.of_dist_eq (λa b, _), refine (embedding_of_subset_dist_le x a b).antisymm (le_of_forall_pos_le_add (λe epos, _)), /- First step: find n with dist a (x n) < e -/ rcases metric.mem_closure_range_iff.1 (H a) (e/2) (half_pos epos) with ⟨n, hn⟩, /- Second step: use the norm control at index n to conclude -/ have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n := by { simp only [embedding_of_subset_coe, sub_sub_sub_cancel_right] }, have := calc dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _ ... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring } ... ≤ 2 * dist a (x n) + |dist b (x n) - dist a (x n)| : by apply_rules [add_le_add_left, le_abs_self] ... ≤ 2 * (e/2) + |embedding_of_subset x b n - embedding_of_subset x a n| : begin rw C, apply_rules [add_le_add, mul_le_mul_of_nonneg_left, hn.le, le_refl], norm_num end ... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) : begin have : |embedding_of_subset x b n - embedding_of_subset x a n| ≤ dist (embedding_of_subset x b) (embedding_of_subset x a), { simpa [dist_eq_norm] using lp.norm_apply_le_norm ennreal.top_ne_zero (embedding_of_subset x b - embedding_of_subset x a) n }, nlinarith, end ... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring, simpa [dist_comm] using this end /-- Every separable metric space embeds isometrically in `ℓ_infty_ℝ`. -/ theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] : ∃(f : α → ℓ_infty_ℝ), isometry f := begin cases (univ : set α).eq_empty_or_nonempty with h h, { use (λ_, 0), assume x, exact absurd h (nonempty.ne_empty ⟨x, mem_univ x⟩) }, { /- We construct a map x : ℕ → α with dense image -/ rcases h with ⟨basepoint⟩, haveI : inhabited α := ⟨basepoint⟩, have : ∃s:set α, s.countable ∧ dense s := exists_countable_dense α, rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩, rcases set.countable_iff_exists_subset_range.1 S_countable with ⟨x, x_range⟩, /- Use embedding_of_subset to construct the desired isometry -/ exact ⟨embedding_of_subset x, embedding_of_subset_isometry x (S_dense.mono x_range)⟩ } end end Kuratowski_embedding open topological_space Kuratowski_embedding /-- The Kuratowski embedding is an isometric embedding of a separable metric space in `ℓ^∞(ℝ)`. -/ def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ := classical.some (Kuratowski_embedding.exists_isometric_embedding α) /-- The Kuratowski embedding is an isometry. -/ protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] : isometry (Kuratowski_embedding α) := classical.some_spec (exists_isometric_embedding α) /-- Version of the Kuratowski embedding for nonempty compacts -/ def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α] [nonempty α] : nonempty_compacts ℓ_infty_ℝ := { carrier := range (Kuratowski_embedding α), compact' := is_compact_range (Kuratowski_embedding.isometry α).continuous, nonempty' := range_nonempty _ }
da9e3728e0162a4efc82d6321e9f7c33a9cfa09c
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/witt_vector/teichmuller.lean
4e4092ca973242d21ef87ef17350554c0a2307d6
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,469
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.witt_vector.basic /-! # Teichmüller lifts This file defines `witt_vector.teichmuller`, a monoid hom `R →* 𝕎 R`, which embeds `r : R` as the `0`-th component of a Witt vector whose other coefficients are `0`. ## Main declarations - `witt_vector.teichmuller`: the Teichmuller map. - `witt_vector.map_teichmuller`: `witt_vector.teichmuller` is a natural transformation. - `witt_vector.ghost_component_teichmuller`: the `n`-th ghost component of `witt_vector.teichmuller p r` is `r ^ p ^ n`. ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ namespace witt_vector open mv_polynomial variables (p : ℕ) {R S : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S] local notation `𝕎` := witt_vector p -- type as `\bbW` /-- The underlying function of the monoid hom `witt_vector.teichmuller`. The `0`-th coefficient of `teichmuller_fun p r` is `r`, and all others are `0`. -/ def teichmuller_fun (r : R) : 𝕎 R := ⟨p, λ n, if n = 0 then r else 0⟩ /-! ## `teichmuller` is a monoid homomorphism On ghost components, it is clear that `teichmuller_fun` is a monoid homomorphism. But in general the ghost map is not injective. We follow the same strategy as for proving that the ring operations on `𝕎 R` satisfy the ring axioms. 1. We first prove it for rings `R` where `p` is invertible, because then the ghost map is in fact an isomorphism. 2. After that, we derive the result for `mv_polynomial R ℤ`, 3. and from that we can prove the result for arbitrary `R`. -/ include hp private lemma ghost_component_teichmuller_fun (r : R) (n : ℕ) : ghost_component n (teichmuller_fun p r) = r ^ p ^ n := begin rw [ghost_component_apply, aeval_witt_polynomial, finset.sum_eq_single 0, pow_zero, one_mul, nat.sub_zero], { refl }, { intros i hi h0, convert mul_zero _, convert zero_pow _, { cases i, { contradiction }, { refl } }, { exact pow_pos hp.1.pos _ } }, { rw finset.mem_range, intro h, exact (h (nat.succ_pos n)).elim } end private lemma map_teichmuller_fun (f : R →+* S) (r : R) : map f (teichmuller_fun p r) = teichmuller_fun p (f r) := by { ext n, cases n, { refl }, { exact f.map_zero } } private lemma teichmuller_mul_aux₁ (x y : mv_polynomial R ℚ) : teichmuller_fun p (x * y) = teichmuller_fun p x * teichmuller_fun p y := begin apply (ghost_map.bijective_of_invertible p (mv_polynomial R ℚ)).1, rw ring_hom.map_mul, ext1 n, simp only [pi.mul_apply, ghost_map_apply, ghost_component_teichmuller_fun, mul_pow], end private lemma teichmuller_mul_aux₂ (x y : mv_polynomial R ℤ) : teichmuller_fun p (x * y) = teichmuller_fun p x * teichmuller_fun p y := begin refine map_injective (mv_polynomial.map (int.cast_ring_hom ℚ)) (mv_polynomial.map_injective _ int.cast_injective) _, simp only [teichmuller_mul_aux₁, map_teichmuller_fun, ring_hom.map_mul] end /-- The Teichmüller lift of an element of `R` to `𝕎 R`. The `0`-th coefficient of `teichmuller p r` is `r`, and all others are `0`. This is a monoid homomorphism. -/ noncomputable def teichmuller : R →* 𝕎 R := { to_fun := teichmuller_fun p, map_one' := begin ext ⟨⟩, { rw one_coeff_zero, refl }, { rw one_coeff_eq_of_pos _ _ _ (nat.succ_pos n), refl } end, map_mul' := begin intros x y, rcases counit_surjective R x with ⟨x, rfl⟩, rcases counit_surjective R y with ⟨y, rfl⟩, simp only [← map_teichmuller_fun, ← ring_hom.map_mul, teichmuller_mul_aux₂], end } @[simp] lemma teichmuller_coeff_zero (r : R) : (teichmuller p r).coeff 0 = r := rfl @[simp] lemma teichmuller_coeff_pos (r : R) : ∀ (n : ℕ) (hn : 0 < n), (teichmuller p r).coeff n = 0 | (n+1) _ := rfl. @[simp] lemma teichmuller_zero : teichmuller p (0:R) = 0 := by ext ⟨⟩; { rw zero_coeff, refl } /-- `teichmuller` is a natural transformation. -/ @[simp] lemma map_teichmuller (f : R →+* S) (r : R) : map f (teichmuller p r) = teichmuller p (f r) := map_teichmuller_fun _ _ _ /-- The `n`-th ghost component of `teichmuller p r` is `r ^ p ^ n`. -/ @[simp] lemma ghost_component_teichmuller (r : R) (n : ℕ) : ghost_component n (teichmuller p r) = r ^ p ^ n := ghost_component_teichmuller_fun _ _ _ end witt_vector
09d4294fcb72baa2364b01f51e516c679ba6add5
618003631150032a5676f229d13a079ac875ff77
/test/delta_instance.lean
cbccb697901af9bc30a26687b73bddefacc162bc
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
836
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.set import algebra.category.Mon.basic @[derive has_coe_to_sort] def X : Type := set ℕ @[derive ring] def T := ℤ class binclass (T1 T2 : Type) instance : binclass ℤ ℤ := ⟨⟩ @[derive [ring, binclass ℤ]] def U := ℤ @[derive λ α, binclass α ℤ] def V := ℤ @[derive ring] def id_ring (α) [ring α] : Type := α @[derive decidable_eq] def S := ℕ @[derive decidable_eq] inductive P | a | b | c open category_theory -- Test that `delta_instance` works in the presence of universe metavariables. attribute [derive large_category] Mon -- test deriving instances on function types @[derive monad] meta def my_tactic : Type → Type := tactic
e7f7194de41717ea5449cb34eab805a4d67db200
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/set/lattice.lean
3cf03ee67fa3f6d82b29ce76b4246b697a47c1a7
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
70,775
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import data.nat.basic import order.complete_boolean_algebra import order.directed import order.galois_connection /-! # The set lattice This file provides usual set notation for unions and intersections, a `complete_lattice` instance for `set α`, and some more set constructions. ## Main declarations * `set.Union`: Union of an indexed family of sets. * `set.Inter`: Intersection of an indexed family of sets. * `set.sInter`: **s**et **Inter**. Intersection of sets belonging to a set of sets. * `set.sUnion`: **s**et **Union**. Union of sets belonging to a set of sets. This is actually defined in core Lean. * `set.sInter_eq_bInter`, `set.sUnion_eq_bInter`: Shows that `⋂₀ s = ⋂ x ∈ s, x` and `⋃₀ s = ⋃ x ∈ s, x`. * `set.complete_boolean_algebra`: `set α` is a `complete_boolean_algebra` with `≤ = ⊆`, `< = ⊂`, `⊓ = ∩`, `⊔ = ∪`, `⨅ = ⋂`, `⨆ = ⋃` and `\` as the set difference. See `set.boolean_algebra`. * `set.kern_image`: For a function `f : α → β`, `s.kern_image f` is the set of `y` such that `f ⁻¹ y ⊆ s`. * `set.seq`: Union of the image of a set under a **seq**uence of functions. `seq s t` is the union of `f '' t` over all `f ∈ s`, where `t : set α` and `s : set (α → β)`. * `set.Union_eq_sigma_of_disjoint`: Equivalence between `⋃ i, t i` and `Σ i, t i`, where `t` is an indexed family of disjoint sets. ## Naming convention In lemma names, * `⋃ i, s i` is called `Union` * `⋂ i, s i` is called `Inter` * `⋃ i j, s i j` is called `Union₂`. This is a `Union` inside a `Union`. * `⋂ i j, s i j` is called `Inter₂`. This is an `Inter` inside an `Inter`. * `⋃ i ∈ s, t i` is called `bUnion` for "bounded `Union`". This is the special case of `Union₂` where `j : i ∈ s`. * `⋂ i ∈ s, t i` is called `bInter` for "bounded `Inter`". This is the special case of `Inter₂` where `j : i ∈ s`. ## Notation * `⋃`: `set.Union` * `⋂`: `set.Inter` * `⋃₀`: `set.sUnion` * `⋂₀`: `set.sInter` -/ open function tactic set universes u variables {α β γ : Type*} {ι ι' ι₂ : Sort*} {κ κ₁ κ₂ : ι → Sort*} {κ' : ι' → Sort*} namespace set /-! ### Complete lattice and complete Boolean algebra instances -/ instance : has_Inf (set α) := ⟨λ s, {a | ∀ t ∈ s, a ∈ t}⟩ instance : has_Sup (set α) := ⟨λ s, {a | ∃ t ∈ s, a ∈ t}⟩ /-- Intersection of a set of sets. -/ def sInter (S : set (set α)) : set α := Inf S /-- Union of a set of sets. -/ def sUnion (S : set (set α)) : set α := Sup S prefix `⋂₀ `:110 := sInter prefix `⋃₀ `:110 := sUnion @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl @[simp] theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃ t ∈ S, x ∈ t := iff.rfl /-- Indexed union of a family of sets -/ def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] lemma Sup_eq_sUnion (S : set (set α)) : Sup S = ⋃₀ S := rfl @[simp] lemma Inf_eq_sInter (S : set (set α)) : Inf S = ⋂₀ S := rfl @[simp] lemma supr_eq_Union (s : ι → set α) : supr s = Union s := rfl @[simp] lemma infi_eq_Inter (s : ι → set α) : infi s = Inter s := rfl @[simp] lemma mem_Union {x : α} {s : ι → set α} : x ∈ (⋃ i, s i) ↔ ∃ i, x ∈ s i := ⟨λ ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, λ ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ @[simp] lemma mem_Inter {x : α} {s : ι → set α} : x ∈ (⋂ i, s i) ↔ ∀ i, x ∈ s i := ⟨λ (h : ∀ a ∈ {a : set α | ∃ i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, λ h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ lemma mem_Union₂ {x : γ} {s : Π i, κ i → set γ} : x ∈ (⋃ i j, s i j) ↔ ∃ i j, x ∈ s i j := by simp_rw mem_Union lemma mem_Inter₂ {x : γ} {s : Π i, κ i → set γ} : x ∈ (⋂ i j, s i j) ↔ ∀ i j, x ∈ s i j := by simp_rw mem_Inter lemma mem_Union_of_mem {s : ι → set α} {a : α} (i : ι) (ha : a ∈ s i) : a ∈ ⋃ i, s i := mem_Union.2 ⟨i, ha⟩ lemma mem_Union₂_of_mem {s : Π i, κ i → set α} {a : α} {i : ι} (j : κ i) (ha : a ∈ s i j) : a ∈ ⋃ i j, s i j := mem_Union₂.2 ⟨i, j, ha⟩ lemma mem_Inter_of_mem {s : ι → set α} {a : α} (h : ∀ i, a ∈ s i) : a ∈ ⋂ i, s i := mem_Inter.2 h lemma mem_Inter₂_of_mem {s : Π i, κ i → set α} {a : α} (h : ∀ i j, a ∈ s i j) : a ∈ ⋂ i j, s i j := mem_Inter₂.2 h instance : complete_boolean_algebra (set α) := { Sup := Sup, Inf := Inf, le_Sup := λ s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := λ s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, le_Inf := λ s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := λ s t t_in a h, h _ t_in, infi_sup_le_sup_Inf := λ s S x, iff.mp $ by simp [forall_or_distrib_left], inf_Sup_le_supr_inf := λ s S x, iff.mp $ by simp [exists_and_distrib_left], .. set.boolean_algebra } /-- `set.image` is monotone. See `set.image_image` for the statement in terms of `⊆`. -/ lemma monotone_image {f : α → β} : monotone (image f) := λ s t, image_subset _ theorem _root_.monotone.inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∩ g x) := hf.inf hg theorem _root_.monotone_on.inter [preorder β] {f g : β → set α} {s : set β} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x ∩ g x) s := hf.inf hg theorem _root_.antitone.inter [preorder β] {f g : β → set α} (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ∩ g x) := hf.inf hg theorem _root_.antitone_on.inter [preorder β] {f g : β → set α} {s : set β} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x ∩ g x) s := hf.inf hg theorem _root_.monotone.union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∪ g x) := hf.sup hg theorem _root_.monotone_on.union [preorder β] {f g : β → set α} {s : set β} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x ∪ g x) s := hf.sup hg theorem _root_.antitone.union [preorder β] {f g : β → set α} (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ∪ g x) := hf.sup hg theorem _root_.antitone_on.union [preorder β] {f g : β → set α} {s : set β} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x ∪ g x) s := hf.sup hg theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀ b, monotone (λ a, p a b)) : monotone (λ a, {b | p a b}) := λ a a' h b, hp b h theorem antitone_set_of [preorder α] {p : α → β → Prop} (hp : ∀ b, antitone (λ a, p a b)) : antitone (λ a, {b | p a b}) := λ a a' h b, hp b h /-- Quantifying over a set is antitone in the set -/ lemma antitone_bforall {P : α → Prop} : antitone (λ s : set α, ∀ x ∈ s, P x) := λ s t hst h x hx, h x $ hst hx section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := λ a b, image_subset_iff /-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s`. -/ def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := λ a b, ⟨ λ h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, λ h x (hx : f x ∈ a), h hx rfl⟩ end galois_connection /-! ### Union and intersection over an indexed family of sets -/ instance : order_top (set α) := { top := univ, le_top := by simp } @[congr] theorem Union_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Union f₁ = Union f₂ := supr_congr_Prop pq f @[congr] theorem Inter_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Inter f₁ = Inter f₂ := infi_congr_Prop pq f lemma Union_eq_if {p : Prop} [decidable p] (s : set α) : (⋃ h : p, s) = if p then s else ∅ := supr_eq_if _ lemma Union_eq_dif {p : Prop} [decidable p] (s : p → set α) : (⋃ (h : p), s h) = if h : p then s h else ∅ := supr_eq_dif _ lemma Inter_eq_if {p : Prop} [decidable p] (s : set α) : (⋂ h : p, s) = if p then s else univ := infi_eq_if _ lemma Infi_eq_dif {p : Prop} [decidable p] (s : p → set α) : (⋂ (h : p), s h) = if h : p then s h else univ := infi_eq_dif _ lemma exists_set_mem_of_union_eq_top {ι : Type*} (t : set ι) (s : ι → set β) (w : (⋃ i ∈ t, s i) = ⊤) (x : β) : ∃ (i ∈ t), x ∈ s i := begin have p : x ∈ ⊤ := set.mem_univ x, simpa only [←w, set.mem_Union] using p, end lemma nonempty_of_union_eq_top_of_nonempty {ι : Type*} (t : set ι) (s : ι → set α) (H : nonempty α) (w : (⋃ i ∈ t, s i) = ⊤) : t.nonempty := begin obtain ⟨x, m, -⟩ := exists_set_mem_of_union_eq_top t s w H.some, exact ⟨x, m⟩, end theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} := ext $ λ i, mem_Union.symm theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} := ext $ λ i, mem_Inter.symm lemma Union_subset {s : ι → set α} {t : set α} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := @supr_le (set α) _ _ _ _ h lemma Union₂_subset {s : Π i, κ i → set α} {t : set α} (h : ∀ i j, s i j ⊆ t) : (⋃ i j, s i j) ⊆ t := Union_subset $ λ x, Union_subset (h x) theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := @le_infi (set β) _ _ _ _ h lemma subset_Inter₂ {s : set α} {t : Π i, κ i → set α} (h : ∀ i j, s ⊆ t i j) : s ⊆ ⋂ i j, t i j := subset_Inter $ λ x, subset_Inter $ h x @[simp] lemma Union_subset_iff {s : ι → set α} {t : set α} : (⋃ i, s i) ⊆ t ↔ ∀ i, s i ⊆ t := ⟨λ h i, subset.trans (le_supr s _) h, Union_subset⟩ lemma Union₂_subset_iff {s : Π i, κ i → set α} {t : set α} : (⋃ i j, s i j) ⊆ t ↔ ∀ i j, s i j ⊆ t := by simp_rw Union_subset_iff @[simp] lemma subset_Inter_iff {s : set α} {t : ι → set α} : s ⊆ (⋂ i, t i) ↔ ∀ i, s ⊆ t i := @le_infi_iff (set α) _ _ _ _ @[simp] lemma subset_Inter₂_iff {s : set α} {t : Π i, κ i → set α} : s ⊆ (⋂ i j, t i j) ↔ ∀ i j, s ⊆ t i j := by simp_rw subset_Inter_iff lemma subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ ⋃ i, s i := le_supr lemma Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le lemma subset_Union₂ {s : Π i, κ i → set α} (i : ι) (j : κ i) : s i j ⊆ ⋃ i j, s i j := @le_supr₂ (set α) _ _ _ _ i j lemma Inter₂_subset {s : Π i, κ i → set α} (i : ι) (j : κ i) : (⋂ i j, s i j) ⊆ s i j := @infi₂_le (set α) _ _ _ _ i j /-- This rather trivial consequence of `subset_Union`is convenient with `apply`, and has `i` explicit for this purpose. -/ lemma subset_Union_of_subset {s : set α} {t : ι → set α} (i : ι) (h : s ⊆ t i) : s ⊆ ⋃ i, t i := @le_supr_of_le (set α) _ _ _ _ i h /-- This rather trivial consequence of `Inter_subset`is convenient with `apply`, and has `i` explicit for this purpose. -/ lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t := @infi_le_of_le (set α) _ _ _ _ i h lemma Union_mono {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋃ i, s i) ⊆ ⋃ i, t i := @supr_mono (set α) _ _ s t h lemma Union₂_mono {s t : Π i, κ i → set α} (h : ∀ i j, s i j ⊆ t i j) : (⋃ i j, s i j) ⊆ ⋃ i j, t i j := @supr₂_mono (set α) _ _ _ s t h lemma Inter_mono {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ ⋂ i, t i := @infi_mono (set α) _ _ s t h lemma Inter₂_mono {s t : Π i, κ i → set α} (h : ∀ i j, s i j ⊆ t i j) : (⋂ i j, s i j) ⊆ ⋂ i j, t i j := @infi₂_mono (set α) _ _ _ s t h lemma Union_mono' {s : ι → set α} {t : ι₂ → set α} (h : ∀ i, ∃ j, s i ⊆ t j) : (⋃ i, s i) ⊆ ⋃ i, t i := @supr_mono' (set α) _ _ _ s t h lemma Union₂_mono' {s : Π i, κ i → set α} {t : Π i', κ' i' → set α} (h : ∀ i j, ∃ i' j', s i j ⊆ t i' j') : (⋃ i j, s i j) ⊆ ⋃ i' j', t i' j' := @supr₂_mono' (set α) _ _ _ _ _ s t h lemma Inter_mono' {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) : (⋂ i, s i) ⊆ (⋂ j, t j) := set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi lemma Inter₂_mono' {s : Π i, κ i → set α} {t : Π i', κ' i' → set α} (h : ∀ i' j', ∃ i j, s i j ⊆ t i' j') : (⋂ i j, s i j) ⊆ ⋂ i' j', t i' j' := subset_Inter₂_iff.2 $ λ i' j', let ⟨i, j, hst⟩ := h i' j' in (Inter₂_subset _ _).trans hst lemma Union₂_subset_Union (κ : ι → Sort*) (s : ι → set α) : (⋃ i (j : κ i), s i) ⊆ ⋃ i, s i := Union_mono $ λ i, Union_subset $ λ h, subset.rfl lemma Inter_subset_Inter₂ (κ : ι → Sort*) (s : ι → set α) : (⋂ i, s i) ⊆ ⋂ i (j : κ i), s i := Inter_mono $ λ i, subset_Inter $ λ h, subset.rfl lemma Union_set_of (P : ι → α → Prop) : (⋃ i, {x : α | P i x}) = {x : α | ∃ i, P i x} := by { ext, exact mem_Union } lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x}) = {x : α | ∀ i, P i x} := by { ext, exact mem_Inter } lemma Union_congr_of_surjective {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋃ x, f x) = ⋃ y, g y := h1.supr_congr h h2 lemma Inter_congr_of_surjective {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋂ x, f x) = ⋂ y, g y := h1.infi_congr h h2 theorem Union_const [nonempty ι] (s : set β) : (⋃ i : ι, s) = s := supr_const theorem Inter_const [nonempty ι] (s : set β) : (⋂ i : ι, s) = s := infi_const @[simp] theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) := compl_supr lemma compl_Union₂ (s : Π i, κ i → set α) : (⋃ i j, s i j)ᶜ = ⋂ i j, (s i j)ᶜ := by simp_rw compl_Union @[simp] theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) := compl_infi lemma compl_Inter₂ (s : Π i, κ i → set α) : (⋂ i j, s i j)ᶜ = ⋃ i j, (s i j)ᶜ := by simp_rw compl_Inter -- classical -- complete_boolean_algebra theorem Union_eq_compl_Inter_compl (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ := by simp only [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_compl_Union_compl (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ := by simp only [compl_Union, compl_compl] theorem inter_Union (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := inf_supr_eq _ _ theorem Union_inter (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := supr_inf_eq _ _ theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := supr_sup_eq theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := infi_inf_eq theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := sup_supr theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := supr_sup theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := inf_infi theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := infi_inf -- classical theorem union_Inter (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := sup_infi_eq _ _ theorem Inter_union (s : ι → set β) (t : set β) : (⋂ i, s i) ∪ t = ⋂ i, s i ∪ t := infi_sup_eq _ _ theorem Union_diff (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := Union_inter _ _ theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter]; refl theorem diff_Inter (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union]; refl lemma directed_on_Union {r} {f : ι → set α} (hd : directed (⊆) f) (h : ∀ x, directed_on r (f x)) : directed_on r (⋃ x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact λ a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ lemma Union_inter_subset {ι α} {s t : ι → set α} : (⋃ i, s i ∩ t i) ⊆ (⋃ i, s i) ∩ (⋃ i, t i) := le_supr_inf_supr s t lemma Union_inter_of_monotone {ι α} [preorder ι] [is_directed ι (≤)] {s t : ι → set α} (hs : monotone s) (ht : monotone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) := supr_inf_of_monotone hs ht lemma Union_inter_of_antitone {ι α} [preorder ι] [is_directed ι (swap (≤))] {s t : ι → set α} (hs : antitone s) (ht : antitone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) := supr_inf_of_antitone hs ht lemma Inter_union_of_monotone {ι α} [preorder ι] [is_directed ι (swap (≤))] {s t : ι → set α} (hs : monotone s) (ht : monotone t) : (⋂ i, s i ∪ t i) = (⋂ i, s i) ∪ (⋂ i, t i) := infi_sup_of_monotone hs ht lemma Inter_union_of_antitone {ι α} [preorder ι] [is_directed ι (≤)] {s t : ι → set α} (hs : antitone s) (ht : antitone t) : (⋂ i, s i ∪ t i) = (⋂ i, s i) ∪ (⋂ i, t i) := infi_sup_of_antitone hs ht /-- An equality version of this lemma is `Union_Inter_of_monotone` in `data.set.finite`. -/ lemma Union_Inter_subset {s : ι → ι' → set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j := supr_infi_le_infi_supr (flip s) lemma Union_option {ι} (s : option ι → set α) : (⋃ o, s o) = s none ∪ ⋃ i, s (some i) := supr_option s lemma Inter_option {ι} (s : option ι → set α) : (⋂ o, s o) = s none ∩ ⋂ i, s (some i) := infi_option s section variables (p : ι → Prop) [decidable_pred p] lemma Union_dite (f : Π i, p i → set α) (g : Π i, ¬p i → set α) : (⋃ i, if h : p i then f i h else g i h) = (⋃ i (h : p i), f i h) ∪ (⋃ i (h : ¬ p i), g i h) := supr_dite _ _ _ lemma Union_ite (f g : ι → set α) : (⋃ i, if p i then f i else g i) = (⋃ i (h : p i), f i) ∪ (⋃ i (h : ¬ p i), g i) := Union_dite _ _ _ lemma Inter_dite (f : Π i, p i → set α) (g : Π i, ¬p i → set α) : (⋂ i, if h : p i then f i h else g i h) = (⋂ i (h : p i), f i h) ∩ (⋂ i (h : ¬ p i), g i h) := infi_dite _ _ _ lemma Inter_ite (f g : ι → set α) : (⋂ i, if p i then f i else g i) = (⋂ i (h : p i), f i) ∩ (⋂ i (h : ¬ p i), g i) := Inter_dite _ _ _ end lemma image_projection_prod {ι : Type*} {α : ι → Type*} {v : Π (i : ι), set (α i)} (hv : (pi univ v).nonempty) (i : ι) : (λ (x : Π (i : ι), α i), x i) '' (⋂ k, (λ (x : Π (j : ι), α j), x k) ⁻¹' v k) = v i:= begin classical, apply subset.antisymm, { simp [Inter_subset] }, { intros y y_in, simp only [mem_image, mem_Inter, mem_preimage], rcases hv with ⟨z, hz⟩, refine ⟨function.update z i y, _, update_same i y z⟩, rw @forall_update_iff ι α _ z i y (λ i t, t ∈ v i), exact ⟨y_in, λ j hj, by simpa using hz j⟩ }, end /-! ### Unions and intersections indexed by `Prop` -/ @[simp] theorem Inter_false {s : false → set α} : Inter s = univ := infi_false @[simp] theorem Union_false {s : false → set α} : Union s = ∅ := supr_false @[simp] theorem Inter_true {s : true → set α} : Inter s = s trivial := infi_true @[simp] theorem Union_true {s : true → set α} : Union s = s trivial := supr_true @[simp] theorem Inter_exists {p : ι → Prop} {f : Exists p → set α} : (⋂ x, f x) = (⋂ i (h : p i), f ⟨i, h⟩) := infi_exists @[simp] theorem Union_exists {p : ι → Prop} {f : Exists p → set α} : (⋃ x, f x) = (⋃ i (h : p i), f ⟨i, h⟩) := supr_exists @[simp] lemma Union_empty : (⋃ i : ι, ∅ : set α) = ∅ := supr_bot @[simp] lemma Inter_univ : (⋂ i : ι, univ : set α) = univ := infi_top section variables {s : ι → set α} @[simp] lemma Union_eq_empty : (⋃ i, s i) = ∅ ↔ ∀ i, s i = ∅ := supr_eq_bot @[simp] lemma Inter_eq_univ : (⋂ i, s i) = univ ↔ ∀ i, s i = univ := infi_eq_top @[simp] lemma nonempty_Union : (⋃ i, s i).nonempty ↔ ∃ i, (s i).nonempty := by simp [← ne_empty_iff_nonempty] @[simp] lemma nonempty_bUnion {t : set α} {s : α → set β} : (⋃ i ∈ t, s i).nonempty ↔ ∃ i ∈ t, (s i).nonempty := by simp [← ne_empty_iff_nonempty] lemma Union_nonempty_index (s : set α) (t : s.nonempty → set β) : (⋃ h, t h) = ⋃ x ∈ s, t ⟨x, ‹_›⟩ := supr_exists end @[simp] theorem Inter_Inter_eq_left {b : β} {s : Π x : β, x = b → set α} : (⋂ x (h : x = b), s x h) = s b rfl := infi_infi_eq_left @[simp] theorem Inter_Inter_eq_right {b : β} {s : Π x : β, b = x → set α} : (⋂ x (h : b = x), s x h) = s b rfl := infi_infi_eq_right @[simp] theorem Union_Union_eq_left {b : β} {s : Π x : β, x = b → set α} : (⋃ x (h : x = b), s x h) = s b rfl := supr_supr_eq_left @[simp] theorem Union_Union_eq_right {b : β} {s : Π x : β, b = x → set α} : (⋃ x (h : b = x), s x h) = s b rfl := supr_supr_eq_right theorem Inter_or {p q : Prop} (s : p ∨ q → set α) : (⋂ h, s h) = (⋂ h : p, s (or.inl h)) ∩ (⋂ h : q, s (or.inr h)) := infi_or theorem Union_or {p q : Prop} (s : p ∨ q → set α) : (⋃ h, s h) = (⋃ i, s (or.inl i)) ∪ (⋃ j, s (or.inr j)) := supr_or theorem Union_and {p q : Prop} (s : p ∧ q → set α) : (⋃ h, s h) = ⋃ hp hq, s ⟨hp, hq⟩ := supr_and theorem Inter_and {p q : Prop} (s : p ∧ q → set α) : (⋂ h, s h) = ⋂ hp hq, s ⟨hp, hq⟩ := infi_and lemma Union_comm (s : ι → ι' → set α) : (⋃ i i', s i i') = ⋃ i' i, s i i' := supr_comm lemma Inter_comm (s : ι → ι' → set α) : (⋂ i i', s i i') = ⋂ i' i, s i i' := infi_comm lemma Union₂_comm (s : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → set α) : (⋃ i₁ j₁ i₂ j₂, s i₁ j₁ i₂ j₂) = ⋃ i₂ j₂ i₁ j₁, s i₁ j₁ i₂ j₂ := supr₂_comm _ lemma Inter₂_comm (s : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → set α) : (⋂ i₁ j₁ i₂ j₂, s i₁ j₁ i₂ j₂) = ⋂ i₂ j₂ i₁ j₁, s i₁ j₁ i₂ j₂ := infi₂_comm _ @[simp] theorem bUnion_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) : (⋃ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) = ⋃ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [Union_and, @Union_comm _ ι'] @[simp] theorem bUnion_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) : (⋃ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) = ⋃ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [Union_and, @Union_comm _ ι] @[simp] theorem bInter_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) : (⋂ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) = ⋂ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [Inter_and, @Inter_comm _ ι'] @[simp] theorem bInter_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) : (⋂ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) = ⋂ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [Inter_and, @Inter_comm _ ι] @[simp] theorem Union_Union_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} : (⋃ x h, s x h) = s b (or.inl rfl) ∪ ⋃ x (h : p x), s x (or.inr h) := by simp only [Union_or, Union_union_distrib, Union_Union_eq_left] @[simp] theorem Inter_Inter_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} : (⋂ x h, s x h) = s b (or.inl rfl) ∩ ⋂ x (h : p x), s x (or.inr h) := by simp only [Inter_or, Inter_inter_distrib, Inter_Inter_eq_left] /-! ### Bounded unions and intersections -/ /-- A specialization of `mem_Union₂`. -/ theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := mem_Union₂_of_mem xs ytx /-- A specialization of `mem_Inter₂`. -/ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := mem_Inter₂_of_mem h /-- A specialization of `subset_Union₂`. -/ theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := subset_Union₂ x xs /-- A specialization of `Inter₂_subset`. -/ theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := Inter₂_subset x xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := Union₂_subset $ λ x hx, subset_bUnion_of_mem $ h hx theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_Inter₂ $ λ x hx, bInter_subset_of_mem $ h hx lemma bUnion_mono {s s' : set α} {t t' : α → set β} (hs : s' ⊆ s) (h : ∀ x ∈ s, t x ⊆ t' x) : (⋃ x ∈ s', t x) ⊆ ⋃ x ∈ s, t' x := (bUnion_subset_bUnion_left hs).trans $ Union₂_mono h lemma bInter_mono {s s' : set α} {t t' : α → set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s', t x) ⊆ (⋂ x ∈ s, t' x) := (bInter_subset_bInter_left hs).trans $ Inter₂_mono h lemma Union_congr {s t : ι → set α} (h : ∀ i, s i = t i) : (⋃ i, s i) = ⋃ i, t i := supr_congr h lemma Inter_congr {s t : ι → set α} (h : ∀ i, s i = t i) : (⋂ i, s i) = ⋂ i, t i := infi_congr h lemma Union₂_congr {s t : Π i, κ i → set α} (h : ∀ i j, s i j = t i j) : (⋃ i j, s i j) = ⋃ i j, t i j := Union_congr $ λ i, Union_congr $ h i lemma Inter₂_congr {s t : Π i, κ i → set α} (h : ∀ i j, s i j = t i j) : (⋂ i j, s i j) = ⋂ i j, t i j := Inter_congr $ λ i, Inter_congr $ h i theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) : (⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) := supr_subtype' theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) : (⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) := infi_subtype' theorem Union_subtype (p : α → Prop) (s : {x // p x} → set β) : (⋃ x : {x // p x}, s x) = ⋃ x (hx : p x), s ⟨x, hx⟩ := supr_subtype theorem Inter_subtype (p : α → Prop) (s : {x // p x} → set β) : (⋂ x : {x // p x}, s x) = ⋂ x (hx : p x), s ⟨x, hx⟩ := infi_subtype theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := infi_emptyset theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ @[simp] lemma bUnion_self (s : set α) : (⋃ x ∈ s, s) = s := subset.antisymm (Union₂_subset $ λ x hx, subset.refl s) (λ x hx, mem_bUnion hx hx) @[simp] lemma Union_nonempty_self (s : set α) : (⋃ h : s.nonempty, s) = s := by rw [Union_nonempty_index, bUnion_self] -- TODO(Jeremy): here is an artifact of the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := infi_singleton theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := by simp -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by rw [bInter_insert, bInter_singleton] lemma bInter_inter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) : (⋂ i ∈ s, f i ∩ t) = (⋂ i ∈ s, f i) ∩ t := begin haveI : nonempty s := hs.to_subtype, simp [bInter_eq_Inter, ← Inter_inter] end lemma inter_bInter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) : (⋂ i ∈ s, t ∩ f i) = t ∩ ⋂ i ∈ s, f i := begin rw [inter_comm, ← bInter_inter hs], simp [inter_comm] end theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union @[simp] lemma Union_coe_set {α β : Type*} (s : set α) (f : s → set β) : (⋃ i, f i) = ⋃ i ∈ s, f ⟨i, ‹i ∈ s›⟩ := Union_subtype _ _ @[simp] lemma Inter_coe_set {α β : Type*} (s : set α) (f : s → set β) : (⋂ i, f i) = ⋂ i ∈ s, f ⟨i, ‹i ∈ s›⟩ := Inter_subtype _ _ theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := by simp theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by simp lemma inter_Union₂ (s : set α) (t : Π i, κ i → set α) : s ∩ (⋃ i j, t i j) = ⋃ i j, s ∩ t i j := by simp only [inter_Union] lemma Union₂_inter (s : Π i, κ i → set α) (t : set α) : (⋃ i j, s i j) ∩ t = ⋃ i j, s i j ∩ t := by simp_rw Union_inter theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ht, hx⟩ -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := λ h, hx ⟨t, ht, h⟩ theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀ t := subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t := Sup_le h @[simp] theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀ t' ∈ s, t' ⊆ t := @Sup_le_iff (set α) _ _ _ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h @[simp] theorem subset_sInter_iff {S : set (set α)} {t : set α} : t ⊆ (⋂₀ S) ↔ ∀ t' ∈ S, t ⊆ t' := @le_Inf_iff (set α) _ _ _ theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton @[simp] theorem sUnion_eq_empty {S : set (set α)} : (⋃₀ S) = ∅ ↔ ∀ s ∈ S, s = ∅ := Sup_eq_bot @[simp] theorem sInter_eq_univ {S : set (set α)} : (⋂₀ S) = univ ↔ ∀ s ∈ S, s = univ := Inf_eq_top @[simp] theorem nonempty_sUnion {S : set (set α)} : (⋃₀ S).nonempty ↔ ∃ s ∈ S, set.nonempty s := by simp [← ne_empty_iff_nonempty] lemma nonempty.of_sUnion {s : set (set α)} (h : (⋃₀ s).nonempty) : s.nonempty := let ⟨s, hs, _⟩ := nonempty_sUnion.1 h in ⟨s, hs⟩ lemma nonempty.of_sUnion_eq_univ [nonempty α] {s : set (set α)} (h : ⋃₀ s = univ) : s.nonempty := nonempty.of_sUnion $ h.symm ▸ univ_nonempty theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert @[simp] lemma sUnion_diff_singleton_empty (s : set (set α)) : ⋃₀ (s \ {∅}) = ⋃₀ s := Sup_diff_singleton_bot s @[simp] lemma sInter_diff_singleton_univ (s : set (set α)) : ⋂₀ (s \ {univ}) = ⋂₀ s := Inf_diff_singleton_top s theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := Sup_pair theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := Inf_pair @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image @[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl @[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl lemma Union_eq_univ_iff {f : ι → set α} : (⋃ i, f i) = univ ↔ ∀ x, ∃ i, x ∈ f i := by simp only [eq_univ_iff_forall, mem_Union] lemma Union₂_eq_univ_iff {s : Π i, κ i → set α} : (⋃ i j, s i j) = univ ↔ ∀ a, ∃ i j, a ∈ s i j := by simp only [Union_eq_univ_iff, mem_Union] lemma sUnion_eq_univ_iff {c : set (set α)} : ⋃₀ c = univ ↔ ∀ a, ∃ b ∈ c, a ∈ b := by simp only [eq_univ_iff_forall, mem_sUnion] -- classical lemma Inter_eq_empty_iff {f : ι → set α} : (⋂ i, f i) = ∅ ↔ ∀ x, ∃ i, x ∉ f i := by simp [set.eq_empty_iff_forall_not_mem] -- classical lemma Inter₂_eq_empty_iff {s : Π i, κ i → set α} : (⋂ i j, s i j) = ∅ ↔ ∀ a, ∃ i j, a ∉ s i j := by simp only [eq_empty_iff_forall_not_mem, mem_Inter, not_forall] -- classical lemma sInter_eq_empty_iff {c : set (set α)} : ⋂₀ c = ∅ ↔ ∀ a, ∃ b ∈ c, a ∉ b := by simp [set.eq_empty_iff_forall_not_mem] -- classical @[simp] theorem nonempty_Inter {f : ι → set α} : (⋂ i, f i).nonempty ↔ ∃ x, ∀ i, x ∈ f i := by simp [← ne_empty_iff_nonempty, Inter_eq_empty_iff] -- classical @[simp] lemma nonempty_Inter₂ {s : Π i, κ i → set α} : (⋂ i j, s i j).nonempty ↔ ∃ a, ∀ i j, a ∈ s i j := by simp [← ne_empty_iff_nonempty, Inter_eq_empty_iff] -- classical @[simp] theorem nonempty_sInter {c : set (set α)}: (⋂₀ c).nonempty ↔ ∃ a, ∀ b ∈ c, a ∈ b := by simp [← ne_empty_iff_nonempty, sInter_eq_empty_iff] -- classical theorem compl_sUnion (S : set (set α)) : (⋃₀ S)ᶜ = ⋂₀ (compl '' S) := ext $ λ x, by simp -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set α)) : ⋃₀ S = (⋂₀ (compl '' S))ᶜ := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set α)) : (⋂₀ S)ᶜ = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_compl_sUnion_compl (S : set (set α)) : ⋂₀ S = (⋃₀ (compl '' S))ᶜ := by rw [←compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] theorem Union_eq_range_psigma (s : ι → set β) : (⋃ i, s i) = range (λ a : Σ' i, s i, a.2) := by simp [set.ext_iff] theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) : (⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s := begin ext x, simp only [mem_Union, mem_image, mem_preimage], split, { rintro ⟨i, a, h, rfl⟩, exact h }, { intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ } end lemma sigma.univ (X : α → Type*) : (set.univ : set (Σ a, X a)) = ⋃ a, range (sigma.mk a) := set.ext $ λ x, iff_of_true trivial ⟨range (sigma.mk x.1), set.mem_range_self _, x.2, sigma.eta x⟩ lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ λ t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union_const {s : set α} (h : ι → ι₂) : (⋃ i : ι, s) ⊆ (⋃ j : ι₂, s) := @supr_const_mono (set α) ι ι₂ _ s h @[simp] lemma Union_singleton_eq_range {α β : Type*} (f : α → β) : (⋃ (x : α), {f x}) = range f := by { ext x, simp [@eq_comm _ x] } lemma Union_of_singleton (α : Type*) : (⋃ x, {x} : set α) = univ := by simp lemma Union_of_singleton_coe (s : set α) : (⋃ (i : s), {i} : set α) = s := by simp lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := by rw [← sUnion_image, image_id'] lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := by rw [← sInter_image, image_id'] lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) := by simp only [←sUnion_range, subtype.range_coe] lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) := by simp only [←sInter_range, subtype.range_coe] lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := sup_eq_supr s₁ s₂ lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := inf_eq_infi s₁ s₂ lemma sInter_union_sInter {S T : set (set α)} : (⋂₀ S) ∪ (⋂₀ T) = (⋂ p ∈ S ×ˢ T, (p : (set α) × (set α)).1 ∪ p.2) := Inf_sup_Inf lemma sUnion_inter_sUnion {s t : set (set α)} : (⋃₀ s) ∩ (⋃₀ t) = (⋃ p ∈ s ×ˢ t, (p : (set α) × (set α )).1 ∩ p.2) := Sup_inf_Sup lemma bUnion_Union (s : ι → set α) (t : α → set β) : (⋃ x ∈ ⋃ i, s i, t x) = ⋃ i (x ∈ s i), t x := by simp [@Union_comm _ ι] lemma bInter_Union (s : ι → set α) (t : α → set β) : (⋂ x ∈ ⋃ i, s i, t x) = ⋂ i (x ∈ s i), t x := by simp [@Inter_comm _ ι] lemma sUnion_Union (s : ι → set (set α)) : ⋃₀ (⋃ i, s i) = ⋃ i, ⋃₀ (s i) := by simp only [sUnion_eq_bUnion, bUnion_Union] theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i := by simp only [sInter_eq_bInter, bInter_Union] lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α)) {f : ∀ (s : C), β → s} (hf : ∀ (s : C), surjective (f s)) : (⋃ (y : β), range (λ (s : C), (f s y).val)) = ⋃₀ C := begin ext x, split, { rintro ⟨s, ⟨y, rfl⟩, ⟨s, hs⟩, rfl⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 }, { rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨s, hs⟩, _⟩, exact congr_arg subtype.val hy } end lemma Union_range_eq_Union (C : ι → set α) {f : ∀ (x : ι), β → C x} (hf : ∀ (x : ι), surjective (f x)) : (⋃ (y : β), range (λ (x : ι), (f x y).val)) = ⋃ x, C x := begin ext x, rw [mem_Union, mem_Union], split, { rintro ⟨y, i, rfl⟩, exact ⟨i, (f i y).2⟩ }, { rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, exact ⟨y, i, congr_arg subtype.val hy⟩ } end lemma union_distrib_Inter_left (s : ι → set α) (t : set α) : t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) := sup_infi_eq _ _ lemma union_distrib_Inter₂_left (s : set α) (t : Π i, κ i → set α) : s ∪ (⋂ i j, t i j) = ⋂ i j, s ∪ t i j := by simp_rw union_distrib_Inter_left lemma union_distrib_Inter_right (s : ι → set α) (t : set α) : (⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) := infi_sup_eq _ _ lemma union_distrib_Inter₂_right (s : Π i, κ i → set α) (t : set α) : (⋂ i j, s i j) ∪ t = ⋂ i j, s i j ∪ t := by simp_rw union_distrib_Inter_right section function /-! ### `maps_to` -/ lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) : maps_to f (⋃₀ S) t := λ x ⟨s, hs, hx⟩, H s hs hx lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) : maps_to f (⋃ i, s i) t := maps_to_sUnion $ forall_range_iff.2 H lemma maps_to_Union₂ {s : Π i, κ i → set α} {t : set β} {f : α → β} (H : ∀ i j, maps_to f (s i j) t) : maps_to f (⋃ i j, s i j) t := maps_to_Union $ λ i, maps_to_Union (H i) lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋃ i, s i) (⋃ i, t i) := maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i) lemma maps_to_Union₂_Union₂ {s : Π i, κ i → set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, maps_to f (s i j) (t i j)) : maps_to f (⋃ i j, s i j) (⋃ i j, t i j) := maps_to_Union_Union $ λ i, maps_to_Union_Union (H i) lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) : maps_to f s (⋂₀ T) := λ x hx t ht, H t ht hx lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) : maps_to f s (⋂ i, t i) := λ x hx, mem_Inter.2 $ λ i, H i hx lemma maps_to_Inter₂ {s : set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, maps_to f s (t i j)) : maps_to f s (⋂ i j, t i j) := maps_to_Inter $ λ i, maps_to_Inter (H i) lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋂ i, s i) (⋂ i, t i) := maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _) lemma maps_to_Inter₂_Inter₂ {s : Π i, κ i → set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, maps_to f (s i j) (t i j)) : maps_to f (⋂ i j, s i j) (⋂ i j, t i j) := maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i) lemma image_Inter_subset (s : ι → set α) (f : α → β) : f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) := (maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset lemma image_Inter₂_subset (s : Π i, κ i → set α) (f : α → β) : f '' (⋂ i j, s i j) ⊆ ⋂ i j, f '' s i j := (maps_to_Inter₂_Inter₂ $ λ i hi, maps_to_image f (s i hi)).image_subset lemma image_sInter_subset (S : set (set α)) (f : α → β) : f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s := by { rw sInter_eq_bInter, apply image_Inter₂_subset } /-! ### `inj_on` -/ lemma inj_on.image_inter {f : α → β} {s t u : set α} (hf : inj_on f u) (hs : s ⊆ u) (ht : t ⊆ u) : f '' (s ∩ t) = f '' s ∩ f '' t := begin apply subset.antisymm (image_inter_subset _ _ _), rintros x ⟨⟨y, ys, hy⟩, ⟨z, zt, hz⟩⟩, have : y = z, { apply hf (hs ys) (ht zt), rwa ← hz at hy }, rw ← this at zt, exact ⟨y, ⟨ys, zt⟩, hy⟩, end lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) : f '' (⋂ i, s i) = ⋂ i, f '' (s i) := begin inhabit ι, refine subset.antisymm (image_Inter_subset s f) (λ y hy, _), simp only [mem_Inter, mem_image_iff_bex] at hy, choose x hx hy using hy, refine ⟨x default, mem_Inter.2 $ λ i, _, hy _⟩, suffices : x default = x i, { rw this, apply hx }, replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i), apply h (hx _) (hx _), simp only [hy] end lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β} (h : inj_on f (⋃ i hi, s i hi)) : f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) := begin simp only [Inter, infi_subtype'], haveI : nonempty {i // p i} := nonempty_subtype.2 hp, apply inj_on.image_Inter_eq, simpa only [Union, supr_subtype'] using h end lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {f : α → β} (hf : ∀ i, inj_on f (s i)) : inj_on f (⋃ i, s i) := begin intros x hx y hy hxy, rcases mem_Union.1 hx with ⟨i, hx⟩, rcases mem_Union.1 hy with ⟨j, hy⟩, rcases hs i j with ⟨k, hi, hj⟩, exact hf k (hi hx) (hj hy) hxy end /-! ### `surj_on` -/ lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) : surj_on f s (⋃₀ T) := λ x ⟨t, ht, hx⟩, H t ht hx lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) : surj_on f s (⋃ i, t i) := surj_on_sUnion $ forall_range_iff.2 H lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) : surj_on f (⋃ i, s i) (⋃ i, t i) := surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _) lemma surj_on_Union₂ {s : set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, surj_on f s (t i j)) : surj_on f s (⋃ i j, t i j) := surj_on_Union $ λ i, surj_on_Union (H i) lemma surj_on_Union₂_Union₂ {s : Π i, κ i → set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, surj_on f (s i j) (t i j)) : surj_on f (⋃ i j, s i j) (⋃ i j, t i j) := surj_on_Union_Union $ λ i, surj_on_Union_Union (H i) lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) t := begin intros y hy, rw [Hinj.image_Inter_eq, mem_Inter], exact λ i, H i hy end lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) (⋂ i, t i) := surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj /-! ### `bij_on` -/ lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := ⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩ lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := ⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _), surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩ lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) end function /-! ### `image`, `preimage` -/ section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃ i, f '' s i) := begin ext1 x, simp [image, ← exists_and_distrib_right, @exists_swap α] end lemma image_Union₂ (f : α → β) (s : Π i, κ i → set α) : f '' (⋃ i j, s i j) = ⋃ i j, f '' s i j := by simp_rw image_Union lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃ x (h : p x), {⟨x, h⟩}) := set.ext $ λ ⟨x, h⟩, by simp [h] lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃ i, {f i}) := set.ext $ λ a, by simp [@eq_comm α a] lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃ i ∈ s, {f i}) := set.ext $ λ b, by simp [@eq_comm β b] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃ x ∈ range f, g x) = (⋃ y, g (f y)) := supr_range @[simp] lemma Union_Union_eq' {f : ι → α} {g : α → set β} : (⋃ x y (h : f y = x), g x) = ⋃ y, g (f y) := by simpa using bUnion_range lemma bInter_range {f : ι → α} {g : α → set β} : (⋂ x ∈ range f, g x) = (⋂ y, g (f y)) := infi_range @[simp] lemma Inter_Inter_eq' {f : ι → α} {g : α → set β} : (⋂ x y (h : f y = x), g x) = ⋂ y, g (f y) := by simpa using bInter_range variables {s : set γ} {f : γ → α} {g : α → set β} lemma bUnion_image : (⋃ x ∈ f '' s, g x) = (⋃ y ∈ s, g (f y)) := supr_image lemma bInter_image : (⋂ x ∈ f '' s, g x) = (⋂ y ∈ s, g (f y)) := infi_image end image section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := λ a b h, preimage_mono h @[simp] lemma preimage_Union {f : α → β} {s : ι → set β} : f ⁻¹' (⋃ i, s i) = (⋃ i, f ⁻¹' s i) := set.ext $ by simp [preimage] lemma preimage_Union₂ {f : α → β} {s : Π i, κ i → set β} : f ⁻¹' (⋃ i j, s i j) = ⋃ i j, f ⁻¹' s i j := by simp_rw preimage_Union @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : f ⁻¹' (⋃₀ s) = (⋃ t ∈ s, f ⁻¹' t) := by rw [sUnion_eq_bUnion, preimage_Union₂] lemma preimage_Inter {f : α → β} {s : ι → set β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_Inter₂ {f : α → β} {s : Π i, κ i → set β} : f ⁻¹' (⋂ i j, s i j) = ⋂ i j, f ⁻¹' s i j := by simp_rw preimage_Inter @[simp] lemma preimage_sInter {f : α → β} {s : set (set β)} : f ⁻¹' (⋂₀ s) = ⋂ t ∈ s, f ⁻¹' t := by rw [sInter_eq_bInter, preimage_Inter₂] @[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := by rw [← preimage_Union₂, bUnion_of_singleton] lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ := by rw [bUnion_preimage_singleton, preimage_range] end preimage section prod lemma prod_Union {s : set α} {t : ι → set β} : s ×ˢ (⋃ i, t i) = ⋃ i, s ×ˢ (t i) := by { ext, simp } lemma prod_Union₂ {s : set α} {t : Π i, κ i → set β} : s ×ˢ (⋃ i j, t i j) = ⋃ i j, s ×ˢ t i j := by simp_rw [prod_Union] lemma prod_sUnion {s : set α} {C : set (set β)} : s ×ˢ (⋃₀ C) = ⋃₀ ((λ t, s ×ˢ t) '' C) := by simp_rw [sUnion_eq_bUnion, bUnion_image, prod_Union₂] lemma Union_prod_const {s : ι → set α} {t : set β} : (⋃ i, s i) ×ˢ t = ⋃ i, s i ×ˢ t := by { ext, simp } lemma Union₂_prod_const {s : Π i, κ i → set α} {t : set β} : (⋃ i j, s i j) ×ˢ t = ⋃ i j, s i j ×ˢ t := by simp_rw [Union_prod_const] lemma sUnion_prod_const {C : set (set α)} {t : set β} : (⋃₀ C) ×ˢ t = ⋃₀ ((λ s : set α, s ×ˢ t) '' C) := by simp only [sUnion_eq_bUnion, Union₂_prod_const, bUnion_image] lemma Union_prod {ι ι' α β} (s : ι → set α) (t : ι' → set β) : (⋃ (x : ι × ι'), s x.1 ×ˢ t x.2) = (⋃ (i : ι), s i) ×ˢ (⋃ (i : ι'), t i) := by { ext, simp } lemma Union_prod_of_monotone [semilattice_sup α] {s : α → set β} {t : α → set γ} (hs : monotone s) (ht : monotone t) : (⋃ x, s x ×ˢ t x) = (⋃ x, s x) ×ˢ (⋃ x, t x) := begin ext ⟨z, w⟩, simp only [mem_prod, mem_Union, exists_imp_distrib, and_imp, iff_def], split, { intros x hz hw, exact ⟨⟨x, hz⟩, x, hw⟩ }, { intros x hz x' hw, exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ } end end prod section image2 variables (f : α → β → γ) {s : set α} {t : set β} lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintro ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ } lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintro ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩, exact ⟨b, d, a, c, e⟩ } lemma image2_Union_left (s : ι → set α) (t : set β) : image2 f (⋃ i, s i) t = ⋃ i, image2 f (s i) t := by simp only [← image_prod, Union_prod_const, image_Union] lemma image2_Union_right (s : set α) (t : ι → set β) : image2 f s (⋃ i, t i) = ⋃ i, image2 f s (t i) := by simp only [← image_prod, prod_Union, image_Union] lemma image2_Union₂_left (s : Π i, κ i → set α) (t : set β) : image2 f (⋃ i j, s i j) t = ⋃ i j, image2 f (s i j) t := by simp_rw image2_Union_left lemma image2_Union₂_right (s : set α) (t : Π i, κ i → set β) : image2 f s (⋃ i j, t i j) = ⋃ i j, image2 f s (t i j) := by simp_rw image2_Union_right lemma image2_Inter_subset_left (s : ι → set α) (t : set β) : image2 f (⋂ i, s i) t ⊆ ⋂ i, image2 f (s i) t := by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i, mem_image2_of_mem (hx _) hy } lemma image2_Inter_subset_right (s : set α) (t : ι → set β) : image2 f s (⋂ i, t i) ⊆ ⋂ i, image2 f s (t i) := by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i, mem_image2_of_mem hx (hy _) } lemma image2_Inter₂_subset_left (s : Π i, κ i → set α) (t : set β) : image2 f (⋂ i j, s i j) t ⊆ ⋂ i j, image2 f (s i j) t := by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i j, mem_image2_of_mem (hx _ _) hy } lemma image2_Inter₂_subset_right (s : set α) (t : Π i, κ i → set β) : image2 f s (⋂ i j, t i j) ⊆ ⋂ i j, image2 f s (t i j) := by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i j, mem_image2_of_mem hx (hy _ _) } /-- The `set.image2` version of `set.image_eq_Union` -/ lemma image2_eq_Union (s : set α) (t : set β) : image2 f s t = ⋃ (i ∈ s) (j ∈ t), {f i j} := by simp_rw [←image_eq_Union, Union_image_left] lemma prod_eq_bUnion_left : s ×ˢ t = ⋃ a ∈ s, (λ b, (a, b)) '' t := by rw [Union_image_left, image2_mk_eq_prod] lemma prod_eq_bUnion_right : s ×ˢ t = ⋃ b ∈ t, (λ a, (a, b)) '' s := by rw [Union_image_right, image2_mk_eq_prod] end image2 section seq /-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over all `f ∈ s`. -/ def seq (s : set (α → β)) (t : set α) : set β := {b | ∃ f ∈ s, ∃ a ∈ t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃ f ∈ s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.rfl lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀ f ∈ s, ∀ a ∈ t, (f : α → β) a ∈ u) := iff.intro (λ h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (λ h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := λ b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λ f : α → β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (λ c, iff.intro _ _), { rintro ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintro ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : s ×ˢ t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintro ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintro ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λ b a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap] lemma image2_eq_seq (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = seq (f '' s) t := by { ext, simp } end seq section pi variables {π : α → Type*} lemma pi_def (i : set α) (s : Π a, set (π a)) : pi i s = (⋂ a ∈ i, eval a ⁻¹' s a) := by { ext, simp } lemma univ_pi_eq_Inter (t : Π i, set (π i)) : pi univ t = ⋂ i, eval i ⁻¹' t i := by simp only [pi_def, Inter_true, mem_univ] lemma pi_diff_pi_subset (i : set α) (s t : Π a, set (π a)) : pi i s \ pi i t ⊆ ⋃ a ∈ i, (eval a ⁻¹' (s a \ t a)) := begin refine diff_subset_comm.2 (λ x hx a ha, _), simp only [mem_diff, mem_pi, mem_Union, not_exists, mem_preimage, not_and, not_not, eval_apply] at hx, exact hx.2 _ ha (hx.1 _ ha) end lemma Union_univ_pi (t : Π i, ι → set (π i)) : (⋃ (x : α → ι), pi univ (λ i, t i (x i))) = pi univ (λ i, ⋃ (j : ι), t i j) := by { ext, simp [classical.skolem] } end pi end set namespace function namespace surjective lemma Union_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋃ x, g (f x)) = ⋃ y, g y := hf.supr_comp g lemma Inter_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋂ x, g (f x)) = ⋂ y, g y := hf.infi_comp g end surjective end function /-! ### Disjoint sets We define some lemmas in the `disjoint` namespace to be able to use projection notation. -/ section disjoint variables {s t u : set α} {f : α → β} namespace disjoint theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u := hs.sup_left ht theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) := ht.sup_right hu lemma inter_left (u : set α) (h : disjoint s t) : disjoint (s ∩ u) t := inf_left _ h lemma inter_left' (u : set α) (h : disjoint s t) : disjoint (u ∩ s) t := inf_left' _ h lemma inter_right (u : set α) (h : disjoint s t) : disjoint s (t ∩ u) := inf_right _ h lemma inter_right' (u : set α) (h : disjoint s t) : disjoint s (u ∩ t) := inf_right' _ h lemma subset_left_of_subset_union (h : s ⊆ t ∪ u) (hac : disjoint s u) : s ⊆ t := hac.left_le_of_le_sup_right h lemma subset_right_of_subset_union (h : s ⊆ t ∪ u) (hab : disjoint s t) : s ⊆ u := hab.left_le_of_le_sup_left h lemma preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) := λ x hx, h hx end disjoint namespace set protected theorem disjoint_iff : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl theorem disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff lemma not_disjoint_iff : ¬disjoint s t ↔ ∃ x, x ∈ s ∧ x ∈ t := not_forall.trans $ exists_congr $ λ x, not_not lemma not_disjoint_iff_nonempty_inter : ¬disjoint s t ↔ (s ∩ t).nonempty := not_disjoint_iff alias not_disjoint_iff_nonempty_inter ↔ _ nonempty.not_disjoint lemma disjoint_or_nonempty_inter (s t : set α) : disjoint s t ∨ (s ∩ t).nonempty := (em _).imp_right not_disjoint_iff_nonempty_inter.mp lemma disjoint_iff_forall_ne : disjoint s t ↔ ∀ (x ∈ s) (y ∈ t), x ≠ y := by simp only [ne.def, disjoint_left, @imp_not_comm _ (_ = _), forall_eq'] lemma _root_.disjoint.ne_of_mem (h : disjoint s t) {x y} (hx : x ∈ s) (hy : y ∈ t) : x ≠ y := disjoint_iff_forall_ne.mp h x hx y hy theorem disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t := d.mono_left h theorem disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t := d.mono_right h theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) : disjoint s t := d.mono h1 h2 @[simp] theorem disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := disjoint_sup_left @[simp] theorem disjoint_union_right : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := disjoint_sup_right @[simp] theorem disjoint_Union_left {ι : Sort*} {s : ι → set α} : disjoint (⋃ i, s i) t ↔ ∀ i, disjoint (s i) t := supr_disjoint_iff @[simp] theorem disjoint_Union_right {ι : Sort*} {s : ι → set α} : disjoint t (⋃ i, s i) ↔ ∀ i, disjoint t (s i) := disjoint_supr_iff @[simp] lemma disjoint_Union₂_left {s : Π i, κ i → set α} {t : set α} : disjoint (⋃ i j, s i j) t ↔ ∀ i j, disjoint (s i j) t := supr₂_disjoint_iff @[simp] lemma disjoint_Union₂_right {s : set α} {t : Π i, κ i → set α} : disjoint s (⋃ i j, t i j) ↔ ∀ i j, disjoint s (t i j) := disjoint_supr₂_iff @[simp] lemma disjoint_sUnion_left {S : set (set α)} {t : set α} : disjoint (⋃₀ S) t ↔ ∀ s ∈ S, disjoint s t := Sup_disjoint_iff @[simp] lemma disjoint_sUnion_right {s : set α} {S : set (set α)} : disjoint s (⋃₀ S) ↔ ∀ t ∈ S, disjoint s t := disjoint_Sup_iff theorem disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) @[simp] theorem disjoint_empty (s : set α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem empty_disjoint (s : set α) : disjoint ∅ s := disjoint_bot_left @[simp] lemma univ_disjoint {s : set α} : disjoint univ s ↔ s = ∅ := top_disjoint @[simp] lemma disjoint_univ {s : set α} : disjoint s univ ↔ s = ∅ := disjoint_top @[simp] theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl @[simp] theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s := by rw [disjoint.comm]; exact disjoint_singleton_left @[simp] lemma disjoint_singleton {a b : α} : disjoint ({a} : set α) {b} ↔ a ≠ b := by rw [disjoint_singleton_left, mem_singleton_iff] theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ} (h : ∀ b ∈ s, ∀ c ∈ t, f b ≠ g c) : disjoint (f '' s) (g '' t) := by rintro a ⟨⟨b, hb, eq⟩, c, hc, rfl⟩; exact h b hb c hc eq lemma disjoint_image_of_injective {f : α → β} (hf : injective f) {s t : set α} (hd : disjoint s t) : disjoint (f '' s) (f '' t) := disjoint_image_image $ λ x hx y hy, hf.ne $ λ H, set.disjoint_iff.1 hd ⟨hx, H.symm ▸ hy⟩ lemma _root_.disjoint.of_image (h : disjoint (f '' s) (f '' t)) : disjoint s t := λ x hx, disjoint_left.1 h (mem_image_of_mem _ hx.1) (mem_image_of_mem _ hx.2) lemma disjoint_image_iff (hf : injective f) : disjoint (f '' s) (f '' t) ↔ disjoint s t := ⟨disjoint.of_image, disjoint_image_of_injective hf⟩ lemma _root_.disjoint.of_preimage (hf : surjective f) {s t : set β} (h : disjoint (f ⁻¹' s) (f ⁻¹' t)) : disjoint s t := by rw [disjoint_iff_inter_eq_empty, ←image_preimage_eq (_ ∩ _) hf, preimage_inter, h.inter_eq, image_empty] lemma disjoint_preimage_iff (hf : surjective f) {s t : set β} : disjoint (f ⁻¹' s) (f ⁻¹' t) ↔ disjoint s t := ⟨disjoint.of_preimage hf, disjoint.preimage _⟩ lemma preimage_eq_empty {f : α → β} {s : set β} (h : disjoint s (range f)) : f ⁻¹' s = ∅ := by simpa using h.preimage f lemma preimage_eq_empty_iff {s : set β} : f ⁻¹' s = ∅ ↔ disjoint s (range f) := ⟨λ h, begin simp only [eq_empty_iff_forall_not_mem, disjoint_iff_inter_eq_empty, not_exists, mem_inter_eq, not_and, mem_range, mem_preimage] at h ⊢, assume y hy x hx, rw ← hx at hy, exact h x hy, end, preimage_eq_empty⟩ lemma _root_.disjoint.image {s t u : set α} {f : α → β} (h : disjoint s t) (hf : inj_on f u) (hs : s ⊆ u) (ht : t ⊆ u) : disjoint (f '' s) (f '' t) := begin rw disjoint_iff_inter_eq_empty at h ⊢, rw [← hf.image_inter hs ht, h, image_empty], end end set end disjoint /-! ### Intervals -/ namespace set variables [complete_lattice α] lemma Ici_supr (f : ι → α) : Ici (⨆ i, f i) = ⋂ i, Ici (f i) := ext $ λ _, by simp only [mem_Ici, supr_le_iff, mem_Inter] lemma Iic_infi (f : ι → α) : Iic (⨅ i, f i) = ⋂ i, Iic (f i) := ext $ λ _, by simp only [mem_Iic, le_infi_iff, mem_Inter] lemma Ici_supr₂ (f : Π i, κ i → α) : Ici (⨆ i j, f i j) = ⋂ i j, Ici (f i j) := by simp_rw Ici_supr lemma Iic_infi₂ (f : Π i, κ i → α) : Iic (⨅ i j, f i j) = ⋂ i j, Iic (f i j) := by simp_rw Iic_infi lemma Ici_Sup (s : set α) : Ici (Sup s) = ⋂ a ∈ s, Ici a := by rw [Sup_eq_supr, Ici_supr₂] lemma Iic_Inf (s : set α) : Iic (Inf s) = ⋂ a ∈ s, Iic a := by rw [Inf_eq_infi, Iic_infi₂] end set namespace set variables (t : α → set β) lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u := ⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩, λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩ lemma bUnion_diff_bUnion_subset (s₁ s₂ : set α) : (⋃ x ∈ s₁, t x) \ (⋃ x ∈ s₂, t x) ⊆ (⋃ x ∈ s₁ \ s₂, t x) := begin simp only [diff_subset_iff, ← bUnion_union], apply bUnion_subset_bUnion_left, rw union_diff_self, apply subset_union_right end /-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i` sending `⟨i, x⟩` to `x`. -/ def sigma_to_Union (x : Σ i, t i) : (⋃ i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩ lemma sigma_to_Union_surjective : surjective (sigma_to_Union t) | ⟨b, hb⟩ := have ∃ a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, b, hb⟩, rfl⟩ lemma sigma_to_Union_injective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : injective (sigma_to_Union t) | ⟨a₁, b₁, h₁⟩ ⟨a₂, b₂, h₂⟩ eq := have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ λ ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩, h _ _ ne this, sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq lemma sigma_to_Union_bijective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : bijective (sigma_to_Union t) := ⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩ /-- Equivalence between a disjoint union and a dependent sum. -/ noncomputable def Union_eq_sigma_of_disjoint {t : α → set β} (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : (⋃ i, t i) ≃ (Σ i, t i) := (equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm lemma Union_ge_eq_Union_nat_add (u : ℕ → set α) (n : ℕ) : (⋃ i ≥ n, u i) = ⋃ i, u (i + n) := supr_ge_eq_supr_nat_add u n lemma Inter_ge_eq_Inter_nat_add (u : ℕ → set α) (n : ℕ) : (⋂ i ≥ n, u i) = ⋂ i, u (i + n) := infi_ge_eq_infi_nat_add u n lemma _root_.monotone.Union_nat_add {f : ℕ → set α} (hf : monotone f) (k : ℕ) : (⋃ n, f (n + k)) = ⋃ n, f n := hf.supr_nat_add k lemma _root_.antitone.Inter_nat_add {f : ℕ → set α} (hf : antitone f) (k : ℕ) : (⋂ n, f (n + k)) = ⋂ n, f n := hf.infi_nat_add k @[simp] lemma Union_Inter_ge_nat_add (f : ℕ → set α) (k : ℕ) : (⋃ n, ⋂ i ≥ n, f (i + k)) = ⋃ n, ⋂ i ≥ n, f i := supr_infi_ge_nat_add f k lemma union_Union_nat_succ (u : ℕ → set α) : u 0 ∪ (⋃ i, u (i + 1)) = ⋃ i, u i := sup_supr_nat_succ u lemma inter_Inter_nat_succ (u : ℕ → set α) : u 0 ∩ (⋂ i, u (i + 1)) = ⋂ i, u i := inf_infi_nat_succ u end set section sup_closed /-- A set `s` is sup-closed if for all `x₁, x₂ ∈ s`, `x₁ ⊔ x₂ ∈ s`. -/ def sup_closed [has_sup α] (s : set α) : Prop := ∀ x1 x2, x1 ∈ s → x2 ∈ s → x1 ⊔ x2 ∈ s lemma sup_closed_singleton [semilattice_sup α] (x : α) : sup_closed ({x} : set α) := λ _ _ y1_mem y2_mem, by { rw set.mem_singleton_iff at *, rw [y1_mem, y2_mem, sup_idem], } lemma sup_closed.inter [semilattice_sup α] {s t : set α} (hs : sup_closed s) (ht : sup_closed t) : sup_closed (s ∩ t) := begin intros x y hx hy, rw set.mem_inter_iff at hx hy ⊢, exact ⟨hs x y hx.left hy.left, ht x y hx.right hy.right⟩, end lemma sup_closed_of_totally_ordered [semilattice_sup α] (s : set α) (hs : ∀ x y : α, x ∈ s → y ∈ s → y ≤ x ∨ x ≤ y) : sup_closed s := begin intros x y hxs hys, cases hs x y hxs hys, { rwa (sup_eq_left.mpr h), }, { rwa (sup_eq_right.mpr h), }, end lemma sup_closed_of_linear_order [linear_order α] (s : set α) : sup_closed s := sup_closed_of_totally_ordered s (λ x y hxs hys, le_total y x) end sup_closed open set variables [complete_lattice β] lemma supr_Union (s : ι → set α) (f : α → β) : (⨆ a ∈ (⋃ i, s i), f a) = ⨆ i (a ∈ s i), f a := by { rw supr_comm, simp_rw [mem_Union, supr_exists] } lemma infi_Union (s : ι → set α) (f : α → β) : (⨅ a ∈ (⋃ i, s i), f a) = ⨅ i (a ∈ s i), f a := @supr_Union α βᵒᵈ _ _ s f lemma Sup_sUnion (s : set (set β)) : Sup (⋃₀ s) = ⨆ t ∈ s, Sup t := by simp only [sUnion_eq_bUnion, Sup_eq_supr, supr_Union] lemma Inf_sUnion (s : set (set β)) : Inf (⋃₀ s) = ⨅ t ∈ s, Inf t := @Sup_sUnion βᵒᵈ _ _
2335f98180c7c079d08d782def2f2e1ecefcd28f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/ns1.lean
123ca59876856db7ca7effd2db558bbd33d917b3
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
112
lean
import logic namespace foo namespace boo theorem tst : true := trivial end boo end foo open foo check boo.tst
9407038115ab2dce2d2ea8a0bdb17cecf1fb6088
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/ring_theory/algebra_tower.lean
e147d1a23b65d85acae51a991060ac1d88edef5f
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
13,308
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.adjoin /-! # Towers of algebras We set up the basic theory of algebra towers. An algebra tower A/S/R is expressed by having instances of `algebra A S`, `algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. In `field_theory/tower.lean` we use this to prove the tower law for finite extensions, that if `R` and `S` are both fields, then `[A:R] = [A:S] [S:A]`. In this file we prepare the main lemma: if `{bi | i ∈ I}` is an `R`-basis of `S` and `{cj | j ∈ J}` is a `S`-basis of `A`, then `{bi cj | i ∈ I, j ∈ J}` is an `R`-basis of `A`. This statement does not require the base rings to be a field, so we also generalize the lemma to rings in this file. -/ universes u v w u₁ variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) namespace is_scalar_tower section semimodule variables [comm_semiring R] [semiring S] [add_comm_monoid A] [add_comm_monoid B] variables [algebra R S] [semimodule S A] [semimodule R A] [semimodule S B] [semimodule R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables {R} (S) {A} theorem algebra_map_smul (r : R) (x : A) : algebra_map R S r • x = r • x := by rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] variables {R S A} theorem smul_left_comm (r : R) (s : S) (x : A) : r • s • x = s • r • x := by rw [← smul_assoc, algebra.smul_def r s, algebra.commutes, mul_smul, algebra_map_smul] end semimodule section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra R A] [algebra S B] [algebra R B] variables {R S A} theorem of_algebra_map_eq (h : ∀ x, algebra_map R A x = algebra_map S A (algebra_map R S x)) : is_scalar_tower R S A := ⟨λ x y z, by simp_rw [algebra.smul_def, ring_hom.map_mul, mul_assoc, h]⟩ variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables (R S A) theorem algebra_map_eq : algebra_map R A = (algebra_map S A).comp (algebra_map R S) := ring_hom.ext $ λ x, by simp_rw [ring_hom.comp_apply, algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] theorem algebra_map_apply (x : R) : algebra_map R A x = algebra_map S A (algebra_map R S x) := by rw [algebra_map_eq R S A, ring_hom.comp_apply] @[ext] lemma algebra.ext {S : Type u} {A : Type v} [comm_semiring S] [semiring A] (h1 h2 : algebra S A) (h : ∀ {r : S} {x : A}, (by haveI := h1; exact r • x) = r • x) : h1 = h2 := begin unfreezingI { cases h1 with f1 g1 h11 h12, cases h2 with f2 g2 h21 h22, cases f1, cases f2, congr', { ext r x, exact h }, ext r, erw [← mul_one (g1 r), ← h12, ← mul_one (g2 r), ← h22, h], refl } end variables (R S A) theorem algebra_comap_eq : algebra.comap.algebra R S A = ‹_› := algebra.ext _ _ $ λ x (z : A), calc algebra_map R S x • z = (x • 1 : S) • z : by rw algebra.algebra_map_eq_smul_one ... = x • (1 : S) • z : by rw smul_assoc ... = (by exact x • z : A) : by rw one_smul /-- In a tower, the canonical map from the middle element to the top element is an algebra homomorphism over the bottom element. -/ def to_alg_hom : S →ₐ[R] A := { commutes' := λ _, (algebra_map_apply _ _ _ _).symm, .. algebra_map S A } @[simp] lemma to_alg_hom_apply (y : S) : to_alg_hom R S A y = algebra_map S A y := rfl variables (R) {S A B} /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrict_base (f : A →ₐ[S] B) : A →ₐ[R] B := { commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B], exact f.commutes (algebra_map R S r) }, .. (f : A →+* B) } @[simp] lemma restrict_base_apply (f : A →ₐ[S] B) (x : A) : restrict_base R f x = f x := rfl instance right : is_scalar_tower R S S := of_algebra_map_eq $ λ x, rfl instance nat : is_scalar_tower ℕ S A := of_algebra_map_eq $ λ x, ((algebra_map S A).map_nat_cast x).symm instance comap {R S A : Type*} [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] : is_scalar_tower R S (algebra.comap R S A) := of_algebra_map_eq $ λ x, rfl instance subsemiring (U : subsemiring S) : is_scalar_tower U S A := of_algebra_map_eq $ λ x, rfl instance subring {S A : Type*} [comm_ring S] [ring A] [algebra S A] (U : set S) [is_subring U] : is_scalar_tower U S A := of_algebra_map_eq $ λ x, rfl @[nolint instance_priority] instance of_ring_hom {R A B : Type*} [comm_semiring R] [comm_semiring A] [comm_semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : @is_scalar_tower R A B _ (f.to_ring_hom.to_algebra.to_has_scalar) _ := by { letI := (f : A →+* B).to_algebra, exact of_algebra_map_eq (λ x, (f.commutes x).symm) } end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [algebra R A] variables [comm_semiring B] [algebra A B] [algebra R B] [is_scalar_tower R A B] instance subalgebra (S : subalgebra R A) : is_scalar_tower R S A := of_algebra_map_eq $ λ x, rfl instance polynomial : is_scalar_tower R A (polynomial B) := of_algebra_map_eq $ λ x, congr_arg polynomial.C $ algebra_map_apply R A B x theorem aeval_apply (x : B) (p : polynomial R) : polynomial.aeval x p = polynomial.aeval x (polynomial.map (algebra_map R A) p) := by rw [polynomial.aeval_def, polynomial.aeval_def, polynomial.eval₂_map, algebra_map_eq R A B] end comm_semiring section comm_ring variables [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A] variables [is_scalar_tower R S A] instance int : is_scalar_tower ℤ S A := of_algebra_map_eq $ λ x, ((algebra_map S A).map_int_cast x).symm end comm_ring section division_ring variables [field R] [division_ring S] [algebra R S] [char_zero R] [char_zero S] instance rat : is_scalar_tower ℚ R S := of_algebra_map_eq $ λ x, ((algebra_map R S).map_rat_cast x).symm end division_ring end is_scalar_tower namespace algebra theorem adjoin_algebra_map' {R : Type u} {S : Type v} {A : Type w} [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] (s : set S) : adjoin R (algebra_map S (comap R S A) '' s) = subalgebra.map (adjoin R s) (to_comap R S A) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) theorem adjoin_algebra_map (R : Type u) (S : Type v) (A : Type w) [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] (s : set S) : adjoin R (algebra_map S A '' s) = subalgebra.map (adjoin R s) (is_scalar_tower.to_alg_hom R S A) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) end algebra namespace subalgebra open is_scalar_tower variables (R) {S A} [comm_semiring R] [comm_semiring S] [semiring A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] /-- If A/S/R is a tower of algebras then the `res`triction of a S-subalgebra of A is an R-subalgebra of A. -/ def res (U : subalgebra S A) : subalgebra R A := { carrier := U, algebra_map_mem' := λ x, by { rw algebra_map_apply R S A, exact U.algebra_map_mem _ } } @[simp] lemma res_top : res R (⊤ : subalgebra S A) = ⊤ := algebra.eq_top_iff.2 $ λ _, show _ ∈ (⊤ : subalgebra S A), from algebra.mem_top @[simp] lemma mem_res {U : subalgebra S A} {x : A} : x ∈ res R U ↔ x ∈ U := iff.rfl lemma res_inj {U V : subalgebra S A} (H : res R U = res R V) : U = V := ext $ λ x, by rw [← mem_res R, H, mem_res] /-- Produces a map from `subalgebra.under`. -/ def of_under {R A B : Type*} [comm_semiring R] [comm_semiring A] [semiring B] [algebra R A] [algebra R B] (S : subalgebra R A) (U : subalgebra S A) [algebra S B] [is_scalar_tower R S B] (f : U →ₐ[S] B) : S.under U →ₐ[R] B := { commutes' := λ r, (f.commutes (algebra_map R S r)).trans (algebra_map_apply R S B r).symm, .. f } end subalgebra namespace is_scalar_tower open subalgebra variables [comm_semiring R] [comm_semiring S] [comm_semiring A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] theorem range_under_adjoin (t : set A) : (to_alg_hom R S A).range.under (algebra.adjoin _ t) = res R (algebra.adjoin S t) := subalgebra.ext $ λ z, show z ∈ subsemiring.closure (set.range (algebra_map (to_alg_hom R S A).range A) ∪ t : set A) ↔ z ∈ subsemiring.closure (set.range (algebra_map S A) ∪ t : set A), from suffices set.range (algebra_map (to_alg_hom R S A).range A) = set.range (algebra_map S A), by rw this, by { ext z, exact ⟨λ ⟨⟨x, y, h1⟩, h2⟩, ⟨y, h2 ▸ h1⟩, λ ⟨y, hy⟩, ⟨⟨z, y, hy⟩, rfl⟩⟩ } end is_scalar_tower namespace submodule open is_scalar_tower variables [comm_semiring R] [semiring S] [add_comm_monoid A] variables [algebra R S] [semimodule S A] [semimodule R A] [is_scalar_tower R S A] variables (R) {S A} /-- Restricting the scalars of submodules in an algebra tower. -/ def restrict_scalars' (U : submodule S A) : submodule R A := { smul_mem' := λ r x hx, algebra_map_smul S r x ▸ U.smul_mem _ hx, .. U } variables (R S A) theorem restrict_scalars'_top : restrict_scalars' R (⊤ : submodule S A) = ⊤ := rfl variables {R S A} theorem restrict_scalars'_injective (U₁ U₂ : submodule S A) (h : restrict_scalars' R U₁ = restrict_scalars' R U₂) : U₁ = U₂ := ext $ by convert set.ext_iff.1 (ext'_iff.1 h); refl theorem restrict_scalars'_inj {U₁ U₂ : submodule S A} : restrict_scalars' R U₁ = restrict_scalars' R U₂ ↔ U₁ = U₂ := ⟨restrict_scalars'_injective U₁ U₂, congr_arg _⟩ end submodule section semiring variables {R S A} variables [comm_semiring R] [semiring S] [add_comm_monoid A] variables [algebra R S] [semimodule S A] [semimodule R A] [is_scalar_tower R S A] namespace submodule open is_scalar_tower theorem smul_mem_span_smul_of_mem {s : set S} {t : set A} {k : S} (hks : k ∈ span R s) {x : A} (hx : x ∈ t) : k • x ∈ span R (s • t) := span_induction hks (λ c hc, subset_span $ set.mem_smul.2 ⟨c, x, hc, hx, rfl⟩) (by { rw zero_smul, exact zero_mem _ }) (λ c₁ c₂ ih₁ ih₂, by { rw add_smul, exact add_mem _ ih₁ ih₂ }) (λ b c hc, by { rw is_scalar_tower.smul_assoc, exact smul_mem _ _ hc }) theorem smul_mem_span_smul {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R t) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hx) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy }) (λ c x hx, smul_left_comm c k x ▸ smul_mem _ _ hx) theorem smul_mem_span_smul' {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R (s • t)) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, let ⟨p, q, hp, hq, hpq⟩ := set.mem_smul.1 hx in by { rw [← hpq, smul_smul], exact smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hq }) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy }) (λ c x hx, smul_left_comm c k x ▸ smul_mem _ _ hx) theorem span_smul {s : set S} (hs : span R s = ⊤) (t : set A) : span R (s • t) = (span S t).restrict_scalars' R := le_antisymm (span_le.2 $ λ x hx, let ⟨p, q, hps, hqt, hpqx⟩ := set.mem_smul.1 hx in hpqx ▸ (span S t).smul_mem p (subset_span hqt)) $ λ p hp, span_induction hp (λ x hx, one_smul S x ▸ smul_mem_span_smul hs (subset_span hx)) (zero_mem _) (λ _ _, add_mem _) (λ k x hx, smul_mem_span_smul' hs hx) end submodule end semiring section ring open_locale big_operators classical universes v₁ w₁ variables {R S A} variables [comm_ring R] [ring S] [add_comm_group A] variables [algebra R S] [module S A] [module R A] [is_scalar_tower R S A] theorem linear_independent_smul {ι : Type v₁} {b : ι → S} {κ : Type w₁} {c : κ → A} (hb : linear_independent R b) (hc : linear_independent S c) : linear_independent R (λ p : ι × κ, b p.1 • c p.2) := begin rw linear_independent_iff' at hb hc, rw linear_independent_iff'', rintros s g hg hsg ⟨i, k⟩, by_cases hik : (i, k) ∈ s, { have h1 : ∑ i in (s.image prod.fst).product (s.image prod.snd), g i • b i.1 • c i.2 = 0, { rw ← hsg, exact (finset.sum_subset finset.subset_product $ λ p _ hp, show g p • b p.1 • c p.2 = 0, by rw [hg p hp, zero_smul]).symm }, rw [finset.sum_product, finset.sum_comm] at h1, simp_rw [← smul_assoc, ← finset.sum_smul] at h1, exact hb _ _ (hc _ _ h1 k (finset.mem_image_of_mem _ hik)) i (finset.mem_image_of_mem _ hik) }, exact hg _ hik end theorem is_basis.smul {ι : Type v₁} {b : ι → S} {κ : Type w₁} {c : κ → A} (hb : is_basis R b) (hc : is_basis S c) : is_basis R (λ p : ι × κ, b p.1 • c p.2) := ⟨linear_independent_smul hb.1 hc.1, by rw [← set.range_smul_range, submodule.span_smul hb.2, ← submodule.restrict_scalars'_top R S A, submodule.restrict_scalars'_inj, hc.2]⟩ end ring
f837215289719638e3d1aa2fddd2f5f98df234fa
9bb72db9297f7837f673785604fb89b3184e13f8
/library/init/core.lean
4c81a7e5fabbd6cb2ae82de531840f7e8d650857
[ "Apache-2.0" ]
permissive
dselsam/lean
ec83d7592199faa85687d884bbaaa570b62c1652
6b0bd5bc2e07e13880d332c89093fe3032bb2469
refs/heads/master
1,621,807,064,966
1,611,454,685,000
1,611,975,642,000
42,734,348
3
3
null
1,498,748,560,000
1,442,594,289,000
C++
UTF-8
Lean
false
false
20,440
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude notation `Prop` := Sort 0 notation f ` $ `:1 a:0 := f a /- Reserving notation. We do this so that the precedence of all of the operators can be seen in one place and to prevent core notation being accidentally overloaded later. -/ /- Notation for logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 -- not used reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 -- eq reserve infix ` == `:50 -- heq reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 -- has_equiv.equiv reserve infix ` ~ `:50 -- used as local notation for relations reserve infix ` ≡ `:50 -- not used reserve infixl ` ⬝ `:75 -- not used reserve infixr ` ▸ `:75 -- eq.subst reserve infixr ` ▹ `:75 -- not used /- types and type constructors -/ reserve infixr ` ⊕ `:30 -- sum (defined in init/data/sum/basic.lean) reserve infixr ` × `:35 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve prefix `-`:75 reserve infixr ` ^ `:80 reserve infixr ` ∘ `:90 -- function composition reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve infixl ` && `:70 reserve infixl ` || `:65 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 reserve infix ` ⊂ `:50 reserve infix ` ⊃ `:50 reserve infix ` \ `:70 -- symmetric difference /- other symbols -/ reserve infix ` ∣ `:50 -- has_dvd.dvd. Note this is different to `|`. reserve infixl ` ++ `:65 -- has_append.append reserve infixr ` :: `:67 -- list.cons reserve infixl `; `:1 -- has_andthen.andthen universes u v w /-- The kernel definitional equality test (t =?= s) has special support for id_delta applications. It implements the following rules 1) (id_delta t) =?= t 2) t =?= (id_delta t) 3) (id_delta t) =?= s IF (unfold_of t) =?= s 4) t =?= id_delta s IF t =?= (unfold_of s) This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel. We use id_delta applications to address performance problems when type checking lemmas generated by the equation compiler. -/ @[inline] def id_delta {α : Sort u} (a : α) : α := a /-- Gadget for optional parameter support. -/ @[reducible] def opt_param (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def out_param (α : Sort u) : Sort u := α /- id_rhs is an auxiliary declaration used in the equation compiler to address performance issues when proving equational lemmas. The equation compiler uses it as a marker. -/ abbreviation id_rhs (α : Sort u) (a : α) : α := a inductive punit : Sort u | star : punit /-- An abbreviation for `punit.{0}`, its most common instantiation. This type should be preferred over `punit` where possible to avoid unnecessary universe parameters. -/ abbreviation unit : Type := punit @[pattern] abbreviation unit.star : unit := punit.star /-- Gadget for defining thunks, thunk parameters have special treatment. Example: given def f (s : string) (t : thunk nat) : nat an application f "hello" 10 is converted into f "hello" (λ _, 10) -/ @[reducible] def thunk (α : Type u) : Type u := unit → α inductive true : Prop | intro : true inductive false : Prop inductive empty : Type /-- Logical not. `not P`, with notation `¬ P`, is the `Prop` which is true if and only if `P` is false. It is internally represented as `P → false`, so one way to prove a goal `⊢ ¬ P` is to use `intro h`, which gives you a new hypothesis `h : P` and the goal `⊢ false`. A hypothesis `h : ¬ P` can be used in term mode as a function, so if `w : P` then `h w : false`. Related mathlib tactic: `contrapose`. -/ def not (a : Prop) := a → false prefix `¬` := not inductive eq {α : Sort u} (a : α) : α → Prop | refl [] : eq a /- Initialize the quotient module, which effectively adds the following definitions: constant quot {α : Sort u} (r : α → α → Prop) : Sort u constant quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : quot r constant quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → eq (f a) (f b)) → quot r → β constant quot.ind {α : Sort u} {r : α → α → Prop} {β : quot r → Prop} : (∀ a : α, β (quot.mk r a)) → ∀ q : quot r, β q Also the reduction rule: quot.lift f _ (quot.mk a) ~~> f a -/ init_quotient /-- Heterogeneous equality. Its purpose is to write down equalities between terms whose types are not definitionally equal. For example, given `x : vector α n` and `y : vector α (0+n)`, `x = y` doesn't typecheck but `x == y` does. If you have a goal `⊢ x == y`, your first instinct should be to ask (either yourself, or on [zulip](https://leanprover.zulipchat.com/)) if something has gone wrong already. If you really do need to follow this route, you may find the lemmas `eq_rec_heq` and `eq_mpr_heq` useful. -/ inductive heq {α : Sort u} (a : α) : Π {β : Sort u}, β → Prop | refl [] : heq a structure prod (α : Type u) (β : Type v) := (fst : α) (snd : β) /-- Similar to `prod`, but α and β can be propositions. We use this type internally to automatically generate the brec_on recursor. -/ structure pprod (α : Sort u) (β : Sort v) := (fst : α) (snd : β) /-- Logical and. `and P Q`, with notation `P ∧ Q`, is the `Prop` which is true precisely when `P` and `Q` are both true. To prove a goal `⊢ P ∧ Q`, you can use the tactic `split`, which gives two separate goals `⊢ P` and `⊢ Q`. Given a hypothesis `h : P ∧ Q`, you can use the tactic `cases h with hP hQ` to obtain two new hypotheses `hP : P` and `hQ : Q`. See also the `obtain` or `rcases` tactics in mathlib. -/ structure and (a b : Prop) : Prop := intro :: (left : a) (right : b) def and.elim_left {a b : Prop} (h : and a b) : a := h.1 def and.elim_right {a b : Prop} (h : and a b) : b := h.2 /- eq basic support -/ infix = := eq attribute [refl] eq.refl @[pattern] def rfl {α : Sort u} {a : α} : a = a := eq.refl a @[elab_as_eliminator, subst] lemma eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b := eq.rec h₂ h₁ notation h1 ▸ h2 := eq.subst h1 h2 @[trans] lemma eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ @[symm] lemma eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a := h ▸ rfl infix == := heq @[pattern] def heq.rfl {α : Sort u} {a : α} : a == a := heq.refl a lemma eq_of_heq {α : Sort u} {a a' : α} (h : a == a') : a = a' := have ∀ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a') (h₂ : α = α'), (eq.rec_on h₂ a : α') = a', from λ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a'), heq.rec_on h₁ (λ h₂ : α = α, rfl), show (eq.rec_on (eq.refl α) a : α) = a', from this α a' h (eq.refl α) /- The following four lemmas could not be automatically generated when the structures were declared, so we prove them manually here. -/ lemma prod.mk.inj {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → and (x₁ = x₂) (y₁ = y₂) := λ h, prod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩) lemma prod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P := λ h₁ _ h₂, prod.no_confusion h₁ h₂ lemma pprod.mk.inj {α : Sort u} {β : Sort v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : pprod.mk x₁ y₁ = pprod.mk x₂ y₂ → and (x₁ = x₂) (y₁ = y₂) := λ h, pprod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩) lemma pprod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P := λ h₁ _ h₂, prod.no_confusion h₁ h₂ inductive sum (α : Type u) (β : Type v) | inl (val : α) : sum | inr (val : β) : sum inductive psum (α : Sort u) (β : Sort v) | inl (val : α) : psum | inr (val : β) : psum /-- Logical or. `or P Q`, with notation `P ∨ Q`, is the proposition which is true if and only if `P` or `Q` is true. To prove a goal `⊢ P ∨ Q`, if you know which alternative you want to prove, you can use the tactics `left` (which gives the goal `⊢ P`) or `right` (which gives the goal `⊢ Q`). Given a hypothesis `h : P ∨ Q` and goal `⊢ R`, the tactic `cases h` will give you two copies of the goal `⊢ R`, with the hypothesis `h : P` in the first, and the hypothesis `h : Q` in the second. -/ inductive or (a b : Prop) : Prop | inl (h : a) : or | inr (h : b) : or def or.intro_left {a : Prop} (b : Prop) (ha : a) : or a b := or.inl ha def or.intro_right (a : Prop) {b : Prop} (hb : b) : or a b := or.inr hb structure sigma {α : Type u} (β : α → Type v) := mk :: (fst : α) (snd : β fst) structure psigma {α : Sort u} (β : α → Sort v) := mk :: (fst : α) (snd : β fst) inductive bool : Type | ff : bool | tt : bool /- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/ structure subtype {α : Sort u} (p : α → Prop) := (val : α) (property : p val) attribute [pp_using_anonymous_constructor] sigma psigma subtype pprod and class inductive decidable (p : Prop) | is_false (h : ¬p) : decidable | is_true (h : p) : decidable @[reducible] def decidable_pred {α : Sort u} (r : α → Prop) := Π (a : α), decidable (r a) @[reducible] def decidable_rel {α : Sort u} (r : α → α → Prop) := Π (a b : α), decidable (r a b) @[reducible] def decidable_eq (α : Sort u) := decidable_rel (@eq α) inductive option (α : Type u) | none : option | some (val : α) : option export option (none some) export bool (ff tt) inductive list (T : Type u) | nil : list | cons (hd : T) (tl : list) : list notation h :: t := list.cons h t notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l inductive nat | zero : nat | succ (n : nat) : nat structure unification_constraint := {α : Type u} (lhs : α) (rhs : α) infix ` ≟ `:50 := unification_constraint.mk infix ` =?= `:50 := unification_constraint.mk structure unification_hint := (pattern : unification_constraint) (constraints : list unification_constraint) /- Declare builtin and reserved notation -/ class has_zero (α : Type u) := (zero : α) class has_one (α : Type u) := (one : α) class has_add (α : Type u) := (add : α → α → α) class has_mul (α : Type u) := (mul : α → α → α) class has_inv (α : Type u) := (inv : α → α) class has_neg (α : Type u) := (neg : α → α) class has_sub (α : Type u) := (sub : α → α → α) class has_div (α : Type u) := (div : α → α → α) class has_dvd (α : Type u) := (dvd : α → α → Prop) class has_mod (α : Type u) := (mod : α → α → α) class has_le (α : Type u) := (le : α → α → Prop) class has_lt (α : Type u) := (lt : α → α → Prop) class has_append (α : Type u) := (append : α → α → α) class has_andthen (α : Type u) (β : Type v) (σ : out_param $ Type w) := (andthen : α → β → σ) class has_union (α : Type u) := (union : α → α → α) class has_inter (α : Type u) := (inter : α → α → α) class has_sdiff (α : Type u) := (sdiff : α → α → α) class has_equiv (α : Sort u) := (equiv : α → α → Prop) class has_subset (α : Type u) := (subset : α → α → Prop) class has_ssubset (α : Type u) := (ssubset : α → α → Prop) /- Type classes has_emptyc and has_insert are used to implement polymorphic notation for collections. Example: {a, b, c}. -/ class has_emptyc (α : Type u) := (emptyc : α) class has_insert (α : out_param $ Type u) (γ : Type v) := (insert : α → γ → γ) class has_singleton (α : out_param $ Type u) (β : Type v) := (singleton : α → β) /- Type class used to implement the notation { a ∈ c | p a } -/ class has_sep (α : out_param $ Type u) (γ : Type v) := (sep : (α → Prop) → γ → γ) /- Type class for set-like membership -/ class has_mem (α : out_param $ Type u) (γ : Type v) := (mem : α → γ → Prop) class has_pow (α : Type u) (β : Type v) := (pow : α → β → α) export has_andthen (andthen) export has_pow (pow) infix ∈ := has_mem.mem notation a ∉ s := ¬ has_mem.mem a s infix + := has_add.add infix * := has_mul.mul infix - := has_sub.sub infix / := has_div.div infix ∣ := has_dvd.dvd infix % := has_mod.mod prefix - := has_neg.neg infix <= := has_le.le infix ≤ := has_le.le infix < := has_lt.lt infix ++ := has_append.append infix ; := andthen notation `∅` := has_emptyc.emptyc infix ∪ := has_union.union infix ∩ := has_inter.inter infix ⊆ := has_subset.subset infix ⊂ := has_ssubset.ssubset infix \ := has_sdiff.sdiff infix ≈ := has_equiv.equiv infixr ^ := has_pow.pow export has_append (append) @[reducible] def ge {α : Type u} [has_le α] (a b : α) : Prop := has_le.le b a @[reducible] def gt {α : Type u} [has_lt α] (a b : α) : Prop := has_lt.lt b a infix >= := ge infix ≥ := ge infix > := gt @[reducible] def superset {α : Type u} [has_subset α] (a b : α) : Prop := has_subset.subset b a @[reducible] def ssuperset {α : Type u} [has_ssubset α] (a b : α) : Prop := has_ssubset.ssubset b a infix ⊇ := superset infix ⊃ := ssuperset def bit0 {α : Type u} [s : has_add α] (a : α) : α := a + a def bit1 {α : Type u} [s₁ : has_one α] [s₂ : has_add α] (a : α) : α := (bit0 a) + 1 attribute [pattern] has_zero.zero has_one.one bit0 bit1 has_add.add has_neg.neg export has_insert (insert) class is_lawful_singleton (α : Type u) (β : Type v) [has_emptyc β] [has_insert α β] [has_singleton α β] : Prop := (insert_emptyc_eq : ∀ (x : α), (insert x ∅ : β) = {x}) export has_singleton (singleton) export is_lawful_singleton (insert_emptyc_eq) attribute [simp] insert_emptyc_eq /- nat basic instances -/ namespace nat protected def add : nat → nat → nat | a zero := a | a (succ b) := succ (add a b) /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation compiler. -/ attribute [pattern] nat.add nat.add._main end nat instance : has_zero nat := ⟨nat.zero⟩ instance : has_one nat := ⟨nat.succ (nat.zero)⟩ instance : has_add nat := ⟨nat.add⟩ def std.priority.default : nat := 1000 def std.priority.max : nat := 0xFFFFFFFF namespace nat protected def prio := std.priority.default + 100 end nat /- Global declarations of right binding strength If a module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ def std.prec.max : nat := 1024 -- the strength of application, identifiers, (, [, etc. def std.prec.arrow : nat := 25 /- The next def is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ def std.prec.max_plus : nat := std.prec.max + 10 reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv postfix ⁻¹ := has_inv.inv notation α × β := prod α β -- notation for n-ary tuples /- sizeof -/ class has_sizeof (α : Sort u) := (sizeof : α → nat) def sizeof {α : Sort u} [s : has_sizeof α] : α → nat := has_sizeof.sizeof /- Declare sizeof instances and lemmas for types declared before has_sizeof. From now on, the inductive compiler will automatically generate sizeof instances and lemmas. -/ /- Every type `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/ protected def default.sizeof (α : Sort u) : α → nat | a := 0 instance default_has_sizeof (α : Sort u) : has_sizeof α := ⟨default.sizeof α⟩ protected def nat.sizeof : nat → nat | n := n instance : has_sizeof nat := ⟨nat.sizeof⟩ protected def prod.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (prod α β) → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (prod α β) := ⟨prod.sizeof⟩ protected def sum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (sum α β) → nat | (sum.inl a) := 1 + sizeof a | (sum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (sum α β) := ⟨sum.sizeof⟩ protected def psum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (psum α β) → nat | (psum.inl a) := 1 + sizeof a | (psum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) := ⟨psum.sizeof⟩ protected def sigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : sigma β → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (sigma β) := ⟨sigma.sizeof⟩ protected def psigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : psigma β → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (psigma β) := ⟨psigma.sizeof⟩ protected def punit.sizeof : punit → nat | u := 1 instance : has_sizeof punit := ⟨punit.sizeof⟩ protected def bool.sizeof : bool → nat | b := 1 instance : has_sizeof bool := ⟨bool.sizeof⟩ protected def option.sizeof {α : Type u} [has_sizeof α] : option α → nat | none := 1 | (some a) := 1 + sizeof a instance (α : Type u) [has_sizeof α] : has_sizeof (option α) := ⟨option.sizeof⟩ protected def list.sizeof {α : Type u} [has_sizeof α] : list α → nat | list.nil := 1 | (list.cons a l) := 1 + sizeof a + list.sizeof l instance (α : Type u) [has_sizeof α] : has_sizeof (list α) := ⟨list.sizeof⟩ protected def subtype.sizeof {α : Type u} [has_sizeof α] {p : α → Prop} : subtype p → nat | ⟨a, _⟩ := sizeof a instance {α : Type u} [has_sizeof α] (p : α → Prop) : has_sizeof (subtype p) := ⟨subtype.sizeof⟩ lemma nat_add_zero (n : nat) : n + 0 = n := rfl /- Combinator calculus -/ namespace combinator universes u₁ u₂ u₃ def I {α : Type u₁} (a : α) := a def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) := a def S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) := x z (y z) end combinator /-- Auxiliary datatype for #[ ... ] notation. #[1, 2, 3, 4] is notation for bin_tree.node (bin_tree.node (bin_tree.leaf 1) (bin_tree.leaf 2)) (bin_tree.node (bin_tree.leaf 3) (bin_tree.leaf 4)) We use this notation to input long sequences without exhausting the system stack space. Later, we define a coercion from `bin_tree` into `list`. -/ inductive bin_tree (α : Type u) | empty : bin_tree | leaf (val : α) : bin_tree | node (left right : bin_tree) : bin_tree attribute [elab_simple] bin_tree.node bin_tree.leaf /- Basic unification hints -/ @[unify] def add_succ_defeq_succ_add_hint (x y z : nat) : unification_hint := { pattern := x + nat.succ y ≟ nat.succ z, constraints := [z ≟ x + y] } /-- Like `by apply_instance`, but not dependent on the tactic framework. -/ @[reducible] def infer_instance {α : Sort u} [i : α] : α := i
0f7a069ba34f6e7338eae92b3830448c9da386e3
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/tactic/monotonicity/basic.lean
5ac8363a32eddf36cbf9b5bfa9684359cc15f832
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
5,489
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.core import category.basic import algebra.order_functions import algebra.order import meta.rb_map namespace tactic.interactive open tactic list open lean lean.parser interactive open interactive.types structure mono_cfg := (unify := ff) @[derive [decidable_eq,has_reflect]] inductive mono_selection : Type | left : mono_selection | right : mono_selection | both : mono_selection section compare parameter opt : mono_cfg meta def compare (e₀ e₁ : expr) : tactic unit := do if opt.unify then do guard (¬ e₀.is_mvar ∧ ¬ e₁.is_mvar), unify e₀ e₁ else is_def_eq e₀ e₁ meta def find_one_difference : list expr → list expr → tactic (list expr × expr × expr × list expr) | (x :: xs) (y :: ys) := do c ← try_core (compare x y), if c.is_some then prod.map (cons x) id <$> find_one_difference xs ys else do guard (xs.length = ys.length), mzip_with' compare xs ys, return ([],x,y,xs) | xs ys := fail format!"find_one_difference: {xs}, {ys}" end compare def last_two {α : Type*} (l : list α) : option (α × α) := match l.reverse with | (x₁ :: x₀ :: _) := some (x₀, x₁) | _ := none end meta def match_imp : expr → tactic (expr × expr) | `(%%e₀ → %%e₁) := do guard (¬ e₁.has_var), return (e₀,e₁) | _ := failed open expr meta def same_operator : expr → expr → bool | (app e₀ _) (app e₁ _) := let fn₀ := e₀.get_app_fn, fn₁ := e₁.get_app_fn in fn₀.is_constant ∧ fn₀.const_name = fn₁.const_name | (pi _ _ _ _) (pi _ _ _ _) := tt | _ _ := ff meta def get_operator (e : expr) : option name := guard (¬ e.is_pi) >> pure e.get_app_fn.const_name meta def monotoncity.check_rel (xs : list expr) (l r : expr) : tactic (option name) := do guard (same_operator l r) <|> do { fail format!"{l} and {r} should be the f x and f y for some f" }, if l.is_pi then pure none else pure r.get_app_fn.const_name @[reducible] def mono_key := (with_bot name × with_bot name) open nat meta def mono_head_candidates : ℕ → list expr → expr → tactic mono_key | 0 _ h := failed | (succ n) xs h := do { (rel,l,r) ← if h.is_arrow then pure (none,h.binding_domain,h.binding_body) else guard h.get_app_fn.is_constant >> prod.mk (some h.get_app_fn.const_name) <$> last_two h.get_app_args, prod.mk <$> monotoncity.check_rel xs.reverse l r <*> pure rel } <|> match xs with | [] := fail format!"oh? {h}" | (x::xs) := mono_head_candidates n xs (h.pis [x]) end meta def monotoncity.check (lm_n : name) (prio : ℕ) (persistent : bool) : tactic mono_key := do lm ← mk_const lm_n, lm_t ← infer_type lm, (xs,h) ← mk_local_pis lm_t, mono_head_candidates 3 xs.reverse h meta instance : has_to_format mono_selection := ⟨ λ x, match x with | mono_selection.left := "left" | mono_selection.right := "right" | mono_selection.both := "both" end ⟩ meta def side : lean.parser mono_selection := with_desc "expecting 'left', 'right' or 'both' (default)" $ do some n ← optional ident | pure mono_selection.both, if n = `left then pure $ mono_selection.left else if n = `right then pure $ mono_selection.right else if n = `both then pure $ mono_selection.both else fail format!"invalid argument: {n}, expecting 'left', 'right' or 'both' (default)" open function @[user_attribute] meta def monotonicity.attr : user_attribute (native.rb_map mono_key (list name)) (option mono_key × mono_selection) := { name := `mono , descr := "monotonicity of function `f` wrt relations `R₀` and `R₁`: R₀ x y → R₁ (f x) (f y)" , cache_cfg := { dependencies := [], mk_cache := λ ls, do ps ← ls.mmap monotonicity.attr.get_param, let ps := ps.filter_map prod.fst, pure $ (ps.zip ls).foldl (flip $ uncurry native.rb_map.insert_cons) (native.rb_map.mk mono_key _) } , after_set := some $ λ n prio p, do { (none,v) ← monotonicity.attr.get_param n | pure (), k ← monotoncity.check n prio p, monotonicity.attr.set n (some k,v) p } , parser := prod.mk none <$> side } meta def filter_instances (e : mono_selection) (ns : list name) : tactic (list name) := ns.mfilter $ λ n, do d ← user_attribute.get_param_untyped monotonicity.attr n, (_,d) ← to_expr ``(id %%d) >>= eval_expr (option mono_key × mono_selection), return (e = d : bool) meta def get_monotonicity_lemmas (k : expr) (e : mono_selection) : tactic (list name) := do ns ← monotonicity.attr.get_cache, k' ← if k.is_pi then pure (get_operator k.binding_domain,none) else do { (x₀,x₁) ← last_two k.get_app_args, pure (get_operator x₀,some k.get_app_fn.const_name) }, let ns := ns.find_def [] k', ns' ← filter_instances e ns, if e ≠ mono_selection.both then (++) ns' <$> filter_instances mono_selection.both ns else pure ns' end tactic.interactive attribute [mono] add_le_add mul_le_mul neg_le_neg mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right imp_imp_imp le_implies_le_of_le_of_le sub_le_sub abs_le_abs attribute [mono left] add_lt_add_of_le_of_lt mul_lt_mul' attribute [mono right] add_lt_add_of_lt_of_le mul_lt_mul open tactic.interactive
c84d7828c8591b43c764d1519a8364b7ceb7e07e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/ODE/picard_lindelof.lean
4e670e38341cb66e6995fae3a906554da2f88a7a
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
20,024
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, Winston Yin -/ import analysis.special_functions.integrals import topology.metric_space.contracting /-! # Picard-Lindelöf (Cauchy-Lipschitz) Theorem In this file we prove that an ordinary differential equation $\dot x=v(t, x)$ such that $v$ is Lipschitz continuous in $x$ and continuous in $t$ has a local solution, see `exists_forall_deriv_within_Icc_eq_of_is_picard_lindelof`. As a corollary, we prove that a time-independent locally continuously differentiable ODE has a local solution. ## Implementation notes In order to split the proof into small lemmas, we introduce a structure `picard_lindelof` that holds all assumptions of the main theorem. This structure and lemmas in the `picard_lindelof` namespace should be treated as private implementation details. This is not to be confused with the `Prop`- valued structure `is_picard_lindelof`, which holds the long hypotheses of the Picard-Lindelöf theorem for actual use as part of the public API. We only prove existence of a solution in this file. For uniqueness see `ODE_solution_unique` and related theorems in `analysis.ODE.gronwall`. ## Tags differential equation -/ open filter function set metric topological_space interval_integral measure_theory open measure_theory.measure_space (volume) open_locale filter topological_space nnreal ennreal nat interval noncomputable theory variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] /-- `Prop` structure holding the hypotheses of the Picard-Lindelöf theorem. The similarly named `picard_lindelof` structure is part of the internal API for convenience, so as not to constantly invoke choice, but is not intended for public use. -/ structure is_picard_lindelof {E : Type*} [normed_add_comm_group E] (v : ℝ → E → E) (t_min t₀ t_max : ℝ) (x₀ : E) (L : ℝ≥0) (R C : ℝ) : Prop := (ht₀ : t₀ ∈ Icc t_min t_max) (hR : 0 ≤ R) (lipschitz : ∀ t ∈ Icc t_min t_max, lipschitz_on_with L (v t) (closed_ball x₀ R)) (cont : ∀ x ∈ closed_ball x₀ R, continuous_on (λ (t : ℝ), v t x) (Icc t_min t_max)) (norm_le : ∀ (t ∈ Icc t_min t_max) (x ∈ closed_ball x₀ R), ‖v t x‖ ≤ C) (C_mul_le_R : (C : ℝ) * linear_order.max (t_max - t₀) (t₀ - t_min) ≤ R) /-- This structure holds arguments of the Picard-Lipschitz (Cauchy-Lipschitz) theorem. It is part of the internal API for convenience, so as not to constantly invoke choice. Unless you want to use one of the auxiliary lemmas, use `exists_forall_deriv_within_Icc_eq_of_lipschitz_of_continuous` instead of using this structure. The similarly named `is_picard_lindelof` is a bundled `Prop` holding the long hypotheses of the Picard-Lindelöf theorem as named arguments. It is used as part of the public API. -/ structure picard_lindelof (E : Type*) [normed_add_comm_group E] [normed_space ℝ E] := (to_fun : ℝ → E → E) (t_min t_max : ℝ) (t₀ : Icc t_min t_max) (x₀ : E) (C R L : ℝ≥0) (is_pl : is_picard_lindelof to_fun t_min t₀ t_max x₀ L R C) namespace picard_lindelof variables (v : picard_lindelof E) instance : has_coe_to_fun (picard_lindelof E) (λ _, ℝ → E → E) := ⟨to_fun⟩ instance : inhabited (picard_lindelof E) := ⟨⟨0, 0, 0, ⟨0, le_rfl, le_rfl⟩, 0, 0, 0, 0, { ht₀ := by { rw [subtype.coe_mk, Icc_self], exact mem_singleton _ }, hR := by refl, lipschitz := λ t ht, (lipschitz_with.const 0).lipschitz_on_with _, cont := λ _ _, by simpa only [pi.zero_apply] using continuous_on_const, norm_le := λ t ht x hx, norm_zero.le, C_mul_le_R := (zero_mul _).le }⟩⟩ lemma t_min_le_t_max : v.t_min ≤ v.t_max := v.t₀.2.1.trans v.t₀.2.2 protected lemma nonempty_Icc : (Icc v.t_min v.t_max).nonempty := nonempty_Icc.2 v.t_min_le_t_max protected lemma lipschitz_on_with {t} (ht : t ∈ Icc v.t_min v.t_max) : lipschitz_on_with v.L (v t) (closed_ball v.x₀ v.R) := v.is_pl.lipschitz t ht protected lemma continuous_on : continuous_on (uncurry v) (Icc v.t_min v.t_max ×ˢ closed_ball v.x₀ v.R) := have continuous_on (uncurry (flip v)) (closed_ball v.x₀ v.R ×ˢ Icc v.t_min v.t_max), from continuous_on_prod_of_continuous_on_lipschitz_on _ v.L v.is_pl.cont v.is_pl.lipschitz, this.comp continuous_swap.continuous_on (preimage_swap_prod _ _).symm.subset lemma norm_le {t : ℝ} (ht : t ∈ Icc v.t_min v.t_max) {x : E} (hx : x ∈ closed_ball v.x₀ v.R) : ‖v t x‖ ≤ v.C := v.is_pl.norm_le _ ht _ hx /-- The maximum of distances from `t₀` to the endpoints of `[t_min, t_max]`. -/ def t_dist : ℝ := max (v.t_max - v.t₀) (v.t₀ - v.t_min) lemma t_dist_nonneg : 0 ≤ v.t_dist := le_max_iff.2 $ or.inl $ sub_nonneg.2 v.t₀.2.2 lemma dist_t₀_le (t : Icc v.t_min v.t_max) : dist t v.t₀ ≤ v.t_dist := begin rw [subtype.dist_eq, real.dist_eq], cases le_total t v.t₀ with ht ht, { rw [abs_of_nonpos (sub_nonpos.2 $ subtype.coe_le_coe.2 ht), neg_sub], exact (sub_le_sub_left t.2.1 _).trans (le_max_right _ _) }, { rw [abs_of_nonneg (sub_nonneg.2 $ subtype.coe_le_coe.2 ht)], exact (sub_le_sub_right t.2.2 _).trans (le_max_left _ _) } end /-- Projection $ℝ → [t_{\min}, t_{\max}]$ sending $(-∞, t_{\min}]$ to $t_{\min}$ and $[t_{\max}, ∞)$ to $t_{\max}$. -/ def proj : ℝ → Icc v.t_min v.t_max := proj_Icc v.t_min v.t_max v.t_min_le_t_max lemma proj_coe (t : Icc v.t_min v.t_max) : v.proj t = t := proj_Icc_coe _ _ lemma proj_of_mem {t : ℝ} (ht : t ∈ Icc v.t_min v.t_max) : ↑(v.proj t) = t := by simp only [proj, proj_Icc_of_mem _ ht, subtype.coe_mk] @[continuity] lemma continuous_proj : continuous v.proj := continuous_proj_Icc /-- The space of curves $γ \colon [t_{\min}, t_{\max}] \to E$ such that $γ(t₀) = x₀$ and $γ$ is Lipschitz continuous with constant $C$. The map sending $γ$ to $\mathbf Pγ(t)=x₀ + ∫_{t₀}^{t} v(τ, γ(τ))\,dτ$ is a contracting map on this space, and its fixed point is a solution of the ODE $\dot x=v(t, x)$. -/ structure fun_space := (to_fun : Icc v.t_min v.t_max → E) (map_t₀' : to_fun v.t₀ = v.x₀) (lipschitz' : lipschitz_with v.C to_fun) namespace fun_space variables {v} (f : fun_space v) instance : has_coe_to_fun (fun_space v) (λ _, Icc v.t_min v.t_max → E) := ⟨to_fun⟩ instance : inhabited v.fun_space := ⟨⟨λ _, v.x₀, rfl, (lipschitz_with.const _).weaken (zero_le _)⟩⟩ protected lemma lipschitz : lipschitz_with v.C f := f.lipschitz' protected lemma continuous : continuous f := f.lipschitz.continuous /-- Each curve in `picard_lindelof.fun_space` is continuous. -/ def to_continuous_map : v.fun_space ↪ C(Icc v.t_min v.t_max, E) := ⟨λ f, ⟨f, f.continuous⟩, λ f g h, by { cases f, cases g, simpa using h }⟩ instance : metric_space v.fun_space := metric_space.induced to_continuous_map to_continuous_map.injective infer_instance lemma uniform_inducing_to_continuous_map : uniform_inducing (@to_continuous_map _ _ _ v) := ⟨rfl⟩ lemma range_to_continuous_map : range to_continuous_map = {f : C(Icc v.t_min v.t_max, E) | f v.t₀ = v.x₀ ∧ lipschitz_with v.C f} := begin ext f, split, { rintro ⟨⟨f, hf₀, hf_lip⟩, rfl⟩, exact ⟨hf₀, hf_lip⟩ }, { rcases f with ⟨f, hf⟩, rintro ⟨hf₀, hf_lip⟩, exact ⟨⟨f, hf₀, hf_lip⟩, rfl⟩ } end lemma map_t₀ : f v.t₀ = v.x₀ := f.map_t₀' protected lemma mem_closed_ball (t : Icc v.t_min v.t_max) : f t ∈ closed_ball v.x₀ v.R := calc dist (f t) v.x₀ = dist (f t) (f.to_fun v.t₀) : by rw f.map_t₀' ... ≤ v.C * dist t v.t₀ : f.lipschitz.dist_le_mul _ _ ... ≤ v.C * v.t_dist : mul_le_mul_of_nonneg_left (v.dist_t₀_le _) v.C.2 ... ≤ v.R : v.is_pl.C_mul_le_R /-- Given a curve $γ \colon [t_{\min}, t_{\max}] → E$, `v_comp` is the function $F(t)=v(π t, γ(π t))$, where `π` is the projection $ℝ → [t_{\min}, t_{\max}]$. The integral of this function is the image of `γ` under the contracting map we are going to define below. -/ def v_comp (t : ℝ) : E := v (v.proj t) (f (v.proj t)) lemma v_comp_apply_coe (t : Icc v.t_min v.t_max) : f.v_comp t = v t (f t) := by simp only [v_comp, proj_coe] lemma continuous_v_comp : continuous f.v_comp := begin have := (continuous_subtype_coe.prod_mk f.continuous).comp v.continuous_proj, refine continuous_on.comp_continuous v.continuous_on this (λ x, _), exact ⟨(v.proj x).2, f.mem_closed_ball _⟩ end lemma norm_v_comp_le (t : ℝ) : ‖f.v_comp t‖ ≤ v.C := v.norm_le (v.proj t).2 $ f.mem_closed_ball _ lemma dist_apply_le_dist (f₁ f₂ : fun_space v) (t : Icc v.t_min v.t_max) : dist (f₁ t) (f₂ t) ≤ dist f₁ f₂ := @continuous_map.dist_apply_le_dist _ _ _ _ _ f₁.to_continuous_map f₂.to_continuous_map _ lemma dist_le_of_forall {f₁ f₂ : fun_space v} {d : ℝ} (h : ∀ t, dist (f₁ t) (f₂ t) ≤ d) : dist f₁ f₂ ≤ d := (@continuous_map.dist_le_iff_of_nonempty _ _ _ _ _ f₁.to_continuous_map f₂.to_continuous_map _ v.nonempty_Icc.to_subtype).2 h instance [complete_space E] : complete_space v.fun_space := begin refine (complete_space_iff_is_complete_range uniform_inducing_to_continuous_map).2 (is_closed.is_complete _), rw [range_to_continuous_map, set_of_and], refine (is_closed_eq (continuous_map.continuous_eval_const _) continuous_const).inter _, have : is_closed {f : Icc v.t_min v.t_max → E | lipschitz_with v.C f} := is_closed_set_of_lipschitz_with v.C, exact this.preimage continuous_map.continuous_coe end lemma interval_integrable_v_comp (t₁ t₂ : ℝ) : interval_integrable f.v_comp volume t₁ t₂ := (f.continuous_v_comp).interval_integrable _ _ variables [complete_space E] /-- The Picard-Lindelöf operator. This is a contracting map on `picard_lindelof.fun_space v` such that the fixed point of this map is the solution of the corresponding ODE. More precisely, some iteration of this map is a contracting map. -/ def next (f : fun_space v) : fun_space v := { to_fun := λ t, v.x₀ + ∫ τ : ℝ in v.t₀..t, f.v_comp τ, map_t₀' := by rw [integral_same, add_zero], lipschitz' := lipschitz_with.of_dist_le_mul $ λ t₁ t₂, begin rw [dist_add_left, dist_eq_norm, integral_interval_sub_left (f.interval_integrable_v_comp _ _) (f.interval_integrable_v_comp _ _)], exact norm_integral_le_of_norm_le_const (λ t ht, f.norm_v_comp_le _), end } lemma next_apply (t : Icc v.t_min v.t_max) : f.next t = v.x₀ + ∫ τ : ℝ in v.t₀..t, f.v_comp τ := rfl lemma has_deriv_within_at_next (t : Icc v.t_min v.t_max) : has_deriv_within_at (f.next ∘ v.proj) (v t (f t)) (Icc v.t_min v.t_max) t := begin haveI : fact ((t : ℝ) ∈ Icc v.t_min v.t_max) := ⟨t.2⟩, simp only [(∘), next_apply], refine has_deriv_within_at.const_add _ _, have : has_deriv_within_at (λ t : ℝ, ∫ τ in v.t₀..t, f.v_comp τ) (f.v_comp t) (Icc v.t_min v.t_max) t, from integral_has_deriv_within_at_right (f.interval_integrable_v_comp _ _) (f.continuous_v_comp.strongly_measurable_at_filter _ _) f.continuous_v_comp.continuous_within_at, rw v_comp_apply_coe at this, refine this.congr_of_eventually_eq_of_mem _ t.coe_prop, filter_upwards [self_mem_nhds_within] with _ ht', rw v.proj_of_mem ht' end lemma dist_next_apply_le_of_le {f₁ f₂ : fun_space v} {n : ℕ} {d : ℝ} (h : ∀ t, dist (f₁ t) (f₂ t) ≤ (v.L * |t - v.t₀|) ^ n / n! * d) (t : Icc v.t_min v.t_max) : dist (next f₁ t) (next f₂ t) ≤ (v.L * |t - v.t₀|) ^ (n + 1) / (n + 1)! * d := begin simp only [dist_eq_norm, next_apply, add_sub_add_left_eq_sub, ← interval_integral.integral_sub (interval_integrable_v_comp _ _ _) (interval_integrable_v_comp _ _ _), norm_integral_eq_norm_integral_Ioc] at *, calc ‖∫ τ in Ι (v.t₀ : ℝ) t, f₁.v_comp τ - f₂.v_comp τ‖ ≤ ∫ τ in Ι (v.t₀ : ℝ) t, v.L * ((v.L * |τ - v.t₀|) ^ n / n! * d) : begin refine norm_integral_le_of_norm_le (continuous.integrable_on_interval_oc _) _, { continuity }, { refine (ae_restrict_mem measurable_set_Ioc).mono (λ τ hτ, _), refine (v.lipschitz_on_with (v.proj τ).2).norm_sub_le_of_le (f₁.mem_closed_ball _) (f₂.mem_closed_ball _) ((h _).trans_eq _), rw v.proj_of_mem, exact (interval_subset_Icc v.t₀.2 t.2 $ Ioc_subset_Icc_self hτ) } end ... = (v.L * |t - v.t₀|) ^ (n + 1) / (n + 1)! * d : _, simp_rw [mul_pow, div_eq_mul_inv, mul_assoc, measure_theory.integral_mul_left, measure_theory.integral_mul_right, integral_pow_abs_sub_interval_oc, div_eq_mul_inv, pow_succ (v.L : ℝ), nat.factorial_succ, nat.cast_mul, nat.cast_succ, mul_inv, mul_assoc] end lemma dist_iterate_next_apply_le (f₁ f₂ : fun_space v) (n : ℕ) (t : Icc v.t_min v.t_max) : dist (next^[n] f₁ t) (next^[n] f₂ t) ≤ (v.L * |t - v.t₀|) ^ n / n! * dist f₁ f₂ := begin induction n with n ihn generalizing t, { rw [pow_zero, nat.factorial_zero, nat.cast_one, div_one, one_mul], exact dist_apply_le_dist f₁ f₂ t }, { rw [iterate_succ_apply', iterate_succ_apply'], exact dist_next_apply_le_of_le ihn _ } end lemma dist_iterate_next_le (f₁ f₂ : fun_space v) (n : ℕ) : dist (next^[n] f₁) (next^[n] f₂) ≤ (v.L * v.t_dist) ^ n / n! * dist f₁ f₂ := begin refine dist_le_of_forall (λ t, (dist_iterate_next_apply_le _ _ _ _).trans _), have : 0 ≤ dist f₁ f₂ := dist_nonneg, have : |(t - v.t₀ : ℝ)| ≤ v.t_dist := v.dist_t₀_le t, mono*; simp only [nat.cast_nonneg, mul_nonneg, nnreal.coe_nonneg, abs_nonneg, *] end end fun_space variables [complete_space E] section lemma exists_contracting_iterate : ∃ (N : ℕ) K, contracting_with K ((fun_space.next : v.fun_space → v.fun_space)^[N]) := begin rcases ((real.tendsto_pow_div_factorial_at_top (v.L * v.t_dist)).eventually (gt_mem_nhds zero_lt_one)).exists with ⟨N, hN⟩, have : (0 : ℝ) ≤ (v.L * v.t_dist) ^ N / N!, from div_nonneg (pow_nonneg (mul_nonneg v.L.2 v.t_dist_nonneg) _) (nat.cast_nonneg _), exact ⟨N, ⟨_, this⟩, hN, lipschitz_with.of_dist_le_mul (λ f g, fun_space.dist_iterate_next_le f g N)⟩ end lemma exists_fixed : ∃ f : v.fun_space, f.next = f := let ⟨N, K, hK⟩ := exists_contracting_iterate v in ⟨_, hK.is_fixed_pt_fixed_point_iterate⟩ end /-- Picard-Lindelöf (Cauchy-Lipschitz) theorem. Use `exists_forall_deriv_within_Icc_eq_of_is_picard_lindelof` instead for the public API. -/ lemma exists_solution : ∃ f : ℝ → E, f v.t₀ = v.x₀ ∧ ∀ t ∈ Icc v.t_min v.t_max, has_deriv_within_at f (v t (f t)) (Icc v.t_min v.t_max) t := begin rcases v.exists_fixed with ⟨f, hf⟩, refine ⟨f ∘ v.proj, _, λ t ht, _⟩, { simp only [(∘), proj_coe, f.map_t₀] }, { simp only [(∘), v.proj_of_mem ht], lift t to Icc v.t_min v.t_max using ht, simpa only [hf, v.proj_coe] using f.has_deriv_within_at_next t } end end picard_lindelof lemma is_picard_lindelof.norm_le₀ {E : Type*} [normed_add_comm_group E] {v : ℝ → E → E} {t_min t₀ t_max : ℝ} {x₀ : E} {C R : ℝ} {L : ℝ≥0} (hpl : is_picard_lindelof v t_min t₀ t_max x₀ L R C) : ‖v t₀ x₀‖ ≤ C := hpl.norm_le t₀ hpl.ht₀ x₀ $ mem_closed_ball_self hpl.hR /-- Picard-Lindelöf (Cauchy-Lipschitz) theorem. -/ theorem exists_forall_deriv_within_Icc_eq_of_is_picard_lindelof [complete_space E] {v : ℝ → E → E} {t_min t₀ t_max : ℝ} (x₀ : E) {C R : ℝ} {L : ℝ≥0} (hpl : is_picard_lindelof v t_min t₀ t_max x₀ L R C) : ∃ f : ℝ → E, f t₀ = x₀ ∧ ∀ t ∈ Icc t_min t_max, has_deriv_within_at f (v t (f t)) (Icc t_min t_max) t := begin lift C to ℝ≥0 using (norm_nonneg _).trans hpl.norm_le₀, lift t₀ to Icc t_min t_max using hpl.ht₀, exact picard_lindelof.exists_solution ⟨v, t_min, t_max, t₀, x₀, C, ⟨R, hpl.hR⟩, L, { ht₀ := t₀.property, ..hpl }⟩ end variables [proper_space E] {v : E → E} (t₀ : ℝ) (x₀ : E) /-- A time-independent, locally continuously differentiable ODE satisfies the hypotheses of the Picard-Lindelöf theorem. -/ lemma exists_is_picard_lindelof_const_of_cont_diff_on_nhds {s : set E} (hv : cont_diff_on ℝ 1 v s) (hs : s ∈ 𝓝 x₀) : ∃ (ε > (0 : ℝ)) L R C, is_picard_lindelof (λ t, v) (t₀ - ε) t₀ (t₀ + ε) x₀ L R C := begin -- extract Lipschitz constant obtain ⟨L, s', hs', hlip⟩ := cont_diff_at.exists_lipschitz_on_with ((hv.cont_diff_within_at (mem_of_mem_nhds hs)).cont_diff_at hs), -- radius of closed ball in which v is bounded obtain ⟨r, hr : 0 < r, hball⟩ := metric.mem_nhds_iff.mp (inter_sets (𝓝 x₀) hs hs'), have hr' := (half_pos hr).le, obtain ⟨C, hC⟩ := (is_compact_closed_ball x₀ (r / 2)).bdd_above_image -- uses proper_space E (hv.continuous_on.norm.mono (subset_inter_iff.mp ((closed_ball_subset_ball (half_lt_self hr)).trans hball)).left), have hC' : 0 ≤ C, { apply (norm_nonneg (v x₀)).trans, apply hC, exact ⟨x₀, ⟨mem_closed_ball_self hr', rfl⟩⟩ }, set ε := if C = 0 then 1 else (r / 2 / C) with hε, have hε0 : 0 < ε, { rw hε, split_ifs, { exact zero_lt_one }, { exact div_pos (half_pos hr) (lt_of_le_of_ne hC' (ne.symm h)) } }, refine ⟨ε, hε0, L, r / 2, C, _⟩, exact { ht₀ := by {rw ←real.closed_ball_eq_Icc, exact mem_closed_ball_self hε0.le}, hR := (half_pos hr).le, lipschitz := λ t ht, hlip.mono (subset_inter_iff.mp (subset_trans (closed_ball_subset_ball (half_lt_self hr)) hball)).2, cont := λ x hx, continuous_on_const, norm_le := λ t ht x hx, hC ⟨x, hx, rfl⟩, C_mul_le_R := begin rw [add_sub_cancel', sub_sub_cancel, max_self, mul_ite, mul_one], split_ifs, { rwa ← h at hr' }, { exact (mul_div_cancel' (r / 2) h).le } end } end /-- A time-independent, locally continuously differentiable ODE admits a solution in some open interval. -/ theorem exists_forall_deriv_at_Ioo_eq_of_cont_diff_on_nhds {s : set E} (hv : cont_diff_on ℝ 1 v s) (hs : s ∈ 𝓝 x₀) : ∃ (ε > (0 : ℝ)) (f : ℝ → E), f t₀ = x₀ ∧ ∀ t ∈ Ioo (t₀ - ε) (t₀ + ε), f t ∈ s ∧ has_deriv_at f (v (f t)) t := begin obtain ⟨ε, hε, L, R, C, hpl⟩ := exists_is_picard_lindelof_const_of_cont_diff_on_nhds t₀ x₀ hv hs, obtain ⟨f, hf1, hf2⟩ := exists_forall_deriv_within_Icc_eq_of_is_picard_lindelof x₀ hpl, have hf2' : ∀ t ∈ Ioo (t₀ - ε) (t₀ + ε), has_deriv_at f (v (f t)) t := λ t ht, (hf2 t (Ioo_subset_Icc_self ht)).has_deriv_at (Icc_mem_nhds ht.1 ht.2), have h : (f ⁻¹' s) ∈ 𝓝 t₀, { have := (hf2' t₀ (mem_Ioo.mpr ⟨sub_lt_self _ hε, lt_add_of_pos_right _ hε⟩)), apply continuous_at.preimage_mem_nhds this.continuous_at, rw hf1, exact hs }, rw metric.mem_nhds_iff at h, obtain ⟨r, hr1, hr2⟩ := h, refine ⟨min r ε, lt_min hr1 hε, f, hf1, λ t ht, ⟨_, hf2' t (mem_of_mem_of_subset ht (Ioo_subset_Ioo (sub_le_sub_left (min_le_right _ _) _) (add_le_add_left (min_le_right _ _) _)))⟩⟩, rw ←set.mem_preimage, apply set.mem_of_mem_of_subset _ hr2, apply set.mem_of_mem_of_subset ht, rw ←real.ball_eq_Ioo, exact (metric.ball_subset_ball (min_le_left _ _)) end /-- A time-independent, continuously differentiable ODE admits a solution in some open interval. -/ theorem exists_forall_deriv_at_Ioo_eq_of_cont_diff (hv : cont_diff ℝ 1 v) : ∃ (ε > (0 : ℝ)) (f : ℝ → E), f t₀ = x₀ ∧ ∀ t ∈ Ioo (t₀ - ε) (t₀ + ε), has_deriv_at f (v (f t)) t := let ⟨ε, hε, f, hf1, hf2⟩ := exists_forall_deriv_at_Ioo_eq_of_cont_diff_on_nhds t₀ x₀ hv.cont_diff_on (is_open.mem_nhds is_open_univ (mem_univ _)) in ⟨ε, hε, f, hf1, λ t ht, (hf2 t ht).2⟩
3e2cb3d3501b6b02786dc4a6bf05d86c9adee550
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/real/ennreal.lean
bfb07f367c6cd4f3af47180c3c72c79f4488e8f7
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
47,843
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Yury Kudryashov Extended non-negative reals -/ import data.real.nnreal import data.set.intervals noncomputable theory open classical set open_locale classical big_operators variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered] def ennreal := with_top nnreal localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} instance : inhabited ennreal := ⟨0⟩ instance : has_coe nnreal ennreal := ⟨ option.some ⟩ instance : can_lift ennreal nnreal := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ennreal) = (⊤ : ennreal) := rfl @[simp] lemma some_eq_coe (a : nnreal) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → nnreal | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ennreal) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ennreal := coe (nnreal.of_real r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : nnreal) : (r : ennreal) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ennreal.of_real x = @coe nnreal ennreal _ (⟨x, h⟩ : nnreal) := by { rw [coe_nnreal_eq], refl } @[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] lemma coe_zero : ↑(0 : nnreal) = (0 : ennreal) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : nnreal) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ennreal).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ennreal).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : nnreal) : (r : ennreal).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ennreal} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:nnreal, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ⊤ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:nnreal) = (0:ennreal) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ⊤ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : nnreal → ennreal) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1] lemma coe_two : ((2:nnreal) : ennreal) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ennreal) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1:ennreal) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast one_lt_two @[simp] lemma two_pos : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ennreal) ≠ 0 := ne_of_gt two_pos lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add /-- Coercion `ℝ≥0 → ennreal` as a `ring_hom`. -/ def of_nnreal_hom : nnreal →+* ennreal := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → nnreal) (a : α) : ((s.indicator f a : nnreal) : ennreal) = s.indicator (λ x, f x) a := (of_nnreal_hom : nnreal →+ ennreal).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n := of_nnreal_hom.map_pow r n lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top _ _ lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top _ _ lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ⊤) (h₂ : r₂ < ⊤) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ⊤, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma not_lt_top {x : ennreal} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not] lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simp [(≠), mul_eq_top] {contextual := tt} lemma mul_lt_top : a < ⊤ → b < ⊤ → a * b < ⊤ := by simpa only [ennreal.lt_top_iff_ne_top] using mul_ne_top lemma ne_top_of_mul_ne_top_left (h : a * b ≠ ⊤) (hb : b ≠ 0) : a ≠ ⊤ := by { simp [mul_eq_top, hb, not_or_distrib] at h ⊢, exact h.2 } lemma ne_top_of_mul_ne_top_right (h : a * b ≠ ⊤) (ha : a ≠ 0) : b ≠ ⊤ := ne_top_of_mul_ne_top_left (by rwa [mul_comm]) ha lemma lt_top_of_mul_lt_top_left (h : a * b < ⊤) (hb : b ≠ 0) : a < ⊤ := by { rw [ennreal.lt_top_iff_ne_top] at h ⊢, exact ne_top_of_mul_ne_top_left h hb } lemma lt_top_of_mul_lt_top_right (h : a * b < ⊤) (ha : a ≠ 0) : b < ⊤ := lt_top_of_mul_lt_top_left (by rwa [mul_comm]) ha @[simp] lemma mul_pos : 0 < a * b ↔ 0 < a ∧ 0 < b := by simp only [zero_lt_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → nnreal} : ↑(∑ a in s, f a) = (∑ a in s, f a : ennreal) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → nnreal} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ennreal) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ (⊤:ennreal) ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe @[simp, norm_cast] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : nat) : ((n : nnreal) : ennreal) = n := with_top.coe_nat n @[simp] lemma nat_ne_top (n : nat) : (n : ennreal) ≠ ⊤ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : nat) : (⊤ : ennreal) ≠ n := with_top.top_ne_nat n @[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top lemma le_coe_iff : a ≤ ↑r ↔ (∃p:nnreal, a = p ∧ p ≤ r) := with_top.le_coe_iff r a lemma coe_le_iff : ↑r ≤ a ↔ (∀p:nnreal, a = p → r ≤ p) := with_top.coe_le_iff r a lemma lt_iff_exists_coe : a < b ↔ (∃p:nnreal, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe a b lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_refl _ }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [le_zero_iff_eq.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [zero_lt_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ⊤ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ⊤ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ⊤) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_epsilon_le : ∀{a b : ennreal}, (∀ε:nnreal, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have (⊤:ennreal) ≤ ↑a + ↑(1:nnreal), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_epsilon_le h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases dense h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:nnreal, a < r ∧ (r : ennreal) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : nnreal, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : nnreal := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ennreal) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ennreal) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ennreal) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ennreal) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ennreal) := λ _ _, coe_nat_lt_coe_nat.2 @[norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ennreal) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ennreal := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ⊤) : ∃n:ℕ, r < n := begin rcases lt_iff_exists_coe.1 (lt_top_iff_ne_top.2 h) with ⟨r, rfl, hb⟩, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin rcases dense ac with ⟨a', aa', a'c⟩, rcases lt_iff_exists_coe.1 aa' with ⟨aR, rfl, _⟩, rcases lt_iff_exists_coe.1 a'c with ⟨a'R, rfl, _⟩, rcases dense bd with ⟨b', bb', b'd⟩, rcases lt_iff_exists_coe.1 bb' with ⟨bR, rfl, _⟩, rcases lt_iff_exists_coe.1 b'd with ⟨b'R, rfl, _⟩, have I : ↑aR + ↑bR < ↑a'R + ↑b'R := begin rw [← coe_add, ← coe_add, coe_lt_coe], apply add_lt_add (coe_lt_coe.1 aa') (coe_lt_coe.1 bb') end, have J : ↑a'R + ↑b'R ≤ c + d := add_le_add (le_of_lt a'c) (le_of_lt b'd), apply lt_of_lt_of_le I J end @[norm_cast] lemma coe_min : ((min r p:nnreal):ennreal) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:nnreal):ennreal) = max r p := coe_mono.map_max end order section complete_lattice lemma coe_Sup {s : set nnreal} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set nnreal} : s.nonempty → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set nnreal} : ↑r ∈ upper_bounds ((coe : nnreal → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅n, f n) = (⨅n:nnreal, f n) ⊓ f ⊤ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) end complete_lattice section mul lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (zero_lt_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left end mul section sub instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le $ 0 + a) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_right_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right h _) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_sub_self : a ≠ ⊤ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, zero_lt_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact zero_lt_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_right (le_refl a) @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _ ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_right_inj {a b c : ennreal} (ha : a < ⊤) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ennreal} : (∀a∈s, f a < ⊤) → ∑ a in s, f a < ⊤ := with_top.sum_lt_top /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ennreal} : ∑ a in s, f a < ⊤ ↔ (∀a∈s, f a < ⊤) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ennreal} : (∑ x in s, f x) = ⊤ ↔ (∃a∈s, f a = ⊤) := with_top.sum_eq_top_iff /-- seeing `ennreal` as `nnreal` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, rw coe_to_nnreal, rw ← ennreal.lt_top_iff_ne_top, exact hf x hx }, { rw ← ennreal.lt_top_iff_ne_top, exact sum_lt_top hf } end /-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } end sum section interval variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ⊤ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ⊤ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_sub_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl lemma mul_div_assoc : (a * b) / c = a * (b / c) := mul_assoc _ _ _ @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : (∞ : ennreal)⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ennreal) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, nnreal.inv_zero, inv_zero, coe_zero, zero_le] else by simp only [coe_inv hr, le_refl] @[norm_cast] lemma coe_inv_two : ((2⁻¹:nnreal):ennreal) = 2⁻¹ := by rw [coe_inv (ne_of_gt zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r := show ↑(p * r⁻¹) = ↑p * (↑r)⁻¹, by rw [coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ennreal)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 nnreal.inv_one @[simp] lemma div_one {a : ennreal} : a / 1 = a := by simp [ennreal.div_def] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv, nnreal.inv_pow, coe_pow], rw [← ne.def] at h, rw [← zero_lt_iff_ne_zero] at *, apply pow_pos h end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ennreal, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ennreal, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_lt_top {x : ennreal} : x⁻¹ < ⊤ ↔ 0 < x := by { simp only [lt_top_iff_ne_top, inv_ne_top, zero_lt_iff_ne_zero] } lemma div_lt_top {x y : ennreal} (h1 : x < ⊤) (h2 : 0 < y) : x / y < ⊤ := mul_lt_top h1 (inv_lt_top.mpr h2) @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := zero_lt_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [zero_lt_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [div_def, top_mul, *] @[simp] lemma div_top : a / ∞ = 0 := by simp only [div_def, inv_top, mul_zero] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ⊤ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ⊤ ∧ b ≠ ⊤) := by simp [ennreal.div_def, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ⊤ ∨ c ≠ ⊤) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ⊤ = ⊤, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ennreal) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_def, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ⊤, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ⊤) (hbt : b ≠ ⊤ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], apply (le_div_iff_mul_le _ _).symm, simpa [inv_ne_zero] using hbt, simpa [inv_ne_zero] using hb0 end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ⊤, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ⊤ ∨ c ≠ ⊤) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ⊤ → a ≠ 0) → (a = ⊤ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ⊤) : a * a⁻¹ = 1 := begin lift a to nnreal using ht, norm_cast at h0, norm_cast, exact nnreal.mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ⊤) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_lt_one_mul_lt : ∀{x y : ennreal}, (∀a<1, a * x ≤ y) → x ≤ y := forall_ennreal.2 $ and.intro (assume r, forall_ennreal.2 $ and.intro (assume q h, coe_le_coe.2 $ nnreal.le_of_forall_lt_one_mul_lt $ assume a ha, begin rw [← coe_le_coe, coe_mul], exact h _ (coe_lt_coe.2 ha) end) (assume h, le_top)) (assume r hr, have ((1 / 2 : nnreal) : ennreal) * ⊤ ≤ r := hr _ (coe_lt_coe.2 ((@nnreal.coe_lt_coe (1/2) 1).1 one_half_lt_one)), have ne : ((1 / 2 : nnreal) : ennreal) ≠ 0, begin rw [(≠), coe_eq_zero], refine zero_lt_iff_ne_zero.1 _, show 0 < (1 / 2 : ℝ), exact div_pos zero_lt_one _root_.two_pos end, by rwa [mul_top, if_neg ne] at this) lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_def, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma inv_two_add_inv_two : (2:ennreal)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_def, div_self two_ne_zero two_ne_top] lemma add_halves (a : ennreal) : a / 2 + a / 2 = a := by rw [div_def, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ⊤ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ⊤ := by simp [zero_lt_iff_ne_zero, not_or_distrib] lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ennreal) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ⊤) : a / 2 < a := begin lift a to nnreal using ht, have h : (2 : ennreal) = ((2 : nnreal) : ennreal), from rfl, have h' : (2 : nnreal) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to nnreal using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ := by simpa only [div_def, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ⊤) : ∃ n : ℕ, b < n * a := begin have : b / a ≠ ⊤, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end end inv section real lemma to_real_add (ha : a ≠ ⊤) (hb : b ≠ ⊤) : (a+b).to_real = a.to_real + b.to_real := begin lift a to nnreal using ha, lift b to nnreal using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ⊤ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ⊤ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q := coe_le_coe.2 nnreal.of_real_add_le @[simp] lemma to_real_le_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real < b.to_real ↔ a < b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end lemma to_real_max (hr : a ≠ ⊤) (hp : b ≠ ⊤) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ennreal} (hb : b ≠ ⊤) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ennreal} (ha : 0 ≤ a) (hb : b ≠ ⊤) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ennreal} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ⊤, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma to_real_of_real_mul (c : ℝ) (a : ennreal) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ⊤) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_real] }, { rw [mul_top, if_neg h, top_to_real] } end @[simp] lemma to_real_top_mul (a : ennreal) : ennreal.to_real (⊤ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real (ha : a < ⊤) (hb : b < ⊤) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin rw ennreal.lt_top_iff_ne_top at *, split, { assume h, apply le_antisymm, rw ← to_real_le_to_real ha hb, exact le_of_eq h, rw ← to_real_le_to_real hb ha, exact le_of_eq h.symm }, { assume h, rw h } end lemma to_real_mul_to_real : (ennreal.to_real a) * (ennreal.to_real b) = ennreal.to_real (a * b) := begin by_cases ha : a = ⊤, { rw ha, simp }, by_cases hb : b = ⊤, { rw hb, simp }, have ha : ennreal.of_real (ennreal.to_real a) = a := of_real_to_real ha, have hb : ennreal.of_real (ennreal.to_real b) = b := of_real_to_real hb, conv_rhs { rw [← ha, ← hb, ← of_real_mul to_real_nonneg] }, rw [to_real_of_real (mul_nonneg to_real_nonneg to_real_nonneg)] end end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] lemma infi_mul {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ⊤) : infi f * x = ⨅i, f i * x := begin by_cases h2 : x = 0, simp only [h2, mul_zero, infi_const], refine le_antisymm (le_infi $ λ i, mul_right_mono $ infi_le _ _) ((div_le_iff_le_mul (or.inl h2) $ or.inl h).mp $ le_infi $ λ i, (div_le_iff_le_mul (or.inl h2) $ or.inl h).mpr $ infi_le _ _) end lemma mul_infi {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ⊤) : x * infi f = ⨅i, x * f i := by { rw [mul_comm, infi_mul h], simp only [mul_comm], assumption } /-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/ end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ⊤ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr end ennreal
eb995182c3123c81b7cdcc296cc8c3e0b89b9e32
94e33a31faa76775069b071adea97e86e218a8ee
/src/set_theory/ordinal/natural_ops.lean
82ebecb84eab6fb15ac7d8a9b70b50ebe5aca39f
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
11,994
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import set_theory.ordinal.arithmetic /-! # Natural operations on ordinals The goal of this file is to define natural addition and multiplication on ordinals, also known as the Hessenberg sum and product, and provide a basic API. The natural addition of two ordinals `a ♯ b` is recursively defined as the least ordinal greater than `a' ♯ b` and `a ♯ b'` for `a' < a` and `b' < b`. The natural multiplication `a ⨳ b` is likewise recursively defined as the least ordinal such that `a ⨳ b ♯ a' ⨳ b'` is greater than `a' ⨳ b ♯ a ⨳ b'` for any `a' < a` and `b' < b`. These operations form a rich algebraic structure: they're commutative, associative, preserve order, have the usual `0` and `1` from ordinals, and distribute over one another. Moreover, these operations are the addition and multiplication of ordinals when viewed as combinatorial `game`s. This makes them particularly useful for game theory. Finally, both operations admit simple, intuitive descriptions in terms of the Cantor normal form. The natural addition of two ordinals corresponds to adding their Cantor normal forms as if they were polynomials in `ω`. Likewise, their natural multiplication corresponds to multiplying the Cantor normal forms as polynomials. # Implementation notes Given the rich algebraic structure of these two operations, we choose to create a type synonym `nat_ordinal`, where we provide the appropriate instances. However, to avoid casting back and forth between both types, we attempt to prove and state most results on `ordinal`. # Todo - Define natural multiplication and provide a basic API. - Prove the characterizations of natural addition and multiplication in terms of the Cantor normal form. -/ universes u v open function order noncomputable theory /-- A type synonym for ordinals with natural addition and multiplication. -/ @[derive [has_zero, inhabited, has_one, linear_order, succ_order, has_well_founded]] def nat_ordinal : Type* := ordinal /-- The identity function between `ordinal` and `nat_ordinal`. -/ @[pattern] def ordinal.to_nat_ordinal : ordinal ≃o nat_ordinal := order_iso.refl _ /-- The identity function between `nat_ordinal` and `ordinal`. -/ @[pattern] def nat_ordinal.to_ordinal : nat_ordinal ≃o ordinal := order_iso.refl _ open ordinal namespace nat_ordinal variables {a b c : nat_ordinal.{u}} @[simp] theorem to_ordinal_symm_eq : nat_ordinal.to_ordinal.symm = ordinal.to_nat_ordinal := rfl @[simp] theorem to_ordinal_to_nat_ordinal (a : nat_ordinal) : a.to_ordinal.to_nat_ordinal = a := rfl theorem lt_wf : @well_founded nat_ordinal (<) := ordinal.lt_wf instance : is_well_order nat_ordinal (<) := ordinal.has_lt.lt.is_well_order @[simp] theorem to_ordinal_zero : to_ordinal 0 = 0 := rfl @[simp] theorem to_ordinal_one : to_ordinal 1 = 1 := rfl @[simp] theorem to_ordinal_eq_zero (a) : to_ordinal a = 0 ↔ a = 0 := iff.rfl @[simp] theorem to_ordinal_eq_one (a) : to_ordinal a = 1 ↔ a = 1 := iff.rfl @[simp] theorem to_ordinal_max : (max a b).to_ordinal = max a.to_ordinal b.to_ordinal := rfl @[simp] theorem to_ordinal_min : (min a b).to_ordinal = min a.to_ordinal b.to_ordinal := rfl theorem succ_def (a : nat_ordinal) : succ a = (a.to_ordinal + 1).to_nat_ordinal := rfl /-- A recursor for `nat_ordinal`. Use as `induction x using nat_ordinal.rec`. -/ protected def rec {β : nat_ordinal → Sort*} (h : Π a, β (to_nat_ordinal a)) : Π a, β a := λ a, h a.to_ordinal /-- `ordinal.induction` but for `nat_ordinal`. -/ theorem induction {p : nat_ordinal → Prop} : ∀ i (h : ∀ j, (∀ k, k < j → p k) → p j), p i := ordinal.induction end nat_ordinal namespace ordinal variables {a b c : ordinal.{u}} @[simp] theorem to_nat_ordinal_symm_eq : to_nat_ordinal.symm = nat_ordinal.to_ordinal := rfl @[simp] theorem to_nat_ordinal_to_ordinal (a : ordinal) : a.to_nat_ordinal.to_ordinal = a := rfl @[simp] theorem to_nat_ordinal_zero : to_nat_ordinal 0 = 0 := rfl @[simp] theorem to_nat_ordinal_one : to_nat_ordinal 1 = 1 := rfl @[simp] theorem to_nat_ordinal_eq_zero (a) : to_nat_ordinal a = 0 ↔ a = 0 := iff.rfl @[simp] theorem to_nat_ordinal_eq_one (a) : to_nat_ordinal a = 1 ↔ a = 1 := iff.rfl @[simp] theorem to_nat_ordinal_max : to_nat_ordinal (max a b) = max a.to_nat_ordinal b.to_nat_ordinal := rfl @[simp] theorem to_nat_ordinal_min : (linear_order.min a b).to_nat_ordinal = linear_order.min a.to_nat_ordinal b.to_nat_ordinal := rfl /-- Natural addition on ordinals `a ♯ b`, also known as the Hessenberg sum, is recursively defined as the least ordinal greater than `a' ♯ b` and `a ♯ b'` for all `a' < a` and `b' < b`. In contrast to normal ordinal addition, it is commutative. Natural addition can equivalently be characterized as the ordinal resulting from adding up corresponding coefficients in the Cantor normal forms of `a` and `b`. -/ noncomputable def nadd : ordinal → ordinal → ordinal | a b := max (blsub.{u u} a $ λ a' h, nadd a' b) (blsub.{u u} b $ λ b' h, nadd a b') using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } localized "infix ` ♯ `:65 := ordinal.nadd" in natural_ops theorem nadd_def (a b : ordinal) : a ♯ b = max (blsub.{u u} a $ λ a' h, a' ♯ b) (blsub.{u u} b $ λ b' h, a ♯ b') := by rw nadd theorem lt_nadd_iff : a < b ♯ c ↔ (∃ b' < b, a ≤ b' ♯ c) ∨ ∃ c' < c, a ≤ b ♯ c' := by { rw nadd_def, simp [lt_blsub_iff] } theorem nadd_le_iff : b ♯ c ≤ a ↔ (∀ b' < b, b' ♯ c < a) ∧ ∀ c' < c, b ♯ c' < a := by { rw nadd_def, simp [blsub_le_iff] } theorem nadd_lt_nadd_left (h : b < c) (a) : a ♯ b < a ♯ c := lt_nadd_iff.2 (or.inr ⟨b, h, le_rfl⟩) theorem nadd_lt_nadd_right (h : b < c) (a) : b ♯ a < c ♯ a := lt_nadd_iff.2 (or.inl ⟨b, h, le_rfl⟩) theorem nadd_le_nadd_left (h : b ≤ c) (a) : a ♯ b ≤ a ♯ c := begin rcases lt_or_eq_of_le h with h | rfl, { exact (nadd_lt_nadd_left h a).le }, { exact le_rfl } end theorem nadd_le_nadd_right (h : b ≤ c) (a) : b ♯ a ≤ c ♯ a := begin rcases lt_or_eq_of_le h with h | rfl, { exact (nadd_lt_nadd_right h a).le }, { exact le_rfl } end variables (a b) theorem nadd_comm : ∀ a b, a ♯ b = b ♯ a | a b := begin rw [nadd_def, nadd_def, max_comm], congr; ext c hc; apply nadd_comm end using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } theorem blsub_nadd_of_mono {f : Π c < a ♯ b, ordinal.{max u v}} (hf : ∀ {i j} hi hj, i ≤ j → f i hi ≤ f j hj) : blsub _ f = max (blsub.{u v} a (λ a' ha', f (a' ♯ b) $ nadd_lt_nadd_right ha' b)) (blsub.{u v} b (λ b' hb', f (a ♯ b') $ nadd_lt_nadd_left hb' a)) := begin apply (blsub_le_iff.2 (λ i h, _)).antisymm (max_le _ _), { rcases lt_nadd_iff.1 h with ⟨a', ha', hi⟩ | ⟨b', hb', hi⟩, { exact lt_max_of_lt_left ((hf h (nadd_lt_nadd_right ha' b) hi).trans_lt (lt_blsub _ _ _)) }, { exact lt_max_of_lt_right ((hf h (nadd_lt_nadd_left hb' a) hi).trans_lt (lt_blsub _ _ _)) } }, all_goals { apply blsub_le_of_brange_subset.{u u v}, rintro c ⟨d, hd, rfl⟩, apply mem_brange_self } end theorem nadd_assoc : ∀ a b c, a ♯ b ♯ c = a ♯ (b ♯ c) | a b c := begin rw [nadd_def a (b ♯ c), nadd_def, blsub_nadd_of_mono, blsub_nadd_of_mono, max_assoc], { congr; ext d hd; apply nadd_assoc }, { exact λ i j _ _ h, nadd_le_nadd_left h a }, { exact λ i j _ _ h, nadd_le_nadd_right h c } end using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } @[simp] theorem nadd_zero : a ♯ 0 = a := begin induction a using ordinal.induction with a IH, rw [nadd_def, blsub_zero, max_zero_right], convert blsub_id a, ext b hb, exact IH _ hb end @[simp] theorem zero_nadd : 0 ♯ a = a := by rw [nadd_comm, nadd_zero] @[simp] theorem nadd_one : a ♯ 1 = succ a := begin induction a using ordinal.induction with a IH, rw [nadd_def, blsub_one, nadd_zero, max_eq_right_iff, blsub_le_iff], intros i hi, rwa [IH i hi, succ_lt_succ_iff] end @[simp] theorem one_nadd : 1 ♯ a = succ a := by rw [nadd_comm, nadd_one] theorem nadd_succ : a ♯ succ b = succ (a ♯ b) := by rw [←nadd_one (a ♯ b), nadd_assoc, nadd_one] theorem succ_nadd : succ a ♯ b = succ (a ♯ b) := by rw [←one_nadd (a ♯ b), ←nadd_assoc, one_nadd] @[simp] theorem nadd_nat (n : ℕ) : a ♯ n = a + n := begin induction n with n hn, { simp }, { rw [nat.cast_succ, add_one_eq_succ, nadd_succ, add_succ, hn] } end @[simp] theorem nat_nadd (n : ℕ) : ↑n ♯ a = a + n := by rw [nadd_comm, nadd_nat] theorem add_le_nadd : a + b ≤ a ♯ b := begin apply b.limit_rec_on, { simp }, { intros c h, rwa [add_succ, nadd_succ, succ_le_succ_iff] }, { intros c hc H, rw [←is_normal.blsub_eq.{u u} (add_is_normal a) hc, blsub_le_iff], exact λ i hi, (H i hi).trans_lt (nadd_lt_nadd_left hi a) } end end ordinal open ordinal namespace nat_ordinal instance : has_add nat_ordinal := ⟨nadd⟩ instance add_covariant_class_lt : covariant_class nat_ordinal.{u} nat_ordinal.{u} (+) (<) := ⟨λ a b c h, nadd_lt_nadd_left h a⟩ instance add_covariant_class_le : covariant_class nat_ordinal.{u} nat_ordinal.{u} (+) (≤) := ⟨λ a b c h, nadd_le_nadd_left h a⟩ instance add_contravariant_class_le : contravariant_class nat_ordinal.{u} nat_ordinal.{u} (+) (≤) := ⟨λ a b c h, by { by_contra' h', exact h.not_lt (add_lt_add_left h' a) }⟩ instance : ordered_cancel_add_comm_monoid nat_ordinal := { add := (+), add_assoc := nadd_assoc, add_left_cancel := λ a b c, add_left_cancel'', add_le_add_left := λ a b, add_le_add_left, le_of_add_le_add_left := λ a b c, le_of_add_le_add_left, zero := 0, zero_add := zero_nadd, add_zero := nadd_zero, add_comm := nadd_comm, ..nat_ordinal.linear_order } instance : add_monoid_with_one nat_ordinal := add_monoid_with_one.unary @[simp] theorem add_one_eq_succ : ∀ a : nat_ordinal, a + 1 = succ a := nadd_one @[simp] theorem to_ordinal_cast_nat (n : ℕ) : to_ordinal n = n := begin induction n with n hn, { refl }, { change nadd (to_ordinal n) 1 = n + 1, rw hn, apply nadd_one } end end nat_ordinal open nat_ordinal open_locale natural_ops namespace ordinal @[simp] theorem to_nat_ordinal_cast_nat (n : ℕ) : to_nat_ordinal n = n := by { rw ←to_ordinal_cast_nat n, refl } theorem lt_of_nadd_lt_nadd_left : ∀ {a b c}, a ♯ b < a ♯ c → b < c := @lt_of_add_lt_add_left nat_ordinal _ _ _ theorem lt_of_nadd_lt_nadd_right : ∀ {a b c}, b ♯ a < c ♯ a → b < c := @_root_.lt_of_add_lt_add_right nat_ordinal _ _ _ theorem le_of_nadd_le_nadd_left : ∀ {a b c}, a ♯ b ≤ a ♯ c → b ≤ c := @le_of_add_le_add_left nat_ordinal _ _ _ theorem le_of_nadd_le_nadd_right : ∀ {a b c}, b ♯ a ≤ c ♯ a → b ≤ c := @le_of_add_le_add_right nat_ordinal _ _ _ theorem nadd_lt_nadd_iff_left : ∀ a {b c}, a ♯ b < a ♯ c ↔ b < c := @add_lt_add_iff_left nat_ordinal _ _ _ _ theorem nadd_lt_nadd_iff_right : ∀ a {b c}, b ♯ a < c ♯ a ↔ b < c := @add_lt_add_iff_right nat_ordinal _ _ _ _ theorem nadd_le_nadd_iff_left : ∀ a {b c}, a ♯ b ≤ a ♯ c ↔ b ≤ c := @add_le_add_iff_left nat_ordinal _ _ _ _ theorem nadd_le_nadd_iff_right : ∀ a {b c}, b ♯ a ≤ c ♯ a ↔ b ≤ c := @_root_.add_le_add_iff_right nat_ordinal _ _ _ _ theorem nadd_left_cancel : ∀ {a b c}, a ♯ b = a ♯ c → b = c := @_root_.add_left_cancel nat_ordinal _ theorem nadd_right_cancel : ∀ {a b c}, a ♯ b = c ♯ b → a = c := @_root_.add_right_cancel nat_ordinal _ theorem nadd_left_cancel_iff : ∀ {a b c}, a ♯ b = a ♯ c ↔ b = c := @add_left_cancel_iff nat_ordinal _ theorem nadd_right_cancel_iff : ∀ {a b c}, b ♯ a = c ♯ a ↔ b = c := @add_right_cancel_iff nat_ordinal _ end ordinal
c1800fba4fef26149df5870e9f420e5ccb656653
b00a388056c6a08748fb68d31375cfc972b8cb36
/src/aristotle_syntax.lean
49bb58ad6b9ced4729227e0520d5ec47a73fce7b
[]
no_license
hjvromen/aristotle
cfe8cedd09e7ba5da0df38db1ab18ddaa1c5c342
fdc6c68ce2edcf6faaa638457cb593e922bfa521
refs/heads/master
1,677,764,431,125
1,676,554,695,000
1,676,554,695,000
327,547,662
0
0
null
null
null
null
UTF-8
Lean
false
false
6,115
lean
/- Copyright (c) 2023 Huub Vromen. All rights reserved. Author: Huub Vromen -/ /- This is a formalisation of Aristotle's assertoric (non-modal) syllogistic. We start with a syntactical account (language and proof system). After that, in the other files, three differrent semantics are presented, each with a proof of soundness of the proof system. -/ variable {term : Type} -- type for terms variables {A B C P S M: term} constants {a e i o : term → term → Prop} infixr ` a ` : 80 := a infixr ` e ` : 80 := e infixr ` i ` : 80 := i infixr ` o ` : 80 := o -- the 'contradictories' constant c : Prop → Prop axiom contr_a : c (A a B) = A o B axiom contr_e : c (A e B) = A i B axiom contr_i : c (A i B) = A e B axiom contr_o : c (A o B) = A a B /-- The deductive system that follows Aristotle's text as closely as possible uses eight axioms / deduction rules. (Smith 1989 pp. xix-xx) -/ -- four 'perfect' syllogisms (we use the traditional medieval names) axiom Barbara₁ : P a M → M a S → P a S axiom Celarent₁ : P e M → M a S → P e S axiom Darii₁ : P a M → M i S → P i S axiom Ferio₁ : P e M → M i S → P o S -- three conversion rules axiom e_conv : A e B → B e A -- simple e_conversion axiom i_conv : A i B → B i A -- simple i_conversion axiom a_conv : A a B → B i A -- accidental a_conversion -- reductio ad absurdum axiom contr {p r : Prop} : (c r → c p) → p → r /-- Aristotle does not use 'extended' deductions, i.e. he does not use already proved theorems but only axioms. The following proofs follow Aristotle's text as closely as possible. -/ -- four second-figure syllogisms lemma Cesare₂ (h1: M e P) (h2 : M a S) : P e S := Celarent₁ (e_conv h1) h2 lemma Camestres₂ (h1: M a P) (h2 : M e S) : P e S := e_conv (Celarent₁ (e_conv h2) h1) lemma Festino₂ (h1: M e P) (h2 : M i S) : P o S := Ferio₁ (e_conv h1) h2 lemma Baroco₂ (h1: M a P) (h2 : M o S) : P o S := begin have h3 : c (P o S) → c (M o S) := begin intro h4, rw contr_o at *, exact Barbara₁ h1 h4, end, exact contr h3 h2, end -- six third-figure syllogisms -/ lemma Darapti₃ (h1 : P a M) (h2 : S a M) : P i S := Darii₁ h1 (a_conv h2) lemma Felapton₃ (h1 : P e M) (h2 : S a M) : P o S := Ferio₁ h1 (a_conv h2) lemma Disamis₃ (h1 : P i M) (h2 : S a M) : P i S := i_conv (Darii₁ h2 (i_conv h1)) lemma Datisi₃ (h1 : P a M) (h2 : S i M) : P i S := Darii₁ h1 (i_conv h2) lemma Bocardo₃ (h1 : P o M) (h2 : S a M) : P o S := begin have h3 : c (P o S) → c (P o M) := begin intro h4, rw contr_o at *, exact Barbara₁ h4 h2, end, exact contr h3 h1, end lemma Ferison₃ (h1 : P e M) (h2 : S i M) : P o S := Ferio₁ h1 (i_conv h2) /-- Up to now, we have 14 valid syllogisms. There are 10 more. First, we prove the four subaltern syllogisms. In order to prove them, we first prove a helpful lemma. -/ lemma subaltrn_e : A e B → A o B := -- accidental e_conversion begin intro h, have h3 : c (A o B) → c (A e B) := begin intro h4, rw contr_e, rw contr_o at h4, exact i_conv (a_conv h4), end, exact contr h3 h, end -- the two subaltern first-figure syllogisms lemma Barbari (h1: P a M) (h2 : M a S) : P i S := i_conv (a_conv (Barbara₁ h1 h2)) lemma Celaront (h1: P e M) (h2 : M a S) : P o S := subaltrn_e (Celarent₁ h1 h2) -- the two subaltern second-figure syllogisms lemma Cesaro₂ (h1: M e P) (h2 : M a S) : P o S := subaltrn_e (Celarent₁ (e_conv h1) h2) lemma Camestrop₂ (h1: M a P) (h2 : M e S) : P o S := subaltrn_e (e_conv (Celarent₁ (e_conv h2) h1)) /-- Second, we prove the six fourth-figure syllogisms -/ lemma Bramantip₄ (h1 : M a P) (h2 : C a M) : P i C := a_conv (Barbara₁ h2 h1) lemma Camenes₄ (h1 : M a P) (h2 : C e M) : P e C := e_conv(Celarent₁ h2 h1) lemma Dimaris₄ (h1 : M i P) (h2 : C a M) : P i C := i_conv(Darii₁ h2 h1) lemma Fesapo₄ (h1 : M e P) (h2 : C a M) : P o C := Ferio₁ (e_conv h1) (a_conv h2) lemma Fresison₄ (h1 : M e P) (h2 : C i M) : P o C := Festino₂ h1 (i_conv h2) lemma Camenop₄ (h1 : M a P) (h2 : C e M) : P o C := subaltrn_e (e_conv(Celarent₁ h2 h1)) /-- Metalogical observations. The proof system is redundant. Aristotle already mentioned that Darii₁ and Ferio₁ do not have to be assumed as axioms, but can be derived from Barbara₁ and Celarent₁ (An. Pr. 29b1-2] in Smith, 1989). This is proven below. -/ lemma Darii (h1 : P a M) (h2 : M i S) : P i S := begin have h3 : c (P i S) → c (M i S) := begin intro h4, rw contr_i at *, exact e_conv (Celarent₁ (e_conv h4) h1), end, exact contr h3 h2, end lemma Ferio (h1 : P e M) (h2 : M i S) : P o S := begin have h3 : c (P o S) → c (M i S) := begin intro h4, rw contr_i, rw contr_o at h4, exact Celarent₁ (e_conv h1) h4, end, exact contr h3 h2, end /-- It is even possible to derive rule i_conv from the other rules (25a22) -/ lemma i_conv_deduction : A i B → B i A := begin intro h3, have h4 : c (B i A) → c (A i B) := begin intro h5, rw contr_i at *, exact e_conv h5 end, exact contr h4 h3, end /- So, Barbara₁ and Celarent₁ together with e-conv and a-conv and contr suffice to prove all 24 valid syllogisms. We will refer to this system by the name `DR` in the semantics files. -/ /- ************** ideas for further research **************** Aristotle argued for the invalidity of all other syllogisms by semantical means, i.e. by providing counterexamples. I would like to prove that all invalid syllogisms cannot be derived; therefore: a. To show that there are exactly 256 syllogisms, I will have to give an inductive definition of a syllogism. b. Then select some rules that are sufficient to refute all invalid syllogisms; see, for instance, van Rooij (2020, p.187). c. Finally, investigate if it is possible to prove these rules in our proof system. -/
1d7ff1096b560438123dbb822094d632148cf263
4fa161becb8ce7378a709f5992a594764699e268
/src/data/indicator_function.lean
1ba0675fad0e0e47e59a1976e367c8ad78c6b6e5
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
7,822
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.pi_instances import data.set.disjointed import data.support /-! # Indicator function `indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `0` otherwise. ## Implementation note In mathematics, an indicator function or a characteristic function is a function used to indicate membership of an element in a set `s`, having the value `1` for all elements of `s` and the value `0` otherwise. But since it is usually used to restrict a function to a certain set `s`, we let the indicator function take the value `f x` for some function `f`, instead of `1`. If the usual indicator function is needed, just set `f` to be the constant function `λx, 1`. ## Tags indicator, characteristic -/ noncomputable theory open_locale classical big_operators namespace set universes u v variables {α : Type u} {β : Type v} section has_zero variables [has_zero β] {s t : set α} {f g : α → β} {a : α} /-- `indicator s f a` is `f a` if `a ∈ s`, `0` otherwise. -/ @[reducible] def indicator (s : set α) (f : α → β) : α → β := λ x, if x ∈ s then f x else 0 lemma indicator_apply (s : set α) (f : α → β) (a : α) : indicator s f a = if a ∈ s then f a else 0 := rfl @[simp] lemma indicator_of_mem (h : a ∈ s) (f : α → β) : indicator s f a = f a := if_pos h @[simp] lemma indicator_of_not_mem (h : a ∉ s) (f : α → β) : indicator s f a = 0 := if_neg h lemma support_indicator : function.support (s.indicator f) ⊆ s := λ x hx, hx.imp_symm (λ h, indicator_of_not_mem h f) lemma indicator_congr (h : ∀ a ∈ s, f a = g a) : indicator s f = indicator s g := funext $ λx, by { simp only [indicator], split_ifs, { exact h _ h_1 }, refl } @[simp] lemma indicator_univ (f : α → β) : indicator (univ : set α) f = f := funext $ λx, indicator_of_mem (mem_univ _) f @[simp] lemma indicator_empty (f : α → β) : indicator (∅ : set α) f = λa, 0 := funext $ λx, indicator_of_not_mem (not_mem_empty _) f variable (β) @[simp] lemma indicator_zero (s : set α) : indicator s (λx, (0:β)) = λx, (0:β) := funext $ λx, by { simp only [indicator], split_ifs, refl, refl } variable {β} lemma indicator_indicator (s t : set α) (f : α → β) : indicator s (indicator t f) = indicator (s ∩ t) f := funext $ λx, by { simp only [indicator], split_ifs, repeat {simp * at * {contextual := tt}} } lemma indicator_comp_of_zero {γ} [has_zero γ] {g : β → γ} (hg : g 0 = 0) : indicator s (g ∘ f) = λ a, indicator (f '' s) g (indicator s f a) := begin funext, simp only [indicator], split_ifs with h h', { refl }, { have := mem_image_of_mem _ h, contradiction }, { rwa eq_comm }, refl end lemma indicator_preimage (s : set α) (f : α → β) (B : set β) : (indicator s f)⁻¹' B = s ∩ f ⁻¹' B ∪ (-s) ∩ (λa:α, (0:β)) ⁻¹' B := by { rw [indicator, if_preimage] } end has_zero section add_monoid variables [add_monoid β] {s t : set α} {f g : α → β} {a : α} lemma indicator_union_of_not_mem_inter (h : a ∉ s ∩ t) (f : α → β) : indicator (s ∪ t) f a = indicator s f a + indicator t f a := by { simp only [indicator], split_ifs, repeat {simp * at * {contextual := tt}} } lemma indicator_union_of_disjoint (h : disjoint s t) (f : α → β) : indicator (s ∪ t) f = λa, indicator s f a + indicator t f a := funext $ λa, indicator_union_of_not_mem_inter (by { convert not_mem_empty a, have := disjoint.eq_bot h, assumption }) _ lemma indicator_add (s : set α) (f g : α → β) : indicator s (λa, f a + g a) = λa, indicator s f a + indicator s g a := by { funext, simp only [indicator], split_ifs, { refl }, rw add_zero } variables (β) instance is_add_monoid_hom.indicator (s : set α) : is_add_monoid_hom (λf:α → β, indicator s f) := { map_add := λ _ _, indicator_add _ _ _, map_zero := indicator_zero _ _ } variables {β} {𝕜 : Type*} [monoid 𝕜] [distrib_mul_action 𝕜 β] lemma indicator_smul (s : set α) (r : 𝕜) (f : α → β) : indicator s (λ (x : α), r • f x) = λ (x : α), r • indicator s f x := by { simp only [indicator], funext, split_ifs, refl, exact (smul_zero r).symm } end add_monoid section add_group variables [add_group β] {s t : set α} {f g : α → β} {a : α} variables (β) instance is_add_group_hom.indicator (s : set α) : is_add_group_hom (λf:α → β, indicator s f) := { .. is_add_monoid_hom.indicator β s } variables {β} lemma indicator_neg (s : set α) (f : α → β) : indicator s (λa, - f a) = λa, - indicator s f a := show indicator s (- f) = - indicator s f, from is_add_group_hom.map_neg _ _ lemma indicator_sub (s : set α) (f g : α → β) : indicator s (λa, f a - g a) = λa, indicator s f a - indicator s g a := show indicator s (f - g) = indicator s f - indicator s g, from is_add_group_hom.map_sub _ _ _ lemma indicator_compl (s : set α) (f : α → β) : indicator (-s) f = λ a, f a - indicator s f a := begin funext, simp only [indicator], split_ifs with h₁ h₂, { rw sub_zero }, { rw sub_self }, { rw ← mem_compl_iff at h₂, contradiction } end lemma indicator_finset_sum {β} [add_comm_monoid β] {ι : Type*} (I : finset ι) (s : set α) (f : ι → α → β) : indicator s (∑ i in I, f i) = ∑ i in I, indicator s (f i) := begin convert (finset.sum_hom _ _).symm, split, exact indicator_zero _ _ end lemma indicator_finset_bUnion {β} [add_comm_monoid β] {ι} (I : finset ι) (s : ι → set α) {f : α → β} : (∀ (i ∈ I) (j ∈ I), i ≠ j → s i ∩ s j = ∅) → indicator (⋃ i ∈ I, s i) f = λ a, ∑ i in I, indicator (s i) f a := begin refine finset.induction_on I _ _, assume h, { funext, simp }, assume a I haI ih hI, funext, simp only [haI, finset.sum_insert, not_false_iff], rw [finset.bUnion_insert, indicator_union_of_not_mem_inter, ih _], { assume i hi j hj hij, exact hI i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj) hij }, simp only [not_exists, exists_prop, mem_Union, mem_inter_eq, not_and], assume hx a' ha', have := hI a (finset.mem_insert_self _ _) a' (finset.mem_insert_of_mem ha') _, { assume h, have h := mem_inter hx h, rw this at h, exact not_mem_empty _ h }, { assume h, rw h at haI, contradiction } end end add_group section mul_zero_class variables [mul_zero_class β] {s t : set α} {f g : α → β} {a : α} lemma indicator_mul (s : set α) (f g : α → β) : indicator s (λa, f a * g a) = λa, indicator s f a * indicator s g a := by { funext, simp only [indicator], split_ifs, { refl }, rw mul_zero } end mul_zero_class section order variables [has_zero β] [preorder β] {s t : set α} {f g : α → β} {a : α} lemma indicator_nonneg' (h : a ∈ s → 0 ≤ f a) : 0 ≤ indicator s f a := by { rw indicator_apply, split_ifs with as, { exact h as }, refl } lemma indicator_nonneg (h : ∀ a ∈ s, 0 ≤ f a) : ∀ a, 0 ≤ indicator s f a := λ a, indicator_nonneg' (h a) lemma indicator_nonpos' (h : a ∈ s → f a ≤ 0) : indicator s f a ≤ 0 := by { rw indicator_apply, split_ifs with as, { exact h as }, refl } lemma indicator_nonpos (h : ∀ a ∈ s, f a ≤ 0) : ∀ a, indicator s f a ≤ 0 := λ a, indicator_nonpos' (h a) lemma indicator_le_indicator (h : f a ≤ g a) : indicator s f a ≤ indicator s g a := by { simp only [indicator], split_ifs with ha, { exact h }, refl } lemma indicator_le_indicator_of_subset (h : s ⊆ t) (hf : ∀a, 0 ≤ f a) (a : α) : indicator s f a ≤ indicator t f a := begin simp only [indicator], split_ifs with h₁, { refl }, { have := h h₁, contradiction }, { exact hf a }, { refl } end end order end set
d5d937d44f05b08feb8d5e83b2d0222dfa4d51bc
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.9.lean
69ed7f9c8d0b58c9ef80dd267d8625e5ce1a5f90
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
977
lean
import standard import data.nat open nat eq.ops -- BEGIN definition foo (n m k l : ℕ) : (n - m) * (k + l) = (k + l) * (n - m) := !mul.comm print foo -- definition foo : ∀ (n m k l : ℕ), (n - m) * (k + l) = (k + l) * (n - m) -- λ (n m k l : ℕ), mul.comm (n - m) (k + l) definition foo2 (n m k l : ℕ) : (n + k) + l = (k + l) + n := !add.assoc ⬝ !add.comm print foo2 -- definition foo2 : ∀ (n : ℕ), ℕ → (∀ (k l : ℕ), n + k + l = k + l + n) -- λ (n m k l : ℕ), add.assoc n k l ⬝ add.comm n (k + l) definition foo3 (l : ℕ) (H : ∀ (n : ℕ), l + 2 ≠ 2 * (n + 1)) (n : ℕ) : l ≠ 2 * n := assume K : l = 2 * n, absurd (show l + 2 = 2 * n + 2, from K ▸ rfl) !H print foo3 -- definition foo3 : ∀ (l : ℕ), -- (∀ (n : ℕ), l + 2 ≠ 2 * (n + 1)) → (∀ (n : ℕ), l ≠ 2 * n) -- λ (l : ℕ) (H : ∀ (n : ℕ), l + 2 ≠ 2 * (n + 1)) (n : ℕ) -- (K : l = 2 * n), -- absurd (show l + 2 = 2 * n + 2, from K ▸ rfl) (H n) -- END
6656fbf0e0259664f193c878272572c01fe579c0
96b8fa8ff5edc088c62b8e0d92e4599e8edbf1e2
/Cli/Basic.lean
dc9361bfbdd61ffbba20d8d02b6bbdb901f326ff
[ "MIT" ]
permissive
pnwamk/lean4-cli
4429db4cebfca510573150ade5e8ed3087014051
0a66055885086864114c8b281830a47f2b601ff4
refs/heads/main
1,678,627,315,712
1,614,105,437,000
1,614,105,437,000
342,072,945
0
0
null
1,614,212,319,000
1,614,212,318,000
null
UTF-8
Lean
false
false
59,586
lean
import Std.Data.RBTree section Utils /-- Matches the lengths of lists `a` and `b` by filling the shorter one with `unit` elements at the tail end. The matched lists are returned in the same order as they were passed. -/ def List.matchLength (a : List α) (b : List α) (unit : α) : List α × List α := if a.length < b.length then (a ++ List.replicate (b.length - a.length) unit, b) else (a, b ++ List.replicate (a.length - b.length) unit) namespace Array -- not really used anymore, but still a neat function to have! /-- Groups elements in `xs` by `key` such that the returned array contains arrays of elements from `xs` that are all equal after being mapped with `key`. -/ def groupBy [Inhabited α] [Inhabited β] [HasLess α] [DecidableRel ((· < ·) : α → α → Prop)] (key : β → α) (xs : Array β) : Array (Array β) := do if xs.size = 0 then return #[] let xs := xs.qsort (key · < key ·) let mut groups : Array (Array β) := #[#[]] let mut currentRepresentative := key xs[0] for x in xs do let k := key x if k < currentRepresentative ∨ k > currentRepresentative then groups := groups.push #[x] currentRepresentative := k else let lastIdx := groups.size - 1 groups := groups.set! lastIdx <| groups[lastIdx].push x return groups def join (xss : Array (Array α)) : Array α := do let mut r := #[] for xs in xss do r := r ++ xs return r def flatMap (f : α → Array β) (xs : Array α) : Array β := xs.map f |>.join end Array namespace String /-- Inserts newlines `\n` into `s` after every `maxWidth` characters so that the result contains no line longer than `maxWidth` characters. Retains newlines `\n` in `s`. Yields `none` if `maxWidth = 0`. -/ def wrapAt? (s : String) (maxWidth : Nat) : Option String := do if maxWidth = 0 then none let lines := s.splitOn "\n" |>.map fun line => do let resultLineCount := if line.length % maxWidth = 0 then line.length / maxWidth else line.length / maxWidth + 1 let mut line := line let mut result := #[] for i in [:resultLineCount] do result := result.push <| line.take maxWidth line := line.drop maxWidth return "\n".intercalate result.toList return "\n".intercalate lines /-- Inserts newlines `\n` into `s` after every `maxWidth` characters so that the result contains no line longer than `maxWidth` characters. Retains newlines `\n` in `s`. Panics if `maxWidth = 0`. -/ def wrapAt! (s : String) (maxWidth : Nat) : String := s.wrapAt? maxWidth |>.get! /-- Deletes all trailing spaces at the end of every line, as seperated by `\n`. -/ def trimTrailingSpaces (s : String) : String := s.splitOn "\n" |>.map (·.dropRightWhile (· = ' ')) |> "\n".intercalate /-- Inserts newlines `\n` into `s` after every `maxWidth` characters before words that would otherwise be broken apart by the newline. The result will contain no line longer than `maxWidth` characters and no words except those already longer than `maxWidth` characters will be broken up in the middle. Removes trailing whitespace before each inserted newline. Retains newlines `\n` in `s`. Returns `none` if `maxWidth = 0`. -/ def wrapWordsAt? (s : String) (maxWidth : Nat) : Option String := do if maxWidth = 0 then none let wordWrappedLines : List String := s.splitOn "\n" |>.map fun s => do let words : Array String := s.splitOn.toArray let mut currentLineWidth : Nat := 0 let mut result : Array String := #[] for i in [:words.size] do let w := words[i] -- `w = ""`: we will never insert a newline on a space. this has the effect -- of inserting the newline only after a bunch of trailing whitespace, which we remove later. -- similarly, `currentLineWidth + w.length ≤ maxWidth` does not count the space after `w` so that -- we do not insert a newline before a word that fits except for a trailing space. if w = "" ∨ currentLineWidth + w.length ≤ maxWidth then -- `+ 1` because we count the space after `w` to accurately keep track of spaces. currentLineWidth := currentLineWidth + w.length + 1 result := result.push w continue -- if `w` is the first proper word, this will insert a `\n` before the text, which we remove later. -- `w.wrapAt! maxWidth` ensures that our new line is not already too large. let wordOnNewLine := "\n" ++ w.wrapAt! maxWidth result := result.push wordOnNewLine let wrappedLines : Array String := wordOnNewLine.splitOn "\n" |>.toArray currentLineWidth := wrappedLines[wrappedLines.size - 1].length + 1 return " ".intercalate result.toList let trimmed : List String := wordWrappedLines.map trimTrailingSpaces |>.map fun line => do if line = "" then return "" if line[0] ≠ '\n' then return line return line.drop 1 return "\n".intercalate trimmed /-- Inserts newlines `\n` into `s` after every `maxWidth` characters before words that would otherwise be broken apart by the newline. The result will contain no line longer than `maxWidth` characters and no words except those already longer than `maxWidth` characters will be broken up in the middle. Removes trailing whitespace before each inserted newline. Retains newlines `\n` in `s`. Panics if `maxWidth = 0`. -/ def wrapWordsAt! (s : String) (maxWidth : Nat) : String := s.wrapWordsAt? maxWidth |>.get! /-- Inserts `n` spaces before each line as seperated by `\n` in `s`. Does not indent `s = ""`. -/ def indent (s : String) (n : Nat := 4) : String := do if s = "" then return "" return s.splitOn "\n" |>.map ("".pushn ' ' n ++ ·) |> "\n".intercalate /-- Intercalates elements `≠ ""` in `xs` using `sep`. -/ def optJoin (xs : Array String) (sep : String) : String := xs.filter (· ≠ "") |>.toList |> sep.intercalate end String namespace Array /-- Renders `rows` as a table with a maximum row width of `maxWidth` and a margin of `margin` between the columns. Wraps words according to `String.wrapWordsAt?` to ensure that no rendered row of the table is longer than `maxWidth`. Returns `none` if `(maxWidth-margin)/2` < 1, i.e. if there is not enough space for text in both columns. -/ def renderTable? (rows : Array (String × String)) (maxWidth : Nat) (margin : Nat := 2) : Option String := do if rows.isEmpty then return "" let rightColumnWidth := rows.map (·.2.length) |>.getMax? (· < ·) |>.get! let minRightColumnWidth := Nat.min rightColumnWidth <| Nat.max ((maxWidth-margin)/2) 1 if maxWidth - margin - minRightColumnWidth < 1 then none let rows : Array (List String × String) := rows.map fun (left, right) => (maxWidth - margin - minRightColumnWidth |> left.wrapWordsAt! |>.splitOn "\n", right) let leftColumnWidth := rows.flatMap (·.1.map (·.length) |>.toArray) |>.getMax? (· < ·) |>.get! + margin let rows : Array (List String × List String) := rows.map fun (left, right) => (left, maxWidth - leftColumnWidth |> right.wrapWordsAt! |>.splitOn "\n") let rows : Array (String × String) := rows.flatMap fun (left, right) => let (left, right) : List String × List String := left.matchLength right "" left.zip right |>.toArray let rows : Array String := rows.map fun (left, right) => if right = "" then left else let padding := "".pushn ' ' (leftColumnWidth - left.length) left ++ padding ++ right return "\n".intercalate rows.toList /-- Renders `rows` as a table with a maximum row width of `maxWidth` and a margin of `margin` between the columns. Wraps words according to `String.wrapWordsAt?` to ensure that no rendered row of the table is longer than `maxWidth`. Panics if `(maxWidth-margin)/2` < 1, i.e. if there is not enough space for text in both columns. -/ def renderTable! (rows : Array (String × String)) (maxWidth : Nat) (margin : Nat := 2) : String := rows.renderTable? maxWidth margin |>.get! end Array namespace Option def join (x : Option (Option α)) : Option α := do ←x def mapM [Monad m] (f : α → m β) : Option α → m (Option β) | none => return none | some x => f x /-- Returns `""` if the passed `Option` is `none`, otherwise converts the contained value using a `ToString` instance. -/ def optStr [ToString α] : Option α → String | none => "" | some v => toString v end Option end Utils namespace Cli section Configuration /-- Represents a type that can be parsed to a string and the corresponding name of the type. Used for converting parsed user input to the respective expected type. -/ class ParseableType (τ) where /-- Name of the type, used when displaying the help. -/ name : String /-- Function to parse a value to the type that returns `none` if it cannot be parsed. -/ parse? : String → Option τ instance : ParseableType Unit where name := "Unit" parse? s := () instance : ParseableType Bool where name := "Bool" parse? | "true" => true | "false" => false | _ => none instance : ParseableType String where name := "String" parse? s := s instance : ParseableType Nat where name := "Nat" parse? -- HACK: temporary workaround for minor bug in String.toNat? | "" => none | s => s.toNat? instance : ParseableType Int where name := "Int" parse? -- HACK: temporary workaround for minor bug in String.toInt? | "" => none | s => s.toInt? instance [inst : ParseableType α] : ParseableType (Array α) where name := if inst.name.contains ' ' then s!"Array ({inst.name})" else s!"Array {inst.name}" parse? | "" => #[] | s => do (← s.splitOn "," |>.mapM inst.parse?).toArray /-- Represents the type of some flag or argument parameter. Typically coerced from types with `ParseableType` instances such that `isValid := (ParseableType.parse? · |>.isSome)`. -/ structure ParamType where /-- Name of the type, used when displaying the help. -/ name : String /-- Function to check whether a value conforms to the type. -/ isValid : String → Bool deriving Inhabited instance : BEq ParamType where beq a b := a.name == b.name instance : Repr ParamType where reprPrec p n := p.name instance [inst : ParseableType τ] : CoeDep Type τ ParamType where coe := ⟨inst.name τ, (inst.parse? · |>.isSome)⟩ /-- Represents a flag, usually known as "option" in standard terminology. -/ structure Flag where /-- Designates `x` in `-x`. -/ shortName? : Option String := none /-- Designates `x` in `--x`. -/ longName : String /-- Description that is displayed in the help. -/ description : String /-- Type according to which the parameter is validated. `Unit` is used to designate flags without a parameter. -/ type : ParamType deriving Inhabited, BEq, Repr namespace Flag /-- Initializes a flag without a parameter. Parameterless flags are designated by the `Unit` type. - `shortName?`: Designates `x` in `-x`. - `longName`: Designates `x` in `--x`. - `description`: Description that is displayed in the help. -/ def paramless (shortName? : Option String := none) (longName : String) (description : String) : Flag := { shortName? := shortName? longName := longName description := description type := Unit } /-- Designates `x` in `-x`. -/ def shortName! (f : Flag) : String := f.shortName?.get! /-- Checks whether `f` has an associated short flag name `x` in `-x`. -/ def hasShortName (f : Flag) : Bool := f.shortName?.isSome /-- Checks whether `f` has a `Unit` type. -/ def isParamless (f : Flag) : Bool := f.type == Unit end Flag /-- Represents an argument (either positional or variable), usually known as "operand" in standard terminology -/ structure Arg where /- Name that is displayed in the help. -/ name : String /- Description that is displayed in the help. -/ description : String /- Description that is displayed in the help. -/ type : ParamType deriving Inhabited, BEq, Repr namespace Parsed /-- Represents a flag and its parsed value. Use `Parsed.Flag.as!` to convert the value to some `ParseableType`. -/ structure Flag where /-- Associated flag meta-data. -/ flag : Flag /-- Parsed value that was validated and conforms to `flag.type`. -/ value : String deriving Inhabited, BEq, Repr instance : ToString Flag where toString f := s!"--{f.flag.longName}" ++ (if f.value ≠ "" then s!"={f.value}" else "") namespace Flag /-- Converts `f.value` to `τ`, which should be the same type that was designated in `f.flag.type`. Yields `none` if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `f.flag.type`. -/ def as? (f : Flag) (τ) [ParseableType τ] : Option τ := ParseableType.parse? f.value /-- Converts `f.value` to `τ`, which should be the same type that was designated in `f.flag.type`. Panics if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `f.flag.type`. -/ def as! (f : Flag) (τ) [Inhabited τ] [ParseableType τ] : τ := f.as? τ |>.get! end Flag /-- Represents an argument and its parsed value. Use `Parsed.Arg.as!` to convert the value to some `ParseableType`. -/ structure Arg where /-- Associated argument meta-data. -/ arg : Arg /-- Parsed value that was validated and conforms to `arg.type`. -/ value : String deriving Inhabited, BEq, Repr instance : ToString Arg where toString a := s!"<{a.arg.name}={a.value}>" namespace Arg /-- Converts `a.value` to `τ`, which should be the same type that was designated in `a.arg.type`. Yields `none` if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `a.arg.type`. -/ def as? (a : Arg) (τ) [ParseableType τ] : Option τ := ParseableType.parse? a.value /-- Converts `a.value` to `τ`, which should be the same type that was designated in `a.arg.type`. Panics if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `a.arg.type`. -/ def as! (a : Arg) (τ) [Inhabited τ] [ParseableType τ] : τ := a.as? τ |>.get! end Arg end Parsed /-- Represents all the non-recursive meta-data of a command. -/ structure Cmd.Meta where /-- Name that is displayed in the help. -/ name : String /-- Names of the commands of which this command is a subcommand. Corresponds to the path from the root to this command. Typically initialized by `Cmd.mk` or `Cmd.mk'`. -/ parentNames : Array String /-- Version of the command that is displayed in the help and when the version is queried. -/ version : String /-- Description that is displayed in the help. -/ description : String /-- Information appended to the end of the help. Useful for command extensions. -/ furtherInformation? : Option String := none /-- Supported flags ("options" in standard terminology). -/ flags : Array Flag /-- Supported positional arguments ("operands" in standard terminology). -/ positionalArgs : Array Arg /-- Variable argument after the end of the positional arguments. -/ variableArg? : Option Arg deriving Inhabited, BEq, Repr namespace Cmd.Meta /-- Full name from the root to this command, including the name of the command itself. -/ def fullName (m : Meta) : String := m.parentNames.push m.name |>.toList |> " ".intercalate /-- Information appended to the end of the help. Useful for command extensions. -/ def furtherInformation! (m : Meta) : String := m.furtherInformation?.get! /-- Variable argument after the end of the positional arguments. -/ def variableArg! (m : Meta) : Arg := m.variableArg?.get! /-- Checks whether `m` has information appended to the end of the help. -/ def hasFurtherInformation (m : Meta) : Bool := m.furtherInformation?.isSome /-- Checks whether `m` supports a variable argument. -/ def hasVariableArg (m : Meta) : Bool := m.variableArg?.isSome /-- Finds the flag in `m` with the corresponding `longName`. -/ def flag? (m : Meta) (longName : String) : Option Flag := m.flags.find? (·.longName = longName) /-- Finds the positional argument in `m` with the corresponding `name`. -/ def positionalArg? (m : Meta) (name : String) : Option Arg := m.positionalArgs.find? (·.name = name) /-- Finds the flag in `m` with the corresponding `longName`. -/ def flag! (m : Meta) (longName : String) : Flag := m.flag? longName |>.get! /-- Finds the positional argument in `m` with the corresponding `name`. -/ def positionalArg! (m : Meta) (name : String) : Arg := m.positionalArg? name |>.get! /-- Checks whether `m` contains a flag with the corresponding `longName`. -/ def hasFlag (m : Meta) (longName : String) : Bool := m.flag? longName |>.isSome /-- Checks whether `m` contains a positional argument with the corresponding `name`. -/ def hasPositionalArg (m : Meta) (name : String) : Bool := m.positionalArg? name |>.isSome /-- Finds the flag in `m` with the corresponding `shortName`. -/ def flagByShortName? (m : Meta) (name : String) : Option Flag := m.flags.findSome? fun flag => do let shortName ← flag.shortName? guard <| shortName = name return flag /-- Finds the flag in `m` with the corresponding `shortName`. -/ def flagByShortName! (m : Meta) (name : String) : Flag := m.flagByShortName? name |>.get! /-- Checks whether `m` has a flag with the corresponding `shortName`. -/ def hasFlagByShortName (m : Meta) (name : String) : Bool := m.flagByShortName? name |>.isSome end Cmd.Meta structure Parsed where /-- Non-recursive meta-data of the associated command. -/ cmd : Cmd.Meta /-- Parsed flags. -/ flags : Array Parsed.Flag /-- Parsed positional arguments. -/ positionalArgs : Array Parsed.Arg /-- Parsed variable arguments. -/ variableArgs : Array Parsed.Arg deriving Inhabited, BEq, Repr namespace Parsed /-- Finds the parsed flag in `p` with the corresponding `longName`. -/ def flag? (p : Parsed) (longName : String) : Option Flag := p.flags.find? (·.flag.longName = longName) /-- Finds the parsed positional argument in `p` with the corresponding `name`. -/ def positionalArg? (p : Parsed) (name : String) : Option Arg := p.positionalArgs.find? (·.arg.name = name) /-- Finds the parsed flag in `p` with the corresponding `longName`. -/ def flag! (p : Parsed) (longName : String) : Flag := p.flag? longName |>.get! /-- Finds the parsed positional argument in `p` with the corresponding `name`. -/ def positionalArg! (p : Parsed) (name : String) : Arg := p.positionalArg? name |>.get! /-- Checks whether `p` has a parsed flag with the corresponding `longName`. -/ def hasFlag (p : Parsed) (longName : String) : Bool := p.flag? longName |>.isSome /-- Checks whether `p` has a positional argument with the corresponding `longName`. -/ def hasPositionalArg (p : Parsed) (name : String) : Bool := p.positionalArg? name |>.isSome /-- Converts all `p.variableArgs` values to `τ`, which should be the same type that was designated in the corresponding `Cli.Arg`. Yields `none` if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in the corresponding `Cli.Arg`. -/ def variableArgsAs? (p : Parsed) (τ) [ParseableType τ] : Option (Array τ) := p.variableArgs.mapM (·.as? τ) /-- Converts all `p.variableArgs` values to `τ`, which should be the same type that was designated in the corresponding `Cli.Arg`. Panics if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in the corresponding `Cli.Arg`. -/ def variableArgsAs! (p : Parsed) (τ) [Inhabited τ] [ParseableType τ] : Array τ := p.variableArgsAs? τ |>.get! instance : ToString Parsed where toString p := s!"cmd: {p.cmd.fullName}; flags: {toString p.flags}; positionalArgs: {toString p.positionalArgs}; " ++ s!"variableArgs: {toString p.variableArgs}" end Parsed /-- Allows user code to extend the library in two ways: - The `meta` of a command can be replaced or extended with new components to adjust the displayed help. - The output of the parser can be postprocessed and validated. -/ structure Extension where /-- Extends the `meta` of a command to adjust the displayed help. -/ extendMeta : Cmd.Meta → Cmd.Meta := id /-- Processes and validates the output of the parser with the extended `meta` as extra information. -/ postprocess : Cmd.Meta → Parsed → Except String Parsed := fun m => pure deriving Inhabited /-- Composes both extensions so that the `meta`s are extended in succession and postprocessed in succession. Postprocessing errors if any of the two `postprocess` functions errors and feeds the `meta` extended with `a.extendMeta` into `b.postprocess`. -/ def Extension.then (a : Extension) (b : Extension) : Extension := { extendMeta := b.extendMeta ∘ a.extendMeta postprocess := fun meta parsed => do let meta' := a.extendMeta meta b.postprocess meta' <| ← a.postprocess meta parsed } open Cmd in /-- Represents a command, i.e. either the application root or some subcommand of the root. -/ inductive Cmd | init (meta : Meta) (run : Parsed → IO UInt32) (subCmds : Array Cmd) (extension? : Option Extension) open Inhabited in instance : Inhabited Cmd where default := Cmd.init default default default default namespace Cmd /-- Non-recursive meta-data. -/ def meta : Cmd → Cmd.Meta | init v _ _ _ => v /-- Handler to run when the command is called and flags/arguments have been successfully processed. -/ def run : Cmd → (Parsed → IO UInt32) | init _ v _ _ => v /-- Subcommands. -/ def subCmds : Cmd → Array Cmd | init _ _ v _ => v /-- Extension of the Cli library. -/ def extension? : Cmd → Option Extension | init _ _ _ v => v /-- Name that is displayed in the help. -/ def name (c : Cmd) : String := c.meta.name /-- Names of the commands of which `c` is a subcommand. Corresponds to the path from the root to `c`. Typically initialized by `Cmd.mk` or `Cmd.mk'`. -/ def parentNames (c : Cmd) : Array String := c.meta.parentNames /-- Version of `c` that is displayed in the help and when the version is queried. -/ def version (c : Cmd) : String := c.meta.version /-- Description that is displayed in the help. -/ def description (c : Cmd) : String := c.meta.description /-- Information appended to the end of the help. Useful for command extensions. -/ def furtherInformation? (c : Cmd) : Option String := c.meta.furtherInformation? /-- Supported flags ("options" in standard terminology). -/ def flags (c : Cmd) : Array Flag := c.meta.flags /-- Supported positional arguments ("operands" in standard terminology). -/ def positionalArgs (c : Cmd) : Array Arg := c.meta.positionalArgs /-- Variable argument at the end of the positional arguments. -/ def variableArg? (c : Cmd) : Option Arg := c.meta.variableArg? /-- Full name from the root to `c`, including the name of `c` itself. -/ def fullName (c : Cmd) : String := c.meta.fullName /-- Information appended to the end of the help. Useful for command extensions. -/ def furtherInformation! (c : Cmd) : String := c.meta.furtherInformation! /-- Variable argument after the end of the positional arguments. -/ def variableArg! (c : Cmd) : Arg := c.meta.variableArg! /-- Extension of the Cli library. -/ def extension! (c : Cmd) : Extension := c.extension?.get! /-- Checks whether `c` has information appended to the end of the help. -/ def hasFurtherInformation (c : Cmd) : Bool := c.meta.hasFurtherInformation /-- Checks whether `c` supports a variable argument. -/ def hasVariableArg (c : Cmd) : Bool := c.meta.hasVariableArg /-- Checks whether `c` is being extended. -/ def hasExtension (c : Cmd) : Bool := c.extension?.isSome /-- Updates the designated fields in `c`. - `meta`: Non-recursive meta-data. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. - `extension?`: Extension of the Cli library. -/ def update' (c : Cmd) (meta : Meta := c.meta) (run : Parsed → IO UInt32 := c.run) (subCmds : Array Cmd := c.subCmds) (extension? : Option Extension := c.extension?) : Cmd := Cmd.init meta run subCmds extension? /-- Updates the designated fields in `c`. - `name`: Name that is displayed in the help. - `parentNames`: Names of the commands of which `c` is a subcommand. Corresponds to the path from the root to `c`. Typically initialized by `Cmd.mk` or `Cmd.mk'`. - `version`: Version that is displayed in the help and when the version is queried. - `description`: Description that is displayed in the help. - `furtherInformation?`: Information appended to the end of the help. Useful for command extensions. - `flags`: Supported flags ("options" in standard terminology). - `positionalArgs`: Supported positional arguments ("operands" in standard terminology). - `variableArg?`: Variable argument at the end of the positional arguments. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. - `extension?`: Extension of the Cli library. -/ def update (c : Cmd) (name : String := c.name) (parentNames : Array String := c.parentNames) (version : String := c.version) (description : String := c.description) (furtherInformation? : Option String := c.furtherInformation?) (flags : Array Flag := c.flags) (positionalArgs : Array Arg := c.positionalArgs) (variableArg? : Option Arg := c.variableArg?) (run : Parsed → IO UInt32 := c.run) (subCmds : Array Cmd := c.subCmds) (extension? : Option Extension := c.extension?) : Cmd := Cmd.init ⟨name, parentNames, version, description, furtherInformation?, flags, positionalArgs, variableArg?⟩ run subCmds extension? /-- Creates a new command. Adds a `-h, --help` and a `--version` flag. Updates the `parentNames` of all subcommands. - `meta`: Non-recursive meta-data. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. - `extension?`: Extension of the Cli library. -/ partial def mk' (meta : Meta) (run : Parsed → IO UInt32) (subCmds : Array Cmd := #[]) (extension? : Option Extension := none) : Cmd := do let helpFlag := Flag.paramless (shortName? := "h") (longName := "help") (description := "Prints this message.") let versionFlag := Flag.paramless (longName := "version") (description := "Prints the version.") let meta := { meta with flags := #[helpFlag, versionFlag] ++ meta.flags } let c := Cmd.init meta run subCmds extension? updateParentNames c where updateParentNames (c : Cmd) : Cmd := let subCmds := c.subCmds.map fun subCmd => let subCmd := updateParentNames subCmd subCmd.update (parentNames := #[meta.name] ++ subCmd.parentNames) c.update (subCmds := subCmds) /-- Creates a new command. Adds a `-h, --help` and a `--version` flag. Updates the `parentNames` of all subcommands. - `name`: Name that is displayed in the help. - `version`: Version that is displayed in the help and when the version is queried. - `description`: Description that is displayed in the help. - `furtherInformation?`: Information appended to the end of the help. Useful for command extensions. - `flags`: Supported flags ("options" in standard terminology). - `positionalArgs`: Supported positional arguments ("operands" in standard terminology). - `variableArg?`: Variable argument at the end of the positional arguments. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. - `extension?`: Extension of the Cli library. -/ def mk (name : String) (version : String) (description : String) (furtherInformation? : Option String := none) (flags : Array Flag := #[]) (positionalArgs : Array Arg := #[]) (variableArg? : Option Arg := none) (run : Parsed → IO UInt32) (subCmds : Array Cmd := #[]) (extension? : Option Extension := none) : Cmd := mk' ⟨name, #[], version, description, furtherInformation?, flags, positionalArgs, variableArg?⟩ run subCmds extension? /-- Finds the flag in `c` with the corresponding `longName`. -/ def flag? (c : Cmd) (longName : String) : Option Flag := c.meta.flag? longName /-- Finds the positional argument in `c` with the corresponding `name`. -/ def positionalArg? (c : Cmd) (name : String) : Option Arg := c.meta.positionalArg? name /-- Finds the subcommand in `c` with the corresponding `name`. -/ def subCmd? (c : Cmd) (name : String) : Option Cmd := c.subCmds.find? (·.name = name) /-- Finds the flag in `c` with the corresponding `longName`. -/ def flag! (c : Cmd) (longName : String) : Flag := c.meta.flag! longName /-- Finds the positional argument in `c` with the corresponding `name`. -/ def positionalArg! (c : Cmd) (name : String) : Arg := c.meta.positionalArg! name /-- Finds the subcommand in `c` with the corresponding `name`. -/ def subCmd! (c : Cmd) (name : String) : Cmd := c.subCmd? name |>.get! /-- Checks whether `c` contains a flag with the corresponding `longName`. -/ def hasFlag (c : Cmd) (longName : String) : Bool := c.meta.hasFlag longName /-- Checks whether `c` contains a positional argument with the corresponding `name`. -/ def hasPositionalArg (c : Cmd) (name : String) : Bool := c.meta.hasPositionalArg name /-- Checks whether `c` contains a subcommand with the corresponding `name`. -/ def hasSubCmd (c : Cmd) (name : String) : Bool := c.subCmd? name |>.isSome /-- Finds the flag in `c` with the corresponding `shortName`. -/ def flagByShortName? (c : Cmd) (name : String) : Option Flag := c.meta.flagByShortName? name /-- Finds the flag in `c` with the corresponding `shortName`. -/ def flagByShortName! (c : Cmd) (name : String) : Flag := c.meta.flagByShortName! name /-- Checks whether `c` has a flag with the corresponding `shortName`. -/ def hasFlagByShortName (c : Cmd) (name : String) : Bool := c.meta.hasFlagByShortName name end Cmd end Configuration section Macro open Lean def expandIdentLiterally (s : Syntax) : Syntax := if s.isIdent then quote s.getId.toString else s syntax positionalArg := colGe term " : " term "; " term def expandPositionalArg (positionalArg : Syntax) : MacroM Syntax := let name := expandIdentLiterally positionalArg[0] let type := positionalArg[2] let description := positionalArg[4] `(Arg.mk $name $description $type) syntax variableArg := colGe "..." term " : " term "; " term def expandVariableArg (variableArg : Syntax) : MacroM Syntax := do let name := expandIdentLiterally variableArg[1] let type := variableArg[3] let description := variableArg[5] `(Arg.mk $name $description $type) syntax flag := colGe term ("," term)? (" : " term)? "; " term def expandFlag (flag : Syntax) : MacroM Syntax := do let (shortName, longName) := if flag[1].isNone then (quote (none : Option String), expandIdentLiterally flag[0]) else (expandIdentLiterally flag[0], expandIdentLiterally flag[1][1]) let type := if flag[2].isNone then ← `(Unit) else flag[2][1] let description := flag[4] `(Flag.mk $shortName $longName $description $type) syntax "`[Cli|\n" term " VIA " term "; " "[" term "]" term ("FLAGS:\n" withPosition((flag)*))? ("ARGS:\n" withPosition((positionalArg)* (variableArg)?))? ("SUBCOMMANDS: " sepBy(term, ";", "; "))? ("EXTENSIONS: " sepBy(term, ";", "; "))? "\n]" : term macro_rules | `(`[Cli| $name:term VIA $run:term; [$version:term] $description:term $[FLAGS: $flags* ]? $[ARGS: $positionalArgs* $[$variableArg]? ]? $[SUBCOMMANDS: $subCommands;*]? $[EXTENSIONS: $extensions;*]? ]) => do `(Cmd.mk (name := $(expandIdentLiterally name)) (version := $version) (description := $description) (flags := $((← flags.getD #[] |>.mapM expandFlag) |> quote)) (positionalArgs := $((← positionalArgs.getD #[] |>.mapM expandPositionalArg) |> quote)) (variableArg? := $((← variableArg.join.mapM expandVariableArg) |> quote)) (run := $run) (subCmds := $(quote <| (subCommands.getD (#[] : Array Syntax) : Array Syntax))) (extension? := some <| Array.foldl Extension.then { : Extension } $(quote <| (extensions.getD (#[] : Array Syntax) : Array Syntax)))) end Macro section Info /-- Maximum width within which all formatted text should fit. -/ def maxWidth : Nat := 80 /-- Amount of spaces with which section content is indented. -/ def indentation : Nat := 4 /-- Maximum width within which all formatted text should fit, after indentation. -/ def maxIndentedWidth : Nat := maxWidth - indentation /-- Formats `xs` by `String.optJoin`ing the components with a single space. -/ def line (xs : Array String) : String := " ".optJoin xs /-- Formats `xs` by `String.optJoin`ing the components with a newline `\n`. -/ def lines (xs : Array String) : String := "\n".optJoin xs /-- Renders a help section with the designated `title` and `content`. If `content = ""`, `emptyContentPlaceholder?` will be used instead. If `emptyContentPlaceholder? = none`, neither the title nor the content will be rendered. -/ def renderSection (title : String) (content : String) (emptyContentPlaceholder? : Option String := none) : String := let titleLine? : Option String := do if content = "" then s!"{title}: {← emptyContentPlaceholder?}" else s!"{title}:" lines #[ titleLine?.optStr, content |>.wrapWordsAt! maxIndentedWidth |>.indent indentation ] /-- Renders a table using `Array.renderTable!` and then renders a section with the designated `title` and the rendered table as content. -/ def renderTable (title : String) (columns : Array (String × String)) (emptyTablePlaceholder? : Option String := none) : String := let table := columns.renderTable! (maxWidth := maxIndentedWidth) renderSection title table emptyTablePlaceholder? namespace Cmd private def metaDataInfo (c : Cmd) : String := lines #[ s!"{c.fullName} [{c.version}]".wrapWordsAt! maxWidth, c.description.wrapWordsAt! maxWidth ] private def usageInfo (c : Cmd) : String := let subCmdTitle? : Option String := if ¬c.subCmds.isEmpty then "[SUBCOMMAND]" else none let posArgNames : String := line <| c.positionalArgs.map (s!"<{·.name}>") let varArgName? : Option String := do s!"<{(← c.variableArg?).name}>..." let info := line #[c.fullName, subCmdTitle?.optStr, "[FLAGS]", posArgNames, varArgName?.optStr] renderSection "USAGE" info private def flagInfo (c : Cmd) : String := let columns : Array (String × String) := c.flags.map fun flag => let shortName? : Option String := do s!"-{← flag.shortName?}" let names : String := ", ".optJoin #[shortName?.optStr, s!"--{flag.longName}"] let type? : Option String := if ¬ flag.isParamless then s!": {flag.type.name}" else none (line #[names, type?.optStr], flag.description) renderTable "FLAGS" columns (emptyTablePlaceholder? := "None") private def positionalArgInfo (c : Cmd) : String := let args := if let some variableArg := c.variableArg? then c.positionalArgs ++ #[variableArg] else c.positionalArgs args.map (fun arg => (line #[arg.name, s!": {arg.type.name}"], arg.description)) |> renderTable "ARGS" private def subCommandInfo (c : Cmd) : String := c.subCmds.map (fun subCmd => (subCmd.name, subCmd.description)) |> renderTable "SUBCOMMANDS" /-- Renders the help for `c`. -/ def help (c : Cmd) : String := lines #[ c.metaDataInfo, "\n" ++ c.usageInfo, "\n" ++ c.flagInfo, (if ¬c.positionalArgs.isEmpty ∨ c.hasVariableArg then "\n" else "") ++ c.positionalArgInfo, (if ¬c.subCmds.isEmpty then "\n" else "") ++ c.subCommandInfo, (if c.hasFurtherInformation then "\n" else "") ++ c.furtherInformation?.optStr ] /-- Renders an error for `c` with the designated message `msg`. -/ def error (c : Cmd) (msg : String) : String := lines #[ msg.wrapWordsAt! maxWidth, s!"Run `{c.fullName} -h` for further information.".wrapWordsAt! maxWidth ] /-- Prints the help for `c`. -/ def printHelp (c : Cmd) : IO Unit := IO.println c.help /-- Prints an error for `c` with the designated message `msg`. -/ def printError (c : Cmd) (msg : String) : IO Unit := IO.println <| c.error msg /-- Prints the version of `c`. -/ def printVersion (c : Cmd) : IO Unit := IO.println c.version end Cmd end Info section Parsing /-- Represents the exact representation of a flag as input by the user. -/ structure InputFlag where /-- Flag name input by the user. -/ name : String /-- Whether the flag input by the user was a short one. -/ isShort : Bool instance : ToString InputFlag where toString f := let pre := if f.isShort then "-" else "--" s!"{pre}{f.name}" namespace ParseError /-- Kind of error that occured during parsing. -/ inductive Kind | unknownFlag (inputFlag : InputFlag) (msg : String := s!"Unknown flag `{inputFlag}`.") | missingFlagArg (flag : Flag) (inputFlag : InputFlag) (msg : String := s!"Missing argument for flag `{inputFlag}`.") | duplicateFlag (flag : Flag) (inputFlag : InputFlag) (msg : String := let complementaryName? : Option String := do if inputFlag.isShort then s!" (`--{flag.longName}`)" else s!" (`-{← flag.shortName?}`)" s!"Duplicate flag `{inputFlag}`{complementaryName?.optStr}.") | redundantFlagArg (flag : Flag) (inputFlag : InputFlag) (inputValue : String) (msg : String := s!"Redundant argument `{inputValue}` for flag `{inputFlag}` that takes no arguments.") | invalidFlagType (flag : Flag) (inputFlag : InputFlag) (inputValue : String) (msg : String := s!"Invalid type of argument `{inputValue}` for flag `{inputFlag} : {flag.type.name}`.") | missingPositionalArg (arg : Arg) (msg : String := s!"Missing positional argument `<{arg.name}>.`") | invalidPositionalArgType (arg : Arg) (inputArg : String) (msg : String := s!"Invalid type of argument `{inputArg}` for positional argument `<{arg.name} : {arg.type.name}>`.") | redundantPositionalArg (inputArg : String) (msg : String := s!"Redundant positional argument `{inputArg}`.") | invalidVariableArgType (arg : Arg) (inputArg : String) (msg : String := s!"Invalid type of argument `{inputArg}` for variable argument `<{arg.name} : {arg.type.name}>...`.") /-- Associated message of the error. -/ def Kind.msg : Kind → String | unknownFlag _ msg => msg | missingFlagArg _ _ msg => msg | duplicateFlag _ _ msg => msg | redundantFlagArg _ _ _ msg => msg | invalidFlagType _ _ _ msg => msg | missingPositionalArg _ msg => msg | invalidPositionalArgType _ _ msg => msg | redundantPositionalArg _ msg => msg | invalidVariableArgType _ _ msg => msg end ParseError open ParseError in /-- Error that occured during parsing. Contains the command that the error occured in and the kind of the error. -/ structure ParseError where /-- Command that the error occured in. -/ cmd : Cmd /-- Kind of error that occured. -/ kind : Kind private structure ParseState where idx : Nat cmd : Cmd parsedFlags : Array Parsed.Flag parsedPositionalArgs : Array Parsed.Arg parsedVariableArgs : Array Parsed.Arg private abbrev ParseM := ExceptT ParseError (ReaderT (Array String) (StateM ParseState)) namespace ParseM open ParseError.Kind private def args : ParseM (Array String) := read private def idx : ParseM Nat := do (← get).idx private def cmd : ParseM Cmd := do (← get).cmd private def parsedFlags : ParseM (Array Parsed.Flag) := do (← get).parsedFlags private def parsedPositionalArgs : ParseM (Array Parsed.Arg) := do (← get).parsedPositionalArgs private def parsedVariableArgs : ParseM (Array Parsed.Arg) := do (← get).parsedVariableArgs private def peek? : ParseM (Option String) := do return (← args).get? (← idx) private def peekNext? : ParseM (Option String) := do return (← args).get? <| (← idx) + 1 private def flag? (inputFlag : InputFlag) : ParseM (Option Flag) := do if inputFlag.isShort then return (← cmd).flagByShortName? inputFlag.name else return (← cmd).flag? inputFlag.name private def setIdx (idx : Nat) : ParseM Unit := do set { ← get with idx := idx } private def setCmd (c : Cmd) : ParseM Unit := do set { ← get with cmd := c } private def pushParsedFlag (parsedFlag : Parsed.Flag) : ParseM Unit := do set { ← get with parsedFlags := (← parsedFlags).push parsedFlag } private def pushParsedPositionalArg (parsedPositionalArg : Parsed.Arg) : ParseM Unit := do set { ← get with parsedPositionalArgs := (← parsedPositionalArgs).push parsedPositionalArg } private def pushParsedVariableArg (parsedVariableArg : Parsed.Arg) : ParseM Unit := do set { ← get with parsedVariableArgs := (← parsedVariableArgs).push parsedVariableArg } private def skip : ParseM Unit := do setIdx <| (← idx) + 1 private def parseError (kind : ParseError.Kind) : ParseM ParseError := do return ⟨← cmd, kind⟩ private partial def parseSubCmds : ParseM Unit := do loop (← cmd) where loop (parent : Cmd) : ParseM Unit := do let some subCmd ← parseSubCmd? parent | do setCmd parent loop subCmd parseSubCmd? (parent : Cmd) : ParseM (Option Cmd) := do let some arg ← peek? | return none let some subCmd ← pure <| parent.subCmd? arg | return none skip return subCmd private def parseEndOfFlags : ParseM Bool := do let some arg ← peek? | return false if arg = "--" then skip return true return false private def readFlagContent? : ParseM (Option (String × Bool)) := do let some arg ← peek? | return none if arg = "--" ∨ arg = "-" then return none if arg.take 2 = "--" then return (arg.drop 2, false) if arg.take 1 = "-" then return (arg.drop 1, true) return none private def ensureFlagUnique (flag : Flag) (inputFlag : InputFlag) : ParseM Unit := do if (← parsedFlags).find? (·.flag.longName = flag.longName) |>.isSome then throw <| ← parseError <| duplicateFlag flag inputFlag private def ensureFlagWellTyped (flag : Flag) (inputFlag : InputFlag) (value : String) : ParseM Unit := do if ¬ flag.type.isValid value then throw <| ← parseError <| invalidFlagType flag inputFlag value private partial def readMultiFlag? : ParseM (Option (Array Parsed.Flag)) := do let some (flagContent, true) ← readFlagContent? | return none let some (parsedFlags : Array (String × Parsed.Flag)) ← loop flagContent Std.RBTree.empty | return none for (inputFlagName, parsedFlag) in parsedFlags do ensureFlagUnique parsedFlag.flag ⟨inputFlagName, true⟩ skip return some <| parsedFlags.map (·.2) where loop (flagContent : String) (matched : Std.RBTree String (· < ·)) : ParseM (Option (Array (String × Parsed.Flag))) := do -- this is not tail recursive, but that's fine: `loop` will only recurse further if the corresponding -- flag has not been matched yet, meaning that this can only overflow if the application has an -- astronomical amount of short flags. if flagContent = "" then return some #[] let parsedFlagsCandidates : Array (Array (String × Parsed.Flag)) ← (← cmd).flags.filter (·.isParamless) |>.filter (·.hasShortName) |>.filter (·.shortName!.isPrefixOf flagContent) |>.filter (¬ matched.contains ·.shortName!) |>.qsort (·.shortName!.length > ·.shortName!.length) |>.filterMapM fun flag => do let inputFlagName := flagContent.take flag.shortName!.length let restContent := flagContent.drop flag.shortName!.length let newMatched := matched.insert flag.shortName! let some tail ← loop restContent newMatched | return none return some <| #[(inputFlagName, ⟨flag, ""⟩)] ++ tail return parsedFlagsCandidates.get? 0 private def readEqFlag? : ParseM (Option Parsed.Flag) := do let some (flagContent, isShort) ← readFlagContent? | return none match flagContent.splitOn "=" with | [] => panic! "Cli.readEqFlag?: String.splitOn returned empty list" | [name] => return none | (flagName :: flagArg :: rest) => let flagValue := "=".intercalate <| flagArg :: rest let inputFlag : InputFlag := ⟨flagName, isShort⟩ let some flag ← flag? inputFlag | throw <| ← parseError <| unknownFlag inputFlag if flag.isParamless then throw <| ← parseError <| redundantFlagArg flag inputFlag flagValue ensureFlagUnique flag inputFlag ensureFlagWellTyped flag inputFlag flagValue skip return some ⟨flag, flagValue⟩ private def readWsFlag? : ParseM (Option Parsed.Flag) := do let some (flagName, isShort) ← readFlagContent? | return none let some flagValue ← peekNext? | return none let inputFlag : InputFlag := ⟨flagName, isShort⟩ let some flag ← flag? inputFlag | return none if flag.isParamless then return none ensureFlagUnique flag inputFlag ensureFlagWellTyped flag inputFlag flagValue skip; skip return some ⟨flag, flagValue⟩ private def readPrefixFlag? : ParseM (Option Parsed.Flag) := do let some (flagContent, true) ← readFlagContent? | return none let some flag ← pure <| (← cmd).flags.filter (¬ ·.isParamless) |>.filter (·.hasShortName) |>.filter (·.shortName!.isPrefixOf flagContent) |>.filter (·.shortName!.length < flagContent.length) |>.qsort (·.shortName!.length > ·.shortName!.length) |>.get? 0 | return none let flagName := flag.shortName! let flagValue := flagContent.drop flagName.length let inputFlag : InputFlag := ⟨flagName, true⟩ ensureFlagUnique flag inputFlag ensureFlagWellTyped flag inputFlag flagValue skip return some ⟨flag, flagValue⟩ private def readParamlessFlag? : ParseM (Option Parsed.Flag) := do let some (flagName, isShort) ← readFlagContent? | return none let inputFlag : InputFlag := ⟨flagName, isShort⟩ let some flag ← flag? inputFlag | throw <| ← parseError <| unknownFlag inputFlag if ¬ flag.isParamless then throw <| ← parseError <| missingFlagArg flag inputFlag ensureFlagUnique flag inputFlag skip return some ⟨flag, ""⟩ private def parseFlag : ParseM Bool := do if let some parsedFlags ← readMultiFlag? then for parsedFlag in parsedFlags do pushParsedFlag parsedFlag return true let tryRead parse : OptionT ParseM Parsed.Flag := parse let some parsedFlag ← tryRead readEqFlag? <|> tryRead readWsFlag? <|> tryRead readPrefixFlag? <|> tryRead readParamlessFlag? | return false pushParsedFlag parsedFlag return true private def parsePositionalArg : ParseM Bool := do let some positionalArgValue ← peek? | return false let some positionalArg ← pure <| (← cmd).positionalArgs.get? (← parsedPositionalArgs).size | return false if ¬ positionalArg.type.isValid positionalArgValue then throw <| ← parseError <| invalidPositionalArgType positionalArg positionalArgValue skip pushParsedPositionalArg ⟨positionalArg, positionalArgValue⟩ return true private def parseVariableArg : ParseM Bool := do let some variableArgValue ← peek? | return false let some variableArg ← pure <| (← cmd).variableArg? | throw <| ← parseError <| redundantPositionalArg variableArgValue if ¬ variableArg.type.isValid variableArgValue then throw <| ← parseError <| invalidVariableArgType variableArg variableArgValue skip pushParsedVariableArg ⟨variableArg, variableArgValue⟩ return true private partial def parseArgs : ParseM Unit := do loop false where loop (endOfFlags : Bool) : ParseM Unit := do if ← !endOfFlags <&&> parseEndOfFlags then loop true else if ← !endOfFlags <&&> parseFlag then loop endOfFlags else if ← parsePositionalArg then loop endOfFlags else if ← parseVariableArg then loop endOfFlags private def parse? (c : Cmd) (args : List String) : Option (Except ParseError (Cmd × Parsed)) := do if args = [] then none let args := args.tail!.toArray return parse args |>.run' { idx := 0 cmd := c parsedFlags := #[] parsedPositionalArgs := #[] parsedVariableArgs := #[] } where parse : ParseM (Cmd × Parsed) := do parseSubCmds parseArgs let parsed : Parsed := { cmd := (← cmd).meta flags := ← parsedFlags positionalArgs := ← parsedPositionalArgs variableArgs := ← parsedVariableArgs } if parsed.hasFlag "help" ∨ parsed.hasFlag "version" then return (← cmd, parsed) if (← parsedPositionalArgs).size < (← cmd).positionalArgs.size then throw <| ← parseError <| missingPositionalArg <| (← cmd).positionalArgs.get! (← parsedPositionalArgs).size return (← cmd, parsed) end ParseM namespace Cmd /-- Parses `args` according to the specification provided in `c`, returning either a `ParseError` or the (sub)command that was called and the parsed content of the input. Yields `none` if `args` is empty: The list of arguments is always expected to have the application name at `args[0]`. -/ def parse? (c : Cmd) (args : List String) : Option (Except ParseError (Cmd × Parsed)) := ParseM.parse? c args /-- Parses `args` according to the specification provided in `c`, returning either a `ParseError` or the (sub)command that was called and the parsed content of the input. Yields `none` if `args` is empty: The list of arguments is always expected to have the application name at `args[0]`. -/ def parse! (c : Cmd) (args : List String) : Except ParseError (Cmd × Parsed) := c.parse? args |>.get! /-- Processes `args` by `Cmd.parse?`ing the input according to `c` and then applying the extension of the respective (sub)command that was called. Returns either the (sub)command that an error occured in and the corresponding error message or the (sub)command that was called and the parsed input after postprocessing. Yields `none` if `args` is empty: The list of arguments is always expected to have the application name at `args[0]`. -/ def process? (c : Cmd) (args : List String) : Option (Except (Cmd × String) (Cmd × Parsed)) := do let result ← c.parse? args return do match result with | Except.ok (cmd, parsed) => match cmd.extension? with | some ext => let newMeta := ext.extendMeta cmd.meta let newCmd := cmd.update' (meta := newMeta) match ext.postprocess newMeta parsed with | Except.ok newParsed => return (newCmd, newParsed) | Except.error msg => throw (newCmd, msg) | none => return (cmd, parsed) | Except.error err => throw (err.cmd, err.kind.msg) /-- Processes `args` by `Cmd.parse!`ing the input according to `c` and then applying the extension of the respective (sub)command that was called. Returns either the (sub)command that an error occured in and the corresponding error message or the (sub)command that was called and the parsed input after postprocessing. Panics if `args` is empty: The list of arguments is always expected to have the application name at `args[0]`. -/ def process! (c : Cmd) (args : List String) : Except (Cmd × String) (Cmd × Parsed) := c.process? args |>.get! end Cmd end Parsing section IO namespace Cmd /-- Validates `args` by `Cmd.process?`ing the input according to `c`. Prints the help or the version of the called (sub)command if the respective flag was passed and returns `0` for the exit code. If neither of these flags were passed and processing was successful, the `run` handler of the called command is executed. In the case of a processing error, the error is printed and an exit code of `1` is returned. Yields `none` if `args` is empty: The list of arguments is always expected to have the application name at `args[0]`. -/ def validate? (c : Cmd) (args : List String) : Option (IO UInt32) := do let result ← c.process? args return do match result with | Except.ok (cmd, parsed) => if parsed.hasFlag "help" then cmd.printHelp return 0 if parsed.hasFlag "version" then cmd.printVersion return 0 cmd.run parsed | Except.error (cmd, err) => cmd.printError err return 1 /-- Validates `args` by `Cmd.process!`ing the input according to `c`. Prints the help or the version of the called (sub)command if the respective flag was passed and returns `0` for the exit code. If neither of these flags were passed and processing was successful, the `run` handler of the called command is executed. In the case of a processing error, the error is printed and an exit code of `1` is returned. Panics if `args` is empty: The list of arguments is always expected to have the application name at `args[0]`. -/ def validate! (c : Cmd) (args : List String) : IO UInt32 := c.validate? args |>.get! end Cmd end IO end Cli
504cd00edc53e954296d8f3cd3b153d69edd2e7e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/geometry/manifold/mfderiv.lean
e39e7f56780eb6811e40ec83ec050db5084defb5
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
71,145
lean
/- Copyright (c) 2020 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 geometry.manifold.basic_smooth_bundle /-! # The derivative of functions between smooth manifolds Let `M` and `M'` be two smooth manifolds with corners over a field `𝕜` (with respective models with corners `I` on `(E, H)` and `I'` on `(E', H')`), and let `f : M → M'`. We define the derivative of the function at a point, within a set or along the whole space, mimicking the API for (Fréchet) derivatives. It is denoted by `mfderiv I I' f x`, where "m" stands for "manifold" and "f" for "Fréchet" (as in the usual derivative `fderiv 𝕜 f x`). ## Main definitions * `unique_mdiff_on I s` : predicate saying that, at each point of the set `s`, a function can have at most one derivative. This technical condition is important when we define `mfderiv_within` below, as otherwise there is an arbitrary choice in the derivative, and many properties will fail (for instance the chain rule). This is analogous to `unique_diff_on 𝕜 s` in a vector space. Let `f` be a map between smooth manifolds. The following definitions follow the `fderiv` API. * `mfderiv I I' f x` : the derivative of `f` at `x`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. If the map is not differentiable, this is `0`. * `mfderiv_within I I' f s x` : the derivative of `f` at `x` within `s`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. If the map is not differentiable within `s`, this is `0`. * `mdifferentiable_at I I' f x` : Prop expressing whether `f` is differentiable at `x`. * `mdifferentiable_within_at 𝕜 f s x` : Prop expressing whether `f` is differentiable within `s` at `x`. * `has_mfderiv_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative at `x`. * `has_mfderiv_within_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative within `s` at `x`. * `mdifferentiable_on I I' f s` : Prop expressing that `f` is differentiable on the set `s`. * `mdifferentiable I I' f` : Prop expressing that `f` is differentiable everywhere. * `tangent_map I I' f` : the derivative of `f`, as a map from the tangent bundle of `M` to the tangent bundle of `M'`. We also establish results on the differential of the identity, constant functions, charts, extended charts. For functions between vector spaces, we show that the usual notions and the manifold notions coincide. ## Implementation notes The tangent bundle is constructed using the machinery of topological fiber bundles, for which one can define bundled morphisms and construct canonically maps from the total space of one bundle to the total space of another one. One could use this mechanism to construct directly the derivative of a smooth map. However, we want to define the derivative of any map (and let it be zero if the map is not differentiable) to avoid proof arguments everywhere. This means we have to go back to the details of the definition of the total space of a fiber bundle constructed from core, to cook up a suitable definition of the derivative. It is the following: at each point, we have a preferred chart (used to identify the fiber above the point with the model vector space in fiber bundles). Then one should read the function using these preferred charts at `x` and `f x`, and take the derivative of `f` in these charts. Due to the fact that we are working in a model with corners, with an additional embedding `I` of the model space `H` in the model vector space `E`, the charts taking values in `E` are not the original charts of the manifold, but those ones composed with `I`, called extended charts. We define `written_in_ext_chart I I' x f` for the function `f` written in the preferred extended charts. Then the manifold derivative of `f`, at `x`, is just the usual derivative of `written_in_ext_chart I I' x f`, at the point `(ext_chart_at I x) x`. There is a subtelty with respect to continuity: if the function is not continuous, then the image of a small open set around `x` will not be contained in the source of the preferred chart around `f x`, which means that when reading `f` in the chart one is losing some information. To avoid this, we include continuity in the definition of differentiablity (which is reasonable since with any definition, differentiability implies continuity). *Warning*: the derivative (even within a subset) is a linear map on the whole tangent space. Suppose that one is given a smooth submanifold `N`, and a function which is smooth on `N` (i.e., its restriction to the subtype `N` is smooth). Then, in the whole manifold `M`, the property `mdifferentiable_on I I' f N` holds. However, `mfderiv_within I I' f N` is not uniquely defined (what values would one choose for vectors that are transverse to `N`?), which can create issues down the road. The problem here is that knowing the value of `f` along `N` does not determine the differential of `f` in all directions. This is in contrast to the case where `N` would be an open subset, or a submanifold with boundary of maximal dimension, where this issue does not appear. The predicate `unique_mdiff_on I N` indicates that the derivative along `N` is unique if it exists, and is an assumption in most statements requiring a form of uniqueness. On a vector space, the manifold derivative and the usual derivative are equal. This means in particular that they live on the same space, i.e., the tangent space is defeq to the original vector space. To get this property is a motivation for our definition of the tangent space as a single copy of the vector space, instead of more usual definitions such as the space of derivations, or the space of equivalence classes of smooth curves in the manifold. ## Tags Derivative, manifold -/ noncomputable theory open_locale classical topological_space manifold open set universe u section derivatives_definitions /-! ### Derivative of maps between manifolds The derivative of a smooth map `f` between smooth manifold `M` and `M'` at `x` is a bounded linear map from the tangent space to `M` at `x`, to the tangent space to `M'` at `f x`. Since we defined the tangent space using one specific chart, the formula for the derivative is written in terms of this specific chart. We use the names `mdifferentiable` and `mfderiv`, where the prefix letter `m` means "manifold". -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] /-- Predicate ensuring that, at a point and within a set, a function can have at most one derivative. This is expressed using the preferred chart at the considered point. -/ def unique_mdiff_within_at (s : set M) (x : M) := unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- Predicate ensuring that, at all points of a set, a function can have at most one derivative. -/ def unique_mdiff_on (s : set M) := ∀x∈s, unique_mdiff_within_at I s x /-- Conjugating a function to write it in the preferred charts around `x`. The manifold derivative of `f` will just be the derivative of this conjugated function. -/ @[simp, mfld_simps] def written_in_ext_chart_at (x : M) (f : M → M') : E → E' := (ext_chart_at I' (f x)) ∘ f ∘ (ext_chart_at I x).symm /-- `mdifferentiable_within_at I I' f s x` indicates that the function `f` between manifolds has a derivative at the point `x` within the set `s`. This is a generalization of `differentiable_within_at` to manifolds. We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def mdifferentiable_within_at (f : M → M') (s : set M) (x : M) := continuous_within_at f s x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- `mdifferentiable_at I I' f x` indicates that the function `f` between manifolds has a derivative at the point `x`. This is a generalization of `differentiable_at` to manifolds. We require continuity in the definition, as otherwise points close to `x` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def mdifferentiable_at (f : M → M') (x : M) := continuous_at f x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) (range I) ((ext_chart_at I x) x) /-- `mdifferentiable_on I I' f s` indicates that the function `f` between manifolds has a derivative within `s` at all points of `s`. This is a generalization of `differentiable_on` to manifolds. -/ def mdifferentiable_on (f : M → M') (s : set M) := ∀x ∈ s, mdifferentiable_within_at I I' f s x /-- `mdifferentiable I I' f` indicates that the function `f` between manifolds has a derivative everywhere. This is a generalization of `differentiable` to manifolds. -/ def mdifferentiable (f : M → M') := ∀x, mdifferentiable_at I I' f x /-- Prop registering if a local homeomorphism is a local diffeomorphism on its source -/ def local_homeomorph.mdifferentiable (f : local_homeomorph M M') := (mdifferentiable_on I I' f f.source) ∧ (mdifferentiable_on I' I f.symm f.target) variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M'] /-- `has_mfderiv_within_at I I' f s x f'` indicates that the function `f` between manifolds has, at the point `x` and within the set `s`, the derivative `f'`. Here, `f'` is a continuous linear map from the tangent space at `x` to the tangent space at `f x`. This is a generalization of `has_fderiv_within_at` to manifolds (as indicated by the prefix `m`). The order of arguments is changed as the type of the derivative `f'` depends on the choice of `x`. We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def has_mfderiv_within_at (f : M → M') (s : set M) (x : M) (f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) := continuous_within_at f s x ∧ has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f' ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- `has_mfderiv_at I I' f x f'` indicates that the function `f` between manifolds has, at the point `x`, the derivative `f'`. Here, `f'` is a continuous linear map from the tangent space at `x` to the tangent space at `f x`. We require continuity in the definition, as otherwise points close to `x` `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def has_mfderiv_at (f : M → M') (x : M) (f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) := continuous_at f x ∧ has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f' (range I) ((ext_chart_at I x) x) /-- Let `f` be a function between two smooth manifolds. Then `mfderiv_within I I' f s x` is the derivative of `f` at `x` within `s`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. -/ def mfderiv_within (f : M → M') (s : set M) (x : M) : tangent_space I x →L[𝕜] tangent_space I' (f x) := if h : mdifferentiable_within_at I I' f s x then (fderiv_within 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) : _) else 0 /-- Let `f` be a function between two smooth manifolds. Then `mfderiv I I' f x` is the derivative of `f` at `x`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. -/ def mfderiv (f : M → M') (x : M) : tangent_space I x →L[𝕜] tangent_space I' (f x) := if h : mdifferentiable_at I I' f x then (fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : E → E') (range I) ((ext_chart_at I x) x) : _) else 0 /-- The derivative within a set, as a map between the tangent bundles -/ def tangent_map_within (f : M → M') (s : set M) : tangent_bundle I M → tangent_bundle I' M' := λp, ⟨f p.1, (mfderiv_within I I' f s p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩ /-- The derivative, as a map between the tangent bundles -/ def tangent_map (f : M → M') : tangent_bundle I M → tangent_bundle I' M' := λp, ⟨f p.1, (mfderiv I I' f p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩ end derivatives_definitions section derivatives_properties /-! ### Unique differentiability sets in manifolds -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] -- {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] {f f₀ f₁ : M → M'} {x : M} {s t : set M} {g : M' → M''} {u : set M'} lemma unique_mdiff_within_at_univ : unique_mdiff_within_at I univ x := begin unfold unique_mdiff_within_at, simp only [preimage_univ, univ_inter], exact I.unique_diff _ (mem_range_self _) end variable {I} lemma unique_mdiff_within_at_iff {s : set M} {x : M} : unique_mdiff_within_at I s x ↔ unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ (ext_chart_at I x).target) ((ext_chart_at I x) x) := begin apply unique_diff_within_at_congr, rw [nhds_within_inter, nhds_within_inter, nhds_within_ext_chart_target_eq] end lemma unique_mdiff_within_at.mono (h : unique_mdiff_within_at I s x) (st : s ⊆ t) : unique_mdiff_within_at I t x := unique_diff_within_at.mono h $ inter_subset_inter (preimage_mono st) (subset.refl _) lemma unique_mdiff_within_at.inter' (hs : unique_mdiff_within_at I s x) (ht : t ∈ 𝓝[s] x) : unique_mdiff_within_at I (s ∩ t) x := begin rw [unique_mdiff_within_at, ext_chart_preimage_inter_eq], exact unique_diff_within_at.inter' hs (ext_chart_preimage_mem_nhds_within I x ht) end lemma unique_mdiff_within_at.inter (hs : unique_mdiff_within_at I s x) (ht : t ∈ 𝓝 x) : unique_mdiff_within_at I (s ∩ t) x := begin rw [unique_mdiff_within_at, ext_chart_preimage_inter_eq], exact unique_diff_within_at.inter hs (ext_chart_preimage_mem_nhds I x ht) end lemma is_open.unique_mdiff_within_at (xs : x ∈ s) (hs : is_open s) : unique_mdiff_within_at I s x := begin have := unique_mdiff_within_at.inter (unique_mdiff_within_at_univ I) (is_open.mem_nhds hs xs), rwa univ_inter at this end lemma unique_mdiff_on.inter (hs : unique_mdiff_on I s) (ht : is_open t) : unique_mdiff_on I (s ∩ t) := λx hx, unique_mdiff_within_at.inter (hs _ hx.1) (is_open.mem_nhds ht hx.2) lemma is_open.unique_mdiff_on (hs : is_open s) : unique_mdiff_on I s := λx hx, is_open.unique_mdiff_within_at hx hs lemma unique_mdiff_on_univ : unique_mdiff_on I (univ : set M) := is_open_univ.unique_mdiff_on /- We name the typeclass variables related to `smooth_manifold_with_corners` structure as they are necessary in lemmas mentioning the derivative, but not in lemmas about differentiability, so we want to include them or omit them when necessary. -/ variables [Is : smooth_manifold_with_corners I M] [I's : smooth_manifold_with_corners I' M'] [I''s : smooth_manifold_with_corners I'' M''] {f' f₀' f₁' : tangent_space I x →L[𝕜] tangent_space I' (f x)} {g' : tangent_space I' (f x) →L[𝕜] tangent_space I'' (g (f x))} /-- `unique_mdiff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_mdiff_within_at.eq (U : unique_mdiff_within_at I s x) (h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') : f' = f₁' := U.eq h.2 h₁.2 theorem unique_mdiff_on.eq (U : unique_mdiff_on I s) (hx : x ∈ s) (h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') : f' = f₁' := unique_mdiff_within_at.eq (U _ hx) h h₁ /-! ### General lemmas on derivatives of functions between manifolds We mimick the API for functions between vector spaces -/ lemma mdifferentiable_within_at_iff {f : M → M'} {s : set M} {x : M} : mdifferentiable_within_at I I' f s x ↔ continuous_within_at f s x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' s) ((ext_chart_at I x) x) := begin refine and_congr iff.rfl (exists_congr $ λ f', _), rw [inter_comm], simp only [has_fderiv_within_at, nhds_within_inter, nhds_within_ext_chart_target_eq] end include Is I's lemma mfderiv_within_zero_of_not_mdifferentiable_within_at (h : ¬ mdifferentiable_within_at I I' f s x) : mfderiv_within I I' f s x = 0 := by simp only [mfderiv_within, h, dif_neg, not_false_iff] lemma mfderiv_zero_of_not_mdifferentiable_at (h : ¬ mdifferentiable_at I I' f x) : mfderiv I I' f x = 0 := by simp only [mfderiv, h, dif_neg, not_false_iff] theorem has_mfderiv_within_at.mono (h : has_mfderiv_within_at I I' f t x f') (hst : s ⊆ t) : has_mfderiv_within_at I I' f s x f' := ⟨ continuous_within_at.mono h.1 hst, has_fderiv_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩ theorem has_mfderiv_at.has_mfderiv_within_at (h : has_mfderiv_at I I' f x f') : has_mfderiv_within_at I I' f s x f' := ⟨ continuous_at.continuous_within_at h.1, has_fderiv_within_at.mono h.2 (inter_subset_right _ _) ⟩ lemma has_mfderiv_within_at.mdifferentiable_within_at (h : has_mfderiv_within_at I I' f s x f') : mdifferentiable_within_at I I' f s x := ⟨h.1, ⟨f', h.2⟩⟩ lemma has_mfderiv_at.mdifferentiable_at (h : has_mfderiv_at I I' f x f') : mdifferentiable_at I I' f x := ⟨h.1, ⟨f', h.2⟩⟩ @[simp, mfld_simps] lemma has_mfderiv_within_at_univ : has_mfderiv_within_at I I' f univ x f' ↔ has_mfderiv_at I I' f x f' := by simp only [has_mfderiv_within_at, has_mfderiv_at, continuous_within_at_univ] with mfld_simps theorem has_mfderiv_at_unique (h₀ : has_mfderiv_at I I' f x f₀') (h₁ : has_mfderiv_at I I' f x f₁') : f₀' = f₁' := begin rw ← has_mfderiv_within_at_univ at h₀ h₁, exact (unique_mdiff_within_at_univ I).eq h₀ h₁ end lemma has_mfderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' := begin rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_preimage_inter_eq, has_fderiv_within_at_inter', continuous_within_at_inter' h], exact ext_chart_preimage_mem_nhds_within I x h, end lemma has_mfderiv_within_at_inter (h : t ∈ 𝓝 x) : has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' := begin rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_preimage_inter_eq, has_fderiv_within_at_inter, continuous_within_at_inter h], exact ext_chart_preimage_mem_nhds I x h, end lemma has_mfderiv_within_at.union (hs : has_mfderiv_within_at I I' f s x f') (ht : has_mfderiv_within_at I I' f t x f') : has_mfderiv_within_at I I' f (s ∪ t) x f' := begin split, { exact continuous_within_at.union hs.1 ht.1 }, { convert has_fderiv_within_at.union hs.2 ht.2, simp only [union_inter_distrib_right, preimage_union] } end lemma has_mfderiv_within_at.nhds_within (h : has_mfderiv_within_at I I' f s x f') (ht : s ∈ 𝓝[t] x) : has_mfderiv_within_at I I' f t x f' := (has_mfderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_mfderiv_within_at.has_mfderiv_at (h : has_mfderiv_within_at I I' f s x f') (hs : s ∈ 𝓝 x) : has_mfderiv_at I I' f x f' := by rwa [← univ_inter s, has_mfderiv_within_at_inter hs, has_mfderiv_within_at_univ] at h lemma mdifferentiable_within_at.has_mfderiv_within_at (h : mdifferentiable_within_at I I' f s x) : has_mfderiv_within_at I I' f s x (mfderiv_within I I' f s x) := begin refine ⟨h.1, _⟩, simp only [mfderiv_within, h, dif_pos] with mfld_simps, exact differentiable_within_at.has_fderiv_within_at h.2 end lemma mdifferentiable_within_at.mfderiv_within (h : mdifferentiable_within_at I I' f s x) : (mfderiv_within I I' f s x) = fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) := by simp only [mfderiv_within, h, dif_pos] lemma mdifferentiable_at.has_mfderiv_at (h : mdifferentiable_at I I' f x) : has_mfderiv_at I I' f x (mfderiv I I' f x) := begin refine ⟨h.1, _⟩, simp only [mfderiv, h, dif_pos] with mfld_simps, exact differentiable_within_at.has_fderiv_within_at h.2 end lemma mdifferentiable_at.mfderiv (h : mdifferentiable_at I I' f x) : (mfderiv I I' f x) = fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) (range I) ((ext_chart_at I x) x) := by simp only [mfderiv, h, dif_pos] lemma has_mfderiv_at.mfderiv (h : has_mfderiv_at I I' f x f') : mfderiv I I' f x = f' := (has_mfderiv_at_unique h h.mdifferentiable_at.has_mfderiv_at).symm lemma has_mfderiv_within_at.mfderiv_within (h : has_mfderiv_within_at I I' f s x f') (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' f s x = f' := by { ext, rw hxs.eq h h.mdifferentiable_within_at.has_mfderiv_within_at } lemma mdifferentiable.mfderiv_within (h : mdifferentiable_at I I' f x) (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' f s x = mfderiv I I' f x := begin apply has_mfderiv_within_at.mfderiv_within _ hxs, exact h.has_mfderiv_at.has_mfderiv_within_at end lemma mfderiv_within_subset (st : s ⊆ t) (hs : unique_mdiff_within_at I s x) (h : mdifferentiable_within_at I I' f t x) : mfderiv_within I I' f s x = mfderiv_within I I' f t x := ((mdifferentiable_within_at.has_mfderiv_within_at h).mono st).mfderiv_within hs omit Is I's lemma mdifferentiable_within_at.mono (hst : s ⊆ t) (h : mdifferentiable_within_at I I' f t x) : mdifferentiable_within_at I I' f s x := ⟨ continuous_within_at.mono h.1 hst, differentiable_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩ lemma mdifferentiable_within_at_univ : mdifferentiable_within_at I I' f univ x ↔ mdifferentiable_at I I' f x := by simp only [mdifferentiable_within_at, mdifferentiable_at, continuous_within_at_univ] with mfld_simps lemma mdifferentiable_within_at_inter (ht : t ∈ 𝓝 x) : mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x := begin rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_preimage_inter_eq, differentiable_within_at_inter, continuous_within_at_inter ht], exact ext_chart_preimage_mem_nhds I x ht end lemma mdifferentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x := begin rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_preimage_inter_eq, differentiable_within_at_inter', continuous_within_at_inter' ht], exact ext_chart_preimage_mem_nhds_within I x ht end lemma mdifferentiable_at.mdifferentiable_within_at (h : mdifferentiable_at I I' f x) : mdifferentiable_within_at I I' f s x := mdifferentiable_within_at.mono (subset_univ _) (mdifferentiable_within_at_univ.2 h) lemma mdifferentiable_within_at.mdifferentiable_at (h : mdifferentiable_within_at I I' f s x) (hs : s ∈ 𝓝 x) : mdifferentiable_at I I' f x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, mdifferentiable_within_at_inter hs, mdifferentiable_within_at_univ] at h, end lemma mdifferentiable_on.mono (h : mdifferentiable_on I I' f t) (st : s ⊆ t) : mdifferentiable_on I I' f s := λx hx, (h x (st hx)).mono st lemma mdifferentiable_on_univ : mdifferentiable_on I I' f univ ↔ mdifferentiable I I' f := by { simp only [mdifferentiable_on, mdifferentiable_within_at_univ] with mfld_simps, refl } lemma mdifferentiable.mdifferentiable_on (h : mdifferentiable I I' f) : mdifferentiable_on I I' f s := (mdifferentiable_on_univ.2 h).mono (subset_univ _) lemma mdifferentiable_on_of_locally_mdifferentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ mdifferentiable_on I I' f (s ∩ u)) : mdifferentiable_on I I' f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (mdifferentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 (ht x ⟨xs, xt⟩) end include Is I's @[simp, mfld_simps] lemma mfderiv_within_univ : mfderiv_within I I' f univ = mfderiv I I' f := begin ext x : 1, simp only [mfderiv_within, mfderiv] with mfld_simps, rw mdifferentiable_within_at_univ end lemma mfderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_mdiff_within_at I s x) : mfderiv_within I I' f (s ∩ t) x = mfderiv_within I I' f s x := by rw [mfderiv_within, mfderiv_within, ext_chart_preimage_inter_eq, mdifferentiable_within_at_inter ht, fderiv_within_inter (ext_chart_preimage_mem_nhds I x ht) hs] omit Is I's /-! ### Deriving continuity from differentiability on manifolds -/ theorem has_mfderiv_within_at.continuous_within_at (h : has_mfderiv_within_at I I' f s x f') : continuous_within_at f s x := h.1 theorem has_mfderiv_at.continuous_at (h : has_mfderiv_at I I' f x f') : continuous_at f x := h.1 lemma mdifferentiable_within_at.continuous_within_at (h : mdifferentiable_within_at I I' f s x) : continuous_within_at f s x := h.1 lemma mdifferentiable_at.continuous_at (h : mdifferentiable_at I I' f x) : continuous_at f x := h.1 lemma mdifferentiable_on.continuous_on (h : mdifferentiable_on I I' f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma mdifferentiable.continuous (h : mdifferentiable I I' f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at include Is I's lemma tangent_map_within_subset {p : tangent_bundle I M} (st : s ⊆ t) (hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_within_at I I' f t p.1) : tangent_map_within I I' f s p = tangent_map_within I I' f t p := begin simp only [tangent_map_within] with mfld_simps, rw mfderiv_within_subset st hs h, end lemma tangent_map_within_univ : tangent_map_within I I' f univ = tangent_map I I' f := by { ext p : 1, simp only [tangent_map_within, tangent_map] with mfld_simps } lemma tangent_map_within_eq_tangent_map {p : tangent_bundle I M} (hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_at I I' f p.1) : tangent_map_within I I' f s p = tangent_map I I' f p := begin rw ← mdifferentiable_within_at_univ at h, rw ← tangent_map_within_univ, exact tangent_map_within_subset (subset_univ _) hs h, end @[simp, mfld_simps] lemma tangent_map_within_tangent_bundle_proj {p : tangent_bundle I M} : tangent_bundle.proj I' M' (tangent_map_within I I' f s p) = f (tangent_bundle.proj I M p) := rfl @[simp, mfld_simps] lemma tangent_map_within_proj {p : tangent_bundle I M} : (tangent_map_within I I' f s p).1 = f p.1 := rfl @[simp, mfld_simps] lemma tangent_map_tangent_bundle_proj {p : tangent_bundle I M} : tangent_bundle.proj I' M' (tangent_map I I' f p) = f (tangent_bundle.proj I M p) := rfl @[simp, mfld_simps] lemma tangent_map_proj {p : tangent_bundle I M} : (tangent_map I I' f p).1 = f p.1 := rfl omit Is I's /-! ### Congruence lemmas for derivatives on manifolds -/ lemma has_mfderiv_within_at.congr_of_eventually_eq (h : has_mfderiv_within_at I I' f s x f') (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_mfderiv_within_at I I' f₁ s x f' := begin refine ⟨continuous_within_at.congr_of_eventually_eq h.1 h₁ hx, _⟩, apply has_fderiv_within_at.congr_of_eventually_eq h.2, { have : (ext_chart_at I x).symm ⁻¹' {y | f₁ y = f y} ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := ext_chart_preimage_mem_nhds_within I x h₁, apply filter.mem_of_superset this (λy, _), simp only [hx] with mfld_simps {contextual := tt} }, { simp only [hx] with mfld_simps }, end lemma has_mfderiv_within_at.congr_mono (h : has_mfderiv_within_at I I' f s x f') (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_mfderiv_within_at I I' f₁ t x f' := (h.mono h₁).congr_of_eventually_eq (filter.mem_inf_of_right ht) hx lemma has_mfderiv_at.congr_of_eventually_eq (h : has_mfderiv_at I I' f x f') (h₁ : f₁ =ᶠ[𝓝 x] f) : has_mfderiv_at I I' f₁ x f' := begin rw ← has_mfderiv_within_at_univ at ⊢ h, apply h.congr_of_eventually_eq _ (mem_of_mem_nhds h₁ : _), rwa nhds_within_univ end include Is I's lemma mdifferentiable_within_at.congr_of_eventually_eq (h : mdifferentiable_within_at I I' f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x := (h.has_mfderiv_within_at.congr_of_eventually_eq h₁ hx).mdifferentiable_within_at variables (I I') lemma filter.eventually_eq.mdifferentiable_within_at_iff (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f s x ↔ mdifferentiable_within_at I I' f₁ s x := begin split, { assume h, apply h.congr_of_eventually_eq h₁ hx }, { assume h, apply h.congr_of_eventually_eq _ hx.symm, apply h₁.mono, intro y, apply eq.symm } end variables {I I'} lemma mdifferentiable_within_at.congr_mono (h : mdifferentiable_within_at I I' f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : mdifferentiable_within_at I I' f₁ t x := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx h₁).mdifferentiable_within_at lemma mdifferentiable_within_at.congr (h : mdifferentiable_within_at I I' f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx (subset.refl _)).mdifferentiable_within_at lemma mdifferentiable_on.congr_mono (h : mdifferentiable_on I I' f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : mdifferentiable_on I I' f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma mdifferentiable_at.congr_of_eventually_eq (h : mdifferentiable_at I I' f x) (hL : f₁ =ᶠ[𝓝 x] f) : mdifferentiable_at I I' f₁ x := ((h.has_mfderiv_at).congr_of_eventually_eq hL).mdifferentiable_at lemma mdifferentiable_within_at.mfderiv_within_congr_mono (h : mdifferentiable_within_at I I' f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_mdiff_within_at I t x) (h₁ : t ⊆ s) : mfderiv_within I I' f₁ t x = (mfderiv_within I I' f s x : _) := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at hs hx h₁).mfderiv_within hxt lemma filter.eventually_eq.mfderiv_within_eq (hs : unique_mdiff_within_at I s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) := begin by_cases h : mdifferentiable_within_at I I' f s x, { exact ((h.has_mfderiv_within_at).congr_of_eventually_eq hL hx).mfderiv_within hs }, { unfold mfderiv_within, rw [dif_neg h, dif_neg], rwa ← hL.mdifferentiable_within_at_iff I I' hx } end lemma mfderiv_within_congr (hs : unique_mdiff_within_at I s x) (hL : ∀ x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) := filter.eventually_eq.mfderiv_within_eq hs (filter.eventually_eq_of_mem (self_mem_nhds_within) hL) hx lemma tangent_map_within_congr (h : ∀ x ∈ s, f x = f₁ x) (p : tangent_bundle I M) (hp : p.1 ∈ s) (hs : unique_mdiff_within_at I s p.1) : tangent_map_within I I' f s p = tangent_map_within I I' f₁ s p := begin simp only [tangent_map_within, h p.fst hp, true_and, eq_self_iff_true, heq_iff_eq, sigma.mk.inj_iff], congr' 1, exact mfderiv_within_congr hs h (h _ hp) end lemma filter.eventually_eq.mfderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : mfderiv I I' f₁ x = (mfderiv I I' f x : _) := begin have A : f₁ x = f x := (mem_of_mem_nhds hL : _), rw [← mfderiv_within_univ, ← mfderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.mfderiv_within_eq (unique_mdiff_within_at_univ I) A end /-! ### Composition lemmas -/ omit Is I's lemma written_in_ext_chart_comp (h : continuous_within_at f s x) : {y | written_in_ext_chart_at I I'' x (g ∘ f) y = ((written_in_ext_chart_at I' I'' (f x) g) ∘ (written_in_ext_chart_at I I' x f)) y} ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := begin apply @filter.mem_of_superset _ _ ((f ∘ (ext_chart_at I x).symm)⁻¹' (ext_chart_at I' (f x)).source) _ (ext_chart_preimage_mem_nhds_within I x (h.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))), mfld_set_tac, end variable (x) include Is I's I''s theorem has_mfderiv_within_at.comp (hg : has_mfderiv_within_at I' I'' g u (f x) g') (hf : has_mfderiv_within_at I I' f s x f') (hst : s ⊆ f ⁻¹' u) : has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') := begin refine ⟨continuous_within_at.comp hg.1 hf.1 hst, _⟩, have A : has_fderiv_within_at ((written_in_ext_chart_at I' I'' (f x) g) ∘ (written_in_ext_chart_at I I' x f)) (continuous_linear_map.comp g' f' : E →L[𝕜] E'') ((ext_chart_at I x).symm ⁻¹' s ∩ range (I)) ((ext_chart_at I x) x), { have : (ext_chart_at I x).symm ⁻¹' (f ⁻¹' (ext_chart_at I' (f x)).source) ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := (ext_chart_preimage_mem_nhds_within I x (hf.1.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))), unfold has_mfderiv_within_at at *, rw [← has_fderiv_within_at_inter' this, ← ext_chart_preimage_inter_eq] at hf ⊢, have : written_in_ext_chart_at I I' x f ((ext_chart_at I x) x) = (ext_chart_at I' (f x)) (f x), by simp only with mfld_simps, rw ← this at hg, apply has_fderiv_within_at.comp ((ext_chart_at I x) x) hg.2 hf.2 _, assume y hy, simp only with mfld_simps at hy, have : f (((chart_at H x).symm : H → M) (I.symm y)) ∈ u := hst hy.1.1, simp only [hy, this] with mfld_simps }, apply A.congr_of_eventually_eq (written_in_ext_chart_comp hf.1), simp only with mfld_simps end /-- The chain rule. -/ theorem has_mfderiv_at.comp (hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_at I I' f x f') : has_mfderiv_at I I'' (g ∘ f) x (g'.comp f') := begin rw ← has_mfderiv_within_at_univ at *, exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ end theorem has_mfderiv_at.comp_has_mfderiv_within_at (hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_within_at I I' f s x f') : has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') := begin rw ← has_mfderiv_within_at_univ at *, exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ end lemma mdifferentiable_within_at.comp (hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x) (h : s ⊆ f ⁻¹' u) : mdifferentiable_within_at I I'' (g ∘ f) s x := begin rcases hf.2 with ⟨f', hf'⟩, have F : has_mfderiv_within_at I I' f s x f' := ⟨hf.1, hf'⟩, rcases hg.2 with ⟨g', hg'⟩, have G : has_mfderiv_within_at I' I'' g u (f x) g' := ⟨hg.1, hg'⟩, exact (has_mfderiv_within_at.comp x G F h).mdifferentiable_within_at end lemma mdifferentiable_at.comp (hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) : mdifferentiable_at I I'' (g ∘ f) x := (hg.has_mfderiv_at.comp x hf.has_mfderiv_at).mdifferentiable_at lemma mfderiv_within_comp (hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x) (h : s ⊆ f ⁻¹' u) (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I'' (g ∘ f) s x = (mfderiv_within I' I'' g u (f x)).comp (mfderiv_within I I' f s x) := begin apply has_mfderiv_within_at.mfderiv_within _ hxs, exact has_mfderiv_within_at.comp x hg.has_mfderiv_within_at hf.has_mfderiv_within_at h end lemma mfderiv_comp (hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) : mfderiv I I'' (g ∘ f) x = (mfderiv I' I'' g (f x)).comp (mfderiv I I' f x) := begin apply has_mfderiv_at.mfderiv, exact has_mfderiv_at.comp x hg.has_mfderiv_at hf.has_mfderiv_at end lemma mdifferentiable_on.comp (hg : mdifferentiable_on I' I'' g u) (hf : mdifferentiable_on I I' f s) (st : s ⊆ f ⁻¹' u) : mdifferentiable_on I I'' (g ∘ f) s := λx hx, mdifferentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma mdifferentiable.comp (hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) : mdifferentiable I I'' (g ∘ f) := λx, mdifferentiable_at.comp x (hg (f x)) (hf x) lemma tangent_map_within_comp_at (p : tangent_bundle I M) (hg : mdifferentiable_within_at I' I'' g u (f p.1)) (hf : mdifferentiable_within_at I I' f s p.1) (h : s ⊆ f ⁻¹' u) (hps : unique_mdiff_within_at I s p.1) : tangent_map_within I I'' (g ∘ f) s p = tangent_map_within I' I'' g u (tangent_map_within I I' f s p) := begin simp only [tangent_map_within] with mfld_simps, rw mfderiv_within_comp p.1 hg hf h hps, refl end lemma tangent_map_comp_at (p : tangent_bundle I M) (hg : mdifferentiable_at I' I'' g (f p.1)) (hf : mdifferentiable_at I I' f p.1) : tangent_map I I'' (g ∘ f) p = tangent_map I' I'' g (tangent_map I I' f p) := begin simp only [tangent_map] with mfld_simps, rw mfderiv_comp p.1 hg hf, refl end lemma tangent_map_comp (hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) : tangent_map I I'' (g ∘ f) = (tangent_map I' I'' g) ∘ (tangent_map I I' f) := by { ext p : 1, exact tangent_map_comp_at _ (hg _) (hf _) } end derivatives_properties section mfderiv_fderiv /-! ### Relations between vector space derivative and manifold derivative The manifold derivative `mfderiv`, when considered on the model vector space with its trivial manifold structure, coincides with the usual Frechet derivative `fderiv`. In this section, we prove this and related statements. -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {f : E → E'} {s : set E} {x : E} lemma unique_mdiff_within_at_iff_unique_diff_within_at : unique_mdiff_within_at (𝓘(𝕜, E)) s x ↔ unique_diff_within_at 𝕜 s x := by simp only [unique_mdiff_within_at] with mfld_simps alias unique_mdiff_within_at_iff_unique_diff_within_at ↔ unique_mdiff_within_at.unique_diff_within_at unique_diff_within_at.unique_mdiff_within_at lemma unique_mdiff_on_iff_unique_diff_on : unique_mdiff_on (𝓘(𝕜, E)) s ↔ unique_diff_on 𝕜 s := by simp [unique_mdiff_on, unique_diff_on, unique_mdiff_within_at_iff_unique_diff_within_at] alias unique_mdiff_on_iff_unique_diff_on ↔ unique_mdiff_on.unique_diff_on unique_diff_on.unique_mdiff_on @[simp, mfld_simps] lemma written_in_ext_chart_model_space : written_in_ext_chart_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) x f = f := rfl lemma has_mfderiv_within_at_iff_has_fderiv_within_at {f'} : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x f' ↔ has_fderiv_within_at f f' s x := by simpa only [has_mfderiv_within_at, and_iff_right_iff_imp] with mfld_simps using has_fderiv_within_at.continuous_within_at alias has_mfderiv_within_at_iff_has_fderiv_within_at ↔ has_mfderiv_within_at.has_fderiv_within_at has_fderiv_within_at.has_mfderiv_within_at lemma has_mfderiv_at_iff_has_fderiv_at {f'} : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x f' ↔ has_fderiv_at f f' x := by rw [← has_mfderiv_within_at_univ, has_mfderiv_within_at_iff_has_fderiv_within_at, has_fderiv_within_at_univ] alias has_mfderiv_at_iff_has_fderiv_at ↔ has_mfderiv_at.has_fderiv_at has_fderiv_at.has_mfderiv_at /-- For maps between vector spaces, `mdifferentiable_within_at` and `fdifferentiable_within_at` coincide -/ theorem mdifferentiable_within_at_iff_differentiable_within_at : mdifferentiable_within_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x ↔ differentiable_within_at 𝕜 f s x := begin simp only [mdifferentiable_within_at] with mfld_simps, exact ⟨λH, H.2, λH, ⟨H.continuous_within_at, H⟩⟩ end alias mdifferentiable_within_at_iff_differentiable_within_at ↔ mdifferentiable_within_at.differentiable_within_at differentiable_within_at.mdifferentiable_within_at /-- For maps between vector spaces, `mdifferentiable_at` and `differentiable_at` coincide -/ theorem mdifferentiable_at_iff_differentiable_at : mdifferentiable_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f x ↔ differentiable_at 𝕜 f x := begin simp only [mdifferentiable_at, differentiable_within_at_univ] with mfld_simps, exact ⟨λH, H.2, λH, ⟨H.continuous_at, H⟩⟩ end alias mdifferentiable_at_iff_differentiable_at ↔ mdifferentiable_at.differentiable_at differentiable_at.mdifferentiable_at /-- For maps between vector spaces, `mdifferentiable_on` and `differentiable_on` coincide -/ theorem mdifferentiable_on_iff_differentiable_on : mdifferentiable_on (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s ↔ differentiable_on 𝕜 f s := by simp only [mdifferentiable_on, differentiable_on, mdifferentiable_within_at_iff_differentiable_within_at] alias mdifferentiable_on_iff_differentiable_on ↔ mdifferentiable_on.differentiable_on differentiable_on.mdifferentiable_on /-- For maps between vector spaces, `mdifferentiable` and `differentiable` coincide -/ theorem mdifferentiable_iff_differentiable : mdifferentiable (𝓘(𝕜, E)) (𝓘(𝕜, E')) f ↔ differentiable 𝕜 f := by simp only [mdifferentiable, differentiable, mdifferentiable_at_iff_differentiable_at] alias mdifferentiable_iff_differentiable ↔ mdifferentiable.differentiable differentiable.mdifferentiable /-- For maps between vector spaces, `mfderiv_within` and `fderiv_within` coincide -/ @[simp] theorem mfderiv_within_eq_fderiv_within : mfderiv_within (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x = fderiv_within 𝕜 f s x := begin by_cases h : mdifferentiable_within_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x, { simp only [mfderiv_within, h, dif_pos] with mfld_simps }, { simp only [mfderiv_within, h, dif_neg, not_false_iff], rw [mdifferentiable_within_at_iff_differentiable_within_at] at h, exact (fderiv_within_zero_of_not_differentiable_within_at h).symm } end /-- For maps between vector spaces, `mfderiv` and `fderiv` coincide -/ @[simp] theorem mfderiv_eq_fderiv : mfderiv (𝓘(𝕜, E)) (𝓘(𝕜, E')) f x = fderiv 𝕜 f x := begin rw [← mfderiv_within_univ, ← fderiv_within_univ], exact mfderiv_within_eq_fderiv_within end end mfderiv_fderiv section specific_functions /-! ### Differentiability of specific functions -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] namespace continuous_linear_map variables (f : E →L[𝕜] E') {s : set E} {x : E} protected lemma has_mfderiv_within_at : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x f := f.has_fderiv_within_at.has_mfderiv_within_at protected lemma has_mfderiv_at : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x f := f.has_fderiv_at.has_mfderiv_at protected lemma mdifferentiable_within_at : mdifferentiable_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x := f.differentiable_within_at.mdifferentiable_within_at protected lemma mdifferentiable_on : mdifferentiable_on 𝓘(𝕜, E) 𝓘(𝕜, E') f s := f.differentiable_on.mdifferentiable_on protected lemma mdifferentiable_at : mdifferentiable_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x := f.differentiable_at.mdifferentiable_at protected lemma mdifferentiable : mdifferentiable 𝓘(𝕜, E) 𝓘(𝕜, E') f := f.differentiable.mdifferentiable lemma mfderiv_eq : mfderiv 𝓘(𝕜, E) 𝓘(𝕜, E') f x = f := f.has_mfderiv_at.mfderiv lemma mfderiv_within_eq (hs : unique_mdiff_within_at 𝓘(𝕜, E) s x) : mfderiv_within 𝓘(𝕜, E) 𝓘(𝕜, E') f s x = f := f.has_mfderiv_within_at.mfderiv_within hs end continuous_linear_map namespace continuous_linear_equiv variables (f : E ≃L[𝕜] E') {s : set E} {x : E} protected lemma has_mfderiv_within_at : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x (f : E →L[𝕜] E') := f.has_fderiv_within_at.has_mfderiv_within_at protected lemma has_mfderiv_at : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x (f : E →L[𝕜] E') := f.has_fderiv_at.has_mfderiv_at protected lemma mdifferentiable_within_at : mdifferentiable_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x := f.differentiable_within_at.mdifferentiable_within_at protected lemma mdifferentiable_on : mdifferentiable_on 𝓘(𝕜, E) 𝓘(𝕜, E') f s := f.differentiable_on.mdifferentiable_on protected lemma mdifferentiable_at : mdifferentiable_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x := f.differentiable_at.mdifferentiable_at protected lemma mdifferentiable : mdifferentiable 𝓘(𝕜, E) 𝓘(𝕜, E') f := f.differentiable.mdifferentiable lemma mfderiv_eq : mfderiv 𝓘(𝕜, E) 𝓘(𝕜, E') f x = (f : E →L[𝕜] E') := f.has_mfderiv_at.mfderiv lemma mfderiv_within_eq (hs : unique_mdiff_within_at 𝓘(𝕜, E) s x) : mfderiv_within 𝓘(𝕜, E) 𝓘(𝕜, E') f s x = (f : E →L[𝕜] E') := f.has_mfderiv_within_at.mfderiv_within hs end continuous_linear_equiv variables {s : set M} {x : M} section id /-! #### Identity -/ lemma has_mfderiv_at_id (x : M) : has_mfderiv_at I I (@_root_.id M) x (continuous_linear_map.id 𝕜 (tangent_space I x)) := begin refine ⟨continuous_id.continuous_at, _⟩, have : ∀ᶠ y in 𝓝[range I] ((ext_chart_at I x) x), ((ext_chart_at I x) ∘ (ext_chart_at I x).symm) y = id y, { apply filter.mem_of_superset (ext_chart_at_target_mem_nhds_within I x), mfld_set_tac }, apply has_fderiv_within_at.congr_of_eventually_eq (has_fderiv_within_at_id _ _) this, simp only with mfld_simps end theorem has_mfderiv_within_at_id (s : set M) (x : M) : has_mfderiv_within_at I I (@_root_.id M) s x (continuous_linear_map.id 𝕜 (tangent_space I x)) := (has_mfderiv_at_id I x).has_mfderiv_within_at lemma mdifferentiable_at_id : mdifferentiable_at I I (@_root_.id M) x := (has_mfderiv_at_id I x).mdifferentiable_at lemma mdifferentiable_within_at_id : mdifferentiable_within_at I I (@_root_.id M) s x := (mdifferentiable_at_id I).mdifferentiable_within_at lemma mdifferentiable_id : mdifferentiable I I (@_root_.id M) := λx, mdifferentiable_at_id I lemma mdifferentiable_on_id : mdifferentiable_on I I (@_root_.id M) s := (mdifferentiable_id I).mdifferentiable_on @[simp, mfld_simps] lemma mfderiv_id : mfderiv I I (@_root_.id M) x = (continuous_linear_map.id 𝕜 (tangent_space I x)) := has_mfderiv_at.mfderiv (has_mfderiv_at_id I x) lemma mfderiv_within_id (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I (@_root_.id M) s x = (continuous_linear_map.id 𝕜 (tangent_space I x)) := begin rw mdifferentiable.mfderiv_within (mdifferentiable_at_id I) hxs, exact mfderiv_id I end @[simp, mfld_simps] lemma tangent_map_id : tangent_map I I (id : M → M) = id := by { ext1 ⟨x, v⟩, simp [tangent_map] } lemma tangent_map_within_id {p : tangent_bundle I M} (hs : unique_mdiff_within_at I s (tangent_bundle.proj I M p)) : tangent_map_within I I (id : M → M) s p = p := begin simp only [tangent_map_within, id.def], rw mfderiv_within_id, { rcases p, refl }, { exact hs } end end id section const /-! #### Constants -/ variables {c : M'} lemma has_mfderiv_at_const (c : M') (x : M) : has_mfderiv_at I I' (λy : M, c) x (0 : tangent_space I x →L[𝕜] tangent_space I' c) := begin refine ⟨continuous_const.continuous_at, _⟩, simp only [written_in_ext_chart_at, (∘), has_fderiv_within_at_const] end theorem has_mfderiv_within_at_const (c : M') (s : set M) (x : M) : has_mfderiv_within_at I I' (λy : M, c) s x (0 : tangent_space I x →L[𝕜] tangent_space I' c) := (has_mfderiv_at_const I I' c x).has_mfderiv_within_at lemma mdifferentiable_at_const : mdifferentiable_at I I' (λy : M, c) x := (has_mfderiv_at_const I I' c x).mdifferentiable_at lemma mdifferentiable_within_at_const : mdifferentiable_within_at I I' (λy : M, c) s x := (mdifferentiable_at_const I I').mdifferentiable_within_at lemma mdifferentiable_const : mdifferentiable I I' (λy : M, c) := λx, mdifferentiable_at_const I I' lemma mdifferentiable_on_const : mdifferentiable_on I I' (λy : M, c) s := (mdifferentiable_const I I').mdifferentiable_on @[simp, mfld_simps] lemma mfderiv_const : mfderiv I I' (λy : M, c) x = (0 : tangent_space I x →L[𝕜] tangent_space I' c) := has_mfderiv_at.mfderiv (has_mfderiv_at_const I I' c x) lemma mfderiv_within_const (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' (λy : M, c) s x = (0 : tangent_space I x →L[𝕜] tangent_space I' c) := (has_mfderiv_within_at_const _ _ _ _ _).mfderiv_within hxs end const namespace model_with_corners /-! #### Model with corners -/ protected lemma has_mfderiv_at {x} : has_mfderiv_at I 𝓘(𝕜, E) I x (continuous_linear_map.id _ _) := ⟨I.continuous_at, (has_fderiv_within_at_id _ _).congr' I.right_inv_on (mem_range_self _)⟩ protected lemma has_mfderiv_within_at {s x} : has_mfderiv_within_at I 𝓘(𝕜, E) I s x (continuous_linear_map.id _ _) := I.has_mfderiv_at.has_mfderiv_within_at protected lemma mdifferentiable_within_at {s x} : mdifferentiable_within_at I 𝓘(𝕜, E) I s x := I.has_mfderiv_within_at.mdifferentiable_within_at protected lemma mdifferentiable_at {x} : mdifferentiable_at I 𝓘(𝕜, E) I x := I.has_mfderiv_at.mdifferentiable_at protected lemma mdifferentiable_on {s} : mdifferentiable_on I 𝓘(𝕜, E) I s := λ x hx, I.mdifferentiable_within_at protected lemma mdifferentiable : mdifferentiable I (𝓘(𝕜, E)) I := λ x, I.mdifferentiable_at lemma has_mfderiv_within_at_symm {x} (hx : x ∈ range I) : has_mfderiv_within_at 𝓘(𝕜, E) I I.symm (range I) x (continuous_linear_map.id _ _) := ⟨I.continuous_within_at_symm, (has_fderiv_within_at_id _ _).congr' (λ y hy, I.right_inv_on hy.1) ⟨hx, mem_range_self _⟩⟩ lemma mdifferentiable_on_symm : mdifferentiable_on (𝓘(𝕜, E)) I I.symm (range I) := λ x hx, (I.has_mfderiv_within_at_symm hx).mdifferentiable_within_at end model_with_corners section charts variable {e : local_homeomorph M H} lemma mdifferentiable_at_atlas (h : e ∈ atlas H M) {x : M} (hx : x ∈ e.source) : mdifferentiable_at I I e x := begin refine ⟨(e.continuous_on x hx).continuous_at (is_open.mem_nhds e.open_source hx), _⟩, have mem : I ((chart_at H x : M → H) x) ∈ I.symm ⁻¹' ((chart_at H x).symm ≫ₕ e).source ∩ range I, by simp only [hx] with mfld_simps, have : (chart_at H x).symm.trans e ∈ times_cont_diff_groupoid ∞ I := has_groupoid.compatible _ (chart_mem_atlas H x) h, have A : times_cont_diff_on 𝕜 ∞ (I ∘ ((chart_at H x).symm.trans e) ∘ I.symm) (I.symm ⁻¹' ((chart_at H x).symm.trans e).source ∩ range I) := this.1, have B := A.differentiable_on le_top (I ((chart_at H x : M → H) x)) mem, simp only with mfld_simps at B, rw [inter_comm, differentiable_within_at_inter] at B, { simpa only with mfld_simps }, { apply is_open.mem_nhds ((local_homeomorph.open_source _).preimage I.continuous_symm) mem.1 } end lemma mdifferentiable_on_atlas (h : e ∈ atlas H M) : mdifferentiable_on I I e e.source := λx hx, (mdifferentiable_at_atlas I h hx).mdifferentiable_within_at lemma mdifferentiable_at_atlas_symm (h : e ∈ atlas H M) {x : H} (hx : x ∈ e.target) : mdifferentiable_at I I e.symm x := begin refine ⟨(e.continuous_on_symm x hx).continuous_at (is_open.mem_nhds e.open_target hx), _⟩, have mem : I x ∈ I.symm ⁻¹' (e.symm ≫ₕ chart_at H (e.symm x)).source ∩ range (I), by simp only [hx] with mfld_simps, have : e.symm.trans (chart_at H (e.symm x)) ∈ times_cont_diff_groupoid ∞ I := has_groupoid.compatible _ h (chart_mem_atlas H _), have A : times_cont_diff_on 𝕜 ∞ (I ∘ (e.symm.trans (chart_at H (e.symm x))) ∘ I.symm) (I.symm ⁻¹' (e.symm.trans (chart_at H (e.symm x))).source ∩ range I) := this.1, have B := A.differentiable_on le_top (I x) mem, simp only with mfld_simps at B, rw [inter_comm, differentiable_within_at_inter] at B, { simpa only with mfld_simps }, { apply (is_open.mem_nhds ((local_homeomorph.open_source _).preimage I.continuous_symm) mem.1) } end lemma mdifferentiable_on_atlas_symm (h : e ∈ atlas H M) : mdifferentiable_on I I e.symm e.target := λx hx, (mdifferentiable_at_atlas_symm I h hx).mdifferentiable_within_at lemma mdifferentiable_of_mem_atlas (h : e ∈ atlas H M) : e.mdifferentiable I I := ⟨mdifferentiable_on_atlas I h, mdifferentiable_on_atlas_symm I h⟩ lemma mdifferentiable_chart (x : M) : (chart_at H x).mdifferentiable I I := mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _) /-- The derivative of the chart at a base point is the chart of the tangent bundle, composed with the identification between the tangent bundle of the model space and the product space. -/ lemma tangent_map_chart {p q : tangent_bundle I M} (h : q.1 ∈ (chart_at H p.1).source) : tangent_map I I (chart_at H p.1) q = (equiv.sigma_equiv_prod _ _).symm ((chart_at (model_prod H E) p : tangent_bundle I M → model_prod H E) q) := begin dsimp [tangent_map], rw mdifferentiable_at.mfderiv, { refl }, { exact mdifferentiable_at_atlas _ (chart_mem_atlas _ _) h } end /-- The derivative of the inverse of the chart at a base point is the inverse of the chart of the tangent bundle, composed with the identification between the tangent bundle of the model space and the product space. -/ lemma tangent_map_chart_symm {p : tangent_bundle I M} {q : tangent_bundle I H} (h : q.1 ∈ (chart_at H p.1).target) : tangent_map I I (chart_at H p.1).symm q = ((chart_at (model_prod H E) p).symm : model_prod H E → tangent_bundle I M) ((equiv.sigma_equiv_prod H E) q) := begin dsimp only [tangent_map], rw mdifferentiable_at.mfderiv (mdifferentiable_at_atlas_symm _ (chart_mem_atlas _ _) h), -- a trivial instance is needed after the rewrite, handle it right now. rotate, { apply_instance }, simp only [chart_at, basic_smooth_bundle_core.chart, subtype.coe_mk, tangent_bundle_core, h, basic_smooth_bundle_core.to_topological_fiber_bundle_core, equiv.sigma_equiv_prod_apply] with mfld_simps, end end charts end specific_functions /-! ### Differentiable local homeomorphisms -/ namespace local_homeomorph.mdifferentiable variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] {e : local_homeomorph M M'} (he : e.mdifferentiable I I') {e' : local_homeomorph M' M''} include he lemma symm : e.symm.mdifferentiable I' I := ⟨he.2, he.1⟩ protected lemma mdifferentiable_at {x : M} (hx : x ∈ e.source) : mdifferentiable_at I I' e x := (he.1 x hx).mdifferentiable_at (is_open.mem_nhds e.open_source hx) lemma mdifferentiable_at_symm {x : M'} (hx : x ∈ e.target) : mdifferentiable_at I' I e.symm x := (he.2 x hx).mdifferentiable_at (is_open.mem_nhds e.open_target hx) variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M'] [smooth_manifold_with_corners I'' M''] lemma symm_comp_deriv {x : M} (hx : x ∈ e.source) : (mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) = continuous_linear_map.id 𝕜 (tangent_space I x) := begin have : (mfderiv I I (e.symm ∘ e) x) = (mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) := mfderiv_comp x (he.mdifferentiable_at_symm (e.map_source hx)) (he.mdifferentiable_at hx), rw ← this, have : mfderiv I I (_root_.id : M → M) x = continuous_linear_map.id _ _ := mfderiv_id I, rw ← this, apply filter.eventually_eq.mfderiv_eq, have : e.source ∈ 𝓝 x := is_open.mem_nhds e.open_source hx, exact filter.mem_of_superset this (by mfld_set_tac) end lemma comp_symm_deriv {x : M'} (hx : x ∈ e.target) : (mfderiv I I' e (e.symm x)).comp (mfderiv I' I e.symm x) = continuous_linear_map.id 𝕜 (tangent_space I' x) := he.symm.symm_comp_deriv hx /-- The derivative of a differentiable local homeomorphism, as a continuous linear equivalence between the tangent spaces at `x` and `e x`. -/ protected def mfderiv {x : M} (hx : x ∈ e.source) : tangent_space I x ≃L[𝕜] tangent_space I' (e x) := { inv_fun := (mfderiv I' I e.symm (e x)), continuous_to_fun := (mfderiv I I' e x).cont, continuous_inv_fun := (mfderiv I' I e.symm (e x)).cont, left_inv := λy, begin have : (continuous_linear_map.id _ _ : tangent_space I x →L[𝕜] tangent_space I x) y = y := rfl, conv_rhs { rw [← this, ← he.symm_comp_deriv hx] }, refl end, right_inv := λy, begin have : (continuous_linear_map.id 𝕜 _ : tangent_space I' (e x) →L[𝕜] tangent_space I' (e x)) y = y := rfl, conv_rhs { rw [← this, ← he.comp_symm_deriv (e.map_source hx)] }, rw e.left_inv hx, refl end, .. mfderiv I I' e x } lemma mfderiv_bijective {x : M} (hx : x ∈ e.source) : function.bijective (mfderiv I I' e x) := (he.mfderiv hx).bijective lemma mfderiv_injective {x : M} (hx : x ∈ e.source) : function.injective (mfderiv I I' e x) := (he.mfderiv hx).injective lemma mfderiv_surjective {x : M} (hx : x ∈ e.source) : function.surjective (mfderiv I I' e x) := (he.mfderiv hx).surjective lemma ker_mfderiv_eq_bot {x : M} (hx : x ∈ e.source) : (mfderiv I I' e x).ker = ⊥ := (he.mfderiv hx).to_linear_equiv.ker lemma range_mfderiv_eq_top {x : M} (hx : x ∈ e.source) : (mfderiv I I' e x).range = ⊤ := (he.mfderiv hx).to_linear_equiv.range lemma range_mfderiv_eq_univ {x : M} (hx : x ∈ e.source) : range (mfderiv I I' e x) = univ := (he.mfderiv_surjective hx).range_eq lemma trans (he': e'.mdifferentiable I' I'') : (e.trans e').mdifferentiable I I'' := begin split, { assume x hx, simp only with mfld_simps at hx, exact ((he'.mdifferentiable_at hx.2).comp _ (he.mdifferentiable_at hx.1)).mdifferentiable_within_at }, { assume x hx, simp only with mfld_simps at hx, exact ((he.symm.mdifferentiable_at hx.2).comp _ (he'.symm.mdifferentiable_at hx.1)).mdifferentiable_within_at } end end local_homeomorph.mdifferentiable /-! ### Differentiability of `ext_chart_at` -/ section ext_chart_at variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {s : set M} {x y : M} lemma has_mfderiv_at_ext_chart_at (h : y ∈ (chart_at H x).source) : has_mfderiv_at I 𝓘(𝕜, E) (ext_chart_at I x) y (mfderiv I I (chart_at H x) y : _) := I.has_mfderiv_at.comp y ((mdifferentiable_chart I x).mdifferentiable_at h).has_mfderiv_at lemma has_mfderiv_within_at_ext_chart_at (h : y ∈ (chart_at H x).source) : has_mfderiv_within_at I 𝓘(𝕜, E) (ext_chart_at I x) s y (mfderiv I I (chart_at H x) y : _) := (has_mfderiv_at_ext_chart_at I h).has_mfderiv_within_at lemma mdifferentiable_at_ext_chart_at (h : y ∈ (chart_at H x).source) : mdifferentiable_at I 𝓘(𝕜, E) (ext_chart_at I x) y := (has_mfderiv_at_ext_chart_at I h).mdifferentiable_at lemma mdifferentiable_on_ext_chart_at : mdifferentiable_on I 𝓘(𝕜, E) (ext_chart_at I x) (chart_at H x).source := λ y hy, (has_mfderiv_within_at_ext_chart_at I hy).mdifferentiable_within_at end ext_chart_at /-! ### Unique derivative sets in manifolds -/ section unique_mdiff variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {s : set M} /-- If a set has the unique differential property, then its image under a local diffeomorphism also has the unique differential property. -/ lemma unique_mdiff_on.unique_mdiff_on_preimage [smooth_manifold_with_corners I' M'] (hs : unique_mdiff_on I s) {e : local_homeomorph M M'} (he : e.mdifferentiable I I') : unique_mdiff_on I' (e.target ∩ e.symm ⁻¹' s) := begin /- Start from a point `x` in the image, and let `z` be its preimage. Then the unique derivative property at `x` is expressed through `ext_chart_at I' x`, and the unique derivative property at `z` is expressed through `ext_chart_at I z`. We will argue that the composition of these two charts with `e` is a local diffeomorphism in vector spaces, and therefore preserves the unique differential property thanks to lemma `has_fderiv_within_at.unique_diff_within_at`, saying that a differentiable function with onto derivative preserves the unique derivative property.-/ assume x hx, let z := e.symm x, have z_source : z ∈ e.source, by simp only [hx.1] with mfld_simps, have zx : e z = x, by simp only [z, hx.1] with mfld_simps, let F := ext_chart_at I z, -- the unique derivative property at `z` is expressed through its preferred chart, -- that we call `F`. have B : unique_diff_within_at 𝕜 (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z), { have : unique_mdiff_within_at I s z := hs _ hx.2, have S : e.source ∩ e ⁻¹' ((ext_chart_at I' x).source) ∈ 𝓝 z, { apply is_open.mem_nhds, apply e.continuous_on.preimage_open_of_open e.open_source (ext_chart_at_open_source I' x), simp only [z_source, zx] with mfld_simps }, have := this.inter S, rw [unique_mdiff_within_at_iff] at this, exact this }, -- denote by `G` the change of coordinate, i.e., the composition of the two extended charts and -- of `e` let G := F.symm ≫ e.to_local_equiv ≫ (ext_chart_at I' x), -- `G` is differentiable have Diff : ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).mdifferentiable I I', { have A := mdifferentiable_of_mem_atlas I (chart_mem_atlas H z), have B := mdifferentiable_of_mem_atlas I' (chart_mem_atlas H' x), exact A.symm.trans (he.trans B) }, have Mmem : (chart_at H z : M → H) z ∈ ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).source, by simp only [z_source, zx] with mfld_simps, have A : differentiable_within_at 𝕜 G (range I) (F z), { refine (Diff.mdifferentiable_at Mmem).2.congr (λp hp, _) _; simp only [G, F] with mfld_simps }, -- let `G'` be its derivative let G' := fderiv_within 𝕜 G (range I) (F z), have D₁ : has_fderiv_within_at G G' (range I) (F z) := A.has_fderiv_within_at, have D₂ : has_fderiv_within_at G G' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z) := D₁.mono (by mfld_set_tac), -- The derivative `G'` is onto, as it is the derivative of a local diffeomorphism, the composition -- of the two charts and of `e`. have C : dense_range (G' : E → E'), { have : G' = mfderiv I I' ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)) ((chart_at H z : M → H) z), by { rw (Diff.mdifferentiable_at Mmem).mfderiv, refl }, rw this, exact (Diff.mfderiv_surjective Mmem).dense_range }, -- key step: thanks to what we have proved about it, `G` preserves the unique derivative property have key : unique_diff_within_at 𝕜 (G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target)) (G (F z)) := D₂.unique_diff_within_at B C, have : G (F z) = (ext_chart_at I' x) x, by { dsimp [G, F], simp only [hx.1] with mfld_simps }, rw this at key, apply key.mono, show G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) ⊆ (ext_chart_at I' x).symm ⁻¹' e.target ∩ (ext_chart_at I' x).symm ⁻¹' (e.symm ⁻¹' s) ∩ range (I'), rw image_subset_iff, mfld_set_tac end /-- If a set in a manifold has the unique derivative property, then its pullback by any extended chart, in the vector space, also has the unique derivative property. -/ lemma unique_mdiff_on.unique_diff_on_target_inter (hs : unique_mdiff_on I s) (x : M) : unique_diff_on 𝕜 ((ext_chart_at I x).target ∩ ((ext_chart_at I x).symm ⁻¹' s)) := begin -- this is just a reformulation of `unique_mdiff_on.unique_mdiff_on_preimage`, using as `e` -- the local chart at `x`. assume z hz, simp only with mfld_simps at hz, have : (chart_at H x).mdifferentiable I I := mdifferentiable_chart _ _, have T := (hs.unique_mdiff_on_preimage this) (I.symm z), simp only [hz.left.left, hz.left.right, hz.right, unique_mdiff_within_at] with mfld_simps at ⊢ T, convert T using 1, rw @preimage_comp _ _ _ _ (chart_at H x).symm, mfld_set_tac end /-- When considering functions between manifolds, this statement shows up often. It entails the unique differential of the pullback in extended charts of the set where the function can be read in the charts. -/ lemma unique_mdiff_on.unique_diff_on_inter_preimage (hs : unique_mdiff_on I s) (x : M) (y : M') {f : M → M'} (hf : continuous_on f s) : unique_diff_on 𝕜 ((ext_chart_at I x).target ∩ ((ext_chart_at I x).symm ⁻¹' (s ∩ f⁻¹' (ext_chart_at I' y).source))) := begin have : unique_mdiff_on I (s ∩ f ⁻¹' (ext_chart_at I' y).source), { assume z hz, apply (hs z hz.1).inter', apply (hf z hz.1).preimage_mem_nhds_within, exact is_open.mem_nhds (ext_chart_at_open_source I' y) hz.2 }, exact this.unique_diff_on_target_inter _ end variables {F : Type*} [normed_group F] [normed_space 𝕜 F] (Z : basic_smooth_bundle_core I M F) /-- In a smooth fiber bundle constructed from core, the preimage under the projection of a set with unique differential in the basis also has unique differential. -/ lemma unique_mdiff_on.smooth_bundle_preimage (hs : unique_mdiff_on I s) : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (Z.to_topological_fiber_bundle_core.proj ⁻¹' s) := begin /- Using a chart (and the fact that unique differentiability is invariant under charts), we reduce the situation to the model space, where we can use the fact that products respect unique differentiability. -/ assume p hp, replace hp : p.fst ∈ s, by simpa only with mfld_simps using hp, let e₀ := chart_at H p.1, let e := chart_at (model_prod H F) p, -- It suffices to prove unique differentiability in a chart suffices h : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (e.target ∩ e.symm⁻¹' (Z.to_topological_fiber_bundle_core.proj ⁻¹' s)), { have A : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (e.symm.target ∩ e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (Z.to_topological_fiber_bundle_core.proj ⁻¹' s))), { apply h.unique_mdiff_on_preimage, exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)).symm, apply_instance }, have : p ∈ e.symm.target ∩ e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (Z.to_topological_fiber_bundle_core.proj ⁻¹' s)), by simp only [e, hp] with mfld_simps, apply (A _ this).mono, assume q hq, simp only [e, local_homeomorph.left_inv _ hq.1] with mfld_simps at hq, simp only [hq] with mfld_simps }, -- rewrite the relevant set in the chart as a direct product have : (λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' e.target ∩ (λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' (e.symm ⁻¹' (sigma.fst ⁻¹' s)) ∩ ((range I).prod univ) = set.prod (I.symm ⁻¹' (e₀.target ∩ e₀.symm⁻¹' s) ∩ range I) univ, by mfld_set_tac, assume q hq, replace hq : q.1 ∈ (chart_at H p.1).target ∧ ((chart_at H p.1).symm : H → M) q.1 ∈ s, by simpa only with mfld_simps using hq, simp only [unique_mdiff_within_at, model_with_corners.prod, preimage_inter, this] with mfld_simps, -- apply unique differentiability of products to conclude apply unique_diff_on.prod _ unique_diff_on_univ, { simp only [hq] with mfld_simps }, { assume x hx, have A : unique_mdiff_on I (e₀.target ∩ e₀.symm⁻¹' s), { apply hs.unique_mdiff_on_preimage, exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)), apply_instance }, simp only [unique_mdiff_on, unique_mdiff_within_at, preimage_inter] with mfld_simps at A, have B := A (I.symm x) hx.1.1 hx.1.2, rwa [← preimage_inter, model_with_corners.right_inv _ hx.2] at B } end lemma unique_mdiff_on.tangent_bundle_proj_preimage (hs : unique_mdiff_on I s): unique_mdiff_on I.tangent ((tangent_bundle.proj I M) ⁻¹' s) := hs.smooth_bundle_preimage _ end unique_mdiff
6584292bec6fb7169f4dff56bf4b759296d6e67b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/matrix/charpoly/basic.lean
07b454de95dd08e53bb9050519312c788823fd2e
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
4,502
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import linear_algebra.matrix.adjugate import ring_theory.matrix_algebra import ring_theory.polynomial_algebra import tactic.apply_fun import tactic.squeeze /-! # Characteristic polynomials and the Cayley-Hamilton theorem We define characteristic polynomials of matrices and prove the Cayley–Hamilton theorem over arbitrary commutative rings. See the file `matrix/charpoly/coeff` for corollaries of this theorem. ## Main definitions * `matrix.charpoly` is the characteristic polynomial of a matrix. ## Implementation details We follow a nice proof from http://drorbn.net/AcademicPensieve/2015-12/CayleyHamilton.pdf -/ noncomputable theory universes u v w open polynomial matrix open_locale big_operators polynomial variables {R : Type u} [comm_ring R] variables {n : Type w} [decidable_eq n] [fintype n] open finset /-- The "characteristic matrix" of `M : matrix n n R` is the matrix of polynomials $t I - M$. The determinant of this matrix is the characteristic polynomial. -/ def charmatrix (M : matrix n n R) : matrix n n R[X] := matrix.scalar n (X : R[X]) - (C : R →+* R[X]).map_matrix M lemma charmatrix_apply (M : matrix n n R) (i j : n) : charmatrix M i j = X * (1 : matrix n n R[X]) i j - C (M i j) := rfl @[simp] lemma charmatrix_apply_eq (M : matrix n n R) (i : n) : charmatrix M i i = (X : R[X]) - C (M i i) := by simp only [charmatrix, sub_left_inj, pi.sub_apply, scalar_apply_eq, ring_hom.map_matrix_apply, map_apply, dmatrix.sub_apply] @[simp] lemma charmatrix_apply_ne (M : matrix n n R) (i j : n) (h : i ≠ j) : charmatrix M i j = - C (M i j) := by simp only [charmatrix, pi.sub_apply, scalar_apply_ne _ _ _ h, zero_sub, ring_hom.map_matrix_apply, map_apply, dmatrix.sub_apply] lemma mat_poly_equiv_charmatrix (M : matrix n n R) : mat_poly_equiv (charmatrix M) = X - C M := begin ext k i j, simp only [mat_poly_equiv_coeff_apply, coeff_sub, pi.sub_apply], by_cases h : i = j, { subst h, rw [charmatrix_apply_eq, coeff_sub], simp only [coeff_X, coeff_C], split_ifs; simp, }, { rw [charmatrix_apply_ne _ _ _ h, coeff_X, coeff_neg, coeff_C, coeff_C], split_ifs; simp [h], } end lemma charmatrix_reindex {m : Type v} [decidable_eq m] [fintype m] (e : n ≃ m) (M : matrix n n R) : charmatrix (reindex e e M) = reindex e e (charmatrix M) := begin ext i j x, by_cases h : i = j, all_goals { simp [h] } end /-- The characteristic polynomial of a matrix `M` is given by $\det (t I - M)$. -/ def matrix.charpoly (M : matrix n n R) : R[X] := (charmatrix M).det lemma matrix.charpoly_reindex {m : Type v} [decidable_eq m] [fintype m] (e : n ≃ m) (M : matrix n n R) : (reindex e e M).charpoly = M.charpoly := begin unfold matrix.charpoly, rw [charmatrix_reindex, matrix.det_reindex_self] end /-- The **Cayley-Hamilton Theorem**, that the characteristic polynomial of a matrix, applied to the matrix itself, is zero. This holds over any commutative ring. See `linear_map.aeval_self_charpoly` for the equivalent statement about endomorphisms. -/ -- This proof follows http://drorbn.net/AcademicPensieve/2015-12/CayleyHamilton.pdf theorem matrix.aeval_self_charpoly (M : matrix n n R) : aeval M M.charpoly = 0 := begin -- We begin with the fact $χ_M(t) I = adjugate (t I - M) * (t I - M)$, -- as an identity in `matrix n n R[X]`. have h : M.charpoly • (1 : matrix n n R[X]) = adjugate (charmatrix M) * (charmatrix M) := (adjugate_mul _).symm, -- Using the algebra isomorphism `matrix n n R[X] ≃ₐ[R] polynomial (matrix n n R)`, -- we have the same identity in `polynomial (matrix n n R)`. apply_fun mat_poly_equiv at h, simp only [mat_poly_equiv.map_mul, mat_poly_equiv_charmatrix] at h, -- Because the coefficient ring `matrix n n R` is non-commutative, -- evaluation at `M` is not multiplicative. -- However, any polynomial which is a product of the form $N * (t I - M)$ -- is sent to zero, because the evaluation function puts the polynomial variable -- to the right of any coefficients, so everything telescopes. apply_fun (λ p, p.eval M) at h, rw eval_mul_X_sub_C at h, -- Now $χ_M (t) I$, when thought of as a polynomial of matrices -- and evaluated at some `N` is exactly $χ_M (N)$. rw [mat_poly_equiv_smul_one, eval_map] at h, -- Thus we have $χ_M(M) = 0$, which is the desired result. exact h, end
64674a0db99f400f6d12e29b5e852636b99d8ed4
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/sheaves/covering/covering_on_basis.lean
cd9750e9a443a8a9b52603dade0391824515135b
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
1,538
lean
/- Same as covering but the Ui's are elements of the basis and such that Ui ∩ Uj (not necessarily in the basis) is covered by Uijk's all in the basis. -/ import topology.basic import to_mathlib.opens import sheaves.covering.covering universes u v open topological_space lattice section covering_on_basis parameters {α : Type u} [topological_space α] parameters {B : set (opens α)} [HB : opens.is_basis B] -- Open cover for basis. structure covering_basis (U : opens α) extends covering U := {Iij : γ → γ → Type v } (Uijks : Π (i j), Iij i j → opens α) (BUis : ∀ i, Uis i ∈ B) (BUijks : ∀ i j k, Uijks i j k ∈ B) (Hintercov : ∀ i j, ⋃ (Uijks i j) = Uis i ∩ Uis j) -- If ⋃ Uijk = Ui ∩ Uj then for all k, Uijk ⊆ Ui ∩ Uj. lemma subset_covering_basis {U : opens α} {OC : covering_basis U} : ∀ i j k, OC.Uijks i j k ⊆ OC.Uis i ∩ OC.Uis j := λ i j k x, (OC.Hintercov i j) ▸ opens_supr_mem (OC.Uijks i j) k x -- If ⋃ Uijk = Ui ∩ Uj then for all k, Uijk ⊆ Ui. lemma subset_covering_basis_inter_left {U : opens α} {OC : covering_basis U} : ∀ i j k, OC.Uijks i j k ⊆ OC.Uis i := λ i j k, set.subset.trans (subset_covering_basis i j k) (set.inter_subset_left _ _) -- If ⋃ Uijk = Ui ∩ Uj then for all k, Uijk ⊆ Uj. lemma subset_covering_basis_inter_right {U : opens α} {OC : covering_basis U} : ∀ i j k, OC.Uijks i j k ⊆ OC.Uis j := λ i j k, set.subset.trans (subset_covering_basis i j k) (set.inter_subset_right _ _) end covering_on_basis
d2a55db8c5dbb9fafd5785a2d8f05e0a336fcf02
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_851.lean
7e3c28c00f6ddb83040e859d3d4bf566a7b922ac
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
146
lean
import algebra.ring namespace my_ring variables {R : Type*} [ring R] -- BEGIN theorem self_sub (a : R) : a - a = 0 := sorry -- END end my_ring
047d4ef6279ed5dbcddfd018e7f76dcf77ae079e
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/util.lean
bca0cb1d826b1024dda93fbad1d932f783773afe
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
801
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.string.basic universes u v /- debugging helper functions -/ @[extern cpp inline "lean::dbg_trace(#2, #3)"] def dbgTrace {α : Type u} (s : String) (f : Unit → α) : α := f () /- Display the given message if `a` is shared, that is, RC(a) > 1 -/ @[extern cpp inline "lean::dbg_trace_if_shared(#2, #3)"] def dbgTraceIfShared {α : Type u} (s : String) (a : α) : α := a @[extern cpp inline "lean::dbg_sleep(#2, #3)"] def dbgSleep {α : Type u} (ms : UInt32) (f : Unit → α) : α := f () @[extern cpp inline "#4"] unsafe def unsafeCast {α : Type u} {β : Type v} [Inhabited β] (a : α) : β := default _
cb6c57cf5a117a02e36d4b68d5dcfa5048db74da
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/data/fin/basic.lean
673d1b6ca566a1f4ec11acb83711783292b4e624
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,536
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat.basic open nat /-- `fin n` is the subtype of `ℕ` consisting of natural numbers strictly smaller than `n`. -/ def fin (n : ℕ) := {i : ℕ // i < n} namespace fin /-- Backwards-compatible constructor for `fin n`. -/ def mk {n : ℕ} (i) (h) : fin n := ⟨i, h⟩ protected def lt {n} (a b : fin n) : Prop := a.val < b.val protected def le {n} (a b : fin n) : Prop := a.val ≤ b.val instance {n} : has_lt (fin n) := ⟨fin.lt⟩ instance {n} : has_le (fin n) := ⟨fin.le⟩ instance decidable_lt {n} (a b : fin n) : decidable (a < b) := nat.decidable_lt _ _ instance decidable_le {n} (a b : fin n) : decidable (a ≤ b) := nat.decidable_le _ _ def {u} elim0 {α : fin 0 → Sort u} : Π (x : fin 0), α x | ⟨_, h⟩ := absurd h (not_lt_zero _) variable {n : nat} lemma eq_of_veq : ∀ {i j : fin n}, i.val = j.val → i = j | ⟨iv, ilt₁⟩ ⟨.(iv), ilt₂⟩ rfl := rfl lemma veq_of_eq : ∀ {i j : fin n}, i = j → i.val = j.val | ⟨iv, ilt⟩ .(_) rfl := rfl lemma ne_of_vne {i j : fin n} (h : i.val ≠ j.val) : i ≠ j := λ h', absurd (veq_of_eq h') h lemma vne_of_ne {i j : fin n} (h : i ≠ j) : i.val ≠ j.val := λ h', absurd (eq_of_veq h') h end fin open fin instance (n : nat) : decidable_eq (fin n) := λ i j, decidable_of_decidable_of_iff (nat.decidable_eq i.val j.val) ⟨eq_of_veq, veq_of_eq⟩
6c6359f41b16331c44928e42596040d6cebba0e3
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/get_weight.lean
b9b7fe99786bb1d2fa009444d12aae717c15664d
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
113
lean
open tactic #eval ([`(ℕ), `(1 + 0)] : list expr).mmap' $ λ e : expr, do trace (e, e.get_weight, e.get_depth)
d552221ef1c6fcd4cb5f90e787b121e0ab95a666
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast_ematch3.lean
25b7c897e56ccef3f0d702355c89f63444001820
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
732
lean
import algebra.ring data.nat open algebra variables {A : Type} section variables [s : add_comm_monoid A] include s attribute add.comm [forward] attribute add.assoc [forward] set_option blast.simp false set_option blast.subst false set_option blast.ematch true theorem add_comm_three (a b c : A) : a + b + c = c + b + a := by blast theorem add.comm4 : ∀ (n m k l : A), n + m + (k + l) = n + k + (m + l) := by blast end section variable [s : group A] include s attribute mul.assoc [forward] attribute mul.left_inv [forward] attribute one_mul [forward] set_option blast.simp false set_option blast.subst false set_option blast.ematch true theorem inv_mul_cancel_left (a b : A) : a⁻¹ * (a * b) = b := by blast end
24691d4759a6f35df6ade9f1dd23fede4438bc65
492a7e27d49633a89f7ce6e1e28f676b062fcbc9
/src/monoidal_categories_reboot/examples/types.lean
c36867dda543d900cb98f593b5cc28579e06f3f3
[ "Apache-2.0" ]
permissive
semorrison/monoidal-categories-reboot
9edba30277de48a234b63813cf85b171772ce36f
48b5f1d535daba4e591672042a298ac36be2e6dd
refs/heads/master
1,642,472,396,149
1,560,587,477,000
1,560,587,477,000
156,465,626
0
1
null
1,541,549,278,000
1,541,549,278,000
null
UTF-8
Lean
false
false
1,679
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. import category_theory.category import category_theory.functor import category_theory.products import category_theory.natural_isomorphism import ..braided_monoidal_category open category_theory open tactic universes u v namespace category_theory section open monoidal_category open braided_monoidal_category def types_left_unitor (α : Type u) : punit × α → α := λ X, X.2 def types_left_unitor_inv (α : Type u) : α → punit × α := λ X, ⟨punit.star, X⟩ def types_right_unitor (α : Type u) : α × punit → α := λ X, X.1 def types_right_unitor_inv (α : Type u) : α → α × punit := λ X, ⟨X, punit.star⟩ def types_associator (α β γ : Type u) : (α × β) × γ → α × (β × γ) := λ X, ⟨X.1.1, ⟨X.1.2, X.2⟩⟩ def types_associator_inv (α β γ : Type u) : α × (β × γ) → (α × β) × γ := λ X, ⟨⟨X.1, X.2.1⟩, X.2.2⟩ def types_braiding (α β : Type u) : α × β → β × α := λ X, ⟨X.2, X.1⟩ def types_braiding_inv := types_braiding instance symmetric_category_of_types : symmetric_monoidal_category.{(u+1)} (Type u) := { tensor_obj := λ X Y, X × Y, tensor_hom := λ _ _ _ _ f g, prod.map f g, tensor_unit := punit, left_unitor := λ X, { hom := types_left_unitor X, inv := types_left_unitor_inv X }, right_unitor := λ X, { hom := types_right_unitor X, inv := types_right_unitor_inv X }, associator := λ X Y Z, { hom := types_associator X Y Z, inv := types_associator_inv X Y Z}, braiding := λ X Y, { hom := types_braiding X Y, inv := types_braiding_inv Y X } } end end category_theory
6798f09f96780912528c0d3aa5fa758db97de6b1
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/products/basic.lean
bde3df4d03481b7af8e79c15e9b74a91f4480863
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,178
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison -/ import category_theory.eq_to_hom /-! # Cartesian products of categories We define the category instance on `C × D` when `C` and `D` are categories. We define: * `sectl C Z` : the functor `C ⥤ C × D` given by `X ↦ ⟨X, Z⟩` * `sectr Z D` : the functor `D ⥤ C × D` given by `Y ↦ ⟨Z, Y⟩` * `fst` : the functor `⟨X, Y⟩ ↦ X` * `snd` : the functor `⟨X, Y⟩ ↦ Y` * `swap` : the functor `C × D ⥤ D × C` given by `⟨X, Y⟩ ↦ ⟨Y, X⟩` (and the fact this is an equivalence) We further define `evaluation : C ⥤ (C ⥤ D) ⥤ D` and `evaluation_uncurried : C × (C ⥤ D) ⥤ D`, and products of functors and natural transformations, written `F.prod G` and `α.prod β`. -/ namespace category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ section variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] /-- `prod C D` gives the cartesian product of two categories. See https://stacks.math.columbia.edu/tag/001K. -/ @[simps {not_recursive := []}] -- the generates simp lemmas like `id_fst` and `comp_snd` instance prod : category.{max v₁ v₂} (C × D) := { hom := λ X Y, ((X.1) ⟶ (Y.1)) × ((X.2) ⟶ (Y.2)), id := λ X, ⟨ 𝟙 (X.1), 𝟙 (X.2) ⟩, comp := λ _ _ _ f g, (f.1 ≫ g.1, f.2 ≫ g.2) } /-- Two rfl lemmas that cannot be generated by `@[simps]`. -/ @[simp] lemma prod_id (X : C) (Y : D) : 𝟙 (X, Y) = (𝟙 X, 𝟙 Y) := rfl @[simp] lemma prod_comp {P Q R : C} {S T U : D} (f : (P, S) ⟶ (Q, T)) (g : (Q, T) ⟶ (R, U)) : f ≫ g = (f.1 ≫ g.1, f.2 ≫ g.2) := rfl end section variables (C : Type u₁) [category.{v₁} C] (D : Type u₁) [category.{v₁} D] /-- `prod.category.uniform C D` is an additional instance specialised so both factors have the same universe levels. This helps typeclass resolution. -/ instance uniform_prod : category (C × D) := category_theory.prod C D end -- Next we define the natural functors into and out of product categories. For now this doesn't -- address the universal properties. namespace prod /-- `sectl C Z` is the functor `C ⥤ C × D` given by `X ↦ (X, Z)`. -/ @[simps] def sectl (C : Type u₁) [category.{v₁} C] {D : Type u₂} [category.{v₂} D] (Z : D) : C ⥤ C × D := { obj := λ X, (X, Z), map := λ X Y f, (f, 𝟙 Z) } /-- `sectr Z D` is the functor `D ⥤ C × D` given by `Y ↦ (Z, Y)` . -/ @[simps] def sectr {C : Type u₁} [category.{v₁} C] (Z : C) (D : Type u₂) [category.{v₂} D] : D ⥤ C × D := { obj := λ X, (Z, X), map := λ X Y f, (𝟙 Z, f) } variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] /-- `fst` is the functor `(X, Y) ↦ X`. -/ @[simps] def fst : C × D ⥤ C := { obj := λ X, X.1, map := λ X Y f, f.1 } /-- `snd` is the functor `(X, Y) ↦ Y`. -/ @[simps] def snd : C × D ⥤ D := { obj := λ X, X.2, map := λ X Y f, f.2 } /-- The functor swapping the factors of a cartesian product of categories, `C × D ⥤ D × C`. -/ @[simps] def swap : C × D ⥤ D × C := { obj := λ X, (X.2, X.1), map := λ _ _ f, (f.2, f.1) } /-- Swapping the factors of a cartesion product of categories twice is naturally isomorphic to the identity functor. -/ @[simps] def symmetry : swap C D ⋙ swap D C ≅ 𝟭 (C × D) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } /-- The equivalence, given by swapping factors, between `C × D` and `D × C`. -/ @[simps] def braiding : C × D ≌ D × C := equivalence.mk (swap C D) (swap D C) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) instance swap_is_equivalence : is_equivalence (swap C D) := (by apply_instance : is_equivalence (braiding C D).functor) end prod section variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] /-- The "evaluation at `X`" functor, such that `(evaluation.obj X).obj F = F.obj X`, which is functorial in both `X` and `F`. -/ @[simps] def evaluation : C ⥤ (C ⥤ D) ⥤ D := { obj := λ X, { obj := λ F, F.obj X, map := λ F G α, α.app X, }, map := λ X Y f, { app := λ F, F.map f, naturality' := λ F G α, eq.symm (α.naturality f) } } /-- The "evaluation of `F` at `X`" functor, as a functor `C × (C ⥤ D) ⥤ D`. -/ @[simps] def evaluation_uncurried : C × (C ⥤ D) ⥤ D := { obj := λ p, p.2.obj p.1, map := λ x y f, (x.2.map f.1) ≫ (f.2.app y.1), map_comp' := λ X Y Z f g, begin cases g, cases f, cases Z, cases Y, cases X, simp only [prod_comp, nat_trans.comp_app, functor.map_comp, category.assoc], rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app, category.assoc, nat_trans.naturality], end } end variables {A : Type u₁} [category.{v₁} A] {B : Type u₂} [category.{v₂} B] {C : Type u₃} [category.{v₃} C] {D : Type u₄} [category.{v₄} D] namespace functor /-- The cartesian product of two functors. -/ @[simps] def prod (F : A ⥤ B) (G : C ⥤ D) : A × C ⥤ B × D := { obj := λ X, (F.obj X.1, G.obj X.2), map := λ _ _ f, (F.map f.1, G.map f.2) } /- Because of limitations in Lean 3's handling of notations, we do not setup a notation `F × G`. You can use `F.prod G` as a "poor man's infix", or just write `functor.prod F G`. -/ end functor namespace nat_trans /-- The cartesian product of two natural transformations. -/ @[simps] def prod {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) : F.prod H ⟶ G.prod I := { app := λ X, (α.app X.1, β.app X.2), naturality' := λ X Y f, begin cases X, cases Y, simp only [functor.prod_map, prod.mk.inj_iff, prod_comp], split; rw naturality end } /- Again, it is inadvisable in Lean 3 to setup a notation `α × β`; use instead `α.prod β` or `nat_trans.prod α β`. -/ end nat_trans end category_theory
acb1c6301edd7b901784b1f601f204b866f2c1b2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/696.lean
9c473b60d60eb5506ba555ebfb5c9018cc1a5be5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
486
lean
def four1 := double 2 where double (n : Nat) : Nat := 2 * n def four2 := double 2 where double : Nat → Nat := fun n => 2 * n def four3 := double 2 where double(n : Nat) : Nat := 2 * n def four4 := double 2 where double: Nat → Nat := fun n => 2 * n def four5 := let double(n : Nat) : Nat := 2 * n double 2 def four6 := let double: Nat → Nat := fun n => 2 * n double 2 def four7 := let rec double: Nat → Nat := fun n => 2 * n double 2
50acd42f9f7330b5fe6bd7778706eb818882bd33
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/inequality/16.lean
706812da97801ae0669afba1d9c3f2b0634ba5f6
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
390
lean
lemma lt_aux_two (a b : mynat) : succ a ≤ b → a ≤ b ∧ ¬ (b ≤ a) := begin intro h, cases h with n hn, split, use succ n, rwa [hn ,succ_add, add_succ], intro hba, rw hn at hba, cases hba with d hd, rw [add_assoc, succ_add, ← add_succ] at hd, symmetry at hd, have h2 := eq_zero_of_add_right_eq_self a (succ (n + d)) hd, exact succ_ne_zero (n + d) h2, end
c61f5b20031bb324659187846474aca1459ca7fd
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/equiv/local_equiv.lean
28bfa540d872d1fe23f0827c908fc0685e529f71
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
33,627
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 data.equiv.basic /-! # Local equivalences This files defines equivalences between subsets of given types. An element `e` of `local_equiv α β` is made of two maps `e.to_fun` and `e.inv_fun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two local equivalences by restricting the source and target to the maximal set where the composition makes sense. As for equivs, we register a coercion to functions and use it in our simp normal form: we write `e x` and `e.symm y` instead of `e.to_fun x` and `e.inv_fun y`. ## Main definitions `equiv.to_local_equiv`: associating a local equiv to an equiv, with source = target = univ `local_equiv.symm` : the inverse of a local equiv `local_equiv.trans` : the composition of two local equivs `local_equiv.refl` : the identity local equiv `local_equiv.of_set` : the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local equivs (see below in implementation notes) ## Implementation notes There are at least three possible implementations of local equivalences: * equivs on subtypes * pairs of functions taking values in `option α` and `option β`, equal to none where the local equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `pequiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The local_equiv version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `to_fun` and `inv_fun` outside of `source` and `target`). In particular, the equality notion between local equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no local equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal local equivs, this is not an issue in practice. Still, we introduce an equivalence relation `eq_on_source` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `local_equiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ mk_simp_attribute mfld_simps "The simpset `mfld_simps` records several simp lemmas that are especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining readability. The typical use case is the following, in a file on manifolds: If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar] with mfld_simps` and paste its output. The list of lemmas should be reasonable (contrary to the output of `squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick enough. " -- register in the simpset `mfld_simps` several lemmas that are often useful when dealing -- with manifolds attribute [mfld_simps] id.def function.comp.left_id set.mem_set_of_eq set.image_eq_empty set.univ_inter set.preimage_univ set.prod_mk_mem_set_prod_eq and_true set.mem_univ set.mem_image_of_mem true_and set.mem_inter_eq set.mem_preimage function.comp_app set.inter_subset_left set.mem_prod set.range_id and_self set.mem_range_self eq_self_iff_true forall_const forall_true_iff set.inter_univ set.preimage_id function.comp.right_id not_false_iff and_imp set.prod_inter_prod set.univ_prod_univ true_or or_true prod.map_mk set.preimage_inter heq_iff_eq equiv.sigma_equiv_prod_apply equiv.sigma_equiv_prod_symm_apply subtype.coe_mk equiv.to_fun_as_coe equiv.inv_fun_as_coe /-- Common `@[simps]` configuration options used for manifold-related declarations. -/ def mfld_cfg : simps_cfg := {attrs := [`simp, `mfld_simps], fully_applied := ff} namespace tactic.interactive /-- A very basic tactic to show that sets showing up in manifolds coincide or are included in one another. -/ meta def mfld_set_tac : tactic unit := do goal ← tactic.target, match goal with | `(%%e₁ = %%e₂) := `[ext my_y, split; { assume h_my_y, try { simp only [*, -h_my_y] with mfld_simps at h_my_y }, simp only [*] with mfld_simps }] | `(%%e₁ ⊆ %%e₂) := `[assume my_y h_my_y, try { simp only [*, -h_my_y] with mfld_simps at h_my_y }, simp only [*] with mfld_simps] | _ := tactic.fail "goal should be an equality or an inclusion" end end tactic.interactive open function set variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global) maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target` are irrelevant. -/ @[nolint has_inhabited_instance] structure local_equiv (α : Type*) (β : Type*) := (to_fun : α → β) (inv_fun : β → α) (source : set α) (target : set β) (map_source' : ∀{x}, x ∈ source → to_fun x ∈ target) (map_target' : ∀{x}, x ∈ target → inv_fun x ∈ source) (left_inv' : ∀{x}, x ∈ source → inv_fun (to_fun x) = x) (right_inv' : ∀{x}, x ∈ target → to_fun (inv_fun x) = x) /-- Associating a local_equiv to an equiv-/ def equiv.to_local_equiv (e : α ≃ β) : local_equiv α β := { to_fun := e, inv_fun := e.symm, source := univ, target := univ, map_source' := λx hx, mem_univ _, map_target' := λy hy, mem_univ _, left_inv' := λx hx, e.left_inv x, right_inv' := λx hx, e.right_inv x } namespace local_equiv variables (e : local_equiv α β) (e' : local_equiv β γ) /-- The inverse of a local equiv -/ protected def symm : local_equiv β α := { to_fun := e.inv_fun, inv_fun := e.to_fun, source := e.target, target := e.source, map_source' := e.map_target', map_target' := e.map_source', left_inv' := e.right_inv', right_inv' := e.left_inv' } instance : has_coe_to_fun (local_equiv α β) := ⟨_, local_equiv.to_fun⟩ /-- See Note [custom simps projection] -/ def simps.symm_apply (e : local_equiv α β) : β → α := e.symm initialize_simps_projections local_equiv (to_fun → apply, inv_fun → symm_apply) @[simp, mfld_simps] theorem coe_mk (f : α → β) (g s t ml mr il ir) : (local_equiv.mk f g s t ml mr il ir : α → β) = f := rfl @[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) : ((local_equiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl @[simp, mfld_simps] lemma to_fun_as_coe : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_as_coe : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩ protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on /-- Create a copy of a `local_equiv` providing better definitional equalities. -/ @[simps] def copy (e : local_equiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : set α) (hs : e.source = s) (t : set β) (ht : e.target = t) : local_equiv α β := { to_fun := f, inv_fun := g, source := s, target := t, map_source' := λ x, ht ▸ hs ▸ hf ▸ e.map_source, map_target' := λ y, hs ▸ ht ▸ hg ▸ e.map_target, left_inv' := λ x, hs ▸ hf ▸ hg ▸ e.left_inv, right_inv' := λ x, ht ▸ hf ▸ hg ▸ e.right_inv } lemma copy_eq_self (e : local_equiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : set α) (hs : e.source = s) (t : set β) (ht : e.target = t) : e.copy f hf g hg s hs t ht = e := by { substs f g s t, cases e, refl } /-- Associating to a local_equiv an equiv between the source and the target -/ protected def to_equiv : equiv (e.source) (e.target) := { to_fun := λ x, ⟨e x, e.map_source x.mem⟩, inv_fun := λ y, ⟨e.symm y, e.map_target y.mem⟩, left_inv := λ⟨x, hx⟩, subtype.eq $ e.left_inv hx, right_inv := λ⟨y, hy⟩, subtype.eq $ e.right_inv hy } @[simp, mfld_simps] lemma symm_source : e.symm.source = e.target := rfl @[simp, mfld_simps] lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := by { cases e, refl } lemma image_source_eq_target : e '' e.source = e.target := e.bij_on.image_eq /-- We say that `t : set β` is an image of `s : set α` under a local equivalence 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 is_image (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace is_image variables {e} {s : set α} {t : set β} {x : α} {y : β} lemma apply_mem_iff (h : e.is_image s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx lemma symm_apply_mem_iff (h : e.is_image s t) : ∀ ⦃y⦄, y ∈ e.target → (e.symm y ∈ s ↔ y ∈ t) := by { rw [← e.image_source_eq_target, ball_image_iff], intros x hx, rw [e.left_inv hx, h hx] } protected lemma symm (h : e.is_image s t) : e.symm.is_image t s := h.symm_apply_mem_iff @[simp] lemma symm_iff : e.symm.is_image t s ↔ e.is_image s t := ⟨λ h, h.symm, λ h, h.symm⟩ protected lemma maps_to (h : e.is_image s t) : maps_to e (e.source ∩ s) (e.target ∩ t) := λ x hx, ⟨e.maps_to hx.1, (h hx.1).2 hx.2⟩ lemma symm_maps_to (h : e.is_image s t) : maps_to e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.maps_to /-- Restrict a `local_equiv` to a pair of corresponding sets. -/ @[simps] def restr (h : e.is_image s t) : local_equiv α β := { to_fun := e, inv_fun := e.symm, source := e.source ∩ s, target := e.target ∩ t, map_source' := h.maps_to, map_target' := h.symm_maps_to, left_inv' := e.left_inv_on.mono (inter_subset_left _ _), right_inv' := e.right_inv_on.mono (inter_subset_left _ _) } lemma image_eq (h : e.is_image s t) : e '' (e.source ∩ s) = e.target ∩ t := h.restr.image_source_eq_target lemma symm_image_eq (h : e.is_image s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq lemma iff_preimage_eq : e.is_image s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := by simp only [is_image, set.ext_iff, mem_inter_eq, and.congr_right_iff, mem_preimage] alias iff_preimage_eq ↔ local_equiv.is_image.preimage_eq local_equiv.is_image.of_preimage_eq lemma iff_symm_preimage_eq : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias iff_symm_preimage_eq ↔ local_equiv.is_image.symm_preimage_eq local_equiv.is_image.of_symm_preimage_eq lemma of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.is_image s t := of_symm_preimage_eq $ eq.trans (of_symm_preimage_eq rfl).image_eq.symm h lemma of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.is_image s t := of_preimage_eq $ eq.trans (of_preimage_eq rfl).symm_image_eq.symm h protected lemma compl (h : e.is_image s t) : e.is_image sᶜ tᶜ := λ x hx, not_congr (h hx) protected lemma inter {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∩ s') (t ∩ t') := λ x hx, and_congr (h hx) (h' hx) protected lemma union {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∪ s') (t ∪ t') := λ x hx, or_congr (h hx) (h' hx) protected lemma diff {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s \ s') (t \ t') := h.inter h'.compl lemma left_inv_on_piecewise {e' : local_equiv α β} [∀ i, decidable (i ∈ s)] [∀ i, decidable (i ∈ t)] (h : e.is_image s t) (h' : e'.is_image s t) : left_inv_on (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := begin rintro x (⟨he, hs⟩|⟨he, hs : x ∉ s⟩), { rw [piecewise_eq_of_mem _ _ _ hs, piecewise_eq_of_mem _ _ _ ((h he).2 hs), e.left_inv he], }, { rw [piecewise_eq_of_not_mem _ _ _ hs, piecewise_eq_of_not_mem _ _ _ ((h'.compl he).2 hs), e'.left_inv he] } end lemma inter_eq_of_inter_eq_of_eq_on {e' : local_equiv α β} (h : e.is_image s t) (h' : e'.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := by rw [← h.image_eq, ← h'.image_eq, ← hs, Heq.image_eq] lemma symm_eq_on_of_inter_eq_of_eq_on {e' : local_equiv α β} (h : e.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : eq_on e.symm e'.symm (e.target ∩ t) := begin rw [← h.image_eq], rintros y ⟨x, hx, rfl⟩, have hx' := hx, rw hs at hx', rw [e.left_inv hx.1, Heq hx, e'.left_inv hx'.1] end end is_image lemma is_image_source_target : e.is_image e.source e.target := λ x hx, by simp [hx] lemma is_image_source_target_of_disjoint (e' : local_equiv α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) : e.is_image e'.source e'.target := assume x hx, have x ∉ e'.source, from λ hx', hs ⟨hx, hx'⟩, have e x ∉ e'.target, from λ hx', ht ⟨e.maps_to hx, hx'⟩, by simp only * lemma image_source_inter_eq' (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := by rw [inter_comm, e.left_inv_on.image_inter', image_source_eq_target, inter_comm] lemma image_source_inter_eq (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := by rw [inter_comm, e.left_inv_on.image_inter, image_source_eq_target, inter_comm] lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := by rw [← e.image_source_inter_eq', inter_eq_self_of_subset_right h] lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_target_inter_eq (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ lemma symm_image_target_inter_eq' (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' s := e.symm.image_source_inter_eq' _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := set.ext $ λ x, and.congr_right_iff.2 $ λ hx, by simp only [mem_preimage, e.left_inv hx] lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target := e.maps_to lemma symm_image_target_eq_source : e.symm '' e.target = e.source := e.symm.image_source_eq_target lemma target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source := e.symm_maps_to /-- Two local equivs that have the same `source`, same `to_fun` and same `inv_fun`, coincide. -/ @[ext] protected lemma ext {e e' : local_equiv α β} (h : ∀x, e x = e' x) (hsymm : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := begin have A : (e : α → β) = e', by { ext x, exact h x }, have B : (e.symm : β → α) = e'.symm, by { ext x, exact hsymm x }, have I : e '' e.source = e.target := e.image_source_eq_target, have I' : e' '' e'.source = e'.target := e'.image_source_eq_target, rw [A, hs, I'] at I, cases e; cases e', simp * at * end /-- Restricting a local equivalence to e.source ∩ s -/ protected def restr (s : set α) : local_equiv α β := (@is_image.of_symm_preimage_eq α β e s (e.symm ⁻¹' s) rfl).restr @[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ s := rfl @[simp, mfld_simps] lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl lemma restr_eq_of_source_subset {e : local_equiv α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := local_equiv.ext (λ_, rfl) (λ_, rfl) (by simp [inter_eq_self_of_subset_left h]) @[simp, mfld_simps] lemma restr_univ {e : local_equiv α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) /-- The identity local equiv -/ protected def refl (α : Type*) : local_equiv α α := (equiv.refl α).to_local_equiv @[simp, mfld_simps] lemma refl_source : (local_equiv.refl α).source = univ := rfl @[simp, mfld_simps] lemma refl_target : (local_equiv.refl α).target = univ := rfl @[simp, mfld_simps] lemma refl_coe : (local_equiv.refl α : α → α) = id := rfl @[simp, mfld_simps] lemma refl_symm : (local_equiv.refl α).symm = local_equiv.refl α := rfl @[simp, mfld_simps] lemma refl_restr_source (s : set α) : ((local_equiv.refl α).restr s).source = s := by simp @[simp, mfld_simps] lemma refl_restr_target (s : set α) : ((local_equiv.refl α).restr s).target = s := by { change univ ∩ id⁻¹' s = s, simp } /-- The identity local equiv on a set `s` -/ def of_set (s : set α) : local_equiv α α := { to_fun := id, inv_fun := id, source := s, target := s, map_source' := λx hx, hx, map_target' := λx hx, hx, left_inv' := λx hx, rfl, right_inv' := λx hx, rfl } @[simp, mfld_simps] lemma of_set_source (s : set α) : (local_equiv.of_set s).source = s := rfl @[simp, mfld_simps] lemma of_set_target (s : set α) : (local_equiv.of_set s).target = s := rfl @[simp, mfld_simps] lemma of_set_coe (s : set α) : (local_equiv.of_set s : α → α) = id := rfl @[simp, mfld_simps] lemma of_set_symm (s : set α) : (local_equiv.of_set s).symm = local_equiv.of_set s := rfl /-- Composing two local equivs if the target of the first coincides with the source of the second. -/ protected def trans' (e' : local_equiv β γ) (h : e.target = e'.source) : local_equiv α γ := { to_fun := e' ∘ e, inv_fun := e.symm ∘ e'.symm, source := e.source, target := e'.target, map_source' := λx hx, by simp [h.symm, hx], map_target' := λy hy, by simp [h, hy], left_inv' := λx hx, by simp [hx, h.symm], right_inv' := λy hy, by simp [hy, h] } /-- Composing two local equivs, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_equiv α γ := local_equiv.trans' (e.symm.restr (e'.source)).symm (e'.restr (e.target)) (inter_comm _ _) @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl @[simp, mfld_simps] lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := by mfld_set_tac lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := by rw [e.trans_source', e.symm_image_target_inter_eq] lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := (e.symm.restr e'.source).symm.image_source_eq_target @[simp, mfld_simps] lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_equiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc]) @[simp, mfld_simps] lemma trans_refl : e.trans (local_equiv.refl β) = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) @[simp, mfld_simps] lemma refl_trans : (local_equiv.refl α).trans e = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, preimage_id]) lemma trans_refl_restr (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) lemma trans_refl_restr' (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e.source ∩ e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source], rw [← inter_assoc, inter_self] } lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source, inter_comm], rwa inter_assoc } /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. Then `e` and `e'` should really be considered the same local equiv. -/ def eq_on_source (e e' : local_equiv α β) : Prop := e.source = e'.source ∧ (e.source.eq_on e e') /-- `eq_on_source` is an equivalence relation -/ instance eq_on_source_setoid : setoid (local_equiv α β) := { r := eq_on_source, iseqv := ⟨ λe, by simp [eq_on_source], λe e' h, by { simp [eq_on_source, h.1.symm], exact λx hx, (h.2 hx).symm }, λe e' e'' h h', ⟨by rwa [← h'.1, ← h.1], λx hx, by { rw [← h'.2, h.2 hx], rwa ← h.1 }⟩⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- Two equivalent local equivs have the same source -/ lemma eq_on_source.source_eq {e e' : local_equiv α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local equivs coincide on the source -/ lemma eq_on_source.eq_on {e e' : local_equiv α β} (h : e ≈ e') : e.source.eq_on e e' := h.2 /-- Two equivalent local equivs have the same target -/ lemma eq_on_source.target_eq {e e' : local_equiv α β} (h : e ≈ e') : e.target = e'.target := by simp only [← image_source_eq_target, ← h.source_eq, h.2.image_eq] /-- If two local equivs are equivalent, so are their inverses. -/ lemma eq_on_source.symm' {e e' : local_equiv α β} (h : e ≈ e') : e.symm ≈ e'.symm := begin refine ⟨h.target_eq, eq_on_of_left_inv_on_of_right_inv_on e.left_inv_on _ _⟩; simp only [symm_source, h.target_eq, h.source_eq, e'.symm_maps_to], exact e'.right_inv_on.congr_right e'.symm_maps_to (h.source_eq ▸ h.eq_on.symm), end /-- Two equivalent local equivs have coinciding inverses on the target -/ lemma eq_on_source.symm_eq_on {e e' : local_equiv α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.eq_on /-- Composition of local equivs respects equivalence -/ lemma eq_on_source.trans' {e e' : local_equiv α β} {f f' : local_equiv β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := begin split, { rw [trans_source'', trans_source'', ← he.target_eq, ← hf.1], exact (he.symm'.eq_on.mono $ inter_subset_left _ _).image_eq }, { assume x hx, rw trans_source at hx, simp [(he.2 hx.1).symm, hf.2 hx.2] } end /-- Restriction of local equivs respects equivalence -/ lemma eq_on_source.restr {e e' : local_equiv α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := begin split, { simp [he.1] }, { assume x hx, simp only [mem_inter_eq, restr_source] at hx, exact he.2 hx.1 } end /-- Preimages are respected by equivalence -/ lemma eq_on_source.source_inter_preimage_eq {e e' : local_equiv α β} (he : e ≈ e') (s : set β) : e.source ∩ e ⁻¹' s = e'.source ∩ e' ⁻¹' s := by rw [he.eq_on.inter_preimage_eq, he.source_eq] /-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_equiv.of_set e.source := begin have A : (e.trans e.symm).source = e.source, by mfld_set_tac, refine ⟨by simp [A], λx hx, _⟩, rw A at hx, simp only [hx] with mfld_simps end /-- Composition of the inverse of a local equiv and this local equiv is equivalent to the restriction of the identity to the target -/ lemma trans_symm_self : e.symm.trans e ≈ local_equiv.of_set e.target := trans_self_symm (e.symm) /-- Two equivalent local equivs are equal when the source and target are univ -/ lemma eq_of_eq_on_source_univ (e e' : local_equiv α β) (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := begin apply local_equiv.ext (λx, _) (λx, _) h.1, { apply h.2, rw s, exact mem_univ _ }, { apply h.symm'.2, rw [symm_source, t], exact mem_univ _ } end section prod /-- The product of two local equivs, as a local equiv on the product. -/ def prod (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) := { source := set.prod e.source e'.source, target := set.prod e.target e'.target, to_fun := λp, (e p.1, e' p.2), inv_fun := λp, (e.symm p.1, e'.symm p.2), map_source' := λp hp, by { simp at hp, simp [hp] }, map_target' := λp hp, by { simp at hp, simp [map_target, hp] }, left_inv' := λp hp, by { simp at hp, simp [hp] }, right_inv' := λp hp, by { simp at hp, simp [hp] } } @[simp, mfld_simps] lemma prod_source (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl @[simp, mfld_simps] lemma prod_target (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp, mfld_simps] lemma prod_coe (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e') : α × γ → β × δ) = (λp, (e p.1, e' p.2)) := rfl lemma prod_coe_symm (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e').symm : β × δ → α × γ) = (λp, (e.symm p.1, e'.symm p.2)) := rfl @[simp, mfld_simps] lemma prod_symm (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := by ext x; simp [prod_coe_symm] @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} (e : local_equiv α β) (f : local_equiv β γ) (e' : local_equiv δ η) (f' : local_equiv η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := by ext x; simp [ext_iff]; tauto end prod /-- Combine two `local_equiv`s using `set.piecewise`. The source of the new `local_equiv` 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. The definition assumes `e.is_image s t` and `e'.is_image s t`. -/ @[simps] def piecewise (e e' : local_equiv α β) (s : set α) (t : set β) [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) : local_equiv α β := { to_fun := s.piecewise e e', inv_fun := t.piecewise e.symm e'.symm, source := s.ite e.source e'.source, target := t.ite e.target e'.target, map_source' := H.maps_to.piecewise_ite H'.compl.maps_to, map_target' := H.symm.maps_to.piecewise_ite H'.symm.compl.maps_to, left_inv' := H.left_inv_on_piecewise H', right_inv' := H.symm.left_inv_on_piecewise H'.symm } lemma symm_piecewise (e e' : local_equiv α β) {s : set α} {t : set β} [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) : (e.piecewise e' s t H H').symm = e.symm.piecewise e'.symm t s H.symm H'.symm := rfl /-- Combine two `local_equiv`s with disjoint sources and disjoint targets. We reuse `local_equiv.piecewise`, then override `source` and `target` to ensure better definitional equalities. -/ @[simps] def disjoint_union (e e' : local_equiv α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] : local_equiv α β := (e.piecewise e' e.source e.target e.is_image_source_target $ e'.is_image_source_target_of_disjoint _ hs.symm ht.symm).copy _ rfl _ rfl (e.source ∪ e'.source) (ite_left _ _) (e.target ∪ e'.target) (ite_left _ _) lemma disjoint_union_eq_piecewise (e e' : local_equiv α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] : e.disjoint_union e' hs ht = e.piecewise e' e.source e.target e.is_image_source_target (e'.is_image_source_target_of_disjoint _ hs.symm ht.symm) := copy_eq_self _ _ _ _ _ _ _ _ _ section pi variables {ι : Type*} {αi βi : ι → Type*} (ei : Π i, local_equiv (αi i) (βi i)) /-- The product of a family of local equivs, as a local equiv on the pi type. -/ @[simps source target] protected def pi : local_equiv (Π i, αi i) (Π i, βi i) := { to_fun := λ f i, ei i (f i), inv_fun := λ f i, (ei i).symm (f i), source := pi univ (λ i, (ei i).source), target := pi univ (λ i, (ei i).target), map_source' := λ f hf i hi, (ei i).map_source (hf i hi), map_target' := λ f hf i hi, (ei i).map_target (hf i hi), left_inv' := λ f hf, funext $ λ i, (ei i).left_inv (hf i trivial), right_inv' := λ f hf, funext $ λ i, (ei i).right_inv (hf i trivial) } attribute [mfld_simps] pi_source pi_target @[simp, mfld_simps] lemma pi_coe : ⇑(local_equiv.pi ei) = λ (f : Π i, αi i) i, ei i (f i) := rfl @[simp, mfld_simps] lemma pi_symm : (local_equiv.pi ei).symm = local_equiv.pi (λ i, (ei i).symm) := rfl end pi end local_equiv namespace set -- All arguments are explicit to avoid missing information in the pretty printer output /-- A bijection between two sets `s : set α` and `t : set β` provides a local equivalence between `α` and `β`. -/ @[simps] noncomputable def bij_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (t : set β) (hf : bij_on f s t) : local_equiv α β := { to_fun := f, inv_fun := inv_fun_on f s, source := s, target := t, map_source' := hf.maps_to, map_target' := hf.surj_on.maps_to_inv_fun_on, left_inv' := hf.inv_on_inv_fun_on.1, right_inv' := hf.inv_on_inv_fun_on.2 } /-- A map injective on a subset of its domain provides a local equivalence. -/ @[simp, mfld_simps] noncomputable def inj_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (hf : inj_on f s) : local_equiv α β := hf.bij_on_image.to_local_equiv f s (f '' s) end set namespace equiv /- equivs give rise to local_equiv. We set up simp lemmas to reduce most properties of the local equiv to that of the equiv. -/ variables (e : equiv α β) (e' : equiv β γ) @[simp, mfld_simps] lemma to_local_equiv_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma to_local_equiv_symm_coe : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma to_local_equiv_source : e.to_local_equiv.source = univ := rfl @[simp, mfld_simps] lemma to_local_equiv_target : e.to_local_equiv.target = univ := rfl @[simp, mfld_simps] lemma refl_to_local_equiv : (equiv.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [local_equiv.trans_source, equiv.to_local_equiv]) end equiv
f40dd0074f7b9fa971e43a4ad1ef6f5190595e47
7cef822f3b952965621309e88eadf618da0c8ae9
/src/ring_theory/adjoin.lean
6f7a7b3c670691e8ae70cf8110012267f7a7239b
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
8,007
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Adjoining elements to form subalgebras. -/ import ring_theory.algebra_operations ring_theory.polynomial ring_theory.principal_ideal_domain import algebra.pointwise universes u v w open lattice submodule ring namespace algebra variables {R : Type u} {A : Type v} variables [comm_ring R] [comm_ring A] variables [algebra R A] {s t : set A} theorem subset_adjoin : s ⊆ adjoin R s := set.subset.trans (set.subset_union_right _ _) subset_closure theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S := closure_subset $ set.union_subset S.3 H theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:= ⟨set.subset.trans subset_adjoin, adjoin_le⟩ theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t := closure_subset (set.subset.trans (set.union_subset_union_right _ H) subset_closure) variables (R A) @[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ := eq_bot_iff.2 $ adjoin_le $ set.empty_subset _ variables {A} variables (s t) theorem adjoin_union : adjoin R (s ∪ t) = (adjoin R s).under (adjoin (adjoin R s) t) := le_antisymm (closure_mono $ set.union_subset (set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map (adjoin R s) r, rfl⟩) (set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩)) (closure_subset $ set.union_subset (set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2) (set.subset.trans (set.subset_union_right _ _) subset_adjoin)) theorem adjoin_eq_span : (adjoin R s : submodule R A) = span R (monoid.closure s) := begin apply le_antisymm, { intros r hr, rcases ring.exists_list_of_mem_closure hr with ⟨L, HL, rfl⟩, clear hr, induction L with hd tl ih, { rw mem_coe, exact zero_mem _ }, rw list.forall_mem_cons at HL, rw [list.map_cons, list.sum_cons, mem_coe], refine submodule.add_mem _ _ (ih HL.2), replace HL := HL.1, clear ih tl, suffices : ∃ z r (hr : r ∈ monoid.closure s), has_scalar.smul.{u v} z r = list.prod hd, { rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr, exact smul_mem _ _ (subset_span hr) }, induction hd with hd tl ih, { exact ⟨1, 1, is_submonoid.one_mem _, one_smul _ _⟩ }, rw list.forall_mem_cons at HL, rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr], rcases HL.1 with ⟨⟨hd, rfl⟩ | hs⟩ | rfl, { refine ⟨hd * z, r, hr, _⟩, rw [smul_def, smul_def, map_mul, ring.mul_assoc], refl }, { refine ⟨z, hd * r, is_submonoid.mul_mem (monoid.subset_closure hs) hr, _⟩, rw [smul_def, smul_def, mul_left_comm] }, { refine ⟨-z, r, hr, _⟩, rw [neg_smul, neg_one_mul] } }, exact span_le.2 (show monoid.closure s ⊆ adjoin R s, from monoid.closure_subset subset_adjoin) end theorem adjoin_eq_range [decidable_eq R] [decidable_eq A] : adjoin R s = (mv_polynomial.aeval R A s).range := le_antisymm (adjoin_le $ λ x hx, ⟨mv_polynomial.X ⟨x, hx⟩, mv_polynomial.eval₂_X _ _ _⟩) (λ x ⟨p, hp⟩, hp ▸ mv_polynomial.induction_on p (λ r, by rw [mv_polynomial.aeval_def, mv_polynomial.eval₂_C]; exact (adjoin R s).3 ⟨r, rfl⟩) (λ p q hp hq, by rw alg_hom.map_add; exact is_add_submonoid.add_mem hp hq) (λ p ⟨n, hn⟩ hp, by rw [alg_hom.map_mul, mv_polynomial.aeval_def _ _ _ (mv_polynomial.X _), mv_polynomial.eval₂_X]; exact is_submonoid.mul_mem hp (subset_adjoin hn))) theorem adjoin_singleton_eq_range [decidable_eq R] [decidable_eq A] (x : A) : adjoin R {x} = (polynomial.aeval R A x).range := le_antisymm (adjoin_le $ set.singleton_subset_iff.2 ⟨polynomial.X, polynomial.eval₂_X _ _⟩) (λ y ⟨p, hp⟩, hp ▸ polynomial.induction_on p (λ r, by rw [polynomial.aeval_def, polynomial.eval₂_C]; exact (adjoin R _).3 ⟨r, rfl⟩) (λ p q hp hq, by rw alg_hom.map_add; exact is_add_submonoid.add_mem hp hq) (λ n r ih, by rw [pow_succ', ← ring.mul_assoc, alg_hom.map_mul, polynomial.aeval_def _ _ _ polynomial.X, polynomial.eval₂_X]; exact is_submonoid.mul_mem ih (subset_adjoin $ or.inl rfl))) theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t) : submodule R A) = (adjoin R s) * (adjoin R t) := begin rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span], congr' 1, ext z, rw monoid.mem_closure_union_iff, split; { rintro ⟨y, hys, z, hzt, rfl⟩, exact ⟨_, hys, _, hzt, rfl⟩ } end variables {R s t} theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_subring (ring.closure s) := le_antisymm (adjoin_le subset_closure) (closure_subset subset_adjoin) local attribute [instance] set.pointwise_mul_semiring theorem fg_trans (h1 : (adjoin R s : submodule R A).fg) (h2 : (adjoin (adjoin R s) t : submodule (adjoin R s) A).fg) : (adjoin R (s ∪ t) : submodule R A).fg := begin rcases fg_def.1 h1 with ⟨p, hp, hp'⟩, rcases fg_def.1 h2 with ⟨q, hq, hq'⟩, refine fg_def.2 ⟨p * q, set.pointwise_mul_finite hp hq, le_antisymm _ _⟩, { rw [span_le], rintros _ ⟨x, hx, y, hy, rfl⟩, change x * y ∈ _, refine is_submonoid.mul_mem _ _, { have : x ∈ (adjoin R s : submodule R A), { rw ← hp', exact subset_span hx }, exact adjoin_mono (set.subset_union_left _ _) this }, have : y ∈ (adjoin (adjoin R s) t : submodule (adjoin R s) A), { rw ← hq', exact subset_span hy }, change y ∈ adjoin R (s ∪ t), rwa adjoin_union }, { intros r hr, change r ∈ adjoin R (s ∪ t) at hr, rw adjoin_union at hr, change r ∈ (adjoin (adjoin R s) t : submodule (adjoin R s) A) at hr, haveI := classical.dec_eq A, haveI := classical.dec_eq R, rw [← hq', ← set.image_id q, finsupp.mem_span_iff_total (adjoin R s)] at hr, rcases hr with ⟨l, hlq, rfl⟩, have := @finsupp.total_apply A A (adjoin R s), rw [this, finsupp.sum, mem_coe], refine sum_mem _ _, intros z hz, change (l z).1 * _ ∈ _, have : (l z).1 ∈ (adjoin R s : submodule R A) := (l z).2, rw [← hp', ← set.image_id p, finsupp.mem_span_iff_total R] at this, rcases this with ⟨l2, hlp, hl⟩, have := @finsupp.total_apply A A R, rw this at hl, rw [←hl, finsupp.sum_mul], refine sum_mem _ _, intros t ht, change _ * _ ∈ _, rw smul_mul_assoc, refine smul_mem _ _ _, exact subset_span ⟨t, hlp ht, z, hlq hz, rfl⟩ } end end algebra namespace subalgebra variables {R : Type u} {A : Type v} variables [comm_ring R] [comm_ring A] [algebra R A] def fg (S : subalgebra R A) : Prop := ∃ t : finset A, algebra.adjoin R ↑t = S theorem fg_def {S : subalgebra R A} : S.fg ↔ ∃ t : set A, set.finite t ∧ algebra.adjoin R t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa finset.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : subalgebra R A).fg := ⟨∅, algebra.adjoin_empty R A⟩ end subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] instance alg_hom.is_noetherian_ring_range (f : A →ₐ[R] B) [is_noetherian_ring A] : is_noetherian_ring f.range := is_noetherian_ring_range f variables [decidable_eq R] [decidable_eq A] theorem is_noetherian_ring_of_fg {S : subalgebra R A} (HS : S.fg) [is_noetherian_ring R] : is_noetherian_ring S := let ⟨t, ht⟩ := HS in ht ▸ (algebra.adjoin_eq_range R (↑t : set A)).symm ▸ by haveI : is_noetherian_ring (mv_polynomial (↑t : set A) R) := is_noetherian_ring_mv_polynomial_of_fintype; convert alg_hom.is_noetherian_ring_range _; apply_instance theorem is_noetherian_ring_closure (s : set R) (hs : s.finite) : is_noetherian_ring (ring.closure s) := show is_noetherian_ring (subalgebra_of_subring (ring.closure s)), from algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (subalgebra.fg_def.2 ⟨s, hs, rfl⟩)
654d4faf18d3ba01560512d4e12536fef526c40b
e4a7c8ab8b68ca0e53d2c21397320ea590fa01c6
/src/data/polya/field/sform.lean
0d4a3b73118bc387bd8a93c65c5c890e89531149
[]
no_license
lean-forward/field
3ff5dc5f43de40f35481b375f8c871cd0a07c766
7e2127ad485aec25e58a1b9c82a6bb74a599467a
refs/heads/master
1,590,947,010,909
1,563,811,881,000
1,563,811,881,000
190,415,651
1
0
null
1,563,643,371,000
1,559,746,688,000
Lean
UTF-8
Lean
false
false
8,102
lean
import .basic namespace polya.field namespace nterm namespace sform variables {α : Type} [discrete_field α] variables {γ : Type} [const_space γ] variables [morph γ α] {ρ : dict α} instance : has_coe (option (nterm γ)) (nterm γ) := ⟨λ x, x.get_or_else (const 0)⟩ private lemma eval_none : eval ρ ((none : option (nterm γ)) : nterm γ) = 0 := by apply morph.morph_zero' private lemma eval_some {x : nterm γ } : eval ρ (some x : nterm γ) = eval ρ x := rfl local attribute [simp] eval_none local attribute [simp] eval_some def to_option : nterm γ → option (nterm γ) | x := if x = const 0 then none else some x --TODO private lemma eval_to_option {x : nterm γ} : eval ρ (to_option x : nterm γ) = eval ρ x := begin unfold to_option, by_cases h1 : x = const 0, repeat { simp [eval, h1] } end private def add' : option (nterm γ) → nterm γ → nterm γ | (some x) y := if y.coeff = 0 then x else scale (coeff y) $ add (x.scale y.coeff⁻¹) y.term | none y := y private lemma eval_add' {x : option (nterm γ)} {y : nterm γ} : eval ρ (add' x y) = eval ρ (x : nterm γ) + eval ρ y := begin cases x, { simp [add'] }, { by_cases h1 : y.coeff = 0, { rw [eval_term_coeff y, h1], simp [add', h1] }, { unfold add', rw [if_neg h1, eval_scale], unfold eval, rw eval_scale, rw [add_mul, mul_assoc, ← morph.morph_mul', inv_mul_cancel h1, ← eval_term_coeff], simp }} end local attribute [simp] eval_add' private def left : nterm γ → option (nterm γ) | (add x _) := some x | _ := none private def right : nterm γ → (nterm γ) | (add _ x) := x | x := x def rest (S : nterm γ) : option (nterm γ) := (left S.term).map (scale S.coeff) def lead (S : nterm γ) : nterm γ := scale S.coeff (right S.term) theorem eval_left_right (x : nterm γ) : eval ρ x = eval ρ (left x : nterm γ) + eval ρ (right x) := by cases x; simp [left, right, eval] theorem eval_rest_lead {S : nterm γ} : eval ρ S = eval ρ (rest S : nterm γ) + eval ρ (lead S) := begin rw [eval_term_coeff, eval_left_right, add_mul], congr' 1, { unfold rest, cases (term S), repeat { simp [left] }}, { simp [lead] } end @[simp] theorem eval_scale_option {x : option (nterm γ)} {a : γ} : eval ρ (x.map (scale a) : nterm γ) = eval ρ (x : nterm γ) * a := by cases x; simp inductive r : option (nterm γ) → option (nterm γ) → Prop | none {S : nterm γ} : r none (some S) | rest {S : nterm γ} : r (rest S) (some S) namespace wf private lemma acc_r_none : @acc (option (nterm γ)) r none := begin apply acc.intro, intros x h, cases h end private def g : nterm γ → ℕ | (add x _) := g x + 1 | (mul x (const _)) := g x | _ := 0 private def f : option (nterm γ) → ℕ | (some x) := g x + 1 | none := 0 private lemma g_scale {x : nterm γ} {a : γ} : g (x.scale a) ≤ g x := begin sorry end private lemma f_none {S : nterm γ} : f (none : option (nterm γ)) < f (some S) := by { unfold f, linarith } private lemma f_scale_option {x : option (nterm γ)} {a : γ} : f (x.map (scale a)) ≤ f x := by { cases x; simp [f, g_scale] } private lemma f_rest {S : nterm γ} : f (rest S) < f (some S) := begin --TODO: simplify proof show f (rest S) < g S + 1, cases S, case add : { simp only [rest, term, left, coeff, f, g, option.map_some', add_lt_add_iff_right], apply lt_of_le_of_lt, { apply g_scale }, { linarith }}, case mul : x y { cases y, case const : { simp only [rest, term, left, coeff, g], apply lt_of_le_of_lt, { apply f_scale_option }, { cases x, repeat { simp [left, f, g], linarith }}}, repeat { simp [rest, term, left, coeff, f], linarith }}, repeat { simp [rest, term, left, f], linarith } end theorem r_wf : @well_founded (option (nterm γ)) r := begin apply subrelation.wf, intros x y h, show f x < f y, cases h, { apply f_none }, { apply f_rest }, apply measure_wf end meta def rel_tac : tactic unit := `[exact ⟨psigma.lex r (λ _, r), psigma.lex_wf wf.r_wf (λ _, wf.r_wf)⟩] meta def dec_tac : tactic unit := `[apply psigma.lex.left, assumption, done] <|> `[apply psigma.lex.right, assumption, done] end wf private def aux (x y : nterm γ) (s1 s2 s3 : option (nterm γ)) : nterm γ := if x.term = y.term then if x.coeff + y.coeff = 0 then (s1 : nterm γ) else add' s1 (mul x.term (const (x.coeff + y.coeff))) else if x.term < y.term then --TODO add' s2 x else add' s3 y --set_option pp.all true private lemma eval_aux {x y : nterm γ} {s1 s2 s3 : option (nterm γ)} ( H0 : x.coeff ≠ 0 ∧ y.coeff ≠ 0) ( H1 : eval ρ (s2 : nterm γ) = eval ρ (s1 : nterm γ) + eval ρ y ) ( H2 : eval ρ (s3 : nterm γ) = eval ρ (s1 : nterm γ) + eval ρ x ) : eval ρ (aux x y s1 s2 s3) = eval ρ (s1 : nterm γ) + eval ρ y + eval ρ x := begin unfold aux, by_cases h1 : x.term = y.term, { rw [if_pos h1, add_assoc], by_cases h2 : x.coeff + y.coeff = 0, { rw [if_pos h2], have : eval ρ y + eval ρ x = 0, { have : coeff x = - coeff y, from eq_neg_of_add_eq_zero h2, rw [eval_term_coeff x, eval_term_coeff y, h1], rw [this, morph.morph_neg'], ring }, simp [this] }, { rw if_neg h2, rw [eval_add'], congr, unfold eval, rw [morph.morph_add, mul_add], rw [← eval_term_coeff, h1, ← eval_term_coeff, add_comm] }}, { rw if_neg h1, by_cases h2 : x.term < y.term, { rw if_pos h2, rw [eval_add'], congr, apply H1 }, { rw if_neg h2, rw [add_assoc, add_comm (eval ρ y), ← add_assoc, eval_add'], congr, apply H2 }} end private def add_option : option (nterm γ) → option (nterm γ) → option (nterm γ) | (some S) (some T) := have h1 : r (rest S) (some S), from r.rest, have h2 : r (rest T) (some T), from r.rest, let s1 := (add_option (rest S) (rest T)) in let s2 := (add_option (rest S) (some T)) in let s3 := (add_option (some S) (rest T)) in if (lead S).coeff ≠ 0 ∧ (lead T).coeff ≠ 0 then some $ aux (lead S) (lead T) s1 s2 s3 else add S T --should not happen | none x := x | x none := x using_well_founded { rel_tac := λ _ _, wf.rel_tac, dec_tac := wf.dec_tac, } private lemma add_option_def1 {x : option (nterm γ)} : add_option none x = x := by cases x; unfold add_option private lemma add_option_def2 {x : option (nterm γ)} : add_option x none = x := by cases x; unfold add_option private lemma add_option_def3 : Π {S T : nterm γ}, (lead S).coeff ≠ 0 ∧ (lead T).coeff ≠ 0 → add_option (some S) (some T) = some (aux (lead S) (lead T) (add_option (rest S) (rest T)) (add_option (rest S) (some T)) (add_option (some S) (rest T)) ) := begin intros S T h0, simp [h0, add_option] end private lemma eval_add_option : Π (S T : option (nterm γ)), eval ρ (add_option S T : nterm γ) = eval ρ (S : nterm γ) + eval ρ (T : nterm γ) | (some S) (some T) := have h1 : r (rest S) (some S), from r.rest, have h2 : r (rest T) (some T), from r.rest, let ih1 := eval_add_option (rest S) in let ih2 := eval_add_option (some S) (rest T) in begin by_cases h0 : (lead S).coeff ≠ 0 ∧ (lead T).coeff ≠ 0, { rw [eval_some, eval_some, add_option_def3 h0], rw [eval_some, eval_aux h0], { rw [ih1, add_assoc (eval ρ ↑(rest S)), ← eval_rest_lead], rw [add_comm (eval ρ ↑(rest S)), add_assoc, ← eval_rest_lead], apply add_comm }, { rw [ih1, ih1, add_assoc, ← eval_rest_lead], refl }, { rw [ih2, ih1, add_comm (eval ρ ↑(rest S)), add_assoc, ← eval_rest_lead], apply add_comm }}, { simp [add_option, h0], refl } end | none x := by rw [add_option_def1]; simp | x none := by rw [add_option_def2]; simp using_well_founded { rel_tac := λ _ _, wf.rel_tac, dec_tac := wf.dec_tac, } protected def add (x y : nterm γ) : nterm γ := add_option (to_option x) (to_option y) protected theorem eval_add {x y : nterm γ} : eval ρ (sform.add x y) = eval ρ x + eval ρ y := by { unfold sform.add, rw [eval_add_option, eval_to_option, eval_to_option] } end sform end nterm end polya.field
4453c0f22f0c9a4a1228417c9b0ce7395957b280
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Elab/Declaration.lean
9a310cc6d310c1493eca6e69eb3cabf06187337b
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,710
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectLevelParams import Lean.Elab.DeclUtil import Lean.Elab.DefView import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.MutualDef namespace Lean.Elab.Command open Meta /- Auxiliary function for `expandDeclNamespace?` -/ def expandDeclIdNamespace? (declId : Syntax) : Option (Name × Syntax) := let (id, optUnivDeclStx) := expandDeclIdCore declId let scpView := extractMacroScopes id match scpView.name with | Name.str Name.anonymous s _ => none | Name.str pre s _ => let nameNew := { scpView with name := Name.mkSimple s }.review if declId.isIdent then some (pre, mkIdentFrom declId nameNew) else some (pre, declId.setArg 0 (mkIdentFrom declId nameNew)) | _ => none /- given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` -/ def expandDeclNamespace? (stx : Syntax) : Option (Name × Syntax) := if !stx.isOfKind `Lean.Parser.Command.declaration then none else let decl := stx[1] let k := decl.getKind if k == `Lean.Parser.Command.abbrev || k == `Lean.Parser.Command.def || k == `Lean.Parser.Command.theorem || k == `Lean.Parser.Command.constant || k == `Lean.Parser.Command.axiom || k == `Lean.Parser.Command.inductive || k == `Lean.Parser.Command.structure then match expandDeclIdNamespace? decl[1] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 1 declId)) | none => none else if k == `Lean.Parser.Command.instance then let optDeclId := decl[1] if optDeclId.isNone then none else match expandDeclIdNamespace? optDeclId[0] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 1 (optDeclId.setArg 0 declId))) | none => none else if k == `Lean.Parser.Command.classInductive then match expandDeclIdNamespace? decl[2] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 2 declId)) | none => none else none def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- parser! "axiom " >> declId >> declSig let declId := stx[1] let (binders, typeStx) := expandDeclSig stx[2] let scopeLevelNames ← getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← expandDeclId declId modifiers runTermElabM declName fun vars => Term.withLevelNames allUserLevelNames $ Term.elabBinders binders.getArgs fun xs => do Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let type ← instantiateMVars type let type ← mkForallFVars xs type let (type, _) ← mkForallUsedOnly vars type let (type, _) ← Term.levelMVarToParam type let usedParams := collectLevelParams {} type $.params match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with | Except.error msg => throwErrorAt stx msg | Except.ok levelParams => let decl := Declaration.axiomDecl { name := declName, lparams := levelParams, type := type, isUnsafe := modifiers.isUnsafe } Term.ensureNoUnassignedMVars decl addDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation /- parser! "inductive " >> declId >> optDeclSig >> many ctor parser! try ("class " >> "inductive ") >> declId >> optDeclSig >> many ctor Remark: numTokens == 1 for regular `inductive` and 2 for `class inductive`. -/ private def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) (numTokens := 1) : CommandElabM InductiveView := do checkValidInductiveModifier modifiers let (binders, type?) := expandOptDeclSig decl[numTokens + 1] let declId := decl[numTokens] let ⟨name, declName, levelNames⟩ ← expandDeclId declId modifiers let ctors ← decl[numTokens + 2].getArgs.mapM fun ctor => withRef ctor do -- def ctor := parser! " | " >> declModifiers >> ident >> optional inferMod >> optDeclSig let ctorModifiers ← elabModifiers ctor[1] if ctorModifiers.isPrivate && modifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' inductive datatype" if ctorModifiers.isProtected && modifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' inductive datatype" checkValidCtorModifier ctorModifiers let ctorName := ctor.getIdAt 2 let ctorName := declName ++ ctorName let ctorName ← withRef ctor[2] $ applyVisibility ctorModifiers.visibility ctorName let inferMod := !ctor[3].isNone let (binders, type?) := expandOptDeclSig ctor[4] pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView } pure { ref := decl, modifiers := modifiers, shortDeclName := name, declName := declName, levelNames := levelNames, binders := binders, type? := type?, ctors := ctors } private def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := inductiveSyntaxToView modifiers decl 2 def elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let v ← inductiveSyntaxToView modifiers stx elabInductiveViews #[v] def elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let modifiers := modifiers.addAttribute { name := `class } let v ← classInductiveSyntaxToView modifiers stx elabInductiveViews #[v] @[builtinCommandElab declaration] def elabDeclaration : CommandElab := fun stx => match expandDeclNamespace? stx with | some (ns, newStx) => do let ns := mkIdentFrom stx ns let newStx ← `(namespace $ns:ident $newStx end $ns:ident) withMacroExpansion stx newStx $ elabCommand newStx | none => do let modifiers ← elabModifiers stx[0] let decl := stx[1] let declKind := decl.getKind if declKind == `Lean.Parser.Command.«axiom» then elabAxiom modifiers decl else if declKind == `Lean.Parser.Command.«inductive» then elabInductive modifiers decl else if declKind == `Lean.Parser.Command.classInductive then elabClassInductive modifiers decl else if declKind == `Lean.Parser.Command.«structure» then elabStructure modifiers decl else if isDefLike decl then elabMutualDef #[stx] else throwError "unexpected declaration" /- Return true if all elements of the mutual-block are inductive declarations. -/ private def isMutualInductive (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] let declKind := decl.getKind declKind == `Lean.Parser.Command.inductive private def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do let views ← elems.mapM fun stx => do let modifiers ← elabModifiers stx[0] inductiveSyntaxToView modifiers stx[1] elabInductiveViews views /- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/ private def isMutualDef (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] isDefLike decl private def isMutualPreambleCommand (stx : Syntax) : Bool := let k := stx.getKind k == `Lean.Parser.Command.variable || k == `Lean.Parser.Command.variables || k == `Lean.Parser.Command.universe || k == `Lean.Parser.Command.universes || k == `Lean.Parser.Command.check || k == `Lean.Parser.Command.set_option || k == `Lean.Parser.Command.open private partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax × Array Syntax) := let rec loop (i : Nat) : Option (Array Syntax × Array Syntax) := if h : i < elems.size then let elem := elems.get ⟨i, h⟩ if isMutualPreambleCommand elem then loop (i+1) else if i == 0 then none -- `mutual` block does not contain any preamble commands else some (elems[0:i], elems[i:elems.size]) else none -- a `mutual` block containing only preamble commands is not a valid `mutual` block loop 0 @[builtinMacro Lean.Parser.Command.mutual] def expandMutualNamespace : Macro := fun stx => do let mut ns? := none let mut elemsNew := #[] for elem in stx[1].getArgs do match ns?, expandDeclNamespace? elem with | _, none => elemsNew := elemsNew.push elem | none, some (ns, elem) => ns? := some ns; elemsNew := elemsNew.push elem | some nsCurr, some (nsNew, elem) => if nsCurr == nsNew then elemsNew := elemsNew.push elem else Macro.throwError elem s!"conflicting namespaces in mutual declaration, using namespace '{nsNew}', but used '{nsCurr}' in previous declaration" match ns? with | some ns => let ns := mkIdentFrom stx ns let stxNew := stx.setArg 1 (mkNullNode elemsNew) `(namespace $ns:ident $stxNew end $ns:ident) | none => Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualElement : Macro := fun stx => do let mut elemsNew := #[] let mut modified := false for elem in stx[1].getArgs do match (← expandMacro? elem) with | some elemNew => elemsNew := elemsNew.push elemNew; modified := true | none => elemsNew := elemsNew.push elem if modified then pure $ stx.setArg 1 (mkNullNode elemsNew) else Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualPreamble : Macro := fun stx => match splitMutualPreamble stx[1].getArgs with | none => Macro.throwUnsupported | some (preamble, rest) => do let secCmd ← `(section) let newMutual := stx.setArg 1 (mkNullNode rest) let endCmd ← `(end) pure $ mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd]) @[builtinCommandElab «mutual»] def elabMutual : CommandElab := fun stx => do if isMutualInductive stx then elabMutualInductive stx[1].getArgs else if isMutualDef stx then elabMutualDef stx[1].getArgs else throwError "invalid mutual block" /- parser! optional "local " >> "attribute " >> "[" >> sepBy1 Term.attrInstance ", " >> "]" >> many1 ident -/ @[builtinCommandElab «attribute»] def elabAttr : CommandElab := fun stx => do let persistent := stx[0].isNone let attrs ← elabAttrs stx[3] let idents := stx[5].getArgs for ident in idents do withRef ident $ liftTermElabM none do let declName ← resolveGlobalConstNoOverload ident.getId Term.applyAttributes declName attrs persistent def expandInitCmd (builtin : Bool) : Macro := fun stx => let optHeader := stx[1] let doSeq := stx[2] let attrId := mkIdentFrom stx $ if builtin then `builtinInit else `init if optHeader.isNone then `(@[$attrId:ident]def initFn : IO Unit := do $doSeq) else let id := optHeader[0] let type := optHeader[1][1] `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn]constant $id : $type) @[builtinMacro Lean.Parser.Command.«initialize»] def expandInitialize : Macro := expandInitCmd (builtin := false) @[builtinMacro Lean.Parser.Command.«builtin_initialize»] def expandBuiltinInitialize : Macro := expandInitCmd (builtin := true) end Lean.Elab.Command
0b24dee589a6bf6f192625a97299b3cb40c70ead
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/algebra/group/units.lean
5b98b74167b4a4cbe1bb5c62b74a7bbad9a62755
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
11,440
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker -/ import algebra.group.basic import tactic.ext import tactic.norm_cast /-! # Units (i.e., invertible elements) of a multiplicative monoid -/ universe u variable {α : Type u} /-- Units of a monoid, bundled version. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) /-- Units of an add_monoid, bundled version. An element of an add_monoid is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive add_units] units namespace units variables [monoid α] @[to_additive] instance : has_coe (units α) α := ⟨val⟩ @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : units α → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[to_additive] theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := ext.eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq (units α) := λ a b, decidable_of_iff' _ ext_iff /-- Units of a monoid form a group. -/ @[to_additive] instance : group (units α) := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ← mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ← mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, mul_one := λ u, ext $ mul_one u, one_mul := λ u, ext $ one_mul u, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := λ u, ⟨u.2, u.1, u.4, u.3⟩, mul_left_inv := λ u, ext u.inv_val } variables (a b : units α) {c : units α} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl attribute [norm_cast] add_units.coe_add @[simp, norm_cast, to_additive] lemma coe_one : ((1 : units α) : α) = 1 := rfl attribute [norm_cast] add_units.coe_zero @[to_additive] lemma val_coe : (↑a : α) = a.val := rfl @[norm_cast, to_additive] lemma coe_inv : ((a⁻¹ : units α) : α) = a.inv := rfl attribute [norm_cast] add_units.coe_neg @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul' {u : units α} {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by { rw [←h, u.inv_mul], } @[to_additive] lemma mul_inv' {u : units α} {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by { rw [←h, u.mul_inv], } @[simp, to_additive] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[to_additive] instance : inhabited (units α) := ⟨1⟩ @[to_additive] instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp, to_additive] theorem mul_right_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : α} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : α} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ lemma inv_eq_of_mul_eq_one {u : units α} {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = ↑u⁻¹ * ↑u * a : by rw [←h, ←mul_assoc] ... = a : by rw [u.inv_mul, one_mul] lemma inv_unique {u₁ u₂ : units α} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := suffices ↑u₁ * (↑u₂⁻¹ : α) = 1, by exact inv_eq_of_mul_eq_one this, by rw [h, u₂.mul_inv] end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_inv (u : units α) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : units α) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] theorem divp_eq_iff_mul_eq {x : α} {u : units α} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ theorem divp_eq_one_iff_eq {a : α} {u : units α} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid section comm_monoid variables [comm_monoid α] theorem divp_eq_divp_iff {x y : α} {ux uy : units α} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, mul_comm, ← divp_assoc, divp_eq_iff_mul_eq, mul_comm y ux] theorem divp_mul_divp (x y : α) (ux uy : units α) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [← divp_divp_eq_divp_mul, divp_assoc, mul_comm x, divp_assoc, mul_comm] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : units M`, where `units M` is a bundled version of `is_unit`. -/ @[to_additive is_add_unit "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : units M, (u : M) = a @[simp, to_additive is_add_unit_add_unit] lemma is_unit_unit [monoid M] (u : units M) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive is_add_unit_zero] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive is_add_unit_of_add_eq_zero] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit_iff_exists_neg] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨by rintro ⟨⟨a, b, hab, _⟩, rfl⟩; exact ⟨b, hab⟩, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive is_add_unit_iff_exists_neg'] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] /-- Multiplication by a `u : units M` doesn't affect `is_unit`. -/ @[simp, to_additive is_add_unit_add_add_units "Addition of a `u : add_units M` doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : units M) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv ▸ ⟨v * u, (units.coe_mul v u).symm⟩) @[to_additive is_add_unit_of_add_is_add_unit_left] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm @[to_additive] theorem is_unit.mul_right_inj [monoid M] {a b c : M} (ha : is_unit a) : a * b = a * c ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_right_inj] @[to_additive] theorem is_unit.mul_left_inj [monoid M] {a b c : M} (ha : is_unit a) : b * a = c * a ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_left_inj] /-- The element of the group of units, corresponding to an element of a monoid which is a unit. -/ noncomputable def is_unit.unit [monoid M] {a : M} (h : is_unit a) : units M := classical.some h lemma is_unit.unit_spec [monoid M] {a : M} (h : is_unit a) : ↑h.unit = a := classical.some_spec h end is_unit
82d260118ae35f94c2b3ed4af9bab98388d2e23e
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/divisibility.lean
bd4861859287269bac655637f6d087e568aa34c6
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
7,572
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland, Aaron Anderson -/ import algebra.group_with_zero /-! # Divisibility This file defines the basics of the divisibility relation in the context of `(comm_)` `monoid`s `(_with_zero)`. ## Main definitions * `monoid.has_dvd` ## Implementation notes The divisibility relation is defined for all monoids, and as such, depends on the order of multiplication if the monoid is not commutative. There are two possible conventions for divisibility in the noncommutative context, and this relation follows the convention for ordinals, so `a | b` is defined as `∃ c, b = a * c`. ## Tags divisibility, divides -/ variables {α : Type*} section monoid variables [monoid α] {a b c : α} /-- There are two possible conventions for divisibility, which coincide in a `comm_monoid`. This matches the convention for ordinals. -/ @[priority 100] instance monoid_has_dvd : has_dvd α := has_dvd.mk (λ a b, ∃ c, b = a * c) -- TODO: this used to not have c explicit, but that seems to be important -- for use with tactics, similar to exist.intro theorem dvd.intro (c : α) (h : a * c = b) : a ∣ b := exists.intro c h^.symm alias dvd.intro ← dvd_of_mul_right_eq theorem exists_eq_mul_right_of_dvd (h : a ∣ b) : ∃ c, b = a * c := h theorem dvd.elim {P : Prop} {a b : α} (H₁ : a ∣ b) (H₂ : ∀ c, b = a * c → P) : P := exists.elim H₁ H₂ @[refl, simp] theorem dvd_refl (a : α) : a ∣ a := dvd.intro 1 (by simp) local attribute [simp] mul_assoc mul_comm mul_left_comm @[trans] theorem dvd_trans (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c := match h₁, h₂ with | ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ := ⟨d * e, show c = a * (d * e), by simp [h₃, h₄]⟩ end alias dvd_trans ← dvd.trans theorem one_dvd (a : α) : 1 ∣ a := dvd.intro a (by simp) @[simp] theorem dvd_mul_right (a b : α) : a ∣ a * b := dvd.intro b rfl theorem dvd_mul_of_dvd_left (h : a ∣ b) (c : α) : a ∣ b * c := dvd.elim h (λ d h', begin rw [h', mul_assoc], apply dvd_mul_right end) theorem dvd_of_mul_right_dvd (h : a * b ∣ c) : a ∣ c := dvd.elim h (begin intros d h₁, rw [h₁, mul_assoc], apply dvd_mul_right end) end monoid section comm_monoid variables [comm_monoid α] {a b c : α} theorem dvd.intro_left (c : α) (h : c * a = b) : a ∣ b := dvd.intro _ (begin rewrite mul_comm at h, apply h end) alias dvd.intro_left ← dvd_of_mul_left_eq theorem exists_eq_mul_left_of_dvd (h : a ∣ b) : ∃ c, b = c * a := dvd.elim h (assume c, assume H1 : b = a * c, exists.intro c (eq.trans H1 (mul_comm a c))) theorem dvd.elim_left {P : Prop} (h₁ : a ∣ b) (h₂ : ∀ c, b = c * a → P) : P := exists.elim (exists_eq_mul_left_of_dvd h₁) (assume c, assume h₃ : b = c * a, h₂ c h₃) @[simp] theorem dvd_mul_left (a b : α) : a ∣ b * a := dvd.intro b (mul_comm a b) theorem dvd_mul_of_dvd_right (h : a ∣ b) (c : α) : a ∣ c * b := begin rw mul_comm, exact dvd_mul_of_dvd_left h _ end local attribute [simp] mul_assoc mul_comm mul_left_comm theorem mul_dvd_mul : ∀ {a b c d : α}, a ∣ b → c ∣ d → a * c ∣ b * d | a ._ c ._ ⟨e, rfl⟩ ⟨f, rfl⟩ := ⟨e * f, by simp⟩ theorem mul_dvd_mul_left (a : α) {b c : α} (h : b ∣ c) : a * b ∣ a * c := mul_dvd_mul (dvd_refl a) h theorem mul_dvd_mul_right (h : a ∣ b) (c : α) : a * c ∣ b * c := mul_dvd_mul h (dvd_refl c) theorem dvd_of_mul_left_dvd (h : a * b ∣ c) : b ∣ c := dvd.elim h (λ d ceq, dvd.intro (a * d) (by simp [ceq])) end comm_monoid section monoid_with_zero variables [monoid_with_zero α] {a : α} theorem eq_zero_of_zero_dvd (h : 0 ∣ a) : a = 0 := dvd.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (zero_mul c)) /-- Given an element `a` of a commutative monoid with zero, there exists another element whose product with zero equals `a` iff `a` equals zero. -/ @[simp] lemma zero_dvd_iff : 0 ∣ a ↔ a = 0 := ⟨eq_zero_of_zero_dvd, λ h, by rw h⟩ @[simp] theorem dvd_zero (a : α) : a ∣ 0 := dvd.intro 0 (by simp) end monoid_with_zero /-- Given two elements `b`, `c` of a `cancel_monoid_with_zero` and a nonzero element `a`, `a*b` divides `a*c` iff `b` divides `c`. -/ theorem mul_dvd_mul_iff_left [cancel_monoid_with_zero α] {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, mul_right_inj' ha] /-- Given two elements `a`, `b` of a commutative `cancel_monoid_with_zero` and a nonzero element `c`, `a*c` divides `b*c` iff `a` divides `b`. -/ theorem mul_dvd_mul_iff_right [comm_cancel_monoid_with_zero α] {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, mul_left_inj' hc] /-! ### Units in various monoids -/ namespace units section monoid variables [monoid α] {a b : α} {u : units α} /-- Elements of the unit group of a monoid represented as elements of the monoid divide any element of the monoid. -/ lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩ /-- In a monoid, an element `a` divides an element `b` iff `a` divides all associates of `b`. -/ lemma dvd_mul_right : a ∣ b * u ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩) (assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) /-- In a monoid, an element a divides an element b iff all associates of `a` divide `b`.-/ lemma mul_right_dvd : a * u ∣ b ↔ a ∣ b := iff.intro (λ ⟨c, eq⟩, ⟨↑u * c, eq.trans (mul_assoc _ _ _)⟩) (λ h, dvd_trans (dvd.intro ↑u⁻¹ (by rw [mul_assoc, u.mul_inv, mul_one])) h) end monoid section comm_monoid variables [comm_monoid α] {a b : α} {u : units α} /-- In a commutative monoid, an element `a` divides an element `b` iff `a` divides all left associates of `b`. -/ lemma dvd_mul_left : a ∣ u * b ↔ a ∣ b := by { rw mul_comm, apply dvd_mul_right } /-- In a commutative monoid, an element `a` divides an element `b` iff all left associates of `a` divide `b`.-/ lemma mul_left_dvd : ↑u * a ∣ b ↔ a ∣ b := by { rw mul_comm, apply mul_right_dvd } end comm_monoid end units namespace is_unit section monoid variables [monoid α] {a b u : α} (hu : is_unit u) include hu /-- Units of a monoid divide any element of the monoid. -/ @[simp] lemma dvd : u ∣ a := by { rcases hu with ⟨u, rfl⟩, apply units.coe_dvd, } @[simp] lemma dvd_mul_right : a ∣ b * u ↔ a ∣ b := by { rcases hu with ⟨u, rfl⟩, apply units.dvd_mul_right, } /-- In a monoid, an element a divides an element b iff all associates of `a` divide `b`.-/ @[simp] lemma mul_right_dvd : a * u ∣ b ↔ a ∣ b := by { rcases hu with ⟨u, rfl⟩, apply units.mul_right_dvd, } end monoid section comm_monoid variables [comm_monoid α] (a b u : α) (hu : is_unit u) include hu /-- In a commutative monoid, an element `a` divides an element `b` iff `a` divides all left associates of `b`. -/ @[simp] lemma dvd_mul_left : a ∣ u * b ↔ a ∣ b := by { rcases hu with ⟨u, rfl⟩, apply units.dvd_mul_left, } /-- In a commutative monoid, an element `a` divides an element `b` iff all left associates of `a` divide `b`.-/ @[simp] lemma mul_left_dvd : u * a ∣ b ↔ a ∣ b := by { rcases hu with ⟨u, rfl⟩, apply units.mul_left_dvd, } end comm_monoid end is_unit
e625c14948a771388f6b3140cc1406f6d82a5e11
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_topology/dold_kan/faces.lean
d9e7af0e6396041e15cdca4ac0125b8cc205a2eb
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,409
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.homotopies import tactic.ring_exp /-! # Study of face maps for the Dold-Kan correspondence > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. TODO (@joelriou) continue adding the various files referenced below In this file, we obtain the technical lemmas that are used in the file `projections.lean` in order to get basic properties of the endomorphisms `P q : K[X] ⟶ K[X]` with respect to face maps (see `homotopies.lean` for the role of these endomorphisms in the overall strategy of proof). The main lemma in this file is `higher_faces_vanish.induction`. It is based on two technical lemmas `higher_faces_vanish.comp_Hσ_eq` and `higher_faces_vanish.comp_Hσ_eq_zero`. (See `equivalence.lean` for the general strategy of proof of the Dold-Kan equivalence.) -/ open nat open category_theory open category_theory.limits open category_theory.category open category_theory.preadditive open category_theory.simplicial_object open_locale simplicial dold_kan namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] variables {X : simplicial_object C} /-- A morphism `φ : Y ⟶ X _[n+1]` satisfies `higher_faces_vanish q φ` when the compositions `φ ≫ X.δ j` are `0` for `j ≥ max 1 (n+2-q)`. When `q ≤ n+1`, it basically means that the composition `φ ≫ X.δ j` are `0` for the `q` highest possible values of a nonzero `j`. Otherwise, when `q ≥ n+2`, all the compositions `φ ≫ X.δ j` for nonzero `j` vanish. See also the lemma `comp_P_eq_self_iff` in `projections.lean` which states that `higher_faces_vanish q φ` is equivalent to the identity `φ ≫ (P q).f (n+1) = φ`. -/ def higher_faces_vanish {Y : C} {n : ℕ} (q : ℕ) (φ : Y ⟶ X _[n+1]) : Prop := ∀ (j : fin (n+1)), (n+1 ≤ (j : ℕ) + q) → φ ≫ X.δ j.succ = 0 namespace higher_faces_vanish @[reassoc] lemma comp_δ_eq_zero {Y : C} {n : ℕ} {q : ℕ} {φ : Y ⟶ X _[n+1]} (v : higher_faces_vanish q φ) (j : fin (n+2)) (hj₁ : j ≠ 0) (hj₂ : n+2 ≤ (j : ℕ) + q) : φ ≫ X.δ j = 0 := begin obtain ⟨i, hi⟩ := fin.eq_succ_of_ne_zero hj₁, subst hi, apply v i, rw [← @nat.add_le_add_iff_right 1, add_assoc], simpa only [fin.coe_succ, add_assoc, add_comm 1] using hj₂, end lemma of_succ {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]} (v : higher_faces_vanish (q+1) φ) : higher_faces_vanish q φ := λ j hj, v j (by simpa only [← add_assoc] using le_add_right hj) lemma of_comp {Y Z : C} {q n : ℕ} {φ : Y ⟶ X _[n+1]} (v : higher_faces_vanish q φ) (f : Z ⟶ Y) : higher_faces_vanish q (f ≫ φ) := λ j hj, by rw [assoc, v j hj, comp_zero] lemma comp_Hσ_eq {Y : C} {n a q : ℕ} {φ : Y ⟶ X _[n+1]} (v : higher_faces_vanish q φ) (hnaq : n=a+q) : φ ≫ (Hσ q).f (n+1) = - φ ≫ X.δ ⟨a+1, nat.succ_lt_succ (nat.lt_succ_iff.mpr (nat.le.intro hnaq.symm))⟩ ≫ X.σ ⟨a, nat.lt_succ_iff.mpr (nat.le.intro hnaq.symm)⟩ := begin have hnaq_shift : Π d : ℕ, n+d=(a+d)+q, { intro d, rw [add_assoc, add_comm d, ← add_assoc, hnaq], }, rw [Hσ, homotopy.null_homotopic_map'_f (c_mk (n+2) (n+1) rfl) (c_mk (n+1) n rfl), hσ'_eq hnaq (c_mk (n+1) n rfl), hσ'_eq (hnaq_shift 1) (c_mk (n+2) (n+1) rfl)], simp only [alternating_face_map_complex.obj_d_eq, eq_to_hom_refl, comp_id, comp_sum, sum_comp, comp_add], simp only [comp_zsmul, zsmul_comp, ← assoc, ← mul_zsmul], /- cleaning up the first sum -/ rw [← fin.sum_congr' _ (hnaq_shift 2).symm, fin.sum_trunc], swap, { rintro ⟨k, hk⟩, suffices : φ ≫ X.δ (⟨a+2+k, by linarith⟩ : fin (n+2)) = 0, { simp only [this, fin.nat_add_mk, fin.cast_mk, zero_comp, smul_zero], }, convert v ⟨a+k+1, by linarith⟩ (by { rw fin.coe_mk, linarith, }), rw [nat.succ_eq_add_one], linarith, }, /- cleaning up the second sum -/ rw [← fin.sum_congr' _ (hnaq_shift 3).symm, @fin.sum_trunc _ _ (a+3)], swap, { rintros ⟨k, hk⟩, rw [assoc, X.δ_comp_σ_of_gt', v.comp_δ_eq_zero_assoc, zero_comp, zsmul_zero], { intro h, rw [fin.pred_eq_iff_eq_succ, fin.ext_iff] at h, dsimp at h, linarith, }, { dsimp, simp only [fin.coe_pred, fin.coe_mk, succ_add_sub_one], linarith, }, { dsimp, linarith, }, }, /- leaving out three specific terms -/ conv_lhs { congr, skip, rw [fin.sum_univ_cast_succ, fin.sum_univ_cast_succ], }, rw fin.sum_univ_cast_succ, simp only [fin.last, fin.cast_le_mk, fin.coe_cast, fin.cast_mk, fin.coe_cast_le, fin.coe_mk, fin.cast_succ_mk, fin.coe_cast_succ], /- the purpose of the following `simplif` is to create three subgoals in order to finish the proof -/ have simplif : ∀ (a b c d e f : Y ⟶ X _[n+1]), b=f → d+e=0 → c+a=0 → a+b+(c+d+e) = f, { intros a b c d e f h1 h2 h3, rw [add_assoc c d e, h2, add_zero, add_comm a b, add_assoc, add_comm a c, h3, add_zero, h1], }, apply simplif, { /- b=f -/ rw [← pow_add, odd.neg_one_pow, neg_smul, one_zsmul], use a, linarith, }, { /- d+e = 0 -/ rw [assoc, assoc, X.δ_comp_σ_self' (fin.cast_succ_mk _ _ _).symm, X.δ_comp_σ_succ' (fin.succ_mk _ _ _).symm], simp only [comp_id, pow_add _ (a+1) 1, pow_one, mul_neg, mul_one, neg_smul, add_right_neg], }, { /- c+a = 0 -/ rw ← finset.sum_add_distrib, apply finset.sum_eq_zero, rintros ⟨i, hi⟩ h₀, have hia : (⟨i, by linarith⟩ : fin (n+2)) ≤ fin.cast_succ (⟨a, by linarith⟩ : fin (n+1)) := by simpa only [fin.le_iff_coe_le_coe, fin.coe_mk, fin.cast_succ_mk, ← lt_succ_iff] using hi, simp only [fin.coe_mk, fin.cast_le_mk, fin.cast_succ_mk, fin.succ_mk, assoc, fin.cast_mk, ← δ_comp_σ_of_le X hia, add_eq_zero_iff_eq_neg, ← neg_zsmul], congr, ring_exp, }, end lemma comp_Hσ_eq_zero {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]} (v : higher_faces_vanish q φ) (hqn : n<q) : φ ≫ (Hσ q).f (n+1) = 0 := begin simp only [Hσ, homotopy.null_homotopic_map'_f (c_mk (n+2) (n+1) rfl) (c_mk (n+1) n rfl)], rw [hσ'_eq_zero hqn (c_mk (n+1) n rfl), comp_zero, zero_add], by_cases hqn' : n+1<q, { rw [hσ'_eq_zero hqn' (c_mk (n+2) (n+1) rfl), zero_comp, comp_zero], }, { simp only [hσ'_eq (show n+1=0+q, by linarith) (c_mk (n+2) (n+1) rfl), pow_zero, fin.mk_zero, one_zsmul, eq_to_hom_refl, comp_id, comp_sum, alternating_face_map_complex.obj_d_eq], rw [← fin.sum_congr' _ (show 2+(n+1)=n+1+2, by linarith), fin.sum_trunc], { simp only [fin.sum_univ_cast_succ, fin.sum_univ_zero, zero_add, fin.last, fin.cast_le_mk, fin.cast_mk, fin.cast_succ_mk], simp only [fin.mk_zero, fin.coe_zero, pow_zero, one_zsmul, fin.mk_one, fin.coe_one, pow_one, neg_smul, comp_neg], erw [δ_comp_σ_self, δ_comp_σ_succ, add_right_neg], }, { intro j, rw [comp_zsmul, comp_zsmul, δ_comp_σ_of_gt', v.comp_δ_eq_zero_assoc, zero_comp, zsmul_zero], { intro h, rw [fin.pred_eq_iff_eq_succ, fin.ext_iff] at h, dsimp at h, linarith, }, { dsimp, simp only [fin.cast_nat_add, fin.coe_pred, fin.coe_add_nat, add_succ_sub_one], linarith, }, { rw fin.lt_iff_coe_lt_coe, dsimp, linarith, }, }, }, end lemma induction {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]} (v : higher_faces_vanish q φ) : higher_faces_vanish (q+1) (φ ≫ (𝟙 _ + Hσ q).f (n+1)) := begin intros j hj₁, dsimp, simp only [comp_add, add_comp, comp_id], -- when n < q, the result follows immediately from the assumption by_cases hqn : n<q, { rw [v.comp_Hσ_eq_zero hqn, zero_comp, add_zero, v j (by linarith)], }, -- we now assume that n≥q, and write n=a+q cases nat.le.dest (not_lt.mp hqn) with a ha, rw [v.comp_Hσ_eq (show n=a+q, by linarith), neg_comp, add_neg_eq_zero, assoc, assoc], cases n with m hm, -- the boundary case n=0 { simpa only [nat.eq_zero_of_add_eq_zero_left ha, fin.eq_zero j, fin.mk_zero, fin.mk_one, δ_comp_σ_succ, comp_id], }, -- in the other case, we need to write n as m+1 -- then, we first consider the particular case j = a by_cases hj₂ : a = (j : ℕ), { simp only [hj₂, fin.eta, δ_comp_σ_succ, comp_id], congr, ext, simp only [fin.coe_succ, fin.coe_mk], }, -- now, we assume j ≠ a (i.e. a < j) have haj : a<j := (ne.le_iff_lt hj₂).mp (by linarith), have hj₃ := j.is_lt, have ham : a≤m, { by_contradiction, rw [not_le, ← nat.succ_le_iff] at h, linarith, }, rw [X.δ_comp_σ_of_gt', j.pred_succ], swap, { rw fin.lt_iff_coe_lt_coe, simpa only [fin.coe_mk, fin.coe_succ, add_lt_add_iff_right] using haj, }, obtain (ham' | ham'') := ham.lt_or_eq, { -- case where `a<m` rw ← X.δ_comp_δ''_assoc, swap, { rw fin.le_iff_coe_le_coe, dsimp, linarith, }, simp only [← assoc, v j (by linarith), zero_comp], }, { -- in the last case, a=m, q=1 and j=a+1 rw X.δ_comp_δ_self'_assoc, swap, { ext, dsimp, have hq : q = 1 := by rw [← add_left_inj a, ha, ham'', add_comm], linarith, }, simp only [← assoc, v j (by linarith), zero_comp], }, end end higher_faces_vanish end dold_kan end algebraic_topology
317b00bdac37955172e4816db32d459ea9ff757f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/matrix/charpoly/basic.lean
f402becdd93d6cdb73ac5abb8af1a938ea6bcfe9
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,579
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import linear_algebra.matrix.adjugate import ring_theory.polynomial_algebra import tactic.apply_fun import tactic.squeeze /-! # Characteristic polynomials and the Cayley-Hamilton theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define characteristic polynomials of matrices and prove the Cayley–Hamilton theorem over arbitrary commutative rings. See the file `matrix/charpoly/coeff` for corollaries of this theorem. ## Main definitions * `matrix.charpoly` is the characteristic polynomial of a matrix. ## Implementation details We follow a nice proof from http://drorbn.net/AcademicPensieve/2015-12/CayleyHamilton.pdf -/ noncomputable theory universes u v w open polynomial matrix open_locale big_operators polynomial variables {R : Type u} [comm_ring R] variables {n : Type w} [decidable_eq n] [fintype n] open finset /-- The "characteristic matrix" of `M : matrix n n R` is the matrix of polynomials $t I - M$. The determinant of this matrix is the characteristic polynomial. -/ def charmatrix (M : matrix n n R) : matrix n n R[X] := matrix.scalar n (X : R[X]) - (C : R →+* R[X]).map_matrix M lemma charmatrix_apply (M : matrix n n R) (i j : n) : charmatrix M i j = X * (1 : matrix n n R[X]) i j - C (M i j) := rfl @[simp] lemma charmatrix_apply_eq (M : matrix n n R) (i : n) : charmatrix M i i = (X : R[X]) - C (M i i) := by simp only [charmatrix, sub_left_inj, pi.sub_apply, scalar_apply_eq, ring_hom.map_matrix_apply, map_apply, dmatrix.sub_apply] @[simp] lemma charmatrix_apply_ne (M : matrix n n R) (i j : n) (h : i ≠ j) : charmatrix M i j = - C (M i j) := by simp only [charmatrix, pi.sub_apply, scalar_apply_ne _ _ _ h, zero_sub, ring_hom.map_matrix_apply, map_apply, dmatrix.sub_apply] lemma mat_poly_equiv_charmatrix (M : matrix n n R) : mat_poly_equiv (charmatrix M) = X - C M := begin ext k i j, simp only [mat_poly_equiv_coeff_apply, coeff_sub, pi.sub_apply], by_cases h : i = j, { subst h, rw [charmatrix_apply_eq, coeff_sub], simp only [coeff_X, coeff_C], split_ifs; simp, }, { rw [charmatrix_apply_ne _ _ _ h, coeff_X, coeff_neg, coeff_C, coeff_C], split_ifs; simp [h], } end lemma charmatrix_reindex {m : Type v} [decidable_eq m] [fintype m] (e : n ≃ m) (M : matrix n n R) : charmatrix (reindex e e M) = reindex e e (charmatrix M) := begin ext i j x, by_cases h : i = j, all_goals { simp [h] } end /-- The characteristic polynomial of a matrix `M` is given by $\det (t I - M)$. -/ def matrix.charpoly (M : matrix n n R) : R[X] := (charmatrix M).det lemma matrix.charpoly_reindex {m : Type v} [decidable_eq m] [fintype m] (e : n ≃ m) (M : matrix n n R) : (reindex e e M).charpoly = M.charpoly := begin unfold matrix.charpoly, rw [charmatrix_reindex, matrix.det_reindex_self] end /-- The **Cayley-Hamilton Theorem**, that the characteristic polynomial of a matrix, applied to the matrix itself, is zero. This holds over any commutative ring. See `linear_map.aeval_self_charpoly` for the equivalent statement about endomorphisms. -/ -- This proof follows http://drorbn.net/AcademicPensieve/2015-12/CayleyHamilton.pdf theorem matrix.aeval_self_charpoly (M : matrix n n R) : aeval M M.charpoly = 0 := begin -- We begin with the fact $χ_M(t) I = adjugate (t I - M) * (t I - M)$, -- as an identity in `matrix n n R[X]`. have h : M.charpoly • (1 : matrix n n R[X]) = adjugate (charmatrix M) * (charmatrix M) := (adjugate_mul _).symm, -- Using the algebra isomorphism `matrix n n R[X] ≃ₐ[R] polynomial (matrix n n R)`, -- we have the same identity in `polynomial (matrix n n R)`. apply_fun mat_poly_equiv at h, simp only [mat_poly_equiv.map_mul, mat_poly_equiv_charmatrix] at h, -- Because the coefficient ring `matrix n n R` is non-commutative, -- evaluation at `M` is not multiplicative. -- However, any polynomial which is a product of the form $N * (t I - M)$ -- is sent to zero, because the evaluation function puts the polynomial variable -- to the right of any coefficients, so everything telescopes. apply_fun (λ p, p.eval M) at h, rw eval_mul_X_sub_C at h, -- Now $χ_M (t) I$, when thought of as a polynomial of matrices -- and evaluated at some `N` is exactly $χ_M (N)$. rw [mat_poly_equiv_smul_one, eval_map] at h, -- Thus we have $χ_M(M) = 0$, which is the desired result. exact h, end
1b5057694ea50ad8133c1efa804d8bd22889c224
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/meta/expr.lean
3ae73d40b014261b737201f6f02c37d2fefab08d
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
26,873
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- Returns the last non-numerical component of a name, or `"[anonymous]"` otherwise. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) namespace expr /-- Turns an expression into a positive natural number, assuming it is only built up from `has_one.one`, `bit0` and `bit1`. -/ protected meta def to_pos_nat : expr → option ℕ | `(has_one.one _) := some 1 | `(bit0 %%e) := bit0 <$> e.to_pos_nat | `(bit1 %%e) := bit1 <$> e.to_pos_nat | _ := none /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1` and `has_zero.zero`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- is_num_eq n1 n2 returns true if n1 and n2 are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- `instantiate_lambdas_or_apps 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. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxilliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the retulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` Use `environment.in_current_file'` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
8992b8e1533623e8ac0d01fad8ac52189b811642
4727251e0cd73359b15b664c3170e5d754078599
/src/combinatorics/quiver/subquiver.lean
812fff2a73b8eb1f12d17fa6823d0d37eb309f2c
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,477
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import data.set.basic import combinatorics.quiver.basic /-! ## Wide subquivers A wide subquiver `H` of a quiver `H` consists of a subset of the edge set `a ⟶ b` for every pair of vertices `a b : V`. We include 'wide' in the name to emphasize that these subquivers by definition contain all vertices. -/ universes v u /-- A wide subquiver `H` of `G` picks out a set `H a b` of arrows from `a` to `b` for every pair of vertices `a b`. NB: this does not work for `Prop`-valued quivers. It requires `G : quiver.{v+1} V`. -/ def wide_subquiver (V) [quiver.{v+1} V] := Π a b : V, set (a ⟶ b) /-- A type synonym for `V`, when thought of as a quiver having only the arrows from some `wide_subquiver`. -/ @[nolint unused_arguments has_inhabited_instance] def wide_subquiver.to_Type (V) [quiver V] (H : wide_subquiver V) : Type u := V instance wide_subquiver_has_coe_to_sort {V} [quiver V] : has_coe_to_sort (wide_subquiver V) (Type u) := { coe := λ H, wide_subquiver.to_Type V H } /-- A wide subquiver viewed as a quiver on its own. -/ instance wide_subquiver.quiver {V} [quiver V] (H : wide_subquiver V) : quiver H := ⟨λ a b, H a b⟩ namespace quiver instance {V} [quiver V] : has_bot (wide_subquiver V) := ⟨λ a b, ∅⟩ instance {V} [quiver V] : has_top (wide_subquiver V) := ⟨λ a b, set.univ⟩ instance {V} [quiver V] : inhabited (wide_subquiver V) := ⟨⊤⟩ /-- `total V` is the type of _all_ arrows of `V`. -/ -- TODO Unify with `category_theory.arrow`? (The fields have been named to match.) @[ext, nolint has_inhabited_instance] structure total (V : Type u) [quiver.{v} V] : Sort (max (u+1) v) := (left : V) (right : V) (hom : left ⟶ right) /-- A wide subquiver of `G` can equivalently be viewed as a total set of arrows. -/ def wide_subquiver_equiv_set_total {V} [quiver V] : wide_subquiver V ≃ set (total V) := { to_fun := λ H, { e | e.hom ∈ H e.left e.right }, inv_fun := λ S a b, { e | total.mk a b e ∈ S }, left_inv := λ H, rfl, right_inv := by { intro S, ext, cases x, refl } } /-- An `L`-labelling of a quiver assigns to every arrow an element of `L`. -/ def labelling (V : Type u) [quiver V] (L : Sort*) := Π ⦃a b : V⦄, (a ⟶ b) → L instance {V : Type u} [quiver V] (L) [inhabited L] : inhabited (labelling V L) := ⟨λ a b e, default⟩ end quiver
89ced3501218c6677ecafea49862bb662150c014
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/algebra/mul_action.lean
4f250aa67ba1ac73c408ae52741b767d500da55e
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
6,781
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 topology.algebra.constructions import group_theory.group_action.prod import group_theory.group_action.basic import topology.algebra.const_mul_action /-! # Continuous monoid action In this file we define class `has_continuous_smul`. We say `has_continuous_smul M X` if `M` acts on `X` and the map `(c, x) ↦ c • x` is continuous on `M × X`. We reuse this class for topological (semi)modules, vector spaces and algebras. ## Main definitions * `has_continuous_smul M X` : typeclass saying that the map `(c, x) ↦ c • x` is continuous on `M × X`; * `homeomorph.smul_of_ne_zero`: if a group with zero `G₀` (e.g., a field) acts on `X` and `c : G₀` is a nonzero element of `G₀`, then scalar multiplication by `c` is a homeomorphism of `X`; * `homeomorph.smul`: scalar multiplication by an element of a group `G` acting on `X` is a homeomorphism of `X`. * `units.has_continuous_smul`: scalar multiplication by `Mˣ` is continuous when scalar multiplication by `M` is continuous. This allows `homeomorph.smul` to be used with on monoids with `G = Mˣ`. ## Main results Besides homeomorphisms mentioned above, in this file we provide lemmas like `continuous.smul` or `filter.tendsto.smul` that provide dot-syntax access to `continuous_smul`. -/ open_locale topological_space pointwise open filter /-- Class `has_continuous_smul M X` says that the scalar multiplication `(•) : M → X → X` is continuous in both arguments. We use the same class for all kinds of multiplicative actions, including (semi)modules and algebras. -/ class has_continuous_smul (M X : Type*) [has_scalar M X] [topological_space M] [topological_space X] : Prop := (continuous_smul : continuous (λp : M × X, p.1 • p.2)) export has_continuous_smul (continuous_smul) /-- Class `has_continuous_vadd M X` says that the additive action `(+ᵥ) : M → X → X` is continuous in both arguments. We use the same class for all kinds of additive actions, including (semi)modules and algebras. -/ class has_continuous_vadd (M X : Type*) [has_vadd M X] [topological_space M] [topological_space X] : Prop := (continuous_vadd : continuous (λp : M × X, p.1 +ᵥ p.2)) export has_continuous_vadd (continuous_vadd) attribute [to_additive] has_continuous_smul section main variables {M X Y α : Type*} [topological_space M] [topological_space X] [topological_space Y] section has_scalar variables [has_scalar M X] [has_continuous_smul M X] @[priority 100, to_additive] instance has_continuous_smul.has_continuous_const_smul : has_continuous_const_smul M X := { continuous_const_smul := λ _, continuous_smul.comp (continuous_const.prod_mk continuous_id) } @[to_additive] lemma filter.tendsto.smul {f : α → M} {g : α → X} {l : filter α} {c : M} {a : X} (hf : tendsto f l (𝓝 c)) (hg : tendsto g l (𝓝 a)) : tendsto (λ x, f x • g x) l (𝓝 $ c • a) := (continuous_smul.tendsto _).comp (hf.prod_mk_nhds hg) @[to_additive] lemma filter.tendsto.smul_const {f : α → M} {l : filter α} {c : M} (hf : tendsto f l (𝓝 c)) (a : X) : tendsto (λ x, (f x) • a) l (𝓝 (c • a)) := hf.smul tendsto_const_nhds variables {f : Y → M} {g : Y → X} {b : Y} {s : set Y} @[to_additive] lemma continuous_within_at.smul (hf : continuous_within_at f s b) (hg : continuous_within_at g s b) : continuous_within_at (λ x, f x • g x) s b := hf.smul hg @[to_additive] lemma continuous_at.smul (hf : continuous_at f b) (hg : continuous_at g b) : continuous_at (λ x, f x • g x) b := hf.smul hg @[to_additive] lemma continuous_on.smul (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ x, f x • g x) s := λ x hx, (hf x hx).smul (hg x hx) @[continuity, to_additive] lemma continuous.smul (hf : continuous f) (hg : continuous g) : continuous (λ x, f x • g x) := continuous_smul.comp (hf.prod_mk hg) /-- If a scalar is central, then its right action is continuous when its left action is. -/ instance has_continuous_smul.op [has_scalar Mᵐᵒᵖ X] [is_central_scalar M X] : has_continuous_smul Mᵐᵒᵖ X := ⟨ suffices continuous (λ p : M × X, mul_opposite.op p.fst • p.snd), from this.comp (mul_opposite.continuous_unop.prod_map continuous_id), by simpa only [op_smul_eq_smul] using (continuous_smul : continuous (λ p : M × X, _)) ⟩ @[to_additive] instance mul_opposite.has_continuous_smul : has_continuous_smul M Xᵐᵒᵖ := ⟨mul_opposite.continuous_op.comp $ continuous_smul.comp $ continuous_id.prod_map mul_opposite.continuous_unop⟩ end has_scalar section monoid variables [monoid M] [mul_action M X] [has_continuous_smul M X] @[to_additive] instance units.has_continuous_smul : has_continuous_smul Mˣ X := { continuous_smul := show continuous ((λ p : M × X, p.fst • p.snd) ∘ (λ p : Mˣ × X, (p.1, p.2))), from continuous_smul.comp ((units.continuous_coe.comp continuous_fst).prod_mk continuous_snd) } end monoid @[to_additive] instance [has_scalar M X] [has_scalar M Y] [has_continuous_smul M X] [has_continuous_smul M Y] : has_continuous_smul M (X × Y) := ⟨(continuous_fst.smul (continuous_fst.comp continuous_snd)).prod_mk (continuous_fst.smul (continuous_snd.comp continuous_snd))⟩ @[to_additive] instance {ι : Type*} {γ : ι → Type*} [∀ i, topological_space (γ i)] [Π i, has_scalar M (γ i)] [∀ i, has_continuous_smul M (γ i)] : has_continuous_smul M (Π i, γ i) := ⟨continuous_pi $ λ i, (continuous_fst.smul continuous_snd).comp $ continuous_fst.prod_mk ((continuous_apply i).comp continuous_snd)⟩ end main section lattice_ops variables {ι : Sort*} {M X : Type*} [topological_space M] [has_scalar M X] @[to_additive] lemma has_continuous_smul_Inf {ts : set (topological_space X)} (h : Π t ∈ ts, @has_continuous_smul M X _ _ t) : @has_continuous_smul M X _ _ (Inf ts) := { continuous_smul := begin rw ← @Inf_singleton _ _ ‹topological_space M›, exact continuous_Inf_rng (λ t ht, continuous_Inf_dom₂ (eq.refl _) ht (@has_continuous_smul.continuous_smul _ _ _ _ t (h t ht))) end } @[to_additive] lemma has_continuous_smul_infi {ts' : ι → topological_space X} (h : Π i, @has_continuous_smul M X _ _ (ts' i)) : @has_continuous_smul M X _ _ (⨅ i, ts' i) := has_continuous_smul_Inf $ set.forall_range_iff.mpr h @[to_additive] lemma has_continuous_smul_inf {t₁ t₂ : topological_space X} [@has_continuous_smul M X _ _ t₁] [@has_continuous_smul M X _ _ t₂] : @has_continuous_smul M X _ _ (t₁ ⊓ t₂) := by { rw inf_eq_infi, refine has_continuous_smul_infi (λ b, _), cases b; assumption } end lattice_ops
3b859862d6d6f839d7a21789a6f37397d0530fb8
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/monoidal/free/coherence.lean
d7064e2d870d864eb2c1ac8a8e87362677db9d86
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
10,923
lean
/- Copyright (c) 2021 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.monoidal.free.basic import category_theory.discrete_category /-! # The monoidal coherence theorem In this file, we prove the monoidal coherence theorem, stated in the following form: the free monoidal category over any type `C` is thin. We follow a proof described by Ilya Beylin and Peter Dybjer, which has been previously formalized in the proof assistant ALF. The idea is to declare a normal form (with regard to association and adding units) on objects of the free monoidal category and consider the discrete subcategory of objects that are in normal form. A normalization procedure is then just a functor `full_normalize : free_monoidal_category C ⥤ discrete (normal_monoidal_object C)`, where functoriality says that two objects which are related by associators and unitors have the same normal form. Another desirable property of a normalization procedure is that an object is isomorphic (i.e., related via associators and unitors) to its normal form. In the case of the specific normalization procedure we use we not only get these isomorphismns, but also that they assemble into a natural isomorphism `𝟭 (free_monoidal_category C) ≅ full_normalize ⋙ inclusion`. But this means that any two parallel morphisms in the free monoidal category factor through a discrete category in the same way, so they must be equal, and hence the free monoidal category is thin. ## References * [Ilya Beylin and Peter Dybjer, Extracting a proof of coherence for monoidal categories from a proof of normalization for monoids][beylin1996] -/ universe u namespace category_theory open monoidal_category namespace free_monoidal_category variables {C : Type u} section variables (C) /-- We say an object in the free monoidal category is in normal form if it is of the form `(((𝟙_ C) ⊗ X₁) ⊗ X₂) ⊗ ⋯`. -/ @[nolint has_inhabited_instance] inductive normal_monoidal_object : Type u | unit : normal_monoidal_object | tensor : normal_monoidal_object → C → normal_monoidal_object end local notation `F` := free_monoidal_category local notation `N` := discrete ∘ normal_monoidal_object local infixr ` ⟶ᵐ `:10 := hom /-- Auxiliary definition for `inclusion`. -/ @[simp] def inclusion_obj : normal_monoidal_object C → F C | normal_monoidal_object.unit := unit | (normal_monoidal_object.tensor n a) := tensor (inclusion_obj n) (of a) /-- The discrete subcategory of objects in normal form includes into the free monoidal category. -/ @[simp] def inclusion : N C ⥤ F C := discrete.functor inclusion_obj /-- Auxiliary definition for `normalize`. -/ @[simp] def normalize_obj : F C → normal_monoidal_object C → normal_monoidal_object C | unit n := n | (of X) n := normal_monoidal_object.tensor n X | (tensor X Y) n := normalize_obj Y (normalize_obj X n) @[simp] lemma normalize_obj_unitor (n : N C) : normalize_obj (𝟙_ (F C)) n = n := rfl @[simp] lemma normalize_obj_tensor (X Y : F C) (n : N C) : normalize_obj (X ⊗ Y) n = normalize_obj Y (normalize_obj X n) := rfl section open hom /-- Auxiliary definition for `normalize`. Here we prove that objects that are related by associators and unitors map to the same normal form. -/ @[simp] def normalize_map_aux : Π {X Y : F C}, (X ⟶ᵐ Y) → ((discrete.functor (normalize_obj X) : _ ⥤ N C) ⟶ discrete.functor (normalize_obj Y)) | _ _ (id _) := 𝟙 _ | _ _ (α_hom _ _ _) := ⟨λ X, 𝟙 _⟩ | _ _ (α_inv _ _ _) := ⟨λ X, 𝟙 _⟩ | _ _ (l_hom _) := ⟨λ X, 𝟙 _⟩ | _ _ (l_inv _) := ⟨λ X, 𝟙 _⟩ | _ _ (ρ_hom _) := ⟨λ X, 𝟙 _⟩ | _ _ (ρ_inv _) := ⟨λ X, 𝟙 _⟩ | X Y (@comp _ U V W f g) := normalize_map_aux f ≫ normalize_map_aux g | X Y (@hom.tensor _ T U V W f g) := ⟨λ X, (normalize_map_aux g).app (normalize_obj T X) ≫ (discrete.functor (normalize_obj W) : _ ⥤ N C).map ((normalize_map_aux f).app X), by tidy⟩ end section variables (C) /-- Our normalization procedure works by first defining a functor `F C ⥤ (N C ⥤ N C)` (which turns out to be very easy), and then obtain a functor `F C ⥤ N C` by plugging in the normal object `𝟙_ C`. -/ @[simp] def normalize : F C ⥤ N C ⥤ N C := { obj := λ X, discrete.functor (normalize_obj X), map := λ X Y, quotient.lift normalize_map_aux (by tidy) } /-- A variant of the normalization functor where we consider the result as an object in the free monoidal category (rather than an object of the discrete subcategory of objects in normal form). -/ @[simp] def normalize' : F C ⥤ N C ⥤ F C := normalize C ⋙ (whiskering_right _ _ _).obj inclusion /-- The normalization functor for the free monoidal category over `C`. -/ def full_normalize : F C ⥤ N C := { obj := λ X, ((normalize C).obj X).obj normal_monoidal_object.unit, map := λ X Y f, ((normalize C).map f).app normal_monoidal_object.unit } /-- Given an object `X` of the free monoidal category and an object `n` in normal form, taking the tensor product `n ⊗ X` in the free monoidal category is functorial in both `X` and `n`. -/ @[simp] def tensor_func : F C ⥤ N C ⥤ F C := { obj := λ X, discrete.functor (λ n, (inclusion.obj n) ⊗ X), map := λ X Y f, ⟨λ n, 𝟙 _ ⊗ f, by tidy⟩ } lemma tensor_func_map_app {X Y : F C} (f : X ⟶ Y) (n) : ((tensor_func C).map f).app n = 𝟙 _ ⊗ f := rfl lemma tensor_func_obj_map (Z : F C) {n n' : N C} (f : n ⟶ n') : ((tensor_func C).obj Z).map f = inclusion.map f ⊗ 𝟙 Z := by tidy /-- Auxiliary definition for `normalize_iso`. Here we construct the isomorphism between `n ⊗ X` and `normalize X n`. -/ @[simp] def normalize_iso_app : Π (X : F C) (n : N C), ((tensor_func C).obj X).obj n ≅ ((normalize' C).obj X).obj n | (of X) n := iso.refl _ | unit n := ρ_ _ | (tensor X Y) n := (α_ _ _ _).symm ≪≫ tensor_iso (normalize_iso_app X n) (iso.refl _) ≪≫ normalize_iso_app _ _ @[simp] lemma normalize_iso_app_tensor (X Y : F C) (n : N C) : normalize_iso_app C (X ⊗ Y) n = (α_ _ _ _).symm ≪≫ tensor_iso (normalize_iso_app C X n) (iso.refl _) ≪≫ normalize_iso_app _ _ _ := rfl @[simp] lemma normalize_iso_app_unitor (n : N C) : normalize_iso_app C (𝟙_ (F C)) n = ρ_ _ := rfl /-- Auxiliary definition for `normalize_iso`. -/ @[simp] def normalize_iso_aux (X : F C) : (tensor_func C).obj X ≅ (normalize' C).obj X := nat_iso.of_components (normalize_iso_app C X) (by tidy) /-- The isomorphism between `n ⊗ X` and `normalize X n` is natural (in both `X` and `n`, but naturality in `n` is trivial and was "proved" in `normalize_iso_aux`). This is the real heart of our proof of the coherence theorem. -/ def normalize_iso : tensor_func C ≅ normalize' C := nat_iso.of_components (normalize_iso_aux C) begin rintros X Y f, apply quotient.induction_on f, intro f, ext n, induction f generalizing n, { simp only [mk_id, functor.map_id, category.id_comp, category.comp_id] }, { dsimp, simp only [id_tensor_associator_inv_naturality_assoc, ←pentagon_inv_assoc, tensor_hom_inv_id_assoc, tensor_id, category.id_comp, discrete.functor_map_id, comp_tensor_id, iso.cancel_iso_inv_left, category.assoc], dsimp, simp only [category.comp_id] }, { dsimp, simp only [discrete.functor_map_id, comp_tensor_id, category.assoc, pentagon_inv_assoc, ←associator_inv_naturality_assoc, tensor_id, iso.cancel_iso_inv_left], dsimp, simp only [category.comp_id],}, { dsimp, rw triangle_assoc_comp_right_assoc, simp only [discrete.functor_map_id, category.assoc], dsimp, simp only [category.comp_id] }, { dsimp, simp only [triangle_assoc_comp_left_inv_assoc, inv_hom_id_tensor_assoc, tensor_id, category.id_comp, discrete.functor_map_id], dsimp, simp only [category.comp_id] }, { dsimp, rw [←(iso.inv_comp_eq _).2 (right_unitor_tensor _ _), category.assoc, ←right_unitor_naturality], simp only [discrete.functor_map_id, iso.cancel_iso_inv_left, category.assoc], dsimp, simp only [category.comp_id] }, { dsimp, simp only [←(iso.eq_comp_inv _).1 (right_unitor_tensor_inv _ _), iso.hom_inv_id_assoc, right_unitor_conjugation, discrete.functor_map_id, category.assoc], dsimp, simp only [category.comp_id], }, { dsimp at *, rw [id_tensor_comp, category.assoc, f_ih_g ⟦f_g⟧, ←category.assoc, f_ih_f ⟦f_f⟧, category.assoc, ←functor.map_comp], congr' 2 }, { dsimp at *, rw associator_inv_naturality_assoc, slice_lhs 2 3 { rw [←tensor_comp, f_ih_f ⟦f_f⟧] }, conv_lhs { rw [←@category.id_comp (F C) _ _ _ ⟦f_g⟧] }, simp only [category.comp_id, tensor_comp, category.assoc], congr' 2, rw [←mk_tensor, quotient.lift_mk], dsimp, rw [functor.map_comp, ←category.assoc, ←f_ih_g ⟦f_g⟧, ←@category.comp_id (F C) _ _ _ ⟦f_g⟧, ←category.id_comp ((discrete.functor inclusion_obj).map _), tensor_comp], dsimp, simp only [category.assoc, category.comp_id], congr' 1, convert (normalize_iso_aux C f_Z).hom.naturality ((normalize_map_aux f_f).app n), exact (tensor_func_obj_map _ _ _).symm } end /-- The isomorphism between an object and its normal form is natural. -/ def full_normalize_iso : 𝟭 (F C) ≅ full_normalize C ⋙ inclusion := nat_iso.of_components (λ X, (λ_ X).symm ≪≫ ((normalize_iso C).app X).app normal_monoidal_object.unit) begin intros X Y f, dsimp, rw [left_unitor_inv_naturality_assoc, category.assoc, iso.cancel_iso_inv_left], exact congr_arg (λ f, nat_trans.app f normal_monoidal_object.unit) ((normalize_iso.{u} C).hom.naturality f), end end /-- The monoidal coherence theorem. -/ instance subsingleton_hom {X Y : F C} : subsingleton (X ⟶ Y) := ⟨λ f g, have (full_normalize C).map f = (full_normalize C).map g, from subsingleton.elim _ _, begin rw [←functor.id_map f, ←functor.id_map g], simp [←nat_iso.naturality_2 (full_normalize_iso.{u} C), this] end⟩ section groupoid section open hom /-- Auxiliary construction for showing that the free monoidal category is a groupoid. Do not use this, use `is_iso.inv` instead. -/ def inverse_aux : Π {X Y : F C}, (X ⟶ᵐ Y) → (Y ⟶ᵐ X) | _ _ (id X) := id X | _ _ (α_hom _ _ _) := α_inv _ _ _ | _ _ (α_inv _ _ _) := α_hom _ _ _ | _ _ (ρ_hom _) := ρ_inv _ | _ _ (ρ_inv _) := ρ_hom _ | _ _ (l_hom _) := l_inv _ | _ _ (l_inv _) := l_hom _ | _ _ (comp f g) := (inverse_aux g).comp (inverse_aux f) | _ _ (hom.tensor f g) := (inverse_aux f).tensor (inverse_aux g) end instance : groupoid.{u} (F C) := { inv := λ X Y, quotient.lift (λ f, ⟦inverse_aux f⟧) (by tidy), ..(infer_instance : category (F C)) } end groupoid end free_monoidal_category end category_theory
9fce9fd5bc00feae2bc65b1aa763b774352368bd
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/omega/nat/preterm.lean
b05bc0c7b163d02a57994a07aaaeb43b7a56ceec
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
4,881
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ /- Linear natural number arithmetic terms in pre-normalized form. -/ import tactic.omega.term open tactic namespace omega namespace nat /-- The shadow syntax for arithmetic terms. All constants are reified to `cst` (e.g., `5` is reified to `cst 5`) and all other atomic terms are reified to `exp` (e.g., `5 * (list.length l)` is reified to `exp 5 \`(list.length l)`). `exp` accepts a coefficient of type `nat` as its first argument because multiplication by constant is allowed by the omega test. -/ meta inductive exprterm : Type | cst : nat → exprterm | exp : nat → expr → exprterm | add : exprterm → exprterm → exprterm | sub : exprterm → exprterm → exprterm /-- Similar to `exprterm`, except that all exprs are now replaced with de Brujin indices of type `nat`. This is akin to generalizing over the terms represented by the said exprs. -/ @[derive has_reflect, derive decidable_eq, derive inhabited] inductive preterm : Type | cst : nat → preterm | var : nat → nat → preterm | add : preterm → preterm → preterm | sub : preterm → preterm → preterm localized "notation `&` k := omega.nat.preterm.cst k" in omega.nat localized "infix ` ** ` : 300 := omega.nat.preterm.var" in omega.nat localized "notation t ` +* ` s := omega.nat.preterm.add t s" in omega.nat localized "notation t ` -* ` s := omega.nat.preterm.sub t s" in omega.nat namespace preterm /-- Helper tactic for proof by induction over preterms -/ meta def induce (tac : tactic unit := tactic.skip) : tactic unit := `[ intro t, induction t with m m n t s iht ihs t s iht ihs; tac] /-- Preterm evaluation -/ def val (v : nat → nat) : preterm → nat | (& i) := i | (i ** n) := if i = 1 then v n else (v n) * i | (t1 +* t2) := t1.val + t2.val | (t1 -* t2) := t1.val - t2.val @[simp] lemma val_const {v : nat → nat} {m : nat} : (& m).val v = m := rfl @[simp] lemma val_var {v : nat → nat} {m n : nat} : (m ** n).val v = m * (v n) := begin simp only [val], by_cases h1 : m = 1, rw [if_pos h1, h1, one_mul], rw [if_neg h1, mul_comm], end @[simp] lemma val_add {v : nat → nat} {t s : preterm} : (t +* s).val v = t.val v + s.val v := rfl @[simp] lemma val_sub {v : nat → nat} {t s : preterm} : (t -* s).val v = t.val v - s.val v := rfl /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_index t2.fresh_index | (t1 -* t2) := max t1.fresh_index t2.fresh_index /-- If variable assignments `v` and `w` agree on all variables that occur in term `t`, the value of `t` under `v` and `w` are identical. -/ lemma val_constant (v w : nat → nat) : ∀ t : preterm, (∀ x < t.fresh_index, v x = w x) → t.val v = t.val w | (& n) h1 := rfl | (m ** n) h1 := begin simp only [val_var], apply congr_arg (λ y, m * y), apply h1 _ (lt_add_one _) end | (t +* s) h1 := begin simp only [val_add], have ht := val_constant t (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_left _ _))), have hs := val_constant s (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_right _ _))), rw [ht, hs] end | (t -* s) h1 := begin simp only [val_sub], have ht := val_constant t (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_left _ _))), have hs := val_constant s (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_right _ _))), rw [ht, hs] end def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" | (t1 -* t2) := "(" ++ t1.repr ++ " - " ++ t2.repr ++ ")" @[simp] def add_one (t : preterm) : preterm := t +* (&1) /-- Preterm is free of subtractions -/ def sub_free : preterm → Prop | (& m) := true | (m ** n) := true | (t +* s) := t.sub_free ∧ s.sub_free | (_ -* _) := false end preterm open_locale list.func -- get notation for list.func.set /-- Return a term (which is in canonical form by definition) that is equivalent to the input preterm -/ @[simp] def canonize : preterm → term | (& m) := ⟨↑m, []⟩ | (m ** n) := ⟨0, [] {n ↦ ↑m}⟩ | (t +* s) := term.add (canonize t) (canonize s) | (_ -* _) := ⟨0, []⟩ @[simp] lemma val_canonize {v : nat → nat} : ∀ {t : preterm}, t.sub_free → (canonize t).val (λ x, ↑(v x)) = t.val v | (& i) h1 := by simp only [canonize, preterm.val_const, term.val, coeffs.val_nil, add_zero] | (i ** n) h1 := by simp only [preterm.val_var, coeffs.val_set, term.val, zero_add, int.coe_nat_mul, canonize] | (t +* s) h1 := by simp only [val_canonize h1.left, val_canonize h1.right, int.coe_nat_add, canonize, term.val_add, preterm.val_add] end nat end omega
3110c537d7ad02de8c12cb0554d00ad126c6e042
c3de33d4701e6113627153fe1103b255e752ed7d
/data/list/comb.lean
2d3886cd05b571c84a21b373ee2f24619b68dab0
[]
no_license
jroesch/library_dev
77d2b246ff47ab05d55cb9706a37d3de97038388
4faa0a45c6aa7eee6e661113c2072b8840bff79b
refs/heads/master
1,611,281,606,352
1,495,661,644,000
1,495,661,644,000
92,340,430
0
0
null
1,495,663,344,000
1,495,663,344,000
null
UTF-8
Lean
false
false
22,330
lean
/- Copyright (c) 2015 Leonardo de Moura. all rights reserved. Released under Apache 2.0 license as described in the file LICENSE. αuthors: Leonardo de Moura, Haitao Zhang, Floris van Doorn, Jeremy Avigad List combinators. -/ -- TODO(Leo): uncomment data.equiv after refactoring import .basic ..bool data.list.comb --data.bool logic.basic -- data.equiv open nat prod decidable function namespace list universe variables uu vv ww variables {α : Type uu} {β : Type vv} {γ : Type ww} -- TODO(Jeremy): this file is a good testing ground for super and auto section replicate -- 'replicate n a' returns the list that contains n copies of a. def replicate : ℕ → α → list α | 0 a := [] | (succ n) a := a :: replicate n a @[simp] theorem length_replicate : ∀ (i : ℕ) (a : α), length (replicate i a) = i | 0 a := rfl | (succ i) a := congr_arg succ (length_replicate i a) end replicate /- map -/ attribute [simp] map_cons /-def map₂ (f : α → β → γ) : list α → list β → list γ | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys-/ theorem map₂_nil1 (f : α → β → γ) : ∀ (l : list β), map₂ f [] l = [] | [] := rfl | (a::y) := rfl theorem map₂_nil2 (f : α → β → γ) : ∀ (l : list α), map₂ f l [] = [] | [] := rfl | (a::y) := rfl /- TODO(Jeremy): there is an overload ambiguity between min and nat.min -/ /-theorem length_map₂ : ∀ (f : α → β → γ) x y, length (map₂ f x y) = _root_.min (length x) (length y) | f [] [] := rfl | f (xh::xr) [] := rfl | f [] (yh::yr) := rfl | f (xh::xr) (yh::yr) := calc length (map₂ f (xh::xr) (yh::yr)) = length (map₂ f xr yr) + 1 : rfl ... = _root_.min (length xr) (length yr) + 1 : by rw length_map₂ ... = _root_.min (succ (length xr)) (succ (length yr)) : begin rw min_succ_succ, reflexivity end ... = _root_.min (length (xh::xr)) (length (yh::yr)) : rfl-/ /- filter -/ @[simp] theorem filter_nil (p : α → Prop) [h : decidable_pred p] : filter p [] = [] := rfl @[simp] theorem filter_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, p a → filter p (a::l) = a :: filter p l := λ l pa, if_pos pa @[simp] theorem filter_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, ¬ p a → filter p (a::l) = filter p l := λ l pa, if_neg pa theorem of_mem_filter {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ {l}, a ∈ filter p l → p a | [] ain := absurd ain (not_mem_nil a) | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, begin simp [pb] at ain, assumption end, or.elim (eq_or_mem_of_mem_cons this) (suppose a = b, begin rw -this at pb, exact pb end) (suppose a ∈ filter p l, of_mem_filter this) else begin simp [pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ {l}, a ∈ filter p l → a ∈ l | [] ain := absurd ain (not_mem_nil a) | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, begin simp [pb] at ain, assumption end, or.elim (eq_or_mem_of_mem_cons this) (suppose a = b, by simp [this]) (suppose a ∈ filter p l, by simp [mem_of_mem_filter this]) else begin simp [pb] at ain, simp [mem_of_mem_filter ain] end theorem mem_filter_of_mem {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | [] ain pa := absurd ain (not_mem_nil a) | (b::l) ain pa := if pb : p b then or.elim (eq_or_mem_of_mem_cons ain) (suppose a = b, by simp [pb, this]) (suppose a ∈ l, begin simp [pb], exact (mem_cons_of_mem _ (mem_filter_of_mem this pa)) end) else or.elim (eq_or_mem_of_mem_cons ain) (suppose a = b, begin simp [this] at pa, contradiction end) --absurd (this ▸ pa) pb) (suppose a ∈ l, by simp [pa, pb, mem_filter_of_mem this]) @[simp] theorem filter_sub {p : α → Prop} [h : decidable_pred p] (l : list α) : filter p l ⊆ l := λ a ain, mem_of_mem_filter ain @[simp] theorem filter_append {p : α → Prop} [h : decidable_pred p] : ∀ (l₁ l₂ : list α), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂ | [] l₂ := rfl | (a::l₁) l₂ := if pa : p a then by simp [pa, filter_append] else by simp [pa, filter_append] section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : ∀ a b, f a b = f b a) (hassoc : ∀ a b c, f (f a b) c = f a (f b c)) include hcomm hassoc theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := begin change foldl f (f (f a b) c) l = f b (foldl f (f a c) l), rw -foldl_eq_of_comm_of_assoc, change foldl f (f (f a b) c) l = foldl f (f (f a c) b) l, have h₁ : f (f a b) c = f (f a c) b, by rw [hassoc, hassoc, hcomm b c], by rw h₁ end theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := begin simp [foldl_eq_of_comm_of_assoc hcomm hassoc], change f b (foldl f a l) = f b (foldr f a l), rw (foldl_eq_foldr a l) end end foldl_eq_foldr /- all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_eq_tt_of_forall {p : α → bool} : ∀ {l : list α}, (∀ a ∈ l, p a = tt) → all l p = tt | [] h := all_nil p | (a::l) h := begin simp [all_cons, h a], rw all_eq_tt_of_forall, intros a ha, simp [h a, ha] end theorem forall_mem_eq_tt_of_all_eq_tt {p : α → bool} : ∀ {l : list α}, all l p = tt → ∀ a ∈ l, p a = tt | [] h := take a h, absurd h (not_mem_nil a) | (b::l) h := take a, suppose a ∈ b::l, begin simp [bool.band_eq_tt] at h, cases h with h₁ h₂, simp at this, cases this with h' h', simp_using_hs, exact forall_mem_eq_tt_of_all_eq_tt h₂ _ h' end theorem all_eq_tt_iff {p : α → bool} {l : list α} : all l p = tt ↔ ∀ a ∈ l, p a = tt := iff.intro forall_mem_eq_tt_of_all_eq_tt all_eq_tt_of_forall @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_of_mem {p : α → bool} {a : α} : ∀ {l : list α}, a ∈ l → p a = tt → any l p = tt | [] i h := absurd i (not_mem_nil a) | (b::l) i h := or.elim (eq_or_mem_of_mem_cons i) (suppose a = b, begin simp [this^.symm, bool.bor_eq_tt], exact (or.inl h) end) (suppose a ∈ l, begin cases (eq_or_mem_of_mem_cons i) with h' h', { simp [h'^.symm, h] }, simp [bool.bor_eq_tt, any_of_mem h', h] end) theorem exists_of_any_eq_tt {p : α → bool} : ∀ {l : list α}, any l p = tt → ∃ a : α, a ∈ l ∧ p a | [] h := begin simp at h, contradiction end | (b::l) h := begin simp [bool.bor_eq_tt] at h, cases h with h h, { existsi b, simp [h]}, cases (exists_of_any_eq_tt h) with a ha, existsi a, apply (and.intro (or.inr ha^.left) ha^.right) end theorem any_eq_tt_iff {p : α → bool} {l : list α} : any l p = tt ↔ ∃ a : α, a ∈ l ∧ p a = tt := iff.intro exists_of_any_eq_tt (begin intro h, cases h with a ha, apply any_of_mem ha^.left ha^.right end) /- bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x := take x xnil, absurd xnil (not_mem_nil x) theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} (pa : p a) (h : ∀ x ∈ l, p x) : ∀ x ∈ a :: l, p x := take x xal, or.elim (eq_or_mem_of_mem_cons xal) (suppose x = a, by simp [this, pa]) (suppose x ∈ l, by simp [this, h]) theorem of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : p a := h a (by simp) theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := take x xl, h x (by simp [xl]) @[simp] theorem forall_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := iff.intro (λ h, ⟨of_forall_mem_cons h, forall_mem_of_forall_mem_cons h⟩) (λ h, forall_mem_cons h^.left h^.right) theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x := assume h, bexists.elim h (λ a anil, absurd anil (not_mem_nil a)) theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bexists.intro a (by simp) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bexists.elim h (λ x xl px, bexists.intro x (by simp [xl]) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bexists.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (suppose x = a, begin rw -this, simp [px] end) (suppose x ∈ l, or.inr (bexists.intro x this px))) @[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) @[instance] def decidable_forall_mem {p : α → Prop} [h : decidable_pred p] : ∀ l : list α, decidable (∀ x ∈ l, p x) | [] := is_true (forall_mem_nil p) | (a :: l) := decidable_of_decidable_of_iff (@and.decidable _ _ _ (decidable_forall_mem l)) (forall_mem_cons_iff p a l)^.symm @[instance] def decidable_exists_mem {p : α → Prop} [h : decidable_pred p] : ∀ l : list α, decidable (∃ x ∈ l, p x) | [] := is_false (not_exists_mem_nil p) | (a :: l) := decidable_of_decidable_of_iff (@or.decidable _ _ _ (decidable_exists_mem l)) (exists_mem_cons_iff p a l)^.symm /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := begin cases l, reflexivity, reflexivity end @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl theorem unzip_cons' (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = match (unzip l) with (la, lb) := (a :: la, b :: lb) end := rfl -- TODO(Jeremy): it seems this version is better for the simplifier @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = let p := unzip l in (a :: p.1, b :: p.2) := begin rw unzip_cons', cases unzip l, reflexivity end theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := begin simp [zip_unzip l] end -- TODO(Jeremy): this is as far as I got section mapαccumR variable {S : Type} -- This runs a function over a list returning the intermediate results and a -- a final result. def mapαccumR : (α → S → S × β) → list α → S → (S × list β) | f [] c := (c, []) | f (y::yr) c := let r := mapαccumR f yr c in let z := f y r.1 in (z.1, z.2 :: r.2) theorem length_mapαccumR : ∀ (f : α → S → S × β) (x : list α) (s : S), length (mapαccumR f x s).2 = length x | f (a::x) s := calc length (snd (mapαccumR f (a::x) s)) = length x + 1 : begin rw -(length_mapαccumR f x s), reflexivity end ... = length (a::x) : rfl | f [] s := calc length (snd (mapαccumR f [] s)) = 0 : by reflexivity end mapαccumR section mapαccumR₂ variable {S : Type uu} -- This runs a function over two lists returning the intermediate results and a -- a final result. def mapαccumR₂ : (α → β → S → S × γ) → list α → list β → S → S × list γ | f [] _ c := (c,[]) | f _ [] c := (c,[]) | f (x::xr) (y::yr) c := let r := mapαccumR₂ f xr yr c in let q := f x y r.1 in (q.1, q.2 :: r.2) -- TODO(Jeremy) : again the "min" overload theorem length_mapαccumR₂ : ∀ (f : α → β → S → S × γ) (x : list α) (y : list β) (c : S), length (mapαccumR₂ f x y c).2 = _root_.min (length x) (length y) | f (a::x) (b::y) c := calc length (snd (mapαccumR₂ f (a::x) (b::y) c)) = length (snd (mapαccumR₂ f x y c)) + 1 : rfl ... = _root_.min (length x) (length y) + 1 : by rw (length_mapαccumR₂ f x y c) ... = _root_.min (succ (length x)) (succ (length y)) : begin rw min_succ_succ end ... = _root_.min (length (a::x)) (length (b::y)) : rfl | f (a::x) [] c := rfl | f [] (b::y) c := rfl | f [] [] c := rfl end mapαccumR₂ /- flat -/ def flat (l : list (list α)) : list α := foldl append nil l /- product -/ section product def product : list α → list β → list (α × β) | [] l₂ := [] | (a::l₁) l₂ := map (λ b, (a, b)) l₂ ++ product l₁ l₂ theorem nil_product (l : list β) : product (@nil α) l = [] := rfl theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := begin rw [product_cons, product_nil], reflexivity end theorem eq_of_mem_map_pair₁ {a₁ a : α} {b₁ : β} {l : list β} : (a₁, b₁) ∈ map (λ b, (a, b)) l → a₁ = a := assume ain, have fst (a₁, b₁) ∈ map fst (map (λ b, (a, b)) l), from mem_map fst ain, have a₁ ∈ map (λb, a) l, begin revert this, rw [map_map], intro this, assumption end, eq_of_map_const this theorem mem_of_mem_map_pair₁ {a₁ a : α} {b₁ : β} {l : list β} : (a₁, b₁) ∈ map (λ b, (a, b)) l → b₁ ∈ l := assume ain, have snd (a₁, b₁) ∈ map snd (map (λ b, (a, b)) l), from mem_map snd ain, have b₁ ∈ map id l, begin rw [map_map] at this, exact this end, begin rw [map_id] at this, exact this end theorem mem_product {a : α} {b : β} : ∀ {l₁ l₂}, a ∈ l₁ → b ∈ l₂ → (a, b) ∈ @product α β l₁ l₂ | [] l₂ h₁ h₂ := absurd h₁ (not_mem_nil _) | (x::l₁) l₂ h₁ h₂ := or.elim (eq_or_mem_of_mem_cons h₁) (assume aeqx : a = x, have (a, b) ∈ map (λ b, (a, b)) l₂, from mem_map _ h₂, begin rw [-aeqx, product_cons], exact mem_append_left _ this end) (assume ainl₁ : a ∈ l₁, have (a, b) ∈ product l₁ l₂, from mem_product ainl₁ h₂, begin rw [product_cons], exact mem_append_right _ this end) theorem mem_of_mem_product_left {a : α} {b : β} : ∀ {l₁ l₂}, (a, b) ∈ @product α β l₁ l₂ → a ∈ l₁ | [] l₂ h := absurd h (not_mem_nil _) | (x::l₁) l₂ h := or.elim (mem_or_mem_of_mem_append h) (suppose (a, b) ∈ map (λ b, (x, b)) l₂, have a = x, from eq_of_mem_map_pair₁ this, begin rw this, apply mem_cons_self end) (suppose (a, b) ∈ product l₁ l₂, have a ∈ l₁, from mem_of_mem_product_left this, mem_cons_of_mem _ this) theorem mem_of_mem_product_right {a : α} {b : β} : ∀ {l₁ l₂}, (a, b) ∈ @product α β l₁ l₂ → b ∈ l₂ | [] l₂ h := absurd h (not_mem_nil ((a, b))) | (x::l₁) l₂ h := or.elim (mem_or_mem_of_mem_append h) (suppose (a, b) ∈ map (λ b, (x, b)) l₂, mem_of_mem_map_pair₁ this) (suppose (a, b) ∈ product l₁ l₂, mem_of_mem_product_right this) theorem length_product : ∀ (l₁ : list α) (l₂ : list β), length (product l₁ l₂) = length l₁ * length l₂ | [] l₂ := begin simp, reflexivity end | (x::l₁) l₂ := have length (product l₁ l₂) = length l₁ * length l₂, from length_product l₁ l₂, by rw [product_cons, length_append, length_cons, length_map, this, right_distrib, one_mul, add_comm] end product -- new for list/comb dependent map theory def dinj₁ (p : α → Prop) (f : Π a, p a → β) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), a1 ≠ a2 → (f a1 h1) ≠ (f a2 h2) def dinj (p : α → Prop) (f : Π a, p a → β) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), (f a1 h1) = (f a2 h2) → a1 = a2 def dmap (p : α → Prop) [h : decidable_pred p] (f : Π a, p a → β) : list α → list β | [] := [] | (a::l) := if P : (p a) then cons (f a P) (dmap l) else (dmap l) -- properties of dmap section dmap variable {p : α → Prop} variable [h : decidable_pred p] include h variable {f : Π a, p a → β} lemma dmap_nil : dmap p f [] = [] := rfl lemma dmap_cons_of_pos {a : α} (P : p a) : ∀ l, dmap p f (a::l) = (f a P) :: dmap p f l := λ l, dif_pos P lemma dmap_cons_of_neg {a : α} (P : ¬ p a) : ∀ l, dmap p f (a::l) = dmap p f l := λ l, dif_neg P lemma mem_dmap : ∀ {l : list α} {a} (Pa : p a), a ∈ l → (f a Pa) ∈ dmap p f l | [] := take a Pa Pinnil, absurd Pinnil (not_mem_nil _) | (a::l) := take b Pb Pbin, or.elim (eq_or_mem_of_mem_cons Pbin) (assume Pbeqa, begin rw [eq.symm Pbeqa, dmap_cons_of_pos Pb], apply mem_cons_self end) (assume Pbinl, if pa : p a then begin rw [dmap_cons_of_pos pa], apply mem_cons_of_mem, exact mem_dmap Pb Pbinl end else begin rw [dmap_cons_of_neg pa], exact mem_dmap Pb Pbinl end) lemma exists_of_mem_dmap : ∀ {l : list α} {b : β}, b ∈ dmap p f l → ∃ a P, a ∈ l ∧ b = f a P | [] := take b, begin rw dmap_nil, intro h, exact absurd h (not_mem_nil _) end | (a::l) := take b, if Pa : p a then begin rw [dmap_cons_of_pos Pa, mem_cons_iff], intro Pb, cases Pb with Peq Pin, exact exists.intro a (exists.intro Pa (and.intro (mem_cons_self _ _) Peq)), assert Pex : ∃ (a : α) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin, cases Pex with a' Pex', cases Pex' with Pa' P', exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P'))) end else begin rw [dmap_cons_of_neg Pa], intro Pin, assert Pex : ∃ (a : α) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin, cases Pex with a' Pex', cases Pex' with Pa' P', exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P'))) end lemma map_dmap_of_inv_of_pos {g : β → α} (Pinv : ∀ a (Pa : p a), g (f a Pa) = a) : ∀ {l : list α}, (∀ ⦃a⦄, a ∈ l → p a) → map g (dmap p f l) = l | [] := assume Pl, by rw [dmap_nil]; reflexivity | (a::l) := assume Pal, have Pa : p a, from Pal (mem_cons_self _ _), have Pl : ∀ a, a ∈ l → p a, from take x Pxin, Pal (mem_cons_of_mem a Pxin), by rw [dmap_cons_of_pos Pa, map_cons, Pinv, map_dmap_of_inv_of_pos Pl] lemma mem_of_dinj_of_mem_dmap (Pdi : dinj p f) : ∀ {l : list α} {a} (Pa : p a), (f a Pa) ∈ dmap p f l → a ∈ l | [] := take a Pa Pinnil, absurd Pinnil (not_mem_nil _) | (b::l) := take a Pa Pmap, if Pb : p b then begin rw (dmap_cons_of_pos Pb) at Pmap, rw mem_cons_iff at Pmap, rw mem_cons_iff, cases Pmap with h h, left, apply Pdi Pa Pb h, right, apply mem_of_dinj_of_mem_dmap Pa h end else begin rw (dmap_cons_of_neg Pb) at Pmap, apply mem_cons_of_mem, exact mem_of_dinj_of_mem_dmap Pa Pmap end lemma not_mem_dmap_of_dinj_of_not_mem (Pdi : dinj p f) {l : list α} {a} (Pa : p a) : a ∉ l → (f a Pa) ∉ dmap p f l := contrapos (mem_of_dinj_of_mem_dmap Pdi Pa) end dmap /- section open equiv def list_equiv_of_equiv {α β : Type} : α ≃ β → list α ≃ list β | (mk f g l r) := mk (map f) (map g) begin intros, rw [map_map, id_of_left_inverse l, map_id], try reflexivity end begin intros, rw [map_map, id_of_right_inverse r, map_id], try reflexivity end private def to_nat : list nat → nat | [] := 0 | (x::xs) := succ (mkpair (to_nat xs) x) open prod.ops private def of_nat.F : Π (n : nat), (Π m, m < n → list nat) → list nat | 0 f := [] | (succ n) f := (unpair n).2 :: f (unpair n).1 (unpair_lt n) private def of_nat : nat → list nat := well_founded.fix of_nat.F private lemma of_nat_zero : of_nat 0 = [] := well_founded.fix_eq of_nat.F 0 private lemma of_nat_succ (n : nat) : of_nat (succ n) = (unpair n).2 :: of_nat (unpair n).1 := well_founded.fix_eq of_nat.F (succ n) private lemma to_nat_of_nat (n : nat) : to_nat (of_nat n) = n := nat.case_strong_induction_on n _ (λ n ih, begin rw of_nat_succ, unfold to_nat, have to_nat (of_nat (unpair n).1) = (unpair n).1, from ih _ (le_of_lt_succ (unpair_lt n)), rw this, rw mkpair_unpair end) private lemma of_nat_to_nat : ∀ (l : list nat), of_nat (to_nat l) = l | [] := rfl | (x::xs) := begin unfold to_nat, rw of_nat_succ, rw *unpair_mkpair, esimp, congruence, apply of_nat_to_nat end def list_nat_equiv_nat : list nat ≃ nat := mk to_nat of_nat of_nat_to_nat to_nat_of_nat def list_equiv_self_of_equiv_nat {α : Type} : α ≃ nat → list α ≃ α := suppose α ≃ nat, calc list α ≃ list nat : list_equiv_of_equiv this ... ≃ nat : list_nat_equiv_nat ... ≃ α : this end -/ end list
e370cd34fbfaa6f8df67cecb30b048df4049f0e3
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
/src/Lean/Elab/Tactic/Conv/Basic.lean
ea17fa9ecb46a3aa8064ebeb5f123c2ecff77d5f
[ "Apache-2.0" ]
permissive
stephenbrady/lean4
74bf5cae8a433e9c815708ce96c9e54a5caf2115
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
refs/heads/master
1,692,621,473,161
1,634,308,743,000
1,634,310,749,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,685
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Reduce import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Replace import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.BuiltinTactic namespace Lean.Elab.Tactic.Conv open Meta def mkConvGoalFor (lhs : Expr) : MetaM (Expr × Expr) := do let lhsType ← inferType lhs let rhs ← mkFreshExprMVar lhsType let targetNew := mkLHSGoal (← mkEq lhs rhs) let newGoal ← mkFreshExprSyntheticOpaqueMVar targetNew return (rhs, newGoal) def markAsConvGoal (mvarId : MVarId) : MetaM MVarId := do let target ← getMVarType mvarId if isLHSGoal? target |>.isSome then return mvarId -- it is already tagged as LHS goal replaceTargetDefEq mvarId (mkLHSGoal (← getMVarType mvarId)) def convert (lhs : Expr) (conv : TacticM Unit) : TacticM (Expr × Expr) := do let (rhs, newGoal) ← mkConvGoalFor lhs let savedGoals ← getGoals try setGoals [newGoal.mvarId!] conv for mvarId in (← getGoals) do try applyRefl mvarId catch _ => pure () pruneSolvedGoals unless (← getGoals).isEmpty do throwError "convert tactic failed, there are unsolved goals\n{goalsToMessageData (← getGoals)}" pure () finally setGoals savedGoals return (← instantiateMVars rhs, ← instantiateMVars newGoal) def getLhsRhsCore (mvarId : MVarId) : MetaM (Expr × Expr) := withMVarContext mvarId do let some (_, lhs, rhs) ← matchEq? (← getMVarType mvarId) | throwError "invalid 'conv' goal" return (lhs, rhs) def getLhsRhs : TacticM (Expr × Expr) := do getLhsRhsCore (← getMainGoal) def getLhs : TacticM Expr := return (← getLhsRhs).1 def getRhs : TacticM Expr := return (← getLhsRhs).2 /-- `⊢ lhs = rhs` ~~> `⊢ lhs' = rhs` using `h : lhs = lhs'`. -/ def updateLhs (lhs' : Expr) (h : Expr) : TacticM Unit := do let rhs ← getRhs let newGoal ← mkFreshExprSyntheticOpaqueMVar (mkLHSGoal (← mkEq lhs' rhs)) assignExprMVar (← getMainGoal) (← mkEqTrans h newGoal) replaceMainGoal [newGoal.mvarId!] /-- Replace `lhs` with the definitionally equal `lhs'`. -/ def changeLhs (lhs' : Expr) : TacticM Unit := do let rhs ← getRhs liftMetaTactic1 fun mvarId => do replaceTargetDefEq mvarId (mkLHSGoal (← mkEq lhs' rhs)) @[builtinTactic Lean.Parser.Tactic.Conv.whnf] def evalWhnf : Tactic := fun stx => withMainContext do changeLhs (← whnf (← getLhs)) @[builtinTactic Lean.Parser.Tactic.Conv.reduce] def evalReduce : Tactic := fun stx => withMainContext do changeLhs (← reduce (← getLhs)) @[builtinTactic Lean.Parser.Tactic.Conv.convSeq1Indented] def evalConvSeq1Indented : Tactic := fun stx => do evalTacticSeq1Indented stx @[builtinTactic Lean.Parser.Tactic.Conv.convSeqBracketed] def evalConvSeqBracketed : Tactic := fun stx => do let initInfo ← mkInitialTacticInfo stx[0] withRef stx[2] <| closeUsingOrAdmit do -- save state before/after entering focus on `{` withInfoContext (pure ()) initInfo evalManyTacticOptSemi stx[1] evalTactic (← `(tactic| all_goals (try rfl))) @[builtinTactic Lean.Parser.Tactic.Conv.nestedConv] def evalNestedConv : Tactic := fun stx => do evalConvSeqBracketed stx[0] @[builtinTactic Lean.Parser.Tactic.Conv.convSeq] def evalConvSeq : Tactic := fun stx => do evalTactic stx[0] @[builtinTactic Lean.Parser.Tactic.Conv.paren] def evalParen : Tactic := fun stx => evalTactic stx[1] /-- Mark goals of the form `⊢ a = ?m ..` with the conv goal annotation -/ def remarkAsConvGoal : TacticM Unit := do let newGoals ← (← getUnsolvedGoals).mapM fun mvarId => withMVarContext mvarId do let target ← getMVarType mvarId if let some (_, lhs, rhs) ← matchEq? target then if rhs.getAppFn.isMVar then replaceTargetDefEq mvarId (mkLHSGoal target) else return mvarId else return mvarId setGoals newGoals @[builtinTactic Lean.Parser.Tactic.Conv.nestedTacticCore] def evalNestedTacticCore : Tactic := fun stx => do let seq := stx[2] evalTactic seq; remarkAsConvGoal @[builtinTactic Lean.Parser.Tactic.Conv.nestedTactic] def evalNestedTactic : Tactic := fun stx => do let seq := stx[2] let target ← getMainTarget if let some _ := isLHSGoal? target then liftMetaTactic1 fun mvarId => replaceTargetDefEq mvarId target.mdataExpr! focus do evalTactic seq; remarkAsConvGoal private def convTarget (conv : Syntax) : TacticM Unit := withMainContext do let target ← getMainTarget let (targetNew, proof) ← convert target (evalTactic conv) liftMetaTactic1 fun mvarId => replaceTargetEq mvarId targetNew proof evalTactic (← `(tactic| try rfl)) private def convLocalDecl (conv : Syntax) (hUserName : Name) : TacticM Unit := withMainContext do let localDecl ← getLocalDeclFromUserName hUserName let (typeNew, proof) ← convert localDecl.type (evalTactic conv) liftMetaTactic1 fun mvarId => return some (← replaceLocalDecl mvarId localDecl.fvarId typeNew proof).mvarId @[builtinTactic Lean.Parser.Tactic.Conv.conv] def evalConv : Tactic := fun stx => do match stx with | `(tactic| conv $[at $loc?]? in $p => $code) => evalTactic (← `(tactic| conv $[at $loc?]? => pattern $p; ($code:convSeq))) | `(tactic| conv $[at $loc?]? => $code) => if let some loc := loc? then convLocalDecl code loc.getId else convTarget code | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.Conv.first] partial def evalFirst : Tactic := Tactic.evalFirst end Lean.Elab.Tactic.Conv
d916065d2768054e0056b55d8bab1e8ffc8479b5
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/src/o_minimal/examples/from_finite_unions.lean
cc8b81ab740973aa7b302c61875092d1e3887a8a
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
5,313
lean
import for_mathlib.closure import o_minimal.o_minimal /- Construction of (o-minimal) structures of the type: a subset of Rⁿ is definable if it is a finite union of sets of the form [...]. For example, the semialgebraic sets are the finite unions of sets of the form {x ∈ Rⁿ | f(x) = 0, g₁(x) > 0, ..., gₖ(x) > 0}. Semilinear sets and the "minimal" structure of sets definable in (R, <) are also structures of this type. Suppose D ("definable") and B ("basic") are classes of subsets of Rⁿ for each n and the following conditions are satisfied. * A set is definable if and only if it is a finite union of basic sets. * Finite intersections of basic sets are definable. * The complement of a basic set is definable. * If A is a basic set then R × A and A × R are definable. * {x ∈ Rⁿ | x₁ = xₙ} is definable. * The projection of a basic set is definable. Then D forms a structure on R. Furthermore, if every basic subset of R¹ is tame, then so is every definable subset. (TODO: Last sentence above.) -/ namespace o_minimal open set open_locale finvec variables {R : Type*} (D B : Π ⦃n : ℕ⦄, set (set (finvec n R))) /-- Standing hypotheses for this module. -/ structure finite_union_struc_hypotheses : Prop := (definable_iff_finite_union_basic : ∀ {n} {s : set (finvec n R)}, D s ↔ s ∈ finite_union_closure (@B n)) (definable_univ : ∀ {n}, D (set.univ : set (finvec n R))) (definable_basic_inter_basic : ∀ {n} {s t : set (finvec n R)}, B s → B t → D (s ∩ t)) (definable_compl_basic : ∀ {n} {s : set (finvec n R)}, B s → D sᶜ) (definable_r_prod_basic : ∀ {n} {s : set (finvec n R)}, B s → D (finvec.univ_prod 1 s)) (definable_basic_prod_r : ∀ {n} {s : set (finvec n R)}, B s → D (finvec.prod_univ s 1)) (definable_eq_outer : ∀ {n}, D ({x | x 0 = x.last} : set (finvec (n + 1) R))) (definable_proj1_basic : ∀ {n} {s : set (finvec (n + 1) R)}, B s → D (finvec.left '' s)) variables {D B} section struc variables (H : finite_union_struc_hypotheses D B) include H lemma finite_union_struc_hypotheses.D_eq_finite_union_closure_B : D = λ n, finite_union_closure (@B n) := by { ext, apply H.definable_iff_finite_union_basic } /-- Suppose Φ : set (finvec n R) → set (finvec m R) is an operation which commutes with finite unions. Then if (s ∈ B → Φ s ∈ D) then (s ∈ D → Φ s ∈ D). Examples of Φ: product with R¹ on either side; projection. Only uses the assumption `D = finite_union_closure B`. TODO: Generalize this to the setting of for_mathlib.closure. -/ lemma finite_union_struc_hypotheses.promote_hypothesis {n m : ℕ} (Φ : set (finvec n R) → set (finvec m R)) (hΦ₀ : Φ ∅ = ∅) (hΦ₂ : ∀ {s t}, Φ (s ∪ t) = Φ s ∪ Φ t) : (∀ ⦃s : set (finvec n R)⦄, B s → D (Φ s)) → (∀ ⦃s : set (finvec n R)⦄, D s → D (Φ s)) := begin cases H.D_eq_finite_union_closure_B, intros h, apply finite_union_closure.rec, { exact @h }, { rw hΦ₀, apply finite_union_closure.empty }, { rintros s t - - hs ht, rw hΦ₂, apply hs.union ht } end /-- The structure obtained from the hypotheses `finite_union_struc_hypotheses D B`. By definition, the definable sets are given by `D`. -/ def struc_of_finite_union : struc R := { definable := D, definable_empty := begin cases H.D_eq_finite_union_closure_B, intro n, exact finite_union_closure.empty end, definable_union := begin cases H.D_eq_finite_union_closure_B, intros _ _ _ hs ht, exact hs.union ht end, definable_compl := begin cases H.D_eq_finite_union_closure_B, intros n s hs, apply closed_under_complements_finite_union_closure, { apply H.definable_univ }, { apply H.definable_basic_inter_basic }, { apply H.definable_compl_basic }, { exact hs } end, definable_r_prod := begin intro n, refine H.promote_hypothesis (λ s, finvec.univ_prod 1 s) _ _ (λ s h, H.definable_r_prod_basic h); intros; ext; simp [finvec.univ_prod] end, definable_prod_r := begin intro n, refine H.promote_hypothesis (λ s, finvec.prod_univ s 1) _ _ (λ s h, H.definable_basic_prod_r h); intros; ext; simp [finvec.prod_univ], end, definable_eq_outer := H.definable_eq_outer, definable_proj1 := begin intro n, refine H.promote_hypothesis (λ s, finvec.left '' s) _ _ (λ s h, H.definable_proj1_basic h); intros; ext; simp [image_union] end } end struc section o_minimal variables (D B) [DUNLO R] structure finite_union_o_minimal_hypotheses extends finite_union_struc_hypotheses D B : Prop := (definable_lt : D {x : finvec 2 R | x 0 < x 1}) (definable_const : ∀ {r}, D {x : finvec 1 R | x 0 = r}) (tame_of_basic : ∀ {s : set (finvec 1 R)}, B s → tame {r | (λ _, r : finvec 1 R) ∈ s}) variables {D B} (H : finite_union_o_minimal_hypotheses D B) lemma o_minimal_of_finite_union : o_minimal (struc_of_finite_union H.to_finite_union_struc_hypotheses : struc R) := o_minimal.mk' _ H.definable_lt H.definable_const $ begin change ∀ s, D s → _, cases H.to_finite_union_struc_hypotheses.D_eq_finite_union_closure_B, refine preserves_finite_unions.bind' _ closed_under_finite_unions_finite_union_closure _, { split; intros; simp; refl }, exact H.tame_of_basic end end o_minimal end o_minimal
adb424571527adaeabc86b8aef4bd70ae20fffe0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/hales_jewett.lean
f7677fc09aca02ea195536556958798ba380445e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
15,614
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import data.fintype.option import data.fintype.pi import data.fintype.sum import algebra.big_operators.basic /-! # The Hales-Jewett theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We prove the Hales-Jewett theorem and deduce Van der Waerden's theorem as a corollary. The Hales-Jewett theorem is a result in Ramsey theory dealing with *combinatorial lines*. Given an 'alphabet' `α : Type*` and `a b : α`, an example of a combinatorial line in `α^5` is `{ (a, x, x, b, x) | x : α }`. See `combinatorics.line` for a precise general definition. The Hales-Jewett theorem states that for any fixed finite types `α` and `κ`, there exists a (potentially huge) finite type `ι` such that whenever `ι → α` is `κ`-colored (i.e. for any coloring `C : (ι → α) → κ`), there exists a monochromatic line. We prove the Hales-Jewett theorem using the idea of *color focusing* and a *product argument*. See the proof of `combinatorics.line.exists_mono_in_high_dimension'` for details. The version of Van der Waerden's theorem in this file states that whenever a commutative monoid `M` is finitely colored and `S` is a finite subset, there exists a monochromatic homothetic copy of `S`. This follows from the Hales-Jewett theorem by considering the map `(ι → S) → M` sending `v` to `∑ i : ι, v i`, which sends a combinatorial line to a homothetic copy of `S`. ## Main results - `combinatorics.line.exists_mono_in_high_dimension`: the Hales-Jewett theorem. - `combinatorics.exists_mono_homothetic_copy`: a generalization of Van der Waerden's theorem. ## Implementation details For convenience, we work directly with finite types instead of natural numbers. That is, we write `α, ι, κ` for (finite) types where one might traditionally use natural numbers `n, H, c`. This allows us to work directly with `α`, `option α`, `(ι → α) → κ`, and `ι ⊕ ι'` instead of `fin n`, `fin (n+1)`, `fin (c^(n^H))`, and `fin (H + H')`. ## Todo - Prove a finitary version of Van der Waerden's theorem (either by compactness or by modifying the current proof). - One could reformulate the proof of Hales-Jewett to give explicit upper bounds on the number of coordinates needed. ## Tags combinatorial line, Ramsey theory, arithmetic progession ### References * https://en.wikipedia.org/wiki/Hales%E2%80%93Jewett_theorem -/ open_locale classical open_locale big_operators universes u v namespace combinatorics /-- The type of combinatorial lines. A line `l : line α ι` in the hypercube `ι → α` defines a function `α → ι → α` from `α` to the hypercube, such that for each coordinate `i : ι`, the function `λ x, l x i` is either `id` or constant. We require lines to be nontrivial in the sense that `λ x, l x i` is `id` for at least one `i`. Formally, a line is represented by the function `l.idx_fun : ι → option α` which says whether `λ x, l x i` is `id` (corresponding to `l.idx_fun i = none`) or constantly `y` (corresponding to `l.idx_fun i = some y`). When `α` has size `1` there can be many elements of `line α ι` defining the same function. -/ structure line (α ι : Type*) := (idx_fun : ι → option α) (proper : ∃ i, idx_fun i = none) namespace line /- This lets us treat a line `l : line α ι` as a function `α → ι → α`. -/ instance (α ι) : has_coe_to_fun (line α ι) (λ _, α → ι → α) := ⟨λ l x i, (l.idx_fun i).get_or_else x⟩ /-- A line is monochromatic if all its points are the same color. -/ def is_mono {α ι κ} (C : (ι → α) → κ) (l : line α ι) : Prop := ∃ c, ∀ x, C (l x) = c /-- The diagonal line. It is the identity at every coordinate. -/ def diagonal (α ι) [nonempty ι] : line α ι := { idx_fun := λ _, none, proper := ⟨classical.arbitrary ι, rfl⟩ } instance (α ι) [nonempty ι] : inhabited (line α ι) := ⟨diagonal α ι⟩ /-- The type of lines that are only one color except possibly at their endpoints. -/ structure almost_mono {α ι κ : Type*} (C : (ι → option α) → κ) := (line : line (option α) ι) (color : κ) (has_color : ∀ x : α, C (line (some x)) = color) instance {α ι κ : Type*} [nonempty ι] [inhabited κ] : inhabited (almost_mono (λ v : ι → option α, (default : κ))) := ⟨{ line := default, color := default, has_color := λ _, rfl }⟩ /-- The type of collections of lines such that - each line is only one color except possibly at its endpoint - the lines all have the same endpoint - the colors of the lines are distinct. Used in the proof `exists_mono_in_high_dimension`. -/ structure color_focused {α ι κ : Type*} (C : (ι → option α) → κ) := (lines : multiset (almost_mono C)) (focus : ι → option α) (is_focused : ∀ p ∈ lines, almost_mono.line p none = focus) (distinct_colors : (lines.map almost_mono.color).nodup) instance {α ι κ} (C : (ι → option α) → κ) : inhabited (color_focused C) := ⟨⟨0, λ _, none, λ _, false.elim, multiset.nodup_zero⟩⟩ /-- A function `f : α → α'` determines a function `line α ι → line α' ι`. For a coordinate `i`, `l.map f` is the identity at `i` if `l` is, and constantly `f y` if `l` is constantly `y` at `i`. -/ def map {α α' ι} (f : α → α') (l : line α ι) : line α' ι := { idx_fun := λ i, (l.idx_fun i).map f, proper := ⟨l.proper.some, by rw [l.proper.some_spec, option.map_none'] ⟩ } /-- A point in `ι → α` and a line in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def vertical {α ι ι'} (v : ι → α) (l : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim (some ∘ v) l.idx_fun, proper := ⟨sum.inr l.proper.some, l.proper.some_spec⟩ } /-- A line in `ι → α` and a point in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def horizontal {α ι ι'} (l : line α ι) (v : ι' → α) : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun (some ∘ v), proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } /-- One line in `ι → α` and one in `ι' → α` together determine a line in `ι ⊕ ι' → α`. -/ def prod {α ι ι'} (l : line α ι) (l' : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun l'.idx_fun, proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } lemma apply {α ι} (l : line α ι) (x : α) : l x = λ i, (l.idx_fun i).get_or_else x := rfl lemma apply_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i = none) : l x i = x := by simp only [option.get_or_else_none, h, l.apply] lemma apply_of_ne_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i ≠ none) : some (l x i) = l.idx_fun i := by rw [l.apply, option.get_or_else_of_ne_none h] @[simp] lemma map_apply {α α' ι} (f : α → α') (l : line α ι) (x : α) : l.map f (f x) = f ∘ l x := by simp only [line.apply, line.map, option.get_or_else_map] @[simp] lemma vertical_apply {α ι ι'} (v : ι → α) (l : line α ι') (x : α) : l.vertical v x = sum.elim v (l x) := by { funext i, cases i; refl } @[simp] lemma horizontal_apply {α ι ι'} (l : line α ι) (v : ι' → α) (x : α) : l.horizontal v x = sum.elim (l x) v := by { funext i, cases i; refl } @[simp] lemma prod_apply {α ι ι'} (l : line α ι) (l' : line α ι') (x : α) : l.prod l' x = sum.elim (l x) (l' x) := by { funext i, cases i; refl } @[simp] lemma diagonal_apply {α ι} [nonempty ι] (x : α) : line.diagonal α ι x = λ i, x := by simp_rw [line.apply, line.diagonal, option.get_or_else_none] /-- The Hales-Jewett theorem. This version has a restriction on universe levels which is necessary for the proof. See `exists_mono_in_high_dimension` for a fully universe-polymorphic version. -/ private theorem exists_mono_in_high_dimension' : ∀ (α : Type u) [finite α] (κ : Type (max v u)) [finite κ], ∃ (ι : Type) (_ : fintype ι), ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := -- The proof proceeds by induction on `α`. finite.induction_empty_option -- We have to show that the theorem is invariant under `α ≃ α'` for the induction to work. (λ α α' e, forall_imp $ λ κ, forall_imp $ λ _, Exists.imp $ λ ι, Exists.imp $ λ _ h C, let ⟨l, c, lc⟩ := h (λ v, C (e ∘ v)) in ⟨l.map e, c, e.forall_congr_left.mp $ λ x, by rw [←lc x, line.map_apply]⟩) begin -- This deals with the degenerate case where `α` is empty. introsI κ _, by_cases h : nonempty κ, { resetI, exact ⟨unit, infer_instance, λ C, ⟨default, classical.arbitrary _, pempty.rec _⟩⟩, }, { exact ⟨empty, infer_instance, λ C, (h ⟨C (empty.rec _)⟩).elim⟩, } end begin -- Now we have to show that the theorem holds for `option α` if it holds for `α`. introsI α _ ihα κ _, casesI nonempty_fintype κ, -- Later we'll need `α` to be nonempty. So we first deal with the trivial case where `α` is empty. -- Then `option α` has only one element, so any line is monochromatic. by_cases h : nonempty α, work_on_goal 2 { refine ⟨unit, infer_instance, λ C, ⟨diagonal _ _, C (λ _, none), _⟩⟩, rintros (_ | ⟨a⟩), refl, exact (h ⟨a⟩).elim, }, -- The key idea is to show that for every `r`, in high dimension we can either find -- `r` color focused lines or a monochromatic line. suffices key : ∀ r : ℕ, ∃ (ι : Type) (_ : fintype ι), ∀ C : (ι → (option α)) → κ, (∃ s : color_focused C, s.lines.card = r) ∨ (∃ l, is_mono C l), -- Given the key claim, we simply take `r = |κ| + 1`. We cannot have this many distinct colors so -- we must be in the second case, where there is a monochromatic line. { obtain ⟨ι, _inst, hι⟩ := key (fintype.card κ + 1), refine ⟨ι, _inst, λ C, (hι C).resolve_left _⟩, rintro ⟨s, sr⟩, apply nat.not_succ_le_self (fintype.card κ), rw [←nat.add_one, ←sr, ←multiset.card_map, ←finset.card_mk], exact finset.card_le_univ ⟨_, s.distinct_colors⟩ }, -- We now prove the key claim, by induction on `r`. intro r, induction r with r ihr, -- The base case `r = 0` is trivial as the empty collection is color-focused. { exact ⟨empty, infer_instance, λ C, or.inl ⟨default, multiset.card_zero⟩⟩, }, -- Supposing the key claim holds for `r`, we need to show it for `r+1`. First pick a high enough -- dimension `ι` for `r`. obtain ⟨ι, _inst, hι⟩ := ihr, resetI, -- Then since the theorem holds for `α` with any number of colors, pick a dimension `ι'` such that -- `ι' → α` always has a monochromatic line whenever it is `(ι → option α) → κ`-colored. specialize ihα ((ι → option α) → κ), obtain ⟨ι', _inst, hι'⟩ := ihα, resetI, -- We claim that `ι ⊕ ι'` works for `option α` and `κ`-coloring. refine ⟨ι ⊕ ι', infer_instance, _⟩, intro C, -- A `κ`-coloring of `ι ⊕ ι' → option α` induces an `(ι → option α) → κ`-coloring of `ι' → α`. specialize hι' (λ v' v, C (sum.elim v (some ∘ v'))), -- By choice of `ι'` this coloring has a monochromatic line `l'` with color class `C'`, where -- `C'` is a `κ`-coloring of `ι → α`. obtain ⟨l', C', hl'⟩ := hι', -- If `C'` has a monochromatic line, then so does `C`. We use this in two places below. have mono_of_mono : (∃ l, is_mono C' l) → (∃ l, is_mono C l), { rintro ⟨l, c, hl⟩, refine ⟨l.horizontal (some ∘ l' (classical.arbitrary α)), c, λ x, _⟩, rw [line.horizontal_apply, ←hl, ←hl'], }, -- By choice of `ι`, `C'` either has `r` color-focused lines or a monochromatic line. specialize hι C', rcases hι with ⟨s, sr⟩ | _, -- By above, we are done if `C'` has a monochromatic line. work_on_goal 2 { exact or.inr (mono_of_mono hι) }, -- Here we assume `C'` has `r` color focused lines. We split into cases depending on whether one of -- these `r` lines has the same color as the focus point. by_cases h : ∃ p ∈ s.lines, (p : almost_mono _).color = C' s.focus, -- If so then this is a `C'`-monochromatic line and we are done. { obtain ⟨p, p_mem, hp⟩ := h, refine or.inr (mono_of_mono ⟨p.line, p.color, _⟩), rintro (_ | _), rw [hp, s.is_focused p p_mem], apply p.has_color, }, -- If not, we get `r+1` color focused lines by taking the product of the `r` lines with `l'` and -- adding to this the vertical line obtained by the focus point and `l`. refine or.inl ⟨⟨(s.lines.map _).cons ⟨(l'.map some).vertical s.focus, C' s.focus, λ x, _⟩, sum.elim s.focus (l'.map some none), _, _⟩, _⟩, -- The vertical line is almost monochromatic. { rw [vertical_apply, ←congr_fun (hl' x), line.map_apply], }, { refine λ p, ⟨p.line.prod (l'.map some), p.color, λ x, _⟩, -- The product lines are almost monochromatic. rw [line.prod_apply, line.map_apply, ←p.has_color, ←congr_fun (hl' x)], }, -- Our `r+1` lines have the same endpoint. { simp_rw [multiset.mem_cons, multiset.mem_map], rintros _ (rfl | ⟨q, hq, rfl⟩), { rw line.vertical_apply, }, { rw [line.prod_apply, s.is_focused q hq], }, }, -- Our `r+1` lines have distinct colors (this is why we needed to split into cases above). { rw [multiset.map_cons, multiset.map_map, multiset.nodup_cons, multiset.mem_map], exact ⟨λ ⟨q, hq, he⟩, h ⟨q, hq, he⟩, s.distinct_colors⟩, }, -- Finally, we really do have `r+1` lines! { rw [multiset.card_cons, multiset.card_map, sr], }, end /-- The Hales-Jewett theorem: for any finite types `α` and `κ`, there exists a finite type `ι` such that whenever the hypercube `ι → α` is `κ`-colored, there is a monochromatic combinatorial line. -/ theorem exists_mono_in_high_dimension (α : Type u) [finite α] (κ : Type v) [finite κ] : ∃ (ι : Type) [fintype ι], ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := let ⟨ι, ιfin, hι⟩ := exists_mono_in_high_dimension' α (ulift κ) in ⟨ι, ιfin, λ C, let ⟨l, c, hc⟩ := hι (ulift.up ∘ C) in ⟨l, c.down, λ x, by rw ←hc⟩ ⟩ end line /-- A generalization of Van der Waerden's theorem: if `M` is a finitely colored commutative monoid, and `S` is a finite subset, then there exists a monochromatic homothetic copy of `S`. -/ theorem exists_mono_homothetic_copy {M κ : Type*} [add_comm_monoid M] (S : finset M) [finite κ] (C : M → κ) : ∃ (a > 0) (b : M) (c : κ), ∀ s ∈ S, C (a • s + b) = c := begin obtain ⟨ι, _inst, hι⟩ := line.exists_mono_in_high_dimension S κ, resetI, specialize hι (λ v, C $ ∑ i, v i), obtain ⟨l, c, hl⟩ := hι, set s : finset ι := { i ∈ finset.univ | l.idx_fun i = none } with hs, refine ⟨s.card, finset.card_pos.mpr ⟨l.proper.some, _⟩, ∑ i in sᶜ, ((l.idx_fun i).map coe).get_or_else 0, c, _⟩, { rw [hs, finset.sep_def, finset.mem_filter], exact ⟨finset.mem_univ _, l.proper.some_spec⟩, }, intros x xs, rw ←hl ⟨x, xs⟩, clear hl, congr, rw ←finset.sum_add_sum_compl s, congr' 1, { rw ←finset.sum_const, apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.mem_filter] at hi, rw [l.apply_none _ _ hi.right, subtype.coe_mk], }, { apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.compl_filter, finset.mem_filter] at hi, obtain ⟨y, hy⟩ := option.ne_none_iff_exists.mp hi.right, simp_rw [line.apply, ←hy, option.map_some', option.get_or_else_some], }, end end combinatorics
20bb6a3563d329a8bd38ef3bb8f8f5d752b4a011
ef6b7797dbbd7b1dfff69894d190a965b101c5ff
/src/hilbert.lean
d688f30cdfa216776f3ec2ec389d07f85e297b89
[]
no_license
utensil-star/leanteach2020
43d57f1b23eded178e2049a0957b7ec38fd4e1a7
93326a5e5b0efeba30d9dc9ee85d52b1029cb24d
refs/heads/master
1,666,413,811,198
1,592,598,394,000
1,592,598,394,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,618
lean
-- Hilbert's Axioms Formalized import data.real.basic tactic noncomputable theory open_locale classical -- Two undefined types constant Point : Type -- constant Line : Type -- We difine it as a structure instead of a constant. --constant Plane : Type -- We restrict our attention to planar geometry, ignoring solid geometry. -- a Segment is constructed by specifying two points. structure Segment: Type := (p₁ p₂ : Point) -- the subscripts are written as \ 1 and \ 2. -- This is the Betweenness relation. -- It says "y" is in between "x" and "z". constant B (x y z : Point) : Prop -- Polymorphism => make it work for multiple types at the same time -- For every type A, there is a congruence relation C. constant C {A : Type} : A → A → Prop -- Here, "A" is an implicit argument. Lean figures it out. -- In other languages this is called overloading. -- We are defining our own operators here local infix ` ≃ `:55 := C -- \ equiv == equivalence/congruence local infix `⬝`: 56 := Segment.mk -- \ cdot == center-dot -- # I. Incidence Axioms ------------------------ -- I.1 and I.2 -- Hilbert declares that Line is an independent type and then in -- Axioms I.1 and I.2 he provides a necessary and sufficient condition -- for constructing a Line from two Points. We believe it is more -- efficient to directly define Line as a structure that requires two -- distint Points. structure Line : Type := (p₁ p₂ : Point) (ne : p₁ ≠ p₂) -- There are two "lies-on" relations. -- We specify lies_on_line here as a constant. -- lies_on_segment is defined later. constant lies_on_line (x : Point) (y : Line) : Prop -- I.1, I.2 is implicit in constant axiom line_exists (p₁ p₂ : Point) (h : p₁ ≠ p₂) : let l : Line := ⟨p₁, p₂, h⟩ in lies_on_line p₁ l ∧ lies_on_line p₂ l axiom line_unique (p₁ p₂ : Point) (h : p₁ ≠ p₂) (l : Line) : lies_on_line p₁ l → lies_on_line p₂ l → l = ⟨p₁, p₂, h⟩ -- I.3 (part 1) axiom two_points_on_line (l : Line): ∃ (a b : Point), a ≠ b ∧ lies_on_line a l ∧ lies_on_line b l -- I.3 (part 2) axiom no_line_on_three_points: ∃ (a b c : Point), ¬∃ (l : Line), (lies_on_line a l) ∧ (lies_on_line b l) ∧ (lies_on_line c l) -- A Ray is constructed by specifying two Points. structure Ray : Type := (base ext : Point) -- For each Ray, we can define a corresponding Line. def line_of_ray (r : Ray) : r.base ≠ r.ext → Line := Line.mk r.base r.ext -- An Angle is constructed by specifying three Points. -- Angle ⟨a, b, c, _, _⟩ reperesents the angle ∠abc. structure Angle : Type := (ext₁ base ext₂ : Point) -- For each Angle, we can define two corresponding Rays. def rays_of_angle (α : Angle) : Ray × Ray := (⟨α.base, α.ext₁⟩, ⟨α.base, α.ext₂⟩) -- A Triangle is constructed by specifying three Points. structure Triangle : Type := (p₁ p₂ p₃ : Point) -- For every Triangle, we can define get three Segments (its sides). def sides_of_triangle (t : Triangle) : vector Segment 3 := ⟨[t.p₁⬝t.p₂, t.p₂⬝t.p₃, t.p₁⬝t.p₃], rfl⟩ -- For every Triangle, we can define get three Segment Angles. def angles_of_triangle (t : Triangle) : vector Angle 3 := ⟨[⟨t.p₂, t.p₁, t.p₃⟩, ⟨t.p₁, t.p₂, t.p₃⟩, ⟨t.p₂, t.p₃, t.p₁⟩], rfl⟩ -- Note that elements of a vector v can be accessed as v.nth 0 etc. -- Also note that if a vector has lenth n, then asking for element m -- where m ≥ n returns element (m mod n) def equilateral (t: Triangle) : Prop := let sides := sides_of_triangle t in sides.nth 0 ≃ sides.nth 1 ∧ sides.nth 1 ≃ sides.nth 2 -- # II. Order Axioms (Good) --------------------- def collinear_points (a b c : Point) : Prop := ∃ (l : Line), lies_on_line a l ∧ lies_on_line b l ∧ lies_on_line c l /- Note: ----- I.1 and I.2 guarantee that a Line exists between each pair of points, but it does not guarantee that the Lines corresponding to ab, ac, and bc are all the same. For that, we need another axiom (II.1). -/ -- II.1 (part 1) @[symm] axiom B_symm (a b c : Point) : B a b c → B c b a -- II.1 (part 2) axiom B_implies_collinear (a b c : Point): B a b c → collinear_points a b c -- II.2 axiom line_continuity (a c : Point) (h : a ≠ c): let l : Line := ⟨a, c, h⟩ in ∃ (b : Point), lies_on_line b l ∧ B a b c -- II.3 axiom max_one_between (a b c : Point): collinear_points a b c → xor (B a b c) (xor (B a c b) (B c a b)) -- ## Helpful definitions ------------------------- -- Lies-on relation between Point and Segment. def lies_on_segment (x : Point) (s : Segment) (h : s.p₁ ≠ s.p₂) : Prop := B s.p₁ x s.p₂ ∧ lies_on_line x ⟨s.p₁, s.p₂, h⟩ -- Criterion for two Segments intersecting at a Point. def intersect_segment (s₁ s₂ : Segment) (h1 : s₁.p₁ ≠ s₁.p₂) (h2 : s₂.p₁ ≠ s₂.p₂) : Prop := ∃ x : Point, lies_on_segment x s₁ h1 ∧ lies_on_segment x s₂ h2 -- Criterion for two Lines intersecting at a Point. def intersect_line (l₁ l₂ : Line) : Prop := ∃ x : Point, lies_on_line x l₁ ∧ lies_on_line x l₂ -- Criterion for a Segment intersecting with a Line. def intersect_line_segment (l: Line) (s : Segment) (H : s.p₁ ≠ s.p₂) : Prop := ∃ x : Point, lies_on_line x l ∧ lies_on_segment x s H -- Condition for a Segment to be a part of a given Line. def segment_of_line (s : Segment) (l : Line) : Prop := lies_on_line s.p₁ l ∧ lies_on_line s.p₂ l -- Condition for two segments being on the same line end-to-end. def segments_end_to_end (s₁ s₂ : Segment) (h₁ : s₁.p₁ ≠ s₁.p₂) (h₂ : s₂.p₁ ≠ s₂.p₂) : Prop := (s₁.p₂ = s₂.p₁) ∧ (∀ x : Point, lies_on_segment x s₁ h₁ ∧ lies_on_segment x s₂ h₂ → x = s₁.p₂) -- Relationship between two parallel lines def parallel_lines (l₁ l₂ : Line) : Prop := ¬∃ (a : Point), lies_on_line a l₁ ∧ lies_on_line a l₂ -- Condition for two Points to lie on the same side of a Line. def lie_on_same_side (a b : Point) (l : Line) (h : a ≠ b) : Prop := ¬ intersect_line_segment l (a⬝b) h -- Condition for two Points to lie on opposite sides of a Line. def lie_on_opposite_sides (a b : Point) (l : Line) (h : a ≠ b) : Prop := ¬ lie_on_same_side a b l h def side_of_line (l : Line) (p : Point) : ¬ lies_on_line p l → set Point := sorry -- {x : Point | lie_on_same_side x p l sorry} -- II.4 Pasch's axiom -- This can be interpreted as saying "a line that enters a triangle -- from one side, must leave the triangle from one of the reamining -- two sides." axiom pasch (a b c: Point) (l : Line) (hab : a ≠ b) (hbc : b ≠ c) (hac : a ≠ c): (¬collinear_points a b c) → ¬(lies_on_line a l) → ¬(lies_on_line b l) → ¬(lies_on_line c l) → intersect_line_segment l (a⬝b) hab → intersect_line_segment l (a⬝c) hac ∨ intersect_line_segment l (b⬝c) hbc -- # III. Congruence Axioms --------------------------- -- III.1 Part 1 -- This says that we can extend a given Segment in only two ways -- -- one for each side of l. constant segment_copy (a b a' : Point) (l l' : Line) : lies_on_line a l → lies_on_line b l → lies_on_line a' l' → Point × Point axiom segment_copy' (a b a' : Point) (l l' : Line) (hal : lies_on_line a l) (hbl: lies_on_line b l) (ha'l' : lies_on_line a' l') : let points := segment_copy a b a' l l' hal hbl ha'l' in let x : Point := points.1 in let y : Point := points.2 in x ≠ y ∧ lies_on_line x l' ∧ a⬝b ≃ a'⬝x ∧ lies_on_line y l' ∧ a⬝b ≃ a'⬝y -- III.1 Part 2 @[symm] axiom C_segment_symm (s₁ s₂ : Segment) : s₁ ≃ s₂ → s₂ ≃ s₁ axiom segment_swap (x y : Point) : x⬝y ≃ y⬝x -- III.2 @[trans] axiom C_segment_trans (u v w x y z : Point) : (u⬝v ≃ z⬝w) → (u⬝v ≃ x⬝y) → z⬝w ≃ x⬝y -- Congruence of segments is reflexive @[refl] lemma C_segment_refl (a b : Point) : a⬝b ≃ a⬝b := begin fapply C_segment_trans, use b, use a, symmetry, symmetry, repeat {apply segment_swap}, end -- III.3 axiom C_segment_add_trans (a b c a' b' c' : Point) (l l' : Line) (hab : a ≠ b) (hbc : b ≠ c) (ha'b' : a' ≠ b') (hb'c' : b' ≠ c') : segment_of_line (a⬝b) l → segment_of_line (b⬝c) l → segments_end_to_end (a⬝b) (b⬝c) hab hbc → segment_of_line (a'⬝b') l' → segment_of_line (b'⬝c') l' → segments_end_to_end (a'⬝b') (b'⬝c') ha'b' hb'c' → a⬝b ≃ a'⬝b' → b⬝c ≃ b'⬝c' → a⬝c ≃ a'⬝c' -- III.4 -- This axiom says that a given angle can be copied over to a -- new location (the point o) in a unique manner (unique as long as we -- keep track of which side of the line we are on). constant angle_congruent (α : Angle) (o : Point) (r : Ray) : r.base = o → Ray × Ray axiom angle_congruent' (α : Angle) (o : Point) (r : Ray) (h : r.base = o) : let rays := angle_congruent α o r h in let r₁ : Ray := rays.1 in let r₂ : Ray := rays.2 in r₁ ≠ r₂ ∧ r₁.base = o ∧ r₂.base = o ∧ α ≃ ⟨r.ext, o, r₁.ext⟩ ∧ α ≃ ⟨r.ext, o, r₂.ext⟩ -- III.5 (wikipedia) @[trans] axiom C_angle_trans (α β γ : Angle) : α ≃ β → α ≃ γ → β ≃ γ @[symm] axiom angle_symm (a b c : Point) : (⟨a, b, c⟩ : Angle) ≃ ⟨c, b, a⟩ --- III.5 (from Paper) / III.6 (from wikipedia) axiom congruent_triangle_SAS (abc xyz : Triangle) : let angles₁ := angles_of_triangle abc in let angles₂ := angles_of_triangle xyz in abc.p₁⬝abc.p₂ ≃ xyz.p₁⬝xyz.p₂ → abc.p₁⬝abc.p₃ ≃ xyz.p₁⬝xyz.p₃ → angles₁.nth 0 ≃ angles₂.nth 0 → angles₁.nth 1 ≃ angles₂.nth 1 ∧ angles₁.nth 2 ≃ angles₂.nth 2 -- Definition of Congruent Triangles. All sides must be congruent. def congruent_triangle (t₁ t₂ : Triangle) : Prop := let sides1 := sides_of_triangle t₁ in let sides2 := sides_of_triangle t₂ in let angles1 := sides_of_triangle t₁ in let angles2 := sides_of_triangle t₂ in sides1.nth 0 ≃ sides2.nth 0 ∧ sides1.nth 1 ≃ sides2.nth 1 ∧ sides1.nth 2 ≃ sides2.nth 2 ∧ angles1.nth 0 ≃ angles2.nth 0 ∧ angles1.nth 1 ≃ angles2.nth 1 ∧ angles1.nth 2 ≃ angles2.nth 2 -- First theorem of congruence for triangles. If, for the two -- triangles ABC and A′B′C′, the congruences AB≡A′B′, AC≡A′C′, ∠A≡∠A′ -- hold, then the two triangles are congruent to each other. lemma first_congruence (abc xyz : Triangle) : let sides1 := sides_of_triangle abc in let sides2 := sides_of_triangle xyz in let angles1 := angles_of_triangle abc in let angles2 := angles_of_triangle xyz in let a := abc.p₁ in let b := abc.p₂ in let c := abc.p₃ in let x := xyz.p₁ in let y := xyz.p₂ in let z := xyz.p₃ in sides1.nth 0 ≃ sides2.nth 0 → sides1.nth 2 ≃ sides2.nth 2 → angles1.nth 0 ≃ angles2.nth 0 → congruent_triangle abc xyz := begin intros, unfold congruent_triangle, intros, have SAS := congruent_triangle_SAS abc xyz a_1 a_2 a_3, repeat {split}, { assumption}, { sorry}, { assumption}, { assumption}, { exact SAS.1}, { exact SAS.2}, end -- # IV. Parallel Axiom ----------------------- -- Euclid's parallel postulate. This axioms puts us in a Euclidean geometry -- and rules out Elliptical/Spherical/Hyperbolic geometry. constant mk_parallel (p : Point) (l : Line): ¬lies_on_line p l → Line axiom parallel_postulate (a : Point) (l : Line) (h: ¬lies_on_line a l): let l' : Line := mk_parallel a l h in parallel_lines l l' ∧ lies_on_line a l' -- # V. Angles -------------- -- Two angles having the same vertex and one side in common, whilethe -- sides not common form a straight line, are called supplementary -- angles. Two angleshaving a common vertex and whose sides form -- straight lines are calledvertical angles. An angle which is -- congruent to its supplementary angle is called a right angle. def supplementary_angles (α₁ α₂ : Angle) (h₁ : α₁.base ≠ α₁.ext₁) (h₂ : α₂.base ≠ α₂.ext₁) : Prop := α₁.base = α₂.base ∧ (⟨α₁.base, α₁.ext₁, h₁⟩ : Line) = ⟨α₂.base, α₂.ext₁, h₂⟩ ∧ collinear_points α₁.base α₁.ext₂ α₂.ext₂ -- LZ,AD : How to define this rigorously when the point can basically be -- anywhere? -- VK : use *segment_copy*. def mk_supplementary_angle (α : Angle) (h: α.base ≠ α.ext₂): Angle := let l : Line := Line.mk α.base α.ext₂ h in let bl : lies_on_line α.base l := (line_exists α.base α.ext₂ h).1 in let el : lies_on_line α.ext₂ l := (line_exists α.base α.ext₂ h).2 in let thing := segment_copy α.base α.ext₂ α.base l l bl el bl in let P : Point := thing.1 in ⟨α.ext₁, α.base, P⟩ lemma mk_supp_angle_condition (α : Angle) (h : α.base ≠ α.ext₂) : (mk_supplementary_angle α h).base ≠ (mk_supplementary_angle α h).ext₁ := begin unfold mk_supplementary_angle, simp, sorry end lemma mk_supplementary_angle_is_supplementary (α : Angle) (h : α.base ≠ α.ext₁): supplementary_angles α (mk_supplementary_angle α) h (mk_supp_angle_condition α) := sorry -- This specifies a Predicate on the type Angle def is_right (α : Angle) : Prop := α ≃ mk_supplementary_angle α structure Circle: Type := (center outer : Point) def radius_segment (c : Circle) : Segment := ⟨c.center, c.outer⟩ def circumference (c : Circle) : set Point := {x : Point | radius_segment c ≃ ⟨c.center, x⟩} -- # Notion of Distance in Hilbert ---------------------------------- -- may be necessary to properly state and prove pythagorean theorem in -- Lean). We start by defining a `measure` on Segments. def Measure : Type := Segment → ℝ -- Next, we define some axioms for working with distance. axiom distance_nonzero (μ : Measure) (s : Segment) : s.p₁ ≠ s.p₂ ↔ μ s > 0 axiom distance_congruent (μ : Measure) (s₁ s₂ : Segment) : s₁ ≃ s₂ ↔ μ s₁ = μ s₂ axiom distance_between (μ : Measure) (a b c : Point) : B a b c → μ (a⬝b) + μ (b⬝c) = μ (a⬝c) -- Theorems that can be proved in "Foundations of geometry" by Borsuk -- and Szmielew. theorem distance_scale (μ₁ μ₂ : Measure) (s : Segment) : ∃ k : ℝ, k > 0 ∧ μ₁ s = k * μ₂ s := begin sorry end theorem exists_measure (s : Segment) (x : ℝ) : ∃ (μ : Measure), μ s = x := begin sorry end -- # Continuity Axioms ---------------------- -- Using a combo of the version here and Wikipedia : -- https://www.math.ust.hk/~mabfchen/Math4221/Hilbert%20Axioms.pdf axiom Archimedes (s₁ s₂ : Segment) (μ : Measure) : ∃ (n : nat) (q : Point), μ (s₁.p₁ ⬝ q) = n * μ s₂ ∧ B s₁.p₁ s₁.p₂ q -- Continuity axiom 2 --------------------- -- Axiom of Completeness (Vollständigkeit) : To a system of points, -- straight lines,and planes, it is impossible to add other elements -- in such a manner that the systemthus generalized shall form a new -- geometry obeying all of the five groups of axioms.In other words, -- the elements of geometry form a system which is not susceptible -- ofextension, if we regard the five groups of axioms as valid. -- This axiom talks about completeness in a way that we are unsure can -- be actually implemented. -- axiom line_completeness (l : Line) (X : set Point) : ¬ ∃ l' : Line, -- order_preserved X l l' ∧ cong_preserved X l l'
cf4bdebb973862f66087612a699b5eba7057f3aa
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Elab/Exception.lean
79d171ffe554fc1250c6f158a8ab4adc7122c82e
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,526
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.InternalExceptionId import Lean.Meta.Basic namespace Lean.Elab builtin_initialize postponeExceptionId : InternalExceptionId ← registerInternalExceptionId `postpone builtin_initialize unsupportedSyntaxExceptionId : InternalExceptionId ← registerInternalExceptionId `unsupportedSyntax builtin_initialize abortCommandExceptionId : InternalExceptionId ← registerInternalExceptionId `abortCommandElab builtin_initialize abortTermExceptionId : InternalExceptionId ← registerInternalExceptionId `abortTermElab builtin_initialize autoBoundImplicitExceptionId : InternalExceptionId ← registerInternalExceptionId `autoBoundImplicit def throwPostpone [MonadExceptOf Exception m] : m α := throw $ Exception.internal postponeExceptionId def throwUnsupportedSyntax [MonadExceptOf Exception m] : m α := throw $ Exception.internal unsupportedSyntaxExceptionId def throwIllFormedSyntax [Monad m] [MonadError m] : m α := throwError "ill-formed syntax" def throwAutoBoundImplicitLocal [MonadExceptOf Exception m] (n : Name) : m α := throw $ Exception.internal autoBoundImplicitExceptionId <| KVMap.empty.insert `localId n def isAutoBoundImplicitLocalException? (ex : Exception) : Option Name := match ex with | Exception.internal id k => if id == autoBoundImplicitExceptionId then some <| k.getName `localId `x else none | _ => none def throwAlreadyDeclaredUniverseLevel [Monad m] [MonadError m] (u : Name) : m α := throwError! "a universe level named '{u}' has already been declared" -- Throw exception to abort elaboration of the current command without producing any error message def throwAbortCommand {α m} [MonadExcept Exception m] : m α := throw <| Exception.internal abortCommandExceptionId -- Throw exception to abort elaboration of the current term without producing any error message def throwAbortTerm {α m} [MonadExcept Exception m] : m α := throw <| Exception.internal abortTermExceptionId def isAbortExceptionId (id : InternalExceptionId) : Bool := id == abortCommandExceptionId || id == abortTermExceptionId def mkMessageCore (fileName : String) (fileMap : FileMap) (msgData : MessageData) (severity : MessageSeverity) (pos : String.Pos) : Message := let pos := fileMap.toPosition pos { fileName := fileName, pos := pos, data := msgData, severity := severity } end Lean.Elab
1dea90628e6219c4c8c7abd152cc27d3a9192674
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/248.lean
4cdb5193be9dc00c4a7b165c42f7ed195af8cff6
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
49
lean
@[implemented_by foo] opaque foo (x : Nat) : Nat
c8831cc718d24f5f4a7331dc212548ca758fcf53
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/real/pi/wallis.lean
86f00959999401388b29339aef3bbdfd389874de
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,389
lean
/- Copyright (c) 2021 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang -/ import analysis.special_functions.integrals /-! ### The Wallis Product for Pi -/ namespace real open_locale real topological_space big_operators open filter finset interval_integral lemma integral_sin_pow_div_tendsto_one : tendsto (λ k, (∫ x in 0..π, sin x ^ (2 * k + 1)) / ∫ x in 0..π, sin x ^ (2 * k)) at_top (𝓝 1) := begin have h₃ : ∀ n, (∫ x in 0..π, sin x ^ (2 * n + 1)) / ∫ x in 0..π, sin x ^ (2 * n) ≤ 1 := λ n, (div_le_one (integral_sin_pow_pos _)).mpr (integral_sin_pow_succ_le _), have h₄ : ∀ n, (∫ x in 0..π, sin x ^ (2 * n + 1)) / ∫ x in 0..π, sin x ^ (2 * n) ≥ 2 * n / (2 * n + 1), { rintro ⟨n⟩, { have : 0 ≤ (1 + 1) / π, exact div_nonneg (by norm_num) pi_pos.le, simp [this] }, calc (∫ x in 0..π, sin x ^ (2 * n.succ + 1)) / ∫ x in 0..π, sin x ^ (2 * n.succ) ≥ (∫ x in 0..π, sin x ^ (2 * n.succ + 1)) / ∫ x in 0..π, sin x ^ (2 * n + 1) : by { refine div_le_div (integral_sin_pow_pos _).le le_rfl (integral_sin_pow_pos _) _, convert integral_sin_pow_succ_le (2 * n + 1) using 1 } ... = 2 * ↑(n.succ) / (2 * ↑(n.succ) + 1) : by { rw div_eq_iff (integral_sin_pow_pos (2 * n + 1)).ne', convert integral_sin_pow (2 * n + 1), simp with field_simps, norm_cast } }, refine tendsto_of_tendsto_of_tendsto_of_le_of_le _ _ (λ n, (h₄ n).le) (λ n, (h₃ n)), { refine metric.tendsto_at_top.mpr (λ ε hε, ⟨⌈1 / ε⌉₊, λ n hn, _⟩), have h : (2:ℝ) * n / (2 * n + 1) - 1 = -1 / (2 * n + 1), { conv_lhs { congr, skip, rw ← @div_self _ _ ((2:ℝ) * n + 1) (by { norm_cast, linarith }), }, rw [← sub_div, ← sub_sub, sub_self, zero_sub] }, have hpos : (0:ℝ) < 2 * n + 1, { norm_cast, norm_num }, rw [dist_eq, h, abs_div, abs_neg, abs_one, abs_of_pos hpos, one_div_lt hpos hε], calc 1 / ε ≤ ⌈1 / ε⌉₊ : nat.le_ceil _ ... ≤ n : by exact_mod_cast hn.le ... < 2 * n + 1 : by { norm_cast, linarith } }, { exact tendsto_const_nhds }, end /-- This theorem establishes the Wallis Product for `π`. Our proof is largely about analyzing the behavior of the ratio of the integral of `sin x ^ n` as `n → ∞`. See: https://en.wikipedia.org/wiki/Wallis_product The proof can be broken down into two pieces. (Pieces involving general properties of the integral of `sin x ^n` can be found in `analysis.special_functions.integrals`.) First, we use integration by parts to obtain a recursive formula for `∫ x in 0..π, sin x ^ (n + 2)` in terms of `∫ x in 0..π, sin x ^ n`. From this we can obtain closed form products of `∫ x in 0..π, sin x ^ (2 * n)` and `∫ x in 0..π, sin x ^ (2 * n + 1)` via induction. Next, we study the behavior of the ratio `∫ (x : ℝ) in 0..π, sin x ^ (2 * k + 1)) / ∫ (x : ℝ) in 0..π, sin x ^ (2 * k)` and prove that it converges to one using the squeeze theorem. The final product for `π` is obtained after some algebraic manipulation. -/ theorem tendsto_prod_pi_div_two : tendsto (λ k, ∏ i in range k, (((2:ℝ) * i + 2) / (2 * i + 1)) * ((2 * i + 2) / (2 * i + 3))) at_top (𝓝 (π/2)) := begin suffices h : tendsto (λ k, 2 / π * ∏ i in range k, (((2:ℝ) * i + 2) / (2 * i + 1)) * ((2 * i + 2) / (2 * i + 3))) at_top (𝓝 1), { have := tendsto.const_mul (π / 2) h, have h : π / 2 ≠ 0, norm_num [pi_ne_zero], simp only [← mul_assoc, ← @inv_div _ _ π 2, mul_inv_cancel h, one_mul, mul_one] at this, exact this }, have h : (λ (k : ℕ), (2:ℝ) / π * ∏ (i : ℕ) in range k, ((2 * i + 2) / (2 * i + 1)) * ((2 * i + 2) / (2 * i + 3))) = λ k, (2 * ∏ i in range k, (2 * i + 2) / (2 * i + 3)) / (π * ∏ (i : ℕ) in range k, (2 * i + 1) / (2 * i + 2)), { funext, have h : ∏ (i : ℕ) in range k, ((2:ℝ) * ↑i + 2) / (2 * ↑i + 1) = 1 / (∏ (i : ℕ) in range k, (2 * ↑i + 1) / (2 * ↑i + 2)), { rw [one_div, ← finset.prod_inv_distrib'], refine prod_congr rfl (λ x hx, _), field_simp }, rw [prod_mul_distrib, h], field_simp }, simp only [h, ← integral_sin_pow_even, ← integral_sin_pow_odd], exact integral_sin_pow_div_tendsto_one, end end real
924a00d8469c3ab12b9f8cd90ef3b697f3b0fcbf
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/cubical/square.hlean
328908ef68f082838aaa3a476ca262bff330391d
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
31,941
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer Squares in a type -/ import types.eq open eq equiv is_equiv sigma namespace eq variables {A B : Type} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ a₁ a₂ a₃ a₄ : A} /-a₀₀-/ {p₁₀ p₁₀' : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ {p₀₁ p₀₁' : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ p₂₁' : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} /-a₀₂-/ {p₁₂ p₁₂' : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ inductive square {A : Type} {a₀₀ : A} : Π{a₂₀ a₀₂ a₂₂ : A}, a₀₀ = a₂₀ → a₀₂ = a₂₂ → a₀₀ = a₀₂ → a₂₀ = a₂₂ → Type := ids : square idp idp idp idp /- square top bottom left right -/ variables {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁} {s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃} definition ids [reducible] [constructor] := @square.ids definition idsquare [reducible] [constructor] (a : A) := @square.ids A a definition hrefl [unfold 4] (p : a = a') : square idp idp p p := by induction p; exact ids definition vrefl [unfold 4] (p : a = a') : square p p idp idp := by induction p; exact ids definition hrfl [reducible] [unfold 4] {p : a = a'} : square idp idp p p := !hrefl definition vrfl [reducible] [unfold 4] {p : a = a'} : square p p idp idp := !vrefl definition hdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square idp idp p q := by induction r;apply hrefl definition vdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square p q idp idp := by induction r;apply vrefl definition hdeg_square_idp (p : a = a') : hdeg_square (refl p) = hrfl := by reflexivity definition vdeg_square_idp (p : a = a') : vdeg_square (refl p) = vrfl := by reflexivity definition hconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁) : square (p₁₀ ⬝ p₃₀) (p₁₂ ⬝ p₃₂) p₀₁ p₄₁ := by induction s₃₁; exact s₁₁ definition vconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃) : square p₁₀ p₁₄ (p₀₁ ⬝ p₀₃) (p₂₁ ⬝ p₂₃) := by induction s₁₃; exact s₁₁ definition dconcat [unfold 14] {p₀₀ : a₀₀ = a} {p₂₂ : a = a₂₂} (s₂₁ : square p₀₀ p₁₂ p₀₁ p₂₂) (s₁₂ : square p₁₀ p₂₂ p₀₀ p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction s₁₂; exact s₂₁ definition hinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀⁻¹ p₁₂⁻¹ p₂₁ p₀₁ := by induction s₁₁;exact ids definition vinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₂ p₁₀ p₀₁⁻¹ p₂₁⁻¹ := by induction s₁₁;exact ids definition eq_vconcat [unfold 11] {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ p₂₁ := by induction r; exact s₁₁ definition vconcat_eq [unfold 12] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : square p₁₀ p p₀₁ p₂₁ := by induction r; exact s₁₁ definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := by induction r; exact s₁₁ definition hconcat_eq [unfold 12] {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := by induction r; exact s₁₁ infix ` ⬝h `:69 := hconcat --type using \tr infix ` ⬝v `:70 := vconcat --type using \tr infixl ` ⬝hp `:71 := hconcat_eq --type using \tr infixl ` ⬝vp `:73 := vconcat_eq --type using \tr infixr ` ⬝ph `:72 := eq_hconcat --type using \tr infixr ` ⬝pv `:74 := eq_vconcat --type using \tr postfix `⁻¹ʰ`:(max+1) := hinverse --type using \-1h postfix `⁻¹ᵛ`:(max+1) := vinverse --type using \-1v definition transpose [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₀₁ p₂₁ p₁₀ p₁₂ := by induction s₁₁;exact ids definition aps [unfold 12] (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (ap f p₁₀) (ap f p₁₂) (ap f p₀₁) (ap f p₂₁) := by induction s₁₁;exact ids /- canceling, whiskering and moving thinks along the sides of the square -/ definition whisker_tl (p : a = a₀₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁ := by induction s₁₁;induction p;constructor definition whisker_br (p : a₂₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p) := by induction p;exact s₁₁ definition whisker_rt (p : a = a₂₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁) := by induction s₁₁;induction p;constructor definition whisker_tr (p : a₂₀ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁) := by induction s₁₁;induction p;constructor definition whisker_bl (p : a = a₀₂) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁ := by induction s₁₁;induction p;constructor definition whisker_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁ := by induction s₁₁;induction p;constructor definition cancel_tl (p : a = a₀₀) (s₁₁ : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite +idp_con at s₁₁; exact s₁₁ definition cancel_br (p : a₂₂ = a) (s₁₁ : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p;exact s₁₁ definition cancel_rt (p : a = a₂₀) (s₁₁ : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite idp_con at s₁₁; exact s₁₁ definition cancel_tr (p : a₂₀ = a) (s₁₁ : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite [▸* at s₁₁,idp_con at s₁₁]; exact s₁₁ definition cancel_bl (p : a = a₀₂) (s₁₁ : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite idp_con at s₁₁; exact s₁₁ definition cancel_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite [▸* at s₁₁,idp_con at s₁₁]; exact s₁₁ definition move_top_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁) : square (p⁻¹ ⬝ p₁₀) p₁₂ q p₂₁ := by apply cancel_tl p; rewrite con_inv_cancel_left; exact s definition move_top_of_left' {p : a = a₀₀} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p⁻¹ ⬝ q) p₂₁) : square (p ⬝ p₁₀) p₁₂ q p₂₁ := by apply cancel_tl p⁻¹; rewrite inv_con_cancel_left; exact s definition move_left_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁) : square q p₁₂ (p⁻¹ ⬝ p₀₁) p₂₁ := by apply cancel_tl p; rewrite con_inv_cancel_left; exact s definition move_left_of_top' {p : a = a₀₀} {q : a = a₂₀} (s : square (p⁻¹ ⬝ q) p₁₂ p₀₁ p₂₁) : square q p₁₂ (p ⬝ p₀₁) p₂₁ := by apply cancel_tl p⁻¹; rewrite inv_con_cancel_left; exact s definition move_bot_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q)) : square p₁₀ (p₁₂ ⬝ q⁻¹) p₀₁ p := by apply cancel_br q; rewrite inv_con_cancel_right; exact s definition move_bot_of_right' {p : a₂₀ = a} {q : a₂₂ = a} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q⁻¹)) : square p₁₀ (p₁₂ ⬝ q) p₀₁ p := by apply cancel_br q⁻¹; rewrite con_inv_cancel_right; exact s definition move_right_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁) : square p₁₀ p p₀₁ (p₂₁ ⬝ q⁻¹) := by apply cancel_br q; rewrite inv_con_cancel_right; exact s definition move_right_of_bot' {p : a₀₂ = a} {q : a₂₂ = a} (s : square p₁₀ (p ⬝ q⁻¹) p₀₁ p₂₁) : square p₁₀ p p₀₁ (p₂₁ ⬝ q) := by apply cancel_br q⁻¹; rewrite con_inv_cancel_right; exact s definition move_top_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q)) : square (p₁₀ ⬝ p) p₁₂ p₀₁ q := by apply cancel_rt p; rewrite con_inv_cancel_right; exact s definition move_right_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ (q ⬝ p₂₁) := by apply cancel_tr q; rewrite inv_con_cancel_left; exact s definition move_bot_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁) : square p₁₀ (q ⬝ p₁₂) p p₂₁ := by apply cancel_lb q; rewrite inv_con_cancel_left; exact s definition move_left_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁) : square p₁₀ q (p₀₁ ⬝ p) p₂₁ := by apply cancel_bl p; rewrite con_inv_cancel_right; exact s /- some higher ∞-groupoid operations -/ definition vconcat_vrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝v vrefl p₁₂ = s₁₁ := by induction s₁₁; reflexivity definition hconcat_hrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝h hrefl p₂₁ = s₁₁ := by induction s₁₁; reflexivity /- equivalences -/ definition eq_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂ := by induction s₁₁; apply idp definition square_of_eq (r : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₁₂; esimp at r; induction r; induction p₂₁; induction p₁₀; exact ids definition eq_top_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹ := by induction s₁₁; apply idp definition square_of_eq_top (r : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₂; esimp at r;induction r;induction p₁₀;exact ids definition eq_bot_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₂ = p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ := by induction s₁₁; apply idp definition square_of_eq_bot (r : p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ = p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₀; esimp at r; induction r; induction p₀₁; exact ids definition square_equiv_eq [constructor] (t : a₀₀ = a₀₂) (b : a₂₀ = a₂₂) (l : a₀₀ = a₂₀) (r : a₀₂ = a₂₂) : square t b l r ≃ t ⬝ r = l ⬝ b := begin fapply equiv.MK, { exact eq_of_square}, { exact square_of_eq}, { intro s, induction b, esimp [concat] at s, induction s, induction r, induction t, apply idp}, { intro s, induction s, apply idp}, end definition hdeg_square_equiv' [constructor] (p q : a = a') : square idp idp p q ≃ p = q := by transitivity _;apply square_equiv_eq;transitivity _;apply eq_equiv_eq_symm; apply equiv_eq_closed_right;apply idp_con definition vdeg_square_equiv' [constructor] (p q : a = a') : square p q idp idp ≃ p = q := by transitivity _;apply square_equiv_eq;apply equiv_eq_closed_right; apply idp_con definition eq_of_hdeg_square [reducible] {p q : a = a'} (s : square idp idp p q) : p = q := to_fun !hdeg_square_equiv' s definition eq_of_vdeg_square [reducible] {p q : a = a'} (s : square p q idp idp) : p = q := to_fun !vdeg_square_equiv' s definition top_deg_square (l : a₁ = a₂) (b : a₂ = a₃) (r : a₄ = a₃) : square (l ⬝ b ⬝ r⁻¹) b l r := by induction r;induction b;induction l;constructor definition bot_deg_square (l : a₁ = a₂) (t : a₁ = a₃) (r : a₃ = a₄) : square t (l⁻¹ ⬝ t ⬝ r) l r := by induction r;induction t;induction l;constructor /- the following two equivalences have as underlying inverse function the functions hdeg_square and vdeg_square, respectively. See example below the definition -/ definition hdeg_square_equiv [constructor] (p q : a = a') : square idp idp p q ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply hdeg_square_equiv', exact hdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_hdeg_square}, { reflexivity} end definition vdeg_square_equiv [constructor] (p q : a = a') : square p q idp idp ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply vdeg_square_equiv',exact vdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_vdeg_square}, { reflexivity} end example (p q : a = a') : to_inv (hdeg_square_equiv p q) = hdeg_square := idp /- characterization of pathovers in a equality type. The type B of the equality is fixed here. A version where B may also varies over the path p is given in the file squareover -/ definition eq_pathover [unfold 7] {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : square q r (ap f p) (ap g p)) : q =[p] r := begin induction p, apply pathover_idp_of_eq, exact eq_of_vdeg_square s end definition eq_pathover_constant_left {g : A → B} {p : a = a'} {b : B} {q : b = g a} {r : b = g a'} (s : square q r idp (ap g p)) : q =[p] r := eq_pathover (ap_constant p b ⬝ph s) definition eq_pathover_id_left {g : A → A} {p : a = a'} {q : a = g a} {r : a' = g a'} (s : square q r p (ap g p)) : q =[p] r := eq_pathover (ap_id p ⬝ph s) definition eq_pathover_constant_right {f : A → B} {p : a = a'} {b : B} {q : f a = b} {r : f a' = b} (s : square q r (ap f p) idp) : q =[p] r := eq_pathover (s ⬝hp (ap_constant p b)⁻¹) definition eq_pathover_id_right {f : A → A} {p : a = a'} {q : f a = a} {r : f a' = a'} (s : square q r (ap f p) p) : q =[p] r := eq_pathover (s ⬝hp (ap_id p)⁻¹) definition square_of_pathover [unfold 7] {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : q =[p] r) : square q r (ap f p) (ap g p) := by induction p;apply vdeg_square;exact eq_of_pathover_idp s definition eq_pathover_constant_left_id_right {p : a = a'} {a₀ : A} {q : a₀ = a} {r : a₀ = a'} (s : square q r idp p) : q =[p] r := eq_pathover (ap_constant p a₀ ⬝ph s ⬝hp (ap_id p)⁻¹) definition eq_pathover_id_left_constant_right {p : a = a'} {a₀ : A} {q : a = a₀} {r : a' = a₀} (s : square q r p idp) : q =[p] r := eq_pathover (ap_id p ⬝ph s ⬝hp (ap_constant p a₀)⁻¹) definition loop_pathover {p : a = a'} {q : a = a} {r : a' = a'} (s : square q r p p) : q =[p] r := eq_pathover (ap_id p ⬝ph s ⬝hp (ap_id p)⁻¹) /- interaction of equivalences with operations on squares -/ definition eq_pathover_equiv_square [constructor] {f g : A → B} (p : a = a') (q : f a = g a) (r : f a' = g a') : q =[p] r ≃ square q r (ap f p) (ap g p) := equiv.MK square_of_pathover eq_pathover begin intro s, induction p, esimp [square_of_pathover,eq_pathover], exact ap vdeg_square (to_right_inv !pathover_idp (eq_of_vdeg_square s)) ⬝ to_left_inv !vdeg_square_equiv s end begin intro s, induction p, esimp [square_of_pathover,eq_pathover], exact ap pathover_idp_of_eq (to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s)) ⬝ to_left_inv !pathover_idp s end definition square_of_pathover_eq_concato {f g : A → B} {p : a = a'} {q q' : f a = g a} {r : f a' = g a'} (s' : q = q') (s : q' =[p] r) : square_of_pathover (s' ⬝po s) = s' ⬝pv square_of_pathover s := by induction s;induction s';reflexivity definition square_of_pathover_concato_eq {f g : A → B} {p : a = a'} {q : f a = g a} {r r' : f a' = g a'} (s' : r = r') (s : q =[p] r) : square_of_pathover (s ⬝op s') = square_of_pathover s ⬝vp s' := by induction s;induction s';reflexivity definition square_of_pathover_concato {f g : A → B} {p : a = a'} {p' : a' = a''} {q : f a = g a} {q' : f a' = g a'} {q'' : f a'' = g a''} (s : q =[p] q') (s' : q' =[p'] q'') : square_of_pathover (s ⬝o s') = ap_con f p p' ⬝ph (square_of_pathover s ⬝v square_of_pathover s') ⬝hp (ap_con g p p')⁻¹ := by induction s';induction s;esimp [ap_con,hconcat_eq];exact !vconcat_vrfl⁻¹ definition eq_of_square_hrfl [unfold 4] (p : a = a') : eq_of_square hrfl = idp_con p := by induction p;reflexivity definition eq_of_square_vrfl [unfold 4] (p : a = a') : eq_of_square vrfl = (idp_con p)⁻¹ := by induction p;reflexivity definition eq_of_square_hdeg_square {p q : a = a'} (r : p = q) : eq_of_square (hdeg_square r) = !idp_con ⬝ r⁻¹ := by induction r;induction p;reflexivity definition eq_of_square_vdeg_square {p q : a = a'} (r : p = q) : eq_of_square (vdeg_square r) = r ⬝ !idp_con⁻¹ := by induction r;induction p;reflexivity definition eq_of_square_eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝pv s₁₁) = whisker_right p₂₁ r ⬝ eq_of_square s₁₁ := by induction s₁₁;cases r;reflexivity definition eq_of_square_eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝ph s₁₁) = eq_of_square s₁₁ ⬝ (whisker_right p₁₂ r)⁻¹ := by induction r;reflexivity definition eq_of_square_vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : eq_of_square (s₁₁ ⬝vp r) = eq_of_square s₁₁ ⬝ whisker_left p₀₁ r := by induction r;reflexivity definition eq_of_square_hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : eq_of_square (s₁₁ ⬝hp r) = (whisker_left p₁₀ r)⁻¹ ⬝ eq_of_square s₁₁ := by induction s₁₁; induction r;reflexivity definition change_path_eq_pathover {A B : Type} {a a' : A} {f g : A → B} {p p' : a = a'} (r : p = p') {q : f a = g a} {q' : f a' = g a'} (s : square q q' (ap f p) (ap g p)) : change_path r (eq_pathover s) = eq_pathover ((ap02 f r)⁻¹ ⬝ph s ⬝hp (ap02 g r)) := by induction r; reflexivity definition eq_hconcat_hdeg_square {A : Type} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) : q₁ ⬝ph hdeg_square q₂ = hdeg_square (q₁ ⬝ q₂) := by induction q₁; induction q₂; reflexivity definition hdeg_square_hconcat_eq {A : Type} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) : hdeg_square q₁ ⬝hp q₂ = hdeg_square (q₁ ⬝ q₂) := by induction q₁; induction q₂; reflexivity definition eq_hconcat_eq_hdeg_square {A : Type} {a a' : A} {p₁ p₂ p₃ p₄ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) (q₃ : p₃ = p₄) : q₁ ⬝ph hdeg_square q₂ ⬝hp q₃ = hdeg_square (q₁ ⬝ q₂ ⬝ q₃) := by induction q₃; apply eq_hconcat_hdeg_square -- definition vconcat_eq [unfold 11] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : -- square p₁₀ p p₀₁ p₂₁ := -- by induction r; exact s₁₁ -- definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := -- by induction r; exact s₁₁ -- definition hconcat_eq [unfold 11] {p : a₂₀ = a₂₂} -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := -- by induction r; exact s₁₁ -- the following definition is very slow, maybe it's interesting to see why? -- definition eq_pathover_equiv_square' {f g : A → B}(p : a = a') (q : f a = g a) (r : f a' = g a') -- : square q r (ap f p) (ap g p) ≃ q =[p] r := -- equiv.MK eq_pathover -- square_of_pathover -- (λs, begin -- induction p, rewrite [↑[square_of_pathover,eq_pathover], -- to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s), -- to_left_inv !pathover_idp s] -- end) -- (λs, begin -- induction p, rewrite [↑[square_of_pathover,eq_pathover],▸*, -- to_right_inv !(@pathover_idp A) (eq_of_vdeg_square s), -- to_left_inv !vdeg_square_equiv s] -- end) /- recursors for squares where some sides are reflexivity -/ definition rec_on_b [recursor] {a₀₀ : A} {P : Π{a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂}, square t idp l r → Type} {a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂} (s : square t idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), from eq.rec_on (eq_of_square s : t ⬝ r = l) (by induction r; induction t; exact H), left_inv (to_fun !square_equiv_eq) s ▸ H2 definition rec_on_r [recursor] {a₀₀ : A} {P : Π{a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂}, square t b l idp → Type} {a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂} (s : square t b l idp) (H : P ids) : P s := let p : l ⬝ b = t := (eq_of_square s)⁻¹ in have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx p, P (square_of_eq p⁻¹)) _ p (by induction b; induction l; exact H), left_inv (to_fun !square_equiv_eq) s ▸ !inv_inv ▸ H2 definition rec_on_l [recursor] {a₀₁ : A} {P : Π {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂}, square t b idp r → Type} {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂} (s : square t b idp r) (H : P ids) : P s := let p : t ⬝ r = b := eq_of_square s ⬝ !idp_con in have H2 : P (square_of_eq (p ⬝ !idp_con⁻¹)), from eq.rec_on p (by induction r; induction t; exact H), left_inv (to_fun !square_equiv_eq) s ▸ !con_inv_cancel_right ▸ H2 definition rec_on_t [recursor] {a₁₀ : A} {P : Π {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂}, square idp b l r → Type} {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂} (s : square idp b l r) (H : P ids) : P s := let p : l ⬝ b = r := (eq_of_square s)⁻¹ ⬝ !idp_con in have H2 : P (square_of_eq ((p ⬝ !idp_con⁻¹)⁻¹)), from eq.rec_on p (by induction b; induction l; exact H), have H3 : P (square_of_eq ((eq_of_square s)⁻¹⁻¹)), from eq.rec_on !con_inv_cancel_right H2, have H4 : P (square_of_eq (eq_of_square s)), from eq.rec_on !inv_inv H3, proof left_inv (to_fun !square_equiv_eq) s ▸ H4 qed definition rec_on_tb [recursor] {a : A} {P : Π{b : A} {l : a = b} {r : a = b}, square idp idp l r → Type} {b : A} {l : a = b} {r : a = b} (s : square idp idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), from eq.rec_on (eq_of_square s : idp ⬝ r = l) (by induction r; exact H), left_inv (to_fun !square_equiv_eq) s ▸ H2 definition rec_on_lr [recursor] {a : A} {P : Π{a' : A} {t : a = a'} {b : a = a'}, square t b idp idp → Type} {a' : A} {t : a = a'} {b : a = a'} (s : square t b idp idp) (H : P ids) : P s := let p : idp ⬝ b = t := (eq_of_square s)⁻¹ in have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx q, P (square_of_eq q⁻¹)) _ p (by induction b; exact H), to_left_inv (!square_equiv_eq) s ▸ !inv_inv ▸ H2 --we can also do the other recursors (tl, tr, bl, br, tbl, tbr, tlr, blr), but let's postpone this until they are needed definition whisker_square [unfold 14 15 16 17] (r₁₀ : p₁₀ = p₁₀') (r₁₂ : p₁₂ = p₁₂') (r₀₁ : p₀₁ = p₀₁') (r₂₁ : p₂₁ = p₂₁') (s : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀' p₁₂' p₀₁' p₂₁' := by induction r₁₀; induction r₁₂; induction r₀₁; induction r₂₁; exact s /- squares commute with some operations on 2-paths -/ definition square_inv2 {p₁ p₂ p₃ p₄ : a = a'} {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} (s : square t b l r) : square (inverse2 t) (inverse2 b) (inverse2 l) (inverse2 r) := by induction s;constructor definition square_con2 {p₁ p₂ p₃ p₄ : a₁ = a₂} {q₁ q₂ q₃ q₄ : a₂ = a₃} {t₁ : p₁ = p₂} {b₁ : p₃ = p₄} {l₁ : p₁ = p₃} {r₁ : p₂ = p₄} {t₂ : q₁ = q₂} {b₂ : q₃ = q₄} {l₂ : q₁ = q₃} {r₂ : q₂ = q₄} (s₁ : square t₁ b₁ l₁ r₁) (s₂ : square t₂ b₂ l₂ r₂) : square (t₁ ◾ t₂) (b₁ ◾ b₂) (l₁ ◾ l₂) (r₁ ◾ r₂) := by induction s₂;induction s₁;constructor open is_trunc definition is_set.elims [H : is_set A] : square p₁₀ p₁₂ p₀₁ p₂₁ := square_of_eq !is_set.elim definition is_trunc_square [instance] (n : trunc_index) [H : is_trunc n .+2 A] : is_trunc n (square p₁₀ p₁₂ p₀₁ p₂₁) := is_trunc_equiv_closed_rev n !square_equiv_eq -- definition square_of_con_inv_hsquare {p₁ p₂ p₃ p₄ : a₁ = a₂} -- {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} -- (s : square (con_inv_eq_idp t) (con_inv_eq_idp b) (l ◾ r⁻²) idp) -- : square t b l r := -- sorry --by induction s /- Square fillers -/ -- TODO replace by "more algebraic" fillers? variables (p₁₀ p₁₂ p₀₁ p₂₁) definition square_fill_t : Σ (p : a₀₀ = a₂₀), square p p₁₂ p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, !vrefl⟩ definition square_fill_b : Σ (p : a₀₂ = a₂₂), square p₁₀ p p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, !vrefl⟩ definition square_fill_l : Σ (p : a₀₀ = a₀₂), square p₁₀ p₁₂ p p₂₁ := by induction p₁₀; induction p₁₂; exact ⟨_, !hrefl⟩ definition square_fill_r : Σ (p : a₂₀ = a₂₂) , square p₁₀ p₁₂ p₀₁ p := by induction p₁₀; induction p₁₂; exact ⟨_, !hrefl⟩ /- Squares having an 'ap' term on one face -/ --TODO find better names definition square_Flr_ap_idp {c : B} {f : A → B} (p : Π a, f a = c) {a b : A} (q : a = b) : square (p a) (p b) (ap f q) idp := by induction q; apply vrfl definition square_Flr_idp_ap {c : B} {f : A → B} (p : Π a, c = f a) {a b : A} (q : a = b) : square (p a) (p b) idp (ap f q) := by induction q; apply vrfl definition square_ap_idp_Flr {b : B} {f : A → B} (p : Π a, f a = b) {a b : A} (q : a = b) : square (ap f q) idp (p a) (p b) := by induction q; apply hrfl /- Matching eq_hconcat with hconcat etc. -/ -- TODO maybe rename hconcat_eq and the like? variable (s₁₁) definition ph_eq_pv_h_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) : r ⬝ph s₁₁ = !idp_con⁻¹ ⬝pv ((hdeg_square r) ⬝h s₁₁) ⬝vp !idp_con := by cases r; cases s₁₁; esimp definition hdeg_h_eq_pv_ph_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) : hdeg_square r ⬝h s₁₁ = !idp_con ⬝pv (r ⬝ph s₁₁) ⬝vp !idp_con⁻¹ := by cases r; cases s₁₁; esimp definition hp_eq_h {p : a₂₀ = a₂₂} (r : p₂₁ = p) : s₁₁ ⬝hp r = s₁₁ ⬝h hdeg_square r := by cases r; cases s₁₁; esimp definition pv_eq_ph_vdeg_v_vh {p : a₀₀ = a₂₀} (r : p = p₁₀) : r ⬝pv s₁₁ = !idp_con⁻¹ ⬝ph ((vdeg_square r) ⬝v s₁₁) ⬝hp !idp_con := by cases r; cases s₁₁; esimp definition vdeg_v_eq_ph_pv_hp {p : a₀₀ = a₂₀} (r : p = p₁₀) : vdeg_square r ⬝v s₁₁ = !idp_con ⬝ph (r ⬝pv s₁₁) ⬝hp !idp_con⁻¹ := by cases r; cases s₁₁; esimp definition vp_eq_v {p : a₀₂ = a₂₂} (r : p₁₂ = p) : s₁₁ ⬝vp r = s₁₁ ⬝v vdeg_square r := by cases r; cases s₁₁; esimp definition natural_square [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') : square (p a) (p a') (ap f q) (ap g q) := square_of_pathover (apd p q) definition natural_square_tr [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') : square (ap f q) (ap g q) (p a) (p a') := transpose (natural_square p q) definition natural_square011 {A A' : Type} {B : A → Type} {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') {l r : Π⦃a⦄, B a → A'} (g : Π⦃a⦄ (b : B a), l b = r b) : square (apd011 l p q) (apd011 r p q) (g b) (g b') := begin induction q, exact hrfl end definition natural_square0111' {A A' : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'} {c : C b} {c' : C b'} (s : c =[apd011 C p q] c') {l r : Π⦃a⦄ {b : B a}, C b → A'} (g : Π⦃a⦄ {b : B a} (c : C b), l c = r c) : square (apd0111 l p q s) (apd0111 r p q s) (g c) (g c') := begin induction q, esimp at s, induction s using idp_rec_on, exact hrfl end -- this can be generalized a bit, by making the domain and codomain of k different, and also have -- a function at the RHS of s (similar to m) definition natural_square0111 {A A' : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'} {c : C b} {c' : C b'} (r : c =[apd011 C p q] c') {k : A → A} {l : Π⦃a⦄, B a → B (k a)} (m : Π⦃a⦄ {b : B a}, C b → C (l b)) {f : Π⦃a⦄ {b : B a}, C b → A'} (s : Π⦃a⦄ {b : B a} (c : C b), f (m c) = f c) : square (apd0111 (λa b c, f (m c)) p q r) (apd0111 f p q r) (s c) (s c') := begin induction q, esimp at r, induction r using idp_rec_on, exact hrfl end end eq
5a159a0cc4533b07c362a38ada41744c7013226b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/group_theory/submonoid/inverses.lean
0f5fad76af0e1243b2c9969443e360dc4ee74fb9
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
6,888
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 group_theory.submonoid.pointwise /-! # Submonoid of inverses Given a submonoid `N` of a monoid `M`, we define the submonoid `N.left_inv` as the submonoid of left inverses of `N`. When `M` is commutative, we may define `from_comm_left_inv : N.left_inv →* N` since the inverses are unique. When `N ≤ is_unit.submonoid M`, this is precisely the pointwise inverse of `N`, and we may define `left_inv_equiv : S.left_inv ≃* S`. For the pointwise inverse of submonoids of groups, please refer to `group_theory.submonoid.pointwise`. ## TODO Define the submonoid of right inverses and two-sided inverses. See the comments of #10679 for a possible implementation. -/ variables {M : Type*} namespace submonoid @[to_additive] noncomputable instance [monoid M] : group (is_unit.submonoid M) := { inv := λ x, ⟨_, (x.prop.unit⁻¹).is_unit⟩, mul_left_inv := λ x, subtype.eq x.prop.unit.inv_val, ..(show monoid (is_unit.submonoid M), by apply_instance) } @[to_additive] noncomputable instance [comm_monoid M] : comm_group (is_unit.submonoid M) := { mul_comm := λ a b, mul_comm a b, ..(show group (is_unit.submonoid M), by apply_instance) } @[to_additive] lemma is_unit.submonoid.coe_inv [monoid M] (x : is_unit.submonoid M) : ↑(x⁻¹) = (↑x.prop.unit⁻¹ : M) := rfl section monoid variables [monoid M] (S : submonoid M) /-- `S.left_inv` is the submonoid containing all the left inverses of `S`. -/ @[to_additive "`S.left_neg` is the additive submonoid containing all the left additive inverses of `S`."] def left_inv : submonoid M := { carrier := { x : M | ∃ y : S, x * y = 1 }, one_mem' := ⟨1, mul_one 1⟩, mul_mem' := λ a b ⟨a', ha⟩ ⟨b', hb⟩, ⟨b' * a', by rw [coe_mul, ← mul_assoc, mul_assoc a, hb, mul_one, ha]⟩ } @[to_additive] lemma left_inv_left_inv_le : S.left_inv.left_inv ≤ S := begin rintros x ⟨⟨y, z, h₁⟩, h₂ : x * y = 1⟩, convert z.prop, rw [← mul_one x, ← h₁, ← mul_assoc, h₂, one_mul], end @[to_additive] lemma unit_mem_left_inv (x : Mˣ) (hx : (x : M) ∈ S) : ((x⁻¹ : _) : M) ∈ S.left_inv := ⟨⟨x, hx⟩, x.inv_val⟩ @[to_additive] lemma left_inv_left_inv_eq (hS : S ≤ is_unit.submonoid M) : S.left_inv.left_inv = S := begin refine le_antisymm S.left_inv_left_inv_le _, intros x hx, have : x = ((hS hx).unit⁻¹⁻¹ : Mˣ) := by { rw [inv_inv (hS hx).unit], refl }, rw this, exact S.left_inv.unit_mem_left_inv _ (S.unit_mem_left_inv _ hx) end /-- The function from `S.left_inv` to `S` sending an element to its right inverse in `S`. This is a `monoid_hom` when `M` is commutative. -/ @[to_additive "The function from `S.left_add` to `S` sending an element to its right additive inverse in `S`. This is an `add_monoid_hom` when `M` is commutative."] noncomputable def from_left_inv : S.left_inv → S := λ x, x.prop.some @[simp, to_additive] lemma mul_from_left_inv (x : S.left_inv) : (x : M) * S.from_left_inv x = 1 := x.prop.some_spec @[simp, to_additive] lemma from_left_inv_one : S.from_left_inv 1 = 1 := (one_mul _).symm.trans (subtype.eq $ S.mul_from_left_inv 1) end monoid section comm_monoid variables [comm_monoid M] (S : submonoid M) @[simp, to_additive] lemma from_left_inv_mul (x : S.left_inv) : (S.from_left_inv x : M) * x = 1 := by rw [mul_comm, mul_from_left_inv] @[to_additive] lemma left_inv_le_is_unit : S.left_inv ≤ is_unit.submonoid M := λ x ⟨y, hx⟩, ⟨⟨x, y, hx, mul_comm x y ▸ hx⟩, rfl⟩ @[to_additive] lemma from_left_inv_eq_iff (a : S.left_inv) (b : M) : (S.from_left_inv a : M) = b ↔ (a : M) * b = 1 := by rw [← is_unit.mul_right_inj (left_inv_le_is_unit _ a.prop), S.mul_from_left_inv, eq_comm] /-- The `monoid_hom` from `S.left_inv` to `S` sending an element to its right inverse in `S`. -/ @[to_additive "The `add_monoid_hom` from `S.left_neg` to `S` sending an element to its right additive inverse in `S`.", simps] noncomputable def from_comm_left_inv : S.left_inv →* S := { to_fun := S.from_left_inv, map_one' := S.from_left_inv_one, map_mul' := λ x y, subtype.ext $ by rw [from_left_inv_eq_iff, mul_comm x, submonoid.coe_mul, submonoid.coe_mul, mul_assoc, ← mul_assoc (x : M), mul_from_left_inv, one_mul, mul_from_left_inv] } variable (hS : S ≤ is_unit.submonoid M) include hS /-- The submonoid of pointwise inverse of `S` is `mul_equiv` to `S`. -/ @[to_additive "The additive submonoid of pointwise additive inverse of `S` is `add_equiv` to `S`.", simps apply] noncomputable def left_inv_equiv : S.left_inv ≃* S := { inv_fun := λ x, by { choose x' hx using (hS x.prop), exact ⟨x'.inv, x, hx ▸ x'.inv_val⟩ }, left_inv := λ x, subtype.eq $ begin dsimp, generalize_proofs h, rw ← h.some.mul_left_inj, exact h.some.inv_val.trans ((S.mul_from_left_inv x).symm.trans (by rw h.some_spec)), end, right_inv := λ x, by { dsimp, ext, rw [from_left_inv_eq_iff], convert (hS x.prop).some.inv_val, exact (hS x.prop).some_spec.symm }, ..S.from_comm_left_inv } @[simp, to_additive] lemma from_left_inv_left_inv_equiv_symm (x : S) : S.from_left_inv ((S.left_inv_equiv hS).symm x) = x := (S.left_inv_equiv hS).right_inv x @[simp, to_additive] lemma left_inv_equiv_symm_from_left_inv (x : S.left_inv) : (S.left_inv_equiv hS).symm (S.from_left_inv x) = x := (S.left_inv_equiv hS).left_inv x @[to_additive] lemma left_inv_equiv_mul (x : S.left_inv) : (S.left_inv_equiv hS x : M) * x = 1 := by simp @[to_additive] lemma mul_left_inv_equiv (x : S.left_inv) : (x : M) * S.left_inv_equiv hS x = 1 := by simp @[simp, to_additive] lemma left_inv_equiv_symm_mul (x : S) : ((S.left_inv_equiv hS).symm x : M) * x = 1 := by { convert S.mul_left_inv_equiv hS ((S.left_inv_equiv hS).symm x), simp } @[simp, to_additive] lemma mul_left_inv_equiv_symm (x : S) : (x : M) * (S.left_inv_equiv hS).symm x = 1 := by { convert S.left_inv_equiv_mul hS ((S.left_inv_equiv hS).symm x), simp } end comm_monoid section group variables [group M] (S : submonoid M) open_locale pointwise @[to_additive] lemma left_inv_eq_inv : S.left_inv = S⁻¹ := submonoid.ext $ λ x, ⟨λ h, submonoid.mem_inv.mpr ((inv_eq_of_mul_eq_one h.some_spec).symm ▸ h.some.prop), λ h, ⟨⟨_, h⟩, mul_right_inv _⟩⟩ @[simp, to_additive] lemma from_left_inv_eq_inv (x : S.left_inv) : (S.from_left_inv x : M) = x⁻¹ := by rw [← mul_right_inj (x : M), mul_right_inv, mul_from_left_inv] end group section comm_group variables [comm_group M] (S : submonoid M) (hS : S ≤ is_unit.submonoid M) @[simp, to_additive] lemma left_inv_equiv_symm_eq_inv (x : S) : ((S.left_inv_equiv hS).symm x : M) = x⁻¹ := by rw [← mul_right_inj (x : M), mul_right_inv, mul_left_inv_equiv_symm] end comm_group end submonoid
e88d1ee7f6fcd0f1a72f49d6bf0b7d1392820dcb
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/finset/lattice.lean
1842b7855efa1ac466bbea4bbd5a950ef15e6a31
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
17,602
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.fold import data.multiset.lattice /-! # Lattice operations on multisets -/ variables {α β γ : Type*} namespace finset open multiset /-! ### sup -/ section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_def : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b := sup_singleton lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := begin apply iff.trans multiset.sup_le, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := sup_le_iff.2 lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := sup_le_iff.1 (le_refl _) _ hb lemma sup_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.sup f ≤ s.sup g := sup_le (λ b hb, le_trans (h b hb) (le_sup hb)) lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀b ∈ s, f b < a) := by letI := classical.dec_eq β; from ⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h, finset.induction_on s (by simp [ha]) (by simp {contextual := tt}) ⟩ lemma comp_sup_eq_sup_comp [semilattice_sup_bot γ] {s : finset β} {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [g_sup] {contextual := tt}) lemma comp_sup_eq_sup_comp_of_is_total [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := comp_sup_eq_sup_comp g mono_g.map_sup bot /-- Computating `sup` in a subtype (closed under `sup`) is the same as computing it in `α`. -/ lemma sup_coe {P : α → Prop} {Pbot : P ⊥} {Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)} (t : finset β) (f : β → {x : α // P x}) : (@sup _ _ (subtype.semilattice_sup_bot Pbot Psup) t f : α) = t.sup (λ x, f x) := by { classical, rw [comp_sup_eq_sup_comp coe]; intros; refl } theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ := λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) /-! ### inf -/ section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_def : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀b ∈ s, a ≤ f b := @sup_le_iff (order_dual α) _ _ _ _ _ @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton {b : β} : ({b} : finset β).inf f = f b := inf_singleton lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := @sup_union (order_dual α) _ _ _ _ _ _ theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := le_inf_iff.1 (le_refl _) _ hb lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := le_inf_iff.2 lemma inf_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.inf f ≤ s.inf g := le_inf (λ b hb, le_trans (inf_le hb) (h b hb)) lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf_iff [h : is_total α (≤)] {a : α} (ha : a < ⊤) : a < s.inf f ↔ (∀b ∈ s, a < f b) := @sup_lt_iff (order_dual α) _ _ _ _ (@is_total.swap α _ h) _ ha lemma comp_inf_eq_inf_comp [semilattice_inf_top γ] {s : finset β} {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := @comp_sup_eq_sup_comp (order_dual α) _ (order_dual γ) _ _ _ _ _ g_inf top lemma comp_inf_eq_inf_comp_of_is_total [h : is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := comp_inf_eq_inf_comp g mono_g.map_inf top /-- Computating `inf` in a subtype (closed under `inf`) is the same as computing it in `α`. -/ lemma inf_coe {P : α → Prop} {Ptop : P ⊤} {Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)} (t : finset β) (f : β → {x : α // P x}) : (@inf _ _ (subtype.semilattice_inf_top Ptop Pinf) t f : α) = t.inf (λ x, f x) := by { classical, rw [comp_inf_eq_inf_comp coe]; intros; refl } end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := @sup_eq_supr _ (order_dual β) _ _ _ /-! ### max and min of finite sets -/ section max_min variables [decidable_linear_order α] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := by { rw [← insert_emptyc_eq], exact max_insert } theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := by { rw ← insert_emptyc_eq, exact min_insert } theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Given a nonempty finset `s` in a linear order `α `, then `s.min' h` is its minimum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `option α`. -/ def min' (s : finset α) (H : s.nonempty) : α := @option.get _ s.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] /-- Given a nonempty finset `s` in a linear order `α `, then `s.max' h` is its maximum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `option α`. -/ def max' (s : finset α) (H : s.nonempty) : α := @option.get _ s.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (s : finset α) (H : s.nonempty) theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ s) : s.min' H ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ $ min'_mem _ _ theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' H := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ $ max'_mem _ _ theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) : s.min' H < s.max' H := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le s H i H1, have H6 := le_max' s H j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le s H j H2, have H6 := le_max' s H i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end /-- If there's more than 1 element, the min' is less than the max'. An alternate version of `min'_lt_max'` which is sometimes more convenient. -/ lemma min'_lt_max'_of_card (h₂ : 1 < card s) : s.min' H < s.max' H := begin apply lt_of_not_ge, intro a, apply not_le_of_lt h₂ (le_of_eq _), rw card_eq_one, use max' s H, rw eq_singleton_iff_unique_mem, refine ⟨max'_mem _ _, λ t Ht, le_antisymm (le_max' s H t Ht) (le_trans a (min'_le s H t Ht))⟩, end end max_min section exists_max_min variables [linear_order α] lemma exists_max_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := begin letI := classical.DLO α, cases max_of_nonempty (h.image f) with y hy, rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', le_max_of_mem (mem_image_of_mem f hx') hy⟩, end lemma exists_min_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := @exists_max_image (order_dual α) β _ s f h end exists_max_min end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset section lattice variables {ι : Sort*} [complete_lattice α] lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) := begin classical, exact le_antisymm (supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) end lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) := @supr_eq_supr_finset (order_dual α) _ _ _ end lattice namespace set variables {ι : Sort*} lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) := supr_eq_supr_finset s lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) := infi_eq_infi_finset s end set namespace finset /-! ### Interaction with big lattice/set operations -/ section lattice lemma supr_coe [has_Sup β] (f : α → β) (s : finset α) : (⨆ x ∈ (↑s : set α), f x) = ⨆ x ∈ s, f x := rfl lemma infi_coe [has_Inf β] (f : α → β) (s : finset α) : (⨅ x ∈ (↑s : set α), f x) = ⨅ x ∈ s, f x := rfl variables [complete_lattice β] theorem supr_singleton (a : α) (s : α → β) : (⨆ x ∈ ({a} : finset α), s x) = s a := by simp theorem infi_singleton (a : α) (s : α → β) : (⨅ x ∈ ({a} : finset α), s x) = s a := by simp variables [decidable_eq α] theorem supr_union {f : α → β} {s t : finset α} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := by simp [supr_or, supr_sup_eq] theorem infi_union {f : α → β} {s t : finset α} : (⨅ x ∈ s ∪ t, f x) = (⨅ x ∈ s, f x) ⊓ (⨅ x ∈ t, f x) := by simp [infi_or, infi_inf_eq] lemma supr_insert (a : α) (s : finset α) (t : α → β) : (⨆ x ∈ insert a s, t x) = t a ⊔ (⨆ x ∈ s, t x) := by { rw insert_eq, simp only [supr_union, finset.supr_singleton] } lemma infi_insert (a : α) (s : finset α) (t : α → β) : (⨅ x ∈ insert a s, t x) = t a ⊓ (⨅ x ∈ s, t x) := by { rw insert_eq, simp only [infi_union, finset.infi_singleton] } lemma supr_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨆ x ∈ s.image f, g x) = (⨆ y ∈ s, g (f y)) := by rw [← supr_coe, coe_image, supr_image, supr_coe] lemma infi_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨅ x ∈ s.image f, g x) = (⨅ y ∈ s, g (f y)) := by rw [← infi_coe, coe_image, infi_image, infi_coe] end lattice @[simp] theorem bUnion_coe (s : finset α) (t : α → set β) : (⋃ x ∈ (↑s : set α), t x) = ⋃ x ∈ s, t x := rfl @[simp] theorem bInter_coe (s : finset α) (t : α → set β) : (⋂ x ∈ (↑s : set α), t x) = ⋂ x ∈ s, t x := rfl @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton a s @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : finset α), s x) = s a := infi_singleton a s @[simp] lemma bUnion_preimage_singleton (f : α → β) (s : finset β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' ↑s := set.bUnion_preimage_singleton f ↑s variables [decidable_eq α] lemma bUnion_union (s t : finset α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union lemma bInter_inter (s t : finset α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union @[simp] lemma bUnion_insert (a : α) (s : finset α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := supr_insert a s t @[simp] lemma bInter_insert (a : α) (s : finset α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := infi_insert a s t @[simp] lemma bUnion_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋃x ∈ s.image f, g x) = (⋃y ∈ s, g (f y)) := supr_finset_image @[simp] lemma bInter_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋂ x ∈ s.image f, g x) = (⋂ y ∈ s, g (f y)) := infi_finset_image end finset
d308691538bd8ec67977efa3ef4eaad73c16c341
f7315930643edc12e76c229a742d5446dad77097
/tests/lean/run/univ1.lean
62c3dfca7e2fbb3b64eb542ebe7b290f49d6f8aa
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
644
lean
import logic namespace S1 axiom I : Type definition F (X : Type) : Type := (X → Prop) → Prop axiom unfold.{l} : I.{l} → F I.{l} axiom foldd.{l} : F I.{l} → I.{l} axiom iso1 : ∀x, foldd (unfold x) = x end S1 namespace S2 universe u axiom I : Type.{u} definition F (X : Type) : Type := (X → Prop) → Prop axiom unfold : I → F I axiom foldd : F I → I axiom iso1 : ∀x, foldd (unfold x) = x end S2 namespace S3 section hypothesis I : Type definition F (X : Type) : Type := (X → Prop) → Prop hypothesis unfold : I → F I hypothesis foldd : F I → I hypothesis iso1 : ∀x, foldd (unfold x) = x end end S3
5873d55defa29bc78c5c646edbaee9399b48c1f7
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/src/simplex.lean
8f16a27e62e0a0de50698c0adff956e766ca9528
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
44,339
lean
import tableau order.lexicographic open matrix fintype finset function pequiv partition variables {m n : ℕ} local notation `rvec`:2000 n := matrix (fin 1) (fin n) ℚ local notation `cvec`:2000 m := matrix (fin m) (fin 1) ℚ local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := transpose namespace tableau def pivot_col (T : tableau m n) (obj : fin m) : option (fin n) := option.cases_on (fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted ∧ c ∉ T.dead)) (((list.fin_range n).filter (λ c : fin n, 0 < T.to_matrix obj c ∧ c ∉ T.dead)).argmin T.to_partition.colg) some def to_lex (T : tableau m n) (c : fin n) (r' : fin m) : lex ℚ (fin (m + n)) := (abs (T.const r' 0 / T.to_matrix r' c), T.to_partition.rowg r') lemma to_lex_le_iff (T : tableau m n) (c : fin n) (i i' : fin m) : to_lex T c i ≤ to_lex T c i' ↔ abs (T.const i 0 / T.to_matrix i c) < abs (T.const i' 0 / T.to_matrix i' c) ∨ (abs (T.const i 0 / T.to_matrix i c) = abs (T.const i' 0 / T.to_matrix i' c) ∧ T.to_partition.rowg i ≤ T.to_partition.rowg i') := prod.lex_def _ _ def pivot_row (T : tableau m n) (obj: fin m) (c : fin n) : option (fin m) := let l := (list.fin_range m).filter (λ i : fin m, obj ≠ i ∧ T.to_partition.rowg i ∈ T.restricted ∧ T.to_matrix obj c / T.to_matrix i c < 0) in list.argmin (to_lex T c) l lemma pivot_col_spec {T : tableau m n} {obj : fin m} {c : fin n} : c ∈ pivot_col T obj → ((T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted) ∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted)) ∧ c ∉ T.dead := begin dsimp only [pivot_col], cases h : fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted ∧ c ∉ T.dead), { have := not_and.1 (fin.find_eq_none_iff.1 h c) ∘ ne_of_gt, simp only [list.argmin_eq_some_iff, option.mem_def, list.mem_filter, list.mem_fin_range, gt] at * {contextual := tt}, tauto }, { finish [fin.find_eq_some_iff] } end lemma nonpos_of_lt_pivot_col {T : tableau m n} {obj : fin m} {c j : fin n} (hc : c ∈ pivot_col T obj) (hcres : T.to_partition.colg c ∈ T.restricted) (hdead : j ∉ T.dead) (hjc : T.to_partition.colg j < T.to_partition.colg c) : T.to_matrix obj j ≤ 0 := begin rw [pivot_col] at hc, cases h : fin.find (λ c, T.to_matrix obj c ≠ 0 ∧ colg (T.to_partition) c ∉ T.restricted ∧ c ∉ T.dead), { rw h at hc, refine le_of_not_lt (λ hj0, _), exact not_le_of_gt hjc ((list.mem_argmin_iff.1 hc).2.1 j (list.mem_filter.2 (by simp [hj0, hdead]))) }, { rw h at hc, simp [*, fin.find_eq_some_iff] at * } end lemma pivot_col_eq_none_aux {T : tableau m n} {obj : fin m} (hT : T.feasible) {c : fin n} : pivot_col T obj = none → c ∉ T.dead → ((T.to_matrix obj c = 0 ∧ T.to_partition.colg c ∉ T.restricted) ∨ (T.to_matrix obj c ≤ 0 ∧ T.to_partition.colg c ∈ T.restricted)) := begin simp only [pivot_col], cases h : fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted ∧ c ∉ T.dead), { simp only [list.filter_eq_nil, list.argmin_eq_none, not_and', list.mem_fin_range, true_implies_iff, not_lt, fin.find_eq_none_iff, and_imp, not_not] at *, assume hnonneg hdead, by_cases hres : T.to_partition.colg c ∈ T.restricted; simp * at * }, { simp } end lemma pivot_col_eq_none {T : tableau m n} {obj : fin m} (hT : T.feasible) (h : pivot_col T obj = none) : T.is_optimal (T.of_col 0) (T.to_partition.rowg obj) := is_optimal_of_col_zero hT (λ j hj, begin have := pivot_col_eq_none_aux hT h hj, finish [lt_irrefl] end) lemma pivot_row_spec {T : tableau m n} {obj i : fin m} {c : fin n} : i ∈ pivot_row T obj c → obj ≠ i ∧ T.to_partition.rowg i ∈ T.restricted ∧ T.to_matrix obj c / T.to_matrix i c < 0 ∧ (∀ i' : fin m, obj ≠ i' → T.to_partition.rowg i' ∈ T.restricted → T.to_matrix obj c / T.to_matrix i' c < 0 → abs (T.const i 0 / T.to_matrix i c) ≤ abs (T.const i' 0 / T.to_matrix i' c)) := begin simp only [list.mem_filter, pivot_row, option.mem_def, list.argmin_eq_some_iff, list.mem_fin_range, true_and, and_imp], simp only [to_lex_le_iff], intros hor hres hr0 h _, simp only [*, true_and, ne.def, not_false_iff], intros i' hoi' hres' hi0', cases h i' hoi' hres' hi0', { exact le_of_lt (by assumption) }, { exact le_of_eq (by tauto) } end lemma nonneg_of_lt_pivot_row {T : tableau m n} {obj : fin m} {i i' : fin m} {c : fin n} (hc0 : 0 < T.to_matrix obj c) (hres : T.to_partition.rowg i' ∈ T.restricted) (hc : c ∈ pivot_col T obj) (hrow : i ∈ pivot_row T obj c) (hconst : T.const i' 0 = 0) (hjc : T.to_partition.rowg i' < T.to_partition.rowg i) : 0 ≤ T.to_matrix i' c := if hobj : obj = i' then le_of_lt $ hobj ▸ hc0 else le_of_not_gt $ λ hic, not_le_of_lt hjc begin have := (list.argmin_eq_some_iff.1 hrow).2.1 i' (list.mem_filter.2 ⟨list.mem_fin_range _, hobj, hres, div_neg_of_pos_of_neg hc0 hic⟩), simp [hconst, not_lt_of_ge (abs_nonneg _), *, to_lex_le_iff] at * end lemma ne_zero_of_mem_pivot_row {T : tableau m n} {obj i : fin m} {c : fin n} (hrow : i ∈ pivot_row T obj c) : T.to_matrix i c ≠ 0 := assume hrc, by simpa [lt_irrefl, hrc] using pivot_row_spec hrow lemma ne_zero_of_mem_pivot_col {T : tableau m n} {obj : fin m} {c : fin n} (hc : c ∈ pivot_col T obj) : T.to_matrix obj c ≠ 0 := λ h, by simpa [h, lt_irrefl] using pivot_col_spec hc lemma pivot_row_eq_none_aux {T : tableau m n} {obj : fin m} {c : fin n} (hrow : pivot_row T obj c = none) (hs : c ∈ pivot_col T obj) : ∀ i, obj ≠ i → T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix obj c / T.to_matrix i c := by simpa [pivot_row, list.filter_eq_nil] using hrow lemma pivot_row_eq_none {T : tableau m n} {obj : fin m} {c : fin n} (hT : T.feasible) (hrow : pivot_row T obj c = none) (hs : c ∈ pivot_col T obj) : T.is_unbounded_above (T.to_partition.rowg obj) := have hrow : ∀ i, obj ≠ i → T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix obj c / T.to_matrix i c, from pivot_row_eq_none_aux hrow hs, have hc : ((T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted) ∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted)) ∧ c ∉ T.dead, from pivot_col_spec hs, have hToc : T.to_matrix obj c ≠ 0, from λ h, by simpa [h, lt_irrefl] using hc, (lt_or_gt_of_ne hToc).elim (λ hToc : T.to_matrix obj c < 0, is_unbounded_above_rowg_of_nonpos hT c (hc.1.elim and.right (λ h, (not_lt_of_gt hToc h.1).elim)) hc.2 (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToc)) (λ hoi : obj ≠ i, inv_nonpos.1 $ nonpos_of_mul_nonneg_right (hrow _ hoi hi) hToc)) hToc) (λ hToc : 0 < T.to_matrix obj c, is_unbounded_above_rowg_of_nonneg hT c (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToc)) (λ hoi : obj ≠ i, inv_nonneg.1 $ nonneg_of_mul_nonneg_left (hrow _ hoi hi) hToc)) hc.2 hToc) def feasible_of_mem_pivot_row_and_col {T : tableau m n} {obj : fin m} (hT : T.feasible) {c} (hc : c ∈ pivot_col T obj) {i} (hr : i ∈ pivot_row T obj c) : feasible (T.pivot i c) := begin have := pivot_col_spec hc, have := pivot_row_spec hr, have := @feasible_simplex_pivot _ _ _ obj hT i c, tauto end section blands_rule local attribute [instance, priority 0] classical.dec variable (obj : fin m) def fickle (T T' : tableau m n) (v : fin (m + n)) : Prop := T.to_partition.rowp v ≠ T'.to_partition.rowp v ∨ T.to_partition.colp v ≠ T'.to_partition.colp v lemma fickle_symm {T T' : tableau m n} {v : fin (m + n)} : fickle T T' v ↔ fickle T' T v := by simp [fickle, eq_comm] lemma fickle_colg_iff_ne {T T' : tableau m n} {j : fin n} : fickle T T' (T.to_partition.colg j) ↔ T.to_partition.colg j ≠ T'.to_partition.colg j := ⟨λ h h', h.elim (by rw [rowp_colg_eq_none, h', rowp_colg_eq_none]; simp) (by rw [colp_colg, h', colp_colg]; simp), λ h, or.inr $ λ h', h begin have : T'.to_partition.colp (T.to_partition.colg j) = some j, { simpa [eq_comm] using h' }, rwa [← pequiv.eq_some_iff, colp_symm_eq_some_colg, option.some_inj, eq_comm] at this end⟩ lemma fickle_rowg_iff_ne {T T' : tableau m n} {i : fin m} : fickle T T' (T.to_partition.rowg i) ↔ T.to_partition.rowg i ≠ T'.to_partition.rowg i := ⟨λ h h', h.elim (by rw [rowp_rowg, h', rowp_rowg]; simp) (by rw [colp_rowg_eq_none, h', colp_rowg_eq_none]; simp), λ h, or.inl $ λ h', h begin have : T'.to_partition.rowp (T.to_partition.rowg i) = some i, { simpa [eq_comm] using h' }, rwa [← pequiv.eq_some_iff, rowp_symm_eq_some_rowg, option.some_inj, eq_comm] at this end⟩ lemma not_unique_row_and_unique_col {T T' : tableau m n} {i c c'} (hcobj0 : 0 < T.to_matrix obj c) (hc'obj0 : 0 < T'.to_matrix obj c') (hrc0 : T.to_matrix i c < 0) (hflat : T.flat = T'.flat) (hs : T.to_partition.rowg i = T'.to_partition.colg c') (hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj) (hfickle : ∀ i, (fickle T T' (T.to_partition.rowg i)) → T.const i 0 = 0) (hobj : T.const obj 0 = T'.const obj 0) (nonpos_of_colg_eq : ∀ j, j ≠ c' → T'.to_partition.colg j = T.to_partition.colg c → T'.to_matrix obj j ≤ 0) (unique_col : ∀ j, (fickle T' T (T'.to_partition.colg j)) → j ≠ c' → T'.to_matrix obj j ≤ 0) (unique_row : ∀ i' ≠ i, T.const i' 0 = 0 → fickle T T' (T.to_partition.rowg i') → 0 ≤ T.to_matrix i' c) : false := let objr := T.to_partition.rowg obj in let x := λ y : ℚ, T.of_col (y • (single c 0).to_matrix) in have hxflatT' : ∀ {y}, x y ∈ flat T', from hflat ▸ λ _, of_col_mem_flat _ _, have hxrow : ∀ y i, x y (T.to_partition.rowg i) 0 = T.const i 0 + y * T.to_matrix i c, by simp [x, of_col_single_rowg], have hxcol : ∀ {y j}, j ≠ c → x y (T.to_partition.colg j) 0 = 0, from λ y j hjc, by simp [x, of_col_colg, pequiv.to_matrix, single_apply_of_ne hjc.symm], have hxcolc : ∀ {y}, x y (T.to_partition.colg c) 0 = y, by simp [x, of_col_colg, pequiv.to_matrix], let c_star : fin (m + n) → ℚ := λ v, option.cases_on (T'.to_partition.colp v) 0 (T'.to_matrix obj) in have hxobj : ∀ y, x y objr 0 = T.const obj 0 + y * T.to_matrix obj c, from λ y, hxrow _ _, have hgetr : ∀ {y v}, c_star v * x y v 0 ≠ 0 → (T'.to_partition.colp v).is_some, from λ y v, by cases h : T'.to_partition.colp v; dsimp [c_star]; rw h; simp, have c_star_eq_get : ∀ {v} (hv : (T'.to_partition.colp v).is_some), c_star v = T'.to_matrix obj (option.get hv), from λ v hv, by dsimp only [c_star]; conv_lhs{rw [← option.some_get hv]}; refl, have hsummmn : ∀ {y}, sum univ (λ j, T'.to_matrix obj j * x y (T'.to_partition.colg j) 0) = sum univ (λ v, c_star v * x y v 0), from λ y, sum_bij_ne_zero (λ j _ _, T'.to_partition.colg j) (λ _ _ _, mem_univ _) (λ _ _ _ _ _ _ h, T'.to_partition.injective_colg h) (λ v _ h0, ⟨option.get (hgetr h0), mem_univ _, by rw [← c_star_eq_get (hgetr h0)]; simpa using h0, by simp⟩) (λ _ _ h0, by dsimp [c_star]; rw [colp_colg]), have hgetc : ∀ {y v}, c_star v * x y v 0 ≠ 0 → v ≠ T.to_partition.colg c → (T.to_partition.rowp v).is_some, from λ y v, (eq_rowg_or_colg T.to_partition v).elim (λ ⟨i, hi⟩, by rw [hi, rowp_rowg]; simp) (λ ⟨j, hj⟩ h0 hvc, by rw [hj, hxcol (mt (congr_arg T.to_partition.colg) (hvc ∘ hj.trans)), mul_zero] at h0; exact (h0 rfl).elim), have hsummmnn : ∀ {y}, (univ.erase (T.to_partition.colg c)).sum (λ v, c_star v * x y v 0) = univ.sum (λ i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0), from λ y, eq.symm $ sum_bij_ne_zero (λ i _ _, T.to_partition.rowg i) (by simp) (λ _ _ _ _ _ _ h, T.to_partition.injective_rowg h) (λ v hvc h0, ⟨option.get (hgetc h0 (mem_erase.1 hvc).1), mem_univ _, by simpa using h0⟩) (by intros; refl), have hsumm : ∀ {y}, univ.sum (λ i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0) = univ.sum (λ i, c_star (T.to_partition.rowg i) * T.const i 0) + y * univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c), from λ y, by simp only [hxrow, mul_add, add_mul, sum_add_distrib, mul_assoc, mul_left_comm _ y, mul_sum.symm], have hxobj' : ∀ y, x y objr 0 = univ.sum (λ v, c_star v * x y v 0) + T'.const obj 0, from λ y, by dsimp [objr]; rw [hrobj, mem_flat_iff.1 hxflatT', hsummmn], have hy : ∀ {y}, y * T.to_matrix obj c = c_star (T.to_partition.colg c) * y + univ.sum (λ i, c_star (T.to_partition.rowg i) * T.const i 0) + y * univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c), from λ y, by rw [← add_left_inj (T.const obj 0), ← hxobj, hxobj', ← insert_erase (mem_univ (T.to_partition.colg c)), sum_insert (not_mem_erase _ _), hsummmnn, hobj, hsumm, hxcolc]; simp, have hy' : ∀ (y), y * (T.to_matrix obj c - c_star (T.to_partition.colg c) - univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c)) = univ.sum (λ i, c_star (T.to_partition.rowg i) * T.const i 0), from λ y, by rw [mul_sub, mul_sub, hy]; simp [mul_comm, mul_assoc, mul_left_comm], have h0 : T.to_matrix obj c - c_star (T.to_partition.colg c) - univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c) = 0, by rw [← (domain.mul_left_inj (@one_ne_zero ℚ _)), hy', ← hy' 0, zero_mul, mul_zero], have hcolnec' : T'.to_partition.colp (T.to_partition.colg c) ≠ some c', from λ h, by simpa [hs.symm] using congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd, have eq_of_roweqc' : ∀ {i'}, T'.to_partition.colp (T.to_partition.rowg i') = some c' → i' = i, from λ i' h, by simpa [hs.symm, T.to_partition.injective_rowg.eq_iff] using congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd, have sumpos : 0 < univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c), by rw [← sub_eq_zero.1 h0]; exact add_pos_of_pos_of_nonneg hcobj0 (begin simp only [c_star, neg_nonneg], cases h : T'.to_partition.colp (T.to_partition.colg c) with j, { refl }, { exact nonpos_of_colg_eq j (mt (congr_arg some) (h ▸ hcolnec')) (by rw [← (option.eq_some_iff_get_eq.1 h).snd]; simp) } end), have hexi : ∃ i', 0 < c_star (T.to_partition.rowg i') * T.to_matrix i' c, from imp_of_not_imp_not _ _ (by simpa using @sum_nonpos _ _ (@univ (fin m) _) (λ i', c_star (T.to_partition.rowg i') * T.to_matrix i' c) _ _) sumpos, let ⟨i', hi'⟩ := hexi in have hi'0 : T.const i' 0 = 0, from hfickle i' (fickle_rowg_iff_ne.2 $ λ h, by dsimp [c_star] at hi'; rw [h, colp_rowg_eq_none] at hi'; simpa [lt_irrefl] using hi'), have hi'_some : (T'.to_partition.colp (T.to_partition.rowg i')).is_some, from option.ne_none_iff_is_some.1 (λ h, by dsimp only [c_star] at hi'; rw h at hi'; simpa [lt_irrefl] using hi'), have hi' : 0 < T'.to_matrix obj (option.get hi'_some) * T.to_matrix i' c, by dsimp only [c_star] at hi'; rwa [← option.some_get hi'_some] at hi', have hii : i' ≠ i, from λ hir, begin have : option.get hi'_some = c', from T'.to_partition.injective_colg (by rw [colg_get_colp_symm, ← hs, hir]), rw [this, hir] at hi', exact not_lt_of_gt hi' (mul_neg_of_pos_of_neg hc'obj0 hrc0) end, have hnec' : option.get hi'_some ≠ c', from λ eq_c', hii $ @eq_of_roweqc' i' (eq_c' ▸ by simp), have hic0 : T.to_matrix i' c < 0, from neg_of_mul_pos_right hi' (unique_col _ (by rw [fickle_colg_iff_ne]; simp) hnec'), not_le_of_gt hic0 (unique_row _ hii hi'0 (by rw [fickle_rowg_iff_ne, ← colg_get_colp_symm _ _ hi'_some]; exact colg_ne_rowg _ _ _)) inductive rel : tableau m n → tableau m n → Prop | pivot : ∀ {T}, feasible T → ∀ {i c}, c ∈ pivot_col T obj → i ∈ pivot_row T obj c → rel (T.pivot i c) T | trans_pivot : ∀ {T₁ T₂ i c}, rel T₁ T₂ → c ∈ pivot_col T₁ obj → i ∈ pivot_row T₁ obj c → rel (T₁.pivot i c) T₂ lemma feasible_of_rel_right {T T' : tableau m n} (h : rel obj T' T) : T.feasible := rel.rec_on h (by tauto) (by tauto) lemma feasible_of_rel_left {T T' : tableau m n} (h : rel obj T' T) : T'.feasible := rel.rec_on h (λ _ hT _ _ hc hr, feasible_of_mem_pivot_row_and_col hT hc hr) (λ _ _ _ _ _ hc hr hT, feasible_of_mem_pivot_row_and_col hT hc hr) /-- Slightly stronger recursor than the default recursor -/ @[elab_as_eliminator] lemma rel.rec_on' {obj : fin m} {C : tableau m n → tableau m n → Prop} {T T' : tableau m n} (hrel : rel obj T T') (hpivot : ∀ {T : tableau m n} {i : fin m} {c : fin n}, feasible T → c ∈ pivot_col T obj → i ∈ pivot_row T obj c → C (pivot T i c) T) (hpivot_trans : ∀ {T₁ T₂ : tableau m n} {i : fin m} {c : fin n}, rel obj (T₁.pivot i c) T₁ → rel obj T₁ T₂ → c ∈ pivot_col T₁ obj → i ∈ pivot_row T₁ obj c → C (T₁.pivot i c) T₁ → C T₁ T₂ → C (pivot T₁ i c) T₂) : C T T' := rel.rec_on hrel (λ T hT i c hc hr, hpivot hT hc hr) (λ T₁ T₂ i c hrelT₁₂ hc hr ih, hpivot_trans (rel.pivot (feasible_of_rel_left obj hrelT₁₂) hc hr) hrelT₁₂ hc hr (hpivot (feasible_of_rel_left obj hrelT₁₂) hc hr) ih) lemma rel.trans {obj : fin m} {T₁ T₂ T₃ : tableau m n} (h₁₂ : rel obj T₁ T₂) : rel obj T₂ T₃ → rel obj T₁ T₃ := rel.rec_on h₁₂ (λ T i c hT hc hr hrelT, rel.trans_pivot hrelT hc hr) (λ T₁ T₂ i c hrelT₁₂ hc hr ih hrelT₂₃, rel.trans_pivot (ih hrelT₂₃) hc hr) instance : is_trans (tableau m n) (rel obj) := ⟨@rel.trans _ _ obj⟩ lemma flat_eq_of_rel {T T' : tableau m n} (h : rel obj T' T) : flat T' = flat T := rel.rec_on' h (λ _ _ _ _ _ hr, flat_pivot (ne_zero_of_mem_pivot_row hr)) (λ _ _ _ _ _ _ _ _, eq.trans) lemma rowg_obj_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.to_partition.rowg obj = T'.to_partition.rowg obj := rel.rec_on' h (λ T i c hfT hc hr, by simp [rowg_swap_of_ne _ (pivot_row_spec hr).1]) (λ _ _ _ _ _ _ _ _, eq.trans) lemma restricted_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.restricted = T'.restricted := rel.rec_on' h (λ _ _ _ _ _ _, rfl) (λ _ _ _ _ _ _ _ _, eq.trans) lemma dead_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.dead = T'.dead := rel.rec_on' h (λ _ _ _ _ _ _, rfl) (λ _ _ _ _ _ _ _ _, eq.trans) lemma dead_eq_of_rel_or_eq {T T' : tableau m n} (h : T = T' ∨ rel obj T T') : T.dead = T'.dead := h.elim (congr_arg _) $ dead_eq_of_rel _ lemma exists_mem_pivot_row_col_of_rel {T T' : tableau m n} (h : rel obj T' T) : ∃ i c, c ∈ pivot_col T obj ∧ i ∈ pivot_row T obj c := rel.rec_on' h (λ _ i c _ hc hr, ⟨i, c, hc, hr⟩) (λ _ _ _ _ _ _ _ _ _, id) lemma exists_mem_pivot_row_of_rel {T T' : tableau m n} (h : rel obj T' T) {c : fin n} (hc : c ∈ pivot_col T obj) : ∃ i, i ∈ pivot_row T obj c := let ⟨i, c', hc', hr⟩ := exists_mem_pivot_row_col_of_rel obj h in ⟨i, by simp * at *⟩ lemma exists_mem_pivot_col_of_fickle {T₁ T₂ : tableau m n} (h : rel obj T₂ T₁) {c : fin n} : fickle T₁ T₂ (T₁.to_partition.colg c) → ∃ T₃, (T₃ = T₁ ∨ rel obj T₃ T₁) ∧ (rel obj T₂ T₃) ∧ T₃.to_partition.colg c = T₁.to_partition.colg c ∧ c ∈ pivot_col T₃ obj := rel.rec_on' h begin assume T i c' hT hc' hr, rw fickle_colg_iff_ne, by_cases hcc : c = c', { subst hcc, exact λ _, ⟨T, or.inl rfl, rel.pivot hT hc' hr, rfl, hc'⟩ }, { simp [colg_swap_of_ne _ hcc] } end (λ T₁ T₂ i c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂, (imp_iff_not_or.1 ih₁₂).elim (λ ih₁₂, (imp_iff_not_or.1 ihp₁).elim (λ ihp₁ hf, (fickle_colg_iff_ne.1 hf (by simp [*, fickle_colg_iff_ne] at *)).elim) (λ ⟨T₃, hT₃⟩ hf, ⟨T₃, hT₃.1.elim (λ h, h.symm ▸ or.inr hrel₁₂) (λ h, or.inr $ h.trans hrel₁₂), hT₃.2.1, hT₃.2.2.1.trans (by simpa [eq_comm, fickle_colg_iff_ne] using ih₁₂), hT₃.2.2.2⟩)) (λ ⟨T₃, hT₃⟩ hf, ⟨T₃, hT₃.1, hrelp₁.trans hT₃.2.1, hT₃.2.2⟩)) lemma exists_mem_pivot_row_of_fickle {T₁ T₂ : tableau m n} (h : rel obj T₂ T₁) (i : fin m) : fickle T₁ T₂ (T₁.to_partition.rowg i) → ∃ (T₃ : tableau m n) c, (T₃ = T₁ ∨ rel obj T₃ T₁) ∧ (rel obj T₂ T₃) ∧ T₃.to_partition.rowg i = T₁.to_partition.rowg i ∧ c ∈ pivot_col T₃ obj ∧ i ∈ pivot_row T₃ obj c := rel.rec_on' h begin assume T i' c hT hc hi', rw fickle_rowg_iff_ne, by_cases hii : i = i', { subst hii, exact λ _, ⟨T, c, or.inl rfl, rel.pivot hT hc hi', rfl, hc, hi'⟩ }, { simp [rowg_swap_of_ne _ hii] } end (λ T₁ T₂ i c hrelp₁ hrel₁₂ hc hrow ihp₁ ih₁₂, (imp_iff_not_or.1 ih₁₂).elim (λ ih₁₂, (imp_iff_not_or.1 ihp₁).elim (λ ihp₁ hf, (fickle_rowg_iff_ne.1 hf (by simp [*, fickle_rowg_iff_ne] at *)).elim) (λ ⟨T₃, c', hT₃⟩ hf, ⟨T₃, c', hT₃.1.elim (λ h, h.symm ▸ or.inr hrel₁₂) (λ h, or.inr $ h.trans hrel₁₂), hT₃.2.1, hT₃.2.2.1.trans (by simpa [eq_comm, fickle_rowg_iff_ne] using ih₁₂), by clear_aux_decl; tauto⟩)) (λ ⟨T₃, c', hT₃⟩ _, ⟨T₃, c', hT₃.1, (rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hrow).trans hT₃.2.1, hT₃.2.2⟩)) lemma eq_or_rel_pivot_of_rel {T₁ T₂ : tableau m n} (h : rel obj T₁ T₂) : ∀ {i j} (hcol : j ∈ pivot_col T₂ obj) (hrow : i ∈ pivot_row T₂ obj j), T₁ = T₂.pivot i j ∨ rel obj T₁ (T₂.pivot i j) := rel.rec_on' h (λ T i c hT hc hr r' c' hc' hr', by simp * at *) (λ T₁ T₂ i c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂ r' c' hc' hr', (ih₁₂ hc' hr').elim (λ ih₁₂, or.inr $ ih₁₂ ▸ rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr) (λ ih₁₂, or.inr $ (rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr).trans ih₁₂)) lemma exists_mem_pivot_col_of_mem_pivot_row {T : tableau m n} (hrelTT : rel obj T T) {i c} (hc : c ∈ pivot_col T obj) (hrow : i ∈ pivot_row T obj c) : ∃ (T' : tableau m n), c ∈ pivot_col T' obj ∧ T'.to_partition.colg c = T.to_partition.rowg i ∧ rel obj T' T ∧ rel obj T T' := have hrelTTp : rel obj T (T.pivot i c), from (eq_or_rel_pivot_of_rel _ hrelTT hc hrow).elim (λ h, h ▸ hrelTT ) id, let ⟨T', hT'⟩ := exists_mem_pivot_col_of_fickle obj hrelTTp $ fickle_colg_iff_ne.2 $ (show (T.pivot i c).to_partition.colg c ≠ T.to_partition.colg c, by simp) in ⟨T', hT'.2.2.2, by simp [hT'.2.2.1], hT'.1.elim (λ h, h.symm ▸ rel.pivot (feasible_of_rel_left _ hrelTT) hc hrow) (λ h, h.trans $ rel.pivot (feasible_of_rel_left _ hrelTT) hc hrow), hT'.2.1⟩ lemma exists_mem_pivot_col_of_fickle_row {T T' : tableau m n} (hrelTT' : rel obj T T') {i : fin m} (hrelT'T : rel obj T' T) (hrow : fickle T T' (T.to_partition.rowg i)) : ∃ (T₃ : tableau m n) c, c ∈ pivot_col T₃ obj ∧ T₃.to_partition.colg c = T.to_partition.rowg i ∧ rel obj T₃ T ∧ rel obj T T₃ := let ⟨T₃, c, hT₃, hrelT₃T, hrow₃, hc, hr⟩ := exists_mem_pivot_row_of_fickle obj hrelT'T _ hrow in let ⟨T₄, hT₄⟩ := exists_mem_pivot_col_of_mem_pivot_row obj (show rel obj T₃ T₃, from hT₃.elim (λ h, h.symm ▸ hrelTT'.trans hrelT'T) (λ h, h.trans $ hrelTT'.trans hrelT₃T)) hc hr in ⟨T₄, c, hT₄.1, hT₄.2.1.trans hrow₃, hT₄.2.2.1.trans $ hT₃.elim (λ h, h.symm ▸ hrelTT'.trans hrelT'T) (λ h, h.trans $ hrelTT'.trans hrelT'T), hrelTT'.trans (hrelT₃T.trans hT₄.2.2.2)⟩ lemma const_obj_le_of_rel {T₁ T₂ : tableau m n} (h : rel obj T₁ T₂) : T₂.const obj 0 ≤ T₁.const obj 0 := rel.rec_on' h (λ T i c hT hc hr, have hr' : _ := pivot_row_spec hr, simplex_const_obj_le hT (by tauto) (by tauto)) (λ _ _ _ _ _ _ _ _ h₁ h₂, le_trans h₂ h₁) lemma const_obj_eq_of_rel_of_rel {T₁ T₂ : tableau m n} (h₁₂ : rel obj T₁ T₂) (h₂₁ : rel obj T₂ T₁) : T₁.const obj 0 = T₂.const obj 0 := le_antisymm (const_obj_le_of_rel _ h₂₁) (const_obj_le_of_rel _ h₁₂) lemma const_eq_const_of_const_obj_eq {T₁ T₂ : tableau m n} (h₁₂ : rel obj T₁ T₂) : ∀ (hobj : T₁.const obj 0 = T₂.const obj 0) (i : fin m), T₁.const i 0 = T₂.const i 0 := rel.rec_on' h₁₂ (λ T i c hfT hc hrow hobj i', have hr0 : T.const i 0 = 0, from const_eq_zero_of_const_obj_eq hfT (ne_zero_of_mem_pivot_col hc) (ne_zero_of_mem_pivot_row hrow) (pivot_row_spec hrow).1 hobj, if hii : i' = i then by simp [hii, hr0] else by simp [const_pivot_of_ne _ hii, hr0]) (λ T₁ T₂ i c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂ hobj i', have hobjp : (pivot T₁ i c).const obj 0 = T₁.const obj 0, from le_antisymm (hobj.symm ▸ const_obj_le_of_rel _ hrel₁₂) (const_obj_le_of_rel _ hrelp₁), by rw [ihp₁ hobjp, ih₁₂ (hobjp.symm.trans hobj)]) lemma const_eq_zero_of_fickle_of_rel_self {T T' : tableau m n} (hrelTT' : rel obj T T') (hrelT'T : rel obj T' T) (i : fin m) (hrow : fickle T T' (T.to_partition.rowg i)) : T.const i 0 = 0 := let ⟨T₃, c, hT₃₁, hT'₃, hrow₃, hc, hi⟩ := exists_mem_pivot_row_of_fickle obj hrelT'T _ hrow in have T₃.const i 0 = 0, from const_eq_zero_of_const_obj_eq (feasible_of_rel_right _ hT'₃) (ne_zero_of_mem_pivot_col hc) (ne_zero_of_mem_pivot_row hi) (pivot_row_spec hi).1 (const_obj_eq_of_rel_of_rel _ (rel.pivot (feasible_of_rel_right _ hT'₃) hc hi) ((eq_or_rel_pivot_of_rel _ hT'₃ hc hi).elim (λ h, h ▸ hT₃₁.elim (λ h, h.symm ▸ hrelTT') (λ h, h.trans hrelTT')) (λ hrelT'p, hT₃₁.elim (λ h, h.symm ▸ hrelTT'.trans (h ▸ hrelT'p)) (λ h, h.trans $ hrelTT'.trans hrelT'p)))), have hobj : T₃.const obj 0 = T.const obj 0, from hT₃₁.elim (λ h, h ▸ rfl) (λ h, const_obj_eq_of_rel_of_rel _ h (hrelTT'.trans hT'₃)), hT₃₁.elim (λ h, h ▸ this) (λ h, const_eq_const_of_const_obj_eq obj h hobj i ▸ this) lemma colg_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T) {c} (hc : c ∈ pivot_col T obj) : T.to_partition.colg c ∈ T.restricted := let ⟨i, hrow⟩ := exists_mem_pivot_row_of_rel obj hrelTT hc in let ⟨T', c', hT', hrelTT', hrowcol, _, hi'⟩ := exists_mem_pivot_row_of_fickle obj ((eq_or_rel_pivot_of_rel _ hrelTT hc hrow).elim (λ h, show rel obj T (T.pivot i c), from h ▸ hrelTT) id) _ (fickle_rowg_iff_ne.2 $ show (T.pivot i c).to_partition.rowg i ≠ T.to_partition.rowg i, by simp) in (restricted_eq_of_rel _ hrelTT').symm ▸ by convert (pivot_row_spec hi').2.1; simp [hrowcol] lemma eq_zero_of_not_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T) {j} (hjres : T.to_partition.colg j ∉ T.restricted) (hdead : j ∉ T.dead) : T.to_matrix obj j = 0 := let ⟨r, c, hc, hr⟩ := exists_mem_pivot_row_col_of_rel obj hrelTT in have hcres : T.to_partition.colg c ∈ T.restricted, from colg_mem_restricted_of_rel_self obj hrelTT hc, by_contradiction $ λ h0, begin simp [pivot_col] at hc, cases h : fin.find (λ c, T.to_matrix obj c ≠ 0 ∧ colg (T.to_partition) c ∉ T.restricted ∧ c ∉ T.dead), { simp [*, fin.find_eq_none_iff] at * }, { rw h at hc, clear_aux_decl, have := (fin.find_eq_some_iff.1 h).1, simp * at * } end lemma rel.irrefl {obj : fin m} : ∀ (T : tableau m n), ¬ rel obj T T := λ T1 hrelT1, let ⟨iT1 , cT1, hrT1, hcT1⟩ := exists_mem_pivot_row_col_of_rel obj hrelT1 in let ⟨t, ht⟩ := finset.max_of_mem (show T1.to_partition.colg cT1 ∈ univ.filter (λ v, ∃ (T' : tableau m n) (c : fin n), rel obj T' T' ∧ c ∈ pivot_col T' obj ∧ T'.to_partition.colg c = v), by simp only [true_and, mem_filter, mem_univ, exists_and_distrib_left]; exact ⟨T1, hrelT1, cT1, hrT1, rfl⟩) in let ⟨_, T', c', hrelTT'', hcT', hct⟩ := finset.mem_filter.1 (finset.mem_of_max ht) in have htmax : ∀ (s : fin (m + n)) (T : tableau m n), rel obj T T → ∀ (j : fin n), pivot_col T obj = some j → T.to_partition.colg j = s → s ≤ t, by simpa using λ s (h : s ∈ _), finset.le_max_of_mem h ht, let ⟨i, hiT'⟩ := exists_mem_pivot_row_of_rel obj hrelTT'' hcT' in have hrelTT''p : rel obj T' (T'.pivot i c'), from (eq_or_rel_pivot_of_rel obj hrelTT'' hcT' hiT').elim (λ h, h ▸ hrelTT'') id, let ⟨T, c, hTT', hrelT'T, hT'Tr, hc, hr⟩ := exists_mem_pivot_row_of_fickle obj hrelTT''p i (by rw fickle_symm; simp [fickle_colg_iff_ne]) in have hfT' : feasible T', from feasible_of_rel_left _ hrelTT'', have hfT : feasible T, from feasible_of_rel_right _ hrelT'T, have hrelT'pT' : rel obj (T'.pivot i c') T', from rel.pivot hfT' hcT' hiT', have hrelTT' : rel obj T T', from hTT'.elim (λ h, h.symm ▸ hrelT'pT') (λ h, h.trans hrelT'pT'), have hrelTT : rel obj T T, from hrelTT'.trans hrelT'T, have hc't : T.to_partition.colg c ≤ t, from htmax _ T hrelTT _ hc rfl, have hoT'T : T'.const obj 0 = T.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelT'T hrelTT', have hfickle : ∀ i, fickle T T' (T.to_partition.rowg i) → T.const i 0 = 0, from const_eq_zero_of_fickle_of_rel_self obj hrelTT' hrelT'T, have hobj : T.const obj 0 = T'.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelTT' hrelT'T, have hflat : T.flat = T'.flat, from flat_eq_of_rel obj hrelTT', have hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj, from rowg_obj_eq_of_rel _ hrelTT', have hs : T.to_partition.rowg i = T'.to_partition.colg c', by simpa using hT'Tr, have hc'res : T'.to_partition.colg c' ∈ T'.restricted, from hs ▸ restricted_eq_of_rel _ hrelTT' ▸ (pivot_row_spec hr).2.1, have hc'obj0 : 0 < T'.to_matrix obj c' ∧ c' ∉ T'.dead, by simpa [hc'res] using pivot_col_spec hcT', have hcres : T.to_partition.colg c ∈ T.restricted, from colg_mem_restricted_of_rel_self obj hrelTT hc, have hcobj0 : 0 < to_matrix T obj c ∧ c ∉ T.dead, by simpa [hcres] using pivot_col_spec hc, have hrc0 : T.to_matrix i c < 0, from inv_neg'.1 $ neg_of_mul_neg_left (pivot_row_spec hr).2.2.1 (le_of_lt hcobj0.1), have nonpos_of_colg_ne : ∀ j, (fickle T' T (T'.to_partition.colg j)) → j ≠ c' → T'.to_matrix obj j ≤ 0, from λ j hj hjc', let ⟨T₃, hT₃⟩ := exists_mem_pivot_col_of_fickle obj hrelTT' hj in nonpos_of_lt_pivot_col hcT' hc'res (dead_eq_of_rel_or_eq obj hT₃.1 ▸ (pivot_col_spec hT₃.2.2.2).2) (lt_of_le_of_ne (hct.symm ▸ hT₃.2.2.1 ▸ htmax _ T₃ (hT₃.1.elim (λ h, h.symm ▸ hrelTT'') (λ h, h.trans (hrelT'T.trans hT₃.2.1))) _ hT₃.2.2.2 rfl) (by rwa [ne.def, T'.to_partition.injective_colg.eq_iff])), have nonpos_of_colg_eq : ∀ j, j ≠ c' → T'.to_partition.colg j = T.to_partition.colg c → T'.to_matrix obj j ≤ 0, from λ j hjc' hj, if hjc : j = c then by clear_aux_decl; subst hjc; exact nonpos_of_lt_pivot_col hcT' hc'res (by rw [dead_eq_of_rel obj hrelT'T]; tauto) (lt_of_le_of_ne (hj.symm ▸ hct.symm ▸ hc't) (by simpa)) else nonpos_of_colg_ne _ (fickle_colg_iff_ne.2 $ by simpa [hj, eq_comm] using hjc) hjc', have unique_row : ∀ i' ≠ i, T.const i' 0 = 0 → fickle T T' (T.to_partition.rowg i') → 0 ≤ T.to_matrix i' c, from λ i' hii hi0 hrow, let ⟨T₃, c₃, hc₃, hrow₃, hrelT₃T, hrelTT₃⟩ := exists_mem_pivot_col_of_fickle_row _ hrelTT' hrelT'T hrow in have hrelT₃T₃ : rel obj T₃ T₃, from hrelT₃T.trans hrelTT₃, nonneg_of_lt_pivot_row (by exact hcobj0.1) (by rw [← hrow₃, ← restricted_eq_of_rel _ hrelT₃T]; exact colg_mem_restricted_of_rel_self _ hrelT₃T₃ hc₃) hc hr hi0 (lt_of_le_of_ne (by rw [hs, hct, ← hrow₃]; exact htmax _ _ hrelT₃T₃ _ hc₃ rfl) (by simpa [fickle_rowg_iff_ne] using hrow)), not_unique_row_and_unique_col obj hcobj0.1 hc'obj0.1 hrc0 hflat hs hrobj hfickle hobj nonpos_of_colg_eq nonpos_of_colg_ne unique_row noncomputable instance fintype_rel (T : tableau m n) : fintype {T' | rel obj T' T} := fintype.of_injective (λ T', T'.val.to_partition) (λ T₁ T₂ h, subtype.eq $ tableau.ext (by rw [flat_eq_of_rel _ T₁.2, flat_eq_of_rel _ T₂.2]) h (by rw [dead_eq_of_rel _ T₁.2, dead_eq_of_rel _ T₂.2]) (by rw [restricted_eq_of_rel _ T₁.2, restricted_eq_of_rel _ T₂.2])) lemma rel_wf (m n : ℕ) (obj : fin m): well_founded (@rel m n obj) := subrelation.wf (show subrelation (@rel m n obj) (measure (λ T, fintype.card {T' | rel obj T' T})), from assume T₁ T₂ h, set.card_lt_card (set.ssubset_iff_subset_not_subset.2 ⟨λ T' hT', hT'.trans h, not_forall_of_exists_not ⟨T₁, λ h', rel.irrefl _ (h' h)⟩⟩)) (measure_wf (λ T, fintype.card {T' | rel obj T' T})) end blands_rule inductive termination (n : ℕ) : Type | while {} : termination | unbounded (c : fin n) : termination | optimal {} : termination namespace termination lemma injective_unbounded : function.injective (@unbounded n) := λ _ _ h, by injection h @[simp] lemma unbounded_inj {c c' : fin n} : unbounded c = unbounded c' ↔ c = c' := injective_unbounded.eq_iff end termination open termination instance {n : ℕ} : has_repr $ termination n := ⟨λ t, termination.cases_on t "while" (λ c, "unbounded " ++ repr c) "optimal"⟩ open termination /-- The simplex algorithm -/ def simplex (w : tableau m n → bool) (obj : fin m) : Π (T : tableau m n) (hT : feasible T), tableau m n × termination n | T := λ hT, cond (w T) (match pivot_col T obj, @feasible_of_mem_pivot_row_and_col _ _ _ obj hT, @rel.pivot m n obj _ hT with | none, hc, hrel := (T, optimal) | some j, hc, hrel := match pivot_row T obj j, @hc _ rfl, (λ i, @hrel i j rfl) with | none, hrow, hrel := (T, unbounded j) | some i, hrow, hrel := have wf : rel obj (pivot T i j) T, from hrel _ rfl, simplex (T.pivot i j) (hrow rfl) end end) (T, while) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, rel_wf m n obj⟩], dec_tac := tactic.assumption} lemma simplex_pivot {w : tableau m n → bool} {T : tableau m n} (hT : feasible T) (hw : w T = tt) {obj : fin m} {i : fin m} {c : fin n} (hc : c ∈ pivot_col T obj) (hr : i ∈ pivot_row T obj c) : (T.pivot i c).simplex w obj (feasible_of_mem_pivot_row_and_col hT hc hr) = T.simplex w obj hT := by conv_rhs { rw simplex }; simp [hw, show _ = _, from hr, show _ = _, from hc, simplex._match_1, simplex._match_2] lemma simplex_spec_aux (w : tableau m n → bool) (obj : fin m) : Π (T : tableau m n) (hT : feasible T), ((T.simplex w obj hT).2 = while ∧ w (T.simplex w obj hT).1 = ff) ∨ ((T.simplex w obj hT).2 = optimal ∧ w (T.simplex w obj hT).1 = tt ∧ pivot_col (T.simplex w obj hT).1 obj = none) ∨ ∃ c, ((T.simplex w obj hT).2 = unbounded c ∧ w (T.simplex w obj hT).1 = tt ∧ c ∈ pivot_col (T.simplex w obj hT).1 obj ∧ pivot_row (T.simplex w obj hT).1 obj c = none) | T := λ hT, begin cases hw : w T, { rw simplex, simp [hw] }, { cases hc : pivot_col T obj with c, { rw simplex, simp [hc, hw, simplex._match_1] }, { cases hrow : pivot_row T obj c with i, { rw simplex, simp [hrow, hc, hw, simplex._match_1, simplex._match_2] }, { rw [← simplex_pivot hT hw hc hrow], exact have wf : rel obj (T.pivot i c) T, from rel.pivot hT hc hrow, simplex_spec_aux _ _ } } } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, rel_wf m n obj⟩], dec_tac := tactic.assumption} lemma simplex_while_eq_ff {w : tableau m n → bool} {T : tableau m n} {hT : feasible T} {obj : fin m} (hw : w T = ff) : T.simplex w obj hT = (T, while) := by rw [simplex, hw]; refl lemma simplex_pivot_col_eq_none {w : tableau m n → bool} {T : tableau m n} {hT : feasible T} (hw : w T = tt) {obj : fin m} (hc : pivot_col T obj = none) : T.simplex w obj hT = (T, optimal) := by rw simplex; simp [hc, hw, simplex._match_1] lemma simplex_pivot_row_eq_none {w : tableau m n → bool} {T : tableau m n} {hT : feasible T} {obj : fin m} (hw : w T = tt) {c} (hc : c ∈ pivot_col T obj) (hr : pivot_row T obj c = none) : T.simplex w obj hT = (T, unbounded c) := by rw simplex; simp [hw, show _ = _, from hc, hr, simplex._match_1, simplex._match_2] lemma simplex_induction (P : tableau m n → Prop) (w : tableau m n → bool) (obj : fin m): Π {T : tableau m n} (hT : feasible T) (h0 : P T) (hpivot : ∀ {T' i c}, w T' = tt → c ∈ pivot_col T' obj → i ∈ pivot_row T' obj c → feasible T' → P T' → P (T'.pivot i c)), P (T.simplex w obj hT).1 | T := λ hT h0 hpivot, begin cases hw : w T, { rwa [simplex_while_eq_ff hw] }, { cases hc : pivot_col T obj with c, { rwa [simplex_pivot_col_eq_none hw hc] }, { cases hrow : pivot_row T obj c with i, { rwa simplex_pivot_row_eq_none hw hc hrow }, { rw [← simplex_pivot _ hw hc hrow], exact have wf : rel obj (pivot T i c) T, from rel.pivot hT hc hrow, simplex_induction (feasible_of_mem_pivot_row_and_col hT hc hrow) (hpivot hw hc hrow hT h0) @hpivot } } } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, rel_wf m n obj⟩], dec_tac := `[tauto]} @[simp] lemma feasible_simplex {w : tableau m n → bool} {T : tableau m n} {hT : feasible T} {obj : fin m} : feasible (T.simplex w obj hT).1 := simplex_induction feasible _ _ hT hT (λ _ _ _ _ hc hr _ hT', feasible_of_mem_pivot_row_and_col hT' hc hr) @[simp] lemma simplex_simplex {w : tableau m n → bool} {T : tableau m n} {hT : feasible T} {obj : fin m} : (T.simplex w obj hT).1.simplex w obj feasible_simplex = T.simplex w obj hT := simplex_induction (λ T', ∀ (hT' : feasible T'), T'.simplex w obj hT' = T.simplex w obj hT) w _ _ (λ _, rfl) (λ T' i c hw hc hr hT' ih hpivot, by rw [simplex_pivot hT' hw hc hr, ih]) _ /-- `simplex` does not move the row variable it is trying to maximise. -/ @[simp] lemma rowg_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool) (obj : fin m) : (T.simplex w obj hT).1.to_partition.rowg obj = T.to_partition.rowg obj := simplex_induction (λ T', T'.to_partition.rowg obj = T.to_partition.rowg obj) _ _ _ rfl (λ T' i c hw hc hr, by simp [rowg_swap_of_ne _ (pivot_row_spec hr).1]) @[simp] lemma flat_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool) (obj : fin m) : (T.simplex w obj hT).1.flat = T.flat := simplex_induction (λ T', T'.flat = T.flat) w obj _ rfl (λ T' i c hw hc hr hT' ih, have T'.to_matrix i c ≠ 0, from λ h, by simpa [h, lt_irrefl] using pivot_row_spec hr, by rw [flat_pivot this, ih]) @[simp] lemma restricted_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool) (obj : fin m) : (T.simplex w obj hT).1.restricted = T.restricted := simplex_induction (λ T', T'.restricted = T.restricted) _ _ _ rfl (by simp { contextual := tt }) @[simp] lemma dead_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool) (obj : fin m) : (T.simplex w obj hT).1.dead = T.dead := simplex_induction (λ T', T'.dead = T.dead) _ _ _ rfl (by simp { contextual := tt }) @[simp] lemma res_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool) (obj : fin m) : (T.simplex w obj hT).1.res_set = T.res_set := simplex_induction (λ T', T'.res_set = T.res_set) w obj _ rfl (λ T' i c hw hc hr, by simp [res_set_pivot (ne_zero_of_mem_pivot_row hr)] {contextual := tt}) @[simp] lemma dead_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool) (obj : fin m) : (T.simplex w obj hT).1.dead_set = T.dead_set := simplex_induction (λ T', T'.dead_set = T.dead_set) w obj _ rfl (λ T' i c hw hc hr, by simp [dead_set_pivot (ne_zero_of_mem_pivot_row hr) (pivot_col_spec hc).2] {contextual := tt}) @[simp] lemma sol_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool) (obj : fin m) : (T.simplex w obj hT).1.sol_set = T.sol_set := by simp [sol_set_eq_res_set_inter_dead_set] @[simp] lemma of_col_simplex_zero_mem_sol_set {w : tableau m n → bool} {T : tableau m n} {hT : feasible T} {obj : fin m} : (T.simplex w obj hT).1.of_col 0 ∈ sol_set T := by rw [← sol_set_simplex, of_col_zero_mem_sol_set_iff]; exact feasible_simplex @[simp] lemma of_col_simplex_rowg {w : tableau m n → bool} {T : tableau m n} {hT : feasible T} {obj : fin m} (x : cvec n) : (T.simplex w obj hT).1.of_col x (T.to_partition.rowg obj) = ((T.simplex w obj hT).1.to_matrix ⬝ x + (T.simplex w obj hT).1.const) obj := by rw [← of_col_rowg (T.simplex w obj hT).1 x obj, rowg_simplex] @[simp] lemma is_unbounded_above_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} {v : fin (m + n)} : is_unbounded_above (T.simplex w obj hT).1 v ↔ is_unbounded_above T v := by simp [is_unbounded_above] @[simp] lemma is_optimal_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} {x : cvec (m + n)} {v : fin (m + n)} : is_optimal (T.simplex w obj hT).1 x v ↔ is_optimal T x v := by simp [is_optimal] lemma termination_eq_while_iff {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = while ↔ w (T.simplex w obj hT).1 = ff := by have := simplex_spec_aux w obj T hT; finish lemma termination_eq_optimal_iff_pivot_col_eq_none {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal ↔ w (T.simplex w obj hT).1 = tt ∧ pivot_col (T.simplex w obj hT).1 obj = none := by rcases simplex_spec_aux w obj T hT with _ | ⟨_, _, _⟩ | ⟨⟨_, _⟩, _, _, _, _⟩; simp * at * lemma termination_eq_unbounded_iff_pivot_row_eq_none {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} {c : fin n} : (T.simplex w obj hT).2 = unbounded c ↔ w (T.simplex w obj hT).1 = tt ∧ c ∈ pivot_col (T.simplex w obj hT).1 obj ∧ pivot_row (T.simplex w obj hT).1 obj c = none := by split; intros; rcases simplex_spec_aux w obj T hT with _ | ⟨_, _, _⟩ | ⟨⟨⟨_, _⟩, _⟩, _, _, _, _⟩; simp * at * lemma unbounded_of_termination_eq_unbounded {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} {c : fin n} : (T.simplex w obj hT).2 = unbounded c → w (T.simplex w obj hT).1 = tt ∧ is_unbounded_above T (T.to_partition.rowg obj) := begin rw termination_eq_unbounded_iff_pivot_row_eq_none, rintros ⟨_, hc⟩, simpa * using pivot_row_eq_none feasible_simplex hc.2 hc.1 end lemma termination_eq_optimal_iff {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal ↔ w (T.simplex w obj hT).1 = tt ∧ is_optimal T ((T.simplex w obj hT).1.of_col 0) (T.to_partition.rowg obj) := begin rw [termination_eq_optimal_iff_pivot_col_eq_none], split, { rintros ⟨_, hc⟩, simpa * using pivot_col_eq_none feasible_simplex hc }, { cases ht : (T.simplex w obj hT).2, { simp [*, termination_eq_while_iff] at * }, { cases unbounded_of_termination_eq_unbounded ht, simp [*, not_optimal_of_unbounded_above right] }, { simp [*, termination_eq_optimal_iff_pivot_col_eq_none] at * } } end lemma termination_eq_unbounded_iff {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} {c : fin n}: (T.simplex w obj hT).2 = unbounded c ↔ w (T.simplex w obj hT).1 = tt ∧ is_unbounded_above T (T.to_partition.rowg obj) ∧ c ∈ pivot_col (T.simplex w obj hT).1 obj := ⟨λ hc, and.assoc.1 $ ⟨unbounded_of_termination_eq_unbounded hc, (termination_eq_unbounded_iff_pivot_row_eq_none.1 hc).2.1⟩, begin have := @not_optimal_of_unbounded_above m n (T.simplex w obj hT).1 (T.to_partition.rowg obj) ((T.simplex w obj hT).1.of_col 0), cases ht : (T.simplex w obj hT).2; simp [termination_eq_optimal_iff, termination_eq_while_iff, termination_eq_unbounded_iff_pivot_row_eq_none, *] at * end⟩ end tableau
c989ed5c5031fab4e6098ff01c8d01cda2238bc8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/computability/language_auto.lean
39d0c3dcd87bbb1439229f53b3d545d8f0ceabb0
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,476
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.finset.basic import Mathlib.PostPort universes u_1 u v namespace Mathlib /-! # Languages This file contains the definition and operations on formal languages over an alphabet. Note strings are implemented as lists over the alphabet. The operations in this file define a [Kleene algebra](https://en.wikipedia.org/wiki/Kleene_algebra) over the languages. -/ /-- A language is a set of strings over an alphabet. -/ def language (α : Type u_1) := set (List α) namespace language protected instance has_zero {α : Type u} : HasZero (language α) := { zero := ∅ } protected instance has_one {α : Type u} : HasOne (language α) := { one := singleton [] } protected instance inhabited {α : Type u} : Inhabited (language α) := { default := 0 } protected instance has_add {α : Type u} : Add (language α) := { add := set.union } protected instance has_mul {α : Type u} : Mul (language α) := { mul := fun (l m : language α) => (fun (p : List α × List α) => prod.fst p ++ prod.snd p) '' set.prod l m } theorem zero_def {α : Type u} : 0 = ∅ := rfl theorem one_def {α : Type u} : 1 = singleton [] := rfl theorem add_def {α : Type u} (l : language α) (m : language α) : l + m = l ∪ m := rfl theorem mul_def {α : Type u} (l : language α) (m : language α) : l * m = (fun (p : List α × List α) => prod.fst p ++ prod.snd p) '' set.prod l m := rfl /-- The star of a language `L` is the set of all strings which can be written by concatenating strings from `L`. -/ def star {α : Type u} (l : language α) : language α := set_of fun (x : List α) => ∃ (S : List (List α)), x = list.join S ∧ ∀ (y : List α), y ∈ S → y ∈ l theorem star_def {α : Type u} (l : language α) : star l = set_of fun (x : List α) => ∃ (S : List (List α)), x = list.join S ∧ ∀ (y : List α), y ∈ S → y ∈ l := rfl @[simp] theorem mem_one {α : Type u} (x : List α) : x ∈ 1 ↔ x = [] := iff.refl (x ∈ 1) @[simp] theorem mem_add {α : Type u} (l : language α) (m : language α) (x : List α) : x ∈ l + m ↔ x ∈ l ∨ x ∈ m := sorry theorem mem_mul {α : Type u} (l : language α) (m : language α) (x : List α) : x ∈ l * m ↔ ∃ (a : List α), ∃ (b : List α), a ∈ l ∧ b ∈ m ∧ a ++ b = x := sorry theorem mem_star {α : Type u} (l : language α) (x : List α) : x ∈ star l ↔ ∃ (S : List (List α)), x = list.join S ∧ ∀ (y : List α), y ∈ S → y ∈ l := iff.refl (x ∈ star l) protected instance semiring {α : Type u} : semiring (language α) := semiring.mk Add.add sorry 0 sorry sorry sorry Mul.mul mul_assoc_lang 1 one_mul_lang mul_one_lang sorry sorry left_distrib_lang right_distrib_lang @[simp] theorem add_self {α : Type u} (l : language α) : l + l = l := sup_idem theorem star_def_nonempty {α : Type u} (l : language α) : star l = set_of fun (x : List α) => ∃ (S : List (List α)), x = list.join S ∧ ∀ (y : List α), y ∈ S → y ∈ l ∧ y ≠ [] := sorry theorem le_iff {α : Type u} (l : language α) (m : language α) : l ≤ m ↔ l + m = m := iff.symm sup_eq_right theorem le_mul_congr {α : Type u} {l₁ : language α} {l₂ : language α} {m₁ : language α} {m₂ : language α} : l₁ ≤ m₁ → l₂ ≤ m₂ → l₁ * l₂ ≤ m₁ * m₂ := sorry theorem le_add_congr {α : Type u} {l₁ : language α} {l₂ : language α} {m₁ : language α} {m₂ : language α} : l₁ ≤ m₁ → l₂ ≤ m₂ → l₁ + l₂ ≤ m₁ + m₂ := sup_le_sup theorem supr_mul {α : Type u} {ι : Sort v} (l : ι → language α) (m : language α) : (supr fun (i : ι) => l i) * m = supr fun (i : ι) => l i * m := sorry theorem mul_supr {α : Type u} {ι : Sort v} (l : ι → language α) (m : language α) : (m * supr fun (i : ι) => l i) = supr fun (i : ι) => m * l i := sorry theorem supr_add {α : Type u} {ι : Sort v} [Nonempty ι] (l : ι → language α) (m : language α) : (supr fun (i : ι) => l i) + m = supr fun (i : ι) => l i + m := supr_sup theorem add_supr {α : Type u} {ι : Sort v} [Nonempty ι] (l : ι → language α) (m : language α) : (m + supr fun (i : ι) => l i) = supr fun (i : ι) => m + l i := sup_supr theorem star_eq_supr_pow {α : Type u} (l : language α) : star l = supr fun (i : ℕ) => l ^ i := sorry theorem mul_self_star_comm {α : Type u} (l : language α) : star l * l = l * star l := sorry @[simp] theorem one_add_self_mul_star_eq_star {α : Type u} (l : language α) : 1 + l * star l = star l := sorry @[simp] theorem one_add_star_mul_self_eq_star {α : Type u} (l : language α) : 1 + star l * l = star l := eq.mpr (id (Eq._oldrec (Eq.refl (1 + star l * l = star l)) (mul_self_star_comm l))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 + l * star l = star l)) (one_add_self_mul_star_eq_star l))) (Eq.refl (star l))) theorem star_mul_le_right_of_mul_le_right {α : Type u} (l : language α) (m : language α) : l * m ≤ m → star l * m ≤ m := sorry theorem star_mul_le_left_of_mul_le_left {α : Type u} (l : language α) (m : language α) : m * l ≤ m → m * star l ≤ m := sorry end Mathlib
02f5d2acc567a886ca5862429dd53337bd15b8d0
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/real/basic.lean
c2789a1d5b5eddc44ea52059b195976b5c21a93c
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
41,894
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). The construction of the reals is arranged in four files. - basic.lean proves properties about regular sequences of rationals in the namespace rat_seq, defines ℝ to be the quotient type of regular sequences mod equivalence, and shows ℝ is a ring in namespace real. No classical axioms are used. - order.lean defines an order on regular sequences and lifts the order to ℝ. In the namespace real, ℝ is shown to be an ordered ring. No classical axioms are used. - division.lean defines the inverse of a regular sequence and lifts this to ℝ. If a sequence is equivalent to the 0 sequence, its inverse is the zero sequence. In the namespace real, ℝ is shown to be an ordered field. This construction is classical. - complete.lean -/ import data.nat data.rat.order data.pnat open nat eq pnat open - [coercion] rat local postfix `⁻¹` := pnat.inv -- small helper lemmas private theorem s_mul_assoc_lemma_3 (a b n : ℕ+) (p : ℚ) : p * ((a * n)⁻¹ + (b * n)⁻¹) = p * (a⁻¹ + b⁻¹) * n⁻¹ := by rewrite [rat.mul_assoc, right_distrib, *pnat.inv_mul_eq_mul_inv] private theorem s_mul_assoc_lemma_4 {n : ℕ+} {ε q : ℚ} (Hε : ε > 0) (Hq : q > 0) (H : n ≥ pceil (q / ε)) : q * n⁻¹ ≤ ε := begin note H2 := pceil_helper H (div_pos_of_pos_of_pos Hq Hε), note H3 := mul_le_of_le_div (div_pos_of_pos_of_pos Hq Hε) H2, rewrite -(one_mul ε), apply mul_le_mul_of_mul_div_le, repeat assumption end private theorem find_thirds (a b : ℚ) (H : b > 0) : ∃ n : ℕ+, a + n⁻¹ + n⁻¹ + n⁻¹ < a + b := let n := pceil (of_nat 4 / b) in have of_nat 3 * n⁻¹ < b, from calc of_nat 3 * n⁻¹ < of_nat 4 * n⁻¹ : mul_lt_mul_of_pos_right dec_trivial !pnat.inv_pos ... ≤ of_nat 4 * (b / of_nat 4) : mul_le_mul_of_nonneg_left (!inv_pceil_div dec_trivial H) !of_nat_nonneg ... = b / of_nat 4 * of_nat 4 : mul.comm ... = b : !div_mul_cancel dec_trivial, exists.intro n (calc a + n⁻¹ + n⁻¹ + n⁻¹ = a + (1 + 1 + 1) * n⁻¹ : by rewrite [+right_distrib, +rat.one_mul, -+add.assoc] ... = a + of_nat 3 * n⁻¹ : {show 1+1+1=of_nat 3, from dec_trivial} ... < a + b : rat.add_lt_add_left this a) private theorem squeeze {a b : ℚ} (H : ∀ j : ℕ+, a ≤ b + j⁻¹ + j⁻¹ + j⁻¹) : a ≤ b := begin apply le_of_not_gt, intro Hb, cases exists_add_lt_and_pos_of_lt Hb with [c, Hc], cases find_thirds b c (and.right Hc) with [j, Hbj], have Ha : a > b + j⁻¹ + j⁻¹ + j⁻¹, from lt.trans Hbj (and.left Hc), apply (not_le_of_gt Ha) !H end private theorem rewrite_helper (a b c d : ℚ) : a * b - c * d = a * (b - d) + (a - c) * d := by rewrite [mul_sub_left_distrib, mul_sub_right_distrib, add_sub, sub_add_cancel] private theorem rewrite_helper3 (a b c d e f g: ℚ) : a * (b + c) - (d * e + f * g) = (a * b - d * e) + (a * c - f * g) := by rewrite [left_distrib, add_sub_comm] private theorem rewrite_helper4 (a b c d : ℚ) : a * b - c * d = (a * b - a * d) + (a * d - c * d) := by rewrite[add_sub, sub_add_cancel] private theorem rewrite_helper5 (a b x y : ℚ) : a - b = (a - x) + (x - y) + (y - b) := by rewrite[*add_sub, *sub_add_cancel] private theorem rewrite_helper7 (a b c d x : ℚ) : a * b * c - d = (b * c) * (a - x) + (x * b * c - d) := begin have ∀ (a b c : ℚ), a * b * c = b * c * a, begin intros a b c, rewrite (mul.right_comm b c a), rewrite (mul.comm b a) end, rewrite [mul_sub_left_distrib, add_sub], calc a * b * c - d = a * b * c - x * b * c + x * b * c - d : sub_add_cancel ... = b * c * a - b * c * x + x * b * c - d : begin rewrite [this a b c, this x b c] end end private theorem ineq_helper (a b : ℚ) (k m n : ℕ+) (H : a ≤ (k * 2 * m)⁻¹ + (k * 2 * n)⁻¹) (H2 : b ≤ (k * 2 * m)⁻¹ + (k * 2 * n)⁻¹) : (rat_of_pnat k) * a + b * (rat_of_pnat k) ≤ m⁻¹ + n⁻¹ := have H3 : (k * 2 * m)⁻¹ + (k * 2 * n)⁻¹ = (2 * k)⁻¹ * (m⁻¹ + n⁻¹), begin rewrite [left_distrib, *pnat.inv_mul_eq_mul_inv], rewrite (mul.comm k⁻¹) end, have H' : a ≤ (2 * k)⁻¹ * (m⁻¹ + n⁻¹), begin rewrite H3 at H, exact H end, have H2' : b ≤ (2 * k)⁻¹ * (m⁻¹ + n⁻¹), begin rewrite H3 at H2, exact H2 end, have a + b ≤ k⁻¹ * (m⁻¹ + n⁻¹), from calc a + b ≤ (2 * k)⁻¹ * (m⁻¹ + n⁻¹) + (2 * k)⁻¹ * (m⁻¹ + n⁻¹) : add_le_add H' H2' ... = ((2 * k)⁻¹ + (2 * k)⁻¹) * (m⁻¹ + n⁻¹) : by rewrite right_distrib ... = k⁻¹ * (m⁻¹ + n⁻¹) : by rewrite (pnat.add_halves k), calc (rat_of_pnat k) * a + b * (rat_of_pnat k) = (rat_of_pnat k) * a + (rat_of_pnat k) * b : by rewrite (mul.comm b) ... = (rat_of_pnat k) * (a + b) : left_distrib ... ≤ (rat_of_pnat k) * (k⁻¹ * (m⁻¹ + n⁻¹)) : iff.mp (!le_iff_mul_le_mul_left !rat_of_pnat_is_pos) this ... = m⁻¹ + n⁻¹ : by rewrite[-mul.assoc, pnat.inv_cancel_left, one_mul] private theorem factor_lemma (a b c d e : ℚ) : abs (a + b + c - (d + (b + e))) = abs ((a - d) + (c - e)) := !congr_arg (calc a + b + c - (d + (b + e)) = a + b + c - (d + b + e) : rat.add_assoc ... = a + b - (d + b) + (c - e) : add_sub_comm ... = a + b - b - d + (c - e) : sub_add_eq_sub_sub_swap ... = a - d + (c - e) : add_sub_cancel) private theorem factor_lemma_2 (a b c d : ℚ) : (a + b) + (c + d) = (a + c) + (d + b) := begin note H := (binary.comm4 add.comm add.assoc a b c d), rewrite [add.comm b d at H], exact H end -------------------------------------- -- define cauchy sequences and equivalence. show equivalence actually is one namespace rat_seq notation `seq` := ℕ+ → ℚ definition regular (s : seq) := ∀ m n : ℕ+, abs (s m - s n) ≤ m⁻¹ + n⁻¹ definition equiv (s t : seq) := ∀ n : ℕ+, abs (s n - t n) ≤ n⁻¹ + n⁻¹ infix `≡` := equiv theorem equiv.refl (s : seq) : s ≡ s := begin intros, rewrite [sub_self, abs_zero], apply add_invs_nonneg end theorem equiv.symm (s t : seq) (H : s ≡ t) : t ≡ s := begin intros, rewrite [-abs_neg, neg_sub], exact H n end theorem bdd_of_eq {s t : seq} (H : s ≡ t) : ∀ j : ℕ+, ∀ n : ℕ+, n ≥ 2 * j → abs (s n - t n) ≤ j⁻¹ := begin intros [j, n, Hn], apply le.trans, apply H, rewrite -(pnat.add_halves j), apply add_le_add, apply inv_ge_of_le Hn, apply inv_ge_of_le Hn end theorem eq_of_bdd {s t : seq} (Hs : regular s) (Ht : regular t) (H : ∀ j : ℕ+, ∃ Nj : ℕ+, ∀ n : ℕ+, Nj ≤ n → abs (s n - t n) ≤ j⁻¹) : s ≡ t := begin intros, have Hj : (∀ j : ℕ+, abs (s n - t n) ≤ n⁻¹ + n⁻¹ + j⁻¹ + j⁻¹ + j⁻¹), begin intros, cases H j with [Nj, HNj], rewrite [-(sub_add_cancel (s n) (s (max j Nj))), +sub_eq_add_neg, add.assoc (s n + -s (max j Nj)), ↑regular at *], apply rat.le_trans, apply abs_add_le_abs_add_abs, apply rat.le_trans, apply add_le_add, apply Hs, rewrite [-(sub_add_cancel (s (max j Nj)) (t (max j Nj))), add.assoc], apply abs_add_le_abs_add_abs, apply rat.le_trans, apply rat.add_le_add_left, apply add_le_add, apply HNj (max j Nj) (le_max_right j Nj), apply Ht, have hsimp : ∀ m : ℕ+, n⁻¹ + m⁻¹ + (j⁻¹ + (m⁻¹ + n⁻¹)) = n⁻¹ + n⁻¹ + j⁻¹ + (m⁻¹ + m⁻¹), from λm, calc n⁻¹ + m⁻¹ + (j⁻¹ + (m⁻¹ + n⁻¹)) = n⁻¹ + (j⁻¹ + (m⁻¹ + n⁻¹)) + m⁻¹ : add.right_comm ... = n⁻¹ + (j⁻¹ + m⁻¹ + n⁻¹) + m⁻¹ : add.assoc ... = n⁻¹ + (n⁻¹ + (j⁻¹ + m⁻¹)) + m⁻¹ : add.comm ... = n⁻¹ + n⁻¹ + j⁻¹ + (m⁻¹ + m⁻¹) : by rewrite[-*add.assoc], rewrite hsimp, have Hms : (max j Nj)⁻¹ + (max j Nj)⁻¹ ≤ j⁻¹ + j⁻¹, begin apply add_le_add, apply inv_ge_of_le (le_max_left j Nj), apply inv_ge_of_le (le_max_left j Nj), end, apply (calc n⁻¹ + n⁻¹ + j⁻¹ + ((max j Nj)⁻¹ + (max j Nj)⁻¹) ≤ n⁻¹ + n⁻¹ + j⁻¹ + (j⁻¹ + j⁻¹) : rat.add_le_add_left Hms ... = n⁻¹ + n⁻¹ + j⁻¹ + j⁻¹ + j⁻¹ : by rewrite *rat.add_assoc) end, apply squeeze Hj end theorem eq_of_bdd_var {s t : seq} (Hs : regular s) (Ht : regular t) (H : ∀ ε : ℚ, ε > 0 → ∃ Nj : ℕ+, ∀ n : ℕ+, Nj ≤ n → abs (s n - t n) ≤ ε) : s ≡ t := begin apply eq_of_bdd, repeat assumption, intros, apply H, apply pnat.inv_pos end theorem bdd_of_eq_var {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : ∀ ε : ℚ, ε > 0 → ∃ Nj : ℕ+, ∀ n : ℕ+, Nj ≤ n → abs (s n - t n) ≤ ε := begin intro ε Hε, cases pnat_bound Hε with [N, HN], existsi 2 * N, intro n Hn, apply rat.le_trans, apply bdd_of_eq Heq N n Hn, exact HN -- assumption -- TODO: something funny here; what is 11.source.to_has_le_2? end theorem equiv.trans (s t u : seq) (Hs : regular s) (Ht : regular t) (Hu : regular u) (H : s ≡ t) (H2 : t ≡ u) : s ≡ u := begin apply eq_of_bdd Hs Hu, intros, existsi 2 * (2 * j), intro n Hn, rewrite [-sub_add_cancel (s n) (t n), *sub_eq_add_neg, add.assoc], apply rat.le_trans, apply abs_add_le_abs_add_abs, have Hst : abs (s n - t n) ≤ (2 * j)⁻¹, from bdd_of_eq H _ _ Hn, have Htu : abs (t n - u n) ≤ (2 * j)⁻¹, from bdd_of_eq H2 _ _ Hn, rewrite -(pnat.add_halves j), apply add_le_add, exact Hst, exact Htu end ----------------------------------- -- define operations on cauchy sequences. show operations preserve regularity private definition K (s : seq) : ℕ+ := pnat.pos (ubound (abs (s pone)) + 1 + 1) dec_trivial private theorem canon_bound {s : seq} (Hs : regular s) (n : ℕ+) : abs (s n) ≤ rat_of_pnat (K s) := calc abs (s n) = abs (s n - s pone + s pone) : by rewrite sub_add_cancel ... ≤ abs (s n - s pone) + abs (s pone) : abs_add_le_abs_add_abs ... ≤ n⁻¹ + pone⁻¹ + abs (s pone) : add_le_add_right !Hs ... = n⁻¹ + (1 + abs (s pone)) : by rewrite [pone_inv, rat.add_assoc] ... ≤ 1 + (1 + abs (s pone)) : add_le_add_right (inv_le_one n) ... = abs (s pone) + (1 + 1) : by rewrite [add.comm 1 (abs (s pone)), add.comm 1, rat.add_assoc] ... ≤ of_nat (ubound (abs (s pone))) + (1 + 1) : add_le_add_right (!ubound_ge) ... = of_nat (ubound (abs (s pone)) + (1 + 1)) : of_nat_add ... = of_nat (ubound (abs (s pone)) + 1 + 1) : add.assoc ... = rat_of_pnat (K s) : by esimp theorem bdd_of_regular {s : seq} (H : regular s) : ∃ b : ℚ, ∀ n : ℕ+, s n ≤ b := begin existsi rat_of_pnat (K s), intros, apply rat.le_trans, apply le_abs_self, apply canon_bound H end theorem bdd_of_regular_strict {s : seq} (H : regular s) : ∃ b : ℚ, ∀ n : ℕ+, s n < b := begin cases bdd_of_regular H with [b, Hb], existsi b + 1, intro n, apply rat.lt_of_le_of_lt, apply Hb, apply lt_add_of_pos_right, apply zero_lt_one end definition K₂ (s t : seq) := max (K s) (K t) private theorem K₂_symm (s t : seq) : K₂ s t = K₂ t s := !max.comm theorem canon_2_bound_left (s t : seq) (Hs : regular s) (n : ℕ+) : abs (s n) ≤ rat_of_pnat (K₂ s t) := calc abs (s n) ≤ rat_of_pnat (K s) : canon_bound Hs n ... ≤ rat_of_pnat (K₂ s t) : rat_of_pnat_le_of_pnat_le (!le_max_left) theorem canon_2_bound_right (s t : seq) (Ht : regular t) (n : ℕ+) : abs (t n) ≤ rat_of_pnat (K₂ s t) := calc abs (t n) ≤ rat_of_pnat (K t) : canon_bound Ht n ... ≤ rat_of_pnat (K₂ s t) : rat_of_pnat_le_of_pnat_le (!le_max_right) definition sadd (s t : seq) : seq := λ n, (s (2 * n)) + (t (2 * n)) theorem reg_add_reg {s t : seq} (Hs : regular s) (Ht : regular t) : regular (sadd s t) := begin rewrite [↑regular at *, ↑sadd], intros, rewrite add_sub_comm, apply rat.le_trans, apply abs_add_le_abs_add_abs, rewrite add_halves_double, apply add_le_add, apply Hs, apply Ht end definition smul (s t : seq) : seq := λ n : ℕ+, (s ((K₂ s t) * 2 * n)) * (t ((K₂ s t) * 2 * n)) theorem reg_mul_reg {s t : seq} (Hs : regular s) (Ht : regular t) : regular (smul s t) := begin rewrite [↑regular at *, ↑smul], intros, rewrite rewrite_helper, apply rat.le_trans, apply abs_add_le_abs_add_abs, apply rat.le_trans, apply add_le_add, rewrite abs_mul, apply mul_le_mul_of_nonneg_right, apply canon_2_bound_left s t Hs, apply abs_nonneg, rewrite abs_mul, apply mul_le_mul_of_nonneg_left, apply canon_2_bound_right s t Ht, apply abs_nonneg, apply ineq_helper, apply Ht, apply Hs end definition sneg (s : seq) : seq := λ n : ℕ+, - (s n) theorem reg_neg_reg {s : seq} (Hs : regular s) : regular (sneg s) := begin rewrite [↑regular at *, ↑sneg], intros, rewrite [-abs_neg, neg_sub, sub_neg_eq_add, add.comm], apply Hs end ----------------------------------- -- show properties of +, *, - definition zero : seq := λ n, 0 definition one : seq := λ n, 1 theorem s_add_comm (s t : seq) : sadd s t ≡ sadd t s := begin esimp [sadd], intro n, rewrite [sub_add_eq_sub_sub, add_sub_cancel, sub_self, abs_zero], apply add_invs_nonneg end theorem s_add_assoc (s t u : seq) (Hs : regular s) (Hu : regular u) : sadd (sadd s t) u ≡ sadd s (sadd t u) := begin rewrite [↑sadd, ↑equiv, ↑regular at *], intros, rewrite factor_lemma, apply rat.le_trans, apply abs_add_le_abs_add_abs, apply rat.le_trans, rotate 1, apply add_le_add_right, apply inv_two_mul_le_inv, rewrite [-(pnat.add_halves (2 * n)), -(pnat.add_halves n), factor_lemma_2], apply add_le_add, apply Hs, apply Hu end theorem s_mul_comm (s t : seq) : smul s t ≡ smul t s := begin rewrite ↑smul, intros n, rewrite [*(K₂_symm s t), rat.mul_comm, sub_self, abs_zero], apply add_invs_nonneg end private definition DK (s t : seq) := (K₂ s t) * 2 private theorem DK_rewrite (s t : seq) : (K₂ s t) * 2 = DK s t := rfl private definition TK (s t u : seq) := (DK (λ (n : ℕ+), s (mul (DK s t) n) * t (mul (DK s t) n)) u) private theorem TK_rewrite (s t u : seq) : (DK (λ (n : ℕ+), s (mul (DK s t) n) * t (mul (DK s t) n)) u) = TK s t u := rfl private theorem s_mul_assoc_lemma (s t u : seq) (a b c d : ℕ+) : abs (s a * t a * u b - s c * t d * u d) ≤ abs (t a) * abs (u b) * abs (s a - s c) + abs (s c) * abs (t a) * abs (u b - u d) + abs (s c) * abs (u d) * abs (t a - t d) := begin rewrite (rewrite_helper7 _ _ _ _ (s c)), apply rat.le_trans, apply abs_add_le_abs_add_abs, rewrite rat.add_assoc, apply add_le_add, rewrite 2 abs_mul, apply le.refl, rewrite [*rat.mul_assoc, -mul_sub_left_distrib, -left_distrib, abs_mul], apply mul_le_mul_of_nonneg_left, rewrite rewrite_helper, apply le.trans, apply abs_add_le_abs_add_abs, apply add_le_add, rewrite abs_mul, apply rat.le_refl, rewrite [abs_mul, rat.mul_comm], apply rat.le_refl, apply abs_nonneg end private definition Kq (s : seq) := rat_of_pnat (K s) + 1 private theorem Kq_bound {s : seq} (H : regular s) : ∀ n, abs (s n) ≤ Kq s := begin intros, apply le_of_lt, apply lt_of_le_of_lt, apply canon_bound H, apply lt_add_of_pos_right, apply zero_lt_one end private theorem Kq_bound_nonneg {s : seq} (H : regular s) : 0 ≤ Kq s := le.trans !abs_nonneg (Kq_bound H 2) private theorem Kq_bound_pos {s : seq} (H : regular s) : 0 < Kq s := have H1 : 0 ≤ rat_of_pnat (K s), from rat.le_trans (!abs_nonneg) (canon_bound H 2), add_pos_of_nonneg_of_pos H1 rat.zero_lt_one private theorem s_mul_assoc_lemma_5 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (a b c : ℕ+) : abs (t a) * abs (u b) * abs (s a - s c) ≤ (Kq t) * (Kq u) * (a⁻¹ + c⁻¹) := begin repeat apply mul_le_mul, apply Kq_bound Ht, apply Kq_bound Hu, apply abs_nonneg, apply Kq_bound_nonneg Ht, apply Hs, apply abs_nonneg, apply rat.mul_nonneg, apply Kq_bound_nonneg Ht, apply Kq_bound_nonneg Hu, end private theorem s_mul_assoc_lemma_2 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (a b c d : ℕ+) : abs (t a) * abs (u b) * abs (s a - s c) + abs (s c) * abs (t a) * abs (u b - u d) + abs (s c) * abs (u d) * abs (t a - t d) ≤ (Kq t) * (Kq u) * (a⁻¹ + c⁻¹) + (Kq s) * (Kq t) * (b⁻¹ + d⁻¹) + (Kq s) * (Kq u) * (a⁻¹ + d⁻¹) := begin apply add_le_add_three, repeat (assumption | apply mul_le_mul | apply Kq_bound | apply Kq_bound_nonneg | apply abs_nonneg), apply Hs, apply abs_nonneg, apply rat.mul_nonneg, repeat (assumption | apply mul_le_mul | apply Kq_bound | apply Kq_bound_nonneg | apply abs_nonneg), apply Hu, apply abs_nonneg, apply rat.mul_nonneg, repeat (assumption | apply mul_le_mul | apply Kq_bound | apply Kq_bound_nonneg | apply abs_nonneg), apply Ht, apply abs_nonneg, apply rat.mul_nonneg, repeat (apply Kq_bound_nonneg; assumption) end theorem s_mul_assoc {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) : smul (smul s t) u ≡ smul s (smul t u) := begin apply eq_of_bdd_var, repeat apply reg_mul_reg, apply Hs, apply Ht, apply Hu, apply reg_mul_reg Hs, apply reg_mul_reg Ht Hu, intros, apply exists.intro, intros, rewrite [↑smul, *DK_rewrite, *TK_rewrite, -*pnat.mul_assoc, -*mul.assoc], apply rat.le_trans, apply s_mul_assoc_lemma, apply rat.le_trans, apply s_mul_assoc_lemma_2, apply Hs, apply Ht, apply Hu, rewrite [*s_mul_assoc_lemma_3, -distrib_three_right], apply s_mul_assoc_lemma_4, apply a, repeat apply add_pos, repeat apply mul_pos, apply Kq_bound_pos Ht, apply Kq_bound_pos Hu, apply add_pos, repeat apply pnat.inv_pos, repeat apply rat.mul_pos, apply Kq_bound_pos Hs, apply Kq_bound_pos Ht, apply add_pos, repeat apply pnat.inv_pos, repeat apply rat.mul_pos, apply Kq_bound_pos Hs, apply Kq_bound_pos Hu, apply add_pos, repeat apply pnat.inv_pos, apply a_1 end theorem zero_is_reg : regular zero := begin rewrite [↑regular, ↑zero], intros, rewrite [sub_zero, abs_zero], apply add_invs_nonneg end theorem s_zero_add (s : seq) (H : regular s) : sadd zero s ≡ s := begin rewrite [↑sadd, ↑zero, ↑equiv, ↑regular at H], intros, rewrite [rat.zero_add], apply rat.le_trans, apply H, apply add_le_add, apply inv_two_mul_le_inv, apply rat.le_refl end theorem s_add_zero (s : seq) (H : regular s) : sadd s zero ≡ s := begin rewrite [↑sadd, ↑zero, ↑equiv, ↑regular at H], intros, rewrite [rat.add_zero], apply rat.le_trans, apply H, apply add_le_add, apply inv_two_mul_le_inv, apply rat.le_refl end theorem s_neg_cancel (s : seq) (H : regular s) : sadd (sneg s) s ≡ zero := begin rewrite [↑sadd, ↑sneg, ↑regular at H, ↑zero, ↑equiv], intros, rewrite [neg_add_eq_sub, sub_self, sub_zero, abs_zero], apply add_invs_nonneg end theorem neg_s_cancel (s : seq) (H : regular s) : sadd s (sneg s) ≡ zero := begin apply equiv.trans, rotate 3, apply s_add_comm, apply s_neg_cancel s H, repeat (apply reg_add_reg | apply reg_neg_reg | assumption), apply zero_is_reg end theorem add_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Esu : s ≡ u) (Etv : t ≡ v) : sadd s t ≡ sadd u v := begin rewrite [↑sadd, ↑equiv at *], intros, rewrite [add_sub_comm, add_halves_double], apply rat.le_trans, apply abs_add_le_abs_add_abs, apply add_le_add, apply Esu, apply Etv end set_option tactic.goal_names false private theorem mul_bound_helper {s t : seq} (Hs : regular s) (Ht : regular t) (a b c : ℕ+) (j : ℕ+) : ∃ N : ℕ+, ∀ n : ℕ+, n ≥ N → abs (s (a * n) * t (b * n) - s (c * n) * t (c * n)) ≤ j⁻¹ := begin existsi pceil (((rat_of_pnat (K s)) * (b⁻¹ + c⁻¹) + (a⁻¹ + c⁻¹) * (rat_of_pnat (K t))) * (rat_of_pnat j)), intros n Hn, rewrite rewrite_helper4, apply rat.le_trans, apply abs_add_le_abs_add_abs, apply rat.le_trans, rotate 1, show n⁻¹ * ((rat_of_pnat (K s)) * (b⁻¹ + c⁻¹)) + n⁻¹ * ((a⁻¹ + c⁻¹) * (rat_of_pnat (K t))) ≤ j⁻¹, begin rewrite -left_distrib, apply rat.le_trans, apply mul_le_mul_of_nonneg_right, apply pceil_helper Hn, { repeat (apply mul_pos | apply add_pos | apply rat_of_pnat_is_pos | apply pnat.inv_pos) }, apply rat.le_of_lt, apply add_pos, apply rat.mul_pos, apply rat_of_pnat_is_pos, apply add_pos, apply pnat.inv_pos, apply pnat.inv_pos, apply rat.mul_pos, apply add_pos, apply pnat.inv_pos, apply pnat.inv_pos, apply rat_of_pnat_is_pos, have H : (rat_of_pnat (K s) * (b⁻¹ + c⁻¹) + (a⁻¹ + c⁻¹) * rat_of_pnat (K t)) ≠ 0, begin apply ne_of_gt, repeat (apply mul_pos | apply add_pos | apply rat_of_pnat_is_pos | apply pnat.inv_pos), end, rewrite (!div_helper H), apply rat.le_refl end, apply add_le_add, rewrite [-mul_sub_left_distrib, abs_mul], apply rat.le_trans, apply mul_le_mul, apply canon_bound, apply Hs, apply Ht, apply abs_nonneg, apply rat.le_of_lt, apply rat_of_pnat_is_pos, rewrite [*pnat.inv_mul_eq_mul_inv, -right_distrib, -rat.mul_assoc, rat.mul_comm], apply mul_le_mul_of_nonneg_left, apply rat.le_refl, apply rat.le_of_lt, apply pnat.inv_pos, rewrite [-mul_sub_right_distrib, abs_mul], apply rat.le_trans, apply mul_le_mul, apply Hs, apply canon_bound, apply Ht, apply abs_nonneg, apply add_invs_nonneg, rewrite [*pnat.inv_mul_eq_mul_inv, -right_distrib, mul.comm _ n⁻¹, rat.mul_assoc], apply mul_le_mul, repeat apply rat.le_refl, apply rat.le_of_lt, apply rat.mul_pos, apply add_pos, repeat apply pnat.inv_pos, apply rat_of_pnat_is_pos, apply rat.le_of_lt, apply pnat.inv_pos end theorem s_distrib {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) : smul s (sadd t u) ≡ sadd (smul s t) (smul s u) := begin apply eq_of_bdd, repeat (assumption | apply reg_add_reg | apply reg_mul_reg), intros, let exh1 := λ a b c, mul_bound_helper Hs Ht a b c (2 * j), apply exists.elim, apply exh1, rotate 3, intros N1 HN1, let exh2 := λ d e f, mul_bound_helper Hs Hu d e f (2 * j), apply exists.elim, apply exh2, rotate 3, intros N2 HN2, existsi max N1 N2, intros n Hn, rewrite [↑sadd at *, ↑smul, rewrite_helper3, -pnat.add_halves j, -*pnat.mul_assoc at *], apply rat.le_trans, apply abs_add_le_abs_add_abs, apply add_le_add, apply HN1, apply le.trans, apply le_max_left N1 N2, apply Hn, apply HN2, apply le.trans, apply le_max_right N1 N2, apply Hn end theorem mul_zero_equiv_zero {s t : seq} (Hs : regular s) (Ht : regular t) (Htz : t ≡ zero) : smul s t ≡ zero := begin apply eq_of_bdd_var, apply reg_mul_reg Hs Ht, apply zero_is_reg, intro ε Hε, let Bd := bdd_of_eq_var Ht zero_is_reg Htz (ε / (Kq s)) (div_pos_of_pos_of_pos Hε (Kq_bound_pos Hs)), cases Bd with [N, HN], existsi N, intro n Hn, rewrite [↑equiv at Htz, ↑zero at *, sub_zero, ↑smul, abs_mul], apply le.trans, apply mul_le_mul, apply Kq_bound Hs, have HN' : ∀ (n : ℕ+), N ≤ n → abs (t n) ≤ ε / Kq s, from λ n, (eq.subst (sub_zero (t n)) (HN n)), apply HN', apply le.trans Hn, apply pnat.mul_le_mul_left, apply abs_nonneg, apply le_of_lt (Kq_bound_pos Hs), rewrite (mul_div_cancel' (ne.symm (ne_of_lt (Kq_bound_pos Hs)))), apply le.refl end private theorem neg_bound_eq_bound (s : seq) : K (sneg s) = K s := by rewrite [↑K, ↑sneg, abs_neg] private theorem neg_bound2_eq_bound2 (s t : seq) : K₂ s (sneg t) = K₂ s t := by rewrite [↑K₂, neg_bound_eq_bound] private theorem sneg_def (s : seq) : (λ (n : ℕ+), -(s n)) = sneg s := rfl theorem mul_neg_equiv_neg_mul {s t : seq} : smul s (sneg t) ≡ sneg (smul s t) := begin rewrite [↑equiv, ↑smul], intros, rewrite [↑sneg, *sub_neg_eq_add, -neg_mul_eq_mul_neg, add.comm], rewrite [*sneg_def t, *neg_bound2_eq_bound2, add.right_inv, abs_zero], apply add_invs_nonneg end theorem equiv_of_diff_equiv_zero {s t : seq} (Hs : regular s) (Ht : regular t) (H : sadd s (sneg t) ≡ zero) : s ≡ t := begin have hsimp : ∀ a b c d e : ℚ, a + b + c + (d + e) = b + d + a + e + c, from λ a b c d e, calc a + b + c + (d + e) = a + b + (d + e) + c : add.right_comm ... = a + (b + d) + e + c : by rewrite[-*add.assoc] ... = b + d + a + e + c : add.comm, apply eq_of_bdd Hs Ht, intros, note He := bdd_of_eq H, existsi 2 * (2 * (2 * j)), intros n Hn, rewrite (rewrite_helper5 _ _ (s (2 * n)) (t (2 * n))), apply rat.le_trans, apply abs_add_three, apply rat.le_trans, apply add_le_add_three, apply Hs, rewrite [↑sadd at He, ↑sneg at He, ↑zero at He], let He' := λ a b c, eq.subst !sub_zero (He a b c), apply (He' _ _ Hn), apply Ht, rewrite [hsimp, pnat.add_halves, -(pnat.add_halves j), -(pnat.add_halves (2 * j)), -*rat.add_assoc], apply add_le_add_right, apply add_le_add_three, repeat (apply rat.le_trans; apply inv_ge_of_le Hn; apply inv_two_mul_le_inv) end theorem s_sub_cancel (s : seq) : sadd s (sneg s) ≡ zero := begin rewrite [↑equiv, ↑sadd, ↑sneg, ↑zero], intros, rewrite [sub_zero, add.right_inv, abs_zero], apply add_invs_nonneg end theorem diff_equiv_zero_of_equiv {s t : seq} (Hs : regular s) (Ht : regular t) (H : s ≡ t) : sadd s (sneg t) ≡ zero := begin apply equiv.trans, rotate 4, apply s_sub_cancel t, rotate 2, apply zero_is_reg, apply add_well_defined, repeat (assumption | apply reg_neg_reg), apply equiv.refl, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end private theorem mul_well_defined_half1 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Etu : t ≡ u) : smul s t ≡ smul s u := begin apply equiv_of_diff_equiv_zero, rotate 2, apply equiv.trans, rotate 3, apply equiv.symm, apply add_well_defined, rotate 4, apply equiv.refl, apply mul_neg_equiv_neg_mul, apply equiv.trans, rotate 3, apply equiv.symm, apply s_distrib, rotate 3, apply mul_zero_equiv_zero, rotate 2, apply diff_equiv_zero_of_equiv, repeat (assumption | apply reg_mul_reg | apply reg_neg_reg | apply reg_add_reg | apply zero_is_reg) end private theorem mul_well_defined_half2 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Est : s ≡ t) : smul s u ≡ smul t u := begin apply equiv.trans, rotate 3, apply s_mul_comm, apply equiv.trans, rotate 3, apply mul_well_defined_half1, rotate 2, apply Ht, rotate 1, apply s_mul_comm, repeat (assumption | apply reg_mul_reg) end theorem mul_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Esu : s ≡ u) (Etv : t ≡ v) : smul s t ≡ smul u v := begin apply equiv.trans, exact reg_mul_reg Hs Ht, exact reg_mul_reg Hs Hv, exact reg_mul_reg Hu Hv, apply mul_well_defined_half1, repeat assumption, apply mul_well_defined_half2, repeat assumption end theorem neg_well_defined {s t : seq} (Est : s ≡ t) : sneg s ≡ sneg t := begin rewrite [↑sneg, ↑equiv at *], intros, rewrite [-abs_neg, neg_sub, sub_neg_eq_add, add.comm], apply Est end theorem one_is_reg : regular one := begin rewrite [↑regular, ↑one], intros, rewrite [sub_self, abs_zero], apply add_invs_nonneg end theorem s_one_mul {s : seq} (H : regular s) : smul one s ≡ s := begin intros, rewrite [↑smul, ↑one, rat.one_mul], apply rat.le_trans, apply H, apply add_le_add_right, apply pnat.inv_mul_le_inv end theorem s_mul_one {s : seq} (H : regular s) : smul s one ≡ s := begin apply equiv.trans, apply reg_mul_reg H one_is_reg, rotate 2, apply s_mul_comm, apply s_one_mul H, apply reg_mul_reg one_is_reg H, apply H end theorem zero_nequiv_one : ¬ zero ≡ one := begin intro Hz, rewrite [↑equiv at Hz, ↑zero at Hz, ↑one at Hz], note H := Hz (2 * 2), rewrite [zero_sub at H, abs_neg at H, pnat.add_halves at H], have H' : pone⁻¹ ≤ 2⁻¹, from calc pone⁻¹ = 1 : by rewrite -pone_inv ... = abs 1 : abs_of_pos zero_lt_one ... ≤ 2⁻¹ : H, let H'' := ge_of_inv_le H', apply absurd (one_lt_two) (not_lt_of_ge H'') end --------------------------------------------- -- constant sequences definition const (a : ℚ) : seq := λ n, a theorem const_reg (a : ℚ) : regular (const a) := begin intros, rewrite [↑const, sub_self, abs_zero], apply add_invs_nonneg end theorem add_consts (a b : ℚ) : sadd (const a) (const b) ≡ const (a + b) := by apply equiv.refl theorem mul_consts (a b : ℚ) : smul (const a) (const b) ≡ const (a * b) := by apply equiv.refl theorem neg_const (a : ℚ) : sneg (const a) ≡ const (-a) := by apply equiv.refl section open rat lemma eq_of_const_equiv {a b : ℚ} (H : const a ≡ const b) : a = b := have H₁ : ∀ n : ℕ+, abs (a - b) ≤ n⁻¹ + n⁻¹, from H, eq_of_forall_abs_sub_le (take ε, suppose ε > 0, have ε / 2 > 0, begin exact div_pos_of_pos_of_pos this two_pos end, obtain n (Hn : n⁻¹ ≤ ε / 2), from pnat_bound this, show abs (a - b) ≤ ε, from calc abs (a - b) ≤ n⁻¹ + n⁻¹ : H₁ n ... ≤ ε / 2 + ε / 2 : add_le_add Hn Hn ... = ε : add_halves) end --------------------------------------------- -- create the type of regular sequences and lift theorems record reg_seq : Type := (sq : seq) (is_reg : regular sq) definition requiv (s t : reg_seq) := (reg_seq.sq s) ≡ (reg_seq.sq t) definition requiv.refl (s : reg_seq) : requiv s s := equiv.refl (reg_seq.sq s) definition requiv.symm (s t : reg_seq) (H : requiv s t) : requiv t s := equiv.symm (reg_seq.sq s) (reg_seq.sq t) H definition requiv.trans (s t u : reg_seq) (H : requiv s t) (H2 : requiv t u) : requiv s u := equiv.trans _ _ _ (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) H H2 definition radd (s t : reg_seq) : reg_seq := reg_seq.mk (sadd (reg_seq.sq s) (reg_seq.sq t)) (reg_add_reg (reg_seq.is_reg s) (reg_seq.is_reg t)) infix + := radd definition rmul (s t : reg_seq) : reg_seq := reg_seq.mk (smul (reg_seq.sq s) (reg_seq.sq t)) (reg_mul_reg (reg_seq.is_reg s) (reg_seq.is_reg t)) infix * := rmul definition rneg (s : reg_seq) : reg_seq := reg_seq.mk (sneg (reg_seq.sq s)) (reg_neg_reg (reg_seq.is_reg s)) prefix - := rneg definition radd_well_defined {s t u v : reg_seq} (H : requiv s u) (H2 : requiv t v) : requiv (s + t) (u + v) := add_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) H H2 definition rmul_well_defined {s t u v : reg_seq} (H : requiv s u) (H2 : requiv t v) : requiv (s * t) (u * v) := mul_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) H H2 definition rneg_well_defined {s t : reg_seq} (H : requiv s t) : requiv (-s) (-t) := neg_well_defined H theorem requiv_is_equiv : equivalence requiv := mk_equivalence requiv requiv.refl requiv.symm requiv.trans definition reg_seq.to_setoid [instance] : setoid reg_seq := ⦃setoid, r := requiv, iseqv := requiv_is_equiv⦄ definition r_zero : reg_seq := reg_seq.mk (zero) (zero_is_reg) definition r_one : reg_seq := reg_seq.mk (one) (one_is_reg) theorem r_add_comm (s t : reg_seq) : requiv (s + t) (t + s) := s_add_comm (reg_seq.sq s) (reg_seq.sq t) theorem r_add_assoc (s t u : reg_seq) : requiv (s + t + u) (s + (t + u)) := s_add_assoc (reg_seq.sq s) (reg_seq.sq t) (reg_seq.sq u) (reg_seq.is_reg s) (reg_seq.is_reg u) theorem r_zero_add (s : reg_seq) : requiv (r_zero + s) s := s_zero_add (reg_seq.sq s) (reg_seq.is_reg s) theorem r_add_zero (s : reg_seq) : requiv (s + r_zero) s := s_add_zero (reg_seq.sq s) (reg_seq.is_reg s) theorem r_neg_cancel (s : reg_seq) : requiv (-s + s) r_zero := s_neg_cancel (reg_seq.sq s) (reg_seq.is_reg s) theorem r_mul_comm (s t : reg_seq) : requiv (s * t) (t * s) := s_mul_comm (reg_seq.sq s) (reg_seq.sq t) theorem r_mul_assoc (s t u : reg_seq) : requiv (s * t * u) (s * (t * u)) := s_mul_assoc (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) theorem r_mul_one (s : reg_seq) : requiv (s * r_one) s := s_mul_one (reg_seq.is_reg s) theorem r_one_mul (s : reg_seq) : requiv (r_one * s) s := s_one_mul (reg_seq.is_reg s) theorem r_distrib (s t u : reg_seq) : requiv (s * (t + u)) (s * t + s * u) := s_distrib (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) theorem r_zero_nequiv_one : ¬ requiv r_zero r_one := zero_nequiv_one definition r_const (a : ℚ) : reg_seq := reg_seq.mk (const a) (const_reg a) theorem r_add_consts (a b : ℚ) : requiv (r_const a + r_const b) (r_const (a + b)) := add_consts a b theorem r_mul_consts (a b : ℚ) : requiv (r_const a * r_const b) (r_const (a * b)) := mul_consts a b theorem r_neg_const (a : ℚ) : requiv (-r_const a) (r_const (-a)) := neg_const a end rat_seq ---------------------------------------------- -- take quotients to get ℝ and show it's a comm ring open rat_seq definition real := quot reg_seq.to_setoid namespace real notation `ℝ` := real protected definition prio := num.pred rat.prio protected definition add (x y : ℝ) : ℝ := (quot.lift_on₂ x y (λ a b, quot.mk (a + b)) (take a b c d : reg_seq, take Hab : requiv a c, take Hcd : requiv b d, quot.sound (radd_well_defined Hab Hcd))) --infix [priority real.prio] + := add protected definition mul (x y : ℝ) : ℝ := (quot.lift_on₂ x y (λ a b, quot.mk (a * b)) (take a b c d : reg_seq, take Hab : requiv a c, take Hcd : requiv b d, quot.sound (rmul_well_defined Hab Hcd))) --infix [priority real.prio] * := mul protected definition neg (x : ℝ) : ℝ := (quot.lift_on x (λ a, quot.mk (-a)) (take a b : reg_seq, take Hab : requiv a b, quot.sound (rneg_well_defined Hab))) --prefix [priority real.prio] `-` := neg definition real_has_add [instance] [priority real.prio] : has_add real := has_add.mk real.add definition real_has_mul [instance] [priority real.prio] : has_mul real := has_mul.mk real.mul definition real_has_neg [instance] [priority real.prio] : has_neg real := has_neg.mk real.neg protected definition sub [reducible] (a b : ℝ) : real := a + (-b) definition real_has_sub [instance] [priority real.prio] : has_sub real := has_sub.mk real.sub open rat -- no coercions before definition of_rat [coercion] (a : ℚ) : ℝ := quot.mk (r_const a) definition of_int [coercion] (i : ℤ) : ℝ := i definition of_nat [coercion] (n : ℕ) : ℝ := n definition of_num [coercion] [reducible] (n : num) : ℝ := of_rat (rat.of_num n) definition real_has_zero [reducible] : has_zero real := has_zero.mk (of_rat 0) local attribute real_has_zero [instance] [priority real.prio] definition real_has_one [reducible] : has_one real := has_one.mk (of_rat 1) local attribute real_has_one [instance] [priority real.prio] theorem real_zero_eq_rat_zero : (0:real) = of_rat (0:rat) := rfl theorem real_one_eq_rat_one : (1:real) = of_rat (1:rat) := rfl protected theorem add_comm (x y : ℝ) : x + y = y + x := quot.induction_on₂ x y (λ s t, quot.sound (r_add_comm s t)) protected theorem add_assoc (x y z : ℝ) : x + y + z = x + (y + z) := quot.induction_on₃ x y z (λ s t u, quot.sound (r_add_assoc s t u)) protected theorem zero_add (x : ℝ) : 0 + x = x := quot.induction_on x (λ s, quot.sound (r_zero_add s)) protected theorem add_zero (x : ℝ) : x + 0 = x := quot.induction_on x (λ s, quot.sound (r_add_zero s)) protected theorem neg_cancel (x : ℝ) : -x + x = 0 := quot.induction_on x (λ s, quot.sound (r_neg_cancel s)) protected theorem mul_assoc (x y z : ℝ) : x * y * z = x * (y * z) := quot.induction_on₃ x y z (λ s t u, quot.sound (r_mul_assoc s t u)) protected theorem mul_comm (x y : ℝ) : x * y = y * x := quot.induction_on₂ x y (λ s t, quot.sound (r_mul_comm s t)) protected theorem one_mul (x : ℝ) : 1 * x = x := quot.induction_on x (λ s, quot.sound (r_one_mul s)) protected theorem mul_one (x : ℝ) : x * 1 = x := quot.induction_on x (λ s, quot.sound (r_mul_one s)) protected theorem left_distrib (x y z : ℝ) : x * (y + z) = x * y + x * z := quot.induction_on₃ x y z (λ s t u, quot.sound (r_distrib s t u)) protected theorem right_distrib (x y z : ℝ) : (x + y) * z = x * z + y * z := by rewrite [real.mul_comm, real.left_distrib, {x * _}real.mul_comm, {y * _}real.mul_comm] protected theorem zero_ne_one : ¬ (0 : ℝ) = 1 := take H : 0 = 1, absurd (quot.exact H) (r_zero_nequiv_one) protected definition comm_ring [reducible] : comm_ring ℝ := begin fapply comm_ring.mk, exact real.add, exact real.add_assoc, exact 0, exact real.zero_add, exact real.add_zero, exact real.neg, exact real.neg_cancel, exact real.add_comm, exact real.mul, exact real.mul_assoc, apply 1, apply real.one_mul, apply real.mul_one, apply real.left_distrib, apply real.right_distrib, apply real.mul_comm end theorem of_int_eq (a : ℤ) : of_int a = of_rat (rat.of_int a) := rfl theorem of_nat_eq (a : ℕ) : of_nat a = of_rat (rat.of_nat a) := rfl theorem of_rat.inj {x y : ℚ} (H : of_rat x = of_rat y) : x = y := eq_of_const_equiv (quot.exact H) theorem eq_of_of_rat_eq_of_rat {x y : ℚ} (H : of_rat x = of_rat y) : x = y := of_rat.inj H theorem of_rat_eq_of_rat_iff (x y : ℚ) : of_rat x = of_rat y ↔ x = y := iff.intro eq_of_of_rat_eq_of_rat !congr_arg theorem of_int.inj {a b : ℤ} (H : of_int a = of_int b) : a = b := rat.of_int.inj (of_rat.inj H) theorem eq_of_of_int_eq_of_int {a b : ℤ} (H : of_int a = of_int b) : a = b := of_int.inj H theorem of_int_eq_of_int_iff (a b : ℤ) : of_int a = of_int b ↔ a = b := iff.intro of_int.inj !congr_arg theorem of_nat.inj {a b : ℕ} (H : of_nat a = of_nat b) : a = b := int.of_nat.inj (of_int.inj H) theorem eq_of_of_nat_eq_of_nat {a b : ℕ} (H : of_nat a = of_nat b) : a = b := of_nat.inj H theorem of_nat_eq_of_nat_iff (a b : ℕ) : of_nat a = of_nat b ↔ a = b := iff.intro of_nat.inj !congr_arg theorem of_rat_add (a b : ℚ) : of_rat (a + b) = of_rat a + of_rat b := quot.sound (r_add_consts a b) theorem of_rat_neg (a : ℚ) : of_rat (-a) = -of_rat a := eq.symm (quot.sound (r_neg_const a)) theorem of_rat_mul (a b : ℚ) : of_rat (a * b) = of_rat a * of_rat b := quot.sound (r_mul_consts a b) theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl open int theorem of_int_add (a b : ℤ) : of_int (a + b) = of_int a + of_int b := by rewrite [of_int_eq, rat.of_int_add, of_rat_add] theorem of_int_neg (a : ℤ) : of_int (-a) = -of_int a := by rewrite [of_int_eq, rat.of_int_neg, of_rat_neg] theorem of_int_mul (a b : ℤ) : of_int (a * b) = of_int a * of_int b := by rewrite [of_int_eq, rat.of_int_mul, of_rat_mul] theorem of_nat_add (a b : ℕ) : of_nat (a + b) = of_nat a + of_nat b := by rewrite [of_nat_eq, rat.of_nat_add, of_rat_add] theorem of_nat_mul (a b : ℕ) : of_nat (a * b) = of_nat a * of_nat b := by rewrite [of_nat_eq, rat.of_nat_mul, of_rat_mul] theorem add_half_of_rat (n : ℕ+) : of_rat (2 * n)⁻¹ + of_rat (2 * n)⁻¹ = of_rat (n⁻¹) := by rewrite [-of_rat_add, pnat.add_halves] theorem one_add_one : 1 + 1 = (2 : ℝ) := rfl end real
4dd48f15d480819d2e5e6fec9e3acdf1e60259fb
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/implementedByIssue.lean
3ee6de2f1f3f98aa3e0a233e3b391f0bda455b5b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
574
lean
namespace Hidden structure Array (α : Type u) (n : Nat) : Type u where data : (i : Fin n) → α @[extern "some_extern"] def get {α} {n : Nat} (A : Array α n) (i : Fin n) : α := A.data i attribute [implementedBy get] Array.data -- ok def get_2 {α : Type} {n : Nat} (A : Array α n) (i : Fin n) : α := A.data i attribute [implementedBy get_2] Array.data -- error, number of universe parameters do not match def get_3 {α} {n : Nat} (i : Fin n) (A : Array α n) : α := A.data i attribute [implementedBy get_3] Array.data -- error, types do not match
9792fcb854181b12c3a13e0cb63be61092d2797a
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_geometry/AffineScheme.lean
5d5b52cc7c56cbf711ed8d89f01bb697cee32b00
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
17,498
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 algebraic_geometry.Gamma_Spec_adjunction import algebraic_geometry.open_immersion import category_theory.limits.opposites /-! # Affine schemes We define the category of `AffineScheme`s as the essential image of `Spec`. We also define predicates about affine schemes and affine open sets. ## Main definitions * `algebraic_geometry.AffineScheme`: The category of affine schemes. * `algebraic_geometry.is_affine`: A scheme is affine if the canonical map `X ⟶ Spec Γ(X)` is an isomorphism. * `algebraic_geometry.Scheme.iso_Spec`: The canonical isomorphism `X ≅ Spec Γ(X)` for an affine scheme. * `algebraic_geometry.AffineScheme.equiv_CommRing`: The equivalence of categories `AffineScheme ≌ CommRingᵒᵖ` given by `AffineScheme.Spec : CommRingᵒᵖ ⥤ AffineScheme` and `AffineScheme.Γ : AffineSchemeᵒᵖ ⥤ CommRing`. * `algebraic_geometry.is_affine_open`: An open subset of a scheme is affine if the open subscheme is affine. * `algebraic_geometry.is_affine_open.from_Spec`: The immersion `Spec 𝒪ₓ(U) ⟶ X` for an affine `U`. -/ noncomputable theory open category_theory category_theory.limits opposite topological_space universe u namespace algebraic_geometry open Spec (structure_sheaf) /-- The category of affine schemes -/ def AffineScheme := Scheme.Spec.ess_image /-- A Scheme is affine if the canonical map `X ⟶ Spec Γ(X)` is an isomorphism. -/ class is_affine (X : Scheme) : Prop := (affine : is_iso (Γ_Spec.adjunction.unit.app X)) attribute [instance] is_affine.affine /-- The canonical isomorphism `X ≅ Spec Γ(X)` for an affine scheme. -/ def Scheme.iso_Spec (X : Scheme) [is_affine X] : X ≅ Scheme.Spec.obj (op $ Scheme.Γ.obj $ op X) := as_iso (Γ_Spec.adjunction.unit.app X) lemma mem_AffineScheme (X : Scheme) : X ∈ AffineScheme ↔ is_affine X := ⟨λ h, ⟨functor.ess_image.unit_is_iso h⟩, λ h, @@mem_ess_image_of_unit_is_iso _ _ _ X h.1⟩ instance is_affine_AffineScheme (X : AffineScheme.{u}) : is_affine (X : Scheme.{u}) := (mem_AffineScheme _).mp X.prop instance Spec_is_affine (R : CommRingᵒᵖ) : is_affine (Scheme.Spec.obj R) := (mem_AffineScheme _).mp (Scheme.Spec.obj_mem_ess_image R) lemma is_affine_of_iso {X Y : Scheme} (f : X ⟶ Y) [is_iso f] [h : is_affine Y] : is_affine X := by { rw [← mem_AffineScheme] at h ⊢, exact functor.ess_image.of_iso (as_iso f).symm h } namespace AffineScheme /-- The `Spec` functor into the category of affine schemes. -/ @[derive [full, faithful, ess_surj]] def Spec : CommRingᵒᵖ ⥤ AffineScheme := Scheme.Spec.to_ess_image /-- The forgetful functor `AffineScheme ⥤ Scheme`. -/ @[derive [full, faithful], simps] def forget_to_Scheme : AffineScheme ⥤ Scheme := Scheme.Spec.ess_image_inclusion /-- The global section functor of an affine scheme. -/ def Γ : AffineSchemeᵒᵖ ⥤ CommRing := forget_to_Scheme.op ⋙ Scheme.Γ /-- The category of affine schemes is equivalent to the category of commutative rings. -/ def equiv_CommRing : AffineScheme ≌ CommRingᵒᵖ := equiv_ess_image_of_reflective.symm instance Γ_is_equiv : is_equivalence Γ.{u} := begin haveI : is_equivalence Γ.{u}.right_op.op := is_equivalence.of_equivalence equiv_CommRing.op, exact (functor.is_equivalence_trans Γ.{u}.right_op.op (op_op_equivalence _).functor : _), end instance : has_colimits AffineScheme.{u} := begin haveI := adjunction.has_limits_of_equivalence.{u} Γ.{u}, haveI : has_colimits AffineScheme.{u} ᵒᵖᵒᵖ := has_colimits_op_of_has_limits, exactI adjunction.has_colimits_of_equivalence.{u} (op_op_equivalence AffineScheme.{u}).inverse end instance : has_limits AffineScheme.{u} := begin haveI := adjunction.has_colimits_of_equivalence Γ.{u}, haveI : has_limits AffineScheme.{u} ᵒᵖᵒᵖ := limits.has_limits_op_of_has_colimits, exactI adjunction.has_limits_of_equivalence (op_op_equivalence AffineScheme.{u}).inverse end end AffineScheme /-- An open subset of a scheme is affine if the open subscheme is affine. -/ def is_affine_open {X : Scheme} (U : opens X.carrier) : Prop := is_affine (X.restrict U.open_embedding) lemma range_is_affine_open_of_open_immersion {X Y : Scheme} [is_affine X] (f : X ⟶ Y) [H : is_open_immersion f] : is_affine_open ⟨set.range f.1.base, H.base_open.open_range⟩ := begin refine is_affine_of_iso (is_open_immersion.iso_of_range_eq f (Y.of_restrict _) _).inv, exact subtype.range_coe.symm, apply_instance end lemma top_is_affine_open (X : Scheme) [is_affine X] : is_affine_open (⊤ : opens X.carrier) := begin convert range_is_affine_open_of_open_immersion (𝟙 X), ext1, exact set.range_id.symm end instance Scheme.affine_basis_cover_is_affine (X : Scheme) (i : X.affine_basis_cover.J) : is_affine (X.affine_basis_cover.obj i) := algebraic_geometry.Spec_is_affine _ lemma is_basis_affine_open (X : Scheme) : opens.is_basis { U : opens X.carrier | is_affine_open U } := begin rw opens.is_basis_iff_nbhd, rintros U x (hU : x ∈ (U : set X.carrier)), obtain ⟨S, hS, hxS, hSU⟩ := X.affine_basis_cover_is_basis.exists_subset_of_mem_open hU U.prop, refine ⟨⟨S, X.affine_basis_cover_is_basis.is_open hS⟩, _, hxS, hSU⟩, rcases hS with ⟨i, rfl⟩, exact range_is_affine_open_of_open_immersion _, end /-- The open immersion `Spec 𝒪ₓ(U) ⟶ X` for an affine `U`. -/ def is_affine_open.from_Spec {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : Scheme.Spec.obj (op $ X.presheaf.obj $ op U) ⟶ X := begin haveI : is_affine (X.restrict U.open_embedding) := hU, have : U.open_embedding.is_open_map.functor.obj ⊤ = U, { ext1, exact set.image_univ.trans subtype.range_coe }, exact Scheme.Spec.map (X.presheaf.map (eq_to_hom this.symm).op).op ≫ (X.restrict U.open_embedding).iso_Spec.inv ≫ X.of_restrict _ end instance is_affine_open.is_open_immersion_from_Spec {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : is_open_immersion hU.from_Spec := by { delta is_affine_open.from_Spec, apply_instance } lemma is_affine_open.from_Spec_range {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : set.range hU.from_Spec.1.base = (U : set X.carrier) := begin delta is_affine_open.from_Spec, erw [← category.assoc, Scheme.comp_val_base], rw [coe_comp, set.range_comp, set.range_iff_surjective.mpr, set.image_univ], exact subtype.range_coe, rw ← Top.epi_iff_surjective, apply_instance end lemma is_affine_open.from_Spec_image_top {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : hU.is_open_immersion_from_Spec.base_open.is_open_map.functor.obj ⊤ = U := by { ext1, exact set.image_univ.trans hU.from_Spec_range } lemma is_affine_open.is_compact {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : is_compact (U : set X.carrier) := begin convert @is_compact.image _ _ _ _ set.univ hU.from_Spec.1.base prime_spectrum.compact_space.1 (by continuity), convert hU.from_Spec_range.symm, exact set.image_univ end instance Scheme.quasi_compact_of_affine (X : Scheme) [is_affine X] : compact_space X.carrier := ⟨(top_is_affine_open X).is_compact⟩ lemma is_affine_open.from_Spec_base_preimage {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : (opens.map hU.from_Spec.val.base).obj U = ⊤ := begin ext1, change hU.from_Spec.1.base ⁻¹' (U : set X.carrier) = set.univ, rw [← hU.from_Spec_range, ← set.image_univ], exact set.preimage_image_eq _ PresheafedSpace.is_open_immersion.base_open.inj end lemma Scheme.Spec_map_presheaf_map_eq_to_hom {X : Scheme} {U V : opens X.carrier} (h : U = V) (W) : (Scheme.Spec.map (X.presheaf.map (eq_to_hom h).op).op).val.c.app W = eq_to_hom (by { cases h, dsimp, induction W using opposite.rec, congr, ext1, simpa }) := begin have : Scheme.Spec.map (X.presheaf.map (𝟙 (op U))).op = 𝟙 _, { rw [X.presheaf.map_id, op_id, Scheme.Spec.map_id] }, cases h, refine (Scheme.congr_app this _).trans _, erw category.id_comp, simpa end lemma is_affine_open.Spec_Γ_identity_hom_app_from_Spec {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : (Spec_Γ_identity.hom.app (X.presheaf.obj $ op U)) ≫ hU.from_Spec.1.c.app (op U) = (Scheme.Spec.obj _).presheaf.map (eq_to_hom hU.from_Spec_base_preimage).op := begin haveI : is_affine _ := hU, have e₁ := Spec_Γ_identity.hom.naturality (X.presheaf.map (eq_to_hom U.open_embedding_obj_top).op), rw ← is_iso.comp_inv_eq at e₁, have e₂ := Γ_Spec.adjunction_unit_app_app_top (X.restrict U.open_embedding), erw ← e₂ at e₁, simp only [functor.id_map, quiver.hom.unop_op, functor.comp_map, ← functor.map_inv, ← op_inv, LocallyRingedSpace.Γ_map, category.assoc, functor.right_op_map, inv_eq_to_hom] at e₁, delta is_affine_open.from_Spec Scheme.iso_Spec, rw [Scheme.comp_val_c_app, Scheme.comp_val_c_app, ← e₁], simp_rw category.assoc, erw ← X.presheaf.map_comp_assoc, rw ← op_comp, have e₃ : U.open_embedding.is_open_map.adjunction.counit.app U ≫ eq_to_hom U.open_embedding_obj_top.symm = U.open_embedding.is_open_map.functor.map (eq_to_hom U.inclusion_map_eq_top) := subsingleton.elim _ _, have e₄ : X.presheaf.map _ ≫ _ = _ := (as_iso (Γ_Spec.adjunction.unit.app (X.restrict U.open_embedding))) .inv.1.c.naturality_assoc (eq_to_hom U.inclusion_map_eq_top).op _, erw [e₃, e₄, ← Scheme.comp_val_c_app_assoc, iso.inv_hom_id], simp only [eq_to_hom_map, eq_to_hom_op, Scheme.Spec_map_presheaf_map_eq_to_hom], erw [Scheme.Spec_map_presheaf_map_eq_to_hom, category.id_comp], simpa only [eq_to_hom_trans] end @[elementwise] lemma is_affine_open.from_Spec_app_eq {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : hU.from_Spec.1.c.app (op U) = Spec_Γ_identity.inv.app (X.presheaf.obj $ op U) ≫ (Scheme.Spec.obj _).presheaf.map (eq_to_hom hU.from_Spec_base_preimage).op := by rw [← hU.Spec_Γ_identity_hom_app_from_Spec, iso.inv_hom_id_app_assoc] lemma is_affine_open.basic_open_is_affine {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) (f : X.presheaf.obj (op U)) : is_affine_open (X.basic_open f) := begin convert range_is_affine_open_of_open_immersion (Scheme.Spec.map (CommRing.of_hom (algebra_map (X.presheaf.obj (op U)) (localization.away f))).op ≫ hU.from_Spec), ext1, have : hU.from_Spec.val.base '' (hU.from_Spec.val.base ⁻¹' (X.basic_open f : set X.carrier)) = (X.basic_open f : set X.carrier), { rw [set.image_preimage_eq_inter_range, set.inter_eq_left_iff_subset, hU.from_Spec_range], exact Scheme.basic_open_subset _ _ }, rw [subtype.coe_mk, Scheme.comp_val_base, ← this, coe_comp, set.range_comp], congr' 1, refine (congr_arg coe $ Scheme.preimage_basic_open hU.from_Spec f).trans _, refine eq.trans _ (prime_spectrum.localization_away_comap_range (localization.away f) f).symm, congr' 1, have : (opens.map hU.from_Spec.val.base).obj U = ⊤, { ext1, change hU.from_Spec.1.base ⁻¹' (U : set X.carrier) = set.univ, rw [← hU.from_Spec_range, ← set.image_univ], exact set.preimage_image_eq _ PresheafedSpace.is_open_immersion.base_open.inj }, refine eq.trans _ (basic_open_eq_of_affine f), have lm : ∀ s, (opens.map hU.from_Spec.val.base).obj U ⊓ s = s := λ s, this.symm ▸ top_inf_eq, refine eq.trans _ (lm _), refine eq.trans _ ((Scheme.Spec.obj $ op $ X.presheaf.obj $ op U).basic_open_res _ (eq_to_hom this).op), rw ← comp_apply, congr' 2, rw iso.eq_inv_comp, erw hU.Spec_Γ_identity_hom_app_from_Spec, end lemma Scheme.map_prime_spectrum_basic_open_of_affine (X : Scheme) [is_affine X] (f : Scheme.Γ.obj (op X)) : (opens.map X.iso_Spec.hom.1.base).obj (prime_spectrum.basic_open f) = X.basic_open f := begin rw ← basic_open_eq_of_affine, transitivity (opens.map X.iso_Spec.hom.1.base).obj ((Scheme.Spec.obj (op (Scheme.Γ.obj (op X)))).basic_open ((inv (X.iso_Spec.hom.1.c.app (op ((opens.map (inv X.iso_Spec.hom).val.base).obj ⊤)))) ((X.presheaf.map (eq_to_hom _)) f))), congr, { rw [← is_iso.inv_eq_inv, is_iso.inv_inv, is_iso.iso.inv_inv, nat_iso.app_hom], erw ← Γ_Spec.adjunction_unit_app_app_top, refl }, { rw eq_to_hom_map, refl }, { dsimp, congr }, { refine (Scheme.preimage_basic_open _ _).trans _, rw [is_iso.inv_hom_id_apply, Scheme.basic_open_res_eq] } end lemma is_basis_basic_open (X : Scheme) [is_affine X] : opens.is_basis (set.range (X.basic_open : X.presheaf.obj (op ⊤) → opens X.carrier)) := begin delta opens.is_basis, convert prime_spectrum.is_basis_basic_opens.inducing (Top.homeo_of_iso (Scheme.forget_to_Top.map_iso X.iso_Spec)).inducing using 1, ext, simp only [set.mem_image, exists_exists_eq_and], split, { rintro ⟨_, ⟨x, rfl⟩, rfl⟩, refine ⟨_, ⟨_, ⟨x, rfl⟩, rfl⟩, _⟩, exact congr_arg subtype.val (X.map_prime_spectrum_basic_open_of_affine x) }, { rintro ⟨_, ⟨_, ⟨x, rfl⟩, rfl⟩, rfl⟩, refine ⟨_, ⟨x, rfl⟩, _⟩, exact congr_arg subtype.val (X.map_prime_spectrum_basic_open_of_affine x).symm } end /-- The prime ideal of `𝒪ₓ(U)` corresponding to a point `x : U`. -/ noncomputable def is_affine_open.prime_ideal_of {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) (x : U) : prime_spectrum (X.presheaf.obj $ op U) := ((Scheme.Spec.map (X.presheaf.map (eq_to_hom $ show U.open_embedding.is_open_map.functor.obj ⊤ = U, from opens.ext (set.image_univ.trans subtype.range_coe)).op).op).1.base ((@@Scheme.iso_Spec (X.restrict U.open_embedding) hU).hom.1.base x)) lemma is_affine_open.from_Spec_prime_ideal_of {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) (x : U) : hU.from_Spec.val.base (hU.prime_ideal_of x) = x.1 := begin dsimp only [is_affine_open.from_Spec, subtype.coe_mk], erw [← Scheme.comp_val_base_apply, ← Scheme.comp_val_base_apply], simpa only [← functor.map_comp_assoc, ← functor.map_comp, ← op_comp, eq_to_hom_trans, op_id, eq_to_hom_refl, category_theory.functor.map_id, category.id_comp, iso.hom_inv_id_assoc] end lemma is_affine_open.is_localization_stalk_aux {X : Scheme} (U : opens X.carrier) [is_affine (X.restrict U.open_embedding)] : (inv (Γ_Spec.adjunction.unit.app (X.restrict U.open_embedding))).1.c.app (op ((opens.map U.inclusion).obj U)) = X.presheaf.map (eq_to_hom $ by rw opens.inclusion_map_eq_top : U.open_embedding.is_open_map.functor.obj ⊤ ⟶ (U.open_embedding.is_open_map.functor.obj ((opens.map U.inclusion).obj U))).op ≫ to_Spec_Γ (X.presheaf.obj $ op (U.open_embedding.is_open_map.functor.obj ⊤)) ≫ (Scheme.Spec.obj $ op $ X.presheaf.obj $ _).presheaf.map (eq_to_hom (by { rw [opens.inclusion_map_eq_top], refl }) : unop _ ⟶ ⊤).op := begin have e : (opens.map (inv (Γ_Spec.adjunction.unit.app (X.restrict U.open_embedding))).1.base).obj ((opens.map U.inclusion).obj U) = ⊤, by { rw [opens.inclusion_map_eq_top], refl }, rw [Scheme.inv_val_c_app, is_iso.comp_inv_eq, Scheme.app_eq _ e, Γ_Spec.adjunction_unit_app_app_top], simp only [category.assoc, eq_to_hom_op], erw ← functor.map_comp_assoc, rw [eq_to_hom_trans, eq_to_hom_refl, category_theory.functor.map_id, category.id_comp], erw Spec_Γ_identity.inv_hom_id_app_assoc, simp only [eq_to_hom_map, eq_to_hom_trans], end lemma is_affine_open.is_localization_stalk {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) (x : U) : is_localization.at_prime (X.presheaf.stalk x) (hU.prime_ideal_of x).as_ideal := begin haveI : is_affine _ := hU, haveI : nonempty U := ⟨x⟩, rcases x with ⟨x, hx⟩, let y := hU.prime_ideal_of ⟨x, hx⟩, have : hU.from_Spec.val.base y = x := hU.from_Spec_prime_ideal_of ⟨x, hx⟩, change is_localization y.as_ideal.prime_compl _, clear_value y, subst this, apply (is_localization.is_localization_iff_of_ring_equiv _ (as_iso $ PresheafedSpace.stalk_map hU.from_Spec.1 y).CommRing_iso_to_ring_equiv).mpr, convert structure_sheaf.is_localization.to_stalk _ _ using 1, delta structure_sheaf.stalk_algebra, congr' 1, rw ring_hom.algebra_map_to_algebra, refine (PresheafedSpace.stalk_map_germ hU.from_Spec.1 _ ⟨_, _⟩).trans _, delta is_affine_open.from_Spec Scheme.iso_Spec structure_sheaf.to_stalk, simp only [Scheme.comp_val_c_app, category.assoc], dsimp only [functor.op, as_iso_inv, unop_op], erw is_affine_open.is_localization_stalk_aux, simp only [category.assoc], conv_lhs { rw ← category.assoc }, erw [← X.presheaf.map_comp, Spec_Γ_naturality_assoc], congr' 1, simp only [← category.assoc], transitivity _ ≫ (structure_sheaf (X.presheaf.obj $ op U)).1.germ ⟨_, _⟩, { refl }, convert ((structure_sheaf (X.presheaf.obj $ op U)).1.germ_res (hom_of_le le_top) ⟨_, _⟩) using 2, rw category.assoc, erw nat_trans.naturality, rw [← LocallyRingedSpace.Γ_map_op, ← LocallyRingedSpace.Γ.map_comp_assoc, ← op_comp], erw ← Scheme.Spec.map_comp, rw [← op_comp, ← X.presheaf.map_comp], transitivity LocallyRingedSpace.Γ.map (quiver.hom.op $ Scheme.Spec.map (X.presheaf.map (𝟙 (op U))).op) ≫ _, { congr }, simp only [category_theory.functor.map_id, op_id], erw category_theory.functor.map_id, rw category.id_comp, refl end end algebraic_geometry
77890680008557c96c82d971ca2bde53eeb16e0e
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/set/prod.lean
300799e10a195250d98e33885d82d5a3779f4562
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
21,247
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Patrick Massot -/ import data.set.basic /-! # Sets in product and pi types This file defines the product of sets in `α × β` and in `Π i, α i` along with the diagonal of a type. ## Main declarations * `set.prod`: Binary product of sets. For `s : set α`, `t : set β`, we have `s.prod t : set (α × β)`. * `set.diagonal`: Diagonal of a type. `set.diagonal α = {(x, x) | x : α}`. * `set.pi`: Arbitrary product of sets. -/ open function /-- Notation class for product of subobjects (sets, submonoids, subgroups, etc). -/ class has_set_prod (α β : Type*) (γ : out_param Type*) := (prod : α → β → γ) /- This notation binds more strongly than (pre)images, unions and intersections. -/ infixr ` ×ˢ `:82 := has_set_prod.prod namespace set /-! ### Cartesian binary product of sets -/ section prod variables {α β γ δ : Type*} {s s₁ s₂ : set α} {t t₁ t₂ : set β} {a : α} {b : β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ instance : has_set_prod (set α) (set β) (set (α × β)) := ⟨λ s t, {p | p.1 ∈ s ∧ p.2 ∈ t}⟩ lemma prod_eq (s : set α) (t : set β) : s ×ˢ t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl lemma mem_prod_eq {p : α × β} : p ∈ s ×ˢ t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] lemma mem_prod {p : α × β} : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[simp] lemma prod_mk_mem_set_prod_eq : (a, b) ∈ s ×ˢ t = (a ∈ s ∧ b ∈ t) := rfl lemma mk_mem_prod (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t := ⟨ha, hb⟩ lemma prod_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ ×ˢ t₁ ⊆ s₂ ×ˢ t₂ := λ x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ @[simp] lemma prod_self_subset_prod_self : s₁ ×ˢ s₁ ⊆ s₂ ×ˢ s₂ ↔ s₁ ⊆ s₂ := ⟨λ h x hx, (h (mk_mem_prod hx hx)).1, λ h x hx, ⟨h hx.1, h hx.2⟩⟩ @[simp] lemma prod_self_ssubset_prod_self : s₁ ×ˢ s₁ ⊂ s₂ ×ˢ s₂ ↔ s₁ ⊂ s₂ := and_congr prod_self_subset_prod_self $ not_congr prod_self_subset_prod_self lemma prod_subset_iff {P : set (α × β)} : s ×ˢ t ⊆ P ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ hx _ hy, h (mk_mem_prod hx hy), λ h ⟨_, _⟩ hp, h _ hp.1 _ hp.2⟩ lemma forall_prod_set {p : α × β → Prop} : (∀ x ∈ s ×ˢ t, p x) ↔ ∀ (x ∈ s) (y ∈ t), p (x, y) := prod_subset_iff lemma exists_prod_set {p : α × β → Prop} : (∃ x ∈ s ×ˢ t, p x) ↔ ∃ (x ∈ s) (y ∈ t), p (x, y) := by simp [and_assoc] @[simp] lemma prod_empty : s ×ˢ (∅ : set β) = ∅ := by { ext, exact and_false _ } @[simp] lemma empty_prod : (∅ : set α) ×ˢ t = ∅ := by { ext, exact false_and _ } @[simp] lemma univ_prod_univ : @univ α ×ˢ @univ β = univ := by { ext, exact true_and _ } lemma univ_prod {t : set β} : (univ : set α) ×ˢ t = prod.snd ⁻¹' t := by simp [prod_eq] lemma prod_univ {s : set α} : s ×ˢ (univ : set β) = prod.fst ⁻¹' s := by simp [prod_eq] @[simp] lemma singleton_prod : ({a} : set α) ×ˢ t = prod.mk a '' t := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } @[simp] lemma prod_singleton : s ×ˢ ({b} : set β) = (λ a, (a, b)) '' s := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } lemma singleton_prod_singleton : ({a} : set α) ×ˢ ({b} : set β) = {(a, b)} :=by simp @[simp] lemma union_prod : (s₁ ∪ s₂) ×ˢ t = s₁ ×ˢ t ∪ s₂ ×ˢ t := by { ext ⟨x, y⟩, simp [or_and_distrib_right] } @[simp] lemma prod_union : s ×ˢ (t₁ ∪ t₂) = s ×ˢ t₁ ∪ s ×ˢ t₂ := by { ext ⟨x, y⟩, simp [and_or_distrib_left] } lemma prod_inter_prod : s₁ ×ˢ t₁ ∩ s₂ ×ˢ t₂ = (s₁ ∩ s₂) ×ˢ (t₁ ∩ t₂) := by { ext ⟨x, y⟩, simp [and_assoc, and.left_comm] } lemma insert_prod : insert a s ×ˢ t = (prod.mk a '' t) ∪ s ×ˢ t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } lemma prod_insert : s ×ˢ (insert b t) = ((λa, (a, b)) '' s) ∪ s ×ˢ t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } lemma prod_preimage_eq {f : γ → α} {g : δ → β} : (f ⁻¹' s) ×ˢ (g ⁻¹' t) = (λ p : γ × δ, (f p.1, g p.2)) ⁻¹' s ×ˢ t := rfl lemma prod_preimage_left {f : γ → α} : (f ⁻¹' s) ×ˢ t = (λ p : γ × β, (f p.1, p.2)) ⁻¹' s ×ˢ t := rfl lemma prod_preimage_right {g : δ → β} : s ×ˢ (g ⁻¹' t) = (λ p : α × δ, (p.1, g p.2)) ⁻¹' s ×ˢ t := rfl lemma preimage_prod_map_prod (f : α → β) (g : γ → δ) (s : set β) (t : set δ) : prod.map f g ⁻¹' s ×ˢ t = (f ⁻¹' s) ×ˢ (g ⁻¹' t) := rfl lemma mk_preimage_prod (f : γ → α) (g : γ → β) : (λ x, (f x, g x)) ⁻¹' s ×ˢ t = f ⁻¹' s ∩ g ⁻¹' t := rfl @[simp] lemma mk_preimage_prod_left (hb : b ∈ t) : (λ a, (a, b)) ⁻¹' s ×ˢ t = s := by { ext a, simp [hb] } @[simp] lemma mk_preimage_prod_right (ha : a ∈ s) : prod.mk a ⁻¹' s ×ˢ t = t := by { ext b, simp [ha] } @[simp] lemma mk_preimage_prod_left_eq_empty (hb : b ∉ t) : (λ a, (a, b)) ⁻¹' s ×ˢ t = ∅ := by { ext a, simp [hb] } @[simp] lemma mk_preimage_prod_right_eq_empty (ha : a ∉ s) : prod.mk a ⁻¹' s ×ˢ t = ∅ := by { ext b, simp [ha] } lemma mk_preimage_prod_left_eq_if [decidable_pred (∈ t)] : (λ a, (a, b)) ⁻¹' s ×ˢ t = if b ∈ t then s else ∅ := by split_ifs; simp [h] lemma mk_preimage_prod_right_eq_if [decidable_pred (∈ s)] : prod.mk a ⁻¹' s ×ˢ t = if a ∈ s then t else ∅ := by split_ifs; simp [h] lemma mk_preimage_prod_left_fn_eq_if [decidable_pred (∈ t)] (f : γ → α) : (λ a, (f a, b)) ⁻¹' s ×ˢ t = if b ∈ t then f ⁻¹' s else ∅ := by rw [← mk_preimage_prod_left_eq_if, prod_preimage_left, preimage_preimage] lemma mk_preimage_prod_right_fn_eq_if [decidable_pred (∈ s)] (g : δ → β) : (λ b, (a, g b)) ⁻¹' s ×ˢ t = if a ∈ s then g ⁻¹' t else ∅ := by rw [← mk_preimage_prod_right_eq_if, prod_preimage_right, preimage_preimage] lemma preimage_swap_prod {s : set α} {t : set β} : prod.swap ⁻¹' t ×ˢ s = s ×ˢ t := by { ext ⟨x, y⟩, simp [and_comm] } lemma image_swap_prod : prod.swap '' t ×ˢ s = s ×ˢ t := by rw [image_swap_eq_preimage_swap, preimage_swap_prod] lemma prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : (m₁ '' s) ×ˢ (m₂ '' t) = (λ p : α × β, (m₁ p.1, m₂ p.2)) '' s ×ˢ t := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] lemma prod_range_range_eq {m₁ : α → γ} {m₂ : β → δ} : (range m₁) ×ˢ (range m₂) = range (λ p : α × β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] @[simp] lemma range_prod_map {m₁ : α → γ} {m₂ : β → δ} : range (prod.map m₁ m₂) = (range m₁) ×ˢ (range m₂) := prod_range_range_eq.symm lemma prod_range_univ_eq {m₁ : α → γ} : (range m₁) ×ˢ (univ : set β) = range (λ p : α × β, (m₁ p.1, p.2)) := ext $ by simp [range] lemma prod_univ_range_eq {m₂ : β → δ} : (univ : set α) ×ˢ (range m₂) = range (λ p : α × β, (p.1, m₂ p.2)) := ext $ by simp [range] lemma range_pair_subset (f : α → β) (g : α → γ) : range (λ x, (f x, g x)) ⊆ (range f) ×ˢ (range g) := have (λ x, (f x, g x)) = prod.map f g ∘ (λ x, (x, x)), from funext (λ x, rfl), by { rw [this, ← range_prod_map], apply range_comp_subset_range } lemma nonempty.prod : s.nonempty → t.nonempty → (s ×ˢ t : set _).nonempty := λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨(x, y), ⟨hx, hy⟩⟩ lemma nonempty.fst : (s ×ˢ t : set _).nonempty → s.nonempty := λ ⟨x, hx⟩, ⟨x.1, hx.1⟩ lemma nonempty.snd : (s ×ˢ t : set _).nonempty → t.nonempty := λ ⟨x, hx⟩, ⟨x.2, hx.2⟩ lemma prod_nonempty_iff : (s ×ˢ t : set _).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, h.1.prod h.2⟩ lemma prod_eq_empty_iff : s ×ˢ t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp only [not_nonempty_iff_eq_empty.symm, prod_nonempty_iff, not_and_distrib] lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : s ×ˢ t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] lemma image_prod_mk_subset_prod_left (hb : b ∈ t) : (λ a, (a, b)) '' s ⊆ s ×ˢ t := by { rintro _ ⟨a, ha, rfl⟩, exact ⟨ha, hb⟩ } lemma image_prod_mk_subset_prod_right (ha : a ∈ s) : prod.mk a '' t ⊆ s ×ˢ t := by { rintro _ ⟨b, hb, rfl⟩, exact ⟨ha, hb⟩ } lemma prod_subset_preimage_fst (s : set α) (t : set β) : s ×ˢ t ⊆ prod.fst ⁻¹' s := inter_subset_left _ _ lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' s ×ˢ t ⊆ s := image_subset_iff.2 $ prod_subset_preimage_fst s t lemma fst_image_prod (s : set β) {t : set α} (ht : t.nonempty) : prod.fst '' s ×ˢ t = s := (fst_image_prod_subset _ _).antisymm $ λ y hy, let ⟨x, hx⟩ := ht in ⟨(y, x), ⟨hy, hx⟩, rfl⟩ lemma prod_subset_preimage_snd (s : set α) (t : set β) : s ×ˢ t ⊆ prod.snd ⁻¹' t := inter_subset_right _ _ lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' s ×ˢ t ⊆ t := image_subset_iff.2 $ prod_subset_preimage_snd s t lemma snd_image_prod {s : set α} (hs : s.nonempty) (t : set β) : prod.snd '' s ×ˢ t = t := (snd_image_prod_subset _ _).antisymm $ λ y y_in, let ⟨x, x_in⟩ := hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ lemma prod_diff_prod : s ×ˢ t \ s₁ ×ˢ t₁ = s ×ˢ (t \ t₁) ∪ (s \ s₁) ×ˢ t := by { ext x, by_cases h₁ : x.1 ∈ s₁; by_cases h₂ : x.2 ∈ t₁; simp * } /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : s ×ˢ t ⊆ s₁ ×ˢ t₁ ↔ s ⊆ s₁ ∧ t ⊆ t₁ ∨ s = ∅ ∨ t = ∅ := begin cases (s ×ˢ t : set _).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, have st : s.nonempty ∧ t.nonempty, by rwa [prod_nonempty_iff] at h, refine ⟨λ H, or.inl ⟨_, _⟩, _⟩, { have := image_subset (prod.fst : α × β → α) H, rwa [fst_image_prod _ st.2, fst_image_prod _ (h.mono H).snd] at this }, { have := image_subset (prod.snd : α × β → β) H, rwa [snd_image_prod st.1, snd_image_prod (h.mono H).fst] at this }, { intro H, simp only [st.1.ne_empty, st.2.ne_empty, or_false] at H, exact prod_mono H.1 H.2 } end lemma prod_eq_prod_iff_of_nonempty (h : (s ×ˢ t : set _).nonempty) : s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ := begin split, { intro heq, have h₁ : (s₁ ×ˢ t₁ : set _).nonempty, { rwa [← heq] }, rw [prod_nonempty_iff] at h h₁, rw [← fst_image_prod s h.2, ← fst_image_prod s₁ h₁.2, heq, eq_self_iff_true, true_and, ← snd_image_prod h.1 t, ← snd_image_prod h₁.1 t₁, heq] }, { rintro ⟨rfl, rfl⟩, refl } end lemma prod_eq_prod_iff : s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ ∨ (s = ∅ ∨ t = ∅) ∧ (s₁ = ∅ ∨ t₁ = ∅) := begin symmetry, cases eq_empty_or_nonempty (s ×ˢ t) with h h, { simp_rw [h, @eq_comm _ ∅, prod_eq_empty_iff, prod_eq_empty_iff.mp h, true_and, or_iff_right_iff_imp], rintro ⟨rfl, rfl⟩, exact prod_eq_empty_iff.mp h }, rw [prod_eq_prod_iff_of_nonempty h], rw [← ne_empty_iff_nonempty, ne.def, prod_eq_empty_iff] at h, simp_rw [h, false_and, or_false], end @[simp] lemma prod_eq_iff_eq (ht : t.nonempty) : s ×ˢ t = s₁ ×ˢ t ↔ s = s₁ := begin simp_rw [prod_eq_prod_iff, ht.ne_empty, eq_self_iff_true, and_true, or_iff_left_iff_imp, or_false], rintro ⟨rfl, rfl⟩, refl, end @[simp] lemma image_prod (f : α → β → γ) : (λ x : α × β, f x.1 x.2) '' s ×ˢ t = image2 f s t := set.ext $ λ a, ⟨ by { rintro ⟨_, _, rfl⟩, exact ⟨_, _, (mem_prod.mp ‹_›).1, (mem_prod.mp ‹_›).2, rfl⟩ }, by { rintro ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), mem_prod.mpr ⟨‹_›, ‹_›⟩, rfl⟩ }⟩ @[simp] lemma image2_mk_eq_prod : image2 prod.mk s t = s ×ˢ t := ext $ by simp section mono variables [preorder α] {f : α → set β} {g : α → set γ} theorem _root_.monotone.set_prod (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ×ˢ g x) := λ a b h, prod_mono (hf h) (hg h) theorem _root_.antitone.set_prod (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ×ˢ g x) := λ a b h, prod_mono (hf h) (hg h) theorem _root_.monotone_on.set_prod (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x ×ˢ g x) s := λ a ha b hb h, prod_mono (hf ha hb h) (hg ha hb h) theorem _root_.antitone_on.set_prod (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x ×ˢ g x) s := λ a ha b hb h, prod_mono (hf ha hb h) (hg ha hb h) end mono end prod /-! ### Diagonal -/ section diagonal variables {α : Type*} {s t : set α} /-- `diagonal α` is the set of `α × α` consisting of all pairs of the form `(a, a)`. -/ def diagonal (α : Type*) : set (α × α) := {p | p.1 = p.2} lemma mem_diagonal (x : α) : (x, x) ∈ diagonal α := by simp [diagonal] @[simp] lemma mem_diagonal_iff {x : α × α} : x ∈ diagonal α ↔ x.1 = x.2 := iff.rfl lemma preimage_coe_coe_diagonal (s : set α) : (prod.map coe coe) ⁻¹' (diagonal α) = diagonal s := by { ext ⟨⟨x, hx⟩, ⟨y, hy⟩⟩, simp [set.diagonal] } lemma diagonal_eq_range : diagonal α = range (λ x, (x, x)) := by { ext ⟨x, y⟩, simp [diagonal, eq_comm] } @[simp] lemma prod_subset_compl_diagonal_iff_disjoint : s ×ˢ t ⊆ (diagonal α)ᶜ ↔ disjoint s t := subset_compl_comm.trans $ by simp_rw [diagonal_eq_range, range_subset_iff, disjoint_left, mem_compl_iff, prod_mk_mem_set_prod_eq, not_and] end diagonal /-! ### Cartesian set-indexed product of sets -/ section pi variables {ι : Type*} {α β : ι → Type*} {s s₁ s₂ : set ι} {t t₁ t₂ : Π i, set (α i)} {i : ι} /-- Given an index set `ι` and a family of sets `t : Π i, set (α i)`, `pi s t` is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `t a` whenever `a ∈ s`. -/ def pi (s : set ι) (t : Π i, set (α i)) : set (Π i, α i) := {f | ∀ i ∈ s, f i ∈ t i} @[simp] lemma mem_pi {f : Π i, α i} : f ∈ s.pi t ↔ ∀ i ∈ s, f i ∈ t i := iff.rfl @[simp] lemma mem_univ_pi {f : Π i, α i} : f ∈ pi univ t ↔ ∀ i, f i ∈ t i := by simp @[simp] lemma empty_pi (s : Π i, set (α i)) : pi ∅ s = univ := by { ext, simp [pi] } @[simp] lemma pi_univ (s : set ι) : pi s (λ i, (univ : set (α i))) = univ := eq_univ_of_forall $ λ f i hi, mem_univ _ lemma pi_mono (h : ∀ i ∈ s, t₁ i ⊆ t₂ i) : pi s t₁ ⊆ pi s t₂ := λ x hx i hi, (h i hi $ hx i hi) lemma pi_inter_distrib : s.pi (λ i, t i ∩ t₁ i) = s.pi t ∩ s.pi t₁ := ext $ λ x, by simp only [forall_and_distrib, mem_pi, mem_inter_eq] lemma pi_congr (h : s₁ = s₂) (h' : ∀ i ∈ s₁, t₁ i = t₂ i) : s₁.pi t₁ = s₂.pi t₂ := h ▸ (ext $ λ x, forall₂_congr $ λ i hi, h' i hi ▸ iff.rfl) lemma pi_eq_empty (hs : i ∈ s) (ht : t i = ∅) : s.pi t = ∅ := by { ext f, simp only [mem_empty_eq, not_forall, iff_false, mem_pi, not_imp], exact ⟨i, hs, by simp [ht]⟩ } lemma univ_pi_eq_empty (ht : t i = ∅) : pi univ t = ∅ := pi_eq_empty (mem_univ i) ht lemma pi_nonempty_iff : (s.pi t).nonempty ↔ ∀ i, ∃ x, i ∈ s → x ∈ t i := by simp [classical.skolem, set.nonempty] lemma univ_pi_nonempty_iff : (pi univ t).nonempty ↔ ∀ i, (t i).nonempty := by simp [classical.skolem, set.nonempty] lemma pi_eq_empty_iff : s.pi t = ∅ ↔ ∃ i, is_empty (α i) ∨ i ∈ s ∧ t i = ∅ := begin rw [← not_nonempty_iff_eq_empty, pi_nonempty_iff], push_neg, refine exists_congr (λ i, ⟨λ h, (is_empty_or_nonempty (α i)).imp_right _, _⟩), { rintro ⟨x⟩, exact ⟨(h x).1, by simp [eq_empty_iff_forall_not_mem, h]⟩ }, { rintro (h | h) x, { exact h.elim' x }, { simp [h] } } end lemma univ_pi_eq_empty_iff : pi univ t = ∅ ↔ ∃ i, t i = ∅ := by simp [← not_nonempty_iff_eq_empty, univ_pi_nonempty_iff] @[simp] lemma univ_pi_empty [h : nonempty ι] : pi univ (λ i, ∅ : Π i, set (α i)) = ∅ := univ_pi_eq_empty_iff.2 $ h.elim $ λ x, ⟨x, rfl⟩ @[simp] lemma range_dcomp (f : Π i, α i → β i) : range (λ (g : Π i, α i), (λ i, f i (g i))) = pi univ (λ i, range (f i)) := begin apply subset.antisymm _ (λ x hx, _), { rintro _ ⟨x, rfl⟩ i -, exact ⟨x i, rfl⟩ }, { choose y hy using hx, exact ⟨λ i, y i trivial, funext $ λ i, hy i trivial⟩ } end @[simp] lemma insert_pi (i : ι) (s : set ι) (t : Π i, set (α i)) : pi (insert i s) t = (eval i ⁻¹' t i) ∩ pi s t := by { ext, simp [pi, or_imp_distrib, forall_and_distrib] } @[simp] lemma singleton_pi (i : ι) (t : Π i, set (α i)) : pi {i} t = (eval i ⁻¹' t i) := by { ext, simp [pi] } lemma singleton_pi' (i : ι) (t : Π i, set (α i)) : pi {i} t = {x | x i ∈ t i} := singleton_pi i t lemma univ_pi_singleton (f : Π i, α i) : pi univ (λ i, {f i}) = ({f} : set (Π i, α i)) := ext $ λ g, by simp [funext_iff] lemma pi_if {p : ι → Prop} [h : decidable_pred p] (s : set ι) (t₁ t₂ : Π i, set (α i)) : pi s (λ i, if p i then t₁ i else t₂ i) = pi {i ∈ s | p i} t₁ ∩ pi {i ∈ s | ¬ p i} t₂ := begin ext f, refine ⟨λ h, _, _⟩, { split; { rintro i ⟨his, hpi⟩, simpa [*] using h i } }, { rintro ⟨ht₁, ht₂⟩ i his, by_cases p i; simp * at * } end lemma union_pi : (s₁ ∪ s₂).pi t = s₁.pi t ∩ s₂.pi t := by simp [pi, or_imp_distrib, forall_and_distrib, set_of_and] @[simp] lemma pi_inter_compl (s : set ι) : pi s t ∩ pi sᶜ t = pi univ t := by rw [← union_pi, union_compl_self] lemma pi_update_of_not_mem [decidable_eq ι] (hi : i ∉ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = s.pi (λ j, t j (f j)) := pi_congr rfl $ λ j hj, by { rw update_noteq, exact λ h, hi (h ▸ hj) } lemma pi_update_of_mem [decidable_eq ι] (hi : i ∈ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) := calc s.pi (λ j, t j (update f i a j)) = ({i} ∪ s \ {i}).pi (λ j, t j (update f i a j)) : by rw [union_diff_self, union_eq_self_of_subset_left (singleton_subset_iff.2 hi)] ... = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) : by { rw [union_pi, singleton_pi', update_same, pi_update_of_not_mem], simp } lemma univ_pi_update [decidable_eq ι] {β : Π i, Type*} (i : ι) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : pi univ (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ pi {i}ᶜ (λ j, t j (f j)) := by rw [compl_eq_univ_diff, ← pi_update_of_mem (mem_univ _)] lemma univ_pi_update_univ [decidable_eq ι] (i : ι) (s : set (α i)) : pi univ (update (λ j : ι, (univ : set (α j))) i s) = eval i ⁻¹' s := by rw [univ_pi_update i (λ j, (univ : set (α j))) s (λ j t, t), pi_univ, inter_univ, preimage] lemma eval_image_pi_subset (hs : i ∈ s) : eval i '' s.pi t ⊆ t i := image_subset_iff.2 $ λ f hf, hf i hs lemma eval_image_univ_pi_subset : eval i '' pi univ t ⊆ t i := eval_image_pi_subset (mem_univ i) lemma eval_image_pi (hs : i ∈ s) (ht : (s.pi t).nonempty) : eval i '' s.pi t = t i := begin refine (eval_image_pi_subset hs).antisymm _, classical, obtain ⟨f, hf⟩ := ht, refine λ y hy, ⟨update f i y, λ j hj, _, update_same _ _ _⟩, obtain rfl | hji := eq_or_ne j i; simp [*, hf _ hj] end @[simp] lemma eval_image_univ_pi (ht : (pi univ t).nonempty) : (λ f : Π i, α i, f i) '' pi univ t = t i := eval_image_pi (mem_univ i) ht lemma eval_preimage [decidable_eq ι] {s : set (α i)} : eval i ⁻¹' s = pi univ (update (λ i, univ) i s) := by { ext x, simp [@forall_update_iff _ (λ i, set (α i)) _ _ _ _ (λ i' y, x i' ∈ y)] } lemma eval_preimage' [decidable_eq ι] {s : set (α i)} : eval i ⁻¹' s = pi {i} (update (λ i, univ) i s) := by { ext, simp } lemma update_preimage_pi [decidable_eq ι] {f : Π i, α i} (hi : i ∈ s) (hf : ∀ j ∈ s, j ≠ i → f j ∈ t j) : (update f i) ⁻¹' s.pi t = t i := begin ext x, refine ⟨λ h, _, λ hx j hj, _⟩, { convert h i hi, simp }, { obtain rfl | h := eq_or_ne j i, { simpa }, { rw update_noteq h, exact hf j hj h } } end lemma update_preimage_univ_pi [decidable_eq ι] {f : Π i, α i} (hf : ∀ j ≠ i, f j ∈ t j) : (update f i) ⁻¹' pi univ t = t i := update_preimage_pi (mem_univ i) (λ j _, hf j) lemma subset_pi_eval_image (s : set ι) (u : set (Π i, α i)) : u ⊆ pi s (λ i, eval i '' u) := λ f hf i hi, ⟨f, hf, rfl⟩ lemma univ_pi_ite (s : set ι) [decidable_pred (∈ s)] (t : Π i, set (α i)) : pi univ (λ i, if i ∈ s then t i else univ) = s.pi t := by { ext, simp_rw [mem_univ_pi], refine forall_congr (λ i, _), split_ifs; simp [h] } end pi end set
6979d331a3846f9a1ae06c0e92383d006ab01cf3
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/list/pairwise.lean
269d0285a379bcc3379860a4ddd9212c0a30a5b1
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,385
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.sublists /-! # Pairwise relations on a list This file provides basic results about `list.pairwise` and `list.pw_filter` (definitions are in `data.list.defs`). `pairwise r [a 0, ..., a (n - 1)]` means `∀ i j, i < j → r (a i) (a j)`. For example, `pairwise (≠) l` means that all elements of `l` are distinct, and `pairwise (<) l` means that `l` is strictly increasing. `pw_filter r l` is the list obtained by iteratively adding each element of `l` that doesn't break the pairwiseness of the list we have so far. It thus yields `l'` a maximal sublist of `l` such that `pairwise r l'`. ## Tags sorted, nodup -/ open nat function namespace list variables {α β : Type*} {R : α → α → Prop} mk_iff_of_inductive_prop list.pairwise list.pairwise_iff /-! ### Pairwise -/ theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a :: l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a :: l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.tail : ∀ {l : list α} (p : pairwise R l), pairwise R l.tail | [] h := h | (a :: l) h := pairwise_of_pairwise_cons h theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.and {S : α → α → Prop} {l : list α} : pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l := ⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩, λ ⟨hR, hS⟩, begin clear_, induction hR with a l R1 R2 IH; simp only [pairwise.nil, pairwise_cons] at *, exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ end⟩ theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop} (H : ∀ a b, R a b → S a b → T a b) {l : list α} (hR : pairwise R l) (hS : pairwise S l) : pairwise T l := (pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; [exact pairwise.nil, simp only [*, pairwise_cons, forall_2_true_iff, and_true]] theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left s.subset i) theorem forall_of_forall_of_pairwise (H : symmetric R) {l : list α} (H₁ : ∀ x ∈ l, R x x) (H₂ : pairwise R l) : ∀ (x ∈ l) (y ∈ l), R x y := begin induction l with a l IH, { exact forall_mem_nil _ }, cases forall_mem_cons.1 H₁ with H₁₁ H₁₂, cases pairwise_cons.1 H₂ with H₂₁ H₂₂, rintro x (rfl | hx) y (rfl | hy), exacts [H₁₁, H₂₁ _ hy, H (H₂₁ _ hx), IH H₁₂ H₂₂ _ hx _ hy] end lemma forall_of_pairwise (H : symmetric R) {l : list α} (hl : pairwise R l) : (∀a∈l, ∀b∈l, a ≠ b → R a b) := forall_of_forall_of_pairwise (λ a b h hne, H (h hne.symm)) (λ _ _ h, (h rfl).elim) (pairwise.imp (λ _ _ h _, h) hl) theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append], simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]] theorem pairwise_append_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a :: l₂) ↔ pairwise R (a :: (l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_append_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp only [map, pairwise.nil] | (b :: l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'], by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map] theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp only [option.mem_def], induction l with a l IH, { simp only [filter_map, pairwise.nil] }, cases e : f a with b, { rw [filter_map_cons_none _ _ e, IH, pairwise_cons], simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] }, rw [filter_map_cons_some _ _ _ e], simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'], end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_pmap {p : β → Prop} {f : Π b, p b → α} {l : list β} (h : ∀ x ∈ l, p x) : pairwise R (l.pmap f h) ↔ pairwise (λ b₁ b₂, ∀ (h₁ : p b₁) (h₂ : p b₂), R (f b₁ h₁) (f b₂ h₂)) l := begin induction l with a l ihl, { simp }, obtain ⟨ha, hl⟩ : p a ∧ ∀ b, b ∈ l → p b, by simpa using h, simp only [ihl hl, pairwise_cons, bex_imp_distrib, pmap, and.congr_left_iff, mem_pmap], refine λ _, ⟨λ H b hb hpa hpb, H _ _ hb rfl, _⟩, rintro H _ b hb rfl, exact H b hb _ _ end theorem pairwise.pmap {l : list α} (hl : pairwise R l) {p : α → Prop} {f : Π a, p a → β} (h : ∀ x ∈ l, p x) {S : β → β → Prop} (hS : ∀ ⦃x⦄ (hx : p x) ⦃y⦄ (hy : p y), R x y → S (f x hx) (f y hy)) : pairwise S (l.pmap f h) := begin refine (pairwise_pmap h).2 (pairwise.imp_of_mem _ hl), intros, apply hS, assumption end theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons], simp only [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH, pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h] lemma pairwise.set_pairwise_on {l : list α} (h : pairwise R l) (hr : symmetric R) : set.pairwise_on {x | x ∈ l} R := begin induction h with hd tl imp h IH, { simp }, { intros x hx y hy hxy, simp only [mem_cons_iff, set.mem_set_of_eq] at hx hy, rcases hx with rfl|hx; rcases hy with rfl|hy, { contradiction }, { exact imp y hy }, { exact hr (imp x hx) }, { exact IH x hx y hy hxy } } end lemma pairwise_of_reflexive_on_dupl_of_forall_ne [decidable_eq α] {l : list α} {r : α → α → Prop} (hr : ∀ a, 1 < count a l → r a a) (h : ∀ (a ∈ l) (b ∈ l), a ≠ b → r a b) : l.pairwise r := begin induction l with hd tl IH, { simp }, { rw list.pairwise_cons, split, { intros x hx, by_cases H : hd = x, { rw H, refine hr _ _, simpa [count_cons, H, nat.succ_lt_succ_iff, count_pos] using hx }, { exact h hd (mem_cons_self _ _) x (mem_cons_of_mem _ hx) H } }, { refine IH _ _, { intros x hx, refine hr _ _, rw count_cons, split_ifs, { exact hx.trans (nat.lt_succ_self _) }, { exact hx } }, { intros x hx y hy, exact h x (mem_cons_of_mem _ hx) y (mem_cons_of_mem _ hy) } } } end lemma pairwise_of_reflexive_of_forall_ne {l : list α} {r : α → α → Prop} (hr : reflexive r) (h : ∀ (a ∈ l) (b ∈ l), a ≠ b → r a b) : l.pairwise r := begin classical, refine pairwise_of_reflexive_on_dupl_of_forall_ne _ h, exact λ _ _, hr _ end theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (nat.not_lt_zero j).elim h | (a :: l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (nat.not_lt_zero _).elim h₂}, cases i with i, { exact H.1 _ (nth_le_mem l _ _) }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ pairwise.nil := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel (H₁ _ $ sl₁.subset $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this /-! ### Pairwise filtering -/ variable [decidable_rel R] @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a :: l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a :: l) = pw_filter R l := if_neg h theorem pw_filter_map (f : β → α) : Π (l : list β), pw_filter R (map f l) = map f (pw_filter (λ x y, R (f x) (f y)) l) | [] := rfl | (x :: xs) := if h : ∀ b ∈ pw_filter R (map f xs), R (f x) b then have h' : ∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ b hb, h _ (by rw [pw_filter_map]; apply mem_map_of_mem _ hb), by rw [map,pw_filter_cons_of_pos h,pw_filter_cons_of_pos h',pw_filter_map,map] else have h' : ¬∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ hh, h $ λ a ha, by { rw [pw_filter_map,mem_map] at ha, rcases ha with ⟨b,hb₀,hb₁⟩, subst a, exact hh _ hb₀, }, by rw [map,pw_filter_cons_of_neg h,pw_filter_cons_of_neg h',pw_filter_map] theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x :: l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact cons_sublist_cons _ (pw_filter_sublist l) }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := (pw_filter_sublist _).subset theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil | (x :: l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {refl}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ @[simp] theorem pw_filter_idempotent {l : list α} : pw_filter R (pw_filter R l) = pw_filter R l := pw_filter_eq_self.mpr (pairwise_pw_filter l) theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH, { exact λ _ _, false.elim }, simp only [forall_mem_cons], by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end list
27725bff282a2db439a8f958d4f6e6d9c28101ba
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Util/SCC.lean
479f44ffb16b7de87fab384992ff52d20476d604
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,170
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.HashMap namespace Lean namespace SCC /- Very simple implementation of Tarjan's SCC algorithm. Performance is not a goal here since we use this module to compiler mutually recursive definitions, where each function (and nested let-rec) in the mutual block is a vertex. So, the graphs are small. -/ open Std section variables (α : Type) [HasBeq α] [Hashable α] structure Data := (index? : Option Nat := none) (lowlink? : Option Nat := none) (onStack : Bool := false) structure State := (stack : List α := []) (nextIndex : Nat := 0) (data : Std.HashMap α Data := {}) (sccs : List (List α) := []) abbrev M := StateM (State α) end variables {α : Type} [HasBeq α] [Hashable α] private def getDataOf (a : α) : M α Data := do s ← get; match s.data.find? a with | some d => pure d | none => pure {} private def push (a : α) : M α Unit := modify fun s => { s with stack := a :: s.stack, nextIndex := s.nextIndex + 1, data := s.data.insert a { index? := s.nextIndex, lowlink? := s.nextIndex, onStack := true } } private def modifyDataOf (a : α) (f : Data → Data) : M α Unit := modify fun s => { s with data := match s.data.find? a with | none => s.data | some d => s.data.insert a (f d) } private def resetOnStack (a : α) : M α Unit := modifyDataOf a fun d => { d with onStack := false } private def updateLowLinkOf (a : α) (v : Option Nat) : M α Unit := modifyDataOf a fun d => { d with lowlink? := match d.lowlink?, v with | i, none => i | none, i => i | some i, some j => if i < j then i else j } private partial def addSCCAux (a : α) : List α → List α → M α Unit | [], newSCC => modify fun s => { s with stack := [], sccs := newSCC :: s.sccs } | b::bs, newSCC => do resetOnStack b; let newSCC := b::newSCC; if a != b then addSCCAux bs newSCC else modify fun s => { s with stack := bs, sccs := newSCC :: s.sccs } private def addSCC (a : α) : M α Unit := do s ← get; addSCCAux a s.stack [] @[specialize] private partial def sccAux (successorsOf : α → List α) : α → M α Unit | a => do push a; (successorsOf a).forM fun b => do { bData ← getDataOf b; if bData.index?.isNone then do -- `b` has not been visited yet sccAux b; bData ← getDataOf b; updateLowLinkOf a bData.lowlink? else if bData.onStack then do -- `b` is on the stack. So, it must be in the current SCC -- The edge `(a, b)` is pointing to an SCC already found and must be ignored updateLowLinkOf a bData.index? else pure () }; aData ← getDataOf a; when (aData.lowlink? == aData.index?) $ addSCC a @[specialize] def scc (vertices : List α) (successorsOf : α → List α) : List (List α) := let main : M α Unit := vertices.forM fun a => do { aData ← getDataOf a; when aData.index?.isNone do sccAux successorsOf a }; let (_, s) := main.run {}; s.sccs.reverse end SCC end Lean
6f272ae15d7a677d1fdb7632592779e22d1f21a0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/flat_parser.lean
784366aad2338213e517e9b56cc8421a48954885
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
14,561
lean
import init.lean.message init.lean.parser.syntax init.lean.parser.trie init.lean.parser.basic init.lean.parser.stringliteral import init.lean.parser.token namespace Lean namespace flatParser open String open Parser (Syntax Syntax.missing) open Parser (Trie TokenMap) abbreviation pos := String.Pos /-- A precomputed cache for quickly mapping Char offsets to positions. -/ structure FileMap := (offsets : Array Nat) (lines : Array Nat) namespace FileMap private def fromStringAux (s : String) : Nat → Nat → Nat → pos → Array Nat → Array Nat → FileMap | 0 offset line i offsets lines := ⟨offsets.push offset, lines.push line⟩ | (k+1) offset line i offsets lines := if s.atEnd i then ⟨offsets.push offset, lines.push line⟩ else let c := s.get i in let i := s.next i in let offset := offset + 1 in if c = '\n' then fromStringAux k offset (line+1) i (offsets.push offset) (lines.push (line+1)) else fromStringAux k offset line i offsets lines def fromString (s : String) : FileMap := fromStringAux s s.length 0 1 0 (Array.empty.push 0) (Array.empty.push 1) /- Remark: `offset is in [(offsets.get b), (offsets.get e)]` and `b < e` -/ private def toPositionAux (offsets : Array Nat) (lines : Array Nat) (offset : Nat) : Nat → Nat → Nat → Position | 0 b e := ⟨offset, 1⟩ -- unreachable | (k+1) b e := let offsetB := offsets.get b in if e = b + 1 then ⟨offset - offsetB, lines.get b⟩ else let m := (b + e) / 2 in let offsetM := offsets.get m in if offset = offsetM then ⟨0, lines.get m⟩ else if offset > offsetM then toPositionAux k m e else toPositionAux k b m def toPosition : FileMap → Nat → Position | ⟨offsets, lines⟩ offset := toPositionAux offsets lines offset offsets.size 0 (offsets.size-1) end FileMap structure TokenConfig := («prefix» : String) (lbp : Nat := 0) structure FrontendConfig := (filename : String) (input : String) (FileMap : FileMap) /- Remark: if we have a Node in the Trie with `some TokenConfig`, the String induced by the path is equal to the `TokenConfig.prefix`. -/ structure ParserConfig extends FrontendConfig := (tokens : Trie TokenConfig) -- Backtrackable State structure ParserState := (messages : MessageLog) structure TokenCacheEntry := (startPos stopPos : pos) (tk : Syntax) -- Non-backtrackable State structure ParserCache := (tokenCache : Option TokenCacheEntry := none) inductive Result (α : Type) | ok (a : α) (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result | error {} (msg : String) (i : pos) (cache : ParserCache) (stx : Syntax) (eps : Bool) : Result inductive Result.IsOk {α : Type} : Result α → Prop | mk (a : α) (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result.IsOk (Result.ok a i cache State eps) theorem errorIsNotOk {α : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool} (h : Result.IsOk (@Result.error α msg i cache stx eps)) : False := match h with end @[inline] def unreachableError {α β : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool} (h : Result.IsOk (@Result.error α msg i cache stx eps)) : β := False.elim (errorIsNotOk h) def resultOk := {r : Result Unit // r.IsOk} @[inline] def mkResultOk (i : pos) (cache : ParserCache) (State : ParserState) (eps := true) : resultOk := ⟨Result.ok () i cache State eps, Result.IsOk.mk _ _ _ _ _⟩ def parserCoreM (α : Type) := ParserConfig → resultOk → Result α abbreviation parserCore := parserCoreM Syntax structure recParsers := (cmdParser : parserCore) (termParser : Nat → parserCore) def parserM (α : Type) := recParsers → parserCoreM α abbreviation Parser := parserM Syntax abbreviation trailingParser := Syntax → Parser @[inline] def command.Parser : Parser := λ ps, ps.cmdParser @[inline] def Term.Parser (rbp : Nat := 0) : Parser := λ ps, ps.termParser rbp @[inline] def parserM.pure {α : Type} (a : α) : parserM α := λ _ _ r, match r with | ⟨Result.ok _ it c s _, h⟩ := Result.ok a it c s true | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline_if_reduce] def eagerOr (b₁ b₂ : Bool) := b₁ || b₂ @[inline_if_reduce] def eagerAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def parserM.bind {α β : Type} (x : parserM α) (f : α → parserM β) : parserM β := λ ps cfg r, match x ps cfg r with | Result.ok a i c s e₁ := (match f a ps cfg (mkResultOk i c s) with | Result.ok b i c s e₂ := Result.ok b i c s (eagerAnd e₁ e₂) | Result.error msg i c stx e₂ := Result.error msg i c stx (eagerAnd e₁ e₂)) | Result.error msg i c stx e := Result.error msg i c stx e instance : Monad parserM := {pure := @parserM.pure, bind := @parserM.bind} @[inline] protected def orelse {α : Type} (p q : parserM α) : parserM α := λ ps cfg r, match r with | ⟨Result.ok _ i₁ _ s₁ _, _⟩ := (match p ps cfg r with | Result.error msg₁ i₂ c₂ stx₁ true := q ps cfg (mkResultOk i₁ c₂ s₁) | other := other) | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline] protected def failure {α : Type} : parserM α := λ _ _ r, match r with | ⟨Result.ok _ i c s _, h⟩ := Result.error "failure" i c Syntax.missing true | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h instance : Alternative parserM := { orelse := @flatParser.orelse, failure := @flatParser.failure, ..flatParser.Monad } def setSilentError {α : Type} : Result α → Result α | (Result.error i c msg stx _) := Result.error i c msg stx true | other := other /-- `try p` behaves like `p`, but it pretends `p` hasn't consumed any input when `p` fails. -/ @[inline] def try {α : Type} (p : parserM α) : parserM α := λ ps cfg r, setSilentError (p ps cfg r) @[inline] def atEnd (cfg : ParserConfig) (i : pos) : Bool := cfg.input.atEnd i @[inline] def curr (cfg : ParserConfig) (i : pos) : Char := cfg.input.get i @[inline] def next (cfg : ParserConfig) (i : pos) : pos := cfg.input.next i @[inline] def inputSize (cfg : ParserConfig) : Nat := cfg.input.length @[inline] def currPos : resultOk → pos | ⟨Result.ok _ i _ _ _, _⟩ := i | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline] def currState : resultOk → ParserState | ⟨Result.ok _ _ _ s _, _⟩ := s | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h def mkError {α : Type} (r : resultOk) (msg : String) (stx : Syntax := Syntax.missing) (eps := true) : Result α := match r with | ⟨Result.ok _ i c s _, _⟩ := Result.error msg i c stx eps | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline] def satisfy (p : Char → Bool) : parserM Char := λ _ cfg r, match r with | ⟨Result.ok _ i ch st e, _⟩ := if atEnd cfg i then mkError r "end of input" else let c := curr cfg i in if p c then Result.ok c (next cfg i) ch st false else mkError r "unexpected character" | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h def any : parserM Char := satisfy (λ _, true) @[specialize] def takeUntilAux (p : Char → Bool) (cfg : ParserConfig) : Nat → resultOk → Result Unit | 0 r := r.val | (n+1) r := match r with | ⟨Result.ok _ i ch st e, _⟩ := if atEnd cfg i then r.val else let c := curr cfg i in if p c then r.val else takeUntilAux n (mkResultOk (next cfg i) ch st true) | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[specialize] def takeUntil (p : Char → Bool) : parserM Unit := λ ps cfg r, takeUntilAux p cfg (inputSize cfg) r def takeUntilNewLine : parserM Unit := takeUntil (= '\n') def whitespace : parserM Unit := takeUntil (λ c, !c.isWhitespace) -- setOption Trace.Compiler.boxed True --- setOption pp.implicit True def strAux (cfg : ParserConfig) (str : String) (error : String) : Nat → resultOk → pos → Result Unit | 0 r j := mkError r error | (n+1) r j := if str.atEnd j then r.val else match r with | ⟨Result.ok _ i ch st e, _⟩ := if atEnd cfg i then Result.error error i ch Syntax.missing true else if curr cfg i = str.get j then strAux n (mkResultOk (next cfg i) ch st true) (str.next j) else Result.error error i ch Syntax.missing true | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h -- #exit @[inline] def str (s : String) : parserM Unit := λ ps cfg r, strAux cfg s ("expected " ++ repr s) (inputSize cfg) r 0 @[specialize] def manyAux (p : parserM Unit) : Nat → Bool → parserM Unit | 0 fst := pure () | (k+1) fst := λ ps cfg r, let i₀ := currPos r in let s₀ := currState r in match p ps cfg r with | Result.ok a i c s _ := manyAux k false ps cfg (mkResultOk i c s) | Result.error _ _ c _ _ := Result.ok () i₀ c s₀ fst @[inline] def many (p : parserM Unit) : parserM Unit := λ ps cfg r, manyAux p (inputSize cfg) true ps cfg r @[inline] def many1 (p : parserM Unit) : parserM Unit := p *> many p def dummyParserCore : parserCore := λ cfg r, mkError r "dummy" def testParser {α : Type} (x : parserM α) (input : String) : String := let r := x { cmdParser := dummyParserCore, termParser := λ _, dummyParserCore } { filename := "test", input := input, FileMap := FileMap.fromString input, tokens := Lean.Parser.Trie.empty } (mkResultOk 0 {} {messages := MessageLog.empty}) in match r with | Result.ok _ i _ _ _ := "Ok at " ++ toString i | Result.error msg i _ _ _ := "Error at " ++ toString i ++ ": " ++ msg /- mutual def recCmd, recTerm (parseCmd : Parser) (parseTerm : Nat → Parser) (parseLvl : Nat → parserCore) with recCmd : Nat → parserCore | 0 cfg r := mkError r "Parser: no progress" | (n+1) cfg r := parseCmd ⟨recCmd n, parseLvl, recTerm n⟩ cfg r with recTerm : Nat → Nat → parserCore | 0 rbp cfg r := mkError r "Parser: no progress" | (n+1) rbp cfg r := parseTerm rbp ⟨recCmd n, parseLvl, recTerm n⟩ cfg r -/ /- def runParser (x : Parser) (parseCmd : Parser) (parseLvl : Nat → Parser) (parseTerm : Nat → Parser) (input : Iterator) (cfg : ParserConfig) : Result Syntax := let it := input in let n := it.remaining in let r := mkResultOk it {} {messages := MessageLog.Empty} in let pl := recLvl (parseLvl) n in let ps : recParsers := { cmdParser := recCmd parseCmd parseTerm pl n, lvlParser := pl, termParser := recTerm parseCmd parseTerm pl n } in x ps cfg r -/ structure parsingTables := (leadingTermParsers : TokenMap Parser) (trailingTermParsers : TokenMap trailingParser) abbreviation CommandParserM (α : Type) := parsingTables → parserM α end flatParser end Lean section open Lean.flatParser def flatP : parserM Unit := many1 (str "++" <|> str "**" <|> (str "--" *> takeUntil (= '\n') *> any *> pure ())) end section open Lean.Parser open Lean.Parser.MonadParsec @[reducible] def Parser (α : Type) : Type := ReaderT Lean.flatParser.recParsers (ReaderT Lean.flatParser.ParserConfig (ParsecT Syntax (StateT ParserCache Id))) α def testParsec (p : Parser Unit) (input : String) : String := let ps : Lean.flatParser.recParsers := { cmdParser := Lean.flatParser.dummyParserCore, termParser := λ _, Lean.flatParser.dummyParserCore } in let cfg : Lean.flatParser.ParserConfig := { filename := "test", input := input, FileMap := Lean.flatParser.FileMap.fromString input, tokens := Lean.Parser.Trie.empty } in let r := p ps cfg input.mkOldIterator {} in match r with | (Parsec.Result.ok _ it _, _) := "OK at " ++ toString it.offset | (Parsec.Result.error msg _, _) := "Error " ++ msg.toString @[inline] def str' (s : String) : Parser Unit := str s *> pure () def parsecP : Parser Unit := many1' (str' "++" <|> str' "**" <|> (str "--" *> takeUntil (λ c, c = '\n') *> any *> pure ())) def parsecP2 : Parser Unit := many1' ((parseStringLiteral *> whitespace *> pure ()) <|> (str "--" *> takeUntil (λ c, c = '\n') *> any *> pure ())) end namespace BasicParser open Lean.Parser open Lean.Parser.MonadParsec def testBasicParser (p : BasicParserM Unit) (input : String) : String := let cfg : Lean.Parser.ParserConfig := { filename := "test", input := input, fileMap := { lines := {} }, tokens := Lean.Parser.Trie.empty } in let r := p cfg input.mkOldIterator {} in match r with | (Parsec.Result.ok _ it _, _) := "OK at " ++ toString it.offset | (Parsec.Result.error msg _, _) := "Error " ++ msg.toString @[inline] def str' (s : String) : BasicParserM Unit := str s *> pure () def parserP : BasicParserM Unit := many1' (str' "++" <|> str' "**" <|> (str "--" *> takeUntil (λ c, c = '\n') *> any *> pure ())) def parser2 : BasicParserM Unit := many1' ((parseStringLiteral *> Lean.Parser.MonadParsec.whitespace *> pure ()) <|> (str "--" *> takeUntil (λ c, c = '\n') *> any *> pure ())) def parser3 : BasicParserM Unit := Lean.Parser.whitespace end BasicParser def mkBigString : Nat → String → String | 0 s := s | (n+1) s := mkBigString n (s ++ "-- new comment\n") def mkBigString2 : Nat → String → String | 0 s := s | (n+1) s := mkBigString2 n (s ++ "\"hello\\nworld\"\n-- comment\n") def mkBigString3 : Nat → String → String | 0 s := s | (n+1) s := mkBigString3 n (s ++ "/- /- comment 1 -/ -/ \n -- comment 2 \n \t \n ") @[noinline] def testFlatP (s : String) : IO Unit := IO.println (Lean.flatParser.testParser flatP s) @[noinline] def testParsecP (p : Parser Unit) (s : String) : IO Unit := IO.println (testParsec p s) @[noinline] def testBasicParser (p : Lean.Parser.BasicParserM Unit) (s : String) : IO Unit := IO.println (BasicParser.testBasicParser p s) @[noinline] def prof {α : Type} (msg : String) (p : IO α) : IO α := let msg₁ := "Time for '" ++ msg ++ "':" in let msg₂ := "Memory usage for '" ++ msg ++ "':" in allocprof msg₂ (timeit msg₁ p) def main (xs : List String) : IO Unit := -- let s₁ := mkBigString xs.head.toNat "" in -- let s₂ := s₁ ++ "bad" ++ mkBigString 20 "" in -- let s₃ := mkBigString2 xs.head.toNat "" in let s₄ := mkBigString3 xs.head.toNat "" in -- prof "flat Parser 1" (testFlatP s₁) *> -- prof "flat Parser 2" (testFlatP s₂) *> -- prof "Parsec 1" (testParsecP parsecP s₁) *> -- prof "Parsec 2" (testParsecP parsecP s₂) *> -- prof "Parsec 3" (testParsecP parsecP2 s₃) *> prof "Basic parser 1" (testBasicParser BasicParser.parser3 s₄)
f440822d150493421c9f9d8e9abd12a274e7d94c
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/category_theory/functor_category.lean
db0a5323bda09eb29e5cdfc177349fdb94acca3f
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
4,127
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.natural_transformation namespace category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation open nat_trans category category_theory.functor variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `functor.category C D` gives the category structure on functors and natural transformations between categories `C` and `D`. Notice that if `C` and `D` are both small categories at the same universe level, this is another small category at that level. However if `C` and `D` are both large categories at the same universe level, this is a small category at the next higher level. -/ instance functor.category : category.{(max u₁ v₂)} (C ⥤ D) := { hom := λ F G, nat_trans F G, id := λ F, nat_trans.id F, comp := λ _ _ _ α β, vcomp α β } variables {C D} {E : Type u₃} [ℰ : category.{v₃} E] variables {F G H I : C ⥤ D} namespace nat_trans @[simp] lemma vcomp_eq_comp (α : F ⟶ G) (β : G ⟶ H) : vcomp α β = α ≫ β := rfl lemma congr_app {α β : F ⟶ G} (h : α = β) (X : C) : α.app X = β.app X := by rw h @[simp] lemma id_app (F : C ⥤ D) (X : C) : (𝟙 F : F ⟶ F).app X = 𝟙 (F.obj X) := rfl @[simp] lemma comp_app {F G H : C ⥤ D} (α : F ⟶ G) (β : G ⟶ H) (X : C) : (α ≫ β).app X = α.app X ≫ β.app X := rfl include ℰ lemma app_naturality {F G : C ⥤ (D ⥤ E)} (T : F ⟶ G) (X : C) {Y Z : D} (f : Y ⟶ Z) : ((F.obj X).map f) ≫ ((T.app X).app Z) = ((T.app X).app Y) ≫ ((G.obj X).map f) := (T.app X).naturality f lemma naturality_app {F G : C ⥤ (D ⥤ E)} (T : F ⟶ G) (Z : D) {X Y : C} (f : X ⟶ Y) : ((F.map f).app Z) ≫ ((T.app Y).app Z) = ((T.app X).app Z) ≫ ((G.map f).app Z) := congr_fun (congr_arg app (T.naturality f)) Z /-- `hcomp α β` is the horizontal composition of natural transformations. -/ def hcomp {H I : D ⥤ E} (α : F ⟶ G) (β : H ⟶ I) : (F ⋙ H) ⟶ (G ⋙ I) := { app := λ X : C, (β.app (F.obj X)) ≫ (I.map (α.app X)), naturality' := begin intros, rw [functor.comp_map, functor.comp_map, assoc_symm, naturality, assoc], rw [← map_comp I, naturality, map_comp, assoc] end } infix ` ◫ `:80 := hcomp @[simp] lemma hcomp_app {H I : D ⥤ E} (α : F ⟶ G) (β : H ⟶ I) (X : C) : (α ◫ β).app X = (β.app (F.obj X)) ≫ (I.map (α.app X)) := rfl -- Note that we don't yet prove a `hcomp_assoc` lemma here: even stating it is painful, because we -- need to use associativity of functor composition. (It's true without the explicit associator, -- because functor composition is definitionally associative, but relying on the definitional equality -- causes bad problems with elaboration later.) lemma exchange {I J K : D ⥤ E} (α : F ⟶ G) (β : G ⟶ H) (γ : I ⟶ J) (δ : J ⟶ K) : (α ≫ β) ◫ (γ ≫ δ) = (α ◫ γ) ≫ (β ◫ δ) := by { ext, dsimp, rw [assoc, assoc, map_comp, assoc_symm (δ.app _), ← naturality, assoc] } end nat_trans open nat_trans namespace functor include ℰ protected def flip (F : C ⥤ (D ⥤ E)) : D ⥤ (C ⥤ E) := { obj := λ k, { obj := λ j, (F.obj j).obj k, map := λ j j' f, (F.map f).app k, map_id' := λ X, begin rw category_theory.functor.map_id, refl end, map_comp' := λ X Y Z f g, by rw [map_comp, ←comp_app] }, map := λ c c' f, { app := λ j, (F.obj j).map f } }. @[simp] lemma flip_obj_obj (F : C ⥤ (D ⥤ E)) (c) (d) : (F.flip.obj d).obj c = (F.obj c).obj d := rfl @[simp] lemma flip_obj_map (F : C ⥤ (D ⥤ E)) {c c' : C} (f : c ⟶ c') (d : D) : (F.flip.obj d).map f = (F.map f).app d := rfl @[simp] lemma flip_map_app (F : C ⥤ (D ⥤ E)) {d d' : D} (f : d ⟶ d') (c : C) : (F.flip.map f).app c = (F.obj c).map f := rfl end functor end category_theory
34d4c810c3530a379bdb463a4a206d871c98bbb8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/sym.lean
dc6196ff4984b648f66865a577b1a331faf098e9
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,850
lean
/- Copyright (c) 2020 Kyle Miller All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kyle Miller. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.basic import Mathlib.data.vector2 import Mathlib.tactic.tidy import Mathlib.PostPort universes u namespace Mathlib /-! # Symmetric powers This file defines symmetric powers of a type. The nth symmetric power consists of homogeneous n-tuples modulo permutations by the symmetric group. The special case of 2-tuples is called the symmetric square, which is addressed in more detail in `data.sym2`. TODO: This was created as supporting material for `data.sym2`; it needs a fleshed-out interface. ## Tags symmetric powers -/ /-- The nth symmetric power is n-tuples up to permutation. We define it as a subtype of `multiset` since these are well developed in the library. We also give a definition `sym.sym'` in terms of vectors, and we show these are equivalent in `sym.sym_equiv_sym'`. -/ def sym (α : Type u) (n : ℕ) := Subtype fun (s : multiset α) => coe_fn multiset.card s = n /-- This is the `list.perm` setoid lifted to `vector`. -/ def vector.perm.is_setoid (α : Type u) (n : ℕ) : setoid (vector α n) := setoid.mk (fun (a b : vector α n) => subtype.val a ~ subtype.val b) sorry namespace sym /-- This is the quotient map that takes a list of n elements as an n-tuple and produces an nth symmetric power. -/ def of_vector {α : Type u} {n : ℕ} (x : vector α n) : sym α n := { val := ↑(subtype.val x), property := sorry } protected instance has_lift {α : Type u} {n : ℕ} : has_lift (vector α n) (sym α n) := has_lift.mk of_vector /-- The unique element in `sym α 0`. -/ def nil {α : Type u} : sym α 0 := { val := 0, property := sorry } /-- Inserts an element into the term of `sym α n`, increasing the length by one. -/ def cons {α : Type u} {n : ℕ} : α → sym α n → sym α (Nat.succ n) := sorry infixr:67 " :: " => Mathlib.sym.cons @[simp] theorem cons_inj_right {α : Type u} {n : ℕ} (a : α) (s : sym α n) (s' : sym α n) : a :: s = a :: s' ↔ s = s' := sorry @[simp] theorem cons_inj_left {α : Type u} {n : ℕ} (a : α) (a' : α) (s : sym α n) : a :: s = a' :: s ↔ a = a' := sorry theorem cons_swap {α : Type u} {n : ℕ} (a : α) (b : α) (s : sym α n) : a :: b :: s = b :: a :: s := sorry /-- `α ∈ s` means that `a` appears as one of the factors in `s`. -/ def mem {α : Type u} {n : ℕ} (a : α) (s : sym α n) := a ∈ subtype.val s protected instance has_mem {α : Type u} {n : ℕ} : has_mem α (sym α n) := has_mem.mk mem protected instance decidable_mem {α : Type u} {n : ℕ} [DecidableEq α] (a : α) (s : sym α n) : Decidable (a ∈ s) := subtype.cases_on s fun (s_val : multiset α) (s_property : coe_fn multiset.card s_val = n) => id (multiset.decidable_mem a s_val) @[simp] theorem mem_cons {α : Type u} {n : ℕ} {a : α} {b : α} {s : sym α n} : a ∈ b :: s ↔ a = b ∨ a ∈ s := sorry theorem mem_cons_of_mem {α : Type u} {n : ℕ} {a : α} {b : α} {s : sym α n} (h : a ∈ s) : a ∈ b :: s := iff.mpr mem_cons (Or.inr h) @[simp] theorem mem_cons_self {α : Type u} {n : ℕ} (a : α) (s : sym α n) : a ∈ a :: s := iff.mpr mem_cons (Or.inl rfl) theorem cons_of_coe_eq {α : Type u} {n : ℕ} (a : α) (v : vector α n) : a :: ↑v = ↑(a::ᵥv) := sorry theorem sound {α : Type u} {n : ℕ} {a : vector α n} {b : vector α n} (h : subtype.val a ~ subtype.val b) : ↑a = ↑b := sorry /-- Another definition of the nth symmetric power, using vectors modulo permutations. (See `sym`.) -/ def sym' (α : Type u) (n : ℕ) := quotient (vector.perm.is_setoid α n) /-- This is `cons` but for the alternative `sym'` definition. -/ def cons' {α : Type u} {n : ℕ} : α → sym' α n → sym' α (Nat.succ n) := fun (a : α) => quotient.map (vector.cons a) sorry infixr:67 " :: " => Mathlib.sym.cons' /-- Multisets of cardinality n are equivalent to length-n vectors up to permutations. -/ def sym_equiv_sym' {α : Type u} {n : ℕ} : sym α n ≃ sym' α n := equiv.subtype_quotient_equiv_quotient_subtype (fun (l : List α) => list.length l = n) (fun (s : multiset α) => coe_fn multiset.card s = n) sorry sorry theorem cons_equiv_eq_equiv_cons (α : Type u) (n : ℕ) (a : α) (s : sym α n) : a :: coe_fn sym_equiv_sym' s = coe_fn sym_equiv_sym' (a :: s) := sorry -- Instances to make the linter happy protected instance inhabited_sym {α : Type u} [Inhabited α] (n : ℕ) : Inhabited (sym α n) := { default := { val := multiset.repeat Inhabited.default n, property := sorry } } protected instance inhabited_sym' {α : Type u} [Inhabited α] (n : ℕ) : Inhabited (sym' α n) := { default := quotient.mk' (vector.repeat Inhabited.default n) }
46bbdd23c488d59c8ff2262cd4dc6a83f7645bcc
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/monad/algebra.lean
4db185dd9cf6e605a2743249448348a1be718859
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,626
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.monad.basic import category_theory.adjunction.basic import category_theory.reflects_isomorphisms /-! # Eilenberg-Moore (co)algebras for a (co)monad This file defines Eilenberg-Moore (co)algebras for a (co)monad, and provides the category instance for them. Further it defines the adjoint pair of free and forgetful functors, respectively from and to the original category, as well as the adjoint pair of forgetful and cofree functors, respectively from and to the original category. ## References * [Riehl, *Category theory in context*, Section 5.2.4][riehl2017] -/ namespace category_theory open category universes v₁ u₁ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v₁} C] namespace monad /-- An Eilenberg-Moore algebra for a monad `T`. cf Definition 5.2.3 in [Riehl][riehl2017]. -/ structure algebra (T : monad C) : Type (max u₁ v₁) := (A : C) (a : (T : C ⥤ C).obj A ⟶ A) (unit' : T.η.app A ≫ a = 𝟙 A . obviously) (assoc' : T.μ.app A ≫ a = (T : C ⥤ C).map a ≫ a . obviously) restate_axiom algebra.unit' restate_axiom algebra.assoc' attribute [reassoc] algebra.unit algebra.assoc namespace algebra variables {T : monad C} /-- A morphism of Eilenberg–Moore algebras for the monad `T`. -/ @[ext] structure hom (A B : algebra T) := (f : A.A ⟶ B.A) (h' : T.map f ≫ B.a = A.a ≫ f . obviously) restate_axiom hom.h' attribute [simp, reassoc] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore algebra. -/ def id (A : algebra T) : hom A A := { f := 𝟙 A.A } instance (A : algebra T) : inhabited (hom A A) := ⟨{ f := 𝟙 _ }⟩ /-- Composition of Eilenberg–Moore algebra homomorphisms. -/ def comp {P Q R : algebra T} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f } end hom instance : category_struct (algebra T) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ } @[simp] lemma comp_eq_comp {A A' A'' : algebra T} (f : A ⟶ A') (g : A' ⟶ A'') : algebra.hom.comp f g = f ≫ g := rfl @[simp] lemma id_eq_id (A : algebra T) : algebra.hom.id A = 𝟙 A := rfl @[simp] lemma id_f (A : algebra T) : (𝟙 A : A ⟶ A).f = 𝟙 A.A := rfl @[simp] lemma comp_f {A A' A'' : algebra T} (f : A ⟶ A') (g : A' ⟶ A'') : (f ≫ g).f = f.f ≫ g.f := rfl /-- The category of Eilenberg-Moore algebras for a monad. cf Definition 5.2.4 in [Riehl][riehl2017]. -/ instance EilenbergMoore : category (algebra T) := {}. /-- To construct an isomorphism of algebras, it suffices to give an isomorphism of the carriers which commutes with the structure morphisms. -/ @[simps] def iso_mk {A B : algebra T} (h : A.A ≅ B.A) (w : T.map h.hom ≫ B.a = A.a ≫ h.hom) : A ≅ B := { hom := { f := h.hom }, inv := { f := h.inv, h' := by { rw [h.eq_comp_inv, category.assoc, ←w, ←functor.map_comp_assoc], simp } } } end algebra variables (T : monad C) /-- The forgetful functor from the Eilenberg-Moore category, forgetting the algebraic structure. -/ @[simps] def forget : algebra T ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } /-- The free functor from the Eilenberg-Moore category, constructing an algebra for any object. -/ @[simps] def free : C ⥤ algebra T := { obj := λ X, { A := T.obj X, a := T.μ.app X, assoc' := (T.assoc _).symm }, map := λ X Y f, { f := T.map f, h' := T.μ.naturality _ } } instance [inhabited C] : inhabited (algebra T) := ⟨(free T).obj (default C)⟩ /-- The adjunction between the free and forgetful constructions for Eilenberg-Moore algebras for a monad. cf Lemma 5.2.8 of [Riehl][riehl2017]. -/ -- The other two `simps` projection lemmas can be derived from these two, so `simp_nf` complains if -- those are added too @[simps unit counit {rhs_md := semireducible}] def adj : T.free ⊣ T.forget := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, T.η.app X ≫ f.f, inv_fun := λ f, { f := T.map f ≫ Y.a, h' := by { dsimp, simp [←Y.assoc, ←T.μ.naturality_assoc] } }, left_inv := λ f, by { ext, dsimp, simp }, right_inv := λ f, begin dsimp only [forget_obj, monad_to_functor_eq_coe], rw [←T.η.naturality_assoc, Y.unit], apply category.comp_id, end }} /-- Given an algebra morphism whose carrier part is an isomorphism, we get an algebra isomorphism. -/ lemma algebra_iso_of_iso {A B : algebra T} (f : A ⟶ B) [is_iso f.f] : is_iso f := ⟨{ f := inv f.f, h' := by { rw [is_iso.eq_comp_inv f.f, category.assoc, ← f.h], dsimp, simp } }, by tidy⟩ instance forget_reflects_iso : reflects_isomorphisms (forget T) := { reflects := λ A B, algebra_iso_of_iso T } instance forget_faithful : faithful (forget T) := {} /-- Given a monad morphism from `T₂` to `T₁`, we get a functor from the algebras of `T₁` to algebras of `T₂`. -/ @[simps] def algebra_functor_of_monad_hom {T₁ T₂ : monad C} (h : T₂ ⟶ T₁) : algebra T₁ ⥤ algebra T₂ := { obj := λ A, { A := A.A, a := h.app A.A ≫ A.a, unit' := by { dsimp, simp [A.unit] }, assoc' := by { dsimp, simp [A.assoc] } }, map := λ A₁ A₂ f, { f := f.f } } /-- The identity monad morphism induces the identity functor from the category of algebras to itself. -/ @[simps {rhs_md := semireducible}] def algebra_functor_of_monad_hom_id {T₁ : monad C} : algebra_functor_of_monad_hom (𝟙 T₁) ≅ 𝟭 _ := nat_iso.of_components (λ X, algebra.iso_mk (iso.refl _) (by { dsimp, simp, })) (λ X Y f, by { ext, dsimp, simp }) /-- A composition of monad morphisms gives the composition of corresponding functors. -/ @[simps {rhs_md := semireducible}] def algebra_functor_of_monad_hom_comp {T₁ T₂ T₃ : monad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) : algebra_functor_of_monad_hom (f ≫ g) ≅ algebra_functor_of_monad_hom g ⋙ algebra_functor_of_monad_hom f := nat_iso.of_components (λ X, algebra.iso_mk (iso.refl _) (by { dsimp, simp })) (λ X Y f, by { ext, dsimp, simp }) /-- If `f` and `g` are two equal morphisms of monads, then the functors of algebras induced by them are isomorphic. We define it like this as opposed to using `eq_to_iso` so that the components are nicer to prove lemmas about. -/ @[simps {rhs_md := semireducible}] def algebra_functor_of_monad_hom_eq {T₁ T₂ : monad C} {f g : T₁ ⟶ T₂} (h : f = g) : algebra_functor_of_monad_hom f ≅ algebra_functor_of_monad_hom g := nat_iso.of_components (λ X, algebra.iso_mk (iso.refl _) (by { dsimp, simp [h] })) (λ X Y f, by { ext, dsimp, simp }) /-- Isomorphic monads give equivalent categories of algebras. Furthermore, they are equivalent as categories over `C`, that is, we have `algebra_equiv_of_iso_monads h ⋙ forget = forget`. -/ @[simps] def algebra_equiv_of_iso_monads {T₁ T₂ : monad C} (h : T₁ ≅ T₂) : algebra T₁ ≌ algebra T₂ := { functor := algebra_functor_of_monad_hom h.inv, inverse := algebra_functor_of_monad_hom h.hom, unit_iso := algebra_functor_of_monad_hom_id.symm ≪≫ algebra_functor_of_monad_hom_eq (by simp) ≪≫ algebra_functor_of_monad_hom_comp _ _, counit_iso := (algebra_functor_of_monad_hom_comp _ _).symm ≪≫ algebra_functor_of_monad_hom_eq (by simp) ≪≫ algebra_functor_of_monad_hom_id } @[simp] lemma algebra_equiv_of_iso_monads_comp_forget {T₁ T₂ : monad C} (h : T₁ ⟶ T₂) : algebra_functor_of_monad_hom h ⋙ forget _ = forget _ := rfl end monad namespace comonad /-- An Eilenberg-Moore coalgebra for a comonad `T`. -/ @[nolint has_inhabited_instance] structure coalgebra (G : comonad C) : Type (max u₁ v₁) := (A : C) (a : A ⟶ G.obj A) (counit' : a ≫ G.ε.app A = 𝟙 A . obviously) (coassoc' : a ≫ G.δ.app A = a ≫ G.map a . obviously) restate_axiom coalgebra.counit' restate_axiom coalgebra.coassoc' attribute [reassoc] coalgebra.counit coalgebra.coassoc namespace coalgebra variables {G : comonad C} /-- A morphism of Eilenberg-Moore coalgebras for the comonad `G`. -/ @[ext, nolint has_inhabited_instance] structure hom (A B : coalgebra G) := (f : A.A ⟶ B.A) (h' : A.a ≫ G.map f = f ≫ B.a . obviously) restate_axiom hom.h' attribute [simp, reassoc] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore coalgebra. -/ def id (A : coalgebra G) : hom A A := { f := 𝟙 A.A } /-- Composition of Eilenberg–Moore coalgebra homomorphisms. -/ def comp {P Q R : coalgebra G} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f } end hom /-- The category of Eilenberg-Moore coalgebras for a comonad. -/ instance : category_struct (coalgebra G) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ } @[simp] lemma comp_eq_comp {A A' A'' : coalgebra G} (f : A ⟶ A') (g : A' ⟶ A'') : coalgebra.hom.comp f g = f ≫ g := rfl @[simp] lemma id_eq_id (A : coalgebra G) : coalgebra.hom.id A = 𝟙 A := rfl @[simp] lemma id_f (A : coalgebra G) : (𝟙 A : A ⟶ A).f = 𝟙 A.A := rfl @[simp] lemma comp_f {A A' A'' : coalgebra G} (f : A ⟶ A') (g : A' ⟶ A'') : (f ≫ g).f = f.f ≫ g.f := rfl /-- The category of Eilenberg-Moore coalgebras for a comonad. -/ instance EilenbergMoore : category (coalgebra G) := {}. /-- To construct an isomorphism of coalgebras, it suffices to give an isomorphism of the carriers which commutes with the structure morphisms. -/ @[simps] def iso_mk {A B : coalgebra G} (h : A.A ≅ B.A) (w : A.a ≫ G.map h.hom = h.hom ≫ B.a) : A ≅ B := { hom := { f := h.hom }, inv := { f := h.inv, h' := by { rw [h.eq_inv_comp, ←reassoc_of w, ←functor.map_comp], simp } } } end coalgebra variables (G : comonad C) /-- The forgetful functor from the Eilenberg-Moore category, forgetting the coalgebraic structure. -/ @[simps] def forget : coalgebra G ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } /-- Given a coalgebra morphism whose carrier part is an isomorphism, we get a coalgebra isomorphism. -/ lemma coalgebra_iso_of_iso {A B : coalgebra G} (f : A ⟶ B) [is_iso f.f] : is_iso f := ⟨{ f := inv f.f, h' := by { rw [is_iso.eq_inv_comp f.f, ←f.h_assoc], dsimp, simp } }, by tidy⟩ instance forget_reflects_iso : reflects_isomorphisms (forget G) := { reflects := λ A B, coalgebra_iso_of_iso G } /-- The cofree functor from the Eilenberg-Moore category, constructing a coalgebra for any object. -/ @[simps] def cofree : C ⥤ coalgebra G := { obj := λ X, { A := G.obj X, a := G.δ.app X, coassoc' := (G.coassoc _).symm }, map := λ X Y f, { f := G.map f, h' := (G.δ.naturality _).symm } } /-- The adjunction between the cofree and forgetful constructions for Eilenberg-Moore coalgebras for a comonad. -/ -- The other two `simps` projection lemmas can be derived from these two, so `simp_nf` complains if -- those are added too @[simps unit counit] def adj : forget G ⊣ cofree G := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, { f := X.a ≫ G.map f, h' := by { dsimp, simp [←coalgebra.coassoc_assoc] } }, inv_fun := λ g, g.f ≫ G.ε.app Y, left_inv := λ f, by { dsimp, rw [category.assoc, G.ε.naturality, functor.id_map, X.counit_assoc] }, right_inv := λ g, begin ext1, dsimp, rw [functor.map_comp, g.h_assoc, cofree_obj_a, comonad.right_counit], apply comp_id, end }} instance forget_faithful : faithful (forget G) := {} end comonad end category_theory
0b7305c63e6fc81f65dfc0069840576afe89b733
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/hash_map.lean
e074cf42b5fb1e88175c1c2e66a04e02c61d7a15
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
27,979
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import data.list.basic data.pnat.basic data.array.lemmas logic.basic algebra.group data.list.defs data.nat.basic data.option.basic data.bool data.prod import tactic.finish data.sigma.basic universes u v w /-- `bucket_array α β` is the underlying data type for `hash_map α β`, an array of linked lists of key-value pairs. -/ def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) := array n.1 (list Σ a, β a) /-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/ def hash_map.mk_idx (n : ℕ+) (i : nat) : fin n.1 := ⟨i % n.1, nat.mod_lt _ n.2⟩ namespace bucket_array section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) variables {n : ℕ+} (data : bucket_array α β n) instance : inhabited (bucket_array α β n) := ⟨mk_array _ []⟩ /-- Read the bucket corresponding to an element -/ def read (a : α) : list Σ a, β a := let bidx := hash_map.mk_idx n (hash_fn a) in data.read bidx /-- Write the bucket corresponding to an element -/ def write (a : α) (l : list Σ a, β a) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in data.write bidx l /-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/ def modify (a : α) (f : list (Σ a, β a) → list (Σ a, β a)) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in array.write data bidx (f (array.read data bidx)) /-- The list of all key-value pairs in the bucket list -/ def as_list : list Σ a, β a := data.to_list.join theorem mem_as_list {a : Σ a, β a} : a ∈ data.as_list ↔ ∃i, a ∈ array.read data i := have (∃ (l : list (Σ (a : α), β a)) (i : fin (n.val)), a ∈ l ∧ array.read data i = l) ↔ ∃ (i : fin (n.val)), a ∈ array.read data i, by rw exists_swap; exact exists_congr (λ i, by simp), by simp [as_list]; simpa [array.mem.def, and_comm] /-- Fold a function `f` over the key-value pairs in the bucket list -/ def foldl {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : δ := data.foldl d (λ b d, b.foldl (λ r a, f r a.1 a.2) d) theorem foldl_eq {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : data.foldl d f = data.as_list.foldl (λ r a, f r a.1 a.2) d := by rw [foldl, as_list, list.foldl_join, ← array.to_list_foldl] end end bucket_array namespace hash_map section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) /-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array (without checking for duplication) -/ def reinsert_aux {n} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n := data.modify hash_fn a (λl, ⟨a, b⟩ :: l) theorem mk_as_list (n : ℕ+) : bucket_array.as_list (mk_array n.1 [] : bucket_array α β n) = [] := list.eq_nil_iff_forall_not_mem.mpr $ λ x m, let ⟨i, h⟩ := (bucket_array.mem_as_list _).1 m in h parameter [decidable_eq α] /-- Search a bucket for a key `a` and return the value -/ def find_aux (a : α) : list (Σ a, β a) → option (β a) | [] := none | (⟨a',b⟩::t) := if h : a' = a then some (eq.rec_on h b) else find_aux t theorem find_aux_iff {a : α} {b : β a} : Π {l : list Σ a, β a}, (l.map sigma.fst).nodup → (find_aux a l = some b ↔ sigma.mk a b ∈ l) | [] nd := ⟨λn, by injection n, false.elim⟩ | (⟨a',b'⟩::t) nd := begin by_cases a' = a, { clear find_aux_iff, subst h, suffices : b' = b ↔ b' = b ∨ sigma.mk a' b ∈ t, {simpa [find_aux, eq_comm]}, refine (or_iff_left_of_imp (λ m, _)).symm, have : a' ∉ t.map sigma.fst, from list.not_mem_of_nodup_cons nd, exact this.elim (list.mem_map_of_mem sigma.fst m) }, { have : sigma.mk a b ≠ ⟨a', b'⟩, { intro e, injection e with e, exact h e.symm }, simp at nd, simp [find_aux, h, ne.symm h, find_aux_iff, nd] } end /-- Returns `tt` if the bucket `l` contains the key `a` -/ def contains_aux (a : α) (l : list Σ a, β a) : bool := (find_aux a l).is_some theorem contains_aux_iff {a : α} {l : list Σ a, β a} (nd : (l.map sigma.fst).nodup) : contains_aux a l ↔ a ∈ l.map sigma.fst := begin unfold contains_aux, cases h : find_aux a l with b; simp, { assume (b : β a) (m : sigma.mk a b ∈ l), rw (find_aux_iff nd).2 m at h, contradiction }, { show ∃ (b : β a), sigma.mk a b ∈ l, exact ⟨_, (find_aux_iff nd).1 h⟩ }, end /-- Modify a bucket to replace a value in the list. Leaves the list unchanged if the key is not found. -/ def replace_aux (a : α) (b : β a) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then ⟨a, b⟩::t else ⟨a', b'⟩ :: replace_aux t /-- Modify a bucket to remove a key, if it exists. -/ def erase_aux (a : α) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then t else ⟨a', b'⟩ :: erase_aux t /-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map` invariants: There are exactly `sz` elements in it, every pair is in the bucket determined by its key and the hash function, and no key appears multiple times in the list. -/ structure valid {n} (bkts : bucket_array α β n) (sz : nat) : Prop := (len : bkts.as_list.length = sz) (idx : ∀ {i} {a : Σ a, β a}, a ∈ array.read bkts i → mk_idx n (hash_fn a.1) = i) (nodup : ∀i, ((array.read bkts i).map sigma.fst).nodup) theorem valid.idx_enum {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : ∃ h, mk_idx n (hash_fn a) = ⟨i, h⟩ := (array.mem_to_list_enum.mp he).imp (λ h e, by subst e; exact v.idx hl) theorem valid.idx_enum_1 {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : (mk_idx n (hash_fn a)).1 = i := let ⟨h, e⟩ := v.idx_enum _ he hl in by rw e; refl theorem valid.as_list_nodup {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) : (bkts.as_list.map sigma.fst).nodup := begin suffices : (bkts.to_list.map (list.map sigma.fst)).pairwise list.disjoint, { simp [bucket_array.as_list, list.nodup_join, this], change ∀ l s, array.mem s bkts → list.map sigma.fst s = l → l.nodup, introv m e, subst e, cases m with i e, subst e, apply v.nodup }, rw [← list.enum_map_snd bkts.to_list, list.pairwise_map, list.pairwise_map], have : (bkts.to_list.enum.map prod.fst).nodup := by simp [list.nodup_range], refine list.pairwise.imp_of_mem _ ((list.pairwise_map _).1 this), rw prod.forall, intros i l₁, rw prod.forall, intros j l₂ me₁ me₂ ij, simp [list.disjoint], intros a b ml₁ b' ml₂, apply ij, rwa [← v.idx_enum_1 _ me₁ ml₁, ← v.idx_enum_1 _ me₂ ml₂] end theorem mk_valid (n : ℕ+) : @valid n (mk_array n.1 []) 0 := ⟨by simp [mk_as_list], λ i a h, by cases h, λ i, list.nodup_nil⟩ theorem valid.find_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {a : α} {b : β a} : find_aux a (bkts.read hash_fn a) = some b ↔ sigma.mk a b ∈ bkts.as_list := (find_aux_iff (v.nodup _)).trans $ by rw bkts.mem_as_list; exact ⟨λ h, ⟨_, h⟩, λ ⟨i, h⟩, (v.idx h).symm ▸ h⟩ theorem valid.contains_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) (a : α) : contains_aux a (bkts.read hash_fn a) ↔ a ∈ bkts.as_list.map sigma.fst := by simp [contains_aux, option.is_some_iff_exists, v.find_aux_iff hash_fn] section parameters {n : ℕ+} {bkts : bucket_array α β n} {bidx : fin n.1} {f : list (Σ a, β a) → list (Σ a, β a)} (u v1 v2 w : list Σ a, β a) local notation `L` := array.read bkts bidx private def bkts' : bucket_array α β n := array.write bkts bidx (f L) variables (hl : L = u ++ v1 ++ w) (hfl : f L = u ++ v2 ++ w) include hl hfl theorem append_of_modify : ∃ u' w', bkts.as_list = u' ++ v1 ++ w' ∧ bkts'.as_list = u' ++ v2 ++ w' := begin unfold bucket_array.as_list, have h : bidx.1 < bkts.to_list.length, {simp [bidx.2]}, refine ⟨(bkts.to_list.take bidx.1).join ++ u, w ++ (bkts.to_list.drop (bidx.1+1)).join, _, _⟩, { conv { to_lhs, rw [← list.take_append_drop bidx.1 bkts.to_list, list.drop_eq_nth_le_cons h], simp [hl] }, simp }, { conv { to_lhs, rw [bkts', array.write_to_list, list.update_nth_eq_take_cons_drop _ h], simp [hfl] }, simp } end variables (hvnd : (v2.map sigma.fst).nodup) (hal : ∀ (a : Σ a, β a), a ∈ v2 → mk_idx n (hash_fn a.1) = bidx) (djuv : (u.map sigma.fst).disjoint (v2.map sigma.fst)) (djwv : (w.map sigma.fst).disjoint (v2.map sigma.fst)) include hvnd hal djuv djwv theorem valid.modify {sz : ℕ} (v : valid bkts sz) : v1.length ≤ sz + v2.length ∧ valid bkts' (sz + v2.length - v1.length) := begin rcases append_of_modify u v1 v2 w hl hfl with ⟨u', w', e₁, e₂⟩, rw [← v.len, e₁], suffices : valid bkts' (u' ++ v2 ++ w').length, { simpa [ge, add_comm, add_left_comm, nat.le_add_right, nat.add_sub_cancel_left] }, refine ⟨congr_arg _ e₂, λ i a, _, λ i, _⟩, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.idx _ _ _ v bidx a, simp only [hl, list.mem_append, or_imp_distrib, forall_and_distrib] at this ⊢, exact ⟨⟨this.1.1, hal _⟩, this.2⟩ }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.idx } }, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.nodup _ _ _ v bidx, simp [hl, list.nodup_append] at this, simp [list.nodup_append, this, hvnd, djuv, djwv.symm] }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.nodup } } end end theorem valid.replace_aux (a : α) (b : β a) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b', l = u ++ [⟨a, b'⟩] ++ w ∧ replace_aux a b l = u ++ [⟨a, b⟩] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', suffices : ∃ (u w : list Σ a, β a) (b'' : β a), (sigma.mk a b') :: t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b (⟨a, b'⟩ :: t) = u ++ ⟨a, b⟩ :: w, {simpa}, refine ⟨[], t, b', _⟩, simp [replace_aux] }, { suffices : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), (sigma.mk a' b') :: t = u ++ ⟨a, b''⟩ :: w ∧ (sigma.mk a' b') :: (replace_aux a b t) = u ++ ⟨a, b⟩ :: w, { simpa [replace_aux, ne.symm e, e] }, intros x m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b t = u ++ ⟨a, b⟩ :: w, { simpa using valid.replace_aux t }, rcases IH x m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm, ne.symm e]⟩ } end theorem valid.replace {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (replace_aux a b)) sz := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b', hl, hfl⟩, simp [hl, list.nodup_append] at nd, refine (v.modify hash_fn u [⟨a, b'⟩] [⟨a, b⟩] w hl hfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa' e1 e2, _) (λa' e1 e2, _)).2; { revert e1, simp [-sigma.exists] at e2, subst a', simp [nd] } end theorem valid.insert {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hnc : ¬ contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (reinsert_aux bkts a b) (sz+1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), refine (v.modify hash_fn [] [] [⟨a, b⟩] (bkts.read hash_fn a) rfl rfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa', false.elim) (λa' e1 e2, _)).2, simp [-sigma.exists] at e2, subst a', exact Hnc ((contains_aux_iff nd).2 e1) end theorem valid.erase_aux (a : α) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b, l = u ++ [⟨a, b⟩] ++ w ∧ erase_aux a l = u ++ [] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', simpa [erase_aux, and_comm] using show ∃ u w (x : β a), t = u ++ w ∧ (sigma.mk a b') :: t = u ++ ⟨a, x⟩ :: w, from ⟨[], t, b', by simp⟩ }, { simp [erase_aux, e, ne.symm e], suffices : ∀ (b : β a) (_ : sigma.mk a b ∈ t), ∃ u w (x : β a), (sigma.mk a' b') :: t = u ++ ⟨a, x⟩ :: w ∧ (sigma.mk a' b') :: (erase_aux a t) = u ++ w, { simpa [replace_aux, ne.symm e, e] }, intros b m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (x : β a), t = u ++ ⟨a, x⟩ :: w ∧ erase_aux a t = u ++ w, { simpa using valid.erase_aux t }, rcases IH b m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm]⟩ } end theorem valid.erase {n} {bkts : bucket_array α β n} {sz} (a : α) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (erase_aux a)) (sz-1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.erase_aux a (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b, hl, hfl⟩, refine (v.modify hash_fn u [⟨a, b⟩] [] w hl hfl list.nodup_nil _ _ _).2; simp end end end hash_map /-- A hash map data structure, representing a finite key-value map with key type `α` and value type `β` (which may depend on `α`). -/ structure hash_map (α : Type u) [decidable_eq α] (β : α → Type v) := (hash_fn : α → nat) (size : ℕ) (nbuckets : ℕ+) (buckets : bucket_array α β nbuckets) (is_valid : hash_map.valid hash_fn buckets size) /-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/ def mk_hash_map {α : Type u} [decidable_eq α] {β : α → Type v} (hash_fn : α → nat) (nbuckets := 8) : hash_map α β := let n := if nbuckets = 0 then 8 else nbuckets in let nz : n > 0 := by abstract { cases nbuckets; simp [if_pos, nat.succ_ne_zero] } in { hash_fn := hash_fn, size := 0, nbuckets := ⟨n, nz⟩, buckets := mk_array n [], is_valid := hash_map.mk_valid _ _ } namespace hash_map variables {α : Type u} {β : α → Type v} [decidable_eq α] /-- Return the value corresponding to a key, or `none` if not found -/ def find (m : hash_map α β) (a : α) : option (β a) := find_aux a (m.buckets.read m.hash_fn a) /-- Return `tt` if the key exists in the map -/ def contains (m : hash_map α β) (a : α) : bool := (m.find a).is_some instance : has_mem α (hash_map α β) := ⟨λa m, m.contains a⟩ /-- Fold a function over the key-value pairs in the map -/ def fold {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → Π a, β a → δ) : δ := m.buckets.foldl d f /-- The list of key-value pairs in the map -/ def entries (m : hash_map α β) : list Σ a, β a := m.buckets.as_list /-- The list of keys in the map -/ def keys (m : hash_map α β) : list α := m.entries.map sigma.fst theorem find_iff (m : hash_map α β) (a : α) (b : β a) : m.find a = some b ↔ sigma.mk a b ∈ m.entries := m.is_valid.find_aux_iff _ theorem contains_iff (m : hash_map α β) (a : α) : m.contains a ↔ a ∈ m.keys := m.is_valid.contains_aux_iff _ _ theorem entries_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).entries = [] := by dsimp [entries, mk_hash_map]; rw mk_as_list theorem keys_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).keys = [] := by dsimp [keys]; rw entries_empty; refl theorem find_empty (hash_fn : α → nat) (n a) : (@mk_hash_map α _ β hash_fn n).find a = none := by induction h : (@mk_hash_map α _ β hash_fn n).find a; [refl, { have := (find_iff _ _ _).1 h, rw entries_empty at this, contradiction }] theorem not_contains_empty (hash_fn : α → nat) (n a) : ¬ (@mk_hash_map α _ β hash_fn n).contains a := by apply bool_iff_false.2; dsimp [contains]; rw [find_empty]; refl theorem insert_lemma (hash_fn : α → nat) {n n'} {bkts : bucket_array α β n} {sz} (v : valid hash_fn bkts sz) : valid hash_fn (bkts.foldl (mk_array _ [] : bucket_array α β n') (reinsert_aux hash_fn)) sz := begin suffices : ∀ (l : list Σ a, β a) (t : bucket_array α β n') sz, valid hash_fn t sz → ((l ++ t.as_list).map sigma.fst).nodup → valid hash_fn (l.foldl (λr (a : Σ a, β a), reinsert_aux hash_fn r a.1 a.2) t) (sz + l.length), { have p := this bkts.as_list _ _ (mk_valid _ _), rw [mk_as_list, list.append_nil, zero_add, v.len] at p, rw bucket_array.foldl_eq, exact p (v.as_list_nodup _) }, intro l, induction l with c l IH; intros t sz v nd, {exact v}, rw show sz + (c :: l).length = sz + 1 + l.length, by simp [add_comm], rcases (show (l.map sigma.fst).nodup ∧ ((bucket_array.as_list t).map sigma.fst).nodup ∧ c.fst ∉ l.map sigma.fst ∧ c.fst ∉ (bucket_array.as_list t).map sigma.fst ∧ (l.map sigma.fst).disjoint ((bucket_array.as_list t).map sigma.fst), by simpa [list.nodup_append, not_or_distrib, and_comm, and.left_comm] using nd) with ⟨nd1, nd2, nm1, nm2, dj⟩, have v' := v.insert _ _ c.2 (λHc, nm2 $ (v.contains_aux_iff _ c.1).1 Hc), apply IH _ _ v', suffices : ∀ ⦃a : α⦄ (b : β a), sigma.mk a b ∈ l → ∀ (b' : β a), sigma.mk a b' ∈ (reinsert_aux hash_fn t c.1 c.2).as_list → false, { simpa [list.nodup_append, nd1, v'.as_list_nodup _, list.disjoint] }, intros a b m1 b' m2, rcases (reinsert_aux hash_fn t c.1 c.2).mem_as_list.1 m2 with ⟨i, im⟩, have : sigma.mk a b' ∉ array.read t i, { intro m3, have : a ∈ list.map sigma.fst t.as_list := list.mem_map_of_mem sigma.fst (t.mem_as_list.2 ⟨_, m3⟩), exact dj (list.mem_map_of_mem sigma.fst m1) this }, by_cases h : mk_idx n' (hash_fn c.1) = i, { subst h, have e : sigma.mk a b' = ⟨c.1, c.2⟩, { simpa [reinsert_aux, bucket_array.modify, array.read_write, this] using im }, injection e with e, subst a, exact nm1.elim (@list.mem_map_of_mem _ _ sigma.fst _ _ m1) }, { apply this, simpa [reinsert_aux, bucket_array.modify, array.read_write_of_ne _ _ h] using im } end /-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/ def insert : Π (m : hash_map α β) (a : α) (b : β a), hash_map α β | ⟨hash_fn, size, n, buckets, v⟩ a b := let bkt := buckets.read hash_fn a in if hc : contains_aux a bkt then { hash_fn := hash_fn, size := size, nbuckets := n, buckets := buckets.modify hash_fn a (replace_aux a b), is_valid := v.replace _ a b hc } else let size' := size + 1, buckets' := buckets.modify hash_fn a (λl, ⟨a, b⟩::l), valid' := v.insert _ a b hc in if size' ≤ n.1 then { hash_fn := hash_fn, size := size', nbuckets := n, buckets := buckets', is_valid := valid' } else let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩, buckets'' : bucket_array α β n' := buckets'.foldl (mk_array _ []) (reinsert_aux hash_fn) in { hash_fn := hash_fn, size := size', nbuckets := n', buckets := buckets'', is_valid := insert_lemma _ valid' } theorem mem_insert : Π (m : hash_map α β) (a b a' b'), (sigma.mk a' b' : sigma β) ∈ (m.insert a b).entries ↔ if a = a' then b == b' else sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a b a' b' := begin let bkt := bkts.read hash_fn a, have nd : (bkt.map sigma.fst).nodup := v.nodup (mk_idx n (hash_fn a)), have lem : Π (bkts' : bucket_array α β n) (v1 u w) (hl : bucket_array.as_list bkts = u ++ v1 ++ w) (hfl : bucket_array.as_list bkts' = u ++ [⟨a, b⟩] ++ w) (veq : (v1 = [] ∧ ¬ contains_aux a bkt) ∨ ∃b'', v1 = [⟨a, b''⟩]), sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list, { intros bkts' v1 u w hl hfl veq, rw [hl, hfl], by_cases h : a = a', { subst a', suffices : b = b' ∨ sigma.mk a b' ∈ u ∨ sigma.mk a b' ∈ w ↔ b = b', { simpa [eq_comm, or.left_comm] }, refine or_iff_left_of_imp (not.elim $ not_or_distrib.2 _), rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩, { have na := (not_iff_not_of_iff $ v.contains_aux_iff _ _).1 Hnc, simp [hl, not_or_distrib] at na, simp [na] }, { have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] } }, { suffices : sigma.mk a' b' ∉ v1, {simp [h, ne.symm h, this]}, rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩; simp [ne.symm h] } }, by_cases Hc : (contains_aux a bkt : Prop), { rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u', w', b'', hl', hfl'⟩, rcases (append_of_modify u' [⟨a, b''⟩] [⟨a, b⟩] w' hl' hfl') with ⟨u, w, hl, hfl⟩, simpa [insert, @dif_pos (contains_aux a bkt) _ Hc] using lem _ _ u w hl hfl (or.inr ⟨b'', rfl⟩) }, { let size' := size + 1, let bkts' := bkts.modify hash_fn a (λl, ⟨a, b⟩::l), have mi : sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list := let ⟨u, w, hl, hfl⟩ := append_of_modify [] [] [⟨a, b⟩] _ rfl rfl in lem bkts' _ u w hl hfl $ or.inl ⟨rfl, Hc⟩, simp [insert, @dif_neg (contains_aux a bkt) _ Hc], by_cases h : size' ≤ n.1, -- TODO(Mario): Why does the by_cases assumption look different than the stated one? { simpa [show size' ≤ n.1, from h] using mi }, { let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩, let bkts'' : bucket_array α β n' := bkts'.foldl (mk_array _ []) (reinsert_aux hash_fn), suffices : sigma.mk a' b' ∈ bkts''.as_list ↔ sigma.mk a' b' ∈ bkts'.as_list.reverse, { simpa [show ¬ size' ≤ n.1, from h, mi] }, rw [show bkts'' = bkts'.as_list.foldl _ _, from bkts'.foldl_eq _ _, ← list.foldr_reverse], induction bkts'.as_list.reverse with a l IH, { simp [mk_as_list] }, { cases a with a'' b'', let B := l.foldr (λ (y : sigma β) (x : bucket_array α β n'), reinsert_aux hash_fn x y.1 y.2) (mk_array n'.1 []), rcases append_of_modify [] [] [⟨a'', b''⟩] _ rfl rfl with ⟨u, w, hl, hfl⟩, simp [IH.symm, or.left_comm, show B.as_list = _, from hl, show (reinsert_aux hash_fn B a'' b'').as_list = _, from hfl] } } } end theorem find_insert_eq (m : hash_map α β) (a : α) (b : β a) : (m.insert a b).find a = some b := (find_iff (m.insert a b) a b).2 $ (mem_insert m a b a b).2 $ by rw if_pos rfl theorem find_insert_ne (m : hash_map α β) (a a' : α) (b : β a) (h : a ≠ a') : (m.insert a b).find a' = m.find a' := option.eq_of_eq_some $ λb', let t := mem_insert m a b a' b' in (find_iff _ _ _).trans $ iff.trans (by rwa if_neg h at t) (find_iff _ _ _).symm theorem find_insert (m : hash_map α β) (a' a : α) (b : β a) : (m.insert a b).find a' = if h : a = a' then some (eq.rec_on h b) else m.find a' := if h : a = a' then by rw dif_pos h; exact match a', h with ._, rfl := find_insert_eq m a b end else by rw dif_neg h; exact find_insert_ne m a a' b h /-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/ def insert_all (l : list (Σ a, β a)) (m : hash_map α β) : hash_map α β := l.foldl (λ m ⟨a, b⟩, insert m a b) m /-- Construct a hash map from a list of key-value pairs. -/ def of_list (l : list (Σ a, β a)) (hash_fn) : hash_map α β := insert_all l (mk_hash_map hash_fn (2 * l.length)) /-- Remove a key from the map. (Modifies `m` in-place when applicable) -/ def erase (m : hash_map α β) (a : α) : hash_map α β := match m with ⟨hash_fn, size, n, buckets, v⟩ := if hc : contains_aux a (buckets.read hash_fn a) then { hash_fn := hash_fn, size := size - 1, nbuckets := n, buckets := buckets.modify hash_fn a (erase_aux a), is_valid := v.erase _ a hc } else m end theorem mem_erase : Π (m : hash_map α β) (a a' b'), (sigma.mk a' b' : sigma β) ∈ (m.erase a).entries ↔ a ≠ a' ∧ sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a a' b' := begin let bkt := bkts.read hash_fn a, by_cases Hc : (contains_aux a bkt : Prop), { let bkts' := bkts.modify hash_fn a (erase_aux a), suffices : sigma.mk a' b' ∈ bkts'.as_list ↔ a ≠ a' ∧ sigma.mk a' b' ∈ bkts.as_list, { simpa [erase, @dif_pos (contains_aux a bkt) _ Hc] }, have nd := v.nodup (mk_idx n (hash_fn a)), rcases valid.erase_aux a bkt ((contains_aux_iff nd).1 Hc) with ⟨u', w', b, hl', hfl'⟩, rcases append_of_modify u' [⟨a, b⟩] [] _ hl' hfl' with ⟨u, w, hl, hfl⟩, suffices : ∀_:sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w, a ≠ a', { have : sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w ↔ (¬a = a' ∧ a' = a) ∧ b' == b ∨ ¬a = a' ∧ (sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w), { simp [eq_comm, not_and_self_iff, and_iff_right_of_imp this] }, simpa [hl, show bkts'.as_list = _, from hfl, and_or_distrib_left, and_comm, and.left_comm, or.left_comm] }, intros m e, subst a', revert m, apply not_or_distrib.2, have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] }, { suffices : ∀_:sigma.mk a' b' ∈ bucket_array.as_list bkts, a ≠ a', { simp [erase, @dif_neg (contains_aux a bkt) _ Hc, entries, and_iff_right_of_imp this] }, intros m e, subst a', exact Hc ((v.contains_aux_iff _ _).2 (list.mem_map_of_mem sigma.fst m)) } end theorem find_erase_eq (m : hash_map α β) (a : α) : (m.erase a).find a = none := begin cases h : (m.erase a).find a with b, {refl}, exact absurd rfl ((mem_erase m a a b).1 ((find_iff (m.erase a) a b).1 h)).left end theorem find_erase_ne (m : hash_map α β) (a a' : α) (h : a ≠ a') : (m.erase a).find a' = m.find a' := option.eq_of_eq_some $ λb', (find_iff _ _ _).trans $ (mem_erase m a a' b').trans $ (and_iff_right h).trans (find_iff _ _ _).symm theorem find_erase (m : hash_map α β) (a' a : α) : (m.erase a).find a' = if a = a' then none else m.find a' := if h : a = a' then by subst a'; simp [find_erase_eq m a] else by rw if_neg h; exact find_erase_ne m a a' h section string variables [has_to_string α] [∀ a, has_to_string (β a)] open prod private def key_data_to_string (a : α) (b : β a) (first : bool) : string := (if first then "" else ", ") ++ sformat!"{a} ← {b}" private def to_string (m : hash_map α β) : string := "⟨" ++ (fst (fold m ("", tt) (λ p a b, (fst p ++ key_data_to_string a b (snd p), ff)))) ++ "⟩" instance : has_to_string (hash_map α β) := ⟨to_string⟩ end string section format open format prod variables [has_to_format α] [∀ a, has_to_format (β a)] private meta def format_key_data (a : α) (b : β a) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b private meta def to_format (m : hash_map α β) : format := group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ p a b, (fst p ++ format_key_data a b (snd p), ff)))) ++ to_fmt "⟩" meta instance : has_to_format (hash_map α β) := ⟨to_format⟩ end format end hash_map
1bf190b69a020f1181caab6ee395883099f934c8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/pfunctor/univariate/basic.lean
c5b73352f0b7ed40b60c9b2bc187cd7459a3f693
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,324
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 data.W.basic /-! # Polynomial functors This file defines polynomial functors and the W-type construction as a polynomial functor. (For the M-type construction, see pfunctor/M.lean.) -/ universe u /-- A polynomial functor `P` is given by a type `A` and a family `B` of types over `A`. `P` maps any type `α` to a new type `P.obj α`, which is defined as the sigma type `Σ x, P.B x → α`. An element of `P.obj α` is a pair `⟨a, f⟩`, where `a` is an element of a type `A` and `f : B a → α`. Think of `a` as the shape of the object and `f` as an index to the relevant elements of `α`. -/ structure pfunctor := (A : Type u) (B : A → Type u) namespace pfunctor instance : inhabited pfunctor := ⟨⟨default _, default _⟩⟩ variables (P : pfunctor) {α β : Type u} /-- Applying `P` to an object of `Type` -/ def obj (α : Type*) := Σ x : P.A, P.B x → α /-- Applying `P` to a morphism of `Type` -/ def map {α β : Type*} (f : α → β) : P.obj α → P.obj β := λ ⟨a, g⟩, ⟨a, f ∘ g⟩ instance obj.inhabited [inhabited P.A] [inhabited α] : inhabited (P.obj α) := ⟨ ⟨ default _, λ _, default _ ⟩ ⟩ instance : functor P.obj := {map := @map P} protected theorem map_eq {α β : Type*} (f : α → β) (a : P.A) (g : P.B a → α) : @functor.map P.obj _ _ _ f ⟨a, g⟩ = ⟨a, f ∘ g⟩ := rfl protected theorem id_map {α : Type*} : ∀ x : P.obj α, id <$> x = id x := λ ⟨a, b⟩, rfl protected theorem comp_map {α β γ : Type*} (f : α → β) (g : β → γ) : ∀ x : P.obj α, (g ∘ f) <$> x = g <$> (f <$> x) := λ ⟨a, b⟩, rfl instance : is_lawful_functor P.obj := {id_map := @pfunctor.id_map P, comp_map := @pfunctor.comp_map P} /-- re-export existing definition of W-types and adapt it to a packaged definition of polynomial functor -/ def W := _root_.W_type P.B /- inhabitants of W types is awkward to encode as an instance assumption because there needs to be a value `a : P.A` such that `P.B a` is empty to yield a finite tree -/ attribute [nolint has_inhabited_instance] W variables {P} /-- root element of a W tree -/ def W.head : W P → P.A | ⟨a, f⟩ := a /-- children of the root of a W tree -/ def W.children : Π x : W P, P.B (W.head x) → W P | ⟨a, f⟩ := f /-- destructor for W-types -/ def W.dest : W P → P.obj (W P) | ⟨a, f⟩ := ⟨a, f⟩ /-- constructor for W-types -/ def W.mk : P.obj (W P) → W P | ⟨a, f⟩ := ⟨a, f⟩ @[simp] theorem W.dest_mk (p : P.obj (W P)) : W.dest (W.mk p) = p := by cases p; reflexivity @[simp] theorem W.mk_dest (p : W P) : W.mk (W.dest p) = p := by cases p; reflexivity variables (P) /-- `Idx` identifies a location inside the application of a pfunctor. For `F : pfunctor`, `x : F.obj α` and `i : F.Idx`, `i` can designate one part of `x` or is invalid, if `i.1 ≠ x.1` -/ def Idx := Σ x : P.A, P.B x instance Idx.inhabited [inhabited P.A] [inhabited (P.B (default _))] : inhabited P.Idx := ⟨ ⟨default _, default _⟩ ⟩ variables {P} /-- `x.iget i` takes the component of `x` designated by `i` if any is or returns a default value -/ def obj.iget [decidable_eq P.A] {α} [inhabited α] (x : P.obj α) (i : P.Idx) : α := if h : i.1 = x.1 then x.2 (cast (congr_arg _ h) i.2) else default _ @[simp] lemma fst_map {α β : Type u} (x : P.obj α) (f : α → β) : (f <$> x).1 = x.1 := by { cases x; refl } @[simp] lemma iget_map [decidable_eq P.A] {α β : Type u} [inhabited α] [inhabited β] (x : P.obj α) (f : α → β) (i : P.Idx) (h : i.1 = x.1) : (f <$> x).iget i = f (x.iget i) := by { simp only [obj.iget, fst_map, *, dif_pos, eq_self_iff_true], cases x, refl } end pfunctor /- Composition of polynomial functors. -/ namespace pfunctor /-- functor composition for polynomial functors -/ def comp (P₂ P₁ : pfunctor.{u}) : pfunctor.{u} := ⟨ Σ a₂ : P₂.1, P₂.2 a₂ → P₁.1, λ a₂a₁, Σ u : P₂.2 a₂a₁.1, P₁.2 (a₂a₁.2 u) ⟩ /-- constructor for composition -/ def comp.mk (P₂ P₁ : pfunctor.{u}) {α : Type} (x : P₂.obj (P₁.obj α)) : (comp P₂ P₁).obj α := ⟨ ⟨ x.1, sigma.fst ∘ x.2 ⟩, λ a₂a₁, (x.2 a₂a₁.1).2 a₂a₁.2 ⟩ /-- destructor for composition -/ def comp.get (P₂ P₁ : pfunctor.{u}) {α : Type} (x : (comp P₂ P₁).obj α) : P₂.obj (P₁.obj α) := ⟨ x.1.1, λ a₂, ⟨x.1.2 a₂, λ a₁, x.2 ⟨a₂,a₁⟩ ⟩ ⟩ end pfunctor /- Lifting predicates and relations. -/ namespace pfunctor variables {P : pfunctor.{u}} open functor theorem liftp_iff {α : Type u} (p : α → Prop) (x : P.obj α) : liftp p x ↔ ∃ a f, x = ⟨a, f⟩ ∧ ∀ i, p (f i) := begin split, { rintros ⟨y, hy⟩, cases h : y with a f, refine ⟨a, λ i, (f i).val, _, λ i, (f i).property⟩, rw [←hy, h, pfunctor.map_eq] }, rintros ⟨a, f, xeq, pf⟩, use ⟨a, λ i, ⟨f i, pf i⟩⟩, rw [xeq], reflexivity end theorem liftp_iff' {α : Type u} (p : α → Prop) (a : P.A) (f : P.B a → α) : @liftp.{u} P.obj _ α p ⟨a,f⟩ ↔ ∀ i, p (f i) := begin simp only [liftp_iff, sigma.mk.inj_iff]; split; intro, { casesm* [Exists _, _ ∧ _], subst_vars, assumption }, repeat { constructor <|> assumption } end theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : P.obj α) : liftr r x y ↔ ∃ a f₀ f₁, x = ⟨a, f₀⟩ ∧ y = ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) := begin split, { rintros ⟨u, xeq, yeq⟩, cases h : u with a f, use [a, λ i, (f i).val.fst, λ i, (f i).val.snd], split, { rw [←xeq, h], refl }, split, { rw [←yeq, h], refl }, intro i, exact (f i).property }, rintros ⟨a, f₀, f₁, xeq, yeq, h⟩, use ⟨a, λ i, ⟨(f₀ i, f₁ i), h i⟩⟩, split, { rw [xeq], refl }, rw [yeq], refl end open set theorem supp_eq {α : Type u} (a : P.A) (f : P.B a → α) : @supp.{u} P.obj _ α (⟨a,f⟩ : P.obj α) = f '' univ := begin ext, simp only [supp, image_univ, mem_range, mem_set_of_eq], split; intro h, { apply @h (λ x, ∃ (y : P.B a), f y = x), rw liftp_iff', intro, refine ⟨_,rfl⟩ }, { simp only [liftp_iff'], cases h, subst x, tauto } end end pfunctor
ecb1f9854690fdef7787ddeee53994f8cb19ac4f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/cases_ginductive.lean
e1ad2d68c4ffb7f11be78126bfd3a68340c4392c
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
4,433
lean
inductive term | const (c : string) : term | app (fn : string) (ts : list term) : term mutual inductive is_rename, is_rename_lst with is_rename : term → string → string → term → Prop | const_eq (c₁ c₂) : is_rename (term.const c₁) c₁ c₂ (term.const c₂) | const_ne (c₁ c₂ c₃) (hne : c₁ ≠ c₂) : is_rename (term.const c₁) c₂ c₃ (term.const c₁) | app (fn c₁ c₂ ts₁ ts₂) (h₁ : is_rename_lst ts₁ c₁ c₂ ts₂) : is_rename (term.app fn ts₁) c₁ c₂ (term.app fn ts₂) with is_rename_lst : list term → string → string → list term → Prop | nil (c₁ c₂) : is_rename_lst [] c₁ c₂ [] | cons (t₁ ts₁ t₂ ts₂ c₁ c₂) (h₁ : is_rename t₁ c₁ c₂ t₂) (h₂ : is_rename_lst ts₁ c₁ c₂ ts₂) : is_rename_lst (t₁::ts₁) c₁ c₂ (t₂::ts₂) mutual def term.ind, term_list.ind (p : term → Prop) (ps : list term → Prop) (h₁ : ∀ c, p (term.const c)) (h₂ : ∀ fn ts, ps ts → p (term.app fn ts)) (h₃ : ps []) (h₄ : ∀ t ts, p t → ps ts → ps (t::ts)) with term.ind : ∀ t : term, p t | (term.const c) := h₁ c | (term.app fn ts) := h₂ fn ts (term_list.ind ts) with term_list.ind : ∀ ts : list term, ps ts | [] := h₃ | (t::ts) := h₄ t ts (term.ind t) (term_list.ind ts) lemma term.ind_on (p : term → Prop) (ps : list term → Prop) (t : term) (h₁ : ∀ c, p (term.const c)) (h₂ : ∀ fn ts, ps ts → p (term.app fn ts)) (h₃ : ps []) (h₄ : ∀ t ts, p t → ps ts → ps (t::ts)) : p t := term.ind p ps h₁ h₂ h₃ h₄ t lemma is_rename_det : ∀ t₁ t₂ t₂' c₁ c₂, is_rename t₁ c₁ c₂ t₂ → is_rename t₁ c₁ c₂ t₂' → t₂ = t₂' := begin intro t₁, apply term.ind_on (λ t₁ : term, ∀ t₂ t₂' c₁ c₂, is_rename t₁ c₁ c₂ t₂ → is_rename t₁ c₁ c₂ t₂' → t₂ = t₂') (λ ts₁ : list term, ∀ ts₂ ts₂' c₁ c₂, is_rename_lst ts₁ c₁ c₂ ts₂ → is_rename_lst ts₁ c₁ c₂ ts₂' → ts₂ = ts₂') t₁, { intros c₁ t₂ t₂' c₁' c₂ h₁ h₂, cases h₁; cases h₂; trace_state; { refl <|> contradiction } }, { intros fn ts ih t₂ t₂' c₁ c₂ h₁ h₂, cases h₁; cases h₂, trace_state, have := ih _ _ _ _ h₁_h₁ h₂_h₁, simp [*] }, { intros ts₂ ts₂' c₁ c₂ h₁ h₂, cases h₁; cases h₂; refl }, { intros t ts ih₁ ih₂ ts₂ ts₂' c₁ c₂ h₁ h₂, cases h₁; cases h₂, have := ih₁ _ _ _ _ h₁_h₁ h₂_h₁, have := ih₂ _ _ _ _ h₁_h₂ h₂_h₂, simp [*] } end mutual def is_rename.ind, is_rename_lst.ind (p : ∀ {t₁ c₁ c₂ t₂}, is_rename t₁ c₁ c₂ t₂ → Prop) (ps : ∀ {ts₁ c₁ c₂ ts₂}, is_rename_lst ts₁ c₁ c₂ ts₂ → Prop) (h₁ : ∀ (c₁ c₂ : string), p (is_rename.const_eq c₁ c₂)) (h₂ : ∀ (c₁ c₂ c₃ : string) (hne : c₁ ≠ c₂), p (is_rename.const_ne c₁ c₂ c₃ hne)) (h₃ : ∀ (fn c₁ c₂ ts₁ ts₂ h) (ih : ps h), p (is_rename.app fn c₁ c₂ ts₁ ts₂ h)) (h₄ : ∀ (c₁ c₂ : string), ps (is_rename_lst.nil c₁ c₂)) (h₅ : ∀ (t₁ ts₁ t₂ ts₂ c₁ c₂ h₁ h₂) (ih₁ : p h₁) (ih₂ : ps h₂), ps (is_rename_lst.cons t₁ ts₁ t₂ ts₂ c₁ c₂ h₁ h₂)) with is_rename.ind : ∀ (t₁ c₁ c₂ t₂) (h : is_rename t₁ c₁ c₂ t₂), p h | (term.const c) := begin intros c₁ c₂ t₂ hr, cases t₂; cases hr, { apply h₁ }, { apply h₂, assumption } end | (term.app fn ts₁) := have ih : ∀ (c₁ c₂ ts₂) (h : is_rename_lst ts₁ c₁ c₂ ts₂), ps h, from is_rename_lst.ind ts₁, begin intros c₁ c₂ t₂ hr, cases t₂; cases hr, apply h₃, apply ih, assumption end with is_rename_lst.ind : ∀ (ts₁ c₁ c₂ ts₂) (h : is_rename_lst ts₁ c₁ c₂ ts₂), ps h | [] := begin intros c₁ c₂ ts₂ hr, cases ts₂; cases hr, apply h₄ end | (t₁::ts₁) := have ih₁ : ∀ (c₁ c₂ t₂) (h : is_rename t₁ c₁ c₂ t₂), p h, from is_rename.ind t₁, have ih₂ : ∀ (c₁ c₂ ts₂) (h : is_rename_lst ts₁ c₁ c₂ ts₂), ps h, from is_rename_lst.ind ts₁, begin intros c₁ c₂ ts₂ hr, cases ts₂; cases hr, fapply h₅, exact hr_h₁, exact hr_h₂, exact ih₁ _ _ _ hr_h₁, exact ih₂ _ _ _ hr_h₂ end
7a5b1beb52df45d27395c1ead00d67b3be248554
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/polynomial/field_division.lean
05678aa8f573faea2df6b007746cde0f91eb0678
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
20,909
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.derivative import data.polynomial.ring_division import ring_theory.euclidean_domain /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical big_operators polynomial namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ} section is_domain variables [comm_ring R] [is_domain R] lemma roots_C_mul (p : R[X]) {a : R} (hzero : a ≠ 0) : (C a * p).roots = p.roots := begin by_cases hpzero : p = 0, { simp only [hpzero, mul_zero] }, rw multiset.ext, intro b, have prodzero : C a * p ≠ 0, { simp only [hpzero, or_false, ne.def, mul_eq_zero, C_eq_zero, hzero, not_false_iff] }, rw [count_roots, count_roots, root_multiplicity_mul prodzero], have mulzero : root_multiplicity b (C a) = 0, { simp only [hzero, root_multiplicity_eq_zero, eval_C, is_root.def, not_false_iff] }, simp only [mulzero, zero_add] end lemma derivative_root_multiplicity_of_root [char_zero R] {p : R[X]} {t : R} (hpt : p.is_root t) : p.derivative.root_multiplicity t = p.root_multiplicity t - 1 := begin rcases eq_or_ne p 0 with rfl | hp, { simp }, nth_rewrite 0 [←p.div_by_monic_mul_pow_root_multiplicity_eq t], simp only [derivative_pow, derivative_mul, derivative_sub, derivative_X, derivative_C, sub_zero, mul_one], set n := p.root_multiplicity t - 1, have hn : n + 1 = _ := tsub_add_cancel_of_le ((root_multiplicity_pos hp).mpr hpt), rw ←hn, set q := p /ₘ (X - C t) ^ (n + 1) with hq, convert_to root_multiplicity t ((X - C t) ^ n * (derivative q * (X - C t) + q * ↑(n + 1))) = n, { congr, rw [mul_add, mul_left_comm $ (X - C t) ^ n, ←pow_succ'], congr' 1, rw [mul_left_comm $ (X - C t) ^ n, mul_comm $ (X - C t) ^ n] }, have h : (derivative q * (X - C t) + q * ↑(n + 1)).eval t ≠ 0, { suffices : eval t q * ↑(n + 1) ≠ 0, { simpa }, refine mul_ne_zero _ (nat.cast_ne_zero.mpr n.succ_ne_zero), convert eval_div_by_monic_pow_root_multiplicity_ne_zero t hp, exact hn ▸ hq }, rw [root_multiplicity_mul, root_multiplicity_X_sub_C_pow, root_multiplicity_eq_zero h, add_zero], refine mul_ne_zero (pow_ne_zero n $ X_sub_C_ne_zero t) _, contrapose! h, rw [h, eval_zero] end lemma root_multiplicity_sub_one_le_derivative_root_multiplicity [char_zero R] (p : R[X]) (t : R) : p.root_multiplicity t - 1 ≤ p.derivative.root_multiplicity t := begin by_cases p.is_root t, { exact (derivative_root_multiplicity_of_root h).symm.le }, { rw [root_multiplicity_eq_zero h, zero_tsub], exact zero_le _ } end section normalization_monoid variables [normalization_monoid R] instance : normalization_monoid R[X] := { norm_unit := λ p, ⟨C ↑(norm_unit (p.leading_coeff)), C ↑(norm_unit (p.leading_coeff))⁻¹, by rw [← ring_hom.map_mul, units.mul_inv, C_1], by rw [← ring_hom.map_mul, units.inv_mul, C_1]⟩, norm_unit_zero := units.ext (by simp), norm_unit_mul := λ p q hp0 hq0, units.ext (begin dsimp, rw [ne.def, ← leading_coeff_eq_zero] at *, rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul], end), norm_unit_coe_units := λ u, units.ext begin rw [← mul_one u⁻¹, units.coe_mul, units.eq_inv_mul_iff_mul_eq], dsimp, rcases polynomial.is_unit_iff.1 ⟨u, rfl⟩ with ⟨_, ⟨w, rfl⟩, h2⟩, rw [← h2, leading_coeff_C, norm_unit_coe_units, ← C_mul, units.mul_inv, C_1], end } @[simp] lemma coe_norm_unit {p : R[X]} : (norm_unit p : R[X]) = C ↑(norm_unit p.leading_coeff) := by simp [norm_unit] lemma leading_coeff_normalize (p : R[X]) : leading_coeff (normalize p) = normalize (leading_coeff p) := by simp lemma monic.normalize_eq_self {p : R[X]} (hp : p.monic) : normalize p = p := by simp only [polynomial.coe_norm_unit, normalize_apply, hp.leading_coeff, norm_unit_one, units.coe_one, polynomial.C.map_one, mul_one] lemma roots_normalize {p : R[X]} : (normalize p).roots = p.roots := by rw [normalize_apply, mul_comm, coe_norm_unit, roots_C_mul _ (norm_unit (leading_coeff p)).ne_zero] end normalization_monoid end is_domain section division_ring variables [division_ring R] {p q : R[X]} lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, begin rw [eq_C_of_degree_le_zero h] at hp0 hp, exact hp (is_unit.map C (is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))), end) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : R[X]) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul, degree_C h₁, add_zero] @[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R →+* S) : p.map f = 0 ↔ p = 0 := by simp only [polynomial.ext_iff, f.map_eq_zero, coeff_map, coeff_zero] lemma map_ne_zero [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : p.map f ≠ 0 := mt (map_eq_zero f).1 hp end division_ring section field variables [field R] {p q : R[X]} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ theorem irreducible_of_monic {p : R[X]} (hp1 : p.monic) (hp2 : p ≠ 1) : irreducible p ↔ (∀ f g : R[X], f.monic → g.monic → f * g = p → f = 1 ∨ g = 1) := ⟨λ hp3 f g hf hg hfg, or.cases_on (hp3.is_unit_or_is_unit hfg.symm) (assume huf : is_unit f, or.inl $ eq_one_of_is_unit_of_monic hf huf) (assume hug : is_unit g, or.inr $ eq_one_of_is_unit_of_monic hg hug), λ hp3, ⟨mt (eq_one_of_is_unit_of_monic hp1) hp2, λ f g hp, have hf : f ≠ 0, from λ hf, by { rw [hp, hf, zero_mul] at hp1, exact not_monic_zero hp1 }, have hg : g ≠ 0, from λ hg, by { rw [hp, hg, mul_zero] at hp1, exact not_monic_zero hp1 }, or.imp (λ hf, is_unit_of_mul_eq_one _ _ hf) (λ hg, is_unit_of_mul_eq_one _ _ hg) $ hp3 (f * C f.leading_coeff⁻¹) (g * C g.leading_coeff⁻¹) (monic_mul_leading_coeff_inv hf) (monic_mul_leading_coeff_inv hg) $ by rw [mul_assoc, mul_left_comm _ g, ← mul_assoc, ← C_mul, ← mul_inv, ← leading_coeff_mul, ← hp, monic.def.1 hp1, inv_one, C_1, mul_one]⟩⟩ /-- Division of polynomials. See `polynomial.div_by_monic` for more details.-/ def div (p q : R[X]) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) /-- Remainder of polynomial division. See `polynomial.mod_by_monic` for more details. -/ def mod (p q : R[X]) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : R[X]) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : R[X]) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) instance : has_div R[X] := ⟨div⟩ instance : has_mod R[X] := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : R[X]) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : R[X]) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : R[X]) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain R[X] := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nontrivial } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv_rhs { rw [← euclidean_domain.div_add_mod p q, degree_add_eq_left_of_degree_lt this, degree_mul] } lemma degree_div_le (p q : R[X]) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [division_ring k] (p : R[X]) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective f.injective @[simp] lemma nat_degree_map [division_ring k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [division_ring k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp only [← coeff_nat_degree, coeff_map f, nat_degree_map] theorem monic_map_iff [division_ring k] {f : R →+* k} {p : R[X]} : (p.map f).monic ↔ p.monic := by rw [monic, leading_coeff_map, ← f.map_one, function.injective.eq_iff f.injective, monic] theorem is_unit_map [field k] (f : R →+* k) : is_unit (p.map f) ↔ is_unit p := by simp_rw [is_unit_iff_degree_eq_zero, degree_map] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, polynomial.map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [f.map_inv, coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← f.map_inv, ← map_C f, ← polynomial.map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] section open euclidean_domain theorem gcd_map [field k] (f : R →+* k) : gcd (p.map f) (q.map f) = (gcd p q).map f := gcd.induction p q (λ x, by simp_rw [polynomial.map_zero, euclidean_domain.gcd_zero_left]) $ λ x y hx ih, by rw [gcd_val, ← map_mod, ih, ← gcd_val] end lemma eval₂_gcd_eq_zero [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} (hf : f.eval₂ ϕ α = 0) (hg : g.eval₂ ϕ α = 0) : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 := by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.eval₂_add, polynomial.eval₂_mul, polynomial.eval₂_mul, hf, hg, zero_mul, zero_mul, zero_add] lemma eval_gcd_eq_zero {f g : R[X]} {α : R} (hf : f.eval α = 0) (hg : g.eval α = 0) : (euclidean_domain.gcd f g).eval α = 0 := eval₂_gcd_eq_zero hf hg lemma root_left_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : f.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_left f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_right_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : g.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_right f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_gcd_iff_root_left_right [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 ↔ (f.eval₂ ϕ α = 0) ∧ (g.eval₂ ϕ α = 0) := ⟨λ h, ⟨root_left_of_root_gcd h, root_right_of_root_gcd h⟩, λ h, eval₂_gcd_eq_zero h.1 h.2⟩ lemma is_root_gcd_iff_is_root_left_right {f g : R[X]} {α : R} : (euclidean_domain.gcd f g).is_root α ↔ f.is_root α ∧ g.is_root α := root_gcd_iff_root_left_right theorem is_coprime_map [field k] (f : R →+* k) : is_coprime (p.map f) (q.map f) ↔ is_coprime p q := by rw [← euclidean_domain.gcd_is_unit_iff, ← euclidean_domain.gcd_is_unit_iff, gcd_map, is_unit_map] lemma mem_roots_map [field k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ (p.map f).roots ↔ p.eval₂ f x = 0 := begin rw mem_roots (show p.map f ≠ 0, by exact map_ne_zero hp), dsimp only [is_root], rw polynomial.eval_map, end lemma mem_root_set [field k] [algebra R k] {x : k} (hp : p ≠ 0) : x ∈ p.root_set k ↔ aeval x p = 0 := iff.trans multiset.mem_to_finset (mem_roots_map hp) lemma root_set_C_mul_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (C a * X ^ n).root_set S = {0} := begin ext x, rw [set.mem_singleton_iff, mem_root_set, aeval_mul, aeval_C, aeval_X_pow, mul_eq_zero], { simp_rw [ring_hom.map_eq_zero, pow_eq_zero_iff (nat.pos_of_ne_zero hn), or_iff_right_iff_imp], exact λ ha', (ha ha').elim }, { exact mul_ne_zero (mt C_eq_zero.mp ha) (pow_ne_zero n X_ne_zero) }, end lemma root_set_monomial {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (monomial n a).root_set S = {0} := by rw [←C_mul_X_pow_eq_monomial, root_set_C_mul_X_pow hn ha] lemma root_set_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) : (X ^ n : R[X]).root_set S = {0} := by { rw [←one_mul (X ^ n : R[X]), ←C_1, root_set_C_mul_X_pow hn], exact one_ne_zero } lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_rfl)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : R[X]ˣ) (n : ℕ) : ((↑u : R[X]).coeff n)⁻¹ = ((↑u⁻¹ : R[X]).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := begin rw [ne.def, ← leading_coeff_eq_zero, ← ne.def, ← is_unit_iff_ne_zero] at hp0, rw [monic, leading_coeff_normalize, normalize_eq_one], apply hp0, end lemma leading_coeff_div (hpq : q.degree ≤ p.degree) : (p / q).leading_coeff = p.leading_coeff / q.leading_coeff := begin by_cases hq : q = 0, { simp [hq] }, rw [div_def, leading_coeff_mul, leading_coeff_C, leading_coeff_div_by_monic_of_monic (monic_mul_leading_coeff_inv hq) _, mul_comm, div_eq_mul_inv], rwa [degree_mul_leading_coeff_inv q hq] end lemma div_C_mul : p / (C a * q) = C a⁻¹ * (p / q) := begin by_cases ha : a = 0, { simp [ha] }, simp only [div_def, leading_coeff_mul, mul_inv, leading_coeff_C, C.map_mul, mul_assoc], congr' 3, rw [mul_left_comm q, ← mul_assoc, ← C.map_mul, mul_inv_cancel ha, C.map_one, one_mul] end lemma C_mul_dvd (ha : a ≠ 0) : C a * p ∣ q ↔ p ∣ q := ⟨λ h, dvd_trans (dvd_mul_left _ _) h, λ ⟨r, hr⟩, ⟨C a⁻¹ * r, by rw [mul_assoc, mul_left_comm p, ← mul_assoc, ← C.map_mul, _root_.mul_inv_cancel ha, C.map_one, one_mul, hr]⟩⟩ lemma dvd_C_mul (ha : a ≠ 0) : p ∣ polynomial.C a * q ↔ p ∣ q := ⟨λ ⟨r, hr⟩, ⟨C a⁻¹ * r, by rw [mul_left_comm p, ← hr, ← mul_assoc, ← C.map_mul, _root_.inv_mul_cancel ha, C.map_one, one_mul]⟩, λ h, dvd_trans h (dvd_mul_left _ _)⟩ lemma coe_norm_unit_of_ne_zero (hp : p ≠ 0) : (norm_unit p : R[X]) = C p.leading_coeff⁻¹ := have p.leading_coeff ≠ 0 := mt leading_coeff_eq_zero.mp hp, by simp [comm_group_with_zero.coe_norm_unit _ this] lemma normalize_monic (h : monic p) : normalize p = p := by simp [h] theorem map_dvd_map' [field k] (f : R →+* k) {x y : R[X]} : x.map f ∣ y.map f ↔ x ∣ y := if H : x = 0 then by rw [H, polynomial.map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero] else by rw [← normalize_dvd_iff, ← @normalize_dvd_iff R[X], normalize_apply, normalize_apply, coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H), leading_coeff_map, ← f.map_inv, ← map_C, ← polynomial.map_mul, map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)] lemma degree_normalize : degree (normalize p) = degree p := by simp lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from monic.prime_of_degree_eq_one (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), (normalize_associated _).prime this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := (prime_of_degree_eq_one hp1).irreducible theorem not_irreducible_C (x : R) : ¬irreducible (C x) := if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero } else λ hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree := lt_of_not_ge $ λ hp0, have _ := eq_C_of_degree_le_zero hp0, not_irreducible_C (p.coeff 0) $ this ▸ hp /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : K[X]) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : K[X]) (f /ₘ (X - C a)) := begin refine or.resolve_left (euclidean_domain.dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end end field end polynomial
e6edf0d32a00b14e56ca67f35f395689ffc72132
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/int_gcd.lean
2a43a90ce27a22c3c1819d02aedeb8526708e7d6
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
2,128
lean
import data.int.basic data.nat.gcd namespace int lemma dvd_mod_iff {k m n : ℤ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m := let t := @dvd_add_iff_left _ _ _ (m % n) _ (dvd_trans h (dvd_mul_right n (m / n))) in by rwa mod_add_div at t @[simp] lemma gcd_zero_left (a : ℤ) : gcd 0 a = a.nat_abs := nat.gcd_zero_left _ @[simp] lemma gcd_zero_right (a : ℤ) : gcd a 0 = a.nat_abs := nat.gcd_zero_right _ @[simp] lemma gcd_one_left (a : ℤ) : gcd 1 a = 1 := nat.gcd_one_left _ @[simp] lemma gcd_one_right (a : ℤ) : gcd a 1 = 1 := nat.gcd_one_right _ lemma gcd_comm (a b : ℤ) : gcd a b = gcd b a := nat.gcd_comm _ _ lemma gcd_mul_left (a b c : ℤ) : gcd (a * b) (a * c) = a.nat_abs * gcd b c := by unfold gcd; rw [nat_abs_mul, nat_abs_mul, nat.gcd_mul_left] lemma gcd_mul_right (a b c : ℤ) : gcd (b * a) (c * a) = gcd b c * a.nat_abs := by rw [mul_comm b, mul_comm c, gcd_mul_left, mul_comm (gcd b c)] lemma gcd_pos_of_ne_zero_left {a : ℤ} (b : ℤ) (hb : b ≠ 0) : 0 < gcd a b := by unfold gcd; exact nat.gcd_pos_of_pos_right _ (nat_abs_pos_of_ne_zero hb) @[simp] lemma gcd_neg (a b : ℤ) : gcd (-a) b = gcd a b := by unfold gcd; rw nat_abs_neg @[simp] lemma gcd_neg' (a b : ℤ) : gcd a (-b) = gcd a b := by unfold gcd; rw nat_abs_neg lemma gcd_dvd_left (a b : ℤ) : (gcd a b : ℤ) ∣ a := dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left _ _ lemma gcd_dvd_right (a b : ℤ) : (gcd a b : ℤ) ∣ b := dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_right _ _ lemma dvd_gcd {a b c : ℤ} (hb : a ∣ b) (hc : a ∣ c) : a ∣ gcd b c := nat_abs_dvd.1 $ int.coe_nat_dvd.2 (begin rw [← nat_abs_dvd, ← dvd_nat_abs, int.coe_nat_dvd] at hb hc, exact nat.dvd_gcd hb hc end) lemma gcd_mod (a b : ℤ) : gcd (b % a) a = gcd a b:= nat.dvd_antisymm (int.coe_nat_dvd.1 (dvd_gcd (gcd_dvd_right (b % a) a) ((dvd_mod_iff (gcd_dvd_right (b % a) a)).1 (gcd_dvd_left (b % a) a)))) (int.coe_nat_dvd.1 (dvd_gcd ((dvd_mod_iff (gcd_dvd_left a b)).2 (gcd_dvd_right a b)) (gcd_dvd_left a b))) lemma gcd_assoc (a b c : ℤ) : gcd (gcd a b) c = gcd a (gcd b c) := nat.gcd_assoc _ _ _ end int
3ecfabd99550d589b346810eeb8171b21939c89d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/as.lean
5191a132db33267f4a8165ba8135a12c1a1ec1ed
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
445
lean
namespace foo definition id {A : Type} (a : A) := a definition pr1 {A : Type} (a b : A) := a end foo open foo as bla (hiding pr1) #check bla.id open foo as bla (renaming pr1→pr) #check bla.pr #print raw bla.id open foo as boo (pr1) #check boo.pr1 open foo as boooo (renaming pr1→pr) (hiding id) #check boooo.pr namespace foo namespace bla definition pr2 {A : Type} (a b : A) := b end bla end foo open foo.bla as bb #check bb.pr2
2594d502a464326d017e97c400a2f0df82d8a95f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/constructions/binary_products.lean
ec481c48145971a0051453f471248f0ce3863c8b
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,638
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.terminal import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.binary_products /-! # Constructing binary product from pullbacks and terminal object. If a category has pullbacks and a terminal object, then it has binary products. TODO: provide the dual result. -/ universes v u open category_theory category_theory.category category_theory.limits /-- Any category with pullbacks and terminal object has binary products. -/ -- This is not an instance, as it is not always how one wants to construct binary products! lemma has_binary_products_of_terminal_and_pullbacks (C : Type u) [𝒞 : category.{v} C] [has_terminal C] [has_pullbacks C] : has_binary_products C := { has_limit := λ F, has_limit.mk { cone := { X := pullback (terminal.from (F.obj walking_pair.left)) (terminal.from (F.obj walking_pair.right)), π := discrete.nat_trans (λ x, walking_pair.cases_on x pullback.fst pullback.snd)}, is_limit := { lift := λ c, pullback.lift ((c.π).app walking_pair.left) ((c.π).app walking_pair.right) (subsingleton.elim _ _), fac' := λ s c, walking_pair.cases_on c (limit.lift_π _ _) (limit.lift_π _ _), uniq' := λ s m J, begin rw [←J, ←J], ext; rw limit.lift_π; refl end } } }
a5e61bc1469be1856dd8b6c21af23437b191f111
d0c6b2ba2af981e9ab0a98f6e169262caad4b9b9
/src/Std/Data/PersistentArray.lean
b6420c5dd47737a73fffdbcec7bb8edc56d494dd
[ "Apache-2.0" ]
permissive
fizruk/lean4
953b7dcd76e78c17a0743a2c1a918394ab64bbc0
545ed50f83c570f772ade4edbe7d38a078cbd761
refs/heads/master
1,677,655,987,815
1,612,393,885,000
1,612,393,885,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,730
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ universes u v w namespace Std inductive PersistentArrayNode (α : Type u) where | node (cs : Array (PersistentArrayNode α)) : PersistentArrayNode α | leaf (vs : Array α) : PersistentArrayNode α deriving Inhabited namespace PersistentArrayNode def isNode {α} : PersistentArrayNode α → Bool | node _ => true | leaf _ => false end PersistentArrayNode abbrev PersistentArray.initShift : USize := 5 abbrev PersistentArray.branching : USize := USize.ofNat (2 ^ PersistentArray.initShift.toNat) structure PersistentArray (α : Type u) where /- Recall that we run out of memory if we have more than `usizeSz/8` elements. So, we can stop adding elements at `root` after `size > usizeSz`, and keep growing the `tail`. This modification allow us to use `USize` instead of `Nat` when traversing `root`. -/ root : PersistentArrayNode α := PersistentArrayNode.node (Array.mkEmpty PersistentArray.branching.toNat) tail : Array α := Array.mkEmpty PersistentArray.branching.toNat size : Nat := 0 shift : USize := PersistentArray.initShift tailOff : Nat := 0 deriving Inhabited abbrev PArray (α : Type u) := PersistentArray α namespace PersistentArray /- TODO: use proofs for showing that array accesses are not out of bounds. We can do it after we reimplement the tactic framework. -/ variable {α : Type u} open Std.PersistentArrayNode def empty : PersistentArray α := {} def isEmpty (a : PersistentArray α) : Bool := a.size == 0 def mkEmptyArray : Array α := Array.mkEmpty branching.toNat abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) partial def getAux [Inhabited α] : PersistentArrayNode α → USize → USize → α | node cs, i, shift => getAux (cs.get! (div2Shift i shift).toNat) (mod2Shift i shift) (shift - initShift) | leaf cs, i, _ => cs.get! i.toNat def get! [Inhabited α] (t : PersistentArray α) (i : Nat) : α := if i >= t.tailOff then t.tail.get! (i - t.tailOff) else getAux t.root (USize.ofNat i) t.shift def getOp [Inhabited α] (self : PersistentArray α) (idx : Nat) : α := self.get! idx partial def setAux : PersistentArrayNode α → USize → USize → α → PersistentArrayNode α | node cs, i, shift, a => let j := div2Shift i shift let i := mod2Shift i shift let shift := shift - initShift node $ cs.modify j.toNat $ fun c => setAux c i shift a | leaf cs, i, _, a => leaf (cs.set! i.toNat a) def set (t : PersistentArray α) (i : Nat) (a : α) : PersistentArray α := if i >= t.tailOff then { t with tail := t.tail.set! (i - t.tailOff) a } else { t with root := setAux t.root (USize.ofNat i) t.shift a } @[specialize] partial def modifyAux [Inhabited α] (f : α → α) : PersistentArrayNode α → USize → USize → PersistentArrayNode α | node cs, i, shift => let j := div2Shift i shift let i := mod2Shift i shift let shift := shift - initShift node $ cs.modify j.toNat $ fun c => modifyAux f c i shift | leaf cs, i, _ => leaf (cs.modify i.toNat f) @[specialize] def modify [Inhabited α] (t : PersistentArray α) (i : Nat) (f : α → α) : PersistentArray α := if i >= t.tailOff then { t with tail := t.tail.modify (i - t.tailOff) f } else { t with root := modifyAux f t.root (USize.ofNat i) t.shift } partial def mkNewPath (shift : USize) (a : Array α) : PersistentArrayNode α := if shift == 0 then leaf a else node (mkEmptyArray.push (mkNewPath (shift - initShift) a)) partial def insertNewLeaf : PersistentArrayNode α → USize → USize → Array α → PersistentArrayNode α | node cs, i, shift, a => if i < branching then node (cs.push (leaf a)) else let j := div2Shift i shift let i := mod2Shift i shift let shift := shift - initShift if j.toNat < cs.size then node $ cs.modify j.toNat fun c => insertNewLeaf c i shift a else node $ cs.push $ mkNewPath shift a | n, _, _, _ => n -- unreachable def mkNewTail (t : PersistentArray α) : PersistentArray α := if t.size <= (mul2Shift 1 (t.shift + initShift)).toNat then { t with tail := mkEmptyArray, root := insertNewLeaf t.root (USize.ofNat (t.size - 1)) t.shift t.tail, tailOff := t.size } else { t with tail := #[], root := let n := mkEmptyArray.push t.root; node (n.push (mkNewPath t.shift t.tail)), shift := t.shift + initShift, tailOff := t.size } def tooBig : Nat := USize.size / 8 def push (t : PersistentArray α) (a : α) : PersistentArray α := let r := { t with tail := t.tail.push a, size := t.size + 1 } if r.tail.size < branching.toNat || t.size >= tooBig then r else mkNewTail r private def emptyArray {α : Type u} : Array (PersistentArrayNode α) := Array.mkEmpty PersistentArray.branching.toNat partial def popLeaf : PersistentArrayNode α → Option (Array α) × Array (PersistentArrayNode α) | n@(node cs) => if h : cs.size ≠ 0 then let idx : Fin cs.size := ⟨cs.size - 1, by exact Nat.predLt h⟩ let last := cs.get idx let cs' := cs.set idx arbitrary match popLeaf last with | (none, _) => (none, emptyArray) | (some l, newLast) => if newLast.size == 0 then let cs' := cs'.pop if cs'.isEmpty then (some l, emptyArray) else (some l, cs') else (some l, cs'.set (Array.sizeSetEq cs idx _ ▸ idx) (node newLast)) else (none, emptyArray) | leaf vs => (some vs, emptyArray) def pop (t : PersistentArray α) : PersistentArray α := if t.tail.size > 0 then { t with tail := t.tail.pop, size := t.size - 1 } else match popLeaf t.root with | (none, _) => t | (some last, newRoots) => let last := last.pop let newSize := t.size - 1 let newTailOff := newSize - last.size if newRoots.size == 1 && (newRoots.get! 0).isNode then { root := newRoots.get! 0, shift := t.shift - initShift, size := newSize, tail := last, tailOff := newTailOff } else { t with root := node newRoots, size := newSize, tail := last, tailOff := newTailOff } section variable {m : Type v → Type w} [Monad m] variable {β : Type v} @[specialize] private partial def foldlMAux (f : β → α → m β) : PersistentArrayNode α → β → m β | node cs, b => cs.foldlM (fun b c => foldlMAux f c b) b | leaf vs, b => vs.foldlM f b @[specialize] private partial def foldlFromMAux (f : β → α → m β) : PersistentArrayNode α → USize → USize → β → m β | node cs, i, shift, b => do let j := (div2Shift i shift).toNat let b ← foldlFromMAux f (cs.get! j) (mod2Shift i shift) (shift - initShift) b cs.foldlM (init := b) (start := j+1) fun b c => foldlMAux f c b | leaf vs, i, _, b => vs.foldlM (init := b) (start := i.toNat) f @[specialize] def foldlM (t : PersistentArray α) (f : β → α → m β) (init : β) (start : Nat := 0) : m β := do if start == 0 then let b ← foldlMAux f t.root init t.tail.foldlM f b else if start >= t.tailOff then t.tail.foldlM (init := init) (start := start - t.tailOff) f else do let b ← foldlFromMAux f t.root (USize.ofNat start) t.shift init; t.tail.foldlM f b @[specialize] partial def forInAux {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] [inh : Inhabited β] (f : α → β → m (ForInStep β)) (n : PersistentArrayNode α) (b : β) : m (ForInStep β) := do let mut b := b match n with | leaf vs => for v in vs do match (← f v b) with | r@(ForInStep.done b) => return r | ForInStep.yield bNew => b := bNew return ForInStep.yield b | node cs => for c in cs do match (← forInAux f c b) with | r@(ForInStep.done b) => return r | ForInStep.yield bNew => b := bNew return ForInStep.yield b @[specialize] def forIn (t : PersistentArray α) (init : β) (f : α → β → m (ForInStep β)) : m β := do match (← forInAux (inh := ⟨init⟩) f t.root init) with | ForInStep.done b => pure b | ForInStep.yield b => let mut b := b for v in t.tail do match (← f v b) with | ForInStep.done b => return b | ForInStep.yield bNew => b := bNew return b @[specialize] partial def findSomeMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β) | node cs => cs.findSomeM? (fun c => findSomeMAux f c) | leaf vs => vs.findSomeM? f @[specialize] def findSomeM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do match (← findSomeMAux f t.root) with | none => t.tail.findSomeM? f | some b => pure (some b) @[specialize] partial def findSomeRevMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β) | node cs => cs.findSomeRevM? (fun c => findSomeRevMAux f c) | leaf vs => vs.findSomeRevM? f @[specialize] def findSomeRevM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do match (← t.tail.findSomeRevM? f) with | none => findSomeRevMAux f t.root | some b => pure (some b) @[specialize] partial def forMAux (f : α → m PUnit) : PersistentArrayNode α → m PUnit | node cs => cs.forM (fun c => forMAux f c) | leaf vs => vs.forM f @[specialize] def forM (t : PersistentArray α) (f : α → m PUnit) : m PUnit := forMAux f t.root *> t.tail.forM f end @[inline] def foldl {β} (t : PersistentArray α) (f : β → α → β) (init : β) (start : Nat := 0) : β := Id.run $ t.foldlM f init start @[inline] def filter (as : PersistentArray α) (p : α → Bool) : PersistentArray α := as.foldl (init := {}) fun asNew a => if p a then asNew.push a else asNew def toArray (t : PersistentArray α) : Array α := t.foldl Array.push #[] def append (t₁ t₂ : PersistentArray α) : PersistentArray α := if t₁.isEmpty then t₂ else t₂.foldl PersistentArray.push t₁ instance : Append (PersistentArray α) := ⟨append⟩ @[inline] def findSome? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β := Id.run $ t.findSomeM? f @[inline] def findSomeRev? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β := Id.run $ t.findSomeRevM? f def toList (t : PersistentArray α) : List α := (t.foldl (init := []) fun xs x => x :: xs).reverse section variable {m : Type → Type w} [Monad m] @[specialize] partial def anyMAux (p : α → m Bool) : PersistentArrayNode α → m Bool | node cs => cs.anyM fun c => anyMAux p c | leaf vs => vs.anyM p @[specialize] def anyM (t : PersistentArray α) (p : α → m Bool) : m Bool := anyMAux p t.root <||> t.tail.anyM p @[inline] def allM (a : PersistentArray α) (p : α → m Bool) : m Bool := do let b ← anyM a (fun v => do let b ← p v; pure (not b)) pure (not b) end @[inline] def any (a : PersistentArray α) (p : α → Bool) : Bool := Id.run $ anyM a p @[inline] def all (a : PersistentArray α) (p : α → Bool) : Bool := !any a fun v => !p v section variable {m : Type u → Type v} [Monad m] variable {β : Type u} @[specialize] partial def mapMAux (f : α → m β) : PersistentArrayNode α → m (PersistentArrayNode β) | node cs => node <$> cs.mapM (fun c => mapMAux f c) | leaf vs => leaf <$> vs.mapM f @[specialize] def mapM (f : α → m β) (t : PersistentArray α) : m (PersistentArray β) := do let root ← mapMAux f t.root let tail ← t.tail.mapM f pure { t with tail := tail, root := root } end @[inline] def map {β} (f : α → β) (t : PersistentArray α) : PersistentArray β := Id.run $ t.mapM f structure Stats where numNodes : Nat depth : Nat tailSize : Nat partial def collectStats : PersistentArrayNode α → Stats → Nat → Stats | node cs, s, d => cs.foldl (fun s c => collectStats c s (d+1)) { s with numNodes := s.numNodes + 1, depth := Nat.max d s.depth } | leaf vs, s, d => { s with numNodes := s.numNodes + 1, depth := Nat.max d s.depth } def stats (r : PersistentArray α) : Stats := collectStats r.root { numNodes := 0, depth := 0, tailSize := r.tail.size } 0 def Stats.toString (s : Stats) : String := s!"\{nodes := {s.numNodes}, depth := {s.depth}, tail size := {s.tailSize}}" instance : ToString Stats := ⟨Stats.toString⟩ end PersistentArray def mkPersistentArray {α : Type u} (n : Nat) (v : α) : PArray α := n.fold (init := PersistentArray.empty) fun i p => p.push v @[inline] def mkPArray {α : Type u} (n : Nat) (v : α) : PArray α := mkPersistentArray n v end Std open Std (PersistentArray PersistentArray.empty) def List.toPersistentArrayAux {α : Type u} : List α → PersistentArray α → PersistentArray α | [], t => t | x::xs, t => toPersistentArrayAux xs (t.push x) def List.toPersistentArray {α : Type u} (xs : List α) : PersistentArray α := xs.toPersistentArrayAux {} def Array.toPersistentArray {α : Type u} (xs : Array α) : PersistentArray α := xs.foldl (init := PersistentArray.empty) fun p x => p.push x @[inline] def Array.toPArray {α : Type u} (xs : Array α) : PersistentArray α := xs.toPersistentArray
fd579264e03e5b4a44cc9414532c29c17307a7ea
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_243.lean
db4a2f4b5c1015a1459943a7f9da34bf45a12d99
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
288
lean
variables p q r : Prop -- BEGIN example (h : (p ∧ q) ∧ r) : q := begin cases h with h₂ h₃, -- We have `h₂ : p` and `h₃ : q` by left and right conjunction elimination on `h`. exact h₂.right -- The result follows by right conjunction elimination on `h₂`. end -- END
a57163cc1a124b201f5d9ff248d40d67bdfe254a
bb31430994044506fa42fd667e2d556327e18dfe
/src/ring_theory/integral_domain.lean
210b69b717ac606cf9c862412aa8c13c0a37f026
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
9,367
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes -/ import data.polynomial.ring_division import group_theory.specific_groups.cyclic import algebra.geom_sum /-! # Integral domains Assorted theorems about integral domains. ## Main theorems * `is_cyclic_of_subgroup_is_domain`: A finite subgroup of the units of an integral domain is cyclic. * `fintype.field_of_domain`: A finite integral domain is a field. ## TODO Prove Wedderburn's little theorem, which shows that all finite division rings are actually fields. ## Tags integral domain, finite integral domain, finite field -/ section open finset polynomial function open_locale big_operators nat section cancel_monoid_with_zero -- There doesn't seem to be a better home for these right now variables {M : Type*} [cancel_monoid_with_zero M] [finite M] lemma mul_right_bijective_of_finite₀ {a : M} (ha : a ≠ 0) : bijective (λ b, a * b) := finite.injective_iff_bijective.1 $ mul_right_injective₀ ha lemma mul_left_bijective_of_finite₀ {a : M} (ha : a ≠ 0) : bijective (λ b, b * a) := finite.injective_iff_bijective.1 $ mul_left_injective₀ ha /-- Every finite nontrivial cancel_monoid_with_zero is a group_with_zero. -/ def fintype.group_with_zero_of_cancel (M : Type*) [cancel_monoid_with_zero M] [decidable_eq M] [fintype M] [nontrivial M] : group_with_zero M := { inv := λ a, if h : a = 0 then 0 else fintype.bij_inv (mul_right_bijective_of_finite₀ h) 1, mul_inv_cancel := λ a ha, by { simp [has_inv.inv, dif_neg ha], exact fintype.right_inverse_bij_inv _ _ }, inv_zero := by { simp [has_inv.inv, dif_pos rfl] }, ..‹nontrivial M›, ..‹cancel_monoid_with_zero M› } lemma exists_eq_pow_of_mul_eq_pow_of_coprime {R : Type*} [comm_semiring R] [is_domain R] [gcd_monoid R] [unique Rˣ] {a b c : R} {n : ℕ} (cp : is_coprime a b) (h : a * b = c ^ n) : ∃ d : R, a = d ^ n := begin refine exists_eq_pow_of_mul_eq_pow (is_unit_of_dvd_one _ _) h, obtain ⟨x, y, hxy⟩ := cp, rw [← hxy], exact dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left _ _) _) (dvd_mul_of_dvd_right (gcd_dvd_right _ _) _) end lemma finset.exists_eq_pow_of_mul_eq_pow_of_coprime {ι R : Type*} [comm_semiring R] [is_domain R] [gcd_monoid R] [unique Rˣ] {n : ℕ} {c : R} {s : finset ι} {f : ι → R} (h : ∀ i j ∈ s, i ≠ j → is_coprime (f i) (f j)) (hprod : ∏ i in s, f i = c ^ n) : ∀ i ∈ s, ∃ d : R, f i = d ^ n := begin classical, intros i hi, rw [← insert_erase hi, prod_insert (not_mem_erase i s)] at hprod, refine exists_eq_pow_of_mul_eq_pow_of_coprime (is_coprime.prod_right (λ j hj, h i hi j (erase_subset i s hj) (λ hij, _))) hprod, rw [hij] at hj, exact (s.not_mem_erase _) hj end end cancel_monoid_with_zero variables {R : Type*} {G : Type*} section ring variables [ring R] [is_domain R] [fintype R] /-- Every finite domain is a division ring. TODO: Prove Wedderburn's little theorem, which shows a finite domain is in fact commutative, hence a field. -/ def fintype.division_ring_of_is_domain (R : Type*) [ring R] [is_domain R] [decidable_eq R] [fintype R] : division_ring R := { ..show group_with_zero R, from fintype.group_with_zero_of_cancel R, ..‹ring R› } /-- Every finite commutative domain is a field. TODO: Prove Wedderburn's little theorem, which shows a finite domain is automatically commutative, dropping one assumption from this theorem. -/ def fintype.field_of_domain (R) [comm_ring R] [is_domain R] [decidable_eq R] [fintype R] : field R := { .. fintype.group_with_zero_of_cancel R, .. ‹comm_ring R› } lemma finite.is_field_of_domain (R) [comm_ring R] [is_domain R] [finite R] : is_field R := by { casesI nonempty_fintype R, exact @field.to_is_field R (@@fintype.field_of_domain R _ _ (classical.dec_eq R) _) } end ring variables [comm_ring R] [is_domain R] [group G] lemma card_nth_roots_subgroup_units [fintype G] (f : G →* R) (hf : injective f) {n : ℕ} (hn : 0 < n) (g₀ : G) : ({g ∈ univ | g ^ n = g₀} : finset G).card ≤ (nth_roots n (f g₀)).card := begin haveI : decidable_eq R := classical.dec_eq _, refine le_trans _ (nth_roots n (f g₀)).to_finset_card_le, apply card_le_card_of_inj_on f, { intros g hg, rw [sep_def, mem_filter] at hg, rw [multiset.mem_to_finset, mem_nth_roots hn, ← f.map_pow, hg.2] }, { intros, apply hf, assumption } end /-- A finite subgroup of the unit group of an integral domain is cyclic. -/ lemma is_cyclic_of_subgroup_is_domain [finite G] (f : G →* R) (hf : injective f) : is_cyclic G := begin classical, casesI nonempty_fintype G, apply is_cyclic_of_card_pow_eq_one_le, intros n hn, convert (le_trans (card_nth_roots_subgroup_units f hf hn 1) (card_nth_roots n (f 1))) end /-- The unit group of a finite integral domain is cyclic. To support `ℤˣ` and other infinite monoids with finite groups of units, this requires only `finite Rˣ` rather than deducing it from `finite R`. -/ instance [finite Rˣ] : is_cyclic Rˣ := is_cyclic_of_subgroup_is_domain (units.coe_hom R) $ units.ext section variables (S : subgroup Rˣ) [finite S] /-- A finite subgroup of the units of an integral domain is cyclic. -/ instance subgroup_units_cyclic : is_cyclic S := begin refine is_cyclic_of_subgroup_is_domain ⟨(coe : S → R), _, _⟩ (units.ext.comp subtype.val_injective), { simp }, { intros, simp }, end end variables [fintype G] lemma card_fiber_eq_of_mem_range {H : Type*} [group H] [decidable_eq H] (f : G →* H) {x y : H} (hx : x ∈ set.range f) (hy : y ∈ set.range f) : (univ.filter $ λ g, f g = x).card = (univ.filter $ λ g, f g = y).card := begin rcases hx with ⟨x, rfl⟩, rcases hy with ⟨y, rfl⟩, refine card_congr (λ g _, g * x⁻¹ * y) _ _ (λ g hg, ⟨g * y⁻¹ * x, _⟩), { simp only [mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv, eq_self_iff_true, monoid_hom.map_mul_inv, and_self, forall_true_iff] {contextual := tt} }, { simp only [mul_left_inj, imp_self, forall_2_true_iff], }, { simp only [true_and, mem_filter, mem_univ] at hg, simp only [hg, mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv, eq_self_iff_true, exists_prop_of_true, monoid_hom.map_mul_inv, and_self, mul_inv_cancel_right, inv_mul_cancel_right], } end /-- In an integral domain, a sum indexed by a nontrivial homomorphism from a finite group is zero. -/ lemma sum_hom_units_eq_zero (f : G →* R) (hf : f ≠ 1) : ∑ g : G, f g = 0 := begin classical, obtain ⟨x, hx⟩ : ∃ x : monoid_hom.range f.to_hom_units, ∀ y : monoid_hom.range f.to_hom_units, y ∈ submonoid.powers x, from is_cyclic.exists_monoid_generator, have hx1 : x ≠ 1, { rintro rfl, apply hf, ext g, rw [monoid_hom.one_apply], cases hx ⟨f.to_hom_units g, g, rfl⟩ with n hn, rwa [subtype.ext_iff, units.ext_iff, subtype.coe_mk, monoid_hom.coe_to_hom_units, one_pow, eq_comm] at hn, }, replace hx1 : (x : R) - 1 ≠ 0, from λ h, hx1 (subtype.eq (units.ext (sub_eq_zero.1 h))), let c := (univ.filter (λ g, f.to_hom_units g = 1)).card, calc ∑ g : G, f g = ∑ g : G, f.to_hom_units g : rfl ... = ∑ u : Rˣ in univ.image f.to_hom_units, (univ.filter (λ g, f.to_hom_units g = u)).card • u : sum_comp (coe : Rˣ → R) f.to_hom_units ... = ∑ u : Rˣ in univ.image f.to_hom_units, c • u : sum_congr rfl (λ u hu, congr_arg2 _ _ rfl) -- remaining goal 1, proven below ... = ∑ b : monoid_hom.range f.to_hom_units, c • ↑b : finset.sum_subtype _ (by simp ) _ ... = c • ∑ b : monoid_hom.range f.to_hom_units, (b : R) : smul_sum.symm ... = c • 0 : congr_arg2 _ rfl _ -- remaining goal 2, proven below ... = 0 : smul_zero _, { -- remaining goal 1 show (univ.filter (λ (g : G), f.to_hom_units g = u)).card = c, apply card_fiber_eq_of_mem_range f.to_hom_units, { simpa only [mem_image, mem_univ, exists_prop_of_true, set.mem_range] using hu, }, { exact ⟨1, f.to_hom_units.map_one⟩ } }, -- remaining goal 2 show ∑ b : monoid_hom.range f.to_hom_units, (b : R) = 0, calc ∑ b : monoid_hom.range f.to_hom_units, (b : R) = ∑ n in range (order_of x), x ^ n : eq.symm $ sum_bij (λ n _, x ^ n) (by simp only [mem_univ, forall_true_iff]) (by simp only [implies_true_iff, eq_self_iff_true, subgroup.coe_pow, units.coe_pow, coe_coe]) (λ m n hm hn, pow_injective_of_lt_order_of _ (by simpa only [mem_range] using hm) (by simpa only [mem_range] using hn)) (λ b hb, let ⟨n, hn⟩ := hx b in ⟨n % order_of x, mem_range.2 (nat.mod_lt _ (order_of_pos _)), by rw [← pow_eq_mod_order_of, hn]⟩) ... = 0 : _, rw [← mul_left_inj' hx1, zero_mul, geom_sum_mul, coe_coe], norm_cast, simp [pow_order_of_eq_one], end /-- In an integral domain, a sum indexed by a homomorphism from a finite group is zero, unless the homomorphism is trivial, in which case the sum is equal to the cardinality of the group. -/ lemma sum_hom_units (f : G →* R) [decidable (f = 1)] : ∑ g : G, f g = if f = 1 then fintype.card G else 0 := begin split_ifs with h h, { simp [h, card_univ] }, { exact sum_hom_units_eq_zero f h } end end
5ba834a055dd641601799b4441d1758107ccc09b
a338c3e75cecad4fb8d091bfe505f7399febfd2b
/src/ring_theory/localization.lean
aa7a55c9dc6c9986ab66a6d84670a3da1e7f7166
[ "Apache-2.0" ]
permissive
bacaimano/mathlib
88eb7911a9054874fba2a2b74ccd0627c90188af
f2edc5a3529d95699b43514d6feb7eb11608723f
refs/heads/master
1,686,410,075,833
1,625,497,070,000
1,625,497,070,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
71,744
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston -/ import data.equiv.ring import group_theory.monoid_localization import ring_theory.ideal.operations import ring_theory.algebraic import ring_theory.integral_closure import ring_theory.non_zero_divisors /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. In the following, let `R, P` be commutative rings, `S, Q` be `R`- and `P`-algebras and `M, T` be submonoids of `R` and `P` respectively, e.g.: ``` variables (R S P Q : Type*) [comm_ring R] [comm_ring S] [comm_ring P] [comm_ring Q] variables [algebra R S] [algebra P Q] (M : submonoid R) (T : submonoid P) ``` ## Main definitions * `is_localization (M : submonoid R) (S : Type*)` is a typeclass expressing that `S` is a localization of `R` at `M`, i.e. the canonical map `algebra_map R S : R →+* S` is a localization map (satisfying the above properties). * `is_localization.mk' S` is a surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹` * `is_localization.lift` is the ring homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. * `is_localization.map S Q` is the ring homomorphism from `S` to `Q` which maps elements of `M` to elements of `T` * `is_localization.ring_equiv_of_ring_equiv`: if `R` and `P` are isomorphic by an isomorphism sending `M` to `T`, then `S` and `Q` are isomorphic * `is_localization.alg_equiv`: if `Q` is another localization of `R` at `M`, then `S` and `Q` are isomorphic as `R`-algebras * `is_localization.is_integer` is a predicate stating that `x : S` is in the image of `R` * `is_localization.away (x : R) S` expresses that `S` is a localization away from `x`, as an abbreviation of `is_localization (submonoid.powers x) S` * `is_localization.at_prime (I : ideal R) [is_prime I] (S : Type*)` expresses that `S` is a localization at (the complement of) a prime ideal `I`, as an abbreviation of `is_localization I.prime_compl S` * `is_fraction_ring R K` expresses that `K` is a field of fractions of `R`, as an abbreviation of `is_localization (non_zero_divisors R) K` ## Main results * `localization M S`, a construction of the localization as a quotient type, defined in `group_theory.monoid_localization`, has `comm_ring`, `algebra R` and `is_localization M` instances if `R` is a ring. `localization.away`, `localization.at_prime` and `fraction_ring` are abbreviations for `localization`s and have their corresponding `is_localization` instances * `is_localization.at_prime.local_ring`: a theorem (not an instance) stating a localization at the complement of a prime ideal is a local ring * `is_fraction_ring.field`: a definition (not an instance) stating the localization of an integral domain `R` at `R \ {0}` is a field * `rat.is_fraction_ring_int` is an instance stating `ℚ` is the field of fractions of `ℤ` ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A previous version of this file used a fully bundled type of ring localization maps, then used a type synonym `f.codomain` for `f : localization_map M S` to instantiate the `R`-algebra structure on `S`. This results in defining ad-hoc copies for everything already defined on `S`. By making `is_localization` a predicate on the `algebra_map R S`, we can ensure the localization map commutes nicely with other `algebra_map`s. To prove most lemmas about a localization map `algebra_map R S` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `is_localization.to_localization_map M S`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `algebra_map : R →+* localization M`. The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] open function open_locale big_operators /-- The typeclass `is_localization (M : submodule R) S` where `S` is an `R`-algebra expresses that `S` is isomorphic to the localization of `R` at `M`. -/ class is_localization : Prop := (map_units [] : ∀ y : M, is_unit (algebra_map R S y)) (surj [] : ∀ z : S, ∃ x : R × M, z * algebra_map R S x.2 = algebra_map R S x.1) (eq_iff_exists [] : ∀ {x y}, algebra_map R S x = algebra_map R S y ↔ ∃ c : M, x * c = y * c) variables {M S} namespace is_localization section is_localization variables [is_localization M S] section variables (M S) /-- `is_localization.to_localization_map M S` shows `S` is the monoid localization of `R` at `M`. -/ @[simps] def to_localization_map : submonoid.localization_map M S := { to_fun := algebra_map R S, map_units' := is_localization.map_units _, surj' := is_localization.surj _, eq_iff_exists' := λ _ _, is_localization.eq_iff_exists _ _, .. algebra_map R S } @[simp] lemma to_localization_map_to_map : (to_localization_map M S).to_map = (algebra_map R S : R →* S) := rfl lemma to_localization_map_to_map_apply (x) : (to_localization_map M S).to_map x = algebra_map R S x := rfl end section variables (R) -- TODO: define a subalgebra of `is_integer`s /-- Given `a : S`, `S` a localization of `R`, `is_integer R a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ (algebra_map R S).range end lemma is_integer_zero : is_integer R (0 : S) := subring.zero_mem _ lemma is_integer_one : is_integer R (1 : S) := subring.one_mem _ lemma is_integer_add {a b : S} (ha : is_integer R a) (hb : is_integer R b) : is_integer R (a + b) := subring.add_mem _ ha hb lemma is_integer_mul {a b : S} (ha : is_integer R a) (hb : is_integer R b) : is_integer R (a * b) := subring.mul_mem _ ha hb lemma is_integer_smul {a : R} {b : S} (hb : is_integer R b) : is_integer R (a • b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, (algebra_map R S).map_mul, algebra.smul_def] end variables (M) /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer R (a * algebra_map R S b) := let ⟨⟨num, denom⟩, h⟩ := is_localization.surj _ a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer R ((b : R) • a) := by { simp_rw [algebra.smul_def, mul_comm _ a], apply exists_integer_multiple' } /-- Given a localization map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z`. -/ noncomputable def sec (z : S) : R × M := classical.some $ is_localization.surj _ z @[simp] lemma to_localization_map_sec : (to_localization_map M S).sec = sec M := rfl /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec (z : S) : z * algebra_map R S (is_localization.sec M z).2 = algebra_map R S (is_localization.sec M z).1 := classical.some_spec $ is_localization.surj _ z /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' (z : S) : algebra_map R S (is_localization.sec M z).1 = algebra_map R S (is_localization.sec M z).2 * z := by rw [mul_comm, sec_spec] open_locale big_operators /-- We can clear the denominators of a finite set of fractions. -/ lemma exist_integer_multiples_of_finset (s : finset S) : ∃ (b : M), ∀ a ∈ s, is_integer R ((b : R) • a) := begin haveI := classical.prop_decidable, use ∏ a in s, (is_localization.sec M a).2, intros a ha, use (∏ x in s.erase a, (is_localization.sec M x).2) * (is_localization.sec M a).1, rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←(algebra_map R S).map_mul, ← algebra.smul_def], congr' 2, refine trans _ ((submonoid.subtype M).map_prod _ _).symm, rw [mul_comm, ←finset.prod_insert (s.not_mem_erase a), finset.insert_erase ha], refl, end variables {R M} lemma map_right_cancel {x y} {c : M} (h : algebra_map R S (c * x) = algebra_map R S (c * y)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : algebra_map R S (x * c) = algebra_map R S (y * c)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * algebra_map R S y = algebra_map R S x) (hx : x = 0) : z = 0 := by { rw [hx, (algebra_map R S).map_zero] at h, exact (is_unit.mul_left_eq_zero (is_localization.map_units S y)).1 h} variables (S) /-- `is_localization.mk' S` is the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (x : R) (y : M) : S := (to_localization_map M S).mk' x y @[simp] lemma mk'_sec (z : S) : mk' S (is_localization.sec M z).1 (is_localization.sec M z).2 = z := (to_localization_map M S).mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * x₂) (y₁ * y₂) = mk' S x₁ y₁ * mk' S x₂ y₂ := (to_localization_map M S).mk'_mul _ _ _ _ lemma mk'_one (x) : mk' S x (1 : M) = algebra_map R S x := (to_localization_map M S).mk'_one _ @[simp] lemma mk'_spec (x) (y : M) : mk' S x y * algebra_map R S y = algebra_map R S x := (to_localization_map M S).mk'_spec _ _ @[simp] lemma mk'_spec' (x) (y : M) : algebra_map R S y * mk' S x y = algebra_map R S x := (to_localization_map M S).mk'_spec' _ _ variables {S} theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = mk' S x y ↔ z * algebra_map R S y = algebra_map R S x := (to_localization_map M S).eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : mk' S x y = z ↔ algebra_map R S x = z * algebra_map R S y := (to_localization_map M S).mk'_eq_iff_eq_mul variables (M) lemma mk'_surjective (z : S) : ∃ x (y : M), mk' S x y = z := let ⟨r, hr⟩ := is_localization.surj _ z in ⟨r.1, r.2, (eq_mk'_iff_mul_eq.2 hr).symm⟩ variables {M} lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ algebra_map R S (x₁ * y₂) = algebra_map R S (x₂ * y₁) := (to_localization_map M S).mk'_eq_iff_eq lemma mk'_mem_iff {x} {y : M} {I : ideal S} : mk' S x y ∈ I ↔ algebra_map R S x ∈ I := begin split; intro h, { rw [← mk'_spec S x y, mul_comm], exact I.mul_mem_left ((algebra_map R S) y) h }, { rw ← mk'_spec S x y at h, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units S y), have := I.mul_mem_left b h, rwa [mul_comm, mul_assoc, hb, mul_one] at this } end protected lemma eq {a₁ b₁} {a₂ b₂ : M} : mk' S a₁ a₂ = mk' S b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := (to_localization_map M S).eq section ext variables [algebra R P] [is_localization M P] lemma eq_iff_eq {x y} : algebra_map R S x = algebra_map R S y ↔ algebra_map R P x = algebra_map R P y := (to_localization_map M S).eq_iff_eq (to_localization_map M P) lemma mk'_eq_iff_mk'_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ mk' P x₁ y₁ = mk' P x₂ y₂ := (to_localization_map M S).mk'_eq_iff_mk'_eq (to_localization_map M P) lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : mk' S a₁ a₂ = mk' S b₁ b₂ := (to_localization_map M S).mk'_eq_of_eq H variables (S) @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : mk' S x ⟨x, hx⟩ = 1 := (to_localization_map M S).mk'_self _ hx @[simp] lemma mk'_self' {x : M} : mk' S (x : R) x = 1 := (to_localization_map M S).mk'_self' _ lemma mk'_self'' {x : M} : mk' S x.1 x = 1 := mk'_self' _ end ext lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : (algebra_map R S) x * mk' S y z = mk' S (x * y) z := (to_localization_map M S).mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : mk' S x y = (algebra_map R S) x * mk' S 1 y := ((to_localization_map M S).mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : mk' S (y * x : R) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : mk' S (x * y) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : mk' S (x : R) y * mk' S (y : R) x = 1 := by rw [←mk'_mul, mul_comm]; exact mk'_self _ _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : mk' S x y * mk' S (y : R) ⟨x, h⟩ = 1 := mk'_mul_mk'_eq_one ⟨x, h⟩ _ section variables (M) lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp (algebra_map R S) y) := (to_localization_map M S).is_unit_comp j.to_monoid_hom _ end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : (algebra_map R S) x = (algebra_map R S) y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = mk' S x₁ y₁ + mk' S x₂ y₂ := mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul, mul_comm _ ((algebra_map R S) _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc, ←(algebra_map R S).map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul], simp only [(algebra_map R S).map_add, submonoid.coe_mul, (algebra_map R S).map_mul], ring_exp, end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg) $ begin intros x y, rw [(to_localization_map M S).lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm, (to_localization_map M S).lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq', ←eq_sub_iff_add_eq, mul_assoc, (to_localization_map M S).lift_spec_mul], show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _), simp only [← g.map_sub, ← g.map_mul, to_localization_map_sec], apply eq_of_eq hg, rw [(algebra_map R S).map_mul, sec_spec', mul_sub, (algebra_map R S).map_sub], simp only [ring_hom.map_mul, sec_spec'], ring, assumption end variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : lift hg (mk' S x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ := (to_localization_map M S).lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : lift hg (mk' S x y) = v ↔ g x = g y * v := (to_localization_map M S).lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : lift hg ((algebra_map R S) x) = g x := (to_localization_map M S).lift_eq _ _ lemma lift_eq_iff {x y : R × M} : lift hg (mk' S x.1 x.2) = lift hg (mk' S y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := (to_localization_map M S).lift_eq_iff _ @[simp] lemma lift_comp : (lift hg).comp (algebra_map R S) = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : lift (is_unit_comp M j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_of_comp j.to_monoid_hom variables (M) lemma epic_of_localization_map (j k : S →+* P) (h : ∀ a, j.comp (algebra_map R S) a = k.comp (algebra_map R S) a) : j = k := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map _ _ _ _ _ _ _ (to_localization_map M S) j.to_monoid_hom k.to_monoid_hom h variables {M} lemma lift_unique {j : S →+* P} (hj : ∀ x, j ((algebra_map R S) x) = g x) : lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : lift (map_units S : ∀ y : M, is_unit _) x = x := (to_localization_map M S).lift_id _ lemma lift_surjective_iff : surjective (lift hg : S → P) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := (to_localization_map M S).lift_surjective_iff hg lemma lift_injective_iff : injective (lift hg : S → P) ↔ ∀ x y, algebra_map R S x = algebra_map R S y ↔ g x = g y := (to_localization_map M S).lift_injective_iff hg section map variables {T : submonoid P} {Q : Type*} [comm_ring Q] (hy : M ≤ T.comap g) variables [algebra P Q] [is_localization T Q] section variables (Q) /-- Map a homomorphism `g : R →+* P` to `S →+* Q`, where `S` and `Q` are localizations of `R` and `P` at `M` and `T` respectively, such that `g(M) ⊆ T`. We send `z : S` to `algebra_map P Q (g x) * (algebra_map P Q (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : R →+* P) (hy : M ≤ T.comap g) : S →+* Q := @lift R _ M _ _ _ _ _ _ ((algebra_map P Q).comp g) (λ y, map_units _ ⟨g y, hy y.2⟩) end lemma map_eq (x) : map Q g hy ((algebra_map R S) x) = algebra_map P Q (g x) := lift_eq (λ y, map_units _ ⟨g y, hy y.2⟩) x @[simp] lemma map_comp : (map Q g hy).comp (algebra_map R S) = (algebra_map P Q).comp g := lift_comp $ λ y, map_units _ ⟨g y, hy y.2⟩ lemma map_mk' (x) (y : M) : map Q g hy (mk' S x y) = mk' Q (g x) ⟨g y, hy y.2⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom _ (λ y, hy y.2) _ _ (to_localization_map T Q) _ _ @[simp] lemma map_id (z : S) (h : M ≤ M.comap (ring_hom.id R) := le_refl M) : map S (ring_hom.id _) h z = z := lift_id _ lemma map_unique (j : S →+* Q) (hj : ∀ x : R, j (algebra_map R S x) = algebra_map P Q (g x)) : map Q g hy = j := lift_unique (λ y, map_units _ ⟨g y, hy y.2⟩) hj /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) : (map W l hl).comp (map Q g hy : S →+* _) = map W (l.comp g) (λ x hx, hl (hy hx)) := ring_hom.ext $ λ x, @submonoid.localization_map.map_map _ _ _ _ _ P _ (to_localization_map M S) g _ _ _ _ _ _ _ _ _ _ (to_localization_map U W) l _ x /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) (x : S) : map W l hl (map Q g hy x) = map W (l.comp g) (λ x hx, hl (hy hx)) x := by rw ←map_comp_map hy hl; refl section variables (S Q) /-- If `S`, `Q` are localizations of `R` and `P` at submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ @[simps] noncomputable def ring_equiv_of_ring_equiv (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := have H' : T.map h.symm.to_monoid_hom = M, by { rw [← M.map_id, ← H, submonoid.map_map], congr, ext, apply h.symm_apply_apply }, { to_fun := map Q (h : R →+* P) (M.le_comap_of_map_le (le_of_eq H)), inv_fun := map S (h.symm : P →+* R) (T.le_comap_of_map_le (le_of_eq H')), left_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map R S) (h.symm_apply_apply x).symm }, right_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map P Q) (h.apply_symm_apply x).symm }, .. map Q (h : R →+* P) _ } end lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (ring_equiv_of_ring_equiv S Q j H : S →+* Q) = map Q (j : R →+* P) (M.le_comap_of_map_le (le_of_eq H)) := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : ring_equiv_of_ring_equiv S Q j H ((algebra_map R S) x) = algebra_map P Q (j x) := map_eq _ _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x : R) (y : M) : ring_equiv_of_ring_equiv S Q j H (mk' S x y) = mk' Q (j x) ⟨j y, show j y ∈ T, from H ▸ set.mem_image_of_mem j y.2⟩ := map_mk' _ _ _ end map section alg_equiv variables {Q : Type*} [comm_ring Q] [algebra R Q] [is_localization M Q] section variables (M S Q) /-- If `S`, `Q` are localizations of `R` at the submonoid `M` respectively, there is an isomorphism of localizations `S ≃ₐ[R] Q`. -/ @[simps] noncomputable def alg_equiv : S ≃ₐ[R] Q := { commutes' := ring_equiv_of_ring_equiv_eq _, .. ring_equiv_of_ring_equiv S Q (ring_equiv.refl R) M.map_id } end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S Q (mk' S x y) = mk' Q x y:= map_mk' _ _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S Q).symm (mk' Q x y) = mk' S x y:= map_mk' _ _ _ end alg_equiv end is_localization section away variables (x : R) /-- Given `x : R`, the typeclass `is_localization.away x S` states that `S` is isomorphic to the localization of `R` at the submonoid generated by `x`. -/ abbreviation away (S : Type*) [comm_ring S] [algebra R S] := is_localization (submonoid.powers x) S namespace away variables [is_localization.away x S] /-- Given `x : R` and a localization map `F : R →+* S` away from `x`, `inv_self` is `(F x)⁻¹`. -/ noncomputable def inv_self : S := mk' S 1 ⟨x, submonoid.mem_powers _⟩ variables {g : R →+* P} /-- Given `x : R`, a localization map `F : R →+* S` away from `x`, and a map of `comm_ring`s `g : R →+* P` such that `g x` is invertible, the homomorphism induced from `S` to `P` sending `z : S` to `g y * (g x)⁻ⁿ`, where `y : R, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/ noncomputable def lift (hg : is_unit (g x)) : S →+* P := is_localization.lift $ λ (y : submonoid.powers x), show is_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_pow], exact is_unit.map (monoid_hom.of $ ((^ n) : P → P)) hg, end @[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : R) : lift x hg ((algebra_map R S) a) = g a := lift_eq _ _ @[simp] lemma away_map.lift_comp (hg : is_unit (g x)) : (lift x hg).comp (algebra_map R S) = g := lift_comp _ /-- Given `x y : R` and localizations `S`, `P` away from `x` and `x * y` respectively, the homomorphism induced from `S` to `P`. -/ noncomputable def away_to_away_right (y : R) [algebra R P] [is_localization.away (x * y) P] : S →+* P := lift x $ show is_unit ((algebra_map R P) x), from is_unit_of_mul_eq_one ((algebra_map R P) x) (mk' P y ⟨x * y, submonoid.mem_powers _⟩) $ by rw [mul_mk'_eq_mk'_of_mul, mk'_self] end away end away end is_localization namespace localization open is_localization /-! ### Constructing a localization at a given submonoid -/ variables {M} instance : has_add (localization M) := ⟨λ z w, con.lift_on₂ z w (λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $ λ r1 r2 r3 r4 h1 h2, (con.eq _).2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) = (r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring ... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end⟩ instance : has_neg (localization M) := ⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $ λ r1 r2 h, (con.eq _).2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht], ring_nf, end⟩ instance : has_zero (localization M) := ⟨mk 0 1⟩ private meta def tac := `[{ intros, refine quotient.sound' (r_of_eq _), simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul], ring }] instance : comm_ring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac), zero_add := λ y, quotient.induction_on' y (by tac), add_zero := λ y, quotient.induction_on' y (by tac), neg := has_neg.neg, sub := λ x y, x + -y, sub_eq_add_neg := λ x y, rfl, add_left_neg := λ y, by exact quotient.induction_on' y (by tac), add_comm := λ y z, quotient.induction_on₂' z y (by tac), left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), ..localization.comm_monoid M } instance : algebra R (localization M) := ring_hom.to_algebra $ { map_zero' := rfl, map_add' := λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm], .. localization.monoid_of M } instance : is_localization M (localization M) := { map_units := (localization.monoid_of M).map_units, surj := (localization.monoid_of M).surj, eq_iff_exists := λ _ _, (localization.monoid_of M).eq_iff_exists } lemma monoid_of_eq_algebra_map (x) : (monoid_of M).to_map x = algebra_map R (localization M) x := rfl lemma mk_one_eq_algebra_map (x) : mk x 1 = algebra_map R (localization M) x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = is_localization.mk' (localization M) x y := mk_eq_monoid_of_mk'_apply _ _ @[simp] lemma mk_eq_mk' : (mk : R → M → (localization M)) = is_localization.mk' (localization M) := mk_eq_monoid_of_mk' variables [is_localization M S] section variables (M S) /-- The localization of `R` at `M` as a quotient type is isomorphic to any other localization. -/ @[simps] noncomputable def alg_equiv : localization M ≃ₐ[R] S := is_localization.alg_equiv M _ _ end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S (mk' (localization M) x y) = mk' S x y := alg_equiv_mk' _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk' (localization M) x y := alg_equiv_symm_mk' _ _ lemma alg_equiv_mk (x y) : alg_equiv M S (mk x y) = mk' S x y := by rw [mk_eq_mk', alg_equiv_mk'] lemma alg_equiv_symm_mk (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk x y := by rw [mk_eq_mk', alg_equiv_symm_mk'] end localization variables {M} section at_prime variables (I : ideal R) [hp : I.is_prime] include hp namespace ideal /-- The complement of a prime ideal `I ⊆ R` is a submonoid of `R`. -/ def prime_compl : submonoid R := { carrier := (Iᶜ : set R), one_mem' := by convert I.ne_top_iff_one.1 hp.1; refl, mul_mem' := λ x y hnx hny hxy, or.cases_on (hp.mem_or_mem hxy) hnx hny } end ideal variables (S) /-- Given a prime ideal `P`, the typeclass `is_localization.at_prime S P` states that `S` is isomorphic to the localization of `R` at the complement of `P`. -/ protected abbreviation is_localization.at_prime := is_localization I.prime_compl S /-- Given a prime ideal `P`, `localization.at_prime S P` is a localization of `R` at the complement of `P`, as a quotient type. -/ protected abbreviation localization.at_prime := localization I.prime_compl namespace is_localization theorem at_prime.local_ring [is_localization.at_prime S I] : local_ring S := local_of_nonunits_ideal (λ hze, begin rw [←(algebra_map R S).map_one, ←(algebra_map R S).map_zero] at hze, obtain ⟨t, ht⟩ := (eq_iff_exists I.prime_compl S).1 hze, exact ((show (t : R) ∉ I, from t.2) (have htz : (t : R) = 0, by simpa using ht.symm, htz.symm ▸ I.zero_mem)) end) (begin intros x y hx hy hu, cases is_unit_iff_exists_inv.1 hu with z hxyz, have : ∀ {r : R} {s : I.prime_compl}, mk' S r s ∈ nonunits S → r ∈ I, from λ (r : R) (s : I.prime_compl), not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨mk' S ↑s (⟨r, nr⟩ : I.prime_compl), mk'_mul_mk'_eq_one' _ _ nr⟩), rcases mk'_surjective I.prime_compl x with ⟨rx, sx, hrx⟩, rcases mk'_surjective I.prime_compl y with ⟨ry, sy, hry⟩, rcases mk'_surjective I.prime_compl z with ⟨rz, sz, hrz⟩, rw [←hrx, ←hry, ←hrz, ←mk'_add, ←mk'_mul, ←mk'_self S I.prime_compl.one_mem] at hxyz, rw ←hrx at hx, rw ←hry at hy, obtain ⟨t, ht⟩ := is_localization.eq.1 hxyz, simp only [mul_one, one_mul, submonoid.coe_mul, subtype.coe_mk] at ht, rw [←sub_eq_zero, ←sub_mul] at ht, have hr := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right t.2, rw sub_eq_add_neg at hr, have := I.neg_mem_iff.1 ((ideal.add_mem_iff_right _ _).1 hr), { exact not_or (mt hp.mem_or_mem (not_or sx.2 sy.2)) sz.2 (hp.mem_or_mem this)}, { exact I.mul_mem_right _ (I.add_mem (I.mul_mem_right _ (this hx)) (I.mul_mem_right _ (this hy)))} end) end is_localization namespace localization /-- The localization of `R` at the complement of a prime ideal is a local ring. -/ instance at_prime.local_ring : local_ring (localization I.prime_compl) := is_localization.at_prime.local_ring (localization I.prime_compl) I end localization end at_prime namespace is_localization variables [is_localization M S] section ideals variables (M) (S) include M /-- Explicit characterization of the ideal given by `ideal.map (algebra_map R S) I`. In practice, this ideal differs only in that the carrier set is defined explicitly. This definition is only meant to be used in proving `mem_map_to_map_iff`, and any proof that needs to refer to the explicit carrier set should use that theorem. -/ private def map_ideal (I : ideal R) : ideal S := { carrier := { z : S | ∃ x : I × M, z * algebra_map R S x.2 = algebra_map R S x.1}, zero_mem' := ⟨⟨0, 1⟩, by simp⟩, add_mem' := begin rintros a b ⟨a', ha⟩ ⟨b', hb⟩, use ⟨a'.2 * b'.1 + b'.2 * a'.1, I.add_mem (I.mul_mem_left _ b'.1.2) (I.mul_mem_left _ a'.1.2)⟩, use a'.2 * b'.2, simp only [ring_hom.map_add, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], rw [add_mul, ← mul_assoc a, ha, mul_comm (algebra_map R S a'.2) (algebra_map R S b'.2), ← mul_assoc b, hb], ring end, smul_mem' := begin rintros c x ⟨x', hx⟩, obtain ⟨c', hc⟩ := is_localization.surj M c, use ⟨c'.1 * x'.1, I.mul_mem_left c'.1 x'.1.2⟩, use c'.2 * x'.2, simp only [←hx, ←hc, smul_eq_mul, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], ring end } theorem mem_map_algebra_map_iff {I : ideal R} {z} : z ∈ ideal.map (algebra_map R S) I ↔ ∃ x : I × M, z * algebra_map R S x.2 = algebra_map R S x.1 := begin split, { change _ → z ∈ map_ideal M S I, refine λ h, ideal.mem_Inf.1 h (λ z hz, _), obtain ⟨y, hy⟩ := hz, use ⟨⟨⟨y, hy.left⟩, 1⟩, by simp [hy.right]⟩ }, { rintros ⟨⟨a, s⟩, h⟩, rw [← ideal.unit_mul_mem_iff_mem _ (map_units S s), mul_comm], exact h.symm ▸ ideal.mem_map_of_mem _ a.2 } end theorem map_comap (J : ideal S) : ideal.map (algebra_map R S) (ideal.comap (algebra_map R S) J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x hJ, begin obtain ⟨r, s, hx⟩ := mk'_surjective M x, rw ←hx at ⊢ hJ, exact ideal.mul_mem_right _ _ (ideal.mem_map_of_mem _ (show (algebra_map R S) r ∈ J, from mk'_spec S r s ▸ J.mul_mem_right ((algebra_map R S) s) hJ)), end theorem comap_map_of_is_prime_disjoint (I : ideal R) (hI : I.is_prime) (hM : disjoint (M : set R) I) : ideal.comap (algebra_map R S) (ideal.map (algebra_map R S) I) = I := begin refine le_antisymm (λ a ha, _) ideal.le_comap_map, rw [ideal.mem_comap, mem_map_algebra_map_iff M S] at ha, obtain ⟨⟨b, s⟩, h⟩ := ha, have : (algebra_map R S) (a * ↑s - b) = 0 := by simpa [sub_eq_zero] using h, rw [← (algebra_map R S).map_zero, eq_iff_exists M S] at this, obtain ⟨c, hc⟩ := this, have : a * s ∈ I, { rw zero_mul at hc, let this : (a * ↑s - ↑b) * ↑c ∈ I := hc.symm ▸ I.zero_mem, cases hI.mem_or_mem this with h1 h2, { simpa using I.add_mem h1 b.2 }, { exfalso, refine hM ⟨c.2, h2⟩ } }, cases hI.mem_or_mem this with h1 h2, { exact h1 }, { exfalso, refine hM ⟨s.2, h2⟩ } end /-- If `S` is the localization of `R` at a submonoid, the ordering of ideals of `S` is embedded in the ordering of ideals of `R`. -/ def order_embedding : ideal S ↪o ideal R := { to_fun := λ J, ideal.comap (algebra_map R S) J, inj' := function.left_inverse.injective (map_comap M S), map_rel_iff' := λ J₁ J₂, ⟨λ hJ, (map_comap M S) J₁ ▸ (map_comap M S) J₂ ▸ ideal.map_mono hJ, ideal.comap_mono⟩ } /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its comap, see `le_rel_iso_of_prime` for the more general relation isomorphism -/ lemma is_prime_iff_is_prime_disjoint (J : ideal S) : J.is_prime ↔ (ideal.comap (algebra_map R S) J).is_prime ∧ disjoint (M : set R) ↑(ideal.comap (algebra_map R S) J) := begin split, { refine λ h, ⟨⟨_, _⟩, λ m hm, h.ne_top (ideal.eq_top_of_is_unit_mem _ hm.2 (map_units S ⟨m, hm.left⟩))⟩, { refine λ hJ, h.ne_top _, rw [eq_top_iff, ← (order_embedding M S).le_iff_le], exact le_of_eq hJ.symm }, { intros x y hxy, rw [ideal.mem_comap, ring_hom.map_mul] at hxy, exact h.mem_or_mem hxy } }, { refine λ h, ⟨λ hJ, h.left.ne_top (eq_top_iff.2 _), _⟩, { rwa [eq_top_iff, ← (order_embedding M S).le_iff_le] at hJ }, { intros x y hxy, obtain ⟨a, s, ha⟩ := mk'_surjective M x, obtain ⟨b, t, hb⟩ := mk'_surjective M y, have : mk' S (a * b) (s * t) ∈ J := by rwa [mk'_mul, ha, hb], rw [mk'_mem_iff, ← ideal.mem_comap] at this, replace this := h.left.mem_or_mem this, rw [ideal.mem_comap, ideal.mem_comap] at this, rwa [← ha, ← hb, mk'_mem_iff, mk'_mem_iff] } } end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its map, see `le_rel_iso_of_prime` for the more general relation isomorphism, and the reverse implication -/ lemma is_prime_of_is_prime_disjoint (I : ideal R) (hp : I.is_prime) (hd : disjoint (M : set R) ↑I) : (ideal.map (algebra_map R S) I).is_prime := begin rw [is_prime_iff_is_prime_disjoint M S, comap_map_of_is_prime_disjoint M S I hp hd], exact ⟨hp, hd⟩ end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M` -/ def order_iso_of_prime : {p : ideal S // p.is_prime} ≃o {p : ideal R // p.is_prime ∧ disjoint (M : set R) ↑p} := { to_fun := λ p, ⟨ideal.comap (algebra_map R S) p.1, (is_prime_iff_is_prime_disjoint M S p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map (algebra_map R S) p.1, is_prime_of_is_prime_disjoint M S p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap M S J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint M S I.1 I.2.1 I.2.2), map_rel_iff' := λ I I', ⟨λ h, (show I.val ≤ I'.val, from (map_comap M S I.val) ▸ (map_comap M S I'.val) ▸ (ideal.map_mono h)), λ h x hx, h hx⟩ } /-- `quotient_map` applied to maximal ideals of a localization is `surjective`. The quotient by a maximal ideal is a field, so inverses to elements already exist, and the localization necessarily maps the equivalence class of the inverse in the localization -/ lemma surjective_quotient_map_of_maximal_of_localization {I : ideal S} [I.is_prime] {J : ideal R} {H : J ≤ I.comap (algebra_map R S)} (hI : (I.comap (algebra_map R S)).is_maximal) : function.surjective (I.quotient_map (algebra_map R S) H) := begin intro s, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective s, obtain ⟨r, ⟨m, hm⟩, rfl⟩ := mk'_surjective M s, by_cases hM : (ideal.quotient.mk (I.comap (algebra_map R S))) m = 0, { have : I = ⊤, { rw ideal.eq_top_iff_one, rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_comap] at hM, convert I.mul_mem_right (mk' S 1 ⟨m, hm⟩) hM, rw [← mk'_eq_mul_mk'_one, mk'_self] }, exact ⟨0, eq_comm.1 (by simp [ideal.quotient.eq_zero_iff_mem, this])⟩ }, { rw ideal.quotient.maximal_ideal_iff_is_field_quotient at hI, obtain ⟨n, hn⟩ := hI.3 hM, obtain ⟨rn, rfl⟩ := ideal.quotient.mk_surjective n, refine ⟨(ideal.quotient.mk J) (r * rn), _⟩, -- The rest of the proof is essentially just algebraic manipulations to prove the equality rw ← ring_hom.map_mul at hn, replace hn := congr_arg (ideal.quotient_map I (algebra_map R S) le_rfl) hn, simp only [ring_hom.map_one, ideal.quotient_map_mk, ring_hom.map_mul] at hn, rw [ideal.quotient_map_mk, ← sub_eq_zero, ← ring_hom.map_sub, ideal.quotient.eq_zero_iff_mem, ← ideal.quotient.eq_zero_iff_mem, ring_hom.map_sub, sub_eq_zero, mk'_eq_mul_mk'_one], simp only [mul_eq_mul_left_iff, ring_hom.map_mul], exact or.inl (mul_left_cancel' (λ hn, hM (ideal.quotient.eq_zero_iff_mem.2 (ideal.mem_comap.2 (ideal.quotient.eq_zero_iff_mem.1 hn)))) (trans hn (by rw [← ring_hom.map_mul, ← mk'_eq_mul_mk'_one, mk'_self, ring_hom.map_one]))) } end end ideals variables (S) /-- Map from ideals of `R` to submodules of `S` induced by `f`. -/ -- This was previously a `has_coe` instance, but if `S = R` then this will loop. -- It could be a `has_coe_t` instance, but we keep it explicit here to avoid slowing down -- the rest of the library. def coe_submodule (I : ideal R) : submodule R S := submodule.map (algebra.linear_map R S) I lemma mem_coe_submodule (I : ideal R) {x : S} : x ∈ coe_submodule S I ↔ ∃ y : R, y ∈ I ∧ algebra_map R S y = x := iff.rfl variables {g : R →+* P} variables {T : submonoid P} (hy : M ≤ T.comap g) {Q : Type*} [comm_ring Q] variables [algebra P Q] [is_localization T Q] lemma map_smul (x : S) (z : R) : map Q g hy (z • x : S) = g z • map Q g hy x := by rw [algebra.smul_def, algebra.smul_def, ring_hom.map_mul, map_eq] section include M lemma is_noetherian_ring (h : is_noetherian_ring R) : is_noetherian_ring S := begin rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at h ⊢, exact order_embedding.well_founded ((is_localization.order_embedding M S).dual) h end end section integer_normalization open polynomial open_locale classical variables (M) {S} /-- `coeff_integer_normalization p` gives the coefficients of the polynomial `integer_normalization p` -/ noncomputable def coeff_integer_normalization (p : polynomial S) (i : ℕ) : R := if hi : i ∈ p.support then classical.some (classical.some_spec (exist_integer_multiples_of_finset M (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) else 0 lemma coeff_integer_normalization_of_not_mem_support (p : polynomial S) (i : ℕ) (h : coeff p i = 0) : coeff_integer_normalization M p i = 0 := by simp only [coeff_integer_normalization, h, mem_support_iff, eq_self_iff_true, not_true, ne.def, dif_neg, not_false_iff] lemma coeff_integer_normalization_mem_support (p : polynomial S) (i : ℕ) (h : coeff_integer_normalization M p i ≠ 0) : i ∈ p.support := begin contrapose h, rw [ne.def, not_not, coeff_integer_normalization, dif_neg h] end /-- `integer_normalization g` normalizes `g` to have integer coefficients by clearing the denominators -/ noncomputable def integer_normalization (p : polynomial S) : polynomial R := ∑ i in p.support, monomial i (coeff_integer_normalization M p i) @[simp] lemma integer_normalization_coeff (p : polynomial S) (i : ℕ) : (integer_normalization M p).coeff i = coeff_integer_normalization M p i := by simp [integer_normalization, coeff_monomial, coeff_integer_normalization_of_not_mem_support] {contextual := tt} lemma integer_normalization_spec (p : polynomial S) : ∃ (b : M), ∀ i, algebra_map R S ((integer_normalization M p).coeff i) = (b : R) • p.coeff i := begin use classical.some (exist_integer_multiples_of_finset M (p.support.image p.coeff)), intro i, rw [integer_normalization_coeff, coeff_integer_normalization], split_ifs with hi, { exact classical.some_spec (classical.some_spec (exist_integer_multiples_of_finset M (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) }, { convert (smul_zero _).symm, { apply ring_hom.map_zero }, { exact not_mem_support_iff.mp hi } } end lemma integer_normalization_map_to_map (p : polynomial S) : ∃ (b : M), (integer_normalization M p).map (algebra_map R S) = (b : R) • p := let ⟨b, hb⟩ := integer_normalization_spec M p in ⟨b, polynomial.ext (λ i, by { rw [coeff_map, coeff_smul], exact hb i })⟩ variables {R' : Type*} [comm_ring R'] lemma integer_normalization_eval₂_eq_zero (g : S →+* R') (p : polynomial S) {x : R'} (hx : eval₂ g x p = 0) : eval₂ (g.comp (algebra_map R S)) x (integer_normalization M p) = 0 := let ⟨b, hb⟩ := integer_normalization_map_to_map M p in trans (eval₂_map (algebra_map R S) g x).symm (by rw [hb, ← is_scalar_tower.algebra_map_smul S (b : R) p, eval₂_smul, hx, mul_zero]) lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra S R'] [is_scalar_tower R S R'] (p : polynomial S) {x : R'} (hx : aeval x p = 0) : aeval x (integer_normalization M p) = 0 := by rw [aeval_def, is_scalar_tower.algebra_map_eq R S R', integer_normalization_eval₂_eq_zero _ _ _ hx] end integer_normalization variables {R M} (S) {A K : Type*} [integral_domain A] lemma to_map_eq_zero_iff {x : R} (hM : M ≤ non_zero_divisors R) : algebra_map R S x = 0 ↔ x = 0 := begin rw ← (algebra_map R S).map_zero, split; intro h, { cases (eq_iff_exists M S).mp h with c hc, rw zero_mul at hc, exact hM c.2 x hc }, { rw h }, end protected lemma injective (hM : M ≤ non_zero_divisors R) : injective (algebra_map R S) := begin rw ring_hom.injective_iff (algebra_map R S), intros a ha, rwa to_map_eq_zero_iff S hM at ha end protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] (hM : M ≤ non_zero_divisors R) {x : R} (hx : x ∈ non_zero_divisors R) : algebra_map R S x ≠ 0 := map_ne_zero_of_mem_non_zero_divisors (is_localization.injective S hM) hx variables (S Q M) /-- Injectivity of a map descends to the map induced on localizations. -/ lemma map_injective_of_injective (hg : function.injective g) [is_localization (M.map g : submonoid P) Q] (hM : (M.map g : submonoid P) ≤ non_zero_divisors P) : function.injective (map Q g M.le_comap_map : S → Q) := begin rintros x y hxy, obtain ⟨a, b, rfl⟩ := mk'_surjective M x, obtain ⟨c, d, rfl⟩ := mk'_surjective M y, rw [map_mk' _ a b, map_mk' _ c d, mk'_eq_iff_eq] at hxy, refine mk'_eq_iff_eq.2 (congr_arg (algebra_map _ _) (hg _)), convert is_localization.injective _ hM hxy; simp, end variables (S) {Q M} /-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of non-zero elements is an integral domain. -/ def integral_domain_of_le_non_zero_divisors [algebra A S] {M : submonoid A} [is_localization M S] (hM : M ≤ non_zero_divisors A) : integral_domain S := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases surj M z with x hx, cases surj M w with y hy, have : z * w * algebra_map A S y.2 * algebra_map A S x.2 = algebra_map A S x.1 * algebra_map A S y.1, by rw [mul_assoc z, hy, ←hx]; ac_refl, rw [h, zero_mul, zero_mul, ← (algebra_map A S).map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff S hM).mp this.symm) with H H, { exact or.inl (eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (eq_zero_of_fst_eq_zero hy H) }, end, exists_pair_ne := ⟨(algebra_map A S) 0, (algebra_map A S) 1, λ h, zero_ne_one (is_localization.injective S hM h)⟩, .. ‹comm_ring S› } /-- The localization at of an integral domain to a set of non-zero elements is an integral domain -/ def integral_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) : integral_domain (localization M) := integral_domain_of_le_non_zero_divisors _ hM /-- The localization of an integral domain at the complement of a prime ideal is an integral domain. -/ instance integral_domain_of_local_at_prime {P : ideal A} (hp : P.is_prime) : integral_domain (localization.at_prime P) := integral_domain_localization (le_non_zero_divisors_of_domain (by simpa only [] using P.zero_mem)) namespace at_prime variables (I : ideal R) [hI : I.is_prime] [is_localization.at_prime S I] include hI lemma is_unit_to_map_iff (x : R) : is_unit ((algebra_map R S) x) ↔ x ∈ I.prime_compl := ⟨λ h hx, (is_prime_of_is_prime_disjoint I.prime_compl S I hI disjoint_compl_left).ne_top $ (ideal.map (algebra_map R S) I).eq_top_of_is_unit_mem (ideal.mem_map_of_mem _ hx) h, λ h, map_units S ⟨x, h⟩⟩ -- Can't use typeclasses to infer the `local_ring` instance, so use an `opt_param` instead -- (since `local_ring` is a `Prop`, there should be no unification issues.) lemma to_map_mem_maximal_iff (x : R) (h : _root_.local_ring S := local_ring S I) : algebra_map R S x ∈ local_ring.maximal_ideal S ↔ x ∈ I := not_iff_not.mp $ by simpa only [@local_ring.mem_maximal_ideal S, mem_nonunits_iff, not_not] using is_unit_to_map_iff S I x lemma is_unit_mk'_iff (x : R) (y : I.prime_compl) : is_unit (mk' S x y) ↔ x ∈ I.prime_compl := ⟨λ h hx, mk'_mem_iff.mpr ((to_map_mem_maximal_iff S I x).mpr hx) h, λ h, is_unit_iff_exists_inv.mpr ⟨mk' S ↑y ⟨x, h⟩, mk'_mul_mk'_eq_one ⟨x, h⟩ y⟩⟩ lemma mk'_mem_maximal_iff (x : R) (y : I.prime_compl) (h : _root_.local_ring S := local_ring S I) : mk' S x y ∈ local_ring.maximal_ideal S ↔ x ∈ I := not_iff_not.mp $ by simpa only [@local_ring.mem_maximal_ideal S, mem_nonunits_iff, not_not] using is_unit_mk'_iff S I x y end at_prime end is_localization namespace localization open is_localization local attribute [instance] classical.prop_decidable variables (I : ideal R) [hI : I.is_prime] include hI variables {I} /-- The unique maximal ideal of the localization at `I.prime_compl` lies over the ideal `I`. -/ lemma at_prime.comap_maximal_ideal : ideal.comap (algebra_map R (localization.at_prime I)) (local_ring.maximal_ideal (localization I.prime_compl)) = I := ideal.ext $ λ x, by simpa only [ideal.mem_comap] using at_prime.to_map_mem_maximal_iff _ I x /-- The image of `I` in the localization at `I.prime_compl` is a maximal ideal, and in particular it is the unique maximal ideal given by the local ring structure `at_prime.local_ring` -/ lemma at_prime.map_eq_maximal_ideal : ideal.map (algebra_map R (localization.at_prime I)) I = (local_ring.maximal_ideal (localization I.prime_compl)) := begin convert congr_arg (ideal.map _) at_prime.comap_maximal_ideal.symm, rw map_comap I.prime_compl end lemma le_comap_prime_compl_iff {J : ideal P} [hJ : J.is_prime] {f : R →+* P} : I.prime_compl ≤ J.prime_compl.comap f ↔ J.comap f ≤ I := ⟨λ h x hx, by { contrapose! hx, exact h hx }, λ h x hx hfxJ, hx (h hfxJ)⟩ variables (I) /-- For a ring hom `f : R →+* S` and a prime ideal `J` in `S`, the induced ring hom from the localization of `R` at `J.comap f` to the localization of `S` at `J`. To make this definition more flexible, we allow any ideal `I` of `R` as input, together with a proof that `I = J.comap f`. This can be useful when `I` is not definitionally equal to `J.comap f`. -/ noncomputable def local_ring_hom (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) : localization.at_prime I →+* localization.at_prime J := is_localization.map (localization.at_prime J) f (le_comap_prime_compl_iff.mpr (ge_of_eq hIJ)) lemma local_ring_hom_to_map (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) (x : R) : local_ring_hom I J f hIJ (algebra_map _ _ x) = algebra_map _ _ (f x) := map_eq _ _ lemma local_ring_hom_mk' (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) (x : R) (y : I.prime_compl) : local_ring_hom I J f hIJ (is_localization.mk' _ x y) = is_localization.mk' (localization.at_prime J) (f x) (⟨f y, le_comap_prime_compl_iff.mpr (ge_of_eq hIJ) y.2⟩ : J.prime_compl) := map_mk' _ _ _ instance is_local_ring_hom_local_ring_hom (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) : is_local_ring_hom (local_ring_hom I J f hIJ) := is_local_ring_hom.mk $ λ x hx, begin rcases is_localization.mk'_surjective I.prime_compl x with ⟨r, s, rfl⟩, rw local_ring_hom_mk' at hx, rw at_prime.is_unit_mk'_iff at hx ⊢, exact λ hr, hx ((set_like.ext_iff.mp hIJ r).mp hr), end lemma local_ring_hom_unique (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) {j : localization.at_prime I →+* localization.at_prime J} (hj : ∀ x : R, j (algebra_map _ _ x) = algebra_map _ _ (f x)) : local_ring_hom I J f hIJ = j := map_unique _ _ hj @[simp] lemma local_ring_hom_id : local_ring_hom I I (ring_hom.id R) (ideal.comap_id I).symm = ring_hom.id _ := local_ring_hom_unique _ _ _ _ (λ x, rfl) @[simp] lemma local_ring_hom_comp {S : Type*} [comm_ring S] (J : ideal S) [hJ : J.is_prime] (K : ideal P) [hK : K.is_prime] (f : R →+* S) (hIJ : I = J.comap f) (g : S →+* P) (hJK : J = K.comap g) : local_ring_hom I K (g.comp f) (by rw [hIJ, hJK, ideal.comap_comap f g]) = (local_ring_hom J K g hJK).comp (local_ring_hom I J f hIJ) := local_ring_hom_unique _ _ _ _ (λ r, by simp only [function.comp_app, ring_hom.coe_comp, local_ring_hom_to_map]) end localization open is_localization /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma localization_map_bijective_of_field {R Rₘ : Type*} [integral_domain R] [comm_ring Rₘ] {M : submonoid R} (hM : (0 : R) ∉ M) (hR : is_field R) [algebra R Rₘ] [is_localization M Rₘ] : function.bijective (algebra_map R Rₘ) := begin refine ⟨is_localization.injective _ (le_non_zero_divisors_of_domain hM), λ x, _⟩, obtain ⟨r, ⟨m, hm⟩, rfl⟩ := mk'_surjective M x, obtain ⟨n, hn⟩ := hR.mul_inv_cancel (λ hm0, hM (hm0 ▸ hm) : m ≠ 0), exact ⟨r * n, by erw [eq_mk'_iff_mul_eq, ← ring_hom.map_mul, mul_assoc, mul_comm n, hn, mul_one]⟩ end variables (R) {A : Type*} [integral_domain A] variables (K : Type*) /-- `is_fraction_ring R K` states `K` is the field of fractions of an integral domain `R`. -/ -- TODO: should this extend `algebra` instead of assuming it? abbreviation is_fraction_ring [comm_ring K] [algebra R K] := is_localization (non_zero_divisors R) K /-- The cast from `int` to `rat` as a `fraction_ring`. -/ instance rat.is_fraction_ring : is_fraction_ring ℤ ℚ := { map_units := begin rintro ⟨x, hx⟩, rw mem_non_zero_divisors_iff_ne_zero at hx, simpa only [ring_hom.eq_int_cast, is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx, end, surj := begin rintro ⟨n, d, hd, h⟩, refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩, rwa [mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos] end, eq_iff_exists := begin intros x y, rw [ring_hom.eq_int_cast, ring_hom.eq_int_cast, int.cast_inj], refine ⟨by { rintro rfl, use 1 }, _⟩, rintro ⟨⟨c, hc⟩, h⟩, apply int.eq_of_mul_eq_mul_right _ h, rwa mem_non_zero_divisors_iff_ne_zero at hc, end } namespace is_fraction_ring variables {R K} section comm_ring variables [comm_ring K] [algebra R K] [is_fraction_ring R K] [algebra A K] [is_fraction_ring A K] lemma to_map_eq_zero_iff {x : R} : algebra_map R K x = 0 ↔ x = 0 := to_map_eq_zero_iff _ (le_of_eq rfl) variables (R K) protected theorem injective : function.injective (algebra_map R K) := is_localization.injective _ (le_of_eq rfl) variables {R K} protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] {x : R} (hx : x ∈ non_zero_divisors R) : algebra_map R K x ≠ 0 := is_localization.to_map_ne_zero_of_mem_non_zero_divisors _ (le_refl _) hx variables (A) /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an integral domain. -/ def to_integral_domain : integral_domain K := integral_domain_of_le_non_zero_divisors K (le_refl (non_zero_divisors A)) local attribute [instance] classical.dec_eq /-- The inverse of an element in the field of fractions of an integral domain. -/ protected noncomputable def inv (z : K) : K := if h : z = 0 then 0 else mk' K ↑(sec (non_zero_divisors A) z).2 ⟨(sec _ z).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ eq_zero_of_fst_eq_zero (sec_spec (non_zero_divisors A) z) h0⟩ protected lemma mul_inv_cancel (x : K) (hx : x ≠ 0) : x * is_fraction_ring.inv A x = 1 := show x * dite _ _ _ = 1, by rw [dif_neg hx, ←is_unit.mul_left_inj (map_units K ⟨(sec _ x).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ eq_zero_of_fst_eq_zero (sec_spec (non_zero_divisors A) x) h0⟩), one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (mk'_sec _ x).symm /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a field. -/ noncomputable def to_field : field K := { inv := is_fraction_ring.inv A, mul_inv_cancel := is_fraction_ring.mul_inv_cancel A, inv_zero := dif_pos rfl, .. to_integral_domain A } end comm_ring variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L] [algebra A K] [is_fraction_ring A K] {g : A →+* L} lemma mk'_mk_eq_div {r s} (hs : s ∈ non_zero_divisors A) : mk' K r ⟨s, hs⟩ = algebra_map A K r / algebra_map A K s := mk'_eq_iff_eq_mul.2 $ (div_mul_cancel (algebra_map A K r) (is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hs)).symm lemma mk'_eq_div {r} (s : non_zero_divisors A) : mk' K r s = algebra_map A K r / algebra_map A K s := mk'_mk_eq_div s.2 lemma is_unit_map_of_injective (hg : function.injective g) (y : non_zero_divisors A) : is_unit (g y) := is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg y.2 /-- Given an integral domain `A` with field of fractions `K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (hg : injective g) : K →+* L := lift $ λ (y : non_zero_divisors A), is_unit_map_of_injective hg y /-- Given an integral domain `A` with field of fractions `K`, and an injective ring hom `g : A →+* L` where `L` is a field, field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all `x : A, y ∈ non_zero_divisors A`. -/ @[simp] lemma lift_mk' (hg : injective g) (x) (y : non_zero_divisors A) : lift hg (mk' K x y) = g x / g y := begin erw lift_mk' (is_unit_map_of_injective hg), erw submonoid.localization_map.mul_inv_left (λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from is_unit_map_of_injective hg y), exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg y.2)).symm, end /-- Given integral domains `A, B` with fields of fractions `K`, `L` and an injective ring hom `j : A →+* B`, we get a field hom sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map [algebra B L] [is_fraction_ring B L] {j : A →+* B} (hj : injective j) : K →+* L := map L j (show non_zero_divisors A ≤ (non_zero_divisors B).comap j, from λ y hy, map_mem_non_zero_divisors hj hy) /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of fields of fractions `K ≃+* L`. -/ noncomputable def field_equiv_of_ring_equiv [algebra B L] [is_fraction_ring B L] (h : A ≃+* B) : K ≃+* L := ring_equiv_of_ring_equiv K L h begin ext b, show b ∈ h.to_equiv '' _ ↔ _, erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero], exact h.symm.map_ne_zero_iff end lemma integer_normalization_eq_zero_iff {p : polynomial K} : integer_normalization (non_zero_divisors A) p = 0 ↔ p = 0 := begin refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm), obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec _ p, split; intros h i, { apply to_map_eq_zero_iff.mp, rw [hb i, h i], apply smul_zero, assumption }, { have hi := h i, rw [polynomial.coeff_zero, ← @to_map_eq_zero_iff A _ K, hb i, algebra.smul_def] at hi, apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi), intro h, apply mem_non_zero_divisors_iff_ne_zero.mp nonzero, exact to_map_eq_zero_iff.mp h } end /-- A field is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/ lemma comap_is_algebraic_iff [algebra A L] [algebra K L] [is_scalar_tower A K L] : algebra.is_algebraic A L ↔ algebra.is_algebraic K L := begin split; intros h x; obtain ⟨p, hp, px⟩ := h x, { refine ⟨p.map (algebra_map A K), λ h, hp (polynomial.ext (λ i, _)), _⟩, { have : algebra_map A K (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]), exact to_map_eq_zero_iff.mp this }, { rwa is_scalar_tower.aeval_apply _ K at px } }, { exact ⟨integer_normalization _ p, mt integer_normalization_eq_zero_iff.mp hp, integer_normalization_aeval_eq_zero _ p px⟩ }, end section num_denom variables (A) [unique_factorization_monoid A] lemma exists_reduced_fraction (x : K) : ∃ (a : A) (b : non_zero_divisors A), (∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ mk' K a b = x := begin obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := exists_integer_multiple (non_zero_divisors A) x, obtain ⟨a', b', c', no_factor, rfl, rfl⟩ := unique_factorization_monoid.exists_reduced_factors' a b (mem_non_zero_divisors_iff_ne_zero.mp b_nonzero), obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero, refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩, refine mul_left_cancel' (is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors b_nonzero) _, simp only [subtype.coe_mk, ring_hom.map_mul, algebra.smul_def] at *, erw [←hab, mul_assoc, mk'_spec' _ a' ⟨b', b'_nonzero⟩], end /-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/ noncomputable def num (x : K) : A := classical.some (exists_reduced_fraction A x) /-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/ noncomputable def denom (x : K) : non_zero_divisors A := classical.some (classical.some_spec (exists_reduced_fraction A x)) lemma num_denom_reduced (x : K) : ∀ {d}, d ∣ num A x → d ∣ denom A x → is_unit d := (classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).1 @[simp] lemma mk'_num_denom (x : K) : mk' K (num A x) (denom A x) = x := (classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).2 variables {A} lemma num_mul_denom_eq_num_iff_eq {x y : K} : x * algebra_map A K (denom A y) = algebra_map A K (num A y) ↔ x = y := ⟨λ h, by simpa only [mk'_num_denom] using eq_mk'_iff_mul_eq.mpr h, λ h, eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom])⟩ lemma num_mul_denom_eq_num_iff_eq' {x y : K} : y * algebra_map A K (denom A x) = algebra_map A K (num A x) ↔ x = y := ⟨λ h, by simpa only [eq_comm, mk'_num_denom] using eq_mk'_iff_mul_eq.mpr h, λ h, eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom])⟩ lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : K} : num A y * denom A x = num A x * denom A y ↔ x = y := ⟨λ h, by simpa only [mk'_num_denom] using mk'_eq_of_eq h, λ h, by rw h⟩ lemma eq_zero_of_num_eq_zero {x : K} (h : num A x = 0) : x = 0 := num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero]) lemma is_integer_of_is_unit_denom {x : K} (h : is_unit (denom A x : A)) : is_integer A x := begin cases h with d hd, have d_ne_zero : algebra_map A K (denom A x) ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors (denom A x).2, use ↑d⁻¹ * num A x, refine trans _ (mk'_num_denom A x), rw [ring_hom.map_mul, ring_hom.map_units_inv, hd], apply mul_left_cancel' d_ne_zero, rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, mk'_spec'] end lemma is_unit_denom_of_num_eq_zero {x : K} (h : num A x = 0) : is_unit (denom A x : A) := num_denom_reduced A x (h.symm ▸ dvd_zero _) (dvd_refl _) end num_denom end is_fraction_ring section algebra section is_integral variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] variables [algebra R Rₘ] [is_localization M Rₘ] variables [algebra S Sₘ] [is_localization (algebra.algebra_map_submonoid S M) Sₘ] section variables (S M) /-- Definition of the natural algebra induced by the localization of an algebra. Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`, let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`. Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes, where `localization_map.map_comp` gives the commutativity of the underlying maps -/ noncomputable def localization_algebra : algebra Rₘ Sₘ := (map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) : Rₘ →+* Sₘ).to_algebra end lemma algebra_map_mk' (r : R) (m : M) : (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) (mk' Rₘ r m) = mk' Sₘ (algebra_map R S r) ⟨algebra_map R S m, algebra.mem_algebra_map_submonoid_of_mem m⟩ := map_mk' _ _ _ variables (Rₘ Sₘ) /-- Injectivity of the underlying `algebra_map` descends to the algebra induced by localization. -/ lemma localization_algebra_injective (hRS : function.injective (algebra_map R S)) (hM : algebra.algebra_map_submonoid S M ≤ non_zero_divisors S) : function.injective (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) := is_localization.map_injective_of_injective M Rₘ Sₘ hRS hM variables {Rₘ Sₘ} open polynomial lemma ring_hom.is_integral_elem_localization_at_leading_coeff {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (x : S) (p : polynomial R) (hf : p.eval₂ f x = 0) (M : submonoid R) (hM : p.leading_coeff ∈ M) {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] [algebra R Rₘ] [is_localization M Rₘ] [algebra S Sₘ] [is_localization (M.map f : submonoid S) Sₘ] : (map Sₘ f M.le_comap_map : Rₘ →+* _).is_integral_elem (algebra_map S Sₘ x) := begin by_cases triv : (1 : Rₘ) = 0, { exact ⟨0, ⟨trans leading_coeff_zero triv.symm, eval₂_zero _ _⟩⟩ }, haveI : nontrivial Rₘ := nontrivial_of_ne 1 0 triv, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.mp (map_units Rₘ ⟨p.leading_coeff, hM⟩), refine ⟨(p.map (algebra_map R Rₘ)) * C b, ⟨_, _⟩⟩, { refine monic_mul_C_of_leading_coeff_mul_eq_one _, rwa leading_coeff_map_of_leading_coeff_ne_zero (algebra_map R Rₘ), refine λ hfp, zero_ne_one (trans (zero_mul b).symm (hfp ▸ hb) : (0 : Rₘ) = 1) }, { refine eval₂_mul_eq_zero_of_left _ _ _ _, erw [eval₂_map, is_localization.map_comp, ← hom_eval₂ _ f (algebra_map S Sₘ) x], exact trans (congr_arg (algebra_map S Sₘ) hf) (ring_hom.map_zero _) } end /-- Given a particular witness to an element being algebraic over an algebra `R → S`, We can localize to a submonoid containing the leading coefficient to make it integral. Explicitly, the map between the localizations will be an integral ring morphism -/ theorem is_integral_localization_at_leading_coeff {x : S} (p : polynomial R) (hp : aeval x p = 0) (hM : p.leading_coeff ∈ M) : (map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) : Rₘ →+* _).is_integral_elem (algebra_map S Sₘ x) := (algebra_map R S).is_integral_elem_localization_at_leading_coeff x p hp M hM /-- If `R → S` is an integral extension, `M` is a submonoid of `R`, `Rₘ` is the localization of `R` at `M`, and `Sₘ` is the localization of `S` at the image of `M` under the extension map, then the induced map `Rₘ → Sₘ` is also an integral extension -/ theorem is_integral_localization (H : algebra.is_integral R S) : (map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) : Rₘ →+* _).is_integral := begin intro x, by_cases triv : (1 : R) = 0, { have : (1 : Rₘ) = 0 := by convert congr_arg (algebra_map R Rₘ) triv; simp, exact ⟨0, ⟨trans leading_coeff_zero this.symm, eval₂_zero _ _⟩⟩ }, { haveI : nontrivial R := nontrivial_of_ne 1 0 triv, obtain ⟨⟨s, ⟨u, hu⟩⟩, hx⟩ := surj (algebra.algebra_map_submonoid S M) x, obtain ⟨v, hv⟩ := hu, obtain ⟨v', hv'⟩ := is_unit_iff_exists_inv'.1 (map_units Rₘ ⟨v, hv.1⟩), refine @is_integral_of_is_integral_mul_unit Rₘ _ _ _ (localization_algebra M S) x (algebra_map S Sₘ u) v' _ _, { replace hv' := congr_arg (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) hv', rw [ring_hom.map_mul, ring_hom.map_one, ← ring_hom.comp_apply _ (algebra_map R Rₘ)] at hv', erw is_localization.map_comp at hv', exact hv.2 ▸ hv' }, { obtain ⟨p, hp⟩ := H s, exact hx.symm ▸ is_integral_localization_at_leading_coeff p hp.2 (hp.1.symm ▸ M.one_mem) } } end lemma is_integral_localization' {R S : Type*} [comm_ring R] [comm_ring S] {f : R →+* S} (hf : f.is_integral) (M : submonoid R) : (map (localization (M.map (f : R →* S))) f M.le_comap_map : localization M →+* _).is_integral := @is_integral_localization R _ M S _ f.to_algebra _ _ _ _ _ _ _ _ hf end is_integral namespace integral_closure variables {L : Type*} [field K] [field L] [algebra A K] [is_fraction_ring A K] open algebra /-- If the field `L` is an algebraic extension of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ lemma is_fraction_ring_of_algebraic [algebra A L] (alg : is_algebraic A L) (inj : ∀ x, algebra_map A L x = 0 → x = 0) : is_fraction_ring (integral_closure A L) L := ⟨(λ ⟨⟨y, integral⟩, nonzero⟩, have y ≠ 0 := λ h, mem_non_zero_divisors_iff_ne_zero.mp nonzero (subtype.ext_iff_val.mpr h), show is_unit y, from ⟨⟨y, y⁻¹, mul_inv_cancel this, inv_mul_cancel this⟩, rfl⟩), (λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in ⟨⟨x, ⟨y, mem_non_zero_divisors_iff_ne_zero.mpr hy⟩⟩, hxy⟩), (λ x y, ⟨λ (h : x.1 = y.1), ⟨1, by simpa using subtype.ext_iff_val.mpr h⟩, λ ⟨c, hc⟩, congr_arg (algebra_map _ L) (mul_right_cancel' (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc)⟩)⟩ variables (K L) /-- If the field `L` is a finite extension of the fraction field of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ lemma is_fraction_ring_of_finite_extension [algebra A L] [algebra K L] [is_scalar_tower A K L] [finite_dimensional K L] : is_fraction_ring (integral_closure A L) L := is_fraction_ring_of_algebraic (is_fraction_ring.comap_is_algebraic_iff.mpr (is_algebraic_of_finite : is_algebraic K L)) (λ x hx, is_fraction_ring.to_map_eq_zero_iff.mp ((algebra_map K L).map_eq_zero.mp $ (is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx)) end integral_closure end algebra variables (A) /-- The fraction field of an integral domain as a quotient type. -/ @[reducible] def fraction_ring := localization (non_zero_divisors A) namespace fraction_ring variables {A} noncomputable instance : field (fraction_ring A) := is_fraction_ring.to_field A @[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) = (algebra_map _ _ r / algebra_map A _ s : fraction_ring A) := by rw [localization.mk_eq_mk', is_fraction_ring.mk'_eq_div] variables (A) /-- Given an integral domain `A` and a localization map to a field of fractions `f : A →+* K`, we get an `A`-isomorphism between the field of fractions of `A` as a quotient type and `K`. -/ noncomputable def alg_equiv (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] : fraction_ring A ≃ₐ[A] K := localization.alg_equiv (non_zero_divisors A) K end fraction_ring
967f61b475be48915e9af7c6ce6cea1ca3453147
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/Group/images.lean
a7c6d9101f729ce7fb2d7c7974519e30690e95af
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,377
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Group.abelian import category_theory.limits.shapes.images /-! # The category of commutative additive groups has images. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Note that we don't need to register any of the constructions here as instances, because we get them from the fact that `AddCommGroup` is an abelian category. -/ open category_theory open category_theory.limits universe u namespace AddCommGroup -- Note that because `injective_of_mono` is currently only proved in `Type 0`, -- we restrict to the lowest universe here for now. variables {G H : AddCommGroup.{0}} (f : G ⟶ H) local attribute [ext] subtype.ext_val section -- implementation details of `has_image` for AddCommGroup; use the API, not these /-- the image of a morphism in AddCommGroup is just the bundling of `add_monoid_hom.range f` -/ def image : AddCommGroup := AddCommGroup.of (add_monoid_hom.range f) /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ H := f.range.subtype instance : mono (image.ι f) := concrete_category.mono_of_injective (image.ι f) subtype.val_injective /-- the corestriction map to the image -/ def factor_thru_image : G ⟶ image f := f.range_restrict lemma image.fac : factor_thru_image f ≫ image.ι f = f := by { ext, refl, } local attribute [simp] image.fac variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := { to_fun := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I), map_zero' := begin haveI := F'.m_mono, apply injective_of_mono F'.m, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, add_monoid_hom.map_zero], exact (classical.indefinite_description (λ y, f y = 0) _).2, end, map_add' := begin intros x y, haveI := F'.m_mono, apply injective_of_mono F'.m, rw [add_monoid_hom.map_add], change (F'.e ≫ F'.m) _ = (F'.e ≫ F'.m) _ + (F'.e ≫ F'.m) _, rw [F'.fac], rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, refl, end, } lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := begin ext x, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, (classical.indefinite_description _ x.2).2], refl, end end /-- the factorisation of any morphism in AddCommGroup through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := factor_thru_image f } /-- the factorisation of any morphism in AddCommGroup through a mono has the universal property of the image. -/ noncomputable def is_image : is_image (mono_factorisation f) := { lift := image.lift, lift_fac' := image.lift_fac } /-- The categorical image of a morphism in `AddCommGroup` agrees with the usual group-theoretical range. -/ noncomputable def image_iso_range {G H : AddCommGroup.{0}} (f : G ⟶ H) : limits.image f ≅ AddCommGroup.of f.range := is_image.iso_ext (image.is_image f) (is_image f) end AddCommGroup
0b89a0679849dedfbff65f5cdefc13e6e849ae66
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/constantCompilerBug.lean
d11a6e821852ab32e64a41094f637d169a183003
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
273
lean
import Init.Lean new_frontend open Lean open Lean.Parser def regBlaParserAttribute : IO Unit := registerBuiltinDynamicParserAttribute (mkNameSimple "blaParser") (mkNameSimple "bla") @[inline] def parser : Parser := categoryParser (mkNameSimple "bla") 0 #check @parser
9c501502dabfe2b2591384adf6699bac3720ad6d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/dynamics/flow.lean
14000867f74f3458fe45fc8fe7356bd5a5d7f8d0
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,257
lean
/- Copyright (c) 2020 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo -/ import topology.algebra.group.basic import logic.function.iterate /-! # Flows and invariant sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines a flow on a topological space `α` by a topological monoid `τ` as a continuous monoid-act of `τ` on `α`. Anticipating the cases where `τ` is one of `ℕ`, `ℤ`, `ℝ⁺`, or `ℝ`, we use additive notation for the monoids, though the definition does not require commutativity. A subset `s` of `α` is invariant under a family of maps `ϕₜ : α → α` if `ϕₜ s ⊆ s` for all `t`. In many cases `ϕ` will be a flow on `α`. For the cases where `ϕ` is a flow by an ordered (additive, commutative) monoid, we additionally define forward invariance, where `t` ranges over those elements which are nonnegative. Additionally, we define such constructions as the restriction of a flow onto an invariant subset, and the time-reveral of a flow by a group. -/ open set function filter /-! ### Invariant sets -/ section invariant variables {τ : Type*} {α : Type*} /-- A set `s ⊆ α` is invariant under `ϕ : τ → α → α` if `ϕ t s ⊆ s` for all `t` in `τ`. -/ def is_invariant (ϕ : τ → α → α) (s : set α): Prop := ∀ t, maps_to (ϕ t) s s variables (ϕ : τ → α → α) (s : set α) lemma is_invariant_iff_image : is_invariant ϕ s ↔ ∀ t, ϕ t '' s ⊆ s := by simp_rw [is_invariant, maps_to'] /-- A set `s ⊆ α` is forward-invariant under `ϕ : τ → α → α` if `ϕ t s ⊆ s` for all `t ≥ 0`. -/ def is_fw_invariant [preorder τ] [has_zero τ] (ϕ : τ → α → α) (s : set α): Prop := ∀ ⦃t⦄, 0 ≤ t → maps_to (ϕ t) s s lemma is_invariant.is_fw_invariant [preorder τ] [has_zero τ] {ϕ : τ → α → α} {s : set α} (h : is_invariant ϕ s) : is_fw_invariant ϕ s := λ t ht, h t /-- If `τ` is a `canonically_ordered_add_monoid` (e.g., `ℕ` or `ℝ≥0`), then the notions `is_fw_invariant` and `is_invariant` are equivalent. -/ lemma is_fw_invariant.is_invariant [canonically_ordered_add_monoid τ] {ϕ : τ → α → α} {s : set α} (h : is_fw_invariant ϕ s) : is_invariant ϕ s := λ t, h (zero_le t) /-- If `τ` is a `canonically_ordered_add_monoid` (e.g., `ℕ` or `ℝ≥0`), then the notions `is_fw_invariant` and `is_invariant` are equivalent. -/ lemma is_fw_invariant_iff_is_invariant [canonically_ordered_add_monoid τ] {ϕ : τ → α → α} {s : set α} : is_fw_invariant ϕ s ↔ is_invariant ϕ s := ⟨is_fw_invariant.is_invariant, is_invariant.is_fw_invariant⟩ end invariant /-! ### Flows -/ /-- A flow on a topological space `α` by an a additive topological monoid `τ` is a continuous monoid action of `τ` on `α`.-/ structure flow (τ : Type*) [topological_space τ] [add_monoid τ] [has_continuous_add τ] (α : Type*) [topological_space α] := (to_fun : τ → α → α) (cont' : continuous (uncurry to_fun)) (map_add' : ∀ t₁ t₂ x, to_fun (t₁ + t₂) x = to_fun t₁ (to_fun t₂ x)) (map_zero' : ∀ x, to_fun 0 x = x) namespace flow variables {τ : Type*} [add_monoid τ] [topological_space τ] [has_continuous_add τ] {α : Type*} [topological_space α] (ϕ : flow τ α) instance : inhabited (flow τ α) := ⟨{ to_fun := λ _ x, x, cont' := continuous_snd, map_add' := λ _ _ _, rfl, map_zero' := λ _, rfl }⟩ instance : has_coe_to_fun (flow τ α) (λ _, τ → α → α) := ⟨flow.to_fun⟩ @[ext] lemma ext : ∀ {ϕ₁ ϕ₂ : flow τ α}, (∀ t x, ϕ₁ t x = ϕ₂ t x) → ϕ₁ = ϕ₂ | ⟨f₁, _, _, _⟩ ⟨f₂, _, _, _⟩ h := by { congr, funext, exact h _ _ } @[continuity] protected lemma continuous {β : Type*} [topological_space β] {t : β → τ} (ht : continuous t) {f : β → α} (hf : continuous f) : continuous (λ x, ϕ (t x) (f x)) := ϕ.cont'.comp (ht.prod_mk hf) alias flow.continuous ← _root_.continuous.flow lemma map_add (t₁ t₂ : τ) (x : α) : ϕ (t₁ + t₂) x = ϕ t₁ (ϕ t₂ x) := ϕ.map_add' _ _ _ @[simp] lemma map_zero : ϕ 0 = id := funext ϕ.map_zero' lemma map_zero_apply (x : α) : ϕ 0 x = x := ϕ.map_zero' x /-- Iterations of a continuous function from a topological space `α` to itself defines a semiflow by `ℕ` on `α`. -/ def from_iter {g : α → α} (h : continuous g) : flow ℕ α := { to_fun := λ n x, g^[n] x, cont' := continuous_uncurry_of_discrete_topology_left (continuous.iterate h), map_add' := iterate_add_apply _, map_zero' := λ x, rfl } /-- Restriction of a flow onto an invariant set. -/ def restrict {s : set α} (h : is_invariant ϕ s) : flow τ ↥s := { to_fun := λ t, (h t).restrict _ _ _, cont' := (ϕ.continuous continuous_fst continuous_subtype_coe.snd').subtype_mk _, map_add' := λ _ _ _, subtype.ext (map_add _ _ _ _), map_zero' := λ _, subtype.ext (map_zero_apply _ _)} end flow namespace flow variables {τ : Type*} [add_comm_group τ] [topological_space τ] [topological_add_group τ] {α : Type*} [topological_space α] (ϕ : flow τ α) lemma is_invariant_iff_image_eq (s : set α) : is_invariant ϕ s ↔ ∀ t, ϕ t '' s = s := (is_invariant_iff_image _ _).trans (iff.intro (λ h t, subset.antisymm (h t) (λ _ hx, ⟨_, h (-t) ⟨_, hx, rfl⟩, by simp [← map_add]⟩)) (λ h t, by rw h t)) /-- The time-reversal of a flow `ϕ` by a (commutative, additive) group is defined `ϕ.reverse t x = ϕ (-t) x`. -/ def reverse : flow τ α := { to_fun := λ t, ϕ (-t), cont' := ϕ.continuous continuous_fst.neg continuous_snd, map_add' := λ _ _ _, by rw [neg_add, map_add], map_zero' := λ _, by rw [neg_zero, map_zero_apply] } /-- The map `ϕ t` as a homeomorphism. -/ def to_homeomorph (t : τ) : α ≃ₜ α := { to_fun := ϕ t, inv_fun := ϕ (-t), left_inv := λ x, by rw [← map_add, neg_add_self, map_zero_apply], right_inv := λ x, by rw [← map_add, add_neg_self, map_zero_apply] } lemma image_eq_preimage (t : τ) (s : set α) : ϕ t '' s = ϕ (-t) ⁻¹' s := (ϕ.to_homeomorph t).to_equiv.image_eq_preimage s end flow
431dae6d63a75c3f29353d41880ba83843cbc74c
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/pending/default.lean
0432b5b274dbad595a4855e1b40653699609c2eb
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
106
lean
/- Temporary space for definitions pending merges to the lean repository -/ attribute [simp] nat.div_self
577e1989c62dc1f20704904c55cfebc88ab60a3f
159fed64bfae88f3b6a6166836d6278f953bcbf9
/Structure/Generic/Lemmas/DerivedFunctors.lean
7b79c816b0152b79e8473d5c3c5d7415939551b7
[ "MIT" ]
permissive
SReichelt/lean4-experiments
3e56830c8b2fbe3814eda071c48e3c8810d254a8
ff55357a01a34a91bf670d712637480089085ee4
refs/heads/main
1,683,977,454,907
1,622,991,121,000
1,622,991,121,000
340,765,677
2
0
null
null
null
null
UTF-8
Lean
false
false
12,967
lean
import Structure.Generic.Axioms.Universes import Structure.Generic.Axioms.AbstractFunctors set_option autoBoundImplicitLocal false --set_option pp.universes true namespace HasLinearFunOp variable {U : Universe} [HasInternalFunctors U] [h : HasLinearFunOp U] -- The "swap" functor swaps the arguments of a nested functor. Its plain version `swapFun` actually -- just fixes the second argument. def swapIsFun {α β γ : U} (F : α ⟶' β ⟶ γ) (b : β) : HasExternalFunctors.IsFun (λ a : α => F a b) := h.compIsFun F (appFun' b γ) def swapFun' {α β γ : U} (F : α ⟶' β ⟶ γ) (b : β) : α ⟶' γ := BundledFunctor.mkFun (swapIsFun F b) def swapFun {α β γ : U} (F : α ⟶ β ⟶ γ) (b : β) : α ⟶ γ := HasInternalFunctors.fromBundled (swapFun' (HasInternalFunctors.toBundled F) b) @[simp] theorem swapFun.eff {α β γ : U} (F : α ⟶ β ⟶ γ) (b : β) (a : α) : (swapFun F b) a = F a b := by apply HasInternalFunctors.fromBundled.eff theorem swapFunFun.def {α β γ : U} (F : α ⟶' β ⟶ γ) (b : β) : HasInternalFunctors.fromBundled (swapFun' F b) = HasInternalFunctors.fromBundled (HasInternalFunctors.toBundled (appFun b γ) ⊙' F) := HasInternalFunctors.toFromBundled (appFun' b γ) ▸ rfl def swapFunIsFun {α β γ : U} (F : α ⟶' β ⟶ γ) : HasExternalFunctors.IsFun (λ b : β => HasInternalFunctors.fromBundled (swapFun' F b)) := funext (swapFunFun.def F) ▸ h.compIsFun (appFunFun' β γ) (compFunFun' F γ) def swapFunFun' {α β γ : U} (F : α ⟶' β ⟶ γ) : β ⟶' α ⟶ γ := BundledFunctor.mkFun (swapFunIsFun F) def swapFunFun {α β γ : U} (F : α ⟶ β ⟶ γ) : β ⟶ α ⟶ γ := HasInternalFunctors.fromBundled (swapFunFun' (HasInternalFunctors.toBundled F)) @[simp] theorem swapFunFun.eff {α β γ : U} (F : α ⟶ β ⟶ γ) (b : β) : (swapFunFun F) b = swapFun F b := by apply HasInternalFunctors.fromBundled.eff @[simp] theorem swapFunFun.effEff {α β γ : U} (F : α ⟶ β ⟶ γ) (b : β) (a : α) : ((swapFunFun F) b) a = F a b := by simp theorem swapFunFunFun.def (α β γ : U) (F : α ⟶ β ⟶ γ) : HasInternalFunctors.mkFun (swapFunIsFun (HasInternalFunctors.toBundled F)) = HasInternalFunctors.fromBundled (HasInternalFunctors.toBundled (compFunFun F γ) ⊙' appFunFun' β γ) := HasInternalFunctors.toFromBundled (compFunFun' (HasInternalFunctors.toBundled F) γ) ▸ elimRec def swapFunFunIsFun (α β γ : U) : HasExternalFunctors.IsFun (λ F : α ⟶ β ⟶ γ => swapFunFun F) := funext (swapFunFunFun.def α β γ) ▸ h.compIsFun (compFunFunFun' α (β ⟶ γ) γ) (compFunFun' (appFunFun' β γ) (α ⟶ γ)) def swapFunFunFun' (α β γ : U) : (α ⟶ β ⟶ γ) ⟶' (β ⟶ α ⟶ γ) := BundledFunctor.mkFun (swapFunFunIsFun α β γ) def swapFunFunFun (α β γ : U) : (α ⟶ β ⟶ γ) ⟶ (β ⟶ α ⟶ γ) := HasInternalFunctors.fromBundled (swapFunFunFun' α β γ) @[simp] theorem swapFunFunFun.eff (α β γ : U) (F : α ⟶ β ⟶ γ) : (swapFunFunFun α β γ) F = swapFunFun F := by apply HasInternalFunctors.fromBundled.eff @[simp] theorem swapFunFunFun.effEff (α β γ : U) (F : α ⟶ β ⟶ γ) (b : β) : ((swapFunFunFun α β γ) F) b = swapFun F b := by simp @[simp] theorem swapFunFunFun.effEffEff (α β γ : U) (F : α ⟶ β ⟶ γ) (b : β) (a : α) : (((swapFunFunFun α β γ) F) b) a = F a b := by simp -- In particular, reverse composition is also functorial. def revCompFun {α β γ : U} (G : β ⟶ γ) (F : α ⟶ β) : α ⟶ γ := compFun F G infixr:90 " ⊙ " => HasLinearFunOp.revCompFun @[simp] theorem revCompFun.eff {α β γ : U} (F : α ⟶ β) (G : β ⟶ γ) (a : α) : (G ⊙ F) a = G (F a) := compFun.eff F G a theorem revCompFunFun.def (α : U) {β γ : U} (G : β ⟶' γ) (F : α ⟶ β) : HasInternalFunctors.fromBundled (G ⊙' HasInternalFunctors.toBundled F) = (compFunFun F γ) (HasInternalFunctors.fromBundled G) := Eq.subst (motive := λ H => HasInternalFunctors.fromBundled (H ⊙' HasInternalFunctors.toBundled F) = (compFunFun F γ) (HasInternalFunctors.fromBundled G)) (HasInternalFunctors.toFromBundled G) (Eq.symm (compFunFun.eff F γ (HasInternalFunctors.fromBundled G))) def revCompFunIsFun (α : U) {β γ : U} (G : β ⟶' γ) : HasExternalFunctors.IsFun (λ F : α ⟶ β => HasInternalFunctors.fromBundled (G ⊙' HasInternalFunctors.toBundled F)) := funext (revCompFunFun.def α G) ▸ swapIsFun (compFunFunFun' α β γ) (HasInternalFunctors.fromBundled G) def revCompFunFun' (α : U) {β γ : U} (G : β ⟶' γ) : (α ⟶ β) ⟶' (α ⟶ γ) := BundledFunctor.mkFun (revCompFunIsFun α G) def revCompFunFun (α : U) {β γ : U} (G : β ⟶ γ) : (α ⟶ β) ⟶ (α ⟶ γ) := HasInternalFunctors.fromBundled (revCompFunFun' α (HasInternalFunctors.toBundled G)) @[simp] theorem revCompFunFun.eff (α : U) {β γ : U} (G : β ⟶ γ) (F : α ⟶ β) : (revCompFunFun α G) F = G ⊙ F := by apply HasInternalFunctors.fromBundled.eff @[simp] theorem revCompFunFun.effEff (α : U) {β γ : U} (G : β ⟶ γ) (F : α ⟶ β) (a : α) : ((revCompFunFun α G) F) a = G (F a) := by simp theorem revCompFunFunFun.def (α β γ : U) (G : β ⟶ γ) : HasInternalFunctors.mkFun (revCompFunIsFun α (HasInternalFunctors.toBundled G)) = HasInternalFunctors.fromBundled (swapFun' (compFunFunFun' α β γ) G) := congrArg (λ H => HasInternalFunctors.fromBundled (swapFun' (compFunFunFun' α β γ) H)) (HasInternalFunctors.fromToBundled G) ▸ elimRec def revCompFunFunIsFun (α β γ : U) : HasExternalFunctors.IsFun (λ G : β ⟶ γ => revCompFunFun α G) := funext (revCompFunFunFun.def α β γ) ▸ swapFunIsFun (compFunFunFun' α β γ) def revCompFunFunFun' (α β γ : U) : (β ⟶ γ) ⟶' (α ⟶ β) ⟶ (α ⟶ γ) := BundledFunctor.mkFun (revCompFunFunIsFun α β γ) def revCompFunFunFun (α β γ : U) : (β ⟶ γ) ⟶ (α ⟶ β) ⟶ (α ⟶ γ) := HasInternalFunctors.fromBundled (revCompFunFunFun' α β γ) @[simp] theorem revCompFunFunFun.eff (α β γ : U) (G : β ⟶ γ) : (revCompFunFunFun α β γ) G = revCompFunFun α G := by apply HasInternalFunctors.fromBundled.eff @[simp] theorem revCompFunFunFun.effEff (α β γ : U) (G : β ⟶ γ) (F : α ⟶ β) : ((revCompFunFunFun α β γ) G) F = G ⊙ F := by simp @[simp] theorem revCompFunFunFun.effEffEff (α β γ : U) (G : β ⟶ γ) (F : α ⟶ β) (a : α) : (((revCompFunFunFun α β γ) G) F) a = G (F a) := by simp -- Composition of a function with two arguments. def compFun₂ {α β γ δ : U} (F : α ⟶ β ⟶ γ) (G : γ ⟶ δ) : α ⟶ β ⟶ δ := swapFunFun (revCompFunFun α G ⊙ swapFunFun F) end HasLinearFunOp namespace HasFullFunOp variable {U : Universe} [HasInternalFunctors U] [h : HasFullFunOp U] -- The S combinator (see https://en.wikipedia.org/wiki/SKI_combinator_calculus), which in our case says -- that if we can functorially construct a functor `H : β ⟶ γ` and an argument `b : β`, then the -- construction of `H b` is also functorial. theorem substFun.def {α β γ : U} (F : α ⟶' β ⟶ γ) (G : α ⟶' β) (a : α) : F a (G a) = HasInternalFunctors.fromBundled (HasLinearFunOp.swapFun' F (G a)) a := Eq.symm (HasInternalFunctors.fromBundled.eff (HasLinearFunOp.swapFun' F (G a)) a) def substIsFun {α β γ : U} (F : α ⟶' β ⟶ γ) (G : α ⟶' β) : HasExternalFunctors.IsFun (λ a : α => F a (G a)) := funext (substFun.def F G) ▸ h.dupIsFun (HasLinearFunOp.swapFunFun' F ⊙' G) def substFun' {α β γ : U} (F : α ⟶' β ⟶ γ) (G : α ⟶' β) : α ⟶' γ := BundledFunctor.mkFun (substIsFun F G) def substFun {α β γ : U} (F : α ⟶ β ⟶ γ) (G : α ⟶ β) : α ⟶ γ := HasInternalFunctors.fromBundled (substFun' (HasInternalFunctors.toBundled F) (HasInternalFunctors.toBundled G)) @[simp] theorem substFun.eff {α β γ : U} (F : α ⟶ β ⟶ γ) (G : α ⟶ β) (a : α) : (substFun F G) a = F a (G a) := by apply HasInternalFunctors.fromBundled.eff theorem substFunFun.def {α β γ : U} (F : α ⟶' β ⟶ γ) (G : α ⟶ β) : HasInternalFunctors.mkFun (substIsFun F (HasInternalFunctors.toBundled G)) = HasInternalFunctors.fromBundled (HasNonLinearFunOp.dupFun' (HasInternalFunctors.toBundled (HasInternalFunctors.fromBundled (HasLinearFunOp.swapFunFun' F ⊙' HasInternalFunctors.toBundled G)))) := HasInternalFunctors.toFromBundled _ ▸ elimRec def substFunIsFun {α β γ : U} (F : α ⟶' β ⟶ γ) : HasExternalFunctors.IsFun (λ G : α ⟶ β => HasInternalFunctors.fromBundled (substFun' F (HasInternalFunctors.toBundled G))) := funext (substFunFun.def F) ▸ h.compIsFun (HasLinearFunOp.revCompFunFun' α (HasLinearFunOp.swapFunFun' F)) (HasNonLinearFunOp.dupFunFun' α γ) def substFunFun' {α β γ : U} (F : α ⟶' β ⟶ γ) : (α ⟶ β) ⟶' (α ⟶ γ) := BundledFunctor.mkFun (substFunIsFun F) def substFunFun {α β γ : U} (F : α ⟶ β ⟶ γ) : (α ⟶ β) ⟶ (α ⟶ γ) := HasInternalFunctors.fromBundled (substFunFun' (HasInternalFunctors.toBundled F)) @[simp] theorem substFunFun.eff {α β γ : U} (F : α ⟶ β ⟶ γ) (G : α ⟶ β) : (substFunFun F) G = substFun F G := by apply HasInternalFunctors.fromBundled.eff @[simp] theorem substFunFun.effEff {α β γ : U} (F : α ⟶ β ⟶ γ) (G : α ⟶ β) (a : α) : ((substFunFun F) G) a = F a (G a) := by simp theorem substFunFunFun.def (α β γ : U) (F : α ⟶ β ⟶ γ) : HasInternalFunctors.mkFun (substFunIsFun (HasInternalFunctors.toBundled F)) = HasInternalFunctors.fromBundled (HasNonLinearFunOp.dupFunFun' α γ ⊙' HasInternalFunctors.toBundled (HasLinearFunOp.revCompFunFun α (HasLinearFunOp.swapFunFun F))) := HasInternalFunctors.toFromBundled _ ▸ HasInternalFunctors.toFromBundled _ ▸ elimRec def substFunFunIsFun (α β γ : U) : HasExternalFunctors.IsFun (λ F : α ⟶ β ⟶ γ => substFunFun F) := funext (substFunFunFun.def α β γ) ▸ h.compIsFun (HasLinearFunOp.revCompFunFunFun' α β (α ⟶ γ) ⊙' HasLinearFunOp.swapFunFunFun' α β γ) (HasLinearFunOp.revCompFunFun' (α ⟶ β) (HasNonLinearFunOp.dupFunFun' α γ)) def substFunFunFun' (α β γ : U) : (α ⟶ β ⟶ γ) ⟶' (α ⟶ β) ⟶ (α ⟶ γ) := BundledFunctor.mkFun (substFunFunIsFun α β γ) def substFunFunFun (α β γ : U) : (α ⟶ β ⟶ γ) ⟶ (α ⟶ β) ⟶ (α ⟶ γ) := HasInternalFunctors.fromBundled (substFunFunFun' α β γ) @[simp] theorem substFunFunFun.eff (α β γ : U) (F : α ⟶ β ⟶ γ) : (substFunFunFun α β γ) F = substFunFun F := by apply HasInternalFunctors.fromBundled.eff @[simp] theorem substFunFunFun.effEff (α β γ : U) (F : α ⟶ β ⟶ γ) (G : α ⟶ β) : ((substFunFunFun α β γ) F) G = substFun F G := by simp @[simp] theorem substFunFunFun.effEffEff (α β γ : U) (F : α ⟶ β ⟶ γ) (G : α ⟶ β) (a : α) : (((substFunFunFun α β γ) F) G) a = F a (G a) := by simp end HasFullFunOp -- Using the functoriality axioms and the constructions above, we can algorithmically prove -- functoriality of lambda terms. The algorithm to prove `HasExternalFunctors.IsFun (λ a : α => t)` -- is as follows: -- -- Case | Proof -- --------------------------------+-------------------------------------------------------------- -- `t` does not contain `a` | `constIsFun α t` -- `t` is `a` | `idIsFun α` -- `t` is `G b` with `G : β ⟶ γ`: | -- `a` appears only in `b` | Prove that `λ a => b` is functorial, yielding a functor -- | `F : α ⟶ β`. Then the proof is `compIsFun F G`. -- `b` is `a` | Optimization: `HasInternalFunctors.isFun G` -- `a` appears only in `G` | Prove that `λ a => G` is functorial, yielding a functor -- | `F : α ⟶ β ⟶ γ`. Then the proof is `swapIsFun F b`. -- `G` is `a` | Optimization: `appIsFun b γ` -- `a` appears in both | Prove that `λ a => G` is functorial, yielding a functor -- | `F₁ : α ⟶ β ⟶ γ`. Prove that `λ a => b` is functorial, -- | yielding a functor `F₂ : α ⟶ β`. Then the proof is -- | `substIsFun F₁ F₂`. -- `t` is `mkFun (λ b : β => c)` | Prove that `λ a => c` is functorial when regarding `b` as -- | a constant, yielding a functor `F : α ⟶ γ` for every `b`. -- | Prove that `λ b => F` is functorial, yielding a functor -- | `G : β ⟶ α ⟶ γ`. Then the proof is `swapFunIsFun G`. -- -- (This list does not contain all possible optimizations.)
eb3ec0c833f15575927e3554a4628c6dc146ab1c
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/category/Group/images.lean
ac3bfdf66e08c25bcfe7e9a4f166843513ab6216
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
3,566
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Group /-! # The category of commutative additive groups has images. -/ open category_theory open category_theory.limits universe u namespace AddCommGroup -- Note that because `injective_of_mono` is currently only proved in `Type 0`, -- we restrict to the lowest universe here for now. variables {G H : AddCommGroup.{0}} (f : G ⟶ H) local attribute [ext] subtype.ext_val section -- implementation details of `has_image` for AddCommGroup; use the API, not these /-- the image of a morphism in AddCommGroup is just the bundling of `set.range f` -/ def image : AddCommGroup := AddCommGroup.of (set.range f) /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ H := f.range_subtype_val instance : mono (image.ι f) := concrete_category.mono_of_injective (image.ι f) subtype.val_injective /-- the corestriction map to the image -/ def factor_thru_image : G ⟶ image f := add_monoid_hom.range_factorization f lemma image.fac : factor_thru_image f ≫ image.ι f = f := by { ext, refl, } local attribute [simp] image.fac variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := { to_fun := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I), map_zero' := begin haveI := F'.m_mono, apply injective_of_mono F'.m, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, add_monoid_hom.map_zero], convert (classical.indefinite_description (λ y, f y = 0) _).2, end, map_add' := begin intros x y, haveI := F'.m_mono, apply injective_of_mono F'.m, rw [add_monoid_hom.map_add], change (F'.e ≫ F'.m) _ = (F'.e ≫ F'.m) _ + (F'.e ≫ F'.m) _, rw [F'.fac], rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, refl, end, } lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := begin ext x, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, (classical.indefinite_description _ x.2).2], refl, end end /-- the factorisation of any morphism in AddCommGroup through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := factor_thru_image f } noncomputable instance : has_image f := { F := mono_factorisation f, is_image := { lift := image.lift, lift_fac' := image.lift_fac } } noncomputable instance : has_images AddCommGroup.{0} := { has_image := infer_instance } -- We'll later get this as a consequence of `[abelian AddCommGroup]`. -- Nevertheless this instance has the desired definitional behaviour, -- and is useful in the meantime for doing cohomology. -- When the `[abelian AddCommGroup]` instance is available -- this instance should be reviewed, and ideally removed if the `[abelian]` instance -- provides something definitionally equivalent. noncomputable instance : has_image_maps AddCommGroup.{0} := { has_image_map := λ f g st, { map := { to_fun := image.map ((forget AddCommGroup).map_arrow.map st), map_zero' := by { ext, simp, }, map_add' := λ x y, by { ext, simp, refl, } } } } @[simp] lemma image_map {f g : arrow AddCommGroup.{0}} (st : f ⟶ g) (x : image f.hom): (image.map st x).val = st.right x.1 := rfl end AddCommGroup
d2f55a4c5ba8c0b9c5d08a98c2a232177740e4b5
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/category_theory/limits/cones.lean
6e7109bc4b0919d29155f423d655866cc25ac84f
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,602
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.const import category_theory.discrete_category import category_theory.yoneda import category_theory.reflects_isomorphisms universes v u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. open category_theory variables {J : Type v} [small_category J] variables {K : Type v} [small_category K] variables {C : Type u₁} [category.{v} C] variables {D : Type u₂} [category.{v} D] open category_theory open category_theory.category open category_theory.functor open opposite namespace category_theory namespace functor variables {J C} (F : J ⥤ C) /-- `F.cones` is the functor assigning to an object `X` the type of natural transformations from the constant functor with value `X` to `F`. An object representing this functor is a limit of `F`. -/ @[simps] def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ yoneda.obj F /-- `F.cocones` is the functor assigning to an object `X` the type of natural transformations from `F` to the constant functor with value `X`. An object corepresenting this functor is a colimit of `F`. -/ @[simps] def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F) end functor section variables (J C) /-- Functorially associated to each functor `J ⥤ C`, we have the `C`-presheaf consisting of cones with a given cone point. -/ @[simps] def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) := { obj := functor.cones, map := λ F G f, whisker_left (const J).op (yoneda.map f) } /-- Contravariantly associated to each functor `J ⥤ C`, we have the `C`-copresheaf consisting of cocones with a given cocone point. -/ @[simps] def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) := { obj := λ F, functor.cocones (unop F), map := λ F G f, whisker_left (const J) (coyoneda.map f) } end namespace limits /-- A `c : cone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`. `cone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cones.obj X`. -/ structure cone (F : J ⥤ C) := (X : C) (π : (const J).obj X ⟶ F) instance inhabited_cone (F : discrete punit ⥤ C) : inhabited (cone F) := ⟨{ X := F.obj punit.star, π := { app := λ ⟨⟩, 𝟙 _ } }⟩ @[simp, reassoc] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') : c.π.app j ≫ F.map f = c.π.app j' := by { rw ← c.π.naturality f, apply id_comp } /-- A `c : cocone F` is * an object `c.X` and * a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor. `cocone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cocones.obj X`. -/ structure cocone (F : J ⥤ C) := (X : C) (ι : F ⟶ (const J).obj X) instance inhabited_cocone (F : discrete punit ⥤ C) : inhabited (cocone F) := ⟨{ X := F.obj punit.star, ι := { app := λ ⟨⟩, 𝟙 _ } }⟩ @[simp, reassoc] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') : F.map f ≫ c.ι.app j' = c.ι.app j := by { rw c.ι.naturality f, apply comp_id } variables {F : J ⥤ C} namespace cone /-- The isomorphism between a cone on `F` and an element of the functor `F.cones`. -/ @[simps] def equiv (F : J ⥤ C) : cone F ≅ Σ X, F.cones.obj X := { hom := λ c, ⟨op c.X, c.π⟩, inv := λ c, { X := c.1.unop, π := c.2 }, hom_inv_id' := by { ext1, cases x, refl }, inv_hom_id' := by { ext1, cases x, refl } } /-- A map to the vertex of a cone naturally induces a cone by composition. -/ @[simps] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones := { app := λ X f, (const J).map f ≫ c.π } /-- A map to the vertex of a cone induces a cone by composition. -/ @[simps] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F := { X := X, π := c.extensions.app (op X) f } /-- Whisker a cone by precomposition of a functor. -/ @[simps] def whisker (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) := { X := c.X, π := whisker_left E c.π } end cone namespace cocone /-- The isomorphism between a cocone on `F` and an element of the functor `F.cocones`. -/ def equiv (F : J ⥤ C) : cocone F ≅ Σ X, F.cocones.obj X := { hom := λ c, ⟨c.X, c.ι⟩, inv := λ c, { X := c.1, ι := c.2 }, hom_inv_id' := by { ext1, cases x, refl }, inv_hom_id' := by { ext1, cases x, refl } } /-- A map from the vertex of a cocone naturally induces a cocone by composition. -/ @[simps] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones := { app := λ X f, c.ι ≫ (const J).map f } /-- A map from the vertex of a cocone induces a cocone by composition. -/ @[simps] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F := { X := X, ι := c.extensions.app X f } /-- Whisker a cocone by precomposition of a functor. See `whiskering` for a functorial version. -/ @[simps] def whisker (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) := { X := c.X, ι := whisker_left E c.ι } end cocone /-- A cone morphism between two cones for the same diagram is a morphism of the cone points which commutes with the cone legs. -/ @[ext] structure cone_morphism (A B : cone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously) restate_axiom cone_morphism.w' attribute [simp, reassoc] cone_morphism.w instance inhabited_cone_morphism (A : cone F) : inhabited (cone_morphism A A) := ⟨{ hom := 𝟙 _ }⟩ /-- The category of cones on a given diagram. -/ @[simps] instance cone.category : category (cone F) := { hom := λ A B, cone_morphism A B, comp := λ X Y Z f g, { hom := f.hom ≫ g.hom }, id := λ B, { hom := 𝟙 B.X } } namespace cones /-- To give an isomorphism between cones, it suffices to give an isomorphism between their vertices which commutes with the cone maps. -/ @[ext, simps] def ext {c c' : cone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } } /-- Given a cone morphism whose object part is an isomorphism, produce an isomorphism of cones. -/ lemma cone_iso_of_hom_iso {K : J ⥤ C} {c d : cone K} (f : c ⟶ d) [i : is_iso f.hom] : is_iso f := ⟨⟨{ hom := inv f.hom, w' := λ j, (as_iso f.hom).inv_comp_eq.2 (f.w j).symm }, by tidy⟩⟩ /-- Functorially postcompose a cone for `F` by a natural transformation `F ⟶ G` to give a cone for `G`. -/ @[simps] def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G := { obj := λ c, { X := c.X, π := c.π ≫ α }, map := λ c₁ c₂ f, { hom := f.hom } } /-- Postcomposing a cone by the composite natural transformation `α ≫ β` is the same as postcomposing by `α` and then by `β`. -/ @[simps] def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) /-- Postcomposing by the identity does not change the cone up to isomorphism. -/ @[simps] def postcompose_id : postcompose (𝟙 F) ≅ 𝟭 (cone F) := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) /-- If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of cones. -/ @[simps] def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G := { functor := postcompose α.hom, inverse := postcompose α.inv, unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) } /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cone F` to `cone (E ⋙ F)`. -/ @[simps] def whiskering (E : K ⥤ J) : cone F ⥤ cone (E ⋙ F) := { obj := λ c, c.whisker E, map := λ c c' f, { hom := f.hom } } /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ @[simps] def whiskering_equivalence (e : K ≌ J) : cone F ≌ cone (e.functor ⋙ F) := { functor := whiskering e.functor, inverse := whiskering e.inverse ⋙ postcompose (e.inv_fun_id_assoc F).hom, unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (begin intro k, dsimp, -- See library note [dsimp, simp] simpa [e.counit_app_functor] using s.w (e.unit_inv.app k), end)) (by tidy), } /-- The categories of cones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ @[simps functor inverse unit_iso counit_iso] def equivalence_of_reindexing {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cone F ≌ cone G := (whiskering_equivalence e).trans (postcompose_equivalence α) section variable (F) /-- Forget the cone structure and obtain just the cone point. -/ @[simps] def forget : cone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } variables (G : C ⥤ D) /-- A functor `G : C ⥤ D` sends cones over `F` to cones over `F ⋙ G` functorially. -/ @[simps] def functoriality : cone F ⥤ cone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ X Y f, { hom := G.map f.hom, w' := λ j, by simp [-cone_morphism.w, ←f.w j] } } instance functoriality_full [full G] [faithful G] : full (functoriality F G) := { preimage := λ X Y t, { hom := G.preimage t.hom, w' := λ j, G.map_injective (by simpa using t.w j) } } instance functoriality_faithful [faithful G] : faithful (cones.functoriality F G) := { map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } } /-- If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an equivalence between cones over `F` and cones over `F ⋙ e.functor`. -/ @[simps] def functoriality_equivalence (e : C ≌ D) : cone F ≌ cone (F ⋙ e.functor) := let f : (F ⋙ e.functor) ⋙ e.inverse ≅ F := functor.associator _ _ _ ≪≫ iso_whisker_left _ (e.unit_iso).symm ≪≫ functor.right_unitor _ in { functor := functoriality F e.functor, inverse := (functoriality (F ⋙ e.functor) e.inverse) ⋙ (postcompose_equivalence f).functor, unit_iso := nat_iso.of_components (λ c, cones.ext (e.unit_iso.app _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cones.ext (e.counit_iso.app _) (by tidy)) (by tidy), } /-- If `F` reflects isomorphisms, then `cones.functoriality F` reflects isomorphisms as well. -/ instance reflects_cone_isomorphism (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) : reflects_isomorphisms (cones.functoriality K F) := begin constructor, introsI, haveI : is_iso (F.map f.hom) := (cones.forget (K ⋙ F)).map_is_iso ((cones.functoriality K F).map f), haveI := reflects_isomorphisms.reflects F f.hom, apply cone_iso_of_hom_iso end end end cones /-- A cocone morphism between two cocones for the same diagram is a morphism of the cocone points which commutes with the cocone legs. -/ @[ext] structure cocone_morphism (A B : cocone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously) instance inhabited_cocone_morphism (A : cocone F) : inhabited (cocone_morphism A A) := ⟨{ hom := 𝟙 _ }⟩ restate_axiom cocone_morphism.w' attribute [simp, reassoc] cocone_morphism.w @[simps] instance cocone.category : category (cocone F) := { hom := λ A B, cocone_morphism A B, comp := λ _ _ _ f g, { hom := f.hom ≫ g.hom }, id := λ B, { hom := 𝟙 B.X } } namespace cocones /-- To give an isomorphism between cocones, it suffices to give an isomorphism between their vertices which commutes with the cocone maps. -/ @[ext, simps] def ext {c c' : cocone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } } /-- Given a cocone morphism whose object part is an isomorphism, produce an isomorphism of cocones. -/ lemma cocone_iso_of_hom_iso {K : J ⥤ C} {c d : cocone K} (f : c ⟶ d) [i : is_iso f.hom] : is_iso f := ⟨⟨{ hom := inv f.hom, w' := λ j, (as_iso f.hom).comp_inv_eq.2 (f.w j).symm }, by tidy⟩⟩ /-- Functorially precompose a cocone for `F` by a natural transformation `G ⟶ F` to give a cocone for `G`. -/ @[simps] def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G := { obj := λ c, { X := c.X, ι := α ≫ c.ι }, map := λ c₁ c₂ f, { hom := f.hom } } /-- Precomposing a cocone by the composite natural transformation `α ≫ β` is the same as precomposing by `β` and then by `α`. -/ def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : precompose (α ≫ β) ≅ precompose β ⋙ precompose α := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) /-- Precomposing by the identity does not change the cocone up to isomorphism. -/ def precompose_id : precompose (𝟙 F) ≅ 𝟭 (cocone F) := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) /-- If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of cocones. -/ @[simps] def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G := { functor := precompose α.hom, inverse := precompose α.inv, unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) } /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cocone F` to `cocone (E ⋙ F)`. -/ @[simps] def whiskering (E : K ⥤ J) : cocone F ⥤ cocone (E ⋙ F) := { obj := λ c, c.whisker E, map := λ c c' f, { hom := f.hom, } } /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ @[simps] def whiskering_equivalence (e : K ≌ J) : cocone F ≌ cocone (e.functor ⋙ F) := { functor := whiskering e.functor, inverse := whiskering e.inverse ⋙ precompose ((functor.left_unitor F).inv ≫ (whisker_right (e.counit_iso).inv F) ≫ (functor.associator _ _ _).inv), unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (begin intro k, dsimp, simpa [e.counit_inv_app_functor k] using s.w (e.unit.app k), end)) (by tidy), } /-- The categories of cocones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ @[simps functor_obj] def equivalence_of_reindexing {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cocone F ≌ cocone G := (whiskering_equivalence e).trans (precompose_equivalence α.symm) section variable (F) /-- Forget the cocone structure and obtain just the cocone point. -/ @[simps] def forget : cocone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } variables (G : C ⥤ D) /-- A functor `G : C ⥤ D` sends cocones over `F` to cocones over `F ⋙ G` functorially. -/ @[simps] def functoriality : cocone F ⥤ cocone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ _ _ f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } } instance functoriality_full [full G] [faithful G] : full (functoriality F G) := { preimage := λ X Y t, { hom := G.preimage t.hom, w' := λ j, G.map_injective (by simpa using t.w j) } } instance functoriality_faithful [faithful G] : faithful (functoriality F G) := { map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } } /-- If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an equivalence between cocones over `F` and cocones over `F ⋙ e.functor`. -/ @[simps] def functoriality_equivalence (e : C ≌ D) : cocone F ≌ cocone (F ⋙ e.functor) := let f : (F ⋙ e.functor) ⋙ e.inverse ≅ F := functor.associator _ _ _ ≪≫ iso_whisker_left _ (e.unit_iso).symm ≪≫ functor.right_unitor _ in { functor := functoriality F e.functor, inverse := (functoriality (F ⋙ e.functor) e.inverse) ⋙ (precompose_equivalence f.symm).functor, unit_iso := nat_iso.of_components (λ c, cocones.ext (e.unit_iso.app _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cocones.ext (e.counit_iso.app _) begin -- Unfortunately this doesn't work by `tidy`. -- In this configuration `simp` reaches a dead-end and needs help. intros j, dsimp, simp only [←equivalence.counit_inv_app_functor, iso.inv_hom_id_app, map_comp, equivalence.fun_inv_map, assoc, id_comp, iso.inv_hom_id_app_assoc], dsimp, simp, -- See note [dsimp, simp]. end) (λ c c' f, by { ext, dsimp, simp, dsimp, simp, }), } /-- If `F` reflects isomorphisms, then `cocones.functoriality F` reflects isomorphisms as well. -/ instance reflects_cocone_isomorphism (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) : reflects_isomorphisms (cocones.functoriality K F) := begin constructor, introsI, haveI : is_iso (F.map f.hom) := (cocones.forget (K ⋙ F)).map_is_iso ((cocones.functoriality K F).map f), haveI := reflects_isomorphisms.reflects F f.hom, apply cocone_iso_of_hom_iso end end end cocones end limits namespace functor variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) open category_theory.limits /-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/ @[simps] def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality F H).obj c /-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/ @[simps] def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality F H).obj c /-- Given a cone morphism `c ⟶ c'`, construct a cone morphism on the mapped cones functorially. -/ def map_cone_morphism {c c' : cone F} (f : c ⟶ c') : H.map_cone c ⟶ H.map_cone c' := (cones.functoriality F H).map f /-- Given a cocone morphism `c ⟶ c'`, construct a cocone morphism on the mapped cocones functorially. -/ def map_cocone_morphism {c c' : cocone F} (f : c ⟶ c') : H.map_cocone c ⟶ H.map_cocone c' := (cocones.functoriality F H).map f /-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone for `F ⋙ H`.-/ def map_cone_inv [is_equivalence H] (c : cone (F ⋙ H)) : cone F := (limits.cones.functoriality_equivalence F (as_equivalence H)).inverse.obj c /-- `map_cone` is the left inverse to `map_cone_inv`. -/ def map_cone_map_cone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone (F ⋙ H)) : map_cone H (map_cone_inv H c) ≅ c := (limits.cones.functoriality_equivalence F (as_equivalence H)).counit_iso.app c /-- `map_cone` is the right inverse to `map_cone_inv`. -/ def map_cone_inv_map_cone {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone F) : map_cone_inv H (map_cone H c) ≅ c := (limits.cones.functoriality_equivalence F (as_equivalence H)).unit_iso.symm.app c /-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone for `F ⋙ H`.-/ def map_cocone_inv [is_equivalence H] (c : cocone (F ⋙ H)) : cocone F := (limits.cocones.functoriality_equivalence F (as_equivalence H)).inverse.obj c /-- `map_cocone` is the left inverse to `map_cocone_inv`. -/ def map_cocone_map_cocone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cocone (F ⋙ H)) : map_cocone H (map_cocone_inv H c) ≅ c := (limits.cocones.functoriality_equivalence F (as_equivalence H)).counit_iso.app c /-- `map_cocone` is the right inverse to `map_cocone_inv`. -/ def map_cocone_inv_map_cocone {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cocone F) : map_cocone_inv H (map_cocone H c) ≅ c := (limits.cocones.functoriality_equivalence F (as_equivalence H)).unit_iso.symm.app c /-- `functoriality F _ ⋙ postcompose (whisker_left F _)` simplifies to `functoriality F _`. -/ @[simps] def functoriality_comp_postcompose {H H' : C ⥤ D} (α : H ≅ H') : cones.functoriality F H ⋙ cones.postcompose (whisker_left F α.hom) ≅ cones.functoriality F H' := nat_iso.of_components (λ c, cones.ext (α.app _) (by tidy)) (by tidy) /-- For `F : J ⥤ C`, given a cone `c : cone F`, and a natural isomorphism `α : H ≅ H'` for functors `H H' : C ⥤ D`, the postcomposition of the cone `H.map_cone` using the isomorphism `α` is isomorphic to the cone `H'.map_cone`. -/ @[simps] def postcompose_whisker_left_map_cone {H H' : C ⥤ D} (α : H ≅ H') (c : cone F) : (cones.postcompose (whisker_left F α.hom : _)).obj (H.map_cone c) ≅ H'.map_cone c := (functoriality_comp_postcompose α).app c /-- `map_cone` commutes with `postcompose`. In particular, for `F : J ⥤ C`, given a cone `c : cone F`, a natural transformation `α : F ⟶ G` and a functor `H : C ⥤ D`, we have two obvious ways of producing a cone over `G ⋙ H`, and they are both isomorphic. -/ @[simps] def map_cone_postcompose {α : F ⟶ G} {c} : H.map_cone ((cones.postcompose α).obj c) ≅ (cones.postcompose (whisker_right α H : _)).obj (H.map_cone c) := cones.ext (iso.refl _) (by tidy) /-- `map_cone` commutes with `postcompose_equivalence` -/ @[simps] def map_cone_postcompose_equivalence_functor {α : F ≅ G} {c} : H.map_cone ((cones.postcompose_equivalence α).functor.obj c) ≅ (cones.postcompose_equivalence (iso_whisker_right α H : _)).functor.obj (H.map_cone c) := cones.ext (iso.refl _) (by tidy) /-- `functoriality F _ ⋙ precompose (whisker_left F _)` simplifies to `functoriality F _`. -/ @[simps] def functoriality_comp_precompose {H H' : C ⥤ D} (α : H ≅ H') : cocones.functoriality F H ⋙ cocones.precompose (whisker_left F α.inv) ≅ cocones.functoriality F H' := nat_iso.of_components (λ c, cocones.ext (α.app _) (by tidy)) (by tidy) /-- For `F : J ⥤ C`, given a cocone `c : cocone F`, and a natural isomorphism `α : H ≅ H'` for functors `H H' : C ⥤ D`, the precomposition of the cocone `H.map_cocone` using the isomorphism `α` is isomorphic to the cocone `H'.map_cocone`. -/ @[simps] def precompose_whisker_left_map_cocone {H H' : C ⥤ D} (α : H ≅ H') (c : cocone F) : (cocones.precompose (whisker_left F α.inv : _)).obj (H.map_cocone c) ≅ H'.map_cocone c := (functoriality_comp_precompose α).app c /-- `map_cocone` commutes with `precompose`. In particular, for `F : J ⥤ C`, given a cocone `c : cocone F`, a natural transformation `α : F ⟶ G` and a functor `H : C ⥤ D`, we have two obvious ways of producing a cocone over `G ⋙ H`, and they are both isomorphic. -/ @[simps] def map_cocone_precompose {α : F ⟶ G} {c} : H.map_cocone ((cocones.precompose α).obj c) ≅ (cocones.precompose (whisker_right α H : _)).obj (H.map_cocone c) := cocones.ext (iso.refl _) (by tidy) /-- `map_cocone` commutes with `precompose_equivalence` -/ @[simps] def map_cocone_precompose_equivalence_functor {α : F ≅ G} {c} : H.map_cocone ((cocones.precompose_equivalence α).functor.obj c) ≅ (cocones.precompose_equivalence (iso_whisker_right α H : _)).functor.obj (H.map_cocone c) := cocones.ext (iso.refl _) (by tidy) /-- `map_cone` commutes with `whisker` -/ @[simps] def map_cone_whisker {E : K ⥤ J} {c : cone F} : H.map_cone (c.whisker E) ≅ (H.map_cone c).whisker E := cones.ext (iso.refl _) (by tidy) /-- `map_cocone` commutes with `whisker` -/ @[simps] def map_cocone_whisker {E : K ⥤ J} {c : cocone F} : H.map_cocone (c.whisker E) ≅ (H.map_cocone c).whisker E := cocones.ext (iso.refl _) (by tidy) end functor end category_theory namespace category_theory.limits section variables {F : J ⥤ C} /-- Change a `cocone F` into a `cone F.op`. -/ @[simps] def cocone.op (c : cocone F) : cone F.op := { X := op c.X, π := { app := λ j, (c.ι.app (unop j)).op, naturality' := λ j j' f, has_hom.hom.unop_inj (by tidy) } } /-- Change a `cone F` into a `cocone F.op`. -/ @[simps] def cone.op (c : cone F) : cocone F.op := { X := op c.X, ι := { app := λ j, (c.π.app (unop j)).op, naturality' := λ j j' f, has_hom.hom.unop_inj (by tidy) } } /-- Change a `cocone F.op` into a `cone F`. -/ @[simps] def cocone.unop (c : cocone F.op) : cone F := { X := unop c.X, π := { app := λ j, (c.ι.app (op j)).unop, naturality' := λ j j' f, has_hom.hom.op_inj (c.ι.naturality f.op).symm } } /-- Change a `cone F.op` into a `cocone F`. -/ @[simps] def cone.unop (c : cone F.op) : cocone F := { X := unop c.X, ι := { app := λ j, (c.π.app (op j)).unop, naturality' := λ j j' f, has_hom.hom.op_inj (c.π.naturality f.op).symm } } variables (F) /-- The category of cocones on `F` is equivalent to the opposite category of the category of cones on the opposite of `F`. -/ @[simps] def cocone_equivalence_op_cone_op : cocone F ≌ (cone F.op)ᵒᵖ := { functor := { obj := λ c, op (cocone.op c), map := λ X Y f, has_hom.hom.op { hom := f.hom.op, w' := λ j, by { apply has_hom.hom.unop_inj, dsimp, simp, }, } }, inverse := { obj := λ c, cone.unop (unop c), map := λ X Y f, { hom := f.unop.hom.unop, w' := λ j, by { apply has_hom.hom.op_inj, dsimp, simp, }, } }, unit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, by { op_induction c, dsimp, apply iso.op, exact cones.ext (iso.refl _) (by tidy), }) begin intros, have hX : X = op (unop X) := rfl, revert hX, generalize : unop X = X', rintro rfl, have hY : Y = op (unop Y) := rfl, revert hY, generalize : unop Y = Y', rintro rfl, apply has_hom.hom.unop_inj, apply cone_morphism.ext, dsimp, simp, end, functor_unit_iso_comp' := λ c, begin apply has_hom.hom.unop_inj, ext, dsimp, simp, end } end section variables {F : J ⥤ Cᵒᵖ} /-- Change a cocone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/ -- Here and below we only automatically generate the `@[simp]` lemma for the `X` field, -- as we can write a simpler `rfl` lemma for the components of the natural transformation by hand. @[simps {rhs_md := semireducible, simp_rhs := tt}] def cone_of_cocone_left_op (c : cocone F.left_op) : cone F := { X := op c.X, π := nat_trans.remove_left_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) } /-- Change a cone on `F : J ⥤ Cᵒᵖ` to a cocone on `F.left_op : Jᵒᵖ ⥤ C`. -/ @[simps {rhs_md := semireducible, simp_rhs := tt}] def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) := { X := unop c.X, ι := nat_trans.left_op c.π } /-- Change a cone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/ /- When trying use `@[simps]` to generate the `ι_app` field of this definition, `@[simps]` tries to reduce the RHS using `expr.dsimp` and `expr.simp`, but for some reason the expression is not being simplified properly. -/ @[simps X] def cocone_of_cone_left_op (c : cone F.left_op) : cocone F := { X := op c.X, ι := nat_trans.remove_left_op ((const.op_obj_unop (op c.X)).hom ≫ c.π) } @[simp] lemma cocone_of_cone_left_op_ι_app (c : cone F.left_op) (j) : (cocone_of_cone_left_op c).ι.app j = (c.π.app (op j)).op := by { dsimp [cocone_of_cone_left_op], simp } /-- Change a cocone on `F : J ⥤ Cᵒᵖ` to a cone on `F.left_op : Jᵒᵖ ⥤ C`. -/ @[simps {rhs_md := semireducible, simp_rhs := tt}] def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) := { X := unop c.X, π := nat_trans.left_op c.ι } end end category_theory.limits namespace category_theory.functor open category_theory.limits variables {F : J ⥤ C} section variables (G : C ⥤ D) /-- The opposite cocone of the image of a cone is the image of the opposite cocone. -/ @[simps {rhs_md := semireducible}] def map_cone_op (t : cone F) : (G.map_cone t).op ≅ (G.op.map_cocone t.op) := cocones.ext (iso.refl _) (by tidy) /-- The opposite cone of the image of a cocone is the image of the opposite cone. -/ @[simps {rhs_md := semireducible}] def map_cocone_op {t : cocone F} : (G.map_cocone t).op ≅ (G.op.map_cone t.op) := cones.ext (iso.refl _) (by tidy) end end category_theory.functor
bfe7aec3a04cb511f0d52529741be6c07c48fab9
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/analysis/complex/polynomial.lean
a0f55184a34e0fcf0a6adf0490e5dac62fed0348
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,590
lean
/- Copyright (c) 2019 Chris Hughes All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import analysis.special_functions.pow import field_theory.is_alg_closed.basic /-! # The fundamental theorem of algebra This file proves that every nonconstant complex polynomial has a root. As a consequence, the complex numbers are algebraically closed. -/ open complex polynomial metric filter is_absolute_value set open_locale classical namespace complex /- The following proof uses the method given at <https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus> -/ /-- **Fundamental theorem of algebra**: every non constant complex polynomial has a root -/ lemma exists_root {f : polynomial ℂ} (hf : 0 < degree f) : ∃ z : ℂ, is_root f z := let ⟨z₀, hz₀⟩ := f.exists_forall_norm_le in exists.intro z₀ $ classical.by_contradiction $ λ hf0, have hfX : f - C (f.eval z₀) ≠ 0, from mt sub_eq_zero.1 (λ h, not_le_of_gt hf (h.symm ▸ degree_C_le)), let n := root_multiplicity z₀ (f - C (f.eval z₀)) in let g := (f - C (f.eval z₀)) /ₘ ((X - C z₀) ^ n) in have hg0 : g.eval z₀ ≠ 0, from eval_div_by_monic_pow_root_multiplicity_ne_zero _ hfX, have hg : g * (X - C z₀) ^ n = f - C (f.eval z₀), from div_by_monic_mul_pow_root_multiplicity_eq _ _, have hn0 : 0 < n, from nat.pos_of_ne_zero $ λ hn0, by simpa [g, hn0] using hg0, let ⟨δ', hδ'₁, hδ'₂⟩ := continuous_iff.1 (polynomial.continuous g) z₀ ((g.eval z₀).abs) (complex.abs_pos.2 hg0) in let δ := min (min (δ' / 2) 1) (((f.eval z₀).abs / (g.eval z₀).abs) / 2) in have hf0' : 0 < (f.eval z₀).abs, from complex.abs_pos.2 hf0, have hg0' : 0 < abs (eval z₀ g), from complex.abs_pos.2 hg0, have hfg0 : 0 < (f.eval z₀).abs / abs (eval z₀ g), from div_pos hf0' hg0', have hδ0 : 0 < δ, from lt_min (lt_min (half_pos hδ'₁) (by norm_num)) (half_pos hfg0), have hδ : ∀ z : ℂ, abs (z - z₀) = δ → abs (g.eval z - g.eval z₀) < (g.eval z₀).abs, from λ z hz, hδ'₂ z (by rw [complex.dist_eq, hz]; exact ((min_le_left _ _).trans (min_le_left _ _)).trans_lt (half_lt_self hδ'₁)), have hδ1 : δ ≤ 1, from le_trans (min_le_left _ _) (min_le_right _ _), let F : polynomial ℂ := C (f.eval z₀) + C (g.eval z₀) * (X - C z₀) ^ n in let z' := (-f.eval z₀ * (g.eval z₀).abs * δ ^ n / ((f.eval z₀).abs * g.eval z₀)) ^ (n⁻¹ : ℂ) + z₀ in have hF₁ : F.eval z' = f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs, by simp only [F, cpow_nat_inv_pow _ hn0, div_eq_mul_inv, eval_pow, mul_assoc, mul_comm (g.eval z₀), mul_left_comm (g.eval z₀), mul_left_comm (g.eval z₀)⁻¹, mul_inv₀, inv_mul_cancel hg0, eval_C, eval_add, eval_neg, sub_eq_add_neg, eval_mul, eval_X, add_neg_cancel_right, neg_mul_eq_neg_mul_symm, mul_one, div_eq_mul_inv]; simp only [mul_comm, mul_left_comm, mul_assoc], have hδs : (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs < 1, from (div_lt_one hf0').2 $ (lt_div_iff' hg0').1 $ calc δ ^ n ≤ δ ^ 1 : pow_le_pow_of_le_one (le_of_lt hδ0) hδ1 hn0 ... = δ : pow_one _ ... ≤ ((f.eval z₀).abs / (g.eval z₀).abs) / 2 : min_le_right _ _ ... < _ : half_lt_self (div_pos hf0' hg0'), have hF₂ : (F.eval z').abs = (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n, from calc (F.eval z').abs = (f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs).abs : congr_arg abs hF₁ ... = abs (f.eval z₀) * complex.abs (1 - (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs : ℝ) : by rw [← complex.abs_mul]; exact congr_arg complex.abs (by simp [mul_add, add_mul, mul_assoc, div_eq_mul_inv, sub_eq_add_neg]) ... = _ : by rw [complex.abs_of_nonneg (sub_nonneg.2 (le_of_lt hδs)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt hf0')), mul_one], have hef0 : abs (eval z₀ g) * (eval z₀ f).abs ≠ 0, from mul_ne_zero (mt complex.abs_eq_zero.1 hg0) (mt complex.abs_eq_zero.1 hf0), have hz'z₀ : abs (z' - z₀) = δ, by simp [z', mul_assoc, mul_left_comm _ (_ ^ n), mul_comm _ (_ ^ n), mul_comm (eval z₀ f).abs, _root_.mul_div_cancel _ hef0, of_real_mul, neg_mul_eq_neg_mul_symm, neg_div, is_absolute_value.abv_pow complex.abs, complex.abs_of_nonneg (le_of_lt hδ0), real.pow_nat_rpow_nat_inv (le_of_lt hδ0) hn0], have hF₃ : (f.eval z' - F.eval z').abs < (g.eval z₀).abs * δ ^ n, from calc (f.eval z' - F.eval z').abs = (g.eval z' - g.eval z₀).abs * (z' - z₀).abs ^ n : by rw [← eq_sub_iff_add_eq.1 hg, ← is_absolute_value.abv_pow complex.abs, ← complex.abs_mul, sub_mul]; simp [F, eval_pow, eval_add, eval_mul, eval_sub, eval_C, eval_X, eval_neg, add_sub_cancel, sub_eq_add_neg, add_assoc] ... = (g.eval z' - g.eval z₀).abs * δ ^ n : by rw hz'z₀ ... < _ : (mul_lt_mul_right (pow_pos hδ0 _)).2 (hδ _ hz'z₀), lt_irrefl (f.eval z₀).abs $ calc (f.eval z₀).abs ≤ (f.eval z').abs : hz₀ _ ... = (F.eval z' + (f.eval z' - F.eval z')).abs : by simp ... ≤ (F.eval z').abs + (f.eval z' - F.eval z').abs : complex.abs_add _ _ ... < (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n + (g.eval z₀).abs * δ ^ n : add_lt_add_of_le_of_lt (by rw hF₂) hF₃ ... = (f.eval z₀).abs : sub_add_cancel _ _ instance is_alg_closed : is_alg_closed ℂ := is_alg_closed.of_exists_root _ $ λ p _ hp, complex.exists_root $ degree_pos_of_irreducible hp end complex
4a330a96a4cf7a01ecabab5982e064e59fe5b87e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/algebra/valuation.lean
a6cd831f8e720e2142bda23a9fba5f42e86e8ba9
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,098
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.algebra.nonarchimedean.bases import topology.algebra.uniform_filter_basis import ring_theory.valuation.basic /-! # The topology on a valued ring In this file, we define the non archimedean topology induced by a valuation on a ring. The main definition is a `valued` type class which equips a ring with a valuation taking values in a group with zero (living in the same universe). Other instances are then deduced from this. -/ open_locale classical topological_space open set valuation noncomputable theory universe u /-- A valued ring is a ring that comes equipped with a distinguished valuation.-/ class valued (R : Type u) [ring R] := (Γ₀ : Type u) [grp : linear_ordered_comm_group_with_zero Γ₀] (v : valuation R Γ₀) attribute [instance] valued.grp namespace valued variables {R : Type*} [ring R] [valued R] /-- The basis of open subgroups for the topology on a valued ring.-/ lemma subgroups_basis : ring_subgroups_basis (λ γ : units (Γ₀ R), valued.v.lt_add_subgroup γ) := { inter := begin rintros γ₀ γ₁, use min γ₀ γ₁, simp [valuation.lt_add_subgroup] ; tauto end, mul := begin rintros γ, cases exists_square_le γ with γ₀ h, use γ₀, rintro - ⟨r, s, r_in, s_in, rfl⟩, calc v (r*s) = v r * v s : valuation.map_mul _ _ _ ... < γ₀*γ₀ : mul_lt_mul₀ r_in s_in ... ≤ γ : by exact_mod_cast h end, left_mul := begin rintros x γ, rcases group_with_zero.eq_zero_or_unit (v x) with Hx | ⟨γx, Hx⟩, { use 1, rintros y (y_in : v y < 1), change v (x * y) < _, rw [valuation.map_mul, Hx, zero_mul], exact units.zero_lt γ }, { simp only [image_subset_iff, set_of_subset_set_of, preimage_set_of_eq, valuation.map_mul], use γx⁻¹*γ, rintros y (vy_lt : v y < ↑(γx⁻¹ * γ)), change v (x * y) < γ, rw [valuation.map_mul, Hx, mul_comm], rw [units.coe_mul, mul_comm] at vy_lt, simpa using mul_inv_lt_of_lt_mul₀ vy_lt } end, right_mul := begin rintros x γ, rcases group_with_zero.eq_zero_or_unit (v x) with Hx | ⟨γx, Hx⟩, { use 1, rintros y (y_in : v y < 1), change v (y * x) < _, rw [valuation.map_mul, Hx, mul_zero], exact units.zero_lt γ }, { use γx⁻¹*γ, rintros y (vy_lt : v y < ↑(γx⁻¹ * γ)), change v (y * x) < γ, rw [valuation.map_mul, Hx], rw [units.coe_mul, mul_comm] at vy_lt, simpa using mul_inv_lt_of_lt_mul₀ vy_lt } end } @[priority 100] instance : topological_space R := subgroups_basis.topology lemma mem_nhds {s : set R} {x : R} : (s ∈ 𝓝 x) ↔ ∃ γ : units (valued.Γ₀ R), {y | v (y - x) < γ } ⊆ s := by simpa [(subgroups_basis.has_basis_nhds x).mem_iff] lemma mem_nhds_zero {s : set R} : (s ∈ 𝓝 (0 : R)) ↔ ∃ γ : units (Γ₀ R), {x | v x < (γ : Γ₀ R) } ⊆ s := by simp [valued.mem_nhds, sub_zero] lemma loc_const {x : R} (h : v x ≠ 0) : {y : R | v y = v x} ∈ 𝓝 x := begin rw valued.mem_nhds, rcases units.exists_iff_ne_zero.mpr h with ⟨γ, hx⟩, use γ, rw hx, intros y y_in, exact valuation.map_eq_of_sub_lt _ y_in end /-- The uniform structure on a valued ring.-/ @[priority 100] instance uniform_space : uniform_space R := topological_add_group.to_uniform_space R /-- A valued ring is a uniform additive group.-/ @[priority 100] instance uniform_add_group : uniform_add_group R := topological_add_group_is_uniform lemma cauchy_iff {F : filter R} : cauchy F ↔ F.ne_bot ∧ ∀ γ : units (Γ₀ R), ∃ M ∈ F, ∀ x y, x ∈ M → y ∈ M → v (y - x) < γ := begin rw add_group_filter_basis.cauchy_iff, apply and_congr iff.rfl, simp_rw subgroups_basis.mem_add_group_filter_basis_iff, split, { intros h γ, exact h _ (subgroups_basis.mem_add_group_filter_basis _) }, { rintros h - ⟨γ, rfl⟩, exact h γ } end end valued
a512475bab7ea7b03b026f675b16b9c98a0df4ca
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/free_ring.lean
ff18d27ddc151decf00652dde4e9166b6de5401f
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
2,577
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import group_theory.free_abelian_group import ring_theory.subring /-! # Free rings The theory of the free ring over a type. ## Main definitions * `free_ring α` : the free (not commutative in general) ring over a type. * `lift (f : α → R)` : the ring hom `free_ring α →+* R` induced by `f`. * `map (f : α → β)` : the ring hom `free_ring α →+* free_ring β` induced by `f`. ## Implementation details `free_ring α` is implemented as the free abelian group over the free monoid on `α`. ## Tags free ring -/ universes u v /-- The free ring over a type `α`. -/ @[derive [ring, inhabited]] def free_ring (α : Type u) : Type u := free_abelian_group $ free_monoid α namespace free_ring variables {α : Type u} /-- The canonical map from α to `free_ring α`. -/ def of (x : α) : free_ring α := free_abelian_group.of (free_monoid.of x) lemma of_injective : function.injective (of : α → free_ring α) := free_abelian_group.of_injective.comp free_monoid.of_injective @[elab_as_eliminator] protected lemma induction_on {C : free_ring α → Prop} (z : free_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_ring α) ▸ ha _ _ hn1 h1) (λ m, list.rec_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {R : Type v} [ring R] (f : α → R) /-- The ring homomorphism `free_ring α →+* R` induced from a map `α → R`. -/ def lift : (α → R) ≃ (free_ring α →+* R) := free_monoid.lift.trans free_abelian_group.lift_monoid @[simp] lemma lift_of (x : α) : lift f (of x) = f x := congr_fun (lift.left_inv f) x @[simp] lemma lift_comp_of (f : free_ring α →+* R) : lift (f ∘ of) = f := lift.right_inv f @[ext] lemma hom_ext ⦃f g : free_ring α →+* R⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := lift.symm.injective (funext h) end lift variables {β : Type v} (f : α → β) /-- The canonical ring homomorphism `free_ring α →+* free_ring β` generated by a map `α → β`. -/ def map : free_ring α →+* free_ring β := lift $ of ∘ f @[simp] lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ end free_ring
07ff8635e0fd8f57608df02e5c4d1cb186a92ff0
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/number_theory/liouville/basic.lean
f857cfb6c599fbbae3c8e13fe304844eb91cb660
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
12,299
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Jujian Zhang -/ import analysis.calculus.mean_value import data.polynomial.denoms_clearable import data.real.irrational /-! # Liouville's theorem This file contains a proof of Liouville's theorem stating that all Liouville numbers are transcendental. To obtain this result, there is first a proof that Liouville numbers are irrational and two technical lemmas. These lemmas exploit the fact that a polynomial with integer coefficients takes integer values at integers. When evaluating at a rational number, we can clear denominators and obtain precise inequalities that ultimately allow us to prove transcendence of Liouville numbers. -/ /-- A Liouville number is a real number `x` such that for every natural number `n`, there exist `a, b ∈ ℤ` with `1 < b` such that `0 < |x - a/b| < 1/bⁿ`. In the implementation, the condition `x ≠ a/b` replaces the traditional equivalent `0 < |x - a/b|`. -/ def liouville (x : ℝ) := ∀ n : ℕ, ∃ a b : ℤ, 1 < b ∧ x ≠ a / b ∧ abs (x - a / b) < 1 / b ^ n namespace liouville @[protected] lemma irrational {x : ℝ} (h : liouville x) : irrational x := begin -- By contradiction, `x = a / b`, with `a ∈ ℤ`, `0 < b ∈ ℕ` is a Liouville number, rintros ⟨⟨a, b, bN0, cop⟩, rfl⟩, -- clear up the mess of constructions of rationals change (liouville (a / b)) at h, -- Since `a / b` is a Liouville number, there are `p, q ∈ ℤ`, with `q1 : 1 < q`, -- `a0 : a / b ≠ p / q` and `a1 : abs (a / b - p / q) < 1 / q ^ (b + 1)` rcases h (b + 1) with ⟨p, q, q1, a0, a1⟩, -- A few useful inequalities have qR0 : (0 : ℝ) < q := int.cast_pos.mpr (zero_lt_one.trans q1), have b0 : (b : ℝ) ≠ 0 := ne_of_gt (nat.cast_pos.mpr bN0), have bq0 : (0 : ℝ) < b * q := mul_pos (nat.cast_pos.mpr bN0) qR0, -- At a1, clear denominators... replace a1 : abs (a * q - b * p) * q ^ (b + 1) < b * q, by rwa [div_sub_div _ _ b0 (ne_of_gt qR0), abs_div, div_lt_div_iff (abs_pos.mpr (ne_of_gt bq0)) (pow_pos qR0 _), abs_of_pos bq0, one_mul, -- ... and revert to integers ← int.cast_pow, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_mul, ← int.cast_sub, ← int.cast_abs, ← int.cast_mul, int.cast_lt] at a1, -- At a0, clear denominators... replace a0 : ¬a * q - ↑b * p = 0, by rwa [ne.def, div_eq_div_iff b0 (ne_of_gt qR0), mul_comm ↑p, ← sub_eq_zero, -- ... and revert to integers ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_mul, ← int.cast_sub, int.cast_eq_zero] at a0, -- Actually, `q` is a natural number lift q to ℕ using (zero_lt_one.trans q1).le, -- Looks innocuous, but we now have an integer with non-zero absolute value: this is at -- least one away from zero. The gain here is what gets the proof going. have ap : 0 < abs (a * ↑q - ↑b * p) := abs_pos.mpr a0, -- Actually, the absolute value of an integer is a natural number lift (abs (a * ↑q - ↑b * p)) to ℕ using (abs_nonneg (a * ↑q - ↑b * p)), -- At a1, revert to natural numbers rw [← int.coe_nat_mul, ← int.coe_nat_pow, ← int.coe_nat_mul, int.coe_nat_lt] at a1, -- Recall this is by contradiction: we obtained the inequality `b * q ≤ x * q ^ (b + 1)`, so -- we are done. exact not_le.mpr a1 (nat.mul_lt_mul_pow_succ (int.coe_nat_pos.mp ap) (int.coe_nat_lt.mp q1)).le, end open polynomial metric set real ring_hom /-- Let `Z, N` be types, let `R` be a metric space, let `α : R` be a point and let `j : Z → N → R` be a function. We aim to estimate how close we can get to `α`, while staying in the image of `j`. The points `j z a` of `R` in the image of `j` come with a "cost" equal to `d a`. As we get closer to `α` while staying in the image of `j`, we are interested in bounding the quantity `d a * dist α (j z a)` from below by a strictly positive amount `1 / A`: the intuition is that approximating well `α` with the points in the image of `j` should come at a high cost. The hypotheses on the function `f : R → R` provide us with sufficient conditions to ensure our goal. The first hypothesis is that `f` is Lipschitz at `α`: this yields a bound on the distance. The second hypothesis is specific to the Liouville argument and provides the missing bound involving the cost function `d`. This lemma collects the properties used in the proof of `exists_pos_real_of_irrational_root`. It is stated in more general form than needed: in the intended application, `Z = ℤ`, `N = ℕ`, `R = ℝ`, `d a = (a + 1) ^ f.nat_degree`, `j z a = z / (a + 1)`, `f ∈ ℤ[x]`, `α` is an irrational root of `f`, `ε` is small, `M` is a bound on the Lipschitz constant of `f` near `α`, `n` is the degree of the polynomial `f`. -/ lemma exists_one_le_pow_mul_dist {Z N R : Type*} [metric_space R] {d : N → ℝ} {j : Z → N → R} {f : R → R} {α : R} {ε M : ℝ} -- denominators are positive (d0 : ∀ (a : N), 1 ≤ d a) (e0 : 0 < ε) -- function is Lipschitz at α (B : ∀ ⦃y : R⦄, y ∈ closed_ball α ε → dist (f α) (f y) ≤ (dist α y) * M) -- clear denominators (L : ∀ ⦃z : Z⦄, ∀ ⦃a : N⦄, j z a ∈ closed_ball α ε → 1 ≤ (d a) * dist (f α) (f (j z a))) : ∃ A : ℝ, 0 < A ∧ ∀ (z : Z), ∀ (a : N), 1 ≤ (d a) * (dist α (j z a) * A) := begin -- A useful inequality to keep at hand have me0 : 0 < max (1 / ε) M := lt_max_iff.mpr (or.inl (one_div_pos.mpr e0)), -- The maximum between `1 / ε` and `M` works refine ⟨max (1 / ε) M, me0, λ z a, _⟩, -- First, let's deal with the easy case in which we are far away from `α` by_cases dm1 : 1 ≤ (dist α (j z a) * max (1 / ε) M), { exact one_le_mul_of_one_le_of_one_le (d0 a) dm1 }, { -- `j z a = z / (a + 1)`: we prove that this ratio is close to `α` have : j z a ∈ closed_ball α ε, { refine mem_closed_ball'.mp (le_trans _ ((one_div_le me0 e0).mpr (le_max_left _ _))), exact ((le_div_iff me0).mpr (not_le.mp dm1).le) }, -- use the "separation from `1`" (assumption `L`) for numerators, refine (L this).trans _, -- remove a common factor and use the Lipschitz assumption `B` refine mul_le_mul_of_nonneg_left ((B this).trans _) (zero_le_one.trans (d0 a)), exact mul_le_mul_of_nonneg_left (le_max_right _ M) dist_nonneg } end lemma exists_pos_real_of_irrational_root {α : ℝ} (ha : irrational α) {f : polynomial ℤ} (f0 : f ≠ 0) (fa : eval α (map (algebra_map ℤ ℝ) f) = 0): ∃ A : ℝ, 0 < A ∧ ∀ (a : ℤ), ∀ (b : ℕ), (1 : ℝ) ≤ (b + 1) ^ f.nat_degree * (abs (α - (a / (b + 1))) * A) := begin -- `fR` is `f` viewed as a polynomial with `ℝ` coefficients. set fR : polynomial ℝ := map (algebra_map ℤ ℝ) f, -- `fR` is non-zero, since `f` is non-zero. obtain fR0 : fR ≠ 0 := λ fR0, (map_injective (algebra_map ℤ ℝ) (λ _ _ A, int.cast_inj.mp A)).ne f0 (fR0.trans (polynomial.map_zero _).symm), -- reformulating assumption `fa`: `α` is a root of `fR`. have ar : α ∈ (fR.roots.to_finset : set ℝ) := finset.mem_coe.mpr (multiset.mem_to_finset.mpr ((mem_roots fR0).mpr (is_root.def.mpr fa))), -- Since the polynomial `fR` has finitely many roots, there is a closed interval centered at `α` -- such that `α` is the only root of `fR` in the interval. obtain ⟨ζ, z0, U⟩ : ∃ ζ > 0, closed_ball α ζ ∩ (fR.roots.to_finset) = {α} := @exists_closed_ball_inter_eq_singleton_of_discrete _ _ _ discrete_of_t1_of_finite _ ar, -- Since `fR` is continuous, it is bounded on the interval above. obtain ⟨xm, -, hM⟩ : ∃ (xm : ℝ) (H : xm ∈ Icc (α - ζ) (α + ζ)), ∀ (y : ℝ), y ∈ Icc (α - ζ) (α + ζ) → abs (fR.derivative.eval y) ≤ abs (fR.derivative.eval xm) := is_compact.exists_forall_ge is_compact_Icc ⟨α, (sub_lt_self α z0).le, (lt_add_of_pos_right α z0).le⟩ (continuous_abs.comp fR.derivative.continuous_aeval).continuous_on, -- Use the key lemma `exists_one_le_pow_mul_dist`: we are left to show that ... refine @exists_one_le_pow_mul_dist ℤ ℕ ℝ _ _ _ (λ y, fR.eval y) α ζ (abs (fR.derivative.eval xm)) _ z0 (λ y hy, _) (λ z a hq, _), -- 1: the denominators are positive -- essentially by definition; { exact λ a, one_le_pow_of_one_le ((le_add_iff_nonneg_left 1).mpr a.cast_nonneg) _ }, -- 2: the polynomial `fR` is Lipschitz at `α` -- as its derivative continuous; { rw mul_comm, rw closed_ball_Icc at hy, -- apply the Mean Value Theorem: the bound on the derivative comes from differentiability. refine convex.norm_image_sub_le_of_norm_deriv_le (λ _ _, fR.differentiable_at) (λ y h, by { rw fR.deriv, exact hM _ h }) (convex_Icc _ _) hy (mem_Icc_iff_abs_le.mp _), exact @mem_closed_ball_self ℝ _ α ζ (le_of_lt z0) }, -- 3: the weird inequality of Liouville type with powers of the denominators. { show 1 ≤ (a + 1 : ℝ) ^ f.nat_degree * abs (eval α fR - eval (z / (a + 1)) fR), rw [fa, zero_sub, abs_neg], -- key observation: the right-hand side of the inequality is an *integer*. Therefore, -- if its absolute value is not at least one, then it vanishes. Proceed by contradiction refine one_le_pow_mul_abs_eval_div (int.coe_nat_succ_pos a) (λ hy, _), -- As the evaluation of the polynomial vanishes, we found a root of `fR` that is rational. -- We know that `α` is the only root of `fR` in our interval, and `α` is irrational: -- follow your nose. refine (irrational_iff_ne_rational α).mp ha z (a + 1) ((mem_singleton_iff.mp _).symm), refine U.subset _, refine ⟨hq, finset.mem_coe.mp (multiset.mem_to_finset.mpr _)⟩, exact (mem_roots fR0).mpr (is_root.def.mpr hy) } end theorem transcendental {x : ℝ} (lx : liouville x) : transcendental ℤ x := begin -- Proceed by contradiction: if `x` is algebraic, then `x` is the root (`ef0`) of a -- non-zero (`f0`) polynomial `f` rintros ⟨f : polynomial ℤ, f0, ef0⟩, -- Change `aeval x f = 0` to `eval (map _ f) = 0`, who knew. replace ef0 : (f.map (algebra_map ℤ ℝ)).eval x = 0, { rwa [aeval_def, ← eval_map] at ef0 }, -- There is a "large" real number `A` such that `(b + 1) ^ (deg f) * |f (x - a / (b + 1))| * A` -- is at least one. This is obtained from lemma `exists_pos_real_of_irrational_root`. obtain ⟨A, hA, h⟩ : ∃ (A : ℝ), 0 < A ∧ ∀ (a : ℤ) (b : ℕ), (1 : ℝ) ≤ (b.succ) ^ f.nat_degree * (abs (x - a / (b.succ)) * A) := exists_pos_real_of_irrational_root lx.irrational f0 ef0, -- Since the real numbers are Archimedean, a power of `2` exceeds `A`: `hn : A < 2 ^ r`. rcases pow_unbounded_of_one_lt A (lt_add_one 1) with ⟨r, hn⟩, -- Use the Liouville property, with exponent `r + deg f`. obtain ⟨a, b, b1, -, a1⟩ : ∃ (a b : ℤ), 1 < b ∧ x ≠ a / b ∧ abs (x - a / b) < 1 / b ^ (r + f.nat_degree) := lx (r + f.nat_degree), have b0 : (0 : ℝ) < b := zero_lt_one.trans (by { rw ← int.cast_one, exact int.cast_lt.mpr b1 }), -- Prove that `b ^ f.nat_degree * abs (x - a / b)` is strictly smaller than itself -- recall, this is a proof by contradiction! refine lt_irrefl ((b : ℝ) ^ f.nat_degree * abs (x - ↑a / ↑b)) _, -- clear denominators at `a1` rw [lt_div_iff' (pow_pos b0 _), pow_add, mul_assoc] at a1, -- split the inequality via `1 / A`. refine ((_ : (b : ℝ) ^ f.nat_degree * abs (x - a / b) < 1 / A).trans_le _), -- This branch of the proof uses the Liouville condition and the Archimedean property { refine (lt_div_iff' hA).mpr _, refine lt_of_le_of_lt _ a1, refine mul_le_mul_of_nonneg_right _ (mul_nonneg (pow_nonneg b0.le _) (abs_nonneg _)), refine hn.le.trans _, refine pow_le_pow_of_le_left zero_le_two _ _, exact int.cast_two.symm.le.trans (int.cast_le.mpr (int.add_one_le_iff.mpr b1)) }, -- this branch of the proof exploits the "integrality" of evaluations of polynomials -- at ratios of integers. { lift b to ℕ using zero_le_one.trans b1.le, specialize h a b.pred, rwa [nat.succ_pred_eq_of_pos (zero_lt_one.trans _), ← mul_assoc, ← (div_le_iff hA)] at h, exact int.coe_nat_lt.mp b1 } end end liouville
77aaf4d1bf06d2964c6acd882464861ac59cd98d
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/real/basic.lean
c4c91150e266a0864f1d6190558a42e4deb41e8d
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
25,015
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import order.conditionally_complete_lattice import data.real.cau_seq_completion import algebra.archimedean import algebra.star.basic /-! # Real numbers from Cauchy sequences This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers. This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply lifting everything to `ℚ`. -/ /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure real := of_cauchy :: (cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _) notation `ℝ` := real attribute [pp_using_anonymous_constructor] real namespace real open cau_seq cau_seq.completion variables {x y : ℝ} lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩ ⟨b⟩ := by split; cc lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy := ⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 @[irreducible] private def zero : ℝ := ⟨0⟩ @[irreducible] private def one : ℝ := ⟨1⟩ @[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero ℝ := ⟨zero⟩ instance : has_one ℝ := ⟨one⟩ instance : has_add ℝ := ⟨add⟩ instance : has_neg ℝ := ⟨neg⟩ instance : has_mul ℝ := ⟨mul⟩ lemma zero_cauchy : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero lemma one_cauchy : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one lemma add_cauchy {a b} : (⟨a⟩ + ⟨b⟩ : ℝ) = ⟨a + b⟩ := show add _ _ = _, by rw add lemma neg_cauchy {a} : (-⟨a⟩ : ℝ) = ⟨-a⟩ := show neg _ = _, by rw neg lemma mul_cauchy {a b} : (⟨a⟩ * ⟨b⟩ : ℝ) = ⟨a * b⟩ := show mul _ _ = _, by rw mul instance : comm_ring ℝ := begin refine_struct { zero := 0, one := 1, mul := (*), add := (+), neg := @has_neg.neg ℝ _, sub := λ a b, a + (-b), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨@has_neg.neg ℝ _⟩ }; repeat { rintro ⟨_⟩, }; try { refl }; simp [← zero_cauchy, ← one_cauchy, add_cauchy, neg_cauchy, mul_cauchy]; apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|> apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip end /-! Extra instances to short-circuit type class resolution. These short-circuits have an additional property of ensuring that a computable path is found; if `field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable` version of them. -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : has_sub ℝ := by apply_instance instance : module ℝ ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : star_ring ℝ := star_ring_of_comm /-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this is `cau_seq.completion.of_rat`, not `rat.cast`. -/ def of_rat : ℚ →+* ℝ := by refine_struct { to_fun := of_cauchy ∘ of_rat }; simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add, one_cauchy, zero_cauchy, ← mul_cauchy, ← add_cauchy] lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩ theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans mk_eq @[irreducible] private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ := quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩ instance : has_lt ℝ := ⟨lt⟩ lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy lemma mk_zero : mk 0 = 0 := by rw ← zero_cauchy; refl lemma mk_one : mk 1 = 1 := by rw ← one_cauchy; refl lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, add_cauchy] lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, mul_cauchy] lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, neg_cauchy] @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f)) @[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨le⟩ private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp [le_def, mk_eq]; refl @[elab_as_eliminator] protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x := begin cases x with x, induction x using quot.induction_on with x, exact h x end theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := begin induction a using real.ind_mk, induction b using real.ind_mk, induction c using real.ind_mk, simp only [mk_lt, ← mk_add], show pos _ ↔ pos _, rw add_sub_add_left_eq_sub end instance : partial_order ℝ := { le := (≤), lt := (<), lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_refl := λ a, a.ind_mk (by intro a; rw mk_le), le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c, by simpa using le_trans, lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b } instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := begin rw [mk_lt] {md := tactic.transparency.semireducible}, exact const_lt end protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert of_rat_lt.2 zero_lt_one; simp protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := begin induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos end instance : ordered_ring ℝ := { add_le_add_left := begin simp only [le_iff_eq_or_lt], rintros a b ⟨rfl, h⟩, { simp }, { exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) } end, zero_le_one := le_of_lt real.zero_lt_one, mul_pos := @real.mul_pos, .. real.comm_ring, .. real.partial_order, .. real.semiring } instance : ordered_semiring ℝ := by apply_instance instance : ordered_add_comm_group ℝ := by apply_instance instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance instance : ordered_add_comm_monoid ℝ := by apply_instance instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩ open_locale classical noncomputable instance : linear_order ℝ := { le_total := begin intros a b, induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa using le_total a b, end, decidable_le := by apply_instance, .. real.partial_order } noncomputable instance : linear_ordered_comm_ring ℝ := { .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_ring ℝ := by apply_instance noncomputable instance : linear_ordered_semiring ℝ := by apply_instance instance : domain ℝ := { .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.to_domain } /-- The real numbers are an ordered `*`-ring, with the trivial `*`-structure. -/ instance : star_ordered_ring ℝ := { star_mul_self_nonneg := λ r, mul_self_nonneg r, } @[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩ noncomputable instance : has_inv ℝ := ⟨inv'⟩ lemma inv_cauchy {f} : (⟨f⟩ : ℝ)⁻¹ = ⟨f⁻¹⟩ := show inv' _ = _, by rw inv' noncomputable instance : linear_ordered_field ℝ := { inv := has_inv.inv, mul_inv_cancel := begin rintros ⟨a⟩ h, rw mul_comm, simp only [inv_cauchy, mul_cauchy, ← one_cauchy, ← zero_cauchy, ne.def] at *, exact cau_seq.completion.inv_mul_cancel h, end, inv_zero := by simp [← zero_cauchy, inv_cauchy], ..real.linear_ordered_comm_ring, ..real.domain } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance noncomputable instance field : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : integral_domain ℝ := by apply_instance noncomputable instance : distrib_lattice ℝ := by apply_instance noncomputable instance : lattice ℝ := by apply_instance noncomputable instance : semilattice_inf ℝ := by apply_instance noncomputable instance : semilattice_sup ℝ := by apply_instance noncomputable instance : has_inf ℝ := by apply_instance noncomputable instance : has_sup ℝ := by apply_instance noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := of_rat.eq_rat_cast theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := begin intro h, induction x using real.ind_mk with x, apply le_of_not_lt, rw mk_lt, rintro ⟨K, K0, hK⟩, obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)), apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, rw [mk_lt] {md := tactic.transparency.semireducible}, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := begin cases h with i H, rw [← neg_le_neg_iff, ← mk_neg], exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ end theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_is_lub (S : set ℝ) (hne : S.nonempty) (hbdd : bdd_above S) : ∃ x, is_lub S x := begin rcases ⟨hne, hbdd⟩ with ⟨⟨L, hL⟩, ⟨U, hU⟩⟩, have : ∀ d : ℕ, bdd_above {m : ℤ | ∃ y ∈ S, (m : ℝ) ≤ y * d}, { cases exists_int_gt U with k hk, refine λ d, ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (hy.trans _), push_cast, exact mul_le_mul_of_nonneg_right ((hU yS).trans hk.le) d.cast_nonneg }, choose f hf using λ d : ℕ, int.exists_greatest_of_bdd (this d) ⟨⌊L * d⌋, L, hL, floor_le _⟩, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, have hg : is_cau_seq abs (λ n, f n / n : ℕ → ℚ), { intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) }, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, ⟨λ x xS, _, λ y h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h xS)⟩ } end noncomputable instance : has_Sup ℝ := ⟨λ S, if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_is_lub S h.1 h.2) else 0⟩ lemma Sup_def (S : set ℝ) : Sup S = if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_is_lub S h.1 h.2) else 0 := rfl theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp only [Sup_def, dif_pos (and.intro h₁ h₂)]; exact is_lub_le_iff (classical.some_spec (exists_is_lub S h₁ h₂)) theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := ⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs, λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩ noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup {x | -x ∈ S}⟩ lemma Inf_def (S : set ℝ) : Inf S = -Sup {x | -x ∈ S} := rfl theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end section -- this proof times out without this local attribute [instance, priority 1000] classical.prop_decidable theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) end theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := has_Sup.Sup, Inf := has_Inf.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s ‹s.nonempty› H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s ‹s.nonempty› H, ..real.linear_order, ..real.lattice} lemma lt_Inf_add_pos {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {ε : ℝ} (hε : 0 < ε) : ∃ a ∈ s, a < Inf s + ε := (Inf_lt _ h' h).1 $ lt_add_of_pos_right _ hε lemma add_neg_lt_Sup {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {ε : ℝ} (hε : ε < 0) : ∃ a ∈ s, Sup s + ε < a := (real.lt_Sup _ h' h).1 $ add_lt_iff_neg_left.mpr hε lemma Inf_le_iff {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {a : ℝ} : Inf s ≤ a ↔ ∀ ε, 0 < ε → ∃ x ∈ s, x < a + ε := begin rw le_iff_forall_pos_lt_add, split; intros H ε ε_pos, { exact exists_lt_of_cInf_lt h' (H ε ε_pos) }, { rcases H ε ε_pos with ⟨x, x_in, hx⟩, exact cInf_lt_of_lt h x_in hx } end lemma le_Sup_iff {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {a : ℝ} : a ≤ Sup s ↔ ∀ ε, ε < 0 → ∃ x ∈ s, a + ε < x := begin rw le_iff_forall_pos_lt_add, refine ⟨λ H ε ε_neg, _, λ H ε ε_pos, _⟩, { exact exists_lt_of_lt_cSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr ε_neg))) }, { rcases H _ (neg_lt_zero.mpr ε_pos) with ⟨x, x_in, hx⟩, exact sub_lt_iff_lt_add.mp (lt_cSup_of_lt h x_in hx) } end @[simp] theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Sup_univ : Sup (@set.univ ℝ) = 0 := real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _) @[simp] theorem Inf_empty : Inf (∅ : set ℝ) = 0 := by simp [Inf_def, Sup_empty] theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 := have bdd_above {x | -x ∈ s} → bdd_below s, from assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb $ by simp [hxs]⟩, have ¬ bdd_above {x | -x ∈ s}, from mt this hs, neg_eq_zero.2 $ Sup_of_not_bdd_above $ this /-- As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Sup_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Sup S := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { exact Sup_empty.ge }, { apply dite _ (λ h, le_cSup_of_le h hy $ hS y hy) (λ h, (Sup_of_not_bdd_above h).ge) } end /-- As `0` is the default value for `real.Sup` of the empty set, it suffices to show that `S` is bounded above by `0` to show that `Sup S ≤ 0`. -/ lemma Sup_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Sup S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, exacts [Sup_empty.le, Sup_le_ub _ hS₂ hS], end /-- As `0` is the default value for `real.Inf` of the empty set, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Inf_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Inf S := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, exacts [Inf_empty.ge, lb_le_Inf S hS₂ hS] end /-- As `0` is the default value for `real.Inf` of the empty set or sets which are not bounded below, it suffices to show that `S` is bounded above by `0` to show that `Inf S ≤ 0`. -/ lemma Inf_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Inf S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { exact Inf_empty.le }, { apply dite _ (λ h, cInf_le_of_le h hy $ hS y hy) (λ h, (Inf_of_not_bdd_below h).le) } end lemma Inf_le_Sup (s : set ℝ) (h₁ : bdd_below s) (h₂ : bdd_above s) : Inf s ≤ Sup s := begin rcases s.eq_empty_or_nonempty with rfl | hne, { rw [Inf_empty, Sup_empty] }, { exact cInf_le_cSup h₁ h₂ hne } end theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) (sub_lt_self _ (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ end real