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
cce5ee5eb6828971aebdb1f6c3ecde3e4f76cd9b
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/algebra/category/Group/basic.lean
6c94b3e99b4e0fd07fb6d823b3727bfb4b82f522
[ "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
9,373
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.category.Mon.basic import category_theory.endomorphism /-! # Category instances for group, add_group, comm_group, and add_comm_group. We introduce the bundled categories: * `Group` * `AddGroup` * `CommGroup` * `AddCommGroup` along with the relevant forgetful functors between them, and to the bundled monoid categories. ## Implementation notes See the note [locally reducible category instances]. -/ universes u v open category_theory /-- The category of groups and group morphisms. -/ @[to_additive AddGroup] def Group : Type (u+1) := bundled group /-- The category of additive groups and group morphisms -/ add_decl_doc AddGroup namespace Group @[to_additive] instance : bundled_hom.parent_projection group.to_monoid := ⟨⟩ /-- Construct a bundled `Group` from the underlying type and typeclass. -/ @[to_additive] def of (X : Type u) [group X] : Group := bundled.of X /-- Construct a bundled `AddGroup` from the underlying type and typeclass. -/ add_decl_doc AddGroup.of local attribute [reducible] Group @[to_additive] instance : has_coe_to_sort Group := infer_instance -- short-circuit type class inference @[to_additive add_group] instance (G : Group) : group G := G.str @[to_additive] instance : has_one Group := ⟨Group.of punit⟩ @[to_additive] instance : inhabited Group := ⟨1⟩ @[to_additive] instance : unique (1 : Group) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : Group) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[to_additive] instance : category Group := infer_instance -- short-circuit type class inference @[to_additive] instance : concrete_category Group := infer_instance -- short-circuit type class inference @[to_additive,ext] lemma ext (G H : Group) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } attribute [ext] AddGroup.ext @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ Group Mon := bundled_hom.forget₂ _ _ end Group /-- The category of commutative groups and group morphisms. -/ @[to_additive AddCommGroup] def CommGroup : Type (u+1) := bundled comm_group /-- The category of additive commutative groups and group morphisms. -/ add_decl_doc AddCommGroup /-- `Ab` is an abbreviation for `AddCommGroup`, for the sake of mathematicians' sanity. -/ abbreviation Ab := AddCommGroup namespace CommGroup @[to_additive] instance : bundled_hom.parent_projection comm_group.to_group := ⟨⟩ /-- Construct a bundled `CommGroup` from the underlying type and typeclass. -/ @[to_additive] def of (G : Type u) [comm_group G] : CommGroup := bundled.of G /-- Construct a bundled `AddCommGroup` from the underlying type and typeclass. -/ add_decl_doc AddCommGroup.of local attribute [reducible] CommGroup @[to_additive] instance : has_coe_to_sort CommGroup := infer_instance -- short-circuit type class inference @[to_additive add_comm_group_instance] instance comm_group_instance (G : CommGroup) : comm_group G := G.str @[to_additive] instance : has_one CommGroup := ⟨CommGroup.of punit⟩ @[to_additive] instance : inhabited CommGroup := ⟨1⟩ @[to_additive] instance : unique (1 : CommGroup) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : CommGroup) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[to_additive] instance : category CommGroup := infer_instance -- short-circuit type class inference @[to_additive] instance : concrete_category CommGroup := infer_instance -- short-circuit type class inference @[to_additive,ext] lemma ext (G H : CommGroup) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } attribute [ext] AddCommGroup.ext @[to_additive has_forget_to_AddGroup] instance has_forget_to_Group : has_forget₂ CommGroup Group := bundled_hom.forget₂ _ _ @[to_additive has_forget_to_AddCommMon] instance has_forget_to_CommMon : has_forget₂ CommGroup CommMon := induced_category.has_forget₂ (λ G : CommGroup, CommMon.of G) end CommGroup -- This example verifies an improvement possible in Lean 3.8. -- Before that, to have `monoid_hom.map_map` usable by `simp` here, -- we had to mark all the concrete category `has_coe_to_sort` instances reducible. -- Now, it just works. @[to_additive] example {R S : CommGroup} (i : R ⟶ S) (r : R) (h : r = 1) : i r = 1 := by simp [h] namespace AddCommGroup /-- Any element of an abelian group gives a unique morphism from `ℤ` sending `1` to that element. -/ -- Note that because `ℤ : Type 0`, this forces `G : AddCommGroup.{0}`, -- so we write this explicitly to be clear. -- TODO generalize this, requiring a `ulift_instances.lean` file def as_hom {G : AddCommGroup.{0}} (g : G) : (AddCommGroup.of ℤ) ⟶ G := gmultiples_hom G g @[simp] lemma as_hom_apply {G : AddCommGroup.{0}} (g : G) (i : ℤ) : (as_hom g) i = i • g := rfl lemma as_hom_injective {G : AddCommGroup.{0}} : function.injective (@as_hom G) := λ h k w, by convert congr_arg (λ k : (AddCommGroup.of ℤ) ⟶ G, (k : ℤ → G) (1 : ℤ)) w; simp @[ext] lemma int_hom_ext {G : AddCommGroup.{0}} (f g : (AddCommGroup.of ℤ) ⟶ G) (w : f (1 : ℤ) = g (1 : ℤ)) : f = g := add_monoid_hom.ext_int w -- TODO: this argument should be generalised to the situation where -- the forgetful functor is representable. lemma injective_of_mono {G H : AddCommGroup.{0}} (f : G ⟶ H) [mono f] : function.injective f := λ g₁ g₂ h, begin have t0 : as_hom g₁ ≫ f = as_hom g₂ ≫ f := begin ext, simpa [as_hom_apply] using h, end, have t1 : as_hom g₁ = as_hom g₂ := (cancel_mono _).1 t0, apply as_hom_injective t1, end end AddCommGroup variables {X Y : Type u} /-- Build an isomorphism in the category `Group` from a `mul_equiv` between `group`s. -/ @[to_additive add_equiv.to_AddGroup_iso] def mul_equiv.to_Group_iso [group X] [group Y] (e : X ≃* Y) : Group.of X ≅ Group.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } /-- Build an isomorphism in the category `AddGroup` from an `add_equiv` between `add_group`s. -/ add_decl_doc add_equiv.to_AddGroup_iso attribute [simps] mul_equiv.to_Group_iso add_equiv.to_AddGroup_iso /-- Build an isomorphism in the category `CommGroup` from a `mul_equiv` between `comm_group`s. -/ @[to_additive add_equiv.to_AddCommGroup_iso] def mul_equiv.to_CommGroup_iso [comm_group X] [comm_group Y] (e : X ≃* Y) : CommGroup.of X ≅ CommGroup.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } /-- Build an isomorphism in the category `AddCommGroup` from a `add_equiv` between `add_comm_group`s. -/ add_decl_doc add_equiv.to_AddCommGroup_iso attribute [simps] mul_equiv.to_CommGroup_iso add_equiv.to_AddCommGroup_iso namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Group`. -/ @[to_additive AddGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddGroup`."] def Group_iso_to_mul_equiv {X Y : Group} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. attribute [simps] Group_iso_to_mul_equiv AddGroup_iso_to_add_equiv /-- Build a `mul_equiv` from an isomorphism in the category `CommGroup`. -/ @[to_additive AddCommGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommGroup`."] def CommGroup_iso_to_mul_equiv {X Y : CommGroup} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. attribute [simps] CommGroup_iso_to_mul_equiv AddCommGroup_iso_to_add_equiv end category_theory.iso /-- multiplicative equivalences between `group`s are the same as (isomorphic to) isomorphisms in `Group` -/ @[to_additive add_equiv_iso_AddGroup_iso "additive equivalences between `add_group`s are the same as (isomorphic to) isomorphisms in `AddGroup`"] def mul_equiv_iso_Group_iso {X Y : Type u} [group X] [group Y] : (X ≃* Y) ≅ (Group.of X ≅ Group.of Y) := { hom := λ e, e.to_Group_iso, inv := λ i, i.Group_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_group`s are the same as (isomorphic to) isomorphisms in `CommGroup` -/ @[to_additive add_equiv_iso_AddCommGroup_iso "additive equivalences between `add_comm_group`s are the same as (isomorphic to) isomorphisms in `AddCommGroup`"] def mul_equiv_iso_CommGroup_iso {X Y : Type u} [comm_group X] [comm_group Y] : (X ≃* Y) ≅ (CommGroup.of X ≅ CommGroup.of Y) := { hom := λ e, e.to_CommGroup_iso, inv := λ i, i.CommGroup_iso_to_mul_equiv, } namespace category_theory.Aut /-- The (bundled) group of automorphisms of a type is isomorphic to the (bundled) group of permutations. -/ def iso_perm {α : Type u} : Group.of (Aut α) ≅ Group.of (equiv.perm α) := { hom := ⟨λ g, g.to_equiv, (by tidy), (by tidy)⟩, inv := ⟨λ g, g.to_iso, (by tidy), (by tidy)⟩ } /-- The (unbundled) group of automorphisms of a type is `mul_equiv` to the (unbundled) group of permutations. -/ def mul_equiv_perm {α : Type u} : Aut α ≃* equiv.perm α := iso_perm.Group_iso_to_mul_equiv end category_theory.Aut
1c5b86617c2faa0b189ad3d9063bf72e5a5a4414
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/int/form.lean
6f68dacc1117fdd78dc32f3bf94bcaeeddb0c145
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
3,046
lean
import .preterm --..simp_omega ..logic namespace int @[derive has_reflect] inductive form | eq : preterm → preterm → form | le : preterm → preterm → form | not : form → form | or : form → form → form | and : form → form → form notation x `=*` y := form.eq x y notation x `≤*` y := form.le x y notation `¬*` p := form.not p notation p `∨*` q := form.or p q notation p `∧*` q := form.and p q -- | (t =* s) := -- | (t ≤* s) := -- | (¬* p) := -- | (p ∨* q) := -- | (p ∧* q) := def valuation.cons (i : int) (v : nat → int) : nat → int | 0 := i | (k+1) := v k notation i `::` v := valuation.cons i v open tactic namespace form @[omega] def holds (v : nat → int) : form → Prop | (t =* s) := t.val v = s.val v | (t ≤* s) := t.val v ≤ s.val v | (¬* p) := ¬ p.holds | (p ∨* q) := p.holds ∨ q.holds | (p ∧* q) := p.holds ∧ q.holds end form @[omega] def uniclo (p : form) : (nat → int) → nat → Prop | v 0 := p.holds v | v (k+1) := ∀ i : int, uniclo (i::v) k namespace form def fresh_idx : form → nat | (t =* s) := max t.fresh_idx s.fresh_idx | (t ≤* s) := max t.fresh_idx s.fresh_idx | (¬* p) := p.fresh_idx | (p ∨* q) := max p.fresh_idx q.fresh_idx | (p ∧* q) := max p.fresh_idx q.fresh_idx --def uniclo (p : form) : Prop := --uniclo_core p p.fresh_idx (λ _, 0) def valid (p : form) : Prop := ∀ v, holds v p def sat (p : form) : Prop := ∃ v, holds v p def implies (p q : form) : Prop := ∀ v, (holds v p → holds v q) def equiv (p q : form) : Prop := ∀ v, (holds v p ↔ holds v q) lemma sat_of_implies_of_sat {p q} : implies p q → sat p → sat q := begin intros h1 h2, apply exists_of_exists h1 h2 end lemma sat_or {p q : form} : sat (p ∨* q) ↔ sat p ∨ sat q := begin constructor; intro h1, { cases h1 with v h1, cases h1 with h1 h1; [left,right]; refine ⟨v,_⟩; assumption }, { cases h1 with h1 h1; cases h1 with v h1; refine ⟨v,_⟩; [left,right]; assumption } end def unsat (p : form) : Prop := ¬ sat p def repr : form → string | (t =* s) := "(" ++ t.repr ++ " = " ++ s.repr ++ ")" | (t ≤* s) := "(" ++ t.repr ++ " ≤ " ++ s.repr ++ ")" | (¬* p) := "¬" ++ p.repr | (p ∨* q) := "(" ++ p.repr ++ " ∨ " ++ q.repr ++ ")" | (p ∧* q) := "(" ++ p.repr ++ " ∧ " ++ q.repr ++ ")" instance has_repr : has_repr form := ⟨repr⟩ meta instance has_to_format : has_to_format form := ⟨λ x, x.repr⟩ end form lemma uniclo_of_valid {p : form} : ∀ {m v}, p.valid → uniclo p v m | 0 v h1 := h1 _ | (m+1) v h1 := λ i, uniclo_of_valid h1 --lemma uniclo_of_valid {p : form} (h : p.valid) : p.uniclo := --uniclo_core_of_valid h lemma valid_of_unsat_not {p : form} : (¬*p).unsat → p.valid := begin simp only [form.sat, form.unsat, form.valid, form.holds], rw classical.not_exists_not, intro h, assumption end meta def form.induce (t : tactic unit := skip) : tactic unit := `[ intro p, induction p with t s t s p ih p q ihp ihq p q ihp ihq; t] end int
4cfb3b4dc6612cf7409cffe6e47158b722812cb4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1039.lean
345f10eca7769f88a82f9a4124fc9e953a16854a
[ "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
1,464
lean
import Lean.Elab.BuiltinCommand open Lean.Elab.Command open Lean namespace Something namespace MyNamespace local elab "end" id:ident : command => do println!"foo" let node := mkNode ``Lean.Parser.Command.end #[Lean.mkAtom "end", mkOptionalNode id] elabEnd node end MyNamespace -- print "foo" end Something -- nothing namespace Something namespace MyNamespace @[local command_elab Lean.Parser.Command.end] def elabEnd' : CommandElab := fun stx => match stx with | `(end $id:ident) => do println!"boo" let node := mkNode ``Lean.Parser.Command.end #[Lean.mkAtom "end", mkOptionalNode id] elabEnd node | _ => Elab.throwUnsupportedSyntax end MyNamespace -- print "boo" end Something -- print nothing as expected namespace Something' namespace MyNamespace local elab_rules : command | `(end $id:ident) => do println!"hello" let node := mkNode ``Lean.Parser.Command.end #[Lean.mkAtom "end", mkOptionalNode id] elabEnd node end MyNamespace -- print "hello" end Something' -- print nothing as expected namespace Something'' namespace MyNamespace scoped elab_rules : command | `(end $id:ident) => do println!"bla" let node := mkNode ``Lean.Parser.Command.end #[Lean.mkAtom "end", mkOptionalNode id] elabEnd node end MyNamespace -- print "bla" end Something'' -- should print nothing namespace Something'' namespace MyNamespace end MyNamespace -- print "bla" end Something'' -- should print nothing
3767bdb19a6c89a90ac372714f8f1236e8e10d76
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/fourier/add_circle.lean
4ad7a556d91e683b98cb841e78d04a997f57a6c6
[ "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
23,578
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, David Loeffler -/ import analysis.special_functions.complex.circle import topology.instances.add_circle import analysis.inner_product_space.l2_space import measure_theory.function.continuous_map_dense import measure_theory.function.l2_space import measure_theory.group.integration import measure_theory.integral.periodic import topology.continuous_function.stone_weierstrass /-! # Fourier analysis on the additive circle This file contains basic results on Fourier series for functions on the additive circle `add_circle T = ℝ / ℤ • T`. ## Main definitions * `haar_add_circle`, Haar measure on `add_circle T`, normalized to have total measure `1`. (Note that this is not the same normalisation as the standard measure defined in `integral.periodic`, so we do not declare it as a `measure_space` instance, to avoid confusion.) * for `n : ℤ`, `fourier n` is the monomial `λ x, exp (2 π i n x / T)`, bundled as a continuous map from `add_circle T` to `ℂ`. * `fourier_basis` is the Hilbert basis of `Lp ℂ 2 haar_add_circle` given by the images of the monomials `fourier n`. * `fourier_coeff f n`, for `f : add_circle T → E` (with `E` a complete normed `ℂ`-vector space), is the `n`-th Fourier coefficient of `f`, defined as an integral over `add_circle T`. The lemma `fourier_coeff_eq_interval_integral` expresses this as an integral over `[a, a + T]` for any real `a`. * `fourier_coeff_on`, for `f : ℝ → E` and `a < b` reals, is the `n`-th Fourier coefficient of the unique periodic function of period `b - a` which agrees with `f` on `(a, b]`. The lemma `fourier_coeff_on_eq_integral` expresses this as an integral over `[a, b]`. ## Main statements The theorem `span_fourier_closure_eq_top` states that the span of the monomials `fourier n` is dense in `C(add_circle T, ℂ)`, i.e. that its `submodule.topological_closure` is `⊤`. This follows from the Stone-Weierstrass theorem after checking that the span is a subalgebra, is closed under conjugation, and separates points. Using this and general theory on approximation of Lᵖ functions by continuous functions, we deduce (`span_fourier_Lp_closure_eq_top`) that for any `1 ≤ p < ∞`, the span of the Fourier monomials is dense in the Lᵖ space of `add_circle T`. For `p = 2` we show (`orthonormal_fourier`) that the monomials are also orthonormal, so they form a Hilbert basis for L², which is named as `fourier_basis`; in particular, for `L²` functions `f`, the Fourier series of `f` converges to `f` in the `L²` topology (`has_sum_fourier_series_L2`). Parseval's identity, `tsum_sq_fourier_coeff`, is a direct consequence. For continuous maps `f : add_circle T → ℂ`, the theorem `continuous_map.has_sum_fourier_series_of_summable` states that if the sequence of Fourier coefficients of `f` is summable, then the Fourier series `∑ (i:ℤ), f.fourier_coeff i * fourier i` converges to `f` in the uniform-convergence topology of `C(add_circle T, ℂ)`. -/ noncomputable theory open_locale ennreal complex_conjugate real open topological_space continuous_map measure_theory measure_theory.measure algebra submodule set variables {T : ℝ} namespace add_circle /-! ### Map from `add_circle` to `circle` -/ lemma scaled_exp_map_periodic : function.periodic (λ x, exp_map_circle (2 * π / T * x)) T := begin -- The case T = 0 is not interesting, but it is true, so we prove it to save hypotheses rcases eq_or_ne T 0 with rfl | hT, { intro x, simp }, { intro x, simp_rw mul_add, rw [div_mul_cancel _ hT, periodic_exp_map_circle] } end /-- The canonical map `λ x, exp (2 π i x / T)` from `ℝ / ℤ • T` to the unit circle in `ℂ`. If `T = 0` we understand this as the constant function 1. -/ def to_circle : add_circle T → circle := (@scaled_exp_map_periodic T).lift lemma to_circle_add (x : add_circle T) (y : add_circle T) : to_circle (x + y) = to_circle x * to_circle y := begin induction x using quotient_add_group.induction_on', induction y using quotient_add_group.induction_on', simp_rw [←quotient_add_group.coe_add, to_circle, function.periodic.lift_coe, mul_add, exp_map_circle_add], end lemma continuous_to_circle : continuous (@to_circle T) := continuous_coinduced_dom.mpr (exp_map_circle.continuous.comp $ continuous_const.mul continuous_id') lemma injective_to_circle (hT : T ≠ 0) : function.injective (@to_circle T) := begin intros a b h, induction a using quotient_add_group.induction_on', induction b using quotient_add_group.induction_on', simp_rw [to_circle, function.periodic.lift_coe] at h, obtain ⟨m, hm⟩ := exp_map_circle_eq_exp_map_circle.mp h.symm, simp_rw [quotient_add_group.eq, add_subgroup.mem_zmultiples_iff, zsmul_eq_mul], use m, field_simp [real.two_pi_pos.ne'] at hm, rw ← mul_right_inj' real.two_pi_pos.ne', linarith end /-! ### Measure on `add_circle T` In this file we use the Haar measure on `add_circle T` normalised to have total measure 1 (which is **not** the same as the standard measure defined in `topology.instances.add_circle`). -/ variables [hT : fact (0 < T)] include hT /-- Haar measure on the additive circle, normalised to have total measure 1. -/ @[derive is_add_haar_measure] def haar_add_circle : measure (add_circle T) := add_haar_measure ⊤ instance : is_probability_measure (@haar_add_circle T _) := is_probability_measure.mk add_haar_measure_self lemma volume_eq_smul_haar_add_circle : (volume : measure (add_circle T)) = ennreal.of_real T • haar_add_circle := rfl end add_circle open add_circle section monomials /-- The family of exponential monomials `λ x, exp (2 π i n x / T)`, parametrized by `n : ℤ` and considered as bundled continuous maps from `ℝ / ℤ • T` to `ℂ`. -/ def fourier (n : ℤ) : C(add_circle T, ℂ) := { to_fun := λ x, to_circle (n • x), continuous_to_fun := continuous_induced_dom.comp $ continuous_to_circle.comp $ continuous_zsmul _} @[simp] lemma fourier_apply {n : ℤ} {x : add_circle T} : fourier n x = to_circle (n • x) := rfl @[simp] lemma fourier_coe_apply {n : ℤ} {x : ℝ} : fourier n (x : add_circle T) = complex.exp (2 * π * complex.I * n * x / T) := begin rw [fourier_apply, ←quotient_add_group.coe_zsmul, to_circle, function.periodic.lift_coe, exp_map_circle_apply, complex.of_real_mul, complex.of_real_div, complex.of_real_mul, zsmul_eq_mul, complex.of_real_mul, complex.of_real_int_cast, complex.of_real_bit0, complex.of_real_one], congr' 1, ring, end @[simp] lemma fourier_zero {x : add_circle T} : fourier 0 x = 1 := begin induction x using quotient_add_group.induction_on', simp only [fourier_coe_apply, algebra_map.coe_zero, mul_zero, zero_mul, zero_div, complex.exp_zero], end @[simp] lemma fourier_eval_zero (n : ℤ) : fourier n (0 : add_circle T) = 1 := by rw [←quotient_add_group.coe_zero, fourier_coe_apply, complex.of_real_zero, mul_zero, zero_div, complex.exp_zero] @[simp] lemma fourier_one {x : add_circle T} : fourier 1 x = to_circle x := by rw [fourier_apply, one_zsmul] @[simp] lemma fourier_neg {n : ℤ} {x : add_circle T} : fourier (-n) x = conj (fourier n x) := begin induction x using quotient_add_group.induction_on', simp_rw [fourier_apply, to_circle, ←quotient_add_group.coe_zsmul, function.periodic.lift_coe, ←coe_inv_circle_eq_conj, ←exp_map_circle_neg, neg_smul, mul_neg], end @[simp] lemma fourier_add {m n : ℤ} {x : add_circle T} : fourier (m + n) x = fourier m x * fourier n x := by simp_rw [fourier_apply, add_zsmul, to_circle_add, coe_mul_unit_sphere] lemma fourier_norm [fact (0 < T)] (n : ℤ) : ‖@fourier T n‖ = 1 := begin rw continuous_map.norm_eq_supr_norm, have : ∀ (x : add_circle T), ‖fourier n x‖ = 1 := λ x, abs_coe_circle _, simp_rw this, exact @csupr_const _ _ _ has_zero.nonempty _, end /-- For `n ≠ 0`, a translation by `T / 2 / n` negates the function `fourier n`. -/ lemma fourier_add_half_inv_index {n : ℤ} (hn : n ≠ 0) (hT : 0 < T) (x : add_circle T) : fourier n (x + ((T / 2 / n) : ℝ)) = - fourier n x := begin rw [fourier_apply, zsmul_add, ←quotient_add_group.coe_zsmul, to_circle_add, coe_mul_unit_sphere], have : (n : ℂ) ≠ 0 := by simpa using hn, have : ((@to_circle T ((n • (T / 2 / n)) : ℝ)) : ℂ) = -1, { rw [zsmul_eq_mul, to_circle, function.periodic.lift_coe, exp_map_circle_apply], replace hT := complex.of_real_ne_zero.mpr hT.ne', convert complex.exp_pi_mul_I using 3, field_simp, ring, }, rw this, simp, end /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` . -/ def fourier_subalgebra : subalgebra ℂ C(add_circle T, ℂ) := algebra.adjoin ℂ (range fourier) /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` is in fact the linear span of these functions. -/ lemma fourier_subalgebra_coe : (@fourier_subalgebra T).to_submodule = span ℂ (range fourier) := begin apply adjoin_eq_span_of_subset, refine subset.trans _ submodule.subset_span, intros x hx, apply submonoid.closure_induction hx (λ _, id) ⟨0, _⟩, { rintros _ _ ⟨m, rfl⟩ ⟨n, rfl⟩, refine ⟨m + n, _⟩, ext1 z, exact fourier_add }, { ext1 z, exact fourier_zero } end /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` is invariant under complex conjugation. -/ lemma fourier_subalgebra_conj_invariant : conj_invariant_subalgebra ((@fourier_subalgebra T).restrict_scalars ℝ) := begin apply subalgebra_conj_invariant, rintros _ ⟨n, rfl⟩, exact ⟨-n, ext (λ _, fourier_neg)⟩ end variables [hT : fact (0 < T)] include hT /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` separates points. -/ lemma fourier_subalgebra_separates_points : (@fourier_subalgebra T).separates_points := begin intros x y hxy, refine ⟨_, ⟨fourier 1, subset_adjoin ⟨1, rfl⟩, rfl⟩, _⟩, dsimp only, rw [fourier_one, fourier_one], contrapose! hxy, rw subtype.coe_inj at hxy, exact injective_to_circle hT.elim.ne' hxy, end /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` is dense. -/ lemma fourier_subalgebra_closure_eq_top : (@fourier_subalgebra T).topological_closure = ⊤ := continuous_map.subalgebra_is_R_or_C_topological_closure_eq_top_of_separates_points fourier_subalgebra fourier_subalgebra_separates_points fourier_subalgebra_conj_invariant /-- The linear span of the monomials `fourier n` is dense in `C(add_circle T, ℂ)`. -/ lemma span_fourier_closure_eq_top : (span ℂ (range $ @fourier T)).topological_closure = ⊤ := begin rw ← fourier_subalgebra_coe, exact congr_arg subalgebra.to_submodule fourier_subalgebra_closure_eq_top, end /-- The family of monomials `fourier n`, parametrized by `n : ℤ` and considered as elements of the `Lp` space of functions `add_circle T → ℂ`. -/ abbreviation fourier_Lp (p : ℝ≥0∞) [fact (1 ≤ p)] (n : ℤ) : Lp ℂ p (@haar_add_circle T hT) := to_Lp p haar_add_circle ℂ (fourier n) lemma coe_fn_fourier_Lp (p : ℝ≥0∞) [fact (1 ≤ p)] (n : ℤ) : (@fourier_Lp T hT p _ n) =ᵐ[haar_add_circle] fourier n := coe_fn_to_Lp haar_add_circle (fourier n) /-- For each `1 ≤ p < ∞`, the linear span of the monomials `fourier n` is dense in `Lp ℂ p haar_circle`. -/ lemma span_fourier_Lp_closure_eq_top {p : ℝ≥0∞} [fact (1 ≤ p)] (hp : p ≠ ∞) : (span ℂ (range (@fourier_Lp T _ p _))).topological_closure = ⊤ := begin convert (continuous_map.to_Lp_dense_range ℂ hp (@haar_add_circle T hT) ℂ ).topological_closure_map_submodule (span_fourier_closure_eq_top), rw [map_span, range_comp], simp only [continuous_linear_map.coe_coe], end /-- The monomials `fourier n` are an orthonormal set with respect to normalised Haar measure. -/ lemma orthonormal_fourier : orthonormal ℂ (@fourier_Lp T _ 2 _) := begin rw orthonormal_iff_ite, intros i j, rw continuous_map.inner_to_Lp (@haar_add_circle T hT) (fourier i) (fourier j), simp_rw [←fourier_neg, ←fourier_add], split_ifs, { simp_rw [h, neg_add_self], have : ⇑(@fourier T 0) = (λ x, 1 : (add_circle T) → ℂ), { ext1, exact fourier_zero }, rw [this, integral_const, measure_univ, ennreal.one_to_real, complex.real_smul, complex.of_real_one, mul_one] }, have hij : -i + j ≠ 0, { rw add_comm, exact sub_ne_zero.mpr (ne.symm h) }, convert integral_eq_zero_of_add_right_eq_neg (fourier_add_half_inv_index hij hT.elim), exact is_add_left_invariant.is_add_right_invariant end end monomials section scope_hT -- everything from here on needs `0 < T` variables [hT : fact (0 < T)] include hT section fourier_coeff variables {E : Type} [normed_add_comm_group E] [normed_space ℂ E] [complete_space E] /-- The `n`-th Fourier coefficient of a function `add_circle T → E`, for `E` a complete normed `ℂ`-vector space, defined as the integral over `add_circle T` of `fourier (-n) t • f t`. -/ def fourier_coeff (f : add_circle T → E) (n : ℤ) : E := ∫ (t : add_circle T), fourier (-n) t • f t ∂ haar_add_circle /-- The Fourier coefficients of a function on `add_circle T` can be computed as an integral over `[a, a + T]`, for any real `a`. -/ lemma fourier_coeff_eq_interval_integral (f : add_circle T → E) (n : ℤ) (a : ℝ) : fourier_coeff f n = (1 / T) • ∫ x in a .. a + T, @fourier T (-n) x • f x := begin have : ∀ (x : ℝ), @fourier T (-n) x • f x = (λ (z : add_circle T), @fourier T (-n) z • f z) x, { intro x, refl, }, simp_rw this, rw [fourier_coeff, add_circle.interval_integral_preimage T a, volume_eq_smul_haar_add_circle, integral_smul_measure, ennreal.to_real_of_real hT.out.le, ←smul_assoc, smul_eq_mul, one_div_mul_cancel hT.out.ne', one_smul], end lemma fourier_coeff.const_smul (f : add_circle T → E) (c : ℂ) (n : ℤ) : fourier_coeff (c • f) n = c • fourier_coeff f n := by simp_rw [fourier_coeff, pi.smul_apply, ←smul_assoc, smul_eq_mul, mul_comm, ←smul_eq_mul, smul_assoc, integral_smul] lemma fourier_coeff.const_mul (f : add_circle T → ℂ) (c : ℂ) (n : ℤ) : fourier_coeff (λ x, c * f x) n = c * fourier_coeff f n := fourier_coeff.const_smul f c n omit hT /-- For a function on `ℝ`, the Fourier coefficients of `f` on `[a, b]` are defined as the Fourier coefficients of the unique periodic function agreeing with `f` on `Ioc a b`. -/ def fourier_coeff_on {a b : ℝ} (hab : a < b) (f : ℝ → E) (n : ℤ) : E := begin haveI := fact.mk (by linarith : 0 < b - a), exact fourier_coeff (add_circle.lift_Ioc (b - a) a f) n end lemma fourier_coeff_on_eq_integral {a b : ℝ} (f : ℝ → E) (n : ℤ) (hab : a < b) : fourier_coeff_on hab f n = (1 / (b - a)) • ∫ x in a ..b, fourier (-n) (x : add_circle (b - a)) • f x := begin rw [fourier_coeff_on, fourier_coeff_eq_interval_integral _ _ a], congr' 1, rw [add_sub, add_sub_cancel'], simp_rw interval_integral.integral_of_le hab.le, refine set_integral_congr measurable_set_Ioc (λ x hx, _), dsimp only, rwa [lift_Ioc_coe_apply], rwa [add_sub, add_sub_cancel'], end lemma fourier_coeff_on.const_smul {a b : ℝ} (f : ℝ → E) (c : ℂ) (n : ℤ) (hab : a < b) : fourier_coeff_on hab (c • f) n = c • fourier_coeff_on hab f n := by apply fourier_coeff.const_smul lemma fourier_coeff_on.const_mul {a b : ℝ} (f : ℝ → ℂ) (c : ℂ) (n : ℤ) (hab : a < b) : fourier_coeff_on hab (λ x, c * f x) n = c * fourier_coeff_on hab f n := fourier_coeff_on.const_smul _ _ _ _ include hT lemma fourier_coeff_lift_Ioc_eq {a : ℝ} (f : ℝ → ℂ) (n : ℤ) : fourier_coeff (add_circle.lift_Ioc T a f) n = fourier_coeff_on (lt_add_of_pos_right a hT.out) f n := begin rw [fourier_coeff_on_eq_integral, fourier_coeff_eq_interval_integral, add_sub_cancel' a T], congr' 1, refine interval_integral.integral_congr_ae (ae_of_all _ (λ x hx, _)), rw lift_Ioc_coe_apply, rwa uIoc_of_le (lt_add_of_pos_right a hT.out).le at hx, end lemma fourier_coeff_lift_Ico_eq {a : ℝ} (f : ℝ → ℂ) (n : ℤ) : fourier_coeff (add_circle.lift_Ico T a f) n = fourier_coeff_on (lt_add_of_pos_right a hT.out) f n := begin rw [fourier_coeff_on_eq_integral, fourier_coeff_eq_interval_integral _ _ a, add_sub_cancel' a T], congr' 1, simp_rw [interval_integral.integral_of_le (lt_add_of_pos_right a hT.out).le, integral_Ioc_eq_integral_Ioo], refine set_integral_congr measurable_set_Ioo (λ x hx, _), dsimp only, rw lift_Ico_coe_apply (Ioo_subset_Ico_self hx), end end fourier_coeff section fourier_L2 /-- We define `fourier_basis` to be a `ℤ`-indexed Hilbert basis for `Lp ℂ 2 haar_add_circle`, which by definition is an isometric isomorphism from `Lp ℂ 2 haar_add_circle` to `ℓ²(ℤ, ℂ)`. -/ def fourier_basis : hilbert_basis ℤ ℂ (Lp ℂ 2 $ @haar_add_circle T hT) := hilbert_basis.mk orthonormal_fourier (span_fourier_Lp_closure_eq_top (by norm_num)).ge /-- The elements of the Hilbert basis `fourier_basis` are the functions `fourier_Lp 2`, i.e. the monomials `fourier n` on the circle considered as elements of `L²`. -/ @[simp] lemma coe_fourier_basis : ⇑(@fourier_basis _ hT) = fourier_Lp 2 := hilbert_basis.coe_mk _ _ /-- Under the isometric isomorphism `fourier_basis` from `Lp ℂ 2 haar_circle` to `ℓ²(ℤ, ℂ)`, the `i`-th coefficient is `fourier_coeff f i`, i.e., the integral over `add_circle T` of `λ t, fourier (-i) t * f t` with respect to the Haar measure of total mass 1. -/ lemma fourier_basis_repr (f : Lp ℂ 2 $ @haar_add_circle T hT) (i : ℤ) : fourier_basis.repr f i = fourier_coeff f i := begin transitivity ∫ (t : add_circle T), conj (((@fourier_Lp T hT 2 _ i) : add_circle T → ℂ) t) * f t ∂ haar_add_circle, { simp [fourier_basis.repr_apply_apply f i, measure_theory.L2.inner_def] }, { apply integral_congr_ae, filter_upwards [coe_fn_fourier_Lp 2 i] with _ ht, rw [ht, ←fourier_neg, smul_eq_mul], } end /-- The Fourier series of an `L2` function `f` sums to `f`, in the `L²` space of `add_circle T`. -/ lemma has_sum_fourier_series_L2 (f : Lp ℂ 2 $ @haar_add_circle T hT) : has_sum (λ i, fourier_coeff f i • fourier_Lp 2 i) f := by { simp_rw ←fourier_basis_repr, simpa using hilbert_basis.has_sum_repr fourier_basis f } /-- **Parseval's identity**: for an `L²` function `f` on `add_circle T`, the sum of the squared norms of the Fourier coefficients equals the `L²` norm of `f`. -/ lemma tsum_sq_fourier_coeff (f : Lp ℂ 2 $ @haar_add_circle T hT) : ∑' i : ℤ, ‖fourier_coeff f i‖ ^ 2 = ∫ (t : add_circle T), ‖f t‖ ^ 2 ∂ haar_add_circle := begin simp_rw ←fourier_basis_repr, have H₁ : ‖fourier_basis.repr f‖ ^ 2 = ∑' i, ‖fourier_basis.repr f i‖ ^ 2, { exact_mod_cast lp.norm_rpow_eq_tsum _ (fourier_basis.repr f), norm_num }, have H₂ : ‖fourier_basis.repr f‖ ^ 2 = ‖f‖ ^ 2 := by simp, have H₃ := congr_arg is_R_or_C.re (@L2.inner_def (add_circle T) ℂ ℂ _ _ _ _ f f), rw ← integral_re at H₃, { simp only [← norm_sq_eq_inner] at H₃, rw [← H₁, H₂, H₃], }, { exact L2.integrable_inner f f }, end end fourier_L2 section convergence variables (f : C(add_circle T, ℂ)) lemma fourier_coeff_to_Lp (n : ℤ) : fourier_coeff (to_Lp 2 haar_add_circle ℂ f) n = fourier_coeff f n := integral_congr_ae (filter.eventually_eq.mul (filter.eventually_of_forall (by tauto)) (continuous_map.coe_fn_to_ae_eq_fun haar_add_circle f)) variables {f} /-- If the sequence of Fourier coefficients of `f` is summable, then the Fourier series converges uniformly to `f`. -/ lemma has_sum_fourier_series_of_summable (h : summable (fourier_coeff f)) : has_sum (λ i, fourier_coeff f i • fourier i) f := begin have sum_L2 := has_sum_fourier_series_L2 (to_Lp 2 haar_add_circle ℂ f), simp_rw fourier_coeff_to_Lp at sum_L2, refine continuous_map.has_sum_of_has_sum_Lp (summable_of_summable_norm _) sum_L2, simp_rw [norm_smul, fourier_norm, mul_one, summable_norm_iff], exact h, end /-- If the sequence of Fourier coefficients of `f` is summable, then the Fourier series of `f` converges everywhere pointwise to `f`. -/ lemma has_pointwise_sum_fourier_series_of_summable (h : summable (fourier_coeff f)) (x : add_circle T) : has_sum (λ i, fourier_coeff f i • fourier i x) (f x) := (continuous_map.eval_clm ℂ x).has_sum (has_sum_fourier_series_of_summable h) end convergence end scope_hT section deriv open complex interval_integral open_locale interval variables (T) lemma has_deriv_at_fourier (n : ℤ) (x : ℝ) : has_deriv_at (λ y:ℝ, fourier n (y : add_circle T)) (2 * π * I * n / T * fourier n (x : add_circle T)) x := begin simp_rw [fourier_coe_apply], refine (_ : has_deriv_at (λ y, exp (2 * π * I * n * y / T)) _ _).comp_of_real, rw (λ α β, by ring : ∀ (α β : ℂ), α * exp β = exp β * α), refine (has_deriv_at_exp _).comp x _, convert has_deriv_at_mul_const (2 * ↑π * I * ↑n / T), ext1 y, ring, end lemma has_deriv_at_fourier_neg (n : ℤ) (x : ℝ) : has_deriv_at (λ y:ℝ, fourier (-n) (y : add_circle T)) (-2 * π * I * n / T * fourier (-n) (x : add_circle T)) x := by simpa using has_deriv_at_fourier T (-n) x variables {T} lemma has_antideriv_at_fourier_neg (hT : fact (0 < T)) {n : ℤ} (hn : n ≠ 0) (x : ℝ) : has_deriv_at (λ (y : ℝ), (T : ℂ) / (-2 * π * I * n) * fourier (-n) (y : add_circle T)) (fourier (-n) (x : add_circle T)) x := begin convert (has_deriv_at_fourier_neg T n x).div_const (-2 * π * I * n / T) using 1, { ext1 y, rw div_div_eq_mul_div, ring, }, { rw mul_div_cancel_left, simp only [ne.def, div_eq_zero_iff, neg_eq_zero, mul_eq_zero, bit0_eq_zero, one_ne_zero, of_real_eq_zero, false_or, int.cast_eq_zero, not_or_distrib], exact ⟨⟨⟨real.pi_ne_zero, I_ne_zero⟩, hn⟩, hT.out.ne'⟩ }, end /-- Express Fourier coefficients of `f` on an interval in terms of those of its derivative. -/ lemma fourier_coeff_on_of_has_deriv_at {a b : ℝ} (hab : a < b) {f f' : ℝ → ℂ} {n : ℤ} (hn : n ≠ 0) (hf : ∀ x, x ∈ [a, b] → has_deriv_at f (f' x) x) (hf' : interval_integrable f' volume a b) : fourier_coeff_on hab f n = 1 / (-2 * π * I * n) * (fourier (-n) (a : add_circle (b - a)) * (f b - f a) - (b - a) * fourier_coeff_on hab f' n) := begin rw ←of_real_sub, have hT : fact (0 < b - a) := ⟨by linarith⟩, simp_rw [fourier_coeff_on_eq_integral, smul_eq_mul, real_smul, of_real_div, of_real_one], conv { for (fourier _ _ * _) [1, 2, 3] { rw mul_comm } }, rw integral_mul_deriv_eq_deriv_mul hf (λ x hx, has_antideriv_at_fourier_neg hT hn x) hf' (((map_continuous (fourier (-n))).comp (add_circle.continuous_mk' _)).interval_integrable _ _), dsimp only, have : ∀ (u v w : ℂ), u * ( (b - a : ℝ) / v * w) = (b - a : ℝ) / v * (u * w) := by {intros, ring}, conv in (interval_integral _ _ _ _) { congr, funext, rw this, }, rw (by ring : ((b - a : ℝ) : ℂ) / ((-2) * π * I * n) = ((b - a : ℝ) : ℂ) * (1 / ((-2) * π * I * n))), have s2 : (b : add_circle (b - a)) = (a : add_circle (b - a)), { simpa using coe_add_period (b - a) a, }, rw [s2, integral_const_mul, ←sub_mul, mul_sub, mul_sub], congr' 1, { conv_lhs {rw [mul_comm, mul_div, mul_one]}, rw [div_eq_iff (of_real_ne_zero.mpr hT.out.ne')], ring, }, { ring, }, end end deriv
c4a00d8ad3d085a337bfcdf97c811082911cfbc9
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/kcomp.lean
12767798a868d1debc7f683e4eec7bee1e4a2f9e
[ "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
907
lean
import logic set_option pp.notation false constant A : Type constants a b : A constant P : A → Type constant H₁ : a = a constant H₂ : P a constant H₃ : a = b constant f {A : Type} (a : A) : a = a eval eq.rec H₂ (f a) eval eq.rec H₂ H₁ eval eq.rec H₂ H₃ eval eq.rec H₂ (eq.refl a) eval λ (A : Type) (a b : A) (H₁ : a = a) (P : A → Prop) (H₂ : P a) (H₃ : a = a) (c : A), eq.rec (eq.rec H₂ H₁) H₃ check @eq.rec A a P H₂ a check λ H : a = a, H₂ inductive to_type {B : Type} : B → Type := mk : Π (b : B), to_type b definition tst1 : to_type (λ H : a = a, H₂) := to_type.mk (@eq.rec A a P H₂ a) check to_type.mk(λ H : a = a, H₂) check to_type.mk(@eq.rec A a P H₂ a) check to_type.mk(λ H : a = a, H₂) = to_type.mk(@eq.rec A a P H₂ a) check to_type.mk(eq.rec H₂ H₁) = to_type.mk(H₂) check to_type.mk(eq.rec H₂ (f a)) = to_type.mk(H₂)
539f5d1d1b1a9091ecd811f12ca8485d1a9281c0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/bad_quoted_symbol.lean
258fc62ccf4f2bac2f64235063848f8db5ffb944
[ "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
166
lean
notation (name := or2) a ` \/ ` b := a ∨ b notation a `1\/` b := a ∨ b notation a ` 1\/` b := a ∨ b notation a ` \ / ` b := a ∨ b notation a ` ` b := a ∨ b
2615aebbb394f02ae324c81434f3864527f94adf
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/number_theory/number_field.lean
0f9694873406009b5ea72e35898f279337b3597a
[ "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
3,687
lean
/- Copyright (c) 2021 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ashvni Narayanan, Anne Baanen -/ import algebra.field import data.rat.basic import ring_theory.algebraic import ring_theory.dedekind_domain import ring_theory.integral_closure import ring_theory.polynomial.rational_root /-! # Number fields This file defines a number field and the ring of integers corresponding to it. ## Main definitions - `number_field` defines a number field as a field which has characteristic zero and is finite dimensional over ℚ. - `ring_of_integers` defines the ring of integers (or number ring) corresponding to a number field as the integral closure of ℤ in the number field. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [P. Samuel, *Algebraic Theory of Numbers*][samuel1970algebraic] ## Tags number field, ring of integers -/ /-- A number field is a field which has characteristic zero and is finite dimensional over ℚ. -/ class number_field (K : Type*) [field K] : Prop := [to_char_zero : char_zero K] [to_finite_dimensional : finite_dimensional ℚ K] open function open_locale classical big_operators namespace number_field variables (K : Type*) [field K] [nf : number_field K] include nf -- See note [lower instance priority] attribute [priority 100, instance] number_field.to_char_zero number_field.to_finite_dimensional protected lemma is_algebraic : algebra.is_algebraic ℚ K := algebra.is_algebraic_of_finite omit nf /-- The ring of integers (or number ring) corresponding to a number field is the integral closure of ℤ in the number field. -/ def ring_of_integers := integral_closure ℤ K namespace ring_of_integers variables {K} instance [number_field K] : is_fraction_ring (ring_of_integers K) K := integral_closure.is_fraction_ring_of_finite_extension ℚ _ instance : is_integral_closure (ring_of_integers K) ℤ K := integral_closure.is_integral_closure _ _ instance [number_field K] : is_integrally_closed (ring_of_integers K) := integral_closure.is_integrally_closed_of_finite_extension ℚ lemma is_integral_coe (x : ring_of_integers K) : is_integral ℤ (x : K) := x.2 /-- The ring of integers of `K` are equivalent to any integral closure of `ℤ` in `K` -/ protected noncomputable def equiv (R : Type*) [comm_ring R] [algebra R K] [is_integral_closure R ℤ K] : ring_of_integers K ≃+* R := (is_integral_closure.equiv ℤ R K _).symm.to_ring_equiv variables (K) instance [number_field K] : char_zero (ring_of_integers K) := char_zero.of_algebra K -- TODO: show `ring_of_integers K` is a Dedekind domain end ring_of_integers end number_field namespace rat open number_field instance rat.number_field : number_field ℚ := { to_char_zero := infer_instance, to_finite_dimensional := by { convert (infer_instance : finite_dimensional ℚ ℚ), -- The vector space structure of `ℚ` over itself can arise in multiple ways: -- all fields are vector spaces over themselves (used in `rat.finite_dimensional`) -- all char 0 fields have a canonical embedding of `ℚ` (used in `number_field`). -- Show that these coincide: ext, simp [algebra.smul_def] } } /-- The ring of integers of `ℚ` as a number field is just `ℤ`. -/ noncomputable def ring_of_integers_equiv : ring_of_integers ℚ ≃+* ℤ := ring_of_integers.equiv ℤ end rat
8c2b9a4d14af71697f9b7bd7e4e644afb648966d
b392eb79fb36952401156496daa60628ccb07438
/MathPort/PrintSource.lean
3ade9faf29f3ff589f271027e24e818daf51a323
[ "Apache-2.0" ]
permissive
AurelienSaue/mathportsource
d9eabe74e3ab7774baa6a10a6dc8d4855ff92266
1a164e4fff7204c522c1f4ecc5024fd909be3b0b
refs/heads/master
1,685,214,377,305
1,623,621,223,000
1,623,621,223,000
364,191,042
0
0
null
null
null
null
UTF-8
Lean
false
false
29,718
lean
import Lean import MathPort.Basic open Lean open MathPort -- Options def useSorry := false def doFilter := true def declareUniverses := true def importPostport := false def printIgnored := true -- Utils def MathlibPrefix : Name := `Mathlib def removeMathlibPrefix : Name → Name | n@(Name.str p s _) => if (n == MathlibPrefix) then Name.anonymous else Name.mkStr (removeMathlibPrefix p) s | Name.num p n _ => Name.mkNum (removeMathlibPrefix p) n | Name.anonymous => Name.anonymous def startsWithAux : (s : List Char) → (subStr : List Char) → Bool | _, [] => true | [], _ => false | c₁::t₁, c₂::t₂ => c₁ = c₂ && startsWithAux t₁ t₂ def String.startsWith (s : String) (start : String) : Bool := startsWithAux s.data start.data def removeStartAux : (s : List Char) → (subStr : List Char) → List Char | l, [] => l | [], l => [] | c₁::t₁, c₂::t₂ => removeStartAux t₁ t₂ def String.removeStart (s : String) (start : String) : String := ⟨removeStartAux s.data start.data⟩ def String.endsWith (s : String) (ending : String) : Bool := startsWithAux s.data.reverse ending.data.reverse def containsStrAux : (s : List Char) → (subStr : List Char) → Bool | [], [] => true | [], _ => false | _, [] => true | c₁::t₁, c₂::t₂ => if c₁ = c₂ then (startsWithAux t₁ t₂) || (containsStrAux t₁ (c₂::t₂)) else (containsStrAux t₁ (c₂::t₂)) def String.containsStr (s : String) (subStr : String) : Bool := containsStrAux s.data subStr.data def replaceAux (c : Char) (toInsert : String) (prev : List Char): List Char → List Char | c₁::t => if c₁ = c then (replaceAux c toInsert (prev ++ toInsert.data) t) else (replaceAux c toInsert (prev ++ [c₁]) t) | [] => prev def String.replace (s : String) (c : Char) (toInsert : String) : String := ⟨replaceAux c toInsert [] s.data⟩ def countAux (c : Char) : List Char → Nat | c₁::t => if c₁ = c then Nat.succ (countAux c t) else countAux c t | [] => 0 def String.count (s : String) (c : Char) : Nat:= (countAux c s.data) def Lean.Name.last : Name → String | Name.str _ s _ => s | Name.num _ n _ => toString n | Name.anonymous => "[anonymous]" def Lean.Name.removeSuffix : Name → Name → Name | n, Name.anonymous => n | Name.str p₁ s₁ _, Name.str p₂ s₂ _ => removeSuffix p₁ p₂ | Name.num p₁ n₁ _, Name.num p₂ n₂ _ => removeSuffix p₁ p₂ | _, _ => arbitrary def Lean.Name.removePrefix (n : Name) (pfx : Name) : IO Name := if n.beq pfx then Name.anonymous else match n with | Name.anonymous => do println! "Invalid prefix {pfx} for {n}" Name.anonymous | Name.str p s _ => do Name.mkStr (← removePrefix p pfx) s | Name.num p n _ => do Name.mkNum (← removePrefix p pfx) n def rip : (Std.Format) → String | Std.Format.nil => "nil" | Std.Format.line => "line" | Std.Format.text s => s!"text \"{s}\"" | Std.Format.append f₁ f₂ => s!"{(rip f₁)}\n{(rip f₂)}" | Std.Format.nest x f => s!"nest {x}\n| {(rip f).replace '\n' "\n| "}" | Std.Format.group f Std.Format.FlattenBehavior.allOrNone => s!"group aon\n| {(rip f).replace '\n' "\n| "}" | Std.Format.group f Std.Format.FlattenBehavior.fill => s!"fill\n| {(rip f).replace '\n' "\n| "}" def listMetaM {α : Type _} (l : List (MetaM α)) : MetaM (List α) := match l with | [] => [] | x::t => do (← x)::(← listMetaM t) def arrayMetaM {α : Type _} (array : Array (MetaM α)) : MetaM (Array α) := do return ⟨← listMetaM array.data⟩ def Lean.Expr.forallDepth (prevnames : List Name) : (type : Expr) → Nat | Expr.forallE n _ e _ => do if n.beq `ᾰ || prevnames.contains n then 0 else forallDepth (n :: prevnames) e + 1 | _ => 0 def Lean.Expr.forallRoot : (type : Expr) → Expr | Expr.forallE _ _ e _ => forallRoot e | e => e -- Copy of private definitions from Lean/Meta/Basic.lean private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do match (← Lean.Meta.getTransparency) with | Lean.Meta.TransparencyMode.all => return some info | Lean.Meta.TransparencyMode.default => return some info | _ => if (← isReducible info.name) then return some info else return none private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do let env ← getEnv match env.find? constName with | some (info@(ConstantInfo.thmInfo _)) => Lean.Meta.getTheoremInfo info | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info | some info => pure (some info) | none => throwUnknownConstant constName private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do let env ← getEnv if isClass env constName then pure (LOption.some constName) else match (← getConstTemp? constName) with | some _ => pure LOption.undef | none => pure LOption.none private 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 match (← Lean.Meta.getExprMVarAssignment? mvarId) 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 private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `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`. -/ private partial def withNewLocalInstancesImp (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← Lean.Meta.getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | LOption.none => withNewLocalInstancesImp fvars (i+1) k | LOption.undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => Lean.Meta.withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k | LOption.some c => Lean.Meta.withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k else k private partial def lambdaTelescopeReducingAuxAux (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | Expr.lam n d b c => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← Lean.Meta.whnf type if newType.isLambda then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def lambdaTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← Lean.Meta.whnf type if newType.isLambda then lambdaTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? : Expr → MetaM (Option Name) | type => Lean.Meta.withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants. lambdaTelescopeReducingAux type none fun xs type => do let env ← getEnv match type.getAppFn with | Expr.const c _ _ => do if isClass env c then return some c else -- make sure abbreviations are unfolded match (← Lean.Meta.whnf type).getAppFn with | Expr.const c _ _ => return if isClass env c then some c else none | _ => return none | _ => return none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | LOption.none => pure none | LOption.some c => pure (some c) | LOption.undef => isClassExpensive? type end variable [MonadControlT MetaM n] [Monad n] private partial def lambdaBoundedTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) (maxDepth : Nat): MetaM α := do let rec process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) (maxDepth : Nat): MetaM α := do match maxDepth, consumeLet, e with | 0, _, _ => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e | _, _, Expr.lam n d b c => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b (maxDepth - 1) | _, true, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b (maxDepth - 1) | _, _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e process consumeLet (← getLCtx) #[] 0 e maxDepth /-- Similar to `forallTelescope` but for lambda expressions. -/ def lambdaBoundedTelescope (type : Expr) (k : Array Expr → Expr → n α) (maxDepth : Nat): n α := Lean.Meta.map2MetaM (fun k => lambdaBoundedTelescopeImp type false k maxDepth) k -- Printing def printExpr (e : Expr) (currNamespace : Name) : MetaM Format := do PrettyPrinter.ppExpr currNamespace [] e def levelParamsToMessageData (levelParams : List Name) : MessageData := match levelParams with | [] => "" | u::us => do let mut m := m!".\{{u}" for u in us do m := m ++ ", " ++ u return m ++ "}" def mkHeader (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (currNamespace : Name) (safety : DefinitionSafety) (numParams : Option Nat := none): PortM Format := do let info ← (← get).name2info.find! id let m : MessageData := if info.simp then "@[simp] " else "" let m := m ++ match safety with | DefinitionSafety.unsafe => "unsafe " | DefinitionSafety.partial => "partial " | DefinitionSafety.safe => "" let m := if info.protected then m ++ "protected " else m let (m, shortid) : MessageData × IO Name := do match privateToUserName? (removeMathlibPrefix id) with | some shid => (m ++ "private ", shid) | none => do return (m, id.removePrefix currNamespace) let kind := if info.instance then "instance" else kind let m := m ++ kind ++ " " ++ (← shortid) if declareUniverses then let m := m ++ levelParamsToMessageData levelParams let numParams ← if numParams.isNone then some $ type.forallDepth [] else numParams let formatType (args : Array Expr) (resType : Expr) : MetaM Format := do let mut s : Format := (← m.toString) for arg in args do let argType ← Meta.inferType arg let localDecl ← Meta.getFVarLocalDecl arg -- println! "RIP arg\n{rip (← printExpr arg currNamespace)}" -- println! "RIP argtype\n{rip (← printExpr argType currNamespace)}" match localDecl.binderInfo with | BinderInfo.default => s := s ++ Format.line ++ Format.fill (Format.nest 2 ("(" ++ (← printExpr arg currNamespace) ++ " :" ++ Format.line ++ (← printExpr argType currNamespace) ++ ")")) | BinderInfo.implicit => s := s ++ Format.line ++ Format.fill (Format.nest 2 ("{" ++ (← printExpr arg currNamespace) ++ " :" ++ Format.line ++ (← printExpr argType currNamespace) ++ "}")) | BinderInfo.strictImplicit => s := s ++ Format.line ++ Format.fill (Format.nest 2 ("⦃" ++ (← printExpr arg currNamespace) ++ " :" ++ Format.line ++ (← printExpr argType currNamespace) ++ "⦄")) | BinderInfo.instImplicit => do let str ← printExpr arg currNamespace if (toString str).startsWith "_" then s := s ++ Format.line ++ Format.fill (Format.nest 2 ("[" ++ (← printExpr argType currNamespace) ++ "]")) else s := s ++ Format.line ++ Format.fill (Format.nest 2 ("[" ++ (← printExpr arg currNamespace) ++ " :" ++ Format.line ++ (← printExpr argType currNamespace) ++ "]")) | BinderInfo.auxDecl => println! "ERROR: argument {arg} is auxDecl" match resType with | Expr.sort _ _ => () | _ => s := s ++ " :" ++ Format.line ++ Format.fill (Format.nest 2 ((← PrettyPrinter.ppExpr currNamespace [] resType))) Format.fill (Format.nest 2 s) let ftype : Format ← liftMetaM (@Meta.forallBoundedTelescope MetaM _ _ _ type numParams formatType) return ftype def sorryTerm := mkApp (mkApp (mkConst `sorryAx []) (mkConst `Nat)) (mkConst `Bool.false) def containsAutoGenerated (value : Expr) : PortM Bool := do match value with | Expr.forallE _ d b _ => (← containsAutoGenerated d) || (← containsAutoGenerated b) | Expr.lam _ d b _ => (← containsAutoGenerated d) || (← containsAutoGenerated b) | Expr.mdata _ e _ => (← containsAutoGenerated e) | Expr.letE _ t v b _ => (← containsAutoGenerated t) || (← containsAutoGenerated v) || (← containsAutoGenerated b) | Expr.app f a _ => (← containsAutoGenerated f) || (← containsAutoGenerated a) | Expr.proj _ _ e _ => (← containsAutoGenerated e) | Expr.const n _ _ => do println! "found constant {n}" let s ← get println! " -> {(s.name2info.findD n {}).autoGenerated} {n.isInternal}" return (s.name2info.findD n {}).autoGenerated || n.isInternal | e => false def replaceAutoGenerated (id : Name) (value : Expr) : PortM Expr := do match value with | Expr.forallE n d b dt => Expr.forallE n (← replaceAutoGenerated id d) (← replaceAutoGenerated id b) dt | Expr.lam n d b dt => Expr.lam n (← replaceAutoGenerated id d) (← replaceAutoGenerated id b) dt | Expr.mdata m e d => Expr.mdata m (← replaceAutoGenerated id e) d | Expr.letE n t v b d => Expr.letE n (← replaceAutoGenerated id t) (← replaceAutoGenerated id v) (← replaceAutoGenerated id b) d | Expr.app f a d => match (← replaceAutoGenerated id f) with | Expr.app (Expr.app (Expr.const `sorryAx _ _) _ _) _ _ => sorryTerm | e => Expr.app e (← replaceAutoGenerated id a) d | Expr.proj n x e d => Expr.proj n x (← replaceAutoGenerated id e) d | e@(Expr.const n _ _) => do let s ← get if id.isPrefixOf n then return sorryTerm else return e | e => e def printDefLike (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (value : Expr) (currNamespace : Name) (safety := DefinitionSafety.safe) : PortM Format := do let mut m : Format := (← mkHeader kind id levelParams type currNamespace safety) if useSorry then m := m ++ " :=" ++ Format.line ++ "sorry" else -- println! "printing value {value}" let numParams ← type.forallDepth [] println! "depth: {numParams}" let value ← replaceAutoGenerated id value let formatValue (args : Array Expr) (resValue : Expr) : MetaM Format := do (← PrettyPrinter.ppExpr currNamespace [] resValue) let fvalue : Format ← liftMetaM (@lambdaBoundedTelescope MetaM _ _ _ value formatValue numParams) let svalue := toString fvalue if svalue.length > 1000 then m := m ++ " :=" ++ Format.line ++ "sorry" else if (kind = "theorem" && svalue.count '\n' > 2) then m := m ++ " :=" ++ Format.line ++ "sorry" else m := m ++ " :=" ++ Format.line ++ fvalue -- println! "RIPdeflike\n{rip (Format.fill m)}" pure $ Format.fill $ Format.nest 2 $ m def mkHeader' (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (isUnsafe : Bool) (currNamespace : Name) (numParams : Option Nat := none): PortM Format := mkHeader kind id levelParams type currNamespace (if isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe) numParams def printAxiomLike (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (currNamespace : Name) (isUnsafe := false) : PortM Format := do mkHeader' kind id levelParams type isUnsafe currNamespace def printQuot (kind : QuotKind) (id : Name) (levelParams : List Name) (type : Expr) (currNamespace : Name) : PortM Format := do printAxiomLike "Quotient primitive" id levelParams type currNamespace def findExtensions (id : Name) : PortM (Array Expr) := do -- TODO : Would be more clever to use the constructor let getResType (fields : Array Expr) (resType : Expr) : MetaM Expr := do println! "rt" println! "resType: {(← printExpr resType Name.anonymous)}" resType println! "looking for extensions" let mut res := #[] let s ← get let extensionsPrefix : String := id.toString ++ ".to_" println! "prefix: {extensionsPrefix}" let pos := (s.name2info.find! id).position for (name, info) in s.name2info.toArray do if name.toString.startsWith extensionsPrefix && not (name.toString = (extensionsPrefix ++ "fun")) && info.position = pos then println! "candidate : {name} of type {info.type}" res := res.push info.type.forallRoot return res def extractStructureName (e : Expr) : Name := do match e with | Expr.app e1 e2 _ => extractStructureName e1 | Expr.const n _ _ => n | _ => panic! s!"WRONG STRUCT FORMAT in {e}" def findFields (id : Name) : MetaM (List Name) := do let findFieldsAux (numParams : Nat) (fields : Array Expr) (resType : Expr) : MetaM (List Name) := do let mut res := [] let mut i := 0 let ctx ← getLCtx for field in fields do if i >= numParams then let fieldName ← (ctx.getFVar! field).userName println! "field {fieldName}" println! "numParams: {numParams}" res := fieldName :: res i := i + 1 return res match (← getEnv).find? (id) with | ConstantInfo.inductInfo { levelParams := us, numParams := np, numIndices := numIndices, type := t, ctors := ctors, isUnsafe := u, .. } => if ctors.length != 1 then panic! s!"{id} is not a struct (too many constructors)" else println! "real num params {np}" let cinfo ← getConstInfo ctors.head! return ← Meta.forallBoundedTelescope cinfo.type none (findFieldsAux np) | _ => panic! s!"{id} is not a struct (not inductive type)" def printInduct (id : Name) (levelParams : List Name) (numParams : Nat) (numIndices : Nat) (type : Expr) (ctors : List Name) (isUnsafe : Bool) (currNamespace : Name) (keyword : String): PortM Format := do let info ← (← get).name2info.find! id let mut struct := false if ctors.length = 1 then let ctor ← ctors.head! let name2info ← (← get).name2info let checkFields (fields : Array Expr) (resType : Expr) : MetaM Bool := do let mut res := true let mut i := 0 let ctx ← getLCtx for field in fields do if i >= numParams then let fieldName ← (ctx.getFVar! field).userName println! "field {field}: {id ++ fieldName}" let isDefined ← name2info.contains $ id ++ fieldName let autoGenerated ← fieldName.toString.startsWith "_" println! "the field is defined:{isDefined} the field is autogen:{autoGenerated}" res := res && (isDefined || autoGenerated) i := i + 1 res let cinfo ← getConstInfo ctor struct := (← liftMetaM $ Meta.forallBoundedTelescope cinfo.type none checkFields) if struct then let kind ← do if info.class then "class" else "structure" println! "STRUCTURE kind: {kind} numParams: {numParams} numIndices: {numIndices}" let header ← mkHeader' kind id levelParams type isUnsafe currNamespace numParams let extensions ← findExtensions id println! "extensions: {extensions}" let ctor ← ctors.head! println! "constructor: {ctor}" let formatFields (fields : Array Expr) (resType : Expr) : MetaM Format := do let mut f : Format := header let mut fields2Ignore := [] -- TODO : This list is useless (the fields of the extended structures are not in the constructor) if extensions != #[] then let mut fextensions : Format := "extends" ++ Format.line println! "fields" for field in fields do println! "{field} aka {(← printExpr field currNamespace)}" let mut i := 0 for extension in extensions do println! "instanciating {extension}" let extension ← extension.liftLooseBVars 0 (fields.size - numParams - 1) println! "instanciating {extension}" let extension ← (extension.instantiateRev fields) println! "=> {(← printExpr extension Name.anonymous)}" if i > 0 then fextensions := fextensions ++ "," ++ Format.line fextensions := fextensions ++ (← printExpr extension currNamespace) i := i + 1 let extensionName ← extractStructureName extension println! "struct name {(extractStructureName extension)}" let extensionFields : List Name ← findFields extensionName fields2Ignore := fields2Ignore.append extensionFields fextensions := Format.fill (Format.nest 2 fextensions) f := Format.fill (Format.nest 2 (f ++ Format.nest 2 (Format.line ++ fextensions ++ Format.line ++ "where"))) else f := Format.fill (Format.nest 2 (f ++ Format.nest 2 (Format.line ++ "where"))) f := Format.fill f let mut i := 0 let ctx ← getLCtx let mut ffields := Format.nil for field in fields do let fieldName ← (ctx.getFVar! field).userName if i >= numParams then if fields2Ignore.contains fieldName|| fieldName.toString.startsWith "_" then println! "ignored field {fieldName}" else let fieldType ← Meta.inferType field ffields := ffields ++ Format.line ++ Format.fill (Format.nest 2 ((← printExpr field currNamespace) ++ " :" ++ Format.line ++ (← printExpr fieldType currNamespace))) i := i + 1 return f ++ (Format.nest 2 ffields) let formatFieldsCustomCtor (ctorname : Name) (fields : Array Expr) (resType : Expr) : MetaM Format := do let mut f : Format := header let mut fields2Ignore := [] if extensions != #[] then let mut fextensions : Format := "extends" ++ Format.line println! "fields" for field in fields do println! "{field} aka {(← printExpr field currNamespace)}" let mut i := 0 for extension in extensions do println! "instanciating {extension}" let extension ← extension.liftLooseBVars 0 (fields.size - numParams - 1) println! "instanciating {extension}" let extension ← (extension.instantiateRev fields) println! "=> {(← printExpr extension Name.anonymous)}" if i > 0 then fextensions := fextensions ++ "," ++ Format.line fextensions := fextensions ++ (← printExpr extension currNamespace) i := i + 1 let extensionName ← extractStructureName extension println! "struct name {(extractStructureName extension)}" let extensionFields : List Name ← findFields extensionName fields2Ignore := fields2Ignore.append extensionFields fextensions := Format.fill (Format.nest 2 fextensions) f := Format.fill (Format.nest 2 (f ++ Format.nest 2 (Format.line ++ fextensions ++ Format.line ++ "where"))) else f := Format.fill (Format.nest 2 (f ++ Format.nest 2 (Format.line ++ "where"))) f := Format.fill f let mut i := 0 let ctx ← getLCtx let mut ffields := Format.nil for field in fields do let fieldName ← (ctx.getFVar! field).userName if i >= numParams then if fields2Ignore.contains fieldName|| fieldName.toString.startsWith "_" then println! "ignored field {fieldName}" else let fieldType ← Meta.inferType field ffields := ffields ++ Format.line ++ Format.fill (Format.nest 2 ("(" ++ (← printExpr field currNamespace) ++ " :" ++ Format.line ++ (← printExpr fieldType currNamespace) ++ ")")) i := i + 1 return f ++ Format.nest 2 (Format.line ++ Format.group (Format.nest 2 (ctorname.toString ++ " ::" ++ ffields))) let cinfo ← getConstInfo ctor if ctor.last = "mk" then return (← liftMetaM $ Meta.forallBoundedTelescope cinfo.type none formatFields) else return (← liftMetaM $ Meta.forallBoundedTelescope cinfo.type none (formatFieldsCustomCtor ctor.last)) else let kind ← do if info.class then "class inductive" else "inductive" println! "INDUCTIVE {id} kind: {kind} numParams: {numParams} numIndices: {numIndices}" let mut m ← mkHeader' kind id levelParams type isUnsafe currNamespace numParams m := Format.fill ( Format.nest 2 (m ++ Format.nest 2 (Format.line ++ "where"))) let formatCtorType (args : Array Expr) (resType : Expr) : MetaM Format := do let mut s : Format := "" let mut explicit := false for arg in args do let localDecl ← Meta.getFVarLocalDecl arg match localDecl.binderInfo with | BinderInfo.default => explicit := true | _ => () if explicit then s := s ++ " {}" s := s ++ " :" ++ Format.line ++ (← printExpr resType currNamespace) return Format.fill (Format.nest 4 s) for ctor in ctors do let cinfo ← getConstInfo ctor m := m ++ Format.line ++ "| " ++ (← ctor.removePrefix id).toString m := m ++ (← liftMetaM $ Meta.forallBoundedTelescope cinfo.type (some numParams) formatCtorType) return m def constantToString (id : Name) (currNamespace : Name) (keyword : String): PortM Format := do match (← getEnv).find? id with | ConstantInfo.defnInfo { levelParams := us, type := t, value := v, safety := s, .. } => printDefLike "def" id us t v currNamespace s | ConstantInfo.thmInfo { levelParams := us, type := t, value := v, .. } => printDefLike "theorem" id us t v currNamespace | ConstantInfo.axiomInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "axiom" id us t currNamespace u | ConstantInfo.opaqueInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constant" id us t currNamespace u | ConstantInfo.quotInfo { kind := kind, levelParams := us, type := t, .. } => printQuot kind id us t currNamespace | ConstantInfo.ctorInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constructor" id us t currNamespace u | ConstantInfo.recInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "recursor" id us t currNamespace u | ConstantInfo.inductInfo { levelParams := us, numParams := numParams, numIndices := numIndices, type := t, ctors := ctors, isUnsafe := u, .. } => printInduct id us numParams numIndices t ctors u currNamespace keyword | _ => "not found"
ce49e8fdab0b8973c7b03cf60a76e09d09ebd61d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/uniform_space/completion.lean
8a7ff764c8ea50db6fef28ef2193b51ae21a4f75
[ "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
23,507
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import topology.uniform_space.abstract_completion /-! # Hausdorff completions of uniform spaces The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces into all uniform spaces. Any uniform space `α` gets a completion `completion α` and a morphism (ie. uniformly continuous map) `coe : α → completion α` which solves the universal mapping problem of factorizing morphisms from `α` to any complete Hausdorff uniform space `β`. It means any uniformly continuous `f : α → β` gives rise to a unique morphism `completion.extension f : completion α → β` such that `f = completion.extension f ∘ coe`. Actually `completion.extension f` is defined for all maps from `α` to `β` but it has the desired properties only if `f` is uniformly continuous. Beware that `coe` is not injective if `α` is not Hausdorff. But its image is always dense. The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense. For every uniform spaces `α` and `β`, it turns `f : α → β` into a morphism `completion.map f : completion α → completion β` such that `coe ∘ f = (completion.map f) ∘ coe` provided `f` is uniformly continuous. This construction is compatible with composition. In this file we introduce the following concepts: * `Cauchy α` the uniform completion of the uniform space `α` (using Cauchy filters). These are not minimal filters. * `completion α := quotient (separation_setoid (Cauchy α))` the Hausdorff completion. ## References This formalization is mostly based on N. Bourbaki: General Topology I. M. James: Topologies and Uniformities From a slightly different perspective in order to reuse material in topology.uniform_space.basic. -/ noncomputable theory open filter set universes u v w x open_locale uniformity classical topological_space filter /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] variables {β : Type v} {γ : Type w} variables [uniform_space β] [uniform_space γ] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ p.1.val ×ᶠ p.2.val } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem (α×α) (p.1.val ×ᶠ p.2.val) private lemma symm_gen : map prod.swap ((𝓤 α).lift' gen) ≤ (𝓤 α).lift' gen := calc map prod.swap ((𝓤 α).lift' gen) = (𝓤 α).lift' (λs:set (α×α), {p | s ∈ p.2.val ×ᶠ p.1.val }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem, function.comp, image_swap_eq_preimage_swap, -subtype.val_eq_coe] end ... ≤ (𝓤 α).lift' gen : uniformity_lift_le_swap (monotone_principal.comp (monotone_set_of $ assume p, @monotone_mem (α×α) (p.2.val ×ᶠ p.1.val))) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h, -subtype.val_eq_coe, mem_map'], exact le_rfl, end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val), t₂, (ht₂ : t₂ ∈ h.val), (h₁ : t₁ ×ˢ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val), t₄, (ht₄ : t₄ ∈ g.val), (h₂ : t₃ ×ˢ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val, from inter_mem ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := h.property.left.nonempty_of_mem this in (f.val ×ᶠ g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ t₁ ×ˢ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ t₃ ×ˢ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) ≤ (𝓤 α).lift' gen := calc ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) = (𝓤 α).lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ (𝓤 α).lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = ((𝓤 α).lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ (𝓤 α).lift' gen : lift'_mono comp_le_uniformity le_rfl instance : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := (𝓤 α).lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, ∀ f g : Cauchy α, t ∈ f.1 ×ᶠ g.1 → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion `Cauchy α` -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_inducing_pure_cauchy : uniform_inducing (pure_cauchy : α → Cauchy α) := ⟨have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ((𝓤 α).lift' gen) = (𝓤 α).lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq monotone_gen ... = 𝓤 α : by simp [this]⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := { inj := assume a₁ a₂ h, pure_injective $ subtype.ext_iff_val.1 h, ..uniform_inducing_pure_cauchy } lemma dense_range_pure_cauchy : dense_range pure_cauchy := assume f, have h_ex : ∀ s ∈ 𝓤 (Cauchy α), ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ f.val ×ᶠ f.val, from f.property.right ht'₁, let ⟨t, ht, (h : t ×ˢ t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := f.property.left.nonempty_of_mem ht in have t'' ∈ f.val ×ᶠ pure x, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, h $ mk_mem_prod hx hx, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp only [closure_eq_cluster_pts, cluster_pt, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm _ (range pure_cauchy), mem_set_of_eq], exact (lift'_ne_bot_iff $ monotone_const.inter monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ⟨_, this⟩) end lemma dense_inducing_pure_cauchy : dense_inducing pure_cauchy := uniform_inducing_pure_cauchy.dense_inducing dense_range_pure_cauchy lemma dense_embedding_pure_cauchy : dense_embedding pure_cauchy := uniform_embedding_pure_cauchy.dense_embedding dense_range_pure_cauchy lemma nonempty_Cauchy_iff : nonempty (Cauchy α) ↔ nonempty α := begin split ; rintro ⟨c⟩, { have := eq_univ_iff_forall.1 dense_embedding_pure_cauchy.to_dense_inducing.closure_range c, obtain ⟨_, ⟨_, a, _⟩⟩ := mem_closure_iff.1 this _ is_open_univ trivial, exact ⟨a⟩ }, { exact ⟨pure_cauchy c⟩ } end section set_option eqn_compiler.zeta true instance : complete_space (Cauchy α) := complete_space_extension uniform_inducing_pure_cauchy dense_range_pure_cauchy $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ (𝓤 $ Cauchy α).lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : t' ×ˢ t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (f ×ᶠ pure x).sets_of_superset (prod_mem_prod ht' hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end instance [inhabited α] : inhabited (Cauchy α) := ⟨pure_cauchy default⟩ instance [h : nonempty α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a section extend def extend (f : α → β) : (Cauchy α → β) := if uniform_continuous f then dense_inducing_pure_cauchy.extend f else λ x, f (classical.inhabited_of_nonempty $ nonempty_Cauchy_iff.1 ⟨x⟩).default section separated_space variables [separated_space β] lemma extend_pure_cauchy {f : α → β} (hf : uniform_continuous f) (a : α) : extend f (pure_cauchy a) = f a := begin rw [extend, if_pos hf], exact uniformly_extend_of_ind uniform_inducing_pure_cauchy dense_range_pure_cauchy hf _ end end separated_space variables [_root_.complete_space β] lemma uniform_continuous_extend {f : α → β} : uniform_continuous (extend f) := begin by_cases hf : uniform_continuous f, { rw [extend, if_pos hf], exact uniform_continuous_uniformly_extend uniform_inducing_pure_cauchy dense_range_pure_cauchy hf }, { rw [extend, if_neg hf], exact uniform_continuous_of_const (assume a b, by congr) } end end extend end theorem Cauchy_eq {α : Type*} [inhabited α] [uniform_space α] [complete_space α] [separated_space α] {f g : Cauchy α} : Lim f.1 = Lim g.1 ↔ (f, g) ∈ separation_rel (Cauchy α) := begin split, { intros e s hs, rcases Cauchy.mem_uniformity'.1 hs with ⟨t, tu, ts⟩, apply ts, rcases comp_mem_uniformity_sets tu with ⟨d, du, dt⟩, refine mem_prod_iff.2 ⟨_, f.2.le_nhds_Lim (mem_nhds_right (Lim f.1) du), _, g.2.le_nhds_Lim (mem_nhds_left (Lim g.1) du), λ x h, _⟩, cases x with a b, cases h with h₁ h₂, rw ← e at h₂, exact dt ⟨_, h₁, h₂⟩ }, { intros H, refine separated_def.1 (by apply_instance) _ _ (λ t tu, _), rcases mem_uniformity_is_closed tu with ⟨d, du, dc, dt⟩, refine H {p | (Lim p.1.1, Lim p.2.1) ∈ t} (Cauchy.mem_uniformity'.2 ⟨d, du, λ f g h, _⟩), rcases mem_prod_iff.1 h with ⟨x, xf, y, yg, h⟩, have limc : ∀ (f : Cauchy α) (x ∈ f.1), Lim f.1 ∈ closure x, { intros f x xf, rw closure_eq_cluster_pts, exact f.2.1.mono (le_inf f.2.le_nhds_Lim (le_principal_iff.2 xf)) }, have := dc.closure_subset_iff.2 h, rw closure_prod_eq at this, refine dt (this ⟨_, _⟩); dsimp; apply limc; assumption } end section local attribute [instance] uniform_space.separation_setoid lemma separated_pure_cauchy_injective {α : Type*} [uniform_space α] [s : separated_space α] : function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h := separated_def.1 s _ _ $ assume s hs, let ⟨t, ht, hts⟩ := by rw [← (@uniform_embedding_pure_cauchy α _).comap_uniformity, filter.mem_comap] at hs; exact hs in have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht, @hts (a, b) this end end Cauchy local attribute [instance] uniform_space.separation_setoid open Cauchy set namespace uniform_space variables (α : Type*) [uniform_space α] variables {β : Type*} [uniform_space β] variables {γ : Type*} [uniform_space γ] instance complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (f.comap (λx, ⟦x⟧)), from hf.comap' comap_quotient_le_uniformity $ hf.left.comap_of_surj (surjective_quotient_mk _), let ⟨x, (hx : f.comap (λx, ⟦x⟧) ≤ 𝓝 x)⟩ := complete_space.complete this in ⟨⟦x⟧, (comap_le_comap_iff $ by simp).1 (hx.trans $ map_le_iff_le_comap.1 continuous_quotient_mk.continuous_at)⟩⟩ /-- Hausdorff completion of `α` -/ def completion := quotient (separation_setoid $ Cauchy α) namespace completion instance [inhabited α] : inhabited (completion α) := by unfold completion; apply_instance @[priority 50] instance : uniform_space (completion α) := by dunfold completion ; apply_instance instance : complete_space (completion α) := by dunfold completion ; apply_instance instance : separated_space (completion α) := by dunfold completion ; apply_instance instance : regular_space (completion α) := separated_regular /-- Automatic coercion from `α` to its completion. Not always injective. -/ instance : has_coe_t α (completion α) := ⟨quotient.mk ∘ pure_cauchy⟩ -- note [use has_coe_t] protected lemma coe_eq : (coe : α → completion α) = quotient.mk ∘ pure_cauchy := rfl lemma comap_coe_eq_uniformity : (𝓤 _).comap (λ(p:α×α), ((p.1 : completion α), (p.2 : completion α))) = 𝓤 α := begin have : (λx:α×α, ((x.1 : completion α), (x.2 : completion α))) = (λx:(Cauchy α)×(Cauchy α), (⟦x.1⟧, ⟦x.2⟧)) ∘ (λx:α×α, (pure_cauchy x.1, pure_cauchy x.2)), { ext ⟨a, b⟩; simp; refl }, rw [this, ← filter.comap_comap], change filter.comap _ (filter.comap _ (𝓤 $ quotient $ separation_setoid $ Cauchy α)) = 𝓤 α, rw [comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.comap_uniformity] end lemma uniform_inducing_coe : uniform_inducing (coe : α → completion α) := ⟨comap_coe_eq_uniformity α⟩ variables {α} lemma dense_range_coe : dense_range (coe : α → completion α) := dense_range_pure_cauchy.quotient variables (α) def cpkg {α : Type*} [uniform_space α] : abstract_completion α := { space := completion α, coe := coe, uniform_struct := by apply_instance, complete := by apply_instance, separation := by apply_instance, uniform_inducing := completion.uniform_inducing_coe α, dense := completion.dense_range_coe } instance abstract_completion.inhabited : inhabited (abstract_completion α) := ⟨cpkg⟩ local attribute [instance] abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation lemma nonempty_completion_iff : nonempty (completion α) ↔ nonempty α := cpkg.dense.nonempty_iff.symm lemma uniform_continuous_coe : uniform_continuous (coe : α → completion α) := cpkg.uniform_continuous_coe lemma continuous_coe : continuous (coe : α → completion α) := cpkg.continuous_coe lemma uniform_embedding_coe [separated_space α] : uniform_embedding (coe : α → completion α) := { comap_uniformity := comap_coe_eq_uniformity α, inj := separated_pure_cauchy_injective } lemma coe_injective [separated_space α] : function.injective (coe : α → completion α) := uniform_embedding.inj (uniform_embedding_coe _) variable {α} lemma dense_inducing_coe : dense_inducing (coe : α → completion α) := { dense := dense_range_coe, ..(uniform_inducing_coe α).inducing } open topological_space instance separable_space_completion [separable_space α] : separable_space (completion α) := completion.dense_inducing_coe.separable_space lemma dense_embedding_coe [separated_space α]: dense_embedding (coe : α → completion α) := { inj := separated_pure_cauchy_injective, ..dense_inducing_coe } lemma dense_range_coe₂ : dense_range (λx:α × β, ((x.1 : completion α), (x.2 : completion β))) := dense_range_coe.prod_map dense_range_coe lemma dense_range_coe₃ : dense_range (λx:α × (β × γ), ((x.1 : completion α), ((x.2.1 : completion β), (x.2.2 : completion γ)))) := dense_range_coe.prod_map dense_range_coe₂ @[elab_as_eliminator] lemma induction_on {p : completion α → Prop} (a : completion α) (hp : is_closed {a | p a}) (ih : ∀a:α, p a) : p a := is_closed_property dense_range_coe hp ih a @[elab_as_eliminator] lemma induction_on₂ {p : completion α → completion β → Prop} (a : completion α) (b : completion β) (hp : is_closed {x : completion α × completion β | p x.1 x.2}) (ih : ∀(a:α) (b:β), p a b) : p a b := have ∀x : completion α × completion β, p x.1 x.2, from is_closed_property dense_range_coe₂ hp $ assume ⟨a, b⟩, ih a b, this (a, b) @[elab_as_eliminator] lemma induction_on₃ {p : completion α → completion β → completion γ → Prop} (a : completion α) (b : completion β) (c : completion γ) (hp : is_closed {x : completion α × completion β × completion γ | p x.1 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ), p a b c) : p a b c := have ∀x : completion α × completion β × completion γ, p x.1 x.2.1 x.2.2, from is_closed_property dense_range_coe₃ hp $ assume ⟨a, b, c⟩, ih a b c, this (a, b, c) lemma ext [t2_space β] {f g : completion α → β} (hf : continuous f) (hg : continuous g) (h : ∀a:α, f a = g a) : f = g := cpkg.funext hf hg h section extension variables {f : α → β} /-- "Extension" to the completion. It is defined for any map `f` but returns an arbitrary constant value if `f` is not uniformly continuous -/ protected def extension (f : α → β) : completion α → β := cpkg.extend f section complete_space variables [complete_space β] lemma uniform_continuous_extension : uniform_continuous (completion.extension f) := cpkg.uniform_continuous_extend lemma continuous_extension : continuous (completion.extension f) := cpkg.continuous_extend end complete_space @[simp] lemma extension_coe [separated_space β] (hf : uniform_continuous f) (a : α) : (completion.extension f) a = f a := cpkg.extend_coe hf a variables [separated_space β] [complete_space β] lemma extension_unique (hf : uniform_continuous f) {g : completion α → β} (hg : uniform_continuous g) (h : ∀ a : α, f a = g (a : completion α)) : completion.extension f = g := cpkg.extend_unique hf hg h @[simp] lemma extension_comp_coe {f : completion α → β} (hf : uniform_continuous f) : completion.extension (f ∘ coe) = f := cpkg.extend_comp_coe hf end extension section map variables {f : α → β} /-- Completion functor acting on morphisms -/ protected def map (f : α → β) : completion α → completion β := cpkg.map cpkg f lemma uniform_continuous_map : uniform_continuous (completion.map f) := cpkg.uniform_continuous_map cpkg f lemma continuous_map : continuous (completion.map f) := cpkg.continuous_map cpkg f @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : (completion.map f) a = f a := cpkg.map_coe cpkg hf a lemma map_unique {f : α → β} {g : completion α → completion β} (hg : uniform_continuous g) (h : ∀a:α, ↑(f a) = g a) : completion.map f = g := cpkg.map_unique cpkg hg h @[simp] lemma map_id : completion.map (@id α) = id := cpkg.map_id lemma extension_map [complete_space γ] [separated_space γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : completion.extension f ∘ completion.map g = completion.extension (f ∘ g) := completion.ext (continuous_extension.comp continuous_map) continuous_extension $ by intro a; simp only [hg, hf, hf.comp hg, (∘), map_coe, extension_coe] lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : completion.map g ∘ completion.map f = completion.map (g ∘ f) := extension_map ((uniform_continuous_coe _).comp hg) hf end map /- In this section we construct isomorphisms between the completion of a uniform space and the completion of its separation quotient -/ section separation_quotient_completion def completion_separation_quotient_equiv (α : Type u) [uniform_space α] : completion (separation_quotient α) ≃ completion α := begin refine ⟨completion.extension (separation_quotient.lift (coe : α → completion α)), completion.map quotient.mk, _, _⟩, { assume a, refine induction_on a (is_closed_eq (continuous_map.comp continuous_extension) continuous_id) _, rintros ⟨a⟩, show completion.map quotient.mk (completion.extension (separation_quotient.lift coe) ↑⟦a⟧) = ↑⟦a⟧, rw [extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α), completion.map_coe uniform_continuous_quotient_mk] ; apply_instance }, { assume a, refine completion.induction_on a (is_closed_eq (continuous_extension.comp continuous_map) continuous_id) (λ a, _), rw [map_coe uniform_continuous_quotient_mk, extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α) _] ; apply_instance } end lemma uniform_continuous_completion_separation_quotient_equiv : uniform_continuous ⇑(completion_separation_quotient_equiv α) := uniform_continuous_extension lemma uniform_continuous_completion_separation_quotient_equiv_symm : uniform_continuous ⇑(completion_separation_quotient_equiv α).symm := uniform_continuous_map end separation_quotient_completion section extension₂ variables (f : α → β → γ) open function protected def extension₂ (f : α → β → γ) : completion α → completion β → γ := cpkg.extend₂ cpkg f section separated_space variables [separated_space γ] {f} @[simp] lemma extension₂_coe_coe (hf : uniform_continuous₂ f) (a : α) (b : β) : completion.extension₂ f a b = f a b := cpkg.extension₂_coe_coe cpkg hf a b end separated_space variables [complete_space γ] (f) lemma uniform_continuous_extension₂ : uniform_continuous₂ (completion.extension₂ f) := cpkg.uniform_continuous_extension₂ cpkg f end extension₂ section map₂ open function protected def map₂ (f : α → β → γ) : completion α → completion β → completion γ := cpkg.map₂ cpkg cpkg f lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous₂ (completion.map₂ f) := cpkg.uniform_continuous_map₂ cpkg cpkg f lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → completion α} {b : δ → completion β} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, completion.map₂ f (a d) (b d)) := cpkg.continuous_map₂ cpkg cpkg ha hb lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous₂ f) : completion.map₂ f (a : completion α) (b : completion β) = f a b := cpkg.map₂_coe_coe cpkg cpkg a b f hf end map₂ end completion end uniform_space
a8b617bd619ff7c26ef9ad92acf4f36f24cc4007
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/IR/EmitLLVM.lean
350dd492570226d8a3ce910f28c9d16eadcfeb17
[ "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
76,129
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Siddharth Bhat -/ import Lean.Data.HashMap import Lean.Runtime import Lean.Compiler.NameMangling import Lean.Compiler.ExportAttr import Lean.Compiler.InitAttr import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.EmitUtil import Lean.Compiler.IR.NormIds import Lean.Compiler.IR.SimpCase import Lean.Compiler.IR.Boxing import Lean.Compiler.IR.ResetReuse import Lean.Compiler.IR.LLVMBindings open Lean.IR.ExplicitBoxing (isBoxedName) namespace Lean.IR def leanMainFn := "_lean_main" namespace LLVM -- TODO(bollu): instantiate target triple and find out what size_t is. def size_tType (llvmctx : LLVM.Context) : IO (LLVM.LLVMType llvmctx) := LLVM.i64Type llvmctx -- Helper to add a function if it does not exist, and to return the function handle if it does. def getOrAddFunction (m : LLVM.Module ctx) (name : String) (type : LLVM.LLVMType ctx) : BaseIO (LLVM.Value ctx) := do match (← LLVM.getNamedFunction m name) with | some fn => return fn | none => /- By the evidence shown in: https://github.com/leanprover/lean4/issues/2373#issuecomment-1658743284 this is how clang implements `-fstack-clash-protection` in the LLVM IR, we want this feature for robust stack overflow detection. -/ let fn ← LLVM.addFunction m name type let attr ← LLVM.createStringAttribute "probe-stack" "inline-asm" LLVM.addAttributeAtIndex fn LLVM.AttributeIndex.AttributeFunctionIndex attr return fn def getOrAddGlobal (m : LLVM.Module ctx) (name : String) (type : LLVM.LLVMType ctx) : BaseIO (LLVM.Value ctx) := do match (← LLVM.getNamedGlobal m name) with | .some fn => return fn | .none => LLVM.addGlobal m name type end LLVM namespace EmitLLVM structure Context (llvmctx : LLVM.Context) where env : Environment modName : Name jpMap : JPParamsMap := {} mainFn : FunId := default mainParams : Array Param := #[] llvmmodule : LLVM.Module llvmctx structure State (llvmctx : LLVM.Context) where var2val : HashMap VarId (LLVM.LLVMType llvmctx × LLVM.Value llvmctx) jp2bb : HashMap JoinPointId (LLVM.BasicBlock llvmctx) abbrev Error := String abbrev M (llvmctx : LLVM.Context) := StateRefT (State llvmctx) (ReaderT (Context llvmctx) (ExceptT Error IO)) instance : Inhabited (M llvmctx α) where default := throw "Error: inhabitant" def addVartoState (x : VarId) (v : LLVM.Value llvmctx) (ty : LLVM.LLVMType llvmctx) : M llvmctx Unit := do modify (fun s => { s with var2val := s.var2val.insert x (ty, v) }) -- add new variable def addJpTostate (jp : JoinPointId) (bb : LLVM.BasicBlock llvmctx) : M llvmctx Unit := modify (fun s => { s with jp2bb := s.jp2bb.insert jp bb }) def emitJp (jp : JoinPointId) : M llvmctx (LLVM.BasicBlock llvmctx) := do let state ← get match state.jp2bb.find? jp with | .some bb => return bb | .none => throw s!"unable to find join point {jp}" def getLLVMModule : M llvmctx (LLVM.Module llvmctx) := Context.llvmmodule <$> read def getEnv : M llvmctx Environment := Context.env <$> read def getModName : M llvmctx Name := Context.modName <$> read def getDecl (n : Name) : M llvmctx Decl := do let env ← getEnv match findEnvDecl env n with | some d => pure d | none => throw s!"unknown declaration {n}" def constIntUnsigned (n : Nat) : M llvmctx (LLVM.Value llvmctx) := do LLVM.constIntUnsigned llvmctx (UInt64.ofNat n) def getOrCreateFunctionPrototype (mod : LLVM.Module llvmctx) (retty : LLVM.LLVMType llvmctx) (name : String) (args : Array (LLVM.LLVMType llvmctx)) : M llvmctx (LLVM.Value llvmctx) := do LLVM.getOrAddFunction mod name $ ← LLVM.functionType retty args (isVarArg := false) def callLeanBox (builder : LLVM.Builder llvmctx) (arg : LLVM.Value llvmctx) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_box" let retty ← LLVM.voidPtrType llvmctx let argtys := #[ ← LLVM.size_tType llvmctx ] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[arg] name def callLeanMarkPersistentFn (builder : LLVM.Builder llvmctx) (arg : LLVM.Value llvmctx) : M llvmctx Unit := do let fnName := "lean_mark_persistent" let retty ← LLVM.voidType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx ] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[arg] -- `lean_{inc, dec}_{ref?}_{1,n}` inductive RefcountKind where | inc | dec instance : ToString RefcountKind where toString | .inc => "inc" | .dec => "dec" def callLeanRefcountFn (builder : LLVM.Builder llvmctx) (kind : RefcountKind) (checkRef? : Bool) (arg : LLVM.Value llvmctx) (delta : Option (LLVM.Value llvmctx) := Option.none) : M llvmctx Unit := do let fnName := s!"lean_{kind}{if checkRef? then "" else "_ref"}{if delta.isNone then "" else "_n"}" let retty ← LLVM.voidType llvmctx let argtys := if delta.isNone then #[← LLVM.voidPtrType llvmctx] else #[← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys match delta with | .none => do -- since refcount δ is 1, we only supply the pointer. let _ ← LLVM.buildCall2 builder fnty fn #[arg] | .some n => do let _ ← LLVM.buildCall2 builder fnty fn #[arg, n] -- `decRef1` -- Do NOT attempt to merge this code with callLeanRefcountFn, because of the uber confusing -- semantics of 'ref?'. If 'ref?' is true, it calls the version that is lean_dec def callLeanDecRef (builder : LLVM.Builder llvmctx) (res : LLVM.Value llvmctx) : M llvmctx Unit := do let fnName := "lean_dec_ref" let retty ← LLVM.voidType llvmctx let argtys := #[ ← LLVM.i8PtrType llvmctx ] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[res] def callLeanUnsignedToNatFn (builder : LLVM.Builder llvmctx) (n : Nat) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let mod ← getLLVMModule let argtys := #[← LLVM.i32Type llvmctx] let retty ← LLVM.voidPtrType llvmctx let f ← getOrCreateFunctionPrototype mod retty "lean_unsigned_to_nat" argtys let fnty ← LLVM.functionType retty argtys let nv ← LLVM.constInt32 llvmctx (UInt64.ofNat n) LLVM.buildCall2 builder fnty f #[nv] name def callLeanMkStringFromBytesFn (builder : LLVM.Builder llvmctx) (strPtr nBytes : LLVM.Value llvmctx) (name : String) : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_mk_string_from_bytes" let retty ← LLVM.voidPtrType llvmctx let argtys := #[← LLVM.voidPtrType llvmctx, ← LLVM.i64Type llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[strPtr, nBytes] name def callLeanMkString (builder : LLVM.Builder llvmctx) (strPtr : LLVM.Value llvmctx) (name : String) : M llvmctx (LLVM.Value llvmctx) := do let retty ← LLVM.voidPtrType llvmctx let argtys := #[← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty "lean_mk_string" argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[strPtr] name def callLeanCStrToNatFn (builder : LLVM.Builder llvmctx) (n : Nat) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_cstr_to_nat" let retty ← LLVM.voidPtrType llvmctx let argtys := #[← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let s ← LLVM.buildGlobalString builder (value := toString n) LLVM.buildCall2 builder fnty fn #[s] name def callLeanIOMkWorld (builder : LLVM.Builder llvmctx) : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_io_mk_world" let retty ← LLVM.voidPtrType llvmctx let argtys := #[] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[] "mk_io_out" def callLeanIOResultIsError (builder : LLVM.Builder llvmctx) (arg : LLVM.Value llvmctx) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_io_result_is_error" let retty ← LLVM.i1Type llvmctx let argtys := #[← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[arg] name def callLeanAllocCtor (builder : LLVM.Builder llvmctx) (tag num_objs scalar_sz : Nat) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_alloc_ctor" let retty ← LLVM.voidPtrType llvmctx let i32 ← LLVM.i32Type llvmctx let argtys := #[i32, i32, i32] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let tag ← LLVM.constInt32 llvmctx (UInt64.ofNat tag) let num_objs ← LLVM.constInt32 llvmctx (UInt64.ofNat num_objs) let scalar_sz ← LLVM.constInt32 llvmctx (UInt64.ofNat scalar_sz) LLVM.buildCall2 builder fnty fn #[tag, num_objs, scalar_sz] name def callLeanCtorSet (builder : LLVM.Builder llvmctx) (o i v : LLVM.Value llvmctx) : M llvmctx Unit := do let fnName := "lean_ctor_set" let retty ← LLVM.voidType llvmctx let voidptr ← LLVM.voidPtrType llvmctx let unsigned ← LLVM.size_tType llvmctx let argtys := #[voidptr, unsigned, voidptr] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys _ <- LLVM.buildCall2 builder fnty fn #[o, i, v] def callLeanIOResultMKOk (builder : LLVM.Builder llvmctx) (v : LLVM.Value llvmctx) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_io_result_mk_ok" let voidptr ← LLVM.voidPtrType llvmctx let retty := voidptr let argtys := #[voidptr] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[v] name def callLeanAllocClosureFn (builder : LLVM.Builder llvmctx) (f arity nys : LLVM.Value llvmctx) (retName : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_alloc_closure" let retty ← LLVM.voidPtrType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx, ← LLVM.size_tType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[f, arity, nys] retName def callLeanClosureSetFn (builder : LLVM.Builder llvmctx) (closure ix arg : LLVM.Value llvmctx) (retName : String := "") : M llvmctx Unit := do let fnName := "lean_closure_set" let retty ← LLVM.voidType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx, ← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[closure, ix, arg] retName def callLeanObjTag (builder : LLVM.Builder llvmctx) (closure : LLVM.Value llvmctx) (retName : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_obj_tag" let retty ← LLVM.i32Type llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let out ← LLVM.buildCall2 builder fnty fn #[closure] retName LLVM.buildSextOrTrunc builder out (← LLVM.i64Type llvmctx) def callLeanIOResultGetValue (builder : LLVM.Builder llvmctx) (v : LLVM.Value llvmctx) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_io_result_get_value" let retty ← LLVM.voidPtrType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[v] name def callLeanCtorRelease (builder : LLVM.Builder llvmctx) (closure i : LLVM.Value llvmctx) (retName : String := "") : M llvmctx Unit := do let fnName := "lean_ctor_release" let retty ← LLVM.voidType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[closure, i] retName def callLeanCtorSetTag (builder : LLVM.Builder llvmctx) (closure i : LLVM.Value llvmctx) (retName : String := "") : M llvmctx Unit := do let fnName := "lean_ctor_set_tag" let retty ← LLVM.voidType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[closure, i] retName def toLLVMType (t : IRType) : M llvmctx (LLVM.LLVMType llvmctx) := do match t with | IRType.float => LLVM.doubleTypeInContext llvmctx | IRType.uint8 => LLVM.intTypeInContext llvmctx 8 | IRType.uint16 => LLVM.intTypeInContext llvmctx 16 | IRType.uint32 => LLVM.intTypeInContext llvmctx 32 | IRType.uint64 => LLVM.intTypeInContext llvmctx 64 -- TODO: how to cleanly size_t in LLVM? We can do eg. instantiate the current target and query for size. | IRType.usize => LLVM.size_tType llvmctx | IRType.object => do LLVM.pointerType (← LLVM.i8Type llvmctx) | IRType.tobject => do LLVM.pointerType (← LLVM.i8Type llvmctx) | IRType.irrelevant => do LLVM.pointerType (← LLVM.i8Type llvmctx) | IRType.struct _ _ => panic! "not implemented yet" | IRType.union _ _ => panic! "not implemented yet" def throwInvalidExportName {α : Type} (n : Name) : M llvmctx α := do throw s!"invalid export name {n.toString}" def toCName (n : Name) : M llvmctx String := do match getExportNameFor? (← getEnv) n with | some (.str .anonymous s) => pure s | some _ => throwInvalidExportName n | none => if n == `main then pure leanMainFn else pure n.mangle def toCInitName (n : Name) : M llvmctx String := do match getExportNameFor? (← getEnv) n with | some (.str .anonymous s) => return "_init_" ++ s | some _ => throwInvalidExportName n | none => pure ("_init_" ++ n.mangle) /-- ## LLVM Control flow Utilities -/ -- Indicates whether the API for building the blocks for then/else should -- forward the control flow to the merge block. inductive ShouldForwardControlFlow where | yes | no -- Get the function we are currently inserting into. def builderGetInsertionFn (builder : LLVM.Builder llvmctx) : M llvmctx (LLVM.Value llvmctx) := do let builderBB ← LLVM.getInsertBlock builder LLVM.getBasicBlockParent builderBB def builderAppendBasicBlock (builder : LLVM.Builder llvmctx) (name : String) : M llvmctx (LLVM.BasicBlock llvmctx) := do let fn ← builderGetInsertionFn builder LLVM.appendBasicBlockInContext llvmctx fn name def buildWhile_ (builder : LLVM.Builder llvmctx) (name : String) (condcodegen : LLVM.Builder llvmctx → M llvmctx (LLVM.Value llvmctx)) (bodycodegen : LLVM.Builder llvmctx → M llvmctx Unit) : M llvmctx Unit := do let fn ← builderGetInsertionFn builder let nameHeader := name ++ "header" let nameBody := name ++ "body" let nameMerge := name ++ "merge" -- cur → header let headerbb ← LLVM.appendBasicBlockInContext llvmctx fn nameHeader let _ ← LLVM.buildBr builder headerbb let bodybb ← LLVM.appendBasicBlockInContext llvmctx fn nameBody let mergebb ← LLVM.appendBasicBlockInContext llvmctx fn nameMerge -- header → {body, merge} LLVM.positionBuilderAtEnd builder headerbb let cond ← condcodegen builder let _ ← LLVM.buildCondBr builder cond bodybb mergebb -- body → header LLVM.positionBuilderAtEnd builder bodybb bodycodegen builder let _ ← LLVM.buildBr builder headerbb -- merge LLVM.positionBuilderAtEnd builder mergebb -- build an if, and position the builder at the merge basic block after execution. -- The '_' denotes that we return Unit on each branch. def buildIfThen_ (builder : LLVM.Builder llvmctx) (name : String) (brval : LLVM.Value llvmctx) (thencodegen : LLVM.Builder llvmctx → M llvmctx ShouldForwardControlFlow) : M llvmctx Unit := do let fn ← builderGetInsertionFn builder let nameThen := name ++ "Then" let nameElse := name ++ "Else" let nameMerge := name ++ "Merge" let thenbb ← LLVM.appendBasicBlockInContext llvmctx fn nameThen let elsebb ← LLVM.appendBasicBlockInContext llvmctx fn nameElse let mergebb ← LLVM.appendBasicBlockInContext llvmctx fn nameMerge let _ ← LLVM.buildCondBr builder brval thenbb elsebb -- then LLVM.positionBuilderAtEnd builder thenbb let fwd? ← thencodegen builder match fwd? with | .yes => let _ ← LLVM.buildBr builder mergebb | .no => pure () -- else LLVM.positionBuilderAtEnd builder elsebb let _ ← LLVM.buildBr builder mergebb -- merge LLVM.positionBuilderAtEnd builder mergebb def buildIfThenElse_ (builder : LLVM.Builder llvmctx) (name : String) (brval : LLVM.Value llvmctx) (thencodegen : LLVM.Builder llvmctx → M llvmctx ShouldForwardControlFlow) (elsecodegen : LLVM.Builder llvmctx → M llvmctx ShouldForwardControlFlow) : M llvmctx Unit := do let fn ← LLVM.getBasicBlockParent (← LLVM.getInsertBlock builder) let thenbb ← LLVM.appendBasicBlockInContext llvmctx fn (name ++ "Then") let elsebb ← LLVM.appendBasicBlockInContext llvmctx fn (name ++ "Else") let mergebb ← LLVM.appendBasicBlockInContext llvmctx fn (name ++ "Merge") let _ ← LLVM.buildCondBr builder brval thenbb elsebb -- then LLVM.positionBuilderAtEnd builder thenbb let fwd? ← thencodegen builder match fwd? with | .yes => let _ ← LLVM.buildBr builder mergebb | .no => pure () -- else LLVM.positionBuilderAtEnd builder elsebb let fwd? ← elsecodegen builder match fwd? with | .yes => let _ ← LLVM.buildBr builder mergebb | .no => pure () -- merge LLVM.positionBuilderAtEnd builder mergebb -- Recall that lean uses `i8` for booleans, not `i1`, so we need to compare with `true`. def buildLeanBoolTrue? (builder : LLVM.Builder llvmctx) (b : LLVM.Value llvmctx) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do LLVM.buildICmp builder LLVM.IntPredicate.NE b (← LLVM.constInt8 llvmctx 0) name def emitFnDeclAux (mod : LLVM.Module llvmctx) (decl : Decl) (cppBaseName : String) (isExternal : Bool) : M llvmctx (LLVM.Value llvmctx) := do let ps := decl.params let env ← getEnv -- bollu: if we have a declaration with no parameters, then we emit it as a global pointer. -- bollu: Otherwise, we emit it as a function let global ← if ps.isEmpty then let retty ← (toLLVMType decl.resultType) let global ← LLVM.getOrAddGlobal mod cppBaseName retty if !isExternal then LLVM.setInitializer global (← LLVM.getUndef retty) pure global else let retty ← (toLLVMType decl.resultType) let mut argtys := #[] for p in ps do -- if it is extern, then we must not add irrelevant args if !(isExternC env decl.name) || !p.ty.isIrrelevant then argtys := argtys.push (← toLLVMType p.ty) -- TODO (bollu): simplify this API, this code of `closureMaxArgs` is duplicated in multiple places. if argtys.size > closureMaxArgs && isBoxedName decl.name then argtys := #[← LLVM.pointerType (← LLVM.voidPtrType llvmctx)] let fnty ← LLVM.functionType retty argtys (isVarArg := false) LLVM.getOrAddFunction mod cppBaseName fnty -- we must now set symbol visibility for global. if ps.isEmpty then if isClosedTermName env decl.name then LLVM.setVisibility global LLVM.Visibility.hidden -- static else if isExternal then pure () -- extern (Recall that C/LLVM funcs are extern linkage by default.) else LLVM.setDLLStorageClass global LLVM.DLLStorageClass.export -- LEAN_EXPORT else if !isExternal -- An extern decl might be linked in from a different translation unit. -- Thus, we cannot export an external declaration as we do not define it, -- only declare its presence. -- So, we only export non-external definitions. then LLVM.setDLLStorageClass global LLVM.DLLStorageClass.export return global def emitFnDecl (decl : Decl) (isExternal : Bool) : M llvmctx Unit := do let cppBaseName ← toCName decl.name let _ ← emitFnDeclAux (← getLLVMModule) decl cppBaseName isExternal def emitExternDeclAux (decl : Decl) (cNameStr : String) : M llvmctx Unit := do let env ← getEnv let extC := isExternC env decl.name let _ ← emitFnDeclAux (← getLLVMModule) decl cNameStr extC def emitFnDecls : M llvmctx Unit := do let env ← getEnv let decls := getDecls env let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {} let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {} let usedDecls := usedDecls.toList for n in usedDecls do let decl ← getDecl n match getExternNameFor env `c decl.name with | some cName => emitExternDeclAux decl cName | none => emitFnDecl decl (!modDecls.contains n) return () def emitLhsSlot_ (x : VarId) : M llvmctx (LLVM.LLVMType llvmctx × LLVM.Value llvmctx) := do let state ← get match state.var2val.find? x with | .some v => return v | .none => throw s!"unable to find variable {x}" def emitLhsVal (builder : LLVM.Builder llvmctx) (x : VarId) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let (xty, xslot) ← emitLhsSlot_ x LLVM.buildLoad2 builder xty xslot name def emitLhsSlotStore (builder : LLVM.Builder llvmctx) (x : VarId) (v : LLVM.Value llvmctx) : M llvmctx Unit := do let (_, slot) ← emitLhsSlot_ x LLVM.buildStore builder v slot def emitArgSlot_ (builder : LLVM.Builder llvmctx) (x : Arg) : M llvmctx (LLVM.LLVMType llvmctx × LLVM.Value llvmctx) := do match x with | Arg.var x => emitLhsSlot_ x | _ => do let slotty ← LLVM.voidPtrType llvmctx let slot ← LLVM.buildAlloca builder slotty "irrelevant_slot" let v ← callLeanBox builder (← LLVM.constIntUnsigned llvmctx 0) "irrelevant_val" let _ ← LLVM.buildStore builder v slot return (slotty, slot) def emitArgVal (builder : LLVM.Builder llvmctx) (x : Arg) (name : String := "") : M llvmctx (LLVM.LLVMType llvmctx × LLVM.Value llvmctx) := do let (xty, xslot) ← emitArgSlot_ builder x let xval ← LLVM.buildLoad2 builder xty xslot name return (xty, xval) def emitAllocCtor (builder : LLVM.Builder llvmctx) (c : CtorInfo) : M llvmctx (LLVM.Value llvmctx) := do -- TODO(bollu) : find the correct size, don't assume 'void*' size is 8 let hackSizeofVoidPtr := 8 let scalarSize := hackSizeofVoidPtr * c.usize + c.ssize callLeanAllocCtor builder c.cidx c.size scalarSize "lean_alloc_ctor_out" def emitCtorSetArgs (builder : LLVM.Builder llvmctx) (z : VarId) (ys : Array Arg) : M llvmctx Unit := do ys.size.forM fun i => do let zv ← emitLhsVal builder z let (_yty, yv) ← emitArgVal builder ys[i]! let iv ← LLVM.constIntUnsigned llvmctx (UInt64.ofNat i) callLeanCtorSet builder zv iv yv emitLhsSlotStore builder z zv pure () def emitCtor (builder : LLVM.Builder llvmctx) (z : VarId) (c : CtorInfo) (ys : Array Arg) : M llvmctx Unit := do let (_llvmty, slot) ← emitLhsSlot_ z if c.size == 0 && c.usize == 0 && c.ssize == 0 then do let v ← callLeanBox builder (← constIntUnsigned c.cidx) "lean_box_outv" let _ ← LLVM.buildStore builder v slot else do let v ← emitAllocCtor builder c let _ ← LLVM.buildStore builder v slot emitCtorSetArgs builder z ys def emitInc (builder : LLVM.Builder llvmctx) (x : VarId) (n : Nat) (checkRef? : Bool) : M llvmctx Unit := do let xv ← emitLhsVal builder x if n != 1 then do let nv ← LLVM.constIntUnsigned llvmctx (UInt64.ofNat n) callLeanRefcountFn builder (kind := RefcountKind.inc) (checkRef? := checkRef?) (delta := nv) xv else callLeanRefcountFn builder (kind := RefcountKind.inc) (checkRef? := checkRef?) xv def emitDec (builder : LLVM.Builder llvmctx) (x : VarId) (n : Nat) (checkRef? : Bool) : M llvmctx Unit := do let xv ← emitLhsVal builder x if n != 1 then throw "expected n = 1 for emitDec" else callLeanRefcountFn builder (kind := RefcountKind.dec) (checkRef? := checkRef?) xv def emitNumLit (builder : LLVM.Builder llvmctx) (t : IRType) (v : Nat) : M llvmctx (LLVM.Value llvmctx) := do if t.isObj then if v < UInt32.size then callLeanUnsignedToNatFn builder v else callLeanCStrToNatFn builder v else LLVM.constInt (← toLLVMType t) (UInt64.ofNat v) def toHexDigit (c : Nat) : String := String.singleton c.digitChar -- TODO(bollu) : Setup code sharing between 'EmitC' and 'EmitLLVM' def quoteString (s : String) : String := let q := "\""; let q := s.foldl (fun q c => q ++ if c == '\n' then "\\n" else if c == '\r' then "\\r" else if c == '\t' then "\\t" else if c == '\\' then "\\\\" else if c == '\"' then "\\\"" else if c.toNat <= 31 then "\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16) -- TODO(Leo) : we should use `\unnnn` for escaping unicode characters. else String.singleton c) q; q ++ "\"" def emitSimpleExternalCall (builder : LLVM.Builder llvmctx) (f : String) (ps : Array Param) (ys : Array Arg) (retty : IRType) (name : String) : M llvmctx (LLVM.Value llvmctx) := do let mut args := #[] let mut argTys := #[] for (p, y) in ps.zip ys do if !p.ty.isIrrelevant then let (_yty, yv) ← emitArgVal builder y "" argTys := argTys.push (← toLLVMType p.ty) args := args.push yv let fnty ← LLVM.functionType (← toLLVMType retty) argTys let fn ← LLVM.getOrAddFunction (← getLLVMModule) f fnty LLVM.buildCall2 builder fnty fn args name -- TODO: if the external call is one that we cannot code generate, give up and -- generate fallback code. def emitExternCall (builder : LLVM.Builder llvmctx) (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) (retty : IRType) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := match getExternEntryFor extData `c with | some (ExternEntry.standard _ extFn) => emitSimpleExternalCall builder extFn ps ys retty name | some (ExternEntry.inline "llvm" _pat) => throw "Unimplemented codegen of inline LLVM" | some (ExternEntry.inline _ pat) => throw s!"Cannot codegen non-LLVM inline code '{pat}'." | some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall builder extFn ps ys retty name | _ => throw s!"Failed to emit extern application '{f}'." def getFunIdTy (f : FunId) : M llvmctx (LLVM.LLVMType llvmctx) := do let decl ← getDecl f let retty ← toLLVMType decl.resultType let argtys ← decl.params.mapM (fun p => do toLLVMType p.ty) LLVM.functionType retty argtys /-- Create a function declaration and return a pointer to the function. If the function actually takes arguments, then we must have a function pointer in scope. If the function takes no arguments, then it is a top-level closed term, and its value will be stored in a global pointer. So, we load from the global pointer. The type of the global is function pointer pointer. This returns a *function pointer.* -/ def getOrAddFunIdValue (builder : LLVM.Builder llvmctx) (f : FunId) : M llvmctx (LLVM.Value llvmctx) := do let decl ← getDecl f let fcname ← toCName f let retty ← toLLVMType decl.resultType if decl.params.isEmpty then let gslot ← LLVM.getOrAddGlobal (← getLLVMModule) fcname retty LLVM.buildLoad2 builder retty gslot else let argtys ← decl.params.mapM (fun p => do toLLVMType p.ty) let fnty ← LLVM.functionType retty argtys LLVM.getOrAddFunction (← getLLVMModule) fcname fnty def emitPartialApp (builder : LLVM.Builder llvmctx) (z : VarId) (f : FunId) (ys : Array Arg) : M llvmctx Unit := do let decl ← getDecl f let fv ← getOrAddFunIdValue builder f let arity := decl.params.size let (_zty, zslot) ← emitLhsSlot_ z let zval ← callLeanAllocClosureFn builder fv (← constIntUnsigned arity) (← constIntUnsigned ys.size) LLVM.buildStore builder zval zslot ys.size.forM fun i => do let (yty, yslot) ← emitArgSlot_ builder ys[i]! let yval ← LLVM.buildLoad2 builder yty yslot callLeanClosureSetFn builder zval (← constIntUnsigned i) yval def emitApp (builder : LLVM.Builder llvmctx) (z : VarId) (f : VarId) (ys : Array Arg) : M llvmctx Unit := do if ys.size > closureMaxArgs then do let aargs ← LLVM.buildAlloca builder (← LLVM.arrayType (← LLVM.voidPtrType llvmctx) (UInt64.ofNat ys.size)) "aargs" for i in List.range ys.size do let (yty, yv) ← emitArgVal builder ys[i]! let aslot ← LLVM.buildInBoundsGEP2 builder yty aargs #[← constIntUnsigned 0, ← constIntUnsigned i] s!"param_{i}_slot" LLVM.buildStore builder yv aslot let fnName := s!"lean_apply_m" let retty ← LLVM.voidPtrType llvmctx let args := #[← emitLhsVal builder f, ← constIntUnsigned ys.size, aargs] -- '1 + ...'. '1' for the fn and 'args' for the arguments let argtys := #[← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let zv ← LLVM.buildCall2 builder fnty fn args emitLhsSlotStore builder z zv else do let fnName := s!"lean_apply_{ys.size}" let retty ← LLVM.voidPtrType llvmctx let args : Array (LLVM.Value llvmctx) := #[← emitLhsVal builder f] ++ (← ys.mapM (fun y => Prod.snd <$> (emitArgVal builder y))) -- '1 + ...'. '1' for the fn and 'args' for the arguments let argtys := (List.replicate (1 + ys.size) (← LLVM.voidPtrType llvmctx)).toArray let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let zv ← LLVM.buildCall2 builder fnty fn args emitLhsSlotStore builder z zv def emitFullApp (builder : LLVM.Builder llvmctx) (z : VarId) (f : FunId) (ys : Array Arg) : M llvmctx Unit := do let (__zty, zslot) ← emitLhsSlot_ z let decl ← getDecl f match decl with | Decl.extern _ ps retty extData => let zv ← emitExternCall builder f ps extData ys retty LLVM.buildStore builder zv zslot | Decl.fdecl .. => if ys.size > 0 then let fv ← getOrAddFunIdValue builder f let ys ← ys.mapM (fun y => do let (yty, yslot) ← emitArgSlot_ builder y let yv ← LLVM.buildLoad2 builder yty yslot return yv) let zv ← LLVM.buildCall2 builder (← getFunIdTy f) fv ys LLVM.buildStore builder zv zslot else let zv ← getOrAddFunIdValue builder f LLVM.buildStore builder zv zslot -- Note that this returns a *slot*, just like `emitLhsSlot_`. def emitLit (builder : LLVM.Builder llvmctx) (z : VarId) (t : IRType) (v : LitVal) : M llvmctx (LLVM.Value llvmctx) := do let llvmty ← toLLVMType t let zslot ← LLVM.buildAlloca builder llvmty addVartoState z zslot llvmty let zv ← match v with | LitVal.num v => emitNumLit builder t v | LitVal.str v => let zero ← LLVM.constIntUnsigned llvmctx 0 let str_global ← LLVM.buildGlobalString builder v -- access through the global, into the 0th index of the array let strPtr ← LLVM.buildInBoundsGEP2 builder (← LLVM.opaquePointerTypeInContext llvmctx) str_global #[zero] "" let nbytes ← LLVM.constIntUnsigned llvmctx (UInt64.ofNat (v.utf8ByteSize)) callLeanMkStringFromBytesFn builder strPtr nbytes "" LLVM.buildStore builder zv zslot return zslot def callLeanCtorGet (builder : LLVM.Builder llvmctx) (x i : LLVM.Value llvmctx) (retName : String) : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_ctor_get" let retty ← LLVM.voidPtrType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.i32Type llvmctx] let fnty ← LLVM.functionType retty argtys let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let i ← LLVM.buildSextOrTrunc builder i (← LLVM.i32Type llvmctx) LLVM.buildCall2 builder fnty fn #[x, i] retName def emitProj (builder : LLVM.Builder llvmctx) (z : VarId) (i : Nat) (x : VarId) : M llvmctx Unit := do let xval ← emitLhsVal builder x let zval ← callLeanCtorGet builder xval (← constIntUnsigned i) "" emitLhsSlotStore builder z zval def callLeanCtorGetUsize (builder : LLVM.Builder llvmctx) (x i : LLVM.Value llvmctx) (retName : String) : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_ctor_get_usize" let retty ← LLVM.size_tType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx] let fnty ← LLVM.functionType retty argtys let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys LLVM.buildCall2 builder fnty fn #[x, i] retName def emitUProj (builder : LLVM.Builder llvmctx) (z : VarId) (i : Nat) (x : VarId) : M llvmctx Unit := do let xval ← emitLhsVal builder x let zval ← callLeanCtorGetUsize builder xval (← constIntUnsigned i) "" emitLhsSlotStore builder z zval def emitOffset (builder : LLVM.Builder llvmctx) (n : Nat) (offset : Nat) : M llvmctx (LLVM.Value llvmctx) := do -- TODO(bollu) : replace 8 with sizeof(void*) let out ← constIntUnsigned 8 let out ← LLVM.buildMul builder out (← constIntUnsigned n) "" -- sizeof(void*)*n LLVM.buildAdd builder out (← constIntUnsigned offset) "" -- sizeof(void*)*n+offset def emitSProj (builder : LLVM.Builder llvmctx) (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M llvmctx Unit := do let (fnName, retty) ← match t with | IRType.float => pure ("lean_ctor_get_float", ← LLVM.doubleTypeInContext llvmctx) | IRType.uint8 => pure ("lean_ctor_get_uint8", ← LLVM.i8Type llvmctx) | IRType.uint16 => pure ("lean_ctor_get_uint16", ← LLVM.i16Type llvmctx) | IRType.uint32 => pure ("lean_ctor_get_uint32", ← LLVM.i32Type llvmctx) | IRType.uint64 => pure ("lean_ctor_get_uint64", ← LLVM.i64Type llvmctx) | _ => throw s!"Invalid type for lean_ctor_get: '{t}'" let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let xval ← emitLhsVal builder x let offset ← emitOffset builder n offset let fnty ← LLVM.functionType retty argtys let zval ← LLVM.buildCall2 builder fnty fn #[xval, offset] emitLhsSlotStore builder z zval def callLeanIsExclusive (builder : LLVM.Builder llvmctx) (closure : LLVM.Value llvmctx) (retName : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_is_exclusive" let retty ← LLVM.i1Type llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let out ← LLVM.buildCall2 builder fnty fn #[closure] retName LLVM.buildSextOrTrunc builder out (← LLVM.i8Type llvmctx) def callLeanIsScalar (builder : LLVM.Builder llvmctx) (closure : LLVM.Value llvmctx) (retName : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_is_scalar" let retty ← LLVM.i8Type llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[closure] retName def emitIsShared (builder : LLVM.Builder llvmctx) (z : VarId) (x : VarId) : M llvmctx Unit := do let xv ← emitLhsVal builder x let exclusive? ← callLeanIsExclusive builder xv let exclusive? ← LLVM.buildSextOrTrunc builder exclusive? (← LLVM.i1Type llvmctx) let shared? ← LLVM.buildNot builder exclusive? let shared? ← LLVM.buildSext builder shared? (← LLVM.i8Type llvmctx) emitLhsSlotStore builder z shared? def emitBox (builder : LLVM.Builder llvmctx) (z : VarId) (x : VarId) (xType : IRType) : M llvmctx Unit := do let xv ← emitLhsVal builder x let (fnName, argTy, xv) ← match xType with | IRType.usize => pure ("lean_box_usize", ← LLVM.size_tType llvmctx, xv) | IRType.uint32 => pure ("lean_box_uint32", ← LLVM.i32Type llvmctx, xv) | IRType.uint64 => pure ("lean_box_uint64", ← LLVM.size_tType llvmctx, xv) | IRType.float => pure ("lean_box_float", ← LLVM.doubleTypeInContext llvmctx, xv) | _ => do -- sign extend smaller values into i64 let xv ← LLVM.buildSext builder xv (← LLVM.size_tType llvmctx) pure ("lean_box", ← LLVM.size_tType llvmctx, xv) let retty ← LLVM.voidPtrType llvmctx let argtys := #[argTy] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let zv ← LLVM.buildCall2 builder fnty fn #[xv] emitLhsSlotStore builder z zv def IRType.isIntegerType (t : IRType) : Bool := match t with | .uint8 => true | .uint16 => true | .uint32 => true | .uint64 => true | .usize => true | _ => false def callUnboxForType (builder : LLVM.Builder llvmctx) (t : IRType) (v : LLVM.Value llvmctx) (retName : String := "") : M llvmctx (LLVM.Value llvmctx) := do let (fnName, retty) ← match t with | IRType.usize => pure ("lean_unbox_usize", ← toLLVMType t) | IRType.uint32 => pure ("lean_unbox_uint32", ← toLLVMType t) | IRType.uint64 => pure ("lean_unbox_uint64", ← toLLVMType t) | IRType.float => pure ("lean_unbox_float", ← toLLVMType t) | _ => pure ("lean_unbox", ← LLVM.size_tType llvmctx) let argtys := #[← LLVM.voidPtrType llvmctx ] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[v] retName def emitUnbox (builder : LLVM.Builder llvmctx) (z : VarId) (t : IRType) (x : VarId) (retName : String := "") : M llvmctx Unit := do let zval ← callUnboxForType builder t (← emitLhsVal builder x) retName -- NOTE(bollu) : note that lean_unbox only returns an i64, but we may need to truncate to -- smaller widths. see `phashmap` for an example of this occurring at calls to `lean_unbox` let zval ← if IRType.isIntegerType t then LLVM.buildSextOrTrunc builder zval (← toLLVMType t) else pure zval emitLhsSlotStore builder z zval def emitReset (builder : LLVM.Builder llvmctx) (z : VarId) (n : Nat) (x : VarId) : M llvmctx Unit := do let xv ← emitLhsVal builder x let isExclusive ← callLeanIsExclusive builder xv let isExclusive ← buildLeanBoolTrue? builder isExclusive buildIfThenElse_ builder "isExclusive" isExclusive (fun builder => do let xv ← emitLhsVal builder x n.forM fun i => do callLeanCtorRelease builder xv (← constIntUnsigned i) emitLhsSlotStore builder z xv return ShouldForwardControlFlow.yes ) (fun builder => do let xv ← emitLhsVal builder x callLeanDecRef builder xv let box0 ← callLeanBox builder (← constIntUnsigned 0) "box0" emitLhsSlotStore builder z box0 return ShouldForwardControlFlow.yes ) def emitReuse (builder : LLVM.Builder llvmctx) (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M llvmctx Unit := do let xv ← emitLhsVal builder x let isScalar ← callLeanIsScalar builder xv let isScalar ← buildLeanBoolTrue? builder isScalar buildIfThenElse_ builder "isScalar" isScalar (fun builder => do let cv ← emitAllocCtor builder c emitLhsSlotStore builder z cv return ShouldForwardControlFlow.yes ) (fun builder => do let xv ← emitLhsVal builder x emitLhsSlotStore builder z xv if updtHeader then let zv ← emitLhsVal builder z callLeanCtorSetTag builder zv (← constIntUnsigned c.cidx) return ShouldForwardControlFlow.yes ) emitCtorSetArgs builder z ys def emitVDecl (builder : LLVM.Builder llvmctx) (z : VarId) (t : IRType) (v : Expr) : M llvmctx Unit := do match v with | Expr.ctor c ys => emitCtor builder z c ys | Expr.reset n x => emitReset builder z n x | Expr.reuse x c u ys => emitReuse builder z x c u ys | Expr.proj i x => emitProj builder z i x | Expr.uproj i x => emitUProj builder z i x | Expr.sproj n o x => emitSProj builder z t n o x | Expr.fap c ys => emitFullApp builder z c ys | Expr.pap c ys => emitPartialApp builder z c ys | Expr.ap x ys => emitApp builder z x ys | Expr.box t x => emitBox builder z x t | Expr.unbox x => emitUnbox builder z t x | Expr.isShared x => emitIsShared builder z x | Expr.lit v => let _ ← emitLit builder z t v def declareVar (builder : LLVM.Builder llvmctx) (x : VarId) (t : IRType) : M llvmctx Unit := do let llvmty ← toLLVMType t let alloca ← LLVM.buildAlloca builder llvmty "varx" addVartoState x alloca llvmty partial def declareVars (builder : LLVM.Builder llvmctx) (f : FnBody) : M llvmctx Unit := do match f with | FnBody.vdecl x t _ b => do declareVar builder x t declareVars builder b | FnBody.jdecl _ xs _ b => do for param in xs do declareVar builder param.x param.ty declareVars builder b | e => do if e.isTerminal then pure () else declareVars builder e.body def emitTag (builder : LLVM.Builder llvmctx) (x : VarId) (xType : IRType) : M llvmctx (LLVM.Value llvmctx) := do if xType.isObj then do let xval ← emitLhsVal builder x callLeanObjTag builder xval else if xType.isScalar then do emitLhsVal builder x else throw "Do not know how to `emitTag` in general." def emitSet (builder : LLVM.Builder llvmctx) (x : VarId) (i : Nat) (y : Arg) : M llvmctx Unit := do let fnName := "lean_ctor_set" let retty ← LLVM.voidType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx, ← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[← emitLhsVal builder x, ← constIntUnsigned i, (← emitArgVal builder y).2] def emitUSet (builder : LLVM.Builder llvmctx) (x : VarId) (i : Nat) (y : VarId) : M llvmctx Unit := do let fnName := "lean_ctor_set_usize" let retty ← LLVM.voidType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx, ← LLVM.size_tType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[← emitLhsVal builder x, ← constIntUnsigned i, (← emitLhsVal builder y)] def emitTailCall (builder : LLVM.Builder llvmctx) (f : FunId) (v : Expr) : M llvmctx Unit := do match v with | Expr.fap _ ys => do let llvmctx ← read let ps := llvmctx.mainParams unless ps.size == ys.size do throw s!"Invalid tail call. f:'{f}' v:'{v}'" let args ← ys.mapM (fun y => Prod.snd <$> emitArgVal builder y) let fn ← builderGetInsertionFn builder let call ← LLVM.buildCall2 builder (← getFunIdTy f) fn args -- TODO (bollu) : add 'musttail' attribute using the C API. LLVM.setTailCall call true -- mark as tail call let _ ← LLVM.buildRet builder call | _ => throw s!"EmitTailCall expects function application, found '{v}'" def emitJmp (builder : LLVM.Builder llvmctx) (jp : JoinPointId) (xs : Array Arg) : M llvmctx Unit := do let llvmctx ← read let ps ← match llvmctx.jpMap.find? jp with | some ps => pure ps | none => throw s!"Unknown join point {jp}" unless xs.size == ps.size do throw s!"Invalid goto, mismatched sizes between arguments, formal parameters." for (p, x) in ps.zip xs do let (_xty, xv) ← emitArgVal builder x emitLhsSlotStore builder p.x xv let _ ← LLVM.buildBr builder (← emitJp jp) def emitSSet (builder : LLVM.Builder llvmctx) (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M llvmctx Unit := do let (fnName, setty) ← match t with | IRType.float => pure ("lean_ctor_set_float", ← LLVM.doubleTypeInContext llvmctx) | IRType.uint8 => pure ("lean_ctor_set_uint8", ← LLVM.i8Type llvmctx) | IRType.uint16 => pure ("lean_ctor_set_uint16", ← LLVM.i16Type llvmctx) | IRType.uint32 => pure ("lean_ctor_set_uint32", ← LLVM.i32Type llvmctx) | IRType.uint64 => pure ("lean_ctor_set_uint64", ← LLVM.i64Type llvmctx) | _ => throw s!"invalid type for 'lean_ctor_set': '{t}'" let argtys := #[ ← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx, setty] let retty ← LLVM.voidType llvmctx let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let xv ← emitLhsVal builder x let offset ← emitOffset builder n offset let yv ← emitLhsVal builder y let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[xv, offset, yv] def emitDel (builder : LLVM.Builder llvmctx) (x : VarId) : M llvmctx Unit := do let argtys := #[ ← LLVM.voidPtrType llvmctx] let retty ← LLVM.voidType llvmctx let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty "lean_free_object" argtys let xv ← emitLhsVal builder x let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[xv] def emitSetTag (builder : LLVM.Builder llvmctx) (x : VarId) (i : Nat) : M llvmctx Unit := do let argtys := #[← LLVM.voidPtrType llvmctx, ← LLVM.size_tType llvmctx] let retty ← LLVM.voidType llvmctx let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty "lean_ctor_set_tag" argtys let xv ← emitLhsVal builder x let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[xv, ← constIntUnsigned i] def ensureHasDefault' (alts : Array Alt) : Array Alt := if alts.any Alt.isDefault then alts else let last := alts.back let alts := alts.pop alts.push (Alt.default last.body) mutual partial def emitCase (builder : LLVM.Builder llvmctx) (x : VarId) (xType : IRType) (alts : Array Alt) : M llvmctx Unit := do let oldBB ← LLVM.getInsertBlock builder -- NOTE: In this context, 'Zext' versus 'Sext' have a meaninful semantic difference. -- We perform a zero extend so that one-bit tags of `0/-1` actually extend to `0/1` -- in 64-bit space. let tag ← emitTag builder x xType let tag ← LLVM.buildZext builder tag (← LLVM.i64Type llvmctx) let alts := ensureHasDefault' alts let defaultBB ← builderAppendBasicBlock builder s!"case_{xType}_default" let numCasesHint := alts.size let switch ← LLVM.buildSwitch builder tag defaultBB (UInt64.ofNat numCasesHint) alts.forM fun alt => do match alt with | Alt.ctor c b => let destbb ← builderAppendBasicBlock builder s!"case_{xType}_{c.name}_{c.cidx}" LLVM.addCase switch (← constIntUnsigned c.cidx) destbb LLVM.positionBuilderAtEnd builder destbb emitFnBody builder b | Alt.default b => LLVM.positionBuilderAtEnd builder defaultBB emitFnBody builder b LLVM.clearInsertionPosition builder LLVM.positionBuilderAtEnd builder oldBB -- reset state to previous insertion point. -- NOTE: emitJP promises to keep the builder context untouched. partial def emitJDecl (builder : LLVM.Builder llvmctx) (jp : JoinPointId) (_ps : Array Param) (b : FnBody) : M llvmctx Unit := do let oldBB ← LLVM.getInsertBlock builder let jpbb ← builderAppendBasicBlock builder s!"jp_{jp.idx}" addJpTostate jp jpbb LLVM.positionBuilderAtEnd builder jpbb -- NOTE(bollu) : Note that we declare the slots for the variables that are inside -- the join point body before emitting the join point body. -- This ensures reachability via dominance. -- TODO(bollu) : Eliminate the need entirely for 'alloca'/slots by generating SSA phi nodes -- directly as discussed with digamma(Mario Carneiro <di.gama@gmail.com>) declareVars builder b emitBlock builder b LLVM.positionBuilderAtEnd builder oldBB -- reset state partial def emitUnreachable (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do let retty ← LLVM.voidType llvmctx let argtys := #[] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty "lean_internal_panic_unreachable" argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[] let _ ← LLVM.buildUnreachable builder partial def emitBlock (builder : LLVM.Builder llvmctx) (b : FnBody) : M llvmctx Unit := do match b with | FnBody.jdecl j xs v b => emitJDecl builder j xs v emitBlock builder b | d@(FnBody.vdecl x t v b) => do let llvmctx ← read if isTailCallTo llvmctx.mainFn d then emitTailCall builder llvmctx.mainFn v else emitVDecl builder x t v emitBlock builder b | FnBody.inc x n c p b => unless p do emitInc builder x n c emitBlock builder b | FnBody.dec x n c p b => unless p do emitDec builder x n c emitBlock builder b | FnBody.del x b => emitDel builder x; emitBlock builder b | FnBody.setTag x i b => emitSetTag builder x i; emitBlock builder b | FnBody.set x i y b => emitSet builder x i y; emitBlock builder b | FnBody.uset x i y b => emitUSet builder x i y; emitBlock builder b | FnBody.sset x i o y t b => emitSSet builder x i o y t; emitBlock builder b | FnBody.mdata _ b => emitBlock builder b | FnBody.ret x => do let (_xty, xv) ← emitArgVal builder x "ret_val" let _ ← LLVM.buildRet builder xv | FnBody.case _ x xType alts => emitCase builder x xType alts | FnBody.jmp j xs => emitJmp builder j xs | FnBody.unreachable => emitUnreachable builder partial def emitFnBody (builder : LLVM.Builder llvmctx) (b : FnBody) : M llvmctx Unit := do declareVars builder b emitBlock builder b end def emitFnArgs (builder : LLVM.Builder llvmctx) (needsPackedArgs? : Bool) (llvmfn : LLVM.Value llvmctx) (params : Array Param) : M llvmctx Unit := do if needsPackedArgs? then do let argsp ← LLVM.getParam llvmfn 0 -- lean_object **args for i in List.range params.size do let param := params[i]! -- argsi := (args + i) let argsi ← LLVM.buildGEP2 builder (← LLVM.voidPtrType llvmctx) argsp #[← constIntUnsigned i] s!"packed_arg_{i}_slot" let llvmty ← toLLVMType param.ty -- pv := *(argsi) = *(args + i) let pv ← LLVM.buildLoad2 builder llvmty argsi -- slot for arg[i] which is always void* ? let alloca ← LLVM.buildAlloca builder llvmty s!"arg_{i}" LLVM.buildStore builder pv alloca addVartoState params[i]!.x alloca llvmty else let n ← LLVM.countParams llvmfn for i in (List.range n.toNat) do let llvmty ← toLLVMType params[i]!.ty let alloca ← LLVM.buildAlloca builder llvmty s!"arg_{i}" let arg ← LLVM.getParam llvmfn (UInt64.ofNat i) let _ ← LLVM.buildStore builder arg alloca addVartoState params[i]!.x alloca llvmty def emitDeclAux (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) (d : Decl) : M llvmctx Unit := do let env ← getEnv let (_, jpMap) := mkVarJPMaps d withReader (fun llvmctx => { llvmctx with jpMap := jpMap }) do unless hasInitAttr env d.name do match d with | .fdecl (f := f) (xs := xs) (type := t) (body := b) .. => let baseName ← toCName f let name := if xs.size > 0 then baseName else "_init_" ++ baseName let retty ← toLLVMType t let mut argtys := #[] let needsPackedArgs? := xs.size > closureMaxArgs && isBoxedName d.name if needsPackedArgs? then argtys := #[← LLVM.pointerType (← LLVM.voidPtrType llvmctx)] else for x in xs do argtys := argtys.push (← toLLVMType x.ty) let fnty ← LLVM.functionType retty argtys (isVarArg := false) let llvmfn ← LLVM.getOrAddFunction mod name fnty -- set linkage and visibility -- TODO: consider refactoring these into a separate concept (e.g. 'setLinkageAndVisibility') -- Find the spots where this refactor needs to happen by grepping for 'LEAN_EXPORT' -- in the C backend if xs.size == 0 then LLVM.setVisibility llvmfn LLVM.Visibility.hidden -- "static " else LLVM.setDLLStorageClass llvmfn LLVM.DLLStorageClass.export -- LEAN_EXPORT: make symbol visible to the interpreter withReader (fun llvmctx => { llvmctx with mainFn := f, mainParams := xs }) do set { var2val := default, jp2bb := default : EmitLLVM.State llvmctx } -- flush variable map let bb ← LLVM.appendBasicBlockInContext llvmctx llvmfn "entry" LLVM.positionBuilderAtEnd builder bb emitFnArgs builder needsPackedArgs? llvmfn xs emitFnBody builder b pure () | _ => pure () def emitDecl (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) (d : Decl) : M llvmctx Unit := do let d := d.normalizeIds -- ensure we don't have gaps in the variable indices try emitDeclAux mod builder d return () catch err => throw (s!"emitDecl:\ncompiling:\n{d}\nerr:\n{err}\n") def emitFns (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do let env ← getEnv let decls := getDecls env decls.reverse.forM (emitDecl mod builder) def callIODeclInitFn (builder : LLVM.Builder llvmctx) (initFnName : String) (world : LLVM.Value llvmctx): M llvmctx (LLVM.Value llvmctx) := do let retty ← LLVM.voidPtrType llvmctx let argtys := #[← LLVM.voidPtrType llvmctx] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty initFnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[world] def callPureDeclInitFn (builder : LLVM.Builder llvmctx) (initFnName : String) (retty : LLVM.LLVMType llvmctx): M llvmctx (LLVM.Value llvmctx) := do let argtys := #[] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty initFnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[] def emitDeclInit (builder : LLVM.Builder llvmctx) (parentFn : LLVM.Value llvmctx) (d : Decl) : M llvmctx Unit := do let env ← getEnv if isIOUnitInitFn env d.name then do let world ← callLeanIOMkWorld builder let resv ← callIODeclInitFn builder (← toCName d.name) world let err? ← callLeanIOResultIsError builder resv "is_error" buildIfThen_ builder s!"init_{d.name}_isError" err? (fun builder => do let _ ← LLVM.buildRet builder resv pure ShouldForwardControlFlow.no) -- TODO (bollu) : emit lean_dec_ref. For now, it does not matter. else if d.params.size == 0 then match getInitFnNameFor? env d.name with | some initFn => let llvmty ← toLLVMType d.resultType let dslot ← LLVM.getOrAddGlobal (← getLLVMModule) (← toCName d.name) llvmty LLVM.setInitializer dslot (← LLVM.getUndef llvmty) let initBB ← builderAppendBasicBlock builder s!"do_{d.name}_init" let restBB ← builderAppendBasicBlock builder s!"post_{d.name}_init" let checkBuiltin? := getBuiltinInitFnNameFor? env d.name |>.isSome if checkBuiltin? then -- `builtin` is set to true if the initializer is part of the executable, -- and not loaded dynamically. let builtinParam ← LLVM.getParam parentFn 0 let cond ← buildLeanBoolTrue? builder builtinParam "is_builtin_true" let _ ← LLVM.buildCondBr builder cond initBB restBB else let _ ← LLVM.buildBr builder initBB LLVM.positionBuilderAtEnd builder initBB let world ← callLeanIOMkWorld builder let resv ← callIODeclInitFn builder (← toCName initFn) world let err? ← callLeanIOResultIsError builder resv s!"{d.name}_is_error" buildIfThen_ builder s!"init_{d.name}_isError" err? (fun builder => do let _ ← LLVM.buildRet builder resv pure ShouldForwardControlFlow.no) if d.resultType.isScalar then let dval ← callLeanIOResultGetValue builder resv s!"{d.name}_res" let dval ← callUnboxForType builder d.resultType dval LLVM.buildStore builder dval dslot else let dval ← callLeanIOResultGetValue builder resv s!"{d.name}_res" LLVM.buildStore builder dval dslot callLeanMarkPersistentFn builder dval let _ ← LLVM.buildBr builder restBB LLVM.positionBuilderAtEnd builder restBB | none => do let llvmty ← toLLVMType d.resultType let dslot ← LLVM.getOrAddGlobal (← getLLVMModule) (← toCName d.name) llvmty LLVM.setInitializer dslot (← LLVM.getUndef llvmty) let dval ← callPureDeclInitFn builder (← toCInitName d.name) (← toLLVMType d.resultType) LLVM.buildStore builder dval dslot if d.resultType.isObj then callLeanMarkPersistentFn builder dval def callModInitFn (builder : LLVM.Builder llvmctx) (modName : Name) (input world : LLVM.Value llvmctx) (retName : String): M llvmctx (LLVM.Value llvmctx) := do let fnName := mkModuleInitializationFunctionName modName let retty ← LLVM.voidPtrType llvmctx let argtys := #[ (← LLVM.i8Type llvmctx), (← LLVM.voidPtrType llvmctx)] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[input, world] retName def emitInitFn (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do let env ← getEnv let modName ← getModName let initFnTy ← LLVM.functionType (← LLVM.voidPtrType llvmctx) #[ (← LLVM.i8Type llvmctx), (← LLVM.voidPtrType llvmctx)] (isVarArg := false) let initFn ← LLVM.getOrAddFunction mod (mkModuleInitializationFunctionName modName) initFnTy LLVM.setDLLStorageClass initFn LLVM.DLLStorageClass.export -- LEAN_EXPORT let entryBB ← LLVM.appendBasicBlockInContext llvmctx initFn "entry" LLVM.positionBuilderAtEnd builder entryBB let ginit?ty := ← LLVM.i1Type llvmctx let ginit?slot ← LLVM.getOrAddGlobal mod (modName.mangle ++ "_G_initialized") ginit?ty LLVM.setVisibility ginit?slot LLVM.Visibility.hidden -- static LLVM.setInitializer ginit?slot (← LLVM.constFalse llvmctx) let ginit?v ← LLVM.buildLoad2 builder ginit?ty ginit?slot "init_v" buildIfThen_ builder "isGInitialized" ginit?v (fun builder => do let box0 ← callLeanBox builder (← LLVM.constIntUnsigned llvmctx 0) "box0" let out ← callLeanIOResultMKOk builder box0 "retval" let _ ← LLVM.buildRet builder out pure ShouldForwardControlFlow.no) LLVM.buildStore builder (← LLVM.constTrue llvmctx) ginit?slot env.imports.forM fun import_ => do let builtin ← LLVM.getParam initFn 0 let world ← callLeanIOMkWorld builder let res ← callModInitFn builder import_.module builtin world ("res_" ++ import_.module.mangle) let err? ← callLeanIOResultIsError builder res ("res_is_error_" ++ import_.module.mangle) buildIfThen_ builder ("IsError" ++ import_.module.mangle) err? (fun builder => do let _ ← LLVM.buildRet builder res pure ShouldForwardControlFlow.no) callLeanDecRef builder res let decls := getDecls env decls.reverse.forM (emitDeclInit builder initFn) let box0 ← callLeanBox builder (← LLVM.constIntUnsigned llvmctx 0) "box0" let out ← callLeanIOResultMKOk builder box0 "retval" let _ ← LLVM.buildRet builder out def callLeanInitialize (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do let fnName := "lean_initialize" let retty ← LLVM.voidType llvmctx let argtys := #[] let fnty ← LLVM.functionType retty argtys let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let _ ← LLVM.buildCall2 builder fnty fn #[] def callLeanInitializeRuntimeModule (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do let fnName := "lean_initialize_runtime_module" let retty ← LLVM.voidType llvmctx let argtys := #[] let fnty ← LLVM.functionType retty argtys let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let _ ← LLVM.buildCall2 builder fnty fn #[] def callLeanSetPanicMessages (builder : LLVM.Builder llvmctx) (enable? : LLVM.Value llvmctx) : M llvmctx Unit := do let fnName := "lean_set_panic_messages" let retty ← LLVM.voidType llvmctx let argtys := #[ ← LLVM.i1Type llvmctx ] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[enable?] def callLeanIOMarkEndInitialization (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do let fnName := "lean_io_mark_end_initialization" let retty ← LLVM.voidType llvmctx let argtys := #[] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[] def callLeanIOResultIsOk (builder : LLVM.Builder llvmctx) (arg : LLVM.Value llvmctx) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_io_result_is_ok" let retty ← LLVM.i1Type llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx ] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[arg] name def callLeanInitTaskManager (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do let fnName := "lean_init_task_manager" let retty ← LLVM.voidType llvmctx let argtys := #[] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[] def callLeanFinalizeTaskManager (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do let fnName := "lean_finalize_task_manager" let retty ← LLVM.voidPtrType llvmctx let argtys := #[] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[] def callLeanUnboxUint32 (builder : LLVM.Builder llvmctx) (v : LLVM.Value llvmctx) (name : String := "") : M llvmctx (LLVM.Value llvmctx) := do let fnName := "lean_unbox_uint32" let retty ← LLVM.i32Type llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx ] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys LLVM.buildCall2 builder fnty fn #[v] name def callLeanIOResultShowError (builder : LLVM.Builder llvmctx) (v : LLVM.Value llvmctx) (name : String := "") : M llvmctx Unit := do let fnName := "lean_io_result_show_error" let retty ← LLVM.voidType llvmctx let argtys := #[ ← LLVM.voidPtrType llvmctx ] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty fnName argtys let fnty ← LLVM.functionType retty argtys let _ ← LLVM.buildCall2 builder fnty fn #[v] name def callLeanMainFn (builder : LLVM.Builder llvmctx) (argv? : Option (LLVM.Value llvmctx)) (world : LLVM.Value llvmctx) (name : String) : M llvmctx (LLVM.Value llvmctx) := do let retty ← LLVM.voidPtrType llvmctx let voidptr ← LLVM.voidPtrType llvmctx let argtys := if argv?.isSome then #[ voidptr, voidptr ] else #[ voidptr ] let fn ← getOrCreateFunctionPrototype (← getLLVMModule) retty leanMainFn argtys let fnty ← LLVM.functionType retty argtys let args := match argv? with | .some argv => #[argv, world] | .none => #[world] LLVM.buildCall2 builder fnty fn args name def emitMainFn (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do let d ← getDecl `main let xs ← match d with | .fdecl (xs := xs) .. => pure xs | _ => throw "Function declaration expected for 'main'" unless xs.size == 2 || xs.size == 1 do throw s!"Invalid main function, main expected to have '2' or '1' arguments, found '{xs.size}' arguments" let env ← getEnv let usesLeanAPI := usesModuleFrom env `Lean let mainTy ← LLVM.functionType (← LLVM.i64Type llvmctx) #[(← LLVM.i64Type llvmctx), (← LLVM.pointerType (← LLVM.voidPtrType llvmctx))] let main ← LLVM.getOrAddFunction mod "main" mainTy let entry ← LLVM.appendBasicBlockInContext llvmctx main "entry" LLVM.positionBuilderAtEnd builder entry /- #if defined(WIN32) || defined(_WIN32) SetErrorMode(SEM_FAILCRITICALERRORS); #endif -/ let inty ← LLVM.voidPtrType llvmctx let inslot ← LLVM.buildAlloca builder (← LLVM.pointerType inty) "in" let resty ← LLVM.voidPtrType llvmctx let res ← LLVM.buildAlloca builder (← LLVM.pointerType resty) "res" if usesLeanAPI then callLeanInitialize builder else callLeanInitializeRuntimeModule builder /- We disable panic messages because they do not mesh well with extracted closed terms. See issue #534. We can remove this workaround after we implement issue #467. -/ callLeanSetPanicMessages builder (← LLVM.constFalse llvmctx) let world ← callLeanIOMkWorld builder let resv ← callModInitFn builder (← getModName) (← LLVM.constInt8 llvmctx 1) world ((← getModName).toString ++ "_init_out") let _ ← LLVM.buildStore builder resv res callLeanSetPanicMessages builder (← LLVM.constTrue llvmctx) callLeanIOMarkEndInitialization builder let resv ← LLVM.buildLoad2 builder resty res "resv" let res_is_ok ← callLeanIOResultIsOk builder resv "res_is_ok" buildIfThen_ builder "resIsOkBranches" res_is_ok (fun builder => do -- then clause of the builder) callLeanDecRef builder resv callLeanInitTaskManager builder if xs.size == 2 then let inv ← callLeanBox builder (← LLVM.constInt (← LLVM.size_tType llvmctx) 0) "inv" let _ ← LLVM.buildStore builder inv inslot let ity ← LLVM.size_tType llvmctx let islot ← LLVM.buildAlloca builder ity "islot" let argcval ← LLVM.getParam main 0 let argvval ← LLVM.getParam main 1 LLVM.buildStore builder argcval islot buildWhile_ builder "argv" (condcodegen := fun builder => do let iv ← LLVM.buildLoad2 builder ity islot "iv" let i_gt_1 ← LLVM.buildICmp builder LLVM.IntPredicate.UGT iv (← constIntUnsigned 1) "i_gt_1" return i_gt_1) (bodycodegen := fun builder => do let iv ← LLVM.buildLoad2 builder ity islot "iv" let iv_next ← LLVM.buildSub builder iv (← constIntUnsigned 1) "iv.next" LLVM.buildStore builder iv_next islot let nv ← callLeanAllocCtor builder 1 2 0 "nv" let argv_i_next_slot ← LLVM.buildGEP2 builder (← LLVM.voidPtrType llvmctx) argvval #[iv_next] "argv.i.next.slot" let argv_i_next_val ← LLVM.buildLoad2 builder (← LLVM.voidPtrType llvmctx) argv_i_next_slot "argv.i.next.val" let argv_i_next_val_str ← callLeanMkString builder argv_i_next_val "arg.i.next.val.str" callLeanCtorSet builder nv (← constIntUnsigned 0) argv_i_next_val_str let inv ← LLVM.buildLoad2 builder inty inslot "inv" callLeanCtorSet builder nv (← constIntUnsigned 1) inv LLVM.buildStore builder nv inslot) let world ← callLeanIOMkWorld builder let inv ← LLVM.buildLoad2 builder inty inslot "inv" let resv ← callLeanMainFn builder (argv? := .some inv) (world := world) "resv" let _ ← LLVM.buildStore builder resv res pure ShouldForwardControlFlow.yes else let world ← callLeanIOMkWorld builder let resv ← callLeanMainFn builder (argv? := .none) (world := world) "resv" let _ ← LLVM.buildStore builder resv res pure ShouldForwardControlFlow.yes ) -- `IO _` let retTy := env.find? `main |>.get! |>.type |>.getForallBody -- either `UInt32` or `(P)Unit` let retTy := retTy.appArg! -- finalize at least the task manager to avoid leak sanitizer false positives -- from tasks outliving the main thread callLeanFinalizeTaskManager builder let resv ← LLVM.buildLoad2 builder resty res "resv" let res_is_ok ← callLeanIOResultIsOk builder resv "res_is_ok" buildIfThenElse_ builder "res.is.ok" res_is_ok (fun builder => -- then builder if retTy.constName? == some ``UInt32 then do let resv ← LLVM.buildLoad2 builder resty res "resv" let retv ← callLeanUnboxUint32 builder (← callLeanIOResultGetValue builder resv "io_val") "retv" let retv ← LLVM.buildSext builder retv (← LLVM.i64Type llvmctx) "retv_sext" callLeanDecRef builder resv let _ ← LLVM.buildRet builder retv pure ShouldForwardControlFlow.no else do callLeanDecRef builder resv let _ ← LLVM.buildRet builder (← LLVM.constInt64 llvmctx 0) pure ShouldForwardControlFlow.no ) (fun builder => do -- else builder let resv ← LLVM.buildLoad2 builder resty res "resv" callLeanIOResultShowError builder resv callLeanDecRef builder resv let _ ← LLVM.buildRet builder (← LLVM.constInt64 llvmctx 1) pure ShouldForwardControlFlow.no) -- at the merge let _ ← LLVM.buildUnreachable builder def hasMainFn : M llvmctx Bool := do let env ← getEnv let decls := getDecls env return decls.any (fun d => d.name == `main) def emitMainFnIfNeeded (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do if (← hasMainFn) then emitMainFn mod builder def main : M llvmctx Unit := do emitFnDecls let builder ← LLVM.createBuilderInContext llvmctx emitFns (← getLLVMModule) builder emitInitFn (← getLLVMModule) builder emitMainFnIfNeeded (← getLLVMModule) builder end EmitLLVM def getLeanHBcPath : IO System.FilePath := do return (← getLibDir (← getBuildDir)) / "lean.h.bc" def optimizeLLVMModule (mod : LLVM.Module ctx) : IO Unit := do let pm ← LLVM.createPassManager let pmb ← LLVM.createPassManagerBuilder pmb.setOptLevel 3 pmb.populateModulePassManager pm LLVM.runPassManager pm mod LLVM.disposePassManager pm LLVM.disposePassManagerBuilder pmb /-- Get the names of all global symbols in the module -/ partial def getModuleGlobals (mod : LLVM.Module llvmctx) : IO (Array (LLVM.Value llvmctx)) := do let rec go (v : LLVM.Value llvmctx) (acc : Array (LLVM.Value llvmctx)) : IO (Array (LLVM.Value llvmctx)) := do if v.isNull then return acc else go (← LLVM.getNextGlobal v) (acc.push v) go (← LLVM.getFirstGlobal mod) #[] /-- Get the names of all global functions in the module -/ partial def getModuleFunctions (mod : LLVM.Module llvmctx) : IO (Array (LLVM.Value llvmctx)) := do let rec go (v : LLVM.Value llvmctx) (acc : Array (LLVM.Value llvmctx)) : IO (Array (LLVM.Value llvmctx)) := do if v.isNull then return acc else go (← LLVM.getNextFunction v) (acc.push v) go (← LLVM.getFirstFunction mod) #[] /-- `emitLLVM` is the entrypoint for the lean shell to code generate LLVM. -/ @[export lean_ir_emit_llvm] def emitLLVM (env : Environment) (modName : Name) (filepath : String) (tripleStr? : Option String) : IO Unit := do LLVM.llvmInitializeTargetInfo let llvmctx ← LLVM.createContext let module ← LLVM.createModule llvmctx modName.toString let emitLLVMCtx : EmitLLVM.Context llvmctx := {env := env, modName := modName, llvmmodule := module} let initState := { var2val := default, jp2bb := default : EmitLLVM.State llvmctx} let out? ← ((EmitLLVM.main (llvmctx := llvmctx)).run initState).run emitLLVMCtx match out? with | .ok _ => do let membuf ← LLVM.createMemoryBufferWithContentsOfFile (← getLeanHBcPath).toString let modruntime ← LLVM.parseBitcode llvmctx membuf /- It is important that we extract the names here because pointers into modruntime get invalidated by linkModules -/ let runtimeGlobals ← (← getModuleGlobals modruntime).mapM (·.getName) let filter func := do -- | Do not insert internal linkage for -- intrinsics such as `@llvm.umul.with.overflow.i64` which clang generates, and also -- for declarations such as `lean_inc_ref_cold` which are externally defined. if (← LLVM.isDeclaration func) then return none else return some (← func.getName) let runtimeFunctions ← (← getModuleFunctions modruntime).filterMapM filter LLVM.linkModules (dest := emitLLVMCtx.llvmmodule) (src := modruntime) -- Mark every global and function as having internal linkage. for name in runtimeGlobals do let some global ← LLVM.getNamedGlobal emitLLVMCtx.llvmmodule name | throw <| IO.Error.userError s!"ERROR: linked module must have global from runtime module: '{name}'" LLVM.setLinkage global LLVM.Linkage.internal for name in runtimeFunctions do let some fn ← LLVM.getNamedFunction emitLLVMCtx.llvmmodule name | throw <| IO.Error.userError s!"ERROR: linked module must have function from runtime module: '{name}'" LLVM.setLinkage fn LLVM.Linkage.internal optimizeLLVMModule emitLLVMCtx.llvmmodule LLVM.writeBitcodeToFile emitLLVMCtx.llvmmodule filepath let tripleStr := tripleStr?.getD (← LLVM.getDefaultTargetTriple) let target ← LLVM.getTargetFromTriple tripleStr let cpu := "generic" let features := "" let targetMachine ← LLVM.createTargetMachine target tripleStr cpu features let codegenType := LLVM.CodegenFileType.ObjectFile LLVM.targetMachineEmitToFile targetMachine emitLLVMCtx.llvmmodule (filepath ++ ".o") codegenType LLVM.disposeModule emitLLVMCtx.llvmmodule LLVM.disposeTargetMachine targetMachine | .error err => throw (IO.Error.userError err) end Lean.IR
43769ae1adc93cfe45314a6799a912b63471eefb
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/for_mathlib/order.lean
847837dcb310185300845b46238f6b28f6687839
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,412
lean
import data.fintype.basic open_locale classical lemma exists_le_finset {α : Type*} [inhabited α] [semilattice_inf α] (G : finset α) : ∃ j : α, ∀ g ∈ G, j ≤ g := begin by_cases h : G.nonempty, { exact ⟨finset.inf' G h id, λ g, finset.inf'_le _⟩ }, { exact ⟨default α, λ g hg, false.elim $ h ⟨_, hg⟩⟩ } end lemma Inter_eq {α β : Type*} [inhabited α] [fintype β] [semilattice_inf α] (i : α) (f : Π (a : α) (ha : a ≤ i), set β) (hf : ∀ (a b : α) (ha : a ≤ i) (hb : b ≤ i) (h : a ≤ b), f a ha ≤ f b hb) : (∃ (j : α) (hj : j ≤ i), (⋂ (k : α) (hk : k ≤ i), f k hk) = f j hj) := begin suffices : (∃ (j : α) (hj : j ≤ i), ∀ (k : α) (hk : k ≤ i), f j hj ≤ f k hk), { rcases this with ⟨j,hj,h⟩, use j, use hj, refine le_antisymm _ _, { refine set.sInter_subset_of_mem ⟨j, _⟩, tidy }, { rintros x hx _ ⟨k,rfl⟩, rintro _ ⟨hk,rfl⟩, apply h _ _ hx } }, let BB := {S : set β | ∃ (e : α) (he : e ≤ i), S = f e he }, let FF : BB → α := λ ee, classical.some ee.2, have hFF : ∀ S : BB, FF S ≤ i := λ S, (classical.some_spec S.2).some, have hFF' : ∀ S : BB, (S : set β) = f (FF S) (hFF S) := λ S, (classical.some_spec S.2).some_spec, haveI : fintype BB := fintype.of_injective (λ S : BB, S.1) (by tidy), let GG := (finset.univ : finset BB).image FF, obtain ⟨j0,hj0⟩ := exists_le_finset GG, use [j0 ⊓ i, inf_le_right], intros k hk, have : ∃ (e : α) (he : e ≤ i) (heFF : e ∈ GG), f k hk = f e he, { let T : BB := ⟨f k hk, k, hk, rfl⟩, use [FF T, hFF _], split, { erw finset.mem_image, use T, simp }, { rw ← hFF', refl, } }, obtain ⟨e,he,heFF,hhe⟩ := this, rw hhe, exact hf _ _ _ _ (le_trans inf_le_left (hj0 _ heFF)), end lemma eventually_constant {α β : Type*} [inhabited α] [fintype β] [semilattice_inf α] (i : α) (f : Π (a : α) (ha : a ≤ i), set β) (hf : ∀ (a b : α) (ha : a ≤ i) (hb : b ≤ i) (h : a ≤ b), f a ha ≤ f b hb) : (∃ (j : α) (hj : j ≤ i), ∀ (k : α) (hk : k ≤ j), f k (le_trans hk hj) = f j hj) := begin let S := ⋂ (k : α) (hk : k ≤ i), f k hk, obtain ⟨j0,hj0,h⟩ := Inter_eq i f hf, use [j0, hj0], intros e he, refine le_antisymm (hf _ _ _ _ he) _, rw ← h, rintros x hx, refine hx _ ⟨e, _⟩, tidy end
52b52f6c11f56b402dabc51e3e2d98e6281439b1
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/set_theory/cardinal.lean
5d23f57ea704921978c937a5798cabd29afe5019
[ "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
45,519
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, Mario Carneiro -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic: addition, multiplication, power, cardinal successor, minimum, supremum, infinitary sums and products ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. There is a lift operation lifting cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/ordinal.lean`, because concepts from that file are used in the proof. ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nonzero cardinal.{u} := { zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) @[simp] lemma pow_cast_right (κ : cardinal.{u}) : ∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n | 0 := by simp | (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right] section order_properties open sum theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } instance : canonically_ordered_add_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.injective h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 := by { rw [←le_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a := begin apply quotient.induction_on a, intro α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩, end /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega := ⟨λ h, ⟨lt_of_le_of_lt (le_add_right _ _) h, lt_of_le_of_lt (le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (mul_le_mul ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < omega ↔ a < omega ∧ b < omega := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_subsingleton_and_nonempty {α : Type*} : mk α = 1 ↔ (subsingleton α ∧ nonempty α) := calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, ne_zero_iff_nonempty] end theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩, λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma mk_int : mk ℤ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk ℕ+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, classical.not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : mk (subtype p) ≤ mk (subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ := begin split, { intro h, have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h], refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _), rcases cardinal.eq.mp h2 with ⟨f, _⟩, cases f ⟨_, hx⟩ }, { intro, convert mk_emptyc _ } end theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α := quotient.sound ⟨(equiv.set.range f h).symm⟩ lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union H⟩ lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := quotient.sound ⟨equiv.set.sum_compl s⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : mk s ≤ mk α := mk_subtype_le s lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : mk {a : α // p (e a)} = mk {b : β // p b} := quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩ lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : mk (f ⁻¹' s) ≤ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal
6b155a37098434971b302460cb036303d9b837b5
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-numbertheory-33.lean
840f218ad091623e74120476527fa9bf85ab8a6c
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
260
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.nat.basic example (n : ℕ) (h₀ : n < 398) (h₁ : (n * 7) % 398 = 1 ) : n = 57 := begin sorry end
cf32b2484d27afd96ff266cb9b612b48ae74ea18
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/class_number/admissible_abs.lean
cd1b7993a5c406c2bb2c7c6be7625d76019a7aea
[ "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,579
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.algebra.basic import number_theory.class_number.admissible_absolute_value /-! # Admissible absolute value on the integers This file defines an admissible absolute value `absolute_value.abs_is_admissible` which we use to show the class number of the ring of integers of a number field is finite. ## Main results * `absolute_value.abs_is_admissible` shows the "standard" absolute value on `ℤ`, mapping negative `x` to `-x`, is admissible. -/ namespace absolute_value open int /-- We can partition a finite family into `partition_card ε` sets, such that the remainders in each set are close together. -/ lemma exists_partition_int (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : ℤ} (hb : b ≠ 0) (A : fin n → ℤ) : ∃ (t : fin n → fin ⌈1 / ε⌉₊), ∀ i₀ i₁, t i₀ = t i₁ → ↑(abs (A i₁ % b - A i₀ % b)) < abs b • ε := begin have hb' : (0 : ℝ) < ↑(abs b) := int.cast_pos.mpr (abs_pos.mpr hb), have hbε : 0 < abs b • ε, { rw algebra.smul_def, exact mul_pos hb' hε }, have hfloor : ∀ i, 0 ≤ floor ((A i % b : ℤ) / (abs b • ε) : ℝ), { intro i, exact floor_nonneg.mpr (div_nonneg (cast_nonneg.mpr (mod_nonneg _ hb)) hbε.le) }, refine ⟨λ i, ⟨nat_abs (floor ((A i % b : ℤ) / (abs b • ε) : ℝ)), _⟩, _⟩, { rw [← coe_nat_lt, nat_abs_of_nonneg (hfloor i), floor_lt], apply lt_of_lt_of_le _ (nat.le_ceil _), rw [algebra.smul_def, ring_hom.eq_int_cast, ← div_div, div_lt_div_right hε, div_lt_iff hb', one_mul, cast_lt], exact int.mod_lt _ hb }, intros i₀ i₁ hi, have hi : (⌊↑(A i₀ % b) / abs b • ε⌋.nat_abs : ℤ) = ⌊↑(A i₁ % b) / abs b • ε⌋.nat_abs := congr_arg (coe : ℕ → ℤ) (subtype.mk_eq_mk.mp hi), rw [nat_abs_of_nonneg (hfloor i₀), nat_abs_of_nonneg (hfloor i₁)] at hi, have hi := abs_sub_lt_one_of_floor_eq_floor hi, rw [abs_sub_comm, ← sub_div, abs_div, abs_of_nonneg hbε.le, div_lt_iff hbε, one_mul] at hi, rwa [int.cast_abs, int.cast_sub] end /-- `abs : ℤ → ℤ` is an admissible absolute value -/ noncomputable def abs_is_admissible : is_admissible absolute_value.abs := { card := λ ε, ⌈1 / ε⌉₊, exists_partition' := λ n ε hε b hb, exists_partition_int n hε hb, .. absolute_value.abs_is_euclidean } noncomputable instance : inhabited (is_admissible absolute_value.abs) := ⟨abs_is_admissible⟩ end absolute_value
5a8660cff45337b69670699abf108ba81e5b3f95
367134ba5a65885e863bdc4507601606690974c1
/src/control/bitraversable/basic.lean
b7299fb4a2e8b1d74e7599974218a738d8910675
[ "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
2,795
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import control.bifunctor import control.traversable.basic /-! # Bitraversable type class Type class for traversing bifunctors. The concepts and laws are taken from <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> Simple examples of `bitraversable` are `prod` and `sum`. A more elaborate example is to define an a-list as: ``` def alist (key val : Type) := list (key × val) ``` Then we can use `f : key → io key'` and `g : val → io val'` to manipulate the `alist`'s key and value respectively with `bitraverse f g : alist key val → io (alist key' val')` ## Main definitions * bitraversable - exposes the `bitraverse` function * is_lawful_bitraversable - laws similar to is_lawful_traversable ## Tags traversable bitraversable iterator functor bifunctor applicative -/ universes u class bitraversable (t : Type u → Type u → Type u) extends bifunctor t := (bitraverse : Π {m : Type u → Type u} [applicative m] {α α' β β'}, (α → m α') → (β → m β') → t α β → m (t α' β')) export bitraversable ( bitraverse ) def bisequence {t m} [bitraversable t] [applicative m] {α β} : t (m α) (m β) → m (t α β) := bitraverse id id open functor class is_lawful_bitraversable (t : Type u → Type u → Type u) [bitraversable t] extends is_lawful_bifunctor t := (id_bitraverse : ∀ {α β} (x : t α β), bitraverse id.mk id.mk x = id.mk x ) (comp_bitraverse : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α α' β β' γ γ'} (f : β → F γ) (f' : β' → F γ') (g : α → G β) (g' : α' → G β') (x : t α α'), bitraverse (comp.mk ∘ map f ∘ g) (comp.mk ∘ map f' ∘ g') x = comp.mk (bitraverse f f' <$> bitraverse g g' x) ) (bitraverse_eq_bimap_id : ∀ {α α' β β'} (f : α → β) (f' : α' → β') (x : t α α'), bitraverse (id.mk ∘ f) (id.mk ∘ f') x = id.mk (bimap f f' x)) (binaturality : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (η : applicative_transformation F G) {α α' β β'} (f : α → F β) (f' : α' → F β') (x : t α α'), η (bitraverse f f' x) = bitraverse (@η _ ∘ f) (@η _ ∘ f') x) export is_lawful_bitraversable ( id_bitraverse comp_bitraverse bitraverse_eq_bimap_id ) open is_lawful_bitraversable attribute [higher_order bitraverse_id_id] id_bitraverse attribute [higher_order bitraverse_comp] comp_bitraverse attribute [higher_order] binaturality bitraverse_eq_bimap_id export is_lawful_bitraversable (bitraverse_id_id bitraverse_comp)
f6e965fc2d761d0c520ce8160df2cdf3b6a9695e
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/lens.lean
f307e4dd73ddbf00aedf22f36683f0ed15b4c40b
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,098
lean
-- A minimal implementation of lenses. universe variables u v -- This tactic proves (∀v s, get (set v s) = v by case splitting on s -- and using reflexivity. meta def lens.get_set_tactic : tactic unit := do tactic.intro `v, e ← tactic.intro `s, tactic.cases e [], tactic.reflexivity -- This tactic proves (∀v s, set (get s) = s by case splitting on s -- and using reflexivity. meta def lens.set_get_tactic : tactic unit := do e ← tactic.intro `s, tactic.cases e [], tactic.reflexivity -- This tactic proves (∀u v s, set u (set v s) = set u s by case splitting on s -- and using reflexivity. meta def lens.set_set_tactic : tactic unit := do tactic.intro `u, tactic.intro `v, e ← tactic.intro `s, tactic.cases e [], tactic.reflexivity -- A lens is a structure with a getter, setter, and axioms about their effect. structure lens (S : Type u) (α : Type v) := (get : S → α) (set : α → S → S) (get_set : ∀ (v : α) (s : S), get (set v s) = v . lens.get_set_tactic) (set_get : ∀ (s : S), set (get s) s = s . lens.set_get_tactic) (set_set : ∀ (u v : α) (s : S), set u (set v s) = set u s . lens.set_set_tactic) @[simp] lemma get_set_cancel {S : Type u} {α : Type v} (l : lens S α) : ∀ (v : α) (s : S), l.get (l.set v s) = v := l.get_set @[simp] lemma set_get_cancel {S : Type u} {α : Type v} (l : lens S α) : ∀ (s : S), l.set (l.get s) s = s := l.set_get @[simp] lemma set_set_cancel {S : Type u} {α : Type v} (l : lens S α) : ∀ (u v : α) (s : S), l.set u (l.set v s) = l.set u s := l.set_set namespace lens variables { s t : Type u } variables { a b : Type v } -- This applies a function to the value of a lens on an object and updates the state. def over (l : lens s a) (f : a → a) (x : s) : s := lens.set l (f (lens.get l x)) x end lens infixr ` .~ `:4 := lens.set infixr ` %~ `:4 := lens.over @[reducible] def call {a b} : a → (a → b) → b := λx f, f x infixl ` & `:2 := call @[simp] theorem call_elim {α : Type u} {β : Type v} (f : α → β) (x : α) : (x & f) = f x := by simp [call]
7a762465a113c1ff70ef057a53aeba311a519845
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/homology/homotopy.lean
302d76301fcc26f2364a660329168ffc8fee2f7d
[ "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
17,015
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.homology.additive /-! # Chain homotopies We define chain homotopies, and prove that homotopic chain maps induce the same map on homology. -/ universes v u open_locale classical noncomputable theory open category_theory category_theory.limits homological_complex variables {ι : Type*} variables {V : Type u} [category.{v} V] [preadditive V] variables {c : complex_shape ι} {C D E : homological_complex V c} variables (f g : C ⟶ D) (h k : D ⟶ E) (i : ι) section /-- The composition of `C.d i i' ≫ f i' i` if there is some `i'` coming after `i`, and `0` otherwise. -/ def d_next (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X i ⟶ D.X i) := add_monoid_hom.mk' (λ f, match c.next i with | none := 0 | some ⟨i',w⟩ := C.d i i' ≫ f i' i end) begin intros f g, rcases c.next i with _|⟨i',w⟩, exact (zero_add _).symm, exact preadditive.comp_add _ _ _ _ _ _, end /-- `f i' i` if `i'` comes after `i`, and 0 if there's no such `i'`. Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next` to see that `d_next` factors through `C.d_from i`. -/ def from_next [has_zero_object V] (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X_next i ⟶ D.X i) := add_monoid_hom.mk' (λ f, match c.next i with | none := 0 | some ⟨i',w⟩ := (C.X_next_iso w).hom ≫ f i' i end) begin intros f g, rcases c.next i with _|⟨i',w⟩, exact (zero_add _).symm, exact preadditive.comp_add _ _ _ _ _ _, end lemma d_next_eq_d_from_from_next [has_zero_object V] (f : Π i j, C.X i ⟶ D.X j) (i : ι) : d_next i f = C.d_from i ≫ from_next i f := begin dsimp [d_next, from_next], rcases c.next i with ⟨⟩|⟨⟨i', w⟩⟩; { dsimp [d_next, from_next], simp }, end lemma d_next_eq (f : Π i j, C.X i ⟶ D.X j) {i i' : ι} (w : c.rel i i') : d_next i f = C.d i i' ≫ f i' i := begin dsimp [d_next], rw c.next_eq_some w, refl, end @[simp] lemma d_next_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (i : ι) : d_next i (λ i j, f.f i ≫ g i j) = f.f i ≫ d_next i g := begin dsimp [d_next], rcases c.next i with _|⟨i',w⟩, { exact comp_zero.symm, }, { dsimp [d_next], simp, }, end @[simp] lemma d_next_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (i : ι) : d_next i (λ i j, f i j ≫ g.f j) = d_next i f ≫ g.f i := begin dsimp [d_next], rcases c.next i with _|⟨i',w⟩, { exact zero_comp.symm, }, { dsimp [d_next], simp, }, end /-- The composition of `f j j' ≫ D.d j' j` if there is some `j'` coming before `j`, and `0` otherwise. -/ def prev_d (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X j) := add_monoid_hom.mk' (λ f, match c.prev j with | none := 0 | some ⟨j',w⟩ := f j j' ≫ D.d j' j end) begin intros f g, rcases c.prev j with _|⟨j',w⟩, exact (zero_add _).symm, exact preadditive.add_comp _ _ _ _ _ _, end /-- `f j j'` if `j'` comes after `j`, and 0 if there's no such `j'`. Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next` to see that `d_next` factors through `C.d_from i`. -/ def to_prev [has_zero_object V] (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X_prev j) := add_monoid_hom.mk' (λ f, match c.prev j with | none := 0 | some ⟨j',w⟩ := f j j' ≫ (D.X_prev_iso w).inv end) begin intros f g, rcases c.prev j with _|⟨j',w⟩, exact (zero_add _).symm, exact preadditive.add_comp _ _ _ _ _ _, end lemma prev_d_eq_to_prev_d_to [has_zero_object V] (f : Π i j, C.X i ⟶ D.X j) (j : ι) : prev_d j f = to_prev j f ≫ D.d_to j := begin dsimp [prev_d, to_prev], rcases c.prev j with ⟨⟩|⟨⟨j', w⟩⟩; { dsimp [prev_d, to_prev], simp }, end lemma prev_d_eq (f : Π i j, C.X i ⟶ D.X j) {j j' : ι} (w : c.rel j' j) : prev_d j f = f j j' ≫ D.d j' j := begin dsimp [prev_d], rw c.prev_eq_some w, refl, end @[simp] lemma prev_d_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (j : ι) : prev_d j (λ i j, f.f i ≫ g i j) = f.f j ≫ prev_d j g := begin dsimp [prev_d], rcases c.prev j with _|⟨j',w⟩, { exact comp_zero.symm, }, { dsimp [prev_d, hom.prev], simp, }, end @[simp] lemma to_prev'_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (j : ι) : prev_d j (λ i j, f i j ≫ g.f j) = prev_d j f ≫ g.f j := begin dsimp [prev_d], rcases c.prev j with _|⟨j',w⟩, { exact zero_comp.symm, }, { dsimp [prev_d], simp, }, end /-- A homotopy `h` between chain maps `f` and `g` consists of components `h i j : C.X i ⟶ D.X j` which are zero unless `c.rel j i`, satisfying the homotopy condition. -/ @[ext, nolint has_inhabited_instance] structure homotopy (f g : C ⟶ D) := (hom : Π i j, C.X i ⟶ D.X j) (zero' : ∀ i j, ¬ c.rel j i → hom i j = 0 . obviously) (comm : ∀ i, f.f i = d_next i hom + prev_d i hom + g.f i . obviously') variables {f g} namespace homotopy restate_axiom homotopy.zero' /-- `f` is homotopic to `g` iff `f - g` is homotopic to `0`. -/ def equiv_sub_zero : homotopy f g ≃ homotopy (f - g) 0 := { to_fun := λ h, { hom := λ i j, h.hom i j, zero' := λ i j w, h.zero _ _ w, comm := λ i, by simp [h.comm] }, inv_fun := λ h, { hom := λ i j, h.hom i j, zero' := λ i j w, h.zero _ _ w, comm := λ i, by simpa [sub_eq_iff_eq_add] using h.comm i }, left_inv := by tidy, right_inv := by tidy, } /-- Every chain map is homotopic to itself. -/ @[refl] def refl (f : C ⟶ D) : homotopy f f := { hom := 0, zero' := λ i j w, rfl, comm := λ i, by rw [add_monoid_hom.map_zero, add_monoid_hom.map_zero, zero_add, zero_add] } /-- `f` is homotopic to `g` iff `g` is homotopic to `f`. -/ @[symm] def symm {f g : C ⟶ D} (h : homotopy f g) : homotopy g f := { hom := -h.hom, zero' := λ i j w, by rw [pi.neg_apply, pi.neg_apply, h.zero i j w, neg_zero], comm := λ i, by rw [add_monoid_hom.map_neg, add_monoid_hom.map_neg, h.comm, ← neg_add, ← add_assoc, neg_add_self, zero_add] } /-- homotopy is a transitive relation. -/ @[trans] def trans {e f g : C ⟶ D} (h : homotopy e f) (k : homotopy f g) : homotopy e g := { hom := h.hom + k.hom, zero' := λ i j w, by rw [pi.add_apply, pi.add_apply, h.zero i j w, k.zero i j w, zero_add], comm := λ i, by { rw [add_monoid_hom.map_add, add_monoid_hom.map_add, h.comm, k.comm], abel }, } /-- homotopy is closed under composition (on the right) -/ def comp_right {e f : C ⟶ D} (h : homotopy e f) (g : D ⟶ E) : homotopy (e ≫ g) (f ≫ g) := { hom := λ i j, h.hom i j ≫ g.f j, zero' := λ i j w, by rw [h.zero i j w, zero_comp], comm := λ i, by simp only [h.comm i, d_next_comp_right, preadditive.add_comp, to_prev'_comp_right, comp_f], } /-- homotopy is closed under composition (on the left) -/ def comp_left {f g : D ⟶ E} (h : homotopy f g) (e : C ⟶ D) : homotopy (e ≫ f) (e ≫ g) := { hom := λ i j, e.f i ≫ h.hom i j, zero' := λ i j w, by rw [h.zero i j w, comp_zero], comm := λ i, by simp only [h.comm i, d_next_comp_left, preadditive.comp_add, prev_d_comp_left, comp_f], } /-- a variant of `homotopy.comp_right` useful for dealing with homotopy equivalences. -/ def comp_right_id {f : C ⟶ C} (h : homotopy f (𝟙 C)) (g : C ⟶ D) : homotopy (f ≫ g) g := by { convert h.comp_right g, simp, } /-- a variant of `homotopy.comp_left` useful for dealing with homotopy equivalences. -/ def comp_left_id {f : D ⟶ D} (h : homotopy f (𝟙 D)) (g : C ⟶ D) : homotopy (g ≫ f) g := by { convert h.comp_left g, simp, } /-! `homotopy.mk_inductive` allows us to build a homotopy inductively, so that as we construct each component, we have available the previous two components, and the fact that they satisfy the homotopy condition. To simplify the situation, we only construct homotopies of the form `homotopy e 0`. `homotopy.equiv_sub_zero` can provide the general case. Notice however, that this construction does not have particularly good definitional properties: we have to insert `eq_to_hom` in several places. Hopefully this is okay in most applications, where we only need to have the existence of some homotopy. -/ section mk_inductive variables {P Q : chain_complex V ℕ} @[simp] lemma prev_d_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (j : ℕ) : prev_d j f = f j (j+1) ≫ Q.d _ _ := begin dsimp [prev_d], simp only [chain_complex.prev], refl, end @[simp] lemma d_next_succ_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (i : ℕ) : d_next (i+1) f = P.d _ _ ≫ f i (i+1) := begin dsimp [d_next], simp only [chain_complex.next_nat_succ], refl, end @[simp] lemma d_next_zero_chain_complex (f : Π i j, P.X i ⟶ Q.X j) : d_next 0 f = 0 := begin dsimp [d_next], simp only [chain_complex.next_nat_zero], refl, end variables (e : P ⟶ Q) (zero : P.X 0 ⟶ Q.X 1) (comm_zero : e.f 0 = zero ≫ Q.d 1 0) (one : P.X 1 ⟶ Q.X 2) (comm_one : e.f 1 = P.d 1 0 ≫ zero + one ≫ Q.d 2 1) (succ : ∀ (n : ℕ) (p : Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)), e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1)), Σ' f'' : P.X (n+2) ⟶ Q.X (n+3), e.f (n+2) = P.d (n+2) (n+1) ≫ p.2.1 + f'' ≫ Q.d (n+3) (n+2)) include comm_one comm_zero /-- An auxiliary construction for `mk_inductive`. Here we build by induction a family of diagrams, but don't require at the type level that these successive diagrams actually agree. They do in fact agree, and we then capture that at the type level (i.e. by constructing a homotopy) in `mk_inductive`. At this stage, we don't check the homotopy condition in degree 0, because it "falls off the end", and is easier to treat using `X_next` and `X_prev`, which we do in `mk_inductive_aux₂`. -/ @[simp, nolint unused_arguments] def mk_inductive_aux₁ : Π n, Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)), e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1) | 0 := ⟨zero, one, comm_one⟩ | 1 := ⟨one, (succ 0 ⟨zero, one, comm_one⟩).1, (succ 0 ⟨zero, one, comm_one⟩).2⟩ | (n+2) := ⟨(mk_inductive_aux₁ (n+1)).2.1, (succ (n+1) (mk_inductive_aux₁ (n+1))).1, (succ (n+1) (mk_inductive_aux₁ (n+1))).2⟩ section variable [has_zero_object V] /-- An auxiliary construction for `mk_inductive`. -/ @[simp] def mk_inductive_aux₂ : Π n, Σ' (f : P.X_next n ⟶ Q.X n) (f' : P.X n ⟶ Q.X_prev n), e.f n = P.d_from n ≫ f + f' ≫ Q.d_to n | 0 := ⟨0, zero ≫ (Q.X_prev_iso rfl).inv, by simpa using comm_zero⟩ | (n+1) := let I := mk_inductive_aux₁ e zero comm_zero one comm_one succ n in ⟨(P.X_next_iso rfl).hom ≫ I.1, I.2.1 ≫ (Q.X_prev_iso rfl).inv, by simpa using I.2.2⟩ lemma mk_inductive_aux₃ (i : ℕ) : (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso rfl).hom = (P.X_next_iso rfl).inv ≫ (mk_inductive_aux₂ e zero comm_zero one comm_one succ (i+1)).1 := by rcases i with (_|_|i); { dsimp, simp, } /-- A constructor for a `homotopy e 0`, for `e` a chain map between `ℕ`-indexed chain complexes, working by induction. You need to provide the components of the homotopy in degrees 0 and 1, show that these satisfy the homotopy condition, and then give a construction of each component, and the fact that it satisfies the homotopy condition, using as an inductive hypothesis the data and homotopy condition for the previous two components. -/ def mk_inductive : homotopy e 0 := { hom := λ i j, if h : i + 1 = j then (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso h).hom else 0, zero' := λ i j w, by rwa dif_neg, comm := λ i, begin dsimp, simp only [add_zero], convert (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.2, { rcases i with (_|_|_|i), { dsimp, simp only [d_next_zero_chain_complex, d_from_eq_zero, limits.comp_zero], }, all_goals { simp only [d_next_succ_chain_complex], dsimp, simp only [category.comp_id, category.assoc, iso.inv_hom_id, d_from_comp_X_next_iso_assoc, dite_eq_ite, if_true, eq_self_iff_true]}, }, { cases i, all_goals { simp only [prev_d_chain_complex], dsimp, simp only [category.comp_id, category.assoc, iso.inv_hom_id, X_prev_iso_comp_d_to, dite_eq_ite, if_true, eq_self_iff_true], }, }, end, } end end mk_inductive end homotopy /-- A homotopy equivalence between two chain complexes consists of a chain map each way, and homotopies from the compositions to the identity chain maps. Note that this contains data; arguably it might be more useful for many applications if we truncated it to a Prop. -/ structure homotopy_equiv (C D : homological_complex V c) := (hom : C ⟶ D) (inv : D ⟶ C) (homotopy_hom_inv_id : homotopy (hom ≫ inv) (𝟙 C)) (homotopy_inv_hom_id : homotopy (inv ≫ hom) (𝟙 D)) namespace homotopy_equiv /-- Any complex is homotopy equivalent to itself. -/ @[refl] def refl (C : homological_complex V c) : homotopy_equiv C C := { hom := 𝟙 C, inv := 𝟙 C, homotopy_hom_inv_id := by simp, homotopy_inv_hom_id := by simp, } instance : inhabited (homotopy_equiv C C) := ⟨refl C⟩ /-- Being homotopy equivalent is a symmetric relation. -/ @[symm] def symm {C D : homological_complex V c} (f : homotopy_equiv C D) : homotopy_equiv D C := { hom := f.inv, inv := f.hom, homotopy_hom_inv_id := f.homotopy_inv_hom_id, homotopy_inv_hom_id := f.homotopy_hom_inv_id, } /-- Homotopy equivalence is a transitive relation. -/ @[trans] def trans {C D E : homological_complex V c} (f : homotopy_equiv C D) (g : homotopy_equiv D E) : homotopy_equiv C E := { hom := f.hom ≫ g.hom, inv := g.inv ≫ f.inv, homotopy_hom_inv_id := by simpa using ((g.homotopy_hom_inv_id.comp_right_id f.inv).comp_left f.hom).trans f.homotopy_hom_inv_id, homotopy_inv_hom_id := by simpa using ((f.homotopy_inv_hom_id.comp_right_id g.hom).comp_left g.inv).trans g.homotopy_inv_hom_id, } end homotopy_equiv variables [has_equalizers V] [has_cokernels V] [has_images V] [has_image_maps V] variable [has_zero_object V] /-- Homotopic maps induce the same map on homology. -/ theorem homology_map_eq_of_homotopy (h : homotopy f g) (i : ι) : (homology_functor V c i).map f = (homology_functor V c i).map g := begin dsimp [homology_functor], apply eq_of_sub_eq_zero, ext, simp only [homology.π_map, comp_zero, preadditive.comp_sub], dsimp [kernel_subobject_map], simp_rw [h.comm i], simp only [zero_add, zero_comp, d_next_eq_d_from_from_next, kernel_subobject_arrow_comp_assoc, preadditive.comp_add], rw [←preadditive.sub_comp], simp only [category_theory.subobject.factor_thru_add_sub_factor_thru_right], erw [subobject.factor_thru_of_le (D.boundaries_le_cycles i)], { simp, }, { rw [prev_d_eq_to_prev_d_to, ←category.assoc], apply image_subobject_factors_comp_self, }, end /-- Homotopy equivalent complexes have isomorphic homologies. -/ def homology_obj_iso_of_homotopy_equiv (f : homotopy_equiv C D) (i : ι) : (homology_functor V c i).obj C ≅ (homology_functor V c i).obj D := { hom := (homology_functor V c i).map f.hom, inv := (homology_functor V c i).map f.inv, hom_inv_id' := begin rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_hom_inv_id, category_theory.functor.map_id], end, inv_hom_id' := begin rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_inv_hom_id, category_theory.functor.map_id], end, } end namespace category_theory variables {W : Type*} [category W] [preadditive W] /-- An additive functor takes homotopies to homotopies. -/ @[simps] def functor.map_homotopy (F : V ⥤ W) [F.additive] {f g : C ⟶ D} (h : homotopy f g) : homotopy ((F.map_homological_complex c).map f) ((F.map_homological_complex c).map g) := { hom := λ i j, F.map (h.hom i j), zero' := λ i j w, by { rw [h.zero i j w, F.map_zero], }, comm := λ i, begin have := h.comm i, dsimp [d_next, prev_d] at *, rcases c.next i with _|⟨inext,wn⟩; rcases c.prev i with _|⟨iprev,wp⟩; dsimp [d_next, prev_d] at *; { intro h, simp [h] }, end, } /-- An additive functor preserves homotopy equivalences. -/ @[simps] def functor.map_homotopy_equiv (F : V ⥤ W) [F.additive] (h : homotopy_equiv C D) : homotopy_equiv ((F.map_homological_complex c).obj C) ((F.map_homological_complex c).obj D) := { hom := (F.map_homological_complex c).map h.hom, inv := (F.map_homological_complex c).map h.inv, homotopy_hom_inv_id := begin rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id], exact F.map_homotopy h.homotopy_hom_inv_id, end, homotopy_inv_hom_id := begin rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id], exact F.map_homotopy h.homotopy_inv_hom_id, end } end category_theory
255765282942cfcc4cbadd46e8a344263b03aa99
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/caracteristique_pol/tools.lean
30261a5a6357afa8f8d030730d8cb555ec6cf876
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
12,629
lean
import data.polynomial open finset universes u v variables {R : Type u}[nonzero_comm_ring R] {A : Type v} [fintype A][decidable_eq A] (M : matrix A A R) (N : matrix A A (polynomial R)) namespace tools open polynomial open with_bot notation `Σ` := finset.sum finset.univ open_locale big_operators /-! We start by explaining the strategy. Let : `(s : finset A)(φ :A → polynomial R)(a : A)` `(hyp : ∀ b : A, a ≠ b → degree (φ b) < degree (φ a) )` `(hyp_not_nul : ⊥ < degree (φ a))`: Then `if a ∈ s then (degree (finset.sum s φ ) = degree (φ a))` ` else degree (finset.sum s φ ) < (degree (φ a))` The caracteristic polynomial is constuct as a product over permutation. We analyse each term of the sum. If `σ = id ` then the degree of the polynomial is `card A` else the degre is less (`<`) than `card A` That permit to apply the next lemma. -/ namespace with_bot end with_bot lemma χ_degree_strategy (s : finset A)(φ :A → polynomial R)(a : A) (hyp : ∀ b : A, a ≠ b → degree (φ b) < degree (φ a) ) (hyp_not_nul : ⊥ < degree (φ a)): if a ∈ s then (degree (finset.sum s φ ) = degree (φ a)) else degree (finset.sum s φ ) < (degree (φ a)) := begin apply (finset.induction_on s), { intros, let F := not_mem_empty a, split_ifs, rw finset.sum_empty, rw degree_zero, assumption, }, {{ intros ℓ s hyp_ℓ hyp_rec, let p1 := φ a, let p2 := finset.sum s φ , split_ifs with H, by_cases a = ℓ, { rw sum_insert (by assumption), rw ← h, split_ifs at hyp_rec, { rw h at h_1, trivial, }, { rw add_comm, apply degree_add_eq_of_degree_lt,exact hyp_rec, }, }, { split_ifs at hyp_rec, { rw sum_insert (by assumption),rw ← hyp_rec, apply degree_add_eq_of_degree_lt, rw hyp_rec, exact hyp ℓ h, }, { rw sum_insert (by assumption), let g := mem_of_mem_insert_of_ne H h, trivial, }, }, split_ifs at hyp_rec, { have : a ∈ insert ℓ s, apply mem_insert_of_mem h, trivial, }, { rw sum_insert (by assumption), have : a ≠ ℓ, let g := mem_insert_self ℓ s, intro, rw a_1 at H, trivial, specialize hyp ℓ this, apply lt_of_le_of_lt (degree_add_le (φ ℓ ) p2), apply max_lt (hyp)(hyp_rec), }, }}, end /-- A friend version. -/ lemma proof_strategy.car_pol_degree (φ :A → polynomial R)(a : A) (hyp : ∀ b : A, a ≠ b → degree (φ b) < degree (φ a) ) (hyp_not_nul : ⊥ < degree (φ a)): (degree (Σ φ ) = degree (φ a)) := begin let g := χ_degree_strategy (finset.univ) φ a hyp hyp_not_nul, split_ifs at g, assumption, let h := mem_univ a, trivial, end theorem my_theo (a b : with_bot ℕ ) : a ≤ b → a+1 ≤ b+1 := begin intros, rcases b, intros, rcases a, exact le_refl (none +1), erw le_bot_iff at a_1, rw a_1, refine le_refl _, rcases a, exact bot_le, apply some_le_some.mpr, apply add_le_add, apply some_le_some.mp a_1, exact le_refl 1, end #check with_bot.some_lt_some lemma zero_le_one' : (0 : with_bot ℕ ) ≤ 1 := begin apply coe_le_coe.mpr, exact zero_le_one, end lemma prod_monic (s : finset A)(φ : A → polynomial R) (hyp : ∀ a : A, monic (φ a)) : monic (finset.prod s (λ x : A, φ x)) := begin apply (finset.induction_on s), { erw prod_empty at *, exact leading_coeff_C _, }, { intros ℓ s hyp' hyp_rec, rw finset.prod_insert (by assumption), apply monic_mul, exact hyp ℓ, exact hyp_rec, }, end lemma degree_prod_monic (s : finset A)(φ : A → polynomial R) (hyp_lc : ∀ ℓ : A, monic (φ ℓ )) : degree (finset.prod s (λ x : A, φ x)) = finset.sum s ( λ x : A, degree (φ x)) := begin apply (finset.induction_on s), { rw prod_empty, exact degree_C (one_ne_zero), }, { intros ℓ s hyp' hyp_rec, rw finset.prod_insert (by assumption), rw finset.sum_insert (by assumption), let g := monic_mul (hyp_lc ℓ ) (prod_monic s φ hyp_lc) , rw ← hyp_rec, apply degree_mul_eq', conv_lhs { erw monic.def.mp (hyp_lc ℓ), rw one_mul, erw monic.def.mp (prod_monic s φ hyp_lc), }, exact one_ne_zero, }, end theorem cast_with_bot (a : ℕ ) : nat.cast (a) = (a: with_bot ℕ ) := begin apply (nat.rec_on a), { exact rfl, }, intros ℓ hyp_rec, change _ = ↑ℓ + ↑1, erw ← hyp_rec, exact rfl, end lemma prod_monic_one (s : finset A)(φ : A → polynomial R)(hyp : ∀ ℓ : A, degree(φ ℓ ) = 1 ) (hyp_lc : ∀ ℓ : A, monic(φ ℓ) ) : -- monic ! degree (finset.prod s (λ x : A, φ x)) = card s := begin rw degree_prod_monic s φ hyp_lc, let g := @finset.sum_const _ _ s _ 1, conv_lhs{ apply_congr, skip, rw hyp x, }, rw finset.sum_const, rw add_monoid.smul_one, unfold_coes, rw some_eq_coe, refine cast_with_bot _ , end lemma degree_prod_le_sum_degree (s : finset A)(φ : A → polynomial R) : degree (finset.prod s (λ x : A, φ x)) ≤ finset.sum s ( λ x : A, degree (φ x)) := begin apply (finset.induction_on s), { rw prod_empty, rw sum_empty, rw degree_one, exact le_refl 0, }, intros ℓ s hyp_ℓ hyp_rec, rw sum_insert (by assumption), rw prod_insert (by assumption), exact le_trans (degree_mul_le _ _) (add_le_add_left' (hyp_rec)), end theorem sum_le (s : finset A) (φ : A → (with_bot ℕ) ) (hyp : ∀ ℓ : A, φ ℓ ≤ 1) : finset.sum s φ ≤ card s := begin apply (finset.induction_on s), { rw sum_empty, rw card_empty, exact le_refl 0, }, intros ℓ s hyp_l hyp_rec, rw sum_insert (by assumption), rw card_insert_of_not_mem(by assumption), rw coe_add, rw add_comm, apply add_le_add' hyp_rec (hyp ℓ ), end lemma prod_degree_one_le_card (s : finset A)(φ : A → polynomial R) (hyp : ∀ ℓ : A, degree(φ ℓ ) ≤ 1 ) : degree (finset.prod s (λ x : A, φ x)) ≤ card s := begin apply le_trans (degree_prod_le_sum_degree s φ), apply sum_le , exact hyp, end lemma le_add_compensation (a : ℕ) { b c d : with_bot ℕ} : (a : with_bot ℕ ) + c ≤ b +d → b ≤ a → c ≤ d := begin intros hyp1 hyp2 , have r : b+d ≤ a + d, exact add_le_add_right' hyp2, have : (a : with_bot ℕ ) + c ≤ a + d, apply le_trans (hyp1) (r), rcases c, exact bot_le, rcases d, erw le_bot_iff at this, trivial, rw ← some_eq_coe at * , erw ← coe_add at this, erw ← coe_add at this, let F := coe_le_coe.mp this, apply coe_le_coe.mpr, exact (add_le_add_iff_left a).mp F, end /-! The last technical lemma -/ example (a b: ℕ ): a = b → a ≤ b := begin library_search, end lemma add_eq_bot (a : ℕ ) (b : with_bot ℕ ) : (a : with_bot ℕ ) + b = ⊥ → b = ⊥ := begin cases b, intros, rw none_eq_bot, intros, rw some_eq_coe at a_1, rw ← coe_add at a_1, finish, end #check with_bot. --by cases a; cases b; simp [none_eq_bot, some_eq_coe, coe_add.symm] lemma ert (a b : ℕ) : (a = b ) → (a : with_bot ℕ ) = b := begin intros,exact congr_arg coe a_1, end lemma tre (a b : ℕ ) : (a : with_bot ℕ ) = b → a = b := begin intros,exact option.some_inj.mp a_1, end lemma left_cancel ( a : ℕ ) {b c : with_bot ℕ } : ↑a + b = a + c → b = c := begin intros, rcases b, rcases c, exact rfl, rw none_eq_bot at a_1, rw add_bot at a_1, rw some_eq_coe at a_1, let g := (add_eq_bot a) c, let h := eq.symm a_1, specialize g h, trivial, rw some_eq_coe at a_1, rw ← coe_add at a_1,cases c, finish, rw some_eq_coe at a_1, rw ← coe_add at a_1, let k := tre (a+b) (a+c) a_1, rw some_eq_coe , rw some_eq_coe, apply ert, apply eq_of_add_eq_add_left k, end theorem proof_stra (a : ℕ) { b c d : ℕ} : a ≤ c → b ≤ d → (a+ b = c +d → (a=c ∧ b = d)) := begin intros,split, apply le_antisymm, assumption, apply (add_le_add_iff_left b).mp, conv_rhs { rw add_comm, rw a_3, rw add_comm, }, apply (add_le_add_iff_right c).mpr , assumption, apply le_antisymm, assumption, apply (add_le_add_iff_left a).mp, conv_rhs { rw a_3, }, apply (add_le_add_iff_right d).mpr , assumption, end /-- I use proof_strategy 2 -/ theorem q_card_insert_eq_card (s : finset A) (φ : A → (with_bot ℕ) ) (hyp : ∀ ℓ : A, φ ℓ ≤ 1) (ℓ0 ∉ s ): finset.sum (insert ℓ0 s) φ = card (insert ℓ0 s) → finset.sum s φ = card s := begin rw sum_insert(by assumption), rw card_insert_of_not_mem(by assumption), rw [coe_add, add_comm], intros hyp_s, apply le_antisymm( sum_le s φ hyp), have pre_strat : ↑1 + ↑(card s) = φ ℓ0 + finset.sum s (λ (x : A), φ x), rw add_comm, rw ← hyp_s, rw add_comm, apply le_add_compensation 1 (le_of_eq (pre_strat)), exact (hyp ℓ0), end theorem jenesaispas (s : finset A) (φ : A → (with_bot ℕ) ) (hyp : ∀ ℓ : A, φ ℓ ≤ 1) : finset.sum s φ = card s → (∀ ℓ : A, ℓ ∈ s → φ ℓ = 1) := begin apply (finset.induction_on s), { rw sum_empty, intros, let g := not_mem_empty ℓ , trivial, }, { intros ℓ s hyp_l hyp_rec,intros, by_cases ℓ_1 = ℓ,{ let h' := h, by_cases (finset.sum s φ = ↑(card s)),{ rw [sum_insert(by assumption),card_insert_of_not_mem(by assumption), coe_add] at a, intros,rw h', rw h at a, rw add_comm at a, refine left_cancel (card s) a , }, let pre_strat := q_card_insert_eq_card s φ hyp ℓ hyp_l a,trivial, }, { let p := mem_of_mem_insert_of_ne a_1 h, let pre_strat := q_card_insert_eq_card s φ hyp ℓ hyp_l a, specialize hyp_rec pre_strat, exact hyp_rec ℓ_1 p, }, }, end theorem det_card_term_'11 ( s: finset A) (φ : A → polynomial R) (hyp : ∀ ℓ : A, degree(φ ℓ ) ≤ (1 : with_bot ℕ )) : degree (finset.prod s (λ x :A, φ x)) = card s → (∀ ℓ : A, ℓ ∈ s → degree (φ ℓ ) = 1) := begin let je := jenesaispas s (λ x, degree (φ x)) hyp, intros, have rr : finset.sum s (λ x, degree (φ x)) = card s, apply le_antisymm,{ apply sum_le s , exact hyp, }, { rw ← a, exact degree_prod_le_sum_degree s φ, }, exact je rr ℓ a_1, end theorem degree_prod_le_one_lt_card (φ : A → polynomial R) (hyp : ∀ ℓ : A, degree(φ ℓ ) ≤ 1 ) (hyp_lc : ∃ ℓ0 : A, degree (φ ℓ0) < 1) : degree (finset.prod finset.univ (λ x :A, φ x)) < fintype.card A := begin by_contradiction contra, push_neg at contra, let g := det_card_term_'11 (finset.univ) φ hyp, have : ↑(fintype.card A) = degree (finset.prod univ (λ (x : A), φ x)), apply le_antisymm (by assumption), apply le_trans (degree_prod_le_sum_degree (finset.univ) φ), apply sum_le , exact hyp, rcases hyp_lc with ⟨ ζ, j⟩, specialize g (eq.symm this) ζ (mem_univ _), rw g at j,exact lt_irrefl 1 j, end end tools /- unfold car_matrix, split_ifs, rw eval_add, rw eval_C, rw eval_X, rw h, rw add_val, rw smul_val, rw one_val, rw mul_ite, rw mul_one, rw mul_zero,simp, rw eval_C,rw add_val, rw smul_val, rw one_val, rw mul_ite,split_ifs, rw mul_zero,rw add_zero, -/
5861c51e57aa50072dbef3a36bd6d5c70b8ffa1d
649957717d58c43b5d8d200da34bf374293fe739
/src/data/nat/basic.lean
6eee06fce724e4cebf5df67b2d82ccff81a0b1b7
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
47,351
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro Basic operations on the natural numbers. -/ import logic.basic algebra.ordered_ring data.option.basic universes u v namespace nat variables {m n k : ℕ} -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ_inj, congr_arg _⟩ theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ lemma zero_max {m : nat} : max 0 m = m := max_eq_right (zero_le _) theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := (lt_or_eq_of_le H).imp le_of_lt_succ id @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] theorem pos_iff_ne_zero : n > 0 ↔ n ≠ 0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ theorem pos_iff_ne_zero' : 0 < n ↔ n ≠ 0 := pos_iff_ne_zero lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : n ≥ m) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] protected theorem lt_of_sub_pos (h : n - m > 0) : m < n := lt_of_not_ge (assume : m ≥ n, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : m > 0) (h₂ : n > 0) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h lemma le_mul_of_pos_left {m n : ℕ} (h : n > 0) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : n > 0) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by rw [add_comm, add_mul_mod_self_left, mul_mod_right]; exact dec_trivial) @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (decidable.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := begin revert x, refine nat.strong_rec' _ y, clear y, intros y IH x, cases decidable.lt_or_le y k with h h, { rw [div_eq_of_lt h], cases x with x, { simp [zero_mul, zero_le] }, { rw succ_mul, exact iff_of_false (not_succ_le_zero _) (not_le_of_lt $ lt_of_lt_of_le h (le_add_left _ _)) } }, { rw [div_eq_sub_div k0 h], cases x with x, { simp [zero_mul, zero_le] }, { rw [← add_one, nat.add_le_add_iff_le_right, succ_mul, IH _ (sub_lt_of_pos_le _ _ k0 h), add_le_to_le_sub _ h] } } end theorem div_mul_le_self' (m n : ℕ) : m / n * n ≤ m := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0, zero_le]) $ λ n0, (le_div_iff_mul_le' n0).1 (le_refl _) theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self' _ _) h lemma lt_of_div_lt_div {m n k : ℕ} (h : m / k < n / k) : m < n := by_contradiction $ λ h₁, absurd h (not_lt_of_ge (nat.div_le_div_right (not_lt.1 h₁))) protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected theorem mul_right_inj {a b c : ℕ} (ha : a > 0) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : a > 0) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_right_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_left_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc] else by conv {to_rhs, rw ← mod_add_div a (b * c)}; rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))] lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : a > 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_left_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : c > 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_right_inj hc] @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) theorem add_pos_left {m : ℕ} (h : m > 0) (n : ℕ) : m + n > 0 := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : n > 0) : m + n > 0 := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : m + n > 0 ↔ m > 0 ∨ n > 0 := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], by clear_aux_decl; finish⟩ lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_left_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) /- partial subtraction -/ /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : ℕ → option ℕ | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : ℕ) : ℕ → option ℕ | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := by dsimp; apply option.bind_eq_some.trans; simp [psub_eq_some] theorem psub_eq_none (m n : ℕ) : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (λ h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≤ m, rw ← psub_eq_some.1 s, apply le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) := psub_eq_some.2 $ nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, bind_assoc] /- pow -/ attribute [simp] nat.pow_zero nat.pow_one @[simp] lemma one_pow : ∀ n : ℕ, 1 ^ n = 1 | 0 := rfl | (k+1) := show 1^k * 1 = 1, by rw [mul_one, one_pow] theorem pow_add (a m n : ℕ) : a^(m + n) = a^m * a^n := by induction n; simp [*, pow_succ, mul_assoc] theorem pow_two (a : ℕ) : a ^ 2 = a * a := show (1 * a) * a = _, by rw one_mul theorem pow_dvd_pow (a : ℕ) {m n : ℕ} (h : m ≤ n) : a^m ∣ a^n := by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right theorem pow_dvd_pow_of_dvd {a b : ℕ} (h : a ∣ b) : ∀ n:ℕ, a^n ∣ b^n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul (pow_dvd_pow_of_dvd n) h theorem mul_pow (a b n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := by induction n; simp [*, nat.pow_succ, mul_comm, mul_assoc, mul_left_comm] protected theorem pow_mul (a b n : ℕ) : n ^ (a * b) = (n ^ a) ^ b := by induction b; simp [*, nat.succ_eq_add_one, nat.pow_add, mul_add, mul_comm] theorem pow_pos {p : ℕ} (hp : p > 0) : ∀ n : ℕ, p ^ n > 0 | 0 := by simpa using zero_lt_one | (k+1) := mul_pos (pow_pos _) hp lemma pow_eq_mul_pow_sub (p : ℕ) {m n : ℕ} (h : m ≤ n) : p ^ m * p ^ (n - m) = p ^ n := by rw [←nat.pow_add, nat.add_sub_cancel' h] lemma pow_lt_pow_succ {p : ℕ} (h : p > 1) (n : ℕ) : p^n < p^(n+1) := suffices p^n*1 < p^n*p, by simpa, nat.mul_lt_mul_of_pos_left h (nat.pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : ℕ} (h : p > 1) : ∀ n : ℕ, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≤ p ^ (n+1) : pow_lt_pow_succ h _ lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : p > 1) (hk : k > 1), ¬ p^k ∣ p | (succ p) (succ k) hp hk h := have (succ p)^k * succ p ∣ 1 * succ p, by simpa, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_right (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 > 1, by rwa [this] at hk, absurd this dec_trivial @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /- iterate -/ section variables {α : Sort*} (op : α → α) @[simp] theorem iterate_zero (a : α) : op^[0] a = a := rfl @[simp] theorem iterate_succ (n : ℕ) (a : α) : op^[succ n] a = (op^[n]) (op a) := rfl theorem iterate_add : ∀ (m n : ℕ) (a : α), op^[m + n] a = (op^[m]) (op^[n] a) | m 0 a := rfl | m (succ n) a := iterate_add m n _ theorem iterate_succ' (n : ℕ) (a : α) : op^[succ n] a = op (op^[n] a) := by rw [← one_add, iterate_add]; refl theorem iterate₀ {α : Type u} {op : α → α} {x : α} (H : op x = x) {n : ℕ} : op^[n] x = x := by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]] theorem iterate₁ {α : Type u} {β : Type v} {op : α → α} {op' : β → β} {op'' : α → β} (H : ∀ x, op' (op'' x) = op'' (op x)) {n : ℕ} {x : α} : op'^[n] (op'' x) = op'' (op^[n] x) := by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]] theorem iterate₂ {α : Type u} {op : α → α} {op' : α → α → α} (H : ∀ x y, op (op' x y) = op' (op x) (op y)) {n : ℕ} {x y : α} : op^[n] (op' x y) = op' (op^[n] x) (op^[n] y) := by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]] theorem iterate_cancel {α : Type u} {op op' : α → α} (H : ∀ x, op (op' x) = x) {n : ℕ} {x : α} : op^[n] (op'^[n] x) = x := by induction n; [refl, rwa [iterate_succ, iterate_succ', H]] theorem iterate_inj {α : Type u} {op : α → α} (Hinj : function.injective op) (n : ℕ) (x y : α) (H : (op^[n] x) = (op^[n] y)) : x = y := by induction n with n ih; simp only [iterate_zero, iterate_succ'] at H; [exact H, exact ih (Hinj H)] end /- size and shift -/ theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, refl end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0 @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ_inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := λ n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases e : bit b m = 0, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero'] at this; exact not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /- factorial -/ /-- `fact n` is the factorial of `n`. -/ @[simp] def fact : nat → nat | 0 := 1 | (succ n) := succ n * fact n @[simp] theorem fact_zero : fact 0 = 1 := rfl @[simp] theorem fact_one : fact 1 = 1 := rfl @[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl theorem fact_pos : ∀ n, fact n > 0 | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (fact_pos n) theorem fact_ne_zero (n : ℕ) : fact n ≠ 0 := ne_of_gt (fact_pos _) theorem fact_dvd_fact {m n} (h : m ≤ n) : fact m ∣ fact n := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } } end theorem dvd_fact : ∀ {m n}, m > 0 → m ≤ n → m ∣ fact n | (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h) theorem fact_le {m n} (h : m ≤ n) : fact m ≤ fact n := le_of_dvd (fact_pos _) (fact_dvd_fact h) lemma fact_mul_pow_le_fact : ∀ {m n : ℕ}, m.fact * m.succ ^ n ≤ (m + n).fact | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.fact_succ, mul_comm (nat.succ _), nat.pow_succ, ← mul_assoc]; exact mul_le_mul fact_mul_pow_le_fact (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) /- choose -/ def choose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := choose n k + choose n (succ k) @[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl @[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0 | _ 0 hk := absurd hk dec_trivial | 0 (k + 1) hk := choose_zero_succ _ | (n + 1) (k + 1) hk := have hnk : n < k, from lt_of_succ_lt_succ hk, have hnk1 : n < k + 1, from lt_of_succ_lt hk, by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] lemma choose_self (n : ℕ) : choose n n = 1 := by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n; simp [*, choose] lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k | 0 _ hk := by rw [eq_zero_of_le_zero hk]; exact dec_trivial | (n + 1) 0 hk := by simp; exact dec_trivial | (n + 1) (k + 1) hk := by rw choose_succ_succ; exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (nat.zero_le _) lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0 0 := dec_trivial | 0 (k + 1) := by simp [choose] | (n + 1) 0 := by simp | (n + 1) (k + 1) := by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ, ←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul] lemma choose_mul_fact_mul_fact : ∀ {n k}, k ≤ n → choose n k * fact k * fact (n - k) = fact n | 0 _ hk := by simp [eq_zero_of_le_zero hk] | (n + 1) 0 hk := by simp | (n + 1) (succ k) hk := begin cases lt_or_eq_of_le hk with hk₁ hk₁, { have h : choose n k * fact (succ k) * fact (n - k) = succ k * fact n := by rw ← choose_mul_fact_mul_fact (le_of_succ_le_succ hk); simp [fact_succ, mul_comm, mul_left_comm], have h₁ : fact (n - k) = (n - k) * fact (n - succ k) := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), fact_succ], have h₂ : choose n (succ k) * fact (succ k) * ((n - k) * fact (n - succ k)) = (n - k) * fact n := by rw ← choose_mul_fact_mul_fact (le_of_lt_succ hk₁); simp [fact_succ, mul_comm, mul_left_comm, mul_assoc], have h₃ : k * fact n ≤ n * fact n := mul_le_mul_right _ (le_of_succ_le_succ hk), rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, ← add_one, add_mul, nat.mul_sub_right_distrib, fact_succ, ← nat.add_sub_assoc h₃, add_assoc, ← add_mul, nat.add_sub_cancel_left, add_comm] }, { simp [hk₁, mul_comm, choose, nat.sub_self] } end theorem choose_eq_fact_div_fact {n k : ℕ} (hk : k ≤ n) : choose n k = fact n / (fact k * fact (n - k)) := begin have : fact n = choose n k * (fact k * fact (n - k)) := by rw ← mul_assoc; exact (choose_mul_fact_mul_fact hk).symm, exact (nat.div_eq_of_eq_mul_left (mul_pos (fact_pos _) (fact_pos _)) this).symm end theorem fact_mul_fact_dvd_fact {n k : ℕ} (hk : k ≤ n) : fact k * fact (n - k) ∣ fact n := by rw [←choose_mul_fact_mul_fact hk, mul_assoc]; exact dvd_mul_left _ _ section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_spec_and_le : ∀{b m}, m ≤ b → P m → P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b | 0 m hm hP := have m = 0, from le_antisymm hm (nat.zero_le _), show P 0 ∧ m ≤ 0, from this ▸ ⟨hP, le_refl _⟩ | (b + 1) m hm hP := begin by_cases h : P (b + 1), { simp [h, hm] }, { have : m ≠ b + 1 := assume this, h $ this ▸ hP, have : m ≤ b := (le_of_not_gt $ assume h : b + 1 ≤ m, this $ le_antisymm hm h), have : P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b := find_greatest_spec_and_le this hP, simp [h, this] } end lemma find_greatest_spec {b} : (∃m, m ≤ b ∧ P m) → P (nat.find_greatest P b) | ⟨m, hmb, hm⟩ := (find_greatest_spec_and_le hmb hm).1 lemma find_greatest_le : ∀ {b}, nat.find_greatest P b ≤ b | 0 := le_refl _ | (b + 1) := have nat.find_greatest P b ≤ b + 1, from le_trans find_greatest_le (nat.le_succ b), by by_cases P (b + 1); simp [h, this] lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := (find_greatest_spec_and_le hmb hm).2 lemma find_greatest_is_greatest {P : ℕ → Prop} [decidable_pred P] {b} : (∃ m, m ≤ b ∧ P m) → ∀ k, nat.find_greatest P b < k ∧ k ≤ b → ¬ P k | ⟨m, hmb, hP⟩ k ⟨hk, hkb⟩ hPk := lt_irrefl k $ lt_of_le_of_lt (le_find_greatest hkb hPk) hk lemma find_greatest_eq_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b}, (∀ n ≤ b, ¬ P n) → nat.find_greatest P b = 0 | 0 h := find_greatest_zero | (n + 1) h := begin have := nat.find_greatest_of_not (h (n + 1) (le_refl _)), rw this, exact find_greatest_eq_zero (assume k hk, h k (le_trans hk $ nat.le_succ _)) end lemma find_greatest_of_ne_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b m}, nat.find_greatest P b = m → m ≠ 0 → P m | 0 m rfl h := by { have := @find_greatest_zero P _, contradiction } | (b + 1) m rfl h := decidable.by_cases (assume hb : P (b + 1), by { have := find_greatest_eq hb, rw this, exact hb }) (assume hb : ¬ P (b + 1), find_greatest_of_ne_zero (find_greatest_of_not hb).symm h) end find_greatest section div lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : a > 0, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have hac : a ∣ c, from dvd_of_mul_right_dvd h, have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have b > 0, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have d > 0, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk lemma eq_of_dvd_quot_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := begin rcases w with ⟨b, rfl⟩, rw [nat.mul_comm, nat.mul_div_cancel] at h, { simp [h] }, { by_contradiction, simp * at * } end lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end end div lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ lemma with_bot.add_eq_zero_iff : ∀ {n m : with_bot ℕ}, n + m = 0 ↔ n = 0 ∧ m = 0 | none m := iff_of_false dec_trivial (λ h, absurd h.1 dec_trivial) | n none := iff_of_false (by cases n; exact dec_trivial) (λ h, absurd h.2 dec_trivial) | (some n) (some m) := show (n + m : with_bot ℕ) = (0 : ℕ) ↔ (n : with_bot ℕ) = (0 : ℕ) ∧ (m : with_bot ℕ) = (0 : ℕ), by rw [← with_bot.coe_add, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, add_eq_zero_iff' (nat.zero_le _) (nat.zero_le _)] lemma with_bot.add_eq_one_iff : ∀ {n m : with_bot ℕ}, n + m = 1 ↔ (n = 0 ∧ m = 1) ∨ (n = 1 ∧ m = 0) | none none := dec_trivial | none (some m) := dec_trivial | (some n) none := iff_of_false dec_trivial (λ h, h.elim (λ h, absurd h.2 dec_trivial) (λ h, absurd h.2 dec_trivial)) | (some n) (some 0) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp | (some n) (some (m + 1)) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp [nat.add_succ, nat.succ_inj', nat.succ_ne_zero] -- induction @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n ≥ m, P n → P (n + 1)) : ∀ n ≥ m, P n := by apply nat.less_than_or_equal.rec h0; exact h1 @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } end nat
77346ad09d12adbf2d97ab0e0f285ceb15da30ee
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/nielsen_schreier.lean
7b4cacc75d63fc800d9c636c9672b89c865b3e15
[ "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,006
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 category_theory.action import combinatorics.quiver import group_theory.is_free_group /-! # The Nielsen-Schreier theorem This file proves that a subgroup of a free group is itself free. ## Main result - `subgroup_is_free_of_is_free H`: an instance saying that a subgroup of a free group is free. ## Proof overview The proof is analogous to the proof using covering spaces and fundamental groups of graphs, but we work directly with groupoids instead of topological spaces. Under this analogy, - `is_free_groupoid G` corresponds to saying that a space is a graph. - `End_mul_equiv_subgroup H` plays the role of replacing 'subgroup of fundamental group' with 'fundamental group of covering space'. - `action_groupoid_is_free G A` corresponds to the fact that a covering of a (single-vertex) graph is a graph. - `End_is_free T` corresponds to the fact that, given a spanning tree `T` of a graph, its fundamental group is free (generated by loops from the complement of the tree). ## Implementation notes Our definition of `is_free_groupoid` is nonstandard. Normally one would require that functors `G ⥤ X` to any _groupoid_ `X` are given by graph homomorphisms from the generators, but we only consider _groups_ `X`. This simplifies the argument since functor equality is complicated in general, but simple for functors to single object categories. ## References https://ncatlab.org/nlab/show/Nielsen-Schreier+theorem ## Tags free group, free groupoid, Nielsen-Schreier -/ noncomputable theory open_locale classical universes v u open category_theory category_theory.action_category category_theory.single_obj quiver is_free_group as fgp /-- `is_free_groupoid.generators G` is a type synonym for `G`. We think of this as the vertices of the generating quiver of `G` when `G` is free. We can't use `G` directly, since `G` already has a quiver instance from being a groupoid. -/ @[nolint unused_arguments has_inhabited_instance] def is_free_groupoid.generators (G) [groupoid G] := G /-- A groupoid `G` is free when we have the following data: - a quiver on `is_free_groupoid.generators G` (a type synonym for `G`) - a function `of` taking a generating arrow to a morphism in `G` - such that a functor from `G` to any group `X` is uniquely determined by assigning labels in `X` to the generating arrows. This definition is nonstandard. Normally one would require that functors `G ⥤ X` to any _groupoid_ `X` are given by graph homomorphisms from `generators`. -/ class is_free_groupoid (G) [groupoid.{v} G] := (quiver_generators : quiver.{v+1} (is_free_groupoid.generators G)) (of : Π {a b : is_free_groupoid.generators G}, (a ⟶ b) → ((show G, from a) ⟶ b)) (unique_lift : ∀ {X : Type v} [group X] (f : labelling (is_free_groupoid.generators G) X), ∃! F : G ⥤ single_obj X, ∀ a b (g : a ⟶ b), F.map (of g) = f g) namespace is_free_groupoid attribute [instance] quiver_generators /-- Two functors from a free groupoid to a group are equal when they agree on the generating quiver. -/ @[ext] lemma ext_functor {G} [groupoid.{v} G] [is_free_groupoid G] {X : Type v} [group X] (f g : G ⥤ single_obj X) (h : ∀ a b (e : a ⟶ b), f.map (of e) = g.map (of e)) : f = g := let ⟨_, _, u⟩ := @unique_lift G _ _ X _ (λ (a b : generators G) (e : a ⟶ b), g.map (of e)) in trans (u _ h) (u _ (λ _ _ _, rfl)).symm /-- An action groupoid over a free froup is free. More generally, one could show that the groupoid of elements over a free groupoid is free, but this version is easier to prove and suffices for our purposes. Analogous to the fact that a covering space of a graph is a graph. (A free groupoid is like a graph, and a groupoid of elements is like a covering space.) -/ instance action_groupoid_is_free {G A : Type u} [group G] [is_free_group G] [mul_action G A] : is_free_groupoid (action_category G A) := { quiver_generators := ⟨λ a b, { e : fgp.generators G // fgp.of e • a.back = b.back }⟩, of := λ a b e, ⟨fgp.of e, e.property⟩, unique_lift := begin introsI X _ f, let f' : fgp.generators G → (A → X) ⋊[mul_aut_arrow] G := λ e, ⟨λ b, @f ⟨(), _⟩ ⟨(), b⟩ ⟨e, smul_inv_smul _ b⟩, fgp.of e⟩, rcases fgp.unique_lift f' with ⟨F', hF', uF'⟩, refine ⟨uncurry F' _, _, _⟩, { suffices : semidirect_product.right_hom.comp F' = monoid_hom.id _, { exact monoid_hom.ext_iff.mp this }, ext, rw [monoid_hom.comp_apply, hF'], refl }, { rintros ⟨⟨⟩, a : A⟩ ⟨⟨⟩, b⟩ ⟨e, h : fgp.of e • a = b⟩, change (F' (fgp.of _)).left _ = _, rw hF', cases (inv_smul_eq_iff.mpr h.symm), refl }, { intros E hE, have : curry E = F', { apply uF', intro e, ext, { convert hE _ _ _, refl }, { refl } }, apply functor.hext, { intro, apply unit.ext }, { refine action_category.cases _, intros, simp only [←this, uncurry_map, curry_apply_left, coe_back, hom_of_pair.val] } }, end } namespace spanning_tree /- In this section, we suppose we have a free groupoid with a spanning tree for its generating quiver. The goal is to prove that the vertex group at the root is free. A picture to have in mind is that we are 'pulling' the endpoints of all the edges of the quiver along the spanning tree to the root. -/ variables {G : Type u} [groupoid.{u} G] [is_free_groupoid G] (T : wide_subquiver (symmetrify $ generators G)) [arborescence T] /-- The root of `T`, except its type is `G` instead of the type synonym `T`. -/ private def root' : G := show T, from root T /-- A path in the tree gives a hom, by composition. -/ -- this has to be marked noncomputable, see issue #451. -- It might be nicer to define this in terms of `compose_path` noncomputable def hom_of_path : Π {a : G}, path (root T) a → (root' T ⟶ a) | _ path.nil := 𝟙 _ | a (path.cons p f) := hom_of_path p ≫ sum.rec_on f.val (λ e, of e) (λ e, inv (of e)) /-- For every vertex `a`, there is a canonical hom from the root, given by the path in the tree. -/ def tree_hom (a : G) : root' T ⟶ a := hom_of_path T (default _) /-- Any path to `a` gives `tree_hom T a`, since paths in the tree are unique. -/ lemma tree_hom_eq {a : G} (p : path (root T) a) : tree_hom T a = hom_of_path T p := by rw [tree_hom, unique.default_eq] @[simp] lemma tree_hom_root : tree_hom T (root' T) = 𝟙 _ := -- this should just be `tree_hom_eq T path.nil`, but Lean treats `hom_of_path` with suspicion. trans (tree_hom_eq T path.nil) rfl /-- Any hom in `G` can be made into a loop, by conjugating with `tree_hom`s. -/ def loop_of_hom {a b : G} (p : a ⟶ b) : End (root' T) := tree_hom T a ≫ p ≫ inv (tree_hom T b) /-- Turning an edge in the spanning tree into a loop gives the indentity loop. -/ lemma loop_of_hom_eq_id {a b : generators G} (e ∈ wide_subquiver_symmetrify T a b) : loop_of_hom T (of e) = 𝟙 (root' T) := begin rw [loop_of_hom, ←category.assoc, is_iso.comp_inv_eq, category.id_comp], cases H, { rw [tree_hom_eq T (path.cons (default _) ⟨sum.inl e, H⟩), hom_of_path], refl }, { rw [tree_hom_eq T (path.cons (default _) ⟨sum.inr e, H⟩), hom_of_path], simp only [is_iso.inv_hom_id, category.comp_id, category.assoc, tree_hom] } end /-- Since a hom gives a loop, any homomorphism from the vertex group at the root extends to a functor on the whole groupoid. -/ @[simps] def functor_of_monoid_hom {X} [monoid X] (f : End (root' T) →* X) : G ⥤ single_obj X := { obj := λ _, (), map := λ a b p, f (loop_of_hom T p), map_id' := begin intro a, rw [loop_of_hom, category.id_comp, is_iso.hom_inv_id, ←End.one_def, f.map_one, id_as_one], end, map_comp' := begin intros, rw [comp_as_mul, ←f.map_mul], simp only [is_iso.inv_hom_id_assoc, loop_of_hom, End.mul_def, category.assoc] end } /-- Given a free groupoid and an arborescence of its generating quiver, the vertex group at the root is freely generated by loops coming from generating arrows in the complement of the tree. -/ def End_is_free : is_free_group (End (root' T)) := { generators := set.compl (wide_subquiver_equiv_set_total $ wide_subquiver_symmetrify T), of := λ e, loop_of_hom T (of e.val.hom), unique_lift' := begin introsI X _ f, let f' : labelling (generators G) X := λ a b e, if h : e ∈ wide_subquiver_symmetrify T a b then 1 else f ⟨⟨a, b, e⟩, h⟩, rcases unique_lift f' with ⟨F', hF', uF'⟩, refine ⟨F'.map_End _, _, _⟩, { suffices : ∀ {x y} (q : x ⟶ y), F'.map (loop_of_hom T q) = (F'.map q : X), { rintro ⟨⟨a, b, e⟩, h⟩, rw [functor.map_End_apply, this, hF'], exact dif_neg h }, intros, suffices : ∀ {a} (p : path (root' T) a), F'.map (hom_of_path T p) = 1, { simp only [this, tree_hom, comp_as_mul, inv_as_inv, loop_of_hom, one_inv, mul_one, one_mul, functor.map_inv, functor.map_comp] }, intros a p, induction p with b c p e ih, { rw [hom_of_path, F'.map_id, id_as_one] }, rw [hom_of_path, F'.map_comp, comp_as_mul, ih, mul_one], rcases e with ⟨e | e, eT⟩, { rw hF', exact dif_pos (or.inl eT) }, { rw [F'.map_inv, inv_as_inv, inv_eq_one, hF'], exact dif_pos (or.inr eT) } }, { intros E hE, ext, suffices : (functor_of_monoid_hom T E).map x = F'.map x, { simpa only [loop_of_hom, functor_of_monoid_hom_map, is_iso.inv_id, tree_hom_root, category.id_comp, category.comp_id] using this }, congr, apply uF', intros a b e, change E (loop_of_hom T _) = dite _ _ _, split_ifs, { rw [loop_of_hom_eq_id T e h, ←End.one_def, E.map_one] }, { exact hE ⟨⟨a, b, e⟩, h⟩ } } end } end spanning_tree /-- Another name for the identity function `G → G`, to help type checking. -/ private def symgen {G : Type u} [groupoid.{v} G] [is_free_groupoid G] : G → symmetrify (generators G) := id /-- If there exists a morphism `a → b` in a free groupoid, then there also exists a zigzag from `a` to `b` in the generating quiver. -/ lemma path_nonempty_of_hom {G} [groupoid.{u u} G] [is_free_groupoid G] {a b : G} : nonempty (a ⟶ b) → nonempty (path (symgen a) (symgen b)) := begin rintro ⟨p⟩, rw [←weakly_connected_component.eq, eq_comm, ←free_group.of_injective.eq_iff, ←mul_inv_eq_one], let X := free_group (weakly_connected_component $ symmetrify $ generators G), let f : G → X := λ g, free_group.of ↑(symgen g), let F : G ⥤ single_obj X := single_obj.difference_functor f, change F.map p = ((category_theory.functor.const G).obj ()).map p, congr, ext, rw [functor.const.obj_map, id_as_one, difference_functor_map, mul_inv_eq_one], apply congr_arg free_group.of, rw weakly_connected_component.eq, exact ⟨hom.to_path (sum.inr e)⟩, end /-- Given a connected free groupoid, its generating quiver is rooted-connected. -/ instance generators_connected (G) [groupoid.{u u} G] [is_connected G] [is_free_groupoid G] (r : G) : rooted_connected (symgen r) := ⟨λ b, path_nonempty_of_hom (category_theory.nonempty_hom_of_connected_groupoid r b)⟩ /-- A vertex group in a free connected groupoid is free. With some work one could drop the connectedness assumption, by looking at connected components. -/ instance End_is_free_of_connected_free {G} [groupoid G] [is_connected G] [is_free_groupoid G] (r : G) : is_free_group (End r) := spanning_tree.End_is_free $ geodesic_subtree (symgen r) end is_free_groupoid /-- The Nielsen-Schreier theorem: a subgroup of a free group is free. -/ instance subgroup_is_free_of_is_free {G : Type u} [group G] [is_free_group G] (H : subgroup G) : is_free_group H := is_free_group.of_mul_equiv (End_mul_equiv_subgroup H)
c3a1292e8a902d0cbd41ddd97a847ac52cbc782a
64a7884f2a9a760de30168e86a897e1ed06616d2
/TPPmark/hagiwara/Subsequences.lean
99368681333220e455cd21fe72b5b8a64fcd62c9
[]
no_license
aigarashi/TPP2017
b87b44649856bd092aa44e9d30dd2b99fecae8ac
3d27301214cebccad6262315b822f81ab273940a
refs/heads/master
1,630,127,109,936
1,512,981,388,000
1,512,981,388,000
104,860,417
1
2
null
1,512,542,842,000
1,506,415,863,000
Coq
UTF-8
Lean
false
false
14,137
lean
prelude import init.data.list.lemmas import init.data.nat.lemmas variables {α : Type} {β : Type} open list nat prod well_founded namespace list lemma strong_ind_help {A : Type} (f : A → ℕ) {P : A → Prop} (H : ∀ n : ℕ, ∀ a : A, f a ≤ n → P a) : ∀ a : A, P a := begin intro a, apply (H (f a)), reflexivity end lemma funcToNat_strong_ind {A : Type} {f : A → ℕ} {P : A → Prop} (H0 : ∀ a : A, f a = 0 → P a) (Hn : ∀ n : ℕ, (∀ b : A, f b ≤ n → P b) → ∀ c : A, f c = n+1 → P c) : ∀ a : A, P a := begin intro a, apply (strong_ind_help f), intro n, induction n with n H', {intros a0 Ha0, apply H0, assert Temp : forall x: nat, x ≤ 0 → x = 0, {intros x H, cases H, {trivial}}, apply Temp, assumption}, {intros b h, assert hm : f b = succ n ∨ f b < succ n, apply nat.eq_or_lt_of_le h, apply or.elim hm, apply Hn, apply H', intro h, assert hk : f b ≤ n, apply le_of_lt_succ, apply h, apply H', apply hk}, end definition subseq : list α → list α → Prop | [] _ := true | (a::A') [] := false | (a::A') (b::B') := ((a=b) ∧ (subseq A' B')) ∨ (subseq (a::A') B') lemma nil_subseq (A : list α) : subseq [] A := begin cases A with a A', trivial, unfold subseq, trivial end lemma subseq_nil (A : list α) : subseq A [] ↔ A = [] := begin apply iff.intro, {cases A with a A', {intro h, apply eq.refl}, {unfold subseq, apply false.elim}}, {intro h, rw h, apply nil_subseq} end lemma subseq_self (A : list α) : subseq A A := begin induction A with a A', {apply nil_subseq}, {unfold subseq, apply or.intro_left, apply and.intro, apply rfl, apply ih_1} end lemma tail_subseq (a : α) (A' : list α): subseq A' (a::A') := begin induction A' with a' A'', {apply nil_subseq}, {unfold subseq, apply or.intro_right, apply subseq_self (a'::A'')} end lemma subseq_implies_leq (A B : list α) : (subseq A B) → length (A) ≤ length (B) := begin revert A, induction B with b B', {intros A h, assert h1 : A = [], revert h, apply iff.elim_left (subseq_nil A), rw h1}, {intro A, cases A with a A', {intro h, unfold length, apply zero_le}, {unfold subseq, intro h, apply or.elim h, {intro h, unfold length, apply succ_le_succ, apply ih_1 A', apply and.right h}, {intro h, apply le_succ_of_le, apply ih_1 (a::A'), apply h}}} end lemma subseq_trans (X Y Z : list α) : (subseq X Y) → (subseq Y Z) → (subseq X Z) := begin revert X Y, induction Z with z Z', {intros X Y hXY hY, unfold subseq, assert h1 : Y = [], revert hY, apply iff.elim_left (subseq_nil Y), assert h2 : X = [], revert hXY, rw h1, apply iff.elim_left (subseq_nil X), rw h2, unfold subseq, trivial}, {intros X Y, cases Y with y Y', {intros h1 h2, assert h3 : X = [], revert h1, apply iff.elim_left (subseq_nil X), rw h3, apply nil_subseq}, {cases X with x X', {intros, apply nil_subseq}, {unfold subseq, intros h1 h2, apply or.elim h1, {intro hXY, apply or.elim h2, {intro hYZ, apply or.intro_left, apply and.intro, apply eq.trans, apply and.left hXY, apply and.left hYZ, apply ih_1 X' Y' (and.right hXY) (and.right hYZ)}, {intro hYZ', apply or.intro_right, apply ih_1 (x::X') (y::Y'), apply or.intro_left, apply hXY, apply hYZ'}}, {intro hXY', apply or.elim h2, {intro h5, apply or.intro_right, apply ih_1 (x::X') Y' (hXY') (and.right h5)}, {intro hYZ', apply or.intro_right, apply ih_1 (x::X') Y', apply hXY', apply ih_1 Y' (y::Y'), apply tail_subseq, apply hYZ'}}}}} end lemma subseq_iff_tail_subseq (x : α) (X Y : list α) : subseq (x::X) (x::Y) ↔ subseq X Y := begin apply iff.intro, {unfold subseq, intro h, apply or.elim h, {intro h2, apply and.right h2}, {intro h2, apply subseq_trans, apply tail_subseq x, apply h2},}, {intro h, unfold subseq, apply or.intro_left, apply and.intro, apply rfl, apply h} end definition com_subseq (V X Y: list α) := (subseq V X) ∧ (subseq V Y) lemma nil_com_subseq (X Y : list α) : com_subseq [] X Y := begin unfold com_subseq, apply and.intro, apply nil_subseq, apply nil_subseq end lemma com_subseq_nil_left (V X: list α) : com_subseq V [] X ↔ V = [] := begin apply iff.intro, {intro h, apply iff.elim_left (subseq_nil V), apply and.left h}, {intro h, rw h, apply nil_com_subseq} end lemma com_subseq_nil_right (V X : list α) : com_subseq V X [] ↔ V = [] := begin apply iff.intro, {intro h, apply iff.elim_left (subseq_nil V), apply and.right h}, {intro h, rw h, apply nil_com_subseq} end lemma com_subseq_tail_tail (x: α) (V X Y : list α) : com_subseq (x::V) (x::X) (x::Y) ↔ com_subseq V X Y := begin apply iff.intro, {intro h, unfold com_subseq, apply and.intro, {apply iff.elim_left (subseq_iff_tail_subseq x V X), apply and.left h}, {apply iff.elim_left (subseq_iff_tail_subseq x V Y), apply and.right h}}, {intro h, unfold com_subseq, apply and.intro, {unfold subseq, apply or.intro_left, apply and.intro, refl, apply and.left h}, {unfold subseq, apply or.intro_left, apply and.intro, refl, apply and.right h},} end definition longest_com (V X Y : list α) := (com_subseq V X Y) ∧ (∀ ⦃W : list α⦄, (com_subseq W X Y) → (length W ≤ length V)) lemma nil_longest_com_left (X : list α) : longest_com [] [] X := begin apply and.intro, {apply nil_com_subseq}, {intros W hW, assert hW1 : W = [], revert hW, apply iff.elim_left (com_subseq_nil_left W X), rw hW1}, end lemma nil_longest_com_right (X : list α) : longest_com [] X [] := begin apply and.intro, {apply nil_com_subseq}, {intros W hW, assert hW1 : W = [], revert hW, apply iff.elim_left (com_subseq_nil_right W X), rw hW1} end lemma longest_com_tail (x : nat) (V X' Y' : list nat) : longest_com (x::V) (x::X') (x::Y') ↔ longest_com V X' Y' := begin apply iff.intro, {intro h, unfold longest_com, apply and.intro, {apply iff.elim_left (com_subseq_tail_tail x V X' Y'), apply and.left h}, {intros W h1, apply nat.le_of_add_le_add_left, rw -add_comm, rw add_comm 1 (length V), change length (x::W) ≤ length (x::V), apply and.right h, apply iff.elim_right (com_subseq_tail_tail x W X' Y'), apply h1},}, {intro h, unfold longest_com, apply and.intro, {apply iff.elim_right (com_subseq_tail_tail x V X' Y'), apply and.left h}, {intros W h1, cases W with w W', begin -- W = [] unfold length, apply zero_le, end, begin -- W = (w::W') cases decidable.em (w=x), begin -- w=x, revert h1, rw -a, intro h1, unfold length, apply succ_le_succ, apply and.right h, apply iff.elim_left (com_subseq_tail_tail w W' X' Y'), apply h1, end, begin -- w≠x note hWX := and.left h1, note hWY := and.right h1, unfold length, apply succ_le_succ, apply and.right h, apply and.intro, {apply subseq_trans, apply (tail_subseq w W'), revert hWX, unfold subseq, intro hWX, apply or.elim hWX, {intro h2, apply false.elim, apply iff.elim_left (not_and_self (w=x)), apply and.intro, apply a, apply and.left h2}, {intro h2, apply h2}}, {apply subseq_trans, apply (tail_subseq w W'), revert hWY, unfold subseq, intro hWY, apply or.elim hWY, {intro h2, apply false.elim, apply iff.elim_left (not_and_self (w=x)), apply and.intro, apply a, apply and.left h2}, {intro h2, apply h2},} end, end,},}, end definition longer : list α → list α → list α | X Y := if length X ≤ length Y then Y else X -- If well-founded recursion is enabled, use this defintion for com' instead : -- definition com : list nat → list nat → list nat -- | [] _ := [] -- | _ [] := [] -- | (x::X') (y::Y') := if x = y then (x :: (com X' Y')) else longer (com (x::X') Y') (com X' (y:: Y')) definition com (comX : list nat → list nat) (x : nat) (X : list nat) : list nat → list nat | [] := [] | (y::Y) := if x = y then x :: comX Y else longer (com Y) (comX (y :: Y)) definition com' : list nat → list nat → list nat | [] _ := [] | (x::X) Y := com (com' X) x X Y lemma com'_nil_left (X : list nat) : com' [] X = [] := begin unfold com', trivial end lemma com'_nil_right (X : list nat) : com' X [] = [] := begin cases X with x X', {unfold com, trivial}, {unfold com, unfold com', trivial} end definition pair_length (Z : list α × list β) := length (fst Z) + length (snd Z) lemma com'_implies_subseq_left_prod (Z : list nat × list nat) : subseq (com' (fst Z) (snd Z)) (fst Z) := begin assert H0 : ∀ Z : list ℕ × list ℕ, pair_length Z = 0 → subseq (com' (fst Z) (snd Z)) (fst Z), intros Z1 hlZ, cases Z1 with X Y, assert h: X = [], apply eq_nil_of_length_eq_zero, apply eq_zero_of_add_eq_zero_right hlZ, rw h, rw com'_nil_left, apply nil_subseq, assert Hn : ∀ n : ℕ, (∀ Z : list ℕ × list ℕ, pair_length Z ≤ n → subseq (com' (fst Z) (snd Z)) (fst Z)) → (∀ Z : list ℕ × list ℕ, pair_length Z = n+1 → subseq (com' (fst Z) (snd Z)) (fst Z)), {intros n hind Z hlZ, cases Z with X Y, cases X with x X', {rw com'_nil_left, apply nil_subseq}, {cases Y with y Y', {rw com'_nil_right, apply nil_subseq}, {change subseq (com' (x::X') (y::Y')) (x::X'), unfold com', unfold com, cases decidable.em (x=y) with hxy hnxy, {rw if_pos hxy, unfold subseq, apply or.intro_left, apply and.intro, refl, apply hind (X', Y'), assert hlXY'' : pair_length (X', Y') = n - 1, revert hlZ, unfold pair_length, change length (x::X') + length (y::Y') = n + 1 → length X' + length Y' = n - 1, unfold length, intro h1, assert h2 : length X' + 1 + length Y' = n, revert h1, rw -add_assoc, apply nat.add_right_cancel, rw -h2, rw add_assoc, rw (add_comm 1 (length Y')), rw -add_assoc, trivial, rw hlXY'', rw sub_one, rw pred_le_iff_true, trivial}, {rw if_neg hnxy, change subseq (longer (com' (x::X') Y') (com' X' (y::Y'))) (x::X'), unfold longer, cases decidable.em (length (com' (x::X') Y') ≤ length (com' X' (y::Y'))), {rw if_pos a, apply subseq_trans, apply hind (X', (y::Y')), apply le_of_eq, revert hlZ, unfold pair_length, unfold length, simp, rw add_comm, apply nat.add_right_cancel, apply tail_subseq}, {rw if_neg a, apply hind ((x::X'), Y'), apply le_of_eq, revert hlZ, unfold pair_length, unfold length, rw -add_assoc, apply add_right_cancel}, }, }, }, }, apply funcToNat_strong_ind H0 Hn end lemma com'_implies_subseq_right_prod (Z : list nat × list nat) : subseq (com' (fst Z) (snd Z)) (snd Z) := begin assert H0 : ∀ Z : list ℕ × list ℕ, pair_length Z = 0 → subseq (com' (fst Z) (snd Z)) (snd Z), intros Z1 hlZ, cases Z1 with X Y, assert h: X = [], apply eq_nil_of_length_eq_zero, apply eq_zero_of_add_eq_zero_right hlZ, rw h, rw com'_nil_left, apply nil_subseq, assert Hn : ∀ n : ℕ, (∀ Z : list ℕ × list ℕ, pair_length Z ≤ n → subseq (com' (fst Z) (snd Z)) (snd Z)) → (∀ Z : list ℕ × list ℕ, pair_length Z = n+1 → subseq (com' (fst Z) (snd Z)) (snd Z)), {intros n hind Z hlZ, cases Z with X Y, cases X with x X', {rw com'_nil_left, apply nil_subseq}, {cases Y with y Y', {rw com'_nil_right, apply nil_subseq}, {change subseq (com' (x::X') (y::Y')) (y::Y'), unfold com', unfold com, cases decidable.em (x=y) with hxy hnxy, {rw if_pos hxy, unfold subseq, apply or.intro_left, apply and.intro, apply hxy, apply hind (X', Y'), assert hlXY'' : pair_length (X', Y') = n - 1, revert hlZ, unfold pair_length, change length (x::X') + length (y::Y') = n + 1 → length X' + length Y' = n - 1, unfold length, intro h1, assert h2 : length X' + 1 + length Y' = n, revert h1, rw -add_assoc, apply nat.add_right_cancel, rw -h2, rw add_assoc, rw (add_comm 1 (length Y')), rw -add_assoc, trivial, rw hlXY'', rw sub_one, rw pred_le_iff_true, trivial}, {rw if_neg hnxy, change subseq (longer (com' (x::X') Y') (com' X' (y::Y'))) (y::Y'), unfold longer, cases decidable.em (length (com' (x::X') Y') ≤ length (com' X' (y::Y'))), {rw if_pos a, apply hind (X', (y::Y')), apply le_of_eq, revert hlZ, unfold pair_length, unfold length, simp, rw add_comm, apply nat.add_right_cancel}, {rw if_neg a, apply subseq_trans, apply hind ((x::X'), Y'), apply le_of_eq, revert hlZ, unfold pair_length, unfold length, rw -add_assoc, apply add_right_cancel, apply tail_subseq}, }, }, }, }, apply funcToNat_strong_ind H0 Hn end lemma com'_implies_subseq_left (X Y : list nat) : subseq (com' X Y) X := begin apply com'_implies_subseq_left_prod (X, Y) end lemma com'_implies_subseq_right (X Y : list nat) : subseq (com' X Y) Y := begin apply com'_implies_subseq_right_prod (X, Y) end lemma com'_implies_com_subseq (X Y : list nat) : com_subseq (com' X Y) X Y := begin apply and.intro, apply com'_implies_subseq_left, apply com'_implies_subseq_right end end list
abc03987a4a7ca07f3fdf5e5717918483e7d855d
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/polynomial/mirror.lean
5564f7f5247fdf5fc647a91b1a5a04164909a349
[ "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
7,465
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import data.polynomial.ring_division /-! # "Mirror" of a univariate polynomial In this file we define `polynomial.mirror`, a variant of `polynomial.reverse`. The difference between `reverse` and `mirror` is that `reverse` will decrease the degree if the polynomial is divisible by `X`. We also define `polynomial.norm2`, which is the sum of the squares of the coefficients of a polynomial. It is also a coefficient of `p * p.mirror`. ## Main definitions - `polynomial.mirror` - `polynomial.norm2` ## Main results - `polynomial.mirror_mul_of_domain`: `mirror` preserves multiplication. - `polynomial.irreducible_of_mirror`: an irreducibility criterion involving `mirror` - `polynomial.norm2_eq_mul_reverse_coeff`: `norm2` is a coefficient of `p * p.mirror` -/ namespace polynomial variables {R : Type*} [semiring R] (p : polynomial R) section mirror /-- mirror of a polynomial: reverses the coefficients while preserving `polynomial.nat_degree` -/ noncomputable def mirror := p.reverse * X ^ p.nat_trailing_degree @[simp] lemma mirror_zero : (0 : polynomial R).mirror = 0 := by simp [mirror] lemma mirror_monomial (n : ℕ) (a : R) : (monomial n a).mirror = (monomial n a) := begin by_cases ha : a = 0, { rw [ha, monomial_zero_right, mirror_zero] }, { rw [mirror, reverse, nat_degree_monomial n a ha, nat_trailing_degree_monomial ha, ←C_mul_X_pow_eq_monomial, reflect_C_mul_X_pow, rev_at_le (le_refl n), tsub_self, pow_zero, mul_one] }, end lemma mirror_C (a : R) : (C a).mirror = C a := mirror_monomial 0 a lemma mirror_X : X.mirror = (X : polynomial R) := mirror_monomial 1 (1 : R) lemma mirror_nat_degree : p.mirror.nat_degree = p.nat_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, by_cases hR : nontrivial R, { haveI := hR, rw [mirror, nat_degree_mul', reverse_nat_degree, nat_degree_X_pow, tsub_add_cancel_of_le p.nat_trailing_degree_le_nat_degree], rwa [leading_coeff_X_pow, mul_one, reverse_leading_coeff, ne, trailing_coeff_eq_zero] }, { haveI := not_nontrivial_iff_subsingleton.mp hR, exact congr_arg nat_degree (subsingleton.elim p.mirror p) }, end lemma mirror_nat_trailing_degree : p.mirror.nat_trailing_degree = p.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, { rw [mirror, nat_trailing_degree_mul_X_pow ((mt reverse_eq_zero.mp) hp), reverse_nat_trailing_degree, zero_add] }, end lemma coeff_mirror (n : ℕ) : p.mirror.coeff n = p.coeff (rev_at (p.nat_degree + p.nat_trailing_degree) n) := begin by_cases h2 : p.nat_degree < n, { rw [coeff_eq_zero_of_nat_degree_lt (by rwa mirror_nat_degree)], by_cases h1 : n ≤ p.nat_degree + p.nat_trailing_degree, { rw [rev_at_le h1, coeff_eq_zero_of_lt_nat_trailing_degree], exact (tsub_lt_iff_left h1).mpr (nat.add_lt_add_right h2 _) }, { rw [←rev_at_fun_eq, rev_at_fun, if_neg h1, coeff_eq_zero_of_nat_degree_lt h2] } }, rw not_lt at h2, rw [rev_at_le (h2.trans (nat.le_add_right _ _))], by_cases h3 : p.nat_trailing_degree ≤ n, { rw [←tsub_add_eq_add_tsub h2, ←tsub_tsub_assoc h2 h3, mirror, coeff_mul_X_pow', if_pos h3, coeff_reverse, rev_at_le (tsub_le_self.trans h2)] }, rw not_le at h3, rw coeff_eq_zero_of_nat_degree_lt (lt_tsub_iff_right.mpr (nat.add_lt_add_left h3 _)), exact coeff_eq_zero_of_lt_nat_trailing_degree (by rwa mirror_nat_trailing_degree), end --TODO: Extract `finset.sum_range_rev_at` lemma. lemma mirror_eval_one : p.mirror.eval 1 = p.eval 1 := begin simp_rw [eval_eq_finset_sum, one_pow, mul_one, mirror_nat_degree], refine finset.sum_bij_ne_zero _ _ _ _ _, { exact λ n hn hp, rev_at (p.nat_degree + p.nat_trailing_degree) n }, { intros n hn hp, rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right, ←mirror_nat_trailing_degree], exact nat_trailing_degree_le_of_ne_zero hp }, { exact λ n₁ n₂ hn₁ hp₁ hn₂ hp₂ h, by rw [←@rev_at_invol _ n₁, h, rev_at_invol] }, { intros n hn hp, use rev_at (p.nat_degree + p.nat_trailing_degree) n, refine ⟨_, _, rev_at_invol.symm⟩, { rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right], exact nat_trailing_degree_le_of_ne_zero hp }, { change p.mirror.coeff _ ≠ 0, rwa [coeff_mirror, rev_at_invol] } }, { exact λ n hn hp, p.coeff_mirror n }, end lemma mirror_mirror : p.mirror.mirror = p := polynomial.ext (λ n, by rw [coeff_mirror, coeff_mirror, mirror_nat_degree, mirror_nat_trailing_degree, rev_at_invol]) lemma mirror_eq_zero : p.mirror = 0 ↔ p = 0 := ⟨λ h, by rw [←p.mirror_mirror, h, mirror_zero], λ h, by rw [h, mirror_zero]⟩ lemma mirror_trailing_coeff : p.mirror.trailing_coeff = p.leading_coeff := by rw [leading_coeff, trailing_coeff, mirror_nat_trailing_degree, coeff_mirror, rev_at_le (nat.le_add_left _ _), add_tsub_cancel_right] lemma mirror_leading_coeff : p.mirror.leading_coeff = p.trailing_coeff := by rw [←p.mirror_mirror, mirror_trailing_coeff, p.mirror_mirror] lemma mirror_mul_of_domain {R : Type*} [ring R] [is_domain R] (p q : polynomial R) : (p * q).mirror = p.mirror * q.mirror := begin by_cases hp : p = 0, { rw [hp, zero_mul, mirror_zero, zero_mul] }, by_cases hq : q = 0, { rw [hq, mul_zero, mirror_zero, mul_zero] }, rw [mirror, mirror, mirror, reverse_mul_of_domain, nat_trailing_degree_mul hp hq, pow_add], rw [mul_assoc, ←mul_assoc q.reverse], conv_lhs { congr, skip, congr, rw [←X_pow_mul] }, repeat { rw [mul_assoc], }, end lemma mirror_smul {R : Type*} [ring R] [is_domain R] (p : polynomial R) (a : R) : (a • p).mirror = a • p.mirror := by rw [←C_mul', ←C_mul', mirror_mul_of_domain, mirror_C] lemma mirror_neg {R : Type*} [ring R] (p : polynomial R) : (-p).mirror = -(p.mirror) := by rw [mirror, mirror, reverse_neg, nat_trailing_degree_neg, neg_mul_eq_neg_mul] lemma irreducible_of_mirror {R : Type*} [comm_ring R] [is_domain R] {f : polynomial R} (h1 : ¬ is_unit f) (h2 : ∀ k, f * f.mirror = k * k.mirror → k = f ∨ k = -f ∨ k = f.mirror ∨ k = -f.mirror) (h3 : ∀ g, g ∣ f → g ∣ f.mirror → is_unit g) : irreducible f := begin split, { exact h1 }, { intros g h fgh, let k := g * h.mirror, have key : f * f.mirror = k * k.mirror, { rw [fgh, mirror_mul_of_domain, mirror_mul_of_domain, mirror_mirror, mul_assoc, mul_comm h, mul_comm g.mirror, mul_assoc, ←mul_assoc] }, have g_dvd_f : g ∣ f, { rw fgh, exact dvd_mul_right g h }, have h_dvd_f : h ∣ f, { rw fgh, exact dvd_mul_left h g }, have g_dvd_k : g ∣ k, { exact dvd_mul_right g h.mirror }, have h_dvd_k_rev : h ∣ k.mirror, { rw [mirror_mul_of_domain, mirror_mirror], exact dvd_mul_left h g.mirror }, have hk := h2 k key, rcases hk with hk | hk | hk | hk, { exact or.inr (h3 h h_dvd_f (by rwa ← hk)) }, { exact or.inr (h3 h h_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, mirror_neg, dvd_neg])) }, { exact or.inl (h3 g g_dvd_f (by rwa ← hk)) }, { exact or.inl (h3 g g_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, dvd_neg])) } }, end end mirror end polynomial
27f95fdc5a9ef86b4717aba2a4c2f684986b98ef
fd71e7836e9a5d14548f6d3291653cbb6c608dbe
/src/test/slim_check/liftable.lean
2e29b780a6d59fe113e6db4570b7ba8ee05d2340
[]
no_license
cipher1024/slim_check
382c80a98aed105a97eeac84f590a06dca4d8c7d
5969b7f72e01fdd46f2502ed0cbf69c0699061d4
refs/heads/master
1,625,514,334,828
1,574,118,572,000
1,574,118,572,000
101,538,155
2
1
null
null
null
null
UTF-8
Lean
false
false
4,048
lean
import data.equiv.basic import tactic universes u₀ u₁ v₀ v₁ v₂ w w₀ w₁ class liftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) := (up {} : Π {α β}, α ≃ β → f α → g β) (down {} : Π {α β}, α ≃ β → g β → f α) (up_down : ∀ {α β} (F : α ≃ β) (x : g β), up F (down F x) = x) (down_up : ∀ {α β} (F : α ≃ β) (x : f α), down F (up F x) = x) attribute [simp] liftable.up_down liftable.down_up namespace liftable @[reducible] def up' {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [liftable f g] {α} : f α → g (ulift α) := liftable.up equiv.ulift.symm @[reducible] def down' {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [liftable f g] {α} : g (ulift α) → f α := liftable.down equiv.ulift.symm end liftable open ulift protected lemma prod.map_map {α α' α'' β β' β''} (x : α × β) (f : α → α') (f' : α' → α'') (g : β → β') (g' : β' → β'') : prod.map f' g' (prod.map f g x) = prod.map (f' ∘ f) (g' ∘ g) x := by cases x; refl protected lemma prod.id_map {α β} (x : α × β) : prod.map (λ x, x) (λ x, x) x = x := by cases x; refl instance : liftable id id := { up := λ _ _ F, F , down := λ _ _ F, F.symm , up_down := by intros; simp , down_up := by intros; simp } def state_t.liftable' {s s' m m'} [functor m'] [functor m] [is_lawful_functor m'] [is_lawful_functor m] [liftable m m'] (F : s ≃ s') : liftable (state_t s m) (state_t s' m') := { up := λ _ _ G ⟨ f ⟩, ⟨ λ s, liftable.up (equiv.prod_congr G F) (f $ F.symm s) ⟩ , down := λ _ _ G ⟨ g ⟩, ⟨ λ s, liftable.down (equiv.prod_congr G F) $ g (F s) ⟩ , up_down := by { rintros α β G ⟨ f ⟩, simp! } , down_up := by { rintros α β G ⟨ g ⟩, simp! [map_map,function.comp] } } instance {s m m'} [functor m'] [functor m] [is_lawful_functor m'] [is_lawful_functor m] [liftable m m'] : liftable (state_t s m) (state_t (ulift s) m') := state_t.liftable' equiv.ulift.symm def reader_t.liftable' {s s' m m'} [liftable m m'] (F : s ≃ s') : liftable (reader_t s m) (reader_t s' m') := { up := λ _ _ G ⟨ f ⟩, ⟨ λ s, liftable.up G (f $ F.symm s) ⟩ , down := λ _ _ G ⟨ g ⟩, ⟨ λ s, liftable.down G $ g $ F s ⟩ , up_down := by { rintros α β G ⟨ f ⟩, simp! } , down_up := by { rintros α β G ⟨ g ⟩, simp! [map_map,function.comp] } } instance {s m m'} [liftable m m'] : liftable (reader_t s m) (reader_t (ulift s) m') := reader_t.liftable' equiv.ulift.symm -- namespace liftable -- variables {f : Type (max u₀ w) → Type u₁} {g : Type (max (max u₀ w) v₀) → Type v₁} -- variables [liftable f g] [functor g] -- variable {α : Type w} -- open functor -- def up' (x : f (ulift.{u₀} α)) : g (ulift.{max u₀ v₀} α) := -- map (ulift.up ∘ ulift.down ∘ ulift.down) $ up x -- def down' (x : g (ulift.{max u₀ v₀} α)) : f (ulift.{u₀} α) := -- down $ map (ulift.up ∘ ulift.up ∘ ulift.down) x -- variables [is_lawful_functor g] -- lemma up_down' : ∀ (x : g (ulift.{max u₀ v₀} α)), up' (down' x : f (ulift.{u₀} α)) = x := -- by intros; simp [up',down',map_map,function.comp,ulift.up_down] -- lemma down_up' : ∀ (x : f (ulift.{u₀} α)), down' (up' x : g (ulift.{max u₀ v₀} α)) = x := -- by intros; simp [up',down',map_map,function.comp,ulift.up_down] -- end liftable section trans open liftable -- def liftable.trans -- {f : Type u₀ → Type u₁} -- {g : Type v₀ → Type v₁} -- {h : Type w₀ → Type w₁} -- [functor h] [is_lawful_functor h] -- (_ : liftable f g) -- (_ : liftable g h) : -- liftable f h := -- by refine -- { up := λ α β G, (up' : g (ulift α) → h (ulift.{max v₀ w} α)) ∘ (up : f α → g (ulift α)), -- down := λ α β G, (down : g (ulift α) → f α) ∘ (down' : h (ulift.{max v₀ w} α) → g (ulift α)) , -- .. }; -- intros; simp [function.comp,up_down',down_up'] end trans
dddf5c377c64adb4706b6762ec7ba3f32135db6c
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/category/basic.lean
c44fccb3afd461ed8ebd243850a020b5a936c9ae
[ "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
2,030
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn -/ open eq eq.ops structure category [class] (ob : Type) : Type := (hom : ob → ob → Type) (comp : Π⦃a b c : ob⦄, hom b c → hom a b → hom a c) (ID : Π (a : ob), hom a a) (assoc : Π ⦃a b c d : ob⦄ (h : hom c d) (g : hom b c) (f : hom a b), comp h (comp g f) = comp (comp h g) f) (id_left : Π ⦃a b : ob⦄ (f : hom a b), comp !ID f = f) (id_right : Π ⦃a b : ob⦄ (f : hom a b), comp f !ID = f) attribute category [multiple_instances] namespace category variables {ob : Type} [C : category ob] variables {a b c d : ob} include C definition compose := @comp ob _ definition id [reducible] {a : ob} : hom a a := ID a infixr `∘` := comp infixl `⟶`:25 := hom -- input ⟶ using \--> (this is a different arrow than \-> (→)) variables {h : hom c d} {g : hom b c} {f : hom a b} {i : hom a a} --the following is the only theorem for which "include C" is necessary if C is a variable (why?) theorem id_compose (a : ob) : (ID a) ∘ id = id := !id_left theorem left_id_unique (H : Π{b} {f : hom b a}, i ∘ f = f) : i = id := calc i = i ∘ id : id_right ... = id : H theorem right_id_unique (H : Π{b} {f : hom a b}, f ∘ i = f) : i = id := calc i = id ∘ i : id_left ... = id : H end category inductive Category : Type := mk : Π (ob : Type), category ob → Category namespace category definition Mk {ob} (C) : Category := Category.mk ob C definition MK (a b c d e f g) : Category := Category.mk a (category.mk b c d e f g) definition objects [coercion] [reducible] (C : Category) : Type := Category.rec (fun c s, c) C definition category_instance [instance] [coercion] (C : Category) : category (objects C) := Category.rec (fun c s, s) C end category open category theorem Category.equal (C : Category) : Category.mk C C = C := Category.rec (λ ob c, rfl) C
d7f2222e6b5e5d3b4a31983177415d60bcb34788
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/linear_algebra/linear_independent.lean
4ce340a67e92809cf7f58353cbdca21bd80f05c9
[ "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
56,531
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp, Anne Baanen -/ import linear_algebra.finsupp import linear_algebra.prod import data.equiv.fin import set_theory.cardinal /-! # Linear independence This file defines linear independence in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define `linear_independent R v` as `ker (finsupp.total ι M R v) = ⊥`. Here `finsupp.total` is the linear map sending a function `f : ι →₀ R` with finite support to the linear combination of vectors from `v` with these coefficients. Then we prove that several other statements are equivalent to this one, including injectivity of `finsupp.total ι M R v` and some versions with explicitly written linear combinations. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. ## Main statements We prove several specialized tests for linear independence of families of vectors and of sets of vectors. * `fintype.linear_independent_iff`: if `ι` is a finite type, then any function `f : ι → R` has finite support, so we can reformulate the statement using `∑ i : ι, f i • v i` instead of a sum over an auxiliary `s : finset ι`; * `linear_independent_empty_type`: a family indexed by an empty type is linearly independent; * `linear_independent_unique_iff`: if `ι` is a singleton, then `linear_independent K v` is equivalent to `v (default ι) ≠ 0`; * linear_independent_option`, `linear_independent_sum`, `linear_independent_fin_cons`, `linear_independent_fin_succ`: type-specific tests for linear independence of families of vector fields; * `linear_independent_insert`, `linear_independent_union`, `linear_independent_pair`, `linear_independent_singleton`: linear independence tests for set operations. In many cases we additionally provide dot-style operations (e.g., `linear_independent.union`) to make the linear independence tests usable as `hv.insert ha` etc. We also prove that, when working over a field, any family of vectors includes a linear independent subfamily spanning the same subspace. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence -/ noncomputable theory open function set submodule open_locale classical big_operators universes u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} variables [semiring R] [add_comm_monoid M] [add_comm_monoid M'] [add_comm_monoid M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} variables (R) (v) /-- `linear_independent R v` states the family of vectors `v` is linearly independent over `R`. -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_independent_iff'' : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R) (hg : ∀ i ∉ s, g i = 0), ∑ i in s, g i • v i = 0 → ∀ i, g i = 0 := linear_independent_iff'.trans ⟨λ H s g hg hv i, if his : i ∈ s then H s g hv i his else hg i his, λ H s g hg i hi, by { convert H s (λ j, if j ∈ s then g j else 0) (λ j hj, if_neg hj) (by simp_rw [ite_smul, zero_smul, finset.sum_extend_by_zero, hg]) i, exact (if_pos hi).symm }⟩ theorem linear_dependent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, (∑ i in s, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, not_forall], end theorem fintype.linear_independent_iff [fintype ι] : linear_independent R v ↔ ∀ g : ι → R, ∑ i, g i • v i = 0 → ∀ i, g i = 0 := begin refine ⟨λ H g, by simpa using linear_independent_iff'.1 H finset.univ g, λ H, linear_independent_iff''.2 $ λ s g hg hs i, H _ _ _⟩, rw ← hs, refine (finset.sum_subset (finset.subset_univ _) (λ i _ hi, _)).symm, rw [hg i hi, zero_smul] end /-- A finite family of vectors `v i` is linear independent iff the linear map that sends `c : ι → R` to `∑ i, c i • v i` has the trivial kernel. -/ theorem fintype.linear_independent_iff' [fintype ι] : linear_independent R v ↔ (linear_map.lsum R (λ i : ι, R) ℕ (λ i, linear_map.id.smul_right (v i))).ker = ⊥ := by simp [fintype.linear_independent_iff, linear_map.ker_eq_bot', funext_iff] lemma linear_independent_empty_type [is_empty ι] : linear_independent R v := linear_independent_iff.mpr $ λ v hv, subsingleton.elim v 0 lemma linear_independent.ne_zero [nontrivial R] (i : ι) (hv : linear_independent R v) : v i ≠ 0 := λ h, @zero_ne_one R _ _ $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), { simp }, { simp [h] } end /-- A subfamily of a linearly independent family (i.e., a composition with an injective map) is a linearly independent family. -/ lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext x, convert h_map_domain x, rw [finsupp.map_domain_apply hf] end lemma linear_independent.coe_range (i : linear_independent R v) : linear_independent R (coe : range v → M) := by simpa using i.comp _ (range_splitting_injective v) /-- If `v` is a linearly independent family of vectors and the kernel of a linear map `f` is disjoint with the submodule spanned by the vectors of `v`, then `f ∘ v` is a linearly independent family of vectors. See also `linear_independent.map'` for a special case assuming `ker f = ⊥`. -/ lemma linear_independent.map (hv : linear_independent R v) {f : M →ₗ[R] M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_image_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv ⊢, rw [hv, le_bot_iff] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [finsupp.total_comp, @finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, linear_map.ker_comp, hf_inj], exact λ _, rfl, end /-- An injective linear map sends linearly independent families of vectors to linearly independent families of vectors. See also `linear_independent.map` for a more general statement. -/ lemma linear_independent.map' (hv : linear_independent R v) (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) := hv.map $ by simp [hf_inj] /-- If the image of a family of vectors under a linear map is linearly independent, then so is the original family. -/ lemma linear_independent.of_comp (f : M →ₗ[R] M') (hfv : linear_independent R (f ∘ v)) : linear_independent R v := linear_independent_iff'.2 $ λ s g hg i his, have ∑ (i : ι) in s, g i • f (v i) = 0, by simp_rw [← f.map_smul, ← f.map_sum, hg, f.map_zero], linear_independent_iff'.1 hfv s g this i his /-- If `f` is an injective linear map, then the family `f ∘ v` is linearly independent if and only if the family `v` is linearly independent. -/ protected lemma linear_map.linear_independent_iff (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) ↔ linear_independent R v := ⟨λ h, h.of_comp f, λ h, h.map $ by simp only [hf_inj, disjoint_bot_right]⟩ @[nontriviality] lemma linear_independent_of_subsingleton [subsingleton R] : linear_independent R v := linear_independent_iff.2 (λ l hl, subsingleton.elim _ _) theorem linear_independent_equiv (e : ι ≃ ι') {f : ι' → M} : linear_independent R (f ∘ e) ↔ linear_independent R f := ⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective, λ h, h.comp _ e.injective⟩ theorem linear_independent_equiv' (e : ι ≃ ι') {f : ι' → M} {g : ι → M} (h : f ∘ e = g) : linear_independent R g ↔ linear_independent R f := h ▸ linear_independent_equiv e theorem linear_independent_subtype_range {ι} {f : ι → M} (hf : injective f) : linear_independent R (coe : range f → M) ↔ linear_independent R f := iff.symm $ linear_independent_equiv' (equiv.of_injective f hf) rfl alias linear_independent_subtype_range ↔ linear_independent.of_subtype_range _ theorem linear_independent_image {ι} {s : set ι} {f : ι → M} (hf : set.inj_on f s) : linear_independent R (λ x : s, f x) ↔ linear_independent R (λ x : f '' s, (x : M)) := linear_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := linear_independent.of_comp (span R (range v)).subtype hs /-- See `linear_independent.fin_cons` for a family of elements in a vector space. -/ lemma linear_independent.fin_cons' {m : ℕ} (x : M) (v : fin m → M) (hli : linear_independent R v) (x_ortho : (∀ (c : R) (y : submodule.span R (set.range v)), c • x + y = (0 : M) → c = 0)) : linear_independent R (fin.cons x v : fin m.succ → M) := begin rw fintype.linear_independent_iff at hli ⊢, rintros g total_eq j, have zero_not_mem : (0 : fin m.succ) ∉ finset.univ.image (fin.succ : fin m → fin m.succ), { rw finset.mem_image, rintro ⟨x, hx, succ_eq⟩, exact fin.succ_ne_zero _ succ_eq }, simp only [submodule.coe_mk, fin.univ_succ, finset.sum_insert zero_not_mem, fin.cons_zero, fin.cons_succ, forall_true_iff, imp_self, fin.succ_inj, finset.sum_image] at total_eq, have : g 0 = 0, { refine x_ortho (g 0) ⟨∑ (i : fin m), g i.succ • v i, _⟩ total_eq, exact sum_mem _ (λ i _, smul_mem _ _ (subset_span ⟨i, rfl⟩)) }, refine fin.cases this (λ j, _) j, apply hli (λ i, g i.succ), simpa only [this, zero_smul, zero_add] using total_eq end /-- A set of linearly independent vectors in a module `M` over a semiring `K` is also linearly independent over a subring `R` of `K`. The implementation uses minimal assumptions about the relationship between `R`, `K` and `M`. The version where `K` is an `R`-algebra is `linear_independent.restrict_scalars_algebras`. -/ lemma linear_independent.restrict_scalars [semiring K] [smul_with_zero R K] [module K M] [is_scalar_tower R K M] (hinj : function.injective (λ r : R, r • (1 : K))) (li : linear_independent K v) : linear_independent R v := begin refine linear_independent_iff'.mpr (λ s g hg i hi, hinj (eq.trans _ (zero_smul _ _).symm)), refine (linear_independent_iff'.mp li : _) _ _ _ i hi, simp_rw [smul_assoc, one_smul], exact hg, end /-- Every finite subset of a linearly independent set is linearly independent. -/ lemma linear_independent_finset_map_embedding_subtype (s : set M) (li : linear_independent R (coe : s → M)) (t : finset s) : linear_independent R (coe : (finset.map (embedding.subtype s) t) → M) := begin let f : t.map (embedding.subtype s) → s := λ x, ⟨x.1, begin obtain ⟨x, h⟩ := x, rw [finset.mem_map] at h, obtain ⟨a, ha, rfl⟩ := h, simp only [subtype.coe_prop, embedding.coe_subtype], end⟩, convert linear_independent.comp li f _, rintros ⟨x, hx⟩ ⟨y, hy⟩, rw [finset.mem_map] at hx hy, obtain ⟨a, ha, rfl⟩ := hx, obtain ⟨b, hb, rfl⟩ := hy, simp only [imp_self, subtype.mk_eq_mk], end /-- If every finite set of linearly independent vectors has cardinality at most `n`, then the same is true for arbitrary sets of linearly independent vectors. -/ lemma linear_independent_bounded_of_finset_linear_independent_bounded {n : ℕ} (H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) : ∀ s : set M, linear_independent R (coe : s → M) → cardinal.mk s ≤ n := begin intros s li, apply cardinal.card_le_of, intro t, rw ← finset.card_map (embedding.subtype s), apply H, apply linear_independent_finset_map_embedding_subtype _ li, end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin simp only [linear_independent_iff, (∘), finsupp.mem_supported, finsupp.total_apply, set.subset_def, finset.mem_coe], split, { intros h l hl₁ hl₂, have := h (l.subtype_domain s) ((finsupp.sum_subtype_domain_index hl₁).trans hl₂), exact (finsupp.subtype_domain_eq_zero_iff hl₁).1 this }, { intros h l hl, refine finsupp.emb_domain_eq_zero.1 (h (l.emb_domain $ function.embedding.subtype s) _ _), { suffices : ∀ i hi, ¬l ⟨i, hi⟩ = 0 → i ∈ s, by simpa, intros, assumption }, { rwa [finsupp.emb_domain_eq_map_domain, finsupp.sum_map_domain_index], exacts [λ _, zero_smul _ _, λ _ _ _, add_smul _ _ _] } } end lemma linear_dependent_comp_subtype' {s : set ι} : ¬ linear_independent R (v ∘ coe : s → M) ↔ ∃ f : ι →₀ R, f ∈ finsupp.supported R R s ∧ finsupp.total ι M R v f = 0 ∧ f ≠ 0 := by simp [linear_independent_comp_subtype] /-- A version of `linear_dependent_comp_subtype'` with `finsupp.total` unfolded. -/ lemma linear_dependent_comp_subtype {s : set ι} : ¬ linear_independent R (v ∘ coe : s → M) ↔ ∃ f : ι →₀ R, f ∈ finsupp.supported R R s ∧ ∑ i in f.support, f i • v i = 0 ∧ f ≠ 0 := linear_dependent_comp_subtype' theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := hs variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { resetI, refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed (directed_comp.2 $ hs.directed_coe) (by simpa using h) end subtype end module /-! ### Properties which require `ring R` -/ section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} theorem linear_independent_iff_injective_total : linear_independent R v ↔ function.injective (finsupp.total ι M R v) := linear_independent_iff.trans (finsupp.total ι M R v).to_add_monoid_hom.injective_iff.symm alias linear_independent_iff_injective_total ↔ linear_independent.injective_total _ lemma linear_independent.injective [nontrivial R] (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { simp_rw [linear_map.map_sub, finsupp.total_apply], simp [hij] }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, simpa [finsupp.single_eq_single_iff] using h_single_eq end theorem linear_independent.to_subtype_range {ι} {f : ι → M} (hf : linear_independent R f) : linear_independent R (coe : range f → M) := begin nontriviality R, exact (linear_independent_subtype_range hf.injective).2 hf end theorem linear_independent.to_subtype_range' {ι} {f : ι → M} (hf : linear_independent R f) {t} (ht : range f = t) : linear_independent R (coe : t → M) := ht ▸ hf.to_subtype_range theorem linear_independent.image_of_comp {ι ι'} (s : set ι) (f : ι → ι') (g : ι' → M) (hs : linear_independent R (λ x : s, g (f x))) : linear_independent R (λ x : f '' s, g x) := begin nontriviality R, have : inj_on f s, from inj_on_iff_injective.2 hs.injective.of_comp, exact (linear_independent_equiv' (equiv.set.image_of_inj_on f s this) rfl).1 hs end theorem linear_independent.image {ι} {s : set ι} {f : ι → M} (hs : linear_independent R (λ x : s, f x)) : linear_independent R (λ x : f '' s, (x : M)) := by convert linear_independent.image_of_comp s f id hs lemma linear_independent.group_smul {G : Type*} [hG : group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] [smul_comm_class G R M] {v : ι → M} (hv : linear_independent R v) (w : ι → G) : linear_independent R (w • v) := begin rw linear_independent_iff'' at hv ⊢, intros s g hgs hsum i, refine (smul_eq_zero_iff_eq (w i)).1 _, refine hv s (λ i, w i • g i) (λ i hi, _) _ i, { dsimp only, exact (hgs i hi).symm ▸ smul_zero _ }, { rw [← hsum, finset.sum_congr rfl _], intros, erw [pi.smul_apply, smul_assoc, smul_comm] }, end -- This lemma cannot be proved with `linear_independent.group_smul` since the action of -- `units R` on `R` is not commutative. lemma linear_independent.units_smul {v : ι → M} (hv : linear_independent R v) (w : ι → units R) : linear_independent R (w • v) := begin rw linear_independent_iff'' at hv ⊢, intros s g hgs hsum i, rw ← (w i).mul_left_eq_zero, refine hv s (λ i, g i • w i) (λ i hi, _) _ i, { dsimp only, exact (hgs i hi).symm ▸ zero_smul _ _ }, { rw [← hsum, finset.sum_congr rfl _], intros, erw [pi.smul_apply, smul_assoc], refl } end section maximal universes v w /-- A linearly independent family is maximal if there is no strictly larger linearly independent family. -/ @[nolint unused_arguments] def linear_independent.maximal {ι : Type w} {R : Type u} [semiring R] {M : Type v} [add_comm_monoid M] [module R M] {v : ι → M} (i : linear_independent R v) : Prop := ∀ (s : set M) (i' : linear_independent R (coe : s → M)) (h : range v ≤ s), range v = s /-- An alternative characterization of a maximal linearly independent family, quantifying over types (in the same universe as `M`) into which the indexing family injects. -/ lemma linear_independent.maximal_iff {ι : Type w} {R : Type u} [ring R] [nontrivial R] {M : Type v} [add_comm_group M] [module R M] {v : ι → M} (i : linear_independent R v) : i.maximal ↔ ∀ (κ : Type v) (w : κ → M) (i' : linear_independent R w) (j : ι → κ) (h : w ∘ j = v), surjective j := begin fsplit, { rintros p κ w i' j rfl, specialize p (range w) i'.coe_range (range_comp_subset_range _ _), rw [range_comp, ←@image_univ _ _ w] at p, exact range_iff_surjective.mp (image_injective.mpr i'.injective p), }, { intros p w i' h, specialize p w (coe : w → M) i' (λ i, ⟨v i, range_subset_iff.mp h i⟩) (by { ext, simp, }), have q := congr_arg (λ s, (coe : w → M) '' s) p.range_eq, dsimp at q, rw [←image_univ, image_image] at q, simpa using q, }, end end maximal /-- Linear independent families are injective, even if you multiply either side. -/ lemma linear_independent.eq_of_smul_apply_eq_smul_apply {M : Type*} [add_comm_group M] [module R M] {v : ι → M} (li : linear_independent R v) (c d : R) (i j : ι) (hc : c ≠ 0) (h : c • v i = d • v j) : i = j := begin let l : ι →₀ R := finsupp.single i c - finsupp.single j d, have h_total : finsupp.total ι M R v l = 0, { simp_rw [linear_map.map_sub, finsupp.total_apply], simp [h] }, have h_single_eq : finsupp.single i c = finsupp.single j d, { rw linear_independent_iff at li, simp [eq_add_of_sub_eq' (li l h_total)] }, rcases (finsupp.single_eq_single_iff _ _ _ _).mp h_single_eq with ⟨this, _⟩ | ⟨hc, _⟩, { exact this }, { contradiction }, end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ lemma linear_independent.disjoint_span_image (hv : linear_independent R v) {s t : set ι} (hs : disjoint s t) : disjoint (submodule.span R $ v '' s) (submodule.span R $ v '' t) := begin simp only [disjoint_def, finsupp.mem_span_image_iff_total], rintros _ ⟨l₁, hl₁, rfl⟩ ⟨l₂, hl₂, H⟩, rw [hv.injective_total.eq_iff] at H, subst l₂, have : l₁ = 0 := finsupp.disjoint_supported_supported hs (submodule.mem_inf.2 ⟨hl₁, hl₂⟩), simp [this] end lemma linear_independent.not_mem_span_image [nontrivial R] (hv : linear_independent R v) {s : set ι} {x : ι} (h : x ∉ s) : v x ∉ submodule.span R (v '' s) := begin have h' : v x ∈ submodule.span R (v '' {x}), { rw set.image_singleton, exact mem_span_singleton_self (v x), }, intro w, apply linear_independent.ne_zero x hv, refine disjoint_def.1 (hv.disjoint_span_image _) (v x) h' w, simpa using h, end lemma linear_independent.total_ne_of_not_mem_support [nontrivial R] (hv : linear_independent R v) {x : ι} (f : ι →₀ R) (h : x ∉ f.support) : finsupp.total ι M R v f ≠ v x := begin replace h : x ∉ (f.support : set ι) := h, have p := hv.not_mem_span_image h, intro w, rw ←w at p, rw finsupp.span_image_eq_map_total at p, simp only [not_exists, not_and, mem_map] at p, exact p f (f.mem_supported_support R) rfl, end lemma linear_independent_sum {v : ι ⊕ ι' → M} : linear_independent R v ↔ linear_independent R (v ∘ sum.inl) ∧ linear_independent R (v ∘ sum.inr) ∧ disjoint (submodule.span R (range (v ∘ sum.inl))) (submodule.span R (range (v ∘ sum.inr))) := begin rw [range_comp v, range_comp v], refine ⟨λ h, ⟨h.comp _ sum.inl_injective, h.comp _ sum.inr_injective, h.disjoint_span_image is_compl_range_inl_range_inr.1⟩, _⟩, rintro ⟨hl, hr, hlr⟩, rw [linear_independent_iff'] at *, intros s g hg i hi, have : ∑ i in s.preimage sum.inl (sum.inl_injective.inj_on _), (λ x, g x • v x) (sum.inl i) + ∑ i in s.preimage sum.inr (sum.inr_injective.inj_on _), (λ x, g x • v x) (sum.inr i) = 0, { rw [finset.sum_preimage', finset.sum_preimage', ← finset.sum_union, ← finset.filter_or], { simpa only [← mem_union, range_inl_union_range_inr, mem_univ, finset.filter_true] }, { exact finset.disjoint_filter.2 (λ x hx, disjoint_left.1 is_compl_range_inl_range_inr.1) } }, { rw ← eq_neg_iff_add_eq_zero at this, rw [disjoint_def'] at hlr, have A := hlr _ (sum_mem _ $ λ i hi, _) _ (neg_mem _ $ sum_mem _ $ λ i hi, _) this, { cases i with i i, { exact hl _ _ A i (finset.mem_preimage.2 hi) }, { rw [this, neg_eq_zero] at A, exact hr _ _ A i (finset.mem_preimage.2 hi) } }, { exact smul_mem _ _ (subset_span ⟨sum.inl i, mem_range_self _, rfl⟩) }, { exact smul_mem _ _ (subset_span ⟨sum.inr i, mem_range_self _, rfl⟩) } } end lemma linear_independent.sum_type {v' : ι' → M} (hv : linear_independent R v) (hv' : linear_independent R v') (h : disjoint (submodule.span R (range v)) (submodule.span R (range v'))) : linear_independent R (sum.elim v v') := linear_independent_sum.2 ⟨hv, hv', h⟩ lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := (hs.sum_type ht $ by simpa).to_subtype_range' $ by simp lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, { apply directed_of_sup, exact (λ t₁ t₂ ht, Union_subset_Union $ λ i, Union_subset_Union_const $ λ h, ht h) }, assume t, induction t using finset.induction_on with i s his ih, { refine (linear_independent_empty _ _).mono _, simp }, { rw [finset.set_bUnion_insert], refine (hl _).union ih _, refine (hd i s s.finite_to_set his).mono_right _, simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), exact λ i, ⟨i, le_rfl⟩ } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin nontriviality R, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero _ h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ @[simps] def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw [← linear_map.ker_eq_bot, linear_map.ker_cod_restrict], apply hv }, { rw [← linear_map.range_eq_top, linear_map.range_eq_map, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm @[simp] lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end lemma linear_independent.span_repr_eq [nontrivial R] (x) : span.repr R (set.range v) x = (hv.repr x).equiv_map_domain (equiv.of_injective _ hv.injective) := begin have p : (span.repr R (set.range v) x).equiv_map_domain (equiv.of_injective _ hv.injective).symm = hv.repr x, { apply (linear_independent.total_equiv hv).injective, ext, simp, }, ext ⟨_, ⟨i, rfl⟩⟩, simp [←p], end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_image_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_image_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ variable (R) lemma exists_maximal_independent' (s : ι → M) : ∃ I : set ι, linear_independent R (λ x : I, s x) ∧ ∀ J : set ι, I ⊆ J → linear_independent R (λ x : J, s x) → I = J := begin let indep : set ι → Prop := λ I, linear_independent R (s ∘ coe : I → M), let X := { I : set ι // indep I }, let r : X → X → Prop := λ I J, I.1 ⊆ J.1, have key : ∀ c : set X, zorn.chain r c → indep (⋃ (I : X) (H : I ∈ c), I), { intros c hc, dsimp [indep], rw [linear_independent_comp_subtype], intros f hsupport hsum, rcases eq_empty_or_nonempty c with rfl | ⟨a, hac⟩, { simpa using hsupport }, haveI : is_refl X r := ⟨λ _, set.subset.refl _⟩, obtain ⟨I, I_mem, hI⟩ : ∃ I ∈ c, (f.support : set ι) ⊆ I := finset.exists_mem_subset_of_subset_bUnion_of_directed_on hac hc.directed_on hsupport, exact linear_independent_comp_subtype.mp I.2 f hI hsum }, have trans : transitive r := λ I J K, set.subset.trans, obtain ⟨⟨I, hli : indep I⟩, hmax : ∀ a, r ⟨I, hli⟩ a → r a ⟨I, hli⟩⟩ := @zorn.exists_maximal_of_chains_bounded _ r (λ c hc, ⟨⟨⋃ I ∈ c, (I : set ι), key c hc⟩, λ I, set.subset_bUnion_of_mem⟩) trans, exact ⟨I, hli, λ J hsub hli, set.subset.antisymm hsub (hmax ⟨J, hli⟩ hsub)⟩, end lemma exists_maximal_independent (s : ι → M) : ∃ I : set ι, linear_independent R (λ x : I, s x) ∧ ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I) := begin classical, rcases exists_maximal_independent' R s with ⟨I, hIlinind, hImaximal⟩, use [I, hIlinind], intros i hi, specialize hImaximal (I ∪ {i}) (by simp), set J := I ∪ {i} with hJ, have memJ : ∀ {x}, x ∈ J ↔ x = i ∨ x ∈ I, by simp [hJ], have hiJ : i ∈ J := by simp, have h := mt hImaximal _, swap, { intro h2, rw h2 at hi, exact absurd hiJ hi }, obtain ⟨f, supp_f, sum_f, f_ne⟩ := linear_dependent_comp_subtype.mp h, have hfi : f i ≠ 0, { contrapose hIlinind, refine linear_dependent_comp_subtype.mpr ⟨f, _, sum_f, f_ne⟩, simp only [finsupp.mem_supported, hJ] at ⊢ supp_f, rintro x hx, refine (memJ.mp (supp_f hx)).resolve_left _, rintro rfl, exact hIlinind (finsupp.mem_support_iff.mp hx) }, use [f i, hfi], have hfi' : i ∈ f.support := finsupp.mem_support_iff.mpr hfi, rw [← finset.insert_erase hfi', finset.sum_insert (finset.not_mem_erase _ _), add_eq_zero_iff_eq_neg] at sum_f, rw sum_f, refine neg_mem _ (sum_mem _ (λ c hc, smul_mem _ _ (subset_span ⟨c, _, rfl⟩))), exact (memJ.mp (supp_f (finset.erase_subset _ _ hc))).resolve_left (finset.ne_of_mem_erase hc), end end repr lemma surjective_of_linear_independent_of_span [nontrivial R] (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) : surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl }, { exact f.injective } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype [nontrivial R] {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image_subtype {s : set M} {f : M →ₗ[R] M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [← @subtype.range_coe _ s] at hf_inj, refine (hs.map hf_inj).to_subtype_range' _, simp [set.range_comp f] end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := (hv.map' (inl R M M') ker_inl).sum_type (hv'.map' (inr R M M') ker_inr) $ begin refine is_compl_range_inl_inr.disjoint.mono _ _; simp only [span_le, range_coe, range_comp_subset_range], end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note -- <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [comm_ring L] [no_zero_divisors L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the -- monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : finset.sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [finset.sum_apply, finset.sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element -- of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span hl hsu htu, span_mono⟩ end module section nontrivial variables [ring R] [nontrivial R] [add_comm_group M] [add_comm_group M'] variables [module R M] [no_zero_smul_divisors R M] [module R M'] variables {v : ι → M} {s t : set M} {x y z : M} lemma linear_independent_unique_iff (v : ι → M) [unique ι] : linear_independent R v ↔ v (default ι) ≠ 0 := begin simp only [linear_independent_iff, finsupp.total_unique, smul_eq_zero], refine ⟨λ h hv, _, λ hv l hl, finsupp.unique_ext $ hl.resolve_right hv⟩, have := h (finsupp.single (default ι) 1) (or.inr hv), exact one_ne_zero (finsupp.single_eq_zero.1 this) end alias linear_independent_unique_iff ↔ _ linear_independent_unique lemma linear_independent_singleton {x : M} (hx : x ≠ 0) : linear_independent R (λ x, x : ({x} : set M) → M) := linear_independent_unique coe hx end nontrivial /-! ### Properties which require `division_ring K` These can be considered generalizations of properties of linear independence in vector spaces. -/ section module variables [division_ring K] [add_comm_group V] [add_comm_group V'] variables [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton' x0] end lemma linear_independent_option' : linear_independent K (λ o, option.cases_on' o x v : option ι → V) ↔ linear_independent K v ∧ (x ∉ submodule.span K (range v)) := begin rw [← linear_independent_equiv (equiv.option_equiv_sum_punit ι).symm, linear_independent_sum, @range_unique _ punit, @linear_independent_unique_iff punit, disjoint_span_singleton], dsimp [(∘)], refine ⟨λ h, ⟨h.1, λ hx, h.2.1 $ h.2.2 hx⟩, λ h, ⟨h.1, _, λ hx, (h.2 hx).elim⟩⟩, rintro rfl, exact h.2 (zero_mem _) end lemma linear_independent.option (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (λ o, option.cases_on' o x v : option ι → V) := linear_independent_option'.2 ⟨hv, hx⟩ lemma linear_independent_option {v : option ι → V} : linear_independent K v ↔ linear_independent K (v ∘ coe : ι → V) ∧ v none ∉ submodule.span K (range (v ∘ coe : ι → V)) := by simp only [← linear_independent_option', option.cases_on'_none_coe] theorem linear_independent_insert' {ι} {s : set ι} {a : ι} {f : ι → V} (has : a ∉ s) : linear_independent K (λ x : insert a s, f x) ↔ linear_independent K (λ x : s, f x) ∧ f a ∉ submodule.span K (f '' s) := by { rw [← linear_independent_equiv ((equiv.option_equiv_sum_punit _).trans (equiv.set.insert has).symm), linear_independent_option], simp [(∘), range_comp f] } theorem linear_independent_insert (hxs : x ∉ s) : linear_independent K (λ b : insert x s, (b : V)) ↔ linear_independent K (λ b : s, (b : V)) ∧ x ∉ submodule.span K s := (@linear_independent_insert' _ _ _ _ _ _ _ _ id hxs).trans $ by simp lemma linear_independent_pair {x y : V} (hx : x ≠ 0) (hy : ∀ a : K, a • x ≠ y) : linear_independent K (coe : ({x, y} : set V) → V) := pair_comm y x ▸ (linear_independent_singleton hx).insert $ mt mem_span_singleton.1 (not_exists.2 hy) lemma linear_independent_fin_cons {n} {v : fin n → V} : linear_independent K (fin.cons x v : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := begin rw [← linear_independent_equiv (fin_succ_equiv n).symm, linear_independent_option], convert iff.rfl, { ext, -- TODO: why doesn't simp use `fin_succ_equiv_symm_coe` here? rw [comp_app, comp_app, fin_succ_equiv_symm_coe, fin.cons_succ] }, { ext, rw [comp_app, comp_app, fin_succ_equiv_symm_coe, fin.cons_succ] } end lemma linear_independent_fin_snoc {n} {v : fin n → V} : linear_independent K (fin.snoc v x : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := by rw [fin.snoc_eq_cons_rotate, linear_independent_equiv, linear_independent_fin_cons] /-- See `linear_independent.fin_cons'` for an uglier version that works if you only have a module over a semiring. -/ lemma linear_independent.fin_cons {n} {v : fin n → V} (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (fin.cons x v : fin (n + 1) → V) := linear_independent_fin_cons.2 ⟨hv, hx⟩ lemma linear_independent_fin_succ {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.tail v) ∧ v 0 ∉ submodule.span K (range $ fin.tail v) := by rw [← linear_independent_fin_cons, fin.cons_self_tail] lemma linear_independent_fin_succ' {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.init v) ∧ v (fin.last _) ∉ submodule.span K (range $ fin.init v) := by rw [← linear_independent_fin_snoc, fin.snoc_init_self] lemma linear_independent_fin2 {f : fin 2 → V} : linear_independent K f ↔ f 1 ≠ 0 ∧ ∀ a : K, a • f 1 ≠ f 0 := by rw [linear_independent_fin_succ, linear_independent_unique_iff, range_unique, mem_span_singleton, not_exists, show fin.tail f (default (fin 1)) = f 1, by rw ← fin.succ_zero_eq_one; refl] lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset_nonempty {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end /-- `linear_independent.extend` adds vectors to a linear independent set `s ⊆ t` until it spans all elements of `t`. -/ noncomputable def linear_independent.extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : set V := classical.some (exists_linear_independent hs hst) lemma linear_independent.extend_subset (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : hs.extend hst ⊆ t := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in hbt lemma linear_independent.subset_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : s ⊆ hs.extend hst := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in hsb lemma linear_independent.subset_span_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : t ⊆ span K (hs.extend hst) := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in htb lemma linear_independent.linear_independent_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : linear_independent K (coe : hs.extend hst → V) := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in hli variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ end module
6b43bd446be3ab1ce91df4f763cbe2d3831f3702
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/types/trunc.hlean
451de40388048b185adb75ba31e777fac20eb176
[ "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
47,529
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Properties of trunc_index, is_trunc, trunctype, trunc, and the pointed versions of these -/ -- NOTE: the fact that (is_trunc n A) is a mere proposition is proved in .prop_trunc import .pointed2 ..function algebra.order types.nat.order types.unit types.int.hott open eq sigma sigma.ops pi function equiv trunctype is_equiv prod pointed nat is_trunc algebra unit /- basic computation with ℕ₋₂, its operations and its order -/ namespace trunc_index definition minus_one_le_succ (n : ℕ₋₂) : -1 ≤ n.+1 := succ_le_succ (minus_two_le n) definition zero_le_of_nat (n : ℕ) : 0 ≤ of_nat n := succ_le_succ !minus_one_le_succ open decidable protected definition has_decidable_eq [instance] : Π(n m : ℕ₋₂), decidable (n = m) | has_decidable_eq -2 -2 := inl rfl | has_decidable_eq (n.+1) -2 := inr (by contradiction) | has_decidable_eq -2 (m.+1) := inr (by contradiction) | has_decidable_eq (n.+1) (m.+1) := match has_decidable_eq n m with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ n = succ m, by injection h with xeqy; exact absurd xeqy xney) end definition not_succ_le_minus_two {n : ℕ₋₂} (H : n .+1 ≤ -2) : empty := by cases H protected definition le_trans {n m k : ℕ₋₂} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k := begin induction H2 with k H2 IH, { exact H1}, { exact le.step IH} end definition le_of_succ_le_succ {n m : ℕ₋₂} (H : n.+1 ≤ m.+1) : n ≤ m := begin cases H with m H', { apply le.tr_refl}, { exact trunc_index.le_trans (le.step !le.tr_refl) H'} end theorem not_succ_le_self {n : ℕ₋₂} : ¬n.+1 ≤ n := begin induction n with n IH: intro H, { exact not_succ_le_minus_two H}, { exact IH (le_of_succ_le_succ H)} end protected definition le_antisymm {n m : ℕ₋₂} (H1 : n ≤ m) (H2 : m ≤ n) : n = m := begin induction H2 with n H2 IH, { reflexivity}, { exfalso, apply @not_succ_le_self n, exact trunc_index.le_trans H1 H2} end protected definition le_succ {n m : ℕ₋₂} (H1 : n ≤ m) : n ≤ m.+1 := le.step H1 protected definition self_le_succ (n : ℕ₋₂) : n ≤ n.+1 := le.step (trunc_index.le.tr_refl n) -- the order is total open sum protected theorem le_sum_le (n m : ℕ₋₂) : n ≤ m ⊎ m ≤ n := begin induction m with m IH, { exact inr !minus_two_le}, { cases IH with H H, { exact inl (trunc_index.le_succ H)}, { cases H with n' H, { exact inl !trunc_index.self_le_succ}, { exact inr (succ_le_succ H)}}} end end trunc_index open trunc_index definition linear_weak_order_trunc_index [trans_instance] [reducible] : linear_weak_order trunc_index := linear_weak_order.mk le trunc_index.le.tr_refl @trunc_index.le_trans @trunc_index.le_antisymm trunc_index.le_sum_le namespace trunc_index /- more theorems about truncation indices -/ definition zero_add (n : ℕ₋₂) : (0 : ℕ₋₂) + n = n := begin cases n with n, reflexivity, cases n with n, reflexivity, induction n with n IH, reflexivity, exact ap succ IH end definition add_zero (n : ℕ₋₂) : n + (0 : ℕ₋₂) = n := by reflexivity definition succ_add_nat (n : ℕ₋₂) (m : ℕ) : n.+1 + m = (n + m).+1 := by induction m with m IH; reflexivity; exact ap succ IH definition nat_add_succ (n : ℕ) (m : ℕ₋₂) : n + m.+1 = (n + m).+1 := begin cases m with m, reflexivity, cases m with m, reflexivity, induction m with m IH, reflexivity, exact ap succ IH end definition add_nat_succ (n : ℕ₋₂) (m : ℕ) : n + (nat.succ m) = (n + m).+1 := by reflexivity definition nat_succ_add (n : ℕ) (m : ℕ₋₂) : (nat.succ n) + m = (n + m).+1 := begin cases m with m, reflexivity, cases m with m, reflexivity, induction m with m IH, reflexivity, exact ap succ IH end definition sub_two_add_two (n : ℕ₋₂) : sub_two (add_two n) = n := begin induction n with n IH, { reflexivity}, { exact ap succ IH} end definition add_two_sub_two (n : ℕ) : add_two (sub_two n) = n := begin induction n with n IH, { reflexivity}, { exact ap nat.succ IH} end definition of_nat_add_plus_two_of_nat (n m : ℕ) : n +2+ m = of_nat (n + m + 2) := begin induction m with m IH, { reflexivity}, { exact ap succ IH} end definition of_nat_add_of_nat (n m : ℕ) : of_nat n + of_nat m = of_nat (n + m) := begin induction m with m IH, { reflexivity}, { exact ap succ IH} end definition succ_add_plus_two (n m : ℕ₋₂) : n.+1 +2+ m = (n +2+ m).+1 := begin induction m with m IH, { reflexivity}, { exact ap succ IH} end definition add_plus_two_succ (n m : ℕ₋₂) : n +2+ m.+1 = (n +2+ m).+1 := idp definition add_succ_succ (n m : ℕ₋₂) : n + m.+2 = n +2+ m := idp definition succ_add_succ (n m : ℕ₋₂) : n.+1 + m.+1 = n +2+ m := begin cases m with m IH, { reflexivity}, { apply succ_add_plus_two} end definition succ_succ_add (n m : ℕ₋₂) : n.+2 + m = n +2+ m := begin cases m with m IH, { reflexivity}, { exact !succ_add_succ ⬝ !succ_add_plus_two} end definition succ_sub_two (n : ℕ) : (nat.succ n).-2 = n.-2 .+1 := rfl definition sub_two_succ_succ (n : ℕ) : n.-2.+1.+1 = n := rfl definition succ_sub_two_succ (n : ℕ) : (nat.succ n).-2.+1 = n := rfl definition of_nat_add_two (n : ℕ₋₂) : of_nat (add_two n) = n.+2 := begin induction n with n IH, reflexivity, exact ap succ IH end lemma minus_two_add_plus_two (n : ℕ₋₂) : -2+2+n = n := by induction n with n p; reflexivity; exact ap succ p lemma add_plus_two_comm (n k : ℕ₋₂) : n +2+ k = k +2+ n := begin induction n with n IH, { exact minus_two_add_plus_two k }, { exact !succ_add_plus_two ⬝ ap succ IH} end lemma sub_one_add_plus_two_sub_one (n m : ℕ) : n.-1 +2+ m.-1 = of_nat (n + m) := begin induction m with m IH, { reflexivity }, { exact ap succ IH } end definition of_nat_le_of_nat {n m : ℕ} (H : n ≤ m) : (of_nat n ≤ of_nat m) := begin induction H with m H IH, { apply le.refl}, { exact trunc_index.le_succ IH} end definition sub_two_le_sub_two {n m : ℕ} (H : n ≤ m) : n.-2 ≤ m.-2 := begin induction H with m H IH, { apply le.refl}, { exact trunc_index.le_succ IH} end definition add_two_le_add_two {n m : ℕ₋₂} (H : n ≤ m) : add_two n ≤ add_two m := begin induction H with m H IH, { reflexivity}, { constructor, exact IH}, end definition le_of_sub_two_le_sub_two {n m : ℕ} (H : n.-2 ≤ m.-2) : n ≤ m := begin rewrite [-add_two_sub_two n, -add_two_sub_two m], exact add_two_le_add_two H, end definition le_of_of_nat_le_of_nat {n m : ℕ} (H : of_nat n ≤ of_nat m) : n ≤ m := begin apply le_of_sub_two_le_sub_two, exact le_of_succ_le_succ (le_of_succ_le_succ H) end protected definition of_nat_monotone {n k : ℕ} : n ≤ k → of_nat n ≤ of_nat k := begin intro H, induction H with k H K, { apply le.tr_refl }, { apply le.step K } end protected theorem succ_le_of_not_le {n m : ℕ₋₂} (H : ¬ n ≤ m) : m.+1 ≤ n := begin cases (le.total n m) with H2 H2, { exfalso, exact H H2}, { cases H2 with n' H2', { exfalso, exact H !le.refl}, { exact succ_le_succ H2'}} end definition trunc_index.decidable_le [instance] : Π(n m : ℕ₋₂), decidable (n ≤ m) := begin intro n, induction n with n IH: intro m, { left, apply minus_two_le}, cases m with m, { right, apply not_succ_le_minus_two}, cases IH m with H H, { left, apply succ_le_succ H}, right, intro H2, apply H, exact le_of_succ_le_succ H2 end protected definition pred [unfold 1] (n : ℕ₋₂) : ℕ₋₂ := begin cases n with n, exact -2, exact n end definition trunc_index_equiv_nat [constructor] : ℕ₋₂ ≃ ℕ := equiv.MK add_two sub_two add_two_sub_two sub_two_add_two definition is_set_trunc_index [instance] : is_set ℕ₋₂ := is_trunc_equiv_closed_rev 0 trunc_index_equiv_nat _ end trunc_index open trunc_index namespace is_trunc variables {A B : Type} {n : ℕ₋₂} /- closure properties of truncatedness -/ theorem is_trunc_is_embedding_closed (f : A → B) [Hf : is_embedding f] [HB : is_trunc n B] (Hn : -1 ≤ n) : is_trunc n A := begin induction n with n, {exfalso, exact not_succ_le_minus_two Hn}, {apply is_trunc_succ_intro, intro a a', exact is_trunc_is_equiv_closed_rev n (ap f) _ _ } end theorem is_trunc_is_retraction_closed (f : A → B) [Hf : is_retraction f] (n : ℕ₋₂) [HA : is_trunc n A] : is_trunc n B := begin revert A B f Hf HA, induction n with n IH, { intro A B f Hf HA, induction Hf with g ε, fapply is_contr.mk, { exact f (center A)}, { intro b, apply concat, { apply (ap f), exact (center_eq (g b))}, { apply ε}}}, { intro A B f Hf HA, induction Hf with g ε, apply is_trunc_succ_intro, intro b b', fapply (IH (g b = g b')), { intro q, exact ((ε b)⁻¹ ⬝ ap f q ⬝ ε b')}, { apply (is_retraction.mk (ap g)), { intro p, induction p, {rewrite [↑ap, con.left_inv]}}}, { apply is_trunc_eq}} end definition is_embedding_to_fun (A B : Type) : is_embedding (@to_fun A B) := λf f', !is_equiv_ap_to_fun /- theorems about trunctype -/ protected definition trunctype.sigma_char.{l} [constructor] (n : ℕ₋₂) : (trunctype.{l} n) ≃ (Σ (A : Type.{l}), is_trunc n A) := begin fapply equiv.MK, { intro A, exact (⟨carrier A, struct A⟩)}, { intro S, exact (trunctype.mk S.1 S.2)}, { intro S, induction S with S1 S2, reflexivity}, { intro A, induction A with A1 A2, reflexivity}, end definition trunctype_eq_equiv [constructor] (n : ℕ₋₂) (A B : n-Type) : (A = B) ≃ (carrier A = carrier B) := calc (A = B) ≃ (to_fun (trunctype.sigma_char n) A = to_fun (trunctype.sigma_char n) B) : eq_equiv_fn_eq ... ≃ ((to_fun (trunctype.sigma_char n) A).1 = (to_fun (trunctype.sigma_char n) B).1) : equiv.symm (!equiv_subtype) ... ≃ (carrier A = carrier B) : equiv.refl theorem is_trunc_trunctype [instance] (n : ℕ₋₂) : is_trunc n.+1 (n-Type) := begin apply is_trunc_succ_intro, intro X Y, apply is_trunc_equiv_closed_rev _ !trunctype_eq_equiv, apply is_trunc_equiv_closed_rev _ !eq_equiv_equiv, induction n, { apply is_contr_of_inhabited_prop, { exact equiv_of_is_contr_of_is_contr _ _ }, { apply is_trunc_equiv }}, { apply is_trunc_equiv } end /- univalence for truncated types -/ definition teq_equiv_equiv {n : ℕ₋₂} {A B : n-Type} : (A = B) ≃ (A ≃ B) := trunctype_eq_equiv n A B ⬝e eq_equiv_equiv A B definition tua {n : ℕ₋₂} {A B : n-Type} (f : A ≃ B) : A = B := (trunctype_eq_equiv n A B)⁻¹ᶠ (ua f) definition tua_refl {n : ℕ₋₂} (A : n-Type) : tua (@erfl A) = idp := begin refine ap (trunctype_eq_equiv n A A)⁻¹ᶠ (ua_refl A) ⬝ _, refine ap (inj _) _ ⬝ !inj'_idp , apply ap (dpair_eq_dpair idp), apply is_prop.elim end definition tua_trans {n : ℕ₋₂} {A B C : n-Type} (f : A ≃ B) (g : B ≃ C) : tua (f ⬝e g) = tua f ⬝ tua g := begin refine ap (trunctype_eq_equiv n A C)⁻¹ᶠ (ua_trans f g) ⬝ _, refine ap (inj _) _ ⬝ !inj'_con, refine _ ⬝ !dpair_eq_dpair_con, apply ap (dpair_eq_dpair _), esimp, apply is_prop.elim end definition tua_symm {n : ℕ₋₂} {A B : n-Type} (f : A ≃ B) : tua f⁻¹ᵉ = (tua f)⁻¹ := begin apply eq_inv_of_con_eq_idp', refine !tua_trans⁻¹ ⬝ _, refine ap tua _ ⬝ !tua_refl, apply equiv_eq, exact to_right_inv f end definition tcast [unfold 4] {n : ℕ₋₂} {A B : n-Type} (p : A = B) (a : A) : B := cast (ap trunctype.carrier p) a definition ptcast [constructor] {n : ℕ₋₂} {A B : n-Type*} (p : A = B) : A →* B := pcast (ap ptrunctype.to_pType p) theorem tcast_tua_fn {n : ℕ₋₂} {A B : n-Type} (f : A ≃ B) : tcast (tua f) = to_fun f := begin cases A with A HA, cases B with B HB, esimp at *, induction f using rec_on_ua_idp, esimp, have HA = HB, from !is_prop.elim, cases this, exact ap tcast !tua_refl end /- theorems about decidable equality and axiom K -/ theorem is_set_of_axiom_K {A : Type} (K : Π{a : A} (p : a = a), p = idp) : is_set A := is_set.mk _ (λa b p q, eq.rec K q p) theorem is_set_of_relation.{u} {A : Type.{u}} (R : A → A → Type.{u}) (mere : Π(a b : A), is_prop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) : is_set A := is_set_of_axiom_K (λa p, have H2 : transport (λx, R a x → a = x) p (@imp a a) = @imp a a, from !apdt, have H3 : Π(r : R a a), transport (λx, a = x) p (imp r) = imp (transport (λx, R a x) p r), from to_fun (equiv.symm !heq_pi) H2, have H4 : imp (refl a) ⬝ p = imp (refl a), from calc imp (refl a) ⬝ p = transport (λx, a = x) p (imp (refl a)) : eq_transport_r ... = imp (transport (λx, R a x) p (refl a)) : H3 ... = imp (refl a) : is_prop.elim, cancel_left (imp (refl a)) H4) definition relation_equiv_eq {A : Type} (R : A → A → Type) (mere : Π(a b : A), is_prop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) (a b : A) : R a b ≃ a = b := have is_set A, from is_set_of_relation R mere refl @imp, equiv_of_is_prop imp (λp, p ▸ refl a) _ _ local attribute not [reducible] theorem is_set_of_double_neg_elim {A : Type} (H : Π(a b : A), ¬¬a = b → a = b) : is_set A := is_set_of_relation (λa b, ¬¬a = b) _ (λa n, n idp) H section open decidable --this is proven differently in init.hedberg theorem is_set_of_decidable_eq (A : Type) [H : decidable_eq A] : is_set A := is_set_of_double_neg_elim (λa b, by_contradiction) end theorem is_trunc_of_axiom_K_of_le {A : Type} {n : ℕ₋₂} (H : -1 ≤ n) (K : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λa b, is_trunc_of_imp_is_trunc_of_le H (λp, eq.rec_on p !K)) theorem is_trunc_succ_of_is_trunc_loop (Hn : -1 ≤ n) (Hp : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := begin apply is_trunc_succ_intro, intros a a', apply is_trunc_of_imp_is_trunc_of_le Hn, intro p, induction p, apply Hp end theorem is_prop_iff_is_contr {A : Type} (a : A) : is_prop A ↔ is_contr A := iff.intro (λH, is_contr.mk a (is_prop.elim a)) _ theorem is_trunc_succ_iff_is_trunc_loop (A : Type) (Hn : -1 ≤ n) : is_trunc (n.+1) A ↔ Π(a : A), is_trunc n (a = a) := iff.intro _ (is_trunc_succ_of_is_trunc_loop Hn) -- use loopn in name theorem is_trunc_iff_is_contr_loop_succ (n : ℕ) (A : Type) : is_trunc n A ↔ Π(a : A), is_contr (Ω[succ n](pointed.Mk a)) := begin revert A, induction n with n IH, { intro A, esimp [loopn], transitivity _, { apply is_trunc_succ_iff_is_trunc_loop, apply le.refl}, { apply pi_iff_pi, intro a, esimp, apply is_prop_iff_is_contr, reflexivity}}, { intro A, esimp [loopn], transitivity _, { apply @is_trunc_succ_iff_is_trunc_loop @n, esimp, apply minus_one_le_succ}, apply pi_iff_pi, intro a, transitivity _, apply IH, transitivity _, apply pi_iff_pi, intro p, rewrite [loopn_space_loop_irrel n p], apply iff.refl, esimp, apply imp_iff, reflexivity} end -- use loopn in name theorem is_trunc_iff_is_contr_loop (n : ℕ) (A : Type) : is_trunc (n.-2.+1) A ↔ (Π(a : A), is_contr (Ω[n](pointed.Mk a))) := begin induction n with n, { esimp [sub_two,loopn], apply iff.intro, intro H a, exact is_contr_of_inhabited_prop a _, intro H, apply is_prop_of_imp_is_contr, exact H}, { apply is_trunc_iff_is_contr_loop_succ}, end -- rename to is_contr_loopn_of_is_trunc theorem is_contr_loop_of_is_trunc (n : ℕ) (A : Type*) [H : is_trunc (n.-2.+1) A] : is_contr (Ω[n] A) := begin induction A, apply iff.mp !is_trunc_iff_is_contr_loop H end theorem is_trunc_loopn_of_is_trunc (n : ℕ₋₂) (k : ℕ) (A : Type*) [H : is_trunc n A] : is_trunc n (Ω[k] A) := begin induction k with k IH, { exact H}, { apply is_trunc_eq} end definition is_trunc_loopn (k : ℕ₋₂) (n : ℕ) (A : Type*) [H : is_trunc (k+n) A] : is_trunc k (Ω[n] A) := begin revert k H, induction n with n IH: intro k H, exact _, apply is_trunc_eq, apply IH, rewrite [succ_add_nat, add_nat_succ at H], exact H end lemma is_trunc_loopn_nat (n m : ℕ) (A : Type*) [H : is_trunc (n + m) A] : is_trunc n (Ω[m] A) := @is_trunc_loopn n m A (transport (λk, is_trunc k _) (of_nat_add_of_nat n m)⁻¹ H) definition is_set_loopn (n : ℕ) (A : Type*) [is_trunc n A] : is_set (Ω[n] A) := have is_trunc (0+n) A, by rewrite [zero_add]; exact _, is_trunc_loopn_nat 0 n A lemma is_trunc_loop_nat (n : ℕ) (A : Type*) [H : is_trunc (n + 1) A] : is_trunc n (Ω A) := is_trunc_loop A n definition is_trunc_of_eq {n m : ℕ₋₂} (p : n = m) {A : Type} (H : is_trunc n A) : is_trunc m A := transport (λk, is_trunc k A) p H definition pequiv_punit_of_is_contr [constructor] (A : Type*) (H : is_contr A) : A ≃* punit := pequiv_of_equiv (equiv_unit_of_is_contr A _) (@is_prop.elim unit _ _ _) definition pequiv_punit_of_is_contr' [constructor] (A : Type) (H : is_contr A) : pointed.MK A (center A) ≃* punit := pequiv_punit_of_is_contr (pointed.MK A (center A)) H definition is_trunc_is_contr_fiber (n : ℕ₋₂) {A B : Type} (f : A → B) (b : B) [is_trunc n A] [is_trunc n B] : is_trunc n (is_contr (fiber f b)) := begin cases n, { refine is_contr_of_inhabited_prop _ _, apply is_contr_fun_of_is_equiv, exact is_equiv_of_is_contr _ _ _ }, { exact is_trunc_succ_of_is_prop _ _ _ } end end is_trunc open is_trunc namespace trunc universe variable u variables {n : ℕ₋₂} {A : Type.{u}} {B : Type} {a₁ a₂ a₃ a₄ : A} definition trunc_functor2 [unfold 6 7] {n : ℕ₋₂} {A B C : Type} (f : A → B → C) (x : trunc n A) (y : trunc n B) : trunc n C := by induction x with a; induction y with b; exact tr (f a b) definition tconcat [unfold 6 7] (p : trunc n (a₁ = a₂)) (q : trunc n (a₂ = a₃)) : trunc n (a₁ = a₃) := trunc_functor2 concat p q definition tinverse [unfold 5] (p : trunc n (a₁ = a₂)) : trunc n (a₂ = a₁) := trunc_functor _ inverse p definition tidp [reducible] [constructor] : trunc n (a₁ = a₁) := tr idp definition tassoc (p : trunc n (a₁ = a₂)) (q : trunc n (a₂ = a₃)) (r : trunc n (a₃ = a₄)) : tconcat (tconcat p q) r = tconcat p (tconcat q r) := by induction p; induction q; induction r; exact ap tr !con.assoc definition tidp_tcon (p : trunc n (a₁ = a₂)) : tconcat tidp p = p := by induction p; exact ap tr !idp_con definition tcon_tidp (p : trunc n (a₁ = a₂)) : tconcat p tidp = p := by induction p; reflexivity definition left_tinv (p : trunc n (a₁ = a₂)) : tconcat (tinverse p) p = tidp := by induction p; exact ap tr !con.left_inv definition right_tinv (p : trunc n (a₁ = a₂)) : tconcat p (tinverse p) = tidp := by induction p; exact ap tr !con.right_inv definition tap [unfold 7] (f : A → B) (p : trunc n (a₁ = a₂)) : trunc n (f a₁ = f a₂) := trunc_functor _ (ap f) p definition tap_tidp (f : A → B) : tap f (@tidp n A a₁) = tidp := idp definition tap_tcon (f : A → B) (p : trunc n (a₁ = a₂)) (q : trunc n (a₂ = a₃)) : tap f (tconcat p q) = tconcat (tap f p) (tap f q) := by induction p; induction q; exact ap tr !ap_con /- characterization of equality in truncated types -/ protected definition code [unfold 3 4] (n : ℕ₋₂) (aa aa' : trunc n.+1 A) : trunctype.{u} n := by induction aa with a; induction aa' with a'; exact trunctype.mk' n (trunc n (a = a')) protected definition encode [unfold 3 5] {n : ℕ₋₂} {aa aa' : trunc n.+1 A} : aa = aa' → trunc.code n aa aa' := begin intro p, induction p, induction aa with a, esimp, exact (tr idp) end protected definition decode [unfold 3 4 5] {n : ℕ₋₂} (aa aa' : trunc n.+1 A) : trunc.code n aa aa' → aa = aa' := begin induction aa' with a', induction aa with a, esimp [trunc.code, trunc.rec_on], intro x, induction x with p, exact ap tr p, end definition trunc_eq_equiv [constructor] (n : ℕ₋₂) (aa aa' : trunc n.+1 A) : aa = aa' ≃ trunc.code n aa aa' := begin fapply equiv.MK, { apply trunc.encode}, { apply trunc.decode}, { eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa), intro a a' x, esimp [trunc.code, trunc.rec_on] at x, refine (@trunc.rec_on n _ _ x _ _), intro x, apply is_trunc_eq, intro p, induction p, reflexivity}, { intro p, induction p, apply (trunc.rec_on aa), intro a, exact idp}, end definition tr_eq_tr_equiv [constructor] (n : ℕ₋₂) (a a' : A) : (tr a = tr a' :> trunc n.+1 A) ≃ trunc n (a = a') := !trunc_eq_equiv definition trunc_eq {n : ℕ₋₂} {a a' : A} (p : trunc n (a = a')) :tr a = tr a' :> trunc n.+1 A := !tr_eq_tr_equiv⁻¹ᵉ p definition code_mul {n : ℕ₋₂} {aa₁ aa₂ aa₃ : trunc n.+1 A} (g : trunc.code n aa₁ aa₂) (h : trunc.code n aa₂ aa₃) : trunc.code n aa₁ aa₃ := begin induction aa₁ with a₁, induction aa₂ with a₂, induction aa₃ with a₃, esimp at *, apply tconcat g h, end /- encode preserves concatenation -/ definition encode_con' {n : ℕ₋₂} {aa₁ aa₂ aa₃ : trunc n.+1 A} (p : aa₁ = aa₂) (q : aa₂ = aa₃) : trunc.encode (p ⬝ q) = code_mul (trunc.encode p) (trunc.encode q) := begin induction p, induction q, induction aa₁ with a₁, reflexivity end definition encode_con {n : ℕ₋₂} {a₁ a₂ a₃ : A} (p : tr a₁ = tr a₂ :> trunc (n.+1) A) (q : tr a₂ = tr a₃ :> trunc (n.+1) A) : trunc.encode (p ⬝ q) = tconcat (trunc.encode p) (trunc.encode q) := encode_con' p q /- the principle of unique choice -/ definition unique_choice {P : A → Type} [H : Πa, is_prop (P a)] (f : Πa, ∥ P a ∥) (a : A) : P a := !trunc_equiv (f a) /- transport over a truncated family -/ definition trunc_transport {a a' : A} {P : A → Type} (p : a = a') (n : ℕ₋₂) (x : P a) : transport (λa, trunc n (P a)) p (tr x) = tr (p ▸ x) := by induction p; reflexivity /- pathover over a truncated family -/ definition trunc_pathover {A : Type} {B : A → Type} {n : ℕ₋₂} {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') : @tr n _ b =[p] @tr n _ b' := by induction q; constructor /- truncations preserve truncatedness -/ definition is_trunc_trunc_of_is_trunc [instance] [priority 500] (A : Type) (n m : ℕ₋₂) [H : is_trunc n A] : is_trunc n (trunc m A) := begin revert A m H, eapply (trunc_index.rec_on n), { clear n, intro A m H, refine is_contr_equiv_closed_rev _ H, { apply trunc_equiv, exact is_trunc_of_is_contr _ _ _ } }, { clear n, intro n IH A m H, induction m with m, { exact is_trunc_of_is_contr _ _ _ }, { apply is_trunc_succ_intro, intro aa aa', apply (@trunc.rec_on _ _ _ aa (λy, is_trunc_succ_of_is_prop _ _ _)), eapply (@trunc.rec_on _ _ _ aa' (λy, is_trunc_succ_of_is_prop _ _ _)), intro a a', apply is_trunc_equiv_closed_rev _ !tr_eq_tr_equiv (IH _ _ _) }} end /- equivalences between truncated types (see also hit.trunc) -/ definition trunc_trunc_equiv_left [constructor] (A : Type) {n m : ℕ₋₂} (H : n ≤ m) : trunc n (trunc m A) ≃ trunc n A := begin note H2 := is_trunc_of_le (trunc n A) H _, fapply equiv.MK, { intro x, induction x with x, induction x with x, exact tr x }, { exact trunc_functor n tr }, { intro x, induction x with x, reflexivity}, { intro x, induction x with x, induction x with x, reflexivity} end definition trunc_trunc_equiv_right [constructor] (A : Type) {n m : ℕ₋₂} (H : n ≤ m) : trunc m (trunc n A) ≃ trunc n A := begin apply trunc_equiv, exact is_trunc_of_le _ H _, end definition trunc_equiv_trunc_of_le {n m : ℕ₋₂} {A B : Type} (H : n ≤ m) (f : trunc m A ≃ trunc m B) : trunc n A ≃ trunc n B := (trunc_trunc_equiv_left A H)⁻¹ᵉ ⬝e trunc_equiv_trunc n f ⬝e trunc_trunc_equiv_left B H definition trunc_trunc_equiv_trunc_trunc [constructor] (n m : ℕ₋₂) (A : Type) : trunc n (trunc m A) ≃ trunc m (trunc n A) := begin fapply equiv.MK: intro x; induction x with x; induction x with x, { exact tr (tr x)}, { exact tr (tr x)}, { reflexivity}, { reflexivity} end theorem is_trunc_trunc_of_le (A : Type) (n : ℕ₋₂) {m k : ℕ₋₂} (H : m ≤ k) [is_trunc n (trunc k A)] : is_trunc n (trunc m A) := is_trunc_equiv_closed _ (trunc_trunc_equiv_left _ H) _ definition trunc_functor_homotopy [unfold 7] {X Y : Type} (n : ℕ₋₂) {f g : X → Y} (p : f ~ g) (x : trunc n X) : trunc_functor n f x = trunc_functor n g x := begin induction x with x, esimp, exact ap tr (p x) end section hsquare variables {A₀₀ A₂₀ A₄₀ A₀₂ A₂₂ A₄₂ A₀₄ A₂₄ A₄₄ : Type} {f₁₀ : A₀₀ → A₂₀} {f₀₁ : A₀₀ → A₀₂} {f₂₁ : A₂₀ → A₂₂} {f₁₂ : A₀₂ → A₂₂} definition trunc_functor_hsquare (n : ℕ₋₂) (h : hsquare f₁₀ f₁₂ f₀₁ f₂₁) : hsquare (trunc_functor n f₁₀) (trunc_functor n f₁₂) (trunc_functor n f₀₁) (trunc_functor n f₂₁) := λa, !trunc_functor_compose⁻¹ ⬝ trunc_functor_homotopy n h a ⬝ !trunc_functor_compose end hsquare definition trunc_functor_homotopy_of_le {n k : ℕ₋₂} {A B : Type} (f : A → B) (H : n ≤ k) : to_fun (trunc_trunc_equiv_left B H) ∘ trunc_functor n (trunc_functor k f) ∘ to_fun (trunc_trunc_equiv_left A H)⁻¹ᵉ ~ trunc_functor n f := begin intro x, induction x with x, reflexivity end definition is_equiv_trunc_functor_of_le {n k : ℕ₋₂} {A B : Type} (f : A → B) (H : n ≤ k) (H' : is_equiv (trunc_functor k f)) : is_equiv (trunc_functor n f) := is_equiv_of_equiv_of_homotopy (trunc_equiv_trunc_of_le H (equiv.mk (trunc_functor k f) _)) (trunc_functor_homotopy_of_le f H) /- trunc_functor preserves surjectivity -/ definition is_surjective_trunc_functor {A B : Type} (n : ℕ₋₂) (f : A → B) [H : is_surjective f] : is_surjective (trunc_functor n f) := begin cases n with n: intro b, { exact tr (fiber.mk !center !is_prop.elim)}, { refine @trunc.rec _ _ _ _ _ b, {intro x, exact is_trunc_of_le _ !minus_one_le_succ _ }, clear b, intro b, induction H b with a p, exact tr (fiber.mk (tr a) (ap tr p))} end /- truncation of pointed types -/ definition ptrunc [constructor] (n : ℕ₋₂) (X : Type*) : n-Type* := ptrunctype.mk (trunc n X) _ (tr pt) definition is_trunc_ptrunc_of_is_trunc [instance] [priority 500] (A : Type*) (n m : ℕ₋₂) [H : is_trunc n A] : is_trunc n (ptrunc m A) := is_trunc_trunc_of_is_trunc A n m definition is_contr_ptrunc_minus_one (A : Type*) : is_contr (ptrunc -1 A) := is_contr_of_inhabited_prop pt _ /- pointed maps involving ptrunc -/ definition ptrunc_functor [constructor] {X Y : Type*} (n : ℕ₋₂) (f : X →* Y) : ptrunc n X →* ptrunc n Y := pmap.mk (trunc_functor n f) (ap tr (respect_pt f)) definition ptr [constructor] (n : ℕ₋₂) (A : Type*) : A →* ptrunc n A := pmap.mk tr idp definition puntrunc [constructor] (n : ℕ₋₂) (A : Type*) [is_trunc n A] : ptrunc n A →* A := pmap.mk untrunc_of_is_trunc idp definition ptrunc.elim [constructor] (n : ℕ₋₂) {X Y : Type*} [is_trunc n Y] (f : X →* Y) : ptrunc n X →* Y := pmap.mk (trunc.elim f) (respect_pt f) definition ptrunc_functor_le {k l : ℕ₋₂} (p : l ≤ k) (X : Type*) : ptrunc k X →* ptrunc l X := have is_trunc k (ptrunc l X), from is_trunc_of_le _ p _, ptrunc.elim _ (ptr l X) /- pointed equivalences involving ptrunc -/ definition ptrunc_pequiv_ptrunc [constructor] (n : ℕ₋₂) {X Y : Type*} (H : X ≃* Y) : ptrunc n X ≃* ptrunc n Y := pequiv_of_equiv (trunc_equiv_trunc n H) (ap tr (respect_pt H)) definition ptrunc_pequiv [constructor] (n : ℕ₋₂) (X : Type*) [H : is_trunc n X] : ptrunc n X ≃* X := pequiv_of_equiv (trunc_equiv n X) idp definition ptrunc_ptrunc_pequiv_left [constructor] (A : Type*) {n m : ℕ₋₂} (H : n ≤ m) : ptrunc n (ptrunc m A) ≃* ptrunc n A := pequiv_of_equiv (trunc_trunc_equiv_left A H) idp definition ptrunc_ptrunc_pequiv_right [constructor] (A : Type*) {n m : ℕ₋₂} (H : n ≤ m) : ptrunc m (ptrunc n A) ≃* ptrunc n A := pequiv_of_equiv (trunc_trunc_equiv_right A H) idp definition ptrunc_pequiv_ptrunc_of_le {n m : ℕ₋₂} {A B : Type*} (H : n ≤ m) (f : ptrunc m A ≃* ptrunc m B) : ptrunc n A ≃* ptrunc n B := (ptrunc_ptrunc_pequiv_left A H)⁻¹ᵉ* ⬝e* ptrunc_pequiv_ptrunc n f ⬝e* ptrunc_ptrunc_pequiv_left B H definition ptrunc_ptrunc_pequiv_ptrunc_ptrunc [constructor] (n m : ℕ₋₂) (A : Type*) : ptrunc n (ptrunc m A) ≃* ptrunc m (ptrunc n A) := pequiv_of_equiv (trunc_trunc_equiv_trunc_trunc n m A) idp definition ptrunc_change_index {k l : ℕ₋₂} (p : k = l) (X : Type*) : ptrunc k X ≃* ptrunc l X := pequiv_ap (λ n, ptrunc n X) p definition loop_ptrunc_pequiv [constructor] (n : ℕ₋₂) (A : Type*) : Ω (ptrunc (n+1) A) ≃* ptrunc n (Ω A) := pequiv_of_equiv !tr_eq_tr_equiv idp definition loop_ptrunc_pequiv_con {n : ℕ₋₂} {A : Type*} (p q : Ω (ptrunc (n+1) A)) : loop_ptrunc_pequiv n A (p ⬝ q) = tconcat (loop_ptrunc_pequiv n A p) (loop_ptrunc_pequiv n A q) := encode_con p q definition loopn_ptrunc_pequiv (n : ℕ₋₂) (k : ℕ) (A : Type*) : Ω[k] (ptrunc (n+k) A) ≃* ptrunc n (Ω[k] A) := begin revert n, induction k with k IH: intro n, { reflexivity}, { refine _ ⬝e* loop_ptrunc_pequiv n (Ω[k] A), change Ω (Ω[k] (ptrunc (n + succ k) A)) ≃* Ω (ptrunc (n + 1) (Ω[k] A)), apply loop_pequiv_loop, refine _ ⬝e* IH (n.+1), exact loopn_pequiv_loopn k (pequiv_of_eq (ap (λn, ptrunc n A) !succ_add_nat⁻¹)) } end definition loopn_ptrunc_pequiv_nat (n k : ℕ) (A : Type*) : Ω[k] (ptrunc (n + k) A) ≃* ptrunc n (Ω[k] A) := loopn_pequiv_loopn k (ptrunc_change_index (of_nat_add_of_nat n k)⁻¹ A) ⬝e* loopn_ptrunc_pequiv n k A definition loopn_ptrunc_pequiv_con {n : ℕ₋₂} {k : ℕ} {A : Type*} (p q : Ω[succ k] (ptrunc (n+succ k) A)) : loopn_ptrunc_pequiv n (succ k) A (p ⬝ q) = tconcat (loopn_ptrunc_pequiv n (succ k) A p) (loopn_ptrunc_pequiv n (succ k) A q) := begin refine _ ⬝ loop_ptrunc_pequiv_con _ _, exact ap !loop_ptrunc_pequiv !loop_pequiv_loop_con end definition loopn_ptrunc_pequiv_inv_con {n : ℕ₋₂} {k : ℕ} {A : Type*} (p q : ptrunc n (Ω[succ k] A)) : (loopn_ptrunc_pequiv n (succ k) A)⁻¹ᵉ* (tconcat p q) = (loopn_ptrunc_pequiv n (succ k) A)⁻¹ᵉ* p ⬝ (loopn_ptrunc_pequiv n (succ k) A)⁻¹ᵉ* q := equiv.inv_preserve_binary (loopn_ptrunc_pequiv n (succ k) A) concat tconcat (@loopn_ptrunc_pequiv_con n k A) p q /- pointed homotopies involving ptrunc -/ definition ptrunc_functor_pcompose [constructor] {X Y Z : Type*} (n : ℕ₋₂) (g : Y →* Z) (f : X →* Y) : ptrunc_functor n (g ∘* f) ~* ptrunc_functor n g ∘* ptrunc_functor n f := begin fapply phomotopy.mk, { apply trunc_functor_compose}, { esimp, refine !idp_con ⬝ _, refine whisker_right _ !ap_compose' ⬝ _, esimp, refine whisker_right _ (ap_compose tr g _) ⬝ _, exact !ap_con⁻¹}, end definition ptrunc_functor_pid [constructor] (X : Type*) (n : ℕ₋₂) : ptrunc_functor n (pid X) ~* pid (ptrunc n X) := begin fapply phomotopy.mk, { apply trunc_functor_id}, { reflexivity}, end definition ptrunc_functor_pcast [constructor] {X Y : Type*} (n : ℕ₋₂) (p : X = Y) : ptrunc_functor n (pcast p) ~* pcast (ap (ptrunc n) p) := begin fapply phomotopy.mk, { intro x, esimp, refine !trunc_functor_cast ⬝ _, refine ap010 cast _ x, refine !ap_compose' ⬝ !ap_compose }, { induction p, reflexivity}, end definition ptrunc_functor_phomotopy [constructor] {X Y : Type*} (n : ℕ₋₂) {f g : X →* Y} (p : f ~* g) : ptrunc_functor n f ~* ptrunc_functor n g := begin fapply phomotopy.mk, { exact trunc_functor_homotopy n p}, { esimp, refine !ap_con⁻¹ ⬝ _, exact ap02 tr !to_homotopy_pt}, end definition ptrunc_functor_pconst [constructor] (n : ℕ₋₂) (X Y : Type*) : ptrunc_functor n (pconst X Y) ~* pconst (ptrunc n X) (ptrunc n Y) := begin fapply phomotopy.mk, { intro x, induction x with x, reflexivity }, { reflexivity } end definition pcast_ptrunc [constructor] (n : ℕ₋₂) {A B : Type*} (p : A = B) : pcast (ap (ptrunc n) p) ~* ptrunc_functor n (pcast p) := begin fapply phomotopy.mk, { intro a, induction p, esimp, exact !trunc_functor_id⁻¹}, { induction p, reflexivity} end definition ptrunc_elim_ptr [constructor] (n : ℕ₋₂) {X Y : Type*} [is_trunc n Y] (f : X →* Y) : ptrunc.elim n f ∘* ptr n X ~* f := begin fapply phomotopy.mk, { reflexivity }, { reflexivity } end definition ptrunc_elim_phomotopy (n : ℕ₋₂) {X Y : Type*} [is_trunc n Y] {f g : X →* Y} (H : f ~* g) : ptrunc.elim n f ~* ptrunc.elim n g := begin fapply phomotopy.mk, { intro x, induction x with x, exact H x }, { exact to_homotopy_pt H } end definition ap1_ptrunc_functor (n : ℕ₋₂) {A B : Type*} (f : A →* B) : Ω→ (ptrunc_functor (n.+1) f) ∘* (loop_ptrunc_pequiv n A)⁻¹ᵉ* ~* (loop_ptrunc_pequiv n B)⁻¹ᵉ* ∘* ptrunc_functor n (Ω→ f) := begin fapply phomotopy.mk, { intro p, induction p with p, refine (!ap_inv⁻¹ ◾ !ap_compose⁻¹ ◾ idp) ⬝ _ ⬝ !ap_con⁻¹, apply whisker_right, refine _ ⬝ !ap_con⁻¹, exact whisker_left _ !ap_compose }, { induction B with B b, induction f with f p, esimp at f, esimp at p, induction p, reflexivity } end definition ap1_ptrunc_elim (n : ℕ₋₂) {A B : Type*} (f : A →* B) [is_trunc (n.+1) B] : Ω→ (ptrunc.elim (n.+1) f) ∘* (loop_ptrunc_pequiv n A)⁻¹ᵉ* ~* ptrunc.elim n (Ω→ f) := begin fapply phomotopy.mk, { intro p, induction p with p, exact idp ◾ !ap_compose⁻¹ ◾ idp }, { reflexivity } end definition ap1_ptr (n : ℕ₋₂) (A : Type*) : Ω→ (ptr (n.+1) A) ~* (loop_ptrunc_pequiv n A)⁻¹ᵉ* ∘* ptr n (Ω A) := begin fapply phomotopy.mk, { intro p, apply idp_con }, { reflexivity } end definition ptrunc_elim_ptrunc_functor (n : ℕ₋₂) {A B C : Type*} (g : B →* C) (f : A →* B) [is_trunc n C] : ptrunc.elim n g ∘* ptrunc_functor n f ~* ptrunc.elim n (g ∘* f) := begin fapply phomotopy.mk, { intro x, induction x with a, reflexivity }, { esimp, exact !idp_con ⬝ whisker_right _ !ap_compose }, end definition ptrunc_pequiv_natural [constructor] (n : ℕ₋₂) {A B : Type*} (f : A →* B) [is_trunc n A] [is_trunc n B] : f ∘* ptrunc_pequiv n A ~* ptrunc_pequiv n B ∘* ptrunc_functor n f := begin fapply phomotopy.mk, { intro a, induction a with a, reflexivity }, { refine !idp_con ⬝ _ ⬝ !idp_con⁻¹, refine !ap_compose' ⬝ _, apply ap_id } end definition ptr_natural [constructor] (n : ℕ₋₂) {A B : Type*} (f : A →* B) : ptrunc_functor n f ∘* ptr n A ~* ptr n B ∘* f := begin fapply phomotopy.mk, { intro a, reflexivity }, { reflexivity } end definition ptrunc_elim_pcompose (n : ℕ₋₂) {A B C : Type*} (g : B →* C) (f : A →* B) [is_trunc n B] [is_trunc n C] : ptrunc.elim n (g ∘* f) ~* g ∘* ptrunc.elim n f := begin fapply phomotopy.mk, { intro a, induction a with a, reflexivity }, { apply idp_con } end definition ptrunc_elim_ptr_phomotopy_pid (n : ℕ₋₂) (A : Type*): ptrunc.elim n (ptr n A) ~* pid (ptrunc n A) := begin fapply phomotopy.mk, { intro a, induction a with a, reflexivity }, { apply idp_con } end section psquare variables {A₀₀ A₂₀ A₀₂ A₂₂ : Type*} {f₁₀ : A₀₀ →* A₂₀} {f₁₂ : A₀₂ →* A₂₂} {f₀₁ : A₀₀ →* A₀₂} {f₂₁ : A₂₀ →* A₂₂} definition ptrunc_functor_psquare (n : ℕ₋₂) (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : psquare (ptrunc_functor n f₁₀) (ptrunc_functor n f₁₂) (ptrunc_functor n f₀₁) (ptrunc_functor n f₂₁) := !ptrunc_functor_pcompose⁻¹* ⬝* ptrunc_functor_phomotopy n p ⬝* !ptrunc_functor_pcompose end psquare definition is_equiv_ptrunc_functor_ptr [constructor] (A : Type*) {n m : ℕ₋₂} (H : n ≤ m) : is_equiv (ptrunc_functor n (ptr m A)) := to_is_equiv (trunc_trunc_equiv_left A H)⁻¹ᵉ -- The following pointed equivalence can be defined more easily, but now we get the right maps definitionally definition ptrunc_pequiv_ptrunc_of_is_trunc {n m k : ℕ₋₂} {A : Type*} (H1 : n ≤ m) (H2 : n ≤ k) (H : is_trunc n A) : ptrunc m A ≃* ptrunc k A := have is_trunc m A, from is_trunc_of_le A H1 _, have is_trunc k A, from is_trunc_of_le A H2 _, pequiv.MK (ptrunc.elim _ (ptr k A)) (ptrunc.elim _ (ptr m A)) abstract begin refine !ptrunc_elim_pcompose⁻¹* ⬝* _, exact ptrunc_elim_phomotopy _ !ptrunc_elim_ptr ⬝* !ptrunc_elim_ptr_phomotopy_pid, end end abstract begin refine !ptrunc_elim_pcompose⁻¹* ⬝* _, exact ptrunc_elim_phomotopy _ !ptrunc_elim_ptr ⬝* !ptrunc_elim_ptr_phomotopy_pid, end end /- A more general version of ptrunc_elim_phomotopy, where the proofs of truncatedness might be different -/ definition ptrunc_elim_phomotopy2 [constructor] (k : ℕ₋₂) {A B : Type*} {f g : A →* B} (H₁ : is_trunc k B) (H₂ : is_trunc k B) (p : f ~* g) : @ptrunc.elim k A B H₁ f ~* @ptrunc.elim k A B H₂ g := begin fapply phomotopy.mk, { intro x, induction x with a, exact p a }, { exact to_homotopy_pt p } end definition pmap_ptrunc_equiv [constructor] (n : ℕ₋₂) (A B : Type*) [H : is_trunc n B] : (ptrunc n A →* B) ≃ (A →* B) := begin fapply equiv.MK, { intro g, exact g ∘* ptr n A }, { exact ptrunc.elim n }, { intro f, apply eq_of_phomotopy, apply ptrunc_elim_ptr }, { intro g, apply eq_of_phomotopy, exact ptrunc_elim_pcompose n g (ptr n A) ⬝* pwhisker_left g (ptrunc_elim_ptr_phomotopy_pid n A) ⬝* pcompose_pid g } end definition pmap_ptrunc_pequiv [constructor] (n : ℕ₋₂) (A B : Type*) [H : is_trunc n B] : ppmap (ptrunc n A) B ≃* ppmap A B := pequiv_of_equiv (pmap_ptrunc_equiv n A B) (eq_of_phomotopy (pconst_pcompose (ptr n A))) definition ptrunctype.sigma_char [constructor] (n : ℕ₋₂) : n-Type* ≃ Σ(X : Type*), is_trunc n X := equiv.MK (λX, ⟨ptrunctype.to_pType X, _⟩) (λX, ptrunctype.mk (carrier X.1) X.2 pt) begin intro X, induction X with X HX, induction X, reflexivity end begin intro X, induction X, reflexivity end definition is_embedding_ptrunctype_to_pType (n : ℕ₋₂) : is_embedding (@ptrunctype.to_pType n) := begin intro X Y, fapply is_equiv_of_equiv_of_homotopy, { exact eq_equiv_fn_eq (ptrunctype.sigma_char n) _ _ ⬝e subtype_eq_equiv _ _ }, intro p, induction p, reflexivity end definition ptrunctype_eq_equiv {n : ℕ₋₂} (X Y : n-Type*) : (X = Y) ≃ (X ≃* Y) := equiv.mk _ (is_embedding_ptrunctype_to_pType n X Y) ⬝e pType_eq_equiv X Y definition Prop_eq {P Q : Prop} (H : P ↔ Q) : P = Q := tua (equiv_of_is_prop (iff.mp H) (iff.mpr H) _ _) end trunc open trunc /- The truncated encode-decode method -/ namespace eq definition truncated_encode {k : ℕ₋₂} {A : Type} {a₀ a : A} {code : A → Type} [Πa, is_trunc k (code a)] (c₀ : code a₀) (p : trunc k (a₀ = a)) : code a := begin induction p with p, exact transport code p c₀ end definition truncated_encode_decode_method {k : ℕ₋₂} {A : Type} (a₀ a : A) (code : A → Type) [Πa, is_trunc k (code a)] (c₀ : code a₀) (decode : Π(a : A) (c : code a), trunc k (a₀ = a)) (encode_decode : Π(a : A) (c : code a), truncated_encode c₀ (decode a c) = c) (decode_encode : decode a₀ c₀ = tr idp) : trunc k (a₀ = a) ≃ code a := begin fapply equiv.MK, { exact truncated_encode c₀}, { apply decode}, { intro c, apply encode_decode}, { intro p, induction p with p, induction p, exact decode_encode}, end end eq /- some consequences for properties about functions (surjectivity etc.) -/ namespace function open fiber variables {A B : Type} definition is_surjective_of_is_equiv [instance] (f : A → B) [H : is_equiv f] : is_surjective f := λb, begin esimp, apply center, apply is_trunc_trunc_of_is_trunc end definition is_equiv_equiv_is_embedding_times_is_surjective [constructor] (f : A → B) : is_equiv f ≃ (is_embedding f × is_surjective f) := equiv_of_is_prop (λH, (_, _)) (λP, prod.rec_on P (λH₁ H₂, !is_equiv_of_is_surjective_of_is_embedding)) _ _ /- Theorem 8.8.1: A function is an equivalence if it's an embedding and it's action on sets is an surjection -/ definition is_equiv_of_is_surjective_trunc_of_is_embedding {A B : Type} (f : A → B) [H : is_embedding f] [H' : is_surjective (trunc_functor 0 f)] : is_equiv f := have is_surjective f, begin intro b, induction H' (tr b) with a p, induction a with a, esimp at p, induction (tr_eq_tr_equiv _ _ _ p) with q, exact image.mk a q end, is_equiv_of_is_surjective_of_is_embedding f /- Corollary 8.8.2: A function f is an equivalence if Ωf and trunc_functor 0 f are equivalences -/ definition is_equiv_of_is_equiv_ap1_of_is_equiv_trunc {A B : Type} (f : A → B) [H : Πa, is_equiv (ap1 (pmap_of_map f a))] [H' : is_equiv (trunc_functor 0 f)] : is_equiv f := have is_embedding f, begin intro a a', apply is_equiv_of_imp_is_equiv, intro p, note q := ap (@tr 0 _) p, note r := @(inj' (trunc_functor 0 f)) _ (tr a) (tr a') q, induction (tr_eq_tr_equiv _ _ _ r) with s, induction s, refine is_equiv.homotopy_closed (ap1 (pmap_of_map f a)) _ (H a), intro p, apply idp_con end, is_equiv_of_is_surjective_trunc_of_is_embedding f -- Whitehead's principle itself is in homotopy.homotopy_group, since it needs the definition of -- a homotopy group. end function /- functions between ℤ and ℕ₋₂ -/ namespace int private definition maxm2_le.lemma₁ {n k : ℕ} : n+(1:int) + -[1+ k] ≤ n := le.intro ( calc n + 1 + -[1+ k] + k = n + 1 + (-(k + 1)) + k : by reflexivity ... = n + 1 + (- 1 - k) + k : by krewrite (neg_add_rev k 1) ... = n + 1 + (- 1 - k + k) : add.assoc ... = n + 1 + (- 1 + -k + k) : by reflexivity ... = n + 1 + (- 1 + (-k + k)) : add.assoc ... = n + 1 + (- 1 + 0) : add.left_inv ... = n + (1 + (- 1 + 0)) : add.assoc ... = n : int.add_zero) private definition maxm2_le.lemma₂ {n : ℕ} {k : ℤ} : -[1+ n] + 1 + k ≤ k := le.intro ( calc -[1+ n] + 1 + k + n = - (n + 1) + 1 + k + n : by reflexivity ... = -n - 1 + 1 + k + n : by rewrite (neg_add n 1) ... = -n + (- 1 + 1) + k + n : by krewrite (int.add_assoc (-n) (- 1) 1) ... = -n + 0 + k + n : add.left_inv 1 ... = -n + k + n : int.add_zero ... = k + -n + n : int.add_comm ... = k + (-n + n) : int.add_assoc ... = k + 0 : add.left_inv n ... = k : int.add_zero) open trunc_index /- The function from integers to truncation indices which sends positive numbers to themselves, and negative numbers to negative 2. In particular -1 is sent to -2, but since we only work with pointed types, that doesn't matter for us -/ definition maxm2 [unfold 1] : ℤ → ℕ₋₂ := λ n, int.cases_on n trunc_index.of_nat (λk, -2) -- we also need the max -1 - function definition maxm1 [unfold 1] : ℤ → ℕ₋₂ := λ n, int.cases_on n trunc_index.of_nat (λk, -1) definition maxm2_le_maxm1 (n : ℤ) : maxm2 n ≤ maxm1 n := begin induction n with n n, { exact le.tr_refl n }, { exact minus_two_le -1 } end -- this is maxm1 minus 1 definition maxm1m1 [unfold 1] : ℤ → ℕ₋₂ := λ n, int.cases_on n (λ k, k.-1) (λ k, -2) definition maxm1_eq_succ (n : ℤ) : maxm1 n = (maxm1m1 n).+1 := begin induction n with n n, { reflexivity }, { reflexivity } end definition maxm2_le_maxm0 (n : ℤ) : maxm2 n ≤ max0 n := begin induction n with n n, { exact le.tr_refl n }, { exact minus_two_le 0 } end definition max0_le_of_le {n : ℤ} {m : ℕ} (H : n ≤ of_nat m) : nat.le (max0 n) m := begin induction n with n n, { exact le_of_of_nat_le_of_nat H }, { exact nat.zero_le m } end definition maxm2_monotone {n m : ℤ} (H : n ≤ m) : maxm2 n ≤ maxm2 m := begin induction n with n n, { induction m with m m, { apply of_nat_le_of_nat, exact le_of_of_nat_le_of_nat H }, { exfalso, exact not_neg_succ_le_of_nat H }}, { apply minus_two_le } end definition sub_nat_le (n : ℤ) (m : ℕ) : n - m ≤ n := le.intro !sub_add_cancel definition sub_nat_lt (n : ℤ) (m : ℕ) : n - m < n + 1 := add_le_add_right (sub_nat_le n m) 1 definition sub_one_le (n : ℤ) : n - 1 ≤ n := sub_nat_le n 1 definition le_add_nat (n : ℤ) (m : ℕ) : n ≤ n + m := le.intro rfl definition le_add_one (n : ℤ) : n ≤ n + 1 := le_add_nat n 1 open trunc_index definition maxm2_le (n k : ℤ) : maxm2 (n+1+k) ≤ (maxm1m1 n).+1+2+(maxm1m1 k) := begin rewrite [-(maxm1_eq_succ n)], induction n with n n, { induction k with k k, { induction k with k IH, { apply le.tr_refl }, { exact succ_le_succ IH } }, { exact trunc_index.le_trans (maxm2_monotone maxm2_le.lemma₁) (maxm2_le_maxm1 n) } }, { krewrite (add_plus_two_comm -1 (maxm1m1 k)), rewrite [-(maxm1_eq_succ k)], exact trunc_index.le_trans (maxm2_monotone maxm2_le.lemma₂) (maxm2_le_maxm1 k) } end end int open int
e905f7d42ba8a9994ae98e2807386d9894c40f13
1dd482be3f611941db7801003235dc84147ec60a
/src/data/list/alist.lean
de1b91276266a83349aeaf1e218098d292a46a80
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
6,023
lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro Association lists. -/ import data.list.sigma universes u v w open list variables {α : Type u} {β : α → Type v} /-- `alist β` is a key-value map stored as a `list` (i.e. a linked list). It is a wrapper around certain `list` functions with the added constraint that the list have unique keys. -/ structure alist (β : α → Type v) : Type (max u v) := (entries : list (sigma β)) (nodupkeys : entries.nodupkeys) namespace alist @[extensionality] theorem ext : ∀ {s t : alist β}, s.entries = t.entries → s = t | ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr' /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : has_mem α (alist β) := ⟨λ a s, ∃ b : β a, sigma.mk a b ∈ s.entries⟩ theorem mem_def {a : α} {s : alist β} : a ∈ s ↔ ∃ b : β a, sigma.mk a b ∈ s.entries := iff.rfl theorem mem_of_perm {a : α} {s₁ s₂ : alist β} (p : s₁.entries ~ s₂.entries) : a ∈ s₁ ↔ a ∈ s₂ := exists_congr $ λ b, mem_of_perm p /-- The list of keys of an association list. -/ def keys (s : alist β) : list α := s.entries.map sigma.fst theorem mem_keys {a : α} {s : alist β} : a ∈ s.keys ↔ a ∈ s := by rw [keys, mem_map]; exact ⟨λ ⟨⟨_, b⟩, h, rfl⟩, ⟨b, h⟩, λ ⟨b, h⟩, ⟨_, h, rfl⟩⟩ theorem keys_nodup (s : alist β) : s.keys.nodup := s.nodupkeys /-- The empty association list. -/ instance : has_emptyc (alist β) := ⟨⟨[], nodupkeys_nil⟩⟩ theorem not_mem_empty_entries {s : sigma β} : s ∉ (∅ : alist β).entries := not_mem_nil _ theorem not_mem_empty {a : α} : a ∉ (∅ : alist β) := λ ⟨b, h⟩, not_mem_empty_entries h @[simp] theorem keys_empty : (∅ : alist β).keys = [] := rfl /-- The singleton association list. -/ def singleton (a : α) (b : β a) : alist β := ⟨[⟨a, b⟩], nodupkeys_singleton _⟩ @[simp] theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = [a] := rfl variables [decidable_eq α] /-- Look up the value associated to a key in an association list. -/ def lookup (a : α) (s : alist β) : option (β a) := s.entries.lookup a theorem lookup_is_some {a : α} {s : alist β} : (s.lookup a).is_some ↔ a ∈ s := lookup_is_some theorem perm_lookup {a : α} {s₁ s₂ : alist β} (p : s₁.entries ~ s₂.entries) : s₁.lookup a = s₂.lookup a := perm_lookup _ s₁.nodupkeys s₂.nodupkeys p instance (a : α) (s : alist β) : decidable (a ∈ s) := decidable_of_iff _ lookup_is_some /-- Insert a key-value pair into an association list. If the key is already present it does nothing. -/ def insert (a : α) (b : β a) (s : alist β) : alist β := if h : a ∈ s then s else ⟨⟨a, b⟩ :: s.entries, nodup_cons.2 ⟨mt mem_keys.1 h, s.nodupkeys⟩⟩ @[simp] theorem insert_of_pos {a : α} {b : β a} {s : alist β} (h : a ∈ s) : insert a b s = s := dif_pos h theorem insert_entries_of_neg {a : α} {b : β a} {s : alist β} (h : a ∉ s) : (insert a b s).entries = ⟨a, b⟩ :: s.entries := by simp [insert, h] @[simp] theorem keys_insert (a : α) (b : β a) (s : alist β) : (insert a b s).keys = _root_.insert a s.keys := begin by_cases a ∈ s, { simp [h, mem_keys.2 h] }, { simp [keys, insert_entries_of_neg h], exact (insert_of_not_mem (mt mem_keys.1 h)).symm } end @[simp] theorem mem_insert {a a' : α} {b : β a} {s : alist β} : a' ∈ insert a b s ↔ a' = a ∨ a' ∈ s := by rw [← mem_keys, ← mem_keys]; simp theorem perm_insert {a : α} {b : β a} {s₁ s₂ : alist β} (p : s₁.entries ~ s₂.entries) : (insert a b s₁).entries ~ (insert a b s₂).entries := begin by_cases a ∈ s₁, { simp [h, (mem_of_perm p).1 h, p] }, { simp [insert_entries_of_neg h, insert_entries_of_neg (mt (mem_of_perm p).2 h)], exact p.skip _ } end /-- Replace a key with a given value in an association list. If the key is not present it does nothing. -/ def replace (a : α) (b : β a) (s : alist β) : alist β := ⟨kreplace a b s.entries, (kreplace_nodupkeys a b).2 s.nodupkeys⟩ @[simp] theorem keys_replace (a : α) (b : β a) (s : alist β) : (replace a b s).keys = s.keys := kreplace_map_fst _ _ _ @[simp] theorem mem_replace {a a' : α} {b : β a} {s : alist β} : a' ∈ replace a b s ↔ a' ∈ s := by rw [← mem_keys, keys_replace, mem_keys] theorem perm_replace {a : α} {b : β a} {s₁ s₂ : alist β} : s₁.entries ~ s₂.entries → (replace a b s₁).entries ~ (replace a b s₂).entries := perm_kreplace s₁.nodupkeys /-- Fold a function over the key-value pairs in the map. -/ def foldl {δ : Type w} (f : δ → Π a, β a → δ) (d : δ) (m : alist β) : δ := m.entries.foldl (λ r a, f r a.1 a.2) d /-- Erase a key from the map. If the key is not present it does nothing. -/ def erase (a : α) (s : alist β) : alist β := ⟨kerase a s.entries, kerase_nodupkeys _ s.nodupkeys⟩ @[simp] theorem keys_erase (a : α) (s : alist β) : (erase a s).keys = s.keys.erase a := by rw [erase_eq_erasep, keys, keys, erasep_map]; refl @[simp] theorem mem_erase {a a' : α} {s : alist β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := by rw [← mem_keys, keys_erase, mem_erase_iff_of_nodup s.keys_nodup, mem_keys] theorem perm_erase {a : α} {s₁ s₂ : alist β} : s₁.entries ~ s₂.entries → (erase a s₁).entries ~ (erase a s₂).entries := perm_kerase s₁.nodupkeys /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : α) (s : alist β) : option (β a) × alist β := have (kextract a s.entries).2.nodupkeys, by rw [kextract_eq_lookup_kerase]; exact kerase_nodupkeys _ s.nodupkeys, match kextract a s.entries, this with | (b, l), h := (b, ⟨l, h⟩) end @[simp] theorem extract_eq_lookup_erase (a : α) (s : alist β) : extract a s = (lookup a s, erase a s) := by simp [extract]; split; refl end alist
162d53e0a55498b50cc86ddd08098a0b65ed5f99
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/lint/basic.lean
7e41666a417c19ba0157abb4c2dfaa7cc711e465
[]
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
2,084
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort namespace Mathlib /-! # Basic linter types and attributes This file defines the basic types and attributes used by the linting framework. A linter essentially consists of a function `declaration → tactic (option string)`, this function together with some metadata is stored in the `linter` structure. We define two attributes: * `@[linter]` applies to a declaration of type `linter` and adds it to the default linter set. * `@[nolint linter_name]` omits the tagged declaration from being checked by the linter with name `linter_name`. -/ /-- We store the list of nolint names as `@id (list name) (Prop simp_nf doc_blame has_coe_t)` See Note [user attribute parameters] -/ /-- Defines the user attribute `nolint` for skipping `#lint` -/ /-- `should_be_linted linter decl` returns true if `decl` should be checked using `linter`, i.e., if there is no `nolint` attribute. -/ /-- A linting test for the `#lint` command. `test` defines a test to perform on every declaration. It should never fail. Returning `none` signifies a passing test. Returning `some msg` reports a failing test with error `msg`. `no_errors_found` is the message printed when all tests are negative, and `errors_found` is printed when at least one test is positive. If `is_fast` is false, this test will be omitted from `#lint-`. If `auto_decls` is true, this test will also be executed on automatically generated declarations. -/ /-- Takes a list of names that resolve to declarations of type `linter`, and produces a list of linters. -/ /-- Defines the user attribute `linter` for adding a linter to the default set. Linters should be defined in the `linter` namespace. A linter `linter.my_new_linter` is referred to as `my_new_linter` (without the `linter` namespace) when used in `#lint`. -/
5f9884a516dcac82feb366abb70930542cb5a1cb
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/setoid/partition.lean
d6015200388646a3e131b4223d66fbd6cf931021
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
9,153
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen -/ import data.setoid.basic import data.set.lattice /-! # Equivalence relations: partitions This file comprises properties of equivalence relations viewed as partitions. ## Tags setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class -/ namespace setoid variables {α : Type*} /-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/ lemma eq_of_mem_eqv_class {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') : b = b' := (H x).unique2 hc hb hc' hb' /-- Makes an equivalence relation from a set of sets partitioning α. -/ def mk_classes (c : set (set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) : setoid α := ⟨λ x y, ∀ s ∈ c, x ∈ s → y ∈ s, ⟨λ _ _ _ hx, hx, λ x y h s hs hy, (H x).elim2 $ λ t ht hx _, have s = t, from eq_of_mem_eqv_class H hs hy ht (h t ht hx), this.symm ▸ hx, λ x y z h1 h2 s hs hx, (H y).elim2 $ λ t ht hy _, (H z).elim2 $ λ t' ht' hz _, have hst : s = t, from eq_of_mem_eqv_class H hs (h1 _ hs hx) ht hy, have htt' : t = t', from eq_of_mem_eqv_class H ht (h2 _ ht hy) ht' hz, (hst.trans htt').symm ▸ hz⟩⟩ /-- Makes the equivalence classes of an equivalence relation. -/ def classes (r : setoid α) : set (set α) := {s | ∃ y, s = {x | r.rel x y}} lemma mem_classes (r : setoid α) (y) : {x | r.rel x y} ∈ r.classes := ⟨y, rfl⟩ /-- Two equivalence relations are equal iff all their equivalence classes are equal. -/ lemma eq_iff_classes_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ ∀ x, {y | r₁.rel x y} = {y | r₂.rel x y} := ⟨λ h x, h ▸ rfl, λ h, ext' $ λ x, set.ext_iff.1 $ h x⟩ lemma rel_iff_exists_classes (r : setoid α) {x y} : r.rel x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c := ⟨λ h, ⟨_, r.mem_classes y, h, r.refl' y⟩, λ ⟨c, ⟨z, hz⟩, hx, hy⟩, by { subst c, exact r.trans' hx (r.symm' hy) }⟩ /-- Two equivalence relations are equal iff their equivalence classes are equal. -/ lemma classes_inj {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.classes = r₂.classes := ⟨λ h, h ▸ rfl, λ h, ext' $ λ a b, by simp only [rel_iff_exists_classes, exists_prop, h] ⟩ /-- The empty set is not an equivalence class. -/ lemma empty_not_mem_classes {r : setoid α} : ∅ ∉ r.classes := λ ⟨y, hy⟩, set.not_mem_empty y $ hy.symm ▸ r.refl' y /-- Equivalence classes partition the type. -/ lemma classes_eqv_classes {r : setoid α} (a) : ∃! b ∈ r.classes, a ∈ b := exists_unique.intro2 {x | r.rel x a} (r.mem_classes a) (r.refl' _) $ begin rintros _ ⟨y, rfl⟩ ha, ext x, exact ⟨λ hx, r.trans' hx (r.symm' ha), λ hx, r.trans' hx ha⟩ end /-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/ lemma eq_of_mem_classes {r : setoid α} {x b} (hc : b ∈ r.classes) (hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' := eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb' /-- The elements of a set of sets partitioning α are the equivalence classes of the equivalence relation defined by the set of sets. -/ lemma eq_eqv_class_of_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) : s = {x | (mk_classes c H).rel x y} := set.ext $ λ x, ⟨λ hs', symm' (mk_classes c H) $ λ b' hb' h', eq_of_mem_eqv_class H hs hy hb' h' ▸ hs', λ hx, (H x).elim2 $ λ b' hc' hb' h', (eq_of_mem_eqv_class H hs hy hc' $ hx b' hc' hb').symm ▸ hb'⟩ /-- The equivalence classes of the equivalence relation defined by a set of sets partitioning α are elements of the set of sets. -/ lemma eqv_class_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} : {x | (mk_classes c H).rel x y} ∈ c := (H y).elim2 $ λ b hc hy hb, eq_eqv_class_of_mem H hc hy ▸ hc /-- Distinct elements of a set of sets partitioning α are disjoint. -/ lemma eqv_classes_disjoint {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) : set.pairwise_disjoint c := λ b₁ h₁ b₂ h₂ h, set.disjoint_left.2 $ λ x hx1 hx2, (H x).elim2 $ λ b hc hx hb, h $ eq_of_mem_eqv_class H h₁ hx1 h₂ hx2 /-- A set of disjoint sets covering α partition α (classical). -/ lemma eqv_classes_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : set.pairwise_disjoint c) (a) : ∃! b ∈ c, a ∈ b := let ⟨b, hc, ha⟩ := set.mem_sUnion.1 $ show a ∈ _, by rw hu; exact set.mem_univ a in exists_unique.intro2 b hc ha $ λ b' hc' ha', H.elim hc' hc a ha' ha /-- Makes an equivalence relation from a set of disjoints sets covering α. -/ def setoid_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : set.pairwise_disjoint c) : setoid α := setoid.mk_classes c $ eqv_classes_of_disjoint_union hu H /-- The equivalence relation made from the equivalence classes of an equivalence relation r equals r. -/ theorem mk_classes_classes (r : setoid α) : mk_classes r.classes classes_eqv_classes = r := ext' $ λ x y, ⟨λ h, r.symm' (h {z | r.rel z x} (r.mem_classes x) $ r.refl' x), λ h b hb hx, eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩ @[simp] theorem sUnion_classes (r : setoid α) : ⋃₀ r.classes = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 ⟨{ y | r.rel y x }, ⟨x, rfl⟩, setoid.refl _⟩ section partition /-- A collection `c : set (set α)` of sets is a partition of `α` into pairwise disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/ def is_partition (c : set (set α)) := ∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b /-- A partition of `α` does not contain the empty set. -/ lemma nonempty_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (h : s ∈ c) : s.nonempty := set.ne_empty_iff_nonempty.1 $ λ hs0, hc.1 $ hs0 ▸ h lemma is_partition_classes (r : setoid α) : is_partition r.classes := ⟨empty_not_mem_classes, classes_eqv_classes⟩ lemma is_partition.pairwise_disjoint {c : set (set α)} (hc : is_partition c) : c.pairwise_disjoint := eqv_classes_disjoint hc.2 lemma is_partition.sUnion_eq_univ {c : set (set α)} (hc : is_partition c) : ⋃₀ c = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 $ let ⟨t, ht⟩ := hc.2 x in ⟨t, by clear_aux_decl; finish⟩ /-- All elements of a partition of α are the equivalence class of some y ∈ α. -/ lemma exists_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (hs : s ∈ c) : ∃ y, s = {x | (mk_classes c hc.2).rel x y} := let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs in ⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩ /-- The equivalence classes of the equivalence relation defined by a partition of α equal the original partition. -/ theorem classes_mk_classes (c : set (set α)) (hc : is_partition c) : (mk_classes c hc.2).classes = c := set.ext $ λ s, ⟨λ ⟨y, hs⟩, (hc.2 y).elim2 $ λ b hm hb hy, by rwa (show s = b, from hs.symm ▸ set.ext (λ x, ⟨λ hx, symm' (mk_classes c hc.2) hx b hm hb, λ hx b' hc' hx', eq_of_mem_eqv_class hc.2 hm hx hc' hx' ▸ hb⟩)), exists_of_mem_partition hc⟩ /-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/ instance partition.le : has_le (subtype (@is_partition α)) := ⟨λ x y, mk_classes x.1 x.2.2 ≤ mk_classes y.1 y.2.2⟩ /-- Defining a partial order on partitions as the partial order on their induced equivalence relations. -/ instance partition.partial_order : partial_order (subtype (@is_partition α)) := { le := (≤), lt := λ x y, x ≤ y ∧ ¬y ≤ x, le_refl := λ _, @le_refl (setoid α) _ _, le_trans := λ _ _ _, @le_trans (setoid α) _ _ _ _, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ x y hx hy, let h := @le_antisymm (setoid α) _ _ _ hx hy in by rw [subtype.ext_iff_val, ←classes_mk_classes x.1 x.2, ←classes_mk_classes y.1 y.2, h] } variables (α) /-- The order-preserving bijection between equivalence relations and partitions of sets. -/ def partition.rel_iso : setoid α ≃o subtype (@is_partition α) := { to_fun := λ r, ⟨r.classes, empty_not_mem_classes, classes_eqv_classes⟩, inv_fun := λ x, mk_classes x.1 x.2.2, left_inv := mk_classes_classes, right_inv := λ x, by rw [subtype.ext_iff_val, ←classes_mk_classes x.1 x.2], map_rel_iff' := λ x y, by conv {to_lhs, rw [←mk_classes_classes x, ←mk_classes_classes y]}; refl } variables {α} /-- A complete lattice instance for partitions; there is more infrastructure for the equivalent complete lattice on equivalence relations. -/ instance partition.complete_lattice : complete_lattice (subtype (@is_partition α)) := galois_insertion.lift_complete_lattice $ @rel_iso.to_galois_insertion _ (subtype (@is_partition α)) _ (partial_order.to_preorder _) $ partition.rel_iso α end partition end setoid
67bbff155be933a82e4881a55f2177f0a0f48045
1437b3495ef9020d5413178aa33c0a625f15f15f
/data/finsupp.lean
be90196b839cf211fb47a857ae781ba567063172
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,177
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 Type of functions with finite support. Functions with finite support provide the basis for the following concrete instances: * ℕ →₀ α: Polynomials (where α is a ring) * (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names) * α →₀ ℕ: Multisets * α →₀ ℤ: Abelian groups freely generated by α * β →₀ α: Linear combinations over β where α is the scalar ring Most of the theory assumes that the range is a commutative monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. A general advice is to not use α →₀ β directly, as the type class setup might not be fitting. The best is to define a copy and select the instances best suited. -/ import data.finset data.set.finite algebra.big_operators algebra.module open finset variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*} {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} reserve infix ` →₀ `:25 /-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (β : Type*) [has_zero β] := (support : finset α) (to_fun : α → β) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infix →₀ := finsupp namespace finsupp section basic variable [has_zero β] instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩ instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl instance : inhabited (α →₀ β) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 := by haveI := classical.dec; exact not_iff_comm.1 mem_support_iff.symm @[extensionality] lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin have : f = g, { funext a, exact h a }, subst this, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end @[simp] lemma support_eq_empty [decidable_eq β] {f : α →₀ β} : f.support = ∅ ↔ f = 0 := ⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $ mem_support_iff.2 H, by rintro rfl; refl⟩ instance [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ⟨assume ⟨h₁, h₂⟩, ext $ assume a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, by rwa [mem_support_iff, not_not] at h, have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h, by rw [hf, hg], by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩ lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} := ⟨set.fintype_of_finset f.support (λ _, mem_support_iff)⟩ lemma support_subset_iff {s : set α} {f : α →₀ β} [decidable_eq α] : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) end basic section single variables [decidable_eq α] [decidable_eq β] [has_zero β] {a a' : α} {b : β} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : β) : α →₀ β := ⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl @[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h @[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 := ext $ assume a', begin by_cases h : a = a', { rw [h, single_eq_same, zero_apply] }, { rw [single_eq_of_ne h, zero_apply] } end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] end single section on_finset variables [decidable_eq β] [has_zero β] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`. The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise often better set representation is available. -/ def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β := ⟨s.filter (λa, f a ≠ 0), f, assume a, classical.by_cases (assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩) (assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} : (on_finset s f hf : α →₀ β) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ end on_finset section map_range variables [has_zero β₁] [has_zero β₂] [decidable_eq β₂] /-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is `map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/ def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 := finsupp.ext $ λ a, by simp [hf] lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset variables [decidable_eq α] [decidable_eq β₁] @[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} : map_range f hf (single a b) = single a (f b) := finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range section zip_with variables [has_zero β] [has_zero β₁] [has_zero β₂] [decidable_eq α] [decidable_eq β] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/ def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin haveI := classical.dec_eq β₁, simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := support_on_finset_subset end zip_with section erase variables [decidable_eq α] [decidable_eq β] def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h end erase -- [to_additive finsupp.sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.sum (λa, g a (f a)) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive finsupp.sum] def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.prod (λa, g a (f a)) attribute [to_additive finsupp.sum.equations._eqn_1] finsupp.prod.equations._eqn_1 @[to_additive finsupp.sum_map_range_index] lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] [decidable_eq β₂] {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[to_additive finsupp.sum_zero_index] lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} : (0 : α →₀ β).prod h = 1 := rfl section decidable variables [decidable_eq α] [decidable_eq β] section add_monoid variables [add_monoid β] @[to_additive finsupp.sum_single_index] lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := begin by_cases h : b = 0, { simp only [h, h_zero, single_zero]; refl }, { simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton, prod_singleton, single_eq_same] } end instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support): (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_monoid (α →₀ β) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) := by refine_struct {..}; simp lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero] else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)] lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add] else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)] @[elab_as_eliminator] protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma map_range_add [decidable_eq β₁] [decidable_eq β₂] [add_monoid β₁] [add_monoid β₂] {f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := finsupp.ext $ λ a, by simp [hf'] end add_monoid instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group β] : add_group (α →₀ β) := { neg := map_range (has_neg.neg) neg_zero, add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, .. finsupp.add_monoid } lemma single_multiset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β] (s : multiset β) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β] (s : finset γ) (f : γ → β) (a : α) : single a (s.sum f) = s.sum (λb, single a (f b)) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero γ] [add_comm_monoid β] [decidable_eq α] [decidable_eq β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive finsupp.sum_neg_index] lemma prod_neg_index [add_group β] [comm_monoid γ] {g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl @[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) instance [add_comm_group β] : add_comm_group (α →₀ β) := { add_comm := add_comm, ..finsupp.add_group } @[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (finset.sum_hom (λf : α →₀ β, f a₂)).symm lemma support_sum [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} : (f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) := have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 → (∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this @[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} : f.sum (λa b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h := finset.sum_hom (@has_neg.neg γ _) @[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl @[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) : f.sum single = f := have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) = ({a} : finset α).sum (λa', ite (a' = a) (f a') 0), begin intro a, by_cases h : a ∈ f.support, { have : (finset.singleton a : finset α) ⊆ f.support, { simpa only [finset.subset_iff, mem_singleton, forall_eq] }, refine (finset.sum_subset this (λ _ _ H, _)).symm, exact if_neg (mt mem_singleton.2 H) }, { transitivity (f.support.sum (λa, (0 : β))), { refine (finset.sum_congr rfl $ λ a' ha', if_neg _), rintro rfl, exact h ha' }, { rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton, if_pos rfl, not_mem_support_iff.1 h] } } end, ext $ assume a, by simp only [sum_apply, single_apply, this, insert_empty_eq_singleton, sum_singleton, if_pos] @[to_additive finsupp.sum_add_index] lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, calc (f + g).support.prod (λa, h a ((f + g) a)) = (f.support ∪ g.support).prod (λa, h a ((f + g) a)) : finset.prod_subset support_add $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero] ... = (f.support ∪ g.support).prod (λa, h a (f a)) * (f.support ∪ g.support).prod (λa, h a (g a)) : by simp only [add_apply, h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀a, h a 0 = 0, from assume a, have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0, by simpa only [sub_self] using this, have h_neg : ∀a b, h a (- b) = - h a b, from assume a b, have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b, by simpa only [h_zero, zero_sub] using this, have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂, from assume a b₁ b₂, have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂), by simpa only [h_neg, sub_neg_eq_add] using this, calc (f - g).sum h = (f + - g).sum h : rfl ... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg] ... = f.sum h - g.sum h : rfl @[to_additive finsupp.sum_finset_sum_index] lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ] [decidable_eq ι] {s : finset ι} {g : ι → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂): s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive finsupp.sum_sum_index] lemma prod_sum_index [decidable_eq α₁] [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂): (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [decidable_eq α] [decidable_eq β] [add_comm_monoid β] [add_comm_monoid γ] (f : multiset (α →₀ β)) (h : α → β → γ) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (finset.sum_hom _).symm lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (finset.sum_hom multiset.sum).symm section map_domain variables [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] {v v₁ v₂ : α →₀ β} /-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β` is the finitely supported function whose value at `a : α₂` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β := v.sum $ λa, single (f a) lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (λ _ _, sum_single_index _), { exact single_zero } end lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) := sum_zero_index lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_finset_sum [decidable_eq ι] {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} : map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_support {f : α → α₂} {s : α →₀ β} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $ by rw [finset.bind_singleton]; exact subset.refl _ @[to_additive finsupp.sum_map_domain_index] lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β} {h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _) end map_domain /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the monoid of monomial exponents.) -/ instance [has_add α] [semiring β] : has_mul (α →₀ β) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl /-- The unit of the multiplication is `single 0 1`, i.e. the function that is 1 at 0 and zero elsewhere. -/ instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) := ⟨single 0 1⟩ lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl section filter section has_zero variables [has_zero β] (p : α → Prop) [decidable_pred p] (f : α →₀ β) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) [decidable_pred p] (f : α →₀ β) : α →₀ β := on_finset f.support (λa, if p a then f a else 0) $ λ a H, mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter : (f.filter p).support = f.support.filter p := finset.ext.mpr $ assume a, if H : p a then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true] else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def, ne_self_iff_false] @[simp] lemma filter_single_of_pos {a : α} {b : β} (h : p a) : (single a b).filter p = single a b := finsupp.ext $ λ x, begin by_cases h' : p x; simp [h'], rw single_eq_of_ne, rintro rfl, exact h' h end @[simp] lemma filter_single_of_neg {a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 := finsupp.ext $ λ x, begin by_cases h' : p x; simp [h'], rw single_eq_of_ne, rintro rfl, exact h h' end end has_zero lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) [decidable_pred p] : f.filter p + f.filter (λa, ¬ p a) = f := finsupp.ext $ assume a, if H : p a then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero] else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add] end filter section frange variables [has_zero β] def frange (f : α →₀ β) : finset β := finset.image f f.support theorem mem_frange {f : α →₀ β} {y : β} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange section subtype_domain variables {α' : Type*} [has_zero δ] {p : α → Prop} [decidable_pred p] section zero variables [has_zero β] {v v' : α' →₀ β} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) [decidable_pred p] (f : α →₀ β) : (subtype p →₀ β) := ⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain {f : α →₀ β} : (subtype_domain p f).support = f.support.subtype p := rfl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 := rfl @[to_additive finsupp.sum_subtype_domain_index] lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β} {h : α → β → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section monoid variables [add_monoid β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_add {v v' : α →₀ β} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl instance subtype_domain.is_add_monoid_hom [add_monoid β] : is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) := by refine_struct {..}; simp @[simp] lemma filter_add {v v' : α →₀ β} : (v + v').filter p = v.filter p + v'.filter p := ext $ λ a, by by_cases p a; simp [h] end monoid section comm_monoid variables [add_comm_monoid β] lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (finset.sum_hom _) lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end comm_monoid section group variables [add_group β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_neg {v : α →₀ β} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub {v v' : α →₀ β} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl end group end subtype_domain section multiset def to_multiset (f : α →₀ ℕ) : multiset α := f.sum (λa n, add_monoid.smul n {a}) @[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) : (finset.sum_hom _).symm ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul] ... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl ... = f a * (a :: 0 : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by simp only [multiset.count_singleton, mul_one] def of_multiset [decidable_eq α] (m : multiset α) : α →₀ ℕ := on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $ by_contradiction (mt multiset.count_eq_zero.2 H) @[simp] lemma of_multiset_apply [decidable_eq α] (m : multiset α) (a : α) : of_multiset m a = m.count a := rfl def equiv_multiset [decidable_eq α] : (α →₀ ℕ) ≃ (multiset α) := ⟨ to_multiset, of_multiset, assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset], assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩ lemma mem_support_multiset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β] {s : multiset (α →₀ β)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β] {s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ lemma mem_support_single [decidable_eq α] [decidable_eq β] [has_zero β] (a a' : α) (b : β) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := ⟨λ H : (a ∈ ite _ _ _), if h : b = 0 then by rw if_pos h at H; exact H.elim else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩, λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩ end multiset section curry_uncurry protected def curry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ] (f : (α × β) →₀ γ) : α →₀ (β →₀ γ) := f.sum $ λp c, single p.1 (single p.2 c) lemma sum_curry_index [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ] [add_comm_monoid δ] (f : (α × β) →₀ γ) (g : α → β → γ → δ) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end protected def uncurry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ := f.sum $ λa g, g.sum $ λb c, single (a, b) c def finsupp_prod_equiv [add_comm_monoid γ] [decidable_eq α] [decidable_eq β] [decidable_eq γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] end curry_uncurry section variables [add_monoid α] [semiring β] -- TODO: the simplifier unfolds 0 in the instance proof! private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] def to_semiring : semiring (α →₀ β) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := zero_mul, mul_zero := mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } end local attribute [instance] to_semiring def to_comm_semiring [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [add_comm] end, .. finsupp.to_semiring } local attribute [instance] to_comm_semiring def to_ring [add_monoid α] [ring β] : ring (α →₀ β) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. finsupp.to_semiring } def to_comm_ring [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) := { mul_comm := mul_comm, .. finsupp.to_ring} lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}: single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := (sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [_root_.mul_zero, single_zero])) lemma prod_single [decidable_eq ι] [add_comm_monoid α] [comm_semiring β] {s : finset ι} {a : ι → α} {b : ι → β} : s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] section variables (α β) def to_has_scalar' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ local attribute [instance] to_has_scalar' @[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {a : α} {b : γ} {v : α →₀ β} : (b • v) a = b • (v a) := rfl def to_semimodule {R:semiring γ} [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) := { smul := (•), smul_add := λ a x y, finsupp.ext $ λ _, smul_add _ _ _, add_smul := λ a x y, finsupp.ext $ λ _, add_smul _ _ _, one_smul := λ x, finsupp.ext $ λ _, one_smul _, mul_smul := λ r s x, finsupp.ext $ λ _, mul_smul _ _ _, zero_smul := λ x, finsupp.ext $ λ _, zero_smul _, smul_zero := λ x, finsupp.ext $ λ _, smul_zero _ } def to_module {R:ring γ} [add_comm_group β] [module γ β] : module γ (α →₀ β) := { ..to_semimodule α β } variables {α β} lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} : (b • g).support ⊆ g.support := λ a, by simp; exact mt (λ h, h.symm ▸ smul_zero _) section variables {α' : Type*} [has_zero δ] {p : α → Prop} [decidable_pred p] @[simp] lemma filter_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p := ext $ λ a, by by_cases p a; simp [h] end lemma map_domain_smul {α'} [decidable_eq α'] {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v := begin change map_domain f (map_range _ _ _) = map_range _ _ _, apply finsupp.induction v, {simp}, intros a b v' hv₁ hv₂ IH, rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add, map_range_single, map_domain_single, map_domain_single, map_range_single]; apply smul_add end @[simp] lemma smul_single {R:semiring γ} [add_comm_monoid β] [semimodule γ β] (c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) := ext $ λ a', by by_cases a = a'; [{subst h, simp}, simp [h]] end def to_has_scalar [ring β] : has_scalar β (α →₀ β) := to_has_scalar' α β local attribute [instance] to_has_scalar @[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} : (b • v) a = b • (v a) := rfl lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 end decidable section variables [semiring β] [semiring γ] lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} : (s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma mul_sum [semiring β] [semiring γ] (b : γ) (s : α →₀ β) {f : α → β → γ} : b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) := by simp only [finsupp.sum, finset.mul_sum] end end finsupp
72257d3c4a522c1f3905e5e4ffdf15a29b3fd309
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tmp/new-frontend/expander.lean
9faab8592703b297a3f134252c3968240ee028ed
[ "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
23,488
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich Macro Expander for the Lean language, using a variant of the [sets of scopes](http://www.cs.utah.edu/plt/Scope-sets/) hygiene algorithm. TODO(Sebastian): document/link to documentation of algorithm -/ prelude import init.lean.parser.module import init.lean.expr namespace Lean namespace Expander open Parser open Parser.Combinators open Parser.Term open Parser.command structure TransformerConfig extends FrontendConfig -- TODO(Sebastian): the recursion point for `localExpand` probably needs to be stored here instance transformerConfigCoeFrontendConfig : HasCoe TransformerConfig FrontendConfig := ⟨TransformerConfig.toFrontendConfig⟩ -- TODO(Sebastian): recursive expansion @[derive Monad MonadReader MonadExcept] def TransformM := ReaderT FrontendConfig $ ExceptT Message Id abbrev transformer := Syntax → TransformM (Option Syntax) /-- We allow macros to refuse expansion. This means that nodes can decide whether to act as macros or not depending on their contents, allowing them to unfold to some normal form without changing the general Node kind and shape (and thus View Type). -/ def noExpansion : TransformM (Option Syntax) := pure none def error {m : Type → Type} {ρ : Type} [Monad m] [MonadReader ρ m] [HasLiftT ρ FrontendConfig] [MonadExcept Message m] {α : Type} (context : Option Syntax) (text : String) : m α := do cfg ← read, throw { filename := FrontendConfig.filename ↑cfg, pos := (FrontendConfig.fileMap ↑cfg).toPosition $ (context >>= Syntax.getPos).getOrElse (default _), text := text } /-- Coercion useful for introducing macro-local variables. Use `globId` to refer to global bindings instead. -/ instance coeNameIdent : HasCoe Name SyntaxIdent := ⟨λ n, {val := n, rawVal := Substring.ofString n.toString}⟩ /-- Create an identifier preresolved against a global binding. Because we cannot use Syntax quotations yet, which the Expander would have preresolved against the global context at macro declaration time, we have to do the preresolution manually instead. -/ def globId (n : Name) : Syntax := review identUnivs { id :={val := n, rawVal := Substring.ofString n.toString, preresolved := [n]}, } instance coeIdentIdentUnivs : HasCoe SyntaxIdent identUnivs.View := ⟨λ id, {id := id}⟩ instance coeIdentBinderId : HasCoe SyntaxIdent binderIdent.View := ⟨binderIdent.View.id⟩ instance coeIdentsBindersExt {α : Type} [HasCoeT α binderIdent.View] : HasCoe (List α) Term.bindersExt.View := ⟨λ ids, {leadingIds := ids.map coe}⟩ instance coeBracketedBinderMixedBinder : HasCoe bracketedBinder.View mixedBinder.View := ⟨mixedBinder.View.bracketed⟩ instance coeMixedBindersBindersExt {α : Type} [HasCoeT α mixedBinder.View] : HasCoe (List α) Term.bindersExt.View := ⟨λ mbs, {leadingIds := [], remainder := some $ bindersRemainder.View.mixed $ mbs.map coe}⟩ instance coeBindersExtBinders : HasCoe Term.bindersExt.View Term.binders.View := ⟨Term.binders.View.extended⟩ instance coeSimpleBinderBinders : HasCoe Term.simpleBinder.View Term.binders.View := ⟨Term.binders.View.simple⟩ instance coeBinderBracketedBinder : HasCoe Term.binder.View Term.bracketedBinder.View := ⟨λ b, match b with | binder.View.bracketed bb := bb | binder.View.unbracketed bc := Term.bracketedBinder.View.explicit {content := explicitBinderContent.View.other bc}⟩ section «notation» open Parser.command.NotationSpec /-- A notation together with a unique Node kind. -/ structure NotationMacro := (kind : SyntaxNodeKind) (nota : notation.View) /-- Helper State of the loop in `mkNotationTransformer`. -/ structure NotationTransformerState := (stx : Syntax) -- children of `stx` that have not been consumed yet (stxArgs : List Syntax := []) -- substitutions for notation variables (reversed) (substs : List (SyntaxIdent × Syntax) := []) -- filled by `binders` transitions, consumed by `scoped` actions (scoped : Option $ Term.binders.View := none) private def popStxArg : StateT NotationTransformerState TransformM Syntax := do st ← get, match st.stxArgs with | Arg::args := set {st with stxArgs := args} *> pure Arg | _ := error st.stx "mkNotationTransformer: unreachable" def mkNotationTransformer (nota : NotationMacro) : transformer := λ stx, do some {args := stxArgs, ..} ← pure stx.asNode | error stx "mkNotationTransformer: unreachable", flip StateT.run' {NotationTransformerState . stx := stx, stxArgs := stxArgs} $ do let spec := nota.nota.spec, -- Walk through the notation specification, consuming `stx` args and building up substitutions -- for the notation RHS. -- Also see `CommandParserConfig.registerNotationParser` for the expected structure of `stx`. match spec.prefixArg with | none := pure () | some Arg := do { stxArg ← popStxArg, modify $ λ st, {st with substs := (Arg, stxArg)::st.substs} }, nota.nota.spec.rules.mfor (λ r : rule.View, do match r.symbol with | notationSymbol.View.quoted {symbol := some a ..} := popStxArg | _ := error stx "mkNotationTransformer: unreachable", match r.transition with | some (transition.View.binder b) := do { stxArg ← popStxArg, modify $ λ st, {st with scoped := some $ binders.View.extended {leadingIds := [view binderIdent.Parser stxArg]}} } | some (transition.View.binders b) := do { stxArg ← popStxArg, modify $ λ st, {st with scoped := some $ view Term.binders.Parser stxArg} } | some (transition.View.Arg {action := none, id := id}) := do { stxArg ← popStxArg, modify $ λ st, {st with substs := (id, stxArg)::st.substs} } | some (transition.View.Arg {action := some {kind := actionKind.View.prec _}, id := id}) := do { stxArg ← popStxArg, modify $ λ st, {st with substs := (id, stxArg)::st.substs} } | some (transition.View.Arg {action := some {kind := actionKind.View.scoped sc}, id := id}) := do stxArg ← popStxArg, {scoped := some bnders, ..} ← get | error stx "mkNotationTransformer: unreachable", -- TODO(Sebastian): not correct with multiple binders let scLam := review lambda {binders := [sc.id], body := sc.Term}, let lam := review lambda {binders := bnders, body := stxArg}, let Arg := review app {fn := scLam, Arg := lam}, modify $ λ st, {st with substs := (id, Arg)::st.substs} | none := pure () | _ := error stx "mkNotationTransformer: unimplemented"), st ← get, -- apply substitutions -- HACK: this substitution completely disregards binders on the notation's RHS. -- We have discussed switching to a more explicit antiquotation Syntax like %%_ -- that cannot be abstracted over. let substs := st.substs.map (λ ⟨id, t⟩, (id.val, t)), let t := nota.nota.Term.replace $ λ stx, match tryView identUnivs stx with | some {id := id, univs := none} := pure $ substs.lookup id.val | _ := pure none, pure $ some $ t def mixfixToNotationSpec (k : mixfix.kind.View) (sym : notationSymbol.View) : TransformM NotationSpec.View := let prec := match sym with | notationSymbol.View.quoted q := q.prec /-| _ := none -/ in -- `notation` allows more Syntax after `:` than mixfix commands, so we have to do a small conversion let precToAction := λ prec, {action.View . kind := actionKind.View.prec prec} in match k with | mixfix.kind.View.prefix _ := -- `prefix sym:prec` ~> `notation sym:prec b:prec` pure { rules := [{ symbol := sym, transition := transition.View.Arg {id := `b, action := precToAction <$> precedence.View.Term <$> prec}}]} | mixfix.kind.View.postfix _ := -- `postfix tk:prec` ~> `notation a tk:prec` pure { prefixArg := `a, rules := [{symbol := sym}]} | mixfix.kind.View.infixr _ := do -- `infixr tk:prec` ~> `notation a tk:prec b:(prec-1)` act ← match prec with | some prec := if prec.Term.toNat = 0 then error (review «precedence» prec) "invalid `infixr` declaration, given precedence must greater than zero" else pure $ some $ precToAction $ precedenceTerm.View.lit $ precedenceLit.View.num $ number.View.ofNat $ prec.Term.toNat - 1 | none := pure none, pure { prefixArg := `a, rules := [{ symbol := sym, transition := transition.View.Arg {id := `b, action := act}}]} | _ := -- `infix/infixl tk:prec` ~> `notation a tk:prec b:prec` pure { prefixArg := `a, rules := [{ symbol := sym, transition := transition.View.Arg {id := `b, action := precToAction <$> precedence.View.Term <$> prec}}]} def mixfix.transform : transformer := λ stx, do let v := view mixfix stx, let notaSym := match v.symbol with | mixfixSymbol.View.quoted q := notationSymbol.View.quoted q | mixfixSymbol.View.unquoted u := notationSymbol.View.quoted {symbol := u}, spec ← mixfixToNotationSpec v.kind notaSym, let Term := match v.kind with | mixfix.kind.View.prefix _ := -- `prefix tk:prec? := e` ~> `notation tk:prec? b:prec? := e b` review app {fn := v.Term, Arg := review identUnivs `b} | mixfix.kind.View.postfix _ := -- `postfix tk:prec? := e` ~> `notation tk:prec? b:prec? := e b` review app {fn := v.Term, Arg := review identUnivs `a} | _ := review app {fn := review app {fn := v.Term, Arg := review identUnivs `a}, Arg := review identUnivs `b}, pure $ review «notation» {«local» := v.local, spec := spec, Term := Term} def reserveMixfix.transform : transformer := λ stx, do let v := view reserveMixfix stx, spec ← mixfixToNotationSpec v.kind v.symbol, pure $ review reserveNotation {spec := spec} end «notation» def mkSimpleBinder (id : SyntaxIdent) (bi : BinderInfo) (type : Syntax) : simpleBinder.View := let bc : binderContent.View := {ids := [id], type := some {type := type}} in match bi with | BinderInfo.default := simpleBinder.View.explicit {id := id, type := type} | BinderInfo.implicit := simpleBinder.View.implicit {id := id, type := type} | BinderInfo.strictImplicit := simpleBinder.View.strictImplicit {id := id, type := type} | BinderInfo.instImplicit := simpleBinder.View.instImplicit {id := id, type := type} | BinderInfo.auxDecl := /- should not happen -/ simpleBinder.View.explicit {id := id, type := type} def binderIdentToIdent : binderIdent.View → SyntaxIdent | (binderIdent.View.id id) := id | (binderIdent.View.hole _) := "a" def getOptType : Option typeSpec.View → Syntax | none := review hole {} | (some v) := v.type def expandBracketedBinder : bracketedBinder.View → TransformM (List simpleBinder.View) -- local notation: should have been handled by caller, erase | (bracketedBinder.View.explicit {content := explicitBinderContent.View.notation _}) := pure [] | mbb := do (bi, bc) ← match mbb with | bracketedBinder.View.explicit {content := bc} := pure (match bc with | explicitBinderContent.View.other bc := (BinderInfo.default, bc) | _ := (BinderInfo.default, {ids := []}) /- unreachable, see above -/) | bracketedBinder.View.implicit {content := bc} := pure (BinderInfo.implicit, bc) | bracketedBinder.View.strictImplicit {content := bc} := pure (BinderInfo.strictImplicit, bc) | bracketedBinder.View.instImplicit {content := bc} := pure $ Prod.mk BinderInfo.instImplicit $ match bc with | instImplicitBinderContent.View.anonymous bca := {ids := ["_inst_"], type := some {type := bca.type}} | instImplicitBinderContent.View.named bcn := {ids := [bcn.id], type := some {type := bcn.type}} | bracketedBinder.View.anonymousConstructor ctor := error (review anonymousConstructor ctor) "unexpected anonymous Constructor", let type := getOptType bc.type, type ← match bc.default with | none := pure type | some (binderDefault.View.val bdv) := pure $ mkApp (globId `optParam) [type, bdv.Term] | some bdv@(binderDefault.View.tac bdt) := match bc.type with | none := pure $ mkApp (globId `autoParam) [bdt.Term] | some _ := error (review binderDefault bdv) "unexpected auto Param after Type annotation", pure $ bc.ids.map (λ bid, mkSimpleBinder (binderIdentToIdent bid) bi type) /-- Unfold `binders.View.extended` into `binders.View.simple`. -/ def expandBinders (mkBinding : binders.View → Syntax → Syntax) (bnders : binders.View) (body : Syntax) : TransformM (Option Syntax) := do binders.View.extended extBinders ← pure bnders | noExpansion, -- build Result `r` bottom-up let r := body, r ← match extBinders.remainder with | bindersRemainder.View.mixed brms := brms.mfoldr (λ brm r, match brm with -- anonymous Constructor binding ~> binding + match | mixedBinder.View.bracketed (bracketedBinder.View.anonymousConstructor ctor) := pure $ mkBinding (mkSimpleBinder "x" BinderInfo.default (review hole {})) $ review «match» { scrutinees := [review identUnivs ↑"x"], equations := [{item := {lhs := [review anonymousConstructor ctor], rhs := r}}] } -- local notation: should have been handled by caller, erase | mixedBinder.View.bracketed mbb := do bnders ← expandBracketedBinder mbb, pure $ bnders.foldr (λ bnder, mkBinding bnder) r | mixedBinder.View.id bid := pure $ mkBinding (mkSimpleBinder (binderIdentToIdent bid) BinderInfo.default (review hole {})) r ) r | _ := pure r, let leadingTy := match extBinders.remainder with | bindersRemainder.View.type brt := brt.type | _ := review hole {}, let r := extBinders.leadingIds.foldr (λ bid r, mkBinding (mkSimpleBinder (binderIdentToIdent bid) BinderInfo.default leadingTy) r) r, pure r def bracketedBinders.transform : transformer := λ stx, do let v := view bracketedBinders stx, match v with | bracketedBinders.View.simple _ := noExpansion | bracketedBinders.View.extended bnders := do bnders ← bnders.mmap expandBracketedBinder, pure $ review bracketedBinders $ bracketedBinders.View.simple $ List.join bnders def lambda.transform : transformer := λ stx, do let v := view lambda stx, expandBinders (λ binders body, review lambda {binders := binders, body := body}) v.binders v.body def pi.transform : transformer := λ stx, do let v := view pi stx, expandBinders (λ binders body, review pi {op := v.op, binders := binders, range := body}) v.binders v.range def depArrow.transform : transformer := λ stx, do let v := view depArrow stx, pure $ review pi { op := Syntax.atom {val := "Π"}, binders := binders.View.extended [v.binder], range := v.range} def arrow.transform : transformer := λ stx, do let v := view arrow stx, pure $ review pi { op := Syntax.atom {val := "Π"}, binders := binders.View.simple $ simpleBinder.View.explicit {id := `a, type := v.dom}, range := v.range} def paren.transform : transformer := λ stx, do let v := view paren stx, match v.content with | none := pure $ globId `Unit.unit | some {Term := t, special := none} := pure t | some {Term := t, special := parenSpecial.View.tuple tup} := pure $ (t::tup.tail.map SepBy.Elem.View.item).foldr1Opt (λ t tup, mkApp (globId `Prod.mk) [t, tup]) | some {Term := t, special := parenSpecial.View.typed pst} := pure $ mkApp (globId `typedExpr) [pst.type, t] def assume.transform : transformer := λ stx, do let v := view «assume» stx, let binders : binders.View := match v.binders with | assumeBinders.View.anonymous aba := binders.View.simple $ -- TODO(Sebastian): unhygienic! simpleBinder.View.explicit {id := "this", type := aba.type} | assumeBinders.View.binders abb := abb, pure $ review lambda {binders := binders, body := v.body} def if.transform : transformer := λ stx, do let v := view «if» stx, pure $ match v.id with | some id := mkApp (globId `dite) [v.prop, review lambda {binders := binders.View.simple $ simpleBinder.View.explicit {id := id.id, type := v.prop}, body := v.thenBranch}, review lambda {binders := binders.View.simple $ simpleBinder.View.explicit {id := id.id, type := mkApp (globId `Not) [v.prop]}, body := v.elseBranch}] | none := mkApp (globId `ite) [v.prop, v.thenBranch, v.elseBranch] def let.transform : transformer := λ stx, do let v := view «let» stx, match v.lhs with | letLhs.View.id {id := _, binders := [], type := some _} := noExpansion | letLhs.View.id lli@{id := _, binders := [], type := none} := pure $ review «let» {v with lhs := letLhs.View.id {lli with type := some {type := review hole {}}}} | letLhs.View.id lli@{id := _, binders := _, type := ty} := let bindrs := binders.View.extended lli.binders in pure $ review «let» {v with lhs := letLhs.View.id { id := lli.id, binders := [], type := some {type := review pi {op := Syntax.atom {val := "Π"}, binders := bindrs, range := getOptType ty}}}, value := review lambda {binders := bindrs, body := v.value}} | letLhs.View.pattern llp := pure $ review «match» { scrutinees := [v.value], equations := [{item := {lhs := [llp], rhs := v.body}}]} -- move parameters into Type def axiom.transform : transformer := λ stx, do let v := view «axiom» stx, match v with | {sig := {params := bracketedBinders.View.extended bindrs, type := type}, ..} := do let bindrs := binders.View.extended bindrs, pure $ review «axiom» {v with sig := { params := bracketedBinders.View.simple [], type := {type := review pi {op := Syntax.atom {val := "Π"}, binders := bindrs, range := type.type}}}} | _ := noExpansion def declaration.transform : transformer := λ stx, do let v := view «declaration» stx, match v.inner with | declaration.inner.View.inductive ind@{«class» := some _, ..} := let attrs := v.modifiers.attrs.getOrElse {attrs := []} in pure $ review «declaration» {v with modifiers := {v.modifiers with attrs := some {attrs with attrs := {item := {Name := "class", args := []}} :: attrs.attrs}}, inner := declaration.inner.View.inductive {ind with «class» := none} } | declaration.inner.View.structure s@{keyword := structureKw.View.class _, ..} := let attrs := v.modifiers.attrs.getOrElse {attrs := []} in pure $ review «declaration» {v with modifiers := {v.modifiers with attrs := some {attrs with attrs := {item := {Name := "class", args := []}} :: attrs.attrs}}, inner := declaration.inner.View.structure {s with keyword := structureKw.View.structure} } | _ := noExpansion def introRule.transform : transformer := λ stx, do let v := view «introRule» stx, match v.sig with | {params := bracketedBinders.View.extended bindrs, type := some type} := do let bindrs := binders.View.extended bindrs, pure $ review «introRule» {v with sig := { params := bracketedBinders.View.simple [], type := some {type := review pi {op := Syntax.atom {val := "Π"}, binders := bindrs, range := type.type}}}} | _ := noExpansion /- We expand `variable` into `variables` instead of the other way around since, in theory, elaborating multiple variables at the same time makes it possible to omit more information. -/ def variable.transform : transformer := λ stx, do let v := view «variable» stx, pure $ review «variables» {binders := bracketedBinders.View.extended [v.binder]} @[derive HasView] def bindingAnnotationUpdate.Parser : termParser := node! bindingAnnotationUpdate ["dummy"] -- FIXME: bad node! expansion def variables.transform : transformer := λ stx, do let v := view «variables» stx, match v.binders with | bracketedBinders.View.simple _ := noExpansion | bracketedBinders.View.extended bnders := do bnders ← bnders.mmap $ λ b, match b with -- binding annotation update | bracketedBinder.View.explicit eb@{content := explicitBinderContent.View.other bc@{ids := ids, type := none, default := none}} := expandBracketedBinder $ bracketedBinder.View.explicit {eb with content := explicitBinderContent.View.other {bc with type := some {type := review bindingAnnotationUpdate {}}}} | _ := expandBracketedBinder b, pure $ review «variables» {binders := bracketedBinders.View.simple $ List.join bnders} def Level.leading.transform : transformer := λ stx, do let v := view Level.leading stx, match v with | Level.leading.View.paren p := pure p.inner | _ := noExpansion def Subtype.transform : transformer := λ stx, do let v := view Term.Subtype stx, pure $ mkApp (globId `Subtype) [review lambda { binders := mkSimpleBinder v.id BinderInfo.default $ getOptType v.type, body := v.prop }] def universes.transform : transformer := λ stx, do let v := view «universes» stx, pure $ Syntax.list $ v.ids.map (λ id, review «universe» {id := id}) def sorry.transform : transformer := λ stx, pure $ mkApp (globId `sorryAx) [review hole {}, globId `Bool.false] -- TODO(Sebastian): replace with attribute def builtinTransformers : RBMap Name transformer Name.quickLt := RBMap.fromList [ (mixfix.name, mixfix.transform), (reserveMixfix.name, reserveMixfix.transform), (bracketedBinders.name, bracketedBinders.transform), (lambda.name, lambda.transform), (pi.name, pi.transform), (depArrow.name, depArrow.transform), (arrow.name, arrow.transform), (paren.name, paren.transform), (assume.name, assume.transform), (if.name, if.transform), (let.name, let.transform), (axiom.name, axiom.transform), (declaration.name, declaration.transform), (introRule.name, introRule.transform), (variable.name, variable.transform), (variables.name, variables.transform), (Level.leading.name, Level.leading.transform), (Term.Subtype.name, Subtype.transform), (universes.name, universes.transform), (sorry.name, sorry.transform) ] _ structure ExpanderState := (nextScope : MacroScope) structure ExpanderConfig extends TransformerConfig := (transformers : RBMap Name transformer Name.quickLt) instance ExpanderConfig.HasLift : HasLift ExpanderConfig TransformerConfig := ⟨ExpanderConfig.toTransformerConfig⟩ @[reducible] def ExpanderM := StateT ExpanderState $ ReaderT ExpanderConfig $ ExceptT Message Id section local attribute [reducible] MacroScope def ExpanderState.new : ExpanderState := ⟨0⟩ def mkScope : ExpanderM MacroScope := do st ← get, set {st with nextScope := st.nextScope + 1}, pure st.nextScope end private def expandCore : Nat → Syntax → ExpanderM Syntax | 0 stx := error stx "macro expansion limit exceeded" | (fuel + 1) stx := do some n ← pure stx.asNode | pure stx, cfg ← read, some t ← pure $ cfg.transformers.find n.kind.name -- not a macro: recurse | Syntax.mkNode n.kind <$> n.args.mmap (expandCore fuel), sc ← mkScope, let n' := Syntax.mkNode n.kind $ n.args.map (Syntax.flipScopes [sc]), some stx' ← StateT.lift $ λ cfg, t n' ↑cfg -- no unfolding: recurse | Syntax.mkNode n.kind <$> n.args.mmap (expandCore fuel), -- flip again, expand iteratively expandCore fuel $ stx'.flipScopes [sc] def expand (stx : Syntax) : ReaderT ExpanderConfig (Except Message) Syntax := -- TODO(Sebastian): persist macro scopes across commands/files Prod.fst <$> expandCore 1000 stx ExpanderState.new end Expander end Lean
3c463658536a607232dff33109b4ca9b23b65faf
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/compiler_proj_bug.lean
3c63fac5336ffe04dd60142737f49aa89dfe7a26
[ "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
117
lean
structure S := (a : Nat) (h : a > 0) (b : Nat) def f (s : S) := s.b - s.a #eval f {a := 5, b := 30, h := sorry }
404504ef01f1cf6ba792bbf6b0a3894e0b603333
50b3917f95cf9fe84639812ea0461b38f8f0dbe1
/canonical_isomorphism/kenny_function_1.lean
8fa6f01b5a7cf285eb991b4edd6468e39bb8b3f5
[]
no_license
roro47/xena
6389bcd7dcf395656a2c85cfc90a4366e9b825bb
237910190de38d6ff43694ffe3a9b68f79363e6c
refs/heads/master
1,598,570,061,948
1,570,052,567,000
1,570,052,567,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,405
lean
import algebra.group data.set data.equiv def is_add_group_hom {α : Type*} {β : Type*} [add_group α] [add_group β] (f : α → β) : Prop := @is_group_hom (multiplicative α) (multiplicative β) _ _ f attribute [class] is_add_group_hom namespace is_add_group_hom variables {α : Type*} {β : Type*} [add_group α] [add_group β] (f : α → β) [hf : is_add_group_hom f] theorem mk (H : ∀ x y, f (x + y) = f x + f y) : is_add_group_hom f := ⟨H⟩ theorem add (x y) : f (x + y) = f x + f y := @is_group_hom.mul (multiplicative α) (multiplicative β) _ _ f hf x y theorem zero : f 0 = 0 := @is_group_hom.one (multiplicative α) (multiplicative β) _ _ f hf theorem neg (x) : f (-x) = -f x := @is_group_hom.inv (multiplicative α) (multiplicative β) _ _ f hf x def ker : set α := { x | f x = 0 } end is_add_group_hom theorem three (A B C A' B' C' : Type*) [add_comm_group A] [add_comm_group A'] [add_comm_group B] [add_comm_group B'] [add_comm_group C] [add_comm_group C'] (ab : A → B) [is_add_group_hom ab] (bc : B → C) [is_add_group_hom bc] (Habc : set.range ab = is_add_group_hom.ker bc) (fa : A ≃ A') [is_add_group_hom fa] (fb : B ≃ B') [is_add_group_hom fb] (fc : C ≃ C') [is_add_group_hom fc] (ab' : A' → B') [is_add_group_hom ab'] (bc' : B' → C') [is_add_group_hom bc'] (H1 : fb ∘ ab = ab' ∘ fa) (H2 : fc ∘ bc = bc' ∘ fb) : set.range ab' = is_add_group_hom.ker bc' := begin apply set.ext, intro b', split, { intro hb', cases hb' with a' ha', simp [is_add_group_hom.ker], let a := fa.symm a', have ha : fa a = a', { simp [a] }, rw [← ha', ← ha], change bc' ((ab' ∘ fa) a) = 0, rw ← H1, change (bc' ∘ fb) (ab a) = 0, rw ← H2, have H3 : ab a ∈ is_add_group_hom.ker bc, { rw ← Habc, existsi a, simp }, simp [is_add_group_hom.ker] at H3 ⊢, rw H3, apply is_add_group_hom.zero }, { intro hb', let b := fb.symm b', have hb : fb b = b', { simp [b] }, simp [is_add_group_hom.ker] at hb', rw ← hb at hb', change (bc' ∘ fb) b = 0 at hb', rw ← H2 at hb', rw ← is_add_group_hom.zero fc at hb', replace hb' := congr_arg fc.symm hb', simp at hb', have H3 : b ∈ set.range ab, { rwa Habc }, cases H3 with a ha, existsi fa a, change (ab' ∘ fa) a = b', rw ← H1, simp [ha] } end
5b44513809ab78c729d00c358920b34986a13eb5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/wiedijk_100_theorems/friendship_graphs.lean
222ca67a633ba3ff2aef2f368dff265b0284857f
[ "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
13,954
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller -/ import combinatorics.simple_graph.adj_matrix import linear_algebra.matrix.charpoly.finite_field import data.int.modeq import data.zmod.basic import tactic.interval_cases /-! # The Friendship Theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Definitions and Statement - A `friendship` graph is one in which any two distinct vertices have exactly one neighbor in common - A `politician`, at least in the context of this problem, is a vertex in a graph which is adjacent to every other vertex. - The friendship theorem (Erdős, Rényi, Sós 1966) states that every finite friendship graph has a politician. ## Proof outline The proof revolves around the theory of adjacency matrices, although some steps could equivalently be phrased in terms of counting walks. - Assume `G` is a finite friendship graph. - First we show that any two nonadjacent vertices have the same degree - Assume for contradiction that `G` does not have a politician. - Conclude from the last two points that `G` is `d`-regular for some `d : ℕ`. - Show that `G` has `d ^ 2 - d + 1` vertices. - By casework, show that if `d = 0, 1, 2`, then `G` has a politician. - If `3 ≤ d`, let `p` be a prime factor of `d - 1`. - If `A` is the adjacency matrix of `G` with entries in `ℤ/pℤ`, we show that `A ^ p` has trace `1`. - This gives a contradiction, as `A` has trace `0`, and thus `A ^ p` has trace `0`. ## References - [P. Erdős, A. Rényi, V. Sós, *On A Problem of Graph Theory*][erdosrenyisos] - [C. Huneke, *The Friendship Theorem*][huneke2002] -/ open_locale classical big_operators namespace theorems_100 noncomputable theory open finset simple_graph matrix universes u v variables {V : Type u} {R : Type v} [semiring R] section friendship_def variables (G : simple_graph V) /-- This property of a graph is the hypothesis of the friendship theorem: every pair of nonadjacent vertices has exactly one common friend, a vertex to which both are adjacent. -/ def friendship [fintype V] : Prop := ∀ ⦃v w : V⦄, v ≠ w → fintype.card (G.common_neighbors v w) = 1 /-- A politician is a vertex that is adjacent to all other vertices. -/ def exists_politician : Prop := ∃ (v : V), ∀ (w : V), v ≠ w → G.adj v w end friendship_def variables [fintype V] {G : simple_graph V} {d : ℕ} (hG : friendship G) include hG namespace friendship variables (R) /-- One characterization of a friendship graph is that there is exactly one walk of length 2 between distinct vertices. These walks are counted in off-diagonal entries of the square of the adjacency matrix, so for a friendship graph, those entries are all 1. -/ theorem adj_matrix_sq_of_ne {v w : V} (hvw : v ≠ w) : ((G.adj_matrix R) ^ 2) v w = 1 := begin rw [sq, ← nat.cast_one, ← hG hvw], simp [common_neighbors, neighbor_finset_eq_filter, finset.filter_filter, and_comm, ← neighbor_finset_def], end /-- This calculation amounts to counting the number of length 3 walks between nonadjacent vertices. We use it to show that nonadjacent vertices have equal degrees. -/ lemma adj_matrix_pow_three_of_not_adj {v w : V} (non_adj : ¬ G.adj v w) : ((G.adj_matrix R) ^ 3) v w = degree G v := begin rw [pow_succ, mul_eq_mul, adj_matrix_mul_apply, degree, card_eq_sum_ones, nat.cast_sum], apply sum_congr rfl, intros x hx, rw [adj_matrix_sq_of_ne _ hG, nat.cast_one], rintro ⟨rfl⟩, rw mem_neighbor_finset at hx, exact non_adj hx, end variable {R} /-- As `v` and `w` not being adjacent implies `degree G v = ((G.adj_matrix R) ^ 3) v w` and `degree G w = ((G.adj_matrix R) ^ 3) v w`, the degrees are equal if `((G.adj_matrix R) ^ 3) v w = ((G.adj_matrix R) ^ 3) w v` This is true as the adjacency matrix is symmetric. -/ lemma degree_eq_of_not_adj {v w : V} (hvw : ¬ G.adj v w) : degree G v = degree G w := begin rw [← nat.cast_id (G.degree v), ← nat.cast_id (G.degree w), ← adj_matrix_pow_three_of_not_adj ℕ hG hvw, ← adj_matrix_pow_three_of_not_adj ℕ hG (λ h, hvw (G.symm h))], conv_lhs {rw ← transpose_adj_matrix}, simp only [pow_succ, sq, mul_eq_mul, ← transpose_mul, transpose_apply], simp only [← mul_eq_mul, mul_assoc], end /-- Let `A` be the adjacency matrix of a graph `G`. If `G` is a friendship graph, then all of the off-diagonal entries of `A^2` are 1. If `G` is `d`-regular, then all of the diagonal entries of `A^2` are `d`. Putting these together determines `A^2` exactly for a `d`-regular friendship graph. -/ theorem adj_matrix_sq_of_regular (hd : G.is_regular_of_degree d) : ((G.adj_matrix R) ^ 2) = λ v w, if v = w then d else 1 := begin ext v w, by_cases h : v = w, { rw [h, sq, mul_eq_mul, adj_matrix_mul_self_apply_self, hd], simp, }, { rw [adj_matrix_sq_of_ne R hG h, if_neg h], }, end lemma adj_matrix_sq_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) ^ 2 = λ _ _, 1 := by simp [adj_matrix_sq_of_regular hG hd, dmod] section nonempty variable [nonempty V] /-- If `G` is a friendship graph without a politician (a vertex adjacent to all others), then it is regular. We have shown that nonadjacent vertices of a friendship graph have the same degree, and if there isn't a politician, we can show this for adjacent vertices by finding a vertex neither is adjacent to, and then using transitivity. -/ theorem is_regular_of_not_exists_politician (hG' : ¬exists_politician G) : ∃ (d : ℕ), G.is_regular_of_degree d := begin have v := classical.arbitrary V, use G.degree v, intro x, by_cases hvx : G.adj v x, swap, { exact (degree_eq_of_not_adj hG hvx).symm, }, dunfold theorems_100.exists_politician at hG', push_neg at hG', rcases hG' v with ⟨w, hvw', hvw⟩, rcases hG' x with ⟨y, hxy', hxy⟩, by_cases hxw : G.adj x w, swap, { rw degree_eq_of_not_adj hG hvw, exact degree_eq_of_not_adj hG hxw }, rw degree_eq_of_not_adj hG hxy, by_cases hvy : G.adj v y, swap, { exact (degree_eq_of_not_adj hG hvy).symm }, rw degree_eq_of_not_adj hG hvw, apply degree_eq_of_not_adj hG, intro hcontra, rcases finset.card_eq_one.mp (hG hvw') with ⟨⟨a, ha⟩, h⟩, have key : ∀ {x}, x ∈ G.common_neighbors v w → x = a, { intros x hx, have h' := mem_univ (subtype.mk x hx), rw [h, mem_singleton] at h', injection h', }, apply hxy', rw [key ((mem_common_neighbors G).mpr ⟨hvx, G.symm hxw⟩), key ((mem_common_neighbors G).mpr ⟨hvy, G.symm hcontra⟩)], end /-- Let `A` be the adjacency matrix of a `d`-regular friendship graph, and let `v` be a vector all of whose components are `1`. Then `v` is an eigenvector of `A ^ 2`, and we can compute the eigenvalue to be `d * d`, or as `d + (fintype.card V - 1)`, so those quantities must be equal. This essentially means that the graph has `d ^ 2 - d + 1` vertices. -/ lemma card_of_regular (hd : G.is_regular_of_degree d) : d + (fintype.card V - 1) = d * d := begin have v := classical.arbitrary V, transitivity ((G.adj_matrix ℕ) ^ 2).mul_vec (λ _, 1) v, { rw [adj_matrix_sq_of_regular hG hd, mul_vec, dot_product, ← insert_erase (mem_univ v)], simp only [sum_insert, mul_one, if_true, nat.cast_id, eq_self_iff_true, mem_erase, not_true, ne.def, not_false_iff, add_right_inj, false_and], rw [finset.sum_const_nat, card_erase_of_mem (mem_univ v), mul_one], { refl }, intros x hx, simp [(ne_of_mem_erase hx).symm], }, { rw [sq, mul_eq_mul, ← mul_vec_mul_vec], simp [adj_matrix_mul_vec_const_apply_of_regular hd, neighbor_finset, card_neighbor_set_eq_degree, hd v], } end /-- The size of a `d`-regular friendship graph is `1 mod (d-1)`, and thus `1 mod p` for a factor `p ∣ d-1`. -/ lemma card_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (fintype.card V : zmod p) = 1 := begin have hpos : 0 < fintype.card V := fintype.card_pos_iff.mpr infer_instance, rw [← nat.succ_pred_eq_of_pos hpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], have h := congr_arg (λ n, (↑n : zmod p)) (card_of_regular hG hd), revert h, simp [dmod], end end nonempty omit hG lemma adj_matrix_sq_mul_const_one_of_regular (hd : G.is_regular_of_degree d) : (G.adj_matrix R) * (λ _ _, 1) = λ _ _, d := by { ext x, simp [← hd x, degree] } lemma adj_matrix_mul_const_one_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) * (λ _ _, 1) = λ _ _, 1 := by rw [adj_matrix_sq_mul_const_one_of_regular hd, dmod] include hG /-- Modulo a factor of `d-1`, the square and all higher powers of the adjacency matrix of a `d`-regular friendship graph reduce to the matrix whose entries are all 1. -/ lemma adj_matrix_pow_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) {k : ℕ} (hk : 2 ≤ k) : (G.adj_matrix (zmod p)) ^ k = λ _ _, 1 := begin iterate 2 {cases k with k, { exfalso, linarith, }, }, induction k with k hind, { exact adj_matrix_sq_mod_p_of_regular hG dmod hd, }, rw [pow_succ, hind (nat.le_add_left 2 k)], exact adj_matrix_mul_const_one_mod_p_of_regular dmod hd, end variable [nonempty V] /-- This is the main proof. Assuming that `3 ≤ d`, we take `p` to be a prime factor of `d-1`. Then the `p`th power of the adjacency matrix of a `d`-regular friendship graph must have trace 1 mod `p`, but we can also show that the trace must be the `p`th power of the trace of the original adjacency matrix, which is 0, a contradiction. -/ lemma false_of_three_le_degree (hd : G.is_regular_of_degree d) (h : 3 ≤ d) : false := begin -- get a prime factor of d - 1 let p : ℕ := (d - 1).min_fac, have p_dvd_d_pred := (zmod.nat_coe_zmod_eq_zero_iff_dvd _ _).mpr (d - 1).min_fac_dvd, have dpos : 0 < d := by linarith, have d_cast : ↑(d - 1) = (d : ℤ) - 1 := by norm_cast, haveI : fact p.prime := ⟨nat.min_fac_prime (by linarith)⟩, have hp2 : 2 ≤ p := (fact.out p.prime).two_le, have dmod : (d : zmod p) = 1, { rw [← nat.succ_pred_eq_of_pos dpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], exact p_dvd_d_pred, }, have Vmod := card_mod_p_of_regular hG dmod hd, -- now we reduce to a trace calculation have := zmod.trace_pow_card (G.adj_matrix (zmod p)), contrapose! this, clear this, -- the trace is 0 mod p when computed one way rw [trace_adj_matrix, zero_pow (fact.out p.prime).pos], -- but the trace is 1 mod p when computed the other way rw adj_matrix_pow_mod_p_of_regular hG dmod hd hp2, dunfold fintype.card at Vmod, simp only [matrix.trace, matrix.diag, mul_one, nsmul_eq_mul, linear_map.coe_mk, sum_const], rw [Vmod, ← nat.cast_one, zmod.nat_coe_zmod_eq_zero_iff_dvd, nat.dvd_one, nat.min_fac_eq_one_iff], linarith, end /-- If `d ≤ 1`, a `d`-regular friendship graph has at most one vertex, which is trivially a politician. -/ lemma exists_politician_of_degree_le_one (hd : G.is_regular_of_degree d) (hd1 : d ≤ 1) : exists_politician G := begin have sq : d * d = d := by { interval_cases d; norm_num }, have h := card_of_regular hG hd, rw sq at h, have : fintype.card V ≤ 1, { cases fintype.card V with n, { exact zero_le _, }, { have : n = 0, { rw [nat.succ_sub_succ_eq_sub, tsub_zero] at h, linarith }, subst n, } }, use classical.arbitrary V, intros w h, exfalso, apply h, apply fintype.card_le_one_iff.mp this, end /-- If `d = 2`, a `d`-regular friendship graph has 3 vertices, so it must be complete graph, and all the vertices are politicians. -/ lemma neighbor_finset_eq_of_degree_eq_two (hd : G.is_regular_of_degree 2) (v : V) : G.neighbor_finset v = finset.univ.erase v := begin apply finset.eq_of_subset_of_card_le, { rw finset.subset_iff, intro x, rw [mem_neighbor_finset, finset.mem_erase], exact λ h, ⟨(G.ne_of_adj h).symm, finset.mem_univ _⟩ }, convert_to 2 ≤ _, { convert_to _ = fintype.card V - 1, { have hfr:= card_of_regular hG hd, linarith }, { exact finset.card_erase_of_mem (finset.mem_univ _), }, }, { dsimp [is_regular_of_degree, degree] at hd, rw hd, } end lemma exists_politician_of_degree_eq_two (hd : G.is_regular_of_degree 2) : exists_politician G := begin have v := classical.arbitrary V, use v, intros w hvw, rw [← mem_neighbor_finset, neighbor_finset_eq_of_degree_eq_two hG hd v, finset.mem_erase], exact ⟨hvw.symm, finset.mem_univ _⟩, end lemma exists_politician_of_degree_le_two (hd : G.is_regular_of_degree d) (h : d ≤ 2) : exists_politician G := begin interval_cases d, iterate 2 { apply exists_politician_of_degree_le_one hG hd, norm_num }, { exact exists_politician_of_degree_eq_two hG hd }, end end friendship /-- **Friendship theorem**: We wish to show that a friendship graph has a politician (a vertex adjacent to all others). We proceed by contradiction, and assume the graph has no politician. We have already proven that a friendship graph with no politician is `d`-regular for some `d`, and now we do casework on `d`. If the degree is at most 2, we observe by casework that it has a politician anyway. If the degree is at least 3, the graph cannot exist. -/ theorem friendship_theorem [nonempty V] : exists_politician G := begin by_contradiction npG, rcases hG.is_regular_of_not_exists_politician npG with ⟨d, dreg⟩, cases lt_or_le d 3 with dle2 dge3, { exact npG (hG.exists_politician_of_degree_le_two dreg (nat.lt_succ_iff.mp dle2)) }, { exact hG.false_of_three_le_degree dreg dge3 }, end end theorems_100
de3ce70e5b0f0686d8213519ba2f375a26fbd277
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/adjoin_auto.lean
6429cb3c1024915ef864434c3224306e1bc648aa
[]
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
8,033
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.polynomial.basic import Mathlib.algebra.algebra.subalgebra import Mathlib.PostPort universes u v w namespace Mathlib /-! # Adjoining elements to form subalgebras This file develops the basic theory of subalgebras of an R-algebra generated by a set of elements. A basic interface for `adjoin` is set up, and various results about finitely-generated subalgebras and submodules are proved. ## Definitions * `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated as an A-algebra ## Tags adjoin, algebra, finitely-generated algebra -/ namespace algebra theorem subset_adjoin {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {s : set A} : s ⊆ ↑(adjoin R s) := set.subset.trans (set.subset_union_right (set.range ⇑(algebra_map R A)) s) subsemiring.subset_closure theorem adjoin_le {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {s : set A} {S : subalgebra R A} (H : s ⊆ ↑S) : adjoin R s ≤ S := iff.mpr subsemiring.closure_le (set.union_subset (subalgebra.range_le S) H) theorem adjoin_le_iff {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {s : set A} {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ ↑S := { mp := set.subset.trans subset_adjoin, mpr := adjoin_le } theorem adjoin_mono {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {s : set A} {t : set A} (H : s ⊆ t) : adjoin R s ≤ adjoin R t := iff.mpr subsemiring.closure_le (set.subset.trans (set.union_subset_union_right (set.range ⇑(algebra_map R A)) H) subsemiring.subset_closure) @[simp] theorem adjoin_empty (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : adjoin R ∅ = ⊥ := iff.mpr eq_bot_iff (adjoin_le (set.empty_subset ↑⊥)) theorem adjoin_eq_span (R : Type u) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (s : set A) : ↑(adjoin R s) = submodule.span R (monoid.closure s) := sorry theorem adjoin_image (R : Type u) {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (f : alg_hom R A B) (s : set A) : adjoin R (⇑f '' s) = subalgebra.map (adjoin R s) f := le_antisymm (adjoin_le (set.image_subset (⇑f) subset_adjoin)) (iff.mpr subalgebra.map_le (adjoin_le (iff.mp set.image_subset_iff subset_adjoin))) @[simp] theorem adjoin_insert_adjoin (R : Type u) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (s : set A) (x : A) : adjoin R (insert x ↑↑(adjoin R s)) = adjoin R (insert x s) := sorry theorem adjoin_union (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (s : set A) (t : set A) : adjoin R (s ∪ t) = subalgebra.under (adjoin R s) (adjoin (↥(adjoin R s)) t) := sorry theorem adjoin_eq_range (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (s : set A) : adjoin R s = alg_hom.range (mv_polynomial.aeval coe) := sorry theorem adjoin_singleton_eq_range (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (x : A) : adjoin R (singleton x) = alg_hom.range (polynomial.aeval x) := sorry theorem adjoin_singleton_one (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] : adjoin R (singleton 1) = ⊥ := iff.mpr eq_bot_iff (adjoin_le (iff.mpr set.singleton_subset_iff (subalgebra.one_mem ⊥))) theorem adjoin_union_coe_submodule (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (s : set A) (t : set A) : ↑(adjoin R (s ∪ t)) = ↑(adjoin R s) * ↑(adjoin R t) := sorry theorem adjoin_int {R : Type u} [comm_ring R] (s : set R) : adjoin ℤ s = subalgebra_of_is_subring (ring.closure s) := le_antisymm (adjoin_le ring.subset_closure) (ring.closure_subset subset_adjoin) theorem mem_adjoin_iff {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] {s : set A} {x : A} : x ∈ adjoin R s ↔ x ∈ ring.closure (set.range ⇑(algebra_map R A) ∪ s) := sorry theorem adjoin_eq_ring_closure {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (s : set A) : ↑(adjoin R s) = ring.closure (set.range ⇑(algebra_map R A) ∪ s) := set.ext fun (x : A) => mem_adjoin_iff theorem fg_trans {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] [algebra R A] {s : set A} {t : set A} (h1 : submodule.fg ↑(adjoin R s)) (h2 : submodule.fg ↑(adjoin (↥(adjoin R s)) t)) : submodule.fg ↑(adjoin R (s ∪ t)) := sorry end algebra namespace subalgebra /-- A subalgebra `S` is finitely generated if there exists `t : finset A` such that `algebra.adjoin R t = S`. -/ def fg {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) := ∃ (t : finset A), algebra.adjoin R ↑t = S theorem fg_adjoin_finset {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (s : finset A) : fg (algebra.adjoin R ↑s) := Exists.intro s rfl theorem fg_def {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {S : subalgebra R A} : fg S ↔ ∃ (t : set A), set.finite t ∧ algebra.adjoin R t = S := sorry theorem fg_bot {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] : fg ⊥ := Exists.intro ∅ (algebra.adjoin_empty R A) theorem fg_of_fg_to_submodule {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {S : subalgebra R A} : submodule.fg ↑S → fg S := sorry theorem fg_of_noetherian {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] [is_noetherian R A] (S : subalgebra R A) : fg S := fg_of_fg_to_submodule (is_noetherian.noetherian ↑S) theorem fg_of_submodule_fg {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (h : submodule.fg ⊤) : fg ⊤ := sorry theorem fg_map {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] (S : subalgebra R A) (f : alg_hom R A B) (hs : fg S) : fg (map S f) := sorry theorem fg_of_fg_map {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] (S : subalgebra R A) (f : alg_hom R A B) (hf : function.injective ⇑f) (hs : fg (map S f)) : fg S := sorry theorem fg_top {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : fg ⊤ ↔ fg S := sorry theorem induction_on_adjoin {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] [is_noetherian R A] (P : subalgebra R A → Prop) (base : P ⊥) (ih : ∀ (S : subalgebra R A) (x : A), P S → P (algebra.adjoin R (insert x ↑S))) (S : subalgebra R A) : P S := sorry end subalgebra /-- The image of a Noetherian R-algebra under an R-algebra map is a Noetherian ring. -/ protected instance alg_hom.is_noetherian_ring_range {R : Type u} {A : Type v} {B : Type w} [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] (f : alg_hom R A B) [is_noetherian_ring A] : is_noetherian_ring ↥(alg_hom.range f) := Mathlib.is_noetherian_ring_range (alg_hom.to_ring_hom f) theorem is_noetherian_ring_of_fg {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] [algebra R A] {S : subalgebra R A} (HS : subalgebra.fg S) [is_noetherian_ring R] : is_noetherian_ring ↥S := sorry theorem is_noetherian_ring_closure {R : Type u} [comm_ring R] (s : set R) (hs : set.finite s) : is_noetherian_ring ↥(ring.closure s) := (fun (this : is_noetherian_ring ↥(subalgebra_of_is_subring (ring.closure s))) => this) (algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (iff.mpr subalgebra.fg_def (Exists.intro s { left := hs, right := rfl }))) end Mathlib
2cb0bdea5b91923f3341a5b5c02f9d245217f5c7
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/10_Structures_and_Records.org.2.lean
61223c3b86e40a51a843900e2a0ed1727930e95b
[]
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
381
lean
import standard structure point (A : Type) := mk :: (x : A) (y : A) -- BEGIN check point -- a Type check point.rec_on -- the recursor check point.induction_on -- then recursor to Prop check point.destruct -- an alias for point.rec_on check point.x -- a projection / field accessor check point.y -- a projection / field accessor -- END
2d95b3819942c1e23c34e7c0bbe1da814e6f030e
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/nat/enat.lean
c62a1b2a56b600c184d82008cac4d0d8f43c5863
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
12,645
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Natural numbers with infinity, represented as roption ℕ. -/ import data.pfun algebra.ordered_group import tactic.norm_cast tactic.norm_num open roption def enat : Type := roption ℕ namespace enat instance : has_zero enat := ⟨some 0⟩ instance : inhabited enat := ⟨0⟩ instance : has_one enat := ⟨some 1⟩ instance : has_add enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance : has_coe ℕ enat := ⟨some⟩ instance (n : ℕ) : decidable (n : enat).dom := is_true trivial @[simp] lemma coe_inj {x y : ℕ} : (x : enat) = y ↔ x = y := roption.some_inj instance : add_comm_monoid enat := { add := (+), zero := (0), add_comm := λ x y, roption.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, roption.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, roption.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, roption.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : has_le enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top enat := ⟨none⟩ instance : has_bot enat := ⟨0⟩ instance : has_sup enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ @[elab_as_eliminator] protected lemma cases_on {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P n) → P a := roption.induction_on @[simp] lemma top_add (x : enat) : ⊤ + x = ⊤ := roption.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp, norm_cast] lemma coe_zero : ((0 : ℕ) : enat) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℕ) : enat) = 1 := rfl @[simp, norm_cast] lemma coe_add (x y : ℕ) : ((x + y : ℕ) : enat) = x + y := roption.ext' (and_true _).symm (λ _ _, rfl) @[simp, norm_cast] lemma get_coe {x : ℕ} : get (x : enat) true.intro = x := rfl lemma coe_add_get {x : ℕ} {y : enat} (h : ((x : enat) + y).dom) : get ((x : enat) + y) h = x + get y h.2 := rfl @[simp] lemma get_add {x y : enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] lemma coe_get {x : enat} (h : x.dom) : (x.get h : enat) = x := roption.ext' (iff_of_true trivial h) (λ _ _, rfl) @[simp] lemma get_zero (h : (0 : enat).dom) : (0 : enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : enat).dom) : (1 : enat).get h = 1 := rfl lemma dom_of_le_some {x : enat} {y : ℕ} : x ≤ y → x.dom := λ ⟨h, _⟩, h trivial instance : partial_order enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_refl _⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, roption.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } @[simp, norm_cast] lemma coe_le_coe {x y : ℕ} : (x : enat) ≤ y ↔ x ≤ y := ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ @[simp, norm_cast] lemma coe_lt_coe {x y : ℕ} : (x : enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] lemma get_le_get {x y : enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} instance semilattice_sup_bot : semilattice_sup_bot enat := { sup := (⊔), bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩, le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..enat.partial_order } instance order_top : order_top enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩, ..enat.semilattice_sup_bot } lemma top_eq_none : (⊤ : enat) = none := rfl lemma coe_lt_top (x : ℕ) : (x : enat) < ⊤ := lt_of_le_of_ne le_top (λ h, absurd (congr_arg dom h) true_ne_false) @[simp] lemma coe_ne_top (x : ℕ) : (x : enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma ne_top_iff {x : enat} : x ≠ ⊤ ↔ ∃(n : ℕ), x = n := roption.ne_none_iff lemma ne_top_iff_dom {x : enat} : x ≠ ⊤ ↔ x.dom := by classical; exact not_iff_comm.1 roption.eq_none_iff'.symm lemma ne_top_of_lt {x y : enat} (h : x < y) : x ≠ ⊤ := ne_of_lt $ lt_of_lt_of_le h le_top lemma pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x := enat.cases_on x ⟨λ _, le_top, λ _, coe_lt_top _⟩ (λ n, ⟨λ h, enat.coe_le_coe.2 (enat.coe_lt_coe.1 h), λ h, enat.coe_lt_coe.2 (enat.coe_le_coe.1 h)⟩) noncomputable instance : decidable_linear_order enat := { le_total := λ x y, enat.cases_on x (or.inr le_top) (enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))), decidable_le := classical.dec_rel _, ..enat.partial_order } noncomputable instance : bounded_lattice enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..enat.order_top, ..enat.semilattice_sup_bot } lemma sup_eq_max {a b : enat} : a ⊔ b = max a b := le_antisymm (sup_le (le_max_left _ _) (le_max_right _ _)) (max_le le_sup_left le_sup_right) lemma inf_eq_min {a b : enat} : a ⊓ b = min a b := rfl instance : ordered_add_comm_monoid enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro trivial (h₁ h.2), λ _, add_le_add_left (h₂ _) c⟩), lt_of_add_lt_add_left := λ a b c, enat.cases_on a (λ h, by simpa [lt_irrefl] using h) (λ a, enat.cases_on b (λ h, absurd h (not_lt_of_ge (by rw add_top; exact le_top))) (λ b, enat.cases_on c (λ _, coe_lt_top _) (λ c h, coe_lt_coe.2 (by rw [← coe_add, ← coe_add, coe_lt_coe] at h; exact lt_of_add_lt_add_left h)))), ..enat.decidable_linear_order, ..enat.add_comm_monoid } instance : canonically_ordered_add_monoid enat := { le_iff_exists_add := λ a b, enat.cases_on b (iff_of_true le_top ⟨⊤, (add_top _).symm⟩) (λ b, enat.cases_on a (iff_of_false (not_le_of_gt (coe_lt_top _)) (not_exists.2 (λ x, ne_of_lt (by rw [top_add]; exact coe_lt_top _)))) (λ a, ⟨λ h, ⟨(b - a : ℕ), by rw [← coe_add, coe_inj, add_comm, nat.sub_add_cancel (coe_le_coe.1 h)]⟩, (λ ⟨c, hc⟩, enat.cases_on c (λ hc, hc.symm ▸ show (a : enat) ≤ a + ⊤, by rw [add_top]; exact le_top) (λ c (hc : (b : enat) = a + c), coe_le_coe.2 (by rw [← coe_add, coe_inj] at hc; rw hc; exact nat.le_add_right _ _)) hc)⟩)), ..enat.semilattice_sup_bot, ..enat.ordered_add_comm_monoid } protected lemma add_lt_add_right {x y z : enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := begin rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, rcases ne_top_iff.mp hz with ⟨k, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply_mod_cast coe_lt_top }, norm_cast at h, apply_mod_cast add_lt_add_right h end protected lemma add_lt_add_iff_right {x y z : enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right', λ h, enat.add_lt_add_right h hz⟩ protected lemma add_lt_add_iff_left {x y z : enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, enat.add_lt_add_iff_right hz] protected lemma lt_add_iff_pos_right {x y : enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by { conv_rhs { rw [← enat.add_lt_add_iff_left hx] }, rw [add_zero] } lemma lt_add_one {x : enat} (hx : x ≠ ⊤) : x < x + 1 := by { rw [enat.lt_add_iff_pos_right hx], norm_cast, norm_num } lemma le_of_lt_add_one {x y : enat} (h : x < y + 1) : x ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h end lemma add_one_le_of_lt {x y : enat} (h : x < y) : x + 1 ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h end lemma add_one_le_iff_lt {x y : enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := begin split, swap, exact add_one_le_of_lt, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, apply coe_lt_top, apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h end lemma lt_add_one_iff_lt {x y : enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := begin split, exact le_of_lt_add_one, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply coe_lt_top }, apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h end lemma add_eq_top_iff {a b : enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by apply enat.cases_on a; apply enat.cases_on b; simp; simp only [(enat.coe_add _ _).symm, enat.coe_ne_top]; simp protected lemma add_right_cancel_iff {a b c : enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := begin rcases ne_top_iff.1 hc with ⟨c, rfl⟩, apply enat.cases_on a; apply enat.cases_on b; simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : enat)]; simp only [(enat.coe_add _ _).symm, add_left_cancel_iff, enat.coe_inj, add_comm]; tauto end protected lemma add_left_cancel_iff {a b c : enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, enat.add_right_cancel_iff ha] section with_top /-- Computably converts an `enat` to a `with_top ℕ`. -/ def to_with_top (x : enat) [decidable x.dom]: with_top ℕ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' {h : decidable (⊤ : enat).dom} : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' {h : decidable (0 : enat).dom}: to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_coe (n : ℕ) : to_with_top n = n := rfl @[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : enat).dom} : to_with_top (n : enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := enat.cases_on y (by simp) (enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := by simp only [lt_iff_le_not_le, to_with_top_le] end with_top section with_top_equiv open_locale classical /-- Order isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_equiv : enat ≃ with_top ℕ := { to_fun := λ x, to_with_top x, inv_fun := λ x, match x with (some n) := coe n | none := ⊤ end, left_inv := λ x, by apply enat.cases_on x; intros; simp; refl, right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl } @[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n := to_with_top_coe' _ @[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 := with_top_equiv_coe _ @[simp] lemma with_top_equiv_le {x y : enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] lemma with_top_equiv_lt {x y : enat} : with_top_equiv x < with_top_equiv y ↔ x < y := to_with_top_lt @[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ := rfl @[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n := rfl @[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 := rfl @[simp] lemma with_top_equiv_symm_le {x y : with_top ℕ} : with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y := by rw ← with_top_equiv_le; simp @[simp] lemma with_top_equiv_symm_lt {x y : with_top ℕ} : with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y := by rw ← with_top_equiv_lt; simp end with_top_equiv lemma lt_wf : well_founded ((<) : enat → enat → Prop) := show well_founded (λ a b : enat, a < b), by haveI := classical.dec; simp only [to_with_top_lt.symm] {eta := ff}; exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) instance : has_well_founded enat := ⟨(<), lt_wf⟩ end enat
f681b0f8d6aa0988a6a8d71f25b3103b74eccfbe
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebraic_geometry/function_field.lean
6e8f90ac361b0ed02eaa46d5a76f875d0be071ab
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
8,159
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.properties /-! # Function field of integral schemes We define the function field of an irreducible scheme as the stalk of the generic point. This is a field when the scheme is integral. ## Main definition * `algebraic_geometry.Scheme.function_field`: The function field of an integral scheme. * `algebraic_geometry.germ_to_function_field`: The canonical map from a component into the function field. This map is injective. -/ universes u v open topological_space opposite category_theory category_theory.limits Top namespace algebraic_geometry variable (X : Scheme) /-- The function field of an irreducible scheme is the local ring at its generic point. Despite the name, this is a field only when the scheme is integral. -/ noncomputable abbreviation Scheme.function_field [irreducible_space X.carrier] : CommRing := X.presheaf.stalk (generic_point X.carrier) /-- The restriction map from a component to the function field. -/ noncomputable abbreviation Scheme.germ_to_function_field [irreducible_space X.carrier] (U : opens X.carrier) [h : nonempty U] : X.presheaf.obj (op U) ⟶ X.function_field := X.presheaf.germ ⟨generic_point X.carrier, ((generic_point_spec X.carrier).mem_open_set_iff U.is_open).mpr (by simpa using h)⟩ noncomputable instance [irreducible_space X.carrier] (U : opens X.carrier) [nonempty U] : algebra (X.presheaf.obj (op U)) X.function_field := (X.germ_to_function_field U).to_algebra noncomputable instance [is_integral X] : field X.function_field := begin apply field_of_is_unit_or_eq_zero, intro a, obtain ⟨U, m, s, rfl⟩ := Top.presheaf.germ_exist _ _ a, rw [or_iff_not_imp_right, ← (X.presheaf.germ ⟨_, m⟩).map_zero], intro ha, replace ha := ne_of_apply_ne _ ha, have hs : generic_point X.carrier ∈ RingedSpace.basic_open _ s, { rw [← set_like.mem_coe, (generic_point_spec X.carrier).mem_open_set_iff, set.top_eq_univ, set.univ_inter, set.nonempty_iff_ne_empty, ne.def, ← opens.coe_bot, ← set_like.ext'_iff], erw basic_open_eq_bot_iff, exacts [ha, (RingedSpace.basic_open _ _).is_open] }, have := (X.presheaf.germ ⟨_, hs⟩).is_unit_map (RingedSpace.is_unit_res_basic_open _ s), rwa Top.presheaf.germ_res_apply at this end lemma germ_injective_of_is_integral [is_integral X] {U : opens X.carrier} (x : U) : function.injective (X.presheaf.germ x) := begin rw injective_iff_map_eq_zero, intros y hy, rw ← (X.presheaf.germ x).map_zero at hy, obtain ⟨W, hW, iU, iV, e⟩ := X.presheaf.germ_eq _ x.prop x.prop _ _ hy, cases (show iU = iV, from subsingleton.elim _ _), haveI : nonempty W := ⟨⟨_, hW⟩⟩, exact map_injective_of_is_integral X iU e end lemma Scheme.germ_to_function_field_injective [is_integral X] (U : opens X.carrier) [nonempty U] : function.injective (X.germ_to_function_field U) := germ_injective_of_is_integral _ _ lemma generic_point_eq_of_is_open_immersion {X Y : Scheme} (f : X ⟶ Y) [H : is_open_immersion f] [hX : irreducible_space X.carrier] [irreducible_space Y.carrier] : f.1.base (generic_point X.carrier : _) = (generic_point Y.carrier : _) := begin apply ((generic_point_spec _).eq _).symm, show t0_space Y.carrier, by apply_instance, convert (generic_point_spec X.carrier).image (show continuous f.1.base, by continuity), symmetry, rw [eq_top_iff, set.top_eq_univ, set.top_eq_univ], convert subset_closure_inter_of_is_preirreducible_of_is_open _ H.base_open.open_range _, rw [set.univ_inter, set.image_univ], apply_with preirreducible_space.is_preirreducible_univ { instances := ff }, show preirreducible_space Y.carrier, by apply_instance, exact ⟨_, trivial, set.mem_range_self hX.2.some⟩, end noncomputable instance stalk_function_field_algebra [irreducible_space X.carrier] (x : X.carrier) : algebra (X.presheaf.stalk x) X.function_field := begin apply ring_hom.to_algebra, exact X.presheaf.stalk_specializes ((generic_point_spec X.carrier).specializes trivial) end instance function_field_is_scalar_tower [irreducible_space X.carrier] (U : opens X.carrier) (x : U) [nonempty U] : is_scalar_tower (X.presheaf.obj $ op U) (X.presheaf.stalk x) X.function_field := begin apply is_scalar_tower.of_algebra_map_eq', simp_rw [ring_hom.algebra_map_to_algebra], change _ = X.presheaf.germ x ≫ _, rw X.presheaf.germ_stalk_specializes, refl end noncomputable instance (R : CommRing) [is_domain R] : algebra R (Scheme.Spec.obj $ op R).function_field := ring_hom.to_algebra $ by { change CommRing.of R ⟶ _, apply structure_sheaf.to_stalk } @[simp] lemma generic_point_eq_bot_of_affine (R : CommRing) [is_domain R] : generic_point (Scheme.Spec.obj $ op R).carrier = (⟨0, ideal.bot_prime⟩ : prime_spectrum R) := begin apply (generic_point_spec (Scheme.Spec.obj $ op R).carrier).eq, simp [is_generic_point_def, ← prime_spectrum.zero_locus_vanishing_ideal_eq_closure] end instance function_field_is_fraction_ring_of_affine (R : CommRing.{u}) [is_domain R] : is_fraction_ring R (Scheme.Spec.obj $ op R).function_field := begin convert structure_sheaf.is_localization.to_stalk R _, delta is_fraction_ring is_localization.at_prime, congr' 1, rw generic_point_eq_bot_of_affine, ext, exact mem_non_zero_divisors_iff_ne_zero end instance {X : Scheme} [is_integral X] {U : opens X.carrier} [hU : nonempty U] : is_integral (X.restrict U.open_embedding) := begin haveI : nonempty (X.restrict U.open_embedding).carrier := hU, exact is_integral_of_open_immersion (X.of_restrict U.open_embedding) end lemma is_affine_open.prime_ideal_of_generic_point {X : Scheme} [is_integral X] {U : opens X.carrier} (hU : is_affine_open U) [h : nonempty U] : hU.prime_ideal_of ⟨generic_point X.carrier, ((generic_point_spec X.carrier).mem_open_set_iff U.is_open).mpr (by simpa using h)⟩ = generic_point (Scheme.Spec.obj $ op $ X.presheaf.obj $ op U).carrier := begin haveI : is_affine _ := hU, have e : U.open_embedding.is_open_map.functor.obj ⊤ = U, { ext1, exact set.image_univ.trans subtype.range_coe }, delta is_affine_open.prime_ideal_of, rw ← Scheme.comp_val_base_apply, convert (generic_point_eq_of_is_open_immersion ((X.restrict U.open_embedding).iso_Spec.hom ≫ Scheme.Spec.map (X.presheaf.map (eq_to_hom e).op).op)), ext1, exact (generic_point_eq_of_is_open_immersion (X.of_restrict U.open_embedding)).symm end lemma function_field_is_fraction_ring_of_is_affine_open [is_integral X] (U : opens X.carrier) (hU : is_affine_open U) [hU' : nonempty U] : is_fraction_ring (X.presheaf.obj $ op U) X.function_field := begin haveI : is_affine _ := hU, haveI : nonempty (X.restrict U.open_embedding).carrier := hU', haveI : is_integral (X.restrict U.open_embedding) := @@is_integral_of_is_affine_is_domain _ _ _ (by { dsimp, rw opens.open_embedding_obj_top, apply_instance }), have e : U.open_embedding.is_open_map.functor.obj ⊤ = U, { ext1, exact set.image_univ.trans subtype.range_coe }, delta is_fraction_ring Scheme.function_field, convert hU.is_localization_stalk ⟨generic_point X.carrier, _⟩ using 1, rw [hU.prime_ideal_of_generic_point, generic_point_eq_bot_of_affine], ext, exact mem_non_zero_divisors_iff_ne_zero end instance (x : X.carrier) : is_affine (X.affine_cover.obj x) := algebraic_geometry.Spec_is_affine _ instance [h : is_integral X] (x : X.carrier) : is_fraction_ring (X.presheaf.stalk x) X.function_field := begin let U : opens X.carrier := ⟨set.range (X.affine_cover.map x).1.base, PresheafedSpace.is_open_immersion.base_open.open_range⟩, haveI : nonempty U := ⟨⟨_, X.affine_cover.covers x⟩⟩, have hU : is_affine_open U := range_is_affine_open_of_open_immersion (X.affine_cover.map x), exact @@is_fraction_ring.is_fraction_ring_of_is_domain_of_is_localization _ _ _ _ _ _ _ _ _ _ _ (hU.is_localization_stalk ⟨x, X.affine_cover.covers x⟩) (function_field_is_fraction_ring_of_is_affine_open X U hU) end end algebraic_geometry
0b33f823e1e8fce20265c6445de5834e9ee35d04
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/group_theory/complement.lean
e8554aca64a67d3539a7c58f8bd2653c44edb3e3
[ "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,503
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import group_theory.order_of_element /-! # Complements In this file we define the complement of a subgroup. ## Main definitions - `is_complement S T` where `S` and `T` are subsets of `G` states that every `g : G` can be written uniquely as a product `s * t` for `s ∈ S`, `t ∈ T`. - `left_transversals T` where `T` is a subset of `G` is the set of all left-complements of `T`, i.e. the set of all `S : set G` that contain exactly one element of each left coset of `T`. - `right_transversals S` where `S` is a subset of `G` is the set of all right-complements of `S`, i.e. the set of all `T : set G` that contain exactly one element of each right coset of `S`. ## Main results - `is_complement_of_coprime` : Subgroups of coprime order are complements. -/ open_locale big_operators namespace subgroup variables {G : Type*} [group G] (H K : subgroup G) (S T : set G) /-- `S` and `T` are complements if `(*) : S × T → G` is a bijection. This notion generalizes left transversals, right transversals, and complementary subgroups. -/ @[to_additive "`S` and `T` are complements if `(*) : S × T → G` is a bijection"] def is_complement : Prop := function.bijective (λ x : S × T, x.1.1 * x.2.1) /-- `H` and `K` are complements if `(*) : H × K → G` is a bijection -/ @[to_additive "`H` and `K` are complements if `(*) : H × K → G` is a bijection"] abbreviation is_complement' := is_complement (H : set G) (K : set G) /-- The set of left-complements of `T : set G` -/ @[to_additive "The set of left-complements of `T : set G`"] def left_transversals : set (set G) := {S : set G | is_complement S T} /-- The set of right-complements of `S : set G` -/ @[to_additive "The set of right-complements of `S : set G`"] def right_transversals : set (set G) := {T : set G | is_complement S T} variables {H K S T} @[to_additive] lemma is_complement'_def : is_complement' H K ↔ is_complement (H : set G) (K : set G) := iff.rfl @[to_additive] lemma is_complement_iff_exists_unique : is_complement S T ↔ ∀ g : G, ∃! x : S × T, x.1.1 * x.2.1 = g := function.bijective_iff_exists_unique _ @[to_additive] lemma is_complement.exists_unique (h : is_complement S T) (g : G) : ∃! x : S × T, x.1.1 * x.2.1 = g := is_complement_iff_exists_unique.mp h g @[to_additive] lemma is_complement'.symm (h : is_complement' H K) : is_complement' K H := begin let ϕ : H × K ≃ K × H := equiv.mk (λ x, ⟨x.2⁻¹, x.1⁻¹⟩) (λ x, ⟨x.2⁻¹, x.1⁻¹⟩) (λ x, prod.ext (inv_inv _) (inv_inv _)) (λ x, prod.ext (inv_inv _) (inv_inv _)), let ψ : G ≃ G := equiv.mk (λ g : G, g⁻¹) (λ g : G, g⁻¹) inv_inv inv_inv, suffices : ψ ∘ (λ x : H × K, x.1.1 * x.2.1) = (λ x : K × H, x.1.1 * x.2.1) ∘ ϕ, { rwa [is_complement'_def, is_complement, ←equiv.bijective_comp, ←this, equiv.comp_bijective] }, exact funext (λ x, mul_inv_rev _ _), end @[to_additive] lemma is_complement'_comm : is_complement' H K ↔ is_complement' K H := ⟨is_complement'.symm, is_complement'.symm⟩ @[to_additive] lemma is_complement_top_singleton {g : G} : is_complement (⊤ : set G) {g} := ⟨λ ⟨x, _, rfl⟩ ⟨y, _, rfl⟩ h, prod.ext (subtype.ext (mul_right_cancel h)) rfl, λ x, ⟨⟨⟨x * g⁻¹, ⟨⟩⟩, g, rfl⟩, inv_mul_cancel_right x g⟩⟩ @[to_additive] lemma is_complement_singleton_top {g : G} : is_complement ({g} : set G) ⊤ := ⟨λ ⟨⟨_, rfl⟩, x⟩ ⟨⟨_, rfl⟩, y⟩ h, prod.ext rfl (subtype.ext (mul_left_cancel h)), λ x, ⟨⟨⟨g, rfl⟩, g⁻¹ * x, ⟨⟩⟩, mul_inv_cancel_left g x⟩⟩ @[to_additive] lemma is_complement_singleton_left {g : G} : is_complement {g} S ↔ S = ⊤ := begin refine ⟨λ h, top_le_iff.mp (λ x hx, _), λ h, (congr_arg _ h).mpr is_complement_singleton_top⟩, obtain ⟨⟨⟨z, rfl : z = g⟩, y, _⟩, hy⟩ := h.2 (g * x), rwa ← mul_left_cancel hy, end @[to_additive] lemma is_complement_singleton_right {g : G} : is_complement S {g} ↔ S = ⊤ := begin refine ⟨λ h, top_le_iff.mp (λ x hx, _), λ h, (congr_arg _ h).mpr is_complement_top_singleton⟩, obtain ⟨y, hy⟩ := h.2 (x * g), conv_rhs at hy { rw ← (show y.2.1 = g, from y.2.2) }, rw ← mul_right_cancel hy, exact y.1.2, end @[to_additive] lemma is_complement_top_left : is_complement ⊤ S ↔ ∃ g : G, S = {g} := begin refine ⟨λ h, set.exists_eq_singleton_iff_nonempty_unique_mem.mpr ⟨_, λ a ha b hb, _⟩, _⟩, { obtain ⟨a, ha⟩ := h.2 1, exact ⟨a.2.1, a.2.2⟩ }, { have : (⟨⟨_, mem_top a⁻¹⟩, ⟨a, ha⟩⟩ : (⊤ : set G) × S) = ⟨⟨_, mem_top b⁻¹⟩, ⟨b, hb⟩⟩ := h.1 ((inv_mul_self a).trans (inv_mul_self b).symm), exact subtype.ext_iff.mp ((prod.ext_iff.mp this).2) }, { rintro ⟨g, rfl⟩, exact is_complement_top_singleton }, end @[to_additive] lemma is_complement_top_right : is_complement S ⊤ ↔ ∃ g : G, S = {g} := begin refine ⟨λ h, set.exists_eq_singleton_iff_nonempty_unique_mem.mpr ⟨_, λ a ha b hb, _⟩, _⟩, { obtain ⟨a, ha⟩ := h.2 1, exact ⟨a.1.1, a.1.2⟩ }, { have : (⟨⟨a, ha⟩, ⟨_, mem_top a⁻¹⟩⟩ : S × (⊤ : set G)) = ⟨⟨b, hb⟩, ⟨_, mem_top b⁻¹⟩⟩ := h.1 ((mul_inv_self a).trans (mul_inv_self b).symm), exact subtype.ext_iff.mp ((prod.ext_iff.mp this).1) }, { rintro ⟨g, rfl⟩, exact is_complement_singleton_top }, end @[to_additive] lemma is_complement'_top_bot : is_complement' (⊤ : subgroup G) ⊥ := is_complement_top_singleton @[to_additive] lemma is_complement'_bot_top : is_complement' (⊥ : subgroup G) ⊤ := is_complement_singleton_top @[simp, to_additive] lemma is_complement'_bot_left : is_complement' ⊥ H ↔ H = ⊤ := is_complement_singleton_left.trans coe_eq_univ @[simp, to_additive] lemma is_complement'_bot_right : is_complement' H ⊥ ↔ H = ⊤ := is_complement_singleton_right.trans coe_eq_univ @[simp, to_additive] lemma is_complement'_top_left : is_complement' ⊤ H ↔ H = ⊥ := is_complement_top_left.trans coe_eq_singleton @[simp, to_additive] lemma is_complement'_top_right : is_complement' H ⊤ ↔ H = ⊥ := is_complement_top_right.trans coe_eq_singleton @[to_additive] lemma mem_left_transversals_iff_exists_unique_inv_mul_mem : S ∈ left_transversals T ↔ ∀ g : G, ∃! s : S, (s : G)⁻¹ * g ∈ T := begin rw [left_transversals, set.mem_set_of_eq, is_complement_iff_exists_unique], refine ⟨λ h g, _, λ h g, _⟩, { obtain ⟨x, h1, h2⟩ := h g, exact ⟨x.1, (congr_arg (∈ T) (eq_inv_mul_of_mul_eq h1)).mp x.2.2, λ y hy, (prod.ext_iff.mp (h2 ⟨y, y⁻¹ * g, hy⟩ (mul_inv_cancel_left y g))).1⟩ }, { obtain ⟨x, h1, h2⟩ := h g, refine ⟨⟨x, x⁻¹ * g, h1⟩, mul_inv_cancel_left x g, λ y hy, _⟩, have := h2 y.1 ((congr_arg (∈ T) (eq_inv_mul_of_mul_eq hy)).mp y.2.2), exact prod.ext this (subtype.ext (eq_inv_mul_of_mul_eq ((congr_arg _ this).mp hy))) }, end @[to_additive] lemma mem_right_transversals_iff_exists_unique_mul_inv_mem : S ∈ right_transversals T ↔ ∀ g : G, ∃! s : S, g * (s : G)⁻¹ ∈ T := begin rw [right_transversals, set.mem_set_of_eq, is_complement_iff_exists_unique], refine ⟨λ h g, _, λ h g, _⟩, { obtain ⟨x, h1, h2⟩ := h g, exact ⟨x.2, (congr_arg (∈ T) (eq_mul_inv_of_mul_eq h1)).mp x.1.2, λ y hy, (prod.ext_iff.mp (h2 ⟨⟨g * y⁻¹, hy⟩, y⟩ (inv_mul_cancel_right g y))).2⟩ }, { obtain ⟨x, h1, h2⟩ := h g, refine ⟨⟨⟨g * x⁻¹, h1⟩, x⟩, inv_mul_cancel_right g x, λ y hy, _⟩, have := h2 y.2 ((congr_arg (∈ T) (eq_mul_inv_of_mul_eq hy)).mp y.1.2), exact prod.ext (subtype.ext (eq_mul_inv_of_mul_eq ((congr_arg _ this).mp hy))) this }, end @[to_additive] lemma mem_left_transversals_iff_exists_unique_quotient_mk'_eq : S ∈ left_transversals (H : set G) ↔ ∀ q : quotient (quotient_group.left_rel H), ∃! s : S, quotient.mk' s.1 = q := begin have key : ∀ g h, quotient.mk' g = quotient.mk' h ↔ g⁻¹ * h ∈ H := @quotient.eq' G (quotient_group.left_rel H), simp_rw [mem_left_transversals_iff_exists_unique_inv_mul_mem, set_like.mem_coe, ←key], exact ⟨λ h q, quotient.induction_on' q h, λ h g, h (quotient.mk' g)⟩, end @[to_additive] lemma mem_right_transversals_iff_exists_unique_quotient_mk'_eq : S ∈ right_transversals (H : set G) ↔ ∀ q : quotient (quotient_group.right_rel H), ∃! s : S, quotient.mk' s.1 = q := begin have key : ∀ g h, quotient.mk' g = quotient.mk' h ↔ h * g⁻¹ ∈ H := @quotient.eq' G (quotient_group.right_rel H), simp_rw [mem_right_transversals_iff_exists_unique_mul_inv_mem, set_like.mem_coe, ←key], exact ⟨λ h q, quotient.induction_on' q h, λ h g, h (quotient.mk' g)⟩, end @[to_additive] lemma mem_left_transversals_iff_bijective : S ∈ left_transversals (H : set G) ↔ function.bijective (S.restrict (quotient.mk' : G → quotient (quotient_group.left_rel H))) := mem_left_transversals_iff_exists_unique_quotient_mk'_eq.trans (function.bijective_iff_exists_unique (S.restrict quotient.mk')).symm @[to_additive] lemma mem_right_transversals_iff_bijective : S ∈ right_transversals (H : set G) ↔ function.bijective (set.restrict (quotient.mk' : G → quotient (quotient_group.right_rel H)) S) := mem_right_transversals_iff_exists_unique_quotient_mk'_eq.trans (function.bijective_iff_exists_unique (S.restrict quotient.mk')).symm @[to_additive] instance : inhabited (left_transversals (H : set G)) := ⟨⟨set.range quotient.out', mem_left_transversals_iff_bijective.mpr ⟨by { rintros ⟨_, q₁, rfl⟩ ⟨_, q₂, rfl⟩ hg, rw (q₁.out_eq'.symm.trans hg).trans q₂.out_eq' }, λ q, ⟨⟨q.out', q, rfl⟩, quotient.out_eq' q⟩⟩⟩⟩ @[to_additive] instance : inhabited (right_transversals (H : set G)) := ⟨⟨set.range quotient.out', mem_right_transversals_iff_bijective.mpr ⟨by { rintros ⟨_, q₁, rfl⟩ ⟨_, q₂, rfl⟩ hg, rw (q₁.out_eq'.symm.trans hg).trans q₂.out_eq' }, λ q, ⟨⟨q.out', q, rfl⟩, quotient.out_eq' q⟩⟩⟩⟩ lemma is_complement'.is_compl (h : is_complement' H K) : is_compl H K := begin refine ⟨λ g ⟨p, q⟩, let x : H × K := ⟨⟨g, p⟩, 1⟩, y : H × K := ⟨1, g, q⟩ in subtype.ext_iff.mp (prod.ext_iff.mp (show x = y, from h.1 ((mul_one g).trans (one_mul g).symm))).1, λ g _, _⟩, obtain ⟨⟨h, k⟩, rfl⟩ := h.2 g, exact subgroup.mul_mem_sup h.2 k.2, end lemma is_complement'.sup_eq_top (h : subgroup.is_complement' H K) : H ⊔ K = ⊤ := h.is_compl.sup_eq_top lemma is_complement'.disjoint (h : is_complement' H K) : disjoint H K := h.is_compl.disjoint lemma is_complement.card_mul [fintype G] [fintype S] [fintype T] (h : is_complement S T) : fintype.card S * fintype.card T = fintype.card G := (fintype.card_prod _ _).symm.trans (fintype.card_of_bijective h) lemma is_complement'.card_mul [fintype G] [fintype H] [fintype K] (h : is_complement' H K) : fintype.card H * fintype.card K = fintype.card G := h.card_mul lemma is_complement'_of_card_mul_and_disjoint [fintype G] [fintype H] [fintype K] (h1 : fintype.card H * fintype.card K = fintype.card G) (h2 : disjoint H K) : is_complement' H K := begin refine (fintype.bijective_iff_injective_and_card _).mpr ⟨λ x y h, _, (fintype.card_prod H K).trans h1⟩, rw [←eq_inv_mul_iff_mul_eq, ←mul_assoc, ←mul_inv_eq_iff_eq_mul] at h, change ↑(x.2 * y.2⁻¹) = ↑(x.1⁻¹ * y.1) at h, rw [prod.ext_iff, ←@inv_mul_eq_one H _ x.1 y.1, ←@mul_inv_eq_one K _ x.2 y.2, subtype.ext_iff, subtype.ext_iff, coe_one, coe_one, h, and_self, ←mem_bot, ←h2.eq_bot, mem_inf], exact ⟨subtype.mem ((x.1)⁻¹ * (y.1)), (congr_arg (∈ K) h).mp (subtype.mem (x.2 * (y.2)⁻¹))⟩, end lemma is_complement'_iff_card_mul_and_disjoint [fintype G] [fintype H] [fintype K] : is_complement' H K ↔ fintype.card H * fintype.card K = fintype.card G ∧ disjoint H K := ⟨λ h, ⟨h.card_mul, h.disjoint⟩, λ h, is_complement'_of_card_mul_and_disjoint h.1 h.2⟩ lemma is_complement'_of_coprime [fintype G] [fintype H] [fintype K] (h1 : fintype.card H * fintype.card K = fintype.card G) (h2 : nat.coprime (fintype.card H) (fintype.card K)) : is_complement' H K := is_complement'_of_card_mul_and_disjoint h1 (disjoint_iff.mpr (inf_eq_bot_of_coprime h2)) end subgroup
ec3f3db4352fe8998374c0c8f8929f4b574baec3
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/geom_sum.lean
5e7cdbd7450f0c50a6a1970fd6cc0396adfcea67
[ "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
7,749
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Sums of finite geometric series -/ import algebra.group_with_zero_power import algebra.big_operators universe u variable {α : Type u} open finset opposite open_locale big_operators /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i$. -/ def geom_series [semiring α] (x : α) (n : ℕ) := ∑ i in range n, x ^ i theorem geom_series_def [semiring α] (x : α) (n : ℕ) : geom_series x n = ∑ i in range n, x ^ i := rfl @[simp] theorem geom_series_zero [semiring α] (x : α) : geom_series x 0 = 0 := rfl @[simp] theorem geom_series_one [semiring α] (x : α) : geom_series x 1 = 1 := by { rw [geom_series_def, sum_range_one, pow_zero] } @[simp] lemma op_geom_series [ring α] (x : α) (n : ℕ) : op (geom_series x n) = geom_series (op x) n := by simp [geom_series_def] /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i y^{n-1-i}$. -/ def geom_series₂ [semiring α] (x y : α) (n : ℕ) := ∑ i in range n, x ^ i * (y ^ (n - 1 - i)) theorem geom_series₂_def [semiring α] (x y : α) (n : ℕ) : geom_series₂ x y n = ∑ i in range n, x ^ i * y ^ (n - 1 - i) := rfl @[simp] theorem geom_series₂_zero [semiring α] (x y : α) : geom_series₂ x y 0 = 0 := rfl @[simp] theorem geom_series₂_one [semiring α] (x y : α) : geom_series₂ x y 1 = 1 := by { have : 1 - 1 - 0 = 0 := rfl, rw [geom_series₂_def, sum_range_one, this, pow_zero, pow_zero, mul_one] } @[simp] theorem geom_series₂_with_one [semiring α] (x : α) (n : ℕ) : geom_series₂ x 1 n = geom_series x n := sum_congr rfl (λ i _, by { rw [one_pow, mul_one] }) /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ protected theorem commute.geom_sum₂_mul_add [semiring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_series₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := begin let f := λ (m i : ℕ), (x + y) ^ i * y ^ (m - 1 - i), change (∑ i in range n, (f n) i) * x + y ^ n = (x + y) ^ n, induction n with n ih, { rw [range_zero, sum_empty, zero_mul, zero_add, pow_zero, pow_zero] }, { have f_last : f (n + 1) n = (x + y) ^ n := by { dsimp [f], rw [nat.sub_sub, nat.add_comm, nat.sub_self, pow_zero, mul_one] }, have f_succ : ∀ i, i ∈ range n → f (n + 1) i = y * f n i := λ i hi, by { dsimp [f], have : commute y ((x + y) ^ i) := (h.symm.add_right (commute.refl y)).pow_right i, rw [← mul_assoc, this.eq, mul_assoc, ← pow_succ y (n - 1 - i)], congr' 2, rw [nat.add_sub_cancel, nat.sub_sub, add_comm 1 i], have : i + 1 + (n - (i + 1)) = n := nat.add_sub_of_le (mem_range.mp hi), rw [add_comm (i + 1)] at this, rw [← this, nat.add_sub_cancel, add_comm i 1, ← add_assoc, nat.add_sub_cancel] }, rw [pow_succ (x + y), add_mul, sum_range_succ, f_last, add_mul, add_assoc], rw [(((commute.refl x).add_right h).pow_right n).eq], congr' 1, rw[sum_congr rfl f_succ, ← mul_sum, pow_succ y], rw[mul_assoc, ← mul_add y, ih] } end theorem geom_series₂_self {α : Type*} [comm_ring α] (x : α) (n : ℕ) : geom_series₂ x x n = n * x ^ (n-1) := calc ∑ i in finset.range n, x ^ i * x ^ (n - 1 - i) = ∑ i in finset.range n, x ^ (i + (n - 1 - i)) : by simp_rw [← pow_add] ... = ∑ i in finset.range n, x ^ (n - 1) : finset.sum_congr rfl (λ i hi, congr_arg _ $ nat.add_sub_cancel' $ nat.le_pred_of_lt $ finset.mem_range.1 hi) ... = (finset.range n).card •ℕ (x ^ (n - 1)) : finset.sum_const _ ... = n * x ^ (n - 1) : by rw [finset.card_range, nsmul_eq_mul] /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ theorem geom_sum₂_mul_add [comm_semiring α] (x y : α) (n : ℕ) : (geom_series₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := (commute.all x y).geom_sum₂_mul_add n theorem geom_sum_mul_add [semiring α] (x : α) (n : ℕ) : (geom_series (x + 1) n) * x + 1 = (x + 1) ^ n := begin have := (commute.one_right x).geom_sum₂_mul_add n, rw [one_pow, geom_series₂_with_one] at this, exact this end theorem geom_sum₂_mul_comm [ring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_series₂ x y n) * (x - y) = x ^ n - y ^ n := begin have := (h.sub_left (commute.refl y)).geom_sum₂_mul_add n, rw [sub_add_cancel] at this, rw [← this, add_sub_cancel] end theorem geom_sum₂_mul [comm_ring α] (x y : α) (n : ℕ) : (geom_series₂ x y n) * (x - y) = x ^ n - y ^ n := geom_sum₂_mul_comm (commute.all x y) n theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : (geom_series x n) * (x - 1) = x ^ n - 1 := begin have := geom_sum₂_mul_comm (commute.one_right x) n, rw [one_pow, geom_series₂_with_one] at this, exact this end lemma mul_geom_sum [ring α] (x : α) (n : ℕ) : (x - 1) * (geom_series x n) = x ^ n - 1 := begin rw ← op_inj_iff, simpa using geom_sum_mul (op x) n, end theorem geom_sum_mul_neg [ring α] (x : α) (n : ℕ) : (geom_series x n) * (1 - x) = 1 - x ^ n := begin have := congr_arg has_neg.neg (geom_sum_mul x n), rw [neg_sub, ← mul_neg_eq_neg_mul_symm, neg_sub] at this, exact this end lemma mul_neg_geom_sum [ring α] (x : α) (n : ℕ) : (1 - x) * (geom_series x n) = 1 - x ^ n := begin rw ← op_inj_iff, simpa using geom_sum_mul_neg (op x) n, end theorem geom_sum [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (geom_series x n) = (x ^ n - 1) / (x - 1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] theorem geom_sum_Ico_mul [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (x - 1) = x^n - x^m := by rw [sum_Ico_eq_sub _ hmn, ← geom_series_def, ← geom_series_def, sub_mul, geom_sum_mul, geom_sum_mul, sub_sub_sub_cancel_right] theorem geom_sum_Ico_mul_neg [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (1 - x) = x^m - x^n := by rw [sum_Ico_eq_sub _ hmn, ← geom_series_def, ← geom_series_def, sub_mul, geom_sum_mul_neg, geom_sum_mul_neg, sub_sub_sub_cancel_left] theorem geom_sum_Ico [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i = (x ^ n - x ^ m) / (x - 1) := by simp only [sum_Ico_eq_sub _ hmn, (geom_series_def _ _).symm, geom_sum hx, div_sub_div_same, sub_sub_sub_cancel_right] lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (geom_series x⁻¹ n) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * (x ^ n)⁻¹ = (x ^ n)⁻¹ * x := nat.rec_on n (by simp) (λ n h, by rw [pow_succ, mul_inv_rev', ←mul_assoc, h, mul_assoc, mul_inv_cancel hx0, mul_assoc, inv_mul_cancel hx0]), begin rw [geom_sum h₁, div_eq_iff_mul_eq h₂, ← mul_right_inj' h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃], simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄, sub_eq_add_neg, add_comm, add_left_comm], end variables {β : Type*} theorem ring_hom.map_geom_series [semiring α] [semiring β] (x : α) (n : ℕ) (f : α →+* β) : f (geom_series x n) = geom_series (f x) n := by simp [geom_series_def, f.map_sum] theorem ring_hom.map_geom_series₂ [semiring α] [semiring β] (x y : α) (n : ℕ) (f : α →+* β) : f (geom_series₂ x y n) = geom_series₂ (f x) (f y) n := by simp [geom_series₂_def, f.map_sum]
504a7ffbe09aa61b057de162a8c39f12cd6f1655
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/compiler/StackOverflow.lean
e495adbe68b14b253ea4fff06870d708e0437b64
[ "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
104
lean
partial def foo : Nat → Nat | n => foo n + 1 @[neverExtract] def main : IO Unit := IO.println $ foo 0
88c402a3276288c37143a52e36508b7474575773
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/e15.lean
1bcac11f15a1e6c06c377b86b1ffb6a6806a8ee9
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
605
lean
inductive nat : Type := | zero : nat | succ : nat → nat inductive list (A : Type) : Type := | nil {} : list A | cons : A → list A → list A check nil check nil.{1} check @nil.{1} nat check @nil nat check cons zero nil inductive vector (A : Type) : nat → Type := | vnil {} : vector A zero | vcons : forall {n : nat}, A → vector A n → vector A (succ n) check vcons zero vnil variable n : nat check vcons n vnil check vector_rec definition vector_to_list {A : Type} {n : nat} (v : vector A n) : list A := vector_rec nil (fun (n : nat) (a : A) (v : vector A n) (l : list A), cons a l) v
e04d57c1cacf2817607b3a0f706b6d56ac9906cc
193da933cf42f2f9188bb47e3c973205bc2abc5c
/AA_Algebras/01_dm_bool/1_builtin.bool.lean
354f27a7ba0ac29c10e4dcc59a6c50c675ab90f2
[]
no_license
pandaman64/cs-dm
aa4e2621c7a19e2dae911bc237c33e02fcb0c7a3
bfd2f5fd2612472e15bd970c7870b5d0dd73bd1c
refs/heads/master
1,647,620,340,607
1,570,055,187,000
1,570,055,187,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,939
lean
/- TYPES AND VALUES: Case study of the boolean type -/ /- In Lean, Every value, and indeed every expression that represents some value, has exactly one type. A type in turn defines a set of values, namely the set of all and the only values of the given type. For example, in Lean, the Boolean values, tt and ff (for "true" and "false") are the two and only values of the type called bool. In Lean, you can always check the type of any expression, including any literal value, by using the #check command. Hover your mouse pointer over the #check command to see its output. -/ #check tt /- The output of this command is what we call a "type judgement". In particular, it is the type judgement, "tt : bool." You can read this as saying "the type of tt is bool". -/ /- EXERCISE: use #check to confirm that the type of ff is also bool. -/ /- *** Operators and xpressions and their types -/ /- Through its libraries, Lean provides many operations on Boolean values. These include the usual "and", "or", and "not" operators familiar from CS1. For example, "band tt ff" is an expression in Lean that applies the Boolean "and", or conjunction, operator to the Boolean values tt and ff to compute a new Boolean value. The or function in lean is called bor. And the not function is called bnot. -/ /- The result of applying the bnot operator to one Boolean value is another Boolean value. Thus the type of an expression in which the bnot operator is applied to a Boolean value is ... wait for it ... bool. -/ #check bnot tt /- Note that functions are applied to values by writing the function name followed by the argument(s) to the function. -/ /- The Boolean "and" (conjunction) and "or" (disjunction), operators are called band and bor, respectively. Eacof these functions takes two Boolean-valued arguments and returns a result of type bool. -/ #check bor tt ff /- EXERCISE: Use #check to check the types of expressions in which the band operator is applied to two Boolean arguments. -/ /- You will remember from CS1 that Boolean expressions are usually written something like this: true && false, or true || false, where && means "and" and || means "or." From now on, you can think of || and && as just shorthands for "and" and "or" with the main difference being that they are written between rather than in front of their arguments. Lean also provides the same shortcutss. We call operators such as band and bor "prefix", because they are written before their operands, while && and || are called "infix" because they are written between their arguments. There are no differences in meaning, just in the "surface syntax." (band tt ff) and (tt && ff) mean exactly the same thing. The Lean compiler really just converts the latter into the former "under the hood." -/ #check tt && ff /- EXERCISE: Check the type of the expression (bor tt ff) but now write the expression using the || infix operator. -/ /- Lean also provides a mathematical shorthand for the Boolean not operator. You get this notation in Lean by typing a backslash immediately followed by "not" ane then a space. -/ #check ¬ tt /- EXERCISE: type the same #check command to be sure you know how to typeset the not operator in Lean. As you'll see, Lean gives you the ability to write mathematical logic using ordinary math and logic symbols. -/ /- *** The Evaluation (or Reduction) of Expressions -/ /- Part of magic of computers is that they can tell you not only the type of an expression, but even what value it reduces to when you evaluate the expressions. In Lean, you can use the #eval command to have Lean compute and display the reduced value of an expression. -/ #eval band tt ff /- EXERCISE: Use #eval to evaluate the disjunction of tt and ff. EXERCISE: Use #eval to evaluate the negation of tt EXERCISE: Evaluate a Lean expression for what we would informally say as "the negation of the conjunction of true and false". Use parenthesis to group the and operator and its arguments. Use #check to check the type of this expression, and use #eval to reduce it to a Boolean value. -/ /- At this point, you should feel good! You have learned about types, values, operators that are closed on values of a type, and expressions involving these operators and values. What you are seeing is the "algebra" of Boolean values, formalized in Lean, and amenable to automated type checking and evaluation. -/ /- Now it's one thing to use a computerize algebra built in to a programming system, such as Lean or Python, that someone else has given you, but it's another thing altogether to understand how to define an algebra yourself. Seeing how to do that is the purpose of the next unit. And we might as well proceed by implementing our own version of the Boolean algebra we just saw. -/
f3a7ecfaef49b0d3300136c4d711ab2e1415983a
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Lean/Util/Trace.lean
d70fabcdf602fe9eba748ae1f1fc346295a1078f
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
5,461
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Message import Lean.MonadEnv universe u namespace Lean open Std (PersistentArray) structure TraceElem where ref : Syntax msg : MessageData deriving Inhabited structure TraceState where enabled : Bool := true traces : PersistentArray TraceElem := {} deriving Inhabited namespace TraceState private def toFormat (traces : PersistentArray TraceElem) (sep : Format) : IO Format := traces.size.foldM (fun i r => do let curr ← (traces.get! i).msg.format pure $ if i > 0 then r ++ sep ++ curr else r ++ curr) Format.nil end TraceState class MonadTrace (m : Type → Type) where modifyTraceState : (TraceState → TraceState) → m Unit getTraceState : m TraceState export MonadTrace (getTraceState modifyTraceState) instance (m n) [MonadLift m n] [MonadTrace m] : MonadTrace n where modifyTraceState := fun f => liftM (modifyTraceState f : m _) getTraceState := liftM (getTraceState : m _) variable {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] def printTraces {m} [Monad m] [MonadTrace m] [MonadLiftT IO m] : m Unit := do let traceState ← getTraceState traceState.traces.forM fun m => do let d ← m.msg.format IO.println d def resetTraceState {m} [MonadTrace m] : m Unit := modifyTraceState (fun _ => {}) private def checkTraceOptionAux (opts : Options) : Name → Bool | n@(Name.str p _ _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux opts p) | _ => false def checkTraceOption (opts : Options) (cls : Name) : Bool := if opts.isEmpty then false else checkTraceOptionAux opts (`trace ++ cls) private def checkTraceOptionM [MonadOptions m] (cls : Name) : m Bool := do let opts ← getOptions pure $ checkTraceOption opts cls @[inline] def isTracingEnabledFor [MonadOptions m] (cls : Name) : m Bool := do let s ← getTraceState if !s.enabled then pure false else checkTraceOptionM cls @[inline] def enableTracing (b : Bool) : m Bool := do let s ← getTraceState let oldEnabled := s.enabled modifyTraceState fun s => { s with enabled := b } pure oldEnabled @[inline] def getTraces : m (PersistentArray TraceElem) := do let s ← getTraceState pure s.traces @[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit := modifyTraceState fun s => { s with traces := f s.traces } @[inline] def setTraceState (s : TraceState) : m Unit := modifyTraceState fun _ => s private def addNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) : m Unit := modifyTraces fun traces => if traces.isEmpty then oldTraces else let d := MessageData.tagged cls m!"[{cls}] {MessageData.node (traces.toArray.map fun elem => elem.msg)}" oldTraces.push { ref := ref, msg := d } private def getResetTraces : m (PersistentArray TraceElem) := do let oldTraces ← getTraces modifyTraces fun _ => {} pure oldTraces section variable [MonadRef m] [AddMessageContext m] [MonadOptions m] def addTrace (cls : Name) (msg : MessageData) : m Unit := do let ref ← getRef let msg ← addMessageContext msg modifyTraces fun traces => traces.push { ref := ref, msg := MessageData.tagged cls m!"[{cls}] {msg}" } @[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do if (← isTracingEnabledFor cls) then addTrace cls (msg ()) @[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do if (← isTracingEnabledFor cls) then let msg ← mkMsg addTrace cls msg @[inline] def traceCtx [MonadFinally m] (cls : Name) (ctx : m α) : m α := do let b ← isTracingEnabledFor cls if !b then let old ← enableTracing false try ctx finally enableTracing old else let ref ← getRef let oldCurrTraces ← getResetTraces try ctx finally addNode oldCurrTraces cls ref -- TODO: delete after fix old frontend def MonadTracer.trace (cls : Name) (msg : Unit → MessageData) : m Unit := Lean.trace cls msg end def registerTraceClass (traceClassName : Name) : IO Unit := registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" } syntax "trace[" ident "]" (interpolatedStr(term) <|> term) : term macro_rules | `(trace[$id] $s) => if s.getKind == interpolatedStrKind then `(Lean.trace $(quote id.getId) fun _ => m! $s) else `(Lean.trace $(quote id.getId) fun _ => ($s : MessageData)) private def withNestedTracesFinalizer [Monad m] [MonadTrace m] (ref : Syntax) (currTraces : PersistentArray TraceElem) : m Unit := do modifyTraces fun traces => if traces.size == 0 then currTraces else if traces.size == 1 && traces[0].msg.isNest then currTraces ++ traces -- No nest of nest else let d := traces.foldl (init := MessageData.nil) fun d elem => if d.isNil then elem.msg else m!"{d}\n{elem.msg}" currTraces.push { ref := ref, msg := MessageData.nestD d } @[inline] def withNestedTraces [Monad m] [MonadFinally m] [MonadTrace m] [MonadRef m] (x : m α) : m α := do let currTraces ← getTraces modifyTraces fun _ => {} let ref ← getRef try x finally withNestedTracesFinalizer ref currTraces end Lean
d5118b68ccfac850a33b38a02c318a6698f69cfc
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Elab/Declaration.lean
20c05594f17b7e06de57587a9af822c1e3a468c9
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
13,584
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 import Lean.Elab.DeclarationRange 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.classInductive || 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[3] if optDeclId.isNone then none else match expandDeclIdNamespace? optDeclId[0] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 3 (optDeclId.setArg 0 declId))) | none => none else none def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- leading_parser "axiom " >> declId >> declSig let declId := stx[1] let (binders, typeStx) := expandDeclSig stx[2] let scopeLevelNames ← getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName stx 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 ← mkForallFVars vars type (usedOnly := true) 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, levelParams := levelParams, type := type, isUnsafe := modifiers.isUnsafe } Term.ensureNoUnassignedMVars decl addDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking if isExtern (← getEnv) declName then compileDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation /- leading_parser "inductive " >> declId >> optDeclSig >> optional ":=" >> many ctor leading_parser atomic (group ("class " >> "inductive ")) >> declId >> optDeclSig >> optional ":=" >> many ctor >> optDeriving -/ private def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do checkValidInductiveModifier modifiers let (binders, type?) := expandOptDeclSig decl[2] let declId := decl[1] let ⟨name, declName, levelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName decl let ctors ← decl[4].getArgs.mapM fun ctor => withRef ctor do -- def ctor := leading_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] addDocString' ctorName ctorModifiers.docString? addAuxDeclarationRanges ctorName ctor ctor[2] pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView } let classes ← getOptDerivingClasses decl[5] pure { ref := decl modifiers := modifiers shortDeclName := name declName := declName levelNames := levelNames binders := binders type? := type? ctors := ctors derivingClasses := classes } private def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := inductiveSyntaxToView modifiers decl 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] def getTerminationBy? (stx : Syntax) : Option Syntax := let decl := stx[1] let k := decl.getKind if k == ``Parser.Command.def || k == ``Parser.Command.theorem || k == ``Parser.Command.instance then decl.getArgs.back.getOptional? else none @[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] (getTerminationBy? 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.universe || 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.throwErrorAt 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 let terminationBy? := stx[3].getOptional? if isMutualInductive stx then unless terminationBy?.isNone do throwErrorAt stx[3] "invalid 'termination_by' in mutually inductive datatype declaration" elabMutualInductive stx[1].getArgs else if isMutualDef stx then for arg in stx[1].getArgs do if let some bad := getTerminationBy? arg then throwErrorAt bad "invalid 'termination_by' in 'mutual' block, it must be used after the 'end' keyword" elabMutualDef stx[1].getArgs terminationBy? else throwError "invalid mutual block" /- leading_parser "attribute " >> "[" >> sepBy1 (eraseAttr <|> Term.attrInstance) ", " >> "]" >> many1 ident -/ @[builtinCommandElab «attribute»] def elabAttr : CommandElab := fun stx => do let mut attrInsts := #[] let mut toErase := #[] for attrKindStx in stx[2].getSepArgs do if attrKindStx.getKind == ``Lean.Parser.Command.eraseAttr then let attrName := attrKindStx[1].getId.eraseMacroScopes unless isAttribute (← getEnv) attrName do throwError "unknown attribute [{attrName}]" toErase := toErase.push attrName else attrInsts := attrInsts.push attrKindStx let attrs ← elabAttrs attrInsts let idents := stx[4].getArgs for ident in idents do withRef ident <| liftTermElabM none do let declName ← resolveGlobalConstNoOverloadWithInfo ident Term.applyAttributes declName attrs for attrName in toErase do Attribute.erase declName attrName def expandInitCmd (builtin : Bool) : Macro := fun stx => do let optVisibility := stx[0] let optHeader := stx[2] let doSeq := stx[3] let attrId := mkIdentFrom stx $ if builtin then `builtinInit else `init if optHeader.isNone then unless optVisibility.isNone do Macro.throwError "invalid initialization command, 'visibility' modifer is not allowed" `(@[$attrId:ident]def initFn : IO Unit := do $doSeq) else let id := optHeader[0] let type := optHeader[1][1] if optVisibility.isNone then `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn] constant $id : $type) else if optVisibility[0].getKind == ``Parser.Command.private then `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn] private constant $id : $type) else if optVisibility[0].getKind == ``Parser.Command.protected then `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn] protected constant $id : $type) else Macro.throwError "unexpected visibility annotation" @[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
cef6ba7479b760f4e66a891b3f3fcc90597b538b
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/zmod/basic.lean
812a957118d89095f92295001556314fc5ba1e02
[ "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
27,492
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.int.modeq import algebra.char_p import data.nat.totient import ring_theory.ideal.operations /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `zmod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class * `val_min_abs` returns the integer closest to zero in the equivalence class. * A coercion `cast` is defined from `zmod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ namespace fin /-! ## Ring structure on `fin n` We define a commutative ring structure on `fin n`, but we do not register it as instance. Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions to register the ring structure on `zmod n` as type class instance. -/ open nat nat.modeq int /-- Negation on `fin n` -/ def has_neg (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n, begin have npos : 0 < n := lt_of_le_of_lt (nat.zero_le _) a.2, have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 npos, have := int.mod_lt (-(a.1 : ℤ)) h, rw [(abs_of_nonneg (int.coe_nat_nonneg n))] at this, rwa [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h)] end⟩⟩ /-- Additive commutative semigroup structure on `fin (n+1)`. -/ def add_comm_semigroup (n : ℕ) : add_comm_semigroup (fin (n+1)) := { add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (show ((a + b) % (n+1) + c) ≡ (a + (b + c) % (n+1)) [MOD (n+1)], from calc ((a + b) % (n+1) + c) ≡ a + b + c [MOD (n+1)] : modeq_add (nat.mod_mod _ _) rfl ... ≡ a + (b + c) [MOD (n+1)] : by rw add_assoc ... ≡ (a + (b + c) % (n+1)) [MOD (n+1)] : modeq_add rfl (nat.mod_mod _ _).symm), add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % (n+1) = (b + a) % (n+1), by rw add_comm), ..fin.has_add } /-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/ def comm_semigroup (n : ℕ) : comm_semigroup (fin (n+1)) := { mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : modeq_mul (nat.mod_mod _ _) rfl ... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc ... ≡ a * (b * c % (n+1)) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _).symm), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm), ..fin.has_mul } local attribute [instance] fin.add_comm_semigroup fin.comm_semigroup private lemma one_mul_aux (n : ℕ) (a : fin (n+1)) : (1 : fin (n+1)) * a = a := begin cases n with n, { exact subsingleton.elim _ _ }, { have h₁ : (a : ℕ) % n.succ.succ = a := nat.mod_eq_of_lt a.2, apply fin.ext, simp only [coe_mul, coe_one, h₁, one_mul], } end private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _) ... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add ... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm) /-- Commutative ring structure on `fin (n+1)`. -/ def comm_ring (n : ℕ) : comm_ring (fin (n+1)) := { zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % (n+1) = a, by rw zero_add; exact nat.mod_eq_of_lt ha), add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha), add_left_neg := λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % (n+1)).to_nat + a) % (n+1) = 0, from int.coe_nat_inj begin have npos : 0 < n+1 := lt_of_le_of_lt (nat.zero_le _) ha, have hn : ((n+1) : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 npos)).symm, rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm], simp, end), one_mul := one_mul_aux n, mul_one := λ a, by rw mul_comm; exact one_mul_aux n a, left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..fin.has_zero, ..fin.has_one, ..fin.has_neg (n+1), ..fin.add_comm_semigroup n, ..fin.comm_semigroup n } end fin /-- The integers modulo `n : ℕ`. -/ def zmod : ℕ → Type | 0 := ℤ | (n+1) := fin (n+1) namespace zmod instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n) | 0 _ := false.elim $ nat.not_lt_zero 0 ‹0 < 0› | (n+1) _ := fin.fintype (n+1) lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { exact fintype.card_fin (n+1) } end instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n) | 0 := int.decidable_eq | (n+1) := fin.decidable_eq _ instance has_repr : Π (n : ℕ), has_repr (zmod n) | 0 := int.has_repr | (n+1) := fin.has_repr _ instance comm_ring : Π (n : ℕ), comm_ring (zmod n) | 0 := int.comm_ring | (n+1) := fin.comm_ring n instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩ /-- `val a` is a natural number defined as: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class See `zmod.val_min_abs` for a variant that takes values in the integers. -/ def val : Π {n : ℕ}, zmod n → ℕ | 0 := int.nat_abs | (n+1) := (coe : fin (n + 1) → ℕ) lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, exact fin.is_lt a end @[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0 | 0 := rfl | (n+1) := rfl lemma val_cast_nat {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n := begin casesI n, { rw [nat.mod_zero, int.nat_cast_eq_coe_nat], exact int.nat_abs_of_nat a, }, rw ← fin.of_nat_eq_coe, refl end instance (n : ℕ) : char_p (zmod n) n := { cast_eq_zero_iff := begin intro k, cases n, { simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], }, rw [fin.eq_iff_veq], show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _, rw [val_cast_nat, val_zero, nat.dvd_iff_mod_eq_zero], end } @[simp] lemma cast_self (n : ℕ) : (n : zmod n) = 0 := char_p.cast_eq_zero (zmod n) n @[simp] lemma cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 := by rw [← nat.cast_add_one, cast_self (n + 1)] section universal_property variables {n : ℕ} {R : Type*} section variables [has_zero R] [has_one R] [has_add R] [has_neg R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `zmod.cast_hom` for a bundled version. -/ def cast : Π {n : ℕ}, zmod n → R | 0 := int.cast | (n+1) := λ i, i.val -- see Note [coercion into rings] @[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩ @[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 := by { cases n; refl } end lemma nat_cast_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) := begin assume i, casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { change fin (n + 1) at i, refine ⟨i, _⟩, rw [fin.ext_iff, fin.coe_coe_eq_self] } end lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) := begin assume i, cases n, { exact ⟨i, int.cast_id i⟩ }, { rcases nat_cast_surjective i with ⟨k, rfl⟩, refine ⟨k, _⟩, norm_cast } end lemma cast_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a := begin rcases nat_cast_surjective a with ⟨k, rfl⟩, symmetry, rw [val_cast_nat, ← sub_eq_zero, ← nat.cast_sub, char_p.cast_eq_zero_iff (zmod n) n], { apply nat.dvd_sub_mod }, { apply nat.mod_le } end @[simp, norm_cast] lemma cast_id : ∀ n (i : zmod n), ↑i = i | 0 i := int.cast_id i | (n+1) i := cast_val i variables [ring R] @[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, refl end section char_dvd /-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/ variables {n} {m : ℕ} [char_p R m] @[simp] lemma cast_one (h : m ∣ n) : ((1 : zmod n) : R) = 1 := begin casesI n, { exact int.cast_one }, show ((1 % (n+1) : ℕ) : R) = 1, cases n, { rw [nat.dvd_one] at h, substI m, apply subsingleton.elim }, rw nat.mod_eq_of_lt, { exact nat.cast_one }, exact nat.lt_of_sub_eq_succ rfl end lemma cast_add (h : m ∣ n) (a b : zmod n) : ((a + b : zmod n) : R) = a + b := begin casesI n, { apply int.cast_add }, simp only [coe_coe], symmetry, erw [fin.coe_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ m], exact dvd_trans h (nat.dvd_sub_mod _), end lemma cast_mul (h : m ∣ n) (a b : zmod n) : ((a * b : zmod n) : R) = a * b := begin casesI n, { apply int.cast_mul }, simp only [coe_coe], symmetry, erw [fin.coe_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ m], exact dvd_trans h (nat.dvd_sub_mod _), end /-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. -/ def cast_hom (h : m ∣ n) (R : Type*) [ring R] [char_p R m] : zmod n →+* R := { to_fun := coe, map_zero' := cast_zero, map_one' := cast_one h, map_add' := cast_add h, map_mul' := cast_mul h } @[simp] lemma cast_hom_apply {h : m ∣ n} (i : zmod n) : cast_hom h R i = i := rfl lemma cast_sub (h : m ∣ n) (a b : zmod n) : ((a - b : zmod n) : R) = a - b := (cast_hom h R).map_sub a b lemma cast_pow (h : m ∣ n) (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := (cast_hom h R).map_pow a k lemma cast_nat_cast (h : m ∣ n) (k : ℕ) : ((k : zmod n) : R) = k := (cast_hom h R).map_nat_cast k lemma cast_int_cast (h : m ∣ n) (k : ℤ) : ((k : zmod n) : R) = k := (cast_hom h R).map_int_cast k end char_dvd section char_eq /-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/ variable [char_p R n] @[simp] lemma cast_one' : ((1 : zmod n) : R) = 1 := cast_one (dvd_refl _) @[simp] lemma cast_add' (a b : zmod n) : ((a + b : zmod n) : R) = a + b := cast_add (dvd_refl _) a b @[simp] lemma cast_mul' (a b : zmod n) : ((a * b : zmod n) : R) = a * b := cast_mul (dvd_refl _) a b @[simp] lemma cast_sub' (a b : zmod n) : ((a - b : zmod n) : R) = a - b := cast_sub (dvd_refl _) a b @[simp] lemma cast_pow' (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := cast_pow (dvd_refl _) a k @[simp, norm_cast] lemma cast_nat_cast' (k : ℕ) : ((k : zmod n) : R) = k := cast_nat_cast (dvd_refl _) k @[simp, norm_cast] lemma cast_int_cast' (k : ℤ) : ((k : zmod n) : R) = k := cast_int_cast (dvd_refl _) k end char_eq end universal_property lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] := char_p.int_coe_eq_int_coe_iff (zmod c) c a b lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] := begin convert zmod.int_coe_eq_int_coe_iff a b c, simp [nat.modeq.modeq_iff_dvd, int.modeq.modeq_iff_dvd], end lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a := begin change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a, rw [zmod.int_coe_eq_int_coe_iff, int.modeq.modeq_zero_iff], end lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a := begin change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a, rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq.modeq_zero_iff], end @[push_cast, simp] lemma cast_mod_int (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) := begin rw zmod.int_coe_eq_int_coe_iff, apply int.modeq.mod_modeq, end @[simp] lemma coe_to_nat (p : ℕ) : ∀ {z : ℤ} (h : 0 ≤ z), (z.to_nat : zmod p) = z | (n : ℕ) h := by simp only [int.cast_coe_nat, int.to_nat_coe_nat] | -[1+n] h := false.elim h lemma val_injective (n : ℕ) [fact (0 < n)] : function.injective (zmod.val : zmod n → ℕ) := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹_› }, assume a b h, ext, exact h end lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n := by rw [← nat.cast_one, val_cast_nat] lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 := by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt ‹1 < n› } lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { apply fin.val_add } end lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n := begin cases n, { rw nat.mod_zero, apply int.nat_abs_mul }, { apply fin.val_mul } end instance nontrivial (n : ℕ) [fact (1 < n)] : nontrivial (zmod n) := ⟨⟨0, 1, assume h, zero_ne_one $ calc 0 = (0 : zmod n).val : by rw val_zero ... = (1 : zmod n).val : congr_arg zmod.val h ... = 1 : val_one n ⟩⟩ /-- The inversion on `zmod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv : Π (n : ℕ), zmod n → zmod n | 0 i := int.sign i | (n+1) i := nat.gcd_a i.val (n+1) instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩ lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0 | 0 := int.sign_zero | (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0, by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl } lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) : a * a⁻¹ = nat.gcd a.val n := begin cases n, { calc a * a⁻¹ = a * int.sign a : rfl ... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat] ... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl }, { set k := n.succ, calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [cast_self, zero_mul, add_zero] ... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) : by { push_cast, rw cast_val, refl } ... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, } end @[simp] lemma cast_mod_nat (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] := begin cases n, { simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], }, { rw [fin.ext_iff, nat.modeq, ← val_cast_nat, ← val_cast_nat], exact iff.rfl, } end lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (x * x⁻¹ : zmod n) = 1 := begin rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h, rw [mul_inv_eq_gcd, val_cast_nat, h, nat.cast_one], end /-- `unit_of_coprime` makes an element of `units (zmod n)` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) := ⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩ @[simp] lemma cast_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (unit_of_coprime x h : zmod n) = x := rfl lemma val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) : nat.coprime (u : zmod n).val n := begin cases n, { rcases int.units_eq_one_or u with rfl|rfl; exact dec_trivial }, apply nat.modeq.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val, have := units.ext_iff.1 (mul_right_inv u), rw [units.coe_one] at this, rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this, rw [← cast_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))], rw [units.coe_mul, val_mul, cast_mod_nat], end @[simp] lemma inv_coe_unit {n : ℕ} (u : units (zmod n)) : (u : zmod n)⁻¹ = (u⁻¹ : units (zmod n)) := begin have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u), rw [← mul_inv_eq_gcd, nat.cast_one] at this, let u' : units (zmod n) := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩, have h : u = u', { apply units.ext, refl }, rw h, refl end lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a * a⁻¹ = 1 := begin rcases h with ⟨u, rfl⟩, rw [inv_coe_unit, u.mul_inv], end lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a⁻¹ * a = 1 := by rw [mul_comm, mul_inv_of_unit a h] /-- Equivalence between the units of `zmod n` and the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/ def units_equiv_coprime {n : ℕ} [fact (0 < n)] : units (zmod n) ≃ {x : zmod n // nat.coprime x.val n} := { to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩, inv_fun := λ x, unit_of_coprime x.1.val x.2, left_inv := λ ⟨_, _, _, _⟩, units.ext (cast_val _), right_inv := λ ⟨_, _⟩, by simp } section totient open_locale nat @[simp] lemma card_units_eq_totient (n : ℕ) [fact (0 < n)] : fintype.card (units (zmod n)) = φ n := calc fintype.card (units (zmod n)) = fintype.card {x : zmod n // x.val.coprime n} : fintype.card_congr zmod.units_equiv_coprime ... = φ n : begin apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val), { intro a, simp [(a : zmod n).val_lt, a.prop.symm] {contextual := tt} }, { intros _ _ _ _ h, rw subtype.ext_iff_val, apply val_injective, exact h, }, { intros b hb, rw [finset.mem_filter, finset.mem_range] at hb, refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩, { let u := unit_of_coprime b hb.2.symm, exact val_coe_unit_coprime u }, { show zmod.val (b : zmod n) = b, rw [val_cast_nat, nat.mod_eq_of_lt hb.1], } } end end totient instance subsingleton_units : subsingleton (units (zmod 2)) := ⟨λ x y, begin cases x with x xi, cases y with y yi, revert x y xi yi, exact dec_trivial end⟩ lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val := begin haveI npos : fact (0 < n) := by { apply (nat.eq_zero_or_pos n).resolve_left, unfreezingI { rintro rfl }, simpa [fact] using hn, }, have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left npos).2 dec_trivial), have hn2' : (n : ℕ) - n / 2 = n / 2 + 1, { conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos]}, rw [← nat.two_mul_odd_div_two hn, two_mul, ← nat.succ_add, nat.add_sub_cancel], }, have hxn : (n : ℕ) - x.val < n, { rw [nat.sub_lt_iff (le_of_lt x.val_lt) (le_refl _), nat.sub_self], rw ← zmod.cast_val x at hx0, exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) }, by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self, ← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.val_lt), zmod.val_cast_nat, nat.mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.val_lt)] } end lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a := λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha, by rwa [← h, ← not_lt, not_iff_self] at this lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] : (-1 : zmod n) ≠ 1 := char_p.neg_one_ne_one (zmod n) n @[simp] lemma neg_eq_self_mod_two : ∀ (a : zmod 2), -a = a := dec_trivial @[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a := begin cases a, { simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] }, { simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] } end @[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0 | 0 a := int.nat_abs_eq_zero | (n+1) a := by { rw fin.ext_iff, exact iff.rfl } lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a := by rw [val_cast_nat, nat.mod_eq_of_lt h] lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n := begin have : ((-a).val + a.val) % n = (n - a.val + a.val) % n, { rw [←val_add, add_left_neg, nat.sub_add_cancel (le_of_lt a.val_lt), nat.mod_self, val_zero], }, calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt) ... = (n - val a) % n : nat.modeq.modeq_add_cancel_right rfl this end lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val := begin rw neg_val', by_cases h : a = 0, { rw [if_pos h, h, val_zero, nat.sub_zero, nat.mod_self] }, rw if_neg h, apply nat.mod_eq_of_lt, apply nat.sub_lt ‹0 < n›, contrapose! h, rwa [nat.le_zero_iff, val_eq_zero] at h, end /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]`. -/ def val_min_abs : Π {n : ℕ}, zmod n → ℤ | 0 x := x | n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n @[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) : val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { refl } end @[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x | 0 x := int.cast_id x | k@(n+1) x := begin rw val_min_abs_def_pos, split_ifs, { rw [int.cast_coe_nat, cast_val] }, { rw [int.cast_sub, int.cast_coe_nat, cast_val, int.cast_coe_nat, cast_self, sub_zero], } end lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 := begin rw zmod.val_min_abs_def_pos, split_ifs with h, { exact h }, have : (x.val - n : ℤ) ≤ 0, { rw [sub_nonpos, int.coe_nat_le], exact le_of_lt x.val_lt, }, rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub], conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul, int.coe_nat_bit0, int.coe_nat_one] }, suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x), { rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring }, norm_cast, calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 : nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _ ... ≤ x.val : by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) } end @[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0 | 0 := by simp only [val_min_abs_def_zero] | (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero] @[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) : x.val_min_abs = 0 ↔ x = 0 := begin cases n, { simp }, split, { simp only [val_min_abs_def_pos, int.coe_nat_succ], split_ifs with h h; assume h0, { apply val_injective, rwa [int.coe_nat_eq_zero] at h0, }, { apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } }, { rintro rfl, rw val_min_abs_zero } end lemma cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a := begin have : (a.val : ℤ) - n ≤ 0, by { erw [sub_nonpos, int.coe_nat_le], exact le_of_lt a.val_lt, }, rw [zmod.val_min_abs_def_pos], split_ifs, { rw [int.nat_abs_of_nat, cast_val] }, { rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub], rw [int.cast_coe_nat, int.cast_coe_nat, cast_self, sub_zero, cast_val], } end @[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) : (-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs := begin cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], }, by_cases ha0 : a = 0, { rw [ha0, neg_zero] }, by_cases haa : -a = a, { rw [haa] }, suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, { rw [val_min_abs_def_pos, val_min_abs_def_pos], rw ← not_le at hpa, simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub (le_of_lt a.val_lt)], split_ifs, all_goals { rw [← int.nat_abs_neg], congr' 1, ring } }, suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, by rwa [nat.mod_add_div] at this, suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a, by rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel, this], cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1, { split, { assume h, apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h), contrapose! haa, rw [← zmod.cast_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add], rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)], rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] }, { rw [hn0, zero_add], exact le_of_lt } }, { rw [hn1, add_comm, nat.succ_le_iff] } end lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n := by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] } lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) : (q : zmod p) ≠ 0 := by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, nat.coprime_primes hp hq] end zmod namespace zmod variables (p : ℕ) [fact p.prime] private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 := begin obtain ⟨k, rfl⟩ := nat_cast_surjective a, apply coe_mul_inv_eq_one, apply nat.coprime.symm, rwa [nat.prime.coprime_iff_not_dvd ‹p.prime›, ← char_p.cast_eq_zero_iff (zmod p)] end /-- Field structure on `zmod p` if `p` is prime. -/ instance : field (zmod p) := { mul_inv_cancel := mul_inv_cancel_aux p, inv_zero := inv_zero p, .. zmod.comm_ring p, .. zmod.has_inv p, .. zmod.nontrivial p } end zmod lemma ring_hom.ext_zmod {n : ℕ} {R : Type*} [semiring R] (f g : (zmod n) →+* R) : f = g := begin ext a, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective a, let φ : ℤ →+* R := f.comp (int.cast_ring_hom (zmod n)), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom (zmod n)), show φ k = ψ k, rw φ.ext_int ψ, end instance zmod.subsingleton_ring_hom {n : ℕ} {R : Type*} [semiring R] : subsingleton ((zmod n) →+* R) := ⟨ring_hom.ext_zmod⟩ lemma zmod.ring_hom_surjective {R : Type*} [comm_ring R] {n : ℕ} (f : R →+* (zmod n)) : function.surjective f := begin intros k, rcases zmod.int_cast_surjective k with ⟨n, rfl⟩, refine ⟨n, f.map_int_cast n⟩ end lemma zmod.ring_hom_eq_of_ker_eq {R : Type*} [comm_ring R] {n : ℕ} (f g : R →+* (zmod n)) (h : f.ker = g.ker) : f = g := by rw [← f.lift_of_surjective_comp (zmod.ring_hom_surjective f) g (le_of_eq h), ring_hom.ext_zmod (f.lift_of_surjective _ _ _) (ring_hom.id _), ring_hom.id_comp]
b31483a18df989705b682f32eaa8ddc95d17f50e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/ordering/basic.lean
881d3822ee66ae6758568f85a094172c051109cf
[]
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
1,268
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.repr import Mathlib.Lean3Lib.init.data.prod import Mathlib.Lean3Lib.init.data.sum.basic universes l u namespace Mathlib inductive ordering where | lt : ordering | eq : ordering | gt : ordering protected instance ordering.has_repr : has_repr ordering := has_repr.mk fun (s : ordering) => sorry namespace ordering def swap : ordering → ordering := sorry def or_else : ordering → ordering → ordering := sorry theorem swap_swap (o : ordering) : swap (swap o) = o := ordering.cases_on o (idRhs (swap (swap lt) = swap (swap lt)) rfl) (idRhs (swap (swap eq) = swap (swap eq)) rfl) (idRhs (swap (swap gt) = swap (swap gt)) rfl) end ordering def cmp_using {α : Type u} (lt : α → α → Prop) [DecidableRel lt] (a : α) (b : α) : ordering := ite (lt a b) ordering.lt (ite (lt b a) ordering.gt ordering.eq) def cmp {α : Type u} [HasLess α] [DecidableRel Less] (a : α) (b : α) : ordering := cmp_using Less a b protected instance ordering.decidable_eq : DecidableEq ordering := fun (a b : ordering) => sorry
cfa1df1d0462c5c1bd4bcd850f72eeae76462581
7c2dd01406c42053207061adb11703dc7ce0b5e5
/src/exercises/08_limits_negation.lean
96e508480cff248fbebf003e9b0d565c5974e595
[ "Apache-2.0" ]
permissive
leanprover-community/tutorials
50ec79564cbf2ad1afd1ac43d8ee3c592c2883a8
79a6872a755c4ae0c2aca57e1adfdac38b1d8bb1
refs/heads/master
1,687,466,144,386
1,672,061,276,000
1,672,061,276,000
189,169,918
186
81
Apache-2.0
1,686,350,300,000
1,559,113,678,000
Lean
UTF-8
Lean
false
false
3,795
lean
import tuto_lib section /- The first part of this file makes sure you can negate quantified statements in your head without the help of `push_neg`. You need to complete the statement and then use the `check_me` tactic to check your answer. This tactic exists only for those exercises, it mostly calls `push_neg` and then cleans up a bit. def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε -/ -- In this section, u denotes a sequence of real numbers -- f is a function from ℝ to ℝ -- x₀ and l are real numbers variables (u : ℕ → ℝ) (f : ℝ → ℝ) (x₀ l : ℝ) /- Negation of "u tends to l" -/ -- 0062 example : ¬ (∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε) ↔ sorry := begin sorry end /- Negation of "f is continuous at x₀" -/ -- 0063 example : ¬ (∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - f x₀| ≤ ε) ↔ sorry := begin sorry end /- In the next exercise, we need to keep in mind that `∀ x x', ...` is the abbreviation of `∀ x, ∀ x', ... `. Also, `∃ x x', ...` is the abbreviation of `∃ x, ∃ x', ...`. -/ /- Negation of "f is uniformly continuous on ℝ" -/ -- 0064 example : ¬ (∀ ε > 0, ∃ δ > 0, ∀ x x', |x' - x| ≤ δ → |f x' - f x| ≤ ε) ↔ sorry := begin sorry end /- Negation of "f is sequentially continuous at x₀" -/ -- 0065 example : ¬ (∀ u : ℕ → ℝ, (∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - x₀| ≤ ε) → (∀ ε > 0, ∃ N, ∀ n ≥ N, |(f ∘ u) n - f x₀| ≤ ε)) ↔ sorry := begin sorry end end /- We now turn to elementary applications of negations to limits of sequences. Remember that `linarith` can find easy numerical contradictions. Also recall the following lemmas: abs_le {x y : ℝ} : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q /-- The sequence `u` tends to `+∞`. -/ def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A -/ -- 0066 example {u : ℕ → ℝ} : tendsto_infinity u → ∀ l, ¬ seq_limit u l := begin sorry end def nondecreasing_seq (u : ℕ → ℝ) := ∀ n m, n ≤ m → u n ≤ u m -- 0067 example (u : ℕ → ℝ) (l : ℝ) (h : seq_limit u l) (h' : nondecreasing_seq u) : ∀ n, u n ≤ l := begin sorry end /- In the following exercises, `A : set ℝ` means that A is a set of real numbers. We can use the usual notation x ∈ A. The notation `∀ x ∈ A, ...` is the abbreviation of `∀ x, x ∈ A → ... ` The notation `∃ x ∈ A, ...` is the abbreviation of `∃ x, x ∈ A ∧ ... `. More precisely it is the abbreviation of `∃ x (H : x ∈ A), ...` which is Lean's strange way of saying `∃ x, x ∈ A ∧ ... `. You can convert between these forms using the lemma exists_prop {p q : Prop} : (∃ (h : p), q) ↔ p ∧ q We'll work with upper bounds and supremums. Again we'll introduce specialized definitions for the sake of exercises, but mathlib has more general versions. def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y Remark: one can easily show that a set of real numbers has at most one sup, but we won't need this. -/ -- 0068 example {A : set ℝ} {x : ℝ} (hx : is_sup A x) : ∀ y, y < x → ∃ a ∈ A, y < a := begin sorry end /- Let's do a variation on an example from file 07 that will be useful in the last exercise below. -/ -- 0069 lemma le_of_le_add_all' {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin sorry end -- 0070 example {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x) (ineg : ∀ n, u n ≤ y) : x ≤ y := begin sorry end
6b736a01261510929ab24bcc039d790f44e49ab4
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/tactic/field_simp.lean
bef9be5a60453bf0efb66e57e74ed3bda7d02083
[ "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,189
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 tactic.interactive import tactic.norm_num /-! # `field_simp` tactic Tactic to clear denominators in algebraic expressions, based on `simp` with a specific simpset. -/ namespace tactic /-- Try to prove a goal of the form `x ≠ 0` by calling `assumption`, or `norm_num1` if `x` is a numeral. -/ meta def field_simp.ne_zero : tactic unit := do goal ← tactic.target, match goal with | `(%%e ≠ 0) := assumption <|> do n ← e.to_rat, `[norm_num1] | _ := tactic.fail "goal should be of the form `x ≠ 0`" end namespace interactive setup_tactic_parser /-- The goal of `field_simp` is to reduce an expression in a field to an expression of the form `n / d` where neither `n` nor `d` contains any division symbol, just using the simplifier (with a carefully crafted simpset named `field_simps`) to reduce the number of division symbols whenever possible by iterating the following steps: - write an inverse as a division - in any product, move the division to the right - if there are several divisions in a product, group them together at the end and write them as a single division - reduce a sum to a common denominator If the goal is an equality, this simpset will also clear the denominators, so that the proof can normally be concluded by an application of `ring` or `ring_exp`. `field_simp [hx, hy]` is a short form for `simp [-one_div, -mul_eq_zero, hx, hy] with field_simps {discharger := [field_simp.ne_zero]}` Note that this naive algorithm will not try to detect common factors in denominators to reduce the complexity of the resulting expression. Instead, it relies on the ability of `ring` to handle complicated expressions in the next step. As always with the simplifier, reduction steps will only be applied if the preconditions of the lemmas can be checked. This means that proofs that denominators are nonzero should be included. The fact that a product is nonzero when all factors are, and that a power of a nonzero number is nonzero, are included in the simpset, but more complicated assertions (especially dealing with sums) should be given explicitly. If your expression is not completely reduced by the simplifier invocation, check the denominators of the resulting expression and provide proofs that they are nonzero to enable further progress. To check that denominators are nonzero, `field_simp` will look for facts in the context, and will try to apply `norm_num` to close numerical goals. The invocation of `field_simp` removes the lemma `one_div` from the simpset, as this lemma works against the algorithm explained above. It also removes `mul_eq_zero : x * y = 0 ↔ x = 0 ∨ y = 0`, as `norm_num` can not work on disjunctions to close goals of the form `24 ≠ 0`, and replaces it with `mul_ne_zero : x ≠ 0 → y ≠ 0 → x * y ≠ 0` creating two goals instead of a disjunction. For example, ```lean example (a b c d x y : ℂ) (hx : x ≠ 0) (hy : y ≠ 0) : a + b / x + c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x + c) / x) := begin field_simp, ring end ``` See also the `cancel_denoms` tactic, which tries to do a similar simplification for expressions that have numerals in denominators. The tactics are not related: `cancel_denoms` will only handle numeric denominators, and will try to entirely remove (numeric) division from the expression by multiplying by a factor. -/ meta def field_simp (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : simp_config_ext := {discharger := field_simp.ne_zero}) : tactic unit := let attr_names := `field_simps :: attr_names, hs := simp_arg_type.except `one_div :: simp_arg_type.except `mul_eq_zero :: hs in propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat >> skip) add_tactic_doc { name := "field_simp", category := doc_category.tactic, decl_names := [`tactic.interactive.field_simp], tags := ["simplification", "arithmetic"] } end interactive end tactic
d19d2a51855a80f0fa95eaea9b3cce2194f92306
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/linear_algebra/pi_tensor_product.lean
9322f64851225cda69dfa28477fcea1f8d460c32
[ "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
21,404
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis, Eric Wieser -/ import group_theory.congruence import linear_algebra.multilinear /-! # Tensor product of an indexed family of modules over commutative semirings We define the tensor product of an indexed family `s : ι → Type*` of modules over commutative semirings. We denote this space by `⨂[R] i, s i` and define it as `free_add_monoid (R × Π i, s i)` quotiented by the appropriate equivalence relation. The treatment follows very closely that of the binary tensor product in `linear_algebra/tensor_product.lean`. ## Main definitions * `pi_tensor_product R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. * `tprod R f` with `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`. This is bundled as a multilinear map from `Π i, s i` to `⨂[R] i, s i`. * `lift_add_hom` constructs an `add_monoid_hom` from `(⨂[R] i, s i)` to some space `F` from a function `φ : (R × Π i, s i) → F` with the appropriate properties. * `lift φ` with `φ : multilinear_map R s E` is the corresponding linear map `(⨂[R] i, s i) →ₗ[R] E`. This is bundled as a linear equivalence. * `pi_tensor_product.reindex e` re-indexes the components of `⨂[R] i : ι, M` along `e : ι ≃ ι₂`. * `pi_tensor_product.tmul_equiv` equivalence between a `tensor_product` of `pi_tensor_product`s and a single `pi_tensor_product`. ## Notations * `⨂[R] i, s i` is defined as localized notation in locale `tensor_product` * `⨂ₜ[R] i, f i` with `f : Π i, f i` is defined globally as the tensor product of all the `f i`'s. ## Implementation notes * We define it via `free_add_monoid (R × Π i, s i)` with the `R` representing a "hidden" tensor factor, rather than `free_add_monoid (Π i, s i)` to ensure that, if `ι` is an empty type, the space is isomorphic to the base ring `R`. * We have not restricted the index type `ι` to be a `fintype`, as nothing we do here strictly requires it. However, problems may arise in the case where `ι` is infinite; use at your own caution. ## TODO * Define tensor powers, symmetric subspace, etc. * API for the various ways `ι` can be split into subsets; connect this with the binary tensor product. * Include connection with holors. * Port more of the API from the binary tensor product over to this case. ## Tags multilinear, tensor, tensor product -/ open function section semiring variables {ι ι₂ ι₃ : Type*} [decidable_eq ι] [decidable_eq ι₂] [decidable_eq ι₃] variables {R : Type*} [comm_semiring R] variables {R' : Type*} [comm_semiring R'] [algebra R' R] variables {s : ι → Type*} [∀ i, add_comm_monoid (s i)] [∀ i, module R (s i)] variables {M : Type*} [add_comm_monoid M] [module R M] variables {E : Type*} [add_comm_monoid E] [module R E] variables {F : Type*} [add_comm_monoid F] namespace pi_tensor_product include R variables (R) (s) /-- The relation on `free_add_monoid (R × Π i, s i)` that generates a congruence whose quotient is the tensor product. -/ inductive eqv : free_add_monoid (R × Π i, s i) → free_add_monoid (R × Π i, s i) → Prop | of_zero : ∀ (r : R) (f : Π i, s i) (i : ι) (hf : f i = 0), eqv (free_add_monoid.of (r, f)) 0 | of_zero_scalar : ∀ (f : Π i, s i), eqv (free_add_monoid.of (0, f)) 0 | of_add : ∀ (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i), eqv (free_add_monoid.of (r, update f i m₁) + free_add_monoid.of (r, update f i m₂)) (free_add_monoid.of (r, update f i (m₁ + m₂))) | of_add_scalar : ∀ (r r' : R) (f : Π i, s i), eqv (free_add_monoid.of (r, f) + free_add_monoid.of (r', f)) (free_add_monoid.of (r + r', f)) | of_smul : ∀ (r : R) (f : Π i, s i) (i : ι) (r' : R), eqv (free_add_monoid.of (r, update f i (r' • (f i)))) (free_add_monoid.of (r' * r, f)) | add_comm : ∀ x y, eqv (x + y) (y + x) end pi_tensor_product variables (R) (s) /-- `pi_tensor_product R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. -/ def pi_tensor_product : Type* := (add_con_gen (pi_tensor_product.eqv R s)).quotient variables {R} /- This enables the notation `⨂[R] i : ι, s i` for the pi tensor product, given `s : ι → Type*`. -/ localized "notation `⨂[`:100 R `] ` binders `, ` r:(scoped:67 f, pi_tensor_product R f) := r" in tensor_product open_locale tensor_product namespace pi_tensor_product section module instance : add_comm_monoid (⨂[R] i, s i) := { add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.add_comm _ _, .. (add_con_gen (pi_tensor_product.eqv R s)).add_monoid } instance : inhabited (⨂[R] i, s i) := ⟨0⟩ variables (R) {s} /-- `tprod_coeff R r f` with `r : R` and `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`, multiplied by the coefficient `r`. Note that this is meant as an auxiliary definition for this file alone, and that one should use `tprod` defined below for most purposes. -/ def tprod_coeff (r : R) (f : Π i, s i) : ⨂[R] i, s i := add_con.mk' _ $ free_add_monoid.of (r, f) variables {R} lemma zero_tprod_coeff (f : Π i, s i) : tprod_coeff R 0 f = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_scalar _ lemma zero_tprod_coeff' (z : R) (f : Π i, s i) (i : ι) (hf: f i = 0) : tprod_coeff R z f = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero _ _ i hf lemma add_tprod_coeff (z : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i) : tprod_coeff R z (update f i m₁) + tprod_coeff R z (update f i m₂) = tprod_coeff R z (update f i (m₁ + m₂)) := quotient.sound' $ add_con_gen.rel.of _ _ (eqv.of_add z f i m₁ m₂) lemma add_tprod_coeff' (z₁ z₂ : R) (f : Π i, s i) : tprod_coeff R z₁ f + tprod_coeff R z₂ f = tprod_coeff R (z₁ + z₂) f := quotient.sound' $ add_con_gen.rel.of _ _ (eqv.of_add_scalar z₁ z₂ f) lemma smul_tprod_coeff_aux (z : R) (f : Π i, s i) (i : ι) (r : R) : tprod_coeff R z (update f i (r • f i)) = tprod_coeff R (r * z) f := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _ _ lemma smul_tprod_coeff (z : R) (f : Π i, s i) (i : ι) (r : R') [module R' (s i)] [is_scalar_tower R' R (s i)] : tprod_coeff R z (update f i (r • f i)) = tprod_coeff R (r • z) f := begin have h₁ : r • z = (r • (1 : R)) * z := by simp, have h₂ : r • (f i) = (r • (1 : R)) • f i := by simp, rw [h₁, h₂], exact smul_tprod_coeff_aux z f i _, end /-- Construct an `add_monoid_hom` from `(⨂[R] i, s i)` to some space `F` from a function `φ : (R × Π i, s i) → F` with the appropriate properties. -/ def lift_add_hom (φ : (R × Π i, s i) → F) (C0 : ∀ (r : R) (f : Π i, s i) (i : ι) (hf : f i = 0), φ (r, f) = 0) (C0' : ∀ (f : Π i, s i), φ (0, f) = 0) (C_add : ∀ (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i), φ (r, update f i m₁) + φ (r, update f i m₂) = φ (r, update f i (m₁ + m₂))) (C_add_scalar : ∀ (r r' : R) (f : Π i, s i), φ (r , f) + φ (r', f) = φ (r + r', f)) (C_smul : ∀ (r : R) (f : Π i, s i) (i : ι) (r' : R), φ (r, update f i (r' • (f i))) = φ (r' * r, f)) : (⨂[R] i, s i) →+ F := (add_con_gen (pi_tensor_product.eqv R s)).lift (free_add_monoid.lift φ) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero r' f i hf) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C0 r' f i hf] | _, _, (eqv.of_zero_scalar f) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C0'] | _, _, (eqv.of_add z f i m₁ m₂) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C_add] | _, _, (eqv.of_add_scalar z₁ z₂ f) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C_add_scalar] | _, _, (eqv.of_smul z f i r') := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C_smul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance has_scalar' : has_scalar R' (⨂[R] i, s i) := ⟨λ r, lift_add_hom (λ f : R × Π i, s i, tprod_coeff R (r • f.1) f.2) (λ r' f i hf, by simp_rw [zero_tprod_coeff' _ f i hf]) (λ f, by simp [zero_tprod_coeff]) (λ r' f i m₁ m₂, by simp [add_tprod_coeff]) (λ r' r'' f, by simp [add_tprod_coeff', mul_add]) (λ z f i r', by simp [smul_tprod_coeff])⟩ instance : has_scalar R (⨂[R] i, s i) := pi_tensor_product.has_scalar' lemma smul_tprod_coeff' (r : R') (z : R) (f : Π i, s i) : r • (tprod_coeff R z f) = tprod_coeff R (r • z) f := rfl protected theorem smul_add (r : R') (x y : ⨂[R] i, s i) : r • (x + y) = r • x + r • y := add_monoid_hom.map_add _ _ _ @[elab_as_eliminator] protected theorem induction_on' {C : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i) (C1 : ∀ {r : R} {f : Π i, s i}, C (tprod_coeff R r f)) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := begin have C0 : C 0, { have h₁ := @C1 0 0, rwa [zero_tprod_coeff] at h₁ }, refine add_con.induction_on z (λ x, free_add_monoid.rec_on x C0 _), simp_rw add_con.coe_add, refine λ f y ih, Cp _ ih, convert @C1 f.1 f.2, simp only [prod.mk.eta], end -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance module' : module R' (⨂[R] i, s i) := { smul := (•), smul_add := λ r x y, pi_tensor_product.smul_add r x y, mul_smul := λ r r' x, begin refine pi_tensor_product.induction_on' x _ _, { intros r'' f, simp [smul_tprod_coeff', smul_smul] }, { intros x y ihx ihy, simp [pi_tensor_product.smul_add, ihx, ihy] } end, one_smul := λ x, pi_tensor_product.induction_on' x (λ f, by simp [smul_tprod_coeff' _ _]) (λ z y ihz ihy, by simp_rw [pi_tensor_product.smul_add, ihz, ihy]), add_smul := λ r r' x, begin refine pi_tensor_product.induction_on' x _ _, { intros r f, simp [smul_tprod_coeff' _ _, add_smul, add_tprod_coeff'] }, { intros x y ihx ihy, simp [pi_tensor_product.smul_add, ihx, ihy, add_add_add_comm] } end, smul_zero := λ r, add_monoid_hom.map_zero _, zero_smul := λ x, begin refine pi_tensor_product.induction_on' x _ _, { intros r f, simp_rw [smul_tprod_coeff' _ _, zero_smul], exact zero_tprod_coeff _ }, { intros x y ihx ihy, rw [pi_tensor_product.smul_add, ihx, ihy, add_zero] }, end } instance : module R' (⨂[R] i, s i) := pi_tensor_product.module' variables {R} variables (R) /-- The canonical `multilinear_map R s (⨂[R] i, s i)`. -/ def tprod : multilinear_map R s (⨂[R] i, s i) := { to_fun := tprod_coeff R 1, map_add' := λ f i x y, (add_tprod_coeff (1 : R) f i x y).symm, map_smul' := λ f i r x, by simp_rw [smul_tprod_coeff', ←smul_tprod_coeff (1 : R) _ i, update_idem, update_same] } variables {R} notation `⨂ₜ[`:100 R`] ` binders `, ` r:(scoped:67 f, tprod R f) := r @[simp] lemma tprod_coeff_eq_smul_tprod (z : R) (f : Π i, s i) : tprod_coeff R z f = z • tprod R f := begin have : z = z • (1 : R) := by simp only [mul_one, algebra.id.smul_eq_mul], conv_lhs { rw this }, rw ←smul_tprod_coeff', refl, end @[elab_as_eliminator] protected theorem induction_on {C : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i) (C1 : ∀ {r : R} {f : Π i, s i}, C (r • (tprod R f))) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := begin simp_rw ←tprod_coeff_eq_smul_tprod at C1, exact pi_tensor_product.induction_on' z @C1 @Cp, end @[ext] theorem ext {φ₁ φ₂ : (⨂[R] i, s i) →ₗ[R] E} (H : φ₁.comp_multilinear_map (tprod R) = φ₂.comp_multilinear_map (tprod R)) : φ₁ = φ₂ := begin refine linear_map.ext _, refine λ z, (pi_tensor_product.induction_on' z _ (λ x y hx hy, by rw [φ₁.map_add, φ₂.map_add, hx, hy])), { intros r f, rw [tprod_coeff_eq_smul_tprod, φ₁.map_smul, φ₂.map_smul], apply _root_.congr_arg, exact multilinear_map.congr_fun H f } end end module section multilinear open multilinear_map variables {s} /-- Auxiliary function to constructing a linear map `(⨂[R] i, s i) → E` given a `multilinear map R s E` with the property that its composition with the canonical `multilinear_map R s (⨂[R] i, s i)` is the given multilinear map. -/ def lift_aux (φ : multilinear_map R s E) : (⨂[R] i, s i) →+ E := lift_add_hom (λ (p : R × Π i, s i), p.1 • (φ p.2)) (λ z f i hf, by rw [map_coord_zero φ i hf, smul_zero]) (λ f, by rw [zero_smul]) (λ z f i m₁ m₂, by rw [←smul_add, φ.map_add]) (λ z₁ z₂ f, by rw [←add_smul]) (λ z f i r, by simp [φ.map_smul, smul_smul, mul_comm]) lemma lift_aux_tprod (φ : multilinear_map R s E) (f : Π i, s i) : lift_aux φ (tprod R f) = φ f := by simp only [lift_aux, lift_add_hom, tprod, multilinear_map.coe_mk, tprod_coeff, free_add_monoid.lift_eval_of, one_smul, add_con.lift_mk'] lemma lift_aux_tprod_coeff (φ : multilinear_map R s E) (z : R) (f : Π i, s i) : lift_aux φ (tprod_coeff R z f) = z • φ f := by simp [lift_aux, lift_add_hom, tprod_coeff, free_add_monoid.lift_eval_of] lemma lift_aux.smul {φ : multilinear_map R s E} (r : R) (x : ⨂[R] i, s i) : lift_aux φ (r • x) = r • lift_aux φ x := begin refine pi_tensor_product.induction_on' x _ _, { intros z f, rw [smul_tprod_coeff' r z f, lift_aux_tprod_coeff, lift_aux_tprod_coeff, smul_assoc] }, { intros z y ihz ihy, rw [smul_add, (lift_aux φ).map_add, ihz, ihy, (lift_aux φ).map_add, smul_add] } end /-- Constructing a linear map `(⨂[R] i, s i) → E` given a `multilinear_map R s E` with the property that its composition with the canonical `multilinear_map R s E` is the given multilinear map `φ`. -/ def lift : (multilinear_map R s E) ≃ₗ[R] ((⨂[R] i, s i) →ₗ[R] E) := { to_fun := λ φ, { map_smul' := lift_aux.smul, .. lift_aux φ }, inv_fun := λ φ', φ'.comp_multilinear_map (tprod R), left_inv := λ φ, by { ext, simp [lift_aux_tprod, linear_map.comp_multilinear_map] }, right_inv := λ φ, by { ext, simp [lift_aux_tprod] }, map_add' := λ φ₁ φ₂, by { ext, simp [lift_aux_tprod] }, map_smul' := λ r φ₂, by { ext, simp [lift_aux_tprod] } } variables {φ : multilinear_map R s E} @[simp] lemma lift.tprod (f : Π i, s i) : lift φ (tprod R f) = φ f := lift_aux_tprod φ f theorem lift.unique' {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : φ'.comp_multilinear_map (tprod R) = φ) : φ' = lift φ := ext $ H.symm ▸ (lift.symm_apply_apply φ).symm theorem lift.unique {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : ∀ f, φ' (tprod R f) = φ f) : φ' = lift φ := lift.unique' (multilinear_map.ext H) @[simp] theorem lift_symm (φ' : (⨂[R] i, s i) →ₗ[R] E) : lift.symm φ' = φ'.comp_multilinear_map (tprod R) := rfl @[simp] theorem lift_tprod : lift (tprod R : multilinear_map R s _) = linear_map.id := eq.symm $ lift.unique' rfl section variables (R M) /-- Re-index the components of the tensor power by `e`. For simplicity, this is defined only for homogeneously- (rather than dependently-) typed components. -/ def reindex (e : ι ≃ ι₂) : ⨂[R] i : ι, M ≃ₗ[R] ⨂[R] i : ι₂, M := linear_equiv.of_linear (((lift.symm ≪≫ₗ (multilinear_map.dom_dom_congr_linear_equiv M (⨂[R] i : ι₂, M) R R e.symm)) ≪≫ₗ lift) (linear_map.id)) (((lift.symm ≪≫ₗ (multilinear_map.dom_dom_congr_linear_equiv M (⨂[R] i : ι, M) R R e)) ≪≫ₗ lift) (linear_map.id)) (by { ext, simp }) (by { ext, simp }) end @[simp] lemma reindex_tprod (e : ι ≃ ι₂) (f : Π i, M) : reindex R M e (tprod R f) = tprod R (λ i, f (e.symm i)) := lift.tprod f @[simp] lemma reindex_comp_tprod (e : ι ≃ ι₂) : (reindex R M e : ⨂[R] i : ι, M →ₗ[R] ⨂[R] i : ι₂, M).comp_multilinear_map (tprod R) = (tprod R : multilinear_map R (λ i, M) _).dom_dom_congr e.symm := multilinear_map.ext $ reindex_tprod e @[simp] lemma lift_comp_reindex (e : ι ≃ ι₂) (φ : multilinear_map R (λ _ : ι₂, M) E) : (lift φ) ∘ₗ ↑(reindex R M e) = lift (φ.dom_dom_congr e.symm) := by { ext, simp, } @[simp] lemma lift_reindex (e : ι ≃ ι₂) (φ : multilinear_map R (λ _, M) E) (x : ⨂[R] i, M) : lift φ (reindex R M e x) = lift (φ.dom_dom_congr e.symm) x := linear_map.congr_fun (lift_comp_reindex e φ) x @[simp] lemma reindex_trans (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) : (reindex R M e).trans (reindex R M e') = reindex R M (e.trans e') := begin apply linear_equiv.to_linear_map_injective, ext f, simp only [linear_equiv.trans_apply, linear_equiv.coe_coe, reindex_tprod, linear_map.coe_comp_multilinear_map, function.comp_app, multilinear_map.dom_dom_congr_apply, reindex_comp_tprod], congr, end @[simp] lemma reindex_symm (e : ι ≃ ι₂) : (reindex R M e).symm = reindex R M e.symm := rfl @[simp] lemma reindex_refl : reindex R M (equiv.refl ι) = linear_equiv.refl R _ := begin apply linear_equiv.to_linear_map_injective, ext1, rw [reindex_comp_tprod, linear_equiv.refl_to_linear_map, equiv.refl_symm], refl, end /-- The tensor product over an empty set of indices is isomorphic to the base ring -/ def pempty_equiv : ⨂[R] i : pempty, M ≃ₗ[R] R := { to_fun := lift ⟨λ (_ : pempty → M), (1 : R), λ v, pempty.elim, λ v, pempty.elim⟩, inv_fun := λ r, r • tprod R (λ v, pempty.elim v), left_inv := λ x, by { apply x.induction_on, { intros r f, have : f = (λ i, pempty.elim i) := funext (λ i, pempty.elim i), simp [this], }, { simp only, intros x y hx hy, simp [add_smul, hx, hy] }}, right_inv := λ t, by simp only [mul_one, algebra.id.smul_eq_mul, multilinear_map.coe_mk, linear_map.map_smul, pi_tensor_product.lift.tprod], map_add' := linear_map.map_add _, map_smul' := linear_map.map_smul _, } section tmul /-- Collapse a `tensor_product` of `pi_tensor_product`s. -/ private def tmul : (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) →ₗ[R] ⨂[R] i : ι ⊕ ι₂, M := tensor_product.lift { to_fun := λ a, pi_tensor_product.lift $ pi_tensor_product.lift (multilinear_map.curry_sum_equiv R _ _ M _ (tprod R)) a, map_add' := λ a b, by simp only [linear_equiv.map_add, linear_map.map_add], map_smul' := λ r a, by simp only [linear_equiv.map_smul, linear_map.map_smul], } private lemma tmul_apply (a : ι → M) (b : ι₂ → M) : tmul ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, sum.elim a b i := begin erw [tensor_product.lift.tmul, pi_tensor_product.lift.tprod, pi_tensor_product.lift.tprod], refl end /-- Expand `pi_tensor_product` into a `tensor_product` of two factors. -/ private def tmul_symm : ⨂[R] i : ι ⊕ ι₂, M →ₗ[R] (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) := -- by using tactic mode, we avoid the need for a lot of `@`s and `_`s pi_tensor_product.lift $ by apply multilinear_map.dom_coprod; [exact tprod R, exact tprod R] private lemma tmul_symm_apply (a : ι ⊕ ι₂ → M) : tmul_symm (⨂ₜ[R] i, a i) = (⨂ₜ[R] i, a (sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (sum.inr i)) := pi_tensor_product.lift.tprod _ variables (R M) local attribute [ext] tensor_product.ext /-- Equivalence between a `tensor_product` of `pi_tensor_product`s and a single `pi_tensor_product` indexed by a `sum` type. For simplicity, this is defined only for homogeneously- (rather than dependently-) typed components. -/ def tmul_equiv : (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) ≃ₗ[R] ⨂[R] i : ι ⊕ ι₂, M := linear_equiv.of_linear tmul tmul_symm (by { ext x, show tmul (tmul_symm (tprod R x)) = tprod R x, -- Speed up the call to `simp`. simp only [tmul_symm_apply, tmul_apply, sum.elim_comp_inl_inr], }) (by { ext x y, show tmul_symm (tmul (tprod R x ⊗ₜ[R] tprod R y)) = tprod R x ⊗ₜ[R] tprod R y, simp only [tmul_apply, tmul_symm_apply, sum.elim_inl, sum.elim_inr], }) @[simp] lemma tmul_equiv_apply (a : ι → M) (b : ι₂ → M) : tmul_equiv R M ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, sum.elim a b i := tmul_apply a b @[simp] lemma tmul_equiv_symm_apply (a : ι ⊕ ι₂ → M) : (tmul_equiv R M).symm (⨂ₜ[R] i, a i) = (⨂ₜ[R] i, a (sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (sum.inr i)) := tmul_symm_apply a end tmul end multilinear end pi_tensor_product end semiring section ring namespace pi_tensor_product open pi_tensor_product open_locale tensor_product variables {ι : Type*} [decidable_eq ι] {R : Type*} [comm_ring R] variables {s : ι → Type*} [∀ i, add_comm_group (s i)] [∀ i, module R (s i)] /- Unlike for the binary tensor product, we require `R` to be a `comm_ring` here, otherwise this is false in the case where `ι` is empty. -/ instance : add_comm_group (⨂[R] i, s i) := module.add_comm_monoid_to_add_comm_group R end pi_tensor_product end ring
1f56b1345894f68b6c37e1ca8377b3fbc1beb3cf
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/Data/Fin.lean
4e571c0f4b2c14100ccf28bb9dcabd0bea78560b
[ "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
198
lean
/- Copyright (c) 2017 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.Fin.Basic
8dbb05845e6d62db90267d166de7fd7d6e51cf90
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/free_module/pid.lean
597e4628030dfd3b3c737f68b6520850086532df
[ "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
25,546
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import linear_algebra.dimension import ring_theory.principal_ideal_domain import ring_theory.finiteness /-! # Free modules over PID A free `R`-module `M` is a module with a basis over `R`, equivalently it is an `R`-module linearly equivalent to `ι →₀ R` for some `ι`. This file proves a submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain (PID), i.e. we have instances `[is_domain R] [is_principal_ideal_ring R]`. We express "free `R`-module of finite rank" as a module `M` which has a basis `b : ι → R`, where `ι` is a `fintype`. We call the cardinality of `ι` the rank of `M` in this file; it would be equal to `finrank R M` if `R` is a field and `M` is a vector space. ## Main results In this section, `M` is a free and finitely generated `R`-module, and `N` is a submodule of `M`. - `submodule.induction_on_rank`: if `P` holds for `⊥ : submodule R M` and if `P N` follows from `P N'` for all `N'` that are of lower rank, then `P` holds on all submodules - `submodule.exists_basis_of_pid`: if `R` is a PID, then `N : submodule R M` is free and finitely generated. This is the first part of the structure theorem for modules. - `submodule.smith_normal_form`: if `R` is a PID, then `M` has a basis `bM` and `N` has a basis `bN` such that `bN i = a i • bM i`. Equivalently, a linear map `f : M →ₗ M` with `range f = N` can be written as a matrix in Smith normal form, a diagonal matrix with the coefficients `a i` along the diagonal. ## Tags free module, finitely generated module, rank, structure theorem -/ open_locale big_operators universes u v section ring variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] variables {ι : Type*} (b : basis ι R M) open submodule.is_principal submodule lemma eq_bot_of_generator_maximal_map_eq_zero (b : basis ι R M) {N : submodule R M} {ϕ : M →ₗ[R] R} (hϕ : ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ) [(N.map ϕ).is_principal] (hgen : generator (N.map ϕ) = (0 : R)) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine b.ext_elem (λ i, _), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], exact (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr) bot_le) _ ⟨x, hx, rfl⟩ end lemma eq_bot_of_generator_maximal_submodule_image_eq_zero {N O : submodule R M} (b : basis ι R O) (hNO : N ≤ O) {ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N) [(ϕ.submodule_image N).is_principal] (hgen : generator (ϕ.submodule_image N) = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine congr_arg coe (show (⟨x, hNO hx⟩ : O) = 0, from b.ext_elem (λ i, _)), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], refine (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr) bot_le) _ _, exact (linear_map.mem_submodule_image_of_le hNO).mpr ⟨x, hx, rfl⟩ end end ring section is_domain variables {ι : Type*} {R : Type*} [comm_ring R] [is_domain R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} open submodule.is_principal set submodule lemma dvd_generator_iff {I : ideal R} [I.is_principal] {x : R} (hx : x ∈ I) : x ∣ generator I ↔ I = ideal.span {x} := begin conv_rhs { rw [← span_singleton_generator I] }, erw [ideal.span_singleton_eq_span_singleton, ← dvd_dvd_iff_associated, ← mem_iff_generator_dvd], exact ⟨λ h, ⟨hx, h⟩, λ h, h.2⟩ end end is_domain section principal_ideal_domain open submodule.is_principal set submodule variables {ι : Type*} {R : Type*} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} open submodule.is_principal lemma generator_maximal_submodule_image_dvd {N O : submodule R M} (hNO : N ≤ O) {ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N) [(ϕ.submodule_image N).is_principal] (y : M) (yN : y ∈ N) (ϕy_eq : ϕ ⟨y, hNO yN⟩ = generator (ϕ.submodule_image N)) (ψ : O →ₗ[R] R) : generator (ϕ.submodule_image N) ∣ ψ ⟨y, hNO yN⟩ := begin let a : R := generator (ϕ.submodule_image N), let d : R := is_principal.generator (submodule.span R {a, ψ ⟨y, hNO yN⟩}), have d_dvd_left : d ∣ a := (mem_iff_generator_dvd _).mp (subset_span (mem_insert _ _)), have d_dvd_right : d ∣ ψ ⟨y, hNO yN⟩ := (mem_iff_generator_dvd _).mp (subset_span (mem_insert_of_mem _ (mem_singleton _))), refine dvd_trans _ d_dvd_right, rw [dvd_generator_iff, ideal.span, ← span_singleton_generator (submodule.span R {a, ψ ⟨y, hNO yN⟩})], obtain ⟨r₁, r₂, d_eq⟩ : ∃ r₁ r₂ : R, d = r₁ * a + r₂ * ψ ⟨y, hNO yN⟩, { obtain ⟨r₁, r₂', hr₂', hr₁⟩ := mem_span_insert.mp (is_principal.generator_mem (submodule.span R {a, ψ ⟨y, hNO yN⟩})), obtain ⟨r₂, rfl⟩ := mem_span_singleton.mp hr₂', exact ⟨r₁, r₂, hr₁⟩ }, let ψ' : O →ₗ[R] R := r₁ • ϕ + r₂ • ψ, have : span R {d} ≤ ψ'.submodule_image N, { rw [span_le, singleton_subset_iff, set_like.mem_coe, linear_map.mem_submodule_image_of_le hNO], refine ⟨y, yN, _⟩, change r₁ * ϕ ⟨y, hNO yN⟩ + r₂ * ψ ⟨y, hNO yN⟩ = d, rw [d_eq, ϕy_eq] }, refine le_antisymm (this.trans (le_of_eq _)) (ideal.span_singleton_le_span_singleton.mpr d_dvd_left), rw span_singleton_generator, refine hϕ ψ' (le_trans _ this), rw [← span_singleton_generator (ϕ.submodule_image N)], exact ideal.span_singleton_le_span_singleton.mpr d_dvd_left, { exact subset_span (mem_insert _ _) } end /-- The induction hypothesis of `submodule.basis_of_pid` and `submodule.smith_normal_form`. Basically, it says: let `N ≤ M` be a pair of submodules, then we can find a pair of submodules `N' ≤ M'` of strictly smaller rank, whose basis we can extend to get a basis of `N` and `M`. Moreover, if the basis for `M'` is up to scalars a basis for `N'`, then the basis we find for `M` is up to scalars a basis for `N`. For `basis_of_pid` we only need the first half and can fix `M = ⊤`, for `smith_normal_form` we need the full statement, but must also feed in a basis for `M` using `basis_of_pid` to keep the induction going. -/ lemma submodule.basis_of_pid_aux [fintype ι] {O : Type*} [add_comm_group O] [module R O] (M N : submodule R O) (b'M : basis ι R M) (N_bot : N ≠ ⊥) (N_le_M : N ≤ M) : ∃ (y ∈ M) (a : R) (hay : a • y ∈ N) (M' ≤ M) (N' ≤ N) (N'_le_M' : N' ≤ M') (y_ortho_M' : ∀ (c : R) (z : O), z ∈ M' → c • y + z = 0 → c = 0) (ay_ortho_N' : ∀ (c : R) (z : O), z ∈ N' → c • a • y + z = 0 → c = 0), ∀ (n') (bN' : basis (fin n') R N'), ∃ (bN : basis (fin (n' + 1)) R N), ∀ (m') (hn'm' : n' ≤ m') (bM' : basis (fin m') R M'), ∃ (hnm : (n' + 1) ≤ (m' + 1)) (bM : basis (fin (m' + 1)) R M), ∀ (as : fin n' → R) (h : ∀ (i : fin n'), (bN' i : O) = as i • (bM' (fin.cast_le hn'm' i) : O)), ∃ (as' : fin (n' + 1) → R), ∀ (i : fin (n' + 1)), (bN i : O) = as' i • (bM (fin.cast_le hnm i) : O) := begin -- Let `ϕ` be a maximal projection of `M` onto `R`, in the sense that there is -- no `ψ` whose image of `N` is larger than `ϕ`'s image of `N`. have : ∃ ϕ : M →ₗ[R] R, ∀ (ψ : M →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N, { obtain ⟨P, P_eq, P_max⟩ := set_has_maximal_iff_noetherian.mpr (infer_instance : is_noetherian R R) _ (show (set.range (λ ψ : M →ₗ[R] R, ψ.submodule_image N)).nonempty, from ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩), obtain ⟨ϕ, rfl⟩ := set.mem_range.mp P_eq, exact ⟨ϕ, λ ψ hψ, P_max _ ⟨_, rfl⟩ hψ⟩ }, let ϕ := this.some, have ϕ_max := this.some_spec, -- Since `ϕ(N)` is a `R`-submodule of the PID `R`, -- it is principal and generated by some `a`. let a := generator (ϕ.submodule_image N), have a_mem : a ∈ ϕ.submodule_image N := generator_mem _, -- If `a` is zero, then the submodule is trivial. So let's assume `a ≠ 0`, `N ≠ ⊥`. by_cases a_zero : a = 0, { have := eq_bot_of_generator_maximal_submodule_image_eq_zero b'M N_le_M ϕ_max a_zero, contradiction }, -- We claim that `ϕ⁻¹ a = y` can be taken as basis element of `N`. obtain ⟨y, yN, ϕy_eq⟩ := (linear_map.mem_submodule_image_of_le N_le_M).mp a_mem, have ϕy_ne_zero : ϕ ⟨y, N_le_M yN⟩ ≠ 0 := λ h, a_zero (ϕy_eq.symm.trans h), -- Write `y` as `a • y'` for some `y'`. have hdvd : ∀ i, a ∣ b'M.coord i ⟨y, N_le_M yN⟩ := λ i, generator_maximal_submodule_image_dvd N_le_M ϕ_max y yN ϕy_eq (b'M.coord i), choose c hc using hdvd, let y' : O := ∑ i, c i • b'M i, have y'M : y' ∈ M := M.sum_mem (λ i _, M.smul_mem (c i) (b'M i).2), have mk_y' : (⟨y', y'M⟩ : M) = ∑ i, c i • b'M i := subtype.ext (show y' = M.subtype _, by { simp only [linear_map.map_sum, linear_map.map_smul], refl }), have a_smul_y' : a • y' = y, { refine congr_arg coe (show (a • ⟨y', y'M⟩ : M) = ⟨y, N_le_M yN⟩, from _), rw [← b'M.sum_repr ⟨y, N_le_M yN⟩, mk_y', finset.smul_sum], refine finset.sum_congr rfl (λ i _, _), rw [← mul_smul, ← hc], refl }, -- We found an `y` and an `a`! refine ⟨y', y'M, a, a_smul_y'.symm ▸ yN, _⟩, have ϕy'_eq : ϕ ⟨y', y'M⟩ = 1 := mul_left_cancel₀ a_zero (calc a • ϕ ⟨y', y'M⟩ = ϕ ⟨a • y', _⟩ : (ϕ.map_smul a ⟨y', y'M⟩).symm ... = ϕ ⟨y, N_le_M yN⟩ : by simp only [a_smul_y'] ... = a : ϕy_eq ... = a * 1 : (mul_one a).symm), have ϕy'_ne_zero : ϕ ⟨y', y'M⟩ ≠ 0 := by simpa only [ϕy'_eq] using one_ne_zero, -- `M' := ker (ϕ : M → R)` is smaller than `M` and `N' := ker (ϕ : N → R)` is smaller than `N`. let M' : submodule R O := ϕ.ker.map M.subtype, let N' : submodule R O := (ϕ.comp (of_le N_le_M)).ker.map N.subtype, have M'_le_M : M' ≤ M := M.map_subtype_le ϕ.ker, have N'_le_M' : N' ≤ M', { intros x hx, simp only [mem_map, linear_map.mem_ker] at hx ⊢, obtain ⟨⟨x, xN⟩, hx, rfl⟩ := hx, exact ⟨⟨x, N_le_M xN⟩, hx, rfl⟩ }, have N'_le_N : N' ≤ N := N.map_subtype_le (ϕ.comp (of_le N_le_M)).ker, -- So fill in those results as well. refine ⟨M', M'_le_M, N', N'_le_N, N'_le_M', _⟩, -- Note that `y'` is orthogonal to `M'`. have y'_ortho_M' : ∀ (c : R) z ∈ M', c • y' + z = 0 → c = 0, { intros c x xM' hc, obtain ⟨⟨x, xM⟩, hx', rfl⟩ := submodule.mem_map.mp xM', rw linear_map.mem_ker at hx', have hc' : (c • ⟨y', y'M⟩ + ⟨x, xM⟩ : M) = 0 := subtype.coe_injective hc, simpa only [linear_map.map_add, linear_map.map_zero, linear_map.map_smul, smul_eq_mul, add_zero, mul_eq_zero, ϕy'_ne_zero, hx', or_false] using congr_arg ϕ hc' }, -- And `a • y'` is orthogonal to `N'`. have ay'_ortho_N' : ∀ (c : R) z ∈ N', c • a • y' + z = 0 → c = 0, { intros c z zN' hc, refine (mul_eq_zero.mp (y'_ortho_M' (a * c) z (N'_le_M' zN') _)).resolve_left a_zero, rw [mul_comm, mul_smul, hc] }, -- So we can extend a basis for `N'` with `y` refine ⟨y'_ortho_M', ay'_ortho_N', λ n' bN', ⟨_, _⟩⟩, { refine basis.mk_fin_cons_of_le y yN bN' N'_le_N _ _, { intros c z zN' hc, refine ay'_ortho_N' c z zN' _, rwa ← a_smul_y' at hc }, { intros z zN, obtain ⟨b, hb⟩ : _ ∣ ϕ ⟨z, N_le_M zN⟩ := generator_submodule_image_dvd_of_mem N_le_M ϕ zN, refine ⟨-b, submodule.mem_map.mpr ⟨⟨_, N.sub_mem zN (N.smul_mem b yN)⟩, _, _⟩⟩, { refine linear_map.mem_ker.mpr (show ϕ (⟨z, N_le_M zN⟩ - b • ⟨y, N_le_M yN⟩) = 0, from _), rw [linear_map.map_sub, linear_map.map_smul, hb, ϕy_eq, smul_eq_mul, mul_comm, sub_self] }, { simp only [sub_eq_add_neg, neg_smul], refl } } }, -- And extend a basis for `M'` with `y'` intros m' hn'm' bM', refine ⟨nat.succ_le_succ hn'm', _, _⟩, { refine basis.mk_fin_cons_of_le y' y'M bM' M'_le_M y'_ortho_M' _, intros z zM, refine ⟨-ϕ ⟨z, zM⟩, ⟨⟨z, zM⟩ - (ϕ ⟨z, zM⟩) • ⟨y', y'M⟩, linear_map.mem_ker.mpr _, _⟩⟩, { rw [linear_map.map_sub, linear_map.map_smul, ϕy'_eq, smul_eq_mul, mul_one, sub_self] }, { rw [linear_map.map_sub, linear_map.map_smul, sub_eq_add_neg, neg_smul], refl } }, -- It remains to show the extended bases are compatible with each other. intros as h, refine ⟨fin.cons a as, _⟩, intro i, rw [basis.coe_mk_fin_cons_of_le, basis.coe_mk_fin_cons_of_le], refine fin.cases _ (λ i, _) i, { simp only [fin.cons_zero, fin.cast_le_zero], exact a_smul_y'.symm }, { rw fin.cast_le_succ, simp only [fin.cons_succ, coe_of_le, h i] } end /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. This is a `lemma` to make the induction a bit easier. To actually access the basis, see `submodule.basis_of_pid`. See also the stronger version `submodule.smith_normal_form`. -/ lemma submodule.nonempty_basis_of_pid {ι : Type*} [fintype ι] (b : basis ι R M) (N : submodule R M) : ∃ (n : ℕ), nonempty (basis (fin n) R N) := begin haveI := classical.dec_eq M, refine N.induction_on_rank b _ _, intros N ih, let b' := (b.reindex (fintype.equiv_fin ι)).map (linear_equiv.of_top _ rfl).symm, by_cases N_bot : N = ⊥, { subst N_bot, exact ⟨0, ⟨basis.empty _⟩⟩ }, obtain ⟨y, -, a, hay, M', -, N', N'_le_N, -, -, ay_ortho, h'⟩ := submodule.basis_of_pid_aux ⊤ N b' N_bot le_top, obtain ⟨n', ⟨bN'⟩⟩ := ih N' N'_le_N _ hay ay_ortho, obtain ⟨bN, hbN⟩ := h' n' bN', exact ⟨n' + 1, ⟨bN⟩⟩ end /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. See also the stronger version `submodule.smith_normal_form`. -/ noncomputable def submodule.basis_of_pid {ι : Type*} [fintype ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), (basis (fin n) R N) := ⟨_, (N.nonempty_basis_of_pid b).some_spec.some⟩ lemma submodule.basis_of_pid_bot {ι : Type*} [fintype ι] (b : basis ι R M) : submodule.basis_of_pid b ⊥ = ⟨0, basis.empty _⟩ := begin obtain ⟨n, b'⟩ := submodule.basis_of_pid b ⊥, let e : fin n ≃ fin 0 := b'.index_equiv (basis.empty _ : basis (fin 0) R (⊥ : submodule R M)), obtain rfl : n = 0 := by simpa using fintype.card_eq.mpr ⟨e⟩, exact sigma.eq rfl (basis.eq_of_apply_eq $ fin_zero_elim) end /-- A submodule inside a free `R`-submodule of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. See also the stronger version `submodule.smith_normal_form_of_le`. -/ noncomputable def submodule.basis_of_pid_of_le {ι : Type*} [fintype ι] {N O : submodule R M} (hNO : N ≤ O) (b : basis ι R O) : Σ (n : ℕ), basis (fin n) R N := let ⟨n, bN'⟩ := submodule.basis_of_pid b (N.comap O.subtype) in ⟨n, bN'.map (submodule.comap_subtype_equiv_of_le hNO)⟩ /-- A submodule inside the span of a linear independent family is a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid_of_le_span {ι : Type*} [fintype ι] {b : ι → M} (hb : linear_independent R b) {N : submodule R M} (le : N ≤ submodule.span R (set.range b)) : Σ (n : ℕ), basis (fin n) R N := submodule.basis_of_pid_of_le le (basis.span hb) variable {M} /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free [fintype ι] {s : ι → M} (hs : span R (range s) = ⊤) [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := begin classical, -- We define `N` as the submodule spanned by a maximal linear independent subfamily of `s` have := exists_maximal_independent R s, let I : set ι := this.some, obtain ⟨indepI : linear_independent R (s ∘ coe : I → M), hI : ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I)⟩ := this.some_spec, let N := span R (range $ (s ∘ coe : I → M)), -- same as `span R (s '' I)` but more convenient let sI : I → N := λ i, ⟨s i.1, subset_span (mem_range_self i)⟩, -- `s` restricted to `I` let sI_basis : basis I R N, -- `s` restricted to `I` is a basis of `N` from basis.span indepI, -- Our first goal is to build `A ≠ 0` such that `A • M ⊆ N` have exists_a : ∀ i : ι, ∃ a : R, a ≠ 0 ∧ a • s i ∈ N, { intro i, by_cases hi : i ∈ I, { use [1, zero_ne_one.symm], rw one_smul, exact subset_span (mem_range_self (⟨i, hi⟩ : I)) }, { simpa [image_eq_range s I] using hI i hi } }, choose a ha ha' using exists_a, let A := ∏ i, a i, have hA : A ≠ 0, { rw finset.prod_ne_zero_iff, simpa using ha }, -- `M ≃ A • M` because `M` is torsion free and `A ≠ 0` let φ : M →ₗ[R] M := linear_map.lsmul R M A, have : φ.ker = ⊥, from linear_map.ker_lsmul hA, let ψ : M ≃ₗ[R] φ.range := linear_equiv.of_injective φ (linear_map.ker_eq_bot.mp this), have : φ.range ≤ N, -- as announced, `A • M ⊆ N` { suffices : ∀ i, φ (s i) ∈ N, { rw [linear_map.range_eq_map, ← hs, φ.map_span_le], rintros _ ⟨i, rfl⟩, apply this }, intro i, calc (∏ j, a j) • s i = (∏ j in {i}ᶜ, a j) • a i • s i : by rw [fintype.prod_eq_prod_compl_mul i, mul_smul] ... ∈ N : N.smul_mem _ (ha' i) }, -- Since a submodule of a free `R`-module is free, we get that `A • M` is free obtain ⟨n, b : basis (fin n) R φ.range⟩ := submodule.basis_of_pid_of_le this sI_basis, -- hence `M` is free. exact ⟨n, b.map ψ.symm⟩ end /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free' [module.finite R M] [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := module.free_of_finite_type_torsion_free module.finite.exists_fin.some_spec.some_spec section smith_normal /-- A Smith normal form basis for a submodule `N` of a module `M` consists of bases for `M` and `N` such that the inclusion map `N → M` can be written as a (rectangular) matrix with `a` along the diagonal: in Smith normal form. -/ @[nolint has_nonempty_instance] structure basis.smith_normal_form (N : submodule R M) (ι : Type*) (n : ℕ) := (bM : basis ι R M) (bN : basis (fin n) R N) (f : fin n ↪ ι) (a : fin n → R) (snf : ∀ i, (bN i : M) = a i • bM (f i)) /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. See `submodule.smith_normal_form_of_le` for a version of this theorem that returns a `basis.smith_normal_form`. This is a strengthening of `submodule.basis_of_pid_of_le`. -/ theorem submodule.exists_smith_normal_form_of_le [fintype ι] (b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) : ∃ (n o : ℕ) (hno : n ≤ o) (bO : basis (fin o) R O) (bN : basis (fin n) R N) (a : fin n → R), ∀ i, (bN i : M) = a i • bO (fin.cast_le hno i) := begin revert N, refine induction_on_rank b _ _ O, intros M ih N N_le_M, obtain ⟨m, b'M⟩ := M.basis_of_pid b, by_cases N_bot : N = ⊥, { subst N_bot, exact ⟨0, m, nat.zero_le _, b'M, basis.empty _, fin_zero_elim, fin_zero_elim⟩ }, obtain ⟨y, hy, a, hay, M', M'_le_M, N', N'_le_N, N'_le_M', y_ortho, ay_ortho, h⟩ := submodule.basis_of_pid_aux M N b'M N_bot N_le_M, obtain ⟨n', m', hn'm', bM', bN', as', has'⟩ := ih M' M'_le_M y hy y_ortho N' N'_le_M', obtain ⟨bN, h'⟩ := h n' bN', obtain ⟨hmn, bM, h''⟩ := h' m' hn'm' bM', obtain ⟨as, has⟩ := h'' as' has', exact ⟨_, _, hmn, bM, bN, as, has⟩ end /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. See `submodule.exists_smith_normal_form_of_le` for a version of this theorem that doesn't need to map `N` into a submodule of `O`. This is a strengthening of `submodule.basis_of_pid_of_le`. -/ noncomputable def submodule.smith_normal_form_of_le [fintype ι] (b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) : Σ (o n : ℕ), basis.smith_normal_form (N.comap O.subtype) (fin o) n := begin choose n o hno bO bN a snf using N.exists_smith_normal_form_of_le b O N_le_O, refine ⟨o, n, bO, bN.map (comap_subtype_equiv_of_le N_le_O).symm, (fin.cast_le hno).to_embedding, a, λ i, _⟩, ext, simp only [snf, basis.map_apply, submodule.comap_subtype_equiv_of_le_symm_apply_coe_coe, submodule.coe_smul_of_tower, rel_embedding.coe_fn_to_embedding] end /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. This is a strengthening of `submodule.basis_of_pid`. See also `ideal.smith_normal_form`, which moreover proves that the dimension of an ideal is the same as the dimension of the whole ring. -/ noncomputable def submodule.smith_normal_form [fintype ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), basis.smith_normal_form N ι n := let ⟨m, n, bM, bN, f, a, snf⟩ := N.smith_normal_form_of_le b ⊤ le_top, bM' := bM.map (linear_equiv.of_top _ rfl), e := bM'.index_equiv b in ⟨n, bM'.reindex e, bN.map (comap_subtype_equiv_of_le le_top), f.trans e.to_embedding, a, λ i, by simp only [snf, basis.map_apply, linear_equiv.of_top_apply, submodule.coe_smul_of_tower, submodule.comap_subtype_equiv_of_le_apply_coe, coe_coe, basis.reindex_apply, equiv.to_embedding_apply, function.embedding.trans_apply, equiv.symm_apply_apply]⟩ /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix. See `ideal.exists_smith_normal_form` for a version of this theorem that doesn't need to map `I` into a submodule of `R`. This is a strengthening of `submodule.basis_of_pid`. -/ noncomputable def ideal.smith_normal_form [fintype ι] {S : Type*} [comm_ring S] [is_domain S] [algebra R S] (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : basis.smith_normal_form (I.restrict_scalars R) ι (fintype.card ι) := let ⟨n, bS, bI, f, a, snf⟩ := (I.restrict_scalars R).smith_normal_form b in have eq : _ := ideal.rank_eq bS hI (bI.map ((restrict_scalars_equiv R S S I).restrict_scalars _)), let e : fin n ≃ fin (fintype.card ι) := fintype.equiv_of_card_eq (by rw [eq, fintype.card_fin]) in ⟨bS, bI.reindex e, e.symm.to_embedding.trans f, a ∘ e.symm, λ i, by simp only [snf, basis.coe_reindex, function.embedding.trans_apply, equiv.to_embedding_apply]⟩ /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix. See also `ideal.smith_normal_form` for a version of this theorem that returns a `basis.smith_normal_form`. -/ theorem ideal.exists_smith_normal_form [finite ι] {S : Type*} [comm_ring S] [is_domain S] [algebra R S] (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : ∃ (b' : basis ι R S) (a : ι → R) (ab' : basis ι R I), ∀ i, (ab' i : S) = a i • b' i := by casesI nonempty_fintype ι; exact let ⟨bS, bI, f, a, snf⟩ := I.smith_normal_form b hI, e : fin (fintype.card ι) ≃ ι := equiv.of_bijective f ((fintype.bijective_iff_injective_and_card f).mpr ⟨f.injective, fintype.card_fin _⟩) in have fe : ∀ i, f (e.symm i) = i := e.apply_symm_apply, ⟨bS, a ∘ e.symm, (bI.reindex e).map ((restrict_scalars_equiv _ _ _ _).restrict_scalars R), λ i, by simp only [snf, fe, basis.map_apply, linear_equiv.restrict_scalars_apply, submodule.restrict_scalars_equiv_apply, basis.coe_reindex]⟩ end smith_normal end principal_ideal_domain /-- A set of linearly independent vectors in a module `M` over a semiring `S` is also linearly independent over a subring `R` of `K`. -/ lemma linear_independent.restrict_scalars_algebras {R S M ι : Type*} [comm_semiring R] [semiring S] [add_comm_monoid M] [algebra R S] [module R M] [module S M] [is_scalar_tower R S M] (hinj : function.injective (algebra_map R S)) {v : ι → M} (li : linear_independent S v) : linear_independent R v := linear_independent.restrict_scalars (by rwa algebra.algebra_map_eq_smul_one' at hinj) li
d974d8ec7fca1c92ade411350cbd9e75b6c3f3a0
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/ring_theory/hahn_series.lean
31c82b5d6187df6006b9c40838dbd7da21ec4a8a
[ "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
26,019
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.well_founded_set import algebra.big_operators import ring_theory.valuation.basic import algebra.module.pi import ring_theory.power_series.basic /-! # Hahn Series ## Main Definitions * If `Γ` is linearly ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are well-founded. * If `R` is a (commutative) additive monoid or group, then so is `hahn_series Γ R`. * If `R` is a (comm_)(semi)ring, then so is `hahn_series Γ R`. * `hahn_series.add_val Γ R` defines an `add_valuation` on `hahn_series Γ R`. ## TODO * Given `[linear_ordered_add_comm_group Γ]` and `[field R]`, define `field (hahn_series Γ R)`. * Build an API for the variable `X` * Define Laurent series -/ open finset open_locale big_operators classical noncomputable theory /-- If `Γ` is linearly ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are well-founded. -/ @[ext] structure hahn_series (Γ : Type*) (R : Type*) [linear_order Γ] [has_zero R] := (coeff : Γ → R) (is_wf_support' : (function.support coeff).is_wf) variables {Γ : Type*} {R : Type*} namespace hahn_series section zero variables [linear_order Γ] [has_zero R] /-- The support of a Hahn series is just the set of indices whose coefficients are nonzero. Notably, it is well-founded. -/ def support (x : hahn_series Γ R) : set Γ := function.support x.coeff @[simp] lemma is_wf_support (x : hahn_series Γ R) : x.support.is_wf := x.is_wf_support' @[simp] lemma mem_support (x : hahn_series Γ R) (a : Γ) : a ∈ x.support ↔ x.coeff a ≠ 0 := iff.refl _ instance : has_zero (hahn_series Γ R) := ⟨{ coeff := 0, is_wf_support' := by simp }⟩ instance : inhabited (hahn_series Γ R) := ⟨0⟩ instance [subsingleton R] : subsingleton (hahn_series Γ R) := ⟨λ a b, a.ext b (subsingleton.elim _ _)⟩ @[simp] lemma zero_coeff {a : Γ} : (0 : hahn_series Γ R).coeff a = 0 := rfl lemma support_zero : support (0 : hahn_series Γ R) = ∅ := function.support_zero @[simp] lemma support_nonempty_iff {x : hahn_series Γ R} : x.support.nonempty ↔ x ≠ 0 := begin split, { rintro ⟨a, ha⟩ rfl, apply ha zero_coeff }, { contrapose!, rw set.not_nonempty_iff_eq_empty, intro h, ext a, have ha := set.not_mem_empty a, rw [← h, mem_support, not_not] at ha, rw [ha, zero_coeff] } end /-- `single a r` is the Hahn series which has coefficient `r` at `a` and zero otherwise. -/ def single (a : Γ) : zero_hom R (hahn_series Γ R) := { to_fun := λ r, { coeff := pi.single a r, is_wf_support' := (set.is_wf_singleton a).mono pi.support_single_subset }, map_zero' := ext _ _ (pi.single_zero _) } variables {a b : Γ} {r : R} @[simp] theorem single_coeff_same (a : Γ) (r : R) : (single a r).coeff a = r := pi.single_eq_same a r @[simp] theorem single_coeff_of_ne (h : b ≠ a) : (single a r).coeff b = 0 := pi.single_eq_of_ne h r theorem single_coeff : (single a r).coeff b = if (b = a) then r else 0 := by { split_ifs with h; simp [h] } @[simp] lemma support_single_of_ne (h : r ≠ 0) : support (single a r) = {a} := pi.support_single_of_ne h lemma support_single_subset : support (single a r) ⊆ {a} := pi.support_single_subset lemma eq_of_mem_support_single {b : Γ} (h : b ∈ support (single a r)) : b = a := support_single_subset h @[simp] lemma single_eq_zero : (single a (0 : R)) = 0 := (single a).map_zero instance [nonempty Γ] [nontrivial R] : nontrivial (hahn_series Γ R) := ⟨begin obtain ⟨r, s, rs⟩ := exists_pair_ne R, inhabit Γ, refine ⟨single (arbitrary Γ) r, single (arbitrary Γ) s, λ con, rs _⟩, rw [← single_coeff_same (arbitrary Γ) r, con, single_coeff_same], end⟩ lemma coeff_min_ne_zero {x : hahn_series Γ R} (hx : x ≠ 0) : x.coeff (x.is_wf_support.min (support_nonempty_iff.2 hx)) ≠ 0 := x.is_wf_support.min_mem (support_nonempty_iff.2 hx) end zero section addition variable [linear_order Γ] section add_monoid variable [add_monoid R] instance : has_add (hahn_series Γ R) := { add := λ x y, { coeff := x.coeff + y.coeff, is_wf_support' := (x.is_wf_support.union y.is_wf_support).mono (function.support_add _ _) } } instance : add_monoid (hahn_series Γ R) := { zero := 0, add := (+), add_assoc := λ x y z, by { ext, apply add_assoc }, zero_add := λ x, by { ext, apply zero_add }, add_zero := λ x, by { ext, apply add_zero } } @[simp] lemma add_coeff' {x y : hahn_series Γ R} : (x + y).coeff = x.coeff + y.coeff := rfl lemma add_coeff {x y : hahn_series Γ R} {a : Γ} : (x + y).coeff a = x.coeff a + y.coeff a := rfl lemma support_add_subset {x y : hahn_series Γ R} : support (x + y) ⊆ support x ∪ support y := λ a ha, begin rw [mem_support, add_coeff] at ha, rw [set.mem_union, mem_support, mem_support], contrapose! ha, rw [ha.1, ha.2, add_zero], end /-- `single` as an additive monoid/group homomorphism -/ def single.add_monoid_hom (a : Γ) : R →+ (hahn_series Γ R) := { map_add' := λ x y, by { ext b, by_cases h : b = a; simp [h] }, ..single a } @[simp] lemma single.add_monoid_hom_apply {a : Γ} {r : R} : single.add_monoid_hom a r = single a r := rfl end add_monoid instance [add_comm_monoid R] : add_comm_monoid (hahn_series Γ R) := { add_comm := λ x y, by { ext, apply add_comm } .. hahn_series.add_monoid } section add_group variable [add_group R] instance : add_group (hahn_series Γ R) := { neg := λ x, { coeff := λ a, - x.coeff a, is_wf_support' := by { rw function.support_neg, exact x.is_wf_support }, }, add_left_neg := λ x, by { ext, apply add_left_neg }, .. hahn_series.add_monoid } @[simp] lemma neg_coeff' {x : hahn_series Γ R} : (- x).coeff = - x.coeff := rfl lemma neg_coeff {x : hahn_series Γ R} {a : Γ} : (- x).coeff a = - x.coeff a := rfl @[simp] lemma support_neg {x : hahn_series Γ R} : (- x).support = x.support := by { ext, simp } @[simp] lemma sub_coeff' {x y : hahn_series Γ R} : (x - y).coeff = x.coeff - y.coeff := by { ext, simp [sub_eq_add_neg] } lemma sub_coeff {x y : hahn_series Γ R} {a : Γ} : (x - y).coeff a = x.coeff a - y.coeff a := by simp end add_group instance [add_comm_group R] : add_comm_group (hahn_series Γ R) := { .. hahn_series.add_comm_monoid, .. hahn_series.add_group } end addition section distrib_mul_action variables [linear_order Γ] {V : Type*} [monoid R] [add_monoid V] [distrib_mul_action R V] instance : has_scalar R (hahn_series Γ V) := ⟨λ r x, { coeff := r • x.coeff, is_wf_support' := x.is_wf_support.mono (function.support_smul_subset_right r x.coeff) }⟩ @[simp] lemma smul_coeff {r : R} {x : hahn_series Γ V} {a : Γ} : (r • x).coeff a = r • (x.coeff a) := rfl instance : distrib_mul_action R (hahn_series Γ V) := { smul := (•), one_smul := λ _, by { ext, simp }, smul_zero := λ _, by { ext, simp }, smul_add := λ _ _ _, by { ext, simp [smul_add] }, mul_smul := λ _ _ _, by { ext, simp [mul_smul] } } variables {S : Type*} [monoid S] [distrib_mul_action S V] instance [has_scalar R S] [is_scalar_tower R S V] : is_scalar_tower R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp }⟩ instance [smul_comm_class R S V] : smul_comm_class R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp [smul_comm] }⟩ end distrib_mul_action section semimodule variables [linear_order Γ] [semiring R] {V : Type*} [add_comm_monoid V] [semimodule R V] instance : semimodule R (hahn_series Γ V) := { zero_smul := λ _, by { ext, simp }, add_smul := λ _ _ _, by { ext, simp [add_smul] }, .. hahn_series.distrib_mul_action } /-- `single` as a linear map -/ def single.linear_map (a : Γ) : R →ₗ[R] (hahn_series Γ R) := { map_smul' := λ r s, by { ext b, by_cases h : b = a; simp [h] }, ..single.add_monoid_hom a } @[simp] lemma single.linear_map_apply {a : Γ} {r : R} : single.linear_map a r = single a r := rfl end semimodule section multiplication variable [linear_ordered_cancel_add_comm_monoid Γ] instance [has_zero R] [has_one R] : has_one (hahn_series Γ R) := ⟨single 0 1⟩ @[simp] lemma one_coeff [has_zero R] [has_one R] {a : Γ} : (1 : hahn_series Γ R).coeff a = if a = 0 then 1 else 0 := single_coeff @[simp] lemma single_zero_one [has_zero R] [has_one R] : (single 0 (1 : R)) = 1 := rfl @[simp] lemma support_one [semiring R] [nontrivial R] : support (1 : hahn_series Γ R) = {0} := support_single_of_ne one_ne_zero instance [semiring R] : has_mul (hahn_series Γ R) := { mul := λ x y, { coeff := λ a, ∑ ij in (add_antidiagonal x.is_wf_support y.is_wf_support a), x.coeff ij.fst * y.coeff ij.snd, is_wf_support' := begin have h : {a : Γ | ∑ (ij : Γ × Γ) in add_antidiagonal x.is_wf_support y.is_wf_support a, x.coeff ij.fst * y.coeff ij.snd ≠ 0} ⊆ {a : Γ | (add_antidiagonal x.is_wf_support y.is_wf_support a).nonempty}, { intros a ha, contrapose! ha, simp [not_nonempty_iff_eq_empty.1 ha] }, exact is_wf_support_add_antidiagonal.mono h, end, }, } @[simp] lemma mul_coeff [semiring R] {x y : hahn_series Γ R} {a : Γ} : (x * y).coeff a = ∑ ij in (add_antidiagonal x.is_wf_support y.is_wf_support a), x.coeff ij.fst * y.coeff ij.snd := rfl lemma mul_coeff_right' [semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_wf) (hys : y.support ⊆ s) : (x * y).coeff a = ∑ ij in (add_antidiagonal x.is_wf_support hs a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_right hys) _ (λ _ _, rfl), intros b hb, simp only [not_and, not_not, mem_sdiff, mem_add_antidiagonal, ne.def, set.mem_set_of_eq, mem_support] at hb, rw [(hb.2 hb.1.1 hb.1.2.1), mul_zero] end lemma mul_coeff_left' [semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_wf) (hxs : x.support ⊆ s) : (x * y).coeff a = ∑ ij in (add_antidiagonal hs y.is_wf_support a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_left hxs) _ (λ _ _, rfl), intros b hb, simp only [not_and, not_not, mem_sdiff, mem_add_antidiagonal, ne.def, set.mem_set_of_eq, mem_support] at hb, rw [not_not.1 (λ con, hb.1.2.2 (hb.2 hb.1.1 con)), zero_mul], end instance [semiring R] : distrib (hahn_series Γ R) := { left_distrib := λ x y z, begin ext a, have hwf := (y.is_wf_support.union z.is_wf_support), rw [mul_coeff_right' hwf, add_coeff, mul_coeff_right' hwf (set.subset_union_right _ _), mul_coeff_right' hwf (set.subset_union_left _ _)], { simp only [add_coeff, mul_add, sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], } end, right_distrib := λ x y z, begin ext a, have hwf := (x.is_wf_support.union y.is_wf_support), rw [mul_coeff_left' hwf, add_coeff, mul_coeff_left' hwf (set.subset_union_right _ _), mul_coeff_left' hwf (set.subset_union_left _ _)], { simp only [add_coeff, add_mul, sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], }, end, .. hahn_series.has_mul, .. hahn_series.has_add } lemma single_mul_coeff_add [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : ((single b r) * x).coeff (a + b) = r * x.coeff a := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, mul_zero], rw [sum_congr _ (λ _ _, rfl), sum_empty], ext ⟨a1, a2⟩, simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not, mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro h1 rfl h2, rw add_comm at h1, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(b, a)}, (single b r).coeff ij.fst * x.coeff ij.snd, { apply sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal, mem_singleton, set.mem_set_of_eq], split, { rintro ⟨h1, rfl, h2⟩, rw add_comm at h1, refine ⟨rfl, add_right_cancel h1⟩ }, { rintro ⟨rfl, rfl⟩, refine ⟨add_comm _ _, _⟩, simp [hx] } }, { simp } end lemma mul_single_coeff_add [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : (x * (single b r)).coeff (a + b) = x.coeff a * r := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, zero_mul], rw [sum_congr _ (λ _ _, rfl), sum_empty], ext ⟨a1, a2⟩, simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not, mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro h1 h2 rfl, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(a,b)}, x.coeff ij.fst * (single b r).coeff ij.snd, { apply sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal, mem_singleton, set.mem_set_of_eq], split, { rintro ⟨h1, h2, rfl⟩, refine ⟨add_right_cancel h1, rfl⟩ }, { rintro ⟨rfl, rfl⟩, simp [hx] } }, { simp } end @[simp] lemma mul_single_zero_coeff [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : (x * (single 0 r)).coeff a = x.coeff a * r := by rw [← add_zero a, mul_single_coeff_add, add_zero] lemma single_zero_mul_coeff [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : ((single 0 r) * x).coeff a = r * x.coeff a := by rw [← add_zero a, single_mul_coeff_add, add_zero] @[simp] lemma single_zero_mul_eq_smul [semiring R] {r : R} {x : hahn_series Γ R} : (single 0 r) * x = r • x := by { ext, exact single_zero_mul_coeff } theorem support_mul_subset_add_support [semiring R] {x y : hahn_series Γ R} : support (x * y) ⊆ support x + support y := begin apply set.subset.trans (λ x hx, _) support_add_antidiagonal_subset_add, { exact x.is_wf_support }, { exact y.is_wf_support }, contrapose! hx, simp only [not_nonempty_iff_eq_empty, ne.def, set.mem_set_of_eq] at hx, simp [hx], end @[simp] lemma mul_coeff_min_add_min [semiring R] {x y : hahn_series Γ R} (hx : x ≠ 0) (hy : y ≠ 0) : (x * y).coeff (x.is_wf_support.min (support_nonempty_iff.2 hx) + y.is_wf_support.min (support_nonempty_iff.2 hy)) = (x.coeff (x.is_wf_support.min (support_nonempty_iff.2 hx))) * y.coeff (y.is_wf_support.min (support_nonempty_iff.2 hy)) := by rw [mul_coeff, finset.add_antidiagonal_min_add_min, finset.sum_singleton] private lemma mul_assoc' [semiring R] (x y z : hahn_series Γ R) : x * y * z = x * (y * z) := begin ext b, rw [mul_coeff_left' (x.is_wf_support.add y.is_wf_support) support_mul_subset_add_support, mul_coeff_right' (y.is_wf_support.add z.is_wf_support) support_mul_subset_add_support], simp only [mul_coeff, add_coeff, sum_mul, mul_sum, sum_sigma'], refine sum_bij_ne_zero (λ a has ha0, ⟨⟨a.2.1, a.2.2 + a.1.2⟩, ⟨a.2.2, a.1.2⟩⟩) _ _ _ _, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [true_and, set.image2_add, eq_self_iff_true, mem_add_antidiagonal, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq] at H1 H2 ⊢, obtain ⟨⟨rfl, ⟨H3, nz⟩⟩, ⟨rfl, nx, ny⟩⟩ := H1, refine ⟨⟨(add_assoc _ _ _).symm, nx, set.add_mem_add ny nz⟩, ny, nz⟩ }, { rintros ⟨⟨i1,j1⟩, ⟨k1,l1⟩⟩ ⟨⟨i2,j2⟩, ⟨k2,l2⟩⟩ H1 H2 H3 H4 H5, simp only [set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq] at H1 H3 H5, obtain ⟨⟨rfl, H⟩, rfl, rfl⟩ := H5, simp only [and_true, prod.mk.inj_iff, eq_self_iff_true, heq_iff_eq], exact add_right_cancel (H1.1.1.trans H3.1.1.symm) }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [exists_prop, set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal, sigma.exists, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq, prod.exists] at H1 H2 ⊢, obtain ⟨⟨rfl, nx, H⟩, rfl, ny, nz⟩ := H1, exact ⟨i + k, l, i, k, ⟨⟨add_assoc _ _ _, set.add_mem_add nx ny, nz⟩, rfl, nx, ny⟩, λ con, H2 ((mul_assoc _ _ _).symm.trans con), ⟨rfl, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp [mul_assoc], } end instance [semiring R] : semiring (hahn_series Γ R) := { zero := 0, one := 1, add := (+), mul := (*), zero_mul := λ _, by { ext, simp }, mul_zero := λ _, by { ext, simp }, one_mul := λ x, single_zero_mul_eq_smul.trans (one_smul _ _), mul_one := λ x, by { ext, exact mul_single_zero_coeff.trans (mul_one _) }, mul_assoc := mul_assoc', .. hahn_series.add_comm_monoid, .. hahn_series.distrib } instance [comm_semiring R] : comm_semiring (hahn_series Γ R) := { mul_comm := λ x y, begin ext, simp_rw [mul_coeff, mul_comm], refine sum_bij (λ a ha, ⟨a.2, a.1⟩) _ (λ a ha, by simp) _ _, { intros a ha, simp only [mem_add_antidiagonal, ne.def, set.mem_set_of_eq] at ha ⊢, obtain ⟨h1, h2, h3⟩ := ha, refine ⟨_, h3, h2⟩, rw [add_comm, h1], }, { rintros ⟨a1, a2⟩ ⟨b1, b2⟩ ha hb hab, rw prod.ext_iff at *, refine ⟨hab.2, hab.1⟩, }, { intros a ha, refine ⟨a.swap, _, by simp⟩, simp only [prod.fst_swap, mem_add_antidiagonal, prod.snd_swap, ne.def, set.mem_set_of_eq] at ha ⊢, exact ⟨(add_comm _ _).trans ha.1, ha.2.2, ha.2.1⟩ } end, .. hahn_series.semiring } instance [ring R] : ring (hahn_series Γ R) := { .. hahn_series.semiring, .. hahn_series.add_comm_group } instance [comm_ring R] : comm_ring (hahn_series Γ R) := { .. hahn_series.comm_semiring, .. hahn_series.ring } instance [integral_domain R] : integral_domain (hahn_series Γ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y xy, begin by_cases hx : x = 0, { left, exact hx }, right, contrapose! xy, rw [hahn_series.ext_iff, function.funext_iff, not_forall], refine ⟨x.is_wf_support.min (support_nonempty_iff.2 hx) + y.is_wf_support.min (support_nonempty_iff.2 xy), _⟩, rw [mul_coeff_min_add_min, zero_coeff, mul_eq_zero], simp [coeff_min_ne_zero, hx, xy], end, .. hahn_series.nontrivial, .. hahn_series.comm_ring } section semiring variables [semiring R] @[simp] lemma single_mul_single {a b : Γ} {r s : R} : single a r * single b s = single (a + b) (r * s) := begin ext x, by_cases h : x = a + b, { rw [h, mul_single_coeff_add], simp }, { rw [single_coeff_of_ne h, mul_coeff, sum_eq_zero], rintros ⟨y1, y2⟩ hy, obtain ⟨rfl, hy1, hy2⟩ := mem_add_antidiagonal.1 hy, rw [eq_of_mem_support_single hy1, eq_of_mem_support_single hy2] at h, exact (h rfl).elim } end /-- `C a` is the constant Hahn Series `a`. `C` is provided as a ring homomorphism. -/ def C : R →+* (hahn_series Γ R) := { to_fun := single 0, map_zero' := single_eq_zero, map_one' := rfl, map_add' := λ x y, by { ext a, by_cases h : a = 0; simp [h] }, map_mul' := λ x y, by rw [single_mul_single, zero_add] } @[simp] lemma C_apply (r : R) : C r = single (0 : Γ) r := rfl @[simp] lemma C_zero : C (0 : R) = (0 : hahn_series Γ R) := C.map_zero @[simp] lemma C_one : C (1 : R) = (1 : hahn_series Γ R) := C.map_one lemma C_mul_eq_smul {r : R} {x : hahn_series Γ R} : C r * x = r • x := single_zero_mul_eq_smul end semiring section algebra variables [comm_semiring R] {A : Type*} [semiring A] [algebra R A] instance : algebra R (hahn_series Γ A) := { to_ring_hom := C.comp (algebra_map R A), smul_def' := λ r x, by { ext, simp }, commutes' := λ r x, by { ext, simp only [smul_coeff, single_zero_mul_eq_smul, ring_hom.coe_comp, ring_hom.to_fun_eq_coe, C_apply, function.comp_app, algebra_map_smul, mul_single_zero_coeff], rw [← algebra.commutes, algebra.smul_def], }, } theorem C_eq_algebra_map : C = (algebra_map R (hahn_series Γ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (hahn_series Γ A) r = C (algebra_map R A r) := rfl instance [nontrivial Γ] [nontrivial R] : nontrivial (subalgebra R (hahn_series Γ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], obtain ⟨a, ha⟩ := exists_ne (0 : Γ), refine ⟨single a 1, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, function.funext_iff, not_forall], refine ⟨a, _⟩, rw [single_coeff_same, algebra_map_apply, C_apply, single_coeff_of_ne ha], exact zero_ne_one end⟩⟩ end algebra end multiplication section semiring variables [semiring R] /-- The ring `hahn_series ℕ R` is isomorphic to `power_series R`. -/ def to_power_series : (hahn_series ℕ R) ≃+* power_series R := { to_fun := λ f, power_series.mk f.coeff, inv_fun := λ f, ⟨λ n, power_series.coeff R n f, nat.lt_wf.is_wf _⟩, left_inv := λ f, by { ext, simp }, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, simp }, map_mul' := λ f g, begin ext n, simp only [power_series.coeff_mul, power_series.coeff_mk, mul_coeff, is_wf_support], classical, refine sum_filter_ne_zero.symm.trans ((sum_congr _ (λ _ _, rfl)).trans sum_filter_ne_zero), ext m, simp only [nat.mem_antidiagonal, and.congr_left_iff, mem_add_antidiagonal, ne.def, and_iff_left_iff_imp, mem_filter, mem_support], intros h1 h2, contrapose h1, rw ← decidable.or_iff_not_and_not at h1, cases h1; simp [h1] end } @[simp] lemma coeff_to_power_series {f : hahn_series ℕ R} {n : ℕ} : power_series.coeff R n f.to_power_series = f.coeff n := power_series.coeff_mk _ _ @[simp] lemma coeff_to_power_series_symm {f : power_series R} {n : ℕ} : (hahn_series.to_power_series.symm f).coeff n = power_series.coeff R n f := rfl end semiring section algebra variables (R) [comm_semiring R] {A : Type*} [semiring A] [algebra R A] /-- The `R`-algebra `hahn_series ℕ A` is isomorphic to `power_series A`. -/ def to_power_series_alg : (hahn_series ℕ A) ≃ₐ[R] power_series A := { commutes' := λ r, begin ext n, simp only [algebra_map_apply, power_series.algebra_map_apply, ring_equiv.to_fun_eq_coe, C_apply, coeff_to_power_series], cases n, { simp only [power_series.coeff_zero_eq_constant_coeff, single_coeff_same], refl }, { simp only [n.succ_ne_zero, ne.def, not_false_iff, single_coeff_of_ne], rw [power_series.coeff_C, if_neg n.succ_ne_zero] } end, .. to_power_series } @[simp] lemma to_power_series_alg_apply {f : hahn_series ℕ A} : hahn_series.to_power_series_alg R f = f.to_power_series := rfl @[simp] lemma to_power_series_alg_symm_apply {f : power_series A} : (hahn_series.to_power_series_alg R).symm f = hahn_series.to_power_series.symm f := rfl end algebra section valuation variables [linear_ordered_add_comm_group Γ] [integral_domain R] [nontrivial R] instance : linear_ordered_comm_group (multiplicative Γ) := { .. (infer_instance : linear_order (multiplicative Γ)), .. (infer_instance : ordered_comm_group (multiplicative Γ)) } instance : linear_ordered_comm_group_with_zero (with_zero (multiplicative Γ)) := { zero_le_one := with_zero.zero_le 1, .. (with_zero.ordered_comm_monoid), .. (infer_instance : linear_order (with_zero (multiplicative Γ))), .. (infer_instance : comm_group_with_zero (with_zero (multiplicative Γ))) } variables (Γ) (R) /-- The additive valuation on `hahn_series Γ R`, returning the smallest index at which a Hahn Series has a nonzero coefficient, or `⊤` for the 0 series. -/ def add_val : add_valuation (hahn_series Γ R) (with_top Γ) := add_valuation.of (λ x, if h : x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.is_wf_support.min (support_nonempty_iff.2 h)) (dif_pos rfl) ((dif_neg one_ne_zero).trans (by simp)) (λ x y, begin by_cases hx : x = 0, { by_cases hy : y = 0; { simp [hx, hy] } }, { by_cases hy : y = 0, { simp [hx, hy] }, { simp only [hx, hy, support_nonempty_iff, dif_neg, not_false_iff, is_wf_support, min_le_iff], by_cases hxy : x + y = 0, { simp [hxy] }, rw [dif_neg hxy, with_top.coe_le_coe, with_top.coe_le_coe, ← min_le_iff, ← set.is_wf.min_union], exact set.is_wf.min_le_min_of_subset support_add_subset, } }, end) (λ x y, begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [dif_neg hx, dif_neg hy, dif_neg (mul_ne_zero hx hy), ← with_top.coe_add, with_top.coe_eq_coe], apply le_antisymm, { apply set.is_wf.min_le, rw [mem_support, mul_coeff_min_add_min], exact mul_ne_zero (coeff_min_ne_zero hx) (coeff_min_ne_zero hy) }, { rw ← set.is_wf.min_add, exact set.is_wf.min_le_min_of_subset (support_mul_subset_add_support) }, end) variables {Γ} {R} lemma add_val_apply {x : hahn_series Γ R} : add_val Γ R x = if h : x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.is_wf_support.min (support_nonempty_iff.2 h) := add_valuation.of_apply _ @[simp] lemma add_val_apply_of_ne {x : hahn_series Γ R} (hx : x ≠ 0) : add_val Γ R x = x.is_wf_support.min (support_nonempty_iff.2 hx) := dif_neg hx end valuation end hahn_series
97284f4f7e7e42bf98f7e5fe0f571b27eed6e579
2d787ac9a5ab28a7d164cd13cee8a3cdc1e4680a
/src/my_exercises/06_sub_sequences.lean
f3375fe2df3b255f015ee018a13c6f85f30184c0
[ "Apache-2.0" ]
permissive
paulzfm/lean3-tutorials
8c113ec2c9494d401c8a877f094db93e5a631fd6
f41baf1c62c251976ec8dd9ccae9e85ec4c4d336
refs/heads/master
1,679,267,488,532
1,614,782,461,000
1,614,782,461,000
344,157,026
0
0
null
null
null
null
UTF-8
Lean
false
false
4,603
lean
import tuto_lib /- This file continues the elementary study of limits of sequences. It can be skipped if the previous file was too easy, it won't introduce any new tactic or trick. Remember useful lemmas: abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y abs_add (x y : ℝ) : |x + y| ≤ |x| + |y| abs_sub (x y : ℝ) : |x - y| = |y - x| ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q and the definition: def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε You can also use a property proved in the previous file: unique_limit : seq_limit u l → seq_limit u l' → l = l' def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m -/ variable { φ : ℕ → ℕ} /- The next lemma is proved by an easy induction, but we haven't seen induction in this tutorial. If you did the natural number game then you can delete the proof below and try to reconstruct it. -/ /-- An extraction is greater than id -/ lemma id_le_extraction' : extraction φ → ∀ n, n ≤ φ n := begin intros hyp n, induction n with n hn, { exact nat.zero_le _ }, { exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) }, end /-- Extractions take arbitrarily large values for arbitrarily large inputs. -/ -- 0039 lemma extraction_ge : extraction φ → ∀ N N', ∃ n ≥ N', φ n ≥ N := begin intros hyp n n', use max n n', split, { apply le_max_right, }, { calc n ≤ max n n' : by apply le_max_left ... ≤ φ (max n n') : by apply id_le_extraction' hyp, } end /-- A real number `a` is a cluster point of a sequence `u` if `u` has a subsequence converging to `a`. def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a -/ variables {u : ℕ → ℝ} {a l : ℝ} /- In the exercise, we use `∃ n ≥ N, ...` which is the abbreviation of `∃ n, n ≥ N ∧ ...`. Lean can read this abbreviation, but displays it as the confusing: `∃ (n : ℕ) (H : n ≥ N)` One gets used to it. Alternatively, one can get rid of it using the lemma exists_prop {p q : Prop} : (∃ (h : p), q) ↔ p ∧ q -/ /-- If `a` is a cluster point of `u` then there are values of `u` arbitrarily close to `a` for arbitrarily large input. -/ -- 0040 lemma near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε := begin intros hcp ε hε n, rcases hcp with ⟨φ, hφ, ha⟩, cases ha ε hε with N ha, rcases extraction_ge hφ n N with ⟨m, hm, hφ⟩, exact ⟨φ m, hφ, ha m hm⟩, end /- The above exercice can be done in five lines. Hint: you can use the anonymous constructor syntax when proving existential statements. -/ /-- If `u` tends to `l` then its subsequences tend to `l`. -/ -- 0041 lemma subseq_tendsto_of_tendsto' (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l := begin intros ε hε, cases h ε hε with N hN, use N, intros n hn, apply hN, calc N ≤ n : hn ... ≤ φ n : id_le_extraction' hφ n, end /-- If `u` tends to `l` all its cluster points are equal to `l`. -/ -- 0042 lemma cluster_limit (hl : seq_limit u l) (ha : cluster_point u a) : a = l := begin rcases ha with ⟨φ, hφ, h₁⟩, have h₂ : seq_limit (u ∘ φ) l, from subseq_tendsto_of_tendsto' hl hφ, exact unique_limit h₁ h₂, end /-- Cauchy_sequence sequence -/ def cauchy_sequence (u : ℕ → ℝ) := ∀ ε > 0, ∃ N, ∀ p q, p ≥ N → q ≥ N → |u p - u q| ≤ ε -- 0043 example : (∃ l, seq_limit u l) → cauchy_sequence u := begin rintros ⟨l, hl⟩ ε hε, cases hl (ε/2) (by linarith) with N hN, use N, intros p q hp hq, calc |u p - u q| = |(u p - l) + (l - u q)| : by ring ... ≤ |u p - l| + |l - u q| : by apply abs_add ... = |u p - l| + |u q - l| : by rw abs_sub l (u q) ... ≤ ε : by linarith [hN p hp, hN q hq] end /- In the next exercise, you can reuse near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε -/ -- 0044 example (hu : cauchy_sequence u) (hl : cluster_point u l) : seq_limit u l := begin intros ε hε, cases hu (ε/2) (by linarith) with N hN, rcases near_cluster hl (ε/2) (by linarith) N with ⟨m, hm, hl⟩, use N, intros n hn, calc |u n - l| = |(u n - u m) + (u m - l)| : by ring ... ≤ |u n - u m| + |u m - l| : by apply abs_add ... ≤ ε : by linarith [hN n m hn hm] end
8c3faedad85b9fe4f9527b7070475b6acde15ec9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/preadditive/additive_functor.lean
a03efebe32898724598fe399954e04f17a015f71
[ "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
5,364
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Scott Morrison -/ import category_theory.preadditive import category_theory.limits.shapes.biproducts /-! # Additive Functors A functor between two preadditive categories is called *additive* provided that the induced map on hom types is a morphism of abelian groups. An additive functor between preadditive categories creates and preserves biproducts. # Implementation details `functor.additive` is a `Prop`-valued class, defined by saying that for every two objects `X` and `Y`, the map `F.map : (X ⟶ Y) → (F.obj X ⟶ F.obj Y)` is a morphism of abelian groups. # Project: - Prove that a functor is additive if it preserves finite biproducts (See https://stacks.math.columbia.edu/tag/010M.) -/ namespace category_theory /-- A functor `F` is additive provided `F.map` is an additive homomorphism. -/ class functor.additive {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) : Prop := (map_zero' : Π {X Y : C}, F.map (0 : X ⟶ Y) = 0 . obviously) (map_add' : Π {X Y : C} {f g : X ⟶ Y}, F.map (f + g) = F.map f + F.map g . obviously) section preadditive namespace functor section variables {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) [functor.additive F] @[simp] lemma map_zero {X Y : C} : F.map (0 : X ⟶ Y) = 0 := functor.additive.map_zero' @[simp] lemma map_add {X Y : C} {f g : X ⟶ Y} : F.map (f + g) = F.map f + F.map g := functor.additive.map_add' instance : additive (𝟭 C) := {} instance {E : Type*} [category E] [preadditive E] (G : D ⥤ E) [functor.additive G] : additive (F ⋙ G) := {} /-- `F.map_add_hom` is an additive homomorphism whose underlying function is `F.map`. -/ @[simps] def map_add_hom {X Y : C} : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y) := { to_fun := λ f, F.map f, map_zero' := F.map_zero, map_add' := λ _ _, F.map_add } lemma coe_map_add_hom {X Y : C} : ⇑(F.map_add_hom : (X ⟶ Y) →+ _) = @map C _ D _ F X Y := rfl @[simp] lemma map_neg {X Y : C} {f : X ⟶ Y} : F.map (-f) = - F.map f := F.map_add_hom.map_neg _ @[simp] lemma map_sub {X Y : C} {f g : X ⟶ Y} : F.map (f - g) = F.map f - F.map g := F.map_add_hom.map_sub _ _ -- You can alternatively just use `functor.map_smul` here, with an explicit `(r : ℤ)` argument. lemma map_zsmul {X Y : C} {f : X ⟶ Y} {r : ℤ} : F.map (r • f) = r • F.map f := F.map_add_hom.map_zsmul _ _ open_locale big_operators @[simp] lemma map_sum {X Y : C} {α : Type*} (f : α → (X ⟶ Y)) (s : finset α) : F.map (∑ a in s, f a) = ∑ a in s, F.map (f a) := (F.map_add_hom : (X ⟶ Y) →+ _).map_sum f s open category_theory.limits open_locale zero_object /-- An additive functor takes the zero object to the zero object (up to isomorphism). -/ @[simps] def map_zero_object [has_zero_object C] [has_zero_object D] : F.obj 0 ≅ 0 := { hom := 0, inv := 0, hom_inv_id' := by { rw ←F.map_id, simp, } } end section induced_category variables {C : Type*} {D : Type*} [category D] [preadditive D] (F : C → D) instance induced_functor_additive : functor.additive (induced_functor F) := {} end induced_category section -- To talk about preservation of biproducts we need to specify universes explicitly. noncomputable theory universes v u₁ u₂ variables {C : Type u₁} {D : Type u₂} [category.{v} C] [category.{v} D] [preadditive C] [preadditive D] (F : C ⥤ D) [functor.additive F] open category_theory.limits /-- An additive functor between preadditive categories creates finite biproducts. -/ instance map_has_biproduct {J : Type v} [fintype J] [decidable_eq J] (f : J → C) [has_biproduct f] : has_biproduct (λ j, F.obj (f j)) := has_biproduct_of_total { X := F.obj (⨁ f), π := λ j, F.map (biproduct.π f j), ι := λ j, F.map (biproduct.ι f j), ι_π := λ j j', by { simp only [←F.map_comp], split_ifs, { subst h, simp, }, { simp [h], }, }, } (by simp_rw [←F.map_comp, ←F.map_sum, biproduct.total, functor.map_id]) /-- An additive functor between preadditive categories preserves finite biproducts. -/ -- This essentially repeats the work of the previous instance, -- but gives good definitional reduction to `biproduct.lift` and `biproduct.desc`. @[simps] def map_biproduct {J : Type v} [fintype J] [decidable_eq J] (f : J → C) [has_biproduct f] : F.obj (⨁ f) ≅ ⨁ (λ j, F.obj (f j)) := { hom := biproduct.lift (λ j, F.map (biproduct.π f j)), inv := biproduct.desc (λ j, F.map (biproduct.ι f j)), hom_inv_id' := by simp only [biproduct.lift_desc, ←F.map_comp, ←F.map_sum, biproduct.total, F.map_id], inv_hom_id' := begin ext j j', simp only [category.comp_id, category.assoc, biproduct.lift_π, biproduct.ι_desc_assoc, ←F.map_comp, biproduct.ι_π, F.map_dite, dif_ctx_congr, eq_to_hom_map, F.map_zero], end } end end functor namespace equivalence variables {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] instance inverse_additive (e : C ≌ D) [e.functor.additive] : e.inverse.additive := { map_zero' := λ X Y, by { apply e.functor.map_injective, simp, }, map_add' := λ X Y f g, by { apply e.functor.map_injective, simp, }, } end equivalence end preadditive end category_theory
4246bd2f3be3067061ee9ef44728e5b08019e38d
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/ring_theory/integral_domain.lean
6039a70ee385571acda1c93f1c449b2747ee7a8d
[ "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
6,413
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.fintype.card import data.polynomial import group_theory.order_of_element import algebra.geom_sum /-! # Integral domains -/ section open finset polynomial function open_locale big_operators nat variables {R : Type*} {G : Type*} [integral_domain R] [group G] [fintype G] lemma card_nth_roots_subgroup_units (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 apply card_le_card_of_inj_on f, { intros g hg, rw [sep_def, mem_filter] at hg, rw [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_integral_domain (f : G →* R) (hf : injective f) : is_cyclic G := begin haveI := classical.dec_eq 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. -/ instance [fintype R] : is_cyclic (units R) := is_cyclic_of_subgroup_integral_domain (units.coe_hom R) $ units.ext /-- Every finite integral domain is a field. -/ def field_of_integral_domain [fintype R] [decidable_eq R] : field R := { inv := λ a, if h : a = 0 then 0 else fintype.bij_inv (show function.bijective (* a), from fintype.injective_iff_bijective.1 $ λ _ _, (domain.mul_left_inj h).1) 1, mul_inv_cancel := λ a ha, show a * dite _ _ _ = _, by rw [dif_neg ha, mul_comm]; exact fintype.right_inverse_bij_inv (show function.bijective (* a), from _) 1, inv_zero := dif_pos rfl, ..show integral_domain R, by apply_instance } section variables (S : set (units R)) [is_subgroup S] [fintype 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_integral_domain ⟨(coe : S → R), _, _⟩ (units.ext.comp subtype.val_injective), { simp only [is_submonoid.coe_one, units.coe_one, coe_coe] }, { intros, simp only [is_submonoid.coe_mul, units.coe_mul, coe_coe] }, end end 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 : set.range f.to_hom_units, ∀ y : set.range f.to_hom_units, y ∈ powers x, from is_cyclic.exists_monoid_generator (set.range (f.to_hom_units)), 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, is_submonoid.coe_pow, units.coe_pow, is_submonoid.coe_one, units.coe_one, _root_.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 : units R in univ.image f.to_hom_units, (univ.filter (λ g, f.to_hom_units g = u)).card • u : sum_comp (coe : units R → R) f.to_hom_units ... = ∑ u : units R in univ.image f.to_hom_units, c • u : sum_congr rfl (λ u hu, congr_arg2 _ _ rfl) -- remaining goal 1, proven below ... = ∑ b : set.range f.to_hom_units, c • ↑b : finset.sum_subtype (by simp only [mem_image, set.mem_range, forall_const, iff_self, mem_univ, exists_prop_of_true]) _ ... = c • ∑ b : set.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 : set.range f.to_hom_units, (b : R) = 0, calc ∑ b : set.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 [is_submonoid.coe_pow, eq_self_iff_true, units.coe_pow, coe_coe, forall_true_iff]) (λ 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 [← domain.mul_left_inj hx1, zero_mul, ← geom_series, geom_sum_mul, coe_coe], norm_cast, rw [pow_order_of_eq_one, is_submonoid.coe_one, units.coe_one, sub_self], 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
cc7a07035a9d70454da6e4dd46d8def0d92a7b2b
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/topology/path_connected.lean
7380ad64bfe49ea97de62d9dc247274680e57015
[ "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
22,199
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.instances.real /-! # Path connectedness ## Main definitions In the file the unit interval `[0, 1]` in `ℝ` is denoted by `I`, and `X` is a topological space. * `path (x y : X)` is the type of paths from `x` to `y`, i.e., continuous maps from `I` to `X` mapping `0` to `x` and `1` to `y`. * `path.map` is the image of a path under a continuous map. * `joined (x y : X)` means there is a path between `x` and `y`. * `joined.some_path (h : joined x y)` selects some path between two points `x` and `y`. * `path_component (x : X)` is the set of points joined to `x`. * `path_connected_space X` is a predicate class asserting that `X` is non-empty and every two points of `X` are joined. Then there are corresponding relative notions for `F : set X`. * `joined_in F (x y : X)` means there is a path `γ` joining `x` to `y` with values in `F`. * `joined_in.some_path (h : joined_in F x y)` selects a path from `x` to `y` inside `F`. * `path_component_in F (x : X)` is the set of points joined to `x` in `F`. * `is_path_connected F` asserts that `F` is non-empty and every two points of `F` are joined in `F`. * `loc_path_connected_space X` is a predicate class asserting that `X` is locally path-connected: each point has a basis of path-connected neighborhoods (we do *not* ask these to be open). ## Main theorems * `joined` and `joined_in F` are transitive relations. One can link the absolute and relative version in two directions, using `(univ : set X)` or the subtype `↥F`. * `path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X)` * `is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space ↥F` For locally path connected spaces, we have * `path_connected_space_iff_connected_space : path_connected_space X ↔ connected_space X` * `is_connected_iff_is_path_connected (U_op : is_open U) : is_path_connected U ↔ is_connected U` ## Implementation notes By default, all paths have `I` as their source and `X` as their target, but there is an operation `I_extend` that will extend any continuous map `γ : I → X` into a continuous map `I_extend γ : ℝ → X` that is constant before `0` and after `1`. This is used to define `path.extend` that turns `γ : path x y` into a continuous map `γ.extend : ℝ → X` whose restriction to `I` is the original `γ`, and is equal to `x` on `(-∞, 0]` and to `y` on `[1, +∞)`. -/ noncomputable theory open_locale classical topological_space filter open filter set function variables {X : Type*} [topological_space X] {x y z : X} {ι : Type*} /-! ### The unit interval -/ local notation `I` := Icc (0 : ℝ) 1 lemma Icc_zero_one_symm {t : ℝ} : t ∈ I ↔ 1 - t ∈ I := begin rw [mem_Icc, mem_Icc], split ; intro ; split ; linarith end instance I_has_zero : has_zero I := ⟨⟨0, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_zero : ((0 : I) : ℝ) = 0 := rfl instance I_has_one : has_one I := ⟨⟨1, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_one : ((1 : I) : ℝ) = 1 := rfl /-- Unit interval central symmetry. -/ def I_symm : I → I := λ t, ⟨1 - t.val, Icc_zero_one_symm.mp t.property⟩ local notation `σ` := I_symm @[simp] lemma I_symm_zero : σ 0 = 1 := subtype.ext $ by simp [I_symm] @[simp] lemma I_symm_one : σ 1 = 0 := subtype.ext $ by simp [I_symm] @[continuity] lemma continuous_I_symm : continuous σ := by continuity! /-- Projection of `ℝ` onto its unit interval. -/ def proj_I : ℝ → I := λ t, if h : t ≤ 0 then ⟨0, left_mem_Icc.mpr zero_le_one⟩ else if h' : t ≤ 1 then ⟨t, ⟨le_of_lt $ not_le.mp h, h'⟩⟩ else ⟨1, right_mem_Icc.mpr zero_le_one⟩ lemma proj_I_I {t : ℝ} (h : t ∈ I) : proj_I t = ⟨t, h⟩ := begin unfold proj_I, rw mem_Icc at h, split_ifs, { simp [show t = 0, by linarith] }, { refl }, { exfalso, linarith } end lemma surjective_proj_I : surjective proj_I := λ ⟨t, t_in⟩, ⟨t, proj_I_I t_in⟩ lemma range_proj_I : range proj_I = univ := surjective_proj_I.range_eq @[continuity] lemma continuous_proj_I : continuous proj_I := begin refine continuous_induced_rng' (coe : I → ℝ) rfl _, have : continuous (λ t : ℝ, if t ≤ 0 then 0 else if t ≤ 1 then t else 1), { refine continuous_if _ continuous_const (continuous_if _ continuous_id continuous_const) ; simp [Iic_def, zero_le_one] }, convert this, ext, dsimp [proj_I], split_ifs ; refl end variables {β : Type*} /-- Extension of a function defined on the unit interval to `ℝ`, by precomposing with the projection. -/ def I_extend {β : Type*} (f : I → β) : ℝ → β := f ∘ proj_I @[continuity] lemma continuous.I_extend {f : I → X} (hf : continuous f) : continuous (I_extend f) := hf.comp continuous_proj_I lemma I_extend_extends (f : I → β) {t : ℝ} (ht : t ∈ I) : I_extend f t = f ⟨t, ht⟩ := by simp [I_extend, proj_I_I, ht] @[simp] lemma I_extend_zero (f : I → β) : I_extend f 0 = f 0 := I_extend_extends _ _ @[simp] lemma I_extend_one (f : I → β) : I_extend f 1 = f 1 := I_extend_extends _ _ @[simp] lemma I_extend_range (f : I → β) : range (I_extend f) = range f := surjective_proj_I.range_comp f instance : connected_space I := subtype.connected_space ⟨nonempty_Icc.mpr zero_le_one, is_preconnected_Icc⟩ instance : compact_space I := compact_iff_compact_space.1 compact_Icc /-! ### Paths -/ /-- Continuous path connecting two points `x` and `y` in a topological space -/ @[nolint has_inhabited_instance] structure path (x y : X) := (to_fun : I → X) (continuous' : continuous to_fun) (source' : to_fun 0 = x) (target' : to_fun 1 = y) instance : has_coe_to_fun (path x y) := ⟨_, path.to_fun⟩ namespace path variable (γ : path x y) @[continuity] protected lemma continuous : continuous γ := γ.continuous' @[simp] protected lemma source : γ 0 = x := γ.source' @[simp] protected lemma target : γ 1 = y := γ.target' /-- The constant path from a point to itself -/ @[refl] def refl (x : X) : path x x := { to_fun := λ t, x, continuous' := continuous_const, source' := rfl, target' := rfl } /-- The reverse of a path from `x` to `y`, as a path from `y` to `x` -/ @[symm] def symm (γ : path x y) : path y x := { to_fun := γ ∘ σ, continuous' := by continuity, source' := by simpa [-path.target] using γ.target, target' := by simpa [-path.source] using γ.source } /-- A continuous map extending a path to `ℝ`, constant before `0` and after `1`. -/ def extend : ℝ → X := I_extend γ lemma continuous_extend : continuous γ.extend := γ.continuous.I_extend @[simp] lemma extend_zero : γ.extend 0 = x := by simp [extend] @[simp] lemma extend_one : γ.extend 1 = y := by simp [extend] /-- The path obtained from a map defined on `ℝ` by restriction to the unit interval. -/ def of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : path x y := { to_fun := f ∘ coe, continuous' := hf.comp_continuous continuous_subtype_coe (by rw subtype.range_coe), source' := h₀, target' := h₁ } lemma of_line_mem {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : ∀ t, of_line hf h₀ h₁ t ∈ f '' I := λ ⟨t, t_in⟩, ⟨t, t_in, rfl⟩ local attribute [simp] Iic_def /-- Concatenation of two paths from `x` to `y` and from `y` to `z`, putting the first path on `[0, 1/2]` and the second one on `[1/2, 1]`. -/ @[trans] def trans (γ : path x y) (γ' : path y z) : path x z := { to_fun := (λ t : ℝ, if t ≤ 1/2 then γ.extend (2*t) else γ'.extend (2*t-1)) ∘ coe, continuous' := begin apply (continuous_if _ _ _).comp continuous_subtype_coe, { norm_num }, { continuity }, { continuity } end, source' := by norm_num, target' := by norm_num } /-- Image of a path from `x` to `y` by a continuous map -/ def map (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : path (f x) (f y) := { to_fun := f ∘ γ, continuous' := by continuity, source' := by simp, target' := by simp } @[simp] lemma map_coe (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : (γ.map h : I → Y) = f ∘ γ := by { ext t, refl } /-- Casting a path from `x` to `y` to a path from `x'` to `y'` when `x' = x` and `y' = y` -/ def cast (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : path x' y' := { to_fun := γ, continuous' := γ.continuous, source' := by simp [hx], target' := by simp [hy] } @[simp] lemma cast_coe (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : (γ.cast hx hy : I → X) = γ := rfl end path /-! ### Being joined by a path -/ /-- The relation "being joined by a path". This is an equivalence relation. -/ def joined (x y : X) : Prop := nonempty (path x y) @[refl] lemma joined.refl (x : X) : joined x x := ⟨path.refl x⟩ /-- When two points are joined, choose some path from `x` to `y`. -/ def joined.some_path (h : joined x y) : path x y := nonempty.some h @[symm] lemma joined.symm {x y : X} (h : joined x y) : joined y x := ⟨h.some_path.symm⟩ @[trans] lemma joined.trans {x y z : X} (hxy : joined x y) (hyz : joined y z) : joined x z := ⟨hxy.some_path.trans hyz.some_path⟩ variables (X) /-- The setoid corresponding the equivalence relation of being joined by a continuous path. -/ def path_setoid : setoid X := { r := joined, iseqv := mk_equivalence _ joined.refl (λ x y, joined.symm) (λ x y z, joined.trans) } /-- The quotient type of points of a topological space modulo being joined by a continuous path. -/ def zeroth_homotopy := quotient (path_setoid X) instance : inhabited (zeroth_homotopy ℝ) := ⟨@quotient.mk ℝ (path_setoid ℝ) 0⟩ variables {X} /-! ### Being joined by a path inside a set -/ /-- The relation "being joined by a path in `F`". Not quite an equivalence relation since it's not reflexive for points that do not belong to `F`. -/ def joined_in (F : set X) (x y : X) : Prop := ∃ γ : path x y, ∀ t, γ t ∈ F variables {F : set X} lemma joined_in.mem (h : joined_in F x y) : x ∈ F ∧ y ∈ F := begin rcases h with ⟨γ, γ_in⟩, have : γ 0 ∈ F ∧ γ 1 ∈ F, by { split; apply γ_in }, simpa using this end lemma joined_in.source_mem (h : joined_in F x y) : x ∈ F := h.mem.1 lemma joined_in.target_mem (h : joined_in F x y) : y ∈ F := h.mem.2 /-- When `x` and `y` are joined in `F`, choose a path from `x` to `y` inside `F` -/ def joined_in.some_path (h : joined_in F x y) : path x y := classical.some h lemma joined_in.some_path_mem (h : joined_in F x y) (t : I) : h.some_path t ∈ F := classical.some_spec h t /-- If `x` and `y` are joined in the set `F`, then they are joined in the subtype `F`. -/ lemma joined_in.joined_subtype (h : joined_in F x y) : joined (⟨x, h.source_mem⟩ : F) (⟨y, h.target_mem⟩ : F) := ⟨{ to_fun := λ t, ⟨h.some_path t, h.some_path_mem t⟩, continuous' := by continuity, source' := by simp, target' := by simp }⟩ lemma joined_in.of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) (hF : f '' I ⊆ F) : joined_in F x y := ⟨path.of_line hf h₀ h₁, λ t, hF $ path.of_line_mem hf h₀ h₁ t⟩ lemma joined_in.joined (h : joined_in F x y) : joined x y := ⟨h.some_path⟩ lemma joined_in_iff_joined (x_in : x ∈ F) (y_in : y ∈ F) : joined_in F x y ↔ joined (⟨x, x_in⟩ : F) (⟨y, y_in⟩ : F) := ⟨λ h, h.joined_subtype, λ h, ⟨h.some_path.map continuous_subtype_coe, by simp⟩⟩ @[simp] lemma joined_in_univ : joined_in univ x y ↔ joined x y := by simp [joined_in, joined, exists_true_iff_nonempty] lemma joined_in.mono {U V : set X} (h : joined_in U x y) (hUV : U ⊆ V) : joined_in V x y := ⟨h.some_path, λ t, hUV (h.some_path_mem t)⟩ lemma joined_in.refl (h : x ∈ F) : joined_in F x x := ⟨path.refl x, λ t, h⟩ @[symm] lemma joined_in.symm (h : joined_in F x y) : joined_in F y x := begin cases h.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact h.symm end lemma joined_in.trans (hxy : joined_in F x y) (hyz : joined_in F y z) : joined_in F x z := begin cases hxy.mem with hx hy, cases hyz.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact hxy.trans hyz end /-! ### Path component -/ /-- The path component of `x` is the set of points that can be joined to `x`. -/ def path_component (x : X) := {y | joined x y} @[simp] lemma mem_path_component_self (x : X) : x ∈ path_component x := joined.refl x @[simp] lemma path_component.nonempty (x : X) : (path_component x).nonempty := ⟨x, mem_path_component_self x⟩ lemma mem_path_component_of_mem (h : x ∈ path_component y) : y ∈ path_component x := joined.symm h lemma path_component_symm : x ∈ path_component y ↔ y ∈ path_component x := ⟨λ h, mem_path_component_of_mem h, λ h, mem_path_component_of_mem h⟩ lemma path_component_congr (h : x ∈ path_component y) : path_component x = path_component y := begin ext z, split, { intro h', rw path_component_symm, exact (h.trans h').symm }, { intro h', rw path_component_symm at h' ⊢, exact h'.trans h }, end lemma path_component_subset_component (x : X) : path_component x ⊆ connected_component x := λ y h, subset_connected_component (is_connected_range h.some_path.continuous).2 ⟨0, by simp⟩ ⟨1, by simp⟩ /-- The path component of `x` in `F` is the set of points that can be joined to `x` in `F`. -/ def path_component_in (x : X) (F : set X) := {y | joined_in F x y} @[simp] lemma path_component_in_univ (x : X) : path_component_in x univ = path_component x := by simp [path_component_in, path_component, joined_in, joined, exists_true_iff_nonempty] lemma joined.mem_path_component (hyz : joined y z) (hxy : y ∈ path_component x) : z ∈ path_component x := hxy.trans hyz /-! ### Path connected sets -/ /-- A set `F` is path connected if it contains a point that can be joined to all other in `F`. -/ def is_path_connected (F : set X) : Prop := ∃ x ∈ F, ∀ {y}, y ∈ F → joined_in F x y lemma is_path_connected_iff_eq : is_path_connected F ↔ ∃ x ∈ F, path_component_in x F = F := begin split ; rintros ⟨x, x_in, h⟩ ; use [x, x_in], { ext y, exact ⟨λ hy, hy.mem.2, h⟩ }, { intros y y_in, rwa ← h at y_in }, end lemma is_path_connected.joined_in (h : is_path_connected F) : ∀ x y ∈ F, joined_in F x y := λ x y x_in y_in, let ⟨b, b_in, hb⟩ := h in (hb x_in).symm.trans (hb y_in) lemma is_path_connected_iff : is_path_connected F ↔ F.nonempty ∧ ∀ x y ∈ F, joined_in F x y := ⟨λ h, ⟨let ⟨b, b_in, hb⟩ := h in ⟨b, b_in⟩, h.joined_in⟩, λ ⟨⟨b, b_in⟩, h⟩, ⟨b, b_in, λ x x_in, h b x b_in x_in⟩⟩ lemma is_path_connected.image {Y : Type*} [topological_space Y] (hF : is_path_connected F) {f : X → Y} (hf : continuous f) : is_path_connected (f '' F) := begin rcases hF with ⟨x, x_in, hx⟩, use [f x, mem_image_of_mem f x_in], rintros _ ⟨y, y_in, rfl⟩, exact ⟨(hx y_in).some_path.map hf, λ t, ⟨_, (hx y_in).some_path_mem t, rfl⟩⟩, end lemma is_path_connected.mem_path_component (h : is_path_connected F) (x_in : x ∈ F) (y_in : y ∈ F) : y ∈ path_component x := (h.joined_in x y x_in y_in).joined lemma is_path_connected.subset_path_component (h : is_path_connected F) (x_in : x ∈ F) : F ⊆ path_component x := λ y y_in, h.mem_path_component x_in y_in lemma is_path_connected.union {U V : set X} (hU : is_path_connected U) (hV : is_path_connected V) (hUV : (U ∩ V).nonempty) : is_path_connected (U ∪ V) := begin rcases hUV with ⟨x, xU, xV⟩, use [x, or.inl xU], rintros y (yU | yV), { exact (hU.joined_in x y xU yU).mono (subset_union_left U V) }, { exact (hV.joined_in x y xV yV).mono (subset_union_right U V) }, end /-- If a set `W` is path-connected, then it is also path-connected when seen as a set in a smaller ambient type `U` (when `U` contains `W`). -/ lemma is_path_connected.preimage_coe {U W : set X} (hW : is_path_connected W) (hWU : W ⊆ U) : is_path_connected ((coe : U → X) ⁻¹' W) := begin rcases hW with ⟨x, x_in, hx⟩, use [⟨x, hWU x_in⟩, by simp [x_in]], rintros ⟨y, hyU⟩ hyW, exact ⟨(hx hyW).joined_subtype.some_path.map (continuous_inclusion hWU), by simp⟩ end /-! ### Path connected spaces -/ /-- A topological space is path-connected if it is non-empty and every two points can be joined by a continuous path. -/ class path_connected_space (X : Type*) [topological_space X] : Prop := (nonempty : nonempty X) (joined : ∀ x y : X, joined x y) attribute [instance, priority 50] path_connected_space.nonempty lemma path_connected_space_iff_zeroth_homotopy : path_connected_space X ↔ nonempty (zeroth_homotopy X) ∧ subsingleton (zeroth_homotopy X) := begin letI := path_setoid X, split, { introI h, refine ⟨(nonempty_quotient_iff _).mpr h.1, ⟨_⟩⟩, rintros ⟨x⟩ ⟨y⟩, exact quotient.sound (path_connected_space.joined x y) }, { unfold zeroth_homotopy, rintros ⟨h, h'⟩, resetI, exact ⟨(nonempty_quotient_iff _).mp h, λ x y, quotient.exact $ subsingleton.elim ⟦x⟧ ⟦y⟧⟩ }, end namespace path_connected_space variables [path_connected_space X] /-- Use path-connectedness to build a path between two points. -/ def some_path (x y : X) : path x y := nonempty.some (joined x y) end path_connected_space lemma is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space F := begin rw is_path_connected_iff, split, { rintro ⟨⟨x, x_in⟩, h⟩, refine ⟨⟨⟨x, x_in⟩⟩, _⟩, rintros ⟨y, y_in⟩ ⟨z, z_in⟩, have H := h y z y_in z_in, rwa joined_in_iff_joined y_in z_in at H }, { rintros ⟨⟨x, x_in⟩, H⟩, refine ⟨⟨x, x_in⟩, λ y z y_in z_in, _⟩, rw joined_in_iff_joined y_in z_in, apply H } end lemma path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X) := begin split, { introI h, inhabit X, refine ⟨default X, mem_univ _, _⟩, simpa using path_connected_space.joined (default X) }, { intro h, have h' := h.joined_in, cases h with x h, exact ⟨⟨x⟩, by simpa using h'⟩ }, end lemma path_connected_space_iff_eq : path_connected_space X ↔ ∃ x : X, path_component x = univ := by simp [path_connected_space_iff_univ, is_path_connected_iff_eq] @[priority 100] -- see Note [lower instance priority] instance path_connected_space.connected_space [path_connected_space X] : connected_space X := begin rw connected_space_iff_connected_component, rcases is_path_connected_iff_eq.mp (path_connected_space_iff_univ.mp ‹_›) with ⟨x, x_in, hx⟩, use x, rw ← univ_subset_iff, exact (by simpa using hx : path_component x = univ) ▸ path_component_subset_component x end /-! ### Locally path connected spaces -/ /-- A topological space is locally path connected, at every point, path connected neighborhoods form a neighborhood basis. -/ class loc_path_connected_space (X : Type*) [topological_space X] : Prop := (path_connected_basis : ∀ x : X, (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s) id) export loc_path_connected_space (path_connected_basis) lemma loc_path_connected_of_bases {p : ι → Prop} {s : X → ι → set X} (h : ∀ x, (𝓝 x).has_basis p (s x)) (h' : ∀ x i, p i → is_path_connected (s x i)) : loc_path_connected_space X := begin constructor, intro x, apply (h x).to_has_basis, { intros i pi, exact ⟨s x i, ⟨(h x).mem_of_mem pi, h' x i pi⟩, by refl⟩ }, { rintros U ⟨U_in, hU⟩, rcases (h x).mem_iff.mp U_in with ⟨i, pi, hi⟩, tauto } end lemma path_connected_space_iff_connected_space [loc_path_connected_space X] : path_connected_space X ↔ connected_space X := begin split, { introI h, apply_instance }, { introI hX, inhabit X, let x₀ := default X, rw path_connected_space_iff_eq, use x₀, refine eq_univ_of_nonempty_clopen (by simp) ⟨_, _⟩, { rw is_open_iff_mem_nhds, intros y y_in, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, apply mem_sets_of_superset U_in, rw ← path_component_congr y_in, exact hU.subset_path_component (mem_of_nhds U_in) }, { rw is_closed_iff_nhds, intros y H, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, rcases H U U_in with ⟨z, hz, hz'⟩, exact ((hU.joined_in z y hz $ mem_of_nhds U_in).joined.mem_path_component hz') } }, end lemma path_connected_subset_basis [loc_path_connected_space X] {U : set X} (h : is_open U) (hx : x ∈ U) : (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s ∧ s ⊆ U) id := (path_connected_basis x).has_basis_self_subset (mem_nhds_sets h hx) lemma loc_path_connected_of_is_open [loc_path_connected_space X] {U : set X} (h : is_open U) : loc_path_connected_space U := ⟨begin rintros ⟨x, x_in⟩, rw nhds_subtype_eq_comap, constructor, intros V, rw (has_basis.comap (coe : U → X) (path_connected_subset_basis h x_in)).mem_iff, split, { rintros ⟨W, ⟨W_in, hW, hWU⟩, hWV⟩, exact ⟨coe ⁻¹' W, ⟨⟨preimage_mem_comap W_in, hW.preimage_coe hWU⟩, hWV⟩⟩ }, { rintros ⟨W, ⟨W_in, hW⟩, hWV⟩, refine ⟨coe '' W, ⟨filter.image_coe_mem_sets (mem_nhds_sets h x_in) W_in, hW.image continuous_subtype_coe, subtype.coe_image_subset U W⟩, _⟩, rintros x ⟨y, ⟨y_in, hy⟩⟩, rw ← subtype.coe_injective hy, tauto }, end⟩ lemma is_open.is_connected_iff_is_path_connected [loc_path_connected_space X] {U : set X} (U_op : is_open U) : is_path_connected U ↔ is_connected U := begin rw [is_connected_iff_connected_space, is_path_connected_iff_path_connected_space], haveI := loc_path_connected_of_is_open U_op, exact path_connected_space_iff_connected_space end
00b737368caacc8a4ecdb6eb1cb8fa093c11ecb1
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/field_theory/primitive_element.lean
c5f8dc421f5f7eea21dc2de5530007ab40ac0f0f
[ "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
9,098
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.adjoin import field_theory.is_alg_closed.basic import field_theory.separable import ring_theory.integral_domain /-! # Primitive Element Theorem In this file we prove the primitive element theorem. ## Main results - `exists_primitive_element`: a finite separable extension `E / F` has a primitive element, i.e. there is an `α : E` such that `F⟮α⟯ = (⊤ : subalgebra F E)`. ## Implementation notes In declaration names, `primitive_element` abbreviates `adjoin_simple_eq_top`: it stands for the statement `F⟮α⟯ = (⊤ : subalgebra F E)`. We did not add an extra declaration `is_primitive_element F α := F⟮α⟯ = (⊤ : subalgebra F E)` because this requires more unfolding without much obvious benefit. ## Tags primitive element, separable field extension, separable extension, intermediate field, adjoin, exists_adjoin_simple_eq_top -/ noncomputable theory open_locale classical open finite_dimensional polynomial intermediate_field namespace field section primitive_element_finite variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] /-! ### Primitive element theorem for finite fields -/ /-- **Primitive element theorem** assuming E is finite. -/ lemma exists_primitive_element_of_fintype_top [fintype E] : ∃ α : E, F⟮α⟯ = ⊤ := begin obtain ⟨α, hα⟩ := is_cyclic.exists_generator (units E), use α, apply eq_top_iff.mpr, rintros x -, by_cases hx : x = 0, { rw hx, exact F⟮α.val⟯.zero_mem }, { obtain ⟨n, hn⟩ := set.mem_range.mp (hα (units.mk0 x hx)), rw (show x = α^n, by { norm_cast, rw [hn, units.coe_mk0] }), exact pow_mem F⟮↑α⟯ (mem_adjoin_simple_self F ↑α) n, }, end /-- Primitive element theorem for finite dimensional extension of a finite field. -/ theorem exists_primitive_element_of_fintype_bot [fintype F] [finite_dimensional F E] : ∃ α : E, F⟮α⟯ = ⊤ := begin haveI : fintype E := fintype_of_fintype F E, exact exists_primitive_element_of_fintype_top F E, end end primitive_element_finite /-! ### Primitive element theorem for infinite fields -/ section primitive_element_inf variables {F : Type*} [field F] [infinite F] {E : Type*} [field E] (ϕ : F →+* E) (α β : E) lemma primitive_element_inf_aux_exists_c (f g : polynomial F) : ∃ c : F, ∀ (α' ∈ (f.map ϕ).roots) (β' ∈ (g.map ϕ).roots), -(α' - α)/(β' - β) ≠ ϕ c := begin let sf := (f.map ϕ).roots, let sg := (g.map ϕ).roots, let s := (sf.bind (λ α', sg.map (λ β', -(α' - α) / (β' - β)))).to_finset, let s' := s.preimage ϕ (λ x hx y hy h, ϕ.injective h), obtain ⟨c, hc⟩ := infinite.exists_not_mem_finset s', simp_rw [finset.mem_preimage, multiset.mem_to_finset, multiset.mem_bind, multiset.mem_map] at hc, push_neg at hc, exact ⟨c, hc⟩, end variables (F) [algebra F E] -- This is the heart of the proof of the primitive element theorem. It shows that if `F` is -- infinite and `α` and `β` are separable over `F` then `F⟮α, β⟯` is generated by a single element. lemma primitive_element_inf_aux [is_separable F E] : ∃ γ : E, F⟮α, β⟯ = F⟮γ⟯ := begin have hα := is_separable.is_integral F α, have hβ := is_separable.is_integral F β, let f := minpoly F α, let g := minpoly F β, let ιFE := algebra_map F E, let ιEE' := algebra_map E (splitting_field (g.map ιFE)), obtain ⟨c, hc⟩ := primitive_element_inf_aux_exists_c (ιEE'.comp ιFE) (ιEE' α) (ιEE' β) f g, let γ := α + c • β, suffices β_in_Fγ : β ∈ F⟮γ⟯, { use γ, apply le_antisymm, { rw adjoin_le_iff, have α_in_Fγ : α ∈ F⟮γ⟯, { rw ← add_sub_cancel α (c • β), exact F⟮γ⟯.sub_mem (mem_adjoin_simple_self F γ) (F⟮γ⟯.to_subalgebra.smul_mem β_in_Fγ c) }, exact λ x hx, by cases hx; cases hx; cases hx; assumption }, { rw adjoin_le_iff, change {γ} ⊆ _, rw set.singleton_subset_iff, have α_in_Fαβ : α ∈ F⟮α, β⟯ := subset_adjoin F {α, β} (set.mem_insert α {β}), have β_in_Fαβ : β ∈ F⟮α, β⟯ := subset_adjoin F {α, β} (set.mem_insert_of_mem α rfl), exact F⟮α,β⟯.add_mem α_in_Fαβ (F⟮α, β⟯.smul_mem β_in_Fαβ) } }, let p := euclidean_domain.gcd ((f.map (algebra_map F F⟮γ⟯)).comp (C (adjoin_simple.gen F γ) - (C ↑c * X))) (g.map (algebra_map F F⟮γ⟯)), let h := euclidean_domain.gcd ((f.map ιFE).comp (C γ - (C (ιFE c) * X))) (g.map ιFE), have map_g_ne_zero : g.map ιFE ≠ 0 := map_ne_zero (minpoly.ne_zero hβ), have h_ne_zero : h ≠ 0 := mt euclidean_domain.gcd_eq_zero_iff.mp (not_and.mpr (λ _, map_g_ne_zero)), suffices p_linear : p.map (algebra_map F⟮γ⟯ E) = (C h.leading_coeff) * (X - C β), { have finale : β = algebra_map F⟮γ⟯ E (-p.coeff 0 / p.coeff 1), { rw [ring_hom.map_div, ring_hom.map_neg, ←coeff_map, ←coeff_map, p_linear], simp [mul_sub, coeff_C, mul_div_cancel_left β (mt leading_coeff_eq_zero.mp h_ne_zero)] }, rw finale, exact subtype.mem (-p.coeff 0 / p.coeff 1) }, have h_sep : h.separable := separable_gcd_right _ (is_separable.separable F β).map, have h_root : h.eval β = 0, { apply eval_gcd_eq_zero, { rw [eval_comp, eval_sub, eval_mul, eval_C, eval_C, eval_X, eval_map, ←aeval_def, ←algebra.smul_def, add_sub_cancel, minpoly.aeval] }, { rw [eval_map, ←aeval_def, minpoly.aeval] } }, have h_splits : splits ιEE' h := splits_of_splits_gcd_right ιEE' map_g_ne_zero (splitting_field.splits _), have h_roots : ∀ x ∈ (h.map ιEE').roots, x = ιEE' β, { intros x hx, rw mem_roots_map h_ne_zero at hx, specialize hc ((ιEE' γ) - (ιEE' (ιFE c)) * x) (begin have f_root := root_left_of_root_gcd hx, rw [eval₂_comp, eval₂_sub, eval₂_mul,eval₂_C, eval₂_C, eval₂_X, eval₂_map] at f_root, exact (mem_roots_map (minpoly.ne_zero hα)).mpr f_root, end), specialize hc x (begin rw [mem_roots_map (minpoly.ne_zero hβ), ←eval₂_map], exact root_right_of_root_gcd hx, end), by_contradiction a, apply hc, apply (div_eq_iff (sub_ne_zero.mpr a)).mpr, simp only [algebra.smul_def, ring_hom.map_add, ring_hom.map_mul, ring_hom.comp_apply], ring }, rw ← eq_X_sub_C_of_separable_of_root_eq h_sep h_root h_splits h_roots, transitivity euclidean_domain.gcd (_ : polynomial E) (_ : polynomial E), { dsimp only [p], convert (gcd_map (algebra_map F⟮γ⟯ E)).symm }, { simpa [map_comp, polynomial.map_map, ←is_scalar_tower.algebra_map_eq, h] }, end end primitive_element_inf variables (F E : Type*) [field F] [field E] variables [algebra F E] [finite_dimensional F E] [is_separable F E] /-- Primitive element theorem: a finite separable field extension `E` of `F` has a primitive element, i.e. there is an `α ∈ E` such that `F⟮α⟯ = (⊤ : subalgebra F E)`.-/ theorem exists_primitive_element : ∃ α : E, F⟮α⟯ = ⊤ := begin rcases is_empty_or_nonempty (fintype F) with F_inf|⟨⟨F_finite⟩⟩, { let P : intermediate_field F E → Prop := λ K, ∃ α : E, F⟮α⟯ = K, have base : P ⊥ := ⟨0, adjoin_zero⟩, have ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯, { intros K β hK, cases hK with α hK, rw [←hK, adjoin_simple_adjoin_simple], haveI : infinite F := is_empty_fintype.mp F_inf, cases primitive_element_inf_aux F α β with γ hγ, exact ⟨γ, hγ.symm⟩ }, exact induction_on_adjoin P base ih ⊤ }, { exactI exists_primitive_element_of_fintype_bot F E } end /-- Alternative phrasing of primitive element theorem: a finite separable field extension has a basis `1, α, α^2, ..., α^n`. See also `exists_primitive_element`. -/ noncomputable def power_basis_of_finite_of_separable : power_basis F E := let α := (exists_primitive_element F E).some, pb := (adjoin.power_basis (is_separable.is_integral F α)) in have e : F⟮α⟯ = ⊤ := (exists_primitive_element F E).some_spec, pb.map ((intermediate_field.equiv_of_eq e).trans intermediate_field.top_equiv) /-- If `E / F` is a finite separable extension, then there are finitely many embeddings from `E` into `K` that fix `F`, corresponding to the number of conjugate roots of the primitive element generating `F`. -/ instance {K : Type*} [field K] [algebra F K] : fintype (E →ₐ[F] K) := power_basis.alg_hom.fintype (power_basis_of_finite_of_separable F E) end field @[simp] lemma alg_hom.card (F E K : Type*) [field F] [field E] [field K] [is_alg_closed K] [algebra F E] [finite_dimensional F E] [is_separable F E] [algebra F K] : fintype.card (E →ₐ[F] K) = finrank F E := (alg_hom.card_of_power_basis (field.power_basis_of_finite_of_separable F E) (is_separable.separable _ _) (is_alg_closed.splits_codomain _)).trans (power_basis.finrank _).symm
9b851a73441f74d6cc22282bf611b8ade6eaea14
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/algebra/euclidean_domain.lean
3b3195363f53b5145e75f12fba52c73d509cd162
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
13,694
lean
/- Copyright (c) 2018 Louis Carlin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Louis Carlin, Mario Carneiro Euclidean domains and Euclidean algorithm (extended to come) A lot is based on pre-existing code in mathlib for natural number gcds -/ import data.int.basic universe u section prio set_option default_priority 100 -- see Note [default priority] class euclidean_domain (α : Type u) extends nonzero_comm_ring α := (quotient : α → α → α) (quotient_zero : ∀ a, quotient a 0 = 0) (remainder : α → α → α) -- This could be changed to the same order as int.mod_add_div. -- We normally write qb+r rather than r + qb though. (quotient_mul_add_remainder_eq : ∀ a b, b * quotient a b + remainder a b = a) (r : α → α → Prop) (r_well_founded : well_founded r) (remainder_lt : ∀ a {b}, b ≠ 0 → r (remainder a b) b) /- `val_le_mul_left` is often not a required in definitions of a euclidean domain since given the other properties we can show there is a (noncomputable) euclidean domain α with the property `val_le_mul_left`. So potentially this definition could be split into two different ones (euclidean_domain_weak and euclidean_domain_strong) with a noncomputable function from weak to strong. I've currently divided the lemmas into strong and weak depending on whether they require `val_le_mul_left` or not. -/ (mul_left_not_lt : ∀ a {b}, b ≠ 0 → ¬r (a * b) a) end prio namespace euclidean_domain variable {α : Type u} variables [euclidean_domain α] local infix ` ≺ `:50 := euclidean_domain.r @[priority 70] -- see Note [lower instance priority] instance : has_div α := ⟨quotient⟩ @[priority 70] -- see Note [lower instance priority] instance : has_mod α := ⟨remainder⟩ theorem div_add_mod (a b : α) : b * (a / b) + a % b = a := quotient_mul_add_remainder_eq _ _ lemma mod_eq_sub_mul_div {α : Type*} [euclidean_domain α] (a b : α) : a % b = a - b * (a / b) := calc a % b = b * (a / b) + a % b - b * (a / b) : (add_sub_cancel' _ _).symm ... = a - b * (a / b) : by rw div_add_mod theorem mod_lt : ∀ a {b : α}, b ≠ 0 → (a % b) ≺ b := remainder_lt theorem mul_right_not_lt {a : α} (b) (h : a ≠ 0) : ¬(a * b) ≺ b := by rw mul_comm; exact mul_left_not_lt b h lemma mul_div_cancel_left {a : α} (b) (a0 : a ≠ 0) : a * b / a = b := eq.symm $ eq_of_sub_eq_zero $ classical.by_contradiction $ λ h, begin have := mul_left_not_lt a h, rw [mul_sub, sub_eq_iff_eq_add'.2 (div_add_mod (a*b) a).symm] at this, exact this (mod_lt _ a0) end lemma mul_div_cancel (a) {b : α} (b0 : b ≠ 0) : a * b / b = a := by rw mul_comm; exact mul_div_cancel_left a b0 @[simp] lemma mod_zero (a : α) : a % 0 = a := by simpa only [zero_mul, zero_add] using div_add_mod a 0 @[simp] lemma mod_eq_zero {a b : α} : a % b = 0 ↔ b ∣ a := ⟨λ h, by rw [← div_add_mod a b, h, add_zero]; exact dvd_mul_right _ _, λ ⟨c, e⟩, begin rw [e, ← add_left_cancel_iff, div_add_mod, add_zero], haveI := classical.dec, by_cases b0 : b = 0, { simp only [b0, zero_mul] }, { rw [mul_div_cancel_left _ b0] } end⟩ @[simp] lemma mod_self (a : α) : a % a = 0 := mod_eq_zero.2 (dvd_refl _) lemma dvd_mod_iff {a b c : α} (h : c ∣ b) : c ∣ a % b ↔ c ∣ a := by rw [dvd_add_iff_right (dvd_mul_of_dvd_left h _), div_add_mod] lemma lt_one (a : α) : a ≺ (1:α) → a = 0 := by haveI := classical.dec; exact not_imp_not.1 (λ h, by simpa only [one_mul] using mul_left_not_lt 1 h) lemma val_dvd_le : ∀ a b : α, b ∣ a → a ≠ 0 → ¬a ≺ b | _ b ⟨d, rfl⟩ ha := mul_left_not_lt b (mt (by rintro rfl; exact mul_zero _) ha) @[simp] lemma mod_one (a : α) : a % 1 = 0 := mod_eq_zero.2 (one_dvd _) @[simp] lemma zero_mod (b : α) : 0 % b = 0 := mod_eq_zero.2 (dvd_zero _) @[simp] lemma div_zero (a : α) : a / 0 = 0 := quotient_zero a @[simp] lemma zero_div {a : α} : 0 / a = 0 := classical.by_cases (λ a0 : a = 0, a0.symm ▸ div_zero 0) (λ a0, by simpa only [zero_mul] using mul_div_cancel 0 a0) @[simp] lemma div_self {a : α} (a0 : a ≠ 0) : a / a = 1 := by simpa only [one_mul] using mul_div_cancel 1 a0 lemma eq_div_of_mul_eq_left {a b c : α} (hb : b ≠ 0) (h : a * b = c) : a = c / b := by rw [← h, mul_div_cancel _ hb] lemma eq_div_of_mul_eq_right {a b c : α} (ha : a ≠ 0) (h : a * b = c) : b = c / a := by rw [← h, mul_div_cancel_left _ ha] theorem mul_div_assoc (x : α) {y z : α} (h : z ∣ y) : x * y / z = x * (y / z) := begin classical, by_cases hz : z = 0, { subst hz, rw [div_zero, div_zero, mul_zero] }, rcases h with ⟨p, rfl⟩, rw [mul_div_cancel_left _ hz, mul_left_comm, mul_div_cancel_left _ hz] end section open_locale classical @[elab_as_eliminator] theorem gcd.induction {P : α → α → Prop} : ∀ a b : α, (∀ x, P 0 x) → (∀ a b, a ≠ 0 → P (b % a) a → P a b) → P a b | a := λ b H0 H1, if a0 : a = 0 then by rw [a0]; apply H0 else have h:_ := mod_lt b a0, H1 _ _ a0 (gcd.induction (b%a) a H0 H1) using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} end section gcd variable [decidable_eq α] def gcd : α → α → α | a := λ b, if a0 : a = 0 then b else have h:_ := mod_lt b a0, gcd (b%a) a using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = a := by rw gcd; exact if_pos rfl @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = a := by rw gcd; split_ifs; simp only [h, zero_mod, gcd_zero_left] theorem gcd_val (a b : α) : gcd a b = gcd (b % a) a := by rw gcd; split_ifs; [simp only [h, mod_zero, gcd_zero_right], refl] theorem gcd_dvd (a b : α) : gcd a b ∣ a ∧ gcd a b ∣ b := gcd.induction a b (λ b, by rw [gcd_zero_left]; exact ⟨dvd_zero _, dvd_refl _⟩) (λ a b aneq ⟨IH₁, IH₂⟩, by rw gcd_val; exact ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (a b : α) : gcd a b ∣ a := (gcd_dvd a b).left theorem gcd_dvd_right (a b : α) : gcd a b ∣ b := (gcd_dvd a b).right protected theorem gcd_eq_zero_iff {a b : α} : gcd a b = 0 ↔ a = 0 ∧ b = 0 := ⟨λ h, by simpa [h] using gcd_dvd a b, by rintro ⟨rfl, rfl⟩; simp⟩ theorem dvd_gcd {a b c : α} : c ∣ a → c ∣ b → c ∣ gcd a b := gcd.induction a b (λ _ _ H, by simpa only [gcd_zero_left] using H) (λ a b a0 IH ca cb, by rw gcd_val; exact IH ((dvd_mod_iff ca).2 cb) ca) theorem gcd_eq_left {a b : α} : gcd a b = a ↔ a ∣ b := ⟨λ h, by rw ← h; apply gcd_dvd_right, λ h, by rw [gcd_val, mod_eq_zero.2 h, gcd_zero_left]⟩ @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := gcd_eq_left.2 (one_dvd _) @[simp] theorem gcd_self (a : α) : gcd a a = a := gcd_eq_left.2 (dvd_refl _) def xgcd_aux : α → α → α → α → α → α → α × α × α | r := λ s t r' s' t', if hr : r = 0 then (r', s', t') else have r' % r ≺ r, from mod_lt _ hr, let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} @[simp] theorem xgcd_zero_left {s t r' s' t' : α} : xgcd_aux 0 s t r' s' t' = (r', s', t') := by unfold xgcd_aux; exact if_pos rfl theorem xgcd_aux_rec {r s t r' s' t' : α} (h : r ≠ 0) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t := by conv {to_lhs, rw [xgcd_aux]}; exact if_neg h /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : α) : α × α := (xgcd_aux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a (x y : α) : α := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b (x y : α) : α := (xgcd x y).2 @[simp] theorem xgcd_aux_fst (x y : α) : ∀ s t s' t', (xgcd_aux x s t y s' t').1 = gcd x y := gcd.induction x y (by intros; rw [xgcd_zero_left, gcd_zero_left]) (λ x y h IH s t s' t', by simp only [xgcd_aux_rec h, if_neg h, IH]; rw ← gcd_val) theorem xgcd_aux_val (x y : α) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1, prod.mk.eta] theorem xgcd_val (x y : α) : xgcd x y = (gcd_a x y, gcd_b x y) := prod.mk.eta.symm private def P (a b : α) : α × α × α → Prop | (r, s, t) := (r : α) = a * s + b * t theorem xgcd_aux_P (a b : α) {r r' : α} : ∀ {s t s' t'}, P a b (r, s, t) → P a b (r', s', t') → P a b (xgcd_aux r s t r' s' t') := gcd.induction r r' (by intros; simpa only [xgcd_zero_left]) $ λ x y h IH s t s' t' p p', begin rw [xgcd_aux_rec h], refine IH _ p, unfold P at p p' ⊢, rw [mul_sub, mul_sub, add_sub, sub_add_eq_add_sub, ← p', sub_sub, mul_comm _ s, ← mul_assoc, mul_comm _ t, ← mul_assoc, ← add_mul, ← p, mod_eq_sub_mul_div] end theorem gcd_eq_gcd_ab (a b : α) : (gcd a b : α) = a * gcd_a a b + b * gcd_b a b := by have := @xgcd_aux_P _ _ _ a b a b 1 0 0 1 (by rw [P, mul_one, mul_zero, add_zero]) (by rw [P, mul_one, mul_zero, zero_add]); rwa [xgcd_aux_val, xgcd_val] at this @[priority 70] -- see Note [lower instance priority] instance (α : Type*) [e : euclidean_domain α] : integral_domain α := by haveI := classical.dec_eq α; exact { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b (h : a * b = 0), or_iff_not_and_not.2 $ λ h0 : a ≠ 0 ∧ b ≠ 0, h0.1 $ by rw [← mul_div_cancel a h0.2, h, zero_div], ..e } end gcd section lcm variables [decidable_eq α] def lcm (x y : α) : α := x * y / gcd x y theorem dvd_lcm_left (x y : α) : x ∣ lcm x y := classical.by_cases (assume hxy : gcd x y = 0, by rw [lcm, hxy, div_zero]; exact dvd_zero _) (λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).2 in ⟨z, eq.symm $ eq_div_of_mul_eq_left hxy $ by rw [mul_right_comm, mul_assoc, ← hz]⟩) theorem dvd_lcm_right (x y : α) : y ∣ lcm x y := classical.by_cases (assume hxy : gcd x y = 0, by rw [lcm, hxy, div_zero]; exact dvd_zero _) (λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).1 in ⟨z, eq.symm $ eq_div_of_mul_eq_right hxy $ by rw [← mul_assoc, mul_right_comm, ← hz]⟩) theorem lcm_dvd {x y z : α} (hxz : x ∣ z) (hyz : y ∣ z) : lcm x y ∣ z := begin rw lcm, by_cases hxy : gcd x y = 0, { rw [hxy, div_zero], rw euclidean_domain.gcd_eq_zero_iff at hxy, rwa hxy.1 at hxz }, rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, suffices : x * y ∣ z * gcd x y, { cases this with p hp, use p, generalize_hyp : gcd x y = g at hxy hs hp ⊢, subst hs, rw [mul_left_comm, mul_div_cancel_left _ hxy, ← domain.mul_left_inj hxy, hp], rw [← mul_assoc], simp only [mul_right_comm] }, rw [gcd_eq_gcd_ab, mul_add], apply dvd_add, { rw mul_left_comm, exact mul_dvd_mul_left _ (dvd_mul_of_dvd_left hyz _) }, { rw [mul_left_comm, mul_comm], exact mul_dvd_mul_left _ (dvd_mul_of_dvd_left hxz _) } end @[simp] lemma lcm_dvd_iff {x y z : α} : lcm x y ∣ z ↔ x ∣ z ∧ y ∣ z := ⟨λ hz, ⟨dvd_trans (dvd_lcm_left _ _) hz, dvd_trans (dvd_lcm_right _ _) hz⟩, λ ⟨hxz, hyz⟩, lcm_dvd hxz hyz⟩ @[simp] lemma lcm_zero_left (x : α) : lcm 0 x = 0 := by rw [lcm, zero_mul, zero_div] @[simp] lemma lcm_zero_right (x : α) : lcm x 0 = 0 := by rw [lcm, mul_zero, zero_div] @[simp] lemma lcm_eq_zero_iff {x y : α} : lcm x y = 0 ↔ x = 0 ∨ y = 0 := begin split, { intro hxy, rw [lcm, mul_div_assoc _ (gcd_dvd_right _ _), mul_eq_zero] at hxy, apply or_of_or_of_imp_right hxy, intro hy, by_cases hgxy : gcd x y = 0, { rw euclidean_domain.gcd_eq_zero_iff at hgxy, exact hgxy.2 }, { rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, generalize_hyp : gcd x y = g at hr hs hy hgxy ⊢, subst hs, rw [mul_div_cancel_left _ hgxy] at hy, rw [hy, mul_zero] } }, rintro (hx | hy), { rw [hx, lcm_zero_left] }, { rw [hy, lcm_zero_right] } end @[simp] lemma gcd_mul_lcm (x y : α) : gcd x y * lcm x y = x * y := begin rw lcm, by_cases h : gcd x y = 0, { rw [h, zero_mul], rw euclidean_domain.gcd_eq_zero_iff at h, rw [h.1, zero_mul] }, rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, generalize_hyp : gcd x y = g at h hr ⊢, subst hr, rw [mul_assoc, mul_div_cancel_left _ h] end end lcm end euclidean_domain open euclidean_domain instance int.euclidean_domain : euclidean_domain ℤ := { quotient := (/), quotient_zero := int.div_zero, remainder := (%), quotient_mul_add_remainder_eq := λ a b, by rw add_comm; exact int.mod_add_div _ _, r := λ a b, a.nat_abs < b.nat_abs, r_well_founded := measure_wf (λ a, int.nat_abs a), remainder_lt := λ a b b0, int.coe_nat_lt.1 $ by rw [int.nat_abs_of_nonneg (int.mod_nonneg _ b0), ← int.abs_eq_nat_abs]; exact int.mod_lt _ b0, mul_left_not_lt := λ a b b0, not_lt_of_ge $ by rw [← mul_one a.nat_abs, int.nat_abs_mul]; exact mul_le_mul_of_nonneg_left (int.nat_abs_pos_of_ne_zero b0) (nat.zero_le _) } @[priority 100] -- see Note [lower instance priority] instance field.to_euclidean_domain {K : Type u} [field K] : euclidean_domain K := { quotient := (/), remainder := λ a b, a - a * b / b, quotient_zero := div_zero, quotient_mul_add_remainder_eq := λ a b, by classical; by_cases b = 0; simp [h, mul_div_cancel'], r := λ a b, a = 0 ∧ b ≠ 0, r_well_founded := well_founded.intro $ λ a, acc.intro _ $ λ b ⟨hb, hna⟩, acc.intro _ $ λ c ⟨hc, hnb⟩, false.elim $ hnb hb, remainder_lt := λ a b hnb, by simp [hnb], mul_left_not_lt := λ a b hnb ⟨hab, hna⟩, or.cases_on (mul_eq_zero.1 hab) hna hnb }
cdc8d1ac478aa3b0f86eb29b5aaa82de647c9515
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/order/group/abs.lean
da98dd2c757a75f5feae17597f0a405bbcb472ee
[ "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
10,001
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.abs import algebra.order.group.order_iso import order.min_max /-! # Absolute values in ordered groups. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} open function section covariant_add_le section has_neg /-- `abs a` is the absolute value of `a`. -/ @[to_additive "`abs a` is the absolute value of `a`", priority 100] -- see Note [lower instance priority] instance has_inv.to_has_abs [has_inv α] [has_sup α] : has_abs α := ⟨λ a, a ⊔ a⁻¹⟩ @[to_additive] lemma abs_eq_sup_inv [has_inv α] [has_sup α] (a : α) : |a| = a ⊔ a⁻¹ := rfl variables [has_neg α] [linear_order α] {a b: α} lemma abs_eq_max_neg : abs a = max a (-a) := rfl lemma abs_choice (x : α) : |x| = x ∨ |x| = -x := max_choice _ _ lemma abs_le' : |a| ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff lemma le_abs : a ≤ |b| ↔ a ≤ b ∨ a ≤ -b := le_max_iff lemma le_abs_self (a : α) : a ≤ |a| := le_max_left _ _ lemma neg_le_abs_self (a : α) : -a ≤ |a| := le_max_right _ _ lemma lt_abs : a < |b| ↔ a < b ∨ a < -b := lt_max_iff theorem abs_le_abs (h₀ : a ≤ b) (h₁ : -a ≤ b) : |a| ≤ |b| := (abs_le'.2 ⟨h₀, h₁⟩).trans (le_abs_self b) lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (|a|) := sup_ind _ _ h1 h2 end has_neg section add_group variables [add_group α] [linear_order α] @[simp] lemma abs_neg (a : α) : | -a| = |a| := begin rw [abs_eq_max_neg, max_comm, neg_neg, abs_eq_max_neg] end lemma eq_or_eq_neg_of_abs_eq {a b : α} (h : |a| = b) : a = b ∨ a = -b := by simpa only [← h, eq_comm, eq_neg_iff_eq_neg] using abs_choice a lemma abs_eq_abs {a b : α} : |a| = |b| ↔ a = b ∨ a = -b := begin refine ⟨λ h, _, λ h, _⟩, { obtain rfl | rfl := eq_or_eq_neg_of_abs_eq h; simpa only [neg_eq_iff_neg_eq, neg_inj, or.comm, @eq_comm _ (-b)] using abs_choice b }, { cases h; simp only [h, abs_neg] }, end lemma abs_sub_comm (a b : α) : |a - b| = |b - a| := calc |a - b| = | - (b - a)| : congr_arg _ (neg_sub b a).symm ... = |b - a| : abs_neg (b - a) variables [covariant_class α α (+) (≤)] {a b c : α} lemma abs_of_nonneg (h : 0 ≤ a) : |a| = a := max_eq_left $ (neg_nonpos.2 h).trans h lemma abs_of_pos (h : 0 < a) : |a| = a := abs_of_nonneg h.le lemma abs_of_nonpos (h : a ≤ 0) : |a| = -a := max_eq_right $ h.trans (neg_nonneg.2 h) lemma abs_of_neg (h : a < 0) : |a| = -a := abs_of_nonpos h.le lemma abs_le_abs_of_nonneg (ha : 0 ≤ a) (hab : a ≤ b) : |a| ≤ |b| := by rwa [abs_of_nonneg ha, abs_of_nonneg (ha.trans hab)] @[simp] lemma abs_zero : |0| = (0:α) := abs_of_nonneg le_rfl @[simp] lemma abs_pos : 0 < |a| ↔ a ≠ 0 := begin rcases lt_trichotomy a 0 with (ha|rfl|ha), { simp [abs_of_neg ha, neg_pos, ha.ne, ha] }, { simp }, { simp [abs_of_pos ha, ha, ha.ne.symm] } end lemma abs_pos_of_pos (h : 0 < a) : 0 < |a| := abs_pos.2 h.ne.symm lemma abs_pos_of_neg (h : a < 0) : 0 < |a| := abs_pos.2 h.ne lemma neg_abs_le_self (a : α) : -|a| ≤ a := begin cases le_total 0 a with h h, { calc -|a| = - a : congr_arg (has_neg.neg) (abs_of_nonneg h) ... ≤ 0 : neg_nonpos.mpr h ... ≤ a : h }, { calc -|a| = - - a : congr_arg (has_neg.neg) (abs_of_nonpos h) ... ≤ a : (neg_neg a).le } end lemma add_abs_nonneg (a : α) : 0 ≤ a + |a| := begin rw ←add_right_neg a, apply add_le_add_left, exact (neg_le_abs_self a), end lemma neg_abs_le_neg (a : α) : -|a| ≤ -a := by simpa using neg_abs_le_self (-a) @[simp] lemma abs_nonneg (a : α) : 0 ≤ |a| := (le_total 0 a).elim (λ h, h.trans (le_abs_self a)) (λ h, (neg_nonneg.2 h).trans $ neg_le_abs_self a) @[simp] lemma abs_abs (a : α) : | |a| | = |a| := abs_of_nonneg $ abs_nonneg a @[simp] lemma abs_eq_zero : |a| = 0 ↔ a = 0 := decidable.not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos @[simp] lemma abs_nonpos_iff {a : α} : |a| ≤ 0 ↔ a = 0 := (abs_nonneg a).le_iff_eq.trans abs_eq_zero variable [covariant_class α α (swap (+)) (≤)] lemma abs_le_abs_of_nonpos (ha : a ≤ 0) (hab : b ≤ a) : |a| ≤ |b| := by { rw [abs_of_nonpos ha, abs_of_nonpos (hab.trans ha)], exact neg_le_neg_iff.mpr hab } lemma abs_lt : |a| < b ↔ - b < a ∧ a < b := max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt] lemma neg_lt_of_abs_lt (h : |a| < b) : -b < a := (abs_lt.mp h).1 lemma lt_of_abs_lt (h : |a| < b) : a < b := (abs_lt.mp h).2 lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = |a - b| := begin cases le_total a b with ab ba, { rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos }, { rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], rwa sub_nonneg } end lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = |b - a| := by { rw abs_sub_comm, exact max_sub_min_eq_abs' _ _ } end add_group end covariant_add_le section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] {a b c d : α} lemma abs_le : |a| ≤ b ↔ - b ≤ a ∧ a ≤ b := by rw [abs_le', and.comm, neg_le] lemma le_abs' : a ≤ |b| ↔ b ≤ -a ∨ a ≤ b := by rw [le_abs, or.comm, le_neg] lemma neg_le_of_abs_le (h : |a| ≤ b) : -b ≤ a := (abs_le.mp h).1 lemma le_of_abs_le (h : |a| ≤ b) : a ≤ b := (abs_le.mp h).2 @[to_additive] lemma apply_abs_le_mul_of_one_le' {β : Type*} [mul_one_class β] [preorder β] [covariant_class β β (*) (≤)] [covariant_class β β (swap (*)) (≤)] {f : α → β} {a : α} (h₁ : 1 ≤ f a) (h₂ : 1 ≤ f (-a)) : f (|a|) ≤ f a * f (-a) := (le_total a 0).by_cases (λ ha, (abs_of_nonpos ha).symm ▸ le_mul_of_one_le_left' h₁) (λ ha, (abs_of_nonneg ha).symm ▸ le_mul_of_one_le_right' h₂) @[to_additive] lemma apply_abs_le_mul_of_one_le {β : Type*} [mul_one_class β] [preorder β] [covariant_class β β (*) (≤)] [covariant_class β β (swap (*)) (≤)] {f : α → β} (h : ∀ x, 1 ≤ f x) (a : α) : f (|a|) ≤ f a * f (-a) := apply_abs_le_mul_of_one_le' (h _) (h _) /-- The **triangle inequality** in `linear_ordered_add_comm_group`s. -/ lemma abs_add (a b : α) : |a + b| ≤ |a| + |b| := abs_le.2 ⟨(neg_add (|a|) (|b|)).symm ▸ add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _), add_le_add (le_abs_self _) (le_abs_self _)⟩ lemma abs_add' (a b : α) : |a| ≤ |b| + |b + a| := by simpa using abs_add (-b) (b + a) theorem abs_sub (a b : α) : |a - b| ≤ |a| + |b| := by { rw [sub_eq_add_neg, ←abs_neg b], exact abs_add a _ } lemma abs_sub_le_iff : |a - b| ≤ c ↔ a - b ≤ c ∧ b - a ≤ c := by rw [abs_le, neg_le_sub_iff_le_add, sub_le_iff_le_add', and_comm, sub_le_iff_le_add'] lemma abs_sub_lt_iff : |a - b| < c ↔ a - b < c ∧ b - a < c := by rw [abs_lt, neg_lt_sub_iff_lt_add', sub_lt_iff_lt_add', and_comm, sub_lt_iff_lt_add'] lemma sub_le_of_abs_sub_le_left (h : |a - b| ≤ c) : b - c ≤ a := sub_le_comm.1 $ (abs_sub_le_iff.1 h).2 lemma sub_le_of_abs_sub_le_right (h : |a - b| ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub_comm a b ▸ h) lemma sub_lt_of_abs_sub_lt_left (h : |a - b| < c) : b - c < a := sub_lt_comm.1 $ (abs_sub_lt_iff.1 h).2 lemma sub_lt_of_abs_sub_lt_right (h : |a - b| < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub_comm a b ▸ h) lemma abs_sub_abs_le_abs_sub (a b : α) : |a| - |b| ≤ |a - b| := sub_le_iff_le_add.2 $ calc |a| = |a - b + b| : by rw [sub_add_cancel] ... ≤ |a - b| + |b| : abs_add _ _ lemma abs_abs_sub_abs_le_abs_sub (a b : α) : | |a| - |b| | ≤ |a - b| := abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub_comm; apply abs_sub_abs_le_abs_sub⟩ lemma abs_eq (hb : 0 ≤ b) : |a| = b ↔ a = b ∨ a = -b := begin refine ⟨eq_or_eq_neg_of_abs_eq, _⟩, rintro (rfl|rfl); simp only [abs_neg, abs_of_nonneg hb] end lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : |b| ≤ max (|a|) (|c|) := abs_le'.2 ⟨by simp [hbc.trans (le_abs_self c)], by simp [(neg_le_neg_iff.mpr hab).trans (neg_le_abs_self a)]⟩ lemma min_abs_abs_le_abs_max : min (|a|) (|b|) ≤ |max a b| := (le_total a b).elim (λ h, (min_le_right _ _).trans_eq $ congr_arg _ (max_eq_right h).symm) (λ h, (min_le_left _ _).trans_eq $ congr_arg _ (max_eq_left h).symm) lemma min_abs_abs_le_abs_min : min (|a|) (|b|) ≤ |min a b| := (le_total a b).elim (λ h, (min_le_left _ _).trans_eq $ congr_arg _ (min_eq_left h).symm) (λ h, (min_le_right _ _).trans_eq $ congr_arg _ (min_eq_right h).symm) lemma abs_max_le_max_abs_abs : |max a b| ≤ max (|a|) (|b|) := (le_total a b).elim (λ h, (congr_arg _ $ max_eq_right h).trans_le $ le_max_right _ _) (λ h, (congr_arg _ $ max_eq_left h).trans_le $ le_max_left _ _) lemma abs_min_le_max_abs_abs : |min a b| ≤ max (|a|) (|b|) := (le_total a b).elim (λ h, (congr_arg _ $ min_eq_left h).trans_le $ le_max_left _ _) (λ h, (congr_arg _ $ min_eq_right h).trans_le $ le_max_right _ _) lemma eq_of_abs_sub_eq_zero {a b : α} (h : |a - b| = 0) : a = b := sub_eq_zero.1 $ abs_eq_zero.1 h lemma abs_sub_le (a b c : α) : |a - c| ≤ |a - b| + |b - c| := calc |a - c| = |a - b + (b - c)| : by rw [sub_add_sub_cancel] ... ≤ |a - b| + |b - c| : abs_add _ _ lemma abs_add_three (a b c : α) : |a + b + c| ≤ |a| + |b| + |c| := (abs_add _ _).trans (add_le_add_right (abs_add _ _) _) lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : |a - b| ≤ ub - lb := abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩ lemma eq_of_abs_sub_nonpos (h : |a - b| ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) end linear_ordered_add_comm_group
48f544a7144cf0e2b3171ea1b467c97572fe32ae
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/topology/continuous_function/compact.lean
ade58a4b6b6d4c99b4636d509926c6747707b300
[ "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
4,802
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.continuous_function.bounded import analysis.normed_space.linear_isometry import tactic.equiv_rw /-! # Continuous functions on a compact space Continuous functions `C(α, β)` from a compact space `α` to a metric space `β` are automatically bounded, and so acquire various structures inherited from `α →ᵇ β`. This file transfers these structures, and restates some lemmas characterising these structures. If you need a lemma which is proved about `α →ᵇ β` but not for `C(α, β)` when `α` is compact, you should restate it here. You can also use `bounded_continuous_function.equiv_continuous_map_of_compact` to functions back and forth. -/ noncomputable theory open_locale topological_space classical nnreal bounded_continuous_function open set filter metric variables (α : Type*) (β : Type*) [topological_space α] [compact_space α] [normed_group β] open bounded_continuous_function namespace continuous_map /-- When `α` is compact, the bounded continuous maps `α →ᵇ 𝕜` are equivalent to `C(α, 𝕜)`. -/ @[simps] def equiv_bounded_of_compact : C(α, β) ≃ (α →ᵇ β) := ⟨mk_of_compact, forget_boundedness α β, λ f, by { ext, refl, }, λ f, by { ext, refl, }⟩ /-- When `α` is compact, the bounded continuous maps `α →ᵇ 𝕜` are additively equivalent to `C(α, 𝕜)`. -/ @[simps] def add_equiv_bounded_of_compact : C(α, β) ≃+ (α →ᵇ β) := ({ ..forget_boundedness_add_hom α β, ..(equiv_bounded_of_compact α β).symm, } : (α →ᵇ β) ≃+ C(α, β)).symm -- It would be nice if `@[simps]` produced this directly, -- instead of the unhelpful `add_equiv_bounded_of_compact_apply_to_continuous_map`. @[simp] lemma add_equiv_bounded_of_compact_apply_apply (f : C(α, β)) (a : α) : add_equiv_bounded_of_compact α β f a = f a := rfl @[simp] lemma add_equiv_bounded_of_compact_to_equiv : (add_equiv_bounded_of_compact α β).to_equiv = equiv_bounded_of_compact α β := rfl instance : metric_space C(α,β) := metric_space.induced (equiv_bounded_of_compact α β) (equiv_bounded_of_compact α β).injective (by apply_instance) variables (α β) /-- When `α` is compact, and `β` is a metric space, the bounded continuous maps `α →ᵇ β` are isometric to `C(α, β)`. -/ @[simps] def isometric_bounded_of_compact : C(α, β) ≃ᵢ (α →ᵇ β) := { isometry_to_fun := λ x y, rfl, to_equiv := equiv_bounded_of_compact α β } -- TODO at some point we will need lemmas characterising this norm! -- At the moment the only way to reason about it is to transfer `f : C(α,β)` back to `α →ᵇ β`. instance : has_norm C(α,β) := { norm := λ x, dist x 0 } instance : normed_group C(α,β) := { dist_eq := λ x y, begin change dist x y = dist (x-y) 0, -- it would be nice if `equiv_rw` could rewrite in multiple places at once equiv_rw (equiv_bounded_of_compact α β) at x, equiv_rw (equiv_bounded_of_compact α β) at y, have p : dist x y = dist (x-y) 0, { rw dist_eq_norm, rw dist_zero_right, }, convert p, exact ((add_equiv_bounded_of_compact α β).symm.map_sub _ _).symm, end, } section variables {R : Type*} [normed_ring R] instance : normed_ring C(α,R) := { norm_mul := λ f g, begin equiv_rw (equiv_bounded_of_compact α R) at f, equiv_rw (equiv_bounded_of_compact α R) at g, exact norm_mul_le f g, end, ..(infer_instance : normed_group C(α,R)) } end section variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] instance : normed_space 𝕜 C(α,β) := { norm_smul_le := λ c f, begin equiv_rw (equiv_bounded_of_compact α β) at f, exact le_of_eq (norm_smul c f), end } variables (α 𝕜) /-- When `α` is compact and `𝕜` is a normed field, the `𝕜`-algebra of bounded continuous maps `α →ᵇ β` is `𝕜`-linearly isometric to `C(α, β)`. -/ def linear_isometry_bounded_of_compact : C(α, β) ≃ₗᵢ[𝕜] (α →ᵇ β) := { map_smul' := λ c f, by { ext, simp, }, norm_map' := λ f, rfl, ..add_equiv_bounded_of_compact α β } @[simp] lemma linear_isometry_bounded_of_compact_to_isometric : (linear_isometry_bounded_of_compact α β 𝕜).to_isometric = isometric_bounded_of_compact α β := rfl @[simp] lemma linear_isometry_bounded_of_compact_to_add_equiv : (linear_isometry_bounded_of_compact α β 𝕜).to_linear_equiv.to_add_equiv = add_equiv_bounded_of_compact α β := rfl @[simp] lemma linear_isometry_bounded_of_compact_of_compact_to_equiv : (linear_isometry_bounded_of_compact α β 𝕜).to_linear_equiv.to_equiv = equiv_bounded_of_compact α β := rfl end end continuous_map
8978900e13d4b294fab35d0787fc68c1347f4f43
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/algebra/group.lean
06d2273664179c36cf86a93cd7c57141af8d8f6f
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,057
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.group Authors: Jeremy Avigad, Leonardo de Moura Various multiplicative and additive structures. Partially modeled on Isabelle's library. -/ import logic.eq logic.connectives import data.unit data.sigma data.prod import algebra.function algebra.binary open eq eq.ops -- note: ⁻¹ will be overloaded namespace algebra variable {A : Type} /- overloaded symbols -/ structure has_mul [class] (A : Type) := (mul : A → A → A) structure has_add [class] (A : Type) := (add : A → A → A) structure has_one [class] (A : Type) := (one : A) structure has_zero [class] (A : Type) := (zero : A) structure has_inv [class] (A : Type) := (inv : A → A) structure has_neg [class] (A : Type) := (neg : A → A) infixl `*` := has_mul.mul infixl `+` := has_add.add postfix `⁻¹` := has_inv.inv prefix `-` := has_neg.neg notation 1 := has_one.one notation 0 := has_zero.zero /- semigroup -/ structure semigroup [class] (A : Type) extends has_mul A := (mul_assoc : ∀a b c, mul (mul a b) c = mul a (mul b c)) theorem mul_assoc [s : semigroup A] (a b c : A) : a * b * c = a * (b * c) := !semigroup.mul_assoc structure comm_semigroup [class] (A : Type) extends semigroup A := (mul_comm : ∀a b, mul a b = mul b a) theorem mul_comm [s : comm_semigroup A] (a b : A) : a * b = b * a := !comm_semigroup.mul_comm theorem mul_left_comm [s : comm_semigroup A] (a b c : A) : a * (b * c) = b * (a * c) := binary.left_comm (@mul_comm A s) (@mul_assoc A s) a b c theorem mul_right_comm [s : comm_semigroup A] (a b c : A) : (a * b) * c = (a * c) * b := binary.right_comm (@mul_comm A s) (@mul_assoc A s) a b c structure left_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_left_cancel : ∀a b c, mul a b = mul a c → b = c) theorem mul_left_cancel [s : left_cancel_semigroup A] {a b c : A} : a * b = a * c → b = c := !left_cancel_semigroup.mul_left_cancel structure right_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_right_cancel : ∀a b c, mul a b = mul c b → a = c) theorem mul_right_cancel [s : right_cancel_semigroup A] {a b c : A} : a * b = c * b → a = c := !right_cancel_semigroup.mul_right_cancel /- additive semigroup -/ structure add_semigroup [class] (A : Type) extends has_add A := (add_assoc : ∀a b c, add (add a b) c = add a (add b c)) theorem add_assoc [s : add_semigroup A] (a b c : A) : a + b + c = a + (b + c) := !add_semigroup.add_assoc structure add_comm_semigroup [class] (A : Type) extends add_semigroup A := (add_comm : ∀a b, add a b = add b a) theorem add_comm [s : add_comm_semigroup A] (a b : A) : a + b = b + a := !add_comm_semigroup.add_comm theorem add_left_comm [s : add_comm_semigroup A] (a b c : A) : a + (b + c) = b + (a + c) := binary.left_comm (@add_comm A s) (@add_assoc A s) a b c theorem add_right_comm [s : add_comm_semigroup A] (a b c : A) : (a + b) + c = (a + c) + b := binary.right_comm (@add_comm A s) (@add_assoc A s) a b c structure add_left_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_left_cancel : ∀a b c, add a b = add a c → b = c) theorem add_left_cancel [s : add_left_cancel_semigroup A] {a b c : A} : a + b = a + c → b = c := !add_left_cancel_semigroup.add_left_cancel structure add_right_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_right_cancel : ∀a b c, add a b = add c b → a = c) theorem add_right_cancel [s : add_right_cancel_semigroup A] {a b c : A} : a + b = c + b → a = c := !add_right_cancel_semigroup.add_right_cancel /- monoid -/ structure monoid [class] (A : Type) extends semigroup A, has_one A := (mul_left_id : ∀a, mul one a = a) (mul_right_id : ∀a, mul a one = a) theorem mul_left_id [s : monoid A] (a : A) : 1 * a = a := !monoid.mul_left_id theorem mul_right_id [s : monoid A] (a : A) : a * 1 = a := !monoid.mul_right_id structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A /- additive monoid -/ structure add_monoid [class] (A : Type) extends add_semigroup A, has_zero A := (add_left_id : ∀a, add zero a = a) (add_right_id : ∀a, add a zero = a) theorem add_left_id [s : add_monoid A] (a : A) : 0 + a = a := !add_monoid.add_left_id theorem add_right_id [s : add_monoid A] (a : A) : a + 0 = a := !add_monoid.add_right_id structure add_comm_monoid [class] (A : Type) extends add_monoid A, add_comm_semigroup A /- group -/ structure group [class] (A : Type) extends monoid A, has_inv A := (mul_left_inv : ∀a, mul (inv a) a = one) -- Note: with more work, we could derive the axiom mul_left_id section group variable [s : group A] include s theorem mul_left_inv (a : A) : a⁻¹ * a = 1 := !group.mul_left_inv theorem inv_mul_cancel_left (a b : A) : a⁻¹ * (a * b) = b := calc a⁻¹ * (a * b) = a⁻¹ * a * b : mul_assoc ... = 1 * b : mul_left_inv ... = b : mul_left_id theorem inv_mul_cancel_right (a b : A) : a * b⁻¹ * b = a := calc a * b⁻¹ * b = a * (b⁻¹ * b) : mul_assoc ... = a * 1 : mul_left_inv ... = a : mul_right_id theorem inv_unique {a b : A} (H : a * b = 1) : a⁻¹ = b := calc a⁻¹ = a⁻¹ * 1 : mul_right_id ... = a⁻¹ * (a * b) : H ... = b : inv_mul_cancel_left theorem inv_one : 1⁻¹ = 1 := inv_unique (mul_left_id 1) theorem inv_inv (a : A) : (a⁻¹)⁻¹ = a := inv_unique (mul_left_inv a) theorem inv_inj {a b : A} (H : a⁻¹ = b⁻¹) : a = b := calc a = (a⁻¹)⁻¹ : inv_inv ... = b : inv_unique (H⁻¹ ▸ (mul_left_inv _)) theorem inv_eq_inv_iff_eq (a b : A) : a⁻¹ = b⁻¹ ↔ a = b := iff.intro (assume H, inv_inj H) (assume H, congr_arg _ H) theorem inv_eq_one_iff_eq_one (a b : A) : a⁻¹ = 1 ↔ a = 1 := inv_one ▸ !inv_eq_inv_iff_eq theorem eq_inv_imp_eq_inv {a b : A} (H : a = b⁻¹) : b = a⁻¹ := H⁻¹ ▸ (inv_inv b)⁻¹ theorem eq_inv_iff_eq_inv (a b : A) : a = b⁻¹ ↔ b = a⁻¹ := iff.intro !eq_inv_imp_eq_inv !eq_inv_imp_eq_inv theorem mul_right_inv (a : A) : a * a⁻¹ = 1 := calc a * a⁻¹ = (a⁻¹)⁻¹ * a⁻¹ : inv_inv ... = 1 : mul_left_inv theorem mul_inv_cancel_left (a b : A) : a * (a⁻¹ * b) = b := calc a * (a⁻¹ * b) = a * a⁻¹ * b : mul_assoc ... = 1 * b : mul_right_inv ... = b : mul_left_id theorem mul_inv_cancel_right (a b : A) : a * b * b⁻¹ = a := calc a * b * b⁻¹ = a * (b * b⁻¹) : mul_assoc ... = a * 1 : mul_right_inv ... = a : mul_right_id theorem inv_mul (a b : A) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := inv_unique (calc a * b * (b⁻¹ * a⁻¹) = a * (b * (b⁻¹ * a⁻¹)) : mul_assoc ... = a * a⁻¹ : mul_inv_cancel_left ... = 1 : mul_right_inv) theorem mul_inv_eq_one_imp_eq {a b : A} (H : a * b⁻¹ = 1) : a = b := calc a = a * b⁻¹ * b : inv_mul_cancel_right ... = 1 * b : H ... = b : mul_left_id -- TODO: better names for the next eight theorems? (Also for additive ones.) theorem mul_eq_imp_eq_mul_inv {a b c : A} (H : a * b = c) : a = c * b⁻¹ := H ▸ !mul_inv_cancel_right⁻¹ theorem mul_eq_imp_eq_inv_mul {a b c : A} (H : a * b = c) : b = a⁻¹ * c := H ▸ !inv_mul_cancel_left⁻¹ theorem eq_mul_imp_inv_mul_eq {a b c : A} (H : a = b * c) : b⁻¹ * a = c := H⁻¹ ▸ !inv_mul_cancel_left theorem eq_mul_imp_mul_inv_eq {a b c : A} (H : a = b * c) : a * c⁻¹ = b := H⁻¹ ▸ !mul_inv_cancel_right theorem mul_inv_eq_imp_eq_mul {a b c : A} (H : a * b⁻¹ = c) : a = c * b := !inv_inv ▸ (mul_eq_imp_eq_mul_inv H) theorem inv_mul_eq_imp_eq_mul {a b c : A} (H : a⁻¹ * b = c) : b = a * c := !inv_inv ▸ (mul_eq_imp_eq_inv_mul H) theorem eq_inv_mul_imp_mul_eq {a b c : A} (H : a = b⁻¹ * c) : b * a = c := !inv_inv ▸ (eq_mul_imp_inv_mul_eq H) theorem eq_mul_inv_imp_mul_eq {a b c : A} (H : a = b * c⁻¹) : a * c = b := !inv_inv ▸ (eq_mul_imp_mul_inv_eq H) definition group.to_left_cancel_semigroup [instance] : left_cancel_semigroup A := left_cancel_semigroup.mk (@group.mul A s) (@group.mul_assoc A s) (take a b c, assume H : a * b = a * c, calc b = a⁻¹ * (a * b) : inv_mul_cancel_left ... = a⁻¹ * (a * c) : H ... = c : inv_mul_cancel_left) definition group.to_right_cancel_semigroup [instance] : right_cancel_semigroup A := right_cancel_semigroup.mk (@group.mul A s) (@group.mul_assoc A s) (take a b c, assume H : a * b = c * b, calc a = (a * b) * b⁻¹ : mul_inv_cancel_right ... = (c * b) * b⁻¹ : H ... = c : mul_inv_cancel_right) end group structure comm_group [class] (A : Type) extends group A, comm_monoid A /- additive group -/ structure add_group [class] (A : Type) extends add_monoid A, has_neg A := (add_left_inv : ∀a, add (neg a) a = zero) section add_group variables [s : add_group A] include s theorem add_left_inv (a : A) : -a + a = 0 := !add_group.add_left_inv theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b := calc -a + (a + b) = -a + a + b : add_assoc ... = 0 + b : add_left_inv ... = b : add_left_id theorem neg_add_cancel_right (a b : A) : a + -b + b = a := calc a + -b + b = a + (-b + b) : add_assoc ... = a + 0 : add_left_inv ... = a : add_right_id theorem neg_unique {a b : A} (H : a + b = 0) : -a = b := calc -a = -a + 0 : add_right_id ... = -a + (a + b) : H ... = b : neg_add_cancel_left theorem neg_zero : -0 = 0 := neg_unique (add_left_id 0) theorem neg_neg (a : A) : -(-a) = a := neg_unique (add_left_inv a) theorem neg_inj {a b : A} (H : -a = -b) : a = b := calc a = -(-a) : neg_neg ... = b : neg_unique (H⁻¹ ▸ (add_left_inv _)) theorem neg_eq_neg_iff_eq (a b : A) : -a = -b ↔ a = b := iff.intro (assume H, neg_inj H) (assume H, congr_arg _ H) theorem neg_eq_zero_iff_eq_zero (a b : A) : -a = 0 ↔ a = 0 := neg_zero ▸ !neg_eq_neg_iff_eq theorem eq_neg_imp_eq_neg {a b : A} (H : a = -b) : b = -a := H⁻¹ ▸ (neg_neg b)⁻¹ theorem eq_neg_iff_eq_neg (a b : A) : a = -b ↔ b = -a := iff.intro !eq_neg_imp_eq_neg !eq_neg_imp_eq_neg theorem add_right_inv (a : A) : a + -a = 0 := calc a + -a = -(-a) + -a : neg_neg ... = 0 : add_left_inv theorem add_neg_cancel_left (a b : A) : a + (-a + b) = b := calc a + (-a + b) = a + -a + b : add_assoc ... = 0 + b : add_right_inv ... = b : add_left_id theorem add_neg_cancel_right (a b : A) : a + b + -b = a := calc a + b + -b = a + (b + -b) : add_assoc ... = a + 0 : add_right_inv ... = a : add_right_id theorem neg_add (a b : A) : -(a + b) = -b + -a := neg_unique (calc a + b + (-b + -a) = a + (b + (-b + -a)) : add_assoc ... = a + -a : add_neg_cancel_left ... = 0 : add_right_inv) theorem add_eq_imp_eq_add_neg {a b c : A} (H : a + b = c) : a = c + -b := H ▸ !add_neg_cancel_right⁻¹ theorem add_eq_imp_eq_neg_add {a b c : A} (H : a + b = c) : b = -a + c := H ▸ !neg_add_cancel_left⁻¹ theorem eq_add_imp_neg_add_eq {a b c : A} (H : a = b + c) : -b + a = c := H⁻¹ ▸ !neg_add_cancel_left theorem eq_add_imp_add_neg_eq {a b c : A} (H : a = b + c) : a + -c = b := H⁻¹ ▸ !add_neg_cancel_right theorem add_neg_eq_imp_eq_add {a b c : A} (H : a + -b = c) : a = c + b := !neg_neg ▸ (add_eq_imp_eq_add_neg H) theorem neg_add_eq_imp_eq_add {a b c : A} (H : -a + b = c) : b = a + c := !neg_neg ▸ (add_eq_imp_eq_neg_add H) theorem eq_neg_add_imp_add_eq {a b c : A} (H : a = -b + c) : b + a = c := !neg_neg ▸ (eq_add_imp_neg_add_eq H) theorem eq_add_neg_imp_add_eq {a b c : A} (H : a = b + -c) : a + c = b := !neg_neg ▸ (eq_add_imp_add_neg_eq H) definition add_group.to_left_cancel_semigroup [instance] : add_left_cancel_semigroup A := add_left_cancel_semigroup.mk (@add_group.add A s) (@add_group.add_assoc A s) (take a b c, assume H : a + b = a + c, calc b = -a + (a + b) : neg_add_cancel_left ... = -a + (a + c) : H ... = c : neg_add_cancel_left) definition add_group.to_add_right_cancel_semigroup [instance] : add_right_cancel_semigroup A := add_right_cancel_semigroup.mk (@add_group.add A s) (@add_group.add_assoc A s) (take a b c, assume H : a + b = c + b, calc a = (a + b) + -b : add_neg_cancel_right ... = (c + b) + -b : H ... = c : add_neg_cancel_right) /- minus -/ -- TODO: derive corresponding facts for div in a field definition minus (a b : A) : A := a + -b infix `-` := minus theorem minus_self (a : A) : a - a = 0 := !add_right_inv theorem minus_add_cancel (a b : A) : a - b + b = a := !neg_add_cancel_right theorem add_minus_cancel (a b : A) : a + b - b = a := !add_neg_cancel_right theorem minus_eq_zero_imp_eq {a b : A} (H : a - b = 0) : a = b := calc a = (a - b) + b : minus_add_cancel ... = 0 + b : H ... = b : add_left_id theorem eq_iff_minus_eq_zero (a b : A) : a = b ↔ a - b = 0 := iff.intro (assume H, H ▸ !minus_self) (assume H, minus_eq_zero_imp_eq H) theorem zero_minus (a : A) : 0 - a = -a := !add_left_id theorem minus_zero (a : A) : a - 0 = a := subst (eq.symm neg_zero) !add_right_id theorem minus_neg_eq_add (a b : A) : a - (-b) = a + b := !neg_neg⁻¹ ▸ rfl theorem neg_minus_eq (a b : A) : -(a - b) = b - a := neg_unique (calc a - b + (b - a) = a - b + b - a : add_assoc ... = a - a : minus_add_cancel ... = 0 : minus_self) theorem add_minus_eq (a b c : A) : a + (b - c) = a + b - c := !add_assoc⁻¹ theorem minus_add_eq_minus_swap (a b c : A) : a - (b + c) = a - c - b := calc a - (b + c) = a + (-c - b) : neg_add ... = a - c - b : add_assoc theorem minus_eq_iff_eq_add (a b c : A) : a - b = c ↔ a = c + b := iff.intro (assume H, add_neg_eq_imp_eq_add H) (assume H, eq_add_imp_add_neg_eq H) theorem eq_minus_iff_add_eq (a b c : A) : a = b - c ↔ a + c = b := iff.intro (assume H, eq_add_neg_imp_add_eq H) (assume H, add_eq_imp_eq_add_neg H) theorem minus_eq_minus_iff {a b c d : A} (H : a - b = c - d) : a = b ↔ c = d := calc a = b ↔ a - b = 0 : eq_iff_minus_eq_zero ... ↔ c - d = 0 : H ▸ !iff.refl ... ↔ c = d : iff.symm (eq_iff_minus_eq_zero c d) end add_group structure add_comm_group [class] (A : Type) extends add_group A, add_comm_monoid A section add_comm_group variable [s : add_comm_group A] include s theorem minus_add_eq (a b c : A) : a - (b + c) = a - b - c := !add_comm ▸ !minus_add_eq_minus_swap theorem neg_add_eq_minus (a b : A) : -a + b = b - a := !add_comm theorem neg_add_distrib (a b : A) : -(a + b) = -a + -b := !add_comm ▸ !neg_add theorem minus_add_right_comm (a b c : A) : a - b + c = a + c - b := !add_right_comm theorem minus_minus_eq (a b c : A) : a - b - c = a - (b + c) := calc a - b - c = a + (-b + -c) : add_assoc ... = a + -(b + c) : neg_add_distrib ... = a - (b + c) : rfl theorem add_minus_cancel_left (a b c : A) : (c + a) - (c + b) = a - b := calc (c + a) - (c + b) = c + a - c - b : minus_add_eq ... = a + c - c - b : add_comm a c ... = a - b : add_minus_cancel end add_comm_group /- bundled structures -/ structure Semigroup := (carrier : Type) (struct : semigroup carrier) coercion Semigroup.carrier instance Semigroup.struct structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) coercion CommSemigroup.carrier instance CommSemigroup.struct structure Monoid := (carrier : Type) (struct : monoid carrier) coercion Monoid.carrier instance Monoid.struct structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) coercion CommMonoid.carrier instance CommMonoid.struct structure Group := (carrier : Type) (struct : group carrier) coercion Group.carrier instance Group.struct structure CommGroup := (carrier : Type) (struct : comm_group carrier) coercion CommGroup.carrier instance CommGroup.struct structure AddSemigroup := (carrier : Type) (struct : add_semigroup carrier) coercion AddSemigroup.carrier instance AddSemigroup.struct structure AddCommSemigroup := (carrier : Type) (struct : add_comm_semigroup carrier) coercion AddCommSemigroup.carrier instance AddCommSemigroup.struct structure AddMonoid := (carrier : Type) (struct : add_monoid carrier) coercion AddMonoid.carrier instance AddMonoid.struct structure AddCommMonoid := (carrier : Type) (struct : add_comm_monoid carrier) coercion AddCommMonoid.carrier instance AddCommMonoid.struct structure AddGroup := (carrier : Type) (struct : add_group carrier) coercion AddGroup.carrier instance AddGroup.struct structure AddCommGroup := (carrier : Type) (struct : add_comm_group carrier) coercion AddCommGroup.carrier instance AddCommGroup.struct end algebra
b6fada06355c7169f79ab7ed1e651b7bda60ca77
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/int_to_nat_bug.lean
10dee983656606caa431d880f84320f332946da5
[ "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
26
lean
#eval (4294967295 : Int)
91410d2d0a9c197e33993668deaea21c64a48ca5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/expectedTypeAsGoal.lean
78f2237537d3d4cc758b23fe87d627b0a9026d01
[ "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
175
lean
def big : IO Unit := do let x := 10 if true then IO.println s!"a{x}" --^ $/lean/plainTermGoal if false then IO.println "b" if 1 < 3 then IO.println "c"
08e8236b8d8edf3e43edbfbc641d823321e2e59a
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/abel.lean
101438b48a0a41ba7c28b1691c3f0126328a876d
[ "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
12,382
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Evaluate expressions in the language of additive, commutative monoids and groups. -/ import algebra.group_power tactic.norm_num namespace tactic namespace abel meta structure cache := (α : expr) (univ : level) (α0 : expr) (is_group : bool) (inst : expr) meta def mk_cache (e : expr) : tactic cache := do α ← infer_type e, c ← mk_app ``add_comm_monoid [α] >>= mk_instance, cg ← try_core (mk_app ``add_comm_group [α] >>= mk_instance), u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, α0 ← expr.of_nat α 0, match cg with | (some cg) := return ⟨α, u, α0, tt, cg⟩ | _ := return ⟨α, u, α0, ff, c⟩ end meta def cache.app (c : cache) (n : name) (inst : expr) : list expr → expr := (@expr.const tt n [c.univ] c.α inst).mk_app meta def cache.mk_app (c : cache) (n inst : name) (l : list expr) : tactic expr := do m ← mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ c.app n m l meta def add_g : name → name | (name.mk_string s p) := name.mk_string (s ++ "g") p | n := n meta def cache.iapp (c : cache) (n : name) : list expr → expr := c.app (if c.is_group then add_g n else n) c.inst def term {α} [add_comm_monoid α] (n : ℕ) (x a : α) : α := add_monoid.smul n x + a def termg {α} [add_comm_group α] (n : ℤ) (x a : α) : α := gsmul n x + a meta def cache.mk_term (c : cache) (n x a : expr) : expr := c.iapp ``term [n, x, a] meta def cache.int_to_expr (c : cache) (n : ℤ) : tactic expr := expr.of_int (if c.is_group then `(ℤ) else `(ℕ)) n meta inductive normal_expr : Type | zero (e : expr) : normal_expr | nterm (e : expr) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr meta def normal_expr.e : normal_expr → expr | (normal_expr.zero e) := e | (normal_expr.nterm e _ _ _) := e meta instance : has_coe normal_expr expr := ⟨normal_expr.e⟩ meta def normal_expr.term' (c : cache) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr := normal_expr.nterm (c.mk_term n.1 x a) n x a meta def normal_expr.zero' (c : cache) : normal_expr := normal_expr.zero c.α0 meta def normal_expr.to_list : normal_expr → list (ℤ × expr) | (normal_expr.zero _) := [] | (normal_expr.nterm _ (_, n) x a) := (n, x) :: a.to_list open normal_expr meta def normal_expr.to_string (e : normal_expr) : string := " + ".intercalate $ (to_list e).map $ λ ⟨n, e⟩, to_string n ++ " • (" ++ to_string e ++ ")" meta def normal_expr.pp (e : normal_expr) : tactic format := do l ← (to_list e).mmap (λ ⟨n, e⟩, do pe ← pp e, return (to_fmt n ++ " • (" ++ pe ++ ")")), return $ format.join $ l.intersperse ↑" + " meta instance : has_to_tactic_format normal_expr := ⟨normal_expr.pp⟩ meta def normal_expr.refl_conv (e : normal_expr) : tactic (normal_expr × expr) := do p ← mk_eq_refl e, return (e, p) theorem const_add_term {α} [add_comm_monoid α] (k n x a a') (h : k + a = a') : k + @term α _ n x a = term n x a' := by simp [h.symm, term] theorem const_add_termg {α} [add_comm_group α] (k n x a a') (h : k + a = a') : k + @termg α _ n x a = termg n x a' := by simp [h.symm, termg] theorem term_add_const {α} [add_comm_monoid α] (n x a k a') (h : a + k = a') : @term α _ n x a + k = term n x a' := by simp [h.symm, term] theorem term_add_constg {α} [add_comm_group α] (n x a k a') (h : a + k = a') : @termg α _ n x a + k = termg n x a' := by simp [h.symm, termg] theorem term_add_term {α} [add_comm_monoid α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @term α _ n₁ x a₁ + @term α _ n₂ x a₂ = term n' x a' := by simp [h₁.symm, h₂.symm, term, add_monoid.add_smul] theorem term_add_termg {α} [add_comm_group α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @termg α _ n₁ x a₁ + @termg α _ n₂ x a₂ = termg n' x a' := by simp [h₁.symm, h₂.symm, termg, add_gsmul] theorem zero_term {α} [add_comm_monoid α] (x a) : @term α _ 0 x a = a := by simp [term] theorem zero_termg {α} [add_comm_group α] (x a) : @termg α _ 0 x a = a := by simp [termg] meta def eval_add (c : cache) : normal_expr → normal_expr → tactic (normal_expr × expr) | (zero _) e₂ := do p ← mk_app ``zero_add [e₂], return (e₂, p) | e₁ (zero _) := do p ← mk_app ``add_zero [e₁], return (e₁, p) | he₁@(nterm e₁ n₁ x₁ a₁) he₂@(nterm e₂ n₂ x₂ a₂) := if expr.lex_lt x₁ x₂ then do (a', h) ← eval_add a₁ he₂, return (term' c n₁ x₁ a', c.iapp ``term_add_const [n₁.1, x₁, a₁, e₂, a', h]) else if x₁ ≠ x₂ then do (a', h) ← eval_add he₁ a₂, return (term' c n₂ x₂ a', c.iapp ``const_add_term [e₁, n₂.1, x₂, a₂, a', h]) else do (n', h₁) ← mk_app ``has_add.add [n₁.1, n₂.1] >>= norm_num, (a', h₂) ← eval_add a₁ a₂, let k := n₁.2 + n₂.2, let p₁ := c.iapp ``term_add_term [n₁.1, x₁, a₁, n₂.1, a₂, n', a', h₁, h₂], if k = 0 then do p ← mk_eq_trans p₁ (c.iapp ``zero_term [x₁, a']), return (a', p) else return (term' c (n', k) x₁ a', p₁) theorem term_neg {α} [add_comm_group α] (n x a n' a') (h₁ : -n = n') (h₂ : -a = a') : -@termg α _ n x a = termg n' x a' := by simp [h₂.symm, h₁.symm, termg] meta def eval_neg (c : cache) : normal_expr → tactic (normal_expr × expr) | (zero e) := do p ← c.mk_app ``neg_zero ``add_group [], return (zero' c, p) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_neg.neg [n.1] >>= norm_num, (a', h₂) ← eval_neg a, return (term' c (n', -n.2) x a', c.app ``term_neg c.inst [n.1, x, a, n', a', h₁, h₂]) def smul {α} [add_comm_monoid α] (n : ℕ) (x : α) : α := add_monoid.smul n x def smulg {α} [add_comm_group α] (n : ℤ) (x : α) : α := gsmul n x theorem zero_smul {α} [add_comm_monoid α] (c) : smul c (0 : α) = 0 := by simp [smul] theorem zero_smulg {α} [add_comm_group α] (c) : smulg c (0 : α) = 0 := by simp [smulg] theorem term_smul {α} [add_comm_monoid α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smul c a = a') : smul c (@term α _ n x a) = term n' x a' := by simp [h₂.symm, h₁.symm, term, smul, add_monoid.smul_add, add_monoid.mul_smul] theorem term_smulg {α} [add_comm_group α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smulg c a = a') : smulg c (@termg α _ n x a) = termg n' x a' := by simp [h₂.symm, h₁.symm, termg, smulg, gsmul_add, gsmul_mul] meta def eval_smul (c : cache) (k : expr × ℤ) : normal_expr → tactic (normal_expr × expr) | (zero _) := return (zero' c, c.iapp ``zero_smul [k.1]) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_mul.mul [k.1, n.1] >>= norm_num, (a', h₂) ← eval_smul a, return (term' c (n', k.2 * n.2) x a', c.iapp ``term_smul [k.1, n.1, x, a, n', a', h₁, h₂]) theorem term_atom {α} [add_comm_monoid α] (x : α) : x = term 1 x 0 := by simp [term] theorem term_atomg {α} [add_comm_group α] (x : α) : x = termg 1 x 0 := by simp [termg] meta def eval_atom (c : cache) (e : expr) : tactic (normal_expr × expr) := do n1 ← c.int_to_expr 1, return (term' c (n1, 1) e (zero' c), c.iapp ``term_atom [e]) lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := h theorem unfold_smul {α} [add_comm_monoid α] (n) (x y : α) (h : smul n x = y) : add_monoid.smul n x = y := h theorem unfold_smulg {α} [add_comm_group α] (n : ℕ) (x y : α) (h : smulg (int.of_nat n) x = y) : add_monoid.smul n x = y := h theorem unfold_gsmul {α} [add_comm_group α] (n : ℤ) (x y : α) (h : smulg n x = y) : gsmul n x = y := h lemma subst_into_smul {α} [add_comm_monoid α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smul α _ tl tr = t) : smul l r = t := by simp [prl, prr, prt] lemma subst_into_smulg {α} [add_comm_group α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smulg α _ tl tr = t) : smulg l r = t := by simp [prl, prr, prt] meta def eval (c : cache) : expr → tactic (normal_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add c e₁' e₂', p ← c.mk_app ``norm_num.subst_into_sum ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | `(%%e₁ - %%e₂) := do e₂' ← mk_app ``has_neg.neg [e₂], e ← mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← c.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p], return (e', p') | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg c e₁, p ← c.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(add_monoid.smul %%e₁ %%e₂) := do n ← if c.is_group then mk_app ``int.of_nat [e₁] else return e₁, (e', p) ← eval $ c.iapp ``smul [n, e₂], return (e', c.iapp ``unfold_smul [e₁, e₂, e', p]) | `(gsmul %%e₁ %%e₂) := do guardb c.is_group, (e', p) ← eval $ c.iapp ``smul [e₁, e₂], return (e', c.app ``unfold_gsmul c.inst [e₁, e₂, e', p]) | `(smul %%e₁ %%e₂) := do guard (¬ c.is_group), (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁, n ← e₁'.to_nat, (e₂', p₂) ← eval e₂, (e', p) ← eval_smul c (e₁', n) e₂', return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p]) | `(smulg %%e₁ %%e₂) := do guardb c.is_group, (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁, n ← e₁'.to_int, (e₂', p₂) ← eval e₂, (e', p) ← eval_smul c (e₁', n) e₂', return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p]) | e := eval_atom c e meta def eval' (c : cache) (e : expr) : tactic (expr × expr) := do (e', p) ← eval c e, return (e', p) @[derive has_reflect] inductive normalize_mode | raw | term meta def normalize (mode := normalize_mode.term) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.term := [``term.equations._eqn_1, ``termg.equations._eqn_1, ``add_zero, ``add_monoid.one_smul, ``one_gsmul] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do c ← mk_cache e, (new_e, pr) ← match mode with | normalize_mode.raw := eval' c | normalize_mode.term := trans_conv (eval' c) (simplify lemmas []) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end abel namespace interactive open interactive interactive.types lean.parser open tactic.abel local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *additive*, commutative monoids and groups. This version of `abel` fails if the target is not an equality that is provable by the axioms of commutative monoids/groups. -/ meta def abel1 : tactic unit := do `(%%e₁ = %%e₂) ← target, c ← mk_cache e₁, (e₁', p₁) ← eval c e₁, (e₂', p₂) ← eval c e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p meta def abel.mode : lean.parser abel.normalize_mode := with_desc "(raw|term)?" $ do mode ← ident?, match mode with | none := return abel.normalize_mode.term | some `term := return abel.normalize_mode.term | some `raw := return abel.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *additive*, commutative monoids and groups. Attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails it falls back to rewriting all monoid expressions into a normal form. -/ meta def abel (SOP : parse abel.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := abel1 | _ := failed end <|> do ns ← loc.get_locals, tt ← tactic.replace_at (normalize SOP) ns loc.include_goal | fail "abel failed to simplify", when loc.include_goal $ try tactic.reflexivity end interactive end tactic
64bdf7d090d72aed1bd0c55fc06ba31f3ba3de88
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/box_integral/partition/basic.lean
8c879527a35d2df6ec342ed5db5e43a31bfe929b
[ "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
29,153
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 analysis.box_integral.box.basic /-! # Partitions of rectangular boxes in `ℝⁿ` In this file we define (pre)partitions of rectangular boxes in `ℝⁿ`. A partition of a box `I` in `ℝⁿ` (see `box_integral.prepartition` and `box_integral.prepartition.is_partition`) is a finite set of pairwise disjoint boxes such that their union is exactly `I`. We use `boxes : finset (box ι)` to store the set of boxes. Many lemmas about box integrals deal with pairwise disjoint collections of subboxes, so we define a structure `box_integral.prepartition (I : box_integral.box ι)` that stores a collection of boxes such that * each box `J ∈ boxes` is a subbox of `I`; * the boxes are pairwise disjoint as sets in `ℝⁿ`. Then we define a predicate `box_integral.prepartition.is_partition`; `π.is_partition` means that the boxes of `π` actually cover the whole `I`. We also define some operations on prepartitions: * `box_integral.partition.bUnion`: split each box of a partition into smaller boxes; * `box_integral.partition.restrict`: restrict a partition to a smaller box. We also define a `semilattice_inf` structure on `box_integral.partition I` for all `I : box_integral.box ι`. ## Tags rectangular box, partition -/ open set finset function open_locale classical nnreal big_operators noncomputable theory namespace box_integral variables {ι : Type*} /-- A prepartition of `I : box_integral.box ι` is a finite set of pairwise disjoint subboxes of `I`. -/ structure prepartition (I : box ι) := (boxes : finset (box ι)) (le_of_mem' : ∀ J ∈ boxes, J ≤ I) (pairwise_disjoint : set.pairwise ↑boxes (disjoint on (coe : box ι → set (ι → ℝ)))) namespace prepartition variables {I J J₁ J₂ : box ι} (π : prepartition I) {π₁ π₂ : prepartition I} {x : ι → ℝ} instance : has_mem (box ι) (prepartition I) := ⟨λ J π, J ∈ π.boxes⟩ @[simp] lemma mem_boxes : J ∈ π.boxes ↔ J ∈ π := iff.rfl @[simp] lemma mem_mk {s h₁ h₂} : J ∈ (mk s h₁ h₂ : prepartition I) ↔ J ∈ s := iff.rfl lemma disjoint_coe_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (h : J₁ ≠ J₂) : disjoint (J₁ : set (ι → ℝ)) J₂ := π.pairwise_disjoint h₁ h₂ h lemma eq_of_mem_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hx₁ : x ∈ J₁) (hx₂ : x ∈ J₂) : J₁ = J₂ := by_contra $ λ H, π.disjoint_coe_of_mem h₁ h₂ H ⟨hx₁, hx₂⟩ lemma eq_of_le_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle₁ : J ≤ J₁) (hle₂ : J ≤ J₂) : J₁ = J₂ := π.eq_of_mem_of_mem h₁ h₂ (hle₁ J.upper_mem) (hle₂ J.upper_mem) lemma eq_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle : J₁ ≤ J₂) : J₁ = J₂ := π.eq_of_le_of_le h₁ h₂ le_rfl hle lemma le_of_mem (hJ : J ∈ π) : J ≤ I := π.le_of_mem' J hJ lemma lower_le_lower (hJ : J ∈ π) : I.lower ≤ J.lower := box.antitone_lower (π.le_of_mem hJ) lemma upper_le_upper (hJ : J ∈ π) : J.upper ≤ I.upper := box.monotone_upper (π.le_of_mem hJ) lemma injective_boxes : function.injective (boxes : prepartition I → finset (box ι)) := by { rintro ⟨s₁, h₁, h₁'⟩ ⟨s₂, h₂, h₂'⟩ (rfl : s₁ = s₂), refl } @[ext] lemma ext (h : ∀ J, J ∈ π₁ ↔ J ∈ π₂) : π₁ = π₂ := injective_boxes $ finset.ext h /-- The singleton prepartition `{J}`, `J ≤ I`. -/ @[simps] def single (I J : box ι) (h : J ≤ I) : prepartition I := ⟨{J}, by simpa, by simp⟩ @[simp] lemma mem_single {J'} (h : J ≤ I) : J' ∈ single I J h ↔ J' = J := mem_singleton /-- We say that `π ≤ π'` if each box of `π` is a subbox of some box of `π'`. -/ instance : has_le (prepartition I) := ⟨λ π π', ∀ ⦃I⦄, I ∈ π → ∃ I' ∈ π', I ≤ I'⟩ instance : partial_order (prepartition I) := { le := (≤), le_refl := λ π I hI, ⟨I, hI, le_rfl⟩, le_trans := λ π₁ π₂ π₃ h₁₂ h₂₃ I₁ hI₁, let ⟨I₂, hI₂, hI₁₂⟩ := h₁₂ hI₁, ⟨I₃, hI₃, hI₂₃⟩ := h₂₃ hI₂ in ⟨I₃, hI₃, hI₁₂.trans hI₂₃⟩, le_antisymm := begin suffices : ∀ {π₁ π₂ : prepartition I}, π₁ ≤ π₂ → π₂ ≤ π₁ → π₁.boxes ⊆ π₂.boxes, from λ π₁ π₂ h₁ h₂, injective_boxes (subset.antisymm (this h₁ h₂) (this h₂ h₁)), intros π₁ π₂ h₁ h₂ J hJ, rcases h₁ hJ with ⟨J', hJ', hle⟩, rcases h₂ hJ' with ⟨J'', hJ'', hle'⟩, obtain rfl : J = J'', from π₁.eq_of_le hJ hJ'' (hle.trans hle'), obtain rfl : J' = J, from le_antisymm ‹_› ‹_›, assumption end } instance : order_top (prepartition I) := { top := single I I le_rfl, le_top := λ π J hJ, ⟨I, by simp, π.le_of_mem hJ⟩ } instance : order_bot (prepartition I) := { bot := ⟨∅, λ J hJ, false.elim hJ, λ J hJ, false.elim hJ⟩, bot_le := λ π J hJ, false.elim hJ } instance : inhabited (prepartition I) := ⟨⊤⟩ lemma le_def : π₁ ≤ π₂ ↔ ∀ J ∈ π₁, ∃ J' ∈ π₂, J ≤ J' := iff.rfl @[simp] lemma mem_top : J ∈ (⊤ : prepartition I) ↔ J = I := mem_singleton @[simp] lemma top_boxes : (⊤ : prepartition I).boxes = {I} := rfl @[simp] lemma not_mem_bot : J ∉ (⊥ : prepartition I) := id @[simp] lemma bot_boxes : (⊥ : prepartition I).boxes = ∅ := rfl /-- An auxiliary lemma used to prove that the same point can't belong to more than `2 ^ fintype.card ι` closed boxes of a prepartition. -/ lemma inj_on_set_of_mem_Icc_set_of_lower_eq (x : ι → ℝ) : inj_on (λ J : box ι, {i | J.lower i = x i}) {J | J ∈ π ∧ x ∈ J.Icc} := begin rintros J₁ ⟨h₁, hx₁⟩ J₂ ⟨h₂, hx₂⟩ (H : {i | J₁.lower i = x i} = {i | J₂.lower i = x i}), suffices : ∀ i, (Ioc (J₁.lower i) (J₁.upper i) ∩ Ioc (J₂.lower i) (J₂.upper i)).nonempty, { choose y hy₁ hy₂, exact π.eq_of_mem_of_mem h₁ h₂ hy₁ hy₂ }, intro i, simp only [set.ext_iff, mem_set_of_eq] at H, cases (hx₁.1 i).eq_or_lt with hi₁ hi₁, { have hi₂ : J₂.lower i = x i, from (H _).1 hi₁, have H₁ : x i < J₁.upper i, by simpa only [hi₁] using J₁.lower_lt_upper i, have H₂ : x i < J₂.upper i, by simpa only [hi₂] using J₂.lower_lt_upper i, rw [Ioc_inter_Ioc, hi₁, hi₂, sup_idem, set.nonempty_Ioc], exact lt_min H₁ H₂ }, { have hi₂ : J₂.lower i < x i, from (hx₂.1 i).lt_of_ne (mt (H _).2 hi₁.ne), exact ⟨x i, ⟨hi₁, hx₁.2 i⟩, ⟨hi₂, hx₂.2 i⟩⟩ } end /-- The set of boxes of a prepartition that contain `x` in their closures has cardinality at most `2 ^ fintype.card ι`. -/ lemma card_filter_mem_Icc_le [fintype ι] (x : ι → ℝ) : (π.boxes.filter (λ J : box ι, x ∈ J.Icc)).card ≤ 2 ^ fintype.card ι := begin rw [← fintype.card_set], refine finset.card_le_card_of_inj_on (λ J : box ι, {i | J.lower i = x i}) (λ _ _, finset.mem_univ _) _, simpa only [finset.mem_filter] using π.inj_on_set_of_mem_Icc_set_of_lower_eq x end /-- Given a prepartition `π : box_integral.prepartition I`, `π.Union` is the part of `I` covered by the boxes of `π`. -/ protected def Union : set (ι → ℝ) := ⋃ J ∈ π, ↑J lemma Union_def : π.Union = ⋃ J ∈ π, ↑J := rfl lemma Union_def' : π.Union = ⋃ J ∈ π.boxes, ↑J := rfl @[simp] lemma mem_Union : x ∈ π.Union ↔ ∃ J ∈ π, x ∈ J := set.mem_Union₂ @[simp] lemma Union_single (h : J ≤ I) : (single I J h).Union = J := by simp [Union_def] @[simp] lemma Union_top : (⊤ : prepartition I).Union = I := by simp [prepartition.Union] @[simp] lemma Union_eq_empty : π₁.Union = ∅ ↔ π₁ = ⊥ := by simp [← injective_boxes.eq_iff, finset.ext_iff, prepartition.Union, imp_false] @[simp] lemma Union_bot : (⊥ : prepartition I).Union = ∅ := Union_eq_empty.2 rfl lemma subset_Union (h : J ∈ π) : ↑J ⊆ π.Union := subset_bUnion_of_mem h lemma Union_subset : π.Union ⊆ I := Union₂_subset π.le_of_mem' @[mono] lemma Union_mono (h : π₁ ≤ π₂) : π₁.Union ⊆ π₂.Union := λ x hx, let ⟨J₁, hJ₁, hx⟩ := π₁.mem_Union.1 hx, ⟨J₂, hJ₂, hle⟩ := h hJ₁ in π₂.mem_Union.2 ⟨J₂, hJ₂, hle hx⟩ lemma disjoint_boxes_of_disjoint_Union (h : disjoint π₁.Union π₂.Union) : disjoint π₁.boxes π₂.boxes := finset.disjoint_left.2 $ λ J h₁ h₂, h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂) ⟨J.upper_mem, J.upper_mem⟩ lemma le_iff_nonempty_imp_le_and_Union_subset : π₁ ≤ π₂ ↔ (∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J') ∧ π₁.Union ⊆ π₂.Union := begin fsplit, { refine λ H, ⟨λ J hJ J' hJ' Hne, _, Union_mono H⟩, rcases H hJ with ⟨J'', hJ'', Hle⟩, rcases Hne with ⟨x, hx, hx'⟩, rwa π₂.eq_of_mem_of_mem hJ' hJ'' hx' (Hle hx) }, { rintro ⟨H, HU⟩ J hJ, simp only [set.subset_def, mem_Union] at HU, rcases HU J.upper ⟨J, hJ, J.upper_mem⟩ with ⟨J₂, hJ₂, hx⟩, exact ⟨J₂, hJ₂, H _ hJ _ hJ₂ ⟨_, J.upper_mem, hx⟩⟩ } end lemma eq_of_boxes_subset_Union_superset (h₁ : π₁.boxes ⊆ π₂.boxes) (h₂ : π₂.Union ⊆ π₁.Union) : π₁ = π₂ := le_antisymm (λ J hJ, ⟨J, h₁ hJ, le_rfl⟩) $ le_iff_nonempty_imp_le_and_Union_subset.2 ⟨λ J₁ hJ₁ J₂ hJ₂ Hne, (π₂.eq_of_mem_of_mem hJ₁ (h₁ hJ₂) Hne.some_spec.1 Hne.some_spec.2).le, h₂⟩ /-- Given a prepartition `π` of a box `I` and a collection of prepartitions `πi J` of all boxes `J ∈ π`, returns the prepartition of `I` into the union of the boxes of all `πi J`. Though we only use the values of `πi` on the boxes of `π`, we require `πi` to be a globally defined function. -/ @[simps] def bUnion (πi : Π J : box ι, prepartition J) : prepartition I := { boxes := π.boxes.bUnion $ λ J, (πi J).boxes, le_of_mem' := λ J hJ, begin simp only [finset.mem_bUnion, exists_prop, mem_boxes] at hJ, rcases hJ with ⟨J', hJ', hJ⟩, exact ((πi J').le_of_mem hJ).trans (π.le_of_mem hJ') end, pairwise_disjoint := begin simp only [set.pairwise, finset.mem_coe, finset.mem_bUnion], rintro J₁' ⟨J₁, hJ₁, hJ₁'⟩ J₂' ⟨J₂, hJ₂, hJ₂'⟩ Hne x ⟨hx₁, hx₂⟩, apply Hne, obtain rfl : J₁ = J₂, from π.eq_of_mem_of_mem hJ₁ hJ₂ ((πi J₁).le_of_mem hJ₁' hx₁) ((πi J₂).le_of_mem hJ₂' hx₂), exact (πi J₁).eq_of_mem_of_mem hJ₁' hJ₂' hx₁ hx₂ end } variables {πi πi₁ πi₂ : Π J : box ι, prepartition J} @[simp] lemma mem_bUnion : J ∈ π.bUnion πi ↔ ∃ J' ∈ π, J ∈ πi J' := by simp [bUnion] lemma bUnion_le (πi : Π J, prepartition J) : π.bUnion πi ≤ π := λ J hJ, let ⟨J', hJ', hJ⟩ := π.mem_bUnion.1 hJ in ⟨J', hJ', (πi J').le_of_mem hJ⟩ @[simp] lemma bUnion_top : π.bUnion (λ _, ⊤) = π := by { ext, simp } @[congr] lemma bUnion_congr (h : π₁ = π₂) (hi : ∀ J ∈ π₁, πi₁ J = πi₂ J) : π₁.bUnion πi₁ = π₂.bUnion πi₂ := by { subst π₂, ext J, simp [hi] { contextual := tt } } lemma bUnion_congr_of_le (h : π₁ = π₂) (hi : ∀ J ≤ I, πi₁ J = πi₂ J) : π₁.bUnion πi₁ = π₂.bUnion πi₂ := bUnion_congr h $ λ J hJ, hi J (π₁.le_of_mem hJ) @[simp] lemma Union_bUnion (πi : Π J : box ι, prepartition J) : (π.bUnion πi).Union = ⋃ J ∈ π, (πi J).Union := by simp [prepartition.Union] @[simp] lemma sum_bUnion_boxes {M : Type*} [add_comm_monoid M] (π : prepartition I) (πi : Π J, prepartition J) (f : box ι → M) : ∑ J in π.boxes.bUnion (λ J, (πi J).boxes), f J = ∑ J in π.boxes, ∑ J' in (πi J).boxes, f J' := begin refine finset.sum_bUnion (λ J₁ h₁ J₂ h₂ hne, finset.disjoint_left.2 $ λ J' h₁' h₂', _), exact hne (π.eq_of_le_of_le h₁ h₂ ((πi J₁).le_of_mem h₁') ((πi J₂).le_of_mem h₂')) end /-- Given a box `J ∈ π.bUnion πi`, returns the box `J' ∈ π` such that `J ∈ πi J'`. For `J ∉ π.bUnion πi`, returns `I`. -/ def bUnion_index (πi : Π J, prepartition J) (J : box ι) : box ι := if hJ : J ∈ π.bUnion πi then (π.mem_bUnion.1 hJ).some else I lemma bUnion_index_mem (hJ : J ∈ π.bUnion πi) : π.bUnion_index πi J ∈ π := by { rw [bUnion_index, dif_pos hJ], exact (π.mem_bUnion.1 hJ).some_spec.fst } lemma bUnion_index_le (πi : Π J, prepartition J) (J : box ι) : π.bUnion_index πi J ≤ I := begin by_cases hJ : J ∈ π.bUnion πi, { exact π.le_of_mem (π.bUnion_index_mem hJ) }, { rw [bUnion_index, dif_neg hJ], exact le_rfl } end lemma mem_bUnion_index (hJ : J ∈ π.bUnion πi) : J ∈ πi (π.bUnion_index πi J) := by convert (π.mem_bUnion.1 hJ).some_spec.snd; exact dif_pos hJ lemma le_bUnion_index (hJ : J ∈ π.bUnion πi) : J ≤ π.bUnion_index πi J := le_of_mem _ (π.mem_bUnion_index hJ) /-- Uniqueness property of `box_integral.partition.bUnion_index`. -/ lemma bUnion_index_of_mem (hJ : J ∈ π) {J'} (hJ' : J' ∈ πi J) : π.bUnion_index πi J' = J := have J' ∈ π.bUnion πi, from π.mem_bUnion.2 ⟨J, hJ, hJ'⟩, π.eq_of_le_of_le (π.bUnion_index_mem this) hJ (π.le_bUnion_index this) (le_of_mem _ hJ') lemma bUnion_assoc (πi : Π J, prepartition J) (πi' : box ι → Π J : box ι, prepartition J) : π.bUnion (λ J, (πi J).bUnion (πi' J)) = (π.bUnion πi).bUnion (λ J, πi' (π.bUnion_index πi J) J) := begin ext J, simp only [mem_bUnion, exists_prop], fsplit, { rintro ⟨J₁, hJ₁, J₂, hJ₂, hJ⟩, refine ⟨J₂, ⟨J₁, hJ₁, hJ₂⟩, _⟩, rwa π.bUnion_index_of_mem hJ₁ hJ₂ }, { rintro ⟨J₁, ⟨J₂, hJ₂, hJ₁⟩, hJ⟩, refine ⟨J₂, hJ₂, J₁, hJ₁, _⟩, rwa π.bUnion_index_of_mem hJ₂ hJ₁ at hJ } end /-- Create a `box_integral.prepartition` from a collection of possibly empty boxes by filtering out the empty one if it exists. -/ def of_with_bot (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) : prepartition I := { boxes := boxes.erase_none, le_of_mem' := λ J hJ, begin rw mem_erase_none at hJ, simpa only [with_bot.some_eq_coe, with_bot.coe_le_coe] using le_of_mem _ hJ end, pairwise_disjoint := λ J₁ h₁ J₂ h₂ hne, begin simp only [mem_coe, mem_erase_none] at h₁ h₂, exact box.disjoint_coe.1 (pairwise_disjoint h₁ h₂ (mt option.some_inj.1 hne)) end } @[simp] lemma mem_of_with_bot {boxes : finset (with_bot (box ι))} {h₁ h₂} : J ∈ (of_with_bot boxes h₁ h₂ : prepartition I) ↔ (J : with_bot (box ι)) ∈ boxes := mem_erase_none @[simp] lemma Union_of_with_bot (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) : (of_with_bot boxes le_of_mem pairwise_disjoint).Union = ⋃ J ∈ boxes, ↑J := begin suffices : (⋃ (J : box ι) (hJ : ↑J ∈ boxes), ↑J) = ⋃ J ∈ boxes, ↑J, by simpa [of_with_bot, prepartition.Union], simp only [← box.bUnion_coe_eq_coe, @Union_comm _ _ (box ι), @Union_comm _ _ (@eq _ _ _), Union_Union_eq_right] end lemma of_with_bot_le {boxes : finset (with_bot (box ι))} {le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ boxes, J ≠ ⊥ → ∃ J' ∈ π, J ≤ ↑J') : of_with_bot boxes le_of_mem pairwise_disjoint ≤ π := have ∀ (J : box ι), ↑J ∈ boxes → ∃ J' ∈ π, J ≤ J', from λ J hJ, by simpa only [with_bot.coe_le_coe] using H J hJ with_bot.coe_ne_bot, by simpa [of_with_bot, le_def] lemma le_of_with_bot {boxes : finset (with_bot (box ι))} {le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ π, ∃ J' ∈ boxes, ↑J ≤ J') : π ≤ of_with_bot boxes le_of_mem pairwise_disjoint := begin intros J hJ, rcases H J hJ with ⟨J', J'mem, hle⟩, lift J' to box ι using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hle, exact ⟨J', mem_of_with_bot.2 J'mem, with_bot.coe_le_coe.1 hle⟩ end lemma of_with_bot_mono {boxes₁ : finset (with_bot (box ι))} {le_of_mem₁ : ∀ J ∈ boxes₁, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint₁ : set.pairwise (boxes₁ : set (with_bot (box ι))) disjoint} {boxes₂ : finset (with_bot (box ι))} {le_of_mem₂ : ∀ J ∈ boxes₂, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint₂ : set.pairwise (boxes₂ : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ boxes₁, J ≠ ⊥ → ∃ J' ∈ boxes₂, J ≤ J') : of_with_bot boxes₁ le_of_mem₁ pairwise_disjoint₁ ≤ of_with_bot boxes₂ le_of_mem₂ pairwise_disjoint₂ := le_of_with_bot _ $ λ J hJ, H J (mem_of_with_bot.1 hJ) with_bot.coe_ne_bot lemma sum_of_with_bot {M : Type*} [add_comm_monoid M] (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) (f : box ι → M) : ∑ J in (of_with_bot boxes le_of_mem pairwise_disjoint).boxes, f J = ∑ J in boxes, option.elim J 0 f := finset.sum_erase_none _ _ /-- Restrict a prepartition to a box. -/ def restrict (π : prepartition I) (J : box ι) : prepartition J := of_with_bot (π.boxes.image (λ J', J ⊓ J')) (λ J' hJ', by { rcases finset.mem_image.1 hJ' with ⟨J', -, rfl⟩, exact inf_le_left }) begin simp only [set.pairwise, on_fun, finset.mem_coe, finset.mem_image], rintro _ ⟨J₁, h₁, rfl⟩ _ ⟨J₂, h₂, rfl⟩ Hne, have : J₁ ≠ J₂, by { rintro rfl, exact Hne rfl }, exact ((box.disjoint_coe.2 $ π.disjoint_coe_of_mem h₁ h₂ this).inf_left' _).inf_right' _ end @[simp] lemma mem_restrict : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : with_bot (box ι)) = J ⊓ J' := by simp [restrict, eq_comm] lemma mem_restrict' : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : set (ι → ℝ)) = J ∩ J' := by simp only [mem_restrict, ← box.with_bot_coe_inj, box.coe_inf, box.coe_coe] @[mono] lemma restrict_mono {π₁ π₂ : prepartition I} (Hle : π₁ ≤ π₂) : π₁.restrict J ≤ π₂.restrict J := begin refine of_with_bot_mono (λ J₁ hJ₁ hne, _), rw finset.mem_image at hJ₁, rcases hJ₁ with ⟨J₁, hJ₁, rfl⟩, rcases Hle hJ₁ with ⟨J₂, hJ₂, hle⟩, exact ⟨_, finset.mem_image_of_mem _ hJ₂, inf_le_inf_left _ $ with_bot.coe_le_coe.2 hle⟩ end lemma monotone_restrict : monotone (λ π : prepartition I, restrict π J) := λ π₁ π₂, restrict_mono /-- Restricting to a larger box does not change the set of boxes. We cannot claim equality of prepartitions because they have different types. -/ lemma restrict_boxes_of_le (π : prepartition I) (h : I ≤ J) : (π.restrict J).boxes = π.boxes := begin simp only [restrict, of_with_bot, erase_none_eq_bUnion], refine finset.image_bUnion.trans _, refine (finset.bUnion_congr rfl _).trans finset.bUnion_singleton_eq_self, intros J' hJ', rw [inf_of_le_right, ← with_bot.some_eq_coe, option.to_finset_some], exact with_bot.coe_le_coe.2 ((π.le_of_mem hJ').trans h) end @[simp] lemma restrict_self : π.restrict I = π := injective_boxes $ restrict_boxes_of_le π le_rfl @[simp] lemma Union_restrict : (π.restrict J).Union = J ∩ π.Union := by simp [restrict, ← inter_Union, ← Union_def] @[simp] lemma restrict_bUnion (πi : Π J, prepartition J) (hJ : J ∈ π) : (π.bUnion πi).restrict J = πi J := begin refine (eq_of_boxes_subset_Union_superset (λ J₁ h₁, _) _).symm, { refine (mem_restrict _).2 ⟨J₁, π.mem_bUnion.2 ⟨J, hJ, h₁⟩, (inf_of_le_right _).symm⟩, exact with_bot.coe_le_coe.2 (le_of_mem _ h₁) }, { simp only [Union_restrict, Union_bUnion, set.subset_def, set.mem_inter_eq, set.mem_Union], rintro x ⟨hxJ, J₁, h₁, hx⟩, obtain rfl : J = J₁, from π.eq_of_mem_of_mem hJ h₁ hxJ (Union_subset _ hx), exact hx } end lemma bUnion_le_iff {πi : Π J, prepartition J} {π' : prepartition I} : π.bUnion πi ≤ π' ↔ ∀ J ∈ π, πi J ≤ π'.restrict J := begin fsplit; intros H J hJ, { rw ← π.restrict_bUnion πi hJ, exact restrict_mono H }, { rw mem_bUnion at hJ, rcases hJ with ⟨J₁, h₁, hJ⟩, rcases H J₁ h₁ hJ with ⟨J₂, h₂, Hle⟩, rcases π'.mem_restrict.mp h₂ with ⟨J₃, h₃, H⟩, exact ⟨J₃, h₃, Hle.trans $ with_bot.coe_le_coe.1 $ H.trans_le inf_le_right⟩ } end lemma le_bUnion_iff {πi : Π J, prepartition J} {π' : prepartition I} : π' ≤ π.bUnion πi ↔ π' ≤ π ∧ ∀ J ∈ π, π'.restrict J ≤ πi J := begin refine ⟨λ H, ⟨H.trans (π.bUnion_le πi), λ J hJ, _⟩, _⟩, { rw ← π.restrict_bUnion πi hJ, exact restrict_mono H }, { rintro ⟨H, Hi⟩ J' hJ', rcases H hJ' with ⟨J, hJ, hle⟩, have : J' ∈ π'.restrict J, from π'.mem_restrict.2 ⟨J', hJ', (inf_of_le_right $ with_bot.coe_le_coe.2 hle).symm⟩, rcases Hi J hJ this with ⟨Ji, hJi, hlei⟩, exact ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hlei⟩ } end instance : has_inf (prepartition I) := ⟨λ π₁ π₂, π₁.bUnion (λ J, π₂.restrict J)⟩ lemma inf_def (π₁ π₂ : prepartition I) : π₁ ⊓ π₂ = π₁.bUnion (λ J, π₂.restrict J) := rfl @[simp] lemma mem_inf {π₁ π₂ : prepartition I} : J ∈ π₁ ⊓ π₂ ↔ ∃ (J₁ ∈ π₁) (J₂ ∈ π₂), (J : with_bot (box ι)) = J₁ ⊓ J₂ := by simp only [inf_def, mem_bUnion, mem_restrict] @[simp] lemma Union_inf (π₁ π₂ : prepartition I) : (π₁ ⊓ π₂).Union = π₁.Union ∩ π₂.Union := by simp only [inf_def, Union_bUnion, Union_restrict, ← Union_inter, ← Union_def] instance : semilattice_inf (prepartition I) := { inf_le_left := λ π₁ π₂, π₁.bUnion_le _, inf_le_right := λ π₁ π₂, (bUnion_le_iff _).2 (λ J hJ, le_rfl), le_inf := λ π π₁ π₂ h₁ h₂, π₁.le_bUnion_iff.2 ⟨h₁, λ J hJ, restrict_mono h₂⟩, .. prepartition.has_inf, .. prepartition.partial_order } /-- The prepartition with boxes `{J ∈ π | p J}`. -/ @[simps] def filter (π : prepartition I) (p : box ι → Prop) : prepartition I := { boxes := π.boxes.filter p, le_of_mem' := λ J hJ, π.le_of_mem (mem_filter.1 hJ).1, pairwise_disjoint := λ J₁ h₁ J₂ h₂, π.disjoint_coe_of_mem (mem_filter.1 h₁).1 (mem_filter.1 h₂).1 } @[simp] lemma mem_filter {p : box ι → Prop} : J ∈ π.filter p ↔ J ∈ π ∧ p J := finset.mem_filter lemma filter_le (π : prepartition I) (p : box ι → Prop) : π.filter p ≤ π := λ J hJ, let ⟨hπ, hp⟩ := π.mem_filter.1 hJ in ⟨J, hπ, le_rfl⟩ lemma filter_of_true {p : box ι → Prop} (hp : ∀ J ∈ π, p J) : π.filter p = π := by { ext J, simpa using hp J } @[simp] lemma filter_true : π.filter (λ _, true) = π := π.filter_of_true (λ _ _, trivial) @[simp] lemma Union_filter_not (π : prepartition I) (p : box ι → Prop) : (π.filter (λ J, ¬p J)).Union = π.Union \ (π.filter p).Union := begin simp only [prepartition.Union], convert (@set.bUnion_diff_bUnion_eq _ (box ι) π.boxes (π.filter p).boxes coe _).symm, { ext J x, simp { contextual := tt } }, { convert π.pairwise_disjoint, simp } end lemma sum_fiberwise {α M} [add_comm_monoid M] (π : prepartition I) (f : box ι → α) (g : box ι → M) : ∑ y in π.boxes.image f, ∑ J in (π.filter (λ J, f J = y)).boxes, g J = ∑ J in π.boxes, g J := by convert sum_fiberwise_of_maps_to (λ _, finset.mem_image_of_mem f) g /-- Union of two disjoint prepartitions. -/ @[simps] def disj_union (π₁ π₂ : prepartition I) (h : disjoint π₁.Union π₂.Union) : prepartition I := { boxes := π₁.boxes ∪ π₂.boxes, le_of_mem' := λ J hJ, (finset.mem_union.1 hJ).elim π₁.le_of_mem π₂.le_of_mem, pairwise_disjoint := suffices ∀ (J₁ ∈ π₁) (J₂ ∈ π₂), J₁ ≠ J₂ → disjoint (J₁ : set (ι → ℝ)) J₂, by simpa [pairwise_union_of_symmetric (symmetric_disjoint.comap _), pairwise_disjoint], λ J₁ h₁ J₂ h₂ _, h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂) } @[simp] lemma mem_disj_union (H : disjoint π₁.Union π₂.Union) : J ∈ π₁.disj_union π₂ H ↔ J ∈ π₁ ∨ J ∈ π₂ := finset.mem_union @[simp] lemma Union_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).Union = π₁.Union ∪ π₂.Union := by simp [disj_union, prepartition.Union, Union_or, Union_union_distrib] @[simp] lemma sum_disj_union_boxes {M : Type*} [add_comm_monoid M] (h : disjoint π₁.Union π₂.Union) (f : box ι → M) : ∑ J in π₁.boxes ∪ π₂.boxes, f J = ∑ J in π₁.boxes, f J + ∑ J in π₂.boxes, f J := sum_union $ disjoint_boxes_of_disjoint_Union h section distortion variable [fintype ι] /-- The distortion of a prepartition is the maximum of the distortions of the boxes of this prepartition. -/ def distortion : ℝ≥0 := π.boxes.sup box.distortion lemma distortion_le_of_mem (h : J ∈ π) : J.distortion ≤ π.distortion := le_sup h lemma distortion_le_iff {c : ℝ≥0} : π.distortion ≤ c ↔ ∀ J ∈ π, box.distortion J ≤ c := sup_le_iff lemma distortion_bUnion (π : prepartition I) (πi : Π J, prepartition J) : (π.bUnion πi).distortion = π.boxes.sup (λ J, (πi J).distortion) := sup_bUnion _ _ @[simp] lemma distortion_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).distortion = max π₁.distortion π₂.distortion := sup_union lemma distortion_of_const {c} (h₁ : π.boxes.nonempty) (h₂ : ∀ J ∈ π, box.distortion J = c) : π.distortion = c := (sup_congr rfl h₂).trans (sup_const h₁ _) @[simp] lemma distortion_top (I : box ι) : distortion (⊤ : prepartition I) = I.distortion := sup_singleton @[simp] lemma distortion_bot (I : box ι) : distortion (⊥ : prepartition I) = 0 := sup_empty end distortion /-- A prepartition `π` of `I` is a partition if the boxes of `π` cover the whole `I`. -/ def is_partition (π : prepartition I) := ∀ x ∈ I, ∃ J ∈ π, x ∈ J lemma is_partition_iff_Union_eq {π : prepartition I} : π.is_partition ↔ π.Union = I := by simp_rw [is_partition, set.subset.antisymm_iff, π.Union_subset, true_and, set.subset_def, mem_Union, box.mem_coe] @[simp] lemma is_partition_single_iff (h : J ≤ I) : is_partition (single I J h) ↔ J = I := by simp [is_partition_iff_Union_eq] lemma is_partition_top (I : box ι) : is_partition (⊤ : prepartition I) := λ x hx, ⟨I, mem_top.2 rfl, hx⟩ namespace is_partition variables {π} lemma Union_eq (h : π.is_partition) : π.Union = I := is_partition_iff_Union_eq.1 h lemma Union_subset (h : π.is_partition) (π₁ : prepartition I) : π₁.Union ⊆ π.Union := h.Union_eq.symm ▸ π₁.Union_subset protected lemma exists_unique (h : π.is_partition) (hx : x ∈ I) : ∃! J ∈ π, x ∈ J := begin rcases h x hx with ⟨J, h, hx⟩, exact exists_unique.intro2 J h hx (λ J' h' hx', π.eq_of_mem_of_mem h' h hx' hx), end lemma nonempty_boxes (h : π.is_partition) : π.boxes.nonempty := let ⟨J, hJ, _⟩ := h _ I.upper_mem in ⟨J, hJ⟩ lemma eq_of_boxes_subset (h₁ : π₁.is_partition) (h₂ : π₁.boxes ⊆ π₂.boxes) : π₁ = π₂ := eq_of_boxes_subset_Union_superset h₂ $ h₁.Union_subset _ lemma le_iff (h : π₂.is_partition) : π₁ ≤ π₂ ↔ ∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J' := le_iff_nonempty_imp_le_and_Union_subset.trans $ and_iff_left $ h.Union_subset _ protected lemma bUnion (h : is_partition π) (hi : ∀ J ∈ π, is_partition (πi J)) : is_partition (π.bUnion πi) := λ x hx, let ⟨J, hJ, hxi⟩ := h x hx, ⟨Ji, hJi, hx⟩ := hi J hJ x hxi in ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hx⟩ protected lemma restrict (h : is_partition π) (hJ : J ≤ I) : is_partition (π.restrict J) := is_partition_iff_Union_eq.2 $ by simp [h.Union_eq, hJ] protected lemma inf (h₁ : is_partition π₁) (h₂ : is_partition π₂) : is_partition (π₁ ⊓ π₂) := is_partition_iff_Union_eq.2 $ by simp [h₁.Union_eq, h₂.Union_eq] end is_partition lemma Union_bUnion_partition (h : ∀ J ∈ π, (πi J).is_partition) : (π.bUnion πi).Union = π.Union := (Union_bUnion _ _).trans $ Union_congr_of_surjective id surjective_id $ λ J, Union_congr_of_surjective id surjective_id $ λ hJ, (h J hJ).Union_eq lemma is_partition_disj_union_of_eq_diff (h : π₂.Union = I \ π₁.Union) : is_partition (π₁.disj_union π₂ (h.symm ▸ disjoint_diff)) := is_partition_iff_Union_eq.2 $ (Union_disj_union _).trans $ by simp [h, π₁.Union_subset] end prepartition end box_integral
af3a5d258ecc02cb9f6996367f3e33981999b3e1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/etale.lean
01ea28e03242841325753b9ef11c7a454b507297
[ "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
22,940
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 ring_theory.nilpotent import ring_theory.derivation /-! # Formally étale morphisms An `R`-algebra `A` is formally étale (resp. unramified, smooth) if for every `R`-algebra, every square-zero ideal `I : ideal B` and `f : A →ₐ[R] B ⧸ I`, there exists exactly (resp. at most, at least) one lift `A →ₐ[R] B`. We show that the property extends onto nilpotent ideals, and that these properties are stable under `R`-algebra homomorphisms and compositions. -/ universes u namespace algebra section variables (R : Type u) [comm_semiring R] variables (A : Type u) [semiring A] [algebra R A] variables {B : Type u} [comm_ring B] [algebra R B] (I : ideal B) include R A /-- An `R`-algebra `A` is formally unramified if for every `R`-algebra, every square-zero ideal `I : ideal B` and `f : A →ₐ[R] B ⧸ I`, there exists at most one lift `A →ₐ[R] B`. -/ @[mk_iff] class formally_unramified : Prop := (comp_injective : ∀ ⦃B : Type u⦄ [comm_ring B], by exactI ∀ [algebra R B] (I : ideal B) (hI : I ^ 2 = ⊥), by exactI function.injective ((ideal.quotient.mkₐ R I).comp : (A →ₐ[R] B) → (A →ₐ[R] B ⧸ I))) /-- An `R` algebra `A` is formally smooth if for every `R`-algebra, every square-zero ideal `I : ideal B` and `f : A →ₐ[R] B ⧸ I`, there exists at least one lift `A →ₐ[R] B`. -/ @[mk_iff] class formally_smooth : Prop := (comp_surjective : ∀ ⦃B : Type u⦄ [comm_ring B], by exactI ∀ [algebra R B] (I : ideal B) (hI : I ^ 2 = ⊥), by exactI function.surjective ((ideal.quotient.mkₐ R I).comp : (A →ₐ[R] B) → (A →ₐ[R] B ⧸ I))) /-- An `R` algebra `A` is formally étale if for every `R`-algebra, every square-zero ideal `I : ideal B` and `f : A →ₐ[R] B ⧸ I`, there exists exactly one lift `A →ₐ[R] B`. -/ @[mk_iff] class formally_etale : Prop := (comp_bijective : ∀ ⦃B : Type u⦄ [comm_ring B], by exactI ∀ [algebra R B] (I : ideal B) (hI : I ^ 2 = ⊥), by exactI function.bijective ((ideal.quotient.mkₐ R I).comp : (A →ₐ[R] B) → (A →ₐ[R] B ⧸ I))) variables {R A} lemma formally_etale.iff_unramified_and_smooth : formally_etale R A ↔ formally_unramified R A ∧ formally_smooth R A := begin rw [formally_unramified_iff, formally_smooth_iff, formally_etale_iff], simp_rw ← forall_and_distrib, refl end @[priority 100] instance formally_etale.to_unramified [h : formally_etale R A] : formally_unramified R A := (formally_etale.iff_unramified_and_smooth.mp h).1 @[priority 100] instance formally_etale.to_smooth [h : formally_etale R A] : formally_smooth R A := (formally_etale.iff_unramified_and_smooth.mp h).2 lemma formally_etale.of_unramified_and_smooth [h₁ : formally_unramified R A] [h₂ : formally_smooth R A] : formally_etale R A := formally_etale.iff_unramified_and_smooth.mpr ⟨h₁, h₂⟩ omit R A lemma formally_unramified.lift_unique {B : Type u} [comm_ring B] [_RB : algebra R B] [formally_unramified R A] (I : ideal B) (hI : is_nilpotent I) (g₁ g₂ : A →ₐ[R] B) (h : (ideal.quotient.mkₐ R I).comp g₁ = (ideal.quotient.mkₐ R I).comp g₂) : g₁ = g₂ := begin revert g₁ g₂, change function.injective (ideal.quotient.mkₐ R I).comp, unfreezingI { revert _RB }, apply ideal.is_nilpotent.induction_on I hI, { introsI B _ I hI _, exact formally_unramified.comp_injective I hI }, { introsI B _ I J hIJ h₁ h₂ _ g₁ g₂ e, apply h₁, apply h₂, ext x, replace e := alg_hom.congr_fun e x, dsimp only [alg_hom.comp_apply, ideal.quotient.mkₐ_eq_mk] at e ⊢, rwa [ideal.quotient.eq, ← map_sub, ideal.mem_quotient_iff_mem hIJ, ← ideal.quotient.eq] }, end lemma formally_unramified.ext [formally_unramified R A] (hI : is_nilpotent I) {g₁ g₂ : A →ₐ[R] B} (H : ∀ x, ideal.quotient.mk I (g₁ x) = ideal.quotient.mk I (g₂ x)) : g₁ = g₂ := formally_unramified.lift_unique I hI g₁ g₂ (alg_hom.ext H) lemma formally_unramified.lift_unique_of_ring_hom [formally_unramified R A] {C : Type u} [comm_ring C] (f : B →+* C) (hf : is_nilpotent f.ker) (g₁ g₂ : A →ₐ[R] B) (h : f.comp ↑g₁ = f.comp (g₂ : A →+* B)) : g₁ = g₂ := formally_unramified.lift_unique _ hf _ _ begin ext x, have := ring_hom.congr_fun h x, simpa only [ideal.quotient.eq, function.comp_app, alg_hom.coe_comp, ideal.quotient.mkₐ_eq_mk, ring_hom.mem_ker, map_sub, sub_eq_zero], end lemma formally_unramified.ext' [formally_unramified R A] {C : Type u} [comm_ring C] (f : B →+* C) (hf : is_nilpotent f.ker) (g₁ g₂ : A →ₐ[R] B) (h : ∀ x, f (g₁ x) = f (g₂ x)) : g₁ = g₂ := formally_unramified.lift_unique_of_ring_hom f hf g₁ g₂ (ring_hom.ext h) lemma formally_unramified.lift_unique' [formally_unramified R A] {C : Type u} [comm_ring C] [algebra R C] (f : B →ₐ[R] C) (hf : is_nilpotent (f : B →+* C).ker) (g₁ g₂ : A →ₐ[R] B) (h : f.comp g₁ = f.comp g₂) : g₁ = g₂ := formally_unramified.ext' _ hf g₁ g₂ (alg_hom.congr_fun h) lemma formally_smooth.exists_lift {B : Type u} [comm_ring B] [_RB : algebra R B] [formally_smooth R A] (I : ideal B) (hI : is_nilpotent I) (g : A →ₐ[R] B ⧸ I) : ∃ f : A →ₐ[R] B, (ideal.quotient.mkₐ R I).comp f = g := begin revert g, change function.surjective (ideal.quotient.mkₐ R I).comp, unfreezingI { revert _RB }, apply ideal.is_nilpotent.induction_on I hI, { introsI B _ I hI _, exact formally_smooth.comp_surjective I hI }, { introsI B _ I J hIJ h₁ h₂ _ g, let : ((B ⧸ I) ⧸ J.map (ideal.quotient.mk I)) ≃ₐ[R] B ⧸ J := { commutes' := λ x, rfl, ..((double_quot.quot_quot_equiv_quot_sup I J).trans (ideal.quot_equiv_of_eq (sup_eq_right.mpr hIJ))) }, obtain ⟨g', e⟩ := h₂ (this.symm.to_alg_hom.comp g), obtain ⟨g', rfl⟩ := h₁ g', replace e := congr_arg this.to_alg_hom.comp e, conv_rhs at e { rw [← alg_hom.comp_assoc, alg_equiv.to_alg_hom_eq_coe, alg_equiv.to_alg_hom_eq_coe, alg_equiv.comp_symm, alg_hom.id_comp] }, exact ⟨g', e⟩ } end /-- For a formally smooth `R`-algebra `A` and a map `f : A →ₐ[R] B ⧸ I` with `I` square-zero, this is an arbitrary lift `A →ₐ[R] B`. -/ noncomputable def formally_smooth.lift [formally_smooth R A] (I : ideal B) (hI : is_nilpotent I) (g : A →ₐ[R] B ⧸ I) : A →ₐ[R] B := (formally_smooth.exists_lift I hI g).some @[simp] lemma formally_smooth.comp_lift [formally_smooth R A] (I : ideal B) (hI : is_nilpotent I) (g : A →ₐ[R] B ⧸ I) : (ideal.quotient.mkₐ R I).comp (formally_smooth.lift I hI g) = g := (formally_smooth.exists_lift I hI g).some_spec @[simp] lemma formally_smooth.mk_lift [formally_smooth R A] (I : ideal B) (hI : is_nilpotent I) (g : A →ₐ[R] B ⧸ I) (x : A) : ideal.quotient.mk I (formally_smooth.lift I hI g x) = g x := alg_hom.congr_fun (formally_smooth.comp_lift I hI g : _) x variables {C : Type u} [comm_ring C] [algebra R C] /-- For a formally smooth `R`-algebra `A` and a map `f : A →ₐ[R] B ⧸ I` with `I` nilpotent, this is an arbitrary lift `A →ₐ[R] B`. -/ noncomputable def formally_smooth.lift_of_surjective [formally_smooth R A] (f : A →ₐ[R] C) (g : B →ₐ[R] C) (hg : function.surjective g) (hg' : is_nilpotent (g : B →+* C).ker) : A →ₐ[R] B := formally_smooth.lift _ hg' ((ideal.quotient_ker_alg_equiv_of_surjective hg).symm.to_alg_hom.comp f) @[simp] lemma formally_smooth.lift_of_surjective_apply [formally_smooth R A] (f : A →ₐ[R] C) (g : B →ₐ[R] C) (hg : function.surjective g) (hg' : is_nilpotent (g : B →+* C).ker) (x : A) : g (formally_smooth.lift_of_surjective f g hg hg' x) = f x := begin apply (ideal.quotient_ker_alg_equiv_of_surjective hg).symm.injective, change _ = ((ideal.quotient_ker_alg_equiv_of_surjective hg).symm.to_alg_hom.comp f) x, rw [← formally_smooth.mk_lift _ hg' ((ideal.quotient_ker_alg_equiv_of_surjective hg).symm.to_alg_hom.comp f)], apply (ideal.quotient_ker_alg_equiv_of_surjective hg).injective, rw [alg_equiv.apply_symm_apply, ideal.quotient_ker_alg_equiv_of_surjective, ideal.quotient_ker_alg_equiv_of_right_inverse.apply], exact (ideal.ker_lift_alg_mk _ _).symm end @[simp] lemma formally_smooth.comp_lift_of_surjective [formally_smooth R A] (f : A →ₐ[R] C) (g : B →ₐ[R] C) (hg : function.surjective g) (hg' : is_nilpotent (g : B →+* C).ker) : g.comp (formally_smooth.lift_of_surjective f g hg hg') = f := alg_hom.ext (formally_smooth.lift_of_surjective_apply f g hg hg') end section of_equiv variables {R : Type u} [comm_semiring R] variables {A B : Type u} [semiring A] [algebra R A] [semiring B] [algebra R B] lemma formally_smooth.of_equiv [formally_smooth R A] (e : A ≃ₐ[R] B) : formally_smooth R B := begin constructor, introsI C _ _ I hI f, use (formally_smooth.lift I ⟨2, hI⟩ (f.comp e : A →ₐ[R] C ⧸ I)).comp e.symm, rw [← alg_hom.comp_assoc, formally_smooth.comp_lift, alg_hom.comp_assoc, alg_equiv.comp_symm, alg_hom.comp_id], end lemma formally_unramified.of_equiv [formally_unramified R A] (e : A ≃ₐ[R] B) : formally_unramified R B := begin constructor, introsI C _ _ I hI f₁ f₂ e', rw [← f₁.comp_id, ← f₂.comp_id, ← e.comp_symm, ← alg_hom.comp_assoc, ← alg_hom.comp_assoc], congr' 1, refine formally_unramified.comp_injective I hI _, rw [← alg_hom.comp_assoc, e', alg_hom.comp_assoc], end lemma formally_etale.of_equiv [formally_etale R A] (e : A ≃ₐ[R] B) : formally_etale R B := formally_etale.iff_unramified_and_smooth.mpr ⟨formally_unramified.of_equiv e, formally_smooth.of_equiv e⟩ end of_equiv section polynomial open_locale polynomial variables (R : Type u) [comm_semiring R] instance formally_smooth.mv_polynomial (σ : Type u) : formally_smooth R (mv_polynomial σ R) := begin constructor, introsI C _ _ I hI f, have : ∀ (s : σ), ∃ c : C, ideal.quotient.mk I c = f (mv_polynomial.X s), { exact λ s, ideal.quotient.mk_surjective _ }, choose g hg, refine ⟨mv_polynomial.aeval g, _⟩, ext s, rw [← hg, alg_hom.comp_apply, mv_polynomial.aeval_X], refl, end instance formally_smooth.polynomial : formally_smooth R R[X] := @@formally_smooth.of_equiv _ _ _ _ _ (formally_smooth.mv_polynomial R punit) (mv_polynomial.punit_alg_equiv R) end polynomial section comp variables (R : Type u) [comm_semiring R] variables (A : Type u) [comm_semiring A] [algebra R A] variables (B : Type u) [semiring B] [algebra R B] [algebra A B] [is_scalar_tower R A B] lemma formally_smooth.comp [formally_smooth R A] [formally_smooth A B] : formally_smooth R B := begin constructor, introsI C _ _ I hI f, obtain ⟨f', e⟩ := formally_smooth.comp_surjective I hI (f.comp (is_scalar_tower.to_alg_hom R A B)), letI := f'.to_ring_hom.to_algebra, obtain ⟨f'', e'⟩ := formally_smooth.comp_surjective I hI { commutes' := alg_hom.congr_fun e.symm, ..f.to_ring_hom }, apply_fun (alg_hom.restrict_scalars R) at e', exact ⟨f''.restrict_scalars _, e'.trans (alg_hom.ext $ λ _, rfl)⟩, end lemma formally_unramified.comp [formally_unramified R A] [formally_unramified A B] : formally_unramified R B := begin constructor, introsI C _ _ I hI f₁ f₂ e, have e' := formally_unramified.lift_unique I ⟨2, hI⟩ (f₁.comp $ is_scalar_tower.to_alg_hom R A B) (f₂.comp $ is_scalar_tower.to_alg_hom R A B) (by rw [← alg_hom.comp_assoc, e, alg_hom.comp_assoc]), letI := (f₁.comp (is_scalar_tower.to_alg_hom R A B)).to_ring_hom.to_algebra, let F₁ : B →ₐ[A] C := { commutes' := λ r, rfl, ..f₁ }, let F₂ : B →ₐ[A] C := { commutes' := alg_hom.congr_fun e'.symm, ..f₂ }, ext1, change F₁ x = F₂ x, congr, exact formally_unramified.ext I ⟨2, hI⟩ (alg_hom.congr_fun e), end lemma formally_unramified.of_comp [formally_unramified R B] : formally_unramified A B := begin constructor, introsI Q _ _ I e f₁ f₂ e', letI := ((algebra_map A Q).comp (algebra_map R A)).to_algebra, letI : is_scalar_tower R A Q := is_scalar_tower.of_algebra_map_eq' rfl, refine alg_hom.restrict_scalars_injective R _, refine formally_unramified.ext I ⟨2, e⟩ _, intro x, exact alg_hom.congr_fun e' x end lemma formally_etale.comp [formally_etale R A] [formally_etale A B] : formally_etale R B := formally_etale.iff_unramified_and_smooth.mpr ⟨formally_unramified.comp R A B, formally_smooth.comp R A B⟩ end comp section of_surjective variables {R S : Type u} [comm_ring R] [comm_semiring S] variables {P A : Type u} [comm_ring A] [algebra R A] [comm_ring P] [algebra R P] variables (I : ideal P) (f : P →ₐ[R] A) (hf : function.surjective f) lemma formally_smooth.of_split [formally_smooth R P] (g : A →ₐ[R] P ⧸ f.to_ring_hom.ker ^ 2) (hg : f.ker_square_lift.comp g = alg_hom.id R A) : formally_smooth R A := begin constructor, introsI C _ _ I hI i, let l : P ⧸ f.to_ring_hom.ker ^ 2 →ₐ[R] C, { refine ideal.quotient.liftₐ _ (formally_smooth.lift I ⟨2, hI⟩ (i.comp f)) _, have : ring_hom.ker f ≤ I.comap (formally_smooth.lift I ⟨2, hI⟩ (i.comp f)), { rintros x (hx : f x = 0), have : _ = i (f x) := (formally_smooth.mk_lift I ⟨2, hI⟩ (i.comp f) x : _), rwa [hx, map_zero, ← ideal.quotient.mk_eq_mk, submodule.quotient.mk_eq_zero] at this }, intros x hx, have := (ideal.pow_mono this 2).trans (ideal.le_comap_pow _ 2) hx, rwa hI at this }, have : i.comp f.ker_square_lift = (ideal.quotient.mkₐ R _).comp l, { apply alg_hom.coe_ring_hom_injective, apply ideal.quotient.ring_hom_ext, ext x, exact (formally_smooth.mk_lift I ⟨2, hI⟩ (i.comp f) x).symm }, exact ⟨l.comp g, by rw [← alg_hom.comp_assoc, ← this, alg_hom.comp_assoc, hg, alg_hom.comp_id]⟩ end include hf /-- Let `P →ₐ[R] A` be a surjection with kernel `J`, and `P` a formally smooth `R`-algebra, then `A` is formally smooth over `R` iff the surjection `P ⧸ J ^ 2 →ₐ[R] A` has a section. Geometric intuition: we require that a first-order thickening of `Spec A` inside `Spec P` admits a retraction. -/ lemma formally_smooth.iff_split_surjection [formally_smooth R P] : formally_smooth R A ↔ ∃ g, f.ker_square_lift.comp g = alg_hom.id R A := begin split, { introI, have surj : function.surjective f.ker_square_lift := λ x, ⟨submodule.quotient.mk (hf x).some, (hf x).some_spec⟩, have sqz : ring_hom.ker f.ker_square_lift.to_ring_hom ^ 2 = 0, { rw [alg_hom.ker_ker_sqare_lift, ideal.cotangent_ideal_square, ideal.zero_eq_bot] }, refine ⟨formally_smooth.lift _ ⟨2, sqz⟩ (ideal.quotient_ker_alg_equiv_of_surjective surj).symm.to_alg_hom, _⟩, ext x, have := (ideal.quotient_ker_alg_equiv_of_surjective surj).to_alg_hom.congr_arg (formally_smooth.mk_lift _ ⟨2, sqz⟩ (ideal.quotient_ker_alg_equiv_of_surjective surj).symm.to_alg_hom x), dsimp at this, rw [alg_equiv.apply_symm_apply] at this, conv_rhs { rw [← this, alg_hom.id_apply] }, obtain ⟨y, e⟩ := ideal.quotient.mk_surjective (formally_smooth.lift _ ⟨2, sqz⟩ (ideal.quotient_ker_alg_equiv_of_surjective surj).symm.to_alg_hom x), dsimp at e ⊢, rw ← e, refl }, { rintro ⟨g, hg⟩, exact formally_smooth.of_split f g hg } end end of_surjective section unramified_derivation open_locale tensor_product variables {R S : Type u} [comm_ring R] [comm_ring S] [algebra R S] instance formally_unramified.subsingleton_kaehler_differential [formally_unramified R S] : subsingleton Ω[S⁄R] := begin rw ← not_nontrivial_iff_subsingleton, introsI h, obtain ⟨f₁, f₂, e⟩ := (kaehler_differential.End_equiv R S).injective.nontrivial, apply e, ext1, apply formally_unramified.lift_unique' _ _ _ _ (f₁.2.trans f₂.2.symm), rw [← alg_hom.to_ring_hom_eq_coe, alg_hom.ker_ker_sqare_lift], exact ⟨_, ideal.cotangent_ideal_square _⟩, end lemma formally_unramified.iff_subsingleton_kaehler_differential : formally_unramified R S ↔ subsingleton Ω[S⁄R] := begin split, { introsI, apply_instance }, { introI H, constructor, introsI B _ _ I hI f₁ f₂ e, letI := f₁.to_ring_hom.to_algebra, haveI := is_scalar_tower.of_algebra_map_eq' (f₁.comp_algebra_map).symm, have := ((kaehler_differential.linear_map_equiv_derivation R S).to_equiv.trans (derivation_to_square_zero_equiv_lift I hI)).surjective.subsingleton, exact subtype.ext_iff.mp (@@subsingleton.elim this ⟨f₁, rfl⟩ ⟨f₂, e.symm⟩) } end end unramified_derivation section base_change open_locale tensor_product variables {R : Type u} [comm_semiring R] variables {A : Type u} [semiring A] [algebra R A] variables (B : Type u) [comm_semiring B] [algebra R B] instance formally_unramified.base_change [formally_unramified R A] : formally_unramified B (B ⊗[R] A) := begin constructor, introsI C _ _ I hI f₁ f₂ e, letI := ((algebra_map B C).comp (algebra_map R B)).to_algebra, haveI : is_scalar_tower R B C := is_scalar_tower.of_algebra_map_eq' rfl, apply alg_hom.restrict_scalars_injective R, apply tensor_product.ext, any_goals { apply_instance }, intros b a, have : b ⊗ₜ[R] a = b • (1 ⊗ₜ a), by { rw [tensor_product.smul_tmul', smul_eq_mul, mul_one] }, rw [this, alg_hom.restrict_scalars_apply, alg_hom.restrict_scalars_apply, map_smul, map_smul], congr' 1, change ((f₁.restrict_scalars R).comp tensor_product.include_right) a = ((f₂.restrict_scalars R).comp tensor_product.include_right) a, congr' 1, refine formally_unramified.ext I ⟨2, hI⟩ _, intro x, exact alg_hom.congr_fun e (1 ⊗ₜ x) end instance formally_smooth.base_change [formally_smooth R A] : formally_smooth B (B ⊗[R] A) := begin constructor, introsI C _ _ I hI f, letI := ((algebra_map B C).comp (algebra_map R B)).to_algebra, haveI : is_scalar_tower R B C := is_scalar_tower.of_algebra_map_eq' rfl, refine ⟨tensor_product.product_left_alg_hom (algebra.of_id B C) _, _⟩, { exact formally_smooth.lift I ⟨2, hI⟩ ((f.restrict_scalars R).comp tensor_product.include_right) }, { apply alg_hom.restrict_scalars_injective R, apply tensor_product.ext, any_goals { apply_instance }, intros b a, suffices : algebra_map B _ b * f (1 ⊗ₜ[R] a) = f (b ⊗ₜ[R] a), { simpa [algebra.of_id_apply] }, rw [← algebra.smul_def, ← map_smul, tensor_product.smul_tmul', smul_eq_mul, mul_one] }, end instance formally_etale.base_change [formally_etale R A] : formally_etale B (B ⊗[R] A) := formally_etale.iff_unramified_and_smooth.mpr ⟨infer_instance, infer_instance⟩ end base_change section localization variables {R S Rₘ Sₘ : Type u} [comm_ring R] [comm_ring S] [comm_ring Rₘ] [comm_ring Sₘ] variables (M : submonoid R) variables [algebra R S] [algebra R Sₘ] [algebra S Sₘ] [algebra R Rₘ] [algebra Rₘ Sₘ] variables [is_scalar_tower R Rₘ Sₘ] [is_scalar_tower R S Sₘ] variables [is_localization M Rₘ] [is_localization (M.map (algebra_map R S)) Sₘ] local attribute [elab_as_eliminator] ideal.is_nilpotent.induction_on include M lemma formally_smooth.of_is_localization : formally_smooth R Rₘ := begin constructor, introsI Q _ _ I e f, have : ∀ x : M, is_unit (algebra_map R Q x), { intro x, apply (is_nilpotent.is_unit_quotient_mk_iff ⟨2, e⟩).mp, convert (is_localization.map_units Rₘ x).map f, simp only [ideal.quotient.mk_algebra_map, alg_hom.commutes] }, let : Rₘ →ₐ[R] Q := { commutes' := is_localization.lift_eq this, ..(is_localization.lift this) }, use this, apply alg_hom.coe_ring_hom_injective, refine is_localization.ring_hom_ext M _, ext, simp, end /-- This holds in general for epimorphisms. -/ lemma formally_unramified.of_is_localization : formally_unramified R Rₘ := begin constructor, introsI Q _ _ I e f₁ f₂ e, apply alg_hom.coe_ring_hom_injective, refine is_localization.ring_hom_ext M _, ext, simp, end lemma formally_etale.of_is_localization : formally_etale R Rₘ := formally_etale.iff_unramified_and_smooth.mpr ⟨formally_unramified.of_is_localization M, formally_smooth.of_is_localization M⟩ lemma formally_smooth.localization_base [formally_smooth R Sₘ] : formally_smooth Rₘ Sₘ := begin constructor, introsI Q _ _ I e f, letI := ((algebra_map Rₘ Q).comp (algebra_map R Rₘ)).to_algebra, letI : is_scalar_tower R Rₘ Q := is_scalar_tower.of_algebra_map_eq' rfl, let f : Sₘ →ₐ[Rₘ] Q, { refine { commutes' := _, ..(formally_smooth.lift I ⟨2, e⟩ (f.restrict_scalars R)) }, intro r, change (ring_hom.comp (formally_smooth.lift I ⟨2, e⟩ (f.restrict_scalars R) : Sₘ →+* Q) (algebra_map _ _)) r = algebra_map _ _ r, congr' 1, refine is_localization.ring_hom_ext M _, rw [ring_hom.comp_assoc, ← is_scalar_tower.algebra_map_eq, ← is_scalar_tower.algebra_map_eq, alg_hom.comp_algebra_map] }, use f, ext, simp, end /-- This actually does not need the localization instance, and is stated here again for consistency. See `algebra.formally_unramified.of_comp` instead. The intended use is for copying proofs between `formally_{unramified, smooth, etale}` without the need to change anything (including removing redundant arguments). -/ @[nolint unused_arguments] lemma formally_unramified.localization_base [formally_unramified R Sₘ] : formally_unramified Rₘ Sₘ := formally_unramified.of_comp R Rₘ Sₘ lemma formally_etale.localization_base [formally_etale R Sₘ] : formally_etale Rₘ Sₘ := formally_etale.iff_unramified_and_smooth.mpr ⟨formally_unramified.localization_base M, formally_smooth.localization_base M⟩ lemma formally_smooth.localization_map [formally_smooth R S] : formally_smooth Rₘ Sₘ := begin haveI : formally_smooth S Sₘ := formally_smooth.of_is_localization (M.map (algebra_map R S)), haveI : formally_smooth R Sₘ := formally_smooth.comp R S Sₘ, exact formally_smooth.localization_base M end lemma formally_unramified.localization_map [formally_unramified R S] : formally_unramified Rₘ Sₘ := begin haveI : formally_unramified S Sₘ := formally_unramified.of_is_localization (M.map (algebra_map R S)), haveI : formally_unramified R Sₘ := formally_unramified.comp R S Sₘ, exact formally_unramified.localization_base M end lemma formally_etale.localization_map [formally_etale R S] : formally_etale Rₘ Sₘ := begin haveI : formally_etale S Sₘ := formally_etale.of_is_localization (M.map (algebra_map R S)), haveI : formally_etale R Sₘ := formally_etale.comp R S Sₘ, exact formally_etale.localization_base M end end localization end algebra
480ca4b5e0fa422d765fc95ce452377949777134
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/normed_space/add_torsor.lean
3f6ac912b33d70a5e53689476ac3a47cbcf6dc31
[ "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
17,779
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov -/ import linear_algebra.affine_space.midpoint import analysis.normed_space.basic import topology.instances.real_vector_space /-! # Torsors of additive normed group actions. This file defines torsors of additive normed group actions, with a metric space structure. The motivating case is Euclidean affine spaces. -/ noncomputable theory open_locale nnreal topological_space open filter /-- A `semi_normed_add_torsor V P` is a torsor of an additive seminormed group action by a `semi_normed_group V` on points `P`. We bundle the pseudometric space structure and require the distance to be the same as results from the norm (which in fact implies the distance yields a pseudometric space, but bundling just the distance and using an instance for the pseudometric space results in type class problems). -/ class semi_normed_add_torsor (V : out_param $ Type*) (P : Type*) [out_param $ semi_normed_group V] [pseudo_metric_space P] extends add_torsor V P := (dist_eq_norm' : ∀ (x y : P), dist x y = ∥(x -ᵥ y : V)∥) /-- A `normed_add_torsor V P` is a torsor of an additive normed group action by a `normed_group V` on points `P`. We bundle the metric space structure and require the distance to be the same as results from the norm (which in fact implies the distance yields a metric space, but bundling just the distance and using an instance for the metric space results in type class problems). -/ class normed_add_torsor (V : out_param $ Type*) (P : Type*) [out_param $ normed_group V] [metric_space P] extends add_torsor V P := (dist_eq_norm' : ∀ (x y : P), dist x y = ∥(x -ᵥ y : V)∥) /-- A `normed_add_torsor` is a `semi_normed_add_torsor`. -/ @[priority 100] instance normed_add_torsor.to_semi_normed_add_torsor {V P : Type*} [normed_group V] [metric_space P] [β : normed_add_torsor V P] : semi_normed_add_torsor V P := { ..β } variables {α V P : Type*} [semi_normed_group V] [pseudo_metric_space P] [semi_normed_add_torsor V P] variables {W Q : Type*} [normed_group W] [metric_space Q] [normed_add_torsor W Q] /-- A `semi_normed_group` is a `semi_normed_add_torsor` over itself. -/ @[priority 100] instance semi_normed_group.normed_add_torsor : semi_normed_add_torsor V V := { dist_eq_norm' := dist_eq_norm } /-- A `normed_group` is a `normed_add_torsor` over itself. -/ @[priority 100] instance normed_group.normed_add_torsor : normed_add_torsor W W := { dist_eq_norm' := dist_eq_norm } include V section variables (V W) /-- The distance equals the norm of subtracting two points. In this lemma, it is necessary to have `V` as an explicit argument; otherwise `rw dist_eq_norm_vsub` sometimes doesn't work. -/ lemma dist_eq_norm_vsub (x y : P) : dist x y = ∥(x -ᵥ y)∥ := semi_normed_add_torsor.dist_eq_norm' x y end @[simp] lemma dist_vadd_cancel_left (v : V) (x y : P) : dist (v +ᵥ x) (v +ᵥ y) = dist x y := by rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, vadd_vsub_vadd_cancel_left] @[simp] lemma dist_vadd_cancel_right (v₁ v₂ : V) (x : P) : dist (v₁ +ᵥ x) (v₂ +ᵥ x) = dist v₁ v₂ := by rw [dist_eq_norm_vsub V, dist_eq_norm, vadd_vsub_vadd_cancel_right] @[simp] lemma dist_vadd_left (v : V) (x : P) : dist (v +ᵥ x) x = ∥v∥ := by simp [dist_eq_norm_vsub V _ x] @[simp] lemma dist_vadd_right (v : V) (x : P) : dist x (v +ᵥ x) = ∥v∥ := by rw [dist_comm, dist_vadd_left] @[simp] lemma dist_vsub_cancel_left (x y z : P) : dist (x -ᵥ y) (x -ᵥ z) = dist y z := by rw [dist_eq_norm, vsub_sub_vsub_cancel_left, dist_comm, dist_eq_norm_vsub V] @[simp] lemma dist_vsub_cancel_right (x y z : P) : dist (x -ᵥ z) (y -ᵥ z) = dist x y := by rw [dist_eq_norm, vsub_sub_vsub_cancel_right, dist_eq_norm_vsub V] lemma dist_vadd_vadd_le (v v' : V) (p p' : P) : dist (v +ᵥ p) (v' +ᵥ p') ≤ dist v v' + dist p p' := by simpa using dist_triangle (v +ᵥ p) (v' +ᵥ p) (v' +ᵥ p') lemma dist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : dist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ dist p₁ p₃ + dist p₂ p₄ := by { rw [dist_eq_norm, vsub_sub_vsub_comm, dist_eq_norm_vsub V, dist_eq_norm_vsub V], exact norm_sub_le _ _ } lemma nndist_vadd_vadd_le (v v' : V) (p p' : P) : nndist (v +ᵥ p) (v' +ᵥ p') ≤ nndist v v' + nndist p p' := by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vadd_vadd_le] lemma nndist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : nndist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ nndist p₁ p₃ + nndist p₂ p₄ := by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vsub_vsub_le] lemma edist_vadd_vadd_le (v v' : V) (p p' : P) : edist (v +ᵥ p) (v' +ᵥ p') ≤ edist v v' + edist p p' := by { simp only [edist_nndist], apply_mod_cast nndist_vadd_vadd_le } lemma edist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : edist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ edist p₁ p₃ + edist p₂ p₄ := by { simp only [edist_nndist], apply_mod_cast nndist_vsub_vsub_le } omit V /-- The pseudodistance defines a pseudometric space structure on the torsor. This is not an instance because it depends on `V` to define a `metric_space P`. -/ def pseudo_metric_space_of_normed_group_of_add_torsor (V P : Type*) [semi_normed_group V] [add_torsor V P] : pseudo_metric_space P := { dist := λ x y, ∥(x -ᵥ y : V)∥, dist_self := λ x, by simp, dist_comm := λ x y, by simp only [←neg_vsub_eq_vsub_rev y x, norm_neg], dist_triangle := begin intros x y z, change ∥x -ᵥ z∥ ≤ ∥x -ᵥ y∥ + ∥y -ᵥ z∥, rw ←vsub_add_vsub_cancel, apply norm_add_le end } /-- The distance defines a metric space structure on the torsor. This is not an instance because it depends on `V` to define a `metric_space P`. -/ def metric_space_of_normed_group_of_add_torsor (V P : Type*) [normed_group V] [add_torsor V P] : metric_space P := { dist := λ x y, ∥(x -ᵥ y : V)∥, dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, by simpa using h, dist_comm := λ x y, by simp only [←neg_vsub_eq_vsub_rev y x, norm_neg], dist_triangle := begin intros x y z, change ∥x -ᵥ z∥ ≤ ∥x -ᵥ y∥ + ∥y -ᵥ z∥, rw ←vsub_add_vsub_cancel, apply norm_add_le end } include V namespace isometric /-- The map `v ↦ v +ᵥ p` as an isometric equivalence between `V` and `P`. -/ def vadd_const (p : P) : V ≃ᵢ P := ⟨equiv.vadd_const p, isometry_emetric_iff_metric.2 $ λ x₁ x₂, dist_vadd_cancel_right x₁ x₂ p⟩ @[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const p) = λ v, v +ᵥ p := rfl @[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const p).symm = λ p', p' -ᵥ p := rfl @[simp] lemma vadd_const_to_equiv (p : P) : (vadd_const p).to_equiv = equiv.vadd_const p := rfl /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P) : P ≃ᵢ V := ⟨equiv.const_vsub p, isometry_emetric_iff_metric.2 $ λ p₁ p₂, dist_vsub_cancel_left _ _ _⟩ @[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P) : ⇑(const_vsub p).symm = λ v, -v +ᵥ p := rfl variables (P) /-- The map `p ↦ v +ᵥ p` as an isometric automorphism of `P`. -/ def const_vadd (v : V) : P ≃ᵢ P := ⟨equiv.const_vadd P v, isometry_emetric_iff_metric.2 $ dist_vadd_cancel_left v⟩ @[simp] lemma coe_const_vadd (v : V) : ⇑(const_vadd P v) = (+ᵥ) v := rfl variable (V) @[simp] lemma const_vadd_zero : const_vadd P (0:V) = isometric.refl P := isometric.to_equiv_inj $ equiv.const_vadd_zero V P variables {P V} /-- Point reflection in `x` as an `isometric` homeomorphism. -/ def point_reflection (x : P) : P ≃ᵢ P := (const_vsub x).trans (vadd_const x) lemma point_reflection_apply (x y : P) : point_reflection x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_to_equiv (x : P) : (point_reflection x).to_equiv = equiv.point_reflection x := rfl @[simp] lemma point_reflection_self (x : P) : point_reflection x x = x := equiv.point_reflection_self x lemma point_reflection_involutive (x : P) : function.involutive (point_reflection x : P → P) := equiv.point_reflection_involutive x @[simp] lemma point_reflection_symm (x : P) : (point_reflection x).symm = point_reflection x := to_equiv_inj $ equiv.point_reflection_symm x @[simp] lemma dist_point_reflection_fixed (x y : P) : dist (point_reflection x y) x = dist y x := by rw [← (point_reflection x).dist_eq y x, point_reflection_self] lemma dist_point_reflection_self' (x y : P) : dist (point_reflection x y) y = ∥bit0 (x -ᵥ y)∥ := by rw [point_reflection_apply, dist_eq_norm_vsub V, vadd_vsub_assoc, bit0] lemma dist_point_reflection_self (𝕜 : Type*) [normed_field 𝕜] [semi_normed_space 𝕜 V] (x y : P) : dist (point_reflection x y) y = ∥(2:𝕜)∥ * dist x y := by rw [dist_point_reflection_self', ← two_smul' 𝕜 (x -ᵥ y), norm_smul, ← dist_eq_norm_vsub V] lemma point_reflection_fixed_iff (𝕜 : Type*) [normed_field 𝕜] [semi_normed_space 𝕜 V] [invertible (2:𝕜)] {x y : P} : point_reflection x y = y ↔ y = x := affine_equiv.point_reflection_fixed_iff_of_module 𝕜 variables [semi_normed_space ℝ V] lemma dist_point_reflection_self_real (x y : P) : dist (point_reflection x y) y = 2 * dist x y := by { rw [dist_point_reflection_self ℝ, real.norm_two], apply_instance } @[simp] lemma point_reflection_midpoint_left (x y : P) : point_reflection (midpoint ℝ x y) x = y := affine_equiv.point_reflection_midpoint_left x y @[simp] lemma point_reflection_midpoint_right (x y : P) : point_reflection (midpoint ℝ x y) y = x := affine_equiv.point_reflection_midpoint_right x y end isometric lemma lipschitz_with.vadd [pseudo_emetric_space α] {f : α → V} {g : α → P} {Kf Kg : ℝ≥0} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (f +ᵥ g) := λ x y, calc edist (f x +ᵥ g x) (f y +ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_vadd_vadd_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.vsub [pseudo_emetric_space α] {f g : α → P} {Kf Kg : ℝ≥0} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (f -ᵥ g) := λ x y, calc edist (f x -ᵥ g x) (f y -ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_vsub_vsub_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma uniform_continuous_vadd : uniform_continuous (λ x : V × P, x.1 +ᵥ x.2) := (lipschitz_with.prod_fst.vadd lipschitz_with.prod_snd).uniform_continuous lemma uniform_continuous_vsub : uniform_continuous (λ x : P × P, x.1 -ᵥ x.2) := (lipschitz_with.prod_fst.vsub lipschitz_with.prod_snd).uniform_continuous lemma continuous_vadd : continuous (λ x : V × P, x.1 +ᵥ x.2) := uniform_continuous_vadd.continuous lemma continuous_vsub : continuous (λ x : P × P, x.1 -ᵥ x.2) := uniform_continuous_vsub.continuous lemma filter.tendsto.vadd {l : filter α} {f : α → V} {g : α → P} {v : V} {p : P} (hf : tendsto f l (𝓝 v)) (hg : tendsto g l (𝓝 p)) : tendsto (f +ᵥ g) l (𝓝 (v +ᵥ p)) := (continuous_vadd.tendsto (v, p)).comp (hf.prod_mk_nhds hg) lemma filter.tendsto.vsub {l : filter α} {f g : α → P} {x y : P} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (f -ᵥ g) l (𝓝 (x -ᵥ y)) := (continuous_vsub.tendsto (x, y)).comp (hf.prod_mk_nhds hg) section variables [topological_space α] lemma continuous.vadd {f : α → V} {g : α → P} (hf : continuous f) (hg : continuous g) : continuous (f +ᵥ g) := continuous_vadd.comp (hf.prod_mk hg) lemma continuous.vsub {f g : α → P} (hf : continuous f) (hg : continuous g) : continuous (f -ᵥ g) := continuous_vsub.comp (hf.prod_mk hg : _) lemma continuous_at.vadd {f : α → V} {g : α → P} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (f +ᵥ g) x := hf.vadd hg lemma continuous_at.vsub {f g : α → P} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (f -ᵥ g) x := hf.vsub hg lemma continuous_within_at.vadd {f : α → V} {g : α → P} {x : α} {s : set α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (f +ᵥ g) s x := hf.vadd hg lemma continuous_within_at.vsub {f g : α → P} {x : α} {s : set α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (f -ᵥ g) s x := hf.vsub hg end section variables {R : Type*} [ring R] [topological_space R] [module R V] [has_continuous_smul R V] lemma filter.tendsto.line_map {l : filter α} {f₁ f₂ : α → P} {g : α → R} {p₁ p₂ : P} {c : R} (h₁ : tendsto f₁ l (𝓝 p₁)) (h₂ : tendsto f₂ l (𝓝 p₂)) (hg : tendsto g l (𝓝 c)) : tendsto (λ x, affine_map.line_map (f₁ x) (f₂ x) (g x)) l (𝓝 $ affine_map.line_map p₁ p₂ c) := (hg.smul (h₂.vsub h₁)).vadd h₁ lemma filter.tendsto.midpoint [invertible (2:R)] {l : filter α} {f₁ f₂ : α → P} {p₁ p₂ : P} (h₁ : tendsto f₁ l (𝓝 p₁)) (h₂ : tendsto f₂ l (𝓝 p₂)) : tendsto (λ x, midpoint R (f₁ x) (f₂ x)) l (𝓝 $ midpoint R p₁ p₂) := h₁.line_map h₂ tendsto_const_nhds end variables {V' : Type*} {P' : Type*} [semi_normed_group V'] [pseudo_metric_space P'] [semi_normed_add_torsor V' P'] /-- The map `g` from `V1` to `V2` corresponding to a map `f` from `P1` to `P2`, at a base point `p`, is an isometry if `f` is one. -/ lemma isometry.vadd_vsub {f : P → P'} (hf : isometry f) {p : P} {g : V → V'} (hg : ∀ v, g v = f (v +ᵥ p) -ᵥ f p) : isometry g := begin convert (isometric.vadd_const (f p)).symm.isometry.comp (hf.comp (isometric.vadd_const p).isometry), exact funext hg end section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [semi_normed_space 𝕜 V] open affine_map /-- If `f` is an affine map, then its linear part is continuous iff `f` is continuous. -/ lemma affine_map.continuous_linear_iff [semi_normed_space 𝕜 V'] {f : P →ᵃ[𝕜] P'} : continuous f.linear ↔ continuous f := begin inhabit P, have : (f.linear : V → V') = (isometric.vadd_const $ f $ default P).to_homeomorph.symm ∘ f ∘ (isometric.vadd_const $ default P).to_homeomorph, { ext v, simp }, rw this, simp only [homeomorph.comp_continuous_iff, homeomorph.comp_continuous_iff'], end @[simp] lemma dist_center_homothety (p₁ p₂ : P) (c : 𝕜) : dist p₁ (homothety p₁ c p₂) = ∥c∥ * dist p₁ p₂ := by simp [homothety_def, norm_smul, ← dist_eq_norm_vsub, dist_comm] @[simp] lemma dist_homothety_center (p₁ p₂ : P) (c : 𝕜) : dist (homothety p₁ c p₂) p₁ = ∥c∥ * dist p₁ p₂ := by rw [dist_comm, dist_center_homothety] @[simp] lemma dist_homothety_self (p₁ p₂ : P) (c : 𝕜) : dist (homothety p₁ c p₂) p₂ = ∥1 - c∥ * dist p₁ p₂ := by rw [homothety_eq_line_map, ← line_map_apply_one_sub, ← homothety_eq_line_map, dist_homothety_center, dist_comm] @[simp] lemma dist_self_homothety (p₁ p₂ : P) (c : 𝕜) : dist p₂ (homothety p₁ c p₂) = ∥1 - c∥ * dist p₁ p₂ := by rw [dist_comm, dist_homothety_self] variables [invertible (2:𝕜)] @[simp] lemma dist_left_midpoint (p₁ p₂ : P) : dist p₁ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [midpoint, ← homothety_eq_line_map, dist_center_homothety, inv_of_eq_inv, ← normed_field.norm_inv] @[simp] lemma dist_midpoint_left (p₁ p₂ : P) : dist (midpoint 𝕜 p₁ p₂) p₁ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [dist_comm, dist_left_midpoint] @[simp] lemma dist_midpoint_right (p₁ p₂ : P) : dist (midpoint 𝕜 p₁ p₂) p₂ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [midpoint_comm, dist_midpoint_left, dist_comm] @[simp] lemma dist_right_midpoint (p₁ p₂ : P) : dist p₂ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [dist_comm, dist_midpoint_right] lemma dist_midpoint_midpoint_le' (p₁ p₂ p₃ p₄ : P) : dist (midpoint 𝕜 p₁ p₂) (midpoint 𝕜 p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / ∥(2 : 𝕜)∥ := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, midpoint_vsub_midpoint]; try { apply_instance }, rw [midpoint_eq_smul_add, norm_smul, inv_of_eq_inv, normed_field.norm_inv, ← div_eq_inv_mul], exact div_le_div_of_le_of_nonneg (norm_add_le _ _) (norm_nonneg _), end end normed_space variables [semi_normed_space ℝ V] [normed_space ℝ W] lemma dist_midpoint_midpoint_le (p₁ p₂ p₃ p₄ : V) : dist (midpoint ℝ p₁ p₂) (midpoint ℝ p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / 2 := by simpa using dist_midpoint_midpoint_le' p₁ p₂ p₃ p₄ include W /-- A continuous map between two normed affine spaces is an affine map provided that it sends midpoints to midpoints. -/ def affine_map.of_map_midpoint (f : P → Q) (h : ∀ x y, f (midpoint ℝ x y) = midpoint ℝ (f x) (f y)) (hfc : continuous f) : P →ᵃ[ℝ] Q := affine_map.mk' f ↑((add_monoid_hom.of_map_midpoint ℝ ℝ ((affine_equiv.vadd_const ℝ (f $ classical.arbitrary P)).symm ∘ f ∘ (affine_equiv.vadd_const ℝ (classical.arbitrary P))) (by simp) (λ x y, by simp [h])).to_real_linear_map $ by apply_rules [continuous.vadd, continuous.vsub, continuous_const, hfc.comp, continuous_id]) (classical.arbitrary P) (λ p, by simp)
8f49018c761272659ecc6e4105f91b890158d1de
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/nat/basic.lean
66ad13b996a730fa0d9a4d8b5195654c97856fe3
[ "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
59,030
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import algebra.ordered_ring /-! # Basic operations on the natural numbers This file contains: - instances on the natural numbers - some basic lemmas about natural numbers - extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `strong_rec'`: recursion based on strong inequalities - decidability instances on predicates about the natural numbers -/ universes u v /-! ### instances -/ instance : nontrivial ℕ := ⟨⟨0, 1, nat.zero_ne_one⟩⟩ instance : comm_semiring nat := { add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm, nsmul := λ m n, m * n, nsmul_zero' := nat.zero_mul, nsmul_succ' := λ n x, by rw [nat.succ_eq_one_add, nat.right_distrib, nat.one_mul] } instance : linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0), mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_eq := nat.decidable_eq, exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩, ..nat.comm_semiring, ..nat.linear_order } -- all the fields are already included in the linear_ordered_semiring instance instance : linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.linear_ordered_semiring } instance : linear_ordered_comm_monoid_with_zero ℕ := { mul_le_mul_left := λ a b h c, nat.mul_le_mul_left c h, ..nat.linear_ordered_semiring, ..(infer_instance : comm_monoid_with_zero ℕ)} /-! Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := assume a b, ⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, eq_zero_or_eq_zero_of_mul_eq_zero := assume a b, nat.eq_zero_of_mul_eq_zero, bot := 0, bot_le := nat.zero_le, .. nat.nontrivial, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } instance : canonically_linear_ordered_add_monoid ℕ := { .. (infer_instance : canonically_ordered_add_monoid ℕ), .. nat.linear_order } instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : nonempty s] : semilattice_sup_bot s := { bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_linear_order } theorem nat.nsmul_eq_mul (m n : ℕ) : m • n = m * n := rfl theorem nat.eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact nat.eq_of_mul_eq_mul_left Hm H instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ := { mul_left_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_left (nat.pos_of_ne_zero h1) h2, mul_right_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_right (nat.pos_of_ne_zero h1) h2, .. (infer_instance : comm_monoid_with_zero ℕ) } attribute [simp] nat.not_lt_zero nat.succ_ne_zero nat.succ_ne_self nat.zero_ne_one nat.one_ne_zero nat.zero_ne_bit1 nat.bit1_ne_zero nat.bit0_ne_one nat.one_ne_bit0 nat.bit0_ne_bit1 nat.bit1_ne_bit0 /-! Inject some simple facts into the type class system. This `fact` should not be confused with the factorial function `nat.fact`! -/ section facts instance succ_pos'' (n : ℕ) : fact (0 < n.succ) := ⟨n.succ_pos⟩ instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := ⟨lt_trans zero_lt_one h.1⟩ end facts variables {m n k : ℕ} namespace nat /-! ### Recursion and `set.range` -/ section set open set theorem zero_union_range_succ : {0} ∪ range succ = univ := by { ext n, cases n; simp } variables {α : Type*} theorem range_of_succ (f : ℕ → α) : {f 0} ∪ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {α : Type*} (x : α) (f : ℕ → α → α) : (set.range (λ n, nat.rec x f n) : set α) = {x} ∪ set.range (λ n, nat.rec (f 0 x) (f ∘ succ) n) := begin convert (range_of_succ _).symm, ext n, induction n with n ihn, { refl }, { dsimp at ihn ⊢, rw ihn } end theorem range_cases_on {α : Type*} (x : α) (f : ℕ → α) : (set.range (λ n, nat.cases_on n x f) : set α) = {x} ∪ set.range f := (range_of_succ _).symm end set /-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/ theorem units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) instance unique_units : unique (units ℕ) := { default := 1, uniq := nat.units_eq_one } instance unique_add_units : unique (add_units ℕ) := { default := 0, uniq := nat.add_units_eq_zero } /-! ### Equalities and inequalities involving zero and one -/ lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ lemma zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le _) lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h theorem eq_one_of_mul_eq_one_right {m n : ℕ} (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩ theorem eq_one_of_mul_eq_one_left {m n : ℕ} (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (by rwa mul_comm) /-! ### `succ` -/ theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) lemma eq_of_le_of_lt_succ {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n + 1) : m = n := nat.le_antisymm (le_of_succ_le_succ h₂) h₁ theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ.inj, congr_arg _⟩ theorem succ_injective : function.injective nat.succ := λ x y, succ.inj lemma succ_ne_succ {n m : ℕ} : succ n ≠ succ m ↔ n ≠ m := succ_injective.ne_iff @[simp] lemma succ_succ_ne_one (n : ℕ) : n.succ.succ ≠ 1 := succ_ne_succ.mpr n.succ_ne_zero @[simp] lemma one_lt_succ_succ (n : ℕ) : 1 < n.succ.succ := succ_lt_succ $ succ_pos n theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := H.lt_or_eq_dec.imp le_of_lt_succ id lemma succ_lt_succ_iff {m n : ℕ} : succ m < succ n ↔ m < n := ⟨lt_of_succ_lt_succ, succ_lt_succ⟩ lemma div_le_iff_le_mul_add_pred {m n k : ℕ} (n0 : 0 < n) : m / n ≤ k ↔ m ≤ n * k + (n - 1) := begin rw [← lt_succ_iff, div_lt_iff_lt_mul _ _ n0, succ_mul, mul_comm], cases n, {cases n0}, exact lt_succ_iff, end /-! ### `add` -/ -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ lemma add_succ_lt_add {a b c d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := begin rw add_assoc, exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℕ} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℕ} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } /-! ### `pred` -/ @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] /-! ### `sub` -/ protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem add_sub_eq_max (n m : ℕ) : n + (m - n) = max n m := by rw [add_comm, max_comm, sub_add_eq_max] theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_add_sub_cancel {a b c : ℕ} (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c := by rw [←nat.add_sub_assoc hbc, ←nat.sub_add_comm hab, nat.add_sub_cancel] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := (nat.sub_eq_iff_eq_add (le_trans (nat.sub_le _ _) h₁)).2 $ by rw [add_right_comm, add_assoc, nat.sub_add_cancel h₂, nat.sub_add_cancel h₁] protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := lt_of_not_ge (assume : n ≤ m, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) lemma le_or_le_of_add_eq_add_pred {a b c d : ℕ} (h : c + d = a + b - 1) : a ≤ c ∨ b ≤ d := begin cases le_or_lt a c with h' h'; [left, right], { exact h', }, { replace h' := add_lt_add_right h' d, rw h at h', cases b.eq_zero_or_pos with hb hb, { rw hb, exact zero_le d, }, rw [a.add_sub_assoc hb, add_lt_add_iff_left] at h', exact nat.le_of_pred_lt h', }, end /-! ### `mul` -/ lemma succ_mul_pos (m : ℕ) (hn : 0 < n) : 0 < (succ m) * n := mul_pos (succ_pos m) hn theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := decidable.mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := decidable.mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, le_imp_le_of_lt_imp_lt mul_self_lt_mul_self⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := le_iff_le_iff_lt_iff_lt.1 mul_self_le_mul_self_iff theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact decidable.mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact decidable.mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by { rw [add_comm, add_mul_mod_self_left, mul_mod_right, mod_eq_of_lt]; simp }) lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨ λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], λ h, by simp only [h, mul_one]⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ lemma mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, x * a) := λ _ _, eq_of_mul_eq_mul_right ha lemma mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, a * x) := λ _ _, eq_of_mul_eq_mul_left ha lemma mul_ne_mul_left {a b c : ℕ} (ha : 0 < a) : b * a ≠ c * a ↔ b ≠ c := (mul_left_injective ha).ne_iff lemma mul_ne_mul_right {a b c : ℕ} (ha : 0 < a) : a * b ≠ a * c ↔ b ≠ c := (mul_right_injective ha).ne_iff lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_right_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans decidable.le_iff_lt_or_eq theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ @[simp] lemma rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) : (nat.rec h0 h : Π n, C n) 0 = h0 := rfl @[simp] lemma rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) (n : ℕ) : (nat.rec h0 h : Π n, C n) (n + 1) = h n ((nat.rec h0 h : Π n, C n) n) := rfl /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } /-! ### `div` -/ attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (_root_.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := le_div_iff_mul_le x y k0 theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self _ _) h lemma lt_of_div_lt_div {m n k : ℕ} : m / k < n / k → m < n := lt_imp_lt_of_le_imp_le $ λ h, nat.div_le_div_right h protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ protected lemma div_eq_zero {a b : ℕ} (hb : a < b) : a / b = 0 := (nat.div_eq_zero_iff $ (zero_le a).trans_lt hb).mpr hb lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] /-! ### `mod`, `dvd` -/ lemma div_add_mod (m k : ℕ) : k * (m / k) + m % k = m := (nat.add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw [eq_zero_of_zero_dvd h₁, nat.div_zero, nat.div_zero] | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := begin rcases eq_zero_or_pos b with rfl|hb, { simp }, rcases eq_zero_or_pos c with rfl|hc, { simp }, conv_rhs { rw ← mod_add_div a (b * c) }, rw [mul_assoc, nat.add_mul_div_left _ _ hb, add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos hb hc)))] end lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n := by { rw [bit1, nat.dvd_add_right two_dvd_bit0, nat.dvd_one], cc } /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) -- TODO: update `nat.dvd_sub` in core lemma dvd_sub' {k m n : ℕ} (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := begin cases le_total n m with H H, { exact dvd_sub H h₁ h₂ }, { rw nat.sub_eq_zero_of_le H, exact dvd_zero k }, end lemma not_dvd_of_pos_of_lt {a b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬ a ∣ b := begin rintros ⟨c, rfl⟩, rcases eq_zero_or_pos c with (rfl | hc), { exact lt_irrefl 0 h1 }, { exact not_lt.2 (le_mul_of_pos_right hc) h2 }, end protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := by simp | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _), rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), nat.add_sub_add_right], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left, ←nat.mul_sub_left_distrib, nat.mul_mod_right] @[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1) lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, nat.sub_eq_of_eq_add (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma add_mod_eq_ite {a b n : ℕ} : (a + b) % n = if n ≤ a % n + b % n then a % n + b % n - n else a % n + b % n := begin cases n, { simp }, rw nat.add_mod, split_ifs with h, { rw [nat.mod_eq_sub_mod h, nat.mod_eq_of_lt], exact (nat.sub_lt_right_iff_lt_add h).mpr (nat.add_lt_add (a.mod_lt n.zero_lt_succ) (b.mod_lt n.zero_lt_succ)) }, { exact nat.mod_eq_of_lt (lt_of_not_ge h) } end lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc, add_mul_mod_self_right] } end lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end @[simp] lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a | 0 _ := by simp | (a + 1) 0 := λ _ dvd _, by simpa using dvd | (a + 1) (c + 1) := have a_split : a + 1 ≠ 0 := succ_ne_zero a, have c_split : c + 1 ≠ 0 := succ_ne_zero c, λ b dvd dvd2, begin rcases dvd2 with ⟨k, rfl⟩, rcases dvd with ⟨k2, pr⟩, have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr, rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr, nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k, ←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero), nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)], end lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end lemma lt_iff_le_pred : ∀ {m n : ℕ}, 0 < n → (m < n ↔ m ≤ n - 1) | m (n+1) _ := lt_succ_iff lemma div_eq_sub_mod_div {m n : ℕ} : m / n = (m - m % n) / n := begin by_cases n0 : n = 0, { rw [n0, nat.div_zero, nat.div_zero] }, { rw [← mod_add_div m n] { occs := occurrences.pos [2] }, rw [nat.add_sub_cancel_left, mul_div_right _ (nat.pos_of_ne_zero n0)] } end lemma mul_div_le (m n : ℕ) : n * (m / n) ≤ m := begin cases nat.eq_zero_or_pos n with n0 h, { rw [n0, zero_mul], exact m.zero_le }, { rw [mul_comm, ← nat.le_div_iff_mul_le' h] }, end lemma lt_mul_div_succ (m : ℕ) {n : ℕ} (n0 : 0 < n) : m < n * ((m / n) + 1) := begin rw [mul_comm, ← nat.div_lt_iff_lt_mul' n0], exact lt_succ_self _ end @[simp] lemma mod_div_self (m n : ℕ) : m % n / n = 0 := begin cases n, { exact (m % 0).div_zero }, { exact nat.div_eq_zero (m.mod_lt n.succ_pos) } end /-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m := begin split, { rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k, rw [lt_succ_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def, ← pos_iff_ne_zero] at h, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ h, _⟩, rw [add_comm _ 1, left_distrib, mul_one], exact add_lt_add_right (mod_lt _ hn) _ } end /-- Two natural numbers are equal if and only if the have the same multiples. -/ lemma dvd_right_iff_eq {m n : ℕ} : (∀ a : ℕ, m ∣ a ↔ n ∣ a) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mpr (dvd_refl _)) ((h _).mp (dvd_refl _)), λ h n, by rw h⟩ /-- Two natural numbers are equal if and only if the have the same divisors. -/ lemma dvd_left_iff_eq {m n : ℕ} : (∀ a : ℕ, a ∣ m ↔ a ∣ n) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mp (dvd_refl _)) ((h _).mpr (dvd_refl _)), λ h n, by rw h⟩ /-- `dvd` is injective in the left argument -/ lemma dvd_left_injective : function.injective ((∣) : ℕ → ℕ → Prop) := λ m n h, dvd_right_iff_eq.mp $ λ a, iff_of_eq (congr_fun h a) /-! ### `find` -/ section find variables {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] lemma find_eq_iff (h : ∃ n : ℕ, p n) : nat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n := begin split, { rintro rfl, exact ⟨nat.find_spec h, λ _, nat.find_min h⟩ }, { rintro ⟨hm, hlt⟩, exact le_antisymm (nat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ nat.find_spec h) } end @[simp] lemma find_lt_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h < n ↔ ∃ m < n, p m := ⟨λ h2, ⟨nat.find h, h2, nat.find_spec h⟩, λ ⟨m, hmn, hm⟩, (nat.find_min' h hm).trans_lt hmn⟩ @[simp] lemma find_le_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h ≤ n ↔ ∃ m ≤ n, p m := by simp only [exists_prop, ← lt_succ_iff, find_lt_iff] @[simp] lemma le_find_iff (h : ∃ (n : ℕ), p n) (n : ℕ) : n ≤ nat.find h ↔ ∀ m < n, ¬ p m := by simp_rw [← not_lt, find_lt_iff, not_exists] @[simp] lemma lt_find_iff (h : ∃ n : ℕ, p n) (n : ℕ) : n < nat.find h ↔ ∀ m ≤ n, ¬ p m := by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff] @[simp] lemma find_eq_zero (h : ∃ n : ℕ, p n) : nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] @[simp] lemma find_pos (h : ∃ n : ℕ, p n) : 0 < nat.find h ↔ ¬ p 0 := by rw [pos_iff_ne_zero, ne, nat.find_eq_zero] theorem find_le (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ (h _ (nat.find_spec hq)) lemma find_comp_succ (h₁ : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h0 : ¬ p 0) : nat.find h₁ = nat.find h₂ + 1 := begin refine (find_eq_iff _).2 ⟨nat.find_spec h₂, λ n hn, _⟩, cases n with n, exacts [h0, @nat.find_min (λ n, p (n + 1)) _ h₂ _ (succ_lt_succ_iff.1 hn)] end end find /-! ### `find_greatest` -/ section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_eq_iff {b m} : nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ b → ¬P n) := begin induction b with b ihb generalizing m, { rw [eq_comm, iff.comm], simp only [nonpos_iff_eq_zero, ne.def, and_iff_left_iff_imp, find_greatest_zero], rintro rfl, exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ }, { by_cases hb : P (b + 1), { rw [find_greatest_eq hb], split, { rintro rfl, exact ⟨le_refl _, λ _, hb, λ n hlt hle, (hlt.not_le hle).elim⟩ }, { rintros ⟨hle, h0, hm⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt, exacts [rfl, (hm hlt (le_refl _) hb).elim] } }, { rw [find_greatest_of_not hb, ihb], split, { rintros ⟨hle, hP, hm⟩, refine ⟨hle.trans b.le_succ, hP, λ n hlt hle, _⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt', exacts [hb, hm hlt $ lt_succ_iff.1 hlt'] }, { rintros ⟨hle, hP, hm⟩, refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans b.le_succ)⟩, rintro rfl, exact hb (hP b.succ_ne_zero) } } } end lemma find_greatest_eq_zero_iff {b} : nat.find_greatest P b = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ b → ¬P n := by simp [find_greatest_eq_iff] lemma find_greatest_spec {b} (h : ∃m, m ≤ b ∧ P m) : P (nat.find_greatest P b) := begin rcases h with ⟨m, hmb, hm⟩, by_cases h : nat.find_greatest P b = 0, { cases m, { rwa h }, exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim }, { exact (find_greatest_eq_iff.1 rfl).2.1 h } end lemma find_greatest_le {b} : nat.find_greatest P b ≤ b := (find_greatest_eq_iff.1 rfl).1 lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma find_greatest_is_greatest {b k} (hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬ P k := (find_greatest_eq_iff.1 rfl).2.2 hk hkb lemma find_greatest_of_ne_zero {b m} (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m := (find_greatest_eq_iff.1 h).2.1 h0 end find_greatest /-! ### `bodd_div2` and `bodd` -/ @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /-! ### `bit0` and `bit1` -/ -- There is no need to prove `bit0_eq_zero : bit0 n = 0 ↔ n = 0` -- as this is true for any `[semiring R] [no_zero_divisors R] [char_zero R]` -- However the lemmas `bit0_eq_bit0`, `bit1_eq_bit1`, `bit1_eq_one`, `one_eq_bit1` -- need `[ring R] [no_zero_divisors R] [char_zero R]` in general, -- so we prove `ℕ` specialized versions here. @[simp] lemma bit0_eq_bit0 {m n : ℕ} : bit0 m = bit0 n ↔ m = n := ⟨nat.bit0_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_bit1 {m n : ℕ} : bit1 m = bit1 n ↔ m = n := ⟨nat.bit1_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_one {n : ℕ} : bit1 n = 1 ↔ n = 0 := ⟨@nat.bit1_inj n 0, λ h, by subst h⟩ @[simp] lemma one_eq_bit1 {n : ℕ} : 1 = bit1 n ↔ n = 0 := ⟨λ h, (@nat.bit1_inj 0 n h).symm, λ h, by subst h⟩ protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 @[simp] lemma bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp } @[simp] lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp } lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /-! ### decidability of predicates -/ instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (le_of_lt_succ h').lt_or_eq_dec.elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] : decidable_pred (λ n, ∃ (m : ℕ), m < n ∧ P m) | 0 := is_false (by simp) | (n + 1) := decidable_of_decidable_of_iff (@or.decidable _ _ (decidable_exists_lt n) (h n)) (by simp only [lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, exists_eq_left]) end nat
3822ea0539ba782cc40d726a564a181732f3e8b8
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/heap_mem.lean
f6a0a30411cab21b1eabdfacf2de242134422382
[ "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
3,826
lean
/- We use the following auxiliary type instead of (Σ α : Type, α) because the code generator produces better code for `pointed`. For `pointed`, the code generator erases the field `α`. -/ structure pointed := (α : Type) (a : α) /- The following two commands demonstrate the difference. To remove the overhead in the `sigma` case, the code generator would have to support code specialization. -/ #eval pointed.mk nat 10 #eval (⟨nat, 10⟩ : Σ α : Type, α) structure heap := (size : nat) (mem : array size pointed) structure ref (α : Type) := (idx : nat) def in_heap {α : Type} (r : ref α) (h : heap) : Prop := ∃ hlt : r.idx < h.size, (h.mem.read ⟨r.idx, hlt⟩).1 = α lemma lt_of_in_heap {α : Type} {r : ref α} {h : heap} (hin : in_heap r h) : r.idx < h.size := by cases hin; assumption lemma cast_of_in_heap {α : Type} {r : ref α} {h : heap} (hin : in_heap r h) : (h.mem.read ⟨r.idx, lt_of_in_heap hin⟩).1 = α := by cases hin; exact hin_h def mk_ref : heap → Π {α : Type}, α → ref α × heap | ⟨n, mem⟩ α v := ({idx := n}, { size := n+1, mem := mem.push_back ⟨α, v⟩ }) def read : Π (h : heap) {α : Type} (r : ref α) (prf : in_heap r h), α | ⟨n, mem⟩ α r hin := eq.rec_on (cast_of_in_heap hin) (mem.read ⟨r.idx, lt_of_in_heap hin⟩).2 def write : Π (h : heap) {α : Type} (r : ref α) (prf : in_heap r h) (a : α), heap | ⟨n, mem⟩ α r hin a := { size := n, mem := mem.write ⟨r.idx, lt_of_in_heap hin⟩ ⟨α, a⟩ } lemma in_heap_mk_ref (h : heap) {α : Type} (a : α) : in_heap (mk_ref h a).1 (mk_ref h a).2 := begin cases h, simp [mk_ref, in_heap], dsimp, have : h_size < h_size + 1, { apply nat.lt_succ_self }, existsi this, simp [array.push_back, array.read, d_array.read, *] end lemma in_heap_mk_ref_of_in_heap {α β : Type} {h : heap} {r : ref α} (b : β) : in_heap r h → in_heap r (mk_ref h b).2 := begin intro hin, have := lt_of_in_heap hin, have hlt := nat.lt_succ_of_lt this, cases h, simp [in_heap, mk_ref, *] at *, dsimp, have : r.idx ≠ h_size, { intro heq, subst heq, exact absurd this (irrefl _) }, simp [array.push_back, array.read, d_array.read, *], existsi hlt, cases hin, assumption end @[simp] lemma fin.mk_eq {n : nat} {i j : nat} (h₁ : i < n) (h₂ : j < n) (h₃ : i ≠ j) : (⟨i, h₁⟩ : fin n) ≠ ⟨j, h₂⟩ := fin.ne_of_vne h₃ lemma in_heap_write_of_in_heap {α β : Type} {h : heap} {r₁ : ref β} {r₂ : ref α} (a : α) : ∀ (hin₁ : in_heap r₁ h) (hin₂ : in_heap r₂ h), in_heap r₁ (write h r₂ hin₂ a) := begin intros, have := lt_of_in_heap hin₁, have := lt_of_in_heap hin₂, have := cast_of_in_heap hin₁, have := cast_of_in_heap hin₂, cases h, simp [in_heap, write, *] at *, dsimp, existsi this, by_cases r₂.idx = r₁.idx, { simp [*] at * }, { simp [*] } end inductive is_extension : heap → heap → Prop | refl : ∀ h, is_extension h h | by_mk_ref (h' h : heap) {α : Type} (a : α) (he : is_extension h' h) : is_extension (mk_ref h' a).2 h | by_write (h' h : heap) {α : Type} (r : ref α) (hin : in_heap r h') (a : α) (he : is_extension h' h) : is_extension (write h' r hin a) h lemma is_extension.trans {h₁ h₂ h₃ : heap} : is_extension h₁ h₂ → is_extension h₂ h₃ → is_extension h₁ h₃ := begin intro he₁, induction he₁, { intros, assumption }, all_goals { intro he₂, constructor, apply he₁_ih, assumption } end lemma in_heap_of_is_extension_of_in_heap {α : Type} {r : ref α} {h h' : heap} : is_extension h' h → in_heap r h → in_heap r h' := begin intro he, induction he generalizing α r, { intros, assumption }, { intro hin, apply in_heap_mk_ref_of_in_heap, apply he_ih, assumption }, { intro hin, apply in_heap_write_of_in_heap, apply he_ih, assumption } end
a66dc442fdae2ed802507813f4265ea2f48a7b2a
6cc23d886ccf271bfd0c9ca5d29cafb9c0be7bf5
/src/LeanPlay/LeanVersion.lean
8bfbed8e11b4eca53b5c44ca2201e4aba2e5809f
[]
no_license
Anderssorby/LeanPlay
d39b15dbc3441c2be5a4ea5adf8fe70c4648737b
8fd63d98d02490060323f4c5117b9a7e8da50813
refs/heads/main
1,692,004,930,931
1,633,974,729,000
1,633,974,729,000
368,654,414
0
0
null
null
null
null
UTF-8
Lean
false
false
1,063
lean
import Blake3 namespace LeanPlay def leanVersionStringCore := s!"{Lean.version.major}.{Lean.version.minor}.{Lean.version.patch}" def origin := "leanprover/lean4" def leanVersionString := if Lean.version.isRelease then s!"{origin}:{leanVersionStringCore}" else if Lean.version.specialDesc ≠ "" then s!"{origin}:{Lean.version.specialDesc}" else s!"{origin}:master" def uiLeanVersionString := if Lean.version.isRelease then leanVersionStringCore else if Lean.version.specialDesc ≠ "" then s!"{leanVersionStringCore}-{Lean.version.specialDesc}" else s!"master ({leanVersionStringCore})" def verifyLeanVersion : IO PUnit := do let out ← IO.Process.output { cmd := "lean", args := #["--version"] } if out.exitCode == 0 then unless out.stdout.drop 14 |>.startsWith uiLeanVersionString do throw <| IO.userError <| s!"expected {uiLeanVersionString}, but got {out.stdout.trim}" else throw <| IO.userError <| "missing lean!" def version := s!"Lean: {uiLeanVersionString} Blake3: {Blake3.version}"
9597b724a537fbcbccc7233db92a6d9f55e8c370
626e312b5c1cb2d88fca108f5933076012633192
/src/ring_theory/polynomial/dickson.lean
ece916bba803a4b678cddcdd864aa3a9a71e772f
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,501
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import ring_theory.polynomial.chebyshev import ring_theory.localization import data.zmod.basic import algebra.char_p.invertible /-! # Dickson polynomials The (generalised) Dickson polynomials are a family of polynomials indexed by `ℕ × ℕ`, with coefficients in a commutative ring `R` depending on an element `a∈R`. More precisely, the they satisfy the recursion `dickson k a (n + 2) = X * (dickson k a n + 1) - a * (dickson k a n)` with starting values `dickson k a 0 = 3 - k` and `dickson k a 1 = X`. In the literature, `dickson k a n` is called the `n`-th Dickson polynomial of the `k`-th kind associated to the parameter `a : R`. They are closely related to the Chebyshev polynomials in the case that `a=1`. When `a=0` they are just the family of monomials `X ^ n`. ## Main definition * `polynomial.dickson`: the generalised Dickson polynomials. ## Main statements * `polynomial.dickson_one_one_mul`, the `(m * n)`-th Dickson polynomial of the first kind for parameter `1 : R` is the composition of the `m`-th and `n`-th Dickson polynomials of the first kind for `1 : R`. * `polynomial.dickson_one_one_char_p`, for a prime number `p`, the `p`-th Dickson polynomial of the first kind associated to parameter `1 : R` is congruent to `X ^ p` modulo `p`. ## References * [R. Lidl, G. L. Mullen and G. Turnwald, _Dickson polynomials_][MR1237403] ## TODO * Redefine `dickson` in terms of `linear_recurrence`. * Show that `dickson 2 1` is equal to the characteristic polynomial of the adjacency matrix of a type A Dynkin diagram. * Prove that the adjacency matrices of simply laced Dynkin diagrams are precisely the adjacency matrices of simple connected graphs which annihilate `dickson 2 1`. -/ noncomputable theory namespace polynomial variables {R S : Type*} [comm_ring R] [comm_ring S] (k : ℕ) (a : R) /-- `dickson` is the `n`the (generalised) Dickson polynomial of the `k`-th kind associated to the element `a ∈ R`. -/ noncomputable def dickson : ℕ → polynomial R | 0 := 3 - k | 1 := X | (n + 2) := X * dickson (n + 1) - (C a) * dickson n @[simp] lemma dickson_zero : dickson k a 0 = 3 - k := rfl @[simp] lemma dickson_one : dickson k a 1 = X := rfl lemma dickson_two : dickson k a 2 = X ^ 2 - C a * (3 - k) := by simp only [dickson, sq] @[simp] lemma dickson_add_two (n : ℕ) : dickson k a (n + 2) = X * dickson k a (n + 1) - C a * dickson k a n := by rw dickson lemma dickson_of_two_le {n : ℕ} (h : 2 ≤ n) : dickson k a n = X * dickson k a (n - 1) - C a * dickson k a (n - 2) := begin obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h, rw add_comm, exact dickson_add_two k a n end variables {R S k a} lemma map_dickson (f : R →+* S) : ∀ (n : ℕ), map f (dickson k a n) = dickson k (f a) n | 0 := by simp only [dickson_zero, map_sub, map_nat_cast, bit1, bit0, map_add, map_one] | 1 := by simp only [dickson_one, map_X] | (n + 2) := begin simp only [dickson_add_two, map_sub, map_mul, map_X, map_C], rw [map_dickson, map_dickson] end variable {R} @[simp] lemma dickson_two_zero : ∀ (n : ℕ), dickson 2 (0 : R) n = X ^ n | 0 := by { simp only [dickson_zero, pow_zero], norm_num } | 1 := by simp only [dickson_one, pow_one] | (n + 2) := begin simp only [dickson_add_two, C_0, zero_mul, sub_zero], rw [dickson_two_zero, pow_add X (n + 1) 1, mul_comm, pow_one] end section dickson /-! ### A Lambda structure on `polynomial ℤ` Mathlib doesn't currently know what a Lambda ring is. But once it does, we can endow `polynomial ℤ` with a Lambda structure in terms of the `dickson 1 1` polynomials defined below. There is exactly one other Lambda structure on `polynomial ℤ` in terms of binomial polynomials. -/ variables {R} lemma dickson_one_one_eval_add_inv (x y : R) (h : x * y = 1) : ∀ n, (dickson 1 (1 : R) n).eval (x + y) = x ^ n + y ^ n | 0 := by { simp only [bit0, eval_one, eval_add, pow_zero, dickson_zero], norm_num } | 1 := by simp only [eval_X, dickson_one, pow_one] | (n + 2) := begin simp only [eval_sub, eval_mul, dickson_one_one_eval_add_inv, eval_X, dickson_add_two, C_1, eval_one], conv_lhs { simp only [pow_succ, add_mul, mul_add, h, ← mul_assoc, mul_comm y x, one_mul] }, ring_exp end variables (R) lemma dickson_one_one_eq_chebyshev_T [invertible (2 : R)] : ∀ n, dickson 1 (1 : R) n = 2 * (chebyshev.T R n).comp (C (⅟2) * X) | 0 := by { simp only [chebyshev.T_zero, mul_one, one_comp, dickson_zero], norm_num } | 1 := by rw [dickson_one, chebyshev.T_one, X_comp, ← mul_assoc, ← C_1, ← C_bit0, ← C_mul, mul_inv_of_self, C_1, one_mul] | (n + 2) := begin simp only [dickson_add_two, chebyshev.T_add_two, dickson_one_one_eq_chebyshev_T (n + 1), dickson_one_one_eq_chebyshev_T n, sub_comp, mul_comp, add_comp, X_comp, bit0_comp, one_comp], simp only [← C_1, ← C_bit0, ← mul_assoc, ← C_mul, mul_inv_of_self], rw [C_1, one_mul], ring end lemma chebyshev_T_eq_dickson_one_one [invertible (2 : R)] (n : ℕ) : chebyshev.T R n = C (⅟2) * (dickson 1 1 n).comp (2 * X) := begin rw dickson_one_one_eq_chebyshev_T, simp only [comp_assoc, mul_comp, C_comp, X_comp, ← mul_assoc, ← C_1, ← C_bit0, ← C_mul], rw [inv_of_mul_self, C_1, one_mul, one_mul, comp_X] end /-- The `(m * n)`-th Dickson polynomial of the first kind is the composition of the `m`-th and `n`-th. -/ lemma dickson_one_one_mul (m n : ℕ) : dickson 1 (1 : R) (m * n) = (dickson 1 1 m).comp (dickson 1 1 n) := begin have h : (1 : R) = int.cast_ring_hom R (1), simp only [ring_hom.eq_int_cast, int.cast_one], rw h, simp only [← map_dickson (int.cast_ring_hom R), ← map_comp], congr' 1, apply map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_dickson, map_comp, ring_hom.eq_int_cast, int.cast_one, dickson_one_one_eq_chebyshev_T, chebyshev.T_mul, two_mul, ← add_comp], simp only [← two_mul, ← comp_assoc], apply eval₂_congr rfl rfl, rw [comp_assoc], apply eval₂_congr rfl _ rfl, rw [mul_comp, C_comp, X_comp, ← mul_assoc, ← C_1, ← C_bit0, ← C_mul, inv_of_mul_self, C_1, one_mul] end lemma dickson_one_one_comp_comm (m n : ℕ) : (dickson 1 (1 : R) m).comp (dickson 1 1 n) = (dickson 1 1 n).comp (dickson 1 1 m) := by rw [← dickson_one_one_mul, mul_comm, dickson_one_one_mul] lemma dickson_one_one_zmod_p (p : ℕ) [fact p.prime] : dickson 1 (1 : zmod p) p = X ^ p := begin -- Recall that `dickson_eval_add_inv` characterises `dickson 1 1 p` -- as a polynomial that maps `x + x⁻¹` to `x ^ p + (x⁻¹) ^ p`. -- Since `X ^ p` also satisfies this property in characteristic `p`, -- we can use a variant on `polynomial.funext` to conclude that these polynomials are equal. -- For this argument, we need an arbitrary infinite field of characteristic `p`. obtain ⟨K, _, _, H⟩ : ∃ (K : Type) [field K], by exactI ∃ [char_p K p], infinite K, { let K := fraction_ring (polynomial (zmod p)), let f : zmod p →+* K := (algebra_map _ (fraction_ring _)).comp C, haveI : char_p K p, { rw ← f.char_p_iff_char_p, apply_instance }, haveI : infinite K := infinite.of_injective (algebra_map (polynomial (zmod p)) (fraction_ring (polynomial (zmod p)))) (is_fraction_ring.injective _ _), refine ⟨K, _, _, _⟩; apply_instance }, resetI, apply map_injective (zmod.cast_hom (dvd_refl p) K) (ring_hom.injective _), rw [map_dickson, map_pow, map_X], apply eq_of_infinite_eval_eq, -- The two polynomials agree on all `x` of the form `x = y + y⁻¹`. apply @set.infinite_mono _ {x : K | ∃ y, x = y + y⁻¹ ∧ y ≠ 0}, { rintro _ ⟨x, rfl, hx⟩, simp only [eval_X, eval_pow, set.mem_set_of_eq, @add_pow_char K _ p, dickson_one_one_eval_add_inv _ _ (mul_inv_cancel hx), inv_pow', zmod.cast_hom_apply, zmod.cast_one'] }, -- Now we need to show that the set of such `x` is infinite. -- If the set is finite, then we will show that `K` is also finite. { intro h, rw ← set.infinite_univ_iff at H, apply H, -- To each `x` of the form `x = y + y⁻¹` -- we `bind` the set of `y` that solve the equation `x = y + y⁻¹`. -- For every `x`, that set is finite (since it is governed by a quadratic equation). -- For the moment, we claim that all these sets together cover `K`. suffices : (set.univ : set K) = {x : K | ∃ (y : K), x = y + y⁻¹ ∧ y ≠ 0} >>= (λ x, {y | x = y + y⁻¹ ∨ y = 0}), { rw this, clear this, refine h.bUnion (λ x hx, _), -- The following quadratic polynomial has as solutions the `y` for which `x = y + y⁻¹`. let φ : polynomial K := X ^ 2 - C x * X + 1, have hφ : φ ≠ 0, { intro H, have : φ.eval 0 = 0, by rw [H, eval_zero], simpa [eval_X, eval_one, eval_pow, eval_sub, sub_zero, eval_add, eval_mul, mul_zero, sq, zero_add, one_ne_zero] }, classical, convert (φ.roots ∪ {0}).to_finset.finite_to_set using 1, ext1 y, simp only [multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe, multiset.mem_union, mem_roots hφ, is_root, eval_add, eval_sub, eval_pow, eval_mul, eval_X, eval_C, eval_one, multiset.mem_singleton], by_cases hy : y = 0, { simp only [hy, eq_self_iff_true, or_true] }, apply or_congr _ iff.rfl, rw [← mul_left_inj' hy, eq_comm, ← sub_eq_zero, add_mul, inv_mul_cancel hy], apply eq_iff_eq_cancel_right.mpr, ring }, -- Finally, we prove the claim that our finite union of finite sets covers all of `K`. { apply (set.eq_univ_of_forall _).symm, intro x, simp only [exists_prop, set.mem_Union, set.bind_def, ne.def, set.mem_set_of_eq], by_cases hx : x = 0, { simp only [hx, and_true, eq_self_iff_true, inv_zero, or_true], exact ⟨_, 1, rfl, one_ne_zero⟩ }, { simp only [hx, or_false, exists_eq_right], exact ⟨_, rfl, hx⟩ } } } end lemma dickson_one_one_char_p (p : ℕ) [fact p.prime] [char_p R p] : dickson 1 (1 : R) p = X ^ p := begin have h : (1 : R) = zmod.cast_hom (dvd_refl p) R (1), simp only [zmod.cast_hom_apply, zmod.cast_one'], rw [h, ← map_dickson (zmod.cast_hom (dvd_refl p) R), dickson_one_one_zmod_p, map_pow, map_X] end end dickson end polynomial
8451cefeeaf57ce699e2a6775d9d2ab178ec3dd7
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/convex/extreme.lean
4dd905a8ca99c0c2efe9750bd3b1b3a480d98c75
[ "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
9,522
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.convex.hull /-! # Extreme sets This file defines extreme sets and extreme points for sets in a module. An extreme set of `A` is a subset of `A` that is as far as it can get in any outward direction: If point `x` is in it and point `y ∈ A`, then the line passing through `x` and `y` leaves `A` at `x`. This is an analytic notion of "being on the side of". It is weaker than being exposed (see `is_exposed.is_extreme`). ## Main declarations * `is_extreme 𝕜 A B`: States that `B` is an extreme set of `A` (in the literature, `A` is often implicit). * `set.extreme_points 𝕜 A`: Set of extreme points of `A` (corresponding to extreme singletons). * `convex.mem_extreme_points_iff_convex_diff`: A useful equivalent condition to being an extreme point: `x` is an extreme point iff `A \ {x}` is convex. ## Implementation notes The exact definition of extremeness has been carefully chosen so as to make as many lemmas unconditional (in particular, the Krein-Milman theorem doesn't need the set to be convex!). In practice, `A` is often assumed to be a convex set. ## References See chapter 8 of [Barry Simon, *Convexity*][simon2011] ## TODO Define intrinsic frontier and prove lemmas related to extreme sets and points. More not-yet-PRed stuff is available on the branch `sperner_again`. -/ open_locale classical affine open set variables (𝕜 : Type*) {E : Type*} section has_smul variables [ordered_semiring 𝕜] [add_comm_monoid E] [has_smul 𝕜 E] /-- A set `B` is an extreme subset of `A` if `B ⊆ A` and all points of `B` only belong to open segments whose ends are in `B`. -/ def is_extreme (A B : set E) : Prop := B ⊆ A ∧ ∀ ⦃x₁⦄, x₁ ∈ A → ∀ ⦃x₂⦄, x₂ ∈ A → ∀ ⦃x⦄, x ∈ B → x ∈ open_segment 𝕜 x₁ x₂ → x₁ ∈ B ∧ x₂ ∈ B /-- A point `x` is an extreme point of a set `A` if `x` belongs to no open segment with ends in `A`, except for the obvious `open_segment x x`. -/ def set.extreme_points (A : set E) : set E := {x ∈ A | ∀ ⦃x₁⦄, x₁ ∈ A → ∀ ⦃x₂⦄, x₂ ∈ A → x ∈ open_segment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x} @[refl] protected lemma is_extreme.refl (A : set E) : is_extreme 𝕜 A A := ⟨subset.rfl, λ x₁ hx₁A x₂ hx₂A x hxA hx, ⟨hx₁A, hx₂A⟩⟩ variables {𝕜} {A B C : set E} {x : E} protected lemma is_extreme.rfl : is_extreme 𝕜 A A := is_extreme.refl 𝕜 A @[trans] protected lemma is_extreme.trans (hAB : is_extreme 𝕜 A B) (hBC : is_extreme 𝕜 B C) : is_extreme 𝕜 A C := begin refine ⟨subset.trans hBC.1 hAB.1, λ x₁ hx₁A x₂ hx₂A x hxC hx, _⟩, obtain ⟨hx₁B, hx₂B⟩ := hAB.2 hx₁A hx₂A (hBC.1 hxC) hx, exact hBC.2 hx₁B hx₂B hxC hx, end protected lemma is_extreme.antisymm : anti_symmetric (is_extreme 𝕜 : set E → set E → Prop) := λ A B hAB hBA, subset.antisymm hBA.1 hAB.1 instance : is_partial_order (set E) (is_extreme 𝕜) := { refl := is_extreme.refl 𝕜, trans := λ A B C, is_extreme.trans, antisymm := is_extreme.antisymm } lemma is_extreme.inter (hAB : is_extreme 𝕜 A B) (hAC : is_extreme 𝕜 A C) : is_extreme 𝕜 A (B ∩ C) := begin use subset.trans (inter_subset_left _ _) hAB.1, rintro x₁ hx₁A x₂ hx₂A x ⟨hxB, hxC⟩ hx, obtain ⟨hx₁B, hx₂B⟩ := hAB.2 hx₁A hx₂A hxB hx, obtain ⟨hx₁C, hx₂C⟩ := hAC.2 hx₁A hx₂A hxC hx, exact ⟨⟨hx₁B, hx₁C⟩, hx₂B, hx₂C⟩, end protected lemma is_extreme.mono (hAC : is_extreme 𝕜 A C) (hBA : B ⊆ A) (hCB : C ⊆ B) : is_extreme 𝕜 B C := ⟨hCB, λ x₁ hx₁B x₂ hx₂B x hxC hx, hAC.2 (hBA hx₁B) (hBA hx₂B) hxC hx⟩ lemma is_extreme_Inter {ι : Type*} [nonempty ι] {F : ι → set E} (hAF : ∀ i : ι, is_extreme 𝕜 A (F i)) : is_extreme 𝕜 A (⋂ i : ι, F i) := begin obtain i := classical.arbitrary ι, refine ⟨Inter_subset_of_subset i (hAF i).1, λ x₁ hx₁A x₂ hx₂A x hxF hx, _⟩, simp_rw mem_Inter at ⊢ hxF, have h := λ i, (hAF i).2 hx₁A hx₂A (hxF i) hx, exact ⟨λ i, (h i).1, λ i, (h i).2⟩, end lemma is_extreme_bInter {F : set (set E)} (hF : F.nonempty) (hAF : ∀ B ∈ F, is_extreme 𝕜 A B) : is_extreme 𝕜 A (⋂ B ∈ F, B) := begin obtain ⟨B, hB⟩ := hF, refine ⟨(bInter_subset_of_mem hB).trans (hAF B hB).1, λ x₁ hx₁A x₂ hx₂A x hxF hx, _⟩, simp_rw mem_Inter₂ at ⊢ hxF, have h := λ B hB, (hAF B hB).2 hx₁A hx₂A (hxF B hB) hx, exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩, end lemma is_extreme_sInter {F : set (set E)} (hF : F.nonempty) (hAF : ∀ B ∈ F, is_extreme 𝕜 A B) : is_extreme 𝕜 A (⋂₀ F) := begin obtain ⟨B, hB⟩ := hF, refine ⟨(sInter_subset_of_mem hB).trans (hAF B hB).1, λ x₁ hx₁A x₂ hx₂A x hxF hx, _⟩, simp_rw mem_sInter at ⊢ hxF, have h := λ B hB, (hAF B hB).2 hx₁A hx₂A (hxF B hB) hx, exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩, end lemma extreme_points_def : x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ open_segment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x := iff.rfl /-- x is an extreme point to A iff {x} is an extreme set of A. -/ lemma mem_extreme_points_iff_extreme_singleton : x ∈ A.extreme_points 𝕜 ↔ is_extreme 𝕜 A {x} := begin refine ⟨_, λ hx, ⟨singleton_subset_iff.1 hx.1, λ x₁ hx₁ x₂ hx₂, hx.2 hx₁ hx₂ rfl⟩⟩, rintro ⟨hxA, hAx⟩, use singleton_subset_iff.2 hxA, rintro x₁ hx₁A x₂ hx₂A y (rfl : y = x), exact hAx hx₁A hx₂A, end lemma extreme_points_subset : A.extreme_points 𝕜 ⊆ A := λ x hx, hx.1 @[simp] lemma extreme_points_empty : (∅ : set E).extreme_points 𝕜 = ∅ := subset_empty_iff.1 extreme_points_subset @[simp] lemma extreme_points_singleton : ({x} : set E).extreme_points 𝕜 = {x} := extreme_points_subset.antisymm $ singleton_subset_iff.2 ⟨mem_singleton x, λ x₁ hx₁ x₂ hx₂ _, ⟨hx₁, hx₂⟩⟩ lemma inter_extreme_points_subset_extreme_points_of_subset (hBA : B ⊆ A) : B ∩ A.extreme_points 𝕜 ⊆ B.extreme_points 𝕜 := λ x ⟨hxB, hxA⟩, ⟨hxB, λ x₁ hx₁ x₂ hx₂ hx, hxA.2 (hBA hx₁) (hBA hx₂) hx⟩ lemma is_extreme.extreme_points_subset_extreme_points (hAB : is_extreme 𝕜 A B) : B.extreme_points 𝕜 ⊆ A.extreme_points 𝕜 := λ x hx, mem_extreme_points_iff_extreme_singleton.2 (hAB.trans (mem_extreme_points_iff_extreme_singleton.1 hx)) lemma is_extreme.extreme_points_eq (hAB : is_extreme 𝕜 A B) : B.extreme_points 𝕜 = B ∩ A.extreme_points 𝕜 := subset.antisymm (λ x hx, ⟨hx.1, hAB.extreme_points_subset_extreme_points hx⟩) (inter_extreme_points_subset_extreme_points_of_subset hAB.1) end has_smul section ordered_semiring variables {𝕜} [ordered_semiring 𝕜] [add_comm_group E] [module 𝕜 E] {A B : set E} {x : E} lemma is_extreme.convex_diff (hA : convex 𝕜 A) (hAB : is_extreme 𝕜 A B) : convex 𝕜 (A \ B) := convex_iff_open_segment_subset.2 (λ x₁ x₂ ⟨hx₁A, hx₁B⟩ ⟨hx₂A, hx₂B⟩ x hx, ⟨hA.open_segment_subset hx₁A hx₂A hx, λ hxB, hx₁B (hAB.2 hx₁A hx₂A hxB hx).1⟩) end ordered_semiring section linear_ordered_ring variables {𝕜} [linear_ordered_ring 𝕜] [add_comm_group E] [module 𝕜 E] variables [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 E] {A B : set E} {x : E} /-- A useful restatement using `segment`: `x` is an extreme point iff the only (closed) segments that contain it are those with `x` as one of their endpoints. -/ lemma mem_extreme_points_iff_forall_segment : x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x := begin refine and_congr_right (λ hxA, forall₄_congr $ λ x₁ h₁ x₂ h₂, _), split, { rw ← insert_endpoints_open_segment, rintro H (rfl|rfl|hx), exacts [or.inl rfl, or.inr rfl, or.inl $ (H hx).1] }, { intros H hx, rcases H (open_segment_subset_segment _ _ _ hx) with rfl | rfl, exacts [⟨rfl, (left_mem_open_segment_iff.1 hx).symm⟩, ⟨right_mem_open_segment_iff.1 hx, rfl⟩] } end lemma convex.mem_extreme_points_iff_convex_diff (hA : convex 𝕜 A) : x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ convex 𝕜 (A \ {x}) := begin use λ hx, ⟨hx.1, (mem_extreme_points_iff_extreme_singleton.1 hx).convex_diff hA⟩, rintro ⟨hxA, hAx⟩, refine mem_extreme_points_iff_forall_segment.2 ⟨hxA, λ x₁ hx₁ x₂ hx₂ hx, _⟩, rw convex_iff_segment_subset at hAx, by_contra' h, exact (hAx ⟨hx₁, λ hx₁, h.1 (mem_singleton_iff.2 hx₁)⟩ ⟨hx₂, λ hx₂, h.2 (mem_singleton_iff.2 hx₂)⟩ hx).2 rfl, end lemma convex.mem_extreme_points_iff_mem_diff_convex_hull_diff (hA : convex 𝕜 A) : x ∈ A.extreme_points 𝕜 ↔ x ∈ A \ convex_hull 𝕜 (A \ {x}) := by rw [hA.mem_extreme_points_iff_convex_diff, hA.convex_remove_iff_not_mem_convex_hull_remove, mem_diff] lemma extreme_points_convex_hull_subset : (convex_hull 𝕜 A).extreme_points 𝕜 ⊆ A := begin rintro x hx, rw (convex_convex_hull 𝕜 _).mem_extreme_points_iff_convex_diff at hx, by_contra, exact (convex_hull_min (subset_diff.2 ⟨subset_convex_hull 𝕜 _, disjoint_singleton_right.2 h⟩) hx.2 hx.1).2 rfl, apply_instance end end linear_ordered_ring
57c5e764c2ab3c8813c5aafe03656344142f0e37
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/quotient.lean
0f31cb354613ccf87d1a336f6efeabc54285c1b3
[ "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
2,060
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import data.set_like.basic /-! # Algebraic quotients This file defines notation for algebraic quotients, e.g. quotient groups `G ⧸ H`, quotient modules `M ⧸ N` and ideal quotients `R ⧸ I`. The actual quotient structures are defined in the following files: * quotient group: `src/group_theory/quotient_group.lean` * quotient module: `src/linear_algebra/quotient.lean` * quotient ring: `src/ring_theory/ideal/quotient.lean` ## Notations The following notation is introduced: * `G ⧸ H` stands for the quotient of the type `G` by some term `H` (for example, `H` can be a normal subgroup of `G`). To implement this notation for other quotients, you should provide a `has_quotient` instance. Note that since `G` can usually be inferred from `H`, `_ ⧸ H` can also be used, but this is less readable. ## Tags quotient, group quotient, quotient group, module quotient, quotient module, ring quotient, ideal quotient, quotient ring -/ universes u v /-- `has_quotient A B` is a notation typeclass that allows us to write `A ⧸ b` for `b : B`. This allows the usual notation for quotients of algebraic structures, such as groups, modules and rings. `A` is a parameter, despite being unused in the definition below, so it appears in the notation. -/ class has_quotient (A : out_param $ Type u) (B : Type v) := (quotient' : B → Type (max u v)) /-- `has_quotient.quotient A b` (with notation `A ⧸ b`) is the quotient of the type `A` by `b`. This differs from `has_quotient.quotient'` in that the `A` argument is explicit, which is necessary to make Lean show the notation in the goal state. -/ @[reducible, nolint has_nonempty_instance] -- Will be provided by e.g. `ideal.quotient.inhabited` def has_quotient.quotient (A : out_param $ Type u) {B : Type v} [has_quotient A B] (b : B) : Type (max u v) := has_quotient.quotient' b notation G ` ⧸ `:35 H:34 := has_quotient.quotient G H
ac4c5a1eb3e9c2fee374b0b895034abfe7189c12
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/order/group.lean
8106e0424248c72ce357952443745a0f17c6f09a
[ "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
49,211
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.abs import algebra.order.sub /-! # Ordered groups This file develops the basics of ordered groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ set_option old_structure_cmd true open function universe u variable {α : Type u} /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (α : Type u) extends comm_group α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) attribute [to_additive] ordered_comm_group @[to_additive] instance ordered_comm_group.to_covariant_class_left_le (α : Type u) [ordered_comm_group α] : covariant_class α α (*) (≤) := { elim := λ a b c bc, ordered_comm_group.mul_le_mul_left b c bc a } /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive "The units of an ordered commutative additive monoid form an ordered commutative additive group."] instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group αˣ := { mul_le_mul_left := λ a b h c, (mul_le_mul_left' (h : (a : α) ≤ b) _ : (c : α) * a ≤ c * b), .. units.partial_order, .. units.comm_group } @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { mul_left_cancel := λ a b c, (mul_right_inj a).mp, le_of_mul_le_mul_left := λ a b c, (mul_le_mul_iff_left a).mp, ..s } @[priority 100, to_additive] instance ordered_comm_group.has_exists_mul_of_le (α : Type u) [ordered_comm_group α] : has_exists_mul_of_le α := ⟨λ a b hab, ⟨b * a⁻¹, (mul_inv_cancel_comm_assoc a b).symm⟩⟩ @[to_additive] instance [h : has_inv α] : has_inv αᵒᵈ := h @[to_additive] instance [h : has_div α] : has_div αᵒᵈ := h @[to_additive] instance [h : has_involutive_inv α] : has_involutive_inv αᵒᵈ := h @[to_additive] instance [h : div_inv_monoid α] : div_inv_monoid αᵒᵈ := h @[to_additive order_dual.subtraction_monoid] instance [h : division_monoid α] : division_monoid αᵒᵈ := h @[to_additive order_dual.subtraction_comm_monoid] instance [h : division_comm_monoid α] : division_comm_monoid αᵒᵈ := h @[to_additive] instance [h : group α] : group αᵒᵈ := h @[to_additive] instance [h : comm_group α] : comm_group αᵒᵈ := h instance [h : group_with_zero α] : group_with_zero αᵒᵈ := h instance [h : comm_group_with_zero α] : comm_group_with_zero αᵒᵈ := h @[to_additive] instance [ordered_comm_group α] : ordered_comm_group αᵒᵈ := { .. order_dual.ordered_comm_monoid, .. order_dual.group } section group variables [group α] section typeclasses_left_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_nonpos_iff] lemma left.inv_le_one_iff : a⁻¹ ≤ 1 ↔ 1 ≤ a := by { rw [← mul_le_mul_iff_left a], simp } /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.nonneg_neg_iff] lemma left.one_le_inv_iff : 1 ≤ a⁻¹ ↔ a ≤ 1 := by { rw [← mul_le_mul_iff_left a], simp } @[simp, to_additive] lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c := by { rw ← mul_le_mul_iff_left a, simp } @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c := by rw [← mul_le_mul_iff_left b, mul_inv_cancel_left] @[to_additive neg_le_iff_add_nonneg'] lemma inv_le_iff_one_le_mul' : a⁻¹ ≤ b ↔ 1 ≤ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one_left : a ≤ b⁻¹ ↔ b * a ≤ 1 := (mul_le_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_mul_iff_le : 1 ≤ b⁻¹ * a ↔ b ≤ a := by rw [← mul_le_mul_iff_left b, mul_one, mul_inv_cancel_left] @[to_additive] lemma inv_mul_le_one_iff : a⁻¹ * b ≤ 1 ↔ b ≤ a := trans (inv_mul_le_iff_le_mul) $ by rw mul_one end typeclasses_left_le section typeclasses_left_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c : α} /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_pos_iff] lemma left.one_lt_inv_iff : 1 < a⁻¹ ↔ a < 1 := by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one] /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_neg_iff] lemma left.inv_lt_one_iff : a⁻¹ < 1 ↔ 1 < a := by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := by { rw [← mul_lt_mul_iff_left a], simp } @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := by rw [← mul_lt_mul_iff_left b, mul_inv_cancel_left] @[to_additive] lemma inv_lt_iff_one_lt_mul' : a⁻¹ < b ↔ 1 < a * b := (mul_lt_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_iff_mul_lt_one' : a < b⁻¹ ↔ b * a < 1 := (mul_lt_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_mul_iff_lt : 1 < b⁻¹ * a ↔ b < a := by rw [← mul_lt_mul_iff_left b, mul_one, mul_inv_cancel_left] @[to_additive] lemma inv_mul_lt_one_iff : a⁻¹ * b < 1 ↔ b < a := trans (inv_mul_lt_iff_lt_mul) $ by rw mul_one end typeclasses_left_lt section typeclasses_right_le variables [has_le α] [covariant_class α α (swap (*)) (≤)] {a b c : α} /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_nonpos_iff] lemma right.inv_le_one_iff : a⁻¹ ≤ 1 ↔ 1 ≤ a := by { rw [← mul_le_mul_iff_right a], simp } /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.nonneg_neg_iff] lemma right.one_le_inv_iff : 1 ≤ a⁻¹ ↔ a ≤ 1 := by { rw [← mul_le_mul_iff_right a], simp } @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ b * a := (mul_le_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive] lemma le_inv_iff_mul_le_one_right : a ≤ b⁻¹ ↔ a * b ≤ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive] lemma mul_inv_le_iff_le_mul : a * b⁻¹ ≤ c ↔ a ≤ c * b := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma le_mul_inv_iff_mul_le : c ≤ a * b⁻¹ ↔ c * b ≤ a := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma mul_inv_le_one_iff_le : a * b⁻¹ ≤ 1 ↔ a ≤ b := mul_inv_le_iff_le_mul.trans $ by rw one_mul @[to_additive] lemma le_mul_inv_iff_le : 1 ≤ a * b⁻¹ ↔ b ≤ a := by rw [← mul_le_mul_iff_right b, one_mul, inv_mul_cancel_right] @[to_additive] lemma mul_inv_le_one_iff : b * a⁻¹ ≤ 1 ↔ b ≤ a := trans (mul_inv_le_iff_le_mul) $ by rw one_mul end typeclasses_right_le section typeclasses_right_lt variables [has_lt α] [covariant_class α α (swap (*)) (<)] {a b c : α} /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_neg_iff "Uses `right` co(ntra)variant."] lemma right.inv_lt_one_iff : a⁻¹ < 1 ↔ 1 < a := by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul] /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_pos_iff "Uses `right` co(ntra)variant."] lemma right.one_lt_inv_iff : 1 < a⁻¹ ↔ a < 1 := by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul] @[to_additive] lemma inv_lt_iff_one_lt_mul : a⁻¹ < b ↔ 1 < b * a := (mul_lt_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive] lemma lt_inv_iff_mul_lt_one : a < b⁻¹ ↔ a * b < 1 := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive] lemma mul_inv_lt_iff_lt_mul : a * b⁻¹ < c ↔ a < c * b := by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right] @[simp, to_additive] lemma lt_mul_inv_iff_mul_lt : c < a * b⁻¹ ↔ c * b < a := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma inv_mul_lt_one_iff_lt : a * b⁻¹ < 1 ↔ a < b := by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right, one_mul] @[to_additive] lemma lt_mul_inv_iff_lt : 1 < a * b⁻¹ ↔ b < a := by rw [← mul_lt_mul_iff_right b, one_mul, inv_mul_cancel_right] @[to_additive] lemma mul_inv_lt_one_iff : b * a⁻¹ < 1 ↔ b < a := trans (mul_inv_lt_iff_lt_mul) $ by rw one_mul end typeclasses_right_lt section typeclasses_left_right_le variables [has_le α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by { rw [← mul_le_mul_iff_left a, ← mul_le_mul_iff_right b], simp } alias neg_le_neg_iff ↔ le_of_neg_le_neg _ section variable (α) /-- `x ↦ x⁻¹` as an order-reversing equivalence. -/ @[to_additive "`x ↦ -x` as an order-reversing equivalence.", simps] def order_iso.inv : α ≃o αᵒᵈ := { to_equiv := (equiv.inv α).trans order_dual.to_dual, map_rel_iff' := λ a b, @inv_le_inv_iff α _ _ _ _ _ _ } end @[to_additive neg_le] lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := (order_iso.inv α).symm_apply_le alias inv_le' ↔ inv_le_of_inv_le' _ attribute [to_additive neg_le_of_neg_le] inv_le_of_inv_le' @[to_additive le_neg] lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := (order_iso.inv α).le_symm_apply @[to_additive] lemma mul_inv_le_inv_mul_iff : a * b⁻¹ ≤ d⁻¹ * c ↔ d * a ≤ c * b := by rw [← mul_le_mul_iff_left d, ← mul_le_mul_iff_right b, mul_inv_cancel_left, mul_assoc, inv_mul_cancel_right] @[simp, to_additive] lemma div_le_self_iff (a : α) {b : α} : a / b ≤ a ↔ 1 ≤ b := by simp [div_eq_mul_inv] @[simp, to_additive] lemma le_div_self_iff (a : α) {b : α} : a ≤ a / b ↔ b ≤ 1 := by simp [div_eq_mul_inv] alias sub_le_self_iff ↔ _ sub_le_self end typeclasses_left_right_le section typeclasses_left_right_lt variables [has_lt α] [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c d : α} @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := by { rw [← mul_lt_mul_iff_left a, ← mul_lt_mul_iff_right b], simp } @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := by rw [← inv_lt_inv_iff, inv_inv] @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := by rw [← inv_lt_inv_iff, inv_inv] alias lt_inv' ↔ lt_inv_of_lt_inv _ attribute [to_additive] lt_inv_of_lt_inv alias inv_lt' ↔ inv_lt_of_inv_lt' _ attribute [to_additive neg_lt_of_neg_lt] inv_lt_of_inv_lt' @[to_additive] lemma mul_inv_lt_inv_mul_iff : a * b⁻¹ < d⁻¹ * c ↔ d * a < c * b := by rw [← mul_lt_mul_iff_left d, ← mul_lt_mul_iff_right b, mul_inv_cancel_left, mul_assoc, inv_mul_cancel_right] @[simp, to_additive] lemma div_lt_self_iff (a : α) {b : α} : a / b < a ↔ 1 < b := by simp [div_eq_mul_inv] alias sub_lt_self_iff ↔ _ sub_lt_self end typeclasses_left_right_lt section pre_order variable [preorder α] section left_le variables [covariant_class α α (*) (≤)] {a : α} @[to_additive] lemma left.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (left.inv_le_one_iff.mpr h) h alias left.neg_le_self ← neg_le_self @[to_additive] lemma left.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (left.one_le_inv_iff.mpr h) end left_le section left_lt variables [covariant_class α α (*) (<)] {a : α} @[to_additive] lemma left.inv_lt_self (h : 1 < a) : a⁻¹ < a := (left.inv_lt_one_iff.mpr h).trans h alias left.neg_lt_self ← neg_lt_self @[to_additive] lemma left.self_lt_inv (h : a < 1) : a < a⁻¹ := lt_trans h (left.one_lt_inv_iff.mpr h) end left_lt section right_le variables [covariant_class α α (swap (*)) (≤)] {a : α} @[to_additive] lemma right.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (right.inv_le_one_iff.mpr h) h @[to_additive] lemma right.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (right.one_le_inv_iff.mpr h) end right_le section right_lt variables [covariant_class α α (swap (*)) (<)] {a : α} @[to_additive] lemma right.inv_lt_self (h : 1 < a) : a⁻¹ < a := (right.inv_lt_one_iff.mpr h).trans h @[to_additive] lemma right.self_lt_inv (h : a < 1) : a < a⁻¹ := lt_trans h (right.one_lt_inv_iff.mpr h) end right_lt end pre_order end group section comm_group variables [comm_group α] section has_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive add_neg_le_add_neg_iff] lemma mul_inv_le_mul_inv_iff' : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := by rw [mul_comm c, mul_inv_le_inv_mul_iff, mul_comm] end has_le section has_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive] lemma inv_mul_lt_iff_lt_mul' : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[simp, to_additive] lemma mul_inv_lt_iff_le_mul' : a * b⁻¹ < c ↔ a < b * c := by rw [← inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive add_neg_lt_add_neg_iff] lemma mul_inv_lt_mul_inv_iff' : a * b⁻¹ < c * d⁻¹ ↔ a * d < c * b := by rw [mul_comm c, mul_inv_lt_inv_mul_iff, mul_comm] end has_lt end comm_group alias le_inv' ↔ le_inv_of_le_inv _ attribute [to_additive] le_inv_of_le_inv alias left.inv_le_one_iff ↔ one_le_of_inv_le_one _ attribute [to_additive] one_le_of_inv_le_one alias left.one_le_inv_iff ↔ le_one_of_one_le_inv _ attribute [to_additive nonpos_of_neg_nonneg] le_one_of_one_le_inv alias inv_lt_inv_iff ↔ lt_of_inv_lt_inv _ attribute [to_additive] lt_of_inv_lt_inv alias left.inv_lt_one_iff ↔ one_lt_of_inv_lt_one _ attribute [to_additive] one_lt_of_inv_lt_one alias left.inv_lt_one_iff ← inv_lt_one_iff_one_lt attribute [to_additive] inv_lt_one_iff_one_lt alias left.inv_lt_one_iff ← inv_lt_one' attribute [to_additive neg_lt_zero] inv_lt_one' alias left.one_lt_inv_iff ↔ inv_of_one_lt_inv _ attribute [to_additive neg_of_neg_pos] inv_of_one_lt_inv alias left.one_lt_inv_iff ↔ _ one_lt_inv_of_inv attribute [to_additive neg_pos_of_neg] one_lt_inv_of_inv alias le_inv_mul_iff_mul_le ↔ mul_le_of_le_inv_mul _ attribute [to_additive] mul_le_of_le_inv_mul alias le_inv_mul_iff_mul_le ↔ _ le_inv_mul_of_mul_le attribute [to_additive] le_inv_mul_of_mul_le alias inv_mul_le_iff_le_mul ↔ _ inv_mul_le_of_le_mul attribute [to_additive] inv_mul_le_iff_le_mul alias lt_inv_mul_iff_mul_lt ↔ mul_lt_of_lt_inv_mul _ attribute [to_additive] mul_lt_of_lt_inv_mul alias lt_inv_mul_iff_mul_lt ↔ _ lt_inv_mul_of_mul_lt attribute [to_additive] lt_inv_mul_of_mul_lt alias inv_mul_lt_iff_lt_mul ↔ lt_mul_of_inv_mul_lt inv_mul_lt_of_lt_mul attribute [to_additive] lt_mul_of_inv_mul_lt attribute [to_additive] inv_mul_lt_of_lt_mul alias lt_mul_of_inv_mul_lt ← lt_mul_of_inv_mul_lt_left attribute [to_additive] lt_mul_of_inv_mul_lt_left alias left.inv_le_one_iff ← inv_le_one' attribute [to_additive neg_nonpos] inv_le_one' alias left.one_le_inv_iff ← one_le_inv' attribute [to_additive neg_nonneg] one_le_inv' alias left.one_lt_inv_iff ← one_lt_inv' attribute [to_additive neg_pos] one_lt_inv' alias mul_lt_mul_left' ← ordered_comm_group.mul_lt_mul_left' attribute [to_additive ordered_add_comm_group.add_lt_add_left] ordered_comm_group.mul_lt_mul_left' alias le_of_mul_le_mul_left' ← ordered_comm_group.le_of_mul_le_mul_left attribute [to_additive ordered_add_comm_group.le_of_add_le_add_left] ordered_comm_group.le_of_mul_le_mul_left alias lt_of_mul_lt_mul_left' ← ordered_comm_group.lt_of_mul_lt_mul_left attribute [to_additive ordered_add_comm_group.lt_of_add_lt_add_left] ordered_comm_group.lt_of_mul_lt_mul_left /-- Pullback an `ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_add_comm_group "Pullback an `ordered_add_comm_group` under an injective map."] def function.injective.ordered_comm_group [ordered_comm_group α] {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] [has_pow β ℕ] [has_pow β ℤ] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) : ordered_comm_group β := { ..partial_order.lift f hf, ..hf.ordered_comm_monoid f one mul npow, ..hf.comm_group f one mul inv div npow zpow } /- Most of the lemmas that are primed in this section appear in ordered_field. -/ /- I (DT) did not try to minimise the assumptions. -/ section group variables [group α] [has_le α] section right variables [covariant_class α α (swap (*)) (≤)] {a b c d : α} @[simp, to_additive] lemma div_le_div_iff_right (c : α) : a / c ≤ b / c ↔ a ≤ b := by simpa only [div_eq_mul_inv] using mul_le_mul_iff_right _ @[to_additive sub_le_sub_right] lemma div_le_div_right' (h : a ≤ b) (c : α) : a / c ≤ b / c := (div_le_div_iff_right c).2 h @[simp, to_additive sub_nonneg] lemma one_le_div' : 1 ≤ a / b ↔ b ≤ a := by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_nonneg ↔ le_of_sub_nonneg sub_nonneg_of_le @[simp, to_additive sub_nonpos] lemma div_le_one' : a / b ≤ 1 ↔ a ≤ b := by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_nonpos ↔ le_of_sub_nonpos sub_nonpos_of_le @[to_additive] lemma le_div_iff_mul_le : a ≤ c / b ↔ a * b ≤ c := by rw [← mul_le_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right] alias le_sub_iff_add_le ↔ add_le_of_le_sub_right le_sub_right_of_add_le @[to_additive] lemma div_le_iff_le_mul : a / c ≤ b ↔ a ≤ b * c := by rw [← mul_le_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right] -- TODO: Should we get rid of `sub_le_iff_le_add` in favor of -- (a renamed version of) `tsub_le_iff_right`? @[priority 100] -- see Note [lower instance priority] instance add_group.to_has_ordered_sub {α : Type*} [add_group α] [has_le α] [covariant_class α α (swap (+)) (≤)] : has_ordered_sub α := ⟨λ a b c, sub_le_iff_le_add⟩ /-- `equiv.mul_right` as an `order_iso`. See also `order_embedding.mul_right`. -/ @[to_additive "`equiv.add_right` as an `order_iso`. See also `order_embedding.add_right`.", simps to_equiv apply {simp_rhs := tt}] def order_iso.mul_right (a : α) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_iff_right a, to_equiv := equiv.mul_right a } @[simp, to_additive] lemma order_iso.mul_right_symm (a : α) : (order_iso.mul_right a).symm = order_iso.mul_right a⁻¹ := by { ext x, refl } end right section left variables [covariant_class α α (*) (≤)] /-- `equiv.mul_left` as an `order_iso`. See also `order_embedding.mul_left`. -/ @[to_additive "`equiv.add_left` as an `order_iso`. See also `order_embedding.add_left`.", simps to_equiv apply {simp_rhs := tt}] def order_iso.mul_left (a : α) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_iff_left a, to_equiv := equiv.mul_left a } @[simp, to_additive] lemma order_iso.mul_left_symm (a : α) : (order_iso.mul_left a).symm = order_iso.mul_left a⁻¹ := by { ext x, refl } variables [covariant_class α α (swap (*)) (≤)] {a b c : α} @[simp, to_additive] lemma div_le_div_iff_left (a : α) : a / b ≤ a / c ↔ c ≤ b := by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_le_mul_iff_left a⁻¹, inv_mul_cancel_left, inv_mul_cancel_left, inv_le_inv_iff] @[to_additive sub_le_sub_left] lemma div_le_div_left' (h : a ≤ b) (c : α) : c / b ≤ c / a := (div_le_div_iff_left c).2 h end left end group section comm_group variables [comm_group α] section has_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive sub_le_sub_iff] lemma div_le_div_iff' : a / b ≤ c / d ↔ a * d ≤ c * b := by simpa only [div_eq_mul_inv] using mul_inv_le_mul_inv_iff' @[to_additive] lemma le_div_iff_mul_le' : b ≤ c / a ↔ a * b ≤ c := by rw [le_div_iff_mul_le, mul_comm] alias le_sub_iff_add_le' ↔ add_le_of_le_sub_left le_sub_left_of_add_le @[to_additive] lemma div_le_iff_le_mul' : a / b ≤ c ↔ a ≤ b * c := by rw [div_le_iff_le_mul, mul_comm] alias sub_le_iff_le_add' ↔ le_add_of_sub_left_le sub_left_le_of_le_add @[simp, to_additive] lemma inv_le_div_iff_le_mul : b⁻¹ ≤ a / c ↔ c ≤ a * b := le_div_iff_mul_le.trans inv_mul_le_iff_le_mul' @[to_additive] lemma inv_le_div_iff_le_mul' : a⁻¹ ≤ b / c ↔ c ≤ a * b := by rw [inv_le_div_iff_le_mul, mul_comm] @[to_additive sub_le] lemma div_le'' : a / b ≤ c ↔ a / c ≤ b := div_le_iff_le_mul'.trans div_le_iff_le_mul.symm @[to_additive le_sub] lemma le_div'' : a ≤ b / c ↔ c ≤ b / a := le_div_iff_mul_le'.trans le_div_iff_mul_le.symm end has_le section preorder variables [preorder α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive sub_le_sub] lemma div_le_div'' (hab : a ≤ b) (hcd : c ≤ d) : a / d ≤ b / c := begin rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_le_inv_mul_iff, mul_comm], exact mul_le_mul' hab hcd end end preorder end comm_group /- Most of the lemmas that are primed in this section appear in ordered_field. -/ /- I (DT) did not try to minimise the assumptions. -/ section group variables [group α] [has_lt α] section right variables [covariant_class α α (swap (*)) (<)] {a b c d : α} @[simp, to_additive] lemma div_lt_div_iff_right (c : α) : a / c < b / c ↔ a < b := by simpa only [div_eq_mul_inv] using mul_lt_mul_iff_right _ @[to_additive sub_lt_sub_right] lemma div_lt_div_right' (h : a < b) (c : α) : a / c < b / c := (div_lt_div_iff_right c).2 h @[simp, to_additive sub_pos] lemma one_lt_div' : 1 < a / b ↔ b < a := by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_pos ↔ lt_of_sub_pos sub_pos_of_lt @[simp, to_additive sub_neg] lemma div_lt_one' : a / b < 1 ↔ a < b := by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_neg ↔ lt_of_sub_neg sub_neg_of_lt alias sub_neg ← sub_lt_zero @[to_additive] lemma lt_div_iff_mul_lt : a < c / b ↔ a * b < c := by rw [← mul_lt_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right] alias lt_sub_iff_add_lt ↔ add_lt_of_lt_sub_right lt_sub_right_of_add_lt @[to_additive] lemma div_lt_iff_lt_mul : a / c < b ↔ a < b * c := by rw [← mul_lt_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right] alias sub_lt_iff_lt_add ↔ lt_add_of_sub_right_lt sub_right_lt_of_lt_add end right section left variables [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c : α} @[simp, to_additive] lemma div_lt_div_iff_left (a : α) : a / b < a / c ↔ c < b := by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_lt_mul_iff_left a⁻¹, inv_mul_cancel_left, inv_mul_cancel_left, inv_lt_inv_iff] @[simp, to_additive] lemma inv_lt_div_iff_lt_mul : a⁻¹ < b / c ↔ c < a * b := by rw [div_eq_mul_inv, lt_mul_inv_iff_mul_lt, inv_mul_lt_iff_lt_mul] @[to_additive sub_lt_sub_left] lemma div_lt_div_left' (h : a < b) (c : α) : c / b < c / a := (div_lt_div_iff_left c).2 h end left end group section comm_group variables [comm_group α] section has_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive sub_lt_sub_iff] lemma div_lt_div_iff' : a / b < c / d ↔ a * d < c * b := by simpa only [div_eq_mul_inv] using mul_inv_lt_mul_inv_iff' @[to_additive] lemma lt_div_iff_mul_lt' : b < c / a ↔ a * b < c := by rw [lt_div_iff_mul_lt, mul_comm] alias lt_sub_iff_add_lt' ↔ add_lt_of_lt_sub_left lt_sub_left_of_add_lt @[to_additive] lemma div_lt_iff_lt_mul' : a / b < c ↔ a < b * c := by rw [div_lt_iff_lt_mul, mul_comm] alias sub_lt_iff_lt_add' ↔ lt_add_of_sub_left_lt sub_left_lt_of_lt_add @[to_additive] lemma inv_lt_div_iff_lt_mul' : b⁻¹ < a / c ↔ c < a * b := lt_div_iff_mul_lt.trans inv_mul_lt_iff_lt_mul' @[to_additive sub_lt] lemma div_lt'' : a / b < c ↔ a / c < b := div_lt_iff_lt_mul'.trans div_lt_iff_lt_mul.symm @[to_additive lt_sub] lemma lt_div'' : a < b / c ↔ c < b / a := lt_div_iff_mul_lt'.trans lt_div_iff_mul_lt.symm end has_lt section preorder variables [preorder α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive sub_lt_sub] lemma div_lt_div'' (hab : a < b) (hcd : c < d) : a / d < b / c := begin rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_lt_inv_mul_iff, mul_comm], exact mul_lt_mul_of_lt_of_lt hab hcd end end preorder end comm_group section linear_order variables [group α] [linear_order α] [covariant_class α α (*) (≤)] section variable_names variables {a b c : α} @[to_additive] lemma le_of_forall_one_lt_lt_mul (h : ∀ ε : α, 1 < ε → a < b * ε) : a ≤ b := le_of_not_lt (λ h₁, lt_irrefl a (by simpa using (h _ (lt_inv_mul_iff_lt.mpr h₁)))) @[to_additive] lemma le_iff_forall_one_lt_lt_mul : a ≤ b ↔ ∀ ε, 1 < ε → a < b * ε := ⟨λ h ε, lt_mul_of_le_of_one_lt h, le_of_forall_one_lt_lt_mul⟩ /- I (DT) introduced this lemma to prove (the additive version `sub_le_sub_flip` of) `div_le_div_flip` below. Now I wonder what is the point of either of these lemmas... -/ @[to_additive] lemma div_le_inv_mul_iff [covariant_class α α (swap (*)) (≤)] : a / b ≤ a⁻¹ * b ↔ a ≤ b := begin rw [div_eq_mul_inv, mul_inv_le_inv_mul_iff], exact ⟨λ h, not_lt.mp (λ k, not_lt.mpr h (mul_lt_mul_of_lt_of_lt k k)), λ h, mul_le_mul' h h⟩, end /- What is the point of this lemma? See comment about `div_le_inv_mul_iff` above. -/ @[simp, to_additive] lemma div_le_div_flip {α : Type*} [comm_group α] [linear_order α] [covariant_class α α (*) (≤)] {a b : α}: a / b ≤ b / a ↔ a ≤ b := begin rw [div_eq_mul_inv b, mul_comm], exact div_le_inv_mul_iff, end @[simp, to_additive] lemma max_one_div_max_inv_one_eq_self (a : α) : max a 1 / max a⁻¹ 1 = a := by { rcases le_total a 1 with h|h; simp [h] } alias max_zero_sub_max_neg_zero_eq_self ← max_zero_sub_eq_self end variable_names section densely_ordered variables [densely_ordered α] {a b c : α} @[to_additive] lemma le_of_forall_one_lt_le_mul (h : ∀ ε : α, 1 < ε → a ≤ b * ε) : a ≤ b := le_of_forall_le_of_dense $ λ c hc, calc a ≤ b * (b⁻¹ * c) : h _ (lt_inv_mul_iff_lt.mpr hc) ... = c : mul_inv_cancel_left b c @[to_additive] lemma le_of_forall_lt_one_mul_le (h : ∀ ε < 1, a * ε ≤ b) : a ≤ b := @le_of_forall_one_lt_le_mul αᵒᵈ _ _ _ _ _ _ h @[to_additive] lemma le_of_forall_one_lt_div_le (h : ∀ ε : α, 1 < ε → a / ε ≤ b) : a ≤ b := le_of_forall_lt_one_mul_le $ λ ε ε1, by simpa only [div_eq_mul_inv, inv_inv] using h ε⁻¹ (left.one_lt_inv_iff.2 ε1) @[to_additive] lemma le_iff_forall_one_lt_le_mul : a ≤ b ↔ ∀ ε, 1 < ε → a ≤ b * ε := ⟨λ h ε ε_pos, le_mul_of_le_of_one_le h ε_pos.le, le_of_forall_one_lt_le_mul⟩ @[to_additive] lemma le_iff_forall_lt_one_mul_le : a ≤ b ↔ ∀ ε < 1, a * ε ≤ b := @le_iff_forall_one_lt_le_mul αᵒᵈ _ _ _ _ _ _ end densely_ordered end linear_order /-! ### Linearly ordered commutative groups -/ /-- A linearly ordered additive commutative group is an additive commutative group with a linear order in which addition is monotone. -/ @[protect_proj, ancestor ordered_add_comm_group linear_order] class linear_ordered_add_comm_group (α : Type u) extends ordered_add_comm_group α, linear_order α /-- A linearly ordered commutative monoid with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined.` -/ @[protect_proj, ancestor linear_ordered_add_comm_monoid_with_top sub_neg_monoid nontrivial] class linear_ordered_add_comm_group_with_top (α : Type*) extends linear_ordered_add_comm_monoid_with_top α, sub_neg_monoid α, nontrivial α := (neg_top : - (⊤ : α) = ⊤) (add_neg_cancel : ∀ a:α, a ≠ ⊤ → a + (- a) = 0) /-- A linearly ordered commutative group is a commutative group with a linear order in which multiplication is monotone. -/ @[protect_proj, ancestor ordered_comm_group linear_order, to_additive] class linear_ordered_comm_group (α : Type u) extends ordered_comm_group α, linear_order α @[to_additive] instance [linear_ordered_comm_group α] : linear_ordered_comm_group αᵒᵈ := { .. order_dual.ordered_comm_group, .. order_dual.linear_order α } section linear_ordered_comm_group variables [linear_ordered_comm_group α] {a b c : α} @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_linear_ordered_cancel_comm_monoid : linear_ordered_cancel_comm_monoid α := { le_of_mul_le_mul_left := λ x y z, le_of_mul_le_mul_left', mul_left_cancel := λ x y z, mul_left_cancel, ..‹linear_ordered_comm_group α› } /-- Pullback a `linear_ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_add_comm_group "Pullback a `linear_ordered_add_comm_group` under an injective map."] def function.injective.linear_ordered_comm_group {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] [has_pow β ℕ] [has_pow β ℤ] [has_sup β] [has_inf β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_ordered_comm_group β := { ..linear_order.lift f hf hsup hinf, ..hf.ordered_comm_group f one mul inv div npow zpow } @[to_additive linear_ordered_add_comm_group.add_lt_add_left] lemma linear_ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b := mul_lt_mul_left' h c @[to_additive min_neg_neg] lemma min_inv_inv' (a b : α) : min (a⁻¹) (b⁻¹) = (max a b)⁻¹ := eq.symm $ @monotone.map_max α αᵒᵈ _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive max_neg_neg] lemma max_inv_inv' (a b : α) : max (a⁻¹) (b⁻¹) = (min a b)⁻¹ := eq.symm $ @monotone.map_min α αᵒᵈ _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive min_sub_sub_right] lemma min_div_div_right' (a b c : α) : min (a / c) (b / c) = min a b / c := by simpa only [div_eq_mul_inv] using min_mul_mul_right a b (c⁻¹) @[to_additive max_sub_sub_right] lemma max_div_div_right' (a b c : α) : max (a / c) (b / c) = max a b / c := by simpa only [div_eq_mul_inv] using max_mul_mul_right a b (c⁻¹) @[to_additive min_sub_sub_left] lemma min_div_div_left' (a b c : α) : min (a / b) (a / c) = a / max b c := by simp only [div_eq_mul_inv, min_mul_mul_left, min_inv_inv'] @[to_additive max_sub_sub_left] lemma max_div_div_left' (a b c : α) : max (a / b) (a / c) = a / min b c := by simp only [div_eq_mul_inv, max_mul_mul_left, max_inv_inv'] @[to_additive eq_zero_of_neg_eq] lemma eq_one_of_inv_eq' (h : a⁻¹ = a) : a = 1 := match lt_trichotomy a 1 with | or.inl h₁ := have 1 < a, from h ▸ one_lt_inv_of_inv h₁, absurd h₁ this.asymm | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 1, from h ▸ inv_lt_one'.mpr h₁, absurd h₁ this.asymm end @[to_additive exists_zero_lt] lemma exists_one_lt' [nontrivial α] : ∃ (a:α), 1 < a := begin obtain ⟨y, hy⟩ := decidable.exists_ne (1 : α), cases hy.lt_or_lt, { exact ⟨y⁻¹, one_lt_inv'.mpr h⟩ }, { exact ⟨y, h⟩ } end @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_max_order [nontrivial α] : no_max_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a * y, lt_mul_of_one_lt_right' a hy⟩ end ⟩ @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_min_order [nontrivial α] : no_min_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a / y, (div_lt_self_iff a).mpr hy⟩ end ⟩ end linear_ordered_comm_group section covariant_add_le section has_neg /-- `abs a` is the absolute value of `a`. -/ @[to_additive "`abs a` is the absolute value of `a`", priority 100] -- see Note [lower instance priority] instance has_inv.to_has_abs [has_inv α] [has_sup α] : has_abs α := ⟨λ a, a ⊔ a⁻¹⟩ @[to_additive] lemma abs_eq_sup_inv [has_inv α] [has_sup α] (a : α) : |a| = a ⊔ a⁻¹ := rfl variables [has_neg α] [linear_order α] {a b: α} lemma abs_eq_max_neg : abs a = max a (-a) := rfl lemma abs_choice (x : α) : |x| = x ∨ |x| = -x := max_choice _ _ lemma abs_le' : |a| ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff lemma le_abs : a ≤ |b| ↔ a ≤ b ∨ a ≤ -b := le_max_iff lemma le_abs_self (a : α) : a ≤ |a| := le_max_left _ _ lemma neg_le_abs_self (a : α) : -a ≤ |a| := le_max_right _ _ lemma lt_abs : a < |b| ↔ a < b ∨ a < -b := lt_max_iff theorem abs_le_abs (h₀ : a ≤ b) (h₁ : -a ≤ b) : |a| ≤ |b| := (abs_le'.2 ⟨h₀, h₁⟩).trans (le_abs_self b) lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (|a|) := sup_ind _ _ h1 h2 end has_neg section add_group variables [add_group α] [linear_order α] @[simp] lemma abs_neg (a : α) : | -a| = |a| := begin rw [abs_eq_max_neg, max_comm, neg_neg, abs_eq_max_neg] end lemma eq_or_eq_neg_of_abs_eq {a b : α} (h : |a| = b) : a = b ∨ a = -b := by simpa only [← h, eq_comm, eq_neg_iff_eq_neg] using abs_choice a lemma abs_eq_abs {a b : α} : |a| = |b| ↔ a = b ∨ a = -b := begin refine ⟨λ h, _, λ h, _⟩, { obtain rfl | rfl := eq_or_eq_neg_of_abs_eq h; simpa only [neg_eq_iff_neg_eq, neg_inj, or.comm, @eq_comm _ (-b)] using abs_choice b }, { cases h; simp only [h, abs_neg] }, end lemma abs_sub_comm (a b : α) : |a - b| = |b - a| := calc |a - b| = | - (b - a)| : congr_arg _ (neg_sub b a).symm ... = |b - a| : abs_neg (b - a) variables [covariant_class α α (+) (≤)] {a b c : α} lemma abs_of_nonneg (h : 0 ≤ a) : |a| = a := max_eq_left $ (neg_nonpos.2 h).trans h lemma abs_of_pos (h : 0 < a) : |a| = a := abs_of_nonneg h.le lemma abs_of_nonpos (h : a ≤ 0) : |a| = -a := max_eq_right $ h.trans (neg_nonneg.2 h) lemma abs_of_neg (h : a < 0) : |a| = -a := abs_of_nonpos h.le @[simp] lemma abs_zero : |0| = (0:α) := abs_of_nonneg le_rfl @[simp] lemma abs_pos : 0 < |a| ↔ a ≠ 0 := begin rcases lt_trichotomy a 0 with (ha|rfl|ha), { simp [abs_of_neg ha, neg_pos, ha.ne, ha] }, { simp }, { simp [abs_of_pos ha, ha, ha.ne.symm] } end lemma abs_pos_of_pos (h : 0 < a) : 0 < |a| := abs_pos.2 h.ne.symm lemma abs_pos_of_neg (h : a < 0) : 0 < |a| := abs_pos.2 h.ne lemma neg_abs_le_self (a : α) : -|a| ≤ a := begin cases le_total 0 a with h h, { calc -|a| = - a : congr_arg (has_neg.neg) (abs_of_nonneg h) ... ≤ 0 : neg_nonpos.mpr h ... ≤ a : h }, { calc -|a| = - - a : congr_arg (has_neg.neg) (abs_of_nonpos h) ... ≤ a : (neg_neg a).le } end lemma add_abs_nonneg (a : α) : 0 ≤ a + |a| := begin rw ←add_right_neg a, apply add_le_add_left, exact (neg_le_abs_self a), end lemma neg_abs_le_neg (a : α) : -|a| ≤ -a := by simpa using neg_abs_le_self (-a) @[simp] lemma abs_nonneg (a : α) : 0 ≤ |a| := (le_total 0 a).elim (λ h, h.trans (le_abs_self a)) (λ h, (neg_nonneg.2 h).trans $ neg_le_abs_self a) @[simp] lemma abs_abs (a : α) : | |a| | = |a| := abs_of_nonneg $ abs_nonneg a @[simp] lemma abs_eq_zero : |a| = 0 ↔ a = 0 := decidable.not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos @[simp] lemma abs_nonpos_iff {a : α} : |a| ≤ 0 ↔ a = 0 := (abs_nonneg a).le_iff_eq.trans abs_eq_zero variable [covariant_class α α (swap (+)) (≤)] lemma abs_lt : |a| < b ↔ - b < a ∧ a < b := max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt] lemma neg_lt_of_abs_lt (h : |a| < b) : -b < a := (abs_lt.mp h).1 lemma lt_of_abs_lt (h : |a| < b) : a < b := (abs_lt.mp h).2 lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = |a - b| := begin cases le_total a b with ab ba, { rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos }, { rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], rwa sub_nonneg } end lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = |b - a| := by { rw abs_sub_comm, exact max_sub_min_eq_abs' _ _ } end add_group end covariant_add_le section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] {a b c d : α} lemma abs_le : |a| ≤ b ↔ - b ≤ a ∧ a ≤ b := by rw [abs_le', and.comm, neg_le] lemma le_abs' : a ≤ |b| ↔ b ≤ -a ∨ a ≤ b := by rw [le_abs, or.comm, le_neg] lemma neg_le_of_abs_le (h : |a| ≤ b) : -b ≤ a := (abs_le.mp h).1 lemma le_of_abs_le (h : |a| ≤ b) : a ≤ b := (abs_le.mp h).2 @[to_additive] lemma apply_abs_le_mul_of_one_le' {β : Type*} [mul_one_class β] [preorder β] [covariant_class β β (*) (≤)] [covariant_class β β (swap (*)) (≤)] {f : α → β} {a : α} (h₁ : 1 ≤ f a) (h₂ : 1 ≤ f (-a)) : f (|a|) ≤ f a * f (-a) := (le_total a 0).by_cases (λ ha, (abs_of_nonpos ha).symm ▸ le_mul_of_one_le_left' h₁) (λ ha, (abs_of_nonneg ha).symm ▸ le_mul_of_one_le_right' h₂) @[to_additive] lemma apply_abs_le_mul_of_one_le {β : Type*} [mul_one_class β] [preorder β] [covariant_class β β (*) (≤)] [covariant_class β β (swap (*)) (≤)] {f : α → β} (h : ∀ x, 1 ≤ f x) (a : α) : f (|a|) ≤ f a * f (-a) := apply_abs_le_mul_of_one_le' (h _) (h _) /-- The **triangle inequality** in `linear_ordered_add_comm_group`s. -/ lemma abs_add (a b : α) : |a + b| ≤ |a| + |b| := abs_le.2 ⟨(neg_add (|a|) (|b|)).symm ▸ add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _), add_le_add (le_abs_self _) (le_abs_self _)⟩ lemma abs_add' (a b : α) : |a| ≤ |b| + |b + a| := by simpa using abs_add (-b) (b + a) theorem abs_sub (a b : α) : |a - b| ≤ |a| + |b| := by { rw [sub_eq_add_neg, ←abs_neg b], exact abs_add a _ } lemma abs_sub_le_iff : |a - b| ≤ c ↔ a - b ≤ c ∧ b - a ≤ c := by rw [abs_le, neg_le_sub_iff_le_add, sub_le_iff_le_add', and_comm, sub_le_iff_le_add'] lemma abs_sub_lt_iff : |a - b| < c ↔ a - b < c ∧ b - a < c := by rw [abs_lt, neg_lt_sub_iff_lt_add', sub_lt_iff_lt_add', and_comm, sub_lt_iff_lt_add'] lemma sub_le_of_abs_sub_le_left (h : |a - b| ≤ c) : b - c ≤ a := sub_le.1 $ (abs_sub_le_iff.1 h).2 lemma sub_le_of_abs_sub_le_right (h : |a - b| ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub_comm a b ▸ h) lemma sub_lt_of_abs_sub_lt_left (h : |a - b| < c) : b - c < a := sub_lt.1 $ (abs_sub_lt_iff.1 h).2 lemma sub_lt_of_abs_sub_lt_right (h : |a - b| < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub_comm a b ▸ h) lemma abs_sub_abs_le_abs_sub (a b : α) : |a| - |b| ≤ |a - b| := sub_le_iff_le_add.2 $ calc |a| = |a - b + b| : by rw [sub_add_cancel] ... ≤ |a - b| + |b| : abs_add _ _ lemma abs_abs_sub_abs_le_abs_sub (a b : α) : | |a| - |b| | ≤ |a - b| := abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub_comm; apply abs_sub_abs_le_abs_sub⟩ lemma abs_eq (hb : 0 ≤ b) : |a| = b ↔ a = b ∨ a = -b := begin refine ⟨eq_or_eq_neg_of_abs_eq, _⟩, rintro (rfl|rfl); simp only [abs_neg, abs_of_nonneg hb] end lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : |b| ≤ max (|a|) (|c|) := abs_le'.2 ⟨by simp [hbc.trans (le_abs_self c)], by simp [(neg_le_neg_iff.mpr hab).trans (neg_le_abs_self a)]⟩ lemma eq_of_abs_sub_eq_zero {a b : α} (h : |a - b| = 0) : a = b := sub_eq_zero.1 $ abs_eq_zero.1 h lemma abs_sub_le (a b c : α) : |a - c| ≤ |a - b| + |b - c| := calc |a - c| = |a - b + (b - c)| : by rw [sub_add_sub_cancel] ... ≤ |a - b| + |b - c| : abs_add _ _ lemma abs_add_three (a b c : α) : |a + b + c| ≤ |a| + |b| + |c| := (abs_add _ _).trans (add_le_add_right (abs_add _ _) _) lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : |a - b| ≤ ub - lb := abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩ lemma eq_of_abs_sub_nonpos (h : |a - b| ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) lemma max_sub_max_le_max (a b c d : α) : max a b - max c d ≤ max (a - c) (b - d) := begin simp only [sub_le_iff_le_add, max_le_iff], split, calc a = a - c + c : (sub_add_cancel a c).symm ... ≤ max (a - c) (b - d) + max c d : add_le_add (le_max_left _ _) (le_max_left _ _), calc b = b - d + d : (sub_add_cancel b d).symm ... ≤ max (a - c) (b - d) + max c d : add_le_add (le_max_right _ _) (le_max_right _ _) end lemma abs_max_sub_max_le_max (a b c d : α) : |max a b - max c d| ≤ max (|a - c|) (|b - d|) := begin refine abs_sub_le_iff.2 ⟨_, _⟩, { exact (max_sub_max_le_max _ _ _ _).trans (max_le_max (le_abs_self _) (le_abs_self _)) }, { rw [abs_sub_comm a c, abs_sub_comm b d], exact (max_sub_max_le_max _ _ _ _).trans (max_le_max (le_abs_self _) (le_abs_self _)) } end lemma abs_min_sub_min_le_max (a b c d : α) : |min a b - min c d| ≤ max (|a - c|) (|b - d|) := by simpa only [max_neg_neg, neg_sub_neg, abs_sub_comm] using abs_max_sub_max_le_max (-a) (-b) (-c) (-d) lemma abs_max_sub_max_le_abs (a b c : α) : |max a c - max b c| ≤ |a - b| := by simpa only [sub_self, abs_zero, max_eq_left (abs_nonneg _)] using abs_max_sub_max_le_max a c b c instance with_top.linear_ordered_add_comm_group_with_top : linear_ordered_add_comm_group_with_top (with_top α) := { neg := option.map (λ a : α, -a), neg_top := @option.map_none _ _ (λ a : α, -a), add_neg_cancel := begin rintro (a | a) ha, { exact (ha rfl).elim }, { exact with_top.coe_add.symm.trans (with_top.coe_eq_coe.2 (add_neg_self a)) } end, .. with_top.linear_ordered_add_comm_monoid_with_top, .. option.nontrivial } @[simp, norm_cast] lemma with_top.coe_neg (a : α) : ((-a : α) : with_top α) = -a := rfl end linear_ordered_add_comm_group namespace add_comm_group /-- A collection of elements in an `add_comm_group` designated as "non-negative". This is useful for constructing an `ordered_add_commm_group` by choosing a positive cone in an exisiting `add_comm_group`. -/ @[nolint has_inhabited_instance] structure positive_cone (α : Type*) [add_comm_group α] := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (-a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) /-- A positive cone in an `add_comm_group` induces a linear order if for every `a`, either `a` or `-a` is non-negative. -/ @[nolint has_inhabited_instance] structure total_positive_cone (α : Type*) [add_comm_group α] extends positive_cone α := (nonneg_decidable : decidable_pred nonneg) (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) /-- Forget that a `total_positive_cone` is total. -/ add_decl_doc total_positive_cone.to_positive_cone end add_comm_group namespace ordered_add_comm_group open add_comm_group /-- Construct an `ordered_add_comm_group` by designating a positive cone in an existing `add_comm_group`. -/ def mk_of_positive_cone {α : Type*} [add_comm_group α] (C : positive_cone α) : ordered_add_comm_group α := { le := λ a b, C.nonneg (b - a), lt := λ a b, C.pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [C.pos_iff]; simp, le_refl := λ a, by simp [C.zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact C.add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ C.nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, ..‹add_comm_group α› } end ordered_add_comm_group namespace linear_ordered_add_comm_group open add_comm_group /-- Construct a `linear_ordered_add_comm_group` by designating a positive cone in an existing `add_comm_group` such that for every `a`, either `a` or `-a` is non-negative. -/ def mk_of_positive_cone {α : Type*} [add_comm_group α] (C : total_positive_cone α) : linear_ordered_add_comm_group α := { le_total := λ a b, by { convert C.nonneg_total (b - a), change C.nonneg _ = _, congr, simp, }, decidable_le := λ a b, C.nonneg_decidable _, ..ordered_add_comm_group.mk_of_positive_cone C.to_positive_cone } end linear_ordered_add_comm_group namespace prod variables {G H : Type*} @[to_additive] instance [ordered_comm_group G] [ordered_comm_group H] : ordered_comm_group (G × H) := { .. prod.comm_group, .. prod.partial_order G H, .. prod.ordered_cancel_comm_monoid } end prod section type_tags instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_add_comm_group (additive α) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_group α] : linear_ordered_comm_group (multiplicative α) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_group } instance [linear_ordered_comm_group α] : linear_ordered_add_comm_group (additive α) := { ..additive.linear_order, ..additive.ordered_add_comm_group } end type_tags section norm_num_lemmas /- The following lemmas are stated so that the `norm_num` tactic can use them with the expected signatures. -/ variables [ordered_comm_group α] {a b : α} @[to_additive neg_le_neg] lemma inv_le_inv' : a ≤ b → b⁻¹ ≤ a⁻¹ := inv_le_inv_iff.mpr @[to_additive neg_lt_neg] lemma inv_lt_inv' : a < b → b⁻¹ < a⁻¹ := inv_lt_inv_iff.mpr /- The additive version is also a `linarith` lemma. -/ @[to_additive] theorem inv_lt_one_of_one_lt : 1 < a → a⁻¹ < 1 := inv_lt_one_iff_one_lt.mpr /- The additive version is also a `linarith` lemma. -/ @[to_additive] lemma inv_le_one_of_one_le : 1 ≤ a → a⁻¹ ≤ 1 := inv_le_one'.mpr @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one : a ≤ 1 → 1 ≤ a⁻¹ := one_le_inv'.mpr end norm_num_lemmas section variables {β : Type*} [group α] [preorder α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] [preorder β] {f : β → α} {s : set β} @[to_additive] lemma monotone.inv (hf : monotone f) : antitone (λ x, (f x)⁻¹) := λ x y hxy, inv_le_inv_iff.2 (hf hxy) @[to_additive] lemma antitone.inv (hf : antitone f) : monotone (λ x, (f x)⁻¹) := λ x y hxy, inv_le_inv_iff.2 (hf hxy) @[to_additive] lemma monotone_on.inv (hf : monotone_on f s) : antitone_on (λ x, (f x)⁻¹) s := λ x hx y hy hxy, inv_le_inv_iff.2 (hf hx hy hxy) @[to_additive] lemma antitone_on.inv (hf : antitone_on f s) : monotone_on (λ x, (f x)⁻¹) s := λ x hx y hy hxy, inv_le_inv_iff.2 (hf hx hy hxy) end section variables {β : Type*} [group α] [preorder α] [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] [preorder β] {f : β → α} {s : set β} @[to_additive] lemma strict_mono.inv (hf : strict_mono f) : strict_anti (λ x, (f x)⁻¹) := λ x y hxy, inv_lt_inv_iff.2 (hf hxy) @[to_additive] lemma strict_anti.inv (hf : strict_anti f) : strict_mono (λ x, (f x)⁻¹) := λ x y hxy, inv_lt_inv_iff.2 (hf hxy) @[to_additive] lemma strict_mono_on.inv (hf : strict_mono_on f s) : strict_anti_on (λ x, (f x)⁻¹) s := λ x hx y hy hxy, inv_lt_inv_iff.2 (hf hx hy hxy) @[to_additive] lemma strict_anti_on.inv (hf : strict_anti_on f s) : strict_mono_on (λ x, (f x)⁻¹) s := λ x hx y hy hxy, inv_lt_inv_iff.2 (hf hx hy hxy) end
79a5716a57cda6e77b529c4a0dee2d3026ebbc6a
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/free.lean
6c409137ac68b4b78544e154ad85cac12015761a
[ "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
22,576
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.equiv.basic import control.applicative import control.traversable.basic /-! # Free constructions ## Main definitions * `free_magma α`: free magma (structure with binary operation without any axioms) over alphabet `α`, defined inductively, with traversable instance and decidable equality. * `magma.free_semigroup α`: free semigroup over magma `α`. * `free_semigroup α`: free semigroup over alphabet `α`, defined as a synonym for `α × list α` (i.e. nonempty lists), with traversable instance and decidable equality. * `free_semigroup_free_magma α`: isomorphism between `magma.free_semigroup (free_magma α)` and `free_semigroup α`. -/ universes u v l /-- Free magma over a given alphabet. -/ @[derive decidable_eq] inductive free_magma (α : Type u) : Type u | of : α → free_magma | mul : free_magma → free_magma → free_magma /-- Free nonabelian additive magma over a given alphabet. -/ @[derive decidable_eq] inductive free_add_magma (α : Type u) : Type u | of : α → free_add_magma | add : free_add_magma → free_add_magma → free_add_magma attribute [to_additive] free_magma namespace free_magma variables {α : Type u} @[to_additive] instance [inhabited α] : inhabited (free_magma α) := ⟨of (default _)⟩ @[to_additive] instance : has_mul (free_magma α) := ⟨free_magma.mul⟩ attribute [pattern] has_mul.mul @[simp, to_additive] theorem mul_eq (x y : free_magma α) : mul x y = x * y := rfl /-- Recursor for `free_magma` using `x * y` instead of `free_magma.mul x y`. -/ @[to_additive "Recursor for `free_add_magma` using `x + y` instead of `free_add_magma.add x y`."] def rec_on' {C : free_magma α → Sort l} (x) (ih1 : ∀ x, C (of x)) (ih2 : ∀ x y, C x → C y → C (x * y)) : C x := free_magma.rec_on x ih1 ih2 attribute [elab_as_eliminator] rec_on' free_add_magma.rec_on' end free_magma /-- Lifts a function `α → β` to a magma homomorphism `free_magma α → β` given a magma `β`. -/ def free_magma.lift {α : Type u} {β : Type v} [has_mul β] (f : α → β) : free_magma α → β | (free_magma.of x) := f x | (x * y) := x.lift * y.lift /-- Lifts a function `α → β` to an additive magma homomorphism `free_add_magma α → β` given an additive magma `β`. -/ def free_add_magma.lift {α : Type u} {β : Type v} [has_add β] (f : α → β) : free_add_magma α → β | (free_add_magma.of x) := f x | (x + y) := x.lift + y.lift attribute [to_additive free_add_magma.lift] free_magma.lift namespace free_magma variables {α : Type u} {β : Type v} [has_mul β] (f : α → β) @[simp, to_additive] lemma lift_of (x) : lift f (of x) = f x := rfl @[simp, to_additive] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := rfl @[to_additive] theorem lift_unique (f : free_magma α → β) (hf : ∀ x y, f (x * y) = f x * f y) : f = lift (f ∘ of) := funext $ λ x, free_magma.rec_on x (λ x, rfl) $ λ x y ih1 ih2, (hf x y).trans $ congr (congr_arg _ ih1) ih2 end free_magma /-- The unique magma homomorphism `free_magma α → free_magma β` that sends each `of x` to `of (f x)`. -/ def free_magma.map {α : Type u} {β : Type v} (f : α → β) : free_magma α → free_magma β | (free_magma.of x) := free_magma.of (f x) | (x * y) := x.map * y.map /-- The unique additive magma homomorphism `free_add_magma α → free_add_magma β` that sends each `of x` to `of (f x)`. -/ def free_add_magma.map {α : Type u} {β : Type v} (f : α → β) : free_add_magma α → free_add_magma β | (free_add_magma.of x) := free_add_magma.of (f x) | (x + y) := x.map + y.map attribute [to_additive free_add_magma.map] free_magma.map namespace free_magma variables {α : Type u} section map variables {β : Type v} (f : α → β) @[simp, to_additive] lemma map_of (x) : map f (of x) = of (f x) := rfl @[simp, to_additive] lemma map_mul (x y) : map f (x * y) = map f x * map f y := rfl end map section category @[to_additive] instance : monad free_magma := { pure := λ _, of, bind := λ _ _ x f, lift f x } /-- Recursor on `free_magma` using `pure` instead of `of`. -/ @[elab_as_eliminator, to_additive "Recursor on `free_add_magma` using `pure` instead of `of`."] protected def rec_on'' {C : free_magma α → Sort l} (x) (ih1 : ∀ x, C (pure x)) (ih2 : ∀ x y, C x → C y → C (x * y)) : C x := free_magma.rec_on' x ih1 ih2 variables {β : Type u} @[simp, to_additive] lemma map_pure (f : α → β) (x) : (f <$> pure x : free_magma β) = pure (f x) := rfl @[simp, to_additive] lemma map_mul' (f : α → β) (x y : free_magma α) : (f <$> (x * y)) = (f <$> x * f <$> y) := rfl @[simp, to_additive] lemma pure_bind (f : α → free_magma β) (x) : (pure x >>= f) = f x := rfl @[simp, to_additive] lemma mul_bind (f : α → free_magma β) (x y : free_magma α) : (x * y >>= f) = ((x >>= f) * (y >>= f)) := rfl @[simp, to_additive] lemma pure_seq {α β : Type u} {f : α → β} {x : free_magma α} : pure f <*> x = f <$> x := rfl @[simp, to_additive] lemma mul_seq {α β : Type u} {f g : free_magma (α → β)} {x : free_magma α} : (f * g) <*> x = (f <*> x) * (g <*> x) := rfl @[to_additive] instance : is_lawful_monad free_magma.{u} := { pure_bind := λ _ _ _ _, rfl, bind_assoc := λ α β γ x f g, free_magma.rec_on'' x (λ x, rfl) (λ x y ih1 ih2, by rw [mul_bind, mul_bind, mul_bind, ih1, ih2]), id_map := λ α x, free_magma.rec_on'' x (λ _, rfl) (λ x y ih1 ih2, by rw [map_mul', ih1, ih2]) } end category end free_magma /-- `free_magma` is traversable. -/ protected def free_magma.traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) : free_magma α → m (free_magma β) | (free_magma.of x) := free_magma.of <$> F x | (x * y) := (*) <$> x.traverse <*> y.traverse /-- `free_add_magma` is traversable. -/ protected def free_add_magma.traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) : free_add_magma α → m (free_add_magma β) | (free_add_magma.of x) := free_add_magma.of <$> F x | (x + y) := (+) <$> x.traverse <*> y.traverse attribute [to_additive free_add_magma.traverse] free_magma.traverse namespace free_magma variables {α : Type u} section category variables {β : Type u} @[to_additive] instance : traversable free_magma := ⟨@free_magma.traverse⟩ variables {m : Type u → Type u} [applicative m] (F : α → m β) @[simp, to_additive] lemma traverse_pure (x) : traverse F (pure x : free_magma α) = pure <$> F x := rfl @[simp, to_additive] lemma traverse_pure' : traverse F ∘ pure = λ x, (pure <$> F x : m (free_magma β)) := rfl @[simp, to_additive] lemma traverse_mul (x y : free_magma α) : traverse F (x * y) = (*) <$> traverse F x <*> traverse F y := rfl @[simp, to_additive] lemma traverse_mul' : function.comp (traverse F) ∘ @has_mul.mul (free_magma α) _ = λ x y, (*) <$> traverse F x <*> traverse F y := rfl @[simp, to_additive] lemma traverse_eq (x) : free_magma.traverse F x = traverse F x := rfl @[simp, to_additive] lemma mul_map_seq (x y : free_magma α) : ((*) <$> x <*> y : id (free_magma α)) = (x * y : free_magma α) := rfl @[to_additive] instance : is_lawful_traversable free_magma.{u} := { id_traverse := λ α x, free_magma.rec_on'' x (λ x, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, mul_map_seq]), comp_traverse := λ F G hf1 hg1 hf2 hg2 α β γ f g x, free_magma.rec_on'' x (λ x, by resetI; simp only [traverse_pure, traverse_pure'] with functor_norm) (λ x y ih1 ih2, by resetI; rw [traverse_mul, ih1, ih2, traverse_mul]; simp only [traverse_mul'] with functor_norm), naturality := λ F G hf1 hg1 hf2 hg2 η α β f x, free_magma.rec_on'' x (λ x, by simp only [traverse_pure] with functor_norm) (λ x y ih1 ih2, by simp only [traverse_mul] with functor_norm; rw [ih1, ih2]), traverse_eq_map_id := λ α β f x, free_magma.rec_on'' x (λ _, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, map_mul', mul_map_seq]; refl), .. free_magma.is_lawful_monad } end category end free_magma /-- Representation of an element of a free magma. -/ protected def free_magma.repr {α : Type u} [has_repr α] : free_magma α → string | (free_magma.of x) := repr x | (x * y) := "( " ++ x.repr ++ " * " ++ y.repr ++ " )" /-- Representation of an element of a free additive magma. -/ protected def free_add_magma.repr {α : Type u} [has_repr α] : free_add_magma α → string | (free_add_magma.of x) := repr x | (x + y) := "( " ++ x.repr ++ " + " ++ y.repr ++ " )" attribute [to_additive free_add_magma.repr] free_magma.repr @[to_additive] instance {α : Type u} [has_repr α] : has_repr (free_magma α) := ⟨free_magma.repr⟩ /-- Length of an element of a free magma. -/ def free_magma.length {α : Type u} : free_magma α → ℕ | (free_magma.of x) := 1 | (x * y) := x.length + y.length /-- Length of an element of a free additive magma. -/ def free_add_magma.length {α : Type u} : free_add_magma α → ℕ | (free_add_magma.of x) := 1 | (x + y) := x.length + y.length attribute [to_additive free_add_magma.length] free_magma.length /-- Associativity relations for a magma. -/ inductive magma.free_semigroup.r (α : Type u) [has_mul α] : α → α → Prop | intro : ∀ x y z, magma.free_semigroup.r ((x * y) * z) (x * (y * z)) | left : ∀ w x y z, magma.free_semigroup.r (w * ((x * y) * z)) (w * (x * (y * z))) /-- Associativity relations for an additive magma. -/ inductive add_magma.free_add_semigroup.r (α : Type u) [has_add α] : α → α → Prop | intro : ∀ x y z, add_magma.free_add_semigroup.r ((x + y) + z) (x + (y + z)) | left : ∀ w x y z, add_magma.free_add_semigroup.r (w + ((x + y) + z)) (w + (x + (y + z))) attribute [to_additive add_magma.free_add_semigroup.r] magma.free_semigroup.r namespace magma /-- Free semigroup over a magma. -/ @[to_additive add_magma.free_add_semigroup "Free additive semigroup over an additive magma."] def free_semigroup (α : Type u) [has_mul α] : Type u := quot $ free_semigroup.r α namespace free_semigroup variables {α : Type u} [has_mul α] /-- Embedding from magma to its free semigroup. -/ @[to_additive "Embedding from additive magma to its free additive semigroup."] def of : α → free_semigroup α := quot.mk _ @[to_additive] instance [inhabited α] : inhabited (free_semigroup α) := ⟨of (default _)⟩ @[elab_as_eliminator, to_additive] protected lemma induction_on {C : free_semigroup α → Prop} (x : free_semigroup α) (ih : ∀ x, C (of x)) : C x := quot.induction_on x ih @[to_additive] theorem of_mul_assoc (x y z : α) : of ((x * y) * z) = of (x * (y * z)) := quot.sound $ r.intro x y z @[to_additive] theorem of_mul_assoc_left (w x y z : α) : of (w * ((x * y) * z)) = of (w * (x * (y * z))) := quot.sound $ r.left w x y z @[to_additive] theorem of_mul_assoc_right (w x y z : α) : of (((w * x) * y) * z) = of ((w * (x * y)) * z) := by rw [of_mul_assoc, of_mul_assoc, of_mul_assoc, of_mul_assoc_left] @[to_additive] instance : semigroup (free_semigroup α) := { mul := λ x y, begin refine quot.lift_on x (λ p, quot.lift_on y (λ q, (quot.mk _ $ p * q : free_semigroup α)) _) _, { rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); change of _ = of _, { rw of_mul_assoc_left }, { rw [← of_mul_assoc, of_mul_assoc_left, of_mul_assoc] } }, { refine quot.induction_on y (λ q, _), rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); change of _ = of _, { rw of_mul_assoc_right }, { rw [of_mul_assoc, of_mul_assoc, of_mul_assoc_left, of_mul_assoc_left, of_mul_assoc_left, ← of_mul_assoc c d, ← of_mul_assoc c d, of_mul_assoc_left] } } end, mul_assoc := λ x y z, quot.induction_on x $ λ p, quot.induction_on y $ λ q, quot.induction_on z $ λ r, of_mul_assoc p q r } @[to_additive] theorem of_mul (x y : α) : of (x * y) = of x * of y := rfl section lift variables {β : Type v} [semigroup β] (f : α → β) /-- Lifts a magma homomorphism `α → β` to a semigroup homomorphism `magma.free_semigroup α → β` given a semigroup `β`. -/ @[to_additive "Lifts an additive magma homomorphism `α → β` to an additive semigroup homomorphism `add_magma.free_add_semigroup α → β` given an additive semigroup `β`."] def lift (hf : ∀ x y, f (x * y) = f x * f y) : free_semigroup α → β := quot.lift f $ by rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); simp only [hf, mul_assoc] @[simp, to_additive] lemma lift_of {hf} (x : α) : lift f hf (of x) = f x := rfl @[simp, to_additive] lemma lift_mul {hf} (x y) : lift f hf (x * y) = lift f hf x * lift f hf y := quot.induction_on x $ λ p, quot.induction_on y $ λ q, hf p q @[to_additive] theorem lift_unique (f : free_semigroup α → β) (hf : ∀ x y, f (x * y) = f x * f y) : f = lift (f ∘ of) (λ p q, hf (of p) (of q)) := funext $ λ x, quot.induction_on x $ λ p, rfl end lift variables {β : Type v} [has_mul β] (f : α → β) /-- From a magma homomorphism `α → β` to a semigroup homomorphism `magma.free_semigroup α → magma.free_semigroup β`. -/ @[to_additive "From an additive magma homomorphism `α → β` to an additive semigroup homomorphism `add_magma.free_add_semigroup α → add_magma.free_add_semigroup β`."] def map (hf : ∀ x y, f (x * y) = f x * f y) : free_semigroup α → free_semigroup β := lift (of ∘ f) (λ x y, congr_arg of $ hf x y) @[simp, to_additive] lemma map_of {hf} (x) : map f hf (of x) = of (f x) := rfl @[simp, to_additive] lemma map_mul {hf} (x y) : map f hf (x * y) = map f hf x * map f hf y := lift_mul _ _ _ end free_semigroup end magma /-- Free semigroup over a given alphabet. (Note: In this definition, the free semigroup does not contain the empty word.) -/ @[to_additive "Free additive semigroup over a given alphabet."] def free_semigroup (α : Type u) : Type u := α × list α namespace free_semigroup variables {α : Type u} @[to_additive] instance : semigroup (free_semigroup α) := { mul := λ L1 L2, (L1.1, L1.2 ++ L2.1 :: L2.2), mul_assoc := λ L1 L2 L3, prod.ext rfl $ list.append_assoc _ _ _ } /-- The embedding `α → free_semigroup α`. -/ @[to_additive "The embedding `α → free_add_semigroup α`."] def of (x : α) : free_semigroup α := (x, []) @[to_additive] instance [inhabited α] : inhabited (free_semigroup α) := ⟨of (default _)⟩ /-- Recursor for free semigroup using `of` and `*`. -/ @[elab_as_eliminator, to_additive "Recursor for free additive semigroup using `of` and `+`."] protected def rec_on {C : free_semigroup α → Sort l} (x) (ih1 : ∀ x, C (of x)) (ih2 : ∀ x y, C (of x) → C y → C (of x * y)) : C x := prod.rec_on x $ λ f s, list.rec_on s ih1 (λ hd tl ih f, ih2 f (hd, tl) (ih1 f) (ih hd)) f end free_semigroup /-- Auxiliary function for `free_semigroup.lift`. -/ def free_semigroup.lift' {α : Type u} {β : Type v} [semigroup β] (f : α → β) : α → list α → β | x [] := f x | x (hd::tl) := f x * free_semigroup.lift' hd tl /-- Auxiliary function for `free_semigroup.lift`. -/ def free_add_semigroup.lift' {α : Type u} {β : Type v} [add_semigroup β] (f : α → β) : α → list α → β | x [] := f x | x (hd::tl) := f x + free_add_semigroup.lift' hd tl attribute [to_additive free_add_semigroup.lift'] free_semigroup.lift' namespace free_semigroup variables {α : Type u} section lift variables {β : Type v} [semigroup β] (f : α → β) /-- Lifts a function `α → β` to a semigroup homomorphism `free_semigroup α → β` given a semigroup `β`. -/ @[to_additive "Lifts a function `α → β` to an additive semigroup homomorphism `free_add_semigroup α → β` given an additive semigroup `β`."] def lift (x : free_semigroup α) : β := lift' f x.1 x.2 @[simp, to_additive] lemma lift_of (x : α) : lift f (of x) = f x := rfl @[to_additive] lemma lift_of_mul (x y) : lift f (of x * y) = f x * lift f y := rfl @[simp, to_additive] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := free_semigroup.rec_on x (λ p, rfl) (λ p x ih1 ih2, by rw [mul_assoc, lift_of_mul, lift_of_mul, mul_assoc, ih2]) @[to_additive] theorem lift_unique (f : free_semigroup α → β) (hf : ∀ x y, f (x * y) = f x * f y) : f = lift (f ∘ of) := funext $ λ ⟨x, L⟩, list.rec_on L (λ x, rfl) (λ hd tl ih x, (hf (of x) (hd, tl)).trans $ congr_arg _ $ ih _) x end lift section map variables {β : Type v} (f : α → β) /-- The unique semigroup homomorphism that sends `of x` to `of (f x)`. -/ @[to_additive "The unique additive semigroup homomorphism that sends `of x` to `of (f x)`."] def map : free_semigroup α → free_semigroup β := lift $ of ∘ f @[simp, to_additive] lemma map_of (x) : map f (of x) = of (f x) := rfl @[simp, to_additive] lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ end map section category variables {β : Type u} @[to_additive] instance : monad free_semigroup := { pure := λ _, of, bind := λ _ _ x f, lift f x } /-- Recursor that uses `pure` instead of `of`. -/ @[elab_as_eliminator, to_additive "Recursor that uses `pure` instead of `of`."] def rec_on' {C : free_semigroup α → Sort l} (x) (ih1 : ∀ x, C (pure x)) (ih2 : ∀ x y, C (pure x) → C y → C (pure x * y)) : C x := free_semigroup.rec_on x ih1 ih2 @[simp, to_additive] lemma map_pure (f : α → β) (x) : (f <$> pure x : free_semigroup β) = pure (f x) := rfl @[simp, to_additive] lemma map_mul' (f : α → β) (x y : free_semigroup α) : (f <$> (x * y)) = (f <$> x * f <$> y) := map_mul _ _ _ @[simp, to_additive] lemma pure_bind (f : α → free_semigroup β) (x) : (pure x >>= f) = f x := rfl @[simp, to_additive] lemma mul_bind (f : α → free_semigroup β) (x y : free_semigroup α) : (x * y >>= f) = ((x >>= f) * (y >>= f)) := lift_mul _ _ _ @[simp, to_additive] lemma pure_seq {f : α → β} {x : free_semigroup α} : pure f <*> x = f <$> x := rfl @[simp, to_additive] lemma mul_seq {f g : free_semigroup (α → β)} {x : free_semigroup α} : (f * g) <*> x = (f <*> x) * (g <*> x) := mul_bind _ _ _ @[to_additive] instance : is_lawful_monad free_semigroup.{u} := { pure_bind := λ _ _ _ _, rfl, bind_assoc := λ α β γ x f g, rec_on' x (λ x, rfl) (λ x y ih1 ih2, by rw [mul_bind, mul_bind, mul_bind, ih1, ih2]), id_map := λ α x, rec_on' x (λ _, rfl) (λ x y ih1 ih2, by rw [map_mul', ih1, ih2]) } /-- `free_semigroup` is traversable. -/ @[to_additive "`free_add_semigroup` is traversable."] protected def traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) (x : free_semigroup α) : m (free_semigroup β) := rec_on' x (λ x, pure <$> F x) (λ x y ihx ihy, (*) <$> ihx <*> ihy) @[to_additive] instance : traversable free_semigroup := ⟨@free_semigroup.traverse⟩ variables {m : Type u → Type u} [applicative m] (F : α → m β) @[simp, to_additive] lemma traverse_pure (x) :traverse F (pure x : free_semigroup α) = pure <$> F x := rfl @[simp, to_additive] lemma traverse_pure' : traverse F ∘ pure = λ x, (pure <$> F x : m (free_semigroup β)) := rfl section variables [is_lawful_applicative m] @[simp, to_additive] lemma traverse_mul (x y : free_semigroup α) : traverse F (x * y) = (*) <$> traverse F x <*> traverse F y := let ⟨x, L1⟩ := x, ⟨y, L2⟩ := y in list.rec_on L1 (λ x, rfl) (λ hd tl ih x, show (*) <$> pure <$> F x <*> traverse F ((hd, tl) * (y, L2) : free_semigroup α) = (*) <$> ((*) <$> pure <$> F x <*> traverse F (hd, tl)) <*> traverse F (y, L2), by rw ih; simp only [(∘), (mul_assoc _ _ _).symm] with functor_norm) x @[simp, to_additive] lemma traverse_mul' : function.comp (traverse F) ∘ @has_mul.mul (free_semigroup α) _ = λ x y, (*) <$> traverse F x <*> traverse F y := funext $ λ x, funext $ λ y, traverse_mul F x y end @[simp, to_additive] lemma traverse_eq (x) : free_semigroup.traverse F x = traverse F x := rfl @[simp, to_additive] lemma mul_map_seq (x y : free_semigroup α) : ((*) <$> x <*> y : id (free_semigroup α)) = (x * y : free_semigroup α) := rfl @[to_additive] instance : is_lawful_traversable free_semigroup.{u} := { id_traverse := λ α x, free_semigroup.rec_on x (λ x, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, mul_map_seq]), comp_traverse := λ F G hf1 hg1 hf2 hg2 α β γ f g x, rec_on' x (λ x, by resetI; simp only [traverse_pure, traverse_pure'] with functor_norm) (λ x y ih1 ih2, by resetI; rw [traverse_mul, ih1, ih2, traverse_mul]; simp only [traverse_mul'] with functor_norm), naturality := λ F G hf1 hg1 hf2 hg2 η α β f x, rec_on' x (λ x, by simp only [traverse_pure] with functor_norm) (λ x y ih1 ih2, by resetI; simp only [traverse_mul] with functor_norm; rw [ih1, ih2]), traverse_eq_map_id := λ α β f x, free_semigroup.rec_on x (λ _, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, map_mul', mul_map_seq]; refl), .. free_semigroup.is_lawful_monad } end category @[to_additive] instance [decidable_eq α] : decidable_eq (free_semigroup α) := prod.decidable_eq end free_semigroup /-- Isomorphism between `magma.free_semigroup (free_magma α)` and `free_semigroup α`. -/ @[to_additive "Isomorphism between `add_magma.free_add_semigroup (free_add_magma α)` and `free_add_semigroup α`."] def free_semigroup_free_magma (α : Type u) : magma.free_semigroup (free_magma α) ≃ free_semigroup α := { to_fun := magma.free_semigroup.lift (free_magma.lift free_semigroup.of) (free_magma.lift_mul _), inv_fun := free_semigroup.lift (magma.free_semigroup.of ∘ free_magma.of), left_inv := λ x, magma.free_semigroup.induction_on x $ λ p, by rw magma.free_semigroup.lift_of; exact free_magma.rec_on' p (λ x, by rw [free_magma.lift_of, free_semigroup.lift_of]) (λ x y ihx ihy, by rw [free_magma.lift_mul, free_semigroup.lift_mul, ihx, ihy, magma.free_semigroup.of_mul]), right_inv := λ x, free_semigroup.rec_on x (λ x, by rw [free_semigroup.lift_of, magma.free_semigroup.lift_of, free_magma.lift_of]) (λ x y ihx ihy, by rw [free_semigroup.lift_mul, magma.free_semigroup.lift_mul, ihx, ihy]) } @[simp, to_additive] lemma free_semigroup_free_magma_mul {α : Type u} (x y) : free_semigroup_free_magma α (x * y) = free_semigroup_free_magma α x * free_semigroup_free_magma α y := magma.free_semigroup.lift_mul _ _ _
996e9a4cef05b08db7a702317d9cb25d65bacab2
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/rewriter1.lean
009782810261e3da536e458a587e0e4e8fbd3e91
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
195
lean
import data.nat open algebra theorem test {A : Type} [s : comm_ring A] (a b c : A) : a + b + c = a + c + b := begin rewrite [add.assoc, {b + _}add.comm, -add.assoc] end print definition test
2d6a15095f03551158edf74c92474634e0347f2c
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/geometry/euclidean/basic.lean
9730bb4b92567f61cc1e0f4b115958cc26596533
[ "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
45,200
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import analysis.normed_space.inner_product import algebra.quadratic_discriminant import analysis.normed_space.add_torsor import data.matrix.notation import linear_algebra.affine_space.finite_dimensional import tactic.fin_cases noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space /-! # Euclidean spaces This file makes some definitions and proves very basic geometrical results about real inner product spaces and Euclidean affine spaces. Results about real inner product spaces that involve the norm and inner product but not angles generally go in `analysis.normed_space.inner_product`. Results with longer proofs or more geometrical content generally go in separate files. ## Main definitions * `inner_product_geometry.angle` is the undirected angle between two vectors. * `euclidean_geometry.angle`, with notation `∠`, is the undirected angle determined by three points. * `euclidean_geometry.orthogonal_projection` is the orthogonal projection of a point onto an affine subspace. * `euclidean_geometry.reflection` is the reflection of a point in an affine subspace. ## Implementation notes To declare `P` as the type of points in a Euclidean affine space with `V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]`. This works better with `out_param` to make `V` implicit in most cases than having a separate type alias for Euclidean affine spaces. Rather than requiring Euclidean affine spaces to be finite-dimensional (as in the definition on Wikipedia), this is specified only for those theorems that need it. ## References * https://en.wikipedia.org/wiki/Euclidean_space -/ namespace inner_product_geometry /-! ### Geometrical results on real inner product spaces This section develops some geometrical definitions and results on real inner product spaces, where those definitions and results can most conveniently be developed in terms of vectors and then used to deduce corresponding results for Euclidean affine spaces. -/ variables {V : Type*} [inner_product_space ℝ V] /-- The undirected angle between two vectors. If either vector is 0, this is π/2. -/ def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥)) /-- The cosine of the angle between two vectors. -/ lemma cos_angle (x y : V) : real.cos (angle x y) = inner x y / (∥x∥ * ∥y∥) := real.cos_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 /-- The angle between two vectors does not depend on their order. -/ lemma angle_comm (x y : V) : angle x y = angle y x := begin unfold angle, rw [real_inner_comm, mul_comm] end /-- The angle between the negation of two vectors. -/ @[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y := begin unfold angle, rw [inner_neg_neg, norm_neg, norm_neg] end /-- The angle between two vectors is nonnegative. -/ lemma angle_nonneg (x y : V) : 0 ≤ angle x y := real.arccos_nonneg _ /-- The angle between two vectors is at most π. -/ lemma angle_le_pi (x y : V) : angle x y ≤ π := real.arccos_le_pi _ /-- The angle between a vector and the negation of another vector. -/ lemma angle_neg_right (x y : V) : angle x (-y) = π - angle x y := begin unfold angle, rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div] end /-- The angle between the negation of a vector and another vector. -/ lemma angle_neg_left (x y : V) : angle (-x) y = π - angle x y := by rw [←angle_neg_neg, neg_neg, angle_neg_right] /-- The angle between the zero vector and a vector. -/ @[simp] lemma angle_zero_left (x : V) : angle 0 x = π / 2 := begin unfold angle, rw [inner_zero_left, zero_div, real.arccos_zero] end /-- The angle between a vector and the zero vector. -/ @[simp] lemma angle_zero_right (x : V) : angle x 0 = π / 2 := begin unfold angle, rw [inner_zero_right, zero_div, real.arccos_zero] end /-- The angle between a nonzero vector and itself. -/ @[simp] lemma angle_self {x : V} (hx : x ≠ 0) : angle x x = 0 := begin unfold angle, rw [←real_inner_self_eq_norm_square, div_self (λ h, hx (inner_self_eq_zero.1 h)), real.arccos_one] end /-- The angle between a nonzero vector and its negation. -/ @[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x ≠ 0) : angle x (-x) = π := by rw [angle_neg_right, angle_self hx, sub_zero] /-- The angle between the negation of a nonzero vector and that vector. -/ @[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x ≠ 0) : angle (-x) x = π := by rw [angle_comm, angle_self_neg_of_nonzero hx] /-- The angle between a vector and a positive multiple of a vector. -/ @[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle x (r • y) = angle x y := begin unfold angle, rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc, mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)] end /-- The angle between a positive multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle (r • x) y = angle x y := by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm] /-- The angle between a vector and a negative multiple of a vector. -/ @[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle x (r • y) = angle x (-y) := by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr), angle_neg_right] /-- The angle between a negative multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle (r • x) y = angle (-x) y := by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm] /-- The cosine of the angle between two vectors, multiplied by the product of their norms. -/ lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (∥x∥ * ∥y∥) = inner x y := begin rw [cos_angle, div_mul_cancel_of_imp], simp [or_imp_distrib] { contextual := tt }, end /-- The sine of the angle between two vectors, multiplied by the product of their norms. -/ lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (∥x∥ * ∥y∥) = real.sqrt (inner x x * inner y y - inner x y * inner x y) := begin unfold angle, rw [real.sin_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2, ←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), ←real.sqrt_mul' _ (mul_self_nonneg _), pow_two, real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), real_inner_self_eq_norm_square, real_inner_self_eq_norm_square], by_cases h : (∥x∥ * ∥y∥) = 0, { rw [(show ∥x∥ * ∥x∥ * (∥y∥ * ∥y∥) = (∥x∥ * ∥y∥) * (∥x∥ * ∥y∥), by ring), h, mul_zero, mul_zero, zero_sub], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left, zero_mul, neg_zero] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right, zero_mul, neg_zero] } }, { field_simp [h], ring } end /-- The angle between two vectors is zero if and only if they are nonzero and one is a positive multiple of the other. -/ lemma angle_eq_zero_iff {x y : V} : angle x y = 0 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin rw [angle, ← real_inner_div_norm_mul_norm_eq_one_iff, real.arccos_eq_zero, has_le.le.le_iff_eq, eq_comm], exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 end /-- The angle between two vectors is π if and only if they are nonzero and one is a negative multiple of the other. -/ lemma angle_eq_pi_iff {x y : V} : angle x y = π ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin rw [angle, ← real_inner_div_norm_mul_norm_eq_neg_one_iff, real.arccos_eq_pi, has_le.le.le_iff_eq], exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 end /-- If the angle between two vectors is π, the angles between those vectors and a third vector add to π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = π) : angle x z + angle y z = π := begin rcases angle_eq_pi_iff.1 h with ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩, rw [angle_smul_left_of_neg x z hr, angle_neg_left, add_sub_cancel'_right] end /-- Two vectors have inner product 0 if and only if the angle between them is π/2. -/ lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : ⟪x, y⟫ = 0 ↔ angle x y = π / 2 := iff.symm $ by simp [angle, or_imp_distrib] { contextual := tt } end inner_product_geometry namespace euclidean_geometry /-! ### Geometrical results on Euclidean affine spaces This section develops some geometrical definitions and results on Euclidean affine spaces. -/ open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] local notation `⟪`x`, `y`⟫` := @inner ℝ V _ x y include V /-- The undirected angle at `p2` between the line segments to `p1` and `p3`. If either of those points equals `p2`, this is π/2. Use `open_locale euclidean_geometry` to access the `∠ p1 p2 p3` notation. -/ def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2) localized "notation `∠` := euclidean_geometry.angle" in euclidean_geometry /-- The angle at a point does not depend on the order of the other two points. -/ lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 := angle_comm _ _ /-- The angle at a point is nonnegative. -/ lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 := angle_nonneg _ _ /-- The angle at a point is at most π. -/ lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π := angle_le_pi _ _ /-- The angle ∠AAB at a point. -/ lemma angle_eq_left (p1 p2 : P) : ∠ p1 p1 p2 = π / 2 := begin unfold angle, rw vsub_self, exact angle_zero_left _ end /-- The angle ∠ABB at a point. -/ lemma angle_eq_right (p1 p2 : P) : ∠ p1 p2 p2 = π / 2 := by rw [angle_comm, angle_eq_left] /-- The angle ∠ABA at a point. -/ lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ p1 p2 p1 = 0 := angle_self (λ he, h (vsub_eq_zero_iff_eq.1 he)) /-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p1 p3 = 0 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, rw angle_eq_zero_iff, rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2, use [hp1p2, -r + 1, add_pos (neg_pos_of_neg hr) zero_lt_one], rw [add_smul, ←neg_vsub_eq_vsub_rev p1 p2, smul_neg], simp [←hpr] end /-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p3 p1 = 0 := begin rw angle_comm at h, exact angle_eq_zero_of_angle_eq_pi_left h end /-- If ∠BCD = π, then ∠ABC = ∠ABD. -/ lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p2 p3 = ∠ p1 p2 p4 := begin unfold angle at *, rcases angle_eq_pi_iff.1 h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩, rw [eq_comm], convert angle_smul_right_of_pos (p1 -ᵥ p2) (p3 -ᵥ p2) (add_pos (neg_pos_of_neg hr) zero_lt_one), rw [add_smul, ← neg_vsub_eq_vsub_rev p2 p3, smul_neg, neg_smul, ← hpr], simp end /-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p3 p2 + ∠ p1 p3 p4 = π := begin unfold angle at h, rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4], unfold angle, exact angle_add_angle_eq_pi_of_angle_eq_pi _ h end /-- The inner product of two vectors given with `weighted_vsub`, in terms of the pairwise distances. -/ lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P) (h₂ : ∑ i in s₂, w₂ i = 0) : inner (s₁.weighted_vsub p₁ w₁) (s₂.weighted_vsub p₂ w₂) = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 := begin rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply, inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂], simp_rw [vsub_sub_vsub_cancel_right], rcongr i₁ i₂; rw dist_eq_norm_vsub V (p₁ i₁) (p₂ i₂) end /-- The distance between two points given with `affine_combination`, in terms of the pairwise distances between the points in that combination. -/ lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P) (h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) : dist (s.affine_combination p w₁) (s.affine_combination p w₂) * dist (s.affine_combination p w₁) (s.affine_combination p w₂) = (-∑ i₁ in s, ∑ i₂ in s, (w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 := begin rw [dist_eq_norm_vsub V (s.affine_combination p w₁) (s.affine_combination p w₂), ←inner_self_eq_norm_square, finset.affine_combination_vsub], have h : ∑ i in s, (w₁ - w₂) i = 0, { simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] }, exact inner_weighted_vsub p h p h end /-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal to that between `p₁` and `p₂`. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁) (hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := begin have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0, { conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁, skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ }, rw [←add_sub_comm, inner_sub_left], conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂, skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ }, rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁, dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂, simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add, neg_add_eq_sub, hc₁, hc₂, sub_zero] }, simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h end /-- The squared distance between points on a line (expressed as a multiple of a fixed vector added to a point) and another point, expressed as a quadratic. -/ lemma dist_smul_vadd_square (r : ℝ) (v : V) (p₁ p₂ : P) : dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ = ⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ := begin rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_square, vadd_vsub_assoc, real_inner_add_add_self, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right], ring end /-- The condition for two points on a line to be equidistant from another point. -/ lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) : dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) := begin conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_square, ←sub_eq_zero_iff_eq, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂, ←real_inner_self_eq_norm_square, sub_self] }, have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv, have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 = (2 * inner v (p₁ -ᵥ p₂)) * (2 * inner v (p₁ -ᵥ p₂)), { rw discrim, ring }, rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul, ←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc, mul_div_mul_left, mul_div_assoc], norm_num end open affine_subspace finite_dimensional /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in a two-dimensional subspace containing those points (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_mem_of_findim_eq_two {s : affine_subspace ℝ P} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P} (hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (by cc) (by cc), have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (by cc) (by cc), let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁], have hb : linear_independent ℝ b, { refine linear_independent_of_ne_zero_of_inner_eq_zero _ _, { intro i, fin_cases i; simp [b, hc.symm, hp.symm] }, { intros i j hij, fin_cases i; fin_cases j; try { exact false.elim (hij rfl) }, { exact ho }, { rw real_inner_comm, exact ho } } }, have hbs : submodule.span ℝ (set.range b) = s.direction, { refine eq_of_le_of_findim_eq _ _, { rw [submodule.span_le, set.range_subset_iff], intro i, fin_cases i, { exact vsub_mem_direction hc₂s hc₁s }, { exact vsub_mem_direction hp₂s hp₁s } }, { rw [findim_span_eq_card hb, fintype.card_fin, hd] } }, have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁), { intros v hv, have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁}, { have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial, rw [←fintype.coe_image_univ, hu], simp, refl }, rw [←hbs, hr, submodule.mem_span_insert] at hv, rcases hv with ⟨t₁, v', hv', hv⟩, rw submodule.mem_span_singleton at hv', rcases hv' with ⟨t₂, rfl⟩, exact ⟨t₁, t₂, hv⟩ }, rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩, simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero, inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop, rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt, subst hpt, have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] }, have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] }, rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂, simp only [one_ne_zero, false_or] at hp₂, rw hp₂.symm at hpc₁, cases hpc₁; simp [hpc₁] end /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_findim_eq_two [finite_dimensional ℝ V] (hd : findim ℝ V = 2) {c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have hd' : findim ℝ (⊤ : affine_subspace ℝ P).direction = 2, { rw [direction_top, findim_top], exact hd }, exact eq_of_dist_eq_of_dist_eq_of_mem_of_findim_eq_two hd' (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂ end variables {V} /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : P := classical.some $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin convert submodule.is_compl_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›), exact direction_mk' p s.directionᗮ end /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection_fn` of that point onto the subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection_fn s p} := classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin convert submodule.is_compl_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›), exact direction_mk' p s.directionᗮ end /-- The `orthogonal_projection_fn` lies in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ s := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_left _ _ end /-- The `orthogonal_projection_fn` lies in the orthogonal subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ mk' p s.directionᗮ := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_right _ _ end /-- Subtracting `p` from its `orthogonal_projection_fn` produces a result in the orthogonal direction. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p -ᵥ p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal p) (self_mem_mk' _ _) /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete. The corresponding linear map (mapping a vector to the difference between the projections of two points whose difference is that vector) is the `orthogonal_projection` for real inner product spaces, onto the direction of the affine subspace being projected onto. -/ def orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P →ᵃ[ℝ] s := { to_fun := λ p, ⟨orthogonal_projection_fn s p, orthogonal_projection_fn_mem p⟩, linear := orthogonal_projection s.direction, map_vadd' := λ p v, begin have hs : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ s := vadd_mem_of_mem_direction (orthogonal_projection s.direction v).2 (orthogonal_projection_fn_mem p), have ho : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ mk' (v +ᵥ p) s.directionᗮ, { rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk', vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc], refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal p) _, rw submodule.mem_orthogonal', intros w hw, rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ w hw, neg_zero], }, have hm : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ ({orthogonal_projection_fn s (v +ᵥ p)} : set P), { rw ←inter_eq_singleton_orthogonal_projection_fn (v +ᵥ p), exact set.mem_inter hs ho }, rw set.mem_singleton_iff at hm, ext, exact hm.symm end } @[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p = orthogonal_projection s p := rfl /-- The linear map corresponding to `orthogonal_projection`. -/ @[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] : (orthogonal_projection s).linear = _root_.orthogonal_projection s.direction := rfl /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection` of that point onto the subspace. -/ lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection s p} := begin rw ←orthogonal_projection_fn_eq, exact inter_eq_singleton_orthogonal_projection_fn p end /-- The `orthogonal_projection` lies in the given subspace. -/ lemma orthogonal_projection_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ s := (orthogonal_projection s p).2 /-- The `orthogonal_projection` lies in the orthogonal subspace. -/ lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ mk' p s.directionᗮ := orthogonal_projection_fn_mem_orthogonal p /-- Subtracting a point in the given subspace from the `orthogonal_projection` produces a result in the direction of the given subspace. -/ lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction) ∈ s.direction := (orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction).2 /-- Subtracting the `orthogonal_projection` from a point in the given subspace produces a result in the direction of the given subspace. -/ lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction) ∈ s.direction := ((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction).2 /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : ↑(orthogonal_projection s p) = p ↔ p ∈ s := begin split, { exact λ h, h ▸ orthogonal_projection_mem p }, { intro h, have hp : p ∈ ((s : set P) ∩ mk' p s.directionᗮ) := ⟨h, self_mem_mk' p _⟩, rw [inter_eq_singleton_orthogonal_projection p] at hp, symmetry, exact hp } end /-- Orthogonal projection is idempotent. -/ @[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p := begin ext, rw orthogonal_projection_eq_self_iff, exact orthogonal_projection_mem p, end lemma eq_orthogonal_projection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (orthogonal_projection s p : P) = (orthogonal_projection s' p : P) := begin change orthogonal_projection_fn s p = orthogonal_projection_fn s' p, congr, exact h end /-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/ lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : dist p (orthogonal_projection s p) = 0 ↔ p ∈ s := by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff] /-- The distance between a point and its orthogonal projection is nonzero if it does not lie in the subspace. -/ lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∉ s) : dist p (orthogonal_projection s p) ≠ 0 := mt dist_orthogonal_projection_eq_zero_iff.mp hp /-- Subtracting `p` from its `orthogonal_projection` produces a result in the orthogonal direction. -/ lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : (orthogonal_projection s p : P) -ᵥ p ∈ s.directionᗮ := orthogonal_projection_fn_vsub_mem_direction_orthogonal p /-- Subtracting the `orthogonal_projection` from `p` produces a result in the orthogonal direction. -/ lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : p -ᵥ orthogonal_projection s p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p) /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector was in the orthogonal direction. -/ lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : orthogonal_projection s (v +ᵥ p) = ⟨p, hp⟩ := begin have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p), rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h, refine (eq_of_vsub_eq_zero _).symm, ext, refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h, exact (_ : s.direction).2 end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) : orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = ⟨p1, hp⟩ := orthogonal_projection_vadd_eq_self hp (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) /-- The square of the distance from a point in `s` to `p2` equals the sum of the squares of the distances of the two points to the `orthogonal_projection`. -/ lemma dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : dist p1 p2 * dist p1 p2 = dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) + dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) := begin rw [metric_space.dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2, norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero], exact submodule.inner_right_of_mem_orthogonal (vsub_orthogonal_projection_mem_direction p2 hp1) (orthogonal_projection_vsub_mem_direction_orthogonal s p2), end /-- The square of the distance between two points constructed by adding multiples of the same orthogonal vector to points in the same subspace. -/ lemma dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V} (hv : v ∈ s.directionᗮ) : dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) := calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ * ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ : by { rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul], abel } ... = ∥p1 -ᵥ p2∥ * ∥p1 -ᵥ p2∥ + ∥(r1 - r2) • v∥ * ∥(r1 - r2) • v∥ : norm_add_square_eq_norm_square_add_norm_square_real (submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2) (submodule.smul_mem _ _ hv)) ... = ∥(p1 -ᵥ p2 : V)∥ * ∥(p1 -ᵥ p2 : V)∥ + abs (r1 - r2) * abs (r1 - r2) * ∥v∥ * ∥v∥ : by { rw [norm_smul, real.norm_eq_abs], ring } ... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) : by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] } /-- Reflection in an affine subspace, which is expected to be nonempty and complete. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in an affine subspace, is a more general sense of the word that includes both those common cases. If the subspace is empty or not complete, `orthogonal_projection` is defined as the identity map, which results in `reflection` being the identity map in that case as well. -/ def reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P ≃ᵢ P := { to_fun := λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p, inv_fun := λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p, left_inv := λ p, by simp [vsub_vadd_eq_vsub_sub, -orthogonal_projection_linear], right_inv := λ p, by simp [vsub_vadd_eq_vsub_sub, -orthogonal_projection_linear], isometry_to_fun := begin dsimp only, rw isometry_emetric_iff_metric, intros p₁ p₂, rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_eq_norm_vsub V ((↑(orthogonal_projection s p₁) -ᵥ p₁) +ᵥ ↑(orthogonal_projection s p₁)), dist_eq_norm_vsub V p₁, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square], calc ⟪((orthogonal_projection s p₁ : P) -ᵥ p₁ +ᵥ (orthogonal_projection s p₁ : P) -ᵥ ((orthogonal_projection s p₂ : P) -ᵥ p₂ +ᵥ orthogonal_projection s p₂)), ((orthogonal_projection s p₁ : P) -ᵥ p₁ +ᵥ (orthogonal_projection s p₁ : P) -ᵥ ((orthogonal_projection s p₂ : P) -ᵥ p₂ +ᵥ orthogonal_projection s p₂))⟫ = ⟪(_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂)) + _root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) - (p₁ -ᵥ p₂), _root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) + _root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) - (p₁ -ᵥ p₂)⟫ : by { rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, ←vsub_vadd_eq_vsub_sub, vsub_vadd_comm, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, ←coe_vsub, ←affine_map.linear_map_vsub], simp } ... = -4 * inner (p₁ -ᵥ p₂ - (_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) : V)) (_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂)) + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ : by { simp [inner_sub_left, inner_sub_right, inner_add_left, inner_add_right, real_inner_comm (p₁ -ᵥ p₂)], ring } ... = ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ : by simp, end } /-- The result of reflecting. -/ lemma reflection_apply (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s p = (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p := rfl lemma eq_reflection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (reflection s p : P) = (reflection s' p : P) := by simp [reflection_apply, eq_orthogonal_projection_of_eq_subspace h] /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : (reflection s).symm = reflection s := rfl /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s (reflection s p) = p := (reflection s).left_inv p /-- Reflection is involutive. -/ lemma reflection_involutive (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : function.involutive (reflection s) := reflection_reflection s /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : reflection s p = p ↔ p ∈ s := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, ←two_smul ℝ (↑(orthogonal_projection s p) -ᵥ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, simp [h] } end /-- Reflecting a point in two subspaces produces the same result if and only if the point has the same orthogonal projection in each of those subspaces. -/ lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P) [nonempty s₁] [nonempty s₂] [complete_space s₁.direction] [complete_space s₂.direction] (p : P) : reflection s₁ p = reflection s₂ p ↔ (orthogonal_projection s₁ p : P) = orthogonal_projection s₂ p := begin rw [reflection_apply, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, vsub_sub_vsub_cancel_right, ←two_smul ℝ ((orthogonal_projection s₁ p : P) -ᵥ orthogonal_projection s₂ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, rw h } end /-- The distance between `p₁` and the reflection of `p₂` equals that between the reflection of `p₁` and `p₂`. -/ lemma dist_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p₁ p₂ : P) : dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ := begin conv_lhs { rw ←reflection_reflection s p₁ }, exact (reflection s).dist_eq _ _ end /-- A point in the subspace is equidistant from another point and its reflection. -/ lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] {p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) : dist p₁ (reflection s p₂) = dist p₁ p₂ := begin rw ←reflection_eq_self_iff p₁ at hp₁, convert (reflection s).dist_eq p₁ p₂, rw hp₁ end /-- The reflection of a point in a subspace is contained in any larger subspace containing both the point and the subspace reflected in. -/ lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} [nonempty s₁] [complete_space s₁.direction] (hle : s₁ ≤ s₂) {p : P} (hp : p ∈ s₂) : reflection s₁ p ∈ s₂ := begin rw [reflection_apply], have ho : ↑(orthogonal_projection s₁ p) ∈ s₂ := hle (orthogonal_projection_mem p), exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho end /-- Reflecting an orthogonal vector plus a point in the subspace produces the negation of that vector plus the point. -/ lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : reflection s (v +ᵥ p) = -v +ᵥ p := begin rw [reflection_apply, orthogonal_projection_vadd_eq_self hp hv, vsub_vadd_eq_vsub_sub], simp end /-- Reflecting a vector plus a point in the subspace produces the negation of that vector plus the point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) : reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) = -(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ := reflection_orthogonal_vadd hp₁ (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) omit V /-- A set of points is cospherical if they are equidistant from some point. In two dimensions, this is the same thing as being concyclic. -/ def cospherical (ps : set P) : Prop := ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius /-- The definition of `cospherical`. -/ lemma cospherical_def (ps : set P) : cospherical ps ↔ ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := iff.rfl /-- A subset of a cospherical set is cospherical. -/ lemma cospherical_subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) : cospherical ps₁ := begin rcases hc with ⟨c, r, hcr⟩, exact ⟨c, r, λ p hp, hcr p (hs hp)⟩ end include V /-- The empty set is cospherical. -/ lemma cospherical_empty : cospherical (∅ : set P) := begin use add_torsor.nonempty.some, simp, end omit V /-- A single point is cospherical. -/ lemma cospherical_singleton (p : P) : cospherical ({p} : set P) := begin use p, simp end include V /-- Two points are cospherical. -/ lemma cospherical_insert_singleton (p₁ p₂ : P) : cospherical ({p₁, p₂} : set P) := begin use [(2⁻¹ : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁, (2⁻¹ : ℝ) * (dist p₂ p₁)], intro p, rw [set.mem_insert_iff, set.mem_singleton_iff], rintro ⟨_|_⟩, { rw [dist_eq_norm_vsub V p₁, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, norm_neg, norm_smul, dist_eq_norm_vsub V p₂], simp }, { rw [H, dist_eq_norm_vsub V p₂, vsub_vadd_eq_vsub_sub, dist_eq_norm_vsub V p₂], conv_lhs { congr, congr, rw ←one_smul ℝ (p₂ -ᵥ p₁ : V) }, rw [←sub_smul, norm_smul], norm_num } end /-- Any three points in a cospherical set are affinely independent. -/ lemma cospherical.affine_independent {s : set P} (hs : cospherical s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := begin rw affine_independent_iff_not_collinear, intro hc, rw collinear_iff_of_mem ℝ (set.mem_range_self (0 : fin 3)) at hc, rcases hc with ⟨v, hv⟩, rw set.forall_range_iff at hv, have hv0 : v ≠ 0, { intro h, have he : p 1 = p 0, by simpa [h] using hv 1, exact (dec_trivial : (1 : fin 3) ≠ 0) (hpi he) }, rcases hs with ⟨c, r, hs⟩, have hs' := λ i, hs (p i) (set.mem_of_mem_of_subset (set.mem_range_self _) hps), choose f hf using hv, have hsd : ∀ i, dist ((f i • v) +ᵥ p 0) c = r, { intro i, rw ←hf, exact hs' i }, have hf0 : f 0 = 0, { have hf0' := hf 0, rw [eq_comm, ←@vsub_eq_zero_iff_eq V, vadd_vsub, smul_eq_zero] at hf0', simpa [hv0] using hf0' }, have hfi : function.injective f, { intros i j h, have hi := hf i, rw [h, ←hf j] at hi, exact hpi hi }, simp_rw [←hsd 0, hf0, zero_smul, zero_vadd, dist_smul_vadd_eq_dist (p 0) c hv0] at hsd, have hfn0 : ∀ i, i ≠ 0 → f i ≠ 0 := λ i, (hfi.ne_iff' hf0).2, have hfn0' : ∀ i, i ≠ 0 → f i = (-2) * ⟪v, (p 0 -ᵥ c)⟫ / ⟪v, v⟫, { intros i hi, have hsdi := hsd i, simpa [hfn0, hi] using hsdi }, have hf12 : f 1 = f 2, { rw [hfn0' 1 dec_trivial, hfn0' 2 dec_trivial] }, exact (dec_trivial : (1 : fin 3) ≠ 2) (hfi hf12) end end euclidean_geometry
971231c8e462bfe5f9e6d57ec88d2b05e2555033
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/generator.lean
1ba6e9b0a90c1a4f9504ef0ea20bf637ef98ff1e
[ "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
27,353
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.balanced import category_theory.limits.essentially_small import category_theory.limits.opposites import category_theory.limits.shapes.zero_morphisms import category_theory.subobject.lattice import category_theory.subobject.well_powered import data.set.opposite /-! # Separating and detecting sets There are several non-equivalent notions of a generator of a category. Here, we consider two of them: * We say that `𝒢` is a separating set if the functors `C(G, -)` for `G ∈ 𝒢` are collectively faithful, i.e., if `h ≫ f = h ≫ g` for all `h` with domain in `𝒢` implies `f = g`. * We say that `𝒢` is a detecting set if the functors `C(G, -)` collectively reflect isomorphisms, i.e., if any `h` with domain in `𝒢` uniquely factors through `f`, then `f` is an isomorphism. There are, of course, also the dual notions of coseparating and codetecting sets. ## Main results We * define predicates `is_separating`, `is_coseparating`, `is_detecting` and `is_codetecting` on sets of objects; * show that separating and coseparating are dual notions; * show that detecting and codetecting are dual notions; * show that if `C` has equalizers, then detecting implies separating; * show that if `C` has coequalizers, then codetecting implies separating; * show that if `C` is balanced, then separating implies detecting and coseparating implies codetecting; * show that `∅` is separating if and only if `∅` is coseparating if and only if `C` is thin; * show that `∅` is detecting if and only if `∅` is codetecting if and only if `C` is a groupoid; * define predicates `is_separator`, `is_coseparator`, `is_detector` and `is_codetector` as the singleton counterparts to the definitions for sets above and restate the above results in this situation; * show that `G` is a separator if and only if `coyoneda.obj (op G)` is faithful (and the dual); * show that `G` is a detector if and only if `coyoneda.obj (op G)` reflects isomorphisms (and the dual). ## Future work * We currently don't have any examples yet. * We will want typeclasses `has_separator C` and similar. -/ universes w v₁ v₂ u₁ u₂ open category_theory.limits opposite namespace category_theory variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- We say that `𝒢` is a separating set if the functors `C(G, -)` for `G ∈ 𝒢` are collectively faithful, i.e., if `h ≫ f = h ≫ g` for all `h` with domain in `𝒢` implies `f = g`. -/ def is_separating (𝒢 : set C) : Prop := ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ (G ∈ 𝒢) (h : G ⟶ X), h ≫ f = h ≫ g) → f = g /-- We say that `𝒢` is a coseparating set if the functors `C(-, G)` for `G ∈ 𝒢` are collectively faithful, i.e., if `f ≫ h = g ≫ h` for all `h` with codomain in `𝒢` implies `f = g`. -/ def is_coseparating (𝒢 : set C) : Prop := ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ (G ∈ 𝒢) (h : Y ⟶ G), f ≫ h = g ≫ h) → f = g /-- We say that `𝒢` is a detecting set if the functors `C(G, -)` collectively reflect isomorphisms, i.e., if any `h` with domain in `𝒢` uniquely factors through `f`, then `f` is an isomorphism. -/ def is_detecting (𝒢 : set C) : Prop := ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ (G ∈ 𝒢) (h : G ⟶ Y), ∃! (h' : G ⟶ X), h' ≫ f = h) → is_iso f /-- We say that `𝒢` is a codetecting set if the functors `C(-, G)` collectively reflect isomorphisms, i.e., if any `h` with codomain in `G` uniquely factors through `f`, then `f` is an isomorphism. -/ def is_codetecting (𝒢 : set C) : Prop := ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ (G ∈ 𝒢) (h : X ⟶ G), ∃! (h' : Y ⟶ G), f ≫ h' = h) → is_iso f section dual lemma is_separating_op_iff (𝒢 : set C) : is_separating 𝒢.op ↔ is_coseparating 𝒢 := begin refine ⟨λ h𝒢 X Y f g hfg, _, λ h𝒢 X Y f g hfg, _⟩, { refine quiver.hom.op_inj (h𝒢 _ _ (λ G hG h, quiver.hom.unop_inj _)), simpa only [unop_comp, quiver.hom.unop_op] using hfg _ (set.mem_op.1 hG) _ }, { refine quiver.hom.unop_inj (h𝒢 _ _ (λ G hG h, quiver.hom.op_inj _)), simpa only [op_comp, quiver.hom.op_unop] using hfg _ (set.op_mem_op.2 hG) _ } end lemma is_coseparating_op_iff (𝒢 : set C) : is_coseparating 𝒢.op ↔ is_separating 𝒢 := begin refine ⟨λ h𝒢 X Y f g hfg, _, λ h𝒢 X Y f g hfg, _⟩, { refine quiver.hom.op_inj (h𝒢 _ _ (λ G hG h, quiver.hom.unop_inj _)), simpa only [unop_comp, quiver.hom.unop_op] using hfg _ (set.mem_op.1 hG) _ }, { refine quiver.hom.unop_inj (h𝒢 _ _ (λ G hG h, quiver.hom.op_inj _)), simpa only [op_comp, quiver.hom.op_unop] using hfg _ (set.op_mem_op.2 hG) _ } end lemma is_coseparating_unop_iff (𝒢 : set Cᵒᵖ) : is_coseparating 𝒢.unop ↔ is_separating 𝒢 := by rw [← is_separating_op_iff, set.unop_op] lemma is_separating_unop_iff (𝒢 : set Cᵒᵖ) : is_separating 𝒢.unop ↔ is_coseparating 𝒢 := by rw [← is_coseparating_op_iff, set.unop_op] lemma is_detecting_op_iff (𝒢 : set C) : is_detecting 𝒢.op ↔ is_codetecting 𝒢 := begin refine ⟨λ h𝒢 X Y f hf, _, λ h𝒢 X Y f hf, _⟩, { refine (is_iso_op_iff _).1 (h𝒢 _ (λ G hG h, _)), obtain ⟨t, ht, ht'⟩ := hf (unop G) (set.mem_op.1 hG) h.unop, exact ⟨t.op, quiver.hom.unop_inj ht, λ y hy, quiver.hom.unop_inj (ht' _ (quiver.hom.op_inj hy))⟩ }, { refine (is_iso_unop_iff _).1 (h𝒢 _ (λ G hG h, _)), obtain ⟨t, ht, ht'⟩ := hf (op G) (set.op_mem_op.2 hG) h.op, refine ⟨t.unop, quiver.hom.op_inj ht, λ y hy, quiver.hom.op_inj (ht' _ _)⟩, exact quiver.hom.unop_inj (by simpa only using hy) } end lemma is_codetecting_op_iff (𝒢 : set C) : is_codetecting 𝒢.op ↔ is_detecting 𝒢 := begin refine ⟨λ h𝒢 X Y f hf, _, λ h𝒢 X Y f hf, _⟩, { refine (is_iso_op_iff _).1 (h𝒢 _ (λ G hG h, _)), obtain ⟨t, ht, ht'⟩ := hf (unop G) (set.mem_op.1 hG) h.unop, exact ⟨t.op, quiver.hom.unop_inj ht, λ y hy, quiver.hom.unop_inj (ht' _ (quiver.hom.op_inj hy))⟩ }, { refine (is_iso_unop_iff _).1 (h𝒢 _ (λ G hG h, _)), obtain ⟨t, ht, ht'⟩ := hf (op G) (set.op_mem_op.2 hG) h.op, refine ⟨t.unop, quiver.hom.op_inj ht, λ y hy, quiver.hom.op_inj (ht' _ _)⟩, exact quiver.hom.unop_inj (by simpa only using hy) } end lemma is_detecting_unop_iff (𝒢 : set Cᵒᵖ) : is_detecting 𝒢.unop ↔ is_codetecting 𝒢 := by rw [← is_codetecting_op_iff, set.unop_op] lemma is_codetecting_unop_iff {𝒢 : set Cᵒᵖ} : is_codetecting 𝒢.unop ↔ is_detecting 𝒢 := by rw [← is_detecting_op_iff, set.unop_op] end dual lemma is_detecting.is_separating [has_equalizers C] {𝒢 : set C} (h𝒢 : is_detecting 𝒢) : is_separating 𝒢 := λ X Y f g hfg, have is_iso (equalizer.ι f g), from h𝒢 _ (λ G hG h, equalizer.exists_unique _ (hfg _ hG _)), by exactI eq_of_epi_equalizer section lemma is_codetecting.is_coseparating [has_coequalizers C] {𝒢 : set C} : is_codetecting 𝒢 → is_coseparating 𝒢 := by simpa only [← is_separating_op_iff, ← is_detecting_op_iff] using is_detecting.is_separating end lemma is_separating.is_detecting [balanced C] {𝒢 : set C} (h𝒢 : is_separating 𝒢) : is_detecting 𝒢 := begin intros X Y f hf, refine (is_iso_iff_mono_and_epi _).2 ⟨⟨λ Z g h hgh, h𝒢 _ _ (λ G hG i, _)⟩, ⟨λ Z g h hgh, _⟩⟩, { obtain ⟨t, -, ht⟩ := hf G hG (i ≫ g ≫ f), rw [ht (i ≫ g) (category.assoc _ _ _), ht (i ≫ h) (hgh.symm ▸ category.assoc _ _ _)] }, { refine h𝒢 _ _ (λ G hG i, _), obtain ⟨t, rfl, -⟩ := hf G hG i, rw [category.assoc, hgh, category.assoc] } end section local attribute [instance] balanced_opposite lemma is_coseparating.is_codetecting [balanced C] {𝒢 : set C} : is_coseparating 𝒢 → is_codetecting 𝒢 := by simpa only [← is_detecting_op_iff, ← is_separating_op_iff] using is_separating.is_detecting end lemma is_detecting_iff_is_separating [has_equalizers C] [balanced C] (𝒢 : set C) : is_detecting 𝒢 ↔ is_separating 𝒢 := ⟨is_detecting.is_separating, is_separating.is_detecting⟩ lemma is_codetecting_iff_is_coseparating [has_coequalizers C] [balanced C] {𝒢 : set C} : is_codetecting 𝒢 ↔ is_coseparating 𝒢 := ⟨is_codetecting.is_coseparating, is_coseparating.is_codetecting⟩ section mono lemma is_separating.mono {𝒢 : set C} (h𝒢 : is_separating 𝒢) {ℋ : set C} (h𝒢ℋ : 𝒢 ⊆ ℋ) : is_separating ℋ := λ X Y f g hfg, h𝒢 _ _ $ λ G hG h, hfg _ (h𝒢ℋ hG) _ lemma is_coseparating.mono {𝒢 : set C} (h𝒢 : is_coseparating 𝒢) {ℋ : set C} (h𝒢ℋ : 𝒢 ⊆ ℋ) : is_coseparating ℋ := λ X Y f g hfg, h𝒢 _ _ $ λ G hG h, hfg _ (h𝒢ℋ hG) _ lemma is_detecting.mono {𝒢 : set C} (h𝒢 : is_detecting 𝒢) {ℋ : set C} (h𝒢ℋ : 𝒢 ⊆ ℋ) : is_detecting ℋ := λ X Y f hf, h𝒢 _ $ λ G hG h, hf _ (h𝒢ℋ hG) _ lemma is_codetecting.mono {𝒢 : set C} (h𝒢 : is_codetecting 𝒢) {ℋ : set C} (h𝒢ℋ : 𝒢 ⊆ ℋ) : is_codetecting ℋ := λ X Y f hf, h𝒢 _ $ λ G hG h, hf _ (h𝒢ℋ hG) _ end mono section empty lemma thin_of_is_separating_empty (h : is_separating (∅ : set C)) : quiver.is_thin C := λ _ _, ⟨λ f g, h _ _ $ λ G, false.elim⟩ lemma is_separating_empty_of_thin [quiver.is_thin C] : is_separating (∅ : set C) := λ X Y f g hfg, subsingleton.elim _ _ lemma thin_of_is_coseparating_empty (h : is_coseparating (∅ : set C)) : quiver.is_thin C := λ _ _, ⟨λ f g, h _ _ $ λ G, false.elim⟩ lemma is_coseparating_empty_of_thin [quiver.is_thin C] : is_coseparating (∅ : set C) := λ X Y f g hfg, subsingleton.elim _ _ lemma groupoid_of_is_detecting_empty (h : is_detecting (∅ : set C)) {X Y : C} (f : X ⟶ Y) : is_iso f := h _ $ λ G, false.elim lemma is_detecting_empty_of_groupoid [∀ {X Y : C} (f : X ⟶ Y), is_iso f] : is_detecting (∅ : set C) := λ X Y f hf, infer_instance lemma groupoid_of_is_codetecting_empty (h : is_codetecting (∅ : set C)) {X Y : C} (f : X ⟶ Y) : is_iso f := h _ $ λ G, false.elim lemma is_codetecting_empty_of_groupoid [∀ {X Y : C} (f : X ⟶ Y), is_iso f] : is_codetecting (∅ : set C) := λ X Y f hf, infer_instance end empty lemma is_separating_iff_epi (𝒢 : set C) [Π (A : C), has_coproduct (λ f : Σ G : 𝒢, (G : C) ⟶ A, (f.1 : C))] : is_separating 𝒢 ↔ ∀ A : C, epi (sigma.desc (@sigma.snd 𝒢 (λ G, (G : C) ⟶ A))) := begin refine ⟨λ h A, ⟨λ Z u v huv, h _ _ (λ G hG f, _)⟩, λ h X Y f g hh, _⟩, { simpa using (sigma.ι (λ f : Σ G : 𝒢, (G : C) ⟶ A, (f.1 : C)) ⟨⟨G, hG⟩, f⟩) ≫= huv }, { haveI := h X, refine (cancel_epi (sigma.desc (@sigma.snd 𝒢 (λ G, (G : C) ⟶ X)))).1 (colimit.hom_ext (λ j, _)), simpa using hh j.as.1.1 j.as.1.2 j.as.2 } end lemma is_coseparating_iff_mono (𝒢 : set C) [Π (A : C), has_product (λ f : Σ G : 𝒢, A ⟶ (G : C), (f.1 : C))] : is_coseparating 𝒢 ↔ ∀ A : C, mono (pi.lift (@sigma.snd 𝒢 (λ G, A ⟶ (G : C)))) := begin refine ⟨λ h A, ⟨λ Z u v huv, h _ _ (λ G hG f, _)⟩, λ h X Y f g hh, _⟩, { simpa using huv =≫ (pi.π (λ f : Σ G : 𝒢, A ⟶ (G : C), (f.1 : C)) ⟨⟨G, hG⟩, f⟩) }, { haveI := h Y, refine (cancel_mono (pi.lift (@sigma.snd 𝒢 (λ G, Y ⟶ (G : C))))).1 (limit.hom_ext (λ j, _)), simpa using hh j.as.1.1 j.as.1.2 j.as.2 } end /-- An ingredient of the proof of the Special Adjoint Functor Theorem: a complete well-powered category with a small coseparating set has an initial object. In fact, it follows from the Special Adjoint Functor Theorem that `C` is already cocomplete, see `has_colimits_of_has_limits_of_is_coseparating`. -/ lemma has_initial_of_is_coseparating [well_powered C] [has_limits C] {𝒢 : set C} [small.{v₁} 𝒢] (h𝒢 : is_coseparating 𝒢) : has_initial C := begin haveI := has_products_of_shape_of_small C 𝒢, haveI := λ A, has_products_of_shape_of_small.{v₁} C (Σ G : 𝒢, A ⟶ (G : C)), letI := complete_lattice_of_complete_semilattice_Inf (subobject (pi_obj (coe : 𝒢 → C))), suffices : ∀ A : C, unique (((⊥ : subobject (pi_obj (coe : 𝒢 → C))) : C) ⟶ A), { exactI has_initial_of_unique ((⊥ : subobject (pi_obj (coe : 𝒢 → C))) : C) }, refine λ A, ⟨⟨_⟩, λ f, _⟩, { let s := pi.lift (λ f : Σ G : 𝒢, A ⟶ (G : C), id (pi.π (coe : 𝒢 → C)) f.1), let t := pi.lift (@sigma.snd 𝒢 (λ G, A ⟶ (G : C))), haveI : mono t := (is_coseparating_iff_mono 𝒢).1 h𝒢 A, exact subobject.of_le_mk _ (pullback.fst : pullback s t ⟶ _) bot_le ≫ pullback.snd }, { generalize : default = g, suffices : is_split_epi (equalizer.ι f g), { exactI eq_of_epi_equalizer }, exact is_split_epi.mk' ⟨subobject.of_le_mk _ (equalizer.ι f g ≫ subobject.arrow _) bot_le, by { ext, simp }⟩ } end /-- An ingredient of the proof of the Special Adjoint Functor Theorem: a cocomplete well-copowered category with a small separating set has a terminal object. In fact, it follows from the Special Adjoint Functor Theorem that `C` is already complete, see `has_limits_of_has_colimits_of_is_separating`. -/ lemma has_terminal_of_is_separating [well_powered Cᵒᵖ] [has_colimits C] {𝒢 : set C} [small.{v₁} 𝒢] (h𝒢 : is_separating 𝒢) : has_terminal C := begin haveI : small.{v₁} 𝒢.op := small_of_injective (set.op_equiv_self 𝒢).injective, haveI : has_initial Cᵒᵖ := has_initial_of_is_coseparating ((is_coseparating_op_iff _).2 h𝒢), exact has_terminal_of_has_initial_op end section well_powered namespace subobject lemma eq_of_le_of_is_detecting {𝒢 : set C} (h𝒢 : is_detecting 𝒢) {X : C} (P Q : subobject X) (h₁ : P ≤ Q) (h₂ : ∀ (G ∈ 𝒢) {f : G ⟶ X}, Q.factors f → P.factors f) : P = Q := begin suffices : is_iso (of_le _ _ h₁), { exactI le_antisymm h₁ (le_of_comm (inv (of_le _ _ h₁)) (by simp)) }, refine h𝒢 _ (λ G hG f, _), have : P.factors (f ≫ Q.arrow) := h₂ _ hG ((factors_iff _ _).2 ⟨_, rfl⟩), refine ⟨factor_thru _ _ this, _, λ g (hg : g ≫ _ = f), _⟩, { simp only [← cancel_mono Q.arrow, category.assoc, of_le_arrow, factor_thru_arrow] }, { simp only [← cancel_mono (subobject.of_le _ _ h₁), ← cancel_mono Q.arrow, hg, category.assoc, of_le_arrow, factor_thru_arrow] } end lemma inf_eq_of_is_detecting [has_pullbacks C] {𝒢 : set C} (h𝒢 : is_detecting 𝒢) {X : C} (P Q : subobject X) (h : ∀ (G ∈ 𝒢) {f : G ⟶ X}, P.factors f → Q.factors f) : P ⊓ Q = P := eq_of_le_of_is_detecting h𝒢 _ _ _root_.inf_le_left (λ G hG f hf, (inf_factors _).2 ⟨hf, h _ hG hf⟩) lemma eq_of_is_detecting [has_pullbacks C] {𝒢 : set C} (h𝒢 : is_detecting 𝒢) {X : C} (P Q : subobject X) (h : ∀ (G ∈ 𝒢) {f : G ⟶ X}, P.factors f ↔ Q.factors f) : P = Q := calc P = P ⊓ Q : eq.symm $ inf_eq_of_is_detecting h𝒢 _ _ $ λ G hG f hf, (h G hG).1 hf ... = Q ⊓ P : inf_comm ... = Q : inf_eq_of_is_detecting h𝒢 _ _ $ λ G hG f hf, (h G hG).2 hf end subobject /-- A category with pullbacks and a small detecting set is well-powered. -/ lemma well_powered_of_is_detecting [has_pullbacks C] {𝒢 : set C} [small.{v₁} 𝒢] (h𝒢 : is_detecting 𝒢) : well_powered C := ⟨λ X, @small_of_injective _ _ _ (λ P : subobject X, { f : Σ G : 𝒢, G.1 ⟶ X | P.factors f.2 }) $ λ P Q h, subobject.eq_of_is_detecting h𝒢 _ _ (by simpa [set.ext_iff] using h)⟩ end well_powered namespace structured_arrow variables (S : D) (T : C ⥤ D) lemma is_coseparating_proj_preimage {𝒢 : set C} (h𝒢 : is_coseparating 𝒢) : is_coseparating ((proj S T).obj ⁻¹' 𝒢) := begin refine λ X Y f g hfg, ext _ _ (h𝒢 _ _ (λ G hG h, _)), exact congr_arg comma_morphism.right (hfg (mk (Y.hom ≫ T.map h)) hG (hom_mk h rfl)) end end structured_arrow namespace costructured_arrow variables (S : C ⥤ D) (T : D) lemma is_separating_proj_preimage {𝒢 : set C} (h𝒢 : is_separating 𝒢) : is_separating ((proj S T).obj ⁻¹' 𝒢) := begin refine λ X Y f g hfg, ext _ _ (h𝒢 _ _ (λ G hG h, _)), convert congr_arg comma_morphism.left (hfg (mk (S.map h ≫ X.hom)) hG (hom_mk h rfl)) end end costructured_arrow /-- We say that `G` is a separator if the functor `C(G, -)` is faithful. -/ def is_separator (G : C) : Prop := is_separating ({G} : set C) /-- We say that `G` is a coseparator if the functor `C(-, G)` is faithful. -/ def is_coseparator (G : C) : Prop := is_coseparating ({G} : set C) /-- We say that `G` is a detector if the functor `C(G, -)` reflects isomorphisms. -/ def is_detector (G : C) : Prop := is_detecting ({G} : set C) /-- We say that `G` is a codetector if the functor `C(-, G)` reflects isomorphisms. -/ def is_codetector (G : C) : Prop := is_codetecting ({G} : set C) section dual lemma is_separator_op_iff (G : C) : is_separator (op G) ↔ is_coseparator G := by rw [is_separator, is_coseparator, ← is_separating_op_iff, set.singleton_op] lemma is_coseparator_op_iff (G : C) : is_coseparator (op G) ↔ is_separator G := by rw [is_separator, is_coseparator, ← is_coseparating_op_iff, set.singleton_op] lemma is_coseparator_unop_iff (G : Cᵒᵖ) : is_coseparator (unop G) ↔ is_separator G := by rw [is_separator, is_coseparator, ← is_coseparating_unop_iff, set.singleton_unop] lemma is_separator_unop_iff (G : Cᵒᵖ) : is_separator (unop G) ↔ is_coseparator G := by rw [is_separator, is_coseparator, ← is_separating_unop_iff, set.singleton_unop] lemma is_detector_op_iff (G : C) : is_detector (op G) ↔ is_codetector G := by rw [is_detector, is_codetector, ← is_detecting_op_iff, set.singleton_op] lemma is_codetector_op_iff (G : C) : is_codetector (op G) ↔ is_detector G := by rw [is_detector, is_codetector, ← is_codetecting_op_iff, set.singleton_op] lemma is_codetector_unop_iff (G : Cᵒᵖ) : is_codetector (unop G) ↔ is_detector G := by rw [is_detector, is_codetector, ← is_codetecting_unop_iff, set.singleton_unop] lemma is_detector_unop_iff (G : Cᵒᵖ) : is_detector (unop G) ↔ is_codetector G := by rw [is_detector, is_codetector, ← is_detecting_unop_iff, set.singleton_unop] end dual lemma is_detector.is_separator [has_equalizers C] {G : C} : is_detector G → is_separator G := is_detecting.is_separating lemma is_codetector.is_coseparator [has_coequalizers C] {G : C} : is_codetector G → is_coseparator G := is_codetecting.is_coseparating lemma is_separator.is_detector [balanced C] {G : C} : is_separator G → is_detector G := is_separating.is_detecting lemma is_cospearator.is_codetector [balanced C] {G : C} : is_coseparator G → is_codetector G := is_coseparating.is_codetecting lemma is_separator_def (G : C) : is_separator G ↔ ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ h : G ⟶ X, h ≫ f = h ≫ g) → f = g := ⟨λ hG X Y f g hfg, hG _ _ $ λ H hH h, by { obtain rfl := set.mem_singleton_iff.1 hH, exact hfg h }, λ hG X Y f g hfg, hG _ _ $ λ h, hfg _ (set.mem_singleton _) _⟩ lemma is_separator.def {G : C} : is_separator G → ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ h : G ⟶ X, h ≫ f = h ≫ g) → f = g := (is_separator_def _).1 lemma is_coseparator_def (G : C) : is_coseparator G ↔ ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ h : Y ⟶ G, f ≫ h = g ≫ h) → f = g := ⟨λ hG X Y f g hfg, hG _ _ $ λ H hH h, by { obtain rfl := set.mem_singleton_iff.1 hH, exact hfg h }, λ hG X Y f g hfg, hG _ _ $ λ h, hfg _ (set.mem_singleton _) _⟩ lemma is_coseparator.def {G : C} : is_coseparator G → ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ h : Y ⟶ G, f ≫ h = g ≫ h) → f = g := (is_coseparator_def _).1 lemma is_detector_def (G : C) : is_detector G ↔ ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : G ⟶ Y, ∃! h', h' ≫ f = h) → is_iso f := ⟨λ hG X Y f hf, hG _ $ λ H hH h, by { obtain rfl := set.mem_singleton_iff.1 hH, exact hf h }, λ hG X Y f hf, hG _ $ λ h, hf _ (set.mem_singleton _) _⟩ lemma is_detector.def {G : C} : is_detector G → ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : G ⟶ Y, ∃! h', h' ≫ f = h) → is_iso f := (is_detector_def _).1 lemma is_codetector_def (G : C) : is_codetector G ↔ ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : X ⟶ G, ∃! h', f ≫ h' = h) → is_iso f := ⟨λ hG X Y f hf, hG _ $ λ H hH h, by { obtain rfl := set.mem_singleton_iff.1 hH, exact hf h }, λ hG X Y f hf, hG _ $ λ h, hf _ (set.mem_singleton _) _⟩ lemma is_codetector.def {G : C} : is_codetector G → ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : X ⟶ G, ∃! h', f ≫ h' = h) → is_iso f := (is_codetector_def _).1 lemma is_separator_iff_faithful_coyoneda_obj (G : C) : is_separator G ↔ faithful (coyoneda.obj (op G)) := ⟨λ hG, ⟨λ X Y f g hfg, hG.def _ _ (congr_fun hfg)⟩, λ h, (is_separator_def _).2 $ λ X Y f g hfg, by exactI (coyoneda.obj (op G)).map_injective (funext hfg)⟩ lemma is_coseparator_iff_faithful_yoneda_obj (G : C) : is_coseparator G ↔ faithful (yoneda.obj G) := ⟨λ hG, ⟨λ X Y f g hfg, quiver.hom.unop_inj (hG.def _ _ (congr_fun hfg))⟩, λ h, (is_coseparator_def _).2 $ λ X Y f g hfg, quiver.hom.op_inj $ by exactI (yoneda.obj G).map_injective (funext hfg)⟩ lemma is_separator_iff_epi (G : C) [Π A : C, has_coproduct (λ (f : G ⟶ A), G)] : is_separator G ↔ ∀ (A : C), epi (sigma.desc (λ (f : G ⟶ A), f)) := begin rw is_separator_def, refine ⟨λ h A, ⟨λ Z u v huv, h _ _ (λ i, _)⟩, λ h X Y f g hh, _⟩, { simpa using (sigma.ι _ i) ≫= huv }, { haveI := h X, refine (cancel_epi (sigma.desc (λ (f : G ⟶ X), f))).1 (colimit.hom_ext (λ j, _)), simpa using hh j.as } end lemma is_coseparator_iff_mono (G : C) [Π A : C, has_product (λ (f : A ⟶ G), G)] : is_coseparator G ↔ ∀ (A : C), mono (pi.lift (λ (f : A ⟶ G), f)) := begin rw is_coseparator_def, refine ⟨λ h A, ⟨λ Z u v huv, h _ _ (λ i, _)⟩, λ h X Y f g hh, _⟩, { simpa using huv =≫ (pi.π _ i) }, { haveI := h Y, refine (cancel_mono (pi.lift (λ (f : Y ⟶ G), f))).1 (limit.hom_ext (λ j, _)), simpa using hh j.as } end section zero_morphisms variables [has_zero_morphisms C] lemma is_separator_coprod (G H : C) [has_binary_coproduct G H] : is_separator (G ⨿ H) ↔ is_separating ({G, H} : set C) := begin refine ⟨λ h X Y u v huv, _, λ h, (is_separator_def _).2 (λ X Y u v huv, h _ _ (λ Z hZ g, _))⟩, { refine h.def _ _ (λ g, coprod.hom_ext _ _), { simpa using huv G (by simp) (coprod.inl ≫ g) }, { simpa using huv H (by simp) (coprod.inr ≫ g) } }, { simp only [set.mem_insert_iff, set.mem_singleton_iff] at hZ, unfreezingI { rcases hZ with rfl|rfl }, { simpa using coprod.inl ≫= huv (coprod.desc g 0) }, { simpa using coprod.inr ≫= huv (coprod.desc 0 g) } } end lemma is_separator_coprod_of_is_separator_left (G H : C) [has_binary_coproduct G H] (hG : is_separator G) : is_separator (G ⨿ H) := (is_separator_coprod _ _).2 $ is_separating.mono hG $ by simp lemma is_separator_coprod_of_is_separator_right (G H : C) [has_binary_coproduct G H] (hH : is_separator H) : is_separator (G ⨿ H) := (is_separator_coprod _ _).2 $ is_separating.mono hH $ by simp lemma is_separator_sigma {β : Type w} (f : β → C) [has_coproduct f] : is_separator (∐ f) ↔ is_separating (set.range f) := begin refine ⟨λ h X Y u v huv, _, λ h, (is_separator_def _).2 (λ X Y u v huv, h _ _ (λ Z hZ g, _))⟩, { refine h.def _ _ (λ g, colimit.hom_ext (λ b, _)), simpa using huv (f b.as) (by simp) (colimit.ι (discrete.functor f) _ ≫ g) }, { obtain ⟨b, rfl⟩ := set.mem_range.1 hZ, classical, simpa using sigma.ι f b ≫= huv (sigma.desc (pi.single b g)) } end lemma is_separator_sigma_of_is_separator {β : Type w} (f : β → C) [has_coproduct f] (b : β) (hb : is_separator (f b)) : is_separator (∐ f) := (is_separator_sigma _).2 $ is_separating.mono hb $ by simp lemma is_coseparator_prod (G H : C) [has_binary_product G H] : is_coseparator (G ⨯ H) ↔ is_coseparating ({G, H} : set C) := begin refine ⟨λ h X Y u v huv, _, λ h, (is_coseparator_def _).2 (λ X Y u v huv, h _ _ (λ Z hZ g, _))⟩, { refine h.def _ _ (λ g, prod.hom_ext _ _), { simpa using huv G (by simp) (g ≫ limits.prod.fst) }, { simpa using huv H (by simp) (g ≫ limits.prod.snd) } }, { simp only [set.mem_insert_iff, set.mem_singleton_iff] at hZ, unfreezingI { rcases hZ with rfl|rfl }, { simpa using huv (prod.lift g 0) =≫ limits.prod.fst }, { simpa using huv (prod.lift 0 g) =≫ limits.prod.snd } } end lemma is_coseparator_prod_of_is_coseparator_left (G H : C) [has_binary_product G H] (hG : is_coseparator G) : is_coseparator (G ⨯ H) := (is_coseparator_prod _ _).2 $ is_coseparating.mono hG $ by simp lemma is_coseparator_prod_of_is_coseparator_right (G H : C) [has_binary_product G H] (hH : is_coseparator H) : is_coseparator (G ⨯ H) := (is_coseparator_prod _ _).2 $ is_coseparating.mono hH $ by simp lemma is_coseparator_pi {β : Type w} (f : β → C) [has_product f] : is_coseparator (∏ f) ↔ is_coseparating (set.range f) := begin refine ⟨λ h X Y u v huv, _, λ h, (is_coseparator_def _).2 (λ X Y u v huv, h _ _ (λ Z hZ g, _))⟩, { refine h.def _ _ (λ g, limit.hom_ext (λ b, _)), simpa using huv (f b.as) (by simp) (g ≫ limit.π (discrete.functor f) _ ) }, { obtain ⟨b, rfl⟩ := set.mem_range.1 hZ, classical, simpa using huv (pi.lift (pi.single b g)) =≫ pi.π f b } end lemma is_coseparator_pi_of_is_coseparator {β : Type w} (f : β → C) [has_product f] (b : β) (hb : is_coseparator (f b)) : is_coseparator (∏ f) := (is_coseparator_pi _).2 $ is_coseparating.mono hb $ by simp end zero_morphisms lemma is_detector_iff_reflects_isomorphisms_coyoneda_obj (G : C) : is_detector G ↔ reflects_isomorphisms (coyoneda.obj (op G)) := begin refine ⟨λ hG, ⟨λ X Y f hf, hG.def _ (λ h, _)⟩, λ h, (is_detector_def _).2 (λ X Y f hf, _)⟩, { rw [is_iso_iff_bijective, function.bijective_iff_exists_unique] at hf, exact hf h }, { suffices : is_iso ((coyoneda.obj (op G)).map f), { exactI @is_iso_of_reflects_iso _ _ _ _ _ _ _ (coyoneda.obj (op G)) _ h }, rwa [is_iso_iff_bijective, function.bijective_iff_exists_unique] } end lemma is_codetector_iff_reflects_isomorphisms_yoneda_obj (G : C) : is_codetector G ↔ reflects_isomorphisms (yoneda.obj G) := begin refine ⟨λ hG, ⟨λ X Y f hf, _ ⟩, λ h, (is_codetector_def _).2 (λ X Y f hf, _)⟩, { refine (is_iso_unop_iff _).1 (hG.def _ _), rwa [is_iso_iff_bijective, function.bijective_iff_exists_unique] at hf }, { rw ← is_iso_op_iff, suffices : is_iso ((yoneda.obj G).map f.op), { exactI @is_iso_of_reflects_iso _ _ _ _ _ _ _ (yoneda.obj G) _ h }, rwa [is_iso_iff_bijective, function.bijective_iff_exists_unique] } end lemma well_powered_of_is_detector [has_pullbacks C] (G : C) (hG : is_detector G) : well_powered C := well_powered_of_is_detecting hG end category_theory
380942cfc494ab38a94cfd84aaa5be09f5cbbd7b
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/nat/enat.lean
7ab6f2c18c4dc645a517ae0b889662ac56a3dc48
[ "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
12,650
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Natural numbers with infinity, represented as roption ℕ. -/ import data.pfun import tactic.norm_num open roption /-- Type of natural numbers with infinity -/ def enat : Type := roption ℕ namespace enat instance : has_zero enat := ⟨some 0⟩ instance : inhabited enat := ⟨0⟩ instance : has_one enat := ⟨some 1⟩ instance : has_add enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance : has_coe ℕ enat := ⟨some⟩ instance (n : ℕ) : decidable (n : enat).dom := is_true trivial @[simp] lemma coe_inj {x y : ℕ} : (x : enat) = y ↔ x = y := roption.some_inj instance : add_comm_monoid enat := { add := (+), zero := (0), add_comm := λ x y, roption.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, roption.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, roption.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, roption.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : has_le enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top enat := ⟨none⟩ instance : has_bot enat := ⟨0⟩ instance : has_sup enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ @[elab_as_eliminator] protected lemma cases_on {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P n) → P a := roption.induction_on @[simp] lemma top_add (x : enat) : ⊤ + x = ⊤ := roption.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp, norm_cast] lemma coe_zero : ((0 : ℕ) : enat) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℕ) : enat) = 1 := rfl @[simp, norm_cast] lemma coe_add (x y : ℕ) : ((x + y : ℕ) : enat) = x + y := roption.ext' (and_true _).symm (λ _ _, rfl) @[simp, norm_cast] lemma get_coe {x : ℕ} : get (x : enat) true.intro = x := rfl lemma coe_add_get {x : ℕ} {y : enat} (h : ((x : enat) + y).dom) : get ((x : enat) + y) h = x + get y h.2 := rfl @[simp] lemma get_add {x y : enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] lemma coe_get {x : enat} (h : x.dom) : (x.get h : enat) = x := roption.ext' (iff_of_true trivial h) (λ _ _, rfl) @[simp] lemma get_zero (h : (0 : enat).dom) : (0 : enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : enat).dom) : (1 : enat).get h = 1 := rfl lemma dom_of_le_some {x : enat} {y : ℕ} : x ≤ y → x.dom := λ ⟨h, _⟩, h trivial instance : partial_order enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_refl _⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, roption.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } @[simp, norm_cast] lemma coe_le_coe {x y : ℕ} : (x : enat) ≤ y ↔ x ≤ y := ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ @[simp, norm_cast] lemma coe_lt_coe {x y : ℕ} : (x : enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] lemma get_le_get {x y : enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} instance semilattice_sup_bot : semilattice_sup_bot enat := { sup := (⊔), bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩, le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..enat.partial_order } instance order_top : order_top enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩, ..enat.semilattice_sup_bot } lemma top_eq_none : (⊤ : enat) = none := rfl lemma coe_lt_top (x : ℕ) : (x : enat) < ⊤ := lt_of_le_of_ne le_top (λ h, absurd (congr_arg dom h) true_ne_false) @[simp] lemma coe_ne_top (x : ℕ) : (x : enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma ne_top_iff {x : enat} : x ≠ ⊤ ↔ ∃(n : ℕ), x = n := roption.ne_none_iff lemma ne_top_iff_dom {x : enat} : x ≠ ⊤ ↔ x.dom := by classical; exact not_iff_comm.1 roption.eq_none_iff'.symm lemma ne_top_of_lt {x y : enat} (h : x < y) : x ≠ ⊤ := ne_of_lt $ lt_of_lt_of_le h le_top lemma pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x := enat.cases_on x ⟨λ _, le_top, λ _, coe_lt_top _⟩ (λ n, ⟨λ h, enat.coe_le_coe.2 (enat.coe_lt_coe.1 h), λ h, enat.coe_lt_coe.2 (enat.coe_le_coe.1 h)⟩) noncomputable instance : decidable_linear_order enat := { le_total := λ x y, enat.cases_on x (or.inr le_top) (enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))), decidable_le := classical.dec_rel _, ..enat.partial_order } noncomputable instance : bounded_lattice enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..enat.order_top, ..enat.semilattice_sup_bot } lemma sup_eq_max {a b : enat} : a ⊔ b = max a b := le_antisymm (sup_le (le_max_left _ _) (le_max_right _ _)) (max_le le_sup_left le_sup_right) lemma inf_eq_min {a b : enat} : a ⊓ b = min a b := rfl instance : ordered_add_comm_monoid enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro trivial (h₁ h.2), λ _, add_le_add_left (h₂ _) c⟩), lt_of_add_lt_add_left := λ a b c, enat.cases_on a (λ h, by simpa [lt_irrefl] using h) (λ a, enat.cases_on b (λ h, absurd h (not_lt_of_ge (by rw add_top; exact le_top))) (λ b, enat.cases_on c (λ _, coe_lt_top _) (λ c h, coe_lt_coe.2 (by rw [← coe_add, ← coe_add, coe_lt_coe] at h; exact lt_of_add_lt_add_left h)))), ..enat.decidable_linear_order, ..enat.add_comm_monoid } instance : canonically_ordered_add_monoid enat := { le_iff_exists_add := λ a b, enat.cases_on b (iff_of_true le_top ⟨⊤, (add_top _).symm⟩) (λ b, enat.cases_on a (iff_of_false (not_le_of_gt (coe_lt_top _)) (not_exists.2 (λ x, ne_of_lt (by rw [top_add]; exact coe_lt_top _)))) (λ a, ⟨λ h, ⟨(b - a : ℕ), by rw [← coe_add, coe_inj, add_comm, nat.sub_add_cancel (coe_le_coe.1 h)]⟩, (λ ⟨c, hc⟩, enat.cases_on c (λ hc, hc.symm ▸ show (a : enat) ≤ a + ⊤, by rw [add_top]; exact le_top) (λ c (hc : (b : enat) = a + c), coe_le_coe.2 (by rw [← coe_add, coe_inj] at hc; rw hc; exact nat.le_add_right _ _)) hc)⟩)), ..enat.semilattice_sup_bot, ..enat.ordered_add_comm_monoid } protected lemma add_lt_add_right {x y z : enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := begin rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, rcases ne_top_iff.mp hz with ⟨k, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply_mod_cast coe_lt_top }, norm_cast at h, apply_mod_cast add_lt_add_right h end protected lemma add_lt_add_iff_right {x y z : enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, λ h, enat.add_lt_add_right h hz⟩ protected lemma add_lt_add_iff_left {x y z : enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, enat.add_lt_add_iff_right hz] protected lemma lt_add_iff_pos_right {x y : enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by { conv_rhs { rw [← enat.add_lt_add_iff_left hx] }, rw [add_zero] } lemma lt_add_one {x : enat} (hx : x ≠ ⊤) : x < x + 1 := by { rw [enat.lt_add_iff_pos_right hx], norm_cast, norm_num } lemma le_of_lt_add_one {x y : enat} (h : x < y + 1) : x ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h end lemma add_one_le_of_lt {x y : enat} (h : x < y) : x + 1 ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h end lemma add_one_le_iff_lt {x y : enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := begin split, swap, exact add_one_le_of_lt, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, apply coe_lt_top, apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h end lemma lt_add_one_iff_lt {x y : enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := begin split, exact le_of_lt_add_one, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply coe_lt_top }, apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h end lemma add_eq_top_iff {a b : enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by apply enat.cases_on a; apply enat.cases_on b; simp; simp only [(enat.coe_add _ _).symm, enat.coe_ne_top]; simp protected lemma add_right_cancel_iff {a b c : enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := begin rcases ne_top_iff.1 hc with ⟨c, rfl⟩, apply enat.cases_on a; apply enat.cases_on b; simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : enat)]; simp only [(enat.coe_add _ _).symm, add_left_cancel_iff, enat.coe_inj, add_comm]; tauto end protected lemma add_left_cancel_iff {a b c : enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, enat.add_right_cancel_iff ha] section with_top /-- Computably converts an `enat` to a `with_top ℕ`. -/ def to_with_top (x : enat) [decidable x.dom]: with_top ℕ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' {h : decidable (⊤ : enat).dom} : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' {h : decidable (0 : enat).dom}: to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_coe (n : ℕ) : to_with_top n = n := rfl @[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : enat).dom} : to_with_top (n : enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := enat.cases_on y (by simp) (enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := by simp only [lt_iff_le_not_le, to_with_top_le] end with_top section with_top_equiv open_locale classical /-- Order isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_equiv : enat ≃ with_top ℕ := { to_fun := λ x, to_with_top x, inv_fun := λ x, match x with (some n) := coe n | none := ⊤ end, left_inv := λ x, by apply enat.cases_on x; intros; simp; refl, right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl } @[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n := to_with_top_coe' _ @[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 := with_top_equiv_coe _ @[simp] lemma with_top_equiv_le {x y : enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] lemma with_top_equiv_lt {x y : enat} : with_top_equiv x < with_top_equiv y ↔ x < y := to_with_top_lt @[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ := rfl @[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n := rfl @[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 := rfl @[simp] lemma with_top_equiv_symm_le {x y : with_top ℕ} : with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y := by rw ← with_top_equiv_le; simp @[simp] lemma with_top_equiv_symm_lt {x y : with_top ℕ} : with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y := by rw ← with_top_equiv_lt; simp end with_top_equiv lemma lt_wf : well_founded ((<) : enat → enat → Prop) := show well_founded (λ a b : enat, a < b), by haveI := classical.dec; simp only [to_with_top_lt.symm] {eta := ff}; exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) instance : has_well_founded enat := ⟨(<), lt_wf⟩ end enat
9e3a3a057f5b48875c2e723512ce89af79628d8c
0003047346476c031128723dfd16fe273c6bc605
/src/group_theory/quotient_group.lean
70dc027f2b35033a6a5dac3e948c61fe94918b3f
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,540
lean
/- Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot. This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl. -/ import group_theory.coset universes u v namespace quotient_group variables {G : Type u} [group G] (N : set G) [normal_subgroup N] {H : Type v} [group H] instance : group (quotient N) := { one := (1 : G), mul := λ a b, quotient.lift_on₂' a b (λ a b, ((a * b : G) : quotient N)) (λ a₁ a₂ b₁ b₂ hab₁ hab₂, quot.sound ((is_subgroup.mul_mem_cancel_left N (is_subgroup.inv_mem hab₂)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact normal_subgroup.normal _ hab₁ _))), mul_assoc := λ a b c, quotient.induction_on₃' a b c (λ a b c, congr_arg mk (mul_assoc a b c)), one_mul := λ a, quotient.induction_on' a (λ a, congr_arg mk (one_mul a)), mul_one := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_one a)), inv := λ a, quotient.lift_on' a (λ a, ((a⁻¹ : G) : quotient N)) (λ a b hab, quotient.sound' begin show a⁻¹⁻¹ * b⁻¹ ∈ N, rw ← mul_inv_rev, exact is_subgroup.inv_mem (is_subgroup.mem_norm_comm hab) end), mul_left_inv := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_left_inv a)) } attribute [to_additive quotient_add_group.add_group._proof_6] quotient_group.group._proof_6 attribute [to_additive quotient_add_group.add_group._proof_5] quotient_group.group._proof_5 attribute [to_additive quotient_add_group.add_group._proof_4] quotient_group.group._proof_4 attribute [to_additive quotient_add_group.add_group._proof_3] quotient_group.group._proof_3 attribute [to_additive quotient_add_group.add_group._proof_2] quotient_group.group._proof_2 attribute [to_additive quotient_add_group.add_group._proof_1] quotient_group.group._proof_1 attribute [to_additive quotient_add_group.add_group] quotient_group.group attribute [to_additive quotient_add_group.quotient.equations._eqn_1] quotient_group.quotient.equations._eqn_1 attribute [to_additive quotient_add_group.add_group.equations._eqn_1] quotient_group.group.equations._eqn_1 instance : is_group_hom (mk : G → quotient N) := ⟨λ _ _, rfl⟩ attribute [to_additive quotient_add_group.is_add_group_hom] quotient_group.is_group_hom attribute [to_additive quotient_add_group.is_add_group_hom.equations._eqn_1] quotient_group.is_group_hom.equations._eqn_1 instance {G : Type*} [comm_group G] (s : set G) [is_subgroup s] : comm_group (quotient s) := { mul_comm := λ a b, quotient.induction_on₂' a b (λ a b, congr_arg mk (mul_comm a b)), ..@quotient_group.group _ _ s (normal_subgroup_of_comm_group s) } attribute [to_additive quotient_add_group.add_comm_group._proof_6] quotient_group.comm_group._proof_6 attribute [to_additive quotient_add_group.add_comm_group._proof_5] quotient_group.comm_group._proof_5 attribute [to_additive quotient_add_group.add_comm_group._proof_4] quotient_group.comm_group._proof_4 attribute [to_additive quotient_add_group.add_comm_group._proof_3] quotient_group.comm_group._proof_3 attribute [to_additive quotient_add_group.add_comm_group._proof_2] quotient_group.comm_group._proof_2 attribute [to_additive quotient_add_group.add_comm_group._proof_1] quotient_group.comm_group._proof_1 attribute [to_additive quotient_add_group.add_comm_group] quotient_group.comm_group attribute [to_additive quotient_add_group.add_comm_group.equations._eqn_1] quotient_group.comm_group.equations._eqn_1 @[simp] lemma coe_one : ((1 : G) : quotient N) = 1 := rfl @[simp] lemma coe_mul (a b : G) : ((a * b : G) : quotient N) = a * b := rfl @[simp] lemma coe_inv (a : G) : ((a⁻¹ : G) : quotient N) = a⁻¹ := rfl @[simp] lemma coe_pow (a : G) (n : ℕ) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.pow _ _ _ _ mk _ a n attribute [to_additive quotient_add_group.coe_zero] coe_one attribute [to_additive quotient_add_group.coe_add] coe_mul attribute [to_additive quotient_add_group.coe_neg] coe_inv @[simp] lemma coe_gpow (a : G) (n : ℤ) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.gpow _ _ _ _ mk _ a n local notation ` Q ` := quotient N def lift (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (q : Q) : H := q.lift_on' φ $ assume a b (hab : a⁻¹ * b ∈ N), (calc φ a = φ a * 1 : by simp ... = φ a * φ (a⁻¹ * b) : by rw HN (a⁻¹ * b) hab ... = φ (a * (a⁻¹ * b)) : by rw is_group_hom.mul φ a (a⁻¹ * b) ... = φ b : by simp) attribute [to_additive quotient_add_group.lift._proof_1] lift._proof_1 attribute [to_additive quotient_add_group.lift] lift attribute [to_additive quotient_add_group.lift.equations._eqn_1] lift.equations._eqn_1 @[simp] lemma lift_mk {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (g : Q) = φ g := rfl attribute [to_additive quotient_add_group.lift_mk] lift_mk @[simp] lemma lift_mk' {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (mk g : Q) = φ g := rfl attribute [to_additive quotient_add_group.lift_mk'] lift_mk' def map (M : set H) [normal_subgroup M] (f : G → H) [is_group_hom f] (h : N ⊆ f ⁻¹' M) : quotient N → quotient M := begin haveI : is_group_hom ((mk : H → quotient M) ∘ f) := is_group_hom.comp _ _, refine quotient_group.lift N (mk ∘ f) _, assume x hx, refine quotient_group.eq.2 _, rw [mul_one, is_subgroup.inv_mem_iff], exact h hx, end attribute [to_additive quotient_add_group.map._proof_1] map._proof_1 attribute [to_additive quotient_add_group.map._proof_2] map._proof_2 attribute [to_additive quotient_add_group.map] map variables (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1) instance is_group_hom_quotient_lift : is_group_hom (lift N φ HN) := ⟨λ q r, quotient.induction_on₂' q r $ λ a b, show φ (a * b) = φ a * φ b, from is_group_hom.mul φ a b⟩ attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift] quotient_group.is_group_hom_quotient_lift attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift.equations._eqn_1] quotient_group.is_group_hom_quotient_lift.equations._eqn_1 @[to_additive quotient_add_group.map_is_add_group_hom] instance map_is_group_hom (M : set H) [normal_subgroup M] (f : G → H) [is_group_hom f] (h : N ⊆ f ⁻¹' M) : is_group_hom (map N M f h) := quotient_group.is_group_hom_quotient_lift _ _ _ open function is_group_hom /-- The induced map from the quotient by the kernel to the codomain. -/ def ker_lift : quotient (ker φ) → H := lift _ φ $ λ g, (mem_ker φ).mp attribute [to_additive quotient_add_group.ker_lift._proof_1] quotient_group.ker_lift._proof_1 attribute [to_additive quotient_add_group.ker_lift._proof_2] quotient_group.ker_lift._proof_2 attribute [to_additive quotient_add_group.ker_lift] quotient_group.ker_lift attribute [to_additive quotient_add_group.ker_lift.equations._eqn_1] quotient_group.ker_lift.equations._eqn_1 @[simp, to_additive quotient_add_group.ker_lift_mk] lemma ker_lift_mk (g : G) : (ker_lift φ) g = φ g := lift_mk _ _ _ @[simp, to_additive quotient_add_group.ker_lift_mk'] lemma ker_lift_mk' (g : G) : (ker_lift φ) (mk g) = φ g := lift_mk' _ _ _ @[to_additive quotient_add_group.ker_lift_is_add_group_hom] instance ker_lift_is_group_hom : is_group_hom (ker_lift φ) := quotient_group.is_group_hom_quotient_lift _ _ _ @[to_additive quotient_add_group.injective_ker_lift] lemma injective_ker_lift : injective (ker_lift φ) := assume a b, quotient.induction_on₂' a b $ assume a b (h : φ a = φ b), quotient.sound' $ show a⁻¹ * b ∈ ker φ, by rw [mem_ker φ, is_group_hom.mul φ, ← h, is_group_hom.inv φ, inv_mul_self] --@[to_additive quotient_add_group.quotient_ker_equiv_range] noncomputable def quotient_ker_equiv_range : (quotient (ker φ)) ≃ set.range φ := @equiv.of_bijective _ (set.range φ) (λ x, ⟨lift (ker φ) φ (by simp [mem_ker]) x, by exact quotient.induction_on' x (λ x, ⟨x, rfl⟩)⟩) ⟨λ a b h, injective_ker_lift _ (subtype.mk.inj h), λ ⟨x, y, hy⟩, ⟨mk y, subtype.eq hy⟩⟩ noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) : (quotient (ker φ)) ≃ H := calc (quotient_group.quotient (is_group_hom.ker φ)) ≃ set.range φ : quotient_ker_equiv_range _ ... ≃ H : ⟨λ a, a.1, λ b, ⟨b, hφ b⟩, λ ⟨_, _⟩, rfl, λ _, rfl⟩ end quotient_group namespace quotient_add_group open is_add_group_hom variables {G : Type u} [_root_.add_group G] (N : set G) [normal_add_subgroup N] {H : Type v} [_root_.add_group H] variables (φ : G → H) [_root_.is_add_group_hom φ] noncomputable def quotient_ker_equiv_range : (quotient (ker φ)) ≃ set.range φ := @quotient_group.quotient_ker_equiv_range (multiplicative G) _ (multiplicative H) _ φ _ noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) : (quotient (ker φ)) ≃ H := @quotient_group.quotient_ker_equiv_of_surjective (multiplicative G) _ (multiplicative H) _ φ _ hφ attribute [to_additive quotient_add_group.quotient_ker_equiv_range] quotient_group.quotient_ker_equiv_range attribute [to_additive quotient_add_group.quotient_ker_equiv_of_surjective] quotient_group.quotient_ker_equiv_of_surjective end quotient_add_group
761ce0d7084aec204bcda735015d073d207fc7c5
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/tactic/basic.lean
992a7a881268e5019cf1097ec5242084a0c61f00
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
29,939
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import data.dlist.basic category.basic meta.expr meta.rb_map namespace expr open tactic attribute [derive has_reflect] binder_info protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /- only traverses the direct descendents -/ meta def {u} traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) end expr namespace interaction_monad open result meta def get_result {σ α} (tac : interaction_monad σ α) : interaction_monad σ (interaction_monad.result σ α) | s := match tac s with | r@(success _ s') := success r s' | r@(exception _ _ s') := success r s' end end interaction_monad namespace lean.parser open lean interaction_monad.result meta def of_tactic' {α} (tac : tactic α) : parser α := do r ← of_tactic (interaction_monad.get_result tac), match r with | (success a _) := return a | (exception f pos _) := exception f pos end -- Override the builtin `lean.parser.of_tactic` coe, which is broken. -- (See test/tactics.lean for a failure case.) @[priority 2000] meta instance has_coe' {α} : has_coe (tactic α) (parser α) := ⟨of_tactic'⟩ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left -- Emit a source code string at the location being parsed. meta def emit_code_here : string → lean.parser unit | str := do left ← emit_command_here str, if left.length = 0 then return () else emit_code_here left end lean.parser namespace tactic meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α -- `mk_fresh_name` returns identifiers starting with underscores, -- which are not legal when emitted by tactic programs. Turn the -- useful source of random names provided by `mk_fresh_name` into -- names which are usable by tactic programs. -- -- The returned name has four components. meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ meta def is_simp_lemma : name → tactic bool := succeeds ∘ tactic.has_attribute `simp meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file' e d.to_name then s.insert d.to_name d else s), pure xs meta def simp_lemmas_from_file : tactic name_set := do s ← local_decls, let s := s.map (expr.list_constant ∘ declaration.value), xs ← s.to_list.mmap ((<$>) name_set.of_list ∘ mfilter tactic.is_simp_lemma ∘ name_set.to_list ∘ prod.snd), return $ name_set.filter (xs.foldl name_set.union mk_name_set) (λ x, ¬ s.contains x) meta def file_simp_attribute_decl (attr : name) : tactic unit := do s ← simp_lemmas_from_file, trace format!"run_cmd mk_simp_attr `{attr}", let lmms := format.join $ list.intersperse " " $ s.to_list.map to_fmt, trace format!"local attribute [{attr}] {lmms}" meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) meta def local_def_value (e : expr) : tactic expr := do do (v,_) ← solve_aux `(true) (do (expr.elet n t v _) ← (revert e >> target) | fail format!"{e} is not a local definition", return v), return v meta def check_defn (n : name) (e : pexpr) : tactic unit := do (declaration.defn _ _ _ d _ _) ← get_decl n, e' ← to_expr e, guard (d =ₐ e') <|> trace d >> failed -- meta def compile_eqn (n : name) (univ : list name) (args : list expr) (val : expr) (num : ℕ) : tactic unit := -- do let lhs := (expr.const n $ univ.map level.param).mk_app args, -- stmt ← mk_app `eq [lhs,val], -- let vs := stmt.list_local_const, -- let stmt := stmt.pis vs, -- (_,pr) ← solve_aux stmt (tactic.intros >> reflexivity), -- add_decl $ declaration.thm (n <.> "equations" <.> to_string (format!"_eqn_{num}")) univ stmt (pure pr) meta def to_implicit : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map to_implicit <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least m times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) end instance_cache /-- Reset the instance cache for the main goal. -/ meta def reset_instance_cache : tactic unit := unfreeze_local_instances meta def match_head (e : expr) : expr → tactic unit | e' := unify e e' <|> do `(_ → %%e') ← whnf e', v ← mk_mvar, match_head (e'.instantiate_var v) meta def find_matching_head : expr → list expr → tactic (list expr) | e [] := return [] | e (H :: Hs) := do t ← infer_type H, ((::) H <$ match_head e t <|> pure id) <*> find_matching_head e Hs meta def subst_locals (s : list (expr × expr)) (e : expr) : expr := (e.abstract_locals (s.map (expr.local_uniq_name ∘ prod.fst)).reverse).instantiate_vars (s.map prod.snd) meta def set_binder : expr → list binder_info → expr | e [] := e | (expr.pi v _ d b) (bi :: bs) := expr.pi v bi d (set_binder b bs) | e _ := e meta def last_explicit_arg : expr → tactic expr | (expr.app f e) := do t ← infer_type f >>= whnf, if t.binding_info = binder_info.default then pure e else last_explicit_arg f | e := pure e private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of the given (Pi-)type -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of the given function -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity /-- variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] meta def drop_binders : expr → tactic expr | (expr.pi n bi t b) := b.instantiate_var <$> mk_local' n bi t >>= drop_binders | e := pure e meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, [c] ← pure $ env.constructors_of struct_n | fail "too many constructors", vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do e ← mk_const (n.update_prefix struct_n) >>= infer_type >>= drop_binders, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) open nat meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /--`iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /--`iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /--`apply_list l`: try to apply the tactics in the list `l` on the first goal, and fail if none succeeds -/ meta def apply_list_expr : list expr → tactic unit | [] := fail "no matching rule" | (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t /-- constructs a list of expressions given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list.-/ meta def build_list_expr_for_apply : list pexpr → tactic (list expr) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← list.mmap mk_const l, return (m.append tail)) <|> return (a::tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times -/ meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit := do l ← build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l) meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' meta def symm_apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := tactic.apply e cfg <|> (symmetry >> tactic.apply e cfg) meta def apply_assumption (asms : tactic (list expr) := local_context) (tac : tactic unit := skip) : tactic unit := do { ctx ← asms, ctx.any_of (λ H, symm_apply H >> tac) } <|> do { exfalso, ctx ← asms, ctx.any_of (λ H, symm_apply H >> tac) } <|> fail "assumption tactic failed" meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- assuming olde and newe are defeq when elaborated, replaces occurences of olde with newe at hypothesis h. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), change_core repl_tp (some h) open nat meta def solve_by_elim_aux (discharger : tactic unit) (asms : tactic (list expr)) : ℕ → tactic unit | 0 := done | (succ n) := discharger <|> (apply_assumption asms $ solve_by_elim_aux n) meta structure by_elim_opt := (discharger : tactic unit := done) (assumptions : tactic (list expr) := local_context) (max_rep : ℕ := 3) meta def solve_by_elim (opt : by_elim_opt := { }) : tactic unit := do tactic.fail_if_no_goals, focus1 $ solve_by_elim_aux opt.discharger opt.assumptions opt.max_rep meta def metavariables : tactic (list expr) := do r ← result, pure (r.list_meta_vars) /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do goals ← get_goals, p ← is_proof goals.head, guard p meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} private meta def iterate_aux (t : tactic α) : list α → tactic (list α) | L := (do r ← t, iterate_aux (r :: L)) <|> return L /-- Apply a tactic as many times as possible, collecting the results in a list. -/ meta def iterate' (t : tactic α) : tactic (list α) := list.reverse <$> iterate_aux t [] /-- Like iterate', but fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (α × list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate' t, return (r, L) meta def intros1 : tactic (list expr) := iterate1 intro1 >>= λ p, return (p.1 :: p.2) /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Return target after instantiating metavars and whnf -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | tactic.fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] meta def note_anon (e : expr) : tactic unit := do n ← get_unused_name "lh", note n none e, skip /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, prod.snd <$> solve_aux t' assumption /-- `dependent_pose_core l`: introduce dependent hypothesis, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), t ← target, new_goal ← mk_meta_var (t.pis lc), old::other_goals ← get_goals, set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- like `mk_local_pis` but translating into weak head normal form before checking if it is a Π. -/ meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do (expr.pi n bi d b) ← whnf e | return ([], e), p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) /-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g` -/ meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do t ← infer_type h, (ctxt, t) ← mk_local_pis_whnf t, `(@Exists %%α %%p) ← whnf t transparency.all | fail "expected a term of the shape ∀xs, ∃a, p xs a", α_t ← infer_type α, expr.sort u ← whnf α_t transparency.all, value ← mk_local_def data (α.pis ctxt), t' ← head_beta (p.app (value.mk_app ctxt)), spec ← mk_local_def spec (t'.pis ctxt), dependent_pose_core [ (value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt), (spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)], try (tactic.clear h), intro1, intro1 /-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`, an a final hypothesis on `p as` -/ meta def choose : expr → list name → tactic unit | h [] := fail "expect list of variables" | h [n] := do cnt ← revert h, intro n, intron (cnt - 1), return () | h (n::ns) := do v ← get_unused_name >>= choose1 h n, choose v ns /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ``` instance : monad id := {! !} ``` invoking hole command `Instance Stub` produces: ``` instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := list.intersperse (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {format.join fs} }", return [(out,"")] } meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis, let vs := vs.filter (λ v, is_default_local v), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ``` meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command `Match Stub` produces: ``` meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } /-- Hole command used to generate a `match` expression. In the following: ``` meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` invoking hole command `Equations Stub` produces: ``` meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking `Equations Stub` on the following: ``` meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ``` meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } /-- This command lists the constructors that can be used to satisfy the expected type. When used in the following hole: ``` def foo : ℤ ⊕ ℕ := {! !} ``` the command will produce: ``` def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ``` sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← mk_local_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, pure format!"\n{c} : {t}\n" }, let fs := list.intersperse (", " : format) $ cs.map to_fmt, let out := format.to_string format!"{{! {format.join fs} !}", trace (format.join ts).to_string, return [(out,"")] } meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure (add_prime lmm), add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm tt lmm', copy_attribute `functor_norm lmm tt lmm' } attribute [higher_order map_comp_pure] map_pure private meta def tactic.use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> tactic.use_aux) meta def tactic.use (l : list pexpr) : tactic unit := focus1 $ l.mmap' $ λ h, tactic.use_aux h <|> fail format!"failed to instantiate goal with {h}" meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux end tactic
b43d085067a185a895340e92d9f814d38fee581f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/representation_theory/invariants.lean
5a9380d2cc6c30b858e928e6e8ba54f5e283bee0
[ "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
5,764
lean
/- Copyright (c) 2022 Antoine Labelle. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Labelle -/ import representation_theory.basic import representation_theory.fdRep /-! # Subspace of invariants a group representation > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file introduces the subspace of invariants of a group representation and proves basic results about it. The main tool used is the average of all elements of the group, seen as an element of `monoid_algebra k G`. The action of this special element gives a projection onto the subspace of invariants. In order for the definition of the average element to make sense, we need to assume for most of the results that the order of `G` is invertible in `k` (e. g. `k` has characteristic `0`). -/ open_locale big_operators open monoid_algebra open representation namespace group_algebra variables (k G : Type*) [comm_semiring k] [group G] variables [fintype G] [invertible (fintype.card G : k)] /-- The average of all elements of the group `G`, considered as an element of `monoid_algebra k G`. -/ noncomputable def average : monoid_algebra k G := ⅟(fintype.card G : k) • ∑ g : G, of k G g /-- `average k G` is invariant under left multiplication by elements of `G`. -/ @[simp] theorem mul_average_left (g : G) : (finsupp.single g 1 * average k G : monoid_algebra k G) = average k G := begin simp only [mul_one, finset.mul_sum, algebra.mul_smul_comm, average, monoid_algebra.of_apply, finset.sum_congr, monoid_algebra.single_mul_single], set f : G → monoid_algebra k G := λ x, finsupp.single x 1, show ⅟ ↑(fintype.card G) • ∑ (x : G), f (g * x) = ⅟ ↑(fintype.card G) • ∑ (x : G), f x, rw function.bijective.sum_comp (group.mul_left_bijective g) _, end /-- `average k G` is invariant under right multiplication by elements of `G`. -/ @[simp] theorem mul_average_right (g : G) : average k G * finsupp.single g 1 = average k G := begin simp only [mul_one, finset.sum_mul, algebra.smul_mul_assoc, average, monoid_algebra.of_apply, finset.sum_congr, monoid_algebra.single_mul_single], set f : G → monoid_algebra k G := λ x, finsupp.single x 1, show ⅟ ↑(fintype.card G) • ∑ (x : G), f (x * g) = ⅟ ↑(fintype.card G) • ∑ (x : G), f x, rw function.bijective.sum_comp (group.mul_right_bijective g) _, end end group_algebra namespace representation section invariants open group_algebra variables {k G V : Type*} [comm_semiring k] [group G] [add_comm_monoid V] [module k V] variables (ρ : representation k G V) /-- The subspace of invariants, consisting of the vectors fixed by all elements of `G`. -/ def invariants : submodule k V := { carrier := set_of (λ v, ∀ (g : G), ρ g v = v), zero_mem' := λ g, by simp only [map_zero], add_mem' := λ v w hv hw g, by simp only [hv g, hw g, map_add], smul_mem' := λ r v hv g, by simp only [hv g, linear_map.map_smulₛₗ, ring_hom.id_apply]} @[simp] lemma mem_invariants (v : V) : v ∈ invariants ρ ↔ ∀ (g: G), ρ g v = v := by refl lemma invariants_eq_inter : (invariants ρ).carrier = ⋂ g : G, function.fixed_points (ρ g) := by {ext, simp [function.is_fixed_pt]} variables [fintype G] [invertible (fintype.card G : k)] /-- The action of `average k G` gives a projection map onto the subspace of invariants. -/ @[simp] noncomputable def average_map : V →ₗ[k] V := as_algebra_hom ρ (average k G) /-- The `average_map` sends elements of `V` to the subspace of invariants. -/ theorem average_map_invariant (v : V) : average_map ρ v ∈ invariants ρ := λ g, by rw [average_map, ←as_algebra_hom_single_one, ←linear_map.mul_apply, ←map_mul (as_algebra_hom ρ), mul_average_left] /-- The `average_map` acts as the identity on the subspace of invariants. -/ theorem average_map_id (v : V) (hv : v ∈ invariants ρ) : average_map ρ v = v := begin rw mem_invariants at hv, simp [average, map_sum, hv, finset.card_univ, nsmul_eq_smul_cast k _ v, smul_smul], end theorem is_proj_average_map : linear_map.is_proj ρ.invariants ρ.average_map := ⟨ρ.average_map_invariant, ρ.average_map_id⟩ end invariants namespace lin_hom universes u open category_theory Action section Rep variables {k : Type u} [comm_ring k] {G : Group.{u}} lemma mem_invariants_iff_comm {X Y : Rep k G} (f : X.V →ₗ[k] Y.V) (g : G) : (lin_hom X.ρ Y.ρ) g f = f ↔ f.comp (X.ρ g) = (Y.ρ g).comp f := begin dsimp, erw [←ρ_Aut_apply_inv], rw [←linear_map.comp_assoc, ←Module.comp_def, ←Module.comp_def, iso.inv_comp_eq, ρ_Aut_apply_hom], exact comm, end /-- The invariants of the representation `lin_hom X.ρ Y.ρ` correspond to the the representation homomorphisms from `X` to `Y` -/ @[simps] def invariants_equiv_Rep_hom (X Y : Rep k G) : (lin_hom X.ρ Y.ρ).invariants ≃ₗ[k] (X ⟶ Y) := { to_fun := λ f, ⟨f.val, λ g, (mem_invariants_iff_comm _ g).1 (f.property g)⟩, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl, inv_fun := λ f, ⟨f.hom, λ g, (mem_invariants_iff_comm _ g).2 (f.comm g)⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, by { ext, refl } } end Rep section fdRep variables {k : Type u} [field k] {G : Group.{u}} /-- The invariants of the representation `lin_hom X.ρ Y.ρ` correspond to the the representation homomorphisms from `X` to `Y` -/ def invariants_equiv_fdRep_hom (X Y : fdRep k G) : (lin_hom X.ρ Y.ρ).invariants ≃ₗ[k] (X ⟶ Y) := begin rw [←fdRep.forget₂_ρ, ←fdRep.forget₂_ρ], exact (lin_hom.invariants_equiv_Rep_hom _ _) ≪≫ₗ (fdRep.forget₂_hom_linear_equiv X Y), end end fdRep end lin_hom end representation
24146c27be5ffeb9760fb6cb46e5db3e0db41ab7
82e44445c70db0f03e30d7be725775f122d72f3e
/src/field_theory/polynomial_galois_group.lean
958d2d7b82544a50c36a6d27ddf81b86c0913b93
[ "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
21,485
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import analysis.complex.polynomial import field_theory.galois import group_theory.perm.cycle_type import ring_theory.eisenstein_criterion /-! # Galois Groups of Polynomials In this file, we introduce the Galois group of a polynomial `p` over a field `F`, defined as the automorphism group of its splitting field. We also provide some results about some extension `E` above `p.splitting_field`, and some specific results about the Galois groups of ℚ-polynomials with specific numbers of non-real roots. ## Main definitions - `polynomial.gal p`: the Galois group of a polynomial p. - `polynomial.gal.restrict p E`: the restriction homomorphism `(E ≃ₐ[F] E) → gal p`. - `polynomial.gal.gal_action p E`: the action of `gal p` on the roots of `p` in `E`. ## Main results - `polynomial.gal.restrict_smul`: `restrict p E` is compatible with `gal_action p E`. - `polynomial.gal.gal_action_hom_injective`: `gal p` acting on the roots of `p` in `E` is faithful. - `polynomial.gal.restrict_prod_injective`: `gal (p * q)` embeds as a subgroup of `gal p × gal q`. - `polynomial.gal.card_of_separable`: For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. - `polynomial.gal.gal_action_hom_bijective_of_prime_degree`: An irreducible polynomial of prime degree with two non-real roots has full Galois group. ## Other results - `polynomial.gal.card_complex_roots_eq_card_real_add_card_not_gal_inv`: The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ noncomputable theory open_locale classical open finite_dimensional namespace polynomial variables {F : Type*} [field F] (p q : polynomial F) (E : Type*) [field E] [algebra F E] /-- The Galois group of a polynomial. -/ @[derive [has_coe_to_fun, group, fintype]] def gal := p.splitting_field ≃ₐ[F] p.splitting_field namespace gal @[ext] lemma ext {σ τ : p.gal} (h : ∀ x ∈ p.root_set p.splitting_field, σ x = τ x) : σ = τ := begin refine alg_equiv.ext (λ x, (alg_hom.mem_equalizer σ.to_alg_hom τ.to_alg_hom x).mp ((set_like.ext_iff.mp _ x).mpr algebra.mem_top)), rwa [eq_top_iff, ←splitting_field.adjoin_roots, algebra.adjoin_le_iff], end /-- If `p` splits in `F` then the `p.gal` is trivial. -/ def unique_gal_of_splits (h : p.splits (ring_hom.id F)) : unique p.gal := { default := 1, uniq := λ f, alg_equiv.ext (λ x, by { obtain ⟨y, rfl⟩ := algebra.mem_bot.mp ((set_like.ext_iff.mp ((is_splitting_field.splits_iff _ p).mp h) x).mp algebra.mem_top), rw [alg_equiv.commutes, alg_equiv.commutes] }) } instance [h : fact (p.splits (ring_hom.id F))] : unique p.gal := unique_gal_of_splits _ (h.1) instance unique_gal_zero : unique (0 : polynomial F).gal := unique_gal_of_splits _ (splits_zero _) instance unique_gal_one : unique (1 : polynomial F).gal := unique_gal_of_splits _ (splits_one _) instance unique_gal_C (x : F) : unique (C x).gal := unique_gal_of_splits _ (splits_C _ _) instance unique_gal_X : unique (X : polynomial F).gal := unique_gal_of_splits _ (splits_X _) instance unique_gal_X_sub_C (x : F) : unique (X - C x).gal := unique_gal_of_splits _ (splits_X_sub_C _) instance unique_gal_X_pow (n : ℕ) : unique (X ^ n : polynomial F).gal := unique_gal_of_splits _ (splits_X_pow _ _) instance [h : fact (p.splits (algebra_map F E))] : algebra p.splitting_field E := (is_splitting_field.lift p.splitting_field p h.1).to_ring_hom.to_algebra instance [h : fact (p.splits (algebra_map F E))] : is_scalar_tower F p.splitting_field E := is_scalar_tower.of_algebra_map_eq (λ x, ((is_splitting_field.lift p.splitting_field p h.1).commutes x).symm) /-- Restrict from a superfield automorphism into a member of `gal p`. -/ def restrict [fact (p.splits (algebra_map F E))] : (E ≃ₐ[F] E) →* p.gal := alg_equiv.restrict_normal_hom p.splitting_field lemma restrict_surjective [fact (p.splits (algebra_map F E))] [normal F E] : function.surjective (restrict p E) := alg_equiv.restrict_normal_hom_surjective E section roots_action /-- The function taking `roots p p.splitting_field` to `roots p E`. This is actually a bijection, see `polynomial.gal.map_roots_bijective`. -/ def map_roots [fact (p.splits (algebra_map F E))] : root_set p p.splitting_field → root_set p E := λ x, ⟨is_scalar_tower.to_alg_hom F p.splitting_field E x, begin have key := subtype.mem x, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw [mem_root_set h, aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩ lemma map_roots_bijective [h : fact (p.splits (algebra_map F E))] : function.bijective (map_roots p E) := begin split, { exact λ _ _ h, subtype.ext (ring_hom.injective _ (subtype.ext_iff.mp h)) }, { intro y, -- this is just an equality of two different ways to write the roots of `p` as an `E`-polynomial have key := roots_map (is_scalar_tower.to_alg_hom F p.splitting_field E : p.splitting_field →+* E) ((splits_id_iff_splits _).mpr (is_splitting_field.splits p.splitting_field p)), rw [map_map, alg_hom.comp_algebra_map] at key, have hy := subtype.mem y, simp only [root_set, finset.mem_coe, multiset.mem_to_finset, key, multiset.mem_map] at hy, rcases hy with ⟨x, hx1, hx2⟩, exact ⟨⟨x, multiset.mem_to_finset.mpr hx1⟩, subtype.ext hx2⟩ } end /-- The bijection between `root_set p p.splitting_field` and `root_set p E`. -/ def roots_equiv_roots [fact (p.splits (algebra_map F E))] : (root_set p p.splitting_field) ≃ (root_set p E) := equiv.of_bijective (map_roots p E) (map_roots_bijective p E) instance gal_action_aux : mul_action p.gal (root_set p p.splitting_field) := { smul := λ ϕ x, ⟨ϕ x, begin have key := subtype.mem x, --simp only [root_set, finset.mem_coe, multiset.mem_to_finset] at *, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw mem_root_set h, change aeval (ϕ.to_alg_hom x) p = 0, rw [aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩, one_smul := λ _, by { ext, refl }, mul_smul := λ _ _ _, by { ext, refl } } /-- The action of `gal p` on the roots of `p` in `E`. -/ instance gal_action [fact (p.splits (algebra_map F E))] : mul_action p.gal (root_set p E) := { smul := λ ϕ x, roots_equiv_roots p E (ϕ • ((roots_equiv_roots p E).symm x)), one_smul := λ _, by simp only [equiv.apply_symm_apply, one_smul], mul_smul := λ _ _ _, by simp only [equiv.apply_symm_apply, equiv.symm_apply_apply, mul_smul] } variables {p E} /-- `polynomial.gal.restrict p E` is compatible with `polynomial.gal.gal_action p E`. -/ @[simp] lemma restrict_smul [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑((restrict p E ϕ) • x) = ϕ x := begin let ψ := alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F p.splitting_field E), change ↑(ψ (ψ.symm _)) = ϕ x, rw alg_equiv.apply_symm_apply ψ, change ϕ (roots_equiv_roots p E ((roots_equiv_roots p E).symm x)) = ϕ x, rw equiv.apply_symm_apply (roots_equiv_roots p E), end variables (p E) /-- `polynomial.gal.gal_action` as a permutation representation -/ def gal_action_hom [fact (p.splits (algebra_map F E))] : p.gal →* equiv.perm (root_set p E) := { to_fun := λ ϕ, equiv.mk (λ x, ϕ • x) (λ x, ϕ⁻¹ • x) (λ x, inv_smul_smul ϕ x) (λ x, smul_inv_smul ϕ x), map_one' := by { ext1 x, exact mul_action.one_smul x }, map_mul' := λ x y, by { ext1 z, exact mul_action.mul_smul x y z } } lemma gal_action_hom_restrict [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑(gal_action_hom p E (restrict p E ϕ) x) = ϕ x := restrict_smul ϕ x /-- `gal p` embeds as a subgroup of permutations of the roots of `p` in `E`. -/ lemma gal_action_hom_injective [fact (p.splits (algebra_map F E))] : function.injective (gal_action_hom p E) := begin rw monoid_hom.injective_iff, intros ϕ hϕ, ext x hx, have key := equiv.perm.ext_iff.mp hϕ (roots_equiv_roots p E ⟨x, hx⟩), change roots_equiv_roots p E (ϕ • (roots_equiv_roots p E).symm (roots_equiv_roots p E ⟨x, hx⟩)) = roots_equiv_roots p E ⟨x, hx⟩ at key, rw equiv.symm_apply_apply at key, exact subtype.ext_iff.mp (equiv.injective (roots_equiv_roots p E) key), end end roots_action variables {p q} /-- `polynomial.gal.restrict`, when both fields are splitting fields of polynomials. -/ def restrict_dvd (hpq : p ∣ q) : q.gal →* p.gal := if hq : q = 0 then 1 else @restrict F _ p _ _ _ ⟨splits_of_splits_of_dvd (algebra_map F q.splitting_field) hq (splitting_field.splits q) hpq⟩ lemma restrict_dvd_surjective (hpq : p ∣ q) (hq : q ≠ 0) : function.surjective (restrict_dvd hpq) := by simp only [restrict_dvd, dif_neg hq, restrict_surjective] variables (p q) /-- The Galois group of a product maps into the product of the Galois groups. -/ def restrict_prod : (p * q).gal →* p.gal × q.gal := monoid_hom.prod (restrict_dvd (dvd_mul_right p q)) (restrict_dvd (dvd_mul_left q p)) /-- `polynomial.gal.restrict_prod` is actually a subgroup embedding. -/ lemma restrict_prod_injective : function.injective (restrict_prod p q) := begin by_cases hpq : (p * q) = 0, { haveI : unique (p * q).gal := by { rw hpq, apply_instance }, exact λ f g h, eq.trans (unique.eq_default f) (unique.eq_default g).symm }, intros f g hfg, dsimp only [restrict_prod, restrict_dvd] at hfg, simp only [dif_neg hpq, monoid_hom.prod_apply, prod.mk.inj_iff] at hfg, ext x hx, rw [root_set, map_mul, polynomial.roots_mul] at hx, cases multiset.mem_add.mp (multiset.mem_to_finset.mp hx) with h h, { haveI : fact (p.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_right p q)⟩, have key : x = algebra_map (p.splitting_field) (p * q).splitting_field ((roots_equiv_roots p _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots p _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.1 _) }, { haveI : fact (q.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_left q p)⟩, have key : x = algebra_map (q.splitting_field) (p * q).splitting_field ((roots_equiv_roots q _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots q _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.2 _) }, { rwa [ne.def, mul_eq_zero, map_eq_zero, map_eq_zero, ←mul_eq_zero] } end lemma mul_splits_in_splitting_field_of_mul {p₁ q₁ p₂ q₂ : polynomial F} (hq₁ : q₁ ≠ 0) (hq₂ : q₂ ≠ 0) (h₁ : p₁.splits (algebra_map F q₁.splitting_field)) (h₂ : p₂.splits (algebra_map F q₂.splitting_field)) : (p₁ * p₂).splits (algebra_map F (q₁ * q₂).splitting_field) := begin apply splits_mul, { rw ← (splitting_field.lift q₁ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_right q₁ q₂))).comp_algebra_map, exact splits_comp_of_splits _ _ h₁, }, { rw ← (splitting_field.lift q₂ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_left q₂ q₁))).comp_algebra_map, exact splits_comp_of_splits _ _ h₂, }, end /-- `p` splits in the splitting field of `p ∘ q`, for `q` non-constant. -/ lemma splits_in_splitting_field_of_comp (hq : q.nat_degree ≠ 0) : p.splits (algebra_map F (p.comp q).splitting_field) := begin let P : polynomial F → Prop := λ r, r.splits (algebra_map F (r.comp q).splitting_field), have key1 : ∀ {r : polynomial F}, irreducible r → P r, { intros r hr, by_cases hr' : nat_degree r = 0, { exact splits_of_nat_degree_le_one _ (le_trans (le_of_eq hr') zero_le_one) }, obtain ⟨x, hx⟩ := exists_root_of_splits _ (splitting_field.splits (r.comp q)) (λ h, hr' ((mul_eq_zero.mp (nat_degree_comp.symm.trans (nat_degree_eq_of_degree_eq_some h))).resolve_right hq)), rw [←aeval_def, aeval_comp] at hx, have h_normal : normal F (r.comp q).splitting_field := splitting_field.normal (r.comp q), have qx_int := normal.is_integral h_normal (aeval x q), exact splits_of_splits_of_dvd _ (minpoly.ne_zero qx_int) (normal.splits h_normal _) (dvd_symm_of_irreducible (minpoly.irreducible qx_int) hr (minpoly.dvd F _ hx)) }, have key2 : ∀ {p₁ p₂ : polynomial F}, P p₁ → P p₂ → P (p₁ * p₂), { intros p₁ p₂ hp₁ hp₂, by_cases h₁ : p₁.comp q = 0, { cases comp_eq_zero_iff.mp h₁ with h h, { rw [h, zero_mul], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, by_cases h₂ : p₂.comp q = 0, { cases comp_eq_zero_iff.mp h₂ with h h, { rw [h, mul_zero], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, have key := mul_splits_in_splitting_field_of_mul h₁ h₂ hp₁ hp₂, rwa ← mul_comp at key }, exact wf_dvd_monoid.induction_on_irreducible p (splits_zero _) (λ _, splits_of_is_unit _) (λ _ _ _ h, key2 (key1 h)), end /-- `polynomial.gal.restrict` for the composition of polynomials. -/ def restrict_comp (hq : q.nat_degree ≠ 0) : (p.comp q).gal →* p.gal := @restrict F _ p _ _ _ ⟨splits_in_splitting_field_of_comp p q hq⟩ lemma restrict_comp_surjective (hq : q.nat_degree ≠ 0) : function.surjective (restrict_comp p q hq) := by simp only [restrict_comp, restrict_surjective] variables {p q} /-- For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. -/ lemma card_of_separable (hp : p.separable) : fintype.card p.gal = finrank F p.splitting_field := begin haveI : is_galois F p.splitting_field := is_galois.of_separable_splitting_field hp, exact is_galois.card_aut_eq_finrank F p.splitting_field, end lemma prime_degree_dvd_card [char_zero F] (p_irr : irreducible p) (p_deg : p.nat_degree.prime) : p.nat_degree ∣ fintype.card p.gal := begin rw gal.card_of_separable p_irr.separable, have hp : p.degree ≠ 0 := λ h, nat.prime.ne_zero p_deg (nat_degree_eq_zero_iff_degree_le_zero.mpr (le_of_eq h)), let α : p.splitting_field := root_of_splits (algebra_map F p.splitting_field) (splitting_field.splits p) hp, have hα : is_integral F α := (is_algebraic_iff_is_integral F).mp (algebra.is_algebraic_of_finite α), use finite_dimensional.finrank F⟮α⟯ p.splitting_field, suffices : (minpoly F α).nat_degree = p.nat_degree, { rw [←finite_dimensional.finrank_mul_finrank F F⟮α⟯ p.splitting_field, intermediate_field.adjoin.finrank hα, this] }, suffices : minpoly F α ∣ p, { have key := dvd_symm_of_irreducible (minpoly.irreducible hα) p_irr this, apply le_antisymm, { exact nat_degree_le_of_dvd this p_irr.ne_zero }, { exact nat_degree_le_of_dvd key (minpoly.ne_zero hα) } }, apply minpoly.dvd F α, rw [aeval_def, map_root_of_splits _ (splitting_field.splits p) hp], end section rationals lemma splits_ℚ_ℂ {p : polynomial ℚ} : fact (p.splits (algebra_map ℚ ℂ)) := ⟨is_alg_closed.splits_codomain p⟩ local attribute [instance] splits_ℚ_ℂ /-- The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ lemma card_complex_roots_eq_card_real_add_card_not_gal_inv (p : polynomial ℚ) : (p.root_set ℂ).to_finset.card = (p.root_set ℝ).to_finset.card + (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card := begin by_cases hp : p = 0, { simp_rw [hp, root_set_zero, set.to_finset_eq_empty_iff.mpr rfl, finset.card_empty, zero_add], refine eq.symm (nat.le_zero_iff.mp ((finset.card_le_univ _).trans (le_of_eq _))), simp_rw [hp, root_set_zero, fintype.card_eq_zero_iff], apply_instance }, have inj : function.injective (is_scalar_tower.to_alg_hom ℚ ℝ ℂ) := (algebra_map ℝ ℂ).injective, rw [←finset.card_image_of_injective _ subtype.coe_injective, ←finset.card_image_of_injective _ inj], let a : finset ℂ := _, let b : finset ℂ := _, let c : finset ℂ := _, change a.card = b.card + c.card, have ha : ∀ z : ℂ, z ∈ a ↔ aeval z p = 0 := λ z, by rw [set.mem_to_finset, mem_root_set hp], have hb : ∀ z : ℂ, z ∈ b ↔ aeval z p = 0 ∧ z.im = 0, { intro z, simp_rw [finset.mem_image, exists_prop, set.mem_to_finset, mem_root_set hp], split, { rintros ⟨w, hw, rfl⟩, exact ⟨by rw [aeval_alg_hom_apply, hw, alg_hom.map_zero], rfl⟩ }, { rintros ⟨hz1, hz2⟩, have key : is_scalar_tower.to_alg_hom ℚ ℝ ℂ z.re = z := by { ext, refl, rw hz2, refl }, exact ⟨z.re, inj (by rwa [←aeval_alg_hom_apply, key, alg_hom.map_zero]), key⟩ } }, have hc0 : ∀ w : p.root_set ℂ, gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ)) w = w ↔ w.val.im = 0, { intro w, rw [subtype.ext_iff, gal_action_hom_restrict], exact complex.eq_conj_iff_im }, have hc : ∀ z : ℂ, z ∈ c ↔ aeval z p = 0 ∧ z.im ≠ 0, { intro z, simp_rw [finset.mem_image, exists_prop], split, { rintros ⟨w, hw, rfl⟩, exact ⟨(mem_root_set hp).mp w.2, mt (hc0 w).mpr (equiv.perm.mem_support.mp hw)⟩ }, { rintros ⟨hz1, hz2⟩, exact ⟨⟨z, (mem_root_set hp).mpr hz1⟩, equiv.perm.mem_support.mpr (mt (hc0 _).mp hz2), rfl⟩ } }, rw ← finset.card_disjoint_union, { apply congr_arg finset.card, simp_rw [finset.ext_iff, finset.mem_union, ha, hb, hc], tauto }, { intro z, rw [finset.inf_eq_inter, finset.mem_inter, hb, hc], tauto }, { apply_instance }, end /-- An irreducible polynomial of prime degree with two non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree {p : polynomial ℚ} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots : fintype.card (p.root_set ℂ) = fintype.card (p.root_set ℝ) + 2) : function.bijective (gal_action_hom p ℂ) := begin have h1 : fintype.card (p.root_set ℂ) = p.nat_degree, { simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots], { exact is_alg_closed.splits_codomain p }, { exact nodup_roots ((separable_map (algebra_map ℚ ℂ)).mpr p_irr.separable) } }, have h2 : fintype.card p.gal = fintype.card (gal_action_hom p ℂ).range := fintype.card_congr (monoid_hom.of_injective (gal_action_hom_injective p ℂ)).to_equiv, let conj := restrict p ℂ (complex.conj_ae.restrict_scalars ℚ), refine ⟨gal_action_hom_injective p ℂ, λ x, (congr_arg (has_mem.mem x) (show (gal_action_hom p ℂ).range = ⊤, from _)).mpr (subgroup.mem_top x)⟩, apply equiv.perm.subgroup_eq_top_of_swap_mem, { rwa h1 }, { rw h1, convert prime_degree_dvd_card p_irr p_deg using 1, convert h2.symm }, { exact ⟨conj, rfl⟩ }, { rw ← equiv.perm.card_support_eq_two, apply nat.add_left_cancel, rw [←p_roots, ←set.to_finset_card (root_set p ℝ), ←set.to_finset_card (root_set p ℂ)], exact (card_complex_roots_eq_card_real_add_card_not_gal_inv p).symm }, end /-- An irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree' {p : polynomial ℚ} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots1 : fintype.card (p.root_set ℝ) + 1 ≤ fintype.card (p.root_set ℂ)) (p_roots2 : fintype.card (p.root_set ℂ) ≤ fintype.card (p.root_set ℝ) + 3) : function.bijective (gal_action_hom p ℂ) := begin apply gal_action_hom_bijective_of_prime_degree p_irr p_deg, let n := (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card, have hn : 2 ∣ n := equiv.perm.two_dvd_card_support (by rw [←monoid_hom.map_pow, ←monoid_hom.map_pow, show alg_equiv.restrict_scalars ℚ complex.conj_ae ^ 2 = 1, from alg_equiv.ext complex.conj_conj, monoid_hom.map_one, monoid_hom.map_one]), have key := card_complex_roots_eq_card_real_add_card_not_gal_inv p, simp_rw [set.to_finset_card] at key, rw [key, add_le_add_iff_left] at p_roots1 p_roots2, rw [key, add_right_inj], suffices : ∀ m : ℕ, 2 ∣ m → 1 ≤ m → m ≤ 3 → m = 2, { exact this n hn p_roots1 p_roots2 }, rintros m ⟨k, rfl⟩ h2 h3, exact le_antisymm (nat.lt_succ_iff.mp (lt_of_le_of_ne h3 (show 2 * k ≠ 2 * 1 + 1, from nat.two_mul_ne_two_mul_add_one))) (nat.succ_le_iff.mpr (lt_of_le_of_ne h2 (show 2 * 0 + 1 ≠ 2 * k, from nat.two_mul_ne_two_mul_add_one.symm))), end end rationals end gal end polynomial
04d6a1b97cc09dff2b68d4fe13017e0aac73ea14
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/dual_auto.lean
1fd7230a7c997db2e2681cf89ba0331d7f731116
[]
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
9,806
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Frédéric Dupuis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.normed_space.hahn_banach import Mathlib.analysis.normed_space.inner_product import Mathlib.PostPort universes u_1 u_2 u v namespace Mathlib /-! # The topological dual of a normed space In this file we define the topological dual of a normed space, and the bounded linear map from a normed space into its double dual. We also prove that, for base field `𝕜` with `[is_R_or_C 𝕜]`, this map is an isometry. We then consider inner product spaces, with base field over `ℝ` (the corresponding results for `ℂ` will require the definition of conjugate-linear maps). We define `to_dual_map`, a continuous linear map from `E` to its dual, which maps an element `x` of the space to `λ y, ⟪x, y⟫`. We check (`to_dual_map_isometry`) that this map is an isometry onto its image, and particular is injective. We also define `to_dual'` as the function taking taking a vector to its dual for a base field `𝕜` with `[is_R_or_C 𝕜]`; this is a function and not a linear map. Finally, under the hypothesis of completeness (i.e., for Hilbert spaces), we prove the Fréchet-Riesz representation (`to_dual_map_eq_top`), which states the surjectivity: every element of the dual of a Hilbert space `E` has the form `λ u, ⟪x, u⟫` for some `x : E`. This permits the map `to_dual_map` to be upgraded to an (isometric) continuous linear equivalence, `to_dual`, between a Hilbert space and its dual. ## References * [M. Einsiedler and T. Ward, *Functional Analysis, Spectral Theory, and Applications*] [EinsiedlerWard2017] ## Tags dual, Fréchet-Riesz -/ namespace normed_space /-- The topological dual of a normed space `E`. -/ def dual (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] := continuous_linear_map 𝕜 E 𝕜 protected instance dual.inhabited (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] : Inhabited (dual 𝕜 E) := { default := 0 } /-- The inclusion of a normed space in its double (topological) dual. -/ def inclusion_in_double_dual' (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] (x : E) : dual 𝕜 (dual 𝕜 E) := linear_map.mk_continuous (linear_map.mk (fun (f : dual 𝕜 E) => coe_fn f x) sorry sorry) (norm x) sorry @[simp] theorem dual_def (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] (x : E) (f : dual 𝕜 E) : coe_fn (inclusion_in_double_dual' 𝕜 E x) f = coe_fn f x := rfl theorem double_dual_bound (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] (x : E) : norm (inclusion_in_double_dual' 𝕜 E x) ≤ norm x := sorry /-- The inclusion of a normed space in its double (topological) dual, considered as a bounded linear map. -/ def inclusion_in_double_dual (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] : continuous_linear_map 𝕜 E (dual 𝕜 (dual 𝕜 E)) := linear_map.mk_continuous (linear_map.mk (fun (x : E) => inclusion_in_double_dual' 𝕜 E x) sorry sorry) 1 sorry /-- If one controls the norm of every `f x`, then one controls the norm of `x`. Compare `continuous_linear_map.op_norm_le_bound`. -/ theorem norm_le_dual_bound {𝕜 : Type v} [is_R_or_C 𝕜] {E : Type u} [normed_group E] [normed_space 𝕜 E] (x : E) {M : ℝ} (hMp : 0 ≤ M) (hM : ∀ (f : dual 𝕜 E), norm (coe_fn f x) ≤ M * norm f) : norm x ≤ M := sorry /-- The inclusion of a normed space in its double dual is an isometry onto its image.-/ theorem inclusion_in_double_dual_isometry {𝕜 : Type v} [is_R_or_C 𝕜] {E : Type u} [normed_group E] [normed_space 𝕜 E] (x : E) : norm (coe_fn (inclusion_in_double_dual 𝕜 E) x) = norm x := sorry end normed_space namespace inner_product_space /-- Given some `x` in an inner product space, we can define its dual as the continuous linear map `λ y, ⟪x, y⟫`. Consider using `to_dual` or `to_dual_map` instead in the real case. -/ def to_dual' (𝕜 : Type u_1) {E : Type u_2} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] : E →+ normed_space.dual 𝕜 E := add_monoid_hom.mk (fun (x : E) => linear_map.mk_continuous (linear_map.mk (fun (y : E) => inner x y) sorry sorry) (norm x) sorry) sorry sorry @[simp] theorem to_dual'_apply (𝕜 : Type u_1) {E : Type u_2} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] {x : E} {y : E} : coe_fn (coe_fn (to_dual' 𝕜) x) y = inner x y := rfl /-- In an inner product space, the norm of the dual of a vector `x` is `∥x∥` -/ @[simp] theorem norm_to_dual'_apply (𝕜 : Type u_1) {E : Type u_2} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] (x : E) : norm (coe_fn (to_dual' 𝕜) x) = norm x := sorry theorem to_dual'_isometry (𝕜 : Type u_1) (E : Type u_2) [is_R_or_C 𝕜] [inner_product_space 𝕜 E] : isometry ⇑(to_dual' 𝕜) := add_monoid_hom.isometry_of_norm (to_dual' 𝕜) (norm_to_dual'_apply 𝕜) /-- Fréchet-Riesz representation: any `ℓ` in the dual of a Hilbert space `E` is of the form `λ u, ⟪y, u⟫` for some `y : E`, i.e. `to_dual'` is surjective. -/ theorem to_dual'_surjective (𝕜 : Type u_1) (E : Type u_2) [is_R_or_C 𝕜] [inner_product_space 𝕜 E] [complete_space E] : function.surjective ⇑(to_dual' 𝕜) := sorry /-- In a real inner product space `F`, the function that takes a vector `x` in `F` to its dual `λ y, ⟪x, y⟫` is a continuous linear map. If the space is complete (i.e. is a Hilbert space), consider using `to_dual` instead. -/ -- TODO extend to `is_R_or_C` (requires a definition of conjugate linear maps) def to_dual_map {F : Type u_1} [inner_product_space ℝ F] : continuous_linear_map ℝ F (normed_space.dual ℝ F) := linear_map.mk_continuous (linear_map.mk ⇑(to_dual' ℝ) sorry sorry) 1 sorry @[simp] theorem to_dual_map_apply {F : Type u_1} [inner_product_space ℝ F] {x : F} {y : F} : coe_fn (coe_fn to_dual_map x) y = inner x y := rfl /-- In an inner product space, the norm of the dual of a vector `x` is `∥x∥` -/ @[simp] theorem norm_to_dual_map_apply {F : Type u_1} [inner_product_space ℝ F] (x : F) : norm (coe_fn to_dual_map x) = norm x := norm_to_dual'_apply ℝ x theorem to_dual_map_isometry {F : Type u_1} [inner_product_space ℝ F] : isometry ⇑to_dual_map := add_monoid_hom.isometry_of_norm (to_dual' ℝ) norm_to_dual_map_apply theorem to_dual_map_injective {F : Type u_1} [inner_product_space ℝ F] : function.injective ⇑to_dual_map := isometry.injective to_dual_map_isometry @[simp] theorem ker_to_dual_map {F : Type u_1} [inner_product_space ℝ F] : continuous_linear_map.ker to_dual_map = ⊥ := iff.mpr linear_map.ker_eq_bot to_dual_map_injective @[simp] theorem to_dual_map_eq_iff_eq {F : Type u_1} [inner_product_space ℝ F] {x : F} {y : F} : coe_fn to_dual_map x = coe_fn to_dual_map y ↔ x = y := function.injective.eq_iff (iff.mp linear_map.ker_eq_bot ker_to_dual_map) /-- Fréchet-Riesz representation: any `ℓ` in the dual of a real Hilbert space `F` is of the form `λ u, ⟪y, u⟫` for some `y` in `F`. See `inner_product_space.to_dual` for the continuous linear equivalence thus induced. -/ -- TODO extend to `is_R_or_C` (requires a definition of conjugate linear maps) theorem range_to_dual_map {F : Type u_1} [inner_product_space ℝ F] [complete_space F] : continuous_linear_map.range to_dual_map = ⊤ := iff.mpr linear_map.range_eq_top (to_dual'_surjective ℝ F) /-- Fréchet-Riesz representation: If `F` is a Hilbert space, the function that takes a vector in `F` to its dual is a continuous linear equivalence. -/ def to_dual {F : Type u_1} [inner_product_space ℝ F] [complete_space F] : continuous_linear_equiv ℝ F (normed_space.dual ℝ F) := continuous_linear_equiv.of_isometry (continuous_linear_map.to_linear_map to_dual_map) to_dual_map_isometry range_to_dual_map /-- Fréchet-Riesz representation: If `F` is a Hilbert space, the function that takes a vector in `F` to its dual is an isometry. -/ def isometric.to_dual {F : Type u_1} [inner_product_space ℝ F] [complete_space F] : F ≃ᵢ normed_space.dual ℝ F := isometric.mk (linear_equiv.to_equiv (continuous_linear_equiv.to_linear_equiv to_dual)) (to_dual'_isometry ℝ F) @[simp] theorem to_dual_apply {F : Type u_1} [inner_product_space ℝ F] [complete_space F] {x : F} {y : F} : coe_fn (coe_fn to_dual x) y = inner x y := rfl @[simp] theorem to_dual_eq_iff_eq {F : Type u_1} [inner_product_space ℝ F] [complete_space F] {x : F} {y : F} : coe_fn to_dual x = coe_fn to_dual y ↔ x = y := function.injective.eq_iff (continuous_linear_equiv.injective to_dual) theorem to_dual_eq_iff_eq' {F : Type u_1} [inner_product_space ℝ F] [complete_space F] {x : F} {x' : F} : (∀ (y : F), inner x y = inner x' y) ↔ x = x' := sorry @[simp] theorem norm_to_dual_apply {F : Type u_1} [inner_product_space ℝ F] [complete_space F] (x : F) : norm (coe_fn to_dual x) = norm x := norm_to_dual_map_apply x /-- In a Hilbert space, the norm of a vector in the dual space is the norm of its corresponding primal vector. -/ theorem norm_to_dual_symm_apply {F : Type u_1} [inner_product_space ℝ F] [complete_space F] (ℓ : normed_space.dual ℝ F) : norm (coe_fn (continuous_linear_equiv.symm to_dual) ℓ) = norm ℓ := sorry end Mathlib
ca182afeb7783b2f99568fbc79116ade16eab609
d9ed0fce1c218297bcba93e046cb4e79c83c3af8
/tests/lean/run/equation_with_values.lean
8cd7fe34066b9f61a1bd3fd015399e853bed6d69
[ "Apache-2.0" ]
permissive
leodemoura/lean_clone
005c63aa892a6492f2d4741ee3c2cb07a6be9d7f
cc077554b584d39bab55c360bc12a6fe7957afe6
refs/heads/master
1,610,506,475,484
1,482,348,354,000
1,482,348,543,000
77,091,586
0
0
null
null
null
null
UTF-8
Lean
false
false
903
lean
def f : char → nat | #"a" := 0 | #"b" := 1 | #"c" := 2 | #"d" := 3 | #"e" := 4 | _ := 5 check f.equations.eqn_1 check f.equations.eqn_2 check f.equations.eqn_3 check f.equations.eqn_4 check f.equations.eqn_5 check f.equations.eqn_6 def g : nat → nat | 100000 := 0 | 200000 := 1 | 300000 := 2 | 400000 := 3 | _ := 5 check g.equations.eqn_1 check g.equations.eqn_2 check g.equations.eqn_3 check g.equations.eqn_4 check g.equations.eqn_5 def h : string → nat | "hello" := 0 | "world" := 1 | "bla" := 2 | "boo" := 3 | _ := 5 check h.equations.eqn_1 check h.equations.eqn_2 check h.equations.eqn_3 check h.equations.eqn_4 check h.equations.eqn_5 def r : string × string → nat | ("hello", "world") := 0 | ("world", "hello") := 1 | _ := 2 check r.equations.eqn_1 check r.equations.eqn_2 check r.equations.eqn_3 check r.equations.eqn_4 check r.equations.eqn_5
88720bc678d610ea1349ffc0f3f8009a304ae00d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/sign.lean
99bde85fc7a58aff4ce69b3e287257da31c679b6
[ "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
13,219
lean
/- Copyright (c) 2022 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import algebra.big_operators.order import data.fintype.big_operators import data.int.lemmas import tactic.derive_fintype /-! # Sign function This file defines the sign function for types with zero and a decidable less-than relation, and proves some basic theorems about it. -/ /-- The type of signs. -/ @[derive [decidable_eq, inhabited, fintype]] inductive sign_type | zero | neg | pos namespace sign_type instance : has_zero sign_type := ⟨zero⟩ instance : has_one sign_type := ⟨pos⟩ instance : has_neg sign_type := ⟨λ s, match s with | neg := pos | zero := zero | pos := neg end⟩ @[simp] lemma zero_eq_zero : zero = 0 := rfl @[simp] lemma neg_eq_neg_one : neg = -1 := rfl @[simp] lemma pos_eq_one : pos = 1 := rfl instance : has_mul sign_type := ⟨λ x y, match x with | neg := -y | zero := zero | pos := y end⟩ /-- The less-than relation on signs. -/ inductive le : sign_type → sign_type → Prop | of_neg (a) : le neg a | zero : le zero zero | of_pos (a) : le a pos instance : has_le sign_type := ⟨le⟩ instance : decidable_rel le := λ a b, by cases a; cases b; exact is_false (by rintro ⟨⟩) <|> exact is_true (by constructor) /- We can define a `field` instance on `sign_type`, but it's not mathematically sensible, so we only define the `comm_group_with_zero`. -/ instance : comm_group_with_zero sign_type := { zero := 0, one := 1, mul := (*), inv := id, mul_zero := λ a, by cases a; refl, zero_mul := λ a, by cases a; refl, mul_one := λ a, by cases a; refl, one_mul := λ a, by cases a; refl, mul_inv_cancel := λ a ha, by cases a; trivial, mul_comm := λ a b, by casesm* _; refl, mul_assoc := λ a b c, by casesm* _; refl, exists_pair_ne := ⟨0, 1, by rintro ⟨⟩⟩, inv_zero := rfl } instance : linear_order sign_type := { le := (≤), le_refl := λ a, by cases a; constructor, le_total := λ a b, by casesm* _; dec_trivial, le_antisymm := λ a b ha hb, by casesm* _; refl, le_trans := λ a b c hab hbc, by casesm* _; constructor, decidable_le := le.decidable_rel } instance : bounded_order sign_type := { top := 1, le_top := le.of_pos, bot := -1, bot_le := le.of_neg } instance : has_distrib_neg sign_type := { neg_neg := λ x, by cases x; refl, neg_mul := λ x y, by casesm* _; refl, mul_neg := λ x y, by casesm* _; refl, ..sign_type.has_neg } /-- `sign_type` is equivalent to `fin 3`. -/ def fin3_equiv : sign_type ≃* fin 3 := { to_fun := λ a, a.rec_on 0 (-1) 1, inv_fun := λ a, match a with | ⟨0, h⟩ := 0 | ⟨1, h⟩ := 1 | ⟨2, h⟩ := -1 | ⟨n+3, h⟩ := (h.not_le le_add_self).elim end, left_inv := λ a, by cases a; refl, right_inv := λ a, match a with | ⟨0, h⟩ := rfl | ⟨1, h⟩ := rfl | ⟨2, h⟩ := rfl | ⟨n+3, h⟩ := (h.not_le le_add_self).elim end, map_mul' := λ x y, by casesm* _; refl } section case_bashing lemma nonneg_iff {a : sign_type} : 0 ≤ a ↔ a = 0 ∨ a = 1 := by dec_trivial! lemma nonneg_iff_ne_neg_one {a : sign_type} : 0 ≤ a ↔ a ≠ -1 := by dec_trivial! lemma neg_one_lt_iff {a : sign_type} : -1 < a ↔ 0 ≤ a := by dec_trivial! lemma nonpos_iff {a : sign_type} : a ≤ 0 ↔ a = -1 ∨ a = 0 := by dec_trivial! lemma nonpos_iff_ne_one {a : sign_type} : a ≤ 0 ↔ a ≠ 1 := by dec_trivial! lemma lt_one_iff {a : sign_type} : a < 1 ↔ a ≤ 0 := by dec_trivial! @[simp] lemma neg_iff {a : sign_type} : a < 0 ↔ a = -1 := by dec_trivial! @[simp] lemma le_neg_one_iff {a : sign_type} : a ≤ -1 ↔ a = -1 := le_bot_iff @[simp] lemma pos_iff {a : sign_type} : 0 < a ↔ a = 1 := by dec_trivial! @[simp] lemma one_le_iff {a : sign_type} : 1 ≤ a ↔ a = 1 := top_le_iff @[simp] lemma neg_one_le (a : sign_type) : -1 ≤ a := bot_le @[simp] lemma le_one (a : sign_type) : a ≤ 1 := le_top @[simp] lemma not_lt_neg_one (a : sign_type) : ¬ a < -1 := not_lt_bot @[simp] lemma not_one_lt (a : sign_type) : ¬ 1 < a := not_top_lt @[simp] lemma self_eq_neg_iff (a : sign_type) : a = -a ↔ a = 0 := by dec_trivial! @[simp] lemma neg_eq_self_iff (a : sign_type) : -a = a ↔ a = 0 := by dec_trivial! @[simp] lemma neg_one_lt_one : (-1 : sign_type) < 1 := bot_lt_top end case_bashing section cast variables {α : Type*} [has_zero α] [has_one α] [has_neg α] /-- Turn a `sign_type` into zero, one, or minus one. This is a coercion instance, but note it is only a `has_coe_t` instance: see note [use has_coe_t]. -/ def cast : sign_type → α | zero := 0 | pos := 1 | neg := -1 instance : has_coe_t sign_type α := ⟨cast⟩ @[simp] lemma cast_eq_coe (a : sign_type) : (cast a : α) = a := rfl @[simp] lemma coe_zero : ↑(0 : sign_type) = (0 : α) := rfl @[simp] lemma coe_one : ↑(1 : sign_type) = (1 : α) := rfl @[simp] lemma coe_neg_one : ↑(-1 : sign_type) = (-1 : α) := rfl end cast /-- `sign_type.cast` as a `mul_with_zero_hom`. -/ @[simps] def cast_hom {α} [mul_zero_one_class α] [has_distrib_neg α] : sign_type →*₀ α := { to_fun := cast, map_zero' := rfl, map_one' := rfl, map_mul' := λ x y, by cases x; cases y; simp } lemma range_eq {α} (f : sign_type → α) : set.range f = {f zero, f neg, f pos} := begin classical, simpa only [← finset.coe_singleton, ← finset.image_singleton, ← fintype.coe_image_univ, finset.coe_image, ← set.image_insert_eq], end end sign_type variables {α : Type*} open sign_type section preorder variables [has_zero α] [preorder α] [decidable_rel ((<) : α → α → Prop)] {a : α} /-- The sign of an element is 1 if it's positive, -1 if negative, 0 otherwise. -/ def sign : α →o sign_type := ⟨λ a, if 0 < a then 1 else if a < 0 then -1 else 0, λ a b h, begin dsimp, split_ifs with h₁ h₂ h₃ h₄ _ _ h₂ h₃; try {constructor}, { cases lt_irrefl 0 (h₁.trans $ h.trans_lt h₃) }, { cases h₂ (h₁.trans_le h) }, { cases h₄ (h.trans_lt h₃) } end⟩ lemma sign_apply : sign a = ite (0 < a) 1 (ite (a < 0) (-1) 0) := rfl @[simp] lemma sign_zero : sign (0 : α) = 0 := by simp [sign_apply] @[simp] lemma sign_pos (ha : 0 < a) : sign a = 1 := by rwa [sign_apply, if_pos] @[simp] lemma sign_neg (ha : a < 0) : sign a = -1 := by rwa [sign_apply, if_neg $ asymm ha, if_pos] lemma sign_eq_one_iff : sign a = 1 ↔ 0 < a := begin refine ⟨λ h, _, λ h, sign_pos h⟩, by_contra hn, rw [sign_apply, if_neg hn] at h, split_ifs at h; simpa using h end lemma sign_eq_neg_one_iff : sign a = -1 ↔ a < 0 := begin refine ⟨λ h, _, λ h, sign_neg h⟩, rw sign_apply at h, split_ifs at h, { simpa using h }, { exact h_2 }, { simpa using h } end end preorder section linear_order variables [has_zero α] [linear_order α] {a : α} @[simp] lemma sign_eq_zero_iff : sign a = 0 ↔ a = 0 := begin refine ⟨λ h, _, λ h, h.symm ▸ sign_zero⟩, rw [sign_apply] at h, split_ifs at h; cases h, exact (le_of_not_lt h_1).eq_of_not_lt h_2 end lemma sign_ne_zero : sign a ≠ 0 ↔ a ≠ 0 := sign_eq_zero_iff.not @[simp] lemma sign_nonneg_iff : 0 ≤ sign a ↔ 0 ≤ a := begin rcases lt_trichotomy 0 a with (h|rfl|h), { simp [h, h.le] }, { simp }, { simpa [h, h.not_le] } end @[simp] lemma sign_nonpos_iff : sign a ≤ 0 ↔ a ≤ 0 := begin rcases lt_trichotomy 0 a with (h|rfl|h), { simp [h, h.not_le] }, { simp }, { simp [h, h.le] } end end linear_order section ordered_semiring variables [ordered_semiring α] [decidable_rel ((<) : α → α → Prop)] [nontrivial α] @[simp] lemma sign_one : sign (1 : α) = 1 := sign_pos zero_lt_one end ordered_semiring section linear_ordered_ring variables [linear_ordered_ring α] {a b : α} /- I'm not sure why this is necessary, see https://leanprover.zulipchat.com/#narrow/stream/ 113488-general/topic/type.20class.20inference.20issues/near/276937942 -/ local attribute [instance] linear_ordered_ring.decidable_lt lemma sign_mul (x y : α) : sign (x * y) = sign x * sign y := begin rcases lt_trichotomy x 0 with hx | hx | hx; rcases lt_trichotomy y 0 with hy | hy | hy; simp only [sign_zero, mul_zero, zero_mul, sign_pos, sign_neg, hx, hy, mul_one, neg_one_mul, neg_neg, one_mul, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, neg_zero, mul_neg_of_pos_of_neg, mul_pos] end /-- `sign` as a `monoid_with_zero_hom` for a nontrivial ordered semiring. Note that linearity is required; consider ℂ with the order `z ≤ w` iff they have the same imaginary part and `z - w ≤ 0` in the reals; then `1 + i` and `1 - i` are incomparable to zero, and thus we have: `0 * 0 = sign (1 + i) * sign (1 - i) ≠ sign 2 = 1`. (`complex.ordered_comm_ring`) -/ def sign_hom : α →*₀ sign_type := { to_fun := sign, map_zero' := sign_zero, map_one' := sign_one, map_mul' := sign_mul } lemma sign_pow (x : α) (n : ℕ) : sign (x ^ n) = (sign x) ^ n := begin change sign_hom (x ^ n) = (sign_hom x) ^ n, exact map_pow _ _ _ end end linear_ordered_ring section add_group variables [add_group α] [preorder α] [decidable_rel ((<) : α → α → Prop)] lemma left.sign_neg [covariant_class α α (+) (<)] (a : α) : sign (-a) = - sign a := begin simp_rw [sign_apply, left.neg_pos_iff, left.neg_neg_iff], split_ifs with h h', { exact false.elim (lt_asymm h h') }, { simp }, { simp }, { simp } end lemma right.sign_neg [covariant_class α α (function.swap (+)) (<)] (a : α) : sign (-a) = - sign a := begin simp_rw [sign_apply, right.neg_pos_iff, right.neg_neg_iff], split_ifs with h h', { exact false.elim (lt_asymm h h') }, { simp }, { simp }, { simp } end end add_group section linear_ordered_add_comm_group open_locale big_operators variables [linear_ordered_add_comm_group α] /- I'm not sure why this is necessary, see https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Decidable.20vs.20decidable_rel -/ local attribute [instance] linear_ordered_add_comm_group.decidable_lt lemma sign_sum {ι : Type*} {s : finset ι} {f : ι → α} (hs : s.nonempty) (t : sign_type) (h : ∀ i ∈ s, sign (f i) = t) : sign (∑ i in s, f i) = t := begin cases t, { simp_rw [zero_eq_zero, sign_eq_zero_iff] at ⊢ h, exact finset.sum_eq_zero h }, { simp_rw [neg_eq_neg_one, sign_eq_neg_one_iff] at ⊢ h, exact finset.sum_neg h hs }, { simp_rw [pos_eq_one, sign_eq_one_iff] at ⊢ h, exact finset.sum_pos h hs } end end linear_ordered_add_comm_group namespace int lemma sign_eq_sign (n : ℤ) : n.sign = _root_.sign n := begin obtain ((_ | _) | _) := n, { exact congr_arg coe sign_zero.symm }, { exact congr_arg coe (sign_pos $ int.succ_coe_nat_pos _).symm }, { exact congr_arg coe (_root_.sign_neg $ neg_succ_lt_zero _).symm } end end int open finset nat open_locale big_operators private lemma exists_signed_sum_aux [decidable_eq α] (s : finset α) (f : α → ℤ) : ∃ (β : Type u_1) (t : finset β) (sgn : β → sign_type) (g : β → α), (∀ b, g b ∈ s) ∧ t.card = ∑ a in s, (f a).nat_abs ∧ ∀ a ∈ s, (∑ b in t, if g b = a then (sgn b : ℤ) else 0) = f a := begin refine ⟨Σ a : {x // x ∈ s}, ℕ, finset.univ.sigma (λ a, range (f a).nat_abs), λ a, sign (f a.1), λ a, a.1, λ a, a.1.prop, _, _⟩, { simp [@sum_attach _ _ _ _ (λ a, (f a).nat_abs)] }, { intros x hx, simp [sum_sigma, hx, ← int.sign_eq_sign, int.sign_mul_nat_abs, mul_comm ((f _).nat_abs : ℤ), @sum_attach _ _ _ _ (λ a, ∑ j in range (f a).nat_abs, if a = x then (f a).sign else 0)] } end /-- We can decompose a sum of absolute value `n` into a sum of `n` signs. -/ lemma exists_signed_sum [decidable_eq α] (s : finset α) (f : α → ℤ) : ∃ (β : Type u_1) (_ : fintype β) (sgn : β → sign_type) (g : β → α), by exactI (∀ b, g b ∈ s) ∧ fintype.card β = ∑ a in s, (f a).nat_abs ∧ ∀ a ∈ s, (∑ b, if g b = a then (sgn b : ℤ) else 0) = f a := let ⟨β, t, sgn, g, hg, ht, hf⟩ := exists_signed_sum_aux s f in ⟨t, infer_instance, λ b, sgn b, λ b, g b, λ b, hg b, by simp [ht], λ a ha, (@sum_attach _ _ t _ (λ b, ite (g b = a) (sgn b : ℤ) 0)).trans $ hf _ ha⟩ /-- We can decompose a sum of absolute value less than `n` into a sum of at most `n` signs. -/ lemma exists_signed_sum' [nonempty α] [decidable_eq α] (s : finset α) (f : α → ℤ) (n : ℕ) (h : ∑ i in s, (f i).nat_abs ≤ n) : ∃ (β : Type u_1) (_ : fintype β) (sgn : β → sign_type) (g : β → α), by exactI (∀ b, g b ∉ s → sgn b = 0) ∧ fintype.card β = n ∧ ∀ a ∈ s, (∑ i, if g i = a then (sgn i : ℤ) else 0) = f a := begin obtain ⟨β, _, sgn, g, hg, hβ, hf⟩ := exists_signed_sum s f, resetI, refine ⟨β ⊕ fin (n - ∑ i in s, (f i).nat_abs), infer_instance, sum.elim sgn 0, sum.elim g $ classical.arbitrary _, _, by simp [hβ, h], λ a ha, by simp [hf _ ha]⟩, rintro (b | b) hb, { cases hb (hg _) }, { refl } end
be5f4581521f9b674659cccda629e7b23b0c2de5
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/theories/finite_group_theory/subgroup.lean
c2a0be65fa45146d9c7ff02c0174dcdb5dbbed90
[ "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
16,922
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import data algebra.group data open function eq.ops open set namespace coset -- semigroup coset definition section variable {A : Type} variable [s : semigroup A] include s definition lmul (a : A) := λ x, a * x definition rmul (a : A) := λ x, x * a definition l a (S : set A) := (lmul a) ' S definition r a (S : set A) := (rmul a) ' S lemma lmul_compose : ∀ (a b : A), (lmul a) ∘ (lmul b) = lmul (a*b) := take a, take b, funext (assume x, by rewrite [↑function.comp, ↑lmul, mul.assoc]) lemma rmul_compose : ∀ (a b : A), (rmul a) ∘ (rmul b) = rmul (b*a) := take a, take b, funext (assume x, by rewrite [↑function.comp, ↑rmul, mul.assoc]) lemma lcompose a b (S : set A) : l a (l b S) = l (a*b) S := calc (lmul a) ' ((lmul b) ' S) = ((lmul a) ∘ (lmul b)) ' S : image_comp ... = lmul (a*b) ' S : lmul_compose lemma rcompose a b (S : set A) : r a (r b S) = r (b*a) S := calc (rmul a) ' ((rmul b) ' S) = ((rmul a) ∘ (rmul b)) ' S : image_comp ... = rmul (b*a) ' S : rmul_compose lemma l_sub a (S H : set A) : S ⊆ H → (l a S) ⊆ (l a H) := image_subset (lmul a) definition l_same S (a b : A) := l a S = l b S definition r_same S (a b : A) := r a S = r b S lemma l_same.refl S (a : A) : l_same S a a := rfl lemma l_same.symm S (a b : A) : l_same S a b → l_same S b a := eq.symm lemma l_same.trans S (a b c : A) : l_same S a b → l_same S b c → l_same S a c := eq.trans example (S : set A) : equivalence (l_same S) := mk_equivalence (l_same S) (l_same.refl S) (l_same.symm S) (l_same.trans S) end end coset section variable {A : Type} variable [s : group A] include s definition lmul_by (a : A) := λ x, a * x definition rmul_by (a : A) := λ x, x * a definition glcoset a (H : set A) : set A := λ x, H (a⁻¹ * x) definition grcoset H (a : A) : set A := λ x, H (x * a⁻¹) end namespace group_theory namespace ops infixr `∘>`:55 := glcoset -- stronger than = (50), weaker than * (70) infixl `<∘`:55 := grcoset infixr `∘c`:55 := conj_by end ops end group_theory open group_theory.ops section variable {A : Type} variable [s : group A] include s lemma conj_inj (g : A) : injective (conj_by g) := injective_of_has_left_inverse (exists.intro (conj_by g⁻¹) take a, !conj_inv_cancel) lemma lmul_inj (a : A) : injective (lmul_by a) := take x₁ x₂ Peq, by esimp [lmul_by] at Peq; rewrite [-(inv_mul_cancel_left a x₁), -(inv_mul_cancel_left a x₂), Peq] lemma lmul_inv_on (a : A) (H : set A) : left_inv_on (lmul_by a⁻¹) (lmul_by a) H := take x Px, show a⁻¹*(a*x) = x, by rewrite inv_mul_cancel_left lemma lmul_inj_on (a : A) (H : set A) : inj_on (lmul_by a) H := inj_on_of_left_inv_on (lmul_inv_on a H) lemma glcoset_eq_lcoset a (H : set A) : a ∘> H = coset.l a H := ext begin intro x, rewrite [↑glcoset, ↑coset.l, ↑image, ↑set_of, ↑mem, ↑coset.lmul], apply iff.intro, intro P1, apply (exists.intro (a⁻¹ * x)), apply and.intro, exact P1, exact (mul_inv_cancel_left a x), show (∃ (x_1 : A), H x_1 ∧ a * x_1 = x) → H (a⁻¹ * x), from assume P2, obtain x_1 P3, from P2, have P4 : a * x_1 = x, from and.right P3, have P5 : x_1 = a⁻¹ * x, from eq_inv_mul_of_mul_eq P4, eq.subst P5 (and.left P3) end lemma grcoset_eq_rcoset a (H : set A) : H <∘ a = coset.r a H := begin rewrite [↑grcoset, ↑coset.r, ↑image, ↑coset.rmul, ↑set_of], apply ext, rewrite ↑mem, intro x, apply iff.intro, show H (x * a⁻¹) → (∃ (x_1 : A), H x_1 ∧ x_1 * a = x), from assume PH, exists.intro (x * a⁻¹) (and.intro PH (inv_mul_cancel_right x a)), show (∃ (x_1 : A), H x_1 ∧ x_1 * a = x) → H (x * a⁻¹), from assume Pex, obtain x_1 Pand, from Pex, eq.subst (eq_mul_inv_of_mul_eq (and.right Pand)) (and.left Pand) end lemma glcoset_sub a (S H : set A) : S ⊆ H → (a ∘> S) ⊆ (a ∘> H) := assume Psub, have P : _, from coset.l_sub a S H Psub, eq.symm (glcoset_eq_lcoset a S) ▸ eq.symm (glcoset_eq_lcoset a H) ▸ P lemma glcoset_compose (a b : A) (H : set A) : a ∘> b ∘> H = a*b ∘> H := begin rewrite [*glcoset_eq_lcoset], exact (coset.lcompose a b H) end lemma grcoset_compose (a b : A) (H : set A) : H <∘ a <∘ b = H <∘ a*b := begin rewrite [*grcoset_eq_rcoset], exact (coset.rcompose b a H) end lemma glcoset_id (H : set A) : 1 ∘> H = H := funext (assume x, calc (1 ∘> H) x = H (1⁻¹*x) : rfl ... = H (1*x) : {one_inv} ... = H x : {one_mul x}) lemma grcoset_id (H : set A) : H <∘ 1 = H := funext (assume x, calc H (x*1⁻¹) = H (x*1) : {one_inv} ... = H x : {mul_one x}) --lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H := -- funext (assume x, -- calc glcoset a⁻¹ (glcoset a H) x = H x : {mul_inv_cancel_left a⁻¹ x}) lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H := calc a⁻¹ ∘> a ∘> H = (a⁻¹*a) ∘> H : glcoset_compose ... = 1 ∘> H : mul.left_inv ... = H : glcoset_id lemma grcoset_inv H (a : A) : (H <∘ a) <∘ a⁻¹ = H := funext (assume x, calc grcoset (grcoset H a) a⁻¹ x = H x : {inv_mul_cancel_right x a⁻¹}) lemma glcoset_cancel a b (H : set A) : (b*a⁻¹) ∘> a ∘> H = b ∘> H := calc (b*a⁻¹) ∘> a ∘> H = b*a⁻¹*a ∘> H : glcoset_compose ... = b ∘> H : {inv_mul_cancel_right b a} lemma grcoset_cancel a b (H : set A) : H <∘ a <∘ a⁻¹*b = H <∘ b := calc H <∘ a <∘ a⁻¹*b = H <∘ a*(a⁻¹*b) : grcoset_compose ... = H <∘ b : {mul_inv_cancel_left a b} -- test how precedence breaks tie: infixr takes hold since its encountered first example a b (H : set A) : a ∘> H <∘ b = a ∘> (H <∘ b) := rfl -- should be true for semigroup as well but irrelevant lemma lcoset_rcoset_assoc a b (H : set A) : a ∘> H <∘ b = (a ∘> H) <∘ b := funext (assume x, begin esimp [glcoset, grcoset], rewrite mul.assoc end) definition mul_closed_on H := ∀ (x y : A), x ∈ H → y ∈ H → x * y ∈ H lemma closed_lcontract a (H : set A) : mul_closed_on H → a ∈ H → a ∘> H ⊆ H := begin rewrite [↑mul_closed_on, ↑glcoset, ↑subset, ↑mem], intro Pclosed, intro PHa, intro x, intro PHainvx, exact (eq.subst (mul_inv_cancel_left a x) (Pclosed a (a⁻¹*x) PHa PHainvx)) end lemma closed_rcontract a (H : set A) : mul_closed_on H → a ∈ H → H <∘ a ⊆ H := assume P1 : mul_closed_on H, assume P2 : H a, begin rewrite ↑subset, intro x, rewrite [↑grcoset, ↑mem], intro P3, exact (eq.subst (inv_mul_cancel_right x a) (P1 (x * a⁻¹) a P3 P2)) end lemma closed_lcontract_set a (H G : set A) : mul_closed_on G → H ⊆ G → a∈G → a∘>H ⊆ G := assume Pclosed, assume PHsubG, assume PainG, have PaGsubG : a ∘> G ⊆ G, from closed_lcontract a G Pclosed PainG, have PaHsubaG : a ∘> H ⊆ a ∘> G, from eq.symm (glcoset_eq_lcoset a H) ▸ eq.symm (glcoset_eq_lcoset a G) ▸ (coset.l_sub a H G PHsubG), subset.trans PaHsubaG PaGsubG definition subgroup.has_inv H := ∀ (a : A), a ∈ H → a⁻¹ ∈ H -- two ways to define the same equivalence relatiohship for subgroups definition in_lcoset [reducible] H (a b : A) := a ∈ b ∘> H definition in_rcoset [reducible] H (a b : A) := a ∈ H <∘ b definition same_lcoset [reducible] H (a b : A) := a ∘> H = b ∘> H definition same_rcoset [reducible] H (a b : A) := H <∘ a = H <∘ b definition same_left_right_coset (N : set A) := ∀ x, x ∘> N = N <∘ x structure is_subgroup [class] (H : set A) : Type := (has_one : H 1) (mul_closed : mul_closed_on H) (has_inv : subgroup.has_inv H) structure is_normal_subgroup [class] (N : set A) extends is_subgroup N := (normal : same_left_right_coset N) end section subgroup variable {A : Type} variable [s : group A] include s variable {H : set A} variable [is_subg : is_subgroup H] include is_subg section set_reducible local attribute set [reducible] lemma subg_has_one : H (1 : A) := @is_subgroup.has_one A s H is_subg lemma subg_mul_closed : mul_closed_on H := @is_subgroup.mul_closed A s H is_subg lemma subg_has_inv : subgroup.has_inv H := @is_subgroup.has_inv A s H is_subg lemma subgroup_coset_id : ∀ a, a ∈ H → (a ∘> H = H ∧ H <∘ a = H) := take a, assume PHa : H a, have Pl : a ∘> H ⊆ H, from closed_lcontract a H subg_mul_closed PHa, have Pr : H <∘ a ⊆ H, from closed_rcontract a H subg_mul_closed PHa, have PHainv : H a⁻¹, from subg_has_inv a PHa, and.intro (ext (assume x, begin esimp [glcoset, mem], apply iff.intro, apply Pl, intro PHx, exact (subg_mul_closed a⁻¹ x PHainv PHx) end)) (ext (assume x, begin esimp [grcoset, mem], apply iff.intro, apply Pr, intro PHx, exact (subg_mul_closed x a⁻¹ PHx PHainv) end)) lemma subgroup_lcoset_id : ∀ a, a ∈ H → a ∘> H = H := take a, assume PHa : H a, and.left (subgroup_coset_id a PHa) lemma subgroup_rcoset_id : ∀ a, a ∈ H → H <∘ a = H := take a, assume PHa : H a, and.right (subgroup_coset_id a PHa) lemma subg_in_coset_refl (a : A) : a ∈ a ∘> H ∧ a ∈ H <∘ a := have PH1 : H 1, from subg_has_one, have PHinvaa : H (a⁻¹*a), from (eq.symm (mul.left_inv a)) ▸ PH1, have PHainva : H (a*a⁻¹), from (eq.symm (mul.right_inv a)) ▸ PH1, and.intro PHinvaa PHainva end set_reducible lemma subg_in_lcoset_same_lcoset (a b : A) : in_lcoset H a b → same_lcoset H a b := assume Pa_in_b : H (b⁻¹*a), have Pbinva : b⁻¹*a ∘> H = H, from subgroup_lcoset_id (b⁻¹*a) Pa_in_b, have Pb_binva : b ∘> b⁻¹*a ∘> H = b ∘> H, from Pbinva ▸ rfl, have Pbbinva : b*(b⁻¹*a)∘>H = b∘>H, from glcoset_compose b (b⁻¹*a) H ▸ Pb_binva, mul_inv_cancel_left b a ▸ Pbbinva lemma subg_same_lcoset_in_lcoset (a b : A) : same_lcoset H a b → in_lcoset H a b := assume Psame : a∘>H = b∘>H, have Pa : a ∈ a∘>H, from and.left (subg_in_coset_refl a), by exact (Psame ▸ Pa) lemma subg_lcoset_same (a b : A) : in_lcoset H a b = (a∘>H = b∘>H) := propext(iff.intro (subg_in_lcoset_same_lcoset a b) (subg_same_lcoset_in_lcoset a b)) lemma subg_rcoset_same (a b : A) : in_rcoset H a b = (H<∘a = H<∘b) := propext(iff.intro (assume Pa_in_b : H (a*b⁻¹), have Pabinv : H<∘a*b⁻¹ = H, from subgroup_rcoset_id (a*b⁻¹) Pa_in_b, have Pabinv_b : H <∘ a*b⁻¹ <∘ b = H <∘ b, from Pabinv ▸ rfl, have Pabinvb : H <∘ a*b⁻¹*b = H <∘ b, from grcoset_compose (a*b⁻¹) b H ▸ Pabinv_b, inv_mul_cancel_right a b ▸ Pabinvb) (assume Psame, have Pa : a ∈ H<∘a, from and.right (subg_in_coset_refl a), by exact (Psame ▸ Pa))) lemma subg_same_lcoset.refl (a : A) : same_lcoset H a a := rfl lemma subg_same_rcoset.refl (a : A) : same_rcoset H a a := rfl lemma subg_same_lcoset.symm (a b : A) : same_lcoset H a b → same_lcoset H b a := eq.symm lemma subg_same_rcoset.symm (a b : A) : same_rcoset H a b → same_rcoset H b a := eq.symm lemma subg_same_lcoset.trans (a b c : A) : same_lcoset H a b → same_lcoset H b c → same_lcoset H a c := eq.trans lemma subg_same_rcoset.trans (a b c : A) : same_rcoset H a b → same_rcoset H b c → same_rcoset H a c := eq.trans variable {S : set A} lemma subg_lcoset_subset_subg (Psub : S ⊆ H) (a : A) : a ∈ H → a ∘> S ⊆ H := assume Pin, have P : a ∘> S ⊆ a ∘> H, from glcoset_sub a S H Psub, subgroup_lcoset_id a Pin ▸ P end subgroup section normal_subg open quot variable {A : Type} variable [s : group A] include s variable (N : set A) variable [is_nsubg : is_normal_subgroup N] include is_nsubg local notation a `~` b := same_lcoset N a b -- note : does not bind as strong as → lemma nsubg_normal : same_left_right_coset N := @is_normal_subgroup.normal A s N is_nsubg lemma nsubg_same_lcoset_product : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ((a1*a2) ~ (b1*b2)) := take a1, take a2, take b1, take b2, assume Psame1 : a1 ∘> N = b1 ∘> N, assume Psame2 : a2 ∘> N = b2 ∘> N, calc a1*a2 ∘> N = a1 ∘> a2 ∘> N : glcoset_compose ... = a1 ∘> b2 ∘> N : by rewrite Psame2 ... = a1 ∘> (N <∘ b2) : by rewrite (nsubg_normal N) ... = (a1 ∘> N) <∘ b2 : by rewrite lcoset_rcoset_assoc ... = (b1 ∘> N) <∘ b2 : by rewrite Psame1 ... = N <∘ b1 <∘ b2 : by rewrite (nsubg_normal N) ... = N <∘ (b1*b2) : by rewrite grcoset_compose ... = (b1*b2) ∘> N : by rewrite (nsubg_normal N) example (a b : A) : (a⁻¹ ~ b⁻¹) = (a⁻¹ ∘> N = b⁻¹ ∘> N) := rfl lemma nsubg_same_lcoset_inv : ∀ a b, (a ~ b) → (a⁻¹ ~ b⁻¹) := take a b, assume Psame : a ∘> N = b ∘> N, calc a⁻¹ ∘> N = a⁻¹*b*b⁻¹ ∘> N : by rewrite mul_inv_cancel_right ... = a⁻¹*b ∘> b⁻¹ ∘> N : by rewrite glcoset_compose ... = a⁻¹*b ∘> (N <∘ b⁻¹) : by rewrite nsubg_normal ... = (a⁻¹*b ∘> N) <∘ b⁻¹ : by rewrite lcoset_rcoset_assoc ... = (a⁻¹ ∘> b ∘> N) <∘ b⁻¹ : by rewrite glcoset_compose ... = (a⁻¹ ∘> a ∘> N) <∘ b⁻¹ : by rewrite Psame ... = N <∘ b⁻¹ : by rewrite glcoset_inv ... = b⁻¹ ∘> N : by rewrite nsubg_normal definition nsubg_setoid [instance] : setoid A := setoid.mk (same_lcoset N) (mk_equivalence (same_lcoset N) (subg_same_lcoset.refl) (subg_same_lcoset.symm) (subg_same_lcoset.trans)) definition coset_of : Type := quot (nsubg_setoid N) definition coset_inv_base (a : A) : coset_of N := ⟦a⁻¹⟧ definition coset_product (a b : A) : coset_of N := ⟦a*b⟧ lemma coset_product_well_defined : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ⟦a1*a2⟧ = ⟦b1*b2⟧ := take a1 a2 b1 b2, assume P1 P2, quot.sound (nsubg_same_lcoset_product N a1 a2 b1 b2 P1 P2) definition coset_mul (aN bN : coset_of N) : coset_of N := quot.lift_on₂ aN bN (coset_product N) (coset_product_well_defined N) lemma coset_inv_well_defined : ∀ a b, (a ~ b) → ⟦a⁻¹⟧ = ⟦b⁻¹⟧ := take a b, assume P, quot.sound (nsubg_same_lcoset_inv N a b P) definition coset_inv (aN : coset_of N) : coset_of N := quot.lift_on aN (coset_inv_base N) (coset_inv_well_defined N) definition coset_one : coset_of N := ⟦1⟧ local infixl `cx`:70 := coset_mul N example (a b c : A) : ⟦a⟧ cx ⟦b*c⟧ = ⟦a*(b*c)⟧ := rfl lemma coset_product_assoc (a b c : A) : ⟦a⟧ cx ⟦b⟧ cx ⟦c⟧ = ⟦a⟧ cx (⟦b⟧ cx ⟦c⟧) := calc ⟦a*b*c⟧ = ⟦a*(b*c)⟧ : {mul.assoc a b c} ... = ⟦a⟧ cx ⟦b*c⟧ : rfl lemma coset_product_left_id (a : A) : ⟦1⟧ cx ⟦a⟧ = ⟦a⟧ := calc ⟦1*a⟧ = ⟦a⟧ : {one_mul a} lemma coset_product_right_id (a : A) : ⟦a⟧ cx ⟦1⟧ = ⟦a⟧ := calc ⟦a*1⟧ = ⟦a⟧ : {mul_one a} lemma coset_product_left_inv (a : A) : ⟦a⁻¹⟧ cx ⟦a⟧ = ⟦1⟧ := calc ⟦a⁻¹*a⟧ = ⟦1⟧ : {mul.left_inv a} lemma coset_mul.assoc (aN bN cN : coset_of N) : aN cx bN cx cN = aN cx (bN cx cN) := quot.ind (λ a, quot.ind (λ b, quot.ind (λ c, coset_product_assoc N a b c) cN) bN) aN lemma coset_mul.one_mul (aN : coset_of N) : coset_one N cx aN = aN := quot.ind (coset_product_left_id N) aN lemma coset_mul.mul_one (aN : coset_of N) : aN cx (coset_one N) = aN := quot.ind (coset_product_right_id N) aN lemma coset_mul.left_inv (aN : coset_of N) : (coset_inv N aN) cx aN = (coset_one N) := quot.ind (coset_product_left_inv N) aN definition mk_quotient_group : group (coset_of N):= group.mk (coset_mul N) (coset_mul.assoc N) (coset_one N) (coset_mul.one_mul N) (coset_mul.mul_one N) (coset_inv N) (coset_mul.left_inv N) end normal_subg namespace group_theory namespace quotient section open quot variable {A : Type} variable [s : group A] include s variable {N : set A} variable [is_nsubg : is_normal_subgroup N] include is_nsubg definition quotient_group [instance] : group (coset_of N) := mk_quotient_group N example (aN : coset_of N) : aN * aN⁻¹ = 1 := mul.right_inv aN definition natural (a : A) : coset_of N := ⟦a⟧ end end quotient end group_theory
7c620aeb2fcc4d6dbc7b465b0d7d4194dfc5025c
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/linear_algebra/determinant.lean
e147d10398b64b5803fd51fa6508ba2b58b75c2e
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
8,833
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Tim Baanen -/ import data.matrix.pequiv import data.fintype.card import group_theory.perm.sign universes u v open equiv equiv.perm finset function namespace matrix open_locale matrix variables {n : Type u} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R] local notation `ε` σ:max := ((sign σ : ℤ ) : R) /-- The determinant of a matrix given by the Leibniz formula. -/ definition det (M : matrix n n R) : R := univ.sum (λ (σ : perm n), ε σ * univ.prod (λ i, M (σ i) i)) @[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = univ.prod d := begin refine (finset.sum_eq_single 1 _ _).trans _, { intros σ h1 h2, cases not_forall.1 (mt (equiv.ext _ _) h2) with x h3, convert ring.mul_zero _, apply finset.prod_eq_zero, { change x ∈ _, simp }, exact if_neg h3 }, { simp }, { simp } end @[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 := by rw [← diagonal_zero, det_diagonal, finset.prod_const, ← fintype.card, zero_pow (fintype.card_pos_iff.2 h)] @[simp] lemma det_one : det (1 : matrix n n R) = 1 := by rw [← diagonal_one]; simp [-diagonal_one] lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 := begin have perm_eq : (univ : finset (perm n)) = finset.singleton 1 := univ_eq_singleton_of_card_one (1 : perm n) (by simp [card_univ, fintype.card_perm, h]), simp [det, card_eq_zero.mp h, perm_eq], end lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) : univ.sum (λ σ : perm n, (ε σ) * (univ.prod (λ x, M (σ x) (p x) * N (p x) x))) = 0 := begin obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j, { rw [← fintype.injective_iff_bijective, injective] at H, push_neg at H, exact H }, exact sum_involution (λ σ _, σ * swap i j) (λ σ _, have ∀ a, p (swap i j a) = p a := λ a, by simp only [swap_apply_def]; split_ifs; cc, have univ.prod (λ x, M (σ x) (p x)) = univ.prod (λ x, M ((σ * swap i j) x) (p x)), from prod_bij (λ a _, swap i j a) (λ _ _, mem_univ _) (by simp [this]) (λ _ _ _ _ h, (swap i j).injective h) (λ b _, ⟨swap i j b, mem_univ _, by simp⟩), by simp [sign_mul, this, sign_swap hij, prod_mul_distrib]) (λ σ _ _ h, hij (σ.injective $ by conv {to_lhs, rw ← h}; simp)) (λ _ _, mem_univ _) (λ _ _, equiv.ext _ _ $ by simp) end @[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N := calc det (M ⬝ N) = univ.sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : by simp only [det, mul_val, prod_univ_sum, mul_sum, fintype.pi_finset_univ]; rw [finset.sum_comm] ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : eq.symm $ sum_subset (filter_subset _) (λ f _ hbij, det_mul_aux $ by simpa using hbij) ... = (@univ (perm n) _).sum (λ τ, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (τ i) * N (τ i) i))) : sum_bij (λ p h, equiv.of_bijective (mem_filter.1 h).2) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ h, by injection h) (λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, eq_of_to_fun_eq rfl⟩) ... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n, (univ.prod (λ i, N (σ i) i) * ε τ) * univ.prod (λ j, M (τ j) (σ j)))) : by simp [mul_sum, det, mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc] ... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n, (univ.prod (λ i, N (σ i) i) * (ε σ * ε τ)) * univ.prod (λ i, M (τ i) i))) : sum_congr rfl (λ σ _, sum_bij (λ τ _, τ * σ⁻¹) (λ _ _, mem_univ _) (λ τ _, have univ.prod (λ j, M (τ j) (σ j)) = univ.prod (λ j, M ((τ * σ⁻¹) j) j), by rw ← finset.prod_equiv σ⁻¹; simp [mul_apply], have h : ε σ * ε (τ * σ⁻¹) = ε τ := calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) : by rw [mul_comm, sign_mul (τ * σ⁻¹)]; simp [sign_mul] ... = ε τ : by simp, by rw h; simp [this, mul_comm, mul_assoc, mul_left_comm]) (λ _ _ _ _, (mul_left_inj _).1) (λ τ _, ⟨τ * σ, by simp⟩)) ... = det M * det N : by simp [det, mul_assoc, mul_sum, mul_comm, mul_left_comm] instance : is_monoid_hom (det : matrix n n R → R) := { map_one := det_one, map_mul := det_mul } /-- Transposing a matrix preserves the determinant. -/ @[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det := begin apply sum_bij (λ σ _, σ⁻¹), { intros σ _, apply mem_univ }, { intros σ _, rw [sign_inv], congr' 1, apply prod_bij (λ i _, σ i), { intros i _, apply mem_univ }, { intros i _, simp }, { intros i j _ _ h, simp at h, assumption }, { intros i _, use σ⁻¹ i, finish } }, { intros σ σ' _ _ h, simp at h, assumption }, { intros σ _, use σ⁻¹, finish } end /-- The determinant of a permutation matrix equals its sign. -/ @[simp] lemma det_permutation (σ : perm n) : matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign := begin suffices : matrix.det (σ.to_pequiv.to_matrix) = ↑σ.sign * det (1 : matrix n n R), { simp [this] }, unfold det, rw mul_sum, apply sum_bij (λ τ _, σ * τ), { intros τ _, apply mem_univ }, { intros τ _, conv_lhs { rw [←one_mul (sign τ), ←int.units_pow_two (sign σ)] }, conv_rhs { rw [←mul_assoc, coe_coe, sign_mul, units.coe_mul, int.cast_mul, ←mul_assoc] }, congr, { simp [pow_two] }, { ext i, apply pequiv.equiv_to_pequiv_to_matrix } }, { intros τ τ' _ _, exact (mul_right_inj σ).mp }, { intros τ _, use σ⁻¹ * τ, use (mem_univ _), exact (mul_inv_cancel_left _ _).symm } end /-- Permuting the columns changes the sign of the determinant. -/ lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det := by rw [←det_permutation, ←det_mul, pequiv.to_pequiv_mul_matrix] @[simp] lemma det_smul {A : matrix n n R} {c : R} : det (c • A) = c ^ fintype.card n * det A := calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul] ... = det (diagonal (λ _, c)) * det A : det_mul _ _ ... = c ^ fintype.card n * det A : by simp [card_univ] section det_zero /-! ### `det_zero` section Prove that a matrix with a repeated column has determinant equal to zero. -/ lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 := begin rw [←det_transpose, det], convert @sum_const_zero _ _ (univ : finset (perm n)) _, ext σ, convert mul_zero ↑(sign σ), apply prod_eq_zero (mem_univ i), rw [transpose_val], apply h end /-- `mod_swap i j` contains permutations up to swapping `i` and `j`. We use this to partition permutations in the expression for the determinant, such that each partitions sums up to `0`. -/ def mod_swap {n : Type u} [decidable_eq n] (i j : n) : setoid (perm n) := ⟨ λ σ τ, σ = τ ∨ σ = swap i j * τ, λ σ, or.inl (refl σ), λ σ τ h, or.cases_on h (λ h, or.inl h.symm) (λ h, or.inr (by rw [h, swap_mul_self_mul])), λ σ τ υ hστ hτυ, by cases hστ; cases hτυ; try {rw [hστ, hτυ, swap_mul_self_mul]}; finish⟩ instance (i j : n) : decidable_rel (mod_swap i j).r := λ σ τ, or.decidable variables {M : matrix n n R} {i j : n} /-- If a matrix has a repeated column, the determinant will be zero. -/ theorem det_zero_of_column_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 := begin have swap_invariant : ∀ k, M (swap i j k) = M k, { intros k, rw [swap_apply_def], by_cases k = i, { rw [if_pos h, h, ←hij] }, rw [if_neg h], by_cases k = j, { rw [if_pos h, h, hij] }, rw [if_neg h] }, have : ∀ σ, _root_.disjoint (_root_.singleton σ) (_root_.singleton (swap i j * σ)), { intros σ, rw [finset.singleton_eq_singleton, finset.singleton_eq_singleton, disjoint_singleton], apply (not_congr mem_singleton).mpr, exact (not_congr swap_mul_eq_iff).mpr i_ne_j }, apply finset.sum_cancels_of_partition_cancels (mod_swap i j), intros σ _, erw [filter_or, filter_eq', filter_eq', if_pos (mem_univ σ), if_pos (mem_univ (swap i j * σ)), sum_union (this σ), sum_singleton, sum_singleton], convert add_right_neg (↑↑(sign σ) * finset.prod univ (λ (i : n), M (σ i) i)), rw [neg_mul_eq_neg_mul], congr, { rw [sign_mul, sign_swap i_ne_j], norm_num }, ext j, rw [mul_apply, swap_invariant] end end det_zero end matrix
600cb0164982fda6c0ee775eb965c88eb3555302
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/integrally_closed.lean
6da8d3d3db43df0c565bfde1cce371a6b997ba11
[ "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,182
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.integral_closure import ring_theory.localization /-! # Integrally closed rings An integrally closed domain `R` contains all the elements of `Frac(R)` that are integral over `R`. A special case of integrally closed domains are the Dedekind domains. ## Main definitions * `is_integrally_closed R` states `R` contains all integral elements of `Frac(R)` ## Main results * `is_integrally_closed_iff K`, where `K` is a fraction field of `R`, states `R` is integrally closed iff it is the integral closure of `R` in `K` -/ open_locale non_zero_divisors /-- `R` is integrally closed if all integral elements of `Frac(R)` are also elements of `R`. This definition uses `fraction_ring R` to denote `Frac(R)`. See `is_integrally_closed_iff` if you want to choose another field of fractions for `R`. -/ class is_integrally_closed (R : Type*) [comm_ring R] [is_domain R] : Prop := (algebra_map_eq_of_integral : ∀ {x : fraction_ring R}, is_integral R x → ∃ y, algebra_map R (fraction_ring R) y = x) section iff variables {R : Type*} [comm_ring R] [is_domain R] variables (K : Type*) [field K] [algebra R K] [is_fraction_ring R K] /-- `R` is integrally closed iff all integral elements of its fraction field `K` are also elements of `R`. -/ theorem is_integrally_closed_iff : is_integrally_closed R ↔ ∀ {x : K}, is_integral R x → ∃ y, algebra_map R K y = x := begin let e : K ≃ₐ[R] fraction_ring R := is_localization.alg_equiv R⁰_ _, split, { rintros ⟨cl⟩, refine λ x hx, _, obtain ⟨y, hy⟩ := cl ((is_integral_alg_equiv e).mpr hx), exact ⟨y, e.algebra_map_eq_apply.mp hy⟩ }, { rintros cl, refine ⟨λ x hx, _⟩, obtain ⟨y, hy⟩ := cl ((is_integral_alg_equiv e.symm).mpr hx), exact ⟨y, e.symm.algebra_map_eq_apply.mp hy⟩ }, end /-- `R` is integrally closed iff it is the integral closure of itself in its field of fractions. -/ theorem is_integrally_closed_iff_is_integral_closure : is_integrally_closed R ↔ is_integral_closure R R K := (is_integrally_closed_iff K).trans $ begin let e : K ≃ₐ[R] fraction_ring R := is_localization.alg_equiv R⁰_ _, split, { intros cl, refine ⟨is_fraction_ring.injective _ _, λ x, ⟨cl, _⟩⟩, rintros ⟨y, y_eq⟩, rw ← y_eq, exact is_integral_algebra_map }, { rintros ⟨-, cl⟩ x hx, exact cl.mp hx } end end iff namespace is_integrally_closed variables {R : Type*} [comm_ring R] [is_domain R] [iic : is_integrally_closed R] variables {K : Type*} [field K] [algebra R K] [is_fraction_ring R K] instance : is_integral_closure R R K := (is_integrally_closed_iff_is_integral_closure K).mp iic include iic lemma is_integral_iff {x : K} : is_integral R x ↔ ∃ y, algebra_map R K y = x := is_integral_closure.is_integral_iff omit iic variables {R} (K) lemma integral_closure_eq_bot_iff : integral_closure R K = ⊥ ↔ is_integrally_closed R := begin refine eq_bot_iff.trans _, split, { rw is_integrally_closed_iff K, intros h x hx, exact set.mem_range.mp (algebra.mem_bot.mp (h hx)), assumption }, { intros h x hx, rw [algebra.mem_bot, set.mem_range], exactI is_integral_iff.mp hx }, end include iic variables (R K) @[simp] lemma integral_closure_eq_bot : integral_closure R K = ⊥ := (integral_closure_eq_bot_iff K).mpr ‹_› end is_integrally_closed namespace integral_closure open is_integrally_closed variables {R : Type*} [comm_ring R] [is_domain R] [iic : is_integrally_closed R] variables (K : Type*) [field K] [algebra R K] [is_fraction_ring R K] variables {L : Type*} [field L] [algebra K L] [algebra R L] [is_scalar_tower R K L] -- Can't be an instance because you need to supply `K`. lemma is_integrally_closed_of_finite_extension [finite_dimensional K L] : is_integrally_closed (integral_closure R L) := begin letI : is_fraction_ring (integral_closure R L) L := is_fraction_ring_of_finite_extension K L, exact (integral_closure_eq_bot_iff L).mp integral_closure_idem end end integral_closure
cd1ddbeded8aeba7519158d29cb66d709d6b6530
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/dfinsupp.lean
e264ea0790113caa7f4ed439da5013e5fb5d0a9b
[ "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
8,028
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau -/ import data.finsupp.to_dfinsupp import linear_algebra.basis /-! # Properties of the module `Π₀ i, M i` Given an indexed collection of `R`-modules `M i`, the `R`-module structure on `Π₀ i, M i` is defined in `data.dfinsupp`. In this file we define `linear_map` versions of various maps: * `dfinsupp.lsingle a : M →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map; * `dfinsupp.lmk s : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map; * `dfinsupp.lapply i : (Π₀ i, M i) →ₗ[R] M`: the map `λ f, f i` as a linear map; * `dfinsupp.lsum`: `dfinsupp.sum` or `dfinsupp.lift_add_hom` as a `linear_map`; ## Implementation notes This file should try to mirror `linear_algebra.finsupp` where possible. The API of `finsupp` is much more developed, but many lemmas in that file should be eligible to copy over. ## Tags function with finite support, module, linear algebra -/ variables {ι : Type*} {R : Type*} {S : Type*} {M : ι → Type*} {N : Type*} variables [dec_ι : decidable_eq ι] variables [semiring R] [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] variables [add_comm_monoid N] [module R N] namespace dfinsupp include dec_ι /-- `dfinsupp.mk` as a `linear_map`. -/ def lmk (s : finset ι) : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i := { to_fun := mk s, map_add' := λ _ _, mk_add, map_smul' := λ c x, mk_smul R x } /-- `dfinsupp.single` as a `linear_map` -/ def lsingle (i) : M i →ₗ[R] Π₀ i, M i := { to_fun := single i, map_smul' := λ r x, single_smul _, .. dfinsupp.single_add_hom _ _ } /-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. -/ lemma lhom_ext ⦃φ ψ : (Π₀ i, M i) →ₗ[R] N⦄ (h : ∀ i x, φ (single i x) = ψ (single i x)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. See note [partially-applied ext lemmas]. After apply this lemma, if `M = R` then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' ⦃φ ψ : (Π₀ i, M i) →ₗ[R] N⦄ (h : ∀ i, φ.comp (lsingle i) = ψ.comp (lsingle i)) : φ = ψ := lhom_ext $ λ i, linear_map.congr_fun (h i) omit dec_ι /-- Interpret `λ (f : Π₀ i, M i), f i` as a linear map. -/ def lapply (i : ι) : (Π₀ i, M i) →ₗ[R] M i := { to_fun := λ f, f i, map_add' := λ f g, add_apply f g i, map_smul' := λ c f, smul_apply c f i} include dec_ι @[simp] lemma lmk_apply (s : finset ι) (x) : (lmk s : _ →ₗ[R] Π₀ i, M i) x = mk s x := rfl @[simp] lemma lsingle_apply (i : ι) (x : M i) : (lsingle i : _ →ₗ[R] _) x = single i x := rfl omit dec_ι @[simp] lemma lapply_apply (i : ι) (f : Π₀ i, M i) : (lapply i : _ →ₗ[R] _) f = f i := rfl section lsum /-- Typeclass inference can't find `dfinsupp.add_comm_monoid` without help for this case. This instance allows it to be found where it is needed on the LHS of the colon in `dfinsupp.module_of_linear_map`. -/ instance add_comm_monoid_of_linear_map : add_comm_monoid (Π₀ (i : ι), M i →ₗ[R] N) := @dfinsupp.add_comm_monoid _ (λ i, M i →ₗ[R] N) _ /-- Typeclass inference can't find `dfinsupp.module` without help for this case. This is needed to define `dfinsupp.lsum` below. The cause seems to be an inability to unify the `Π i, add_comm_monoid (M i →ₗ[R] N)` instance that we have with the `Π i, has_zero (M i →ₗ[R] N)` instance which appears as a parameter to the `dfinsupp` type. -/ instance module_of_linear_map [semiring S] [module S N] [smul_comm_class R S N] : module S (Π₀ (i : ι), M i →ₗ[R] N) := @dfinsupp.module _ (λ i, M i →ₗ[R] N) _ _ _ _ variables (S) include dec_ι /-- The `dfinsupp` version of `finsupp.lsum`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps apply symm_apply] def lsum [semiring S] [module S N] [smul_comm_class R S N] : (Π i, M i →ₗ[R] N) ≃ₗ[S] ((Π₀ i, M i) →ₗ[R] N) := { to_fun := λ F, { to_fun := sum_add_hom (λ i, (F i).to_add_monoid_hom), map_add' := (lift_add_hom (λ i, (F i).to_add_monoid_hom)).map_add, map_smul' := λ c f, by { apply dfinsupp.induction f, { rw [smul_zero, add_monoid_hom.map_zero, smul_zero] }, { intros a b f ha hb hf, rw [smul_add, add_monoid_hom.map_add, add_monoid_hom.map_add, smul_add, hf, ←single_smul, sum_add_hom_single, sum_add_hom_single, linear_map.to_add_monoid_hom_coe, linear_map.map_smul], } } }, inv_fun := λ F i, F.comp (lsingle i), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp }, map_smul' := λ c F, by { ext, simp } } end lsum /-! ### Bundled versions of `dfinsupp.map_range` The names should match the equivalent bundled `finsupp.map_range` definitions. -/ section map_range variables {β β₁ β₂: ι → Type*} variables [Π i, add_comm_monoid (β i)] [Π i, add_comm_monoid (β₁ i)] [Π i, add_comm_monoid (β₂ i)] variables [Π i, module R (β i)] [Π i, module R (β₁ i)] [Π i, module R (β₂ i)] lemma map_range_smul (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (r : R) (hf' : ∀ i x, f i (r • x) = r • f i x) (g : Π₀ i, β₁ i): map_range f hf (r • g) = r • map_range f hf g := begin ext, simp only [map_range_apply f, coe_smul, pi.smul_apply, hf'] end /-- `dfinsupp.map_range` as an `linear_map`. -/ @[simps apply] def map_range.linear_map (f : Π i, β₁ i →ₗ[R] β₂ i) : (Π₀ i, β₁ i) →ₗ[R] (Π₀ i, β₂ i) := { to_fun := map_range (λ i x, f i x) (λ i, (f i).map_zero), map_smul' := λ r, map_range_smul _ _ _ (λ i, (f i).map_smul r), .. map_range.add_monoid_hom (λ i, (f i).to_add_monoid_hom) } @[simp] lemma map_range.linear_map_id : map_range.linear_map (λ i, (linear_map.id : (β₂ i) →ₗ[R] _)) = linear_map.id := linear_map.ext map_range_id lemma map_range.linear_map_comp (f : Π i, β₁ i →ₗ[R] β₂ i) (f₂ : Π i, β i →ₗ[R] β₁ i): map_range.linear_map (λ i, (f i).comp (f₂ i)) = (map_range.linear_map f).comp (map_range.linear_map f₂) := linear_map.ext $ map_range_comp (λ i x, f i x) (λ i x, f₂ i x) _ _ _ /-- `dfinsupp.map_range.linear_map` as an `linear_equiv`. -/ @[simps apply] def map_range.linear_equiv (e : Π i, β₁ i ≃ₗ[R] β₂ i) : (Π₀ i, β₁ i) ≃ₗ[R] (Π₀ i, β₂ i) := { to_fun := map_range (λ i x, e i x) (λ i, (e i).map_zero), inv_fun := map_range (λ i x, (e i).symm x) (λ i, (e i).symm.map_zero), .. map_range.add_equiv (λ i, (e i).to_add_equiv), .. map_range.linear_map (λ i, (e i).to_linear_map) } @[simp] lemma map_range.linear_equiv_refl : (map_range.linear_equiv $ λ i, linear_equiv.refl R (β₁ i)) = linear_equiv.refl _ _ := linear_equiv.ext map_range_id lemma map_range.linear_equiv_trans (f : Π i, β i ≃ₗ[R] β₁ i) (f₂ : Π i, β₁ i ≃ₗ[R] β₂ i): map_range.linear_equiv (λ i, (f i).trans (f₂ i)) = (map_range.linear_equiv f).trans (map_range.linear_equiv f₂) := linear_equiv.ext $ map_range_comp (λ i x, f₂ i x) (λ i x, f i x) _ _ _ @[simp] lemma map_range.linear_equiv_symm (e : Π i, β₁ i ≃ₗ[R] β₂ i) : (map_range.linear_equiv e).symm = map_range.linear_equiv (λ i, (e i).symm) := rfl end map_range section basis /-- The direct sum of free modules is free. Note that while this is stated for `dfinsupp` not `direct_sum`, the types are defeq. -/ noncomputable def basis {η : ι → Type*} (b : Π i, basis (η i) R (M i)) : basis (Σ i, η i) R (Π₀ i, M i) := basis.of_repr ((map_range.linear_equiv (λ i, (b i).repr)).trans (sigma_finsupp_lequiv_dfinsupp R).symm) end basis end dfinsupp
2fd5cc60bdc526ad37b2a939d9c45c8fe133c96f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/simp_subsingleton.lean
dec49d666b5816f92aafefb0979f330ecc0e8e1c
[ "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
1,328
lean
inductive some_subsingleton : Type | canonical open some_subsingleton instance : subsingleton some_subsingleton := ⟨λ a b, by cases a; cases b; refl⟩ -- Note that ⟨λ a b, refl a⟩ does not work as a valid instance: -- the type is a subsingleton, but not definitionally! def some_function : some_subsingleton → some_subsingleton := λ x, x @[simp] lemma some_function_lemma {a : some_subsingleton} : some_function a = canonical := by cases a; refl -- Motivating example: example (a : some_subsingleton) : some_function a = canonical := by simp only [some_function_lemma] example (a : some_subsingleton) : some_function a = canonical := by {(do t <- tactic.target, c <- tactic.mk_specialized_congr_lemma_simp t, tactic.trace c.arg_kinds), simp } example : cond (to_bool (2 = 2)) 0 1 = 0 := by {(do `((cond %%t %%i %%e) = _) <- tactic.target, c <- tactic.mk_specialized_congr_lemma_simp t, tactic.trace c.arg_kinds), simp } constants (γ : Type) (f : Π (α : Type*) (β : Sort*), α → β → γ) (X : Type) (X_ss : subsingleton X) (Y : Prop) attribute [instance] X_ss example (x₁ x₂ : X) (y₁ y₂ : Y) : f X Y x₁ y₁ = f X Y x₂ y₂ := by { (do `(%%t = _) <- tactic.target, cs <- tactic.mk_specialized_congr_lemma_simp t, tactic.trace cs.arg_kinds), congr }
d97b69264656d746dba17e22ad5693ddef4802ff
626e312b5c1cb2d88fca108f5933076012633192
/src/data/finsupp/basic.lean
1359ac9aef4a2a087f6abe7ec11e4f889447e6a8
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
105,481
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, Scott Morrison -/ import data.finset.preimage import algebra.indicator_function import algebra.group_action_hom /-! # Type of functions with finite support For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use `finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `linear_independent`) is defined as a map `finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `multiset α ≃+ α →₀ ℕ`; * `free_abelian_group α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have non-pointwise multiplication. ## Notations This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## TODO * This file is currently ~2K lines long, so possibly it should be splitted into smaller chunks; * Add the list of definitions and important lemmas to the module docstring. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## Notation This file defines `α →₀ β` as notation for `finsupp α β`. -/ noncomputable theory open_locale classical big_operators open finset variables {α β γ ι M M' N P G H R S : Type*} /-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (M : Type*) [has_zero M] := (support : finset α) (to_fun : α → M) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ section basic variable [has_zero M] instance : has_coe_to_fun (α →₀ M) := ⟨λ _, α → M, to_fun⟩ @[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance : has_zero (α →₀ M) := ⟨⟨∅, 0, λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl instance : inhabited (α →₀ M) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[simp, norm_cast] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support := set.ext $ λ x, mem_support_iff.symm lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm lemma coe_fn_injective : @function.injective (α →₀ M) (α → M) coe_fn | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin change f = g at h, subst h, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end @[simp, norm_cast] lemma coe_fn_inj {f g : α →₀ M} : (f : α → M) = g ↔ f = g := coe_fn_injective.eq_iff @[simp, norm_cast] lemma coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, coe_fn_inj] @[ext] lemma ext {f g : α →₀ M} (h : ∀a, f a = g a) : f = g := coe_fn_injective (funext h) lemma ext_iff {f g : α →₀ M} : f = g ↔ (∀a:α, f a = g a) := ⟨by rintros rfl a; refl, ext⟩ lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, from not_mem_support_iff.1 h, have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h, by rw [hf, hg]⟩ lemma congr_fun {f g : α →₀ M} (h : f = g) (a : α) : f a = g a := congr_fun (congr_arg finsupp.to_fun h) a @[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := by exact_mod_cast @function.support_eq_empty_iff _ _ _ f lemma support_nonempty_iff {f : α →₀ M} : f.support.nonempty ↔ f ≠ 0 := by simp only [finsupp.support_eq_empty, finset.nonempty_iff_ne_empty, ne.def] lemma nonzero_iff_exists {f : α →₀ M} : f ≠ 0 ↔ ∃ a : α, f a ≠ 0 := by simp [← finsupp.support_eq_empty, finset.eq_empty_iff_forall_not_mem] lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 := by simp instance [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm lemma finite_support (f : α →₀ M) : set.finite (function.support f) := f.fun_support_eq.symm ▸ f.support.finite_to_set lemma support_subset_iff {s : set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, not_imp_comm) /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps] def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ, iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ @[simp] lemma equiv_fun_on_fintype_symm_coe {α} [fintype α] (f : α →₀ M) : equiv_fun_on_fintype.symm f = f := by { ext, simp [equiv_fun_on_fintype], } end basic /-! ### Declarations about `single` -/ section single variables [has_zero M] {a a' : α} {b : M} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : M) : α →₀ M := ⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply [decidable (a = a')] : single a b a' = if a = a' then b else 0 := by convert rfl lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) := by { ext, simp [single_apply, set.indicator, @eq_comm _ a] } @[simp] lemma single_eq_same : (single a b : α →₀ M) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := if_neg h lemma single_eq_update : ⇑(single a b) = function.update 0 a b := by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton] lemma single_eq_pi_single : ⇑(single a b) = pi.single a b := single_eq_update @[simp] lemma single_zero : (single a 0 : α →₀ M) = 0 := coe_fn_injective $ by simpa only [single_eq_update, coe_zero] using function.update_eq_self a (0 : α → M) lemma single_of_single_apply (a a' : α) (b : M) : single a ((single a' b) a) = single a' (single a' b) a := begin rw [single_apply, single_apply], ext, split_ifs, { rw h, }, { rw [zero_apply, single_apply, if_t_t], }, end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) := by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]] lemma range_single_subset : set.range (single a b) ⊆ {0, b} := set.range_subset_iff.2 single_apply_mem /-- `finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see `finsupp.single_left_injective` -/ lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) := assume b₁ b₂ eq, have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) := by simp [single_eq_indicator] lemma mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by simp [single_apply_eq_zero, not_or_distrib] lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := begin refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩, rintro ⟨h, rfl⟩, ext x, by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff], exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx) end lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (single_injective a₂).eq_iff] at eq }, { rw [ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end /-- `finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see `finsupp.single_injective` -/ lemma single_left_injective (h : b ≠ 0) : function.injective (λ a : α, single a b) := λ a a' H, (((single_eq_single_iff _ _ _ _).mp H).resolve_right $ λ hb, h hb.1).left lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := (single_left_injective h).eq_iff lemma support_single_ne_bot (i : α) (h : b ≠ 0) : (single i b).support ≠ ⊥ := begin have : i ∈ (single i b).support := by simpa using h, intro H, simpa [H] end lemma support_single_disjoint {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} : disjoint (single i b).support (single j b').support ↔ i ≠ j := by simpa [support_single_ne_zero, hb, hb'] using ne_comm @[simp] lemma single_eq_zero : single a b = 0 ↔ b = 0 := by simp [ext_iff, single_eq_indicator] lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by simp only [single_apply]; ac_refl instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) := begin inhabit α, rcases exists_ne (0 : M) with ⟨x, hx⟩, exact nontrivial_of_ne (single (default α) x) 0 (mt single_eq_zero.1 hx) end lemma unique_single [unique α] (x : α →₀ M) : x = single (default α) (x (default α)) := ext $ unique.forall_iff.2 single_eq_same.symm lemma unique_ext [unique α] {f g : α →₀ M} (h : f (default α) = g (default α)) : f = g := ext $ λ a, by rwa [unique.eq_default a] lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f (default α) = g (default α) := ⟨λ h, h ▸ rfl, unique_ext⟩ @[simp] lemma unique_single_eq_iff [unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same] lemma support_eq_singleton {f : α →₀ M} {a : α} : f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) := ⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a, eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero h.1⟩ lemma support_eq_singleton' {f : α →₀ M} {a : α} : f.support = {a} ↔ ∃ b ≠ 0, f = single a b := ⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩, λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero hb⟩ lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by simp only [card_eq_one, support_eq_singleton] lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b := by simp only [card_eq_one, support_eq_singleton'] @[simp] lemma equiv_fun_on_fintype_single [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _) (finsupp.single x m) = pi.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } @[simp] lemma equiv_fun_on_fintype_symm_single [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _).symm (pi.single x m) = finsupp.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } end single /-! ### Declarations about `on_finset` -/ section on_finset variables [has_zero M] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M := ⟨s.filter (λa, f a ≠ 0), f, by simpa⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} : (on_finset s f hf : α →₀ M) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ _ @[simp] lemma mem_support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} : a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 := by rw [finsupp.mem_support_iff, finsupp.on_finset_apply] lemma support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : (finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) := rfl end on_finset section of_support_finite variables [has_zero M] /-- The natural `finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def of_support_finite (f : α → M) (hf : (function.support f).finite) : α →₀ M := { support := hf.to_finset, to_fun := f, mem_support_to_fun := λ _, hf.mem_to_finset } lemma of_support_finite_coe {f : α → M} {hf : (function.support f).finite} : (of_support_finite f hf : α → M) = f := rfl instance : can_lift (α → M) (α →₀ M) := { coe := coe_fn, cond := λ f, (function.support f).finite, prf := λ f hf, ⟨of_support_finite f hf, rfl⟩ } end of_support_finite /-! ### Declarations about `map_range` -/ section map_range variables [has_zero M] [has_zero N] [has_zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled: * `finsupp.map_range.equiv` * `finsupp.map_range.zero_hom` * `finsupp.map_range.add_monoid_hom` * `finsupp.map_range.add_equiv` * `finsupp.map_range.linear_map` * `finsupp.map_range.linear_equiv` -/ def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 := ext $ λ a, by simp only [hf, zero_apply, map_range_apply] @[simp] lemma map_range_id (g : α →₀ M) : map_range id rfl g = g := ext $ λ _, rfl lemma map_range_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : map_range (f ∘ f₂) h g = map_range f hf (map_range f₂ hf₂ g) := ext $ λ _, rfl lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : map_range f hf (single a b) = single a (f b) := ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range /-! ### Declarations about `emb_domain` -/ section emb_domain variables [has_zero M] [has_zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) }, { assume a₂, split_ifs, { simp only [h, true_iff, ne.def], rw [← not_mem_support_iff, not_not], apply finset.choose_mem }, { simp only [h, ne.def, ne_self_iff_false] } } end @[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) : (emb_domain f v).support = v.support.map f := rfl @[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 := rfl @[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α → M) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_injective (f : α ↪ β) : function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) := λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a) @[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := (emb_domain_injective f).eq_iff @[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} : emb_domain f l = 0 ↔ l = 0 := (emb_domain_injective f).eq_iff' $ emb_domain_zero f lemma emb_domain_map_range (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : l.emb_domain f = single a b) : ∃ x, l = single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = {a}, by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl, have ha : a ∈ finset.map f (l.support), by simp only [h_map_support, finset.mem_singleton], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← emb_domain_apply f l, h], by_cases h_cases : c = d, { simp only [eq.symm h_cases, hc₂, single_eq_same] }, { rw [single_apply, single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.injective (hc₂.trans hfd)) } }, { exact hc₂ } end @[simp] lemma emb_domain_single (f : α ↪ β) (a : α) (m : M) : emb_domain f (single a m) = single (f a) m := begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a', rfl⟩, simp [single_apply], }, { simp only [emb_domain_notin_range, h, single_apply, not_false_iff], rw if_neg, rintro rfl, simpa using h, }, end end emb_domain /-! ### Declarations about `zip_with` -/ section zip_with variables [has_zero M] [has_zero N] [has_zero P] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/ def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : (α →₀ P) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with [D : decidable_eq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by rw subsingleton.elim D; exact support_on_finset_subset end zip_with /-! ### Declarations about `erase` -/ section erase variables [has_zero M] /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. -/ def erase (a : α) (f : α →₀ M) : α →₀ M := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase {a : α} {f : α →₀ M} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h @[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 := begin ext s, by_cases hs : s = a, { rw [hs, erase_same], refl }, { rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) } end lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b := begin ext s, by_cases hs : s = a, { rw [hs, erase_same, single_eq_of_ne (h.symm)] }, { rw [erase_ne hs] } end @[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by rw [← support_eq_empty, support_erase, support_zero, erase_empty] end erase /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ section sum_prod -- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∑ a in f.support, g a (f a) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive] def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∏ a in f.support, g a (f a) variables [has_zero M] [has_zero M'] [comm_monoid N] @[to_additive] lemma prod_of_support_subset (f : α →₀ M) {s : finset α} (hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) : f.prod g = ∏ x in s, g x (f x) := finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx @[to_additive] lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := f.prod_of_support_subset (subset_univ _) g (λ x _, h x) @[simp, to_additive] lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := calc (single a b).prod h = ∏ x in {a}, h x (single a b x) : prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero ... = h a b : by simp @[to_additive] lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[simp, to_additive] lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl @[to_additive] lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := finset.prod_comm @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } @[simp] lemma sum_ite_self_eq [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (a = x) v 0) = f a := by { convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma sum_ite_self_eq' [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (x = a) v 0) = f a := by { convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } @[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := f.prod_fintype _ $ λ a, pow_zero _ /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ @[to_additive "If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`."] lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) : (on_finset s f hf).prod g = ∏ a in s, g a (f a) := finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt } @[to_additive] lemma _root_.submonoid.finsupp_prod_mem (S : submonoid N) (f : α →₀ M) (g : α → M → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.prod g ∈ S := S.prod_mem $ λ i hi, h _ (finsupp.mem_support_iff.mp hi) end sum_prod /-! ### Additive monoid structure on `α →₀ M` -/ section add_zero_class variables [add_zero_class M] instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl lemma add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add [decidable_eq α] {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq [decidable_eq α] {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : M} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_zero_class (α →₀ M) := { zero := 0, add := (+), zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } /-- `finsupp.single` as an `add_monoid_hom`. See `finsupp.lsingle` for the stronger version as a linear map. -/ @[simps] def single_add_hom (a : α) : M →+ α →₀ M := ⟨single a, single_zero, λ _ _, single_add⟩ /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `finsupp.lapply` for the stronger version as a linear map. -/ @[simps apply] def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply _ _ _⟩ lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero] else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)] lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add] else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)] @[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := begin ext s, by_cases hs : s = a, { rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] }, rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply], end @[elab_as_eliminator] protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) : p f := induction₂ f h0 (λ a b f _ _ w, hadd _ _ w (hsingle _ _)) @[simp] lemma add_closure_Union_range_single : add_submonoid.closure (⋃ a : α, set.range (single a : M → α →₀ M)) = ⊤ := top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $ λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ set.mem_Union.2 ⟨a, set.mem_range_self _⟩) hf /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x y, f (single x y) = g (single x y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_Union_range_single (λ f hf, _), simp only [set.mem_Union, set.mem_range] at hf, rcases hf with ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext] lemma add_hom_ext' [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) lemma mul_hom_ext [mul_one_class N] ⦃f g : multiplicative (α →₀ M) →* N⦄ (H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) : f = g := monoid_hom.ext $ add_monoid_hom.congr_fun $ @add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H @[ext] lemma mul_hom_ext' [mul_one_class N] {f g : multiplicative (α →₀ M) →* N} (H : ∀ x, f.comp (single_add_hom x).to_multiplicative = g.comp (single_add_hom x).to_multiplicative) : f = g := mul_hom_ext $ λ x, monoid_hom.congr_fun (H x) lemma map_range_add [add_zero_class N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := ext $ λ a, by simp only [hf', add_apply, map_range_apply] /-- Bundle `emb_domain f` as an additive map from `α →₀ M` to `β →₀ M`. -/ @[simps] def emb_domain.add_monoid_hom (f : α ↪ β) : (α →₀ M) →+ (β →₀ M) := { to_fun := λ v, emb_domain f v, map_zero' := by simp, map_add' := λ v w, begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a, rfl⟩, simp, }, { simp [emb_domain_notin_range, h], }, end, } @[simp] lemma emb_domain_add (f : α ↪ β) (v w : α →₀ M) : emb_domain f (v + w) = emb_domain f v + emb_domain f w := (emb_domain.add_monoid_hom f).map_add v w end add_zero_class section add_monoid variables [add_monoid M] instance : add_monoid (α →₀ M) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, nsmul := λ n v, v.map_range ((•) n) (nsmul_zero _), nsmul_zero' := λ v, by { ext i, simp }, nsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_nsmul] }, .. finsupp.add_zero_class } end add_monoid end finsupp @[to_additive] lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := h.map_sum _ _ lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(f.prod g) = f.prod (λ i fi, g i fi) := monoid_hom.coe_prod _ _ @[simp, to_additive] lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) (x : N) : f.prod g x = f.prod (λ i fi, g i fi x) := monoid_hom.finset_prod_apply _ _ _ namespace finsupp section nat_sub instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩ @[simp] lemma coe_nat_sub (g₁ g₂ : α →₀ ℕ) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma nat_sub_apply (g₁ g₂ : α →₀ ℕ) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma single_nat_sub {a : α} {n₁ n₂ : ℕ} : single a (n₁ - n₂) = single a n₁ - single a n₂ := begin ext f, by_cases h : (a = f), { rw [h, nat_sub_apply, single_eq_same, single_eq_same, single_eq_same] }, rw [nat_sub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h] end -- These next two lemmas are used in developing -- the partial derivative on `mv_polynomial`. lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := begin ext b, rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply], by_cases h : a = b, { rw [←h, single_eq_same], cases (u a), { contradiction }, { simp }, }, { simp [h], } end lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := begin ext b, rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply], by_cases h : a = b, { rw [←h, single_eq_same], cases (u' a), { contradiction }, { simp }, }, { simp [h], } end @[simp] lemma nat_zero_sub (f : α →₀ ℕ) : 0 - f = 0 := ext $ λ x, nat.zero_sub _ end nat_sub instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group G] : has_sub (α →₀ G) := ⟨zip_with has_sub.sub (sub_zero _)⟩ instance [add_group G] : add_group (α →₀ G) := { neg := map_range (has_neg.neg) neg_zero, sub := has_sub.sub, sub_eq_add_neg := λ x y, ext (λ i, sub_eq_add_neg _ _), add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, gsmul := λ n v, v.map_range ((•) n) (gsmul_zero _), gsmul_zero' := λ v, by { ext i, simp }, gsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_gsmul] }, gsmul_neg' := λ n v, by { ext i, simp only [nat.succ_eq_add_one, map_range_apply, gsmul_neg_succ_of_nat, int.coe_nat_succ, neg_inj, add_gsmul, add_nsmul, one_gsmul, gsmul_coe_nat, one_nsmul] }, .. finsupp.add_monoid } instance [add_comm_group G] : add_comm_group (α →₀ G) := { add_comm := add_comm, ..finsupp.add_group } lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma coe_neg [add_group G] (g : α →₀ G) : ⇑(-g) = -g := rfl lemma neg_apply [add_group G] (g : α →₀ G) (a : α) : (- g) a = - g a := rfl @[simp] lemma coe_sub [add_group G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma sub_apply [add_group G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group G] {f : α →₀ G} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) @[simp] lemma sum_apply [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (apply_add_hom a₂ : (β →₀ N) →+ _).map_sum _ _ lemma support_sum [decidable_eq β] [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → (β →₀ N)} : (f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) := have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop] @[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} : f.sum (λa b, (0 : N)) = 0 := finset.sum_const_zero @[simp, to_additive] lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} : f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M} {h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ := (((monoid_hom.id G)⁻¹).map_prod _ _).symm @[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M} {h₁ h₂ : α → M → G} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := finset.sum_sub_distrib @[to_additive] lemma prod_add_index [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have hf : f.prod h = ∏ a in f.support ∪ g.support, h a (f a), from f.prod_of_support_subset (subset_union_left _ _) _ $ λ a ha, h_zero a, have hg : g.prod h = ∏ a in f.support ∪ g.support, h a (g a), from g.prod_of_support_subset (subset_union_right _ _) _ $ λ a ha, h_zero a, have hfg : (f + g).prod h = ∏ a in f.support ∪ g.support, h a ((f + g) a), from (f + g).prod_of_support_subset support_add _ $ λ a ha, h_zero a, by simp only [*, add_apply, prod_mul_distrib] @[simp] lemma sum_add_index' [add_comm_monoid M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) : (f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) := sum_add_index (λ a, (h a).map_zero) (λ a, (h a).map_add) @[simp] lemma prod_add_index' [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} (h : α → multiplicative M →* N) : (f + g).prod (λ a b, h a (multiplicative.of_add b)) = f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) := prod_add_index (λ a, (h a).map_one) (λ a, (h a).map_mul) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom [add_comm_monoid M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := { to_fun := λ F, { to_fun := λ f, f.sum (λ x, F x), map_zero' := finset.sum_empty, map_add' := λ _ _, sum_add_index (λ x, (F x).map_zero) (λ x, (F x).map_add) }, inv_fun := λ F x, F.comp $ single_add_hom x, left_inv := λ F, by { ext, simp }, right_inv := λ F, by { ext, simp }, map_add' := λ F G, by { ext, simp } } @[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : lift_add_hom F f = f.sum (λ x, F x) := rfl @[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : lift_add_hom.symm F x = F.comp (single_add_hom x) := rfl lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : lift_add_hom.symm F x y = F (single x y) := rfl @[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] : lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) : f.sum single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : lift_add_hom f (single a b) = f a b := sum_single_index (f a).map_zero @[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : (lift_add_hom f).comp (single_add_hom a) = f a := add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g @[to_additive] lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : (v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) := begin rw [prod, prod, support_emb_domain, finset.prod_map], simp_rw emb_domain_apply, end @[to_additive] lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma support_sum_eq_bUnion {α : Type*} {ι : Type*} {M : Type*} [add_comm_monoid M] {g : ι → α →₀ M} (s : finset ι) (h : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint (g i₁).support (g i₂).support) : (∑ i in s, g i).support = s.bUnion (λ i, (g i).support) := begin apply finset.induction_on s, { simp }, { intros i s hi, simp only [hi, sum_insert, not_false_iff, bUnion_insert], intro hs, rw [finsupp.support_add_eq, hs], rw [hs], intros x hx, simp only [mem_bUnion, exists_prop, inf_eq_inter, ne.def, mem_inter] at hx, obtain ⟨hxi, j, hj, hxj⟩ := hx, have hn : i ≠ j := λ H, hi (H.symm ▸ hj), apply h _ _ hn, simp [hxi, hxj] } end lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (multiset.map_add_monoid_hom m).map_sum _ f.support lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (multiset.sum_add_monoid_hom : multiset N →+ N).map_sum _ f.support section map_range section equiv variables [has_zero M] [has_zero N] [has_zero P] /-- `finsupp.map_range` as an equiv. -/ @[simps apply] def map_range.equiv (f : M ≃ N) (hf : f 0 = 0) (hf' : f.symm 0 = 0) : (α →₀ M) ≃ (α →₀ N) := { to_fun := (map_range f hf : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm hf' : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end } @[simp] lemma map_range.equiv_refl : map_range.equiv (equiv.refl M) rfl rfl = equiv.refl (α →₀ M) := equiv.ext map_range_id lemma map_range.equiv_trans (f : M ≃ N) (hf : f 0 = 0) (hf') (f₂ : N ≃ P) (hf₂ : f₂ 0 = 0) (hf₂') : (map_range.equiv (f.trans f₂) (by rw [equiv.trans_apply, hf, hf₂]) (by rw [equiv.symm_trans_apply, hf₂', hf']) : (α →₀ _) ≃ _) = (map_range.equiv f hf hf').trans (map_range.equiv f₂ hf₂ hf₂') := equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.equiv_symm (f : M ≃ N) (hf hf') : ((map_range.equiv f hf hf').symm : (α →₀ _) ≃ _) = map_range.equiv f.symm hf' hf := equiv.ext $ λ x, rfl end equiv section zero_hom variables [has_zero M] [has_zero N] [has_zero P] /-- Composition with a fixed zero-preserving homomorphism is itself an zero-preserving homomorphism on functions. -/ @[simps] def map_range.zero_hom (f : zero_hom M N) : zero_hom (α →₀ M) (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero } @[simp] lemma map_range.zero_hom_id : map_range.zero_hom (zero_hom.id M) = zero_hom.id (α →₀ M) := zero_hom.ext map_range_id lemma map_range.zero_hom_comp (f : zero_hom N P) (f₂ : zero_hom M N) : (map_range.zero_hom (f.comp f₂) : zero_hom (α →₀ _) _) = (map_range.zero_hom f).comp (map_range.zero_hom f₂) := zero_hom.ext $ map_range_comp _ _ _ _ _ end zero_hom section add_monoid_hom variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ @[simps] def map_range.add_monoid_hom (f : M →+ N) : (α →₀ M) →+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero, map_add' := λ a b, map_range_add f.map_add _ _ } @[simp] lemma map_range.add_monoid_hom_id : map_range.add_monoid_hom (add_monoid_hom.id M) = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext map_range_id lemma map_range.add_monoid_hom_comp (f : N →+ P) (f₂ : M →+ N) : (map_range.add_monoid_hom (f.comp f₂) : (α →₀ _) →+ _) = (map_range.add_monoid_hom f).comp (map_range.add_monoid_hom f₂) := add_monoid_hom.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_monoid_hom_to_zero_hom (f : M →+ N) : (map_range.add_monoid_hom f).to_zero_hom = (map_range.zero_hom f.to_zero_hom : zero_hom (α →₀ _) _) := zero_hom.ext $ λ _, rfl lemma map_range_multiset_sum (f : M →+ N) (m : multiset (α →₀ M)) : map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_multiset_sum _ lemma map_range_finset_sum (f : M →+ N) (s : finset ι) (g : ι → (α →₀ M)) : map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_sum _ _ /-- `finsupp.map_range.add_monoid_hom` as an equiv. -/ @[simps apply] def map_range.add_equiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm f.symm.map_zero : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end, ..(map_range.add_monoid_hom f.to_add_monoid_hom) } @[simp] lemma map_range.add_equiv_refl : map_range.add_equiv (add_equiv.refl M) = add_equiv.refl (α →₀ M) := add_equiv.ext map_range_id lemma map_range.add_equiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) : (map_range.add_equiv (f.trans f₂) : (α →₀ _) ≃+ _) = (map_range.add_equiv f).trans (map_range.add_equiv f₂) := add_equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_equiv_symm (f : M ≃+ N) : ((map_range.add_equiv f).symm : (α →₀ _) ≃+ _) = map_range.add_equiv f.symm := add_equiv.ext $ λ x, rfl @[simp] lemma map_range.add_equiv_to_add_monoid_hom (f : M ≃+ N) : (map_range.add_equiv f : (α →₀ _) ≃+ _).to_add_monoid_hom = (map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ _) →+ _) := add_monoid_hom.ext $ λ _, rfl @[simp] lemma map_range.add_equiv_to_equiv (f : M ≃+ N) : (map_range.add_equiv f).to_equiv = (map_range.equiv f.to_equiv f.map_zero f.symm.map_zero : (α →₀ _) ≃ _) := equiv.ext $ λ _, rfl end add_monoid_hom end map_range /-! ### Declarations about `map_domain` -/ section map_domain variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M} /-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α → β) (v : α →₀ M) : β →₀ M := v.sum $ λa, single (f a) lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] } end lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end @[simp] lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → β} {g : β → γ} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (λ _ _, sum_single_index _), { exact single_zero } end @[simp] lemma map_domain_single {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] lemma map_domain_zero {f : α → β} : map_domain f (0 : α →₀ M) = (0 : β →₀ M) := sum_zero_index lemma map_domain_congr {f g : α → β} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) @[simp] lemma map_domain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) : map_domain f x a = x (f.symm a) := begin conv_lhs { rw ←f.apply_symm_apply a }, exact map_domain_apply f.injective _ _, end /-- `finsupp.map_domain` is an `add_monoid_hom`. -/ @[simps] def map_domain.add_monoid_hom (f : α → β) : (α →₀ M) →+ (β →₀ M) := { to_fun := map_domain f, map_zero' := map_domain_zero, map_add' := λ _ _, map_domain_add} @[simp] lemma map_domain.add_monoid_hom_id : map_domain.add_monoid_hom id = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext $ λ _, map_domain_id lemma map_domain.add_monoid_hom_comp (f : β → γ) (g : α → β) : (map_domain.add_monoid_hom (f ∘ g) : (α →₀ M) →+ (γ →₀ M)) = (map_domain.add_monoid_hom f).comp (map_domain.add_monoid_hom g) := add_monoid_hom.ext $ λ _, map_domain_comp lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} : map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_sum _ _ lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_finsupp_sum _ _ lemma map_domain_support [decidable_eq β] {f : α → β} {s : α →₀ M} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bUnion_mono $ assume a ha, support_single_subset) $ by rw [finset.bUnion_singleton]; exact subset.refl _ @[to_additive] lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀b, h b 0 = 1) (h_add : ∀b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) : (map_domain f s).prod h = s.prod (λa m, h (f a) m) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _) /-- A version of `sum_map_domain_index` that takes a bundled `add_monoid_hom`, rather than separate linearity hypotheses. -/ -- Note that in `prod_map_domain_index`, `M` is still an additive monoid, -- so there is no analogous version in terms of `monoid_hom`. @[simp] lemma sum_map_domain_index_add_monoid_hom [add_comm_monoid N] {f : α → β} {s : α →₀ M} (h : β → M →+ N) : (map_domain f s).sum (λ b m, h b m) = s.sum (λ a m, h (f a) m) := @sum_map_domain_index _ _ _ _ _ _ _ _ (λ b m, h b m) (λ b, (h b).map_zero) (λ b m₁ m₂, (h b).map_add _ _) lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply f.injective, emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end @[to_additive] lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : function.injective f) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain] lemma map_domain_injective {f : α → β} (hf : function.injective f) : function.injective (map_domain f : (α →₀ M) → (β →₀ M)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end lemma map_domain.add_monoid_hom_comp_map_range [add_comm_monoid N] (f : α → β) (g : M →+ N) : (map_domain.add_monoid_hom f).comp (map_range.add_monoid_hom g) = (map_range.add_monoid_hom g).comp (map_domain.add_monoid_hom f) := by { ext, simp } /-- When `g` preserves addition, `map_range` and `map_domain` commute. -/ lemma map_domain_map_range [add_comm_monoid N] (f : α → β) (v : α →₀ M) (g : M → N) (h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) : map_domain f (map_range g h0 v) = map_range g h0 (map_domain f v) := let g' : M →+ N := { to_fun := g, map_zero' := h0, map_add' := hadd} in add_monoid_hom.congr_fun (map_domain.add_monoid_hom_comp_map_range f g') v end map_domain /-! ### Declarations about `comap_domain` -/ section comap_domain /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α →₀ M := { support := l.support.preimage f hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } @[simp] lemma comap_domain_apply [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) : comap_domain f l hf a = l (f a) := rfl lemma sum_comap_domain [has_zero M] [add_comm_monoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : (comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g := begin simp only [sum, comap_domain_apply, (∘)], simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))], end lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : comap_domain f l hf.inj_on = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end lemma map_domain_comap_domain [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : function.injective f) (hl : ↑l.support ⊆ set.range f): map_domain f (comap_domain f l (hf.inj_on _)) = l := begin ext a, by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) } end end comap_domain section option /-- Restrict a finitely supported function on `option α` to a finitely supported function on `α`. -/ def some [has_zero M] (f : option α →₀ M) : α →₀ M := f.comap_domain option.some (λ _, by simp) @[simp] lemma some_apply [has_zero M] (f : option α →₀ M) (a : α) : f.some a = f (option.some a) := rfl @[simp] lemma some_zero [has_zero M] : (0 : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_add [add_comm_monoid M] (f g : option α →₀ M) : (f + g).some = f.some + g.some := by { ext, simp, } @[simp] lemma some_single_none [has_zero M] (m : M) : (single none m : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_single_some [has_zero M] (a : α) (m : M) : (single (option.some a) m : option α →₀ M).some = single a m := by { ext b, simp [single_apply], } @[to_additive] lemma prod_option_index [add_comm_monoid M] [comm_monoid N] (f : option α →₀ M) (b : option α → M → N) (h_zero : ∀ o, b o 0 = 1) (h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) : f.prod b = b none (f none) * f.some.prod (λ a, b (option.some a)) := begin apply induction_linear f, { simp [h_zero], }, { intros f₁ f₂ h₁ h₂, rw [finsupp.prod_add_index, h₁, h₂, some_add, finsupp.prod_add_index], simp only [h_add, pi.add_apply, finsupp.coe_add], rw mul_mul_mul_comm, all_goals { simp [h_zero, h_add], }, }, { rintros (_|a) m; simp [h_zero, h_add], } end lemma sum_option_index_smul [semiring R] [add_comm_monoid M] [module R M] (f : option α →₀ R) (b : option α → M) : f.sum (λ o r, r • b o) = f none • b none + f.some.sum (λ a r, r • b (option.some a)) := f.sum_option_index _ (λ _, zero_smul _ _) (λ _ _ _, add_smul _ _ _) end option /-! ### Declarations about `equiv_congr_left` -/ section equiv_congr_left variable [has_zero M] /-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equiv_map_domain f l : β →₀ M` (computably) by mapping the support forwards and the function backwards. -/ def equiv_map_domain (f : α ≃ β) (l : α →₀ M) : β →₀ M := { support := l.support.map f.to_embedding, to_fun := λ a, l (f.symm a), mem_support_to_fun := λ a, by simp only [finset.mem_map_equiv, mem_support_to_fun]; refl } @[simp] lemma equiv_map_domain_apply (f : α ≃ β) (l : α →₀ M) (b : β) : equiv_map_domain f l b = l (f.symm b) := rfl lemma equiv_map_domain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) : equiv_map_domain f.symm l a = l (f a) := rfl @[simp] lemma equiv_map_domain_refl (l : α →₀ M) : equiv_map_domain (equiv.refl _) l = l := by ext x; refl lemma equiv_map_domain_refl' : equiv_map_domain (equiv.refl _) = @id (α →₀ M) := by ext x; refl lemma equiv_map_domain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) : equiv_map_domain (f.trans g) l = equiv_map_domain g (equiv_map_domain f l) := by ext x; refl lemma equiv_map_domain_trans' (f : α ≃ β) (g : β ≃ γ) : @equiv_map_domain _ _ M _ (f.trans g) = equiv_map_domain g ∘ equiv_map_domain f := by ext x; refl @[simp] lemma equiv_map_domain_single (f : α ≃ β) (a : α) (b : M) : equiv_map_domain f (single a b) = single (f a) b := by ext x; simp only [single_apply, equiv.apply_eq_iff_eq_symm_apply, equiv_map_domain_apply]; congr @[simp] lemma equiv_map_domain_zero {f : α ≃ β} : equiv_map_domain f (0 : α →₀ M) = (0 : β →₀ M) := by ext x; simp only [equiv_map_domain_apply, coe_zero, pi.zero_apply] lemma equiv_map_domain_eq_map_domain {M} [add_comm_monoid M] (f : α ≃ β) (l : α →₀ M) : equiv_map_domain f l = map_domain f l := by ext x; simp [map_domain_equiv_apply] /-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection: `(α →₀ M) ≃ (β →₀ M)`. This is the finitely-supported version of `equiv.Pi_congr_left`. -/ def equiv_congr_left (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) := by refine ⟨equiv_map_domain f, equiv_map_domain f.symm, λ f, _, λ f, _⟩; ext x; simp only [equiv_map_domain_apply, equiv.symm_symm, equiv.symm_apply_apply, equiv.apply_symm_apply] @[simp] lemma equiv_congr_left_apply (f : α ≃ β) (l : α →₀ M) : equiv_congr_left f l = equiv_map_domain f l := rfl @[simp] lemma equiv_congr_left_symm (f : α ≃ β) : (@equiv_congr_left _ _ M _ f).symm = equiv_congr_left f.symm := rfl end equiv_congr_left /-! ### Declarations about `filter` -/ section filter section has_zero variables [has_zero M] (p : α → Prop) (f : α →₀ M) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ M) : α →₀ M := { to_fun := λ a, if p a then f a else 0, support := f.support.filter (λ a, p a), mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } } lemma filter_apply (a : α) [D : decidable (p a)] : f.filter p a = if p a then f a else 0 := by rw subsingleton.elim D; refl lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter [D : decidable_pred p] : (f.filter p).support = f.support.filter p := by rw subsingleton.elim D; refl lemma filter_zero : (0 : α →₀ M).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b := coe_fn_injective $ by simp [filter_eq_indicator, set.subset_def, mem_support_single, h] @[simp] lemma filter_single_of_neg {a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 := ext $ by simp [filter_eq_indicator, single_apply_eq_zero, @imp.swap (p _), h] end has_zero lemma filter_pos_add_filter_neg [add_zero_class M] (f : α →₀ M) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := coe_fn_injective $ set.indicator_self_add_compl {x | p x} f end filter /-! ### Declarations about `frange` -/ section frange variables [has_zero M] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ M) : finset M := finset.image f f.support theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ M} : (0:M) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange /-! ### Declarations about `subtype_domain` -/ section subtype_domain section zero variables [has_zero M] {p : α → Prop} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) := ⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain [D : decidable_pred p] {f : α →₀ M} : (subtype_domain p f).support = f.support.subtype p := by rw subsingleton.elim D; refl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 := rfl lemma subtype_domain_eq_zero_iff' {f : α →₀ M} : f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 := by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff] lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) : f.subtype_domain p = 0 ↔ f = 0 := subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x, if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩ @[to_additive] lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section add_zero_class variables [add_zero_class M] {p : α → Prop} {v v' : α →₀ M} @[simp] lemma subtype_domain_add {v v' : α →₀ M} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl /-- `subtype_domain` but as an `add_monoid_hom`. -/ def subtype_domain_add_monoid_hom : (α →₀ M) →+ subtype p →₀ M := { to_fun := subtype_domain p, map_zero' := subtype_domain_zero, map_add' := λ _ _, subtype_domain_add } /-- `finsupp.filter` as an `add_monoid_hom`. -/ def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) := { to_fun := filter p, map_zero' := filter_zero p, map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g } @[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p := (filter_add_hom p).map_add v v' end add_zero_class section comm_monoid variables [add_comm_monoid M] {p : α → Prop} lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := (subtype_domain_add_monoid_hom : _ →+ subtype p →₀ M).map_sum _ s lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset ι) (f : ι → α →₀ M) : (∑ a in s, f a).filter p = ∑ a in s, filter p (f a) := (filter_add_hom p : (α →₀ M) →+ _).map_sum f s lemma filter_eq_sum (p : α → Prop) [D : decidable_pred p] (f : α →₀ M) : f.filter p = ∑ i in f.support.filter p, single i (f i) := (f.filter p).sum_single.symm.trans $ finset.sum_congr (by rw subsingleton.elim D; refl) $ λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2] end comm_monoid section group variables [add_group G] {p : α → Prop} {v v' : α →₀ G} @[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl @[simp] lemma single_neg {a : α} {b : G} : single a (-b) = -single a b := (single_add_hom a : G →+ _).map_neg b @[simp] lemma single_sub {a : α} {b₁ b₂ : G} : single a (b₁ - b₂) = single a b₁ - single a b₂ := (single_add_hom a : G →+ _).map_sub b₁ b₂ end group end subtype_domain /-! ### Declarations relating `finsupp` to `multiset` -/ section multiset /-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of `f` on the elements of `α`. We define this function as an `add_equiv`. -/ def to_multiset : (α →₀ ℕ) ≃+ multiset α := { to_fun := λ f, f.sum (λa n, n • {a}), inv_fun := λ s, ⟨s.to_finset, λ a, s.count a, λ a, by simp⟩, left_inv := λ f, ext $ λ a, by { simp only [sum, multiset.count_sum', multiset.count_singleton, mul_boole, coe_mk, multiset.mem_to_finset, iff_self, not_not, mem_support_iff, ite_eq_left_iff, ne.def, multiset.count_eq_zero, multiset.count_nsmul, finset.sum_ite_eq, ite_not], exact eq.symm }, right_inv := λ s, by simp only [sum, coe_mk, multiset.to_finset_sum_count_nsmul_eq], map_add' := λ f g, sum_add_index (λ a, zero_nsmul _) (λ a, add_nsmul _) } lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 := rfl lemma to_multiset_add (m n : α →₀ ℕ) : (m + n).to_multiset = m.to_multiset + n.to_multiset := to_multiset.map_add m n lemma to_multiset_apply (f : α →₀ ℕ) : f.to_multiset = f.sum (λ a n, n • {a}) := rfl @[simp] lemma to_multiset_symm_apply (s : multiset α) (x : α) : finsupp.to_multiset.symm s x = s.count x := rfl @[simp] lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n • {a} := by rw [to_multiset_apply, sum_single_index]; apply zero_nsmul lemma to_multiset_sum {ι : Type*} {f : ι → α →₀ ℕ} (s : finset ι) : finsupp.to_multiset (∑ i in s, f i) = ∑ i in s, finsupp.to_multiset (f i) := add_equiv.map_sum _ _ _ lemma to_multiset_sum_single {ι : Type*} (s : finset ι) (n : ℕ) : finsupp.to_multiset (∑ i in s, single i n) = n • s.val := by simp_rw [to_multiset_sum, finsupp.to_multiset_single, sum_nsmul, sum_multiset_singleton] lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) := by simp [to_multiset_apply, add_monoid_hom.map_finsupp_sum, function.id_def] lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) : f.to_multiset.map g = (f.map_domain g).to_multiset := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single, to_multiset_single, to_multiset_add, to_multiset_single, ← multiset.coe_map_add_monoid_hom, (multiset.map_add_monoid_hom g).map_nsmul], refl } end @[simp] lemma prod_to_multiset [comm_monoid M] (f : M →₀ ℕ) : f.to_multiset.prod = f.prod (λa n, a ^ n) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index, finsupp.prod_single_index, multiset.prod_nsmul, multiset.prod_singleton], { exact pow_zero a }, { exact pow_zero }, { exact pow_add } } end @[simp] lemma to_finset_to_multiset [decidable_eq α] (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.to_finset_zero, support_zero] }, { assume a n f ha hn ih, rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq, support_single_ne_zero hn, multiset.to_finset_nsmul _ _ hn, multiset.to_finset_singleton], refine disjoint.mono_left support_single_subset _, rwa [finset.singleton_disjoint] } end @[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (n • {x} : multiset α).count a) : (multiset.count_add_monoid_hom a).map_sum _ f.support ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_nsmul] ... = f a * ({a} : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_singleton, if_false, H.symm, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by rw [multiset.count_singleton_self, mul_one] lemma mem_support_multiset_sum [add_comm_monoid M] {s : multiset (α →₀ M)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid M] {s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃ c ∈ s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ @[simp] lemma mem_to_multiset (f : α →₀ ℕ) (i : α) : i ∈ f.to_multiset ↔ i ∈ f.support := by rw [← multiset.count_ne_zero, finsupp.count_to_multiset, finsupp.mem_support_iff] end multiset /-! ### Declarations about `curry` and `uncurry` -/ section curry_uncurry variables [add_comm_monoid M] [add_comm_monoid N] /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry (f : (α × β) →₀ M) : α →₀ (β →₀ M) := f.sum $ λp c, single p.1 (single p.2 c) @[simp] lemma curry_apply (f : (α × β) →₀ M) (x : α) (y : β) : f.curry x y = f (x, y) := begin have : ∀ (b : α × β), single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0, { rintros ⟨b₁, b₂⟩, simp [single_apply, ite_apply, prod.ext_iff, ite_and], split_ifs; simp [single_apply, *] }, rw [finsupp.curry, sum_apply, sum_apply, finsupp.sum, finset.sum_eq_single, this, if_pos rfl], { intros b hb b_ne, rw [this b, if_neg b_ne] }, { intros hxy, rw [this (x, y), if_pos rfl, not_mem_support_iff.mp hxy] } end lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M := f.sum $ λa g, g.sum $ λb c, single (a, b) c /-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry (f : α × β →₀ M) (p : α → Prop) : (f.filter (λa:α×β, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, filter_sum, support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry [decidable_eq α] (f : α × β →₀ M) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bUnion_singleton, refine finset.subset.trans support_sum _, refine finset.bUnion_mono (assume a _, support_single_subset) end end curry_uncurry section sum /-- `finsupp.sum_elim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/ def sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ := on_finset ((f.support.map ⟨_, sum.inl_injective⟩) ∪ g.support.map ⟨_, sum.inr_injective⟩) (sum.elim f g) (λ ab h, by { cases ab with a b; simp only [sum.elim_inl, sum.elim_inr] at h; simpa }) @[simp] lemma coe_sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : ⇑(sum_elim f g) = sum.elim f g := rfl lemma sum_elim_apply {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) : sum_elim f g x = sum.elim f g x := rfl lemma sum_elim_inl {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α) : sum_elim f g (sum.inl x) = f x := rfl lemma sum_elim_inr {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : β) : sum_elim f g (sum.inr x) = g x := rfl /-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] : ((α ⊕ β) →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) := { to_fun := λ f, ⟨f.comap_domain sum.inl (sum.inl_injective.inj_on _), f.comap_domain sum.inr (sum.inr_injective.inj_on _)⟩, inv_fun := λ fg, sum_elim fg.1 fg.2, left_inv := λ f, by { ext ab, cases ab with a b; simp }, right_inv := λ fg, by { ext; simp } } lemma fst_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (x : α) : (sum_finsupp_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (y : β) : (sum_finsupp_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inl {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (x : α) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inr {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (y : β) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl variables [add_monoid M] /-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_add_equiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃+ (α →₀ M) × (β →₀ M) := { map_add' := by { intros, ext; simp only [equiv.to_fun_as_coe, prod.fst_add, prod.snd_add, add_apply, snd_sum_finsupp_equiv_prod_finsupp, fst_sum_finsupp_equiv_prod_finsupp] }, .. sum_finsupp_equiv_prod_finsupp } lemma fst_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_add_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_add_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl end sum section variables [group G] [mul_action G α] [add_comm_monoid M] /-- Scalar multiplication by a group element g, given by precomposition with the action of g⁻¹ on the domain. -/ def comap_has_scalar : has_scalar G (α →₀ M) := { smul := λ g f, f.comap_domain (λ a, g⁻¹ • a) (λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) } local attribute [instance] comap_has_scalar /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is multiplicative in g. -/ def comap_mul_action : mul_action G (α →₀ M) := { one_smul := λ f, by { ext, dsimp [(•)], simp, }, mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, } local attribute [instance] comap_mul_action /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is additive in the second argument. -/ def comap_distrib_mul_action : distrib_mul_action G (α →₀ M) := { smul_zero := λ g, by { ext, dsimp [(•)], simp, }, smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, } /-- Scalar multiplication by a group element on finitely supported functions on a group, given by precomposition with the action of g⁻¹. -/ def comap_distrib_mul_action_self : distrib_mul_action G (G →₀ M) := @finsupp.comap_distrib_mul_action G M G _ (monoid.to_mul_action G) _ @[simp] lemma comap_smul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := begin ext a', dsimp [(•)], by_cases h : g • a = a', { subst h, simp [←mul_smul], }, { simp [single_eq_of_ne h], rw [single_eq_of_ne], rintro rfl, simpa [←mul_smul] using h, } end @[simp] lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := rfl end section instance [monoid R] [add_monoid M] [distrib_mul_action R M] : has_scalar R (α →₀ M) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ /-! Throughout this section, some `monoid` and `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp] lemma coe_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • v := rfl lemma smul_apply {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) (a : α) : (b • v) a = b • (v a) := rfl lemma _root_.is_smul_regular.finsupp {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {k : R} (hk : is_smul_regular M k) : is_smul_regular (α →₀ M) k := λ _ _ h, ext $ λ i, hk (congr_fun h i) instance [monoid R] [nonempty α] [add_monoid M] [distrib_mul_action R M] [has_faithful_scalar R M] : has_faithful_scalar R (α →₀ M) := { eq_of_smul_eq_smul := λ r₁ r₂ h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ m : M, by simpa using congr_fun (h (single a m)) a } variables (α M) instance [monoid R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (α →₀ M) := { smul := (•), smul_add := λ a x y, ext $ λ _, smul_add _ _ _, one_smul := λ x, ext $ λ _, one_smul _ _, mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _, smul_zero := λ x, ext $ λ _, smul_zero _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [has_scalar R S] [is_scalar_tower R S M] : is_scalar_tower R S (α →₀ M) := { smul_assoc := λ r s a, ext $ λ _, smul_assoc _ _ _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [smul_comm_class R S M] : smul_comm_class R S (α →₀ M) := { smul_comm := λ r s a, ext $ λ _, smul_comm _ _ _ } instance [semiring R] [add_comm_monoid M] [module R M] : module R (α →₀ M) := { smul := (•), zero_smul := λ x, ext $ λ _, zero_smul _ _, add_smul := λ a x y, ext $ λ _, add_smul _ _ _, .. finsupp.distrib_mul_action α M } variables {α M} {R} lemma support_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {g : α →₀ M} : (b • g).support ⊆ g.support := λ a, by { simp only [smul_apply, mem_support_iff, ne.def], exact mt (λ h, h.symm ▸ smul_zero _) } section variables {p : α → Prop} @[simp] lemma filter_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p := coe_fn_injective $ set.indicator_smul {x | p x} b v end lemma map_domain_smul {_ : monoid R} [add_comm_monoid M] [distrib_mul_action R M] {f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v := begin change map_domain f (map_range _ _ _) = map_range _ _ _, apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] }, intros a b v' hv₁ hv₂ IH, rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add, map_range_single, map_domain_single, map_domain_single, map_range_single]; apply smul_add end @[simp] lemma smul_single {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) := map_range_single @[simp] lemma smul_single' {_ : semiring R} (c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) := smul_single _ _ _ lemma map_range_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] [add_monoid N] [distrib_mul_action R N] {f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) : map_range f hf (c • v) = c • map_range f hf v := begin erw ←map_range_comp, have : (f ∘ (•) c) = ((•) c ∘ f) := funext hsmul, simp_rw this, apply map_range_comp, rw [function.comp_apply, smul_zero, hf], end lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b := by rw [smul_single, smul_eq_mul, mul_one] end lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 lemma sum_smul_index' [monoid R] [add_monoid M] [distrib_mul_action R M] [add_comm_monoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi c, h i (b • c)) := finsupp.sum_map_range_index h0 /-- A version of `finsupp.sum_smul_index'` for bundled additive maps. -/ lemma sum_smul_index_add_monoid_hom [monoid R] [add_monoid M] [add_comm_monoid N] [distrib_mul_action R M] {g : α →₀ M} {b : R} {h : α → M →+ N} : (b • g).sum (λ a, h a) = g.sum (λ i c, h i (b • c)) := sum_map_range_index (λ i, (h i).map_zero) instance [semiring R] [add_comm_monoid M] [module R M] {ι : Type*} [no_zero_smul_divisors R M] : no_zero_smul_divisors R (ι →₀ M) := ⟨λ c f h, or_iff_not_imp_left.mpr (λ hc, finsupp.ext (λ i, (smul_eq_zero.mp (finsupp.ext_iff.mp h i)).resolve_left hc))⟩ section distrib_mul_action_hom variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid N] [distrib_mul_action R M] [distrib_mul_action R N] /-- `finsupp.single` as a `distrib_mul_action_hom`. See also `finsupp.lsingle` for the version as a linear map. -/ def distrib_mul_action_hom.single (a : α) : M →+[R] (α →₀ M) := { map_smul' := λ k m, by simp only [add_monoid_hom.to_fun_eq_coe, single_add_hom_apply, smul_single], .. single_add_hom a } lemma distrib_mul_action_hom_ext {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) : f = g := distrib_mul_action_hom.to_add_monoid_hom_injective $ add_hom_ext h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma distrib_mul_action_hom_ext' {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α), f.comp (distrib_mul_action_hom.single a) = g.comp (distrib_mul_action_hom.single a)) : f = g := distrib_mul_action_hom_ext $ λ a, distrib_mul_action_hom.congr_fun (h a) end distrib_mul_action_hom section variables [has_zero R] /-- The `finsupp` version of `pi.unique`. -/ instance unique_of_right [subsingleton R] : unique (α →₀ R) := { uniq := λ l, ext $ λ i, subsingleton.elim _ _, .. finsupp.inhabited } /-- The `finsupp` version of `pi.unique_of_is_empty`. -/ instance unique_of_left [is_empty α] : unique (α →₀ R) := { uniq := λ l, ext is_empty_elim, .. finsupp.inhabited } end /-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrict_support_equiv (s : set α) (M : Type*) [add_comm_monoid M] : {f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) := begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end /-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between `α →₀ M` and `β →₀ M`. This is `finsupp.equiv_congr_left` as an `add_equiv`. -/ @[simps apply] protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) := { to_fun := equiv_map_domain e, inv_fun := equiv_map_domain e.symm, left_inv := λ v, begin simp only [← equiv_map_domain_trans, equiv.trans_symm], exact equiv_map_domain_refl _ end, right_inv := begin assume v, simp only [← equiv_map_domain_trans, equiv.symm_trans], exact equiv_map_domain_refl _ end, map_add' := λ a b, by simp only [equiv_map_domain_eq_map_domain]; exact map_domain_add } @[simp] lemma dom_congr_refl [add_comm_monoid M] : finsupp.dom_congr (equiv.refl α) = add_equiv.refl (α →₀ M) := add_equiv.ext $ λ _, equiv_map_domain_refl _ @[simp] lemma dom_congr_symm [add_comm_monoid M] (e : α ≃ β) : (finsupp.dom_congr e).symm = (finsupp.dom_congr e.symm : (β →₀ M) ≃+ (α →₀ M)):= add_equiv.ext $ λ _, rfl @[simp] lemma dom_congr_trans [add_comm_monoid M] (e : α ≃ β) (f : β ≃ γ) : (finsupp.dom_congr e).trans (finsupp.dom_congr f) = (finsupp.dom_congr (e.trans f) : (α →₀ M) ≃+ _) := add_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm end finsupp namespace finsupp /-! ### Declarations about sigma types -/ section sigma variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. This is the `finsupp` version of `sigma.curry`. -/ def split (i : ι) : αs i →₀ M := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right, mem_support_iff, sigma.exists, ne.def] end /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def split_comp [has_zero N] (g : Π i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw [mem_split_support_iff_nonzero, not_iff_not, hg], end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image, mem_preimage, sigma.forall, mem_sigma]; tauto lemma sigma_sum [add_comm_monoid N] (f : (Σ (i : ι), αs i) → M → N) : l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) := by simp only [sum, sigma_support, sum_sigma, split_apply] variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α] /-- On a `fintype η`, `finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `finsupp` version of `equiv.Pi_curry`. -/ noncomputable def sigma_finsupp_equiv_pi_finsupp : ((Σ j, ιs j) →₀ α) ≃ Π j, (ιs j →₀ α) := { to_fun := split, inv_fun := λ f, on_finset (finset.univ.sigma (λ j, (f j).support)) (λ ji, f ji.1 ji.2) (λ g hg, finset.mem_sigma.mpr ⟨finset.mem_univ _, mem_support_iff.mpr hg⟩), left_inv := λ f, by { ext, simp [split] }, right_inv := λ f, by { ext, simp [split] } } @[simp] lemma sigma_finsupp_equiv_pi_finsupp_apply (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl /-- On a `fintype η`, `finsupp.split` is an additive equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `add_equiv` version of `finsupp.sigma_finsupp_equiv_pi_finsupp`. -/ noncomputable def sigma_finsupp_add_equiv_pi_finsupp {α : Type*} {ιs : η → Type*} [add_monoid α] : ((Σ j, ιs j) →₀ α) ≃+ Π j, (ιs j →₀ α) := { map_add' := λ f g, by { ext, simp }, .. sigma_finsupp_equiv_pi_finsupp } @[simp] lemma sigma_finsupp_add_equiv_pi_finsupp_apply {α : Type*} {ιs : η → Type*} [add_monoid α] (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_add_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl end sigma end finsupp /-! ### Declarations relating `multiset` to `finsupp` -/ namespace multiset /-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by the multiplicities of the elements of `s`. -/ def to_finsupp : multiset α ≃+ (α →₀ ℕ) := finsupp.to_multiset.symm @[simp] lemma to_finsupp_support [D : decidable_eq α] (s : multiset α) : s.to_finsupp.support = s.to_finset := by rw subsingleton.elim D; refl @[simp] lemma to_finsupp_apply [D : decidable_eq α] (s : multiset α) (a : α) : to_finsupp s a = s.count a := by rw subsingleton.elim D; refl lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := add_equiv.map_zero _ lemma to_finsupp_add (s t : multiset α) : to_finsupp (s + t) = to_finsupp s + to_finsupp t := to_finsupp.map_add s t @[simp] lemma to_finsupp_singleton (a : α) : to_finsupp ({a} : multiset α) = finsupp.single a 1 := finsupp.to_multiset.symm_apply_eq.2 $ by simp @[simp] lemma to_finsupp_to_multiset (s : multiset α) : s.to_finsupp.to_multiset = s := finsupp.to_multiset.apply_symm_apply s lemma to_finsupp_eq_iff {s : multiset α} {f : α →₀ ℕ} : s.to_finsupp = f ↔ s = f.to_multiset := finsupp.to_multiset.symm_apply_eq end multiset @[simp] lemma finsupp.to_multiset_to_finsupp (f : α →₀ ℕ) : f.to_multiset.to_finsupp = f := finsupp.to_multiset.symm_apply_apply f /-! ### Declarations about order(ed) instances on `finsupp` -/ namespace finsupp instance [preorder M] [has_zero M] : preorder (α →₀ M) := { le := λ f g, ∀ s, f s ≤ g s, le_refl := λ f s, le_refl _, le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) } instance [partial_order M] [has_zero M] : partial_order (α →₀ M) := { le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s), .. finsupp.preorder } instance [ordered_cancel_add_comm_monoid M] : ordered_cancel_add_comm_monoid (α →₀ M) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s), add_left_cancel := λ a b c h, ext $ λ s, add_left_cancel (ext_iff.1 h s), .. finsupp.add_comm_monoid, .. finsupp.partial_order } lemma le_def [preorder M] [has_zero M] {f g : α →₀ M} : f ≤ g ↔ ∀ x, f x ≤ g x := iff.rfl lemma le_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) : f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ instance decidable_le [canonically_ordered_add_monoid M] [decidable_rel (@has_le.le M _)] : decidable_rel (@has_le.le (α →₀ M) _) := λ f g, decidable_of_iff _ (le_iff f g).symm @[simp] lemma add_eq_zero_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) : f + g = 0 ↔ f = 0 ∧ g = 0 := by simp [ext_iff, forall_and_distrib] /-- `finsupp.to_multiset` as an order isomorphism. -/ def order_iso_multiset : (α →₀ ℕ) ≃o multiset α := { to_equiv := to_multiset.to_equiv, map_rel_iff' := λ f g, by simp [multiset.le_iff_count, le_def] } @[simp] lemma coe_order_iso_multiset : ⇑(@order_iso_multiset α) = to_multiset := rfl @[simp] lemma coe_order_iso_multiset_symm : ⇑(@order_iso_multiset α).symm = multiset.to_finsupp := rfl lemma to_multiset_strict_mono : strict_mono (@to_multiset α) := order_iso_multiset.strict_mono lemma sum_id_lt_of_lt (m n : α →₀ ℕ) (h : m < n) : m.sum (λ _, id) < n.sum (λ _, id) := begin rw [← card_to_multiset, ← card_to_multiset], apply multiset.card_lt_of_lt, exact to_multiset_strict_mono h end variable (α) /-- The order on `σ →₀ ℕ` is well-founded.-/ lemma lt_wf : well_founded (@has_lt.lt (α →₀ ℕ) _) := subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf variable {α} @[simp] lemma nat_add_sub_cancel (f g : α →₀ ℕ) : f + g - g = f := ext $ λ a, nat.add_sub_cancel _ _ @[simp] lemma nat_add_sub_cancel_left (f g : α →₀ ℕ) : f + g - f = g := ext $ λ a, nat.add_sub_cancel_left _ _ lemma nat_add_sub_of_le {f g : α →₀ ℕ} (h : f ≤ g) : f + (g - f) = g := ext $ λ a, nat.add_sub_of_le (h a) lemma nat_sub_add_cancel {f g : α →₀ ℕ} (h : f ≤ g) : g - f + f = g := ext $ λ a, nat.sub_add_cancel (h a) instance : canonically_ordered_add_monoid (α →₀ ℕ) := { bot := 0, bot_le := λ f s, zero_le (f s), le_iff_exists_add := λ f g, ⟨λ H, ⟨g - f, (nat_add_sub_of_le H).symm⟩, λ ⟨c, hc⟩, hc.symm ▸ λ x, by simp⟩, .. (infer_instance : ordered_add_comm_monoid (α →₀ ℕ)) } end finsupp namespace multiset lemma to_finsuppstrict_mono : strict_mono (@to_finsupp α) := finsupp.order_iso_multiset.symm.strict_mono end multiset
86bd19e26fdd21f10a23e52da16666a088c4f3f6
4727251e0cd73359b15b664c3170e5d754078599
/src/order/filter/pointwise.lean
0d46fc013b8cc81726d968940aa95d7e12cb595d
[ "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
23,884
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yaël Dillies -/ import data.set.pointwise import order.filter.n_ary import order.filter.ultrafilter /-! # Pointwise operations on filters This file defines pointwise operations on filters. This is useful because usual algebraic operations distribute over pointwise operations. For example, * `(f₁ * f₂).map m = f₁.map m * f₂.map m` * `𝓝 (x * y) = 𝓝 x * 𝓝 y` ## Main declarations * `0` (`filter.has_zero`): Pure filter at `0 : α`, or alternatively principal filter at `0 : set α`. * `1` (`filter.has_one`): Pure filter at `1 : α`, or alternatively principal filter at `1 : set α`. * `f + g` (`filter.has_add`): Addition, filter generated by all `s + t` where `s ∈ f` and `t ∈ g`. * `f * g` (`filter.has_mul`): Multiplication, filter generated by all `s * t` where `s ∈ f` and `t ∈ g`. * `-f` (`filter.has_neg`): Negation, filter of all `-s` where `s ∈ f`. * `f⁻¹` (`filter.has_inv`): Inversion, filter of all `x⁻¹` where `s ∈ f`. * `f - g` (`filter.has_sub`): Subtraction, filter generated by all `x - y` where `s ∈ f` and `t ∈ g`. * `f / g` (`filter.has_div`): Division, filter generated by all `x / y` where `s ∈ f` and `t ∈ g`. * `f +ᵥ g` (`filter.has_vadd`): Scalar addition, filter generated by all `x +ᵥ y` where `s ∈ f` and `t ∈ g`. * `f -ᵥ g` (`filter.has_vsub`): Scalar subtraction, filter generated by all `x -ᵥ y` where `s ∈ f` and `t ∈ g`. * `f • g` (`filter.has_scalar`): Scalar multiplication, filter generated by all `x • y` where `s ∈ f` and `t ∈ g`. * `a +ᵥ f` (`filter.has_vadd_filter`): Translation, filter of all `a +ᵥ x` where `s ∈ f`. * `a • f` (`filter.has_scalar_filter`): Scaling, filter of all `a • s` where `s ∈ f`. ## Implementation notes We put all instances in the locale `pointwise`, so that these instances are not available by default. Note that we do not mark them as reducible (as argued by note [reducible non-instances]) since we expect the locale to be open whenever the instances are actually used (and making the instances reducible changes the behavior of `simp`. ## Tags filter multiplication, filter addition, pointwise addition, pointwise multiplication, -/ open function set open_locale filter pointwise variables {F α β γ δ ε : Type*} namespace filter /-! ### `0`/`1` as filters -/ section has_one variables [has_one α] {f : filter α} {s : set α} /-- `1 : filter α` is defined as the filter of sets containing `1 : α` in locale `pointwise`. -/ @[to_additive "`0 : filter α` is defined as the filter of sets containing `0 : α` in locale `pointwise`."] protected def has_one : has_one (filter α) := ⟨pure 1⟩ localized "attribute [instance] filter.has_one filter.has_zero" in pointwise @[simp, to_additive] lemma mem_one : s ∈ (1 : filter α) ↔ (1 : α) ∈ s := mem_pure @[to_additive] lemma one_mem_one : (1 : set α) ∈ (1 : filter α) := mem_pure.2 one_mem_one @[simp, to_additive] lemma pure_one : pure 1 = (1 : filter α) := rfl @[simp, to_additive] lemma principal_one : 𝓟 1 = (1 : filter α) := principal_singleton _ @[to_additive] lemma one_ne_bot : (1 : filter α).ne_bot := filter.pure_ne_bot @[simp, to_additive] protected lemma map_one' (f : α → β) : (1 : filter α).map f = pure (f 1) := rfl @[simp, to_additive] lemma le_one_iff : f ≤ 1 ↔ (1 : set α) ∈ f := le_pure_iff @[simp, to_additive] lemma eventually_one {p : α → Prop} : (∀ᶠ x in 1, p x) ↔ p 1 := eventually_pure @[simp, to_additive] lemma tendsto_one {a : filter β} {f : β → α} : tendsto f a 1 ↔ ∀ᶠ x in a, f x = 1 := tendsto_pure variables [has_one β] @[simp, to_additive] protected lemma map_one [one_hom_class F α β] (φ : F) : map φ 1 = 1 := by rw [filter.map_one', map_one, pure_one] end has_one /-! ### Filter negation/inversion -/ section has_inv variables [has_inv α] {f g : filter α} {s : set α} {a : α} /-- The inverse of a filter is the pointwise preimage under `⁻¹` of its sets. -/ @[to_additive "The negation of a filter is the pointwise preimage under `-` of its sets."] instance : has_inv (filter α) := ⟨map has_inv.inv⟩ @[simp, to_additive] protected lemma map_inv : f.map has_inv.inv = f⁻¹ := rfl @[to_additive] lemma mem_inv : s ∈ f⁻¹ ↔ has_inv.inv ⁻¹' s ∈ f := iff.rfl @[to_additive] protected lemma inv_le_inv (hf : f ≤ g) : f⁻¹ ≤ g⁻¹ := map_mono hf @[simp, to_additive] lemma inv_pure : (pure a : filter α)⁻¹ = pure a⁻¹ := rfl @[simp, to_additive] lemma inv_eq_bot_iff : f⁻¹ = ⊥ ↔ f = ⊥ := map_eq_bot_iff @[simp, to_additive] lemma ne_bot_inv_iff : f⁻¹.ne_bot ↔ ne_bot f := map_ne_bot_iff _ @[to_additive] lemma ne_bot.inv : f.ne_bot → f⁻¹.ne_bot := λ h, h.map _ end has_inv section has_involutive_inv variables [has_involutive_inv α] {f : filter α} {s : set α} @[to_additive] lemma inv_mem_inv (hs : s ∈ f) : s⁻¹ ∈ f⁻¹ := by rwa [mem_inv, inv_preimage, inv_inv] /-- Inversion is involutive on `filter α` if it is on `α`. -/ @[to_additive "Negation is involutive on `filter α` if it is on `α`."] def has_involutive_inv : has_involutive_inv (filter α) := { inv_inv := λ f, map_map.trans $ by rw [inv_involutive.comp_self, map_id], ..filter.has_inv } end has_involutive_inv /-! ### Filter addition/multiplication -/ section has_mul variables [has_mul α] [has_mul β] {f f₁ f₂ g g₁ g₂ h : filter α} {s t : set α} {a b : α} /-- The filter `f * g` is generated by `{s * t | s ∈ f, t ∈ g}` in locale `pointwise`. -/ @[to_additive "The filter `f + g` is generated by `{s + t | s ∈ f, t ∈ g}` in locale `pointwise`."] protected def has_mul : has_mul (filter α) := /- This is defeq to `map₂ (*) f g`, but the hypothesis unfolds to `t₁ * t₂ ⊆ s` rather than all the way to `set.image2 (*) t₁ t₂ ⊆ s`. -/ ⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s}, ..map₂ (*) f g }⟩ localized "attribute [instance] filter.has_mul filter.has_add" in pointwise @[simp, to_additive] lemma map₂_mul : map₂ (*) f g = f * g := rfl @[to_additive] lemma mem_mul_iff : s ∈ f * g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s := iff.rfl @[to_additive] lemma mul_mem_mul : s ∈ f → t ∈ g → s * t ∈ f * g := image2_mem_map₂ @[simp, to_additive] lemma bot_mul : ⊥ * g = ⊥ := map₂_bot_left @[simp, to_additive] lemma mul_bot : f * ⊥ = ⊥ := map₂_bot_right @[simp, to_additive] lemma mul_eq_bot_iff : f * g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff @[simp, to_additive] lemma mul_ne_bot_iff : (f * g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff @[to_additive] lemma ne_bot.mul : ne_bot f → ne_bot g → ne_bot (f * g) := ne_bot.map₂ @[to_additive] lemma ne_bot.of_mul_left : (f * g).ne_bot → f.ne_bot := ne_bot.of_map₂_left @[to_additive] lemma ne_bot.of_mul_right : (f * g).ne_bot → g.ne_bot := ne_bot.of_map₂_right @[simp, to_additive] lemma pure_mul : pure a * g = g.map ((*) a) := map₂_pure_left @[simp, to_additive] lemma mul_pure : f * pure b = f.map (* b) := map₂_pure_right @[simp, to_additive] lemma pure_mul_pure : (pure a : filter α) * pure b = pure (a * b) := map₂_pure @[simp, to_additive] lemma le_mul_iff : h ≤ f * g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s * t ∈ h := le_map₂_iff @[to_additive] instance covariant_mul : covariant_class (filter α) (filter α) (*) (≤) := ⟨λ f g h, map₂_mono_left⟩ @[to_additive] instance covariant_swap_mul : covariant_class (filter α) (filter α) (swap (*)) (≤) := ⟨λ f g h, map₂_mono_right⟩ @[to_additive] protected lemma map_mul [mul_hom_class F α β] (m : F) : (f₁ * f₂).map m = f₁.map m * f₂.map m := map_map₂_distrib $ map_mul m end has_mul /-! ### Filter subtraction/division -/ section div variables [has_div α] {f f₁ f₂ g g₁ g₂ h : filter α} {s t : set α} {a b : α} /-- The filter `f / g` is generated by `{s / t | s ∈ f, t ∈ g}` in locale `pointwise`. -/ @[to_additive "The filter `f - g` is generated by `{s - t | s ∈ f, t ∈ g}` in locale `pointwise`."] protected def has_div : has_div (filter α) := /- This is defeq to `map₂ (/) f g`, but the hypothesis unfolds to `t₁ / t₂ ⊆ s` rather than all the way to `set.image2 (/) t₁ t₂ ⊆ s`. -/ ⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ / t₂ ⊆ s}, ..map₂ (/) f g }⟩ localized "attribute [instance] filter.has_div filter.has_sub" in pointwise @[simp, to_additive] lemma map₂_div : map₂ (/) f g = f / g := rfl @[to_additive] lemma mem_div : s ∈ f / g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ / t₂ ⊆ s := iff.rfl @[to_additive] lemma div_mem_div : s ∈ f → t ∈ g → s / t ∈ f / g := image2_mem_map₂ @[simp, to_additive] lemma bot_div : ⊥ / g = ⊥ := map₂_bot_left @[simp, to_additive] lemma div_bot : f / ⊥ = ⊥ := map₂_bot_right @[simp, to_additive] lemma div_eq_bot_iff : f / g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff @[simp, to_additive] lemma div_ne_bot_iff : (f / g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff @[to_additive] lemma ne_bot.div : ne_bot f → ne_bot g → ne_bot (f / g) := ne_bot.map₂ @[to_additive] lemma ne_bot.of_div_left : (f / g).ne_bot → f.ne_bot := ne_bot.of_map₂_left @[to_additive] lemma ne_bot.of_div_right : (f / g).ne_bot → g.ne_bot := ne_bot.of_map₂_right @[simp, to_additive] lemma pure_div : pure a / g = g.map ((/) a) := map₂_pure_left @[simp, to_additive] lemma div_pure : f / pure b = f.map (/ b) := map₂_pure_right @[simp, to_additive] lemma pure_div_pure : (pure a : filter α) / pure b = pure (a / b) := map₂_pure @[to_additive] protected lemma div_le_div : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ / g₁ ≤ f₂ / g₂ := map₂_mono @[to_additive] protected lemma div_le_div_left : g₁ ≤ g₂ → f / g₁ ≤ f / g₂ := map₂_mono_left @[to_additive] protected lemma div_le_div_right : f₁ ≤ f₂ → f₁ / g ≤ f₂ / g := map₂_mono_right @[simp, to_additive] protected lemma le_div_iff : h ≤ f / g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s / t ∈ h := le_map₂_iff @[to_additive] instance covariant_div : covariant_class (filter α) (filter α) (/) (≤) := ⟨λ f g h, map₂_mono_left⟩ @[to_additive] instance covariant_swap_div : covariant_class (filter α) (filter α) (swap (/)) (≤) := ⟨λ f g h, map₂_mono_right⟩ end div open_locale pointwise /-- `filter α` is a `semigroup` under pointwise operations if `α` is.-/ @[to_additive "`filter α` is an `add_semigroup` under pointwise operations if `α` is."] protected def semigroup [semigroup α] : semigroup (filter α) := { mul := (*), mul_assoc := λ f g h, map₂_assoc mul_assoc } /-- `filter α` is a `comm_semigroup` under pointwise operations if `α` is. -/ @[to_additive "`filter α` is an `add_comm_semigroup` under pointwise operations if `α` is."] protected def comm_semigroup [comm_semigroup α] : comm_semigroup (filter α) := { mul_comm := λ f g, map₂_comm mul_comm, ..filter.semigroup } section mul_one_class variables [mul_one_class α] [mul_one_class β] /-- `filter α` is a `mul_one_class` under pointwise operations if `α` is. -/ @[to_additive "`filter α` is an `add_zero_class` under pointwise operations if `α` is."] protected def mul_one_class : mul_one_class (filter α) := { one := 1, mul := (*), one_mul := λ f, by simp only [←pure_one, ←map₂_mul, map₂_pure_left, one_mul, map_id'], mul_one := λ f, by simp only [←pure_one, ←map₂_mul, map₂_pure_right, mul_one, map_id'] } localized "attribute [instance] filter.semigroup filter.add_semigroup filter.comm_semigroup filter.add_comm_semigroup filter.mul_one_class filter.add_zero_class" in pointwise /-- If `φ : α →* β` then `map_monoid_hom φ` is the monoid homomorphism `filter α →* filter β` induced by `map φ`. -/ @[to_additive "If `φ : α →+ β` then `map_add_monoid_hom φ` is the monoid homomorphism `filter α →+ filter β` induced by `map φ`."] def map_monoid_hom [monoid_hom_class F α β] (φ : F) : filter α →* filter β := { to_fun := map φ, map_one' := filter.map_one φ, map_mul' := λ _ _, filter.map_mul φ } -- The other direction does not hold in general @[to_additive] lemma comap_mul_comap_le [mul_hom_class F α β] (m : F) {f g : filter β} : f.comap m * g.comap m ≤ (f * g).comap m := λ s ⟨t, ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, mt⟩, ⟨m ⁻¹' t₁, m ⁻¹' t₂, ⟨t₁, ht₁, subset.rfl⟩, ⟨t₂, ht₂, subset.rfl⟩, (preimage_mul_preimage_subset _).trans $ (preimage_mono t₁t₂).trans mt⟩ @[to_additive] lemma tendsto.mul_mul [mul_hom_class F α β] (m : F) {f₁ g₁ : filter α} {f₂ g₂ : filter β} : tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ * g₁) (f₂ * g₂) := λ hf hg, (filter.map_mul m).trans_le $ mul_le_mul' hf hg end mul_one_class section monoid variables [monoid α] {f g : filter α} {s : set α} {a : α} /-- `filter α` is a `monoid` under pointwise operations if `α` is. -/ @[to_additive "`filter α` is an `add_monoid` under pointwise operations if `α` is."] protected def monoid : monoid (filter α) := { ..filter.mul_one_class, ..filter.semigroup } localized "attribute [instance] filter.monoid filter.add_monoid" in pointwise @[to_additive] lemma pow_mem_pow (hs : s ∈ f) : ∀ n : ℕ, s ^ n ∈ f ^ n | 0 := by { rw pow_zero, exact one_mem_one } | (n + 1) := by { rw pow_succ, exact mul_mem_mul hs (pow_mem_pow _) } end monoid /-- `filter α` is a `comm_monoid` under pointwise operations if `α` is. -/ @[to_additive "`filter α` is an `add_comm_monoid` under pointwise operations if `α` is."] protected def comm_monoid [comm_monoid α] : comm_monoid (filter α) := { ..filter.mul_one_class, ..filter.comm_semigroup } localized "attribute [instance] filter.comm_monoid filter.add_comm_monoid" in pointwise -- TODO: Generalize the duplicated lemmas and instances below to `division_monoid` /-- `f / g = f * g⁻¹` for all `f g : filter α` if `a / b = a * b⁻¹` for all `a b : α`. -/ @[to_additive filter.sub_neg_monoid "`f - g = f + -g` for all `f g : filter α` if `a - b = a + -b` for all `a b : α`."] protected def div_inv_monoid [group α] : div_inv_monoid (filter α) := { div_eq_mul_inv := λ f g, map_map₂_distrib_right div_eq_mul_inv, ..filter.monoid, ..filter.has_inv, ..filter.has_div } /-- `f / g = f * g⁻¹` for all `f g : filter α` if `a / b = a * b⁻¹` for all `a b : α`. -/ protected def div_inv_monoid' [group_with_zero α] : div_inv_monoid (filter α) := { div_eq_mul_inv := λ f g, map_map₂_distrib_right div_eq_mul_inv, ..filter.monoid, ..filter.has_inv, ..filter.has_div } localized "attribute [instance] filter.div_inv_monoid filter.sub_neg_monoid filter.div_inv_monoid'" in pointwise /-! Note that `filter α` is not a group because `f / f ≠ 1` in general -/ section group variables [group α] [group β] [monoid_hom_class F α β] (m : F) {f g f₁ g₁ : filter α} {f₂ g₂ : filter β} include β @[to_additive] lemma map_inv' : f⁻¹.map m = (f.map m)⁻¹ := map_comm (funext $ map_inv m) _ @[to_additive] lemma tendsto.inv_inv : tendsto m f₁ f₂ → tendsto m f₁⁻¹ f₂⁻¹ := λ hf, (filter.map_inv' m).trans_le $ filter.inv_le_inv hf @[to_additive] protected lemma map_div : (f / g).map m = f.map m / g.map m := map_map₂_distrib $ map_div m @[to_additive] lemma tendsto.div_div : tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ / g₁) (f₂ / g₂) := λ hf hg, (filter.map_div m).trans_le $ filter.div_le_div hf hg end group /-! ### Scalar addition/multiplication of filters -/ section smul variables [has_scalar α β] {f f₁ f₂ : filter α} {g g₁ g₂ h : filter β} {s : set α} {t : set β} {a : α} {b : β} @[to_additive filter.has_vadd] instance : has_scalar (filter α) (filter β) := /- This is defeq to `map₂ (•) f g`, but the hypothesis unfolds to `t₁ • t₂ ⊆ s` rather than all the way to `set.image2 (•) t₁ t₂ ⊆ s`. -/ ⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ • t₂ ⊆ s}, ..map₂ (•) f g }⟩ @[simp, to_additive] lemma map₂_smul : map₂ (•) f g = f • g := rfl @[to_additive] lemma mem_smul : t ∈ f • g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ • t₂ ⊆ t := iff.rfl @[to_additive] lemma smul_mem_smul : s ∈ f → t ∈ g → s • t ∈ f • g := image2_mem_map₂ @[simp, to_additive] lemma bot_smul : (⊥ : filter α) • g = ⊥ := map₂_bot_left @[simp, to_additive] lemma smul_bot : f • (⊥ : filter β) = ⊥ := map₂_bot_right @[simp, to_additive] lemma smul_eq_bot_iff : f • g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff @[simp, to_additive] lemma smul_ne_bot_iff : (f • g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff @[to_additive] lemma ne_bot.smul : ne_bot f → ne_bot g → ne_bot (f • g) := ne_bot.map₂ @[to_additive] lemma ne_bot.of_smul_left : (f • g).ne_bot → f.ne_bot := ne_bot.of_map₂_left @[to_additive] lemma ne_bot.of_smul_right : (f • g).ne_bot → g.ne_bot := ne_bot.of_map₂_right @[simp, to_additive] lemma pure_smul : (pure a : filter α) • g = g.map ((•) a) := map₂_pure_left @[simp, to_additive] lemma smul_pure : f • pure b = f.map (• b) := map₂_pure_right @[simp, to_additive] lemma pure_smul_pure : (pure a : filter α) • (pure b : filter β) = pure (a • b) := map₂_pure @[to_additive] lemma smul_le_smul : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ • g₁ ≤ f₂ • g₂ := map₂_mono @[to_additive] lemma smul_le_smul_left : g₁ ≤ g₂ → f • g₁ ≤ f • g₂ := map₂_mono_left @[to_additive] lemma smul_le_smul_right : f₁ ≤ f₂ → f₁ • g ≤ f₂ • g := map₂_mono_right @[simp, to_additive] lemma le_smul_iff : h ≤ f • g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s • t ∈ h := le_map₂_iff @[to_additive] instance covariant_smul : covariant_class (filter α) (filter β) (•) (≤) := ⟨λ f g h, map₂_mono_left⟩ end smul /-! ### Scalar subtraction of filters -/ section vsub variables [has_vsub α β] {f f₁ f₂ g g₁ g₂ : filter β} {h : filter α} {s t : set β} {a b : β} include α /-- The filter `f -ᵥ g` is generated by `{s -ᵥ t | s ∈ f, t ∈ g}` in locale `pointwise`. -/ protected def has_vsub : has_vsub (filter α) (filter β) := /- This is defeq to `map₂ (-ᵥ) f g`, but the hypothesis unfolds to `t₁ -ᵥ t₂ ⊆ s` rather than all the way to `set.image2 (-ᵥ) t₁ t₂ ⊆ s`. -/ ⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ -ᵥ t₂ ⊆ s}, ..map₂ (-ᵥ) f g }⟩ localized "attribute [instance] filter.has_vsub" in pointwise @[simp] lemma map₂_vsub : map₂ (-ᵥ) f g = f -ᵥ g := rfl lemma mem_vsub {s : set α} : s ∈ f -ᵥ g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ -ᵥ t₂ ⊆ s := iff.rfl lemma vsub_mem_vsub : s ∈ f → t ∈ g → s -ᵥ t ∈ f -ᵥ g := image2_mem_map₂ @[simp] lemma bot_vsub : (⊥ : filter β) -ᵥ g = ⊥ := map₂_bot_left @[simp] lemma vsub_bot : f -ᵥ (⊥ : filter β) = ⊥ := map₂_bot_right @[simp] lemma vsub_eq_bot_iff : f -ᵥ g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff @[simp] lemma vsub_ne_bot_iff : (f -ᵥ g : filter α).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff lemma ne_bot.vsub : ne_bot f → ne_bot g → ne_bot (f -ᵥ g) := ne_bot.map₂ lemma ne_bot.of_vsub_left : (f -ᵥ g : filter α).ne_bot → f.ne_bot := ne_bot.of_map₂_left lemma ne_bot.of_vsub_right : (f -ᵥ g : filter α).ne_bot → g.ne_bot := ne_bot.of_map₂_right @[simp] lemma pure_vsub : (pure a : filter β) -ᵥ g = g.map ((-ᵥ) a) := map₂_pure_left @[simp] lemma vsub_pure : f -ᵥ pure b = f.map (-ᵥ b) := map₂_pure_right @[simp] lemma pure_vsub_pure : (pure a : filter β) -ᵥ pure b = (pure (a -ᵥ b) : filter α) := map₂_pure lemma vsub_le_vsub : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ -ᵥ g₁ ≤ f₂ -ᵥ g₂ := map₂_mono lemma vsub_le_vsub_left : g₁ ≤ g₂ → f -ᵥ g₁ ≤ f -ᵥ g₂ := map₂_mono_left lemma vsub_le_vsub_right : f₁ ≤ f₂ → f₁ -ᵥ g ≤ f₂ -ᵥ g := map₂_mono_right @[simp] lemma le_vsub_iff : h ≤ f -ᵥ g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s -ᵥ t ∈ h := le_map₂_iff end vsub /-! ### Translation/scaling of filters -/ section smul variables [has_scalar α β] {f f₁ f₂ : filter β} {s : set β} {a : α} /-- `a • f` is the map of `f` under `a •` in locale `pointwise`. -/ @[to_additive filter.has_vadd_filter "`a +ᵥ f` is the map of `f` under `a +ᵥ` in locale `pointwise`."] protected def has_scalar_filter : has_scalar α (filter β) := ⟨λ a, map ((•) a)⟩ localized "attribute [instance] filter.has_scalar_filter filter.has_vadd_filter" in pointwise @[simp, to_additive] lemma map_smul : map (λ b, a • b) f = a • f := rfl @[to_additive] lemma mem_smul_filter : s ∈ a • f ↔ (•) a ⁻¹' s ∈ f := iff.rfl @[to_additive] lemma smul_set_mem_smul_filter : s ∈ f → a • s ∈ a • f := image_mem_map @[simp, to_additive] lemma smul_filter_bot : a • (⊥ : filter β) = ⊥ := map_bot @[simp, to_additive] lemma smul_filter_eq_bot_iff : a • f = ⊥ ↔ f = ⊥ := map_eq_bot_iff @[simp, to_additive] lemma smul_filter_ne_bot_iff : (a • f).ne_bot ↔ f.ne_bot := map_ne_bot_iff _ @[to_additive] lemma ne_bot.smul_filter : f.ne_bot → (a • f).ne_bot := λ h, h.map _ @[to_additive] lemma smul_filter_le_smul_filter (hf : f₁ ≤ f₂) : a • f₁ ≤ a • f₂ := map_mono hf @[to_additive] instance covariant_smul_filter : covariant_class α (filter β) (•) (≤) := ⟨λ f, map_mono⟩ end smul open_locale pointwise @[to_additive] instance smul_comm_class_filter [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] : smul_comm_class α (filter β) (filter γ) := ⟨λ a f g, map_map₂_distrib_right $ smul_comm a⟩ @[to_additive] instance smul_comm_class_filter' [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] : smul_comm_class (filter α) β (filter γ) := by haveI := smul_comm_class.symm α β γ; exact smul_comm_class.symm _ _ _ @[to_additive] instance smul_comm_class [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] : smul_comm_class (filter α) (filter β) (filter γ) := ⟨λ f g h, map₂_left_comm smul_comm⟩ instance is_scalar_tower [has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] : is_scalar_tower α β (filter γ) := ⟨λ a b f, by simp only [←map_smul, map_map, smul_assoc]⟩ instance is_scalar_tower' [has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] : is_scalar_tower α (filter β) (filter γ) := ⟨λ a f g, by { refine (map_map₂_distrib_left $ λ _ _, _).symm, exact (smul_assoc a _ _).symm }⟩ instance is_scalar_tower'' [has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] : is_scalar_tower (filter α) (filter β) (filter γ) := ⟨λ f g h, map₂_assoc smul_assoc⟩ instance is_central_scalar [has_scalar α β] [has_scalar αᵐᵒᵖ β] [is_central_scalar α β] : is_central_scalar α (filter β) := ⟨λ a f, congr_arg (λ m, map m f) $ by exact funext (λ _, op_smul_eq_smul _ _)⟩ @[to_additive] instance [monoid α] [mul_action α β] : mul_action (filter α) (filter β) := { one_smul := λ f, by simp only [←pure_one, ←map₂_smul, map₂_pure_left, one_smul, map_id'], mul_smul := λ f g h, map₂_assoc mul_smul } end filter
cb0818911bbba8f1ce059377663e5951192e6974
b1e80085f6d9158c0b431ffc4fa9d0d53cbac8e4
/src/misc.lean
48afd702e0601519ecb94ce8001dd688915cebfc
[]
no_license
dwarn/nielsen-schreier-2
d73c20e4d2a8ae537fe4f8063272d0b72c58276a
e51a8c6511d374dc584698c7fa236a5be47e7dbe
refs/heads/master
1,679,911,740,113
1,615,656,058,000
1,615,656,058,000
344,111,212
1
0
null
null
null
null
UTF-8
Lean
false
false
2,302
lean
import category_theory.single_obj category_theory.action open_locale classical open category_theory function quotient_group instance {C} [category C] (F : C ⥤ Type*) : faithful (category_of_elements.π F) := by tidy def homset_equiv_of_mul_equiv {G H K} [group G] [group H] [group K] (h : G ≃* H) : (G →* K) ≃ (H →* K) := { to_fun := λ g, g.comp h.symm.to_monoid_hom, inv_fun := λ g, g.comp h.to_monoid_hom, left_inv := by tidy, right_inv := by tidy } lemma stabilizer_of_coset_action {G} [group G] {H : subgroup G} : mul_action.stabilizer G (default _ : quotient H) = H := by { ext, change _ = _ ↔ _, rw eq_comm, convert quotient_group.eq, simp } instance action_category_inhabited {M X} [monoid M] [mul_action M X] [inhabited X] : inhabited (action_category M X) := ⟨⟨single_obj.star M, (default _ : X)⟩⟩ def End_mul_equiv_subgroup {G} [group G] (H : subgroup G) : End (default (action_category G (quotient H))) ≃* H := begin refine mul_equiv.trans _ _, { exact mul_action.stabilizer G (default _ : quotient H) }, { apply_instance }, { refl }, -- this is a heavy refl { rw stabilizer_of_coset_action }, end noncomputable def compl_sum_set_equiv {A} (s : set A) : (set.compl s) ⊕ s ≃ A := { to_fun := λ x, sum.rec_on x coe coe, inv_fun := λ a, if h : a ∈ s then sum.inr ⟨a, h⟩ else sum.inl ⟨a, h⟩, left_inv := begin intro x, rcases x with ⟨x, h⟩ | ⟨x, h⟩, { dsimp, rw dif_neg }, { dsimp, rw dif_pos } end, right_inv := begin intro y, by_cases y ∈ s, { dsimp, rw dif_pos, { refl }, exact h }, { dsimp, rw dif_neg, { refl }, exact h }, end } instance (G A X : Type*) [group G] [mul_action G A] : mul_action G (A → X) := { smul := λ g F a, F (g⁻¹ • a), -- the inverse is only here so we get a *left* action one_smul := by tidy, mul_smul := by simp [mul_smul] } def my_mul_aut (G A X : Type*) [group G] [mul_action G A] [group X] : G →* mul_aut (A → X) := { to_fun := λ g, { to_fun := λ F, g • F, inv_fun := λ F, g⁻¹ • F, left_inv := λ F, inv_smul_smul g F, right_inv := λ F, smul_inv_smul g F, map_mul' := by tidy }, map_one' := by tidy, map_mul' := by { intros, ext, simp [mul_smul] }}
b1c12d6538d5784e520306a15441c2e429ecd77d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Tactic/LinearArith/Solver.lean
6b02bc1db1330a01ba7067f98c9794db26cdaaee
[ "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
8,508
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.Rat namespace Lean.Meta.Linear structure Var where id : Nat deriving Inhabited, Ord, DecidableEq, Repr instance : LT Var where lt a b := a.id < b.id instance (a b : Var) : Decidable (a < b) := inferInstanceAs (Decidable (a.id < b.id)) structure Assignment where val : Array Rat := #[] deriving Inhabited abbrev Assignment.size (a : Assignment) : Nat := a.val.size abbrev Assignment.get? (a : Assignment) (x : Var) : Option Rat := if h : x.id < a.size then some (a.val.get ⟨x.id, h⟩) else none abbrev Assignment.push (a : Assignment) (v : Rat) : Assignment := { a with val := a.val.push v } abbrev Assignment.shrink (a : Assignment) (newSize : Nat) : Assignment := { a with val := a.val.shrink newSize } structure Poly where val : Array (Int × Var) deriving Inhabited, Repr, DecidableEq abbrev Poly.size (e : Poly) : Nat := e.val.size abbrev Poly.getMaxVarCoeff (e : Poly) : Int := e.val.back.1 abbrev Poly.getMaxVar (e : Poly) : Var := e.val.back.2 abbrev Poly.get (e : Poly) (i : Fin e.size) : Int × Var := e.val.get i def Poly.scale (d : Int) (e : Poly) : Poly := { e with val := e.val.map fun (c, x) => (c*d, x) } def Poly.add (e₁ e₂ : Poly) : Poly := let rec go (i₁ i₂ : Nat) (r : Array (Int × Var)) : Poly := if h₁ : i₁ < e₁.size then if h₂ : i₂ < e₂.size then let (c₁, x₁) := e₁.get ⟨i₁, h₁⟩ let (c₂, x₂) := e₂.get ⟨i₂, h₂⟩ if x₁ = x₂ then if c₁ + c₂ = 0 then go (i₁+1) (i₂+1) r else go (i₁+1) (i₂+1) (r.push (c₁+c₂, x₁)) else if x₁ < x₂ then go (i₁+1) i₂ (r.push (c₁, x₁)) else go i₁ (i₂+1) (r.push (c₂, x₂)) else go (i₁+1) i₂ (r.push (e₁.get ⟨i₁, h₁⟩)) else if h₂ : i₂ < e₂.size then go i₁ (i₂+1) (r.push (e₂.get ⟨i₂, h₂⟩)) else { val := r } go 0 0 #[] termination_by go i j _ => (e₁.size - i, e₂.size - j) def Poly.combine (d₁ : Int) (e₁ : Poly) (d₂ : Int) (e₂ : Poly) : Poly := let rec go (i₁ i₂ : Nat) (r : Array (Int × Var)) : Poly := if h₁ : i₁ < e₁.size then let (c₁, x₁) := e₁.get ⟨i₁, h₁⟩ if h₂ : i₂ < e₂.size then let (c₂, x₂) := e₂.get ⟨i₂, h₂⟩ if x₁ = x₂ then let c := c₁*d₁ + c₂*d₂ if c = 0 then go (i₁+1) (i₂+1) r else go (i₁+1) (i₂+1) (r.push (c, x₁)) else if x₁ < x₂ then go (i₁+1) i₂ (r.push (d₁*c₁, x₁)) else go i₁ (i₂+1) (r.push (d₂*c₂, x₂)) else go (i₁+1) i₂ (r.push (d₁*c₁, x₁)) else if h₂ : i₂ < e₂.size then let (c₂, x₂) := e₂.get ⟨i₂, h₂⟩ go i₁ (i₂+1) (r.push (d₂*c₂, x₂)) else { val := r } go 0 0 #[] termination_by go i j _ => (e₁.size - i, e₂.size - j) def Poly.eval? (e : Poly) (a : Assignment) : Option Rat := Id.run do let mut r := 0 for (c, x) in e.val do if let some v := a.get? x then r := r + c*v else return none return r structure AssumptionId where id : Nat := 0 deriving Inhabited, DecidableEq, Repr inductive Justification where | combine (c₁ : Int) (j₁ : Justification) (c₂ : Int) (j₂ : Justification) | assumption (id : AssumptionId) deriving Inhabited, DecidableEq, BEq, Repr inductive CnstrKind where | eq | div | lt | le deriving Inhabited, DecidableEq, BEq, Repr structure Cnstr where kind : CnstrKind lhs : Poly rhs : Int jst : Justification deriving Inhabited, DecidableEq, BEq, Repr abbrev Cnstr.isStrict (c : Cnstr) : Bool := c.kind matches CnstrKind.lt def Cnstr.getBound (c : Cnstr) (a : Assignment) : Rat := Id.run do let mut r : Rat := c.rhs -- The maximal variable is in the last position for (c, x) in c.lhs.val[:c.lhs.val.size-1] do if let some v := a.get? x then r := r - c*v else unreachable! let k := c.lhs.val.back.1 return r / k def Cnstr.isUnsat (c : Cnstr) (a : Assignment) : Bool := if let some v := c.lhs.eval? a then match c.kind with | CnstrKind.eq => !(v == c.rhs) | CnstrKind.lt => !(v < c.rhs) | CnstrKind.le => !(v <= c.rhs) | CnstrKind.div => unreachable! -- TODO else false def getBestBound? (cs : Array Cnstr) (a : Assignment) (isLower isInt : Bool) : Option (Rat × Cnstr) := let adjust (v : Rat) := if isInt then if isLower then (v.ceil : Rat) else v.floor else v if h : 0 < cs.size then let c0 := cs.get ⟨0, h⟩ let b := adjust <| c0.getBound a some <| cs[1:].foldl (init := (b, c0)) fun r c => let b' := adjust <| c.getBound a if isLower then if b' > r.1 then (b', c) else r else if b' < r.1 then (b', c) else r else none inductive Result where | unsat (j : Justification) | unsupported | timeout | sat (a : Assignment) structure Context where int : Array Bool structure State where lowers : Array (Array Cnstr) uppers : Array (Array Cnstr) int : Array Bool assignment : Assignment := {} -- partial assignment deriving Inhabited abbrev State.getNumVars (s : State) : Nat := s.lowers.size abbrev State.currVar (s : State) : Nat := s.assignment.size abbrev State.getBestLowerBound? (s : State) : Option (Rat × Cnstr) := getBestBound? s.lowers[s.currVar]! s.assignment true s.int[s.currVar]! abbrev State.getBestUpperBound? (s : State) : Option (Rat × Cnstr) := getBestBound? s.uppers[s.currVar]! s.assignment false s.int[s.currVar]! abbrev State.assignCurr (s : State) (v : Rat) : State := { s with assignment := s.assignment.push v } def pickAssignment? (lower : Rat) (lowerIsStrict : Bool) (upper : Rat) (upperIsStrict : Bool) : Option Rat := if lower == upper then if lowerIsStrict || upperIsStrict then none else some lower else if lower < upper then if lowerIsStrict then let c := if lower.isInt then lower + 1 else lower.ceil if c < upper then some c else some ((lower + upper) / 2) else some lower else none def resolve (s : State) (cl : Cnstr) (cu : Cnstr) : Sum Result State := let kl : Int := - cl.lhs.getMaxVarCoeff let ku : Int := cu.lhs.getMaxVarCoeff -- Both `kl` and `ku` must be positive let lhs := Poly.combine ku cl.lhs kl cu.lhs -- TODO: normalize coefficients let rhs := ku * cl.rhs + kl * cu.rhs let c := { lhs, rhs, kind := if cl.isStrict || cu.isStrict then CnstrKind.lt else CnstrKind.le jst := Justification.combine kl cl.jst ku cu.jst : Cnstr } if !c.isUnsat s.assignment then -- TODO: the naive resolution procedure above may fail for integer constraints Sum.inl Result.unsupported else if lhs.size == 0 then Sum.inl <| Result.unsat c.jst else let maxVarIdx := c.lhs.getMaxVar.id match s with -- Hack: we avoid { s with ... } to make sure we get a destructive update | { lowers, uppers, int, assignment, } => let assignment := assignment.shrink maxVarIdx if c.lhs.getMaxVarCoeff < 0 then let lowers := lowers.modify maxVarIdx (·.push c) Sum.inr { lowers, uppers, int, assignment } else let uppers := uppers.modify maxVarIdx (·.push c) Sum.inr { lowers, uppers, int, assignment } def solve (n : Nat) (s : State) : Result := match n with | 0 => Result.timeout | n+1 => let i := s.currVar if i = s.getNumVars then Result.sat s.assignment -- all variables have been assigned else match s.getBestLowerBound?, s.getBestUpperBound? with | none, none => solve n <| s.assignCurr 0 | some (l, cl), none => solve n <| s.assignCurr (if cl.isStrict then l.ceil + 1 else l.ceil) | none, some (u, cu) => solve n <| s.assignCurr (if cu.isStrict then u.floor - 1 else u.floor) | some (l, cl), some (u, cu) => match pickAssignment? l cl.isStrict u cu.isStrict with | some v => solve n <| s.assignCurr v | none => match resolve s cl cu with | Sum.inl r => r | Sum.inr s => solve n s end Lean.Meta.Linear
6d5e7554ab92553fcc0db1108f89b3ea823f4e64
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/preadditive/schur.lean
f159180f057273e3dbd4f0a54e0450f9488741d4
[ "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
6,916
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import category_theory.simple import category_theory.linear import category_theory.endomorphism import field_theory.algebraic_closure /-! # Schur's lemma We first prove the part of Schur's Lemma that holds in any preadditive category with kernels, that any nonzero morphism between simple objects is an isomorphism. Second, we prove Schur's lemma for `𝕜`-linear categories with finite dimensional hom spaces, over an algebraically closed field `𝕜`: the hom space `X ⟶ Y` between simple objects `X` and `Y` is at most one dimensional, and is 1-dimensional iff `X` and `Y` are isomorphic. ## Future work It might be nice to provide a `division_ring` instance on `End X` when `X` is simple. This is an easy consequence of the results here, but may take some care setting up usable instances. -/ namespace category_theory open category_theory.limits universes v u variables {C : Type u} [category.{v} C] variables [preadditive C] /-- The part of **Schur's lemma** that holds in any preadditive category with kernels: that a nonzero morphism between simple objects is an isomorphism. -/ lemma is_iso_of_hom_simple [has_kernels C] {X Y : C} [simple X] [simple Y] {f : X ⟶ Y} (w : f ≠ 0) : is_iso f := begin haveI : mono f := preadditive.mono_of_kernel_zero (kernel_zero_of_nonzero_from_simple w), exact is_iso_of_mono_of_nonzero w end /-- As a corollary of Schur's lemma for preadditive categories, any morphism between simple objects is (exclusively) either an isomorphism or zero. -/ lemma is_iso_iff_nonzero [has_kernels C] {X Y : C} [simple.{v} X] [simple.{v} Y] (f : X ⟶ Y) : is_iso.{v} f ↔ f ≠ 0 := ⟨λ I, begin introI h, apply id_nonzero X, simp only [←is_iso.hom_inv_id f, h, zero_comp], end, λ w, is_iso_of_hom_simple w⟩ open finite_dimensional variables (𝕜 : Type*) [field 𝕜] /-- Part of **Schur's lemma** for `𝕜`-linear categories: the hom space between two non-isomorphic simple objects is 0-dimensional. -/ lemma finrank_hom_simple_simple_eq_zero_of_not_iso [has_kernels C] [linear 𝕜 C] {X Y : C} [simple.{v} X] [simple.{v} Y] (h : (X ≅ Y) → false): finrank 𝕜 (X ⟶ Y) = 0 := begin haveI := subsingleton_of_forall_eq (0 : X ⟶ Y) (λ f, begin have p := not_congr (is_iso_iff_nonzero f), simp only [not_not, ne.def] at p, refine p.mp (λ _, by exactI h (as_iso f)), end), exact finrank_zero_of_subsingleton, end variables [is_alg_closed 𝕜] [linear 𝕜 C] -- In the proof below we have some difficulty using `I : finite_dimensional 𝕜 (X ⟶ X)` -- where we need a `finite_dimensional 𝕜 (End X)`. -- These are definitionally equal, but without eta reduction Lean can't see this. -- To get around this, we use `convert I`, -- then check the various instances agree field-by-field, -- using `ext` equipped with the following extra lemmas: local attribute [ext] add_comm_group module distrib_mul_action mul_action has_scalar /-- An auxiliary lemma for Schur's lemma. If `X ⟶ X` is finite dimensional, and every nonzero endomorphism is invertible, then `X ⟶ X` is 1-dimensional. -/ -- We prove this with the explicit `is_iso_iff_nonzero` assumption, -- rather than just `[simple X]`, as this form is useful for -- Müger's formulation of semisimplicity. lemma finrank_endomorphism_eq_one {X : C} (is_iso_iff_nonzero : ∀ f : X ⟶ X, is_iso f ↔ f ≠ 0) [I : finite_dimensional 𝕜 (X ⟶ X)] : finrank 𝕜 (X ⟶ X) = 1 := begin have id_nonzero := (is_iso_iff_nonzero (𝟙 X)).mp (by apply_instance), apply finrank_eq_one (𝟙 X), { exact id_nonzero, }, { intro f, haveI : nontrivial (End X) := nontrivial_of_ne _ _ id_nonzero, obtain ⟨c, nu⟩ := @exists_spectrum_of_is_alg_closed_of_finite_dimensional 𝕜 _ _ (End X) _ _ _ (by { convert I, ext; refl, ext; refl, }) (End.of f), use c, rw [is_unit_iff_is_iso, is_iso_iff_nonzero, ne.def, not_not, sub_eq_zero, algebra.algebra_map_eq_smul_one] at nu, exact nu.symm, }, end variables [has_kernels C] /-- **Schur's lemma** for endomorphisms in `𝕜`-linear categories. -/ lemma finrank_endomorphism_simple_eq_one (X : C) [simple.{v} X] [I : finite_dimensional 𝕜 (X ⟶ X)] : finrank 𝕜 (X ⟶ X) = 1 := finrank_endomorphism_eq_one 𝕜 is_iso_iff_nonzero lemma endomorphism_simple_eq_smul_id {X : C} [simple.{v} X] [I : finite_dimensional 𝕜 (X ⟶ X)] (f : X ⟶ X) : ∃ c : 𝕜, c • 𝟙 X = f := (finrank_eq_one_iff_of_nonzero' (𝟙 X) (id_nonzero X)).mp (finrank_endomorphism_simple_eq_one 𝕜 X) f /-- **Schur's lemma** for `𝕜`-linear categories: if hom spaces are finite dimensional, then the hom space between simples is at most 1-dimensional. See `finrank_hom_simple_simple_eq_one_iff` and `finrank_hom_simple_simple_eq_zero_iff` below for the refinements when we know whether or not the simples are isomorphic. -/ -- We don't really need `[∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)]` here, -- just at least one of `[finite_dimensional 𝕜 (X ⟶ X)]` or `[finite_dimensional 𝕜 (Y ⟶ Y)]`. lemma finrank_hom_simple_simple_le_one (X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] : finrank 𝕜 (X ⟶ Y) ≤ 1 := begin cases subsingleton_or_nontrivial (X ⟶ Y) with h, { resetI, convert zero_le_one, exact finrank_zero_of_subsingleton, }, { obtain ⟨f, nz⟩ := (nontrivial_iff_exists_ne 0).mp h, haveI fi := (is_iso_iff_nonzero f).mpr nz, apply finrank_le_one f, intro g, obtain ⟨c, w⟩ := endomorphism_simple_eq_smul_id 𝕜 (g ≫ inv f), exact ⟨c, by simpa using w =≫ f⟩, }, end lemma finrank_hom_simple_simple_eq_one_iff (X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] : finrank 𝕜 (X ⟶ Y) = 1 ↔ nonempty (X ≅ Y) := begin fsplit, { intro h, rw finrank_eq_one_iff' at h, obtain ⟨f, nz, -⟩ := h, rw ←is_iso_iff_nonzero at nz, exactI ⟨as_iso f⟩, }, { rintro ⟨f⟩, have le_one := finrank_hom_simple_simple_le_one 𝕜 X Y, have zero_lt : 0 < finrank 𝕜 (X ⟶ Y) := finrank_pos_iff_exists_ne_zero.mpr ⟨f.hom, (is_iso_iff_nonzero f.hom).mp infer_instance⟩, linarith, } end lemma finrank_hom_simple_simple_eq_zero_iff (X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] : finrank 𝕜 (X ⟶ Y) = 0 ↔ ¬ nonempty (X ≅ Y) := begin rw ←not_congr (finrank_hom_simple_simple_eq_one_iff 𝕜 X Y), refine ⟨λ h, by { rw h, simp, }, λ h, _⟩, have := finrank_hom_simple_simple_le_one 𝕜 X Y, interval_cases finrank 𝕜 (X ⟶ Y) with h', { exact h', }, { exact false.elim (h h'), }, end end category_theory
076e60596bff58766dc65f66f01e613d25998cc8
618003631150032a5676f229d13a079ac875ff77
/src/algebra/direct_limit.lean
4dfeeec8a88e19e46eb5875822dcf40873939dee
[ "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,234
lean
/- Copyright (c) 2019 Kenny Lau, Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes Direct limit of modules, abelian groups, rings, and fields. See Atiyah-Macdonald PP.32-33, Matsumura PP.269-270 Generalizes the notion of "union", or "gluing", of incomparable modules over the same ring, or incomparable abelian groups, or rings, or fields. It is constructed as a quotient of the free module (for the module case) or quotient of the free commutative ring (for the ring case) instead of a quotient of the disjoint union so as to make the operations (addition etc.) "computable". -/ import ring_theory.free_comm_ring universes u v w u₁ open submodule variables {R : Type u} [ring R] variables {ι : Type v} [nonempty ι] variables [decidable_eq ι] [directed_order ι] variables (G : ι → Type w) [Π i, decidable_eq (G i)] /-- A directed system is a functor from the category (directed poset) to another category. This is used for abelian groups and rings and fields because their maps are not bundled. See module.directed_system -/ class directed_system (f : Π i j, i ≤ j → G i → G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) namespace module variables [Π i, add_comm_group (G i)] [Π i, module R (G i)] /-- A directed system is a functor from the category (directed poset) to the category of R-modules. -/ class directed_system (f : Π i j, i ≤ j → G i →ₗ[R] G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) variables (f : Π i j, i ≤ j → G i →ₗ[R] G j) [directed_system G f] /-- The direct limit of a directed system is the modules glued together along the maps. -/ def direct_limit : Type (max v w) := (span R $ { a | ∃ (i j) (H : i ≤ j) x, direct_sum.lof R ι G i x - direct_sum.lof R ι G j (f i j H x) = a }).quotient namespace direct_limit instance : add_comm_group (direct_limit G f) := quotient.add_comm_group _ instance : semimodule R (direct_limit G f) := quotient.semimodule _ variables (R ι) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →ₗ[R] direct_limit G f := (mkq _).comp $ direct_sum.lof R ι G i variables {R ι G f} @[simp] lemma of_f {i j hij x} : (of R ι G f j (f i j hij x)) = of R ι G f i x := eq.symm $ (submodule.quotient.eq _).2 $ subset_span ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of (z : direct_limit G f) : ∃ i x, of R ι G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ z, direct_sum.induction_on z ⟨ind, 0, linear_map.map_zero _⟩ (λ i x, ⟨i, x, rfl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [linear_map.map_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] protected theorem induction_on {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of R ι G f i x)) : C z := let ⟨i, x, h⟩ := exists_of z in h ▸ ih i x variables {P : Type u₁} [add_comm_group P] [module R P] (g : Π i, G i →ₗ[R] P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg variables (R ι G f) /-- The universal property of the direct limit: maps from the components to another module that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →ₗ[R] P := liftq _ (direct_sum.to_module R ι P g) (span_le.2 $ λ a ⟨i, j, hij, x, hx⟩, by rw [← hx, mem_coe, linear_map.sub_mem_ker_iff, direct_sum.to_module_lof, direct_sum.to_module_lof, Hg]) variables {R ι G f} omit Hg lemma lift_of {i} (x) : lift R ι G f g Hg (of R ι G f i x) = g i x := direct_sum.to_module_lof R _ _ theorem lift_unique (F : direct_limit G f →ₗ[R] P) (x) : F x = lift R ι G f (λ i, F.comp $ of R ι G f i) (λ i j hij x, by rw [linear_map.comp_apply, of_f]; refl) x := direct_limit.induction_on x $ λ i x, by rw lift_of; refl section totalize open_locale classical variables (G f) noncomputable def totalize : Π i j, G i →ₗ[R] G j := λ i j, if h : i ≤ j then f i j h else 0 variables {G f} lemma totalize_apply (i j x) : totalize G f i j x = if h : i ≤ j then f i j h x else 0 := if h : i ≤ j then by dsimp only [totalize]; rw [dif_pos h, dif_pos h] else by dsimp only [totalize]; rw [dif_neg h, dif_neg h, linear_map.zero_apply] end totalize lemma to_module_totalize_of_le {x : direct_sum ι G} {i j : ι} (hij : i ≤ j) (hx : ∀ k ∈ x.support, k ≤ i) : direct_sum.to_module R ι (G j) (λ k, totalize G f k j) x = f i j hij (direct_sum.to_module R ι (G i) (λ k, totalize G f k i) x) := begin rw [← @dfinsupp.sum_single ι G _ _ _ x], unfold dfinsupp.sum, simp only [linear_map.map_sum], refine finset.sum_congr rfl (λ k hk, _), rw direct_sum.single_eq_lof R k (x k), simp [totalize_apply, hx k hk, le_trans (hx k hk) hij, directed_system.map_map f] end lemma of.zero_exact_aux {x : direct_sum ι G} (H : submodule.quotient.mk x = (0 : direct_limit G f)) : ∃ j, (∀ k ∈ x.support, k ≤ j) ∧ direct_sum.to_module R ι (G j) (λ i, totalize G f i j) x = (0 : G j) := nonempty.elim (by apply_instance) $ assume ind : ι, span_induction ((quotient.mk_eq_zero _).1 H) (λ x ⟨i, j, hij, y, hxy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, begin clear_, subst hxy, split, { intros i0 hi0, rw [dfinsupp.mem_support_iff, dfinsupp.sub_apply, ← direct_sum.single_eq_lof, ← direct_sum.single_eq_lof, dfinsupp.single_apply, dfinsupp.single_apply] at hi0, split_ifs at hi0 with hi hj hj, { rwa hi at hik }, { rwa hi at hik }, { rwa hj at hjk }, exfalso, apply hi0, rw sub_zero }, simp [linear_map.map_sub, totalize_apply, hik, hjk, directed_system.map_map f, direct_sum.apply_eq_component, direct_sum.component.of], end⟩) ⟨ind, λ _ h, (finset.not_mem_empty _ h).elim, linear_map.map_zero _⟩ (λ x y ⟨i, hi, hxi⟩ ⟨j, hj, hyj⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, λ l hl, (finset.mem_union.1 (dfinsupp.support_add hl)).elim (λ hl, le_trans (hi _ hl) hik) (λ hl, le_trans (hj _ hl) hjk), by simp [linear_map.map_add, hxi, hyj, to_module_totalize_of_le hik hi, to_module_totalize_of_le hjk hj]⟩) (λ a x ⟨i, hi, hxi⟩, ⟨i, λ k hk, hi k (dfinsupp.support_smul hk), by simp [linear_map.map_smul, hxi]⟩) /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact {i x} (H : of R ι G f i x = 0) : ∃ j hij, f i j hij x = (0 : G j) := let ⟨j, hj, hxj⟩ := of.zero_exact_aux H in if hx0 : x = 0 then ⟨i, le_refl _, by simp [hx0]⟩ else have hij : i ≤ j, from hj _ $ by simp [direct_sum.apply_eq_component, hx0], ⟨j, hij, by simpa [totalize_apply, hij] using hxj⟩ end direct_limit end module namespace add_comm_group variables [Π i, add_comm_group (G i)] /-- The direct limit of a directed system is the abelian groups glued together along the maps. -/ def direct_limit (f : Π i j, i ≤ j → G i → G j) [Π i j hij, is_add_group_hom (f i j hij)] [directed_system G f] : Type* := @module.direct_limit ℤ _ ι _ _ _ G _ _ _ (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) ⟨directed_system.map_self f, directed_system.map_map f⟩ namespace direct_limit variables (f : Π i j, i ≤ j → G i → G j) variables [Π i j hij, is_add_group_hom (f i j hij)] [directed_system G f] lemma directed_system : module.directed_system G (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) := ⟨directed_system.map_self f, directed_system.map_map f⟩ local attribute [instance] directed_system instance : add_comm_group (direct_limit G f) := module.direct_limit.add_comm_group G (λ i j hij, (add_monoid_hom.of $f i j hij).to_int_linear_map) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i → direct_limit G f := module.direct_limit.of ℤ ι G (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) i variables {G f} instance of.is_add_group_hom (i) : is_add_group_hom (of G f i) := linear_map.is_add_group_hom _ @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := module.direct_limit.of_f @[simp] lemma of_zero (i) : of G f i 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_add_hom.map_add _ _ _ @[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_add_group_hom.map_neg _ _ @[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_add_group_hom.map_sub _ _ _ @[elab_as_eliminator] protected theorem induction_on {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := module.direct_limit.induction_on z ih /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact (i x) (h : of G f i x = 0) : ∃ j hij, f i j hij x = 0 := module.direct_limit.of.zero_exact h variables (P : Type u₁) [add_comm_group P] variables (g : Π i, G i → P) [Π i, is_add_group_hom (g i)] variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) variables (G f) /-- The universal property of the direct limit: maps from the components to another abelian group that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f → P := module.direct_limit.lift ℤ ι G (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) (λ i, (add_monoid_hom.of $ g i).to_int_linear_map) Hg variables {G f} instance lift.is_add_group_hom : is_add_group_hom (lift G f P g Hg) := linear_map.is_add_group_hom _ @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := module.direct_limit.lift_of _ _ _ @[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y := is_add_hom.map_add _ _ _ @[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x := is_add_group_hom.map_neg _ _ @[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y := is_add_group_hom.map_sub _ _ _ lemma lift_unique (F : direct_limit G f → P) [is_add_group_hom F] (x) : F x = @lift _ _ _ _ G _ _ f _ _ P _ (λ i x, F $ of G f i x) (λ i, is_add_group_hom.comp _ _) (λ i j hij x, by dsimp; rw of_f) x := direct_limit.induction_on x $ λ i x, by rw lift_of end direct_limit end add_comm_group namespace ring variables [Π i, comm_ring (G i)] variables (f : Π i j, i ≤ j → G i → G j) variables [Π i j hij, is_ring_hom (f i j hij)] variables [directed_system G f] open free_comm_ring /-- The direct limit of a directed system is the rings glued together along the maps. -/ def direct_limit : Type (max v w) := (ideal.span { a | (∃ i j H x, of (⟨j, f i j H x⟩ : Σ i, G i) - of ⟨i, x⟩ = a) ∨ (∃ i, of (⟨i, 1⟩ : Σ i, G i) - 1 = a) ∨ (∃ i x y, of (⟨i, x + y⟩ : Σ i, G i) - (of ⟨i, x⟩ + of ⟨i, y⟩) = a) ∨ (∃ i x y, of (⟨i, x * y⟩ : Σ i, G i) - (of ⟨i, x⟩ * of ⟨i, y⟩) = a) }).quotient namespace direct_limit instance : comm_ring (direct_limit G f) := ideal.quotient.comm_ring _ instance : ring (direct_limit G f) := comm_ring.to_ring _ /-- The canonical map from a component to the direct limit. -/ def of (i) (x : G i) : direct_limit G f := ideal.quotient.mk _ $ of ⟨i, x⟩ variables {G f} instance of.is_ring_hom (i) : is_ring_hom (of G f i) := { map_one := ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inl ⟨i, rfl⟩, map_mul := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inr ⟨i, x, y, rfl⟩, map_add := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inl ⟨i, x, y, rfl⟩ } @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := ideal.quotient.eq.2 $ subset_span $ or.inl ⟨i, j, hij, x, rfl⟩ @[simp] lemma of_zero (i) : of G f i 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma of_one (i) : of G f i 1 = 1 := is_ring_hom.map_one _ @[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_ring_hom.map_add _ @[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_ring_hom.map_neg _ @[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_ring_hom.map_sub _ @[simp] lemma of_mul (i x y) : of G f i (x * y) = of G f i x * of G f i y := is_ring_hom.map_mul _ @[simp] lemma of_pow (i x) (n : ℕ) : of G f i (x ^ n) = of G f i x ^ n := is_semiring_hom.map_pow _ _ _ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of (z : direct_limit G f) : ∃ i x, of G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ x, free_abelian_group.induction_on x ⟨ind, 0, of_zero ind⟩ (λ s, multiset.induction_on s ⟨ind, 1, of_one ind⟩ (λ a s ih, let ⟨i, x⟩ := a, ⟨j, y, hs⟩ := ih, ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x * f j k hjk y, by rw [of_mul, of_f, of_f, hs]; refl⟩)) (λ s ⟨i, x, ih⟩, ⟨i, -x, by rw [of_neg, ih]; refl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [of_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] theorem induction_on {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := let ⟨i, x, hx⟩ := exists_of z in hx ▸ ih i x section of_zero_exact open_locale classical variables (G f) lemma of.zero_exact_aux2 {x : free_comm_ring Σ i, G i} {s t} (hxs : is_supported x s) {j k} (hj : ∀ z : Σ i, G i, z ∈ s → z.1 ≤ j) (hk : ∀ z : Σ i, G i, z ∈ t → z.1 ≤ k) (hjk : j ≤ k) (hst : s ⊆ t) : f j k hjk (lift (λ ix : s, f ix.1.1 j (hj ix ix.2) ix.1.2) (restriction s x)) = lift (λ ix : t, f ix.1.1 k (hk ix ix.2) ix.1.2) (restriction t x) := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw [restriction_one, lift_one, is_ring_hom.map_one (f j k hjk), restriction_one, lift_one] }, { rw [restriction_neg, restriction_one, lift_neg, lift_one, is_ring_hom.map_neg (f j k hjk), is_ring_hom.map_one (f j k hjk), restriction_neg, restriction_one, lift_neg, lift_one] }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [restriction_mul, lift_mul, is_ring_hom.map_mul (f j k hjk), ih, restriction_mul, lift_mul, restriction_of, dif_pos hps, lift_of, restriction_of, dif_pos (hst hps), lift_of], dsimp only, rw directed_system.map_map f, refl }, { rintros x y ihx ihy, rw [restriction_add, lift_add, is_ring_hom.map_add (f j k hjk), ihx, ihy, restriction_add, lift_add] } end variables {G f} lemma of.zero_exact_aux {x : free_comm_ring Σ i, G i} (H : ideal.quotient.mk _ x = (0 : direct_limit G f)) : ∃ j s, ∃ H : (∀ k : Σ i, G i, k ∈ s → k.1 ≤ j), is_supported x s ∧ lift (λ ix : s, f ix.1.1 j (H ix ix.2) ix.1.2) (restriction s x) = (0 : G j) := begin refine span_induction (ideal.quotient.eq_zero_iff_mem.1 H) _ _ _ _, { rintros x (⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩), { refine ⟨j, {⟨i, x⟩, ⟨j, f i j hij x⟩}, _, is_supported_sub (is_supported_of.2 $ or.inr rfl) (is_supported_of.2 $ or.inl rfl), _⟩, { rintros k (rfl | ⟨rfl | _⟩), exact hij, refl }, { rw [restriction_sub, lift_sub, restriction_of, dif_pos, restriction_of, dif_pos, lift_of, lift_of], dsimp only, rw directed_system.map_map f, exact sub_self _, exacts [or.inr rfl, or.inl rfl] } }, { refine ⟨i, {⟨i, 1⟩}, _, is_supported_sub (is_supported_of.2 rfl) is_supported_one, _⟩, { rintros k (rfl|h), refl }, { rw [restriction_sub, lift_sub, restriction_of, dif_pos, restriction_one, lift_of, lift_one], dsimp only, rw [is_ring_hom.map_one (f i i _), sub_self], exacts [_inst_7 i i _, rfl] } }, { refine ⟨i, {⟨i, x+y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_add (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [restriction_sub, restriction_add, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, lift_sub, lift_add, lift_of, lift_of, lift_of], dsimp only, rw is_ring_hom.map_add (f i i _), exact sub_self _, exacts [or.inl rfl, by apply_instance, or.inr (or.inr rfl), or.inr (or.inl rfl)] } }, { refine ⟨i, {⟨i, x*y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_mul (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [restriction_sub, restriction_mul, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, lift_sub, lift_mul, lift_of, lift_of, lift_of], dsimp only, rw is_ring_hom.map_mul (f i i _), exacts [sub_self _, or.inl rfl, by apply_instance, or.inr (or.inr rfl), or.inr (or.inl rfl)] } } }, { refine nonempty.elim (by apply_instance) (assume ind : ι, _), refine ⟨ind, ∅, λ _, false.elim, is_supported_zero, _⟩, rw [restriction_zero, lift_zero] }, { rintros x y ⟨i, s, hi, hxs, ihs⟩ ⟨j, t, hj, hyt, iht⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exact le_trans (hi z hz) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, s ∪ t, this, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hyt $ set.subset_union_right s t), _⟩, { rw [restriction_add, lift_add, ← of.zero_exact_aux2 G f hxs hi this hik (set.subset_union_left s t), ← of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right s t), ihs, is_ring_hom.map_zero (f i k hik), iht, is_ring_hom.map_zero (f j k hjk), zero_add] } }, { rintros x y ⟨j, t, hj, hyt, iht⟩, rw smul_eq_mul, rcases exists_finset_support x with ⟨s, hxs⟩, rcases (s.image sigma.fst).exists_le with ⟨i, hi⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ ↑s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exact le_trans (hi z.1 $ finset.mem_image.2 ⟨z, hz, rfl⟩) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, ↑s ∪ t, this, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left ↑s t) (is_supported_upwards hyt $ set.subset_union_right ↑s t), _⟩, rw [restriction_mul, lift_mul, ← of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right ↑s t), iht, is_ring_hom.map_zero (f j k hjk), mul_zero] } end /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ lemma of.zero_exact {i x} (hix : of G f i x = 0) : ∃ j, ∃ hij : i ≤ j, f i j hij x = 0 := let ⟨j, s, H, hxs, hx⟩ := of.zero_exact_aux hix in have hixs : (⟨i, x⟩ : Σ i, G i) ∈ s, from is_supported_of.1 hxs, ⟨j, H ⟨i, x⟩ hixs, by rw [restriction_of, dif_pos hixs, lift_of] at hx; exact hx⟩ end of_zero_exact /-- If the maps in the directed system are injective, then the canonical maps from the components to the direct limits are injective. -/ theorem of_inj (hf : ∀ i j hij, function.injective (f i j hij)) (i) : function.injective (of G f i) := begin suffices : ∀ x, of G f i x = 0 → x = 0, { intros x y hxy, rw ← sub_eq_zero_iff_eq, apply this, rw [is_ring_hom.map_sub (of G f i), hxy, sub_self] }, intros x hx, rcases of.zero_exact hx with ⟨j, hij, hfx⟩, apply hf i j hij, rw [hfx, is_ring_hom.map_zero (f i j hij)] end variables (P : Type u₁) [comm_ring P] variables (g : Π i, G i → P) [Π i, is_ring_hom (g i)] variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg open free_comm_ring variables (G f) /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. We don't use this function as the canonical form because Lean 3 fails to automatically coerce it to a function; use `lift` instead. -/ def lift_hom : direct_limit G f →+* P := ideal.quotient.lift _ (free_comm_ring.lift_hom $ λ x, g x.1 x.2) begin suffices : ideal.span _ ≤ ideal.comap (free_comm_ring.lift_hom (λ (x : Σ (i : ι), G i), g (x.fst) (x.snd))) ⊥, { intros x hx, exact (mem_bot P).1 (this hx) }, rw ideal.span_le, intros x hx, rw [mem_coe, ideal.mem_comap, mem_bot], rcases hx with ⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩; simp only [coe_lift_hom, lift_sub, lift_of, Hg, lift_one, lift_add, lift_mul, is_ring_hom.map_one (g i), is_ring_hom.map_add (g i), is_ring_hom.map_mul (g i), sub_self] end /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f → P := lift_hom G f P g Hg instance lift_is_ring_hom : is_ring_hom (lift G f P g Hg) := (lift_hom G f P g Hg).is_ring_hom variables {G f} omit Hg @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := free_comm_ring.lift_of _ _ @[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := (lift_hom G f P g Hg).map_zero @[simp] lemma lift_one : lift G f P g Hg 1 = 1 := (lift_hom G f P g Hg).map_one @[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y := (lift_hom G f P g Hg).map_add x y @[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x := (lift_hom G f P g Hg).map_neg x @[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y := (lift_hom G f P g Hg).map_sub x y @[simp] lemma lift_mul (x y) : lift G f P g Hg (x * y) = lift G f P g Hg x * lift G f P g Hg y := (lift_hom G f P g Hg).map_mul x y @[simp] lemma lift_pow (x) (n : ℕ) : lift G f P g Hg (x ^ n) = lift G f P g Hg x ^ n := (lift_hom G f P g Hg).map_pow x n local attribute [instance, priority 100] is_ring_hom.comp theorem lift_unique (F : direct_limit G f → P) [is_ring_hom F] (x) : F x = lift G f P (λ i x, F $ of G f i x) (λ i j hij x, by rw [of_f]) x := direct_limit.induction_on x $ λ i x, by rw lift_of end direct_limit end ring namespace field variables [Π i, field (G i)] variables (f : Π i j, i ≤ j → G i → G j) [Π i j hij, is_ring_hom (f i j hij)] variables [directed_system G f] namespace direct_limit instance nonzero : nonzero (ring.direct_limit G f) := { zero_ne_one := nonempty.elim (by apply_instance) $ assume i : ι, begin change (0 : ring.direct_limit G f) ≠ 1, rw ← ring.direct_limit.of_one, intros H, rcases ring.direct_limit.of.zero_exact H.symm with ⟨j, hij, hf⟩, rw is_ring_hom.map_one (f i j hij) at hf, exact one_ne_zero hf end } theorem exists_inv {p : ring.direct_limit G f} : p ≠ 0 → ∃ y, p * y = 1 := ring.direct_limit.induction_on p $ λ i x H, ⟨ring.direct_limit.of G f i (x⁻¹), by erw [← ring.direct_limit.of_mul, mul_inv_cancel (assume h : x = 0, H $ by rw [h, ring.direct_limit.of_zero]), ring.direct_limit.of_one]⟩ section open_locale classical noncomputable def inv (p : ring.direct_limit G f) : ring.direct_limit G f := if H : p = 0 then 0 else classical.some (direct_limit.exists_inv G f H) protected theorem mul_inv_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : p * inv G f p = 1 := by rw [inv, dif_neg hp, classical.some_spec (direct_limit.exists_inv G f hp)] protected theorem inv_mul_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : inv G f p * p = 1 := by rw [_root_.mul_comm, direct_limit.mul_inv_cancel G f hp] protected noncomputable def field : field (ring.direct_limit G f) := { inv := inv G f, mul_inv_cancel := λ p, direct_limit.mul_inv_cancel G f, inv_zero := dif_pos rfl, .. ring.direct_limit.comm_ring G f, .. direct_limit.nonzero G f } end end direct_limit end field
87cd0b4222e897d0374eb41fe7f53cea728a8d4b
6305b69bc7636a761e1a1947508bb5ebad93cb7e
/leanpkg/leanpkg/resolve.lean
9da8a7d5495f076d1201e5e5135508a945e86451
[ "Apache-2.0" ]
permissive
HGldJ1966/lean
e7f0068f8a69fde3593b77d8a44609ae446d7738
049d940167c419cd5935d12b459c0695d8615ae9
refs/heads/master
1,611,340,395,700
1,503,103,829,000
1,503,103,829,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,941
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ import leanpkg.manifest system.io leanpkg.proc variable [io.interface] namespace leanpkg def assignment := list (string × string) namespace assignment def empty : assignment := [] def find : assignment → string → option string | [] s := none | ((k, v) :: kvs) s := if k = s then some v else find kvs s def contains (a : assignment) (s : string) : bool := (a.find s).is_some def insert (a : assignment) (k v : string) : assignment := if a.contains k then a else (k, v) :: a def fold {α} (i : α) (f : α → string → string → α) : assignment → α := list.foldl (λ a ⟨k, v⟩, f a k v) i end assignment @[reducible] def solver := state_t assignment io instance {α : Type} : has_coe (io α) (solver α) := ⟨state_t.lift⟩ def not_yet_assigned (d : string) : solver bool := do assg ← state_t.read, return $ ¬ assg.contains d def resolved_path (d : string) : solver string := do assg ← state_t.read, some path ← return (assg.find d) | io.fail "", return path -- TODO(gabriel): directory existence testing def dir_exists (d : string) : io bool := do ch ← io.proc.spawn { cmd := "test", args := ["-d", d] }, ev ← io.proc.wait ch, return $ ev = 0 -- TODO(gabriel): windows? def resolve_dir (abs_or_rel : string) (base : string) : string := if abs_or_rel.front = '/' then abs_or_rel -- absolute else base ++ "/" ++ abs_or_rel def materialize (relpath : string) (dep : dependency) : solver unit := match dep.src with | (source.path dir) := do let depdir := resolve_dir dir relpath, io.put_str_ln $ dep.name ++ ": using local path " ++ depdir, state_t.modify $ λ assg, assg.insert dep.name depdir | (source.git url rev) := do let depdir := "_target/deps/" ++ dep.name, already_there ← dir_exists depdir, let checkout_action := exec_cmd {cmd := "git", args := ["checkout", "--detach", rev], cwd := depdir}, (do guard already_there, io.put_str_ln $ dep.name ++ ": trying to update " ++ depdir ++ " to revision " ++ rev, checkout_action) <|> (do guard already_there, exec_cmd {cmd := "git", args := ["fetch"], cwd := depdir}, checkout_action) <|> (do io.put_str_ln $ dep.name ++ ": cloning " ++ url ++ " to " ++ depdir, exec_cmd {cmd := "rm", args := ["-rf", depdir]}, exec_cmd {cmd := "mkdir", args := ["-p", depdir]}, exec_cmd {cmd := "git", args := ["clone", url, depdir]}, exec_cmd {cmd := "git", args := ["checkout", "--detach", rev], cwd := depdir}), state_t.modify $ λ assg, assg.insert dep.name depdir end def solve_deps_core : ∀ (rel_path : string) (d : manifest) (max_depth : ℕ), solver unit | _ _ 0 := io.fail "maximum dependency resolution depth reached" | relpath d (max_depth + 1) := do deps ← monad.filter (not_yet_assigned ∘ dependency.name) d.dependencies, deps.mmap' (materialize relpath), deps.mmap' $ λ dep, do p ← resolved_path dep.name, d ← manifest.from_file $ p ++ "/" ++ "leanpkg.toml", when (d.name ≠ dep.name) $ io.fail $ d.name ++ " (in " ++ relpath ++ ") depends on " ++ d.name ++ ", but resolved dependency has name " ++ dep.name ++ " (in " ++ p ++ ")", solve_deps_core p d max_depth def solve_deps (d : manifest) : io assignment := do (_, assg) ← solve_deps_core "." d 1024 $ assignment.empty.insert d.name ".", return assg def construct_path_core (depname : string) (dirname : string) : io (list string) := list.map (λ relpath, dirname ++ "/" ++ relpath) <$> manifest.effective_path <$> (manifest.from_file $ dirname ++ "/" ++ leanpkg_toml_fn) def construct_path (assg : assignment) : io (list string) := do let assg := assg.fold [] (λ xs depname dirname, (depname, dirname) :: xs), list.join <$> (assg.mmap $ λ ⟨depname, dirname⟩, construct_path_core depname dirname) end leanpkg
bf708c25d304b11546a4c70faeb43557edd61ade
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Elab/Open.lean
196dc4c78621d2aa40a109c136d059a71f7e6802
[ "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
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
3,577
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.Log import Lean.Elab.Util namespace Lean.Elab namespace OpenDecl variable [Monad m] [STWorld IO.RealWorld m] [MonadEnv m] variable [MonadExceptOf Exception m] [MonadRef m] [AddErrorMessageContext m] variable [AddMessageContext m] [MonadLiftT (ST IO.RealWorld) m] [MonadLog m] /-- A local copy of name resolution state that allows us to immediately use new open decls in further name resolution as in `open Lean Elab`. -/ structure State where openDecls : List OpenDecl currNamespace : Name abbrev M := StateRefT State m instance : MonadResolveName (M (m := m)) where getCurrNamespace := return (← get).currNamespace getOpenDecls := return (← get).openDecls def resolveId (ns : Name) (idStx : Syntax) : M (m := m) Name := do let declName := ns ++ idStx.getId if (← getEnv).contains declName then return declName else withRef idStx <| resolveGlobalConstNoOverloadCore declName private def addOpenDecl (decl : OpenDecl) : M (m:=m) Unit := modify fun s => { s with openDecls := decl :: s.openDecls } private def resolveNameUsingNamespacesCore (nss : List Name) (idStx : Syntax) : M (m:=m) Name := do let mut exs := #[] let mut result := #[] for ns in nss do try let declName ← resolveId ns idStx result := result.push declName catch ex => exs := exs.push ex if exs.size == nss.length then withRef idStx do if exs.size == 1 then throw exs[0]! else throwErrorWithNestedErrors "failed to open" exs if result.size == 1 then return result[0]! else withRef idStx do throwError "ambiguous identifier '{idStx.getId}', possible interpretations: {result.map mkConst}" def elabOpenDecl [MonadResolveName m] (stx : TSyntax ``Parser.Command.openDecl) : m (List OpenDecl) := do StateRefT'.run' (s := { openDecls := (← getOpenDecls), currNamespace := (← getCurrNamespace) }) do match stx with | `(Parser.Command.openDecl| $nss*) => for ns in nss do for ns in (← resolveNamespace ns) do addOpenDecl (OpenDecl.simple ns []) activateScoped ns | `(Parser.Command.openDecl| scoped $nss*) => for ns in nss do for ns in (← resolveNamespace ns) do activateScoped ns | `(Parser.Command.openDecl| $ns ($ids*)) => let nss ← resolveNamespace ns for idStx in ids do let declName ← resolveNameUsingNamespacesCore nss idStx addOpenDecl (OpenDecl.explicit idStx.getId declName) | `(Parser.Command.openDecl| $ns hiding $ids*) => let ns ← resolveUniqueNamespace ns for id in ids do let _ ← resolveId ns id let ids := ids.map (·.getId) |>.toList addOpenDecl (OpenDecl.simple ns ids) | `(Parser.Command.openDecl| $ns renaming $[$froms -> $tos],*) => let ns ← resolveUniqueNamespace ns for («from», to) in froms.zip tos do let declName ← resolveId ns «from» addOpenDecl (OpenDecl.explicit to.getId declName) | _ => throwUnsupportedSyntax return (← get).openDecls def resolveNameUsingNamespaces [MonadResolveName m] (nss : List Name) (idStx : Ident) : m Name := do StateRefT'.run' (s := { openDecls := (← getOpenDecls), currNamespace := (← getCurrNamespace) }) do resolveNameUsingNamespacesCore nss idStx end OpenDecl export OpenDecl (elabOpenDecl resolveNameUsingNamespaces) end Lean.Elab